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
ratings.rs
use super::*; use crate::{core::util, infrastructure::flows::prelude as flows}; #[post("/ratings", format = "application/json", data = "<data>")] pub fn
( connections: sqlite::Connections, mut search_engine: tantivy::SearchEngine, data: Json<usecases::NewPlaceRating>, ) -> Result<()> { let _ = flows::create_rating(&connections, &mut search_engine, data.into_inner())?; Ok(Json(())) } #[get("/ratings/<ids>")] pub fn load_rating(db: sqlite::Connection...
post_rating
identifier_name
ratings.rs
use super::*; use crate::{core::util, infrastructure::flows::prelude as flows}; #[post("/ratings", format = "application/json", data = "<data>")] pub fn post_rating( connections: sqlite::Connections,
Ok(Json(())) } #[get("/ratings/<ids>")] pub fn load_rating(db: sqlite::Connections, ids: String) -> Result<Vec<json::Rating>> { // TODO: RESTful API // - Only lookup and return a single entity // - Add a new action and method for getting multiple ids at once let ids = util::split_ids(&ids); ...
mut search_engine: tantivy::SearchEngine, data: Json<usecases::NewPlaceRating>, ) -> Result<()> { let _ = flows::create_rating(&connections, &mut search_engine, data.into_inner())?;
random_line_split
ratings.rs
use super::*; use crate::{core::util, infrastructure::flows::prelude as flows}; #[post("/ratings", format = "application/json", data = "<data>")] pub fn post_rating( connections: sqlite::Connections, mut search_engine: tantivy::SearchEngine, data: Json<usecases::NewPlaceRating>, ) -> Result<()> { let ...
let ratings_with_comments = usecases::load_ratings_with_comments(&*db.shared()?, &ids)?; let result = ratings_with_comments .into_iter() .map(|(r, cs)| { let comments = cs .into_iter() .map(|c| json::Comment { id: c.id.clone().into...
{ return Ok(Json(vec![])); }
conditional_block
Container.tsx
import * as React from 'react'; import 'cbioportal-frontend-commons/dist/styles.css'; import '../../globalStyles/prefixed-global.scss'; import PortalHeader from './PortalHeader'; import { getBrowserWindow, isWebdriver } from 'cbioportal-frontend-commons'; import { observer } from 'mobx-react'; import { getServerConf...
renderChildren() { const childProps = { ...this.props }; const { children } = this.props; return React.Children.map(children, c => React.cloneElement(c as React.ReactElement<any>, childProps) ); } render() { if ( !isLocalDBServer() && ...
{ return getBrowserWindow().globalStores.appStore; }
identifier_body
Container.tsx
import * as React from 'react'; import 'cbioportal-frontend-commons/dist/styles.css'; import '../../globalStyles/prefixed-global.scss'; import PortalHeader from './PortalHeader'; import { getBrowserWindow, isWebdriver } from 'cbioportal-frontend-commons'; import { observer } from 'mobx-react'; import { getServerConf...
body={ <a href={buildCBioPortalPageUrl('/')}> Return to homepage </a> } errorLog={formatErrorLog( ...
random_line_split
Container.tsx
import * as React from 'react'; import 'cbioportal-frontend-commons/dist/styles.css'; import '../../globalStyles/prefixed-global.scss'; import PortalHeader from './PortalHeader'; import { getBrowserWindow, isWebdriver } from 'cbioportal-frontend-commons'; import { observer } from 'mobx-react'; import { getServerConf...
return ( <div> <Helmet> <meta charSet="utf-8" /> <title>{getServerConfig().skin_title}</title> <meta name="description" content={getServerConfig().skin_description} ...
{ return ( <div className="contentWrapper"> <ErrorScreen title={'No session service configured'} body={ <p> As of version 3.0.0, all cBioPortal ...
conditional_block
Container.tsx
import * as React from 'react'; import 'cbioportal-frontend-commons/dist/styles.css'; import '../../globalStyles/prefixed-global.scss'; import PortalHeader from './PortalHeader'; import { getBrowserWindow, isWebdriver } from 'cbioportal-frontend-commons'; import { observer } from 'mobx-react'; import { getServerConf...
() { return getBrowserWindow().routingStore; } private get appStore() { return getBrowserWindow().globalStores.appStore; } renderChildren() { const childProps = { ...this.props }; const { children } = this.props; return React.Children.map(children, c => ...
routingStore
identifier_name
nsistags.py
############################################################################### # Name: nsistags.py # # Purpose: Generate Tags for Nullsoft Installer Scripts # # Author: Cody Precord <cprecord@editra.org> # ...
(buff): """Create a DocStruct object that represents a NSIS Script @param buff: a file like buffer object (StringIO) @todo: generate tags for lua tables? """ rtags = taglib.DocStruct() # Set Descriptions of Document Element Types rtags.SetElementDescription('variable', "Defines") rtags...
GenerateTags
identifier_name
nsistags.py
############################################################################### # Name: nsistags.py # # Purpose: Generate Tags for Nullsoft Installer Scripts # # Author: Cody Precord <cprecord@editra.org> # ...
llen = len(line) # Skip comment and empty lines if line.startswith(u"#") or line.startswith(u";") or not line: continue # Look for functions and sections if parselib.IsToken(line, 0, u'Function'): parts = line.split() if len(parts) > 1: ...
"""Create a DocStruct object that represents a NSIS Script @param buff: a file like buffer object (StringIO) @todo: generate tags for lua tables? """ rtags = taglib.DocStruct() # Set Descriptions of Document Element Types rtags.SetElementDescription('variable', "Defines") rtags.SetElementD...
identifier_body
nsistags.py
############################################################################### # Name: nsistags.py # # Purpose: Generate Tags for Nullsoft Installer Scripts # # Author: Cody Precord <cprecord@editra.org> # ...
else: continue return rtags #-----------------------------------------------------------------------------# # Test if __name__ == '__main__': import sys import StringIO fhandle = open(sys.argv[1]) txt = fhandle.read() fhandle.close() tags = GenerateTags(StringIO.St...
rtags.AddVariable(taglib.Variable(parts[1], lnum))
conditional_block
nsistags.py
############################################################################### # Name: nsistags.py # # Purpose: Generate Tags for Nullsoft Installer Scripts # # Author: Cody Precord <cprecord@editra.org> # ...
""" __author__ = "Cody Precord <cprecord@editra.org>" __svnid__ = "$Id: nsistags.py 52675 2008-03-22 03:34:38Z CJP $" __revision__ = "$Revision: 52675 $" #--------------------------------------------------------------------------# # Dependancies import taglib import parselib #---------------------------------------...
Generate a DocStruct object that captures the structure of a NSIS Script. It currently supports generating tags for Sections, Functions, and Macro defs.
random_line_split
dataaccess.py
# -*- coding: UTF-8 -*- from django.core.cache import cache from django.db.models.signals import post_delete, post_save import functools import hashlib WEEK = 7 * 24 * 60 * 60 # 1 week def cache_me(key=None, ikey=None, signals=(), models=(), timeout=WEEK): def hashme(k): if isinstance(k, unicode): ...
else: pingbacks = [] reactions = sorted(list(trackbacks) + list(pingbacks), key=lambda r: r.date, reverse=True) # normalizzo le reactions, mi assicuro che tutte abbiano un excerpt for ix, r in enumerate(reactions): if not hasattr(r, 'excerpt'): r.excerpt = r.content retu...
from pingback.models import Pingback # Purtroppo il metodo pingbacks_for_object vuole un oggetto non un id content = models.PostContent.objects.get(id=cid) pingbacks = Pingback.objects.pingbacks_for_object(content).filter(approved=True)
conditional_block
dataaccess.py
# -*- coding: UTF-8 -*- from django.core.cache import cache from django.db.models.signals import post_delete, post_save import functools import hashlib WEEK = 7 * 24 * 60 * 60 # 1 week def cache_me(key=None, ikey=None, signals=(), models=(), timeout=WEEK): def hashme(k): if isinstance(k, unicode): ...
k = key % args return hashme(k) @functools.wraps(f) def wrapper(*args, **kwargs): k = _key(*args, **kwargs) data = cache.get(k) if data is None: data = f(*args, **kwargs) cache.set(k, data, timeout) ...
k = key(*args, **kwargs) else:
random_line_split
dataaccess.py
# -*- coding: UTF-8 -*- from django.core.cache import cache from django.db.models.signals import post_delete, post_save import functools import hashlib WEEK = 7 * 24 * 60 * 60 # 1 week def cache_me(key=None, ikey=None, signals=(), models=(), timeout=WEEK):
if ikey or (ikey is None and key is None): for s in signals: s.connect(invalidate, weak=False) for m in models: post_save.connect(invalidate, sender=m, weak=False) post_delete.connect(invalidate, sender=m, weak=False) def _key(*ar...
def hashme(k): if isinstance(k, unicode): k = k.encode('utf-8') return hashlib.md5(k).hexdigest() def decorator(f): def invalidate(sender, **kwargs): if ikey is None: ks = (f.__name__,) elif callable(ikey): k = ikey(sender,...
identifier_body
dataaccess.py
# -*- coding: UTF-8 -*- from django.core.cache import cache from django.db.models.signals import post_delete, post_save import functools import hashlib WEEK = 7 * 24 * 60 * 60 # 1 week def cache_me(key=None, ikey=None, signals=(), models=(), timeout=WEEK): def
(k): if isinstance(k, unicode): k = k.encode('utf-8') return hashlib.md5(k).hexdigest() def decorator(f): def invalidate(sender, **kwargs): if ikey is None: ks = (f.__name__,) elif callable(ikey): k = ikey(sender, **kwargs)...
hashme
identifier_name
hooks.py
# Copyright 2015-2017 F-Secure # 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, ...
'context')) def hooks_factory(identifier, configuration, context): """ Returns the initialized hooks. """ manager = HookManager(identifier, configuration) manager.load_hooks(context) return manager class HookManager(object): """ The Hoo...
random_line_split
hooks.py
# Copyright 2015-2017 F-Secure # 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, ...
else: return HookClass
raise ValueError("%r is not subclass of of %r" % (HookClass, Hook))
conditional_block
hooks.py
# Copyright 2015-2017 F-Secure # 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, ...
(self, name, configuration, context): self.logger.debug('Loading %s hook.', name) try: HookClass = lookup_hook_class(name) hook = HookClass(HookParameters(self.identifier, configuration, cont...
_load_hook
identifier_name
hooks.py
# Copyright 2015-2017 F-Secure # 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, ...
def _load_hook(self, name, configuration, context): self.logger.debug('Loading %s hook.', name) try: HookClass = lookup_hook_class(name) hook = HookClass(HookParameters(self.identifier, configuration, ...
""" Initializes the Hooks and loads them within the Environment. """ for hook in self.configuration.get('hooks', ()): config = hook.get('configuration', {}) config.update(self.configuration.get('configuration', {})) try: self._load_hook(hook['...
identifier_body
NestedMenuItem.ts
import { StructureSchema } from '@ephox/boulder'; import { Optional, Result } from '@ephox/katamari'; import { FancyMenuItemSpec, MenuItemSpec, SeparatorMenuItemSpec, ToggleMenuItemSpec } from '../../api/Menu'; import * as ComponentSchema from '../../core/ComponentSchema'; import { CommonMenuItem, CommonMenuItemSpec, ...
export interface NestedMenuItem extends CommonMenuItem { type: 'nestedmenuitem'; icon: Optional<string>; getSubmenuItems: () => string | Array<NestedMenuItemContents>; onSetup: (api: NestedMenuItemInstanceApi) => (api: NestedMenuItemInstanceApi) => void; } export const nestedMenuItemSchema = StructureSchema.o...
random_line_split
controllers.js
angular.module('starter.controllers', []) // A simple controller that fetches a list of data from a service .controller('JobIndexCtrl', function($rootScope, PetService) { // "Pets" is a service returning mock data (services.js) $rootScope.pets = PetService.all(); }) // A simple controller that shows a tapped it...
}; $rootScope.pet = PetService.get(newJobId); $rootScope.pets = PetService.all(); $localstorage.setObject(newJobId, newJob); $state.go('new-quote', {'jobId' : newJobId}); } } });
{ var newJobId = $localstorage.length() - 1; var newJob = { id: String(newJobId), title: String(title.value.trim()), description: String(desc.value.trim()), location: String(location.value.trim()), quote: { damageDesc: "", estimatedCost: "", ...
conditional_block
controllers.js
angular.module('starter.controllers', []) // A simple controller that fetches a list of data from a service .controller('JobIndexCtrl', function($rootScope, PetService) { // "Pets" is a service returning mock data (services.js) $rootScope.pets = PetService.all(); }) // A simple controller that shows a tapped it...
location: String(location.value.trim()), quote: { damageDesc: "", estimatedCost: "", estimatedTime: "", }, report: { fixDesc: "", actualCost: "", startTime: "", finishTime: "" } }; $rootScope.p...
var newJobId = $localstorage.length() - 1; var newJob = { id: String(newJobId), title: String(title.value.trim()), description: String(desc.value.trim()),
random_line_split
decorator.ts
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import { StandaloneEditorWidget, IStandaloneEditorView, IEditorModel } from './widget'; import { EditorViewDecorator, EditorWidgetDecorator, EditorWidget } from '../decorator'; /** * A standalone editor view d...
else { this.editor.title.className = this.editor.title.className.replace(DIRTY_CLASS, ''); } } }
{ this.editor.title.className += ` ${DIRTY_CLASS}`; }
conditional_block
decorator.ts
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import { StandaloneEditorWidget, IStandaloneEditorView, IEditorModel } from './widget'; import { EditorViewDecorator, EditorWidgetDecorator, EditorWidget } from '../decorator'; /** * A standalone editor view d...
(editor:T) { editor.addClass(EDITOR_CLASS); this.updateTitleLabel(editor.getModel().uri); } /** * Handles model uri changed events. */ protected onModelUriChanged(model:IEditorModel): void { this.updateTitleLabel(model.uri); } /** * Handles dirty status changes. */ setDirty(dirty: ...
decorate
identifier_name
decorator.ts
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import { StandaloneEditorWidget, IStandaloneEditorView, IEditorModel } from './widget'; import { EditorViewDecorator, EditorWidgetDecorator, EditorWidget } from '../decorator'; /** * A standalone editor view d...
/** * Handles dirty status changes. */ setDirty(dirty: boolean): void { this.updateTitleStyles(dirty); super.setDirty(dirty); } /** * Updates a title lable of the decorated editor widget. */ protected updateTitleLabel(uri:string) { const label = uri ? uri.split('/').pop() : 'Untitle...
{ this.updateTitleLabel(model.uri); }
identifier_body
decorator.ts
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import { StandaloneEditorWidget, IStandaloneEditorView, IEditorModel } from './widget'; import { EditorViewDecorator, EditorWidgetDecorator, EditorWidget } from '../decorator'; /** * A standalone editor view d...
} /** * Decorates the given editor. */ protected decorate(editor:T) { editor.addClass(EDITOR_CLASS); this.updateTitleLabel(editor.getModel().uri); } /** * Handles model uri changed events. */ protected onModelUriChanged(model:IEditorModel): void { this.updateTitleLabel(model.uri); ...
*/ protected disconnect(editor:T) { editor.getModel().uriChanged.disconnect(this.onModelUriChanged, this);
random_line_split
realvid.py
Genesis Add-on Copyright (C) 2015 lambda 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. T...
# -*- coding: utf-8 -*- '''
random_line_split
realvid.py
# -*- coding: utf-8 -*- ''' Genesis Add-on Copyright (C) 2015 lambda 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 opt...
try: url = url.replace('/embed-', '/') url = re.compile('//.+?/([\w]+)').findall(url)[0] url = 'http://realvid.net/embed-%s.html' % url result = client.request(url) url = re.compile('file *: *"(http.+?)"').findall(result)[-1] return url except: ret...
identifier_body
realvid.py
# -*- coding: utf-8 -*- ''' Genesis Add-on Copyright (C) 2015 lambda 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 opt...
(url): try: url = url.replace('/embed-', '/') url = re.compile('//.+?/([\w]+)').findall(url)[0] url = 'http://realvid.net/embed-%s.html' % url result = client.request(url) url = re.compile('file *: *"(http.+?)"').findall(result)[-1] return url except: ...
resolve
identifier_name
index.d.ts
export interface Options { /** * defaults to false */ usa?: boolean; /** * defaults to the current time */ now?: Date; /** * defaults to 80 */ cutoff?: number; } declare function parse(str: string, options?: Options): string | null; export default parse; export function parseNearbyDays(s...
export function parseWordyDate(string: string, now: Date, cutoff: number): string | null; export function monthFromName(month: string): number | null; export function date(year: number, month: number, day: number): string | null;
random_line_split
image.js
import F2 from '@antv/f2'; const data = [ { year: '2001', sales: 1500 }, { year: '2002', sales: 5500 }, { year: '2003', sales: 1200 }, { year: '2004', sales: 2000 } ]; const chart = new F2.Chart({ id: 'container', pixelRatio: window.devicePixelRatio }); chart.sour...
x, y: y - 20, src: 'https://gw.alipayobjects.com/zos/antfincdn/FLrTNDvlna/antv.png', width: 20, height: 20 } }); }); chart.animate(false); chart.render();
attrs: {
random_line_split
bitops.rs
//Thanks to sanxiyn at irc.orinzer.org pub trait Bitops { fn bit_length() -> usize; fn bit_mask() -> Self; } impl Bitops for u8 { fn bit_length() -> usize { 8usize } fn bit_mask() -> u8 { 0xFFu8 } } impl Bitops for u16 { fn bit_length() -> usize { 16usize } fn bit_mask() -> u16 { 0xFFFFu16 }...
} pub fn bit_mask<T: Bitops>() -> T { T::bit_mask() }
random_line_split
bitops.rs
//Thanks to sanxiyn at irc.orinzer.org pub trait Bitops { fn bit_length() -> usize; fn bit_mask() -> Self; } impl Bitops for u8 { fn bit_length() -> usize { 8usize } fn bit_mask() -> u8 { 0xFFu8 } } impl Bitops for u16 { fn bit_length() -> usize { 16usize } fn bit_mask() -> u16 { 0xFFFFu16 }...
<T: Bitops>() -> T { T::bit_mask() }
bit_mask
identifier_name
bitops.rs
//Thanks to sanxiyn at irc.orinzer.org pub trait Bitops { fn bit_length() -> usize; fn bit_mask() -> Self; } impl Bitops for u8 { fn bit_length() -> usize { 8usize } fn bit_mask() -> u8 { 0xFFu8 } } impl Bitops for u16 { fn bit_length() -> usize { 16usize } fn bit_mask() -> u16 { 0xFFFFu16 }...
{ T::bit_mask() }
identifier_body
app-routing.module.ts
import { NgModule } from '@angular/core'; import { RouterModule, Routes, PreloadAllModules } from '@angular/router'; import { HomeComponent } from './home/home.component';
const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'i18n', component: I18nComponent }, { path: 'list', loadChildren: () => import('./list/list.module').then(m => m.ListModule) }, { path: 'validation', componen...
import { I18nComponent } from './i18n/i18n.component'; import { ValidationComponent } from './validation/validation.component';
random_line_split
app-routing.module.ts
import { NgModule } from '@angular/core'; import { RouterModule, Routes, PreloadAllModules } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { I18nComponent } from './i18n/i18n.component'; import { ValidationComponent } from './validation/validation.component'; const routes: Rout...
{ }
AppRoutingModule
identifier_name
setup.py
# -*- coding: utf-8 -*- from setuptools import setup, find_packages long_desc = ''' This package contains the ${name} Sphinx extension. .. add description here ..
name='sphinxcontrib-${name}', version='0.1', url='http://bitbucket.org/birkenfeld/sphinx-contrib', download_url='http://pypi.python.org/pypi/sphinxcontrib-${name}', license='BSD', author='${author}', author_email='${author_email}', description='Sphinx "${name}" extension', long_descr...
''' requires = ['Sphinx>=0.6'] setup(
random_line_split
conditions.py
''' A condition ''' from base import Base from compares import const class ComparisonMixin(object): ''' Compare two values with a comparison utility to denote if a change has validated. ''' def compare(self, a, b, ctype=None): ''' compare 'a' against 'b' for a comparison of `ctyp...
Optionally `valid` callback when the condition is met ''' self.watch = node self.field = attr self.target = value self._valid_cb = valid def valid(self): ''' Is this condition valid ''' vs = self._validate() for node in vs: ...
the attribute to monitor (String), a value to validate condition.
random_line_split
conditions.py
''' A condition ''' from base import Base from compares import const class
(object): ''' Compare two values with a comparison utility to denote if a change has validated. ''' def compare(self, a, b, ctype=None): ''' compare 'a' against 'b' for a comparison of `ctype` by defauly ctype will compare for an exact match ''' if ctype is ...
ComparisonMixin
identifier_name
conditions.py
''' A condition ''' from base import Base from compares import const class ComparisonMixin(object): ''' Compare two values with a comparison utility to denote if a change has validated. ''' def compare(self, a, b, ctype=None): ''' compare 'a' against 'b' for a comparison of `ctyp...
def valid(self): ''' Is this condition valid ''' vs = self._validate() for node in vs: val = vs[node] if val == False: return False return True def get_nodes(self): ''' return a list of Nodes retrieved from the machine us...
''' A condition perpetuates changes of an object base upon rules applied at configuration. ''' def __init__(self, node, attr, value=None, valid=None): ''' A condition requires a node (Node|String|iterable), the attribute to monitor (String), a value to valida...
identifier_body
conditions.py
''' A condition ''' from base import Base from compares import const class ComparisonMixin(object): ''' Compare two values with a comparison utility to denote if a change has validated. ''' def compare(self, a, b, ctype=None): ''' compare 'a' against 'b' for a comparison of `ctyp...
return r
v = node.get(field) # print 'node:', v, 'cache', cv, 'ctype', ctype c = self.compare(v, value, ctype) r.update({ node: c }) # import pdb;pdb.set_trace()
conditional_block
string_template_formatting.ts
import {seq, per, altPrio, ver, Expression} from "../combi"; import {Source} from "."; import {IStatementRunnable} from "../statement_runnable"; import {Version} from "../../../version"; import {Dynamic} from "./dynamic"; export class StringTemplateFormatting extends Expression { public
(): IStatementRunnable { // https://help.sap.com/doc/abapdocu_752_index_htm/7.52/en-us/abapcompute_string_format_options.htm const alphaOptions = altPrio("OUT", "RAW", "IN", Source); const alignOptions = altPrio("LEFT", "RIGHT", "CENTER", Source); const dateTimeOptions = altPrio("RAW", "ISO", "USER",...
getRunnable
identifier_name
string_template_formatting.ts
import {seq, per, altPrio, ver, Expression} from "../combi"; import {Source} from "."; import {IStatementRunnable} from "../statement_runnable"; import {Version} from "../../../version"; import {Dynamic} from "./dynamic"; export class StringTemplateFormatting extends Expression { public getRunnable(): IStatementRunn...
"SIGN_AS_POSTFIX", "SCALE_PRESERVING", "SCIENTIFIC", "SCIENTIFIC_WITH_LEADING_ZERO", "SCALE_PRESERVING_SCIENTIFIC", "ENGIN...
{ // https://help.sap.com/doc/abapdocu_752_index_htm/7.52/en-us/abapcompute_string_format_options.htm const alphaOptions = altPrio("OUT", "RAW", "IN", Source); const alignOptions = altPrio("LEFT", "RIGHT", "CENTER", Source); const dateTimeOptions = altPrio("RAW", "ISO", "USER", "ENVIRONMENT", Source,...
identifier_body
string_template_formatting.ts
import {seq, per, altPrio, ver, Expression} from "../combi"; import {Source} from "."; import {IStatementRunnable} from "../statement_runnable"; import {Version} from "../../../version"; import {Dynamic} from "./dynamic"; export class StringTemplateFormatting extends Expression { public getRunnable(): IStatementRunn...
const timeStampOptions = altPrio("SPACE", "ISO", "USER", "ENVIRONMENT", Source); const numberOptions = altPrio("RAW", "USER", "ENVIRONMENT", Source); const signOptions = altPrio("LEFT", "LEFTPLUS", "LEFTSPACE", "RIGHT", "RIGHTPLUS", "RIGHTSPACE", Source); const caseOptions = altPrio("RAW", "UPPER", "...
const dateTimeOptions = altPrio("RAW", "ISO", "USER", "ENVIRONMENT", Source, Dynamic);
random_line_split
plot_couplings.py
#! /usr/bin/env python """ This programs plots the electronic coupling between two states. It reads all Ham_*_im files and cache them in a tensor saved on disk. Usage: plot_couplings.py -p . -s1 XX -s2 YY -dt 1.0 p = path to the hamiltonian files s1 = state 1 index s2 = state 2 index dt = time step in fs """ i...
(parser): """ Parse Command line options. """ args = parser.parse_args() attributes = ['p', 's1', 's2', 'dt'] return [getattr(args, p) for p in attributes] if __name__ == "__main__": msg = "plot_decho -p <path/to/hamiltonians> -s1 <State 1> -s2 <State 2>\ -dt <time step>" parser...
read_cmd_line
identifier_name
plot_couplings.py
#! /usr/bin/env python """ This programs plots the electronic coupling between two states. It reads all Ham_*_im files and cache them in a tensor saved on disk. Usage: plot_couplings.py -p . -s1 XX -s2 YY -dt 1.0 p = path to the hamiltonian files s1 = state 1 index s2 = state 2 index dt = time step in fs """ i...
parser.add_argument('-p', required=True, help='path to the Hamiltonian files in Pyxaid format') parser.add_argument('-s1', required=True, type=int, help='Index of the first state') parser.add_argument('-s2', required=True, type=int, hel...
msg = "plot_decho -p <path/to/hamiltonians> -s1 <State 1> -s2 <State 2>\ -dt <time step>" parser = argparse.ArgumentParser(description=msg)
random_line_split
plot_couplings.py
#! /usr/bin/env python """ This programs plots the electronic coupling between two states. It reads all Ham_*_im files and cache them in a tensor saved on disk. Usage: plot_couplings.py -p . -s1 XX -s2 YY -dt 1.0 p = path to the hamiltonian files s1 = state 1 index s2 = state 2 index dt = time step in fs """ i...
msg = "plot_decho -p <path/to/hamiltonians> -s1 <State 1> -s2 <State 2>\ -dt <time step>" parser = argparse.ArgumentParser(description=msg) parser.add_argument('-p', required=True, help='path to the Hamiltonian files in Pyxaid format') parser.add_argument('-s1', required=True, t...
conditional_block
plot_couplings.py
#! /usr/bin/env python """ This programs plots the electronic coupling between two states. It reads all Ham_*_im files and cache them in a tensor saved on disk. Usage: plot_couplings.py -p . -s1 XX -s2 YY -dt 1.0 p = path to the hamiltonian files s1 = state 1 index s2 = state 2 index dt = time step in fs """ i...
def read_cmd_line(parser): """ Parse Command line options. """ args = parser.parse_args() attributes = ['p', 's1', 's2', 'dt'] return [getattr(args, p) for p in attributes] if __name__ == "__main__": msg = "plot_decho -p <path/to/hamiltonians> -s1 <State 1> -s2 <State 2>\ -dt <tim...
if not os.path.isfile('couplings.npy'): # Check all the files stored files_im = glob.glob('Ham_*_im') # Read the couplings couplings = np.stack( np.loadtxt(f'Ham_{f}_im') for f in range(len(files_im))) # Save the file for fast reading afterwards np.save('coupli...
identifier_body
regularizers.py
import numpy as np from keras.datasets import mnist from keras.layers import Activation from keras.layers import Dense from keras.models import Sequential from keras.utils import np_utils np.random.seed(1337) nb_classes = 10 batch_size = 128 nb_epoch = 5
high_weight = 5 max_train_samples = 5000 max_test_samples = 1000 def get_data(): # the data, shuffled and split between tran and test sets (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = X_train.reshape(60000, 784)[:max_train_samples] X_test = X_test.reshape(10000, 784)[:max_test_sa...
weighted_class = 9 standard_weight = 1
random_line_split
regularizers.py
import numpy as np from keras.datasets import mnist from keras.layers import Activation from keras.layers import Dense from keras.models import Sequential from keras.utils import np_utils np.random.seed(1337) nb_classes = 10 batch_size = 128 nb_epoch = 5 weighted_class = 9 standard_weight = 1 high_weight = 5 max_trai...
model = Sequential() model.add(Dense(50, input_shape=(784,))) model.add(Activation('relu')) model.add(Dense(10, W_regularizer=weight_reg, activity_regularizer=activity_reg)) model.add(Activation('softmax')) return model
identifier_body
regularizers.py
import numpy as np from keras.datasets import mnist from keras.layers import Activation from keras.layers import Dense from keras.models import Sequential from keras.utils import np_utils np.random.seed(1337) nb_classes = 10 batch_size = 128 nb_epoch = 5 weighted_class = 9 standard_weight = 1 high_weight = 5 max_trai...
(): # the data, shuffled and split between tran and test sets (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = X_train.reshape(60000, 784)[:max_train_samples] X_test = X_test.reshape(10000, 784)[:max_test_samples] X_train = X_train.astype('float32') / 255 X_test = X_test.astype...
get_data
identifier_name
config.py
ELSIUS, __version__) from homeassistant.core import valid_entity_id from homeassistant.exceptions import HomeAssistantError from homeassistant.util.yaml import load_yaml import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import set_customize from homeassistant.util import dt as d...
() -> str: """Put together the default configuration directory based on OS.""" data_dir = os.getenv('APPDATA') if os.name == "nt" \ else os.path.expanduser('~') return os.path.join(data_dir, CONFIG_DIR_NAME) def ensure_config_exists(config_dir: str, detect_location: bool=True) -> str: """Ensur...
get_default_config_dir
identifier_name
config.py
ELSIUS, __version__) from homeassistant.core import valid_entity_id from homeassistant.exceptions import HomeAssistantError from homeassistant.util.yaml import load_yaml import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import set_customize from homeassistant.util import dt as d...
def load_yaml_config_file(config_path): """Parse a YAML configuration file. This method needs to run in an executor. """ conf_dict = load_yaml(config_path) if not isinstance(conf_dict, dict): msg = 'The configuration file {} does not contain a dictionary'.format( os.path.bas...
"""Look in given directory for supported configuration files. Async friendly. """ config_path = os.path.join(config_dir, YAML_CONFIG_FILE) return config_path if os.path.isfile(config_path) else None
identifier_body
config.py
ELSIUS, __version__) from homeassistant.core import valid_entity_id from homeassistant.exceptions import HomeAssistantError from homeassistant.util.yaml import load_yaml import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import set_customize from homeassistant.util import dt as d...
""" def _load_hass_yaml_config(): path = find_config_file(hass.config.config_dir) conf = load_yaml_config_file(path) return conf conf = yield from hass.loop.run_in_executor(None, _load_hass_yaml_config) return conf def find_config_file(config_dir): """Look in given directo...
This function allow component inside asyncio loop to reload his config by self. This method is a coroutine.
random_line_split
config.py
ELSIUS, __version__) from homeassistant.core import valid_entity_id from homeassistant.exceptions import HomeAssistantError from homeassistant.util.yaml import load_yaml import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import set_customize from homeassistant.util import dt as d...
config_file.write(DEFAULT_CONFIG) with open(version_path, 'wt') as version_file: version_file.write(__version__) return config_path except IOError: print('Unable to create default configuration file', config_path) return None @asyncio.coroutine def asyn...
if info[attr] is None: continue elif description: config_file.write(" # {}\n".format(description)) config_file.write(" {}: {}\n".format(attr, info[attr]))
conditional_block
connection-button.js
import BarButton from '../bar-button/bar-button'; import { useRef, useEffect } from 'react'; export default function ConnectionButton() { const buttonRef = useRef(); const isUserConnected = elementorAdminTopBarConfig.is_user_connected;
jQuery( buttonRef.current ).elementorConnect(); }, [] ); let tooltipText = __( 'Connect your account to get access to Elementor\'s Template Library & more.', 'elementor' ), connectUrl = elementorAdminTopBarConfig.connect_url, buttonText = __( 'Connect Account', 'elementor' ), targetUrl = '_self'; if ( isU...
useEffect( () => { if ( ! buttonRef.current || isUserConnected ) { return; }
random_line_split
connection-button.js
import BarButton from '../bar-button/bar-button'; import { useRef, useEffect } from 'react'; export default function
() { const buttonRef = useRef(); const isUserConnected = elementorAdminTopBarConfig.is_user_connected; useEffect( () => { if ( ! buttonRef.current || isUserConnected ) { return; } jQuery( buttonRef.current ).elementorConnect(); }, [] ); let tooltipText = __( 'Connect your account to get access to Eleme...
ConnectionButton
identifier_name
connection-button.js
import BarButton from '../bar-button/bar-button'; import { useRef, useEffect } from 'react'; export default function ConnectionButton() { const buttonRef = useRef(); const isUserConnected = elementorAdminTopBarConfig.is_user_connected; useEffect( () => { if ( ! buttonRef.current || isUserConnected )
jQuery( buttonRef.current ).elementorConnect(); }, [] ); let tooltipText = __( 'Connect your account to get access to Elementor\'s Template Library & more.', 'elementor' ), connectUrl = elementorAdminTopBarConfig.connect_url, buttonText = __( 'Connect Account', 'elementor' ), targetUrl = '_self'; if ( is...
{ return; }
conditional_block
connection-button.js
import BarButton from '../bar-button/bar-button'; import { useRef, useEffect } from 'react'; export default function ConnectionButton()
buttonText = __( 'My Elementor', 'elementor' ); targetUrl = '_blank'; } return ( <BarButton icon="eicon-user-circle-o" buttonRef={buttonRef} dataInfo={tooltipText} href={connectUrl} target={targetUrl}>{ buttonText }</BarButton> ); }
{ const buttonRef = useRef(); const isUserConnected = elementorAdminTopBarConfig.is_user_connected; useEffect( () => { if ( ! buttonRef.current || isUserConnected ) { return; } jQuery( buttonRef.current ).elementorConnect(); }, [] ); let tooltipText = __( 'Connect your account to get access to Elemento...
identifier_body
Queue.test.js
const test = require('tape') const Queue = require('./Queue') test('peek on empty queue', assert => { const queue = new Queue() assert.strictEqual(queue.peek(), null) assert.end() }) test('enqueue items to the queue', assert => { const queue = new Queue() queue.enqueue('foo') queue.enqueue('bar') assert...
const queue = new Queue() queue.enqueue('A') queue.enqueue('B') queue.enqueue('C') assert.equal(queue.dequeue(), 'A') assert.equal(queue.dequeue(), 'B') assert.equal(queue.dequeue(), 'C') assert.end() }) test('create queue from array', assert => { const queue = new Queue(['A', 'B', 'C']) assert.equ...
assert.end() }) test('dequeue items from the queue', assert => {
random_line_split
DMF.py
#coding:utf8 from baseclass.DeepRecommender import DeepRecommender import numpy as np from random import choice,random,randint,shuffle from tool import config import tensorflow as tf #According to the paper, we only class DMF(DeepRecommender): def __init__(self,conf,trainingSet=None,testSet=None,fold='[1]'): ...
v = choice(itemList) while self.data.contains(u,v): u = choice(userList) v = choice(itemList) rows[self.batch_size-1+i]=self.data.row(u) cols[self.batch_size-1+i]=self.data.col(i) u_idx.append(self.data.user[u]) v_id...
rows = np.zeros(((self.negative_sp+1)*self.batch_size,self.num_items)) cols = np.zeros(((self.negative_sp+1)*self.batch_size,self.num_users)) batch_idx = range(self.batch_size*i,self.batch_size*(i+1)) users = [self.data.trainingData[idx][0] for idx in batch_idx] items = [self.data.train...
identifier_body
DMF.py
#coding:utf8 from baseclass.DeepRecommender import DeepRecommender import numpy as np from random import choice,random,randint,shuffle from tool import config import tensorflow as tf #According to the paper, we only class DMF(DeepRecommender): def __init__(self,conf,trainingSet=None,testSet=None,fold='[1]'): ...
self.loss = self.r*tf.log(self.y_) + (1 - self.r) * tf.log(1 - self.y_)#tf.nn.sigmoid_cross_entropy_with_logits(logits=self.y_,labels=self.r) #self.loss = tf.nn.l2_loss(tf.subtract(self.y_,self.r)) self.loss = -tf.reduce_sum(self.loss) reg_lambda = tf.constant(self.regU, dtype=tf.float32...
self.y_ = tf.reduce_sum(tf.multiply(self.user_out, self.item_out), axis=1) / ( norm_item_output * norm_user_output) self.y_ = tf.maximum(1e-6, self.y_)
random_line_split
DMF.py
#coding:utf8 from baseclass.DeepRecommender import DeepRecommender import numpy as np from random import choice,random,randint,shuffle from tool import config import tensorflow as tf #According to the paper, we only class DMF(DeepRecommender): def __init__(self,conf,trainingSet=None,testSet=None,fold='[1]'): ...
self.normalized_V = np.sqrt(np.sum(self.V * self.V, axis=1)) self.normalized_U = np.sqrt(np.sum(self.U * self.U, axis=1)) self.ranking_performance() print("Optimization Finished!") def predictForRanking(self, u): 'invoked to rank all the items for the user' ...
users,items,ratings,u_idx,v_idx = self.next_batch(i) shuffle_idx=np.random.permutation(range(len(users))) users = users[shuffle_idx] items = items[shuffle_idx] ratings = ratings[shuffle_idx] u_idx = u_idx[shuffle_idx] v_idx...
conditional_block
DMF.py
#coding:utf8 from baseclass.DeepRecommender import DeepRecommender import numpy as np from random import choice,random,randint,shuffle from tool import config import tensorflow as tf #According to the paper, we only class DMF(DeepRecommender): def __init__(self,conf,trainingSet=None,testSet=None,fold='[1]'): ...
(self, u): 'invoked to rank all the items for the user' if self.data.containsUser(u): uid = self.data.user[u] return np.divide(self.V.dot(self.U[uid]),self.normalized_U[uid]*self.normalized_V) else: return [self.data.globalMean] * self.num_items
predictForRanking
identifier_name
sepcomp-lib.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ assert_eq!(one(), 1); assert_eq!(two(), 2); assert_eq!(three(), 3); }
identifier_body
sepcomp-lib.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}
assert_eq!(two(), 2); assert_eq!(three(), 3);
random_line_split
sepcomp-lib.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { assert_eq!(one(), 1); assert_eq!(two(), 2); assert_eq!(three(), 3); }
main
identifier_name
data.py
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2017 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # 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, eith...
def check_data_writable(): """Check we can write to data dir.""" create_and_check_dir(settings.DATA_DIR) create_and_check_dir(data_dir('home')) create_and_check_dir(data_dir('whoosh')) create_and_check_dir(data_dir('ssh')) create_and_check_dir(data_dir('vcs')) def data_dir(component): """R...
not os.access(path, os.W_OK): raise OSError( 'DATA_DIR {0} is not writable!'.format(path) )
conditional_block
data.py
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2017 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # 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, eith...
def data_dir(component): """Return path to data dir for given component.""" return os.path.join(settings.DATA_DIR, component)
random_line_split
data.py
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2017 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # 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, eith...
"""Check we can write to data dir.""" create_and_check_dir(settings.DATA_DIR) create_and_check_dir(data_dir('home')) create_and_check_dir(data_dir('whoosh')) create_and_check_dir(data_dir('ssh')) create_and_check_dir(data_dir('vcs')) def data_dir(component): """Return path to data dir for...
ck_data_writable():
identifier_name
data.py
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2017 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # 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, eith...
def data_dir(component): """Return path to data dir for given component.""" return os.path.join(settings.DATA_DIR, component)
Check we can write to data dir.""" create_and_check_dir(settings.DATA_DIR) create_and_check_dir(data_dir('home')) create_and_check_dir(data_dir('whoosh')) create_and_check_dir(data_dir('ssh')) create_and_check_dir(data_dir('vcs'))
identifier_body
fetchbot.py
from praw import Reddit import json import os import time import datetime from .tools import storage from .tools import display class FetchBot: """Bot to fetch the subreddit data.""" def __init__(self, user_agent, subreddit, data_file): """Basic constructor""" self._user_agent = user_agent ...
if not os.path.exists(os.path.dirname(self._data_file)): os.makedirs(os.path.dirname(self._data_file)) with open(self._data_file, 'w') as df: json.dump(self._data, df) def fetch(self): """Fetching function""" self._fetch(self._praw.get_comments(self._subreddi...
def __del__(self): """Destructor"""
random_line_split
fetchbot.py
from praw import Reddit import json import os import time import datetime from .tools import storage from .tools import display class FetchBot: """Bot to fetch the subreddit data.""" def __init__(self, user_agent, subreddit, data_file): """Basic constructor""" self._user_agent = user_agent ...
if __name__ == "__main__": autorun()
"""Autorun function of this module""" home = os.getenv('HOME') config_file = os.path.join(home, '.config/flairstats/config.json') if not os.path.exists(config_file): raise FileNotFoundError(config_file) fetchbots = FetchBotGenerator(config_file) for bot in fetchbots: bot.fetch()
identifier_body
fetchbot.py
from praw import Reddit import json import os import time import datetime from .tools import storage from .tools import display class FetchBot: """Bot to fetch the subreddit data.""" def __init__(self, user_agent, subreddit, data_file): """Basic constructor""" self._user_agent = user_agent ...
with open(self._data_file, 'w') as df: json.dump(self._data, df) def fetch(self): """Fetching function""" self._fetch(self._praw.get_comments(self._subreddit, limit=500), 'comments') self._fetch(self._praw.get_subreddit(self._subreddit).get_new(limit=500), 'posts') ...
os.makedirs(os.path.dirname(self._data_file))
conditional_block
fetchbot.py
from praw import Reddit import json import os import time import datetime from .tools import storage from .tools import display class FetchBot: """Bot to fetch the subreddit data.""" def __init__(self, user_agent, subreddit, data_file): """Basic constructor""" self._user_agent = user_agent ...
(config_file): """Generate a list-like container of FetchBot objects""" with open(config_file) as cf: json_config = json.load(cf) user_agent = json_config['user-agent'] for i in json_config['bots']: yield FetchBot(user_agent, i['subreddit'], i['data-file']) def autorun(): """Autoru...
FetchBotGenerator
identifier_name
members.js
'use strict'; /** * @ngdoc function * @name lubriApp.controller:MembersCtrl * @description * # MembersCtrl * Controller of the lubriApp */ angular.module('lubriApp') .config(function($stateProvider) { $stateProvider.state('app.members', { abstract: true, url: '/members', templateUrl: 'vi...
elete }; $scope.delete = function(id) { SweetAlert.swal({ title: '您确定要删除吗?', type: 'warning', showCancelButton: true, confirmButtonColor: '#DD6B55' }, function(isConfirm){ if (isConfirm) { Member.deleteById(id, function() { toasty.pop.success({title: '组员被删除',...
ope.viewActions = { delete : $scope.d
identifier_body
members.js
'use strict'; /** * @ngdoc function * @name lubriApp.controller:MembersCtrl * @description * # MembersCtrl * Controller of the lubriApp */ angular.module('lubriApp') .config(function($stateProvider) { $stateProvider.state('app.members', { abstract: true, url: '/members', templateUrl: 'vi...
.member = Member.findById({ id: memberId }, function() {}, function(err) { console.log(err); }); } else { $scope.member = {}; } $scope.gridOptions = { data: 'members', enableFiltering: true, paginationPageSizes: [5, 10, 15], paginationPageSize: 10, headerRowHeight: 39,...
{ var members = $scope.importData; for (var i=0;i<members.length;i++) { var member = members[i]; member.created = new Date(); delete member.$$hashKey; Member.upsert(member, function() { }, function(err) { console.log(err); }); }; toasty....
conditional_block
members.js
'use strict'; /** * @ngdoc function * @name lubriApp.controller:MembersCtrl * @description * # MembersCtrl * Controller of the lubriApp */ angular.module('lubriApp') .config(function($stateProvider) { $stateProvider.state('app.members', { abstract: true, url: '/members', templateUrl: 'vi...
paginationPageSizes: [5, 10, 15], paginationPageSize: 10, headerRowHeight: 39, rowHeight: 39, columnFooterHeight: 39, gridFooterHeight: 39, selectionRowHeaderWidth: 39, columnDefs: [ { name: 'Edit', width: 80, displayName: '编辑', enableSorting: false, enableFiltering: false, cellTem...
random_line_split
members.js
'use strict'; /** * @ngdoc function * @name lubriApp.controller:MembersCtrl * @description * # MembersCtrl * Controller of the lubriApp */ angular.module('lubriApp') .config(function($stateProvider) { $stateProvider.state('app.members', { abstract: true, url: '/members', templateUrl: 'vi...
$scope.viewActions = { delete : $scope.delete }; $scope.delete = function(id) { SweetAlert.swal({ title: '您确定要删除吗?', type: 'warning', showCancelButton: true, confirmButtonColor: '#DD6B55' }, function(isConfirm){ if (isConfirm) { Member.deleteById(id, function() { ...
ms();
identifier_name
nestedNavigation.js
/* * Copyright 2022 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to ...
(e, depth) { let parentElement, counter = depth; while (counter > 0) { if (!parentElement) { parentElement = e.parentElement; } else { parentElement = parentElement?.parentElement; } counter--; } return parentElement; } export function getFocusableChild(element, depth, childToG...
getAncestorByDepth
identifier_name
nestedNavigation.js
/* * Copyright 2022 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to ...
{ const parentElement = getAncestorByDepth(e, depth); if (parentElement) { const nextElementParent = parentElement[direction]; if (!nextElementParent) { return null; } // Get the first child that is not disabled and has tabindex -1. return nextElementParent.querySelector(SELECTOR); } r...
identifier_body
nestedNavigation.js
/* * Copyright 2022 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to ...
* @param {number} depth Nesting depth of the element to see how far up we have to look for the ancestor. * @return {Object} Found element. */ export function getAncestorByDepth(e, depth) { let parentElement, counter = depth; while (counter > 0) { if (!parentElement) { parentElement = e.parentEleme...
/** * Gets the ancestor element of the active element based on given depth. * * @param {Object} e Original element to get the parent of.
random_line_split
nestedNavigation.js
/* * Copyright 2022 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to ...
return parentElement; } export function getFocusableChild(element, depth, childToGet = 'firstChild') { const parentElement = getAncestorByDepth(element, depth); const firstElementParent = parentElement.parentNode[childToGet]; // First non-disabled child with tabIndex -1. return firstElementParent.querySelec...
{ if (!parentElement) { parentElement = e.parentElement; } else { parentElement = parentElement?.parentElement; } counter--; }
conditional_block
ui.py
import os import pygtk pygtk.require('2.0') import gtk from gtkcodebuffer import CodeBuffer, SyntaxLoader class Ui(object): """ The user interface. This dialog is the LaTeX input window and includes widgets to display compilation logs and a preview. It uses GTK2 which must be installed an importable...
raise SystemExit(1) def destroy(self, widget, event, data=None): """Destroy hook for the GTK window. Quit and return False.""" gtk.main_quit() return False def setup_ui(self): """Creates the actual UI.""" # create a floating toplevel window and set some title ...
random_line_split
ui.py
import os import pygtk pygtk.require('2.0') import gtk from gtkcodebuffer import CodeBuffer, SyntaxLoader class Ui(object): """ The user interface. This dialog is the LaTeX input window and includes widgets to display compilation logs and a preview. It uses GTK2 which must be installed an importable...
def main(self): gtk.main()
buffer = self.log_view.get_buffer() buffer.set_text(msg) self.notebook.set_current_page(1)
identifier_body
ui.py
import os import pygtk pygtk.require('2.0') import gtk from gtkcodebuffer import CodeBuffer, SyntaxLoader class Ui(object): """ The user interface. This dialog is the LaTeX input window and includes widgets to display compilation logs and a preview. It uses GTK2 which must be installed an importable...
def cancel(self, widget, data=None): """Close button pressed: Exit""" raise SystemExit(1) def destroy(self, widget, event, data=None): """Destroy hook for the GTK window. Quit and return False.""" gtk.main_quit() return False def setup_ui(self): """Creat...
gtk.main_quit() return False
conditional_block
ui.py
import os import pygtk pygtk.require('2.0') import gtk from gtkcodebuffer import CodeBuffer, SyntaxLoader class Ui(object): """ The user interface. This dialog is the LaTeX input window and includes widgets to display compilation logs and a preview. It uses GTK2 which must be installed an importable...
(self): gtk.main()
main
identifier_name
__init__.py
# coding=utf8 from django.views.generic import ListView, DetailView, CreateView from django.db.models import Q from django.http import JsonResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from django.shortcuts import render from pure_pagination.mixins import PaginationMixin from django.contri...
籍不可以删除,没有关联书籍可以删除 try: obj = self.model.objects.get(pk=pk) if not obj.book_set.all(): self.model.objects.filter(pk=pk).delete() res = {"code": 0, "result": "删除出版商成功"} else: res = {"code": 1, "errmsg": "该出版社有关联书籍,请联系管理员"} ...
如果有关联书
identifier_name
__init__.py
# coding=utf8 from django.views.generic import ListView, DetailView, CreateView from django.db.models import Q from django.http import JsonResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from django.shortcuts import render from pure_pagination.mixins import PaginationMixin from django.contri...
return queryset def get_context_data(self, **kwargs): context = super(PublishListView, self).get_context_data(**kwargs) context['keyword'] = self.keyword return context def post(self, request): form = PublishForm(request.POST) if form.is_valid(): form.sav...
et = queryset.filter(Q(name__icontains=self.keyword) | Q(address__icontains=self.keyword) | Q(city__icontains=self.keyword))
conditional_block
__init__.py
# coding=utf8 from django.views.generic import ListView, DetailView, CreateView from django.db.models import Q from django.http import JsonResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse from django.shortcuts import render from pure_pagination.mixins import PaginationMixin from django.contrib.auth.mixins import LoginRequiredMixin from django.conf import settings from books.models import Publish, Author, Book from books.forms import PublishForm import json ...
random_line_split
__init__.py
# coding=utf8 from django.views.generic import ListView, DetailView, CreateView from django.db.models import Q from django.http import JsonResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from django.shortcuts import render from pure_pagination.mixins import PaginationMixin from django.contri...
所在该出版社的书籍,如果有关联书籍不可以删除,没有关联书籍可以删除 try: obj = self.model.objects.get(pk=pk) if not obj.book_set.all(): self.model.objects.filter(pk=pk).delete() res = {"code": 0, "result": "删除出版商成功"} else: res = {"code": 1, "errmsg": "该出版社有关联书籍,...
shForm(request.POST, instance=p) if form.is_valid(): form.save() res = {"code": 0, "result": "更新出版商成功", 'next_url': self.next_url} else: res = {"code": 1, "errmsg": form.errors, 'next_url': self.next_url} return render(request, settings.JUMP_PAGE, res) ...
identifier_body
utils.py
import asyncio import os from urllib.parse import urlparse import aiohttp def damerau_levenshtein(first_string, second_string): """Returns the Damerau-Levenshtein edit distance between two strings.""" previous = None prev_a = None current = [i for i, x in enumerate(second_string, 1)] + [0] for ...
def get(url, **kwargs): full_url = url + '&'.join(sorted('='.join(kv) for kv in kwargs.get('params', {}).items())) if full_url in RequestManager.current_requests: return RequestManager.current_requests[full_url].wait_for() r = RequestManager(url, **kwargs) RequestManager.current_requests[full...
return self.callbacks[-1]
random_line_split
utils.py
import asyncio import os from urllib.parse import urlparse import aiohttp def damerau_levenshtein(first_string, second_string): """Returns the Damerau-Levenshtein edit distance between two strings.""" previous = None prev_a = None current = [i for i, x in enumerate(second_string, 1)] + [0] for ...
(self, url, **kwargs): self.url = url self.kwargs = kwargs self.callbacks = [] RequestManager.count += 1 @asyncio.coroutine def run(self): key = urlparse(self.url).netloc p = self.get_pool(key) with (yield from p): response = yield from aioh...
__init__
identifier_name
utils.py
import asyncio import os from urllib.parse import urlparse import aiohttp def damerau_levenshtein(first_string, second_string): """Returns the Damerau-Levenshtein edit distance between two strings.""" previous = None prev_a = None current = [i for i, x in enumerate(second_string, 1)] + [0] for ...
def get(url, **kwargs): full_url = url + '&'.join(sorted('='.join(kv) for kv in kwargs.get('params', {}).items())) if full_url in RequestManager.current_requests: return RequestManager.current_requests[full_url].wait_for() r = RequestManager(url, **kwargs) RequestManager.current_requests[fu...
self.callbacks.append(asyncio.Future()) return self.callbacks[-1]
identifier_body
utils.py
import asyncio import os from urllib.parse import urlparse import aiohttp def damerau_levenshtein(first_string, second_string): """Returns the Damerau-Levenshtein edit distance between two strings.""" previous = None prev_a = None current = [i for i, x in enumerate(second_string, 1)] + [0] for ...
def wait_for(self): self.callbacks.append(asyncio.Future()) return self.callbacks[-1] def get(url, **kwargs): full_url = url + '&'.join(sorted('='.join(kv) for kv in kwargs.get('params', {}).items())) if full_url in RequestManager.current_requests: return RequestManager.current_...
cb.set_result((response, json))
conditional_block
log-edit.tsx
import React, { useState, useEffect, useCallback, useMemo } from 'react'; import { TMemo } from '@shared/components/TMemo'; import type { ChatLogItem } from '@shared/model/chat'; import styled from 'styled-components'; import { Row, Button, Checkbox, Modal, Form, Input, message } from 'antd'; import _pick from 'lodash/...
tName, setReportName] = useState(''); // 生成跑团战报 const createTRPGReport = useCallback(() => { const selectedLogs = logs .filter((log) => log.selected) // 获取选中的记录 .map((log) => _pick(log, reportLogRequireKey)); // 仅提取需要的字段 setModalLoading(true); createTRPGGameReport(reportName, playerUUID, g...
ome((x) => x === true); } }, [logs]); const [repor
conditional_block
log-edit.tsx
import React, { useState, useEffect, useCallback, useMemo } from 'react'; import { TMemo } from '@shared/components/TMemo'; import type { ChatLogItem } from '@shared/model/chat'; import styled from 'styled-components'; import { Row, Button, Checkbox, Modal, Form, Input, message } from 'antd'; import _pick from 'lodash/...
return ( <LogEditItem key={log.uuid} log={log} playerUUID={playerUUID} onSelect={() => handleSelect(index)} /> ); })} {logs.length > 0 ? ( <Row> <Button onClick={showModal} block={t...
{logs.map((log, index) => {
random_line_split
PaymentsTwoTone.js
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(
<React.Fragment><path d="M17 6H3v8h14V6zm-7 7c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3z" opacity=".3" /><path d="M17 4H3c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zM3 14V6h14v8H3z" /><path d="M10 7c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3zm13 0v11c0 1.1-.9 2-2 2H4v-2h17V7...
random_line_split
jodirectsend.component.ts
import {Component} from '@angular/core' import {JoDirectService, JoDirectResponse, JoDirectCode} from '../../services/jodirect.service' @Component({ selector: `jodirect-send-page`, template: ` <div id="parent"> <span [style.display]="itemDisplay">You can only send one message to a token, s...
} }
{ this.joDirectService.send(this.token, this.message).forEach((response: JoDirectResponse) => { if (response.status() === JoDirectCode.NO_ERROR) { this.itemDisplay = 'none' this.errorDisplay = 'none' this.successDisplay = 'block' ...
conditional_block
jodirectsend.component.ts
import {Component} from '@angular/core' import {JoDirectService, JoDirectResponse, JoDirectCode} from '../../services/jodirect.service' @Component({ selector: `jodirect-send-page`, template: ` <div id="parent"> <span [style.display]="itemDisplay">You can only send one message to a token, s...
export class JoDirectSendComponent { token = '' message = '' error = '' errorDisplay = 'none' itemDisplay = 'block' successDisplay = 'none' constructor(private joDirectService: JoDirectService) { } onSend() { this.error = '' this.errorDisplay = 'none' if (...
margin-top: 10px; margin-bottom: 10px; } `] })
random_line_split