seq_id
stringlengths
7
11
text
stringlengths
156
1.7M
repo_name
stringlengths
7
125
sub_path
stringlengths
4
132
file_name
stringlengths
4
77
file_ext
stringclasses
6 values
file_size_in_byte
int64
156
1.7M
program_lang
stringclasses
1 value
lang
stringclasses
38 values
doc_type
stringclasses
1 value
stars
int64
0
24.2k
dataset
stringclasses
1 value
pt
stringclasses
1 value
28029416892
from django.shortcuts import render,redirect from django.contrib.auth.decorators import login_required from django.http.response import JsonResponse from ..models import Image import json from django.template.loader import render_to_string # Create your views here. @login_required def menu_main(request): print('北'...
mituoka/hobby_management
hobby_management/main_app/views/menu.py
menu.py
py
2,688
python
en
code
0
github-code
6
19280716334
import dict # print(dict.word_dict) words = dict.word_dict center_letter = input("enter the center letter: ") other_letters = [] for i in range(1, 7): letter = input("enter other letter " + str(i) + ": ") while letter in other_letters or letter == center_letter: print("letter has been used ") ...
LovelyGkotta/script
python_spelling_bee_crack/spell.py
spell.py
py
889
python
en
code
0
github-code
6
4459921919
from . import dataset import os import shutil from tqdm import tqdm import cv2 import numpy as np def coco_data(images_path, json_annotation_path): # list files in dir if not os.path.exists(images_path): raise FileExistsError("images path not found") if not os.path.exists(json_annotation_path): ...
virasad/semantic_segmentation_service
train/utils/datahandler.py
datahandler.py
py
3,116
python
en
code
2
github-code
6
32909477589
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import datetime import time import random import decimal from PySide2.QtWidgets import QApplication, QMessageBox, QWidget from PySide2 import QtCore from PySide2.QtUiTools import QUiLoader from PyQt5.QtCore import QTimer marry_date = '2020-07-06' birth_date = '2022-01-22 ...
id10tttt/tools
qt_tools/compute_day.py
compute_day.py
py
2,564
python
en
code
1
github-code
6
36223514660
# -*- coding: utf-8 -*- """ Created on Sun Sep 24 11:01:22 2023 @author: brand """ import math import matplotlib.pyplot as plt import numpy as np timeStep = 0.01 #seconds timeRange = np.arange(0,5,timeStep).tolist() # 20 seconds to take off # reynolds is 200k class Aircraft(): def __init__(self, weight, wingAvgCho...
Brandonh291/RC-Plane
Systems Engineering/Phase B - Preliminary Design and Technology Completition/Plane Take-off Sim.py
Plane Take-off Sim.py
py
3,633
python
en
code
0
github-code
6
12025294058
from typing import Dict from numbers import Number from transformers.trainer_utils import EvalPrediction from sklearn.metrics import accuracy_score, precision_recall_fscore_support def compute_sts_metrics(eval_pred: EvalPrediction) -> Dict[str, Number]: predictions, labels = eval_pred preds = predictions.arg...
jinmang2/sts-sift
solution/metrics.py
metrics.py
py
596
python
en
code
1
github-code
6
9264743430
import numpy import numpy as np def vec2diad(vec): return np.outer(vec, vec) def cross_prod_mat(vec): identity = np.eye(3) return np.cross(identity, vec.reshape(-1, )) def vector_angle(a, b, normalized=False): if normalized: return np.arccos(np.clip(np.dot(a, b), -1., 1.)) else: ...
rpatrik96/adcs-simulation
src/alg_utils.py
alg_utils.py
py
3,468
python
en
code
0
github-code
6
1293512231
import inspect from onnx import defs from onnx.backend.test.runner import BackendIsNotSupposedToImplementIt from onnx_jax.logger import logger class Handler(object): ONNX_OP = None DOMAIN = defs.ONNX_DOMAIN VERSION = 0 SINCE_VERSION = 0 @classmethod def check_cls(cls): if not cls.O...
gglin001/onnx-jax
onnx_jax/handlers/handler.py
handler.py
py
1,679
python
en
code
7
github-code
6
37864457588
import subprocess import sys def process_exists(process_name): if sys.platform.startswith("win32"): # https://stackoverflow.com/questions/7787120/python-check-if-a-process-is-running-or-not # Use tasklist to reduce package dependency. call = "TASKLIST", "/FI", "imagename eq %s" % process...
juria90/service_ppt
process_exists.py
process_exists.py
py
768
python
en
code
0
github-code
6
72532696509
""" Subsystem to communicate with catalog service """ import logging from aiohttp import web from pint import UnitRegistry from servicelib.aiohttp.application_setup import ModuleCategory, app_module_setup from . import _handlers _logger = logging.getLogger(__name__) @app_module_setup( __name__, ModuleCate...
ITISFoundation/osparc-simcore
services/web/server/src/simcore_service_webserver/catalog/plugin.py
plugin.py
py
801
python
en
code
35
github-code
6
1584126381
# -*- coding: utf-8 -*- import os from django.utils.translation import ugettext_lazy as _ from cms.plugin_pool import plugin_pool from cms.plugin_base import CMSPluginBase from filer.settings import FILER_STATICMEDIA_PREFIX from cmsplugin_filer_html5video.models import FilerHTML5Video class FilerHTML5VideoPlugin(C...
beniwohli/cmsplugin-filer-html5video
cmsplugin_filer_html5video/cms_plugins.py
cms_plugins.py
py
1,464
python
en
code
8
github-code
6
29806901602
import os from dataclasses import dataclass from datetime import datetime from fastapi.encoders import jsonable_encoder from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import joinedload from MenuApp.src.models import Menu, Submenu @dataclass class ReportService: ...
Aliakseeva/MenuApp
MenuApp/src/services/tasks/report_service.py
report_service.py
py
2,538
python
en
code
0
github-code
6
10138014338
import engine.db_structure as db_py import os filename = "io.vdb" if os.path.isfile(filename): os.remove(filename) db = db_py.Database(False, filename) def test_create_io(): db.create_table("vadik_table", {"zhenya1": "int", "zhenya2": "str"}) assert db.get_io_count() == 31 def test_insert_io(): db....
etozhezhenechka/VadikDB
engine_tests/io_tests.py
io_tests.py
py
993
python
en
code
0
github-code
6
36416683518
class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: num = [0]*len(temperatures) index = [] for i,j in enumerate(temperatures): while len(index)!=0 and temperatures[index[-1]] < j: i1 = index.pop() num[i1] = i - i1 ...
eyosiasbitsu/Competitive-programming-A2SV
Before BootCamp/week2/daily-temperatures.py
daily-temperatures.py
py
363
python
en
code
3
github-code
6
74189715388
# 3 : Write a Python program to display the first and last colors from the following list. # Example : color_list = ["Red","Green","White" ,"Black"]. # Your list should be flexible such that it displays any color that is part of the list. from typing import List color_list = ["Red", "Green", "White", "Black", "Pink", ...
aryashah0907/Arya_GITSpace
Test_Question_2.py
Test_Question_2.py
py
454
python
en
code
0
github-code
6
2077956577
from odoo import models, api, fields, _ # from odoo.exceptions import UserError from datetime import datetime from dateutil.relativedelta import relativedelta import json import xlsxwriter _ from odoo.exceptions import ValidationError from odoo.exceptions import UserError import base64 import io tr...
Odolution/lacas
ol_lacas_custom_recovery_report/wizard/custom_wizard.py
custom_wizard.py
py
8,991
python
en
code
0
github-code
6
17931901914
'''. Average Salary Excluding the Minimum and Maximum Salary Easy 2K 174 Companies You are given an array of unique integers salary where salary[i] is the salary of the ith employee. Return the average salary of employees excluding the minimum and maximum salary. Answers within 10-5 of the actual answer will be accept...
LakshmiN5/leetcode_ex
avg_sal_exc_max_min.py
avg_sal_exc_max_min.py
py
988
python
en
code
0
github-code
6
7266170385
from chaco.api import Plot from chaco.tools.api import BetterSelectingZoom, PanTool """ Chaco wrapper. """ class ChacoPlot(Plot): """ A 2D Chaco plot wrapped with useful common functionality. """ @staticmethod def sci_formatter(value): """ Convert a value to a scientific notation string as applicable. ""...
0/SpanishAcquisition
spacq/gui/display/plot/common/chaco_plot.py
chaco_plot.py
py
1,396
python
en
code
1
github-code
6
1701692877
#!/usr/bin/python3 # hashtable """ ADT: slot init private: _load_factory 计算负载因子 _rehash 重新hash _hash hash计算index _find_key _check_can_insert _find_slot_for_insert public: get add remove reindex: (index * 5 + 1) % _len factory: ...
ChenBaiYii/DataStructure
hashtable.py
hashtable.py
py
4,277
python
en
code
0
github-code
6
7166024264
import pathlib from typing import Any import pytest from competitive_verifier.models import ( AddtionalSource, CommandVerification, ConstVerification, ResultStatus, VerificationFile, ) test_parse_VerificationFile_params: list[ tuple[VerificationFile, dict[str, Any], dict[str, Any]] ] = [ ...
competitive-verifier/competitive-verifier
tests/models/test_file.py
test_file.py
py
4,735
python
en
code
8
github-code
6
39372786389
# -*- coding: utf-8 -*- ''' Server Program used to handle multiple clients in a secure manner using certificates and SSL/TLS protocol, store data to the database. @author: Manish Gupta <manishthaparian.gupta@gmail.com> ''' # Copyright (C) 2018 Manish Gupta <manishthaparian.gupta@gmail.com>; # This progr...
manishgupta1208/SP-home
home.py
home.py
py
8,738
python
en
code
0
github-code
6
14347113756
import pandas as pd def pre_processing_state_table(data_df): """ This function takes a pandas DataFrame as input and splits the next_state_0 and next_state_1 columns into two columns each. """ data_df = data_df.applymap(lambda x: x.strip()) data_df[['next_state_0', 'output_0']] = data_df['next...
Duynghk/LogicDesign
website/minimize_state_table.py
minimize_state_table.py
py
7,473
python
en
code
1
github-code
6
19882697980
import os import trio import ssl from async_generator import asynccontextmanager from structlog import get_logger from typing import Optional, Union from guardata.crypto import SigningKey from guardata.api.transport import Transport, TransportError, TransportClosedByPeer from guardata.api.protocol import ( DeviceI...
bitlogik/guardata
guardata/client/backend_connection/transport.py
transport.py
py
6,416
python
en
code
9
github-code
6
38967040281
# -*- coding: utf-8 -*- import scrapy from bs4 import BeautifulSoup import re from desk_zol.items import DeskZolItem class BizhiSpider(scrapy.Spider): name = 'bizhi' start_urls = ['http://desk.zol.com.cn/nb/','http://desk.zol.com.cn/pc/'] def parse(self, response): soup = BeautifulSoup(response...
zaoyubo/desk_zol
desk_zol/spiders/bizhi.py
bizhi.py
py
1,401
python
en
code
0
github-code
6
40290878008
def profitTable(maxPrice): """Prints a table of profits from a show based on ticket price.    Parameters:        maxPrice: maximum price to consider    Return value: None    """ print('Price   Income    Profit') print('------ --------- ---------') for price in range(1, 2*maxPrice + 1): realprice =...
vivekworks/learning-to-code
4. Discovering Computer Science/Python/Chapter 4 - Growth And Decay/concert.py
concert.py
py
616
python
en
code
0
github-code
6
43536075224
import requests import json import os import sys import logging logger = logging.getLogger(__name__) def gdc_read_file(file_id="11443f3c-9b8b-4e47-b5b7-529468fec098"): data_endpt = "https://api.gdc.cancer.gov/slicing/view/{}".format(file_id) TOKEN_FILE_PATH = os.environ.get('GDC_TOKEN') if not TOKEN_FIL...
neksa/mutagene
mutagene/io/gdc.py
gdc.py
py
807
python
en
code
3
github-code
6
9093667498
filename = 'input.txt' # filename = 'test.txt' data = ['A Y', 'B X', 'C Z'] def load_data(filename): data = [] with open(filename) as f: lines = f.readlines() for line in lines: if line != '\n': data.append(line.strip()) return data def calc_match_score(matc...
lapssh/advent_of_code
2022/day02/day02.py
day02.py
py
2,332
python
en
code
0
github-code
6
26113028615
__authors__ = ["T. Vincent"] __license__ = "MIT" __date__ = "03/04/2017" import ctypes import numpy from .....math.combo import min_max from .... import _glutils as glutils from ...._glutils import gl from .GLPlotItem import GLPlotItem class GLPlotTriangles(GLPlotItem): """Handle rendering of a set of colored...
silx-kit/silx
src/silx/gui/plot/backends/glutils/GLPlotTriangles.py
GLPlotTriangles.py
py
5,702
python
en
code
106
github-code
6
26529515886
#한수 N = int(input()) result = N for i in range(1, N+1): temp = [] while i != 0: temp.append(i % 10) i = i // 10 if len(temp) < 3: continue dif = temp[0] - temp[1] for j in range(1, len(temp)-1): if dif != (temp[j] - temp[j+1]): result -= 1 bre...
Jaeheon-So/baekjoon-algorithm
완전탐색/1065.py
1065.py
py
340
python
en
code
0
github-code
6
33875335541
import torch import wandb from .utils import matrix_to_dict class Logger(object): def __init__(self, hparams, model) -> None: super().__init__() self.hparams = hparams self._setup_exp_management(model) self.total_loss_values = None def _setup_exp_management(self, model): ...
rpatrik96/nl-causal-representations
care_nl_ica/logger.py
logger.py
py
1,456
python
en
code
12
github-code
6
10368808313
from . import get_help __doc__ = get_help("help_autoban") from telethon import events from pyUltroid.dB.base import KeyManager from . import LOGS, asst, ultroid_bot, ultroid_cmd Keym = KeyManager("DND_CHATS", cast=list) def join_func(e): return e.user_joined and Keym.contains(e.chat_id) async def dnd_func(...
TeamUltroid/Ultroid
plugins/autoban.py
autoban.py
py
1,550
python
en
code
2,615
github-code
6
32060115586
import torch from torch import nn from torchvision import models, transforms class VGG16Extractor(nn.Module): def __init__(self): super(VGG16Extractor, self).__init__() vgg = models.vgg16(pretrained=True) features = vgg.features self.relu_1_2 = nn.Sequential() self.relu_2...
harsh020/image-colorization
colorizer/utils.py
utils.py
py
1,588
python
en
code
1
github-code
6
9384835860
import argparse from click import secho import sys from DNScanner.DNScanner import DNScanner savesys = sys.stdout # Flags parser = argparse.ArgumentParser(description='\t Scan domains https://github.com/ChinadaCam/DNScanner') parser.add_argument('-d', '--domain', required=True, type=str, help='Set domain (example.c...
ChinadaCam/DNScanner
start.py
start.py
py
2,894
python
en
code
9
github-code
6
38961189531
class Employe: def setEmploye(self,Eid,Ename,Desig,Salary): self.Eid=Eid self.Ename=Ename self.Desig=Desig self.Salary=Salary def PrintEmploye(self): print("Your Id is",self.Eid) print(self.Ename) print(self.Desig) print(self.Salary) ob=Employe() o...
Aswin2289/LuminarPython
LuminarPythonPrograms/Oops/Employe.py
Employe.py
py
378
python
en
code
0
github-code
6
72532004029
# pylint: disable=redefined-outer-name # pylint: disable=unused-argument from copy import deepcopy import pytest from pytest import MonkeyPatch from settings_library.docker_registry import RegistrySettings MOCKED_BASE_REGISTRY_ENV_VARS: dict[str, str] = { "REGISTRY_AUTH": "False", "REGISTRY_USER": "usr", ...
ITISFoundation/osparc-simcore
packages/settings-library/tests/test_docker_registry.py
test_docker_registry.py
py
1,754
python
en
code
35
github-code
6
277948458
import torch import torch.nn as nn from shapmagn.global_variable import Shape from shapmagn.utils.obj_factory import obj_factory from shapmagn.modules_reg.module_gradient_flow import gradient_flow_guide from shapmagn.shape.point_sampler import point_fps_sampler class GradFlowPreAlign(nn.Module): def __init__(self...
uncbiag/shapmagn
shapmagn/modules_reg/module_gradflow_prealign.py
module_gradflow_prealign.py
py
12,227
python
en
code
94
github-code
6
38831023014
from hyperopt import hp, STATUS_OK import numpy as np from mne.filter import resample from crossvalidate import crossvalidate,test_ensamble,test_naive, run_a_trial from keras.utils import to_categorical import keras.backend as K import uuid from utils import save_results,get_subj_split from my_models import ShallowCo...
bkozyrskiy/NN_hyperopt_search
opt_shallow.py
opt_shallow.py
py
3,725
python
en
code
0
github-code
6
11474271839
''' Created on Jan 9, 2010 @author: eric ''' import asyncore import socket import time from ParsedMessage import ParsedMessage class Connection(asyncore.dispatcher): ''' maintains the connection to the server ''' buffer = "" bytesIn = 0 bytesOut = 0 connectionAttempts = 0 reconn...
ericbutera/pyib
src/Pyib/Connection.py
Connection.py
py
3,734
python
en
code
0
github-code
6
16838640248
import pytest import requests_mock from csvcubed.utils.cache import session from csvcubed.definitions import ROOT_DIR_PATH @pytest.fixture(scope="package", autouse=True) def mock_http_session_qube_config_schema(): """ Fixture which mocks the HTTP responses of the JSON qube-config schema file for testing. ...
GDonRanasinghe/csvcubed-models-test-5
csvcubed/tests/unit/readers/cubeconfig/v1_0/conftest.py
conftest.py
py
844
python
en
code
0
github-code
6
74883082427
from collections import defaultdict class UnionFind(): def __init__(self, n): # 頂点の値が0から始まる前提なので注意 self.par = [i for i in range(n)] def root(self, x): if self.par[x] == x: return x else: self.par[x] = self.root(self.par[x]) return self.par[x...
kazuo-mu/at_coder_answers
ABC049/d_connectivity.py
d_connectivity.py
py
1,393
python
ja
code
0
github-code
6
42137815915
import numpy as np # Set the seed for reproducibility np.random.seed(42) # Define the number of bulbs and the number of defective bulbs num_bulbs = 100 num_defective = 10 # Define the sample size and the number of simulations sample_size = 5 num_simulations = 100000 tolerance = 0.01 # Simulate drawing samples and c...
gadepall/digital-communication
ncert/12/13/5/14/codes/verify_soln.py
verify_soln.py
py
782
python
en
code
7
github-code
6
24680635783
# -*- coding: utf-8 -*- """ @author: Yashoeep @Roll number: 170003060 @Read Inputs @ This function will read inputs from the inpus folder and store them properly @ in a dictionary which is also the return value return valuedescription --> { ... subject : { images: [ list of paths to images for this su...
yashodeepchikte/Multi-Template-Matching
main/read_inputs.py
read_inputs.py
py
3,023
python
en
code
5
github-code
6
3774041977
#!/usr/bin/env python import argparse import yaml import sys import http.server import http.client import requests configFile = 'config.yaml' configDefault = {'server': {'host': "127.0.0.1", 'port': 2323}, 'proxies': None, 'forwarder': {'host': "127.0.0.1", 'headers': ["Content-Type"...
ecator/http-forwarder
http-forwarder.py
http-forwarder.py
py
6,296
python
en
code
0
github-code
6
4312235542
def print_rangoli(size): letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] line_size = 4 * size - 3 l = letters[0: size] limit = (2 * size - 1) // 2 + 1 sb = "-" S = [] for i in range(limit): ...
thiagojuliao/Hacker-Rank
Python/Strings/AlphabetRangoli.py
AlphabetRangoli.py
py
813
python
en
code
1
github-code
6
42931890464
from turtle import right class Solution: def minSwaps(self, arr, b): minCount = 0 for i in range(len(arr)): if arr[i] < b: minCount +=1 if minCount <= 1: return 0 else: rightCount, leftCount, count = 0, 0, 0 ...
shwetakumari14/Practice-Problems
Pythons Solutions/Minimum Swaps.py
Minimum Swaps.py
py
890
python
en
code
0
github-code
6
26624507906
from livesettings import * from django.utils.translation import ugettext_lazy as _ # this is so that the translation utility will pick up the string gettext = lambda s: s _strings = (gettext('CreditCard'), gettext('Credit Card')) PAYMENT_GROUP = ConfigurationGroup('PAYMENT_AUTHORIZENET', _('Authorize.net Payment ...
dokterbob/satchmo
satchmo/apps/payment/modules/authorizenet/config.py
config.py
py
4,529
python
en
code
30
github-code
6
34225982423
#This file is part of Chess-game-tracker. #Chess-game-tracker 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. #Chess-game-tracker is dis...
nandovm/chess-game-tracker
Chess-game-tracker/multithread/Capturer.py
Capturer.py
py
2,793
python
en
code
1
github-code
6
33317389259
import pandas as pd import streamlit as st import folium from streamlit_folium import st_folium st.title("Peta Nilai Properti Kota Tangerang") st.markdown("Sumber Data: Pusat Pembinaan Profesi Keuangan") st.markdown("") # Load data df_tangcity = pd.read_csv('df_property.csv') # Set up map tangcity_map = f...
danarssidig/propertymap
property_map.py
property_map.py
py
2,935
python
en
code
0
github-code
6
72197108348
#Look for #IMPLEMENT tags in this file. These tags indicate changes in the #file to implement the required routines. '''8-Puzzle STATESPACE ''' import copy from search import * class eightPuzzle(StateSpace): StateSpace.n = 0 def __init__(self, action, gval, state, parent = None): '''Create a...
TylerPham/Eight_puzzle_solver
eightPuzzle.py
eightPuzzle.py
py
5,880
python
en
code
0
github-code
6
26626826683
# Import the qrcode library import qrcode # Create a qr code instance qr = qrcode.QRCode( version = 1, error_correction = qrcode.constants.ERROR_CORRECT_L, box_size = 10, border = 4, ) # The data that you want to encode data = "192.168.1.19:8765" # Add the data qr.add_data(data) qr.make(fit=True) # ...
Gex-devs/val_overlay
ts/BackUp_Local_Api_py/QRcode.py
QRcode.py
py
564
python
en
code
2
github-code
6
41119379113
import random random.seed(1) import numpy as np np.random.seed(1) import tensorflow.compat.v1 as tf tf.random.set_random_seed(1) import gym import os tf.disable_v2_behavior() env = gym.make('CartPole-v1') class PolicyNetwork: def __init__(self, state_size, action_size, learning_rate, name='policy_network'): ...
eladfeld/DRL_hw
hw2/actor_critic.py
actor_critic.py
py
7,669
python
en
code
0
github-code
6
23777756221
from conformity.fields import Dictionary, UnicodeString, List import json instance = Dictionary({ "title": UnicodeString(), "url": UnicodeString(), "about_url": UnicodeString(), "description": UnicodeString(), "tags": List(UnicodeString()), }, optional_keys=["description", "tags", "about_url"]) ins...
simonw/datasette-registry
test_registry.py
test_registry.py
py
451
python
en
code
1
github-code
6
25608742266
# n, m 입력 n, m = map(int, input().split()) # 떡의 길이 리스트 입력 array = list(map(int, input().split())) # 이진탐색을 위한 범위인 절단기 높이를 1부터 가장 긴 떡의 길이까지 설정 lt=1 rt = max(array) # 이진 탐색 while lt<=rt: mid=(lt+rt)//2 total=0 # 떡의 길이가 mid 보다 길 때 떡의 길이 추가 for i in array: if i>mid: total+=i-mid # ...
seyiclover/AlgorithmStudy
Seyi/BinarySearch/떡볶이 떡 만들기.py
떡볶이 떡 만들기.py
py
767
python
ko
code
0
github-code
6
9345123435
from datetime import datetime from elasticsearch_dsl import DocType, Date, Nested, Boolean, \ analyzer, InnerObjectWrapper, Completion, Keyword, Text from elasticsearch_dsl.analysis import CustomAnalyzer as _CustomAnalyzer from elasticsearch_dsl.connections import connections connections.create_connection(hosts=["...
XiaoShenLong/scrapy-search
baike_spider/baike/models/es_types.py
es_types.py
py
1,703
python
en
code
0
github-code
6
33562211468
import cv2 import numpy as np def contraste(inp): f,c,color=inp.shape c1=np.min(inp) d=np.max(inp) for i in range(f): for j in range(c): inp[i][j][0]=round((inp[i][j][0]-c1)*((255)/(d-c1))) inp[i][j][1]=round((inp[i][j][1]-c1)*((255)/(d-c1))) inp[i][...
renzovc987/CG
multipliacion.py
multipliacion.py
py
1,313
python
en
code
0
github-code
6
38938537041
from Cache import Cache from Bus import Bus class Control: def __init__(self, number): self.cache = Cache() self.cache_state = self.cache.cache_mem self.cache_state self.bus = Bus.get_instance() self.bus.set_proc_control(number, self) self.number = number def ...
ortegajosant/cachecoherence
Control.py
Control.py
py
4,935
python
en
code
0
github-code
6
41635641329
''' This program rewrite corpus like LLL_triplets.txt into [ID \t sentence] in each line. There are ___, which are other protein names besides PROT1 and PROT2, in corpus. We replace ___ with PROT3, PROT4... ''' import sys, getopt argv = sys.argv[1:] try: opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])...
PeiYau-Lung/ChemProtBioCreativeVI
src/RewriteCorpus.py
RewriteCorpus.py
py
1,381
python
en
code
7
github-code
6
12877884293
from sklearn import datasets from sklearn.preprocessing import MaxAbsScaler from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report from sklearn.model_selection import train_test_split, cross_val_score from sklearn.linear_model import LogisticRegressi...
abhi-baireddy/IRProject
left_right_classifier.py
left_right_classifier.py
py
5,085
python
en
code
0
github-code
6
18244520374
import json from datetime import datetime, timedelta from news_utilities import add_news cache_file = '/home/pi/AlarmClockProject/AlarmClock/cache/calendars/' + 'cal_ed.json' homeworks = None calendar = None notes = None datetime_now = datetime.now() def str_to_datetime(date_str): if len(date_str) == 16: ...
cg-Kdaf/RPIAlarmClock
src/ED_utilities.py
ED_utilities.py
py
4,112
python
en
code
1
github-code
6
33816564423
from pyswip.prolog import Prolog from pyswip.easy import * prolog = Prolog() # Global handle to interpreter def query_the_KB(query): price, distance, cuisine_type = query retractall = Functor("retractall") known = Functor("known",3) def read_list_choice_py(A, V, Y): if str(A) == 'price...
AshNguyen/CS152-LBA
query_KB.py
query_KB.py
py
929
python
en
code
0
github-code
6
43085107371
#!/bin/env python import numpy as np from matplotlib import pyplot as plt import argparse import sys import parse_ats def load(fname, density): dat = np.loadtxt(fname) # units s, mol/s dat[:,0] = dat[:,0] / 86400. # convert to days dat[:,1] = dat[:,1] / density * 86400 # convert to m^3/d return dat d...
amanzi/ats
tools/utils/plot_runoff.py
plot_runoff.py
py
2,293
python
en
code
35
github-code
6
18298344467
import argparse import socket import struct import codecs import dns.resolver import dns.message import dns.query import base64 from aes import aes # Address of the DNS server #dns_server = "8.8.8.8" # DNS query message format #dns_query = struct.pack("!6H", 0x1234, 1, 1, 0, 0, 0) + b"\x03foo\x03bar\x00...
unicycling-amphibian/CovertDNS
DNSCovert_Client.py
DNSCovert_Client.py
py
9,310
python
en
code
0
github-code
6
34408932008
from flask_restplus import Resource from flask import current_app as cur_app from flask import request from app.main.services.story.brand_story_services import duplicate_story, get_all_draft_or_published_story, get_story, issue_story_template_before_save, post_story_publish_and_draft, remove_story_from_search, update_s...
deepakarya09/cureas_reads
app/main/controllers/api_story_controller.py
api_story_controller.py
py
3,300
python
en
code
0
github-code
6
3562737092
from modules import s3upload, s3transcribe, parse import argparse if __name__ == "__main__": # Create Argument Parser parser = argparse.ArgumentParser(description='Process video, create transcripts, proofread with OpenAI GPT.') parser.add_argument('input_folder', type=str, help='Input folder with .mp4 inte...
uitrial/Interview-Transcribe-Proofread
process_transcripts.py
process_transcripts.py
py
1,168
python
en
code
4
github-code
6
42269789956
from .models import * from .forms import * from app import filtersets import cx_Oracle from django.http.response import Http404 from django.shortcuts import render, redirect from django.contrib.auth import login from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.models import User ...
maxquevedo/safelyWeb
safely/app/views.py
views.py
py
21,095
python
en
code
2
github-code
6
40687101493
import time import unittest import s1ap_types import s1ap_wrapper class TestMultiEnbCompleteReset(unittest.TestCase): """Unittest: TestMultiEnbCompleteReset""" def setUp(self): """Initialize before test case execution""" self._s1ap_wrapper = s1ap_wrapper.TestWrapper() def tearDown(self)...
magma/magma
lte/gateway/python/integ_tests/s1aptests/test_multi_enb_complete_reset.py
test_multi_enb_complete_reset.py
py
3,952
python
en
code
1,605
github-code
6
70078277628
import numpy as np import torch import os import yaml import tqdm from addict import Dict from collections import defaultdict from matplotlib import pyplot as plt import matplotlib.patches as patches import pickle import random import pytorch_ssim from skimage.measure import compare_ssim as ssim from train import buil...
azadef/interactive_scene_generation
evaluate_vg.py
evaluate_vg.py
py
18,847
python
en
code
0
github-code
6
41118007213
import logging import time import traceback from pathlib import Path from requests_tracker.request import WebRequestType from requests_tracker.session import WebSessionFactory from requests_tracker.storage import convert_HAR_to_markdown, write_HAR_to_local_file, CookiesFileStorage from requests_tracker.util import Log...
eladeon/requests-tracker-python
examples/scraper.py
scraper.py
py
1,851
python
en
code
0
github-code
6
29379124351
def convert(h): return {'A': 1, 'B': 2, 'C': 3}[h] score = 0 for round in open('strategy.txt', 'r').read().split('\n'): foe, result = round.split(' ') foe = convert(foe) me = 0 if (result == 'Y'): score += 3 me = foe elif (result == 'Z'): score += 6 if (foe =...
patrikjanson/AoC2022
Day2_RockPaperScissors/part2.py
part2.py
py
606
python
en
code
0
github-code
6
7965040405
import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy import signal import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.collections import PolyCollection # # fs = 11240. # t = 10 # time = np.arange(fs*t) / fs # frequen...
phongcpt72/Unitmotion-Detection
Unitmotion/testplot.py
testplot.py
py
2,027
python
en
code
0
github-code
6
7505782016
import printing file_name = "game_stat.txt" gametitle = "Diablo II" # Export functions def exportdata(datas): with open("export.txt", "w") as data: for i in range(len(datas)): data.write(str(datas[i]) + "\n") if __name__ == "__main__": gamedata = printing.print_datas(file_name, gametit...
CodecoolMSC2017/pbwp-3rd-si-game-statistics-roskogabor
part2/export.py
export.py
py
348
python
en
code
0
github-code
6
8266559866
import copy import logging from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, Iterable, List, NamedTuple, Union import yaml import cekit from cekit.cekit_types import _T, RawDescriptor from cekit.config import Config from cekit.descriptor import ( Arg, Descriptor, Env, La...
cekit/cekit
cekit/descriptor/image.py
image.py
py
19,524
python
en
code
70
github-code
6
29876271313
# pylint: disable=invalid-name, unused-argument, unspecified-encoding, missing-function-docstring """ Implements all winreg functions https://docs.python.org/3/library/winreg.html#functions """ import os from typing import Union from re import findall from tempfile import TemporaryDirectory from warnings import warn f...
Jan200101/unixreg
unixreg/functions.py
functions.py
py
6,498
python
en
code
0
github-code
6
70338202429
#!/usr/bin/env python3 """ The main program that will be run on the Raspberry Pi, which is the controller for the pharmacy client. DINs of drugs on this pharmacy should be specified in din.cfg """ # these libraries come with python import logging import datetime import struct import asyncio import json ...
alimzhan2000/arka_project_on_python
drug_delivering_code.py
drug_delivering_code.py
py
11,430
python
en
code
1
github-code
6
1883485650
import sys import os import pefile # Imprime as seções de um executável def print_sections(directory, executable): pe = pefile.PE(executable if directory is None else directory + "/" + executable) sections = [] for section in pe.sections: sections.append(section.Name.decode('utf-8')) print(e...
kkatzer/CDadosSeg
T2/Parte2/T2P2a.py
T2P2a.py
py
791
python
en
code
0
github-code
6
19052604441
import json import snappy from structlog import get_logger from jwcrypto.common import base64url_decode from app.data_model.app_models import QuestionnaireState from app.storage import data_access from app.storage.storage_encryption import StorageEncryption logger = get_logger() class EncryptedQuestionnaireStorage...
ONSdigital/census-survey-runner
app/storage/encrypted_questionnaire_storage.py
encrypted_questionnaire_storage.py
py
2,887
python
en
code
0
github-code
6
6634012203
def isGlodonNumber(num): hset = set() t = 0 while t == len(hset): num = sum(map(lambda x: int(x)**2, list(str(num)))) if num == 1: return True t+=1 hset.add(num) return False # if 1 < num < 4: # return False # return True # map...
rh01/gofiles
lcode1-99/ex06/glodon.py
glodon.py
py
370
python
en
code
0
github-code
6
14875088196
import bpy import bmesh import sys import time import argparse # blender -b -P Resize.py -- --height 0.8 --inm Objects/Bed.obj --outm oBed2.obj def get_args(): parser = argparse.ArgumentParser() # get all script args _, all_arguments = parser.parse_known_args() double_dash_index = all_arguments.index('--...
Niloofar-didar/AR-Realtime-Decimation-main
eAR-offline_modeling/Resize.py
Resize.py
py
1,784
python
en
code
2
github-code
6
36181808903
""" gradient descent 연습 """ import matplotlib.pyplot as plt from scratch08.ex01 import difference_quotient, tangent, move def g(x): """y = (1/3)x**3 - x""" return x ** 3 / 3 - x if __name__ == '__main__': # ex01에서 작성한 함수를 이용, 함수 g(x)의 그래프를 그림 # 극값(local 최소/최대)를 경사 하강법으로 찾음 xs = [x / 10 for x in ...
lee-saint/lab-python
scratch08/ex02.py
ex02.py
py
1,510
python
en
code
0
github-code
6
39749765607
""" This file creates all the tables and databases, used in the in_Voice APP as class, and also does the CRUD operations of database by using the methods. """ # Importing the required modules to working with database import sqlite3 # Importing os module to work with files and folders import os # Importing a function...
Kumara2mahe/in_Voice
inVoiceDB.py
inVoiceDB.py
py
50,993
python
en
code
0
github-code
6
14349515929
import numpy as np # import packages from PIL import Image import pytesseract import argparse import cv2 import os import re # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("--image", required=True, help="path to input image to be OCR'd") ap.add_argument("-p", "--...
guessthepartei/App
magic/parse.py
parse.py
py
2,186
python
en
code
0
github-code
6
6547068714
""" Tests for Randomized Reconstruction Commands """ import unittest import requests import sys import os import importlib from pathlib import Path import json # Add the client folder to sys.path CLIENT_DIR = os.path.join(os.path.dirname(__file__), "..", "client") if CLIENT_DIR not in sys.path: sys.path.append(C...
albertotono/Fusion360GalleryDataset
tools/fusion360gym/test/test_fusion360gym_randomized_reconstruction.py
test_fusion360gym_randomized_reconstruction.py
py
6,122
python
en
code
null
github-code
6
31019892466
import json import re import os from bs4 import BeautifulSoup import io import html2text #import transformationScript import datetime #from pprint import pprint class Word: content = "" tag = "" # The class "constructor" - It's actually an initializer def __init__(self, content, tag): self.co...
fspring/NeuralArgMining
Translators/Portuguese/TransFormationScriptComplete.py
TransFormationScriptComplete.py
py
17,944
python
en
code
0
github-code
6
35920335524
import requests from bifocal import utils, models from polo import Polo from coindesk import Coindesk class Blockscan(object): @staticmethod def _request(**kwargs): uri = 'http://xcp.blockscan.com/api2?%s' % utils.encode_args(kwargs) ret = requests.get(uri) return utils.parse_json(ret...
super3/bifocal
bifocal/apis/blockscan.py
blockscan.py
py
1,672
python
en
code
1
github-code
6
388251844
favorites = ['Creme Brulee', 'Apple Pie', 'Churros', 'Tiramisú', 'Chocolate Cake'] for i in range(10): print(f"looping {i}") for item in favorites: print(f"I like this {item}") count = 0 while count < len(favorites): print(f"I like this desert, {favorites[count]}") count += 1 for idx, item in enum...
andrejarboe/meta
python/course1/1loops.py
1loops.py
py
847
python
en
code
0
github-code
6
15211930040
""" Perform Outlier Rejection with MCMC ----------------------------------- Figure 8.9 Bayesian outlier detection for the same data as shown in figure 8.8. The top-left panel shows the data, with the fits from each model. The top-right panel shows the 1-sigma and 2-sigma contours for the slope and intercept with no ou...
astroML/astroML_figures
book_figures/chapter8/fig_outlier_rejection.py
fig_outlier_rejection.py
py
8,174
python
en
code
7
github-code
6
13394323895
# -*- coding: utf-8 -*- """This module loads images from csv files and outputs numpy arrays""" from __future__ import absolute_import, division, print_function from copy import deepcopy import numpy as np import tensorflow as tf from six import string_types import niftynet.utilities.util_csv as util_csv from niftyne...
LUYU0004/ISLES2018-1
lib/niftynet/io/image_reader.py
image_reader.py
py
10,262
python
en
code
0
github-code
6
6827571219
""" https://adventofcode.com/2020/day/17 """ from typing import List from copy import deepcopy from functools import lru_cache def part1(data: List[str]) -> int: """ O(n) solution """ size_x = len(data[0]) + 2 * CYCLES size_y = len(data) + 2 * CYCLES size_z = CYCLES * 2 + 1 pocket = [[[False] *...
pozhega/AoC
2020/d17.py
d17.py
py
3,804
python
en
code
0
github-code
6
22093127538
import sys import itertools expected = open(sys.argv[1], 'r').readlines() actual = open(sys.argv[2], 'r').readlines() # do a pc analysis. easiest bugs to find are the ones where we simply dont run a set of code that # the expected output shows should be run. expected_pcs = list(map(lambda x : x.strip().split(" ")[-...
bmchtech/GameBeanAdvance
source/emu/core/diag/compare-logs.py
compare-logs.py
py
1,480
python
en
code
24
github-code
6
73819284349
import numpy as np import dill import math import sys sys.path.append('../') sys.path.append('./') from src.graph import Graph from src.evolution_strategies import one_plus_lambda, tournament_selection from src.population import Population from src.arg_parser import parse_args import cProfile import pstats def bool_a...
fhtanaka/CGPython
tests/diversity_parity_test.py
diversity_parity_test.py
py
3,954
python
en
code
2
github-code
6
16606388338
from rich import print from napalm import get_network_driver from my_devices import arista1, arista2, arista3, arista4 def main(): for device in (arista1, arista2, arista3, arista4): driver = get_network_driver('eos') with driver(**device) as device: device.open() ...
caseymorris87/pynet_test2
napalm/ex2.py
ex2.py
py
839
python
en
code
0
github-code
6
20105217581
#https://towardsdatascience.com/how-to-perform-lasso-and-ridge-regression-in-python-3b3b75541ad8 import numpy as np import pandas as pd #we only have three advertising mediums, and sales is our target variable. DATAPATH = 'Advertising.csv' data = pd.read_csv(DATAPATH) print(data.head()) data.drop(['Unnamed: 0'], axis=...
eyadwin/Machine_Learning
regularization_lasso_regression.py
regularization_lasso_regression.py
py
1,396
python
en
code
0
github-code
6
26420683804
from pyspark.sql import * from pyspark.sql.functions import * from pyspark.sql.types import * from job.config.ConfigStore import * from job.udfs.UDFs import * from job.graph import * def pipeline(spark: SparkSession) -> None: df_Source_1 = Source_1(spark) df_FileOps_1 = FileOps_1(spark, df_Source_1) df_ran...
anshuman-91/GameDay11thMay
code/scala/pipelines/Reformat/code/job/pipeline.py
pipeline.py
py
1,189
python
en
code
0
github-code
6
17641215127
import numpy as np def MAPE(actual, forecast): return np.mean(np.abs((actual - forecast) / actual)) * 100 def double_exponential_smoothing(x, alpha=0.3, beta=0.5, l_zero=2, b_zero=0, mape=False): if not (0 <= alpha <= 1): raise ValueError("Invalid alpha") if not (0 <= beta <= 1): raise Val...
akiffbaba0/Double-Exponantial-Smoothing-to-Create-Forecasts
untitled1.py
untitled1.py
py
1,122
python
en
code
0
github-code
6
20665200266
import csv class NameDescriptor: """ Дескриптор для проверки и хранения ФИО студента. Проверяет, что каждая часть ФИО содержит только буквы и начинается с заглавной буквы. """ def __get__(self, instance, owner): return f'{instance._first_name} {instance._first_name} {instance._patronymic}'...
nadia3373/GeekBrains-Python-Developer
Diving into Python/s12/homework.py
homework.py
py
4,274
python
ru
code
1
github-code
6
17203277817
#Pasos a seguir: #1) Installar el repostorio de proyecto EELabs, con .env y credentials.json en \resources_folder\google, y el entorno conda #2) Pegar este script en dentro del repositorio \ #3) Ejecutar desde su ubicacion #IMPORTANTE no permite realizar actualizaciones de fecha, está pensado para una descarga úni...
mt4sd/EELabs_paper
Download_data/Photometer_data/Download_EELabs_photometers.py
Download_EELabs_photometers.py
py
11,585
python
en
code
0
github-code
6
26306025238
#!/usr/bin/python3 """Use reddit api to get info about subredit subscribers""" def number_of_subscribers(subreddit): """Return number of subscribers in subreddit given as argument""" import requests url = 'https://www.reddit.com/r/{}/about.json'.format(subreddit) headers = {'user-agent': 'andy'} ...
AndyMSP/holbertonschool-system_engineering-devops
0x16-api_advanced/0-subs.py
0-subs.py
py
496
python
en
code
0
github-code
6
21837055614
"""Parsing url to check its SEO and availability""" from datetime import date from bs4 import BeautifulSoup def get_page_data(response): """Check SEO functionality of url""" result = {'status_code': response.status_code} page = BeautifulSoup(response.text, 'html.parser') result['h1'] = page.h1.get_...
GunGalla/python-project-83
page_analyzer/parse_url.py
parse_url.py
py
628
python
en
code
0
github-code
6
655866557
from __future__ import annotations import contextlib import inspect import os import time import warnings from collections import OrderedDict from importlib import import_module from typing import Any, Callable, Dict, Optional, Union import numpy as np import torch import torch.cuda.amp as amp from tqdm import tqdm ...
constantinpape/torch-em
torch_em/trainer/default_trainer.py
default_trainer.py
py
29,151
python
en
code
42
github-code
6
14095456258
# Aditya Halder // @AdityaHalder import os import aiofiles import aiohttp import ffmpeg import requests from os import path from asyncio.queues import QueueEmpty from typing import Callable from pyrogram import Client, filters from pyrogram.types import Message, Voice, InlineKeyboardButton, InlineKeyboardMarkup from p...
ndika22/KaalMusic
plugins/vcbot.py
vcbot.py
py
8,167
python
en
code
0
github-code
6