file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
nmap.py | #!/usr/bin/env python3
import argparse
import os
import subprocess
import sys
import datetime
from jackal import HostSearch, RangeSearch, Service, ServiceSearch, Logger
from jackal.config import Config
from jackal.utils import print_error, print_notification, print_success
from libnmap.parser import NmapParser, NmapPa... | parser = NmapParser()
report = parser.parse_fromstring(result)
imported_hosts = 0
imported_services = 0
for nmap_host in report.hosts:
if check_function(nmap_host):
imported_hosts += 1
host = host_search.id_to_object(nmap_host.address)
host.status = nmap_h... | random_line_split | |
nmap.py | #!/usr/bin/env python3
import argparse
import os
import subprocess
import sys
import datetime
from jackal import HostSearch, RangeSearch, Service, ServiceSearch, Logger
from jackal.config import Config
from jackal.utils import print_error, print_notification, print_success
from libnmap.parser import NmapParser, NmapPa... | ():
"""
Scans available smb services in the database for smb signing and ms17-010.
"""
service_search = ServiceSearch()
services = service_search.get_services(ports=['445'], tags=['!smb_vulnscan'], up=True)
services = [service for service in services]
service_dict = {}
for service in... | nmap_smb_vulnscan | identifier_name |
nmap.py | #!/usr/bin/env python3
import argparse
import os
import subprocess
import sys
import datetime
from jackal import HostSearch, RangeSearch, Service, ServiceSearch, Logger
from jackal.config import Config
from jackal.utils import print_error, print_notification, print_success
from libnmap.parser import NmapParser, NmapPa... |
for host in hosts:
host.add_tag('nmap_os')
host.save()
print_notification("Done, found the os of {} systems".format(count))
else:
print_notification("No systems found to be checked.")
if __name__ == '__main__':
os_discovery()
| for script_result in nmap_host.scripts_results:
script_result = script_result.get('elements', {})
host = host_dict[str(nmap_host.address)]
if 'fqdn' in script_result:
host.hostname.append(script_result['fqdn'])
if 'os' in script_result... | conditional_block |
nmap.py | #!/usr/bin/env python3
import argparse
import os
import subprocess
import sys
import datetime
from jackal import HostSearch, RangeSearch, Service, ServiceSearch, Logger
from jackal.config import Config
from jackal.utils import print_error, print_notification, print_success
from libnmap.parser import NmapParser, NmapPa... |
def include_up_hosts(nmap_host):
"""
Includes only hosts that have the status 'up'
"""
if nmap_host.status == 'up':
return True
return False
def nmap(nmap_args, ips):
"""
Start an nmap process with the given args on the given ips.
"""
config = Config()
argume... | """
Function to filter out hosts with hostnames
"""
if nmap_host.hostnames:
return True
return False | identifier_body |
tool.py | # USEFUL FUNC.(TOOL) IN IMSNG MODULE
# 2019.03.03 CREATED BY Gregory S.H. Paek
# 2019.08.29 UPDATED BY Gregory S.H. Paek
#============================================================
def timename():
'''
CONVERT 'TIME' TO YYMMDD, HHMMSS FORM.
INPUT : NONE
OUTPUT : STRIG FORM OF 'YYMMDD', 'HHMMSS'
'''
import numpy ... |
else:
sec = str(se)
yymmdd = yy+mm+dd
hhmmss = hour+mini+sec
return yymmdd, hhmmss
#------------------------------------------------------------
def detection(name, ra, dec, time, location):
import numpy as np
import os, glob, sys
from astropy import units as u
from astropy.time import Time
from astro... | sec = '0'+str(se) | conditional_block |
tool.py | # USEFUL FUNC.(TOOL) IN IMSNG MODULE
# 2019.03.03 CREATED BY Gregory S.H. Paek
# 2019.08.29 UPDATED BY Gregory S.H. Paek
#============================================================
def timename():
'''
CONVERT 'TIME' TO YYMMDD, HHMMSS FORM.
INPUT : NONE
OUTPUT : STRIG FORM OF 'YYMMDD', 'HHMMSS'
'''
import numpy ... | ERROR: type should be large_string, got "\thttps://cpuu.postype.com/post/23066\n\tCode reference\n\thttps://kimdoky.github.io/python/2017/07/21/smtplib_email.html\n\tFile attach\n\thttps://brunch.co.kr/@jk-lab/31\n\t'''\n\timport smtplib\n\tfrom email.mime.text import MIMEText\n\timport codecs\n\temail_text = codecs.open(filename, 'rb', 'utf-8')\n\tmsg = MIMEText(email_text.read())\n\temail_text.close()\n\tmsg['Subject']\t= subject\n\tmsg['From']\t\t= sendID\n\tsmtp_gmail\t\t= smtplib.SMTP_SSL('smtp.gmail.com', 465)\n\tsmtp_gmail.login(sendID, sendPW)\n\tsmtp_gmail.sendmail(sendID, reciver, msg.as_string())\n\tsmtp_gmail.quit()\n\tcomment\t= 'Send '+filename+'\\n'+'From '+sendID+' To '+reciver; print(comment)\n#------------------------------------------------------------\ndef send_gmail(subject, contents, fromID, fromPW, toIDs, ccIDs=None, path=None):\n\t'''\n\tSEND GMAIL\n\tSecurity reference\n\thttps://cpuu.postype.com/post/23066\n\tCode reference\n\thttps://kimdoky.github.io/python/2017/07/21/smtplib_email.html\n\tFile attach\n\thttps://brunch.co.kr/@jk-lab/31\n\t'''\n\timport os\n\timport smtplib\n\tfrom email.mime.base import MIMEBase\n\tfrom email.mime.text import MIMEText\n\tfrom email.mime.multipart import MIMEMultipart\n\tfrom email.header import Header \n\t#msg\t\t= MIMEBase('mixed')\n\t#msg\t\t= MIMEText(contents, 'plain', 'utf-8')\n\tmsg\t\t= MIMEMultipart()\n\tmsg['Subject']\t= Header(s=subject, charset=\"utf-8\")\n\tmsg['From']\t\t= fromID\n\tmsg['To']\t\t= toIDs\n\tif ccIDs != None:\n\t\tmsg['Cc']\t\t= ccIDs\n\tmsg.attach(MIMEText(contents, 'plain', 'utf-8'))\n\t#\tATTACH TEXT FILE ON MAIL\n\tif path != None:\n\t\tif type(path) != list:\n\t\t\tfilelist\t= []\n\t\t\tfilelist.append(path)\n\t\telse:\n\t\t\tfilelist\t= path\n\n\t\tfor file in filelist:\n\t\t\tpart\t= MIMEBase(\"application\", \"octet-stream\")\n\t\t\tpart.set_payload(open(file, 'rb').read())\n\t\t\tpart.add_header(\t'Content-Disposition',\n\t\t\t\t\t\t\t\t'attachment; filename=\"%s\"'% os.path.basename(file))\n\t\t\tmsg.attach(part)\n\t\n\n\n\t#\tACCESS TO GMAIL & SEND MAIL\n\tsmtp_gmail\t\t= smtplib.SMTP_SSL('smtp.gmail.com', 465)\n\tsmtp_gmail.login(fromID, fromPW)\n\tsmtp_gmail.sendmail(msg[\"From\"], msg[\"To\"].split(\",\") + msg[\"Cc\"].split(\",\"), msg.as_string())\n\tsmtp_gmail.quit()\n\tcomment\t= 'Send '+str(path)+'\\nFrom\\t'+fromID+'\\nTo'; print(comment); print(toIDs)\n#------------------------------------------------------------\ndef abs2app(mag, magerr, gwdist, gwdiststd):\n\timport numpy as np\n\tapp\t\t= 5*np.log10(gwdist)-5+mag\n\tapperr\t= 5*gwdiststd/(gwdist*np.log(10))\n\treturn app, apperr\n#------------------------------------------------------------\ndef GW170817_like(gwdist, gwdiststd):\n\timport numpy as np\n\tm0\t\t= 17.476\t#\t[AB] in i-band (t0+10h)\n\tm0err\t= 0.018\t\n\tdist0\t= 38.4\t\t#\t[MPC]\tIm et al. 2017\n\tdist0err= 8.9\n\tm\t\t= m0+5.*np.log10(gwdist/dist0)\n\tmerr\t= np.sqrt( (m0err)**2 + ((5.*gwdiststd)/(gwdist*np.log(10)))**2 + ((5.*dist0err)/(dist0*np.log(10)))**2 )\n\treturn m, merr\n#------------------------------------------------------------\ndef func_linear(a, x, scaling=[0, 0]):\n\txpt, ypt= scaling[0], scaling[1]\n\tydel\t= ypt - (-1*a*xpt)\n\treturn -1*a*x + ydel\n#------------------------------------------------------------\ndef calc_app(mag, magerr, gwdist0, gwdiststd0, gwdist1, gwdiststd1):\n\timport numpy as np\n\tapp\t\t= mag+5*np.log10(gwdist1/gwdist0)\n\tapperr\t= np.sqrt( (magerr)**2 + ((5*gwdiststd1)/(np.log(5)*gwdist1))**2 + ((5*gwdiststd0)/(np.log(5)*gwdist0))**2 )\n\treturn app, apperr\n#------------------------------------------------------------\ndef ds9regmaker(filename, name, ra, dec):\n\timport os,sys\n\timport string\n\tfrom astropy.io import ascii \n\timport numpy as np\n\timport math\n\t'''\n\tracol\t\t= 'ALPHA_J2000'\n\tdeccol\t\t= 'DELTA_J2000'\n\tname\t\t= 'NUMBER'\n\tintbl\t\t= ascii.read(filename)\n\t'''\n\tradius\t= \"\"\" 5\" \"\"\"\n\tcolor\t= \"green\"\n\tf\t\t= open(filename, 'w')\n\n\thead1\t= \"# Region file format: DS9 version 4.1\\n\"\n\thead2\t= \"\"\"global color=green dashlist=8 3 width=1 font=\"helvetica 10 normal roman\" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1\\n\"\"\"\n\thead3\t= \"fk5\\n\"\n\n\tf.write(head1)\n\tf.write(head2)\n\tf.write(head3)\n\n\tfor n in range(len(ra)):\n\t\tbody=\"circle(\"+str(ra[n])+\",\"+str(dec[n])+\",\"+radius+\") # color=\"+color+\" text={\"+str(name[n])+\"}\\n\"\t\n\t\tf.write(body)\n\tf.close()\n#------------------------------------------------------------\ndef rtsmaker(observatory, headname, save_path, obspath, catpath, start, end, altlimit=30., moonseperation=40., sunlimit='-18', numlimit=100):\n\timport pytz\n\timport jdcal\n\timport ephem\n\t#from numpy import *\n\timport numpy as np\n\timport os, sys\n\timport string\n\timport datetime\n\timport astropy.units as u\n\tfrom astropy.io import ascii\n\timport mskpy.observing as obs\n\timport astropy.coordinates as coord\n\tfrom astropy import units as u\n\tfrom astropy.coordinates import SkyCoord\n\n\t#------------------------------------------------------------#\n\t#\tINPUT SAMPLE\n\t#------------------------------------------------------------#\n\t'''\n\tobservatory\t\t= 'SAO'\n\tsave_path\t\t= './'\n\tobspath\t\t\t= \"/home/gw/Research/observatory.txt\"\n\tcatpath\t\t\t= 'MS181101ab_Preliminary-all_candidates.txt'\n\tstart\t\t\t= '2019/04/17'\n\tend\t\t\t\t= '2019/04/19'\n\t#altitute limit and moon seperation, moon serperation is a little bit close (2~3 deg)\n\tnumlimit\t\t= 100\n\taltlimit\t\t= 30.\n\tmoonseperation\t= 40.\n\tsunlimit\t\t= '-18'\n\t'''\n\t#------------------------------------------------------------#\n\t#\tOBSERVATORY INFO.\n\t#------------------------------------------------------------#\n\tobsinfo\t\t\t= ascii.read(obspath)\n\tobsname \t= np.copy(obsinfo['name'])\n\tobsindex\t\t= np.where(obsname == observatory)[0]\n\tobslat\t\t\t= (np.copy(obsinfo['latitude(N+)'])[obsindex])[0]\n\tobslon\t\t\t= (np.copy(obsinfo['longitude(E+)'])[obsindex])[0]\n\tobsalt\t\t\t= (np.copy(obsinfo['altitude'])[obsindex])[0]\n\tobstz\t\t\t= (np.copy(obsinfo['timezone'])[obsindex])[0]\n\ttz\t\t\t\t= pytz.timezone(obstz)\n\t#------------------------------------------------------------#\n\tobserv\t\t\t= ephem.Observer()\n\tobserv.lat\t\t= str(obslat)\n\tobserv.lon\t\t= str(obslon)\n\tobserv.elevation= obsalt\n\tobserv.horizon\t= sunlimit\n\t#------------------------------------------------------------#\n\t#objects from catalog file\n\ttdata\t\t\t= ascii.read(catpath)\n\tobjname\t\t\t= tdata['name']\n\tra\t\t\t\t= tdata['ra']\n\tdec\t\t\t\t= tdata['dec']\n\tprior\t\t\t= tdata['sort']\n\trank\t\t\t= tdata['rank']\t\t\t\n\tdist\t\t\t= tdata['dist']\n\n\tRA\t\t\t\t= coord.Angle(ra, unit = u.deg)\n\tDec\t\t\t\t= coord.Angle(dec, unit = u.deg)\n\n\tradd\t\t\t= RA.value\n\trad\t\t\t\t= RA.hour\n\tdecd\t\t\t= Dec.value\n\tdecdd\t\t\t= Dec.degree\n\n\t#angular distance calculation\n\tdef angsep(ra1deg, dec1deg, ra2deg, dec2deg) : \n\t\tra1rad\t\t= ra1deg*np.pi/180\n\t\tdec1rad\t\t= dec1deg*np.pi/180\n\t\tra2rad\t\t= ra2deg*np.pi/180\n\t\tdec2rad\t\t= dec2deg*np.pi/180\n\t\tcos_a\t\t= np.sin(dec1rad)*np.sin(dec2rad)+(np.cos(dec1rad)*np.cos(dec2rad)*np.cos(ra1rad-ra2rad))\n\t\tanglesep\t= np.arccos(cos_a)*180/np.pi\n\t\treturn anglesep\n\n\t#dates to calculate\n\tfmt\t\t\t\t= '%Y/%m/%d'\n\tstartdt\t\t\t= datetime.datetime.strptime(start, fmt)\n\tenddt\t\t\t= datetime.datetime.strptime(end, fmt)\n\tstartmjd\t\t= (jdcal.gcal2jd(startdt.year, startdt.month, startdt.day))[1]\n\tendmjd\t\t\t= (jdcal.gcal2jd(enddt.year, enddt.month, enddt.day))[1]\n\n\tfor i in range(int(endmjd-startmjd+1)):\n\t\tonedaymjd = startmjd+i+1\n\t\toneday = jdcal.jd2gcal(2400000.5, onedaymjd)\n\t\tonedaydt = datetime.datetime(oneday[0], oneday[1], oneday[2])\n\t\tdst = tz.dst(onedaydt, is_dst=True)\n\t\tdst = dst.seconds/3600\n\n\t\tonedaydt = datetime.datetime(oneday[0], oneday[1], oneday[2], tzinfo=tz)\n\t\tonedayutc = onedaydt.astimezone(pytz.utc)\n\t\tobserv.date = onedayutc\n\n\t\t# Moon distance and information\n\t\tmcoord\t\t= ephem.Moon()\n\t\tmcoord.compute(observ)\n\t\tminfo\t\t= 'Moon ra, dec : '+str(mcoord.ra)+' '+str(mcoord.dec)+'\\n'\n\t\tmphase\t\t= ephem.Moon(observ.date)\n\t\tmphasestr\t= 'Moon phase : '+ \"%.2f\" % mphase.moon_phase +'\\n'\n\t\tmsep\t\t= angsep(radd, decdd, np.degrees(mcoord.ra), np.degrees(mcoord.dec))\n\n\t\t#\tSUNSET CALC.\n\t\tsunset = observ.previous_setting(ephem.Sun())\n\t\tsunsettu = ephem.Date.tuple(sunset)\n\t\tsunsetdt = datetime.datetime(sunsettu[0],sunsettu[1],sunsettu[2],sunsettu[3],int(sunsettu[4]),tzinfo=pytz.utc)\n\t\tsunsetlocal = sunsetdt.astimezone(tz)\n\t\tsunsetstr = sunlimit+' deg sunset : '+str(sunsetlocal.hour)+':'+str(sunsetlocal.minute)+'\\n'\n\t\tsunsethour = sunsetlocal.hour+sunsetlocal.minute/60.+sunsetlocal.second/3600.\n\t\t#\tSUNRISE CALC.\n\t\tsunrise = observ.next_rising(ephem.Sun())\n\t\tsunrisetu = ephem.Date.tuple(sunrise)\n\t\tsunrisedt = datetime.datetime(sunrisetu[0],sunrisetu[1],sunrisetu[2],sunrisetu[3],int(sunrisetu[4]),tzinfo=pytz.utc)\n\t\tsunriselocal = sunrisedt.astimezone(tz)\n\t\tsunrisestr = sunlimit+' deg sunrise : '+str(sunriselocal.hour)+':'+str(sunriselocal.minute)+'\\n'\n\t\tsunrisehour = sunriselocal.hour+sunriselocal.minute/60.+sunriselocal.second/3600.\n\t\t#print (observatory)\n\t\t#print ('Local mid night in UTC : '+str(observ.date))\n\t\t#print (minfo,mphasestr,sunsetstr,sunrisestr)\n\n\t\t#\tMAKE RESULT FILE\n\t\tstryear = str(oneday[0])\n\t\tstrmonth = str(oneday[1])\n\t\tstrday = str(oneday[2]-1)\n\t\tif int(strmonth) < 10 : strmonth = '0'+strmonth\n\t\tif int(strday) < 10 : strday = '0'+strday\n\n\t\tf\t\t\t= open(save_path+'/'+headname+'-'+stryear+strmonth+strday+\"-rts_vis-\"+observatory+\".txt\",'w')\n\t\tf.write('#\\t'+str(observ.date)+' UTC & Day Time Saving +'+str(dst)+'\\n')\n\t\tf.write('#\\tObservatory\\t= '+observatory+'\\n')\n\t\tf.write('#\\t'+sunsetstr)\n\t\tf.write('#\\t'+sunrisestr)\n\t\tf.write('#\\t'+minfo)\n\t\tf.write('#\\t'+mphasestr)\n\t\tf.write('#\\tMoon seperation = '+str(moonseperation)+'\\n')\n\t\tf.write('#\\tAltitude limit = '+str(altlimit)+'\\n')\n\t\tf.write('#\\tRank : the lower rank, the higher priority\\n')\n\t\tf.write('#------------------------------------------------------- \\n')\n\t\tf.write('name ra dec rise(LT) transit(LT) set(LT) moon_dist(deg) distance(Mpc) rank\\n')\n\n\t\tnumcount\t= 0\n\t\tfor n in range(len(rad)):\n\t\t\t#calculate rise transit set time with altitute limit\n\t\t\tparam_rts\t= dict(\tra=radd[n],\n\t\t\t\t\t\t\t\tdec=decdd[n],\n\t\t\t\t\t\t\t\tdate=onedaydt,\n\t\t\t\t\t\t\t\tlon=obslon,\n\t\t\t\t\t\t\t\tlat=obslat,\n\t\t\t\t\t\t\t\ttz=obstz,\n\t\t\t\t\t\t\t\tlimit=altlimit,\n\t\t\t\t\t\t\t\tprecision=1440)\n\t\t\trtscal\t\t= obs.rts(**param_rts)\n\t\t\trt\t\t\t= rtscal[0]\n\t\t\ttt\t\t\t= rtscal[1]\n\t\t\tst\t\t\t= rtscal[2]\n\t\t\tif rtscal[0]== None:\n\t\t\t\t#print (objname[n],ra[n],dec[n], rtscal[0], rtscal[1], rtscal[2],\"%.2f\" % msep[n])\n\t\t\t\tpass\n\t\t\telif sunrisehour < rtscal[0] < sunsethour and sunrisehour < rtscal[2] < sunsethour and sunrisehour < rtscal[1] < sunsethour: \n\t\t\t\t#print (objname[n]+' It can be seen in daytime!')\n\t\t\t\tpass\n\t\t\telif msep[n] < moonseperation or msep[n] > 360-moonseperation:\n\t\t\t\t#print (objname[n]+' too close to Moon < '+str(moonseperation)+' deg')\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tif numcount < numlimit:\n\t\t\t\t\tc= SkyCoord(ra=ra[n]*u.degree, dec=dec[n]*u.degree, frame='icrs')\n\t\t\t\t\tc_ra= c.ra.hms\n\t\t\t\t\tc_dec= c.dec.dms\n\t\t\t\t\t\n\t\t\t\t\tnra='%02d:%02d:%.3f' %(c_ra[0], abs(c_ra[1]), abs(c_ra[2]))\n\t\t\t\t\tndec='%02d:%02d:%.3f' %(c_dec[0], abs(c_dec[1]), abs(c_dec[2]))\n\t\t\t\t\t\n\t\t\t\t\trtp\t=\"%.2d\" % int(rt)+':'+\"%.2d\" % int((rt-int(rt))*60)\n\t\t\t\t\tttp\t=\"%.2d\" % int(tt)+':'+\"%.2d\" % int((tt-int(tt))*60)\n\t\t\t\t\tstp\t=\"%.2d\" % int(st)+':'+\"%.2d\" % int((st-int(st))*60)\n\t\t\t\t\tvis\t='{:8s}\t{:12s}\t{:12s}\t{:5s}\t{:5s}\t{:5s}\t{:3s}\t\t{:4s}\t{:4s}'.format(objname[n],str(nra),str(ndec),rtp,ttp,stp,str(int(msep[n])),str(int(dist[n])),str(rank[n]))+'\\n'\n\t\t\t\t\tf.write(vis)\n\t\t\t\t\t#print (objname[n],ra[n],dec[n], rtp,ttp,stp,\"%.2f\" % msep[n])\n\t\t\t\t\tnumcount+= 1\n\t\t\t\telse:\n\t\t\t\t\tpass\n\t\t\t\t'''\n\t\t\t\tif numcount < numlimit:\n\t\t\t\t\t\n\t\t\t\t\trtp=\"%.2d\" % int(rt)+':'+\"%.2d\" % int((rt-int(rt))*60)\n\t\t\t\t\tttp=\"%.2d\" % int(tt)+':'+\"%.2d\" % int((tt-int(tt))*60)\n\t\t\t\t\tstp=\"%.2d\" % int(st)+':'+\"%.2d\" % int((st-int(st))*60)\n\t\t\t\t\tvis='{:24s}\t{:12s}\t{:12s}\t{:5s}\t{:5s}\t{:5s}\t{:3s}\t{:2s}'.format(objname[n],str(ra[n]),str(dec[n]),rtp,ttp,stp,str(int(msep[n])),str(prior[n]))+'\\n'\n\t\t\t\t\tf.write(vis)\n\t\t\t\t\t#print (objname[n],ra[n],dec[n], rtp,ttp,stp,\"%.2f\" % msep[n])\n\t\t\t\t\tnumcount+= 1\n\t\t\t\telse:\n\t\t\t\t\tpass\n\t\t\t\t'''\n\t\tf.close()" | #------------------------------------------------------------
def sendmail(filename, subject, sendID, sendPW, reciver):
'''
Security reference | random_line_split |
tool.py | # USEFUL FUNC.(TOOL) IN IMSNG MODULE
# 2019.03.03 CREATED BY Gregory S.H. Paek
# 2019.08.29 UPDATED BY Gregory S.H. Paek
#============================================================
def | ():
'''
CONVERT 'TIME' TO YYMMDD, HHMMSS FORM.
INPUT : NONE
OUTPUT : STRIG FORM OF 'YYMMDD', 'HHMMSS'
'''
import numpy as np
import time
now = time.gmtime(time.time())
y, m, d = now.tm_year, now.tm_mon, now.tm_mday
ho, mi, se = now.tm_hour, now.tm_min, now.tm_sec
yy = str(y)[2:]
if len(str(m)) < 2:... | timename | identifier_name |
tool.py | # USEFUL FUNC.(TOOL) IN IMSNG MODULE
# 2019.03.03 CREATED BY Gregory S.H. Paek
# 2019.08.29 UPDATED BY Gregory S.H. Paek
#============================================================
def timename():
'''
CONVERT 'TIME' TO YYMMDD, HHMMSS FORM.
INPUT : NONE
OUTPUT : STRIG FORM OF 'YYMMDD', 'HHMMSS'
'''
import numpy ... | import pytz
import jdcal
import ephem
#from numpy import *
import numpy as np
import os, sys
import string
import datetime
import astropy.units as u
from astropy.io import ascii
import mskpy.observing as obs
import astropy.coordinates as coord
from astropy import units as u
from astropy.coordinates import ... | identifier_body | |
retina_loss.py | import torch.nn as nn
import torch
from model.retina_config import DefaultConfig
import numpy as np
def | (image_shape,stride):
'''
transfor one fmap coords to orig coords
Args
featurn [batch_size,h,w,c]
stride int
Returns
coords [n,2]
'''
h,w= image_shape
shifts_x = torch.arange(0, w * stride, stride, dtype=torch.float32)
shifts_y = torch.arange(0, h * stride, stride, dtype=torc... | coords_fmap2orig | identifier_name |
retina_loss.py | import torch.nn as nn
import torch
from model.retina_config import DefaultConfig
import numpy as np
def coords_fmap2orig(image_shape,stride):
'''
transfor one fmap coords to orig coords
Args
featurn [batch_size,h,w,c]
stride int
Returns
coords [n,2]
'''
h,w= image_shape
shifts_x... |
def forward(self, inputs):
"""
cls_logits :(n, sum(H*W)*A, class_num+1)
reg_preds:(n, sum(H*W)*A, 4)
anchors:(sum(H*W)*A, 4)
boxes:(n, max_num, 4)
classes:(n, max_num)
"""
cls_logits, reg_preds, anchors, boxes, classes = inputs
anchor_widths ... | super(LOSS, self).__init__()
self.reg_mode = reg_mode | identifier_body |
retina_loss.py | import torch.nn as nn
import torch
from model.retina_config import DefaultConfig
import numpy as np
def coords_fmap2orig(image_shape,stride):
'''
transfor one fmap coords to orig coords
Args
featurn [batch_size,h,w,c]
stride int
Returns
coords [n,2]
'''
h,w= image_shape
shifts_x... | reg_loss = torch.tensor(0).float().cuda()
else:
reg_loss = torch.tensor(0).float()
return reg_loss
def compute_giou_loss(boxes1, boxes2):
"""
boxes1 :(N,4) (x1,y1,x2,y2)
boxes2: (N,4) (x1,y1,x2,y2)
"""
x1y1 = torch.max(boxes1[:, :2], boxes2[:, :2])
x2y2 = ... |
preds_boxes = torch.stack([pred_x1,pred_y1,pred_x2,pred_y2], dim=0).t() #(num_pos,4)
reg_loss = compute_giou_loss(gt_boxes, preds_boxes)
else:
if torch.cuda.is_available(): | random_line_split |
retina_loss.py | import torch.nn as nn
import torch
from model.retina_config import DefaultConfig
import numpy as np
def coords_fmap2orig(image_shape,stride):
'''
transfor one fmap coords to orig coords
Args
featurn [batch_size,h,w,c]
stride int
Returns
coords [n,2]
'''
h,w= image_shape
shifts_x... |
else:
reg_loss = torch.tensor(0).float()
return reg_loss
def compute_giou_loss(boxes1, boxes2):
"""
boxes1 :(N,4) (x1,y1,x2,y2)
boxes2: (N,4) (x1,y1,x2,y2)
"""
x1y1 = torch.max(boxes1[:, :2], boxes2[:, :2])
x2y2 = torch.min(boxes1[:, 2:], boxes2[:, 2:])
wh = torc... | reg_loss = torch.tensor(0).float().cuda() | conditional_block |
preprocess_lidc1.py | import numpy as np
import scipy.ndimage
import matplotlib.pyplot as plt
import pylidc as pl
import warnings
import pickle
from tqdm import tqdm
import glob
import random
import threading
warnings.filterwarnings("ignore")
from joblib import Parallel, delayed
NEW_SPACING= (1.4,1.4,2.)
PROCESSED_DIR = '/home/ronens1/li... | cluster_group=[]
for ann in cluster:
diameter = ann.estimate_diameter()
features = ann.feature_vals()
c = ann.centroid()
c[:2]=c[:2]*np.array(spacing[:2])
c[2] = c[2]-z0
c = c/np.array(NEW_SPACING)
b = ann.bbox()
... | for cluster in clusters: | random_line_split |
preprocess_lidc1.py | import numpy as np
import scipy.ndimage
import matplotlib.pyplot as plt
import pylidc as pl
import warnings
import pickle
from tqdm import tqdm
import glob
import random
import threading
warnings.filterwarnings("ignore")
from joblib import Parallel, delayed
NEW_SPACING= (1.4,1.4,2.)
PROCESSED_DIR = '/home/ronens1/li... |
def shift_radius(shift):
r = 100
while r > shift:
v = np.random.uniform(-shift,high=shift,size=(3,))
r = np.linalg.norm(v)
vox_shift = (v/np.array(NEW_SPACING)).astype(int)
return vox_shift
def find_nodule(annotation,min_agreement):
good_clusters = [cluster for cluster in annotation if len(clus... | Focus_radius = 30 # mm
dist = np.linalg.norm( (np.array(pos)-np.array(centroid))*np.array(NEW_SPACING))/Focus_radius
return max(1-dist,0) | identifier_body |
preprocess_lidc1.py | import numpy as np
import scipy.ndimage
import matplotlib.pyplot as plt
import pylidc as pl
import warnings
import pickle
from tqdm import tqdm
import glob
import random
import threading
warnings.filterwarnings("ignore")
from joblib import Parallel, delayed
NEW_SPACING= (1.4,1.4,2.)
PROCESSED_DIR = '/home/ronens1/li... |
perm = range(len(annotations))
random.shuffle(perm)
data = [data[i] for i in perm]
annotations= [annotations[i] for i in perm]
data=np.asarray(data)
return data,annotations
def soft_focus(pos,centroid):
Focus_radius = 30 # mm
dist = np.linalg.norm( (np.array(pos)-np.array(centroid))*n... | data.append(np.load(name))
annotation_file_name = '.'.join(name.split('.')[:-1])+'annotation.txt'
with open(annotation_file_name,'r') as pickle_file:
annotations.append(pickle.load(pickle_file)) | conditional_block |
preprocess_lidc1.py | import numpy as np
import scipy.ndimage
import matplotlib.pyplot as plt
import pylidc as pl
import warnings
import pickle
from tqdm import tqdm
import glob
import random
import threading
warnings.filterwarnings("ignore")
from joblib import Parallel, delayed
NEW_SPACING= (1.4,1.4,2.)
PROCESSED_DIR = '/home/ronens1/li... | (shift):
r = 100
while r > shift:
v = np.random.uniform(-shift,high=shift,size=(3,))
r = np.linalg.norm(v)
vox_shift = (v/np.array(NEW_SPACING)).astype(int)
return vox_shift
def find_nodule(annotation,min_agreement):
good_clusters = [cluster for cluster in annotation if len(cluster)>=min_agreement... | shift_radius | identifier_name |
kinematics.py | # -*- coding: utf-8 -*-
"""
Kinematics analysis: multiple trials - single subject
Simon Marchant 2017
"""
import csv
import numpy as np
import pickle
def csvread(file):
"""
Read a CSV file and output a numpy array object of that file.
|
def tableread(filelist, start, frames, onlyinclude=''):
"""
Read a list of lists, from a Nexus CSV export, to extract vector data.
Output is a dictionary of lists.
Inputs:-
filelist = the data
start = the row number where data to be read starts
frames = dict of Start and End fra... | """
thisfile = open(file)
thisreader = csv.reader(thisfile)
filelist = np.array(list(thisreader))
return filelist
| random_line_split |
kinematics.py | # -*- coding: utf-8 -*-
"""
Kinematics analysis: multiple trials - single subject
Simon Marchant 2017
"""
import csv
import numpy as np
import pickle
def csvread(file):
"""
Read a CSV file and output a numpy array object of that file.
"""
thisfile = open(file)
thisreader = csv.rea... |
for m in range(len(array[n])):
try:
if line[m] == 'del':
del line[m]
except IndexError:
continue
array[n] = line[0:shortest]
return array
if __name__ == '__main__':
trials = ['OW... | if m % cut == 0 and m != 0:
line[m] = 'del' | conditional_block |
kinematics.py | # -*- coding: utf-8 -*-
"""
Kinematics analysis: multiple trials - single subject
Simon Marchant 2017
"""
import csv
import numpy as np
import pickle
def csvread(file):
"""
Read a CSV file and output a numpy array object of that file.
"""
thisfile = open(file)
thisreader = csv.rea... | (array):
"""
Make numpy array rows the same length by shortening long ones.
"""
lengths = [len(x) for x in array]
#shortindex = lengths.index(min(lengths))
shortest = min(lengths)
for n in range(len(array)):
line = array[n]
if len(array[n]) != shortest:
... | arraycleaner | identifier_name |
kinematics.py | # -*- coding: utf-8 -*-
"""
Kinematics analysis: multiple trials - single subject
Simon Marchant 2017
"""
import csv
import numpy as np
import pickle
def csvread(file):
"""
Read a CSV file and output a numpy array object of that file.
"""
thisfile = open(file)
thisreader = csv.rea... |
def arraycleaner(array):
"""
Make numpy array rows the same length by shortening long ones.
"""
lengths = [len(x) for x in array]
#shortindex = lengths.index(min(lengths))
shortest = min(lengths)
for n in range(len(array)):
line = array[n]
if len(array[n]) != sho... | """
Returns the minimum foot clearance in middle of swing in marked stride.
Inputs: Toe marker Z (list), Start frame, foot off frame, end frame, start fraction of mid swing, end fraction of mid swing.
Output: minimum clearance, frame it occurs at.
"""
swing = ToeZ[FootOff:EndFrame]
ground ... | identifier_body |
client.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
import urllib2
import urllib
import time
import re
import httplib
import sys
import os
import socket
import cStringIO
#import io
from PIL import Image #dont use import Image ,maybe different
socket.setdefaulttimeout(15) #global
reload(sys)
sys.setdefaultencoding('u... | OnSaveConf, button1)
self.Bind(wx.EVT_BUTTON, self.OnCancel, button2)
vbox = wx.BoxSizer(wx.VERTICAL)
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
hbox2 = wx.BoxSizer(wx.HORIZONTAL)
hbox3 = wx.BoxSizer(wx.HORIZONTAL)
hbox4 = wx.BoxSizer(wx.HORIZONTAL)
hbox1.Add(ipLabel,flag=wx.LEFT,border=8)
hbox1.Add(self.ipT... | identifier_body | |
client.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
import urllib2
import urllib
import time
import re
import httplib
import sys
import os
import socket
import cStringIO
#import io
from PIL import Image #dont use import Image ,maybe different
socket.setdefaulttimeout(15) #global
reload(sys)
sys.setdefaultencoding('u... | SaveAs(self, event):
# ๅผนๅบๆไปถไฟๅญๅฏน่ฏๆก
file_wildcard="txt files(*.txt)|*.txt|All files(*.*)|*.*"
dlg = wx.FileDialog(self,"Save file as ...", style = wx.SAVE | wx.OVERWRITE_PROMPT,wildcard = file_wildcard)
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetPath().encode('utf-8')
#if not os.path.splitex... | text)
fh.close()
def On | conditional_block |
client.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
import urllib2
import urllib
import time
import re
import httplib
import sys
import os
import socket
import cStringIO
#import io
from PIL import Image #dont use import Image ,maybe different
socket.setdefaulttimeout(15) #global
reload(sys)
sys.setdefaultencoding('u... | hbox4.Add(button2,flag=wx.ALIGN_LEFT|wx.LEFT,border=8)
vbox.Add(hbox4,flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.Bottom,border=10)
panel.SetSizer(vbox)
self.loadConf() #ๅ ่ฝฝ้
็ฝฎๆไปถ๏ผๆพ็คบๅจ็้ข
def loadConf(self):
fh=open('server.conf')
size=len(fh.read())
fh.seek(0)
while(fh.tell()!=size):
data=fh.readline()
if(dat... | vbox.Add((-1, 50))
hbox4.Add(button1,flag=wx.LEFT,border=18) | random_line_split |
client.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
import urllib2
import urllib
import time
import re
import httplib
import sys
import os
import socket
import cStringIO
#import io
from PIL import Image #dont use import Image ,maybe different
socket.setdefaulttimeout(15) #global
reload(sys)
sys.setdefaultencoding('u... | button1)
self.Bind(wx.EVT_BUTTON, self.OnCancel, button2)
vbox = wx.BoxSizer(wx.VERTICAL)
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
hbox2 = wx.BoxSizer(wx.HORIZONTAL)
hbox3 = wx.BoxSizer(wx.HORIZONTAL)
hbox4 = wx.BoxSizer(wx.HORIZONTAL)
hbox1.Add(ipLabel,flag=wx.LEFT,border=8)
hbox1.Add(self.ipText,proporti... | veConf, | identifier_name |
ftp_manage.py | #!/usr/bin/python3
#@Author:CaiDeyang
#@Time: 2018/9/14 7:36
import os
import time
import pickle
import hashlib
from conf import settings
from modules.files import Files
def get_md5(data, type="str"):
m = hashlib.md5()
if type == "str":
m.update(data.encode('utf-8'))
elif type == "file":
i... |
res2 = pickle.loads(self.conn.recv(8192))
# print(res2)
seek_place = res2['seek_place'] # ่ทๅๅฎขๆท็ซฏ่ฎฉๅผๅงไผ ่พ็ไฝ็ฝฎ
to_send_size = file_size - seek_place #้่ฆๅ้็ๅญ่ๆฐ
# print(to_send_size)
with open(abs_file,'rb') as f:
f.seek(seek_place)
... | ze": file_size }
self.conn.send(pickle.dumps(res))
# ๆฅๆถๅฎขๆท็ซฏๅผๅงไผ ่พ็ๆไปค | conditional_block |
ftp_manage.py | #!/usr/bin/python3
#@Author:CaiDeyang
#@Time: 2018/9/14 7:36
import os
import time
import pickle
import hashlib
from conf import settings
from modules.files import Files
def get_md5(data, type="str"):
m = hashlib.md5()
if type == "str":
m.update(data.encode('utf-8'))
elif type == "file":
i... | self.user_info = get_info(self.name)
# print(self.user_info.__dict__)
if self.user_info.password == password:
self.is_certified = True
self.current_path = self.user_info.current_path
send_data['response']['msg'] = "่ฎค่ฏๆๅ๏ผ"
el... | random_line_split | |
ftp_manage.py | #!/usr/bin/python3
#@Author:CaiDeyang
#@Time: 2018/9/14 7:36
import os
import time
import pickle
import hashlib
from conf import settings
from modules.files import Files
def get_md5(data, type="str"):
m = hashlib.md5()
if type == "str":
m.update(data.encode('utf-8'))
elif type == "file":
i... | ath
# self.conn.send(msg.encode('utf-8'))
return msg.encode('utf-8')
def mkdir(self, request):
print(request)
new_dir = request.split()[1]
abs_path = os.path.join(settings.BaseDir, self.current_path)
if new_dir in os.listdir(abs_path):
msg = "่ฏฅ็ฎๅฝๅๅทฒ็ป่ขซๅ ็จ๏ผ"
... | ame = request['name']
password = request['password']
send_data = {}
send_data['action'] = 'login'
send_data['response'] = {}
if self.name in os.listdir(settings.db):
self.user_info = get_info(self.name)
# print(self.user_info.__dict__)
if self.... | identifier_body |
ftp_manage.py | #!/usr/bin/python3
#@Author:CaiDeyang
#@Time: 2018/9/14 7:36
import os
import time
import pickle
import hashlib
from conf import settings
from modules.files import Files
def get_md5(data, type="str"):
m = hashlib.md5()
if type == "str":
m.update(data.encode('utf-8'))
elif type == "file":
i... | ():
def __init__(self, conn):
# ่ฏปๅๆฐๆฎๅบ
# self.name = None
self.conn = conn
self.is_certified = False # ๆฏๅฆๅทฒ็ป่ฎค่ฏ
self.current_path = None # ๅฝๅ่ทฏๅพ
# self.db_file = os.path.join(settings.db, name)
self.db_file = None
self.user_info = None
# ็จๆท็ป้
... | FtpManage | identifier_name |
rows.go | package pgx
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/jackc/pgx/v5/internal/stmtcache"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
)
// Rows is the result set returned from *Conn.Query. Rows must be closed before
// the *Conn can be used again. Rows are c... |
return scanTargets, err
}
| {
sf := dstElemType.Field(i)
if sf.PkgPath != "" && !sf.Anonymous {
// Field is unexported, skip it.
continue
}
// Handle anoymous struct embedding, but do not try to handle embedded pointers.
if sf.Anonymous && sf.Type.Kind() == reflect.Struct {
scanTargets, err = rs.appendScanTargets(dstElemValue.F... | conditional_block |
rows.go | package pgx
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/jackc/pgx/v5/internal/stmtcache"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
)
// Rows is the result set returned from *Conn.Query. Rows must be closed before
// the *Conn can be used again. Rows are c... | if strings.EqualFold(desc.Name, field) {
return i
}
}
return
}
func (rs *namedStructRowScanner) appendScanTargets(dstElemValue reflect.Value, scanTargets []any, fldDescs []pgconn.FieldDescription) ([]any, error) {
var err error
dstElemType := dstElemValue.Type()
if scanTargets == nil {
scanTargets = mak... | for i, desc := range fldDescs { | random_line_split |
rows.go | package pgx
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/jackc/pgx/v5/internal/stmtcache"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
)
// Rows is the result set returned from *Conn.Query. Rows must be closed before
// the *Conn can be used again. Rows are c... |
func (rs *positionalStructRowScanner) appendScanTargets(dstElemValue reflect.Value, scanTargets []any) []any {
dstElemType := dstElemValue.Type()
if scanTargets == nil {
scanTargets = make([]any, 0, dstElemType.NumField())
}
for i := 0; i < dstElemType.NumField(); i++ {
sf := dstElemType.Field(i)
// Handl... | {
dst := rs.ptrToStruct
dstValue := reflect.ValueOf(dst)
if dstValue.Kind() != reflect.Ptr {
return fmt.Errorf("dst not a pointer")
}
dstElemValue := dstValue.Elem()
scanTargets := rs.appendScanTargets(dstElemValue, nil)
if len(rows.RawValues()) > len(scanTargets) {
return fmt.Errorf("got %d values, but ds... | identifier_body |
rows.go | package pgx
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/jackc/pgx/v5/internal/stmtcache"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
)
// Rows is the result set returned from *Conn.Query. Rows must be closed before
// the *Conn can be used again. Rows are c... | (fldDescs []pgconn.FieldDescription, field string) (i int) {
i = -1
for i, desc := range fldDescs {
if strings.EqualFold(desc.Name, field) {
return i
}
}
return
}
func (rs *namedStructRowScanner) appendScanTargets(dstElemValue reflect.Value, scanTargets []any, fldDescs []pgconn.FieldDescription) ([]any, err... | fieldPosByName | identifier_name |
build.py | #!/usr/bin/python
# Script to build OpenVPN with support for OQS cipher suites
# Written/tested for Python 2.7
# Script assumes
# - it is being run from the openvpn/build directory
# - any necessary authentication tokens are already available to Git (if not using the public GitHub URLs)
# - Linux: all d... |
cmd.append(repo_url)
if local_name:
cmd.append(local_name)
run_command(cmd)
if commit is not None:
if local_name:
os.chdir(local_name)
else:
print "git_clone with a commit ID only valid with a local_name"
sys.exit(1)
cmd = [... | cmd.extend(['--branch', branch]) | conditional_block |
build.py | #!/usr/bin/python
# Script to build OpenVPN with support for OQS cipher suites
# Written/tested for Python 2.7
# Script assumes
# - it is being run from the openvpn/build directory
# - any necessary authentication tokens are already available to Git (if not using the public GitHub URLs)
# - Linux: all d... |
If the error is for another reason it re-raises the error.
Usage : ``shutil.rmtree(path, onerror=onerror)``
"""
import stat
if not os.access(path, os.W_OK):
# Is the error an access error ?
os.chmod(path, stat.S_IWUSR)
func(path)
else:
raise
def build_openvpn_... | random_line_split | |
build.py | #!/usr/bin/python
# Script to build OpenVPN with support for OQS cipher suites
# Written/tested for Python 2.7
# Script assumes
# - it is being run from the openvpn/build directory
# - any necessary authentication tokens are already available to Git (if not using the public GitHub URLs)
# - Linux: all d... | (cmd):
print '***** Running command: %s' % ' '.join(map(str,cmd))
p = subprocess.Popen(cmd)
p.wait()
# Clone a git repo, using the default name, in the CWD
# If branch is specified, clone that branch
def git_clone(repo_url, branch, local_name, commit=None):
r = re.compile(".*/(.*)$")
m = r.match(re... | run_command | identifier_name |
build.py | #!/usr/bin/python
# Script to build OpenVPN with support for OQS cipher suites
# Written/tested for Python 2.7
# Script assumes
# - it is being run from the openvpn/build directory
# - any necessary authentication tokens are already available to Git (if not using the public GitHub URLs)
# - Linux: all d... |
def on_error(func, path, exc_info):
"""
Error handler for ``shutil.rmtree``.
If the error is due to an access error (read only file)
it attempts to add write permission and then retries.
If the error is for another reason it re-raises the error.
Usage : ``shutil.rmtree(path, onerror=onerror... | if platform.system() == 'Windows':
# Create source trees for x86 and x64
# Note that there's no way to clean up one tree and re-use it for a different arch
git_clone(OPENSSL_OQS_REPO, OPENSSL_OQS_BRANCH, 'openssl-oqs-win-x86', OPENSSL_OQS_COMMIT)
shutil.copytree('openssl-oqs-win-x86', 'o... | identifier_body |
utils.py | import copy
import os
from datetime import datetime
import numpy as np
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import normalize
ROOT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../')
DATA_FILE = os.path.join(ROOT_DIR, 'data/data_train.csv')
TRAINING_FILE_NAME = os.... | (data, use_three_way):
masked_data = np.copy(data)
if use_three_way:
mask_file = VALIDATION_MASK_FILE_NAME
else:
mask_file = VALIDATION_FILE_NAME
mask_indices = get_indices_from_file(mask_file)
for row_index, col_index in mask_indices:
masked_data[row_index][col_index] = 0
... | mask_validation | identifier_name |
utils.py | import copy
import os
from datetime import datetime
import numpy as np
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import normalize
ROOT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../')
DATA_FILE = os.path.join(ROOT_DIR, 'data/data_train.csv')
TRAINING_FILE_NAME = os.... | for i in range(reconstruction.shape[0]):
stacked_ratings = []
for neighbor in neighbors[i]:
stacked_ratings.append(reconstruction[neighbor])
stacked_ratings = np.asarray(stacked_ratings)
aggregated_neighbor_ratings[i] =\
np.matmul(weights[i], stacked_ratin... | similarities = ones - distances
weights = np.square(np.square(similarities))
smoothed_data = np.zeros(reconstruction.shape)
aggregated_neighbor_ratings = np.zeros(reconstruction.shape)
| random_line_split |
utils.py | import copy
import os
from datetime import datetime
import numpy as np
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import normalize
ROOT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../')
DATA_FILE = os.path.join(ROOT_DIR, 'data/data_train.csv')
TRAINING_FILE_NAME = os.... |
return indices_to_predict
def write_ratings(predictions, submission_file):
with open(submission_file, 'w') as file:
file.write('Id,Prediction\n')
for i, j, prediction in predictions:
file.write('r%d_c%d,%f\n' % (i, j, prediction))
def reconstruction_to_predictions(
reconst... | key, _ = line.split(",")
row_string, col_string = key.split("_")
i = int(row_string[1:]) - 1
j = int(col_string[1:]) - 1
indices_to_predict.append((i, j)) | conditional_block |
utils.py | import copy
import os
from datetime import datetime
import numpy as np
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import normalize
ROOT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../')
DATA_FILE = os.path.join(ROOT_DIR, 'data/data_train.csv')
TRAINING_FILE_NAME = os.... |
def clip(data):
data[data > 5] = 5
data[data < 1] = 1
return data
def ampute_reconstruction(reconstruction, data):
observed_indices = get_observed_indices(data)
for row_index, col_index in observed_indices:
reconstruction[row_index][col_index] = data[row_index][col_index]
def impute_by_a... | reconstruction_to_predictions(
reconstruction, ROOT_DIR + 'data/meta_training_' + name + '_stacking'
+ datetime.now().strftime('%Y-%b-%d-%H-%M-%S') + '.csv',
indices_to_predict=get_validation_indices(use_three_way=True))
reconstruction_to_predictions(
reconstruction, ROOT_DIR + 'data... | identifier_body |
Q_Learner.py | #deep Q-learning
import time
import itertools
import numpy as np
from tqdm import tqdm
import tensorflow as tf
from utils import Utility
from AgentBrain import Brain
from environment import Environment
from memory import ExperienceMemory
from StateProcessor import StateProcessor
from prioritizedExperienceMemory import ... | (self,sess,reloadM):
self.env.reset(sess)
if not reloadM:
print ('Initializing my experience memory...')
else:
print('Restoring my experience memory (naive solution!)...')
state = self.state_process.get_state(sess)
done = False
for v in tqdm(range(self.replay_strt_size)):
if not reloadM:
... | fill_memory | identifier_name |
Q_Learner.py | #deep Q-learning
import time
import itertools
import numpy as np
from tqdm import tqdm
import tensorflow as tf
from utils import Utility
from AgentBrain import Brain
from environment import Environment
from memory import ExperienceMemory
from StateProcessor import StateProcessor
from prioritizedExperienceMemory import ... | else:
state = nxt_state
pass
if(self.rendering):
self.env.render()
pass #TO DO -> sample of Q-action values summaries
def summaries(self,sess):
#print "in summaries!"
#basics
listy = {'totReward' : self.totalReward, 'avgReward' : (self.totalReward / self.countR) , 'epDur' : self.duration }
... | self.summaries(sess)
break #end of episode | random_line_split |
Q_Learner.py | #deep Q-learning
import time
import itertools
import numpy as np
from tqdm import tqdm
import tensorflow as tf
from utils import Utility
from AgentBrain import Brain
from environment import Environment
from memory import ExperienceMemory
from StateProcessor import StateProcessor
from prioritizedExperienceMemory import ... |
pass #TO DO -> sample of Q-action values summaries
def summaries(self,sess):
#print "in summaries!"
#basics
listy = {'totReward' : self.totalReward, 'avgReward' : (self.totalReward / self.countR) , 'epDur' : self.duration }
if self.training:
listy.update({"totLoss" : self.totalLoss , "avgLoss" : (self... | self.totalLoss =0.0
self.countL = 0
self.totalReward = 0.0
self.countR = 0
self.updates = 0
self.startTime = time.time()
self.env.reset(sess)
state = self.state_process.get_state(sess)
no_op = 0
for _ in itertools.count():
#take action
action = self.behaviour_e_policy(state,sess)
#step a... | identifier_body |
Q_Learner.py | #deep Q-learning
import time
import itertools
import numpy as np
from tqdm import tqdm
import tensorflow as tf
from utils import Utility
from AgentBrain import Brain
from environment import Environment
from memory import ExperienceMemory
from StateProcessor import StateProcessor
from prioritizedExperienceMemory import ... |
else:
print('Restoring my experience memory (naive solution!)...')
state = self.state_process.get_state(sess)
done = False
for v in tqdm(range(self.replay_strt_size)):
if not reloadM:
#select an action randomly
action = self.env.takeRandomAction()
else:
action = self.behaviour_e_policy(... | print ('Initializing my experience memory...') | conditional_block |
scripts.js | // v1
var $ = jQuery;
var WPTHEME = '/wp-content/themes/CorePaws-v2/';
var DOMAIN = location.protocol + "//" + location.host;
jQuery(document).ready(function ($) {
// Doc ready functions
GAtracking();
});
// ===================================================================
// Function with all of the gener... | $me = $(this);
if (!$me.hasClass('active')) {
if ($('.faq .question.active').length > 0) {
$('.faq .active').removeClass('active').next().hide();
}
$me.addClass('active').next().slideDown();
... |
$i.on('click', function () { | random_line_split |
scripts.js | // v1
var $ = jQuery;
var WPTHEME = '/wp-content/themes/CorePaws-v2/';
var DOMAIN = location.protocol + "//" + location.host;
jQuery(document).ready(function ($) {
// Doc ready functions
GAtracking();
});
// ===================================================================
// Function with all of the gener... | () {
// mobile menu clicks
$('#burger').on('click', function () {
$('#menu').toggleClass('open');
$('#burger').toggleClass('open');
$('html').toggleClass('scroll-lock');
});
}
function popVideo(id) {
$tar = $('#videobox');
$tar.addClass('on');
$str = '<div class="video-f... | menu | identifier_name |
scripts.js | // v1
var $ = jQuery;
var WPTHEME = '/wp-content/themes/CorePaws-v2/';
var DOMAIN = location.protocol + "//" + location.host;
jQuery(document).ready(function ($) {
// Doc ready functions
GAtracking();
});
// ===================================================================
// Function with all of the gener... |
// mobile menu
function menu() {
// mobile menu clicks
$('#burger').on('click', function () {
$('#menu').toggleClass('open');
$('#burger').toggleClass('open');
$('html').toggleClass('scroll-lock');
});
}
function popVideo(id) {
$tar = $('#videobox');
$tar.addClass('on');
... | {
var $frame = $('iframe');
var width = $('.video').width();
$frame.attr('width', width);
$frame.attr('height', (width * 3 / 5));
} | identifier_body |
scripts.js | // v1
var $ = jQuery;
var WPTHEME = '/wp-content/themes/CorePaws-v2/';
var DOMAIN = location.protocol + "//" + location.host;
jQuery(document).ready(function ($) {
// Doc ready functions
GAtracking();
});
// ===================================================================
// Function with all of the gener... | else {
url += '&' + key + '=' + value;
}
});
// Use "search" variable to record events if desired
window.location = DOMAIN + '/adoption/' + url;
});
}
// ===================================================================
// Function to initialize Featured Pe... | {
url = '?' + key + '=' + value;
} | conditional_block |
queued.rs | // Copyright (c) 2013-2016 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, inc... | (&self) -> Box<dyn PipelineHook> {
Box::new(self.clone())
}
fn get_pipelined_cap(&self, ops: &[PipelineOp]) -> Box<dyn ClientHook> {
self.get_pipelined_cap_move(ops.into())
}
fn get_pipelined_cap_move(&self, ops: Vec<PipelineOp>) -> Box<dyn ClientHook> {
if let Some(p) = &self.i... | add_ref | identifier_name |
queued.rs | // Copyright (c) 2013-2016 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, inc... | client_resolution_queue: SenderQueue<(), Box<dyn ClientHook>>,
}
impl ClientInner {
pub fn resolve(state: &Rc<RefCell<Self>>, result: Result<Box<dyn ClientHook>, Error>) {
assert!(state.borrow().redirect.is_none());
let client = match result {
Ok(clienthook) => clienthook,
... | // delivered after calls made earlier), but *before* any queued calls return (because it might
// confuse the application if a queued call returns before the capability on which it was made
// resolves). Luckily, we know that queued calls will involve, at the very least, an
// eventLoop.evalLater. | random_line_split |
framework.rs | use std::future::Future;
#[cfg(target_arch = "wasm32")]
use std::str::FromStr;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;
#[cfg(target_arch = "wasm32")]
use web_sys::{ImageBitmapRenderingContext, OffscreenCanvas};
use winit::{
event::{self, WindowEvent},
event_loop::{ControlFlow, EventLoop},
};... |
#[cfg(target_arch = "wasm32")]
pub struct Spawner {}
#[cfg(target_arch = "wasm32")]
impl Spawner {
fn new() -> Self {
Self {}
}
#[allow(dead_code)]
pub fn spawn_local(&self, future: impl Future<Output = ()> + 'static) {
wasm_bindgen_futures::spawn_local(future);
}
}
#[cfg(not(tar... | fn run_until_stalled(&self) {
while self.executor.try_tick() {}
}
} | random_line_split |
framework.rs | use std::future::Future;
#[cfg(target_arch = "wasm32")]
use std::str::FromStr;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;
#[cfg(target_arch = "wasm32")]
use web_sys::{ImageBitmapRenderingContext, OffscreenCanvas};
use winit::{
event::{self, WindowEvent},
event_loop::{ControlFlow, EventLoop},
};... |
fn start<E: Example>(
#[cfg(not(target_arch = "wasm32"))] Setup {
window,
event_loop,
instance,
size,
surface,
adapter,
device,
queue,
}: Setup,
#[cfg(target_arch = "wasm32")] Setup {
window,
event_loop,
instance,
... | {
#[cfg(not(target_arch = "wasm32"))]
{
env_logger::init();
};
let event_loop = EventLoop::new();
let mut builder = winit::window::WindowBuilder::new();
builder = builder.with_title(title);
#[cfg(windows_OFF)] // TODO
{
use winit::platform::windows::WindowBuilderExtWindo... | identifier_body |
framework.rs | use std::future::Future;
#[cfg(target_arch = "wasm32")]
use std::str::FromStr;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;
#[cfg(target_arch = "wasm32")]
use web_sys::{ImageBitmapRenderingContext, OffscreenCanvas};
use winit::{
event::{self, WindowEvent},
event_loop::{ControlFlow, EventLoop},
};... |
};
let view = frame.texture.create_view(&wgpu::TextureViewDescriptor {
format: Some(surface_view_format),
..wgpu::TextureViewDescriptor::default()
});
example.render(&view, &device, &queue, &spawner);
... | {
surface.configure(&device, &config);
surface
.get_current_texture()
.expect("Failed to acquire next surface texture!")
} | conditional_block |
framework.rs | use std::future::Future;
#[cfg(target_arch = "wasm32")]
use std::str::FromStr;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;
#[cfg(target_arch = "wasm32")]
use web_sys::{ImageBitmapRenderingContext, OffscreenCanvas};
use winit::{
event::{self, WindowEvent},
event_loop::{ControlFlow, EventLoop},
};... | <E: Example>(title: &str) {
use wasm_bindgen::prelude::*;
let title = title.to_owned();
wasm_bindgen_futures::spawn_local(async move {
let setup = setup::<E>(&title).await;
let start_closure = Closure::once_into_js(move || start::<E>(setup));
// make sure to handle JS exceptions th... | run | identifier_name |
main.rs | use std::convert::Infallible;
use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};
mod github;
mod zulip;
const BOT_NAME: &'static str = "bisect-bot ";
const USER_AGENT: &'static str = "https://github.com/bjorn3/cargo-bisect-rustc-bot";
const REPO_WHITELIST: &'static [&'sta... | cmds.push(format!("--end={}", end));
println!("{:?}", &cmds);
push_job(&reply_to, comment_id, &cmds, &code).await?;
}
None => {}
}
Ok(())
}
async fn push_job(reply_to: &ReplyTo, job_id: &str, bisect_cmds: &[String], repro: &str) -> reqwest::Result<()> {
... | } | random_line_split |
main.rs | use std::convert::Infallible;
use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};
mod github;
mod zulip;
const BOT_NAME: &'static str = "bisect-bot ";
const USER_AGENT: &'static str = "https://github.com/bjorn3/cargo-bisect-rustc-bot";
const REPO_WHITELIST: &'static [&'sta... | else if part.starts_with("end=") {
if end.is_some() {
return Err(format!("end range specified twice"));
}
end = Some(part["end=".len()..].to_string());
} else {
... | {
if start.is_some() {
return Err(format!("start range specified twice"));
}
start = Some(part["start=".len()..].to_string());
} | conditional_block |
main.rs | use std::convert::Infallible;
use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};
mod github;
mod zulip;
const BOT_NAME: &'static str = "bisect-bot ";
const USER_AGENT: &'static str = "https://github.com/bjorn3/cargo-bisect-rustc-bot";
const REPO_WHITELIST: &'static [&'sta... | {
path: String,
mode: TreeEntryMode,
#[serde(rename = "type")]
type_: TreeEntryType,
sha: String,
}
#[derive(serde::Serialize)]
enum TreeEntryMode {
#[serde(rename = "100644")]
File,
#[serde(rename = "100755")]
Executable,
#[serde(rename = "040000")]
Subdirectory,
#[ser... | TreeEntry | identifier_name |
probe_bert.py | """ Finetuning the AFTER models for sequence classification (Bert, XLM, XLNet, RoBERTa, Albert, XLM-RoBERTa)."""
import argparse
import json
import logging
import os
import random
import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler
from torch.utils.data.distribute... | (args, model, prefix=""):
# Loop to handle MNLI double evaluation (matched, mis-matched)
eval_task_names = ("mnli", "mnli-mm") if args.task_name == "mnli" else (args.task_name,)
eval_outputs_dirs = (args.output_dir, args.output_dir + "-MM") if args.task_name == "mnli" else (args.output_dir,)
results = ... | evaluate | identifier_name |
probe_bert.py | """ Finetuning the AFTER models for sequence classification (Bert, XLM, XLNet, RoBERTa, Albert, XLM-RoBERTa)."""
import argparse
import json
import logging
import os
import random
import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler
from torch.utils.data.distribute... |
if args.max_steps > 0 and global_step > args.max_steps:
epoch_iterator.close()
break
if args.max_steps > 0 and global_step > args.max_steps:
train_iterator.close()
break
return global_step, tr_loss / global_step
def evaluate(args, mode... | train_steps = global_step / len(train_domain_dataloader)
# Save model checkpoint
output_dir = os.path.join(args.output_dir,
"checkpoint".format(train_steps))
if not os.path.exists(output_dir):
... | conditional_block |
probe_bert.py | """ Finetuning the AFTER models for sequence classification (Bert, XLM, XLNet, RoBERTa, Albert, XLM-RoBERTa)."""
import argparse
import json
import logging
import os
import random
import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler
from torch.utils.data.distribute... |
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input", required=False,
default='probe_bert_mrpc_pubmed.yaml',
help="config file of input data")
parser.add_argument("--seed", type=int, default=2319, help="random ... | if (
os.path.exists(args.output_dir)
and os.listdir(args.output_dir)
and args.do_train
and not args.overwrite_output_dir
):
raise ValueError(
"Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format(
... | identifier_body |
probe_bert.py | """ Finetuning the AFTER models for sequence classification (Bert, XLM, XLNet, RoBERTa, Albert, XLM-RoBERTa)."""
import argparse
import json
import logging
import os
import random
import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler
from torch.utils.data.distribute... | args.__dict__.update(config)
if args.model_type == "bert-ft":
args.ckpt_file = "/data/data1/users/gvernikos/After_v1.0/AfterBERT/MRPC/seed_{}/checkpoint".format(args.seed)
args.lambd = "_"
elif args.model_type == "afterbert":
args.ckpt_file = "/data/data1/users/gvernikos/After_v1.0/... | args = parser.parse_args()
config = train_options(args.input)
# Merge the input arguments with the configuration yaml | random_line_split |
dri.go | // Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package graphics contains graphics-related utility functions for local tests.
package graphics
import (
"context"
"fmt"
"io/ioutil"
"math"
"os"
"strings"
"time"
... | (ctx context.Context, backend Backend, width, height int) (objectCount int, err error) {
const (
pollingInterval = 1 * time.Second
// Time to wait for the object count to be stable.
waitTimeout = 120 * time.Second
// Threshold (in percentage) below which the object count is considered stable.
objectCountThre... | readStableObjectCount | identifier_name |
dri.go | // Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package graphics contains graphics-related utility functions for local tests.
package graphics
import (
"context"
"fmt"
"io/ioutil"
"math"
"os"
"strings"
"time"
... |
// Round rounds up value for the Intel platforms and all codecs.
func (g I915Backend) Round(value int) int {
const i915Alignment = 16
// Inspired by Chromium's base/bits.h:Align() function.
return (value + i915Alignment - 1) & ^(i915Alignment - 1)
}
// ReadFramebufferCount tries to open the i915FramebufferFile an... | {
if _, err := os.Stat(i915FramebufferFile); err != nil {
return nil
}
return &I915Backend{}
} | identifier_body |
dri.go | // Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package graphics contains graphics-related utility functions for local tests.
package graphics
import (
"context"
"fmt"
"io/ioutil"
"math"
"os"
"strings"
"time"
... | if _, err := os.Stat(i915FramebufferFile); err != nil {
return nil
}
return &I915Backend{}
}
// Round rounds up value for the Intel platforms and all codecs.
func (g I915Backend) Round(value int) int {
const i915Alignment = 16
// Inspired by Chromium's base/bits.h:Align() function.
return (value + i915Alignmen... | func i915Backend() *I915Backend { | random_line_split |
dri.go | // Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package graphics contains graphics-related utility functions for local tests.
package graphics
import (
"context"
"fmt"
"io/ioutil"
"math"
"os"
"strings"
"time"
... |
text, err := ioutil.ReadAll(f)
if err != nil {
return framebuffers, errors.Wrap(err, "failed to read dri file")
}
lines := strings.Split(string(text), "\n")
for _, line := range lines {
// The line we're looking for looks like "...size=1920x1080"
var fbWidth, fbHeight int
if _, err := fmt.Sscanf(line, " ... | {
return framebuffers, errors.Wrap(err, "failed to open dri file")
} | conditional_block |
context.rs | use crate::*;
use winit::event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent};
use winit::event_loop::{ControlFlow, EventLoop};
use winit::platform::desktop::EventLoopExtDesktop;
const ENABLE_DEBUG_MESSENGER_CALLBACK: bool = true;
#[derive(Copy, Clone, Debug, Hash, PartialEq)]
pub struct BufferHa... | (pub u64);
#[derive(Copy, Clone, Debug, Hash, PartialEq)]
pub struct PassHandle(pub u64);
#[derive(Copy, Clone, Debug, Hash, PartialEq)]
pub struct ImageHandle(pub u64);
#[derive(Copy, Clone, Debug, Hash, PartialEq)]
pub struct ShaderHandle(pub u64);
pub struct Context {
window: winit::window::Window,
event_lo... | GraphHandle | identifier_name |
context.rs | use crate::*;
use winit::event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent};
use winit::event_loop::{ControlFlow, EventLoop};
use winit::platform::desktop::EventLoopExtDesktop;
const ENABLE_DEBUG_MESSENGER_CALLBACK: bool = true;
#[derive(Copy, Clone, Debug, Hash, PartialEq)]
pub struct BufferHa... | &mut self.image_list,
&self.debug_utils,
);
// Recreate the images which depend on the resolution of the swapchain
for i in 0..self.image_list.list.len() {
let (_, internal_image) = &mut self.image_list.list[i];
if let ImageKind::RelativeSized { sc... | random_line_split | |
context.rs | use crate::*;
use winit::event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent};
use winit::event_loop::{ControlFlow, EventLoop};
use winit::platform::desktop::EventLoopExtDesktop;
const ENABLE_DEBUG_MESSENGER_CALLBACK: bool = true;
#[derive(Copy, Clone, Debug, Hash, PartialEq)]
pub struct BufferHa... |
}
| {
self.image_list.new_image_from_file(
name,
path,
&self.gpu,
self.command_pool,
&self.debug_utils,
)
} | identifier_body |
context.rs | use crate::*;
use winit::event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent};
use winit::event_loop::{ControlFlow, EventLoop};
use winit::platform::desktop::EventLoopExtDesktop;
const ENABLE_DEBUG_MESSENGER_CALLBACK: bool = true;
#[derive(Copy, Clone, Debug, Hash, PartialEq)]
pub struct BufferHa... |
_ => (),
}
});
// This mechanism is need on Windows:
if resize_needed {
self.recreate_resolution_dependent_state();
}
// This mechanism suffices on Linux:
// Acquiring the swapchain image fails if the window has been resized. If ... | {
*control_flow = ControlFlow::Exit;
} | conditional_block |
ner.rs | // Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
// Copyright (c) 2018 chakki (https://github.com/chakki-works/seqeval/blob/master/seqeval/metrics/sequence_labeling.py)
// Copyright 2019 Guillaume Becquin
// Licensed under the Apache License, Version 2.0 (the "License... |
fn consolidate_entities(tokens: &[Token]) -> Vec<Entity> {
let mut entities: Vec<Entity> = Vec::new();
let mut entity_builder = EntityBuilder::new();
for (position, token) in tokens.iter().enumerate() {
let tag = token.get_tag();
let label = token.get_label();
... |
let tokens = self.token_classification_model.predict(input, true, false);
let mut entities: Vec<Vec<Entity>> = Vec::new();
for sequence_tokens in tokens {
entities.push(Self::consolidate_entities(&sequence_tokens));
}
entities
}
| identifier_body |
ner.rs | // Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
// Copyright (c) 2018 chakki (https://github.com/chakki-works/seqeval/blob/master/seqeval/metrics/sequence_labeling.py)
// Copyright 2019 Guillaume Becquin
// Licensed under the Apache License, Version 2.0 (the "License... | }
}
fn flush_and_reset(&mut self, position: usize, tokens: &[Token]) -> Option<Entity> {
let entity = if let Some((start, _, label)) = self.previous_node {
let entity_tokens = &tokens[start..position];
Some(Entity {
word: entity_tokens
... |
if let Some((_, previous_tag, previous_label)) = self.previous_node {
if (previous_tag == Tag::End)
| (previous_tag == Tag::Single)
| (previous_label != label)
{
let entity = self.flush_and_r... | conditional_block |
ner.rs | // Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
// Copyright (c) 2018 chakki (https://github.com/chakki-works/seqeval/blob/master/seqeval/metrics/sequence_labeling.py)
// Copyright 2019 Guillaume Becquin
// Licensed under the Apache License, Version 2.0 (the "License... |
&mut self,
tag: Tag,
label: &'a str,
position: usize,
tokens: &[Token],
) -> Option<Entity> {
match tag {
Tag::Outside => self.flush_and_reset(position, tokens),
Tag::Begin | Tag::Single => {
let entity = self.flush_and_reset(p... | andle_current_tag( | identifier_name |
ner.rs | // Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
// Copyright (c) 2018 chakki (https://github.com/chakki-works/seqeval/blob/master/seqeval/metrics/sequence_labeling.py)
// Copyright 2019 Guillaume Becquin
// Licensed under the Apache License, Version 2.0 (the "License... | //! device: Device::cuda_if_available(),
//! ..Default::default()
//! };
//!
//! let ner_model = NERModel::new(ner_config)?;
//!
//! // Define input
//! let input = [
//! "Mein Name ist Amรฉlie. Ich lebe in Paris.",
//! "Paris ist eine Stadt in Frankreich.",
//! ];
//! let output = ner_model.predict(&... | //! lower_case: false, | random_line_split |
membership.go | /*
Copyright 2016 The Smudge Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwar... |
} else {
continue
}
}
currentHeartbeat++
logfTrace("%d - hosts=%d (announce=%d forward=%d)",
currentHeartbeat,
len(randomAllNodes),
emitCount(),
pingRequestCount())
PingNode(node)
pingCounter++
time.Sleep(time.Millisecond * time.Duration(GetHeartbeatMillis()))
if ... | {
logDebug("Forgetting dead node", node.Address())
deadNodeRetries.Lock()
delete(deadNodeRetries.m, node.Address())
deadNodeRetries.Unlock()
RemoveNode(node)
continue
} | conditional_block |
membership.go | /*
Copyright 2016 The Smudge Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwar... |
func transmitVerbPingUDP(node *Node, code uint32) error {
key := node.Address() + ":" + strconv.FormatInt(int64(code), 10)
pack := pendingAck{
node: node,
startTime: GetNowInMillis(),
packType: packPing}
pendingAcks.Lock()
pendingAcks.m[key] = &pack
pendingAcks.Unlock()
return transmitVerbGenericU... | {
return transmitVerbGenericUDP(node, nil, verbAck, code)
} | identifier_body |
membership.go | /*
Copyright 2016 The Smudge Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwar... | filteredNodes := getTargetNodes(pingRequestCount(), thisHost, pack.node)
if len(filteredNodes) == 0 {
logDebug(thisHost.Address(), "Cannot forward ping request: no more nodes")
updateNodeStatus(pack.node, StatusDead, currentHeartbeat, thisHost)
} else {
for i, n := range filteredNodes {
logfDebug("(%d/%d)... |
return name, msgBytes, nil
}
func doForwardOnTimeout(pack *pendingAck) { | random_line_split |
membership.go | /*
Copyright 2016 The Smudge Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwar... | (node *Node, forwardTo *Node, verb messageVerb, code uint32) error {
// Transmit the ACK
remoteAddr, err := net.ResolveUDPAddr("udp", node.Address())
c, err := net.DialUDP("udp", nil, remoteAddr)
if err != nil {
return err
}
defer c.Close()
msg := newMessage(verb, thisHost, code)
if forwardTo != nil {
ms... | transmitVerbGenericUDP | identifier_name |
connection.go | package ayame
import (
"context"
"encoding/json"
"fmt"
"math/rand"
"time"
"github.com/oklog/ulid/v2"
"github.com/rs/zerolog"
"github.com/shiguredo/websocket"
)
type connection struct {
ID string
roomID string
clientID string
authnMetadata *interface{}
signalingKey *string
// ใฏใฉ... | }
// ่ช่จผใตใผใใฎๆปใๅคใใใใใๅ ดๅใฏๅ
จ้จ Error ใซใใ
if resp.Allowed == nil {
c.errLog().Caller().Msg("AuthnWebhookResponseError")
if err := c.sendRejectMessage("InternalServerError"); err != nil {
c.errLog().Err(err).Caller().Msg("FailedSendRejectMessage")
return err
}
return errAuthnWebhookResponse
}
if... | c.errLog().Err(err).Caller().Msg("FailedSendRejectMessage")
return err
}
return err | random_line_split |
connection.go | package ayame
import (
"context"
"encoding/json"
"fmt"
"math/rand"
"time"
"github.com/oklog/ulid/v2"
"github.com/rs/zerolog"
"github.com/shiguredo/websocket"
)
type connection struct {
ID string
roomID string
clientID string
authnMetadata *interface{}
signalingKey *string
// ใฏใฉ... |
}
return nil
}
func (c *connection) sendPingMessage() error {
msg := &pingMessage{
Type: "ping",
}
if err := c.SendJSON(msg); err != nil {
return err
}
return nil
}
// reason ใฎ้ทใใไธๅๅใใใชๅ ดๅใฏ CloseMessage ใงใฏใชใ TextMessage ใไฝฟ็จใใใใใซๅคๆดใใ
func (c *connection) sendCloseMessage(code int, reason string) error {
... | turn err | identifier_name |
connection.go | package ayame
import (
"context"
"encoding/json"
"fmt"
"math/rand"
"time"
"github.com/oklog/ulid/v2"
"github.com/rs/zerolog"
"github.com/shiguredo/websocket"
)
type connection struct {
ID string
roomID string
clientID string
authnMetadata *interface{}
signalingKey *string
// ใฏใฉ... |
return nil
}
// reason ใฎ้ทใใไธๅๅใใใชๅ ดๅใฏ CloseMessage ใงใฏใชใ TextMessage ใไฝฟ็จใใใใใซๅคๆดใใ
func (c *connection) sendCloseMessage(code int, reason string) error {
deadline := time.Now().Add(writeWait)
closeMessage := websocket.FormatCloseMessage(code, reason)
return c.wsConn.WriteControl(websocket.CloseMessage, closeMessage,... | c (c *connection) sendPingMessage() error {
msg := &pingMessage{
Type: "ping",
}
if err := c.SendJSON(msg); err != nil {
return err
}
| identifier_body |
connection.go | package ayame
import (
"context"
"encoding/json"
"fmt"
"math/rand"
"time"
"github.com/oklog/ulid/v2"
"github.com/rs/zerolog"
"github.com/shiguredo/websocket"
)
type connection struct {
ID string
roomID string
clientID string
authnMetadata *interface{}
signalingKey *string
// ใฏใฉ... | -MESSAGE")
}
break loop
}
if err := c.wsConn.WriteMessage(websocket.TextMessage, forward.rawMessage); err != nil {
c.errLog().Err(err).Msg("FailedWriteMessage")
// ้ใใชใใฃใใ้ใใใกใใปใผใธใ้ใใชใใฎใง return
return
}
}
}
// ใใกใใฎ้ฝๅใง็ตไบใใใฎใง Websocket ็ตไบใฎใ็ฅใใใ้ใ
if err := c.sendCloseMessage(websocket.C... | r != nil {
c.errLog().Err(err).Msg("FailedSendByeMessage")
// ้ใใชใใฃใใ้ใใใกใใปใผใธใ้ใใชใใฎใง return
return
}
c.debugLog().Msg("SENT-BYE | conditional_block |
images.go | // Copyright 2016 Mender Software AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicabl... |
metaArtifact.Updates = append(
metaArtifact.Updates,
images.Update{
TypeInfo: images.ArtifactUpdateTypeInfo{
Type: p.GetUpdateType().Type,
},
MetaData: p.GetMetadata(),
Files: uFiles,
})
}
return metaArtifact, nil
}
| {
return nil, errors.Wrap(err, "Cannot get update files:")
} | conditional_block |
images.go | // Copyright 2016 Mender Software AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicabl... |
// DeleteImage removes metadata and image file
// Noop for not exisitng images
// Allowed to remove image only if image is not scheduled or in progress for an updates - then image file is needed
// In case of already finished updates only image file is not needed, metadata is attached directly to device deployment
//... | {
image, err := i.imagesStorage.FindByID(id)
if err != nil {
return nil, errors.Wrap(err, "Searching for image with specified ID")
}
if image == nil {
return nil, nil
}
return image, nil
} | identifier_body |
images.go | // Copyright 2016 Mender Software AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicabl... | return metaArtifact, nil
} | random_line_split | |
images.go | // Copyright 2016 Mender Software AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicabl... | (imageID string, expire time.Duration) (*images.Link, error) {
found, err := i.imagesStorage.Exists(imageID)
if err != nil {
return nil, errors.Wrap(err, "Searching for image with specified ID")
}
if !found {
return nil, nil
}
found, err = i.fileStorage.Exists(imageID)
if err != nil {
return nil, errors... | DownloadLink | identifier_name |
file.go | // Copyright 2013 Google Inc. All Rights Reserved.
// Copyright 2017 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENS... | else {
match = pattern.MatchString(entry.Message) ||
pattern.MatchString(entry.File)
}
if match && entry.Time >= startTimestamp && entry.Time <= endTimestamp {
entries = append([]Entry{entry}, entries...)
if len(entries) >= maxEntries {
break
}
}
if entry.Time < startTimestamp {
entryBef... | {
match = true
} | conditional_block |
file.go | // Copyright 2013 Google Inc. All Rights Reserved.
// Copyright 2017 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENS... |
func (l *loggingT) listLogFiles() ([]FileInfo, error) {
var results []FileInfo
dir, err := logging.logDir.get()
if err != nil {
// No log directory configured: simply indicate that there are no
// log files.
return nil, nil
}
infos, err := ioutil.ReadDir(dir)
if err != nil {
return results, err
}
// T... | {
return logging.listLogFiles()
} | identifier_body |
file.go | // Copyright 2013 Google Inc. All Rights Reserved.
// Copyright 2017 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENS... | (prefix string, t time.Time) (name, link string) {
// Replace the ':'s in the time format with '_'s to allow for log files in
// Windows.
tFormatted := strings.Replace(t.Format(time.RFC3339), ":", "_", -1)
name = fmt.Sprintf("%s.%s.%s.%s.%06d.log",
removePeriods(prefix),
removePeriods(host),
removePeriods(us... | logName | identifier_name |
file.go | // Copyright 2013 Google Inc. All Rights Reserved.
// Copyright 2017 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENS... |
// LogFileMaxSize is the maximum size of a log file in bytes.
var LogFileMaxSize int64 = 10 << 20 // 10MiB
// LogFilesCombinedMaxSize is the maximum total size in bytes for log
// files. Note that this is only checked when log files are created,
// so the total size of log files per severity might temporarily be up
/... | "github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
) | random_line_split |
guidestar.py | #!/usr/bin/env python3
#
# Copyright (C) 2018 Cambridge Astronomical Survey Unit
#
# This program 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... | (self,guide):
self.new_xml()
xml_target = self.targets_base[0].cloneNode(True)
guide_ra = guide['GAIA_RA']
guide_dec = guide['GAIA_DEC']
dx = (self.ra - guide_ra)*self.plate_scale
dy = (self.dec - guide_dec)*self.plate_scale
xml_target.setAttribute('targx',str(dx... | to_xml | identifier_name |
guidestar.py | #!/usr/bin/env python3
#
# Copyright (C) 2018 Cambridge Astronomical Survey Unit
#
# This program 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... |
else:
t0 = tabs[0]
for t in tabs[1:]:
for g in t:
t0.add_row(g)
self.guides = t0
return
def select_target(self,annular=False):
import numpy
from operator import indexOf
fro... | self.guides = tabs[0] | conditional_block |
guidestar.py | #!/usr/bin/env python3
#
# Copyright (C) 2018 Cambridge Astronomical Survey Unit
#
# This program 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... |
if __name__ =='__main__':
if 0:
import ifu
ra = 178.835488822
dec = 58.2835493041
pa = 0.0
gs = ifu.guidestar(ra,dec,pa)
gs.set_geometry()
guide = gs.get_guide(annular_fail=True,as_xml=True)
#gs.retrieve_guidecats()
#gs.select_target()... | self.new_xml()
xml_target = self.targets_base[0].cloneNode(True)
guide_ra = guide['GAIA_RA']
guide_dec = guide['GAIA_DEC']
dx = (self.ra - guide_ra)*self.plate_scale
dy = (self.dec - guide_dec)*self.plate_scale
xml_target.setAttribute('targx',str(dx))
xml_target.... | identifier_body |
guidestar.py | #!/usr/bin/env python3
#
# Copyright (C) 2018 Cambridge Astronomical Survey Unit
#
# This program 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... | if rnd_dist > r_min:
if rnd_dist < r_max:
self.healpix_indices.append(hp.skycoord_to_healpix(SkyCoord(rnd_ra,rnd_dec,unit='deg')))
in_annulus.append([rnd_ra,rnd_dec])
#print len(in_annulus)
print '....done'
self.healpix_... | rnd_ra = self.ra+(2*(random.random()-0.5)*radius)
rnd_dec = self.dec+(2*(random.random()-0.5)*radius)
rnd_dist = (((rnd_ra-self.ra)**2)+((rnd_dec-self.dec)**2))**0.5 | random_line_split |
detours.rs | #![allow(non_camel_case_types)]
extern crate winapi;
extern crate kernel32;
extern crate field_offset;
use winapi::*;
#[allow(unused_imports)]
use self::field_offset::*;
use std::mem;
use std::ffi::CStr;
use std::ptr::null_mut;
use std::iter::once;
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
// Copie... | {
module: HMODULE,
}
impl Module {
#[allow(dead_code)]
pub fn target(moduleName: &str) -> Option<Module> {
let mut library = Module { module: 0 as HMODULE };
let wModuleName: Vec<u16> = OsStr::new(moduleName)
.encode_wide()
.chain(once(0))
.collect();
... | Module | identifier_name |
detours.rs | #![allow(non_camel_case_types)]
extern crate winapi;
extern crate kernel32;
extern crate field_offset;
use winapi::*;
#[allow(unused_imports)]
use self::field_offset::*;
use std::mem;
use std::ffi::CStr;
use std::ptr::null_mut;
use std::iter::once;
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
// Copie... |
}
#[allow(unused_variables)]
#[cfg(test)]
extern "system" fn myCreatePipe(hReadPipe: PHANDLE,
hWritePipe: PHANDLE,
lpPipeAttributes: LPVOID,
nSize: DWORD)
-> BOOL {
0x31337
}
#[test]
fn... | {
let base_addr: PBYTE = unsafe { mem::transmute::<HMODULE, PBYTE>(self.module) };
let dos_hdr: PIMAGE_DOS_HEADER =
unsafe { mem::transmute::<HMODULE, PIMAGE_DOS_HEADER>(self.module) };
if unsafe { (*dos_hdr).e_magic } != IMAGE_DOS_SIGNATURE {
return None;
}
... | identifier_body |
detours.rs | #![allow(non_camel_case_types)]
extern crate winapi;
extern crate kernel32;
extern crate field_offset;
use winapi::*;
#[allow(unused_imports)]
use self::field_offset::*;
use std::mem;
use std::ffi::CStr;
use std::ptr::null_mut;
use std::iter::once;
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
// Copie... |
if (orig_thunk.u1 & IMAGE_ORDINAL_FLAG) != 0 {
continue;
}
let import: PIMAGE_IMPORT_BY_NAME =
unsafe {
mem::transmute::<PBYTE,
PIMAGE_I... | {
break;
} | conditional_block |
detours.rs | #![allow(non_camel_case_types)]
extern crate winapi;
extern crate kernel32;
extern crate field_offset;
use winapi::*;
#[allow(unused_imports)]
use self::field_offset::*;
use std::mem;
use std::ffi::CStr;
use std::ptr::null_mut;
use std::iter::once;
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
// Copie... | let mut result = target.intercept("kernel32.dll", "CreatePipe", unsafe {
mem::transmute::<extern "system" fn(PHANDLE,
PHANDLE,
LPVOID,
DWORD)
... |
#[test]
fn test_intercept() {
let target = Module::self_target();
| random_line_split |
amap.go | package amap
import (
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
"time"
"github.com/go-resty/resty"
)
// PoiResult PoiResult
type PoiResult struct {
Count string `json:"count"`
Info string `json:"info"`
Infocode string `json:"infocode"`
Pois []Poi `json:"pois"`
Status string... |
pois = result.Pois
return
}
func minRecPagesPois(minRecPages []minRecPage) (pois []Poi) {
for _, minRecPage := range minRecPages {
pagePois, err := minRecPagePois(minRecPage)
if err == nil {
pois = append(pois, pagePois...)
} else {
fmt.Println(minRecPages, err)
}
}
return
}
func minRecPages(mRec ... | {
return
} | conditional_block |
amap.go | package amap
import (
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
"time"
"github.com/go-resty/resty"
)
// PoiResult PoiResult
type PoiResult struct {
Count string `json:"count"`
Info string `json:"info"`
Infocode string `json:"infocode"`
Pois []Poi `json:"pois"`
Status string... |
func recRequest(para map[string]string) (result PoiResult, err error) {
para["key"] = key
resp, err := resty.
SetTimeout(10 * time.Second).
SetRetryCount(5).
SetRetryWaitTime(10 * time.Second).
SetRetryMaxWaitTime(65 * time.Second).
R().
SetQueryParams(para).
Get(gaoDePolygonURL)
if err != nil {
re... | {
pages := recTypePages(rec, types)
pois = minRecPagesPois(pages)
return
} | identifier_body |
amap.go | package amap
import (
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
"time"
"github.com/go-resty/resty"
)
// PoiResult PoiResult
type PoiResult struct {
Count string `json:"count"`
Info string `json:"info"`
Infocode string `json:"infocode"`
Pois []Poi `json:"pois"`
Status string... | AosTagScore float64 `json:"aos_tag_score"`
Recommend string `json:"recommend"`
HighQuality int `json:"high_quality"`
Labels []interface{} `json:"labels"`
ReviewID string `json:"review_id"`
AuthorProfileurl string `json:"auth... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.