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.rs | extern crate rustbox;
use std::env;
use std::io::Result;
use std::path::Path;
mod filedata;
use filedata::FileData;
mod display;
use display::Display;
fn main()
{
let fd = match init_data()
{
Ok(v) => v,
Err(e) => {
println!("could not open specified file: {}", e);
return;
}
};
let display = Displ... | () -> Result<FileData>
{
let mut args = env::args().skip(1);
if args.len() > 0
{
let path_str = args.next().unwrap_or(String::new());
let path_str_copy = path_str.clone();
let path = Path::new(&path_str_copy);
if path.exists() == false
{
Ok(FileData::new_with_name(path_str))
}
else
{
FileData... | init_data | identifier_name |
log.js | /**
* @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
/**
* @fileOverview Defines {@link CKEDITOR#verbosity} and binary flags {@link CKEDITOR#VERBOSITY_WARN} and
* {@link CKEDITOR#VERBOSITY_ERROR}. Defines also ... |
};
/**
* Error reporting function. When {@link CKEDITOR#verbosity} has {@link CKEDITOR#VERBOSITY_ERROR} flag set, it fires
* {@link CKEDITOR#log} event with the type set to `error`. The fired event also contains the provided `errorCode` and
* `additionalData`.
*
* @since 4.5.4
* @member CKEDITOR
* @param {Stri... | {
CKEDITOR.fire( 'log', { type: 'warn', errorCode: errorCode, additionalData: additionalData } );
} | conditional_block |
log.js | /**
* @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
/**
* @fileOverview Defines {@link CKEDITOR#verbosity} and binary flags {@link CKEDITOR#VERBOSITY_WARN} and
* {@link CKEDITOR#VERBOSITY_ERROR}. Defines also ... | * Fired by {@link CKEDITOR#warn} and {@link CKEDITOR#error} methods.
* Default listener logs provided information to the console.
*
* This event can be used to provide a custom error/warning handler:
*
* CKEDTIOR.on( 'log', function( evt ) {
* // Cancel default listener.
* evt.cancel();
* // ... | };
/** | random_line_split |
parent-link.directive.ts | /*
* Squidex Headless CMS
*
* @license
* Copyright (c) Squidex UG (haftungsbeschränkt). All rights reserved.
*/
import { Directive, ElementRef, HostListener, Input, OnInit, Renderer2 } from '@angular/core';
import { ActivatedRoute, NavigationEnd, QueryParamsHandling, Router } from '@angular/router';
import { Reso... | }));
}
@HostListener('click')
public onClick(): boolean {
if (this.url) {
this.router.navigateByUrl(this.url);
}
return false;
}
private updateUrl() {
const queryParamsHandling = this.queryParamsHandling;
this.url = this.isLazyL... | .subscribe(event => {
if (event instanceof NavigationEnd) {
this.updateUrl();
} | random_line_split |
parent-link.directive.ts | /*
* Squidex Headless CMS
*
* @license
* Copyright (c) Squidex UG (haftungsbeschränkt). All rights reserved.
*/
import { Directive, ElementRef, HostListener, Input, OnInit, Renderer2 } from '@angular/core';
import { ActivatedRoute, NavigationEnd, QueryParamsHandling, Router } from '@angular/router';
import { Reso... |
private updateUrl() {
const queryParamsHandling = this.queryParamsHandling;
this.url = this.isLazyLoaded ?
this.router.createUrlTree(['.'], { queryParamsHandling, relativeTo: this.route.parent!.parent }).toString() :
this.router.createUrlTree(['.'], { queryParamsHandling, r... |
if (this.url) {
this.router.navigateByUrl(this.url);
}
return false;
}
| identifier_body |
parent-link.directive.ts | /*
* Squidex Headless CMS
*
* @license
* Copyright (c) Squidex UG (haftungsbeschränkt). All rights reserved.
*/
import { Directive, ElementRef, HostListener, Input, OnInit, Renderer2 } from '@angular/core';
import { ActivatedRoute, NavigationEnd, QueryParamsHandling, Router } from '@angular/router';
import { Reso... |
private readonly router: Router,
private readonly route: ActivatedRoute,
private readonly element: ElementRef,
private readonly renderer: Renderer2,
) {
super();
}
public ngOnInit() {
this.own(
this.route.url
.subscribe(() => {
... | onstructor( | identifier_name |
parent-link.directive.ts | /*
* Squidex Headless CMS
*
* @license
* Copyright (c) Squidex UG (haftungsbeschränkt). All rights reserved.
*/
import { Directive, ElementRef, HostListener, Input, OnInit, Renderer2 } from '@angular/core';
import { ActivatedRoute, NavigationEnd, QueryParamsHandling, Router } from '@angular/router';
import { Reso... |
return false;
}
private updateUrl() {
const queryParamsHandling = this.queryParamsHandling;
this.url = this.isLazyLoaded ?
this.router.createUrlTree(['.'], { queryParamsHandling, relativeTo: this.route.parent!.parent }).toString() :
this.router.createUrlTree(['... |
this.router.navigateByUrl(this.url);
}
| conditional_block |
LiveDataDemoBigJobs.py |
import numpy as np
import networkx
from zephyr.Problem import SeisFDFDProblem
# Plotting configuration
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.ticker as ticker
import matplotlib
matplotlib.rcParams.update({'font.size': 20})
# System / modelling configuration
cellSize = 1 ... |
trackprogress(sp, jobs)
| try:
plt.pause(interval)
update()
except KeyboardInterrupt:
print('Exiting loop...')
break
finally:
if not reduce(np.add, sp.par['dview']['resultTracker.interactcounter']) < (nsp * nsrc):
break | conditional_block |
LiveDataDemoBigJobs.py |
import numpy as np
import networkx
from zephyr.Problem import SeisFDFDProblem
# Plotting configuration
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.ticker as ticker
import matplotlib
matplotlib.rcParams.update({'font.size': 20})
# System / modelling configuration
cellSize = 1 ... | ():
#try:
# res = reduce(np.add, sp.par['dview']['resultTracker'])
#except:
# res = {}
#keys = [(freqs[0], i) for i in range(nrec)]
#resarr = np.array([res[key] if key in res.keys() else np.zeros(nrec) for key in keys])
status = np.zeros((len(jobke... | update | identifier_name |
LiveDataDemoBigJobs.py |
import numpy as np
import networkx
from zephyr.Problem import SeisFDFDProblem
# Plotting configuration
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.ticker as ticker
import matplotlib
matplotlib.rcParams.update({'font.size': 20})
# System / modelling configuration
cellSize = 1 ... | #keys = [(freqs[0], i) for i in range(nrec)]
#resarr = np.array([res[key] if key in res.keys() else np.zeros(nrec) for key in keys])
status = np.zeros((len(jobkeys),nsrc))
for i, key in enumerate(jobkeys):
status[i,:] = 1. * systemJobs[key][0].ready()#np.array([syste... | systemJobs = jobs['systemJobs']
jobkeys = systemJobs.keys()
jobkeys.sort()
fig = plt.figure()
ax1 = fig.add_axes([0.1,0.10,0.15,0.85], xlabel='Subproblem', ylabel='Source')
ax1.get_xaxis().set_major_locator(ticker.MaxNLocator(integer=True))
ax2 = fig.add_axes([0.25,0.10,0.75,0.85], xlabel='Rec... | identifier_body |
LiveDataDemoBigJobs.py | import numpy as np
import networkx
from zephyr.Problem import SeisFDFDProblem
# Plotting configuration
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.ticker as ticker
import matplotlib
matplotlib.rcParams.update({'font.size': 20})
# System / modelling configuration
cellSize = 1 ... | #keys = [(freqs[0], i) for i in range(nrec)]
#resarr = np.array([res[key] if key in res.keys() else np.zeros(nrec) for key in keys])
status = np.zeros((len(jobkeys),nsrc))
for i, key in enumerate(jobkeys):
status[i,:] = 1. * systemJobs[key][0].ready()#np.array([syste... | random_line_split | |
npc_table.js | /**
* Created by Akkadius on 2/10/2015.
*/
$(document).ready(function() {
var CalcDataTableHeight = function () {
return $(window).height() * 60 / 100;
};
var table = $("#npc_head_table").DataTable( {
scrollY: CalcDataTableHeight(),
scrollX: true,
scrollColl... | $(this).children("input").css('height', (parseInt(height)));
$(this).children("input").css("font-size", "12px");
// $('textarea').autosize();
data = "";
});
$( "#npc_head_table td, .DTFC_Cloned td" ).unbind("mouseleave");
$( "#npc_head_table td, .DTFC_Cloned td" ).bind("mous... | $(this).children("input").css('width', (parseInt(width) * 1)); | random_line_split |
npc_table.js | /**
* Created by Akkadius on 2/10/2015.
*/
$(document).ready(function() {
var CalcDataTableHeight = function () {
return $(window).height() * 60 / 100;
};
var table = $("#npc_head_table").DataTable( {
scrollY: CalcDataTableHeight(),
scrollX: true,
scrollColl... |
if($(this).has("button").length){ return; }
/* If no data present and */
if(!data && (!$(this).has("select").length && !$(this).has("input").length)){ $(this).attr("is_field_translated", 0); return; }
// console.log('data catch ' + data);
$(this).html(data);
data = "... | { data = $(this).children("input").val(); } | conditional_block |
ptr.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use bindings::*;
use heapsize::HeapSizeOf;
use std::fmt::{self, Debug};
// Defines an Arc-like type that manages ... | ptr: data
}
}
pub fn as_raw(&self) -> *mut $holder_type { self.ptr }
}
unsafe impl Send for $arc_type {}
unsafe impl Sync for $arc_type {}
impl Clone for $arc_type {
fn clone(&self) -> $arc_type {
... | impl $arc_type {
pub fn new(data: *mut $holder_type) -> $arc_type {
debug_assert!(!data.is_null());
unsafe { $addref(data); }
$arc_type { | random_line_split |
accordion.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Directive, Input} from '@angular/core';
import {coerceBooleanProperty} from '@angular/cdk/coercion';
import {... |
set hideToggle(show: boolean) { this._hideToggle = coerceBooleanProperty(show); }
private _hideToggle: boolean = false;
/**
* The display mode used for all expansion panels in the accordion. Currently two display
* modes exist:
* default - a gutter-like spacing is placed around any expanded panel, p... | { return this._hideToggle; } | identifier_body |
accordion.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Directive, Input} from '@angular/core';
import {coerceBooleanProperty} from '@angular/cdk/coercion';
import {... | extends _CdkAccordion {
/** Whether the expansion indicator should be hidden. */
@Input() get hideToggle(): boolean { return this._hideToggle; }
set hideToggle(show: boolean) { this._hideToggle = coerceBooleanProperty(show); }
private _hideToggle: boolean = false;
/**
* The display mode used for all exp... | MatAccordion | identifier_name |
accordion.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Directive, Input} from '@angular/core';
import {coerceBooleanProperty} from '@angular/cdk/coercion';
import {... | selector: 'mat-accordion',
exportAs: 'matAccordion',
host: {
class: 'mat-accordion'
}
})
export class MatAccordion extends _CdkAccordion {
/** Whether the expansion indicator should be hidden. */
@Input() get hideToggle(): boolean { return this._hideToggle; }
set hideToggle(show: boolean) { this._hide... | * Directive for a Material Design Accordion.
*/
@Directive({ | random_line_split |
coord.js | PUMP_SELECTOR.CoordSlicer = function( parameters ) {
var image = parameters.image;
var coord = parameters.coord;
var name = parameters.name;
var obj = {};
if( image === undefined) {
//PUMPER.debug("PUMPER::CoordSlicer() - Cannot slice image, image missing.");
return undefine... | else{
var coords = coord.split("\n");
coords.clean("");
for(var i=0;i<coords.length;i++) {
var coordinate = coords[i].split(" ");
obj[coordinate[0]] = PUMP_SELECTOR.CropImage(image,coordinate[1],coordinate[2],coordinate[3],coordinate[4]);
}
return obj;
... | {
//PUMPER.debug("PUMPER::CoordSlicer() - Warn: No coordinate data given. Returning image.");
return obj[name] = obj;
} | conditional_block |
coord.js | PUMP_SELECTOR.CoordSlicer = function( parameters ) {
var image = parameters.image;
var coord = parameters.coord;
var name = parameters.name; | //PUMPER.debug("PUMPER::CoordSlicer() - Cannot slice image, image missing.");
return undefined;
}else if (coord === undefined) {
//PUMPER.debug("PUMPER::CoordSlicer() - Warn: No coordinate data given. Returning image.");
return obj[name] = obj;
}else{
var coords = coord.s... | var obj = {};
if( image === undefined) { | random_line_split |
oauthreturn.py | from flask import request, render_template
from flask.ext.login import current_user, login_user
from mysite.weibo import Client
from mysite import app, db
from mysite.models import Wuser, User
from . import weibo
@weibo.route('/oauthreturn')
def | ():
code = request.args.get('code', '')
if code:
client = Client(app.config['API_KEY'], app.config['API_SECRET'], app.config['REDIRECT_URI'])
client.set_code(code)
uid = client.token['uid']
profile = client.get('users/show', access_token=client.access_token, uid=uid)
wuser = Wuser.query.filter_by(uid=uid)... | oauthreturn | identifier_name |
oauthreturn.py | from flask import request, render_template
from flask.ext.login import current_user, login_user
from mysite.weibo import Client
from mysite import app, db
from mysite.models import Wuser, User
from . import weibo
@weibo.route('/oauthreturn')
def oauthreturn():
| db.session.add(wuser)
db.session.commit()
return render_template("weibo/profile.html", wuser=wuser) | code = request.args.get('code', '')
if code:
client = Client(app.config['API_KEY'], app.config['API_SECRET'], app.config['REDIRECT_URI'])
client.set_code(code)
uid = client.token['uid']
profile = client.get('users/show', access_token=client.access_token, uid=uid)
wuser = Wuser.query.filter_by(uid=uid).firs... | identifier_body |
oauthreturn.py | from flask import request, render_template
from flask.ext.login import current_user, login_user
from mysite.weibo import Client
from mysite import app, db
from mysite.models import Wuser, User
from . import weibo
@weibo.route('/oauthreturn')
def oauthreturn():
code = request.args.get('code', '')
if code:
client = ... |
return render_template("weibo/profile.html", wuser=wuser) | random_line_split | |
oauthreturn.py | from flask import request, render_template
from flask.ext.login import current_user, login_user
from mysite.weibo import Client
from mysite import app, db
from mysite.models import Wuser, User
from . import weibo
@weibo.route('/oauthreturn')
def oauthreturn():
code = request.args.get('code', '')
if code:
client = ... |
wuser.update_access_token(client.token['access_token'])
wuser.update_profile(profile)
db.session.add(wuser)
db.session.commit()
return render_template("weibo/profile.html", wuser=wuser) | user = User()
wuser = Wuser(uid=uid)
wuser.user = user
db.session.add(user)
login_user(user) | conditional_block |
monitor-threaded.py | #!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# Copyright (c) 2010 Jean-Baptiste Denis.
#
# This is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License version 3 and superior as published by the Free
# Software Foundation.
#
# A copy of the license has been inclu... |
def close_write(self, path, is_dir):
""" callback called on a 'IN_CLOSE_WRITE' event """
_LOGGER.info("close_write: %s %s %s" % (path, is_dir, threading.current_thread().name))
def moved_from(self, path, is_dir):
""" callback called on a 'IN_MOVED_FROM' event """
_LOGGER.inf... | """ callback called on a 'IN_DELETE' event """
_LOGGER.info("delete: %s %s %s" % (path, is_dir, threading.current_thread().name)) | identifier_body |
monitor-threaded.py | #!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# Copyright (c) 2010 Jean-Baptiste Denis.
#
# This is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License version 3 and superior as published by the Free
# Software Foundation.
#
# A copy of the license has been inclu... |
def modify(self, path, is_dir):
""" callback called on a 'IN_MODIFY' event """
_LOGGER.info("modify: %s %s %s" % (path, is_dir, threading.current_thread().name))
def attrib(self, path, is_dir):
""" callback called on a 'IN_ATTRIB' event """
_LOGGER.info("attrib: %s %s %s" % (p... | """ callback called on a 'IN_MOVED_TO' event """
_LOGGER.info("moved_to: %s %s %s" % (path, is_dir, threading.current_thread().name))
| random_line_split |
monitor-threaded.py | #!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# Copyright (c) 2010 Jean-Baptiste Denis.
#
# This is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License version 3 and superior as published by the Free
# Software Foundation.
#
# A copy of the license has been inclu... | (self, path, is_dir):
""" callback called on a 'IN_MOVED_FROM' event """
_LOGGER.info("moved_from: %s %s %s" % (path, is_dir, threading.current_thread().name))
def moved_to(self, path, is_dir):
""" callback called on a 'IN_MOVED_TO' event """
_LOGGER.info("moved_to: %s %s %s" % (pa... | moved_from | identifier_name |
monitor-threaded.py | #!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# Copyright (c) 2010 Jean-Baptiste Denis.
#
# This is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License version 3 and superior as published by the Free
# Software Foundation.
#
# A copy of the license has been inclu... |
# we check if the provided string is a valid directory
path_to_watch = sys.argv[1]
if not os.path.isdir(path_to_watch):
print path_to_watch, "is not a valid directory."
sys.exit(2)
# We instanciate our callbacks object
callbacks = MonitorCallbacks()
# we get a source tree moni... | print "usage:", sys.argv[0], "directory"
sys.exit(1) | conditional_block |
game.py | #!/usr/bin/env python
#
# Copyright (C) 2007 Sascha Peilicke <sasch.pe@gmx.de>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later ... |
elif field == FIELD_MARKED_INVALID:
self.__level[row][col] = FIELD_INVALID
return self.__level[row][col]
def load(self,file=DEFAULT_LEVELPACK,skill=None):
"""Loads a level either from a zipped levelpack or from a textfile.
Parameters:
file - Can be a file path or zipped levelpack
skill - Desired ... | self.__level[row][col] = FIELD_MARKED_INVALID | conditional_block |
game.py | #!/usr/bin/env python
#
# Copyright (C) 2007 Sascha Peilicke <sasch.pe@gmx.de>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later ... | for file in zip.namelist():
if file.startswith('easy'):
candidates.append(file)
elif skill == SKILL_MEDIUM:
for file in zip.namelist():
if file.startswith('medium'):
candidates.append(file)
elif skill == SKILL_HARD:
for file in zip.namelist():
if file.startswith('har... | candidates = []
if skill == SKILL_EASY: | random_line_split |
game.py | #!/usr/bin/env python
#
# Copyright (C) 2007 Sascha Peilicke <sasch.pe@gmx.de>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later ... | (self, skill=None):
"""Creates a picross game.
Parameters:
skill - Desired skill level (None == random)
"""
self.__level = None
self.__name = None
self.__skill = None
self.__fieldsToOpen = 0
self.__fieldsOpened = 0
self.load(skill=skill)
#
# Miscellaneous methods
#
def _debug_print(self):
... | __init__ | identifier_name |
game.py | #!/usr/bin/env python
#
# Copyright (C) 2007 Sascha Peilicke <sasch.pe@gmx.de>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later ... |
def getColumnHint(self,col):
"""Returns the hint for a specific column.
"""
hint,count = [],0
for row in self.__level:
if row[col] == FIELD_VALID:
count += 1
else:
if count > 0:
hint.append(count)
count = 0
if count > 0:
hint.append(count)
if not hint:
hint.append(0)
ret... | """Returns the hint for a specific row.
"""
hint,count = [],0
for columnItem in self.__level[row]:
if columnItem == FIELD_VALID:
count += 1
else:
if count > 0:
hint.append(count)
count = 0
if count > 0:
hint.append(count)
if not hint:
hint.append(0)
return hint | identifier_body |
LayerListItem.tsx | /**
* Copyright © 2021 Rémi Pace.
* This file is part of Abc-Map.
*
* Abc-Map is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later vers... | xtends Component<Props, {}> {
public render(): ReactNode {
const meta = this.props.metadata;
const selectedClass = meta.active ? Cls.active : '';
const dataLayer = meta.active ? 'active' : `inactive`;
const icon = meta.visible ? 'fa-eye' : 'fa-eye-slash';
return (
<div onClick={() => this.pr... | yerListItem e | identifier_name |
LayerListItem.tsx | /**
* Copyright © 2021 Rémi Pace.
* This file is part of Abc-Map.
*
* Abc-Map is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of | * Abc-Map is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General
* Publi... | * the License, or (at your option) any later version.
* | random_line_split |
GenericList.js | Ext.define('Category.view.GenericList', {
extend: 'Ext.grid.Panel',
alias: 'widget.genericlist',
store: 'Generic',
title: Raptor.getTag('category_header'),
iconCls:'',
initComponent: function() {
this.columns = [{
header:Raptor.getTag('category_name'),
da... | xtype: 'button',
text: Raptor.getTag('delete'),
disabled:true,
privilegeName:'delete/:id',
action:'deleteAction',
iconCls:'icon-del'
}]
}];
this.callParent();
}
}); | },{ | random_line_split |
write_vectored.rs | use crate::io::AsyncWrite;
use futures_core::future::Future;
use futures_core::task::{Context, Poll};
use std::io::{self, IoSlice};
use std::pin::Pin;
/// Future for the [`write_vectored`](super::AsyncWriteExt::write_vectored) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]... | <'a, 'b, W: ?Sized> {
writer: &'a mut W,
bufs: &'a [IoSlice<'b>],
}
impl<W: ?Sized + Unpin> Unpin for WriteVectored<'_, '_, W> {}
impl<'a, 'b, W: AsyncWrite + ?Sized + Unpin> WriteVectored<'a, 'b, W> {
pub(super) fn new(writer: &'a mut W, bufs: &'a [IoSlice<'b>]) -> Self {
Self { writer, bufs }
... | WriteVectored | identifier_name |
write_vectored.rs | use crate::io::AsyncWrite;
use futures_core::future::Future;
use futures_core::task::{Context, Poll};
use std::io::{self, IoSlice};
use std::pin::Pin;
/// Future for the [`write_vectored`](super::AsyncWriteExt::write_vectored) method.
#[derive(Debug)] | #[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct WriteVectored<'a, 'b, W: ?Sized> {
writer: &'a mut W,
bufs: &'a [IoSlice<'b>],
}
impl<W: ?Sized + Unpin> Unpin for WriteVectored<'_, '_, W> {}
impl<'a, 'b, W: AsyncWrite + ?Sized + Unpin> WriteVectored<'a, 'b, W> {
pub(super) f... | random_line_split | |
write_vectored.rs | use crate::io::AsyncWrite;
use futures_core::future::Future;
use futures_core::task::{Context, Poll};
use std::io::{self, IoSlice};
use std::pin::Pin;
/// Future for the [`write_vectored`](super::AsyncWriteExt::write_vectored) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]... |
}
impl<W: AsyncWrite + ?Sized + Unpin> Future for WriteVectored<'_, '_, W> {
type Output = io::Result<usize>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = &mut *self;
Pin::new(&mut this.writer).poll_write_vectored(cx, this.bufs)
}
}
| {
Self { writer, bufs }
} | identifier_body |
kegg.js | var ld = this;
var img = new Image();
img.src = img_src;
img.onload = function(){
ld.width = img.width;
ld.height = img.height;
console.log("loaded img", ld.width, ld.height);
ld.svg = kgml;
console.log('width', ld.width, 'height', ld.height);
ld.svg = ld.svg
... | var img_src_s = kgml.indexOf('image=');
var img_src_e = kgml.indexOf('"', img_src_s+7);
var img_src = kgml.substring(img_src_s+7, img_src_e);
| random_line_split | |
kegg.js | .33 .33 0 0 \n' +
'\t\t .33 .33 .33 0 0 \n' +
'\t\t .33 .33 .33 0 0\n' +
'\t\t 0 0 0 1 0"/>\n' +
'\t\t</filter>\n' +
'\t\t<filter id="matrix-invert">\n' +
'\t\t\t<feColorMatrix in="SourceGraphic" type="matrix" values="-1 0 0 0 1 \n'... | {
var r = pixels.data[i];
var g = pixels.data[i+1];
var b = pixels.data[i+2];
// if the pixel matches our transparent color, set alpha to 0
if(r == transparentColor.r && g == transparentColor.g && b == transparentColor.b){
pixels.data[i+3] = 0;
}
} | conditional_block | |
kegg.js |
var kgml_to_svg = function kgml_to_svg(kgml, c_id, clbk) {
this.kgml = kgml;
this.c_id = c_id;
this.tagNames = {"rect": 1, "circle": 1};
var fill_opacity = '0.0';
var img_src_s = kgml.indexOf('image=');
var img_src_e = kgml.indexOf('"', img_src_s+7);
var img_src = kgml.substring(... | {
if (!(key in obj)) { obj[key] = [ val ]; } else { if (obj[key].indexOf(val) == -1) { obj[key].push( val ) } }
} | identifier_body | |
kegg.js | ="matrix" values="0 0 0 0 0\n' +
'\t\t\t 0 0 0 0 0\n' +
'\t\t\t 0 0 0 0 0\n' +
'\t\t\t -1 -1 -1 1 0"/>\n' +
'\t\t</filter>\n' +
'\t\t<filter id="saturate">\n' +
'\t\t\t<feColorMatrix in="SourceGraphic" type="saturate" values... | make_transparency | identifier_name | |
htmlbodyelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrHelpers};
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull... |
}
pub trait HTMLBodyElementHelpers {
fn get_background_color(&self) -> Option<RGBA>;
}
impl HTMLBodyElementHelpers for HTMLBodyElement {
fn get_background_color(&self) -> Option<RGBA> {
self.background_color.get()
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLBodyElement> {
fn super_type<'b>... | {
let win = window_from_node(self).root();
win.r().SetOnunload(listener)
} | identifier_body |
htmlbodyelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrHelpers};
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull... | (&self, attr: JSRef<Attr>) {
match self.super_type() {
Some(ref s) => s.before_remove_attr(attr),
_ => {}
}
match attr.local_name() {
&atom!("bgcolor") => self.background_color.set(None),
_ => {}
}
}
}
| before_remove_attr | identifier_name |
htmlbodyelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrHelpers};
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull... | window.r().reflector().get_jsobject());
let evtarget: JSRef<EventTarget> =
if FORWARDED_EVENTS.iter().any(|&event| &**name == event) {
EventTargetCast::from_ref(window.r())
} else {
EventTargetCas... | window.r().get_url(), | random_line_split |
htmlbodyelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrHelpers};
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull... | ;
evtarget.set_event_handler_uncompiled(cx, url, reflector,
&name[2..],
(**attr.value()).to_owned());
}
match attr.local_name() {
&atom!("bgcolor") => {
self.backg... | {
EventTargetCast::from_ref(*self)
} | conditional_block |
__init__.py | # -*- coding: utf-8 -*-
##############################################################################
# | #
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it wil... | # OpenERP, Open Source Management Solution
# Copyright (c) 2013 ErpAndCloud All Rights Reserved
# https://github.com/jmesteve
# <engineering@erpandcloud.com> | random_line_split |
wizard_report.py | implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
################################... | action=self._get_action_report_to_return(cr, uid, ids, intervent_ids, report_name, title, context=context)
action['report_type']='pdf'
action['model']=model
id_report = printsock.report(db, uid, pwd, report_name, interve... | #self._get_action_report_to_return(cr, uid, ids, intervent_ids, report_name, title, context=context)
if intervent_ids: | random_line_split |
wizard_report.py | implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
################################... | file_pdf.close()
return False
def print_intervent_report(self, cr, uid, ids, context=None):
''' With filter parameter select all intervent searched
Create data element to call after the aeroo report
'''
if context is None:
co... | action=self._get_action_report_to_return(cr, uid, ids, intervent_ids, report_name, title, context=context)
action['report_type']='pdf'
action['model']=model
id_report = printsock.report(db, uid, pwd, report_name, intervent_ids, action)#ids ... | conditional_block |
wizard_report.py | implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
################################... | (self, group_by):
''' Return report parameter: (report_name, title, order)
according to group_by clause passed
'''
if group_by == 'state': # group state
return ("intervent_report_state", "Intervent report list (group by state)", "partner_id,ref,date_star... | _get_report_parameter_for_action | identifier_name |
wizard_report.py | implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
################################... |
def _get_filter_from_wizard(self, cr, uid, ids, with_partner=True, context=None):
''' In wizard passed get the filter selected in normal domain format
the with_partner parameter is used for parametrize this function
for filter report or for load all partner of the f... | ''' Compose action to return according to passed: intervent_ids, report_name, title
'''
datas = {'ids': intervent_ids,}
datas['model'] = 'intervention.report'
datas['form'] = self.read(cr, uid, ids)[0]
datas['title']= title
# return action:
retur... | identifier_body |
CeleryConstants.py |
# encoding: utf-8
__author__ = "Nils Tobias Schmidt"
__email__ = "schmidt89 at informatik.uni-marburg.de"
'''
Holds some constants/settings related to celery.
'''
from androlyze.settings import *
############################################################
#---Max retry wait time
##################################... | ():
from androlyze.analyze.distributed.tasks.AnalyzeTask import AnalyzeTask
return AnalyzeTask.name
| get_analyze_task_name | identifier_name |
CeleryConstants.py | # encoding: utf-8
__author__ = "Nils Tobias Schmidt"
__email__ = "schmidt89 at informatik.uni-marburg.de"
'''
Holds some constants/settings related to celery.
'''
from androlyze.settings import *
############################################################
#---Max retry wait time
###################################... | CELERY_RESULT_BACKEND_KEY_TRACEBACK = "traceback"
CELERY_RESULT_BACKEND_KEY_STATUS = "status"
############################################################
#---Other
############################################################
# value for retrying until success
CELERY_RETRY_INFINITE = None
def get_analyze_task_name()... | ############################################################
CELERY_RESULT_BACKEND_KEY_RESULT = "result" | random_line_split |
CeleryConstants.py |
# encoding: utf-8
__author__ = "Nils Tobias Schmidt"
__email__ = "schmidt89 at informatik.uni-marburg.de"
'''
Holds some constants/settings related to celery.
'''
from androlyze.settings import *
############################################################
#---Max retry wait time
##################################... | from androlyze.analyze.distributed.tasks.AnalyzeTask import AnalyzeTask
return AnalyzeTask.name | identifier_body | |
prng.rs | use core::usize;
use rng::Rng;
// https://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use
#[cfg(target_pointer_width = "32")]
pub const OFFSET: usize = 1013904223;
#[cfg(target_pointer_width = "32")]
pub const MULTIPLIER: usize = 1664525;
#[cfg(target_pointer_width = "64")]
pub const OF... | (&mut self, seed: usize) {
self.seed = seed;
}
}
impl Rng for Prng {
// http://indiegamr.com/generate-repeatable-random-numbers-in-js/
#[inline]
fn next(&mut self) -> usize {
self.seed = ((MULTIPLIER.wrapping_mul(self.seed)).wrapping_add(OFFSET)) % MAX;
self.seed
}
}
| set_seed | identifier_name |
prng.rs | use core::usize;
use rng::Rng;
// https://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use
#[cfg(target_pointer_width = "32")]
pub const OFFSET: usize = 1013904223;
#[cfg(target_pointer_width = "32")]
pub const MULTIPLIER: usize = 1664525;
#[cfg(target_pointer_width = "64")]
pub const OF... |
}
impl Rng for Prng {
// http://indiegamr.com/generate-repeatable-random-numbers-in-js/
#[inline]
fn next(&mut self) -> usize {
self.seed = ((MULTIPLIER.wrapping_mul(self.seed)).wrapping_add(OFFSET)) % MAX;
self.seed
}
}
| {
self.seed = seed;
} | identifier_body |
prng.rs | use core::usize;
use rng::Rng;
// https://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use
#[cfg(target_pointer_width = "32")]
pub const OFFSET: usize = 1013904223;
#[cfg(target_pointer_width = "32")]
pub const MULTIPLIER: usize = 1664525;
#[cfg(target_pointer_width = "64")]
pub const OF... | pub const MAX: usize = usize::MAX as usize;
pub struct Prng {
seed: usize,
}
impl Prng {
#[inline]
pub fn new() -> Self {
Prng {
// get a value for initial seed
seed: &false as *const _ as usize,
}
}
#[inline]
pub fn seed(&self) -> usize { self.seed }
... | #[cfg(target_pointer_width = "64")]
pub const MULTIPLIER: usize = 6364136223846793005;
| random_line_split |
step1_controller.js | /**
* 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... | name: 'wizardStep1Controller'
}); | random_line_split | |
state.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
declare_test!{GeneralStateTest_stAttackTest, "GeneralStateTests/stAttackTest/"}
declare_test!{GeneralStateTest_stBadOpcodeTest, "GeneralStateTests/stBadOpcode/"}
declare_test!{GeneralStateTest_stCallCodes, "GeneralStateTests/stCallCodes/"}
declare_test!{GeneralStateTest_stCallDelegateCodesCallCodeHomestead, "Gene... | {
json_chain_test(json_data)
} | identifier_body |
state.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | let transaction: SignedTransaction = multitransaction.select(&state.indexes).into();
let result = || -> Result<_, EvmTestError> {
Ok(EvmTestClient::from_pod_state(spec, pre.clone())?
.transact(&env, transaction, trace::NoopVMTracer))
};
match result() {
Err(err) => {
print... | random_line_split | |
state.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | (json_data: &[u8]) -> Vec<String> {
json_chain_test(json_data)
}
declare_test!{GeneralStateTest_stAttackTest, "GeneralStateTests/stAttackTest/"}
declare_test!{GeneralStateTest_stBadOpcodeTest, "GeneralStateTests/stBadOpcode/"}
declare_test!{GeneralStateTest_stCallCodes, "GeneralStateTests/stCallCodes/"}
declare... | do_json_test | identifier_name |
react-notification-system-tests.tsx | import * as React from 'react';
import * as NotificationSystem from 'react-notification-system';
class MyComponent extends React.Component<any, any> {
private notificationSystem: NotificationSystem.System = null;
private notification: NotificationSystem.Notification = {
title: 'Notification title',
... | }
};
private addNotification() {
this.notification = this.notificationSystem.addNotification(this.notification);
}
componentDidMount() {
this.addNotification();
}
render() {
const style: NotificationSystem.Style = {
NotificationItem: { // Override ... | random_line_split | |
react-notification-system-tests.tsx | import * as React from 'react';
import * as NotificationSystem from 'react-notification-system';
class MyComponent extends React.Component<any, any> {
private notificationSystem: NotificationSystem.System = null;
private notification: NotificationSystem.Notification = {
title: 'Notification title',
... |
render() {
const style: NotificationSystem.Style = {
NotificationItem: { // Override the notification item
DefaultStyle: { // Applied to every notification, regardless of the notification level
margin: '10px 5px 2px 1px'
},
... | {
this.addNotification();
} | identifier_body |
react-notification-system-tests.tsx | import * as React from 'react';
import * as NotificationSystem from 'react-notification-system';
class MyComponent extends React.Component<any, any> {
private notificationSystem: NotificationSystem.System = null;
private notification: NotificationSystem.Notification = {
title: 'Notification title',
... | () {
this.notification = this.notificationSystem.addNotification(this.notification);
}
componentDidMount() {
this.addNotification();
}
render() {
const style: NotificationSystem.Style = {
NotificationItem: { // Override the notification item
Default... | addNotification | identifier_name |
lib.rs | n > 0.0
}
/// Determine whether a number is a pentagonal number
pub fn | (p: u64) -> bool {
let n = (1.0 + (1.0 + 24.0*(p as f64)).sqrt()) / 6.0;
n == n.floor()
}
/// Determine whether a number is a hexagonal number
pub fn is_hexagonal(p: u64) -> bool {
let n = (1.0 + (1.0 + 8.0*(p as f64)).sqrt()) / 4.0;
n == n.floor()
}
/// Determine whether a number is prime
pub fn is_p... | is_pentagonal | identifier_name |
lib.rs |
/// Determine whether a number is a pentagonal number
pub fn is_pentagonal(p: u64) -> bool {
let n = (1.0 + (1.0 + 24.0*(p as f64)).sqrt()) / 6.0;
n == n.floor()
}
/// Determine whether a number is a hexagonal number
pub fn is_hexagonal(p: u64) -> bool {
let n = (1.0 + (1.0 + 8.0*(p as f64)).sqrt()) / 4.0... | /// Determine whether a number is a triangular number
pub fn is_triangular(p: u64) -> bool {
let n = (-1.0 + (1.0 + 8.0*(p as f64)).sqrt()) / 2.0;
n == n.floor() && n > 0.0
} | random_line_split | |
lib.rs |
/// Determine whether a number is a pentagonal number
pub fn is_pentagonal(p: u64) -> bool {
let n = (1.0 + (1.0 + 24.0*(p as f64)).sqrt()) / 6.0;
n == n.floor()
}
/// Determine whether a number is a hexagonal number
pub fn is_hexagonal(p: u64) -> bool {
let n = (1.0 + (1.0 + 8.0*(p as f64)).sqrt()) / 4.... | {
let n = (-1.0 + (1.0 + 8.0*(p as f64)).sqrt()) / 2.0;
n == n.floor() && n > 0.0
} | identifier_body | |
lib.rs | n > 0.0
}
/// Determine whether a number is a pentagonal number
pub fn is_pentagonal(p: u64) -> bool {
let n = (1.0 + (1.0 + 24.0*(p as f64)).sqrt()) / 6.0;
n == n.floor()
}
/// Determine whether a number is a hexagonal number
pub fn is_hexagonal(p: u64) -> bool {
let n = (1.0 + (1.0 + 8.0*(p as f64)).sq... |
digits[d as usize] = true;
value *= 10;
}
for i in l..(k + 1) {
if !digits[i as usize] {
return false;
}
}
for i in 0..l {
if digits[i as usize] {
return false;
}
}
true
}
#[cfg(test)]
mod tests {
use super::*;
use... | {
return false;
} | conditional_block |
resolution.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Resolution values:
//!
//! https://drafts.csswg.org/css-values/#resolution
use std::fmt::{self, Write};
use s... | (CSSFloat);
impl Resolution {
/// Returns this resolution value as dppx.
#[inline]
pub fn dppx(&self) -> CSSFloat {
self.0
}
}
impl ToComputedValue for specified::Resolution {
type ComputedValue = Resolution;
#[inline]
fn to_computed_value(&self, _: &Context) -> Self::ComputedValu... | Resolution | identifier_name |
resolution.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Resolution values:
//!
//! https://drafts.csswg.org/css-values/#resolution
use std::fmt::{self, Write};
use s... |
}
impl ToComputedValue for specified::Resolution {
type ComputedValue = Resolution;
#[inline]
fn to_computed_value(&self, _: &Context) -> Self::ComputedValue {
Resolution(self.to_dppx())
}
#[inline]
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
specified::R... | {
self.0
} | identifier_body |
resolution.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Resolution values:
//!
//! https://drafts.csswg.org/css-values/#resolution
use std::fmt::{self, Write};
use s... | impl ToComputedValue for specified::Resolution {
type ComputedValue = Resolution;
#[inline]
fn to_computed_value(&self, _: &Context) -> Self::ComputedValue {
Resolution(self.to_dppx())
}
#[inline]
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
specified::Resol... | self.0
}
}
| random_line_split |
fixi.rs | use {
fixity::{
fixity::Builder,
path::Path,
value::{Key, Value},
Config, Fixity,
},
std::path::PathBuf,
structopt::StructOpt,
};
#[derive(Debug, StructOpt)]
#[structopt(name = "fixi", about = "fixity content management")]
struct Opt {
#[structopt(flatten)]
fixi_... | (fixi: Fixity, path: Path) -> Result<(), Error> {
let stdout = tokio::io::stdout();
let bytes = fixi.bytes(path)?;
let _ = bytes.read(stdout).await?;
Ok(())
}
async fn cmd_bytes_put(fixi: Fixity, path: Path, commit: bool) -> Result<(), Error> {
if path.len() == 0 {
return Err(Error::User(
... | cmd_bytes_get | identifier_name |
fixi.rs | use {
fixity::{
fixity::Builder,
path::Path,
value::{Key, Value},
Config, Fixity,
},
std::path::PathBuf,
structopt::StructOpt,
};
#[derive(Debug, StructOpt)]
#[structopt(name = "fixi", about = "fixity content management")]
struct Opt {
#[structopt(flatten)]
fixi_... | Ls {
#[structopt(short = "s", long = "start", parse(try_from_str = Key::from_cli_str))]
start: Option<Key>,
#[structopt(short = "e", long = "end", parse(try_from_str = Key::from_cli_str))]
end: Option<Key>,
},
}
async fn cmd_map(fixi: Fixity, path: Path, subcmd: MapSubcmd) -> Res... | value: Value,
}, | random_line_split |
fixi.rs | use {
fixity::{
fixity::Builder,
path::Path,
value::{Key, Value},
Config, Fixity,
},
std::path::PathBuf,
structopt::StructOpt,
};
#[derive(Debug, StructOpt)]
#[structopt(name = "fixi", about = "fixity content management")]
struct Opt {
#[structopt(flatten)]
fixi_... | let stdin = tokio::io::stdin();
let bytes = fixi.bytes(path)?;
let _ = bytes.write(stdin).await?;
if commit {
let addr = bytes.commit().await?;
println!("{:?}", addr);
} else {
println!("bytes staged");
}
Ok(())
}
| {
if path.len() == 0 {
return Err(Error::User(
"cannot get/put bytes to root of fixity repository".to_owned(),
));
}
// TODO: tokio docs recommend against this for interactive uses[1], so this
// should be fixed eventually - when interactivity is prioritized a bit more.
/... | identifier_body |
system_dic.py | # Copyright 2022 moco_beta
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... | UnknownsDictionary.__init__(self, chardefs, unknowns) | MMapDictionary.__init__(self, mmap_entries[0], mmap_entries[1], mmap_entries[2], connections) | random_line_split |
system_dic.py | # Copyright 2022 moco_beta
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... | """
MMap System dictionary class
"""
__INSTANCE = None
__lock = threading.Lock()
@classmethod
def instance(cls):
if not cls.__INSTANCE:
with cls.__lock:
if not cls.__INSTANCE:
cls.__INSTANCE = MMapSystemDictionary(mmap_entries(), connecti... | identifier_body | |
system_dic.py | # Copyright 2022 moco_beta
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... |
return cls.__INSTANCE
def __init__(self, mmap_entries, connections, chardefs, unknowns):
MMapDictionary.__init__(self, mmap_entries[0], mmap_entries[1], mmap_entries[2], connections)
UnknownsDictionary.__init__(self, chardefs, unknowns)
| with cls.__lock:
if not cls.__INSTANCE:
cls.__INSTANCE = MMapSystemDictionary(mmap_entries(), connections, chardef.DATA, unknowns.DATA) | conditional_block |
system_dic.py | # Copyright 2022 moco_beta
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... | (cls):
if not cls.__INSTANCE:
with cls.__lock:
if not cls.__INSTANCE:
cls.__INSTANCE = SystemDictionary(entries(), connections, chardef.DATA, unknowns.DATA)
return cls.__INSTANCE
def __init__(self, entries, connections, chardefs, unknowns):
RA... | instance | identifier_name |
webtest_tests.py | from unittest import TestCase
from webtest import TestApp
from nose.tools import * # noqa
from ..main import app
class TestAUser(TestCase):
def setUp(self):
self.app = TestApp(app)
def tearDown(self):
pass
def test_can_see_homepage(self):
# Goes to homepage
res = self.ap... | def test_can_see_a_page(self):
# Goes to homepage
res = self.app.get('')
# Sees titles for a page
assert_in('install Python', res)
# Clicks on a title
res = res.click('install Python 2 and/or 3')
assert_equal(res.status_code, 200)
# Is at the page
... | assert_in("All I want to do is", res)
| random_line_split |
webtest_tests.py | from unittest import TestCase
from webtest import TestApp
from nose.tools import * # noqa
from ..main import app
class TestAUser(TestCase):
def setUp(self):
self.app = TestApp(app)
def tearDown(self):
pass
def test_can_see_homepage(self):
# Goes to homepage
res = self.ap... |
def test_can_see_deps(self):
# Goes to homepage
res = self.app.get('')
# Clicks on a page
res = res.click('install Python 2 and/or 3')
# The page has dependency
# The dependency titles are listed
assert_in("install-homebrew", res)
# Clicks on the dep... | res = self.app.get('')
# Sees titles for a page
assert_in('install Python', res)
# Clicks on a title
res = res.click('install Python 2 and/or 3')
assert_equal(res.status_code, 200)
# Is at the page
# Can see the title
assert_in("Install Python", res)
... | identifier_body |
webtest_tests.py | from unittest import TestCase
from webtest import TestApp
from nose.tools import * # noqa
from ..main import app
class TestAUser(TestCase):
def | (self):
self.app = TestApp(app)
def tearDown(self):
pass
def test_can_see_homepage(self):
# Goes to homepage
res = self.app.get('')
assert_equal(res.status_code, 200)
assert_in("All I want to do is", res)
def test_can_see_a_page(self):
# Goes to hom... | setUp | identifier_name |
gulpfile.js | /*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.gi... | var elements = gulp.src(['app/elements/**/*.html'])
.pipe(gulp.dest('dist/elements'));
var swBootstrap = gulp.src(['bower_components/platinum-sw/bootstrap/*.js'])
.pipe(gulp.dest('dist/elements/bootstrap'));
var swToolbox = gulp.src(['bower_components/sw-toolbox/*.js'])
.pipe(gulp.dest('dist/sw-tool... | 'bower_components/**/*'
]).pipe(gulp.dest('dist/bower_components'));
| random_line_split |
gulpfile.js | /*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.gi... |
});
});
// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));
// Watch Files For Changes & Reload
//gulp.task('serve', ['styles', 'elements', 'images'], function () {
gulp.task('serve', ['styles', 'elements'], function () {
browserSync({
notify: false,
// Run as an https by unco... | {
files.push('index.html', './', 'bower_components/webcomponentsjs/webcomponents.min.js');
var filePath = path.join(dir, 'precache.json');
fs.writeFile(filePath, JSON.stringify(files), callback);
} | conditional_block |
AccountTabList.tsx | import '../../styles/content-pane-fade.less';
import './styles/accounts.less';
import * as React from 'react';
import { Route, Switch, RouteComponentProps, withRouter } from 'react-router';
import { NavLink } from 'react-router-dom';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import Consta... | interface AccountTabListRouterParams {
account: string;
}
interface AccountTabListProps extends RouteComponentProps<AccountTabListRouterParams> {
loading: boolean;
accounts: Account[];
loadAccounts: (id: number) => void;
}
class AccountTabList extends React.Component<AccountTabListProps> {
componentWillMou... | random_line_split | |
AccountTabList.tsx | import '../../styles/content-pane-fade.less';
import './styles/accounts.less';
import * as React from 'react';
import { Route, Switch, RouteComponentProps, withRouter } from 'react-router';
import { NavLink } from 'react-router-dom';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import Consta... |
buildAccountPreview(account: Account) {
let linkTarget = `${Constants.ROUTES.accounts}/${account.id}`;
return (
<li key={account.id} id={`accounts-list-id-${account.id}`}>
<NavLink to={linkTarget} activeClassName="active" isActive={() => account.id === Number(this.props.match.params.account) ... | {
this.updateAccountList(-1);
} | identifier_body |
AccountTabList.tsx | import '../../styles/content-pane-fade.less';
import './styles/accounts.less';
import * as React from 'react';
import { Route, Switch, RouteComponentProps, withRouter } from 'react-router';
import { NavLink } from 'react-router-dom';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import Consta... | () {
this.updateAccountList(-1);
}
buildAccountPreview(account: Account) {
let linkTarget = `${Constants.ROUTES.accounts}/${account.id}`;
return (
<li key={account.id} id={`accounts-list-id-${account.id}`}>
<NavLink to={linkTarget} activeClassName="active" isActive={() => account.id === ... | componentWillMount | identifier_name |
interalSimpleDownloader.py | selfAddon = xbmcaddon.Addon(id=addon_id)
__addonname__ = selfAddon.getAddonInfo('name')
__icon__ = selfAddon.getAddonInfo('icon')
downloadPath = xbmc.translatePath(selfAddon.getAddonInfo('profile'))#selfAddon["profile"])
#F4Mversion=''
class interalSimpleDownloader():
outputfile =''
clientHeader... |
def MD5(self,data):
m = hashlib.md5()
m.update(data)
return m.digest()
def makeToken(self,sessionID,swfUrl):
swfData = self.getURL(swfUrl)
decData = self.decompressSWF(swf | if type(f) is str:
f = StringIO(f)
f.seek(0, 0)
magic = f.read(3)
if magic == "CWS":
return "FWS" + f.read(5) + zlib.decompress(f.read())
elif magic == "FWS":
#SWF Not Compressed
f.seek(0, 0)
return f.read()
else:
... | identifier_body |
interalSimpleDownloader.py | def __init__(self):
self.init_done=False
def thisme(self):
return 'aaaa'
def openUrl(self,url, ischunkDownloading=False):
try:
post=None
openner = urllib2.build_opener(urllib2.HTTPHandler, urllib2.HTTPSHandler)
if post:
req = urll... | random_line_split | ||
interalSimpleDownloader.py | selfAddon = xbmcaddon.Addon(id=addon_id)
__addonname__ = selfAddon.getAddonInfo('name')
__icon__ = selfAddon.getAddonInfo('icon')
downloadPath = xbmc.translatePath(selfAddon.getAddonInfo('profile'))#selfAddon["profile"])
#F4Mversion=''
class interalSimpleDownloader():
outputfile =''
clientHeader... | (self,url,dest_stream):
try:
url=self.url
fileout=dest_stream
self.status='bootstrap done'
while True:
response=self.openUrl(url)
buf="start"
firstBlock=True
try:
... | downloadInternal | identifier_name |
interalSimpleDownloader.py | selfAddon = xbmcaddon.Addon(id=addon_id)
__addonname__ = selfAddon.getAddonInfo('name')
__icon__ = selfAddon.getAddonInfo('icon')
downloadPath = xbmc.translatePath(selfAddon.getAddonInfo('profile'))#selfAddon["profile"])
#F4Mversion=''
class interalSimpleDownloader():
outputfile =''
clientHeader... |
else:
req = urllib2.Request(url)
ua_header=False
if self.clientHeader:
for n,v in self.clientHeader:
req.add_header(n,v)
if n=='User-Agent':
ua_header=True
if no... | req = urllib2.Request(url, post) | conditional_block |
DerivedFields.test.tsx | import React from 'react';
import { mount } from 'enzyme';
import { DerivedFields } from './DerivedFields';
import { Button } from '@grafana/ui';
import { DerivedField } from './DerivedField';
import { act } from 'react-dom/test-utils';
describe('DerivedFields', () => {
let originalGetSelection: typeof window.getSel... | expect(newValue[0]).toMatchObject({
matcherRegex: 'regex2',
name: 'test2',
url: 'localhost2',
});
});
});
const testValue = [
{
matcherRegex: 'regex1',
name: 'test1',
url: 'localhost1',
},
{
matcherRegex: 'regex2',
name: 'test2',
url: 'localhost2',
},
]; | removeButton.simulate('click');
const newValue = onChangeMock.mock.calls[0][0];
expect(newValue.length).toBe(1); | random_line_split |
component-helpers.ts | export interface DragDelta {
x: number
y: number
}
let targets: HTMLElement[] = []
export function getDragDeltas ( | ) {
let oldX = 0
let oldY = 0
let target: HTMLElement
function onmousedown (e: MouseEvent) {
target = e.currentTarget as HTMLElement
targets.push(target)
oldX = e.clientX
oldY = e.clientY
document.addEventListener('mousemove', onMouseMove)
document.addEventListener('mouseup', onMouseUp)
onMouseDown &... | onDragDelta: (d: DragDelta) => void,
onMouseDown?: (e?: MouseEvent) => void | random_line_split |
component-helpers.ts | export interface DragDelta {
x: number
y: number
}
let targets: HTMLElement[] = []
export function getDragDeltas (
onDragDelta: (d: DragDelta) => void,
onMouseDown?: (e?: MouseEvent) => void
) {
let oldX = 0
let oldY = 0
let target: HTMLElement
function | (e: MouseEvent) {
target = e.currentTarget as HTMLElement
targets.push(target)
oldX = e.clientX
oldY = e.clientY
document.addEventListener('mousemove', onMouseMove)
document.addEventListener('mouseup', onMouseUp)
onMouseDown && onMouseDown(e)
}
function onMouseUp () {
document.removeEventListener('m... | onmousedown | identifier_name |
component-helpers.ts | export interface DragDelta {
x: number
y: number
}
let targets: HTMLElement[] = []
export function getDragDeltas (
onDragDelta: (d: DragDelta) => void,
onMouseDown?: (e?: MouseEvent) => void
) {
let oldX = 0
let oldY = 0
let target: HTMLElement
function onmousedown (e: MouseEvent) |
function onMouseUp () {
document.removeEventListener('mousemove', onMouseMove)
document.removeEventListener('mouseup', onMouseUp)
targets = targets.filter(t => t !== target)
}
function onMouseMove (e: MouseEvent) {
for (const t of targets) {
if (t !== target && target.contains(t)) return
}
onDragDe... | {
target = e.currentTarget as HTMLElement
targets.push(target)
oldX = e.clientX
oldY = e.clientY
document.addEventListener('mousemove', onMouseMove)
document.addEventListener('mouseup', onMouseUp)
onMouseDown && onMouseDown(e)
} | identifier_body |
editor_plugin_src.js | /**
* $Id: editor_plugin_src.js,v 1.1 2012/11/16 23:22:25 delara Exp $
*
* @author Moxiecode
* @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved.
*/
(function() {
tinymce.create('tinymce.plugins.Preview', {
init : function(ed, url) {
var t = this;
t.editor = ed;
ed.addComma... | return ed.documentBaseURI.toAbsolute(u);
});
if (pos != -1) {
pos = c.indexOf('>', pos);
pos2 = c.lastIndexOf('</body>');
c = c.substring(pos + 1, pos2);
}
html += ed.getParam('doctype');
html += '<html xmlns="http://www.w3.org/1999/xhtml">';
html += '<head>';
html += '... | pos = c.indexOf('<body');
css = ed.getParam("content_css", '').split(',');
tinymce.map(css, function(u) { | random_line_split |
editor_plugin_src.js | /**
* $Id: editor_plugin_src.js,v 1.1 2012/11/16 23:22:25 delara Exp $
*
* @author Moxiecode
* @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved.
*/
(function() {
tinymce.create('tinymce.plugins.Preview', {
init : function(ed, url) {
var t = this;
t.editor = ed;
ed.addComma... |
for (i=0; i<el.length; i++) {
ne = d.createElement("div");
ne.innerHTML = d._embeds[i];
el[i].parentNode.insertBefore(ne.firstChild, el[i]);
}
},
_writeFlash : function(p) {
p.src = this.editor.documentBaseURI.toAbsolute(p.src);
TinyMCE_PreviewPlugin._writeEmbed(
'D27CDB6E-AE6D-11cf-96... |
sv = tinymce.isIE ? nl[i].innerHTML : nl[i].firstChild.nodeValue;
if (new RegExp('write(Flash|ShockWave|WindowsMedia|QuickTime|RealMedia)\\(.*', 'g').test(sv))
el[el.length] = nl[i];
}
| conditional_block |
nl-SR.js | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
glo... | (n) {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0) return 1;
return 5;
}
root.ng.common.locales['nl-sr'] = [
'nl-SR',
[['a.m.', 'p.m.'], u, u],
u,
[
['Z', 'M', 'D', 'W', 'D', 'V', 'Z'], ['zo', 'ma', 'di', 'wo', 'do', 'vr... | plural | identifier_name |
nl-SR.js | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
glo... | ['dd-MM-y', 'd MMM y', 'd MMMM y', 'EEEE d MMMM y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'],
['{1} {0}', u, '{1} \'om\' {0}', u],
[',', '.', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤ #,##0.00;¤ -#,##0.00', '#E0'],
'$',
'Surinaamse dollar',
... | 1,
[6, 0], | random_line_split |
nl-SR.js | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
glo... |
root.ng.common.locales['nl-sr'] = [
'nl-SR',
[['a.m.', 'p.m.'], u, u],
u,
[
['Z', 'M', 'D', 'W', 'D', 'V', 'Z'], ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'],
['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'],
['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za']
... | {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0) return 1;
return 5;
} | identifier_body |
subscription.rs | //! Helper types for converting types to `Result<T, FieldError<E>>`.
//!
//! Used in `#[graphql_subscription]` macros to convert result type aliases on
//! subscription handlers to a concrete return type.
use futures::Stream;
use crate::{FieldError, GraphQLValue, IntoFieldError, ScalarValue};
/// Trait for wrapping ... | ;
/// This trait is used in `juniper::graphql_subscription` macro to get stream's
/// item type that implements `GraphQLValue` from type alias provided
/// by user.
pub trait ExtractTypeFromStream<T, S>
where
S: ScalarValue,
{
/// Stream's return Value that will be returned if
/// no errors occured. Is use... | ResultStreamResult | identifier_name |
subscription.rs | //! Helper types for converting types to `Result<T, FieldError<E>>`.
//!
//! Used in `#[graphql_subscription]` macros to convert result type aliases on
//! subscription handlers to a concrete return type.
use futures::Stream;
use crate::{FieldError, GraphQLValue, IntoFieldError, ScalarValue};
/// Trait for wrapping ... | /// of values.
pub struct StreamItem;
/// This struct is used in `ExtractTypeFromStream` implementation for results
/// with streams of values inside.
pub struct StreamResult;
/// This struct is used in `ExtractTypeFromStream` implementation for streams
/// of results of values inside.
pub struct ResultStreamItem;
/... | /// This struct is used in `ExtractTypeFromStream` implementation for streams | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.