file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
main.go
.Redirect(w, r, url, http.StatusFound) } // oauth2callback is the handler to which Google's OAuth service redirects the // user after they have granted the appropriate permissions. func oauth2callbackHandler(w http.ResponseWriter, r *http.Request) { // Create an oauth transport with a urlfetch.Transport embedded insi...
w.WriteHeader(500) LogPrintf("oauth: json marshal") return } storeCredential(userId, tok, string(userSer)) http.Redirect(w, r, fullUrl, http.StatusFound) } func SetupHandler(w http.ResponseWriter, r *http.Request) { userId, err := userID(r) if err != nil || userId == "" { w.WriteHeader(400) LogPrintf("s...
} userSer, err := json.Marshal(u) if err != nil {
random_line_split
main.go
(w, r, url, http.StatusFound) } // oauth2callback is the handler to which Google's OAuth service redirects the // user after they have granted the appropriate permissions. func oauth2callbackHandler(w http.ResponseWriter, r *http.Request) { // Create an oauth transport with a urlfetch.Transport embedded inside. t :=...
(conn *picarus.Conn, svc *mirror.Service, trans *oauth.Transport, t *mirror.TimelineItem) ([]byte, error) { a, err := svc.Timeline.Attachments.Get(t.Id, t.Attachments[0].Id).Do() if err != nil { LogPrintf("getattachment: metadata") return nil, err } req, err := http.NewRequest("GET", a.ContentUrl, nil) if err ...
getImageAttachment
identifier_name
snapshots.go
"Content upload reference to use", }, cli.BoolFlag{ Name: "keep", Usage: "Keep diff content. up to creator to delete it.", }, }, commands.LabelFlag), Action: func(context *cli.Context) error { var ( idA = context.Args().First() idB = context.Args().Get(1) ) if idA == "" { return errors.Ne...
Flags: []cli.Flag{ cli.StringFlag{ Name: "target, t", Usage: "Mount target path, will print mount, if provided", }, cli.BoolFlag{ Name: "mounts", Usage: "Print out snapshot mounts as JSON", }, }, Action: func(context *cli.Context) error { if narg := context.NArg(); narg < 1 || narg > 2 { r...
ArgsUsage: "[flags] <key> [<parent>]",
random_line_split
snapshots.go
"target, t", Usage: "Mount target path, will print mount, if provided", }, cli.BoolFlag{ Name: "mounts", Usage: "Print out snapshot mounts as JSON", }, }, Action: func(context *cli.Context) error { if narg := context.NArg(); narg < 1 || narg > 2 { return cli.ShowSubcommandHelp(context) } var...
{ // FIXME: This is specific to Unix for _, m := range mounts { fmt.Printf("mount -t %s %s %s -o %s\n", m.Type, m.Source, filepath.Join(target, m.Target), strings.Join(m.Options, ",")) } }
identifier_body
snapshots.go
) } return nil }, } var viewCommand = cli.Command{ Name: "view", Usage: "Create a read-only snapshot from a committed snapshot", ArgsUsage: "[flags] <key> [<parent>]", Flags: []cli.Flag{ cli.StringFlag{ Name: "target, t", Usage: "Mount target path, will print mount, if provided", }, cli...
printMounts
identifier_name
snapshots.go
(ctx, id) if err != nil { return ocispec.Descriptor{}, err } if info.Kind == snapshots.KindActive { mounts, err = sn.Mounts(ctx, id) if err != nil { return ocispec.Descriptor{}, err } } else { key := fmt.Sprintf("%s-view-key", id) mounts, err = sn.View(ctx, key, id) if err != nil { return ocispe...
{ return err }
conditional_block
server.py
shake(
v): key = base64.b64encode(hashlib.sha1(v + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest()) response = 'HTTP/1.1 101 Switching Protocols\r\n' \ 'Upgrade: websocket\r\n' \ 'Connection: Upgrade\r\n' \ 'Sec-WebSocket-Accept:' + key + '\r\n\...
self, conn,
identifier_name
server.py
shake(self, conn, v): key = base64.b64encode(hashlib.sha1(v + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest()) response = 'HTTP/1.1 101 Switching Protocols\r\n' \ 'Upgrade: websocket\r\n' \ 'Connection: Upgrade\r\n' \ 'Sec-WebSocket-Accept...
length = len_flag ret = '' for cnt, d in enumerate(raw): ret += chr(ord(d) ^ ord(mask[cnt % 4])) if not ret: pass # logging.debug("frame info FIN %d Opcode %d mask %d length %d " % (FIN, Opcode, is_mask, length)) # hexstr = binas...
raw = data[14:] length = reduce(lambda y, z: y * 256 + z, map(lambda x: ord(x), data[2:9])) else: mask = data[2:6] raw = data[6:]
random_line_split
server.py
shake(self, conn, v): key = base64.b64encode(hashlib.sha1(v + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest()) response = 'HTTP/1.1 101 Switching Protocols\r\n' \ 'Upgrade: websocket\r\n' \ 'Connection: Upgrade\r\n' \ 'Sec-WebSocket-Accept...
ey]['no'])) elif msg['a'] == 'f': logging.info('a %s s %d e %d n %d' % (msg['a'], msg['s'], msg['e'], msg['n'])) start, end = msg['s'], msg['e'] length = end - start if msg['n'] != session['no']: if msg['n'] < session[...
self.session[sesskey]['filebuffer'] = [] self.session[sesskey]['no'] = 0 self.session[sesskey]['file'] = open( os.path.join(os.path.dirname(__file__), 'upload', msg['name']), 'ab') elif msg['a'] == 'ping': self.ws_send(conn, "ok:%d"...
conditional_block
server.py
Server: socket = None socket_list = set() port = 7000 buffersize = 1024*1024 timeout = 20 content = dict() session = dict() def __init__(self): filelist = ['test.html', 'upload.js', 'spark-md5.min.js'] for i in filelist: with open(i, 'r') as f: ...
b.md5() while True: data = f.read(block_size) if not data: break md5.update(data) return md5.hexdigest() class
identifier_body
rol_common.js
fdid = $(this).parent().find(".folder_id").val(); var fdname = $(this).parent().find(".folder_name").val(); var parent = $(this).parent(); setTimeout(function(){ //添加焦点事件 parent.addClass("left_nav_infolink_high"); var edit_div = $('#float_edit'); edit_div.css("display","block"); edit_div.css("t...
function show_msg_tips_newdiv(type,msg,id){ if(!type || !msg) return; var time=3000; if('success'==type || 'yes'==type) $.scmtips.show("success",msg,null,time); if('warn'==type || 'warning'==type) $.scmtips.show("warn",msg,null,time); if('error'==type || 'wrong'==type) $.scmtips.show("error",msg,null,time)...
//在弹出框中显示提示信息
random_line_split
rol_common.js
nav_open"); } } //左边菜单展开,关闭替换图标 function replaceImg(obj){ var img = $(obj).find("img"); var src = img.attr("src"); if(src.indexOf('open')>0){ img.attr("src",src.replace("open","close")); }else{ img.attr("src",src.replace("close","open")); } } //打开左侧菜单,根据设置的.info样式 function open_left_nav(){ $("#left_nav"...
$(obj).css("zIndex",1000); $(obj).css("height",$(obj).find(".float_div_content").height()+70) },100); }else{ $(obj).hide(); } } //左菜单展开,关闭 function switch_left_nav(obj){ var div = $(obj).parent(); if($(obj).hasClass("left_nav_open")) { div.find(">div:not(div:first-child)").hide(); $(obj).removeClass("le...
conditional_block
rol_common.js
fdid = $(this).parent().find(".folder_id").val(); var fdname = $(this).parent().find(".folder_name").val(); var parent = $(this).parent(); setTimeout(function(){ //添加焦点事件 parent.addClass("left_nav_infolink_high"); var edit_div = $('#float_edit'); edit_div.css("display","block"); edit_div.css("t...
rror",msg,null,time); } function show_msg_tips(type,msg,width){ if(!type || !msg) return; var time=1000; if('success'==type || 'yes'==type) $.scmtips.show("success",msg, width,time); if('warn'==type || 'warning'==type) $.scmtips.show("warn",msg, width,time); if('error'==type || 'wrong'==type) $.scmtips.sh...
cmtips.show("warn",msg,null,time); if('error'==type || 'wrong'==type) $.scmtips.show("e
identifier_body
rol_common.js
,null,time); } function show_msg_tips(type,msg,width){ if(!type || !msg) return; var time=1000; if('success'==type || 'yes'==type) $.scmtips.show("success",msg, width,time); if('warn'==type || 'warning'==type) $.scmtips.show("warn",msg, width,time); if('error'==type || 'wrong'==type) $.scmtips.show("error...
break;
identifier_name
ranker_ltr.py
): """ Trains a model and saves it to a file. - This function currently only supports GBRT. Args: inss: erd.ml.CERInstances, train instances model_file: A file to save the model. For None value, the model will not be saved Returns: ranker, th...
return self.ml.apply_model(inss, model) def rank_queries(self, queries, time_log_file=None): # commonness_th, filter=True, """ Ranks entities for the given queries using the trained model. :param queries: a dictionary, {q_id: q_content, ...} :param time_log_file: file nam...
model = self.model
conditional_block
ranker_ltr.py
): """ Trains a model and saves it to a file. - This function currently only supports GBRT. Args: inss: erd.ml.CERInstances, train instances model_file: A file to save the model. For None value, the model will not be saved Returns: ranker, th...
(self, queries, time_log_file=None): # commonness_th, filter=True, """ Ranks entities for the given queries using the trained model. :param queries: a dictionary, {q_id: q_content, ...} :param time_log_file: file name to save time log :return erd.ml.CERInstances, Ranked instanc...
rank_queries
identifier_name
ranker_ltr.py
): """ Trains a model and saves it to a file. - This function currently only supports GBRT. Args: inss: erd.ml.CERInstances, train instances model_file: A file to save the model. For None value, the model will not be saved Returns: ranker, th...
inss_list.append(q_inss) # time log e_t = datetime.now() diff = e_t - s_t total_time += diff.total_seconds() time_log = "Execution time(min):\t" + str(round(total_time/60, 4)) + "\n" time_log += "Avg. time per query:\t" + str(round(total_time/len(queries), 4)...
""" Ranks entities for the given queries using the trained model. :param queries: a dictionary, {q_id: q_content, ...} :param time_log_file: file name to save time log :return erd.ml.CERInstances, Ranked instances """ print "Ranking queries ..." total_time = 0.0 ...
identifier_body
ranker_ltr.py
model: the trained model """ def __init__(self, commonness_th=None, sf_source=None, filter=True, model=None, config={}): self.commonness_th = commonness_th self.sf_source = sf_source self.filter = filter self.config = config self.model = model self.ml = ML...
random_line_split
opentuna-stack.ts
extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props: OpenTunaStackProps) { super(scope, id, props); const stack = cdk.Stack.of(this); const domainName = this.node.tryGetContext('domainName'); const domainZoneName = this.node.tryGetContext('domainZone'); const iamCertId = thi...
OpentunaStack
identifier_name
opentuna-stack.ts
const tunaManagerALBSG = new ec2.SecurityGroup(this, "TunaManagerALBSG", { vpc, description: "SG of ALB of Tuna Manager", allowAllOutbound: false, }); const tunaWorkerSG = new ec2.SecurityGroup(this, "TunaWorkerSG", { vpc, description: "SG of Tuna Worker", allowAllOutboun...
{ // ACM cert cloudfrontProps = { aliasConfiguration: { acmCertRef: cloudfrontCert.certificateArn, names: [domainName], }, ...cloudfrontProps } }
conditional_block
opentuna-stack.ts
} else if (!stack.region.startsWith('cn-')) { // Try to use ACM certificate in us-east-1 for CloudFront cloudfrontCert = new acm.DnsValidatedCertificate(this, 'CloudFrontCertificate', { domainName: domainName, hostedZone: domainZone, validation: acm.CertificateValidat...
{ super(scope, id, props); const stack = cdk.Stack.of(this); const domainName = this.node.tryGetContext('domainName'); const domainZoneName = this.node.tryGetContext('domainZone'); const iamCertId = this.node.tryGetContext('iamCertId'); let useHTTPS = false; let domainZone: r53.IHostedZone...
identifier_body
opentuna-stack.ts
cloudfrontCert: acm.Certificate | string | null = null; if (domainName && domainZoneName) { domainZone = r53.HostedZone.fromLookup(this, 'HostedZone', { domainName: domainZoneName, }); useHTTPS = true; if (iamCertId !== undefined) { // Use IAM first when specified cl...
allowAllOutbound: true, }); const tunaManagerALBSG = new ec2.SecurityGroup(this, "TunaManagerALBSG", { vpc, description: "SG of ALB of Tuna Manager", allowAllOutbound: false, }); const tunaWorkerSG = new ec2.SecurityGroup(this, "TunaWorkerSG", { vpc, description: "SG ...
const tunaManagerSG = new ec2.SecurityGroup(this, "TunaManagerSG", { vpc, description: "SG of Tuna Manager",
random_line_split
L.IM_RoutingControl.js
);transform:scale(-1.3, 1.3)"></i>'+ '</span>', tooltip: 'right', marker_style_origen: { icon : '', markerColor : 'green', divColor:'transparent', iconAnchor : new L.Point(14, 42), iconSize : new L.Point(28, 42), iconColor : '#000000', prefix : 'fa', isCanvas:false, radius:6, opacity...
else { return L.marker(wp.latLng, { draggable: true, icon: puntIntermig }); } }; this._plan = new this._reversablePlan([], { geocoder: L.Control.Geocoder.icgc(), routeWhileDragging: true, language: lang, createMarker: createM...
return L.marker(wp.latLng, { draggable: true, icon: puntDesti }); }
conditional_block
L.IM_RoutingControl.js
'<i class="t-square-rounded" style="-webkit-transform:scale(1.25) scale(0.65) rotate(45deg);-moz-transform:scale(1.25) scale(0.65) rotate(45deg);transform:scale(1.25) scale(0.65) rotate(45deg)"></i>'+ '<i class="t-turn-90-l t-c-white" style="-webkit-transform:scale(-1.3, 1.3);-moz-transform:scale(-1.3, 1.3);transfo...
random_line_split
views.py
from students.forms import CourseEnrollForm from .models import Course, Module, Content, Subject from .forms import ModuleFormSet class OwnerMixin(object): """ Миксин переопределяющий метод get_queryset во всех дочерних классах. Может взаимодействовать со всеми моделями у которых есть атрибут owner. """ def g...
c lass CourseUpdateView(PermissionRequiredMixin, OwnerCourseEditMixin, UpdateView): """ Используется для изменения Course """ # PermissionRequiredMixin проверяет если у пользователя указанный permission_required permission_required = "courses.change_course" class CourseDeleteView(PermissionRequiredMixin, Owne...
age_course_list') template_name = "courses/manage/course/form.html" class ManageCourseListView(OwnerCourseMixin, ListView): """ Используя наследование от OwnerCourseMixin, ListView этот класс также будет содержать все поля и методы из OwnerCourseMixin, ListView, OwnerMixin """ template_name = "courses/manage/c...
identifier_body
views.py
from .models import Course, Module, Content, Subject from .forms import ModuleFormSet class OwnerMixin(object): """ Миксин переопределяющий метод get_queryset во всех дочерних классах. Может взаимодействовать со всеми моделями у которых есть атрибут owner. """ def get_queryset(self): """ вернуть объекты со...
ериализирует response """ def post(self, request): for id, order in self.request_json.items(): print('id', id, ' -- ', order) for id, order in self.request_json.items(): Content.objects.filter(id=id, module__course__owner=request.user).update(order=order) return self.render_json_response({'sa
conditional_block
views.py
apps from students.forms import CourseEnrollForm from .models import Course, Module, Content, Subject from .forms import ModuleFormSet class OwnerMixin(object): """ Миксин переопределяющий метод get_queryset во всех дочерних классах. Может взаимодействовать со всеми моделями у которых есть атрибут owner. """ ...
content.content_object.delete() content.delete() # возвращаемся к списку контента модуля return redirect('module_content_list', module.id) class ModuleContentListView(TemplateResponseMixin, View): template_name = "courses/manage/module/content_list.html" def get(self, request, module_id): module = get_ob...
id=id, module__course__owner=request.user) module = content.module
random_line_split
views.py
from students.forms import CourseEnrollForm from .models import Course, Module, Content, Subject from .forms import ModuleFormSet class OwnerMixin(object): """ Миксин переопределяющий метод get_queryset во всех дочерних классах. Может взаимодействовать со всеми моделями у которых есть атрибут owner. """ def g...
ы) задается владелец этого объекта. """ form.instance.owner = self.request.user return super(OwnerEditMixin, self).form_valid(form) class OwnerCourseMixin(OwnerMixin, LoginRequiredMixin): """ Указание модели для queryset во всех дочерних классах """ model = Course class OwnerCourseEditMixin(OwnerCourseM...
верждение форм
identifier_name
CKEditor_media_tab.js
/dialogs/image.js */ function _eatlas_media_frame_ckeditor_create_media_tab() { // As defined in imageDialog function var IMAGE = 1, LINK = 2, PREVIEW = 4, CLEANUP = 8; var IMAGESTYLE_CLASS_PREFIX = 'img__view_mode__'; var IMAGEID_CLASS_PREFIX = 'img__fid__'; var onMediaStyleChange = function() ...
else { inputEl.setAttribute('readonly', true); inputEl.addClass('disabled'); } }; var imageStyles = [ ['Original', 'media_original'], ['Link', 'media_link'], ['Preview', 'media_preview'], ['Large', 'media_large'] ]; // NOTE: Drupal.settings.eatlas_media_frame_filter.drupal_custom_image...
{ inputEl.removeAttribute('readonly'); inputEl.removeClass('disabled'); }
conditional_block
CKEditor_media_tab.js
/image/dialogs/image.js */ function _eatlas_media_frame_ckeditor_create_media_tab() { // As defined in imageDialog function var IMAGE = 1, LINK = 2, PREVIEW = 4, CLEANUP = 8; var IMAGESTYLE_CLASS_PREFIX = 'img__view_mode__'; var IMAGEID_CLASS_PREFIX = 'img__fid__'; var onMediaStyleChange = funct...
// Remove previous 'image style' class and find the image ID var newClasses = []; for (var i=0, len=classes.length; i<len; i++) { if (classes[i].substring(0, IMAGESTYLE_CLASS_PREFIX.length) !== IMAGESTYLE_CLASS_PREFIX) { newClasses.push(classes[i]); } } // Add new 'image style' class ne...
// API: dialog.getValueOf(pageId, elementId); var classes = dialog.getValueOf('advanced', 'txtGenClass'); classes = classes ? classes.split(/\s+/) : [];
random_line_split
CKEditor_media_tab.js
El = dialog.getContentElement('media', inputID).getInputElement(); if (active) { inputEl.removeAttribute('readonly'); inputEl.removeClass('disabled'); } else { inputEl.setAttribute('readonly', true); inputEl.addClass('disabled'); } }; var imageStyles = [ ['Original', 'media_original'], ...
{ return $('<div/>').html(str).text(); }
identifier_body
CKEditor_media_tab.js
}; var toggleInput = function(dialog, inputID, active) { var inputEl = dialog.getContentElement('media', inputID).getInputElement(); if (active) { inputEl.removeAttribute('readonly'); inputEl.removeClass('disabled'); } else { inputEl.setAttribute('readonly', true); inputEl.addClass('disabled...
_decode
identifier_name
lib.rs
RuntimeOrigin> + IsType<<<Self as frame_system::Config>::RuntimeOrigin as frame_support::traits::OriginTrait>::PalletsOrigin>; /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; } #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { //...
} #[pallet::hooks] impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> { fn integrity_test() { // If you hit this error, you need to try to `Box` big dispatchable parameters. assert!( sp_std::mem::size_of::<<T as Config>::RuntimeCall>() as u32 <= CALL_ALIGN, "Call enum size should be smaller tha...
{ let allocator_limit = sp_core::MAX_POSSIBLE_ALLOCATION; let call_size = ((sp_std::mem::size_of::<<T as Config>::RuntimeCall>() as u32 + CALL_ALIGN - 1) / CALL_ALIGN) * CALL_ALIGN; // The margin to take into account vec doubling capacity. let margin_factor = 3; allocator_limit / margin_factor /...
identifier_body
lib.rs
RuntimeOrigin> + IsType<<<Self as frame_system::Config>::RuntimeOrigin as frame_support::traits::OriginTrait>::PalletsOrigin>; /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; } #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { //...
() { // If you hit this error, you need to try to `Box` big dispatchable parameters. assert!( sp_std::mem::size_of::<<T as Config>::RuntimeCall>() as u32 <= CALL_ALIGN, "Call enum size should be smaller than {} bytes.", CALL_ALIGN, ); } } #[pallet::error] pub enum Error<T> { /// Too many ca...
integrity_test
identifier_name
lib.rs
_constants] impl<T: Config> Pallet<T> { /// The limit on the number of batched calls. fn batched_calls_limit() -> u32 { let allocator_limit = sp_core::MAX_POSSIBLE_ALLOCATION; let call_size = ((sp_std::mem::size_of::<<T as Config>::RuntimeCall>() as u32 + CALL_ALIGN - 1) / CALL_ALIGN) * CALL_ALIGN; ...
{ return Err(BadOrigin.into()) }
conditional_block
lib.rs
>::RuntimeOrigin> + IsType<<<Self as frame_system::Config>::RuntimeOrigin as frame_support::traits::OriginTrait>::PalletsOrigin>; /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; } #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { ...
/// event is deposited. If a call failed and the batch was interrupted, then the /// `BatchInterrupted` event is deposited, along with the number of successful calls made /// and the error of the failed call. If all were successful, then the `BatchCompleted` /// event is deposited. #[pallet::call_index(0)] ...
/// - O(C) where C is the number of calls to be batched. /// /// This will return `Ok` in all circumstances. To determine the success of the batch, an
random_line_split
main.py
True, 'input_dim':2048} else: warnings.warn('=> You did not choose a global image representation method!') representation = None # which for original vgg or alexnet model = get_model(args.arch, representation, args.num_classe...
__init__
identifier_name
main.py
.parameters(), 'lr': args.lr, 'weight_decay': args.weight_decay}) params_list.append({'params': model.classifier.parameters(), 'lr': args.lr*args.classifier_factor, 'weight_decay': 0. if args.arch.startswith('vgg') else args.weight_...
lr_factor, lr = self.log(params, total_epoch)
conditional_block
main.py
-trained model') parser.add_argument('--world-size', default=1, type=int, help='number of distributed processes') parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str, help='url used to set up distributed training') parser.add_argument('--dist-backend', ...
loss = criterion(output, target) # measure accuracy and record loss prec1, prec5 = accuracy(output, target, topk=(1, 5)) losses.update(loss.item(), input.size(0)) top1.update(prec1[0], input.size(0)) top5.update(prec5[0], input.size(0)) # compute gradient and do...
batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() # switch to train mode model.train() end = time.time() for i, (input, target) in enumerate(train_loader): # measure data loading time data_time.upd...
identifier_body
main.py
-trained model') parser.add_argument('--world-size', default=1, type=int, help='number of distributed processes')
help='url used to set up distributed training') parser.add_argument('--dist-backend', default='gloo', type=str, help='distributed backend') parser.add_argument('--seed', default=None, type=int, help='seed for initializing training. ') parser.add_argument('--gp...
parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str,
random_line_split
shlex.go
nil || b == nil { return false } if a.tokenType != b.tokenType { return false } return a.value == b.value } const ( RUNE_CHAR string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-,/@$*()+=><:;&^%~|!?[]{}" RUNE_SPACE string = " \t\r\n" RUNE_ESCAPING_QUOTE st...
func (classifier *TokenClassifier) ClassifyRune(rune int32) RuneTokenType { return classifier.typeMap[rune] } /* A type for turning an input stream in to a sequence of strings. Whitespace and comments are skipped. */ type Lexer struct { tokenizer *Tokenizer } /* Create a new lexer. */ func NewLexer(r io.Reader) (...
{ typeMap := map[int32]RuneTokenType{} addRuneClass(&typeMap, RUNE_CHAR, RUNETOKEN_CHAR) addRuneClass(&typeMap, RUNE_SPACE, RUNETOKEN_SPACE) addRuneClass(&typeMap, RUNE_ESCAPING_QUOTE, RUNETOKEN_ESCAPING_QUOTE) addRuneClass(&typeMap, RUNE_NONESCAPING_QUOTE, RUNETOKEN_NONESCAPING_QUOTE) addRuneClass(&typeMap, RUNE...
identifier_body
shlex.go
never equal another token. */ func (a *Token) Equal(b *Token) bool { if a == nil || b == nil { return false } if a.tokenType != b.tokenType { return false } return a.value == b.value } const ( RUNE_CHAR string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-,/@$*()+=><:;&^%~|...
random_line_split
shlex.go
nil || b == nil { return false } if a.tokenType != b.tokenType { return false } return a.value == b.value } const ( RUNE_CHAR string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-,/@$*()+=><:;&^%~|!?[]{}" RUNE_SPACE string = " \t\r\n" RUNE_ESCAPING_QUOTE st...
(r io.Reader) (*Lexer, error) { tokenizer, err := NewTokenizer(r) if err != nil { return nil, err } lexer := &Lexer{tokenizer: tokenizer} return lexer, nil } /* Return the next word, and an error value. If there are no more words, the error will be io.EOF. */ func (l *Lexer) NextWord() (string, error) { var t...
NewLexer
identifier_name
shlex.go
for turning an input stream in to a sequence of strings. Whitespace and comments are skipped. */ type Lexer struct { tokenizer *Tokenizer } /* Create a new lexer. */ func NewLexer(r io.Reader) (*Lexer, error) { tokenizer, err := NewTokenizer(r) if err != nil { return nil, err } lexer := &Lexer{tokenizer: toke...
{ word, err := l.NextWord() if err != nil { if err == io.EOF { return subStrings, nil } return subStrings, err } subStrings = append(subStrings, word) }
conditional_block
mod.rs
sequences from `tail` until either (1) `tail` is // exhausted, or (2) the display width of the result would exceed `display_width`. // // 3. If tail was exhausted, then contribute graphemes and ANSI escape sequences from `s` until the // display_width of the result would exceed `display_width`. pub fn truncate_s...
asure_text_width_osc_hyperlink_non_ascii() { assert_eq!(measure_text_width("\x1b[38;5;4m\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b\\src/ansi/modバー.rs\x1b]8;;\x1b\\\x1b[0m"), measure_text_width("src/ansi/modバー.rs")); } #[test] fn test_parse_first_style() { let...
_text_width("\x1b[38;5;4m\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b\\src/ansi/mod.rs\x1b]8;;\x1b\\\x1b[0m"), measure_text_width("src/ansi/mod.rs")); } #[test] fn test_me
identifier_body
mod.rs
sequences from `tail` until either (1) `tail` is // exhausted, or (2) the display width of the result would exceed `display_width`. // // 3. If tail was exhausted, then contribute graphemes and ANSI escape sequences from `s` until the // display_width of the result would exceed `display_width`. pub fn truncate_s...
ure_text_width("\x1b[38;5;4m\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b\\src/ansi/modバー.rs\x1b]8;;\x1b\\\x1b[0m"), measure_text_width("src/ansi/modバー.rs")); } #[test] fn test_parse_first_style() { let minus_line_from_unconfigured_git = "\x1b[31m-____\x1b[m\n"; ...
hyperlink_non_ascii() { assert_eq!(meas
identifier_name
mod.rs
sequences from `tail` until either (1) `tail` is // exhausted, or (2) the display width of the result would exceed `display_width`. // // 3. If tail was exhausted, then contribute graphemes and ANSI escape sequences from `s` until the // display_width of the result would exceed `display_width`. pub fn truncate_s...
} Cow::from(format!("{result}{result_tail}")) } pub fn parse_style_sections(s: &str) -> Vec<(ansi_term::Style, &str)> { let mut sections = Vec::new(); let mut curr_style = Style::default(); for element in AnsiElementIterator::new(s) { match element { Element::Text(start, end) ...
{ result.push_str(t); }
conditional_block
mod.rs
escape sequences from `tail` until either (1) `tail` is // exhausted, or (2) the display width of the result would exceed `display_width`. // // 3. If tail was exhausted, then contribute graphemes and ANSI escape sequences from `s` until the // display_width of the result would exceed `display_width`. pub fn tru...
measure_text_width("src/ansi/mod.rs")); } #[test] fn test_measure_text_width_osc_hyperlink_non_ascii() { assert_eq!(measure_text_width("\x1b[38;5;4m\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b\\src/ansi/modバー.rs\x1b]8;;\x1b\\\x1b[0m"), measure_text_w...
random_line_split
main.rs
: u32; static __DATA_END: u32; static mut __DATA_START: u32; static mut __BSS_START: u32; static mut __BSS_END: u32; } let data_load = &__DATA_LOAD; let data_start = &mut __DATA_START; let data_end = &__DATA_END; let bss_start = &mut __BSS_START; let bss_end = &__...
let drag_color = Color::from_hex(0x000000); let grid_color = Color::from_hex(0x444444); // lcd controller let mut lcd = lcd::init(ltdc, rcc, &mut gpio); touch::check_family_id(&mut i2c_3).unwrap(); loop { SYSCLOCK.reset(); lcd.clear_screen(); lcd.set_background_color(Color::from_h...
gpio::Resistor::NoPull) .expect("Could not configure pwm pin"); let axis_color = Color::from_hex(0xffffff);
random_line_split
main.rs
u32; static __DATA_END: u32; static mut __DATA_START: u32; static mut __BSS_START: u32; static mut __BSS_END: u32; } let data_load = &__DATA_LOAD; let data_start = &mut __DATA_START; let data_end = &__DATA_END; let bss_start = &mut __BSS_START; let bss_end = &__B...
(hw: board::Hardware) -> ! { let board::Hardware { rcc, pwr, flash, fmc, ltdc, gpio_a, gpio_b, gpio_c, gpio_d, gpio_e, gpio_f, gpio_g, gpio_h, gpio_i, gpio_j, gpio_k, spi_2, ...
main
identifier_name
main.rs
// enable floating point unit let scb = stm32f7::cortex_m::peripheral::scb_mut(); scb.cpacr.modify(|v| v | 0b1111 << 20); asm!("DSB; ISB;"::::"volatile"); // pipeline flush main(board::hw()); } // WORKAROUND: rust compiler will inline & reorder fp instructions into #[inline(ne...
{ extern "C" { static __DATA_LOAD: u32; static __DATA_END: u32; static mut __DATA_START: u32; static mut __BSS_START: u32; static mut __BSS_END: u32; } let data_load = &__DATA_LOAD; let data_start = &mut __DATA_START; let data_end = &__DATA_END; let bss_s...
identifier_body
navtreeindex22.js
8h.htm#gaeb0fca7dd680f3f8863edb56b5ce0e5b":[4,0,72,21], "token-stack_8h.htm#gaeb9bc13c387e34deb35e981dd9c1a276":[4,0,72,10], "token-stack_8h.htm#gaec433bb494f14daea12eb32616d685a8":[4,0,72,30], "token-stack_8h.htm#gaed1a0a2b07a388b3c94cfc512dfa8335":[4,0,72,39], "token-stack_8h.htm#gaee5596e09a93afc50340f794e61a64d4":[...
"zigbee-device-common_8h.htm#gaf8e641f05f5b8359571fa677ccb8c4b3":[4,0,76,0], "zigbee-device-common_8h_source.htm":[4,0,76], "zigbee-device-host_8h.htm":[4,0,77],
random_line_split
index.ts
utOptions: InputOptions, plugin: Plugin) { if (plugin.options) return plugin.options(inputOptions) || inputOptions; return inputOptions; } function getInputOptions(rawInputOptions: GenericConfigObject): any { if (!rawInputOptions) { throw new Error('You must supply an options object to rollup'); } // inputOpti...
yOptionHook(inp
identifier_name
index.ts
(!rawInputOptions) { throw new Error('You must supply an options object to rollup'); } // inputOptions: input 从命令行或配置文件与默认配置合并 // deprecations: 过时的参数列表,过时的参数,仍然会写入正确的地方 // optionError: 错误信息 let { inputOptions, deprecations, optionError } = mergeOptions({ config: rawInputOptions, deprecateConfig: { input: tr...
.then(addons => { // pre-render all chunks for (const chunk of chunks) { if (!inputOptions.experimentalPreserveModules) chunk.generateInternalExports(outputOptions); if (chunk.isEntryModuleFacade) chunk.exportMode = getExportMode(chunk, outputOptions); } ...
random_line_split
index.ts
function checkInputOptions(options: InputOptions) { if (options.transform || options.load || options.resolveId || options.resolveExternal) { throw new Error( 'The `transform`, `load`, `resolveId` and `resolveExternal` options are deprecated in favour of a unified plugin API. See https://rollupjs.org/guide/en#plug...
{ const message = `The following options have been renamed — please update your config: ${deprecations .map(option => `${option.old} -> ${option.new}`) .join(', ')}`; warn({ code: 'DEPRECATED_OPTIONS', message, deprecations }); }
identifier_body
index.ts
function checkOutputOptions(options: OutputOptions) { if (<string>options.format === 'es6') { error({ message: 'The `es6` output format is deprecated – use `es` instead', url: `https://rollupjs.org/guide/en#output-format-f-format` }); } if (!options.format) { error({ message: `You must specify outp...
throw new Error( 'The `transform`, `load`, `resolveId` and `resolveExternal` options are deprecated in favour of a unified plugin API. See https://rollupjs.org/guide/en#plugins' ); } }
conditional_block
model_probabilistic.py
ization( self.MLP_SIZE, activation = mlp_activation, ) layer_0_act = self.layer_0(self.x_ph) layer_0_out = tf.layers.dropout(layer_0_act, rate = self.DROP, training = self.is_training) self.layer_1 = tfp.layers.DenseLocalReparameterization( self.MLP_SIZE, act...
input_scaled = self.get_scaled_features(input_raw)
random_line_split
model_probabilistic.py
[key] for key in details} self.features_shape = self.scaling['features_shape'] self.targets_shape = self.scaling['targets_shape'] def get_scaled_features(self, features): if self.config['feature_rescaling'] == 'standardization': scaled = (features - self.scaling['mean_features']) / self.scaling['std_featur...
return raw def set_hyperparameters(self, hyperparam_dict): for key, value in hyperparam_dict.items(): setattr(self, key, value) def construct_graph(self): act_funcs = { 'linear': lambda y: y, 'leaky_relu': lambda y: tf.nn.leaky_relu(y, 0.2), 'relu': lambda y: tf.nn.relu(y), 'so...
raw = targets
conditional_block
model_probabilistic.py
self.targets_shape[1]]) self.layer_0 = tfp.layers.DenseLocalReparameterization( self.MLP_SIZE, activation = mlp_activation, ) layer_0_act = self.layer_0(self.x_ph) layer_0_out = tf.layers.dropout(layer_0_act, rate = self.DROP, training = self.is_training) self.layer_1 ...
if not self.is_graph_constructed: self.construct_inference() self.sess = tf.compat.v1.Session(graph = self.graph) self.saver = tf.compat.v1.train.Saver() try: self.saver.restore(self.sess, model_path) return True except AttributeError: return False
identifier_body
model_probabilistic.py
(self, graph, dataset_details, config, scope, batch_size, max_iter = 10**8): self.graph = graph self.scope = scope self.config = config self.batch_size = batch_size self.dataset_details = dataset_details self.max_iter = max_iter self.is_graph_constructed = False ...
__init__
identifier_name
walk.py
self.console_stream = console_stream def printer(self, message, stream=False): if not stream: if self.console_output: print('\t' + message) else: if self.console_stream: print('\t' + message) def pool_process(func, iterable, process...
(path_list): """Pool process file hashing.""" return pool_process(md5_tuple, path_list, 'MD5 hashing') def remover(file_path): """Delete a file or directory path only if it exists.""" if os.path.isfile(file_path): os.remove(file_path) return True elif os.path.isdir(file_path): ...
pool_hash
identifier_name
walk.py
self.console_stream = console_stream def printer(self, message, stream=False): if not stream: if self.console_output: print('\t' + message) else: if self.console_stream: print('\t' + message) def pool_process(func, iterable, process...
class DirPaths: def __init__(self, directory, full_paths=False, topdown=True, to_include=None, to_exclude=None, min_level=0, max_level=inf, filters=None, non_e...
"""Pool process file creation dates.""" return pool_process(creation_date_tuple, path_list, 'File creation dates')
identifier_body
walk.py
self.console_stream = console_stream def printer(self, message, stream=False): if not stream: if self.console_output: print('\t' + message) else: if self.console_stream: print('\t' + message) def pool_process(func, iterable, process...
else: self.filters = False self.console_output = console_output self.console_stream = console_stream self._hash_files = hash_files self._printer = Printer(console_output, console_stream).printer self._printer('DIRPATHS') # Check that parallelizatio...
self.filters = PathFilters(to_include, to_exclude, min_level, max_level, filters, non_empty_folders)
conditional_block
walk.py
_output self.console_stream = console_stream def printer(self, message, stream=False): if not stream: if self.console_output: print('\t' + message) else: if self.console_stream: print('\t' + message) def pool_process(func, iterable, ...
return str(self.tree_dict) @property def dict(self): return self.tree_dict def _filter(self, folders, folder_or_file): for index in range(0, len(folders)): filters = self.branches[index][folder_or_file] if filters: exclude = filters.get ...
def __iter__(self): return iter(self.tree_dict.items()) def __str__(self):
random_line_split
utils.py
1].plot(range(total_epochs), bnn.fit_history.history["val_{}".format(this_metric)], '-o', label="validation") axes[i+1].legend() axes[i+1].set_ylabel(this_metric) axes[i+1].set_xlabel("epoch") plt.tight_layout() return fig, axes def make_1d2d(arr): assert arr.ndim == 1 return arr.reshape(arr.shape[0], 1)...
pred_proba_samples: array of predicted probability samples with shape (n_mc_samples, n_examples, n_classes)/(n_mc_samples, n_examples) for multiclass/binary classification. (This is the shape returned by BNN_Classifier.predict). labels: array of one-hot encoded labels with shape (n_examples, n_clas...
Get the sampled accuracies over the entire test set from logit samples. Args:
random_line_split
utils.py
1].plot(range(total_epochs), bnn.fit_history.history["val_{}".format(this_metric)], '-o', label="validation") axes[i+1].legend() axes[i+1].set_ylabel(this_metric) axes[i+1].set_xlabel("epoch") plt.tight_layout() return fig, axes def make_1d2d(arr): assert arr.ndim == 1 return arr.reshape(arr.shape[0], 1)...
return roc_curve_df def load_mnist(fashion, onehot_encode=True, flatten_x=False, crop_x=0, classes=None): """ Load the MNIST dataset Args: onehot_encode: Boolean indicating whether to one-hot encode training and test labels (default True) flatten_x: Boolean indicating whether to flatten the training...
for repeat_idx in range(np.amax(variable_importances["repeat_idx"].unique()+1)): df = variable_importances.loc[ (variable_importances["method"]==method) & (variable_importances["repeat_idx"]==repeat_idx) & (variable_importances[...
conditional_block
utils.py
if len(df)==0: continue preds, labels = df["value"].values, df["causal"].values.astype(float) fpr, tpr, _ = roc_curve(labels, np.abs(preds)) interp_tpr = np.interp(base_fpr, fpr, tpr) auroc = auc(fpr, tpr) ...
compute_power
identifier_name
utils.py
1].plot(range(total_epochs), bnn.fit_history.history["val_{}".format(this_metric)], '-o', label="validation") axes[i+1].legend() axes[i+1].set_ylabel(this_metric) axes[i+1].set_xlabel("epoch") plt.tight_layout() return fig, axes def make_1d2d(arr): assert arr.ndim == 1 return arr.reshape(arr.shape[0], 1)...
if crop_x > 0: x_train = crop(x_train, crop_x) x_test = crop(x_test, crop_x) # Flatten to 2d arrays (each example 1d) def flatten_image(X): return X.reshape(X.shape[0], X.shape[1]*X.shape[1]) if flatten_x: x_train = flatten_image(x_train) x_test = flatten_image(x_test) if onehot_encode: y_train ...
assert crop_x < X.shape[1]/2 assert crop_x < X.shape[2]/2 return X[:,crop_size:-crop_size,crop_size:-crop_size]
identifier_body
analysis.py
:param data: Data in which to detect outliers. Take care that n_samples > n_features ** 2 . :type data: pandas.DataFrame :param contamination: The amount of contamination of the data set, i.e. the proportion of outliers in the data set. Range is (0, 0.5). :type contamination: float :returns: Dec...
return vectors def get_pca_vectors_by(dataframe, by=None): """ Get principal components for each group as vectors. Vectors can then be used to annotate graphs. :param dataframe: Data holding 'df1' and 'df2' values as columns. :type dataframe: pandas.DataFrame :param by: Column to group data...
v = row[['x', 'y']].values * np.sqrt(row['var_expl']) * 3 # Scale up for better visibility. mean = row[['meanx', 'meany']].values mean_offset = (mean, mean + v) vectors.append(mean_offset)
conditional_block
analysis.py
frame with columns mean, var, count and column names of data as rows. :rtype: pandas.Dataframe """ # There's a bug in pandas 1.0.4 where you can't use custom numpy functions in agg anymore (ValueError). # Note that the variance of projections is usually divided by (n-d) for Vucm and d for Vort. Both are...
" 3 x (3) Two-way split-plot ANOVA with between-factor condition and within-factor block. :param dataframe: Aggregated data containing Fisher-z-transformed synergy index. :type dataframe: pandas.DataFrame :return: mixed-design ANOVA results. :rtype: pandas.DataFrame """ if dataframe['condit...
identifier_body
analysis.py
try: # df1 and df2 have the same scale. No need to standardize. Standardizing might actually distort PCA here. pca.fit(x) except ValueError: # Return empty. df = pd.DataFrame(columns=['var_expl', 'var_expl_ratio', 'x', 'y', 'meanx', 'meany']) else: df = pd.DataFrame({...
try: dV = n * (variances['parallel']/(n-d) - variances['orthogonal']/d) \
random_line_split
analysis.py
:param data: Data in which to detect outliers. Take care that n_samples > n_features ** 2 . :type data: pandas.DataFrame :param contamination: The amount of contamination of the data set, i.e. the proportion of outliers in the data set. Range is (0, 0.5). :type contamination: float :returns: Dec...
(dataframe): """ Get principal components as vectors. Vectors can then be used to annotate graphs. :param dataframe: Tabular PCA data. :type dataframe: pandas.DataFrame :return: Principal components as vector pairs in input space with mean as origin first and offset second. :rtype: list """...
get_pca_vectors
identifier_name
system_information.rs
fn parts(&self) -> &'a UndefinedStruct { self.parts } } impl<'a> SMBiosSystemInformation<'a> { /// Manufacturer pub fn manufacturer(&self) -> Option<String> { self.parts.get_field_string(0x04) } /// Product name pub fn product_name(&self) -> Option<String> { self.pa...
Self { parts } }
identifier_body
system_information.rs
up. pub fn wakeup_type(&self) -> Option<SystemWakeUpTypeData> { self.parts .get_field_byte(0x18) .map(|raw| SystemWakeUpTypeData::from(raw)) } /// SKU Number /// /// This text string identifies a particular computer /// configuration for sale. It is sometimes al...
/// Raw value /// /// _raw_ is most useful when _value_ is None. /// This is most likely to occur when the standard was updated but /// this library code has not been updated to match the current /// standard. pub raw: u8, /// The contained [SystemWakeUpType] value pub value: SystemW...
/// # System - Wake-up Type Data pub struct SystemWakeUpTypeData {
random_line_split
system_information.rs
. pub fn wakeup_type(&self) -> Option<SystemWakeUpTypeData> { self.parts .get_field_byte(0x18) .map(|raw| SystemWakeUpTypeData::from(raw)) } /// SKU Number /// /// This text string identifies a particular computer /// configuration for sale. It is sometimes also ...
>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str(format!("{}", self).as_str()) } } /// # System - Wake-up Type Data pub struct SystemWakeUpTypeData { /// Raw value /// /// _raw_ is most useful when _value_ is None. /// This i...
rialize<S
identifier_name
loader.rs
= data.fullname; self.source = data.source; self.source_other = data.source_other; } } struct ImageData { filename: String, fullname: Option<String>, source: Option<String>, source_other: Option<String>, // align // frameDuration } #[derive(Debug, Default)] pub struct PackInfo { name: String, author: Op...
println!("Unknown song field {}", name.local_name); xml_skip_tag(&mut reader).unwrap(); State::Song(None) } }, XmlEvent::EndElement { .. } => { if song_rhythm.is_empty() { // TODO: be graceful panic!("Empty rhythm"); } let song = SongData { name: song_nam...
"buildup" => State::Song(Some(SongField::Buildup)), "buildupRhythm" => State::Song(Some(SongField::BuildupRhythm)), _ => {
random_line_split
loader.rs
{ pub info: PackInfo, pub images: Vec<ImageLoader>, pub songs: Vec<Song>, } pub struct ImageLoader { //data: SurfaceContext pub name: String, pub fullname: Option<String>, pub data: Surface, pub source: Option<String>, pub source_other: Option<String>, } pub struct SongData { pub name: String, pub title: ...
ResPack
identifier_name
lib.rs
NewLiability( T::Index, TechnicsFor<T>, EconomicsFor<T>, T::AccountId, T::AccountId, ), /// Liability report published. NewReport(T::Index, ReportFor<T>), } #[pallet::error] pub enum Error<T> { /// Agreement proof...
( uri: &str, technics: &
get_params_proof
identifier_name
lib.rs
/// How to report of agreement execution. type Report: dispatch::Parameter + Report<Self::Index, Self::AccountId>; /// The overarching event type. type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>; } pub type TechnicsFor<T> = <<T as Config>:...
/// How to make and process agreement between two parties. type Agreement: dispatch::Parameter + Processing + Agreement<Self::AccountId>;
random_line_split
vrf.go
v *VRF) Disable() { if v.enabled { v.router.disable() v.tap.disable() if v.hostif != nil { v.hostif.disable() } v.enabled = false } } // Name returns the name of the VRF. func (v *VRF) Name() string { return v.name } func (v *VRF) String() string { return v.name } // Index returns a unique identifie...
{ return fmt.Errorf("Adding a rule to %v failed for L3 tunnel: %v", vif, err) }
conditional_block
vrf.go
:= range remotes { ft := NewFiveTuple() ft.SrcIP = CreateIPAddr(remote) ft.DstIP = CreateIPAddr(local) ft.DstPort = dstPort ft.Proto = proto fiveTuples[i] = ft } return fiveTuples } func (v *VRF) addL3Tunnel(vif *VIF) error { t := vif.Tunnel() if t == nil { return fmt.Errorf("%v is not tunnel.", vif...
GetVRFByName
identifier_name
vrf.go
// should be called with lock held func (vm *vrfManager) releaseIndex(vrf *VRF) { vm.byIndex[int(vrf.index)] = nil } // NewVRF creates a VRF instance. func NewVRF(name string) (*VRF, error) { if !vrfMgr.re.MatchString(name) { return nil, fmt.Errorf("Invalid VRF name: '%v'", name) } vrfMgr.mutex.Lock() defer ...
{ // try from the nextIndex to the end if vm.findSlot(vrf, vm.nextIndex, len(vm.byIndex)) { return true } // try from the head to the nextIndex return vm.findSlot(vrf, 0, vm.nextIndex) }
identifier_body
vrf.go
return nil } if err = vif.setVRF(v); err != nil { return err } // router -> VIF if err = v.router.addVIF(vif); err != nil { goto error1 } // ICMP -> VIF if err = v.tap.connect(vif.Outbound(), MatchOutVIF, vif); err != nil { goto error2 } // VIF -> router (DST_SELF) if err = vif.connect(v.router.i...
if t.Security() == SecurityIPSec { for _, nat := range createFiveTuples(t.remotes, t.local, IPP_UDP, PortRange{Start: 4500}) { v.router.disconnect(Match5Tuple, nat) } }
random_line_split
brush.rs
fn depth_stencil_state() -> Option<wgpu::DepthStencilState> { WorldPipelineBase::depth_stencil_state() } // NOTE: if the vertex format is changed, this descriptor must also be changed accordingly. fn vertex_buffer_layouts() -> Vec<wgpu::VertexBufferLayout<'static>> { vec![wgpu::VertexBu...
lightmap: Cow::Borrowed(lightmap.data()), });
random_line_split
brush.rs
pub fn pipeline(&self) -> &wgpu::RenderPipeline { &self.pipeline } pub fn bind_group_layouts(&self) -> &[wgpu::BindGroupLayout] { &self.bind_group_layouts } pub fn bind_group_layout(&self, id: BindGroupLayoutId) -> &wgpu::BindGroupLayout { assert!(id as usize >= BindGroupL...
let layout_refs: Vec<_> = world_bind_group_layouts .iter() .chain(self.bind_group_layouts.iter()) .collect(); self.pipeline = BrushPipeline::recreate(device, compiler, &layout_refs, sample_count); }
identifier_body
brush.rs
BrushRendererBuilder { BrushRendererBuilder { bsp_data: bsp_model.bsp_data().clone(), face_range: bsp_model.face_id..bsp_model.face_id + bsp_model.face_count, leaves: if worldmodel { Some( bsp_model .iter_leaves() ...
let primary_frames: Vec<_> = primary .iter() .map(|f| { self.create_brush_texture_frame( state, f.mipmap(BspTextureMipmap::Full), width, ...
conditional_block
brush.rs
&self) -> &[wgpu::BindGroupLayout] { &self.bind_group_layouts } pub fn bind_group_layout(&self, id: BindGroupLayoutId) -> &wgpu::BindGroupLayout { assert!(id as usize >= BindGroupLayoutId::PerTexture as usize); &self.bind_group_layouts[id as usize - BindGroupLayoutId::PerTexture as usiz...
ind_group_layouts(
identifier_name
glsl3.rs
: GLuint, batch: Batch, } impl Glsl3Renderer { pub fn new() -> Result<Self, Error> { info!("Using OpenGL 3.3 renderer"); let program = TextShaderProgram::new(ShaderVersion::Glsl3)?; let mut vao: GLuint = 0; let mut ebo: GLuint = 0; let mut vbo_instance: GLuint = 0; ...
unsafe { self.program.set_rendering_pass(RenderingPass::Background); gl::DrawElementsInstanced( gl::TRIANGLES, 6, gl::UNSIGNED_INT, ptr::null(), self.batch.len() as GLsizei, ); self....
{ unsafe { gl::BindTexture(gl::TEXTURE_2D, self.batch.tex()); } *self.active_tex = self.batch.tex(); }
conditional_block
glsl3.rs
, ptr::null(), gl::STREAM_DRAW, ); let mut index = 0; let mut size = 0; macro_rules! add_attr { ($count:expr, $gl_type:expr, $type:ty) => { gl::VertexAttribPointer( index, ...
/// Rendering is split into two passes; one for backgrounds, and one for text. u_rendering_pass: GLint, }
random_line_split
glsl3.rs
: GLuint, batch: Batch, } impl Glsl3Renderer { pub fn new() -> Result<Self, Error> { info!("Using OpenGL 3.3 renderer"); let program = TextShaderProgram::new(ShaderVersion::Glsl3)?; let mut vao: GLuint = 0; let mut ebo: GLuint = 0; let mut vbo_instance: GLuint = 0; ...
<'a> { active_tex: &'a mut GLuint, batch: &'a mut Batch, atlas: &'a mut Vec<Atlas>, current_atlas: &'a mut usize, program: &'a mut TextShaderProgram, } impl<'a> TextRenderApi<Batch> for RenderApi<'a> { fn batch(&mut self) -> &mut Batch { self.batch } fn render_batch(&mut self) ...
RenderApi
identifier_name
glsl3.rs
::GenBuffers(1, &mut vbo_instance); gl::BindVertexArray(vao); // --------------------- // Set up element buffer // --------------------- let indices: [u32; 6] = [0, 1, 3, 1, 2, 3]; gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, ebo); gl::Bu...
{ self.instances.len() }
identifier_body
service.rs
/// A future that orchestrates the entire aggregator service. // TODO: maybe add a HashSet or HashMap of clients who already // uploaded their weights to prevent a client from uploading weights // multiple times. Or we could just remove that ID from the // `allowed_ids` map. // TODO: maybe add a HashSet for clients th...
random_line_split
service.rs
the aggregations. aggregator: A, /// A client for the coordinator RPC service. rpc_client: coordinator::rpc::Client, requests: ServiceRequests<A>, aggregation_future: Option<AggregationFuture<A>>, model_number: usize, } /// This trait defines the methods that an aggregator should /// implem...
{ Self { upload: self.upload.clone(), download: self.download.clone(), aggregate: self.aggregate.clone(), select: self.select.clone(), } }
identifier_body
service.rs
that having it here would // make it easier to bypass the HTTP layer, which is convenient // for testing because we can simulate client with just // AggregatorHandles. But maybe that's just another layer of // complexity that is not worth it. global_weights: Bytes, /// The aggregator itself, w...
(&mut self, request: SelectRequest<A>) { info!("handling select request"); let SelectRequest { credentials, response_tx, } = request; let (id, token) = credentials.into_parts(); self.allowed_ids.insert(id, token); if response_tx.send(Ok(())).is_err...
handle_select_request
identifier_name
service.rs
that having it here would // make it easier to bypass the HTTP layer, which is convenient // for testing because we can simulate client with just // AggregatorHandles. But maybe that's just another layer of // complexity that is not worth it. global_weights: Bytes, /// The aggregator itself, w...
pin.poll_aggregation(cx); Poll::Pending } } pub struct ServiceRequests<A>(Pin<Box<dyn Stream<Item = Request<A>> + Send>>) where A: Aggregator; impl<A> Stream for ServiceRequests<A> where A: Aggregator, { type Item = Request<A>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Co...
{ return Poll::Ready(()); }
conditional_block
utils.py
) for args in zip(names_list, thickness_list)) res = np.array(res) Rs, Ts, As = res[:, 0, :], res[:, 1, :], res[:, 2, :] return Rs, Ts, As def merge_layers(categories, thicknesses): ''' Merges consecutive layers with th...
class TMM_sim(): def __init__(self, mats=['Ge'], wavelength=np.arange(0.38, 0.805, 0.01), substrate='Cr', substrate_thick=500): ''' This class returns the spectrum given the designed structures. ''' self.mats = mats # include substrate self.all_mats = mats + [substr...
for i in range(len(progress)): print(progress[i], 0) progress[i] = ['|'.join([l + ' ' + str(d) + ' nm' for l, d in zip(progress[i][0], progress[i][1])]), progress[i][2]] return progress
identifier_body
utils.py
res = Parallel(n_jobs=num_workers)(delayed(spectrum)(args) for args in zip(names_list, thickness_list)) res = np.array(res) Rs, Ts, As = res[:, 0, :], res[:, 1, :], res[:, 2, :] return Rs, Ts, As def merge_layers(categorie...
random_line_split
utils.py
) for args in zip(names_list, thickness_list)) res = np.array(res) Rs, Ts, As = res[:, 0, :], res[:, 1, :], res[:, 2, :] return Rs, Ts, As def merge_layers(categories, thicknesses): ''' Merges consecutive layers with th...
return progress class TMM_sim(): def __init__(self, mats=['Ge'], wavelength=np.arange(0.38, 0.805, 0.01), substrate='Cr', substrate_thick=500): ''' This class returns the spectrum given the designed structures. ''' self.mats = mats # include substrate self.all_...
print(progress[i], 0) progress[i] = ['|'.join([l + ' ' + str(d) + ' nm' for l, d in zip(progress[i][0], progress[i][1])]), progress[i][2]]
conditional_block
utils.py
) for args in zip(names_list, thickness_list)) res = np.array(res) Rs, Ts, As = res[:, 0, :], res[:, 1, :], res[:, 2, :] return Rs, Ts, As def
(categories, thicknesses): ''' Merges consecutive layers with the same material types. ''' thicknesses = thicknesses[1:-1] c_output = [categories[0]] t_output = [thicknesses[0]] for i, (c, d) in enumerate(zip(categories[1:], thicknesses[1:])): if c == c_output[-1]: t_ou...
merge_layers
identifier_name
ImpConcat-Recall.py
desired confounds from the confounds_regressors.tsv file from fmriprep, trim the columns corresponding to trimmed volumes, and save as a .txt file. starttime = time.time() confounds=[] confounds_all=[] mc_all=[] ntr=[] ntr=np.zeros((n_runs_recall,1)) for r in range(firstrun,lastrun+1): fname='_ses-01_task-recall...
# In[18]: #truncate first n_trunc TRs #confounds_trunc=confounds_selected[3:end] epi_trunc=[] #https://github.com/INCF/BrainImagingPipelines/blob/master/bips/workflows/gablab/wips/scripts/modular_nodes.py print('Number of runs to concatenate:', n_runs_recall) for run in range(firstrun,lastrun+1):#lastrun+1 ou...
import nipype.interfaces.fsl as fsl import nipype.interfaces.freesurfer as fs import os if smooth_type == 'susan': if fwhm == 0: return in_file smooth = create_susan_smooth() smooth.base_dir = out_dir#os.getcwd() smooth.inputs.inputnode.fwhm = fwhm smooth....
identifier_body