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 |
---|---|---|---|---|
items.py | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from viaspider.settings import SUMMARY_LIMIT
class ViaspiderItem(scrapy.Item):
# define the fields for your item here like:
url = scrapy.Field()
title = scrapy.Field()
summary = scrapy.Field()
categories = scrapy.Field()
tags = scrapy.Field()
image = scrapy.Field()
source = scrapy.Field()
created = scrapy.Field()
class ItemParser(object):
def __init__(self, source, response, seperator, bloginfo):
self.source = source
self.response = response
self.seperator = seperator
self.bloginfo = " " + self.seperator + " " + bloginfo
@property
def url(self):
return self.response.url
@property
def title(self):
result = self.response.xpath('//head/title/text()').extract()[0].encode('utf-8')
if result.endswith(self.bloginfo):
return (self.seperator.join(result.split(self.seperator)[:-1])).strip()
else:
return result
@property
def summary(self):
result = self.response.xpath('//head/meta[@property="og:description"]/@content').extract()[0]
return result[:-(SUMMARY_LIMIT + 3)] + '...' if len(result) > SUMMARY_LIMIT else result
@property
def categories(self):
results = self.response.xpath('//head/meta[@property="article:section"]/@content').extract()
return results
@property
def tags(self):
results = self.response.xpath('//head/meta[@property="article:tag"]/@content').extract()
return results if len(results) > 0 else self.categories
@property
def image(self):
result = self.response.xpath('//head/meta[@property="og:image"]/@content').extract()[0]
return result
@property
def | (self):
result = self.response.xpath('//head/meta[@property="article:published_time"]/@content').extract()[0]
return result
def parse(self):
item = ViaspiderItem()
item['url'] = self.url
item['source'] = self.source
item['title'] = self.title
item['summary'] = self.summary
item['categories'] = self.categories
item['tags'] = self.tags
item['image'] = self.image
item['created'] = self.created
return item | created | identifier_name |
use-keyword.rs | // Copyright 2016 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that imports with nakes super and self don't fail during parsing |
mod a {
mod b {
use self as A;
//~^ ERROR `self` imports are only allowed within a { } list
use super as B;
//~^ ERROR unresolved import `super` [E0432]
//~| no `super` in the root
use super::{self as C};
//~^ ERROR unresolved import `super` [E0432]
//~| no `super` in the root
}
}
fn main() {} | // FIXME: this shouldn't fail during name resolution either | random_line_split |
use-keyword.rs | // Copyright 2016 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that imports with nakes super and self don't fail during parsing
// FIXME: this shouldn't fail during name resolution either
mod a {
mod b {
use self as A;
//~^ ERROR `self` imports are only allowed within a { } list
use super as B;
//~^ ERROR unresolved import `super` [E0432]
//~| no `super` in the root
use super::{self as C};
//~^ ERROR unresolved import `super` [E0432]
//~| no `super` in the root
}
}
fn | () {}
| main | identifier_name |
use-keyword.rs | // Copyright 2016 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that imports with nakes super and self don't fail during parsing
// FIXME: this shouldn't fail during name resolution either
mod a {
mod b {
use self as A;
//~^ ERROR `self` imports are only allowed within a { } list
use super as B;
//~^ ERROR unresolved import `super` [E0432]
//~| no `super` in the root
use super::{self as C};
//~^ ERROR unresolved import `super` [E0432]
//~| no `super` in the root
}
}
fn main() | {} | identifier_body |
|
plot_quantiles.py | #!/usr/bin/env python
"""
=================================================
Draw a Quantile-Quantile Plot and Confidence Band
=================================================
This is an example of drawing a quantile-quantile plot with a confidence level
(CL) band.
"""
print __doc__
import ROOT
from rootpy.interactive import wait
from rootpy.plotting import Hist, Canvas, Legend, set_style
from rootpy.plotting.contrib.quantiles import qqgraph
set_style('ATLAS')
c = Canvas(width=1200, height=600)
c.Divide(2, 1, 1e-3, 1e-3)
rand = ROOT.TRandom3()
h1 = Hist(100, -5, 5, name="h1", title="Histogram 1",
linecolor='red', legendstyle='l')
h2 = Hist(100, -5, 5, name="h2", title="Histogram 2",
linecolor='blue', legendstyle='l')
for ievt in xrange(10000):
|
pad = c.cd(1)
h1.Draw('hist')
h2.Draw('hist same')
leg = Legend([h1, h2], pad=pad, leftmargin=0.5,
topmargin=0.11, rightmargin=0.05,
textsize=20)
leg.Draw()
pad = c.cd(2)
gr = qqgraph(h1, h2)
gr.xaxis.title = h1.title
gr.yaxis.title = h2.title
gr.fillcolor = 17
gr.fillstyle = 'solid'
gr.linecolor = 17
gr.markercolor = 'darkred'
gr.markerstyle = 20
gr.title = "QQ with CL"
gr.Draw("ap")
x_min = gr.GetXaxis().GetXmin()
x_max = gr.GetXaxis().GetXmax()
y_min = gr.GetXaxis().GetXmin()
y_max = gr.GetXaxis().GetXmax()
gr.Draw('a3')
gr.Draw('Xp same')
# a straight line y=x to be a reference
f_dia = ROOT.TF1("f_dia", "x",
h1.GetXaxis().GetXmin(),
h1.GetXaxis().GetXmax())
f_dia.SetLineColor(9)
f_dia.SetLineWidth(2)
f_dia.SetLineStyle(2)
f_dia.Draw("same")
leg = Legend(3, pad=pad, leftmargin=0.45,
topmargin=0.45, rightmargin=0.05,
textsize=20)
leg.AddEntry(gr, "QQ points", "p")
leg.AddEntry(gr, "68% CL band", "f")
leg.AddEntry(f_dia, "Diagonal line", "l")
leg.Draw()
c.Modified()
c.Update()
c.Draw()
wait()
| h1.Fill(rand.Gaus(0, 0.8))
h2.Fill(rand.Gaus(0, 1)) | conditional_block |
plot_quantiles.py | #!/usr/bin/env python
"""
=================================================
Draw a Quantile-Quantile Plot and Confidence Band
=================================================
This is an example of drawing a quantile-quantile plot with a confidence level
(CL) band.
"""
print __doc__
import ROOT
from rootpy.interactive import wait
from rootpy.plotting import Hist, Canvas, Legend, set_style
from rootpy.plotting.contrib.quantiles import qqgraph
set_style('ATLAS')
c = Canvas(width=1200, height=600)
c.Divide(2, 1, 1e-3, 1e-3)
rand = ROOT.TRandom3()
h1 = Hist(100, -5, 5, name="h1", title="Histogram 1",
linecolor='red', legendstyle='l')
h2 = Hist(100, -5, 5, name="h2", title="Histogram 2",
linecolor='blue', legendstyle='l')
for ievt in xrange(10000):
h1.Fill(rand.Gaus(0, 0.8))
h2.Fill(rand.Gaus(0, 1))
pad = c.cd(1)
h1.Draw('hist')
h2.Draw('hist same')
leg = Legend([h1, h2], pad=pad, leftmargin=0.5,
topmargin=0.11, rightmargin=0.05,
textsize=20)
leg.Draw()
pad = c.cd(2)
gr = qqgraph(h1, h2)
gr.xaxis.title = h1.title
gr.yaxis.title = h2.title
gr.fillcolor = 17
gr.fillstyle = 'solid'
gr.linecolor = 17
gr.markercolor = 'darkred'
gr.markerstyle = 20
gr.title = "QQ with CL"
gr.Draw("ap")
x_min = gr.GetXaxis().GetXmin()
x_max = gr.GetXaxis().GetXmax()
y_min = gr.GetXaxis().GetXmin()
y_max = gr.GetXaxis().GetXmax()
gr.Draw('a3')
gr.Draw('Xp same')
# a straight line y=x to be a reference
f_dia = ROOT.TF1("f_dia", "x",
h1.GetXaxis().GetXmin(),
h1.GetXaxis().GetXmax())
f_dia.SetLineColor(9)
f_dia.SetLineWidth(2) | textsize=20)
leg.AddEntry(gr, "QQ points", "p")
leg.AddEntry(gr, "68% CL band", "f")
leg.AddEntry(f_dia, "Diagonal line", "l")
leg.Draw()
c.Modified()
c.Update()
c.Draw()
wait() | f_dia.SetLineStyle(2)
f_dia.Draw("same")
leg = Legend(3, pad=pad, leftmargin=0.45,
topmargin=0.45, rightmargin=0.05, | random_line_split |
externalUriOpenerService.ts | vs/base/common/arrays';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Iterable } from 'vs/base/common/iterator';
import { Disposable, IDisposable } from 'vs/base/common/lifecycle';
import { LinkedList } from 'vs/base/common/linkedList';
import { isWeb } from 'vs/base/common/platform';
import { URI } from 'vs/base/common/uri';
import * as languages from 'vs/editor/common/languages';
import * as nls from 'vs/nls';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ILogService } from 'vs/platform/log/common/log';
import { IExternalOpener, IOpenerService } from 'vs/platform/opener/common/opener';
import { IQuickInputService, IQuickPickItem, IQuickPickSeparator } from 'vs/platform/quickinput/common/quickInput';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { defaultExternalUriOpenerId, ExternalUriOpenersConfiguration, externalUriOpenersSettingId } from 'vs/workbench/contrib/externalUriOpener/common/configuration';
import { testUrlMatchesGlob } from 'vs/workbench/contrib/url/common/urlGlob';
import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences';
export const IExternalUriOpenerService = createDecorator<IExternalUriOpenerService>('externalUriOpenerService');
export interface IExternalOpenerProvider {
getOpeners(targetUri: URI): AsyncIterable<IExternalUriOpener>;
}
export interface IExternalUriOpener {
readonly id: string;
readonly label: string;
canOpen(uri: URI, token: CancellationToken): Promise<languages.ExternalUriOpenerPriority>;
openExternalUri(uri: URI, ctx: { sourceUri: URI }, token: CancellationToken): Promise<boolean>;
}
export interface IExternalUriOpenerService {
readonly _serviceBrand: undefined;
/**
* Registers a provider for external resources openers.
*/
registerExternalOpenerProvider(provider: IExternalOpenerProvider): IDisposable;
/**
* Get the configured IExternalUriOpener for the the uri.
* If there is no opener configured, then returns the first opener that can handle the uri.
*/
getOpener(uri: URI, ctx: { sourceUri: URI; preferredOpenerId?: string }, token: CancellationToken): Promise<IExternalUriOpener | undefined>;
}
export class ExternalUriOpenerService extends Disposable implements IExternalUriOpenerService, IExternalOpener {
public readonly _serviceBrand: undefined;
private readonly _providers = new LinkedList<IExternalOpenerProvider>();
constructor(
@IOpenerService openerService: IOpenerService,
@IStorageService storageService: IStorageService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@ILogService private readonly logService: ILogService,
@IPreferencesService private readonly preferencesService: IPreferencesService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
) {
super();
this._register(openerService.registerExternalOpener(this));
}
registerExternalOpenerProvider(provider: IExternalOpenerProvider): IDisposable {
const remove = this._providers.push(provider);
return { dispose: remove };
}
private async getOpeners(targetUri: URI, allowOptional: boolean, ctx: { sourceUri: URI; preferredOpenerId?: string }, token: CancellationToken): Promise<IExternalUriOpener[]> {
const allOpeners = await this.getAllOpenersForUri(targetUri);
if (allOpeners.size === 0) {
return [];
}
// First see if we have a preferredOpener
if (ctx.preferredOpenerId) {
if (ctx.preferredOpenerId === defaultExternalUriOpenerId) {
return [];
}
const preferredOpener = allOpeners.get(ctx.preferredOpenerId);
if (preferredOpener) {
// Skip the `canOpen` check here since the opener was specifically requested.
return [preferredOpener];
}
}
// Check to see if we have a configured opener
const configuredOpener = this.getConfiguredOpenerForUri(allOpeners, targetUri);
if (configuredOpener) {
// Skip the `canOpen` check here since the opener was specifically requested.
return configuredOpener === defaultExternalUriOpenerId ? [] : [configuredOpener];
}
// Then check to see if there is a valid opener
const validOpeners: Array<{ opener: IExternalUriOpener; priority: languages.ExternalUriOpenerPriority }> = [];
await Promise.all(Array.from(allOpeners.values()).map(async opener => {
let priority: languages.ExternalUriOpenerPriority;
try {
priority = await opener.canOpen(ctx.sourceUri, token);
} catch (e) {
this.logService.error(e);
return;
}
switch (priority) {
case languages.ExternalUriOpenerPriority.Option:
case languages.ExternalUriOpenerPriority.Default:
case languages.ExternalUriOpenerPriority.Preferred:
validOpeners.push({ opener, priority });
break;
}
}));
if (validOpeners.length === 0) {
return [];
}
// See if we have a preferred opener first
const preferred = firstOrDefault(validOpeners.filter(x => x.priority === languages.ExternalUriOpenerPriority.Preferred));
if (preferred) {
return [preferred.opener];
}
// See if we only have optional openers, use the default opener
if (!allowOptional && validOpeners.every(x => x.priority === languages.ExternalUriOpenerPriority.Option)) {
return [];
}
return validOpeners.map(value => value.opener);
}
async | (href: string, ctx: { sourceUri: URI; preferredOpenerId?: string }, token: CancellationToken): Promise<boolean> {
const targetUri = typeof href === 'string' ? URI.parse(href) : href;
const allOpeners = await this.getOpeners(targetUri, false, ctx, token);
if (allOpeners.length === 0) {
return false;
} else if (allOpeners.length === 1) {
return allOpeners[0].openExternalUri(targetUri, ctx, token);
}
// Otherwise prompt
return this.showOpenerPrompt(allOpeners, targetUri, ctx, token);
}
async getOpener(targetUri: URI, ctx: { sourceUri: URI; preferredOpenerId?: string }, token: CancellationToken): Promise<IExternalUriOpener | undefined> {
const allOpeners = await this.getOpeners(targetUri, true, ctx, token);
if (allOpeners.length >= 1) {
return allOpeners[0];
}
return undefined;
}
private async getAllOpenersForUri(targetUri: URI): Promise<Map<string, IExternalUriOpener>> {
const allOpeners = new Map<string, IExternalUriOpener>();
await Promise.all(Iterable.map(this._providers, async (provider) => {
for await (const opener of provider.getOpeners(targetUri)) {
allOpeners.set(opener.id, opener);
}
}));
return allOpeners;
}
private getConfiguredOpenerForUri(openers: Map<string, IExternalUriOpener>, targetUri: URI): IExternalUriOpener | 'default' | undefined {
const config = this.configurationService.getValue<ExternalUriOpenersConfiguration>(externalUriOpenersSettingId) || {};
for (const [uriGlob, id] of Object.entries(config)) {
if (testUrlMatchesGlob(targetUri.toString(), uriGlob)) {
if (id === defaultExternalUriOpenerId) {
return 'default';
}
const entry = openers.get(id);
if (entry) {
return entry;
}
}
}
return undefined;
}
private async showOpenerPrompt(
openers: ReadonlyArray<IExternalUriOpener>,
targetUri: URI,
ctx: { sourceUri: URI },
token: CancellationToken
): Promise<boolean> {
type PickItem = IQuickPickItem & { opener?: IExternalUriOpener | 'configureDefault' };
const items: Array<PickItem | IQuickPickSeparator> = openers.map((opener): PickItem => {
return {
label: opener.label,
opener: opener
};
});
items.push(
{
label: isWeb
? nls.localize('selectOpenerDefaultLabel.web', 'Open in new browser window')
: nls.localize('selectOpenerDefaultLabel', 'Open in default browser'),
opener: undefined
},
{ type: 'separator' },
{
label: nls.localize('selectOpenerConfigureTitle', "Configure default opener..."),
opener: 'configureDefault'
});
const picked = await this.quickInputService.pick(items, {
placeHolder: nls.localize('selectOpenerPlaceHolder', "How would you like to open: {0}", targetUri.toString())
});
if (!picked) {
// Still cancel the default opener here since we prompted the user
return true;
| openExternal | identifier_name |
externalUriOpenerService.ts | vs/base/common/arrays';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Iterable } from 'vs/base/common/iterator';
import { Disposable, IDisposable } from 'vs/base/common/lifecycle';
import { LinkedList } from 'vs/base/common/linkedList';
import { isWeb } from 'vs/base/common/platform';
import { URI } from 'vs/base/common/uri';
import * as languages from 'vs/editor/common/languages';
import * as nls from 'vs/nls';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ILogService } from 'vs/platform/log/common/log';
import { IExternalOpener, IOpenerService } from 'vs/platform/opener/common/opener';
import { IQuickInputService, IQuickPickItem, IQuickPickSeparator } from 'vs/platform/quickinput/common/quickInput';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { defaultExternalUriOpenerId, ExternalUriOpenersConfiguration, externalUriOpenersSettingId } from 'vs/workbench/contrib/externalUriOpener/common/configuration';
import { testUrlMatchesGlob } from 'vs/workbench/contrib/url/common/urlGlob';
import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences';
export const IExternalUriOpenerService = createDecorator<IExternalUriOpenerService>('externalUriOpenerService');
export interface IExternalOpenerProvider {
getOpeners(targetUri: URI): AsyncIterable<IExternalUriOpener>;
}
export interface IExternalUriOpener {
readonly id: string;
readonly label: string;
canOpen(uri: URI, token: CancellationToken): Promise<languages.ExternalUriOpenerPriority>;
openExternalUri(uri: URI, ctx: { sourceUri: URI }, token: CancellationToken): Promise<boolean>;
}
export interface IExternalUriOpenerService {
readonly _serviceBrand: undefined;
/**
* Registers a provider for external resources openers.
*/
registerExternalOpenerProvider(provider: IExternalOpenerProvider): IDisposable;
/**
* Get the configured IExternalUriOpener for the the uri.
* If there is no opener configured, then returns the first opener that can handle the uri.
*/
getOpener(uri: URI, ctx: { sourceUri: URI; preferredOpenerId?: string }, token: CancellationToken): Promise<IExternalUriOpener | undefined>;
}
export class ExternalUriOpenerService extends Disposable implements IExternalUriOpenerService, IExternalOpener {
public readonly _serviceBrand: undefined;
private readonly _providers = new LinkedList<IExternalOpenerProvider>();
constructor(
@IOpenerService openerService: IOpenerService,
@IStorageService storageService: IStorageService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@ILogService private readonly logService: ILogService,
@IPreferencesService private readonly preferencesService: IPreferencesService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
) {
super();
this._register(openerService.registerExternalOpener(this));
}
registerExternalOpenerProvider(provider: IExternalOpenerProvider): IDisposable {
const remove = this._providers.push(provider);
return { dispose: remove };
}
private async getOpeners(targetUri: URI, allowOptional: boolean, ctx: { sourceUri: URI; preferredOpenerId?: string }, token: CancellationToken): Promise<IExternalUriOpener[]> {
const allOpeners = await this.getAllOpenersForUri(targetUri);
if (allOpeners.size === 0) {
return [];
}
// First see if we have a preferredOpener
if (ctx.preferredOpenerId) {
if (ctx.preferredOpenerId === defaultExternalUriOpenerId) {
return [];
}
const preferredOpener = allOpeners.get(ctx.preferredOpenerId);
if (preferredOpener) {
// Skip the `canOpen` check here since the opener was specifically requested.
return [preferredOpener];
}
}
// Check to see if we have a configured opener
const configuredOpener = this.getConfiguredOpenerForUri(allOpeners, targetUri);
if (configuredOpener) {
// Skip the `canOpen` check here since the opener was specifically requested.
return configuredOpener === defaultExternalUriOpenerId ? [] : [configuredOpener];
}
// Then check to see if there is a valid opener
const validOpeners: Array<{ opener: IExternalUriOpener; priority: languages.ExternalUriOpenerPriority }> = [];
await Promise.all(Array.from(allOpeners.values()).map(async opener => {
let priority: languages.ExternalUriOpenerPriority;
try {
priority = await opener.canOpen(ctx.sourceUri, token);
} catch (e) {
this.logService.error(e);
return;
}
switch (priority) {
case languages.ExternalUriOpenerPriority.Option:
case languages.ExternalUriOpenerPriority.Default:
case languages.ExternalUriOpenerPriority.Preferred:
validOpeners.push({ opener, priority });
break;
}
}));
if (validOpeners.length === 0) {
return [];
}
// See if we have a preferred opener first
const preferred = firstOrDefault(validOpeners.filter(x => x.priority === languages.ExternalUriOpenerPriority.Preferred));
if (preferred) {
return [preferred.opener];
}
// See if we only have optional openers, use the default opener
if (!allowOptional && validOpeners.every(x => x.priority === languages.ExternalUriOpenerPriority.Option)) {
return [];
}
return validOpeners.map(value => value.opener);
}
async openExternal(href: string, ctx: { sourceUri: URI; preferredOpenerId?: string }, token: CancellationToken): Promise<boolean> { | const targetUri = typeof href === 'string' ? URI.parse(href) : href;
const allOpeners = await this.getOpeners(targetUri, false, ctx, token);
if (allOpeners.length === 0) {
return false;
} else if (allOpeners.length === 1) {
return allOpeners[0].openExternalUri(targetUri, ctx, token);
}
// Otherwise prompt
return this.showOpenerPrompt(allOpeners, targetUri, ctx, token);
}
async getOpener(targetUri: URI, ctx: { sourceUri: URI; preferredOpenerId?: string }, token: CancellationToken): Promise<IExternalUriOpener | undefined> {
const allOpeners = await this.getOpeners(targetUri, true, ctx, token);
if (allOpeners.length >= 1) {
return allOpeners[0];
}
return undefined;
}
private async getAllOpenersForUri(targetUri: URI): Promise<Map<string, IExternalUriOpener>> {
const allOpeners = new Map<string, IExternalUriOpener>();
await Promise.all(Iterable.map(this._providers, async (provider) => {
for await (const opener of provider.getOpeners(targetUri)) {
allOpeners.set(opener.id, opener);
}
}));
return allOpeners;
}
private getConfiguredOpenerForUri(openers: Map<string, IExternalUriOpener>, targetUri: URI): IExternalUriOpener | 'default' | undefined {
const config = this.configurationService.getValue<ExternalUriOpenersConfiguration>(externalUriOpenersSettingId) || {};
for (const [uriGlob, id] of Object.entries(config)) {
if (testUrlMatchesGlob(targetUri.toString(), uriGlob)) {
if (id === defaultExternalUriOpenerId) {
return 'default';
}
const entry = openers.get(id);
if (entry) {
return entry;
}
}
}
return undefined;
}
private async showOpenerPrompt(
openers: ReadonlyArray<IExternalUriOpener>,
targetUri: URI,
ctx: { sourceUri: URI },
token: CancellationToken
): Promise<boolean> {
type PickItem = IQuickPickItem & { opener?: IExternalUriOpener | 'configureDefault' };
const items: Array<PickItem | IQuickPickSeparator> = openers.map((opener): PickItem => {
return {
label: opener.label,
opener: opener
};
});
items.push(
{
label: isWeb
? nls.localize('selectOpenerDefaultLabel.web', 'Open in new browser window')
: nls.localize('selectOpenerDefaultLabel', 'Open in default browser'),
opener: undefined
},
{ type: 'separator' },
{
label: nls.localize('selectOpenerConfigureTitle', "Configure default opener..."),
opener: 'configureDefault'
});
const picked = await this.quickInputService.pick(items, {
placeHolder: nls.localize('selectOpenerPlaceHolder', "How would you like to open: {0}", targetUri.toString())
});
if (!picked) {
// Still cancel the default opener here since we prompted the user
return true;
}
| random_line_split |
|
externalUriOpenerService.ts | vs/base/common/arrays';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Iterable } from 'vs/base/common/iterator';
import { Disposable, IDisposable } from 'vs/base/common/lifecycle';
import { LinkedList } from 'vs/base/common/linkedList';
import { isWeb } from 'vs/base/common/platform';
import { URI } from 'vs/base/common/uri';
import * as languages from 'vs/editor/common/languages';
import * as nls from 'vs/nls';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ILogService } from 'vs/platform/log/common/log';
import { IExternalOpener, IOpenerService } from 'vs/platform/opener/common/opener';
import { IQuickInputService, IQuickPickItem, IQuickPickSeparator } from 'vs/platform/quickinput/common/quickInput';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { defaultExternalUriOpenerId, ExternalUriOpenersConfiguration, externalUriOpenersSettingId } from 'vs/workbench/contrib/externalUriOpener/common/configuration';
import { testUrlMatchesGlob } from 'vs/workbench/contrib/url/common/urlGlob';
import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences';
export const IExternalUriOpenerService = createDecorator<IExternalUriOpenerService>('externalUriOpenerService');
export interface IExternalOpenerProvider {
getOpeners(targetUri: URI): AsyncIterable<IExternalUriOpener>;
}
export interface IExternalUriOpener {
readonly id: string;
readonly label: string;
canOpen(uri: URI, token: CancellationToken): Promise<languages.ExternalUriOpenerPriority>;
openExternalUri(uri: URI, ctx: { sourceUri: URI }, token: CancellationToken): Promise<boolean>;
}
export interface IExternalUriOpenerService {
readonly _serviceBrand: undefined;
/**
* Registers a provider for external resources openers.
*/
registerExternalOpenerProvider(provider: IExternalOpenerProvider): IDisposable;
/**
* Get the configured IExternalUriOpener for the the uri.
* If there is no opener configured, then returns the first opener that can handle the uri.
*/
getOpener(uri: URI, ctx: { sourceUri: URI; preferredOpenerId?: string }, token: CancellationToken): Promise<IExternalUriOpener | undefined>;
}
export class ExternalUriOpenerService extends Disposable implements IExternalUriOpenerService, IExternalOpener {
public readonly _serviceBrand: undefined;
private readonly _providers = new LinkedList<IExternalOpenerProvider>();
constructor(
@IOpenerService openerService: IOpenerService,
@IStorageService storageService: IStorageService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@ILogService private readonly logService: ILogService,
@IPreferencesService private readonly preferencesService: IPreferencesService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
) {
super();
this._register(openerService.registerExternalOpener(this));
}
registerExternalOpenerProvider(provider: IExternalOpenerProvider): IDisposable {
const remove = this._providers.push(provider);
return { dispose: remove };
}
private async getOpeners(targetUri: URI, allowOptional: boolean, ctx: { sourceUri: URI; preferredOpenerId?: string }, token: CancellationToken): Promise<IExternalUriOpener[]> {
const allOpeners = await this.getAllOpenersForUri(targetUri);
if (allOpeners.size === 0) {
return [];
}
// First see if we have a preferredOpener
if (ctx.preferredOpenerId) {
if (ctx.preferredOpenerId === defaultExternalUriOpenerId) {
return [];
}
const preferredOpener = allOpeners.get(ctx.preferredOpenerId);
if (preferredOpener) {
// Skip the `canOpen` check here since the opener was specifically requested.
return [preferredOpener];
}
}
// Check to see if we have a configured opener
const configuredOpener = this.getConfiguredOpenerForUri(allOpeners, targetUri);
if (configuredOpener) {
// Skip the `canOpen` check here since the opener was specifically requested.
return configuredOpener === defaultExternalUriOpenerId ? [] : [configuredOpener];
}
// Then check to see if there is a valid opener
const validOpeners: Array<{ opener: IExternalUriOpener; priority: languages.ExternalUriOpenerPriority }> = [];
await Promise.all(Array.from(allOpeners.values()).map(async opener => {
let priority: languages.ExternalUriOpenerPriority;
try {
priority = await opener.canOpen(ctx.sourceUri, token);
} catch (e) {
this.logService.error(e);
return;
}
switch (priority) {
case languages.ExternalUriOpenerPriority.Option:
case languages.ExternalUriOpenerPriority.Default:
case languages.ExternalUriOpenerPriority.Preferred:
validOpeners.push({ opener, priority });
break;
}
}));
if (validOpeners.length === 0) {
return [];
}
// See if we have a preferred opener first
const preferred = firstOrDefault(validOpeners.filter(x => x.priority === languages.ExternalUriOpenerPriority.Preferred));
if (preferred) {
return [preferred.opener];
}
// See if we only have optional openers, use the default opener
if (!allowOptional && validOpeners.every(x => x.priority === languages.ExternalUriOpenerPriority.Option)) {
return [];
}
return validOpeners.map(value => value.opener);
}
async openExternal(href: string, ctx: { sourceUri: URI; preferredOpenerId?: string }, token: CancellationToken): Promise<boolean> {
const targetUri = typeof href === 'string' ? URI.parse(href) : href;
const allOpeners = await this.getOpeners(targetUri, false, ctx, token);
if (allOpeners.length === 0) {
return false;
} else if (allOpeners.length === 1) {
return allOpeners[0].openExternalUri(targetUri, ctx, token);
}
// Otherwise prompt
return this.showOpenerPrompt(allOpeners, targetUri, ctx, token);
}
async getOpener(targetUri: URI, ctx: { sourceUri: URI; preferredOpenerId?: string }, token: CancellationToken): Promise<IExternalUriOpener | undefined> {
const allOpeners = await this.getOpeners(targetUri, true, ctx, token);
if (allOpeners.length >= 1) {
return allOpeners[0];
}
return undefined;
}
private async getAllOpenersForUri(targetUri: URI): Promise<Map<string, IExternalUriOpener>> {
const allOpeners = new Map<string, IExternalUriOpener>();
await Promise.all(Iterable.map(this._providers, async (provider) => {
for await (const opener of provider.getOpeners(targetUri)) {
allOpeners.set(opener.id, opener);
}
}));
return allOpeners;
}
private getConfiguredOpenerForUri(openers: Map<string, IExternalUriOpener>, targetUri: URI): IExternalUriOpener | 'default' | undefined {
const config = this.configurationService.getValue<ExternalUriOpenersConfiguration>(externalUriOpenersSettingId) || {};
for (const [uriGlob, id] of Object.entries(config)) {
if (testUrlMatchesGlob(targetUri.toString(), uriGlob)) {
if (id === defaultExternalUriOpenerId) {
return 'default';
}
const entry = openers.get(id);
if (entry) |
}
}
return undefined;
}
private async showOpenerPrompt(
openers: ReadonlyArray<IExternalUriOpener>,
targetUri: URI,
ctx: { sourceUri: URI },
token: CancellationToken
): Promise<boolean> {
type PickItem = IQuickPickItem & { opener?: IExternalUriOpener | 'configureDefault' };
const items: Array<PickItem | IQuickPickSeparator> = openers.map((opener): PickItem => {
return {
label: opener.label,
opener: opener
};
});
items.push(
{
label: isWeb
? nls.localize('selectOpenerDefaultLabel.web', 'Open in new browser window')
: nls.localize('selectOpenerDefaultLabel', 'Open in default browser'),
opener: undefined
},
{ type: 'separator' },
{
label: nls.localize('selectOpenerConfigureTitle', "Configure default opener..."),
opener: 'configureDefault'
});
const picked = await this.quickInputService.pick(items, {
placeHolder: nls.localize('selectOpenerPlaceHolder', "How would you like to open: {0}", targetUri.toString())
});
if (!picked) {
// Still cancel the default opener here since we prompted the user
return true;
| {
return entry;
} | conditional_block |
externalUriOpenerService.ts | vs/base/common/arrays';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Iterable } from 'vs/base/common/iterator';
import { Disposable, IDisposable } from 'vs/base/common/lifecycle';
import { LinkedList } from 'vs/base/common/linkedList';
import { isWeb } from 'vs/base/common/platform';
import { URI } from 'vs/base/common/uri';
import * as languages from 'vs/editor/common/languages';
import * as nls from 'vs/nls';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ILogService } from 'vs/platform/log/common/log';
import { IExternalOpener, IOpenerService } from 'vs/platform/opener/common/opener';
import { IQuickInputService, IQuickPickItem, IQuickPickSeparator } from 'vs/platform/quickinput/common/quickInput';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { defaultExternalUriOpenerId, ExternalUriOpenersConfiguration, externalUriOpenersSettingId } from 'vs/workbench/contrib/externalUriOpener/common/configuration';
import { testUrlMatchesGlob } from 'vs/workbench/contrib/url/common/urlGlob';
import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences';
export const IExternalUriOpenerService = createDecorator<IExternalUriOpenerService>('externalUriOpenerService');
export interface IExternalOpenerProvider {
getOpeners(targetUri: URI): AsyncIterable<IExternalUriOpener>;
}
export interface IExternalUriOpener {
readonly id: string;
readonly label: string;
canOpen(uri: URI, token: CancellationToken): Promise<languages.ExternalUriOpenerPriority>;
openExternalUri(uri: URI, ctx: { sourceUri: URI }, token: CancellationToken): Promise<boolean>;
}
export interface IExternalUriOpenerService {
readonly _serviceBrand: undefined;
/**
* Registers a provider for external resources openers.
*/
registerExternalOpenerProvider(provider: IExternalOpenerProvider): IDisposable;
/**
* Get the configured IExternalUriOpener for the the uri.
* If there is no opener configured, then returns the first opener that can handle the uri.
*/
getOpener(uri: URI, ctx: { sourceUri: URI; preferredOpenerId?: string }, token: CancellationToken): Promise<IExternalUriOpener | undefined>;
}
export class ExternalUriOpenerService extends Disposable implements IExternalUriOpenerService, IExternalOpener {
public readonly _serviceBrand: undefined;
private readonly _providers = new LinkedList<IExternalOpenerProvider>();
constructor(
@IOpenerService openerService: IOpenerService,
@IStorageService storageService: IStorageService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@ILogService private readonly logService: ILogService,
@IPreferencesService private readonly preferencesService: IPreferencesService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
) |
registerExternalOpenerProvider(provider: IExternalOpenerProvider): IDisposable {
const remove = this._providers.push(provider);
return { dispose: remove };
}
private async getOpeners(targetUri: URI, allowOptional: boolean, ctx: { sourceUri: URI; preferredOpenerId?: string }, token: CancellationToken): Promise<IExternalUriOpener[]> {
const allOpeners = await this.getAllOpenersForUri(targetUri);
if (allOpeners.size === 0) {
return [];
}
// First see if we have a preferredOpener
if (ctx.preferredOpenerId) {
if (ctx.preferredOpenerId === defaultExternalUriOpenerId) {
return [];
}
const preferredOpener = allOpeners.get(ctx.preferredOpenerId);
if (preferredOpener) {
// Skip the `canOpen` check here since the opener was specifically requested.
return [preferredOpener];
}
}
// Check to see if we have a configured opener
const configuredOpener = this.getConfiguredOpenerForUri(allOpeners, targetUri);
if (configuredOpener) {
// Skip the `canOpen` check here since the opener was specifically requested.
return configuredOpener === defaultExternalUriOpenerId ? [] : [configuredOpener];
}
// Then check to see if there is a valid opener
const validOpeners: Array<{ opener: IExternalUriOpener; priority: languages.ExternalUriOpenerPriority }> = [];
await Promise.all(Array.from(allOpeners.values()).map(async opener => {
let priority: languages.ExternalUriOpenerPriority;
try {
priority = await opener.canOpen(ctx.sourceUri, token);
} catch (e) {
this.logService.error(e);
return;
}
switch (priority) {
case languages.ExternalUriOpenerPriority.Option:
case languages.ExternalUriOpenerPriority.Default:
case languages.ExternalUriOpenerPriority.Preferred:
validOpeners.push({ opener, priority });
break;
}
}));
if (validOpeners.length === 0) {
return [];
}
// See if we have a preferred opener first
const preferred = firstOrDefault(validOpeners.filter(x => x.priority === languages.ExternalUriOpenerPriority.Preferred));
if (preferred) {
return [preferred.opener];
}
// See if we only have optional openers, use the default opener
if (!allowOptional && validOpeners.every(x => x.priority === languages.ExternalUriOpenerPriority.Option)) {
return [];
}
return validOpeners.map(value => value.opener);
}
async openExternal(href: string, ctx: { sourceUri: URI; preferredOpenerId?: string }, token: CancellationToken): Promise<boolean> {
const targetUri = typeof href === 'string' ? URI.parse(href) : href;
const allOpeners = await this.getOpeners(targetUri, false, ctx, token);
if (allOpeners.length === 0) {
return false;
} else if (allOpeners.length === 1) {
return allOpeners[0].openExternalUri(targetUri, ctx, token);
}
// Otherwise prompt
return this.showOpenerPrompt(allOpeners, targetUri, ctx, token);
}
async getOpener(targetUri: URI, ctx: { sourceUri: URI; preferredOpenerId?: string }, token: CancellationToken): Promise<IExternalUriOpener | undefined> {
const allOpeners = await this.getOpeners(targetUri, true, ctx, token);
if (allOpeners.length >= 1) {
return allOpeners[0];
}
return undefined;
}
private async getAllOpenersForUri(targetUri: URI): Promise<Map<string, IExternalUriOpener>> {
const allOpeners = new Map<string, IExternalUriOpener>();
await Promise.all(Iterable.map(this._providers, async (provider) => {
for await (const opener of provider.getOpeners(targetUri)) {
allOpeners.set(opener.id, opener);
}
}));
return allOpeners;
}
private getConfiguredOpenerForUri(openers: Map<string, IExternalUriOpener>, targetUri: URI): IExternalUriOpener | 'default' | undefined {
const config = this.configurationService.getValue<ExternalUriOpenersConfiguration>(externalUriOpenersSettingId) || {};
for (const [uriGlob, id] of Object.entries(config)) {
if (testUrlMatchesGlob(targetUri.toString(), uriGlob)) {
if (id === defaultExternalUriOpenerId) {
return 'default';
}
const entry = openers.get(id);
if (entry) {
return entry;
}
}
}
return undefined;
}
private async showOpenerPrompt(
openers: ReadonlyArray<IExternalUriOpener>,
targetUri: URI,
ctx: { sourceUri: URI },
token: CancellationToken
): Promise<boolean> {
type PickItem = IQuickPickItem & { opener?: IExternalUriOpener | 'configureDefault' };
const items: Array<PickItem | IQuickPickSeparator> = openers.map((opener): PickItem => {
return {
label: opener.label,
opener: opener
};
});
items.push(
{
label: isWeb
? nls.localize('selectOpenerDefaultLabel.web', 'Open in new browser window')
: nls.localize('selectOpenerDefaultLabel', 'Open in default browser'),
opener: undefined
},
{ type: 'separator' },
{
label: nls.localize('selectOpenerConfigureTitle', "Configure default opener..."),
opener: 'configureDefault'
});
const picked = await this.quickInputService.pick(items, {
placeHolder: nls.localize('selectOpenerPlaceHolder', "How would you like to open: {0}", targetUri.toString())
});
if (!picked) {
// Still cancel the default opener here since we prompted the user
return true;
| {
super();
this._register(openerService.registerExternalOpener(this));
} | identifier_body |
analysis.py | #
# Copyright (C) 2013 Stanislav Bohm
#
# This file is part of Kaira.
#
# Kaira 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, version 3 of the License, or
# (at your option) any later version.
#
# Kaira 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Kaira. If not, see <http://www.gnu.org/licenses/>.
#
import utils
def all_free_variables(edges):
return utils.unions(edges, lambda edge: edge.get_free_vars())
def get_variable_sources(inscriptions):
sources = {}
for inscription in inscriptions:
|
return sources
def is_dependant(inscription1, inscription2):
if inscription1.edge is inscription2.edge and \
inscription2.index < inscription1.index:
return True
if not inscription2.is_expr_variable():
return False
return inscription2.expr in inscription1.get_foreign_variables()
def analyze_transition(tr):
variable_sources = {} # string -> uid - which inscriptions carry input variables
reuse_tokens = {} # uid -> uid - identification number of token for output inscpription
fresh_tokens = [] # (uid, type) - what tokens has to be created for output
used_tokens = [] # [uid] - Tokens from input inscriptions that are reused on output
variable_sources_out = {} # string -> uid or None
bulk_overtake = [] # [uid]
overtaken_variables = set()
def inscription_out_weight(inscription):
# Reorder edges, bulk edges first because we want them send first
# Otherwise it can cause problems like in sending results in "workers" example
s = inscription.config.get("seq")
if s is None:
seq = 0
else:
seq = int(s) * 3
if inscription.is_bulk():
return seq
# Unconditional edges has higher priority
if inscription.is_conditioned():
return seq + 2
else:
return seq + 1
def inscription_in_weight(inscription):
if inscription.is_conditioned():
return 1
else:
return 0
inscriptions_in = sum((edge.inscriptions for edge in tr.edges_in), [])
inscriptions_in.sort(key=inscription_in_weight)
inscriptions_out = sum((edge.inscriptions for edge in tr.edges_out), [])
inscriptions_out.sort(key=inscription_out_weight)
variable_sources = get_variable_sources(inscriptions_in)
# Order input inscriptions by variable dependancy
inscriptions_in = utils.topological_ordering(inscriptions_in, is_dependant)
if inscriptions_in is None:
raise utils.PtpException("Circle variable dependancy", tr.get_source())
# Try reuse tokens
for inscription in inscriptions_out:
if inscription.is_bulk() or not inscription.is_local():
continue # Bulk and nonlocal edge cannot use token reusage
if not inscription.is_expr_variable():
continue # Current implementation reuses tokens only for variable expression
if inscription.is_collective():
continue # Collective operations cannot use token reusage
token_uid = variable_sources.get(inscription.expr)
if token_uid is None or token_uid in used_tokens:
# Variable is not taken from input as token
# or token is already reused --> reusage not possible
continue
reuse_tokens[inscription.uid] = token_uid
used_tokens.append(token_uid)
# Setup fresh variables where token was not reused
for inscription in inscriptions_out:
if not inscription.is_expr_variable():
continue # We are interested only in variables
variable = inscription.expr
if variable in variable_sources:
# Variable take from input so we do not have to deal here with it
continue
if variable in variable_sources_out:
# Variable already prepared for output
continue
if inscription.is_bulk():
# No token, just build variable
variable_sources_out[variable] = None
continue
if inscription.is_local():
# Local send, we prepare token
fresh_tokens.append((inscription.uid, inscription.edge.place.type))
variable_sources_out[variable] = inscription.uid
reuse_tokens[inscription.uid] = inscription.uid # Use this fresh new token
else:
# Just create variable
variable_sources_out[variable] = None
for inscription in reversed(inscriptions_out):
# Now we are checking overtake. It has to be in reversed order
# becacase overtake has to be the last operation on variable
if not inscription.is_bulk() or not inscription.is_expr_variable():
continue # We are interested only in variables and bulk inscriptions
if inscription.expr not in overtaken_variables:
overtaken_variables.add(inscription.expr)
bulk_overtake.append(inscription.uid)
for inscription in inscriptions_out:
for variable in inscription.get_other_variables():
if variable not in variable_sources and \
variable not in variable_sources_out:
variable_sources_out[variable] = None
tr.inscriptions_in = inscriptions_in
tr.inscriptions_out = inscriptions_out
tr.variable_sources = variable_sources
tr.reuse_tokens = reuse_tokens
tr.variable_sources_out = variable_sources_out
tr.fresh_tokens = fresh_tokens
tr.bulk_overtake = bulk_overtake
| if not inscription.is_expr_variable():
continue
if sources.get(inscription.expr):
continue
if inscription.is_bulk():
sources[inscription.expr] = None
else:
sources[inscription.expr] = inscription.uid | conditional_block |
analysis.py | #
# Copyright (C) 2013 Stanislav Bohm
#
# This file is part of Kaira.
#
# Kaira 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, version 3 of the License, or
# (at your option) any later version.
#
# Kaira 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Kaira. If not, see <http://www.gnu.org/licenses/>.
#
import utils
def all_free_variables(edges):
return utils.unions(edges, lambda edge: edge.get_free_vars())
def get_variable_sources(inscriptions):
sources = {}
for inscription in inscriptions:
if not inscription.is_expr_variable():
continue
if sources.get(inscription.expr):
continue
if inscription.is_bulk():
sources[inscription.expr] = None
else:
sources[inscription.expr] = inscription.uid
return sources
def is_dependant(inscription1, inscription2):
if inscription1.edge is inscription2.edge and \
inscription2.index < inscription1.index:
return True
if not inscription2.is_expr_variable():
return False
return inscription2.expr in inscription1.get_foreign_variables()
def analyze_transition(tr):
variable_sources = {} # string -> uid - which inscriptions carry input variables
reuse_tokens = {} # uid -> uid - identification number of token for output inscpription
fresh_tokens = [] # (uid, type) - what tokens has to be created for output
used_tokens = [] # [uid] - Tokens from input inscriptions that are reused on output
variable_sources_out = {} # string -> uid or None
bulk_overtake = [] # [uid]
overtaken_variables = set()
def inscription_out_weight(inscription):
# Reorder edges, bulk edges first because we want them send first
# Otherwise it can cause problems like in sending results in "workers" example
s = inscription.config.get("seq")
if s is None:
seq = 0
else:
seq = int(s) * 3
if inscription.is_bulk():
return seq
# Unconditional edges has higher priority
if inscription.is_conditioned():
return seq + 2
else:
return seq + 1
def inscription_in_weight(inscription):
if inscription.is_conditioned():
return 1
else:
return 0
inscriptions_in = sum((edge.inscriptions for edge in tr.edges_in), [])
inscriptions_in.sort(key=inscription_in_weight)
inscriptions_out = sum((edge.inscriptions for edge in tr.edges_out), [])
inscriptions_out.sort(key=inscription_out_weight)
variable_sources = get_variable_sources(inscriptions_in)
# Order input inscriptions by variable dependancy
inscriptions_in = utils.topological_ordering(inscriptions_in, is_dependant)
if inscriptions_in is None:
raise utils.PtpException("Circle variable dependancy", tr.get_source())
# Try reuse tokens
for inscription in inscriptions_out:
if inscription.is_bulk() or not inscription.is_local():
continue # Bulk and nonlocal edge cannot use token reusage
if not inscription.is_expr_variable():
continue # Current implementation reuses tokens only for variable expression
if inscription.is_collective():
continue # Collective operations cannot use token reusage
token_uid = variable_sources.get(inscription.expr)
if token_uid is None or token_uid in used_tokens:
# Variable is not taken from input as token
# or token is already reused --> reusage not possible
continue
reuse_tokens[inscription.uid] = token_uid
used_tokens.append(token_uid)
# Setup fresh variables where token was not reused
for inscription in inscriptions_out:
if not inscription.is_expr_variable(): | continue
if variable in variable_sources_out:
# Variable already prepared for output
continue
if inscription.is_bulk():
# No token, just build variable
variable_sources_out[variable] = None
continue
if inscription.is_local():
# Local send, we prepare token
fresh_tokens.append((inscription.uid, inscription.edge.place.type))
variable_sources_out[variable] = inscription.uid
reuse_tokens[inscription.uid] = inscription.uid # Use this fresh new token
else:
# Just create variable
variable_sources_out[variable] = None
for inscription in reversed(inscriptions_out):
# Now we are checking overtake. It has to be in reversed order
# becacase overtake has to be the last operation on variable
if not inscription.is_bulk() or not inscription.is_expr_variable():
continue # We are interested only in variables and bulk inscriptions
if inscription.expr not in overtaken_variables:
overtaken_variables.add(inscription.expr)
bulk_overtake.append(inscription.uid)
for inscription in inscriptions_out:
for variable in inscription.get_other_variables():
if variable not in variable_sources and \
variable not in variable_sources_out:
variable_sources_out[variable] = None
tr.inscriptions_in = inscriptions_in
tr.inscriptions_out = inscriptions_out
tr.variable_sources = variable_sources
tr.reuse_tokens = reuse_tokens
tr.variable_sources_out = variable_sources_out
tr.fresh_tokens = fresh_tokens
tr.bulk_overtake = bulk_overtake | continue # We are interested only in variables
variable = inscription.expr
if variable in variable_sources:
# Variable take from input so we do not have to deal here with it | random_line_split |
analysis.py | #
# Copyright (C) 2013 Stanislav Bohm
#
# This file is part of Kaira.
#
# Kaira 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, version 3 of the License, or
# (at your option) any later version.
#
# Kaira 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Kaira. If not, see <http://www.gnu.org/licenses/>.
#
import utils
def all_free_variables(edges):
return utils.unions(edges, lambda edge: edge.get_free_vars())
def get_variable_sources(inscriptions):
sources = {}
for inscription in inscriptions:
if not inscription.is_expr_variable():
continue
if sources.get(inscription.expr):
continue
if inscription.is_bulk():
sources[inscription.expr] = None
else:
sources[inscription.expr] = inscription.uid
return sources
def is_dependant(inscription1, inscription2):
if inscription1.edge is inscription2.edge and \
inscription2.index < inscription1.index:
return True
if not inscription2.is_expr_variable():
return False
return inscription2.expr in inscription1.get_foreign_variables()
def | (tr):
variable_sources = {} # string -> uid - which inscriptions carry input variables
reuse_tokens = {} # uid -> uid - identification number of token for output inscpription
fresh_tokens = [] # (uid, type) - what tokens has to be created for output
used_tokens = [] # [uid] - Tokens from input inscriptions that are reused on output
variable_sources_out = {} # string -> uid or None
bulk_overtake = [] # [uid]
overtaken_variables = set()
def inscription_out_weight(inscription):
# Reorder edges, bulk edges first because we want them send first
# Otherwise it can cause problems like in sending results in "workers" example
s = inscription.config.get("seq")
if s is None:
seq = 0
else:
seq = int(s) * 3
if inscription.is_bulk():
return seq
# Unconditional edges has higher priority
if inscription.is_conditioned():
return seq + 2
else:
return seq + 1
def inscription_in_weight(inscription):
if inscription.is_conditioned():
return 1
else:
return 0
inscriptions_in = sum((edge.inscriptions for edge in tr.edges_in), [])
inscriptions_in.sort(key=inscription_in_weight)
inscriptions_out = sum((edge.inscriptions for edge in tr.edges_out), [])
inscriptions_out.sort(key=inscription_out_weight)
variable_sources = get_variable_sources(inscriptions_in)
# Order input inscriptions by variable dependancy
inscriptions_in = utils.topological_ordering(inscriptions_in, is_dependant)
if inscriptions_in is None:
raise utils.PtpException("Circle variable dependancy", tr.get_source())
# Try reuse tokens
for inscription in inscriptions_out:
if inscription.is_bulk() or not inscription.is_local():
continue # Bulk and nonlocal edge cannot use token reusage
if not inscription.is_expr_variable():
continue # Current implementation reuses tokens only for variable expression
if inscription.is_collective():
continue # Collective operations cannot use token reusage
token_uid = variable_sources.get(inscription.expr)
if token_uid is None or token_uid in used_tokens:
# Variable is not taken from input as token
# or token is already reused --> reusage not possible
continue
reuse_tokens[inscription.uid] = token_uid
used_tokens.append(token_uid)
# Setup fresh variables where token was not reused
for inscription in inscriptions_out:
if not inscription.is_expr_variable():
continue # We are interested only in variables
variable = inscription.expr
if variable in variable_sources:
# Variable take from input so we do not have to deal here with it
continue
if variable in variable_sources_out:
# Variable already prepared for output
continue
if inscription.is_bulk():
# No token, just build variable
variable_sources_out[variable] = None
continue
if inscription.is_local():
# Local send, we prepare token
fresh_tokens.append((inscription.uid, inscription.edge.place.type))
variable_sources_out[variable] = inscription.uid
reuse_tokens[inscription.uid] = inscription.uid # Use this fresh new token
else:
# Just create variable
variable_sources_out[variable] = None
for inscription in reversed(inscriptions_out):
# Now we are checking overtake. It has to be in reversed order
# becacase overtake has to be the last operation on variable
if not inscription.is_bulk() or not inscription.is_expr_variable():
continue # We are interested only in variables and bulk inscriptions
if inscription.expr not in overtaken_variables:
overtaken_variables.add(inscription.expr)
bulk_overtake.append(inscription.uid)
for inscription in inscriptions_out:
for variable in inscription.get_other_variables():
if variable not in variable_sources and \
variable not in variable_sources_out:
variable_sources_out[variable] = None
tr.inscriptions_in = inscriptions_in
tr.inscriptions_out = inscriptions_out
tr.variable_sources = variable_sources
tr.reuse_tokens = reuse_tokens
tr.variable_sources_out = variable_sources_out
tr.fresh_tokens = fresh_tokens
tr.bulk_overtake = bulk_overtake
| analyze_transition | identifier_name |
analysis.py | #
# Copyright (C) 2013 Stanislav Bohm
#
# This file is part of Kaira.
#
# Kaira 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, version 3 of the License, or
# (at your option) any later version.
#
# Kaira 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Kaira. If not, see <http://www.gnu.org/licenses/>.
#
import utils
def all_free_variables(edges):
return utils.unions(edges, lambda edge: edge.get_free_vars())
def get_variable_sources(inscriptions):
sources = {}
for inscription in inscriptions:
if not inscription.is_expr_variable():
continue
if sources.get(inscription.expr):
continue
if inscription.is_bulk():
sources[inscription.expr] = None
else:
sources[inscription.expr] = inscription.uid
return sources
def is_dependant(inscription1, inscription2):
if inscription1.edge is inscription2.edge and \
inscription2.index < inscription1.index:
return True
if not inscription2.is_expr_variable():
return False
return inscription2.expr in inscription1.get_foreign_variables()
def analyze_transition(tr):
variable_sources = {} # string -> uid - which inscriptions carry input variables
reuse_tokens = {} # uid -> uid - identification number of token for output inscpription
fresh_tokens = [] # (uid, type) - what tokens has to be created for output
used_tokens = [] # [uid] - Tokens from input inscriptions that are reused on output
variable_sources_out = {} # string -> uid or None
bulk_overtake = [] # [uid]
overtaken_variables = set()
def inscription_out_weight(inscription):
# Reorder edges, bulk edges first because we want them send first
# Otherwise it can cause problems like in sending results in "workers" example
|
def inscription_in_weight(inscription):
if inscription.is_conditioned():
return 1
else:
return 0
inscriptions_in = sum((edge.inscriptions for edge in tr.edges_in), [])
inscriptions_in.sort(key=inscription_in_weight)
inscriptions_out = sum((edge.inscriptions for edge in tr.edges_out), [])
inscriptions_out.sort(key=inscription_out_weight)
variable_sources = get_variable_sources(inscriptions_in)
# Order input inscriptions by variable dependancy
inscriptions_in = utils.topological_ordering(inscriptions_in, is_dependant)
if inscriptions_in is None:
raise utils.PtpException("Circle variable dependancy", tr.get_source())
# Try reuse tokens
for inscription in inscriptions_out:
if inscription.is_bulk() or not inscription.is_local():
continue # Bulk and nonlocal edge cannot use token reusage
if not inscription.is_expr_variable():
continue # Current implementation reuses tokens only for variable expression
if inscription.is_collective():
continue # Collective operations cannot use token reusage
token_uid = variable_sources.get(inscription.expr)
if token_uid is None or token_uid in used_tokens:
# Variable is not taken from input as token
# or token is already reused --> reusage not possible
continue
reuse_tokens[inscription.uid] = token_uid
used_tokens.append(token_uid)
# Setup fresh variables where token was not reused
for inscription in inscriptions_out:
if not inscription.is_expr_variable():
continue # We are interested only in variables
variable = inscription.expr
if variable in variable_sources:
# Variable take from input so we do not have to deal here with it
continue
if variable in variable_sources_out:
# Variable already prepared for output
continue
if inscription.is_bulk():
# No token, just build variable
variable_sources_out[variable] = None
continue
if inscription.is_local():
# Local send, we prepare token
fresh_tokens.append((inscription.uid, inscription.edge.place.type))
variable_sources_out[variable] = inscription.uid
reuse_tokens[inscription.uid] = inscription.uid # Use this fresh new token
else:
# Just create variable
variable_sources_out[variable] = None
for inscription in reversed(inscriptions_out):
# Now we are checking overtake. It has to be in reversed order
# becacase overtake has to be the last operation on variable
if not inscription.is_bulk() or not inscription.is_expr_variable():
continue # We are interested only in variables and bulk inscriptions
if inscription.expr not in overtaken_variables:
overtaken_variables.add(inscription.expr)
bulk_overtake.append(inscription.uid)
for inscription in inscriptions_out:
for variable in inscription.get_other_variables():
if variable not in variable_sources and \
variable not in variable_sources_out:
variable_sources_out[variable] = None
tr.inscriptions_in = inscriptions_in
tr.inscriptions_out = inscriptions_out
tr.variable_sources = variable_sources
tr.reuse_tokens = reuse_tokens
tr.variable_sources_out = variable_sources_out
tr.fresh_tokens = fresh_tokens
tr.bulk_overtake = bulk_overtake
| s = inscription.config.get("seq")
if s is None:
seq = 0
else:
seq = int(s) * 3
if inscription.is_bulk():
return seq
# Unconditional edges has higher priority
if inscription.is_conditioned():
return seq + 2
else:
return seq + 1 | identifier_body |
plist.js | /*
* Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com)
*
* openAUSIAS: The stunning micro-library that helps you to develop easily
* AJAX web applications by using Java and jQuery
* openAUSIAS is distributed under the MIT License (MIT)
* Sources at https://github.com/rafaelaznar/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
'use strict';
/* Controllers */
moduloTipoempleado.controller('TipoempleadoPListController', ['$scope', '$routeParams', 'serverService', '$location',
function ($scope, $routeParams, serverService, $location) {
$scope.visibles = {};
$scope.visibles.id = true;
$scope.visibles.cargo = true;
$scope.ob = "tipoempleado";
$scope.op = "plist";
$scope.title = "Listado de tipos de empleados";
$scope.icon = "fa-user-secret";
$scope.neighbourhood = 2;
if (!$routeParams.page) {
$routeParams.page = 1;
}
if (!$routeParams.rpp) {
$routeParams.rpp = 10;
}
$scope.numpage = $routeParams.page;
$scope.rpp = $routeParams.rpp;;
$scope.order = "";
$scope.ordervalue = "";
$scope.filter = "id";
$scope.filteroperator = "like";
$scope.filtervalue = "";
$scope.systemfilter = "";
$scope.systemfilteroperator = "";
$scope.systemfiltervalue = "";
$scope.params = "";
$scope.paramsWithoutOrder = "";
$scope.paramsWithoutFilter = "";
$scope.paramsWithoutSystemFilter = "";
if ($routeParams.order && $routeParams.ordervalue) {
$scope.order = $routeParams.order;
$scope.ordervalue = $routeParams.ordervalue;
$scope.orderParams = "&order=" + $routeParams.order + "&ordervalue=" + $routeParams.ordervalue;
$scope.paramsWithoutFilter += $scope.orderParams;
$scope.paramsWithoutSystemFilter += $scope.orderParams;
} else {
$scope.orderParams = "";
}
if ($routeParams.filter && $routeParams.filteroperator && $routeParams.filtervalue) | else {
$scope.filterParams = "";
}
if ($routeParams.systemfilter && $routeParams.systemfilteroperator && $routeParams.systemfiltervalue) {
$scope.systemFilterParams = "&systemfilter=" + $routeParams.systemfilter + "&systemfilteroperator=" + $routeParams.systemfilteroperator + "&systemfiltervalue=" + $routeParams.systemfiltervalue;
$scope.paramsWithoutOrder += $scope.systemFilterParams;
$scope.paramsWithoutFilter += $scope.systemFilterParams;
} else {
$scope.systemFilterParams = "";
}
$scope.params = ($scope.orderParams + $scope.filterParams + $scope.systemFilterParams);
$scope.params = $scope.params.replace('&', '?');
serverService.getDataFromPromise(serverService.promise_getSome($scope.ob, $scope.rpp, $scope.numpage, $scope.filterParams, $scope.orderParams, $scope.systemFilterParams)).then(function (data) {
if (data.status != 200) {
$scope.status = "Error en la recepción de datos del servidor";
} else {
$scope.pages = data.message.pages.message;
if (parseInt($scope.numpage) > parseInt($scope.pages))
$scope.numpage = $scope.pages;
$scope.page = data.message.page.message;
$scope.registers = data.message.registers.message;
$scope.status = "";
}
});
$scope.getRangeArray = function (lowEnd, highEnd) {
var rangeArray = [];
for (var i = lowEnd; i <= highEnd; i++) {
rangeArray.push(i);
}
return rangeArray;
};
$scope.evaluateMin = function (lowEnd, highEnd) {
return Math.min(lowEnd, highEnd);
};
$scope.evaluateMax = function (lowEnd, highEnd) {
return Math.max(lowEnd, highEnd);
};
$scope.dofilter = function () {
if ($scope.filter != "" && $scope.filteroperator != "" && $scope.filtervalue != "") {
if ($routeParams.order && $routeParams.ordervalue) {
if ($routeParams.systemfilter && $routeParams.systemfilteroperator) {
$location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue).search('order', $routeParams.order).search('ordervalue', $routeParams.ordervalue).search('systemfilter', $routeParams.systemfilter).search('systemfilteroperator', $routeParams.systemfilteroperator).search('systemfiltervalue', $routeParams.systemfiltervalue);
} else {
$location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue).search('order', $routeParams.order).search('ordervalue', $routeParams.ordervalue);
}
} else {
$location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue);
}
}
return false;
};
}]); | {
$scope.filter = $routeParams.filter;
$scope.filteroperator = $routeParams.filteroperator;
$scope.filtervalue = $routeParams.filtervalue;
$scope.filterParams = "&filter=" + $routeParams.filter + "&filteroperator=" + $routeParams.filteroperator + "&filtervalue=" + $routeParams.filtervalue;
$scope.paramsWithoutOrder += $scope.filterParams;
$scope.paramsWithoutSystemFilter += $scope.filterParams;
} | conditional_block |
plist.js | /*
* Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com)
*
* openAUSIAS: The stunning micro-library that helps you to develop easily
* AJAX web applications by using Java and jQuery
* openAUSIAS is distributed under the MIT License (MIT)
* Sources at https://github.com/rafaelaznar/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
'use strict';
/* Controllers */
moduloTipoempleado.controller('TipoempleadoPListController', ['$scope', '$routeParams', 'serverService', '$location',
function ($scope, $routeParams, serverService, $location) {
$scope.visibles = {};
$scope.visibles.id = true;
$scope.visibles.cargo = true;
$scope.ob = "tipoempleado";
$scope.op = "plist";
$scope.title = "Listado de tipos de empleados";
$scope.icon = "fa-user-secret";
$scope.neighbourhood = 2;
if (!$routeParams.page) {
$routeParams.page = 1;
}
if (!$routeParams.rpp) {
$routeParams.rpp = 10;
}
$scope.numpage = $routeParams.page;
$scope.rpp = $routeParams.rpp;;
$scope.order = "";
$scope.ordervalue = "";
$scope.filter = "id";
$scope.filteroperator = "like";
$scope.filtervalue = "";
$scope.systemfilter = "";
$scope.systemfilteroperator = "";
$scope.systemfiltervalue = "";
$scope.params = "";
$scope.paramsWithoutOrder = "";
$scope.paramsWithoutFilter = "";
$scope.paramsWithoutSystemFilter = "";
if ($routeParams.order && $routeParams.ordervalue) {
$scope.order = $routeParams.order;
$scope.ordervalue = $routeParams.ordervalue;
$scope.orderParams = "&order=" + $routeParams.order + "&ordervalue=" + $routeParams.ordervalue;
$scope.paramsWithoutFilter += $scope.orderParams;
$scope.paramsWithoutSystemFilter += $scope.orderParams;
} else {
$scope.orderParams = "";
}
| $scope.filteroperator = $routeParams.filteroperator;
$scope.filtervalue = $routeParams.filtervalue;
$scope.filterParams = "&filter=" + $routeParams.filter + "&filteroperator=" + $routeParams.filteroperator + "&filtervalue=" + $routeParams.filtervalue;
$scope.paramsWithoutOrder += $scope.filterParams;
$scope.paramsWithoutSystemFilter += $scope.filterParams;
} else {
$scope.filterParams = "";
}
if ($routeParams.systemfilter && $routeParams.systemfilteroperator && $routeParams.systemfiltervalue) {
$scope.systemFilterParams = "&systemfilter=" + $routeParams.systemfilter + "&systemfilteroperator=" + $routeParams.systemfilteroperator + "&systemfiltervalue=" + $routeParams.systemfiltervalue;
$scope.paramsWithoutOrder += $scope.systemFilterParams;
$scope.paramsWithoutFilter += $scope.systemFilterParams;
} else {
$scope.systemFilterParams = "";
}
$scope.params = ($scope.orderParams + $scope.filterParams + $scope.systemFilterParams);
$scope.params = $scope.params.replace('&', '?');
serverService.getDataFromPromise(serverService.promise_getSome($scope.ob, $scope.rpp, $scope.numpage, $scope.filterParams, $scope.orderParams, $scope.systemFilterParams)).then(function (data) {
if (data.status != 200) {
$scope.status = "Error en la recepción de datos del servidor";
} else {
$scope.pages = data.message.pages.message;
if (parseInt($scope.numpage) > parseInt($scope.pages))
$scope.numpage = $scope.pages;
$scope.page = data.message.page.message;
$scope.registers = data.message.registers.message;
$scope.status = "";
}
});
$scope.getRangeArray = function (lowEnd, highEnd) {
var rangeArray = [];
for (var i = lowEnd; i <= highEnd; i++) {
rangeArray.push(i);
}
return rangeArray;
};
$scope.evaluateMin = function (lowEnd, highEnd) {
return Math.min(lowEnd, highEnd);
};
$scope.evaluateMax = function (lowEnd, highEnd) {
return Math.max(lowEnd, highEnd);
};
$scope.dofilter = function () {
if ($scope.filter != "" && $scope.filteroperator != "" && $scope.filtervalue != "") {
if ($routeParams.order && $routeParams.ordervalue) {
if ($routeParams.systemfilter && $routeParams.systemfilteroperator) {
$location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue).search('order', $routeParams.order).search('ordervalue', $routeParams.ordervalue).search('systemfilter', $routeParams.systemfilter).search('systemfilteroperator', $routeParams.systemfilteroperator).search('systemfiltervalue', $routeParams.systemfiltervalue);
} else {
$location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue).search('order', $routeParams.order).search('ordervalue', $routeParams.ordervalue);
}
} else {
$location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue);
}
}
return false;
};
}]); | if ($routeParams.filter && $routeParams.filteroperator && $routeParams.filtervalue) {
$scope.filter = $routeParams.filter; | random_line_split |
requests.ts | /// <reference path="./../typings/index.d.ts" />
import {Request} from "hapi";
import * as Bluebird from "bluebird";
/**
* Returns the request's protocol (e.g. https) by trying to read the x-forwarded-proto header. This is the protocol the user typed into their address bar.
* Useful when your server doesn't serve requests directly, but rather passes them through a proxy to your app.
*/
export function getRequestProtocol(request: Request)
{
return (request.headers['x-forwarded-proto'] || request.connection.info.protocol);
}
/**
* Returns the request's host + port (e.g. www.example.com). This is the host the user typed into their address bar.
* Useful when your server doesn't serve requests directly, but rather passes them through a proxy to your app.
*/
export function getRequestHost(request: Request)
{
return request.info.host;
}
/**
* Returns the request's protocol + host (e.g. https://www.example.com). This is the domain the user typed into their address bar.
* Useful when your server doesn't serve requests directly, but rather passes them through a proxy to your app.
*/
export function getRequestDomain(request: Request)
{
const protocol = getRequestProtocol(request);
const host = getRequestHost(request);
return `${protocol}://${host}`
}
/**
* Gets the raw request body string.
*/
export async function getRawBody(request: Request)
| {
return new Bluebird<string>((resolve, reject) =>
{
let body = "";
request.raw.req.on("data", (data: Uint8Array) =>
{
body += data.toString();
});
request.raw.req.once("end", () =>
{
resolve(body);
});
})
} | identifier_body |
|
requests.ts | /// <reference path="./../typings/index.d.ts" />
import {Request} from "hapi";
import * as Bluebird from "bluebird";
/**
* Returns the request's protocol (e.g. https) by trying to read the x-forwarded-proto header. This is the protocol the user typed into their address bar.
* Useful when your server doesn't serve requests directly, but rather passes them through a proxy to your app.
*/
export function getRequestProtocol(request: Request)
{
return (request.headers['x-forwarded-proto'] || request.connection.info.protocol);
}
/**
* Returns the request's host + port (e.g. www.example.com). This is the host the user typed into their address bar.
* Useful when your server doesn't serve requests directly, but rather passes them through a proxy to your app.
*/
export function getRequestHost(request: Request)
{
return request.info.host;
}
/**
* Returns the request's protocol + host (e.g. https://www.example.com). This is the domain the user typed into their address bar.
* Useful when your server doesn't serve requests directly, but rather passes them through a proxy to your app.
*/
export function getRequestDomain(request: Request)
{ |
/**
* Gets the raw request body string.
*/
export async function getRawBody(request: Request)
{
return new Bluebird<string>((resolve, reject) =>
{
let body = "";
request.raw.req.on("data", (data: Uint8Array) =>
{
body += data.toString();
});
request.raw.req.once("end", () =>
{
resolve(body);
});
})
} | const protocol = getRequestProtocol(request);
const host = getRequestHost(request);
return `${protocol}://${host}`
} | random_line_split |
requests.ts | /// <reference path="./../typings/index.d.ts" />
import {Request} from "hapi";
import * as Bluebird from "bluebird";
/**
* Returns the request's protocol (e.g. https) by trying to read the x-forwarded-proto header. This is the protocol the user typed into their address bar.
* Useful when your server doesn't serve requests directly, but rather passes them through a proxy to your app.
*/
export function getRequestProtocol(request: Request)
{
return (request.headers['x-forwarded-proto'] || request.connection.info.protocol);
}
/**
* Returns the request's host + port (e.g. www.example.com). This is the host the user typed into their address bar.
* Useful when your server doesn't serve requests directly, but rather passes them through a proxy to your app.
*/
export function | (request: Request)
{
return request.info.host;
}
/**
* Returns the request's protocol + host (e.g. https://www.example.com). This is the domain the user typed into their address bar.
* Useful when your server doesn't serve requests directly, but rather passes them through a proxy to your app.
*/
export function getRequestDomain(request: Request)
{
const protocol = getRequestProtocol(request);
const host = getRequestHost(request);
return `${protocol}://${host}`
}
/**
* Gets the raw request body string.
*/
export async function getRawBody(request: Request)
{
return new Bluebird<string>((resolve, reject) =>
{
let body = "";
request.raw.req.on("data", (data: Uint8Array) =>
{
body += data.toString();
});
request.raw.req.once("end", () =>
{
resolve(body);
});
})
} | getRequestHost | identifier_name |
main.js | /* ========================================================================
* DOM-based Routing
* Based on http://goo.gl/EUTi53 by Paul Irish
*
* Only fires on body classes that match. If a body class contains a dash,
* replace the dash with an underscore when adding it to the object below.
*
* .noConflict()
* The routing is enclosed within an anonymous function so that you can
* always reference jQuery with $, even when in .noConflict() mode.
* ======================================================================== */
(function($) {
// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
var Sage = {
// All pages
'common': {
init: function() {
$(window).scroll(function() {
if ($(this).scrollTop() > 1){
$('.top-bar').addClass("navbar-fixed-top");
$('#navbar').addClass("navbar-fixed-top");
}
else{
$('.top-bar').removeClass("navbar-fixed-top");
$('#navbar').removeClass("navbar-fixed-top");
}
});
$(function() {
$(".dropdown").hover(
function(){ $(this).addClass('open') },
function(){ $(this).removeClass('open') }
);
});
},
finalize: function() {
// JavaScript to be fired on all pages, after page specific JS is fired
}
},
// Home page
'home': {
init: function() {
// JavaScript to be fired on the home page
},
finalize: function() {
// JavaScript to be fired on the home page, after the init JS
}
},
// About us page, note the change from about-us to about_us.
'about_us': {
init: function() {
// JavaScript to be fired on the about us page
}
}
};
// The routing fires all common scripts, followed by the page specific scripts.
// Add additional events for more control over timing e.g. a finalize event
var UTIL = {
fire: function(func, funcname, args) {
var fire;
var namespace = Sage;
funcname = (funcname === undefined) ? 'init' : funcname;
fire = func !== '';
fire = fire && namespace[func];
fire = fire && typeof namespace[func][funcname] === 'function';
if (fire) |
},
loadEvents: function() {
// Fire common init JS
UTIL.fire('common');
// Fire page-specific init JS, and then finalize JS
$.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
UTIL.fire(classnm);
UTIL.fire(classnm, 'finalize');
});
// Fire common finalize JS
UTIL.fire('common', 'finalize');
}
};
// Load Events
$(document).ready(UTIL.loadEvents);
})(jQuery); // Fully reference jQuery after this point.
| {
namespace[func][funcname](args);
} | conditional_block |
main.js | /* ========================================================================
* DOM-based Routing
* Based on http://goo.gl/EUTi53 by Paul Irish
*
* Only fires on body classes that match. If a body class contains a dash,
* replace the dash with an underscore when adding it to the object below.
*
* .noConflict()
* The routing is enclosed within an anonymous function so that you can
* always reference jQuery with $, even when in .noConflict() mode.
* ======================================================================== */
(function($) {
// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
var Sage = {
// All pages
'common': {
init: function() {
$(window).scroll(function() {
if ($(this).scrollTop() > 1){
$('.top-bar').addClass("navbar-fixed-top");
$('#navbar').addClass("navbar-fixed-top");
}
else{
$('.top-bar').removeClass("navbar-fixed-top");
$('#navbar').removeClass("navbar-fixed-top");
}
});
$(function() {
$(".dropdown").hover(
function(){ $(this).addClass('open') },
function(){ $(this).removeClass('open') }
);
});
},
finalize: function() {
// JavaScript to be fired on all pages, after page specific JS is fired
}
},
// Home page
'home': {
init: function() {
// JavaScript to be fired on the home page
},
finalize: function() { | // About us page, note the change from about-us to about_us.
'about_us': {
init: function() {
// JavaScript to be fired on the about us page
}
}
};
// The routing fires all common scripts, followed by the page specific scripts.
// Add additional events for more control over timing e.g. a finalize event
var UTIL = {
fire: function(func, funcname, args) {
var fire;
var namespace = Sage;
funcname = (funcname === undefined) ? 'init' : funcname;
fire = func !== '';
fire = fire && namespace[func];
fire = fire && typeof namespace[func][funcname] === 'function';
if (fire) {
namespace[func][funcname](args);
}
},
loadEvents: function() {
// Fire common init JS
UTIL.fire('common');
// Fire page-specific init JS, and then finalize JS
$.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
UTIL.fire(classnm);
UTIL.fire(classnm, 'finalize');
});
// Fire common finalize JS
UTIL.fire('common', 'finalize');
}
};
// Load Events
$(document).ready(UTIL.loadEvents);
})(jQuery); // Fully reference jQuery after this point. | // JavaScript to be fired on the home page, after the init JS
}
}, | random_line_split |
demand.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::ty;
use middle::typeck::check::FnCtxt;
use middle::typeck::infer;
use middle::typeck::infer::resolve_type;
use middle::typeck::infer::resolve::try_resolve_tvar_shallow;
use std::result::{Err, Ok};
use std::result;
use syntax::ast;
use syntax::codemap::Span;
use util::ppaux::Repr;
// Requires that the two types unify, and prints an error message if they
// don't.
pub fn suptype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) {
suptype_with_fn(fcx, sp, false, expected, actual,
|sp, e, a, s| { fcx.report_mismatched_types(sp, e, a, s) })
}
pub fn | (fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) {
suptype_with_fn(fcx, sp, true, actual, expected,
|sp, a, e, s| { fcx.report_mismatched_types(sp, e, a, s) })
}
pub fn suptype_with_fn(fcx: &FnCtxt,
sp: Span,
b_is_expected: bool,
ty_a: ty::t,
ty_b: ty::t,
handle_err: |Span, ty::t, ty::t, &ty::type_err|) {
// n.b.: order of actual, expected is reversed
match infer::mk_subty(fcx.infcx(), b_is_expected, infer::Misc(sp),
ty_b, ty_a) {
result::Ok(()) => { /* ok */ }
result::Err(ref err) => {
handle_err(sp, ty_a, ty_b, err);
}
}
}
pub fn eqtype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) {
match infer::mk_eqty(fcx.infcx(), false, infer::Misc(sp), actual, expected) {
Ok(()) => { /* ok */ }
Err(ref err) => {
fcx.report_mismatched_types(sp, expected, actual, err);
}
}
}
// Checks that the type `actual` can be coerced to `expected`.
pub fn coerce(fcx: &FnCtxt, sp: Span, expected: ty::t, expr: &ast::Expr) {
let expr_ty = fcx.expr_ty(expr);
debug!("demand::coerce(expected = {}, expr_ty = {})",
expected.repr(fcx.ccx.tcx),
expr_ty.repr(fcx.ccx.tcx));
let expected = if ty::type_needs_infer(expected) {
resolve_type(fcx.infcx(), expected,
try_resolve_tvar_shallow).unwrap_or(expected)
} else { expected };
match fcx.mk_assignty(expr, expr_ty, expected) {
result::Ok(()) => { /* ok */ }
result::Err(ref err) => {
fcx.report_mismatched_types(sp, expected, expr_ty, err);
}
}
}
| subtype | identifier_name |
demand.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::ty;
use middle::typeck::check::FnCtxt;
use middle::typeck::infer;
use middle::typeck::infer::resolve_type;
use middle::typeck::infer::resolve::try_resolve_tvar_shallow;
use std::result::{Err, Ok};
use std::result;
use syntax::ast;
use syntax::codemap::Span;
use util::ppaux::Repr;
// Requires that the two types unify, and prints an error message if they
// don't.
pub fn suptype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) {
suptype_with_fn(fcx, sp, false, expected, actual,
|sp, e, a, s| { fcx.report_mismatched_types(sp, e, a, s) })
}
pub fn subtype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) {
suptype_with_fn(fcx, sp, true, actual, expected,
|sp, a, e, s| { fcx.report_mismatched_types(sp, e, a, s) })
}
pub fn suptype_with_fn(fcx: &FnCtxt,
sp: Span,
b_is_expected: bool,
ty_a: ty::t,
ty_b: ty::t,
handle_err: |Span, ty::t, ty::t, &ty::type_err|) {
// n.b.: order of actual, expected is reversed
match infer::mk_subty(fcx.infcx(), b_is_expected, infer::Misc(sp),
ty_b, ty_a) {
result::Ok(()) => { /* ok */ }
result::Err(ref err) => {
handle_err(sp, ty_a, ty_b, err);
}
}
}
pub fn eqtype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) {
match infer::mk_eqty(fcx.infcx(), false, infer::Misc(sp), actual, expected) {
Ok(()) => { /* ok */ }
Err(ref err) => {
fcx.report_mismatched_types(sp, expected, actual, err);
}
}
}
// Checks that the type `actual` can be coerced to `expected`.
pub fn coerce(fcx: &FnCtxt, sp: Span, expected: ty::t, expr: &ast::Expr) {
let expr_ty = fcx.expr_ty(expr);
debug!("demand::coerce(expected = {}, expr_ty = {})",
expected.repr(fcx.ccx.tcx),
expr_ty.repr(fcx.ccx.tcx));
let expected = if ty::type_needs_infer(expected) | else { expected };
match fcx.mk_assignty(expr, expr_ty, expected) {
result::Ok(()) => { /* ok */ }
result::Err(ref err) => {
fcx.report_mismatched_types(sp, expected, expr_ty, err);
}
}
}
| {
resolve_type(fcx.infcx(), expected,
try_resolve_tvar_shallow).unwrap_or(expected)
} | conditional_block |
demand.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::ty;
use middle::typeck::check::FnCtxt;
use middle::typeck::infer;
use middle::typeck::infer::resolve_type;
use middle::typeck::infer::resolve::try_resolve_tvar_shallow;
use std::result::{Err, Ok};
use std::result;
use syntax::ast;
use syntax::codemap::Span;
use util::ppaux::Repr;
// Requires that the two types unify, and prints an error message if they
// don't.
pub fn suptype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) {
suptype_with_fn(fcx, sp, false, expected, actual,
|sp, e, a, s| { fcx.report_mismatched_types(sp, e, a, s) })
}
pub fn subtype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) |
pub fn suptype_with_fn(fcx: &FnCtxt,
sp: Span,
b_is_expected: bool,
ty_a: ty::t,
ty_b: ty::t,
handle_err: |Span, ty::t, ty::t, &ty::type_err|) {
// n.b.: order of actual, expected is reversed
match infer::mk_subty(fcx.infcx(), b_is_expected, infer::Misc(sp),
ty_b, ty_a) {
result::Ok(()) => { /* ok */ }
result::Err(ref err) => {
handle_err(sp, ty_a, ty_b, err);
}
}
}
pub fn eqtype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) {
match infer::mk_eqty(fcx.infcx(), false, infer::Misc(sp), actual, expected) {
Ok(()) => { /* ok */ }
Err(ref err) => {
fcx.report_mismatched_types(sp, expected, actual, err);
}
}
}
// Checks that the type `actual` can be coerced to `expected`.
pub fn coerce(fcx: &FnCtxt, sp: Span, expected: ty::t, expr: &ast::Expr) {
let expr_ty = fcx.expr_ty(expr);
debug!("demand::coerce(expected = {}, expr_ty = {})",
expected.repr(fcx.ccx.tcx),
expr_ty.repr(fcx.ccx.tcx));
let expected = if ty::type_needs_infer(expected) {
resolve_type(fcx.infcx(), expected,
try_resolve_tvar_shallow).unwrap_or(expected)
} else { expected };
match fcx.mk_assignty(expr, expr_ty, expected) {
result::Ok(()) => { /* ok */ }
result::Err(ref err) => {
fcx.report_mismatched_types(sp, expected, expr_ty, err);
}
}
}
| {
suptype_with_fn(fcx, sp, true, actual, expected,
|sp, a, e, s| { fcx.report_mismatched_types(sp, e, a, s) })
} | identifier_body |
demand.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::ty;
use middle::typeck::check::FnCtxt;
use middle::typeck::infer;
use middle::typeck::infer::resolve_type;
use middle::typeck::infer::resolve::try_resolve_tvar_shallow;
use std::result::{Err, Ok};
use std::result;
use syntax::ast;
use syntax::codemap::Span;
use util::ppaux::Repr;
// Requires that the two types unify, and prints an error message if they
// don't.
pub fn suptype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) { |
pub fn subtype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) {
suptype_with_fn(fcx, sp, true, actual, expected,
|sp, a, e, s| { fcx.report_mismatched_types(sp, e, a, s) })
}
pub fn suptype_with_fn(fcx: &FnCtxt,
sp: Span,
b_is_expected: bool,
ty_a: ty::t,
ty_b: ty::t,
handle_err: |Span, ty::t, ty::t, &ty::type_err|) {
// n.b.: order of actual, expected is reversed
match infer::mk_subty(fcx.infcx(), b_is_expected, infer::Misc(sp),
ty_b, ty_a) {
result::Ok(()) => { /* ok */ }
result::Err(ref err) => {
handle_err(sp, ty_a, ty_b, err);
}
}
}
pub fn eqtype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) {
match infer::mk_eqty(fcx.infcx(), false, infer::Misc(sp), actual, expected) {
Ok(()) => { /* ok */ }
Err(ref err) => {
fcx.report_mismatched_types(sp, expected, actual, err);
}
}
}
// Checks that the type `actual` can be coerced to `expected`.
pub fn coerce(fcx: &FnCtxt, sp: Span, expected: ty::t, expr: &ast::Expr) {
let expr_ty = fcx.expr_ty(expr);
debug!("demand::coerce(expected = {}, expr_ty = {})",
expected.repr(fcx.ccx.tcx),
expr_ty.repr(fcx.ccx.tcx));
let expected = if ty::type_needs_infer(expected) {
resolve_type(fcx.infcx(), expected,
try_resolve_tvar_shallow).unwrap_or(expected)
} else { expected };
match fcx.mk_assignty(expr, expr_ty, expected) {
result::Ok(()) => { /* ok */ }
result::Err(ref err) => {
fcx.report_mismatched_types(sp, expected, expr_ty, err);
}
}
} | suptype_with_fn(fcx, sp, false, expected, actual,
|sp, e, a, s| { fcx.report_mismatched_types(sp, e, a, s) })
} | random_line_split |
core.py | # -*- coding: utf8 -*-
# This file is part of Mnemosyne.
#
# Copyright (C) 2013 Daniel Lombraña González
#
# Mnemosyne 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 version.
#
# Mnemosyne 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 Public License
# along with Mnemosyne. If not, see <http://www.gnu.org/licenses/>.
"""
Package for creating the Flask application.
This exports:
- create_app a function that creates the Flask application
"""
from flask import Flask
from mnemosyne.frontend import frontend
from mnemosyne.model import db
try:
import mnemosyne.settings as settings
except:
print "Settings file is missing"
def create_app(db_name=None, testing=False):
"" |
db.init_app(app)
app.register_blueprint(frontend)
return app
| "
Create the Flask app object after configuring it.
Keyword arguments:
db_name -- Database name
testing -- Enable/Disable testing mode
Return value:
app -- Flask application object
"""
try:
app = Flask(__name__)
app.config.from_object(settings)
except:
print "Settings file is missing, trying with env config..."
app.config.from_envvar('MNEMOSYNE_SETTINGS', silent=False)
if db_name:
app.config['SQLALCHEMY_DATABASE_URI'] = db_name | identifier_body |
core.py | # -*- coding: utf8 -*-
# This file is part of Mnemosyne.
#
# Copyright (C) 2013 Daniel Lombraña González
#
# Mnemosyne 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 version.
#
# Mnemosyne 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 Public License
# along with Mnemosyne. If not, see <http://www.gnu.org/licenses/>.
"""
Package for creating the Flask application.
This exports:
- create_app a function that creates the Flask application
"""
from flask import Flask
from mnemosyne.frontend import frontend
from mnemosyne.model import db
try:
import mnemosyne.settings as settings
except:
print "Settings file is missing"
def cr | b_name=None, testing=False):
"""
Create the Flask app object after configuring it.
Keyword arguments:
db_name -- Database name
testing -- Enable/Disable testing mode
Return value:
app -- Flask application object
"""
try:
app = Flask(__name__)
app.config.from_object(settings)
except:
print "Settings file is missing, trying with env config..."
app.config.from_envvar('MNEMOSYNE_SETTINGS', silent=False)
if db_name:
app.config['SQLALCHEMY_DATABASE_URI'] = db_name
db.init_app(app)
app.register_blueprint(frontend)
return app
| eate_app(d | identifier_name |
core.py | # -*- coding: utf8 -*-
# This file is part of Mnemosyne.
#
# Copyright (C) 2013 Daniel Lombraña González
#
# Mnemosyne 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 version.
#
# Mnemosyne 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 Public License
# along with Mnemosyne. If not, see <http://www.gnu.org/licenses/>.
"""
Package for creating the Flask application.
This exports:
- create_app a function that creates the Flask application
"""
from flask import Flask
from mnemosyne.frontend import frontend
from mnemosyne.model import db
try:
import mnemosyne.settings as settings
except:
print "Settings file is missing"
def create_app(db_name=None, testing=False):
"""
Create the Flask app object after configuring it.
Keyword arguments:
db_name -- Database name
testing -- Enable/Disable testing mode
Return value:
app -- Flask application object
"""
try:
app = Flask(__name__) |
if db_name:
app.config['SQLALCHEMY_DATABASE_URI'] = db_name
db.init_app(app)
app.register_blueprint(frontend)
return app | app.config.from_object(settings)
except:
print "Settings file is missing, trying with env config..."
app.config.from_envvar('MNEMOSYNE_SETTINGS', silent=False) | random_line_split |
core.py | # -*- coding: utf8 -*-
# This file is part of Mnemosyne.
#
# Copyright (C) 2013 Daniel Lombraña González
#
# Mnemosyne 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 version.
#
# Mnemosyne 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 Public License
# along with Mnemosyne. If not, see <http://www.gnu.org/licenses/>.
"""
Package for creating the Flask application.
This exports:
- create_app a function that creates the Flask application
"""
from flask import Flask
from mnemosyne.frontend import frontend
from mnemosyne.model import db
try:
import mnemosyne.settings as settings
except:
print "Settings file is missing"
def create_app(db_name=None, testing=False):
"""
Create the Flask app object after configuring it.
Keyword arguments:
db_name -- Database name
testing -- Enable/Disable testing mode
Return value:
app -- Flask application object
"""
try:
app = Flask(__name__)
app.config.from_object(settings)
except:
print "Settings file is missing, trying with env config..."
app.config.from_envvar('MNEMOSYNE_SETTINGS', silent=False)
if db_name:
ap | db.init_app(app)
app.register_blueprint(frontend)
return app
| p.config['SQLALCHEMY_DATABASE_URI'] = db_name
| conditional_block |
Profile.js | function Profile(data, raw) | } else if (data.email) {
this.emails = [{
value: data.email
}];
}
//copy these fields
['picture',
'locale',
'nickname',
'gender',
'identities'].filter(function (k) {
return k in data;
}).forEach(function (k) {
this[k] = data[k];
}.bind(this));
this._json = data;
this._raw = raw;
}
module.exports = Profile; | {
this.displayName = data.name;
this.id = data.user_id || data.sub;
this.user_id = this.id;
if (data.identities) {
this.provider = data.identities[0].provider;
} else if (typeof this.id === 'string' && this.id.indexOf('|') > -1 ) {
this.provider = this.id.split('|')[0];
}
this.name = {
familyName: data.family_name,
givenName: data.given_name
};
if (data.emails) {
this.emails = data.emails.map(function (email) {
return { value: email };
}); | identifier_body |
Profile.js | function Profile(data, raw) {
this.displayName = data.name;
this.id = data.user_id || data.sub;
this.user_id = this.id;
if (data.identities) {
this.provider = data.identities[0].provider;
} else if (typeof this.id === 'string' && this.id.indexOf('|') > -1 ) {
this.provider = this.id.split('|')[0];
}
this.name = {
familyName: data.family_name,
givenName: data.given_name
};
if (data.emails) {
this.emails = data.emails.map(function (email) {
return { value: email };
});
} else if (data.email) {
this.emails = [{
value: data.email
}];
}
//copy these fields
['picture',
'locale',
'nickname',
'gender',
'identities'].filter(function (k) {
return k in data;
}).forEach(function (k) {
this[k] = data[k];
}.bind(this));
this._json = data;
this._raw = raw;
}
| module.exports = Profile; | random_line_split |
|
Profile.js | function | (data, raw) {
this.displayName = data.name;
this.id = data.user_id || data.sub;
this.user_id = this.id;
if (data.identities) {
this.provider = data.identities[0].provider;
} else if (typeof this.id === 'string' && this.id.indexOf('|') > -1 ) {
this.provider = this.id.split('|')[0];
}
this.name = {
familyName: data.family_name,
givenName: data.given_name
};
if (data.emails) {
this.emails = data.emails.map(function (email) {
return { value: email };
});
} else if (data.email) {
this.emails = [{
value: data.email
}];
}
//copy these fields
['picture',
'locale',
'nickname',
'gender',
'identities'].filter(function (k) {
return k in data;
}).forEach(function (k) {
this[k] = data[k];
}.bind(this));
this._json = data;
this._raw = raw;
}
module.exports = Profile; | Profile | identifier_name |
mig-form.component.spec.ts | import { ComponentFixture, TestBed, async, inject } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { MigFormComponent } from './mig-form.component';
import { SpinnerComponent } from './spinner.component';
import { MigService } from './mig.service';
import { SensorService } from './sensor.service';
describe('MigFormComponent', () => {
let comp: MigFormComponent;
let fixture: ComponentFixture<MigFormComponent>;
let migServiceStub = {
getData() | "temperature",
"light"
],
"capacitance": 975,
"temperature": 23,
"light": 13877
},
{
"_id": "58504e9748e01100073bec95",
"temperature": 24.4,
"soil": 367,
"humidity": 32.9,
"host": "rpi02",
"timestamp": "2016-12-13T19:40:06.523466",
"sensor": [
"soil",
"humidity",
"temperature"
]
},
{
"_id": "58504ec048e01100073bec96",
"host": "ESP_CBBAAB",
"sensor": [
"capacitance",
"temperature",
"light"
],
"capacitance": 971,
"temperature": 23,
"light": 13837
}
])
}
}
let sensorServiceStub = {
getSensorID(host: string, sensor: string) {
return "58504ec048e01100073bec96"
}
}
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MigFormComponent, SpinnerComponent], // declare the test component
providers: [{ provide: MigService, useValue: migServiceStub },
{ provide: SensorService, useValue: sensorServiceStub }]
})
.compileComponents();
fixture = TestBed.createComponent(MigFormComponent);
comp = fixture.componentInstance; // BannerComponent test
}));
it('comp type is correct', () => {
expect(comp instanceof MigFormComponent).toBe(true);
})
it('panel title correct', () => {
// query for the title <h1> by CSS element selector
let de = fixture.debugElement.query(By.css('.panel-title'));
let el = de.nativeElement;
expect(el.textContent).toContain('Sensor Data Migration Form');
})
it('initial data empty', () => {
let comp = fixture.componentInstance;
expect(comp.data.length).toBe(0);
expect(comp.errorMsg).toBeNull();
expect(comp.isLoading).toBe(false);
})
it('load function - bypassed', inject([MigService],
(fixture: MigService) => {
let obs = fixture.getData();
expect(obs instanceof Observable).toBe(true);
let sub = obs.subscribe(x => {
console.log('subscribed event - x: ', x);
expect(x.length).toBe(4);
});
}));
it('load function - direct', inject([MigService],
(fixture: MigService) => {
expect(comp.data.length).toBe(0);
comp.load();
expect(comp.data.length).toBe(4);
}));
// following test is insufficient: it only works with a static version of mapped. Otherwise it should make sure
// load() is executed first and it should have both true and false tests based on the mock backend data.
it('mapped function - TODO: load data first and have both good and bad tests', () => {
let comp = fixture.componentInstance;
expect(comp.mapped("rpi02", "soil")).toBe(true);
})
}) | {
return Observable.of([
{
"_id": "58504d6948e01100073bec93",
"temperature": 24.4,
"soil": 367,
"humidity": 33.2,
"host": "rpi02",
"timestamp": "2016-12-13T19:35:03.895033",
"sensor": [
"soil",
"humidity",
"temperature"
]
},
{
"_id": "58504d8f48e01100073bec94",
"host": "ESP_CBBAAB",
"sensor": [
"capacitance", | identifier_body |
mig-form.component.spec.ts | import { ComponentFixture, TestBed, async, inject } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { MigFormComponent } from './mig-form.component';
import { SpinnerComponent } from './spinner.component';
import { MigService } from './mig.service';
import { SensorService } from './sensor.service';
describe('MigFormComponent', () => {
let comp: MigFormComponent;
let fixture: ComponentFixture<MigFormComponent>;
let migServiceStub = {
getData() {
return Observable.of([
{
"_id": "58504d6948e01100073bec93",
"temperature": 24.4,
"soil": 367,
"humidity": 33.2,
"host": "rpi02",
"timestamp": "2016-12-13T19:35:03.895033",
"sensor": [
"soil",
"humidity",
"temperature"
]
},
{
"_id": "58504d8f48e01100073bec94",
"host": "ESP_CBBAAB",
"sensor": [
"capacitance",
"temperature",
"light"
],
"capacitance": 975,
"temperature": 23,
"light": 13877
},
{
"_id": "58504e9748e01100073bec95",
"temperature": 24.4,
"soil": 367,
"humidity": 32.9,
"host": "rpi02",
"timestamp": "2016-12-13T19:40:06.523466",
"sensor": [
"soil",
"humidity",
"temperature"
]
},
{
"_id": "58504ec048e01100073bec96",
"host": "ESP_CBBAAB",
"sensor": [
"capacitance",
"temperature",
"light"
],
"capacitance": 971,
"temperature": 23,
"light": 13837
}
])
}
}
let sensorServiceStub = {
getSensorID(host: string, sensor: string) {
return "58504ec048e01100073bec96"
}
}
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MigFormComponent, SpinnerComponent], // declare the test component
providers: [{ provide: MigService, useValue: migServiceStub },
{ provide: SensorService, useValue: sensorServiceStub }]
})
.compileComponents();
|
comp = fixture.componentInstance; // BannerComponent test
}));
it('comp type is correct', () => {
expect(comp instanceof MigFormComponent).toBe(true);
})
it('panel title correct', () => {
// query for the title <h1> by CSS element selector
let de = fixture.debugElement.query(By.css('.panel-title'));
let el = de.nativeElement;
expect(el.textContent).toContain('Sensor Data Migration Form');
})
it('initial data empty', () => {
let comp = fixture.componentInstance;
expect(comp.data.length).toBe(0);
expect(comp.errorMsg).toBeNull();
expect(comp.isLoading).toBe(false);
})
it('load function - bypassed', inject([MigService],
(fixture: MigService) => {
let obs = fixture.getData();
expect(obs instanceof Observable).toBe(true);
let sub = obs.subscribe(x => {
console.log('subscribed event - x: ', x);
expect(x.length).toBe(4);
});
}));
it('load function - direct', inject([MigService],
(fixture: MigService) => {
expect(comp.data.length).toBe(0);
comp.load();
expect(comp.data.length).toBe(4);
}));
// following test is insufficient: it only works with a static version of mapped. Otherwise it should make sure
// load() is executed first and it should have both true and false tests based on the mock backend data.
it('mapped function - TODO: load data first and have both good and bad tests', () => {
let comp = fixture.componentInstance;
expect(comp.mapped("rpi02", "soil")).toBe(true);
})
}) | fixture = TestBed.createComponent(MigFormComponent); | random_line_split |
mig-form.component.spec.ts | import { ComponentFixture, TestBed, async, inject } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { MigFormComponent } from './mig-form.component';
import { SpinnerComponent } from './spinner.component';
import { MigService } from './mig.service';
import { SensorService } from './sensor.service';
describe('MigFormComponent', () => {
let comp: MigFormComponent;
let fixture: ComponentFixture<MigFormComponent>;
let migServiceStub = {
getData() {
return Observable.of([
{
"_id": "58504d6948e01100073bec93",
"temperature": 24.4,
"soil": 367,
"humidity": 33.2,
"host": "rpi02",
"timestamp": "2016-12-13T19:35:03.895033",
"sensor": [
"soil",
"humidity",
"temperature"
]
},
{
"_id": "58504d8f48e01100073bec94",
"host": "ESP_CBBAAB",
"sensor": [
"capacitance",
"temperature",
"light"
],
"capacitance": 975,
"temperature": 23,
"light": 13877
},
{
"_id": "58504e9748e01100073bec95",
"temperature": 24.4,
"soil": 367,
"humidity": 32.9,
"host": "rpi02",
"timestamp": "2016-12-13T19:40:06.523466",
"sensor": [
"soil",
"humidity",
"temperature"
]
},
{
"_id": "58504ec048e01100073bec96",
"host": "ESP_CBBAAB",
"sensor": [
"capacitance",
"temperature",
"light"
],
"capacitance": 971,
"temperature": 23,
"light": 13837
}
])
}
}
let sensorServiceStub = {
| (host: string, sensor: string) {
return "58504ec048e01100073bec96"
}
}
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MigFormComponent, SpinnerComponent], // declare the test component
providers: [{ provide: MigService, useValue: migServiceStub },
{ provide: SensorService, useValue: sensorServiceStub }]
})
.compileComponents();
fixture = TestBed.createComponent(MigFormComponent);
comp = fixture.componentInstance; // BannerComponent test
}));
it('comp type is correct', () => {
expect(comp instanceof MigFormComponent).toBe(true);
})
it('panel title correct', () => {
// query for the title <h1> by CSS element selector
let de = fixture.debugElement.query(By.css('.panel-title'));
let el = de.nativeElement;
expect(el.textContent).toContain('Sensor Data Migration Form');
})
it('initial data empty', () => {
let comp = fixture.componentInstance;
expect(comp.data.length).toBe(0);
expect(comp.errorMsg).toBeNull();
expect(comp.isLoading).toBe(false);
})
it('load function - bypassed', inject([MigService],
(fixture: MigService) => {
let obs = fixture.getData();
expect(obs instanceof Observable).toBe(true);
let sub = obs.subscribe(x => {
console.log('subscribed event - x: ', x);
expect(x.length).toBe(4);
});
}));
it('load function - direct', inject([MigService],
(fixture: MigService) => {
expect(comp.data.length).toBe(0);
comp.load();
expect(comp.data.length).toBe(4);
}));
// following test is insufficient: it only works with a static version of mapped. Otherwise it should make sure
// load() is executed first and it should have both true and false tests based on the mock backend data.
it('mapped function - TODO: load data first and have both good and bad tests', () => {
let comp = fixture.componentInstance;
expect(comp.mapped("rpi02", "soil")).toBe(true);
})
}) | getSensorID | identifier_name |
typescript.ts | .modifiers && node.modifiers.some((nodeModifier: ts.Modifier) => nodeModifier.kind === modifier));
}
export function getNodeName(node: ts.Node): NodeName | undefined {
const nodeName = (node as unknown as ts.NamedDeclaration).name;
if (nodeName === undefined) {
const defaultModifier = node.modifiers?.find((mod: ts.Modifier) => mod.kind === ts.SyntaxKind.DefaultKeyword);
if (defaultModifier !== undefined) {
return defaultModifier;
}
}
return nodeName;
}
export function getActualSymbol(symbol: ts.Symbol, typeChecker: ts.TypeChecker): ts.Symbol {
if (symbol.flags & ts.SymbolFlags.Alias) {
symbol = typeChecker.getAliasedSymbol(symbol);
}
return symbol;
}
export function getDeclarationNameSymbol(name: NodeName, typeChecker: ts.TypeChecker): ts.Symbol | null {
const symbol = typeChecker.getSymbolAtLocation(name);
if (symbol === undefined) {
return null; | }
export function splitTransientSymbol(symbol: ts.Symbol, typeChecker: ts.TypeChecker): ts.Symbol[] {
// actually I think we even don't need to operate/use "Transient" symbols anywhere
// it's kind of aliased symbol, but just merged
// but it's hard to refractor everything to use array of symbols instead of just symbol
// so let's fix it for some places
if ((symbol.flags & ts.SymbolFlags.Transient) === 0) {
return [symbol];
}
// "Transient" symbol is kinda "merged" symbol
// I don't really know is this way to "split" is correct
// but it seems that it works for now ¯\_(ツ)_/¯
const declarations = getDeclarationsForSymbol(symbol);
const result: ts.Symbol[] = [];
for (const declaration of declarations) {
if (!isNodeNamedDeclaration(declaration) || declaration.name === undefined) {
continue;
}
const sym = typeChecker.getSymbolAtLocation(declaration.name);
if (sym === undefined) {
continue;
}
result.push(getActualSymbol(sym, typeChecker));
}
return result;
}
/**
* @see https://github.com/Microsoft/TypeScript/blob/f7c4fefeb62416c311077a699cc15beb211c25c9/src/compiler/utilities.ts#L626-L628
*/
function isGlobalScopeAugmentation(module: ts.ModuleDeclaration): boolean {
return Boolean(module.flags & ts.NodeFlags.GlobalAugmentation);
}
/**
* Returns whether node is ambient module declaration (declare module "name" or declare global)
* @see https://github.com/Microsoft/TypeScript/blob/f7c4fefeb62416c311077a699cc15beb211c25c9/src/compiler/utilities.ts#L588-L590
*/
export function isAmbientModule(node: ts.Node): boolean {
return ts.isModuleDeclaration(node) && (node.name.kind === ts.SyntaxKind.StringLiteral || isGlobalScopeAugmentation(node));
}
/**
* Returns whether node is `declare module` ModuleDeclaration (not `declare global` or `namespace`)
*/
export function isDeclareModule(node: ts.Node): node is ts.ModuleDeclaration {
// `declare module ""`, `declare global` and `namespace {}` are ModuleDeclaration
// but here we need to check only `declare module` statements
return ts.isModuleDeclaration(node) && !(node.flags & ts.NodeFlags.Namespace) && !isGlobalScopeAugmentation(node);
}
/**
* Returns whether statement is `declare global` ModuleDeclaration
*/
export function isDeclareGlobalStatement(statement: ts.Statement): statement is ts.ModuleDeclaration {
return ts.isModuleDeclaration(statement) && isGlobalScopeAugmentation(statement);
}
/**
* Returns whether node is `namespace` ModuleDeclaration
*/
export function isNamespaceStatement(node: ts.Node): node is ts.ModuleDeclaration {
return ts.isModuleDeclaration(node) && Boolean(node.flags & ts.NodeFlags.Namespace);
}
export function getDeclarationsForSymbol(symbol: ts.Symbol): ts.Declaration[] {
const result: ts.Declaration[] = [];
// Disabling tslint is for backward compat with TypeScript < 3
// tslint:disable-next-line:strict-type-predicates
if (symbol.declarations !== undefined) {
result.push(...symbol.declarations);
}
// Disabling tslint is for backward compat with TypeScript < 3
// tslint:disable-next-line:strict-type-predicates
if (symbol.valueDeclaration !== undefined) {
// push valueDeclaration might be already in declarations array
// so let's check first to avoid duplication nodes
if (!result.includes(symbol.valueDeclaration)) {
result.push(symbol.valueDeclaration);
}
}
return result;
}
export function isDeclarationFromExternalModule(node: ts.Declaration): boolean {
return getLibraryName(node.getSourceFile().fileName) !== null;
}
export const enum ExportType {
CommonJS,
ES6Named,
ES6Default,
}
export interface SourceFileExport {
originalName: string;
exportedName: string;
symbol: ts.Symbol;
type: ExportType;
}
export function getExportsForSourceFile(typeChecker: ts.TypeChecker, sourceFileSymbol: ts.Symbol): SourceFileExport[] {
if (sourceFileSymbol.exports !== undefined) {
const commonJsExport = sourceFileSymbol.exports.get(ts.InternalSymbolName.ExportEquals);
if (commonJsExport !== undefined) {
const symbol = getActualSymbol(commonJsExport, typeChecker);
return [
{
symbol,
type: ExportType.CommonJS,
exportedName: '',
originalName: symbol.escapedName as string,
},
];
}
}
const result: SourceFileExport[] = typeChecker
.getExportsOfModule(sourceFileSymbol)
.map((symbol: ts.Symbol) => ({ symbol, exportedName: symbol.escapedName as string, type: ExportType.ES6Named, originalName: '' }));
if (sourceFileSymbol.exports !== undefined) {
const defaultExportSymbol = sourceFileSymbol.exports.get(ts.InternalSymbolName.Default);
if (defaultExportSymbol !== undefined) {
const defaultExport = result.find((exp: SourceFileExport) => exp.symbol === defaultExportSymbol);
if (defaultExport !== undefined) {
defaultExport.type = ExportType.ES6Default;
} else {
// it seems that default export is always returned by getExportsOfModule
// but let's add it to be sure add if there is no such export
result.push({
symbol: defaultExportSymbol,
type: ExportType.ES6Default,
exportedName: 'default',
originalName: '',
});
}
}
}
result.forEach((exp: SourceFileExport) => {
exp.symbol = getActualSymbol(exp.symbol, typeChecker);
const resolvedIdentifier = resolveIdentifierBySymbol(exp.symbol);
exp.originalName = resolvedIdentifier !== undefined ? resolvedIdentifier.getText() : exp.symbol.escapedName as string;
});
return result;
}
export function resolveIdentifier(typeChecker: ts.TypeChecker, identifier: ts.Identifier): ts.NamedDeclaration['name'] {
const symbol = getDeclarationNameSymbol(identifier, typeChecker);
if (symbol === null) {
return undefined;
}
return resolveIdentifierBySymbol(symbol);
}
function resolveIdentifierBySymbol(identifierSymbol: ts.Symbol): ts.NamedDeclaration['name'] {
const declarations = getDeclarationsForSymbol(identifierSymbol);
if (declarations.length === 0) {
return undefined;
}
const decl = declarations[0];
if (!isNodeNamedDeclaration(decl)) {
return undefined;
}
return decl.name;
}
export function getExportsForStatement(
exportedSymbols: readonly SourceFileExport[],
typeChecker: ts.TypeChecker,
statement: ts.Statement
): SourceFileExport[] {
if (ts.isVariableStatement(statement)) {
if (statement.declarationList.declarations.length === 0) {
return [];
}
const firstDeclarationExports = getExportsForName(
exportedSymbols,
typeChecker,
statement.declarationList.declarations[0].name
);
const allDeclarationsHaveSameExportType = statement.declarationList.declarations.every((variableDecl: ts.VariableDeclaration) => {
// all declaration should have the same export type
// TODO: for now it's not supported to have different type of exports
return getExportsForName(exportedSymbols, typeChecker, variableDecl.name)[0]?.type === firstDeclarationExports[0]?.type;
});
if (!allDeclarationsHaveSameExportType) {
// log warn?
return [];
}
return firstDeclarationExports;
}
const nodeName = getNodeName(statement);
if (nodeName === undefined) {
return [];
}
return getExportsForName(exportedSymbols, typeChecker, nodeName);
}
function getExportsForName(
exportedSymbols: readonly SourceFileExport[],
typeChecker: ts.TypeChecker,
name: NodeName
): SourceFileExport[] {
if (ts.isArrayBindingPattern(name) || ts.isObjectBindingPattern(name)) {
// TODO: binding patterns in variable declarations are not supported for now
// see https://github.com/microsoft/TypeScript/issues/30598 also
return [];
}
const declarationSymbol = typeChecker.getSymbolAtLocation(name);
return exportedSymbols.filter((rootExport: SourceFileExport) => rootExport.symbol === declarationSymbol);
}
// labelled tuples were introduced in | }
return getActualSymbol(symbol, typeChecker); | random_line_split |
typescript.ts | ifiers && node.modifiers.some((nodeModifier: ts.Modifier) => nodeModifier.kind === modifier));
}
export function getNodeName(node: ts.Node): NodeName | undefined {
const nodeName = (node as unknown as ts.NamedDeclaration).name;
if (nodeName === undefined) {
const defaultModifier = node.modifiers?.find((mod: ts.Modifier) => mod.kind === ts.SyntaxKind.DefaultKeyword);
if (defaultModifier !== undefined) {
return defaultModifier;
}
}
return nodeName;
}
export function getActualSymbol(symbol: ts.Symbol, typeChecker: ts.TypeChecker): ts.Symbol {
if (symbol.flags & ts.SymbolFlags.Alias) {
symbol = typeChecker.getAliasedSymbol(symbol);
}
return symbol;
}
export function getDeclarationNameSymbol(name: NodeName, typeChecker: ts.TypeChecker): ts.Symbol | null {
const symbol = typeChecker.getSymbolAtLocation(name);
if (symbol === undefined) {
return null;
}
return getActualSymbol(symbol, typeChecker);
}
export function splitTransientSymbol(symbol: ts.Symbol, typeChecker: ts.TypeChecker): ts.Symbol[] {
// actually I think we even don't need to operate/use "Transient" symbols anywhere
// it's kind of aliased symbol, but just merged
// but it's hard to refractor everything to use array of symbols instead of just symbol
// so let's fix it for some places
if ((symbol.flags & ts.SymbolFlags.Transient) === 0) {
return [symbol];
}
// "Transient" symbol is kinda "merged" symbol
// I don't really know is this way to "split" is correct
// but it seems that it works for now ¯\_(ツ)_/¯
const declarations = getDeclarationsForSymbol(symbol);
const result: ts.Symbol[] = [];
for (const declaration of declarations) {
if (!isNodeNamedDeclaration(declaration) || declaration.name === undefined) {
continue;
}
const sym = typeChecker.getSymbolAtLocation(declaration.name);
if (sym === undefined) {
continue;
}
result.push(getActualSymbol(sym, typeChecker));
}
return result;
}
/**
* @see https://github.com/Microsoft/TypeScript/blob/f7c4fefeb62416c311077a699cc15beb211c25c9/src/compiler/utilities.ts#L626-L628
*/
function isGlobalScopeAugmentation(module: ts.ModuleDeclaration): boolean {
return Boolean(module.flags & ts.NodeFlags.GlobalAugmentation);
}
/**
* Returns whether node is ambient module declaration (declare module "name" or declare global)
* @see https://github.com/Microsoft/TypeScript/blob/f7c4fefeb62416c311077a699cc15beb211c25c9/src/compiler/utilities.ts#L588-L590
*/
export function isAmbientModule(node: ts.Node): boolean {
return ts.isModuleDeclaration(node) && (node.name.kind === ts.SyntaxKind.StringLiteral || isGlobalScopeAugmentation(node));
}
/**
* Returns whether node is `declare module` ModuleDeclaration (not `declare global` or `namespace`)
*/
export function isDeclareModule(node: ts.Node): node is ts.ModuleDeclaration {
// `declare module ""`, `declare global` and `namespace {}` are ModuleDeclaration
// but here we need to check only `declare module` statements
return ts.isModuleDeclaration(node) && !(node.flags & ts.NodeFlags.Namespace) && !isGlobalScopeAugmentation(node);
}
/**
* Returns whether statement is `declare global` ModuleDeclaration
*/
export function isDeclareGlobalStatement(statement: ts.Statement): statement is ts.ModuleDeclaration {
return ts.isModuleDeclaration(statement) && isGlobalScopeAugmentation(statement);
}
/**
* Returns whether node is `namespace` ModuleDeclaration
*/
export function isNamespaceStatement(node: ts.Node): node is ts.ModuleDeclaration {
return ts.isModuleDeclaration(node) && Boolean(node.flags & ts.NodeFlags.Namespace);
}
export function getDeclarationsForSymbol(symbol: ts.Symbol): ts.Declaration[] {
const result: ts.Declaration[] = [];
// Disabling tslint is for backward compat with TypeScript < 3
// tslint:disable-next-line:strict-type-predicates
if (symbol.declarations !== undefined) {
result.push(...symbol.declarations);
}
// Disabling tslint is for backward compat with TypeScript < 3
// tslint:disable-next-line:strict-type-predicates
if (symbol.valueDeclaration !== undefined) {
// push valueDeclaration might be already in declarations array
// so let's check first to avoid duplication nodes
if (!result.includes(symbol.valueDeclaration)) {
result.push(symbol.valueDeclaration);
}
}
return result;
}
export function isDeclarationFromExternalModule(node: ts.Declaration): boolean {
return getLibraryName(node.getSourceFile().fileName) !== null;
}
export const enum ExportType {
CommonJS,
ES6Named,
ES6Default,
}
export interface SourceFileExport {
originalName: string;
exportedName: string;
symbol: ts.Symbol;
type: ExportType;
}
export function getExportsForSourceFile(typeChecker: ts.TypeChecker, sourceFileSymbol: ts.Symbol): SourceFileExport[] {
if (sourceFileSymbol.exports !== undefined) {
const commonJsExport = sourceFileSymbol.exports.get(ts.InternalSymbolName.ExportEquals);
if (commonJsExport !== undefined) {
const symbol = getActualSymbol(commonJsExport, typeChecker);
return [
{
symbol,
type: ExportType.CommonJS,
exportedName: '',
originalName: symbol.escapedName as string,
},
];
}
}
const result: SourceFileExport[] = typeChecker
.getExportsOfModule(sourceFileSymbol)
.map((symbol: ts.Symbol) => ({ symbol, exportedName: symbol.escapedName as string, type: ExportType.ES6Named, originalName: '' }));
if (sourceFileSymbol.exports !== undefined) {
const defaultExportSymbol = sourceFileSymbol.exports.get(ts.InternalSymbolName.Default);
if (defaultExportSymbol !== undefined) {
const defaultExport = result.find((exp: SourceFileExport) => exp.symbol === defaultExportSymbol);
if (defaultExport !== undefined) {
defaultExport.type = ExportType.ES6Default;
} else {
// it seems that default export is always returned by getExportsOfModule
// but let's add it to be sure add if there is no such export
result.push({
symbol: defaultExportSymbol,
type: ExportType.ES6Default,
exportedName: 'default',
originalName: '',
});
}
}
}
result.forEach((exp: SourceFileExport) => {
exp.symbol = getActualSymbol(exp.symbol, typeChecker);
const resolvedIdentifier = resolveIdentifierBySymbol(exp.symbol);
exp.originalName = resolvedIdentifier !== undefined ? resolvedIdentifier.getText() : exp.symbol.escapedName as string;
});
return result;
}
export function resolveIdentifier(typeChecker: ts.TypeChecker, identifier: ts.Identifier): ts.NamedDeclaration['name'] {
const symbol = getDeclarationNameSymbol(identifier, typeChecker);
if (symbol === null) {
return undefined;
}
return resolveIdentifierBySymbol(symbol);
}
function resolveIdentifierBySymbol(identifierSymbol: ts.Symbol): ts.NamedDeclaration['name'] {
const declarations = getDeclarationsForSymbol(identifierSymbol);
if (declarations.length === 0) {
| onst decl = declarations[0];
if (!isNodeNamedDeclaration(decl)) {
return undefined;
}
return decl.name;
}
export function getExportsForStatement(
exportedSymbols: readonly SourceFileExport[],
typeChecker: ts.TypeChecker,
statement: ts.Statement
): SourceFileExport[] {
if (ts.isVariableStatement(statement)) {
if (statement.declarationList.declarations.length === 0) {
return [];
}
const firstDeclarationExports = getExportsForName(
exportedSymbols,
typeChecker,
statement.declarationList.declarations[0].name
);
const allDeclarationsHaveSameExportType = statement.declarationList.declarations.every((variableDecl: ts.VariableDeclaration) => {
// all declaration should have the same export type
// TODO: for now it's not supported to have different type of exports
return getExportsForName(exportedSymbols, typeChecker, variableDecl.name)[0]?.type === firstDeclarationExports[0]?.type;
});
if (!allDeclarationsHaveSameExportType) {
// log warn?
return [];
}
return firstDeclarationExports;
}
const nodeName = getNodeName(statement);
if (nodeName === undefined) {
return [];
}
return getExportsForName(exportedSymbols, typeChecker, nodeName);
}
function getExportsForName(
exportedSymbols: readonly SourceFileExport[],
typeChecker: ts.TypeChecker,
name: NodeName
): SourceFileExport[] {
if (ts.isArrayBindingPattern(name) || ts.isObjectBindingPattern(name)) {
// TODO: binding patterns in variable declarations are not supported for now
// see https://github.com/microsoft/TypeScript/issues/30598 also
return [];
}
const declarationSymbol = typeChecker.getSymbolAtLocation(name);
return exportedSymbols.filter((rootExport: SourceFileExport) => rootExport.symbol === declarationSymbol);
}
// labelled tuples were introduced | return undefined;
}
c | conditional_block |
typescript.ts | ifiers && node.modifiers.some((nodeModifier: ts.Modifier) => nodeModifier.kind === modifier));
}
export function getNodeName(node: ts.Node): NodeName | undefined {
const nodeName = (node as unknown as ts.NamedDeclaration).name;
if (nodeName === undefined) {
const defaultModifier = node.modifiers?.find((mod: ts.Modifier) => mod.kind === ts.SyntaxKind.DefaultKeyword);
if (defaultModifier !== undefined) {
return defaultModifier;
}
}
return nodeName;
}
export function getActualSymbol(symbol: ts.Symbol, typeChecker: ts.TypeChecker): ts.Symbol {
if (symbol.flags & ts.SymbolFlags.Alias) {
symbol = typeChecker.getAliasedSymbol(symbol);
}
return symbol;
}
export function getDeclarationNameSymbol(name: NodeName, typeChecker: ts.TypeChecker): ts.Symbol | null {
const symbol = typeChecker.getSymbolAtLocation(name);
if (symbol === undefined) {
return null;
}
return getActualSymbol(symbol, typeChecker);
}
export function splitTransientSymbol(symbol: ts.Symbol, typeChecker: ts.TypeChecker): ts.Symbol[] {
// actually I think we even don't need to operate/use "Transient" symbols anywhere
// it's kind of aliased symbol, but just merged
// but it's hard to refractor everything to use array of symbols instead of just symbol
// so let's fix it for some places
if ((symbol.flags & ts.SymbolFlags.Transient) === 0) {
return [symbol];
}
// "Transient" symbol is kinda "merged" symbol
// I don't really know is this way to "split" is correct
// but it seems that it works for now ¯\_(ツ)_/¯
const declarations = getDeclarationsForSymbol(symbol);
const result: ts.Symbol[] = [];
for (const declaration of declarations) {
if (!isNodeNamedDeclaration(declaration) || declaration.name === undefined) {
continue;
}
const sym = typeChecker.getSymbolAtLocation(declaration.name);
if (sym === undefined) {
continue;
}
result.push(getActualSymbol(sym, typeChecker));
}
return result;
}
/**
* @see https://github.com/Microsoft/TypeScript/blob/f7c4fefeb62416c311077a699cc15beb211c25c9/src/compiler/utilities.ts#L626-L628
*/
function isGlobalScopeAugmentation(module: ts.ModuleDeclaration): boolean {
return Boolean(module.flags & ts.NodeFlags.GlobalAugmentation);
}
/**
* Returns whether node is ambient module declaration (declare module "name" or declare global)
* @see https://github.com/Microsoft/TypeScript/blob/f7c4fefeb62416c311077a699cc15beb211c25c9/src/compiler/utilities.ts#L588-L590
*/
export function isAmbientModule(node: ts.Node): boolean {
return ts.isModuleDeclaration(node) && (node.name.kind === ts.SyntaxKind.StringLiteral || isGlobalScopeAugmentation(node));
}
/**
* Returns whether node is `declare module` ModuleDeclaration (not `declare global` or `namespace`)
*/
export function isDe | e: ts.Node): node is ts.ModuleDeclaration {
// `declare module ""`, `declare global` and `namespace {}` are ModuleDeclaration
// but here we need to check only `declare module` statements
return ts.isModuleDeclaration(node) && !(node.flags & ts.NodeFlags.Namespace) && !isGlobalScopeAugmentation(node);
}
/**
* Returns whether statement is `declare global` ModuleDeclaration
*/
export function isDeclareGlobalStatement(statement: ts.Statement): statement is ts.ModuleDeclaration {
return ts.isModuleDeclaration(statement) && isGlobalScopeAugmentation(statement);
}
/**
* Returns whether node is `namespace` ModuleDeclaration
*/
export function isNamespaceStatement(node: ts.Node): node is ts.ModuleDeclaration {
return ts.isModuleDeclaration(node) && Boolean(node.flags & ts.NodeFlags.Namespace);
}
export function getDeclarationsForSymbol(symbol: ts.Symbol): ts.Declaration[] {
const result: ts.Declaration[] = [];
// Disabling tslint is for backward compat with TypeScript < 3
// tslint:disable-next-line:strict-type-predicates
if (symbol.declarations !== undefined) {
result.push(...symbol.declarations);
}
// Disabling tslint is for backward compat with TypeScript < 3
// tslint:disable-next-line:strict-type-predicates
if (symbol.valueDeclaration !== undefined) {
// push valueDeclaration might be already in declarations array
// so let's check first to avoid duplication nodes
if (!result.includes(symbol.valueDeclaration)) {
result.push(symbol.valueDeclaration);
}
}
return result;
}
export function isDeclarationFromExternalModule(node: ts.Declaration): boolean {
return getLibraryName(node.getSourceFile().fileName) !== null;
}
export const enum ExportType {
CommonJS,
ES6Named,
ES6Default,
}
export interface SourceFileExport {
originalName: string;
exportedName: string;
symbol: ts.Symbol;
type: ExportType;
}
export function getExportsForSourceFile(typeChecker: ts.TypeChecker, sourceFileSymbol: ts.Symbol): SourceFileExport[] {
if (sourceFileSymbol.exports !== undefined) {
const commonJsExport = sourceFileSymbol.exports.get(ts.InternalSymbolName.ExportEquals);
if (commonJsExport !== undefined) {
const symbol = getActualSymbol(commonJsExport, typeChecker);
return [
{
symbol,
type: ExportType.CommonJS,
exportedName: '',
originalName: symbol.escapedName as string,
},
];
}
}
const result: SourceFileExport[] = typeChecker
.getExportsOfModule(sourceFileSymbol)
.map((symbol: ts.Symbol) => ({ symbol, exportedName: symbol.escapedName as string, type: ExportType.ES6Named, originalName: '' }));
if (sourceFileSymbol.exports !== undefined) {
const defaultExportSymbol = sourceFileSymbol.exports.get(ts.InternalSymbolName.Default);
if (defaultExportSymbol !== undefined) {
const defaultExport = result.find((exp: SourceFileExport) => exp.symbol === defaultExportSymbol);
if (defaultExport !== undefined) {
defaultExport.type = ExportType.ES6Default;
} else {
// it seems that default export is always returned by getExportsOfModule
// but let's add it to be sure add if there is no such export
result.push({
symbol: defaultExportSymbol,
type: ExportType.ES6Default,
exportedName: 'default',
originalName: '',
});
}
}
}
result.forEach((exp: SourceFileExport) => {
exp.symbol = getActualSymbol(exp.symbol, typeChecker);
const resolvedIdentifier = resolveIdentifierBySymbol(exp.symbol);
exp.originalName = resolvedIdentifier !== undefined ? resolvedIdentifier.getText() : exp.symbol.escapedName as string;
});
return result;
}
export function resolveIdentifier(typeChecker: ts.TypeChecker, identifier: ts.Identifier): ts.NamedDeclaration['name'] {
const symbol = getDeclarationNameSymbol(identifier, typeChecker);
if (symbol === null) {
return undefined;
}
return resolveIdentifierBySymbol(symbol);
}
function resolveIdentifierBySymbol(identifierSymbol: ts.Symbol): ts.NamedDeclaration['name'] {
const declarations = getDeclarationsForSymbol(identifierSymbol);
if (declarations.length === 0) {
return undefined;
}
const decl = declarations[0];
if (!isNodeNamedDeclaration(decl)) {
return undefined;
}
return decl.name;
}
export function getExportsForStatement(
exportedSymbols: readonly SourceFileExport[],
typeChecker: ts.TypeChecker,
statement: ts.Statement
): SourceFileExport[] {
if (ts.isVariableStatement(statement)) {
if (statement.declarationList.declarations.length === 0) {
return [];
}
const firstDeclarationExports = getExportsForName(
exportedSymbols,
typeChecker,
statement.declarationList.declarations[0].name
);
const allDeclarationsHaveSameExportType = statement.declarationList.declarations.every((variableDecl: ts.VariableDeclaration) => {
// all declaration should have the same export type
// TODO: for now it's not supported to have different type of exports
return getExportsForName(exportedSymbols, typeChecker, variableDecl.name)[0]?.type === firstDeclarationExports[0]?.type;
});
if (!allDeclarationsHaveSameExportType) {
// log warn?
return [];
}
return firstDeclarationExports;
}
const nodeName = getNodeName(statement);
if (nodeName === undefined) {
return [];
}
return getExportsForName(exportedSymbols, typeChecker, nodeName);
}
function getExportsForName(
exportedSymbols: readonly SourceFileExport[],
typeChecker: ts.TypeChecker,
name: NodeName
): SourceFileExport[] {
if (ts.isArrayBindingPattern(name) || ts.isObjectBindingPattern(name)) {
// TODO: binding patterns in variable declarations are not supported for now
// see https://github.com/microsoft/TypeScript/issues/30598 also
return [];
}
const declarationSymbol = typeChecker.getSymbolAtLocation(name);
return exportedSymbols.filter((rootExport: SourceFileExport) => rootExport.symbol === declarationSymbol);
}
// labelled tuples were | clareModule(nod | identifier_name |
typescript.ts | ifiers && node.modifiers.some((nodeModifier: ts.Modifier) => nodeModifier.kind === modifier));
}
export function getNodeName(node: ts.Node): NodeName | undefined {
const nodeName = (node as unknown as ts.NamedDeclaration).name;
if (nodeName === undefined) {
const defaultModifier = node.modifiers?.find((mod: ts.Modifier) => mod.kind === ts.SyntaxKind.DefaultKeyword);
if (defaultModifier !== undefined) {
return defaultModifier;
}
}
return nodeName;
}
export function getActualSymbol(symbol: ts.Symbol, typeChecker: ts.TypeChecker): ts.Symbol {
if (symbol.flags & ts.SymbolFlags.Alias) {
symbol = typeChecker.getAliasedSymbol(symbol);
}
return symbol;
}
export function getDeclarationNameSymbol(name: NodeName, typeChecker: ts.TypeChecker): ts.Symbol | null |
export function splitTransientSymbol(symbol: ts.Symbol, typeChecker: ts.TypeChecker): ts.Symbol[] {
// actually I think we even don't need to operate/use "Transient" symbols anywhere
// it's kind of aliased symbol, but just merged
// but it's hard to refractor everything to use array of symbols instead of just symbol
// so let's fix it for some places
if ((symbol.flags & ts.SymbolFlags.Transient) === 0) {
return [symbol];
}
// "Transient" symbol is kinda "merged" symbol
// I don't really know is this way to "split" is correct
// but it seems that it works for now ¯\_(ツ)_/¯
const declarations = getDeclarationsForSymbol(symbol);
const result: ts.Symbol[] = [];
for (const declaration of declarations) {
if (!isNodeNamedDeclaration(declaration) || declaration.name === undefined) {
continue;
}
const sym = typeChecker.getSymbolAtLocation(declaration.name);
if (sym === undefined) {
continue;
}
result.push(getActualSymbol(sym, typeChecker));
}
return result;
}
/**
* @see https://github.com/Microsoft/TypeScript/blob/f7c4fefeb62416c311077a699cc15beb211c25c9/src/compiler/utilities.ts#L626-L628
*/
function isGlobalScopeAugmentation(module: ts.ModuleDeclaration): boolean {
return Boolean(module.flags & ts.NodeFlags.GlobalAugmentation);
}
/**
* Returns whether node is ambient module declaration (declare module "name" or declare global)
* @see https://github.com/Microsoft/TypeScript/blob/f7c4fefeb62416c311077a699cc15beb211c25c9/src/compiler/utilities.ts#L588-L590
*/
export function isAmbientModule(node: ts.Node): boolean {
return ts.isModuleDeclaration(node) && (node.name.kind === ts.SyntaxKind.StringLiteral || isGlobalScopeAugmentation(node));
}
/**
* Returns whether node is `declare module` ModuleDeclaration (not `declare global` or `namespace`)
*/
export function isDeclareModule(node: ts.Node): node is ts.ModuleDeclaration {
// `declare module ""`, `declare global` and `namespace {}` are ModuleDeclaration
// but here we need to check only `declare module` statements
return ts.isModuleDeclaration(node) && !(node.flags & ts.NodeFlags.Namespace) && !isGlobalScopeAugmentation(node);
}
/**
* Returns whether statement is `declare global` ModuleDeclaration
*/
export function isDeclareGlobalStatement(statement: ts.Statement): statement is ts.ModuleDeclaration {
return ts.isModuleDeclaration(statement) && isGlobalScopeAugmentation(statement);
}
/**
* Returns whether node is `namespace` ModuleDeclaration
*/
export function isNamespaceStatement(node: ts.Node): node is ts.ModuleDeclaration {
return ts.isModuleDeclaration(node) && Boolean(node.flags & ts.NodeFlags.Namespace);
}
export function getDeclarationsForSymbol(symbol: ts.Symbol): ts.Declaration[] {
const result: ts.Declaration[] = [];
// Disabling tslint is for backward compat with TypeScript < 3
// tslint:disable-next-line:strict-type-predicates
if (symbol.declarations !== undefined) {
result.push(...symbol.declarations);
}
// Disabling tslint is for backward compat with TypeScript < 3
// tslint:disable-next-line:strict-type-predicates
if (symbol.valueDeclaration !== undefined) {
// push valueDeclaration might be already in declarations array
// so let's check first to avoid duplication nodes
if (!result.includes(symbol.valueDeclaration)) {
result.push(symbol.valueDeclaration);
}
}
return result;
}
export function isDeclarationFromExternalModule(node: ts.Declaration): boolean {
return getLibraryName(node.getSourceFile().fileName) !== null;
}
export const enum ExportType {
CommonJS,
ES6Named,
ES6Default,
}
export interface SourceFileExport {
originalName: string;
exportedName: string;
symbol: ts.Symbol;
type: ExportType;
}
export function getExportsForSourceFile(typeChecker: ts.TypeChecker, sourceFileSymbol: ts.Symbol): SourceFileExport[] {
if (sourceFileSymbol.exports !== undefined) {
const commonJsExport = sourceFileSymbol.exports.get(ts.InternalSymbolName.ExportEquals);
if (commonJsExport !== undefined) {
const symbol = getActualSymbol(commonJsExport, typeChecker);
return [
{
symbol,
type: ExportType.CommonJS,
exportedName: '',
originalName: symbol.escapedName as string,
},
];
}
}
const result: SourceFileExport[] = typeChecker
.getExportsOfModule(sourceFileSymbol)
.map((symbol: ts.Symbol) => ({ symbol, exportedName: symbol.escapedName as string, type: ExportType.ES6Named, originalName: '' }));
if (sourceFileSymbol.exports !== undefined) {
const defaultExportSymbol = sourceFileSymbol.exports.get(ts.InternalSymbolName.Default);
if (defaultExportSymbol !== undefined) {
const defaultExport = result.find((exp: SourceFileExport) => exp.symbol === defaultExportSymbol);
if (defaultExport !== undefined) {
defaultExport.type = ExportType.ES6Default;
} else {
// it seems that default export is always returned by getExportsOfModule
// but let's add it to be sure add if there is no such export
result.push({
symbol: defaultExportSymbol,
type: ExportType.ES6Default,
exportedName: 'default',
originalName: '',
});
}
}
}
result.forEach((exp: SourceFileExport) => {
exp.symbol = getActualSymbol(exp.symbol, typeChecker);
const resolvedIdentifier = resolveIdentifierBySymbol(exp.symbol);
exp.originalName = resolvedIdentifier !== undefined ? resolvedIdentifier.getText() : exp.symbol.escapedName as string;
});
return result;
}
export function resolveIdentifier(typeChecker: ts.TypeChecker, identifier: ts.Identifier): ts.NamedDeclaration['name'] {
const symbol = getDeclarationNameSymbol(identifier, typeChecker);
if (symbol === null) {
return undefined;
}
return resolveIdentifierBySymbol(symbol);
}
function resolveIdentifierBySymbol(identifierSymbol: ts.Symbol): ts.NamedDeclaration['name'] {
const declarations = getDeclarationsForSymbol(identifierSymbol);
if (declarations.length === 0) {
return undefined;
}
const decl = declarations[0];
if (!isNodeNamedDeclaration(decl)) {
return undefined;
}
return decl.name;
}
export function getExportsForStatement(
exportedSymbols: readonly SourceFileExport[],
typeChecker: ts.TypeChecker,
statement: ts.Statement
): SourceFileExport[] {
if (ts.isVariableStatement(statement)) {
if (statement.declarationList.declarations.length === 0) {
return [];
}
const firstDeclarationExports = getExportsForName(
exportedSymbols,
typeChecker,
statement.declarationList.declarations[0].name
);
const allDeclarationsHaveSameExportType = statement.declarationList.declarations.every((variableDecl: ts.VariableDeclaration) => {
// all declaration should have the same export type
// TODO: for now it's not supported to have different type of exports
return getExportsForName(exportedSymbols, typeChecker, variableDecl.name)[0]?.type === firstDeclarationExports[0]?.type;
});
if (!allDeclarationsHaveSameExportType) {
// log warn?
return [];
}
return firstDeclarationExports;
}
const nodeName = getNodeName(statement);
if (nodeName === undefined) {
return [];
}
return getExportsForName(exportedSymbols, typeChecker, nodeName);
}
function getExportsForName(
exportedSymbols: readonly SourceFileExport[],
typeChecker: ts.TypeChecker,
name: NodeName
): SourceFileExport[] {
if (ts.isArrayBindingPattern(name) || ts.isObjectBindingPattern(name)) {
// TODO: binding patterns in variable declarations are not supported for now
// see https://github.com/microsoft/TypeScript/issues/30598 also
return [];
}
const declarationSymbol = typeChecker.getSymbolAtLocation(name);
return exportedSymbols.filter((rootExport: SourceFileExport) => rootExport.symbol === declarationSymbol);
}
// labelled tuples were introduced | {
const symbol = typeChecker.getSymbolAtLocation(name);
if (symbol === undefined) {
return null;
}
return getActualSymbol(symbol, typeChecker);
} | identifier_body |
test.js | // 3) if they are both objects, compare each property
if(typeof(x)=="object" && typeof(x)=="object"){
// does every property in x also exist in y?
for (var p in x) {
// log error if a property is not defined
if ( ! x.hasOwnProperty(p) ){
console.log('local lacks a '+p)
return false
}
if ( ! y.hasOwnProperty(p) ){
console.log('server lacks a '+p)
return false
}
// if they are 'pos' objects (used in Pyret), don't bother comparing (yet)
if (p==="pos") continue
// ignore the hashcode property
if(p==="_eqHashCode") continue
// toplevel properties are equal if the sets of names are equal
// WARNING: this may require stronger checking!
if(p==="toplevels"){
// if they're not the same length, bail
if(x_toplevels.length !== y_toplevels.length){
console.log('different number of toplevels. local has '
+x_toplevels.length+', and server has '
+y_toplevels.length)
return false
}
// if they're not the same names, bail
if(!x_toplevels.every(function(v,i) { return y_toplevels.indexOf(v) > -1})){
console.log('different toplevel names')
return false
}
// build sorted lists of all module variables, return true if they are identical
var x_modVariables = x.toplevels.filter(function(tl){return tl.$==="module-variable"}).map(extractTopLevelName)
var y_modVariables = y.toplevels.filter(function(tl){return tl.$==="module-variable"}).map(extractTopLevelName)
x_modVariables.sort()
y_modVariables.sort()
if(!sameResults(x_modVariables, y_modVariables)){
console.log('module variables differed')
return false
}
continue
}
// use pos's as keys into the toplevel dictionaries, and compare their values
if((p==="pos") && (x["$"]==="toplevel") && (x["$"]==="toplevel")){
if(x_toplevels[Number(x[p])] === y_toplevels[Number(y[p])]){ continue }
else {
console.log('different indices for '+x_toplevels[Number(x[p])])
return false
}
}
// if they both have the property, compare it
if(sameResults(x[p],y[p])) continue
else{
console.log('local and server differ on property: '+p)
return false
}
}
// does every property in y also exist in x?
for (p in y) {
// log error if a property is not defined
if ( y.hasOwnProperty(p) && !x.hasOwnProperty(p) ){ return false }
}
// 4)if they are literals, they must be identical
} else {
if (canonicalizeLiteral(x) !== canonicalizeLiteral(y)){
console.log('(local, server) literals not the same:\n'+x+'\nis not equal to \n'+y)
return false
}
}
return true
}
// set the parent row to pink, and add a link that will load
// a diff of the expected and recieved output
function setTestFailureLink(test, expected, recieved){
if(typeof recieved !== "string") recieved = JSON.stringify(recieved)
if(typeof expected !== "string") expected = JSON.stringify(expected)
recieved = recieved.replace(/\s/g,'')
expected = expected.replace(/\s/g,'')
test.style.background = 'pink'
test.style.cursor = 'pointer'
test.onclick = function(){compareText(expected,recieved)}
return false
}
function compareText(expected, recieved){
document.getElementById('text1').value = expected
document.getElementById('text2').value = recieved
document.getElementById('compareText').submit()
}
function loadTests(){
var testButton = document.getElementById('runTests')
var script = document.createElement('script')
var head = document.getElementsByTagName('head')[0]
testButton.value = "Loading tests..."
head.appendChild(script)
script.type = "text/javascript"
script.src = "https://spreadsheets.google.com/feeds/list/0AjzMl1BJlJDkdDI2c0VUSHNZMnR6ZVR5S2hXZEdtd1E/1/public/basic?alt=json-in-script&callback=loadSuite"
}
function loadSuite(json){
var which = document.getElementById('whichTests')
console.log(json)
for(var i=0; i<json.feed.entry.length; i++){
rows.push(json.feed.entry[i].content.$t)
var chunks = rows[i].split(/expr\:|, local\: |, server\: |, diff\: |, reason\: |, desugar\: |, bytecode\: |, pyret\: |, pyretast\: /)
var expr = chunks[1].replace(/^\s+/,"")
var local = chunks[2]
var server = chunks[3]
var difference = chunks[4]
var reason = chunks[5]
var desugar = chunks[6]
var bytecode = chunks[7]
var pyretSrc = chunks[8]
var pyretAST = chunks[9]
var opt = document.createElement('option')
expr = expr.replace(/^\'\'/,"'")
tests.push({expr: expr, local: local, server: server, reason: reason, desugar: desugar
, bytecode: bytecode, pyretSrc: pyretSrc, pyretAST: pyretAST})
opt.value=opt.innerHTML = Number(i)+1
which.appendChild(opt)
}
console.log(document.getElementById('runTests'))
document.getElementById('runTests').disabled=false
document.getElementById('runTests').value="Run test:"
document.getElementById('runTests').onclick=function(){runTests(true)}
document.getElementById('memoryTest').disabled=false
console.log('Test Suite data retrieved from Google Drive: '+tests.length+' tests loaded')
which.style.display = 'inline-block'
}
function runTests(verbose){
function test(expr, expected, desugarRef, bytecodeRef, pyretSrcRef, pyretJSONRef){
// show the result
var row = document.createElement('tr')
var num = document.createElement('td')
var test = document.createElement('td')
var lexEl = document.createElement('td')
var parseEl = document.createElement('td')
var desugar=document.createElement('td')
var bytecode=document.createElement('td')
var pyretSrc = document.createElement('td')
var pyretAST = document.createElement('td')
num.innerHTML = (i+1)+')' // make test nums 1-aligned, instead of 0-aligned
test.innerHTML = expr // show which expr we're testing
row.appendChild(num)
row.appendChild(test)
row.appendChild(lexEl)
row.appendChild(parseEl)
row.appendChild(desugar)
row.appendChild(bytecode)
table.appendChild(row)
row.style.background = 'lightgreen'
// LEX: If we pass when we shouldn't, set to pink and return false.
// Catch: If we fail better than the server, set to blue and return true.
// Catch: If we fail equal to the server, set to green and return true.
// Catch: If we fail when we shoulnd't, set to pink and return false
lexEl.innerHTML = 'lex'
try{
var sexp = lex(expr,"<definitions>")
} catch (e) {
if (e instanceof Error) {
throw e
}
recieved = JSON.parse(e)
if(recieved.betterThanServer){
lexEl.style.background = 'lightblue'
return true
}
if(expected === "LOCAL IS BETTER"){
lexEl.style.background = 'lightblue'
return true
}
if(expected === "PASS"){ return setTestFailureLink(row, expected, recieved)}
else{
let localJSON = JSON.parse(recieved["structured-error"])
let serverJSON = JSON.parse(JSON.parse(expected)["structured-error"])
if(sameResults(localJSON, serverJSON)){
lexEl.style.background = 'lightgreen'
return true
}
else{ return setTestFailureLink(row, expected, recieved)}
}
}
lexEl.style.background = 'lightgreen'
// PARSE: If we pass when we shouldn't, set to pink and return false.
// Catch: If we fail better than the server, set to blue and return true.
// Catch: If we fail equal to the server, set to green and return true.
// Catch: If we fail when we shoulnd't, set to pink and return false
parseEl.innerHTML = 'parse'
try{
var AST = parse(sexp)
} catch (e) {
if (e instanceof Error) {
throw e
}
recieved = JSON.parse(e)
if(recieved.betterThanServer){
parseEl.style.background = 'lightblue'
return true
} | if(expected === "LOCAL IS BETTER"){
parseEl.style.background = 'lightblue'
return true
}
if(expected === "PASS"){ return setTestFailureLink(row, expected, recieved)}
else{
let localJSON = JSON.parse(recieved["structured-error"])
let serverJSON | random_line_split |
|
test.js | // 3) if they are both objects, compare each property
if(typeof(x)=="object" && typeof(x)=="object"){
// does every property in x also exist in y?
for (var p in x) {
// log error if a property is not defined
if ( ! x.hasOwnProperty(p) ){
console.log('local lacks a '+p)
return false
}
if ( ! y.hasOwnProperty(p) ){
console.log('server lacks a '+p)
return false
}
// if they are 'pos' objects (used in Pyret), don't bother comparing (yet)
if (p==="pos") continue
// ignore the hashcode property
if(p==="_eqHashCode") continue
// toplevel properties are equal if the sets of names are equal
// WARNING: this may require stronger checking!
if(p==="toplevels"){
// if they're not the same length, bail
if(x_toplevels.length !== y_toplevels.length){
console.log('different number of toplevels. local has '
+x_toplevels.length+', and server has '
+y_toplevels.length)
return false
}
// if they're not the same names, bail
if(!x_toplevels.every(function(v,i) { return y_toplevels.indexOf(v) > -1})){
console.log('different toplevel names')
return false
}
// build sorted lists of all module variables, return true if they are identical
var x_modVariables = x.toplevels.filter(function(tl){return tl.$==="module-variable"}).map(extractTopLevelName)
var y_modVariables = y.toplevels.filter(function(tl){return tl.$==="module-variable"}).map(extractTopLevelName)
x_modVariables.sort()
y_modVariables.sort()
if(!sameResults(x_modVariables, y_modVariables)){
console.log('module variables differed')
return false
}
continue
}
// use pos's as keys into the toplevel dictionaries, and compare their values
if((p==="pos") && (x["$"]==="toplevel") && (x["$"]==="toplevel")){
if(x_toplevels[Number(x[p])] === y_toplevels[Number(y[p])]){ continue }
else {
console.log('different indices for '+x_toplevels[Number(x[p])])
return false
}
}
// if they both have the property, compare it
if(sameResults(x[p],y[p])) continue
else{
console.log('local and server differ on property: '+p)
return false
}
}
// does every property in y also exist in x?
for (p in y) {
// log error if a property is not defined
if ( y.hasOwnProperty(p) && !x.hasOwnProperty(p) ){ return false }
}
// 4)if they are literals, they must be identical
} else {
if (canonicalizeLiteral(x) !== canonicalizeLiteral(y)){
console.log('(local, server) literals not the same:\n'+x+'\nis not equal to \n'+y)
return false
}
}
return true
}
// set the parent row to pink, and add a link that will load
// a diff of the expected and recieved output
function setTestFailureLink(test, expected, recieved){
if(typeof recieved !== "string") recieved = JSON.stringify(recieved)
if(typeof expected !== "string") expected = JSON.stringify(expected)
recieved = recieved.replace(/\s/g,'')
expected = expected.replace(/\s/g,'')
test.style.background = 'pink'
test.style.cursor = 'pointer'
test.onclick = function(){compareText(expected,recieved)}
return false
}
function compareText(expected, recieved){
document.getElementById('text1').value = expected
document.getElementById('text2').value = recieved
document.getElementById('compareText').submit()
}
function loadTests(){
var testButton = document.getElementById('runTests')
var script = document.createElement('script')
var head = document.getElementsByTagName('head')[0]
testButton.value = "Loading tests..."
head.appendChild(script)
script.type = "text/javascript"
script.src = "https://spreadsheets.google.com/feeds/list/0AjzMl1BJlJDkdDI2c0VUSHNZMnR6ZVR5S2hXZEdtd1E/1/public/basic?alt=json-in-script&callback=loadSuite"
}
function loadSuite(json) | which.appendChild(opt)
}
console.log(document.getElementById('runTests'))
document.getElementById('runTests').disabled=false
document.getElementById('runTests').value="Run test:"
document.getElementById('runTests').onclick=function(){runTests(true)}
document.getElementById('memoryTest').disabled=false
console.log('Test Suite data retrieved from Google Drive: '+tests.length+' tests loaded')
which.style.display = 'inline-block'
}
function runTests(verbose){
function test(expr, expected, desugarRef, bytecodeRef, pyretSrcRef, pyretJSONRef){
// show the result
var row = document.createElement('tr')
var num = document.createElement('td')
var test = document.createElement('td')
var lexEl = document.createElement('td')
var parseEl = document.createElement('td')
var desugar=document.createElement('td')
var bytecode=document.createElement('td')
var pyretSrc = document.createElement('td')
var pyretAST = document.createElement('td')
num.innerHTML = (i+1)+')' // make test nums 1-aligned, instead of 0-aligned
test.innerHTML = expr // show which expr we're testing
row.appendChild(num)
row.appendChild(test)
row.appendChild(lexEl)
row.appendChild(parseEl)
row.appendChild(desugar)
row.appendChild(bytecode)
table.appendChild(row)
row.style.background = 'lightgreen'
// LEX: If we pass when we shouldn't, set to pink and return false.
// Catch: If we fail better than the server, set to blue and return true.
// Catch: If we fail equal to the server, set to green and return true.
// Catch: If we fail when we shoulnd't, set to pink and return false
lexEl.innerHTML = 'lex'
try{
var sexp = lex(expr,"<definitions>")
} catch (e) {
if (e instanceof Error) {
throw e
}
recieved = JSON.parse(e)
if(recieved.betterThanServer){
lexEl.style.background = 'lightblue'
return true
}
if(expected === "LOCAL IS BETTER"){
lexEl.style.background = 'lightblue'
return true
}
if(expected === "PASS"){ return setTestFailureLink(row, expected, recieved)}
else{
let localJSON = JSON.parse(recieved["structured-error"])
let serverJSON = JSON.parse(JSON.parse(expected)["structured-error"])
if(sameResults(localJSON, serverJSON)){
lexEl.style.background = 'lightgreen'
return true
}
else{ return setTestFailureLink(row, expected, recieved)}
}
}
lexEl.style.background = 'lightgreen'
// PARSE: If we pass when we shouldn't, set to pink and return false.
// Catch: If we fail better than the server, set to blue and return true.
// Catch: If we fail equal to the server, set to green and return true.
// Catch: If we fail when we shoulnd't, set to pink and return false
parseEl.innerHTML = 'parse'
try{
var AST = parse(sexp)
} catch (e) {
if (e instanceof Error) {
throw e
}
recieved = JSON.parse(e)
if(recieved.betterThanServer){
parseEl.style.background = 'lightblue'
return true
}
if(expected === "LOCAL IS BETTER"){
parseEl.style.background = 'lightblue'
return true
}
if(expected === "PASS"){ return setTestFailureLink(row, expected, recieved)}
else{
let localJSON = JSON.parse(recieved["structured-error"])
let serverJSON | {
var which = document.getElementById('whichTests')
console.log(json)
for(var i=0; i<json.feed.entry.length; i++){
rows.push(json.feed.entry[i].content.$t)
var chunks = rows[i].split(/expr\:|, local\: |, server\: |, diff\: |, reason\: |, desugar\: |, bytecode\: |, pyret\: |, pyretast\: /)
var expr = chunks[1].replace(/^\s+/,"")
var local = chunks[2]
var server = chunks[3]
var difference = chunks[4]
var reason = chunks[5]
var desugar = chunks[6]
var bytecode = chunks[7]
var pyretSrc = chunks[8]
var pyretAST = chunks[9]
var opt = document.createElement('option')
expr = expr.replace(/^\'\'/,"'")
tests.push({expr: expr, local: local, server: server, reason: reason, desugar: desugar
, bytecode: bytecode, pyretSrc: pyretSrc, pyretAST: pyretAST})
opt.value=opt.innerHTML = Number(i)+1 | identifier_body |
test.js | (obj){
var fields = [], obj2={}
for (i in obj) { if (obj.hasOwnProperty(i) && obj[i] !== "") fields.push(i) }
fields.sort()
for (var i=0;i<fields.length; i++) { obj2[fields[i]] = obj[fields[i]] }
return obj2
}
function canonicalizeLiteral(lit){
return lit.toString().replace(/\s*/g,"")
}
// if either one is an object, canonicalize it
if(typeof(x) === "object") x = canonicalizeObject(x)
if(typeof(y) === "object") y = canonicalizeObject(y)
// 1) if both are Locations, we only care about startChar and span, so perform a weak comparison
if ( x.hasOwnProperty('offset') && y.hasOwnProperty('offset') ){
return ( (x.span == y.span) && (x.offset == y.offset) )
}
// 2) if both objects have a prefix field, build our dictionaries *before* moving on
if(x.hasOwnProperty('prefix') && y.hasOwnProperty('prefix')){
x_toplevels = x.prefix.toplevels.map(extractTopLevelName)
y_toplevels = y.prefix.toplevels.map(extractTopLevelName)
}
// 3) if they are both objects, compare each property
if(typeof(x)=="object" && typeof(x)=="object"){
// does every property in x also exist in y?
for (var p in x) {
// log error if a property is not defined
if ( ! x.hasOwnProperty(p) ){
console.log('local lacks a '+p)
return false
}
if ( ! y.hasOwnProperty(p) ){
console.log('server lacks a '+p)
return false
}
// if they are 'pos' objects (used in Pyret), don't bother comparing (yet)
if (p==="pos") continue
// ignore the hashcode property
if(p==="_eqHashCode") continue
// toplevel properties are equal if the sets of names are equal
// WARNING: this may require stronger checking!
if(p==="toplevels"){
// if they're not the same length, bail
if(x_toplevels.length !== y_toplevels.length){
console.log('different number of toplevels. local has '
+x_toplevels.length+', and server has '
+y_toplevels.length)
return false
}
// if they're not the same names, bail
if(!x_toplevels.every(function(v,i) { return y_toplevels.indexOf(v) > -1})){
console.log('different toplevel names')
return false
}
// build sorted lists of all module variables, return true if they are identical
var x_modVariables = x.toplevels.filter(function(tl){return tl.$==="module-variable"}).map(extractTopLevelName)
var y_modVariables = y.toplevels.filter(function(tl){return tl.$==="module-variable"}).map(extractTopLevelName)
x_modVariables.sort()
y_modVariables.sort()
if(!sameResults(x_modVariables, y_modVariables)){
console.log('module variables differed')
return false
}
continue
}
// use pos's as keys into the toplevel dictionaries, and compare their values
if((p==="pos") && (x["$"]==="toplevel") && (x["$"]==="toplevel")){
if(x_toplevels[Number(x[p])] === y_toplevels[Number(y[p])]){ continue }
else {
console.log('different indices for '+x_toplevels[Number(x[p])])
return false
}
}
// if they both have the property, compare it
if(sameResults(x[p],y[p])) continue
else{
console.log('local and server differ on property: '+p)
return false
}
}
// does every property in y also exist in x?
for (p in y) {
// log error if a property is not defined
if ( y.hasOwnProperty(p) && !x.hasOwnProperty(p) ){ return false }
}
// 4)if they are literals, they must be identical
} else {
if (canonicalizeLiteral(x) !== canonicalizeLiteral(y)){
console.log('(local, server) literals not the same:\n'+x+'\nis not equal to \n'+y)
return false
}
}
return true
}
// set the parent row to pink, and add a link that will load
// a diff of the expected and recieved output
function setTestFailureLink(test, expected, recieved){
if(typeof recieved !== "string") recieved = JSON.stringify(recieved)
if(typeof expected !== "string") expected = JSON.stringify(expected)
recieved = recieved.replace(/\s/g,'')
expected = expected.replace(/\s/g,'')
test.style.background = 'pink'
test.style.cursor = 'pointer'
test.onclick = function(){compareText(expected,recieved)}
return false
}
function compareText(expected, recieved){
document.getElementById('text1').value = expected
document.getElementById('text2').value = recieved
document.getElementById('compareText').submit()
}
function loadTests(){
var testButton = document.getElementById('runTests')
var script = document.createElement('script')
var head = document.getElementsByTagName('head')[0]
testButton.value = "Loading tests..."
head.appendChild(script)
script.type = "text/javascript"
script.src = "https://spreadsheets.google.com/feeds/list/0AjzMl1BJlJDkdDI2c0VUSHNZMnR6ZVR5S2hXZEdtd1E/1/public/basic?alt=json-in-script&callback=loadSuite"
}
function loadSuite(json){
var which = document.getElementById('whichTests')
console.log(json)
for(var i=0; i<json.feed.entry.length; i++){
rows.push(json.feed.entry[i].content.$t)
var chunks = rows[i].split(/expr\:|, local\: |, server\: |, diff\: |, reason\: |, desugar\: |, bytecode\: |, pyret\: |, pyretast\: /)
var expr = chunks[1].replace(/^\s+/,"")
var local = chunks[2]
var server = chunks[3]
var difference = chunks[4]
var reason = chunks[5]
var desugar = chunks[6]
var bytecode = chunks[7]
var pyretSrc = chunks[8]
var pyretAST = chunks[9]
var opt = document.createElement('option')
expr = expr.replace(/^\'\'/,"'")
tests.push({expr: expr, local: local, server: server, reason: reason, desugar: desugar
, bytecode: bytecode, pyretSrc: pyretSrc, pyretAST: pyretAST})
opt.value=opt.innerHTML = Number(i)+1
which.appendChild(opt)
}
console.log(document.getElementById('runTests'))
document.getElementById('runTests').disabled=false
document.getElementById('runTests').value="Run test:"
document.getElementById('runTests').onclick=function(){runTests(true)}
document.getElementById('memoryTest').disabled=false
console.log('Test Suite data retrieved from Google Drive: '+tests.length+' tests loaded')
which.style.display = 'inline-block'
}
function runTests(verbose){
function test(expr, expected, desugarRef, bytecodeRef, pyretSrcRef, pyretJSONRef){
// show the result
var row = document.createElement('tr')
var num = document.createElement('td')
var test = document.createElement('td')
var lexEl = document.createElement('td')
var parseEl = document.createElement('td')
var desugar=document.createElement('td')
var bytecode=document.createElement('td')
var pyretSrc = document.createElement('td')
var pyretAST = document.createElement('td')
num.innerHTML = (i+1)+')' // make test nums 1-aligned, instead of 0-aligned
test.innerHTML = expr // show which expr we're testing
row.appendChild(num)
row.appendChild(test)
row.appendChild(lexEl)
row.appendChild(parseEl)
row.appendChild(desugar)
row.appendChild(bytecode)
table.appendChild(row)
row.style.background = 'lightgreen'
// LEX: If we pass when we shouldn't, set to pink and return false.
// Catch: If we fail better than the server, set to blue and return true.
// Catch: If we fail equal to the server, set to green and return true.
// Catch: If we fail when we shoulnd't, set to pink and return false
lexEl.innerHTML = 'lex'
try{
var sexp = lex(expr,"<definitions>")
} catch (e) {
if (e instanceof Error) {
throw e
}
recieved = JSON.parse(e)
if(recieved.betterThanServer){
lexEl.style.background = 'lightblue'
return true
}
if(expected === "LOCAL IS BETTER"){
lexEl.style.background = 'lightblue'
return true
}
if(expected === "PASS"){ return setTestFailureLink(row, expected, recieved)}
else{
let localJSON = JSON.parse(recieved["structured-error"])
let serverJSON = JSON | canonicalizeObject | identifier_name |
|
argument.ts | 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, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as Api from '../../api/v2';
import {
NewSurfaceArgument,
PermissionArgument,
OptionArgument,
ConfirmationArgument,
DateTimeArgument,
SignInArgument,
PlaceArgument,
TransactionDecisionArgument,
TransactionRequirementsArgument,
DeliveryAddressArgument,
RegisterUpdateArgument,
UpdatePermissionUserIdArgument,
CompletePurchaseArgument,
DigitalPurchaseCheckArgument,
} from '..';
import {RepromptArgument, FinalRepromptArgument} from './noinput';
import {MediaStatusArgument} from './media';
// Need to import because of https://github.com/Microsoft/TypeScript/issues/9944
import {ApiClientObjectMap} from '../../../../common';
// Need to use type to avoid unused local linter errors
export {ApiClientObjectMap};
/** @public */
export type Argument =
Api.GoogleActionsV2Argument[keyof Api.GoogleActionsV2Argument];
export interface ArgumentsNamed {
/**
* True if the request follows a previous request asking for
* permission from the user and the user granted the permission(s).
* Otherwise, false.
* Only use after calling {@link Permission|conv.ask(new Permission)}
* or {@link UpdatePermission|conv.ask(new UpdatePermission)}.
* @public
*/
PERMISSION?: PermissionArgument;
/**
* The option key user chose from options response.
* Only use after calling {@link List|conv.ask(new List)}
* or {@link Carousel|conv.ask(new Carousel)}.
* @public
*/
OPTION?: OptionArgument;
/**
* The transactability of user.
* Only use after calling {@link TransactionRequirements|conv.ask(new TransactionRequirements)}.
* Undefined if no result given.
* @public
*/
TRANSACTION_REQUIREMENTS_CHECK_RESULT?: TransactionRequirementsArgument;
/**
* The order delivery address.
* Only use after calling {@link DeliveryAddress|conv.ask(new DeliveryAddress)}.
* @public
*/
DELIVERY_ADDRESS_VALUE?: DeliveryAddressArgument;
/**
* The transaction decision information.
* Is object with userDecision only if user declines.
* userDecision will be one of {@link GoogleActionsV2TransactionDecisionValueUserDecision}.
* Only use after calling {@link TransactionDecision|conv.ask(new TransactionDecision)}.
* @public
*/
TRANSACTION_DECISION_VALUE?: TransactionDecisionArgument;
/**
* The complete purchase information.
* Only use after calling {@link CompletePurchase|conv.ask(new CompletePurchase)}.
* @public
*/
COMPLETE_PURCHASE_VALUE?: CompletePurchaseArgument;
/**
* Only use after calling {@link DigitalPurchaseCheck|conv.ask(new DigitalPurchaseCheck)}.
* @public
*/
DIGITAL_PURCHASE_CHECK_RESULT?: DigitalPurchaseCheckArgument;
/**
* The confirmation decision.
* Use after {@link Confirmation|conv.ask(new Confirmation)}
* @public
*/
CONFIRMATION?: ConfirmationArgument;
/**
* The user provided date and time.
* Use after {@link DateTime|conv.ask(new DateTime)}
* @public
*/
DATETIME?: DateTimeArgument;
/**
* The status of user sign in request.
* Use after {@link SignIn|conv.ask(new SignIn)}
* @public
*/
SIGN_IN?: SignInArgument;
/**
* The number of subsequent reprompts related to silent input from the user.
* This should be used along with the `actions.intent.NO_INPUT` intent to reprompt the
* user for input in cases where the Google Assistant could not pick up any speech.
* @public
*/
REPROMPT_COUNT?: RepromptArgument;
/**
* True if it is the final reprompt related to silent input from the user.
* This should be used along with the `actions.intent.NO_INPUT` intent to give the final
* response to the user after multiple silences and should be an `conv.close`
* which ends the conversation.
* @public
*/
IS_FINAL_REPROMPT?: FinalRepromptArgument;
/**
* The result of {@link NewSurface|conv.ask(new NewSurface)}
* True if user has triggered conversation on a new device following the
* `actions.intent.NEW_SURFACE` intent.
* @public
*/
NEW_SURFACE?: NewSurfaceArgument;
/**
* True if user accepted update registration request.
* Used with {@link RegisterUpdate|conv.ask(new RegisterUpdate)}
* @public
*/
REGISTER_UPDATE?: RegisterUpdateArgument;
/**
* The updates user id.
* Only use after calling {@link UpdatePermission|conv.ask(new UpdatePermission)}.
* @public
*/
UPDATES_USER_ID?: UpdatePermissionUserIdArgument;
/**
* The user provided place.
* Use after {@link Place|conv.ask(new Place)}.
* @public
*/
PLACE?: PlaceArgument;
/**
* The status of MEDIA_STATUS intent.
* @public
*/
MEDIA_STATUS?: MediaStatusArgument;
}
export interface ArgumentsParsed extends ArgumentsNamed {
/** @public */
[name: string]: Argument | undefined;
}
/** @hidden */
export interface ArgumentsIndexable {
[key: string]: Argument;
}
export interface ArgumentsStatus {
/** @public */
[name: string]: Api.GoogleRpcStatus | undefined;
}
export interface ArgumentsRaw {
/** @public */
[name: string]: Api.GoogleActionsV2Argument;
}
const getValue = (arg: Api.GoogleActionsV2Argument): Argument => {
for (const key in arg) {
if (key === 'name' || key === 'textValue' || key === 'status') |
return (arg as ArgumentsIndexable)[key];
}
// Manually handle the PERMISSION argument because of a bug not returning boolValue
if (arg.name === 'PERMISSION') {
return !!arg.boolValue;
}
return arg.textValue;
};
export class Parsed {
/** @public */
list: Argument[];
/** @public */
input: ArgumentsParsed = {};
/** @hidden */
constructor(raw: Api.GoogleActionsV2Argument[]) {
this.list = raw.map((arg, i) => {
const value = getValue(arg);
const name = arg.name!;
this.input[name] = value;
return value;
});
}
/** @public */
get<TName extends keyof ArgumentsNamed>(name: TName): ArgumentsNamed[TName];
/** @public */
get(name: string): Argument;
get(name: string) {
return this.input[name];
}
}
export class Status {
/** @public */
list: (Api.GoogleRpcStatus | undefined)[];
/** @public */
input: ArgumentsStatus = {};
/** @hidden */
constructor(raw: Api.GoogleActionsV2Argument[]) {
this.list = raw.map((arg, i) => {
const name = arg.name!;
const status = arg.status;
this.input[name] = status;
return status;
});
}
/** @public */
get(name: string) {
return this.input[name];
}
}
export class Raw {
/** @public */
input: ArgumentsRaw;
/** @hidden */
constructor(public list: Api.GoogleActionsV2Argument[]) {
this.input = list.reduce((o, arg) => {
o[arg.name!] = arg;
return o;
}, {} as ArgumentsRaw);
}
/** @public */
get(name: string) {
return this.input[name];
}
}
export class Arguments {
/** @public */
parsed: Parsed;
/** @public */
status: Status;
/** @public */
raw: Raw;
/** @hidden */
constructor(raw: Api.GoogleActionsV2Argument[] = []) {
this.parsed = new Parsed(raw);
this.status = new Status(raw);
this.raw = new Raw(raw);
}
/**
* Get the argument value by name from the current intent.
* The first property value not named `name` or `status` will be returned.
* Will retrieve `textValue` last.
* If there is no other properties, return undefined.
*
* @example
* ```javascript
*
* // Actions SDK
* app.intent('actions.intent.PERMISSION', conv => {
* const granted = conv.arguments.get('PERMISSION') // boolean true if granted, false if not
* })
*
* // Dialogflow
* // Create a Dialogflow intent with the `actions_intent_PERMISSION` event
* app.intent('Get Permission', conv => {
* const granted = conv.arguments.get('PERMISSION') // boolean true if granted, false if not
* })
* ```
*
* @param argument Name of the argument.
* @return First property not named 'name' or 'status' with 'textValue' given last priority
* or undefined if no other properties.
*
* @public
*/
get<TName extends keyof ArgumentsNamed>(name: TName): ArgumentsNamed[TName];
/** @public */
| {
continue;
} | conditional_block |
argument.ts | 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, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as Api from '../../api/v2';
import {
NewSurfaceArgument,
PermissionArgument,
OptionArgument,
ConfirmationArgument,
DateTimeArgument,
SignInArgument,
PlaceArgument,
TransactionDecisionArgument,
TransactionRequirementsArgument,
DeliveryAddressArgument,
RegisterUpdateArgument,
UpdatePermissionUserIdArgument,
CompletePurchaseArgument,
DigitalPurchaseCheckArgument,
} from '..';
import {RepromptArgument, FinalRepromptArgument} from './noinput';
import {MediaStatusArgument} from './media';
// Need to import because of https://github.com/Microsoft/TypeScript/issues/9944
import {ApiClientObjectMap} from '../../../../common';
// Need to use type to avoid unused local linter errors
export {ApiClientObjectMap};
/** @public */
export type Argument =
Api.GoogleActionsV2Argument[keyof Api.GoogleActionsV2Argument];
export interface ArgumentsNamed {
/**
* True if the request follows a previous request asking for
* permission from the user and the user granted the permission(s).
* Otherwise, false.
* Only use after calling {@link Permission|conv.ask(new Permission)}
* or {@link UpdatePermission|conv.ask(new UpdatePermission)}.
* @public
*/
PERMISSION?: PermissionArgument;
/**
* The option key user chose from options response.
* Only use after calling {@link List|conv.ask(new List)}
* or {@link Carousel|conv.ask(new Carousel)}.
* @public
*/
OPTION?: OptionArgument;
/**
* The transactability of user.
* Only use after calling {@link TransactionRequirements|conv.ask(new TransactionRequirements)}.
* Undefined if no result given.
* @public
*/
TRANSACTION_REQUIREMENTS_CHECK_RESULT?: TransactionRequirementsArgument;
/**
* The order delivery address.
* Only use after calling {@link DeliveryAddress|conv.ask(new DeliveryAddress)}.
* @public
*/
DELIVERY_ADDRESS_VALUE?: DeliveryAddressArgument;
/**
* The transaction decision information.
* Is object with userDecision only if user declines.
* userDecision will be one of {@link GoogleActionsV2TransactionDecisionValueUserDecision}.
* Only use after calling {@link TransactionDecision|conv.ask(new TransactionDecision)}.
* @public
*/
TRANSACTION_DECISION_VALUE?: TransactionDecisionArgument;
/**
* The complete purchase information.
* Only use after calling {@link CompletePurchase|conv.ask(new CompletePurchase)}.
* @public
*/
COMPLETE_PURCHASE_VALUE?: CompletePurchaseArgument;
/**
* Only use after calling {@link DigitalPurchaseCheck|conv.ask(new DigitalPurchaseCheck)}.
* @public
*/
DIGITAL_PURCHASE_CHECK_RESULT?: DigitalPurchaseCheckArgument;
/**
* The confirmation decision.
* Use after {@link Confirmation|conv.ask(new Confirmation)}
* @public
*/
CONFIRMATION?: ConfirmationArgument;
/**
* The user provided date and time.
* Use after {@link DateTime|conv.ask(new DateTime)}
* @public
*/
DATETIME?: DateTimeArgument;
/**
* The status of user sign in request.
* Use after {@link SignIn|conv.ask(new SignIn)}
* @public
*/
SIGN_IN?: SignInArgument;
/**
* The number of subsequent reprompts related to silent input from the user.
* This should be used along with the `actions.intent.NO_INPUT` intent to reprompt the
* user for input in cases where the Google Assistant could not pick up any speech.
* @public
*/
REPROMPT_COUNT?: RepromptArgument;
/**
* True if it is the final reprompt related to silent input from the user.
* This should be used along with the `actions.intent.NO_INPUT` intent to give the final
* response to the user after multiple silences and should be an `conv.close`
* which ends the conversation.
* @public
*/
IS_FINAL_REPROMPT?: FinalRepromptArgument;
/**
* The result of {@link NewSurface|conv.ask(new NewSurface)}
* True if user has triggered conversation on a new device following the
* `actions.intent.NEW_SURFACE` intent.
* @public
*/
NEW_SURFACE?: NewSurfaceArgument;
/**
* True if user accepted update registration request.
* Used with {@link RegisterUpdate|conv.ask(new RegisterUpdate)}
* @public
*/
REGISTER_UPDATE?: RegisterUpdateArgument;
/**
* The updates user id.
* Only use after calling {@link UpdatePermission|conv.ask(new UpdatePermission)}.
* @public
*/
UPDATES_USER_ID?: UpdatePermissionUserIdArgument;
/**
* The user provided place.
* Use after {@link Place|conv.ask(new Place)}.
* @public
*/
PLACE?: PlaceArgument;
/**
* The status of MEDIA_STATUS intent.
* @public
*/
MEDIA_STATUS?: MediaStatusArgument;
}
export interface ArgumentsParsed extends ArgumentsNamed {
/** @public */
[name: string]: Argument | undefined;
}
/** @hidden */
export interface ArgumentsIndexable {
[key: string]: Argument;
}
export interface ArgumentsStatus {
/** @public */
[name: string]: Api.GoogleRpcStatus | undefined;
}
export interface ArgumentsRaw {
/** @public */
[name: string]: Api.GoogleActionsV2Argument;
}
const getValue = (arg: Api.GoogleActionsV2Argument): Argument => {
for (const key in arg) {
if (key === 'name' || key === 'textValue' || key === 'status') {
continue;
}
return (arg as ArgumentsIndexable)[key];
}
// Manually handle the PERMISSION argument because of a bug not returning boolValue
if (arg.name === 'PERMISSION') {
return !!arg.boolValue;
}
return arg.textValue;
};
export class Parsed {
/** @public */
list: Argument[];
/** @public */
input: ArgumentsParsed = {};
/** @hidden */
constructor(raw: Api.GoogleActionsV2Argument[]) {
this.list = raw.map((arg, i) => {
const value = getValue(arg);
const name = arg.name!;
this.input[name] = value;
return value;
});
}
/** @public */
get<TName extends keyof ArgumentsNamed>(name: TName): ArgumentsNamed[TName];
/** @public */
get(name: string): Argument;
get(name: string) {
return this.input[name];
}
}
export class Status {
/** @public */
list: (Api.GoogleRpcStatus | undefined)[];
/** @public */
input: ArgumentsStatus = {};
/** @hidden */
constructor(raw: Api.GoogleActionsV2Argument[]) |
/** @public */
get(name: string) {
return this.input[name];
}
}
export class Raw {
/** @public */
input: ArgumentsRaw;
/** @hidden */
constructor(public list: Api.GoogleActionsV2Argument[]) {
this.input = list.reduce((o, arg) => {
o[arg.name!] = arg;
return o;
}, {} as ArgumentsRaw);
}
/** @public */
get(name: string) {
return this.input[name];
}
}
export class Arguments {
/** @public */
parsed: Parsed;
/** @public */
status: Status;
/** @public */
raw: Raw;
/** @hidden */
constructor(raw: Api.GoogleActionsV2Argument[] = []) {
this.parsed = new Parsed(raw);
this.status = new Status(raw);
this.raw = new Raw(raw);
}
/**
* Get the argument value by name from the current intent.
* The first property value not named `name` or `status` will be returned.
* Will retrieve `textValue` last.
* If there is no other properties, return undefined.
*
* @example
* ```javascript
*
* // Actions SDK
* app.intent('actions.intent.PERMISSION', conv => {
* const granted = conv.arguments.get('PERMISSION') // boolean true if granted, false if not
* })
*
* // Dialogflow
* // Create a Dialogflow intent with the `actions_intent_PERMISSION` event
* app.intent('Get Permission', conv => {
* const granted = conv.arguments.get('PERMISSION') // boolean true if granted, false if not
* })
* ```
*
* @param argument Name of the argument.
* @return First property not named 'name' or 'status' with 'textValue' given last priority
* or undefined if no other properties.
*
* @public
*/
get<TName extends keyof ArgumentsNamed>(name: TName): ArgumentsNamed[TName];
/** @public */
| {
this.list = raw.map((arg, i) => {
const name = arg.name!;
const status = arg.status;
this.input[name] = status;
return status;
});
} | identifier_body |
argument.ts | * 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, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as Api from '../../api/v2';
import {
NewSurfaceArgument,
PermissionArgument,
OptionArgument,
ConfirmationArgument,
DateTimeArgument,
SignInArgument,
PlaceArgument,
TransactionDecisionArgument,
TransactionRequirementsArgument,
DeliveryAddressArgument,
RegisterUpdateArgument,
UpdatePermissionUserIdArgument,
CompletePurchaseArgument,
DigitalPurchaseCheckArgument,
} from '..';
import {RepromptArgument, FinalRepromptArgument} from './noinput';
import {MediaStatusArgument} from './media';
// Need to import because of https://github.com/Microsoft/TypeScript/issues/9944
import {ApiClientObjectMap} from '../../../../common';
// Need to use type to avoid unused local linter errors
export {ApiClientObjectMap};
/** @public */
export type Argument =
Api.GoogleActionsV2Argument[keyof Api.GoogleActionsV2Argument];
export interface ArgumentsNamed {
/**
* True if the request follows a previous request asking for
* permission from the user and the user granted the permission(s).
* Otherwise, false.
* Only use after calling {@link Permission|conv.ask(new Permission)}
* or {@link UpdatePermission|conv.ask(new UpdatePermission)}.
* @public
*/
PERMISSION?: PermissionArgument;
/**
* The option key user chose from options response.
* Only use after calling {@link List|conv.ask(new List)}
* or {@link Carousel|conv.ask(new Carousel)}.
* @public
*/
OPTION?: OptionArgument;
/**
* The transactability of user.
* Only use after calling {@link TransactionRequirements|conv.ask(new TransactionRequirements)}.
* Undefined if no result given.
* @public
*/
TRANSACTION_REQUIREMENTS_CHECK_RESULT?: TransactionRequirementsArgument;
/**
* The order delivery address.
* Only use after calling {@link DeliveryAddress|conv.ask(new DeliveryAddress)}.
* @public
*/
DELIVERY_ADDRESS_VALUE?: DeliveryAddressArgument;
/**
* The transaction decision information.
* Is object with userDecision only if user declines.
* userDecision will be one of {@link GoogleActionsV2TransactionDecisionValueUserDecision}.
* Only use after calling {@link TransactionDecision|conv.ask(new TransactionDecision)}.
* @public
*/
TRANSACTION_DECISION_VALUE?: TransactionDecisionArgument;
/**
* The complete purchase information.
* Only use after calling {@link CompletePurchase|conv.ask(new CompletePurchase)}.
* @public
*/
COMPLETE_PURCHASE_VALUE?: CompletePurchaseArgument;
/**
* Only use after calling {@link DigitalPurchaseCheck|conv.ask(new DigitalPurchaseCheck)}.
* @public
*/
DIGITAL_PURCHASE_CHECK_RESULT?: DigitalPurchaseCheckArgument;
/**
* The confirmation decision.
* Use after {@link Confirmation|conv.ask(new Confirmation)}
* @public
*/
CONFIRMATION?: ConfirmationArgument;
/**
* The user provided date and time.
* Use after {@link DateTime|conv.ask(new DateTime)}
* @public
*/
DATETIME?: DateTimeArgument;
/**
* The status of user sign in request.
* Use after {@link SignIn|conv.ask(new SignIn)}
* @public
*/
SIGN_IN?: SignInArgument;
/**
* The number of subsequent reprompts related to silent input from the user.
* This should be used along with the `actions.intent.NO_INPUT` intent to reprompt the
* user for input in cases where the Google Assistant could not pick up any speech.
* @public
*/
REPROMPT_COUNT?: RepromptArgument;
/**
* True if it is the final reprompt related to silent input from the user.
* This should be used along with the `actions.intent.NO_INPUT` intent to give the final
* response to the user after multiple silences and should be an `conv.close`
* which ends the conversation.
* @public
*/
IS_FINAL_REPROMPT?: FinalRepromptArgument;
/**
* The result of {@link NewSurface|conv.ask(new NewSurface)}
* True if user has triggered conversation on a new device following the
* `actions.intent.NEW_SURFACE` intent.
* @public
*/
NEW_SURFACE?: NewSurfaceArgument;
/**
* True if user accepted update registration request.
* Used with {@link RegisterUpdate|conv.ask(new RegisterUpdate)}
* @public
*/
REGISTER_UPDATE?: RegisterUpdateArgument;
/**
* The updates user id.
* Only use after calling {@link UpdatePermission|conv.ask(new UpdatePermission)}.
* @public
*/
UPDATES_USER_ID?: UpdatePermissionUserIdArgument;
/**
* The user provided place.
* Use after {@link Place|conv.ask(new Place)}.
* @public
*/
PLACE?: PlaceArgument;
/**
* The status of MEDIA_STATUS intent.
* @public
*/
MEDIA_STATUS?: MediaStatusArgument;
}
export interface ArgumentsParsed extends ArgumentsNamed {
/** @public */
[name: string]: Argument | undefined;
}
/** @hidden */
export interface ArgumentsIndexable {
[key: string]: Argument;
}
export interface ArgumentsStatus {
/** @public */
[name: string]: Api.GoogleRpcStatus | undefined;
}
export interface ArgumentsRaw {
/** @public */
[name: string]: Api.GoogleActionsV2Argument;
}
const getValue = (arg: Api.GoogleActionsV2Argument): Argument => {
for (const key in arg) {
if (key === 'name' || key === 'textValue' || key === 'status') {
continue;
}
return (arg as ArgumentsIndexable)[key];
}
// Manually handle the PERMISSION argument because of a bug not returning boolValue
if (arg.name === 'PERMISSION') {
return !!arg.boolValue;
}
return arg.textValue;
};
export class Parsed {
/** @public */
list: Argument[];
/** @public */
input: ArgumentsParsed = {};
/** @hidden */
constructor(raw: Api.GoogleActionsV2Argument[]) {
this.list = raw.map((arg, i) => {
const value = getValue(arg);
const name = arg.name!;
this.input[name] = value;
return value;
});
}
/** @public */
get<TName extends keyof ArgumentsNamed>(name: TName): ArgumentsNamed[TName];
/** @public */
get(name: string): Argument;
get(name: string) {
return this.input[name];
}
}
export class Status {
/** @public */
list: (Api.GoogleRpcStatus | undefined)[];
/** @public */
input: ArgumentsStatus = {};
/** @hidden */
constructor(raw: Api.GoogleActionsV2Argument[]) {
this.list = raw.map((arg, i) => {
const name = arg.name!;
const status = arg.status;
this.input[name] = status;
return status;
});
}
/** @public */
get(name: string) {
return this.input[name];
}
}
export class Raw {
/** @public */
input: ArgumentsRaw;
/** @hidden */
constructor(public list: Api.GoogleActionsV2Argument[]) {
this.input = list.reduce((o, arg) => {
o[arg.name!] = arg;
return o;
}, {} as ArgumentsRaw);
}
/** @public */
get(name: string) {
return this.input[name];
}
}
export class Arguments {
/** @public */
parsed: Parsed;
/** @public */
status: Status;
/** @public */
raw: Raw;
/** @hidden */
constructor(raw: Api.GoogleActionsV2Argument[] = []) {
this.parsed = new Parsed(raw);
this.status = new Status(raw);
this.raw = new Raw(raw);
}
/**
* Get the argument value by name from the current intent.
* The first property value not named `name` or `status` will be returned.
* Will retrieve `textValue` last.
* If there is no other properties, return undefined.
*
* @example
* ```javascript
*
* // Actions SDK
* app.intent('actions.intent.PERMISSION', conv => {
* const granted = conv.arguments.get('PERMISSION') // boolean true if granted, false if not
* })
*
* // Dialogflow
* // Create a Dialogflow intent with the `actions_intent_PERMISSION` event
* app.intent('Get Permission', conv => {
* const granted = conv.arguments.get('PERMISSION') // boolean true if granted, false if not
* })
* ```
*
* @param argument Name of the argument.
* @return First property not named 'name' or 'status' with 'textValue' given last priority
* or undefined if no other properties.
*
* @public
*/
get<TName extends keyof Arguments | random_line_split |
||
argument.ts | 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, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as Api from '../../api/v2';
import {
NewSurfaceArgument,
PermissionArgument,
OptionArgument,
ConfirmationArgument,
DateTimeArgument,
SignInArgument,
PlaceArgument,
TransactionDecisionArgument,
TransactionRequirementsArgument,
DeliveryAddressArgument,
RegisterUpdateArgument,
UpdatePermissionUserIdArgument,
CompletePurchaseArgument,
DigitalPurchaseCheckArgument,
} from '..';
import {RepromptArgument, FinalRepromptArgument} from './noinput';
import {MediaStatusArgument} from './media';
// Need to import because of https://github.com/Microsoft/TypeScript/issues/9944
import {ApiClientObjectMap} from '../../../../common';
// Need to use type to avoid unused local linter errors
export {ApiClientObjectMap};
/** @public */
export type Argument =
Api.GoogleActionsV2Argument[keyof Api.GoogleActionsV2Argument];
export interface ArgumentsNamed {
/**
* True if the request follows a previous request asking for
* permission from the user and the user granted the permission(s).
* Otherwise, false.
* Only use after calling {@link Permission|conv.ask(new Permission)}
* or {@link UpdatePermission|conv.ask(new UpdatePermission)}.
* @public
*/
PERMISSION?: PermissionArgument;
/**
* The option key user chose from options response.
* Only use after calling {@link List|conv.ask(new List)}
* or {@link Carousel|conv.ask(new Carousel)}.
* @public
*/
OPTION?: OptionArgument;
/**
* The transactability of user.
* Only use after calling {@link TransactionRequirements|conv.ask(new TransactionRequirements)}.
* Undefined if no result given.
* @public
*/
TRANSACTION_REQUIREMENTS_CHECK_RESULT?: TransactionRequirementsArgument;
/**
* The order delivery address.
* Only use after calling {@link DeliveryAddress|conv.ask(new DeliveryAddress)}.
* @public
*/
DELIVERY_ADDRESS_VALUE?: DeliveryAddressArgument;
/**
* The transaction decision information.
* Is object with userDecision only if user declines.
* userDecision will be one of {@link GoogleActionsV2TransactionDecisionValueUserDecision}.
* Only use after calling {@link TransactionDecision|conv.ask(new TransactionDecision)}.
* @public
*/
TRANSACTION_DECISION_VALUE?: TransactionDecisionArgument;
/**
* The complete purchase information.
* Only use after calling {@link CompletePurchase|conv.ask(new CompletePurchase)}.
* @public
*/
COMPLETE_PURCHASE_VALUE?: CompletePurchaseArgument;
/**
* Only use after calling {@link DigitalPurchaseCheck|conv.ask(new DigitalPurchaseCheck)}.
* @public
*/
DIGITAL_PURCHASE_CHECK_RESULT?: DigitalPurchaseCheckArgument;
/**
* The confirmation decision.
* Use after {@link Confirmation|conv.ask(new Confirmation)}
* @public
*/
CONFIRMATION?: ConfirmationArgument;
/**
* The user provided date and time.
* Use after {@link DateTime|conv.ask(new DateTime)}
* @public
*/
DATETIME?: DateTimeArgument;
/**
* The status of user sign in request.
* Use after {@link SignIn|conv.ask(new SignIn)}
* @public
*/
SIGN_IN?: SignInArgument;
/**
* The number of subsequent reprompts related to silent input from the user.
* This should be used along with the `actions.intent.NO_INPUT` intent to reprompt the
* user for input in cases where the Google Assistant could not pick up any speech.
* @public
*/
REPROMPT_COUNT?: RepromptArgument;
/**
* True if it is the final reprompt related to silent input from the user.
* This should be used along with the `actions.intent.NO_INPUT` intent to give the final
* response to the user after multiple silences and should be an `conv.close`
* which ends the conversation.
* @public
*/
IS_FINAL_REPROMPT?: FinalRepromptArgument;
/**
* The result of {@link NewSurface|conv.ask(new NewSurface)}
* True if user has triggered conversation on a new device following the
* `actions.intent.NEW_SURFACE` intent.
* @public
*/
NEW_SURFACE?: NewSurfaceArgument;
/**
* True if user accepted update registration request.
* Used with {@link RegisterUpdate|conv.ask(new RegisterUpdate)}
* @public
*/
REGISTER_UPDATE?: RegisterUpdateArgument;
/**
* The updates user id.
* Only use after calling {@link UpdatePermission|conv.ask(new UpdatePermission)}.
* @public
*/
UPDATES_USER_ID?: UpdatePermissionUserIdArgument;
/**
* The user provided place.
* Use after {@link Place|conv.ask(new Place)}.
* @public
*/
PLACE?: PlaceArgument;
/**
* The status of MEDIA_STATUS intent.
* @public
*/
MEDIA_STATUS?: MediaStatusArgument;
}
export interface ArgumentsParsed extends ArgumentsNamed {
/** @public */
[name: string]: Argument | undefined;
}
/** @hidden */
export interface ArgumentsIndexable {
[key: string]: Argument;
}
export interface ArgumentsStatus {
/** @public */
[name: string]: Api.GoogleRpcStatus | undefined;
}
export interface ArgumentsRaw {
/** @public */
[name: string]: Api.GoogleActionsV2Argument;
}
const getValue = (arg: Api.GoogleActionsV2Argument): Argument => {
for (const key in arg) {
if (key === 'name' || key === 'textValue' || key === 'status') {
continue;
}
return (arg as ArgumentsIndexable)[key];
}
// Manually handle the PERMISSION argument because of a bug not returning boolValue
if (arg.name === 'PERMISSION') {
return !!arg.boolValue;
}
return arg.textValue;
};
export class Parsed {
/** @public */
list: Argument[];
/** @public */
input: ArgumentsParsed = {};
/** @hidden */
constructor(raw: Api.GoogleActionsV2Argument[]) {
this.list = raw.map((arg, i) => {
const value = getValue(arg);
const name = arg.name!;
this.input[name] = value;
return value;
});
}
/** @public */
get<TName extends keyof ArgumentsNamed>(name: TName): ArgumentsNamed[TName];
/** @public */
get(name: string): Argument;
get(name: string) {
return this.input[name];
}
}
export class Status {
/** @public */
list: (Api.GoogleRpcStatus | undefined)[];
/** @public */
input: ArgumentsStatus = {};
/** @hidden */
constructor(raw: Api.GoogleActionsV2Argument[]) {
this.list = raw.map((arg, i) => {
const name = arg.name!;
const status = arg.status;
this.input[name] = status;
return status;
});
}
/** @public */
| (name: string) {
return this.input[name];
}
}
export class Raw {
/** @public */
input: ArgumentsRaw;
/** @hidden */
constructor(public list: Api.GoogleActionsV2Argument[]) {
this.input = list.reduce((o, arg) => {
o[arg.name!] = arg;
return o;
}, {} as ArgumentsRaw);
}
/** @public */
get(name: string) {
return this.input[name];
}
}
export class Arguments {
/** @public */
parsed: Parsed;
/** @public */
status: Status;
/** @public */
raw: Raw;
/** @hidden */
constructor(raw: Api.GoogleActionsV2Argument[] = []) {
this.parsed = new Parsed(raw);
this.status = new Status(raw);
this.raw = new Raw(raw);
}
/**
* Get the argument value by name from the current intent.
* The first property value not named `name` or `status` will be returned.
* Will retrieve `textValue` last.
* If there is no other properties, return undefined.
*
* @example
* ```javascript
*
* // Actions SDK
* app.intent('actions.intent.PERMISSION', conv => {
* const granted = conv.arguments.get('PERMISSION') // boolean true if granted, false if not
* })
*
* // Dialogflow
* // Create a Dialogflow intent with the `actions_intent_PERMISSION` event
* app.intent('Get Permission', conv => {
* const granted = conv.arguments.get('PERMISSION') // boolean true if granted, false if not
* })
* ```
*
* @param argument Name of the argument.
* @return First property not named 'name' or 'status' with 'textValue' given last priority
* or undefined if no other properties.
*
* @public
*/
get<TName extends keyof ArgumentsNamed>(name: TName): ArgumentsNamed[TName];
/** @public */
get(name | get | identifier_name |
app_store.py | #!/usr/bin/env python
#
# Copyright 2013 Tim O'Shea
#
# This file is part of PyBOMBS
#
# PyBOMBS 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, or (at your option)
# any later version.
#
# PyBOMBS 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyBOMBS; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from PyQt4.QtCore import Qt;
from PyQt4 import QtCore
import PyQt4.QtGui as QtGui
import sys
import os.path
from mod_pybombs import *;
recipe_loader.load_all();
class AppList(QtGui.QWidget):
def __init__(self, parent, name):
super(AppList, self).__init__()
self.parent = parent;
self.lay = QtGui.QGridLayout();
self.setLayout(self.lay);
self.width = 8;
self.idx = 0;
self.cbd = {};
def cb(self):
self._cb();
def addButton(self, name, callback): | defaultimg = "img/unknown.png";
pixmap = QtGui.QPixmap(defaultimg);
icon = QtGui.QIcon(pixmap);
button = QtGui.QToolButton();
action = QtGui.QAction( icon, str(name), self );
action.setStatusTip('Install App')
button.setDefaultAction(action);
button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon);
button.setIconSize(QtCore.QSize(100,100));
button.setAutoRaise(True);
self.connect(action, QtCore.SIGNAL("triggered()"), callback);
self.lay.addWidget(button, self.idx/self.width, self.idx%self.width);
self.idx = self.idx + 1;
class Installer:
def __init__(self, parent, name):
self.parent = parent;
self.name = name;
def cb(self):
print "installing "+ self.name;
install(self.name);
self.parent.refresh();
class Remover:
def __init__(self, parent, name):
self.parent = parent;
self.name = name;
def cb(self):
print "removing "+ self.name;
remove(self.name);
self.parent.refresh();
class ASMain(QtGui.QWidget):
#class ASMain(QtGui.QMainWindow):
def __init__(self):
super(ASMain, self).__init__()
self.setWindowTitle("Python Build Overlay Managed Bundle System - APP STORE GUI");
self.layout = QtGui.QVBoxLayout(self);
self.setLayout(self.layout);
self.menu = QtGui.QMenuBar(self);
pixmap = QtGui.QPixmap("img/logo.png")
lbl = QtGui.QLabel(self)
lbl.setPixmap(pixmap)
l2 = QtGui.QHBoxLayout();
l2.addWidget(QtGui.QLabel(" "));
l2.addWidget(lbl);
l2.addWidget(QtGui.QLabel(" "));
self.tw = QtGui.QTabWidget(self);
self.layout.setMargin(0);
self.layout.addWidget(self.menu);
self.layout.addLayout(l2);
self.layout.addWidget(self.tw);
# Populate Apps
self.populate_tabs();
# Populate the menu
exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)
exitAction.triggered.connect(QtGui.qApp.quit)
fileMenu = self.menu.addMenu('&File');
fileMenu.addAction(exitAction);
reloadAction = QtGui.QAction('&Refresh State', self)
reloadAction.triggered.connect(self.reload_op)
toolsMenu = self.menu.addMenu('&Tools');
toolsMenu.addAction(reloadAction);
self.show();
def reload_op(self):
inv.loadc();
recipe_loader.load_all();
self.refresh();
def refresh(self):
self.populate_tabs();
def populate_tabs(self):
self.tw.clear();
#categories = ["baseline", "common"]
categories = ["common"]
cbs = {};
pages = [];
for c in categories:
pages.append( "Available %s Apps"%(c) );
pages.append( "Installed %s Apps"%(c) );
#pages = ["Available Apps", "Installed Apps"];
tabw = [];
for p in pages:
pp = AppList(self, p);
tabw.append(pp);
self.tw.addTab(pp, p);
catpkg = get_catpkgs()
for c in categories:
cbs[c] = {};
cidx = categories.index(c);
pkgs = catpkg[c];
pkgs.sort();
for p in pkgs:
installed = global_recipes[p].satisfy();
if(installed):
cbs[c][p] = Remover(self, p);
pcidx = 2*cidx+1;
else:
cbs[c][p] = Installer(self, p);
pcidx = 2*cidx;
tabw[pcidx].addButton(p, cbs[c][p].cb);
self.cbs = cbs;
app = QtGui.QApplication(sys.argv)
mw = ASMain();
sys.exit(app.exec_()); | self._cb = callback;
pkgimg = "img/" + name + ".png";
if os.path.exists(pkgimg):
pixmap = QtGui.QPixmap(pkgimg);
else: | random_line_split |
app_store.py | #!/usr/bin/env python
#
# Copyright 2013 Tim O'Shea
#
# This file is part of PyBOMBS
#
# PyBOMBS 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, or (at your option)
# any later version.
#
# PyBOMBS 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyBOMBS; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from PyQt4.QtCore import Qt;
from PyQt4 import QtCore
import PyQt4.QtGui as QtGui
import sys
import os.path
from mod_pybombs import *;
recipe_loader.load_all();
class AppList(QtGui.QWidget):
def __init__(self, parent, name):
super(AppList, self).__init__()
self.parent = parent;
self.lay = QtGui.QGridLayout();
self.setLayout(self.lay);
self.width = 8;
self.idx = 0;
self.cbd = {};
def cb(self):
self._cb();
def addButton(self, name, callback):
self._cb = callback;
pkgimg = "img/" + name + ".png";
if os.path.exists(pkgimg):
pixmap = QtGui.QPixmap(pkgimg);
else:
defaultimg = "img/unknown.png";
pixmap = QtGui.QPixmap(defaultimg);
icon = QtGui.QIcon(pixmap);
button = QtGui.QToolButton();
action = QtGui.QAction( icon, str(name), self );
action.setStatusTip('Install App')
button.setDefaultAction(action);
button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon);
button.setIconSize(QtCore.QSize(100,100));
button.setAutoRaise(True);
self.connect(action, QtCore.SIGNAL("triggered()"), callback);
self.lay.addWidget(button, self.idx/self.width, self.idx%self.width);
self.idx = self.idx + 1;
class Installer:
|
class Remover:
def __init__(self, parent, name):
self.parent = parent;
self.name = name;
def cb(self):
print "removing "+ self.name;
remove(self.name);
self.parent.refresh();
class ASMain(QtGui.QWidget):
#class ASMain(QtGui.QMainWindow):
def __init__(self):
super(ASMain, self).__init__()
self.setWindowTitle("Python Build Overlay Managed Bundle System - APP STORE GUI");
self.layout = QtGui.QVBoxLayout(self);
self.setLayout(self.layout);
self.menu = QtGui.QMenuBar(self);
pixmap = QtGui.QPixmap("img/logo.png")
lbl = QtGui.QLabel(self)
lbl.setPixmap(pixmap)
l2 = QtGui.QHBoxLayout();
l2.addWidget(QtGui.QLabel(" "));
l2.addWidget(lbl);
l2.addWidget(QtGui.QLabel(" "));
self.tw = QtGui.QTabWidget(self);
self.layout.setMargin(0);
self.layout.addWidget(self.menu);
self.layout.addLayout(l2);
self.layout.addWidget(self.tw);
# Populate Apps
self.populate_tabs();
# Populate the menu
exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)
exitAction.triggered.connect(QtGui.qApp.quit)
fileMenu = self.menu.addMenu('&File');
fileMenu.addAction(exitAction);
reloadAction = QtGui.QAction('&Refresh State', self)
reloadAction.triggered.connect(self.reload_op)
toolsMenu = self.menu.addMenu('&Tools');
toolsMenu.addAction(reloadAction);
self.show();
def reload_op(self):
inv.loadc();
recipe_loader.load_all();
self.refresh();
def refresh(self):
self.populate_tabs();
def populate_tabs(self):
self.tw.clear();
#categories = ["baseline", "common"]
categories = ["common"]
cbs = {};
pages = [];
for c in categories:
pages.append( "Available %s Apps"%(c) );
pages.append( "Installed %s Apps"%(c) );
#pages = ["Available Apps", "Installed Apps"];
tabw = [];
for p in pages:
pp = AppList(self, p);
tabw.append(pp);
self.tw.addTab(pp, p);
catpkg = get_catpkgs()
for c in categories:
cbs[c] = {};
cidx = categories.index(c);
pkgs = catpkg[c];
pkgs.sort();
for p in pkgs:
installed = global_recipes[p].satisfy();
if(installed):
cbs[c][p] = Remover(self, p);
pcidx = 2*cidx+1;
else:
cbs[c][p] = Installer(self, p);
pcidx = 2*cidx;
tabw[pcidx].addButton(p, cbs[c][p].cb);
self.cbs = cbs;
app = QtGui.QApplication(sys.argv)
mw = ASMain();
sys.exit(app.exec_());
| def __init__(self, parent, name):
self.parent = parent;
self.name = name;
def cb(self):
print "installing "+ self.name;
install(self.name);
self.parent.refresh(); | identifier_body |
app_store.py | #!/usr/bin/env python
#
# Copyright 2013 Tim O'Shea
#
# This file is part of PyBOMBS
#
# PyBOMBS 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, or (at your option)
# any later version.
#
# PyBOMBS 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyBOMBS; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from PyQt4.QtCore import Qt;
from PyQt4 import QtCore
import PyQt4.QtGui as QtGui
import sys
import os.path
from mod_pybombs import *;
recipe_loader.load_all();
class | (QtGui.QWidget):
def __init__(self, parent, name):
super(AppList, self).__init__()
self.parent = parent;
self.lay = QtGui.QGridLayout();
self.setLayout(self.lay);
self.width = 8;
self.idx = 0;
self.cbd = {};
def cb(self):
self._cb();
def addButton(self, name, callback):
self._cb = callback;
pkgimg = "img/" + name + ".png";
if os.path.exists(pkgimg):
pixmap = QtGui.QPixmap(pkgimg);
else:
defaultimg = "img/unknown.png";
pixmap = QtGui.QPixmap(defaultimg);
icon = QtGui.QIcon(pixmap);
button = QtGui.QToolButton();
action = QtGui.QAction( icon, str(name), self );
action.setStatusTip('Install App')
button.setDefaultAction(action);
button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon);
button.setIconSize(QtCore.QSize(100,100));
button.setAutoRaise(True);
self.connect(action, QtCore.SIGNAL("triggered()"), callback);
self.lay.addWidget(button, self.idx/self.width, self.idx%self.width);
self.idx = self.idx + 1;
class Installer:
def __init__(self, parent, name):
self.parent = parent;
self.name = name;
def cb(self):
print "installing "+ self.name;
install(self.name);
self.parent.refresh();
class Remover:
def __init__(self, parent, name):
self.parent = parent;
self.name = name;
def cb(self):
print "removing "+ self.name;
remove(self.name);
self.parent.refresh();
class ASMain(QtGui.QWidget):
#class ASMain(QtGui.QMainWindow):
def __init__(self):
super(ASMain, self).__init__()
self.setWindowTitle("Python Build Overlay Managed Bundle System - APP STORE GUI");
self.layout = QtGui.QVBoxLayout(self);
self.setLayout(self.layout);
self.menu = QtGui.QMenuBar(self);
pixmap = QtGui.QPixmap("img/logo.png")
lbl = QtGui.QLabel(self)
lbl.setPixmap(pixmap)
l2 = QtGui.QHBoxLayout();
l2.addWidget(QtGui.QLabel(" "));
l2.addWidget(lbl);
l2.addWidget(QtGui.QLabel(" "));
self.tw = QtGui.QTabWidget(self);
self.layout.setMargin(0);
self.layout.addWidget(self.menu);
self.layout.addLayout(l2);
self.layout.addWidget(self.tw);
# Populate Apps
self.populate_tabs();
# Populate the menu
exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)
exitAction.triggered.connect(QtGui.qApp.quit)
fileMenu = self.menu.addMenu('&File');
fileMenu.addAction(exitAction);
reloadAction = QtGui.QAction('&Refresh State', self)
reloadAction.triggered.connect(self.reload_op)
toolsMenu = self.menu.addMenu('&Tools');
toolsMenu.addAction(reloadAction);
self.show();
def reload_op(self):
inv.loadc();
recipe_loader.load_all();
self.refresh();
def refresh(self):
self.populate_tabs();
def populate_tabs(self):
self.tw.clear();
#categories = ["baseline", "common"]
categories = ["common"]
cbs = {};
pages = [];
for c in categories:
pages.append( "Available %s Apps"%(c) );
pages.append( "Installed %s Apps"%(c) );
#pages = ["Available Apps", "Installed Apps"];
tabw = [];
for p in pages:
pp = AppList(self, p);
tabw.append(pp);
self.tw.addTab(pp, p);
catpkg = get_catpkgs()
for c in categories:
cbs[c] = {};
cidx = categories.index(c);
pkgs = catpkg[c];
pkgs.sort();
for p in pkgs:
installed = global_recipes[p].satisfy();
if(installed):
cbs[c][p] = Remover(self, p);
pcidx = 2*cidx+1;
else:
cbs[c][p] = Installer(self, p);
pcidx = 2*cidx;
tabw[pcidx].addButton(p, cbs[c][p].cb);
self.cbs = cbs;
app = QtGui.QApplication(sys.argv)
mw = ASMain();
sys.exit(app.exec_());
| AppList | identifier_name |
app_store.py | #!/usr/bin/env python
#
# Copyright 2013 Tim O'Shea
#
# This file is part of PyBOMBS
#
# PyBOMBS 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, or (at your option)
# any later version.
#
# PyBOMBS 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyBOMBS; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from PyQt4.QtCore import Qt;
from PyQt4 import QtCore
import PyQt4.QtGui as QtGui
import sys
import os.path
from mod_pybombs import *;
recipe_loader.load_all();
class AppList(QtGui.QWidget):
def __init__(self, parent, name):
super(AppList, self).__init__()
self.parent = parent;
self.lay = QtGui.QGridLayout();
self.setLayout(self.lay);
self.width = 8;
self.idx = 0;
self.cbd = {};
def cb(self):
self._cb();
def addButton(self, name, callback):
self._cb = callback;
pkgimg = "img/" + name + ".png";
if os.path.exists(pkgimg):
pixmap = QtGui.QPixmap(pkgimg);
else:
defaultimg = "img/unknown.png";
pixmap = QtGui.QPixmap(defaultimg);
icon = QtGui.QIcon(pixmap);
button = QtGui.QToolButton();
action = QtGui.QAction( icon, str(name), self );
action.setStatusTip('Install App')
button.setDefaultAction(action);
button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon);
button.setIconSize(QtCore.QSize(100,100));
button.setAutoRaise(True);
self.connect(action, QtCore.SIGNAL("triggered()"), callback);
self.lay.addWidget(button, self.idx/self.width, self.idx%self.width);
self.idx = self.idx + 1;
class Installer:
def __init__(self, parent, name):
self.parent = parent;
self.name = name;
def cb(self):
print "installing "+ self.name;
install(self.name);
self.parent.refresh();
class Remover:
def __init__(self, parent, name):
self.parent = parent;
self.name = name;
def cb(self):
print "removing "+ self.name;
remove(self.name);
self.parent.refresh();
class ASMain(QtGui.QWidget):
#class ASMain(QtGui.QMainWindow):
def __init__(self):
super(ASMain, self).__init__()
self.setWindowTitle("Python Build Overlay Managed Bundle System - APP STORE GUI");
self.layout = QtGui.QVBoxLayout(self);
self.setLayout(self.layout);
self.menu = QtGui.QMenuBar(self);
pixmap = QtGui.QPixmap("img/logo.png")
lbl = QtGui.QLabel(self)
lbl.setPixmap(pixmap)
l2 = QtGui.QHBoxLayout();
l2.addWidget(QtGui.QLabel(" "));
l2.addWidget(lbl);
l2.addWidget(QtGui.QLabel(" "));
self.tw = QtGui.QTabWidget(self);
self.layout.setMargin(0);
self.layout.addWidget(self.menu);
self.layout.addLayout(l2);
self.layout.addWidget(self.tw);
# Populate Apps
self.populate_tabs();
# Populate the menu
exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)
exitAction.triggered.connect(QtGui.qApp.quit)
fileMenu = self.menu.addMenu('&File');
fileMenu.addAction(exitAction);
reloadAction = QtGui.QAction('&Refresh State', self)
reloadAction.triggered.connect(self.reload_op)
toolsMenu = self.menu.addMenu('&Tools');
toolsMenu.addAction(reloadAction);
self.show();
def reload_op(self):
inv.loadc();
recipe_loader.load_all();
self.refresh();
def refresh(self):
self.populate_tabs();
def populate_tabs(self):
self.tw.clear();
#categories = ["baseline", "common"]
categories = ["common"]
cbs = {};
pages = [];
for c in categories:
pages.append( "Available %s Apps"%(c) );
pages.append( "Installed %s Apps"%(c) );
#pages = ["Available Apps", "Installed Apps"];
tabw = [];
for p in pages:
pp = AppList(self, p);
tabw.append(pp);
self.tw.addTab(pp, p);
catpkg = get_catpkgs()
for c in categories:
|
self.cbs = cbs;
app = QtGui.QApplication(sys.argv)
mw = ASMain();
sys.exit(app.exec_());
| cbs[c] = {};
cidx = categories.index(c);
pkgs = catpkg[c];
pkgs.sort();
for p in pkgs:
installed = global_recipes[p].satisfy();
if(installed):
cbs[c][p] = Remover(self, p);
pcidx = 2*cidx+1;
else:
cbs[c][p] = Installer(self, p);
pcidx = 2*cidx;
tabw[pcidx].addButton(p, cbs[c][p].cb); | conditional_block |
attribute-form.js | /**
* Copyright (c) 2008-2009 The Open Source Geospatial Foundation
*
* Published under the BSD license.
* See http://svn.geoext.org/core/trunk/geoext/license.txt for the full text
* of the license.
*/
/** api: example[attribute-form]
* Attribute Form
* --------------
* Create a form with fields from attributes read from a WFS
* DescribeFeatureType response
*/
var form;
Ext.onReady(function() {
Ext.QuickTips.init();
// create attributes store
var attributeStore = new GeoExt.data.AttributeStore({
url: "data/describe_feature_type.xml"
});
form = new Ext.form.FormPanel({
renderTo: document.body,
autoScroll: true,
height: 300,
width: 350,
defaults: {
width: 120,
maxLengthText: "too long",
minLengthText: "too short"
},
plugins: [
new GeoExt.plugins.AttributeForm({
attributeStore: attributeStore,
recordToFieldOptions: {
labelTpl: new Ext.XTemplate(
'{name}{[this.getStar(values)]}', {
compiled: true,
disableFormats: true,
getStar: function(v) {
return v.nillable ? '' : ' *';
}
}
)
}
})
]
}); | attributeStore.load();
}); | random_line_split |
|
InputSearchUi.js | import React from 'react';
// A seach input presentational component.
export default React.createClass({
propTypes: {
search: React.PropTypes.func.isRequired,
placeholder: React.PropTypes.string.isRequired
},
searchClear: function() {
return $("#search-clear");
},
searchInput: function() {
return $("#search-input");
},
search: function() {
const text = this.searchInput().val();
this.searchClear().toggle(Boolean(text));
this.props.search(text);
},
resetSearch: function() {
this.searchInput().val('').focus();
this.searchClear().hide();
this.search();
},
render: function() {
return (
<form className="search-form">
<input id="search-input" type="text"
placeholder={this.props.placeholder} className="form-control"
onChange={this.search}
onKeyPress={
function(event) {
if (event.nativeEvent.keyCode === 13) |
}
}/>
<span id="search-clear" className="glyphicon glyphicon-remove-circle"
onClick={this.resetSearch}></span>
</form>
);
}
});
| {
event.preventDefault();
event.stopPropagation();
} | conditional_block |
InputSearchUi.js | import React from 'react';
// A seach input presentational component.
export default React.createClass({
propTypes: {
search: React.PropTypes.func.isRequired,
placeholder: React.PropTypes.string.isRequired
},
searchClear: function() {
return $("#search-clear");
},
searchInput: function() {
return $("#search-input");
},
search: function() {
const text = this.searchInput().val();
this.searchClear().toggle(Boolean(text));
this.props.search(text);
},
resetSearch: function() {
this.searchInput().val('').focus();
this.searchClear().hide();
this.search();
},
render: function() {
return (
<form className="search-form">
<input id="search-input" type="text"
placeholder={this.props.placeholder} className="form-control"
onChange={this.search}
onKeyPress={
function(event) { | }
}/>
<span id="search-clear" className="glyphicon glyphicon-remove-circle"
onClick={this.resetSearch}></span>
</form>
);
}
}); | if (event.nativeEvent.keyCode === 13) {
event.preventDefault();
event.stopPropagation();
} | random_line_split |
topn_ops.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# 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, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Ops for TopN class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import threading
import tensorflow as tf
from tensorflow.python.framework import common_shapes
from tensorflow.python.framework import ops
TOPN_OPS_FILE = '_topn_ops.so'
_topn_ops = None
_ops_lock = threading.Lock()
ops.NotDifferentiable('TopNInsert')
ops.NotDifferentiable('TopNRemove')
ops.RegisterShape('TopNInsert')(common_shapes.call_cpp_shape_fn)
ops.RegisterShape('TopNRemove')(common_shapes.call_cpp_shape_fn)
# Workaround for the fact that importing tensorflow imports contrib
# (even if a user isn't using this or any other contrib op), but
# there's not yet any guarantee that the shared object exists.
# In which case, "import tensorflow" will always crash, even for users that
# never use contrib.
def Load():
"""Load the TopN ops library and return the loaded module."""
with _ops_lock:
global _topn_ops
if not _topn_ops:
|
return _topn_ops
| ops_path = tf.resource_loader.get_path_to_datafile(TOPN_OPS_FILE)
tf.logging.info('data path: %s', ops_path)
_topn_ops = tf.load_op_library(ops_path)
assert _topn_ops, 'Could not load topn_ops.so' | conditional_block |
topn_ops.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# 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, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Ops for TopN class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import threading
import tensorflow as tf
from tensorflow.python.framework import common_shapes
from tensorflow.python.framework import ops
TOPN_OPS_FILE = '_topn_ops.so'
_topn_ops = None
_ops_lock = threading.Lock()
ops.NotDifferentiable('TopNInsert')
ops.NotDifferentiable('TopNRemove')
ops.RegisterShape('TopNInsert')(common_shapes.call_cpp_shape_fn)
ops.RegisterShape('TopNRemove')(common_shapes.call_cpp_shape_fn)
# Workaround for the fact that importing tensorflow imports contrib
# (even if a user isn't using this or any other contrib op), but
# there's not yet any guarantee that the shared object exists.
# In which case, "import tensorflow" will always crash, even for users that
# never use contrib.
def | ():
"""Load the TopN ops library and return the loaded module."""
with _ops_lock:
global _topn_ops
if not _topn_ops:
ops_path = tf.resource_loader.get_path_to_datafile(TOPN_OPS_FILE)
tf.logging.info('data path: %s', ops_path)
_topn_ops = tf.load_op_library(ops_path)
assert _topn_ops, 'Could not load topn_ops.so'
return _topn_ops
| Load | identifier_name |
topn_ops.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# 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, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Ops for TopN class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import threading
import tensorflow as tf
from tensorflow.python.framework import common_shapes
from tensorflow.python.framework import ops
TOPN_OPS_FILE = '_topn_ops.so'
_topn_ops = None
_ops_lock = threading.Lock()
ops.NotDifferentiable('TopNInsert')
ops.NotDifferentiable('TopNRemove')
ops.RegisterShape('TopNInsert')(common_shapes.call_cpp_shape_fn)
ops.RegisterShape('TopNRemove')(common_shapes.call_cpp_shape_fn)
# Workaround for the fact that importing tensorflow imports contrib
# (even if a user isn't using this or any other contrib op), but
# there's not yet any guarantee that the shared object exists.
# In which case, "import tensorflow" will always crash, even for users that
# never use contrib.
def Load():
| """Load the TopN ops library and return the loaded module."""
with _ops_lock:
global _topn_ops
if not _topn_ops:
ops_path = tf.resource_loader.get_path_to_datafile(TOPN_OPS_FILE)
tf.logging.info('data path: %s', ops_path)
_topn_ops = tf.load_op_library(ops_path)
assert _topn_ops, 'Could not load topn_ops.so'
return _topn_ops | identifier_body |
|
topn_ops.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# 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, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | # ==============================================================================
"""Ops for TopN class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import threading
import tensorflow as tf
from tensorflow.python.framework import common_shapes
from tensorflow.python.framework import ops
TOPN_OPS_FILE = '_topn_ops.so'
_topn_ops = None
_ops_lock = threading.Lock()
ops.NotDifferentiable('TopNInsert')
ops.NotDifferentiable('TopNRemove')
ops.RegisterShape('TopNInsert')(common_shapes.call_cpp_shape_fn)
ops.RegisterShape('TopNRemove')(common_shapes.call_cpp_shape_fn)
# Workaround for the fact that importing tensorflow imports contrib
# (even if a user isn't using this or any other contrib op), but
# there's not yet any guarantee that the shared object exists.
# In which case, "import tensorflow" will always crash, even for users that
# never use contrib.
def Load():
"""Load the TopN ops library and return the loaded module."""
with _ops_lock:
global _topn_ops
if not _topn_ops:
ops_path = tf.resource_loader.get_path_to_datafile(TOPN_OPS_FILE)
tf.logging.info('data path: %s', ops_path)
_topn_ops = tf.load_op_library(ops_path)
assert _topn_ops, 'Could not load topn_ops.so'
return _topn_ops | # See the License for the specific language governing permissions and
# limitations under the License. | random_line_split |
express.ts | 'use strict';
import express = require('express');
import stylus = require('stylus');
import bodyParser = require('body-parser');
import cookieParser = require('cookie-parser');
import session = require('express-session');
import passport = require('passport');
import config = require('config');
| app.set('views', config.rootPath + '/server/views');
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
secret: 'team-hestia',
name: 'session',
proxy: true,
resave: true,
saveUninitialized: true
}));
app.use(stylus.middleware(
{
src: config.rootPath + '/public',
compile: (str, path) => stylus(str).set('filename', path)
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(config.rootPath + '/public'));
}; | export function init(app: express.Express, config: config.IConfig) {
app.set('view engine', 'jade'); | random_line_split |
express.ts | 'use strict';
import express = require('express');
import stylus = require('stylus');
import bodyParser = require('body-parser');
import cookieParser = require('cookie-parser');
import session = require('express-session');
import passport = require('passport');
import config = require('config');
export function init(app: express.Express, config: config.IConfig) | app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(config.rootPath + '/public'));
}
; | {
app.set('view engine', 'jade');
app.set('views', config.rootPath + '/server/views');
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
secret: 'team-hestia',
name: 'session',
proxy: true,
resave: true,
saveUninitialized: true
}));
app.use(stylus.middleware(
{
src: config.rootPath + '/public',
compile: (str, path) => stylus(str).set('filename', path)
})); | identifier_body |
express.ts | 'use strict';
import express = require('express');
import stylus = require('stylus');
import bodyParser = require('body-parser');
import cookieParser = require('cookie-parser');
import session = require('express-session');
import passport = require('passport');
import config = require('config');
export function | (app: express.Express, config: config.IConfig) {
app.set('view engine', 'jade');
app.set('views', config.rootPath + '/server/views');
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
secret: 'team-hestia',
name: 'session',
proxy: true,
resave: true,
saveUninitialized: true
}));
app.use(stylus.middleware(
{
src: config.rootPath + '/public',
compile: (str, path) => stylus(str).set('filename', path)
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(config.rootPath + '/public'));
}; | init | identifier_name |
lifetime-update.rs | #![feature(type_changing_struct_update)]
#![allow(incomplete_features)]
#[derive(Clone)]
struct Machine<'a, S> { | }
#[derive(Clone)]
struct State1;
#[derive(Clone)]
struct State2;
fn update_to_state2() {
let s = String::from("hello");
let m1: Machine<State1> = Machine {
state: State1,
lt_str: &s,
//~^ ERROR `s` does not live long enough [E0597]
// FIXME: The error here actually comes from line 34. The
// span of the error message should be corrected to line 34
common_field: 2,
};
// update lifetime
let m3: Machine<'static, State1> = Machine {
lt_str: "hello, too",
..m1.clone()
};
// update lifetime and type
let m4: Machine<'static, State2> = Machine {
state: State2,
lt_str: "hello, again",
..m1.clone()
};
// updating to `static should fail.
let m2: Machine<'static, State1> = Machine {
..m1
};
}
fn main() {} | state: S,
lt_str: &'a str,
common_field: i32, | random_line_split |
lifetime-update.rs | #![feature(type_changing_struct_update)]
#![allow(incomplete_features)]
#[derive(Clone)]
struct Machine<'a, S> {
state: S,
lt_str: &'a str,
common_field: i32,
}
#[derive(Clone)]
struct | ;
#[derive(Clone)]
struct State2;
fn update_to_state2() {
let s = String::from("hello");
let m1: Machine<State1> = Machine {
state: State1,
lt_str: &s,
//~^ ERROR `s` does not live long enough [E0597]
// FIXME: The error here actually comes from line 34. The
// span of the error message should be corrected to line 34
common_field: 2,
};
// update lifetime
let m3: Machine<'static, State1> = Machine {
lt_str: "hello, too",
..m1.clone()
};
// update lifetime and type
let m4: Machine<'static, State2> = Machine {
state: State2,
lt_str: "hello, again",
..m1.clone()
};
// updating to `static should fail.
let m2: Machine<'static, State1> = Machine {
..m1
};
}
fn main() {}
| State1 | identifier_name |
movie.service.ts | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import {UtilityComponent} from '../../shared/components/utility.component';
import { Movie } from './movie.model';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class MovieService {
// Constructor with injected http
constructor (private http: Http) {}
// Get movie's details by id
getMovieById (id: number): Observable<Movie> {
let moviesUrl = UtilityComponent.getUrl('movie/'+id);
return this.http.get(moviesUrl)
.map(res => res.json())
.catch(this.handleError);
}
// Get movie list by name
getMovies (name: string, page: number): Observable<Movie[]> {
let moviesUrl: string;
// If name is defined
if(name) {
// Get movies by name
moviesUrl = UtilityComponent.getUrl('search/movie','&query='+name+'&page='+page);
}else{
// Get popular movies
moviesUrl = UtilityComponent.getUrl('discover/movie','&page='+page);
}
return this.http.get(moviesUrl)
.map(this.extractData)
.catch(this.handleError);
}
// Get the movie's videos by id
| (id: number): Observable<Array<any>> {
let moviesUrl = UtilityComponent.getUrl('movie/'+id+'/videos');
return this.http.get(moviesUrl)
.map(this.extractData)
.catch(this.handleError);
}
// Get the movie's credit list
getMovieCredits(id: number){
let moviesUrl = UtilityComponent.getUrl('movie/'+id+'/credits');
return this.http.get(moviesUrl)
.map(this.extractCast)
.catch(this.handleError);
}
// Extract response data
private extractData(res: Response) {
let body = res.json();
return body.results || { };
}
// Extract response data
private extractCast(res: Response) {
let body = res.json();
return body.cast || { };
}
// Handle errors
private handleError (error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
} | getMovieVideos | identifier_name |
movie.service.ts | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import {UtilityComponent} from '../../shared/components/utility.component';
import { Movie } from './movie.model';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class MovieService {
// Constructor with injected http
constructor (private http: Http) {}
// Get movie's details by id
getMovieById (id: number): Observable<Movie> {
let moviesUrl = UtilityComponent.getUrl('movie/'+id);
return this.http.get(moviesUrl)
.map(res => res.json())
.catch(this.handleError);
}
// Get movie list by name
getMovies (name: string, page: number): Observable<Movie[]> {
let moviesUrl: string;
// If name is defined
if(name) {
// Get movies by name
moviesUrl = UtilityComponent.getUrl('search/movie','&query='+name+'&page='+page);
}else{
// Get popular movies
moviesUrl = UtilityComponent.getUrl('discover/movie','&page='+page);
} | return this.http.get(moviesUrl)
.map(this.extractData)
.catch(this.handleError);
}
// Get the movie's videos by id
getMovieVideos (id: number): Observable<Array<any>> {
let moviesUrl = UtilityComponent.getUrl('movie/'+id+'/videos');
return this.http.get(moviesUrl)
.map(this.extractData)
.catch(this.handleError);
}
// Get the movie's credit list
getMovieCredits(id: number){
let moviesUrl = UtilityComponent.getUrl('movie/'+id+'/credits');
return this.http.get(moviesUrl)
.map(this.extractCast)
.catch(this.handleError);
}
// Extract response data
private extractData(res: Response) {
let body = res.json();
return body.results || { };
}
// Extract response data
private extractCast(res: Response) {
let body = res.json();
return body.cast || { };
}
// Handle errors
private handleError (error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
} | random_line_split |
|
movie.service.ts | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import {UtilityComponent} from '../../shared/components/utility.component';
import { Movie } from './movie.model';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class MovieService {
// Constructor with injected http
constructor (private http: Http) {}
// Get movie's details by id
getMovieById (id: number): Observable<Movie> {
let moviesUrl = UtilityComponent.getUrl('movie/'+id);
return this.http.get(moviesUrl)
.map(res => res.json())
.catch(this.handleError);
}
// Get movie list by name
getMovies (name: string, page: number): Observable<Movie[]> {
let moviesUrl: string;
// If name is defined
if(name) | else{
// Get popular movies
moviesUrl = UtilityComponent.getUrl('discover/movie','&page='+page);
}
return this.http.get(moviesUrl)
.map(this.extractData)
.catch(this.handleError);
}
// Get the movie's videos by id
getMovieVideos (id: number): Observable<Array<any>> {
let moviesUrl = UtilityComponent.getUrl('movie/'+id+'/videos');
return this.http.get(moviesUrl)
.map(this.extractData)
.catch(this.handleError);
}
// Get the movie's credit list
getMovieCredits(id: number){
let moviesUrl = UtilityComponent.getUrl('movie/'+id+'/credits');
return this.http.get(moviesUrl)
.map(this.extractCast)
.catch(this.handleError);
}
// Extract response data
private extractData(res: Response) {
let body = res.json();
return body.results || { };
}
// Extract response data
private extractCast(res: Response) {
let body = res.json();
return body.cast || { };
}
// Handle errors
private handleError (error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
} | {
// Get movies by name
moviesUrl = UtilityComponent.getUrl('search/movie','&query='+name+'&page='+page);
} | conditional_block |
movie.service.ts | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import {UtilityComponent} from '../../shared/components/utility.component';
import { Movie } from './movie.model';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class MovieService {
// Constructor with injected http
constructor (private http: Http) |
// Get movie's details by id
getMovieById (id: number): Observable<Movie> {
let moviesUrl = UtilityComponent.getUrl('movie/'+id);
return this.http.get(moviesUrl)
.map(res => res.json())
.catch(this.handleError);
}
// Get movie list by name
getMovies (name: string, page: number): Observable<Movie[]> {
let moviesUrl: string;
// If name is defined
if(name) {
// Get movies by name
moviesUrl = UtilityComponent.getUrl('search/movie','&query='+name+'&page='+page);
}else{
// Get popular movies
moviesUrl = UtilityComponent.getUrl('discover/movie','&page='+page);
}
return this.http.get(moviesUrl)
.map(this.extractData)
.catch(this.handleError);
}
// Get the movie's videos by id
getMovieVideos (id: number): Observable<Array<any>> {
let moviesUrl = UtilityComponent.getUrl('movie/'+id+'/videos');
return this.http.get(moviesUrl)
.map(this.extractData)
.catch(this.handleError);
}
// Get the movie's credit list
getMovieCredits(id: number){
let moviesUrl = UtilityComponent.getUrl('movie/'+id+'/credits');
return this.http.get(moviesUrl)
.map(this.extractCast)
.catch(this.handleError);
}
// Extract response data
private extractData(res: Response) {
let body = res.json();
return body.results || { };
}
// Extract response data
private extractCast(res: Response) {
let body = res.json();
return body.cast || { };
}
// Handle errors
private handleError (error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
} | {} | identifier_body |
ActionParameterRowEditorDialog.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 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,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
Ext.define('OPF.console.domain.view.action.ActionParameterRowEditorDialog', {
extend: 'Ext.window.Window',
alias: 'widget.action-parameter-row-editor',
title: 'Parameter Editor',
id: 'actionParameterRowEditorDialog',
layout: 'fit',
modal: true,
closable: true,
closeAction: 'hide',
grid: null,
rowIndex: null,
width: 400,
height: 240,
constructor: function(grid, cfg) {
cfg = cfg || {};
OPF.console.domain.view.action.ActionParameterRowEditorDialog.superclass.constructor.call(this, Ext.apply({
grid: grid
}, cfg));
},
initComponent: function(){
this.paramName = OPF.Ui.textFormField('name', 'Name');
this.paramLocation = OPF.Ui.comboFormField('location', 'Location');
this.paramType = OPF.Ui.comboFormField('fieldType', 'Type');
this.paramDescription = OPF.Ui.textFormArea('description', 'Description');
this.form = Ext.create('Ext.form.Panel', {
frame: true,
layout: 'anchor',
defaults: {
bodyStyle: 'padding 5px;'
},
fbar: [
OPF.Ui.createBtn('Save', 50, 'save-parameter', {formBind : true}),
OPF.Ui.createBtn('Reset', 55, 'reset-parameter'),
OPF.Ui.createBtn('Cancel', 60, 'cancel-parameter')
],
items: [
this.paramLocation,
this.paramName,
this.paramType,
this.paramDescription
]
});
this.items = [
this.form
];
this.callParent(arguments);
},
setGrid: function(grid) {
this.grid = grid;
}, | this.rowIndex = rowIndex;
var model = this.grid.store.getAt(rowIndex);
if (isNotEmpty(model)) {
this.paramName.setValue(model.get('name'));
this.paramLocation.setValue(model.get('location'));
this.paramType.setValue(model.get('fieldType'));
this.paramDescription.setValue(model.get('description'));
}
}
},
startEditing: function(rowIndex) {
this.show();
this.fillingEditor(rowIndex);
var constraints = Ext.create('OPF.core.validation.FormInitialisation', OPF.core.utils.RegistryNodeType.ACTION_PARAMETER.getConstraintName());
constraints.initConstraints(this.form, null);
},
stopEditing: function() {
this.hide();
this.paramName.setValue('');
this.paramLocation.setValue('');
this.paramType.setValue('');
this.paramDescription.setValue('');
this.rowIndex = null;
}
}); |
fillingEditor: function(rowIndex) {
if (isNotEmpty(rowIndex)) { | random_line_split |
ActionParameterRowEditorDialog.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 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,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
Ext.define('OPF.console.domain.view.action.ActionParameterRowEditorDialog', {
extend: 'Ext.window.Window',
alias: 'widget.action-parameter-row-editor',
title: 'Parameter Editor',
id: 'actionParameterRowEditorDialog',
layout: 'fit',
modal: true,
closable: true,
closeAction: 'hide',
grid: null,
rowIndex: null,
width: 400,
height: 240,
constructor: function(grid, cfg) {
cfg = cfg || {};
OPF.console.domain.view.action.ActionParameterRowEditorDialog.superclass.constructor.call(this, Ext.apply({
grid: grid
}, cfg));
},
initComponent: function(){
this.paramName = OPF.Ui.textFormField('name', 'Name');
this.paramLocation = OPF.Ui.comboFormField('location', 'Location');
this.paramType = OPF.Ui.comboFormField('fieldType', 'Type');
this.paramDescription = OPF.Ui.textFormArea('description', 'Description');
this.form = Ext.create('Ext.form.Panel', {
frame: true,
layout: 'anchor',
defaults: {
bodyStyle: 'padding 5px;'
},
fbar: [
OPF.Ui.createBtn('Save', 50, 'save-parameter', {formBind : true}),
OPF.Ui.createBtn('Reset', 55, 'reset-parameter'),
OPF.Ui.createBtn('Cancel', 60, 'cancel-parameter')
],
items: [
this.paramLocation,
this.paramName,
this.paramType,
this.paramDescription
]
});
this.items = [
this.form
];
this.callParent(arguments);
},
setGrid: function(grid) {
this.grid = grid;
},
fillingEditor: function(rowIndex) {
if (isNotEmpty(rowIndex)) {
this.rowIndex = rowIndex;
var model = this.grid.store.getAt(rowIndex);
if (isNotEmpty(model)) |
}
},
startEditing: function(rowIndex) {
this.show();
this.fillingEditor(rowIndex);
var constraints = Ext.create('OPF.core.validation.FormInitialisation', OPF.core.utils.RegistryNodeType.ACTION_PARAMETER.getConstraintName());
constraints.initConstraints(this.form, null);
},
stopEditing: function() {
this.hide();
this.paramName.setValue('');
this.paramLocation.setValue('');
this.paramType.setValue('');
this.paramDescription.setValue('');
this.rowIndex = null;
}
}); | {
this.paramName.setValue(model.get('name'));
this.paramLocation.setValue(model.get('location'));
this.paramType.setValue(model.get('fieldType'));
this.paramDescription.setValue(model.get('description'));
} | conditional_block |
lib.rs | #![doc(html_root_url = "http://cpjreynolds.github.io/rustty/rustty/index.html")]
//! # Rustty
//!
//! Rustty is a terminal UI library that provides a simple, concise abstraction over an
//! underlying terminal device.
//!
//! Rustty is based on the concepts of cells and events. A terminal display is an array of cells,
//! each holding a character and a set of foreground and background styles. Events are how a
//! terminal communicates changes in its state; events are received from a terminal, processed, and
//! pushed onto an input stream to be read and responded to.
//!
//! Futher reading on the concepts behind Rustty can be found in the
//! [README](https://github.com/cpjreynolds/rustty/blob/master/README.md)
extern crate term;
extern crate nix;
extern crate libc;
extern crate gag;
#[macro_use] extern crate lazy_static;
mod core;
mod util;
pub mod ui;
pub use core::terminal::Terminal;
pub use core::cellbuffer::{
Cell, | pub use core::position::{Pos, Size, HasSize, HasPosition};
pub use core::input::Event;
pub use util::errors::Error; | Color,
Attr,
CellAccessor,
}; | random_line_split |
WAxesButtons.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from roars.gui.pyqtutils import PyQtWidget, PyQtImageConverter
from WBaseWidget import WBaseWidget
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4 import QtCore
class WAxesButtons(WBaseWidget):
def | (self, name='axes', label='Axes Buttons', changeCallback=None, step=0.001):
super(WAxesButtons, self).__init__(
'ui_axes_buttons'
)
self.name = name
self.label = label
self.step = step
self.ui_label.setText(label)
#⬢⬢⬢⬢⬢➤ Callback
self.changeCallback = changeCallback
self.buttons = {
'x+': self.ui_button_x_plus,
'x-': self.ui_button_x_minus,
'y+': self.ui_button_y_plus,
'y-': self.ui_button_y_minus,
'z+': self.ui_button_z_plus,
'z-': self.ui_button_z_minus
}
self.buttons_name_map = {}
# TODO:example style
self.ui_button_x_minus.setStyleSheet(
"QPushButton:hover{background-color: red}")
for label, button in self.buttons.iteritems():
button.clicked.connect(self.buttonPressed)
self.buttons_name_map[str(button.objectName())] = label
def buttonPressed(self):
if self.changeCallback != None:
label = self.buttons_name_map[str(self.sender().objectName())]
delta = float(label[1] + str(self.step))
val = (self.name, label[0], delta)
self.changeCallback(val)
| __init__ | identifier_name |
WAxesButtons.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from roars.gui.pyqtutils import PyQtWidget, PyQtImageConverter
from WBaseWidget import WBaseWidget
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4 import QtCore
class WAxesButtons(WBaseWidget):
def __init__(self, name='axes', label='Axes Buttons', changeCallback=None, step=0.001):
super(WAxesButtons, self).__init__(
'ui_axes_buttons'
)
self.name = name
self.label = label
self.step = step
self.ui_label.setText(label)
#⬢⬢⬢⬢⬢➤ Callback
self.changeCallback = changeCallback
self.buttons = {
'x+': self.ui_button_x_plus,
'x-': self.ui_button_x_minus,
'y+': self.ui_button_y_plus,
'y-': self.ui_button_y_minus,
'z+': self.ui_button_z_plus,
'z-': self.ui_button_z_minus
}
self.buttons_name_map = {}
# TODO:example style
self.ui_button_x_minus.setStyleSheet(
"QPushButton:hover{background-color: red}")
for label, button in self.buttons.iteritems():
button.clicked.connect(self.buttonPressed)
self.buttons_name_map[str(button.objectName())] = label
def buttonPressed(self):
if self.changeCallback != None:
label = self | .buttons_name_map[str(self.sender().objectName())]
delta = float(label[1] + str(self.step))
val = (self.name, label[0], delta)
self.changeCallback(val)
| conditional_block |
|
WAxesButtons.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*- | from PyQt4.QtCore import *
from PyQt4 import QtCore
class WAxesButtons(WBaseWidget):
def __init__(self, name='axes', label='Axes Buttons', changeCallback=None, step=0.001):
super(WAxesButtons, self).__init__(
'ui_axes_buttons'
)
self.name = name
self.label = label
self.step = step
self.ui_label.setText(label)
#⬢⬢⬢⬢⬢➤ Callback
self.changeCallback = changeCallback
self.buttons = {
'x+': self.ui_button_x_plus,
'x-': self.ui_button_x_minus,
'y+': self.ui_button_y_plus,
'y-': self.ui_button_y_minus,
'z+': self.ui_button_z_plus,
'z-': self.ui_button_z_minus
}
self.buttons_name_map = {}
# TODO:example style
self.ui_button_x_minus.setStyleSheet(
"QPushButton:hover{background-color: red}")
for label, button in self.buttons.iteritems():
button.clicked.connect(self.buttonPressed)
self.buttons_name_map[str(button.objectName())] = label
def buttonPressed(self):
if self.changeCallback != None:
label = self.buttons_name_map[str(self.sender().objectName())]
delta = float(label[1] + str(self.step))
val = (self.name, label[0], delta)
self.changeCallback(val) |
from roars.gui.pyqtutils import PyQtWidget, PyQtImageConverter
from WBaseWidget import WBaseWidget
from PyQt4.QtGui import * | random_line_split |
WAxesButtons.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from roars.gui.pyqtutils import PyQtWidget, PyQtImageConverter
from WBaseWidget import WBaseWidget
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4 import QtCore
class WAxesButtons(WBaseWidget):
def __init__(self, name='axes', label='Axes Buttons', changeCallback=None, step=0.001):
| self.buttons_name_map = {}
# TODO:example style
self.ui_button_x_minus.setStyleSheet(
"QPushButton:hover{background-color: red}")
for label, button in self.buttons.iteritems():
button.clicked.connect(self.buttonPressed)
self.buttons_name_map[str(button.objectName())] = label
def bu
ttonPressed(self):
if self.changeCallback != None:
label = self.buttons_name_map[str(self.sender().objectName())]
delta = float(label[1] + str(self.step))
val = (self.name, label[0], delta)
self.changeCallback(val)
| super(WAxesButtons, self).__init__(
'ui_axes_buttons'
)
self.name = name
self.label = label
self.step = step
self.ui_label.setText(label)
#⬢⬢⬢⬢⬢➤ Callback
self.changeCallback = changeCallback
self.buttons = {
'x+': self.ui_button_x_plus,
'x-': self.ui_button_x_minus,
'y+': self.ui_button_y_plus,
'y-': self.ui_button_y_minus,
'z+': self.ui_button_z_plus,
'z-': self.ui_button_z_minus
} | identifier_body |
component.js | includes(selectedMappingType);
}),
/**
* Calculates the correct urn prefix
* @type {String}
*/
urnPrefix: computed('selectedMappingType', function () {
return `thirdeye:${this.get('selectedMappingType')}:`;
}),
/**
* Single source of truth for new entity mapping urn
* this cp gets and sets 'urnPrefix' and '_id' if the syntax is correct
* @type {String}
*/
urn: computed('urnPrefix', '_id', {
get() {
return `${this.get('urnPrefix')}${this.get('_id')}`;
},
set(key, value) {
if (value.startsWith(this.get('urnPrefix'))) {
const newUrn = value.split(':').pop();
this.set('_id', newUrn);
}
return value;
}
}),
/**
* Checks if the currently selected entity is already in the mapping
*/
mappingExists: computed(
'selectedEntity.label',
'[email protected]',
'metric',
'urn',
function() {
const {
selectedEntity: entity,
relatedEntities,
metric,
urn
} = getProperties(this, 'selectedEntity', 'relatedEntities', 'metric', 'urn');
return [metric, ...relatedEntities].some((relatedEntity) => {
return relatedEntity.label === entity.alias || relatedEntity.urn === urn;
});
}
),
/**
* Helper function that sets an error
* @param {String} error - the error message
*/
setError(error) {
set(this, 'errorMessage', error);
},
/**
* Helper function that clears errors
*/
clearError() {
set(this, 'errorMessage', '');
},
/**
* Entity Mapping columns to be passed into
* ember-models-table
*/
entityColumns: Object.freeze([
{
propertyName: 'type',
title: 'Types',
filterWithSelect: true,
className: 'te-modal__table-cell te-modal__table-cell--capitalized',
predefinedFilterOptions: MAPPING_TYPES.map(type => type.toLowerCase())
},
{
template: 'custom/filterLabel',
title: 'Filter value',
className: 'te-modal__table-cell',
propertyName: 'label',
sortedBy: 'label',
// custom filter function
filterFunction(cell, string, record) {
return ['urn', 'label'].some(key => record[key].includes(string));
}
},
{
propertyName: 'createdBy',
title: 'Created by',
className: 'te-modal__table-cell'
},
// Todo: Fix back end to send
// dateCreated data
// {
// propertyName: 'dateCreated',
// title: 'Date Created'
// },
{
template: 'custom/tableDelete',
title: '',
className: 'te-modal__table-cell te-modal__table-cell--delete te-modal__table-cell--dark'
}
]),
/**
* Custom classes to be applied to the entity modal table
*/
classes: Object.freeze({
theadCell: "te-modal__table-header"
}),
/**
* Whether the user can add the currently selected entity
*/
canAddMapping: computed('mappingExists', 'selectedEntity', '_id', function() {
const {
mappingExists,
_id,
metric
} = getProperties(this, 'mappingExists', '_id', 'metric');
return !mappingExists && [_id, metric].every(isPresent);
}),
/**
* Calculates the params object
* to be send with the create call
* @type {Object}
*/
entityParams: computed(
'selectedMappingType',
'metricUrn',
'urn',
function () {
const {
selectedMappingType: entityType,
metricUrn,
urn
} = getProperties(
this,
'metricUrn',
'selectedMappingType',
'urn'
);
return {
fromURN: metricUrn,
mappingType: `METRIC_TO_${entityType.toUpperCase()}`,
score: '1.0',
toURN: urn
};
}
),
/**
* Restartable Ember concurrency task that triggers the autocomplete behavior
* @return {Array}
*/
searchEntitiesTask: task(function* (searchString) {
yield timeout(600);
const entityType = this.get('selectedMappingType');
let url = '';
switch(entityType) {
case 'metric':
url = entityMappingApi.metricAutoCompleteUrl(searchString);
break;
case 'dataset':
case 'service':
return this.get(`${entityType}s`).filter(item => item.includes(searchString));
}
/**
* Necessary headers for fetch
*/
const headers = {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Cache': 'no-cache'
},
credentials: 'include'
};
return fetch(url, headers)
.then(checkStatus);
}).restartable(),
async init() {
this._super(...arguments);
const datasets = await fetch(entityMappingApi.getDatasetsUrl).then(checkStatus);
if (this.isDestroyed || this.isDestroying) {
return;
}
set(this, 'datasets', datasets);
},
/**
* Fetches new entities with caching and diff checking
*/
didReceiveAttrs() {
const {
metric,
_cachedMetric,
showEntityMappingModal
} = getProperties(this, 'metric', '_cachedMetric', 'showEntityMappingModal');
if (showEntityMappingModal && metric && !_.isEqual(metric, _cachedMetric)) {
set(this, '_cachedMetric', metric);
this._fetchRelatedEntities();
}
},
/**
* Reset the entity mapping type and selected entity
* @param {String} selectedMappingType - selected mapping type
* @return {undefined}
*/
reset(selectedMappingType = 'dataset') {
this.setProperties({
selectedMappingType,
selectedEntity: '',
_id: ''
});
},
/**
* Build the Urn to Id mapping
* @param {Array} entities - array of entities
* @return {undefined}
*/
buildUrnToId(entities) {
const urnToId = entities.reduce((agg, entity) => {
agg[entity.toURN] = entity.id;
return agg;
}, {});
set(this, 'urnToId', urnToId);
},
/**
* Construct the url string based on the passed entities
* @param {Array} entities - array of entities
* @return {String}
*/
makeUrlString(entities) {
const urnStrings = entities
.map((entity) => `${entity.toURN}`)
.join(',');
if (urnStrings.length) {
return entityMappingApi.getRelatedEntitiesDataUrl(urnStrings);
}
},
/**
* Fetches related Entities
*/
_fetchRelatedEntities: async function () {
const metricUrn = get(this, 'metricUrn');
const entities = await fetch(`${entityMappingApi.getRelatedEntitiesUrl}/${metricUrn}`).then(checkStatus);
const url = this.makeUrlString(entities);
this.buildUrnToId(entities);
if (!url) {
return;
}
const relatedEntities = await fetch(url).then(checkStatus);
// merges createBy Props
relatedEntities.forEach((item) => {
if (!item.urn) {
return;
}
const { createdBy } = _.find(entities, { toURN: item.urn }) || { createdBy: null };
item.createdBy = createdBy;
return item;
});
set(this, '_relatedEntities', relatedEntities);
},
actions: {
/**
* Handles the close event
* @return {undefined}
*/
onExit() {
set(this, 'showEntityMappingModal', false);
this.onSubmit();
},
/**
* Deletes the entity
* @param {Object} entity - entity to delete
* @return {undefined}
*/
onDeleteEntity: async function(entity) {
const relatedEntities = get(this, 'relatedEntities');
const id = get(this, 'urnToId')[entity.urn];
const url = `${entityMappingApi.deleteUrl}/${id}`;
try {
const res = await fetch(url, deleteProps);
const { status } = res;
if (status !== 200) {
throw new Error('Uh Oh. Something went wrong.');
}
} catch (error) {
return this.setError('error');
}
this.clearError();
relatedEntities.removeObject(entity);
},
/**
* Handles the add event
* sends new mapping and reloads
* @return {undefined}
*/
onAddFilter: async function() {
const {
canAddMapping,
entityParams
} = getProperties(
this,
'canAddMapping',
'entityParams',
);
if (!canAddMapping) { return; }
try {
const res = await fetch(entityMappingApi.createUrl, postProps(entityParams));
const { status } = res;
if (status !== 200) | {
throw new Error('Uh Oh. Something went wrong.');
} | conditional_block |
|
component.js | '',
/**
* Mapping type array used for the mapping drop down
* @type {Array}
*/
mappingTypes: MAPPING_TYPES
.map(type => type.toLowerCase())
.sort(),
/**
* Mapping from urn to entities Ids
* @type {Object}
*/
urnToId: Object.assign({}),
/**
* Error Message String
*/
errorMessage: '',
/**
* Cached private property for the id portion of the urn
*/
_id: '',
/**
* passed primary metric attrs
* @type {Object}
*/
metric: null,
/**
* Cached metric
*/
_cachedMetric: null,
/**
* Last entity searched
* @type {String}
*/
lastSearchTerm: '',
/**
* Fetched related entities
* @type {Array}
*/
_relatedEntities: Object.assign([]),
/**
* Flag for displaying the modal
* @type {boolean}
*/
showEntityMappingModal: true,
/**
* current logged in user
*/
user: reads('session.data.authenticated.name'),
/**
* Header text of modal
* @type {string}
*/
headerText: computed('metric', function () {
const metric = get(this, 'metric');
if (_.isEmpty(metric)) {
return 'Configure Filters';
}
return `Configure Filters for analyzing ${metric.label}`;
}),
/**
* Primary metric urn
*/
metricUrn: computed('_cachedMetric', function() {
const cachedMetricUrn = getWithDefault(this, '_cachedMetric.urn', '');
const [app, metric, id] = cachedMetricUrn.split(':');
return [app, metric, id].join(':');
}),
/**
* Applies data massaging while getting the property
* @type {Array}
*/
relatedEntities: computed(
'_relatedEntities.@each', {
get() {
return getWithDefault(this, '_relatedEntities', []);
},
set(key, value) {
return value;
}
}
),
/**
* Determines whether to show the power-select or the input
* @type {Boolean}
*/
showAdvancedInput: computed('selectedMappingType', function() {
const selectedMappingType = get(this, 'selectedMappingType');
return ['dataset', 'metric', 'service'].includes(selectedMappingType);
}),
/**
* Calculates the correct urn prefix
* @type {String}
*/
urnPrefix: computed('selectedMappingType', function () {
return `thirdeye:${this.get('selectedMappingType')}:`;
}),
/**
* Single source of truth for new entity mapping urn
* this cp gets and sets 'urnPrefix' and '_id' if the syntax is correct
* @type {String}
*/
urn: computed('urnPrefix', '_id', {
get() {
return `${this.get('urnPrefix')}${this.get('_id')}`;
},
set(key, value) {
if (value.startsWith(this.get('urnPrefix'))) {
const newUrn = value.split(':').pop();
this.set('_id', newUrn);
}
return value;
}
}),
/**
* Checks if the currently selected entity is already in the mapping
*/
mappingExists: computed(
'selectedEntity.label',
'[email protected]',
'metric',
'urn',
function() {
const {
selectedEntity: entity,
relatedEntities,
metric,
urn
} = getProperties(this, 'selectedEntity', 'relatedEntities', 'metric', 'urn');
return [metric, ...relatedEntities].some((relatedEntity) => {
return relatedEntity.label === entity.alias || relatedEntity.urn === urn;
});
}
),
/**
* Helper function that sets an error
* @param {String} error - the error message
*/
setError(error) {
set(this, 'errorMessage', error);
},
/**
* Helper function that clears errors
*/
clearError() {
set(this, 'errorMessage', '');
},
/**
* Entity Mapping columns to be passed into
* ember-models-table
*/
entityColumns: Object.freeze([
{
propertyName: 'type',
title: 'Types',
filterWithSelect: true,
className: 'te-modal__table-cell te-modal__table-cell--capitalized',
predefinedFilterOptions: MAPPING_TYPES.map(type => type.toLowerCase())
},
{
template: 'custom/filterLabel',
title: 'Filter value',
className: 'te-modal__table-cell',
propertyName: 'label',
sortedBy: 'label',
// custom filter function
filterFunction(cell, string, record) {
return ['urn', 'label'].some(key => record[key].includes(string));
}
},
{
propertyName: 'createdBy',
title: 'Created by',
className: 'te-modal__table-cell'
},
// Todo: Fix back end to send
// dateCreated data
// {
// propertyName: 'dateCreated',
// title: 'Date Created'
// },
{
template: 'custom/tableDelete',
title: '',
className: 'te-modal__table-cell te-modal__table-cell--delete te-modal__table-cell--dark'
}
]),
/**
* Custom classes to be applied to the entity modal table
*/
classes: Object.freeze({
theadCell: "te-modal__table-header"
}),
/**
* Whether the user can add the currently selected entity
*/
canAddMapping: computed('mappingExists', 'selectedEntity', '_id', function() {
const {
mappingExists,
_id,
metric
} = getProperties(this, 'mappingExists', '_id', 'metric');
return !mappingExists && [_id, metric].every(isPresent);
}),
/**
* Calculates the params object
* to be send with the create call
* @type {Object}
*/
entityParams: computed(
'selectedMappingType',
'metricUrn',
'urn',
function () {
const {
selectedMappingType: entityType,
metricUrn,
urn
} = getProperties(
this,
'metricUrn',
'selectedMappingType',
'urn'
);
return {
fromURN: metricUrn,
mappingType: `METRIC_TO_${entityType.toUpperCase()}`,
score: '1.0',
toURN: urn
};
}
),
/**
* Restartable Ember concurrency task that triggers the autocomplete behavior
* @return {Array}
*/
searchEntitiesTask: task(function* (searchString) {
yield timeout(600);
const entityType = this.get('selectedMappingType');
let url = '';
switch(entityType) {
case 'metric':
url = entityMappingApi.metricAutoCompleteUrl(searchString);
break;
case 'dataset':
case 'service':
return this.get(`${entityType}s`).filter(item => item.includes(searchString));
}
/**
* Necessary headers for fetch
*/
const headers = {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Cache': 'no-cache'
},
credentials: 'include'
};
return fetch(url, headers)
.then(checkStatus);
}).restartable(),
async | () {
this._super(...arguments);
const datasets = await fetch(entityMappingApi.getDatasetsUrl).then(checkStatus);
if (this.isDestroyed || this.isDestroying) {
return;
}
set(this, 'datasets', datasets);
},
/**
* Fetches new entities with caching and diff checking
*/
didReceiveAttrs() {
const {
metric,
_cachedMetric,
showEntityMappingModal
} = getProperties(this, 'metric', '_cachedMetric', 'showEntityMappingModal');
if (showEntityMappingModal && metric && !_.isEqual(metric, _cachedMetric)) {
set(this, '_cachedMetric', metric);
this._fetchRelatedEntities();
}
},
/**
* Reset the entity mapping type and selected entity
* @param {String} selectedMappingType - selected mapping type
* @return {undefined}
*/
reset(selectedMappingType = 'dataset') {
this.setProperties({
selectedMappingType,
selectedEntity: '',
_id: ''
});
},
/**
* Build the Urn to Id mapping
* @param {Array} entities - array of entities
* @return {undefined}
*/
buildUrnToId(entities) {
const urnToId = entities.reduce((agg, entity) => {
agg[entity.toURN] = entity.id;
return agg;
}, {});
set(this, 'urnToId', urnToId);
},
/**
* Construct the url string based on the passed entities
* @param {Array} entities - array of entities
* @return {String}
*/
makeUrlString(entities) {
const urnStrings = entities
.map((entity) => `${entity.toURN}`)
.join(',');
if (urnStrings.length) {
return entityMappingApi.getRelated | init | identifier_name |
component.js | for the mapping drop down
* @type {Array}
*/
mappingTypes: MAPPING_TYPES
.map(type => type.toLowerCase())
.sort(),
/**
* Mapping from urn to entities Ids
* @type {Object}
*/
urnToId: Object.assign({}),
/**
* Error Message String
*/
errorMessage: '',
/**
* Cached private property for the id portion of the urn
*/
_id: '',
/**
* passed primary metric attrs
* @type {Object}
*/
metric: null,
/**
* Cached metric
*/
_cachedMetric: null,
/**
* Last entity searched
* @type {String}
*/
lastSearchTerm: '',
/**
* Fetched related entities
* @type {Array}
*/
_relatedEntities: Object.assign([]),
/**
* Flag for displaying the modal
* @type {boolean}
*/
showEntityMappingModal: true,
/**
* current logged in user
*/
user: reads('session.data.authenticated.name'),
/**
* Header text of modal
* @type {string}
*/
headerText: computed('metric', function () {
const metric = get(this, 'metric');
if (_.isEmpty(metric)) {
return 'Configure Filters';
}
return `Configure Filters for analyzing ${metric.label}`;
}),
/**
* Primary metric urn
*/
metricUrn: computed('_cachedMetric', function() {
const cachedMetricUrn = getWithDefault(this, '_cachedMetric.urn', '');
const [app, metric, id] = cachedMetricUrn.split(':');
return [app, metric, id].join(':');
}),
/**
* Applies data massaging while getting the property
* @type {Array}
*/
relatedEntities: computed(
'_relatedEntities.@each', {
get() {
return getWithDefault(this, '_relatedEntities', []);
},
set(key, value) {
return value;
}
}
),
/**
* Determines whether to show the power-select or the input
* @type {Boolean}
*/
showAdvancedInput: computed('selectedMappingType', function() {
const selectedMappingType = get(this, 'selectedMappingType');
return ['dataset', 'metric', 'service'].includes(selectedMappingType);
}),
/**
* Calculates the correct urn prefix
* @type {String}
*/
urnPrefix: computed('selectedMappingType', function () {
return `thirdeye:${this.get('selectedMappingType')}:`;
}),
/**
* Single source of truth for new entity mapping urn
* this cp gets and sets 'urnPrefix' and '_id' if the syntax is correct
* @type {String}
*/
urn: computed('urnPrefix', '_id', {
get() {
return `${this.get('urnPrefix')}${this.get('_id')}`;
},
set(key, value) {
if (value.startsWith(this.get('urnPrefix'))) {
const newUrn = value.split(':').pop();
this.set('_id', newUrn);
}
return value;
}
}),
/**
* Checks if the currently selected entity is already in the mapping
*/
mappingExists: computed(
'selectedEntity.label',
'[email protected]',
'metric',
'urn',
function() {
const {
selectedEntity: entity,
relatedEntities,
metric,
urn
} = getProperties(this, 'selectedEntity', 'relatedEntities', 'metric', 'urn');
return [metric, ...relatedEntities].some((relatedEntity) => {
return relatedEntity.label === entity.alias || relatedEntity.urn === urn;
});
}
),
/**
* Helper function that sets an error
* @param {String} error - the error message
*/
setError(error) {
set(this, 'errorMessage', error);
},
/**
* Helper function that clears errors
*/
clearError() {
set(this, 'errorMessage', '');
},
/**
* Entity Mapping columns to be passed into
* ember-models-table
*/
entityColumns: Object.freeze([
{
propertyName: 'type',
title: 'Types',
filterWithSelect: true,
className: 'te-modal__table-cell te-modal__table-cell--capitalized',
predefinedFilterOptions: MAPPING_TYPES.map(type => type.toLowerCase())
},
{
template: 'custom/filterLabel',
title: 'Filter value',
className: 'te-modal__table-cell',
propertyName: 'label',
sortedBy: 'label',
// custom filter function
filterFunction(cell, string, record) {
return ['urn', 'label'].some(key => record[key].includes(string));
}
},
{
propertyName: 'createdBy',
title: 'Created by',
className: 'te-modal__table-cell'
},
// Todo: Fix back end to send
// dateCreated data
// {
// propertyName: 'dateCreated',
// title: 'Date Created'
// },
{
template: 'custom/tableDelete',
title: '',
className: 'te-modal__table-cell te-modal__table-cell--delete te-modal__table-cell--dark'
}
]),
/**
* Custom classes to be applied to the entity modal table
*/
classes: Object.freeze({
theadCell: "te-modal__table-header"
}),
/**
* Whether the user can add the currently selected entity
*/
canAddMapping: computed('mappingExists', 'selectedEntity', '_id', function() {
const {
mappingExists,
_id,
metric
} = getProperties(this, 'mappingExists', '_id', 'metric');
return !mappingExists && [_id, metric].every(isPresent);
}),
/**
* Calculates the params object
* to be send with the create call
* @type {Object}
*/
entityParams: computed(
'selectedMappingType',
'metricUrn',
'urn',
function () {
const {
selectedMappingType: entityType,
metricUrn,
urn
} = getProperties(
this,
'metricUrn',
'selectedMappingType',
'urn'
);
return {
fromURN: metricUrn,
mappingType: `METRIC_TO_${entityType.toUpperCase()}`,
score: '1.0',
toURN: urn
};
}
),
/**
* Restartable Ember concurrency task that triggers the autocomplete behavior
* @return {Array}
*/
searchEntitiesTask: task(function* (searchString) {
yield timeout(600);
const entityType = this.get('selectedMappingType');
let url = '';
switch(entityType) {
case 'metric':
url = entityMappingApi.metricAutoCompleteUrl(searchString);
break;
case 'dataset':
case 'service':
return this.get(`${entityType}s`).filter(item => item.includes(searchString));
}
/**
* Necessary headers for fetch
*/
const headers = {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Cache': 'no-cache'
},
credentials: 'include'
};
return fetch(url, headers)
.then(checkStatus);
}).restartable(),
async init() {
this._super(...arguments);
const datasets = await fetch(entityMappingApi.getDatasetsUrl).then(checkStatus);
if (this.isDestroyed || this.isDestroying) {
return;
}
set(this, 'datasets', datasets);
},
/**
* Fetches new entities with caching and diff checking
*/
didReceiveAttrs() {
const {
metric,
_cachedMetric,
showEntityMappingModal
} = getProperties(this, 'metric', '_cachedMetric', 'showEntityMappingModal');
if (showEntityMappingModal && metric && !_.isEqual(metric, _cachedMetric)) {
set(this, '_cachedMetric', metric);
this._fetchRelatedEntities();
}
},
/**
* Reset the entity mapping type and selected entity
* @param {String} selectedMappingType - selected mapping type
* @return {undefined}
*/
reset(selectedMappingType = 'dataset') {
this.setProperties({
selectedMappingType,
selectedEntity: '',
_id: ''
});
},
/**
* Build the Urn to Id mapping
* @param {Array} entities - array of entities
* @return {undefined}
*/
buildUrnToId(entities) {
const urnToId = entities.reduce((agg, entity) => {
agg[entity.toURN] = entity.id;
return agg;
}, {});
set(this, 'urnToId', urnToId);
},
/**
* Construct the url string based on the passed entities
* @param {Array} entities - array of entities
* @return {String}
*/
makeUrlString(entities) {
const urnStrings = entities
.map((entity) => `${entity.toURN}`)
.join(',');
if (urnStrings.length) { | return entityMappingApi.getRelatedEntitiesDataUrl(urnStrings);
}
},
| random_line_split |
|
component.js | '',
/**
* Mapping type array used for the mapping drop down
* @type {Array}
*/
mappingTypes: MAPPING_TYPES
.map(type => type.toLowerCase())
.sort(),
/**
* Mapping from urn to entities Ids
* @type {Object}
*/
urnToId: Object.assign({}),
/**
* Error Message String
*/
errorMessage: '',
/**
* Cached private property for the id portion of the urn
*/
_id: '',
/**
* passed primary metric attrs
* @type {Object}
*/
metric: null,
/**
* Cached metric
*/
_cachedMetric: null,
/**
* Last entity searched
* @type {String}
*/
lastSearchTerm: '',
/**
* Fetched related entities
* @type {Array}
*/
_relatedEntities: Object.assign([]),
/**
* Flag for displaying the modal
* @type {boolean}
*/
showEntityMappingModal: true,
/**
* current logged in user
*/
user: reads('session.data.authenticated.name'),
/**
* Header text of modal
* @type {string}
*/
headerText: computed('metric', function () {
const metric = get(this, 'metric');
if (_.isEmpty(metric)) {
return 'Configure Filters';
}
return `Configure Filters for analyzing ${metric.label}`;
}),
/**
* Primary metric urn
*/
metricUrn: computed('_cachedMetric', function() {
const cachedMetricUrn = getWithDefault(this, '_cachedMetric.urn', '');
const [app, metric, id] = cachedMetricUrn.split(':');
return [app, metric, id].join(':');
}),
/**
* Applies data massaging while getting the property
* @type {Array}
*/
relatedEntities: computed(
'_relatedEntities.@each', {
get() {
return getWithDefault(this, '_relatedEntities', []);
},
set(key, value) {
return value;
}
}
),
/**
* Determines whether to show the power-select or the input
* @type {Boolean}
*/
showAdvancedInput: computed('selectedMappingType', function() {
const selectedMappingType = get(this, 'selectedMappingType');
return ['dataset', 'metric', 'service'].includes(selectedMappingType);
}),
/**
* Calculates the correct urn prefix
* @type {String}
*/
urnPrefix: computed('selectedMappingType', function () {
return `thirdeye:${this.get('selectedMappingType')}:`;
}),
/**
* Single source of truth for new entity mapping urn
* this cp gets and sets 'urnPrefix' and '_id' if the syntax is correct
* @type {String}
*/
urn: computed('urnPrefix', '_id', {
get() | ,
set(key, value) {
if (value.startsWith(this.get('urnPrefix'))) {
const newUrn = value.split(':').pop();
this.set('_id', newUrn);
}
return value;
}
}),
/**
* Checks if the currently selected entity is already in the mapping
*/
mappingExists: computed(
'selectedEntity.label',
'[email protected]',
'metric',
'urn',
function() {
const {
selectedEntity: entity,
relatedEntities,
metric,
urn
} = getProperties(this, 'selectedEntity', 'relatedEntities', 'metric', 'urn');
return [metric, ...relatedEntities].some((relatedEntity) => {
return relatedEntity.label === entity.alias || relatedEntity.urn === urn;
});
}
),
/**
* Helper function that sets an error
* @param {String} error - the error message
*/
setError(error) {
set(this, 'errorMessage', error);
},
/**
* Helper function that clears errors
*/
clearError() {
set(this, 'errorMessage', '');
},
/**
* Entity Mapping columns to be passed into
* ember-models-table
*/
entityColumns: Object.freeze([
{
propertyName: 'type',
title: 'Types',
filterWithSelect: true,
className: 'te-modal__table-cell te-modal__table-cell--capitalized',
predefinedFilterOptions: MAPPING_TYPES.map(type => type.toLowerCase())
},
{
template: 'custom/filterLabel',
title: 'Filter value',
className: 'te-modal__table-cell',
propertyName: 'label',
sortedBy: 'label',
// custom filter function
filterFunction(cell, string, record) {
return ['urn', 'label'].some(key => record[key].includes(string));
}
},
{
propertyName: 'createdBy',
title: 'Created by',
className: 'te-modal__table-cell'
},
// Todo: Fix back end to send
// dateCreated data
// {
// propertyName: 'dateCreated',
// title: 'Date Created'
// },
{
template: 'custom/tableDelete',
title: '',
className: 'te-modal__table-cell te-modal__table-cell--delete te-modal__table-cell--dark'
}
]),
/**
* Custom classes to be applied to the entity modal table
*/
classes: Object.freeze({
theadCell: "te-modal__table-header"
}),
/**
* Whether the user can add the currently selected entity
*/
canAddMapping: computed('mappingExists', 'selectedEntity', '_id', function() {
const {
mappingExists,
_id,
metric
} = getProperties(this, 'mappingExists', '_id', 'metric');
return !mappingExists && [_id, metric].every(isPresent);
}),
/**
* Calculates the params object
* to be send with the create call
* @type {Object}
*/
entityParams: computed(
'selectedMappingType',
'metricUrn',
'urn',
function () {
const {
selectedMappingType: entityType,
metricUrn,
urn
} = getProperties(
this,
'metricUrn',
'selectedMappingType',
'urn'
);
return {
fromURN: metricUrn,
mappingType: `METRIC_TO_${entityType.toUpperCase()}`,
score: '1.0',
toURN: urn
};
}
),
/**
* Restartable Ember concurrency task that triggers the autocomplete behavior
* @return {Array}
*/
searchEntitiesTask: task(function* (searchString) {
yield timeout(600);
const entityType = this.get('selectedMappingType');
let url = '';
switch(entityType) {
case 'metric':
url = entityMappingApi.metricAutoCompleteUrl(searchString);
break;
case 'dataset':
case 'service':
return this.get(`${entityType}s`).filter(item => item.includes(searchString));
}
/**
* Necessary headers for fetch
*/
const headers = {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Cache': 'no-cache'
},
credentials: 'include'
};
return fetch(url, headers)
.then(checkStatus);
}).restartable(),
async init() {
this._super(...arguments);
const datasets = await fetch(entityMappingApi.getDatasetsUrl).then(checkStatus);
if (this.isDestroyed || this.isDestroying) {
return;
}
set(this, 'datasets', datasets);
},
/**
* Fetches new entities with caching and diff checking
*/
didReceiveAttrs() {
const {
metric,
_cachedMetric,
showEntityMappingModal
} = getProperties(this, 'metric', '_cachedMetric', 'showEntityMappingModal');
if (showEntityMappingModal && metric && !_.isEqual(metric, _cachedMetric)) {
set(this, '_cachedMetric', metric);
this._fetchRelatedEntities();
}
},
/**
* Reset the entity mapping type and selected entity
* @param {String} selectedMappingType - selected mapping type
* @return {undefined}
*/
reset(selectedMappingType = 'dataset') {
this.setProperties({
selectedMappingType,
selectedEntity: '',
_id: ''
});
},
/**
* Build the Urn to Id mapping
* @param {Array} entities - array of entities
* @return {undefined}
*/
buildUrnToId(entities) {
const urnToId = entities.reduce((agg, entity) => {
agg[entity.toURN] = entity.id;
return agg;
}, {});
set(this, 'urnToId', urnToId);
},
/**
* Construct the url string based on the passed entities
* @param {Array} entities - array of entities
* @return {String}
*/
makeUrlString(entities) {
const urnStrings = entities
.map((entity) => `${entity.toURN}`)
.join(',');
if (urnStrings.length) {
return entityMappingApi.get | {
return `${this.get('urnPrefix')}${this.get('_id')}`;
} | identifier_body |
edittime.js | function Ge |
{
return {
"name": "Replacer",
"id": "Rex_Replacer",
"description": "Replace instancne by fade-out itself, and create the target instance then fade-in it.",
"author": "Rex.Rainbow",
"help url": "https://dl.dropbox.com/u/5779181/C2Repo/rex_replacer.html",
"category": "Rex - Movement - opacity",
"flags": bf_onlyone
};
};
//////////////////////////////////////////////////////////////
// Conditions
AddCondition(1, cf_trigger, "On fade-out started", "Fade out", "On {my} fade-out started",
"Triggered when fade-out started", "OnFadeOutStart");
AddCondition(2, cf_trigger, "On fade-out finished", "Fade out", "On {my} fade-out finished",
"Triggered when fade-out finished", "OnFadeOutFinish");
AddCondition(3, cf_trigger, "On fade-in started", "Fade in", "On {my} fade-in started",
"Triggered when fade-out started", "OnFadeInStart");
AddCondition(4, cf_trigger, "On fade-in finished", "Fade in", "On {my} fade-in finished",
"Triggered when fade-in finished", "OnFadeInFinish");
AddCondition(5, 0, "Is fade-out", "Fade out", "Is {my} fade-out",
"Return true if instance is in fade-out stage", "IsFadeOut");
AddCondition(6, 0, "Is fade-in", "Fade in", "Is {my} fade-in",
"Return true if instance is in fade-in stage", "IsFadeIn");
AddCondition(7, 0, "Is idle", "Idle", "Is {my} idle",
"Return true if instance is in idle stage", "IsIdle");
//////////////////////////////////////////////////////////////
// Actions
AddObjectParam("Target", "Target type of replacing instance.");
AddAction(1, 0, "Replace instance", "Replace",
"{my} Replace to {0}","Replace instance.", "ReplaceInst");
AddStringParam("Target", "Target type in nickname of replacing instance.", '""');
AddAction(2, 0, "Replace instance to nickname type", "Replace",
"Replace {my} to nickname: <i>{0}</i>","Replace instance to nickname type.", "ReplaceInst");
AddNumberParam("Duration", "Duration of fade-out or fade in, in seconds.");
AddAction(3, 0, "Set duration", "Configure", "Set {my} fade duration to <i>{0}</i>", "Set the object's fade duration.", "SetDuration");
//////////////////////////////////////////////////////////////
// Expressions
AddExpression(1, ef_return_number, "Get UID of replacing instance", "UID", "ReplacingInstUID",
"The UID of replacing instanc, return -1 if the replacing does not start.");
AddExpression(2, ef_return_number, "Get UID of replacing instance", "UID", "ReplacingInstUID",
"The UID of replacing instanc, return -1 if the replacing does not start.");
ACESDone();
// Property grid properties for this plugin
var property_list = [
new cr.Property(ept_float, "Fade duration", 1, "Duration of fade-out or fade-in, in seconds."),
];
// Called by IDE when a new behavior type is to be created
function CreateIDEBehaviorType()
{
return new IDEBehaviorType();
}
// Class representing a behavior type in the IDE
function IDEBehaviorType()
{
assert2(this instanceof arguments.callee, "Constructor called as a function");
}
// Called by IDE when a new behavior instance of this type is to be created
IDEBehaviorType.prototype.CreateInstance = function(instance)
{
return new IDEInstance(instance, this);
}
// Class representing an individual instance of an object in the IDE
function IDEInstance(instance, type)
{
assert2(this instanceof arguments.callee, "Constructor called as a function");
// Save the constructor parameters
this.instance = instance;
this.type = type;
// Set the default property values from the property table
this.properties = {};
for (var i = 0; i < property_list.length; i++)
this.properties[property_list[i].name] = property_list[i].initial_value;
}
// Called by the IDE after all initialization on this instance has been completed
IDEInstance.prototype.OnCreate = function()
{
}
// Called by the IDE after a property has been changed
IDEInstance.prototype.OnPropertyChanged = function(property_name)
{
// Clamp values
if (this.properties["Fade duration"] < 0)
this.properties["Fade duration"] = 0;
}
| tBehaviorSettings() | identifier_name |
edittime.js | function GetBehaviorSettings()
{
return {
"name": "Replacer",
"id": "Rex_Replacer",
"description": "Replace instancne by fade-out itself, and create the target instance then fade-in it.",
"author": "Rex.Rainbow",
"help url": "https://dl.dropbox.com/u/5779181/C2Repo/rex_replacer.html",
"category": "Rex - Movement - opacity",
"flags": bf_onlyone
};
};
//////////////////////////////////////////////////////////////
// Conditions
AddCondition(1, cf_trigger, "On fade-out started", "Fade out", "On {my} fade-out started",
"Triggered when fade-out started", "OnFadeOutStart");
AddCondition(2, cf_trigger, "On fade-out finished", "Fade out", "On {my} fade-out finished",
"Triggered when fade-out finished", "OnFadeOutFinish");
AddCondition(3, cf_trigger, "On fade-in started", "Fade in", "On {my} fade-in started",
"Triggered when fade-out started", "OnFadeInStart");
AddCondition(4, cf_trigger, "On fade-in finished", "Fade in", "On {my} fade-in finished",
"Triggered when fade-in finished", "OnFadeInFinish");
AddCondition(5, 0, "Is fade-out", "Fade out", "Is {my} fade-out",
"Return true if instance is in fade-out stage", "IsFadeOut");
AddCondition(6, 0, "Is fade-in", "Fade in", "Is {my} fade-in",
"Return true if instance is in fade-in stage", "IsFadeIn");
AddCondition(7, 0, "Is idle", "Idle", "Is {my} idle",
"Return true if instance is in idle stage", "IsIdle");
//////////////////////////////////////////////////////////////
// Actions
AddObjectParam("Target", "Target type of replacing instance.");
AddAction(1, 0, "Replace instance", "Replace",
"{my} Replace to {0}","Replace instance.", "ReplaceInst");
AddStringParam("Target", "Target type in nickname of replacing instance.", '""');
AddAction(2, 0, "Replace instance to nickname type", "Replace",
"Replace {my} to nickname: <i>{0}</i>","Replace instance to nickname type.", "ReplaceInst");
AddNumberParam("Duration", "Duration of fade-out or fade in, in seconds.");
AddAction(3, 0, "Set duration", "Configure", "Set {my} fade duration to <i>{0}</i>", "Set the object's fade duration.", "SetDuration");
//////////////////////////////////////////////////////////////
// Expressions
AddExpression(1, ef_return_number, "Get UID of replacing instance", "UID", "ReplacingInstUID",
"The UID of replacing instanc, return -1 if the replacing does not start.");
AddExpression(2, ef_return_number, "Get UID of replacing instance", "UID", "ReplacingInstUID",
"The UID of replacing instanc, return -1 if the replacing does not start.");
ACESDone();
// Property grid properties for this plugin
var property_list = [
new cr.Property(ept_float, "Fade duration", 1, "Duration of fade-out or fade-in, in seconds."),
];
// Called by IDE when a new behavior type is to be created
function CreateIDEBehaviorType()
{
return new IDEBehaviorType();
}
// Class representing a behavior type in the IDE
function IDEBehaviorType()
{
assert2(this instanceof arguments.callee, "Constructor called as a function");
}
// Called by IDE when a new behavior instance of this type is to be created
IDEBehaviorType.prototype.CreateInstance = function(instance)
{
return new IDEInstance(instance, this);
}
// Class representing an individual instance of an object in the IDE
function IDEInstance(instance, type)
{
assert2(this instanceof arguments.callee, "Constructor called as a function");
// Save the constructor parameters
this.instance = instance;
this.type = type;
// Set the default property values from the property table
this.properties = {};
for (var i = 0; i < property_list.length; i++)
this.properties[property_list[i].name] = property_list[i].initial_value;
}
// Called by the IDE after all initialization on this instance has been completed
IDEInstance.prototype.OnCreate = function()
{
}
| // Clamp values
if (this.properties["Fade duration"] < 0)
this.properties["Fade duration"] = 0;
} | // Called by the IDE after a property has been changed
IDEInstance.prototype.OnPropertyChanged = function(property_name)
{ | random_line_split |
edittime.js | function GetBehaviorSettings()
{
|
//////////////////////////////////////////////////////////////
// Conditions
AddCondition(1, cf_trigger, "On fade-out started", "Fade out", "On {my} fade-out started",
"Triggered when fade-out started", "OnFadeOutStart");
AddCondition(2, cf_trigger, "On fade-out finished", "Fade out", "On {my} fade-out finished",
"Triggered when fade-out finished", "OnFadeOutFinish");
AddCondition(3, cf_trigger, "On fade-in started", "Fade in", "On {my} fade-in started",
"Triggered when fade-out started", "OnFadeInStart");
AddCondition(4, cf_trigger, "On fade-in finished", "Fade in", "On {my} fade-in finished",
"Triggered when fade-in finished", "OnFadeInFinish");
AddCondition(5, 0, "Is fade-out", "Fade out", "Is {my} fade-out",
"Return true if instance is in fade-out stage", "IsFadeOut");
AddCondition(6, 0, "Is fade-in", "Fade in", "Is {my} fade-in",
"Return true if instance is in fade-in stage", "IsFadeIn");
AddCondition(7, 0, "Is idle", "Idle", "Is {my} idle",
"Return true if instance is in idle stage", "IsIdle");
//////////////////////////////////////////////////////////////
// Actions
AddObjectParam("Target", "Target type of replacing instance.");
AddAction(1, 0, "Replace instance", "Replace",
"{my} Replace to {0}","Replace instance.", "ReplaceInst");
AddStringParam("Target", "Target type in nickname of replacing instance.", '""');
AddAction(2, 0, "Replace instance to nickname type", "Replace",
"Replace {my} to nickname: <i>{0}</i>","Replace instance to nickname type.", "ReplaceInst");
AddNumberParam("Duration", "Duration of fade-out or fade in, in seconds.");
AddAction(3, 0, "Set duration", "Configure", "Set {my} fade duration to <i>{0}</i>", "Set the object's fade duration.", "SetDuration");
//////////////////////////////////////////////////////////////
// Expressions
AddExpression(1, ef_return_number, "Get UID of replacing instance", "UID", "ReplacingInstUID",
"The UID of replacing instanc, return -1 if the replacing does not start.");
AddExpression(2, ef_return_number, "Get UID of replacing instance", "UID", "ReplacingInstUID",
"The UID of replacing instanc, return -1 if the replacing does not start.");
ACESDone();
// Property grid properties for this plugin
var property_list = [
new cr.Property(ept_float, "Fade duration", 1, "Duration of fade-out or fade-in, in seconds."),
];
// Called by IDE when a new behavior type is to be created
function CreateIDEBehaviorType()
{
return new IDEBehaviorType();
}
// Class representing a behavior type in the IDE
function IDEBehaviorType()
{
assert2(this instanceof arguments.callee, "Constructor called as a function");
}
// Called by IDE when a new behavior instance of this type is to be created
IDEBehaviorType.prototype.CreateInstance = function(instance)
{
return new IDEInstance(instance, this);
}
// Class representing an individual instance of an object in the IDE
function IDEInstance(instance, type)
{
assert2(this instanceof arguments.callee, "Constructor called as a function");
// Save the constructor parameters
this.instance = instance;
this.type = type;
// Set the default property values from the property table
this.properties = {};
for (var i = 0; i < property_list.length; i++)
this.properties[property_list[i].name] = property_list[i].initial_value;
}
// Called by the IDE after all initialization on this instance has been completed
IDEInstance.prototype.OnCreate = function()
{
}
// Called by the IDE after a property has been changed
IDEInstance.prototype.OnPropertyChanged = function(property_name)
{
// Clamp values
if (this.properties["Fade duration"] < 0)
this.properties["Fade duration"] = 0;
}
| return {
"name": "Replacer",
"id": "Rex_Replacer",
"description": "Replace instancne by fade-out itself, and create the target instance then fade-in it.",
"author": "Rex.Rainbow",
"help url": "https://dl.dropbox.com/u/5779181/C2Repo/rex_replacer.html",
"category": "Rex - Movement - opacity",
"flags": bf_onlyone
};
};
| identifier_body |
PRESUBMIT.py | * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Top-level presubmit script for V8.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl.
"""
import sys
_EXCLUDED_PATHS = (
r"^test[\\\/].*",
r"^testing[\\\/].*",
r"^third_party[\\\/].*",
r"^tools[\\\/].*",
)
# Regular expression that matches code only used for test binaries
# (best effort).
_TEST_CODE_EXCLUDED_PATHS = (
r'.+-unittest\.cc',
# Has a method VisitForTest().
r'src[\\\/]compiler[\\\/]ast-graph-builder\.cc',
# Test extension.
r'src[\\\/]extensions[\\\/]gc-extension\.cc',
)
_TEST_ONLY_WARNING = (
'You might be calling functions intended only for testing from\n'
'production code. It is OK to ignore this warning if you know what\n'
'you are doing, as the heuristics used to detect the situation are\n'
'not perfect. The commit queue will not block on this warning.')
def _V8PresubmitChecks(input_api, output_api):
"""Runs the V8 presubmit checks."""
import sys
sys.path.append(input_api.os_path.join(
input_api.PresubmitLocalPath(), 'tools'))
from presubmit import CppLintProcessor
from presubmit import SourceProcessor
from presubmit import CheckRuntimeVsNativesNameClashes
from presubmit import CheckExternalReferenceRegistration
from presubmit import CheckAuthorizedAuthor
results = []
if not CppLintProcessor().Run(input_api.PresubmitLocalPath()):
results.append(output_api.PresubmitError("C++ lint check failed"))
if not SourceProcessor().Run(input_api.PresubmitLocalPath()):
results.append(output_api.PresubmitError(
"Copyright header, trailing whitespaces and two empty lines " \
"between declarations check failed"))
if not CheckRuntimeVsNativesNameClashes(input_api.PresubmitLocalPath()):
results.append(output_api.PresubmitError(
"Runtime/natives name clash check failed"))
if not CheckExternalReferenceRegistration(input_api.PresubmitLocalPath()):
results.append(output_api.PresubmitError(
"External references registration check failed"))
results.extend(CheckAuthorizedAuthor(input_api, output_api))
return results
def _CheckUnwantedDependencies(input_api, output_api):
| if not CppChecker.IsCppFile(f.LocalPath()):
continue
changed_lines = [line for line_num, line in f.ChangedContents()]
added_includes.append([f.LocalPath(), changed_lines])
deps_checker = checkdeps.DepsChecker(input_api.PresubmitLocalPath())
error_descriptions = []
warning_descriptions = []
for path, rule_type, rule_description in deps_checker.CheckAddedCppIncludes(
added_includes):
description_with_path = '%s\n %s' % (path, rule_description)
if rule_type == Rule.DISALLOW:
error_descriptions.append(description_with_path)
else:
warning_descriptions.append(description_with_path)
results = []
if error_descriptions:
results.append(output_api.PresubmitError(
'You added one or more #includes that violate checkdeps rules.',
error_descriptions))
if warning_descriptions:
results.append(output_api.PresubmitPromptOrNotify(
'You added one or more #includes of files that are temporarily\n'
'allowed but being removed. Can you avoid introducing the\n'
'#include? See relevant DEPS file(s) for details and contacts.',
warning_descriptions))
return results
def _CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api):
"""Attempts to prevent use of functions intended only for testing in
non-testing code. For now this is just a best-effort implementation
that ignores header files and may have some false positives. A
better implementation would probably need a proper C++ parser.
"""
# We only scan .cc files, as the declaration of for-testing functions in
# header files are hard to distinguish from calls to such functions without a
# proper C++ parser.
file_inclusion_pattern = r'.+\.cc'
base_function_pattern = r'[ :]test::[^\s]+|ForTest(ing)?|for_test(ing)?'
inclusion_pattern = input_api.re.compile(r'(%s)\s*\(' % base_function_pattern)
comment_pattern = input_api.re.compile(r'//.*(%s)' % base_function_pattern)
exclusion_pattern = input_api.re.compile(
r'::[A-Za-z0-9_]+(%s)|(%s)[^;]+\{' % (
base_function_pattern, base_function_pattern))
def FilterFile(affected_file):
black_list = (_EXCLUDED_PATHS +
_TEST_CODE_EXCLUDED_PATHS +
input_api.DEFAULT_BLACK_LIST)
return input_api.FilterSourceFile(
affected_file,
white_list=(file_inclusion_pattern, ),
black_list=black_list)
problems = []
for f in input_api.AffectedSourceFiles(FilterFile):
local_path = f.LocalPath()
for line_number, line in f.ChangedContents():
if (inclusion_pattern.search(line) and
not comment_pattern.search(line) and
not exclusion_pattern.search(line)):
problems.append(
'%s:%d\n %s' % (local_path, line_number, line.strip()))
if problems:
return [output_api.PresubmitPromptOrNotify(_TEST_ONLY_WARNING, problems)]
else:
return []
def _CommonChecks(input_api, output_api):
"""Checks common to both upload and commit."""
results = []
results.extend(input_api.canned_checks.CheckOwners(
input_api, output_api, source_file_filter=None))
results.extend(input_api.canned_checks.CheckPatchFormatted(
input_api, output_api))
results.extend(_V8PresubmitChecks(input_api, output_api))
results.extend(_CheckUnwantedDependencies(input_api, output_api))
results.extend(
_CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api))
return results
def _SkipTreeCheck(input_api, output_api):
"""Check the env var whether we want to skip tree check.
Only skip if include/v8-version.h has been updated."""
src_version = 'include/v8-version.h'
FilterFile = lambda file: file.LocalPath() == src_version
if not input_api.AffectedSourceFiles(
lambda file: file.LocalPath() == src_version):
return False
return input_api.environ.get('PRESUBMIT_TREE_CHECK') == 'skip'
def _CheckChangeLogFlag(input_api, output_api):
"""Checks usage of LOG= flag in the commit message."""
results = []
if input_api.change.BUG and not 'LOG' in input_api.change.tags:
results.append(output_api.PresubmitError(
'An issue reference (BUG=) requires a change log flag (LOG=). '
'Use LOG=Y for including this commit message in the change log. '
'Use LOG=N or leave blank otherwise.'))
return results
def CheckChangeOnUpload(input_api, output_api):
results = []
results.extend(_CommonChecks(input_api, output_api))
results.extend(_CheckChangeLogFlag(input_api, output_api))
return results
def CheckChangeOnCommit(input_api, output_api):
results = []
results.extend(_CommonChecks(input_api, output_api))
results.extend(_CheckChangeLogFlag(input_api, output_api))
results.extend(input | """Runs checkdeps on #include statements added in this
change. Breaking - rules is an error, breaking ! rules is a
warning.
"""
# We need to wait until we have an input_api object and use this
# roundabout construct to import checkdeps because this file is
# eval-ed and thus doesn't have __file__.
original_sys_path = sys.path
try:
sys.path = sys.path + [input_api.os_path.join(
input_api.PresubmitLocalPath(), 'buildtools', 'checkdeps')]
import checkdeps
from cpp_checker import CppChecker
from rules import Rule
finally:
# Restore sys.path to what it was before.
sys.path = original_sys_path
added_includes = []
for f in input_api.AffectedFiles(): | identifier_body |
PRESUBMIT.py | * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Top-level presubmit script for V8.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl.
"""
import sys
_EXCLUDED_PATHS = (
r"^test[\\\/].*",
r"^testing[\\\/].*",
r"^third_party[\\\/].*",
r"^tools[\\\/].*",
)
# Regular expression that matches code only used for test binaries
# (best effort).
_TEST_CODE_EXCLUDED_PATHS = (
r'.+-unittest\.cc',
# Has a method VisitForTest().
r'src[\\\/]compiler[\\\/]ast-graph-builder\.cc',
# Test extension.
r'src[\\\/]extensions[\\\/]gc-extension\.cc',
)
_TEST_ONLY_WARNING = (
'You might be calling functions intended only for testing from\n'
'production code. It is OK to ignore this warning if you know what\n'
'you are doing, as the heuristics used to detect the situation are\n'
'not perfect. The commit queue will not block on this warning.')
def _V8PresubmitChecks(input_api, output_api):
"""Runs the V8 presubmit checks."""
import sys
sys.path.append(input_api.os_path.join(
input_api.PresubmitLocalPath(), 'tools'))
from presubmit import CppLintProcessor
from presubmit import SourceProcessor
from presubmit import CheckRuntimeVsNativesNameClashes
from presubmit import CheckExternalReferenceRegistration
from presubmit import CheckAuthorizedAuthor
results = []
if not CppLintProcessor().Run(input_api.PresubmitLocalPath()):
results.append(output_api.PresubmitError("C++ lint check failed"))
if not SourceProcessor().Run(input_api.PresubmitLocalPath()):
results.append(output_api.PresubmitError(
"Copyright header, trailing whitespaces and two empty lines " \
"between declarations check failed"))
if not CheckRuntimeVsNativesNameClashes(input_api.PresubmitLocalPath()):
results.append(output_api.PresubmitError(
"Runtime/natives name clash check failed"))
if not CheckExternalReferenceRegistration(input_api.PresubmitLocalPath()):
results.append(output_api.PresubmitError(
"External references registration check failed"))
results.extend(CheckAuthorizedAuthor(input_api, output_api))
return results
def _CheckUnwantedDependencies(input_api, output_api):
"""Runs checkdeps on #include statements added in this
change. Breaking - rules is an error, breaking ! rules is a
warning.
"""
# We need to wait until we have an input_api object and use this
# roundabout construct to import checkdeps because this file is
# eval-ed and thus doesn't have __file__.
original_sys_path = sys.path
try:
sys.path = sys.path + [input_api.os_path.join(
input_api.PresubmitLocalPath(), 'buildtools', 'checkdeps')]
import checkdeps
from cpp_checker import CppChecker
from rules import Rule
finally:
# Restore sys.path to what it was before.
sys.path = original_sys_path
added_includes = []
for f in input_api.AffectedFiles():
if not CppChecker.IsCppFile(f.LocalPath()):
continue
changed_lines = [line for line_num, line in f.ChangedContents()]
added_includes.append([f.LocalPath(), changed_lines])
deps_checker = checkdeps.DepsChecker(input_api.PresubmitLocalPath())
error_descriptions = []
warning_descriptions = []
for path, rule_type, rule_description in deps_checker.CheckAddedCppIncludes(
added_includes):
description_with_path = '%s\n %s' % (path, rule_description)
if rule_type == Rule.DISALLOW:
error_descriptions.append(description_with_path)
else:
warning_descriptions.append(description_with_path)
results = []
if error_descriptions:
results.append(output_api.PresubmitError(
'You added one or more #includes that violate checkdeps rules.',
error_descriptions))
if warning_descriptions:
results.append(output_api.PresubmitPromptOrNotify(
'You added one or more #includes of files that are temporarily\n'
'allowed but being removed. Can you avoid introducing the\n'
'#include? See relevant DEPS file(s) for details and contacts.',
warning_descriptions))
return results
def | (input_api, output_api):
"""Attempts to prevent use of functions intended only for testing in
non-testing code. For now this is just a best-effort implementation
that ignores header files and may have some false positives. A
better implementation would probably need a proper C++ parser.
"""
# We only scan .cc files, as the declaration of for-testing functions in
# header files are hard to distinguish from calls to such functions without a
# proper C++ parser.
file_inclusion_pattern = r'.+\.cc'
base_function_pattern = r'[ :]test::[^\s]+|ForTest(ing)?|for_test(ing)?'
inclusion_pattern = input_api.re.compile(r'(%s)\s*\(' % base_function_pattern)
comment_pattern = input_api.re.compile(r'//.*(%s)' % base_function_pattern)
exclusion_pattern = input_api.re.compile(
r'::[A-Za-z0-9_]+(%s)|(%s)[^;]+\{' % (
base_function_pattern, base_function_pattern))
def FilterFile(affected_file):
black_list = (_EXCLUDED_PATHS +
_TEST_CODE_EXCLUDED_PATHS +
input_api.DEFAULT_BLACK_LIST)
return input_api.FilterSourceFile(
affected_file,
white_list=(file_inclusion_pattern, ),
black_list=black_list)
problems = []
for f in input_api.AffectedSourceFiles(FilterFile):
local_path = f.LocalPath()
for line_number, line in f.ChangedContents():
if (inclusion_pattern.search(line) and
not comment_pattern.search(line) and
not exclusion_pattern.search(line)):
problems.append(
'%s:%d\n %s' % (local_path, line_number, line.strip()))
if problems:
return [output_api.PresubmitPromptOrNotify(_TEST_ONLY_WARNING, problems)]
else:
return []
def _CommonChecks(input_api, output_api):
"""Checks common to both upload and commit."""
results = []
results.extend(input_api.canned_checks.CheckOwners(
input_api, output_api, source_file_filter=None))
results.extend(input_api.canned_checks.CheckPatchFormatted(
input_api, output_api))
results.extend(_V8PresubmitChecks(input_api, output_api))
results.extend(_CheckUnwantedDependencies(input_api, output_api))
results.extend(
_CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api))
return results
def _SkipTreeCheck(input_api, output_api):
"""Check the env var whether we want to skip tree check.
Only skip if include/v8-version.h has been updated."""
src_version = 'include/v8-version.h'
FilterFile = lambda file: file.LocalPath() == src_version
if not input_api.AffectedSourceFiles(
lambda file: file.LocalPath() == src_version):
return False
return input_api.environ.get('PRESUBMIT_TREE_CHECK') == 'skip'
def _CheckChangeLogFlag(input_api, output_api):
"""Checks usage of LOG= flag in the commit message."""
results = []
if input_api.change.BUG and not 'LOG' in input_api.change.tags:
results.append(output_api.PresubmitError(
'An issue reference (BUG=) requires a change log flag (LOG=). '
'Use LOG=Y for including this commit message in the change log. '
'Use LOG=N or leave blank otherwise.'))
return results
def CheckChangeOnUpload(input_api, output_api):
results = []
results.extend(_CommonChecks(input_api, output_api))
results.extend(_CheckChangeLogFlag(input_api, output_api))
return results
def CheckChangeOnCommit(input_api, output_api):
results = []
results.extend(_CommonChecks(input_api, output_api))
results.extend(_CheckChangeLogFlag(input_api, output_api))
results.extend(input | _CheckNoProductionCodeUsingTestOnlyFunctions | identifier_name |
PRESUBMIT.py | * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Top-level presubmit script for V8.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl.
"""
import sys
_EXCLUDED_PATHS = (
r"^test[\\\/].*",
r"^testing[\\\/].*",
r"^third_party[\\\/].*",
r"^tools[\\\/].*",
)
# Regular expression that matches code only used for test binaries
# (best effort).
_TEST_CODE_EXCLUDED_PATHS = (
r'.+-unittest\.cc',
# Has a method VisitForTest().
r'src[\\\/]compiler[\\\/]ast-graph-builder\.cc',
# Test extension.
r'src[\\\/]extensions[\\\/]gc-extension\.cc',
)
_TEST_ONLY_WARNING = (
'You might be calling functions intended only for testing from\n'
'production code. It is OK to ignore this warning if you know what\n'
'you are doing, as the heuristics used to detect the situation are\n'
'not perfect. The commit queue will not block on this warning.')
def _V8PresubmitChecks(input_api, output_api):
"""Runs the V8 presubmit checks."""
import sys
sys.path.append(input_api.os_path.join(
input_api.PresubmitLocalPath(), 'tools')) | from presubmit import CppLintProcessor
from presubmit import SourceProcessor
from presubmit import CheckRuntimeVsNativesNameClashes
from presubmit import CheckExternalReferenceRegistration
from presubmit import CheckAuthorizedAuthor
results = []
if not CppLintProcessor().Run(input_api.PresubmitLocalPath()):
results.append(output_api.PresubmitError("C++ lint check failed"))
if not SourceProcessor().Run(input_api.PresubmitLocalPath()):
results.append(output_api.PresubmitError(
"Copyright header, trailing whitespaces and two empty lines " \
"between declarations check failed"))
if not CheckRuntimeVsNativesNameClashes(input_api.PresubmitLocalPath()):
results.append(output_api.PresubmitError(
"Runtime/natives name clash check failed"))
if not CheckExternalReferenceRegistration(input_api.PresubmitLocalPath()):
results.append(output_api.PresubmitError(
"External references registration check failed"))
results.extend(CheckAuthorizedAuthor(input_api, output_api))
return results
def _CheckUnwantedDependencies(input_api, output_api):
"""Runs checkdeps on #include statements added in this
change. Breaking - rules is an error, breaking ! rules is a
warning.
"""
# We need to wait until we have an input_api object and use this
# roundabout construct to import checkdeps because this file is
# eval-ed and thus doesn't have __file__.
original_sys_path = sys.path
try:
sys.path = sys.path + [input_api.os_path.join(
input_api.PresubmitLocalPath(), 'buildtools', 'checkdeps')]
import checkdeps
from cpp_checker import CppChecker
from rules import Rule
finally:
# Restore sys.path to what it was before.
sys.path = original_sys_path
added_includes = []
for f in input_api.AffectedFiles():
if not CppChecker.IsCppFile(f.LocalPath()):
continue
changed_lines = [line for line_num, line in f.ChangedContents()]
added_includes.append([f.LocalPath(), changed_lines])
deps_checker = checkdeps.DepsChecker(input_api.PresubmitLocalPath())
error_descriptions = []
warning_descriptions = []
for path, rule_type, rule_description in deps_checker.CheckAddedCppIncludes(
added_includes):
description_with_path = '%s\n %s' % (path, rule_description)
if rule_type == Rule.DISALLOW:
error_descriptions.append(description_with_path)
else:
warning_descriptions.append(description_with_path)
results = []
if error_descriptions:
results.append(output_api.PresubmitError(
'You added one or more #includes that violate checkdeps rules.',
error_descriptions))
if warning_descriptions:
results.append(output_api.PresubmitPromptOrNotify(
'You added one or more #includes of files that are temporarily\n'
'allowed but being removed. Can you avoid introducing the\n'
'#include? See relevant DEPS file(s) for details and contacts.',
warning_descriptions))
return results
def _CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api):
"""Attempts to prevent use of functions intended only for testing in
non-testing code. For now this is just a best-effort implementation
that ignores header files and may have some false positives. A
better implementation would probably need a proper C++ parser.
"""
# We only scan .cc files, as the declaration of for-testing functions in
# header files are hard to distinguish from calls to such functions without a
# proper C++ parser.
file_inclusion_pattern = r'.+\.cc'
base_function_pattern = r'[ :]test::[^\s]+|ForTest(ing)?|for_test(ing)?'
inclusion_pattern = input_api.re.compile(r'(%s)\s*\(' % base_function_pattern)
comment_pattern = input_api.re.compile(r'//.*(%s)' % base_function_pattern)
exclusion_pattern = input_api.re.compile(
r'::[A-Za-z0-9_]+(%s)|(%s)[^;]+\{' % (
base_function_pattern, base_function_pattern))
def FilterFile(affected_file):
black_list = (_EXCLUDED_PATHS +
_TEST_CODE_EXCLUDED_PATHS +
input_api.DEFAULT_BLACK_LIST)
return input_api.FilterSourceFile(
affected_file,
white_list=(file_inclusion_pattern, ),
black_list=black_list)
problems = []
for f in input_api.AffectedSourceFiles(FilterFile):
local_path = f.LocalPath()
for line_number, line in f.ChangedContents():
if (inclusion_pattern.search(line) and
not comment_pattern.search(line) and
not exclusion_pattern.search(line)):
problems.append(
'%s:%d\n %s' % (local_path, line_number, line.strip()))
if problems:
return [output_api.PresubmitPromptOrNotify(_TEST_ONLY_WARNING, problems)]
else:
return []
def _CommonChecks(input_api, output_api):
"""Checks common to both upload and commit."""
results = []
results.extend(input_api.canned_checks.CheckOwners(
input_api, output_api, source_file_filter=None))
results.extend(input_api.canned_checks.CheckPatchFormatted(
input_api, output_api))
results.extend(_V8PresubmitChecks(input_api, output_api))
results.extend(_CheckUnwantedDependencies(input_api, output_api))
results.extend(
_CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api))
return results
def _SkipTreeCheck(input_api, output_api):
"""Check the env var whether we want to skip tree check.
Only skip if include/v8-version.h has been updated."""
src_version = 'include/v8-version.h'
FilterFile = lambda file: file.LocalPath() == src_version
if not input_api.AffectedSourceFiles(
lambda file: file.LocalPath() == src_version):
return False
return input_api.environ.get('PRESUBMIT_TREE_CHECK') == 'skip'
def _CheckChangeLogFlag(input_api, output_api):
"""Checks usage of LOG= flag in the commit message."""
results = []
if input_api.change.BUG and not 'LOG' in input_api.change.tags:
results.append(output_api.PresubmitError(
'An issue reference (BUG=) requires a change log flag (LOG=). '
'Use LOG=Y for including this commit message in the change log. '
'Use LOG=N or leave blank otherwise.'))
return results
def CheckChangeOnUpload(input_api, output_api):
results = []
results.extend(_CommonChecks(input_api, output_api))
results.extend(_CheckChangeLogFlag(input_api, output_api))
return results
def CheckChangeOnCommit(input_api, output_api):
results = []
results.extend(_CommonChecks(input_api, output_api))
results.extend(_CheckChangeLogFlag(input_api, output_api))
results.extend(input | random_line_split |
|
PRESUBMIT.py | * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Top-level presubmit script for V8.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl.
"""
import sys
_EXCLUDED_PATHS = (
r"^test[\\\/].*",
r"^testing[\\\/].*",
r"^third_party[\\\/].*",
r"^tools[\\\/].*",
)
# Regular expression that matches code only used for test binaries
# (best effort).
_TEST_CODE_EXCLUDED_PATHS = (
r'.+-unittest\.cc',
# Has a method VisitForTest().
r'src[\\\/]compiler[\\\/]ast-graph-builder\.cc',
# Test extension.
r'src[\\\/]extensions[\\\/]gc-extension\.cc',
)
_TEST_ONLY_WARNING = (
'You might be calling functions intended only for testing from\n'
'production code. It is OK to ignore this warning if you know what\n'
'you are doing, as the heuristics used to detect the situation are\n'
'not perfect. The commit queue will not block on this warning.')
def _V8PresubmitChecks(input_api, output_api):
"""Runs the V8 presubmit checks."""
import sys
sys.path.append(input_api.os_path.join(
input_api.PresubmitLocalPath(), 'tools'))
from presubmit import CppLintProcessor
from presubmit import SourceProcessor
from presubmit import CheckRuntimeVsNativesNameClashes
from presubmit import CheckExternalReferenceRegistration
from presubmit import CheckAuthorizedAuthor
results = []
if not CppLintProcessor().Run(input_api.PresubmitLocalPath()):
results.append(output_api.PresubmitError("C++ lint check failed"))
if not SourceProcessor().Run(input_api.PresubmitLocalPath()):
results.append(output_api.PresubmitError(
"Copyright header, trailing whitespaces and two empty lines " \
"between declarations check failed"))
if not CheckRuntimeVsNativesNameClashes(input_api.PresubmitLocalPath()):
|
if not CheckExternalReferenceRegistration(input_api.PresubmitLocalPath()):
results.append(output_api.PresubmitError(
"External references registration check failed"))
results.extend(CheckAuthorizedAuthor(input_api, output_api))
return results
def _CheckUnwantedDependencies(input_api, output_api):
"""Runs checkdeps on #include statements added in this
change. Breaking - rules is an error, breaking ! rules is a
warning.
"""
# We need to wait until we have an input_api object and use this
# roundabout construct to import checkdeps because this file is
# eval-ed and thus doesn't have __file__.
original_sys_path = sys.path
try:
sys.path = sys.path + [input_api.os_path.join(
input_api.PresubmitLocalPath(), 'buildtools', 'checkdeps')]
import checkdeps
from cpp_checker import CppChecker
from rules import Rule
finally:
# Restore sys.path to what it was before.
sys.path = original_sys_path
added_includes = []
for f in input_api.AffectedFiles():
if not CppChecker.IsCppFile(f.LocalPath()):
continue
changed_lines = [line for line_num, line in f.ChangedContents()]
added_includes.append([f.LocalPath(), changed_lines])
deps_checker = checkdeps.DepsChecker(input_api.PresubmitLocalPath())
error_descriptions = []
warning_descriptions = []
for path, rule_type, rule_description in deps_checker.CheckAddedCppIncludes(
added_includes):
description_with_path = '%s\n %s' % (path, rule_description)
if rule_type == Rule.DISALLOW:
error_descriptions.append(description_with_path)
else:
warning_descriptions.append(description_with_path)
results = []
if error_descriptions:
results.append(output_api.PresubmitError(
'You added one or more #includes that violate checkdeps rules.',
error_descriptions))
if warning_descriptions:
results.append(output_api.PresubmitPromptOrNotify(
'You added one or more #includes of files that are temporarily\n'
'allowed but being removed. Can you avoid introducing the\n'
'#include? See relevant DEPS file(s) for details and contacts.',
warning_descriptions))
return results
def _CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api):
"""Attempts to prevent use of functions intended only for testing in
non-testing code. For now this is just a best-effort implementation
that ignores header files and may have some false positives. A
better implementation would probably need a proper C++ parser.
"""
# We only scan .cc files, as the declaration of for-testing functions in
# header files are hard to distinguish from calls to such functions without a
# proper C++ parser.
file_inclusion_pattern = r'.+\.cc'
base_function_pattern = r'[ :]test::[^\s]+|ForTest(ing)?|for_test(ing)?'
inclusion_pattern = input_api.re.compile(r'(%s)\s*\(' % base_function_pattern)
comment_pattern = input_api.re.compile(r'//.*(%s)' % base_function_pattern)
exclusion_pattern = input_api.re.compile(
r'::[A-Za-z0-9_]+(%s)|(%s)[^;]+\{' % (
base_function_pattern, base_function_pattern))
def FilterFile(affected_file):
black_list = (_EXCLUDED_PATHS +
_TEST_CODE_EXCLUDED_PATHS +
input_api.DEFAULT_BLACK_LIST)
return input_api.FilterSourceFile(
affected_file,
white_list=(file_inclusion_pattern, ),
black_list=black_list)
problems = []
for f in input_api.AffectedSourceFiles(FilterFile):
local_path = f.LocalPath()
for line_number, line in f.ChangedContents():
if (inclusion_pattern.search(line) and
not comment_pattern.search(line) and
not exclusion_pattern.search(line)):
problems.append(
'%s:%d\n %s' % (local_path, line_number, line.strip()))
if problems:
return [output_api.PresubmitPromptOrNotify(_TEST_ONLY_WARNING, problems)]
else:
return []
def _CommonChecks(input_api, output_api):
"""Checks common to both upload and commit."""
results = []
results.extend(input_api.canned_checks.CheckOwners(
input_api, output_api, source_file_filter=None))
results.extend(input_api.canned_checks.CheckPatchFormatted(
input_api, output_api))
results.extend(_V8PresubmitChecks(input_api, output_api))
results.extend(_CheckUnwantedDependencies(input_api, output_api))
results.extend(
_CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api))
return results
def _SkipTreeCheck(input_api, output_api):
"""Check the env var whether we want to skip tree check.
Only skip if include/v8-version.h has been updated."""
src_version = 'include/v8-version.h'
FilterFile = lambda file: file.LocalPath() == src_version
if not input_api.AffectedSourceFiles(
lambda file: file.LocalPath() == src_version):
return False
return input_api.environ.get('PRESUBMIT_TREE_CHECK') == 'skip'
def _CheckChangeLogFlag(input_api, output_api):
"""Checks usage of LOG= flag in the commit message."""
results = []
if input_api.change.BUG and not 'LOG' in input_api.change.tags:
results.append(output_api.PresubmitError(
'An issue reference (BUG=) requires a change log flag (LOG=). '
'Use LOG=Y for including this commit message in the change log. '
'Use LOG=N or leave blank otherwise.'))
return results
def CheckChangeOnUpload(input_api, output_api):
results = []
results.extend(_CommonChecks(input_api, output_api))
results.extend(_CheckChangeLogFlag(input_api, output_api))
return results
def CheckChangeOnCommit(input_api, output_api):
results = []
results.extend(_CommonChecks(input_api, output_api))
results.extend(_CheckChangeLogFlag(input_api, output_api))
results.extend | results.append(output_api.PresubmitError(
"Runtime/natives name clash check failed")) | conditional_block |
quotemarkRule.ts | /**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as ts from "typescript";
import * as Lint from "../lint";
enum QuoteMark {
SINGLE_QUOTES,
DOUBLE_QUOTES
}
export class | extends Lint.Rules.AbstractRule {
public static SINGLE_QUOTE_FAILURE = "\" should be '";
public static DOUBLE_QUOTE_FAILURE = "' should be \"";
public isEnabled(): boolean {
if (super.isEnabled()) {
const quoteMarkString = this.getOptions().ruleArguments[0];
return (quoteMarkString === "single" || quoteMarkString === "double");
}
return false;
}
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new QuotemarkWalker(sourceFile, this.getOptions()));
}
}
class QuotemarkWalker extends Lint.RuleWalker {
private quoteMark = QuoteMark.DOUBLE_QUOTES;
private avoidEscape: boolean;
constructor(sourceFile: ts.SourceFile, options: Lint.IOptions) {
super(sourceFile, options);
const ruleArguments = this.getOptions();
const quoteMarkString = ruleArguments[0];
if (quoteMarkString === "single") {
this.quoteMark = QuoteMark.SINGLE_QUOTES;
} else {
this.quoteMark = QuoteMark.DOUBLE_QUOTES;
}
this.avoidEscape = ruleArguments.indexOf("avoid-escape") > 0;
}
public visitStringLiteral(node: ts.StringLiteral) {
const text = node.getText();
const width = node.getWidth();
const position = node.getStart();
const firstCharacter = text.charAt(0);
const lastCharacter = text.charAt(text.length - 1);
const expectedQuoteMark = (this.quoteMark === QuoteMark.SINGLE_QUOTES) ? "'" : "\"";
if (firstCharacter !== expectedQuoteMark || lastCharacter !== expectedQuoteMark) {
// allow the "other" quote mark to be used, but only to avoid having to escape
const includesOtherQuoteMark = text.slice(1, -1).indexOf(expectedQuoteMark) !== -1;
if (!(this.avoidEscape && includesOtherQuoteMark)) {
const failureMessage = (this.quoteMark === QuoteMark.SINGLE_QUOTES)
? Rule.SINGLE_QUOTE_FAILURE
: Rule.DOUBLE_QUOTE_FAILURE;
this.addFailure(this.createFailure(position, width, failureMessage));
}
}
super.visitStringLiteral(node);
}
}
| Rule | identifier_name |
quotemarkRule.ts | /**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as ts from "typescript";
import * as Lint from "../lint";
enum QuoteMark {
SINGLE_QUOTES,
DOUBLE_QUOTES
}
export class Rule extends Lint.Rules.AbstractRule {
public static SINGLE_QUOTE_FAILURE = "\" should be '";
public static DOUBLE_QUOTE_FAILURE = "' should be \"";
public isEnabled(): boolean {
if (super.isEnabled()) {
const quoteMarkString = this.getOptions().ruleArguments[0];
return (quoteMarkString === "single" || quoteMarkString === "double");
}
return false;
}
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new QuotemarkWalker(sourceFile, this.getOptions()));
}
}
| private quoteMark = QuoteMark.DOUBLE_QUOTES;
private avoidEscape: boolean;
constructor(sourceFile: ts.SourceFile, options: Lint.IOptions) {
super(sourceFile, options);
const ruleArguments = this.getOptions();
const quoteMarkString = ruleArguments[0];
if (quoteMarkString === "single") {
this.quoteMark = QuoteMark.SINGLE_QUOTES;
} else {
this.quoteMark = QuoteMark.DOUBLE_QUOTES;
}
this.avoidEscape = ruleArguments.indexOf("avoid-escape") > 0;
}
public visitStringLiteral(node: ts.StringLiteral) {
const text = node.getText();
const width = node.getWidth();
const position = node.getStart();
const firstCharacter = text.charAt(0);
const lastCharacter = text.charAt(text.length - 1);
const expectedQuoteMark = (this.quoteMark === QuoteMark.SINGLE_QUOTES) ? "'" : "\"";
if (firstCharacter !== expectedQuoteMark || lastCharacter !== expectedQuoteMark) {
// allow the "other" quote mark to be used, but only to avoid having to escape
const includesOtherQuoteMark = text.slice(1, -1).indexOf(expectedQuoteMark) !== -1;
if (!(this.avoidEscape && includesOtherQuoteMark)) {
const failureMessage = (this.quoteMark === QuoteMark.SINGLE_QUOTES)
? Rule.SINGLE_QUOTE_FAILURE
: Rule.DOUBLE_QUOTE_FAILURE;
this.addFailure(this.createFailure(position, width, failureMessage));
}
}
super.visitStringLiteral(node);
}
} | class QuotemarkWalker extends Lint.RuleWalker { | random_line_split |
quotemarkRule.ts | /**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as ts from "typescript";
import * as Lint from "../lint";
enum QuoteMark {
SINGLE_QUOTES,
DOUBLE_QUOTES
}
export class Rule extends Lint.Rules.AbstractRule {
public static SINGLE_QUOTE_FAILURE = "\" should be '";
public static DOUBLE_QUOTE_FAILURE = "' should be \"";
public isEnabled(): boolean {
if (super.isEnabled()) {
const quoteMarkString = this.getOptions().ruleArguments[0];
return (quoteMarkString === "single" || quoteMarkString === "double");
}
return false;
}
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new QuotemarkWalker(sourceFile, this.getOptions()));
}
}
class QuotemarkWalker extends Lint.RuleWalker {
private quoteMark = QuoteMark.DOUBLE_QUOTES;
private avoidEscape: boolean;
constructor(sourceFile: ts.SourceFile, options: Lint.IOptions) {
super(sourceFile, options);
const ruleArguments = this.getOptions();
const quoteMarkString = ruleArguments[0];
if (quoteMarkString === "single") {
this.quoteMark = QuoteMark.SINGLE_QUOTES;
} else {
this.quoteMark = QuoteMark.DOUBLE_QUOTES;
}
this.avoidEscape = ruleArguments.indexOf("avoid-escape") > 0;
}
public visitStringLiteral(node: ts.StringLiteral) {
const text = node.getText();
const width = node.getWidth();
const position = node.getStart();
const firstCharacter = text.charAt(0);
const lastCharacter = text.charAt(text.length - 1);
const expectedQuoteMark = (this.quoteMark === QuoteMark.SINGLE_QUOTES) ? "'" : "\"";
if (firstCharacter !== expectedQuoteMark || lastCharacter !== expectedQuoteMark) |
super.visitStringLiteral(node);
}
}
| {
// allow the "other" quote mark to be used, but only to avoid having to escape
const includesOtherQuoteMark = text.slice(1, -1).indexOf(expectedQuoteMark) !== -1;
if (!(this.avoidEscape && includesOtherQuoteMark)) {
const failureMessage = (this.quoteMark === QuoteMark.SINGLE_QUOTES)
? Rule.SINGLE_QUOTE_FAILURE
: Rule.DOUBLE_QUOTE_FAILURE;
this.addFailure(this.createFailure(position, width, failureMessage));
}
} | conditional_block |
max_aggregate_only.py | import numpy as np
from scipy.stats import skew, kurtosis, shapiro, pearsonr, ansari, mood, levene, fligner, bartlett, mannwhitneyu
from scipy.spatial.distance import braycurtis, canberra, chebyshev, cityblock, correlation, cosine, euclidean, hamming, jaccard, kulsinski, matching, russellrao, sqeuclidean
from sklearn.preprocessing import LabelBinarizer
from sklearn.linear_model import Ridge, LinearRegression, LogisticRegression
from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, RandomForestClassifier, GradientBoostingClassifier
from sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import explained_variance_score, mean_absolute_error, mean_squared_error, r2_score, accuracy_score, roc_auc_score, average_precision_score, f1_score, hinge_loss, matthews_corrcoef, precision_score, recall_score, zero_one_loss
from sklearn.metrics.cluster import adjusted_mutual_info_score, adjusted_rand_score, completeness_score, homogeneity_completeness_v_measure, homogeneity_score, mutual_info_score, normalized_mutual_info_score, v_measure_score
from boomlet.utils.aggregators import to_aggregator
from boomlet.metrics import max_error, error_variance, relative_error_variance, gini_loss, categorical_gini_loss
from boomlet.transform.type_conversion import Discretizer
from autocause.feature_functions import *
"""
Functions used to combine a list of features into one coherent one.
Sample use:
1. to convert categorical to numerical, we perform a one hot encoding
2. treat each binary column as a separate numerical feature
3. compute numerical features as usual
4. use each of the following functions to create a new feature
(with the input as the nth feature for each of the columns)
WARNING: these will be used in various locations throughout the code base
and will result in feature size growing at faster than a linear rate
"""
AGGREGATORS = [
to_aggregator("max"),
# to_aggregator("min"),
# to_aggregator("median"),
# to_aggregator("mode"),
# to_aggregator("mean"),
# to_aggregator("sum"),
]
"""
Boolean flags specifying whether or not to perform conversions
"""
CONVERT_TO_NUMERICAL = True
CONVERT_TO_CATEGORICAL = True
"""
Functions that compute a metric on a single 1-D array
"""
UNARY_NUMERICAL_FEATURES = [
normalized_entropy,
skew,
kurtosis,
np.std,
shapiro,
]
UNARY_CATEGORICAL_FEATURES = [
lambda x: len(set(x)), # number of unique
]
"""
Functions that compute a metric on two 1-D arrays
"""
BINARY_NN_FEATURES = [
independent_component,
chi_square,
pearsonr,
correlation_magnitude,
braycurtis,
canberra,
chebyshev,
cityblock,
correlation,
cosine,
euclidean,
hamming,
sqeuclidean,
ansari,
mood,
levene,
fligner,
bartlett,
mannwhitneyu,
]
BINARY_NC_FEATURES = [
]
BINARY_CN_FEATURES = [
categorical_numerical_homogeneity,
bucket_variance, | anova,
dice_,
jaccard,
kulsinski,
matching,
rogerstanimoto_,
russellrao,
sokalmichener_,
sokalsneath_,
yule_,
adjusted_mutual_info_score,
adjusted_rand_score,
completeness_score,
homogeneity_completeness_v_measure,
homogeneity_score,
mutual_info_score,
normalized_mutual_info_score,
v_measure_score,
]
"""
Dictionaries of input type (e.g. B corresponds to pairs where binary
data is the input) to pairs of converter functions and a boolean flag
of whether or not to aggregate over the output of the converter function
converter functions should have the type signature:
converter(X_raw, X_current_type, Y_raw, Y_type)
where X_raw is the data to convert
"""
NUMERICAL_CONVERTERS = dict(
N=lambda x, *args: x, # identity function
B=lambda x, *args: x, # identity function
C=lambda x, *args: LabelBinarizer().fit_transform(x),
)
CATEGORICAL_CONVERTERS = dict(
N=lambda x, *args: Discretizer().fit_transform(x).flatten(),
B=lambda x, *args: x, # identity function
C=lambda x, *args: x, # identity function
)
"""
Whether or not the converters can result in a 2D output. This must be set to True
if any of the respective converts can return a 2D output.
"""
NUMERICAL_CAN_BE_2D = True
CATEGORICAL_CAN_BE_2D = False
"""
Estimators used to provide a fit for a variable
"""
REGRESSION_ESTIMATORS = [
Ridge(),
LinearRegression(),
DecisionTreeRegressor(random_state=0),
RandomForestRegressor(random_state=0),
GradientBoostingRegressor(subsample=0.5, n_estimators=10, random_state=0),
KNeighborsRegressor(),
]
CLASSIFICATION_ESTIMATORS = [
LogisticRegression(random_state=0),
DecisionTreeClassifier(random_state=0),
RandomForestClassifier(random_state=0),
GradientBoostingClassifier(subsample=0.5, n_estimators=10, random_state=0),
KNeighborsClassifier(),
GaussianNB(),
]
"""
Functions to provide a value of how good a fit on a variable is
"""
REGRESSION_METRICS = [
explained_variance_score,
mean_absolute_error,
mean_squared_error,
r2_score,
max_error,
error_variance,
relative_error_variance,
gini_loss,
] + BINARY_NN_FEATURES
REGRESSION_RESIDUAL_METRICS = [
] + UNARY_NUMERICAL_FEATURES
BINARY_PROBABILITY_CLASSIFICATION_METRICS = [
roc_auc_score,
hinge_loss,
] + REGRESSION_METRICS
RESIDUAL_PROBABILITY_CLASSIFICATION_METRICS = [
] + REGRESSION_RESIDUAL_METRICS
BINARY_CLASSIFICATION_METRICS = [
accuracy_score,
average_precision_score,
f1_score,
matthews_corrcoef,
precision_score,
recall_score,
zero_one_loss,
categorical_gini_loss,
]
ND_CLASSIFICATION_METRICS = [ # metrics for N-dimensional classification
] + BINARY_CC_FEATURES
"""
Functions to assess the model (e.g. complexity) of the fit on a numerical variable
of type signature:
metric(clf, X, y)
"""
REGRESSION_MODEL_METRICS = [
# TODO model complexity metrics
]
CLASSIFICATION_MODEL_METRICS = [
# TODO use regression model metrics on predict_proba
]
"""
The operations to perform on the A->B features and B->A features.
"""
RELATIVE_FEATURES = [
# Identity functions, comment out the next 2 lines for only relative features
lambda x, y: x,
lambda x, y: y,
lambda x, y: x - y,
]
"""
Whether or not to treat each observation (A,B) as two observations: (A,B) and (B,A)
If this is done and training labels are given, those labels will have to be
reflected as well. The reflection is performed through appending at the end.
(e.g. if we have N training examples, observation N+1 in the output will be
the first example reflected)
"""
REFLECT_DATA = False
"""
Whether or not metafeatures based on the types of A and B are generated.
e.g. 1/0 feature on whether or not A is Numerical, etc.
"""
ADD_METAFEATURES = True
"""
Whether or not to generate combination features between the computed
features and metafeatures.
e.g. for each feature and metafeature, generate a new feature which is the
product of the two
WARNING: will generate a LOT of features (approximately 21 times as many)
"""
COMPUTE_METAFEATURE_COMBINATIONS = False | anova,
]
BINARY_CC_FEATURES = [
categorical_categorical_homogeneity, | random_line_split |
expressionset.rs | use ordered_float::NotNaN;
use bio::stats::probs;
use crate::model;
pub type MeanExpression = NotNaN<f64>;
pub type CDF = probs::cdf::CDF<MeanExpression>;
pub fn cdf(expression_cdfs: &[model::expression::NormalizedCDF], pseudocounts: f64) -> CDF |
// #[cfg(test)]
// mod tests {
// #![allow(non_upper_case_globals)]
//
// use bio::stats::{Prob, LogProb};
//
// use super::*;
// use model;
// use io;
//
//
// const GENE: &'static str = "COL5A1";
//
// fn setup() -> Box<model::readout::Model> {
// model::readout::new_model(
// &[Prob(0.04); 16],
// &[Prob(0.1); 16],
// io::codebook::Codebook::from_file("tests/codebook/140genesData.1.txt").unwrap()
// )
// }
//
// #[test]
// fn test_cdf() {
// let readout = setup();
// let cdfs = [
// model::expression::cdf(GENE, 5, 5, &readout, 100).0,
// model::expression::cdf(GENE, 5, 5, &readout, 100).0,
// model::expression::cdf(GENE, 5, 5, &readout, 100).0,
// model::expression::cdf(GENE, 5, 5, &readout, 100).0
// ];
// println!("{:?}", cdfs[0]);
// let cdf = cdf(&cdfs, 0.0000001);
// println!("{:?}", cdf);
//
// let total = cdf.total_prob();
//
// assert_relative_eq!(*total, *LogProb::ln_one(), epsilon = 0.002);
// }
// }
| {
let pseudocounts = NotNaN::new(pseudocounts).unwrap();
if expression_cdfs.len() == 1 {
let mut cdf = expression_cdfs[0].clone();
for e in cdf.iter_mut() {
e.value += pseudocounts;
}
return cdf;
}
let cdf = model::meanvar::cdf(expression_cdfs, |mean, _| mean + pseudocounts);
assert_relative_eq!(cdf.total_prob().exp(), 1.0, epsilon = 0.001);
cdf.reduce().sample(1000)
} | identifier_body |
expressionset.rs | use ordered_float::NotNaN;
use bio::stats::probs;
use crate::model;
pub type MeanExpression = NotNaN<f64>;
pub type CDF = probs::cdf::CDF<MeanExpression>;
pub fn cdf(expression_cdfs: &[model::expression::NormalizedCDF], pseudocounts: f64) -> CDF {
let pseudocounts = NotNaN::new(pseudocounts).unwrap();
if expression_cdfs.len() == 1 {
let mut cdf = expression_cdfs[0].clone();
for e in cdf.iter_mut() {
e.value += pseudocounts;
}
return cdf;
}
let cdf = model::meanvar::cdf(expression_cdfs, |mean, _| mean + pseudocounts);
assert_relative_eq!(cdf.total_prob().exp(), 1.0, epsilon = 0.001);
cdf.reduce().sample(1000)
}
// #[cfg(test)]
// mod tests {
// #![allow(non_upper_case_globals)]
//
// use bio::stats::{Prob, LogProb};
//
// use super::*;
// use model;
// use io;
//
//
// const GENE: &'static str = "COL5A1";
//
// fn setup() -> Box<model::readout::Model> {
// model::readout::new_model(
// &[Prob(0.04); 16],
// &[Prob(0.1); 16], | // io::codebook::Codebook::from_file("tests/codebook/140genesData.1.txt").unwrap()
// )
// }
//
// #[test]
// fn test_cdf() {
// let readout = setup();
// let cdfs = [
// model::expression::cdf(GENE, 5, 5, &readout, 100).0,
// model::expression::cdf(GENE, 5, 5, &readout, 100).0,
// model::expression::cdf(GENE, 5, 5, &readout, 100).0,
// model::expression::cdf(GENE, 5, 5, &readout, 100).0
// ];
// println!("{:?}", cdfs[0]);
// let cdf = cdf(&cdfs, 0.0000001);
// println!("{:?}", cdf);
//
// let total = cdf.total_prob();
//
// assert_relative_eq!(*total, *LogProb::ln_one(), epsilon = 0.002);
// }
// } | random_line_split |
|
expressionset.rs | use ordered_float::NotNaN;
use bio::stats::probs;
use crate::model;
pub type MeanExpression = NotNaN<f64>;
pub type CDF = probs::cdf::CDF<MeanExpression>;
pub fn | (expression_cdfs: &[model::expression::NormalizedCDF], pseudocounts: f64) -> CDF {
let pseudocounts = NotNaN::new(pseudocounts).unwrap();
if expression_cdfs.len() == 1 {
let mut cdf = expression_cdfs[0].clone();
for e in cdf.iter_mut() {
e.value += pseudocounts;
}
return cdf;
}
let cdf = model::meanvar::cdf(expression_cdfs, |mean, _| mean + pseudocounts);
assert_relative_eq!(cdf.total_prob().exp(), 1.0, epsilon = 0.001);
cdf.reduce().sample(1000)
}
// #[cfg(test)]
// mod tests {
// #![allow(non_upper_case_globals)]
//
// use bio::stats::{Prob, LogProb};
//
// use super::*;
// use model;
// use io;
//
//
// const GENE: &'static str = "COL5A1";
//
// fn setup() -> Box<model::readout::Model> {
// model::readout::new_model(
// &[Prob(0.04); 16],
// &[Prob(0.1); 16],
// io::codebook::Codebook::from_file("tests/codebook/140genesData.1.txt").unwrap()
// )
// }
//
// #[test]
// fn test_cdf() {
// let readout = setup();
// let cdfs = [
// model::expression::cdf(GENE, 5, 5, &readout, 100).0,
// model::expression::cdf(GENE, 5, 5, &readout, 100).0,
// model::expression::cdf(GENE, 5, 5, &readout, 100).0,
// model::expression::cdf(GENE, 5, 5, &readout, 100).0
// ];
// println!("{:?}", cdfs[0]);
// let cdf = cdf(&cdfs, 0.0000001);
// println!("{:?}", cdf);
//
// let total = cdf.total_prob();
//
// assert_relative_eq!(*total, *LogProb::ln_one(), epsilon = 0.002);
// }
// }
| cdf | identifier_name |
expressionset.rs | use ordered_float::NotNaN;
use bio::stats::probs;
use crate::model;
pub type MeanExpression = NotNaN<f64>;
pub type CDF = probs::cdf::CDF<MeanExpression>;
pub fn cdf(expression_cdfs: &[model::expression::NormalizedCDF], pseudocounts: f64) -> CDF {
let pseudocounts = NotNaN::new(pseudocounts).unwrap();
if expression_cdfs.len() == 1 |
let cdf = model::meanvar::cdf(expression_cdfs, |mean, _| mean + pseudocounts);
assert_relative_eq!(cdf.total_prob().exp(), 1.0, epsilon = 0.001);
cdf.reduce().sample(1000)
}
// #[cfg(test)]
// mod tests {
// #![allow(non_upper_case_globals)]
//
// use bio::stats::{Prob, LogProb};
//
// use super::*;
// use model;
// use io;
//
//
// const GENE: &'static str = "COL5A1";
//
// fn setup() -> Box<model::readout::Model> {
// model::readout::new_model(
// &[Prob(0.04); 16],
// &[Prob(0.1); 16],
// io::codebook::Codebook::from_file("tests/codebook/140genesData.1.txt").unwrap()
// )
// }
//
// #[test]
// fn test_cdf() {
// let readout = setup();
// let cdfs = [
// model::expression::cdf(GENE, 5, 5, &readout, 100).0,
// model::expression::cdf(GENE, 5, 5, &readout, 100).0,
// model::expression::cdf(GENE, 5, 5, &readout, 100).0,
// model::expression::cdf(GENE, 5, 5, &readout, 100).0
// ];
// println!("{:?}", cdfs[0]);
// let cdf = cdf(&cdfs, 0.0000001);
// println!("{:?}", cdf);
//
// let total = cdf.total_prob();
//
// assert_relative_eq!(*total, *LogProb::ln_one(), epsilon = 0.002);
// }
// }
| {
let mut cdf = expression_cdfs[0].clone();
for e in cdf.iter_mut() {
e.value += pseudocounts;
}
return cdf;
} | conditional_block |
buildconfigsetrecords.py | __author__ = 'thauser'
from argh import arg
import logging
from pnc_cli import utils
from pnc_cli.swagger_client.apis import BuildconfigurationsetsApi
from pnc_cli.swagger_client.apis import BuildconfigsetrecordsApi
sets_api = BuildconfigurationsetsApi(utils.get_api_client())
bcsr_api = BuildconfigsetrecordsApi(utils.get_api_client())
@arg("-p", "--page-size", help="Limit the amount of build records returned")
@arg("-s", "--sort", help="Sorting RSQL")
@arg("-q", help="RSQL query")
def list_build_configuration_set_records(page_size=200, sort="", q=""):
"""
List all build configuration set records.
"""
response = utils.checked_api_call(bcsr_api, 'get_all', page_size=page_size, sort=sort, q=q) | def get_build_configuration_set_record(id):
"""
Get a specific BuildConfigSetRecord
"""
response = utils.checked_api_call(bcsr_api, 'get_specific', id=id)
if not response:
logging.error("A BuildConfigurationSetRecord with ID {} does not exist.".format(id))
return
return response.content
@arg("id", help="ID of BuildConfigSetRecord to retrieve build records from.")
@arg("-p", "--page-size", help="Limit the amount of build records returned")
@arg("-s", "--sort", help="Sorting RSQL")
@arg("-q", help="RSQL query")
def list_records_for_build_config_set(id, page_size=200, sort="", q=""):
"""
Get a list of BuildRecords for the given BuildConfigSetRecord
"""
bcrs_check = utils.checked_api_call(sets_api, 'get_all', q="id==" + id)
if not bcrs_check:
logging.error("A BuildConfigurationSet with ID {} does not exist.".format(id))
return
response = utils.checked_api_call(bcsr_api, 'get_build_records', id=id, page_size=page_size, sort=sort, q=q)
if response:
return response.content | if response:
return response.content
@arg("id", help="ID of build configuration set record to retrieve.") | random_line_split |
buildconfigsetrecords.py | __author__ = 'thauser'
from argh import arg
import logging
from pnc_cli import utils
from pnc_cli.swagger_client.apis import BuildconfigurationsetsApi
from pnc_cli.swagger_client.apis import BuildconfigsetrecordsApi
sets_api = BuildconfigurationsetsApi(utils.get_api_client())
bcsr_api = BuildconfigsetrecordsApi(utils.get_api_client())
@arg("-p", "--page-size", help="Limit the amount of build records returned")
@arg("-s", "--sort", help="Sorting RSQL")
@arg("-q", help="RSQL query")
def list_build_configuration_set_records(page_size=200, sort="", q=""):
"""
List all build configuration set records.
"""
response = utils.checked_api_call(bcsr_api, 'get_all', page_size=page_size, sort=sort, q=q)
if response:
return response.content
@arg("id", help="ID of build configuration set record to retrieve.")
def get_build_configuration_set_record(id):
"""
Get a specific BuildConfigSetRecord
"""
response = utils.checked_api_call(bcsr_api, 'get_specific', id=id)
if not response:
logging.error("A BuildConfigurationSetRecord with ID {} does not exist.".format(id))
return
return response.content
@arg("id", help="ID of BuildConfigSetRecord to retrieve build records from.")
@arg("-p", "--page-size", help="Limit the amount of build records returned")
@arg("-s", "--sort", help="Sorting RSQL")
@arg("-q", help="RSQL query")
def list_records_for_build_config_set(id, page_size=200, sort="", q=""):
"""
Get a list of BuildRecords for the given BuildConfigSetRecord
"""
bcrs_check = utils.checked_api_call(sets_api, 'get_all', q="id==" + id)
if not bcrs_check:
|
response = utils.checked_api_call(bcsr_api, 'get_build_records', id=id, page_size=page_size, sort=sort, q=q)
if response:
return response.content
| logging.error("A BuildConfigurationSet with ID {} does not exist.".format(id))
return | conditional_block |
buildconfigsetrecords.py | __author__ = 'thauser'
from argh import arg
import logging
from pnc_cli import utils
from pnc_cli.swagger_client.apis import BuildconfigurationsetsApi
from pnc_cli.swagger_client.apis import BuildconfigsetrecordsApi
sets_api = BuildconfigurationsetsApi(utils.get_api_client())
bcsr_api = BuildconfigsetrecordsApi(utils.get_api_client())
@arg("-p", "--page-size", help="Limit the amount of build records returned")
@arg("-s", "--sort", help="Sorting RSQL")
@arg("-q", help="RSQL query")
def list_build_configuration_set_records(page_size=200, sort="", q=""):
"""
List all build configuration set records.
"""
response = utils.checked_api_call(bcsr_api, 'get_all', page_size=page_size, sort=sort, q=q)
if response:
return response.content
@arg("id", help="ID of build configuration set record to retrieve.")
def | (id):
"""
Get a specific BuildConfigSetRecord
"""
response = utils.checked_api_call(bcsr_api, 'get_specific', id=id)
if not response:
logging.error("A BuildConfigurationSetRecord with ID {} does not exist.".format(id))
return
return response.content
@arg("id", help="ID of BuildConfigSetRecord to retrieve build records from.")
@arg("-p", "--page-size", help="Limit the amount of build records returned")
@arg("-s", "--sort", help="Sorting RSQL")
@arg("-q", help="RSQL query")
def list_records_for_build_config_set(id, page_size=200, sort="", q=""):
"""
Get a list of BuildRecords for the given BuildConfigSetRecord
"""
bcrs_check = utils.checked_api_call(sets_api, 'get_all', q="id==" + id)
if not bcrs_check:
logging.error("A BuildConfigurationSet with ID {} does not exist.".format(id))
return
response = utils.checked_api_call(bcsr_api, 'get_build_records', id=id, page_size=page_size, sort=sort, q=q)
if response:
return response.content
| get_build_configuration_set_record | identifier_name |
buildconfigsetrecords.py | __author__ = 'thauser'
from argh import arg
import logging
from pnc_cli import utils
from pnc_cli.swagger_client.apis import BuildconfigurationsetsApi
from pnc_cli.swagger_client.apis import BuildconfigsetrecordsApi
sets_api = BuildconfigurationsetsApi(utils.get_api_client())
bcsr_api = BuildconfigsetrecordsApi(utils.get_api_client())
@arg("-p", "--page-size", help="Limit the amount of build records returned")
@arg("-s", "--sort", help="Sorting RSQL")
@arg("-q", help="RSQL query")
def list_build_configuration_set_records(page_size=200, sort="", q=""):
|
@arg("id", help="ID of build configuration set record to retrieve.")
def get_build_configuration_set_record(id):
"""
Get a specific BuildConfigSetRecord
"""
response = utils.checked_api_call(bcsr_api, 'get_specific', id=id)
if not response:
logging.error("A BuildConfigurationSetRecord with ID {} does not exist.".format(id))
return
return response.content
@arg("id", help="ID of BuildConfigSetRecord to retrieve build records from.")
@arg("-p", "--page-size", help="Limit the amount of build records returned")
@arg("-s", "--sort", help="Sorting RSQL")
@arg("-q", help="RSQL query")
def list_records_for_build_config_set(id, page_size=200, sort="", q=""):
"""
Get a list of BuildRecords for the given BuildConfigSetRecord
"""
bcrs_check = utils.checked_api_call(sets_api, 'get_all', q="id==" + id)
if not bcrs_check:
logging.error("A BuildConfigurationSet with ID {} does not exist.".format(id))
return
response = utils.checked_api_call(bcsr_api, 'get_build_records', id=id, page_size=page_size, sort=sort, q=q)
if response:
return response.content
| """
List all build configuration set records.
"""
response = utils.checked_api_call(bcsr_api, 'get_all', page_size=page_size, sort=sort, q=q)
if response:
return response.content | identifier_body |
upload_clinic_codes.py | from csv import DictReader
from django.core.management.base import BaseCommand
from registrations.models import ClinicCode
class Command(BaseCommand):
help = (
"This command takes in a CSV with the columns: uid, code, facility, province,"
"and location, and creates/updates the cliniccodes in the database."
"This will only add or update, it will not remove"
)
def add_arguments(self, parser):
|
def normalise_location(self, location):
"""
Normalises the location from `[longitude,latitude]` to ISO6709
"""
def fractional_part(f):
if not float(f) % 1:
return ""
parts = f.split(".")
return f".{parts[1]}"
try:
longitude, latitude = location.strip("[]").split(",")
return (
f"{int(float(latitude)):+03d}{fractional_part(latitude)}"
f"{int(float(longitude)):+04d}{fractional_part(longitude)}"
"/"
)
except (AttributeError, ValueError, TypeError):
return None
def handle(self, *args, **kwargs):
updated = 0
created = 0
with open(kwargs["data_csv"]) as f:
reader = DictReader(f)
for row in reader:
_, new = ClinicCode.objects.update_or_create(
uid=row["uid"].strip(),
defaults={
"code": row["code"].strip(),
"value": row["code"].strip(),
"name": row["facility"].strip(),
"province": {
"ec": "ZA-EC",
"fs": "ZA-FS",
"gp": "ZA-GT",
"kz": "ZA-NL",
"lp": "ZA-LP",
"mp": "ZA-MP",
"nc": "ZA-NC",
"nw": "ZA-NW",
"wc": "ZA-WC",
}[row["province"].strip()[:2].lower()],
"location": self.normalise_location(row["location"].strip()),
},
)
if new:
created += 1
else:
updated += 1
self.success(f"Updated {updated} and created {created} clinic codes")
def log(self, level, msg):
self.stdout.write(level(msg))
def success(self, msg):
self.log(self.style.SUCCESS, msg)
| parser.add_argument("data_csv", type=str, help=("The CSV with the data in it")) | identifier_body |
upload_clinic_codes.py | from csv import DictReader
from django.core.management.base import BaseCommand
from registrations.models import ClinicCode
class Command(BaseCommand):
help = (
"This command takes in a CSV with the columns: uid, code, facility, province,"
"and location, and creates/updates the cliniccodes in the database."
"This will only add or update, it will not remove"
)
def add_arguments(self, parser):
parser.add_argument("data_csv", type=str, help=("The CSV with the data in it"))
def normalise_location(self, location):
"""
Normalises the location from `[longitude,latitude]` to ISO6709
"""
def fractional_part(f):
if not float(f) % 1:
return ""
parts = f.split(".")
return f".{parts[1]}"
try:
longitude, latitude = location.strip("[]").split(",")
return (
f"{int(float(latitude)):+03d}{fractional_part(latitude)}"
f"{int(float(longitude)):+04d}{fractional_part(longitude)}"
"/"
)
except (AttributeError, ValueError, TypeError):
return None
def handle(self, *args, **kwargs):
updated = 0
created = 0
with open(kwargs["data_csv"]) as f:
reader = DictReader(f)
for row in reader:
_, new = ClinicCode.objects.update_or_create(
uid=row["uid"].strip(),
defaults={ | "province": {
"ec": "ZA-EC",
"fs": "ZA-FS",
"gp": "ZA-GT",
"kz": "ZA-NL",
"lp": "ZA-LP",
"mp": "ZA-MP",
"nc": "ZA-NC",
"nw": "ZA-NW",
"wc": "ZA-WC",
}[row["province"].strip()[:2].lower()],
"location": self.normalise_location(row["location"].strip()),
},
)
if new:
created += 1
else:
updated += 1
self.success(f"Updated {updated} and created {created} clinic codes")
def log(self, level, msg):
self.stdout.write(level(msg))
def success(self, msg):
self.log(self.style.SUCCESS, msg) | "code": row["code"].strip(),
"value": row["code"].strip(),
"name": row["facility"].strip(), | random_line_split |
upload_clinic_codes.py | from csv import DictReader
from django.core.management.base import BaseCommand
from registrations.models import ClinicCode
class Command(BaseCommand):
help = (
"This command takes in a CSV with the columns: uid, code, facility, province,"
"and location, and creates/updates the cliniccodes in the database."
"This will only add or update, it will not remove"
)
def | (self, parser):
parser.add_argument("data_csv", type=str, help=("The CSV with the data in it"))
def normalise_location(self, location):
"""
Normalises the location from `[longitude,latitude]` to ISO6709
"""
def fractional_part(f):
if not float(f) % 1:
return ""
parts = f.split(".")
return f".{parts[1]}"
try:
longitude, latitude = location.strip("[]").split(",")
return (
f"{int(float(latitude)):+03d}{fractional_part(latitude)}"
f"{int(float(longitude)):+04d}{fractional_part(longitude)}"
"/"
)
except (AttributeError, ValueError, TypeError):
return None
def handle(self, *args, **kwargs):
updated = 0
created = 0
with open(kwargs["data_csv"]) as f:
reader = DictReader(f)
for row in reader:
_, new = ClinicCode.objects.update_or_create(
uid=row["uid"].strip(),
defaults={
"code": row["code"].strip(),
"value": row["code"].strip(),
"name": row["facility"].strip(),
"province": {
"ec": "ZA-EC",
"fs": "ZA-FS",
"gp": "ZA-GT",
"kz": "ZA-NL",
"lp": "ZA-LP",
"mp": "ZA-MP",
"nc": "ZA-NC",
"nw": "ZA-NW",
"wc": "ZA-WC",
}[row["province"].strip()[:2].lower()],
"location": self.normalise_location(row["location"].strip()),
},
)
if new:
created += 1
else:
updated += 1
self.success(f"Updated {updated} and created {created} clinic codes")
def log(self, level, msg):
self.stdout.write(level(msg))
def success(self, msg):
self.log(self.style.SUCCESS, msg)
| add_arguments | identifier_name |
upload_clinic_codes.py | from csv import DictReader
from django.core.management.base import BaseCommand
from registrations.models import ClinicCode
class Command(BaseCommand):
help = (
"This command takes in a CSV with the columns: uid, code, facility, province,"
"and location, and creates/updates the cliniccodes in the database."
"This will only add or update, it will not remove"
)
def add_arguments(self, parser):
parser.add_argument("data_csv", type=str, help=("The CSV with the data in it"))
def normalise_location(self, location):
"""
Normalises the location from `[longitude,latitude]` to ISO6709
"""
def fractional_part(f):
if not float(f) % 1:
return ""
parts = f.split(".")
return f".{parts[1]}"
try:
longitude, latitude = location.strip("[]").split(",")
return (
f"{int(float(latitude)):+03d}{fractional_part(latitude)}"
f"{int(float(longitude)):+04d}{fractional_part(longitude)}"
"/"
)
except (AttributeError, ValueError, TypeError):
return None
def handle(self, *args, **kwargs):
updated = 0
created = 0
with open(kwargs["data_csv"]) as f:
reader = DictReader(f)
for row in reader:
_, new = ClinicCode.objects.update_or_create(
uid=row["uid"].strip(),
defaults={
"code": row["code"].strip(),
"value": row["code"].strip(),
"name": row["facility"].strip(),
"province": {
"ec": "ZA-EC",
"fs": "ZA-FS",
"gp": "ZA-GT",
"kz": "ZA-NL",
"lp": "ZA-LP",
"mp": "ZA-MP",
"nc": "ZA-NC",
"nw": "ZA-NW",
"wc": "ZA-WC",
}[row["province"].strip()[:2].lower()],
"location": self.normalise_location(row["location"].strip()),
},
)
if new:
|
else:
updated += 1
self.success(f"Updated {updated} and created {created} clinic codes")
def log(self, level, msg):
self.stdout.write(level(msg))
def success(self, msg):
self.log(self.style.SUCCESS, msg)
| created += 1 | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.