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 |
|---|---|---|---|---|
eep-service.ts | } from '../app/app-statistics.service';
import { CacheService } from './cache-service';
export enum FileNames {
eepOutJsonOut = 'ak-eep-out.json',
eepOutJsonOutFinished = 'ak-eep-out-json.isfinished',
eepOutLog = 'ak-eep-out.log',
serverOutCommands = 'ak-eep-in.commands',
serverWatching = 'ak-server.iswatch... |
queueCommand = | {
this.logWasCleared = logClearedFunction;
} | identifier_body |
eep-service.ts | } from '../app/app-statistics.service';
import { CacheService } from './cache-service';
export enum FileNames {
eepOutJsonOut = 'ak-eep-out.json',
eepOutJsonOutFinished = 'ak-eep-out-json.isfinished',
eepOutLog = 'ak-eep-out.log',
serverOutCommands = 'ak-eep-in.commands',
serverWatching = 'ak-server.iswatch... | (jsonFile: string, jsonReadyFile: string) {
try {
// EEP has written the JsonFile for us, so let's read it.
const data: string = fs.readFileSync(jsonFile, { encoding: 'latin1' });
const eventLines: string[] = data.split('\n');
for (const line of eventLines) {
if (line.length > 0) {
... | readJsonFile | identifier_name |
StarOrbitModule.js | import {Vector3} from 'three';
import {Loop} from '@whs/core/Loop';
/**
* StarOrbitModule Class
*/
export class StarOrbitModule {
/**
* Stable angular velocity
* @type {boolean}
*/ | * @param {Star} parent_star
* @param {Planet} planet
* @return {ShaderMaterial}
*/
constructor(parent_star, planet) {
const g = 6.67384e-11;
const av_min = 0.00000000001;
Object.assign(this, {
G: g,
SPR: planet.params.physics.fixedTimeSt... | stableAngularVelocity = false;
/**
* Default constructor
* | random_line_split |
StarOrbitModule.js | import {Vector3} from 'three';
import {Loop} from '@whs/core/Loop';
/**
* StarOrbitModule Class
*/
export class StarOrbitModule {
/**
* Stable angular velocity
* @type {boolean}
*/
stableAngularVelocity = false;
/**
* Default constructor
*
* @param {Star} parent_star
... |
// console.log(`[${planet.name}|av]: ( ${planet._physijs.linearVelocity.x} +${l_velocity.x}, ${planet._physijs.linearVelocity.z} +${l_velocity.x} )`);
}
}
| {
// Angular
planet.setAngularVelocity(planet.aVelocity);
// Linear
planet.setLinearVelocity(new Vector3(29861, 0, 0));
// console.log(planet.getLinearVelocity());
// planet.applyForce(
// {x: 29861*100000000, y: 0.0, z: 0.0},
... | conditional_block |
StarOrbitModule.js | import {Vector3} from 'three';
import {Loop} from '@whs/core/Loop';
/**
* StarOrbitModule Class
*/
export class StarOrbitModule {
/**
* Stable angular velocity
* @type {boolean}
*/
stableAngularVelocity = false;
/**
* Default constructor
*
* @param {Star} parent_star
... | (star, planet) {
const distance_to_star = star.position.distanceTo(planet.position);
const acceleration = this.getStarAcceleration(distance_to_star, star.getRealMass());
const d_velocity = acceleration * this.SPR;
let l_velocity = planet.getLinearVelocity().clone();
l... | adjustToStar | identifier_name |
StarOrbitModule.js | import {Vector3} from 'three';
import {Loop} from '@whs/core/Loop';
/**
* StarOrbitModule Class
*/
export class StarOrbitModule {
/**
* Stable angular velocity
* @type {boolean}
*/
stableAngularVelocity = false;
/**
* Default constructor
*
* @param {Star} parent_star
... | planet.setLinearVelocity(new Vector3(29861, 0, 0));
// console.log(planet.getLinearVelocity());
// planet.applyForce(
// {x: 29861*100000000, y: 0.0, z: 0.0},
// {x: 0, y: 0, z: 0}
// );
if(Math.abs(av.x) >= av_min || Math.abs... | {
const distance_to_star = star.position.distanceTo(planet.position);
const acceleration = this.getStarAcceleration(distance_to_star, star.getRealMass());
const d_velocity = acceleration * this.SPR;
let l_velocity = planet.getLinearVelocity().clone();
l_velocity.subVe... | identifier_body |
sensor.py | """Support for Meteo-France raining forecast sensor."""
import logging
from meteofrance_api.helpers import (
get_warning_text_status_from_indice_color,
readeable_phenomenoms_dict,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ATTRIBUTION
from homeassistant.helpers... | sensor_type,
coordinator_forecast.data.position["name"],
)
else:
entities.append(MeteoFranceSensor(sensor_type, coordinator_forecast))
async_add_entities(
entities,
False,
)
class MeteoFranceSensor(CoordinatorEntity)... | "Sensor %s skipped for %s as data is missing in the API", | random_line_split |
sensor.py | """Support for Meteo-France raining forecast sensor."""
import logging
from meteofrance_api.helpers import (
get_warning_text_status_from_indice_color,
readeable_phenomenoms_dict,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ATTRIBUTION
from homeassistant.helpers... |
elif sensor_type == "weather_alert":
if coordinator_alert:
entities.append(MeteoFranceAlertSensor(sensor_type, coordinator_alert))
elif sensor_type in ["rain_chance", "freeze_chance", "snow_chance"]:
if coordinator_forecast.data.probability_forecast:
... | entities.append(MeteoFranceRainSensor(sensor_type, coordinator_rain)) | conditional_block |
sensor.py | """Support for Meteo-France raining forecast sensor."""
import logging
from meteofrance_api.helpers import (
get_warning_text_status_from_indice_color,
readeable_phenomenoms_dict,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ATTRIBUTION
from homeassistant.helpers... | return {
ATTR_NEXT_RAIN_DT_REF: dt_util.utc_from_timestamp(reference_dt).isoformat(),
ATTR_NEXT_RAIN_1_HOUR_FORECAST: {
f"{int((item['dt'] - reference_dt) / 60)} min": item["desc"]
for item in self.coordinator.data.forecast
},
ATTR_... | """Representation of a Meteo-France rain sensor."""
@property
def state(self):
"""Return the state."""
# search first cadran with rain
next_rain = next(
(cadran for cadran in self.coordinator.data.forecast if cadran["rain"] > 1),
None,
)
return (
... | identifier_body |
sensor.py | """Support for Meteo-France raining forecast sensor."""
import logging
from meteofrance_api.helpers import (
get_warning_text_status_from_indice_color,
readeable_phenomenoms_dict,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ATTRIBUTION
from homeassistant.helpers... | (self):
"""Return the unique id."""
return self._unique_id
@property
def name(self):
"""Return the name."""
return self._name
@property
def state(self):
"""Return the state."""
path = SENSOR_TYPES[self._type][ENTITY_API_DATA_PATH].split(":")
data... | unique_id | identifier_name |
main.py | #!/usr/bin/env python2
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>'
import unittest, os, argparse, time, functools
try:
import init_calibre... | ():
return unittest.defaultTestLoader.discover(os.path.dirname(os.path.abspath(__file__)), pattern='*.py')
def run_tests(find_tests=find_tests):
from calibre.gui2 import ensure_app, load_builtin_fonts
ensure_app(), load_builtin_fonts() # needed for dynamic cover generation
parser = argparse.ArgumentPa... | find_tests | identifier_name |
main.py | #!/usr/bin/env python2
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>'
import unittest, os, argparse, time, functools
try:
import init_calibre... |
def find_tests():
return unittest.defaultTestLoader.discover(os.path.dirname(os.path.abspath(__file__)), pattern='*.py')
def run_tests(find_tests=find_tests):
from calibre.gui2 import ensure_app, load_builtin_fonts
ensure_app(), load_builtin_fonts() # needed for dynamic cover generation
parser = arg... | super(TestResult, self).stopTestRun()
if self.wasSuccessful():
tests = sorted(self.times, key=self.times.get, reverse=True)
slowest = ['%s [%g s]' % (t.id(), self.times[t]) for t in tests[:3]]
if len(slowest) > 1:
self.stream.writeln('\nSlowest tests: %s' % ' ... | identifier_body |
main.py | #!/usr/bin/env python2
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>'
import unittest, os, argparse, time, functools
try:
import init_calibre... | r = unittest.TextTestRunner
r.resultclass = TestResult
r(verbosity=4).run(tests)
if __name__ == '__main__':
from calibre.utils.config_base import reset_tweaks_to_default
from calibre.ebooks.metadata.book.base import reset_field_metadata
reset_tweaks_to_default()
reset_field_metadata()
r... | raise SystemExit(1)
tests = ans
else:
tests = unittest.defaultTestLoader.loadTestsFromName(args.name) if args.name else find_tests() | random_line_split |
main.py | #!/usr/bin/env python2
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>'
import unittest, os, argparse, time, functools
try:
import init_calibre... |
tests = ans
else:
tests = unittest.defaultTestLoader.loadTestsFromName(args.name) if args.name else find_tests()
r = unittest.TextTestRunner
r.resultclass = TestResult
r(verbosity=4).run(tests)
if __name__ == '__main__':
from calibre.utils.config_base import reset_tweaks_to_default... | print ('No test named %s found' % args.name)
raise SystemExit(1) | conditional_block |
universal-interceptor.ts | import { Inject, Injectable, Optional } from '@angular/core';
import { HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { REQUEST } from '@nguniversal/express-engine/tokens';
@Injectable()
export class UniversalInterceptor implements HttpInterceptor {
constructor(@Optional() @Inject(R... | (req: HttpRequest<any>, next: HttpHandler) {
if (req.url.includes('http')) {
return next.handle(req);
}
let serverReq: HttpRequest<any> = req;
if (this.request) {
let newUrl = `${this.request.protocol}://${this.request.get('host')}`;
if (!req.url.startsWith('/') && !req.url.startsWith(... | intercept | identifier_name |
universal-interceptor.ts | import { Inject, Injectable, Optional } from '@angular/core';
import { HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { REQUEST } from '@nguniversal/express-engine/tokens';
@Injectable()
export class UniversalInterceptor implements HttpInterceptor {
constructor(@Optional() @Inject(R... |
intercept(req: HttpRequest<any>, next: HttpHandler) {
if (req.url.includes('http')) {
return next.handle(req);
}
let serverReq: HttpRequest<any> = req;
if (this.request) {
let newUrl = `${this.request.protocol}://${this.request.get('host')}`;
if (!req.url.startsWith('/') && !req.ur... | {
} | identifier_body |
universal-interceptor.ts | import { Inject, Injectable, Optional } from '@angular/core';
import { HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { REQUEST } from '@nguniversal/express-engine/tokens';
@Injectable()
export class UniversalInterceptor implements HttpInterceptor {
constructor(@Optional() @Inject(R... |
if (req.url.startsWith('./')) {
newUrl += req.url.slice(1);
} else {
newUrl += req.url;
}
serverReq = req.clone({ url: newUrl });
}
return next.handle(serverReq);
}
}
| {
newUrl += '/';
} | conditional_block |
universal-interceptor.ts | import { Inject, Injectable, Optional } from '@angular/core';
import { HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { REQUEST } from '@nguniversal/express-engine/tokens';
@Injectable()
export class UniversalInterceptor implements HttpInterceptor {
constructor(@Optional() @Inject(R... | newUrl += req.url.slice(1);
} else {
newUrl += req.url;
}
serverReq = req.clone({ url: newUrl });
}
return next.handle(serverReq);
}
} | }
if (req.url.startsWith('./')) { | random_line_split |
EntityCheckboxList.tsx |
import * as React from 'react'
import { classes } from '../Globals'
import * as Finder from '../Finder'
import { FindOptions, ResultRow } from '../FindOptions'
import { TypeContext } from '../TypeContext'
import { TypeReference } from '../Reflection'
import { ModifiableEntity, Lite, Entity, MList, toLite, is, l... |
</div>
);
return (
<fieldset className={classes("sf-checkbox-list", p.ctx.errorClass)} {...{ ...c.baseHtmlAttributes(), ...p.formGroupHtmlAttributes }}>
<legend>
<div>
<span>{p.labelText}</span>
{renderButtons()}
</div>
</legend>
{rende... | {renderCheckboxList()} | identifier_body |
EntityCheckboxList.tsx | import * as React from 'react'
import { classes } from '../Globals'
import * as Finder from '../Finder'
import { FindOptions, ResultRow } from '../FindOptions'
import { TypeContext } from '../TypeContext'
import { TypeReference } from '../Reflection'
import { ModifiableEntity, Lite, Entity, MList, toLite, is, lit... | <input type="checkbox"
className="form-check-input"
checked={checked}
disabled={p.ctx.readOnly}
name={liteKey(row.entity!)}
onChange={e => c.handleOnChange(row.entity!)} />
{p.onRenderItem ? p.onRenderItem(row, i, ch... | return (
<label className="sf-checkbox-element" key={i}>
| random_line_split |
EntityCheckboxList.tsx |
import * as React from 'react'
import { classes } from '../Globals'
import * as Finder from '../Finder'
import { FindOptions, ResultRow } from '../FindOptions'
import { TypeContext } from '../TypeContext'
import { TypeReference } from '../Reflection'
import { ModifiableEntity, Lite, Entity, MList, toLite, is, l... | (state: EntityCheckboxListProps) {
super.getDefaultProps(state);
if (state.ctx.value == null)
state.ctx.value = [];
state.remove = false;
state.create = false;
state.view = false;
state.find = false;
state.columnWidth = 200;
}
handleOnChange = (lite: Lite<Entity>) =... | getDefaultProps | identifier_name |
fslinks_sandbox.js | /**
*
Copyright (C) 2013 FreedomSponsors
The JavaScript code in this page is free software: you can
redistribute it and/or modify it under the terms of the GNU
AFFERO GENERAL PUBLIC LICENSE (GNU AGPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option)
any later v... | (issue){
return "/sandbox/issue"
}
return {
issue_link: issue_link
}
})
| issue_link | identifier_name |
fslinks_sandbox.js | /**
*
Copyright (C) 2013 FreedomSponsors
The JavaScript code in this page is free software: you can
redistribute it and/or modify it under the terms of the GNU
AFFERO GENERAL PUBLIC LICENSE (GNU AGPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option)
any later v... | ERROR: type should be large_string, got " https://github.com/freedomsponsors/www.freedomsponsors.org/blob/master/AGPL_license.txt\n */\n\n\nvar fsapi_mod = angular.module('fslinks', []);\n\nfsapi_mod.factory('FSLinks', function(){\n\n function issue_link(issue){\n return \"/sandbox/issue\"\n }\n\n return {\n issue_link: issue_link\n }\n})" | section 4, provided you include this license notice and a URL
through which recipients can access the Corresponding Source.
For more information, refer to | random_line_split |
fslinks_sandbox.js | /**
*
Copyright (C) 2013 FreedomSponsors
The JavaScript code in this page is free software: you can
redistribute it and/or modify it under the terms of the GNU
AFFERO GENERAL PUBLIC LICENSE (GNU AGPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option)
any later v... |
return {
issue_link: issue_link
}
})
| {
return "/sandbox/issue"
} | identifier_body |
Dropdown_aggregation.graphql.ts | /* tslint:disable */
import { ConcreteFragment } from 'relay-runtime'
export type ArtworkAggregation =
| 'COLOR'
| 'DIMENSION_RANGE'
| 'FOLLOWED_ARTISTS'
| 'GALLERY'
| 'INSTITUTION'
| 'MAJOR_PERIOD'
| 'MEDIUM'
| 'MERCHANDISABLE_ARTISTS'
| 'PARTNER_CITY'
| 'PERIOD'
| 'PRICE_RANGE'
| 'TOTAL'
| ... | readonly name: string | null
readonly id: string
readonly count: number | null
})
| null
> | null
}
const node: ConcreteFragment = {
kind: 'Fragment',
name: 'Dropdown_aggregation',
type: 'ArtworksAggregationResults',
metadata: null,
argumentDefinitions: [],
selections: [... | readonly counts: ReadonlyArray<
| ({ | random_line_split |
index.py | __author__ = 'oier'
import json
from flask import Flask, make_response
app = Flask(__name__)
import seaborn as sns
import numpy as np
import pandas as pd
import os
from datetime import datetime
import matplotlib.pyplot as plt
import sys
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg impo... | (request):
data = load_data()
form = ValueSelector(request)
form.value.choices = [(k,i) for k,i in enumerate(data.columns)]
return(form)
@app.route('/blood', methods=['GET', 'POST'])
def blood():
form = form_values(request.form)
if request.method == 'POST':# and form.validate():
result... | form_values | identifier_name |
index.py | __author__ = 'oier'
import json
from flask import Flask, make_response
app = Flask(__name__)
import seaborn as sns
import numpy as np
import pandas as pd
import os
from datetime import datetime
import matplotlib.pyplot as plt
import sys
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg impo... |
def form_values(request):
data = load_data()
form = ValueSelector(request)
form.value.choices = [(k,i) for k,i in enumerate(data.columns)]
return(form)
@app.route('/blood', methods=['GET', 'POST'])
def blood():
form = form_values(request.form)
if request.method == 'POST':# and form.validate(... | return 'Hello World!' | identifier_body |
index.py | __author__ = 'oier'
import json
from flask import Flask, make_response
app = Flask(__name__)
import seaborn as sns
import numpy as np
import pandas as pd
import os
from datetime import datetime
import matplotlib.pyplot as plt
import sys
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg impo... | return render_template('plot.html',
form=form, result=result)
@app.route('/vib1', methods=['GET', 'POST'])
def vib1():
#form = InputForm(request.form)
form = form_values(request.form)
if request.method == 'POST' and form.validate():
result = compute(form.A.data, form.... | result = None
| random_line_split |
index.py | __author__ = 'oier'
import json
from flask import Flask, make_response
app = Flask(__name__)
import seaborn as sns
import numpy as np
import pandas as pd
import os
from datetime import datetime
import matplotlib.pyplot as plt
import sys
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg impo... |
return render_template('view_plain.html',
form=form, result=result)
if __name__ == '__main__':
app.run() | result = None | conditional_block |
cloudmailru.py | # -*- coding: utf-8 -*-
'''
Specto Add-on
Copyright (C) 2015 lambda
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any l... | (url):
try:
try:
v = url.split('public')[-1]
r = client.request(url)
r = re.sub(r'[^\x00-\x7F]+', ' ', r)
tok = re.findall('"tokens"\s*:\s*{\s*"download"\s*:\s*"([^"]+)', r)[0]
url = re.findall('"weblink_get"\s*:\s*\[.+?"url"\s*:\s*"([^"]+)', r)[0]... | resolve | identifier_name |
cloudmailru.py | # -*- coding: utf-8 -*-
'''
Specto Add-on
Copyright (C) 2015 lambda
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any l... | try:
try:
v = url.split('public')[-1]
r = client.request(url)
r = re.sub(r'[^\x00-\x7F]+', ' ', r)
tok = re.findall('"tokens"\s*:\s*{\s*"download"\s*:\s*"([^"]+)', r)[0]
url = re.findall('"weblink_get"\s*:\s*\[.+?"url"\s*:\s*"([^"]+)', r)[0]
... | identifier_body | |
cloudmailru.py | # -*- coding: utf-8 -*-
'''
Specto Add-on
Copyright (C) 2015 lambda
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any l... | return url
except:
return
except:
return | r = re.sub(r'[^\x00-\x7F]+', ' ', r)
tok = re.findall('"tokens"\s*:\s*{\s*"download"\s*:\s*"([^"]+)', r)[0]
url = re.findall('"weblink_get"\s*:\s*\[.+?"url"\s*:\s*"([^"]+)', r)[0]
url = '%s%s?key=%s' % (url, v, tok)
print("u",url) | random_line_split |
payload.rs | // Copyright 2020 lowRISC contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
}
impl ToWire for Header {
fn to_wire<W: Write>(&self, mut w: W) -> Result<(), ToWireError> {
w.write_be(self.content.to_wire_value())?;
w.write_be(self.content_len)?;
w.write_be(self.checksum)?;
Ok(())
}
}
| {
let content_u8 = r.read_be::<u8>()?;
let content = ContentType::from_wire_value(content_u8).ok_or(FromWireError::OutOfRange)?;
let content_len = r.read_be::<u16>()?;
let checksum = r.read_be::<u8>()?;
Ok(Self {
content,
content_len,
checksum,... | identifier_body |
payload.rs | // Copyright 2020 lowRISC contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
self.crc <<= 1;
}
}
self
}
}
/// Compute the checksum of the given header and payload buffer.
pub fn compute_checksum(header: &Header, payload: &[u8]) -> u8 {
Crc8::init()
.add(&[header.content.to_wire_value()])
.add(&header.content_len.to_be_bytes(... | {
self.crc ^= 0x1070 << 3;
} | conditional_block |
payload.rs | // Copyright 2020 lowRISC contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | Ok(())
}
} | w.write_be(self.content.to_wire_value())?;
w.write_be(self.content_len)?;
w.write_be(self.checksum)?; | random_line_split |
payload.rs | // Copyright 2020 lowRISC contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | (&self) -> u8 {
(self.crc >> 8 & 0xff) as u8
}
/// Adds the specified data to the CRC8 checksum.
/// Taken from
/// https://chromium.googlesource.com/chromiumos/platform/vboot_reference/+/stabilize2/firmware/lib/crc8.c
/// Uses x^8+x^2+x+1 polynomial.
pub fn add(&mut self, data: &[u8]) ... | get | identifier_name |
imce_wysiwyg.js | // $Id: imce_wysiwyg.js,v 1.3.4.1 2010/02/21 00:07:04 sun Exp $
/**
* Wysiwyg API integration helper function.
*/
function imceImageBrowser(field_name, url, type, win) |
/**
* CKeditor integration.
*/
var imceCkeditSendTo = function (file, win) {
var parts = /\?(?:.*&)?CKEditorFuncNum=(\d+)(?:&|$)/.exec(win.location.href);
if (parts && parts.length > 1) {
CKEDITOR.tools.callFunction(parts[1], file.url);
win.close();
}
else {
throw 'CKEditorFuncNum parameter not ... | {
// TinyMCE.
if (win !== 'undefined') {
win.open(Drupal.settings.imce.url + encodeURIComponent(field_name), '', 'width=760,height=560,resizable=1');
}
} | identifier_body |
imce_wysiwyg.js | // $Id: imce_wysiwyg.js,v 1.3.4.1 2010/02/21 00:07:04 sun Exp $
/**
* Wysiwyg API integration helper function.
*/
function imceImageBrowser(field_name, url, type, win) {
// TinyMCE.
if (win !== 'undefined') {
win.open(Drupal.settings.imce.url + encodeURIComponent(field_name), '', 'width=760,height=560,resiza... | */
var imceCkeditSendTo = function (file, win) {
var parts = /\?(?:.*&)?CKEditorFuncNum=(\d+)(?:&|$)/.exec(win.location.href);
if (parts && parts.length > 1) {
CKEDITOR.tools.callFunction(parts[1], file.url);
win.close();
}
else {
throw 'CKEditorFuncNum parameter not found or invalid: ' + win.locat... | * CKeditor integration. | random_line_split |
imce_wysiwyg.js | // $Id: imce_wysiwyg.js,v 1.3.4.1 2010/02/21 00:07:04 sun Exp $
/**
* Wysiwyg API integration helper function.
*/
function imceImageBrowser(field_name, url, type, win) {
// TinyMCE.
if (win !== 'undefined') |
}
/**
* CKeditor integration.
*/
var imceCkeditSendTo = function (file, win) {
var parts = /\?(?:.*&)?CKEditorFuncNum=(\d+)(?:&|$)/.exec(win.location.href);
if (parts && parts.length > 1) {
CKEDITOR.tools.callFunction(parts[1], file.url);
win.close();
}
else {
throw 'CKEditorFuncNum parameter no... | {
win.open(Drupal.settings.imce.url + encodeURIComponent(field_name), '', 'width=760,height=560,resizable=1');
} | conditional_block |
imce_wysiwyg.js | // $Id: imce_wysiwyg.js,v 1.3.4.1 2010/02/21 00:07:04 sun Exp $
/**
* Wysiwyg API integration helper function.
*/
function | (field_name, url, type, win) {
// TinyMCE.
if (win !== 'undefined') {
win.open(Drupal.settings.imce.url + encodeURIComponent(field_name), '', 'width=760,height=560,resizable=1');
}
}
/**
* CKeditor integration.
*/
var imceCkeditSendTo = function (file, win) {
var parts = /\?(?:.*&)?CKEditorFuncNum=(\d+)(... | imceImageBrowser | identifier_name |
remux.rs | #![allow(unused)]
//! Losslessly convert file formats without decoding. I.e. MP4 into something
//! else, without altering the contained video, audio, etc. streams.
//!
//! Tested with this file:
//! * [sintel_trailer-1080p.mp4](https://download.blender.org/durian/trailer/sintel_trailer-1080p.mp4)
//! * sha1: `66798612... | };
use libc::{c_float, c_void, size_t};
use std::convert::AsRef;
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int};
use std::path::{Path, PathBuf};
fn c_str(s: &str) -> CString {
CString::new(s).expect("str to c str")
}
unsafe fn remux(input_path: &str, output_path: &str) {
// I/O
assert!(P... | random_line_split | |
remux.rs | #![allow(unused)]
//! Losslessly convert file formats without decoding. I.e. MP4 into something
//! else, without altering the contained video, audio, etc. streams.
//!
//! Tested with this file:
//! * [sintel_trailer-1080p.mp4](https://download.blender.org/durian/trailer/sintel_trailer-1080p.mp4)
//! * sha1: `66798612... | () {
// HELPER FUNCTION
pub fn path_exists(path: &str) -> bool {
std::fs::metadata(path).is_ok()
}
// CLI Example:
// ```
// cargo run --example remux -- \
// assets/samples/sintel_trailer.1080p.mp4 assets/output/test.mp4
// ```
fn run() -> Result<(), String> {
le... | main | identifier_name |
remux.rs | #![allow(unused)]
//! Losslessly convert file formats without decoding. I.e. MP4 into something
//! else, without altering the contained video, audio, etc. streams.
//!
//! Tested with this file:
//! * [sintel_trailer-1080p.mp4](https://download.blender.org/durian/trailer/sintel_trailer-1080p.mp4)
//! * sha1: `66798612... |
// WRITE OUTPUT
let mut opts: *mut ffmpeg_dev::sys::AVDictionary = std::ptr::null_mut();
ffmpeg_dev::sys::av_dict_set(
&mut opts,
c_str("movflags").as_ptr(),
c_str("frag_keyframe+empty_moov+default_base_moof").as_ptr(),
0,
);
assert!(sys::avformat_write_header(ofmt_... | {
let status = sys::avio_open(
&mut (*ofmt_ctx).pb,
output_path_cstr.as_ptr(),
AVIO_FLAG_WRITE as i32,
);
assert!(status >= 0);
} | conditional_block |
remux.rs | #![allow(unused)]
//! Losslessly convert file formats without decoding. I.e. MP4 into something
//! else, without altering the contained video, audio, etc. streams.
//!
//! Tested with this file:
//! * [sintel_trailer-1080p.mp4](https://download.blender.org/durian/trailer/sintel_trailer-1080p.mp4)
//! * sha1: `66798612... | if !path_exists(input_path) {
return Err(String::from("missing input file"));
}
unsafe {
remux(input_path, output_path);
};
Ok(())
}
match run() {
Ok(()) => (),
Err(msg) => {
eprintln!("[failed] {:?}", msg);
}
... | {
// HELPER FUNCTION
pub fn path_exists(path: &str) -> bool {
std::fs::metadata(path).is_ok()
}
// CLI Example:
// ```
// cargo run --example remux -- \
// assets/samples/sintel_trailer.1080p.mp4 assets/output/test.mp4
// ```
fn run() -> Result<(), String> {
let a... | identifier_body |
Events.spec.ts | import { expect } from "chai";
import Events from "../../components/events/Events";
import * as sinon from "sinon";
describe("Events", () => {
let evt: Events, listener;
before(() => {
evt = new Events("one"); | listener.reset();
});
it("shoud be initialized", () => {
expect(evt).to.exist;
expect(evt.name).to.exist.and.to.be.eql("one");
expect(evt.on).to.exist;
});
it("should use name", () => {
evt.on([evt.name, "test"], listener);
evt.emit("test");
expe... | });
beforeEach(function() {
listener = sinon.stub(); | random_line_split |
ibm_wire.py |
# *****************************************************************
# Copyright (c) 2013 Massachusetts Institute of Technology
#
# Developed exclusively at US Government expense under US Air Force contract
# FA8721-05-C-002. The rights of the United States Government to use, modify,
# reproduce, release, perform, disp... | """Initializes the wire with the display name and circuit specified."""
ico.IBMCircuitObject.__init__(self, displayname, 0.0, 0, circuit) | identifier_body | |
ibm_wire.py |
# *****************************************************************
# Copyright (c) 2013 Massachusetts Institute of Technology
#
# Developed exclusively at US Government expense under US Air Force contract
# FA8721-05-C-002. The rights of the United States Government to use, modify,
# reproduce, release, perform, disp... | (self, displayname, circuit):
"""Initializes the wire with the display name and circuit specified."""
ico.IBMCircuitObject.__init__(self, displayname, 0.0, 0, circuit)
| __init__ | identifier_name |
ibm_wire.py | # *****************************************************************
# Copyright (c) 2013 Massachusetts Institute of Technology
#
# Developed exclusively at US Government expense under US Air Force contract
# FA8721-05-C-002. The rights of the United States Government to use, modify,
# reproduce, release, perform, displ... | # Project: SPAR
# Authors: SY
# Description: IBM TA2 wire class
#
# Modifications:
# Date Name Modification
# ---- ---- ------------
# 22 Oct 2012 SY Original Version
# *************************************************************... | # Unrestricted and Unlimited.
#
# Licensed for use under the BSD License as described in the BSD-LICENSE.txt
# file in the root directory of this release.
# | random_line_split |
plot_55_setting_eeg_reference.py | Since
this tutorial deals specifically with EEG, we'll also restrict the dataset to
just a few EEG channels so the plots are easier to see:
"""
import os
import mne
sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
... |
###############################################################################
# EEG reference and source modeling
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# If you plan to perform source modeling (either with EEG or combined EEG/MEG
# data), it is **strongly recommended** to use the
# average-reference-as-projection a... | fig = raw.plot(proj=proj, n_channels=len(raw))
# make room for title
fig.subplots_adjust(top=0.9)
fig.suptitle('{} reference'.format(title), size='xx-large', weight='bold') | conditional_block |
plot_55_setting_eeg_reference.py | Since
this tutorial deals specifically with EEG, we'll also restrict the dataset to
just a few EEG channels so the plots are easier to see:
"""
import os
import mne
sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
... |
###############################################################################
# EEG reference and source modeling
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# If you plan to perform source modeling (either with EEG or combined EEG/MEG
# data), it is **strongly recommended** to use the
# average-reference-as-projection ap... | fig.subplots_adjust(top=0.9)
fig.suptitle('{} reference'.format(title), size='xx-large', weight='bold') | random_line_split |
term-group.tsx | import React from 'react';
import {connect} from 'react-redux';
import {decorate, getTermProps, getTermGroupProps} from '../utils/plugins';
import {resizeTermGroup} from '../actions/term-groups';
import Term_ from './term';
import SplitPane_ from './split-pane';
import {HyperState, HyperDispatch, TermGroupProps, TermGr... | }
return map[uid];
}
renderSplit(groups: JSX.Element[]) {
const [first, ...rest] = groups;
if (rest.length === 0) {
return first;
}
const direction = this.props.termGroup.direction!.toLowerCase() as 'horizontal' | 'vertical';
return (
<SplitPane
direction={direction... | this.bound.set(fn, {});
}
const map = this.bound.get(fn)!;
if (!map[uid]) {
map[uid] = fn.bind(thisObj, uid); | random_line_split |
term-group.tsx | import React from 'react';
import {connect} from 'react-redux';
import {decorate, getTermProps, getTermGroupProps} from '../utils/plugins';
import {resizeTermGroup} from '../actions/term-groups';
import Term_ from './term';
import SplitPane_ from './split-pane';
import {HyperState, HyperDispatch, TermGroupProps, TermGr... |
onTermRef = (uid: string, term: Term_ | null) => {
this.term = term;
this.props.ref_(uid, term);
};
renderTerm(uid: string) {
const session = this.props.sessions[uid];
const termRef = this.props.terms[uid];
const props = getTermProps(uid, this.props, {
isTermActive: uid === this.props... | {
const [first, ...rest] = groups;
if (rest.length === 0) {
return first;
}
const direction = this.props.termGroup.direction!.toLowerCase() as 'horizontal' | 'vertical';
return (
<SplitPane
direction={direction}
sizes={this.props.termGroup.sizes}
onResize={this.p... | identifier_body |
term-group.tsx | import React from 'react';
import {connect} from 'react-redux';
import {decorate, getTermProps, getTermGroupProps} from '../utils/plugins';
import {resizeTermGroup} from '../actions/term-groups';
import Term_ from './term';
import SplitPane_ from './split-pane';
import {HyperState, HyperDispatch, TermGroupProps, TermGr... |
return map[uid];
}
renderSplit(groups: JSX.Element[]) {
const [first, ...rest] = groups;
if (rest.length === 0) {
return first;
}
const direction = this.props.termGroup.direction!.toLowerCase() as 'horizontal' | 'vertical';
return (
<SplitPane
direction={direction}
... | {
map[uid] = fn.bind(thisObj, uid);
} | conditional_block |
term-group.tsx | import React from 'react';
import {connect} from 'react-redux';
import {decorate, getTermProps, getTermGroupProps} from '../utils/plugins';
import {resizeTermGroup} from '../actions/term-groups';
import Term_ from './term';
import SplitPane_ from './split-pane';
import {HyperState, HyperDispatch, TermGroupProps, TermGr... | (props: TermGroupProps, context: any) {
super(props, context);
this.bound = new WeakMap();
}
bind<T extends (uid: string, ...args: any[]) => any>(
fn: T,
thisObj: any,
uid: string
): (...args: T extends (uid: string, ..._args: infer I) => any ? I : never) => ReturnType<T> {
if (!this.boun... | constructor | identifier_name |
MSVSUserFile.py | #!/usr/bin/python2.4
# Copyright (c) 2009 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Visual Studio user preferences file writer."""
import common
import os
import re
import socket # for gethostname
import xml.dom
import xm... | (self, config_name, command, environment = {},
working_directory=""):
"""Adds a DebugSettings node to the user file for a particular config.
Args:
command: command line to run. First element in the list is the
executable. All elements of the command will be quoted if
... | AddDebugSettings | identifier_name |
MSVSUserFile.py | #!/usr/bin/python2.4
# Copyright (c) 2009 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Visual Studio user preferences file writer."""
import common
import os
import re
import socket # for gethostname
import xml.dom
import xm... |
def AddDebugSettings(self, config_name, command, environment = {},
working_directory=""):
"""Adds a DebugSettings node to the user file for a particular config.
Args:
command: command line to run. First element in the list is the
executable. All elements of the comma... | """Adds a configuration to the project.
Args:
name: Configuration name.
"""
self._AddConfigToNode(self.n_configs, 'Configuration', name) | identifier_body |
MSVSUserFile.py | #!/usr/bin/python2.4
# Copyright (c) 2009 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Visual Studio user preferences file writer."""
import common
import os
import re
import socket # for gethostname
import xml.dom
import xm... |
return command
def _QuoteWin32CommandLineArgs(args):
new_args = []
for arg in args:
# Replace all double-quotes with double-double-quotes to escape
# them for cmd shell, and then quote the whole thing if there
# are any.
if arg.find('"') != -1:
arg = '""'.join(arg.split('"'))
arg = '... | item = os.path.join(path, command)
if os.path.isfile(item) and os.access(item, os.X_OK):
return item | conditional_block |
MSVSUserFile.py | #!/usr/bin/python2.4
# Copyright (c) 2009 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Visual Studio user preferences file writer."""
import common
import os
import re | #------------------------------------------------------------------------------
def _FindCommandInPath(command):
"""If there are no slashes in the command given, this function
searches the PATH env to find the given command, and converts it
to an absolute path. We have to do this because MSVS is looking
... | import socket # for gethostname
import xml.dom
import xml_fix
| random_line_split |
py-finish-breakpoint2.py | # Copyright (C) 2011-2016 Free Software Foundation, Inc.
# 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 progr... | class ExceptionFinishBreakpoint(gdb.FinishBreakpoint):
def __init__(self, frame):
gdb.FinishBreakpoint.__init__ (self, frame, internal=1)
self.silent = True
print ("init ExceptionFinishBreakpoint")
def stop(self):
print ("stopped at ExceptionFinishBreakpoint")
re... | # Breakpoints.
| random_line_split |
py-finish-breakpoint2.py | # Copyright (C) 2011-2016 Free Software Foundation, Inc.
# 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 progr... | (self, frame):
gdb.FinishBreakpoint.__init__ (self, frame, internal=1)
self.silent = True
print ("init ExceptionFinishBreakpoint")
def stop(self):
print ("stopped at ExceptionFinishBreakpoint")
return True
def out_of_scope(self):
print ("exception d... | __init__ | identifier_name |
py-finish-breakpoint2.py | # Copyright (C) 2011-2016 Free Software Foundation, Inc.
# 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 progr... |
print ("Python script imported")
| print ("exception did not finish ...") | identifier_body |
htmldlistelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLDListElementBinding;
use dom::bindings::js::Root;
use dom::bindings::str... | (local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLDListElement> {
Node::reflect_node(box HTMLDListElement::new_inherited(local_name, prefix, document),
document,
HTMLDListElementBinding::Wrap)
... | new | identifier_name |
htmldlistelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLDListElementBinding;
use dom::bindings::js::Root;
use dom::bindings::str... | }
} | random_line_split | |
htmldlistelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLDListElementBinding;
use dom::bindings::js::Root;
use dom::bindings::str... |
}
| {
Node::reflect_node(box HTMLDListElement::new_inherited(local_name, prefix, document),
document,
HTMLDListElementBinding::Wrap)
} | identifier_body |
hash.rs |
}
/// A Bitcoin hash, 32-bytes, computed from x as SHA256(SHA256(x))
pub struct Sha256dHash([u8; 32]);
impl_array_newtype!(Sha256dHash, u8, 32);
/// A RIPEMD-160 hash
pub struct Ripemd160Hash([u8; 20]);
impl_array_newtype!(Ripemd160Hash, u8, 20);
/// A Bitcoin hash160, 20-bytes, computed from x as RIPEMD160(SHA256(... | {
match *self {
HexError::BadLength(_) => "sha256d hex string non-64 length",
HexError::BadCharacter(_) => "sha256d bad hex character"
}
} | identifier_body | |
hash.rs | 8-bit hash obtained by truncating a real hash
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct Hash48((u8, u8, u8, u8, u8, u8));
/// A 64-bit hash obtained by truncating a real hash
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct Hash64((u8, u8, u8, u8, u8, u8, u8, u8));
impl Ripemd160Hash {
/// Cr... | for x in (&mut ret).iter_mut() { *x = x.to_le(); }
Uint256(ret)
}
/// Converts a hash to a big-endian Uint256
#[inline]
pub fn into_be(self) -> Uint256 {
let Sha256dHash(mut data) = self;
data.reverse();
let mut ret: [u64; 4] = unsafe { mem::transmute(data) };
... | pub fn into_le(self) -> Uint256 {
let Sha256dHash(data) = self;
let mut ret: [u64; 4] = unsafe { mem::transmute(data) }; | random_line_split |
hash.rs | ([u8; 32]);
impl_array_newtype!(Sha256dHash, u8, 32);
/// A RIPEMD-160 hash
pub struct Ripemd160Hash([u8; 20]);
impl_array_newtype!(Ripemd160Hash, u8, 20);
/// A Bitcoin hash160, 20-bytes, computed from x as RIPEMD160(SHA256(x))
pub struct Hash160([u8; 20]);
impl_array_newtype!(Hash160, u8, 20);
/// A 32-bit hash ob... | Sha256dHash | identifier_name | |
revision.js | /* Canvas history */
//TODO: This could probably use another rewrite, it really sucks
function addChange() {
currentChange++;
if (currentChange != changes.length) {
changes.splice(currentChange, changes.length - currentChange);
}
changes.push({ layer: currentLayer, context: layers[currentLaye... | }
function redo() {
if (currentChange < changes.length - 1) {
currentChange++;
updateCanvas();
}
}
function updateCanvas() {
var newElement = changes[currentChange];
var newLayer = layers[newElement.layer];
clearCanvas(newLayer);
var img = new Image();
img.src = newElement... | } | random_line_split |
revision.js | /* Canvas history */
//TODO: This could probably use another rewrite, it really sucks
function addChange() {
currentChange++;
if (currentChange != changes.length) {
changes.splice(currentChange, changes.length - currentChange);
}
changes.push({ layer: currentLayer, context: layers[currentLaye... | else { //Hack to allow undoing to blankness
for (var i = 0; i < layers.length; i++) {
clearCanvas(layers[i]);
}
clearCanvas($('#background').get(0));
console.log(currentChange);
}
}
function redo() {
if (currentChange < changes.length - 1) {
currentChange++;... | {
currentChange--;
updateCanvas();
console.log(currentChange);
} | conditional_block |
revision.js | /* Canvas history */
//TODO: This could probably use another rewrite, it really sucks
function addChange() {
currentChange++;
if (currentChange != changes.length) {
changes.splice(currentChange, changes.length - currentChange);
}
changes.push({ layer: currentLayer, context: layers[currentLaye... | () {
var newElement = changes[currentChange];
var newLayer = layers[newElement.layer];
clearCanvas(newLayer);
var img = new Image();
img.src = newElement.context;
newLayer.getContext('2d').globalCompositeOperation = "source-over";
newLayer.getContext('2d').globalAlpha = 1;
newLayer.get... | updateCanvas | identifier_name |
revision.js | /* Canvas history */
//TODO: This could probably use another rewrite, it really sucks
function addChange() |
function undo() {
if (currentChange > 0) {
currentChange--;
updateCanvas();
console.log(currentChange);
} else { //Hack to allow undoing to blankness
for (var i = 0; i < layers.length; i++) {
clearCanvas(layers[i]);
}
clearCanvas($('#background').get... | {
currentChange++;
if (currentChange != changes.length) {
changes.splice(currentChange, changes.length - currentChange);
}
changes.push({ layer: currentLayer, context: layers[currentLayer].toDataURL() });
console.log(currentChange);
} | identifier_body |
node-ipc-tests.ts | import { Socket } from "net";
import RawIPC = require("node-ipc");
let ipc = new RawIPC.IPC();
ipc = RawIPC;
ipc.config.appspace = "./x";
ipc.config.encoding = "base64";
ipc.config.id = "id1";
ipc.config.interfaces = {
localAddress: true,
family: true,
hints: false,
localPort: true,
lookup: false,
}... | ipc.config.socketRoot = "";
ipc.config.stopRetrying = false;
ipc.config.sync = true;
ipc.config.tls = {
rejectUnauthorized: false,
public: "",
private: "",
};
ipc.connectTo("world");
ipc.connectTo("world", () => { });
ipc.connectTo("id1", "path1", () => { });
ipc.connectToNet("world");
ipc.connectToNet("wor... | ipc.config.rawBuffer = true;
ipc.config.retry = 1000;
ipc.config.silent = true; | random_line_split |
extended_encoder.py | #!/usr/bin/env python
#
# Copyright 2014 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
from __future__ import absolute_import
from __future__ import unicode_literals
from gnuradio import gr, blocks
from . import fec_swig as fec
from .threaded_enco... |
if fec.get_encoder_output_conversion(encoder_obj_list[0]) == "packed_bits":
self.blocks.append(blocks.packed_to_unpacked_bb(1, gr.GR_MSB_FIRST))
if self.puncpat != '11':
self.blocks.append(fec.puncture_bb(len(puncpat), read_bitlist(puncpat), 0))
# Connect the input to... | self.blocks.append(fec.encoder(encoder_obj_list[0],
gr.sizeof_char,
gr.sizeof_char)) | conditional_block |
extended_encoder.py | #!/usr/bin/env python
#
# Copyright 2014 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
from __future__ import absolute_import
from __future__ import unicode_literals
from gnuradio import gr, blocks
from . import fec_swig as fec
from .threaded_enco... | # the encoder.
for i in range(len(self.blocks) - 1):
self.connect((self.blocks[i], 0), (self.blocks[i+1], 0)); | random_line_split | |
extended_encoder.py | #!/usr/bin/env python
#
# Copyright 2014 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
from __future__ import absolute_import
from __future__ import unicode_literals
from gnuradio import gr, blocks
from . import fec_swig as fec
from .threaded_enco... | gr.sizeof_char,
gr.sizeof_char))
elif threading == 'ordinary':
self.blocks.append(threaded_encoder(encoder_obj_list,
gr.sizeof_char,
... | gr.hier_block2.__init__(self, "extended_encoder",
gr.io_signature(1, 1, gr.sizeof_char),
gr.io_signature(1, 1, gr.sizeof_char))
self.blocks=[]
self.puncpat=puncpat
if(type(encoder_obj_list) == list):
if(type(encoder_ob... | identifier_body |
extended_encoder.py | #!/usr/bin/env python
#
# Copyright 2014 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
from __future__ import absolute_import
from __future__ import unicode_literals
from gnuradio import gr, blocks
from . import fec_swig as fec
from .threaded_enco... | (self, encoder_obj_list, threading, puncpat=None):
gr.hier_block2.__init__(self, "extended_encoder",
gr.io_signature(1, 1, gr.sizeof_char),
gr.io_signature(1, 1, gr.sizeof_char))
self.blocks=[]
self.puncpat=puncpat
if(type... | __init__ | identifier_name |
socket.rs | use chan::{self, Sender, Receiver};
use json;
use serde::ser::Serialize;
use std::io::{BufReader, Read, Write};
use std::net::Shutdown;
use std::{fs, thread};
use unix_socket::{UnixListener, UnixStream};
use datatype::{Command, DownloadFailed, Error, Event};
use gateway::Gateway;
use interpreter::CommandExec;
/// Th... |
Event::DownloadFailed(id, reason) => {
EventWrapper::new("DownloadFailed", DownloadFailed { update_id: id, reason: reason }).to_json()
}
_ => return
};
let _ = UnixStream::connect(ev_sock)
.map_err(|err| debug!("skipping event socket broadcast: {}", err))
... | {
EventWrapper::new("DownloadComplete", dl).to_json()
} | conditional_block |
socket.rs | use chan::{self, Sender, Receiver};
use json;
use serde::ser::Serialize;
use std::io::{BufReader, Read, Write};
use std::net::Shutdown;
use std::{fs, thread};
use unix_socket::{UnixListener, UnixStream};
use datatype::{Command, DownloadFailed, Error, Event};
use gateway::Gateway;
use interpreter::CommandExec;
/// Th... | (ev_sock: &str, event: Event) {
let reply = match event {
Event::DownloadComplete(dl) => {
EventWrapper::new("DownloadComplete", dl).to_json()
}
Event::DownloadFailed(id, reason) => {
EventWrapper::new("DownloadFailed", DownloadFailed { update_id: id, reason: reason ... | handle_event | identifier_name |
socket.rs | use chan::{self, Sender, Receiver};
use json;
use serde::ser::Serialize;
use std::io::{BufReader, Read, Write};
use std::net::Shutdown;
use std::{fs, thread};
use unix_socket::{UnixListener, UnixStream};
use datatype::{Command, DownloadFailed, Error, Event};
use gateway::Gateway;
use interpreter::CommandExec;
/// Th... |
}
fn handle_stream(mut stream: UnixStream, ctx: &Sender<CommandExec>) {
info!("New socket connection.");
let resp = parse_command(&mut stream, ctx)
.map(|ev| json::to_vec(&ev).expect("couldn't encode Event"))
.unwrap_or_else(|err| format!("{}", err).into_bytes());
stream.write_all(&resp)... | {
info!("Listening for commands at socket {}", self.cmd_sock);
info!("Sending events to socket {}", self.ev_sock);
let _ = fs::remove_file(&self.cmd_sock);
let cmd_sock = UnixListener::bind(&self.cmd_sock).expect("command socket");
let ev_sock = self.ev_sock.clone();
thr... | identifier_body |
socket.rs | use chan::{self, Sender, Receiver};
use json;
use serde::ser::Serialize;
use std::io::{BufReader, Read, Write};
use std::net::Shutdown;
use std::{fs, thread};
use unix_socket::{UnixListener, UnixStream};
use datatype::{Command, DownloadFailed, Error, Event};
use gateway::Gateway;
use interpreter::CommandExec;
/// Th... | #[test]
fn socket_commands_and_events() {
let (ctx, crx) = chan::sync::<CommandExec>(0);
let (etx, erx) = chan::sync::<Event>(0);
let mut socket = Socket { cmd_sock: CMD_SOCK.into(), ev_sock: EV_SOCK.into() };
thread::spawn(move || socket.start(ctx, erx));
let _ = fs::re... | random_line_split | |
helpers.py | 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 Licens... |
def generate_data_table_schema(config, table, schema_override=None):
"""Generate the schema for data table in terraform
Args:
config (CLIConfig): Loaded StreamAlert config
table (string): The name of data table
Returns:
athena_schema (dict): Equivalent Athena schema used for gen... | """Generate the schema for alerts table in terraform by using a fake alert
Returns:
athena_schema (dict): Equivalent Athena schema used for generating create table statement
"""
alert = Alert('temp_rule_name', {}, {})
output = alert.output_dict()
schema = record_to_schema(output)
athena... | identifier_body |
helpers.py | 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 Licens... | (query_result):
"""Simplify Athena query results into a set of values.
Useful for listing tables, partitions, databases, enable_metrics
Args:
query_result (dict): The result of run_athena_query
Returns:
set: Unique values from the query result
"""
return {
value
... | unique_values_from_query | identifier_name |
helpers.py | 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 Licens... |
fmt_values.update(parts.groupdict())
partition_stmt = PARTITION_STMT.format(**fmt_values)
partition_stmt_len = len(partition_stmt)
# It will add a space between sub strings when join the whole statement
space_count = len(statement)
# Monitor the lenght of whole statem... | continue | conditional_block |
helpers.py | 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 Licens... |
athena_schema = logs_schema_to_athena_schema(sanitized_schema, False)
# Add envelope keys to Athena Schema
configuration_options = log_info.get('configuration')
if configuration_options:
envelope_keys = configuration_options.get('envelope_keys')
if envelope_keys:
sanitized_... | sanitized_schema = FirehoseClient.sanitize_keys(schema) | random_line_split |
XiteQt.py | # -*- coding: utf-8 -*-
import ctypes, os, sys, unittest
from PySide.QtCore import *
from PySide.QtGui import *
import ScintillaCallable
sys.path.append("..")
from bin import ScintillaEditPy
scintillaDirectory = ".."
scintillaIncludeDirectory = os.path.join(scintillaDirectory, "include")
sys.path.app... | (self, test=""):
self.face = Face.Face()
self.face.ReadFromFile(os.path.join(scintillaIncludeDirectory, "Scintilla.iface"))
self.test = test
self.form = Form()
scifn = self.form.edit.send(int(self.face.features["GetDirectFunction"]["Value"]), 0, 0)
sciptr = ctypes.c_char_p(self.form.edit.send(
... | __init__ | identifier_name |
XiteQt.py | # -*- coding: utf-8 -*-
import ctypes, os, sys, unittest
from PySide.QtCore import *
from PySide.QtGui import *
import ScintillaCallable
sys.path.append("..")
from bin import ScintillaEditPy
scintillaDirectory = ".."
scintillaIncludeDirectory = os.path.join(scintillaDirectory, "include")
sys.path.app... | xiteFrame.DoStuff()
sys.exit(app.exec_()) | random_line_split | |
XiteQt.py | # -*- coding: utf-8 -*-
import ctypes, os, sys, unittest
from PySide.QtCore import *
from PySide.QtGui import *
import ScintillaCallable
sys.path.append("..")
from bin import ScintillaEditPy
scintillaDirectory = ".."
scintillaIncludeDirectory = os.path.join(scintillaDirectory, "include")
sys.path.app... |
def DoEvents(self):
QApplication.processEvents()
def CmdTest(self):
runner = unittest.TextTestRunner()
tests = unittest.defaultTestLoader.loadTestsFromName(self.test)
results = runner.run(tests)
print(results)
sys.exit(0)
xiteFrame = None
def main(test):
global xiteFrame
app = QAppl... | print(self.test)
self.CmdTest() | identifier_body |
tcm_client.py | # -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... | raise
else:
raise TencentCloudSDKException(e.message, e.message) | :param request: Request instance for DescribeMeshList.
:type request: :class:`tencentcloud.tcm.v20210413.models.DescribeMeshListRequest`
:rtype: :class:`tencentcloud.tcm.v20210413.models.DescribeMeshListResponse`
"""
try:
params = request._serialize()
body... | identifier_body |
tcm_client.py | # -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... | eption(e.message, e.message) | conditional_block | |
tcm_client.py | # -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... |
"""
try:
params = request._serialize()
body = self.call("DescribeMeshList", params)
response = json.loads(body)
if "Error" not in response["Response"]:
model = models.DescribeMeshListResponse()
model._deserialize(response["... | :param request: Request instance for DescribeMeshList.
:type request: :class:`tencentcloud.tcm.v20210413.models.DescribeMeshListRequest`
:rtype: :class:`tencentcloud.tcm.v20210413.models.DescribeMeshListResponse` | random_line_split |
tcm_client.py | # -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... | (self, request):
"""查询网格详情
:param request: Request instance for DescribeMesh.
:type request: :class:`tencentcloud.tcm.v20210413.models.DescribeMeshRequest`
:rtype: :class:`tencentcloud.tcm.v20210413.models.DescribeMeshResponse`
"""
try:
params = request._ser... | DescribeMesh | identifier_name |
dfa_builder.rs | //
// Copyright 2016 Andrew Hunter
//
// 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... | //!
//! The DFA builder trait is implemented by classes that initialise DFAs. Deterministic Finite Automata can act as pattern
//! matchers: for any given state, they only have a single possible transition for each input symbol. They can be efficiently
//! implemented using a table-based approach.
//!
//! The main type... | // 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.
//
| random_line_split |
capture_actor.rs | ::codec::length_delimited;
use uuid::Uuid;
use crate::capture_supervisor::{CaptureActorMetrics, StopCaptureWorker};
use crate::db_registry;
use crate::models::{CreateVideoUnitFile, UpdateVideoUnitFile};
use crate::ws_camera_server::{CameraFrame, FrameResolution, FrameSource, WsCameraServer};
/*
/// Holds messages fro... |
fn finished(&mut self, _ctx: &mut Self::Context) {
info!("Stream handler finished!");
}
}
/// Message for capture actor to start worker
#[derive(Message)]
#[rtype(result = "()")]
struct StartWorker;
impl Handler< | {
let item = match item {
Ok(b) => b,
Err(e) => {
debug!("stream handle error! {}", e);
self.stdin = None;
ctx.terminate();
return;
}
};
let frame: Result<CaptureMessage, bincode::Error> = bincode... | identifier_body |
capture_actor.rs | ::codec::length_delimited;
use uuid::Uuid;
use crate::capture_supervisor::{CaptureActorMetrics, StopCaptureWorker};
use crate::db_registry;
use crate::models::{CreateVideoUnitFile, UpdateVideoUnitFile};
use crate::ws_camera_server::{CameraFrame, FrameResolution, FrameSource, WsCameraServer};
/*
/// Holds messages fro... | }
/// Processes a `CaptureMessage` from the capture worker,
/// performing the appropriate action.
#[allow(clippy::panic)]
fn message_to_action(&mut self, msg: CaptureMessage, ctx: &mut Context<Self>) {
// Check if log
match msg {
CaptureMessage::Log { message } => {
... | error!("Error closing file!");
} | random_line_split |
capture_actor.rs | ::codec::length_delimited;
use uuid::Uuid;
use crate::capture_supervisor::{CaptureActorMetrics, StopCaptureWorker};
use crate::db_registry;
use crate::models::{CreateVideoUnitFile, UpdateVideoUnitFile};
use crate::ws_camera_server::{CameraFrame, FrameResolution, FrameSource, WsCameraServer};
/*
/// Holds messages fro... | (&self, ctx: &mut Context<Self>, filename: &str, end_time: DateTime<Utc>) {
if let (Some(video_unit_id), Some(video_file_id), Ok(metadata)) = (
self.video_unit_id,
self.video_file_id,
fs::metadata(filename),
) {
let fut = db_registry::get_db().send(UpdateV... | close_file | identifier_name |
__openerp__.py | ###############################################################################
#
# Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
# This program 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 ... |
'bom_explode_view.xml',
'report/explode_report.xml',
'wizard/report_component_status.xml',
#'scheduler.xml',
],
'active': False,
'installable': True,
'auto_install': False,
} | 'init_xml': [],
'demo': [],
'data': [
#'security/xml_groups.xml',
#'security/ir.model.access.csv', | random_line_split |
license_wizard.js | var currentLicenseStep = $("[data-step=1A]")
var licenseWizard = $('#license-wizard')
var buttons = $('.license-wizard-step button')
$('#show-license-wizard').click(function(event){
event.preventDefault()
if (licenseWizard.hasClass('hidden')) {
licenseWizard.removeClass('hidden')
} else {
close()
}
})
... | () {
loadStep('1A')
}
function loadStep(id) {
var nextStep = $("[data-step=" + id + "]")
currentLicenseStep.addClass('hidden')
nextStep.removeClass('hidden')
currentLicenseStep = nextStep
} | restart | identifier_name |
license_wizard.js | var currentLicenseStep = $("[data-step=1A]")
var licenseWizard = $('#license-wizard')
var buttons = $('.license-wizard-step button')
$('#show-license-wizard').click(function(event){
event.preventDefault()
if (licenseWizard.hasClass('hidden')) {
licenseWizard.removeClass('hidden')
} else {
close()
}
})
... | function loadStep(id) {
var nextStep = $("[data-step=" + id + "]")
currentLicenseStep.addClass('hidden')
nextStep.removeClass('hidden')
currentLicenseStep = nextStep
} | random_line_split | |
license_wizard.js | var currentLicenseStep = $("[data-step=1A]")
var licenseWizard = $('#license-wizard')
var buttons = $('.license-wizard-step button')
$('#show-license-wizard').click(function(event){
event.preventDefault()
if (licenseWizard.hasClass('hidden')) {
licenseWizard.removeClass('hidden')
} else {
close()
}
})
... | else if (action == 'close') {
close()
} else if (nextStep) {
loadStep(nextStep)
}
})
})
function close() {
licenseWizard.addClass('hidden')
loadStep('1A')
}
function restart() {
loadStep('1A')
}
function loadStep(id) {
var nextStep = $("[data-step=" + id + "]")
currentLicenseStep.add... | {
restart()
} | conditional_block |
license_wizard.js | var currentLicenseStep = $("[data-step=1A]")
var licenseWizard = $('#license-wizard')
var buttons = $('.license-wizard-step button')
$('#show-license-wizard').click(function(event){
event.preventDefault()
if (licenseWizard.hasClass('hidden')) {
licenseWizard.removeClass('hidden')
} else {
close()
}
})
... | {
var nextStep = $("[data-step=" + id + "]")
currentLicenseStep.addClass('hidden')
nextStep.removeClass('hidden')
currentLicenseStep = nextStep
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.