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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
5852926291 | # Pandas package
import pandas as pd
# brics = pd.read_csv("C:/Users/WangZhe/brics.csv")
brics = pd.read_csv("C:/Users/WangZhe/brics.csv", index_col = 0)
# choose and create columns and rows
brics["country"]
brics.country
brics["in_asia"] = [False, True, True, True, False]
brics["density"] = brics["popul... | wzisgood1/Python_collected_examples | 6.2.py | 6.2.py | py | 780 | python | en | code | 2 | github-code | 1 |
43959272703 | import pandas as pd
import streamlit as st
import plotly.express as px
st.set_page_config(page_title="Tickets Dashboard 📊 ", layout="wide" )
df = pd.read_csv('customer_support_tickets.csv')
print(df)
st.title("📊 Tickets Dashboard")
st.markdown("##")
st.sidebar.header("Please Filter Here:")
# ticket_ID = st.... | asmaakhaledd/-Automatic-Ticket-Classification-Tool | app.py | app.py | py | 1,749 | python | en | code | 0 | github-code | 1 |
75090764834 | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'webapp.views.index', name='index'),
url(r'^province/(\w+)/$',... | RHoK-Bilbao/desahucios | website/website/urls.py | urls.py | py | 1,492 | python | en | code | 7 | github-code | 1 |
9362838462 | #coding:utf-8
"""
Description: separate speech from mixed signal of music and speech
Date: 2018.6.3
Reference: const.py, DoExperiment.py and util.py
by wuyiming
in UNet-VocalSeparation-Chainer
<https://github.com/Xiao-Ming/UNet-VocalSeparation-Chainer>
"""
import argparse
import ... | shun60s/Blind-Speech-Separation | separate.py | separate.py | py | 4,185 | python | ja | code | 3 | github-code | 1 |
35829829166 | ## Q3. 2개의 숫자를 입력 그 사이의 짝수만 출력하고 중앙값을 출력하는 함수
## 중앙값이 홀 수이면 출력하지 않음
def find_even_number(n, m):
numbers = [i for i in range(n, m+1)]
middle = numbers[int(len(numbers)/2)]
if middle%2 == 0:
print("중앙값 : " , middle)
list = []
for i in numbers:
if i%2 == 0:
... | somsomp/PY4E_mission | week 3/3.py | 3.py | py | 559 | python | ko | code | 0 | github-code | 1 |
34977561674 | import numpy as np
import cv2
img = cv2.imread('/Users/huojiaxi/Desktop/googlelogo_color_272x92dp.png')
vert = [70, 110, 40] # RGB de la couleur végétale, il est nécessaire de la régler lors que la première figure sera générée
diff_rouge = 60
diff_vert = 40
diff_bleu = 30
boundaries = [([vert[2]-diff_bleu, vert[1... | HUOJIAXI/PROJETDRONE1920 | TraitementDImage/image.py | image.py | py | 853 | python | fr | code | 2 | github-code | 1 |
13191873056 | import tkinter
root = tkinter.Tk()
root.geometry('400x200+100+200')
l1 = tkinter.Label(root, text="Number Addition Program",font="Arial 22 bold")
l2 = tkinter.Label(root, text="First No:")
l3 = tkinter.Label(root, text="Second No:")
e1 = tkinter.Entry(root)
e2 = tkinter.Entry(root)
b1 = tkinter.Button(root, text="Add... | sunakshisharma/PythonProject | pythongui/GuiApp8.py | GuiApp8.py | py | 771 | python | en | code | 0 | github-code | 1 |
24649387466 | # -*- coding: utf-8 -*-
"""
Created on Mon May 28 17:25:39 2018
@author: Administrator
"""
import basicSpider
url = "http://www.sina.com.cn/"
headers = [("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36")]
proxy = {"http":"182... | smakerm/list | note/step4/爬虫笔记/17. Crawler02/day01/testBasicSpider.py | testBasicSpider.py | py | 454 | python | en | code | 0 | github-code | 1 |
43619202901 | a = {1:1, 2:2, 3:1, 4:34}
#b = {}
c=[]
count = {}
for i in a.values():
##print(i)
count.setdefault(i, 0)
count[i] = count[i]+1
#print(count)
#i = 0
for k,v in count.items():
if v == 1:
#i = i+1
#b.update({i:k})
c.append(k)
print(c)
#print(b)
#for i in b.values():
# print(i, ... | abidhafiz1294/PRACTICE | Python Project/first_program/Unique values in Dictionary.py | Unique values in Dictionary.py | py | 329 | python | en | code | 0 | github-code | 1 |
41724455675 | from keras import applications
from keras.preprocessing.image import ImageDataGenerator
from keras import Sequential, Model, optimizers
from keras.layers import Dropout, Flatten, Dense, Input
import os
# Run with GPU
import tensorflow as tf
config = tf.compat.v1.ConfigProto( device_count = {'GPU': 1 , 'CPU': 56} )
s... | lucas2298/midtermIMP | vgg16.py | vgg16.py | py | 2,816 | python | en | code | 0 | github-code | 1 |
17599916978 | import threading
import time
from datetime import datetime
class StartOverException(Exception):
"""Raise to restart the tails thread loop"""
pass
class FluffyTailsThread(threading.Thread):
def __init__(self, bot_object, bot):
threading.Thread.__init__(self)
# self.new_reminder = threadin... | Petricpwnz/NyAI | modules/fluffy_tails_thread.py | fluffy_tails_thread.py | py | 2,234 | python | en | code | 1 | github-code | 1 |
33100415287 | """
Remove the nth node from the end of a linked list.
"""
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def removeNthFromEnd(head, n):
# Create a dummy node to handle the case where the head needs to be removed
dummy = ListNode(0)
dummy.next = ... | akshay-pandita/akshay-pandita | PycharmProjects/Automatio/Problems/medium/remove_nth_node_from_end.py | remove_nth_node_from_end.py | py | 760 | python | en | code | 0 | github-code | 1 |
70880919075 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
# 传入URL
r = requests.get('https://www.csdn.net/')
# 解析URL
soup = BeautifulSoup(r.text, 'html.parser')
content_list = soup.find_all('div', attrs={'class': 'title'})
comment_count = soup.find_all('dl', attrs={'class': 'list_u... | CHOPPERJJ/Python | LearningProject/PythonBasics/Crawler.py | Crawler.py | py | 397 | python | en | code | 0 | github-code | 1 |
72068568354 | import sys
import copy
import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
sys.path.append('../..')
import modules.commons as commons
import modules.... | justinjohn0306/so-vits-svc-4.0-v2 | models.py | models.py | py | 39,167 | python | en | code | 497 | github-code | 1 |
72552120675 | class Node:
def __init__(self, data):
self.data = data
self.right_child = None
self.left_child = None
self.height = 0
class AVL:
def __init__(self):
self.root = None
def insert(self, data):
self.root = self.insert_node(data, self.root)
def traverse(sel... | arjun289/eopi | data_structures/trees/binary_search_trees/avl_tree.py | avl_tree.py | py | 6,305 | python | en | code | 0 | github-code | 1 |
41244608097 | import logging
import socket
import threading
from src import (
parse_args,
TestObject,
TestCase,
TEST_CASE_TO_TEST,
OBJECTS,
)
def perform_calculations(test_object, test_case):
test = TEST_CASE_TO_TEST[test_case]()
test.run(OBJECTS[TestObject(test_object)])
return str(test.report)
... | miska924/Serialization | src/server/__init__.py | __init__.py | py | 2,226 | python | en | code | 0 | github-code | 1 |
8476706656 | from flask import Flask, jsonify, request
import json
import numpy as np
from datetime import datetime
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def filtering_api():
if request.method == 'GET':
with open('data.txt', 'r') as f:
data = f.read().splitlines()
data = [j... | elahe-mohammadi/bounding-box-filtering | app.py | app.py | py | 1,534 | python | en | code | 0 | github-code | 1 |
35871335694 | from multiprocessing.managers import BaseManager
import random
import time
import queue
BaseManager.register('get_task_queue')
BaseManager.register('get_result_queue')
server_addr = '127.0.0.1'
manager = BaseManager(address=(server_addr,5000),authkey=b'abc')
manager.connect()
task = manager.get_task_queue()
result ... | PETERMAOSX/Pycharm_Code | Demo_one/page_1/t13.py | t13.py | py | 612 | python | en | code | 0 | github-code | 1 |
5951517574 | import openai
openai.api_key = "Fill your API key here"
days = 4
place = "Paris"
prompt = f"Make me a travel plan for {days} days to {place}"
response = openai.Completion.create(
engine="text-davinci-002",
prompt=prompt,
max_tokens=4000,
temperature=0.6,
n=1,
stop=None
)
print(str(response[... | snagnik-coder/Travel-Planner | main.py | main.py | py | 344 | python | en | code | 0 | github-code | 1 |
32731325683 | """
Driver for PES-Learn
"""
import timeit
import sys
import os
import json
from six.moves import input
from collections import OrderedDict
import peslearn
import numpy as np
import pandas as pd
with open('input.dat', 'r') as f:
input_string = f.read()
input_obj = peslearn.InputProcessor(input_string)
if input_o... | CCQC/PES-Learn | peslearn/driver.py | driver.py | py | 1,993 | python | en | code | 57 | github-code | 1 |
264564360 | #This file will need to use the DataManager,FlightSearch, FlightData, NotificationManager classes to achieve the program requirements.
from data_manager import DataManager
from flight_search import FlightSearch
from flight_data import FlightData
from notification_manager import NotificationManager
from users import Use... | hollymartiniosos/100dayspython | 39. Flight deal finder/main.py | main.py | py | 3,228 | python | en | code | 0 | github-code | 1 |
72358637153 | # -*- coding: utf-8 -*-
from flask import Flask, render_template, request
from webapp.forms import db, ModelPosts, ModelComments, ModelTags
from read_db import *
# импорт семантического анализа
from semantic import semantic_res
def f_toxic_vals(v0, v1, v2):
# processing results function for provide into web-page... | Leonid-SV/ToxicStackOverflow | webapp/__init__.py | __init__.py | py | 3,469 | python | ru | code | 0 | github-code | 1 |
37657073356 | import os
import copy
import logging
import numpy as np
import json_tricks
from gym import spaces
import nni
from nni.tuner import Tuner
from nni.utils import OptimizeMode, extract_scalar_reward
from .model import Model
from .util import set_global_seeds
from .policy import build_lstm_policy
logger = logging.getLog... | danijimmy19/nni | src/sdk/pynni/nni/ppo_tuner/ppo_tuner.py | ppo_tuner.py | py | 23,509 | python | en | code | null | github-code | 1 |
72417026914 | from aiogram import Bot, Dispatcher,executor,types
from token_auth import token
from script import get_user_info,get_user_subs,get_friends_user,get_user_photo
import json
def telegram_bot(token):
bot = Bot(token=token,parse_mode=types.ParseMode.HTML)
dp = Dispatcher(bot=bot)
#@dp.message_handl... | antifalcone/myhobby | searchingforwatching.py | searchingforwatching.py | py | 4,285 | python | ru | code | 1 | github-code | 1 |
74345472033 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import urllib.request
url="http://google.cn/"
response=urllib.request.urlopen(url)
page=response.read()
#print(page)
f = open('index.html', "wb+")
f.write(page) #用readlines()方法写入文件
f.close() | linjianghe/test | python/url.py | url.py | py | 269 | python | en | code | 0 | github-code | 1 |
60613852 | '''
Created on Jul 17, 2014
@author: c3h3
'''
class EdxUrls(object):
edx_site_dict = {"edx":"https://courses.edx.org",
"stanford":"https://class.stanford.edu",
}
def __init__(self, edx_site="edx"):
assert edx_site in self.edx_site_dict.keys()
... | c3h3/mooqr-crawler | mooqr_crawler/edx/urls.py | urls.py | py | 492 | python | en | code | 0 | github-code | 1 |
22540069696 | import numpy as np
import matplotlib.pyplot as plt
# Color
# https://matplotlib.org/stable/gallery/color/named_colors.html
#https://www.yutaka-note.com/entry/matplotlib_subplots
x = np.linspace(-3,3)
y1 = x**2
y2 = x
fig, ax = plt.subplots(1, 2, squeeze=False,figsize=(8,3),tight_layout=True)
ax[0,0].plot(x, y1,"Ste... | ken-100/Investment_Python | Basic/Chart/Subplots.py | Subplots.py | py | 663 | python | en | code | 0 | github-code | 1 |
1155368532 | import sqlite3, datetime
from EmployeeEdit import randserial
from Login import clear
from Inventory import unique
conn = sqlite3.connect('MarksHardware.db')
cursor = conn.cursor()
def uniquesales(ID): #ensures unique Ids
for id in conn.execute("SELECT SALESID FROM SALES"):
if id[0] == ID:
return False
... | m247murray/MacroHard | Sales.py | Sales.py | py | 3,169 | python | en | code | 0 | github-code | 1 |
5800264250 | with open("2021/03/input.txt", "r") as f:
binaryTable = []
for line in f:
l = [*line]
l.pop()
binaryTable.append(l)
def rating(table, i, type):
bitAtIndex = []
output = []
for j in table:
bitAtIndex.append(j[i])
for j in table:
if type == "oxy... | Inzaguiz/Advent-of-Code | 2021/03/binDiag.py | binDiag.py | py | 1,427 | python | en | code | 0 | github-code | 1 |
33821375551 | from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
import PyPDF2
import os
files=Tk()
files.title('Easy Files')
files.geometry(f'400x600')
files.resizable(False,False)
# Add a frame to set the size of the window
frame= Frame(files, relief= 'sunken')
frame.pack(fill= BOTH, e... | irfanrasheedkc/pdf_to_doc | easyfiles.py | easyfiles.py | py | 3,409 | python | en | code | 0 | github-code | 1 |
22408996664 | import sys
from collections import deque
input = sys.stdin.readline
# bfs와 이분탐색 활용문제
# 처음에는 다리무게를 활용하여 도착지에 갈 수 있는 최소 무게를 탐색
# 나중에는 이분탐색을 활용해 도달할 수 있는 무게의 최대값을 탐색
def bfs(w):
q = deque()
q.append(S)
visited = [0] * (N+1)
visited[S] = 1
while q:
A = q.popleft()
for B, C in G[A]:
... | kky0455/Beakjoon_code | rank/gold/1939.py | 1939.py | py | 999 | python | ko | code | 0 | github-code | 1 |
29243659893 | def nodeDepthsRecursive(root, depth = 0):
if root is None:
return 0
return depth + nodeDepthsRecursive(root.left, depth + 1) + nodeDepthsRecursive(root.right, depth + 1)
def nodeDepthsIterative(root):
# Write your code here.
answer = 0
stack = [{"node": root, "depth": 0}]
while len(stack) > 0:
temp = stac... | jinlee487/Algorithm | src/algoexpert/easy/NodeDepth/solution.py | solution.py | py | 721 | python | en | code | 0 | github-code | 1 |
72507372834 | from __future__ import division
import cv2
import numpy as np
# global
# HSV 色值:
GREEN = [40, 65, 13, 80, 255, 255] # Green
YELLOW = [20, 103, 80, 40, 255, 255] # Yellow
BLUE = [94, 81, 82, 126, 255, 255] # Blue
RED = [0, 144, 0, 20, 255, 255] # Red
# default value: Blue 蓝色
lowHue = BLUE[0]
lowSat = BLUE[1]
lowV... | SPOOKY01/Vanilla | RASPBERRYPI/detected_END.py | detected_END.py | py | 4,752 | python | en | code | 1 | github-code | 1 |
6008443264 | import pandas as pd
from tsfresh import extract_features, select_features
from os import listdir
from os.path import isfile, join
from auto_feature_extraction.config import *
def select():
features_files = [f for f in listdir(features_dir) if isfile(join(features_dir, f))]
# Select features individually from each ... | JoaquinRives/Deep-Learning-Project | auto_feature_extraction/select_features.py | select_features.py | py | 1,441 | python | en | code | 0 | github-code | 1 |
36413039997 | import tensorflow as tf
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2_as_graph
def get_flops(model: tf.keras.models.Model, batch_size: int = 1):
real_model = tf.function(model).get_concrete_function(tf.TensorSpec([batch_size] + model.inputs[0].shape[1:], model.input... | chansoopark98/Tensorflow-Keras-Semantic-Segmentation | utils/get_flops.py | get_flops.py | py | 675 | python | en | code | 12 | github-code | 1 |
18638267814 | from flask_restful import Resource, reqparse
from flask_jwt_extended import jwt_required, get_jwt_identity
from CustomDecorators import *
from flask import jsonify, make_response
from models.category import CategoryModel
from models.item import ItemModel
class Category(Resource):
parse = reqparse.RequestPa... | Devanshi1728/waste-management-react | waste_management-backend/resource/category.py | category.py | py | 2,305 | python | en | code | 0 | github-code | 1 |
41559488736 | def summary(outroot='summary-18.05.17'):
from hsaquery import overlaps
from grizli import utils
overlaps.summary_table(output='pointing_summary')
tab = utils.GTable.gread('pointing_summary.fits')
roots = tab['NAME']
tab['Full'] = ['<a href=https://s3.amazonaws.com/aws-gr... | grizli-project/grizli-aws | grizli_aws/master_catalog.py | master_catalog.py | py | 19,456 | python | en | code | 0 | github-code | 1 |
14343588666 | from common import *
def test_server_available():
assert server()
for endpoint in ('/','/functions','/metrics'):
response = requests.get(f'{server()}{endpoint}')
assert response.status_code==200
def BuildModel_Simple():
m = sdk.Model()
m.TimeStart = 0
m.TimeSteps = 10
m.NumPa... | AlexanderZvyagin/MonterCarlo-SDK | python/test/test_1.py | test_1.py | py | 786 | python | en | code | 0 | github-code | 1 |
2548514147 |
def find_perfect_square(n):
rec = [0]*(n+1)
# 1 is a perfect square.
for j in range(n+1):
rec[j] = j
lmt = int(n**0.5)
for i in range(2, lmt+1):
sqr = i*i
max_count = int(n/sqr) + 1
for k in range(1, max_count):
for j in range(k*sqr, n+1):
... | encgoo/python_practice | DynamicProgramming/PerfectSquare.py | PerfectSquare.py | py | 443 | python | en | code | 0 | github-code | 1 |
17363307259 | import torch.optim as optim
import torchvision.transforms as T
# For list of supported models use timm.list_models
MODEL_NAME = "resnet18"
NUM_ClASSES = 10
IN_CHANNELS = 3
USE_TORCHVISION = False # If you need to use timm models set to False.
# USE_TORCHVISION = True # Should use Torchvision Models or timm models
P... | oke-aditya/pytorch_cnn_trainer | examples/config.py | config.py | py | 1,462 | python | en | code | 26 | github-code | 1 |
72143450595 | import datetime
from typing import Any, Dict, List, Optional, Type, TypeVar, Union, cast
import attr
from dateutil.parser import isoparse
from ..types import UNSET, Unset
T = TypeVar("T", bound="PatchedStepInvocation")
@attr.s(auto_attribs=True)
class PatchedStepInvocation:
"""Dynamically removes fields from s... | caltechads/brigid-api-client | brigid_api_client/models/patched_step_invocation.py | patched_step_invocation.py | py | 3,288 | python | en | code | 0 | github-code | 1 |
14205279543 | from django.conf import settings
from django.contrib.auth import (
login as auth_login,
logout as auth_logout,
REDIRECT_FIELD_NAME
)
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.shortcuts import redirect, render, resolve_url, reverse
from django.utils.http import is_s... | reactsuperwizard/clublink_django_certificate | cms/modules/dashboard/views.py | views.py | py | 3,571 | python | en | code | 2 | github-code | 1 |
10000155956 | import pytest
from rest_framework.test import APIClient
from django.urls import reverse
from website.models import Trip
from website.models.profile import UserDetail
import mock
from rest_framework.response import Response
from website.api.v1.main_page.serializers import TripSerializerRetrieve
from django.shortcuts imp... | mahdi-darvishzadeh/Travelo-BackEnd | core/website/tests/main_page/test_trip_retrieve.py | test_trip_retrieve.py | py | 1,273 | python | en | code | 0 | github-code | 1 |
39994188399 | # generator of knapsack instances
import random
seed = 1
random.seed(seed)
items = 10
instance = dict()
for i in range(items):
instance[i] = {}
instance[i]['profit'] = 0
instance[i]['weight'] = 0
name = "generated_"+str(items)
| simonetome/QuantumGeneticAlgorithm | GQA/knapsack_generator/generator.py | generator.py | py | 244 | python | en | code | 3 | github-code | 1 |
25044352092 | def MapFunction(data):
cur_results = []
words = data.split()
for word in words:
cur_results.append((word, 1))
return cur_results
def ReduceFunction(key, values):
result = sum(values)
return (key, result)
def MapReduce(data):
cur_results = []
for sentence in data:
cur_r... | MEMEDAbobo/WENBO-PROJECT | fifo.py | fifo.py | py | 2,960 | python | en | code | 0 | github-code | 1 |
687494140 | import streamlit as st
import pandas as pd
import numpy as np
#import seaborn as sns
#import matplotlib.pyplot as plt
import plotly.express as px
from PIL import Image
# Page layout
st.set_page_config(page_title='Churn Analysis FinTech', page_icon=':bar_chart:', layout='wide')
df = pd.read_csv('fintech_das... | Asifmehdiyev/dashboard_app | dashboard.py | dashboard.py | py | 11,067 | python | en | code | 0 | github-code | 1 |
7786560335 | import pandas as pd
import nltk
import numpy as np
def init_df(buffer, events):
df = pd.DataFrame()
df["text_buffer"] = buffer
df["events"] = events
return df
def extract_sent(df):
sentence_buffer = []
num_sentences = []
for text in df["text_buffer"]:
sentences = nltk.tokenize.s... | vishalraj247/CoAuthorViz_Dashboard | events.py | events.py | py | 5,643 | python | en | code | 2 | github-code | 1 |
35196253380 | from direct.gui.OnscreenImage import OnscreenImage
from pandac.PandaModules import TransparencyAttrib, VBase3
from direct.showbase.DirectObject import DirectObject
from direct.gui.DirectGui import DirectButton, DGG
from direct.interval.IntervalGlobal import Sequence, LerpHprInterval
from gui.Popup import Popup
from gu... | czorn/Modifire | net/modifire/gui/menus/MainMenu.py | MainMenu.py | py | 7,038 | python | en | code | 0 | github-code | 1 |
1401342227 | import pandas as pd
import numpy as np
import pdfplumber
import re
import zipfile
import os
def unzipper(zip):
"""
unzips zipfile and stores content in tempfolder on same level directory.
returns list of directories of pdf files in temp folder.
______
takes in the zipfile.
"""
path = 'data... | moritzgeiger/stockist | stockist/pdfparser.py | pdfparser.py | py | 2,792 | python | en | code | 0 | github-code | 1 |
43199315422 | import bpy
from bpy.props import StringProperty, BoolProperty
from ... utils.collection import get_groups_collection, get_scene_collections
class CreateCollection(bpy.types.Operator):
bl_idname = "machin3.create_collection"
bl_label = "MACHIN3: Create Collection"
bl_description = "description"
bl_op... | AtixCG/Universal-3D-Shortcuts | Blender/With Addons/scripts/addons/MACHIN3tools/ui/operators/collection.py | collection.py | py | 5,714 | python | en | code | 38 | github-code | 1 |
42174078320 | import numpy as np
import agent as a
class AgentPool(object):
def __init__(self, min_agent_count, objects):
""" init
min_agent_count: mininum number of agents for the pool
objects: a list of the scenario's objects
"""
self._min_agent_count = min_agent_count
self._obj... | econser/active_refer | agent_pool.py | agent_pool.py | py | 853 | python | en | code | 0 | github-code | 1 |
35703471791 | # Define constants.
MAX_STARS = 40
MIN_STARS = 5
def main():
# Read the data values from the user.
values = []
input_str = input("Enter a value (blank to quit): ")
while input_str != "":
values.append(float(input_str))
input_str = input("Enter a value (blank to quit): ")
... | NikosDelijohn/CS-polito | lab09/ex1-4.py | ex1-4.py | py | 680 | python | en | code | 30 | github-code | 1 |
8139289198 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rightSideView(self, root: TreeNode) -> list:
if not root: return []
queue = [[],[]]
ans = []
queue[0]... | MinecraftDawn/LeetCode | Medium/199. Binary Tree Right Side View.py | 199. Binary Tree Right Side View.py | py | 727 | python | en | code | 1 | github-code | 1 |
19741466326 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a cointegration script file.
"""
import numpy as np
import pandas as pd
import tushare as ts
import matplotlib.pyplot as plt
import statsmodels.api as sm
def find_cointegration_pairs(dataframe):
# to obtain the length of dataframe
n = dataframe.shape[1]
... | simple321vip/violin-trade | strategy/cointegration_2.py | cointegration_2.py | py | 1,464 | python | en | code | 1 | github-code | 1 |
40420058444 | from pathlib import Path
import numpy as np
import re
from bisect import bisect_left
from copy import deepcopy
from itertools import compress
reg = re.compile(r"(y|x)=(\d+), (y|x)=(\d+)\.\.(\d+)")
def main():
data_folder = Path(".").resolve()
data = data_folder.joinpath("input.txt").read_text()
res = Rese... | eirikhoe/advent-of-code | 2018/17/sol.py | sol.py | py | 5,780 | python | en | code | 0 | github-code | 1 |
10786456409 | import cv2
import numpy as np
import glob
import re
img_array = []
files = sorted(glob.glob('C:\\Users\\Rodrigo\\Documents\\GitHub\\computerVision\\images\\output\\brighter\\*.png'))
files = sorted(files, key=lambda x:float(re.findall("(\d+)",x)[0]))
outputPath = 'C:\\Users\\Rodrigo\\Documents\\GitHub\\computerVision\... | B4nr/computerVision | mainPython/videoProcessing.py | videoProcessing.py | py | 668 | python | en | code | 0 | github-code | 1 |
73476461794 | import os
from dotenv import load_dotenv
from dataclasses import dataclass, asdict
import os
import openai
from metaphor_python import Metaphor
import html2text
from gtts import gTTS, lang
# set up environment
load_dotenv()
# Class represents information about the articles collected (title, author, published date, co... | bhargavilanka/Audicle | main.py | main.py | py | 7,140 | python | en | code | 0 | github-code | 1 |
6623708133 | '''This program is run separately and manually to add new entries in the
csv file that is not in the database, to the database.
'''
import csv
import sqlite3
db_connection = sqlite3.connect('events.db')
db_cursor = db_connection.cursor()
db_cursor.execute('''DROP TABLE IF EXISTS events''')
db_cursor.execute('''CREATE... | secondspass/emreminder | addtodb.py | addtodb.py | py | 845 | python | en | code | 0 | github-code | 1 |
72387707234 | from collections import deque
def solution(board: list[str]):
answer = 0
dx = [1,0,-1,0]
dy = [0,1,0,-1]
n = len(board)
m = len(board[0])
q = deque()
matrix = [[0 for _ in range(len(board[0]))] for _ in range(len(board))]
for idx in range(len(board)):
for jdx in ... | cafe-jun/codingTest-Algo | programmers/리코쳇로봇.py | 리코쳇로봇.py | py | 1,305 | python | en | code | 0 | github-code | 1 |
20779854741 | # Build file tree
tree = {'parent': None, 'dirs': {}, 'files': []}
with open('input-07.txt', 'r') as file:
for line in file:
arg = line.strip().split()
if arg[1] == 'ls':
continue
elif arg[1] == 'cd':
if arg[2] == '..':
# Go up
current_dir = current_dir['parent']
elif arg[2] == '/':
# Go... | Kjell001/advent-2022 | day-07.py | day-07.py | py | 1,242 | python | en | code | 0 | github-code | 1 |
13586138289 | # -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
riko.modules.fetchpage
~~~~~~~~~~~~~~~~~~~~~~
Provides functions for fetching web pages.
Fetches the source of a given web site as a string. This data can then be
converted into an RSS feed or merged with other data in your Pipe using the
`regex` module.
Examples... | nerevu/riko | riko/modules/fetchpage.py | fetchpage.py | py | 7,784 | python | en | code | 1,605 | github-code | 1 |
24621919782 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/5/2 9:48
# @Author : yaomy
# real+render+fuse 所有物体
import json
import torch
import random
import torch.utils.data
import torch.nn.functional as F
import torchvision.transforms as transforms
import pickle as pkl
import numpy as np
import yaml
import os
... | yaomy533/pose_estimation | dataset/linemod/lm_bop.py | lm_bop.py | py | 29,087 | python | en | code | 0 | github-code | 1 |
27345275869 | import matplotlib.pyplot as plt
import numpy as np
import itertools
# from numba import njit
#import pandas as pd
#@njit
def transfer_matrix(N1, N2, polar='TE', n1=1, n2=1):
tm = np.empty((2,2), dtype = np.complex)
if polar == 'TE':
tm[0, 0] = (N2 + N1) / (2. * N2)
tm[0, 1] = (N2 - N1) / (2. * N2)
tm[1, 0] = (... | Enedys/TMM_Otto | tmm_utils.py | tmm_utils.py | py | 11,969 | python | en | code | 0 | github-code | 1 |
73205797474 | import sys
sys.stdin = open('input (1).txt')
for tc in range(1, 11):
num = int(input())
arr = [list(map(int, input().split())) for _ in range(100)]
result = 0
for j in range(100):
for i in range(100):
if arr[i][j] == 1: # N극일 때
if i+1 < 100 and ... | eunjng5474/Study | week05/S_1220_Magnetic/mysol.py | mysol.py | py | 1,475 | python | ko | code | 2 | github-code | 1 |
17360391205 | """Name hold a name choice for a Request
"""
# from . import db, ma
from marshmallow import fields
from sqlalchemy import event
from sqlalchemy.orm import backref
from sqlalchemy.orm.attributes import get_history
from namex.models import db, ma
class Name(db.Model):
__tablename__ = 'names'
id = db.Column(db... | bcgov/namex | api/namex/models/name.py | name.py | py | 8,023 | python | en | code | 6 | github-code | 1 |
72243327714 | import optparse
parser = optparse.OptionParser(
usage='%prog COMMAND [OPTIONS]',
version="x.x.x",
add_help_option=False)
parser.add_option(
'-h', '--help',
dest='help',
action='store_true',
help='Show help')
parser.disable_interspersed_args()
| adamcharnock/seed | seed/baseparser.py | baseparser.py | py | 275 | python | fi | code | 50 | github-code | 1 |
4668653964 | import ncs
is_lsa = False
ietf_l2vpn_servicepoint = "ietf-l2vpn-ntw-servicepoint"
ietf_l2vpn_validation_callpoint = "ietf-l2vpn-nm-validation"
l2vpn_ntw_augmentations_y1731_servicepoint = "l2vpn-ntw-augmentations-y1731-servicepoint"
def is_lsa_setup():
with ncs.maapi.single_read_trans("", "system", db=ncs.RUNNIN... | lucianonunes/vtal-yangs | vtal/ietf-l2vpn-nm/python/ietf_l2vpn_nm/utils.py | utils.py | py | 834 | python | en | code | 0 | github-code | 1 |
35897770416 | import numpy as np # Bring numpy in for indexing via mask
d = ["able", "ale", "hullabuloo", "apple"] # Here is our dictionary
subsq = [] # emtpy array to hold all of our subsequences
def yieldSubSq(s_, d):
'''
arguments:
s_ string: Master sequence containig subsequences
d list of strings: dictionary o... | Steffanic/GoogleTechDev | FoundationsOfProgramming/longestSubsequenceInDict.py | longestSubsequenceInDict.py | py | 1,722 | python | en | code | 0 | github-code | 1 |
1026582185 | #!pipenv run python3
from pprint import pprint
from PyInquirer import prompt, Separator
from git import Repo
import os
import sys
def get_git_root():
try:
git_repo = Repo(os.getcwd(), search_parent_directories=True)
git_root = git_repo.git.rev_parse("--show-toplevel")
return git_root
ex... | dmaahs2017/git-utils | gbdm/__main__.py | __main__.py | py | 1,055 | python | en | code | 0 | github-code | 1 |
6105937107 | '''
A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent
the minutes (0-59).
Given a non-negative integer n which represents the number of LEDs that are currently on, return all
possible times the watch could represent.
'''
def readBinaryWatch(n):
'''
This fu... | chuckinator0/Projects | scripts/binary_watch.py | binary_watch.py | py | 977 | python | en | code | 17 | github-code | 1 |
27476889408 | """ Enhancement of pathlib, representation with a tree data-structure.
This module enhances the functionalities of pathlib, interpreting the Path
objects as nodes of a tree and automatically creating their subtrees. The tree
can be explored for analysis purposes.
"""
from pathlib import Path
from typing import U... | MCallagher/pathtreelib | pathtreelib/__init__.py | __init__.py | py | 33,778 | python | en | code | 0 | github-code | 1 |
28098104562 | #!/bin/env python
# This is a script to use descriptive statistics calculated previously to produce presentation-quality graphics
# and save them as PNG files for use in a powerpoint presentation
# written by Justin Meyer
# last edited 2022-05-04
#
# import required modules
import pandas as pd
import matp... | meyer443/ABE65100-Final-Project | Temp_Graphic.py | Temp_Graphic.py | py | 1,507 | python | en | code | 0 | github-code | 1 |
35471287132 | # This test must be executed after test_account_transfer_funds tests in order to work properly
from ...parabank.src.base_element import BaseElement
from ...parabank.src.pages.account_services_pages.find_transactions_page import FindTransactionsPage
# from web.parabank.tests.test_account_transfer_funds import transfe... | vshkugal/pythonProject | parabank/tests/test_account_find_transactions.py | test_account_find_transactions.py | py | 8,080 | python | en | code | 0 | github-code | 1 |
75153371233 | from scipy.io import wavfile as wav
from os import walk
import os, glob, wave
import csv
path = 'C:/Users/Muhammad/Desktop/REU19/Talker_Speaker.csv'
audio_location = 'C:/Users/Muhammad/Desktop/REU19/lombardgrid/audio'
with open(path, 'a') as csv_file:
csv_reader = csv.reader(csv_file, delimiter = ',')
... | asgharm1999/Script-for-REU | Generate_CSV.py | Generate_CSV.py | py | 2,599 | python | en | code | 0 | github-code | 1 |
3512440778 | # -*- coding: cp1252 -*-
#exercise 10.1
#The first exercise is related to basic class definition. Create a program which has a class Player, which has two attributes, teamcolor and points.
#Then create a main function which creates an object from this class, gives its attributes values "Blue" and "300". After th... | MadhuASingh/Metropolia-VIOPE | chap10.py | chap10.py | py | 4,759 | python | en | code | 0 | github-code | 1 |
43963665477 |
from inspect import getsourcefile
import os.path as path, sys
current_dir = path.dirname(path.abspath(getsourcefile(lambda:0)))
sys.path.insert(0, current_dir[:current_dir.rfind(path.sep)])
from AP import *
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
from scipy import optimize
import ... | brouwerb/AP3 | XST/Detektortotzeit.py | Detektortotzeit.py | py | 2,086 | python | en | code | 0 | github-code | 1 |
74421974754 | #sorting
l=[2,6,1,9,8,7]
for i in range(len(l)):
for j in range(i,len(l)):
if l[i]>l[j]:
temp=l[i]
l[i]=l[j]
l[j]=temp
print(l)
#sort in ascending order
l=[2,5,9,3,7]
l.sort()
print(l)
#sort in descending order
l=['b','d','a','c']
l.sort(reverse=True)
print(l)
#sort using key
l=['cc','aaa','dddd','b']
l.s... | Deviveeran/Python-programs | sorting.py | sorting.py | py | 1,415 | python | en | code | 0 | github-code | 1 |
3710806835 | from django.shortcuts import render, get_object_or_404, redirect
from blog.models import Post
from .models import Reply
from .forms import CommentForm, PostReplyForm
def post_comment(request, post_pk):
post = get_object_or_404(Post, pk=post_pk)
user = request.user
if request.method == 'POST':
form... | xiaoming000/blog_django | comments/views.py | views.py | py | 1,803 | python | en | code | 1 | github-code | 1 |
28021805495 | RETAILER_STATUS = (
("CREATED", "Created"),
("PENDING", "Pending Approval"),
("KYCAPPROVED", "KYC Approved"),
("KYCREJECTED", "KYC Rejected"),
("APPROVED", "Approved"),
)
BUSINESS_STATUS = (
("NOTREGISTERED", "Not Registered"),
("REGISTERED", "Registered")
)
RETAILER_NOTIFICATION_STATUS = ... | aman0x/market-place | commonToall/common.py | common.py | py | 2,072 | python | en | code | 2 | github-code | 1 |
5513569519 | from oslo_log import log as logging
from oslo_versionedobjects import base as object_base
from cyborg.common import exception
from cyborg.db import api as dbapi
from cyborg.objects import base
from cyborg.objects import fields as object_fields
from cyborg.objects.attribute import Attribute
LOG = logging.getLogger(__... | BobzhouCH/cyborg-acc | cyborg/objects/deployable.py | deployable.py | py | 5,180 | python | en | code | 1 | github-code | 1 |
18687715314 | #-*- encoding:utf-8 -*-
import MySQLdb
import sqlite3
import sys
import codecs
reload(sys)
sys.setdefaultencoding('utf-8')
def transfer(sqliteConn, mysqlConn, srcTableName, dstTableName, baseNo, ids, cityNo = 0):
mysqlCursor = mysqlConn.cursor()
sql = "select * from %s" % dstTableName
mysqlCursor.execute(... | waklin/wxSymphony | DbFiles/Sqlite3ToMySql.py | Sqlite3ToMySql.py | py | 2,102 | python | en | code | 0 | github-code | 1 |
1412018915 | import pandas as pd
import requests
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib import transforms
import numpy as np
# Fetch data from the Elering API
start = "2022-04-01T00%3A00%3A00.000Z"
end = "2023-03-31T23%3A59%3A59.999Z"
url = f"https://dashboard.elering.ee/api/nps/price?sta... | adaresa/nutipistik | analysis/electricity_costs.py | electricity_costs.py | py | 3,880 | python | en | code | 1 | github-code | 1 |
30662861026 | numeros = []
for posicao in range(0, 5):
numeros.append(int(input(f'Digite um número para a {posicao + 1}ª posição: ')))
maior = max(numeros)
menor = min(numeros)
print(f'O maior valor digitado é {maior} e está na posição', end=' ')
if numeros.count(maior) > 1:
for c, valores in enumerate(numeros):
... | EsojMelo/Python_programs | desafio 78.py | desafio 78.py | py | 690 | python | pt | code | 0 | github-code | 1 |
26578612425 | import numpy as np
import matplotlib.pyplot as plt
import itertools as it
from numpy import random
from scipy.stats import multivariate_normal
from math import exp, sqrt, pi
from scipy.spatial import distance
## this function draws an o when the value is -1 and x otherwise
def draw_x_o(data, m, text):
print(text)
... | jaskhalsa/machine-learning-models | model-selection-q26-q29.py | model-selection-q26-q29.py | py | 5,814 | python | en | code | 0 | github-code | 1 |
22495146693 | from tkinter import *
from tkinter import ttk
from PIL import Image,ImageTk
import sqlite3
from tkinter import messagebox
from student import Student
import os
import subprocess
class Login:
def __init__(self, root):
self.root=root
self.root.geometry("1750x900+0+0")
self.root.title("Login S... | nagendra-h/Pyhton_Placement_Management | check.py | check.py | py | 6,215 | python | en | code | 0 | github-code | 1 |
24928316156 | from django.shortcuts import render, redirect
from django.core.files.storage import FileSystemStorage
from django.utils.datastructures import MultiValueDictKeyError
from django.core.mail import EmailMessage
from django.template.loader import render_to_string
from django.contrib.auth import authenticate,login,logout
fro... | Anandu-SK/K10 | Admin/views.py | views.py | py | 7,614 | python | en | code | 0 | github-code | 1 |
44616889018 | '''
Created on 08/08/2014
@author: Gabriel de O. Ramos <goramos@inf.ufrgs.br>
'''
from environment import Environment
import time#@UnusedImport
class CliffWalking(Environment):
def __init__(self):
super(CliffWalking, self).__init__()
self.__create_env()
#pri... | goramos/pyrl | environment/cliffwalking.py | cliffwalking.py | py | 5,702 | python | en | code | 5 | github-code | 1 |
72582152355 | import pandas as pd
from re import split
from tqdm import tqdm
## COUNT GAMES BY INITIAL PLYS
d = pd.read_csv('../data/csv/caissa_clean.csv', index_col=0)
f = lambda pgn: sum([m.strip().split() for m in split(r'\d+\.', pgn) if len(m) > 0],[])
def extract_first_plys(row):
plys = {}
plys['Year'] = row.Year
... | EgorLappo/cultural_transmission_in_chess | data_processing/generate_tables.py | generate_tables.py | py | 1,957 | python | en | code | 1 | github-code | 1 |
21520963102 | from jinja2 import Environment, FileSystemLoader
from netaddr import IPAddress, IPNetwork
from yamlreader import yaml_load
from nameko.rpc import rpc, RpcProxy
import ast
from nameko.standalone.rpc import ClusterRpcProxy
CONFIG = {'AMQP_URI': "amqp://guest:guest@localhost:5672"}
def check_ip_network(ip, network):
... | mmfiorenza/fwunify | services/translators/openflow/openflow.py | openflow.py | py | 10,913 | python | en | code | 1 | github-code | 1 |
18856553165 | # Q1_graded
# Do not change the above line.
import numpy as np
from matplotlib import pyplot as plt
from tensorflow.keras.preprocessing.image import load_img, img_to_array, array_to_img
img = load_img('input.jpg', color_mode="grayscale")
X = img_to_array(img)
# Q1_graded
# Do not change the above line.
... | Sinaeskandari/Kohonen-SOM | kohonen_som.py | kohonen_som.py | py | 1,871 | python | en | code | 0 | github-code | 1 |
73948619875 | import matplotlib
matplotlib.use("agg")
import matplotlib.pyplot as plt
import numpy as np
# Create the point data.
x = np.linspace(-1, 1)
y = x + np.random.normal(size=x.size)
# Vary the marker size.
fig = plt.figure()
ax = fig.gca()
ax.scatter(x, y, s=80)
fig.savefig("images/markers_large.png")
# Make markers di... | brohrer/taming_matplotlib | points_examples.py | points_examples.py | py | 1,404 | python | en | code | 22 | github-code | 1 |
25431009999 | import sys
sys.setrecursionlimit(10**4)
input = sys.stdin.readline
def dfs(graph, v, visited, cnt):
global ans
if cnt == 4:
ans = 1
return
for i in graph[v]:
if not visited[i]:
visited[i] = True
dfs(graph, i, visited,cnt+1)
visited[i... | reddevilmidzy/baekjoonsolve | 백준/Gold/13023. ABCDE/ABCDE.py | ABCDE.py | py | 716 | python | en | code | 3 | github-code | 1 |
16473614058 | import torch
import torch.nn as nn
import torch.nn.functional as F
NOISE_VECTOR_DIM = 100
class Generator(nn.Module):
'''
Generator model definition.
In the Conditional Deep Convolutional GAN it is defined as an CNN model with
input size equal to noise vector plus the 10-class one-ho-encoding vector.
... | CristianCosci/Generative_Adversarial_Networks_GAN__Overview | cDCGAN/Generator.py | Generator.py | py | 2,048 | python | en | code | 5 | github-code | 1 |
30698941822 | '''
4C specific. Extracts the 5'->3' DNA sequence between a primer and its
restriction enzyme cut site.
'''
# TODO add check that tags starts with primers.
# output renamed primer.fa (fix _fwd _rev postfix)
import Bio.SeqIO
from pybedtools import BedTool
import collections
import bisect
from bx.intervals import inters... | eivindgl/GenerateTags | generatetags/find_possible.py | find_possible.py | py | 9,987 | python | en | code | 0 | github-code | 1 |
41334766042 | import re
from pathlib import Path
import torch
def load_checkpoint(path, device='cpu'):
path = Path(path).expanduser()
is_deepspeed = False
if path.is_dir(): # DeepSpeed checkpoint
is_deepspeed = True
latest_path = path / 'latest'
if latest_path.is_file():
with open(... | DiffEqML/kairos | src/utils/checkpoint.py | checkpoint.py | py | 881 | python | en | code | 15 | github-code | 1 |
4554882927 | #THIS IS A TEST UPLOAD
# Here are numbers
days = 0
miles = 0
total_cost = float(0)
# User selects 'y' (yes) or 'n' (no)
yes = 'y'
no = 'n'
# User selects either option 'b' (budget), or option 'd' (daily)
b = 'b'
d = 'd'
yes_or_no = input("Do you want to continue?: ")
while yes_or_no == yes:
print("Customer cla... | arnoringi/forritun | Skilaverkefni (Other)/car_rental_original.py | car_rental_original.py | py | 1,731 | python | en | code | 0 | github-code | 1 |
70318908513 | #!/bin/env python3
from utils.Verilog import Verilog
import utils.APIs.APIs as api
import argparse, os
import utils.APIs.from_module as mp
calculator = Verilog("calculator", "calculator.v")
adder = mp.asVerilog({"module" : "resources/rtl/test.v"})#Verilog("adder", "adder")
subtractor = Verilog("subtractor", "subtracto... | jinrudals/generate-verilog-template | example.py | example.py | py | 1,345 | python | en | code | 2 | github-code | 1 |
72359488674 | import asyncio
from connectionBDD import *
from connectionZabbix import *
from Zapi import *
from datetime import datetime
import time
import sys
import pandas as pd
import os
from pandasql import sqldf
from pyzabbix import ZabbixAPI
#On récupère le path pour que le fichier exécutable soit créé dans le même répertoire... | Energies-citoyennes-en-Pays-de-Vilaine/Indicateurs-ELFE | indicateurs/main.py | main.py | py | 26,063 | python | en | code | 0 | github-code | 1 |
14879425734 | from django.conf.urls import url
import views
# from django.views.generic import TemplateView #TemplateView.as_view(template_name="about.html")
app_name = 'park'
urlpatterns = [
# url(r'^$', views.Index.as_view(), name='index'), #index is button to check, list to charge, free space to public
url(r'^log... | Ganben/pygo | park/urls.py | urls.py | py | 941 | python | en | code | 0 | github-code | 1 |
31972899010 | # Definition for a point
# class Point:
# def __init__(self, a=0, b=0):
# self.x = a
# self.y = b
class Solution:
# @param points, a list of Points
# @return an integer
def maxPoints(self, points):
n = len(points)
if n<3:
return n
res = -1
... | phc260/leetcode | Python/max-points-on-a-line.py | max-points-on-a-line.py | py | 1,056 | python | en | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.