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 |
|---|---|---|---|---|
feature_extract.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2017 Tomoki Hayashi (Nagoya University)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import logging
import multiprocessing as mp
import os
import sys
from distutils.util import strtobool
import librosa
import numpy as np
import... |
# perform linear interpolation
f = interp1d(nz_frames, f0[nz_frames])
cont_f0 = f(np.arange(0, f0.shape[0]))
return uv, cont_f0
def stft_mcep(x, fftl=512, shiftl=256, dim=25, alpha=0.41, window="hamming", is_padding=False):
"""EXTRACT STFT-BASED MEL-CEPSTRUM.
Args:
x (ndarray): Nump... | # get non-zero frame index
nz_frames = np.where(f0 != 0)[0] | random_line_split |
feature_extract.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2017 Tomoki Hayashi (Nagoya University)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import logging
import multiprocessing as mp
import os
import sys
from distutils.util import strtobool
import librosa
import numpy as np
import... | (x, fftl=512, shiftl=256, dim=25, alpha=0.41, window="hamming", is_padding=False):
"""EXTRACT STFT-BASED MEL-CEPSTRUM.
Args:
x (ndarray): Numpy double array with the size (T,).
fftl (int): FFT length in point (default=512).
shiftl (int): Shift length in point (default=256).
dim ... | stft_mcep | identifier_name |
feature_extract.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2017 Tomoki Hayashi (Nagoya University)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import logging
import multiprocessing as mp
import os
import sys
from distutils.util import strtobool
import librosa
import numpy as np
import... |
def melcepstrum_extract(wav_list, args):
"""EXTRACT MEL CEPSTRUM."""
# define feature extractor
for i, wav_name in enumerate(wav_list):
logging.info("now processing %s (%d/%d)" % (wav_name, i + 1, len(wav_list)))
# load wavfile and apply low cut filter
fs, x = wavfile.read(wav_na... | """EXTRACT MEL SPECTROGRAM."""
# define feature extractor
for i, wav_name in enumerate(wav_list):
logging.info("now processing %s (%d/%d)" % (wav_name, i + 1, len(wav_list)))
# load wavfile and apply low cut filter
fs, x = wavfile.read(wav_name)
if x.dtype != np.int16:
... | identifier_body |
feature_extract.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2017 Tomoki Hayashi (Nagoya University)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import logging
import multiprocessing as mp
import os
import sys
from distutils.util import strtobool
import librosa
import numpy as np
import... |
# get number of frames
n_frame = (len(x) - fftl) // shiftl + 1
# get window function
win = get_window(window, fftl)
# calculate spectrogram
mcep = [pysptk.mcep(x[shiftl * i: shiftl * i + fftl] * win,
dim, alpha, eps=EPS, etype=1)
for i in range(n_frame)]
... | n_pad = fftl - (len(x) - fftl) % shiftl
x = np.pad(x, (0, n_pad), 'reflect') | conditional_block |
main.py | import hmac
import sqlite3
import urllib2
import time
import datetime
import webapp2
import jinja2
import os
import re
import random
import hashlib
from google.appengine.ext import db
#base template start
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jin... |
EMAIL_RE = re.compile(r'^[\S]+@[\S]+\.[\S]+$')
def valid_email(email):
return not email or EMAIL_RE.match(email)
class SignUp(BaseHandler):
def get(self):
if self.username != None:
self.redirect('/welcome')
# if valid_username(self.username):
# self.render('welcome.html', username = self.username)
el... | return password and PASS_RE.match(password) | identifier_body |
main.py | import hmac
import sqlite3
import urllib2
import time
import datetime
import webapp2
import jinja2
import os
import re
import random
import hashlib
from google.appengine.ext import db
#base template start
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jin... | if not valid_email(email):
params['error_email'] = "That's not a valid email."
have_error = True
if have_error:
self.render('signup-form.html', **params)
else:
# cooked = 'name=' + uname + ';Path=/'
# self.response.headers.add_header('Set-Cookie',str(cooked))
# self.set_cook('name', uname)
u... | elif password != verify:
params['error_verify'] = "Your passwords didn't match."
have_error = True
| random_line_split |
main.py | import hmac
import sqlite3
import urllib2
import time
import datetime
import webapp2
import jinja2
import os
import re
import random
import hashlib
from google.appengine.ext import db
#base template start
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jin... |
if(int(stk_qty) == int(dat[2])):
print('equal')
conn.execute("INSERT INTO transactionRequests VALUES (?,?,?,?,?,?)", (self.username,stk_qty,sname,stk_price,t_now,"SELL--FAILED"))
conn.execute("DELETE FROM stocks WHERE stk_symbl=?",(sname,))
u.curr_balance = int(u.curr_balance + tot_cost)
u.put()... | conn.execute("INSERT INTO transactionRequests VALUES (?,?,?,?,?,?)", (self.username,stk_qty,sname,stk_price,t_now,"SELL--FAILED"))
print('naaah boy') | conditional_block |
main.py | import hmac
import sqlite3
import urllib2
import time
import datetime
import webapp2
import jinja2
import os
import re
import random
import hashlib
from google.appengine.ext import db
#base template start
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jin... | (self):
uname=self.request.get('username')
passwd=self.request.get('password')
u=User.login(uname, passwd)
if u:
self.login(u)
self.redirect('/welcome')
else:
msg = 'Invalid login'
self.render('login-form.html', error = msg)
class LogOut(BaseHandler):
def get(self):
self.logout()
self.redire... | post | identifier_name |
exception.rs | // Copyright 2020 Datafuse Labs.
//
// 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 ... |
impl ErrorCode {
pub fn from_std_error<T: std::error::Error>(error: T) -> Self {
ErrorCode {
code: 1002,
display_text: format!("{}", error),
cause: None,
backtrace: Some(ErrorCodeBacktrace::Origin(Arc::new(Backtrace::new()))),
}
}
pub fn crea... | error
))
}
} | random_line_split |
exception.rs | // Copyright 2020 Datafuse Labs.
//
// 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 ... | (error: std::num::ParseIntError) -> Self {
ErrorCode::from_std_error(error)
}
}
impl From<std::num::ParseFloatError> for ErrorCode {
fn from(error: std::num::ParseFloatError) -> Self {
ErrorCode::from_std_error(error)
}
}
impl From<common_arrow::arrow::error::ArrowError> for ErrorCode {
... | from | identifier_name |
exception.rs | // Copyright 2020 Datafuse Labs.
//
// 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 ... |
}
impl From<std::num::ParseFloatError> for ErrorCode {
fn from(error: std::num::ParseFloatError) -> Self {
ErrorCode::from_std_error(error)
}
}
impl From<common_arrow::arrow::error::ArrowError> for ErrorCode {
fn from(error: common_arrow::arrow::error::ArrowError) -> Self {
ErrorCode::fro... | {
ErrorCode::from_std_error(error)
} | identifier_body |
mailbox.rs | // use byteorder::{ByteOrder, NativeEndian};
use core::{
convert::TryInto,
fmt, mem, ops, slice,
sync::atomic::{fence, Ordering},
};
use field_offset::offset_of;
use super::mmu::align_up;
const MAIL_BASE: usize = 0xB880;
const MAIL_FULL: u32 = 0x8000_0000;
const MAIL_EMPTY: u32 = 0x4000_0000;
// const M... | (base: usize, offset: u8, value: u32) {
((MAPPED_REGISTERS_BASE + base + offset as usize) as *mut u32).write_volatile(value)
}
unsafe fn read_mailbox(channel: u8) -> u32 {
// 1. Read the status register until the empty flag is not set.
// 2. Read data from the read register.
// 3. If the lower four bit... | write_reg | identifier_name |
mailbox.rs | // use byteorder::{ByteOrder, NativeEndian};
use core::{
convert::TryInto,
fmt, mem, ops, slice,
sync::atomic::{fence, Ordering},
};
use field_offset::offset_of;
use super::mmu::align_up;
const MAIL_BASE: usize = 0xB880;
const MAIL_FULL: u32 = 0x8000_0000;
const MAIL_EMPTY: u32 = 0x4000_0000;
// const M... |
limit -= 1;
}
write_reg(MAIL_BASE, MAILBOX_OFFFSETS.write, data | (channel as u32));
fence(Ordering::SeqCst);
// println!("Finished writing to mailbox");
}
pub trait PropertyTagList: Sized {
fn prepare(self) -> PropertyMessageWrapper<Self> {
PropertyMessageWrapper::new(self)
}
... | {
panic!(
"Gave up waiting for space to write to mailbox (channel {}, data: 0x{:08x})",
channel, data
);
} | conditional_block |
mailbox.rs | // use byteorder::{ByteOrder, NativeEndian};
use core::{
convert::TryInto,
fmt, mem, ops, slice,
sync::atomic::{fence, Ordering},
};
use field_offset::offset_of;
use super::mmu::align_up;
const MAIL_BASE: usize = 0xB880;
const MAIL_FULL: u32 = 0x8000_0000;
const MAIL_EMPTY: u32 = 0x4000_0000;
// const M... |
#[repr(u8)]
#[derive(Copy, Clone, Debug)]
pub enum Channel {
Power = 0,
Framebuffer = 1,
VirtualUART = 2,
VCHIQ = 3,
LEDs = 4,
Buttons = 5,
TouchScreen = 6,
Unknown7 = 7,
PropertyTagsSend = 8,
PropertyTagsReceive = 9,
}
| {
let resp: u32;
let msg_ptr = msg as *mut T;
let msg_addr_usize = msg_ptr as usize;
let msg_addr_u32 = msg_addr_usize.try_into().map_err(|_| ())?;
unsafe {
write_mailbox(channel as u8, msg_addr_u32);
resp = read_mailbox(channel as u8);
}
// println!(
// "Got response... | identifier_body |
mailbox.rs | // use byteorder::{ByteOrder, NativeEndian};
use core::{
convert::TryInto,
fmt, mem, ops, slice,
sync::atomic::{fence, Ordering},
};
use field_offset::offset_of;
use super::mmu::align_up;
const MAIL_BASE: usize = 0xB880;
const MAIL_FULL: u32 = 0x8000_0000;
const MAIL_EMPTY: u32 = 0x4000_0000;
// const M... | // Check the channel (lowest 4 bits) of the read value for the correct channel
// If the channel is not the one we wish to read from (i.e: 1), go to step 1
// Return the data (i.e: the read value >> 4)
// println!("Reading mailbox (want channel {})", channel);
let mut limit = 10;
loop {
... | // Execute a memory barrier
// Read from MAIL0_READ | random_line_split |
internal.rs | extern crate proc_macro;
use ink_lang_ir::Callable;
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{
format_ident,
quote,
};
use std::{
collections::HashMap,
convert::TryFrom,
};
use syn::{
ext::IdentExt,
parenthesized,
parse::{
Parse,
... |
let external_ink_methods_iter = ink_methods.iter_mut().map(|(_, value)| {
value.sig.ident = format_ident!("{}_{}{}", BRUSH_PREFIX, value.sig.ident, EXTERNAL_METHOD_SUFFIX);
value
});
let external_trait_ident = format_ident!("{}_{}{}", BRUSH_PREFIX, trait_ident, EXTERNAL_TRAIT_SUFFIX);
/... | {
let name = format!("{}", trait_name.unwrap());
metadata_name_attr = quote! { #[ink(metadata_name = #name)] }
} | conditional_block |
internal.rs | extern crate proc_macro;
use ink_lang_ir::Callable;
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{
format_ident,
quote,
};
use std::{
collections::HashMap,
convert::TryFrom,
};
use syn::{
ext::IdentExt,
parenthesized, | Parse,
ParseStream,
},
ItemImpl,
};
use crate::{
metadata::Metadata,
trait_definition::{
EXTERNAL_METHOD_SUFFIX,
EXTERNAL_TRAIT_SUFFIX,
WRAPPER_TRAIT_SUFFIX,
},
};
pub(crate) const BRUSH_PREFIX: &'static str = "__brush";
pub(crate) struct MetaList {
pub... | parse::{ | random_line_split |
internal.rs | extern crate proc_macro;
use ink_lang_ir::Callable;
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{
format_ident,
quote,
};
use std::{
collections::HashMap,
convert::TryFrom,
};
use syn::{
ext::IdentExt,
parenthesized,
parse::{
Parse,
... | (input: ParseStream) -> syn::Result<Self> {
let path = input.call(parse_meta_path)?;
parse_meta_list_after_path(path, input)
}
}
pub(crate) enum NestedMeta {
Path(syn::Path),
List(MetaList),
}
impl Parse for NestedMeta {
fn parse(input: ParseStream) -> syn::Result<Self> {
let p... | parse | identifier_name |
internal.rs | extern crate proc_macro;
use ink_lang_ir::Callable;
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{
format_ident,
quote,
};
use std::{
collections::HashMap,
convert::TryFrom,
};
use syn::{
ext::IdentExt,
parenthesized,
parse::{
Parse,
... |
fn parse_meta_list_after_path(path: syn::Path, input: ParseStream) -> syn::Result<MetaList> {
let content;
Ok(MetaList {
path,
_paren_token: parenthesized!(content in input),
nested: content.parse_terminated(TokenStream2::parse)?,
})
}
fn parse_meta_after_path(path: syn::Path, inp... | {
Ok(syn::Path {
leading_colon: input.parse()?,
segments: {
let mut segments = syn::punctuated::Punctuated::new();
while input.peek(syn::Ident::peek_any) {
let ident = syn::Ident::parse_any(input)?;
segments.push_value(syn::PathSegment::from(id... | identifier_body |
data.py | # -*- coding: utf-8 -*-
"""
coref.data
~~~~~~~~~~~~
File Processor
Parses 'Coreference Resolution Input File'
:copyright: (c) 2012 by Adam Walz, Charmaine Keck
:license:
"""
import re
from os import strerror
from sys import stderr
from time import sleep
from errno import EIO
from xml.dom.minid... | #sent = sent[sent.find('\n\n\n'):]
removed = r'[\n ]+'
sent = re.sub(removed, ' ', sent)
return sent.strip()
def _normalize_malformed_xml(xml):
"""Ensures that xml begins and ends with <TXT> </TXT> tags
Args:
xml: string, text to be formatted as xml
Returns:
string, forma... |
""" | random_line_split |
data.py | # -*- coding: utf-8 -*-
"""
coref.data
~~~~~~~~~~~~
File Processor
Parses 'Coreference Resolution Input File'
:copyright: (c) 2012 by Adam Walz, Charmaine Keck
:license:
"""
import re
from os import strerror
from sys import stderr
from time import sleep
from errno import EIO
from xml.dom.minid... |
def get_id(path):
"""Parses a file path for the filename without extension
Args:
path: string, full (or relative) file path for coreference file.
Must end in .crf
Returns:
string, file id (filename without extension)
>>> path = '/home/user/Desktop/full.crf'
>>> ge... | return parses | conditional_block |
data.py | # -*- coding: utf-8 -*-
"""
coref.data
~~~~~~~~~~~~
File Processor
Parses 'Coreference Resolution Input File'
:copyright: (c) 2012 by Adam Walz, Charmaine Keck
:license:
"""
import re
from os import strerror
from sys import stderr
from time import sleep
from errno import EIO
from xml.dom.minid... | ():
"""Creates a unique coreference id tag
Note: only unique if input id's are not of the form num+alpha
Returns:
string, alphanumeric unique id
"""
num, alpha = int(_mk_coref_id.id[:-1]), _mk_coref_id.id[-1]
if alpha == 'Z':
alpha = 'A'
num += 1
else:
alpha... | _mk_coref_id | identifier_name |
data.py | # -*- coding: utf-8 -*-
"""
coref.data
~~~~~~~~~~~~
File Processor
Parses 'Coreference Resolution Input File'
:copyright: (c) 2012 by Adam Walz, Charmaine Keck
:license:
"""
import re
from os import strerror
from sys import stderr
from time import sleep
from errno import EIO
from xml.dom.minid... |
class FilenameException(Exception):
"""Raised when file does not have the correct extension"""
pass
def mk_parses(listfile, corenlp_host):
"""Creates a list of FileParse objects for the files listed in the listfile
Args:
listfile: string, path to input listfile (see assignment description
... | self.ptree = parse[0]
self.words = parse[1]
self.dependencies = parse[2]
self.text = parse[3] | identifier_body |
lucidLog-1.0.0.source.js | seductiveapps.lucidLog = sa.l = {
about : {
whatsThis : 'seductiveapps.lucidLog = sa.l = A better console log for web applications.',
copyright : '(c) (r) 2013-2014 by [the owner of seductiveapps.com] <info@seductiveapps.com>',
license : 'http://seductiveapps.com/seductiveapps/license.txt',
noWarranty : '... | if (document.getElementById ('iframe-content'))
jQuery(document.getElementById ('iframe-content').contentWindow).unbind('mousemove');
dragging = false;
}
});
}
} // sa.l.tools
}; |
jQuery(window).mouseup(function(e){
if (dragging) {
jQuery('#ghostbar').remove();
jQuery(window).unbind('mousemove');
| random_line_split |
lucidLog-1.0.0.source.js | seductiveapps.lucidLog = sa.l = {
about : {
whatsThis : 'seductiveapps.lucidLog = sa.l = A better console log for web applications.',
copyright : '(c) (r) 2013-2014 by [the owner of seductiveapps.com] <info@seductiveapps.com>',
license : 'http://seductiveapps.com/seductiveapps/license.txt',
noWarranty : '... | ;
ua.logMessages = lmn;
};
if (ua.calls) {
for (var i=0; i<ua.calls.length; i++) {
/*
if (!sa.l.settings.gottaCleanup) sa.l.settings.gottaCleanup = [];
sa.l.settings.gottaCleanup[sa.l.settings.gottaCleanup.length] = {
ua : ua.calls[i]
};
*/
sa.l.cleanupTracerData (ua.ca... | {
lmn[lm[i][0]] = lm[i][1][1];
} | conditional_block |
index.ts | /** Stores various indices on all files in the vault to make dataview generation fast. */
import { MetadataCache, Vault, TFile } from 'obsidian';
import { Task } from 'src/tasks';
import * as Tasks from 'src/tasks';
/** Aggregate index which has several sub-indices and will initialize all of them. */
export class Full... |
node.totalCount += 1;
node.files.add(path);
}
public static remove(root: PrefixIndexNode, path: string) {
let parts = path.split("/");
let node = root;
let nodes = [];
for (let index = 0; index < parts.length - 1; index++) {
if (!node.children.has(p... | {
if (!node.children.has(parts[index])) node.children.set(parts[index], new PrefixIndexNode(parts[index]));
node.totalCount += 1;
node = node.children.get(parts[index]) as PrefixIndexNode;
} | conditional_block |
index.ts | /** Stores various indices on all files in the vault to make dataview generation fast. */
import { MetadataCache, Vault, TFile } from 'obsidian';
import { Task } from 'src/tasks';
import * as Tasks from 'src/tasks';
/** Aggregate index which has several sub-indices and will initialize all of them. */
export class Full... | {
// TODO: Instead of only storing file paths at the leaf, consider storing them at every level,
// since this will make for faster deletes and gathers in exchange for slightly slower adds and more memory usage.
// since we are optimizing for gather, and file paths tend to be shallow, this should be ok.
... | PrefixIndexNode | identifier_name |
index.ts | /** Stores various indices on all files in the vault to make dataview generation fast. */
import { MetadataCache, Vault, TFile } from 'obsidian';
import { Task } from 'src/tasks';
import * as Tasks from 'src/tasks';
/** Aggregate index which has several sub-indices and will initialize all of them. */
export class Full... |
/** Get the tasks associated with a file path. */
public get(file: string): Task[] | null {
let result = this.cache[file];
if (result === undefined) return null;
else return result;
}
/** Return a map of all files -> tasks in that file. */
public all(): Record<string, Task... | {
this.vault = vault;
this.cache = cache;
} | identifier_body |
simple-job-board-public.js | /**
* Simple Job Board Core Front-end JS File - V 1.4.0
*
* @author PressTigers <support@presstigers.com>, 2016
*
* Actions List
* - Job Application Submission Callbacks
* - Date Picker Initialization
* - Validate Email
* - Initialize TelInput Plugin
* - Validate Phone Number
* - Allowable Uploa... | ( event ) {
var error_free = true;
$(".sjb-attachment").each(function () {
var element = $("#" + $(this).attr("id"));
var valid = element.hasClass("valid");
var is_required_class = element.hasClass("sjb-not-required");
... | sjb_is_attachment | identifier_name |
simple-job-board-public.js | /**
* Simple Job Board Core Front-end JS File - V 1.4.0
*
* @author PressTigers <support@presstigers.com>, 2016
*
* Actions List
* - Job Application Submission Callbacks
* - Date Picker Initialization
* - Validate Email
* - Initialize TelInput Plugin
* - Validate Phone Number
* - Allowable Uploa... | }
});
/**
* Initialize TelInput Plugin
*
* @since 2.2.0
*/
if ($('.sjb-phone-number').length) {
var telInput_id = $('.sjb-phone-number').map(function () {
return this.id;
}).get();
for (var i... | random_line_split | |
simple-job-board-public.js | /**
* Simple Job Board Core Front-end JS File - V 1.4.0
*
* @author PressTigers <support@presstigers.com>, 2016
*
* Actions List
* - Job Application Submission Callbacks
* - Date Picker Initialization
* - Validate Email
* - Initialize TelInput Plugin
* - Validate Phone Number
* - Allowable Uploa... |
/**
* Remove Required Attribute from Checkbox Group -> When one of the option is selected.
* Add Required Attribute from Checkboxes Group -> When none of the option is selected.
*
* @since 2.3.0
*/
var requiredCheckboxes = $(':checkbox[required]'... | {
var jobpost_form_inputs = $("." + input_class).serializeArray();
var error_free = true;
for (var i in jobpost_form_inputs) {
var element = $("#" + jobpost_form_inputs[i]['name']);
var valid = element.hasClass("valid");
var is_require... | identifier_body |
simple-job-board-public.js | /**
* Simple Job Board Core Front-end JS File - V 1.4.0
*
* @author PressTigers <support@presstigers.com>, 2016
*
* Actions List
* - Job Application Submission Callbacks
* - Date Picker Initialization
* - Validate Email
* - Initialize TelInput Plugin
* - Validate Phone Number
* - Allowable Uploa... | else {
input.removeClass("valid").addClass("invalid");
}
});
/**
* Initialize TelInput Plugin
*
* @since 2.2.0
*/
if ($('.sjb-phone-number').length) {
var telInput_id = $('.sjb-phone-number').map(function () {
... | {
input.removeClass("invalid").addClass("valid");
error_element.hide();
} | conditional_block |
train_timeline.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
import os.path
import os
import time
import sys
sys.path.insert(0,'lib')
sys.path.insert(0,'networks')
import tensorflow as tf
from tensorflow.python.client import timeline
from t... | (filename, epoch):
with open(filename, 'r') as f:
for line in f.readlines():
line = line.split('#', 1)[0]
if line:
par = line.strip().split(':')
e = int(par[0])
lr = float(par[1])
if e <= epoch:
learn... | get_learning_rate_from_file | identifier_name |
train_timeline.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
import os.path
import os
import time
import sys
sys.path.insert(0,'lib')
sys.path.insert(0,'networks')
import tensorflow as tf
from tensorflow.python.client import timeline
from t... |
def main(args):
#network = importlib.import_module(args.model_def)
subdir = datetime.strftime(datetime.now(), '%Y%m%d-%H%M%S')
log_dir = os.path.join(os.path.expanduser(args.logs_base_dir), subdir)
if not os.path.isdir(log_dir): # Create the log directory if it doesn't exist
os.makedirs... | return tf_data.Dataset.from_tensor_slices((tensors_x,tensors_y)) | identifier_body |
train_timeline.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
import os.path
import os
import time
import sys
sys.path.insert(0,'lib')
sys.path.insert(0,'networks')
import tensorflow as tf
from tensorflow.python.client import timeline
from te... |
learning_rate = tf.train.exponential_decay(learning_rate_placeholder, global_step,
args.learning_rate_decay_epochs*args.epoch_size, args.learning_rate_decay_factor, staircase=True)
tf.summary.scalar('learning_rate', lear... | #labels_placeholder = tf.Variable(np.ones([args.batch_size,]),dtype=tf.int32, name='labels_placeholder')
phase_train_placeholder = tf.placeholder(tf.bool, name='phase_train')
| random_line_split |
train_timeline.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
import os.path
import os
import time
import sys
sys.path.insert(0,'lib')
sys.path.insert(0,'networks')
import tensorflow as tf
from tensorflow.python.client import timeline
from t... |
def parse_arguments(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--logs_base_dir', type=str,
help='Directory where to write event logs.', default='logs/facenet_ms_mp')
parser.add_argument('--models_base_dir', type=str,
help='Directory where to write trained mod... | return learning_rate | conditional_block |
index.js | //weather search city
let apiKeyWeather = "bd7e1a6abf699f2eca2f3fae90b453ff";
let apiCallWeather = "https://api.openweathermap.org/data/2.5/weather?";
let lastSearchedCityWeather = {};
//Format the date into text
function fDate(currentDate) {
let fDays = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday"... | tion
function findLocation(){
navigator.geolocation.getCurrentPosition(showPosition);
}
let searchCity = document.querySelector("#searchButton");
searchCity.addEventListener("click", searchYourCity);
let searchLocation = document.querySelector("#locationButton");
searchLocation.addEventListener("click", findLocatio... | at = `lat=${lat}`;
let currentLon = `lon=${lon}`;
//api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}
let weatherCheckUrl = apiCallWeather + currentLat + "&" + currentLon + "&appid=" + apiKeyWeather + "&units=" + units;
//Get weather information from URL and then display weather
axio... | identifier_body |
index.js | //weather search city
let apiKeyWeather = "bd7e1a6abf699f2eca2f3fae90b453ff";
let apiCallWeather = "https://api.openweathermap.org/data/2.5/weather?";
let lastSearchedCityWeather = {};
//Format the date into text
function fDate(currentDate) {
let fDays = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday"... | geolocation.getCurrentPosition(showPosition);
}
let searchCity = document.querySelector("#searchButton");
searchCity.addEventListener("click", searchYourCity);
let searchLocation = document.querySelector("#locationButton");
searchLocation.addEventListener("click", findLocation);
let form = document.querySelector("#s... | navigator. | identifier_name |
index.js | //weather search city
let apiKeyWeather = "bd7e1a6abf699f2eca2f3fae90b453ff";
let apiCallWeather = "https://api.openweathermap.org/data/2.5/weather?";
let lastSearchedCityWeather = {};
//Format the date into text
function fDate(currentDate) {
let fDays = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday"... | //If °F is selected
else
{
units = "imperial";
}
return units;
}
//Temperature conversion
function convertFtoC(tempF){
return Math.floor(((tempF -32)*5/9)*100)/100;
}
function convertCtoF(tempC){
return Math.floor(((tempC*9/5) + 32)*100)/100;
}
//Unit conversions
function convertUnit... |
units = "metric";
}
| conditional_block |
index.js | //weather search city
let apiKeyWeather = "bd7e1a6abf699f2eca2f3fae90b453ff";
let apiCallWeather = "https://api.openweathermap.org/data/2.5/weather?";
let lastSearchedCityWeather = {};
//Format the date into text
function fDate(currentDate) {
let fDays = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday"... | return units;
}
//Temperature conversion
function convertFtoC(tempF){
return Math.floor(((tempF -32)*5/9)*100)/100;
}
function convertCtoF(tempC){
return Math.floor(((tempC*9/5) + 32)*100)/100;
}
//Unit conversions
function convertUnits(){
let windSpeed = document.querySelector("#wind_Speed");
let fee... | } | random_line_split |
web.go | package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/smtp"
"os"
"reflect"
"regexp"
"strconv"
"sync"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
type Mail struct {
Subject string `json:"subject"`
FullName string `... |
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
w.WriteHeader(statusCode)
w.Write(resp)
}
func (c *Config) Populate() {
content, err := ioutil.ReadFile(path("/config/app.json"))
if err != nil {
... | {
http.Error(w, "Failed to encode content to JSON", http.StatusInternalServerError)
return
} | conditional_block |
web.go | package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/smtp"
"os"
"reflect"
"regexp"
"strconv"
"sync"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
type Mail struct {
Subject string `json:"subject"`
FullName string `... |
// Append an error message to slice if value fails the checks
func validateField(f *Field, hash map[string]string) {
length := 0
if f.Value != "" {
length = len(f.Value)
}
switch {
case length < f.Length.Min || length > f.Length.Max:
hash[f.Name] = fmt.Sprintf(LENGTH_ERROR, f.DisplayName, f.Length.Min, f.Le... | random_line_split | |
web.go | package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/smtp"
"os"
"reflect"
"regexp"
"strconv"
"sync"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
type Mail struct {
Subject string `json:"subject"`
FullName string `... |
// Append an error message to slice if value fails the checks
func validateField(f *Field, hash map[string]string) {
length := 0
if f.Value != "" {
length = len(f.Value)
}
switch {
case length < f.Length.Min || length > f.Length.Max:
hash[f.Name] = fmt.Sprintf(LENGTH_ERROR, f.DisplayName, f.Length.Min, f.L... | {
return *h + ":" + strconv.FormatUint(uint64(*p), 10)
} | identifier_body |
web.go | package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/smtp"
"os"
"reflect"
"regexp"
"strconv"
"sync"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
type Mail struct {
Subject string `json:"subject"`
FullName string `... | (w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(io.LimitReader(r.Body, PAYLOAD_MAX_SIZE))
if err != nil {
http.Error(w, "Failed to read body from HTTP request", http.StatusInternalServerError)
return
}
mail := new(Mail)
err = json.Unmarshal(body, &mail)
if err != nil {
http.Error(... | handleWriteEmail | identifier_name |
scraper.py | #!/usr/bin/env python
"""
Provides client interface to Plans.
"""
import sys
if sys.version_info >= (3,3):
from urllib.parse import urlparse, parse_qsl
from http.cookiejar import LWPCookieJar
from html.parser import HTMLParser
elif sys.version_info < (3,):
from urlparse import urlparse, parse_qsl
... | (self):
"""
Retrieve all levels of the autofinger (autoread) list.
Returns a dictionary where the keys are the group names
"Level 1", "Level 2", etc. and the values are a list of
usernames waiting to be read.
"""
# this actually doesn't scrape; there's a functio... | get_autofinger | identifier_name |
scraper.py | #!/usr/bin/env python
"""
Provides client interface to Plans.
"""
import sys
if sys.version_info >= (3,3):
from urllib.parse import urlparse, parse_qsl
from http.cookiejar import LWPCookieJar
from html.parser import HTMLParser
elif sys.version_info < (3,):
from urlparse import urlparse, parse_qsl
... | verify=url.startswith('https'))
except requests.exceptions.ConnectionError:
err = "Check your internet connection. Plans could also be down."
raise PlansError(err)
return handle
def _parse_message(self, soup):
"""
Scrape... | url = '/'.join((self.base_url, name))
req = requests.Request(method, url, params=get, data=post)
prepped = self.session.prepare_request(req)
try:
handle = self.session.send(prepped, | random_line_split |
scraper.py | #!/usr/bin/env python
"""
Provides client interface to Plans.
"""
import sys
if sys.version_info >= (3,3):
from urllib.parse import urlparse, parse_qsl
from http.cookiejar import LWPCookieJar
from html.parser import HTMLParser
elif sys.version_info < (3,):
from urlparse import urlparse, parse_qsl
... |
self.session = requests.Session()
self.session.cookies = self.cookiejar
self.parser = PlansPageParser()
self.username = None
def _get_page(self, name, get=None, post=None):
"""
Retrieve an HTML page from plans.
"""
method = 'GET' if post is None els... | self.cookiejar = cookiejar | conditional_block |
scraper.py | #!/usr/bin/env python
"""
Provides client interface to Plans.
"""
import sys
if sys.version_info >= (3,3):
from urllib.parse import urlparse, parse_qsl
from http.cookiejar import LWPCookieJar
from html.parser import HTMLParser
elif sys.version_info < (3,):
from urlparse import urlparse, parse_qsl
... | """
Return plans updated in the last ``hours`` hours.
The result is a list of (username, timestamp) 2-tuples.
"""
post = {'mytime': str(hours)}
response = self._get_page('planwatch.php', post=post)
soup = bs4.BeautifulSoup(response.text, 'html5lib')
results = so... | identifier_body | |
AnimePageFetcher.py | import requests
import re
import sys
from bs4 import BeautifulSoup
import time
from datetime import datetime
import urllib
# Finds instances of #24332
rank_regex = re.compile(r"#(\d+)")
# Finds instances of 342,543,212
number_regex = re.compile(r"[\d,]+")
# Finds instances of 4 hr.
hours_regex = re.compile(r"(\d+) h... | (html, aggregate_data={}):
getStatSummary(html, aggregate_data)
getStatDistribution(html, aggregate_data)
return aggregate_data
def getStatSummary(html, aggregate_dict={}):
#soup = BeautifulSoup(html, 'html.parser')
start_index = stats_summary_regex.search(html).end()
end_index = stats_score_re... | scrape_stats_page | identifier_name |
AnimePageFetcher.py | import requests
import re
import sys
from bs4 import BeautifulSoup
import time
from datetime import datetime
import urllib
# Finds instances of #24332
rank_regex = re.compile(r"#(\d+)")
# Finds instances of 342,543,212
number_regex = re.compile(r"[\d,]+")
# Finds instances of 4 hr.
hours_regex = re.compile(r"(\d+) h... | with open(out_file, 'w') as f:
soup = BeautifulSoup(html, 'html.parser')
html = soup.prettify()
f.write(html.encode("utf8"))
return html
def load_html_from_file(file):
with open(file, 'r') as f:
html = f.read()
return html
#these are the stats found on the stat... | print "Writing html to", out_file
print "Type is", type(html) | random_line_split |
AnimePageFetcher.py | import requests
import re
import sys
from bs4 import BeautifulSoup
import time
from datetime import datetime
import urllib
# Finds instances of #24332
rank_regex = re.compile(r"#(\d+)")
# Finds instances of 342,543,212
number_regex = re.compile(r"[\d,]+")
# Finds instances of 4 hr.
hours_regex = re.compile(r"(\d+) h... |
else:
aggregate_dict["duration"] = None
# Info/Rating
if "Rating" in info_dict:
rating_text = info_dict["Rating"]
rating_shorthand = rating_text.split(" - ")[0].strip()
aggregate_dict["rating"] = rating_shorthand
else:
aggregate_dict["rating"] = None
return... | duration_text = info_dict["Duration"]
mins = 0.0
# Hours
match = hours_regex.search(duration_text)
if match is not None:
mins += float(match.group(1)) * 60.0
# Minutes
match = min_regex.search(duration_text)
if match is not None:
mins += fl... | conditional_block |
AnimePageFetcher.py | import requests
import re
import sys
from bs4 import BeautifulSoup
import time
from datetime import datetime
import urllib
# Finds instances of #24332
rank_regex = re.compile(r"#(\d+)")
# Finds instances of 342,543,212
number_regex = re.compile(r"[\d,]+")
# Finds instances of 4 hr.
hours_regex = re.compile(r"(\d+) h... |
#Fetches the characters and voice actors associted with a show
#Example: https://myanimelist.net/anime/30/Neon_Genesis_Evangelion/characters
def getCharactersAndJapaneseCast(html):
return
#Fetches the list of other related anime, same series etc.
def getRelatedTitles(html):
return
def cooldown():
COOLDO... | return | identifier_body |
spider.js | //casperjs --disk-cache=yes spider.js --web-security=no
var casper = require('casper').create({
pageSettings: {
//navigationRequested: true,
//请求资源等待时间
resourceTimeout: 1000,
loadImages: false,
//loadPlugins: false,
userAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWeb... | // if (before === after) {
// result["weather" + (i + 1)] = before;
// } else {
// result["weather" + (i + 1)] = before + "转" + after;
// }
// //温度,5°/10°
// result["temp" + (i + 1)] = futures[i].querySelector("span").innerHTML;
// ... | // var before = img[0].getAttribute("alt");
// var after = img[1].getAttribute("alt");
// result["img_title" + (i + 1)] = before;
// result["img_title" + (i + 2)] = after;
// //天气转变,多云转晴 | random_line_split |
spider.js | //casperjs --disk-cache=yes spider.js --web-security=no
var casper = require('casper').create({
pageSettings: {
//navigationRequested: true,
//请求资源等待时间
resourceTimeout: 1000,
loadImages: false,
//loadPlugins: false,
userAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWeb... | var start = new Date().getTime();
var result = {};
this.waitForSelector("div.fl h1", (function () {
// ------------- Today weather --------------
result["cityId"] = cityId;
var city = this.getHTML('div.cityName.clearfix div.fl h2');
if (city === null) {
result["cit... | _utils__.sendAJAX(host, 'POST', result, false,
{
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
});
} catch (e) {
__utils__.log("Server error:" + e, 'error');
}
}
function grab(cityId) {
| identifier_body |
spider.js | //casperjs --disk-cache=yes spider.js --web-security=no
var casper = require('casper').create({
pageSettings: {
//navigationRequested: true,
//请求资源等待时间
resourceTimeout: 1000,
loadImages: false,
//loadPlugins: false,
userAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWeb... | Resource.requested:" + request.url, 'info');
}
});
//casper.on('navigation.requested', function (url, navigationType, navigationLocked, isMainFrame) {
// //this.log("navigation.requested:" + url + " " + navigationType + " " + navigationLocked + " " + isMainFrame, 'info');
//});
//
//casper.on('page.resource.req... | resource.requested:" + request.url,'info');
request.abort();
} else {
//this.log(" | conditional_block |
spider.js | //casperjs --disk-cache=yes spider.js --web-security=no
var casper = require('casper').create({
pageSettings: {
//navigationRequested: true,
//请求资源等待时间
resourceTimeout: 1000,
loadImages: false,
//loadPlugins: false,
userAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWeb... | result["city"] = this.getHTML('div.cityName.clearfix div.fl h3');
} else {
result['city'] = city;
}
result["date"] = this.getHTML('#tabDays > p').replace(/[^0-9:-\s]/ig, "");
result["district"] = this.getHTML('div.cityName.clearfix div.fl h1');
var now = new Date();
result["sysdate... | null) {
| identifier_name |
real_time_plotting_new.py | '''
file: live_plotting.py
Created by: Curtis Puetz 2018-07-08
Improved by: Kimberlee Dube 2019-07-16
note to users:
1) you must hard code in the location you want to LOAD from your log files within the
read_last_line_in_data_log() function on the line:
log_file_path = r"C:\\Users\puetz\Desktop\Telemtry_logs"
2) the... | (projection=ccrs.PlateCarree()):
"""
Code from https://ocefpaf.github.io/python4oceanographers/blog/2015/06/22/osm/
"""
fig, ax = plt.subplots(figsize=(9, 13),
subplot_kw=dict(projection=projection))
gl = ax.gridlines(draw_labels=True)
gl.xlabels_top = gl.ylabels_right... | make_map | identifier_name |
real_time_plotting_new.py | '''
file: live_plotting.py
Created by: Curtis Puetz 2018-07-08
Improved by: Kimberlee Dube 2019-07-16
note to users:
1) you must hard code in the location you want to LOAD from your log files within the
read_last_line_in_data_log() function on the line:
log_file_path = r"C:\\Users\puetz\Desktop\Telemtry_logs"
2) the... | gl.xlabels_top = gl.ylabels_right = False
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
return fig, ax
def save_map_image(loc):
"""
Code adapted from https://ocefpaf.github.io/python4oceanographers/blog/2015/06/22/osm/
Grab google maps image covering geographic are... | fig, ax = plt.subplots(figsize=(9, 13),
subplot_kw=dict(projection=projection))
gl = ax.gridlines(draw_labels=True) | random_line_split |
real_time_plotting_new.py | '''
file: live_plotting.py
Created by: Curtis Puetz 2018-07-08
Improved by: Kimberlee Dube 2019-07-16
note to users:
1) you must hard code in the location you want to LOAD from your log files within the
read_last_line_in_data_log() function on the line:
log_file_path = r"C:\\Users\puetz\Desktop\Telemtry_logs"
2) the... | data = data.split(',')
plot_data(data, header, axes, map_ax, img) | conditional_block | |
real_time_plotting_new.py | '''
file: live_plotting.py
Created by: Curtis Puetz 2018-07-08
Improved by: Kimberlee Dube 2019-07-16
note to users:
1) you must hard code in the location you want to LOAD from your log files within the
read_last_line_in_data_log() function on the line:
log_file_path = r"C:\\Users\puetz\Desktop\Telemtry_logs"
2) the... |
def plot_data(data, header_data, axes, map_ax, img):
'''
Plot a single data point for each of the plots defined in 'set_up_plots()'
This will occur each time a comma separated data list is received
Written by Curtis Puetz 2018-07-07
Rewritten by Kimberlee Dube 2019-07-17
:param data: the li... | '''
Set the the axes of the desired plots
Written by Curtis Puetz 2018-07-07
Completely changed by Kimberlee Dube 2019-07-17
:return: None
'''
fig, axes = plt.subplots(2, 2, figsize=(20, 15), num=1,
sharex=False, sharey=False)
ax0 = axes[0, 0]
ax0.set_title(... | identifier_body |
main.go | // Copyright 2018-2021 CERN
//
// 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 wr... | sd.ID = share.Id.OpaqueId
}
if s := share.GetPermissions().GetPermissions(); s != nil {
sd.Permissions = RoleFromResourcePermissions(share.GetPermissions().GetPermissions(), true).OCSPermissions()
}
if share.Expiration != nil {
sd.Expiration = timestampToExpiration(share.Expiration)
}
if share.Ctime != ni... | if share.Id != nil { | random_line_split |
main.go | // Copyright 2018-2021 CERN
//
// 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 wr... | // PublicShare2ShareData converts a cs3api public share into shareData data model
func PublicShare2ShareData(share *link.PublicShare, r *http.Request, publicURL string) *ShareData {
sd := &ShareData{
// share.permissions are mapped below
// Displaynames are added later
ShareType: ShareTypePublicLink,
Token:... | sd := &ShareData{
// share.permissions are mapped below
// Displaynames are added later
UIDOwner: LocalUserIDToString(share.GetCreator()),
UIDFileOwner: LocalUserIDToString(share.GetOwner()),
}
if share.Grantee.Type == provider.GranteeType_GRANTEE_TYPE_USER {
sd.ShareType = ShareTypeUser
sd.ShareWit... | identifier_body |
main.go | // Copyright 2018-2021 CERN
//
// 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 wr... | anager string, m map[string]map[string]interface{}) (user.Manager, error) {
if f, ok := usermgr.NewFuncs[manager]; ok {
return f(m[manager])
}
return nil, fmt.Errorf("driver %s not found for user manager", manager)
}
// GetPublicShareManager returns a connection to a public share manager
func GetPublicShareManag... | tUserManager(m | identifier_name |
main.go | // Copyright 2018-2021 CERN
//
// 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 wr... | return sd
}
// LocalUserIDToString transforms a cs3api user id into an ocs data model without domain name
// TODO ocs uses user names ... so an additional lookup is needed. see mapUserIds()
func LocalUserIDToString(userID *userpb.UserId) string {
if userID == nil || userID.OpaqueId == "" {
return ""
}
return use... | sd.ShareWith = "***redacted***"
sd.ShareWithDisplayname = "***redacted***"
}
| conditional_block |
main.rs | extern crate ginseng;
use ginseng::guest::Guest;
use ginseng::guest::Range;
use std::cmp::min;
use std::cmp::Ordering;
use std:collections::HashMap;
use std::vec::Vec;
fn social_welfare(proposed_allocation: &Vec<(&Guest, u64)>) -> u64
{
let mut total_welfare: u64 = 0;
for (guest, allocation) in proposed_al... | (proposed_allocations: &Vec<(&Guest, u64)>) -> Vec<(usize, Range)>
{
let mut violations: Vec<(usize, Range)> = Vec::new();
let mut index: usize = 0;
for &(guest, amount) in proposed_allocations.iter()
{
// we want to get the guest's forbidden range with the greatest
// min value that is... | invalid_allocations | identifier_name |
main.rs | extern crate ginseng;
use ginseng::guest::Guest;
use ginseng::guest::Range;
use std::cmp::min;
use std::cmp::Ordering;
use std:collections::HashMap;
use std::vec::Vec;
fn social_welfare(proposed_allocation: &Vec<(&Guest, u64)>) -> u64
{
let mut total_welfare: u64 = 0;
for (guest, allocation) in proposed_al... |
// this guy already returns indices instead of references
fn invalid_allocations(proposed_allocations: &Vec<(&Guest, u64)>) -> Vec<(usize, Range)>
{
let mut violations: Vec<(usize, Range)> = Vec::new();
let mut index: usize = 0;
for &(guest, amount) in proposed_allocations.iter()
{
// we want... | {
let mut remaining_memory: u64 = available_memory;
guest_list.iter().map
(
|guest|
{
// if there's no memory left to hand out our job is simple
if remaining_memory == 0
{
0
}
// otherwise get the maximum amount mem... | identifier_body |
main.rs | extern crate ginseng;
use ginseng::guest::Guest;
use ginseng::guest::Range;
use std::cmp::min;
use std::cmp::Ordering;
use std:collections::HashMap;
use std::vec::Vec;
fn social_welfare(proposed_allocation: &Vec<(&Guest, u64)>) -> u64
{
let mut total_welfare: u64 = 0;
for (guest, allocation) in proposed_al... | // which should be checked after getting the result of this
// function
// I think what I really want to return from this is a vector of allocation amounts
// it'll even take up less space than (reference, allocation) pairs and will be much
// less problematic
fn naive_allocation
(
guest_list: &Vec<&Guest>,
av... | random_line_split | |
map.rs | use super::BareDoomMap;
use super::geom::{Coord, Point, Rect, Size};
use std::collections::HashMap;
use std::marker::PhantomData;
use std;
// TODO
// map diagnostics
// - error:
// - info: unused vertex
// - info: unused side
// - info: sector with no sides
// - info: thing not in the map (polyobjs excluded)
/// A... | (&self) -> (Handle<Vertex>, Handle<Vertex>) {
self.0.vertex_indices()
}
pub fn side_indices(&self) -> (Option<Handle<Side>>, Option<Handle<Side>>) {
self.0.side_indices()
}
pub fn has_special(&self) -> bool {
self.0.has_special()
}
pub fn blocks_player(&self) -> bool {... | vertex_indices | identifier_name |
map.rs | use super::BareDoomMap;
use super::geom::{Coord, Point, Rect, Size};
use std::collections::HashMap;
use std::marker::PhantomData;
use std;
// TODO
// map diagnostics
// - error:
// - info: unused vertex
// - info: unused side
// - info: sector with no sides
// - info: thing not in the map (polyobjs excluded)
/// A... | }
}
impl<T> From<usize> for Handle<T> {
fn from(index: usize) -> Self {
Handle(index, PhantomData)
}
}
trait MapComponent {}
pub struct Thing {
point: Point,
doomednum: u32,
}
impl Thing {
pub fn point(&self) -> Point {
self.point
}
pub fn doomednum(&self) -> u32 {
... | random_line_split | |
map.rs | use super::BareDoomMap;
use super::geom::{Coord, Point, Rect, Size};
use std::collections::HashMap;
use std::marker::PhantomData;
use std;
// TODO
// map diagnostics
// - error:
// - info: unused vertex
// - info: unused side
// - info: sector with no sides
// - info: thing not in the map (polyobjs excluded)
/// A... |
pub fn iter_things(&self) -> std::slice::Iter<Thing> {
self.things.iter()
}
pub fn vertex(&self, handle: Handle<Vertex>) -> &Vertex {
&self.vertices[handle.0]
}
pub fn side(&self, handle: Handle<Side>) -> &Side {
&self.sides[handle.0]
}
pub fn sector(&self, handle... | {
self.sectors.iter()
} | identifier_body |
models.py | from django.db import models
from django.urls import reverse # To generate URLS by reversing URL patterns
from django.conf import settings
from django.core.validators import MaxValueValidator, MinValueValidator
# Imports Django's default User system.
from django.contrib.auth.models import User
# Movie rating import... |
import uuid # Required for unique movie instances
from datetime import date
class Director(models.Model):
# Model representing a director.
name = models.CharField(max_length=100)
date_of_birth = models.DateField(null=True, blank=True)
date_of_death = models.DateField('died', null=True, blank=True)
... | super(Movie, self).save(*args, **kwargs)
# Uses a custom save to end date any subCases
orig = Movie.objects.get(id=self.id)
fields_to_update = []
try:
specs = self.get_video_stats()
orig.duration = specs[0]
orig.fps = specs[1]
ori... | identifier_body |
models.py | from django.db import models
from django.urls import reverse # To generate URLS by reversing URL patterns
from django.conf import settings
from django.core.validators import MaxValueValidator, MinValueValidator
# Imports Django's default User system.
from django.contrib.auth.models import User
# Movie rating import... | max_num_find_articles = models.IntegerField('Max number of research articles', default=5, validators=[MinValueValidator(0), MaxValueValidator(100)], help_text="Default number is 5.")
found_articles = models.TextField('Found Research Articles', max_length=5000, null=True, blank=True, help_text="HTML list output ... | fps = models.CharField(max_length=200)
dimensions = models.CharField(max_length=200)
| random_line_split |
models.py | from django.db import models
from django.urls import reverse # To generate URLS by reversing URL patterns
from django.conf import settings
from django.core.validators import MaxValueValidator, MinValueValidator
# Imports Django's default User system.
from django.contrib.auth.models import User
# Movie rating import... | (self, *args, **kwargs):
super(Movie, self).save(*args, **kwargs)
# Uses a custom save to end date any subCases
orig = Movie.objects.get(id=self.id)
fields_to_update = []
try:
specs = self.get_video_stats()
orig.duration = specs[0]
or... | save | identifier_name |
models.py | from django.db import models
from django.urls import reverse # To generate URLS by reversing URL patterns
from django.conf import settings
from django.core.validators import MaxValueValidator, MinValueValidator
# Imports Django's default User system.
from django.contrib.auth.models import User
# Movie rating import... |
super(Movie, orig).save(update_fields=fields_to_update)
import uuid # Required for unique movie instances
from datetime import date
class Director(models.Model):
# Model representing a director.
name = models.CharField(max_length=100)
date_of_birth = models.DateField(null=True, blank=True)
... | orig.found_articles = orig.get_research_articles(self.max_num_find_articles)
fields_to_update.append('found_articles') | conditional_block |
main.py | from dataclasses import dataclass
from scipy.integrate import solve_ivp, simps
from functools import partial
from typing import List, Iterable, Callable, Tuple
from numpy import exp, ndarray, sqrt
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from consts import *
import consts
τ = 2 * np.pi... | lectron interaction, with the electron from both atoms.
# We integrate over 3d space, using cartesian coordinates.
# Calculate proton-electron interaction.
nuc_elec_F = Vec(0., 0., 0.)
for pt in sample_pts:
# We integrate over volume, eg by splitting up into small cubes
# of len dx, and... | ))
print("Sample range: ", sample_range)
# Calculate nucleus-e | conditional_block |
main.py | from dataclasses import dataclass
from scipy.integrate import solve_ivp, simps
|
from numpy import exp, ndarray, sqrt
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from consts import *
import consts
τ = 2 * np.pi
i = complex(0, 1)
# 2020-11-15
"""
One of your goals is to figure out if you can use hydrogen (1d?) WFs as basis functions to create
arbitrary solns to the Sch... | from functools import partial
from typing import List, Iterable, Callable, Tuple | random_line_split |
main.py | from dataclasses import dataclass
from scipy.integrate import solve_ivp, simps
from functools import partial
from typing import List, Iterable, Callable, Tuple
from numpy import exp, ndarray, sqrt
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from consts import *
import consts
τ = 2 * np.pi... | : Callable, x: float, y: Tuple[complex, complex]
) -> Tuple[complex, complex]:
"""
d²ψ/dx² = 2m/ħ² * (V(x) - E)ψ
"""
ψ, φ = y
ψ_p = φ
φ_p = 2 * m_e / ħ ** 2 * (V(x) - E) * ψ
return ψ_p, φ_p
def solve(E: float, V: Callable, ψ0: float, ψ_p0: float, x_span: Tuple[float, float]):
"""
... | E: float, V | identifier_name |
main.py | from dataclasses import dataclass
from scipy.integrate import solve_ivp, simps
from functools import partial
from typing import List, Iterable, Callable, Tuple
from numpy import exp, ndarray, sqrt
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from consts import *
import consts
τ = 2 * np.pi... | 2 n=1 S orbital hydrogen atoms"""
pass
def h2_potential(x: float) -> float:
"""Calcualte the electric potential between 2 hydrogen atoms"""
# Start with the perspectic of one atom. Calculate the interaction between
# its nucleus and the other atom's nucleus, and electron.
# Our convention w... | e to see if we can back-calculate E = -1/2."""
E = -2 / (n + 1) ** 2
x, ψ = h_static(E)
# Calculate potential between the e- field and the nucleus point by integrating.
# todo: Let's do this manually first, then try to apply a scipy.integrate approach.
dx = 1
result = 0
ψ2 = np.conj(ψ) *... | identifier_body |
syncmgr.rs | //!
//! Manages header synchronization with peers.
//!
use nakamoto_common::bitcoin::consensus::params::Params;
use nakamoto_common::bitcoin::network::constants::ServiceFlags;
use nakamoto_common::bitcoin::network::message_blockdata::Inventory;
use nakamoto_common::bitcoin_hashes::Hash;
use nakamoto_common::block::sto... | pub fn new(config: Config, rng: fastrand::Rng, upstream: U, clock: C) -> Self {
let peers = AddressBook::new(rng.clone());
let last_tip_update = None;
let last_peer_sample = None;
let last_idle = None;
let inflight = HashMap::with_hasher(rng.into());
Self {
... |
impl<U: SetTimer + Disconnect + Wire<Event>, C: Clock> SyncManager<U, C> {
/// Create a new sync manager. | random_line_split |
syncmgr.rs | //!
//! Manages header synchronization with peers.
//!
use nakamoto_common::bitcoin::consensus::params::Params;
use nakamoto_common::bitcoin::network::constants::ServiceFlags;
use nakamoto_common::bitcoin::network::message_blockdata::Inventory;
use nakamoto_common::bitcoin_hashes::Hash;
use nakamoto_common::block::sto... | {
/// A block was added to the main chain.
BlockConnected {
/// Block height.
height: Height,
/// Block header.
header: BlockHeader,
},
/// A block was removed from the main chain.
BlockDisconnected {
/// Block height.
height: Height,
/// Bloc... | Event | identifier_name |
syncmgr.rs | //!
//! Manages header synchronization with peers.
//!
use nakamoto_common::bitcoin::consensus::params::Params;
use nakamoto_common::bitcoin::network::constants::ServiceFlags;
use nakamoto_common::bitcoin::network::message_blockdata::Inventory;
use nakamoto_common::bitcoin_hashes::Hash;
use nakamoto_common::block::sto... |
/// Called when a peer disconnected.
pub fn peer_disconnected(&mut self, id: &PeerId) {
self.unregister(id);
}
/// Called when we received a `getheaders` message from a peer.
pub fn received_getheaders<T: BlockReader>(
&mut self,
addr: &PeerId,
(locator_hashes, sto... | {
if link.is_outbound() && !services.has(REQUIRED_SERVICES) {
return;
}
if height > self.best_height().unwrap_or_else(|| tree.height()) {
self.upstream.event(Event::PeerHeightUpdated { height });
}
self.register(socket, height, preferred, link);
... | identifier_body |
syncmgr.rs | //!
//! Manages header synchronization with peers.
//!
use nakamoto_common::bitcoin::consensus::params::Params;
use nakamoto_common::bitcoin::network::constants::ServiceFlags;
use nakamoto_common::bitcoin::network::message_blockdata::Inventory;
use nakamoto_common::bitcoin_hashes::Hash;
use nakamoto_common::block::sto... |
None
}
/// Register a new peer.
fn register(&mut self, socket: Socket, height: Height, preferred: bool, link: Link) {
let last_active = None;
let last_asked = None;
let tip = BlockHash::all_zeros();
self.peers.insert(
socket.addr,
Peer {
... | {
return Some(time);
} | conditional_block |
dtm.py | #!/usr/bin/env python3
import sys, resource, os, shutil, re, string, gc, subprocess
import django
import nltk
from multiprocess import Pool
from nltk.stem import SnowballStemmer
from nltk import word_tokenize
from time import time, sleep
from functools import partial
from sklearn.feature_extraction.text import TfidfVe... | (topic_n,info,topic_ids,vocab_ids,ys):
print(topic_n)
django.db.connections.close_all()
p = "%03d" % (topic_n,)
p = "dtm-output/lda-seq/topic-"+p+"-var-e-log-prob.dat"
tlambda = np.fromfile(p, sep=" ").reshape((info['NUM_TERMS'],info['SEQ_LENGTH']))
for t in range(len(tlambda)):
for py i... | dtm_topic | identifier_name |
dtm.py | #!/usr/bin/env python3
import sys, resource, os, shutil, re, string, gc, subprocess
import django
import nltk
from multiprocess import Pool
from nltk.stem import SnowballStemmer
from nltk import word_tokenize
from time import time, sleep
from functools import partial
from sklearn.feature_extraction.text import TfidfVe... |
return vl
def tokenize(text):
transtable = {ord(c): None for c in string.punctuation + string.digits}
tokens = nltk.word_tokenize(text.translate(transtable))
tokens = [i for i in tokens if len(i) > 2]
return tokens
def add_features(title):
django.db.connections.close_all()
term, created ... | dt = (
docUTset[gamma[0][d]],
topic_ids[gamma[1][d]],
gamma[2][d],
gamma[2][d] / docsizes[gamma[0][d]],
run_id
)
vl.append(dt) | conditional_block |
dtm.py | #!/usr/bin/env python3
import sys, resource, os, shutil, re, string, gc, subprocess
import django
import nltk
from multiprocess import Pool
from nltk.stem import SnowballStemmer
from nltk import word_tokenize
from time import time, sleep
from functools import partial
from sklearn.feature_extraction.text import TfidfVe... | parallel_add = True
all_dts = []
make_t = 0
add_t = 0
def insert_many(values_list):
query='''
INSERT INTO "tmv_app_doctopic"
("doc_id", "topic_id", "score", "scaled_score", "run_id")
VALUES (%s,%s,%s,%s,%s)
... | ps = 16 | random_line_split |
dtm.py | #!/usr/bin/env python3
import sys, resource, os, shutil, re, string, gc, subprocess
import django
import nltk
from multiprocess import Pool
from nltk.stem import SnowballStemmer
from nltk import word_tokenize
from time import time, sleep
from functools import partial
from sklearn.feature_extraction.text import TfidfVe... |
def add_features(title):
django.db.connections.close_all()
term, created = Term.objects.get_or_create(title=title)
term.run_id.add(run_id)
django.db.connections.close_all()
return term.pk
class snowball_stemmer(object):
def __init__(self):
self.stemmer = SnowballStemmer("english")
... | transtable = {ord(c): None for c in string.punctuation + string.digits}
tokens = nltk.word_tokenize(text.translate(transtable))
tokens = [i for i in tokens if len(i) > 2]
return tokens | identifier_body |
Section3.py |
# coding: utf-8
# In[ ]:
from sklearn import datasets
import numpy as np
iris = datasets.load_iris()
X = iris.data[:,[2,3]]
y = iris.target
print("Class labels:",np.unique(y))
print(iris)
# In[ ]:
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_... | np.hstack((y_train,y_test))
plot_decision_regions(X = X_combined_std,y = y_combined,classifier = ppn,test_idx = range(105,150))
plt.xlabel("petal length")
plt.ylabel("petal width")
plt.legend("upper left")
plt.show()
# In[ ]:
import matplotlib.pyplot as plt
import numpy as np
import math
def sigmoid(... | alpha = 1,marker = "o",s = 100, label = "test_set")
# In[ ]:
X_combined_std = np.vstack((X_train_std,X_test_std))
y_combined = | conditional_block |
Section3.py |
# coding: utf-8
# In[ ]:
from sklearn import datasets
import numpy as np
iris = datasets.load_iris()
X = iris.data[:,[2,3]]
y = iris.target
print("Class labels:",np.unique(y))
print(iris)
# In[ ]:
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_... | ,c1,label = "J(w) y = 1")
c0 = [cost_0(x) for x in z]
plt.plot(phi_z,c0,label = "J(w) y = -1")
plt.ylim(0.0,5.1)
plt.xlim([0,1])
plt.xlabel("$\phi$(z)")
plt.ylabel("J(w)")
plt.legend(loc = "upper left")
plt.tight_layout()
plt.show()
# In[ ]:
class LogisticRegressionGD(object):
def __init__(self,... | or x in z]
plt.plot(phi_z | identifier_body |
Section3.py | # coding: utf-8
# In[ ]:
from sklearn import datasets
import numpy as np
iris = datasets.load_iris()
X = iris.data[:,[2,3]]
y = iris.target
print("Class labels:",np.unique(y))
print(iris)
# In[ ]:
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_sp... |
# In[ ]:
svm = SVC(kernel = "rbf",random_state = 1 ,gamma = 0.10,C = 10.0)
svm.fit(X_xor,y_xor)
plot_decision_regions(X_xor,y_xor,classifier = svm)
plt.tight_layout()
plt.show()
# In[ ]:
svm = SVC(kernel = "rbf",random_state = 1,gamma = 0.2 ,C = 1.0)
svm.fit(X_train_std,y_train)
plot_decision_re... | plt.tight_layout()
plt.show()
| random_line_split |
Section3.py |
# coding: utf-8
# In[ ]:
from sklearn import datasets
import numpy as np
iris = datasets.load_iris()
X = iris.data[:,[2,3]]
y = iris.target
print("Class labels:",np.unique(y))
print(iris)
# In[ ]:
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_... | random_state = random_state
def fit(self,X,y):
rgen = np.random.RandomState(self.random_state)
self.w = rgen.normal(loc = 0.0,scale = 0.01,size =1+ X.shape[1])
self.gosagun = []
for i in range(self.n_iter):
net_input = self.net_input(X)
output... | _iter
self. | identifier_name |
pipeline_cutouts.py | # Python 3.6. Written by Alex Clarke
# Breakup a large fits image into smaller ones, with overlap, and save to disk.
# Sourecfinding is run on each cutout, and catalogues are sifted to remove duplicates from the overlap.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import multiprocessing... | # get cutout file names, must be in same order so they are matched correctly
images_560 = sorted(glob.glob('560*_cutout.fits'))
images_1400 = sorted(glob.glob('1400*_cutout.fits'))
# loop over image cutouts to make cube for each of them
for file560, file1400, i in zip(images_560, images_1400, range(le... | nt(' Cutting out image {0} of {1}'.format(i+1, split_into**2))
cutout = Cutout2D(hdu.data[0,0,:,:], position=tuple(position_coords_inpixels[i], size=tuple(size_inpixels[i]), mode='trim', wcs=wcs.celestial, copy=True)
cutout.plot_on_original(color=next(colourlist))
# Update the FITS header with the cutout WCS by h... | conditional_block |
pipeline_cutouts.py | # Python 3.6. Written by Alex Clarke
# Breakup a large fits image into smaller ones, with overlap, and save to disk.
# Sourecfinding is run on each cutout, and catalogues are sifted to remove duplicates from the overlap.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import multiprocessing... | j, name ):
with open(name + '.pkl', 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def load_obj(name ):
with open(name + '.pkl', 'rb') as f:
return pickle.load(f)
# ------ ------ ------ ------ ------ ------ ------ ------ ------ ------
def update_header_from_cutout2D(hdu, cut... | e_obj(ob | identifier_name |
pipeline_cutouts.py | # Python 3.6. Written by Alex Clarke
# Breakup a large fits image into smaller ones, with overlap, and save to disk.
# Sourecfinding is run on each cutout, and catalogues are sifted to remove duplicates from the overlap.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import multiprocessing... |
def do_sourcefinding(imagename, si=True):
# get beam info manually. SKA image seems to cause PyBDSF issues finding this info.
f = fits.open(imagename)
beam_maj = f[0].header['BMAJ']
beam_min = f[0].header['BMIN']
#beam_p... | = fits.open(input_image)[0]
wcs = WCS(hdu.header)
# currently hard coded to only accept square images
im_width = hdu.header['NAXIS1'] # get image width
print(' Input fits image dimensions: {0}'.format(im_width))
print(' Cutting into {0} images of dimensions {1}'.format(split_into**2, im_width/split... | identifier_body |
pipeline_cutouts.py | # Python 3.6. Written by Alex Clarke
# Breakup a large fits image into smaller ones, with overlap, and save to disk.
# Sourecfinding is run on each cutout, and catalogues are sifted to remove duplicates from the overlap.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import multiprocessing... |
def do_image_chopping(input_image, split_into):
hdu = fits.open(input_image)[0]
wcs = WCS(hdu.header)
# currently hard coded to only accept square images
im_width = hdu.header['NAXIS1'] # get image width
print(' Input fits image dimensions: {0}'.format(im_width))
print(' Cutting into {0} imag... |
# ------ ------ ------ ------ ------ ------ ------ ------ ------ ------ | random_line_split |
web.go | package rreader
import (
"fmt"
//"github.com/stretchrcom/goweb/goweb"
"encoding/json"
"github.com/ziutek/mymysql/mysql"
"net/http"
"strconv"
"strings"
"time"
)
type HomeView struct {
Feeds []FeedViewItem
}
type FeedViewItem struct {
Id int
Title string
Link string
Description strin... |
func serveUpdateItemLabels(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(400)
fmt.Fprint(w, "Not a post request.")
return
}
conn := GetConnection().Clone()
if err := conn.Connect(); err != nil {
respondError( w, err.Error() )
return
}
defer conn.Close()
entryId,... | {
id, err := strconv.ParseInt(r.FormValue("id"), 10, 64)
userId := 1
if err != nil {
respondError( w, err.Error() )
return
}
conn := GetConnection().Clone()
if err := conn.Connect(); err != nil {
respondError( w, err.Error() )
return
}
defer conn.Close()
rows, _, err := conn.Query("SELECT `conten... | identifier_body |
web.go | package rreader
import (
"fmt"
//"github.com/stretchrcom/goweb/goweb"
"encoding/json"
"github.com/ziutek/mymysql/mysql"
"net/http"
"strconv"
"strings"
"time"
)
type HomeView struct {
Feeds []FeedViewItem
}
type FeedViewItem struct {
Id int
Title string
Link string
Description strin... |
/*
_, _, err = GetConnection().QueryFirst("UPDATE user_feed SET unread_items=GREATEST(unread_items-1,0) WHERE user_id=%d AND feed_id=%d", userId, feedId)
if err != nil {
panic(err)
}
*/
//TODO: Extremelly inneficient; Make better method
_, _, err = conn.QueryFirst("CALL update_unread()")
if err != nil {
... | {
respondError( w, err.Error() )
return
} | conditional_block |
web.go | package rreader
import (
"fmt"
//"github.com/stretchrcom/goweb/goweb"
"encoding/json"
"github.com/ziutek/mymysql/mysql"
"net/http"
"strconv"
"strings"
"time"
)
type HomeView struct {
Feeds []FeedViewItem
}
type FeedViewItem struct {
Id int
Title string
Link string
Description strin... | (w http.ResponseWriter, r *http.Request) {
var userId uint32 = 1
searchQuery := fmt.Sprintf("userid=%d", userId)
start, err := strconv.ParseInt(r.FormValue("start"), 10, 64)
if err != nil {
start = 0
}
extraSearch, err := getFeedsQueryFromForm(r)
if err != nil {
respondError( w, err.Error() )
return
... | serveFeedItems | identifier_name |
web.go | package rreader
import (
"fmt"
//"github.com/stretchrcom/goweb/goweb"
"encoding/json"
"github.com/ziutek/mymysql/mysql"
"net/http"
"strconv"
"strings"
"time"
)
type HomeView struct {
Feeds []FeedViewItem
}
type FeedViewItem struct {
Id int
Title string
Link string
Description strin... | respondError( w, err.Error() )
return
}
fmt.Fprint(w, string(b))
}
func serveUpdateItemLabels(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(400)
fmt.Fprint(w, "Not a post request.")
return
}
conn := GetConnection().Clone()
if err := conn.Connect(); err != nil {
r... | //TODO: Extremelly inneficient; Make better method
_, _, err = conn.QueryFirst("CALL update_unread()")
if err != nil { | random_line_split |
sandbox.ts | import invariant from 'tiny-invariant';
import { datasetParser, isElement, evaluate, createSequence } from 'yuzu-utils';
import { IComponentConstructable } from 'yuzu/types';
import { Component } from 'yuzu';
import { createContext, IContext } from './context';
export type entrySelectorFn = (sbx: Sandbox<any>) => bool... |
return this.destroy();
}
/**
* ```js
* destroy()
* ```
*
* Enhances `Component.destroy()`.
* Stops every running component, clears sandbox events and destroys the instance.
*
* @deprecated
* @fires Sandbox#beforeStop
* @fires Sandbox#stop
* @returns {Promise<void>}
* @exam... | {
this.$warn(
`Sandbox.stop is deprecated. Use the "destroy" method instead`,
);
} | conditional_block |
sandbox.ts | import invariant from 'tiny-invariant';
import { datasetParser, isElement, evaluate, createSequence } from 'yuzu-utils';
import { IComponentConstructable } from 'yuzu/types';
import { Component } from 'yuzu';
import { createContext, IContext } from './context';
export type entrySelectorFn = (sbx: Sandbox<any>) => bool... | this.off('beforeStop');
this.off('stop');
}
} | this.off('error'); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.