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
thread.go
package runtime import ( "errors" "sync" "unsafe" ) // ThreadStatus is the type of a thread status type ThreadStatus uint // Available statuses for threads. const ( ThreadOK ThreadStatus = 0 // Running thread ThreadSuspended ThreadStatus = 1 // Thread has yielded and is waiting to be resumed ThreadDead ...
return } // This is to be able to close a suspended coroutine without completing it, but // still allow cleaning up the to-be-closed variables. If this is put on the // resume channel of a running thread, yield will cause a panic in the goroutine // and that will be caught in the defer() clause below. type threadClo...
} next.Push(t.Runtime, ErrorValue(err)) } c = next }
random_line_split
thread.go
package runtime import ( "errors" "sync" "unsafe" ) // ThreadStatus is the type of a thread status type ThreadStatus uint // Available statuses for threads. const ( ThreadOK ThreadStatus = 0 // Running thread ThreadSuspended ThreadStatus = 1 // Thread has yielded and is waiting to be resumed ThreadDead ...
() Cont { return c.Next() } func (c *messageHandlerCont) Push(r *Runtime, v Value) { if !c.done { c.done = true c.err = v } } func (c *messageHandlerCont) PushEtc(r *Runtime, etc []Value) { if c.done || len(etc) == 0 { return } c.Push(r, etc[0]) } func (c *messageHandlerCont) RunInThread(t *Thread) (Cont...
Parent
identifier_name
campaign_loader.rs
use std::path::{Path, PathBuf}; use std::ffi::OsStr; //For image loading and hooking into the Task system use coffee::{ load::Task, graphics::Image, }; use coffee::graphics::Gpu; //For config file loading and parsing use config::*; //To locate all config files extern crate walkdir; use walkdir::WalkDir; u...
else { error!("[Asset Loading] Failed to load asset relating to config file {}. {}", config_path.to_str().unwrap(), "Please review previous warnings." ); } } } //make sure file is one of the right formats for configuration files fn is_config_...
{ info!("[Asset Loading] Loaded asset relating to config file {}", config_path.to_str().unwrap()); }
conditional_block
campaign_loader.rs
use std::path::{Path, PathBuf}; use std::ffi::OsStr; //For image loading and hooking into the Task system use coffee::{ load::Task, graphics::Image, }; use coffee::graphics::Gpu; //For config file loading and parsing use config::*; //To locate all config files extern crate walkdir; use walkdir::WalkDir; u...
// assume image path is given as relative to config path hence taking the parent as a starting point. let audio_path = match config_path.parent() { Some(dir_path) => dir_path.join(file.ok().expect("File value is missing while loading.")), //getting parent from path failed somehow. ...
); return false; } };
random_line_split
campaign_loader.rs
use std::path::{Path, PathBuf}; use std::ffi::OsStr; //For image loading and hooking into the Task system use coffee::{ load::Task, graphics::Image, }; use coffee::graphics::Gpu; //For config file loading and parsing use config::*; //To locate all config files extern crate walkdir; use walkdir::WalkDir; u...
//creates a task for loading a config file and it's resources fn load_config_task(file_path: &PathBuf) -> Task<Config> { //needed so closure below can capture let path = file_path.clone(); Task::new(move || { //coerce into string value or return error let str_path = ...
{ coffee::Error::IO( std::io::Error::new( std::io::ErrorKind::Other, msg ) ) }
identifier_body
campaign_loader.rs
use std::path::{Path, PathBuf}; use std::ffi::OsStr; //For image loading and hooking into the Task system use coffee::{ load::Task, graphics::Image, }; use coffee::graphics::Gpu; //For config file loading and parsing use config::*; //To locate all config files extern crate walkdir; use walkdir::WalkDir; u...
(path: &str, gpu: &mut Gpu, asset_db: &mut AssetDatabase) { //load all config files under the campain folder let mut campaign_config_paths = find_config_files(path); //for each config file, load it then load the associated asset while let Some(config_path) = campaign_config_paths.pop() { ...
load_campaign_data
identifier_name
encryption_properties.go
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
props := &FileEncryptionProperties{ footerKey: footerKey, footerKeyMetadata: cfg.keyMetadata, encryptedFooter: cfg.encryptFooter, aadPrefix: cfg.aadprefix, storeAadPrefixInFile: cfg.storeAadPrefixInFile, encryptedCols: cfg.encryptedCols, utilized: false,...
{ o(&cfg) }
conditional_block
encryption_properties.go
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
} ret.Algo = AesCtr ret.Aad.AadFileUnique = enc.AES_GCM_CTR_V1.AadFileUnique ret.Aad.AadPrefix = enc.AES_GCM_CTR_V1.AadPrefix ret.Aad.SupplyAadPrefix = *enc.AES_GCM_CTR_V1.SupplyAadPrefix return } // FileEncryptionProperties describe how to encrypt a parquet file when writing data. type FileEncryptionProperties ...
ret.Aad.SupplyAadPrefix = *enc.AES_GCM_V1.SupplyAadPrefix return
random_line_split
encryption_properties.go
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
(keyMeta string) EncryptOption { return func(cfg *configEncrypt) { if keyMeta != "" { cfg.keyMetadata = keyMeta } } } // WithAadPrefix sets the AAD prefix to use for encryption and by default will store it in the file func WithAadPrefix(aadPrefix string) EncryptOption { return func(cfg *configEncrypt) { if...
WithFooterKeyMetadata
identifier_name
encryption_properties.go
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
type colEncryptConfig struct { key string keyMetadata string encrypted bool } // ColumnEncryptOption how to specify options to the the NewColumnEncryptionProperties function. type ColumnEncryptOption func(*colEncryptConfig) // WithKey sets a column specific key. // If key is not set on an encrypted col...
{ copy := ce.key return NewColumnEncryptionProperties(ce.columnPath, WithKey(copy), WithKeyMetadata(ce.keyMetadata)) }
identifier_body
bot.js
const Discord = require('discord.js'); const client = new Discord.Client(); const ayarlar = require('./ayarlar.json'); const chalk = require('chalk'); const fs = require('fs'); const moment = require('moment'); const db = require('quick.db') require('./util/eventLoader')(client); const express = require('express'); co...
const request = require('node-superfetch'); const db = require('quick.db'); const ms = require('parse-ms') let timeout = 600000 let dakdest = await db.fetch(`goldzzz_${msg.author.id}`); let i = db.fetch(`gold_${msg.author.id}`) if (i == 'gold') { if (dakdest !== null && timeout - (Date.now() - dakdest) > ...
client.on("message", async msg => {
random_line_split
SI507_Final_Project.py
from bs4 import BeautifulSoup import requests import json import secrets # file that contains your API key import pdb import sqlite3 from flask import Flask CACHE_FILE_NAME = 'cache.json' CACHE_DICT = {} baseurlSoup = 'https://www.internationalstudent.com/school-search/usa' baseurlAPI = 'http://www.mapques...
def printDictKeys(dictionary): i = 1 for key in dictionary.keys(): print('[{}] {}'.format(i, key)) i += 1 pass if __name__=="__main__": # upper lower case createDB() exitFlag = False while not(exitFlag): print("======================================...
i = 1 restaurantInfo = "" for key in restaurantNameInfo.keys(): if i > 10: break name = key address = restaurantNameInfo[key]['address'] phone = restaurantNameInfo[key]['phone'] restaurantInfo = restaurantInfo + "[{}] {} : {}, {} \n".format(i, na...
identifier_body
SI507_Final_Project.py
from bs4 import BeautifulSoup import requests import json import secrets # file that contains your API key import pdb import sqlite3 from flask import Flask CACHE_FILE_NAME = 'cache.json' CACHE_DICT = {} baseurlSoup = 'https://www.internationalstudent.com/school-search/usa' baseurlAPI = 'http://www.mapques...
elif uniName == 'exit': print("Bye~") exitFlag = True break else: print("Please type a correct university name !") if exitFlag: break # extract university information uniIns...
break
conditional_block
SI507_Final_Project.py
from bs4 import BeautifulSoup import requests import json import secrets # file that contains your API key import pdb import sqlite3 from flask import Flask CACHE_FILE_NAME = 'cache.json' CACHE_DICT = {} baseurlSoup = 'https://www.internationalstudent.com/school-search/usa' baseurlAPI = 'http://www.mapques...
(searchResults): '''Extract restaurant info from dictionary that was a return of the API request Parameters ---------- searchResults: Dict Return of the API request Returns ------- restaurantNameInfo : Dict 'Nmae of the restaurant' : {'phone' : value, 'ad...
extractRestaurantInfoOnly
identifier_name
SI507_Final_Project.py
from bs4 import BeautifulSoup import requests import json import secrets # file that contains your API key import pdb import sqlite3 from flask import Flask CACHE_FILE_NAME = 'cache.json' CACHE_DICT = {} baseurlSoup = 'https://www.internationalstudent.com/school-search/usa' baseurlAPI = 'http://www.mapques...
pass try: Uni.male_tot = soup.find_all('strong',{'class':'f-12'})[1].text except: pass try: Uni.male_intl = soup.find_all('strong',{'class':'f-12'})[4].text except: pass try: Uni.female_tot = soup.find_all('strong',{'class':'f-12'})[2].text ...
try: Uni.state = soup.find_all('li',{'class':'breadcrumb-item'})[2].a.text except:
random_line_split
main.go
package main import ( "context" "crypto/rand" "encoding/base64" "encoding/json" "fmt" "io/fs" "io/ioutil" "math/big" "os" "path/filepath" "time" "github.com/joho/godotenv" whisper "github.com/rotationalio/whisper/pkg" v1 "github.com/rotationalio/whisper/pkg/api/v1" "github.com/rotationalio/whisper/pkg/...
Aliases: []string{"G", "gs"}, Usage: "generate a random secret of the specified length", }, &cli.StringFlag{ Name: "in", Aliases: []string{"i", "u", "upload"}, Usage: "upload a file as the secret contents", }, &cli.StringFlag{ Name: "password", Aliases: []str...
}, &cli.IntFlag{ Name: "generate-secret",
random_line_split
main.go
package main import ( "context" "crypto/rand" "encoding/base64" "encoding/json" "fmt" "io/fs" "io/ioutil" "math/big" "os" "path/filepath" "time" "github.com/joho/godotenv" whisper "github.com/rotationalio/whisper/pkg" v1 "github.com/rotationalio/whisper/pkg/api/v1" "github.com/rotationalio/whisper/pkg/...
// Print the password so that it can be used to retrieve the secret later fmt.Printf("Password for retrieval: %s\n", req.Password) } ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() var rep *v1.CreateSecretReply if rep, err = client.CreateSecret(ctx, req); err != nil {...
{ return cli.Exit(err, 1) }
conditional_block
main.go
package main import ( "context" "crypto/rand" "encoding/base64" "encoding/json" "fmt" "io/fs" "io/ioutil" "math/big" "os" "path/filepath" "time" "github.com/joho/godotenv" whisper "github.com/rotationalio/whisper/pkg" v1 "github.com/rotationalio/whisper/pkg/api/v1" "github.com/rotationalio/whisper/pkg/...
func printJSON(v interface{}) (err error) { var data []byte if data, err = json.MarshalIndent(v, "", " "); err != nil { return cli.Exit("could not marshal json response", 2) } fmt.Println(string(data)) return nil }
{ var fi fs.FileInfo if fi, err = os.Stat(path); err != nil { return false, err } return fi.IsDir(), nil }
identifier_body
main.go
package main import ( "context" "crypto/rand" "encoding/base64" "encoding/json" "fmt" "io/fs" "io/ioutil" "math/big" "os" "path/filepath" "time" "github.com/joho/godotenv" whisper "github.com/rotationalio/whisper/pkg" v1 "github.com/rotationalio/whisper/pkg/api/v1" "github.com/rotationalio/whisper/pkg/...
(c *cli.Context) (err error) { // Create the request req := &v1.CreateSecretRequest{ Password: c.String("password"), Accesses: c.Int("accesses"), Lifetime: v1.Duration(c.Duration("lifetime")), } // Add the secret to the request via one of the command line options switch { case c.String("secret") != "": i...
create
identifier_name
sound.js
// # audio/sound.js (function(){ // ## Luv.Audio.Sound // This class wraps an `<audio>` tag. You will likely not instantiate this // class directly; instead you will create a `Luv` instance, which has an // `audio` module. And that module will have a `Sound` method, which will // internally call `Luv.Audio.Sound` wit...
}; // Internal function used by Luv.Sound.getReadyInstance var createInstance = function(sound) { return Luv.Audio.SoundInstance( sound.el.cloneNode(true), function() { clearTimeout(this.expirationTimeOut); }, function() { var instance = this; instance.expirationTimeOut = setTimeout( ...
{ instance = instances[i]; if(instance.isReady()) { return instance; } }
conditional_block
sound.js
// # audio/sound.js (function(){ // ## Luv.Audio.Sound // This class wraps an `<audio>` tag. You will likely not instantiate this // class directly; instead you will create a `Luv` instance, which has an // `audio` module. And that module will have a `Sound` method, which will // internally call `Luv.Audio.Sound` wit...
return instance; } } }; // Internal function used by Luv.Sound.getReadyInstance var createInstance = function(sound) { return Luv.Audio.SoundInstance( sound.el.cloneNode(true), function() { clearTimeout(this.expirationTimeOut); }, function() { var instance = this; instance.expirati...
var getExistingReadyInstance = function(instances) { var instance; for(var i=0; i< instances.length; i++) { instance = instances[i]; if(instance.isReady()) {
random_line_split
LonghurstProvince.py
""" Functions for working with Longhurst provinces """ import numpy as np import pandas as pd import xarray as xr # import AC_tools (https://github.com/tsherwen/AC_tools.git) import AC_tools as AC # s2s specific imports import sparse2spatial.utils as utils def
(target='Iodide'): """ Driver to add Longhurst Provinces fields to spatial NetCDF files """ Filenames = [ 's2s_predicted_{}_0.125x0.125_No_Skagerrak', 's2s_feature_variables_0.125x0.125', 's2s_predicted_{}_0.125x0.125', ] folder = '/work/home/ts551/data/iodide/' for n...
add_longhurst_raster_array_and_LWI_core_NetCDFs
identifier_name
LonghurstProvince.py
""" Functions for working with Longhurst provinces """ import numpy as np import pandas as pd import xarray as xr # import AC_tools (https://github.com/tsherwen/AC_tools.git) import AC_tools as AC # s2s specific imports import sparse2spatial.utils as utils def add_longhurst_raster_array_and_LWI_core_NetCDFs(target=...
# What data sets contribute to this PrtStr = 'Datasets contributing to these numbers: {}' print(PrtStr.format(', '.join(set(tmp['Data_Key'])))) def ParseLonghurstProvinceFile(): """ Parse the Longhurst *.xml file into a dictionary object Notes ----- - This code is copied from elsewh...
MITp_ = tmp_.loc[tmp_.index == idx, :]['PName (MIT)'].values[0] print(PrtStr.format(MITp_, Get_LonghurstProvinceName4Num(MITp_), prov, Get_LonghurstProvinceName4Num(prov)))
conditional_block
LonghurstProvince.py
""" Functions for working with Longhurst provinces """ import numpy as np import pandas as pd import xarray as xr # import AC_tools (https://github.com/tsherwen/AC_tools.git) import AC_tools as AC # s2s specific imports import sparse2spatial.utils as utils def add_longhurst_raster_array_and_LWI_core_NetCDFs(target=...
def Get_LonghurstProvinceName4Num(input): """ Get full Longhurst Province for given number """ LonghurstProvinceDict = { 'ALSK': 'AlaskaDownwellingCoastalProvince', 'ANTA': 'AntarcticProvince', 'APLR': 'AustralPolarProvince', 'ARAB': 'NWArabianUpwellingProvince', ...
""" Get the longhurst province Parameters ------- input (str): input string to use as key to return dictionary value invert (float): reverse the key/pair of the dictionary rtn_dict (bool): return the entire dictionary. Returns ------- (str) Notes ----- - these **are**...
identifier_body
LonghurstProvince.py
""" Functions for working with Longhurst provinces """ import numpy as np import pandas as pd import xarray as xr # import AC_tools (https://github.com/tsherwen/AC_tools.git) import AC_tools as AC # s2s specific imports import sparse2spatial.utils as utils def add_longhurst_raster_array_and_LWI_core_NetCDFs(target=...
rtn_dict=False): """ Get the Longhurst province Parameters ------- input (str): input string to use as key to return dictionary value invert (float): reverse the key/pair of the dictionary rtn_dict (bool): return the entire dictionary. ...
random_line_split
helpers.js
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value)
return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resol...
{ return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
identifier_body
helpers.js
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { t...
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) ...
{ _.label = t[1]; t = op; break; }
conditional_block
helpers.js
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { t...
return __awaiter(this, void 0, void 0, function () { var DotCoverPath, outputLocation, downloadFileName, url, zipLocation; var _this = this; return __generator(this, function (_a) { DotCoverPath = "CommandLineTools-2020-1-3"; outputLocation = _...
random_line_split
helpers.js
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { t...
() { } /// Check value contains content befor returning string value ExtensionHelpers.prototype.NamePairCheck = function (name, value, addQuotes) { if (value != undefined && value != '') { var argument = ' /' + name; if (addQuotes == true) { argument += '="' +...
ExtensionHelpers
identifier_name
utils.py
# -*- coding: utf-8 -*- import inspect import re from collections import OrderedDict import six from django import VERSION as DJANGO_VERSION from django.apps import apps from django.contrib.contenttypes.fields import GenericForeignKey, GenericRel from django.core.exceptions import ImproperlyConfigured, ValidationError...
klass__name = klass.__class__.__name__ raise ValueError( "Object is of type '{}', but must be a Django Model, " "Manager, or QuerySet".format(klass__name) ) return manager.all() def _get_custom_resolver(info): """ Get custom user defined resolver for que...
else:
random_line_split
utils.py
# -*- coding: utf-8 -*- import inspect import re from collections import OrderedDict import six from django import VERSION as DJANGO_VERSION from django.apps import apps from django.contrib.contenttypes.fields import GenericForeignKey, GenericRel from django.core.exceptions import ImproperlyConfigured, ValidationError...
return manager.all() def _get_custom_resolver(info): """ Get custom user defined resolver for query. This resolver must return QuerySet instance to be successfully resolved. """ parent = info.parent_type custom_resolver_name = f"resolve_{to_snake_case(info.field_name)}" if hasattr(pa...
if isinstance(klass, type): klass__name = klass.__name__ else: klass__name = klass.__class__.__name__ raise ValueError( "Object is of type '{}', but must be a Django Model, " "Manager, or QuerySet".format(klass__name) )
conditional_block
utils.py
# -*- coding: utf-8 -*- import inspect import re from collections import OrderedDict import six from django import VERSION as DJANGO_VERSION from django.apps import apps from django.contrib.contenttypes.fields import GenericForeignKey, GenericRel from django.core.exceptions import ImproperlyConfigured, ValidationError...
def create_obj(django_model, new_obj_key=None, *args, **kwargs): """ Function used by my on traditional Mutations to create objs :param django_model: A valid Django Model or a string with format: <app_label>.<model_name> :param new_obj_key: Key into kwargs that contains de data: new_person :p...
""" Function used to get a object :param app_label: A valid Django Model or a string with format: <app_label>.<model_name> :param model_name: Key into kwargs that contains de data: new_person :param object_id: :return: instance """ try: model = apps.get_model("{}.{}".format(app_label...
identifier_body
utils.py
# -*- coding: utf-8 -*- import inspect import re from collections import OrderedDict import six from django import VERSION as DJANGO_VERSION from django.apps import apps from django.contrib.contenttypes.fields import GenericForeignKey, GenericRel from django.core.exceptions import ImproperlyConfigured, ValidationError...
(d): """ Remove all empty fields in a nested dict """ if not isinstance(d, (dict, list)): return d if isinstance(d, list): return [v for v in (clean_dict(v) for v in d) if v] return OrderedDict([(k, v) for k, v in ((k, clean_dict(v)) for k, v in list(d.items())) if v]) def get...
clean_dict
identifier_name
mod.rs
use std::borrow::Cow; use std::pin::Pin; use std::sync::{ atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, Arc, }; use std::task::{Context, Poll}; use std::time::{Duration, Instant}; use backoff::backoff::Backoff; use futures::prelude::*; use futures::task::AtomicWaker; use log::{debug, error, warn}; us...
fn str_sanitize(input: String) -> String { match memchr(0, input.as_bytes()) { Some(_) => input.replace(char::from(0), ""), None => input, } }
false => Poll::Pending, } } }
random_line_split
mod.rs
use std::borrow::Cow; use std::pin::Pin; use std::sync::{ atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, Arc, }; use std::task::{Context, Poll}; use std::time::{Duration, Instant}; use backoff::backoff::Backoff; use futures::prelude::*; use futures::task::AtomicWaker; use log::{debug, error, warn}; us...
(self: Pin<&mut Self>, item: Vec<imageboard::Post>) -> Result<(), Self::Error> { if item.len() > 0 { self.inner .inflight_posts .fetch_add(item.len(), Ordering::AcqRel); self.inner.process_tx.send(Some(item)).unwrap(); } Ok(()) } f...
start_send
identifier_name
mod.rs
use std::borrow::Cow; use std::pin::Pin; use std::sync::{ atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, Arc, }; use std::task::{Context, Poll}; use std::time::{Duration, Instant}; use backoff::backoff::Backoff; use futures::prelude::*; use futures::task::AtomicWaker; use log::{debug, error, warn}; us...
self.inner.flush_waker.register(cx.waker()); match self.inner.is_empty() { true => Poll::Ready(Ok(())), false => Poll::Pending, } } fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { let _ = self.inner.process_tx.sen...
{ return Poll::Ready(Err(Error::ArchiveError)); }
conditional_block
mod.rs
use std::borrow::Cow; use std::pin::Pin; use std::sync::{ atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, Arc, }; use std::task::{Context, Poll}; use std::time::{Duration, Instant}; use backoff::backoff::Backoff; use futures::prelude::*; use futures::task::AtomicWaker; use log::{debug, error, warn}; us...
fn is_empty(&self) -> bool { let posts = self.inflight_posts.load(Ordering::Acquire); posts == 0 } fn has_failed(&self) -> bool { return self.fail_on_save_error && self.failed.load(Ordering::Relaxed); } } impl Sink<Vec<imageboard::Post>> for Search { type Error = Error; ...
{ let posts = self.inflight_posts.load(Ordering::Acquire); posts < self.max_inflight_posts }
identifier_body
file_system_persistence.go
// Copyright 2019 the orbs-network-go authors // This file is part of the orbs-network-go library in the Orbs project. // // This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. // The above notice should be included in all copies or substantial portion...
newTip, err := newFileBlockWriter(file, codec, bhIndex.fetchNextOffset()) if err != nil { closeSilently(file, logger) return nil, err } adapter := &BlockPersistence{ bhIndex: bhIndex, config: conf, blockTracker: synchronization.NewBlockTracker(logger, uint64(bhIndex.getLastBlockHeight()), 5)...
{ closeSilently(file, logger) return nil, err }
conditional_block
file_system_persistence.go
// Copyright 2019 the orbs-network-go authors // This file is part of the orbs-network-go library in the Orbs project. // // This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. // The above notice should be included in all copies or substantial portion...
(file *os.File, conf config.FilesystemBlockPersistenceConfig, logger log.Logger) error { header := newBlocksFileHeader(uint32(conf.NetworkType()), uint32(conf.VirtualChainId())) logger.Info("creating new blocks file", log.String("filename", file.Name())) err := header.write(file) if err != nil { return errors.Wra...
writeNewFileHeader
identifier_name
file_system_persistence.go
// Copyright 2019 the orbs-network-go authors // This file is part of the orbs-network-go library in the Orbs project. // // This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. // The above notice should be included in all copies or substantial portion...
func blocksFileName(config config.FilesystemBlockPersistenceConfig) string { return filepath.Join(config.BlockStorageFileSystemDataDir(), blocksFilename) } func closeSilently(file *os.File, logger log.Logger) { err := file.Close() if err != nil { logger.Error("failed to close file", log.Error(err), log.String("...
{ return blocksFileName(f.config) }
identifier_body
file_system_persistence.go
// Copyright 2019 the orbs-network-go authors // This file is part of the orbs-network-go library in the Orbs project. // // This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. // The above notice should be included in all copies or substantial portion...
return 0, errors.Wrapf(err, "error reading blocks file header") } if header.NetworkType != uint32(conf.NetworkType()) { return 0, fmt.Errorf("blocks file network type mismatch. found netowrk type %d expected %d", header.NetworkType, conf.NetworkType()) } if header.ChainId != uint32(conf.VirtualChainId()) { ...
header := newBlocksFileHeader(0, 0) err = header.read(file) if err != nil {
random_line_split
app.js
let element; element = document.all; element = document.head; element = document.body; element = document.domain; element = document.URL; element = document.characterSet; element = document.contentType; //links element = document.links; element = document.links[2]; element = document.links[2].id; element = document.li...
} console.log(courseList); //local storage //add to local storage localStorage .setItem('name', "Kasia"); // add to session storage //sessionStorage.setItem('name', 'Kasia'); //remove from the storage localStorage.removeItem('name'); //read the value //const name = localStorage.getItem('name'); //console.log(name);...
console.log("courses added"); }
random_line_split
app.js
let element; element = document.all; element = document.head; element = document.body; element = document.domain; element = document.URL; element = document.characterSet; element = document.contentType; //links element = document.links; element = document.links[2]; element = document.links[2].id; element = document.li...
names.push("JavaScript"); localStorage.setItem('names',JSON.stringify(names));
{ names = JSON.parse(localStorageContent) }
conditional_block
app.js
let element; element = document.all; element = document.head; element = document.body; element = document.domain; element = document.URL; element = document.characterSet; element = document.contentType; //links element = document.links; element = document.links[2]; element = document.links[2].id; element = document.li...
console.log(courseList); //local storage //add to local storage localStorage .setItem('name', "Kasia"); // add to session storage //sessionStorage.setItem('name', 'Kasia'); //remove from the storage localStorage.removeItem('name'); //read the value //const name = localStorage.getItem('name'); //console.log(name); ...
{ if (event.target.classList.contains('add-to-cart')){ console.log("courses added"); } }
identifier_body
app.js
let element; element = document.all; element = document.head; element = document.body; element = document.domain; element = document.URL; element = document.characterSet; element = document.contentType; //links element = document.links; element = document.links[2]; element = document.links[2].id; element = document.li...
(event){ if (event.target.classList.contains('add-to-cart')){ console.log("courses added"); } } console.log(courseList); //local storage //add to local storage localStorage .setItem('name', "Kasia"); // add to session storage //sessionStorage.setItem('name', 'Kasia'); //remove from the storage localS...
addToCart
identifier_name
metadata.rs
// Copyright 2018 Google Inc. // // 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...
} } let metadata = self .metadata_fetcher .fetch_metadata(utf8_cargo_dir, /*include_deps=*/ true)?; // In this function because it's metadata, even though it's not returned by `cargo-metadata` let platform_features = match self.settings.as_ref() { Some(settings) => get_per_pla...
{ checksums.insert( package_ident(package.name.as_ref(), &package.version.to_string()), checksum.to_string(), ); }
conditional_block
metadata.rs
// Copyright 2018 Google Inc. // // 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...
} impl MetadataFetcher for CargoMetadataFetcher { fn fetch_metadata(&self, working_dir: &Utf8Path, include_deps: bool) -> Result<Metadata> { let mut command = MetadataCommand::new(); if !include_deps { command.no_deps(); } command .cargo_path(&self.cargo_bin_path) .current_dir(wo...
{ CargoMetadataFetcher { cargo_bin_path: cargo_bin_path(), } }
identifier_body
metadata.rs
// Copyright 2018 Google Inc. // // 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...
.is_none()); // Ensure a Cargo.lock file was generated and matches the expected file assert_eq!( Lockfile::from_str(&fs::read_to_string(expected_lockfile).unwrap()).unwrap(), Lockfile::from_str(&fs::read_to_string(crate_dir.as_ref().join("Cargo.lock")).unwrap()) .unwrap() ); } }
random_line_split
metadata.rs
// Copyright 2018 Google Inc. // // 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...
{ cargo_bin_path: Utf8PathBuf, } impl LockfileGenerator for CargoLockfileGenerator { /// Generate lockfile information from a cargo workspace root fn generate_lockfile(&self, crate_root_dir: &Utf8Path) -> Result<Lockfile> { let lockfile_path = crate_root_dir.join("Cargo.lock"); // Generate lockfile ...
CargoLockfileGenerator
identifier_name
EventModal.js
import { Button, Row, Col, Form,Input, Modal,Upload,Icon, Table } from 'antd'; import React, {Component} from 'react'; import videojs from 'video.js'; import Flash from 'videojs-flash'; import 'video.js/dist/video-js.css'; import moment from 'moment'; import styles from './EventModal.less'; import { getLocalTimeF } fro...
(){ const {form} = this.props; this.props.dispatch({ type:'device/updateState', payload:{ eventModal:false } }) } handleCancel(){ this.props.dispatch({ type:'device/updateState', payload:{ ...
onOk
identifier_name
EventModal.js
import { Button, Row, Col, Form,Input, Modal,Upload,Icon, Table } from 'antd'; import React, {Component} from 'react'; import videojs from 'video.js'; import Flash from 'videojs-flash'; import 'video.js/dist/video-js.css'; import moment from 'moment'; import styles from './EventModal.less'; import { getLocalTimeF } fro...
} ] } else if(videoUrl[index].indexOf('m3u8')>(-1)) { videotype = [ { src: videoUrl[index], type: 'application/x-mpegURL' ...
type: 'rtmp/mp4'
random_line_split
EventModal.js
import { Button, Row, Col, Form,Input, Modal,Upload,Icon, Table } from 'antd'; import React, {Component} from 'react'; import videojs from 'video.js'; import Flash from 'videojs-flash'; import 'video.js/dist/video-js.css'; import moment from 'moment'; import styles from './EventModal.less'; import { getLocalTimeF } fro...
handleImgCancel = () => this.setState({ previewVisible: false }) handlePreview = (file) => { this.setState({ previewImage: file.url || file.thumbUrl, previewVisible: true, }); } render() { const { form: { getFieldDecorator...
{ this.props.dispatch({ type:'device/updateState', payload:{ eventModal:false } }) }
identifier_body
kieapp_types.go
package v1 import ( "context" appsv1 "github.com/openshift/api/apps/v1" buildv1 "github.com/openshift/api/build/v1" oimagev1 "github.com/openshift/api/image/v1" routev1 "github.com/openshift/api/route/v1" imagev1 "github.com/openshift/client-go/image/clientset/versioned/typed/image/v1" corev1 "k8s.io/api/core/...
() { SchemeBuilder.Register(&KieApp{}, &KieAppList{}) }
init
identifier_name
kieapp_types.go
package v1 import ( "context" appsv1 "github.com/openshift/api/apps/v1" buildv1 "github.com/openshift/api/build/v1" oimagev1 "github.com/openshift/api/image/v1" routev1 "github.com/openshift/api/route/v1" imagev1 "github.com/openshift/client-go/image/clientset/versioned/typed/image/v1" corev1 "k8s.io/api/core/...
{ SchemeBuilder.Register(&KieApp{}, &KieAppList{}) }
identifier_body
kieapp_types.go
package v1 import ( "context" appsv1 "github.com/openshift/api/apps/v1" buildv1 "github.com/openshift/api/build/v1" oimagev1 "github.com/openshift/api/image/v1" routev1 "github.com/openshift/api/route/v1" imagev1 "github.com/openshift/client-go/image/clientset/versioned/typed/image/v1" corev1 "k8s.io/api/core/...
DeploymentConfigs []appsv1.DeploymentConfig `json:"deploymentConfigs,omitempty"` BuildConfigs []buildv1.BuildConfig `json:"buildConfigs,omitempty"` ImageStreams []oimagev1.ImageStream `json:"imageStreams,omitempty"` Services []corev1.Service ...
PersistentVolumeClaims []corev1.PersistentVolumeClaim `json:"persistentVolumeClaims,omitempty"` ServiceAccounts []corev1.ServiceAccount `json:"serviceAccounts,omitempty"` Secrets []corev1.Secret `json:"secrets,omitempty"` Roles []rbacv1.Role ...
random_line_split
main.go
package main // big up Hakluke, thanks for making hakrawler. I used your multi-threading as a basis so I could learn and convert this from single to multi <3 import ( "bufio" "flag" "fmt" "io" "io/ioutil" "log" "net/http" "os" "regexp" "strconv" "strings" "sync" "time" ) // global vars for templates var...
/* var templateJinja2 = "Jinja2" // -> {{7*'7'}} would result in 7777777 in Jinja2 var templateMako = "Mako" // -> ${7*7} -> ${"z".join("ab")} is a payload that can identify Mako var templateSmarty = "Smarty" // -> ${7*7} -> a{*comment*}b is a payload that can identify Smarty var templateTwig = "Twig" ...
func attemptToIdentifyEngine(url string, vulnParamElement int, quietMode bool) []string { // this might be meh, but make a request to the same URL per template based on the payloads we have // for this, we don't care about the number of parameters - we just want to try identify the template engine
random_line_split
main.go
package main // big up Hakluke, thanks for making hakrawler. I used your multi-threading as a basis so I could learn and convert this from single to multi <3 import ( "bufio" "flag" "fmt" "io" "io/ioutil" "log" "net/http" "os" "regexp" "strconv" "strings" "sync" "time" ) // global vars for templates var...
() <-chan string { lines := make(chan string) go func() { defer close(lines) sc := bufio.NewScanner(os.Stdin) for sc.Scan() { url := strings.ToLower(sc.Text()) if url != "" { lines <- url } } }() return lines } // TODO: Should we randomise this? Do we care? probably not. // We should extend th...
readStdin
identifier_name
main.go
package main // big up Hakluke, thanks for making hakrawler. I used your multi-threading as a basis so I could learn and convert this from single to multi <3 import ( "bufio" "flag" "fmt" "io" "io/ioutil" "log" "net/http" "os" "regexp" "strconv" "strings" "sync" "time" ) // global vars for templates var...
parameterSplit := strings.Split(urlParamSplit[1], "&") if len(parameterSplit) == 0 { return "", nil, nil // Although we had a ? in the URL, no parameters were actually identified } generatedPayloadCount := 1 // start from 1 because we aren't CS students generatedPayloads := []string{} // coll...
{ return "", nil, nil // Although we had a ? in the URL, no parameters were actually identified as the amount of chars after the ? appeared to be 0 }
conditional_block
main.go
package main // big up Hakluke, thanks for making hakrawler. I used your multi-threading as a basis so I could learn and convert this from single to multi <3 import ( "bufio" "flag" "fmt" "io" "io/ioutil" "log" "net/http" "os" "regexp" "strconv" "strings" "sync" "time" ) // global vars for templates var...
func attemptToIdentifyEngine(url string, vulnParamElement int, quietMode bool) []string { // this might be meh, but make a request to the same URL per template based on the payloads we have // for this, we don't care about the number of parameters - we just want to try identify the template engine /* var templa...
{ r, _ := regexp.Compile(criteria) return r.MatchString(body) }
identifier_body
Generator.py
from itertools import combinations from random import randint import os import numpy as np from jinja2 import Environment, FileSystemLoader from Corridor import CorridorConstants from POMDPX import POMDPXConstants from RS import RockSamplingConstants from RS.RockSamplingConstants import DIRECTION_SYMBOLS """ Note, t...
else: res[src_tile_idx, src_tile_idx] = 1.0 - succ_prob res[src_tile_idx, dst_tile_idx] = succ_prob return res def calculate_euclidian_distance_in_grid(p1, p2): return np.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) def calculate_good_sense_matrices(w, h, rock_positions...
res[src_tile_idx, dst_tile_idx] = 1.0
conditional_block
Generator.py
from itertools import combinations from random import randint import os import numpy as np from jinja2 import Environment, FileSystemLoader from Corridor import CorridorConstants from POMDPX import POMDPXConstants from RS import RockSamplingConstants from RS.RockSamplingConstants import DIRECTION_SYMBOLS """ Note, t...
res = np.zeros(shape=(2, 2)) good, bad = RockSamplingConstants.good_idx, RockSamplingConstants.bad_idx res[bad][bad] = -bad_sample_penalty res[bad][good] = 0 # can't happen res[good][bad] = good_sample_reward res[good][good] = 0 # no effect return res def generate_random_tile(w, h): ...
random_line_split
Generator.py
from itertools import combinations from random import randint import os import numpy as np from jinja2 import Environment, FileSystemLoader from Corridor import CorridorConstants from POMDPX import POMDPXConstants from RS import RockSamplingConstants from RS.RockSamplingConstants import DIRECTION_SYMBOLS """ Note, t...
def get_rock_sample_reward_matrix(good_sample_reward, bad_sample_penalty): res = np.zeros(shape=(2, 2)) good, bad = RockSamplingConstants.good_idx, RockSamplingConstants.bad_idx res[bad][bad] = -bad_sample_penalty res[bad][good] = 0 # can't happen res[good][bad] = good_sample_reward res[goo...
res = {} good_matrices = calculate_good_sense_matrices(w, h, rock_positions, sense_decay_const) bad_matrices = calculate_bad_sense_matrices(w, h, rock_positions, sense_decay_const) for rock_idx in range(len(rock_positions)): rock_symbol = RockSamplingConstants.rock_symbol(rock_idx) res[rock_...
identifier_body
Generator.py
from itertools import combinations from random import randint import os import numpy as np from jinja2 import Environment, FileSystemLoader from Corridor import CorridorConstants from POMDPX import POMDPXConstants from RS import RockSamplingConstants from RS.RockSamplingConstants import DIRECTION_SYMBOLS """ Note, t...
(length, *args): res = [RockSamplingConstants.WILDCARD for _ in range(length)] for i in args: res[i] = PLACE_HOLDER_SYMBOL return ' '.join(res) def calculate_direction(src_tile, dst_tile): x1, y1 = src_tile[0], src_tile[1] x2, y2 = dst_tile[0], dst_tile[1] if y2 - y1 > 0: retur...
create_combination_template
identifier_name
main.rs
extern crate gl; extern crate glfw; extern crate time; extern crate point; use std::sync::mpsc::channel; use std::thread::spawn; use std::mem; use std::ptr; use std::ffi::CString; use std::fs::File; use std::io::Read; use std::fmt::{ Display, Formatter }; use std::fmt; use std::cmp::{Eq, PartialEq}; use gl::types::*;...
let new_tile_spec = TileSpecification { pixels: pixels, center: center, zoom: zoom }; let needs_new_tile = match current_tile { None => true, Some(ref tile) => { tile.specification != new_tile_spec }, }; if tile_queue_empty && needs_...
unsafe { gl::ClearColor(0.2, 0.1, 0.05, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT); } unsafe { set_viewport(program, zoom, &pixels, &center) }; match current_tile { Some(ref tile) => { draw_fractal(&tile.po...
conditional_block
main.rs
extern crate gl; extern crate glfw; extern crate time; extern crate point; use std::sync::mpsc::channel; use std::thread::spawn; use std::mem; use std::ptr; use std::ffi::CString; use std::fs::File; use std::io::Read; use std::fmt::{ Display, Formatter }; use std::fmt; use std::cmp::{Eq, PartialEq}; use gl::types::*;...
unsafe { set_viewport(program, zoom, &pixels, &center) }; match current_tile { Some(ref tile) => { draw_fractal(&tile.positions, &tile.colors, vertex_buffer, color_buffer, &mut window); } None => { /* no tile ready yet */ } ...
gl::Clear(gl::COLOR_BUFFER_BIT); }
random_line_split
main.rs
extern crate gl; extern crate glfw; extern crate time; extern crate point; use std::sync::mpsc::channel; use std::thread::spawn; use std::mem; use std::ptr; use std::ffi::CString; use std::fs::File; use std::io::Read; use std::fmt::{ Display, Formatter }; use std::fmt; use std::cmp::{Eq, PartialEq}; use gl::types::*;...
fn main() { let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(WindowHint::ContextVersion(3, 2)); glfw.window_hint(WindowHint::OpenGlForwardCompat(true)); glfw.window_hint(WindowHint::OpenGlProfile(OpenGlProfileHint::Core)); let x_initial_points = 500; let y_initial_po...
let points = colors.len() / 3; unsafe { load_vector_in_buffer(vertex_buffer, &positions); load_vector_in_buffer(color_buffer, &colors); gl::DrawArrays(gl::POINTS, 0, points as i32); window.swap_buffers(); } }
identifier_body
main.rs
extern crate gl; extern crate glfw; extern crate time; extern crate point; use std::sync::mpsc::channel; use std::thread::spawn; use std::mem; use std::ptr; use std::ffi::CString; use std::fs::File; use std::io::Read; use std::fmt::{ Display, Formatter }; use std::fmt; use std::cmp::{Eq, PartialEq}; use gl::types::*;...
buffer: u32, values: &Vec<GLfloat>) { gl::BindBuffer(gl::ARRAY_BUFFER, buffer); gl::BufferData(gl::ARRAY_BUFFER, (values.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, mem::transmute(&values[0]), gl::STATIC_DRAW); } unsafe fn bind_attribute_to_buffer(...
oad_vector_in_buffer(
identifier_name
model.rs
use std::collections::{BTreeMap, HashMap}; use task::*; use task_ref::TaskRef; use std::io; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Effect { AddTask(Task), ChangeTaskTags { uuid: Uuid, added: Tags, removed: Tags, }, ChangeTaskState(Uuid, TaskStat...
fn test_short_uuid_ref() { for s in vec!["abcdef", "123abc", "000000"] { assert_eq!(TaskRef::from_str(s), Ok(TaskRef::ShortUUID(s.into()))); } assert!( TaskRef::from_str("abcde").is_err(), "Short-UUID with len of 5" ); assert!( ...
#[test]
random_line_split
model.rs
use std::collections::{BTreeMap, HashMap}; use task::*; use task_ref::TaskRef; use std::io; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Effect { AddTask(Task), ChangeTaskTags { uuid: Uuid, added: Tags, removed: Tags, }, ChangeTaskState(Uuid, TaskStat...
pub fn apply_effect(&mut self, effect: &Effect) -> () { use Effect::*; match effect.clone() { AddTask(task) => { self.add_task(task); } ChangeTaskTags { uuid, added, removed, } => { ...
{ let mut model = Self::new(); for effect in effects { model.apply_effect(&effect) } model.is_dirty = false; model }
identifier_body
model.rs
use std::collections::{BTreeMap, HashMap}; use task::*; use task_ref::TaskRef; use std::io; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Effect { AddTask(Task), ChangeTaskTags { uuid: Uuid, added: Tags, removed: Tags, }, ChangeTaskState(Uuid, TaskStat...
ChangeTaskTags { uuid, added, removed, } => { self.change_task_tags(&uuid, added, removed); } ChangeTaskState(uuid, state) => { self.change_task_state(&uuid, state); } ...
{ self.add_task(task); }
conditional_block
model.rs
use std::collections::{BTreeMap, HashMap}; use task::*; use task_ref::TaskRef; use std::io; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Effect { AddTask(Task), ChangeTaskTags { uuid: Uuid, added: Tags, removed: Tags, }, ChangeTaskState(Uuid, TaskStat...
(&self) -> bool { self.is_dirty } } #[cfg(test)] mod tests { use super::*; use chrono; use std::str::FromStr; use uuid::Uuid; use {Priority, Task, TaskState}; #[test] fn test_add_delete_task() { let mut m = Model::new(); let t = Task::new("foo"); m.add_t...
is_dirty
identifier_name
lib.rs
#![warn(rust_2018_idioms)] #![cfg_attr(feature = "strict", deny(warnings))] use std::num::NonZeroUsize; use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::{ parse_macro_input, Error, Expr, ExprLit, ExprRange, FnArg, Index, ItemFn, Li...
(attr: TokenStream, item: TokenStream) -> TokenStream { let punctuated_args = parse_macro_input!(attr with Punctuated<LitStr, Token![,]>::parse_separated_nonempty); let input = parse_macro_input!(item as ItemFn); match create_hook(punctuated_args, input) { Ok(ts) => ts, Err(err) => ...
hook
identifier_name
lib.rs
#![warn(rust_2018_idioms)] #![cfg_attr(feature = "strict", deny(warnings))] use std::num::NonZeroUsize; use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::{ parse_macro_input, Error, Expr, ExprLit, ExprRange, FnArg, Index, ItemFn, Li...
fn create_impl_arguments_parameters(range: ExprRange) -> Result<TokenStream, Error> { let span = range.span(); let start = range .from .ok_or_else(|| Error::new(span, "Tuple length range must have a lower bound"))?; let start = parse_range_bound(*start)?; let end = range .to ...
{ let range = parse_macro_input!(input as ExprRange); match create_impl_arguments_parameters(range) { Ok(ts) => ts, Err(err) => err.to_compile_error().into(), } }
identifier_body
lib.rs
#![warn(rust_2018_idioms)] #![cfg_attr(feature = "strict", deny(warnings))] use std::num::NonZeroUsize; use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::{ parse_macro_input, Error, Expr, ExprLit, ExprRange, FnArg, Index, ItemFn, Li...
let name = sig.ident; let return_type = sig.output; let typecheck_return_type = match &return_type { ReturnType::Default => quote! { () }, ReturnType::Type(_, ty) => quote! { #ty }, }; let hook_name = format_ident!("{}_hook", name); let hook_args = sig.inputs; let mut this_...
random_line_split
train_arch9.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import datetime from functools import partial import json import traceback import imlib as im import numpy as np import pylib import tensorflow as tf import tflib as tl import data_noise_in as...
d_opt = tf.train.AdamOptimizer(lr, beta1=0.5) g_opt = tf.train.AdamOptimizer(lr, beta1=0.5) tower_d_grads = [] tower_g_grads = [] tower_d_loss_gan = [] tower_gp = [] tower_d_loss_cls = [] tower_g_loss_sim = [] tower_g_loss_r = [] tower_g_loss_r0 = [] tower_g_loss_gan = [] tower_g_loss_cls = [] tower_g_loss_cyc =...
pass
conditional_block
train_arch9.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import datetime from functools import partial import json import traceback import imlib as im import numpy as np import pylib import tensorflow as tf import tflib as tl import data_noise_in as...
(x1, x2, y1, y2, margin): return tf.reduce_mean(tf.nn.relu(models.inner_product(x1, x2) - models.inner_product(y1, y2) + margin)) parser = argparse.ArgumentParser() # settings dataroot_default = './data/CelebA' parser.add_argument('--dataroot', type=str, default=dataroot_default) parser.add_argument('--dataset', t...
matching_loss
identifier_name
train_arch9.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import datetime from functools import partial import json import traceback import imlib as im import numpy as np import pylib import tensorflow as tf import tflib as tl import data_noise_in as...
parser = argparse.ArgumentParser() # settings dataroot_default = './data/CelebA' parser.add_argument('--dataroot', type=str, default=dataroot_default) parser.add_argument('--dataset', type=str, default='celeba') parser.add_argument('--gpu', type=str, default='0,1', help='Specify which gpu to use b...
return tf.reduce_mean(tf.nn.relu(models.inner_product(x1, x2) - models.inner_product(y1, y2) + margin))
identifier_body
train_arch9.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import datetime from functools import partial import json import traceback import imlib as im import numpy as np import pylib import tensorflow as tf import tflib as tl import data_noise_in as...
else: pass d_opt = tf.train.AdamOptimizer(lr, beta1=0.5) g_opt = tf.train.AdamOptimizer(lr, beta1=0.5) tower_d_grads = [] tower_g_grads = [] tower_d_loss_gan = [] tower_gp = [] tower_d_loss_cls = [] tower_g_loss_sim = [] tower_g_loss_r = [] tower_g_loss_r0 = [] tower_g_loss_gan = [] tower_g_loss_cls = [] towe...
xt_s = tf.gather(xs_s, permuted_index) lt_s = tf.gather(ls_s, permuted_index) rt_i = tf.gather(rs_s, permuted_index) rt_s = tf.reshape(tf.gather(r_M, rt_i), [rt_i.shape[0], args.dim_noise])
random_line_split
teslatar.py
# # Teslatar 2.0 # import teslapy # Tesla API with new multi-factor authentification import sys, time, random, logging, requests from datetime import datetime, date, timedelta # email="username@gmail.com" # Tesla username password="teslapassword" # Tesla password home_latitute=48.141356 # configure home address ...
( aPrices ): found=False i=0 dt=datetime.now() #dt=datetime(2019,4,3,11,59,59) oneHour=timedelta(hours=1) while i<len(aPrices): #print( aPrices[i][0], aPrices[i][1] ) if( aPrices[i][0]<=dt and dt<aPrices[i][0]+oneHour ): found=True break i+=1 r...
isInsidePriceHour
identifier_name
teslatar.py
# # Teslatar 2.0 # import teslapy # Tesla API with new multi-factor authentification import sys, time, random, logging, requests from datetime import datetime, date, timedelta # email="username@gmail.com" # Tesla username password="teslapassword" # Tesla password home_latitute=48.141356 # configure home address ...
# update vehicle structure vehicles=tesla.vehicle_list() # this command does not effect sleep mode of car #print( vehicles ) # check every car nCar=0 info=["state","position","charge mode","idle","charge state"] while nCar<nNumCars: # ...
aPrices=getHourlyPrices() oldPriceHour = datetime.now().hour
conditional_block
teslatar.py
# # Teslatar 2.0 # import teslapy # Tesla API with new multi-factor authentification import sys, time, random, logging, requests from datetime import datetime, date, timedelta # email="username@gmail.com" # Tesla username password="teslapassword" # Tesla password home_latitute=48.141356 # configure home address ...
#gets an Array of datetime and prices (here for testing only random) def getHourlyPrices(): aPrices=[] logging.info("Query aWATTar for new pricing...") r = requests.get('https://api.awattar.de/v1/marketdata') j = r.json()["data"] #print( j ) for i in j: #print( i["start_timestamp"...
now=float(datetime.now().strftime("%H"))+float(datetime.now().strftime("%M"))/60 hoursLeft=0 if( now>then ): hoursLeft=24-now+then else: hoursLeft=then-now return( hoursLeft )
identifier_body
teslatar.py
# # Teslatar 2.0 # import teslapy # Tesla API with new multi-factor authentification import sys, time, random, logging, requests from datetime import datetime, date, timedelta # email="username@gmail.com" # Tesla username password="teslapassword" # Tesla password home_latitute=48.141356 # configure home address ...
startHour = datetime.now().hour aPrices=[] oldPriceHour=-1 oldLenPrices=-1 timeToFull=[] mode=[] oldMode=[] lastModeChange=[] oldChargeLimitSoc=[] i=0 while i<nNumCars: aChargeMode+=[finishHour] aPricesChosen+=[0] mode+=[0] oldMode+=[-1] lastModeChange+=[0] oldChargeLimitSoc+=[0] timeToFull+...
random_line_split
my_agent.py
''' TEMPLATE for creating your own Agent to compete in 'Dungeons and Data Structures' at the Coder One AI Sports Challenge 2020. For more info and resources, check out: https://bit.ly/aisportschallenge BIO: <Tell us about your Agent here> ''' # import any external packages by un-commenting them # if you'd like to t...
blocks = random_blocks() graph = convert_to_graph(blocks) traps = locate_traps(graph) print_graph(graph, traps) # x = solid block, O = trap. set traps=None to see a clear game state. # function to time decision making # times = [] # for i in range(500): # blocks = random_blocks() ...
conditional_block
my_agent.py
''' TEMPLATE for creating your own Agent to compete in 'Dungeons and Data Structures' at the Coder One AI Sports Challenge 2020. For more info and resources, check out: https://bit.ly/aisportschallenge BIO: <Tell us about your Agent here> ''' # import any external packages by un-commenting them # if you'd like to t...
(self): ''' Place any initialisation code for your agent here (if any) ''' pass def next_move(self, game_state, player_state): ''' This method is called each time your Agent is required to choose an action If you're just starting out or are new to Python, you...
__init__
identifier_name
my_agent.py
''' TEMPLATE for creating your own Agent to compete in 'Dungeons and Data Structures' at the Coder One AI Sports Challenge 2020. For more info and resources, check out: https://bit.ly/aisportschallenge BIO: <Tell us about your Agent here> ''' # import any external packages by un-commenting them # if you'd like to t...
""" Returns a list containing traps. """ traps = [] for node in graph: if len(graph[node]) < 2: traps.append(node) continue else: neighbours = graph[node] # copy graph and delete the node temp_graph = copy.deepcopy(graph) ...
def locate_traps(graph):
random_line_split
my_agent.py
''' TEMPLATE for creating your own Agent to compete in 'Dungeons and Data Structures' at the Coder One AI Sports Challenge 2020. For more info and resources, check out: https://bit.ly/aisportschallenge BIO: <Tell us about your Agent here> ''' # import any external packages by un-commenting them # if you'd like to t...
def locate_traps(graph): """ Returns a list containing traps. """ traps = [] for node in graph: if len(graph[node]) < 2: traps.append(node) continue else: neighbours = graph[node] # copy graph and delete the node temp_graph = co...
""" Generate 43 random blocks (board always starts with 43) Can set seed for consistent testing graph """ cells = [] while len(cells) != 43: cell_to_add = (random.randint(0, 11), random.randint(0, 9)) if cell_to_add not in cells: cells.append(cell_to_add) return cells
identifier_body
calculations.js
/* * kollavarsham * http://kollavarsham.org * * Copyright (c) 2014-2015 The Kollavarsham Team * Licensed under the MIT license. */ 'use strict'; var Celestial = require('./celestial'); var celestial; var Calendar = require('./calendar'); var calendar; var JulianDate = require('./date').JulianDate; var Kollavars...
else { this.calendarData.paksa = 'Suklapaksa'; } }, fromGregorian : function (settings, gregorianDate) { // TODO: Add Tests if/when feasible _setConstants(settings); var julianDay = calendar.gregorianDateToJulianDay(gregorianDate); var ahargana = calendar.julianDayToAhargana(julianD...
{ this.calendarData.tithiDay -= 15; this.calendarData.paksa = 'Krsnapaksa'; }
conditional_block
calculations.js
/* * kollavarsham * http://kollavarsham.org * * Copyright (c) 2014-2015 The Kollavarsham Team * Licensed under the MIT license. */ 'use strict'; var Celestial = require('./celestial'); var celestial; var Calendar = require('./calendar'); var calendar; var JulianDate = require('./date').JulianDate; var Kollavars...
malayalaNaksatra : true, // HP mlMalayalaNaksatra : true, // HP sunriseTime : { hour : true, minute : true } }, setPaksa : function () { // TODO: Add Tests if/when feasible if (15 < this.calendarData.tithiDay) { this.calendarData.tithiDay -= 15; ...
ftithi : true, naksatra : true,
random_line_split
global.go
package shared import ( "fmt" "github.com/pkg/errors" "net/url" "os/exec" "strings" w "github.com/chef/automate/api/config/shared/wrappers" "github.com/chef/automate/lib/io/fileutils" "github.com/chef/automate/lib/proxy" "github.com/chef/automate/lib/stringutils" gw "github.com/golang/protobuf/ptypes/wrappe...
noProxy := c.V1.Proxy.NoProxy for _, noProxyEntry := range proxy.DefaultNoProxyEntries { if !stringutils.SliceContains(noProxy, noProxyEntry) { noProxy = append(noProxy, noProxyEntry) } } return w.String(strings.Join(noProxy, ",")) } func (c *GlobalConfig) SetGlobalConfig(g *GlobalConfig) { } func (c *G...
{ return w.String(strings.Join(proxy.DefaultNoProxyEntries, ",")) }
conditional_block
global.go
package shared import ( "fmt" "github.com/pkg/errors" "net/url" "os/exec" "strings" w "github.com/chef/automate/api/config/shared/wrappers" "github.com/chef/automate/lib/io/fileutils" "github.com/chef/automate/lib/proxy" "github.com/chef/automate/lib/stringutils" gw "github.com/golang/protobuf/ptypes/wrappe...
() error { // nolint gocyclo cfgErr := NewInvalidConfigError() if c.GetV1() == nil { cfgErr.AddMissingKey("global.v1") return cfgErr } if c.GetV1().GetFqdn() == nil { cfgErr.AddMissingKey("global.v1.fqdn") } if len(c.GetV1().GetFrontendTls()) < 1 { // It's not currently mandatory to configure frontend_...
Validate
identifier_name
global.go
package shared import ( "fmt" "github.com/pkg/errors" "net/url" "os/exec" "strings" w "github.com/chef/automate/api/config/shared/wrappers" "github.com/chef/automate/lib/io/fileutils" "github.com/chef/automate/lib/proxy" "github.com/chef/automate/lib/stringutils" gw "github.com/golang/protobuf/ptypes/wrappe...
default: cfgErr.AddInvalidValue("global.v1.external.opensearch.auth.scheme", "Scheme should be one of 'basic_auth', 'aws_os'.") } } if externalPG := c.GetV1().GetExternal().GetPostgresql(); externalPG.GetEnable().GetValue() { if auth := c.GetV1().GetExternal().GetPostgresql().GetAuth(); auth.GetScheme()....
if p == "" { cfgErr.AddMissingKey("global.v1.external.opensearch.auth.aws_os.password") } case "":
random_line_split
global.go
package shared import ( "fmt" "github.com/pkg/errors" "net/url" "os/exec" "strings" w "github.com/chef/automate/api/config/shared/wrappers" "github.com/chef/automate/lib/io/fileutils" "github.com/chef/automate/lib/proxy" "github.com/chef/automate/lib/stringutils" gw "github.com/golang/protobuf/ptypes/wrappe...
// NoProxyString turns a non-empty NoProxy whitelist into a string of comma-separated // entries for easier consumption by the hab config. func (c *GlobalConfig) NoProxyString() *gw.StringValue { // If no proxy is set at all, move along. if c.V1.Proxy == nil { return nil } // Just return the default list if c...
{ if c.V1.Proxy == nil { return nil } proxy := c.V1.Proxy if proxy.Host == nil { return nil } b := strings.Builder{} // NOTE: from testing, it appears that Rust (hab) requires "http://" to be // at the head of the proxy URLs b.WriteString("http://") // nolint: errcheck if proxy.User != nil { authPart...
identifier_body
binocular_input_topographic_map.py
""" Test for ocular preferrence in topographic maps using STDP and synaptic rewiring. http://hdl.handle.net/1842/3997 """ # Imports import numpy as np import pylab as plt import time from pacman.model.constraints.placer_constraints.placer_chip_and_core_constraint import \ PlacerChipAndCoreConstraint import spynnak...
(spikes, title): if spikes is not None and len(spikes) > 0: f, ax1 = plt.subplots(1, 1, figsize=(16, 8)) ax1.set_xlim((0, simtime)) ax1.scatter([i[1] for i in spikes], [i[0] for i in spikes], s=.2) ax1.set_xlabel('Time/ms') ax1.set_ylabel('spikes') ...
plot_spikes
identifier_name
binocular_input_topographic_map.py
""" Test for ocular preferrence in topographic maps using STDP and synaptic rewiring. http://hdl.handle.net/1842/3997 """ # Imports import numpy as np import pylab as plt import time from pacman.model.constraints.placer_constraints.placer_chip_and_core_constraint import \ PlacerChipAndCoreConstraint import spynnak...
plot_spikes(pre_spikes, "Source layer spikes") plt.show() plot_spikes(post_spikes, "Target layer spikes") plt.show() final_ff_conn_network = np.ones((256, 256)) * np.nan final_lat_conn_network = np.ones((256, 256)) * np.nan for source, target, weight, delay in pre_weights[-1]: if...
if spikes is not None and len(spikes) > 0: f, ax1 = plt.subplots(1, 1, figsize=(16, 8)) ax1.set_xlim((0, simtime)) ax1.scatter([i[1] for i in spikes], [i[0] for i in spikes], s=.2) ax1.set_xlabel('Time/ms') ax1.set_ylabel('spikes') ax1.set_title(ti...
identifier_body
binocular_input_topographic_map.py
""" Test for ocular preferrence in topographic maps using STDP and synaptic rewiring. http://hdl.handle.net/1842/3997 """ # Imports import numpy as np import pylab as plt import time from pacman.model.constraints.placer_constraints.placer_chip_and_core_constraint import \ PlacerChipAndCoreConstraint import spynnak...
ax1.set_xlabel('Time/ms') ax1.set_ylabel('spikes') ax1.set_title(title) else: print "No spikes received" plot_spikes(pre_spikes, "Source layer spikes") plt.show() plot_spikes(post_spikes, "Target layer spikes") plt.show() final_ff_conn_netw...
f, ax1 = plt.subplots(1, 1, figsize=(16, 8)) ax1.set_xlim((0, simtime)) ax1.scatter([i[1] for i in spikes], [i[0] for i in spikes], s=.2)
random_line_split
binocular_input_topographic_map.py
""" Test for ocular preferrence in topographic maps using STDP and synaptic rewiring. http://hdl.handle.net/1842/3997 """ # Imports import numpy as np import pylab as plt import time from pacman.model.constraints.placer_constraints.placer_chip_and_core_constraint import \ PlacerChipAndCoreConstraint import spynnak...
assert delay == args.delay for source, target, weight, delay in post_weights[-1]: if np.isnan(final_lat_conn_network[int(source), int(target)]): final_lat_conn_network[int(source), int(target)] = weight else: final_lat_conn_network[int(source), int(target)] += weigh...
final_ff_conn_network[int(source), int(target)] += weight
conditional_block
imaginate.rs
use crate::wasm_application_io::WasmEditorApi; use core::any::TypeId; use core::future::Future; use futures::{future::Either, TryFutureExt}; use glam::{DVec2, U64Vec2}; use graph_craft::imaginate_input::{ImaginateController, ImaginateMaskStartingFill, ImaginatePreferences, ImaginateSamplingMethod, ImaginateServerStatus...
fn initiate_server_check_maybe_fail(&mut self) -> Result<Option<ImaginateFuture>, Error> { use futures::future::FutureExt; let Some(client) = &self.client else { return Ok(None); }; if self.pending_server_check.is_some() { return Ok(None); } self.server_status = ImaginateServerStatus::Checking; l...
{ match parse_url(name) { Ok(url) => self.host_name = url, Err(err) => self.server_status = ImaginateServerStatus::Failed(err.to_string()), } }
identifier_body
imaginate.rs
use crate::wasm_application_io::WasmEditorApi; use core::any::TypeId; use core::future::Future; use futures::{future::Either, TryFutureExt}; use glam::{DVec2, U64Vec2}; use graph_craft::imaginate_input::{ImaginateController, ImaginateMaskStartingFill, ImaginatePreferences, ImaginateSamplingMethod, ImaginateServerStatus...
}; }; let response = match response { Ok(response) => response.and_then(reqwest::Response::error_for_status).map_err(Error::Request)?, Err(_aborted) => { set_progress(ImaginateStatus::Terminating); let url = join_url(&base_url, SDAPI_TERMINATE)?; let request = client.post(url).build().map_err(Error::...
{ if let Ok(ProgressResponse { progress }) = progress { set_progress(ImaginateStatus::Generating(progress * 100.)); } response_future }
conditional_block
imaginate.rs
use crate::wasm_application_io::WasmEditorApi; use core::any::TypeId; use core::future::Future; use futures::{future::Either, TryFutureExt}; use glam::{DVec2, U64Vec2}; use graph_craft::imaginate_input::{ImaginateController, ImaginateMaskStartingFill, ImaginatePreferences, ImaginateSamplingMethod, ImaginateServerStatus...
(futures::future::AbortHandle); impl ImaginateTerminationHandle for ImaginateFutureAbortHandle { fn terminate(&self) { self.0.abort() } } #[derive(Debug)] enum Error { UrlParse { text: String, err: <&'static str as TryInto<Url>>::Error }, ClientBuild(reqwest::Error), RequestBuild(reqwest::Error), Request(reqw...
ImaginateFutureAbortHandle
identifier_name
imaginate.rs
use crate::wasm_application_io::WasmEditorApi; use core::any::TypeId; use core::future::Future; use futures::{future::Either, TryFutureExt}; use glam::{DVec2, U64Vec2}; use graph_craft::imaginate_input::{ImaginateController, ImaginateMaskStartingFill, ImaginatePreferences, ImaginateSamplingMethod, ImaginateServerStatus...
width: res.x, height: res.y, restore_faces: improve_faces.await, tiling: tiling.await, negative_prompt: negative_prompt.await, sampler_index, }; let request_builder = if adapt_input_image.await { let base64_data = image_to_base64(image)?; let request_data = ImaginateImageToImageRequest { common: co...
seed: seed.await, steps: samples.await, cfg_scale: prompt_guidance.await as f64,
random_line_split