text
stringlengths 2
1.04M
| meta
dict |
---|---|
<?php
namespace LaPoiz\WindBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use LaPoiz\WindBundle\Form\DataWindPrevType;
use LaPoiz\WindBundle\Entity\Spot;
use LaPoiz\WindBundle\Entity\DataWindPrev;
use LaPoiz\WindBundle\Entity\PrevisionDate;
use LaPoiz\WindBundle\core\websiteDataManage\WindguruGetData;
use LaPoiz\WindBundle\core\websiteDataManage\MeteoFranceGetData;
use LaPoiz\WindBundle\core\websiteDataManage\MeteorologicGetData;
use LaPoiz\WindBundle\core\WindData;
use SaadTazi\GChartBundle\DataTable;
use SaadTazi\GChartBundle\Chart\PieChart;
class AjaxDataWindPrevController extends Controller
{
/**
* @Template()
*/
// for testing: http://localhost/WindServer/web/app_dev.php/ajax/dataWindPrev/edit/2
public function ajaxEditAction($id=null)
{
if (isset($id)) {
$em = $this->container->get('doctrine.orm.entity_manager');
$dataWindPrev = $em->find('LaPoizWindBundle:DataWindPrev', $id);
if (!$dataWindPrev)
{
return $this->container->get('templating')->renderResponse(
'LaPoizWindBundle:Default:errorBlock.html.twig',
array('errMessage' => "No dataWindPrev find !"));
}
$form=$this->createForm(new DataWindPrevType(), $dataWindPrev);
return $this->render('LaPoizWindBundle:DataWindPrev:blockEdit.html.twig', array(
'dataWindPrev' => $dataWindPrev,
'form' => $form->createView()
));
} else {
return $this->container->get('templating')->renderResponse(
'LaPoizWindBundle:Default:errorPage.html.twig',
array( 'errMessage' => "Error bad parameter (dataWindPrev.id miss)" ));
}
}
/**
* @Template()
*/
// for testing: http://localhost/WindServer/web/app_dev.php/ajax/dataWindPrev/history/data/2
public function historyDataAction($id=null)
{
$message='';
if (isset($id)) {
$date=date('Y-m-d');
$result=$this->historyDataForDatePrev($id,$date);
return $this->container->get('templating')->renderResponse(
'LaPoizWindBundle:Ajax:dataWindPrevHistoryData.html.twig',
$result);
} else {
return $this->container->get('templating')->renderResponse(
'LaPoizWindBundle:Default:errorPage.html.twig',
array( 'errMessage' => "Error bad parameter (dataWindPrev.id miss)" ));
}
}
/**
* @Template()
*/
// for testing: http://localhost/WindServer/web/app_dev.php/spot/ajax/dataWindPrev/history/data/date_prev/2/2013-10-10
public function spotHistoryDataForDatePrevAction($id=null,$date=null)
{
$message='';
if (isset($id)) {
$result=$this->historyDataForDatePrev($id,$date);
return $this->container->get('templating')->renderResponse(
'LaPoizWindBundle:Spot:Ajax/blockHistoryPrevisionForOneDate.html.twig',
$result);
} else {
return $this->container->get('templating')->renderResponse(
'LaPoizWindBundle:Default:errorPage.html.twig',
array( 'errMessage' => "Error bad parameter (dataWindPrev.id miss)" ));
}
}
/**
* @Template()
*/
// for testing: http://localhost/WindServer/web/app_dev.php/ajax/dataWindPrev/history/data/date_prev/2/2012-02-25
public function historyDataForDatePrevAction($id=null,$date=null)
{
$message='';
if (isset($id)) {
$result=$this->historyDataForDatePrev($id,$date);
return $this->container->get('templating')->renderResponse(
'LaPoizWindBundle:Ajax:blockHistoryDataDisplayInfo.html.twig',
$result);
} else {
return $this->container->get('templating')->renderResponse(
'LaPoizWindBundle:Default:errorPage.html.twig',
array( 'errMessage' => "Error bad parameter (dataWindPrev.id miss)" ));
}
}
public function historyDataForDatePrev($id,$date) {
$date = $this->getDateGoodFormat($date);
$em = $this->container->get('doctrine.orm.entity_manager');
$dataWindPrev = $em->find('LaPoizWindBundle:DataWindPrev', $id);
$listPrevisionDate = $this->getDoctrine()
->getRepository('LaPoizWindBundle:PrevisionDate')
->getFromOneWebSiteForOneDay($id,$date);
return array('date' => $date ,
'dataWindPrev' => $dataWindPrev,
'listPrevisionDate' =>$listPrevisionDate);
}
private function getDateGoodFormat($date) {
$dateTime = null;
$date = trim($date);
if (preg_match( '`^\d{4}-\d{1,2}-\d{1,2}$`' , $date ))
return $date;
elseif (preg_match( '`^\d{1,2}/\d{1,2}/\d{4}$`' , $date ))
$dateTime = \DateTime::createFromFormat('d/m/Y', $date);
elseif (preg_match( '`^\d{1,2}-\d{1,2}-\d{4}$`' , $date )) {
$dateTime = \DateTime::createFromFormat('d-m-Y', $date);
} else {
return $date;
}
return $dateTime->format('Y-m-d');
}
/**
* @Template()
*/
// for testing: http://localhost/WindServer/web/app_dev.php/admin/ajax/dataWindPrev/history/data/date_analyse/2/2013-09-15
public function historyDataFromDateAnalyseAction($id=null,$date=null)
{
$message='';
if (isset($id)) {
$result=$this->historyDataFromDateAnalyse($id,$date);
return $this->container->get('templating')->renderResponse(
'LaPoizWindBundle:Ajax:blockHistoryDataFromDateAnalyseDisplayInfo.html.twig',
$result);
} else {
return $this->container->get('templating')->renderResponse(
'LaPoizWindBundle:Default:errorPage.html.twig',
array( 'errMessage' => "Error bad parameter (dataWindPrev.id miss)" ));
}
}
public function historyDataFromDateAnalyse($id,$date) {
$em = $this->container->get('doctrine.orm.entity_manager');
$dataWindPrev = $em->find('LaPoizWindBundle:DataWindPrev', $id);
$listPrevisionDate = $this->getDoctrine()
->getRepository('LaPoizWindBundle:PrevisionDate')
->getFromOneWebSiteFromAnalyseDateOneDay($id,$date);
return array(
'date' => $date,
'dataWindPrev' => $dataWindPrev ,
'listPrevisionDate' =>$listPrevisionDate);
}
/**
* @Template()
*/
// for testing: http://localhost/WindServer/web/app_dev.php/ajax/dataWindPrev/history/analyse/2
public function historyAnalyseAction($id=null)
{
$message='';
if (isset($id)) {
$date=date('Y-m-d');
$em = $this->container->get('doctrine.orm.entity_manager');
$listPrevisionDate = $this->getDoctrine()
->getRepository('LaPoizWindBundle:PrevisionDate')
->getFromOneWebSiteForOneMonth($id,$date);
$tabHistoryAnalyse=$this->buildHistoryAnalyse($listPrevisionDate);
return $this->container->get('templating')->renderResponse(
'LaPoizWindBundle:Ajax:blockHistoryAnalyse.html.twig',
array('tabHistoryAnalyse' =>$tabHistoryAnalyse));
} else {
return $this->container->get('templating')->renderResponse(
'LaPoizWindBundle:Default:errorPage.html.twig',
array( 'errMessage' => "Error bad parameter (dataWindPrev.id miss)" ));
}
}
/*
* return array(date created, array(datePrev,nbElem))
*/
private function buildHistoryAnalyse($listPrevisionDate) {
$result=array();
$firstLine=true;
$dateCreated='';
$line=array();
foreach ($listPrevisionDate as $previsionDate) {
if ($previsionDate->getCreated()<>$dateCreated) {
// change line
if ($firstLine) {
$firstLine=false;
} else {
// add previous line
$result[]=array($dateCreated,$line);
}
$line=array();
$dateCreated=$previsionDate->getCreated();
}
$line[]=array($previsionDate->getDatePrev(),count($previsionDate->getListPrevision()));
}
$result[]=array($dateCreated,$line);
return $result;
}
} | {
"content_hash": "92cf6e04009e295ba7f378e042216bee",
"timestamp": "",
"source": "github",
"line_count": 228,
"max_line_length": 123,
"avg_line_length": 32.59649122807018,
"alnum_prop": 0.6914693218514532,
"repo_name": "lapoiz/WindServer",
"id": "d5ccaeb4f4fbfc4b1d601a4f1d54aa20574a34c3",
"size": "7432",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/LaPoiz/WindBundle/Controller/AjaxDataWindPrevController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "282739"
},
{
"name": "JavaScript",
"bytes": "40880"
},
{
"name": "PHP",
"bytes": "214159"
},
{
"name": "Ruby",
"bytes": "848"
}
],
"symlink_target": ""
} |
// -----------------------------------------------------------------------
// <copyright file="IProviderState.cs" company="Asynkron HB">
// Copyright (C) 2015-2017 Asynkron HB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Threading.Tasks;
using Google.Protobuf;
namespace Proto.Persistence
{
public interface IProviderState
{
Task GetEventsAsync(string actorName, int eventIndexStart, Action<object> callback);
Task<Tuple<object, int>> GetSnapshotAsync(string actorName);
int GetSnapshotInterval();
Task PersistEventAsync(string actorName, int eventIndex, IMessage @event);
Task PersistSnapshotAsync(string actorName, int eventIndex, IMessage snapshot);
void Restart();
}
} | {
"content_hash": "8e092e286decbd23c5a71fad010f8c49",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 92,
"avg_line_length": 38.90909090909091,
"alnum_prop": 0.5747663551401869,
"repo_name": "jasprem/protoactor-dotnet",
"id": "937f122bb1e5245507d29f3793ea9a136d2c6c28",
"size": "858",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Proto.Persistence/IProviderState.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "405"
},
{
"name": "C#",
"bytes": "212225"
},
{
"name": "PowerShell",
"bytes": "6109"
},
{
"name": "Protocol Buffer",
"bytes": "1005"
}
],
"symlink_target": ""
} |
// Karma configuration
// Generated on Sun Apr 26 2015 20:17:33 GMT+0300 (Финляндия (лето))
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/ngstorage/ngStorage.js',
'src/browser-storage-api/vsBrowserStorageAPIModule.js',
'src/handy-storage/vsHandyStorageModule.js',
'src/**/*.js',
'test/unit/**/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
plugins: [
'karma-jasmine',
'karma-chrome-launcher'
]
});
};
| {
"content_hash": "9af98ba252bd2bb55072014e51d496eb",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 120,
"avg_line_length": 25.36842105263158,
"alnum_prop": 0.6628630705394191,
"repo_name": "vskosp/vsHandyStorage",
"id": "23d2d6547f21940f7cf6c71adb87e197ba077f93",
"size": "1941",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "karma.conf.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "33680"
}
],
"symlink_target": ""
} |
/*global define*/
define([
'hammer',
'./selector'
], function (
hammer,
selector
) {
'use strict';
// Get requestAnimationFrame function based on which browser:
var requestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
return true; // return something for requestFrameID
};
function canvas(element) {
this.type = "canvas";
this.className = "canvas";
this.element = element;
this.context = element.getContext("2d");
this.parent = this;
this.width = element.width;
this.height = element.height;
this.children = [];
this.animations = [];
this.requestFrameID = undefined;
this.curFont = "";
this.curFontSize = 0;
}
canvas.prototype.setwidth = function (width) {
this.element.width = width;
this.width = width;
};
canvas.prototype.setheight = function (height) {
this.element.height = height;
this.height = height;
};
canvas.prototype.onAnimationFrame = function () {
// Check if there is anything to animate:
if (this.animations.length <= 0 || this.width <= 0 || this.height <= 0) { // Width and height check can be removed if animations MUST be called. This was originally added since d3 had issues.
this.requestFrameID = undefined;
return;
}
// Request to call this function on next frame (done before rendering to make animations smoother):
var thisCanvas = this;
this.requestFrameID = requestAnimFrame(function () { thisCanvas.onAnimationFrame(); }); // Encapsulate onAnimationFrame to preserve context.
// Get current time to test if animations are over:
var curTime = new Date().getTime(),
animation;
// Execute all animations, filter out any that are finished:
for (var i = 0; i < this.animations.length; i++) {
animation = this.animations[i];
// Call tween function for object:
var timeRatio = Math.min((curTime - animation.timeStart) / animation.duration, 1); // Get the current animation frame which is can be [0, 1].
animation.tweenFunc(animation.easeFunc(timeRatio)); // Call animation tween function.
// Filter out animations which exceeded the time:
if (curTime >= animation.timeEnd) {
animation.animationIndex = undefined;
animation.tweenEndFunc && animation.tweenEndFunc(animation.data.data);
this.animations.splice(i, 1);
i--;
} else {
// Update index:
animation.animationIndex = i;
}
}
// Render objects:
this.render();
};
canvas.prototype.render = canvas.prototype.pumpRender = function () {
if (this.width <= 0 || this.height <= 0) return;
// Reset transform:
this.context.setTransform(1, 0, 0, 1, 0, 0);
// Clear globals:
this.context.font = "40px Times New Roman";
this.curFont = "40px Times New Roman";
//this.curFontFamily = "Times New Roman";
this.curFontSize = 40;
// Calculate children's boundaries and parameters:
for (var i = 0; i < this.children.length; i++) {
this.children[i].calcBounds();
}
// Clear canvas:
this.context.clearRect(0, 0, this.element.width, this.element.height);
// Render children:
for (var i = 0; i < this.children.length; i++) {
this.children[i].render();
}
};
canvas.prototype.startRender = function () {
console.warn("canvas.startRender is deprecated!");
};
function select(canvasElement) {
var // Canvas object (unique to each canvas):
canvasObj = new canvas(canvasElement);
function touchEventHandler(event) {
// Ignore event with no gesture:
/*
if (!event.gesture) {
return;
}
event.gesture.preventDefault();
*/
// Ignore events with more than one touch.
//if (event.gesture.touches.length === 1) {
// Calculate offset from target's top-left corner:
var touch = event.pointers[0], // Get touch location on page.
display = event.target.style.display, // Save display property.
pagePos; // Get target position on page.
event.target.style.display = ""; // Make visible
pagePos = event.target.getBoundingClientRect(); // Get visible coords.
event.target.style.display = display; // Restore display property.
event.offsetX = touch.clientX - pagePos.left;
event.offsetY = touch.clientY - pagePos.top;
event.name = "on" + event.type;
// Loop through every child object on canvas and check if they have been clicked:
for (var i = 0; i < canvasObj.children.length; i++) {
// Check if mouse is in child:
if (canvasObj.children[i].isPointIn(event.offsetX, event.offsetY, event)) {
// If so, propagate event down to child.
canvasObj.children[i].touchEventHandler(event.offsetX, event.offsetY, event);
}
}
//}
}
var hammerObj = hammer(canvasObj.element, {
prevent_default: true,
drag_min_distance: 10,
hold_threshold: 10
});
hammerObj.on("hold tap doubletap touch release", touchEventHandler);
// Return the canvas selector:
return selector(canvasObj);
}
return {
select: select
};
}); | {
"content_hash": "6850ac03cc2669304ee44d0b1fd9d1fb",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 201,
"avg_line_length": 39.348101265822784,
"alnum_prop": 0.5489786070451986,
"repo_name": "EikosPartners/scalejs.canvas",
"id": "135caeaa9b009390861ea3150133d563842ee397",
"size": "6219",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/scalejs.canvas/canvas.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "2045"
},
{
"name": "HTML",
"bytes": "415"
},
{
"name": "JavaScript",
"bytes": "221904"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TRL.Common.Models;
using TRL.Common.Data;
using TRL.Common;
namespace TRL.Configuration
{
public class BarSettingsFactory:IGenericFactory<BarSettings>
{
private StrategyHeader strategyHeader;
private string prefix;
private BarSettingsFactory() { }
public BarSettingsFactory(StrategyHeader strategyHeader, string prefix)
{
this.strategyHeader = strategyHeader;
this.prefix = prefix;
}
public BarSettings Make()
{
try
{
return new BarSettings(this.strategyHeader,
AppSettings.GetStringValue(String.Concat(this.prefix, "_BarSettings_Symbol")),
AppSettings.GetValue<int>(String.Concat(this.prefix, "_BarSettings_Interval")),
AppSettings.GetValue<int>(String.Concat(this.prefix, "_BarSettings_Period")));
}
catch
{
return null;
}
}
}
}
| {
"content_hash": "cfb286c2fac5bf878a031dffbc33f9c9",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 99,
"avg_line_length": 28.205128205128204,
"alnum_prop": 0.5981818181818181,
"repo_name": "wouldyougo/TRx",
"id": "d50658798629c2dc1cf528286ada60ccb013b3c0",
"size": "1102",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "TRL.Configuration/BarSettingsFactory.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "3362669"
},
{
"name": "HTML",
"bytes": "46884"
},
{
"name": "Smalltalk",
"bytes": "92520"
}
],
"symlink_target": ""
} |
module ListPresenterBase
def set_context(view_context)
@view_context = view_context
view_context_holder.set_context(view_context)
self
end
def view_context_holder
@view_context_holder ||= ViewContextHolder.new(nil)
end
protected
def view_context
@view_context
end
end
| {
"content_hash": "0dd24bcf110532ab99ff410624b3f98d",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 55,
"avg_line_length": 18.294117647058822,
"alnum_prop": 0.6977491961414791,
"repo_name": "mwindholtz/ddd_cargo_on_rails",
"id": "2afae6ae46f142d0ff5f0408a498a555bc65ecd7",
"size": "311",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/presenters/list_presenter_base.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1873"
},
{
"name": "HTML",
"bytes": "17860"
},
{
"name": "JavaScript",
"bytes": "641"
},
{
"name": "Ruby",
"bytes": "101571"
}
],
"symlink_target": ""
} |
using namespace lldb;
using namespace lldb_private;
Symtab::Symtab(ObjectFile *objfile)
: m_objfile(objfile), m_symbols(), m_file_addr_to_index(),
m_name_to_index(), m_mutex(), m_file_addr_to_index_computed(false),
m_name_indexes_computed(false) {}
Symtab::~Symtab() {}
void Symtab::Reserve(size_t count) {
// Clients should grab the mutex from this symbol table and lock it manually
// when calling this function to avoid performance issues.
m_symbols.reserve(count);
}
Symbol *Symtab::Resize(size_t count) {
// Clients should grab the mutex from this symbol table and lock it manually
// when calling this function to avoid performance issues.
m_symbols.resize(count);
return m_symbols.empty() ? nullptr : &m_symbols[0];
}
uint32_t Symtab::AddSymbol(const Symbol &symbol) {
// Clients should grab the mutex from this symbol table and lock it manually
// when calling this function to avoid performance issues.
uint32_t symbol_idx = m_symbols.size();
m_name_to_index.Clear();
m_file_addr_to_index.Clear();
m_symbols.push_back(symbol);
m_file_addr_to_index_computed = false;
m_name_indexes_computed = false;
return symbol_idx;
}
size_t Symtab::GetNumSymbols() const {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
return m_symbols.size();
}
void Symtab::SectionFileAddressesChanged() {
m_name_to_index.Clear();
m_file_addr_to_index_computed = false;
}
void Symtab::Dump(Stream *s, Target *target, SortOrder sort_order) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
// s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
s->Indent();
const FileSpec &file_spec = m_objfile->GetFileSpec();
const char *object_name = nullptr;
if (m_objfile->GetModule())
object_name = m_objfile->GetModule()->GetObjectName().GetCString();
if (file_spec)
s->Printf("Symtab, file = %s%s%s%s, num_symbols = %" PRIu64,
file_spec.GetPath().c_str(), object_name ? "(" : "",
object_name ? object_name : "", object_name ? ")" : "",
(uint64_t)m_symbols.size());
else
s->Printf("Symtab, num_symbols = %" PRIu64 "", (uint64_t)m_symbols.size());
if (!m_symbols.empty()) {
switch (sort_order) {
case eSortOrderNone: {
s->PutCString(":\n");
DumpSymbolHeader(s);
const_iterator begin = m_symbols.begin();
const_iterator end = m_symbols.end();
for (const_iterator pos = m_symbols.begin(); pos != end; ++pos) {
s->Indent();
pos->Dump(s, target, std::distance(begin, pos));
}
} break;
case eSortOrderByName: {
// Although we maintain a lookup by exact name map, the table isn't
// sorted by name. So we must make the ordered symbol list up ourselves.
s->PutCString(" (sorted by name):\n");
DumpSymbolHeader(s);
typedef std::multimap<const char *, const Symbol *,
CStringCompareFunctionObject>
CStringToSymbol;
CStringToSymbol name_map;
for (const_iterator pos = m_symbols.begin(), end = m_symbols.end();
pos != end; ++pos) {
const char *name = pos->GetName().AsCString();
if (name && name[0])
name_map.insert(std::make_pair(name, &(*pos)));
}
for (CStringToSymbol::const_iterator pos = name_map.begin(),
end = name_map.end();
pos != end; ++pos) {
s->Indent();
pos->second->Dump(s, target, pos->second - &m_symbols[0]);
}
} break;
case eSortOrderByAddress:
s->PutCString(" (sorted by address):\n");
DumpSymbolHeader(s);
if (!m_file_addr_to_index_computed)
InitAddressIndexes();
const size_t num_entries = m_file_addr_to_index.GetSize();
for (size_t i = 0; i < num_entries; ++i) {
s->Indent();
const uint32_t symbol_idx = m_file_addr_to_index.GetEntryRef(i).data;
m_symbols[symbol_idx].Dump(s, target, symbol_idx);
}
break;
}
} else {
s->PutCString("\n");
}
}
void Symtab::Dump(Stream *s, Target *target,
std::vector<uint32_t> &indexes) const {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
const size_t num_symbols = GetNumSymbols();
// s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
s->Indent();
s->Printf("Symtab %" PRIu64 " symbol indexes (%" PRIu64 " symbols total):\n",
(uint64_t)indexes.size(), (uint64_t)m_symbols.size());
s->IndentMore();
if (!indexes.empty()) {
std::vector<uint32_t>::const_iterator pos;
std::vector<uint32_t>::const_iterator end = indexes.end();
DumpSymbolHeader(s);
for (pos = indexes.begin(); pos != end; ++pos) {
size_t idx = *pos;
if (idx < num_symbols) {
s->Indent();
m_symbols[idx].Dump(s, target, idx);
}
}
}
s->IndentLess();
}
void Symtab::DumpSymbolHeader(Stream *s) {
s->Indent(" Debug symbol\n");
s->Indent(" |Synthetic symbol\n");
s->Indent(" ||Externally Visible\n");
s->Indent(" |||\n");
s->Indent("Index UserID DSX Type File Address/Value Load "
"Address Size Flags Name\n");
s->Indent("------- ------ --- --------------- ------------------ "
"------------------ ------------------ ---------- "
"----------------------------------\n");
}
static int CompareSymbolID(const void *key, const void *p) {
const user_id_t match_uid = *(const user_id_t *)key;
const user_id_t symbol_uid = ((const Symbol *)p)->GetID();
if (match_uid < symbol_uid)
return -1;
if (match_uid > symbol_uid)
return 1;
return 0;
}
Symbol *Symtab::FindSymbolByID(lldb::user_id_t symbol_uid) const {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
Symbol *symbol =
(Symbol *)::bsearch(&symbol_uid, &m_symbols[0], m_symbols.size(),
sizeof(m_symbols[0]), CompareSymbolID);
return symbol;
}
Symbol *Symtab::SymbolAtIndex(size_t idx) {
// Clients should grab the mutex from this symbol table and lock it manually
// when calling this function to avoid performance issues.
if (idx < m_symbols.size())
return &m_symbols[idx];
return nullptr;
}
const Symbol *Symtab::SymbolAtIndex(size_t idx) const {
// Clients should grab the mutex from this symbol table and lock it manually
// when calling this function to avoid performance issues.
if (idx < m_symbols.size())
return &m_symbols[idx];
return nullptr;
}
static bool lldb_skip_name(llvm::StringRef mangled,
Mangled::ManglingScheme scheme) {
switch (scheme) {
case Mangled::eManglingSchemeItanium: {
if (mangled.size() < 3 || !mangled.startswith("_Z"))
return true;
// Avoid the following types of symbols in the index.
switch (mangled[2]) {
case 'G': // guard variables
case 'T': // virtual tables, VTT structures, typeinfo structures + names
case 'Z': // named local entities (if we eventually handle
// eSymbolTypeData, we will want this back)
return true;
default:
break;
}
// Include this name in the index.
return false;
}
// No filters for this scheme yet. Include all names in indexing.
case Mangled::eManglingSchemeMSVC:
return false;
// Don't try and demangle things we can't categorize.
case Mangled::eManglingSchemeNone:
return true;
}
llvm_unreachable("unknown scheme!");
}
void Symtab::InitNameIndexes() {
// Protected function, no need to lock mutex...
if (!m_name_indexes_computed) {
m_name_indexes_computed = true;
static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
Timer scoped_timer(func_cat, "%s", LLVM_PRETTY_FUNCTION);
// Create the name index vector to be able to quickly search by name
const size_t num_symbols = m_symbols.size();
m_name_to_index.Reserve(num_symbols);
// The "const char *" in "class_contexts" and backlog::value_type::second
// must come from a ConstString::GetCString()
std::set<const char *> class_contexts;
std::vector<std::pair<NameToIndexMap::Entry, const char *>> backlog;
backlog.reserve(num_symbols / 2);
// Instantiation of the demangler is expensive, so better use a single one
// for all entries during batch processing.
RichManglingContext rmc;
for (uint32_t value = 0; value < num_symbols; ++value) {
Symbol *symbol = &m_symbols[value];
// Don't let trampolines get into the lookup by name map If we ever need
// the trampoline symbols to be searchable by name we can remove this and
// then possibly add a new bool to any of the Symtab functions that
// lookup symbols by name to indicate if they want trampolines.
if (symbol->IsTrampoline())
continue;
// If the symbol's name string matched a Mangled::ManglingScheme, it is
// stored in the mangled field.
Mangled &mangled = symbol->GetMangled();
if (ConstString name = mangled.GetMangledName()) {
m_name_to_index.Append(name, value);
if (symbol->ContainsLinkerAnnotations()) {
// If the symbol has linker annotations, also add the version without
// the annotations.
ConstString stripped = ConstString(
m_objfile->StripLinkerSymbolAnnotations(name.GetStringRef()));
m_name_to_index.Append(stripped, value);
}
const SymbolType type = symbol->GetType();
if (type == eSymbolTypeCode || type == eSymbolTypeResolver) {
if (mangled.DemangleWithRichManglingInfo(rmc, lldb_skip_name))
RegisterMangledNameEntry(value, class_contexts, backlog, rmc);
}
}
// Symbol name strings that didn't match a Mangled::ManglingScheme, are
// stored in the demangled field.
if (ConstString name = mangled.GetDemangledName(symbol->GetLanguage())) {
m_name_to_index.Append(name, value);
if (symbol->ContainsLinkerAnnotations()) {
// If the symbol has linker annotations, also add the version without
// the annotations.
name = ConstString(
m_objfile->StripLinkerSymbolAnnotations(name.GetStringRef()));
m_name_to_index.Append(name, value);
}
// If the demangled name turns out to be an ObjC name, and is a category
// name, add the version without categories to the index too.
ObjCLanguage::MethodName objc_method(name.GetStringRef(), true);
if (objc_method.IsValid(true)) {
m_selector_to_index.Append(objc_method.GetSelector(), value);
if (ConstString objc_method_no_category =
objc_method.GetFullNameWithoutCategory(true))
m_name_to_index.Append(objc_method_no_category, value);
}
}
}
for (const auto &record : backlog) {
RegisterBacklogEntry(record.first, record.second, class_contexts);
}
m_name_to_index.Sort();
m_name_to_index.SizeToFit();
m_selector_to_index.Sort();
m_selector_to_index.SizeToFit();
m_basename_to_index.Sort();
m_basename_to_index.SizeToFit();
m_method_to_index.Sort();
m_method_to_index.SizeToFit();
}
}
void Symtab::RegisterMangledNameEntry(
uint32_t value, std::set<const char *> &class_contexts,
std::vector<std::pair<NameToIndexMap::Entry, const char *>> &backlog,
RichManglingContext &rmc) {
// Only register functions that have a base name.
rmc.ParseFunctionBaseName();
llvm::StringRef base_name = rmc.GetBufferRef();
if (base_name.empty())
return;
// The base name will be our entry's name.
NameToIndexMap::Entry entry(ConstString(base_name), value);
rmc.ParseFunctionDeclContextName();
llvm::StringRef decl_context = rmc.GetBufferRef();
// Register functions with no context.
if (decl_context.empty()) {
// This has to be a basename
m_basename_to_index.Append(entry);
// If there is no context (no namespaces or class scopes that come before
// the function name) then this also could be a fullname.
m_name_to_index.Append(entry);
return;
}
// Make sure we have a pool-string pointer and see if we already know the
// context name.
const char *decl_context_ccstr = ConstString(decl_context).GetCString();
auto it = class_contexts.find(decl_context_ccstr);
// Register constructors and destructors. They are methods and create
// declaration contexts.
if (rmc.IsCtorOrDtor()) {
m_method_to_index.Append(entry);
if (it == class_contexts.end())
class_contexts.insert(it, decl_context_ccstr);
return;
}
// Register regular methods with a known declaration context.
if (it != class_contexts.end()) {
m_method_to_index.Append(entry);
return;
}
// Regular methods in unknown declaration contexts are put to the backlog. We
// will revisit them once we processed all remaining symbols.
backlog.push_back(std::make_pair(entry, decl_context_ccstr));
}
void Symtab::RegisterBacklogEntry(
const NameToIndexMap::Entry &entry, const char *decl_context,
const std::set<const char *> &class_contexts) {
auto it = class_contexts.find(decl_context);
if (it != class_contexts.end()) {
m_method_to_index.Append(entry);
} else {
// If we got here, we have something that had a context (was inside
// a namespace or class) yet we don't know the entry
m_method_to_index.Append(entry);
m_basename_to_index.Append(entry);
}
}
void Symtab::PreloadSymbols() {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
InitNameIndexes();
}
void Symtab::AppendSymbolNamesToMap(const IndexCollection &indexes,
bool add_demangled, bool add_mangled,
NameToIndexMap &name_to_index_map) const {
if (add_demangled || add_mangled) {
static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
Timer scoped_timer(func_cat, "%s", LLVM_PRETTY_FUNCTION);
std::lock_guard<std::recursive_mutex> guard(m_mutex);
// Create the name index vector to be able to quickly search by name
const size_t num_indexes = indexes.size();
for (size_t i = 0; i < num_indexes; ++i) {
uint32_t value = indexes[i];
assert(i < m_symbols.size());
const Symbol *symbol = &m_symbols[value];
const Mangled &mangled = symbol->GetMangled();
if (add_demangled) {
if (ConstString name = mangled.GetDemangledName(symbol->GetLanguage()))
name_to_index_map.Append(name, value);
}
if (add_mangled) {
if (ConstString name = mangled.GetMangledName())
name_to_index_map.Append(name, value);
}
}
}
}
uint32_t Symtab::AppendSymbolIndexesWithType(SymbolType symbol_type,
std::vector<uint32_t> &indexes,
uint32_t start_idx,
uint32_t end_index) const {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
uint32_t prev_size = indexes.size();
const uint32_t count = std::min<uint32_t>(m_symbols.size(), end_index);
for (uint32_t i = start_idx; i < count; ++i) {
if (symbol_type == eSymbolTypeAny || m_symbols[i].GetType() == symbol_type)
indexes.push_back(i);
}
return indexes.size() - prev_size;
}
uint32_t Symtab::AppendSymbolIndexesWithTypeAndFlagsValue(
SymbolType symbol_type, uint32_t flags_value,
std::vector<uint32_t> &indexes, uint32_t start_idx,
uint32_t end_index) const {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
uint32_t prev_size = indexes.size();
const uint32_t count = std::min<uint32_t>(m_symbols.size(), end_index);
for (uint32_t i = start_idx; i < count; ++i) {
if ((symbol_type == eSymbolTypeAny ||
m_symbols[i].GetType() == symbol_type) &&
m_symbols[i].GetFlags() == flags_value)
indexes.push_back(i);
}
return indexes.size() - prev_size;
}
uint32_t Symtab::AppendSymbolIndexesWithType(SymbolType symbol_type,
Debug symbol_debug_type,
Visibility symbol_visibility,
std::vector<uint32_t> &indexes,
uint32_t start_idx,
uint32_t end_index) const {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
uint32_t prev_size = indexes.size();
const uint32_t count = std::min<uint32_t>(m_symbols.size(), end_index);
for (uint32_t i = start_idx; i < count; ++i) {
if (symbol_type == eSymbolTypeAny ||
m_symbols[i].GetType() == symbol_type) {
if (CheckSymbolAtIndex(i, symbol_debug_type, symbol_visibility))
indexes.push_back(i);
}
}
return indexes.size() - prev_size;
}
uint32_t Symtab::GetIndexForSymbol(const Symbol *symbol) const {
if (!m_symbols.empty()) {
const Symbol *first_symbol = &m_symbols[0];
if (symbol >= first_symbol && symbol < first_symbol + m_symbols.size())
return symbol - first_symbol;
}
return UINT32_MAX;
}
struct SymbolSortInfo {
const bool sort_by_load_addr;
const Symbol *symbols;
};
namespace {
struct SymbolIndexComparator {
const std::vector<Symbol> &symbols;
std::vector<lldb::addr_t> &addr_cache;
// Getting from the symbol to the Address to the File Address involves some
// work. Since there are potentially many symbols here, and we're using this
// for sorting so we're going to be computing the address many times, cache
// that in addr_cache. The array passed in has to be the same size as the
// symbols array passed into the member variable symbols, and should be
// initialized with LLDB_INVALID_ADDRESS.
// NOTE: You have to make addr_cache externally and pass it in because
// std::stable_sort
// makes copies of the comparator it is initially passed in, and you end up
// spending huge amounts of time copying this array...
SymbolIndexComparator(const std::vector<Symbol> &s,
std::vector<lldb::addr_t> &a)
: symbols(s), addr_cache(a) {
assert(symbols.size() == addr_cache.size());
}
bool operator()(uint32_t index_a, uint32_t index_b) {
addr_t value_a = addr_cache[index_a];
if (value_a == LLDB_INVALID_ADDRESS) {
value_a = symbols[index_a].GetAddressRef().GetFileAddress();
addr_cache[index_a] = value_a;
}
addr_t value_b = addr_cache[index_b];
if (value_b == LLDB_INVALID_ADDRESS) {
value_b = symbols[index_b].GetAddressRef().GetFileAddress();
addr_cache[index_b] = value_b;
}
if (value_a == value_b) {
// The if the values are equal, use the original symbol user ID
lldb::user_id_t uid_a = symbols[index_a].GetID();
lldb::user_id_t uid_b = symbols[index_b].GetID();
if (uid_a < uid_b)
return true;
if (uid_a > uid_b)
return false;
return false;
} else if (value_a < value_b)
return true;
return false;
}
};
}
void Symtab::SortSymbolIndexesByValue(std::vector<uint32_t> &indexes,
bool remove_duplicates) const {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
// No need to sort if we have zero or one items...
if (indexes.size() <= 1)
return;
// Sort the indexes in place using std::stable_sort.
// NOTE: The use of std::stable_sort instead of llvm::sort here is strictly
// for performance, not correctness. The indexes vector tends to be "close"
// to sorted, which the stable sort handles better.
std::vector<lldb::addr_t> addr_cache(m_symbols.size(), LLDB_INVALID_ADDRESS);
SymbolIndexComparator comparator(m_symbols, addr_cache);
std::stable_sort(indexes.begin(), indexes.end(), comparator);
// Remove any duplicates if requested
if (remove_duplicates) {
auto last = std::unique(indexes.begin(), indexes.end());
indexes.erase(last, indexes.end());
}
}
uint32_t Symtab::AppendSymbolIndexesWithName(ConstString symbol_name,
std::vector<uint32_t> &indexes) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
Timer scoped_timer(func_cat, "%s", LLVM_PRETTY_FUNCTION);
if (symbol_name) {
if (!m_name_indexes_computed)
InitNameIndexes();
return m_name_to_index.GetValues(symbol_name, indexes);
}
return 0;
}
uint32_t Symtab::AppendSymbolIndexesWithName(ConstString symbol_name,
Debug symbol_debug_type,
Visibility symbol_visibility,
std::vector<uint32_t> &indexes) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
Timer scoped_timer(func_cat, "%s", LLVM_PRETTY_FUNCTION);
if (symbol_name) {
const size_t old_size = indexes.size();
if (!m_name_indexes_computed)
InitNameIndexes();
std::vector<uint32_t> all_name_indexes;
const size_t name_match_count =
m_name_to_index.GetValues(symbol_name, all_name_indexes);
for (size_t i = 0; i < name_match_count; ++i) {
if (CheckSymbolAtIndex(all_name_indexes[i], symbol_debug_type,
symbol_visibility))
indexes.push_back(all_name_indexes[i]);
}
return indexes.size() - old_size;
}
return 0;
}
uint32_t
Symtab::AppendSymbolIndexesWithNameAndType(ConstString symbol_name,
SymbolType symbol_type,
std::vector<uint32_t> &indexes) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
if (AppendSymbolIndexesWithName(symbol_name, indexes) > 0) {
std::vector<uint32_t>::iterator pos = indexes.begin();
while (pos != indexes.end()) {
if (symbol_type == eSymbolTypeAny ||
m_symbols[*pos].GetType() == symbol_type)
++pos;
else
pos = indexes.erase(pos);
}
}
return indexes.size();
}
uint32_t Symtab::AppendSymbolIndexesWithNameAndType(
ConstString symbol_name, SymbolType symbol_type,
Debug symbol_debug_type, Visibility symbol_visibility,
std::vector<uint32_t> &indexes) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
if (AppendSymbolIndexesWithName(symbol_name, symbol_debug_type,
symbol_visibility, indexes) > 0) {
std::vector<uint32_t>::iterator pos = indexes.begin();
while (pos != indexes.end()) {
if (symbol_type == eSymbolTypeAny ||
m_symbols[*pos].GetType() == symbol_type)
++pos;
else
pos = indexes.erase(pos);
}
}
return indexes.size();
}
uint32_t Symtab::AppendSymbolIndexesMatchingRegExAndType(
const RegularExpression ®exp, SymbolType symbol_type,
std::vector<uint32_t> &indexes) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
uint32_t prev_size = indexes.size();
uint32_t sym_end = m_symbols.size();
for (uint32_t i = 0; i < sym_end; i++) {
if (symbol_type == eSymbolTypeAny ||
m_symbols[i].GetType() == symbol_type) {
const char *name = m_symbols[i].GetName().AsCString();
if (name) {
if (regexp.Execute(name))
indexes.push_back(i);
}
}
}
return indexes.size() - prev_size;
}
uint32_t Symtab::AppendSymbolIndexesMatchingRegExAndType(
const RegularExpression ®exp, SymbolType symbol_type,
Debug symbol_debug_type, Visibility symbol_visibility,
std::vector<uint32_t> &indexes) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
uint32_t prev_size = indexes.size();
uint32_t sym_end = m_symbols.size();
for (uint32_t i = 0; i < sym_end; i++) {
if (symbol_type == eSymbolTypeAny ||
m_symbols[i].GetType() == symbol_type) {
if (!CheckSymbolAtIndex(i, symbol_debug_type, symbol_visibility))
continue;
const char *name = m_symbols[i].GetName().AsCString();
if (name) {
if (regexp.Execute(name))
indexes.push_back(i);
}
}
}
return indexes.size() - prev_size;
}
Symbol *Symtab::FindSymbolWithType(SymbolType symbol_type,
Debug symbol_debug_type,
Visibility symbol_visibility,
uint32_t &start_idx) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
const size_t count = m_symbols.size();
for (size_t idx = start_idx; idx < count; ++idx) {
if (symbol_type == eSymbolTypeAny ||
m_symbols[idx].GetType() == symbol_type) {
if (CheckSymbolAtIndex(idx, symbol_debug_type, symbol_visibility)) {
start_idx = idx;
return &m_symbols[idx];
}
}
}
return nullptr;
}
void
Symtab::FindAllSymbolsWithNameAndType(ConstString name,
SymbolType symbol_type,
std::vector<uint32_t> &symbol_indexes) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
Timer scoped_timer(func_cat, "%s", LLVM_PRETTY_FUNCTION);
// Initialize all of the lookup by name indexes before converting NAME to a
// uniqued string NAME_STR below.
if (!m_name_indexes_computed)
InitNameIndexes();
if (name) {
// The string table did have a string that matched, but we need to check
// the symbols and match the symbol_type if any was given.
AppendSymbolIndexesWithNameAndType(name, symbol_type, symbol_indexes);
}
}
void Symtab::FindAllSymbolsWithNameAndType(
ConstString name, SymbolType symbol_type, Debug symbol_debug_type,
Visibility symbol_visibility, std::vector<uint32_t> &symbol_indexes) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
Timer scoped_timer(func_cat, "%s", LLVM_PRETTY_FUNCTION);
// Initialize all of the lookup by name indexes before converting NAME to a
// uniqued string NAME_STR below.
if (!m_name_indexes_computed)
InitNameIndexes();
if (name) {
// The string table did have a string that matched, but we need to check
// the symbols and match the symbol_type if any was given.
AppendSymbolIndexesWithNameAndType(name, symbol_type, symbol_debug_type,
symbol_visibility, symbol_indexes);
}
}
void Symtab::FindAllSymbolsMatchingRexExAndType(
const RegularExpression ®ex, SymbolType symbol_type,
Debug symbol_debug_type, Visibility symbol_visibility,
std::vector<uint32_t> &symbol_indexes) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
AppendSymbolIndexesMatchingRegExAndType(regex, symbol_type, symbol_debug_type,
symbol_visibility, symbol_indexes);
}
Symbol *Symtab::FindFirstSymbolWithNameAndType(ConstString name,
SymbolType symbol_type,
Debug symbol_debug_type,
Visibility symbol_visibility) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
Timer scoped_timer(func_cat, "%s", LLVM_PRETTY_FUNCTION);
if (!m_name_indexes_computed)
InitNameIndexes();
if (name) {
std::vector<uint32_t> matching_indexes;
// The string table did have a string that matched, but we need to check
// the symbols and match the symbol_type if any was given.
if (AppendSymbolIndexesWithNameAndType(name, symbol_type, symbol_debug_type,
symbol_visibility,
matching_indexes)) {
std::vector<uint32_t>::const_iterator pos, end = matching_indexes.end();
for (pos = matching_indexes.begin(); pos != end; ++pos) {
Symbol *symbol = SymbolAtIndex(*pos);
if (symbol->Compare(name, symbol_type))
return symbol;
}
}
}
return nullptr;
}
typedef struct {
const Symtab *symtab;
const addr_t file_addr;
Symbol *match_symbol;
const uint32_t *match_index_ptr;
addr_t match_offset;
} SymbolSearchInfo;
// Add all the section file start address & size to the RangeVector, recusively
// adding any children sections.
static void AddSectionsToRangeMap(SectionList *sectlist,
RangeVector<addr_t, addr_t> §ion_ranges) {
const int num_sections = sectlist->GetNumSections(0);
for (int i = 0; i < num_sections; i++) {
SectionSP sect_sp = sectlist->GetSectionAtIndex(i);
if (sect_sp) {
SectionList &child_sectlist = sect_sp->GetChildren();
// If this section has children, add the children to the RangeVector.
// Else add this section to the RangeVector.
if (child_sectlist.GetNumSections(0) > 0) {
AddSectionsToRangeMap(&child_sectlist, section_ranges);
} else {
size_t size = sect_sp->GetByteSize();
if (size > 0) {
addr_t base_addr = sect_sp->GetFileAddress();
RangeVector<addr_t, addr_t>::Entry entry;
entry.SetRangeBase(base_addr);
entry.SetByteSize(size);
section_ranges.Append(entry);
}
}
}
}
}
void Symtab::InitAddressIndexes() {
// Protected function, no need to lock mutex...
if (!m_file_addr_to_index_computed && !m_symbols.empty()) {
m_file_addr_to_index_computed = true;
FileRangeToIndexMap::Entry entry;
const_iterator begin = m_symbols.begin();
const_iterator end = m_symbols.end();
for (const_iterator pos = m_symbols.begin(); pos != end; ++pos) {
if (pos->ValueIsAddress()) {
entry.SetRangeBase(pos->GetAddressRef().GetFileAddress());
entry.SetByteSize(pos->GetByteSize());
entry.data = std::distance(begin, pos);
m_file_addr_to_index.Append(entry);
}
}
const size_t num_entries = m_file_addr_to_index.GetSize();
if (num_entries > 0) {
m_file_addr_to_index.Sort();
// Create a RangeVector with the start & size of all the sections for
// this objfile. We'll need to check this for any FileRangeToIndexMap
// entries with an uninitialized size, which could potentially be a large
// number so reconstituting the weak pointer is busywork when it is
// invariant information.
SectionList *sectlist = m_objfile->GetSectionList();
RangeVector<addr_t, addr_t> section_ranges;
if (sectlist) {
AddSectionsToRangeMap(sectlist, section_ranges);
section_ranges.Sort();
}
// Iterate through the FileRangeToIndexMap and fill in the size for any
// entries that didn't already have a size from the Symbol (e.g. if we
// have a plain linker symbol with an address only, instead of debug info
// where we get an address and a size and a type, etc.)
for (size_t i = 0; i < num_entries; i++) {
FileRangeToIndexMap::Entry *entry =
m_file_addr_to_index.GetMutableEntryAtIndex(i);
if (entry->GetByteSize() > 0)
continue;
addr_t curr_base_addr = entry->GetRangeBase();
// Symbols with non-zero size will show after zero-sized symbols on the
// same address. So do not set size of a non-last zero-sized symbol.
if (i == num_entries - 1 ||
m_file_addr_to_index.GetMutableEntryAtIndex(i + 1)
->GetRangeBase() != curr_base_addr) {
const RangeVector<addr_t, addr_t>::Entry *containing_section =
section_ranges.FindEntryThatContains(curr_base_addr);
// Use the end of the section as the default max size of the symbol
addr_t sym_size = 0;
if (containing_section) {
sym_size =
containing_section->GetByteSize() -
(entry->GetRangeBase() - containing_section->GetRangeBase());
}
for (size_t j = i; j < num_entries; j++) {
FileRangeToIndexMap::Entry *next_entry =
m_file_addr_to_index.GetMutableEntryAtIndex(j);
addr_t next_base_addr = next_entry->GetRangeBase();
if (next_base_addr > curr_base_addr) {
addr_t size_to_next_symbol = next_base_addr - curr_base_addr;
// Take the difference between this symbol and the next one as
// its size, if it is less than the size of the section.
if (sym_size == 0 || size_to_next_symbol < sym_size) {
sym_size = size_to_next_symbol;
}
break;
}
}
if (sym_size > 0) {
entry->SetByteSize(sym_size);
Symbol &symbol = m_symbols[entry->data];
symbol.SetByteSize(sym_size);
symbol.SetSizeIsSynthesized(true);
}
}
}
// Sort again in case the range size changes the ordering
m_file_addr_to_index.Sort();
}
}
}
void Symtab::CalculateSymbolSizes() {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
// Size computation happens inside InitAddressIndexes.
InitAddressIndexes();
}
Symbol *Symtab::FindSymbolAtFileAddress(addr_t file_addr) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
if (!m_file_addr_to_index_computed)
InitAddressIndexes();
const FileRangeToIndexMap::Entry *entry =
m_file_addr_to_index.FindEntryStartsAt(file_addr);
if (entry) {
Symbol *symbol = SymbolAtIndex(entry->data);
if (symbol->GetFileAddress() == file_addr)
return symbol;
}
return nullptr;
}
Symbol *Symtab::FindSymbolContainingFileAddress(addr_t file_addr) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
if (!m_file_addr_to_index_computed)
InitAddressIndexes();
const FileRangeToIndexMap::Entry *entry =
m_file_addr_to_index.FindEntryThatContains(file_addr);
if (entry) {
Symbol *symbol = SymbolAtIndex(entry->data);
if (symbol->ContainsFileAddress(file_addr))
return symbol;
}
return nullptr;
}
void Symtab::ForEachSymbolContainingFileAddress(
addr_t file_addr, std::function<bool(Symbol *)> const &callback) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
if (!m_file_addr_to_index_computed)
InitAddressIndexes();
std::vector<uint32_t> all_addr_indexes;
// Get all symbols with file_addr
const size_t addr_match_count =
m_file_addr_to_index.FindEntryIndexesThatContain(file_addr,
all_addr_indexes);
for (size_t i = 0; i < addr_match_count; ++i) {
Symbol *symbol = SymbolAtIndex(all_addr_indexes[i]);
if (symbol->ContainsFileAddress(file_addr)) {
if (!callback(symbol))
break;
}
}
}
void Symtab::SymbolIndicesToSymbolContextList(
std::vector<uint32_t> &symbol_indexes, SymbolContextList &sc_list) {
// No need to protect this call using m_mutex all other method calls are
// already thread safe.
const bool merge_symbol_into_function = true;
size_t num_indices = symbol_indexes.size();
if (num_indices > 0) {
SymbolContext sc;
sc.module_sp = m_objfile->GetModule();
for (size_t i = 0; i < num_indices; i++) {
sc.symbol = SymbolAtIndex(symbol_indexes[i]);
if (sc.symbol)
sc_list.AppendIfUnique(sc, merge_symbol_into_function);
}
}
}
void Symtab::FindFunctionSymbols(ConstString name, uint32_t name_type_mask,
SymbolContextList &sc_list) {
std::vector<uint32_t> symbol_indexes;
// eFunctionNameTypeAuto should be pre-resolved by a call to
// Module::LookupInfo::LookupInfo()
assert((name_type_mask & eFunctionNameTypeAuto) == 0);
if (name_type_mask & (eFunctionNameTypeBase | eFunctionNameTypeFull)) {
std::vector<uint32_t> temp_symbol_indexes;
FindAllSymbolsWithNameAndType(name, eSymbolTypeAny, temp_symbol_indexes);
unsigned temp_symbol_indexes_size = temp_symbol_indexes.size();
if (temp_symbol_indexes_size > 0) {
std::lock_guard<std::recursive_mutex> guard(m_mutex);
for (unsigned i = 0; i < temp_symbol_indexes_size; i++) {
SymbolContext sym_ctx;
sym_ctx.symbol = SymbolAtIndex(temp_symbol_indexes[i]);
if (sym_ctx.symbol) {
switch (sym_ctx.symbol->GetType()) {
case eSymbolTypeCode:
case eSymbolTypeResolver:
case eSymbolTypeReExported:
symbol_indexes.push_back(temp_symbol_indexes[i]);
break;
default:
break;
}
}
}
}
}
if (name_type_mask & eFunctionNameTypeBase) {
// From mangled names we can't tell what is a basename and what is a method
// name, so we just treat them the same
if (!m_name_indexes_computed)
InitNameIndexes();
if (!m_basename_to_index.IsEmpty()) {
const UniqueCStringMap<uint32_t>::Entry *match;
for (match = m_basename_to_index.FindFirstValueForName(name);
match != nullptr;
match = m_basename_to_index.FindNextValueForName(match)) {
symbol_indexes.push_back(match->value);
}
}
}
if (name_type_mask & eFunctionNameTypeMethod) {
if (!m_name_indexes_computed)
InitNameIndexes();
if (!m_method_to_index.IsEmpty()) {
const UniqueCStringMap<uint32_t>::Entry *match;
for (match = m_method_to_index.FindFirstValueForName(name);
match != nullptr;
match = m_method_to_index.FindNextValueForName(match)) {
symbol_indexes.push_back(match->value);
}
}
}
if (name_type_mask & eFunctionNameTypeSelector) {
if (!m_name_indexes_computed)
InitNameIndexes();
if (!m_selector_to_index.IsEmpty()) {
const UniqueCStringMap<uint32_t>::Entry *match;
for (match = m_selector_to_index.FindFirstValueForName(name);
match != nullptr;
match = m_selector_to_index.FindNextValueForName(match)) {
symbol_indexes.push_back(match->value);
}
}
}
if (!symbol_indexes.empty()) {
llvm::sort(symbol_indexes.begin(), symbol_indexes.end());
symbol_indexes.erase(
std::unique(symbol_indexes.begin(), symbol_indexes.end()),
symbol_indexes.end());
SymbolIndicesToSymbolContextList(symbol_indexes, sc_list);
}
}
const Symbol *Symtab::GetParent(Symbol *child_symbol) const {
uint32_t child_idx = GetIndexForSymbol(child_symbol);
if (child_idx != UINT32_MAX && child_idx > 0) {
for (uint32_t idx = child_idx - 1; idx != UINT32_MAX; --idx) {
const Symbol *symbol = SymbolAtIndex(idx);
const uint32_t sibling_idx = symbol->GetSiblingIndex();
if (sibling_idx != UINT32_MAX && sibling_idx > child_idx)
return symbol;
}
}
return nullptr;
}
| {
"content_hash": "dd0575f4ebe073c53437db1b40c3f77a",
"timestamp": "",
"source": "github",
"line_count": 1094,
"max_line_length": 80,
"avg_line_length": 35.70201096892139,
"alnum_prop": 0.6235086281939679,
"repo_name": "llvm-mirror/lldb",
"id": "c4e6c2ccfb0982049883742f12abf547929a69ca",
"size": "39926",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "source/Symbol/Symtab.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "131618"
},
{
"name": "C",
"bytes": "195293"
},
{
"name": "C++",
"bytes": "23346708"
},
{
"name": "CMake",
"bytes": "167302"
},
{
"name": "DTrace",
"bytes": "334"
},
{
"name": "LLVM",
"bytes": "6106"
},
{
"name": "Makefile",
"bytes": "50396"
},
{
"name": "Objective-C",
"bytes": "106956"
},
{
"name": "Objective-C++",
"bytes": "24806"
},
{
"name": "Perl",
"bytes": "72175"
},
{
"name": "Python",
"bytes": "3669886"
},
{
"name": "Shell",
"bytes": "6573"
},
{
"name": "Vim script",
"bytes": "8434"
}
],
"symlink_target": ""
} |
layout: default
description: JavaScript API to manage ArangoSearch Analyzers with arangosh and Foxx
title: ArangoSearch Analyzer JS API
---
Analyzer Management
===================
The JavaScript API can be accessed via the `@arangodb/analyzers` module from
both server-side and client-side code (arangosh, Foxx):
```js
var analyzers = require("@arangodb/analyzers");
```
See [Analyzers](arangosearch-analyzers.html) for general information and
details about the attributes.
Analyzer Module Methods
-----------------------
### Create an Analyzer
```js
var analyzer = analyzers.save(<name>, <type>[, <properties>[, <features>]])
```
Create a new Analyzer with custom configuration in the current database.
- **name** (string): name for identifying the Analyzer later
- **type** (string): the kind of Analyzer to create
- **properties** (object, _optional_): settings specific to the chosen *type*.
Most types require at least one property, so this may not be optional
- **features** (array, _optional_): array of strings with names of the features
to enable
- returns **analyzer** (object): Analyzer object, also if an Analyzer with the
same settings exists already. An error is raised if the settings mismatch
or if they are invalid
{% arangoshexample examplevar="examplevar" script="script" result="result" %}
@startDocuBlockInline analyzerCreate
@EXAMPLE_ARANGOSH_OUTPUT{analyzerCreate}
var analyzers = require("@arangodb/analyzers");
analyzers.save("csv", "delimiter", { "delimiter": "," }, []);
~analyzers.remove("csv");
@END_EXAMPLE_ARANGOSH_OUTPUT
@endDocuBlock analyzerCreate
{% endarangoshexample %}
{% include arangoshexample.html id=examplevar script=script result=result %}
### Get an Analyzer
```js
var analyzer = analyzers.analyzer(<name>)
```
Get an Analyzer by the name, stored in the current database. The name can be
prefixed with `_system::` to access Analyzers stored in the `_system` database.
- **name** (string): name of the Analyzer to find
- returns **analyzer** (object\|null): Analyzer object if found, else `null`
{% arangoshexample examplevar="examplevar" script="script" result="result" %}
@startDocuBlockInline analyzerByName
@EXAMPLE_ARANGOSH_OUTPUT{analyzerByName}
var analyzers = require("@arangodb/analyzers");
analyzers.analyzer("text_en");
@END_EXAMPLE_ARANGOSH_OUTPUT
@endDocuBlock analyzerByName
{% endarangoshexample %}
{% include arangoshexample.html id=examplevar script=script result=result %}
### List all Analyzers
```js
var analyzerArray = analyzers.toArray()
```
List all Analyzers available in the current database.
- returns **analyzerArray** (array): array of Analyzer objects
{% arangoshexample examplevar="examplevar" script="script" result="result" %}
@startDocuBlockInline analyzerList
@EXAMPLE_ARANGOSH_OUTPUT{analyzerList}
var analyzers = require("@arangodb/analyzers");
analyzers.toArray();
@END_EXAMPLE_ARANGOSH_OUTPUT
@endDocuBlock analyzerList
{% endarangoshexample %}
{% include arangoshexample.html id=examplevar script=script result=result %}
### Remove an Analyzer
```js
analyzers.remove(<name> [, <force>])
```
Delete an Analyzer from the current database.
- **name** (string): name of the Analyzer to remove
- **force** (bool, _optional_): remove Analyzer even if in use by a View.
Default: `false`
- returns nothing: no return value on success, otherwise an error is raised
{% arangoshexample examplevar="examplevar" script="script" result="result" %}
@startDocuBlockInline analyzerRemove
@EXAMPLE_ARANGOSH_OUTPUT{analyzerRemove}
var analyzers = require("@arangodb/analyzers");
~analyzers.save("csv", "delimiter", { "delimiter": "," }, []);
analyzers.remove("csv");
@END_EXAMPLE_ARANGOSH_OUTPUT
@endDocuBlock analyzerRemove
{% endarangoshexample %}
{% include arangoshexample.html id=examplevar script=script result=result %}
Analyzer Object Methods
-----------------------
Individual Analyzer objects expose getter accessors for the aforementioned
definition attributes (see [Create an Analyzer](#create-an-analyzer)).
### Get Analyzer Name
```js
var name = analyzer.name()
```
- returns **name** (string): name of the Analyzer
{% arangoshexample examplevar="examplevar" script="script" result="result" %}
@startDocuBlockInline analyzerName
@EXAMPLE_ARANGOSH_OUTPUT{analyzerName}
var analyzers = require("@arangodb/analyzers");
analyzers.analyzer("text_en").name();
@END_EXAMPLE_ARANGOSH_OUTPUT
@endDocuBlock analyzerName
{% endarangoshexample %}
{% include arangoshexample.html id=examplevar script=script result=result %}
### Get Analyzer Type
```js
var type = analyzer.type()
```
- returns **type** (string): type of the Analyzer
{% arangoshexample examplevar="examplevar" script="script" result="result" %}
@startDocuBlockInline analyzerType
@EXAMPLE_ARANGOSH_OUTPUT{analyzerType}
var analyzers = require("@arangodb/analyzers");
analyzers.analyzer("text_en").type();
@END_EXAMPLE_ARANGOSH_OUTPUT
@endDocuBlock analyzerType
{% endarangoshexample %}
{% include arangoshexample.html id=examplevar script=script result=result %}
### Get Analyzer Properties
```js
var properties = analyzer.properties()
```
- returns **properties** (object): *type* dependent properties of the Analyzer
{% arangoshexample examplevar="examplevar" script="script" result="result" %}
@startDocuBlockInline analyzerProperties
@EXAMPLE_ARANGOSH_OUTPUT{analyzerProperties}
var analyzers = require("@arangodb/analyzers");
analyzers.analyzer("text_en").properties();
@END_EXAMPLE_ARANGOSH_OUTPUT
@endDocuBlock analyzerProperties
{% endarangoshexample %}
{% include arangoshexample.html id=examplevar script=script result=result %}
### Get Analyzer Features
```js
var features = analyzer.features()
```
- returns **features** (array): array of strings with the features of the Analyzer
{% arangoshexample examplevar="examplevar" script="script" result="result" %}
@startDocuBlockInline analyzerFeatures
@EXAMPLE_ARANGOSH_OUTPUT{analyzerFeatures}
var analyzers = require("@arangodb/analyzers");
analyzers.analyzer("text_en").features();
@END_EXAMPLE_ARANGOSH_OUTPUT
@endDocuBlock analyzerFeatures
{% endarangoshexample %}
{% include arangoshexample.html id=examplevar script=script result=result %}
| {
"content_hash": "3b2e152b73011fbdfc223afbea6f9e77",
"timestamp": "",
"source": "github",
"line_count": 192,
"max_line_length": 83,
"avg_line_length": 33.276041666666664,
"alnum_prop": 0.7284395053999061,
"repo_name": "arangodb/docs",
"id": "65b8d9fb15d60ae91014fb7d7adcd916e2aeb032",
"size": "6393",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "3.6/appendix-java-script-modules-analyzers.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "111161"
},
{
"name": "Dockerfile",
"bytes": "606"
},
{
"name": "HTML",
"bytes": "20095"
},
{
"name": "JavaScript",
"bytes": "7194"
},
{
"name": "Ruby",
"bytes": "60609"
},
{
"name": "Shell",
"bytes": "617"
}
],
"symlink_target": ""
} |
<?php
namespace Web\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* EducationPlace, establece los títulos y cursos para el corriculum.
*
* @ORM\Table()
* @ORM\Entity()
*/
class EducationPlace
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="Web\MainBundle\Entity\Curriculum", inversedBy="education")
* @ORM\JoinColumn(name="curriculum_id", referencedColumnName="id")
*/
protected $curriculumId;
/**
* @var string
*
* @ORM\Column(name="place", type="string", length=100)
*/
private $place;
/**
* @ORM\Column(name="titration", type="string", length=100)
*/
protected $titration;
/**
* @var string
*
* @ORM\Column(name="address", type="string", length=100, nullable=true)
*/
private $address;
/**
* @var string
*
* @ORM\Column(name="description", type="string", length=255, nullable=true)
*/
private $description;
/**
* @var boolean
*
* @ORM\Column(name="is_course", type="boolean")
*/
private $isCourse;
/**
* @var integer
*
* @ORM\Column(name="hours", type="integer")
*/
private $hours;
/**
* @var \DateTime
*
* @ORM\Column(name="start_date", type="datetime")
*/
private $startDate;
/**
* @var \DateTime
*
* @ORM\Column(name="finish_date", type="datetime")
*/
private $finishDate;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set place
*
* @param string $place
*
* @return EducationPlace
*/
public function setPlace($place)
{
$this->place = $place;
return $this;
}
/**
* Get place
*
* @return string
*/
public function getPlace()
{
return $this->place;
}
/**
* Set titration
*
* @param string $titration
*
* @return EducationPlace
*/
public function setTitration($titration)
{
$this->titration = $titration;
return $this;
}
/**
* Get titration
*
* @return string
*/
public function getTitration()
{
return $this->titration;
}
/**
* Set address
*
* @param string $address
*
* @return EducationPlace
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* Get address
*
* @return string
*/
public function getAddress()
{
return $this->address;
}
/**
* Set description
*
* @param string $description
*
* @return EducationPlace
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set isCourse
*
* @param boolean $isCourse
*
* @return EducationPlace
*/
public function setIsCourse($isCourse)
{
$this->isCourse = $isCourse;
return $this;
}
/**
* Get isCourse
*
* @return boolean
*/
public function getIsCourse()
{
return $this->isCourse;
}
/**
* Set hours
*
* @param integer $hours
*
* @return EducationPlace
*/
public function setHours($hours)
{
$this->hours = $hours;
return $this;
}
/**
* Get hours
*
* @return integer
*/
public function getHours()
{
return $this->hours;
}
/**
* Set startDate
*
* @param \DateTime $startDate
*
* @return EducationPlace
*/
public function setStartDate($startDate)
{
$this->startDate = $startDate;
return $this;
}
/**
* Get startDate
*
* @return \DateTime
*/
public function getStartDate()
{
return $this->startDate;
}
/**
* Set finishDate
*
* @param \DateTime $finishDate
*
* @return EducationPlace
*/
public function setFinishDate($finishDate)
{
$this->finishDate = $finishDate;
return $this;
}
/**
* Get finishDate
*
* @return \DateTime
*/
public function getFinishDate()
{
return $this->finishDate;
}
/**
* Set curriculumId
*
* @param \Web\MainBundle\Entity\Curriculum $curriculumId
*
* @return EducationPlace
*/
public function setCurriculumId(\Web\MainBundle\Entity\Curriculum $curriculumId = null)
{
$this->curriculumId = $curriculumId;
return $this;
}
/**
* Get curriculumId
*
* @return \Web\MainBundle\Entity\Curriculum
*/
public function getCurriculumId()
{
return $this->curriculumId;
}
}
| {
"content_hash": "78c54b370c9fa7d734b514cdc530b316",
"timestamp": "",
"source": "github",
"line_count": 309,
"max_line_length": 94,
"avg_line_length": 16.870550161812297,
"alnum_prop": 0.5110301170151544,
"repo_name": "enrique-esteban/curriculum",
"id": "78ebd764d3362e8653598ed47d8823841ba2cffe",
"size": "5214",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Web/MainBundle/Entity/EducationPlace.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "66837"
},
{
"name": "HTML",
"bytes": "96993"
},
{
"name": "JavaScript",
"bytes": "111458"
},
{
"name": "PHP",
"bytes": "274853"
}
],
"symlink_target": ""
} |
Contributors, those mythical beings who unselfishly sacrifice their time in effort to help out fellow developers, whom they
may have never met, in building high quality software and libraries. You are most welcome. This documentation is for you.
## The Why
Contributors are important. Most open source projects suffer from a low
[bus factor](https://en.wikipedia.org/wiki/Bus_factor), often having only a single maintainer, on whom the whole project then
depends. It is the responsibility of the project maintainer(s) to encourage and help potential contributors to get started
with the project. That is why this documentation exists.
Typical open source library documentation (if it exists in the first place :smirk: ) is intended for the _user_ of the
library, describing how the library is used etc. This is of course fine for the user, but it doesn't help a potential
contributor that much, as they would like to know more about the internals, architecture and design of the library. Unlike
user documentation, this _contributor documentation_ focuses on exactly that, making it easier to get started with your
contributions, whether they are just fixing typos in the documentation, reporting issues, correcting them, writing tests or
improving the overall design. All contributions from all contributors are welcome!
## The Guide
This guide is divided into following sections to help you get around quickly.
- [Getting started](#getting-started) - taking those first baby steps
- [Background and motivation](#background-and-motivation) - tells you why Suzaku was created
- [Design and Architecture](#design-and-architecture) - the core principles and ideas behind Suzaku
- [Workflow](#workflow) - the actual workflow for contributing
- [Style guide](#style-guide) - keeping up with the latest style
- [Practical tips](#practical-tips) - making your life easier with some practical tips
## Getting started
First of all make sure you have the necessary tools installed. You'll need the following:
- Git ([downloads](https://git-scm.com/downloads) for all platforms)
- Java 8 JDK ([downloads](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html) for all
platforms)
- SBT (setup for [Linux](http://www.scala-sbt.org/0.13/docs/Installing-sbt-on-Linux.html) \|
[Windows](http://www.scala-sbt.org/0.13/docs/Installing-sbt-on-Windows.html) \|
[Mac](http://www.scala-sbt.org/0.13/docs/Installing-sbt-on-Mac.html))
To make contributions in the project you need to _fork_ your own copy of it first. Go to
[https://github.com/suzaku-io/suzaku](<>) and click the _Fork_ button to do it.

This will create a copy of the current repo state under your own account (for example `ochrons/suzaku`), where you can play
around freely. Next step is to create a local _branch_ where you'll make your changes. In this example we'll be adding
Android support.

You can also create the branch locally after you have cloned the repo to your own computer, which we'll do next.
Some contributions, like small fixes to documentation, can be done using nothing but the GitHub web UI, but for most cases
you'll need to _clone_ the repository on your own computer by clicking the "Clone or download" button, which will provide you
with an appropriate link text. If you have added your
[SSH key to GitHub](https://help.github.com/articles/connecting-to-github-with-ssh/), use the SSH protocol, otherwise choose
HTTPS.

Next you'll need to perform the actual cloning of the repo using your `git` client, for example on the command line with
$ git clone [email protected]:ochrons/suzaku.git
This will create a `suzaku` directory under your current working directory and copy the contents of the repo (with all the
branches and other metadata) there.
Finally switch to the branch you created earlier, so you can get started with your modifications.
```text
$ cd suzaku
$ git checkout add-android-support
```
If you didn't create a branch in the GitHub UI, now is the perfect time to do that with
```text
$ cd suzaku
$ git checkout -b add-android-support
```
To make sure everything works correctly, start `sbt` and compile the included example app with
```text
$ sbt
> webDemo/fastOptJS
```
You can now try out the demo app in your browser at URL
<http://localhost:12345/webdemo/index.html>, served by the wonderful
[Workbench plugin](https://github.com/lihaoyi/workbench).
Now you're all set to play with the source code, make your modifications and test them locally. Before submitting your
contribution, please read the [Workflow](#workflow) and [Style guide](#style-guide) for more information on how.
## Background and motivation
Developing applications with graphical user interfaces is hard. Making them pretty, consistent and functional is even harder.
Having all that in a cross-platform environment is close to impossible. Until Suzaku :smile:
The current frameworks for cross-platform (or even plain web) app development tend to be either based on JavaScript, or not
support all the three major mobile platforms (web, Android and iOS). JavaScript is fine for simple applications but as your
requirements and complexity grow, you'll want a more solid language and a flexible framework to get the job done.
Suzaku was born out of the frustration of using JavaScript web frameworks in Scala.js. Even though Scala.js takes a lot of
the web development pain away, it still suffers from the use of JavaScript libraries underneath as they are not designed to
be used in strongly typed languages like Scala. Most of the libraries are also not compatible with each other and the result
is often an unholy alliance of Scala, jQuery, jQuery plugins, React framework and some support components. Some of these
frameworks, however, have good ideas and architectures (for example [React](https://facebook.github.io/react/) ) that would
work well in a pure Scala environment.
### Designed for mobile first
Suzaku was designed for mobile from the very beginning. Originally just for mobile web apps, but later on it became apparent
that the design would work very well in a true cross-platform environment, too. In mobile you have a serious problem with
performance. The CPUs are weak, but they almost always have multiple cores. Typical web (and native!) apps do not take
advantage of this, but run everything in a single thread. Reason is simple: multithreading is hard (especially on web) and
the frameworks do not provide much (if any) support for it. Thus the first concept of Suzaku was established:
> Suzaku takes advantage of multiple cores for high performance and responsive UX
In web development you don't get threads, you get _web workers_. These are more like separate processes as they do not share
memory with the main (UI) thread. In Suzaku your application code runs in a separate web worker while just the UI code runs
in the main thread. This keeps the UI responsive even when the app is doing something time consuming and fully utilizes
multiple cores for better efficiency.
### UI isolation
However, web workers are isolated and can communicate with each other and the main thread via messages only. To overcome this
challenge, the design must be asynchronous and based solely on messages. What this means in practice is that there has to be
a common _protocol_ between the application and the UI and it has to be serialized to cross the chasm. Now, this is nothing
new, X Window System has had it since 1984! And it is the second concept of Suzaku:
> All communication between the UI and the application is performed using a message protocol in binary
Why binary and not the more typical JSON? Because binary serialization is much more efficient size and speed wise. And we
happened to have a nice serialization library for it ([BooPickle](https://github.com/suzaku-io/boopickle)).
Having that protocol has the nice side effect that it isolates the application from the actual implementation of the UI, and
therefore opens up avenues towards true cross-platform development. When the UI is just a standard protocol, it doesn't
matter if the implementation is HTML, Android Material UI or iOS Cocoa Touch. They are (effectively) all the same from the
application's point of view.
Now that Suzaku turned into a cross-platform framework, we need to add some abstractions. The communication between threads
is no longer limited to web workers, but could be real threads under Android or iOS (or even remote!), so we need a library
to facilitate that. This is what [Arteria](https://github.com/suzaku-io/arteria) was built for. It's a library for
establishing virtual channels over a packet based connection. The protocols are type safe, extensible and automatically
serialized (using BooPickle).
### Friendly API
Although under the hood Suzaku uses some rather advanced techniques, it still needs to be easy and fun to use, while
remaining powerful and extensible at the same time. Suzaku borrows heavily from React (and especially
[React Native](http://facebook.github.io/react-native/)) in the way the UI is constructed. In principle the UI is fully
declarative and mirrors the state of your application. You just tell Suzaku what the user interface should look like _right
now_ and Suzaku makes it happen.
Everything is based on _components_ and _widgets_ making it easy to build complex applications through composition. For most
applications it's quite enough to use the built-in widgets, but Suzaku also allows the application to define their own
widgets with platform specific implementations.
## Design and Architecture
This section covers the architecture and design of Suzaku by going through the codebase in a (hopefully) meaningful order. We
walk through the various classes, traits and objects that make up Suzaku to give you an overview how things work together and
how applications are built using Suzaku.
### Project structure
Suzaku is a monorepo consisting of several interdependent projects. Here is a list of projects and what they are for:
| Project | Description |
| :-------------------------- | :----------------------------------------------------- |
| `core-shared` | Platform independent shared core of Suzaku. |
| `core-ui` | UI side of the core. |
| `core-app` | Application side of the core. |
| `base-widgets` | Platform independent definitions of base widgets. |
| `base-widgets-app` | Application side of base widgets. |
| `platform/web/core-shared` | Web specific implementation of the core. |
| `platform/web/core-ui` | Web specific implementation of the core-ui. |
| `platform/web/core-app` | Web specific implementation of the core-app. |
| `platform/web/base-widgets` | Web specific implementation of the base widgets. |
| `webdemo` | A simple application demonstrating the user of Suzaku. |
### UI and Application separation
In Suzaku the user interface implementation and your application code are running on different threads to benefit from
multi-core CPUs commonly used in all modern devices.

What this means in practice is that your application actually starts in the UI (main) thread and needs to instantiate the
application thread separately. To simplify the required application startup code, Suzaku provides
[`UIBase`](../../core-ui/shared/src/main/scala/suzaku/app/UIBase.scala) and
[`AppBase`](../../core-app/shared/src/main/scala/suzaku/app/AppBase.scala) helper classes.
The UI and the App communicate via a [`Transport`](../../core-shared/shared/src/main/scala/suzaku/platform/Transport.scala) that
sends messages between the two threads using a platform specific implementation.

The application developer must provide the transport and pass it to the constructors of `UiBase`, `UiEntry`, `AppBase` and
`AppEntry`. For example in a web application UI thread you would create an instance of `UiEntry` and implement its `start`
method.
```scala
@JSExportTopLevel("UIEntry")
object UIEntry extends suzaku.platform.web.UIEntry {
override def start(transport: Transport) = new StarterUI(transport)
}
```
This will export a top level JavaScript function that you can call from your HTML to start the application. It will create
a Web Worker transport and pass it to your `start` method, where you will instantiate the application.
```scala
class StarterUI(transport: Transport) extends UIBase(transport) {
override val platform = WebPlatform
override protected def main(): Unit = {
suzaku.platform.web.widget.registerWidgets(widgetManager.asInstanceOf[DOMUIManager])
}
}
```
In `StartUI` we define that we use the `WebPlatform` and register any widgets we'd like to use.
Similarly in the application thread you would extend `AppEntry` and `AppBase`.
```scala
@JSExportTopLevel("ClientEntry")
object ClientEntry extends AppEntry {
override def start(transport: Transport) = new StarterApp(transport)
}
class StarterApp(transport: Transport) extends AppBase(transport) {
override protected def main(): Unit = {
uiManager.render(Button(label = "Hello world!"))
}
}
```
In the `main` method you just need to render the root component of your user interface to get things started. This is
much like in React where you'd call `ReactDOM.render`.
On both sides the setup is very similar, creating entrypoints and instantiating your application class with the provided
transport. This is all you need to do to get Suzaku running.
### Declarative User Interface
The user interface in Suzaku is defined _declaratively_ by calling the
[`UIManagerProxy`](../../core-app/shared/src/main/scala/suzaku/ui/UIManagerProxy.scala)`.render` method. You provide a _root_
component, which in turn contains a _tree_ of other components and widgets. But these components and widgets are not real
instances, but _blueprints_ that declare what kind of component/widget should be instantiated. For example a simple login
view component might contain a `render` method that returns a tree of blueprints (simplified for the example):
```scala
def render(state: State) = {
Layout.Vertical()(
Label("Email"),
Input.Text(state.email),
Label("Password"),
Input.Password(state.password),
Button("Cancel"),
Button("Login")
)
}
```
We can illustrate this blueprint tree like this:

The call to, for example, `Button("Login")` will return an instance of `ButtonBlueprint` which extends
[`WidgetBlueprint`](../../core-app/shared/src/main/scala/suzaku/ui/WidgetBlueprint.scala) and is defined as:
```scala
case class ButtonBlueprint private[Button] (label: String, onClick: Option[() => Unit] = None) extends WidgetBlueprint {
type P = ButtonProtocol.type
type Proxy = ButtonProxy
type This = ButtonBlueprint
override def createProxy(viewId: Int, uiChannel: UIChannel) = new ButtonProxy(this)(viewId, uiChannel)
}
```
This blueprint is not the actual widget, it just declares how to create the widget. The blueprint contains _all_ the
information necessary to create an instance of the actual `Button` widget. If you are familiar with React, the blueprint is
quite similar to what component _props_ are in React, except in Suzaku the blueprint applies to both higher order
_components_ and _widgets_ alike.
### Widgets, blueprints, proxies and protocols
So what exactly is a _widget_ in Suzaku? The concrete widget resides safely in the UI thread whereas it's represented by a
[`WidgetProxy`](../../core-app/shared/src/main/scala/suzaku/ui/WidgetProxy.scala) on the App thread, which communicates with
the widget using a `Protocol`. The _proxy_ and the _widget_ are instantiated by Suzaku according to the data given in the
[`Blueprint`](../../core-app/shared/src/main/scala/suzaku/ui/Blueprint.scala). Sounds rather complicated (and it is!), but
for the user of Suzaku it's all hidden behind the blueprint.

But for someone wanting to create their own widgets, it's crucial to understand how these things work under the hood. Let's
walk through the creation of a `Button` widget and see what happens behind the scenes.
When a user calls `Button("Login")` they actually call `Button.apply(label: String)` method in the `Button` object. This
method constructs an instance of `ButtonBlueprint` which is passed into the blueprint tree maintained by Suzaku. If this is
the first time Suzaku sees the blueprint in that location of the tree, it will create a proxy by calling `createProxy` in the
blueprint, passing an internal `viewId` and the Arteria channel used for UI communication. The `ButtonProxy` extends
[`WidgetProxy`](../../core-app/shared/src/main/scala/suzaku/ui/WidgetProxy.scala) which provides the basic implementation for
proxies.
```scala
class ButtonProxy private[Button] (bd: ButtonBlueprint)(viewId: Int, uiChannel: UIChannel)
extends WidgetProxy(ButtonProtocol, bd, viewId, uiChannel)
```
When the `WidgetProxy` is constructed, it creates a unique channel for communicating with the actual widget in the UI thread.
The widget is identified by the class name of the protocol. The `initWidget` method returns the initial state for the widget,
which in the case of `Button` contains just the `label` from the blueprint.
At this point things are pretty much done for the App thread, so let's take a look what happens on the UI thread. The
[`UIManager`](../../core-ui/shared/src/main/scala/suzaku/ui/UIManager.scala) gets a callback to _materialize_ a new
channel for the widget. Suzaku will look up an appropriate _builder_ for the widget (`DOMButtonBuilder` in this case) and
calls it to create the actual widget
([`DOMButton`](../../platform/web/base-widgets/src/main/scala/suzaku/platform/web/widget/DOMButton.scala)) passing the
initial state (containing the label).
Within `DOMButton` an _artifact_ is created by instantiating a suitable DOM element:
```scala
val artifact = {
val el = tag[dom.html.Button]("button")
uiManager.addListener(ClickEvent)(widgetId, el, onClick)
el.appendChild(labelNode)
DOMWidgetArtifact(el)
}
```
The artifact is not attached to the DOM document at this point, it happens as part of updating the _children_ of the parent
widget (`Layout`). Once the `button` element is in the document, it becomes visible to the user and allows interaction.
### Widget messaging
So what happens when a user _clicks_ the button?
As we saw above, the `DOMButton` registers an event handler on the `button` element, listening to click events. When the user
clicks the button it will call this handler, which sends a `Click` message on the channel.
```scala
def onClick(e: dom.MouseEvent): Unit = {
channel.send(Click)
}
```
The `Click` message is defined in `ButtonProtocol` and is simply a case object. At this point it might be good to take a look
at the implementation of `ButtonProtocol`:
```scala
object ButtonProtocol extends Protocol {
sealed trait ButtonMessage extends Message
case class SetLabel(label: String) extends ButtonMessage
case object Click extends ButtonMessage
val bmPickler = compositePickler[ButtonMessage]
.addConcreteType[SetLabel]
.addConcreteType[Click.type]
implicit val (messagePickler, witnessMsg) = defineProtocol(bmPickler)
case class ChannelContext(label: String)
override val contextPickler = implicitly[Pickler[ChannelContext]]
}
```
A widget protocol is required to define three things:
1. Valid messages for this protocol (and an implicit witness(es) to provide evidence)
2. Initial channel context to be passed when the channel is created
3. Picklers (serializers) for messages and the context
In the case of button the only valid messages are `SetLabel`, which is used to update the button and `Click`, which is used
to indicate that the button was clicked. Note that the channel is always bidirectional, so any message can be sent in either
direction but typically most of the messages travel only in one direction.
When a message is sent on the channel using the `send` method, Suzaku (and Arteria underneath) pass it through the transport
to the other side, where it's routed to the appropriate message handler. This handler is the `process` method in the
`ButtonProxy` class:
```scala
override def process = {
case Click =>
blueprint.onClick.foreach(f => f())
case message =>
super.process(message)
}
```
In `process` we handle only the `Click` message and call the click handler defined in the blueprint, if any.
### UI changes
Previously we covered what happens on the first `render` call when the `Button` widget gets created, but how are changes in
the UI handled, for example if we change the button text from "Login" to "Logout"? Let's find out!
Because Suzaku is based on declarative UI, we need to render the UI again with the changed button component. Everything else
stays the same, but the last button is now defined as `Button("Logout")`. When the call to `uiManager.render` completes,
Suzaku will compare the memoized blueprint tree to the new tree returned by `render`. It will walk the tree and check if
1. widget type has changed
2. widget type is the same, but blueprint has changed
In the latter case it will call `ButtonBlueprint`'s `sameAs` method, which by default calls `equals` and therefore will
notice the change in the label. Next it will pass the new `ButtonBlueprint` to the current `ButtonProxy` instance using its
`update` method, which will check if the label has changed and then send an appropriate message to the widget to update the
label.
```scala
override def update(newBlueprint: ButtonBlueprint) = {
if (newBlueprint.label != blueprint.label)
send(SetLabel(newBlueprint.label))
super.update(newBlueprint)
}
```
This allows widgets to have very fine grained control over how to make updates in the UI. There's no need to perform
expensive virtual DOM comparisons, as the widget knows directly what needs to be updated.
The `DOMButton` receives the `SetLabel` message, and updates the DOM accordingly.
```scala
override def process = {
case SetLabel(label) =>
modifyDOM(_ => labelNode.data = label)
}
```
Note how the widget is performing a direct DOM manipulation, as it has full control over its own DOM tree. This makes updates
very efficient as the widget can decide the best update strategy.
### Styling
On the web the vast majority of styling is done using external CSS style sheets. While this approach worked well for the
static HTML pages, it becomes cumbersome and hard to maintain in a component oriented application. Suzaku provides similar
styling features to CSS, but the styles are always attached to widgets. There are, however, multiple ways to do styling in
Suzaku so let's walk through them to understand how they work.
#### Inline styling
First level of styling is attaching style properties directly to individual widgets. You do this by importing
`suzaku.ui.style._` and using the properties defined there.
```scala
import suzaku.ui.style._
Button("OK") << (backgroundColor := Colors.blue)
```
The styles are attached to the widget using the `<<` method (or the `withStyle` alias), providing a list of properties. In
this example we're setting the background color to `blue`. This syntax is an alternative to using the style property classes
directly as below:
```scala
Button("OK") << BackgroundColor(Colors.blue)
```
The former syntax was chosen because it closely resembles CSS and is therefore easier to many frontend developers. For some
style values, such as lengths, automatic conversions are provided allowing you to write things like `width := 10.px` instead
of `Width(LengthPx(10))`.
So, how does the style system actually work under the hood? How is the style information communicated to the actual widget
since it's obviously external to the actual widget? Each `WidgetBlueprint` contains style information, which is built using
the `<<` method. Every call to `<<` adds one or more style properties to the internal map.
When the widget is instantiated and the `WidgetProxy` created, it sends a special `UpdateStyle` message automatically to the
widget implementation, which will then do the necessary updates for the actual widget. In the case of DOM widgets, this means
updating the `style` of the HTML element, resulting in something like:
```html
<button style="background-color: rgb(0, 0, 255);">OK</button>
```
Note how the color value is normalized into a standard RGB color, instead of the more familiar `#0000ff` format. Similar
normalization happens to many other style properties as well, because Suzaku styles are not directly CSS styles but something
a bit more abstract.
When a style property is updated, added or removed, `WidgetProxy` calculates a difference and communicates only the changed
styles over to the UI. This provides an efficient way to do style updates in the render code using conditionals:
```scala
backgroundColor := (if (state.checked) rgb(0, 0, 255) else rgb(255, 0, 0))
```
But declaring styles directly for each widget gets tedious and is not really the recommended practice. It works fine when you
need to do dynamic styling, but otherwise you should use style classes.
#### Style classes
A style class is a static collection of style properties with a unique name. To create a style class, simply define an
`object` extending the `StyleClass` class and override the `style` method:
```scala
object Red extends StyleClass {
def style = List(
color := 0xFF0000,
backgroundColor := Colors.white
)
}
```
You can now use your style class to style a widget:
```scala
Button("OK") << Red
```
Although on the surface this looks similar to what you get with inline styles, internally it works quite differently. Suzaku
takes advantage of `object`'s singleton behavior and registers the style class the first time it's used. The registration
process allocates an internal identifier (just an integer) to the style class and passes the declared style properties to the
UI. On the UI side (for DOM) a new CSS class is created and injected to the header of the page, for example:
```html
<style type="text/css">
._S1 {color:rgb(255,0,0);background-color:rgb(255,255,255);}
</style>
```
When the `Red` style class is used, only its identifier is passed, allowing the widget implementation to know which CSS class
to use.
```html
<button class="_S1">OK</button>
```
Style classes can also inherit other style classes, allowing the developer to build complex style hierarchies easily. For
example to define a large, red button with some custom fonts:
```scala
object Large extends StyleClass {
def style = List(
height := 100.px
)
}
object LargeRedButton extends StyleClass {
def style = List(
inheritClasses := (Large, Red),
fontFamily := ("Times New Roman", "Times", "serif"),
fontSize := xxlarge,
fontWeight := 600
)
}
```
Although style classes make it easier to assign complex styles to widgets, they still require developer to do it explicitly.
To automatically apply styles to widgets you need to use themes.
#### Style themes
A theme is simply an automatic application of given style classes to widgets. To create a theme, simply define the
associations between widgets and style classes using `Theme`:
```scala
val theme = Theme(
Button -> LargeRedButton,
TextInput -> (Large :: InputStyle :: Nil)
)
```
You can assign one or more styles to each widget and they will be applied in the correct order. Since themes are not automatically registered, you have to activate them explicitly.
```scala
val themeId = uiManager.activateTheme(theme)
...
uiManager.deactivateTheme(themeId)
```
There can be multiple active themes at the same time and you can deactivate and reactivate them at any time.
Suzaku maintains a list of active themes and automatically applies style classes to widgets when they are created.
#### Responsive styles
What responsive design means in web-talk is a UI design that responds to changes in its environment, most notably the screen
size and device type. The developer might want to use a certain set of styles on a desktop browser, but different set on a
mobile device. Suzaku has a lot of features built specifically for responsive design and two of those are in the style
system.
First one is the dynamic use of themes. You can define a separate theme for desktop and mobile versions, and switch between
them depending on the current situation.
Second option is to _remap_ individual style classes. Unlike themes, remapping operates within the widget hierarchy and each
mapping only affects the descendants of a widget. For example within a component, you might want to use a different style for
buttons when on mobile.
```scala
LinearLayout()( ... ) << (
if(onMobile) remapClass := (RedButton -> LargeRedButton :: Nil) else EmptyStyle
)
```
Internally Suzku keeps track of remappings and applies them to widgets automatically.
### Widget styling for Web
In addition to application level styling, Suzaku also has styling in the platform specific widgets. This styling is naturally
different for each platform so the description here applies only to the web platform.
Since Suzaku doesn't use any external CSS files to provide styling, all the style information must be generated in code.
There is a bit of "global" CSS generated by `DOMUIManager` but most of it is provided by the widget implementations. To make
this generated CSS configurable, widgets refer to `WidgetStyleConfig` and `StyleConfig` instances providing parameters for
fonts, sizes, colors, etc. For example `DOMTextField` builds its style using several of these parameters:
```scala
val base = uiManager.registerCSSClass(palette => s"""
|width: 100%;
|height: ${show(styleConfig.inputHeight)};
|line-height: ${show(styleConfig.inputHeight)};
|border: solid ${show(styleConfig.inputBorderWidth)} ${show(styleConfig.inputBorderColor)};
|color: ${show(palette(Palette.Base).color.foregroundColor)};
...
"""
```
The `registerCSSClass` method registers a builder function for the style class and returns the name of the CSS class. This
allows the system to later rebuild the style in case parameters or the palette changes. Since the currently active palette is
provided as an argument to the builder function, widget style can refer to current palette colors.
For CSS pseudo-classes like `:hover` and `:active` you can use the `addCSS` method to register it for your base CSS class:
```scala
uiManager.addCSS(s".$base:hover", s"""box-shadow: ${styleConfig.buttonBoxShadowHover};""".stripMargin)
```
### Layouts
The layout system in Suzaku works very similarly to styles. Each widget can have layout properties that affect how it's laid
out in the container. By default Suzaku supports two kinds of layout containers: linear and grid. If you're familiar with CSS
layout system, a `LinearLayout` is like a flexbox (and implemented with that in the DOM) while the `GridLayout` is like CSS3
grid (again, implemented with CSS grid in DOM UI).
Layout widgets are widgets like others, but they manage their children directly. This means, for example, that a
`LinearLayout` can change the CSS style of its child widget to apply an appropriate layout. You could have a `Button` in a
vertical layout that wants to be positioned to the right by specifying:
```scala
Button("OK").withLayout(alignSelf := end)
```
Unlike styles, the button widget doesn't apply this layout parameter itself but when it's positioned inside a `LinearLayout`
the layout widget goes and sets a CSS style property `align-self: flex-end;` for the button. In case it's positioned inside a
`GridLayout`, the resulting style would be `align-self: end;`.
The linear layout is pretty straight forward, but the `GridLayout` is more interesting. To define a grid layout, you need to
define _columns_ and _rows_, and an optional list of slots:
```scala
GridLayout(
400.px ~ 400.px ~ 200.px ~ 200.px,
100.px ~ 300.px ~ 100.px,
List(
Layout1 :: Layout1 :: Layout1 :: Layout2 :: Nil,
Layout3 :: Layout3 :: Layout3 :: Layout2 :: Nil,
Layout3 :: Layout3 :: Layout3 :: Layout4 :: Nil
)
)(...)
```
Columns and rows are defined via their widths, that can be absolute values like `100.px` or a relative value `1.fr`. See CSS3
grid documentation on how it works in practice. The slots parameter gives names to areas in the grid that can be used to
position the child elements into specific slots.
| |Col 1|Col 2|Col 3|Col 4|
|-----|---------|---------|---------|---------|
|**Row 1**| Layout1 | Layout1 | Layout1 | Layout2 |
|**Row 2**| Layout3 | Layout3 | Layout3 | Layout2 |
|**Row 3**| Layout3 | Layout3 | Layout3 | Layout4 |
Each `LayoutX` is an instance of `LayoutId`, automatically registered and assigned an identifier. Once the layout has been
defined, individual children will be positioned into the matching slots:
```scala
object Layout1 extends LayoutId
object Layout2 extends LayoutId
object Layout3 extends LayoutId
object Layout4 extends LayoutId
GridLayout(...)(
Button("1").withLayout(slot := Layout1),
Button("2").withLayout(slot := Layout2),
Button("3").withLayout(slot := Layout3)
)
```
### Components
If Suzaku provided only widgets, the application would have to render the whole static widget blueprint tree from the root on
every little change. To get more dynamic updates, you need to use _components_. Like widgets, components are also represented
by blueprints, but extending [`ComponentBlueprint`](../../core-shared/shared/src/main/scala/suzaku/ui/ComponentBlueprint.scala). The
`ComponentBlueprint` is even simpler than `WidgetBlueprint`, having only two methods:
```scala
trait ComponentBlueprint extends Blueprint {
def create(proxy: StateProxy): Component[_, _]
def sameAs(that: this.type): Boolean = equals(that)
}
```
The `sameAs` method is used to check if the blueprint has changed from the previously rendered just like in widgets, and the
`create` method is used to instantiate the actual [`Component`](../../core-shared/shared/src/main/scala/suzaku/ui/Component.scala).
#### Component lifecycle
A component has a well defined _lifecycle_ that begins by calling the **constructor** of your component class when it's first
mounted. This is followed by a call to `initialState` to get the, you know, initial state of your component. Next up is a
call to `render` to retrieve the contents of the component. Finally `didMount` is called to indicate that your component is
ready.

After the component has been constructed, there are only three things that can happen to it:
1. a blueprint change
2. a state change
3. destruction
A blueprint change means that the component was rendered again by some other component higher in the hierarchy, but with
different parameters, for example the label on a `Button` might have changed. Instead of building a new component, Suzaku
informs the mounted component about the change through `willReceiveBlueprint` providing access to the upcoming blueprint so
that the component can modify its internal state if necessary. This is followed by a call to `shouldUpdate` which is Suzaku's
way of asking "has something really changed or should we just skip render"? If it returns `true` (as it does by default), the
component `render` is called, followed by a call to `didUpdate`.

For a _state_ change the call sequence is the same, except the `willReceiveBlueprint` is naturally skipped.

Finally after the component is removed from UI and destroyed, its `didUnmount` method is called. This is a good place to remove
any handlers or callbacks you might have registered in `didMount`.

#### Component state
What makes components useful is that they can have internal mutable _state_. This allows components to react to incoming
events like user interaction and modify their state, which leads to re-rendering of the component. But the state of component
is held tight inside Suzaku and the component is only given read-only (not strongly enforced, though) access to it. The
different callback methods liked `render` and `shouldUpdate` are given a reference to the current state, so that component
code may use it. Otherwise it's hidden. Note that this _state_ should only be used to store data that is needed in the render
and all other internal "state" should be kept as variables in the component class. This would include things like handles for
registered listeners that need to be unregistered at unmount time. Suzaku never recreates the component instance, so your
data is safe inside the class.
To make changes in the state, you have to go through `modState(f: State => State)` giving as parameter a function that
performs the desired change in the state. This change may happen asynchronously at a later time, when the Suzaku frameworks
sees fit to actually perform the change (or a list of pending changes). In any case, before any callback method is called,
the state will have been modified. In a typical scenario the state is reprented as a `case class` and modifications to it use
the `copy` method to only partially update the class. For example:
```scala
case class MyState(user: String, password: String)
...
modState(s => s.copy(user = newUser))
```
... to be continued ...
### UI testing
A benefit of a protocol based UI is that it allows easy testing. You can simple replace a real UI implementation with a
mocked one to create exactly the test situations you need without involving any platform specific code whatsoever. Testing
user interaction scenarios is typically very tedious and hard work, but now it's reduced to defining a message exchange
sequence. Of course you still have to test the actual UI, too, but application interaction logic can be tested without the
real UI.
... More coming soon! ...
## Workflow
This is the general workflow for contributing to Suzaku (adapted from
[Scala.js](https://github.com/scala-js/scala-js/blob/master/CONTRIBUTING.md))
1. You should always perform your work in its own Git branch (a "topic branch"). The branch should be given a descriptive
name that explains its intent.
2. When the feature or fix is completed you should [squash](https://help.github.com/articles/about-pull-request-merges/) your
commits into a one (per useful change), [rebase](https://help.github.com/articles/about-git-rebase/) it against the
original branch and open a [Pull Request](https://help.github.com/articles/about-pull-requests/) on GitHub. Squashing
commits keeps the version history clean and clutter free. Typically your PR should target the `master` branch, but there
may be other work-in-progress branches that you can also target in your PR. This is especially true if you have originally
branched from such a WIP branch.
3. The Pull Request should be reviewed by the maintainers. Independent contributors can also participate in the review
process, and are encouraged to do so. There is also an automated CI build that checks that your PR is compiling ok and
tests run without errors.
4. After the review, you should resolve issues brought up by the reviewers as needed (amending or adding commits to address
reviewers' comments), iterating until the reviewers give their thumbs up, the "LGTM" (acronym for "Looks Good To Me").
While iterating, you can push (and squash) new commits to your topic branch and they will show up in the PR automatically.
5. Once the code has passed review the Pull Request can be merged into the distribution.
### Tests
Tests are nice. They help keep the code in working condition even through refactorings and other changes. When you add new
functionality, please write some relevant tests to cover the new functionality. When changing existing code, make sure the
tests are also changed to reflect this.
### Documentation
All code contributed to the user-facing part of the library should come accompanied with documentation. Pull requests
containing undocumented code will not be accepted.
Code contributed to the internals (ie. code that the users of Suzaku typically do not directly use) should come accompanied
by internal documentation if the code is not self-explanatory, e.g., important design decisions that other maintainers should
know about.
### Creating Commits And Writing Commit Messages
Follow these guidelines when creating public commits and writing commit messages.
#### Prepare meaningful commits
If your work spans multiple local commits (for example; if you do safe point commits while working in a feature branch or
work in a branch for long time doing merges/rebases etc.) then please do not commit it all but rewrite the history by
squashing the commits into **one commit per useful unit of change**, each accompanied by a detailed commit message. For more
info, see the article: [Git Workflow](http://sandofsky.com/blog/git-workflow.html). Additionally, every commit should be able
to be used in isolation - that is, each commit must build and pass all tests.
#### Use `scalafmt`
Run `scalafmt` before making a commit to keep source code in style.
#### First line of the commit message
The first line should be a descriptive sentence about what the commit is doing, written using the imperative style, e.g.,
"Change this.", and should not exceed 70 characters. It should be possible to fully understand what the commit does by just
reading this single line. It is **not ok** to only list the ticket number, type "minor fix" or similar. If the commit has a
corresponding ticket, include a reference to the ticket number, with the format "Fix #xxx: Change that.", as the first line.
Sometimes, there is no better message than "Fix #xxx: Fix that issue.", which is redundant. In that case, and assuming that
it aptly and concisely summarizes the commit in a single line, the commit message should be "Fix #xxx: Title of the ticket.".
#### Body of the commit message
If the commit is a small fix, the first line can be enough. Otherwise, following the single line description should be a
blank line followed by details of the commit, in the form of free text, or bulleted list.
## Style guide
Suzaku has a rather flexible styling requirements for contributors so don't fret about it too much. The maintainers will ask
you to fix clear style violations in your contributions or just correct them in the next refactoring/clean-up. All source
code in Suzaku is formatted using [scalafmt](http://scalameta.org/scalafmt/) to maintain coherent style across the project.
What this means is that you don't have to worry too much about the style, but just let `scalafmt` handle it! Before making a
commit, just run `sbt scalafmt` to apply the default styling to the whole codebase.
It is of course much appreciated if you'd spend a few moments looking through the existing code base and try to pick up some
clues about the style being used ;)
## Practical tips
Coming soon!
| {
"content_hash": "08ac3494756b439ac1adc283aa68db67",
"timestamp": "",
"source": "github",
"line_count": 866,
"max_line_length": 180,
"avg_line_length": 50.288683602771364,
"alnum_prop": 0.7644087256027554,
"repo_name": "suzaku-io/suzaku",
"id": "0d4216eabb833696d9a88a3f00f39b4b3781d9d6",
"size": "43579",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/contributor/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "3699"
},
{
"name": "JavaScript",
"bytes": "516"
},
{
"name": "Scala",
"bytes": "281639"
}
],
"symlink_target": ""
} |
import { isPresent } from 'angular2/src/facade/lang';
import { unimplemented } from 'angular2/src/facade/exceptions';
import { DOM } from 'angular2/src/core/dom/dom_adapter';
import { ViewType } from 'angular2/src/core/linker/view';
import { internalView } from 'angular2/src/core/linker/view_ref';
/**
* A DebugElement contains information from the Angular compiler about an
* element and provides access to the corresponding ElementInjector and
* underlying DOM Element, as well as a way to query for children.
*/
export class DebugElement {
get componentInstance() { return unimplemented(); }
;
get nativeElement() { return unimplemented(); }
;
get elementRef() { return unimplemented(); }
;
/**
* Get child DebugElements from within the Light DOM.
*
* @return {DebugElement[]}
*/
get children() { return unimplemented(); }
;
/**
* Get the root DebugElement children of a component. Returns an empty
* list if the current DebugElement is not a component root.
*
* @return {DebugElement[]}
*/
get componentViewChildren() { return unimplemented(); }
;
/**
* Return the first descendant TestElement matching the given predicate
* and scope.
*
* @param {Function: boolean} predicate
* @param {Scope} scope
*
* @return {DebugElement}
*/
query(predicate, scope = Scope.all) {
var results = this.queryAll(predicate, scope);
return results.length > 0 ? results[0] : null;
}
/**
* Return descendant TestElememts matching the given predicate
* and scope.
*
* @param {Function: boolean} predicate
* @param {Scope} scope
*
* @return {DebugElement[]}
*/
queryAll(predicate, scope = Scope.all) {
var elementsInScope = scope(this);
return elementsInScope.filter(predicate);
}
}
export class DebugElement_ extends DebugElement {
constructor(_parentView, _boundElementIndex) {
super();
this._parentView = _parentView;
this._boundElementIndex = _boundElementIndex;
this._elementInjector = this._parentView.elementInjectors[this._boundElementIndex];
}
get componentInstance() {
if (!isPresent(this._elementInjector)) {
return null;
}
return this._elementInjector.getComponent();
}
get nativeElement() { return this.elementRef.nativeElement; }
get elementRef() { return this._parentView.elementRefs[this._boundElementIndex]; }
getDirectiveInstance(directiveIndex) {
return this._elementInjector.getDirectiveAtIndex(directiveIndex);
}
get children() {
return this._getChildElements(this._parentView, this._boundElementIndex);
}
get componentViewChildren() {
var shadowView = this._parentView.getNestedView(this._boundElementIndex);
if (!isPresent(shadowView) || shadowView.proto.type !== ViewType.COMPONENT) {
// The current element is not a component.
return [];
}
return this._getChildElements(shadowView, null);
}
triggerEventHandler(eventName, eventObj) {
this._parentView.triggerEventHandlers(eventName, eventObj, this._boundElementIndex);
}
hasDirective(type) {
if (!isPresent(this._elementInjector)) {
return false;
}
return this._elementInjector.hasDirective(type);
}
inject(type) {
if (!isPresent(this._elementInjector)) {
return null;
}
return this._elementInjector.get(type);
}
getLocal(name) { return this._parentView.locals.get(name); }
/** @internal */
_getChildElements(view, parentBoundElementIndex) {
var els = [];
var parentElementBinder = null;
if (isPresent(parentBoundElementIndex)) {
parentElementBinder = view.proto.elementBinders[parentBoundElementIndex - view.elementOffset];
}
for (var i = 0; i < view.proto.elementBinders.length; ++i) {
var binder = view.proto.elementBinders[i];
if (binder.parent == parentElementBinder) {
els.push(new DebugElement_(view, view.elementOffset + i));
var views = view.viewContainers[view.elementOffset + i];
if (isPresent(views)) {
views.views.forEach((nextView) => { els = els.concat(this._getChildElements(nextView, null)); });
}
}
}
return els;
}
}
/**
* Returns a DebugElement for a ElementRef.
*
* @param {ElementRef}: elementRef
* @return {DebugElement}
*/
export function inspectElement(elementRef) {
return new DebugElement_(internalView(elementRef.parentView), elementRef.boundElementIndex);
}
export function asNativeElements(arr) {
return arr.map((debugEl) => debugEl.nativeElement);
}
export class Scope {
static all(debugElement) {
var scope = [];
scope.push(debugElement);
debugElement.children.forEach(child => scope = scope.concat(Scope.all(child)));
debugElement.componentViewChildren.forEach(child => scope = scope.concat(Scope.all(child)));
return scope;
}
static light(debugElement) {
var scope = [];
debugElement.children.forEach(child => {
scope.push(child);
scope = scope.concat(Scope.light(child));
});
return scope;
}
static view(debugElement) {
var scope = [];
debugElement.componentViewChildren.forEach(child => {
scope.push(child);
scope = scope.concat(Scope.light(child));
});
return scope;
}
}
export class By {
static all() { return (debugElement) => true; }
static css(selector) {
return (debugElement) => {
return isPresent(debugElement.nativeElement) ?
DOM.elementMatches(debugElement.nativeElement, selector) :
false;
};
}
static directive(type) {
return (debugElement) => { return debugElement.hasDirective(type); };
}
}
//# sourceMappingURL=debug_element.js.map | {
"content_hash": "597f2ff1dcbcfcdd580e7974bed66872",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 117,
"avg_line_length": 35.114285714285714,
"alnum_prop": 0.6276647681041497,
"repo_name": "binariedMe/blogging",
"id": "2c02c3fdc1d7dbae1a9172494448b7b7432e692c",
"size": "6145",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "node_modules/angular2/es6/prod/src/core/debug/debug_element.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2143"
},
{
"name": "HTML",
"bytes": "15744"
},
{
"name": "JavaScript",
"bytes": "288352"
},
{
"name": "TypeScript",
"bytes": "18086"
}
],
"symlink_target": ""
} |
CREATE SEQUENCE listicle.s_actor_id START WITH 100;
CREATE TABLE listicle.actor (
id BIGINT NOT NULL,
first_name VARCHAR(100),
last_name VARCHAR(100),
birth_date DATE,
country_id BIGINT,
CONSTRAINT pk_actor PRIMARY KEY (id),
CONSTRAINT fk_actor_country_id FOREIGN KEY (country_id) REFERENCES listicle.country(id)
) | {
"content_hash": "e9898c0548e64227aa6a44b25d823177",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 89,
"avg_line_length": 25.46153846153846,
"alnum_prop": 0.7462235649546828,
"repo_name": "chriswk/listicle",
"id": "5dc5e5bc4b7fb3e5ff0ba8060ba6747f99a922ce",
"size": "331",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/resources/db/migration/V3__create_actor_table.sql",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "81"
},
{
"name": "Java",
"bytes": "2252"
},
{
"name": "Kotlin",
"bytes": "3553"
}
],
"symlink_target": ""
} |
This repo has astronomy related code that I've used in my work which may be useful for other
researchers. Note that, while as a general principle I try to make my
code readable and fairly well-commented, the data in this repo was not
originally designed to be used by other people. As a result it's
possible that there are confusing bits and subtle bugs, so USE AT YOUR
OWN RISK. Feel free to get in touch with me if you need help and/or
find a problem, but I can't guarantee support on any kind of timely
schedule (or indeed, any schedule at all). Similarly, If you do find some use out
of my code, I'd love to hear about it. If it results in a publication
an acknowledgement and/or link to the relevant piece(s) of code would
also be nice.
Good luck!
-Andrew Schechtman-Rook
| {
"content_hash": "baf0b747923444f6583e9fee7ce2539b",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 92,
"avg_line_length": 51.93333333333333,
"alnum_prop": 0.7779204107830552,
"repo_name": "AndrewRook/astro",
"id": "c47282d60013818a812b1eb6d73456fa1439af50",
"size": "779",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "15590"
}
],
"symlink_target": ""
} |
#ifndef __STATIC_BUFFERS_H__
#define __STATIC_BUFFERS_H__
#include "matmul.h"
extern volatile float AA[2][_Score][_Score]; // local A submatrix
extern volatile float BB[2][_Score][_Score]; // local B submatrix
extern volatile float CC [_Score][_Score]; // local C submatrix
extern core_t me; // core data structure
extern volatile shared_buf_ptr_t Mailbox; // Mailbox pointers;
#endif // __STATIC_BUFFERS_H__
| {
"content_hash": "03906e76ceb10e9315ad629eb577ab57",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 70,
"avg_line_length": 28.9375,
"alnum_prop": 0.6306695464362851,
"repo_name": "parallella/pal",
"id": "7cfe987d5178d841e4c369384fcbb78ba1ac6cb9",
"size": "1231",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "examples/math/matmul/static-buffers.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "2375"
},
{
"name": "C",
"bytes": "1200116"
},
{
"name": "C++",
"bytes": "6753"
},
{
"name": "CSS",
"bytes": "895"
},
{
"name": "Erlang",
"bytes": "75621"
},
{
"name": "HTML",
"bytes": "68079"
},
{
"name": "M4",
"bytes": "35028"
},
{
"name": "Makefile",
"bytes": "7369"
},
{
"name": "Python",
"bytes": "1602"
},
{
"name": "Shell",
"bytes": "5445"
}
],
"symlink_target": ""
} |
package org.sakaiproject.tool.assessment.services.shared;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.sakaiproject.tool.assessment.facade.TypeFacade;
import org.sakaiproject.tool.assessment.services.PersistenceService;
/**
* The QuestionPoolService calls the service locator to reach the
* manager on the back end.
* @author Rachel Gollub <[email protected]>
*/
@Slf4j
public class TypeService
{
/**
* Creates a new QuestionPoolService object.
*/
public TypeService() {
}
public TypeFacade getTypeById(String typeId)
{
try{
return PersistenceService.getInstance().getTypeFacadeQueries().
getTypeFacadeById(new Long(typeId));
}
catch(Exception e)
{
log.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
public List getFacadeListByAuthorityDomain(String authority, String domain)
{
try{
return PersistenceService.getInstance().getTypeFacadeQueries().
getFacadeListByAuthorityDomain(authority,domain);
}
catch(Exception e)
{
log.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
public List getListByAuthorityDomain(String authority, String domain)
{
try{
return PersistenceService.getInstance().getTypeFacadeQueries().
getListByAuthorityDomain(authority,domain);
}
catch(Exception e)
{
log.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
public List getFacadeItemTypes() {
try{
return PersistenceService.getInstance().getTypeFacadeQueries().
getFacadeItemTypes();
}
catch(Exception e)
{
log.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
}
| {
"content_hash": "8527c79f80c0b4e65ad8185e531933ba",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 77,
"avg_line_length": 22.525641025641026,
"alnum_prop": 0.6807057484348321,
"repo_name": "OpenCollabZA/sakai",
"id": "818610c6ed0e555922a091e33cba7f8741c82ec4",
"size": "2669",
"binary": false,
"copies": "36",
"ref": "refs/heads/master",
"path": "samigo/samigo-services/src/java/org/sakaiproject/tool/assessment/services/shared/TypeService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "59098"
},
{
"name": "Batchfile",
"bytes": "5172"
},
{
"name": "CSS",
"bytes": "2123328"
},
{
"name": "ColdFusion",
"bytes": "146057"
},
{
"name": "HTML",
"bytes": "6308955"
},
{
"name": "Java",
"bytes": "48045196"
},
{
"name": "JavaScript",
"bytes": "9374877"
},
{
"name": "Lasso",
"bytes": "26436"
},
{
"name": "PHP",
"bytes": "606568"
},
{
"name": "PLSQL",
"bytes": "2328131"
},
{
"name": "Perl",
"bytes": "61738"
},
{
"name": "Python",
"bytes": "44698"
},
{
"name": "Ruby",
"bytes": "1276"
},
{
"name": "Shell",
"bytes": "19259"
},
{
"name": "SourcePawn",
"bytes": "2247"
},
{
"name": "XSLT",
"bytes": "280557"
}
],
"symlink_target": ""
} |
<resources>
<string name="app_name">AndroidBeaconLibrary</string>
</resources> | {
"content_hash": "056a6d3f3d370941c6f310e44dda6400",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 57,
"avg_line_length": 27.333333333333332,
"alnum_prop": 0.7439024390243902,
"repo_name": "JimSeker/bluetooth",
"id": "bf600936e133082454569d346a5a1ec3949ba9f6",
"size": "82",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AndroidBeaconLibraryDemo/app/src/main/res/values/strings.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "187569"
}
],
"symlink_target": ""
} |
from django.utils import six
from rq.decorators import job as _rq_job
from .queues import get_queue
def job(func_or_queue, connection=None, *args, **kwargs):
"""
The same as RQ's job decorator, but it works automatically works out
the ``connection`` argument from RQ_QUEUES.
And also, it allows simplified ``@job`` syntax to put job into
default queue.
"""
if callable(func_or_queue):
func = func_or_queue
queue = 'default'
else:
func = None
queue = func_or_queue
if isinstance(queue, six.string_types):
try:
queue = get_queue(queue)
if connection is None:
connection = queue.connection
except KeyError:
pass
decorator = _rq_job(queue, connection=connection, *args, **kwargs)
if func:
return decorator(func)
return decorator
| {
"content_hash": "ccaae4103e12762507f02d5a88e87a59",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 72,
"avg_line_length": 26.11764705882353,
"alnum_prop": 0.6137387387387387,
"repo_name": "sbussetti/django-rq",
"id": "b64c20c97fbf3064b53d840f2581b09489d435ac",
"size": "888",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "django_rq/decorators.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "17797"
},
{
"name": "Makefile",
"bytes": "97"
},
{
"name": "Python",
"bytes": "59491"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_75) on Sat May 16 22:22:29 CEST 2015 -->
<title>SSTableDeletingNotification</title>
<meta name="date" content="2015-05-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="SSTableDeletingNotification";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/apache/cassandra/notifications/SSTableAddedNotification.html" title="class in org.apache.cassandra.notifications"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/apache/cassandra/notifications/SSTableListChangedNotification.html" title="class in org.apache.cassandra.notifications"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/cassandra/notifications/SSTableDeletingNotification.html" target="_top">Frames</a></li>
<li><a href="SSTableDeletingNotification.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#methods_inherited_from_class_java.lang.Object">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.cassandra.notifications</div>
<h2 title="Class SSTableDeletingNotification" class="title">Class SSTableDeletingNotification</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.apache.cassandra.notifications.SSTableDeletingNotification</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../../../../org/apache/cassandra/notifications/INotification.html" title="interface in org.apache.cassandra.notifications">INotification</a></dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">SSTableDeletingNotification</span>
extends java.lang.Object
implements <a href="../../../../org/apache/cassandra/notifications/INotification.html" title="interface in org.apache.cassandra.notifications">INotification</a></pre>
<div class="block">Fired right before removing an SSTable.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../org/apache/cassandra/io/sstable/format/SSTableReader.html" title="class in org.apache.cassandra.io.sstable.format">SSTableReader</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/notifications/SSTableDeletingNotification.html#deleting">deleting</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../org/apache/cassandra/notifications/SSTableDeletingNotification.html#SSTableDeletingNotification(org.apache.cassandra.io.sstable.format.SSTableReader)">SSTableDeletingNotification</a></strong>(<a href="../../../../org/apache/cassandra/io/sstable/format/SSTableReader.html" title="class in org.apache.cassandra.io.sstable.format">SSTableReader</a> deleting)</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="deleting">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>deleting</h4>
<pre>public final <a href="../../../../org/apache/cassandra/io/sstable/format/SSTableReader.html" title="class in org.apache.cassandra.io.sstable.format">SSTableReader</a> deleting</pre>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="SSTableDeletingNotification(org.apache.cassandra.io.sstable.format.SSTableReader)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>SSTableDeletingNotification</h4>
<pre>public SSTableDeletingNotification(<a href="../../../../org/apache/cassandra/io/sstable/format/SSTableReader.html" title="class in org.apache.cassandra.io.sstable.format">SSTableReader</a> deleting)</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/apache/cassandra/notifications/SSTableAddedNotification.html" title="class in org.apache.cassandra.notifications"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/apache/cassandra/notifications/SSTableListChangedNotification.html" title="class in org.apache.cassandra.notifications"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/cassandra/notifications/SSTableDeletingNotification.html" target="_top">Frames</a></li>
<li><a href="SSTableDeletingNotification.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#methods_inherited_from_class_java.lang.Object">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "46767d5890e63391c1140f24f23d3796",
"timestamp": "",
"source": "github",
"line_count": 268,
"max_line_length": 432,
"avg_line_length": 37.343283582089555,
"alnum_prop": 0.6565747402078337,
"repo_name": "sayanh/ViewMaintenanceCassandra",
"id": "5c005260894f2e8608095677e33d3cddb6f0f9e7",
"size": "10008",
"binary": false,
"copies": "1",
"ref": "refs/heads/trunk",
"path": "doc/org/apache/cassandra/notifications/SSTableDeletingNotification.html",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "801"
},
{
"name": "Batchfile",
"bytes": "21834"
},
{
"name": "GAP",
"bytes": "62279"
},
{
"name": "Java",
"bytes": "10347352"
},
{
"name": "PowerShell",
"bytes": "39438"
},
{
"name": "Python",
"bytes": "314996"
},
{
"name": "Shell",
"bytes": "50026"
},
{
"name": "Thrift",
"bytes": "40282"
}
],
"symlink_target": ""
} |
<?php
namespace IPS\core\extensions\core\FileStorage;
/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
exit;
}
/**
* File Storage Extension: Emoticons
*/
class _Emoticons
{
/**
* Count stored files
*
* @return int
*/
public function count()
{
return \IPS\Db::i()->select( 'COUNT(*)', 'core_emoticons' )->first();
}
/**
* Move stored files
*
* @param int $offset This will be sent starting with 0, increasing to get all files stored by this extension
* @param int $storageConfiguration New storage configuration ID
* @param int|NULL $oldConfiguration Old storage configuration ID
* @throws \UnderflowException When file record doesn't exist. Indicating there are no more files to move
* @return void|int An offset integer to use on the next cycle, or nothing
*/
public function move( $offset, $storageConfiguration, $oldConfiguration=NULL )
{
$emoticon = \IPS\Db::i()->select( '*', 'core_emoticons', array(), 'id', array( $offset, 1 ) )->first();
try
{
$file = \IPS\File::get( $oldConfiguration ?: 'core_Emoticons', $emoticon['image'] )->move( $storageConfiguration );
$image_2x = NULL;
if ( $emoticon['image_2x'] )
{
$image_2x = \IPS\File::get( $oldConfiguration ?: 'core_Emoticons', $emoticon['image_2x'] )->move( $storageConfiguration );
}
if ( (string) $file != $emoticon['image'] or (string) $image_2x != $emoticon['image_2x'] )
{
\IPS\Db::i()->update( 'core_emoticons', array( 'image' => (string) $file, 'image_2x' => (string) $image_2x ), array( 'id=?', $emoticon['id'] ) );
}
unset( \IPS\Data\Store::i()->emoticons );
}
catch( \Exception $e )
{
/* Any issues are logged */
}
}
/**
* Fix all URLs
*
* @param int $offset This will be sent starting with 0, increasing to get all files stored by this extension
* @return void
*/
public function fixUrls( $offset )
{
$emoticon = \IPS\Db::i()->select( '*', 'core_emoticons', array(), 'id', array( $offset, 1 ) )->first();
try
{
$fixed = array();
foreach( array( 'image', 'image_2x' ) as $location )
{
if ( $new = \IPS\File::repairUrl( $emoticon[ $location ] ) )
{
$fixed[ $location ] = $new;
}
}
if ( count( $fixed ) )
{
\IPS\Db::i()->update( 'core_emoticons', $fixed, array( 'id=?', $emoticon['id'] ) );
unset( \IPS\Data\Store::i()->emoticons );
}
}
catch( \Exception $e ) { }
}
/**
* Check if a file is valid
*
* @param \IPS\Http\Url $file The file to check
* @return bool
*/
public function isValidFile( $file )
{
try
{
$emoticon = \IPS\Db::i()->select( '*', 'core_emoticons', array( 'image=? or image_2x=?', (string) $file, (string) $file ) )->first();
return TRUE;
}
catch ( \UnderflowException $e )
{
return FALSE;
}
}
/**
* Delete all stored files
*
* @return void
*/
public function delete()
{
foreach( \IPS\Db::i()->select( '*', 'core_emoticons', 'image IS NOT NULL' ) as $emoticon )
{
try
{
\IPS\File::get( 'core_Emoticons', $emoticon['image'] )->delete();
\IPS\File::get( 'core_Emoticons', $emoticon['image_2x'] )->delete();
}
catch( \Exception $e ){}
}
}
} | {
"content_hash": "8acc8cbd2bdcf9fe5e7238b1d351a30b",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 149,
"avg_line_length": 25.666666666666668,
"alnum_prop": 0.5914994096812278,
"repo_name": "Tresint/worldherb",
"id": "3b0cb74f9bdc58f5aa00d348a669167797887c61",
"size": "3732",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "forum/applications/core/extensions/core/FileStorage/Emoticons.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3448"
},
{
"name": "CSS",
"bytes": "2759914"
},
{
"name": "HTML",
"bytes": "8322895"
},
{
"name": "JavaScript",
"bytes": "3367334"
},
{
"name": "PHP",
"bytes": "31426102"
},
{
"name": "Shell",
"bytes": "743"
},
{
"name": "Smarty",
"bytes": "33"
}
],
"symlink_target": ""
} |
BSLS_IDENT("$Id: $")
//@PURPOSE: Provide efficient creation of nodes used in a node-based container.
//
//@CLASSES:
// bslstl::BidirectionalNodePool: memory manager to allocate hash table nodes
//
//@SEE_ALSO: bslstl_simplepool
//
//@DESCRIPTION: This component implements a mechanism, 'BidirectionalNodePool',
// that creates and destroys 'bslalg::BidirectionalListNode' objects holding
// objects of a (template parameter) type 'VALUE' for use in hash-table-based
// containers.
//
// A 'BidirectionalNodePool' uses a memory pool provided by the
// 'bslstl_simplepool' component in its implementation to provide memory for
// the nodes (see 'bslstl_simplepool').
//
///Memory Allocation
///-----------------
// 'BidirectionalNodePool' uses an allocator of the (template parameter) type
// 'ALLOCATOR' specified at construction to allocate memory.
// 'BidirectionalNodePool' supports allocators meeting the requirements of the
// C++ standard allocator requirements ([allocator.requirements], C++11
// 17.6.3.5).
//
// If 'ALLOCATOR' is 'bsl::allocator' and the (template parameter) type 'VALUE'
// defines the 'bslma::UsesBslmaAllocator' trait, then the 'bslma::Allocator'
// object specified at construction will be supplied to constructors of the
// (template parameter) type 'VALUE' in the 'cloneNode' method and
// 'emplaceIntoNewNode' method overloads.
//
///Usage
///-----
// This section illustrates intended use of this component.
//
///Example 1: Creating a Linked List Container
///- - - - - - - - - - - - - - - - - - - - - -
// Suppose that we want to define a bidirectional linked list that can hold
// elements of a template parameter type. 'bslstl::BidirectionalNodePool' can
// be used to create and destroy nodes that make up a linked list.
//
// First, we create an elided definition of the class template 'MyList':
//..
// #include <bslalg_bidirectionallinklistutil.h>
//
// template <class VALUE, class ALLOCATOR>
// class MyList {
// // This class template implements a bidirectional linked list of
// // element of the (template parameter) type 'VALUE'. The memory used
// // will be allocated from an allocator of the (template parameter) type
// // 'ALLOCATOR' specified at construction.
//
// public:
// // TYPES
// typedef bslalg::BidirectionalNode<VALUE> Node;
// // This 'typedef' is an alias to the type of the linked list node.
//
// private:
// // TYPES
// typedef bslstl::BidirectionalNodePool<VALUE, ALLOCATOR> Pool;
// // This 'typedef' is an alias to the type of the memory pool.
//
// typedef bslalg::BidirectionalLinkListUtil Util;
// // This 'typedef' is an alias to the utility 'struct' providing
// // functions for constructing and manipulating linked lists.
//
// typedef bslalg::BidirectionalLink Link;
// // This 'typedef' is an alis to the type of the linked list link.
//
// // DATA
// Node *d_head_p; // pointer to the head of the linked list
// Node *d_tail_p; // pointer to the tail of the linked list
// Pool d_pool; // memory pool used to allocate memory
//
//
// public:
// // CREATORS
// MyList(const ALLOCATOR& allocator = ALLOCATOR());
// // Create an empty linked list that allocate memory using the
// // specified 'allocator'.
//
// ~MyList();
// // Destroy this linked list by calling destructor for each element
// // and deallocate all allocated storage.
//
// // MANIPULATORS
// void pushFront(const VALUE& value);
// // Insert the specified 'value' at the front of this linked list.
//
// void pushBack(const VALUE& value);
// // Insert the specified 'value' at the end of this linked list.
//
// //...
// };
//..
// Now, we define the methods of 'MyMatrix':
//..
// CREATORS
// template <class VALUE, class ALLOCATOR>
// MyList<VALUE, ALLOCATOR>::MyList(const ALLOCATOR& allocator)
// : d_head_p(0)
// , d_tail_p(0)
// , d_pool(allocator)
// {
// }
//
// template <class VALUE, class ALLOCATOR>
// MyList<VALUE, ALLOCATOR>::~MyList()
// {
// Link *link = d_head_p;
// while (link) {
// Link *next = link->nextLink();
//..
// Here, we call the memory pool's 'deleteNode' method to destroy the 'value'
// attribute of the node and return its memory footprint back to the pool:
//..
// d_pool.deleteNode(static_cast<Node*>(link));
// link = next;
// }
// }
//
// MANIPULATORS
// template <class VALUE, class ALLOCATOR>
// void
// MyList<VALUE, ALLOCATOR>::pushFront(const VALUE& value)
// {
//..
// Here, we call the memory pool's 'emplaceIntoNewNode' method to allocate a
// node and copy-construct the specified 'value' at the 'value' attribute of
// the node:
//..
// Node *node = static_cast<Node *>(d_pool.emplaceIntoNewNode(value));
//..
// Note that the memory pool will allocate the footprint of the node using the
// allocator specified at construction. If the (template parameter) type
// 'ALLOCATOR' is an instance of 'bsl::allocator' and the (template parameter)
// type 'VALUE' has the 'bslma::UsesBslmaAllocator' trait, then the allocator
// specified at construction will also be supplied to the copy-constructor of
// 'VALUE'.
//..
// if (!d_head_p) {
// d_tail_p = node;
// node->setNextLink(0);
// node->setPreviousLink(0);
// }
// else {
// Util::insertLinkBeforeTarget(node, d_head_p);
// }
// d_head_p = node;
// }
//
// template <class VALUE, class ALLOCATOR>
// void
// MyList<VALUE, ALLOCATOR>::pushBack(const VALUE& value)
// {
//..
// Here, just like how we implemented the 'pushFront' method, we call the
// pool's 'emplaceIntoNewNode' method to allocate a node and copy-construct the
// specified 'value' at the 'value' attribute of the node:
//..
// Node *node = static_cast<Node *>(d_pool.emplaceIntoNewNode(value));
// if (!d_head_p) {
// d_head_p = node;
// node->setNextLink(0);
// node->setPreviousLink(0);
// }
// else {
// Util::insertLinkAfterTarget(node, d_tail_p);
// }
// d_tail_p = node;
// }
//..
#ifndef INCLUDED_BSLSCM_VERSION
#include <bslscm_version.h>
#endif
#ifndef INCLUDED_BSLMA_ALLOCATORTRAITS
#include <bslma_allocatortraits.h>
#endif
#ifndef INCLUDED_BSLSTL_SIMPLEPOOL
#include <bslstl_simplepool.h>
#endif
#ifndef INCLUDED_BSLALG_BIDIRECTIONALLINK
#include <bslalg_bidirectionallink.h>
#endif
#ifndef INCLUDED_BSLALG_BIDIRECTIONALNODE
#include <bslalg_bidirectionalnode.h>
#endif
#ifndef INCLUDED_BSLMA_DEALLOCATORPROCTOR
#include <bslma_deallocatorproctor.h>
#endif
#ifndef INCLUDED_BSLMF_ISBITWISEMOVEABLE
#include <bslmf_isbitwisemoveable.h>
#endif
#ifndef INCLUDED_BSLMF_MOVABLEREF
#include <bslmf_movableref.h>
#endif
#ifndef INCLUDED_BSLS_ASSERT
#include <bsls_assert.h>
#endif
#ifndef INCLUDED_BSLS_COMPILERFEATURES
#include <bsls_compilerfeatures.h>
#endif
#ifndef INCLUDED_BSLS_NATIVESTD
#include <bsls_nativestd.h>
#endif
#ifndef INCLUDED_BSLS_UTIL
#include <bsls_util.h>
#endif
namespace BloombergLP {
namespace bslstl {
// ===========================
// class BidirectionalNodePool
// ===========================
template <class VALUE, class ALLOCATOR>
class BidirectionalNodePool {
// This class provides methods for creating and destroying nodes using the
// appropriate allocator-traits of the (template parameter) type
// 'ALLOCATOR'.
// PRIVATE TYPES
typedef SimplePool<bslalg::BidirectionalNode<VALUE>, ALLOCATOR> Pool;
// This 'typedef' is an alias for the memory pool allocator.
typedef typename Pool::AllocatorTraits AllocatorTraits;
// This 'typedef' is an alias for the allocator traits defined by
// 'SimplePool'.
typedef bslmf::MovableRefUtil MoveUtil;
// This typedef is a convenient alias for the utility associated with
// movable references.
// DATA
Pool d_pool; // pool for allocating memory
private:
// NOT IMPLEMENTED
BidirectionalNodePool& operator=(const BidirectionalNodePool&);
BidirectionalNodePool(const BidirectionalNodePool&);
public:
// PUBLIC TYPE
typedef typename Pool::AllocatorType AllocatorType;
// Alias for the allocator type defined by 'SimplePool'.
typedef typename AllocatorTraits::size_type size_type;
// Alias for the 'size_type' of the allocator defined by 'SimplePool'.
public:
// CREATORS
explicit BidirectionalNodePool(const ALLOCATOR& allocator);
// Create a 'BidirectionalNodePool' object that will use the specified
// 'allocator' to supply memory for allocated node objects. If the
// (template parameter) 'ALLOCATOR' is 'bsl::allocator', then
// 'allocator' shall be convertible to 'bslma::Allocator *'.
BidirectionalNodePool(bslmf::MovableRef<BidirectionalNodePool> original);
// Create a bidirectional node-pool, adopting all outstanding memory
// allocations associated with the specified 'original' node-pool, that
// will use the allocator associated with 'original' to supply memory
// for allocated node objects. 'original' is left in a valid but
// unspecified state.
// ~BidirectionalNodePool() = default;
// Destroy the memory pool maintained by this object, releasing all
// memory used by the nodes of the type 'BidirectionalNode<VALUE>' in
// the pool. Any memory allocated for the nodes' 'value' attribute of
// the (template parameter) type 'VALUE' will be leaked unless the
// nodes are explicitly destroyed via the 'destroyNode' method.
// MANIPULATORS
void adopt(bslmf::MovableRef<BidirectionalNodePool> pool);
// Adopt all outstanding memory allocations associated with the
// specified node 'pool'. The behavior is undefined unless this pool
// uses the same allocator as that associated with 'pool'. The
// behavior is also undefined unless this pool is in the
// default-constructed state.
AllocatorType& allocator();
// Return a reference providing modifiable access to the allocator
// supplying memory for the memory pool maintained by this object. The
// behavior is undefined if the allocator used by this object is
// changed with this method. Note that this method provides modifiable
// access to enable a client to call non-'const' methods on the
// allocator.
bslalg::BidirectionalLink *cloneNode(
const bslalg::BidirectionalLink& original);
// Allocate a node of the type 'BidirectionalNode<VALUE>', and
// copy-construct an object of the (template parameter) type 'VALUE'
// having the same value as the specified 'original' at the 'value'
// attribute of the node. Return the address of the node. Note that
// the 'next' and 'prev' attributes of the returned node will be
// uninitialized.
void deleteNode(bslalg::BidirectionalLink *linkNode);
// Destroy the 'VALUE' attribute of the specified 'linkNode' and return
// the memory footprint of 'linkNode' to this pool for potential reuse.
// The behavior is undefined unless 'node' refers to a
// 'bslalg::BidirectionalNode<VALUE>' that was allocated by this pool.
#if !BSLS_COMPILERFEATURES_SIMULATE_CPP11_FEATURES
template <class... Args>
bslalg::BidirectionalLink *emplaceIntoNewNode(Args&&... arguments);
// Allocate a node of the type 'BidirectionalNode<VALUE>', and
// construct in-place an object of the (template parameter) type
// 'VALUE' with the specified constructor 'arguments'. Return the
// address of the node. Note that the 'next' and 'prev' attributes of
// the returned node will be uninitialized.
#elif BSLS_COMPILERFEATURES_SIMULATE_VARIADIC_TEMPLATES
// {{{ BEGIN GENERATED CODE
// The following section is automatically generated. **DO NOT EDIT**
// Generator command line: sim_cpp11_features.pl bslstl_bidirectionalnodepool.h
bslalg::BidirectionalLink *emplaceIntoNewNode(
);
template <class Args_01>
bslalg::BidirectionalLink *emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) arguments_01);
template <class Args_01,
class Args_02>
bslalg::BidirectionalLink *emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) arguments_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) arguments_02);
template <class Args_01,
class Args_02,
class Args_03>
bslalg::BidirectionalLink *emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) arguments_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) arguments_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) arguments_03);
template <class Args_01,
class Args_02,
class Args_03,
class Args_04>
bslalg::BidirectionalLink *emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) arguments_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) arguments_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) arguments_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) arguments_04);
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05>
bslalg::BidirectionalLink *emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) arguments_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) arguments_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) arguments_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) arguments_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) arguments_05);
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06>
bslalg::BidirectionalLink *emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) arguments_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) arguments_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) arguments_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) arguments_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) arguments_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) arguments_06);
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07>
bslalg::BidirectionalLink *emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) arguments_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) arguments_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) arguments_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) arguments_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) arguments_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) arguments_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) arguments_07);
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07,
class Args_08>
bslalg::BidirectionalLink *emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) arguments_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) arguments_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) arguments_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) arguments_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) arguments_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) arguments_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) arguments_07,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_08) arguments_08);
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07,
class Args_08,
class Args_09>
bslalg::BidirectionalLink *emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) arguments_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) arguments_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) arguments_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) arguments_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) arguments_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) arguments_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) arguments_07,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_08) arguments_08,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_09) arguments_09);
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07,
class Args_08,
class Args_09,
class Args_10>
bslalg::BidirectionalLink *emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) arguments_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) arguments_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) arguments_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) arguments_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) arguments_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) arguments_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) arguments_07,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_08) arguments_08,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_09) arguments_09,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_10) arguments_10);
#else
// The generated code below is a workaround for the absence of perfect
// forwarding in some compilers.
template <class... Args>
bslalg::BidirectionalLink *emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args)... arguments);
// }}} END GENERATED CODE
#endif
bslalg::BidirectionalLink *moveIntoNewNode(
bslalg::BidirectionalLink *original);
// Allocate a node of the type 'BidirectionalNode<VALUE>', and
// move-construct an object of the (template parameter) type 'VALUE'
// with the (explicitly moved) value indicated by the 'value' attribute
// of the specified 'original' link. Return the address of the node.
// Note that the 'next' and 'prev' attributes of the returned node will
// be uninitialized. Also note that the 'value' attribute of
// 'original' is left in a valid but unspecified state.
void release();
// Relinquish all memory currently allocated with the memory pool
// maintained by this object.
void reserveNodes(size_type numNodes);
// Reserve memory from this pool to satisfy memory requests for at
// least the specified 'numNodes' before the pool replenishes. The
// behavior is undefined unless '0 < numNodes'.
void swapRetainAllocators(BidirectionalNodePool& other);
// Efficiently exchange the nodes of this object with those of the
// specified 'other' object. This method provides the no-throw
// exception-safety guarantee. The behavior is undefined unless
// 'allocator() == other.allocator()'.
void swapExchangeAllocators(BidirectionalNodePool& other);
// Efficiently exchange the nodes and the allocator of this object with
// those of the specified 'other' object. This method provides the
// no-throw exception-safety guarantee.
// ACCESSORS
const AllocatorType& allocator() const;
// Return a reference providing non-modifiable access to the allocator
// supplying memory for the memory pool maintained by this object.
};
// FREE FUNCTIONS
template <class VALUE, class ALLOCATOR>
void swap(BidirectionalNodePool<VALUE, ALLOCATOR>& a,
BidirectionalNodePool<VALUE, ALLOCATOR>& b);
// Efficiently exchange the nodes of the specified 'a' object with those of
// the specified 'b' object. This method provides the no-throw
// exception-safety guarantee. The behavior is undefined unless
// 'a.allocator() == b.allocator()'.
} // close package namespace
// ============================================================================
// TYPE TRAITS
// ============================================================================
// Type traits for HashTable:
//: o A HashTable is bitwise moveable if the allocator is bitwise moveable.
namespace bslmf {
template <class VALUE, class ALLOCATOR>
struct IsBitwiseMoveable<bslstl::BidirectionalNodePool<VALUE, ALLOCATOR> >
: bsl::integral_constant<bool, bslmf::IsBitwiseMoveable<ALLOCATOR>::value>
{};
} // close namespace bslmf
// ============================================================================
// TEMPLATE AND INLINE FUNCTION DEFINITIONS
// ============================================================================
namespace bslstl {
// CREATORS
template <class VALUE, class ALLOCATOR>
inline
BidirectionalNodePool<VALUE, ALLOCATOR>::BidirectionalNodePool(
const ALLOCATOR& allocator)
: d_pool(allocator)
{
}
template <class VALUE, class ALLOCATOR>
inline
BidirectionalNodePool<VALUE, ALLOCATOR>::BidirectionalNodePool(
bslmf::MovableRef<BidirectionalNodePool> original)
: d_pool(MoveUtil::move(MoveUtil::access(original).d_pool))
{
}
// MANIPULATORS
template <class VALUE, class ALLOCATOR>
inline
void BidirectionalNodePool<VALUE, ALLOCATOR>::adopt(
bslmf::MovableRef<BidirectionalNodePool> pool)
{
BidirectionalNodePool& lvalue = pool;
d_pool.adopt(MoveUtil::move(lvalue.d_pool));
}
template <class VALUE, class ALLOCATOR>
inline
typename
SimplePool<bslalg::BidirectionalNode<VALUE>, ALLOCATOR>::AllocatorType&
BidirectionalNodePool<VALUE, ALLOCATOR>::allocator()
{
return d_pool.allocator();
}
template <class VALUE, class ALLOCATOR>
inline
bslalg::BidirectionalLink *
BidirectionalNodePool<VALUE, ALLOCATOR>::cloneNode(
const bslalg::BidirectionalLink& original)
{
return emplaceIntoNewNode(
static_cast<const bslalg::BidirectionalNode<VALUE>&>(original).value());
}
#if !BSLS_COMPILERFEATURES_SIMULATE_CPP11_FEATURES
template <class VALUE, class ALLOCATOR>
template <class... Args>
inline
bslalg::BidirectionalLink *
BidirectionalNodePool<VALUE, ALLOCATOR>::emplaceIntoNewNode(
Args&&... arguments)
{
bslalg::BidirectionalNode<VALUE> *node = d_pool.allocate();
bslma::DeallocatorProctor<Pool> proctor(node, &d_pool);
AllocatorTraits::construct(
allocator(),
bsls::Util::addressOf(node->value()),
BSLS_COMPILERFEATURES_FORWARD(Args,arguments)...);
proctor.release();
return node;
}
#elif BSLS_COMPILERFEATURES_SIMULATE_VARIADIC_TEMPLATES
// {{{ BEGIN GENERATED CODE
// The following section is automatically generated. **DO NOT EDIT**
// Generator command line: sim_cpp11_features.pl bslstl_bidirectionalnodepool.h
template <class VALUE, class ALLOCATOR>
inline
bslalg::BidirectionalLink *
BidirectionalNodePool<VALUE, ALLOCATOR>::emplaceIntoNewNode(
)
{
bslalg::BidirectionalNode<VALUE> *node = d_pool.allocate();
bslma::DeallocatorProctor<Pool> proctor(node, &d_pool);
AllocatorTraits::construct(allocator(),
bsls::Util::addressOf(node->value()));
proctor.release();
return node;
}
template <class VALUE, class ALLOCATOR>
template <class Args_01>
inline
bslalg::BidirectionalLink *
BidirectionalNodePool<VALUE, ALLOCATOR>::emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01)
{
bslalg::BidirectionalNode<VALUE> *node = d_pool.allocate();
bslma::DeallocatorProctor<Pool> proctor(node, &d_pool);
AllocatorTraits::construct(allocator(),
bsls::Util::addressOf(node->value()),
BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01));
proctor.release();
return node;
}
template <class VALUE, class ALLOCATOR>
template <class Args_01,
class Args_02>
inline
bslalg::BidirectionalLink *
BidirectionalNodePool<VALUE, ALLOCATOR>::emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02)
{
bslalg::BidirectionalNode<VALUE> *node = d_pool.allocate();
bslma::DeallocatorProctor<Pool> proctor(node, &d_pool);
AllocatorTraits::construct(allocator(),
bsls::Util::addressOf(node->value()),
BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01),
BSLS_COMPILERFEATURES_FORWARD(Args_02,args_02));
proctor.release();
return node;
}
template <class VALUE, class ALLOCATOR>
template <class Args_01,
class Args_02,
class Args_03>
inline
bslalg::BidirectionalLink *
BidirectionalNodePool<VALUE, ALLOCATOR>::emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03)
{
bslalg::BidirectionalNode<VALUE> *node = d_pool.allocate();
bslma::DeallocatorProctor<Pool> proctor(node, &d_pool);
AllocatorTraits::construct(allocator(),
bsls::Util::addressOf(node->value()),
BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01),
BSLS_COMPILERFEATURES_FORWARD(Args_02,args_02),
BSLS_COMPILERFEATURES_FORWARD(Args_03,args_03));
proctor.release();
return node;
}
template <class VALUE, class ALLOCATOR>
template <class Args_01,
class Args_02,
class Args_03,
class Args_04>
inline
bslalg::BidirectionalLink *
BidirectionalNodePool<VALUE, ALLOCATOR>::emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04)
{
bslalg::BidirectionalNode<VALUE> *node = d_pool.allocate();
bslma::DeallocatorProctor<Pool> proctor(node, &d_pool);
AllocatorTraits::construct(allocator(),
bsls::Util::addressOf(node->value()),
BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01),
BSLS_COMPILERFEATURES_FORWARD(Args_02,args_02),
BSLS_COMPILERFEATURES_FORWARD(Args_03,args_03),
BSLS_COMPILERFEATURES_FORWARD(Args_04,args_04));
proctor.release();
return node;
}
template <class VALUE, class ALLOCATOR>
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05>
inline
bslalg::BidirectionalLink *
BidirectionalNodePool<VALUE, ALLOCATOR>::emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05)
{
bslalg::BidirectionalNode<VALUE> *node = d_pool.allocate();
bslma::DeallocatorProctor<Pool> proctor(node, &d_pool);
AllocatorTraits::construct(allocator(),
bsls::Util::addressOf(node->value()),
BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01),
BSLS_COMPILERFEATURES_FORWARD(Args_02,args_02),
BSLS_COMPILERFEATURES_FORWARD(Args_03,args_03),
BSLS_COMPILERFEATURES_FORWARD(Args_04,args_04),
BSLS_COMPILERFEATURES_FORWARD(Args_05,args_05));
proctor.release();
return node;
}
template <class VALUE, class ALLOCATOR>
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06>
inline
bslalg::BidirectionalLink *
BidirectionalNodePool<VALUE, ALLOCATOR>::emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06)
{
bslalg::BidirectionalNode<VALUE> *node = d_pool.allocate();
bslma::DeallocatorProctor<Pool> proctor(node, &d_pool);
AllocatorTraits::construct(allocator(),
bsls::Util::addressOf(node->value()),
BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01),
BSLS_COMPILERFEATURES_FORWARD(Args_02,args_02),
BSLS_COMPILERFEATURES_FORWARD(Args_03,args_03),
BSLS_COMPILERFEATURES_FORWARD(Args_04,args_04),
BSLS_COMPILERFEATURES_FORWARD(Args_05,args_05),
BSLS_COMPILERFEATURES_FORWARD(Args_06,args_06));
proctor.release();
return node;
}
template <class VALUE, class ALLOCATOR>
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07>
inline
bslalg::BidirectionalLink *
BidirectionalNodePool<VALUE, ALLOCATOR>::emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07)
{
bslalg::BidirectionalNode<VALUE> *node = d_pool.allocate();
bslma::DeallocatorProctor<Pool> proctor(node, &d_pool);
AllocatorTraits::construct(allocator(),
bsls::Util::addressOf(node->value()),
BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01),
BSLS_COMPILERFEATURES_FORWARD(Args_02,args_02),
BSLS_COMPILERFEATURES_FORWARD(Args_03,args_03),
BSLS_COMPILERFEATURES_FORWARD(Args_04,args_04),
BSLS_COMPILERFEATURES_FORWARD(Args_05,args_05),
BSLS_COMPILERFEATURES_FORWARD(Args_06,args_06),
BSLS_COMPILERFEATURES_FORWARD(Args_07,args_07));
proctor.release();
return node;
}
template <class VALUE, class ALLOCATOR>
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07,
class Args_08>
inline
bslalg::BidirectionalLink *
BidirectionalNodePool<VALUE, ALLOCATOR>::emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_08) args_08)
{
bslalg::BidirectionalNode<VALUE> *node = d_pool.allocate();
bslma::DeallocatorProctor<Pool> proctor(node, &d_pool);
AllocatorTraits::construct(allocator(),
bsls::Util::addressOf(node->value()),
BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01),
BSLS_COMPILERFEATURES_FORWARD(Args_02,args_02),
BSLS_COMPILERFEATURES_FORWARD(Args_03,args_03),
BSLS_COMPILERFEATURES_FORWARD(Args_04,args_04),
BSLS_COMPILERFEATURES_FORWARD(Args_05,args_05),
BSLS_COMPILERFEATURES_FORWARD(Args_06,args_06),
BSLS_COMPILERFEATURES_FORWARD(Args_07,args_07),
BSLS_COMPILERFEATURES_FORWARD(Args_08,args_08));
proctor.release();
return node;
}
template <class VALUE, class ALLOCATOR>
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07,
class Args_08,
class Args_09>
inline
bslalg::BidirectionalLink *
BidirectionalNodePool<VALUE, ALLOCATOR>::emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_08) args_08,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_09) args_09)
{
bslalg::BidirectionalNode<VALUE> *node = d_pool.allocate();
bslma::DeallocatorProctor<Pool> proctor(node, &d_pool);
AllocatorTraits::construct(allocator(),
bsls::Util::addressOf(node->value()),
BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01),
BSLS_COMPILERFEATURES_FORWARD(Args_02,args_02),
BSLS_COMPILERFEATURES_FORWARD(Args_03,args_03),
BSLS_COMPILERFEATURES_FORWARD(Args_04,args_04),
BSLS_COMPILERFEATURES_FORWARD(Args_05,args_05),
BSLS_COMPILERFEATURES_FORWARD(Args_06,args_06),
BSLS_COMPILERFEATURES_FORWARD(Args_07,args_07),
BSLS_COMPILERFEATURES_FORWARD(Args_08,args_08),
BSLS_COMPILERFEATURES_FORWARD(Args_09,args_09));
proctor.release();
return node;
}
template <class VALUE, class ALLOCATOR>
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07,
class Args_08,
class Args_09,
class Args_10>
inline
bslalg::BidirectionalLink *
BidirectionalNodePool<VALUE, ALLOCATOR>::emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_08) args_08,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_09) args_09,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_10) args_10)
{
bslalg::BidirectionalNode<VALUE> *node = d_pool.allocate();
bslma::DeallocatorProctor<Pool> proctor(node, &d_pool);
AllocatorTraits::construct(allocator(),
bsls::Util::addressOf(node->value()),
BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01),
BSLS_COMPILERFEATURES_FORWARD(Args_02,args_02),
BSLS_COMPILERFEATURES_FORWARD(Args_03,args_03),
BSLS_COMPILERFEATURES_FORWARD(Args_04,args_04),
BSLS_COMPILERFEATURES_FORWARD(Args_05,args_05),
BSLS_COMPILERFEATURES_FORWARD(Args_06,args_06),
BSLS_COMPILERFEATURES_FORWARD(Args_07,args_07),
BSLS_COMPILERFEATURES_FORWARD(Args_08,args_08),
BSLS_COMPILERFEATURES_FORWARD(Args_09,args_09),
BSLS_COMPILERFEATURES_FORWARD(Args_10,args_10));
proctor.release();
return node;
}
#else
// The generated code below is a workaround for the absence of perfect
// forwarding in some compilers.
template <class VALUE, class ALLOCATOR>
template <class... Args>
inline
bslalg::BidirectionalLink *
BidirectionalNodePool<VALUE, ALLOCATOR>::emplaceIntoNewNode(
BSLS_COMPILERFEATURES_FORWARD_REF(Args)... args)
{
bslalg::BidirectionalNode<VALUE> *node = d_pool.allocate();
bslma::DeallocatorProctor<Pool> proctor(node, &d_pool);
AllocatorTraits::construct(allocator(),
bsls::Util::addressOf(node->value()),
BSLS_COMPILERFEATURES_FORWARD(Args,args)...);
proctor.release();
return node;
}
// }}} END GENERATED CODE
#endif
template <class VALUE, class ALLOCATOR>
inline
bslalg::BidirectionalLink *
BidirectionalNodePool<VALUE, ALLOCATOR>::moveIntoNewNode(
bslalg::BidirectionalLink *original)
{
return emplaceIntoNewNode(MoveUtil::move(
static_cast<bslalg::BidirectionalNode<VALUE> *>(original)->value()));
}
template <class VALUE, class ALLOCATOR>
void BidirectionalNodePool<VALUE, ALLOCATOR>::deleteNode(
bslalg::BidirectionalLink *linkNode)
{
BSLS_ASSERT(linkNode);
bslalg::BidirectionalNode<VALUE> *node =
static_cast<bslalg::BidirectionalNode<VALUE> *>(linkNode);
AllocatorTraits::destroy(allocator(),
bsls::Util::addressOf(node->value()));
d_pool.deallocate(node);
}
template <class VALUE, class ALLOCATOR>
inline
void BidirectionalNodePool<VALUE, ALLOCATOR>::release()
{
d_pool.release();
}
template <class VALUE, class ALLOCATOR>
inline
void BidirectionalNodePool<VALUE, ALLOCATOR>::reserveNodes(size_type numNodes)
{
BSLS_ASSERT_SAFE(0 < numNodes);
d_pool.reserve(numNodes);
}
template <class VALUE, class ALLOCATOR>
inline
void BidirectionalNodePool<VALUE, ALLOCATOR>::swapRetainAllocators(
BidirectionalNodePool<VALUE, ALLOCATOR>& other)
{
BSLS_ASSERT_SAFE(allocator() == other.allocator());
d_pool.quickSwapRetainAllocators(other.d_pool);
}
template <class VALUE, class ALLOCATOR>
inline
void BidirectionalNodePool<VALUE, ALLOCATOR>::swapExchangeAllocators(
BidirectionalNodePool<VALUE, ALLOCATOR>& other)
{
d_pool.quickSwapExchangeAllocators(other.d_pool);
}
// ACCESSORS
template <class VALUE, class ALLOCATOR>
inline
const typename
SimplePool<bslalg::BidirectionalNode<VALUE>, ALLOCATOR>::
AllocatorType&
BidirectionalNodePool<VALUE, ALLOCATOR>::allocator() const
{
return d_pool.allocator();
}
} // close package namespace
template <class VALUE, class ALLOCATOR>
inline
void bslstl::swap(bslstl::BidirectionalNodePool<VALUE, ALLOCATOR>& a,
bslstl::BidirectionalNodePool<VALUE, ALLOCATOR>& b)
{
a.swapRetainAllocators(b);
}
} // close enterprise namespace
#endif
// ----------------------------------------------------------------------------
// Copyright 2013 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
| {
"content_hash": "81e90005a6ceab6fd0fad373f467aae1",
"timestamp": "",
"source": "github",
"line_count": 1047,
"max_line_length": 79,
"avg_line_length": 41.21298949379179,
"alnum_prop": 0.6090150637311703,
"repo_name": "dharesign/bde",
"id": "bc43ff0e40d136b9c3b11f32dbc47a0ff41660d9",
"size": "43382",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "groups/bsl/bslstl/bslstl_bidirectionalnodepool.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "153030"
},
{
"name": "C++",
"bytes": "95812552"
},
{
"name": "Perl",
"bytes": "2008"
},
{
"name": "Python",
"bytes": "920"
}
],
"symlink_target": ""
} |
import raam
from raam import robust
from raam import crobust
from raam import features
from raam import examples
import numpy as np
discount = 0.99
samples = examples.chain.simple_samples(10,discount)
r = crobust.SRoMDP(1, discount)
statenum = lambda x: np.where(x)[0][0]
zero = lambda x: 0
dict_si = {}
def sampleindex(x):
x = statenum(x)
index = dict_si.get(x,0)
dict_si[x] = index + 1
return index
r.from_samples(samples, decagg_big=statenum, decagg_small=zero,
expagg_big=statenum, expagg_small=sampleindex,
actagg=features.IdCache())
r.rmdp.set_uniform_distributions(0.4)
v,_,_,_ = r.rmdp.mpi_jac_l1(1000,stype=robust.SolutionType.Robust.value)
print(r.decvalue(10, v)) | {
"content_hash": "c11b34a24d92488312807f6258074e25",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 72,
"avg_line_length": 23.46875,
"alnum_prop": 0.6724367509986684,
"repo_name": "marekpetrik/RAAM",
"id": "5d2a1ea59343efb42c5bbd53a4233cdc0fa2234b",
"size": "751",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/sampling_robust/test_simple_robust.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "144083"
},
{
"name": "Shell",
"bytes": "738"
}
],
"symlink_target": ""
} |
// Copyright © 2011 - Present RealDimensions Software, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace chocolatey.infrastructure.app.domain.installers
{
using System.Collections.Generic;
/// <summary>
/// SetupFactory Options
/// </summary>
/// <remarks>
/// http://www.indigorose.com/webhelp/suf9/Program_Reference/Command_Line_Options.htm
///
/// While we can override the extraction path, it should already be overridden
/// because we are overriding the TEMP variable
/// </remarks>
public class SetupFactoryInstaller : InstallerBase
{
public SetupFactoryInstaller()
{
InstallExecutable = "\"{0}\"".format_with(InstallTokens.INSTALLER_LOCATION);
SilentInstall = "/S";
NoReboot = "";
LogFile = "";
// http://www.indigorose.com/forums/threads/23686-How-to-Set-the-Default-Application-Directory
// http://www.indigorose.com/webhelp/suf70/Program_Reference/Screen_Types/Select_Install_Folder/Properties.htm
// http://www.indigorose.com/webhelp/suf70/Program_Reference/Variables/Session_Variables.htm#AppFolder
// todo: basically we need an environment variable for AppFolder
CustomInstallLocation = "";
Language = "";
//OtherInstallOptions = "\"/T:{0}\"".format_with(InstallTokens.TEMP_LOCATION);
OtherInstallOptions = "";
UninstallExecutable = "\"{0}\"".format_with(InstallTokens.UNINSTALLER_LOCATION);
SilentUninstall = "/S";
OtherUninstallOptions = "";
ValidInstallExitCodes = new List<int>
{
0
};
ValidUninstallExitCodes = new List<int>
{
0
};
}
public override InstallerType InstallerType
{
get { return InstallerType.SetupFactory; }
}
}
}
| {
"content_hash": "574a9cbbf64046a0b7ae8dd878842f56",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 122,
"avg_line_length": 40.3968253968254,
"alnum_prop": 0.6137524557956778,
"repo_name": "sideeffffect/choco",
"id": "4f1b4eec2a5e8b267d7b1a368728af792595b516",
"size": "2548",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/chocolatey/infrastructure.app/domain/installers/SetupFactoryInstaller.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "7016"
},
{
"name": "C#",
"bytes": "1840779"
},
{
"name": "PowerShell",
"bytes": "284175"
},
{
"name": "Shell",
"bytes": "2246"
},
{
"name": "XSLT",
"bytes": "13875"
}
],
"symlink_target": ""
} |
@interface KSAutoFootRefreshView ()
@property (nonatomic, strong) UIActivityIndicatorView * indicatorView;
@property (nonatomic, strong) UILabel * titleLabel;
@end
@implementation KSAutoFootRefreshView
@synthesize isLastPage = _isLastPage;
- (instancetype)init
{
self = [super init];
if (self) {
self.indicatorView = [[UIActivityIndicatorView alloc] init];
self.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
self.indicatorView.center = CGPointMake(KS_SCREEN_WIDTH / 2, KSRefreshView_Height / 2);
self.indicatorView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, KS_SCREEN_WIDTH, KSRefreshView_Height)];
self.titleLabel.font = [UIFont systemFontOfSize:16];
self.titleLabel.textColor = [UIColor darkGrayColor];
self.titleLabel.backgroundColor = [UIColor clearColor];
self.titleLabel.textAlignment = NSTextAlignmentCenter;
self.titleLabel.text = KSFootRefreshView_T_1;
self.titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[self addSubview:self.titleLabel];
[self addSubview:self.indicatorView];
self.hidden = YES;
}
return self;
}
- (void)setIsLastPage:(BOOL)isLastPage
{
if (isLastPage) {
[self setValue:@(KSRefreshViewStateDefault) forKeyPath:@"_state"];
[self.titleLabel setText:KSFootRefreshView_T_4];
[self.indicatorView stopAnimating];
UIEdgeInsets ei = self.targetView.contentInset;
ei.bottom = self.targetViewOriginalEdgeInsets.bottom + KSRefreshView_Height;
self.targetView.contentInset = ei;
} else {
[self.titleLabel setText:KSFootRefreshView_T_1];
}
_isLastPage = isLastPage;
}
- (void)setState:(KSRefreshViewState)state
{
if (_isLastPage) {
return;
}
[super setState:state];
switch (state) {
case KSRefreshViewStateDefault:
{
[self.titleLabel setText:KSFootRefreshView_T_1];
[self.indicatorView stopAnimating];
break;
}
case KSRefreshViewStateVisible:
case KSRefreshViewStateTriggered:
{
[self setState:KSRefreshViewStateLoading];
break;
}
case KSRefreshViewStateLoading:
{
[self.titleLabel setText:KSFootRefreshView_T_3];
[self.indicatorView startAnimating];
UIEdgeInsets ei = self.targetView.contentInset;
ei.bottom = self.targetViewOriginalEdgeInsets.bottom + KSRefreshView_Height;
[self setScrollViewContentInset:ei];
if ([self.delegate respondsToSelector:@selector(refreshViewDidLoading:)]) {
[self.delegate refreshViewDidLoading:self];
}
break;
}
}
}
- (void)setScrollViewContentInset:(UIEdgeInsets)contentInset
{
[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionAllowUserInteraction|UIViewAnimationOptionBeginFromCurrentState animations:^{
self.targetView.contentInset = contentInset;
} completion:^(BOOL finished) {
}];
}
@end
| {
"content_hash": "57b7f4e8d79d2ba7a28e8415ef9febc6",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 150,
"avg_line_length": 31.636363636363637,
"alnum_prop": 0.6350574712643678,
"repo_name": "bing6/KSRefresh",
"id": "4e3344eb4c4c7ea9c8b3d0eb4d8640a0f951e0c0",
"size": "3837",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/KSAutoFootRefreshView.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "33501"
},
{
"name": "Ruby",
"bytes": "6161"
}
],
"symlink_target": ""
} |
<?php
// set some variables to use below
if(get_input("type") == "sent"){
// send back to the users sentbox
$url = $vars['url'] . "mod/messages/sent.php";
//this is used on the delete link so we know which type of message it is
$type = "sent";
} else {
//send back to the users inbox
$url = $vars['url'] . "pg/messages/" . $vars['user']->username;
//this is used on the delete link so we know which type of message it is
$type = "inbox";
}
// fix for RE: RE: RE: that builds on replies
$reply_title = $vars['entity']->title;
if (strncmp($reply_title, "RE:", 3) != 0) {
$reply_title = "RE: " . $reply_title;
}
if (isloggedin())
if (isset($vars['entity'])) {
if ($vars['entity']->toID == $vars['user']->guid
|| $vars['entity']->owner_guid == $vars['user']->guid) {
?>
<!-- get the correct return url -->
<div id="messages_return"><!-- start of messages_return div -->
<p><a href="<?php echo $url; ?>">« <?php echo elgg_echo('messages:back'); ?></a></p>
</div><!-- end of messages_return div -->
<div class="messages_single"><!-- start of the message div -->
<div class="messages_single_icon"><!-- start of the message_user_icon div -->
<!-- get the user icon, name and date -->
<?php
// we need a different user icon and name depending on whether the user is reading the message
// from their inbox or sentbox. If it is the inbox, then the icon and name will be the person who sent
// the message. If it is the sentbox, the icon and name will be the user the message was sent to
if($type == "sent"){
//get an instance of the user who the message has been sent to so we can access the name and icon
$user_object = get_entity($vars['entity']->toId);
//get the icon
echo " " . elgg_view("profile/icon",array('entity' => $user_object, 'size' => 'tiny'));
//get the name
echo "<br class=\"clearfloat\" /><p>".elgg_echo('messages:to').": <b>" . $user_object->name . "</b><br />";
}else{
//get the icon
echo " " . elgg_view("profile/icon",array('entity' => get_entity($vars['entity']->fromId), 'size' => 'tiny'));
//get the name
echo "<br class=\"clearfloat\" /><p>".elgg_echo('messages:from').": <b>" . get_entity($vars['entity']->fromId)->name . "</b><br />";
}
?>
<!-- get the time the message was sent -->
<small><?php echo friendly_time($vars['entity']->time_created); ?></small>
</p>
</div><!-- end of the message_user_icon div -->
<div class="message_body"><!-- start of div message_body -->
<?php
//if the message is a reply, display the message the reply was for
//I need to figure out how to get the description out using -> (anyone?)
if($main_message = $vars['entity']->getEntitiesFromRelationship("reply")){
if($type == "sent"){
echo "<div class='previous_message'><h3>".elgg_echo('messages:original').":</h3><p>";
}else{
echo "<div class='previous_message'><h3>".elgg_echo('messages:yours').":</h3><p>";
}
echo $main_message[0][description] . "</p></div>";
}
?>
<!-- display the title -->
<div class="actiontitle">
<h3><?php echo $vars['entity']->title; ?></h3>
</div>
<!-- display the message -->
<div class="messagebody">
<p><?php echo elgg_view('output/longtext',array('value' => $vars['entity']->description)); ?></p>
</div>
<!-- display the edit options, reply and delete -->
<div class="message_options"><!-- start of the message_options div -->
<script type="text/javascript">
$(document).ready(function () {
// click function to toggle reply panel
$('a.message_reply').click(function () {
$('div#message_reply_form').slideToggle("medium");
return false;
});
});
</script>
<p><?php if($type != "sent")echo "<a href=\"javascript:void(0);\" class='message_reply'>".elgg_echo('messages:answer')."</a> "; ?> <?php echo elgg_view("output/confirmlink", array(
'href' => $vars['url'] . "action/messages/delete?message_id=" . $vars['entity']->getGUID() . "&type={$type}&submit=" . elgg_echo('delete'),
'text' => elgg_echo('delete'),
'confirm' => elgg_echo('deleteconfirm'),
)); ?>
</p>
</div><!-- end of the message_options div -->
</div><!-- end of div message_body -->
<!-- display the reply form -->
<div id="message_reply_form">
<form action="<?php echo $vars['url']; ?>action/messages/send" method="post" name="messageForm">
<!-- populate the title space with the orginal message title, inserting re: before it -->
<p><label><?php echo elgg_echo("messages:title"); ?>: <br /><input type='text' name='title' class="input-text" value='<?php echo $reply_title; ?>' /></label></p>
<p class="longtext_editarea"><label><?php echo elgg_echo("messages:message"); ?>:</label></p>
<div id="message_reply_editor">
<?php
echo elgg_view("input/longtext", array(
"internalname" => "message",
"value" => '',
));
?></div>
<p>
<?php
//pass across the guid of the message being replied to
echo "<input type='hidden' name='reply' value='" . $vars['entity']->getGUID() . "' />";
//pass along the owner of the message being replied to
echo "<input type='hidden' name='send_to' value='" . $vars['entity']->fromId . "' />";
?>
<input type="submit" class="submit_button" value="<?php echo elgg_echo("messages:fly"); ?>" />
</p>
</form>
</div><!-- end of div reply_form -->
</div><!-- end of the message div -->
<?php
}
}
?> | {
"content_hash": "a15f0864f74618d1002dd1ca1c29e2b3",
"timestamp": "",
"source": "github",
"line_count": 155,
"max_line_length": 193,
"avg_line_length": 40.76129032258064,
"alnum_prop": 0.5172522950300729,
"repo_name": "namaggarwal/elgg",
"id": "e61326b75d6905450472a2c46f94afb78aa90fdf",
"size": "6834",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mod/messages/views/default/messages/messages.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "28605"
},
{
"name": "JavaScript",
"bytes": "281680"
},
{
"name": "PHP",
"bytes": "4987425"
},
{
"name": "Shell",
"bytes": "167"
}
],
"symlink_target": ""
} |
package org.bkpathak.mapreduce.averagewordcount;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Created by bijay on 11/26/14.
*/
public class TokenizerMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
private IntWritable one = new IntWritable(1);
private Text word = new Text();
@Override
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
}
}
}
| {
"content_hash": "75dbbeeb6097a946aff80d882ef1dbd5",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 107,
"avg_line_length": 28.448275862068964,
"alnum_prop": 0.7490909090909091,
"repo_name": "bkpathak/MapReduce-Collections",
"id": "d3f6ae78423e1ef6b2cfc5658850e321ed39e6a5",
"size": "825",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/bkpathak/mapreduce/averagewordcount/TokenizerMapper.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "71963"
}
],
"symlink_target": ""
} |
<?php namespace CodeIgniter\HTTP;
use Config\App;
/**
* @backupGlobals enabled
*/
class IncomingRequestTest extends \CIUnitTestCase
{
/**
* @var \CodeIgniter\HTTP\IncomingRequest
*/
protected $request;
public function setUp()
{
$this->request = new IncomingRequest(new App(), new URI());
$_POST = $_GET = $_SERVER = $_REQUEST = $_ENV = $_COOKIE = $_SESSION = [];
}
//--------------------------------------------------------------------
public function testCanGrabRequestVars()
{
$_REQUEST['TEST'] = 5;
$this->assertEquals(5, $this->request->getVar('TEST'));
$this->assertEquals(null, $this->request->getVar('TESTY'));
}
//--------------------------------------------------------------------
public function testCanGrabGetVars()
{
$_GET['TEST'] = 5;
$this->assertEquals(5, $this->request->getGet('TEST'));
$this->assertEquals(null, $this->request->getGEt('TESTY'));
}
//--------------------------------------------------------------------
public function testCanGrabPostVars()
{
$_POST['TEST'] = 5;
$this->assertEquals(5, $this->request->getPost('TEST'));
$this->assertEquals(null, $this->request->getPost('TESTY'));
}
//--------------------------------------------------------------------
public function testCanGrabPostBeforeGet()
{
$_POST['TEST'] = 5;
$_GET['TEST'] = 3;
$this->assertEquals(5, $this->request->getPostGet('TEST'));
$this->assertEquals(3, $this->request->getGetPost('TEST'));
}
//--------------------------------------------------------------------
/**
* @group single
*/
public function testCanGetOldInput()
{
$_SESSION['_ci_old_input'] = [
'get' => ['one' => 'two'],
'post' => ['name' => 'foo']
];
$this->assertEquals('foo', $this->request->getOldInput('name'));
$this->assertEquals('two', $this->request->getOldInput('one'));
}
public function testCanGrabServerVars()
{
$_SERVER['TEST'] = 5;
$this->assertEquals(5, $this->request->getServer('TEST'));
$this->assertEquals(null, $this->request->getServer('TESTY'));
}
//--------------------------------------------------------------------
public function testCanGrabEnvVars()
{
$_ENV['TEST'] = 5;
$this->assertEquals(5, $this->request->getEnv('TEST'));
$this->assertEquals(null, $this->request->getEnv('TESTY'));
}
//--------------------------------------------------------------------
public function testCanGrabCookieVars()
{
$_COOKIE['TEST'] = 5;
$this->assertEquals(5, $this->request->getCookie('TEST'));
$this->assertEquals(null, $this->request->getCookie('TESTY'));
}
//--------------------------------------------------------------------
public function testFetchGlobalReturnsSingleValue()
{
$_POST = [
'foo' => 'bar',
'bar' => 'baz',
'xxx' => 'yyy',
'yyy' => 'zzz'
];
$this->assertEquals('baz', $this->request->getPost('bar'));
}
//--------------------------------------------------------------------
public function testFetchGlobalWithArrayTop()
{
$_POST = [
'clients' => [
'address' => [
'zipcode' => 90210
]
]
];
$this->assertEquals(['address' => ['zipcode' => 90210]], $this->request->getPost('clients'));
}
public function testFetchGlobalWithArrayChildNumeric()
{
$_POST = [
'clients' => [
[
'address' => [
'zipcode' => 90210
],
],
[
'address' => [
'zipcode' => 60610
],
],
]
];
$this->assertEquals(['zipcode' => 60610], $this->request->getPost('clients[1][address]'));
}
public function testFetchGlobalWithArrayChildElement()
{
$_POST = [
'clients' => [
'address' => [
'zipcode' => 90210
],
]
];
$this->assertEquals(['zipcode' => 90210], $this->request->getPost('clients[address]'));
}
public function testFetchGlobalWithArrayLastElement()
{
$_POST = [
'clients' => [
'address' => [
'zipcode' => 90210
]
]
];
$this->assertEquals(90210, $this->request->getPost('clients[address][zipcode]'));
}
/**
* @see https://github.com/bcit-ci/CodeIgniter4/issues/353
*/
public function testGetPostReturnsArrayValues()
{
$_POST = [
'ANNOUNCEMENTS' => [
1 => [
'DETAIL' => 'asdf'
],
2 => [
'DETAIL' => 'sdfg'
]
],
'submit' => 'SAVE'
];
$result = $this->request->getPost();
$this->assertEquals($_POST, $result);
$this->assertTrue(is_array($result['ANNOUNCEMENTS']));
$this->assertEquals(2, count($result['ANNOUNCEMENTS']));
}
//--------------------------------------------------------------------
public function testFetchGlobalFiltersValue()
{
$_POST = [
'foo' => 'bar<script>',
'bar' => 'baz',
'xxx' => 'yyy',
'yyy' => 'zzz'
];
$this->assertEquals('bar%3Cscript%3E', $this->request->getPost('foo', FILTER_SANITIZE_ENCODED));
}
//--------------------------------------------------------------------
public function testFetchGlobalFilterWithFlagValue()
{
$_POST = [
'foo' => '`bar<script>',
'bar' => 'baz',
'xxx' => 'yyy',
'yyy' => 'zzz'
];
$this->assertEquals('bar%3Cscript%3E', $this->request->getPost('foo', FILTER_SANITIZE_ENCODED, FILTER_FLAG_STRIP_BACKTICK));
}
//--------------------------------------------------------------------
public function testFetchGlobalReturnsAllWhenEmpty()
{
$post = [
'foo' => 'bar',
'bar' => 'baz',
'xxx' => 'yyy',
'yyy' => 'zzz'
];
$_POST = $post;
$this->assertEquals($post, $this->request->getPost());
}
//--------------------------------------------------------------------
public function testFetchGlobalFiltersAllValues()
{
$_POST = [
'foo' => 'bar<script>',
'bar' => 'baz<script>',
'xxx' => 'yyy<script>',
'yyy' => 'zzz<script>'
];
$expected = [
'foo' => 'bar%3Cscript%3E',
'bar' => 'baz%3Cscript%3E',
'xxx' => 'yyy%3Cscript%3E',
'yyy' => 'zzz%3Cscript%3E'
];
$this->assertEquals($expected, $this->request->getPost(null, FILTER_SANITIZE_ENCODED));
}
//--------------------------------------------------------------------
public function testFetchGlobalFilterWithFlagAllValues()
{
$_POST = [
'foo' => '`bar<script>',
'bar' => '`baz<script>',
'xxx' => '`yyy<script>',
'yyy' => '`zzz<script>'
];
$expected = [
'foo' => 'bar%3Cscript%3E',
'bar' => 'baz%3Cscript%3E',
'xxx' => 'yyy%3Cscript%3E',
'yyy' => 'zzz%3Cscript%3E'
];
$this->assertEquals($expected, $this->request->getPost(null, FILTER_SANITIZE_ENCODED, FILTER_FLAG_STRIP_BACKTICK));
}
//--------------------------------------------------------------------
public function testFetchGlobalReturnsSelectedKeys()
{
$_POST = [
'foo' => 'bar',
'bar' => 'baz',
'xxx' => 'yyy',
'yyy' => 'zzz'
];
$expected = [
'foo' => 'bar',
'bar' => 'baz',
];
$this->assertEquals($expected, $this->request->getPost(['foo', 'bar']));
}
//--------------------------------------------------------------------
public function testFetchGlobalFiltersSelectedValues()
{
$_POST = [
'foo' => 'bar<script>',
'bar' => 'baz<script>',
'xxx' => 'yyy<script>',
'yyy' => 'zzz<script>'
];
$expected = [
'foo' => 'bar%3Cscript%3E',
'bar' => 'baz%3Cscript%3E',
];
$this->assertEquals($expected, $this->request->getPost(['foo', 'bar'], FILTER_SANITIZE_ENCODED));
}
//--------------------------------------------------------------------
public function testFetchGlobalFilterWithFlagSelectedValues()
{
$_POST = [
'foo' => '`bar<script>',
'bar' => '`baz<script>',
'xxx' => '`yyy<script>',
'yyy' => '`zzz<script>'
];
$expected = [
'foo' => 'bar%3Cscript%3E',
'bar' => 'baz%3Cscript%3E',
];
$this->assertEquals($expected, $this->request->getPost(['foo', 'bar'], FILTER_SANITIZE_ENCODED, FILTER_FLAG_STRIP_BACKTICK));
}
//--------------------------------------------------------------------
public function testStoresDefaultLocale()
{
$config = new App();
$this->assertEquals($config->defaultLocale, $this->request->getDefaultLocale());
$this->assertEquals($config->defaultLocale, $this->request->getLocale());
}
//--------------------------------------------------------------------
public function testSetLocaleSaves()
{
$this->request->setLocale('en');
$this->assertEquals('en', $this->request->getLocale());
}
//--------------------------------------------------------------------
public function testNegotiatesLocale()
{
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'es; q=1.0, en; q=0.5';
$config = new App();
$config->negotiateLocale = true;
$config->supportedLocales = ['en', 'es'];
$request = new IncomingRequest($config, new URI());
$this->assertEquals($config->defaultLocale, $request->getDefaultLocale());
$this->assertEquals('es', $request->getLocale());
}
//--------------------------------------------------------------------
public function testCanGrabGetRawJSON()
{
$json = '{"code":1, "message":"ok"}';
$expected = [
'code' => 1,
'message' => 'ok'
];
$request = new IncomingRequest(new App(), new URI(), $json);
$this->assertEquals($expected, $request->getJSON(true));
}
//--------------------------------------------------------------------
public function testCanGrabGetRawInput()
{
$rawstring = 'username=admin001&role=administrator&usepass=0';
$expected = [
'username' => 'admin001',
'role' => 'administrator',
'usepass' => 0
];
$request = new IncomingRequest(new App(), new URI(), $rawstring);
$this->assertEquals($expected, $request->getRawInput());
}
//--------------------------------------------------------------------
}
| {
"content_hash": "de72db7d2c988e3d48b6e56d2750fc57",
"timestamp": "",
"source": "github",
"line_count": 412,
"max_line_length": 127,
"avg_line_length": 23.82766990291262,
"alnum_prop": 0.479372517062239,
"repo_name": "hex-ci/CodeIgniter4",
"id": "ff8622d5239deb5e6f0e3a7daf4e47caa96435bf",
"size": "9817",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "tests/system/HTTP/IncomingRequestTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "4467"
},
{
"name": "CSS",
"bytes": "107744"
},
{
"name": "HTML",
"bytes": "22593"
},
{
"name": "JavaScript",
"bytes": "14817"
},
{
"name": "Makefile",
"bytes": "4808"
},
{
"name": "PHP",
"bytes": "2216279"
},
{
"name": "Python",
"bytes": "11579"
}
],
"symlink_target": ""
} |
.items li:after,
#assets .items .inner:after,
.add:after,
#uploader li:after,
#uploader .totals:after,
#workspace .tools:after,
#workspace .tools .add:after,
.theme:after,
.batch_edit .asset:after,
#asset_usages:after,
#asset_usages div:after,
#tags_view .taggable:after,
.page_content:after,
.page_content .content:after,
.contents li.content:after,
#content.datums .datum:after,
#crop:after,
.asset_association_form:after,
.datums .image:after {
content:".";
display:block;
height:0;
line-height:0;
clear:both;
visibility:hidden; } | {
"content_hash": "d7e4e9030e1d5e24d1f194defc457085",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 30,
"avg_line_length": 21.8,
"alnum_prop": 0.728440366972477,
"repo_name": "Oktavilla/Porthos-Engine",
"id": "10bc670970bf0b2f9d74621fae0c971aeed420e5",
"size": "613",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/assets/stylesheets/clearing.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "37499"
},
{
"name": "JavaScript",
"bytes": "93585"
},
{
"name": "Ruby",
"bytes": "307408"
}
],
"symlink_target": ""
} |
when: renderAfter
---
echo 'hello from bash in shell collection' >> $DOCUMENT_OUTPATH.html | {
"content_hash": "6d68ef28b9a258b6682b72c76a91cc7f",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 68,
"avg_line_length": 30,
"alnum_prop": 0.7555555555555555,
"repo_name": "pflannery/docpad-plugin-cmds",
"id": "912305b825eb9491e739e9ef679b7a90860584ad",
"size": "94",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/src/shell/renderAfter.bash",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "15570"
},
{
"name": "Shell",
"bytes": "1356"
}
],
"symlink_target": ""
} |
<!--
Copyright 2013 JST 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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project name="jst-common-build" xmlns:ivy="antlib:org.apache.ivy.ant">
<dirname property="jst-common-build.dir" file="${ant.file.jst-common-build}" />
<property name="jst-root.dir" location="${jst-common-build.dir}/.." />
<property name="build-deps.dir" location="${jst-root.dir}/build-deps" />
<property name="p2repo.dir" location="${jst-root.dir}/p2repo" />
<property name="ivy.version" value="2.4.0-alpha" />
<property file="${basedir}/build.properties" />
<loadresource property="jst.version">
<file file="${jst-root.dir}/org.hibnet.jst/META-INF/MANIFEST.MF" />
<filterchain>
<linecontainsregexp>
<regexp pattern="Bundle-Version:"/>
</linecontainsregexp>
<striplinebreaks />
<tokenfilter>
<replaceregex pattern="Bundle-Version: (.*)\.qualifier" replace="\1" flags="gi" />
</tokenfilter>
</filterchain>
</loadresource>
<tstamp />
<property name="jst.version.qualifier" value="dev" />
<property name="jst.version.full" value="${jst.version}.${DSTAMP}${TSTAMP}-${jst.version.qualifier}" />
<target name="-check-build-deps">
<condition property="build-deps.exist">
<and>
<available file="${build-deps.dir}/antlr-4.0-complete.jar" />
<available file="${build-deps.dir}/antlr3-task/ant-antlr3.jar" />
<available file="${build-deps.dir}/ivy-${ivy.version}.jar" />
<available file="${build-deps.dir}/antlr-generator-3.2.0.jar" />
<available file="${build-deps.dir}/ant-contrib-20020829.jar" />
</and>
</condition>
<mkdir dir="${user.home}/.ivy2/lib/" />
</target>
<target name="-download-build-deps" depends="-check-build-deps" unless="build-deps.exist">
<mkdir dir="${build-deps.dir}" />
<get src="https://builds.apache.org/pview/job/Ivy/lastSuccessfulBuild/artifact/trunk/build/artifact/jars/ivy.jar" dest="${build-deps.dir}/ivy-${ivy.version}.jar" usetimestamp="true" />
<get src="http://antlr.org/download/antlr-4.0-complete.jar" dest="${build-deps.dir}/antlr-4.0-complete.jar" usetimestamp="true" />
<get src="http://download.itemis.com/antlr-generator-3.2.0.jar" dest="${build-deps.dir}/antlr-generator-3.2.0.jar" usetimestamp="true" />
<copy file="${build-deps.dir}/antlr-generator-3.2.0.jar" tofile="${jst-root.dir}/org.hibnet.jst/.antlr-generator-3.2.0.jar" />
<get src="http://www.antlr.org/share/1169924912745/antlr3-task.zip" dest="${build-deps.dir}/antlr3-task.zip" usetimestamp="true" />
<unzip src="${build-deps.dir}/antlr3-task.zip" dest="${build-deps.dir}" />
<get src="http://repo1.maven.org/maven2/ant-contrib/ant-contrib/20020829/ant-contrib-20020829.jar" dest="${build-deps.dir}/ant-contrib-20020829.jar" usetimestamp="true" />
</target>
<target name="init" depends="-download-build-deps">
<taskdef name="antlr3" classname="org.apache.tools.ant.antlr.ANTLR3">
<classpath>
<pathelement path="${build-deps.dir}/antlr-4.0-complete.jar" />
<pathelement path="${build-deps.dir}/antlr3-task/ant-antlr3.jar" />
</classpath>
</taskdef>
<taskdef resource="org/apache/ivy/ant/antlib.xml" uri="antlib:org.apache.ivy.ant" classpath="${build-deps.dir}/ivy-${ivy.version}.jar" />
<taskdef resource="net/sf/antcontrib/antcontrib.properties" uri="antlib:net.sf.antcontrib" classpath="${build-deps.dir}/ant-contrib-20020829.jar" />
</target>
<target name="ivy:configure" depends="init">
<ivy:configure file="${jst-common-build.dir}/ivysettings.xml" />
</target>
</project> | {
"content_hash": "c8c2cc66e13ff09ec30462362931ca15",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 192,
"avg_line_length": 48.18681318681319,
"alnum_prop": 0.6360319270239453,
"repo_name": "nlalevee/jst",
"id": "d1b60607c914476b09d75bc9ef4f359eb0e42ef2",
"size": "4385",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build/common-build.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "182601"
}
],
"symlink_target": ""
} |
package org.deeplearning4j.datasets.mnist;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public abstract class MnistDbFile extends RandomAccessFile {
private int count;
/**
* Creates new instance and reads the header information.
*
* @param name
* the system-dependent filename
* @param mode
* the access mode
* @throws IOException
* @throws FileNotFoundException
* @see RandomAccessFile
*/
public MnistDbFile(String name, String mode) throws IOException {
super(name, mode);
if (getMagicNumber() != readInt()) {
throw new RuntimeException(
"This MNIST DB file " + name + " should start with the number " + getMagicNumber() + ".");
}
count = readInt();
}
/**
* MNIST DB files start with unique integer number.
*
* @return integer number that should be found in the beginning of the file.
*/
protected abstract int getMagicNumber();
/**
* The current entry index.
*
* @return long
* @throws IOException
*/
public long getCurrentIndex() throws IOException {
return (getFilePointer() - getHeaderSize()) / getEntryLength() + 1;
}
/**
* Set the required current entry index.
*
* @param curr
* the entry index
*/
public void setCurrentIndex(long curr) {
try {
if (curr < 0 || curr > count) {
throw new RuntimeException(curr + " is not in the range 0 to " + count);
}
seek(getHeaderSize() + curr * getEntryLength());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public int getHeaderSize() {
return 8; // two integers
}
/**
* Number of bytes for each entry.
* Defaults to 1.
*
* @return int
*/
public int getEntryLength() {
return 1;
}
/**
* Move to the next entry.
*
* @throws IOException
*/
public void next() throws IOException {
if (getCurrentIndex() < count) {
skipBytes(getEntryLength());
}
}
/**
* Move to the previous entry.
*
* @throws IOException
*/
public void prev() throws IOException {
if (getCurrentIndex() > 0) {
seek(getFilePointer() - getEntryLength());
}
}
public int getCount() {
return count;
}
}
| {
"content_hash": "3123d4a599ba8380b494e55c18fa2ea3",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 118,
"avg_line_length": 23.990654205607477,
"alnum_prop": 0.551227113361901,
"repo_name": "deeplearning4j/deeplearning4j",
"id": "5fd53de813f3c2e33fe1540073013dde53f9124f",
"size": "3458",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "deeplearning4j/deeplearning4j-data/deeplearning4j-datasets/src/main/java/org/deeplearning4j/datasets/mnist/MnistDbFile.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1458"
},
{
"name": "C",
"bytes": "165340"
},
{
"name": "C++",
"bytes": "17817311"
},
{
"name": "CMake",
"bytes": "112697"
},
{
"name": "CSS",
"bytes": "12974"
},
{
"name": "Cuda",
"bytes": "2413085"
},
{
"name": "Cython",
"bytes": "12094"
},
{
"name": "FreeMarker",
"bytes": "77257"
},
{
"name": "HTML",
"bytes": "18609"
},
{
"name": "Java",
"bytes": "47657420"
},
{
"name": "JavaScript",
"bytes": "296767"
},
{
"name": "Kotlin",
"bytes": "2041047"
},
{
"name": "PureBasic",
"bytes": "12254"
},
{
"name": "Python",
"bytes": "77566"
},
{
"name": "Ruby",
"bytes": "4558"
},
{
"name": "Scala",
"bytes": "1026"
},
{
"name": "Shell",
"bytes": "92012"
},
{
"name": "Smarty",
"bytes": "975"
},
{
"name": "Starlark",
"bytes": "931"
},
{
"name": "TypeScript",
"bytes": "81217"
}
],
"symlink_target": ""
} |
title: "Aqua Motion"
description: "Services for senior health."
robots: none
---
{% include {{ page.d.inc }}/local.html %}
| {
"content_hash": "21914101d0504ed3930dc5f66268a53d",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 42,
"avg_line_length": 20.666666666666668,
"alnum_prop": 0.6693548387096774,
"repo_name": "inlandsplash/www.inlandsplash.org",
"id": "42524aa5bc45af65022ede075f4c3175377fb350",
"size": "128",
"binary": false,
"copies": "3",
"ref": "refs/heads/gh-pages",
"path": "aqua-motion/index.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package com.xeiam.xchange.dto.trade;
import java.math.BigDecimal;
import java.util.Date;
import com.xeiam.xchange.currency.CurrencyPair;
import com.xeiam.xchange.dto.Order.OrderType;
import com.xeiam.xchange.dto.marketdata.Trade;
/**
* Data object representing a user trade
*/
public class UserTrade extends Trade {
/**
* The id of the order responsible for execution of this trade
*/
private final String orderId;
/**
* The fee that was charged by the exchange for this trade.
*/
private final BigDecimal feeAmount;
/**
* The symbol of the currency in which the fee was charged.
*/
private final String feeCurrency;
/**
* This constructor is called to construct user's trade objects (in
* {@link com.xeiam.xchange.service.polling.trade.PollingTradeService#getTradeHistory(Object...)} implementations).
*
* @param type The trade type (BID side or ASK side)
* @param tradableAmount The depth of this trade
* @param tradableIdentifier The exchange identifier (e.g. "BTC/USD")
* @param transactionCurrency The transaction currency (e.g. USD in BTC/USD)
* @param price The price (either the bid or the ask)
* @param timestamp The timestamp of the trade
* @param id The id of the trade
* @param orderId The id of the order responsible for execution of this trade
* @param feeAmount The fee that was charged by the exchange for this trade
* @param feeCurrency The symbol of the currency in which the fee was charged
*/
public UserTrade(OrderType type, BigDecimal tradableAmount, CurrencyPair currencyPair, BigDecimal price, Date timestamp, String id, String orderId,
BigDecimal feeAmount, String feeCurrency) {
super(type, tradableAmount, currencyPair, price, timestamp, id);
this.orderId = orderId;
this.feeAmount = feeAmount;
this.feeCurrency = feeCurrency;
}
public String getOrderId() {
return orderId;
}
public BigDecimal getFeeAmount() {
return feeAmount;
}
public String getFeeCurrency() {
return feeCurrency;
}
@Override
public String toString() {
return "UserTrade[type=" + type + ", tradableAmount=" + tradableAmount + ", currencyPair=" + currencyPair + ", price=" + price + ", " +
"timestamp=" + timestamp +
", id=" + id +
", orderId='" + orderId + '\'' +
", feeAmount=" + feeAmount +
", feeCurrency='" + feeCurrency + '\'' +
"]";
}
public static class Builder extends Trade.Builder {
protected String orderId;
protected BigDecimal feeAmount;
protected String feeCurrency;
public static Builder from(UserTrade trade) {
return new Builder().type(trade.getType()).tradableAmount(trade.getTradableAmount()).currencyPair(trade.getCurrencyPair())
.price(trade.getPrice()).timestamp(trade.getTimestamp()).id(trade.getId()).orderId(trade.getOrderId()).feeAmount(trade.getFeeAmount())
.feeCurrency(trade.getFeeCurrency());
}
public Builder type(OrderType type) {
return (Builder) super.type(type);
}
public Builder tradableAmount(BigDecimal tradableAmount) {
return (Builder) super.tradableAmount(tradableAmount);
}
public Builder currencyPair(CurrencyPair currencyPair) {
return (Builder) super.currencyPair(currencyPair);
}
public Builder price(BigDecimal price) {
return (Builder) super.price(price);
}
public Builder timestamp(Date timestamp) {
return (Builder) super.timestamp(timestamp);
}
public Builder id(String id) {
return (Builder) super.id(id);
}
public Builder orderId(String orderId) {
this.orderId = orderId;
return this;
}
public Builder feeAmount(BigDecimal feeAmount) {
this.feeAmount = feeAmount;
return this;
}
public Builder feeCurrency(String feeCurrency) {
this.feeCurrency = feeCurrency;
return this;
}
public UserTrade build() {
return new UserTrade(type, tradableAmount, currencyPair, price, timestamp, id, orderId, feeAmount, feeCurrency);
}
}
}
| {
"content_hash": "78f6a99b3a25462c73022ce8aff955f0",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 149,
"avg_line_length": 30.08823529411765,
"alnum_prop": 0.6862170087976539,
"repo_name": "nivertech/XChange",
"id": "288de6cfc6beb33cfc25da1cdc7f8c2c26671f97",
"size": "4092",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "xchange-core/src/main/java/com/xeiam/xchange/dto/trade/UserTrade.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "4604003"
}
],
"symlink_target": ""
} |
CodeGuard
=========
A simple Guard and validator library made in c#.
Library also available at NuGet.
Need more checks?? Please contribute or contact me.
Example of usage:
-----------------
// --- using Guard.That(...) ---
// Guard.That that will throw an exception, when some condition is not met
public void SomeMethod(int arg1, int arg2)
{
// This line will throw an exception when the arg1 is less or equal to arg2
Guard.That(() => arg1).IsGreaterThan(arg2);
// This will check that arg1 is not null and that is in some range 1..100
Guard.That(arg2).IsNotNull().IsInRange(1,100);
// Several checks can be added.
Guard.That(arg1).IsInRange(100,1000).IsEven().IsTrue(x => x > 50, "Must be over 500");
// Do stuff
}
// --- using Validate.That(...) ---
// Validate.That makes is possible to get a list of all error conditions
public void OtherMethod(int arg1)
{
// Get a list of errors
List<string> errors = Validate.That(() => arg1).IsNotNull().GetResult();
}
Incomplete list of checks:
--------------------------
The following checks are available. But the best documentation is currently the tests.
New checks can easily be made by creating a extension method.
For object:
* Is<Type>
* IsNotDefault
For bool:
* IsTrue
* IsFalse
For class:
* IsNotNull
For IComparable (Int32, Double, String, Char, DateTime and other classes implementing the interface)
* IsEqual
* IsNotEqual
* IsGreatherThan
* IslessThan
* IsInRange
For int and long:
* IsOdd
* IsEven
* IsPrime
For string:
* IsNotEmpty
* IsNotNullOrEmpty
* StartsWith
* EndsWith
* Length
* Contains
* IsMatch
For IEnumerable:
* IsNotEmpty
* Length
* Conatins
For Guid:
* IsNotEmpty
| {
"content_hash": "645c22f1c87258a0c971976ee9331997",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 100,
"avg_line_length": 18.445652173913043,
"alnum_prop": 0.6882734236888627,
"repo_name": "3komma14/Guard",
"id": "a125ade5763428ca3b9038f03728cef12643e258",
"size": "1697",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.markdown",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "2437"
},
{
"name": "C#",
"bytes": "116453"
},
{
"name": "Pascal",
"bytes": "35977"
},
{
"name": "PowerShell",
"bytes": "8317"
},
{
"name": "Puppet",
"bytes": "2914"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project name="Example04" default="help">
<!-- The local.properties file is created and updated by the 'android' tool.
It contains the path to the SDK. It should *NOT* be checked into
Version Control Systems. -->
<property file="local.properties" />
<!-- The ant.properties file can be created by you. It is only edited by the
'android' tool to add properties to it.
This is the place to change some Ant specific build properties.
Here are some properties you may want to change/update:
source.dir
The name of the source directory. Default is 'src'.
out.dir
The name of the output directory. Default is 'bin'.
For other overridable properties, look at the beginning of the rules
files in the SDK, at tools/ant/build.xml
Properties related to the SDK location or the project target should
be updated using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your
application and should be checked into Version Control Systems.
-->
<property file="ant.properties" />
<!-- if sdk.dir was not set from one of the property file, then
get it from the ANDROID_HOME env var.
This must be done before we load project.properties since
the proguard config can use sdk.dir -->
<property environment="env" />
<condition property="sdk.dir" value="${env.ANDROID_HOME}">
<isset property="env.ANDROID_HOME" />
</condition>
<!-- The project.properties file is created and updated by the 'android'
tool, as well as ADT.
This contains project specific properties such as project target, and library
dependencies. Lower level build properties are stored in ant.properties
(or in .classpath for Eclipse projects).
This file is an integral part of the build system for your
application and should be checked into Version Control Systems. -->
<loadproperties srcFile="project.properties" />
<!-- quick check on sdk.dir -->
<fail
message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through the ANDROID_HOME environment variable."
unless="sdk.dir"
/>
<!--
Import per project custom build rules if present at the root of the project.
This is the place to put custom intermediary targets such as:
-pre-build
-pre-compile
-post-compile (This is typically used for code obfuscation.
Compiled code location: ${out.classes.absolute.dir}
If this is not done in place, override ${out.dex.input.absolute.dir})
-post-package
-post-build
-pre-clean
-->
<import file="custom_rules.xml" optional="true" />
<!-- Import the actual build file.
To customize existing targets, there are two options:
- Customize only one target:
- copy/paste the target into this file, *before* the
<import> task.
- customize it to your needs.
- Customize the whole content of build.xml
- copy/paste the content of the rules files (minus the top node)
into this file, replacing the <import> task.
- customize to your needs.
***********************
****** IMPORTANT ******
***********************
In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
in order to avoid having your file be overridden by tools such as "android update project"
-->
<!-- version-tag: 1 -->
<import file="${sdk.dir}/tools/ant/build.xml" />
</project>
| {
"content_hash": "578d99a0a27b667d5872ca7ec9ddf6fd",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 174,
"avg_line_length": 42.619565217391305,
"alnum_prop": 0.6197398622800306,
"repo_name": "donlee888/JsObjects",
"id": "c0dde5bf800223783afbca6ddec456b6bd02961a",
"size": "3921",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "JavaScript/DataUsers/Example04/build.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "856096"
},
{
"name": "Java",
"bytes": "10014"
},
{
"name": "JavaScript",
"bytes": "9362649"
},
{
"name": "Python",
"bytes": "100882"
},
{
"name": "Ruby",
"bytes": "2648"
},
{
"name": "Shell",
"bytes": "51772"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>W28914_text</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div style="margin-left: auto; margin-right: auto; width: 800px; overflow: hidden;">
<div style="float: left;">
<a href="page15.html">«</a>
</div>
<div style="float: right;">
</div>
</div>
<hr/>
<div style="position: absolute; margin-left: 275px; margin-top: 274px;">
<p class="styleSans660.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Hess Corporation EN-VP&R-154-94-2536H-2 <br/>Section 24 T154N R94W Mountrail County, North Dakota <br/>Tiffani Kennedy, Wellsite Geologist <br/>SERVICE <br/>Nos. <br/>6844 Highway 40 Tioga ND. 58852 701-664—1492 <br/> </p>
</div>
</body>
</html>
| {
"content_hash": "b1cd572597f17ac9f18b3dbdc710e806",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 346,
"avg_line_length": 42.78260869565217,
"alnum_prop": 0.5873983739837398,
"repo_name": "datamade/elpc_bakken",
"id": "42d9ac1d83f096a6b6d799f05b6b0c08a547e770",
"size": "987",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ocr_extracted/W28914_text/page16.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "17512999"
},
{
"name": "HTML",
"bytes": "421900941"
},
{
"name": "Makefile",
"bytes": "991"
},
{
"name": "Python",
"bytes": "7186"
}
],
"symlink_target": ""
} |
@implementation FocusBoxLayer
- (instancetype)init {
if (self = [super init]) {
[self setCornerRadius:45.0f];
[self setBounds:CGRectMake(0.0f, 0.0f, 90, 90)];
[self setBorderWidth:5.f];
[self setBorderColor:[UIColorFromRGB(0xffffff) CGColor]];
[self setOpacity:0];
}
return self;
}
- (void)drawaAtPointOfInterest:(CGPoint)point andRemove:(BOOL)remove {
if ( remove )
[self removeAllAnimations];
if ( [self animationForKey:@"transform.scale"] == nil && [self animationForKey:@"opacity"] == nil ) {
[CATransaction begin];
[CATransaction setValue: (id) kCFBooleanTrue forKey: kCATransactionDisableActions];
[self setPosition:point];
[CATransaction commit];
CABasicAnimation *scale = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
[scale setFromValue:[NSNumber numberWithFloat:1]];
[scale setToValue:[NSNumber numberWithFloat:0.7]];
[scale setDuration:0.8];
[scale setRemovedOnCompletion:YES];
CABasicAnimation *opacity = [CABasicAnimation animationWithKeyPath:@"opacity"];
[opacity setFromValue:[NSNumber numberWithFloat:1]];
[opacity setToValue:[NSNumber numberWithFloat:0]];
[opacity setDuration:0.8];
[opacity setRemovedOnCompletion:YES];
[self addAnimation:scale forKey:@"transform.scale"];
[self addAnimation:opacity forKey:@"opacity"];
}
}
@end
| {
"content_hash": "b2537e5bef6134bb34ea22855d9c2d85",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 105,
"avg_line_length": 36.48780487804878,
"alnum_prop": 0.6490641711229946,
"repo_name": "hawk0620/ZPCamera",
"id": "9739eb7bdfeedf17849bc788d19c2fcdcb43601a",
"size": "1652",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ZPCamera/Model/Animation/FocusBox/FocusBoxLayer.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "33440"
},
{
"name": "Objective-C",
"bytes": "531759"
},
{
"name": "Ruby",
"bytes": "259"
}
],
"symlink_target": ""
} |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.296
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace Package.Client.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| {
"content_hash": "920450b2d88c832a096091af5d47aa54",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 151,
"avg_line_length": 37.61538461538461,
"alnum_prop": 0.5633946830265849,
"repo_name": "IKende/IKendeLib",
"id": "f3dc93ba4bfebf4abda343828fb7c46ef092eb65",
"size": "1086",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BeetleDemo/Examples/Package/Package.Client/Package.Client/Properties/Settings.Designer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "40128"
},
{
"name": "C",
"bytes": "1093"
},
{
"name": "C#",
"bytes": "1152929"
},
{
"name": "C++",
"bytes": "25351"
},
{
"name": "CSS",
"bytes": "210883"
},
{
"name": "Java",
"bytes": "64771"
},
{
"name": "JavaScript",
"bytes": "951934"
},
{
"name": "Objective-C",
"bytes": "111"
},
{
"name": "Shell",
"bytes": "1272"
}
],
"symlink_target": ""
} |
<?php
class Service extends FormModel
{
/**
* Returns the list of attribute names.
* By default, this method returns all public properties of the class.
* You may override this method to change the default.
* @return array list of attribute names. Defaults to all public properties of the class.
*/
public function attributeNames(){
$className=get_class($this);
if(!isset(self::$_names[$className])){
$class=new ReflectionClass(get_class($this));
$names=array();
foreach($class->getProperties() as $property){
$name=$property->getName();
if($property->isPublic() && !$property->isStatic())
$names[]=$name;
}
return self::$_names[$className]=$names;
}
else
return self::$_names[$className];
}
/**
* 查找属性值
* @param string $model AR类名
* @param integer $contentId tbContent.id
* @param array $attributeIds 属性ID
* @return array AR记录数组
*/
public function findAllAttributeValue($model, $contentId, $attributeIds){
if(!empty($contentId) && !empty($attributeIds) && is_numeric($contentId) && is_array($attributeIds)) {
$ids = implode(',', $attributeIds);
return $model::model()->findAll(array('select'=>array('fdAttributeID','fdValue'),
'condition'=>"fdContentID = '{$contentId}' AND fdAttributeID IN ({$ids})"));
}
}
} | {
"content_hash": "e0a4d90b12f41029885f345015554fd7",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 110,
"avg_line_length": 35.41860465116279,
"alnum_prop": 0.5666447800393959,
"repo_name": "GitLigbee/ITManage",
"id": "6ec6d77d4a64e5d3843565c3038f1c444c5754ce",
"size": "1549",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "webroot/manage/protected/components/Service.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "126"
},
{
"name": "Batchfile",
"bytes": "1717"
},
{
"name": "CSS",
"bytes": "125329"
},
{
"name": "HTML",
"bytes": "62293"
},
{
"name": "JavaScript",
"bytes": "261963"
},
{
"name": "PHP",
"bytes": "22173012"
}
],
"symlink_target": ""
} |
<HTML><HEAD>
<TITLE>Review for Heat (1995)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1 ALIGN="CENTER" CLASS="title"><A HREF="/Title?0113277">Heat (1995)</A></H1><H3 ALIGN=CENTER>reviewed by<BR><A HREF="/ReviewsBy?Christopher+Null">Christopher Null</A></H3><HR WIDTH="40%" SIZE="4">
<PRE> HEAT
A film review by Christopher Null
Copyright 1995 Christopher Null</PRE>
<P> I hate to condone the making of 3-hour long movies, but HEAT is one
in which you're not going to fall asleep. Comparisons to CASINO are going
to be inevitable, with both hitting the 180-minute mark and starring
Robert DeNiro as a crook, but unlike that film, HEAT manages to keep the
interest level high throughout the whole picture.</P>
<P> HEAT is the instantly gripping tale of a large-scale heist leader and
die-hard loner named Neil McCauley (DeNiro). As the film opens, he and
his team of brutal, precision thieves (including Val Kilmer and Tom
Sizemore) knock over (literally) an armored car for a stash of bearer
bonds. On the case is Detective Vincent Hanna (Al Pacino), a troubled,
angst-ridden veteran of the LAPD. Over the course of the film, McCauley
and Hanna develop a strange sort of kinship, even as McCauley's crimes
increasingly raise the stakes and Hanna's efforts to stop him become more
and more desperate.</P>
<P> The action builds up for a solid two hours until a nearly
catastrophic "final" bank robbery results in one of the most vivid
shoot-outs ever filmed. Writer/director Michael Mann (best known for his
work on "Miami Vice") paces the movie well, and he really puts the
audience through the ringer by getting the adrenaline pumping like an oil
well.</P>
<P> But why is this film 3 hours long, you ask? The answer lies in
Mann's multidimensional examinations of all the major characters, their
wives, their children, and any other love interests who happen along.
Thus over the course of the picture, we discover Hanna is in his third
marriage and his wife's ex-husband is a deadbeat. We learn at length
about McCauley's personal code: to have nothing in his life he can't walk
away from in 30 seconds flat if "the heat" is coming. And when the heat
does come, we see how it affects everyone...in depth. While these
relationship subplots are mildly interesting, they seem completely out of
place in the movie and, in the end, weigh the film down.</P>
<P> This aside, strong performances by the principals and some excellent
bit parts by players like Hank Azaria, Tom Noonan, Natalie Portman, and
Jon Voight make HEAT a truly memorable film. Somewhat more difficult to
figure out is Pacino, who takes his over-the-top, in-your-face screen
presence to new heights, becoming almost cartoonish in his archetypal
portrayal of the insanely driven cop. Altogether, the cast lends a lot of
credibility to what would otherwise be another run-of-the-mill crime
movie. And while the sometimes hard-to-follow script often demands too
much of the viewer, this film is one that's truly worth seeing.</P>
<PRE>RATING: ****</PRE>
<PRE>\-------------------------------\
|* Unquestionably awful |
|** Sub-par on many levels |
|*** Average, hits and misses |
|**** Good, memorable film |
|***** Perfection |
\-------------------------------\ </PRE>
<P>-Christopher Null / <A HREF="mailto:[email protected]">[email protected]</A>
-Movie Emporium (reviews) / <A HREF="http://www.notes.tpoint.net/emporium/">http://www.notes.tpoint.net/emporium/</A>
-Contributing Editor, FEEDBACK / <A HREF="http://www.eden.com/~feedback/">http://www.eden.com/~feedback/</A>
-E-mail requests to join the movie review mailing list</P>
<HR><P CLASS=flush><SMALL>The review above was posted to the
<A HREF="news:rec.arts.movies.reviews">rec.arts.movies.reviews</A> newsgroup (<A HREF="news:de.rec.film.kritiken">de.rec.film.kritiken</A> for German reviews).<BR>
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.<BR>
Please direct comments/criticisms of the review to relevant newsgroups.<BR>
Broken URLs inthe reviews are the responsibility of the author.<BR>
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
</SMALL></P>
<P ALIGN=CENTER>Related links: <A HREF="/Reviews/">index of all rec.arts.movies.reviews reviews</A></P>
</P></BODY></HTML>
| {
"content_hash": "9e3d0e4f526a655f1eba0fe1fe8c13af",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 198,
"avg_line_length": 63.16,
"alnum_prop": 0.7088874815283935,
"repo_name": "xianjunzhengbackup/code",
"id": "2c35baa5b511fff341bd7ca7d80e3219ccc67c00",
"size": "4737",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data science/machine_learning_for_the_web/chapter_4/movie/4390.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "BitBake",
"bytes": "113"
},
{
"name": "BlitzBasic",
"bytes": "256"
},
{
"name": "CSS",
"bytes": "49827"
},
{
"name": "HTML",
"bytes": "157006325"
},
{
"name": "JavaScript",
"bytes": "14029"
},
{
"name": "Jupyter Notebook",
"bytes": "4875399"
},
{
"name": "Mako",
"bytes": "2060"
},
{
"name": "Perl",
"bytes": "716"
},
{
"name": "Python",
"bytes": "874414"
},
{
"name": "R",
"bytes": "454"
},
{
"name": "Shell",
"bytes": "3984"
}
],
"symlink_target": ""
} |
<?php
/*
* This file is part of the overtrue/wechat.
*
* (c) overtrue <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace EasyWeChat\Work\Jssdk;
use Pimple\Container;
use Pimple\ServiceProviderInterface;
/**
* Class ServiceProvider.
*
* @author mingyoung <[email protected]>
*/
class ServiceProvider implements ServiceProviderInterface
{
/**
* {@inheritdoc}.
*/
public function register(Container $app)
{
$app['jssdk'] = function ($app) {
return new Client($app);
};
}
}
| {
"content_hash": "6510d6aafa1c23d2090511cc570f558e",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 65,
"avg_line_length": 19.303030303030305,
"alnum_prop": 0.6483516483516484,
"repo_name": "tianyong90/wechat",
"id": "efb509ca3fa0c4986c6809369ac16fc4946562f1",
"size": "637",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/Work/Jssdk/ServiceProvider.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "1069371"
},
{
"name": "Shell",
"bytes": "3021"
}
],
"symlink_target": ""
} |
<?php
require APPPATH . '/libraries/REST_Controller.php';
class api extends REST_Controller {
function user_get() {
die('wrong');
if (!$this->get('id')) {
$this->response(NULL, 400);
}
$user = $this->user_model->get($this->get('id'));
if ($user) {
$this->response($user, 200); // 200 being the HTTP response code
} else {
$this->response(NULL, 404);
}
}
function user_post() {
$result = $this->user_model->update($this->post('id'), array(
'name' => $this->post('name'),
'email' => $this->post('email'),
));
if ($result === FALSE) {
$this->response(array('status' => 'failed'));
} else {
$this->response(array('status' => 'success'));
}
}
function users_get() {
$users = $this->user_model->get_all();
if ($users) {
$this->response($users, 200);
} else {
$this->response(NULL, 404);
}
}
}
?> | {
"content_hash": "8887df7c563a0649b0f2ab5c500a433f",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 67,
"avg_line_length": 20.023255813953487,
"alnum_prop": 0.5632984901277585,
"repo_name": "sajidshah/customapi",
"id": "6f0fc33344c54435e7dd8d5be3aac50ba694db5d",
"size": "861",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/controllers/api.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "363"
},
{
"name": "HTML",
"bytes": "5633"
},
{
"name": "PHP",
"bytes": "1867821"
}
],
"symlink_target": ""
} |
package com.huawei.streaming.cql.semanticanalyzer.analyzecontext.expressiondesc;
import java.util.ArrayList;
import java.util.List;
import com.huawei.streaming.cql.executor.BinaryExpression;
import com.huawei.streaming.cql.executor.expressioncreater.BinaryExpressionCreator;
import com.huawei.streaming.cql.executor.operatorinfocreater.ExpressionCreatorAnnotation;
/**
* 二元表达式描述
*
* 包含对逻辑表达式、算术表达式和关系表达式的描述
*
*/
@ExpressionCreatorAnnotation(BinaryExpressionCreator.class)
public class BinaryExpressionDesc implements ExpressionDescribe
{
/**
* 二元表达式信息
*/
private BinaryExpression bexpression;
/**
* 二元表达式的参数信息
*/
private List<ExpressionDescribe> argExpressions = new ArrayList<ExpressionDescribe>();;
/**
* <默认构造函数>
*/
public BinaryExpressionDesc(BinaryExpression bexpression)
{
super();
this.bexpression = bexpression;
}
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
return "(" + argExpressions.get(0).toString() + " " + bexpression.getType().getDesc() + " "
+ argExpressions.get(1).toString() + ")";
}
public BinaryExpression getBexpression()
{
return bexpression;
}
public void setBexpression(BinaryExpression bexpression)
{
this.bexpression = bexpression;
}
public List<ExpressionDescribe> getArgExpressions()
{
return argExpressions;
}
public void setArgExpressions(List<ExpressionDescribe> argExpressions)
{
this.argExpressions = argExpressions;
}
}
| {
"content_hash": "0beb34fb95328c2866a19ebc0e1188b9",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 99,
"avg_line_length": 23.028169014084508,
"alnum_prop": 0.6654434250764526,
"repo_name": "HuaweiBigData/StreamCQL",
"id": "a9fc7a8c16eca3fcb070da71ebe5ef17a8ae8910",
"size": "2543",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cql/src/main/java/com/huawei/streaming/cql/semanticanalyzer/analyzecontext/expressiondesc/BinaryExpressionDesc.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "26371"
},
{
"name": "Batchfile",
"bytes": "2101"
},
{
"name": "Java",
"bytes": "5401832"
},
{
"name": "Shell",
"bytes": "692"
}
],
"symlink_target": ""
} |
package com.github.pwittchen.networkevents.library.receiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.github.pwittchen.networkevents.library.BusWrapper;
import com.github.pwittchen.networkevents.library.ConnectivityStatus;
import com.github.pwittchen.networkevents.library.logger.Logger;
public final class InternetConnectionChangeReceiver extends BaseBroadcastReceiver {
public final static String INTENT =
"networkevents.intent.action.INTERNET_CONNECTION_STATE_CHANGED";
public final static String INTENT_EXTRA = "networkevents.intent.extra.CONNECTED_TO_INTERNET";
public InternetConnectionChangeReceiver(BusWrapper busWrapper, Logger logger, Context context) {
super(busWrapper, logger, context);
}
@Override public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(INTENT)) {
boolean connectedToInternet = intent.getBooleanExtra(INTENT_EXTRA, false);
onPostReceive(connectedToInternet, context);
}
}
public void onPostReceive(boolean connectedToInternet, Context context) {
ConnectivityStatus connectivityStatus =
(connectedToInternet) ? ConnectivityStatus.WIFI_CONNECTED_HAS_INTERNET
: ConnectivityStatus.WIFI_CONNECTED_HAS_NO_INTERNET;
if (statusNotChanged(connectivityStatus)) {
return;
}
// we are checking if device is connected to WiFi again,
// because connectivityStatus may change in a short period of time
// after receiving it
if (context != null && !isConnectedToWifi(context)) {
return;
}
postConnectivityChanged(connectivityStatus);
}
private boolean isConnectedToWifi(Context context) {
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null) {
return networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
}
return false;
}
}
| {
"content_hash": "c9c5ac4386a2cb30bea78cdd9dc2c15f",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 98,
"avg_line_length": 35.1,
"alnum_prop": 0.7630579297245964,
"repo_name": "pwittchen/NetworkEvents",
"id": "57d89f0fcdde74c91239c5ab31f7d75af6fae766",
"size": "2703",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "network-events-library/src/main/java/com/github/pwittchen/networkevents/library/receiver/InternetConnectionChangeReceiver.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "52494"
}
],
"symlink_target": ""
} |
/*
* File: app.js
*
* This file was generated by Sencha Architect version 2.2.2.
* http://www.sencha.com/products/architect/
*
* This file requires use of the Sencha Touch 2.2.x library, under independent license.
* License of Sencha Architect does not include license for Sencha Touch 2.2.x. For more
* details see http://www.sencha.com/license or contact [email protected].
*
* This file will be auto-generated each and everytime you save your project.
*
* Do NOT hand edit this file.
*/
//@require @packageOverrides
Ext.Loader.setConfig({
});
Ext.application({
views: [
'LoginForm'
],
controllers: [
'SampleController'
],
name: 'MyApp',
launch: function() {
Ext.create('MyApp.view.LoginForm', {fullscreen: true});
}
});
| {
"content_hash": "5b0288c1e0de68fd8df88a5d3e2a1faa",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 88,
"avg_line_length": 22.714285714285715,
"alnum_prop": 0.6616352201257861,
"repo_name": "sdharmadhikari/sencha-rest-login-module",
"id": "3ebe487e8fe15b3eded402ff1befb9437693f185",
"size": "795",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "login-module/app.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1984"
},
{
"name": "JavaScript",
"bytes": "9865"
}
],
"symlink_target": ""
} |
class UnixWindow;
class UnixPanel : public MainPanel
{
Q_OBJECT
public:
UnixPanel(UnixWindow* panel);
public slots:
void pushButtonMinimize();
void pushButtonMaximize();
void pushButtonClose();
private:
UnixWindow* unixPanel;
};
| {
"content_hash": "6fc6f353eb4cbf0dfca5f6354c4d4f6d",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 34,
"avg_line_length": 14.333333333333334,
"alnum_prop": 0.7015503875968992,
"repo_name": "qwerty01/Client",
"id": "b30a9e9048df4f11cdc0dce62a3bf07c7f425818",
"size": "296",
"binary": false,
"copies": "4",
"ref": "refs/heads/dev",
"path": "Source/UnixPanel.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "62"
},
{
"name": "C++",
"bytes": "458989"
},
{
"name": "CMake",
"bytes": "5348"
},
{
"name": "CSS",
"bytes": "899"
},
{
"name": "QMake",
"bytes": "1052"
}
],
"symlink_target": ""
} |
<h1>WebSocket Server in c#</h1>
<p>NOTE: This is no longer maintained. See https://github.com/ninjasource/Ninja.WebSockets</p>
<p>Set <code>WebSockets.Cmd</code> as the startup project</p>
<h2>License</h2>
The MIT License (MIT)
<br/>See LICENCE.txt
<h2>Introduction</h2>
<p>A lot of the Web Socket examples out there are for old Web Socket versions and included complicated code (and external libraries) for fall back communication. All modern browsers that anyone cares about (including safari on an iphone) support at least <strong>version 13 of the Web Socket protocol </strong>so I'd rather not complicate things. This is a bare bones implementation of the web socket protocol in C# with no external libraries involved. You can connect using standard HTML5 JavaScript.</p>
<p>This application serves up basic html pages as well as handling WebSocket connections. This may seem confusing but it allows you to send the client the html they need to make a web socket connection and also allows you to share the same port. However, the <code>HttpConnection</code> is very rudimentary. I'm sure it has some glaring security problems. It was just made to make this demo easier to run. Replace it with your own or don't use it.</p>
<h2>Background</h2>
<p>There is nothing magical about Web Sockets. The spec is easy to follow and there is no need to use special libraries. At one point, I was even considering somehow communicating with Node.js but that is not necessary. The spec can be a bit fiddly with bits and bytes but this was probably done to keep the overheads low. This is my first CodeProject article and I hope you will find it easy to follow. The following links offer some great advice:</p>
<p>Step by step guide</p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers">https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers</a></li>
</ul>
<p>The official Web Socket spec</p>
<ul>
<li><a href="http://tools.ietf.org/html/rfc6455">http://tools.ietf.org/html/rfc6455</a></li>
</ul>
<p>Some useful stuff in C#</p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_server">https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_server</a></li>
</ul>
<h2>Using the Code</h2>
<p>NOTE You will get a firewall warning because you are listening on a port. This is normal for any socket based server.<p>
<p>A good place to put a breakpoint is in the <code>WebServer</code> class in the <code>HandleAsyncConnection</code> function. Note that this is a multithreaded server so you may want to freeze threads if this gets confusing. The console output prints the thread id to make things easier. If you want to skip past all the plumbing, then another good place to start is the <code>Respond</code> function in the <code>WebSocketConnection</code> class. If you are not interested in the inner workings of Web Sockets and just want to use them, then take a look at the <code>OnTextFrame</code> in the <code>ChatWebSocketConnection</code> class. See below.</p>
<p>Implementation of a chat web socket connection is as follows:</p>
<pre lang="cs">
internal class ChatWebSocketService : WebSocketService
{
private readonly IWebSocketLogger _logger;
public ChatWebSocketService(NetworkStream networkStream, TcpClient tcpClient, string header, IWebSocketLogger logger)
: base(networkStream, tcpClient, header, true, logger)
{
_logger = logger;
}
protected override void OnTextFrame(string text)
{
string response = "ServerABC: " + text;
base.Send(response);
_logger.Information(this.GetType(), response);
}
}</pre>
<p>The factory used to create the connection is as follows:</p>
<pre lang="cs">
internal class ServiceFactory : IServiceFactory
{
public ServiceFactory(string webRoot, IWebSocketLogger logger)
{
_logger = logger;
_webRoot = webRoot;
}
public IService CreateInstance(ConnectionDetails connectionDetails)
{
switch (connectionDetails.ConnectionType)
{
case ConnectionType.WebSocket:
// you can support different kinds of web socket connections using a different path
if (connectionDetails.Path == "/chat")
{
return new ChatWebSocketService(connectionDetails.NetworkStream, connectionDetails.TcpClient, connectionDetails.Header, _logger);
}
break;
case ConnectionType.Http:
// this path actually refers to the reletive location of some html file or image
return new HttpService(connectionDetails.NetworkStream, connectionDetails.Path, _webRoot, _logger);
}
return new BadRequestService(connectionDetails.NetworkStream, connectionDetails.Header, _logger);
}
}</pre>
<p>HTML5 JavaScript used to connect:</p>
<pre lang="jscript">
// open the connection to the Web Socket server
var CONNECTION = new WebSocket('ws://localhost/chat');
// Log messages from the server
CONNECTION.onmessage = function (e) {
console.log(e.data);
};
CONNECTION.send('Hellow World');</pre>
<p>Starting the server and the test client: </p>
<pre lang="cs">
private static void Main(string[] args)
{
IWebSocketLogger logger = new WebSocketLogger();
try
{
string webRoot = Settings.Default.WebRoot;
int port = Settings.Default.Port;
// used to decide what to do with incoming connections
ServiceFactory serviceFactory = new ServiceFactory(webRoot, logger);
using (WebServer server = new WebServer(serviceFactory, logger))
{
server.Listen(port);
Thread clientThread = new Thread(new ParameterizedThreadStart(TestClient));
clientThread.IsBackground = false;
clientThread.Start(logger);
Console.ReadKey();
}
}
catch (Exception ex)
{
logger.Error(null, ex);
Console.ReadKey();
}
}</pre>
<p>The test client runs a short self test to make sure that everything is fine. Opening and closing handshakes are tested here. </p>
<h2>Web Socket Protocol</h2>
<p>The first thing to realize about the protocol is that it is, in essence, a basic duplex TCP/IP socket connection. The connection starts off with the client connecting to a remote server and sending http header text to that server. The header text asks the web server to upgrade the connection to a web socket connection. This is done as a handshake where the web server responds with an appropriate http text header and from then onwards, the client and server will talk the Web Socket language.</p>
<h3>Server Handshake</h3>
<pre lang="cs">
Regex webSocketKeyRegex = new Regex("Sec-WebSocket-Key: (.*)");
Regex webSocketVersionRegex = new Regex("Sec-WebSocket-Version: (.*)");
// check the version. Support version 13 and above
const int WebSocketVersion = 13;
int secWebSocketVersion = Convert.ToInt32(webSocketVersionRegex.Match(header).Groups[1].Value.Trim());
if (secWebSocketVersion < WebSocketVersion)
{
throw new WebSocketVersionNotSupportedException(string.Format("WebSocket Version {0} not suported. Must be {1} or above", secWebSocketVersion, WebSocketVersion));
}
string secWebSocketKey = webSocketKeyRegex.Match(header).Groups[1].Value.Trim();
string setWebSocketAccept = base.ComputeSocketAcceptString(secWebSocketKey);
string response = ("HTTP/1.1 101 Switching Protocols" + Environment.NewLine
+ "Connection: Upgrade" + Environment.NewLine
+ "Upgrade: websocket" + Environment.NewLine
+ "Sec-WebSocket-Accept: " + setWebSocketAccept);
HttpHelper.WriteHttpHeader(response, networkStream);</pre>
<p>This computes the <code>accept string</code>:</p>
<pre lang="cs">
/// <summary>
/// Combines the key supplied by the client with a guid and returns the sha1 hash of the combination
/// </summary>
public static string ComputeSocketAcceptString(string secWebSocketKey)
{
// this is a guid as per the web socket spec
const string webSocketGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
string concatenated = secWebSocketKey + webSocketGuid;
byte[] concatenatedAsBytes = Encoding.UTF8.GetBytes(concatenated);
byte[] sha1Hash = SHA1.Create().ComputeHash(concatenatedAsBytes);
string secWebSocketAccept = Convert.ToBase64String(sha1Hash);
return secWebSocketAccept;
}</pre>
<h3>Client Handshake</h3>
<pre lang="cs">
Uri uri = _uri;
WebSocketFrameReader reader = new WebSocketFrameReader();
Random rand = new Random();
byte[] keyAsBytes = new byte[16];
rand.NextBytes(keyAsBytes);
string secWebSocketKey = Convert.ToBase64String(keyAsBytes);
string handshakeHttpRequestTemplate = @"GET {0} HTTP/1.1{4}" +
"Host: {1}:{2}{4}" +
"Upgrade: websocket{4}" +
"Connection: Upgrade{4}" +
"Sec-WebSocket-Key: {3}{4}" +
"Sec-WebSocket-Version: 13{4}{4}";
string handshakeHttpRequest = string.Format(handshakeHttpRequestTemplate, uri.PathAndQuery, uri.Host, uri.Port, secWebSocketKey, Environment.NewLine);
byte[] httpRequest = Encoding.UTF8.GetBytes(handshakeHttpRequest);
networkStream.Write(httpRequest, 0, httpRequest.Length);</pre>
<h3>Reading and Writing</h3>
<p>After the handshake as been performed, the server goes into a <code>read</code> loop. The following two class convert a stream of bytes to a web socket frame and visa versa: <code>WebSocketFrameReader</code> and <code>WebSocketFrameWriter</code>. </p>
<pre lang="cs">
// from WebSocketFrameReader class
public WebSocketFrame Read(NetworkStream stream, Socket socket)
{
byte byte1;
try
{
byte1 = (byte) stream.ReadByte();
}
catch (IOException)
{
if (socket.Connected)
{
throw;
}
else
{
return null;
}
}
// process first byte
byte finBitFlag = 0x80;
byte opCodeFlag = 0x0F;
bool isFinBitSet = (byte1 & finBitFlag) == finBitFlag;
WebSocketOpCode opCode = (WebSocketOpCode) (byte1 & opCodeFlag);
// read and process second byte
byte byte2 = (byte) stream.ReadByte();
byte maskFlag = 0x80;
bool isMaskBitSet = (byte2 & maskFlag) == maskFlag;
uint len = ReadLength(byte2, stream);
byte[] decodedPayload;
// use the masking key to decode the data if needed
if (isMaskBitSet)
{
const int maskKeyLen = 4;
byte[] maskKey = BinaryReaderWriter.ReadExactly(maskKeyLen, stream);
byte[] encodedPayload = BinaryReaderWriter.ReadExactly((int) len, stream);
decodedPayload = new byte[len];
// apply the mask key
for (int i = 0; i < encodedPayload.Length; i++)
{
decodedPayload[i] = (Byte) (encodedPayload[i] ^ maskKey[i%maskKeyLen]);
}
}
else
{
decodedPayload = BinaryReaderWriter.ReadExactly((int) len, stream);
}
WebSocketFrame frame = new WebSocketFrame(isFinBitSet, opCode, decodedPayload, true);
return frame;
}</pre>
<pre lang="cs">
// from WebSocketFrameWriter class
public void Write(WebSocketOpCode opCode, byte[] payload, bool isLastFrame)
{
// best to write everything to a memory stream before we push it onto the wire
// not really necessary but I like it this way
using (MemoryStream memoryStream = new MemoryStream())
{
byte finBitSetAsByte = isLastFrame ? (byte)0x80 : (byte)0x00;
byte byte1 = (byte)(finBitSetAsByte | (byte)opCode);
memoryStream.WriteByte(byte1);
// NB, dont set the mask flag. No need to mask data from server to client
// depending on the size of the length we want to write it as a byte, ushort or ulong
if (payload.Length < 126)
{
byte byte2 = (byte)payload.Length;
memoryStream.WriteByte(byte2);
}
else if (payload.Length <= ushort.MaxValue)
{
byte byte2 = 126;
memoryStream.WriteByte(byte2);
BinaryReaderWriter.WriteUShort((ushort)payload.Length, memoryStream, false);
}
else
{
byte byte2 = 127;
memoryStream.WriteByte(byte2);
BinaryReaderWriter.WriteULong((ulong)payload.Length, memoryStream, false);
}
memoryStream.Write(payload, 0, payload.Length);
byte[] buffer = memoryStream.ToArray();
_stream.Write(buffer, 0, buffer.Length);
}
}
</pre>
<h2>Points of Interest</h2>
<p>Problems with Proxy Servers:<br />
Proxy servers which have not been configured to support Web sockets will not work well with them.<br />
I suggest that you use transport layer security if you want this to work across the wider internet especially from within a corporation.</p>
<h2>History</h2>
<ul>
<li>Version 1.01 WebSocket</li>
<li>Version 1.02 Fixed endianness bug with length field</li>
<li>Version 1.03 Major refactor and added support for c# Client</li>
</ul>
| {
"content_hash": "2a23eb481a1c3aafb69ea3ae698e56c0",
"timestamp": "",
"source": "github",
"line_count": 321,
"max_line_length": 658,
"avg_line_length": 41.6822429906542,
"alnum_prop": 0.6878176382660688,
"repo_name": "ninjasource/websocket-server",
"id": "0129085c7a096b6aabbd5afb87f5400b594ada20",
"size": "13380",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "136"
},
{
"name": "C#",
"bytes": "71385"
},
{
"name": "HTML",
"bytes": "2477"
}
],
"symlink_target": ""
} |
package org.hswebframework.web.authorization.basic.handler.access;
import org.hswebframework.web.authorization.access.DataAccessConfig;
import org.hswebframework.web.authorization.access.DataAccessController;
import org.hswebframework.web.authorization.access.DataAccessHandler;
import org.hswebframework.web.authorization.define.AuthorizingContext;
import java.util.LinkedList;
import java.util.List;
/**
* 默认的行级权限控制.通过获取DataAccessHandler进行实际处理
*
* @author zhouhao
* @see DataAccessHandler
* @since 3.0
*/
public final class DefaultDataAccessController implements DataAccessController {
private DataAccessController parent;
private List<DataAccessHandler> handlers = new LinkedList<>();
public DefaultDataAccessController() {
this(null);
}
public DefaultDataAccessController(DataAccessController parent) {
if (parent == this) {
throw new UnsupportedOperationException();
}
this.parent = parent;
addHandler(new FieldFilterDataAccessHandler())
.addHandler(new DimensionDataAccessHandler());
}
@Override
public boolean doAccess(DataAccessConfig access, AuthorizingContext context) {
if (parent != null) {
parent.doAccess(access, context);
}
return handlers.stream()
.filter(handler -> handler.isSupport(access))
.allMatch(handler -> handler.handle(access, context));
}
public DefaultDataAccessController addHandler(DataAccessHandler handler) {
handlers.add(handler);
return this;
}
public void setHandlers(List<DataAccessHandler> handlers) {
this.handlers = handlers;
}
public List<DataAccessHandler> getHandlers() {
return handlers;
}
}
| {
"content_hash": "b499d924a3391275a758e58b9198dfdf",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 82,
"avg_line_length": 30.322033898305083,
"alnum_prop": 0.7015092230296255,
"repo_name": "hs-web/hsweb-framework",
"id": "5c67912c5a2c799fc7cf981491cd8492c0ab4fae",
"size": "1827",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/access/DefaultDataAccessController.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1352858"
},
{
"name": "JavaScript",
"bytes": "3965"
},
{
"name": "Shell",
"bytes": "91"
}
],
"symlink_target": ""
} |
package org.jkiss.dbeaver.ext.erd.part;
import org.eclipse.draw2d.ChopboxAnchor;
import org.eclipse.draw2d.ConnectionAnchor;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.ConnectionEditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;
import org.jkiss.dbeaver.ext.erd.ERDMessages;
import org.jkiss.dbeaver.ext.erd.figures.NoteFigure;
import org.jkiss.dbeaver.ext.erd.model.ERDNote;
import org.jkiss.dbeaver.ext.erd.model.EntityDiagram;
import org.jkiss.dbeaver.ext.erd.policy.NoteEditPolicy;
import org.jkiss.dbeaver.model.DBPNamedObject;
import org.jkiss.dbeaver.ui.dialogs.EditTextDialog;
import java.beans.PropertyChangeEvent;
/**
* Represents the editable/resizable note.
*
* @author Serge Rider
*/
public class NotePart extends NodePart
{
public NotePart() {
}
public ERDNote getNote()
{
return (ERDNote) getModel();
}
/**
* Creates edit policies and associates these with roles
*/
@Override
protected void createEditPolicies()
{
final boolean editEnabled = isEditEnabled();
if (editEnabled) {
//installEditPolicy(EditPolicy.GRAPHICAL_NODE_ROLE, new EntityNodeEditPolicy());
//installEditPolicy(EditPolicy.LAYOUT_ROLE, new EntityLayoutEditPolicy());
//installEditPolicy(EditPolicy.CONTAINER_ROLE, new EntityContainerEditPolicy());
installEditPolicy(EditPolicy.COMPONENT_ROLE, new NoteEditPolicy());
//installEditPolicy(EditPolicy.DIRECT_EDIT_ROLE, new NoteDirectEditPolicy());
//installEditPolicy(EditPolicy.SELECTION_FEEDBACK_ROLE, new ResizableEditPolicy());
}
}
@Override
public void performRequest(Request request)
{
if (request.getType() == RequestConstants.REQ_DIRECT_EDIT)
{
/*
if (request instanceof DirectEditRequest
&& !directEditHitTest(((DirectEditRequest) request).getLocation().getCopy()))
return;
performDirectEdit();
*/
} else if (request.getType() == RequestConstants.REQ_OPEN) {
final String newText = EditTextDialog.editText(getViewer().getControl().getShell(), ERDMessages.part_note_title, getNote().getObject());
if (newText != null) {
getNote().setObject(newText);
((NoteFigure)getFigure()).setText(newText);
}
//getTable().openEditor();
}
}
//******************* Miscellaneous stuff *********************/
public String toString()
{
return getNote().getObject();
}
//******************* Listener related methods *********************/
public void handleNameChange(String value)
{
NoteFigure noteFigure = (NoteFigure) getFigure();
noteFigure.setVisible(false);
refreshVisuals();
}
/**
* Reverts to existing name in model when exiting from a direct edit
* (possibly before a commit which will result in a change in the label
* value)
*/
public void revertNameChange()
{
NoteFigure noteFigure = (NoteFigure) getFigure();
noteFigure.setText(getNote().getObject());
noteFigure.setVisible(true);
refreshVisuals();
}
/**
* Handles change in name when committing a direct edit
*/
@Override
protected void commitNameChange(PropertyChangeEvent evt)
{
NoteFigure noteFigure = (NoteFigure) getFigure();
noteFigure.setText(getNote().getObject());
noteFigure.setVisible(true);
refreshVisuals();
}
//******************* Layout related methods *********************/
/**
* Creates a figure which represents the table
*/
@Override
protected IFigure createFigure()
{
final NoteFigure noteFigure = new NoteFigure(getNote());
EntityDiagram.NodeVisualInfo visualInfo = ((DiagramPart) getParent()).getDiagram().getVisualInfo(getNote(), true);
Rectangle bounds = visualInfo.initBounds;
if (bounds != null) {
noteFigure.setBounds(bounds);
noteFigure.setPreferredSize(bounds.getSize());
//noteFigure.setLocation(bounds.getLocation());
//noteFigure.setSize(bounds.getSize());
} else if (noteFigure.getSize().isEmpty()) {
noteFigure.setPreferredSize(new Dimension(100, 50));
}
this.customBackground = visualInfo.bgColor;
if (this.customBackground != null) {
noteFigure.setBackgroundColor(this.customBackground);
}
return noteFigure;
}
/**
* Reset the layout constraint, and revalidate the content pane
*/
@Override
protected void refreshVisuals()
{
NoteFigure notefigure = (NoteFigure) getFigure();
Point location = notefigure.getLocation();
DiagramPart parent = (DiagramPart) getParent();
Rectangle constraint = new Rectangle(location.x, location.y, -1, -1);
parent.setLayoutConstraint(this, notefigure, constraint);
}
/**
* Sets the width of the line when selected
*/
@Override
public void setSelected(int value)
{
super.setSelected(value);
/*
NoteFigure noteFigure = (NoteFigure) getFigure();
if (value != EditPart.SELECTED_NONE)
noteFigure.setSelected(true);
else
noteFigure.setSelected(false);
noteFigure.repaint();
*/
}
@Override
public ConnectionAnchor getSourceConnectionAnchor(ConnectionEditPart connection)
{
return new ChopboxAnchor(getFigure());
}
@Override
public ConnectionAnchor getSourceConnectionAnchor(Request request)
{
return new ChopboxAnchor(getFigure());
}
@Override
public ConnectionAnchor getTargetConnectionAnchor(ConnectionEditPart connection)
{
return new ChopboxAnchor(getFigure());
}
@Override
public ConnectionAnchor getTargetConnectionAnchor(Request request)
{
return new ChopboxAnchor(getFigure());
}
@Override
public Object getAdapter(Class key)
{
if (key == DBPNamedObject.class) {
return getNote();
}
return super.getAdapter(key);
}
} | {
"content_hash": "f34ee8f9cbac4e9bde097ff775cf7837",
"timestamp": "",
"source": "github",
"line_count": 209,
"max_line_length": 148,
"avg_line_length": 30.411483253588518,
"alnum_prop": 0.6500943989930774,
"repo_name": "ruspl-afed/dbeaver",
"id": "e408e7bed7afa6c09f70d876c8296778e6000cf9",
"size": "7102",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plugins/org.jkiss.dbeaver.ext.erd/src/org/jkiss/dbeaver/ext/erd/part/NotePart.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "690"
},
{
"name": "C++",
"bytes": "65328"
},
{
"name": "CSS",
"bytes": "4214"
},
{
"name": "HTML",
"bytes": "2368"
},
{
"name": "Java",
"bytes": "12750447"
},
{
"name": "Shell",
"bytes": "32"
},
{
"name": "XSLT",
"bytes": "7361"
}
],
"symlink_target": ""
} |
package com.zxh.ssm.module.user.service.impl;
import com.zxh.ssm.module.whole.mapper.PatientInformationMapper;
import com.zxh.ssm.module.user.pojo.*;
import com.zxh.ssm.module.user.service.UploadToPIService;
import com.zxh.ssm.module.whole.pojo.PatientInformation;
import com.zxh.ssm.module.whole.pojo.PatientInformationKey;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
* Created by 郑晓辉 on 2016/10/4.
*/
@Service
public class UploadToPIServiceImpl implements UploadToPIService {
@Resource
private PatientInformationMapper patientInformationMapper;
/**
* 根据path,对不同版本的Excel文档进行数据的读取
*
* @param path Excel文档路径
* @return 数据的实体List
* @throws Exception
*/
private RowDataSorted<ErrorPatientInformation<String>, PatientInformation> getExcelData(String path) throws Exception {
GetExcelValue excelValue = new GetExcelValue();
List<PatientInformation> list = new ArrayList<PatientInformation>();
List<ErrorPatientInformation<String>> errorPatientInformationList = new ArrayList<>();
ErrorPatientInformation<String> errorPatientInformation = null;
PatientInformation patientInformation = null;
InputStream is = new FileInputStream(path);
if (path.endsWith("xls")) {
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
// 循环工作表Sheet
for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
// 循环行Row
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if (hssfRow != null) {
patientInformation = new PatientInformation();
errorPatientInformation = new ErrorPatientInformation();
HSSFCell year = hssfRow.getCell(0);
HSSFCell cardId = hssfRow.getCell(1);
HSSFCell name = hssfRow.getCell(2);
HSSFCell sex = hssfRow.getCell(3);
HSSFCell career = hssfRow.getCell(4);
HSSFCell birthday = hssfRow.getCell(5);
HSSFCell age = hssfRow.getCell(6);
HSSFCell workUnit = hssfRow.getCell(7);
HSSFCell tel = hssfRow.getCell(8);
HSSFCell belongs = hssfRow.getCell(9);
HSSFCell address = hssfRow.getCell(10);
HSSFCell addrNationId = hssfRow.getCell(11);
try {
if (!excelValue.getValue(year).equals(".") && !excelValue.getValue(cardId).equals(".")) {
patientInformation.setYear(Integer.parseInt(excelValue.getValue(year)));
patientInformation.setCardid(Integer.parseInt(excelValue.getValue(cardId)));
if (!excelValue.getValue(name).equals(".")) {
patientInformation.setName(excelValue.getValue(name));
}
if (!excelValue.getValue(career).equals(".")) {
patientInformation.setCareer(excelValue.getValue(career));
}
if (!excelValue.getValue(sex).equals(".")) {
patientInformation.setSex(excelValue.getValue(sex));
}
if (!excelValue.getValue(birthday).equals(".")) {
patientInformation.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(excelValue.getValue(birthday)));
} else {
patientInformation.setBirthday(null);
}
if (!excelValue.getValue(age).equals(".")) {
patientInformation.setAge(excelValue.getValue(age));
}
if (!excelValue.getValue(workUnit).equals(".")) {
patientInformation.setWorkunit(excelValue.getValue(workUnit));
}
if (!excelValue.getValue(tel).equals(".")) {
patientInformation.setTel(excelValue.getValue(tel));
}
if (!excelValue.getValue(belongs).equals(".")) {
patientInformation.setBelongs(excelValue.getValue(belongs));
}
if (!excelValue.getValue(address).equals(".")) {
patientInformation.setAddress(excelValue.getValue(address));
}
if (!excelValue.getValue(addrNationId).equals(".")) {
patientInformation.setAddrnationid(Integer.valueOf(excelValue.getValue(addrNationId)));
} else {
patientInformation.setAddrnationid(0);
}
}
} catch (Exception e) {
System.out.println("【!读取数据时出了异常】 message:" + e.getMessage());
//数据不是按规定填写的,数据格式均为String展示用
errorPatientInformation.setYear(excelValue.getValue(year));
errorPatientInformation.setCardid(excelValue.getValue(cardId));
errorPatientInformation.setName(excelValue.getValue(name));
errorPatientInformation.setCareer(excelValue.getValue(career));
errorPatientInformation.setSex(excelValue.getValue(sex));
errorPatientInformation.setBirthday(excelValue.getValue(birthday));
errorPatientInformation.setAge(excelValue.getValue(age));
errorPatientInformation.setWorkunit(excelValue.getValue(workUnit));
errorPatientInformation.setTel(excelValue.getValue(tel));
errorPatientInformation.setBelongs(excelValue.getValue(belongs));
errorPatientInformation.setAddress(excelValue.getValue(address));
errorPatientInformation.setAddrnationid(excelValue.getValue(addrNationId));
errorPatientInformationList.add(errorPatientInformation);
continue;
}
list.add(patientInformation);
continue;
}
}
}
} else if (path.endsWith("xlsx")) {
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
// 循环工作表Sheet
for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
if (xssfSheet == null) {
continue;
}
// 循环行Row
for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
XSSFRow xssfRow = xssfSheet.getRow(rowNum);
if (xssfRow != null) {
patientInformation = new PatientInformation();
errorPatientInformation = new ErrorPatientInformation();
XSSFCell year = xssfRow.getCell(0);
XSSFCell cardId = xssfRow.getCell(1);
XSSFCell name = xssfRow.getCell(2);
XSSFCell sex = xssfRow.getCell(3);
XSSFCell career = xssfRow.getCell(4);
XSSFCell birthday = xssfRow.getCell(5);
XSSFCell age = xssfRow.getCell(6);
XSSFCell workUnit = xssfRow.getCell(7);
XSSFCell tel = xssfRow.getCell(8);
XSSFCell belongs = xssfRow.getCell(9);
XSSFCell address = xssfRow.getCell(10);
XSSFCell addrNationId = xssfRow.getCell(11);
try {
if (!excelValue.getValue(year).equals(".") && !excelValue.getValue(cardId).equals(".")) {
patientInformation.setYear(Integer.parseInt(excelValue.getValue(year)));
patientInformation.setCardid(Integer.parseInt(excelValue.getValue(cardId)));
if (!excelValue.getValue(name).equals(".")) {
patientInformation.setName(excelValue.getValue(name));
}
if (!excelValue.getValue(career).equals(".")) {
patientInformation.setCareer(excelValue.getValue(career));
}
if (!excelValue.getValue(sex).equals(".")) {
patientInformation.setSex(excelValue.getValue(sex));
}
if (!excelValue.getValue(birthday).equals(".")) {
patientInformation.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(excelValue.getValue(birthday)));
} else {
patientInformation.setBirthday(null);
}
if (!excelValue.getValue(age).equals(".")) {
patientInformation.setAge(excelValue.getValue(age));
}
if (!excelValue.getValue(workUnit).equals(".")) {
patientInformation.setWorkunit(excelValue.getValue(workUnit));
}
if (!excelValue.getValue(tel).equals(".")) {
patientInformation.setTel(excelValue.getValue(tel));
}
if (!excelValue.getValue(belongs).equals(".")) {
patientInformation.setBelongs(excelValue.getValue(belongs));
}
if (!excelValue.getValue(addrNationId).equals(".")) {
patientInformation.setAddrnationid(Integer.valueOf(excelValue.getValue(addrNationId)));
} else {
patientInformation.setAddrnationid(0);
}
if (!excelValue.getValue(address).equals(".")) {
patientInformation.setAddress(excelValue.getValue(address));
}
}
} catch (Exception e) {
System.out.println("【!读取数据时出了异常】 message:" + e.getMessage());
//数据不是按规定填写的,数据格式均为String展示用
errorPatientInformation.setYear(excelValue.getValue(year));
errorPatientInformation.setCardid(excelValue.getValue(cardId));
errorPatientInformation.setName(excelValue.getValue(name));
errorPatientInformation.setSex(excelValue.getValue(sex));
errorPatientInformation.setBirthday(excelValue.getValue(birthday));
errorPatientInformation.setAge(excelValue.getValue(age));
errorPatientInformation.setWorkunit(excelValue.getValue(workUnit));
errorPatientInformation.setTel(excelValue.getValue(tel));
errorPatientInformation.setBelongs(excelValue.getValue(belongs));
errorPatientInformation.setCareer(excelValue.getValue(career));
errorPatientInformation.setAddress(excelValue.getValue(address));
errorPatientInformation.setAddrnationid(excelValue.getValue(addrNationId));
errorPatientInformationList.add(errorPatientInformation);
continue;
}
list.add(patientInformation);
continue;
}
}
}
}
RowDataSorted<ErrorPatientInformation<String>, PatientInformation> rowDataSorted = new RowDataSorted<>();
rowDataSorted.setKeyNotNullList(list);
rowDataSorted.setErrorReadingList(errorPatientInformationList);
return rowDataSorted;
}
/**
* 根据文件路径,读取excel文件数据
*
* @param path excel文件路径
* @return 操作状态封装类
* @throws Exception
*/
public UploadDBMessage<ErrorPatientInformation<String>, PatientInformation> saveDataToPatientInformation(String path) throws Exception {
//读取excel数据、处理错误数据
RowDataSorted<ErrorPatientInformation<String>, PatientInformation> rowDataSorted = getExcelData(path);
List<PatientInformation> excelDataList = rowDataSorted.getKeyNotNullList();
List<ErrorPatientInformation<String>> errorReadingList = rowDataSorted.getErrorReadingList();
//上传文件信息
UploadDBMessage<ErrorPatientInformation<String>, PatientInformation> uploadDBMessage = new UploadDBMessage<>();
uploadDBMessage.setErrorReadingList(errorReadingList);
PatientInformation excelRowData = new PatientInformation();
//有记录则更新,无记录则插入,主键为空的数据全部丢弃
PatientInformationKey patientInformationKey = new PatientInformationKey();
List<PatientInformation> updateDataList = new ArrayList<>();
List<PatientInformation> insertDataList = new ArrayList<>();
List<PatientInformation> errorOperatingList = new ArrayList<>();
//数据遍历分类
for (int i = 0; i < excelDataList.size(); i++) {
excelRowData = excelDataList.get(i);
if (null == excelRowData.getYear() || null == excelRowData.getCardid()){
continue;
}
patientInformationKey.setYear(excelRowData.getYear());
patientInformationKey.setCardid(excelRowData.getCardid());
if (patientInformationMapper.selectByPrimaryKey(patientInformationKey) != null) {
updateDataList.add(excelRowData);
excelRowData = null;
continue;
}
insertDataList.add(excelRowData);
excelRowData = null;
continue;
}
//插入操作
int insertRecordNum = 0;
for (int i = 0; i < insertDataList.size(); i++) {
PatientInformation current = insertDataList.get(i);
try {
if (patientInformationMapper.insert(current) == 1) {
insertRecordNum += 1;
continue;
}
} catch (DuplicateKeyException d) {
System.out.println("【!插入操作主键重复异常】 message:" + d.getMessage());
errorOperatingList.add(current);
continue;
} catch (Exception e) {
System.out.println("【!插入操作Exception抛出】message:" + e.getMessage());
errorOperatingList.add(current);
continue;
}
}
//更新操作
int updateRecordNum = 0;
for (int i = 0; i < updateDataList.size(); i++) {
PatientInformation current = updateDataList.get(i);
try {
if (patientInformationMapper.updateByPrimaryKey(current) == 1) {
updateRecordNum += 1;
continue;
}
} catch (DuplicateKeyException d) {
System.out.println("【!更新操作主键重复异常】 message:" + d.getMessage());
errorOperatingList.add(current);
continue;
} catch (Exception e) {
System.out.println("【!更新操作Exception抛出】message:" + e.getMessage());
errorOperatingList.add(current);
continue;
}
}
//操作结果信息(包括成功插入及更新信息数、错误数据信息、主键为空的数据信息)
uploadDBMessage.setSuccessInsertNum(insertRecordNum);
uploadDBMessage.setSuccessUpdateNum(updateRecordNum);
uploadDBMessage.setErrorOperatingList(errorOperatingList);
return uploadDBMessage;
}
} | {
"content_hash": "6f82cb01680e4020164ead47aa6ffaee",
"timestamp": "",
"source": "github",
"line_count": 316,
"max_line_length": 140,
"avg_line_length": 55.20886075949367,
"alnum_prop": 0.5279147082425771,
"repo_name": "Harveychn/MalariaProject",
"id": "84478154b1a66bb1af63ea99eec1548a694e9d0d",
"size": "17986",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/zxh/ssm/module/user/service/impl/UploadToPIServiceImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "222134"
},
{
"name": "Java",
"bytes": "844566"
},
{
"name": "JavaScript",
"bytes": "2194823"
}
],
"symlink_target": ""
} |
exports.log = function(string, data) {
if (!string && !data) {
console.error('System log requires at least one argument.');
}
if (!data) {
console.log("\n" + string + "\n");
} else {
if (data instanceof Array || data instanceof Object) {
console.log(
'\n' + string, JSON.stringify(data),
'\n'
);
} else {
console.log('\n' + string + data + '\n');
}
}
} | {
"content_hash": "6f69ad4853fac2b9435600b558ab41f9",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 68,
"avg_line_length": 21.82608695652174,
"alnum_prop": 0.43227091633466136,
"repo_name": "sanderblue/angular-express-mysql",
"id": "683f2d48aa691814272d0a4aa22a5eb2f5e0a2a0",
"size": "502",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/config/console.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10005"
},
{
"name": "JavaScript",
"bytes": "575859"
},
{
"name": "Ruby",
"bytes": "873"
}
],
"symlink_target": ""
} |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class AudioHandlerController : MonoBehaviour {
public Text ButtonText;
public void ToggleMusic() {
if(AudioListener.volume == 0.0f) {
AudioListener.volume = 1.0f;
this.UpdateButtonText("off");
}
else if(AudioListener.volume == 1.0f) {
AudioListener.volume = 0.0f;
this.UpdateButtonText("on");
}
}
private void UpdateButtonText(string value) {
ButtonText.text = "Turn music " + value;
}
} | {
"content_hash": "9266ecd0b10566ff7491bf11db2efd8a",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 53,
"avg_line_length": 21.434782608695652,
"alnum_prop": 0.7099391480730223,
"repo_name": "crilleengvall/UnityExamples",
"id": "70dc8db329b5d3cdee10e0cb64f09209d3e1cd19",
"size": "495",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Assets/AudioHandlerController.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "2717"
}
],
"symlink_target": ""
} |
package com.plugin.commons.adapter;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.plugin.R;
import com.plugin.commons.ComApp;
import com.plugin.commons.CoreContants;
import com.plugin.commons.helper.ComUtil;
import com.plugin.commons.model.NumberType;
import com.plugin.commons.ui.baoliao.BaoliaoDetailActivity;
import com.plugin.commons.ui.number.NumberListActivity;
public class NumberTypeAdapter extends ZhKdBaseAdapter<NumberType> {
private Context context;
public NumberTypeAdapter(Context context, List<NumberType> numTypes){
this.context = context;
this.dataList = numTypes;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final NumberType number=dataList.get(position);
List<List<NumberType> > groupType=new ArrayList<List<NumberType> >();
View rowView = convertView;
final NewListItemCache viewCache;
if (rowView == null) {
rowView = LayoutInflater.from(context).inflate(R.layout.item_number_ext, null);
viewCache = new NewListItemCache(rowView, null, context, position+ "");
viewCache.getTv_title();
viewCache.getLl_datalist();
rowView.setTag(viewCache);
} else {
viewCache = (NewListItemCache) rowView.getTag();
}
viewCache.getTv_title().setText(number.getName());
viewCache.getLl_datalist().removeAllViews();
//组装数据
List<NumberType> temList = new ArrayList<NumberType>();
int index=0;
boolean flag=false;//分组标识
for(NumberType num:number.getSubtypes()){
temList.add(num);
index++;
if(index%3==0){//8个元素为一组
groupType.add(temList);
temList=new ArrayList<NumberType>();
flag=true;
}else{
flag=false;
}
}
if(!flag){
groupType.add(temList);
}
//描绘视图
drowView(viewCache.getLl_datalist(),groupType);
return rowView;
}
class ItemOnclickListener implements OnClickListener{
NumberType numType;
LinearLayout dataList;
List<List<NumberType> > groupType;
ItemOnclickListener(NumberType numType){
this.numType=numType;
}
ItemOnclickListener(LinearLayout dataList,List<List<NumberType> > groupType){
this.dataList=dataList;
this.groupType=groupType;
}
@Override
public void onClick(View v) {
String flag=(String) v.getTag(R.id.tv_title3);
if(v.getId()==R.id.tv_title3&&"more".equals(flag)){
this.dataList.removeAllViews();
drowFullView(this.dataList,this.groupType);
}else{
Intent intent=new Intent(context ,NumberListActivity.class);
intent.putExtra(CoreContants.PARAMS_MSG,numType);
intent.putExtra(CoreContants.PARAM_CODE, "");
context.startActivity(intent);
}
}
}
private void drowView(LinearLayout dataList,List<List<NumberType> > groupType){
int lineNum=0;
for(List<NumberType> temL:groupType){
View chiView=LayoutInflater.from(context).inflate(R.layout.item_num, null);
TextView tv1=(TextView) chiView.findViewById(R.id.tv_title1);
TextView tv2=(TextView) chiView.findViewById(R.id.tv_title2);
TextView tv3=(TextView) chiView.findViewById(R.id.tv_title3);
lineNum++;
if(lineNum>3){
chiView.setVisibility(View.GONE);
}else if(lineNum==3){
for(int a=0;a<temL.size();a++){
if(a==0){
tv1.setText(temL.get(a).getName());
tv1.setOnClickListener(new ItemOnclickListener(temL.get(a)));
tv1.setVisibility(View.VISIBLE);
}
if(a==1){
tv2.setOnClickListener(new ItemOnclickListener(temL.get(a)));
tv2.setText(temL.get(a).getName());
tv2.setVisibility(View.VISIBLE);
}
if(a==2){
tv3.setVisibility(View.VISIBLE);
tv3.setOnClickListener(new ItemOnclickListener(dataList,groupType));
tv3.setText("更多>>");
tv3.setTag(R.id.tv_title3, "more");
tv3.setTextColor(ComApp.getInstance().getResources().getColor(R.color.light_blue));
}
}
}else{
for(int a=0;a<temL.size();a++){
if(a==0){
tv1.setVisibility(View.VISIBLE);
tv1.setText(temL.get(a).getName());
tv1.setOnClickListener(new ItemOnclickListener(temL.get(a)));
}
if(a==1){
tv2.setVisibility(View.VISIBLE);
tv2.setOnClickListener(new ItemOnclickListener(temL.get(a)));
tv2.setText(temL.get(a).getName());
}
if(a==2){
tv3.setVisibility(View.VISIBLE);
tv3.setText(temL.get(a).getName());
tv3.setOnClickListener(new ItemOnclickListener(temL.get(a)));
}
}
}
dataList.addView(chiView);
}
}
private void drowFullView(LinearLayout dataList,List<List<NumberType> > groupType){
for(List<NumberType> temL:groupType){
View chiView=LayoutInflater.from(context).inflate(R.layout.item_num, null);
TextView tv1=(TextView) chiView.findViewById(R.id.tv_title1);
TextView tv2=(TextView) chiView.findViewById(R.id.tv_title2);
TextView tv3=(TextView) chiView.findViewById(R.id.tv_title3);
for(int a=0;a<temL.size();a++){
if(a==0){
tv1.setVisibility(View.VISIBLE);
tv1.setText(temL.get(a).getName());
tv1.setOnClickListener(new ItemOnclickListener(temL.get(a)));
}
if(a==1){
tv2.setVisibility(View.VISIBLE);
tv2.setOnClickListener(new ItemOnclickListener(temL.get(a)));
tv2.setText(temL.get(a).getName());
}
if(a==2){
tv3.setVisibility(View.VISIBLE);
tv3.setText(temL.get(a).getName());
tv3.setOnClickListener(new ItemOnclickListener(temL.get(a)));
}
}
dataList.addView(chiView);
}
}
}
| {
"content_hash": "cc77f5badb5ca5125f9025b0f5b766d8",
"timestamp": "",
"source": "github",
"line_count": 191,
"max_line_length": 89,
"avg_line_length": 29.94240837696335,
"alnum_prop": 0.69749956286064,
"repo_name": "zhanggh/andr_puligins",
"id": "f10493140e017aaa000425d02f21a1600af36785",
"size": "5759",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "library_common/src/com/plugin/commons/adapter/NumberTypeAdapter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2002060"
}
],
"symlink_target": ""
} |
package com.tq.requisition.infrastructure.Specifications.project;
import com.tq.requisition.domain.Specification.Specification;
import com.tq.requisition.domain.Specification.expression.IHqlExpression;
import com.tq.requisition.domain.Specification.expression.OperationType;
import com.tq.requisition.domain.model.project.Project;
import com.tq.requisition.infrastructure.Specifications.Expression.HqlExpression;
/**
* 规约,根据项目名称判断是否存在
* @author jjh
* @time 2016-01-15 17:44
*
*/
public class ProExistsByNameSpecification extends Specification<Project>{
private String name;
public ProExistsByNameSpecification(Class<Project> _t,String proName) {
super(_t);
this.name = proName;
}
@Override
public IHqlExpression getHqlExpression() {
IHqlExpression expression = new HqlExpression();
expression.setSql("select count(1) from tb_project where pro_name=?");
expression.setParameters(name);
expression.setType(OperationType.SQL);
return expression;
}
}
| {
"content_hash": "b6d2107b053218d0ff2f88c360402923",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 81,
"avg_line_length": 30.5625,
"alnum_prop": 0.7944785276073619,
"repo_name": "huahuajjh/requisition_land",
"id": "070454790b31521cb635929eb4dfeb569f9de3f5",
"size": "1008",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/tq/requisition/infrastructure/Specifications/project/ProExistsByNameSpecification.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "374534"
},
{
"name": "HTML",
"bytes": "53638"
},
{
"name": "Java",
"bytes": "1741763"
},
{
"name": "JavaScript",
"bytes": "1151556"
}
],
"symlink_target": ""
} |
Although Go strives to be a cross platform language, cross compilation from one
platform to another is not as simple as it could be, as you need the Go sources
bootstrapped to each platform and architecture.
The first step towards cross compiling was Dave Cheney's [golang-crosscompile](https://github.com/davecheney/golang-crosscompile)
package, which automatically bootstrapped the necessary sources based on your
existing Go installation. Although this was enough for a lot of cases, certain
drawbacks became apparent where the official libraries used CGO internally: any
dependency to third party platform code is unavailable, hence those parts don't
cross compile nicely (native DNS resolution, system certificate access, etc).
A step forward in enabling cross compilation was Alan Shreve's [gonative](https://github.com/inconshreveable/gonative)
package, which instead of bootstrapping the different platforms based on the
existing Go installation, downloaded the official pre-compiled binaries from the
golang website and injected those into the local toolchain. Since the pre-built
binaries already contained the necessary platform specific code, the few missing
dependencies were resolved, and true cross compilation could commence... of pure
Go code.
However, there was still one feature missing: cross compiling Go code that used
CGO itself, which isn't trivial since you need access to OS specific headers and
libraries. This becomes very annoying when you need access only to some trivial
OS specific functionality (e.g. query the CPU load), but need to configure and
maintain separate build environments to do it.
## Enter xgo
My solution to the challenge of cross compiling Go code with embedded C snippets
(i.e. CGO_ENABLED=1) is based on the concept of [lightweight Linux containers](http://en.wikipedia.org/wiki/LXC).
All the necessary Go tool-chains, C cross compilers and platform headers/libraries
have been assembled into a single Docker container, which can then be called as if
a single command to compile a Go package to various platforms and architectures.
## Installation
Although you could build the container manually, it is available as an automatic
trusted build from Docker's container registry (~530MB):
docker pull karalabe/xgo-latest
To prevent having to remember a potentially complex Docker command every time,
a lightweight Go wrapper was written on top of it.
go get github.com/karalabe/xgo
## Usage
Simply specify the import path you want to build, and xgo will do the rest:
$ xgo github.com/project-iris/iris
...
$ ls -al
-rwxr-xr-x 1 root root 6021828 May 4 10:59 iris-darwin-386
-rwxr-xr-x 1 root root 7664428 May 4 10:59 iris-darwin-amd64
-rwxr-xr-x 1 root root 8292432 May 4 10:59 iris-linux-386
-rwxr-xr-x 1 root root 10252920 May 4 10:59 iris-linux-amd64
-rwxr-xr-x 1 root root 8222976 May 4 10:59 iris-linux-arm
-rwxr-xr-x 1 root root 8373248 May 4 10:59 iris-windows-386.exe
-rwxr-xr-x 1 root root 10331648 May 4 10:59 iris-windows-amd64.exe
### Build flags
A handful of flags can be passed to `go build`. The currently supported ones are
- `-v`: prints the names of packages as they are compiled
- `-race`: enables data race detection (supported only on amd64, rest built without)
### Go releases
As newer versions of the language runtime, libraries and tools get released,
these will get incorporated into xgo too as extensions layers to the base cross
compilation image (only Go 1.3 and above will be supported).
You can select which Go release to work with through the `-go` command line flag
to xgo and if the specific release was already integrated, it will automatically
be retrieved and installed.
$ xgo -go 1.4.2 github.com/project-iris/iris
Since xgo depends on not only the official releases, but also on Dave Cheney's
ARM packages, there will be a slight delay between official Go updates and the
xgo updates.
Additionally, a few wildcard release strings are also supported:
- `latest` will use the latest Go release
- `1.4.x` will use the latest point release of a specific Go version
### Output prefixing
xgo by default uses the name of the package being cross compiled as the output
file prefix. This can be overridden with the `-out` flag.
$ xgo -out iris-v0.3.2 github.com/project-iris/iris
...
$ ls -al
-rwxr-xr-x 1 root root 6021828 May 4 11:00 iris-v0.3.2-darwin-386
-rwxr-xr-x 1 root root 7664428 May 4 11:00 iris-v0.3.2-darwin-amd64
-rwxr-xr-x 1 root root 8292432 May 4 11:00 iris-v0.3.2-linux-386
-rwxr-xr-x 1 root root 10252920 May 4 11:00 iris-v0.3.2-linux-amd64
-rwxr-xr-x 1 root root 8222976 May 4 11:00 iris-v0.3.2-linux-arm
-rwxr-xr-x 1 root root 8373248 May 4 11:00 iris-v0.3.2-windows-386.exe
-rwxr-xr-x 1 root root 10331648 May 4 11:00 iris-v0.3.2-windows-amd64.exe
### Package selection
If the project you are cross compiling is not a single executable, but rather a
larger project containing multiple commands, you can select the specific sub-
package to build via the `--pkg` flag.
$ xgo --pkg cmd/goimports golang.org/x/tools
...
$ ls -al
-rwxr-xr-x 1 root root 3824276 May 4 11:13 goimports-darwin-386
-rwxr-xr-x 1 root root 4947056 May 4 11:13 goimports-darwin-amd64
-rwxr-xr-x 1 root root 3867592 May 4 11:13 goimports-linux-386
-rwxr-xr-x 1 root root 4992584 May 4 11:13 goimports-linux-amd64
-rwxr-xr-x 1 root root 3880544 May 4 11:13 goimports-linux-arm
-rwxr-xr-x 1 root root 4005376 May 4 11:13 goimports-windows-386.exe
-rwxr-xr-x 1 root root 5145600 May 4 11:13 goimports-windows-amd64.exe
This argument may at some point be merged into the import path itself, but for
now it exists as an independent build parameter.
### Branch selection
Similarly to `go get`, xgo also uses the `master` branch of a repository during
source code retrieval. To switch to a different branch before compilation pass
the desired branch name through the `--branch` argument.
$ xgo --pkg cmd/goimports --branch release-branch.go1.4 golang.org/x/tools
...
$ ls -al
-rwxr-xr-x 1 root root 3828396 May 4 11:33 goimports-darwin-386
-rwxr-xr-x 1 root root 4959376 May 4 11:33 goimports-darwin-amd64
-rwxr-xr-x 1 root root 3872736 May 4 11:33 goimports-linux-386
-rwxr-xr-x 1 root root 4997976 May 4 11:33 goimports-linux-amd64
-rwxr-xr-x 1 root root 3885552 May 4 11:33 goimports-linux-arm
-rwxr-xr-x 1 root root 4012032 May 4 11:33 goimports-windows-386.exe
-rwxr-xr-x 1 root root 5153280 May 4 11:33 goimports-windows-amd64.exe
### CGO dependencies
The main differentiator of xgo versus other cross compilers is support for basic
embedded C code and target-platform specific OS SDK availability. The current xgo
release introduces an experimental CGO *dependency* cross compilation, enabling
building Go programs that require external C libraries.
It is assumed that the dependent C library is `configure/make` based, was properly
prepared for cross compilation and is available as a tarball download (`.tar`,
`.tar.gz` or `.tar.bz2`).
Such dependencies can be added via the `--deps` CLI argument. A complex sample
for such a scenario is building the Ethereum CLI node, which has the GNU Multiple
Precision Arithmetic Library as it's dependency.
$ xgo --pkg=cmd/geth --branch=develop --deps=https://gmplib.org/download/gmp/gmp-6.0.0a.tar.bz2 github.com/ethereum/go-ethereum
...
$ ls -al
-rwxr-xr-x 1 root root 12605252 May 4 11:32 geth-darwin-386
-rwxr-xr-x 1 root root 14989860 May 4 11:32 geth-darwin-amd64
-rwxr-xr-x 1 root root 17137020 May 4 11:32 geth-linux-386
-rwxr-xr-x 1 root root 20212335 May 4 11:32 geth-linux-amd64
-rwxr-xr-x 1 root root 16475468 May 4 11:32 geth-linux-arm
-rwxr-xr-x 1 root root 16928256 May 4 11:32 geth-windows-386.exe
-rwxr-xr-x 1 root root 19760640 May 4 11:32 geth-windows-amd64.exe
Note, that since xgo needs to cross compile the dependencies for each platform
and architecture separately, build time can increase significantly.
| {
"content_hash": "b7557b156311bef2efbb402b98fc1ffe",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 131,
"avg_line_length": 47.56,
"alnum_prop": 0.7357923825543674,
"repo_name": "tsg/xgo",
"id": "8e828d4a5cc75e81eeea280687427ccf5f7d98c8",
"size": "8354",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "5203"
},
{
"name": "Shell",
"bytes": "8347"
}
],
"symlink_target": ""
} |
"use strict";
var includes = require("lodash.includes");
var actualAndExpectedMessageValues = require("../actual-and-expected-message-values");
module.exports = function(referee) {
referee.add("contains", {
assert: function(haystack, needle) {
return includes(haystack, needle);
},
assertMessage:
"${customMessage}Expected ${actual} to contain ${expected}",
refuteMessage:
"${customMessage}Expected ${actual} not to contain ${expected}",
expectation: "toContain",
values: actualAndExpectedMessageValues
});
};
| {
"content_hash": "08d26581b65e8ba2adc78457d93f5614",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 86,
"avg_line_length": 33.55555555555556,
"alnum_prop": 0.6390728476821192,
"repo_name": "busterjs/referee",
"id": "b5d67f8e9ce3d2e16f2f19f950a2faedc3feba31",
"size": "604",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/assertions/contains.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "108963"
}
],
"symlink_target": ""
} |
import scala.reflect.runtime.universe._
import scala.reflect.{ClassTag, classTag}
object Test extends App {
def weakTypeTagIsnotClassTag[T: WeakTypeTag] = {
println(classTag[T])
}
weakTypeTagIsnotClassTag[Int]
weakTypeTagIsnotClassTag[String]
weakTypeTagIsnotClassTag[Array[Int]]
} | {
"content_hash": "b9d119576b6ff05ed48a4da63a077d01",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 50,
"avg_line_length": 24.75,
"alnum_prop": 0.7777777777777778,
"repo_name": "shimib/scala",
"id": "de1f8657b6301497cd2fd15bfab57afa200bdbb7",
"size": "297",
"binary": false,
"copies": "5",
"ref": "refs/heads/2.12.x",
"path": "test/files/neg/interop_abstypetags_arenot_classtags.scala",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Awk",
"bytes": "1379"
},
{
"name": "Batchfile",
"bytes": "2970"
},
{
"name": "C",
"bytes": "141"
},
{
"name": "CSS",
"bytes": "57699"
},
{
"name": "HTML",
"bytes": "6291"
},
{
"name": "Java",
"bytes": "344757"
},
{
"name": "JavaScript",
"bytes": "54567"
},
{
"name": "Ruby",
"bytes": "142"
},
{
"name": "Scala",
"bytes": "15828866"
},
{
"name": "Shell",
"bytes": "46895"
}
],
"symlink_target": ""
} |
require 'optim'
function optim.downpour(opfunc, w, config, state)
local config = config or {}
local state = state or config
local lr = config.lr or 0 -- learning rate
local lrd = config.lrd or 0 -- learning rate decay
local l2wd = config.l2wd or 0
local pc = config.pclient or nil
local su = config.su or 0 -- sync updates (grad and param)
state.pversion = state.pversion or 0
state.dusync = state.dusync or 0
if lrd ~= 0 then
lr = lr / (1 + state.pversion*lrd)
end
local fx,dfdx = opfunc(w)
if l2wd ~= 0 then dfdx:add(l2wd, w) end
if pc and su>1 then
-- apply lr
dfdx:mul(-lr)
-- accumulate grad
if not config.dfdx then -- need one copy to accumulate
config.dfdx = torch.Tensor():typeAs(dfdx):resizeAs(dfdx):fill(0)
pc:reset(w,config.dfdx)
end
config.dfdx:add(dfdx)
-- send grads and get new param
if state.pversion%su==0 then
pc:async_send_grad()
pc:async_recv_param()
local synctime = sys.clock()
pc:wait()
state.dusync = state.dusync + sys.clock()-synctime
config.dfdx:fill(0)
else
w:add(dfdx) -- move locally
end
elseif pc and su==1 then
-- apply lr
dfdx:mul(-lr)
-- send
pc:async_send_grad()
pc:async_recv_param()
local synctime = sys.clock()
pc:wait()
state.dusync = state.dusync + sys.clock()-synctime
else
assert(false)
end
state.pversion = state.pversion + 1
return w,{fx}
end
| {
"content_hash": "49a6695bd8a4d75d1356d79260fe2be8",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 66,
"avg_line_length": 26.43859649122807,
"alnum_prop": 0.6138022561380225,
"repo_name": "sixin-zh/mpiT",
"id": "fcad54fe8bc3eb24b7354a4f6b3abf08e3ae1333",
"size": "1603",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "asyncsgd/optim-downpour.lua",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "129547"
},
{
"name": "C++",
"bytes": "13828"
},
{
"name": "CMake",
"bytes": "685"
},
{
"name": "Lua",
"bytes": "129567"
},
{
"name": "Python",
"bytes": "5997"
}
],
"symlink_target": ""
} |
#if defined(USE_TI_UIIOSCOVERFLOWVIEW) || defined(USE_TI_UICOVERFLOWVIEW)
#import "AFUIImageReflection.h"
// SAUS modification note:
// using categories with static libraries don't seem to work
// right on device with iphone - probably a symbol issue
// turn this into a static function (from what was a category to UIImage
// originally)
UIImage* AddImageReflection(UIImage *image, CGFloat reflectionFraction)
{
int reflectionHeight = ceilf(image.size.height * reflectionFraction);
// create a 2 bit CGImage containing a gradient that will be used for masking the
// main view content to create the 'fade' of the reflection. The CGImageCreateWithMask
// function will stretch the bitmap image as required, so we can create a 1 pixel wide gradient
CGImageRef gradientMaskImage = NULL;
// gradient is always black-white and the mask must be in the gray colorspace
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
// create the bitmap context
CGContextRef gradientBitmapContext = CGBitmapContextCreate(nil, 1, reflectionHeight,
8, 0, colorSpace, kCGImageAlphaNone);
// define the start and end grayscale values (with the alpha, even though
// our bitmap context doesn't support alpha the gradient requires it)
CGFloat colors[] = {0.0, 1.0, 1.0, 1.0};
// create the CGGradient and then release the gray color space
CGGradientRef grayScaleGradient = CGGradientCreateWithColorComponents(colorSpace, colors, NULL, 2);
CGColorSpaceRelease(colorSpace);
// create the start and end points for the gradient vector (straight down)
CGPoint gradientStartPoint = CGPointMake(0, reflectionHeight);
CGPoint gradientEndPoint = CGPointZero;
// draw the gradient into the gray bitmap context
CGContextDrawLinearGradient(gradientBitmapContext, grayScaleGradient, gradientStartPoint,
gradientEndPoint, kCGGradientDrawsAfterEndLocation);
CGGradientRelease(grayScaleGradient);
// add a black fill with 50% opacity
CGContextSetGrayFillColor(gradientBitmapContext, 0.0, 0.5);
CGContextFillRect(gradientBitmapContext, CGRectMake(0, 0, 1, reflectionHeight));
// convert the context into a CGImageRef and release the context
gradientMaskImage = CGBitmapContextCreateImage(gradientBitmapContext);
CGContextRelease(gradientBitmapContext);
// create an image by masking the bitmap of the mainView content with the gradient view
// then release the pre-masked content bitmap and the gradient bitmap
if((image.CGImage == NULL) || (gradientMaskImage == NULL))
{
CGImageRelease(gradientMaskImage);
return nil;
}
CGImageRef reflectionImage = CGImageCreateWithMask(image.CGImage, gradientMaskImage);
CGImageRelease(gradientMaskImage);
CGSize size = CGSizeMake(image.size.width, image.size.height + reflectionHeight);
UIGraphicsBeginImageContextWithOptions(size, NO, image.scale);
[image drawAtPoint:CGPointZero];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawImage(context, CGRectMake(0, image.size.height, image.size.width, reflectionHeight), reflectionImage);
UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRelease(reflectionImage);
return result;
}
#endif | {
"content_hash": "61d6292a2e0d3b6431ed5d7fba17a41c",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 116,
"avg_line_length": 42.848101265822784,
"alnum_prop": 0.7462333825701625,
"repo_name": "AcumID/SAUS",
"id": "d494c25d12e0f0fa9ad047d01f7f92982a74a035",
"size": "4535",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build/iphone/Classes/AFOpenFlow/AFUIImageReflection.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "144385"
},
{
"name": "C++",
"bytes": "52728"
},
{
"name": "JavaScript",
"bytes": "3505"
},
{
"name": "Matlab",
"bytes": "1939"
},
{
"name": "Objective-C",
"bytes": "3304269"
},
{
"name": "Shell",
"bytes": "153"
}
],
"symlink_target": ""
} |
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
#import "SCCredentialsView.h"
@protocol SCLoginViewProtocol;
@interface SCLoginView : UIScrollView
@property (nonatomic, weak) id<SCLoginViewProtocol> loginDelegate;
@property (nonatomic, strong) SCCredentialsView *credentialsView;
- (void)removeAllCookies;
- (void)login:(id)sender;
@end
@protocol SCLoginViewProtocol <NSObject>
@optional
- (void)loginView:(SCLoginView *)aLoginView didFailWithError:(NSError *)anError;
@end
| {
"content_hash": "4fd6e9458c10ae8b4c9a2215b7fef9e6",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 80,
"avg_line_length": 23,
"alnum_prop": 0.7846790890269151,
"repo_name": "pwnified/CocoaSoundCloudUI",
"id": "ce8e0e66e60123554700e12df3880428199cb85d",
"size": "1187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Sources/SoundCloudUI/SCLoginView.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "286140"
},
{
"name": "Ruby",
"bytes": "1277"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_17a.html">Class Test_AbaRouteValidator_17a</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_36740_bad
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_17a.html?line=39781#src-39781" >testAbaNumberCheck_36740_bad</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:46:16
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_36740_bad</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/exceptions/AbaRouteValidationException.html?id=41292#AbaRouteValidationException" title="AbaRouteValidationException" name="sl-43">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/ErrorCodes.html?id=41292#ErrorCodes" title="ErrorCodes" name="sl-42">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=41292#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.29411766</span>29.4%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="29.4% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:29.4%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html> | {
"content_hash": "a456e5c64bc4519f24181662f5535a7a",
"timestamp": "",
"source": "github",
"line_count": 235,
"max_line_length": 359,
"avg_line_length": 46.765957446808514,
"alnum_prop": 0.5304822565969063,
"repo_name": "dcarda/aba.route.validator",
"id": "e5bd7bfc8e5bb25ffac2f81ddceba1db2a30a963",
"size": "10990",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_17a_testAbaNumberCheck_36740_bad_vv0.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "18715254"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<meta charset=utf-8>
<title>invalid src: path-bare-percent-sign</title>
<audio src="http://example.com/foo%"></audio>
| {
"content_hash": "26dcee3049e8af7a8bbb5361208c4932",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 50,
"avg_line_length": 33.5,
"alnum_prop": 0.7089552238805971,
"repo_name": "youtube/cobalt",
"id": "2ee3f09377eed18db81536d1940e633e3b8bb16d",
"size": "134",
"binary": false,
"copies": "254",
"ref": "refs/heads/master",
"path": "third_party/web_platform_tests/conformance-checkers/html/elements/audio/src/path-bare-percent-sign-novalid.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package net.bytebuddy.implementation.bind.annotation;
import net.bytebuddy.build.HashCodeAndEqualsPlugin;
import net.bytebuddy.description.annotation.AnnotationDescription;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.method.ParameterDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.implementation.MethodAccessorFactory;
import net.bytebuddy.implementation.bind.MethodDelegationBinder;
import net.bytebuddy.implementation.bytecode.StackManipulation;
import net.bytebuddy.implementation.bytecode.assign.Assigner;
import net.bytebuddy.implementation.bytecode.constant.MethodConstant;
import net.bytebuddy.implementation.bytecode.constant.NullConstant;
import net.bytebuddy.implementation.bytecode.member.FieldAccess;
import org.objectweb.asm.MethodVisitor;
import java.lang.annotation.*;
import java.lang.reflect.Method;
/**
* A parameter with this annotation is assigned an instance of {@link Method} which invokes the super implementation of this method.
* If such a method is not available, this annotation causes that this delegation target cannot be bound unless {@link SuperMethod#nullIfImpossible()}
* is set to {@code true}. The method is declared as {@code public} and is invokable unless the instrumented type itself is not visible. Note that
* requesting such a method exposes the super method to reflection.
*
* @see net.bytebuddy.implementation.MethodDelegation
* @see net.bytebuddy.implementation.bind.annotation.TargetMethodAnnotationDrivenBinder
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface SuperMethod {
/**
* Indicates if the instance assigned to this parameter should be stored in a static field for reuse.
*
* @return {@code true} if this method instance should be cached.
*/
boolean cached() default true;
/**
* Indicates if the instance assigned to this parameter should be looked up using an {@link java.security.AccessController}.
*
* @return {@code true} if this method should be looked up using an {@link java.security.AccessController}.
*/
boolean privileged() default false;
/**
* Indicates that the assigned method should attempt the invocation of an unambiguous default method if no super method is available.
*
* @return {@code true} if a default method should be invoked if it is not ambiguous and no super class method is available.
*/
boolean fallbackToDefault() default true;
/**
* Indicates that {@code null} should be assigned to this parameter if no super method is invokable.
*
* @return {@code true} if {@code null} should be assigned if no valid method can be assigned.
*/
boolean nullIfImpossible() default false;
/**
* A binder for the {@link SuperMethod} annotation.
*/
enum Binder implements TargetMethodAnnotationDrivenBinder.ParameterBinder<SuperMethod> {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Class<SuperMethod> getHandledType() {
return SuperMethod.class;
}
/**
* {@inheritDoc}
*/
public MethodDelegationBinder.ParameterBinding<?> bind(final AnnotationDescription.Loadable<SuperMethod> annotation,
MethodDescription source,
ParameterDescription target,
Implementation.Target implementationTarget,
Assigner assigner,
Assigner.Typing typing) {
if (!target.getType().asErasure().isAssignableFrom(Method.class)) {
throw new IllegalStateException("Cannot assign Method type to " + target);
} else if (source.isMethod()) {
Implementation.SpecialMethodInvocation specialMethodInvocation = annotation.loadSilent().fallbackToDefault()
? implementationTarget.invokeDominant(source.asSignatureToken())
: implementationTarget.invokeSuper(source.asSignatureToken());
if (specialMethodInvocation.isValid()) {
return new MethodDelegationBinder.ParameterBinding.Anonymous(new DelegationMethod(specialMethodInvocation,
annotation.loadSilent().cached(),
annotation.loadSilent().privileged()));
} else if (annotation.loadSilent().nullIfImpossible()) {
return new MethodDelegationBinder.ParameterBinding.Anonymous(NullConstant.INSTANCE);
} else {
return MethodDelegationBinder.ParameterBinding.Illegal.INSTANCE;
}
} else if (annotation.loadSilent().nullIfImpossible()) {
return new MethodDelegationBinder.ParameterBinding.Anonymous(NullConstant.INSTANCE);
} else {
return MethodDelegationBinder.ParameterBinding.Illegal.INSTANCE;
}
}
/**
* Loads the delegation method constant onto the stack.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class DelegationMethod implements StackManipulation {
/**
* The special method invocation that represents the super method call.
*/
private final Implementation.SpecialMethodInvocation specialMethodInvocation;
/**
* {@code true} if the method constant should be cached.
*/
private final boolean cached;
/**
* {@code true} if this method should be looked up using an {@link java.security.AccessController}.
*/
private final boolean privileged;
/**
* Creates a new delegation method.
*
* @param specialMethodInvocation The special method invocation that represents the super method call.
* @param cached {@code true} if the method constant should be cached.
* @param privileged {@code true} if this method should be looked up using an {@link java.security.AccessController}.
*/
protected DelegationMethod(Implementation.SpecialMethodInvocation specialMethodInvocation, boolean cached, boolean privileged) {
this.specialMethodInvocation = specialMethodInvocation;
this.cached = cached;
this.privileged = privileged;
}
/**
* {@inheritDoc}
*/
public boolean isValid() {
return specialMethodInvocation.isValid();
}
/**
* {@inheritDoc}
*/
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
StackManipulation methodConstant = privileged
? MethodConstant.ofPrivileged(implementationContext.registerAccessorFor(specialMethodInvocation, MethodAccessorFactory.AccessType.PUBLIC))
: MethodConstant.of(implementationContext.registerAccessorFor(specialMethodInvocation, MethodAccessorFactory.AccessType.PUBLIC));
return (cached
? FieldAccess.forField(implementationContext.cache(methodConstant, TypeDescription.ForLoadedType.of(Method.class))).read()
: methodConstant).apply(methodVisitor, implementationContext);
}
}
}
}
| {
"content_hash": "22867a97cbd814c8cd2755bcfe7c42c8",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 162,
"avg_line_length": 47.696969696969695,
"alnum_prop": 0.644853875476493,
"repo_name": "DALDEI/byte-buddy",
"id": "b411f45033cc3b2ad7e2339751321b9bbdfe4a56",
"size": "7870",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "byte-buddy-dep/src/main/java/net/bytebuddy/implementation/bind/annotation/SuperMethod.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "10488326"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Globalization;
using System.Web.Security;
namespace CDDemo.Models
{
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}
public class RegisterExternalLoginModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
public string ExternalLoginData { get; set; }
}
public class LocalPasswordModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class LoginModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class ExternalLogin
{
public string Provider { get; set; }
public string ProviderDisplayName { get; set; }
public string ProviderUserId { get; set; }
}
}
| {
"content_hash": "9485beca47d571649d257826d3cdf3df",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 110,
"avg_line_length": 29.072164948453608,
"alnum_prop": 0.6127659574468085,
"repo_name": "cdman/continuous-integration-demo",
"id": "35d2752bd7c8d5effda7e8e77afd27967f51f0de",
"size": "2822",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CDDemo/Models/AccountModels.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "97"
},
{
"name": "C#",
"bytes": "27926"
},
{
"name": "CSS",
"bytes": "13188"
},
{
"name": "JavaScript",
"bytes": "377781"
},
{
"name": "Shell",
"bytes": "207"
}
],
"symlink_target": ""
} |
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SliderComponent } from './slider.component';
@NgModule({
declarations: [
SliderComponent
],
imports: [
CommonModule
],
exports:[
SliderComponent
]
})
export class SliderModule { }
| {
"content_hash": "28d29260ecbf0f86640f27c146d9dfeb",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 53,
"avg_line_length": 17,
"alnum_prop": 0.6633986928104575,
"repo_name": "devnetgomez/devnetgomez.github.io",
"id": "2813ede2bee3c1138d6e49c0cc776f3f6875e3d7",
"size": "306",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/shared/components/slider/slider.module.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "545524"
},
{
"name": "HTML",
"bytes": "46088"
},
{
"name": "JavaScript",
"bytes": "75777"
},
{
"name": "Ruby",
"bytes": "2884"
}
],
"symlink_target": ""
} |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import pino from 'pino';
import SonicBoom from 'sonic-boom';
type Destination = NodeJS.WritableStream | SonicBoom;
type LogEntry = {[key: string]: unknown};
/**
* A logger standardized logger for Google Cloud Functions (and Cloud Run).
* This logger outputs structured (JSON) logs formatted so that Google
* Cloud Logging can efficiently search and filter entries. `console.log()`
* entries will appear in Cloud Logging, but will lack developer specified
* metadata (bindings) and granular severity levels.
*/
export class GCFLogger {
private destination!: Destination;
private pino!: pino.Logger;
constructor(customDestination?: Destination) {
this.initPinoLogger(customDestination);
this.trace = this.trace.bind(this);
this.debug = this.debug.bind(this);
this.info = this.info.bind(this);
this.warn = this.warn.bind(this);
this.metric = this.metric.bind(this);
this.error = this.error.bind(this);
this.child = this.child.bind(this);
}
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Log at the trace level
*/
public trace(msg: string, ...args: any[]): void;
public trace(obj: object, msg?: string, ...args: any[]): void;
public trace(
objOrMsg: object | string,
addMsg?: string,
...args: any[]
): void {
this.log('trace', objOrMsg, addMsg, ...args);
}
/**
* Log at the debug level
*/
public debug(msg: string, ...args: any[]): void;
public debug(obj: object, msg?: string, ...args: any[]): void;
public debug(
objOrMsg: object | string,
addMsg?: string,
...args: any[]
): void {
this.log('debug', objOrMsg, addMsg, ...args);
}
/**
* Log at the info level
*/
public info(msg: string, ...args: any[]): void;
public info(obj: object, msg?: string, ...args: any[]): void;
public info(
objOrMsg: object | string,
addMsg?: string,
...args: any[]
): void {
this.log('info', objOrMsg, addMsg, ...args);
}
/**
* Log at the warn level
*/
public warn(msg: string, ...args: any[]): void;
public warn(obj: object, msg?: string, ...args: any[]): void;
public warn(
objOrMsg: object | string,
addMsg?: string,
...args: any[]
): void {
this.log('warn', objOrMsg, addMsg, ...args);
}
/**
* Log at the error level
*/
public error(msg: string, ...args: any[]): void;
public error(obj: object, msg?: string, ...args: any[]): void;
public error(
objOrMsg: object | string,
addMsg?: string,
...args: any[]
): void {
this.log('error', objOrMsg, addMsg, ...args);
}
/**
* Log at the metric level
*/
public metric(msg: string, entry: LogEntry | string): void;
public metric(msg: string, ...args: any[]): void;
public metric(obj: object, msg?: string, ...args: any[]): void;
public metric(
objOrMsg: object | string,
addMsg?: LogEntry | string,
...args: any[]
): void {
let payload: LogEntry = {
count: 1,
event: 'unknown',
};
if (typeof objOrMsg === 'string') {
payload.event = objOrMsg;
} else {
payload = {...payload, ...objOrMsg};
}
if (typeof addMsg === 'object') {
payload = {...payload, ...addMsg};
addMsg = undefined;
}
this.log('metric', {...payload, type: 'metric'}, addMsg as string, ...args);
}
private log(
level: string,
objOrMsg: object | string,
addMsg?: string,
...args: any[]
): void {
if (typeof objOrMsg === 'object') {
this.pino[level](objOrMsg, addMsg, ...args);
} else {
this.pino[level](objOrMsg, ...args);
}
}
/* eslint-enable @typescript-eslint/no-explicit-any */
/**
* Synchronously flush the buffer for this logger.
* NOTE: Only supported for SonicBoom destinations
*/
public flushSync() {
if (this.destination instanceof SonicBoom) {
this.destination.flushSync();
}
}
/**
* Adds static properties to all logs
* @param properties static properties to bind
*/
public addBindings(properties: object) {
this.pino = this.pino.child(properties);
}
/**
* Return a new child logger with attached static properties to all logs
* @param properties static properties to bind
*/
public child(properties: object): GCFLogger {
const child = new GCFLogger(this.destination);
child.addBindings({
...this.getBindings(),
...properties,
});
return child;
}
/**
* Return the current bindings
*/
public getBindings(): object {
return this.pino.bindings();
}
/**
* Remove all current property bindings
*/
public resetBindings() {
// Pino provides no way to remove bindings
// so we have to throw away the old logger
this.initPinoLogger(this.destination);
}
private initPinoLogger(dest?: Destination) {
const defaultOptions = this.getPinoConfig();
this.destination = dest || pino.destination({sync: true});
this.pino = pino(defaultOptions, this.destination);
}
private getPinoConfig(): pino.LoggerOptions {
return {
formatters: {
level: pinoLevelToCloudLoggingSeverity,
},
customLevels: {
metric: 30,
},
base: null,
messageKey: 'message',
timestamp: false,
level: 'trace',
};
}
}
/**
* Maps Pino's number-based levels to Google Cloud Logging's string-based severity.
* This allows Pino logs to show up with the correct severity in Logs Viewer.
* Also preserves the original Pino level
* @param label the label used by Pino for the level property
* @param level the numbered level from Pino
*/
function pinoLevelToCloudLoggingSeverity(
label: string,
level: number
): {[label: string]: number | string} {
const severityMap: {[level: number]: string} = {
10: 'DEBUG',
20: 'DEBUG',
30: 'INFO',
40: 'WARNING',
50: 'ERROR',
};
const UNKNOWN_SEVERITY = 'DEFAULT';
return {severity: severityMap[level] || UNKNOWN_SEVERITY, level: level};
}
/**
* Build a child logger and attach bindings (attributes). This function is used
* for mocking logging for tests.
*
* @param {GCFLogger} logger The parent logger
* @param {object} bindings Data to add to each log entry
* @returns {GCFLogger}
*/
export function buildRequestLogger(
logger: GCFLogger,
bindings: object
): GCFLogger {
return logger.child(bindings);
}
| {
"content_hash": "cd874d88c963bae36b12f8f1c52ac8ad",
"timestamp": "",
"source": "github",
"line_count": 256,
"max_line_length": 83,
"avg_line_length": 27.140625,
"alnum_prop": 0.6375935521013241,
"repo_name": "googleapis/repo-automation-bots",
"id": "94cc836b4ec541c7ec4c1b091abe3764eaef64f3",
"size": "6948",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "packages/gcf-utils/src/logging/gcf-logger.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "990"
},
{
"name": "Dockerfile",
"bytes": "41290"
},
{
"name": "Go",
"bytes": "24408"
},
{
"name": "Handlebars",
"bytes": "9441"
},
{
"name": "JavaScript",
"bytes": "165425"
},
{
"name": "Makefile",
"bytes": "2344"
},
{
"name": "PowerShell",
"bytes": "18372"
},
{
"name": "Python",
"bytes": "1043"
},
{
"name": "Shell",
"bytes": "75604"
},
{
"name": "TypeScript",
"bytes": "2332680"
}
],
"symlink_target": ""
} |
layout: post
title: Sugar Pie Honeyz 10 - Scene 3
titleinfo: pornvd
desc: Watch Sugar Pie Honeyz 10 - Scene 3. Pornhub is the ultimate xxx porn and sex site.
---
<iframe src="http://www.pornhub.com/embed/462360805" frameborder="0" width="630" height="338" scrolling="no"></iframe>
<h2>Sugar Pie Honeyz 10 - Scene 3</h2>
<h3>Watch Sugar Pie Honeyz 10 - Scene 3. Pornhub is the ultimate xxx porn and sex site.</h3>
| {
"content_hash": "ee2720a1b0b9f4b3ce93a50a10e9a6eb",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 118,
"avg_line_length": 43,
"alnum_prop": 0.6976744186046512,
"repo_name": "pornvd/pornvd.github.io",
"id": "489b4524253f15924aff1c47dd8ef16f47b302e7",
"size": "434",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2016-03-06-Sugar-Pie-Honeyz-10---Scene-3.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "18073"
},
{
"name": "HTML",
"bytes": "10043"
},
{
"name": "JavaScript",
"bytes": "1581"
},
{
"name": "Python",
"bytes": "2932"
},
{
"name": "Ruby",
"bytes": "3287"
},
{
"name": "Shell",
"bytes": "310"
}
],
"symlink_target": ""
} |
package backend.passManaging;
import backend.pass.AnalysisResolver;
import backend.pass.Pass;
import backend.value.Function;
import backend.value.Module;
/**
* FunctionPassManager manages FunctionPasses and BasicBlockPassManagers.
*
* @author Jianping Zeng
* @version 0.4
*/
public class FunctionPassManager implements PassManagerBase {
private FunctionPassManagerImpl fpm;
private Module m;
public FunctionPassManager(Module m) {
fpm = new FunctionPassManagerImpl(0);
fpm.setTopLevelManager(fpm);
this.m = m;
AnalysisResolver resolver = new AnalysisResolver(fpm);
fpm.setAnalysisResolver(resolver);
}
/**
* Execute all of the passes scheduled for execution. Keep
* track of whether any of the passes modifies the function, and if
* so, return true.
*
* @param f
* @return
*/
public boolean run(Function f) {
return fpm.run(f);
}
/**
* Add a pass to the queue of passes to run.
*
* @param p
*/
@Override
public void add(Pass p) {
fpm.add(p);
}
/**
* Run all the initialization works for those passes.
*
* @return
*/
public boolean doInitialization() {
return fpm.doInitialization(m);
}
/**
* * Run all the finalization works for those passes.
*
* @return
*/
public boolean doFinalization() {
return fpm.doFinalization(m);
}
}
| {
"content_hash": "ab2022dd0964731e925966f4598fa99f",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 73,
"avg_line_length": 20.71212121212121,
"alnum_prop": 0.6744696415508412,
"repo_name": "JianpingZeng/xcc",
"id": "b9c1eb87fa81efa57430a7ab6cf3400944c1ba53",
"size": "1367",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xcc/java/backend/passManaging/FunctionPassManager.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?php
/**
* View: Month View Mobile Day
*
* Override this template in your own theme by creating a file at:
* [your-theme]/tribe/events/v2/month/mobile-events/mobile-day.php
*
* See more documentation about our views templating system.
*
* @link {INSERT_ARTCILE_LINK_HERE}
*
* @version 4.9.10
*
* @var string $today_date Today's date in the `Y-m-d` format.
* @var string $day_date The current day date, in the `Y-m-d` format.
* @var array $day The current day data.{
* @type string $date The day date, in the `Y-m-d` format.
* @type bool $is_start_of_week Whether the current day is the first day of the week or not.
* @type string $year_number The day year number, e.g. `2019`.
* @type string $month_number The day year number, e.g. `6` for June.
* @type string $day_number The day number in the month, e.g. `11` for June 11th.
* @type string $day_number_no_pad The day number in the month without leading 0, e.g. `8` for June 8th.
* @type string $day_url The day url, e.g. `http://yoursite.com/events/2019-06-11/`.
* @type int $found_events The total number of events in the day including the ones not fetched due to the per
* page limit, including the multi-day ones.
* @type int $more_events The number of events not showing in the day.
* @type array $events The non multi-day events on this day. The format of each event is the one returned by
* the `tribe_get_event` function.
* @type array $featured_events The featured events on this day. The format of each event is the one returned
* by the `tribe_get_event` function.
* @type array $multiday_events The stack of multi-day events on this day. The stack is a mix of event post
* objects, the format is the one returned from the `tribe_get_event` function, and
* spacers. Spacers are falsy values indicating an empty space in the multi-day stack for
* the day
* }
*/
$events = $day['events'];
if ( ! empty( $day['multiday_events'] ) ) {
$events = array_filter( array_merge( $day['multiday_events'], $events ) );
}
$mobile_day_id = 'tribe-events-calendar-mobile-day-' . $day['year_number'] . '-' . $day['month_number'] . '-' . $day['day_number'];
$classes = [ 'tribe-events-calendar-month-mobile-events__mobile-day' ];
if ( $today_date === $day_date ) {
$classes[] = 'tribe-events-calendar-month-mobile-events__mobile-day--show';
}
?>
<div <?php tribe_classes( $classes ); ?> id="<?php echo sanitize_html_class( $mobile_day_id ); ?>">
<?php $this->template( 'month/mobile-events/mobile-day/day-marker', [ 'day_date' => $day_date ] ); ?>
<?php foreach( $events as $event ) : ?>
<?php $this->setup_postdata( $event ); ?>
<?php $this->template( 'month/mobile-events/mobile-day/mobile-event', [ 'event' => $event ] ); ?>
<?php endforeach; ?>
<?php $this->template( 'month/mobile-events/mobile-day/more-events', [ 'more_events' => $day['more_events'], 'more_url' => $day['day_url'] ] ); ?>
</div>
| {
"content_hash": "dd478d0873c4573ed4a61a4a5055a290",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 147,
"avg_line_length": 51.16129032258065,
"alnum_prop": 0.6156998738965952,
"repo_name": "attacbe/ab2",
"id": "ea67f3d626e856e2d50ebcc1d93ab1c32b56622f",
"size": "3172",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tribe-events/month/mobile-events/mobile-day.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "178374"
},
{
"name": "Hack",
"bytes": "1845"
},
{
"name": "JavaScript",
"bytes": "7855"
},
{
"name": "PHP",
"bytes": "189324"
},
{
"name": "SCSS",
"bytes": "13479"
}
],
"symlink_target": ""
} |
<?php
use yii\helpers\Html;
use kartik\widgets\ActiveForm;
use kartik\widgets\Select2;
use yii\helpers\ArrayHelper;
/* @var $this yii\web\View */
/* @var $model backend\models\TrainingClass */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="training-class-form">
<div class="panel panel-default">
<div class="panel-heading">
<strong>Update Cost Trainer</strong>
</div>
<div style="margin:10px">
<?php $form = ActiveForm::begin([
'action' => ['cost-trainer',
'id'=>$model->trainingSchedule->tb_training_class_subject_id,
'tb_trainer_id'=>$model->tb_trainer_id,
],
'enableAjaxValidation' => false,
'enableClientValidation' => false,
'options'=>[
'onsubmit'=>"
$.ajax({
url: $(this).attr('action'),
type: 'post',
data: $(this).serialize(),
success: function(data) {
$('#modal-heart').modal('hide');
$.pjax.reload({
url: '".\yii\helpers\Url::to(['trainer','id'=>$model->trainingSchedule->tb_training_class_subject_id])."',
container: '#pjax-gridview-trainer',
timeout: 1,
});
},
error: function( jqXHR, textStatus, errorThrown ) {
alert(jqXHR.responseText);
}
});
return false;
",
],
]); ?>
<?= $form->errorSummary($model) ?>
<?php
echo $form->field($model, 'cost');//->label('Trainer');
?>
<hr>
Ket: <br>
Hanya untuk praktisi
<hr>
<?= Html::submitButton(
'<span class="fa fa-fw fa-save"></span> Update',
['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
| {
"content_hash": "5bdeec5344a6fd39f480c9b346732d6d",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 113,
"avg_line_length": 24,
"alnum_prop": 0.5897435897435898,
"repo_name": "hscstudio/syawwal",
"id": "1d1ce55a95640f06e76803b0bc237c5254fb757e",
"size": "1560",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "backend/modules/pusdiklat/execution/views/training-class-subject/costTrainer.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "2728"
},
{
"name": "PHP",
"bytes": "3874212"
},
{
"name": "Shell",
"bytes": "5176"
}
],
"symlink_target": ""
} |
<?php
require_once 'PHPUnit/Framework.php';
require_once 'PHPUnit/Util/Filter.php';
require_once 'PHPUnit/Util/Printer.php';
require_once 'PHPUnit/Util/Test.php';
require_once 'PHPUnit/Util/Timer.php';
PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT');
/**
* Prints the result of a TextUI TestRunner run.
*
* @category Testing
* @package PHPUnit
* @author Sebastian Bergmann <[email protected]>
* @copyright 2002-2009 Sebastian Bergmann <[email protected]>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version Release: 3.4.0RC3
* @link http://www.phpunit.de/
* @since Class available since Release 2.0.0
*/
class PHPUnit_TextUI_ResultPrinter extends PHPUnit_Util_Printer implements PHPUnit_Framework_TestListener
{
const EVENT_TEST_START = 0;
const EVENT_TEST_END = 1;
const EVENT_TESTSUITE_START = 2;
const EVENT_TESTSUITE_END = 3;
/**
* @var integer
*/
protected $column = 0;
/**
* @var integer
*/
protected $indent = 0;
/**
* @var integer
*/
protected $lastEvent = -1;
/**
* @var boolean
*/
protected $lastTestFailed = FALSE;
/**
* @var integer
*/
protected $numAssertions = 0;
/**
* @var integer
*/
protected $numTests = -1;
/**
* @var integer
*/
protected $numTestsRun = 0;
/**
* @var integer
*/
protected $numTestsWidth;
/**
* @var boolean
*/
protected $colors = FALSE;
/**
* @var boolean
*/
protected $debug = FALSE;
/**
* @var boolean
*/
protected $verbose = FALSE;
/**
* Constructor.
*
* @param mixed $out
* @param boolean $verbose
* @param boolean $colors
* @param boolean $debug
* @throws InvalidArgumentException
* @since Method available since Release 3.0.0
*/
public function __construct($out = NULL, $verbose = FALSE, $colors = FALSE, $debug = FALSE)
{
parent::__construct($out);
if (is_bool($verbose)) {
$this->verbose = $verbose;
} else {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'boolean');
}
if (is_bool($colors)) {
$this->colors = $colors;
} else {
throw PHPUnit_Util_InvalidArgumentHelper::factory(3, 'boolean');
}
if (is_bool($debug)) {
$this->debug = $debug;
} else {
throw PHPUnit_Util_InvalidArgumentHelper::factory(4, 'boolean');
}
}
/**
* @param PHPUnit_Framework_TestResult $result
*/
public function printResult(PHPUnit_Framework_TestResult $result)
{
$this->printHeader($result->time());
if ($result->errorCount() > 0) {
$this->printErrors($result);
}
if ($result->failureCount() > 0) {
if ($result->errorCount() > 0) {
print "\n--\n\n";
}
$this->printFailures($result);
}
if ($this->verbose) {
if ($result->notImplementedCount() > 0) {
if ($result->failureCount() > 0) {
print "\n--\n\n";
}
$this->printIncompletes($result);
}
if ($result->skippedCount() > 0) {
if ($result->notImplementedCount() > 0) {
print "\n--\n\n";
}
$this->printSkipped($result);
}
}
$this->printFooter($result);
}
/**
* @param array $defects
* @param integer $count
* @param string $type
*/
protected function printDefects(array $defects, $count, $type)
{
static $called = FALSE;
if ($count == 0) {
return;
}
$this->write(
sprintf(
"%sThere %s %d %s%s:\n",
$called ? "\n" : '',
($count == 1) ? 'was' : 'were',
$count,
$type,
($count == 1) ? '' : 's'
)
);
$i = 1;
foreach ($defects as $defect) {
$this->printDefect($defect, $i++);
}
$called = TRUE;
}
/**
* @param PHPUnit_Framework_TestFailure $defect
* @param integer $count
*/
protected function printDefect(PHPUnit_Framework_TestFailure $defect, $count)
{
$this->printDefectHeader($defect, $count);
$this->printDefectTrace($defect);
}
/**
* @param PHPUnit_Framework_TestFailure $defect
* @param integer $count
*/
protected function printDefectHeader(PHPUnit_Framework_TestFailure $defect, $count)
{
$failedTest = $defect->failedTest();
if ($failedTest instanceof PHPUnit_Framework_SelfDescribing) {
$testName = $failedTest->toString();
} else {
$testName = get_class($failedTest);
}
$this->write(
sprintf(
"\n%d) %s\n",
$count,
$testName
)
);
}
/**
* @param PHPUnit_Framework_TestFailure $defect
*/
protected function printDefectTrace(PHPUnit_Framework_TestFailure $defect)
{
$this->write(
$defect->getExceptionAsString() . "\n" .
PHPUnit_Util_Filter::getFilteredStacktrace(
$defect->thrownException(),
FALSE
)
);
}
/**
* @param PHPUnit_Framework_TestResult $result
*/
protected function printErrors(PHPUnit_Framework_TestResult $result)
{
$this->printDefects($result->errors(), $result->errorCount(), 'error');
}
/**
* @param PHPUnit_Framework_TestResult $result
*/
protected function printFailures(PHPUnit_Framework_TestResult $result)
{
$this->printDefects(
$result->failures(),
$result->failureCount(),
'failure'
);
}
/**
* @param PHPUnit_Framework_TestResult $result
*/
protected function printIncompletes(PHPUnit_Framework_TestResult $result)
{
$this->printDefects(
$result->notImplemented(),
$result->notImplementedCount(),
'incomplete test'
);
}
/**
* @param PHPUnit_Framework_TestResult $result
* @since Method available since Release 3.0.0
*/
protected function printSkipped(PHPUnit_Framework_TestResult $result)
{
$this->printDefects(
$result->skipped(),
$result->skippedCount(),
'skipped test'
);
}
/**
* @param float $timeElapsed
*/
protected function printHeader($timeElapsed)
{
if (isset($_SERVER['REQUEST_TIME'])) {
$timeElapsed = PHPUnit_Util_Timer::secondsToTimeString(
time() - $_SERVER['REQUEST_TIME']
);
} else {
$timeElapsed = PHPUnit_Util_Timer::secondsToTimeString(
$timeElapsed
);
}
$this->write(
sprintf(
"%sTime: %s\n\n",
$this->verbose ? "\n" : "\n\n",
$timeElapsed
)
);
}
/**
* @param PHPUnit_Framework_TestResult $result
*/
protected function printFooter(PHPUnit_Framework_TestResult $result)
{
if ($result->wasSuccessful() &&
$result->allCompletlyImplemented() &&
$result->noneSkipped()) {
if ($this->colors) {
$this->write("\x1b[30;42m\x1b[2K");
}
$this->write(
sprintf(
"OK (%d test%s, %d assertion%s)\n",
count($result),
(count($result) == 1) ? '' : 's',
$this->numAssertions,
($this->numAssertions == 1) ? '' : 's'
)
);
if ($this->colors) {
$this->write("\x1b[0m\x1b[2K");
}
}
else if ((!$result->allCompletlyImplemented() ||
!$result->noneSkipped())&&
$result->wasSuccessful()) {
if ($this->colors) {
$this->write(
"\x1b[30;43m\x1b[2KOK, but incomplete or skipped tests!\n" .
"\x1b[0m\x1b[30;43m\x1b[2K"
);
} else {
$this->write("OK, but incomplete or skipped tests!\n");
}
$this->write(
sprintf(
"Tests: %d, Assertions: %d%s%s.\n",
count($result),
$this->numAssertions,
$this->getCountString(
$result->notImplementedCount(), 'Incomplete'
),
$this->getCountString(
$result->skippedCount(), 'Skipped'
)
)
);
if ($this->colors) {
$this->write("\x1b[0m\x1b[2K");
}
}
else {
$this->write("\n");
if ($this->colors) {
$this->write(
"\x1b[37;41m\x1b[2KFAILURES!\n\x1b[0m\x1b[37;41m\x1b[2K"
);
} else {
$this->write("FAILURES!\n");
}
$this->write(
sprintf(
"Tests: %d, Assertions: %s%s%s%s%s.\n",
count($result),
$this->numAssertions,
$this->getCountString($result->failureCount(), 'Failures'),
$this->getCountString($result->errorCount(), 'Errors'),
$this->getCountString(
$result->notImplementedCount(), 'Incomplete'
),
$this->getCountString($result->skippedCount(), 'Skipped')
)
);
if ($this->colors) {
$this->write("\x1b[0m\x1b[2K");
}
}
}
/**
* @param integer $count
* @param string $name
* @return string
* @since Method available since Release 3.0.0
*/
protected function getCountString($count, $name)
{
$string = '';
if ($count > 0) {
$string = sprintf(
', %s: %d',
$name,
$count
);
}
return $string;
}
/**
*/
public function printWaitPrompt()
{
$this->write("\n<RETURN> to continue\n");
}
/**
* An error occurred.
*
* @param PHPUnit_Framework_Test $test
* @param Exception $e
* @param float $time
*/
public function addError(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->writeProgress('E');
$this->lastTestFailed = TRUE;
}
/**
* A failure occurred.
*
* @param PHPUnit_Framework_Test $test
* @param PHPUnit_Framework_AssertionFailedError $e
* @param float $time
*/
public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time)
{
$this->writeProgress('F');
$this->lastTestFailed = TRUE;
}
/**
* Incomplete test.
*
* @param PHPUnit_Framework_Test $test
* @param Exception $e
* @param float $time
*/
public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->writeProgress('I');
$this->lastTestFailed = TRUE;
}
/**
* Skipped test.
*
* @param PHPUnit_Framework_Test $test
* @param Exception $e
* @param float $time
* @since Method available since Release 3.0.0
*/
public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
$this->writeProgress('S');
$this->lastTestFailed = TRUE;
}
/**
* A testsuite started.
*
* @param PHPUnit_Framework_TestSuite $suite
* @since Method available since Release 2.2.0
*/
public function startTestSuite(PHPUnit_Framework_TestSuite $suite)
{
if ($this->numTests == -1) {
$this->numTests = count($suite);
$this->numTestsWidth = strlen((string)$this->numTests);
} else {
$this->indent++;
}
if ($this->verbose) {
$name = $suite->getName();
if (empty($name)) {
$name = 'Test Suite';
} else {
$name = preg_replace( '(^.*::(.*?)$)', '\\1', $name );
}
$this->write(
sprintf(
"%s%s%s",
$this->lastEvent == self::EVENT_TESTSUITE_END ||
$suite instanceof PHPUnit_Framework_TestSuite_DataProvider ?
"\n" :
'',
str_repeat(' ', $this->indent),
$name
)
);
$this->writeNewLine();
}
$this->lastEvent = self::EVENT_TESTSUITE_START;
}
/**
* A testsuite ended.
*
* @param PHPUnit_Framework_TestSuite $suite
* @since Method available since Release 2.2.0
*/
public function endTestSuite(PHPUnit_Framework_TestSuite $suite)
{
$this->indent--;
if ($this->verbose) {
if ($this->lastEvent != self::EVENT_TESTSUITE_END) {
$this->writeNewLine();
}
}
$this->lastEvent = self::EVENT_TESTSUITE_END;
}
/**
* A test started.
*
* @param PHPUnit_Framework_Test $test
*/
public function startTest(PHPUnit_Framework_Test $test)
{
$this->lastEvent = self::EVENT_TEST_START;
if ($this->debug) {
$this->write(
sprintf(
"\nStarting test '%s'.\n", PHPUnit_Util_Test::describe($test)
)
);
}
$this->numTestsRun++;
}
/**
* A test ended.
*
* @param PHPUnit_Framework_Test $test
* @param float $time
*/
public function endTest(PHPUnit_Framework_Test $test, $time)
{
if (!$this->lastTestFailed) {
$this->writeProgress('.');
}
if ($test instanceof PHPUnit_Framework_TestCase) {
$this->numAssertions += $test->getNumAssertions();
}
$this->lastEvent = self::EVENT_TEST_END;
$this->lastTestFailed = FALSE;
}
/**
* @param string $progress
*/
protected function writeProgress($progress)
{
$this->write($progress);
$this->column++;
if ($this->column == 60) {
if (!$this->verbose) {
$this->write(
sprintf(
' %' . $this->numTestsWidth . 'd / %' .
$this->numTestsWidth . "d",
$this->numTestsRun,
$this->numTests
)
);
}
$this->writeNewLine();
}
}
protected function writeNewLine()
{
$this->write("\n");
if ($this->verbose) {
$this->column = $this->indent;
$this->write(str_repeat(' ', max(0, $this->indent)));
} else {
$this->column = 0;
}
}
}
?>
| {
"content_hash": "082d09a4dab17622e0eb585d37865811",
"timestamp": "",
"source": "github",
"line_count": 623,
"max_line_length": 110,
"avg_line_length": 25.03852327447833,
"alnum_prop": 0.4754791973844477,
"repo_name": "olle/baseweb",
"id": "812576df9544cfebcb30a6dcd0b7c52fb05d3354",
"size": "17676",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/php/PHPUnit/TextUI/ResultPrinter.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "320"
},
{
"name": "CSS",
"bytes": "42449"
},
{
"name": "HTML",
"bytes": "10585"
},
{
"name": "JavaScript",
"bytes": "29522"
},
{
"name": "PHP",
"bytes": "5311326"
},
{
"name": "Shell",
"bytes": "3537"
}
],
"symlink_target": ""
} |
<!doctype html>
<html class="no-js">
<head>
<meta charset="utf-8">
<title>Ani AngularJS Dashboard Theme</title>
<meta name="description" content="">
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<!-- build:css(.tmp) styles/vendor.css -->
<!-- bower:css -->
<link rel="stylesheet" href="../bower_components/animate.css/animate.css" />
<link rel="stylesheet" href="../bower_components/fullcalendar/fullcalendar.css" />
<link rel="stylesheet" href="../bower_components/angular-chart.js/dist/angular-chart.css" />
<link rel="stylesheet" href="../bower_components/fontawesome/css/font-awesome.css" />
<link rel="stylesheet" href="../bower_components/hover/css/hover.css" />
<link rel="stylesheet" href="../bower_components/c3/c3.css" />
<link rel="stylesheet" href="../bower_components/angular-loading-bar/build/loading-bar.css" />
<link rel="stylesheet" href="../bower_components/textAngular/src/textAngular.css" />
<link rel="stylesheet" href="../bower_components/perfect-scrollbar/css/perfect-scrollbar.css" />
<link rel="stylesheet" href="../bower_components/angular-progress-button-styles/dist/angular-progress-button-styles.min.css" />
<!-- endbower -->
<!-- endbuild -->
<!-- build:css(.tmp) styles/main.css -->
<link rel="stylesheet" href="styles/app-red.css">
<!-- endbuild -->
<!-- build:js scripts/vendor.js -->
<script src="../bower_components/jquery/jquery.min.js"></script>
<script src="scripts/extras/modernizr.custom.js"></script>
<!-- bower:js -->
<script src="../bower_components/angular/angular.js"></script>
<script src="../bower_components/angular-mocks/angular-mocks.js"></script>
<script src="../bower_components/ui-router/release/angular-ui-router.js"></script>
<script src="../bower_components/angular-animate/angular-animate.js"></script>
<script src="../bower_components/fullcalendar/fullcalendar.js"></script>
<script src="../bower_components/angular-ui-calendar/src/calendar.js"></script>
<script src="../bower_components/Chart.js/Chart.js"></script>
<script src="../bower_components/angular-chart.js/dist/angular-chart.js"></script>
<script src="../bower_components/d3/d3.js"></script>
<script src="../bower_components/c3/c3.js"></script>
<script src="../bower_components/c3-angular/c3js-directive.js"></script>
<script src="../bower_components/angular-growl/build/angular-growl.js"></script>
<script src="../bower_components/angular-loading-bar/build/loading-bar.js"></script>
<script src="../bower_components/angular-growl-notifications/dist/angular-growl-notifications.js"></script>
<script src="../bower_components/rangy/rangy-core.js"></script>
<script src="../bower_components/rangy/rangy-classapplier.js"></script>
<script src="../bower_components/rangy/rangy-highlighter.js"></script>
<script src="../bower_components/rangy/rangy-selectionsaverestore.js"></script>
<script src="../bower_components/rangy/rangy-serializer.js"></script>
<script src="../bower_components/rangy/rangy-textrange.js"></script>
<script src="../bower_components/textAngular/src/textAngular.js"></script>
<script src="../bower_components/textAngular/src/textAngular-sanitize.js"></script>
<script src="../bower_components/textAngular/src/textAngularSetup.js"></script>
<script src="../bower_components/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../bower_components/classie/classie.js"></script>
<script src="../bower_components/angular-progress-button-styles/dist/angular-progress-button-styles.min.js"></script>
<script src="../bower_components/angular-translate/angular-translate.js"></script>
<script src="../bower_components/angular-translate-loader-url/angular-translate-loader-url.js"></script>
<script src="../bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.js"></script>
<!-- endbower -->
<script src="../bower_components/perfect-scrollbar/js/perfect-scrollbar.jquery.js"></script>
<script src="../bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js"></script>
<!-- endbuild -->
<!-- build:js({.tmp,app}) scripts/scripts.js -->
<script src="scripts/app.js"></script>
<script src="scripts/extras/map.min.js"></script>
<script src="scripts/extras/worldmap.js"></script>
<script src="scripts/extras/progressButton.js"></script>
<script src="scripts/controllers/login.js"></script>
<script src="scripts/controllers/dashboard.js"></script>
<script src="scripts/controllers/alertCtrl.js"></script>
<script src="scripts/controllers/btnCtrl.js"></script>
<script src="scripts/controllers/collapseCtrl.js"></script>
<script src="scripts/controllers/dateCtrl.js"></script>
<script src="scripts/controllers/dropdownCtrl.js"></script>
<script src="scripts/controllers/modalCtrl.js"></script>
<script src="scripts/controllers/paginationCtrl.js"></script>
<script src="scripts/controllers/popoverCtrl.js"></script>
<script src="scripts/controllers/tooltipCtrl.js"></script>
<script src="scripts/controllers/progressCtrl.js"></script>
<script src="scripts/controllers/tabsCtrl.js"></script>
<script src="scripts/controllers/timepickerCtrl.js"></script>
<script src="scripts/controllers/sidebarCtrl.js"></script>
<script src="scripts/controllers/homeCtrl.js"></script>
<script src="scripts/controllers/chartCtrl.js"></script>
<script src="scripts/controllers/todoCtrl.js"></script>
<script src="scripts/controllers/buttonCtrl.js"></script>
<script src="scripts/controllers/clndrCtrl.js"></script>
<script src="scripts/controllers/productCtrl.js"></script>
<script src="scripts/controllers/carouselCtrl.js"></script>
<script src="scripts/directives/topnav/topnav.js"></script>
<script src="scripts/directives/sidebar/sidebar.js"></script>
<script src="scripts/directives/sidebar/right-sidebar.js"></script>
<script src="scripts/directives/stats/stats.js"></script>
<script src="scripts/directives/to-do-list/to-do.js"></script>
<script src="scripts/directives/sidebar/sidebar-widgets/sidebar-widgets.js"></script>
<script src="scripts/directives/sidebar/sidebar-widgets/sidebar-calendar/sidebar-calendar.js"></script>
<script src="scripts/directives/sidebar/sidebar-widgets/sidebar-newsfeed/sidebar-newsfeed.js"></script>
<script src="scripts/directives/sidebar/sidebar-widgets/sidebar-profile/sidebar-profile.js"></script>
<script src="scripts/directives/sidebar/menu-bar/menu-bar.js"></script>
<!-- endbuild -->
</head>
<body ng-app="AniTheme">
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<!-- Add your site or application content here -->
<div>
<div ui-view ></div>
</div>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID -->
<script> /*
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXX-X');
ga('send', 'pageview'); */
</script>
<!-- build:js scripts/oldieshim.js -->
<!--[if lt IE 9]>
<script src="../bower_components/es5-shim/es5-shim.js"></script>
<script src="../bower_components/json3/lib/json3.js"></script>
<![endif]-->
<!-- endbuild -->
</body>
</html>
| {
"content_hash": "ae3ad416d477925ff4cf35bcf4ed1fd1",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 178,
"avg_line_length": 59.796992481203006,
"alnum_prop": 0.6828869608952597,
"repo_name": "jeffestrong/PICNIC_Core",
"id": "8ee213cdb8f2119e8ccb92665fc8949d7d4c32db",
"size": "7953",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/index.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1527563"
},
{
"name": "HTML",
"bytes": "234452"
},
{
"name": "JavaScript",
"bytes": "47674"
}
],
"symlink_target": ""
} |
var WebSocketServer = require('../../').Server
, http = require('http')
, express = require('express')
, app = express();
app.use(express.static(__dirname + '/public'));
var server = http.createServer(app);
server.listen(8080);
var wss = new WebSocketServer({server: server});
wss.on('connection', function (ws) {
var id = setInterval(function () {
ws.send(JSON.stringify(process.memoryUsage()), function () { /* ignore errors */
});
}, 100);
console.log('started client interval');
ws.on('close', function () {
console.log('stopping client interval');
clearInterval(id);
});
});
| {
"content_hash": "2eb134b1d7a269d90225a0c466e514cb",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 88,
"avg_line_length": 29.40909090909091,
"alnum_prop": 0.60741885625966,
"repo_name": "picacure/adc-tmd",
"id": "d073dc36e777d3434cbf8368510388004d7b6324",
"size": "647",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/node_modules/socket.io/node_modules/socket.io-client/node_modules/ws/examples/serverstats-express_3/server.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "13998"
},
{
"name": "JavaScript",
"bytes": "611569"
}
],
"symlink_target": ""
} |
package com.codeprep.bootmvc;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
| {
"content_hash": "f48bfeff5b8d39bb63c7b5f043245887",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 85,
"avg_line_length": 31.076923076923077,
"alnum_prop": 0.8564356435643564,
"repo_name": "codepreplabs/springMVCtutorial",
"id": "419548e7f91c405105d8d18d0af60dc9e3559046",
"size": "404",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "02bootMVC/src/main/java/com/codeprep/bootmvc/ServletInitializer.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "463"
},
{
"name": "Java",
"bytes": "4672"
}
],
"symlink_target": ""
} |
<?php
namespace app\modules\Hres\controllers;
use yii\web\Controller;
class DefaultController extends Controller
{
public function actionIndex()
{
return $this->render('index');
}
}
| {
"content_hash": "d4f9daf9d2491d3c07a8048181f6f3fe",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 42,
"avg_line_length": 15.76923076923077,
"alnum_prop": 0.6878048780487804,
"repo_name": "329221391/home",
"id": "cd8583bdcd6a69d2d33d36b612eefc0a3a630f70",
"size": "205",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/Hres/controllers/DefaultController.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "215"
},
{
"name": "Batchfile",
"bytes": "1093"
},
{
"name": "CSS",
"bytes": "778415"
},
{
"name": "HTML",
"bytes": "100096"
},
{
"name": "JavaScript",
"bytes": "995269"
},
{
"name": "PHP",
"bytes": "2353861"
}
],
"symlink_target": ""
} |
{% extends "base.html" %}
{% load i18n %}
{% block title %}<h2>{% trans "Page not found" %}</h2>{% endblock %}
{% block main %}
<p>{% trans "Page could not be found."%}</p>
<p>{% trans "If you think this is a bug, please send and e-mail to developers." %}</p>
{% endblock %}
| {
"content_hash": "ca4a4f8d778c69a49bed5feb1b41f524",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 86,
"avg_line_length": 30.77777777777778,
"alnum_prop": 0.5848375451263538,
"repo_name": "kartikshah1/Test",
"id": "992cca4b37b1e8e4189d12551a77556342f2a3fa",
"size": "277",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "grader/templates/404.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "21691"
},
{
"name": "C++",
"bytes": "3267"
},
{
"name": "CSS",
"bytes": "355299"
},
{
"name": "Java",
"bytes": "9833"
},
{
"name": "JavaScript",
"bytes": "2844415"
},
{
"name": "Perl",
"bytes": "4202"
},
{
"name": "Python",
"bytes": "1703618"
},
{
"name": "Shell",
"bytes": "6379"
}
],
"symlink_target": ""
} |
using JustLogic.Core;
using System.Collections.Generic;
using UnityEngine;
[UnitMenu("Object/Sample Animation")]
[UnitFriendlyName("Sample Animation")]
public class JLGameObjectSampleAnimation : JLAction
{
[Parameter(ExpressionType = typeof(GameObject))]
public JLExpression OperandValue;
[Parameter(ExpressionType = typeof(AnimationClip))]
public JLExpression Animation;
[Parameter(ExpressionType = typeof(System.Single))]
public JLExpression Time;
protected override IEnumerator<YieldMode> OnExecute(IExecutionContext context)
{
GameObject opValue = OperandValue.GetResult<GameObject>(context);
Animation.GetResult<AnimationClip>(context).SampleAnimation(opValue, Time.GetResult<System.Single>(context));
return null; }
}
| {
"content_hash": "8ed8b7e066f204ec6155d2da4bbb185c",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 117,
"avg_line_length": 31.64,
"alnum_prop": 0.7547408343868521,
"repo_name": "AqlaSolutions/JustLogic",
"id": "90bc034b1fa92fff7e6c65d32b38f15b5984d75f",
"size": "2439",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Assets/JustLogicUnits/Generated/GameObject/JLGameObjectSampleAnimation.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "2892"
},
{
"name": "C#",
"bytes": "3394070"
},
{
"name": "JavaScript",
"bytes": "23005"
}
],
"symlink_target": ""
} |
<?php
namespace PoiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use PoiBundle\Entity\Application\PointsAndroid;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Points
*
* @ORM\Table(name="points", indexes={@ORM\Index(name="FK_Points_Users_idx", columns={"User_Id"}), @ORM\Index(name="FK_Points_Types_idx", columns={"Type_Id"}), @ORM\Index(name="FK_Points_Administrators_idx", columns={"Accept_Id"})})
* @ORM\Entity(repositoryClass="PoiBundle\Repository\PointsRepository")
*/
class Points
{
/**
* @var integer
*
* @ORM\Column(name="Id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var double
*
* @ORM\Column(name="Longitude", type="decimal", precision=9, scale=6, nullable=false)
*/
private $longitude;
/**
* @var double
*
* @ORM\Column(name="Latitude", type="decimal", precision=9, scale=6, nullable=false)
*/
private $latitude;
/**
* @var string
*
* @ORM\Column(name="Name", type="string", length=150, nullable=false)
*/
private $name;
/**
* @var string
*
* @ORM\Column(name="Locality", type="string", length=90, nullable=false)
*/
private $locality;
/**
* @var string
*
* @ORM\Column(name="Rating", type="decimal", precision=2, scale=1, nullable=true)
*/
private $rating;
/**
* @var string
*
* @ORM\Column(name="Description", type="string", length=300, nullable=false)
*/
private $description;
/**
* @var string
* @Assert\File(mimeTypes={"image/jpg", "image/jpeg", "image/png"})
* @ORM\Column(name="Picture", type="string", length=255, nullable=false)
*/
private $picture;
/**
* @var string
*
* @ORM\Column(name="MimeType", type="string", length=50, nullable=false)
*/
private $mimetype;
/**
* @var \DateTime
*
* @ORM\Column(name="AddedDate", type="datetime", nullable=false)
*/
private $addeddate;
/**
* @var boolean
*
* @ORM\Column(name="Accepted", type="boolean", nullable=false)
*/
private $accepted;
/**
* @var boolean
*
* @ORM\Column(name="Unblocked", type="boolean", nullable=false)
*/
private $unblocked;
/**
* @var \Administrators
*
* @ORM\ManyToOne(targetEntity="Administrators")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="Accept_Id", referencedColumnName="Id")
* })
*/
private $accept;
/**
* @var \Types
*
* @ORM\ManyToOne(targetEntity="Types")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="Type_Id", referencedColumnName="Id")
* })
*/
private $type;
/**
* @var \Users
*
* @ORM\ManyToOne(targetEntity="Users")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="User_Id", referencedColumnName="Id")
* })
*/
private $user;
/**
* @var \Ratings
*
* @ORM\OneToMany(targetEntity="Ratings", mappedBy="point")
*/
private $ratings;
public function __construct()
{
}
public static function constructPointAndroid(PointsAndroid $pointAndroid)
{
$instance = new self();
$instance->longitude = $pointAndroid->getLongitude();
$instance->latitude = $pointAndroid->getLatitude();
$instance->name = $pointAndroid->getName();
$instance->locality = $pointAndroid->getLocality();
$instance->description = $pointAndroid->getDescription();
$instance->picture = $pointAndroid->getPicture();
$instance->mimetype = $pointAndroid->getMimetype();
$instance->addeddate = new \DateTime();
$instance->accepted = false;
$instance->unblocked = true;
return $instance;
}
/**
* Set longitude
*
* @param string $longitude
* @return Points
*/
public function setLongitude($longitude)
{
$this->longitude = $longitude;
return $this;
}
/**
* Get longitude
*
* @return string
*/
public function getLongitude()
{
return $this->longitude;
}
/**
* Set latitude
*
* @param string $latitude
* @return Points
*/
public function setLatitude($latitude)
{
$this->latitude = $latitude;
return $this;
}
/**
* Get latitude
*
* @return string
*/
public function getLatitude()
{
return $this->latitude;
}
/**
* Set rating
*
* @param string $rating
* @return Points
*/
public function setRating($rating)
{
$this->rating = $rating;
return $this;
}
/**
* Get rating
*
* @return string
*/
public function getRating()
{
return $this->rating;
}
/**
* Set name
*
* @param string $name
* @return Points
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set locality
*
* @param string $locality
* @return Points
*/
public function setLocality($locality)
{
$this->locality = $locality;
return $this;
}
/**
* Get locality
*
* @return string
*/
public function getLocality()
{
return $this->locality;
}
/**
* Set description
*
* @param string $description
* @return Points
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set picture
*
* @param string $picture
* @return Points
*/
public function setPicture($picture)
{
$this->picture = $picture;
return $this;
}
/**
* Get picture
*
* @return string
*/
public function getPicture()
{
return $this->picture;
}
/**
* Set mimetype
*
* @param string $mimetype
* @return Points
*/
public function setMimetype($mimetype)
{
$this->mimetype = $mimetype;
return $this;
}
/**
* Get mimetype
*
* @return string
*/
public function getMimetype()
{
return $this->mimetype;
}
/**
* Set addeddate
*
* @param \DateTime $addeddate
* @return Points
*/
public function setAddeddate($addeddate)
{
$this->addeddate = $addeddate;
return $this;
}
/**
* Get addeddate
*
* @return \DateTime
*/
public function getAddeddate()
{
return $this->addeddate;
}
/**
* Set accepted
*
* @param boolean $accepted
* @return Points
*/
public function setAccepted($accepted)
{
$this->accepted = $accepted;
return $this;
}
/**
* Get accepted
*
* @return boolean
*/
public function getAccepted()
{
return $this->accepted;
}
/**
* Set unblocked
*
* @param boolean $unblocked
* @return Points
*/
public function setUnblocked($unblocked)
{
$this->unblocked = $unblocked;
return $this;
}
/**
* Get unblocked
*
* @return boolean
*/
public function getUnblocked()
{
return $this->unblocked;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set accept
*
* @param \PoiBundle\Entity\Administrators $accept
* @return Points
*/
public function setAccept(\PoiBundle\Entity\Administrators $accept = null)
{
$this->accept = $accept;
return $this;
}
/**
* Get accept
*
* @return \PoiBundle\Entity\Administrators
*/
public function getAccept()
{
return $this->accept;
}
/**
* Set type
*
* @param \PoiBundle\Entity\Types $type
* @return Points
*/
public function setType(\PoiBundle\Entity\Types $type = null)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* @return \PoiBundle\Entity\Types
*/
public function getType()
{
return $this->type;
}
/**
* Set user
*
* @param \PoiBundle\Entity\Users $user
* @return Points
*/
public function setUser(\PoiBundle\Entity\Users $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* @return \PoiBundle\Entity\Users
*/
public function getUser()
{
return $this->user;
}
/**
* @return Ratings
*/
public function getRatings()
{
return $this->ratings;
}
/**
* @param Ratings $ratings
*/
public function setRatings($ratings)
{
$this->ratings = $ratings;
}
} | {
"content_hash": "e21b1cde9315a9293c83b875ee9fcdda",
"timestamp": "",
"source": "github",
"line_count": 507,
"max_line_length": 232,
"avg_line_length": 18.516765285996055,
"alnum_prop": 0.5209842351938645,
"repo_name": "PrzemyslawMikos/POI",
"id": "fefc6a83df86932209d039018f45d4e52094f2ee",
"size": "9388",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/PoiBundle/Entity/Points.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3605"
},
{
"name": "CSS",
"bytes": "16862"
},
{
"name": "HTML",
"bytes": "114592"
},
{
"name": "JavaScript",
"bytes": "40903"
},
{
"name": "PHP",
"bytes": "191514"
}
],
"symlink_target": ""
} |
class AddTypestringsToReferenceTypes < ActiveRecord::Migration
def change
add_column :reference_types, :typestrings, :string
end
end
| {
"content_hash": "1afd0775d6bd6cabe5f39fc98f56cb43",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 62,
"avg_line_length": 28,
"alnum_prop": 0.7928571428571428,
"repo_name": "globalitdevelopment/histvest",
"id": "98eb7be20fa83d7521eea2b1d81a014aecc498e5",
"size": "140",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db/migrate/20130125135600_add_typestrings_to_reference_types.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "61552"
},
{
"name": "CoffeeScript",
"bytes": "61547"
},
{
"name": "HTML",
"bytes": "109152"
},
{
"name": "JavaScript",
"bytes": "15062"
},
{
"name": "Ruby",
"bytes": "176608"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (C) 2013 Stefan Schroeder
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Contributors:
Stefan Schroeder - initial API and implementation
-->
<algorithm xmlns="http://www.w3schools.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3schools.com algorithm_schema.xsd">
<iterations>2000</iterations>
<construction>
<insertion name="bestInsertion">
<allowVehicleSwitch>false</allowVehicleSwitch>
</insertion>
</construction>
<strategy>
<memory>1</memory>
<searchStrategies>
<searchStrategy name="radialRuinAndRecreate">
<selector name="selectBest"/>
<acceptor name="acceptNewRemoveWorst"/>
<modules>
<module name="ruin_and_recreate">
<ruin name="randomRuin">
<share>0.3</share>
</ruin>
<insertion name="bestInsertion"/>
</module>
</modules>
<probability>0.2</probability>
</searchStrategy>
<searchStrategy name="radialRuinAndRecreate">
<selector name="selectBest"/>
<acceptor name="acceptNewRemoveWorst"/>
<modules>
<module name="ruin_and_recreate">
<ruin id="1" name="radialRuin">
<share>0.15</share>
</ruin>
<insertion name="bestInsertion"/>
</module>
</modules>
<probability>0.2</probability>
</searchStrategy>
<searchStrategy name="radialRuinAndRecreate">
<selector name="selectBest"/>
<acceptor name="acceptNewRemoveWorst"/>
<modules>
<module name="ruin_and_recreate">
<ruin id="2" name="radialRuin">
<share>0.05</share>
</ruin>
<insertion name="bestInsertion"/>
</module>
</modules>
<probability>0.6</probability>
</searchStrategy>
</searchStrategies>
</strategy>
</algorithm>
| {
"content_hash": "c3d98ce3f06dcbe6a334e9e37ca4c6ee",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 165,
"avg_line_length": 31.011627906976745,
"alnum_prop": 0.6329208848893888,
"repo_name": "tribbloid/spookystuff",
"id": "f32c653f1cd49272e2916fa11518f51515ae1f33",
"size": "2669",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "parent/uav/input/abe/algorithmConfig.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "247067"
},
{
"name": "Java",
"bytes": "41120"
},
{
"name": "JavaScript",
"bytes": "154949"
},
{
"name": "Kotlin",
"bytes": "19326"
},
{
"name": "Python",
"bytes": "38856"
},
{
"name": "Scala",
"bytes": "1456793"
},
{
"name": "Shell",
"bytes": "5579"
}
],
"symlink_target": ""
} |
package com.asafge.pocketplus;
import android.content.Context;
import org.json.JSONException;
import org.json.JSONObject;
import com.noinnion.android.reader.api.ExtensionPrefs;
public class Prefs extends ExtensionPrefs {
public static final String KEY_LOGGED_IN = "logged_in";
public static final String KEY_JSON = "key_json";
public static final String USER_AGENT = System.getProperty("http.agent");
public static final String NEWSPLUS_PACKAGE = "com.noinnion.android.newsplus";
public static final String KEY_SYNC_READ = "sync_read";
public static boolean isLoggedIn(Context c) {
return getBoolean(c, KEY_LOGGED_IN, false);
}
public static void setLoggedIn(Context c, boolean value) {
putBoolean(c, KEY_LOGGED_IN, value);
}
public static JSONObject getSessionData(Context c) {
try {
return new JSONObject(getString(c, KEY_JSON));
}
catch (JSONException e) {
return null;
}
catch (NullPointerException e) {
return null;
}
}
public static void setSessionData(Context c, JSONObject json) {
putString(c, KEY_JSON, (json != null) ? json.toString() : "");
}
public static Boolean getSyncRead(Context c) {
try {
return getBoolean( c, KEY_SYNC_READ, false);
}
catch (NullPointerException e) {
return false;
}
}
public static void setSyncRead(Context c, Boolean value) {
putBoolean(c, KEY_SYNC_READ, value);
}
}
| {
"content_hash": "61023e441076ffa144b10bfbcd198b58",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 79,
"avg_line_length": 27.64814814814815,
"alnum_prop": 0.666443402545211,
"repo_name": "asafge/PocketPlus",
"id": "25cc20bf6bc834b2a9db5808f41c404a5895ee23",
"size": "1493",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/asafge/pocketplus/Prefs.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1262681"
}
],
"symlink_target": ""
} |
package org.apache.commons.jelly.tags.jface.preference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import org.apache.commons.jelly.JellyTagException;
import org.apache.commons.jelly.MissingAttributeException;
import org.apache.commons.jelly.XMLOutput;
import org.apache.commons.jelly.tags.core.UseBeanTag;
import org.eclipse.jface.preference.FieldEditor;
import org.eclipse.swt.widgets.Composite;
/**
* This Tag creates a JFace FieldEditor
*
* @author <a href="mailto:[email protected]">Christiaan ten Klooster</a>
*/
public class FieldEditorTag extends UseBeanTag {
public FieldEditorTag(Class arg0) {
super(arg0);
}
/*
* @see org.apache.commons.jelly.Tag#doTag(org.apache.commons.jelly.XMLOutput)
*/
public void doTag(XMLOutput output) throws MissingAttributeException, JellyTagException {
PreferencePageTag tag = (PreferencePageTag) findAncestorWithClass(PreferencePageTag.class);
if (tag == null) {
throw new JellyTagException("This tag must be nested inside a <preferencePage>");
}
// get new instance of FieldEditor
PreferencePageTag.PreferencePageImpl page = tag.getPreferencePageImpl();
getAttributes().put("parentComposite", page.getFieldEditorParent());
// add fieldEditor to PreferencePage
Object fieldEditor = newInstance(getDefaultClass(), getAttributes(), output);
if (fieldEditor instanceof FieldEditor) {
page.addField((FieldEditor) fieldEditor);
}
}
/*
* @see org.apache.commons.jelly.tags.core.UseBeanTag#newInstance(java.lang.Class, java.util.Map, org.apache.commons.jelly.XMLOutput)
*/
protected Object newInstance(Class theClass, Map attributes, XMLOutput output)
throws JellyTagException {
if (theClass == null) {
throw new JellyTagException("No Class available to create the FieldEditor");
}
String name = (String) attributes.get("name");
if (name == null) {
throw new MissingAttributeException("name");
}
String labelText = (String) attributes.get("labelText");
if (labelText == null) {
throw new MissingAttributeException("labelText");
}
Composite parentComposite = (Composite) attributes.get("parentComposite");
if (parentComposite == null) {
throw new MissingAttributeException("parentComposite");
}
// let's try to call a constructor
try {
Class[] types = { String.class, String.class, Composite.class };
Constructor constructor = theClass.getConstructor(types);
if (constructor != null) {
Object[] arguments = { name, labelText, parentComposite };
return constructor.newInstance(arguments);
}
return theClass.newInstance();
} catch (NoSuchMethodException e) {
throw new JellyTagException(e);
} catch (InstantiationException e) {
throw new JellyTagException(e);
} catch (IllegalAccessException e) {
throw new JellyTagException(e);
} catch (InvocationTargetException e) {
throw new JellyTagException(e);
}
}
}
| {
"content_hash": "ee6facc87ed10b716708614b4120a47f",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 137,
"avg_line_length": 36.774193548387096,
"alnum_prop": 0.6441520467836257,
"repo_name": "jenkinsci/jelly",
"id": "7fd0aa535b281e3c46de75c233d9696405554878",
"size": "4054",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "jelly-tags/jface/src/java/org/apache/commons/jelly/tags/jface/preference/FieldEditorTag.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1253"
},
{
"name": "HTML",
"bytes": "30803"
},
{
"name": "Java",
"bytes": "2065279"
},
{
"name": "Shell",
"bytes": "1276"
},
{
"name": "XSLT",
"bytes": "33811"
}
],
"symlink_target": ""
} |
package cn.com.sparkle.firefly.config;
public class ConfigurationException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public ConfigurationException() {
super();
}
public ConfigurationException(String message, Throwable cause) {
super(message, cause);
}
public ConfigurationException(String message) {
super(message);
}
public ConfigurationException(Throwable cause) {
super(cause);
}
}
| {
"content_hash": "b5b4a6737a015a300c2a7310542598d5",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 65,
"avg_line_length": 17.346153846153847,
"alnum_prop": 0.7339246119733924,
"repo_name": "qinannmj/FireFly",
"id": "1d45d8f4ab2edbb5b9205e9761555071ec88ba83",
"size": "451",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/cn/com/sparkle/firefly/config/ConfigurationException.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "911584"
},
{
"name": "Protocol Buffer",
"bytes": "5894"
}
],
"symlink_target": ""
} |
"""
DPQ
~~~~~~~
Simple job queue for python.
"""
from .connections import (
get_current_connection,
use_connection,
push_connection,
pop_connection,
Connection)
from .queue import Queue
from .job import cancel_job
from .worker import Worker
__all__ = ['get_current_connection', 'use_connection', 'push_connection',
'pop_connection', 'Connection', 'Queue', 'cancel_job', 'Worker']
version_info = (0, 0, 1)
__version__ = ".".join([str(v) for v in version_info])
| {
"content_hash": "e835269866812295eb3c3d8da2fb67bb",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 75,
"avg_line_length": 22.772727272727273,
"alnum_prop": 0.6387225548902196,
"repo_name": "DiggerPlus/DPQ",
"id": "5045ae701d516a5a02824bf344ac2d54a228673b",
"size": "526",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dpq/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "60972"
}
],
"symlink_target": ""
} |
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace iDeviceBrowser.Tests
{
[TestClass]
public class UtilitiesTests
{
[TestMethod]
public void GetFileSize_0_Returns0KB()
{
Assert.AreEqual("0 KB", Utilities.GetFileSize(0));
}
[TestMethod]
public void GetFileSize_1_Returns1KB()
{
Assert.AreEqual("1 KB", Utilities.GetFileSize(1));
}
[TestMethod]
public void GetFileSize_1024_Returns1KB()
{
Assert.AreEqual("1 KB", Utilities.GetFileSize(1024));
}
[TestMethod]
public void GetFileSize_10240_Returns10KB()
{
Assert.AreEqual("10 KB", Utilities.GetFileSize(10240));
}
[TestMethod]
public void GetFileSize_1024000_Returns1000KB()
{
Assert.AreEqual("1,000 KB", Utilities.GetFileSize(1024000));
}
// TODO: THIS SHOULD LIKELY RETURN EMPTY.STRING TO MATCH PATH.COMBINE OF SYSTEM.IO
[TestMethod]
public void PathCombine_Empty_Empty_ReturnsSlash()
{
Assert.AreEqual("/", Utilities.PathCombine(string.Empty, string.Empty));
}
// TODO: THIS SHOULD LIKELY RETURN bin TO MATCH PATH.COMBINE OF SYSTEM.IO
[TestMethod]
public void PathCombine_Empty_bin_ReturnsSlash()
{
Assert.AreEqual("/bin", Utilities.PathCombine(string.Empty, "bin"));
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void PathCombine_Empty_Slashbin_ReturnsSlash()
{
Assert.AreEqual("/bin", Utilities.PathCombine(string.Empty, "/bin"));
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void PathCombine_Empty_SlashbinSlash_ReturnsSlash()
{
Assert.AreEqual("/bin/", Utilities.PathCombine(string.Empty, "/bin/"));
}
[TestMethod]
public void PathCombine_Slash_Empty_ReturnsSlash()
{
Assert.AreEqual("/", Utilities.PathCombine("/", string.Empty));
}
[TestMethod]
public void PathCombine_Slash_bin_ReturnsSlash()
{
Assert.AreEqual("/bin", Utilities.PathCombine("/", "bin"));
}
[TestMethod]
public void PathCombine_Slashbin_apt_ReturnsSlash()
{
Assert.AreEqual("/bin/apt", Utilities.PathCombine("/bin", "apt"));
}
[TestMethod]
public void PathCombine_SlashbinSlash_apt_ReturnsSlash()
{
Assert.AreEqual("/bin/apt", Utilities.PathCombine("/bin/", "apt"));
}
[TestMethod]
public void PathCombine_bin_apt_ReturnsSlash()
{
Assert.AreEqual("bin/apt", Utilities.PathCombine("bin", "apt"));
}
}
}
| {
"content_hash": "f2c29cc0a6755ff3ee5c5314d1d39d49",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 90,
"avg_line_length": 29.47,
"alnum_prop": 0.5880556498133696,
"repo_name": "jschulist/iDeviceBrowser",
"id": "df687e9dd500ae813cb7cd8a874476bda2dfcec6",
"size": "2949",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "iDeviceBrowser.Tests/UtilitiesTests.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C#",
"bytes": "261338"
}
],
"symlink_target": ""
} |
package org.wave.classes;
import javax.validation.constraints.AssertFalse;
import javax.validation.constraints.AssertTrue;
public class BooleanClass {
private boolean defaultValue;
@AssertTrue
private boolean trueValue;
@AssertFalse
private boolean falseValue;
public boolean isDefaultValue() {
return this.defaultValue;
}
public boolean isTrueValue() {
return this.trueValue;
}
public boolean isFalseValue() {
return this.falseValue;
}
}
| {
"content_hash": "c7ec1d62235fcf05e506f020bc7d85a9",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 48,
"avg_line_length": 16.607142857142858,
"alnum_prop": 0.7741935483870968,
"repo_name": "org-wave/Populator",
"id": "9be2cfe77d229172f676f2ca3f5968c550b5a119",
"size": "465",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/org/wave/classes/BooleanClass.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "140388"
}
],
"symlink_target": ""
} |
package org.javesi.testcomponents;
import org.javesi.component.SingletonComponent;
public class SingleB
implements SingletonComponent
{
public int value;
}
| {
"content_hash": "df7ed6b91bc213346ea5f3d1f2c2cb15",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 47,
"avg_line_length": 18.444444444444443,
"alnum_prop": 0.7951807228915663,
"repo_name": "fforw/javesi",
"id": "23340aa04ec2cd562d02e9d739f198c5524c2235",
"size": "166",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/org/javesi/testcomponents/SingleB.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "50499"
}
],
"symlink_target": ""
} |
#pragma once
#include <cerrno>
#include <folly/portability/SysUio.h>
#include <folly/portability/Unistd.h>
/**
* Helper functions and templates for FileUtil.cpp. Declared here so
* they can be unittested.
*/
namespace folly { namespace fileutil_detail {
// Wrap call to f(args) in loop to retry on EINTR
template <class F, class... Args>
ssize_t wrapNoInt(F f, Args... args) {
ssize_t r;
do {
r = f(args...);
} while (r == -1 && errno == EINTR);
return r;
}
inline void incr(ssize_t /* n */) {}
inline void incr(ssize_t n, off_t& offset) { offset += off_t(n); }
// Wrap call to read/pread/write/pwrite(fd, buf, count, offset?) to retry on
// incomplete reads / writes. The variadic argument magic is there to support
// an additional argument (offset) for pread / pwrite; see the incr() functions
// above which do nothing if the offset is not present and increment it if it
// is.
template <class F, class... Offset>
ssize_t wrapFull(F f, int fd, void* buf, size_t count, Offset... offset) {
char* b = static_cast<char*>(buf);
ssize_t totalBytes = 0;
ssize_t r;
do {
r = f(fd, b, count, offset...);
if (r == -1) {
if (errno == EINTR) {
continue;
}
return r;
}
totalBytes += r;
b += r;
count -= r;
incr(r, offset...);
} while (r != 0 && count); // 0 means EOF
return totalBytes;
}
// Wrap call to readv/preadv/writev/pwritev(fd, iov, count, offset?) to
// retry on incomplete reads / writes.
template <class F, class... Offset>
ssize_t wrapvFull(F f, int fd, iovec* iov, int count, Offset... offset) {
ssize_t totalBytes = 0;
ssize_t r;
do {
r = f(fd, iov, std::min<int>(count, kIovMax), offset...);
if (r == -1) {
if (errno == EINTR) {
continue;
}
return r;
}
if (r == 0) {
break; // EOF
}
totalBytes += r;
incr(r, offset...);
while (r != 0 && count != 0) {
if (r >= ssize_t(iov->iov_len)) {
r -= ssize_t(iov->iov_len);
++iov;
--count;
} else {
iov->iov_base = static_cast<char*>(iov->iov_base) + r;
iov->iov_len -= r;
r = 0;
}
}
} while (count);
return totalBytes;
}
} // namespace fileutil_detail
} // namespace folly
| {
"content_hash": "cbe76c7f15e150ff3a26b0f5704cd103",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 79,
"avg_line_length": 23.842105263157894,
"alnum_prop": 0.5748344370860927,
"repo_name": "Orvid/folly",
"id": "d45cae862d504bc9c69d608bf8d3f588e0ac95d5",
"size": "2860",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "folly/detail/FileUtilDetail.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "4324"
},
{
"name": "C",
"bytes": "58996"
},
{
"name": "C++",
"bytes": "8487843"
},
{
"name": "CMake",
"bytes": "63672"
},
{
"name": "CSS",
"bytes": "165"
},
{
"name": "M4",
"bytes": "85007"
},
{
"name": "Makefile",
"bytes": "36824"
},
{
"name": "Python",
"bytes": "40534"
},
{
"name": "Ruby",
"bytes": "1531"
},
{
"name": "Shell",
"bytes": "8546"
}
],
"symlink_target": ""
} |
@implementation UIView (Frame)
- (CGFloat)left
{
return self.frame.origin.x;
}
- (void)setLeft:(CGFloat)x
{
CGRect frame = self.frame;
frame.origin.x = x;
self.frame = frame;
}
- (CGFloat)top
{
return self.frame.origin.y;
}
- (void)setTop:(CGFloat)y
{
CGRect frame = self.frame;
frame.origin.y = y;
self.frame = frame;
}
- (CGFloat)right
{
return self.frame.origin.x + self.frame.size.width;
}
- (void)setRight:(CGFloat)right
{
CGRect frame = self.frame;
frame.origin.x = right - frame.size.width;
self.frame = frame;
}
- (CGFloat)bottom
{
return self.frame.origin.y + self.frame.size.height;
}
- (void)setBottom:(CGFloat)bottom
{
CGRect frame = self.frame;
frame.origin.y = bottom - frame.size.height;
self.frame = frame;
}
- (CGPoint)topLeft
{
return self.frame.origin;
}
- (void)setTopLeft:(CGPoint)topLeft
{
CGRect frame = self.frame;
frame.origin = topLeft;
self.frame = frame;
}
- (CGFloat)centerX
{
return self.center.x;
}
- (void)setCenterX:(CGFloat)centerX
{
self.center = CGPointMake(centerX, self.center.y);
}
- (CGFloat)centerY
{
return self.center.y;
}
- (void)setCenterY:(CGFloat)centerY
{
self.center = CGPointMake(self.center.x, centerY);
}
- (CGPoint)boundsCenter
{
return CGPointMake(self.width/2, self.height/2);
}
- (CGFloat)width
{
return self.frame.size.width;
}
- (void)setWidth:(CGFloat)width
{
CGRect frame = self.frame;
frame.size.width = width;
self.frame = frame;
}
- (CGFloat)height
{
return self.frame.size.height;
}
- (void)setHeight:(CGFloat)height
{
CGRect frame = self.frame;
frame.size.height = height;
self.frame = frame;
}
- (CGFloat)ttScreenX
{
CGFloat x = 0;
for (UIView* view = self; view; view = view.superview) {
x += view.left;
}
return x;
}
- (CGFloat)ttScreenY
{
CGFloat y = 0;
for (UIView* view = self; view; view = view.superview) {
y += view.top;
}
return y;
}
- (CGFloat)screenViewX
{
CGFloat x = 0;
for (UIView* view = self; view; view = view.superview) {
x += view.left;
if ([view isKindOfClass:[UIScrollView class]]) {
UIScrollView* scrollView = (UIScrollView*)view;
x -= scrollView.contentOffset.x;
}
}
return x;
}
- (CGFloat)screenViewY
{
CGFloat y = 0;
for (UIView* view = self; view; view = view.superview) {
y += view.top;
if ([view isKindOfClass:[UIScrollView class]]) {
UIScrollView* scrollView = (UIScrollView*)view;
y -= scrollView.contentOffset.y;
}
}
return y;
}
- (CGRect)screenFrame
{
return CGRectMake(self.screenViewX, self.screenViewY, self.width, self.height);
}
- (CGPoint)origin
{
return self.frame.origin;
}
- (void)setOrigin:(CGPoint)origin
{
CGRect frame = self.frame;
frame.origin = origin;
self.frame = frame;
}
- (CGSize)size
{
return self.frame.size;
}
- (void)setSize:(CGSize)size
{
CGRect frame = self.frame;
frame.size = size;
self.frame = frame;
}
- (UIView*)descendantOrSelfWithClass:(Class)cls
{
if ([self isKindOfClass:cls])
return self;
for (UIView* child in self.subviews) {
UIView* it = [child descendantOrSelfWithClass:cls];
if (it)
return it;
}
return nil;
}
- (UIView*)ancestorOrSelfWithClass:(Class)cls
{
if ([self isKindOfClass:cls]) {
return self;
} else if (self.superview) {
return [self.superview ancestorOrSelfWithClass:cls];
} else {
return nil;
}
}
- (void)removeAllSubviews
{
while (self.subviews.count) {
UIView* child = self.subviews.lastObject;
[child removeFromSuperview];
}
}
@end
| {
"content_hash": "3c31f61308c25ddb1f6c5b0a0062b869",
"timestamp": "",
"source": "github",
"line_count": 223,
"max_line_length": 83,
"avg_line_length": 17.103139013452914,
"alnum_prop": 0.6095962244362874,
"repo_name": "chuangyi0128/UICategory",
"id": "575639acbd73ae01159a530bd76a240fa719a015",
"size": "3914",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "UIView+Frame.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "19592"
},
{
"name": "Ruby",
"bytes": "812"
}
],
"symlink_target": ""
} |
# -*- coding: utf-8 -*-
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# google-cloud-network-services documentation build configuration file
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath(".."))
# For plugins that can not read conf.py.
# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85
sys.path.insert(0, os.path.abspath("."))
__version__ = ""
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = "1.5.5"
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.autosummary",
"sphinx.ext.intersphinx",
"sphinx.ext.coverage",
"sphinx.ext.doctest",
"sphinx.ext.napoleon",
"sphinx.ext.todo",
"sphinx.ext.viewcode",
"recommonmark",
]
# autodoc/autosummary flags
autoclass_content = "both"
autodoc_default_options = {"members": True}
autosummary_generate = True
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = [".rst", ".md"]
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The root toctree document.
root_doc = "index"
# General information about the project.
project = "google-cloud-network-services"
copyright = "2019, Google"
author = "Google APIs"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The full version, including alpha/beta/rc tags.
release = __version__
# The short X.Y version.
version = ".".join(release.split(".")[0:2])
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = [
"_build",
"**/.nox/**/*",
"samples/AUTHORING_GUIDE.md",
"samples/CONTRIBUTING.md",
"samples/snippets/README.rst",
]
# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = "alabaster"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
"description": "Google Cloud Client Libraries for google-cloud-network-services",
"github_user": "googleapis",
"github_repo": "python-network-services",
"github_banner": True,
"font_family": "'Roboto', Georgia, sans",
"head_font_family": "'Roboto', Georgia, serif",
"code_font_family": "'Roboto Mono', 'Consolas', monospace",
}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
# html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
# html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
# html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = "google-cloud-network-services-doc"
# -- Options for warnings ------------------------------------------------------
suppress_warnings = [
# Temporarily suppress this to avoid "more than one target found for
# cross-reference" warning, which are intractable for us to avoid while in
# a mono-repo.
# See https://github.com/sphinx-doc/sphinx/blob
# /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843
"ref.python"
]
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(
root_doc,
"google-cloud-network-services.tex",
"google-cloud-network-services Documentation",
author,
"manual",
)
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(
root_doc,
"google-cloud-network-services",
"google-cloud-network-services Documentation",
[author],
1,
)
]
# If true, show URL addresses after external links.
# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(
root_doc,
"google-cloud-network-services",
"google-cloud-network-services Documentation",
author,
"google-cloud-network-services",
"google-cloud-network-services Library",
"APIs",
)
]
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
"python": ("https://python.readthedocs.org/en/latest/", None),
"google-auth": ("https://googleapis.dev/python/google-auth/latest/", None),
"google.api_core": (
"https://googleapis.dev/python/google-api-core/latest/",
None,
),
"grpc": ("https://grpc.github.io/grpc/python/", None),
"proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None),
"protobuf": ("https://googleapis.dev/python/protobuf/latest/", None),
}
# Napoleon settings
napoleon_google_docstring = True
napoleon_numpy_docstring = True
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = True
napoleon_use_admonition_for_examples = False
napoleon_use_admonition_for_notes = False
napoleon_use_admonition_for_references = False
napoleon_use_ivar = False
napoleon_use_param = True
napoleon_use_rtype = True
| {
"content_hash": "277164d861e18ebff4bcb2126a9efe9b",
"timestamp": "",
"source": "github",
"line_count": 384,
"max_line_length": 85,
"avg_line_length": 32.596354166666664,
"alnum_prop": 0.6928976591835104,
"repo_name": "googleapis/python-network-services",
"id": "750c55c202a7bfb82b10243cb10557f3e9ae2a87",
"size": "12517",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "docs/conf.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2050"
},
{
"name": "Python",
"bytes": "1361313"
},
{
"name": "Shell",
"bytes": "30690"
}
],
"symlink_target": ""
} |
/***** includes *****/
#include "lfds720_btree_nu_internal.h"
/****************************************************************************/
enum lfds720_btree_nu_insert_result lfds720_btree_nu_insert( struct lfds720_btree_nu_state *baus,
struct lfds720_btree_nu_element *baue,
struct lfds720_btree_nu_element **existing_baue )
{
char unsigned
result = 0;
int
compare_result = 0;
lfds720_pal_uint_t
backoff_iteration = LFDS720_BACKOFF_INITIAL_VALUE;
struct lfds720_btree_nu_element
*compare = NULL,
*volatile baue_next = NULL,
*volatile baue_parent = NULL,
*volatile baue_temp;
LFDS720_PAL_ASSERT( baus != NULL );
LFDS720_PAL_ASSERT( baue != NULL );
LFDS720_PAL_ASSERT( (lfds720_pal_uint_t) &baue->left % LFDS720_PAL_SINGLE_POINTER_LENGTH_IN_BYTES == 0 );
LFDS720_PAL_ASSERT( (lfds720_pal_uint_t) &baue->right % LFDS720_PAL_SINGLE_POINTER_LENGTH_IN_BYTES == 0 );
LFDS720_PAL_ASSERT( (lfds720_pal_uint_t) &baue->up % LFDS720_PAL_SINGLE_POINTER_LENGTH_IN_BYTES == 0 );
LFDS720_PAL_ASSERT( (lfds720_pal_uint_t) &baue->value % LFDS720_PAL_SINGLE_POINTER_LENGTH_IN_BYTES == 0 );
// TRD : existing_baue can be NULL
/* TRD : we follow a normal search for the insert node and which side to insert
the difference is that insertion may fail because someone else inserts
there before we do
in this case, we resume searching for the insert node from the node
we were attempting to insert upon
(if we attempted to insert the root node and this failed, i.e. we thought
the tree was empty but then it wasn't, then we start searching from the
new root)
*/
baue->up = baue->left = baue->right = NULL;
LFDS720_MISC_BARRIER_LOAD;
baue_temp = baus->root;
LFDS720_MISC_BARRIER_LOAD;
while( result == 0 )
{
// TRD : first we find where to insert
while( baue_temp != NULL )
{
compare_result = baus->key_compare_function( baue->key, baue_temp->key );
if( compare_result == 0 )
{
if( existing_baue != NULL )
*existing_baue = baue_temp;
switch( baus->existing_key )
{
case LFDS720_BTREE_NU_EXISTING_KEY_OVERWRITE:
LFDS720_BTREE_NU_SET_VALUE_IN_ELEMENT( *baue_temp, baue->value );
return LFDS720_BTREE_NU_INSERT_RESULT_SUCCESS_OVERWRITE;
break;
case LFDS720_BTREE_NU_EXISTING_KEY_FAIL:
return LFDS720_BTREE_NU_INSERT_RESULT_FAILURE_EXISTING_KEY;
break;
}
}
if( compare_result < 0 )
baue_next = baue_temp->left;
if( compare_result > 0 )
baue_next = baue_temp->right;
baue_parent = baue_temp;
baue_temp = baue_next;
if( baue_temp != NULL )
LFDS720_MISC_BARRIER_LOAD;
}
/* TRD : second, we actually insert
at this point baue_temp has come to NULL
and baue_parent is the element to insert at
and result of the last compare indicates
the direction of insertion
it may be that another tree has already inserted an element with
the same key as ourselves, or other elements which mean our position
is now wrong
in this case, it is either inserted in the position we're trying
to insert in now, in which case our insert will fail
or, similarly, other elements will have come in where we are,
and our insert will fail
*/
if( baue_parent == NULL )
{
compare = NULL;
baue->up = baus->root;
LFDS720_MISC_BARRIER_STORE;
LFDS720_PAL_ATOMIC_CAS( baus->root, compare, baue, LFDS720_MISC_CAS_STRENGTH_WEAK, result );
if( result == 0 )
baue_temp = baus->root;
}
if( baue_parent != NULL )
{
if( compare_result <= 0 )
{
compare = NULL;
baue->up = baue_parent;
LFDS720_MISC_BARRIER_STORE;
LFDS720_PAL_ATOMIC_CAS( baue_parent->left, compare, baue, LFDS720_MISC_CAS_STRENGTH_WEAK, result );
}
if( compare_result > 0 )
{
compare = NULL;
baue->up = baue_parent;
LFDS720_MISC_BARRIER_STORE;
LFDS720_PAL_ATOMIC_CAS( baue_parent->right, compare, baue, LFDS720_MISC_CAS_STRENGTH_WEAK, result );
}
// TRD : if the insert fails, then resume searching at the insert node
if( result == 0 )
baue_temp = baue_parent;
}
if( result == 0 )
LFDS720_BACKOFF_EXPONENTIAL_BACKOFF( baus->insert_backoff, backoff_iteration );
}
LFDS720_BACKOFF_AUTOTUNE( baus->insert_backoff, backoff_iteration );
// TRD : if we get to here, we added (not failed or overwrite on exist) a new element
if( existing_baue != NULL )
*existing_baue = NULL;
return LFDS720_BTREE_NU_INSERT_RESULT_SUCCESS;
}
| {
"content_hash": "3ab0a6d024819f0466d8becd12b551c6",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 110,
"avg_line_length": 31.563291139240505,
"alnum_prop": 0.5935432123521155,
"repo_name": "grz0zrg/fas",
"id": "9b08c7093bde5d6c7370a0a3541788fdd204beab",
"size": "4987",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/liblfds7.2.0/src/liblfds720/src/lfds720_btree_nodelete_unbalanced/lfds720_btree_nu_insert.c",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "8830"
},
{
"name": "C",
"bytes": "1721009"
},
{
"name": "C++",
"bytes": "82947"
},
{
"name": "CMake",
"bytes": "26182"
},
{
"name": "Faust",
"bytes": "618"
},
{
"name": "HTML",
"bytes": "17050"
},
{
"name": "Makefile",
"bytes": "39086"
},
{
"name": "Python",
"bytes": "2130"
},
{
"name": "Shell",
"bytes": "1120"
}
],
"symlink_target": ""
} |
struct GameContact
{
b2Body *bodyA;
b2Body *bodyB;
b2Fixture *fixtureA;
b2Fixture *fixtureB;
bool begin;
// bool operator == (const MyContact& other) const {
// return (fixtureA == other.fixtureA) && (fixtureB == other.fixtureB);
// }
};
class GameContactListener : public b2ContactListener
{
public:
std::vector<GameContact>_contacts;
GameContactListener();
~GameContactListener();
virtual void BeginContact(b2Contact* contact);
virtual void EndContact(b2Contact* contact);
// virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold);
// virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse);
};
| {
"content_hash": "36ec9a33258cba7dfbe8e3f0fadb1c96",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 80,
"avg_line_length": 27.88,
"alnum_prop": 0.697274031563845,
"repo_name": "johndpope/FinalFighter-mac",
"id": "7dadb234517388929d0083eef8cc8d4bd1e1e21e",
"size": "754",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "FinalFighter-mac/Source/GameContactListener.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "263643"
},
{
"name": "C++",
"bytes": "977718"
},
{
"name": "CMake",
"bytes": "6592"
},
{
"name": "Matlab",
"bytes": "1875"
},
{
"name": "Objective-C",
"bytes": "1466178"
},
{
"name": "Objective-C++",
"bytes": "162622"
},
{
"name": "PHP",
"bytes": "14077"
},
{
"name": "Shell",
"bytes": "764"
}
],
"symlink_target": ""
} |
package org.apache.hc.client5.http.entity.mime;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.util.Args;
/**
* Builder for multipart {@link HttpEntity}s.
*
* @since 4.3
*/
public class MultipartEntityBuilder {
/**
* The pool of ASCII chars to be used for generating a multipart boundary.
*/
private final static char[] MULTIPART_CHARS =
"-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
.toCharArray();
private final static String DEFAULT_SUBTYPE = "form-data";
private ContentType contentType;
private HttpMultipartMode mode = HttpMultipartMode.STRICT;
private String boundary = null;
private Charset charset = null;
private List<FormBodyPart> bodyParts = null;
public static MultipartEntityBuilder create() {
return new MultipartEntityBuilder();
}
MultipartEntityBuilder() {
}
public MultipartEntityBuilder setMode(final HttpMultipartMode mode) {
this.mode = mode;
return this;
}
public MultipartEntityBuilder setLaxMode() {
this.mode = HttpMultipartMode.BROWSER_COMPATIBLE;
return this;
}
public MultipartEntityBuilder setStrictMode() {
this.mode = HttpMultipartMode.STRICT;
return this;
}
public MultipartEntityBuilder setBoundary(final String boundary) {
this.boundary = boundary;
return this;
}
/**
* @since 4.4
*/
public MultipartEntityBuilder setMimeSubtype(final String subType) {
Args.notBlank(subType, "MIME subtype");
this.contentType = ContentType.create("multipart/" + subType);
return this;
}
/**
* @since 4.5
*/
public MultipartEntityBuilder setContentType(final ContentType contentType) {
Args.notNull(contentType, "Content type");
this.contentType = contentType;
return this;
}
public MultipartEntityBuilder setCharset(final Charset charset) {
this.charset = charset;
return this;
}
/**
* @since 4.4
*/
public MultipartEntityBuilder addPart(final FormBodyPart bodyPart) {
if (bodyPart == null) {
return this;
}
if (this.bodyParts == null) {
this.bodyParts = new ArrayList<>();
}
this.bodyParts.add(bodyPart);
return this;
}
public MultipartEntityBuilder addPart(final String name, final ContentBody contentBody) {
Args.notNull(name, "Name");
Args.notNull(contentBody, "Content body");
return addPart(FormBodyPartBuilder.create(name, contentBody).build());
}
public MultipartEntityBuilder addTextBody(
final String name, final String text, final ContentType contentType) {
return addPart(name, new StringBody(text, contentType));
}
public MultipartEntityBuilder addTextBody(
final String name, final String text) {
return addTextBody(name, text, ContentType.DEFAULT_TEXT);
}
public MultipartEntityBuilder addBinaryBody(
final String name, final byte[] b, final ContentType contentType, final String filename) {
return addPart(name, new ByteArrayBody(b, contentType, filename));
}
public MultipartEntityBuilder addBinaryBody(
final String name, final byte[] b) {
return addBinaryBody(name, b, ContentType.DEFAULT_BINARY, null);
}
public MultipartEntityBuilder addBinaryBody(
final String name, final File file, final ContentType contentType, final String filename) {
return addPart(name, new FileBody(file, contentType, filename));
}
public MultipartEntityBuilder addBinaryBody(
final String name, final File file) {
return addBinaryBody(name, file, ContentType.DEFAULT_BINARY, file != null ? file.getName() : null);
}
public MultipartEntityBuilder addBinaryBody(
final String name, final InputStream stream, final ContentType contentType,
final String filename) {
return addPart(name, new InputStreamBody(stream, contentType, filename));
}
public MultipartEntityBuilder addBinaryBody(final String name, final InputStream stream) {
return addBinaryBody(name, stream, ContentType.DEFAULT_BINARY, null);
}
private String generateBoundary() {
final StringBuilder buffer = new StringBuilder();
final Random rand = new Random();
final int count = rand.nextInt(11) + 30; // a random size from 30 to 40
for (int i = 0; i < count; i++) {
buffer.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
}
return buffer.toString();
}
MultipartFormEntity buildEntity() {
String boundaryCopy = boundary;
if (boundaryCopy == null && contentType != null) {
boundaryCopy = contentType.getParameter("boundary");
}
if (boundaryCopy == null) {
boundaryCopy = generateBoundary();
}
Charset charsetCopy = charset;
if (charsetCopy == null && contentType != null) {
charsetCopy = contentType.getCharset();
}
final List<NameValuePair> paramsList = new ArrayList<>(2);
paramsList.add(new BasicNameValuePair("boundary", boundaryCopy));
if (charsetCopy != null) {
paramsList.add(new BasicNameValuePair("charset", charsetCopy.name()));
}
final NameValuePair[] params = paramsList.toArray(new NameValuePair[paramsList.size()]);
final ContentType contentTypeCopy = contentType != null ?
contentType.withParameters(params) :
ContentType.create("multipart/" + DEFAULT_SUBTYPE, params);
final List<FormBodyPart> bodyPartsCopy = bodyParts != null ? new ArrayList<>(bodyParts) :
Collections.<FormBodyPart>emptyList();
final HttpMultipartMode modeCopy = mode != null ? mode : HttpMultipartMode.STRICT;
final AbstractMultipartForm form;
switch (modeCopy) {
case BROWSER_COMPATIBLE:
form = new HttpBrowserCompatibleMultipart(charsetCopy, boundaryCopy, bodyPartsCopy);
break;
case RFC6532:
form = new HttpRFC6532Multipart(charsetCopy, boundaryCopy, bodyPartsCopy);
break;
case RFC7578:
if (charsetCopy == null) {
charsetCopy = StandardCharsets.UTF_8;
}
form = new HttpRFC7578Multipart(charsetCopy, boundaryCopy, bodyPartsCopy);
break;
default:
form = new HttpStrictMultipart(StandardCharsets.US_ASCII, boundaryCopy, bodyPartsCopy);
}
return new MultipartFormEntity(form, contentTypeCopy, form.getTotalLength());
}
public HttpEntity build() {
return buildEntity();
}
}
| {
"content_hash": "5384ad1e445b4420eff0edc803c486cd",
"timestamp": "",
"source": "github",
"line_count": 210,
"max_line_length": 107,
"avg_line_length": 34.90952380952381,
"alnum_prop": 0.6524348656390669,
"repo_name": "UlrichColby/httpcomponents-client",
"id": "441b1c56f574dc62806b156f7840809ff70300dd",
"size": "8514",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "httpclient5/src/main/java/org/apache/hc/client5/http/entity/mime/MultipartEntityBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "21611"
},
{
"name": "CSS",
"bytes": "5273"
},
{
"name": "Java",
"bytes": "3003244"
},
{
"name": "XSLT",
"bytes": "26167"
}
],
"symlink_target": ""
} |
<?php
/* This file is part of the Staq project, which is under MIT license */
namespace Staq\Core\Ground\Stack;
class Exception extends \Exception
{
/* ATTRIBUTES
*************************************************************************/
protected $defaultMessage = NULL;
protected $defaultCode = 0;
/* CONSTRUCTOR
*************************************************************************/
public function __construct($message = NULL, $code = NULL, \Exception $previous = NULL)
{
if (is_null($message)) $message = $this->defaultMessage;
if (is_null($message)) $message = \Staq\Util::getStackSubQueryText($this);
if (is_null($code)) $code = $this->defaultCode;
parent::__construct($message, $code, $previous);
}
public function fromPrevious(\Exception $previous)
{
$class = get_class($this);
return new $class(NULL, NULL, $previous);
}
}
?> | {
"content_hash": "a31d862cd1a745f1c60e50a8fc992d6e",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 91,
"avg_line_length": 27.057142857142857,
"alnum_prop": 0.5216473072861668,
"repo_name": "Elephant418/Staq",
"id": "1742a3c4c4f7fc40e67af86205be488b32a3cbc0",
"size": "947",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Staq/Core/Ground/Stack/Exception.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "384"
},
{
"name": "CSS",
"bytes": "20933"
},
{
"name": "HTML",
"bytes": "18860"
},
{
"name": "JavaScript",
"bytes": "4197"
},
{
"name": "PHP",
"bytes": "188178"
}
],
"symlink_target": ""
} |
class C_BaseAnimatingOverlay : public C_BaseAnimating
{
public:
DECLARE_CLASS( C_BaseAnimatingOverlay, C_BaseAnimating );
DECLARE_CLIENTCLASS();
DECLARE_PREDICTABLE();
DECLARE_INTERPOLATION();
C_BaseAnimatingOverlay();
virtual CStudioHdr *OnNewModel();
C_AnimationLayer* GetAnimOverlay( int i );
void SetNumAnimOverlays( int num ); // This makes sure there is space for this # of layers.
int GetNumAnimOverlays() const;
virtual void GetRenderBounds( Vector& theMins, Vector& theMaxs );
void CheckForLayerChanges( CStudioHdr *hdr, float currentTime );
// model specific
virtual void AccumulateLayers( IBoneSetup &boneSetup, Vector pos[], Quaternion q[], float currentTime );
virtual void DoAnimationEvents( CStudioHdr *pStudioHdr );
enum
{
MAX_OVERLAYS = 15,
};
CUtlVector < C_AnimationLayer > m_AnimOverlay;
CUtlVector < CInterpolatedVar< C_AnimationLayer > > m_iv_AnimOverlay;
float m_flOverlayPrevEventCycle[ MAX_OVERLAYS ];
private:
C_BaseAnimatingOverlay( const C_BaseAnimatingOverlay & ); // not defined, not accessible
};
EXTERN_RECV_TABLE(DT_BaseAnimatingOverlay);
#endif // C_BASEANIMATINGOVERLAY_H
| {
"content_hash": "aea2a4e89b1ad05c26ce39c8914c56aa",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 105,
"avg_line_length": 23.510204081632654,
"alnum_prop": 0.7534722222222222,
"repo_name": "BerntA/tfo-code",
"id": "de0067dd21bfa8caa761f5deaa59e92daf1b9f7d",
"size": "1537",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "game/client/c_baseanimatingoverlay.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "238"
},
{
"name": "Batchfile",
"bytes": "9897"
},
{
"name": "C",
"bytes": "1255315"
},
{
"name": "C++",
"bytes": "39642849"
},
{
"name": "GLSL",
"bytes": "126492"
},
{
"name": "Makefile",
"bytes": "28908"
},
{
"name": "Objective-C",
"bytes": "72895"
},
{
"name": "Objective-C++",
"bytes": "369"
},
{
"name": "Perl",
"bytes": "93035"
},
{
"name": "Perl 6",
"bytes": "1820"
},
{
"name": "Shell",
"bytes": "1362"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="org.lactor.consultant.authentication.ui.LoginActivity"
android:background="#009688"
android:scaleType="centerCrop">
<LinearLayout
android:paddingTop="100dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation= "vertical"
android:weightSum="1"
android:layout_gravity="top|bottom|right"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="LACTOR Android"
android:padding="10dp"
android:textColor="#fff"
android:textStyle= "bold"
android:textSize="32sp"
android:gravity="center|top"
android:layout_weight="0.15"
android:layout_gravity="center_horizontal" />
<EditText
android:id="@+id/email_edittext"
android:padding= "20dp"
android:textColor="#fff"
android:gravity="center"
android:textColorHint="#fff"
android:background="@drawable/edittextstyle"
android:layout_width="300dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:textStyle="bold"
android:hint="Username"/>
<EditText
android:id="@+id/password"
android:textColor="#fff"
android:gravity="center"
android:textColorHint="#fff"
android:background="@drawable/edittextstyle"
android:layout_marginTop="10dp"
android:layout_width="300dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:textStyle="bold"
android:inputType="textPassword"
android:hint="Password"/>
<Button
android:id="@+id/login_button"
android:gravity="center"
android:textColor="#009688"
android:background="#fff"
android:layout_marginTop="50dp"
android:layout_width="match_parent"
android:text="Login"
android:layout_height="60dp"
android:padding="15dp"
android:layout_weight="0.36" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Forgot Password?"
android:textColor="#fff"
android:background="#009688"
android:layout_gravity="right"
android:padding="15dp"
/>
<Button
android:id="@+id/register_button"
android:textColor="#fff"
android:text = "@string/button_register"
android:gravity="center"
android:textColorHint="#fff"
android:background="#009688"
android:layout_marginTop="5dp"
android:layout_width="300dp"
android:layout_height="40dp"
android:layout_gravity="center"
android:textStyle="bold"
android:textSize="15sp"
android:hint="Register"/>
</LinearLayout>
</RelativeLayout>
| {
"content_hash": "87e41d83cc81c6187f8d4c59bcaff377",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 73,
"avg_line_length": 35.23364485981308,
"alnum_prop": 0.593103448275862,
"repo_name": "ambi-disc/lactation-android",
"id": "5a64b688b27b3b08b9f8861134830e08bfd24cf1",
"size": "3770",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/activity_login.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "154116"
}
],
"symlink_target": ""
} |
var EventEmitter = require('events').EventEmitter,
on = require('../on'),
off = require('../off')
var emitter = new EventEmitter()
var handleRequest = function (request) {
console.log('node event handled')
}
on(emitter, 'request', handleRequest)
emitter.emit('request')
off(emitter, 'request', handleRequest)
console.log('node event has been unbound, thus another event should not have triggered')
| {
"content_hash": "0cc1466aad954f37db866eaf09043765",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 88,
"avg_line_length": 25.58823529411765,
"alnum_prop": 0.6758620689655173,
"repo_name": "Georgette/whax",
"id": "499dabe505a1e01396c10af2b092ed9e5148f19f",
"size": "435",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "example/node-example.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "4541"
},
{
"name": "Makefile",
"bytes": "1665"
}
],
"symlink_target": ""
} |
from flask import abort
from flask.ext.security import current_user
def require_editor(f):
def _(*args, **kwargs):
if current_user.has_role('editor') and not current_user.has_role('admin'):
return abort(403)
return f(*args, **kwargs)
return _
def require_admin(f):
def _(*args, **kwargs):
if not current_user.has_role('admin'):
return abort(403)
return f(*args, **kwargs)
return _
| {
"content_hash": "da9b4acf1138d9be324f4395b794849d",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 82,
"avg_line_length": 25.38888888888889,
"alnum_prop": 0.5973741794310722,
"repo_name": "ktmud/david",
"id": "8e5b4d2801134d95df4c5aef1b26d74df62d53fd",
"size": "481",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "david/core/accounts/utils.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "83881"
},
{
"name": "JavaScript",
"bytes": "281633"
},
{
"name": "PHP",
"bytes": "2274"
},
{
"name": "Python",
"bytes": "82385"
}
],
"symlink_target": ""
} |
package cn.easyproject.easyee.sh.base.util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Spring工具类
* @author easyproject.cn
*
*/
@SuppressWarnings("unchecked")
public class SpringUtil {
static ApplicationContext ac=new ClassPathXmlApplicationContext("spring/ApplicationContext.xml");
public static <T> T getBean(String name){
return (T) ac.getBean(name);
}
}
| {
"content_hash": "d3378d8d06c89b159fe2983780a4ebfb",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 98,
"avg_line_length": 24.42105263157895,
"alnum_prop": 0.7844827586206896,
"repo_name": "ushelp/EasyEE",
"id": "98827c9a02b0a9b0921a7f3dd7fd76c76b8e3e2f",
"size": "470",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "project/easyee-sh/src/main/java/cn/easyproject/easyee/sh/base/util/SpringUtil.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "51834855"
}
],
"symlink_target": ""
} |
* [ ] Which version are you using? (Is it latest?)
* [ ] Are you reporting to the correct repository?
* [ ] Did you search existing issues? (Were any related?)
### Description
<!-- Description of the bug or feature -->
### Steps to Reproduce the issue
1. When I do X
2. Then Y
3. I see behavior Z
**Expected behavior:** (What you expected to happen)
**Actual behavior:** (What actually happened)
### CodeSandbox With Reproduction of Issue:
- [Basic Template](https://codesandbox.io/s/cornerstone-basic-issue-template-9slk4)
| {
"content_hash": "66921d9976a9425e8b66503547f46b6a",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 83,
"avg_line_length": 24.227272727272727,
"alnum_prop": 0.7035647279549718,
"repo_name": "chafey/cornerstoneTools",
"id": "6aabb83f7c99b34a4333c2c0cc2b52eb231fc157",
"size": "552",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": ".github/ISSUE_TEMPLATE.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "435347"
}
],
"symlink_target": ""
} |
.form-print-wrapper {
border: 1px solid #d1d8dd;
border-top: none;
}
.print-preview-wrapper {
padding: 30px 0px;
background-color: #f5f7fa;
}
.print-toolbar {
margin: 0px;
padding: 10px 0px;
border-bottom: 1px solid #d1d8dd;
}
.print-toolbar > div {
padding-right: 0px;
}
.print-toolbar > div:last-child {
padding-right: 15px;
}
.form-inner-toolbar {
padding: 10px 15px 0px;
background-color: #fafbfc;
text-align: right;
}
.form-inner-toolbar .btn {
margin-bottom: 10px;
}
.form-clickable-section {
border-top: 1px solid #d1d8dd;
padding: 10px 15px;
background-color: #F7FAFC;
}
.form-page.second-page {
border-top: 1px solid #d1d8dd;
}
.form-message {
padding: 15px 30px;
border-bottom: 1px solid #d1d8dd;
}
.document-flow-wrapper {
padding: 40px 15px 30px;
font-size: 12px;
border-bottom: 1px solid #EBEFF2;
}
.document-flow-wrapper .document-flow {
display: inline-block;
position: relative;
left: 50%;
transform: translateX(-50%);
}
.document-flow-wrapper .document-flow .document-flow-link-wrapper {
width: 140px;
display: inline-block;
}
.document-flow-wrapper .document-flow .document-flow-link-wrapper:not(:last-child) {
border-top: 1px solid #b8c2cc;
margin-right: -4px;
}
.document-flow-wrapper .document-flow .document-flow-link-wrapper:last-child {
margin-right: -140px;
}
.document-flow-wrapper .document-flow .document-flow-link {
margin-top: -10px;
display: inline-block;
}
.document-flow-wrapper .document-flow .document-flow-link:not(.disabled):hover .document-flow-link-label,
.document-flow-wrapper .document-flow .document-flow-link:not(.disabled):focus .document-flow-link-label,
.document-flow-wrapper .document-flow .document-flow-link:not(.disabled):active .document-flow-link-label {
text-decoration: underline;
}
.document-flow-wrapper .document-flow .document-flow-link-label {
display: inline-block;
margin-left: -50%;
margin-top: 5px;
}
@media (max-width: 767px) {
.document-flow-wrapper {
display: none;
}
}
.form-dashboard {
background-color: #fafbfc;
}
.form-dashboard-wrapper {
margin: -15px 0px;
}
.form-documents h6 {
margin-top: 15px;
}
.form-dashboard-section {
margin: 0px -15px;
padding: 15px 30px;
border-bottom: 1px solid #EBEFF2;
}
.form-dashboard-section:first-child {
padding-top: 0px;
}
.form-dashboard-section:last-child {
border-bottom: none;
}
.form-heatmap .heatmap {
display: flex;
justify-content: center;
}
.form-heatmap .heatmap-message {
margin-top: 10px;
}
@media (max-width: 991px) {
.form-heatmap {
overflow: hidden;
overflow-x: scroll;
}
}
.inline-graph .inline-graph-half {
width: 48%;
display: inline-block;
position: relative;
height: 30px;
}
.inline-graph .inline-graph-half .inline-graph-count {
font-size: 10px;
position: absolute;
left: 0;
right: 0;
top: 3px;
padding: 0px 5px;
text-align: left;
}
.inline-graph .inline-graph-half .inline-graph-bar {
position: absolute;
left: 0;
right: 0;
top: 20px;
}
.inline-graph .inline-graph-half .inline-graph-bar-inner {
display: block;
float: left;
background-color: #d1d8dd;
height: 6px;
border-radius: 0px 3px 3px 0px;
}
.inline-graph .inline-graph-half .inline-graph-bar-inner.dark {
background-color: #36414C;
}
.inline-graph .inline-graph-half:first-child {
border-right: 1px solid #d1d8dd;
margin-right: -3px;
}
.inline-graph .inline-graph-half:first-child .inline-graph-count {
text-align: right;
}
.inline-graph .inline-graph-half:first-child .inline-graph-bar-inner {
float: right;
border-radius: 3px 0px 0px 3px;
}
.progress-area {
padding-top: 15px;
padding-bottom: 15px;
}
.form-links .document-link {
margin-bottom: 10px;
height: 22px;
}
.form-links .document-link:hover .badge-link {
text-decoration: underline;
}
.form-links .document-link:hover .badge-link[disabled='disabled'] {
text-decoration: none;
}
.form-links .count {
display: inline-block;
margin-left: 5px;
margin-right: 5px;
}
h6.uppercase,
.h6.uppercase {
font-size: 11px;
font-weight: normal;
letter-spacing: 0.4px;
text-transform: uppercase;
color: #8D99A6;
}
.form-section {
margin: 0px;
padding: 15px;
}
.form-section .form-section-description {
margin-bottom: 10px;
}
.form-section .form-section-heading {
margin: 10px 0px;
}
.form-section .section-head {
margin: 0px 0px 15px 15px;
cursor: pointer;
}
.form-section .section-head .collapse-indicator {
color: #d1d8dd;
margin-left: 10px;
position: relative;
bottom: -1px;
}
.form-section .section-head .collapse-indicator.octicon-chevron-up {
bottom: -2px;
}
.form-section .section-head.collapsed {
margin-bottom: 0px;
}
.form-section:not(:last-child),
.form-inner-toolbar {
border-bottom: 1px solid #d1d8dd;
}
.empty-section {
display: none !important;
}
.modal .form-layout {
margin: -15px;
}
.modal .form-grid .form-layout {
margin: 0px;
}
.modal .form-section {
padding: 15px 7px;
}
.help ol {
padding-left: 19px;
}
.field_description_top {
margin-bottom: 3px;
}
.user-actions {
margin-bottom: 15px;
}
.user-actions a {
font-weight: bold;
}
.badge-important {
background-color: #e74c3c;
}
.address-box {
background-color: #fafbfc;
padding: 0px 15px;
margin: 15px 0px;
border: 1px solid #d1d8dd;
border-radius: 3px;
font-size: 12px;
}
.timeline {
margin: 30px 0px;
}
.timeline .timeline-head .comment-input {
height: auto;
}
.timeline-item {
margin-top: 0px;
}
.timeline-item b {
color: #36414C !important;
}
.timeline-item blockquote {
font-size: inherit;
}
.timeline-item .btn-more {
margin-left: 65px;
}
.timeline-item .gmail_extra {
display: none;
}
.timeline-items {
position: relative;
}
.timeline {
position: relative;
}
.timeline::before {
content: " ";
border-left: 1px solid #d1d8dd;
position: absolute;
top: 0px;
bottom: -124px;
left: 43px;
z-index: 0;
}
.timeline.in-dialog::before {
bottom: 0px;
}
@media (max-width: 991px) {
.timeline::before {
bottom: -64px;
}
}
.timeline-item.user-content {
margin: 30px 0px 30px 27px;
}
.timeline-item.user-content .media-body {
border: 1px solid #d1d8dd;
border-radius: 3px;
margin-left: -7px;
position: relative;
max-width: calc(100% - 50px);
padding-right: 0px;
overflow: visible;
}
.timeline-item.user-content .avatar-medium {
margin-right: 10px;
height: 45px;
width: 45px;
}
.timeline-item.user-content .action-btns {
position: absolute;
right: 0;
padding: 8px 15px 0 5px;
}
.timeline-item.user-content .action-btns .edit-btn-container {
margin-right: 13px;
}
.timeline-item.user-content .comment-header {
background-color: #fafbfc;
padding: 10px 15px 8px 13px;
margin: 0px;
color: #8D99A6;
border-bottom: 1px solid #EBEFF2;
}
.timeline-item.user-content .comment-header.links-active {
padding-right: 77px;
}
.timeline-item.user-content .comment-header .asset-details {
display: inline-block;
width: 100%;
}
.timeline-item.user-content .comment-header .asset-details .btn-link {
border: 0;
border-radius: 0;
padding: 0;
}
.timeline-item.user-content .comment-header .asset-details .btn-link:hover {
text-decoration: none;
}
.timeline-item.user-content .comment-header .commented-on-small {
display: none;
}
.timeline-item.user-content .comment-header .octicon-heart {
color: #ff5858;
cursor: pointer;
}
.timeline-item.user-content .reply {
padding: 15px;
overflow: auto;
}
.timeline-item.user-content .reply > div > p:first-child {
margin-top: 0px;
}
.timeline-item.user-content .reply > div > p:last-child {
margin-bottom: 0px;
}
.timeline-item.user-content .reply hr {
margin: 10px 0px;
}
.timeline-item.user-content .close-btn-container .close {
color: inherit;
opacity: 1;
padding: 0;
font-size: 18px;
}
.timeline-item.user-content .edit-btn-container {
padding: 0;
}
.timeline-item.user-content .edit-btn-container .edit {
color: inherit;
font-size: 21px;
line-height: 1;
}
.timeline-item.user-content .edit-btn-container .edit .octicon-check {
font-size: 1em;
}
.timeline-item.user-content .edit-btn-container .edit:hover,
.timeline-item.user-content .edit-btn-container .edit:focus {
color: #000;
}
.timeline-item.user-content .comment-likes {
margin-left: 5px;
}
.timeline-item.user-content .media-body:after,
.timeline-item.user-content .media-body:before {
right: 100%;
top: 15px;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
}
.timeline-item.user-content .media-body:after {
border-color: rgba(136, 183, 213, 0);
border-right-color: #fafbfc;
border-width: 6px;
margin-top: -6px;
}
.timeline-item.user-content .media-body:before {
border-color: rgba(194, 225, 245, 0);
border-right-color: #d1d8dd;
border-width: 7px;
margin-top: -7px;
}
.timeline-item.notification-content {
padding-left: 30px;
margin: 30px 0px;
position: relative;
color: #8D99A6;
}
.timeline-item.notification-content * {
color: #8D99A6;
}
.timeline-item.notification-content .fa-fw {
margin-left: 36px;
}
.timeline-item.notification-content div.small {
padding-left: 40px;
}
.timeline-item.notification-content div.small .fa-fw {
margin-left: 0px;
}
.timeline-item.notification-content .octicon-heart {
color: #ff5858 !important;
}
.timeline-item.notification-content::before {
content: " ";
width: 7px;
height: 7px;
background-color: #d1d8dd;
position: absolute;
left: 40px;
border-radius: 50%;
top: 5px;
}
.timeline-item .reply-link {
margin-left: 15px;
font-size: 12px;
}
.timeline-head {
background-color: white;
border: 1px solid #d1d8dd;
border-radius: 3px;
position: relative;
z-index: 1;
}
.timeline-head .comment-input-header {
background-color: #fafbfc;
padding: 7px 15px;
border-bottom: 1px solid #EBEFF2;
}
.timeline-head .comment-input-container {
padding: 15px;
}
.timeline-head .comment-input-container .awesomplete > ul {
min-width: 200px;
}
.timeline-head .comment-input {
border-color: #EBEFF2;
max-width: 100%;
}
.timeline-head .comment-input:focus {
box-shadow: none;
}
@media (max-width: 767px) {
.timeline-head {
border-left: none;
border-right: none;
border-radius: 0px;
}
}
.signature-field {
min-height: 300px;
background: #fff;
border: 1px solid #d1d8dd;
border-radius: 3px;
position: relative;
margin-top: -10px;
}
.signature-display {
margin: 7px 0px;
background: #fff;
}
.signature-btn-row {
position: absolute;
bottom: 12px;
right: 12px;
}
.signature-reset {
z-index: 10;
height: 30px;
width: 30px;
padding: 4px 0px;
}
.signature-img {
background: #fff;
border-radius: 3px;
margin-top: 5px;
max-height: 150px;
}
.timeline-new-email {
margin: 30px 0px;
padding-left: 70px;
position: relative;
}
.timeline-new-email::before {
content: " ";
width: 7px;
height: 7px;
background-color: #d1d8dd;
position: absolute;
left: 40px;
border-radius: 50%;
top: 5px;
}
.form-footer h5 {
margin: 15px 0px;
font-weight: bold;
}
.control-label,
.grid-heading-row {
color: #8D99A6;
font-size: 12px;
}
.control-label {
margin-bottom: 5px;
font-weight: normal;
}
.like-disabled-input {
margin-bottom: 7px;
min-height: 30px;
font-weight: bold;
background-color: #f5f7fa;
padding: 5px 10px;
border-radius: 3px;
}
.disabled-check {
color: #f5f7fa;
margin-right: 3px;
margin-bottom: -2px;
}
.like-disabled-input.for-description {
font-weight: normal;
font-size: 12px;
}
.frappe-control {
margin-bottom: 10px;
}
.frappe-control .help-box {
margin-top: 3px;
}
.frappe-control pre {
white-space: pre-wrap;
background-color: inherit;
border: none;
padding: 0px;
margin: 0px;
}
.flex-justify-center {
display: flex;
justify-content: center;
}
.flex-justify-end {
display: flex;
justify-content: flex-end;
}
.hide-control {
display: none !important;
}
.shared-user {
margin-bottom: 10px;
}
.attach-missing-image,
.attach-image-display {
cursor: pointer;
}
select.form-control {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
.form-control.bold {
color: #000;
font-weight: bold;
background-color: #fffdf4;
}
.form-control[data-fieldtype="Password"] {
position: inherit;
}
.password-strength-indicator {
float: right;
padding: 15px;
margin-top: -41px;
margin-right: -7px;
}
.password-strength-message {
margin-top: -10px;
}
.control-code,
.control-code.bold {
height: 400px;
font-family: Monaco, "Courier New", monospace;
color: #36414C;
font-size: 12px;
line-height: 1.7em;
}
.delivery-status-indicator {
display: inline-block;
margin-top: -3px;
margin-left: 1px;
font-weight: 500;
color: #8D99A6;
}
.attach-btn {
margin-top: 10px;
}
@media (min-width: 768px) {
.layout-main .form-column.col-sm-12 > form > .input-max-width {
max-width: 50%;
padding-right: 15px;
}
.col-sm-6 .form-grid .form-column.col-sm-12 > form > .input-max-width {
max-width: none;
padding-right: 0px;
}
.form-column.col-sm-6 textarea[data-fieldtype="Code"] {
height: 120px !important;
}
}
@media (max-width: 991px) {
.form-section .form-section-heading {
margin-top: 10px;
}
}
@media (max-width: 767px) {
.form-section .section-head {
padding: 15px 15px 15px 0px;
}
.form-section .section-body .form-column:first-child .radio,
.form-section .section-body .form-column:first-child .checkbox {
margin-top: 0;
}
.form-column {
border-bottom: 1px solid #EBEFF2;
padding-top: 15px;
padding-bottom: 15px;
}
.form-column:last-child {
border-bottom: 0px;
}
.form-section {
padding-left: 0px !important;
padding-right: 0px !important;
}
.form-grid {
margin-left: -17px;
margin-right: -17px;
border-left: none !important;
border-right: none !important;
border-radius: none;
}
.form-page .form-section {
padding: 0px 15px;
}
.frappe-control.form-page {
padding: 7px 15px;
border-bottom: 1px solid #EBEFF2;
margin: 0px -15px;
}
.frappe-control.form-page .link-btn {
top: -2px;
}
.frappe-control.form-page .like-disabled-input {
min-height: 0px !important;
}
.frappe-control.form-page:last-child {
margin-bottom: 0px;
}
.form-page .frappe-control:last-child {
border-bottom: 0px;
}
.form-page .frappe-control[data-fieldtype="Table"] {
padding: 0px 15px;
margin-top: -1px;
border-bottom: none;
}
.form-page .frappe-control[data-fieldtype="Table"] label {
margin-top: 7px;
}
.form-page .form-control {
border: none;
border-bottom: 1px solid #d1d8dd;
box-shadow: none;
background-color: inherit;
height: auto;
padding: 0px;
margin-bottom: 7px;
border-radius: 0px;
text-align: left !important;
}
.form-page .form-control:focus {
box-shadow: none;
}
}
/* goals */
.goals-page-container {
background-color: #fafbfc;
padding-top: 1px;
}
.goals-page-container .goal-container {
background-color: #fff;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
border-radius: 2px;
padding: 10px;
margin: 10px;
}
body[data-route^="Form/Communication"] textarea[data-fieldname="subject"] {
height: 80px !important;
}
| {
"content_hash": "afd443a238508c60826b01cfe0e5b009",
"timestamp": "",
"source": "github",
"line_count": 720,
"max_line_length": 107,
"avg_line_length": 21.15972222222222,
"alnum_prop": 0.680341319330489,
"repo_name": "mbauskar/frappe",
"id": "255c2afc2ae49d26baf457f22ecb47681a7765ca",
"size": "15235",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "frappe/public/css/form.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "406441"
},
{
"name": "HTML",
"bytes": "213724"
},
{
"name": "JavaScript",
"bytes": "1742788"
},
{
"name": "Makefile",
"bytes": "29"
},
{
"name": "Python",
"bytes": "1966810"
},
{
"name": "Shell",
"bytes": "517"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.