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
70497094234
# coding=utf-8 import json import os from study.day12.file_path_manager import FilePathManager jsondata = ''' { "Uin":0, "UserName":"@c482d142bc698bc3971d9f8c26335c5c", "NickName":"小帅b", "HeadImgUrl":"/cgi-bin/mmwebwx-bin/webwxgeticon?seq=500080&username=@c482d142bc698bc3971d9f8c26335c5c&skey=@crypt_b0f5e5...
Youngfellows/PythonStudy
study/day12/02_json_str_to_dict.py
02_json_str_to_dict.py
py
1,833
python
en
code
0
github-code
50
26193919219
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('esg_leipzig_homepage_2015', '0001_initial'), ] operations = [ migrations.AddField( model_name='event', ...
ESG-Leipzig/Homepage-2015
esg_leipzig_homepage_2015/migrations/0002_event_css_class_name.py
0002_event_css_class_name.py
py
771
python
en
code
0
github-code
50
74960190875
from sklearn.preprocessing import MinMaxScaler import pandas as pd import numpy as np import torch def remove_max(x): x[x.argmax()] = np.median(x) print(x.argmax(), ":", x[x.argmax()], "=>", np.median(x)) return x def groupby_datapoint(df, gb='YYYYMMDD', target=...
CentralPark-gichan/AI_hub
수요예측 모델[한국타이어]/preprocessing.py
preprocessing.py
py
1,934
python
en
code
3
github-code
50
71498263194
def binarySearch(values, k): top = len(values)-1 bottom = 0 values.sort() print(values) found = False while(found != True): mid = (top+bottom) // 2 if(values[mid] == k): print(str(k) + " found at index: " + str(top)) found = True return True elif(values[mid] < k): bottom = mid + 1 elif(values...
timlaroche/PyCLRS
binarysearch.py
binarysearch.py
py
429
python
en
code
0
github-code
50
2348556791
import numpy as np from batch import Batch import scipy.io class Perceptron(): def __init__(self, X, Y): no_weights = X.shape[1] self.weights = np.random.uniform(0,size=[no_weights]) self.tresh = 0 self.X = X self.Y = Y self.l_rate = 0.025 self.train() def predict(self,X): Y = [] for x in X: Y...
NilusvanEdel/EnsembleMethods
decision_tree_constantin/perceptron.py
perceptron.py
py
1,202
python
en
code
2
github-code
50
18863045142
import pathlib import os import subprocess import json from functools import lru_cache class CuratedAppService: DIST_CURATED_APPS_FOLDER = "libboutique/curated_apps/dist" SCRIPT_CURATED_APPS_FOLDER = "libboutique/curated_apps/scripts" CURATED_APPS_APPLICATION_INDEX = "libboutique/curated_apps/dist/applications-en...
ubuntu-mate/python3-libboutique
libboutique/services/curated_app_service.py
curated_app_service.py
py
857
python
en
code
6
github-code
50
40232711881
"""__author__ = 唐宏进 """ if __name__ == '__main__': def fun1(): for x in range(10): return x # 0 < class 'int'> < class 'function' > print(fun1(),type(fun1()),type(fun1)) # 1.yield关键字 """ 只要函数中有yield关键字,那么这个函数就会变成一个生成器。 a.有yield的函数,在调用函数的时候不再是获取返回值, 而是产生一个生成器对象...
M0use7/python
day10-函数和文件操作/04-生成器.py
04-生成器.py
py
1,782
python
zh
code
0
github-code
50
7273497639
""" Schema aplicatiei: oferim o locatie si vrem sa vedem cate grade sunt acolo acum, si eventual alte date vrem sa trimitem aceste informatii o data pe ora la un cont de telegram """ # import the module import python_weather #pip install python-weather import asyncio import telegram #pip install python-telegram-bot - -...
constantinus345/sda_47_con
weather_app.py
weather_app.py
py
1,969
python
en
code
0
github-code
50
28402807345
import logging.config from random import choice # from conf import * logging.config.dictConfig(LOG_CONFIG) logger = logging.getLogger('Utils') def dict_to_format_string(dct: dict) -> str: """Переводит словарь в строку, которую можно отправить в виде сообщения""" res = '' for key, val in dct.items(): ...
kosumosuSpb/tgbot_sun_it_people
utils.py
utils.py
py
747
python
ru
code
0
github-code
50
24497008116
from django.conf.urls import url from . import views from django.conf.urls import include, url from django.conf import settings from django.conf.urls.static import static media_root = getattr(settings, 'MEDIA_ROOT', '/media') app_name = 'polls' urlpatterns = [ url(r'^$',views.test), url(r'^vocabtest/$', views...
ameyashirke13/Ld_detect
polls/urls.py
urls.py
py
1,053
python
en
code
0
github-code
50
18093083869
import spotipy from spotipy.oauth2 import SpotifyClientCredentials import time from graphviz import Graph import argparse g = Graph(format='png') parser = argparse.ArgumentParser() parser.add_argument("-p", "--primary", help="primary artist") parser.add_argument("-s", "--secondary", help="secondary artist") args = pa...
mi-ki-ri/six-step
app.py
app.py
py
2,693
python
en
code
0
github-code
50
12650428269
import pandas as pd from rdkit.Chem.Descriptors import fr_benzene # type: ignore def fr_benzene_1000_heavy_atoms_count(mol): return 1000 * fr_benzene(mol) / mol.GetNumHeavyAtoms() # From https://github.com/rinikerlab/molecular_time_series/blob/55eb420ab0319fbb18cc00fe62a872ac568ad7f5/ga_lib_3.py#L323 DEFAULT_...
datamol-io/splito
splito/simpd/descriptors.py
descriptors.py
py
1,034
python
en
code
5
github-code
50
1532402723
import argparse import os import glob import ot from sklearn.manifold import TSNE import matplotlib.patheffects as PathEffects import seaborn as sns import numpy from tqdm import tqdm import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.decomposition import PCA, TruncatedSVD from torch.u...
Fusang-Wang/mcr2
compare.py
compare.py
py
7,976
python
en
code
null
github-code
50
4353031890
def display_diagonal_elements(matrix): diagonal = [] non_diagonal = [] upper_diagonal = [] lower_diagonal = [] rows = len(matrix) cols = len(matrix[0]) for i in range(rows): for j in range(cols): if i == j: diagonal.append(matrix[i][j]) ...
SAIKRISHNA239/EZ-TS-2
diagional elements.py
diagional elements.py
py
1,127
python
en
code
0
github-code
50
10503617394
import pandas as pd import numpy as np import matplotlib.pyplot as plt #uncomment the plt.show() function to display the charts. df = pd.read_csv('test1.csv') null_val=df.isnull().sum(axis = 0) print(null_val) null_val.plot(kind="barh") plt.tight_layout() plt.show() df_tmp = df['What is your gender?'] all_male...
sfikouris/DM
task1/A1/plots.py
plots.py
py
1,089
python
en
code
0
github-code
50
11963146837
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: node = head while node and node.next: ...
duressa-feyissa/A2SV_Programming
0083-remove-duplicates-from-sorted-list/0083-remove-duplicates-from-sorted-list.py
0083-remove-duplicates-from-sorted-list.py
py
569
python
en
code
0
github-code
50
18207164077
#!/usr/bin/env python ## # ____ _ _ _ _ _ # | _ \ / \ | | | | | / \ # | |_) / _ \| | | | | / _ \ # | __/ ___ \ |_| | |___ / ___ \ # |_| /_/ \_\___/|_____/_/ \_\ # # # Personal # Artificial # Unintelligent # Life # Assistant # ## from paula.core import system f...
NorfairKing/PAULA-proof-of-concept
paula/sleep/sleep.py
sleep.py
py
901
python
en
code
5
github-code
50
7365275059
from models import Model from models.ajaxcomment import Ajaxcomment from models.comment import Comment from models.user import User class AjaxWeibo(Model): """ 微博类 """ def __init__(self, form, user_id=-1): super().__init__(form) self.content = form.get('content', '') ...
Jeffreve/socket_web
models/ajaxweibo.py
ajaxweibo.py
py
1,046
python
en
code
0
github-code
50
20390876489
""" Handles auth to Okta and returns SAML assertion """ # pylint: disable=C0325,R0912,C1801 # Incorporates flow auth code taken from https://github.com/Nike-Inc/gimme-aws-creds import sys import time import requests import re from codecs import decode from urllib.parse import parse_qs from urllib.parse import urlparse ...
seajoshc/dockerfiles
terrata/hacked_okta_auth.py
hacked_okta_auth.py
py
22,599
python
en
code
0
github-code
50
44566172798
import pytest import os.path try: import pyarrow as pa arrow_version = pa.__version__ except ImportError as msg: print('Failed to import pyarrow: {}'.format(msg)) pa = None arrow_version = None import numpy as np from librmm_cffi import librmm as rmm from cudf.comm.gpuarrow import GpuArrowReader...
yongsheng268/rapidsai-cudf
python/cudf/tests/test_sparse_df.py
test_sparse_df.py
py
2,576
python
en
code
0
github-code
50
26045700219
import sys import requests import json url = "http://k.episte.co/keywords/similars" def get_synonyms(infile, outfile, n): with open(infile, 'r') as jsonfile: data = json.load(jsonfile) output = {} for k in data['keywords']: r = requests.get(url, params={'positive': k, 'size': n}) ...
ESHackathon/keyword_synonyms
keywords.py
keywords.py
py
545
python
en
code
1
github-code
50
17047373269
import json import trustlab.lab.config as config import time from asgiref.sync import sync_to_async from rest_framework.renderers import JSONRenderer from trustlab.consumers.chunk_consumer import ChunkAsyncJsonWebsocketConsumer from trustlab.models import * from trustlab.serializers.scenario_serializer import ScenarioS...
zaman365/travos_trust_model
trustlab/consumers/lab_consumer.py
lab_consumer.py
py
13,452
python
en
code
0
github-code
50
20206520026
from view.commands.command import Command class SearchByID(Command): def __init__(self, presenter, view): """ Поиск заметки по идентификатору :param presenter: презентер :param view: представление """ super().__init__(presenter, view) super().set_description...
bunny-nun/git-advance-hw
view/commands/search/search_by_id.py
search_by_id.py
py
1,003
python
ru
code
0
github-code
50
70071774237
def main(): data = readFile(input().strip()) if data is None:return -1 lst = data["list"] n = data["n"] subs = getSubLists(lst,n) domins = [getDominant(sub) for sub in subs] result = getResult(domins,len(lst)) if writer("result.txt",result)==-1:return -1 def writer(out...
samitha278/UoM-Labs
Programming Assignment 2/uom 2015 pp2/2015-PA2-A3-1 - D.List/D.List.py
D.List.py
py
1,476
python
en
code
0
github-code
50
9658908858
import pathlib import diffhtml import flask from flask import request from markupsafe import Markup app = flask.Flask( 'Diff-HTML Demo', template_folder=pathlib.Path(__file__).parent.joinpath('templates'), ) DEFAULT_A = """ I am the very model of a modern Major-General, I've information vegetable, animal,...
uranusjr/diffhtml
demo/app.py
app.py
py
1,395
python
en
code
23
github-code
50
9604369230
"""Spezielle Tags für templates.""" from django.conf import settings from django.utils.module_loading import import_module from django import template from operator import itemgetter from Startseite.views import sysstatus from webpack_loader import utils from webpack_loader.exceptions import WebpackBundleLookupE...
german-in-austria/dioeDB
app/Startseite/templatetags/dioeTags.py
dioeTags.py
py
4,802
python
en
code
2
github-code
50
12632545151
from django.contrib import admin from django.urls import path, include from Insta.views import (PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, UserProfile, EditProfile, ExploreView, SignupView, addLike, addComment, toggleFollow) urlpatte...
clareli9/InstagramDemo
Insta/urls.py
urls.py
py
1,194
python
en
code
0
github-code
50
20877344117
import open3d as o3d from os.path import join, exists from os import makedirs, listdir import numpy as np import cv2 from utils import * from pcd2mesh import pcd2mesh from sklearn.neighbors import NearestNeighbors depth_nbrs = None rgb_nbrs = None def depth_to_colormapjet(depth): depth_color = depth....
Ribosome-rbx/Color_Map_Optimization
color_map_optimization.py
color_map_optimization.py
py
11,580
python
en
code
1
github-code
50
30413103525
# https://zhuanlan.zhihu.com/p/38163970 import numpy as np from matplotlib import pyplot as plt fig = plt.figure() #定义新的三维坐标轴 ax1 = plt.axes(projection='3d') x1 = np.arange(-5,5,0.5) x2 = np.arange(-5,5,0.5) x1, x2 = np.meshgrid(x1, x2) Z = x1**2 - 2*x1+1+x2**2+4*x2+4 g1 = 10-x1-10*x2 g2 = 10*x1-x2-10 ax1.plot_su...
shao1chuan/regression
机器学习/svm/kkt plot.py
kkt plot.py
py
572
python
en
code
1
github-code
50
9397338642
from torch.utils.data.dataset import Dataset import pandas as pd import numpy as np import torch import SimpleITK as sitk import random import sys sys.path.append('../') import utils as dmutils class ContinuousDataset(Dataset): """ Base class for a dataset for training on a continuous data stream """ ...
cirmuw/dynamicmemory
dataset/ContinuousDataset.py
ContinuousDataset.py
py
7,186
python
en
code
13
github-code
50
16198159058
import my_queue import time import random def simulate_line(till_show, max_time): pq = my_queue.Queue() tix_sold = [] for i in range(100): pq.enqueue("person" + str(i)) t_end = time.time() + till_show now = time.time() while now < t_end and not pq.is_empty(): now = time.time()...
98shimpei/python_test
ticket.py
ticket.py
py
527
python
en
code
0
github-code
50
28720445234
# import tkinter as tk # # root = tk.Tk() # root.title('Languages') # root.geometry('500x300') # # v = tk.IntVar() # v.set(1) # # # def show_val(): # print(v.get()) # # # languages = [(1, "JAVA"), (2, "Python"), (3, "c#"), (4, "Javascript")] # tk.Label(root, text="""Choose Language you like most""", ...
Yash-barot25/functions-timemodlues-ranges
TkinterHandsOn/Demo8.py
Demo8.py
py
1,199
python
en
code
0
github-code
50
17406595834
import re import pprint def get_new_loc(op, val, loc, acc): """updates accumulator and finds next line location""" if op == "jmp": loc += int(val) elif op == "acc": acc += int(val) loc += 1 else: loc += 1 return loc, acc def flip_op(op): "...
JackNelson/advent-of-code
2020/day8.py
day8.py
py
1,996
python
en
code
0
github-code
50
36856186258
import string import json import pickle import itertools import collections import numpy as np import math TRAIN_PATH = "data/yelp_reviews_train.json" TEST_PATH = "data/yelp_reviews_test.json" DEV_PATH = "data/yelp_reviews_dev.json" STOPWORD_LIST = "data/stopword.list" TOP_K_FOR_FEATURE = 2000 NUM_FEATURE = 5 def pr...
sharonwx54/TextMining
NetflixReview/data_preprocess.py
data_preprocess.py
py
6,863
python
en
code
0
github-code
50
22312550501
# -*- coding: utf-8 -*- from rest_framework import relations from rest_framework.test import APIRequestFactory from ralph.api.serializers import ReversedChoiceField from ralph.api.tests.api import ( Car, CarSerializer, CarViewSet, ManufacturerSerializer2, ManufacturerViewSet ) from ralph.api.viewse...
0x24bin/ralph
src/ralph/api/tests/test_viewsets.py
test_viewsets.py
py
2,558
python
en
code
null
github-code
50
17438254361
count=0 total=0 while True: n= int(input("Enter an integer (-1 to exit): ")) if n==-1: break count+=1 total+=n print(f"The sum of {count} number(s) is {total}.")
HiMAIayas/SIIT_Lab
GTS123 (Intro To ComProg)/lab7 (while loop)/lab7_9.py
lab7_9.py
py
190
python
en
code
0
github-code
50
30098709852
from lxml import etree class XPATH_CONTEXT (object): def __init__ (self, file_path, ns_prefix = None): self.doc = etree.parse (file_path) if ns_prefix: self.nsmap = {ns_prefix : self.doc.getroot().nsmap [None]} else: self.nsmap = None def attribute (self, xpath): attrib_list = self.node_list (xpath) ...
finnianr/Eiffel-Loop-safe
tool/python-support/eiffel_loop/xml/xpath.py
xpath.py
py
794
python
en
code
1
github-code
50
6351621109
import machine from time import sleep from ssd1306 import SSD1306_I2C class Pantalla: def __init__(self, pin1=5, pin2=4): '''Init display''' i2c = machine.I2C(scl=machine.Pin(pin1), sda=machine.Pin(pin2)) self.oled = SSD1306_I2C(128, 32, i2c) self.clear() def clear(self, color=...
katmai1/microesp
pantalla.py
pantalla.py
py
609
python
es
code
0
github-code
50
18243852987
budget = float(input()) statist = int(input()) clothes_number = float(input()) decor = 0.1 * budget if statist >= 150: clothes_price = clothes_number * 0.9 * statist else: clothes_price = clothes_number * statist outcome = clothes_price + decor needed = outcome - budget have = budget - outcome ...
gajev/programming_basics
Conditional_statements_lab/Godzilla_vs_kong.py
Godzilla_vs_kong.py
py
551
python
en
code
0
github-code
50
1169656225
import molsysmt as msm import os import shutil from pathlib import Path data_dir = Path('../../../data') # Purge files_to_be_purged = [ 'pdb/5zmz.pdb', 'mmtf/5zmz.mmtf', ] for filename in files_to_be_purged: filepath = Path(data_dir, filename) if os.path.isfile(filepath): os....
uibcdf/MolSysMT
molsysmt/systems/make/5zmz.py
5zmz.py
py
573
python
en
code
11
github-code
50
73735252956
# -*- coding: utf-8 -*- import scrapy from scrapy.selector import Selector from scrapy.http import Request from douban.items import HuanQiuChina, DaoMuBiJi class Douban(scrapy.Spider): name = 'huanqiu_china' start_urls = ['http://china.huanqiu.com/'] def parse(self, response): media_xpath = '/htm...
zhannglei/douban
douban/spiders/spider.py
spider.py
py
2,060
python
en
code
0
github-code
50
13139475765
__author__ = 'jwilliams' import os import lib #user defined vars path = 'L:\\cbt_video_published\\content\\'; lesson = 'EL-2-Current' code = 'FM' #setting code will check an entire product, set to 'HU-', 'IFR-', 'EG-' ect.. dir = path + lesson + "\\" os.chdir(dir) if code: result = lib.check_product...
GibsonStudio/pythonProjects
find_unused_in_html/main.py
main.py
py
479
python
en
code
0
github-code
50
12041162217
import sys import datetime windowName = "SpaceX Booster Use/Reuse Beholder" chartName = "SpaceX Core History" spaceXCreationDate = datetime.date(2002, 5, 6) colors = { 'EXPENDED': '#bbbbbb', 'HOP': '#d9ff5e', 'OCEAN': '#053fff', 'RTLS': '#06b700', 'ASDS': '#56b9f7', 'RUD': '#ff0000', 'REUSE':...
rinoldm/SBURB
data.py
data.py
py
2,314
python
en
code
7
github-code
50
2472224163
# Import the dependencies. import configparser from datetime import datetime from uuid import uuid4 from pathlib import Path import os # Import client library classes. from influxdb_client import Authorization, InfluxDBClient, Permission, PermissionResource, Point, WriteOptions from influxdb_client.client.authorizatio...
olegtemirbulatov/sensors
sensorslist/devices.py
devices.py
py
7,382
python
en
code
0
github-code
50
23999549107
bl_info = { "name": "Bizualizer", "description": "Create a simple vizualizer for audio", "author": "doakey3", "version": (1, 0, 3), "blender": (2, 7, 8), "wiki_url": "https://github.com/doakey3/Bizualizer", "tracker_url": "https://github.com/doakey3/Bizualizer/issues", "category": "Anima...
JT-a/blenderpython279
scripts/addons_extern/bizualizer.py
bizualizer.py
py
9,526
python
en
code
5
github-code
50
3723862412
import random import time class SF(): def regiun(self): '''生成身份证前六位''' #列表里面的都是一些地区的前六位号码 first_list = ['362402','362421','362422','362423','362424','362425','362426','362427','362428','362429','362430','362432','110100','110101','110102','110103','110104','110105','110106','110107','110108...
zguo0601/drg
common/sf_xm.py
sf_xm.py
py
3,303
python
en
code
0
github-code
50
15485978789
import json import pytest from gviz_data_table.table import Table valid_schema = ( {'id':'age', 'type':int, 'label':'Age'}, {'id':'name', 'type':str, 'label':'Name'} ) schema_missing_id = ( {'type':int}, {'name':'age', 'type':int} ) bob = (18, 'Bob') sally = (20, 'Sally') def test_conditional(): ...
GoogleCloudPlatform/hellodashboard
gviz_data_table/tests/test_table.py
test_table.py
py
3,832
python
en
code
11
github-code
50
23230063846
# -*- coding: utf-8 -*- """ Created on Tue Jul 16 15:16:29 2019 @author: Andy """ import matplotlib.pyplot as plt import numpy as np im_path = '..\\..\\EXPERIMENTS\\Italy\\data\\adsa\\20190701_1k2f_60c_volume_ref.bmp' area = 5.19/3.6 * 7.58/3.6 # mm^2 im = plt.imread(im_path) im_bw = im[:,:,0] == 0 plt.imshow(im_b...
andylitalo/g-adsa
src/util_clicking/compute_area.py
compute_area.py
py
852
python
en
code
0
github-code
50
27005882350
import pandas as pd import numpy as np import matplotlib.pyplot as plt import statsmodels.api as sm from numpy import exp from arch import arch_model from sklearn.metrics import mean_squared_error from statsmodels.tsa.arima.model import ARIMA from scipy import stats from datetime import datetime import warnin...
cwk0507/MSDM
MSDM5053/Project/Working/HSBC (2).py
HSBC (2).py
py
12,097
python
en
code
0
github-code
50
40991595889
""" Calculate the z-score """ __author__ = "Matt DeSaix" # libraries import numpy as np from WGSassign import zscore_cy def AD_summary(L, AD, i, n_threshold, single_read_threshold): AD_GL_dict = {} for s in np.arange(AD.shape[0]): # The key is the allele depth combination key = tuple([AD[s,2*i], AD[s,2*i...
mgdesaix/WGSassign
WGSassign/zscore.py
zscore.py
py
5,775
python
en
code
3
github-code
50
31612041978
# Program szyfruje i deszyfruje zahardkowana wiadomosc # Aes tszyfruje bloki co 16 bitow wiec musimy uzupelnic znaki (funkcja dopelnienie do16) from Crypto.Cipher import AES import codecs def dopelnienie_do16(zmienna): result = zmienna + (16-len(zmienna))*']' return result key = b"Sixteen byte key" cipher = ...
KBITSecurity/Notes
Programming/Python/UsingScripts/AES.py
AES.py
py
828
python
pl
code
0
github-code
50
40108172990
import FWCore.ParameterSet.Config as cms process = cms.Process("TEST") process.a = cms.ESSource("PoolDBESSource", DBParameters = cms.PSet( messageLevel = cms.untracked.int32(0), authenticationPath = cms.untracked.string('.') ), toGet = cms.VPSet(cms.PSet( record = cms.string('Pedest...
cms-sw/cmssw
CondCore/ESSources/test/python/print_ped_bylabel_cfg.py
print_ped_bylabel_cfg.py
py
1,051
python
en
code
985
github-code
50
72770423834
import itertools #given a list of numbers and a number k, #print out the sum of any two numbers in the list = k num = [10,15,3,7] mylst = list(itertools.combinations(num,r=2)) print (mylst) def to_k(lst,k): for num1, num2 in lst: if num1 +num2 == k: print (f" found: {num1} + {num2} = {k}") ...
JieCMarshall/mylearning
Data_Alg_Exer/iterations.py
iterations.py
py
432
python
en
code
0
github-code
50
73221936154
import os import torch import torch.nn as nn from transformers import Trainer from typing import Optional from transformers import AutoTokenizer from video_chatgpt.model import VideoChatGPTLlamaForCausalLM # from peft import PeftModel from video_chatgpt.constants import * def unwrap_model(model: nn.Module) -> nn.Modu...
Muhammad4hmed/VideoLlama
video_chatgpt/train/llava_trainer.py
llava_trainer.py
py
3,312
python
en
code
0
github-code
50
34749491204
def dask_setup(worker): import os from cachetools import LRUCache def get_classads(): fname = os.getenv("_CONDOR_JOB_AD") if not fname: return {} d = {} with open(fname) as fh: for line in fh: if "=" not in line: co...
mhl0116/cscbkg
cachepreload.py
cachepreload.py
py
875
python
en
code
0
github-code
50
5100305823
import os def split_file(file_path, output_dir, chunk_size=50*1024*1024): if not os.path.exists(output_dir): os.makedirs(output_dir) file_name = os.path.basename(file_path) file_size = os.path.getsize(file_path) num_chunks = (file_size // chunk_size) + 1 with open(file_path, 'rb') as infi...
benhmoore/reduce-llm
preprocessing/seperator.py
seperator.py
py
843
python
en
code
0
github-code
50
74368632154
#coding=utf-8 # 命令行命令, 批量tex转换 import sys import texf_topng import os def texf_topng_batch(filedir, den="200"): if not os.path.isdir(filedir): print("Need a dir with only tex files") return absfiledir = os.path.abspath(filedir) os.chdir(absfiledir) for root, dirs, files in os.walk(ab...
IshmaelHeathcliff/find-inline-formulae
ttpb.py
ttpb.py
py
744
python
en
code
0
github-code
50
38020566206
def busquedaLineal(lista,encontrar): isInList = False for elemento in lista: if elemento == encontrar: isInList = True return isInList listaEntrada = [2,12,34,5,11,59,4,3,1] valorEncontrar = int(input('ingrese un número : ')) listaEntrada.sort() print(busquedaLineal(listaEntrada, valorE...
weincoder/algoritmos202101
clases/algoritmos/busquedaLineal.py
busquedaLineal.py
py
747
python
es
code
1
github-code
50
19831926647
__author__ = 'Alessio' from project import app import logging.handlers from logging import FileHandler, Formatter from datetime import * class Logging(logging.FileHandler): @classmethod def __init__(self,user_connect_=None): self.user_connect = user_connect_ self.application = app\ ...
Sirbin/icollectweb
project/Loggin_Debug.py
Loggin_Debug.py
py
1,347
python
en
code
0
github-code
50
24975343920
import numpy as np class resultsStats: def __init__(self, collisionTable,lastHops ,numNodes,seedList,time,seed = 256,threshold = 0.9): self.threshold = threshold self.seed = seed self.time = sum(time[0:self.seed])/len(time[0:self.seed]) self.maxHop = max(lastHops[0:self.seed]) ...
BigDataLaboratory/MHSE
analyze_results/src/objects/stats.py
stats.py
py
5,525
python
en
code
4
github-code
50
33026470883
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Auteur : Aelaig COURNEZ - Flora GUES - Yann LAMBRECHTS - Romain SAFRAN # Librairies importee import numpy as np import pandas import struct import glob import os import time import datetime as dt from pyproj import Proj, transform #-----------------------...
cournez-ensta/Projet_Classification_2021
Scripts_Python/decode_and_save_EA400data_with_NME0.py
decode_and_save_EA400data_with_NME0.py
py
29,607
python
fr
code
0
github-code
50
22417742951
from alumina.config.userModel import AluminaUserModel from django.shortcuts import render from ATUJobPortal.config.authentication import Authentication from django.http.response import HttpResponseRedirect def aluminaApplicationController(request): auth = Authentication(request) msg = None errorMessage =...
tmsoft96/ATUJobPortal
alumina/controllers/aluminaApplicationController.py
aluminaApplicationController.py
py
1,402
python
en
code
1
github-code
50
15142269500
import cv2 as cv import numpy as np image_width = 480 image_height = 640 def sort_points(points): points = points.reshape((4, 2)) points_new = np.zeros((4, 1, 2), dtype=np.int32) _sum = points.sum(1) _diff = np.diff(points, axis=1) points_new[0] = points[np.argmin(_sum)] points_new[3] = poin...
chaos-6666/cv-projects
doc_scan.py
doc_scan.py
py
2,298
python
en
code
0
github-code
50
25953188511
import keras from keras.models import load_model from agent.agent import Agent from functions import * import sys if len(sys.argv) != 4: print('Usage: python evaluate.py [stock] [model] [window_size]') exit() stock_name, model_name, window_size = sys.argv[1], sys.argv[2], int(sys.argv[3]) agent = Agent(wind...
goho302jo03/nn_model
q-trader/evaluate.py
evaluate.py
py
1,327
python
en
code
0
github-code
50
8147050964
from PIL import Image, ImageDraw import math import random import numpy as np import matplotlib.pyplot as plt random_seed = 123456789 random.seed(random_seed) def to_rgb(image): rgb = image.convert("RGB") width = image.width height = image.height matrix = np.zeros((width, height, 3)) for x in range(width): for...
HyTruongSon/Dirichlet_Process
ising_gibbs.py
ising_gibbs.py
py
2,661
python
en
code
0
github-code
50
28612570847
import os from tkinter import * import tkinter.messagebox as tkMessageBox from idlelib.container import Container, TabbedContainer, ProxyContainer class FileList: # N.B. this import overridden in PyShellFileList. from idlelib.EditorWindow import EditorWindow def __init__(self, root): self.root =...
roseman/idle
FileList.py
FileList.py
py
7,409
python
en
code
48
github-code
50
36603213242
import unittest from unittest import mock import pandas as pd from exabel_data_sdk.client.api.data_classes.entity import Entity from exabel_data_sdk.client.api.data_classes.entity_type import EntityType from exabel_data_sdk.client.api.entity_api import EntityApi from exabel_data_sdk.client.client_config import Client...
Exabel/python-sdk
exabel_data_sdk/tests/util/test_resource_name_normalization.py
test_resource_name_normalization.py
py
16,285
python
en
code
5
github-code
50
6994254119
import numpy as np import pandas as pd from sklearn import linear_model class PolynomialRegression: def __init__(self,degree, Data): self.degree = degree self.regr = linear_model.LinearRegression() self.dataset = pd.read_csv(Data, sep=" ") self.y = self.dataset.iloc[:,-1:].values ...
JuanBC9/UnityCar-AI-
Assets/Scripts/PolynomialRegression.py
PolynomialRegression.py
py
1,521
python
en
code
0
github-code
50
39980500210
import cv2 as cv import os import numpy as np import matplotlib.pyplot as plt import sys from pathlib import Path from src.body_measure import draw_slice_data from src.util import preprocess_image import argparse if __name__ == '__main__': ap = argparse.ArgumentParser() ap.add_argument("-f", "--front_img", re...
amitbend/body_measure
src/viz_measurement_result.py
viz_measurement_result.py
py
2,863
python
en
code
3
github-code
50
1465408384
import heapq import sys input = sys.stdin.readline print = sys.stdout.write v, e = map(int, input().split()) a = int(input()) graph = {i: [] for i in range(1, v + 1)} for _ in range(e): i, j, w = map(int, input().split()) graph[i].append((j, w)) dis = {k: float('inf') for k in graph.keys()} dis[a] = 0 hq =...
kkg5/algorithm
step/shortest_path/1753_최단경로.py
1753_최단경로.py
py
723
python
en
code
0
github-code
50
74937154396
from django.urls import path, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'tests', views.TestView) urlpatterns = [ path('', views.index, name='index'), path('random', views.random, name='random'), path('router/', include(router.urls)) ]
filipweidemann/testing-heroku-deployment
blog/urls.py
urls.py
py
320
python
en
code
0
github-code
50
40237107262
from ..parse_json import parse from pathlib import Path def more_about_health(make_intimate_comfortable, user_dont_know): msg_id = "about_health.0" path = ( Path("consultation_bot/bot/user_dont_know/data/") / "data_more_about_health.json" ) DEFAULT_ACTIONS = { "default-1": (m...
mary-zh555/Consultation_bot
consultation_bot/bot/user_dont_know/more_about_health.py
more_about_health.py
py
484
python
en
code
0
github-code
50
17553389056
class Points: def __init__(self,x,y): self.x = x self.y = y def getDistance(self,other): #两点之间距离公式 return ((self.x - other.x) ** 2+(self.y - other.y) ** 2)**0.5 def type_triangle(self,p2,p3): self_p2 = self.getDistance(p2) self_p3 = self.getDistance(p3) ...
HongwuQz/PythonHmwk
BigData/6.2/BigData6.2.py
BigData6.2.py
py
1,294
python
en
code
1
github-code
50
40699599039
curr = 0 maxcals = 0 data = [] def process_input(line): global maxcals, curr, data if len(line) >0: curr += int(line) else: data.append(curr) curr = 0 def load_data(filename): global data, curr with open (filename, 'r') as file: lines = file.readlines() ...
likwidoxigen/PythonExercises
AdventOfCode/2022/01/01.py
01.py
py
716
python
en
code
0
github-code
50
10261374824
from tkinter import* from timeit import default_timer fenêtre = Tk() can=Canvas(fenêtre,bg="white",height=100,width=150) can.pack() def chronomètre(): now = default_timer() - début minutes,secondes = divmod (now, 60) heures,minutes = divmod(minutes,60) str_time = "%d:%02d:%02d"%(heures,minutes,seconde...
pauld01/amazing-maze
src/chronometre-master/chrono fonctionnel avec simple fenêtre graphique.py
chrono fonctionnel avec simple fenêtre graphique.py
py
512
python
fr
code
0
github-code
50
15327825624
# -*- coding: utf-8 -*- """ Created on Wed Dec 11 15:27:44 2019 @author: KAMPFF-LAB-ANALYSIS3 """ import numpy as np import matplotlib.pyplot as plt import random import seaborn as sns #from filters import * import os #os.sys.path.append('/home/kampff/Repos/Pac-Rat/libraries') os.sys.path.append('D:/Repos/Pac-Rat/lib...
kampff-lab/Pac-Rat
scripts/ephys/MUA_heatmap.py
MUA_heatmap.py
py
7,674
python
en
code
0
github-code
50
1156440255
from molsysmt._private.exceptions import * from molsysmt.api_forms.common_gets import * import numpy as np from molsysmt import puw from molsysmt.native.molecular_system import molecular_system_components form_name='molsysmt.TrajectoryDict' from_type='class' is_form={ } info=["",""] has = molecular_system_component...
uibcdf/MolSysMT
attic/api_forms/api_molsysmt_TrajectoryDict.py
api_molsysmt_TrajectoryDict.py
py
13,530
python
en
code
11
github-code
50
19317832681
from sklearn.metrics import auc, roc_curve import matplotlib.pyplot as plt def plot_roc_auc(y_true, y_pred, savepath=None): if type(y_true) in (list, tuple) and type(y_pred) in (list, tuple): assert len(y_true) == len(y_pred) if len(y_true) > 5: raise ValueError('Up to 5 lines supporte...
mmikolajczak/recommendation_system_hetrec2011_movielens
recommendations_system/experiments_scripts/plotting.py
plotting.py
py
1,130
python
en
code
5
github-code
50
73752449436
from django.urls import path, include from .views import CategoryList, CategoryDetail, EventList, EventDetail, SeatList, SeatDetail, SeatCategoryList, SeatCategoryDetail, EventImageList, EventImageDetail, EventListForCategory from apps.accounts.signals import create_category_api, create_event_api from . import views a...
FakirHerif/react-django
backend/server/apps/accounts/urls.py
urls.py
py
1,557
python
en
code
2
github-code
50
38239478292
## 1. The Range ## import pandas as pd houses = pd.read_table('AmesHousing_1.txt') def range(a): return ( max(a) - min(a) ) k = houses['Yr Sold'].value_counts().reset_index() range_by_year ={} for i in k['index']: hou =houses[houses['Yr Sold']==i] range_by_year[i] = range(hou['SalePrice']) one = ...
nemkothari/Statistics-Intermediate
Measures of Variability-308.py
Measures of Variability-308.py
py
5,124
python
en
code
0
github-code
50
38585374633
import os os.environ['KMP_DUPLICATE_LIB_OK'] = 'True' import datetime from common.buffer import PrioritizedBuffer import torch.nn as nn import torch.autograd as autograd import torch.nn.functional as F import random import gym import numpy as np from tqdm import tqdm import torch import matplotlib.pyplot as plt impo...
cgl-dong/my_rl
hand/PER_DQN2.py
PER_DQN2.py
py
5,999
python
en
code
0
github-code
50
28371073407
"""Processing environment to store, retrieve, and add aliases.""" from __future__ import annotations import os.path Aliases: dict[str, list[str]] = {} alias_relative_file: str = "../../config/alias.txt" def alias_exists_for(name: str): return name in Aliases.keys() def command_for_alias(name: str): return A...
AD417/LEDControl
internals/command/Alias.py
Alias.py
py
1,940
python
en
code
0
github-code
50
40509752290
class Solution: def maxProfit(self, prices: list[int]) -> int: left = 0 right = 1 difference = 0 while right < len(prices): currentProfit = prices[right] - prices[left] if prices[left] < prices[right]: difference = max(currentProfit, difference...
Yahoo002/pythonDSA
bestTimeToBuyAndSellStock.py
bestTimeToBuyAndSellStock.py
py
513
python
en
code
0
github-code
50
42243745118
import sys from itertools import count from collections import defaultdict lines = sys.stdin.readlines() target = lines.pop(-1).strip() lines.pop(-1) rep = defaultdict(list) rev = defaultdict(list) for line in lines: f, t = line.strip().split(' => ') rep[f].append(t) rev[t].append(f) dis = set() def appl...
ShuP1/AoC
src/2015/19.py
19.py
py
1,103
python
en
code
0
github-code
50
27991925985
import numpy as np import tensorflow.compat.v2 as tf from tensorflow.compat.v2.experimental import dtensor from tf_keras import backend from tf_keras.dtensor import integration_test_utils from tf_keras.dtensor import layout_map as layout_map_lib from tf_keras.dtensor import test_util from tf_keras.optimizers import ad...
keras-team/tf-keras
tf_keras/dtensor/mnist_model_test.py
mnist_model_test.py
py
3,216
python
en
code
28
github-code
50
38383059729
import tensorflow as tf import tensorflow_hub as hub model_url = "https://tfhub.dev/tensorflow/efficientnet/lite0/feature-vector/2" IMAGE_SHAPE = (224, 224) layer = hub.KerasLayer(model_url, input_shape=IMAGE_SHAPE+(3,)) model = tf.keras.Sequential([layer]) import numpy as np from tensorflow.keras.preprocessing import...
RunhaiLin/jik
change.py
change.py
py
1,394
python
en
code
0
github-code
50
36114219663
import mindspore.dataset.vision.c_transforms as CV import mindspore.dataset.transforms.c_transforms as C import mindspore.common.dtype as mstype import mindspore.dataset as ds def create_dataset(data_path, batch_size=32): """ 数据处理 Args: dataset_path (str): 数据路径 batch_size (int): 批量大小 ...
littlemou/MindSpore_graduate_pratice
Test5/preprocess.py
preprocess.py
py
1,248
python
en
code
1
github-code
50
20538425560
import logging import _lcms2 import numpy as np from typing import Union, Any, Tuple from . import util_lcms # ------------------------ # setup logger # ------------------------ log = logging.getLogger(__name__) def useDebugMode(): """ sets logging level and creates a stream handler to show full debuggi...
cimatosa/pyColConv
pyColConv/pyColConv.py
pyColConv.py
py
10,541
python
en
code
0
github-code
50
875036738
import collections class ReorganizeString: """ Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same. If possible, output any possible result. If not possible, return the empty string. Example 1: Input: S = "aab" ...
DmitryPukhov/pyquiz
pyquiz/leetcode/ReorganizeString.py
ReorganizeString.py
py
899
python
en
code
0
github-code
50
9633133356
# -*- coding: utf-8 -*- """ Created on Thu May 24 10:28:51 2018 @author: Administrator 将SVG接线图加入通讯中断的状态 """ import xml.dom.minidom doc = xml.dom.minidom.parse('D:/35kV主接线图.svg') def setNewNode(newNode): for nc in newNode.childNodes: if nc.nodeType == nc.ELEMENT_NODE: if nc.nodeName == 'g':...
w8s8y8/pytools
status.py
status.py
py
2,079
python
en
code
0
github-code
50
22502408130
import geopandas as gpd import matplotlib.pyplot as plt from shapely.geometry import MultiPolygon, Point, Polygon import datetime import pandas as pd import random NON_WILDFIRE_POINTS_TO_ADD = 3000 def clean_data(gdf: gpd.GeoDataFrame) -> gpd.GeoDataFrame: # Remove any incomplete rows df = gdf.d...
danielmtro/ThesisBackup
DataCleaning/datacleaning.py
datacleaning.py
py
4,826
python
en
code
0
github-code
50
41296300253
import sys from os.path import abspath, dirname import numpy as np import open3d as o3d parent_dir = dirname(dirname(dirname(abspath(__file__)))) # type: ignore if parent_dir not in sys.path: # type: ignore sys.path.append(parent_dir) print(parent_dir) from pcd_algorithm.utils.merge import merge def visualiz...
sakamo1112/pcd_algorithm
pcd_algorithm/clustering/k_means.py
k_means.py
py
2,600
python
en
code
0
github-code
50
37770993352
import requests import json apiKey = '37134fea34fc11b5bdc5e82ad894109b3d141674' url = 'https://api.github.com/repos/datarepresentationstudent/aPrivateOne' filename = 'repo_out.json' file = open("pmg_test.txt", 'r') #json.dump(repoJSON, file, indent=4) response = requests.put(url, file, auth=('token',apiKey)) #respon...
Pmcg1/dataRepresentation
week06/lab06.02_challenge02.py
lab06.02_challenge02.py
py
450
python
en
code
0
github-code
50
70732891675
import os from os import makedirs from os.path import isdir, join, exists import fcntl from time import sleep, strftime import sys import datetime VERBOSE = False DEBUG_MODE = False ROOT_DIR = '/home/gb/logger/bdata' if DEBUG_MODE: ROOT_DIR = '.' class SoundLogger: def __init__(self, dev_card = 1, sampling_ra...
groundbird/sound_logger
sound_logger.py
sound_logger.py
py
3,242
python
en
code
0
github-code
50
6528910941
from userpreferences.models import UserPreference from .models import Income, IncomeStream import datetime def get_user_currency_symbol(request_user): # get user currency try: user_preferences_object = UserPreference.objects.get(user=request_user) except UserPreference.DoesNotExist: user_pr...
melvinloh/expenses_project
expenses_project/income/utils.py
utils.py
py
1,849
python
en
code
0
github-code
50
37737354939
#!/usr/bin/env python # -*- coding: utf-8 -*- # author: Olivier Noguès import logging from ares.Lib.connectors.files import AresFile class FilePdf(AresFile.AresFile): """ :category: Ares File :rubric: PY :type: class :label: Connector to read a bespoke PDF file. :dsc: Connector t...
jeamick/ares-visual
Lib/connectors/files/AresFilePdf.py
AresFilePdf.py
py
1,645
python
en
code
0
github-code
50
39921209805
#!C:\Python32\python.exe __author__ = 'jonathan' import cgi from dbsql import * import json print("Content-Type: application/json\n") form = cgi.FieldStorage() if "id" in form and len(form["id"].value) == 32 and not form["id"].value.count(' '): q = "SELECT json FROM stored_matches_json WHERE hashed=%(hash)s" ...
sbilstein/twitterjelly
cgi-bin/GetStoredResult.py
GetStoredResult.py
py
862
python
en
code
2
github-code
50
21644429821
# %%-- To do: """ The sets I have done: set 11 both n and p. set 10 both n and p. set 01 both n and p. set 00 both n (with k) and p. """ # %%- # %%-- Imports import pandas as pd import numpy as np import seaborn as sn from sklearn.model_selection import train_test_split, GridSearchCV import matplotlib.pyplot as plt f...
sijinwnag/SRH_sklearn_playwithdata
2_levels_problem/mode2/Et_regression/set11/set11.py
set11.py
py
20,159
python
en
code
0
github-code
50
5880174517
def chars_to_bools(chars): # assert all([c == "0" or c == "1" for c in chars]) return [c == "1" for c in chars] + [False] * (6 - len(chars)) def bools_to_chars(bools): return ["1" if b else "0" for b in bools] def draw_outline(term, start_coords, end_coords, title=None, color=None): if color == None...
aselker/ld48_computer_1
nano_editor.py
nano_editor.py
py
6,311
python
en
code
5
github-code
50
34567644548
__author__ = 'Administrator' # coding: utf-8 import adbtools import os import datetime import time def command(): with open('E:/1/monkey.txt') as file: data = file.readlines() str = ''.join(data) file.close() print(str) os.popen(str) def write_result(): format_time = datetime.d...
luoxin0420/study
monkey.py
monkey.py
py
624
python
en
code
0
github-code
50