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
43965087140
#Question 1 Concurrent import concurrent.futures import time start=time.perf_counter() #define functions def add(x, y): print("This worked") return x + y print("This worked") def subtract(x, y): return x-y def multiply(x, y): return x * y def divide(x, y): if y==0: rai...
mpadill6/UCSD-Intro-to-Programming
Week 4/Question 1/Hw4_Concurrent.py
Hw4_Concurrent.py
py
974
python
en
code
0
github-code
6
73826380346
# This Python file has the entire code without particular libraries. # Made by: Feltrim # Instagram: instagram.com/vfeltrim_ # Libraries from math import factorial, sqrt from time import sleep # Interface functions: def line(size=42): """_summary_ Args: size (int, optional): Defaults to 42. R...
Feltrim/Calculator
Codes/main_code.py
main_code.py
py
6,153
python
en
code
0
github-code
6
74773385148
import numpy as np import os import torch from typing import List, Tuple from tqdm import tqdm from datetime import datetime, timedelta import pickle import matplotlib.pyplot as plt # -------------------- Colorize ------------------------------------------ """A set of common utilities used within the environments. Th...
hannahbull/slrtp2022_t3
utils.py
utils.py
py
2,912
python
en
code
3
github-code
6
32766695147
from django.shortcuts import render, reverse, redirect from django.views.generic import View from django.views.generic.edit import CreateView import requests import re count = 6 # Create your views here. def home(request): template_name = 'home.html' return render(request, template_name=template_name...
SaahilS468/Serverless-API
image/views.py
views.py
py
1,598
python
en
code
0
github-code
6
28830646732
"""Constants for the WiHeat Climate integration.""" import logging API_URL = 'https://wi-heat.com/' ID = 'home-assistant' SESSION = 'A2B3C4D5E6' DOMAIN = "wiheat" CONF_CODE_FORMAT = "code_format" CONF_CODE = "code" CONF_TEMP = "temp" UPDATE_INTERVAL = "timesync" MIN_SCAN_INTERVAL = 60 API_ENDPOINT = { 'getUser...
kimjohnsson/wiheat
custom_components/wiheat/const.py
const.py
py
861
python
en
code
0
github-code
6
5555757977
import copy from typing import Dict, List, Tuple import torch from data.low_res import SingleDomain from data.geography import frequency_encoded_latitude import numpy as np from data.vars import FIELD_MASK, FORCING_MASK, get_var_mask_name import xarray as xr from utils.xarray_oper import tonumpydict def determine_nd...
CemGultekin1/cm2p6
data/low_res_dataset.py
low_res_dataset.py
py
12,208
python
en
code
0
github-code
6
9772532153
# -*- coding: utf-8 -*- """ Created on Fri Dec 11 15:49:56 2020 @author: lnajt """ #import pyximport; pyximport.install() import fib import primes def uncompiled_fib(n): """Print the Fibonacci series up to n.""" a, b = 0, 1 while b < n: print(b, end=' ') a, b = b, a + b print() ...
ElleNajt/TinyProjects
Learning_Cython/use.py
use.py
py
1,023
python
en
code
4
github-code
6
5824663901
""" Flask app for testing the SMART on FHIR OAuth stuff Build from this tutorial: http://docs.smarthealthit.org/tutorials/authorization/ And using requests-oauthlib: http://requests-oauthlib.readthedocs.io/en/latest/index.html """ from flask import Flask, redirect, request, session from requests_oauthlib import OAuth2S...
ahatherly/SMART-on-FHIR-testclient
app.py
app.py
py
6,659
python
en
code
0
github-code
6
1854100159
import sys import os import pandas as pd import seaborn as sns; sns.set(style="ticks", color_codes=True) class Data(object): def __init__(self, fn = "Advertising.csv"): # find path to data files, either called from top-level or within scripts if os.path.exists("../data/"+fn): data...
amloren1/pg
scripts/advertising.py
advertising.py
py
1,102
python
en
code
0
github-code
6
43600893416
# -*- coding: utf-8 -*- from django.contrib import admin from adminsortable2.admin import SortableAdminMixin, SortableInlineAdminMixin from modeltranslation.admin import ( TranslationAdmin, TranslationTabularInline, TranslationStackedInline, TabbedTranslationAdmin ) from .models import ( SiteSettings, Foo...
CrazyChief/acidbro
core/admin.py
admin.py
py
2,524
python
en
code
0
github-code
6
16146274526
from simp_py import tft lcd = tft.tft import machine rtc = machine.RTC() synced = False for i in range(3): try: rtc.ntp_sync('pool.ntp.org') synced = True break except: time.sleep(1) if not synced: lcd.text(0,50, 'time sync failured') else: while True: tuplex = rtc.now() YYYY,MM,DD,hh,mm...
kcfkwok2003/Simp_py
simp_py_examples/course/SM001_old/t209.py
t209.py
py
443
python
en
code
0
github-code
6
2704503307
# -*- coding: utf-8 -*- from django.test import Client, RequestFactory, TestCase from tasks import views from tasks.models import Task, TaskStatus from users.models import CustomUser class TaskTest(TestCase): """Test cases for tasks.""" def setUp(self): """Initial setup before tests.""" self...
altvec/python-project-lvl4
tasks/tests.py
tests.py
py
1,403
python
en
code
0
github-code
6
12981024226
#!/usr/bin/env python """ Pymodbus Synchronous Client Example to showcase Device Information -------------------------------------------------------------------------- This client demonstrates the use of Device Information to get information about servers connected to the client. This is part of the MODBUS specificati...
renatosperlongo/pymodbus
examples/contrib/deviceinfo_showcase_client.py
deviceinfo_showcase_client.py
py
5,108
python
en
code
1
github-code
6
17418292210
import math class Vector3 (object): __slots__ = ('x', 'y', 'z', '_x', '_y', '_z') __hash__ = None def __init__(self, x=0, y=0, z=0): self.x = self._x = x self.y = self._y = y self.z = self._z = z def __copy__(self): return self.__class__(self.x, self.y, self.z)...
dcwatson/pavara-pyglet
pavara/vecmath.py
vecmath.py
py
10,903
python
en
code
1
github-code
6
12579350671
import numpy as np import pandas as pd #FEATURES def make_feature_changing(df, feature_changing_list): for func, params in feature_changing_list: df = func(df=df, **params) return df #MULTIPLE PREDICTIONS def multiple_predictions_TST(models_TST, Xs_TST): predicts = [] for idx, model in enumer...
mechmabot/EVRAZ_AI
module.py
module.py
py
1,856
python
en
code
0
github-code
6
36646912477
import matplotlib matplotlib.use('Agg') # noqa from deepdecoder.data import generator_3d_tags_with_depth_map, DistributionHDF5Dataset import diktya.distributions from diktya.numpy import tile import matplotlib.pyplot as plt import os import argparse from keras.utils.generic_utils import Progbar from scipy.ndimage.int...
berleon/deepdecoder
deepdecoder/scripts/generate_3d_tags.py
generate_3d_tags.py
py
4,038
python
en
code
50
github-code
6
40986191942
import random , sys , traceback from time import sleep from selenium import webdriver import datetime c=1; browser = webdriver.Chrome('D:\\Python\\Bot Insta\\chromedriver') browser.get('https://google.com') while c== 1: c=0 try: browser.find_element_by_xpath('/html/body/ytd-app/div/div/ytd...
mirceah99/Python-Bot-Insta
Teste.py
Teste.py
py
779
python
en
code
0
github-code
6
3714759753
from unittest import TestCase from datetime import datetime from uuid import uuid4 from sh import git, rm, gitlint, touch, echo, ErrorReturnCode class BaseTestCase(TestCase): pass class IntegrationTests(BaseTestCase): """ Simple set of integration tests for gitlint """ tmp_git_repo = None @classmet...
Hawatel/gitlint
qa/integration_test.py
integration_test.py
py
2,991
python
en
code
null
github-code
6
11221441363
import os, bcrypt from datetime import datetime from flask import Flask, request, jsonify, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(__name__, static_folder='.') app.config['UPLOAD_FOLDER'] = 'uploads' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db' app.config['SQLALCHEMY_TRACK_MOD...
tran-simon/hackatown
app.py
app.py
py
3,082
python
en
code
0
github-code
6
75341615226
"""Train an EfficientNetB4 model to predict GBM vs PCNSL. This requires TensorFlow >= 2.3.0. """ import argparse import math from pathlib import Path import pickle from typing import Tuple, Union import h5py import numpy as np import tensorflow as tf PathType = Union[str, Path] def augment_base(x, y): x = tf....
kaczmarj/classification-of-gbm-vs-pcnsl-using-cnns
step1_train_model.py
step1_train_model.py
py
6,476
python
en
code
0
github-code
6
42123556181
# Partie1: Récupération des infos à partir d'un lien article # Choisissez n'importe quelle page Produit sur le site de Books to Scrape. Écrivez un script Python qui visite cette page et en extrait les informations suivantes : import sys import requests from bs4 import BeautifulSoup import csv import os import urllib.re...
glgstyle/MyBookScraper
scrap_article.py
scrap_article.py
py
3,256
python
en
code
0
github-code
6
11472792272
import re import time import datetime import json import copy import random import os from pathlib import Path from urllib.parse import quote from amiyabot import PluginInstance from core.util import read_yaml from core import log, Message, Chain from core.database.user import User, UserInfo from core.database.bot imp...
hsyhhssyy/amiyabot-arknights-hsyhhssyy-wifu
main.py
main.py
py
6,170
python
en
code
0
github-code
6
36229750080
from typing import List ''' 剑指 Offer II 119. 最长连续序列 == 128 一般想法是排序再遍历,时间复杂度为O(nlogn) 连续的数会有一个起始数字num,num - 1不在nums数组中 所以找到num - 1 不在nums中的那个数,查询其连续长度 ''' class Solution: def longestConsecutive(self, nums: List[int]) -> int: s = set(nums) maxlen = 0 for num in s: if num - 1 not ...
z-w-wang/Leetcode-Problemlist
FxxkOffer/Graph/Offer_2_119.py
Offer_2_119.py
py
641
python
en
code
3
github-code
6
2704750787
import os from pymander.contexts import PrebuiltCommandContext, MultiLineContext, StandardPrompt from pymander.shortcuts import run_with_context from pymander.decorators import bind_argparse, bind_regex class FileWriterContext(MultiLineContext): FinishedHandler = MultiLineContext.OverOn2EmptyLines def __ini...
altvod/pymander
examples/fswalk.py
fswalk.py
py
2,906
python
en
code
0
github-code
6
43040033841
# -*- coding: utf-8 -*- """ @author: lucianavarromartin PRODUCTOR CONSUMIDOR 3(limited) El almacén ahora tiene espacio infinito, y cada productor tiene k subalmacenes que pueden estar llenos simultaneamente. Añadimos el objeto Lock, en este código, para tener un acceso controlado a los subalmacenes. El...
lucnav01/ProductorConsumidor
ProductorConsumidor3NavarroMartinLucia.py
ProductorConsumidor3NavarroMartinLucia.py
py
3,451
python
es
code
0
github-code
6
8515938890
import numpy as np from matplotlib import cm import matplotlib.pyplot as plt from matplotlib import gridspec from scipy.optimize import curve_fit from scipy.interpolate import interp1d from pandas import unique import csv import h5py from astropy import constants as const from astropy import units as u I_units = u...
jonasrth/MSc-plots
SED_EMISSA_plots.py
SED_EMISSA_plots.py
py
6,655
python
en
code
0
github-code
6
71144565947
#!/usr/bin/env python3 from dotenv import load_dotenv from pet_posts import bot import logging import os def main(): load_dotenv() # take environment variables from .env. api_token = os.getenv("API_TOKEN") logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", ...
dawngerpony/pet-posts
app.py
app.py
py
483
python
en
code
0
github-code
6
32628012198
import pandas as pd import glob from datetime import datetime, timedelta # Leitura dos arquivos da pasta dataset def readCSV(): listCSV = [] namePath = 'dataset' # Select all csv in folder selected namesFiles = glob.glob(namePath + "/*.csv") # join all them for filename in namesFiles: ...
lfmaster780/dataCovid
utils.py
utils.py
py
3,138
python
en
code
0
github-code
6
20363546350
#%% from dataclasses import dataclass, field from functools import wraps from typing import List, Optional, Protocol, Union import time from .controller import Controller from . import commands from .acceptance_scheme import AcceptanceScheme, UnconditionalAcceptance from .scattering_simulation import ScatteringSimulat...
lestercbarnsley/SasRMC
sas_rmc/simulator.py
simulator.py
py
3,355
python
en
code
0
github-code
6
70941003388
''' Created on 8/03/2016 @author: EJArizaR ''' import unittest from apps.DaneUsers.tests.test_base import test_base from django.core.urlresolvers import reverse class IsUsernameRegisteredTest(test_base): def setUp(self): test_base.setUp(self) def test_returns_False_if_user_doe...
diegopuerto/kiosco_universitario
source/apps/DaneUsers/tests/test_is_username_registered.py
test_is_username_registered.py
py
852
python
en
code
0
github-code
6
15430780258
adjacency_matrix = {1: [2, 3], 2: [4, 5], 3: [5], 4: [6], 5: [6], 6: [7], 7: []} ## Non-recursive def dfs(graph, start): """ All possible connected vertices """ stack,path = [start],[] while stack: ele = stack.pop() if ele in path: continue else: path.append(...
dipalira/LeetCode
Arrays/dfs.py
dfs.py
py
709
python
en
code
0
github-code
6
26804339781
numeral_values = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} for case in range(int(input())): expression = input() numerals = expression.replace("+", " ").replace("=", " ").split() value = 0 for num in numerals: for idx in range(len(num)): if ( (idx + 3 < len...
Stevan-Zhuang/DMOJ
CCC/CCC '96 S4 - When in Rome.py
CCC '96 S4 - When in Rome.py
py
1,321
python
en
code
1
github-code
6
21884803180
def split_article_dict(di:dict) : """ Mandatory info : @author : str @year : int @title : str @journal : str @volume : str Optional Info : @doi : str @issn : str @issue : int @page : str @url : str """ art_mandatory_key = ["author", "year"...
linkv12/bib2md
reff_parser.py
reff_parser.py
py
3,976
python
en
code
0
github-code
6
37429761663
import os from bs4 import BeautifulSoup import requests import requests.exceptions import urllib.parse from collections import deque import re # Create the directory to store the scraped data if it does not already exist if not os.path.exists("scraped_data"): os.makedirs("scraped_data") user_url = str(input('[+] ...
opemi-aa/email_phone_scrape
email_phone_scrape.py
email_phone_scrape.py
py
2,267
python
en
code
0
github-code
6
34780751946
import datetime import csv import re from Classes import Contact contact_list = list() contact_list_csv = "contact_list.csv" # Создание нового контакта и запись его в csv файл def create_contact(): print("Для того чтобы пропустить пункт и оставить его пустым введите: _") new_contact = Contact("", "", "", ""...
NAS371/contactListTestWork
Program.py
Program.py
py
5,649
python
ru
code
0
github-code
6
19240299148
import numpy as np import torch import random import time smp = torch.nn.Softmax(dim=0) smt = torch.nn.Softmax(dim=1) def get_T_global_min(args, record, max_step = None, T0 = None, p0 = None, lr = 0.1, NumTest = None, all_point_cnt = 15000): if max_step is None: max_step = args.max_iter if NumTest...
UCSC-REAL/fair-eval
hoc.py
hoc.py
py
7,838
python
en
code
5
github-code
6
32995735130
#!/usr/bin/env python # coding: utf-8 # In[2]: ## We'll be doing this from scratch, so all imports will come from ## the Python standard library or 3rd-party tools import socket import struct import base64 import json import hashlib import time import enum import xml.etree.ElementTree as ET from enum import Enum i...
irods/iRODS-Protocol-Cookbook
iRODS Protocol Cookbook.py
iRODS Protocol Cookbook.py
py
35,966
python
en
code
1
github-code
6
26112361495
__authors__ = ["V. Valls"] __license__ = "MIT" __date__ = "14/02/2018" import enum import logging from silx.gui import qt from silx.gui.dialog.ImageFileDialog import ImageFileDialog from silx.gui.dialog.DataFileDialog import DataFileDialog import silx.io logging.basicConfig() class Mode(enum.Enum): DEFAULT_FIL...
silx-kit/silx
examples/fileDialog.py
fileDialog.py
py
7,386
python
en
code
106
github-code
6
859547914
from vistrails.core.modules.module_descriptor import ModuleDescriptor from vistrails.core.modules.vistrails_module import Module from vistrails.core.upgradeworkflow import UpgradeModuleRemap class Y(Module): _output_ports = [('result', 'basic:String')] def compute(self): self.set_output('result', 'Y'...
VisTrails/VisTrails
vistrails/tests/resources/looping_upgrades/pkg_y/init.py
init.py
py
727
python
en
code
100
github-code
6
72173805309
# coding: utf-8 ''' Ex Dict & Files: 1 Načti data ze souboru 'TopTen.txt': -- Artist -- | -- Single -- | -- Weeks -- Ezra George | Green Green Grass | 14 Styles Harry | As It Was | 37 Capaldi Lewis | Forget Me | 12 ^^-- EOF --^^ a vytvoř nový soubor 'TopTen_sorted.txt' s údaji setříděné podle počtu týdnů v TopTen od n...
Alesator/python_skoleni
src/ex02_01.py
ex02_01.py
py
1,095
python
cs
code
0
github-code
6
9988571316
import websockets, json, traceback, os, asyncio, inspect, logging import websockets.client import websockets.server from websockets.exceptions import ConnectionClosedOK, ConnectionClosedError from .client_management.client import Client from .session_management.client_state import Client_State from .inventory_manage...
colinhartigan/valorant-inventory-manager
server/src/server.py
server.py
py
5,848
python
en
code
150
github-code
6
14408997276
from announcement.models import AnnouncementModel from UslugiProfi.utils import create_file_absolute_url from rest_framework import serializers class GetAnnouncementsSeriaizer(serializers.ModelSerializer): image = serializers.SerializerMethodField() class Meta: model = AnnouncementModel field...
Johudo-old/UslugiProfi
announcement/serializers.py
serializers.py
py
1,075
python
en
code
0
github-code
6
29732186780
import numpy import random def eval_proportion_diff(model1_pos, model2_pos, model1_samples, model2_samples, num_trials=10000, verbose=False): '''compare proportion of positively predicted samples between two models''' model1_values = numpy.zeros((model1_samples)) model1_values[:model1_pos] = 1 model...
roemmele/narrative-prediction
analysis/stats.py
stats.py
py
3,425
python
en
code
24
github-code
6
27944232660
""" This modules defines the base class for all machine learning models to analyse reusability rate. Last updated: MB 29/08/2020 - created module. """ # import external libraries. import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np import scipy.stats as stats from sklearn.model...
reusability/research
model/base_model.py
base_model.py
py
5,759
python
en
code
1
github-code
6
38043415332
def revisescore(wrongscores): rightscores = [] # 建立一個空列表,用於儲存修正後的成績 for i in wrongscores: # 將十位數和個位數互換,然後添加到正確成績列表中 units = i // 10 tens = i % 10 revisescore = tens * 10 + units rightscores.append(revisescore) return rightscores # 輸入錯誤的成績列表 wrongscore...
7553yn/Cathybank
scores.py
scores.py
py
571
python
en
code
0
github-code
6
34632215573
import cv2 import numpy as np img = cv2.imread('img\\ttt.jpg') #定义结构元素 kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) #腐蚀图像 eroded = cv2.erode(img, kernel) cv2.imshow("fs_eroded", eroded) #膨胀图像 dilated = cv2.dilate(img, kernel) cv2.imshow("pz_dilated", dilated) #NumPy定义的结构元素 NpKernel = np.uint8(np.one...
liuyuhua-ha/opencvStudy
opencvStudy/structTest.py
structTest.py
py
527
python
en
code
0
github-code
6
71432257788
from jaqsmds.server.repliers.utils import QueryInterpreter as Qi class SymbolQI(Qi): def __init__(self, view, *args, **kwargs): super(SymbolQI, self).__init__(view, *args, primary="symbol", **kwargs) InstrumentInfo = Qi("jz.instrumentInfo", trans={"inst_type": int, "list_date": int, "status": int}, sor...
cheatm/jaqsmds
jaqsmds/server/repliers/jsets.py
jsets.py
py
6,039
python
en
code
4
github-code
6
19757717889
# unit.test_shop.test_shopRepo.py from unittest.mock import Mock import tinydb as tdb from fixtures.shop import ShopFixture, TEMP_SHOPS_TINYDB_TEST_PATH, \ PRODUCTS_URLS_9_VALID_TEST_PATH, PRODUCTS_URLS_TEST_DIR from shop.shop import Shop from shop.shopDao import TinyShopDao from shop.shopRepo import ShopRepo fro...
dbyte/WebtomatorPublicEdition
tests/unit/test_shop/test_shopRepo.py
test_shopRepo.py
py
14,072
python
en
code
0
github-code
6
17690019803
#!/usr/bin/env python3 """ Module for view definition """ from flask import Flask, render_template, request from flask_babel import Babel, _ from typing import Optional class Config(object): """ Config class """ # ... LANGUAGES = ['en', 'fr'] BABEL_DEFAULT_LOCALE = 'en' BABEL_DEFAULT_TIMEZONE = 'U...
dnjoe96/alx-backend
0x02-i18n/4-app.py
4-app.py
py
1,140
python
en
code
0
github-code
6
41243183736
from flask import Blueprint, request, jsonify, make_response from tabledef import Technician from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy import update from tabledef import Technician, Call import config # create a query that extracts the information of the table "tech...
fmauri90/call_center
dataservice/api_technician_company.py
api_technician_company.py
py
8,617
python
en
code
0
github-code
6
23796575414
from fish import Fish class FishTracker: def __init__(self, initial_fish): self.fishies = [ Fish(timer) for timer in initial_fish ] self.days_past = 0 def pass_day(self): self.spawn_fishies() for fish in self.fishies: fish.age() ...
maariaw/advent-of-code-2021
Day06/puzzle1/src/fish_tracker.py
fish_tracker.py
py
964
python
en
code
0
github-code
6
8631452934
import pytest import numpy as np from abito.lib.significance import * def test_t_test(): np.random.seed(0) treatment = np.random.normal(100, size=100) control = np.random.normal(100, size=100) r = t_test(treatment, control) assert r.p_value == pytest.approx(0.9, 0.1) r = t_test_1samp(treatmen...
avito-tech/abito
tests/test_significance.py
test_significance.py
py
376
python
en
code
14
github-code
6
11626980377
import pandas as pd import json from message_reader import start # setting up config file input_file = "input.csv" output_file = "out.csv" json_file = "var_old.json" # reading input file & sheet df = pd.read_csv(input_file, header=None) final_written = None def to_every_message(row): global final_written c...
EhtishamSabir/json_parser
main_csv.py
main_csv.py
py
1,053
python
en
code
0
github-code
6
30786451692
import unittest from unittest.mock import Mock from book.book_repository import BookRepository from book.book import Book from book.book_service import BookService class TestBookService(unittest.TestCase): def test_find_book_by_id(self): mock_repository = Mock(spec=BookRepository) mock_repository...
nadia3373/Tests
s4/book_tests/test.py
test.py
py
1,059
python
en
code
0
github-code
6
70713803388
import re import os import sys import time import json import torch import wandb import random import datasets import evaluate import numpy as np import transformers from accelerate import Accelerator from accelerate.utils import set_seed from torch.utils.data import DataLoader from transformers import AutoTokenizer, D...
JesseBrons/Webpageclassification
training/train_model_BERT.py
train_model_BERT.py
py
5,845
python
en
code
1
github-code
6
43269450493
from django.conf.urls import include, url from provisioner.views import ProvisionStatus, login urlpatterns = [ url(r'^$', ProvisionStatus, name='home'), url(r'login.*', login), url(r'^events/', include('events.urls')), url(r'^provisioner/', include('provisioner.urls')), ]
uw-it-aca/msca-provisioner
msca_provisioner/urls.py
urls.py
py
291
python
en
code
1
github-code
6
6969788756
import os import re from PIL import Image import numpy as np import torch import random from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils from torchvision.datasets.folder import default_loader class Celeb(Dataset): def __init__(self, data_file, dst_path='cropped_...
ada-shen/icCNN
celeb.py
celeb.py
py
3,923
python
en
code
18
github-code
6
8861910661
#!/usr/bin/env python # -*- coding: utf-8 -*- # Esteban Quintana # Javier Rodríguez # Tree #id3 # Information gain # Greater gain import re import fileinput import math import copy from node import Node from main import * def get_entropy(node, root, data_types): entropies = [] entropy = 0.0 denominator...
JRC2307/Desicion-Trees
id3.py
id3.py
py
3,181
python
en
code
0
github-code
6
11801518455
def magic_square(matrix): n = len(matrix) M = (n * (n * 2 + 1)) / 2 l = [] d1 = [] d2 = [] for i in range(0, len(matrix)): l.append([item[i] for item in matrix]) d1.append(matrix[i][i]) d2.append(matrix[i][n - 1 - i]) l = matrix + l + [d1] + [d2] l = list(map(lam...
TsvetaKandilarova/Programming101
week0/Problem33/solution.py
solution.py
py
373
python
ko
code
0
github-code
6
1406414263
#String Methods trek= "ncc 1701-d" a= "the prime directive" #using split method a= a.split() print(a) # using join method result will be the_prime_directive a = "_".join(a) print(a) # create a small string lilstring = "Alta3 Research offers classes on Python coding" newlist= lilstring.split(" ") print(newlist) # creat...
tapantriv/py06292020
lab15.py
lab15.py
py
449
python
en
code
0
github-code
6
39403565414
from functools import partial import mmcv import numpy as np import torch from six.moves import map, zip def tensor2imgs(tensor, mean=(0, 0, 0), std=(1, 1, 1), to_rgb=True): """Convert tensor to images Args: tensor (torch.Tensor): Tensor that contains multiple images mean (tuple[float], opti...
fundamentalvision/Parameterized-AP-Loss
mmdet/core/utils/misc.py
misc.py
py
5,069
python
en
code
48
github-code
6
40211307735
from __future__ import division import sys, os, math import vtk from pbrainlib.gtkutils import error_msg, simple_msg, make_option_menu,\ get_num_value, get_num_range, get_two_nums, str2int_or_err,\ OpenSaveSaveAsHBox, ButtonAltLabel import pickle from scipy import array, zeros, ones, sort, absolute, sqrt, ...
nipy/pbrain
eegview/mesh_manager.py
mesh_manager.py
py
2,967
python
en
code
94
github-code
6
1741698512
import pytest import numpy as np import piquasso as pq import strawberryfields as sf pytestmark = pytest.mark.benchmark( group="pure-fock", ) @pytest.fixture def theta(): return np.pi / 5 @pytest.fixture def d(): return 5 @pytest.mark.parametrize("cutoff", range(3, 14)) def piquasso_benchmark(benc...
Budapest-Quantum-Computing-Group/piquasso
benchmarks/purefock_beamsplitter_increasing_cutoff_benchmark.py
purefock_beamsplitter_increasing_cutoff_benchmark.py
py
1,353
python
en
code
19
github-code
6
32704679818
from django.urls import path from .views import * urlpatterns = [ path('', PostList.as_view(), name="post_list_url"), path("search/", Search.as_view(), name='search_form_url'), path("filter/<int:pk>", DateFilter.as_view(), name='date_filter_url'), path("<slug:category>/", PostList.as_view(), name='post...
djaffic/blog_project
news/urls.py
urls.py
py
429
python
en
code
0
github-code
6
10251553901
class Solution: # TC: O(m * n) # SC: O(m * n)?? # cp 103 Jun 9 class exercise def leastBricks(self, wall: List[List[int]]) -> int: lines = {} for row in wall: sum = 0 for brick in row[:-1]: sum += brick # total number of collision at each col ...
stevenwcliu/leetcode_footprints
554-brick-wall/554-brick-wall.py
554-brick-wall.py
py
536
python
en
code
0
github-code
6
41254672775
class Solution: def twoSum(self, nums, target): """ :param nums: : List[int] :param target: : int :return: -> List[int] """ map = dict() for i in range(len(nums)): temp = target - nums[i] if temp in map: return [map[tem...
baichuan1997/leetcode
9.两数之和/1.两数之和.py
1.两数之和.py
py
378
python
en
code
0
github-code
6
71791729148
import numpy.linalg as LA from sklearn.neighbors import KDTree from sampler import Sampler import networkx as nx from shapely.geometry import LineString def can_connect(p1, p2, polygons): line = LineString([p1, p2]) for p in polygons: if p.crosses(line) and p.height >= min(p1[2], p2[2]): ...
magnusja/udacity-flying-cars
FCND-Motion-Planning/prm.py
prm.py
py
1,063
python
en
code
0
github-code
6
29576976470
# -*- coding: utf-8 -*- """ scikit-learnを用いたサンプルデータ生成 http://overlap.hatenablog.jp/entry/2015/10/08/022246 Created on Wed Jul 11 15:25:41 2018 @author: Akitaka """ ### classification sample from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn...
nakanishi-akitaka/python2018_backup
0711/test4_make_sample.py
test4_make_sample.py
py
1,780
python
en
code
5
github-code
6
33562082348
import cv2 as cv import numpy as np from matplotlib import pyplot as plt def thresholdingvivas(inp): f, c = inp.shape for i in range(f): for j in range(c): if(inp[i][j]>=195): inp[i][j]=0 cv.imshow('vivas',inp) def thresholdingmuertas(inp): f, c = inp.sha...
renzovc987/CG
Thresholdingrenzo.py
Thresholdingrenzo.py
py
1,044
python
en
code
0
github-code
6
26628419049
import cv2 import numpy as np import urllib.request from threading import Thread import socket import time import requests import json class Streamer: ''' description:- Class responsible for connecting to the anrdroid app and managing the data communication. How it works: - every m...
MohamedEshmawy/DeepRoasters
streamer/streamer_v2.py
streamer_v2.py
py
7,791
python
en
code
1
github-code
6
72577662587
from dataclasses import dataclass, field from random import randint maps = [ "de_anubis", "de_inferno", "de_ancient", "de_mirage", "de_nuke", "de_overpass", "de_vertigo", ] @dataclass(frozen=True) class Defaultsettings: """Sets basic match information. You can override the number of m...
Rogris/get5matchgen
tools.py
tools.py
py
2,036
python
en
code
1
github-code
6
73839717628
from asyncio import sleep, run import os import random from dotenv import load_dotenv import discord from discord.ext import commands, tasks import data from table2ascii import table2ascii as t2a, PresetStyle import asyncpg from datetime import datetime, timedelta load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') in...
NexhmedinQ/Discord-Finance-Bot
bot.py
bot.py
py
6,920
python
en
code
0
github-code
6
30367946761
import numpy as np from chaco.api import ArrayPlotData, Plot from enable.api import ComponentEditor from traits.api import Array, HasStrictTraits, Instance, Range, on_trait_change from traitsui.api import Item, VGroup, View class PowerFunctionExample(HasStrictTraits): """ Display a plot of a power function. """ ...
enthought/chaco
examples/user_guide/power_function_example.py
power_function_example.py
py
2,379
python
en
code
286
github-code
6
5708829851
import rename_tool import torch import torchaudio from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts import os current_dir = os.getcwd() config_path = os.path.join(current_dir, "source", "model_v2", "config.json") checkpoint_dir = os.path.join(current_dir, "source", "model_V2") co...
douhaohaode/xtts_v2
tts_v2.py
tts_v2.py
py
1,627
python
en
code
16
github-code
6
7212182080
import torch from torch import nn from tqdm.auto import tqdm from torchvision import transforms from torchvision.utils import make_grid from torch.utils.data import DataLoader import matplotlib.pyplot as plt # import glob import random import os from torch.utils.data import Dataset from PIL import Image #filesize impor...
Zefyrus94/GAN_test
cyclegan.py
cyclegan.py
py
25,719
python
en
code
1
github-code
6
32483752873
import torch import torch.nn as nn from mmdet.models import ResNet, FPN, MobileNetV2 import torch.nn.functional as F from common import default_conv, ResBlock, BasicBlock class MCNN(nn.Module): ''' Implementation of Multi-column CNN for crowd counting ''' def __init__(self, load_weights=False): ...
johnran103/mmdet
scale_map_net/s_net.py
s_net.py
py
9,667
python
en
code
1
github-code
6
36459683211
def sockMerchant(n, ar): # Write your code here ar=sorted(ar) set_elm =set(ar) aa =list(set_elm) c=[] for i in range(len(aa)): c.append(ar.count(aa[i])) cres=[i//2 for i in c] return sum(cres)
Nowshin021/HackerRank-Interview
Sales_by_Match.py
Sales_by_Match.py
py
253
python
en
code
0
github-code
6
22451204128
""" @author: Krystof Bogar dvéře """ def condition(a, b): """ podminka sousedu """ return a[-1] == b[0] def solve_key(words): """ resi ulohu s predzarovnym polem """ if len(words) == 2: return condition(words[0], words[1]) elif len(words)>1: for word in words[1:]: ...
kbogi/pjp
cv06/doors.py
doors.py
py
2,242
python
en
code
0
github-code
6
16119619384
N = int(input()) volume = list(map(int, input().split())) volume.sort(reverse=True) result = volume[0] for i in range(1, N): result += volume[i] / 2 print("%g" %result) # 의미없는 소수점 제거를 위해
sujeong11/Algorithm
그리디/20115.py
20115.py
py
217
python
ko
code
0
github-code
6
20426895808
import matplotlib.pyplot as plt import seaborn as sns color_list = sns.color_palette('deep') + sns.color_palette('bright') def DrawDoubleYLines(x, y1, y2, xlabel='', ylabel=['', ''], legend=['', ''], store_path=''): ''' Draw the doulbe y-axis lines. :param x: The vector of the x axis. :param y1: The ve...
salan668/FAE
BC/Visualization/DrawDoubleLines.py
DrawDoubleLines.py
py
1,322
python
en
code
121
github-code
6
37228942399
#!/usr/bin/env python3 import argparse import bids from bids import BIDSLayout import os from pathlib import Path def _filter_pybids_none_any(dct): import bids return { k: bids.layout.Query.NONE if v is None else (bids.layout.Query.ANY if v == "*" else v) for k, v in dct.items()...
ftdc-picsl/pmacsPreps
bin/bidsFilterTest.py
bidsFilterTest.py
py
4,368
python
en
code
0
github-code
6
5361852132
from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen from kivy.lang import Builder import wikipedia from urllib import request Builder.load_file(filename="search.kv") class FirstScreen(Screen): def get_img_link(self): # get user search query = self.manager.current_scre...
mido-99/Advanded-OOP
App-4-Webcam-Photo-Sharer/main.py
main.py
py
4,504
python
en
code
0
github-code
6
26676860635
from flask import Flask, render_template, request, redirect from flask_wtf import FlaskForm from wtforms import StringField, HiddenField, RadioField from wtforms.validators import Length, ValidationError import phonenumbers import random import json import os app = Flask(__name__) app.secret_key = 'Secret!' hours = {...
maksimKnz/flask-project2
app.py
app.py
py
6,791
python
en
code
0
github-code
6
32102854189
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def detectCycle(self, head: ListNode) -> ListNode: if not head or not head.next: return None slow, fast = head, head while fast and fast.next: slow = slow.next ...
Eleanoryuyuyu/LeetCode
字节跳动/链表与树/环形链表 II.py
环形链表 II.py
py
760
python
en
code
3
github-code
6
72602213309
class Solution: def findOccurrences(self, text, first, second): text_list = text.split() res = [] for i in range(len(text_list)-2): if text_list[i] == first and text_list[i+1] == second: res.append(text_list[i+2]) return res if __name__ == "__main__": ...
CodingBuye/PythonForLeetcode
Easy/1078.Occurrences After Bigram.py
1078.Occurrences After Bigram.py
py
460
python
en
code
0
github-code
6
15166780973
#!/usr/bin/python3 if __name__ == "__main__": import sys from calculator_1 import div, mul, add, sub if len(sys.argv) != 4: print("Usage: ./100-my_calculator.py <a> <operator> <b>") exit(1) op_list = {'+': "add", '-':"sub", '/':"div", '*':"mul"} if sys.argv[2] not in list(op_list.key...
AhmedNewiry/alx-higher_level_programming
0x02-python-import_modules/100-my_calculator.py
100-my_calculator.py
py
538
python
en
code
0
github-code
6
19739382962
import json import mechanize import sys import logging import time import urllib from constants import * from excepciones import * from imagen import * from datetime import date, timedelta from termcolor import colored logger = logging.getLogger(__name__) class Browser(object): def __init__(self, config, login=T...
adrianlzt/ingdirect_cli
browser.py
browser.py
py
20,033
python
en
code
0
github-code
6
21276871246
import mindspore as ms import numpy as np from mindspore import Parameter, Tensor from mindspore.ops import operations as P from mindspore_rl.agent import Trainer, trainer class QMIXTrainer(Trainer): """ This is the trainer class of QMIX, which provides the logic of this algorithm. """ def __init__...
mindspore-lab/mindrl
mindspore_rl/algorithm/qmix/qmix_mpe_trainer.py
qmix_mpe_trainer.py
py
5,690
python
en
code
21
github-code
6
7725885886
import pandas as pd from sqlalchemy import create_engine from influxdb import InfluxDBClient import time def connectSQL(): connection_str = 'mssql+pyodbc://royg:Welcome1@SCADA' engine = create_engine(connection_str) conn = engine.connect() return conn def getData(conn,interval): if (interval==1):...
thongnbui/MIDS_251_project
python code/SendToInflux.py
SendToInflux.py
py
2,797
python
en
code
0
github-code
6
2298089969
import concurrent.futures from datetime import datetime import pymongo as pmg import os import uuid from dotenv import load_dotenv load_dotenv() import pytz tz_ind = pytz.timezone('Asia/Kolkata') now = datetime.now(tz_ind) class Logit: """ logger class use this class to log the execution of the program. ...
sanjeevan121/ecommerce
logger/logit.py
logit.py
py
3,100
python
en
code
1
github-code
6
71749351229
from json import loads from kafka import KafkaConsumer consumer = KafkaConsumer( 'test-topic', bootstrap_servers=['0.0.0.0:9092'], auto_offset_reset='earliest', enable_auto_commit=True, group_id='test-json-group', value_deserializer=lambda x: loads(x.decode('utf-8'))) for message in consumer: ...
makseli/kafka-docker-python
consumer-json.py
consumer-json.py
py
522
python
en
code
0
github-code
6
19521121631
import socket import threading from queue import Queue import sys import time import logging import json # pip install PyExecJS #import execjs # # 1. 在windows上不需要其他的依赖便可运行execjs, 也可以调用其他的JS环境 # # windows 默认的执行JS的环境 # execjs.get().name # 返回值: JScript # # 作者本人的windows上装有Node.js , 所以返回值不同 # execjs.get().name # 返回值: Node....
optimjiang/my_3d_game
comm_with_server.py
comm_with_server.py
py
8,394
python
en
code
0
github-code
6
1828590890
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Jackson O'Donnell # jacksonhodonnell@gmail.com from __future__ import division, print_function import healpy as hp import numpy as np from .beam import r3_channel_beams from .constants import (ffp8_nu4_central_freqs, ffp8_nu6_central_freqs) def make_big_R(R4...
jhod0/lgmca_planck_tools
lgmca_planck_tools/planck/fitting.py
fitting.py
py
4,829
python
en
code
0
github-code
6
10230066135
from typing import Optional import tiktoken from evals.elsuite.ballots.prompts import ( control_chat_prompt, control_text_template, manipulation_chat_template, manipulation_text_template, text_prompt, voter_chat_prompt, voter_text_prompt, ) from evals.registry import is_chat_model LOGIT_B...
openai/evals
evals/elsuite/ballots/utils.py
utils.py
py
3,804
python
en
code
12,495
github-code
6
34346316993
''' Exercises of the book "Think python" 13.1.8 Exercise: ''' # Markov analysis: # # 1. Write a program to read a text from a file and perform Markov analysis. The result # should be a dictionary that maps from prefixes to a collection of possible suffixes. # The collection might be a list, tuple, or dicti...
LiliiaMykhaliuk/think-python
chapter13/13.1.8.py
13.1.8.py
py
5,264
python
en
code
0
github-code
6
3367814266
from datetime import date import discord from discord.utils import get from commands import automoderation, send_by_bot from constants import Channels, Members from init_bot import bot from utils.format import create_embed from utils.guild_utils import check_for_beer, find_animated_emoji, get_referenced_author, get_m...
Traus/discord_bot
events/messages.py
messages.py
py
6,311
python
en
code
0
github-code
6
35416705607
#-*- coding: utf-8 -*- from __future__ import print_function import pandas as pd from apriori import * inputfile = 'C:/Users/zhou/Desktop/rrecognized affected infrastructure entities in each news set.xls' outputfile = 'C:/Users/zhou/Desktop/apriori_rules.xls' data = pd.read_excel(inputfile, header = None) ...
0AnonymousSite0/Raw-Data-and-Processing-Details
For Phase 5 Association Rule Learning for IFI chains.py
For Phase 5 Association Rule Learning for IFI chains.py
py
605
python
en
code
2
github-code
6
32185442685
import logging import flask import time import signal import sys import socket from flask import Flask from flask_api import status from os import environ from kubernetes import client, config log = logging.getLogger() log.addHandler(logging.StreamHandler()) log.setLevel(logging.INFO) app = Flask(__name__) try: ...
kiemlicz/util
dockerfiles/experiments/web.py
web.py
py
1,526
python
en
code
20
github-code
6
1523318864
""" Given an array arr[] of n integers, construct a Product Array prod[] (of same size) such that prod[i] is equal to the product of all the elements of arr[] except arr[i]. Solve it without division operator in O(n) time. values = [1,2,3,4,5] output = [120, 60, 40, 30, 24] asked in cimpress coding round(3) part o...
kartikwar/programming_practice
dynamic_programming/product_at_index_i.py
product_at_index_i.py
py
1,015
python
en
code
0
github-code
6
32143586237
import utils import requests import json, sys from datetime import date, datetime, timedelta space_key = "SVMC" # parentTitle = "Project Report - Automatic" # weeklyPageTitle = "Weekly Project Status Report" # monthlyPageTitle = "CP Monthly Report" dailyPageTitle = "Issue Status Tool" pageUrgentPrjTitle = "Issue Tool...
hoangdt9/hoang
WikiSubmit.py
WikiSubmit.py
py
11,061
python
en
code
0
github-code
6