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
mod.rs
pub mod event; use crate::Opt; use diesel::pg::PgConnection; use diesel::r2d2::ConnectionManager; use diesel_migrations::{ find_migrations_directory, mark_migrations_in_directory, run_pending_migrations, setup_database, }; use r2d2::{Pool, PooledConnection}; use std::error::Error; pub type DatabasePool = Pool<Con...
} run_pending_migrations(&connection).expect("Could not run database migrations"); }
eprintln!( "No database migrations available in \"{}\".", migrations_dir.to_string_lossy() );
random_line_split
script_msg.rs
v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use AnimationState; use CompositorEvent; use DocumentState; use IFrameLoadInfo; use IFrameLoadInfoWithData; use LayoutControlMsg; use LoadData; use MozBrowserEvent; use WorkerGlobalScopeInit; use ...
} /// A log entry reported to the constellation /// We don't report all log entries, just serious ones. /// We need a separate type for this because `LogLevel` isn't serializable. #[derive(Clone, Debug, Deserialize, Serialize)] pub enum LogEntry { /// Panic, with a reason and backtrace Panic(String, String), ...
random_line_split
script_msg.rs
with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use AnimationState; use CompositorEvent; use DocumentState; use IFrameLoadInfo; use IFrameLoadInfoWithData; use LayoutControlMsg; use LoadData; use MozBrowserEvent; use WorkerGlobalScopeInit; use WorkerScriptLoadOrigin; use canvas_traits::canvas...
SWManagerMsg
identifier_name
raw.py
""" Export to RAW/RPL file format Based on: http://www.nist.gov/lispix/doc/image-file-formats/raw-file-format.htm """ # Standard library modules. import os # Third party modules. # Local modules. from pyhmsa.fileformat.exporter.exporter import _Exporter, _ExporterThread from pyhmsa.spec.datum.analysislist import A...
(_Exporter): def _create_thread(self, datafile, dirpath, *args, **kwargs): return _ExporterRAWThread(datafile, dirpath) def validate(self, datafile): super().validate(datafile) identifiers = set(datafile.data.findkeys(AnalysisList2D)) | \ set(datafile.data.findkeys(ImageRa...
ExporterRAW
identifier_name
raw.py
""" Export to RAW/RPL file format Based on: http://www.nist.gov/lispix/doc/image-file-formats/raw-file-format.htm """ # Standard library modules. import os # Third party modules. # Local modules. from pyhmsa.fileformat.exporter.exporter import _Exporter, _ExporterThread from pyhmsa.spec.datum.analysislist import A...
super().validate(datafile) identifiers = set(datafile.data.findkeys(AnalysisList2D)) | \ set(datafile.data.findkeys(ImageRaster2D)) | \ set(datafile.data.findkeys(ImageRaster2DSpectral)) if not identifiers: raise ValueError('Datafile must contain at least one ' + \ ...
identifier_body
raw.py
""" Export to RAW/RPL file format Based on: http://www.nist.gov/lispix/doc/image-file-formats/raw-file-format.htm """ # Standard library modules. import os # Third party modules. # Local modules. from pyhmsa.fileformat.exporter.exporter import _Exporter, _ExporterThread from pyhmsa.spec.datum.analysislist import A...
dtype = datum.dtype lines.append('data-length\t%i' % dtype.itemsize) byteorder = 'little-endian' if dtype.itemsize > 1 else 'dont-care' lines.append('byte-order\t%s' % byteorder) if dtype.kind == 'f': data_type = 'float' elif dtype.kind == 'u': ...
raise IOError('Unkmown datum type') lines.append('width\t%i' % width) lines.append('height\t%i' % height) lines.append('depth\t%i' % depth) lines.append('record-by\t%s' % record_by)
random_line_split
raw.py
""" Export to RAW/RPL file format Based on: http://www.nist.gov/lispix/doc/image-file-formats/raw-file-format.htm """ # Standard library modules. import os # Third party modules. # Local modules. from pyhmsa.fileformat.exporter.exporter import _Exporter, _ExporterThread from pyhmsa.spec.datum.analysislist import A...
elif isinstance(datum, ImageRaster2DSpectral): width, height, depth = datum.shape record_by = 'vector' elif isinstance(datum, AnalysisList2D): depth, width, height = datum.shape record_by = 'image' else: raise IOError('Unkmown datum ty...
width, height = datum.shape depth = 1 record_by = 'dont-care'
conditional_block
bulk_compile_all_java.py
#!/usr/bin/python -tt import commands
array_string="" for item in ar: array_string += " "+item array_string=array_string.replace(ar[0],"") return array_string.rstrip().lstrip() def get_class_path(): #using find /xyz/abc/lib/ -type f \( -name "*.jar" -o -name "*.zip" \) | paste -sd: >> classpath f=open("classpath") lines=f.readlines() return s...
import re import sys def aray__to_string(ar):
random_line_split
bulk_compile_all_java.py
#!/usr/bin/python -tt import commands import re import sys def aray__to_string(ar): array_string="" for item in ar: array_string += " "+item array_string=array_string.replace(ar[0],"") return array_string.rstrip().lstrip() def get_class_path(): #using find /xyz/abc/lib/ -type f \( -name "*.jar" -o -name "...
del alllines for files in filestocompile: directory = re.findall(r".+classes.",files)[0] filesname = files.split(directory)[1] file = "cd "+directory+"; javac -cp "+classpath+" "+filesname; (status,outout)=commands.getstatusoutput(file) __file__log__(str(status) + " " + directory + " " + filesname + " ...
if lines.__contains__("WEB-INF") and lines.__contains__("classes"): filestocompile.append(lines) else: filestoignore.append(lines)
conditional_block
bulk_compile_all_java.py
#!/usr/bin/python -tt import commands import re import sys def aray__to_string(ar): array_string="" for item in ar: array_string += " "+item array_string=array_string.replace(ar[0],"") return array_string.rstrip().lstrip() def get_class_path(): #using find /xyz/abc/lib/ -type f \( -name "*.jar" -o -name "...
__file__log__(str(status) + " " + directory + " " + filesname + " - " + files,"comp.py.log") __file__log__(outout,"debug.compile.log") if __name__ == "__main__": main()
classpath = get_class_path() (status,output)=commands.getstatusoutput("find "+aray__to_string(sys.argv)+" -type f -name \"*.java\"") filestocompile = [] filestoignore = [] alllines = [] alllines = output alllines = alllines.split("\n") for lines in alllines: if lines.__contains__("WEB-INF") and lines.__contain...
identifier_body
bulk_compile_all_java.py
#!/usr/bin/python -tt import commands import re import sys def aray__to_string(ar): array_string="" for item in ar: array_string += " "+item array_string=array_string.replace(ar[0],"") return array_string.rstrip().lstrip() def
(): #using find /xyz/abc/lib/ -type f \( -name "*.jar" -o -name "*.zip" \) | paste -sd: >> classpath f=open("classpath") lines=f.readlines() return str(lines[0].split("\n")[0])+":." def __file__log__(s,filename): f=open(filename,"a") f.write(str(s)+"\n") f.flush() f.close() def main(): classpath = get_cla...
get_class_path
identifier_name
dicco_numbers.py
def freq_month(obj):
for i in obj: frequencies[ i-1 ] += 1 print "The following month(s) have a birthday celebration" for i in range(0, len(frequencies)): if frequencies[i] > 0: print str(months[i+1]) + " has " + str(frequencies[i]) return frequencies in_array = [3,6,2,7,7,7,] print freq_month...
if obj is None or obj == []: return months = {1: 'jan', 2: 'feb', 3: 'mar', 4: 'apr', 5: 'may', 6: 'jun', 7: 'jul', 8: 'aug', 9: 'sep', 10: 'oct', 11: 'nov', ...
identifier_body
dicco_numbers.py
def
(obj): if obj is None or obj == []: return months = {1: 'jan', 2: 'feb', 3: 'mar', 4: 'apr', 5: 'may', 6: 'jun', 7: 'jul', 8: 'aug', 9: 'sep', 10: 'oct', 11: 'nov',...
freq_month
identifier_name
dicco_numbers.py
def freq_month(obj): if obj is None or obj == []: return months = {1: 'jan', 2: 'feb', 3: 'mar', 4: 'apr', 5: 'may', 6: 'jun', 7: 'jul', 8: 'aug', 9: 'sep', 10: 'oct', ...
return frequencies in_array = [3,6,2,7,7,7,] print freq_month(in_array) print freq_month([])
print str(months[i+1]) + " has " + str(frequencies[i])
conditional_block
dicco_numbers.py
def freq_month(obj): if obj is None or obj == []: return months = {1: 'jan', 2: 'feb', 3: 'mar', 4: 'apr', 5: 'may', 6: 'jun', 7: 'jul', 8: 'aug', 9: 'sep', 10: 'oct',
# for i in range(0, len(obj)): # frequencies[ obj[i] -1] += 1 for i in obj: frequencies[ i-1 ] += 1 print "The following month(s) have a birthday celebration" for i in range(0, len(frequencies)): if frequencies[i] > 0: print str(months[i+1]) + " has " + str(frequenci...
11: 'nov', 12: 'dec', } frequencies = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
random_line_split
graphicsapp.js
/***** AVAILABLE JAVASCRIPT FUNCTIONS ******/ /* Function: GraphicsApp() * -------------------------------- * Creates a new GraphicsApp object and returns it. * * Parameters: none */ function GraphicsApp() {} /* Function: addButton(buttonName) * ----------------------------------------------- * Creates and...
// day inside of cleanedDaysArray for (var i = 0; i < daysArray.length; i++) { // Create a new day object with the relevant data inside var day = {}; day["dayName"] = dayNames[i]; day["tempHigh"] = daysArray[i]["temp"]["max"]; day["tempLow"] = daysArray[i]["temp"]["min"]; day["weatherDesc...
{ if (this.readyState != 4) return; else if (this.status != 200 && errorFn) errorFn(); else { var data = JSON.parse(this.responseText); var daysArray = data["list"]; // If there is no data, call the error handler if (daysArray == null) { if (errorFn) errorFn(); return; } else if (!success...
identifier_body
graphicsapp.js
/***** AVAILABLE JAVASCRIPT FUNCTIONS ******/ /* Function: GraphicsApp() * -------------------------------- * Creates a new GraphicsApp object and returns it. * * Parameters: none */ function GraphicsApp() {} /* Function: addButton(buttonName) * ----------------------------------------------- * Creates and...
/* Function: sendWeatherRequestWithURL(url, successFn, errorFn) * --------------------------------------------------------- * Makes an AJAX (Asynchronous Javascript and XML) GET request to the given URL. * If the request is unsuccessful, the errorFn callback is called. If successful, * the weather server will ret...
/********* PRIVATE GraphicsApp METHODS ************/
random_line_split
graphicsapp.js
/***** AVAILABLE JAVASCRIPT FUNCTIONS ******/ /* Function: GraphicsApp() * -------------------------------- * Creates a new GraphicsApp object and returns it. * * Parameters: none */ function GraphicsApp() {} /* Function: addButton(buttonName) * ----------------------------------------------- * Creates and...
successFn(cleanedDaysArray); } } // Create and send the request xhr = new XMLHttpRequest(); xhr.onreadystatechange = xhrHandler; xhr.open("GET", url); xhr.send(); } /* Function: dayNamesStartingToday(numDays) * ------------------------------------- * Returns an array of length "numDays" containin...
{ // Create a new day object with the relevant data inside var day = {}; day["dayName"] = dayNames[i]; day["tempHigh"] = daysArray[i]["temp"]["max"]; day["tempLow"] = daysArray[i]["temp"]["min"]; day["weatherDescription"] = daysArray[i]["weather"][0]["main"]; // Rain Clouds Clear Snow day["...
conditional_block
graphicsapp.js
/***** AVAILABLE JAVASCRIPT FUNCTIONS ******/ /* Function: GraphicsApp() * -------------------------------- * Creates a new GraphicsApp object and returns it. * * Parameters: none */ function
() {} /* Function: addButton(buttonName) * ----------------------------------------------- * Creates and adds a new button to the top area of the webpage. The button * will display the text buttonName. * * Parameters: * ----------- * buttonName: the text that is displayed on the button. */ GraphicsApp.prot...
GraphicsApp
identifier_name
tabs-demo.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'sky-tabs-demo', templateUrl: './tabs-demo.component.html' }) export class SkyTabsDemoComponent { public tabsArrayExample1: any[]; public tabsArrayExample2: any[]; public activeTabIndex1: any = 'tab-1'; public activeTabIndex2: any = 0; p...
public openTabClick() { alert('You selected the open tab button'); } public tabChanged(newIndex: any) { console.log('New active tab index: ', newIndex); } }
{ this.tabCounter++; this.tabsArrayExample2.push({ tabHeading: 'Tab ' + this.tabCounter, tabContent: 'Content ' + this.tabCounter, tabIsCloseable: true }); }
identifier_body
tabs-demo.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'sky-tabs-demo', templateUrl: './tabs-demo.component.html' }) export class SkyTabsDemoComponent { public tabsArrayExample1: any[]; public tabsArrayExample2: any[]; public activeTabIndex1: any = 'tab-1'; public activeTabIndex2: any = 0; p...
{ tabHeading: 'Tab 1', tabContent: 'Content 1', tabIndex: 'tab-1' }, { tabHeading: 'Tab 2', tabContent: 'Content 2', tabIndex: 'tab-2' }, { tabHeading: 'Tab 3', tabContent: 'Content 3', tabIndex: 'tab-3' } ];...
constructor() { this.tabsArrayExample1 = [
random_line_split
tabs-demo.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'sky-tabs-demo', templateUrl: './tabs-demo.component.html' }) export class SkyTabsDemoComponent { public tabsArrayExample1: any[]; public tabsArrayExample2: any[]; public activeTabIndex1: any = 'tab-1'; public activeTabIndex2: any = 0; p...
() { this.tabCounter++; this.tabsArrayExample2.push({ tabHeading: 'Tab ' + this.tabCounter, tabContent: 'Content ' + this.tabCounter, tabIsCloseable: true }); } public openTabClick() { alert('You selected the open tab button'); } public tabChanged(newIndex: any) { consol...
addTabClick
identifier_name
resource_thread.rs
.status = None; if let Ok(p) = start_sending_opt(start_chan, metadata, Some(err.clone())) { p.send(Done(Err(err))).unwrap(); } } /// For use by loaders in responding to a Load message that allows content sniffing. pub fn start_sending_sniffed(start_chan: LoadConsumer, metadata: Metadata, ...
AuthCacheEntry
identifier_name
resource_thread.rs
c.send(msg).map_err(|_| ()), ProgressSender::Listener(ref b) => { let action = match msg { ProgressMsg::Payload(buf) => ResponseAction::DataAvailable(buf), ProgressMsg::Done(status) => ResponseAction::ResponseComplete(status), }; ...
} break; } } } } } pub fn write_json_to_file<T: Encodable>(data: &T, profile_dir: &str, filename: &str) { let json_encoded: String; match json::encode(&data) { Ok(d) => json_encoded = d, Err(_) => return, } ...
Err(_) => warn!("Error writing hsts list to disk"), }
random_line_split
sql.py
import os from dataclasses import dataclass from typing import Iterable from dbt.contracts.graph.manifest import SourceFile from dbt.contracts.graph.parsed import ParsedSqlNode, ParsedMacro from dbt.contracts.graph.unparsed import UnparsedMacro from dbt.exceptions import InternalException from dbt.node_types import No...
return os.path.join('sql', block.name) def parse_remote(self, sql: str, name: str) -> ParsedSqlNode: source_file = SourceFile.remote(sql, self.project.project_name) contents = SqlBlock(block_name=name, file=source_file) return self.parse_node(contents) class SqlMacroParser(MacroPa...
)
random_line_split
sql.py
import os from dataclasses import dataclass from typing import Iterable from dbt.contracts.graph.manifest import SourceFile from dbt.contracts.graph.parsed import ParsedSqlNode, ParsedMacro from dbt.contracts.graph.unparsed import UnparsedMacro from dbt.exceptions import InternalException from dbt.node_types import No...
def parse_remote(self, sql: str, name: str) -> ParsedSqlNode: source_file = SourceFile.remote(sql, self.project.project_name) contents = SqlBlock(block_name=name, file=source_file) return self.parse_node(contents) class SqlMacroParser(MacroParser): def parse_remote(self, contents) ->...
if not isinstance(block, SqlBlock): raise InternalException( 'While parsing SQL operation, got an actual file block instead of ' 'an SQL block: {}'.format(block) ) return os.path.join('sql', block.name)
identifier_body
sql.py
import os from dataclasses import dataclass from typing import Iterable from dbt.contracts.graph.manifest import SourceFile from dbt.contracts.graph.parsed import ParsedSqlNode, ParsedMacro from dbt.contracts.graph.unparsed import UnparsedMacro from dbt.exceptions import InternalException from dbt.node_types import No...
(self) -> NodeType: return NodeType.SqlOperation @staticmethod def get_compiled_path(block: FileBlock): # we do it this way to make mypy happy if not isinstance(block, SqlBlock): raise InternalException( 'While parsing SQL operation, got an actual file block ...
resource_type
identifier_name
sql.py
import os from dataclasses import dataclass from typing import Iterable from dbt.contracts.graph.manifest import SourceFile from dbt.contracts.graph.parsed import ParsedSqlNode, ParsedMacro from dbt.contracts.graph.unparsed import UnparsedMacro from dbt.exceptions import InternalException from dbt.node_types import No...
return os.path.join('sql', block.name) def parse_remote(self, sql: str, name: str) -> ParsedSqlNode: source_file = SourceFile.remote(sql, self.project.project_name) contents = SqlBlock(block_name=name, file=source_file) return self.parse_node(contents) class SqlMacroParser(Macro...
raise InternalException( 'While parsing SQL operation, got an actual file block instead of ' 'an SQL block: {}'.format(block) )
conditional_block
urls.py
# Copyright (C) 2012 Aaron Krebs akrebs@ualberta.ca # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is...
urlpatterns = patterns('', # urls for simple one-step registration url(r'^register/$', register, {'backend': 'registration.backends.simple.SimpleBackend', 'template_name': 'registration/registration_form.hamlpy', }, name='registration_register' ), url(r'^regis...
random_line_split
foldercreation.test.ts
import { expect } from "chai"; // if you used the '@types/mocha' method to install mocha type definitions, uncomment the following line import "mocha"; import { GetWorkingFolder, GetWorkingFile } from "../src/GitWikiFuntions"; import { logInfo } from "../src/agentSpecific"; import { existsSync, fstat } from "fs"; impor...
}); it("should be use filename only with a leading \\", () => { expect(GetWorkingFolder(".\\", "\\file1.md", logInfo)).to.equal(".\\"); }); }); describe("Test on the target file", () => { it("should be able to use a path", () => { expect(GetWorkingFile("testdata\\subfolder\\1\\file.md", logInfo)).to.e...
random_line_split
FindPlayer.ts
import { Component } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; import { player } from '../../models/player'; import { side } from '../../models/match'; import { player1 } from '../../models/playerSide'; import { HomePage } from '../home/home'; import { AddPage } from '../add/add'...
this.navCtrl.setRoot(FindPlayerPage); } }
} reload(){
random_line_split
FindPlayer.ts
import { Component } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; import { player } from '../../models/player'; import { side } from '../../models/match'; import { player1 } from '../../models/playerSide'; import { HomePage } from '../home/home'; import { AddPage } from '../add/add'...
else { console.log('User does exist'); console.log("REF DATA: "+ data); this.SidePlayer = data[0]; this.SidePlayer.startKey = this.forNow; console.log("Startkey: " + this.forNow); console.log("SidePlayer Name: " + this.Side...
{ alert("Player with this Jersey Number is not in our databasee") }
conditional_block
FindPlayer.ts
import { Component } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; import { player } from '../../models/player'; import { side } from '../../models/match'; import { player1 } from '../../models/playerSide'; import { HomePage } from '../home/home'; import { AddPage } from '../add/add'...
}
{ this.navCtrl.setRoot(FindPlayerPage); }
identifier_body
FindPlayer.ts
import { Component } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; import { player } from '../../models/player'; import { side } from '../../models/match'; import { player1 } from '../../models/playerSide'; import { HomePage } from '../home/home'; import { AddPage } from '../add/add'...
(public navCtrl: NavController,public navPrams: NavParams, private data: AngularFireDatabase) { this.Checker = null; this.data.object("ClubParams/LiveMatchState/matchPtr").subscribe(data => { console.log("ForNow: " + data.$value); this.forNow = data.$value; //co...
constructor
identifier_name
level.js
'use strict'; const Board = require('./board'), config = require('./config'), Characters = require('./characters'), LongTasks = require('./long-tasks'), Pause = require('./pause'), Scoreboard ...
step(elapsed) { if (this._pause.active) { // TODO: Count how long paused } else { this._handleLongTasks(elapsed); this._handleSubMode(elapsed); this._handleCollisionsAndSteps(elapsed); screenShake.step(elapsed); this._particleE...
}
random_line_split
level.js
'use strict'; const Board = require('./board'), config = require('./config'), Characters = require('./characters'), LongTasks = require('./long-tasks'), Pause = require('./pause'), Scoreboard ...
if (result.dot) { eventBus.fire({ name: 'event.action.eatdot', args: { x: result.x, y: result.y, direction: this._determineCurrentDirection() } }); } } _determin...
{ this._characters.signalFright(); this._frightTimeLeft = this._lvlSpec.frightTime; eventBus.fire({ name: 'event.action.energizer' }); }
conditional_block
level.js
'use strict'; const Board = require('./board'), config = require('./config'), Characters = require('./characters'), LongTasks = require('./long-tasks'), Pause = require('./pause'), Scoreboard ...
() { return this._board.dotsLeft() == false; } _stepPaused(elapsed) { this._pause.step(elapsed); } _handleLongTasks(elapsed) { this._longTasksManager.step(elapsed); } _handleSubMode(elapsed) { if (this._frightTimeLeft !== null) { this._handleFrightL...
checkForEndLevelCondition
identifier_name
level.js
'use strict'; const Board = require('./board'), config = require('./config'), Characters = require('./characters'), LongTasks = require('./long-tasks'), Pause = require('./pause'), Scoreboard ...
stop() { this._characters.stop(); this._pause.stop(); this._scoreboard.stop(); this._particleEmitter.stop(); this._characterParticleEmitter.stop(); screenShake.stop(); // TODO: In next game, make this more encapsulated let idx = this._stage.getChild...
{ this._lvlSpec = config.levelSpecifications[this.number]; this._characters.start(this._lvlSpec); this._pause.start(); this._scoreboard.start(); this._particleEmitter.start(); this._characterParticleEmitter.start(); screenShake.start(this._gfx); eventBus....
identifier_body
vl_demo_sift_edge.py
import Image import numpy import pylab import vlfeat from vlfeat.plotop.vl_plotframe import vl_plotframe if __name__ == '__main__': """ VL_DEMO_SIFT_EDGE Demo: SIFT: edge treshold """ I = numpy.zeros([100, 500]) for i in 10 * (1+numpy.arange(9)): d = numpy.round(i / 3.0) I[50-d-1:50+d-1, i * 5-1] = 1 I = n...
pylab.show()
vl_plotframe(f, color='k', linewidth=3) vl_plotframe(f, color='y', linewidth=2)
random_line_split
vl_demo_sift_edge.py
import Image import numpy import pylab import vlfeat from vlfeat.plotop.vl_plotframe import vl_plotframe if __name__ == '__main__':
pylab.gray() pylab.imshow(I) vl_plotframe(f, color='k', linewidth=3) vl_plotframe(f, color='y', linewidth=2) pylab.show()
""" VL_DEMO_SIFT_EDGE Demo: SIFT: edge treshold """ I = numpy.zeros([100, 500]) for i in 10 * (1+numpy.arange(9)): d = numpy.round(i / 3.0) I[50-d-1:50+d-1, i * 5-1] = 1 I = numpy.array(I, 'f', order='F') I = 2 * numpy.pi * 8 ** 2 * vlfeat.vl_imsmooth(I, 8) I = 255 * I I = numpy.array(I, 'f', order='F')...
conditional_block
anchor.js
tinyMCEPopup.requireLangPack(); var AnchorDialog = { init : function(ed) {
v = ed.dom.getAttrib(elm, 'name'); if (v) { this.action = 'update'; f.anchorName.value = v; } f.insert.value = ed.getLang(elm ? 'update' : 'insert'); }, update : function() { ...
var action, elm, f = document.forms[0]; this.editor = ed; elm = ed.dom.getParent(ed.selection.getNode(), 'A');
random_line_split
anchor.js
tinyMCEPopup.requireLangPack(); var AnchorDialog = { init : function(ed) { var action, elm, f = document.forms[0]; this.editor = ed; elm = ed.dom.getParent(ed.selection.getNode(), 'A'); v = ed.dom.getAttrib(elm, 'name'); if (v)
f.insert.value = ed.getLang(elm ? 'update' : 'insert'); }, update : function() { var ed = this.editor, elm, name = document.forms[0].anchorName.value; tinyMCEPopup.restoreSelection(); if (this.action != 'update') ...
{ this.action = 'update'; f.anchorName.value = v; }
conditional_block
weapp-api-tests.ts
(res) { console.log('WebSocket连接已打开!') }) wx.onSocketError(function (res) { console.log('WebSocket连接打开失败,请检查!') }) var socketOpen = false var socketMsgQueue: Array<string> = [] wx.connectSocket({ url: 'test.php' }) wx.onSocketOpen(function (res) { socketOpen = true for (var i = 0; i < socketMsgQu...
ata: msg }) } else { socketMsgQueue.push(msg) } } wx.connectSocket({ url: 'test.php' }) wx.onSocketMessage(function (res) { console.log('收到服务器内容:' + res.data) }) wx.connectSocket({ url: 'test.php' }) //注意这里有时序问题, //如果 wx.connectSocket 还没回调 wx.onSocketOpen,而先调用 wx.closeSocket,那么就做...
e({ d
identifier_name
weapp-api-tests.ts
(function (res) { console.log('WebSocket连接已打开!') }) wx.onSocketError(function (res) { console.log('WebSocket连接打开失败,请检查!') }) var socketOpen = false var socketMsgQueue: Array<string> = [] wx.connectSocket({ url: 'test.php' }) wx.onSocketOpen(function (res) { socketOpen = true for (var i = 0; i < so...
ketOpen) { wx.sendSocketMessage({ data: msg }) } else { socketMsgQueue.push(msg) } } wx.connectSocket({ url: 'test.php' }) wx.onSocketMessage(function (res) { console.log('收到服务器内容:' + res.data) }) wx.connectSocket({ url: 'test.php' }) //注意这里有时序问题, //如果 wx.conn...
unction sendSocketMessage(msg: string) { if (soc
conditional_block
weapp-api-tests.ts
sendSocketMessage(msg: string) { if (socketOpen) { wx.sendSocketMessage({ data: msg }) } else { socketMsgQueue.push(msg) } } wx.connectSocket({ url: 'test.php' }) wx.onSocketMessage(function (res) { console.log('收到服务器内容:' + res.data) }) wx.connectSocket({ ...
context.rect(50, 50, 200, 200) context.fill()
random_line_split
weapp-api-tests.ts
(function (res) { console.log('WebSocket连接已打开!') }) wx.onSocketError(function (res) { console.log('WebSocket连接打开失败,请检查!') }) var socketOpen = false var socketMsgQueue: Array<string> = [] wx.connectSocket({ url: 'test.php' }) wx.onSocketOpen(function (res) { socketOpen = true for (var i = 0; i < so...
console.log('收到服务器内容:' + res.data) }) wx.connectSocket({ url: 'test.php' }) //注意这里有时序问题, //如果 wx.connectSocket 还没回调 wx.onSocketOpen,而先调用 wx.closeSocket,那么就做不到关闭 WebSocket 的目的。 //必须在 WebSocket 打开期间调用 wx.closeSocket 才能关闭。 wx.onSocketOpen(function () { wx.closeSocket() }) wx.onSocketClose(function (res) { ...
}) } else { socketMsgQueue.push(msg) } } wx.connectSocket({ url: 'test.php' }) wx.onSocketMessage(function (res) {
identifier_body
parser.js
"use strict"; var types = require('./types'); var Tree = require('./tree'); var Rule = require('./rule'); var Principle = require('./principle'); var Lexicon = require('./lexicon'); var Nothing = types.Nothing; var eq = types.eq; var normalize = types.normalize; function Parser ( grammar ) { return { bor...
( p, a_x, a_y, b_x, b_y ) { var a = p.table[a_x][a_y]; var b = p.table[b_x][b_y]; var matches = []; for (var i = 0; i<a.length; i++) { for (var j = 0; j<b.length; j++) { matches.push([a[i], b[j]]); } } return matches; } function all_legs ( p, from, to, n ) { if ...
all_matches
identifier_name
parser.js
"use strict"; var types = require('./types'); var Tree = require('./tree'); var Rule = require('./rule'); var Principle = require('./principle'); var Lexicon = require('./lexicon'); var Nothing = types.Nothing; var eq = types.eq; var normalize = types.normalize; function Parser ( grammar ) { return { bor...
if (!w.length) { p.table[p.n] = [[ Tree(w, wordt) ]]; } else { p.table[p.n] = []; p.table[p.n][0] = w.map(function(x) { return Tree(x, wordt); }); } for (var i = p.n-1; i>=0; i--) { exhaust(p, i, p.n-i); } p.n++; }; function parse ( p, sentenc...
var wordt = Tree(word);
random_line_split
parser.js
"use strict"; var types = require('./types'); var Tree = require('./tree'); var Rule = require('./rule'); var Principle = require('./principle'); var Lexicon = require('./lexicon'); var Nothing = types.Nothing; var eq = types.eq; var normalize = types.normalize; function Parser ( grammar ) { return { bor...
p.n++; }; function parse ( p, sentence ) { if (p.borjes !== 'parser') { p = Parser(p); } else { reset(p); } for (var i = 0; i<sentence.length; i++) { input(p, sentence[i]); } var top = p.table[0][p.n-1]; if (top.length === 0) { return Nothing; } else { retur...
{ exhaust(p, i, p.n-i); }
conditional_block
parser.js
"use strict"; var types = require('./types'); var Tree = require('./tree'); var Rule = require('./rule'); var Principle = require('./principle'); var Lexicon = require('./lexicon'); var Nothing = types.Nothing; var eq = types.eq; var normalize = types.normalize; function Parser ( grammar ) { return { bor...
; function reset ( p ) { p.table = []; p.n = 0; }; Parser.reset = reset; Parser.input = input; Parser.parse = parse; module.exports = Parser;
{ if (p.borjes !== 'parser') { p = Parser(p); } else { reset(p); } for (var i = 0; i<sentence.length; i++) { input(p, sentence[i]); } var top = p.table[0][p.n-1]; if (top.length === 0) { return Nothing; } else { return top; } }
identifier_body
poster1.py
import matplotlib as mpl mpl.rcParams['font.size'] = 14 from morphforge.stdimports import * from morphforgecontrib.stdimports import * eqnset_txt_na = """ define_component hh_na { i = g * (v-erev) * m**3*h m_inf = m_alpha_rate / (m_alpha_rate + m_beta_rate) m_tau = 1.0 / (m_alpha_rate + m_beta_rate) ...
cc = sim.create_currentclamp(name="CC1", amp=qty("100:pA"), dur=qty("100:ms"), delay=qty("100:ms"), cell_location=cell.soma) sim.record(cc, what=StandardTags.Current) # run the simulation results = sim.run() TagViewer(results, timerange=(50, 250)*units.ms, show=True)
# Create the stimulus and record the injected current:
random_line_split
animate.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cg; use darling::util::IdentList; use quote::Tokens; use syn::{DeriveInput, Path}; use synstructure::{Structur...
} } let name = &input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); quote! { impl #impl_generics ::values::animated::Animate for #name #ty_generics #where_clause { #[allow(unused_variables, unused_imports)] #[inline] ...
match_body.append_all(quote! { _ => Err(()) });
random_line_split
animate.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cg; use darling::util::IdentList; use quote::Tokens; use syn::{DeriveInput, Path}; use synstructure::{Structur...
})); Ok(quote! { (&#this_pattern, &#other_pattern) => { #computations Ok(#result_value) } }) } #[darling(attributes(animate), default)] #[derive(Default, FromDeriveInput)] struct AnimateInputAttrs { fallback: Option<Path>, } #[darling(attributes(animation), def...
{ quote! { let #result = ::values::animated::Animate::animate(#this, #other, procedure)?; } }
conditional_block
animate.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cg; use darling::util::IdentList; use quote::Tokens; use syn::{DeriveInput, Path}; use synstructure::{Structur...
(mut input: DeriveInput) -> Tokens { let animation_input_attrs = cg::parse_input_attrs::<AnimationInputAttrs>(&input); let no_bound = animation_input_attrs.no_bound.unwrap_or_default(); let mut where_clause = input.generics.where_clause.take(); for param in input.generics.type_params() { if !no_...
derive
identifier_name
index.d.ts
/* * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * 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 ap...
* var v = dsmeanwd.ndarray( x.length, x, 1, 0 ); * // returns ~0.3333 */ declare var dsmeanwd: Routine; // EXPORTS // export = dsmeanwd;
* * var x = new Float32Array( [ 1.0, -2.0, 2.0 ] ); *
random_line_split
MatchBreakdown1920.ts
import { MatchBreakdownTitle, MatchBreakdownField, MatchBreakdownBoolField, MatchBreakdownRow } from '../../../models/MatchBreakdownRow'; import SkystoneMatchDetails from '../../../models/game-specifics/SkystoneMatchDetails'; import SkystoneAllianceDetails from '../../../models/game-specifics/SkystoneAllianceDetails'; ...
}
{ const level1 = allianceDetails.robot1CapLevel === -1 ? 0 : allianceDetails.robot1CapLevel; const level2 = allianceDetails.robot2CapLevel === -1 ? 0 : allianceDetails.robot2CapLevel; return level1 + level2; }
identifier_body
MatchBreakdown1920.ts
import { MatchBreakdownTitle, MatchBreakdownField, MatchBreakdownBoolField, MatchBreakdownRow } from '../../../models/MatchBreakdownRow'; import SkystoneMatchDetails from '../../../models/game-specifics/SkystoneMatchDetails';
getRows(match: Match): MatchBreakdownRow[] { const details: SkystoneMatchDetails = new SkystoneMatchDetails().fromJSON(match.details.toJSON()); const red: SkystoneAllianceDetails = details.redDtls; const blue: SkystoneAllianceDetails = details.blueDtls; return [ MatchBreakdownTitle('Autonomous',...
import SkystoneAllianceDetails from '../../../models/game-specifics/SkystoneAllianceDetails'; import Match from '../../../models/Match'; export default class MatchBreakdown1920 {
random_line_split
MatchBreakdown1920.ts
import { MatchBreakdownTitle, MatchBreakdownField, MatchBreakdownBoolField, MatchBreakdownRow } from '../../../models/MatchBreakdownRow'; import SkystoneMatchDetails from '../../../models/game-specifics/SkystoneMatchDetails'; import SkystoneAllianceDetails from '../../../models/game-specifics/SkystoneAllianceDetails'; ...
(allianceDetails: SkystoneAllianceDetails) { const level1 = allianceDetails.robot1CapLevel === -1 ? 0 : allianceDetails.robot1CapLevel; const level2 = allianceDetails.robot2CapLevel === -1 ? 0 : allianceDetails.robot2CapLevel; return level1 + level2; } }
getCapLevel
identifier_name
geocode.js
var config = require('./config'); var express = require('express'); var superagent = require('superagent'); /** * Auth Token */ var authToken = null; var expires = 0; var expires_in = 20160; // 14 days in minutes /** * Urls */ var OAUTH = 'https://www.arcgis.com/sharing/oauth2/token'; var GEOCODE = 'http://ge...
}); }); } /** * Reverse geocode */ function reverse(ll, callback) { var location = ll; if (ll.lng) { location = ll.lng + ',' + ll.lat; } else if (ll.x) { location = ll.x + ',' + ll.y; } else if (ll[0]) { location = ll[0] + ',' + ll[1]; } auth(callback, function(token) { superag...
{ var body = parseResponse(res, callback); if (!body || !body.locations || body.locations.length === 0) { callback(new Error('Location not found.')); } else { callback(null, body.locations); } }
conditional_block
geocode.js
var config = require('./config'); var express = require('express'); var superagent = require('superagent'); /** * Auth Token */ var authToken = null; var expires = 0; var expires_in = 20160; // 14 days in minutes /** * Urls */ var OAUTH = 'https://www.arcgis.com/sharing/oauth2/token'; var GEOCODE = 'http://ge...
(ll, callback) { var location = ll; if (ll.lng) { location = ll.lng + ',' + ll.lat; } else if (ll.x) { location = ll.x + ',' + ll.y; } else if (ll[0]) { location = ll[0] + ',' + ll[1]; } auth(callback, function(token) { superagent .get(GEOCODE + '/reverseGeocode') .query({ ...
reverse
identifier_name
geocode.js
var config = require('./config'); var express = require('express'); var superagent = require('superagent'); /** * Auth Token */ var authToken = null; var expires = 0; var expires_in = 20160; // 14 days in minutes /** * Urls */ var OAUTH = 'https://www.arcgis.com/sharing/oauth2/token'; var GEOCODE = 'http://ge...
/** * Geocode */ router.get('/:address', function(req, res) { encode(req.params.address, function(err, addresses) { if (err) { console.error(err); res.status(400).send(err); } else { var ll = addresses[0].feature.geometry; res.status(200).send({ lng: ll.x, lat: ll.y...
random_line_split
geocode.js
var config = require('./config'); var express = require('express'); var superagent = require('superagent'); /** * Auth Token */ var authToken = null; var expires = 0; var expires_in = 20160; // 14 days in minutes /** * Urls */ var OAUTH = 'https://www.arcgis.com/sharing/oauth2/token'; var GEOCODE = 'http://ge...
/** * Generate an auth token */ function generateAuthToken(callback) { // If we're within 7 days of auth token expiration, generate a new one if ((expires - expires_in / 2) < Date.now().valueOf()) { superagent .get(OAUTH) .query({ client_id: config.arcgis_id, client_secret: conf...
{ try { return JSON.parse(res.text); } catch (e) { callback(e); } }
identifier_body
print-tree-actions.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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>,...
fn create_element(&mut self, name: QualName, _attrs: Vec<Attribute>) -> uint { let id = self.get_id(); println!("Created {:?} as {}", name, id); self.names.insert(id, name); id } fn create_comment(&mut self, text: String) -> uint { let id = self.get_id(); p...
{ self.names.get(&target).expect("not an element").clone() }
identifier_body
print-tree-actions.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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>,...
} impl Sink { fn get_id(&mut self) -> uint { let id = self.next_id; self.next_id += 1; id } } impl TreeSink for Sink { type Handle = uint; fn parse_error(&mut self, msg: CowString<'static>) { println!("Parse error: {}", msg); } fn get_document(&mut self) -> ui...
struct Sink { next_id: uint, names: HashMap<uint, QualName>,
random_line_split
print-tree-actions.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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>,...
() { let sink = Sink { next_id: 1, names: HashMap::new(), }; let input = io::stdin().read_to_string().unwrap(); parse_to(sink, one_input(input), Default::default()); }
main
identifier_name
CubeResource.ts
import { AbstractMultiResource } from './AbstractMultiResource'; import { TARGETS } from '@pixi/constants'; import type { Resource } from './Resource'; import type { ISize } from '@pixi/math'; import type { ArrayFixed } from '@pixi/utils'; import type { BaseTexture } from '../BaseTexture'; import type { Renderer } fro...
else { throw new Error(`CubeResource does not support copying of renderTexture.`); } } else { // link mode, the difficult one! baseTexture.target = TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + index; baseTexture.par...
{ if (linkBaseTexture === undefined) { linkBaseTexture = this.linkBaseTexture; } if (!this.items[index]) { throw new Error(`Index ${index} is out of bounds`); } if (!this.linkBaseTexture || baseTexture.parentTextureArray ...
identifier_body
CubeResource.ts
import { AbstractMultiResource } from './AbstractMultiResource'; import { TARGETS } from '@pixi/constants'; import type { Resource } from './Resource'; import type { ISize } from '@pixi/math'; import type { ArrayFixed } from '@pixi/utils'; import type { BaseTexture } from '../BaseTexture'; import type { Renderer } fro...
(baseTexture: BaseTexture, index: number, linkBaseTexture?: boolean): this { if (linkBaseTexture === undefined) { linkBaseTexture = this.linkBaseTexture; } if (!this.items[index]) { throw new Error(`Index ${index} is out of bounds`); } ...
addBaseTextureAt
identifier_name
CubeResource.ts
import { AbstractMultiResource } from './AbstractMultiResource'; import { TARGETS } from '@pixi/constants'; import type { Resource } from './Resource'; import type { ISize } from '@pixi/math'; import type { ArrayFixed } from '@pixi/utils'; import type { BaseTexture } from '../BaseTexture'; import type { Renderer } fro...
} /** * Add binding * * @override * @param {PIXI.BaseTexture} baseTexture - parent base texture */ bind(baseTexture: BaseTexture): void { super.bind(baseTexture); baseTexture.target = TARGETS.TEXTURE_CUBE_MAP; } addBaseTextureAt(baseTexture: BaseTextu...
{ this.load(); }
conditional_block
CubeResource.ts
import { AbstractMultiResource } from './AbstractMultiResource'; import { TARGETS } from '@pixi/constants'; import type { Resource } from './Resource'; import type { ISize } from '@pixi/math'; import type { ArrayFixed } from '@pixi/utils'; import type { BaseTexture } from '../BaseTexture'; import type { Renderer } fro...
if (baseTexture.resource) { this.addResourceAt(baseTexture.resource, index); } else { throw new Error(`CubeResource does not support copying of renderTexture.`); } } else { // link...
|| Object.keys(baseTexture._glTextures).length > 0) { // copy mode
random_line_split
issue-24081.rs
// Copyright 2015 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 ...
() {}
main
identifier_name
issue-24081.rs
// Copyright 2015 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 ...
type Add = bool; struct Sub { x: f32 } enum Mul { A, B } mod Div { } trait Rem { } fn main() {}
use std::ops::Add; //~ ERROR import `Add` conflicts with type in this module use std::ops::Sub; //~ ERROR import `Sub` conflicts with type in this module use std::ops::Mul; //~ ERROR import `Mul` conflicts with type in this module use std::ops::Div; //~ ERROR import `Div` conflicts with existing submodule use std::ops:...
random_line_split
simrun.py
# -*- coding: utf-8 -*- """Simulation launch services. Simulation launch services provide the following functionality: - generating simulation id based on local date and time; - generating simulation directory name; - loading names of simulation directories from a text file; - creating directory structure for simulat...
else: sim_path = sim_dirname os.makedirs(sim_path) # raises an error if simulation directory already # exists if data_dirname is not None: os.makedirs(os.path.join(sim_path, data_dirname)) return sim_path def run_sim(model_filename, params_filename=None, si...
sim_path = os.path.join(sim_master_dirname, sim_dirname)
conditional_block
simrun.py
# -*- coding: utf-8 -*- """Simulation launch services. Simulation launch services provide the following functionality: - generating simulation id based on local date and time; - generating simulation directory name; - loading names of simulation directories from a text file; - creating directory structure for simulat...
if sim_id: cmd += [options['sim_id']['arg'][1], sim_id] if data_dirname: cmd += [options['data_dirname']['arg'][1], data_dirname] cmd.append(options['save_data']['arg'][1]) if model_args: cmd += model_args return subprocess.call(cmd) def norm_executable(executable): """...
cmd += executable cmd.append(model_filename) if params_filename: cmd += [options['params_filename']['arg'][1], params_filename]
random_line_split
simrun.py
# -*- coding: utf-8 -*- """Simulation launch services. Simulation launch services provide the following functionality: - generating simulation id based on local date and time; - generating simulation directory name; - loading names of simulation directories from a text file; - creating directory structure for simulat...
(filename): """Load names of simulation directories from a file.""" COMMENT_START_TOKEN = "#" sim_dirnames = [] with open(filename) as sim_dirnames_file: for line in sim_dirnames_file: # Strip leading and trailing whitespace from the line stripped_line = line.strip() ...
load_sim_dirnames
identifier_name
simrun.py
# -*- coding: utf-8 -*- """Simulation launch services. Simulation launch services provide the following functionality: - generating simulation id based on local date and time; - generating simulation directory name; - loading names of simulation directories from a text file; - creating directory structure for simulat...
def generate_sim_dirname(tmp=False, sim_id=None): """Generate simulation directory name.""" if not sim_id: sim_id = generate_sim_id() return sim_id if not tmp else TMP_DIR_PREFIX + sim_id def make_dirs(sim_dirname, sim_master_dirname=None, data_dirname=None): """Create directory structure f...
"""Generate simulation id based on local date and time.""" t = time.localtime() sim_id = "{0:04}{1:02}{2:02}_{3:02}{4:02}{5:02}".format( t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec) return sim_id
identifier_body
plugin.rs
// Copyright 2014 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 ...
<T, F>(f: F) -> T where F: FnOnce(&mut BTreeMap<Name, Span>) -> T, { USED_DIAGNOSTICS.with(move |slot| { f(&mut *slot.borrow_mut()) }) } pub fn expand_diagnostic_used<'cx>(ecx: &'cx mut ExtCtxt, span: Span, token_tree: &[TokenTre...
with_used_diagnostics
identifier_name
plugin.rs
// Copyright 2014 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 ...
F: FnOnce(&mut BTreeMap<Name, Option<Name>>) -> T, { REGISTERED_DIAGNOSTICS.with(move |slot| { f(&mut *slot.borrow_mut()) }) } fn with_used_diagnostics<T, F>(f: F) -> T where F: FnOnce(&mut BTreeMap<Name, Span>) -> T, { USED_DIAGNOSTICS.with(move |slot| { f(&mut *slot.borrow_mut()) ...
fn with_registered_diagnostics<T, F>(f: F) -> T where
random_line_split
plugin.rs
// Copyright 2014 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 ...
"__register_diagnostic_".to_string() + &token::get_ident(*code) )[])); MacItems::new(vec![quote_item!(ecx, mod $sym {}).unwrap()].into_iter()) } pub fn expand_build_diagnostic_array<'cx>(ecx: &'cx mut ExtCtxt, span: Span, ...
{ let (code, description) = match token_tree { [ast::TtToken(_, token::Ident(ref code, _))] => { (code, None) }, [ast::TtToken(_, token::Ident(ref code, _)), ast::TtToken(_, token::Comma), ast::TtToken(_, token::Literal(token::StrRaw(description, _), None))] => ...
identifier_body
graph_loader.py
""" Provided code for Application portion of Module 1 Imports physics citation graph """ ################################### # Code for loading citation graph CITATION_URL = "phys-cite_graph.txt" def
(graph_url): """ Function that loads a graph given the URL for a text representation of the graph Returns a dictionary that models a graph """ graph_file = open(graph_url) graph_text = graph_file.read() graph_lines = graph_text.split('\n') graph_lines = graph_lines[ : -1] print...
load_graph
identifier_name
graph_loader.py
""" Provided code for Application portion of Module 1 Imports physics citation graph """ ################################### # Code for loading citation graph CITATION_URL = "phys-cite_graph.txt" def load_graph(graph_url):
return answer_graph citation_graph = load_graph(CITATION_URL)
""" Function that loads a graph given the URL for a text representation of the graph Returns a dictionary that models a graph """ graph_file = open(graph_url) graph_text = graph_file.read() graph_lines = graph_text.split('\n') graph_lines = graph_lines[ : -1] print "Loaded graph wi...
identifier_body
graph_loader.py
""" Provided code for Application portion of Module 1 Imports physics citation graph """ ################################### # Code for loading citation graph CITATION_URL = "phys-cite_graph.txt" def load_graph(graph_url): """ Function that loads a graph given the URL for a text representation of the gr...
return answer_graph citation_graph = load_graph(CITATION_URL)
neighbors = line.split(' ') node = int(neighbors[0]) answer_graph[node] = set([]) for neighbor in neighbors[1 : -1]: answer_graph[node].add(int(neighbor))
conditional_block
samba.rs
use std::fs::{create_dir, File}; use std::path::Path; use std::io::Write; use std::fmt::Write as FmtWrite; use users::get_user_by_name; use nix::unistd::chown; use common::config::SambaConfig; pub fn is_installed() -> bool { Path::new("/usr/sbin/smbd").is_file() } pub fn setup(tmp: &Path, samba: &SambaConfig, u...
smb passwd file={0}/smbpasswd security = user map to guest = Bad User load printers = no printing = bsd disable spoolss = yes usershare max shares = 0 create mask = 0644 [qemu] path={1} read only=no guest ok=yes force user={2} "#, samba_folder.display(), samba.path, samba.user) ...
{ assert!(is_installed(), "Optional samba dependency not installed!"); let user = get_user_by_name(&samba.user).unwrap(); let samba_cfg = tmp.join("smbd.conf"); let mut smbd_conf = File::create(&samba_cfg).expect("Failed to create smbd conf"); let samba_folder = tmp.join("samba"); write!(smbd_...
identifier_body
samba.rs
use std::fs::{create_dir, File}; use std::path::Path; use std::io::Write; use std::fmt::Write as FmtWrite; use users::get_user_by_name; use nix::unistd::chown; use common::config::SambaConfig; pub fn is_installed() -> bool { Path::new("/usr/sbin/smbd").is_file() } pub fn
(tmp: &Path, samba: &SambaConfig, usernet: &mut String) { assert!(is_installed(), "Optional samba dependency not installed!"); let user = get_user_by_name(&samba.user).unwrap(); let samba_cfg = tmp.join("smbd.conf"); let mut smbd_conf = File::create(&samba_cfg).expect("Failed to create smbd conf"); ...
setup
identifier_name
samba.rs
use std::fs::{create_dir, File}; use std::path::Path; use std::io::Write; use std::fmt::Write as FmtWrite; use users::get_user_by_name; use nix::unistd::chown; use common::config::SambaConfig; pub fn is_installed() -> bool { Path::new("/usr/sbin/smbd").is_file() } pub fn setup(tmp: &Path, samba: &SambaConfig, u...
map to guest = Bad User load printers = no printing = bsd disable spoolss = yes usershare max shares = 0 create mask = 0644 [qemu] path={1} read only=no guest ok=yes force user={2} "#, samba_folder.display(), samba.path, samba.user) .expect("Failed to write smbd conf"); cre...
cache directory={0} ncalrpc dir={0}/ncalrpc log file={0}/log.smbd smb passwd file={0}/smbpasswd security = user
random_line_split
ConditionalNode.js
'use strict'; var latex = require('../../utils/latex'); var operators = require('../operators'); function factory (type, config, load, typed) { var Node = load(require('./Node')); /** * A lazy evaluating conditional operator: 'condition ? trueExpr : falseExpr' * * @param {Node} condition Condition, mu...
throw new TypeError('Unsupported type of condition "' + defs.math['typeof'](condition) + '"'); }; return ( 'testCondition(' + this.condition._compile(defs) + ') ? ' + '( ' + this.trueExpr._compile(defs) + ') : ' + '( ' + this.falseExpr._compile(defs) + ')' ); }; /** * Execute a ...
{ return false; }
conditional_block
ConditionalNode.js
'use strict'; var latex = require('../../utils/latex'); var operators = require('../operators'); function factory (type, config, load, typed) { var Node = load(require('./Node')); /** * A lazy evaluating conditional operator: 'condition ? trueExpr : falseExpr' * * @param {Node} condition Condition, mu...
if (typeof condition === 'number' || typeof condition === 'boolean' || typeof condition === 'string') { return condition ? true : false; } if (condition) { if (condition.isBigNumber === true) { return condition.isZero() ? false : true; } ...
*/ defs.testCondition = function (condition) {
random_line_split
ConditionalNode.js
'use strict'; var latex = require('../../utils/latex'); var operators = require('../operators'); function factory (type, config, load, typed) { var Node = load(require('./Node')); /** * A lazy evaluating conditional operator: 'condition ? trueExpr : falseExpr' * * @param {Node} condition Condition, mu...
(condition, trueExpr, falseExpr) { if (!(this instanceof ConditionalNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (!(condition && condition.isNode)) throw new TypeError('Parameter condition must be a Node'); if (!(trueExpr && trueExpr.isNode)) throw new ...
ConditionalNode
identifier_name
ConditionalNode.js
'use strict'; var latex = require('../../utils/latex'); var operators = require('../operators'); function factory (type, config, load, typed)
this.condition = condition; this.trueExpr = trueExpr; this.falseExpr = falseExpr; } ConditionalNode.prototype = new Node(); ConditionalNode.prototype.type = 'ConditionalNode'; ConditionalNode.prototype.isConditionalNode = true; /** * Compile the node to javascript code * @param {Object}...
{ var Node = load(require('./Node')); /** * A lazy evaluating conditional operator: 'condition ? trueExpr : falseExpr' * * @param {Node} condition Condition, must result in a boolean * @param {Node} trueExpr Expression evaluated when condition is true * @param {Node} falseExpr Expression eval...
identifier_body
models.py
from __future__ import unicode_literals from sqlalchemy import create_engine, Column, ForeignKey, Integer, String,\ Boolean, Unicode, Date, DateTime, and_, func from sqlalchemy.orm import relationship, backref, sessionmaker from sqlalchemy.engine.url import URL from sqlalchemy.ext.declarative import declarative_bas...
(cls, vk_id): db_session = Session() try: user = db_session.query(cls).filter_by(vk_id=vk_id).one() get_logger('file').debug( 'User with vk_id={} found and retrieved.'.format(vk_id)) except NoResultFound, e: user = None db_session.close...
get_by_vk_id
identifier_name
models.py
from __future__ import unicode_literals from sqlalchemy import create_engine, Column, ForeignKey, Integer, String,\ Boolean, Unicode, Date, DateTime, and_, func from sqlalchemy.orm import relationship, backref, sessionmaker from sqlalchemy.engine.url import URL from sqlalchemy.ext.declarative import declarative_bas...
name = Column(String) birthday = Column(String) photo = Column(String) hometown = Column(String) site = Column(String) instagram = Column(String) facebook = Column(String) twitter = Column(String) skype = Column(String) phone = Column(String) university = Column(String) ...
user_pk = Column(Integer, ForeignKey('user.pk'))
random_line_split
models.py
from __future__ import unicode_literals from sqlalchemy import create_engine, Column, ForeignKey, Integer, String,\ Boolean, Unicode, Date, DateTime, and_, func from sqlalchemy.orm import relationship, backref, sessionmaker from sqlalchemy.engine.url import URL from sqlalchemy.ext.declarative import declarative_bas...
return changes Base.metadata.create_all(engine)
changes[k] = {'old': old_val, 'new': new_val}
conditional_block
models.py
from __future__ import unicode_literals from sqlalchemy import create_engine, Column, ForeignKey, Integer, String,\ Boolean, Unicode, Date, DateTime, and_, func from sqlalchemy.orm import relationship, backref, sessionmaker from sqlalchemy.engine.url import URL from sqlalchemy.ext.declarative import declarative_bas...
class UserActivityLog(BaseMixin, Base): user_pk = Column(Integer, ForeignKey('user.pk')) user = relationship("User", backref='activity_logs') is_online = Column(Boolean, default=True) is_mobile = Column(Boolean, default=False) status = Column(String) updates = Column(String) last_visit_l...
changes = {} excluded_attrs = ['pk', 'user_pk', '_sa_instance_state'] keys = [k for k in old.__dict__.keys() if k not in excluded_attrs and "__" not in k] for k in keys: old_val = getattr(old, k) new_val = getattr(new, k) if old_val != new_val:...
identifier_body
formio.component.ts
import { Component, OnInit, Optional, ViewEncapsulation, Input, NgZone, OnChanges } from '@angular/core'; import { FormioAppConfig } from '../../formio.config'; import { Formio, Form } from 'formiojs'; import { FormioBaseComponent } from '../../FormioBaseComponent'; import { CustomTagsService } from '../../custom-compo...
} getRenderer() { return this.renderer || Form; } }
{ console.warn('You must provide an AppConfig within your application!'); }
conditional_block
formio.component.ts
import { Component, OnInit, Optional, ViewEncapsulation, Input, NgZone, OnChanges } from '@angular/core'; import { FormioAppConfig } from '../../formio.config'; import { Formio, Form } from 'formiojs'; import { FormioBaseComponent } from '../../FormioBaseComponent'; import { CustomTagsService } from '../../custom-compo...
getRenderer() { return this.renderer || Form; } }
} else { console.warn('You must provide an AppConfig within your application!'); } }
random_line_split
formio.component.ts
import { Component, OnInit, Optional, ViewEncapsulation, Input, NgZone, OnChanges } from '@angular/core'; import { FormioAppConfig } from '../../formio.config'; import { Formio, Form } from 'formiojs'; import { FormioBaseComponent } from '../../FormioBaseComponent'; import { CustomTagsService } from '../../custom-compo...
getRenderer() { return this.renderer || Form; } }
{ super(ngZone, config, customTags); if (this.config) { Formio.setBaseUrl(this.config.apiUrl); Formio.setProjectUrl(this.config.appUrl); } else { console.warn('You must provide an AppConfig within your application!'); } }
identifier_body
formio.component.ts
import { Component, OnInit, Optional, ViewEncapsulation, Input, NgZone, OnChanges } from '@angular/core'; import { FormioAppConfig } from '../../formio.config'; import { Formio, Form } from 'formiojs'; import { FormioBaseComponent } from '../../FormioBaseComponent'; import { CustomTagsService } from '../../custom-compo...
() { return this.renderer || Form; } }
getRenderer
identifier_name
grad.rs
#pragma version(1) #pragma rs java_package_name(com.xjt.crazypic.edit.filters) #define MAX_POINTS 16 uint32_t inputWidth; uint32_t inputHeight; static const float Rf = 0.2999f; static const float Gf = 0.587f; static const float Bf = 0.114f; //static const float size_scale = 0.01f; typedef struct { rs_matrix3x3 c...
// generated data static UPointData grads[MAX_POINTS]; void setupGradParams() { int k = 0; for (int i = 0; i < MAX_POINTS; i++) { if (!mask[i]) { continue; } float x1 = xPos1[i]; float y1 = yPos1[i]; float x2 = xPos2[i]; float y2 = yPos2[i]; float denom = (y...
int contrast[MAX_POINTS]; int saturation[MAX_POINTS];
random_line_split
grad.rs
#pragma version(1) #pragma rs java_package_name(com.xjt.crazypic.edit.filters) #define MAX_POINTS 16 uint32_t inputWidth; uint32_t inputHeight; static const float Rf = 0.2999f; static const float Gf = 0.587f; static const float Bf = 0.114f; //static const float size_scale = 0.01f; typedef struct { rs_matrix3x3 c...
grads[k].dy = (y1 - y2) / denom; grads[k].dx = (x1 - x2) / denom; grads[k].off = (y2 * y2 + x2 * x2 - x1 * x2 - y1 * y2) / denom; float S = 1+saturation[i]/100.f; float MS = 1-S; float Rt = Rf * MS; float Gt = Gf * MS; float Bt = Bf * MS; float b = 1+brightness[i...
{ continue; }
conditional_block
baseurl.py
""" html page utils """ import urlparse, re from scrapely.htmlpage import parse_html, HtmlTagType ABSURLRE = re.compile("^https?\:\/\/") DOCTYPERE = re.compile("<!DOCTYPE.*?>", re.S | re.I) def _is_abs_url(url): return bool(ABSURLRE.match(url)) def insert_base_url(html, base): """ Inserts the given base ...
return htmlpage.url
if getattr(element, "tag", None) == "base": return element.attributes.get("href") or htmlpage.url
conditional_block
baseurl.py
""" html page utils """ import urlparse, re from scrapely.htmlpage import parse_html, HtmlTagType ABSURLRE = re.compile("^https?\:\/\/") DOCTYPERE = re.compile("<!DOCTYPE.*?>", re.S | re.I) def _is_abs_url(url): return bool(ABSURLRE.match(url)) def insert_base_url(html, base):
basetag = '<base href="%s" />' % absurl html = html[:baseelement.start] + basetag + html[baseelement.end:] else: # Generate new base element and include basetag = '<base href="%s" />' % base if headelement: insertpos = headelement.end else: ...
""" Inserts the given base url if does not exist in html source, or replace the existing if needed """ baseurl = baseelement = headelement = htmlelement = None for element in parse_html(html): if getattr(element, "tag", None) == "base": baseurl = element.attributes.get("href", No...
identifier_body