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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
36342252422 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Bandit LinUCB - Data Science Project
Group zambra
Created on Sun Nov 3 12:09:56 2019
@author: DANG
"""
from LinUCB_disjoint import LinUCB_disjoint
from LinUCB_hybride import LinUCB_hybrid
from LinUCB_dataPre import MovieLensData
import matplotlib.pyplot as plt
impor... | minhparis/linucb | LinUCB_last_week/LinUCB_param_search.py | LinUCB_param_search.py | py | 2,140 | python | en | code | 2 | github-code | 13 |
12229081770 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import get_object_or_404,render,redirect
from django.http import HttpResponse,JsonResponse,HttpResponseRedirect
from django.contrib import messages
import json
import random
import datetime
# from datetime import date, timedelta
imp... | apengok/bsc2000 | monitor/views.py | views.py | py | 30,903 | python | en | code | 1 | github-code | 13 |
71142729299 | import pandas as pd
import numpy as np
class Metric:
def __init__(self, id):
self.id = id
self.name = 'metric name - ' + str(id)
self.parents = []
self.childs = []
def show_metric(self):
print(self.id)
class Tree(Metric):
def __init__(self, rows, elements_size)... | AndreMaciel66/fake-neural-network | app/fake_kpi_tree_generator.py | fake_kpi_tree_generator.py | py | 2,061 | python | en | code | 0 | github-code | 13 |
1280607001 | import glob
import os
import openpyxl
#①対象ファイルのパス
path = '../excel'
#②対象ファイル種別
fileType = '*.xlsx'
#③置換対象としたいシート名
sheetName = ['表紙']
#④置換対象項目名
tgtItem = ['置き換え対象データ']
#⑤置換後データ
changDate = '置き換え後データ'
#「①対象ファイルのパス」配下にあるExcelファイルのパスを出力
print("■検索対象ファイル")
print(glob.glob(os.path.join(path,fileType )))
#「①対... | hukuikoki/work-efficiency | cellUpdate.py | cellUpdate.py | py | 2,190 | python | ja | code | 0 | github-code | 13 |
15864162055 | #!/usr/bin/env python
from pylab import *
import wave
import numpy as np
from scipy import signal
import sys
audiofile = sys.argv[1]
#load audio file
waveFile = wave.open(audiofile, 'r')
#get length
length = waveFile.getnframes()
#get sample rate
fs = waveFile.getframerate()
#get block size
blocksize = waveFile.ge... | justinsalamon/sonyc-citizensound | processing/spectro.py | spectro.py | py | 974 | python | en | code | 0 | github-code | 13 |
17329631009 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A common training and evaluation runner to allow for easy and consistent model creation and evalutation
"""
__author__ = "John Hoff"
__email__ = "john.hoff@braindonor.net"
__copyright__ = "Copyright 2019, John Hoff"
__license__ = "Creative Commons Attribution-Shar... | theBraindonor/chicago-crime-arrests | utility/runner.py | runner.py | py | 11,885 | python | en | code | 1 | github-code | 13 |
32799544131 | import queue
import re
import jsonpickle
from python.network.msg import MsgUtils
from python.network.threads.PoliteThread import PoliteThread
from python.emulator.MonitoringUtils import MonitoringRequest
from python.request.qos.QoSMsg import QoSRequest
# MsgDispatcher
# Thread receiving the incoming msg... | EVOLVED-5G/ImmersionNetApp | src/python/network/msg/MsgDispatcher.py | MsgDispatcher.py | py | 2,258 | python | en | code | 0 | github-code | 13 |
36947505306 | """
Script to reproduce the few-shot classification results on Meta-Dataset in:
"Fast and Flexible Multi-Task Classification Using Conditional Neural Adaptive Processes"
https://arxiv.org/pdf/1906.07697.pdf
The following command lines should reproduce the published results within error-bars:
Note before running any o... | cambridge-mlg/cnaps | src/run_cnaps.py | run_cnaps.py | py | 17,522 | python | en | code | 155 | github-code | 13 |
42798403165 | from ghidra.program.model.block import BasicBlockModel
from ghidra.app.decompiler import *
from ghidra.framework.plugintool.util import OptionsService
def dumpFuncs(outPath):
# Set image base to 0
curImageBase = currentProgram.getImageBase()
currentProgram.setImageBase(curImageBase.subtract(curImageBase.getOffse... | B2R2-org/FunProbe | tools/ghidra/scripts/ghidra_script.py | ghidra_script.py | py | 749 | python | en | code | 3 | github-code | 13 |
14274302116 | #python
# File: mc_lxRename_removeX.py
# Author: Matt Cox
# Description: Bulk renames a selection of items, removing X amount of characters from the start or the end. Based upon the user variable removeX.
import lx
import re
lxRRemoveXString = lx.eval( "user.value mcRename.removeX ?" )
lxRRemoveXArgs = lx.args()
lxR... | Tilapiatsu/modo-tila_customconfig | mc_lxRename/Scripts/mc_lxRename_removeX.py | mc_lxRename_removeX.py | py | 1,289 | python | en | code | 2 | github-code | 13 |
15963361372 |
class Solution(object):
def __init__(self):
self.diagonal1 = [[0,0],[1,1],[2,2]]
self.diagonal2 = [[0,2],[1,1],[2,0]]
def checkA(self, a_list):
columns = []
rows = []
three_check = []
if (all(x in a_list for x in self.diagonal1)):
retu... | Dan298/LeetCode | TicTacToe.py | TicTacToe.py | py | 2,293 | python | en | code | 0 | github-code | 13 |
23636962778 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 22 12:10:28 2018
@author: Karthikeyan
"""
#load Data
import pandas as pd
import numpy as np
import os
os.getcwd()
CODELOC = "F:\\Chat_bot\\NLPBot\\"
sentence = pd.read_csv('sentences.csv')
sentence.head(10)
sentence.shape
##feature engineering
#Ext... | karthikbd/NLP-PreProcessing | classification.py | classification.py | py | 4,758 | python | en | code | 0 | github-code | 13 |
20682097308 | import torch
import torch.nn as nn
import gymnasium as gym
import numpy as np
import matplotlib.pyplot as plt
import os
from sklearn.linear_model import LinearRegression
# REINFORCE Policy Gradient Algorithm
# Episodes
EPISODES = 2000
# Max Steps per Episode
MAX_STEPS = 1000
# Discount Factor
GAMMA = 0... | Derrc/Reinforcement-Learning | policy-based/reinforce.py | reinforce.py | py | 4,004 | python | en | code | 1 | github-code | 13 |
12392351216 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#Reference https://ebisuke33.hatenablog.com/entry/abc197c
def main():
N = int(input())
array = list(map(int,input().split()))
ans = 10**9+7
if N==1:
print(array[0])
exit()
for i in range(2**(N-1)):
base = 0
or_value = ar... | 06keito/study-atcoder | src/abc197_c.py | abc197_c.py | py | 647 | python | en | code | 0 | github-code | 13 |
72058652499 | # 마을을 분할할 예정. 분리된 마을 안에 집들은 연결되도록 해야함
# 유지비가 최소로 되게끔 하고 싶어함.
# 루트노드를 찾아주는 함수
def findParent(parent, x):
if parent[x] != x:
# 루트노드가 아니라면 재귀적으로 호출
return findParent(parent, parent[x])
return parent[x]
def unionParent(parent, a, b):
a = findParent(parent, a)
b = findParent(parent, b)
... | jaehee222/CodingTest | 1/graph/graph_5.py | graph_5.py | py | 1,193 | python | ko | code | 0 | github-code | 13 |
6683377762 | """
**********************************************************************************
This module contains all the business logic for lists services.
**********************************************************************************
"""
from uuid import UUID, uuid4
from datetime import datetime
import uuid
import fl... | rrickgauer/lists | src/api/api_lists/services/lists/routines.py | routines.py | py | 5,128 | python | en | code | 1 | github-code | 13 |
6523096806 | #!/usr/bin/env python3
import random
def GenRanMac():
MacList = []
for i in range(1,7):
RanStr = "".join(random.sample("01234567890abcdef",2))
MacList.append(RanStr)
RanMac = ":".join(MacList)
return RanMac
print (GenRanMac())
| foxleoly/python3 | randomMac.py | randomMac.py | py | 236 | python | en | code | 1 | github-code | 13 |
31942754836 | from flask_json_schema import JsonSchema
schema = JsonSchema()
template_request = {
'required': ["title", "description", "severity"],
'properties': {
'title': {'type': 'string'},
'description': {'type': 'string'},
'severity': {'type': 'string'}
}
}
template_request_delete = {
'... | malinowakrew/rest_api | schema/__init__.py | __init__.py | py | 589 | python | ko | code | 0 | github-code | 13 |
74007830416 | numero_casos = int(input())
divisores = 0
while numero_casos > 0:
num = int(input())
for a in range(1, num):
if num % a == 0:
divisores += a
if divisores == num:
print(num, "eh perfeito")
else:
print(num, "nao eh perfeito")
numero_casos -= 1
divisores ... | broeringlucas/SIN-UFSC | INE5603 - POO1/Estruturas de Repetição/numero_perfeito.py | numero_perfeito.py | py | 334 | python | pt | code | 0 | github-code | 13 |
36260320592 | #
# Turn command to rotate models.
#
def turn_command(cmdname, args, session):
from .parse import float_arg, int_arg, axis_arg, parse_arguments
req_args = (('axis', axis_arg),
('angle', float_arg),)
opt_args = (('frames', int_arg),)
kw_args = ()
kw = parse_arguments(cmdname, args, s... | HamineOliveira/ChimeraX | src/apps/hydra/commands/turncmd.py | turncmd.py | py | 933 | python | en | code | null | github-code | 13 |
6200711062 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 5 14:16:27 2020
@author: vijetadeshpande
"""
import torch
import torch.nn as nn
import random
class Model(nn.Module):
def __init__(self, encoder, decoder):
super().__init__()
self.encoder = encoder
self.decode... | vijetadeshpande/meta-environment | Transformer/TransformerModel.py | TransformerModel.py | py | 718 | python | en | code | 0 | github-code | 13 |
71378298258 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 2 14:25:18 2020
@author: hossein
"""
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation
from tensorflow.keras.optimizers import Adam
import gym
from collections import deque
... | HosseinSheikhi/Cartpole | ExpectedSARSA/expectedSARSA.py | expectedSARSA.py | py | 7,508 | python | en | code | 0 | github-code | 13 |
23836458665 | import argparse
import requests
import struct
class ParsingError(Exception): pass
class DataBlock(object):
def __init__(self, data, debug=False):
super(DataBlock, self).__init__()
self.data = data
self.pos = 0
self.debug = debug
def offset_read(self, length, offset=None):
... | duty1g/DS-Crawler | DS_Crawler.py | DS_Crawler.py | py | 10,444 | python | en | code | 1 | github-code | 13 |
41433766062 | from django.shortcuts import render
from .models import Article,ArticleImage
from django.views.generic import DetailView,TemplateView
from .forms import ArticleFormSet,ArticleForm
class ArticleDetailView(DetailView):
model = Article
template_name='articles/article.html'
def get_context_data(self, **kwarg... | faci2000/political_website | articles/views.py | views.py | py | 734 | python | en | code | 0 | github-code | 13 |
1416166776 | import sys
if len(sys.argv) <= 1:
raise Exception("No inputs")
with open(sys.argv[1], 'r') as f:
lines = [l.rstrip() for l in f.readlines()]
def read_tiles(ls):
i = 0
tiles = []
while i < len(ls):
l = ls[i]
title, id = l[:-1].split(' ')
i += 1
m = []
while... | asek-ll/aoc2020 | day20/main.py | main.py | py | 7,825 | python | en | code | 0 | github-code | 13 |
5947662768 | import nuke
import os
import logging
import json
from functools import partial
try:
if nuke.NUKE_VERSION_MAJOR < 11:
from PySide import QtCore, QtGui, QtGui as QtWidgets
from PySide.QtCore import Qt
else:
from PySide2 import QtWidgets, QtGui, QtCore
from PySide2.QtCore import Qt... | adrianpueyo/KnobScripter | KnobScripter/codegallery.py | codegallery.py | py | 20,754 | python | en | code | 65 | github-code | 13 |
74894602577 | import telebot
from telebot import types
from icrawler.builtin import GoogleImageCrawler
import shutil
import random
import wikipedia
import requests
import datetime
wikipedia.set_lang('ru')
bot = telebot.TeleBot('5502613023:AAFsb-kerhTpeRSCfqh1_zRnOqPCaykbbDM')
markup = types.ReplyKeyboardMarkup()
mar... | Julkinis/telegram_bot | tgbot.py | tgbot.py | py | 13,760 | python | ru | code | 0 | github-code | 13 |
30701529654 | import numpy as np
import astropy
from astropy.io import fits
import matplotlib
import matplotlib.pyplot as plt
import m2fs_process as m2fs
import os
from isolate_model_result import Model
import scipy
from scipy.spatial import distance
import mycode
matplotlib.use('TkAgg')
from matplotlib.patches import Ellipse
from p... | mgwalkergit/spec | m2fs_fitspectra.py | m2fs_fitspectra.py | py | 10,297 | python | en | code | 0 | github-code | 13 |
35256705805 | import logging
import os
from logging.handlers import RotatingFileHandler
from pathlib import Path
from mb_commons import Scheduler
from app.config import AppConfig
from app.core.db import DB
from app.core.services.system_service import SystemService
from app.core.services.worker_service import WorkerService
class ... | max-block/demo-fastapi | app/core/core.py | core.py | py | 2,053 | python | en | code | 0 | github-code | 13 |
70942051217 | import random
guess = ''
answers = ('heads', 'tails')
while guess not in answers:
print('Guess the coin toss! Enter heads or tails:')
guess = input()
toss = random.randint(0, 1) # 0 is tails, 1 is heads
if answers[toss] == guess:
print('You got it!')
else:
print('Nope! Guess again!')
guess = input... | danhuynhdev/automateboringstuff | chapter10/debug.py | debug.py | py | 448 | python | en | code | 0 | github-code | 13 |
6916789067 | class Neighbors:
def __init__(self, nbs):
self.nw = nbs[0]
self.n = nbs[1]
self.ne = nbs[2]
self.w = nbs[3]
self.c = nbs[4]
self.e = nbs[5]
self.sw = nbs[6]
self.s = nbs[7]
self.se = nbs[8]
@staticmethod
def get_neighbors(x, y, img):
... | steven-gomez/mapkernel | src/neighbors.py | neighbors.py | py | 1,347 | python | en | code | 0 | github-code | 13 |
27236893047 | from typing import Union, Sequence, List, Tuple, Optional, Dict, Any, Iterator
from abc import ABC, abstractmethod
import numpy
import sys
from mini_op2.framework.core import *
from mini_op2.framework.system import SystemInstance, SystemSpecification
from mini_op2.framework.user_code_parser import scan_code, VarUses... | joshjennings98/fyp | graph_schema-4.2.0/apps/nursery/op2/mini_op2/framework/control_flow.py | control_flow.py | py | 13,165 | python | en | code | 0 | github-code | 13 |
22645880702 | import time
from retry import retry
from threadlocal_aws.clients import ec2, route53
from threadlocal_aws.resources import ec2 as ec2_resource
from ec2_utils.instance_info import info
def associate_eip(
eip=None, allocation_id=None, eip_param=None, allocation_id_param=None
):
if not allocation_id:
if ... | NitorCreations/ec2-utils | ec2_utils/interface.py | interface.py | py | 4,325 | python | en | code | 1 | github-code | 13 |
71253828819 | from typing import List
from copy import deepcopy
import torch
import torch.nn as nn
from catalyst import utils
def get_network(params):
params = deepcopy(params)
if(params["type"] == "lstm"):
return _get_lstm_net(**params)
else:
return _get_linear_net(**params)
# Here we define our mod... | denizdurduran/dicmar | src/network_lstm.py | network_lstm.py | py | 5,475 | python | en | code | 1 | github-code | 13 |
24574382243 | # Exercício 092 do curso de Python - Curso em vídeo
# Crie um programa que leia nome, ano de nascimento e carteira de trabalho e cadastre-o
# (com idade) em um dicionário. Se por acaso a CTPS for diferente de ZERO,
# o dicionário receberá também o ano de contratação e o salário.
# Calcule e acrescente, além da ida... | felipecabraloliveira/Python | curso-de-python-curso-em-video/scripts/exercicios/ex092.py | ex092.py | py | 1,268 | python | pt | code | 0 | github-code | 13 |
24463290429 | from pandas import read_csv
from enum import Enum
class Locations(Enum):
"""Encapsulates store location strings"""
BACKGROUND = "#"
CHECKOUT = "C"
CUSTOMER = "K"
DAIRY = "D"
DRINKS = "L"
ENTRANCE = "G"
EXIT = "E"
FRUIT = "F"
SPICES = "S"
# Paths
PATH_SUPERMARKETMAP = "images... | MichlF/projects | data_science/supermarket_markov_simulation/config.py | config.py | py | 1,249 | python | en | code | 1 | github-code | 13 |
14610928708 | from datetime import datetime
from typing import List
from fastapi.logger import logger
from pydantic import parse_obj_as
from sqlalchemy.ext.asyncio import AsyncSession
from app import schemas
from app.controllers import note_controller
from app.models import Note
from app.utils import helpers
async def get_by_id(... | quangpq/fastapi-async-sqlalchemy | app/api/notes/controller.py | controller.py | py | 1,673 | python | en | code | 0 | github-code | 13 |
9500200508 | class translator:
def deciToRoman(self, num):
val = [1000, 900, 500, 400,100, 90, 50, 40,10, 9, 5, 4,1]
syb = ["M", "CM", "D", "CD","C", "XC", "L", "XL","X", "IX", "V", "IV","I"]
roman = ''
i = 0
while num > 0:
for _ in range(num // val[i]):
roma... | rootkidx/OODataStructure_Lab | python2/python2.1.py | python2.1.py | py | 978 | python | en | code | 0 | github-code | 13 |
12600901531 | import operator
import os
import sys
from pynput import keyboard
ListOne = []
ListTwo = ['*', '*']
def on_press(key):
try:
if key.char == '*':
ListOne.append('*')
else:
os.system(r"C:\Users\Lzhyrifx\AppData\Command\Error\SystemError.vbs")
sys... | Lzhyrifx/ApplyEncryption | Command/Python/Synchronization.py | Synchronization.py | py | 696 | python | en | code | 0 | github-code | 13 |
17316751482 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 20 09:12:57 2017
@author: Beau.Uriona
"""
from os import listdir
from os.path import isfile, join, dirname, abspath
import subprocess as sub
from multiprocessing.dummy import Pool
from datetime import datetime
from string import Templat... | Sillson/awPlot | static/controlGUI/runProd.py | runProd.py | py | 4,634 | python | en | code | 0 | github-code | 13 |
17254711928 | import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--ply', type=str, help="chemin vers la racine du dossier contenant les nuages de points")
parser.add_argument('--png', type=str, help="chemin vers la racine du dossier contenant les images 2D")
parser.add_argument('--intersect', type=bo... | keyber/reconstruction3D | source/utils/simplify_database.py | simplify_database.py | py | 5,026 | python | fr | code | 3 | github-code | 13 |
3224357771 | #!/usr/bin/python
"""ansible module for packer init"""
__metaclass__ = type
from pathlib import Path
from ansible.module_utils.basic import AnsibleModule
from mschuchard.general.plugins.module_utils import packer
DOCUMENTATION = r'''
---
module: packer_init
short_description: Module to manage Packer template and c... | mschuchard/ansible.general | plugins/modules/packer_init.py | packer_init.py | py | 3,528 | python | en | code | 0 | github-code | 13 |
14275197886 | # Adapted from tensorflow_CTC_example.
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow.python.ops import ctc_ops as ctc
from tensorflow.python.ops import rnn_cell
from tensorflow.python.ops.rnn import bidirectional_rnn
import numpy as np
import prettytenso... | tilarids/declear | train_ctc.py | train_ctc.py | py | 8,026 | python | en | code | 2 | github-code | 13 |
22011576118 | def price_comparison(request):
"""
Compare the price of different supermarkets
on a particular item
"""
results = []
item = ''
if request.method == "POST":
form = ComparisonForm(request.POST)
if form.is_valid():
retailers = form.cleaned_data.get('retailer')
item = form.cleaned_data.get('itemname')
... | GithakaMbui/consumer-guide | food/pricecomparison_backup.py | pricecomparison_backup.py | py | 1,001 | python | en | code | 0 | github-code | 13 |
35710207522 | from kivy.config import ConfigParser
import xml.etree.ElementTree
import threading
from pathlib import Path
import os.path
from datetime import datetime
from osmap.index import Index
class Osmap:
konfig = ConfigParser()
index = Index()
def nacitajnastavenia(self):
konfig_cesta = Path('nastavenia/... | martincivan/OsMap | osmap/osmap.py | osmap.py | py | 2,221 | python | sl | code | 0 | github-code | 13 |
20814999552 | import json
import plotly.graph_objects as go
with open('response.json') as f:
data = json.load(f)
x_values = []
y_values = []
# Loop through each text annotation
for annotation in data['responses'][0]['textAnnotations']:
vertices = annotation['boundingPoly']['vertices']
# Loop through each vertex
for ver... | sazzadi-r14/textblock-test | advhist.py | advhist.py | py | 1,288 | python | en | code | 0 | github-code | 13 |
9225059235 | """Game Logic for the Progression Brain Game."""
from random import randint
INTRO = 'What number is missing in the progression?'
def make_progression(step, starting_num, missing_spot, progression_length):
"""Method for making a progression string and its missed answer."""
current_spot = 0
current_num ... | alienflakes/python-project-lvl1 | brain_games/games/progression.py | progression.py | py | 1,010 | python | en | code | 0 | github-code | 13 |
39647350620 | import os
import torch
import pandas as pd
import numpy as np
from tqdm import tqdm
from torch.autograd import Variable
from torchvision import transforms
from .dataGenerator import nii_loader, get_patch
from ..helpers import utils
from tqdm import tqdm
def __get_whole_tumor__(data):
return (data > 0)*(data < 4... | koriavinash1/DeepBrainSeg | DeepBrainSeg/tumor/feedBack.py | feedBack.py | py | 6,678 | python | en | code | 175 | github-code | 13 |
23154936493 | #!/usr/bin/env python
import rospy
from std_msgs.msg import String,Float32MultiArray
from geometry_msgs.msg import PoseStamped
from mavros_msgs.msg import RCOut
import roslib
import rospy
import tf
import argparse
class savePressureCVS():
def __init__(self):
rospy.init_node('save... | PastorD/bintel | scripts/save_pressure_cvs.py | save_pressure_cvs.py | py | 1,794 | python | en | code | 3 | github-code | 13 |
43175667599 | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
url(r'^tags$', views.index),
url(r'^tags/add$', views.add_tag, name="add-tag"),
url(r'^tags/(?P<pk>\d+)$', views.edit_tag, name="view-tag"),
#u... | oluka/mapping_rapidsms | apps/tags/urls.py | urls.py | py | 469 | python | en | code | 3 | github-code | 13 |
1596999338 | import os
import sys
import pandas as pd
import sqlite3
import psycopg2
sys.path.append(os.getcwd()+'\\src')
import db_interface
def main():
conn_sqlite3 = sqlite3.connect("temp/data.db")
query = "SELECT * FROM data"
df = pd.read_sql_query(query, conn_sqlite3)
df = df.iloc[:,1:]
print(df.head()... | maj-oliveira/quant-finance-strategy | temp/insert_into_db.py | insert_into_db.py | py | 582 | python | en | code | 0 | github-code | 13 |
35180707730 | import ctypes
from random import randint, random
import games.utils.utils as utils
class Matrix(ctypes.Structure):
"""
Класс Matrix описывает одноименную структуру в С.
Класс имеет поля:
- rows - количество строк матрицы
- columns - количество столбцов матрицы
- matrix - ук... | iu7og/iu7games | games/teen48/teen48_runner.py | teen48_runner.py | py | 10,951 | python | ru | code | 3 | github-code | 13 |
1069966553 | trace0 = go.Scatter(
x = df.columns,
y = df.loc['Netherlands'],
mode = 'lines',
name = 'Netherlands',
line = dict(
color = 'rgb(255, 127, 0)'
)
)
trace1 = go.Scatter(
x = df.columns,
y = df.loc['France'],
mode = 'lines+markers',
name = 'France',
line = dict(
c... | ualberta-rcg/python-plotting | notebooks/solutions/plotly-scatter-netherlands-france.py | plotly-scatter-netherlands-france.py | py | 548 | python | en | code | 5 | github-code | 13 |
32547106375 | # to use the torchvision.datasets.ImageFolder函数,所以使用这个工具将ava中的style_list转化为正常的代码
import os
import shutil
dirpath = '../data/ava_dataset/'
imagepath = dirpath + 'images/'
style_dir_path = dirpath + 'style_image_lists/'
train_id = style_dir_path + 'train.jpgl'
train_tag = style_dir_path + 'train.lab'
test_id = style_dir_... | 2742195759/xkcv_backbone | tools/change_ava_format_to_imagefolder.py | change_ava_format_to_imagefolder.py | py | 1,474 | python | en | code | 0 | github-code | 13 |
29078749494 | from ckeditor_uploader.widgets import CKEditorUploadingWidget
from django import forms
from django.contrib import admin
from django.utils.safestring import mark_safe
from photo.admin import wrapper_photo
from server.utils.handler import ExceptionHandler
from .models import Cake
class CakeAdminForm(forms.ModelForm):
... | AbbasIsaev/DjangoCakes | cake/admin.py | admin.py | py | 1,670 | python | en | code | 0 | github-code | 13 |
35266828276 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
iris_df = load_iris()
# print(iris_df.head())
data = load_iris()
# print(data.feature_names)
# print(dat... | ayuSh0614/Oohooo-DSA-cpp | rough.py | rough.py | py | 900 | python | en | code | 0 | github-code | 13 |
70145146898 | """Kernels used to calculate equivalent width of spectral lines"""
from jax import jit as jjit
from jax import numpy as jnp
@jjit
def _get_quadfit_weights(x, x1, x2, x3, x4):
msk_lo = (x >= x1) & (x <= x2)
msk_hi = (x >= x3) & (x <= x4)
msk = msk_lo | msk_hi
return jnp.where(msk, 1, 0)
@jjit
def _ge... | ArgonneCPAC/dsps | dsps/em_lines/equivalent_width.py | equivalent_width.py | py | 1,699 | python | en | code | 21 | github-code | 13 |
43254519561 | import sys
sys.stdin = open('input.txt')
n = int(input())
num_list = list(map(int, input().split()))
memo = [[0 for _ in range(21)] for _ in range(n+1)]
# memo : i번째 덧/뺄셈의 결과에서 0~20까지 각 숫자가 나온 횟수를 산정
memo[1][num_list[0]] = 1 #case에선 8이므로 8에 해당하는 값 +1
for i in range(1, n):
for j in range(21):
if memo[i][j... | KimSoomae/Algoshipda | week3(dp)/골드5/김성현_5557_1학년.py | 김성현_5557_1학년.py | py | 1,041 | python | en | code | 0 | github-code | 13 |
19563538923 | from nose.plugins.attrib import attr
import unittest2 as unittest
from tempest import exceptions
from tempest.common.utils.data_utils import rand_name
from tempest.tests.compute.base import BaseComputeTest
class ConsoleOutputTest(BaseComputeTest):
@classmethod
def setUpClass(cls):
super(ConsoleOutpu... | aristanetworks/arista-ovs-testing | tempest/tempest/tests/compute/test_console_output.py | test_console_output.py | py | 3,044 | python | en | code | 0 | github-code | 13 |
6820589185 | """
Title: Plotter
Description: For plotting data
Author: Janzen Choi
"""
# Libraries
import matplotlib.pyplot as plt
import matplotlib.colors as mcolours
from moga_neml.helper.experiment import DATA_UNITS
# Constants
DEFAULT_PATH = "./plot"
EXP_TRAIN_COLOUR = "silver"
EXP_VALID_COLOUR = "gr... | ACME-MG/moga_neml | moga_neml/interface/plotter.py | plotter.py | py | 4,835 | python | en | code | 0 | github-code | 13 |
10191525025 | def solution(jobs):
n = len(jobs)
answer = 0
# 소요시간을 기준으로 정렬
jobs = sorted(jobs, key=lambda x: x[1])
start = 0
while jobs:
for i in range(len(jobs)):
if jobs[i][0] <= start:
start += jobs[i][1]
answer += start - jobs[i][0]
#소요시... | Jinnie-J/Algorithm-study | programmers/[힙]디스크컨트롤러.py | [힙]디스크컨트롤러.py | py | 1,187 | python | ko | code | 0 | github-code | 13 |
25319990979 | import os
import operator
from functools import reduce
CURRENT_DIRECTORY = os.path.dirname(__file__)
os.chdir(CURRENT_DIRECTORY)
def read_input_lines():
with open('input.txt', 'r') as fh:
return [x.strip() for x in fh.readlines()]
def read_input_text():
with open('input.txt', 'r') as fh:
retu... | voidlessVoid/advent_of_code_2020 | day_06/michael/solution.py | solution.py | py | 742 | python | en | code | 0 | github-code | 13 |
23060606070 | import random
import math
import numpy as np
from preset import Preset
from parameter import Parameter
from utils import clip
class RadialGradient(Preset):
"""Radial gradient that responds to onsets"""
speed = Parameter('speed', 0.1)
hue_width = Parameter('hue-width', 0.2)
hue_step = Parameter('hue-... | craftyjon/firelight | presets/radial_gradient.py | radial_gradient.py | py | 3,881 | python | en | code | 2 | github-code | 13 |
71329030737 | from grpc_cust.clientapival_client import get_clientinfo, get_clientapikey, get_verified_apikey
def test_clientapival_client():
info = get_clientinfo("mfg")
assert info is not None
apikey = get_clientapikey("IamWrongClient","IamWrongClient")
assert apikey.expiry == "1900-01-01"
apikey = get_clie... | eslywadan/dataservice | tests/clientapival_client_test.py | clientapival_client_test.py | py | 666 | python | en | code | 0 | github-code | 13 |
16984434177 | from __future__ import print_function
from __future__ import absolute_import
import os
import logging
import pickle
import random
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import *
from tensorflow.keras i... | rouqinghuoliushui98/Code_modification | New_Code/ANN_Staqc_new/models_text.py | models_text.py | py | 7,200 | python | en | code | 0 | github-code | 13 |
7702731832 | """
GPU Metrics from GPUtil.
"""
from node.telemetry.metric import Metric
import GPUtil
class GPU(Metric):
"""
Wrapper for GPUtil GPU information.
"""
def metric_name(self) -> str:
return "gpu"
def measure(self) -> dict:
try:
data = {}
gpus = GPUtil.getGPU... | blackadar/shepherd | node/telemetry/metrics/gpu.py | gpu.py | py | 1,026 | python | en | code | 2 | github-code | 13 |
20999043873 | import os
import logging
import click
import shutil
import hashlib
from collections import defaultdict
logging.basicConfig(
filename="history.log", format="%(asctime)s %(message)s", filemode="a"
)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
def _checksum(folder_path, file_path):
absolute_pat... | cobanov/easy-duplicate | duplicate.py | duplicate.py | py | 2,293 | python | en | code | 3 | github-code | 13 |
7709997337 | import requests
import pymysql
import csv
##카카오 API
def whole_region(keyword, start_x,start_y,end_x,end_y):
#print(start_x,start_y,end_x,end_y)
page_num = 1
# 데이터가 담길 리스트
all_data_list = []
while (1):
url = 'https://dapi.kakao.com/v2/local/search/keyword.json'
params = {'query': ke... | lsgyeong/companyproject1 | kakaocrawling.py | kakaocrawling.py | py | 3,698 | python | en | code | 0 | github-code | 13 |
35547771870 | """
This script takes a paired alignment file and, assigns each end to a bin (some chunk of
a chromosome defined by supplied bin size), and prints out the bin-bin counts for only
contacts within some width of the diagonal (distance between the bins).
Prints a unique format. The file starts with a series of lines... | michaelrstadler/hic | bin/archive/HiC_bincounts_generate_compressed_allchr.py | HiC_bincounts_generate_compressed_allchr.py | py | 3,839 | python | en | code | 0 | github-code | 13 |
17081473324 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.HeatMapData import HeatMapData
class AlipayCommerceTransportTaxiHeatmapQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayCommerceTransportTa... | alipay/alipay-sdk-python-all | alipay/aop/api/response/AlipayCommerceTransportTaxiHeatmapQueryResponse.py | AlipayCommerceTransportTaxiHeatmapQueryResponse.py | py | 972 | python | en | code | 241 | github-code | 13 |
31234528949 | def homework_2(lst): # 请同学记得把档案名称改成自己的学号(ex.1104813.py)
count = 0
for i in range(len(lst)): #判断数字是否为奇数
if (lst[i]+1) % 2 == 0:
lst[i] += 1
count += 1
for i in range(len(lst)-1): #判断后一个数字是否比前面的大
while lst[i] >= lst[i+1]:
lst[i+1] += 2
count += ... | daniel880423/Member_System | file/hw2/1080406/s1080406_4.py | s1080406_4.py | py | 517 | python | zh | code | 0 | github-code | 13 |
17938130632 | import requests
from requests.cookies import RequestsCookieJar
import json
import time
import os
import sys
import datetime
import copy
sys_args = int(sys.argv[1])
reverse_data = datetime.datetime.now() + datetime.timedelta(days=6)
reverse_data = reverse_data.strftime('%Y-%m-%d')
reverse_time = ["09:00", "... | Thinknoon/python_reservstion | main_improved.py | main_improved.py | py | 2,668 | python | en | code | 0 | github-code | 13 |
32080025620 | class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree(object):
def __init__(self, root):
self.root = Node(root)
self.stack = []
def traverse(self, node):
curr = node
while True:
... | samgh/Byte-by-Byte-Solutions | python/InorderTraversal.py | InorderTraversal.py | py | 1,141 | python | en | code | 154 | github-code | 13 |
74253715858 | """Script to train a GAN.
Examples:
python main.py --dataset folder --dataroot /path/to/datasets/celeba \
--crop_size 160 --image_size 80 --code_size 256 --norm weight \
--lr 0.00002 --r_iterations 1 --niter 300000 \
--save_path /path/to/checkpoints/exp01 \
#--load_path /path/to/checkpoints/exp01
Trains a n... | aleju/gan-error-avoidance | g_lis/main.py | main.py | py | 26,045 | python | en | code | 23 | github-code | 13 |
6921550367 | from f5.sdk_exception import F5SDKError
from f5_heat.resources import f5_cm_cluster
from heat.common.exception import ResourceFailure
from heat.common import template_format
from heat.engine.hot.template import HOTemplate20150430
from heat.engine import rsrc_defn
from heat.engine import template
import mock
import pyt... | F5Networks/f5-openstack-heat-plugins | f5_heat/resources/test/test_f5_cm_cluster.py | test_f5_cm_cluster.py | py | 4,376 | python | en | code | 7 | github-code | 13 |
26575588722 | class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
# Use dinamic programming to the result
if len(s) == 0:
return 0
DP = [[0] * (len(s) + 1) for i in range(len(s) + 1)]
reverse_s = s[::-1]
#
for i in range(1, len(s) + 1):
f... | ujas09/Leetcode | 516.py | 516.py | py | 633 | python | en | code | 0 | github-code | 13 |
3801919602 | # -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
sys.path.append("..")
from utils import box_blur, CBAM, FastGuidedFilter
def upsample(x, h, w):
return F.interpolate(x, size=[h,w], mode='bicubic', align_corners=True)
class ResBlock(nn.Module):
def __i... | Zhaozixiang1228/Pansharpening-FGF-GAN | models/FGF_GAN.py | FGF_GAN.py | py | 4,684 | python | en | code | 5 | github-code | 13 |
21148807037 | from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
GenderChoices=(
('Male','Male'),
('Female','Female'),
)
YearChoices = (
('1','... | anshulsharma1011/ssaksham | accounts/models.py | models.py | py | 1,760 | python | en | code | 0 | github-code | 13 |
41029348880 | from googleapiclient.discovery import build # used for Google sheets info
from google.oauth2 import service_account # also used for Google sheets info
import random # used for generating random choice (duh)
import config # used to hold our sensitive info
import time # used for sleep (lol)
SERVICE_ACCOUNT_FI... | Voltaic314/Movie-Picker-For-Google-Sheets-In-Python | Movie-Picker.py | Movie-Picker.py | py | 5,447 | python | en | code | 0 | github-code | 13 |
2181041381 | #!usr/bin/python
# -*- coding: utf-8 -*-
import logging
import networkx as nx
import random
import numpy as np
import time
from TriangulationAlgorithms import TriangulationAlgorithm as ta
def triangulate_LexM(G, randomized=False, repetitions=1, reduce_graph=True, timeout=-1):
algo = Algorithm_LexM(G, reduce_graph,... | Feathergunner/Triangulation | TriangulationAlgorithms/LEX_M.py | LEX_M.py | py | 5,214 | python | en | code | 2 | github-code | 13 |
14646334595 | from sqlalchemy import Column, Identity, Integer, String, Table
from . import metadata
PaymentMethodDetailsLinkJson = Table(
"payment_method_details_linkjson",
metadata,
Column(
"country",
String,
comment="Two-letter ISO code representing the funding source country beneath the Link... | offscale/stripe-sql | stripe_openapi/payment_method_details_link.py | payment_method_details_link.py | py | 550 | python | en | code | 1 | github-code | 13 |
74843556177 |
import re
import bpy
import numpy as np
from mathutils import Matrix
from . import faceit_utils as futils
from . import fc_dr_utils
def apply_matrix_to_all_mesh_data(mesh_data, matrix):
'''Apply a matrix to all mesh data'''
# Apply matrix to mesh data
mesh_data = np.matmul(mesh_data, matrix... | V-Sekai/V-Sekai.blender-game-tools | addons/faceit/core/shape_key_utils.py | shape_key_utils.py | py | 9,173 | python | en | code | 7 | github-code | 13 |
3423452850 | import streamlit as st
from st_aggrid import AgGrid, GridOptionsBuilder
from st_aggrid.shared import GridUpdateMode, DataReturnMode
from st_aggrid.shared import JsCode
import pandas as pd
import pickle
import os
from glob import glob
try:
import config
except:
from ntld import config
LOCATIONS = tuple(sorted(... | kthouz/streamlit_app | app.py | app.py | py | 2,957 | python | en | code | 0 | github-code | 13 |
14412323510 | # This file is part of Korman.
#
# Korman 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.
#
# Korman is distributed i... | H-uru/korman | korman/ui/ui_object.py | ui_object.py | py | 2,883 | python | en | code | 31 | github-code | 13 |
38474973195 | # 1
import math
def n_queen(n: int) -> [[int]]:
def helper(row):
if row == n:
result.append(list(col_placement))
return
else:
for col in range(n):
if all(abs(col - c) not in (0, row - i) for i, c in enumerate(col_placement[:row])):
... | bkgsur/Algo | prep/recursion.py | recursion.py | py | 3,158 | python | en | code | 0 | github-code | 13 |
70776602578 | import pandas as pd
import xarray as xr
import numpy as np
import geopandas as gpd
import plotly.express as px
import plotly.graph_objects as go
from shapely.geometry import Point
from geopandas import GeoDataFrame
from shapely.ops import nearest_points
from shapely.geometry import MultiPoint
#########################... | dorotheekar/choropleth-ipcc-projections | main.py | main.py | py | 14,852 | python | en | code | 1 | github-code | 13 |
35055076768 | from flask import Flask, render_template, request, redirect, url_for, flash
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'b64b8nqmxb1ttbufoxjg-mysql.services.clever-cloud.com'
app.config['MYSQL_USER'] = 'up1hh0qi2xsonjuq'
app.config['MYSQL_PASSWORD'] = 'a5nRziQvat1I7BeZ22np'
... | RONY4ALL/pago_servicio_eje3 | App.py | App.py | py | 2,862 | python | en | code | 0 | github-code | 13 |
72755437457 |
import numpy as np
from enum import Enum
def sRb(q):
sq, cq = np.sin(q), np.cos(q)
return np.array([
[cq, -sq],
[sq, cq]
])
class rphase(Enum):
""" enumerate for different phases in the jumping locomotion
"""
TD = 0 # touchdown
SQD = 1 # squat down
BOTTOM = 2 # bott... | Jarvis7923/raibert-hopper-sim | src/rd.py | rd.py | py | 12,950 | python | en | code | 1 | github-code | 13 |
42523544246 | """API for Numerai Signals"""
from typing import List, Dict
import os
import codecs
import decimal
from io import BytesIO
import requests
import pandas as pd
from numerapi import base_api
from numerapi import utils
SIGNALS_DOM = "https://numerai-signals-public-data.s3-us-west-2.amazonaws.com"
class SignalsAPI(bas... | nikampe/Numerai_Models | venv/lib/python3.9/site-packages/numerapi/signalsapi.py | signalsapi.py | py | 17,006 | python | en | code | 0 | github-code | 13 |
11375636224 | from cs50 import get_string
students = []
for i in range(3):
name = get_string("Name: ")
dorm = get_string("Dorm: ")
# key:value
student = {"name": name, "dorm": dorm}
students.append(student)
for student in students:
print(f"{student['name']} is in dorm {student['dorm']}") | lance-lh/learning-cs50 | pset6/struct0.py | struct0.py | py | 303 | python | en | code | 1 | github-code | 13 |
23034384142 | def merge(them):
"""
Given a collection of dictionaries,
recursively merge them and all of their list values
"""
if not isinstance(them, list):
return them
if len(them) == 0:
return {}
if len(them) == 1:
return them[0]
if len(them) > 2:
return merge(
... | gastrodon/terraform-compose | library/depends/tools.py | tools.py | py | 1,193 | python | en | code | 3 | github-code | 13 |
9921411463 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import datetime
import time
from collections import OrderedDict
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
from gi.repository import GObject
from Global import getFechas
# from Tree import Tree
class TreeSemana(Gtk.TreeView):
... | fdanesse/TimeControl | Info.py | Info.py | py | 5,479 | python | es | code | 0 | github-code | 13 |
16130023013 | import structlog
print("\n\t DEFAULT Renderer")
log = structlog.get_logger()
log.msg("first message")
log.msg("second message", whom="world", more_than_a_string=[1, 2, 3])
log.msg("third message", key="value!", more_than_strings=[1, 2, 3])
"""
2023-03-17 12:18:16 [info ] first message
2023-03-17 12:18:16 [info ... | udhayprakash/PythonMaterial | python3/12_Logging/b_structlog/b_log_rendering_formats.py | b_log_rendering_formats.py | py | 3,588 | python | en | code | 7 | github-code | 13 |
13520502436 | from PySide6.QtCore import QAbstractListModel, QModelIndex, Qt, Slot
from PySide6.QtWidgets import QFileDialog, QWidget
from mozregui.ui.addons_editor import Ui_AddonsEditor
class AddonsModel(QAbstractListModel):
"""
A Qt model that can edit addons path.
"""
def __init__(self, parent=None):
... | mozilla/mozregression | gui/mozregui/addons_editor.py | addons_editor.py | py | 2,225 | python | en | code | 165 | github-code | 13 |
39032860366 | import pandas as pd
import numpy as np
import os
import sys
import pickle
sys.path.append("./ml_auto/")
from data_utils import CatNumAgg, FreqEnc, gen_cat_cat
from custom_estimator import Estimator
from lightgbm import LGBMRegressor
DATA_DIR = "../data/"
df = pd.read_excel(os.path.join(DATA_DIR, "data.xlsx"), sheet... | harshsarda/LeadsPredictor | src/train.py | train.py | py | 4,110 | python | en | code | 0 | github-code | 13 |
28609379553 | #Question Link: https://takeuforward.org/data-structure/aggressive-cows-detailed-solution/
#Solution (Python3): Refer the below function
def aggressiveCows(stalls, k):
def ispossible(a, n, cows, minDist):
count = 1
lastPlacedCow = a[0]
for i in range(1,n):
if (a[i] - lastPlacedCow >= minDist):
... | AbhiWorkswithFlutter/StriverSDESheet-Python3-Solutions | Striver SDE Sheet/Day 11/Aggressive Cows.py | Aggressive Cows.py | py | 662 | python | en | code | 3 | github-code | 13 |
36260535792 | def molecule_bonds(molecule, session):
'''
Return bonds derived from residue templates where each bond is a pair of atom numbers.
Returned bonds are an N by 2 numpy array.
'''
bond_templates = session.bond_templates
if bond_templates is None:
session.bond_templates = bond_templates = Bon... | HamineOliveira/ChimeraX | src/apps/hydra/molecule/connect.py | connect.py | py | 8,229 | python | en | code | null | github-code | 13 |
6368029151 | import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import random
import os
import wolframalpha
import smtplib
engine=pyttsx3.init('sapi5')
voices=engine.getProperty('voices')
# print(voices[0].id)
engine.setProperty('voice',voices[0].id)
engine.setProperty... | crazy-cyber/Python-projects | jarvis/jarvis.py | jarvis.py | py | 8,604 | python | en | code | 0 | github-code | 13 |
26593523057 | import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
plt.rcParams['font.sans-serif'] = ['SimHei']
# legend(loc='upper left')
X_train = [[2015], [2016], [2017], [2018]]
y_train = [[7], [9]... | zxwtry/OJ | python/proj/chi/nihe_2.py | nihe_2.py | py | 2,179 | python | en | code | 5 | github-code | 13 |
8616331068 | import configparser
import datetime
import os
import subprocess
import sys
import numpy as np
import pandas as pd
class HRR(object):
def __init__(self, config, compile_=False):
""""
THis is a python-wrapper to handle HRR model in conjunction with a data assimilation module.
Small ... | windsor718/pyHRR | pyHRR.py | pyHRR.py | py | 4,965 | python | en | code | 0 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.