code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
<?php return unserialize('a:1:{i:0;O:27:"Doctrine\\ORM\\Mapping\\Column":9:{s:4:"name";s:5:"parg4";s:4:"type";s:4:"text";s:6:"length";N;s:9:"precision";i:0;s:5:"scale";i:0;s:6:"unique";b:0;s:8:"nullable";b:1;s:7:"options";a:0:{}s:16:"columnDefinition";N;}}');
|
MahdiDhifi/Symfony-Project
|
app/cache/dev/annotations/953a952a52bba814b0a94f0cd27310df3bda573f$parg4.cache.php
|
PHP
|
mit
| 259 |
Deprecated. Now with Docker-Compose, there is little reason for gobox.
# gobox: Golang Process Boxer
gobox manages your microservices for testing and production scenarios.
## Motivation
**You**...
- ...are building a large application with a service-oriented design.
- ...have a variety of services that need to be running in order to execute integration tests.
- ...really like docker, but due to frequent updates to your service layer, don't like the idea of having to constantly rebuild images.
With gobox, you can define a set of processes *and* specify run commands that are to be used in `test` and `production` scenarios. Further, you can define the environment for each scenario at both the process- and global-level.
## Installation
Use the Go tool:
```
go get github.com/tristanwietsma/gobox
```
## Usage
```bash
$ gobox -h
Usage of gobox:
-config=".gobox.toml": path to gobox config file
-prod=false: run in production mode
```
### Define a configuration file
By default, gobox will look for a `.gobox.toml` file in the current working directory. Alternatively, you can specify the file location.
### Define global environment settings
You can specify environment settings for both production and testing using the `prodenviron` and `testenviron` parameters.
```
prodenviron = ["VAR1=VAL1", "VAR2=VAL2"]
testenviron = ["VAR1=X", "VAR2=Z"]
```
### Define each processes
For each process, define a `proc` block in the toml file. A `proc` definition looks like this:
```
[[proc]]
name = "name of the process"
priority = 1
prodcommand = "shell command for production use"
prodenviron = ["NAME=prod1"]
testcommand = "shell command for test use"
testenviron = ["NAME=test1"]
```
#### Name
`name` is purely for logging purposes.
#### Priority
`priority` is an integer the defines the order in which the process should be started relative to other processes in the configuration. Lower numbers have higher priority.
### Running Test Mode
Test mode is the default. Assuming the config file is `.gobox.toml` in the current directory,
```bash
$ gobox
```
### Running Production Mode
```bash
$ gobox -prod=true
```
### Stopping
gobox listens for kill signals and shuts down processes before exiting.
|
tristanwietsma/gobox
|
README.md
|
Markdown
|
mit
| 2,232 |
/* dtpicker javascript jQuery */
(function($) {
// 严格模式
'use strict';
// 控件类名
var pluginName = 'dtpicker';
var PluginClass=T.UI.Controls.DTPicker;
var pluginRef = 't-plugin-ref';
// 胶水代码
$.fn[pluginName] = function(options) {
if(typeof options === 'string'){
// 2. 调用API
var plugin = this.data(pluginRef);
if(!plugin || !plugin[options]){
throw '方法 ' + options + ' 不存在';
}
var result = plugin[options].apply(plugin, Array.prototype.slice.call(arguments, 1));
if(options === 'destroy'){
jqElement.removeData(pluginRef);
}
return result;
}
this.each(function () {
var jqElement=$(this);
var plugin = jqElement.data(pluginRef);
if(plugin === undefined){
// 1. 创建新对象
plugin=new PluginClass(this, $.extend(true, {}, options));
jqElement.data(pluginRef, plugin);
}
else{
// 3. 更新选项
plugin.updateOptions || plugin.updateOptions(options);
}
});
return this;
};
})(jQuery);
// (function($) {
// // 'use strict';
// var dateTimePicker = function (element, options) {
// /********************************************************************************
// *
// * Public API functions
// * =====================
// *
// * Important: Do not expose direct references to private objects or the options
// * object to the outer world. Always return a clone when returning values or make
// * a clone when setting a private variable.
// *
// ********************************************************************************/
// picker.toggle = toggle;
// picker.show = show;
// picker.hide = hide;
// picker.ignoreReadonly = function (ignoreReadonly) {
// if (arguments.length === 0) {
// return options.ignoreReadonly;
// }
// if (typeof ignoreReadonly !== 'boolean') {
// throw new TypeError('ignoreReadonly () expects a boolean parameter');
// }
// options.ignoreReadonly = ignoreReadonly;
// return picker;
// };
// picker.options = function (newOptions) {
// if (arguments.length === 0) {
// return $.extend(true, {}, options);
// }
// if (!(newOptions instanceof Object)) {
// throw new TypeError('options() options parameter should be an object');
// }
// $.extend(true, options, newOptions);
// $.each(options, function (key, value) {
// if (picker[key] !== undefined) {
// picker[key](value);
// } else {
// throw new TypeError('option ' + key + ' is not recognized!');
// }
// });
// return picker;
// };
// picker.date = function (newDate) {
// ///<signature helpKeyword="$.fn.datetimepicker.date">
// ///<summary>Returns the component's model current date, a moment object or null if not set.</summary>
// ///<returns type="Moment">date.clone()</returns>
// ///</signature>
// ///<signature>
// ///<summary>Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration.</summary>
// ///<param name="newDate" locid="$.fn.datetimepicker.date_p:newDate">Takes string, Date, moment, null parameter.</param>
// ///</signature>
// if (arguments.length === 0) {
// if (unset) {
// return null;
// }
// return date.clone();
// }
// if (newDate !== null && typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) {
// throw new TypeError('date() parameter must be one of [null, string, moment or Date]');
// }
// setValue(newDate === null ? null : parseInputDate(newDate));
// return picker;
// };
// picker.format = function (newFormat) {
// ///<summary>test su</summary>
// ///<param name="newFormat">info about para</param>
// ///<returns type="string|boolean">returns foo</returns>
// if (arguments.length === 0) {
// return options.format;
// }
// if ((typeof newFormat !== 'string') && ((typeof newFormat !== 'boolean') || (newFormat !== false))) {
// throw new TypeError('format() expects a sting or boolean:false parameter ' + newFormat);
// }
// options.format = newFormat;
// if (actualFormat) {
// initFormatting(); // reinit formatting
// }
// return picker;
// };
// picker.timeZone = function (newZone) {
// if (arguments.length === 0) {
// return options.timeZone;
// }
// options.timeZone = newZone;
// return picker;
// };
// picker.dayViewHeaderFormat = function (newFormat) {
// if (arguments.length === 0) {
// return options.dayViewHeaderFormat;
// }
// if (typeof newFormat !== 'string') {
// throw new TypeError('dayViewHeaderFormat() expects a string parameter');
// }
// options.dayViewHeaderFormat = newFormat;
// return picker;
// };
// picker.extraFormats = function (formats) {
// if (arguments.length === 0) {
// return options.extraFormats;
// }
// if (formats !== false && !(formats instanceof Array)) {
// throw new TypeError('extraFormats() expects an array or false parameter');
// }
// options.extraFormats = formats;
// if (parseFormats) {
// initFormatting(); // reinit formatting
// }
// return picker;
// };
// picker.disabledDates = function (dates) {
// ///<signature helpKeyword="$.fn.datetimepicker.disabledDates">
// ///<summary>Returns an array with the currently set disabled dates on the component.</summary>
// ///<returns type="array">options.disabledDates</returns>
// ///</signature>
// ///<signature>
// ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of
// ///options.enabledDates if such exist.</summary>
// ///<param name="dates" locid="$.fn.datetimepicker.disabledDates_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param>
// ///</signature>
// if (arguments.length === 0) {
// return (options.disabledDates ? $.extend({}, options.disabledDates) : options.disabledDates);
// }
// if (!dates) {
// options.disabledDates = false;
// update();
// return picker;
// }
// if (!(dates instanceof Array)) {
// throw new TypeError('disabledDates() expects an array parameter');
// }
// options.disabledDates = indexGivenDates(dates);
// options.enabledDates = false;
// update();
// return picker;
// };
// picker.enabledDates = function (dates) {
// ///<signature helpKeyword="$.fn.datetimepicker.enabledDates">
// ///<summary>Returns an array with the currently set enabled dates on the component.</summary>
// ///<returns type="array">options.enabledDates</returns>
// ///</signature>
// ///<signature>
// ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledDates if such exist.</summary>
// ///<param name="dates" locid="$.fn.datetimepicker.enabledDates_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param>
// ///</signature>
// if (arguments.length === 0) {
// return (options.enabledDates ? $.extend({}, options.enabledDates) : options.enabledDates);
// }
// if (!dates) {
// options.enabledDates = false;
// update();
// return picker;
// }
// if (!(dates instanceof Array)) {
// throw new TypeError('enabledDates() expects an array parameter');
// }
// options.enabledDates = indexGivenDates(dates);
// options.disabledDates = false;
// update();
// return picker;
// };
// picker.daysOfWeekDisabled = function (daysOfWeekDisabled) {
// if (arguments.length === 0) {
// return options.daysOfWeekDisabled.splice(0);
// }
// if ((typeof daysOfWeekDisabled === 'boolean') && !daysOfWeekDisabled) {
// options.daysOfWeekDisabled = false;
// update();
// return picker;
// }
// if (!(daysOfWeekDisabled instanceof Array)) {
// throw new TypeError('daysOfWeekDisabled() expects an array parameter');
// }
// options.daysOfWeekDisabled = daysOfWeekDisabled.reduce(function (previousValue, currentValue) {
// currentValue = parseInt(currentValue, 10);
// if (currentValue > 6 || currentValue < 0 || isNaN(currentValue)) {
// return previousValue;
// }
// if (previousValue.indexOf(currentValue) === -1) {
// previousValue.push(currentValue);
// }
// return previousValue;
// }, []).sort();
// if (options.useCurrent && !options.keepInvalid) {
// var tries = 0;
// while (!isValid(date, 'd')) {
// date.add(1, 'd');
// if (tries === 7) {
// throw 'Tried 7 times to find a valid date';
// }
// tries++;
// }
// setValue(date);
// }
// update();
// return picker;
// };
// picker.maxDate = function (maxDate) {
// if (arguments.length === 0) {
// return options.maxDate ? options.maxDate.clone() : options.maxDate;
// }
// if ((typeof maxDate === 'boolean') && maxDate === false) {
// options.maxDate = false;
// update();
// return picker;
// }
// if (typeof maxDate === 'string') {
// if (maxDate === 'now' || maxDate === 'moment') {
// maxDate = getMoment();
// }
// }
// var parsedDate = parseInputDate(maxDate);
// if (!parsedDate.isValid()) {
// throw new TypeError('maxDate() Could not parse date parameter: ' + maxDate);
// }
// if (options.minDate && parsedDate.isBefore(options.minDate)) {
// throw new TypeError('maxDate() date parameter is before options.minDate: ' + parsedDate.format(actualFormat));
// }
// options.maxDate = parsedDate;
// if (options.useCurrent && !options.keepInvalid && date.isAfter(maxDate)) {
// setValue(options.maxDate);
// }
// if (viewDate.isAfter(parsedDate)) {
// viewDate = parsedDate.clone().subtract(options.stepping, 'm');
// }
// update();
// return picker;
// };
// picker.minDate = function (minDate) {
// if (arguments.length === 0) {
// return options.minDate ? options.minDate.clone() : options.minDate;
// }
// if ((typeof minDate === 'boolean') && minDate === false) {
// options.minDate = false;
// update();
// return picker;
// }
// if (typeof minDate === 'string') {
// if (minDate === 'now' || minDate === 'moment') {
// minDate = getMoment();
// }
// }
// var parsedDate = parseInputDate(minDate);
// if (!parsedDate.isValid()) {
// throw new TypeError('minDate() Could not parse date parameter: ' + minDate);
// }
// if (options.maxDate && parsedDate.isAfter(options.maxDate)) {
// throw new TypeError('minDate() date parameter is after options.maxDate: ' + parsedDate.format(actualFormat));
// }
// options.minDate = parsedDate;
// if (options.useCurrent && !options.keepInvalid && date.isBefore(minDate)) {
// setValue(options.minDate);
// }
// if (viewDate.isBefore(parsedDate)) {
// viewDate = parsedDate.clone().add(options.stepping, 'm');
// }
// update();
// return picker;
// };
// picker.defaultDate = function (defaultDate) {
// ///<signature helpKeyword="$.fn.datetimepicker.defaultDate">
// ///<summary>Returns a moment with the options.defaultDate option configuration or false if not set</summary>
// ///<returns type="Moment">date.clone()</returns>
// ///</signature>
// ///<signature>
// ///<summary>Will set the picker's inital date. If a boolean:false value is passed the options.defaultDate parameter is cleared.</summary>
// ///<param name="defaultDate" locid="$.fn.datetimepicker.defaultDate_p:defaultDate">Takes a string, Date, moment, boolean:false</param>
// ///</signature>
// if (arguments.length === 0) {
// return options.defaultDate ? options.defaultDate.clone() : options.defaultDate;
// }
// if (!defaultDate) {
// options.defaultDate = false;
// return picker;
// }
// if (typeof defaultDate === 'string') {
// if (defaultDate === 'now' || defaultDate === 'moment') {
// defaultDate = getMoment();
// }
// }
// var parsedDate = parseInputDate(defaultDate);
// if (!parsedDate.isValid()) {
// throw new TypeError('defaultDate() Could not parse date parameter: ' + defaultDate);
// }
// if (!isValid(parsedDate)) {
// throw new TypeError('defaultDate() date passed is invalid according to component setup validations');
// }
// options.defaultDate = parsedDate;
// if ((options.defaultDate && options.inline) || input.val().trim() === '') {
// setValue(options.defaultDate);
// }
// return picker;
// };
// picker.locale = function (locale) {
// if (arguments.length === 0) {
// return options.locale;
// }
// if (!moment.localeData(locale)) {
// throw new TypeError('locale() locale ' + locale + ' is not loaded from moment locales!');
// }
// options.locale = locale;
// date.locale(options.locale);
// viewDate.locale(options.locale);
// if (actualFormat) {
// initFormatting(); // reinit formatting
// }
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.stepping = function (stepping) {
// if (arguments.length === 0) {
// return options.stepping;
// }
// stepping = parseInt(stepping, 10);
// if (isNaN(stepping) || stepping < 1) {
// stepping = 1;
// }
// options.stepping = stepping;
// return picker;
// };
// picker.useCurrent = function (useCurrent) {
// var useCurrentOptions = ['year', 'month', 'day', 'hour', 'minute'];
// if (arguments.length === 0) {
// return options.useCurrent;
// }
// if ((typeof useCurrent !== 'boolean') && (typeof useCurrent !== 'string')) {
// throw new TypeError('useCurrent() expects a boolean or string parameter');
// }
// if (typeof useCurrent === 'string' && useCurrentOptions.indexOf(useCurrent.toLowerCase()) === -1) {
// throw new TypeError('useCurrent() expects a string parameter of ' + useCurrentOptions.join(', '));
// }
// options.useCurrent = useCurrent;
// return picker;
// };
// picker.collapse = function (collapse) {
// if (arguments.length === 0) {
// return options.collapse;
// }
// if (typeof collapse !== 'boolean') {
// throw new TypeError('collapse() expects a boolean parameter');
// }
// if (options.collapse === collapse) {
// return picker;
// }
// options.collapse = collapse;
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.icons = function (icons) {
// if (arguments.length === 0) {
// return $.extend({}, options.icons);
// }
// if (!(icons instanceof Object)) {
// throw new TypeError('icons() expects parameter to be an Object');
// }
// $.extend(options.icons, icons);
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.tooltips = function (tooltips) {
// if (arguments.length === 0) {
// return $.extend({}, options.tooltips);
// }
// if (!(tooltips instanceof Object)) {
// throw new TypeError('tooltips() expects parameter to be an Object');
// }
// $.extend(options.tooltips, tooltips);
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.useStrict = function (useStrict) {
// if (arguments.length === 0) {
// return options.useStrict;
// }
// if (typeof useStrict !== 'boolean') {
// throw new TypeError('useStrict() expects a boolean parameter');
// }
// options.useStrict = useStrict;
// return picker;
// };
// picker.sideBySide = function (sideBySide) {
// if (arguments.length === 0) {
// return options.sideBySide;
// }
// if (typeof sideBySide !== 'boolean') {
// throw new TypeError('sideBySide() expects a boolean parameter');
// }
// options.sideBySide = sideBySide;
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.viewMode = function (viewMode) {
// if (arguments.length === 0) {
// return options.viewMode;
// }
// if (typeof viewMode !== 'string') {
// throw new TypeError('viewMode() expects a string parameter');
// }
// if (viewModes.indexOf(viewMode) === -1) {
// throw new TypeError('viewMode() parameter must be one of (' + viewModes.join(', ') + ') value');
// }
// options.viewMode = viewMode;
// currentViewMode = Math.max(viewModes.indexOf(viewMode), minViewModeNumber);
// showMode();
// return picker;
// };
// picker.toolbarPlacement = function (toolbarPlacement) {
// if (arguments.length === 0) {
// return options.toolbarPlacement;
// }
// if (typeof toolbarPlacement !== 'string') {
// throw new TypeError('toolbarPlacement() expects a string parameter');
// }
// if (toolbarPlacements.indexOf(toolbarPlacement) === -1) {
// throw new TypeError('toolbarPlacement() parameter must be one of (' + toolbarPlacements.join(', ') + ') value');
// }
// options.toolbarPlacement = toolbarPlacement;
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.widgetPositioning = function (widgetPositioning) {
// if (arguments.length === 0) {
// return $.extend({}, options.widgetPositioning);
// }
// if (({}).toString.call(widgetPositioning) !== '[object Object]') {
// throw new TypeError('widgetPositioning() expects an object variable');
// }
// if (widgetPositioning.horizontal) {
// if (typeof widgetPositioning.horizontal !== 'string') {
// throw new TypeError('widgetPositioning() horizontal variable must be a string');
// }
// widgetPositioning.horizontal = widgetPositioning.horizontal.toLowerCase();
// if (horizontalModes.indexOf(widgetPositioning.horizontal) === -1) {
// throw new TypeError('widgetPositioning() expects horizontal parameter to be one of (' + horizontalModes.join(', ') + ')');
// }
// options.widgetPositioning.horizontal = widgetPositioning.horizontal;
// }
// if (widgetPositioning.vertical) {
// if (typeof widgetPositioning.vertical !== 'string') {
// throw new TypeError('widgetPositioning() vertical variable must be a string');
// }
// widgetPositioning.vertical = widgetPositioning.vertical.toLowerCase();
// if (verticalModes.indexOf(widgetPositioning.vertical) === -1) {
// throw new TypeError('widgetPositioning() expects vertical parameter to be one of (' + verticalModes.join(', ') + ')');
// }
// options.widgetPositioning.vertical = widgetPositioning.vertical;
// }
// update();
// return picker;
// };
// picker.calendarWeeks = function (calendarWeeks) {
// if (arguments.length === 0) {
// return options.calendarWeeks;
// }
// if (typeof calendarWeeks !== 'boolean') {
// throw new TypeError('calendarWeeks() expects parameter to be a boolean value');
// }
// options.calendarWeeks = calendarWeeks;
// update();
// return picker;
// };
// picker.showTodayButton = function (showTodayButton) {
// if (arguments.length === 0) {
// return options.showTodayButton;
// }
// if (typeof showTodayButton !== 'boolean') {
// throw new TypeError('showTodayButton() expects a boolean parameter');
// }
// options.showTodayButton = showTodayButton;
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.showClear = function (showClear) {
// if (arguments.length === 0) {
// return options.showClear;
// }
// if (typeof showClear !== 'boolean') {
// throw new TypeError('showClear() expects a boolean parameter');
// }
// options.showClear = showClear;
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.widgetParent = function (widgetParent) {
// if (arguments.length === 0) {
// return options.widgetParent;
// }
// if (typeof widgetParent === 'string') {
// widgetParent = $(widgetParent);
// }
// if (widgetParent !== null && (typeof widgetParent !== 'string' && !(widgetParent instanceof $))) {
// throw new TypeError('widgetParent() expects a string or a jQuery object parameter');
// }
// options.widgetParent = widgetParent;
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.keepOpen = function (keepOpen) {
// if (arguments.length === 0) {
// return options.keepOpen;
// }
// if (typeof keepOpen !== 'boolean') {
// throw new TypeError('keepOpen() expects a boolean parameter');
// }
// options.keepOpen = keepOpen;
// return picker;
// };
// picker.focusOnShow = function (focusOnShow) {
// if (arguments.length === 0) {
// return options.focusOnShow;
// }
// if (typeof focusOnShow !== 'boolean') {
// throw new TypeError('focusOnShow() expects a boolean parameter');
// }
// options.focusOnShow = focusOnShow;
// return picker;
// };
// picker.inline = function (inline) {
// if (arguments.length === 0) {
// return options.inline;
// }
// if (typeof inline !== 'boolean') {
// throw new TypeError('inline() expects a boolean parameter');
// }
// options.inline = inline;
// return picker;
// };
// picker.clear = function () {
// clear();
// return picker;
// };
// picker.keyBinds = function (keyBinds) {
// options.keyBinds = keyBinds;
// return picker;
// };
// picker.getMoment = function (d) {
// return this.getMoment(d);
// };
// picker.debug = function (debug) {
// if (typeof debug !== 'boolean') {
// throw new TypeError('debug() expects a boolean parameter');
// }
// options.debug = debug;
// return picker;
// };
// picker.allowInputToggle = function (allowInputToggle) {
// if (arguments.length === 0) {
// return options.allowInputToggle;
// }
// if (typeof allowInputToggle !== 'boolean') {
// throw new TypeError('allowInputToggle() expects a boolean parameter');
// }
// options.allowInputToggle = allowInputToggle;
// return picker;
// };
// picker.showClose = function (showClose) {
// if (arguments.length === 0) {
// return options.showClose;
// }
// if (typeof showClose !== 'boolean') {
// throw new TypeError('showClose() expects a boolean parameter');
// }
// options.showClose = showClose;
// return picker;
// };
// picker.keepInvalid = function (keepInvalid) {
// if (arguments.length === 0) {
// return options.keepInvalid;
// }
// if (typeof keepInvalid !== 'boolean') {
// throw new TypeError('keepInvalid() expects a boolean parameter');
// }
// options.keepInvalid = keepInvalid;
// return picker;
// };
// picker.datepickerInput = function (datepickerInput) {
// if (arguments.length === 0) {
// return options.datepickerInput;
// }
// if (typeof datepickerInput !== 'string') {
// throw new TypeError('datepickerInput() expects a string parameter');
// }
// options.datepickerInput = datepickerInput;
// return picker;
// };
// picker.parseInputDate = function (parseInputDate) {
// if (arguments.length === 0) {
// return options.parseInputDate;
// }
// if (typeof parseInputDate !== 'function') {
// throw new TypeError('parseInputDate() sholud be as function');
// }
// options.parseInputDate = parseInputDate;
// return picker;
// };
// picker.disabledTimeIntervals = function (disabledTimeIntervals) {
// ///<signature helpKeyword="$.fn.datetimepicker.disabledTimeIntervals">
// ///<summary>Returns an array with the currently set disabled dates on the component.</summary>
// ///<returns type="array">options.disabledTimeIntervals</returns>
// ///</signature>
// ///<signature>
// ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of
// ///options.enabledDates if such exist.</summary>
// ///<param name="dates" locid="$.fn.datetimepicker.disabledTimeIntervals_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param>
// ///</signature>
// if (arguments.length === 0) {
// return (options.disabledTimeIntervals ? $.extend({}, options.disabledTimeIntervals) : options.disabledTimeIntervals);
// }
// if (!disabledTimeIntervals) {
// options.disabledTimeIntervals = false;
// update();
// return picker;
// }
// if (!(disabledTimeIntervals instanceof Array)) {
// throw new TypeError('disabledTimeIntervals() expects an array parameter');
// }
// options.disabledTimeIntervals = disabledTimeIntervals;
// update();
// return picker;
// };
// picker.disabledHours = function (hours) {
// ///<signature helpKeyword="$.fn.datetimepicker.disabledHours">
// ///<summary>Returns an array with the currently set disabled hours on the component.</summary>
// ///<returns type="array">options.disabledHours</returns>
// ///</signature>
// ///<signature>
// ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of
// ///options.enabledHours if such exist.</summary>
// ///<param name="hours" locid="$.fn.datetimepicker.disabledHours_p:hours">Takes an [ int ] of values and disallows the user to select only from those hours.</param>
// ///</signature>
// if (arguments.length === 0) {
// return (options.disabledHours ? $.extend({}, options.disabledHours) : options.disabledHours);
// }
// if (!hours) {
// options.disabledHours = false;
// update();
// return picker;
// }
// if (!(hours instanceof Array)) {
// throw new TypeError('disabledHours() expects an array parameter');
// }
// options.disabledHours = indexGivenHours(hours);
// options.enabledHours = false;
// if (options.useCurrent && !options.keepInvalid) {
// var tries = 0;
// while (!isValid(date, 'h')) {
// date.add(1, 'h');
// if (tries === 24) {
// throw 'Tried 24 times to find a valid date';
// }
// tries++;
// }
// setValue(date);
// }
// update();
// return picker;
// };
// picker.enabledHours = function (hours) {
// ///<signature helpKeyword="$.fn.datetimepicker.enabledHours">
// ///<summary>Returns an array with the currently set enabled hours on the component.</summary>
// ///<returns type="array">options.enabledHours</returns>
// ///</signature>
// ///<signature>
// ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledHours if such exist.</summary>
// ///<param name="hours" locid="$.fn.datetimepicker.enabledHours_p:hours">Takes an [ int ] of values and allows the user to select only from those hours.</param>
// ///</signature>
// if (arguments.length === 0) {
// return (options.enabledHours ? $.extend({}, options.enabledHours) : options.enabledHours);
// }
// if (!hours) {
// options.enabledHours = false;
// update();
// return picker;
// }
// if (!(hours instanceof Array)) {
// throw new TypeError('enabledHours() expects an array parameter');
// }
// options.enabledHours = indexGivenHours(hours);
// options.disabledHours = false;
// if (options.useCurrent && !options.keepInvalid) {
// var tries = 0;
// while (!isValid(date, 'h')) {
// date.add(1, 'h');
// if (tries === 24) {
// throw 'Tried 24 times to find a valid date';
// }
// tries++;
// }
// setValue(date);
// }
// update();
// return picker;
// };
// picker.viewDate = function (newDate) {
// ///<signature helpKeyword="$.fn.datetimepicker.viewDate">
// ///<summary>Returns the component's model current viewDate, a moment object or null if not set.</summary>
// ///<returns type="Moment">viewDate.clone()</returns>
// ///</signature>
// ///<signature>
// ///<summary>Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration.</summary>
// ///<param name="newDate" locid="$.fn.datetimepicker.date_p:newDate">Takes string, viewDate, moment, null parameter.</param>
// ///</signature>
// if (arguments.length === 0) {
// return viewDate.clone();
// }
// if (!newDate) {
// viewDate = date.clone();
// return picker;
// }
// if (typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) {
// throw new TypeError('viewDate() parameter must be one of [string, moment or Date]');
// }
// viewDate = parseInputDate(newDate);
// viewUpdate();
// return picker;
// };
// };
// })(jQuery);
|
staticmatrix/Triangle
|
src/framework/controls/dtpicker/dtpicker-jq.js
|
JavaScript
|
mit
| 36,843 |
using RippleCommonUtilities;
using RippleDictionary;
using RippleScreenApp.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace RippleScreenApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class ScreenWindow : Window
{
internal static RippleDictionary.Ripple rippleData;
private static TextBlock tbElement = new TextBlock();
private static TextBlock fullScreenTbElement = new TextBlock();
private static Image imgElement = new Image();
private static Image fullScreenImgElement = new Image();
private static String currentVideoURI = String.Empty;
private static RippleDictionary.ContentType currentScreenContent = ContentType.Nothing;
private static bool loopVideo = false;
private BackgroundWorker myBackgroundWorker;
private BackgroundWorker pptWorker;
Utilities.ScriptingHelper helper;
public System.Windows.Forms.Integration.WindowsFormsHost host;
public System.Windows.Forms.WebBrowser browserElement;
internal static String personName;
private long prevRow;
private Tile currentTile = null;
private bool StartVideoPlayed = false;
public static String sessionGuid = String.Empty;
public ScreenWindow()
{
try
{
InitializeComponent();
LoadData();
SetObjectProperties();
//Start receiving messages
Utilities.MessageReceiver.StartReceivingMessages(this);
}
catch (Exception ex)
{
//Exit and do nothing
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Screen {0}", ex.Message);
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
try
{
this.WindowState = System.Windows.WindowState.Maximized;
ResetUI();
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Window Loaded {0}", ex.Message);
}
}
private void SetObjectProperties()
{
//Initialize video properties
this.IntroVideoControl.Source = new Uri(Helper.GetAssetURI(rippleData.Screen.ScreenContents["IntroVideo"].Content));
this.IntroVideoControl.ScrubbingEnabled = true;
//Set image elements properties
imgElement.Stretch = Stretch.Fill;
fullScreenImgElement.Stretch = Stretch.Fill;
//Set text block properties
tbElement.FontSize = 50;
tbElement.Margin = new Thickness(120, 120, 120, 0);
tbElement.TextWrapping = TextWrapping.Wrap;
fullScreenTbElement.FontSize = 50;
fullScreenTbElement.Margin = new Thickness(120, 120, 120, 0);
fullScreenTbElement.TextWrapping = TextWrapping.Wrap;
}
/// <summary>
/// Method that loads the configured data for the Screen, right now the Source is XML
/// </summary>
private void LoadData()
{
try
{
//Loads the local dictionary data from the configuration XML
rippleData = RippleDictionary.Dictionary.GetRipple(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location));
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Load Data for Screen {0}", ex.Message);
throw;
}
}
/// <summary>
/// Resets the UI to System locked mode.
/// </summary>
private void ResetUI()
{
try
{
Globals.ResetGlobals();
currentVideoURI = String.Empty;
currentScreenContent = ContentType.Nothing;
loopVideo = false;
StartVideoPlayed = false;
sessionGuid = String.Empty;
//Pick up content based on the "LockScreen" ID
ProjectContent(rippleData.Screen.ScreenContents["LockScreen"]);
//Commit the telemetry data
Utilities.TelemetryWriter.CommitTelemetryAsync();
}
catch (Exception ex)
{
//Do nothing
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Reset UI for Screen {0}", ex.Message);
}
}
/// <summary>
/// Code will receive messages from the floor
/// Invoke appropriate content projection based on the tile ID passed
/// </summary>
/// <param name="val"></param>
public void OnMessageReceived(string val)
{
try
{
//Check for reset
if (val.Equals("Reset"))
{
//Update the previous entry
Utilities.TelemetryWriter.UpdatePreviousEntry();
//Reset the system
ResetUI();
}
//Check for System start
//Check for System start
else if (val.StartsWith("System Start"))
{
//Load the telemetry Data
Utilities.TelemetryWriter.RetrieveTelemetryData();
//The floor has asked the screen to start the system
//Get the User Name
Globals.UserName = val.Split(':')[1];
//Get the person identity for the session
personName = String.IsNullOrEmpty(Globals.UserName) ? Convert.ToString(Guid.NewGuid()) : Globals.UserName;
Utilities.TelemetryWriter.AddTelemetryRow(rippleData.Floor.SetupID, personName, "Unlock", val, "Unlock");
//Set the system state
Globals.currentAppState = RippleSystemStates.UserDetected;
//Play the Intro Content
ProjectIntroContent(rippleData.Screen.ScreenContents["IntroVideo"]);
}
//Check for gestures
else if (val.StartsWith("Gesture"))
{
OnGestureInput(val.Split(':')[1]);
}
//Check for HTMl messages
else if (val.StartsWith("HTML"))
{
OnHTMLMessagesReceived(val.Split(':')[1]);
}
//Check for options- TODO need to figure out
else if (val.StartsWith("Option"))
{
//Do nothing
}
//Check if a content - tile mapping or in general content tag exists
else
{
if (rippleData.Screen.ScreenContents.ContainsKey(val) && rippleData.Screen.ScreenContents[val].Type != ContentType.Nothing)
{
//Set the system state
Globals.currentAppState = RippleSystemStates.OptionSelected;
ProjectContent(rippleData.Screen.ScreenContents[val]);
RippleCommonUtilities.LoggingHelper.LogTrace(1, "In Message Received {0} {1}:{2}", Utilities.TelemetryWriter.telemetryData.Tables[0].Rows.Count, Utilities.TelemetryWriter.telemetryData.Tables[0].Rows[Utilities.TelemetryWriter.telemetryData.Tables[0].Rows.Count - 1].ItemArray[6], DateTime.Now);
//Update the end time for the previous
Utilities.TelemetryWriter.UpdatePreviousEntry();
//Insert the new entry
Utilities.TelemetryWriter.AddTelemetryRow(rippleData.Floor.SetupID, personName, ((currentTile = GetFloorTileForID(val))==null)?"Unknown":currentTile.Name, val, (val == "Tile0") ? "Start" : "Option");
}
else
{
//Stop any existing projections
DocumentPresentation.HelperMethods.StopPresentation();
FullScreenContentGrid.Children.Clear();
ContentGrid.Children.Clear();
//Set focus for screen window also
Utilities.Helper.ClickOnScreenToGetFocus();
//Stop any existing videos
loopVideo = false;
VideoControl.Source = null;
FullScreenVideoControl.Source = null;
//Clean the images
fullScreenImgElement.Source = null;
imgElement.Source = null;
//Clear the header text
TitleLabel.Text = "";
//Dispose the objects
if(browserElement != null)
browserElement.Dispose();
browserElement = null;
if (host != null)
host.Dispose();
host = null;
if (helper != null)
helper.PropertyChanged -= helper_PropertyChanged;
helper = null;
currentScreenContent = ContentType.Nothing;
ShowText("No content available for this option, Please try some other tile option", "No Content");
}
}
}
catch (Exception ex)
{
//Do nothing
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in On message received for Screen {0}", ex.Message);
}
}
private void OnHTMLMessagesReceived(string p)
{
try
{
if(p.StartsWith("SessionID,"))
{
sessionGuid = p;
return;
}
if (helper != null && currentScreenContent == ContentType.HTML)
{
helper.MessageReceived(p);
}
}
catch (Exception ex)
{
//Do nothing
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in OnHTMLMessagesReceived received for Screen {0}", ex.Message);
}
}
private void OnGestureInput(string inputGesture)
{
try
{
//PPT Mode - left and right swipe
if (inputGesture == GestureTypes.LeftSwipe.ToString() && currentScreenContent == ContentType.PPT)
{
//Acts as previous
DocumentPresentation.HelperMethods.GotoPrevious();
}
else if (inputGesture == GestureTypes.RightSwipe.ToString() && currentScreenContent == ContentType.PPT)
{
//Check again, Means the presentation ended on clicking next
if (!DocumentPresentation.HelperMethods.HasPresentationStarted())
{
//Change the screen
//ShowText("Your presentation has ended, Select some other option", "Select some other option");
ShowImage(@"\Assets\Images\pptend.png", "Presentation Ended");
//Set focus for screen window also
Utilities.Helper.ClickOnScreenToGetFocus();
}
//Acts as next
DocumentPresentation.HelperMethods.GotoNext();
//Check again, Means the presentation ended on clicking next
if (!DocumentPresentation.HelperMethods.HasPresentationStarted())
{
//Change the screen text
//ShowText("Your presentation has ended, Select some other option", "Select some other option");
ShowImage(@"\Assets\Images\pptend.png", "Presentation Ended");
//Set focus for screen window also
Utilities.Helper.ClickOnScreenToGetFocus();
}
}
//Browser mode
else if (currentScreenContent == ContentType.HTML)
{
OnHTMLMessagesReceived(inputGesture.ToString());
}
//Set focus for screen window also
//Utilities.Helper.ClickOnScreenToGetFocus();
}
catch (Exception ex)
{
//Do nothing
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in OnGestureInput received for Screen {0}", ex.Message);
}
}
#region Content Projection methods
/// <summary>
/// Identifies the content type and project accordingly
/// </summary>
/// <param name="screenContent"></param>
private void ProjectContent(RippleDictionary.ScreenContent screenContent)
{
try
{
if (screenContent.Type == ContentType.HTMLMessage)
{
if (helper != null && currentScreenContent == ContentType.HTML)
{
helper.MessageReceived(screenContent.Content);
return;
}
}
//Stop any existing projections
DocumentPresentation.HelperMethods.StopPresentation();
FullScreenContentGrid.Children.Clear();
ContentGrid.Children.Clear();
//Set focus for screen window also
Utilities.Helper.ClickOnScreenToGetFocus();
//Stop any existing videos
loopVideo = false;
VideoControl.Source = null;
FullScreenVideoControl.Source = null;
//Clean the images
fullScreenImgElement.Source = null;
imgElement.Source = null;
//Clear the header text
TitleLabel.Text = "";
//Dispose the objects
if (browserElement != null)
browserElement.Dispose();
browserElement = null;
if (host != null)
host.Dispose();
host = null;
if (helper != null)
helper.PropertyChanged -= helper_PropertyChanged;
helper = null;
currentScreenContent = screenContent.Type;
if (screenContent.Id == "Tile0" && StartVideoPlayed)
{
currentScreenContent = ContentType.Image;
ShowImage("\\Assets\\Images\\default_start.png", screenContent.Header);
return;
}
switch (screenContent.Type)
{
case RippleDictionary.ContentType.HTML:
ShowBrowser(screenContent.Content, screenContent.Header);
break;
case RippleDictionary.ContentType.Image:
ShowImage(screenContent.Content, screenContent.Header);
break;
case RippleDictionary.ContentType.PPT:
ShowPPT(screenContent.Content, screenContent.Header);
break;
case RippleDictionary.ContentType.Text:
ShowText(screenContent.Content, screenContent.Header);
break;
case RippleDictionary.ContentType.Video:
loopVideo = (screenContent.LoopVideo == null) ? false : Convert.ToBoolean(screenContent.LoopVideo);
if (screenContent.Id == "Tile0")
StartVideoPlayed = true;
ShowVideo(screenContent.Content, screenContent.Header);
break;
}
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in ProjectContent Method for screen {0}", ex.Message);
}
}
private void ProjectIntroContent(RippleDictionary.ScreenContent screenContent)
{
try
{
//Dispose the previous content
//Stop any existing projections
DocumentPresentation.HelperMethods.StopPresentation();
FullScreenContentGrid.Children.Clear();
ContentGrid.Children.Clear();
//Set focus for screen window also
Utilities.Helper.ClickOnScreenToGetFocus();
//Stop any existing videos
loopVideo = false;
VideoControl.Source = null;
FullScreenVideoControl.Source = null;
//Clean the images
fullScreenImgElement.Source = null;
imgElement.Source = null;
//Clear the header text
TitleLabel.Text = "";
if (browserElement != null)
browserElement.Dispose();
browserElement = null;
if (host != null)
host.Dispose();
host = null;
if (helper != null)
helper.PropertyChanged -= helper_PropertyChanged;
helper = null;
//Play the Intro video
this.TitleLabel.Text = "";
ContentGrid.Visibility = Visibility.Collapsed;
FullScreenContentGrid.Visibility = Visibility.Collapsed;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
IntroVideoControl.Visibility = Visibility.Visible;
VideoControl.Visibility = Visibility.Collapsed;
VideoGrid.Visibility = Visibility.Visible;
IntroVideoControl.Play();
this.UpdateLayout();
myBackgroundWorker = new BackgroundWorker();
myBackgroundWorker.DoWork += myBackgroundWorker_DoWork;
myBackgroundWorker.RunWorkerCompleted += myBackgroundWorker_RunWorkerCompleted;
myBackgroundWorker.RunWorkerAsync(rippleData.Floor.Start.IntroVideoWaitPeriod);
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in ProjectIntroContent Method for screen {0}", ex.Message);
}
}
private void myBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//System has been started, it just finished playing the intro video
if (Globals.currentAppState == RippleSystemStates.UserDetected)
{
this.IntroVideoControl.Stop();
//this.IntroVideoControl.Source = null;
this.IntroVideoControl.Visibility = System.Windows.Visibility.Collapsed;
ShowGotoStartContent();
}
}
private void myBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
System.Threading.Thread.Sleep(Convert.ToInt16(e.Argument) * 1000);
}
/// <summary>
/// Code to project a video
/// If the Header value is not provided, the content is projected in full screen mode
/// </summary>
/// <param name="Content"></param>
/// <param name="header"></param>
private void ShowVideo(String Content, String header)
{
try
{
//Check if header is null
//Null - Show full screen content
if (String.IsNullOrEmpty(header))
{
//Show the full screen video control
currentVideoURI = Helper.GetAssetURI(Content);
FullScreenVideoControl.Source = new Uri(currentVideoURI);
FullScreenContentGrid.Visibility = Visibility.Collapsed;
FullScreenVideoGrid.Visibility = Visibility.Visible;
FullScreenVideoControl.Play();
}
else
{
TitleLabel.Text = header;
currentVideoURI = Helper.GetAssetURI(Content);
VideoControl.Source = new Uri(currentVideoURI);
ContentGrid.Visibility = Visibility.Collapsed;
FullScreenContentGrid.Visibility = Visibility.Collapsed;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
VideoControl.Visibility = Visibility.Visible;
VideoGrid.Visibility = Visibility.Visible;
VideoControl.Play();
}
this.UpdateLayout();
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Show Video method {0}", ex.Message);
}
}
/// <summary>
/// Code to display text
/// If the Header value is not provided, the content is projected in full screen mode
/// </summary>
/// <param name="Content"></param>
/// <param name="header"></param>
private void ShowText(String Content, String header)
{
try
{
//Check if header is null
//Null - Show full screen content
if (String.IsNullOrEmpty(header))
{
//Show the full screen control with text
fullScreenTbElement.Text = Content;
FullScreenContentGrid.Children.Clear();
FullScreenContentGrid.Children.Add(fullScreenTbElement);
FullScreenContentGrid.Visibility = Visibility.Visible;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
}
else
{
TitleLabel.Text = header;
tbElement.Text = Content;
ContentGrid.Children.Clear();
ContentGrid.Children.Add(tbElement);
ContentGrid.Visibility = Visibility.Visible;
FullScreenContentGrid.Visibility = Visibility.Collapsed;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
VideoGrid.Visibility = Visibility.Collapsed;
}
this.UpdateLayout();
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Show Text method {0}", ex.Message);
}
}
/// <summary>
/// Code to project a PPT
/// If the Header value is not provided, the content is projected in full screen mode
/// </summary>
/// <param name="Content"></param>
/// <param name="header"></param>
private void ShowPPT(String Content, String header)
{
try
{
//Check if header is null
//Null - Show full screen content
if (String.IsNullOrEmpty(header))
{
//Show the full screen video control
FullScreenContentGrid.Visibility = Visibility.Visible;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
}
else
{
TitleLabel.Text = header;
ContentGrid.Visibility = Visibility.Visible;
FullScreenContentGrid.Visibility = Visibility.Collapsed;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
VideoGrid.Visibility = Visibility.Collapsed;
}
this.UpdateLayout();
DocumentPresentation.HelperMethods.StartPresentation(Helper.GetAssetURI(Content));
//ShowText("Please wait while we load your presentation", header);
//ShowImage(@"\Assets\Images\loading.png", header);
//this.UpdateLayout();
//pptWorker = new BackgroundWorker();
//pptWorker.DoWork += pptWorker_DoWork;
//pptWorker.RunWorkerAsync(Content);
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Show PPT method {0}", ex.Message);
}
}
void pptWorker_DoWork(object sender, DoWorkEventArgs e)
{
DocumentPresentation.HelperMethods.StartPresentation(Helper.GetAssetURI(e.Argument.ToString()));
}
/// <summary>
/// Code to project an image
/// If the Header value is not provided, the content is projected in full screen mode
/// </summary>
/// <param name="Content"></param>
/// <param name="header"></param>
private void ShowImage(String Content, String header)
{
try
{
//Check if header is null
//Null - Show full screen content
if (String.IsNullOrEmpty(header))
{
//Show the full screen control with text
fullScreenImgElement.Source = new BitmapImage(new Uri(Helper.GetAssetURI(Content)));
FullScreenContentGrid.Children.Clear();
FullScreenContentGrid.Children.Add(fullScreenImgElement);
FullScreenContentGrid.Visibility = Visibility.Visible;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
}
else
{
TitleLabel.Text = header;
imgElement.Source = new BitmapImage(new Uri(Helper.GetAssetURI(Content)));
ContentGrid.Children.Clear();
ContentGrid.Children.Add(imgElement);
ContentGrid.Visibility = Visibility.Visible;
FullScreenContentGrid.Visibility = Visibility.Collapsed;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
VideoGrid.Visibility = Visibility.Collapsed;
}
this.UpdateLayout();
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Show Image {0}", ex.Message);
}
}
/// <summary>
/// Code to show browser based content, applicable for URL's
/// If the Header value is not provided, the content is projected in full screen mode
/// </summary>
/// <param name="Content"></param>
/// <param name="header"></param>
private void ShowBrowser(String Content, String header)
{
try
{
//Check if header is null
//Null - Show full screen content
if (String.IsNullOrEmpty(header))
{
//Show the full screen video control
//Display HTML content
host = new System.Windows.Forms.Integration.WindowsFormsHost();
browserElement = new System.Windows.Forms.WebBrowser();
browserElement.ScriptErrorsSuppressed = true;
helper = new Utilities.ScriptingHelper(this);
browserElement.ObjectForScripting = helper;
host.Child = browserElement;
helper.PropertyChanged += helper_PropertyChanged;
FullScreenContentGrid.Children.Clear();
FullScreenContentGrid.Children.Add(host);
FullScreenContentGrid.Visibility = Visibility.Visible;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
}
else
{
TitleLabel.Text = header;
host = new System.Windows.Forms.Integration.WindowsFormsHost();
browserElement = new System.Windows.Forms.WebBrowser();
browserElement.ScriptErrorsSuppressed = true;
helper = new Utilities.ScriptingHelper(this);
host.Child = browserElement;
browserElement.ObjectForScripting = helper;
helper.PropertyChanged += helper_PropertyChanged;
ContentGrid.Children.Clear();
ContentGrid.Children.Add(host);
ContentGrid.Visibility = Visibility.Visible;
FullScreenContentGrid.Visibility = Visibility.Collapsed;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
VideoGrid.Visibility = Visibility.Collapsed;
}
String fileLocation = Helper.GetAssetURI(Content);
String pageUri = String.Empty;
//Local file
if (File.Exists(fileLocation))
{
String[] PathParts = fileLocation.Split(new char[] { ':' });
pageUri = "file://127.0.0.1/" + PathParts[0] + "$" + PathParts[1];
}
//Web hosted file
else
{
pageUri = Content;
}
browserElement.Navigate(pageUri);
this.UpdateLayout();
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Show Browser {0}", ex.Message);
}
}
#endregion
#region Helpers
private Tile GetFloorTileForID(string TileID)
{
Tile reqdTile = null;
try
{
reqdTile = rippleData.Floor.Tiles[TileID];
}
catch (Exception)
{
try
{
reqdTile = rippleData.Floor.Tiles[TileID.Substring(0, TileID.LastIndexOf("SubTile"))].SubTiles[TileID];
}
catch (Exception)
{
return null;
}
}
return reqdTile;
}
#endregion
private void VideoControl_MediaEnded(object sender, RoutedEventArgs e)
{
if (currentScreenContent == ContentType.Video && loopVideo && (!String.IsNullOrEmpty(currentVideoURI)))
{
//Replay the video
VideoControl.Source = new Uri(currentVideoURI);
VideoControl.Play();
}
}
private void FullScreenVideoControl_MediaEnded(object sender, RoutedEventArgs e)
{
if (currentScreenContent == ContentType.Video && loopVideo && (!String.IsNullOrEmpty(currentVideoURI)))
{
//Replay the video
FullScreenVideoControl.Source = new Uri(currentVideoURI);
FullScreenVideoControl.Play();
}
}
private void ShowGotoStartContent()
{
//Set the system state
Globals.currentAppState = RippleSystemStates.UserWaitToGoOnStart;
ProjectContent(rippleData.Screen.ScreenContents["GotoStart"]);
}
private void IntroVideoControl_MediaEnded(object sender, RoutedEventArgs e)
{
//System has been started, it just finished playing the intro video
//if (Globals.currentAppState == RippleSystemStates.UserDetected)
//{
// this.IntroVideoControl.Stop();
// ShowGotoStartContent();
//}
}
private void Window_Closing_1(object sender, CancelEventArgs e)
{
RippleCommonUtilities.LoggingHelper.StopLogging();
}
//Handles messages sent by HTML animations
void helper_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
try
{
var scriptingHelper = sender as Utilities.ScriptingHelper;
if (scriptingHelper != null)
{
if (e.PropertyName == "SendMessage")
{
if ((!String.IsNullOrEmpty(scriptingHelper.SendMessage)) && currentScreenContent == ContentType.HTML)
{
//Send the screen a message for HTML parameter passing
Utilities.MessageReceiver.SendMessage("HTML:" + scriptingHelper.SendMessage);
}
}
}
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in helper property changed event {0}", ex.Message);
}
}
}
}
|
Microsoft/kinect-ripple
|
Ripple/RippleScreenApp/ScreenWindow.xaml.cs
|
C#
|
mit
| 33,912 |
/**
******************************************************************************
* @file TIM/TIM_ParallelSynchro/stm32f4xx_conf.h
* @author MCD Application Team
* @version V1.3.0
* @date 13-November-2013
* @brief Library configuration file.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2013 STMicroelectronics</center></h2>
*
* Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2
*
* 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.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F4xx_CONF_H
#define __STM32F4xx_CONF_H
/* Includes ------------------------------------------------------------------*/
/* Uncomment the line below to enable peripheral header file inclusion */
#include "stm32f4xx_adc.h"
#include "stm32f4xx_crc.h"
#include "stm32f4xx_dbgmcu.h"
#include "stm32f4xx_dma.h"
#include "stm32f4xx_exti.h"
#include "stm32f4xx_flash.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_i2c.h"
#include "stm32f4xx_iwdg.h"
#include "stm32f4xx_pwr.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_rtc.h"
#include "stm32f4xx_sdio.h"
#include "stm32f4xx_spi.h"
#include "stm32f4xx_syscfg.h"
#include "stm32f4xx_tim.h"
#include "stm32f4xx_usart.h"
#include "stm32f4xx_wwdg.h"
#include "misc.h" /* High level functions for NVIC and SysTick (add-on to CMSIS functions) */
#if defined (STM32F429_439xx)
#include "stm32f4xx_cryp.h"
#include "stm32f4xx_hash.h"
#include "stm32f4xx_rng.h"
#include "stm32f4xx_can.h"
#include "stm32f4xx_dac.h"
#include "stm32f4xx_dcmi.h"
#include "stm32f4xx_dma2d.h"
#include "stm32f4xx_fmc.h"
#include "stm32f4xx_ltdc.h"
#include "stm32f4xx_sai.h"
#endif /* STM32F429_439xx */
#if defined (STM32F427_437xx)
#include "stm32f4xx_cryp.h"
#include "stm32f4xx_hash.h"
#include "stm32f4xx_rng.h"
#include "stm32f4xx_can.h"
#include "stm32f4xx_dac.h"
#include "stm32f4xx_dcmi.h"
#include "stm32f4xx_dma2d.h"
#include "stm32f4xx_fmc.h"
#include "stm32f4xx_sai.h"
#endif /* STM32F427_437xx */
#if defined (STM32F40_41xxx)
#include "stm32f4xx_cryp.h"
#include "stm32f4xx_hash.h"
#include "stm32f4xx_rng.h"
#include "stm32f4xx_can.h"
#include "stm32f4xx_dac.h"
#include "stm32f4xx_dcmi.h"
#include "stm32f4xx_fsmc.h"
#endif /* STM32F40_41xxx */
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* If an external clock source is used, then the value of the following define
should be set to the value of the external clock source, else, if no external
clock is used, keep this define commented */
/*#define I2S_EXTERNAL_CLOCK_VAL 12288000 */ /* Value of the external clock in Hz */
/* Uncomment the line below to expanse the "assert_param" macro in the
Standard Peripheral Library drivers code */
/* #define USE_FULL_ASSERT 1 */
/* Exported macro ------------------------------------------------------------*/
#ifdef USE_FULL_ASSERT
/**
* @brief The assert_param macro is used for function's parameters check.
* @param expr: If expr is false, it calls assert_failed function
* which reports the name of the source file and the source
* line number of the call that failed.
* If expr is true, it returns no value.
* @retval None
*/
#define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__))
/* Exported functions ------------------------------------------------------- */
void assert_failed(uint8_t* file, uint32_t line);
#else
#define assert_param(expr) ((void)0)
#endif /* USE_FULL_ASSERT */
#endif /* __STM32F4xx_CONF_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
filipek92/STM32F4Discovery
|
STM32F4xx_DSP_StdPeriph_Lib_V1.3.0/Project/STM32F4xx_StdPeriph_Examples/TIM/TIM_ParallelSynchro/stm32f4xx_conf.h
|
C
|
mit
| 4,368 |
# Note that this is not a valid measurement of tail latency. This uses the execution times we measure because they're convenient, but this does not include queueing time inside BitFunnel nor does it include head-of-line blocking queue waiting time on the queue into BitFunnel.
import csv
filename = "/tmp/QueryPipelineStatistics.csv"
times = []
with open(filename) as f:
reader = csv.reader(f)
header = next(reader)
assert header == ['query',
'rows',
'matches',
'quadwords',
'cachelines',
'parse',
'plan',
'match']
for row in reader:
total_time = float(row[-1]) + float(row[-2]) + float(row[-3])
times.append(total_time)
times.sort(reverse=True)
idx_max = len(times) - 1
idx = [round(idx_max / 2),
round(idx_max / 10),
round(idx_max / 100),
round(idx_max / 1000),
0]
tails = [times[x] for x in idx]
print(tails)
|
BitFunnel/BitFunnel
|
src/Scripts/tail-latency.py
|
Python
|
mit
| 1,033 |
const assert = require('assert');
const md5 = require('blueimp-md5');
const createApp = require('../../lib');
describe('tokenize service', () => {
it('tokenizes and stems', () => {
const app = createApp();
const text = `what's the weather in vancouver`;
const hash = md5(text);
return app.service('tokenize').create({ text }).then(data => {
assert.equal(data._id, hash, 'id is MD5 hash of the string');
assert.deepEqual(data, {
_id: '873dd3d48eed1d576a4d5b1dcacd2348',
text: 'what\'s the weather in vancouver',
tokens: [ 'what', 's', 'the', 'weather', 'in', 'vancouver' ],
stems: [ 'what', 's', 'the', 'weather', 'in', 'vancouv' ]
});
});
});
});
|
solveEZ/neuroJ
|
test/services/tokenize.test.js
|
JavaScript
|
mit
| 723 |
// AForge Kinect Video Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © AForge.NET, 2005-2011
// [email protected]
//
namespace AForge.Video.Kinect
{
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using AForge;
using AForge.Imaging;
using AForge.Video;
/// <summary>
/// Enumeration of video camera modes for the <see cref="KinectVideoCamera"/>.
/// </summary>
public enum VideoCameraMode
{
/// <summary>
/// 24 bit per pixel RGB mode.
/// </summary>
Color,
/// <summary>
/// 8 bit per pixel Bayer mode.
/// </summary>
Bayer,
/// <summary>
/// 8 bit per pixel Infra Red mode.
/// </summary>
InfraRed
}
/// <summary>
/// Video source for Microsoft Kinect's video camera.
/// </summary>
///
/// <remarks><para>The video source captures video data from Microsoft <a href="http://en.wikipedia.org/wiki/Kinect">Kinect</a>
/// video camera, which is aimed originally as a gaming device for XBox 360 platform.</para>
///
/// <para><note>Prior to using the class, make sure you've installed Kinect's drivers
/// as described on <a href="http://openkinect.org/wiki/Getting_Started#Windows">Open Kinect</a>
/// project's page.</note></para>
///
/// <para><note>In order to run correctly the class requires <i>freenect.dll</i> library
/// to be put into solution's output folder. This can be found within the AForge.NET framework's
/// distribution in Externals folder.</note></para>
///
/// <para>Sample usage:</para>
/// <code>
/// // create video source
/// KinectVideoCamera videoSource = new KinectVideoCamera( 0 );
/// // set NewFrame event handler
/// videoSource.NewFrame += new NewFrameEventHandler( video_NewFrame );
/// // start the video source
/// videoSource.Start( );
/// // ...
///
/// private void video_NewFrame( object sender, NewFrameEventArgs eventArgs )
/// {
/// // get new frame
/// Bitmap bitmap = eventArgs.Frame;
/// // process the frame
/// }
/// </code>
/// </remarks>
///
public class KinectVideoCamera : IVideoSource
{
// Kinect's device ID
private int deviceID;
// received frames count
private int framesReceived;
// recieved byte count
private long bytesReceived;
// camera mode
private VideoCameraMode cameraMode = VideoCameraMode.Color;
// camera resolution to set
private CameraResolution resolution = CameraResolution.Medium;
// list of currently running cameras
private static List<int> runningCameras = new List<int>( );
// dummy object to lock for synchronization
private object sync = new object( );
/// <summary>
/// New frame event.
/// </summary>
///
/// <remarks><para>Notifies clients about new available frames from the video source.</para>
///
/// <para><note>Since video source may have multiple clients, each client is responsible for
/// making a copy (cloning) of the passed video frame, because the video source disposes its
/// own original copy after notifying of clients.</note></para>
/// </remarks>
///
public event NewFrameEventHandler NewFrame;
/// <summary>
/// Video source error event.
/// </summary>
///
/// <remarks>This event is used to notify clients about any type of errors occurred in
/// video source object, for example internal exceptions.</remarks>
///
public event VideoSourceErrorEventHandler VideoSourceError;
/// <summary>
/// Video playing finished event.
/// </summary>
///
/// <remarks><para>This event is used to notify clients that the video playing has finished.</para>
/// </remarks>
///
public event PlayingFinishedEventHandler PlayingFinished;
/// <summary>
/// Specifies video mode for the camera.
/// </summary>
///
/// <remarks>
/// <para><note>The property must be set before running the video source to take effect.</note></para>
///
/// <para>Default value of the property is set to <see cref="VideoCameraMode.Color"/>.</para>
/// </remarks>
///
public VideoCameraMode CameraMode
{
get { return cameraMode; }
set { cameraMode = value; }
}
/// <summary>
/// Resolution of video camera to set.
/// </summary>
///
/// <remarks><para><note>The property must be set before running the video source to take effect.</note></para>
///
/// <para>Default value of the property is set to <see cref="CameraResolution.Medium"/>.</para>
/// </remarks>
///
public CameraResolution Resolution
{
get { return resolution; }
set { resolution = value; }
}
/// <summary>
/// A string identifying the video source.
/// </summary>
///
public virtual string Source
{
get { return "Kinect:VideoCamera:" + deviceID; }
}
/// <summary>
/// State of the video source.
/// </summary>
///
/// <remarks>Current state of video source object - running or not.</remarks>
///
public bool IsRunning
{
get
{
lock ( sync )
{
return ( device != null );
}
}
}
/// <summary>
/// Received bytes count.
/// </summary>
///
/// <remarks>Number of bytes the video source provided from the moment of the last
/// access to the property.
/// </remarks>
///
public long BytesReceived
{
get
{
long bytes = bytesReceived;
bytesReceived = 0;
return bytes;
}
}
/// <summary>
/// Received frames count.
/// </summary>
///
/// <remarks>Number of frames the video source provided from the moment of the last
/// access to the property.
/// </remarks>
///
public int FramesReceived
{
get
{
int frames = framesReceived;
framesReceived = 0;
return frames;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="KinectVideoCamera"/> class.
/// </summary>
///
/// <param name="deviceID">Kinect's device ID (index) to connect to.</param>
///
public KinectVideoCamera( int deviceID )
{
this.deviceID = deviceID;
}
/// <summary>
/// Initializes a new instance of the <see cref="KinectVideoCamera"/> class.
/// </summary>
///
/// <param name="deviceID">Kinect's device ID (index) to connect to.</param>
/// <param name="resolution">Resolution of video camera to set.</param>
///
public KinectVideoCamera( int deviceID, CameraResolution resolution )
{
this.deviceID = deviceID;
this.resolution = resolution;
}
/// <summary>
/// Initializes a new instance of the <see cref="KinectVideoCamera"/> class.
/// </summary>
///
/// <param name="deviceID">Kinect's device ID (index) to connect to.</param>
/// <param name="resolution">Resolution of video camera to set.</param>
/// <param name="cameraMode">Sets video camera mode.</param>
///
public KinectVideoCamera( int deviceID, CameraResolution resolution, VideoCameraMode cameraMode )
{
this.deviceID = deviceID;
this.resolution = resolution;
this.cameraMode = cameraMode;
}
private Kinect device = null;
private IntPtr imageBuffer = IntPtr.Zero;
private KinectNative.BitmapInfoHeader videoModeInfo;
/// <summary>
/// Start video source.
/// </summary>
///
/// <remarks>Starts video source and returns execution to caller. Video camera will be started
/// and will provide new video frames through the <see cref="NewFrame"/> event.</remarks>
///
/// <exception cref="ArgumentException">The specified resolution is not supported for the selected
/// mode of the Kinect video camera.</exception>
/// <exception cref="ConnectionFailedException">Could not connect to Kinect's video camera.</exception>
/// <exception cref="DeviceBusyException">Another connection to the specified video camera is already running.</exception>
///
public void Start( )
{
lock ( sync )
{
lock ( runningCameras )
{
if ( device == null )
{
bool success = false;
try
{
if ( runningCameras.Contains( deviceID ) )
{
throw new DeviceBusyException( "Another connection to the specified video camera is already running." );
}
// get Kinect device
device = Kinect.GetDevice( deviceID );
KinectNative.VideoCameraFormat dataFormat = KinectNative.VideoCameraFormat.RGB;
if ( cameraMode == VideoCameraMode.Bayer )
{
dataFormat = KinectNative.VideoCameraFormat.Bayer;
}
else if ( cameraMode == VideoCameraMode.InfraRed )
{
dataFormat = KinectNative.VideoCameraFormat.IR8Bit;
}
// find video format parameters
videoModeInfo = KinectNative.freenect_find_video_mode( resolution, dataFormat );
if ( videoModeInfo.IsValid == 0 )
{
throw new ArgumentException( "The specified resolution is not supported for the selected mode of the Kinect video camera." );
}
// set video format
if ( KinectNative.freenect_set_video_mode( device.RawDevice, videoModeInfo ) != 0 )
{
throw new VideoException( "Could not switch to the specified video format." );
}
// allocate video buffer and provide it freenect
imageBuffer = Marshal.AllocHGlobal( (int) videoModeInfo.Bytes );
KinectNative.freenect_set_video_buffer( device.RawDevice, imageBuffer );
// set video callback
videoCallback = new KinectNative.FreenectVideoDataCallback( HandleDataReceived );
KinectNative.freenect_set_video_callback( device.RawDevice, videoCallback );
// start the camera
if ( KinectNative.freenect_start_video( device.RawDevice ) != 0 )
{
throw new ConnectionFailedException( "Could not start video stream." );
}
success = true;
runningCameras.Add( deviceID );
device.AddFailureHandler( deviceID, Stop );
}
finally
{
if ( !success )
{
if ( device != null )
{
device.Dispose( );
device = null;
}
if ( imageBuffer != IntPtr.Zero )
{
Marshal.FreeHGlobal( imageBuffer );
imageBuffer = IntPtr.Zero;
}
}
}
}
}
}
}
/// <summary>
/// Signal video source to stop its work.
/// </summary>
///
/// <remarks><para><note>Calling this method is equivalent to calling <see cref="Stop"/>
/// for Kinect video camera.</note></para></remarks>
///
public void SignalToStop( )
{
Stop( );
}
/// <summary>
/// Wait for video source has stopped.
/// </summary>
///
/// <remarks><para><note>Calling this method is equivalent to calling <see cref="Stop"/>
/// for Kinect video camera.</note></para></remarks>
///
public void WaitForStop( )
{
Stop( );
}
/// <summary>
/// Stop video source.
/// </summary>
///
/// <remarks><para>The method stops the video source, so it no longer provides new video frames
/// and does not consume any resources.</para>
/// </remarks>
///
public void Stop( )
{
lock ( sync )
{
lock ( runningCameras )
{
if ( device != null )
{
bool deviceFailed = device.IsDeviceFailed( deviceID );
if ( !deviceFailed )
{
KinectNative.freenect_stop_video( device.RawDevice );
}
device.Dispose( );
device = null;
runningCameras.Remove( deviceID );
if ( PlayingFinished != null )
{
PlayingFinished( this, ( !deviceFailed ) ?
ReasonToFinishPlaying.StoppedByUser : ReasonToFinishPlaying.DeviceLost );
}
}
if ( imageBuffer != IntPtr.Zero )
{
Marshal.FreeHGlobal( imageBuffer );
imageBuffer = IntPtr.Zero;
}
videoCallback = null;
}
}
}
// New video data event handler
private KinectNative.FreenectVideoDataCallback videoCallback = null;
private void HandleDataReceived( IntPtr device, IntPtr imageData, UInt32 timeStamp )
{
int width = videoModeInfo.Width;
int height = videoModeInfo.Height;
Bitmap image = null;
BitmapData data = null;
try
{
image = ( cameraMode == VideoCameraMode.Color ) ?
new Bitmap( width, height, PixelFormat.Format24bppRgb ) :
AForge.Imaging.Image.CreateGrayscaleImage( width, height );
data = image.LockBits( new Rectangle( 0, 0, width, height ),
ImageLockMode.ReadWrite, image.PixelFormat );
unsafe
{
byte* dst = (byte*) data.Scan0.ToPointer( );
byte* src = (byte*) imageBuffer.ToPointer( );
if ( cameraMode == VideoCameraMode.Color )
{
// color RGB 24 mode
int offset = data.Stride - width * 3;
for ( int y = 0; y < height; y++ )
{
for ( int x = 0; x < width; x++, src += 3, dst += 3 )
{
dst[0] = src[2];
dst[1] = src[1];
dst[2] = src[0];
}
dst += offset;
}
}
else
{
// infra red mode - grayscale output
int stride = data.Stride;
if ( stride != width )
{
for ( int y = 0; y < height; y++ )
{
SystemTools.CopyUnmanagedMemory( dst, src, width );
dst += stride;
src += width;
}
}
else
{
SystemTools.CopyUnmanagedMemory( dst, src, width * height );
}
}
}
image.UnlockBits( data );
framesReceived++;
bytesReceived += width * height;
}
catch ( Exception ex )
{
if ( VideoSourceError != null )
{
VideoSourceError( this, new VideoSourceErrorEventArgs( ex.Message ) );
}
if ( image != null )
{
if ( data != null )
{
image.UnlockBits( data );
}
image.Dispose( );
image = null;
}
}
if ( image != null )
{
if ( NewFrame != null )
{
NewFrame( this, new NewFrameEventArgs( image ) );
}
image.Dispose( );
}
}
}
}
|
lyuboasenov/scheduler
|
packages/AForge.NET Framework-2.2.5/Sources/Video.Kinect/KinectVideoCamera.cs
|
C#
|
mit
| 19,055 |
namespace DeviceHive.Data.EF.Migrations
{
using System.Data.Entity.Migrations;
public partial class _91 : DbMigration
{
public override void Up()
{
CreateTable(
"OAuthClient",
c => new
{
ID = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 128),
Domain = c.String(nullable: false, maxLength: 128),
Subnet = c.String(maxLength: 128),
RedirectUri = c.String(nullable: false, maxLength: 128),
OAuthID = c.String(nullable: false, maxLength: 32),
OAuthSecret = c.String(nullable: false, maxLength: 32),
})
.PrimaryKey(t => t.ID)
.Index(t => t.OAuthID, unique: true);
CreateTable(
"OAuthGrant",
c => new
{
ID = c.Int(nullable: false, identity: true),
Timestamp = c.DateTime(nullable: false, storeType: "datetime2"),
AuthCode = c.Guid(),
ClientID = c.Int(nullable: false),
UserID = c.Int(nullable: false),
AccessKeyID = c.Int(nullable: false),
Type = c.Int(nullable: false),
AccessType = c.Int(nullable: false),
RedirectUri = c.String(maxLength: 128),
Scope = c.String(nullable: false, maxLength: 256),
NetworkList = c.String(maxLength: 128),
})
.PrimaryKey(t => t.ID)
.ForeignKey("OAuthClient", t => t.ClientID, cascadeDelete: true)
.ForeignKey("User", t => t.UserID, cascadeDelete: true)
.ForeignKey("AccessKey", t => t.AccessKeyID, cascadeDelete: false)
.Index(t => t.ClientID)
.Index(t => t.UserID)
.Index(t => t.AccessKeyID);
Sql("CREATE UNIQUE NONCLUSTERED INDEX [IX_AuthCode] ON [OAuthGrant] ( [AuthCode] ASC ) WHERE [AuthCode] IS NOT NULL");
}
public override void Down()
{
DropIndex("OAuthGrant", new[] { "AccessKeyID" });
DropIndex("OAuthGrant", new[] { "UserID" });
DropIndex("OAuthGrant", new[] { "ClientID" });
DropIndex("OAuthGrant", new[] { "AuthCode" });
DropForeignKey("OAuthGrant", "AccessKeyID", "AccessKey");
DropForeignKey("OAuthGrant", "UserID", "User");
DropForeignKey("OAuthGrant", "ClientID", "OAuthClient");
DropTable("OAuthGrant");
DropIndex("OAuthClient", new[] { "OAuthID" });
DropTable("OAuthClient");
}
}
}
|
deus42/devicehive-.net
|
src/Server/DeviceHive.Data.EF/Migrations/201310111016567_9.1.cs
|
C#
|
mit
| 2,823 |
require File.dirname(__FILE__) + '/../test_helper'
require 'posts_controller'
require 'mailing_list_mailer'
# Re-raise errors caught by the controller.
class PostsController
def rescue_action(e)
raise e
end
end
# FIXME Navigation tests are weak. Need to do more than just not blow up
class PostsControllerTest < ActiveSupport::TestCase
def setup
@controller = PostsController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
ActionMailer::Base.delivery_method = :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries = []
end
def test_legacy_routing
assert_recognizes(
{:controller => "posts", :action => "show", :mailing_list_name => "obrarace", :id => "25621"},
"posts/show/obrarace/25621"
)
assert_recognizes(
{:controller => "posts", :action => "new", :mailing_list_name => "obra"},
"posts/new/obra"
)
end
def test_new
obra_chat = mailing_lists(:obra_chat)
get(:new, :mailing_list_name => obra_chat.name)
assert_response(:success)
assert_template("posts/new")
assert_not_nil(assigns["mailing_list"], "Should assign mailing_list")
assert_not_nil(assigns["mailing_list_post"], "Should assign mailing_list_post")
mailing_list_post = assigns["mailing_list_post"]
assert_equal(obra_chat, mailing_list_post.mailing_list, "Post's mailing list")
assert_tag(:tag => "input", :attributes => {:type => "hidden", :name => "mailing_list_post[mailing_list_id]", :value => obra_chat.id})
assert_tag(:tag => "input", :attributes => {:type => "text", :name => "mailing_list_post[subject]"})
assert_tag(:tag => "input", :attributes => {:type => "text", :name => "mailing_list_post[from_email_address]"})
assert_tag(:tag => "input", :attributes => {:type => "text", :name => "mailing_list_post[from_name]"})
assert_tag(:tag => "textarea", :attributes => {:name => "mailing_list_post[body]"})
assert_tag(:tag => "input", :attributes => {:type => "submit", :name => "commit", :value => "Post"})
end
def test_new_reply
obra_race = mailing_lists(:obra_race)
original_post = Post.create({
:mailing_list => obra_race,
:subject => "Only OBRA Race Message",
:date => Date.today,
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
get(:new, :mailing_list_name => obra_race.name, :reply_to => original_post.id)
assert_response(:success)
assert_template("posts/new")
assert_not_nil(assigns["mailing_list"], "Should assign mailing_list")
mailing_list_post = assigns["mailing_list_post"]
assert_not_nil(mailing_list_post, "Should assign mailing_list_post")
assert_equal(original_post, assigns["reply_to"], "Should assign reply_to")
assert_equal("Re: Only OBRA Race Message", mailing_list_post.subject, 'Prepopulated subject')
assert_equal(obra_race, mailing_list_post.mailing_list, "Post's mailing list")
assert_tag(:tag => "input", :attributes => {:type => "hidden", :name => "mailing_list_post[mailing_list_id]", :value => obra_race.id})
assert_tag(:tag => "input", :attributes => {:type => "text", :name => "mailing_list_post[subject]"})
assert_tag(:tag => "input", :attributes => {:type => "text", :name => "mailing_list_post[from_email_address]"})
assert_tag(:tag => "input", :attributes => {:type => "text", :name => "mailing_list_post[from_name]"})
assert_tag(:tag => "textarea", :attributes => {:name => "mailing_list_post[body]"})
assert_tag(:tag => "input", :attributes => {:type => "submit", :name => "commit", :value => "Send"})
end
def test_index_routing
obra_chat = mailing_lists(:obra_chat)
opts = {:controller => "posts", :action => "index", :mailing_list_name => obra_chat.name}
assert_routing("posts/obra", opts)
end
def test_index
get(:index, :mailing_list_name => "obrarace")
assert_response(:redirect)
assert_redirected_to(
:action => "list",
:mailing_list_name => "obrarace",
:month => Date.today.month,
:year => Date.today.year
)
end
def test_list
obra_chat = mailing_lists(:obra_chat)
for index in 1..22
date = Time.now.beginning_of_month + index * 3600 * 24
Post.create({
:mailing_list => obra_chat,
:subject => "Subject Test #{index}",
:date => date,
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message #{index}"
})
end
obra_race = mailing_lists(:obra_race)
Post.create({
:mailing_list => obra_race,
:subject => "Only OBRA Race Message",
:date => date,
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
get(:list, :mailing_list_name => obra_chat.name, :month => Time.now.month, :year => Time.now.year)
assert_response(:success)
assert_not_nil(assigns["mailing_list"], "Should assign mailing_list")
assert_not_nil(assigns["year"], "Should assign month")
assert_not_nil(assigns["month"], "Should assign year")
assert_not_nil(assigns["posts"], "Should assign posts")
assert_equal(22, assigns["posts"].size, "Should show recent posts")
assert_equal(Date.today.month, assigns["month"], "Assign month")
assert_equal(Date.today.year, assigns["year"], "Assign year")
assert_template("posts/list")
get(:list, :mailing_list_name => obra_race.name, :month => Time.now.month, :year => Time.now.year)
assert_response(:success)
assert_not_nil(assigns["mailing_list"], "Should assign mailing_list")
assert_not_nil(assigns["year"], "Should assign month")
assert_not_nil(assigns["month"], "Should assign year")
assert_not_nil(assigns["posts"], "Should assign posts")
assert_equal(1, assigns["posts"].size, "Should show recent posts")
assert_equal(Date.today.month, assigns["month"], "Assign month")
assert_equal(Date.today.year, assigns["year"], "Assign year")
assert_template("posts/list")
end
def test_list_with_date
obra_race = mailing_lists(:obra_race)
post_2004_12_01 = Post.create({
:mailing_list => obra_race,
:subject => "BB 1 Race Results",
:date => Date.new(2004, 12, 1),
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
post_2004_11_31 = Post.create({
:mailing_list => obra_race,
:subject => "Cherry Pie Race Results",
:date => Date.new(2004, 11, 30),
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
post_2004_12_31 = Post.create({
:mailing_list => obra_race,
:subject => "Schedule Changes",
:date => Time.local(2004, 12, 31, 23, 59, 59, 999999),
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
get(:list, :mailing_list_name => obra_race.name, :year => "2004", :month => "11")
assert_response(:success)
assert_not_nil(assigns["mailing_list"], "Should assign mailing_list")
assert_not_nil(assigns["year"], "Should assign month")
assert_not_nil(assigns["month"], "Should assign year")
assert_not_nil(assigns["posts"], "Should assign posts")
assert_equal(1, assigns["posts"].size, "Should show recent posts")
assert_equal(11, assigns["month"], "Assign month")
assert_equal(2004, assigns["year"], "Assign year")
assert_equal(post_2004_11_31, assigns["posts"].first, "Post")
assert_template("posts/list")
get(:list, :mailing_list_name => obra_race.name, :year => "2004", :month => "12")
assert_response(:success)
assert_not_nil(assigns["mailing_list"], "Should assign mailing_list")
assert_not_nil(assigns["year"], "Should assign month")
assert_not_nil(assigns["month"], "Should assign year")
assert_not_nil(assigns["posts"], "Should assign posts")
assert_equal(2, assigns["posts"].size, "Should show recent posts")
assert_equal(12, assigns["month"], "Assign month")
assert_equal(2004, assigns["year"], "Assign year")
assert_equal(post_2004_12_31, assigns["posts"].first, "Post")
assert_equal(post_2004_12_01, assigns["posts"].last, "Post")
assert_template("posts/list")
get(:list, :mailing_list_name => obra_race.name, :year => "2004", :month => "10")
assert_response(:success)
assert_not_nil(assigns["mailing_list"], "Should assign mailing_list")
assert_not_nil(assigns["year"], "Should assign month")
assert_not_nil(assigns["month"], "Should assign year")
assert_not_nil(assigns["posts"], "Should assign posts")
assert_equal(10, assigns["month"], "Assign month")
assert_equal(2004, assigns["year"], "Assign year")
assert(assigns["posts"].empty?, "No posts")
assert_template("posts/list")
end
def test_list_previous_next
obra_race = mailing_lists(:obra_race)
post_2004_12_01 = Post.create({
:mailing_list => obra_race,
:subject => "BB 1 Race Results",
:date => Date.new(2004, 12, 1),
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
post_2004_11_31 = Post.create({
:mailing_list => obra_race,
:subject => "Cherry Pie Race Results",
:date => Date.new(2004, 11, 30),
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
post_2004_12_31 = Post.create({
:mailing_list => obra_race,
:subject => "Schedule Changes",
:date => Time.local(2004, 12, 31, 23, 59, 59, 999999),
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
get(:list, :mailing_list_name => obra_race.name, :year => "2004", :month => "11", :next => ">")
assert_response(:redirect)
assert_redirected_to(:month => 12, :year => 2004)
get(:list, :mailing_list_name => obra_race.name, :year => "2004", :month => "12", :next => ">")
assert_response(:redirect)
assert_redirected_to(:month => 1, :year => 2005)
get(:list, :mailing_list_name => obra_race.name, :year => "2004", :month => "12", :previous => "<")
assert_response(:redirect)
assert_redirected_to(:month => 11, :year => 2004)
end
def test_list_routing
path = {:controller => "posts", :action => "list", :mailing_list_name => "obra", :year => "2003", :month => "8"}
assert_routing("posts/obra/2003/8", path)
end
def test_post
assert(MailingListMailer.deliveries.empty?, "Should have no email deliveries")
obra_chat = mailing_lists(:obra_chat)
subject = "Spynergy for Sale"
from_name = "Tim Schauer"
from_email_address = "[email protected]"
body = "Barely used"
path = {:controller => "posts", :action => "post", :mailing_list_name => 'obra'}
assert_routing("posts/obra/post", path)
post(:post,
:mailing_list_name => obra_chat.name,
:reply_to => {:id => ''},
:mailing_list_post => {
:mailing_list_id => obra_chat.id,
:subject => subject,
:from_name => from_name,
:from_email_address => from_email_address,
:body => body},
:commit => "Post"
)
assert(flash.has_key?(:notice))
assert_response(:redirect)
assert_redirected_to(:action => "confirm", :mailing_list_name => obra_chat.name)
assert_equal(1, MailingListMailer.deliveries.size, "Should have one email delivery")
delivered_mail = MailingListMailer.deliveries.first
assert_equal(subject, delivered_mail.subject, "Subject")
assert_equal([from_email_address], delivered_mail.from, "From email")
assert_equal(from_name, delivered_mail.friendly_from, "From Name")
assert_equal_dates(Date.today, delivered_mail.date, "Date")
assert_equal([obra_chat.name], delivered_mail.to, "Recipient")
end
def test_post_reply
assert(MailingListMailer.deliveries.empty?, "Should have no email deliveries")
obra_chat = mailing_lists(:obra_chat)
subject = "Spynergy for Sale"
from_name = "Tim Schauer"
from_email_address = "[email protected]"
body = "Barely used"
reply_to_post = Post.create({
:mailing_list => obra_chat,
:subject => "Schedule Changes",
:date => Time.local(2004, 12, 31, 23, 59, 59, 999999),
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
path = {:controller => "posts", :action => "post", :mailing_list_name => 'obra'}
assert_routing("posts/obra/post", path)
post(:post,
:mailing_list_name => obra_chat.name,
:mailing_list_post => {
:mailing_list_id => obra_chat.id,
:subject => subject,
:from_name => from_name,
:from_email_address => from_email_address,
:body => body},
:reply_to => {:id => reply_to_post.id},
:commit => "Post"
)
assert(flash.has_key?(:notice))
assert_response(:redirect)
assert_redirected_to(:action => "confirm_private_reply", :mailing_list_name => obra_chat.name)
assert_equal(1, MailingListMailer.deliveries.size, "Should have one email delivery")
delivered_mail = MailingListMailer.deliveries.first
assert_equal(subject, delivered_mail.subject, "Subject")
assert_equal([from_email_address], delivered_mail.from, "From email")
assert_equal(from_name, delivered_mail.friendly_from, "From Name")
assert_equal_dates(Date.today, delivered_mail.date, "Date")
assert_equal(['[email protected]'], delivered_mail.to, "Recipient")
end
def test_post_invalid_reply
obra_chat = mailing_lists(:obra_chat)
subject = "Spynergy for Sale"
from_name = "Tim Schauer"
from_email_address = "[email protected]"
body = "Barely used"
reply_to_post = Post.create!(
:mailing_list => obra_chat,
:subject => "Schedule Changes",
:date => Time.local(2004, 12, 31, 23, 59, 59, 999999),
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
)
post(:post,
:mailing_list_name => obra_chat.name,
:mailing_list_post => {
:mailing_list_id => obra_chat.id,
:subject => "Re: #{subject}",
:from_name => "",
:from_email_address => "",
:body => ""},
:reply_to => {:id => reply_to_post.id},
:commit => "Send"
)
assert_template("posts/new")
assert_not_nil(assigns["mailing_list"], "Should assign mailing_list")
mailing_list_post = assigns["mailing_list_post"]
assert_not_nil(mailing_list_post, "Should assign mailing_list_post")
assert_equal(reply_to_post, assigns["reply_to"], "Should assign reply_to")
assert_equal("Re: #{subject}", mailing_list_post.subject, 'Prepopulated subject')
assert_equal(obra_chat, mailing_list_post.mailing_list, "Post's mailing list")
end
def test_confirm
obra_race = mailing_lists(:obra_race)
path = {:controller => "posts", :action => "confirm", :mailing_list_name => obra_race.name }
assert_routing("posts/obrarace/confirm", path)
get(:confirm, :mailing_list_name => obra_race.name)
assert_response(:success)
assert_template("posts/confirm")
assert_equal(obra_race, assigns["mailing_list"], 'Should assign mailing list')
end
def test_confirm_private_reply
obra_race = mailing_lists(:obra_race)
path = {:controller => "posts", :action => "confirm_private_reply", :mailing_list_name => obra_race.name }
assert_routing("posts/obrarace/confirm_private_reply", path)
get(:confirm_private_reply, :mailing_list_name => obra_race.name)
assert_response(:success)
assert_template("posts/confirm_private_reply")
assert_equal(obra_race, assigns["mailing_list"], 'Should assign mailing list')
end
def test_show
obra_race = mailing_lists(:obra_race)
new_post = Post.create({
:mailing_list => obra_race,
:subject => "Only OBRA Race Message",
:date => Time.now,
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
new_post.save!
path = {:controller => "posts", :action => "show", :mailing_list_name => obra_race.name, :id => new_post.id.to_s }
assert_routing("posts/obrarace/show/#{new_post.id}", path)
get(:show, :mailing_list_name => obra_race.name, :id => new_post.id)
assert_response(:success)
assert_not_nil(assigns["post"], "Should assign post")
assert_template("posts/show")
end
def test_archive_navigation
# No posts
get(:list, :mailing_list_name => "obrarace", :year => "2004", :month => "12")
assert_tag(:tag => "div", :attributes => {:class => "archive_navigation"})
# One post
obra_race = mailing_lists(:obra_race)
new_post = Post.create({
:mailing_list => obra_race,
:subject => "Only OBRA Race Message",
:date => Time.local(2004, 12, 31, 12, 30),
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
get(:list, :mailing_list_name => "obrarace", :year => "2004", :month => "12")
assert_tag(:tag => "div", :attributes => {:class => "archive_navigation"})
# Two months
obra_race = mailing_lists(:obra_race)
new_post = Post.create({
:mailing_list => obra_race,
:subject => "Before OBRA Race Message",
:date => Time.local(2004, 11, 7),
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
get(:list, :mailing_list_name => "obrarace", :year => "2004", :month => "11")
assert_tag(:tag => "div", :attributes => {:class => "archive_navigation"})
end
def test_post_navigation
# One post
obra_race = mailing_lists(:obra_race)
post_2004_12_31 = Post.create({
:mailing_list => obra_race,
:subject => "Only OBRA Race Message",
:date => Time.local(2004, 12, 31, 12, 30),
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
get(:show, :mailing_list_name => obra_race.name, :id => post_2004_12_31.id)
# Two months
post_2004_11_07 = Post.create({
:mailing_list => obra_race,
:subject => "Before OBRA Race Message",
:date => Time.local(2004, 11, 7),
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
get(:show, :mailing_list_name => obra_race.name, :id => post_2004_12_31.id)
# Three months
post_2004_11_03 = Post.create({
:mailing_list => obra_race,
:subject => "Before OBRA Race Message",
:date => Time.local(2004, 11, 3, 8, 00, 00),
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
get(:show, :mailing_list_name => obra_race.name, :id => post_2004_11_07.id)
# Another list
obra_chat = mailing_lists(:obra_chat)
post_other_list = Post.create({
:mailing_list => obra_chat,
:subject => "OBRA Chat",
:date => Time.local(2004, 11, 3, 21, 00, 00),
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
get(:show, :mailing_list_name => obra_race.name, :id => post_2004_11_07.id)
assert_tag(:tag => "div", :attributes => {:class => "archive_navigation"})
end
def test_post_previous_next
obra_race = mailing_lists(:obra_race)
post_2004_12_01 = Post.create({
:mailing_list => obra_race,
:subject => "BB 1 Race Results",
:date => Time.local(2004, 12, 1),
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
post_2004_11_31 = Post.create({
:mailing_list => obra_race,
:subject => "Cherry Pie Race Results",
:date => Time.local(2004, 11, 30),
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
post_2004_12_31 = Post.create({
:mailing_list => obra_race,
:subject => "Schedule Changes",
:date => Time.local(2004, 12, 31, 23, 59, 59, 999999),
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
get(:show, :mailing_list_name => obra_race.name, :next_id => post_2004_12_31.id, :next => ">")
assert_response(:redirect)
assert_redirected_to(:id => post_2004_12_31.id.to_s)
get(:show, :mailing_list_name => obra_race.name, :previous_id => post_2004_11_31.id, :previous => "<")
assert_response(:redirect)
assert_redirected_to(:id => post_2004_11_31.id.to_s)
# This part doesn't prove much
obra_chat = mailing_lists(:obra_chat)
post_other_list = Post.create({
:mailing_list => obra_chat,
:subject => "OBRA Chat",
:date => Time.local(2004, 12, 31, 12, 00, 00),
:from_name => "Scout",
:from_email_address => "[email protected]",
:body => "This is a test message."
})
get(:show, :mailing_list_name => obra_race.name, :next_id => post_2004_12_31.id, :next => ">")
assert_response(:redirect)
assert_redirected_to(:id => post_2004_12_31.id.to_s)
end
def test_list_with_no_lists
MailingList.delete_all
get(:list, :month => Date.today.month, :year => Date.today.year)
assert_response(:success)
assert_template('404')
assert(!flash.empty?, "Should have flash")
end
def test_list_with_bad_name
get(:list, :month => Date.today.month, :year => Date.today.year, :mailing_list_name => "Masters Racing")
assert_response(:success)
assert_template('404')
assert(!flash.empty?, "Should have flash")
end
def test_list_with_bad_month
get(:list, :month => 14, :year => Date.today.year, :mailing_list_name => mailing_lists(:obra_race).name)
assert_redirected_to(
:action => "list",
:mailing_list_name => "obrarace",
:month => Date.today.month,
:year => Date.today.year
)
end
def test_list_with_bad_year
get(:list, :month => 12, :year => 9_116_560, :mailing_list_name => mailing_lists(:obra_race).name)
assert_redirected_to(
:action => "list",
:mailing_list_name => "obrarace",
:month => Date.today.month,
:year => Date.today.year
)
end
end
|
theRocket/wsbaracing
|
test/functional/posts_controller_test.rb
|
Ruby
|
mit
| 22,857 |
class Views::Test::NeedsSubclass < Views::Test::Needs
def content
text "NeedsSubclass #{@foobar}"
end
end
|
erector/erector
|
spec/rails_root/app/views/test/needs_subclass.html.rb
|
Ruby
|
mit
| 114 |
namespace MonoGame.Extended.Collisions
{
public class CollisionGridCell : ICollidable
{
private readonly CollisionGrid _parentGrid;
public CollisionGridCell(CollisionGrid parentGrid, int column, int row, int data)
{
_parentGrid = parentGrid;
Column = column;
Row = row;
Data = data;
Flag = data == 0 ? CollisionGridCellFlag.Empty : CollisionGridCellFlag.Solid;
}
public int Column { get; }
public int Row { get; }
public int Data { get; private set; }
public object Tag { get; set; }
public CollisionGridCellFlag Flag { get; set; }
public RectangleF BoundingBox => _parentGrid.GetCellRectangle(Column, Row).ToRectangleF();
}
}
|
cra0zy/MonoGame.Extended
|
Source/MonoGame.Extended.Collisions/CollisionGridCell.cs
|
C#
|
mit
| 786 |
//
// GPDownloader.h
// test
//
// Created by mac on 15-2-3.
// Copyright (c) 2015年 gpr. All rights reserved.
//
#import <Foundation/Foundation.h>
@class GPDownloader;
typedef NS_ENUM(NSUInteger, GPDownloaderStatus) {
GPDownloaderStatusReady,
GPDownloaderStatusDownLoading,
GPDownloaderStatusPause,
GPDownloaderStatusFinish,
GPDownloaderStatusDestory,
GPDownloaderStatusError
};
// 这些block都不在主线程中执行
typedef void(^StartTaskBlock)(GPDownloader * downloader);
typedef void(^ProgressBlock)(unsigned long long currDownloadSize);
typedef void(^CompleteBlock)(GPDownloader *downloader);
typedef void(^ErrorBlock)(GPDownloader *mdownloader,NSError *error);
// 代理,注意代理方法运行在子线程中
@protocol GPDownloaderDelegate <NSObject>
- (void)downloaderDidStart:(GPDownloader *) downloader;
- (void)downloaderDidUpdateDataSize:(unsigned long long)currDownloadSize;
- (void)downloaderDidComplete:(GPDownloader *) downloader;
- (void)downloader:(GPDownloader *)downloader DidDownLoadFail:(NSError *)error;
@end
@interface GPDownloader : NSObject
#pragma mark - 初始化
+ (instancetype)downloaderWithURLString:(NSString *)urlString downloadRange:(NSRange)downloadRange fileName:(NSString *)fileName;
- (instancetype)initWithURLString:(NSString *)urlString downloadRange:(NSRange)downloadRange fileName:(NSString *)fileName;
+ (instancetype)downloaderWithURLString:(NSString *)urlString downloadRange:(NSRange)downloadRange startBlock:(StartTaskBlock)startBlock progressBlock:(ProgressBlock)progressBlock completeBlock:(CompleteBlock)completeBlock errorBlock:(ErrorBlock)errorBlock fileName:(NSString *)fileName;
- (instancetype)initWithURLString:(NSString *)urlString downloadRange:(NSRange)downloadRange startBlock:(StartTaskBlock)startBlock progressBlock:(ProgressBlock)progressBlock completeBlock:(CompleteBlock)completeBlock errorBlock:(ErrorBlock)errorBlock fileName:(NSString *)fileName;
@property (nonatomic,copy) NSString *urlString;
@property (nonatomic,assign) NSRange downloadRange;
@property (nonatomic,strong) NSString *fileName;
/** 用来标志下载文件的顺序,以便以后拼接文件方便 */
@property (nonatomic,assign) NSInteger fileIndex;
/** 当连接失败的时候会尝试重新连接,默认重新尝试连接次数为3 */
@property (nonatomic,assign) NSInteger maxRestartCount;
/** 已经下载的长度 */
@property (nonatomic,assign) unsigned long long currFileSize;
/** 代理 */
@property (nonatomic,weak) id<GPDownloaderDelegate> delegate;
/** 超时时间,默认为5秒*/
@property (nonatomic,assign) NSTimeInterval timeOut;
/** 临时文件的名字,用于标识一个 GPDownloader 的唯一标识 */
@property (nonatomic,copy,readonly) NSString *tempFilePath;
#pragma mark - 监听下载状态
//@property (nonatomic,assign) GPDownloaderStatus state;
@property (nonatomic,copy) StartTaskBlock startBlock;
@property (nonatomic,copy) ProgressBlock progressBlock;
@property (nonatomic,copy) CompleteBlock completeBlock;
@property (nonatomic,copy) ErrorBlock errorBlock;
#pragma mark - 下载器状态管理
- (void)startDownloadTask;
- (void)pause;
- (void)resume;
- (void)stop;
- (void)destoryDownloader;
@end
|
gpr321/amusement
|
category/category/GPDownloader1/GPDownloader.h
|
C
|
mit
| 3,235 |
/*
Document : main
Created on : Oct 12, 2013, 12:37:21 PM
Author : Andres
Description: Purpose of the stylesheet follows.
*/
.crud-table td{
padding-right: 10px;
padding-bottom: 10px;
padding-top: 0px;
}
/* ------ Mix ------ */
#Grid{
width: 398px;
margin: 0px;
padding: 0px;
overflow: scroll;
overflow-x: hidden;
max-height: 500px;
}
#Grid:after{
content: '';
display: inline-block;
width: 100%;
}
#Grid .mix{
display: none;
opacity: 0;
vertical-align: top;
text-align: center;
width: 100px;
height: 160px;
font-size: 10px;
color: #000000;
margin-bottom: 10px;
margin-left: 18px;
}
#Grid .mix{
display: none;
opacity: 0;
vertical-align: top;
text-align: center;
width: 100px;
height: 150px;
font-size: 10px;
color: #000000;
margin-bottom: 10px;
margin-left: 18px;
}
#Grid .mix a{
text-decoration: none;
color: #000000;
}
#Grid .mix a span{
display: inline-block;
height: 35px;
}
#Grid .mix.seleccionado{
background: #3297fd;
color: #FFFFFF;
outline: 5px solid #3297fd;
font-weight: bold;
}
#Grid .mix.seleccionado a{
color: #FFFFFF;
}
#Grid .gap{
display: inline-block;
width: 200px;
}
/* ------ Pedido producto -------*/
.pPedidoProducto{
width: 800px;
}
.tProductoPedido td{
vertical-align: top;
padding-bottom: 20px;
padding-right: 10px;
}
/* ------ Tabla colapse --------*/
.tColapse td{
padding: 1px !important;
}
.tColapse th{
padding: 1px !important;
}
/*
.records_list td:last-child{
text-align: right;
}
*/
.crud-table{
border: 10px solid #eeefff;
background-color: #eeefff;
}
/* ------ Selecciones menu --------*/
.controlm.selected{
background: #39b3d7;
}
.cobrosm.selected{
background: #ed9c28;
}
.produccionm.selected{
background: #47a447;
}
.tareasm.selected{
background: #6f5499;
}
.tareasm.selected a, .produccionm.selected a, .cobrosm.selected a, .controlm.selected a{
color: #FFFFFF !important;
}
/*tr.odd td.highlighted {
background-color: #D3D6FF;
}*/
tr.even td.highlighted {
background-color: #EAEBFF;
}
.t_control tr.even td, .t_control tr.odd td, table.t_control.dataTable tr.odd td.sorting_1, table.t_control.dataTable tr.even td.sorting_1{
background-color: #DBF7FF;
}
.t_cobros tr.even td, .t_cobros tr.odd td, table.t_cobros.dataTable tr.odd td.sorting_1, table.t_cobros.dataTable tr.even td.sorting_1{
background-color: #FFE9C9;
}
.t_produccion tr.even td, .t_produccion tr.odd td, table.t_produccion.dataTable tr.odd td.sorting_1, table.t_produccion.dataTable tr.even td.sorting_1{
background-color: #D6FFD6;
}
.t_tareas tr.even td, .t_tareas tr.odd td, table.t_tareas.dataTable tr.odd td.sorting_1, table.t_tareas.dataTable tr.even td.sorting_1{
background-color: #EEE3FF;
}
|
pacordovad/project3
|
web/bundles/frontend/css/main.css
|
CSS
|
mit
| 2,941 |
'use strict';
var getTemplatedStylesheet = require('./templatedStylesheet'),
path = require('path');
module.exports = getTemplatedStylesheet(path.join(__dirname, '/templates/stylus.tpl'));
|
filippovdaniil/node-sprite-generator
|
lib/stylesheet/stylus.js
|
JavaScript
|
mit
| 195 |
import React from 'react'
import Icon from 'react-icon-base'
const MdTonality = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m32.9 23.4c0.1-0.6 0.2-1.2 0.3-1.8h-11.6v1.8h11.3z m-2.5 5c0.4-0.6 0.9-1.2 1.2-1.8h-10v1.8h8.8z m-8.8 4.8c1.8-0.2 3.4-0.8 4.9-1.6h-4.9v1.6z m0-16.6v1.8h11.6c-0.1-0.6-0.2-1.2-0.3-1.8h-11.3z m0-5v1.8h10c-0.4-0.6-0.8-1.2-1.2-1.8h-8.8z m0-4.8v1.6h4.9c-1.5-0.8-3.1-1.4-4.9-1.6z m-3.2 26.4v-26.4c-6.6 0.8-11.8 6.4-11.8 13.2s5.2 12.4 11.8 13.2z m1.6-29.8c9.2 0 16.6 7.4 16.6 16.6s-7.4 16.6-16.6 16.6-16.6-7.4-16.6-16.6 7.4-16.6 16.6-16.6z"/></g>
</Icon>
)
export default MdTonality
|
bengimbel/Solstice-React-Contacts-Project
|
node_modules/react-icons/md/tonality.js
|
JavaScript
|
mit
| 635 |
---
title: "Ny fiarahan'Andriamanitra"
date: 30/03/2021
---
Mariho ireo teny voalohany indrindra nataon'Andriamanitra tamin'ny olombelona, na farafaharatsiny araka izay fisehony voalohany ao amin'ny Soratra Masina. Nampahafantarin'Andriamanitra azy ireo ny fahafahany mamorona, miteraka olona tahaka azy ireo ihany. Nasehony azy koa ny tany, ny voary, ary nasaina nameno, nampanompo, sy nanjaka taminy izy ireo. Natorony azy ireo koa ireo zava-maniry azon'izy ireo ihinanana. Raha fintinina izany ny voalazan'ny Baiboly dia mikasika ny fifandraisan'izy ireo amin'ny tontolo mísy azy sy ny fampiasany izany no teny voalohany nataon'Andriamanitra ho an'ny lehilahy sy ny vehivavy.
`Inona no ambaran'ny Gen. 1:28,29 antsika mikasika ny fomba fijerin'Andriamanitra ny tontolo hita maso sy azo-tsapain-tanana? Mampiseho ve ireo andininy ireo fa misy ratsy ao amin'ny zavatra ara-materialy na ny fisitrahantsika izany? Inona no lesona azontsika raisina avy amin'ireo toe-javatra voalohany teo amin'ny tantaran'ny taranak'olombelona ireo, mikasika ny tokony ho fifandraisantsika amin'ny voary?`
Amin'ireo teny ireo ihany koa Andriamanitra dia manao dingana voalohany amin'ny fifandraisana amin'ny olombelona. Miresaka amin'izy ireo Izy; manome toromarika azy, milaza aminy ny tokony hataony. Misy andraikitra ihany koa ao ambadik'ireo teny ireo. Nasain'Andriamanitra nifehy io voary mahatalanjona noforonin'ny Tenany io izy ireo.
`Milaza ny Gen. 1:28 fa nitso-drano an'i Adama sy Eva Andriamanitra. Inona no hevitr'izany? Karazam-pifandraisana inona eo amin'izy ireo sy ny Mpahary azy no asehon'izany?`
Ny firesak’Andriamanitra tamin'i Adama sy Eva dia toy ny amin'ny voary manan-tsaina izay afaka hanisy setriny ny hatsaram-panahiny sy afaka hifandray am-po Aminy. I Adama sy Eva koa, amin'ny maha-voary zanaka azy ireo, dia niankina tamin'ny fitahiana sy ny fiahian'llay Rainy Mpahary azy. Tsy nisy na inona na inona naha-mendrika azy ireo hahazo izay nomen'ny Mpahary azy. Nandray maimaimpoana zavatra izay tsy nisasarany izy ireo.
`Rehefa mamaky ny momba ny famoronana ny lehilahy sy ny vehivavy talohan'ny nisian'ny fahotana isika, dia mahita santionany amin'ilay karazam-pifandraisana tian'Andriamanitra ifandraisana amintsika ankehitriny, dia amin'izao fotoana efa isian'ny fahotana izao. Avereno jerena ity lesona androany ity. Inona ireo hevitra mifanindran-dalana ao ka afaka hanampy antsika hahatakatra ny fomba mety ifandraisantsika Aminy, na dia amin'izao fahalavoana misy antsika izao aza?`
|
imasaru/sabbath-school-lessons
|
src/mg/2021-02/01/04.md
|
Markdown
|
mit
| 2,507 |
---
title: අනුවණකම සහ ඥානවන්තකම
date: 02/12/2020
---
`හිතෝපදේශ 1 කියවන්න. සැබෑ ක්රිස්තියානි අධ්යාපනය කුමක් විය යුතුද යන්න පිළිබඳව මෙය අපට උගන්වන්නේ කුමක්ද?`
අනුවණකම සහ ඥානවන්තකම අතර ස්ථිරවූ සංසන්දනයක් ශුද්ධ බයිබලය තුළින් පෙන්වා දෙයි. අනුවණ ලෙස හැසිරීම සහ අනුවණයන් සමඟ ඇසුරු කිරීම පිලිබඳ අන්තරායන් පිළිබඳව හිතෝපදේශ පොත අපට සිහිපත් කර දෙයි. වෙනස ඉතා පැහැදිලිය: දෙවියන්වහන්සේ ආශා කරන්නේ තම සෙනඟ ඥානය සොයමින්, එය අගය කරමින්, එය තුළ පූර්ණ වීමය.
කලාව හා විද්යාව හදාරන ශිෂ්යයින් දැනුම වැඩි කරගැනීමට සහ ඔවුන්ගේ අධ්යයන කටයුතුවල විශිෂ්ටත්වය පසුපස යෑමට ඔවුන්ගේ හැකියාවන් භාවිතයේ යොදවති. මෙම ශික්ෂාවන්හි ගුරුවරුන්ද එළෙසම කරති. දැනුම සහ හැකියාව හේතුකොටගෙන අපට කලාත්මක සුවිශේෂී දස්කමක් හා විද්යානුකූල වූ විශාල ඉදිරි පියවරක් ගැනීමට හැකි වන්නට පුළුවන.
ක්රිස්තියානි දෘෂ්ටි කෝණයකින් බලනා කල, කලාව හා විද්යාව තුළ දැනුම මඟින් හොඳ සහ නරක අතරද, යහපත සහ අයහපත අතරද, සත්යය සහ වරද අතරද ඇති වෙනස දැනගැනීම කෙරෙහි එය සම්බන්ධ කර නොගන්නේ නම් එයින් අදහස් කරන්නේ කුමක්ද? නිදසුනක් වශයෙන්, යමෙකු විසින් කළ යුතුව ඇති සියල්ල වන්නේ අපූර්ව වූ කුසලතා හා දක්ෂතා තිබීම සදාචාරාත්මක හෝ ඉතා අවංක වූ දැහැමි දිවියකට සමාන නොවන බව දැකීම සඳහා ලෝකයේ අග්රගණයේ කලාකරුවන් ලෙස සැලකෙන ඇතැම් අයගේ ජීවිත ගැන මඳක් කියවා බැලීම වේ. යමෙකු හට තර්ක කළ හැකි දෙයක් වන්නේ, සමූහ විනාශය සඳහා ජීව විද්යාත්මක හෝ රසායනික අවි නිර්මාණය කිරීමේ කාර්යයට සම්බන්ධිත ශ්රේෂ්ඨ විද්යාඥයින් උසස් අධ්යාපනය ලැබූ, සුවිශේෂී කුසලතාවයන්ගෙන් යුත් අය විය හැකි නමුත්, ඔවුන්ගේ කාර්යයේ ඵලය කුමක් වන්නේද? යන්නයි. පෙර සඳහන් කළ පරිදි, නියතවශයෙන්ම දැනුම, එය තුළම පැවතීම යහපත් වූ දෙයක් නොවෙයි.
`හිතෝපදේශ 1: 7 කියවන්න. සැබෑ ක්රිස්තියානි අධ්යාපනයේ වැදගත් වන්නේ කුමක්ද යන්න ගැන මෙම පාඨයෙන් හෙළි වන්නේ කෙසේද?`
`එක් නොබෙල් ත්යාගලාභියෙකුද, අදේවවාදියෙකුද වූ විශ්වය සහ එහි ඇති භෞතික බලයන් පිළිබඳව අධ්යයනය කරනා මිනිසෙක් විසින් මෙසේ ලියන්නට විය: “විශ්වය වඩා තේරුම් ගත හැකි ලෙස පෙනෙන තරමට එය වඩා අර්ථ විරහිත ලෙසද පෙනෙන්නට වෙයි.” දැනුම, එය තුළම පැවතීම මඟින් එය අර්ථ විරහිත වනවා පමණක් නොව, ඊටත් වඩා යහපත්ව හඳුනා නොගත් වැරදි වලටද තුඩු දෙන්නේ කෙසේද යන්න ගැන මින් අපට කිව යුත්තේ කුමක්ද?`
|
imasaru/sabbath-school-lessons
|
src/si/2020-04/10/05.md
|
Markdown
|
mit
| 5,156 |
<?php
namespace Censo\CensoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* TipoViviendas
*
* @ORM\Table(name="tipo_viviendas")
* @ORM\Entity
*/
class TipoViviendas
{
/**
* @var integer
*
* @ORM\Column(name="id", type="bigint", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
* @ORM\SequenceGenerator(sequenceName="tipo_viviendas_id_seq", allocationSize=1, initialValue=1)
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="nombre", type="string", length=255, nullable=false)
*/
private $nombre;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nombre
*
* @param string $nombre
* @return TipoViviendas
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* @return string
*/
public function getNombre()
{
return $this->nombre;
}
public function __toString() {
return $this->getNombre();
}
}
|
profa1131/censo
|
src/Censo/CensoBundle/Entity/TipoViviendas.php
|
PHP
|
mit
| 1,161 |
# school_shop
校园易购,本人于2015年4,5月份开发,后因产品策划的太臃肿,存在一定bug,并在忙其它事,没空修复,
现在将其开源,供大家参考学习
- 注:后台采用SpringMvc开发(Maven),部署在[Openshift](https://www.openshift.com/)服务器,由于是国外免费服务器,所以响应速度比较慢
# Screenshots





# Third-party libraries used
- [SystemBarTint](https://github.com/jgilfelt/SystemBarTint)
- [Gson](https://github.com/google/gson)
- [android-async-http](https://github.com/loopj/android-async-http)
- [Emojiconlibrary](https://github.com/rockerhieu/emojicon)
- [nineoldandroids](https://github.com/JakeWharton/NineOldAndroids)
- [七牛]
- [友盟]
# License
```
Copyright 2015 Owater
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.
```
|
pranavlathigara/school_shop
|
README.md
|
Markdown
|
mit
| 1,503 |
/* Generated by CIL v. 1.7.0 */
/* print_CIL_Input is false */
struct _IO_FILE;
struct timeval;
extern float strtof(char const *str , char const *endptr ) ;
extern void signal(int sig , void *func ) ;
typedef struct _IO_FILE FILE;
extern int atoi(char const *s ) ;
extern double strtod(char const *str , char const *endptr ) ;
extern int fclose(void *stream ) ;
extern void *fopen(char const *filename , char const *mode ) ;
extern void abort() ;
extern void exit(int status ) ;
extern int raise(int sig ) ;
extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ;
extern int strcmp(char const *a , char const *b ) ;
extern int rand() ;
extern unsigned long strtoul(char const *str , char const *endptr , int base ) ;
void RandomFunc(unsigned int input[1] , unsigned int output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
void megaInit(void)
{
{
}
}
void RandomFunc(unsigned int input[1] , unsigned int output[1] )
{
unsigned int state[1] ;
unsigned int local1 ;
char copy11 ;
unsigned short copy12 ;
{
state[0UL] = (input[0UL] + 914778474UL) ^ 3462201355U;
local1 = 0UL;
while (local1 < input[1UL]) {
if (state[0UL] > local1) {
copy11 = *((char *)(& state[local1]) + 0);
*((char *)(& state[local1]) + 0) = *((char *)(& state[local1]) + 1);
*((char *)(& state[local1]) + 1) = copy11;
copy12 = *((unsigned short *)(& state[0UL]) + 1);
*((unsigned short *)(& state[0UL]) + 1) = *((unsigned short *)(& state[0UL]) + 0);
*((unsigned short *)(& state[0UL]) + 0) = copy12;
} else {
state[0UL] |= (state[0UL] & 31U) << 4UL;
state[local1] *= state[local1];
}
local1 ++;
}
output[0UL] = state[0UL] << 5U;
}
}
int main(int argc , char *argv[] )
{
unsigned int input[1] ;
unsigned int output[1] ;
int randomFuns_i5 ;
unsigned int randomFuns_value6 ;
int randomFuns_main_i7 ;
{
megaInit();
if (argc != 2) {
printf("Call this program with %i arguments\n", 1);
exit(-1);
} else {
}
randomFuns_i5 = 0;
while (randomFuns_i5 < 1) {
randomFuns_value6 = (unsigned int )strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == 460535040U) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%u\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
|
tum-i22/obfuscation-benchmarks
|
tigress-generated-programs/empty-Seed4-RandomFuns-Type_int-ControlStructures_9-BB2-ForBound_input-Operators_all.c
|
C
|
mit
| 3,118 |
/* _______ ________
\ \ / _____/ ____ ___
/ | \/ \ ____/ __ \ / \
/ | \ \_\ \ ___/| | \
\____|__ /\______ /\___ >___| /
\/ \/ \/ \/
The MIT License (MIT)
COPYRIGHT (C) 2016 FIXCOM, LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sub-license, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef __NGEN_CALLBACK_HPP
#define __NGEN_CALLBACK_HPP
#include "Ngen.Delegate.hpp"
namespace Ngen {
/** @brief A function-call provider primarily used to bind object instances to member delegates before invocation.
*/
class ngen_api Callback {
public:
/** @brief Constructor. Default. */
Callback() : mThis(0), mFunc(0) {}
/** @brief Constructor. (unknown, Delegate*). */
Callback(unknown _this, Delegate* function) : mThis(_this), mFunc(function) {}
/** @brief Constructor. (Delegate*). */
Callback(Delegate* function) : mThis(0), mFunc(function) {}
/** @brief Constructor. Copy. */
Callback(const Callback& copy) : mThis(copy.mThis), mFunc(copy.mFunc) {}
/** @brief De-constructor. */
~Callback() {
mThis = null;
mFunc = null;
}
/** @brief Determines if the callback is properly configured for an invocation. */
bool IsValid() const {
if(!isnull(mFunc)) {
if(mFunc->IsMember()) {
return !isnull(mThis);
}
return true;
}
return false;
}
/** @brief operator==(const Callback&) */
bool operator==(const Callback& rhs) const {
if(!isnull(mThis) && mThis != rhs.mThis) {
return false;
}
return rhs.mFunc->EqualTo(mFunc);
}
/** @brief operator!=(const Callback&) */
bool operator!=(const Callback& rhs) const {
if(!isnull(mThis) && mThis != rhs.mThis) {
return true;
}
return !rhs.mFunc->EqualTo(mFunc);
}
/** @brief Invokes the callback using the given unknown parameter set. */
unknown Call(unknown* params) {
return mFunc->operator()(mThis, params);
}
void MakeValid(unknown pointer) {
mThis = pointer;
}
Type* ReturnType() const {
return mFunc->ReturnType();
}
Delegate* Function() const {
return mFunc;
}
protected:
unknown mThis;
Delegate* mFunc;
};
}
#endif // __NGEN_CALLBACK_HPP
|
archendian/ngensdk
|
develop/v0.4/Ngen/include/Ngen.Callback.hpp
|
C++
|
mit
| 3,144 |
package logbook.server.proxy;
/**
* 動作に必要なデータのみ取得するためのフィルターです。
*
*/
public class Filter {
/** フィルターするContent-Type */
public static final String CONTENT_TYPE_FILTER = "text/plain";
/** キャプチャーするリクエストのバイトサイズ上限 */
public static final int MAX_POST_FIELD_SIZE = 1024 * 1024;
/** setAttribute用のキー(Response) */
public static final String RESPONSE_BODY = "res-body";
/** setAttribute用のキー(Request) */
public static final String REQUEST_BODY = "req-body";
private static String serverName;
/**
* 鎮守府サーバー名を設定する
* @param name 鎮守府サーバー名
*/
public static void setServerName(String name) {
serverName = name;
}
/**
* 鎮守府サーバー名を取得する
* @param name 鎮守府サーバー名
*/
public static String getServerName() {
return serverName;
}
/**
* 鎮守府サーバー名を検出した場合true
*
* @return 鎮守府サーバー名を検出した場合true
*/
public static boolean isServerDetected() {
return serverName != null;
}
/**
* <p>
* 取得が必要なデータかを調べます<br>
* 鎮守府サーバーが検出された場合はサーバー名から必要かどうかを判別します<br>
* 鎮守府サーバーが検出できていない場合は常にtrue<br>
*
* @param name サーバー名
* @return 取得が必要なデータか
*/
public static boolean isNeed(String name) {
if ((!isServerDetected() || (isServerDetected() && serverName.equals(name)))) {
return true;
}
return false;
}
/**
* <p>
* 取得が必要なデータかを調べます<br>
* 鎮守府サーバーが検出された場合はサーバー名とContent-Typeから必要かどうかを判別します<br>
* 鎮守府サーバーが検出できていない場合はContent-Typeから必要かどうかを判別します<br>
*
* @param name サーバー名
* @param contentType Content-Type
* @return 取得が必要なデータか
*/
public static boolean isNeed(String name, String contentType) {
if ((!isServerDetected() || serverName.equals(name))
&& CONTENT_TYPE_FILTER.equals(contentType)) {
return true;
}
return false;
}
}
|
silfumus/logbook-EN
|
main/logbook/server/proxy/Filter.java
|
Java
|
mit
| 2,555 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: ForwardDocumentEvent.proto
package Diadoc.Api.Proto;
public final class ForwardDocumentEventProtos {
private ForwardDocumentEventProtos() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
}
public interface ForwardDocumentEventOrBuilder extends
// @@protoc_insertion_point(interface_extends:Diadoc.Api.Proto.ForwardDocumentEvent)
com.google.protobuf.MessageOrBuilder {
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
boolean hasTimestamp();
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
Diadoc.Api.Proto.TimestampProtos.Timestamp getTimestamp();
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder getTimestampOrBuilder();
/**
* <code>optional string ToBoxId = 2;</code>
*/
boolean hasToBoxId();
/**
* <code>optional string ToBoxId = 2;</code>
*/
java.lang.String getToBoxId();
/**
* <code>optional string ToBoxId = 2;</code>
*/
com.google.protobuf.ByteString
getToBoxIdBytes();
}
/**
* Protobuf type {@code Diadoc.Api.Proto.ForwardDocumentEvent}
*/
public static final class ForwardDocumentEvent extends
com.google.protobuf.GeneratedMessage implements
// @@protoc_insertion_point(message_implements:Diadoc.Api.Proto.ForwardDocumentEvent)
ForwardDocumentEventOrBuilder {
// Use ForwardDocumentEvent.newBuilder() to construct.
private ForwardDocumentEvent(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private ForwardDocumentEvent(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final ForwardDocumentEvent defaultInstance;
public static ForwardDocumentEvent getDefaultInstance() {
return defaultInstance;
}
public ForwardDocumentEvent getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private ForwardDocumentEvent(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder subBuilder = null;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
subBuilder = timestamp_.toBuilder();
}
timestamp_ = input.readMessage(Diadoc.Api.Proto.TimestampProtos.Timestamp.PARSER, extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(timestamp_);
timestamp_ = subBuilder.buildPartial();
}
bitField0_ |= 0x00000001;
break;
}
case 18: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000002;
toBoxId_ = bs;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.class, Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.Builder.class);
}
public static com.google.protobuf.Parser<ForwardDocumentEvent> PARSER =
new com.google.protobuf.AbstractParser<ForwardDocumentEvent>() {
public ForwardDocumentEvent parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ForwardDocumentEvent(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<ForwardDocumentEvent> getParserForType() {
return PARSER;
}
private int bitField0_;
public static final int TIMESTAMP_FIELD_NUMBER = 1;
private Diadoc.Api.Proto.TimestampProtos.Timestamp timestamp_;
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public boolean hasTimestamp() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Diadoc.Api.Proto.TimestampProtos.Timestamp getTimestamp() {
return timestamp_;
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder getTimestampOrBuilder() {
return timestamp_;
}
public static final int TOBOXID_FIELD_NUMBER = 2;
private java.lang.Object toBoxId_;
/**
* <code>optional string ToBoxId = 2;</code>
*/
public boolean hasToBoxId() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public java.lang.String getToBoxId() {
java.lang.Object ref = toBoxId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
toBoxId_ = s;
}
return s;
}
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public com.google.protobuf.ByteString
getToBoxIdBytes() {
java.lang.Object ref = toBoxId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
toBoxId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private void initFields() {
timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance();
toBoxId_ = "";
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
if (hasTimestamp()) {
if (!getTimestamp().isInitialized()) {
memoizedIsInitialized = 0;
return false;
}
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeMessage(1, timestamp_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(2, getToBoxIdBytes());
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, timestamp_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(2, getToBoxIdBytes());
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code Diadoc.Api.Proto.ForwardDocumentEvent}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:Diadoc.Api.Proto.ForwardDocumentEvent)
Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEventOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.class, Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.Builder.class);
}
// Construct using Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
getTimestampFieldBuilder();
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
if (timestampBuilder_ == null) {
timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance();
} else {
timestampBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
toBoxId_ = "";
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor;
}
public Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent getDefaultInstanceForType() {
return Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.getDefaultInstance();
}
public Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent build() {
Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent buildPartial() {
Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent result = new Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
if (timestampBuilder_ == null) {
result.timestamp_ = timestamp_;
} else {
result.timestamp_ = timestampBuilder_.build();
}
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.toBoxId_ = toBoxId_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent) {
return mergeFrom((Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent other) {
if (other == Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.getDefaultInstance()) return this;
if (other.hasTimestamp()) {
mergeTimestamp(other.getTimestamp());
}
if (other.hasToBoxId()) {
bitField0_ |= 0x00000002;
toBoxId_ = other.toBoxId_;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (hasTimestamp()) {
if (!getTimestamp().isInitialized()) {
return false;
}
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private Diadoc.Api.Proto.TimestampProtos.Timestamp timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance();
private com.google.protobuf.SingleFieldBuilder<
Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder> timestampBuilder_;
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public boolean hasTimestamp() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Diadoc.Api.Proto.TimestampProtos.Timestamp getTimestamp() {
if (timestampBuilder_ == null) {
return timestamp_;
} else {
return timestampBuilder_.getMessage();
}
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Builder setTimestamp(Diadoc.Api.Proto.TimestampProtos.Timestamp value) {
if (timestampBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
timestamp_ = value;
onChanged();
} else {
timestampBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
return this;
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Builder setTimestamp(
Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder builderForValue) {
if (timestampBuilder_ == null) {
timestamp_ = builderForValue.build();
onChanged();
} else {
timestampBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
return this;
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Builder mergeTimestamp(Diadoc.Api.Proto.TimestampProtos.Timestamp value) {
if (timestampBuilder_ == null) {
if (((bitField0_ & 0x00000001) == 0x00000001) &&
timestamp_ != Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance()) {
timestamp_ =
Diadoc.Api.Proto.TimestampProtos.Timestamp.newBuilder(timestamp_).mergeFrom(value).buildPartial();
} else {
timestamp_ = value;
}
onChanged();
} else {
timestampBuilder_.mergeFrom(value);
}
bitField0_ |= 0x00000001;
return this;
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Builder clearTimestamp() {
if (timestampBuilder_ == null) {
timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance();
onChanged();
} else {
timestampBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder getTimestampBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getTimestampFieldBuilder().getBuilder();
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder getTimestampOrBuilder() {
if (timestampBuilder_ != null) {
return timestampBuilder_.getMessageOrBuilder();
} else {
return timestamp_;
}
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder>
getTimestampFieldBuilder() {
if (timestampBuilder_ == null) {
timestampBuilder_ = new com.google.protobuf.SingleFieldBuilder<
Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder>(
getTimestamp(),
getParentForChildren(),
isClean());
timestamp_ = null;
}
return timestampBuilder_;
}
private java.lang.Object toBoxId_ = "";
/**
* <code>optional string ToBoxId = 2;</code>
*/
public boolean hasToBoxId() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public java.lang.String getToBoxId() {
java.lang.Object ref = toBoxId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
toBoxId_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public com.google.protobuf.ByteString
getToBoxIdBytes() {
java.lang.Object ref = toBoxId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
toBoxId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public Builder setToBoxId(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
toBoxId_ = value;
onChanged();
return this;
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public Builder clearToBoxId() {
bitField0_ = (bitField0_ & ~0x00000002);
toBoxId_ = getDefaultInstance().getToBoxId();
onChanged();
return this;
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public Builder setToBoxIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
toBoxId_ = value;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:Diadoc.Api.Proto.ForwardDocumentEvent)
}
static {
defaultInstance = new ForwardDocumentEvent(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:Diadoc.Api.Proto.ForwardDocumentEvent)
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\032ForwardDocumentEvent.proto\022\020Diadoc.Api" +
".Proto\032\017Timestamp.proto\"W\n\024ForwardDocume" +
"ntEvent\022.\n\tTimestamp\030\001 \001(\0132\033.Diadoc.Api." +
"Proto.Timestamp\022\017\n\007ToBoxId\030\002 \001(\tB\034B\032Forw" +
"ardDocumentEventProtos"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
Diadoc.Api.Proto.TimestampProtos.getDescriptor(),
}, assigner);
internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor,
new java.lang.String[] { "Timestamp", "ToBoxId", });
Diadoc.Api.Proto.TimestampProtos.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
|
halex2005/diadocsdk-java
|
src/main/java/Diadoc/Api/Proto/ForwardDocumentEventProtos.java
|
Java
|
mit
| 27,479 |
<!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_55) on Fri Jun 20 06:34:49 EDT 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.solr.handler.dataimport.BinContentStreamDataSource (Solr 4.9.0 API)</title>
<meta name="date" content="2014-06-20">
<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="Uses of Class org.apache.solr.handler.dataimport.BinContentStreamDataSource (Solr 4.9.0 API)";
}
//-->
</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><a href="../../../../../../org/apache/solr/handler/dataimport/BinContentStreamDataSource.html" title="class in org.apache.solr.handler.dataimport">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/solr/handler/dataimport/class-use/BinContentStreamDataSource.html" target="_top">Frames</a></li>
<li><a href="BinContentStreamDataSource.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>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.solr.handler.dataimport.BinContentStreamDataSource" class="title">Uses of Class<br>org.apache.solr.handler.dataimport.BinContentStreamDataSource</h2>
</div>
<div class="classUseContainer">No usage of org.apache.solr.handler.dataimport.BinContentStreamDataSource</div>
<!-- ======= 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><a href="../../../../../../org/apache/solr/handler/dataimport/BinContentStreamDataSource.html" title="class in org.apache.solr.handler.dataimport">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/solr/handler/dataimport/class-use/BinContentStreamDataSource.html" target="_top">Frames</a></li>
<li><a href="BinContentStreamDataSource.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>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2014 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
|
knittledan/Location_Search_Prediction
|
thirdParty/solrSrc/docs/solr-dataimporthandler/org/apache/solr/handler/dataimport/class-use/BinContentStreamDataSource.html
|
HTML
|
mit
| 5,195 |
package saberapplications.pawpads.databinding;
import android.databinding.BaseObservable;
import android.databinding.BindingAdapter;
import android.databinding.BindingConversion;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import saberapplications.pawpads.R;
/**
* Created by Stanislav Volnjanskij on 25.08.16.
*/
public class BindableDouble extends BaseObservable {
private Double value;
private String format="%f";
public Double get() {
return value;
}
public void set(double value) {
if (this.value == null || !this.value.equals(value)) {
this.value = value;
notifyChange();
}
}
public void setSilent(double value) {
if (this.value == null || !this.value.equals(value)) {
this.value = value;
}
}
public BindableDouble(double value) {
super();
this.value = value;
}
public BindableDouble() {
super();
}
@BindingConversion
public static String convertIntegerToString(BindableDouble value) {
if (value != null && value.get()!=null)
return String.format(value.getFormat(), value.get());
else {
return null;
}
}
@BindingAdapter({"binding2way"})
public static void bindEditText(EditText view,
final BindableDouble bindableDouble) {
if (view.getTag(R.id.BIND_ID) == null) {
view.setTag(R.id.BIND_ID, true);
view.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
try {
bindableDouble.setSilent(Double.parseDouble(s.toString()));
} catch (Exception e) {
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
//initial value
if (bindableDouble == null) return;
Double newValue = bindableDouble.get();
if (newValue == null) return;
String strValue= String.format(bindableDouble.getFormat(),newValue);
if (!view.getText().toString().equals(strValue) ) {
view.setText(strValue);
}
}
/**
* Number format to display in text field
* @return
*/
public String getFormat() {
return format;
}
/**
*Set number format to display in text field
* @param format
*/
public void setFormat(String format) {
this.format = format;
}
}
|
castaway2000/Pawpads
|
app/src/main/java/saberapplications/pawpads/databinding/BindableDouble.java
|
Java
|
mit
| 2,887 |
using UnityEngine;
using System.Collections;
public class EnemyDeadInfo {
public int score = 0;
public Transform transform;
public bool headShot = false;
}
|
yantian001/3DSniper
|
Assets/Script/Struct/EnemyDeadInfo.cs
|
C#
|
mit
| 177 |
<?php
/**
* Elgg cron library.
*
* @package Elgg
* @subpackage Core
* @author Curverider Ltd
* @link http://elgg.org/
*/
/** The cron exception. */
class CronException extends Exception {}
/**
* Initialisation
*
*/
function cron_init()
{
// Register a pagehandler for cron
register_page_handler('cron','cron_page_handler');
}
/**
* Cron handler for redirecting pages.
*
* @param unknown_type $page
*/
function cron_page_handler($page)
{
global $CONFIG;
if ($page[0])
{
switch (strtolower($page[0]))
{
case 'minute' :
case 'fiveminute' :
case 'fifteenmin' :
case 'halfhour' :
case 'hourly' :
case 'daily' :
case 'weekly' :
case 'monthly':
case 'yearly' :
case 'reboot' : set_input('period', $page[0]); break;
default : throw new CronException(sprintf(elgg_echo('CronException:unknownperiod'), $page[0]));
}
// Include cron handler
include($CONFIG->path . "engine/handlers/cron_handler.php");
}
else
forward();
}
// Register a startup event
register_elgg_event_handler('init','system','cron_init');
?>
|
namaggarwal/elgg
|
engine/lib/cron.php
|
PHP
|
mit
| 1,140 |
package types
import "gopkg.in/pg.v4/internal/parser"
func AppendJSONB(b, jsonb []byte, quote int) []byte {
if quote == 1 {
b = append(b, '\'')
}
p := parser.New(jsonb)
for p.Valid() {
c := p.Read()
switch c {
case '\'':
if quote == 1 {
b = append(b, '\'', '\'')
} else {
b = append(b, '\'')
}
case '\000':
continue
case '\\':
if p.Got("u0000") {
b = append(b, "\\\\u0000"...)
} else {
b = append(b, '\\')
if p.Valid() {
b = append(b, p.Read())
}
}
default:
b = append(b, c)
}
}
if quote == 1 {
b = append(b, '\'')
}
return b
}
|
yawhide/Lol-personal-counters
|
vendor/gopkg.in/pg.v4/types/append_jsonb.go
|
GO
|
mit
| 612 |
#include <stdio.h>
#include <ruby.h>
#include <ruby/thread.h>
#include <v8.h>
#include <libplatform/libplatform.h>
#include <ruby/encoding.h>
#include <pthread.h>
#include <unistd.h>
#include <mutex>
#include <math.h>
using namespace v8;
class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
public:
virtual void* Allocate(size_t length) {
void* data = AllocateUninitialized(length);
return data == NULL ? data : memset(data, 0, length);
}
virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
virtual void Free(void* data, size_t) { free(data); }
};
typedef struct {
const char* data;
int raw_size;
} SnapshotInfo;
typedef struct {
Isolate* isolate;
ArrayBufferAllocator* allocator;
StartupData* startup_data;
bool interrupted;
pid_t pid;
// how many references to this isolate exist
// we can't rely on Ruby's GC for this, because when destroying
// objects, Ruby will destroy ruby objects first, then call the
// extenstion's deallocators. In this case, that means it would
// call `deallocate_isolate` _before_ `deallocate`, causing a segfault
int refs_count;
} IsolateInfo;
typedef struct {
IsolateInfo* isolate_info;
Persistent<Context>* context;
} ContextInfo;
typedef struct {
bool parsed;
bool executed;
bool terminated;
bool json;
Persistent<Value>* value;
Persistent<Value>* message;
Persistent<Value>* backtrace;
} EvalResult;
typedef struct {
ContextInfo* context_info;
Local<String>* eval;
useconds_t timeout;
EvalResult* result;
} EvalParams;
static VALUE rb_eScriptTerminatedError;
static VALUE rb_eParseError;
static VALUE rb_eScriptRuntimeError;
static VALUE rb_cJavaScriptFunction;
static VALUE rb_eSnapshotError;
static VALUE rb_ePlatformAlreadyInitializedError;
static VALUE rb_mJSON;
static VALUE rb_cFailedV8Conversion;
static VALUE rb_cDateTime = Qnil;
static Platform* current_platform = NULL;
static std::mutex platform_lock;
static VALUE rb_platform_set_flag_as_str(VALUE _klass, VALUE flag_as_str) {
bool platform_already_initialized = false;
platform_lock.lock();
if (current_platform == NULL) {
V8::SetFlagsFromString(RSTRING_PTR(flag_as_str), (int)RSTRING_LEN(flag_as_str));
} else {
platform_already_initialized = true;
}
platform_lock.unlock();
// important to raise outside of the lock
if (platform_already_initialized) {
rb_raise(rb_ePlatformAlreadyInitializedError, "The V8 platform is already initialized");
}
return Qnil;
}
static void init_v8() {
// no need to wait for the lock if already initialized
if (current_platform != NULL) return;
platform_lock.lock();
if (current_platform == NULL) {
V8::InitializeICU();
current_platform = platform::CreateDefaultPlatform();
V8::InitializePlatform(current_platform);
V8::Initialize();
}
platform_lock.unlock();
}
void*
nogvl_context_eval(void* arg) {
EvalParams* eval_params = (EvalParams*)arg;
EvalResult* result = eval_params->result;
Isolate* isolate = eval_params->context_info->isolate_info->isolate;
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
TryCatch trycatch(isolate);
Local<Context> context = eval_params->context_info->context->Get(isolate);
Context::Scope context_scope(context);
// in gvl flag
isolate->SetData(0, (void*)false);
// terminate ASAP
isolate->SetData(1, (void*)false);
MaybeLocal<Script> parsed_script = Script::Compile(context, *eval_params->eval);
result->parsed = !parsed_script.IsEmpty();
result->executed = false;
result->terminated = false;
result->json = false;
result->value = NULL;
if (!result->parsed) {
result->message = new Persistent<Value>();
result->message->Reset(isolate, trycatch.Exception());
} else {
MaybeLocal<Value> maybe_value = parsed_script.ToLocalChecked()->Run(context);
result->executed = !maybe_value.IsEmpty();
if (result->executed) {
// arrays and objects get converted to json
Local<Value> local_value = maybe_value.ToLocalChecked();
if ((local_value->IsObject() || local_value->IsArray()) &&
!local_value->IsDate() && !local_value->IsFunction()) {
Local<Object> JSON = context->Global()->Get(
String::NewFromUtf8(isolate, "JSON"))->ToObject();
Local<Function> stringify = JSON->Get(v8::String::NewFromUtf8(isolate, "stringify"))
.As<Function>();
Local<Object> object = local_value->ToObject();
const unsigned argc = 1;
Local<Value> argv[argc] = { object };
MaybeLocal<Value> json = stringify->Call(JSON, argc, argv);
if (json.IsEmpty()) {
result->executed = false;
} else {
result->json = true;
Persistent<Value>* persistent = new Persistent<Value>();
persistent->Reset(isolate, json.ToLocalChecked());
result->value = persistent;
}
} else {
Persistent<Value>* persistent = new Persistent<Value>();
persistent->Reset(isolate, local_value);
result->value = persistent;
}
}
}
if (!result->executed || !result->parsed) {
if (trycatch.HasCaught()) {
if (!trycatch.Exception()->IsNull()) {
result->message = new Persistent<Value>();
Local<Message> message = trycatch.Message();
char buf[1000];
int len;
len = snprintf(buf, sizeof(buf), "%s at %s:%i:%i", *String::Utf8Value(message->Get()),
*String::Utf8Value(message->GetScriptResourceName()->ToString()),
message->GetLineNumber(),
message->GetStartColumn());
Local<String> v8_message = String::NewFromUtf8(isolate, buf, NewStringType::kNormal, (int)len).ToLocalChecked();
result->message->Reset(isolate, v8_message);
} else if(trycatch.HasTerminated()) {
result->terminated = true;
result->message = new Persistent<Value>();
Local<String> tmp = String::NewFromUtf8(isolate, "JavaScript was terminated (either by timeout or explicitly)");
result->message->Reset(isolate, tmp);
}
if (!trycatch.StackTrace().IsEmpty()) {
result->backtrace = new Persistent<Value>();
result->backtrace->Reset(isolate, trycatch.StackTrace()->ToString());
}
}
}
isolate->SetData(0, (void*)true);
return NULL;
}
static VALUE convert_v8_to_ruby(Isolate* isolate, Handle<Value> &value) {
Isolate::Scope isolate_scope(isolate);
HandleScope scope(isolate);
if (value->IsNull() || value->IsUndefined()){
return Qnil;
}
if (value->IsInt32()) {
return INT2FIX(value->Int32Value());
}
if (value->IsNumber()) {
return rb_float_new(value->NumberValue());
}
if (value->IsTrue()) {
return Qtrue;
}
if (value->IsFalse()) {
return Qfalse;
}
if (value->IsArray()) {
VALUE rb_array = rb_ary_new();
Local<Array> arr = Local<Array>::Cast(value);
for(uint32_t i=0; i < arr->Length(); i++) {
Local<Value> element = arr->Get(i);
VALUE rb_elem = convert_v8_to_ruby(isolate, element);
if (rb_funcall(rb_elem, rb_intern("class"), 0) == rb_cFailedV8Conversion) {
return rb_elem;
}
rb_ary_push(rb_array, rb_elem);
}
return rb_array;
}
if (value->IsFunction()){
return rb_funcall(rb_cJavaScriptFunction, rb_intern("new"), 0);
}
if (value->IsDate()){
double ts = Local<Date>::Cast(value)->ValueOf();
double secs = ts/1000;
long nanos = round((secs - floor(secs)) * 1000000);
return rb_time_new(secs, nanos);
}
if (value->IsObject()) {
VALUE rb_hash = rb_hash_new();
TryCatch trycatch(isolate);
Local<Context> context = Context::New(isolate);
Local<Object> object = value->ToObject();
MaybeLocal<Array> maybe_props = object->GetOwnPropertyNames(context);
if (!maybe_props.IsEmpty()) {
Local<Array> props = maybe_props.ToLocalChecked();
for(uint32_t i=0; i < props->Length(); i++) {
Local<Value> key = props->Get(i);
VALUE rb_key = convert_v8_to_ruby(isolate, key);
Local<Value> value = object->Get(key);
// this may have failed due to Get raising
if (trycatch.HasCaught()) {
// TODO isolate code that translates execption to ruby
// exception so we can properly return it
return rb_funcall(rb_cFailedV8Conversion, rb_intern("new"), 1, rb_str_new2(""));
}
VALUE rb_value = convert_v8_to_ruby(isolate, value);
rb_hash_aset(rb_hash, rb_key, rb_value);
}
}
return rb_hash;
}
Local<String> rstr = value->ToString();
return rb_enc_str_new(*String::Utf8Value(rstr), rstr->Utf8Length(), rb_enc_find("utf-8"));
}
static Handle<Value> convert_ruby_to_v8(Isolate* isolate, VALUE value) {
EscapableHandleScope scope(isolate);
Local<Array> array;
Local<Object> object;
VALUE hash_as_array;
VALUE pair;
int i;
long length;
long fixnum;
VALUE klass;
switch (TYPE(value)) {
case T_FIXNUM:
fixnum = NUM2LONG(value);
if (fixnum > INT_MAX)
{
return scope.Escape(Number::New(isolate, (double)fixnum));
}
return scope.Escape(Integer::New(isolate, (int)fixnum));
case T_FLOAT:
return scope.Escape(Number::New(isolate, NUM2DBL(value)));
case T_STRING:
return scope.Escape(String::NewFromUtf8(isolate, RSTRING_PTR(value), NewStringType::kNormal, (int)RSTRING_LEN(value)).ToLocalChecked());
case T_NIL:
return scope.Escape(Null(isolate));
case T_TRUE:
return scope.Escape(True(isolate));
case T_FALSE:
return scope.Escape(False(isolate));
case T_ARRAY:
length = RARRAY_LEN(value);
array = Array::New(isolate, (int)length);
for(i=0; i<length; i++) {
array->Set(i, convert_ruby_to_v8(isolate, rb_ary_entry(value, i)));
}
return scope.Escape(array);
case T_HASH:
object = Object::New(isolate);
hash_as_array = rb_funcall(value, rb_intern("to_a"), 0);
length = RARRAY_LEN(hash_as_array);
for(i=0; i<length; i++) {
pair = rb_ary_entry(hash_as_array, i);
object->Set(convert_ruby_to_v8(isolate, rb_ary_entry(pair, 0)),
convert_ruby_to_v8(isolate, rb_ary_entry(pair, 1)));
}
return scope.Escape(object);
case T_SYMBOL:
value = rb_funcall(value, rb_intern("to_s"), 0);
return scope.Escape(String::NewFromUtf8(isolate, RSTRING_PTR(value), NewStringType::kNormal, (int)RSTRING_LEN(value)).ToLocalChecked());
case T_DATA:
klass = rb_funcall(value, rb_intern("class"), 0);
if (klass == rb_cTime || klass == rb_cDateTime)
{
if (klass == rb_cDateTime)
{
value = rb_funcall(value, rb_intern("to_time"), 0);
}
value = rb_funcall(value, rb_intern("to_f"), 0);
return scope.Escape(Date::New(isolate, NUM2DBL(value) * 1000));
}
case T_OBJECT:
case T_CLASS:
case T_ICLASS:
case T_MODULE:
case T_REGEXP:
case T_MATCH:
case T_STRUCT:
case T_BIGNUM:
case T_FILE:
case T_UNDEF:
case T_NODE:
default:
return scope.Escape(String::NewFromUtf8(isolate, "Undefined Conversion"));
}
}
static void unblock_eval(void *ptr) {
EvalParams* eval = (EvalParams*)ptr;
eval->context_info->isolate_info->interrupted = true;
}
static VALUE rb_snapshot_size(VALUE self, VALUE str) {
SnapshotInfo* snapshot_info;
Data_Get_Struct(self, SnapshotInfo, snapshot_info);
return INT2NUM(snapshot_info->raw_size);
}
static VALUE rb_snapshot_load(VALUE self, VALUE str) {
SnapshotInfo* snapshot_info;
Data_Get_Struct(self, SnapshotInfo, snapshot_info);
init_v8();
StartupData startup_data = V8::CreateSnapshotDataBlob(RSTRING_PTR(str));
if (startup_data.data == NULL && startup_data.raw_size == 0) {
rb_raise(rb_eSnapshotError, "Could not create snapshot, most likely the source is incorrect");
}
snapshot_info->data = startup_data.data;
snapshot_info->raw_size = startup_data.raw_size;
return Qnil;
}
static VALUE rb_snapshot_warmup(VALUE self, VALUE str) {
SnapshotInfo* snapshot_info;
Data_Get_Struct(self, SnapshotInfo, snapshot_info);
init_v8();
StartupData cold_startup_data = {snapshot_info->data, snapshot_info->raw_size};
StartupData warm_startup_data = V8::WarmUpSnapshotDataBlob(cold_startup_data, RSTRING_PTR(str));
if (warm_startup_data.data == NULL && warm_startup_data.raw_size == 0) {
rb_raise(rb_eSnapshotError, "Could not warm up snapshot, most likely the source is incorrect");
} else {
delete[] snapshot_info->data;
snapshot_info->data = warm_startup_data.data;
snapshot_info->raw_size = warm_startup_data.raw_size;
}
return self;
}
static VALUE rb_isolate_init_with_snapshot(VALUE self, VALUE snapshot) {
IsolateInfo* isolate_info;
Data_Get_Struct(self, IsolateInfo, isolate_info);
init_v8();
isolate_info->allocator = new ArrayBufferAllocator();
isolate_info->interrupted = false;
isolate_info->refs_count = 1;
Isolate::CreateParams create_params;
create_params.array_buffer_allocator = isolate_info->allocator;
StartupData* startup_data = NULL;
if (!NIL_P(snapshot)) {
SnapshotInfo* snapshot_info;
Data_Get_Struct(snapshot, SnapshotInfo, snapshot_info);
int raw_size = snapshot_info->raw_size;
char* data = new char[raw_size];
memcpy(data, snapshot_info->data, sizeof(char) * raw_size);
startup_data = new StartupData;
startup_data->data = data;
startup_data->raw_size = raw_size;
create_params.snapshot_blob = startup_data;
}
isolate_info->startup_data = startup_data;
isolate_info->isolate = Isolate::New(create_params);
return Qnil;
}
static VALUE rb_isolate_idle_notification(VALUE self, VALUE idle_time_in_ms) {
IsolateInfo* isolate_info;
Data_Get_Struct(self, IsolateInfo, isolate_info);
return isolate_info->isolate->IdleNotification(NUM2INT(idle_time_in_ms)) ? Qtrue : Qfalse;
}
static VALUE rb_context_init_with_isolate(VALUE self, VALUE isolate) {
ContextInfo* context_info;
Data_Get_Struct(self, ContextInfo, context_info);
init_v8();
IsolateInfo* isolate_info;
Data_Get_Struct(isolate, IsolateInfo, isolate_info);
context_info->isolate_info = isolate_info;
isolate_info->refs_count++;
{
Locker lock(isolate_info->isolate);
Isolate::Scope isolate_scope(isolate_info->isolate);
HandleScope handle_scope(isolate_info->isolate);
Local<Context> context = Context::New(isolate_info->isolate);
context_info->context = new Persistent<Context>();
context_info->context->Reset(isolate_info->isolate, context);
}
if (Qnil == rb_cDateTime && rb_funcall(rb_cObject, rb_intern("const_defined?"), 1, rb_str_new2("DateTime")) == Qtrue)
{
rb_cDateTime = rb_const_get(rb_cObject, rb_intern("DateTime"));
}
return Qnil;
}
static VALUE rb_context_eval_unsafe(VALUE self, VALUE str) {
EvalParams eval_params;
EvalResult eval_result;
ContextInfo* context_info;
VALUE result;
VALUE message = Qnil;
VALUE backtrace = Qnil;
Data_Get_Struct(self, ContextInfo, context_info);
Isolate* isolate = context_info->isolate_info->isolate;
{
Locker lock(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Local<String> eval = String::NewFromUtf8(isolate, RSTRING_PTR(str),
NewStringType::kNormal, (int)RSTRING_LEN(str)).ToLocalChecked();
eval_params.context_info = context_info;
eval_params.eval = &eval;
eval_params.result = &eval_result;
eval_params.timeout = 0;
VALUE timeout = rb_iv_get(self, "@timeout");
if (timeout != Qnil) {
eval_params.timeout = (useconds_t)NUM2LONG(timeout);
}
eval_result.message = NULL;
eval_result.backtrace = NULL;
rb_thread_call_without_gvl(nogvl_context_eval, &eval_params, unblock_eval, &eval_params);
if (eval_result.message != NULL) {
Local<Value> tmp = Local<Value>::New(isolate, *eval_result.message);
message = convert_v8_to_ruby(isolate, tmp);
eval_result.message->Reset();
delete eval_result.message;
}
if (eval_result.backtrace != NULL) {
Local<Value> tmp = Local<Value>::New(isolate, *eval_result.backtrace);
backtrace = convert_v8_to_ruby(isolate, tmp);
eval_result.backtrace->Reset();
delete eval_result.backtrace;
}
}
// NOTE: this is very important, we can not do an rb_raise from within
// a v8 scope, if we do the scope is never cleaned up properly and we leak
if (!eval_result.parsed) {
if(TYPE(message) == T_STRING) {
rb_raise(rb_eParseError, "%s", RSTRING_PTR(message));
} else {
rb_raise(rb_eParseError, "Unknown JavaScript Error during parse");
}
}
if (!eval_result.executed) {
VALUE ruby_exception = rb_iv_get(self, "@current_exception");
if (ruby_exception == Qnil) {
ruby_exception = eval_result.terminated ? rb_eScriptTerminatedError : rb_eScriptRuntimeError;
// exception report about what happened
if(TYPE(backtrace) == T_STRING) {
rb_raise(ruby_exception, "%s", RSTRING_PTR(backtrace));
} else if(TYPE(message) == T_STRING) {
rb_raise(ruby_exception, "%s", RSTRING_PTR(message));
} else {
rb_raise(ruby_exception, "Unknown JavaScript Error during execution");
}
} else {
VALUE rb_str = rb_funcall(ruby_exception, rb_intern("to_s"), 0);
rb_raise(CLASS_OF(ruby_exception), "%s", RSTRING_PTR(rb_str));
}
}
// New scope for return value
{
Locker lock(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Local<Value> tmp = Local<Value>::New(isolate, *eval_result.value);
if (eval_result.json) {
Local<String> rstr = tmp->ToString();
VALUE json_string = rb_enc_str_new(*String::Utf8Value(rstr), rstr->Utf8Length(), rb_enc_find("utf-8"));
result = rb_funcall(rb_mJSON, rb_intern("parse"), 1, json_string);
} else {
result = convert_v8_to_ruby(isolate, tmp);
}
eval_result.value->Reset();
delete eval_result.value;
}
if (rb_funcall(result, rb_intern("class"), 0) == rb_cFailedV8Conversion) {
// TODO try to recover stack trace from the conversion error
rb_raise(rb_eScriptRuntimeError, "Error converting JS object to Ruby object");
}
return result;
}
typedef struct {
VALUE callback;
int length;
VALUE* args;
bool failed;
} protected_callback_data;
static
VALUE protected_callback(VALUE rdata) {
protected_callback_data* data = (protected_callback_data*)rdata;
VALUE result;
if (data->length > 0) {
result = rb_funcall2(data->callback, rb_intern("call"), data->length, data->args);
} else {
result = rb_funcall(data->callback, rb_intern("call"), 0);
}
return result;
}
static
VALUE rescue_callback(VALUE rdata, VALUE exception) {
protected_callback_data* data = (protected_callback_data*)rdata;
data->failed = true;
return exception;
}
void*
gvl_ruby_callback(void* data) {
FunctionCallbackInfo<Value>* args = (FunctionCallbackInfo<Value>*)data;
VALUE* ruby_args = NULL;
int length = args->Length();
VALUE callback;
VALUE result;
VALUE self;
{
HandleScope scope(args->GetIsolate());
Handle<External> external = Handle<External>::Cast(args->Data());
VALUE* self_pointer = (VALUE*)(external->Value());
self = *self_pointer;
callback = rb_iv_get(self, "@callback");
if (length > 0) {
ruby_args = ALLOC_N(VALUE, length);
}
for (int i = 0; i < length; i++) {
Local<Value> value = ((*args)[i]).As<Value>();
ruby_args[i] = convert_v8_to_ruby(args->GetIsolate(), value);
}
}
// may raise exception stay clear of handle scope
protected_callback_data callback_data;
callback_data.length = length;
callback_data.callback = callback;
callback_data.args = ruby_args;
callback_data.failed = false;
if ((bool)args->GetIsolate()->GetData(1) == true) {
args->GetIsolate()->ThrowException(String::NewFromUtf8(args->GetIsolate(), "Terminated execution during tansition from Ruby to JS"));
V8::TerminateExecution(args->GetIsolate());
return NULL;
}
result = rb_rescue2((VALUE(*)(...))&protected_callback, (VALUE)(&callback_data),
(VALUE(*)(...))&rescue_callback, (VALUE)(&callback_data), rb_eException, (VALUE)0);
if(callback_data.failed) {
VALUE parent = rb_iv_get(self, "@parent");
rb_iv_set(parent, "@current_exception", result);
args->GetIsolate()->ThrowException(String::NewFromUtf8(args->GetIsolate(), "Ruby exception"));
}
else {
HandleScope scope(args->GetIsolate());
Handle<Value> v8_result = convert_ruby_to_v8(args->GetIsolate(), result);
args->GetReturnValue().Set(v8_result);
}
if (length > 0) {
xfree(ruby_args);
}
if ((bool)args->GetIsolate()->GetData(1) == true) {
Isolate* isolate = args->GetIsolate();
V8::TerminateExecution(isolate);
}
return NULL;
}
static void ruby_callback(const FunctionCallbackInfo<Value>& args) {
bool has_gvl = (bool)args.GetIsolate()->GetData(0);
if(has_gvl) {
gvl_ruby_callback((void*)&args);
} else {
rb_thread_call_with_gvl(gvl_ruby_callback, (void*)(&args));
}
}
static VALUE rb_external_function_notify_v8(VALUE self) {
ContextInfo* context_info;
VALUE parent = rb_iv_get(self, "@parent");
VALUE name = rb_iv_get(self, "@name");
VALUE parent_object = rb_iv_get(self, "@parent_object");
VALUE parent_object_eval = rb_iv_get(self, "@parent_object_eval");
bool parse_error = false;
bool attach_error = false;
Data_Get_Struct(parent, ContextInfo, context_info);
Isolate* isolate = context_info->isolate_info->isolate;
{
Locker lock(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Local<Context> context = context_info->context->Get(isolate);
Context::Scope context_scope(context);
Local<String> v8_str = String::NewFromUtf8(isolate, RSTRING_PTR(name),
NewStringType::kNormal, (int)RSTRING_LEN(name)).ToLocalChecked();
// copy self so we can access from v8 external
VALUE* self_copy;
Data_Get_Struct(self, VALUE, self_copy);
*self_copy = self;
Local<Value> external = External::New(isolate, self_copy);
if (parent_object == Qnil) {
context->Global()->Set(v8_str, FunctionTemplate::New(isolate, ruby_callback, external)->GetFunction());
} else {
Local<String> eval = String::NewFromUtf8(isolate, RSTRING_PTR(parent_object_eval),
NewStringType::kNormal, (int)RSTRING_LEN(parent_object_eval)).ToLocalChecked();
MaybeLocal<Script> parsed_script = Script::Compile(context, eval);
if (parsed_script.IsEmpty()) {
parse_error = true;
} else {
MaybeLocal<Value> maybe_value = parsed_script.ToLocalChecked()->Run(context);
attach_error = true;
if (!maybe_value.IsEmpty()) {
Local<Value> value = maybe_value.ToLocalChecked();
if (value->IsObject()){
value.As<Object>()->Set(v8_str, FunctionTemplate::New(isolate, ruby_callback, external)->GetFunction());
attach_error = false;
}
}
}
}
}
// always raise out of V8 context
if (parse_error) {
rb_raise(rb_eParseError, "Invalid object %s", RSTRING_PTR(parent_object));
}
if (attach_error) {
rb_raise(rb_eParseError, "Was expecting %s to be an object", RSTRING_PTR(parent_object));
}
return Qnil;
}
void maybe_free_isolate_info(IsolateInfo* isolate_info) {
// an isolate can only be freed if no Isolate or Context (ruby) object
// still need it
if (isolate_info == NULL || isolate_info->refs_count > 0) {
return;
}
if (isolate_info->isolate) {
Locker lock(isolate_info->isolate);
}
if (isolate_info->isolate) {
if (isolate_info->interrupted) {
fprintf(stderr, "WARNING: V8 isolate was interrupted by Ruby, it can not be disposed and memory will not be reclaimed till the Ruby process exits.\n");
} else {
if (isolate_info->pid != getpid()) {
fprintf(stderr, "WARNING: V8 isolate was forked, it can not be disposed and memory will not be reclaimed till the Ruby process exits.\n");
} else {
isolate_info->isolate->Dispose();
}
}
isolate_info->isolate = NULL;
}
if (isolate_info->startup_data) {
delete[] isolate_info->startup_data->data;
delete isolate_info->startup_data;
}
delete isolate_info->allocator;
xfree(isolate_info);
}
void deallocate_isolate(void* data) {
IsolateInfo* isolate_info = (IsolateInfo*) data;
isolate_info->refs_count--;
maybe_free_isolate_info(isolate_info);
}
void deallocate(void* data) {
ContextInfo* context_info = (ContextInfo*)data;
IsolateInfo* isolate_info = context_info->isolate_info;
if (context_info->context && isolate_info && isolate_info->isolate) {
Locker lock(isolate_info->isolate);
v8::Isolate::Scope isolate_scope(isolate_info->isolate);
context_info->context->Reset();
delete context_info->context;
}
if (isolate_info) {
isolate_info->refs_count--;
maybe_free_isolate_info(isolate_info);
}
}
void deallocate_external_function(void * data) {
xfree(data);
}
void deallocate_snapshot(void * data) {
SnapshotInfo* snapshot_info = (SnapshotInfo*)data;
delete[] snapshot_info->data;
xfree(snapshot_info);
}
VALUE allocate_external_function(VALUE klass) {
VALUE* self = ALLOC(VALUE);
return Data_Wrap_Struct(klass, NULL, deallocate_external_function, (void*)self);
}
VALUE allocate(VALUE klass) {
ContextInfo* context_info = ALLOC(ContextInfo);
context_info->isolate_info = NULL;
context_info->context = NULL;
return Data_Wrap_Struct(klass, NULL, deallocate, (void*)context_info);
}
VALUE allocate_snapshot(VALUE klass) {
SnapshotInfo* snapshot_info = ALLOC(SnapshotInfo);
snapshot_info->data = NULL;
snapshot_info->raw_size = 0;
return Data_Wrap_Struct(klass, NULL, deallocate_snapshot, (void*)snapshot_info);
}
VALUE allocate_isolate(VALUE klass) {
IsolateInfo* isolate_info = ALLOC(IsolateInfo);
isolate_info->isolate = NULL;
isolate_info->allocator = NULL;
isolate_info->startup_data = NULL;
isolate_info->interrupted = false;
isolate_info->refs_count = 0;
isolate_info->pid = getpid();
return Data_Wrap_Struct(klass, NULL, deallocate_isolate, (void*)isolate_info);
}
static VALUE
rb_context_stop(VALUE self) {
ContextInfo* context_info;
Data_Get_Struct(self, ContextInfo, context_info);
Isolate* isolate = context_info->isolate_info->isolate;
// flag for termination
isolate->SetData(1, (void*)true);
V8::TerminateExecution(isolate);
rb_funcall(self, rb_intern("stop_attached"), 0);
return Qnil;
}
extern "C" {
void Init_mini_racer_extension ( void )
{
VALUE rb_mMiniRacer = rb_define_module("MiniRacer");
VALUE rb_cContext = rb_define_class_under(rb_mMiniRacer, "Context", rb_cObject);
VALUE rb_cSnapshot = rb_define_class_under(rb_mMiniRacer, "Snapshot", rb_cObject);
VALUE rb_cIsolate = rb_define_class_under(rb_mMiniRacer, "Isolate", rb_cObject);
VALUE rb_cPlatform = rb_define_class_under(rb_mMiniRacer, "Platform", rb_cObject);
VALUE rb_eEvalError = rb_define_class_under(rb_mMiniRacer, "EvalError", rb_eStandardError);
rb_eScriptTerminatedError = rb_define_class_under(rb_mMiniRacer, "ScriptTerminatedError", rb_eEvalError);
rb_eParseError = rb_define_class_under(rb_mMiniRacer, "ParseError", rb_eEvalError);
rb_eScriptRuntimeError = rb_define_class_under(rb_mMiniRacer, "RuntimeError", rb_eEvalError);
rb_cJavaScriptFunction = rb_define_class_under(rb_mMiniRacer, "JavaScriptFunction", rb_cObject);
rb_eSnapshotError = rb_define_class_under(rb_mMiniRacer, "SnapshotError", rb_eStandardError);
rb_ePlatformAlreadyInitializedError = rb_define_class_under(rb_mMiniRacer, "PlatformAlreadyInitialized", rb_eStandardError);
rb_cFailedV8Conversion = rb_define_class_under(rb_mMiniRacer, "FailedV8Conversion", rb_cObject);
rb_mJSON = rb_define_module("JSON");
VALUE rb_cExternalFunction = rb_define_class_under(rb_cContext, "ExternalFunction", rb_cObject);
rb_define_method(rb_cContext, "stop", (VALUE(*)(...))&rb_context_stop, 0);
rb_define_alloc_func(rb_cContext, allocate);
rb_define_alloc_func(rb_cSnapshot, allocate_snapshot);
rb_define_alloc_func(rb_cIsolate, allocate_isolate);
rb_define_private_method(rb_cContext, "eval_unsafe",(VALUE(*)(...))&rb_context_eval_unsafe, 1);
rb_define_private_method(rb_cContext, "init_with_isolate",(VALUE(*)(...))&rb_context_init_with_isolate, 1);
rb_define_private_method(rb_cExternalFunction, "notify_v8", (VALUE(*)(...))&rb_external_function_notify_v8, 0);
rb_define_alloc_func(rb_cExternalFunction, allocate_external_function);
rb_define_method(rb_cSnapshot, "size", (VALUE(*)(...))&rb_snapshot_size, 0);
rb_define_method(rb_cSnapshot, "warmup!", (VALUE(*)(...))&rb_snapshot_warmup, 1);
rb_define_private_method(rb_cSnapshot, "load", (VALUE(*)(...))&rb_snapshot_load, 1);
rb_define_method(rb_cIsolate, "idle_notification", (VALUE(*)(...))&rb_isolate_idle_notification, 1);
rb_define_private_method(rb_cIsolate, "init_with_snapshot",(VALUE(*)(...))&rb_isolate_init_with_snapshot, 1);
rb_define_singleton_method(rb_cPlatform, "set_flag_as_str!", (VALUE(*)(...))&rb_platform_set_flag_as_str, 1);
}
}
|
lrosskamp/makealist-public
|
vendor/cache/ruby/2.3.0/gems/mini_racer-0.1.9/ext/mini_racer_extension/mini_racer_extension.cc
|
C++
|
mit
| 29,455 |
// This source code is dual-licensed under the Apache License, version
// 2.0, and the Mozilla Public License, version 1.1.
//
// The APL v2.0:
//
//---------------------------------------------------------------------------
// Copyright (C) 2007-2014 GoPivotal, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//---------------------------------------------------------------------------
//
// The MPL v1.1:
//
//---------------------------------------------------------------------------
// The contents of this file are subject to the Mozilla Public License
// Version 1.1 (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.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
// the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is RabbitMQ.
//
// The Initial Developer of the Original Code is GoPivotal, Inc.
// Copyright (c) 2007-2014 GoPivotal, Inc. All rights reserved.
//---------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace RabbitMQ.Client.Impl
{
public abstract class StreamProperties : ContentHeaderBase, IStreamProperties
{
public abstract string ContentType { get; set; }
public abstract string ContentEncoding { get; set; }
public abstract IDictionary<string, object> Headers { get; set; }
public abstract byte Priority { get; set; }
public abstract AmqpTimestamp Timestamp { get; set; }
public abstract void ClearContentType();
public abstract void ClearContentEncoding();
public abstract void ClearHeaders();
public abstract void ClearPriority();
public abstract void ClearTimestamp();
public abstract bool IsContentTypePresent();
public abstract bool IsContentEncodingPresent();
public abstract bool IsHeadersPresent();
public abstract bool IsPriorityPresent();
public abstract bool IsTimestampPresent();
public override object Clone()
{
StreamProperties clone = MemberwiseClone() as StreamProperties;
if (IsHeadersPresent())
{
clone.Headers = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> entry in Headers)
clone.Headers[entry.Key] = entry.Value;
}
return clone;
}
}
}
|
CymaticLabs/Unity3D.Amqp
|
lib/rabbitmq-dotnet-client-rabbitmq_v3_4_4/projects/client/RabbitMQ.Client/src/client/impl/StreamProperties.cs
|
C#
|
mit
| 3,179 |
# Slither.io bot
Just for fun and AI. Written in Javascript, this is a project which the aim is to make a computer play against humans inside a human-driven game, which is in this case Slither.io. The goal is simple - try and make the snake live and get as long as possible.
[](https://gitter.im/ErmiyaEskandary/Slither.io-bot?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
# Table of Contents
- [Installation instructions](https://github.com/ErmiyaEskandary/Slither.io-bot#installation-instructions)
- [Visual tutorial](https://github.com/ErmiyaEskandary/Slither.io-bot#visual-tutorial)
- [Text tutorial](https://github.com/ErmiyaEskandary/Slither.io-bot#text-tutorial)
- [Hotkeys](https://github.com/ErmiyaEskandary/Slither.io-bot#hotkeys)
- [Contributing](https://github.com/ErmiyaEskandary/Slither.io-bot#contributing)
- [Documentation](https://github.com/ErmiyaEskandary/Slither.io-bot#documentation)
- [Authors](https://github.com/ErmiyaEskandary/Slither.io-bot#authors)
- [License](https://github.com/ErmiyaEskandary/Slither.io-bot#license)
# Installation instructions
**NOTE: these instructions are for installing the bot at a production-ready, fully working and a fully tested state, which is recommended. For the latest bleeding edge code, which may not be fully tested, refer to the bot.user.js file in the current default develop branch as the instructions below refer the bot file in the master branch.**
## Interactive tutorial
http://slither.jlynx.net/
## Visual tutorial
https://www.youtube.com/watch?v=d7mkAgQNuCA - Created by http://slither.jlynx.net/
https://youtu.be/mlEKp-ZAi7w - Created by http://slithere.com/
https://youtu.be/QF9JBMi-fLo?t=38s - Created by SeppeTutorials
https://youtu.be/IpsAazbVIcw - Created by TheFlyingPlatypus
## Text tutorial
If you are on chrome, download the [TamperMonkey](https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkkebhmkfjojejmpbldmpobfkfo?hl=en) extension.
On other browsers, use the [GreaseMonkey](https://addons.mozilla.org/en-GB/firefox/addon/greasemonkey/) extension.
Once installed, click on [this](https://github.com/ErmiyaEskandary/slither.io-bot/raw/master/bot.user.js), and choose **Install**.
Go to [slither.io](http://slither.io/), and enjoy !
# Hotkeys
Key | Result
---|---
T / Right Click | Bot enabled/disabled
**O** | **Mobile rendering - Try this if you experience lag**
A/S | Radius multiplier
D | Quick radius change - "approach" and "avoid" mode
I | Auto respawn
G | Leaderboard overlay
Y | Visual debugging
U | Log debugging
H | Overlays
B | Background Change
Mouse wheel | Zoom in/out
Z | Reset zoom
ESC | Quick respawn
Q | Quit to menu
# Contributing
Please refer to the [guidelines for contributing](https://github.com/ErmiyaEskandary/Slither.io-bot/blob/master/.github/CONTRIBUTING.md) for all the information you need.
[Check the wiki for additional information](https://github.com/ErmiyaEskandary/Slither.io-bot/wiki)
NOTE : For existing collaborators, please refer to the [DEVELOPER.md file.](https://github.com/ErmiyaEskandary/Slither.io-bot/blob/master/DEVELOPER.md)
## Documentation
[](http://slitherio-bot.readthedocs.io/en/latest/?badge=latest)
The [online documentation](http://slitherio-bot.readthedocs.io/en/master/) is maintained in the `/docs` directory.
# Authors
**Ermiya Eskandary & Théophile Cailliau (ErmiyaEskandary & FliiFe)**
Started as a collaborative and fun project between me and FliiFe on 2016/04/20, with this :
> Slither.io bot could be cool
# License
**Licensed under the Mozilla Public License, v. 2.0**
Read LICENSE.md for more info.
|
ErmiyaEskandary/slither.io-bot
|
README.md
|
Markdown
|
mit
| 3,770 |
'use strict'
const dotenv = require('dotenv')
const ENV = process.env.NODE_ENV || 'development'
if (ENV === 'development') dotenv.load()
const config = {
ENV: process.env.NODE_ENV,
PORT: process.env.PORT,
PROXY_URI: process.env.PROXY_URI,
WEBHOOK_URL: process.env.WEBHOOK_URL,
BATTLESHIP_COMMAND_TOKEN: process.env.BATTLESHIP_COMMAND_TOKEN,
SLACK_TOKEN: process.env.SLACK_TOKEN,
ICON_EMOJI: ':passenger_ship:',
USERNAME: "Battleship"
}
module.exports = (key) => {
if (!key) return config
return config[key]
}
|
jaksah/slack-battleship
|
src/config.js
|
JavaScript
|
mit
| 535 |
SET NOCOUNT ON;
SELECT
T1.Client_Version0 as VersionNumber,
CASE
WHEN T1.Client_Version0 = '5.00.7711.0000' THEN 'ConfigMgr 2012 RTM'
WHEN T1.Client_Version0 = '5.00.7711.0200' THEN 'ConfigMgr 2012 RTM CU1'
WHEN T1.Client_Version0 = '5.00.7711.0301' THEN 'ConfigMgr 2012 RTM CU2'
WHEN T1.Client_Version0 = '5.00.7804.1000' THEN 'ConfigMgr 2012 SP1'
WHEN T1.Client_Version0 = '5.00.7804.1202' THEN 'ConfigMgr 2012 SP1 CU1'
WHEN T1.Client_Version0 = '5.00.7804.1300' THEN 'ConfigMgr 2012 SP1 CU2'
WHEN T1.Client_Version0 = '5.00.7804.1400' THEN 'ConfigMgr 2012 SP1 CU3'
WHEN T1.Client_Version0 = '5.00.7804.1500' THEN 'ConfigMgr 2012 SP1 CU4'
WHEN T1.Client_Version0 = '5.00.7804.1600' THEN 'ConfigMgr 2012 SP1 CU5'
WHEN T1.Client_Version0 = '5.00.7958.1000' THEN 'ConfigMgr 2012 R2'
WHEN T1.Client_Version0 = '5.00.7958.1101' THEN 'ConfigMgr 2012 R2 with KB290500'
WHEN T1.Client_Version0 = '5.00.7958.1203' THEN 'ConfigMgr 2012 R2 CU1'
WHEN T1.Client_Version0 = '5.00.7958.1303' THEN 'ConfigMgr 2012 R2 CU2'
WHEN T1.Client_Version0 = '5.00.7958.1401' THEN 'ConfigMgr 2012 R2 CU3'
WHEN T1.Client_Version0 = '5.00.7958.1501' THEN 'ConfigMgr 2012 R2 CU4'
WHEN T1.Client_Version0 = '5.00.7958.1601' THEN 'ConfigMgr 2012 R2 CU5'
WHEN T1.Client_Version0 = '5.00.8239.1000' THEN 'ConfigMgr 2012 R2 SP1'
WHEN T1.Client_Version0 = '5.00.8239.1203' THEN 'ConfigMgr 2012 R2 SP1 CU1'
WHEN T1.Client_Version0 = '5.00.8239.1301' THEN 'ConfigMgr 2012 R2 SP1 CU2'
WHEN T1.Client_Version0 = '5.00.8239.1403' THEN 'ConfigMgr 2012 R2 SP1 CU3'
WHEN T1.Client_Version0 = '5.00.8325.1000' THEN 'ConfigMgr Update 1511'
WHEN T1.Client_Version0 = '5.00.8355.1000' THEN 'ConfigMgr Update 1602'
WHEN T1.Client_Version0 = '5.00.8355.1306' THEN 'ConfigMgr Update 1602 UR1'
WHEN T1.Client_Version0 = '5.00.8412.1007' THEN 'ConfigMgr Update 1606'
WHEN T1.Client_Version0 = '5.00.8412.1307' THEN 'ConfigMgr Update 1606 UR1'
ELSE T1.Client_Version0 END as 'Description',
COUNT(T1.ResourceID) as 'Total',
T1.ResourceID MachineId
FROM v_R_System_Valid T1
GROUP BY T1.Client_Version0, T1.ResourceID
ORDER BY Total DESC
|
mayankon24/d-final
|
Source/Apps/Microsoft/Released/Microsoft-SCCM2/Service/Resources/Scripts/ClientHealth_count_clients_installed_version.sql
|
SQL
|
mit
| 2,085 |
/* MACHINE GENERATED FILE, DO NOT EDIT */
#include <jni.h>
#include "extgl.h"
typedef GL_APICALL void (GL_APIENTRY *glTexStorage1DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
typedef GL_APICALL void (GL_APIENTRY *glTexStorage2DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
typedef GL_APICALL void (GL_APIENTRY *glTexStorage3DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
typedef GL_APICALL void (GL_APIENTRY *glTextureStorage1DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
typedef GL_APICALL void (GL_APIENTRY *glTextureStorage2DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
typedef GL_APICALL void (GL_APIENTRY *glTextureStorage3DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
static glTexStorage1DEXTPROC glTexStorage1DEXT;
static glTexStorage2DEXTPROC glTexStorage2DEXT;
static glTexStorage3DEXTPROC glTexStorage3DEXT;
static glTextureStorage1DEXTPROC glTextureStorage1DEXT;
static glTextureStorage2DEXTPROC glTextureStorage2DEXT;
static glTextureStorage3DEXTPROC glTextureStorage3DEXT;
static void JNICALL Java_org_lwjgl_opengles_EXTTextureStorage_nglTexStorage1DEXT(JNIEnv *env, jclass clazz, jint target, jint levels, jint internalformat, jint width) {
glTexStorage1DEXT(target, levels, internalformat, width);
}
static void JNICALL Java_org_lwjgl_opengles_EXTTextureStorage_nglTexStorage2DEXT(JNIEnv *env, jclass clazz, jint target, jint levels, jint internalformat, jint width, jint height) {
glTexStorage2DEXT(target, levels, internalformat, width, height);
}
static void JNICALL Java_org_lwjgl_opengles_EXTTextureStorage_nglTexStorage3DEXT(JNIEnv *env, jclass clazz, jint target, jint levels, jint internalformat, jint width, jint height, jint depth) {
glTexStorage3DEXT(target, levels, internalformat, width, height, depth);
}
static void JNICALL Java_org_lwjgl_opengles_EXTTextureStorage_nglTextureStorage1DEXT(JNIEnv *env, jclass clazz, jint texture, jint target, jint levels, jint internalformat, jint width) {
glTextureStorage1DEXT(texture, target, levels, internalformat, width);
}
static void JNICALL Java_org_lwjgl_opengles_EXTTextureStorage_nglTextureStorage2DEXT(JNIEnv *env, jclass clazz, jint texture, jint target, jint levels, jint internalformat, jint width, jint height) {
glTextureStorage2DEXT(texture, target, levels, internalformat, width, height);
}
static void JNICALL Java_org_lwjgl_opengles_EXTTextureStorage_nglTextureStorage3DEXT(JNIEnv *env, jclass clazz, jint texture, jint target, jint levels, jint internalformat, jint width, jint height, jint depth) {
glTextureStorage3DEXT(texture, target, levels, internalformat, width, height, depth);
}
JNIEXPORT void JNICALL Java_org_lwjgl_opengles_EXTTextureStorage_initNativeStubs(JNIEnv *env, jclass clazz) {
JavaMethodAndExtFunction functions[] = {
{"nglTexStorage1DEXT", "(IIII)V", (void *)&Java_org_lwjgl_opengles_EXTTextureStorage_nglTexStorage1DEXT, "glTexStorage1DEXT", (void *)&glTexStorage1DEXT, false},
{"nglTexStorage2DEXT", "(IIIII)V", (void *)&Java_org_lwjgl_opengles_EXTTextureStorage_nglTexStorage2DEXT, "glTexStorage2DEXT", (void *)&glTexStorage2DEXT, false},
{"nglTexStorage3DEXT", "(IIIIII)V", (void *)&Java_org_lwjgl_opengles_EXTTextureStorage_nglTexStorage3DEXT, "glTexStorage3DEXT", (void *)&glTexStorage3DEXT, false},
{"nglTextureStorage1DEXT", "(IIIII)V", (void *)&Java_org_lwjgl_opengles_EXTTextureStorage_nglTextureStorage1DEXT, "glTextureStorage1DEXT", (void *)&glTextureStorage1DEXT, false},
{"nglTextureStorage2DEXT", "(IIIIII)V", (void *)&Java_org_lwjgl_opengles_EXTTextureStorage_nglTextureStorage2DEXT, "glTextureStorage2DEXT", (void *)&glTextureStorage2DEXT, false},
{"nglTextureStorage3DEXT", "(IIIIIII)V", (void *)&Java_org_lwjgl_opengles_EXTTextureStorage_nglTextureStorage3DEXT, "glTextureStorage3DEXT", (void *)&glTextureStorage3DEXT, false}
};
int num_functions = NUMFUNCTIONS(functions);
extgl_InitializeClass(env, clazz, num_functions, functions);
}
|
eriqadams/computer-graphics
|
lib/lwjgl-2.9.1/lwjgl-source-2.9.1/src/native/generated/opengles/org_lwjgl_opengles_EXTTextureStorage.c
|
C
|
mit
| 4,247 |
/*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
package im.actor.core.entity;
import com.google.j2objc.annotations.Property;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import im.actor.core.api.ApiAvatar;
import im.actor.core.api.ApiBotCommand;
import im.actor.core.api.ApiContactRecord;
import im.actor.core.api.ApiContactType;
import im.actor.core.api.ApiFullUser;
import im.actor.core.api.ApiInt32Value;
import im.actor.core.api.ApiMapValue;
import im.actor.core.api.ApiMapValueItem;
import im.actor.core.api.ApiUser;
import im.actor.runtime.bser.BserCreator;
import im.actor.runtime.bser.BserValues;
import im.actor.runtime.bser.BserWriter;
import im.actor.runtime.storage.KeyValueItem;
// Disabling Bounds checks for speeding up calculations
/*-[
#define J2OBJC_DISABLE_ARRAY_BOUND_CHECKS 1
]-*/
public class User extends WrapperExtEntity<ApiFullUser, ApiUser> implements KeyValueItem {
private static final int RECORD_ID = 10;
private static final int RECORD_FULL_ID = 20;
public static BserCreator<User> CREATOR = User::new;
@Property("readonly, nonatomic")
private int uid;
@Property("readonly, nonatomic")
private long accessHash;
@NotNull
@Property("readonly, nonatomic")
@SuppressWarnings("NullableProblems")
private String name;
@Nullable
@Property("readonly, nonatomic")
private String localName;
@Nullable
@Property("readonly, nonatomic")
private String username;
@Nullable
@Property("readonly, nonatomic")
private String about;
@Nullable
@Property("readonly, nonatomic")
private Avatar avatar;
@NotNull
@Property("readonly, nonatomic")
@SuppressWarnings("NullableProblems")
private Sex sex;
@Property("readonly, nonatomic")
private boolean isBot;
@NotNull
@Property("readonly, nonatomic")
@SuppressWarnings("NullableProblems")
private List<ContactRecord> records;
@Property("readonly, nonatomic")
private boolean isBlocked;
@Nullable
@Property("readonly, nonatomic")
private String timeZone;
@Property("readonly, nonatomic")
private boolean isVerified;
@Property("readonly, nonatomic")
private List<BotCommand> commands;
@NotNull
@Property("readonly, nonatomic")
private boolean haveExtension;
public User(@NotNull ApiUser wrappedUser, @Nullable ApiFullUser ext) {
super(RECORD_ID, RECORD_FULL_ID, wrappedUser, ext);
}
public User(@NotNull byte[] data) throws IOException {
super(RECORD_ID, RECORD_FULL_ID, data);
}
private User() {
super(RECORD_ID, RECORD_FULL_ID);
}
@NotNull
public Peer peer() {
return new Peer(PeerType.PRIVATE, uid);
}
public int getUid() {
return uid;
}
public long getAccessHash() {
return accessHash;
}
@NotNull
public String getServerName() {
return name;
}
@Nullable
public String getLocalName() {
return localName;
}
@NotNull
public String getName() {
if (localName == null) {
return name;
} else {
return localName;
}
}
@Nullable
public String getNick() {
return username;
}
@Nullable
public String getAbout() {
return about;
}
@Nullable
public Avatar getAvatar() {
return avatar;
}
@NotNull
public Sex getSex() {
return sex;
}
public boolean isHaveExtension() {
return haveExtension;
}
@NotNull
public List<ContactRecord> getRecords() {
return records;
}
public boolean isBot() {
return isBot;
}
public List<BotCommand> getCommands() {
return commands;
}
public boolean isBlocked() {
return isBlocked;
}
@Nullable
public String getTimeZone() {
return timeZone;
}
public boolean isVerified() {
return isVerified;
}
public User editName(@NotNull String name) {
ApiUser w = getWrapped();
ApiUser res = new ApiUser(
w.getId(),
w.getAccessHash(),
name,
w.getLocalName(),
w.getNick(),
w.getSex(),
w.getAvatar(),
w.isBot(),
w.getExt());
res.setUnmappedObjects(w.getUnmappedObjects());
return new User(res, getWrappedExt());
}
public User editLocalName(@NotNull String localName) {
ApiUser w = getWrapped();
ApiUser res = new ApiUser(
w.getId(),
w.getAccessHash(),
w.getName(),
localName,
w.getNick(),
w.getSex(),
w.getAvatar(),
w.isBot(),
w.getExt());
res.setUnmappedObjects(w.getUnmappedObjects());
return new User(res, getWrappedExt());
}
public User editNick(@Nullable String nick) {
ApiUser w = getWrapped();
ApiUser res = new ApiUser(
w.getId(),
w.getAccessHash(),
w.getName(),
w.getLocalName(),
nick,
w.getSex(),
w.getAvatar(),
w.isBot(),
w.getExt());
res.setUnmappedObjects(w.getUnmappedObjects());
return new User(res, getWrappedExt());
}
public User editExt(@Nullable ApiMapValue ext) {
ApiUser w = getWrapped();
ApiUser res = new ApiUser(
w.getId(),
w.getAccessHash(),
w.getName(),
w.getLocalName(),
w.getNick(),
w.getSex(),
w.getAvatar(),
w.isBot(),
ext);
res.setUnmappedObjects(w.getUnmappedObjects());
return new User(res, getWrappedExt());
}
public User editAvatar(@Nullable ApiAvatar avatar) {
ApiUser w = getWrapped();
ApiUser res = new ApiUser(
w.getId(),
w.getAccessHash(),
w.getName(),
w.getLocalName(),
w.getNick(),
w.getSex(),
avatar,
w.isBot(),
w.getExt());
res.setUnmappedObjects(w.getUnmappedObjects());
return new User(res, getWrappedExt());
}
public User updateExt(@Nullable ApiFullUser ext) {
return new User(getWrapped(), ext);
}
public User editAbout(@Nullable String about) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
ext.getContactInfo(),
about,
ext.getPreferredLanguages(),
ext.getTimeZone(),
ext.getBotCommands(),
ext.getExt(),
ext.isBlocked()
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
public User editPreferredLanguages(List<String> preferredLanguages) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
ext.getContactInfo(),
ext.getAbout(),
preferredLanguages,
ext.getTimeZone(),
ext.getBotCommands(),
ext.getExt(),
ext.isBlocked()
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
public User editTimeZone(String timeZone) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
ext.getContactInfo(),
ext.getAbout(),
ext.getPreferredLanguages(),
timeZone,
ext.getBotCommands(),
ext.getExt(),
ext.isBlocked()
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
public User editContacts(List<ApiContactRecord> contacts) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
contacts,
ext.getAbout(),
ext.getPreferredLanguages(),
ext.getTimeZone(),
ext.getBotCommands(),
ext.getExt(),
ext.isBlocked()
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
public User editBotCommands(List<ApiBotCommand> commands) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
ext.getContactInfo(),
ext.getAbout(),
ext.getPreferredLanguages(),
ext.getTimeZone(),
commands,
ext.getExt(),
ext.isBlocked()
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
public User editFullExt(ApiMapValue extv) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
ext.getContactInfo(),
ext.getAbout(),
ext.getPreferredLanguages(),
ext.getTimeZone(),
ext.getBotCommands(),
extv,
ext.isBlocked()
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
public User editBlocked(boolean isBlocked) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
ext.getContactInfo(),
ext.getAbout(),
ext.getPreferredLanguages(),
ext.getTimeZone(),
ext.getBotCommands(),
ext.getExt(),
isBlocked
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
@Override
protected void applyWrapped(@NotNull ApiUser wrapped, @Nullable ApiFullUser ext) {
this.uid = wrapped.getId();
this.accessHash = wrapped.getAccessHash();
this.name = wrapped.getName();
this.localName = wrapped.getLocalName();
if (wrapped.getNick() != null && wrapped.getNick().length() > 0) {
this.username = wrapped.getNick();
} else {
this.username = null;
}
if (wrapped.getAvatar() != null) {
this.avatar = new Avatar(wrapped.getAvatar());
}
this.isBot = false;
if (wrapped.isBot() != null) {
this.isBot = wrapped.isBot();
}
this.sex = Sex.UNKNOWN;
if (wrapped.getSex() != null) {
switch (wrapped.getSex()) {
case FEMALE:
this.sex = Sex.FEMALE;
break;
case MALE:
this.sex = Sex.MALE;
break;
}
}
if (wrapped.getExt() != null) {
this.isVerified = true;
for (ApiMapValueItem i : wrapped.getExt().getItems()) {
if ("is_verified".equals(i.getKey())) {
if (i.getValue() instanceof ApiInt32Value) {
this.isVerified = ((ApiInt32Value) i.getValue()).getValue() > 0;
}
}
}
}
// Extension
if (ext != null) {
this.haveExtension = true;
this.records = new ArrayList<>();
this.commands = new ArrayList<BotCommand>();
if (ext.isBlocked() != null) {
this.isBlocked = ext.isBlocked();
} else {
this.isBlocked = false;
}
this.timeZone = ext.getTimeZone();
for (ApiContactRecord record : ext.getContactInfo()) {
if (record.getType() == ApiContactType.PHONE) {
this.records.add(new ContactRecord(ContactRecordType.PHONE, record.getTypeSpec(), "" + record.getLongValue(),
record.getTitle(), record.getSubtitle()));
} else if (record.getType() == ApiContactType.EMAIL) {
this.records.add(new ContactRecord(ContactRecordType.EMAIL, record.getTypeSpec(), record.getStringValue(),
record.getTitle(), record.getSubtitle()));
} else if (record.getType() == ApiContactType.WEB) {
this.records.add(new ContactRecord(ContactRecordType.WEB, record.getTypeSpec(), record.getStringValue(),
record.getTitle(), record.getSubtitle()));
} else if (record.getType() == ApiContactType.SOCIAL) {
this.records.add(new ContactRecord(ContactRecordType.SOCIAL, record.getTypeSpec(), record.getStringValue(),
record.getTitle(), record.getSubtitle()));
}
}
//Bot commands
for (ApiBotCommand command : ext.getBotCommands()) {
commands.add(new BotCommand(command.getSlashCommand(), command.getDescription(), command.getLocKey()));
}
this.about = ext.getAbout();
} else {
this.isBlocked = false;
this.haveExtension = false;
this.records = new ArrayList<>();
this.commands = new ArrayList<BotCommand>();
this.about = null;
this.timeZone = null;
}
}
@Override
public void parse(BserValues values) throws IOException {
// Is Wrapper Layout
if (values.getBool(8, false)) {
// Parse wrapper layout
super.parse(values);
} else {
// Convert old layout
throw new IOException("Unsupported obsolete format");
}
}
@Override
public void serialize(BserWriter writer) throws IOException {
// Mark as wrapper layout
writer.writeBool(8, true);
// Serialize wrapper layout
super.serialize(writer);
}
@Override
public long getEngineId() {
return getUid();
}
@Override
@NotNull
protected ApiUser createInstance() {
return new ApiUser();
}
@Override
protected ApiFullUser createExtInstance() {
return new ApiFullUser();
}
}
|
ljshj/actor-platform
|
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/entity/User.java
|
Java
|
mit
| 15,291 |
<?xml version="1.0" encoding="UTF-8"?>
<tileset name="Canalave Gym Set" firstgid="1" tilewidth="16" tileheight="16">
<image source="Canalave Gym Set.png" trans="000000"/>
</tileset>
|
vVv-AA/Pokemon-AndEngine
|
app/assets/tmx/workspace/Canalave Gym Set.tsx
|
TypeScript
|
mit
| 182 |
/*
* Copyright (c) 2011-2015 NinevehGL. More information at: http://nineveh.gl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#import "NGLRuntime.h"
#import "NGLError.h"
#import "NGLIterator.h"
/*!
* <strong>(Internal only)</strong> An object that holds the array values.
*
* This structure is used as a fixed pointer to preserve the necessary information/memory
* to the array values.
*
* @var NGLArrayValues::pointers
* The pointers array.
*
* @var NGLArrayValues::count
* The count/length of the array.
*
* @var NGLArrayValues::retainOption
* The retain option. This value can't be changed outside the initialization.
*
* @var NGLArrayValues::iterator
* The iterator pointer.
*
* @var NGLArrayValues::i
* The iterator index.
*/
typedef struct
{
void **pointers;
unsigned int count;
unsigned int capacity;
BOOL retainOption;
void **iterator;
unsigned int i;
} NGLArrayValues;
/*!
* Extremelly fast loop to work with NGLArray. This loop is slower than NSFastEnumeration,
* about 50% slower. However it accepts mutations during the loop and can work with
* any kind of data type (Objective-C or standard C).
*
* The syntax is a little bit different than the traditional forin loop:
*
* <pre>
*
* id variable;
*
* nglFor (variable, myNGLArray)
* {
* // Do something...
* }
*
* </pre>
*
* @param p
* A pointer that will receive the values.
*
* @param a
* The NGLArray instance to loop through.
*/
#define nglFor(p, a)\
for(NGLArrayValues *v = [(((a) != nil) ? (a) : [NGLArray array]) forLoop:(void **)&(p)];\
(*v).i < (*v).count;\
(*v).i++, (p) = *(*v).iterator++)
/*!
* Checks if a pointer is valid or not, that means, if a pointer is really pointing to
* a valid object (not released nor deallocated).
*
* @param pointer
* A C pointer to check.
*
* @result A BOOL indicating if the pointer is valid or not.
*/
NGL_API BOOL nglPointerIsValid(void *pointer);
/*!
* Checks if a pointer is valid for a specific kind of class.
*
* To check the validation against any kind of classes, use the #nglPointerIsValid#.
*
* @param pointer
* A C pointer to check.
*
* @param aClass
* An Objective-C class.
*
* @result A BOOL indicating if the pointer is valid or not.
*/
NGL_API BOOL nglPointerIsValidToClass(void *pointer, Class aClass);
/*!
* Checks if a pointer is valid for a specific protocol.
*
* This function will return NO if the pointer is released, deallocated, or just doesn't
* conform to the informed protocol.
*
* @param pointer
* A C pointer to check.
*
* @param aProtocol
* An Objective-C class.
*
* @result A BOOL indicating if the pointer is valid or not.
*/
NGL_API BOOL nglPointerIsValidToProtocol(void *pointer, Protocol *aProtocol);
/*!
* Checks if a pointer is valid and responds to a selector.
*
* This function will return NO if the pointer is released, deallocated, or just doesn't
* conform to the informed protocol.
*
* @param pointer
* A C pointer to check.
*
* @param selector
* An Objective-C selector.
*
* @result A BOOL indicating if the pointer is valid or not.
*/
NGL_API BOOL nglPointerIsValidToSelector(void *pointer, SEL selector);
/*!
* This class is a collection that works just like an array, however it's generic for
* any kind of data type, including basic C types. NGLArray does not retain
* the object.
*
* This class is faster than the traditional NSArray. Depending on the tasks, NGLArray
* can be 50% faster than NSArray, the most expensive task of NGLArray is at least
* 15% faster than NSArray, which is "removeAll". Actually, this class is more like a
* NSMutableArray, because you can change its collection at any time. This one also has
* a "hint" property called capacity, if you already know the maximum number of elements
* you can set this property to boost the performance a little bit more.
*
* By default, every time you try to insert an item in this array and it's capacity is
* full, a new block of 10 items will be allocated into this array.
*
* The reasons that cause this one to be faster than NSArray are:
*
* - It basically work with pointers and dereference, instead of indices.
* - It has an internal iterator loop that manages the enumerations.
* - It doesn't have many too checks. NGLArray assumes you know what you're doing.
*
* The achieve the best performance and still flexible, the NGLArray offers three kind
* of loops. Each one has its own cost and benefits:
*
* - <b>NGLIterator</b>: <i>Loops through 100 millions in 1.5 seg</i>.<br />
* Uses NGLIterator protocol. This loop is good for small array in which you
* need to change it's content during the loop or even from another thread.
* This routine offers a way to reset the loop at any time by calling the
* <code>resetIterator</code> method.
* The disadvantage of this routine is that it makes a Objective-C message call
* at each loop cycle, so it's a little expensive compared to the other ones.
* Its syntax is:
*
* <pre>
*
* id variable;
* while ((variable = [myNGLArray nextIterator]))
* {
* // Do something...
* }
*
* </pre>
*
* - <b>NGLFor</b>: <i>Loops through 100 millions in 0.45 seg</i>.<br />
* Very fast loop using the iterator properties. Can deal with changes during
* the loop or even from another thread.
* Its disadvantage is that it has a special syntax and just resets the iterator
* loop at the beginning. So if you're planning to use the <b>NGLIterator</b> after
* use this one, you must call <code>resetIterator</code> before start the
* <b>NGLIterator</b>. Its syntax is:
*
* <pre>
*
* id variable;
* nglFor (variable, myNGLArray)
* {
* // Do something...
* }
*
* </pre>
*
* - <b>ForEach</b>: <i>Loops through 100 millions in 0.3 seg</i>.<br />
* Uses NSFastEnumeration protocol (the Cocoa "for in" loop). This loop is the
* fastest one. However it's be used only in few situations.
* Its disadvantage is that it only work with Objective-C objects and the array
* can't be changed during the loop (changing the array during the loop will
* result in runtime error).
* Its syntax is:
*
* <pre>
*
* id variable;
* for (variable in myNGLArray)
* {
* // Do something...
* }
*
* </pre>
*
* The NGLArray class also provides a pointer to the items and a pointer to the
* mutations property. You can use them to implement your own NSFastEnumeration.
*/
@interface NGLArray : NSObject <NGLIterator, NSFastEnumeration>
{
@private
NGLArrayValues _values;
}
/*!
* The capacity property is not the size/count of the array, it's just a "hint" to optimize
* the array manipulation spped. This "hint" is useful for large array (above 10 items).
*
* The NGLArray will allocate the memory in sets/packages using this "hint" property.
*/
@property (nonatomic) unsigned int capacity;
/*!
* Indicates if this array will retain or not the objects in it. This property can't be
* changed to ensure the integrity of the items and must be set when initializing this
* array. Only Objective-C objects can receive retain messages.
*/
@property (nonatomic, readonly) BOOL retainOption;
/*!
* Returns the items pointer. This property is useful if you want to create your own
* implementation of NSFastEnumeration but keep using NGLArray as your collection.
*
* Remember that NSFastEnumeration is exclusive for Objective-C objects.
*/
@property (nonatomic, readonly) NGL_ARC_ASSIGN id *itemsPointer;
/*!
* Returns the mutations pointer. This property is useful if you want to create your own
* implementation of NSFastEnumeration but keep using NGLArray as your collection.
*
* Remember that NSFastEnumeration is exclusive for Objective-C objects.
*/
@property (nonatomic, readonly) unsigned long *mutationsPointer;
/*!
* <strong>(Internal only)</strong> Returns a pointer to the array values.
* You should not call this method directly.
*/
@property (nonatomic, readonly) NGLArrayValues *values;
/*!
* Initiates a NGLArray making it a safe collection, that means, it will retain every
* pointer that will be added to it. In this case, all pointer must be a subclass
* of NSObject.
*
* The retained objects will receive a release message when they are removed or this
* instance of NGLArray is released.
*
* @result A NGLArray instance.
*/
- (id) initWithRetainOption;
/*!
* Initiates a NGLArray instance based on another NGLArray.
*
* This method copies all objects/instances inside the informed NGLArray.
*
* @param pointers
* A NGLArray to serve as base to the new NGLArray.
*
* @result A NGLArray instance.
*/
- (id) initWithNGLArray:(NGLArray *)pointers;
/*!
* Initiates a NGLArray instance based on many object/instances.
*
* This method doesn't make use of addPointerOnce, that means if a target is informed
* more than one time, it will remain duplicated inside this collection.
*
* @param first
* The first object/instance to be added.
*
* @param ...
* A sequence of objects/instances separated by commas. This method must end with
* a <code>nil</code> element.
*
* @result A NGLArray instance.
*/
- (id) initWithPointers:(void *)first, ... NS_REQUIRES_NIL_TERMINATION;
/*!
* Adds a new object/instance to this collection. If the target already exist in this
* collection, it will be added again, resulting in a duplication.
*
* @param pointer
* The target it self.
*/
- (void) addPointer:(void *)pointer;
/*!
* Adds a new object/instance to this collection only if the target is not already inside
* this collection. If the target already exist, nothing will happen.
*
* @param pointer
* The target it self.
*/
- (void) addPointerOnce:(void *)pointer;
/*!
* Adds all object/instance to this collection from another NGLArray.
* This method copies all objects/instances inside the informed NGLArray.
*
* @param pointers
* The NGLArray instance to copy pointers from.
*/
- (void) addPointersFromNGLArray:(NGLArray *)pointers;
/*!
* Returns the index of a target inside this collection.
*
* @param pointer
* The target it self.
*
* @result Returns the index of the target or NGL_NOT_FOUND if the target was not found.
*/
- (unsigned int) indexOfPointer:(void *)pointer;
/*!
* Checks if a target is inside this collection.
*
* @param pointer
* The target it self.
*
* @result Returns YES (1) if the target is found, otherwise NO (0) will be returned.
*/
- (BOOL) hasPointer:(void *)pointer;
/*!
* Removes an object/instance inside this collection.
*
* @param pointer
* The target it self.
*/
- (void) removePointer:(void *)pointer;
/*!
* Removes an object/instance in a specific position inside this collection.
*
* @param index
* The index of the target. If the index is out of bounds, nothing will happen.
*/
- (void) removePointerAtIndex:(unsigned int)index;
/*!
* Removes the very first object/instance in this collection.
*/
- (void) removeFirst;
/*!
* Removes the very last object/instance in this collection.
*/
- (void) removeLast;
/*!
* Removes all the instances inside this library.
*
* This method makes a clean up inside this library, freeing all allocated
* memories to the instances in it.
*/
- (void) removeAll;
/*!
* Returns an object/instance in a specific position inside this collection.
*
* @param index
* The index of the target. If the index is out of bounds, NULL will be returned.
*
* @result A pointer or NULL if no result was found.
*/
- (void *) pointerAtIndex:(unsigned int)index;
/*!
* Returns the number of instances in this library at the moment.
*
* @result An int data type.
*/
- (unsigned int) count;
/*!
* <strong>(Internal only)</strong> Prepares this array to work with "nglFor" loop.
* You should not call this method directly.
*
* @param target
* A pointer to the target that will receive the items of this array. Inside this
* method the target will receive the first item.
*
* @result A pointer to the values of this array.
*/
- (NGLArrayValues *) forLoop:(void **)target;
/*!
* Returns an autoreleased instance of NGLArray.
*
* @result A NGLArray autoreleased instance.
*/
+ (id) array;
@end
/*!
* A category that extends the default behavior to perform some convenience method which
* could help when other classes makes use of this one.
*/
@interface NGLArray(NGLArrayExtended)
- (NSArray *) allPointers;
/*!
* A convenience method that loops through all objects making them perform a selector.
*
* IMPORTANT: This method assumes you're sure about this task and no additional check
* will be made to identify if the objects can receive such message. So, make sure all
* the objects are Objective-C instances and can receive the informed message.
*
* @param selector
* The selector which will be performed on all objects.
*/
- (void) makeAllPointersPerformSelector:(SEL)selector;
@end
|
hnney/NinevehGL
|
Source/utils/NGLArray.h
|
C
|
mit
| 14,692 |
package api
import (
"errors"
"io/ioutil"
"log"
"net/http"
"github.com/bitly/go-simplejson"
)
func Request(req *http.Request) (*simplejson.Json, error) {
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
log.Printf("got response code %d - %s", resp.StatusCode, body)
return nil, errors.New("api request returned non 200 status code")
}
data, err := simplejson.NewJson(body)
if err != nil {
return nil, err
}
return data, nil
}
func RequestUnparsedResponse(url string, header http.Header) (
response *http.Response, err error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, errors.New("failed building request for " +
url + ": " + err.Error())
}
req.Header = header
httpclient := &http.Client{}
if response, err = httpclient.Do(req); err != nil {
return nil, errors.New("request failed for " +
url + ": " + err.Error())
}
return
}
|
t-yuki/oauth2_proxy
|
api/api.go
|
GO
|
mit
| 1,053 |
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.0-master-ce33beb
*/
md-radio-button.md-THEME_NAME-theme .md-off {
border-color: '{{foreground-2}}'; }
md-radio-button.md-THEME_NAME-theme .md-on {
background-color: '{{accent-color-0.87}}'; }
md-radio-button.md-THEME_NAME-theme.md-checked .md-off {
border-color: '{{accent-color-0.87}}'; }
md-radio-button.md-THEME_NAME-theme.md-checked .md-ink-ripple {
color: '{{accent-color-0.87}}'; }
md-radio-button.md-THEME_NAME-theme .md-container .md-ripple {
color: '{{accent-A700}}'; }
md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary .md-on, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary .md-on,
md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary .md-on,
md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary .md-on {
background-color: '{{primary-color-0.87}}'; }
md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary .md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary.md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary .md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-off,
md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary .md-checked .md-off,
md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary.md-checked .md-off,
md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary .md-checked .md-off,
md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-off {
border-color: '{{primary-color-0.87}}'; }
md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary .md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary.md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary .md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-ink-ripple,
md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary .md-checked .md-ink-ripple,
md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary.md-checked .md-ink-ripple,
md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary .md-checked .md-ink-ripple,
md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary.md-checked .md-ink-ripple {
color: '{{primary-color-0.87}}'; }
md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-primary .md-container .md-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-primary .md-container .md-ripple,
md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-primary .md-container .md-ripple,
md-radio-button.md-THEME_NAME-theme:not([disabled]).md-primary .md-container .md-ripple {
color: '{{primary-600}}'; }
md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn .md-on, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn .md-on,
md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn .md-on,
md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn .md-on {
background-color: '{{warn-color-0.87}}'; }
md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn .md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn.md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn .md-checked .md-off, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked .md-off,
md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn .md-checked .md-off,
md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn.md-checked .md-off,
md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn .md-checked .md-off,
md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked .md-off {
border-color: '{{warn-color-0.87}}'; }
md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn .md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn.md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn .md-checked .md-ink-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked .md-ink-ripple,
md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn .md-checked .md-ink-ripple,
md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn.md-checked .md-ink-ripple,
md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn .md-checked .md-ink-ripple,
md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn.md-checked .md-ink-ripple {
color: '{{warn-color-0.87}}'; }
md-radio-group.md-THEME_NAME-theme:not([disabled]) .md-warn .md-container .md-ripple, md-radio-group.md-THEME_NAME-theme:not([disabled]).md-warn .md-container .md-ripple,
md-radio-button.md-THEME_NAME-theme:not([disabled]) .md-warn .md-container .md-ripple,
md-radio-button.md-THEME_NAME-theme:not([disabled]).md-warn .md-container .md-ripple {
color: '{{warn-600}}'; }
md-radio-group.md-THEME_NAME-theme[disabled],
md-radio-button.md-THEME_NAME-theme[disabled] {
color: '{{foreground-3}}'; }
md-radio-group.md-THEME_NAME-theme[disabled] .md-container .md-off,
md-radio-button.md-THEME_NAME-theme[disabled] .md-container .md-off {
border-color: '{{foreground-3}}'; }
md-radio-group.md-THEME_NAME-theme[disabled] .md-container .md-on,
md-radio-button.md-THEME_NAME-theme[disabled] .md-container .md-on {
border-color: '{{foreground-3}}'; }
md-radio-group.md-THEME_NAME-theme .md-checked .md-ink-ripple {
color: '{{accent-color-0.26}}'; }
md-radio-group.md-THEME_NAME-theme.md-primary .md-checked:not([disabled]) .md-ink-ripple, md-radio-group.md-THEME_NAME-theme .md-checked:not([disabled]).md-primary .md-ink-ripple {
color: '{{primary-color-0.26}}'; }
md-radio-group.md-THEME_NAME-theme .md-checked.md-primary .md-ink-ripple {
color: '{{warn-color-0.26}}'; }
md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty) .md-checked .md-container:before {
background-color: '{{accent-color-0.26}}'; }
md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty).md-primary .md-checked .md-container:before,
md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty) .md-checked.md-primary .md-container:before {
background-color: '{{primary-color-0.26}}'; }
md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty).md-warn .md-checked .md-container:before,
md-radio-group.md-THEME_NAME-theme.md-focused:not(:empty) .md-checked.md-warn .md-container:before {
background-color: '{{warn-color-0.26}}'; }
|
ioanvranau/iotplatformdashboard
|
app/bower_components/angular-material/modules/js/radioButton/radioButton-default-theme.css
|
CSS
|
mit
| 6,464 |
require 'net/http'
## monkey-patch Net::HTTP
#
# Certain apple endpoints return 415 responses if a Content-Type is supplied.
# Net::HTTP will default a content-type if none is provided by faraday
# This monkey-patch allows us to leave out the content-type if we do not specify one.
class Net::HTTPGenericRequest
def supply_default_content_type
return if content_type()
end
end
|
NghiaTranUIT/spaceship
|
lib/spaceship/helper/net_http_generic_request.rb
|
Ruby
|
mit
| 385 |
<?php
namespace spec\SensioLabs\Behat\PageObjectExtension\PageObject\Factory;
require_once __DIR__.'/Fixtures/ArticleList.php';
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use ProxyManager\Factory\LazyLoadingValueHolderFactory;
use ProxyManager\Proxy\LazyLoadingInterface;
use SensioLabs\Behat\PageObjectExtension\PageObject\Element;
use SensioLabs\Behat\PageObjectExtension\PageObject\Factory;
use SensioLabs\Behat\PageObjectExtension\PageObject\InlineElement;
use SensioLabs\Behat\PageObjectExtension\PageObject\Page;
use SensioLabs\Behat\PageObjectExtension\PageObject\PageObject;
class LazyFactorySpec extends ObjectBehavior
{
function let(Factory $decoratedFactory)
{
$this->beConstructedWith($decoratedFactory, new LazyLoadingValueHolderFactory());
}
function it_is_a_page_object_factory()
{
$this->shouldHaveType('SensioLabs\Behat\PageObjectExtension\PageObject\Factory');
}
function it_delegates_create_page_calls_to_the_decorated_factory(Factory $decoratedFactory, Page $page)
{
$decoratedFactory->createPage('ArticleList')->willReturn($page);
$this->createPage('ArticleList')->shouldReturn($page);
}
function it_delegates_create_element_calls_to_the_decorated_factory(Factory $decoratedFactory, Element $element)
{
$decoratedFactory->createElement('Foo')->willReturn($element);
$this->createElement('Foo')->shouldReturn($element);
}
function it_delegates_create_inline_element_calls_to_the_decorated_factory(Factory $decoratedFactory, InlineElement $element)
{
$decoratedFactory->createInlineElement('.foo')->willReturn($element);
$this->createInlineElement('.foo')->shouldReturn($element);
}
function it_creates_a_proxy_instead_of_instantiating_a_page_object_right_away()
{
$this->create('ArticleList')->shouldReturnAnInstanceOf('ProxyManager\Proxy\LazyLoadingInterface');
}
function it_delegates_instantiation_to_the_decorated_factory(PageObject $pageObject, Factory $decoratedFactory)
{
$decoratedFactory->create('ArticleList')->willReturn($pageObject);
$this->create('ArticleList')->shouldReturnAnInstanceOf('ProxyManager\Proxy\ProxyInterface');
}
}
|
sensiolabs/BehatPageObjectExtension
|
spec/PageObject/Factory/LazyFactorySpec.php
|
PHP
|
mit
| 2,257 |
{{ define "main" }}
{{ partial "breadcrumbs" . }}
<section class="resume-section p-3 p-lg-5 d-flex d-column content">
<div class="my-auto">
<h2 class="mb-0"><span class="text-primary">{{ .Title }}</span></h2>
<p><a href="{{ .Params.link }}">Link to full {{ .Params.pubtype }}</a></p>
{{ with .Params.image }}<img src="{{ . }}" style="max-height:300px;max-width:30%;" align="right"/>{{ end }}
{{ .Content }}
<p class="mt-3">
{{ partial "techtags" . }}
</p>
</div>
</section>
{{ end }}
|
localstatic/morganterry.com
|
themes/hugo-resume-customized/layouts/publications/single.html
|
HTML
|
mit
| 516 |
{{diagnostic}}
<div class="aw-ui-callout aw-ui-callout-info">
<span>Please see below all the price set for various Asha Payment Activities.</span>
</div>
<form class="form-horizontal" #rulesForm="ngForm" (ngSubmit)="onSubmit(ruleForm.value)" method="POST">
<div>
<h2>Maternal Health</h2>
<h3>ANC Checkups</h3>
<div class="form-group">
<label for="101" class="col-sm-4 control-label">No. of Registration during the first trimester of pregnancy at</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-101-R"><i class="fa fa-inr"></i></span>
<input id="101_R" class="form-control" type="text" aria-describedby="addon-101-R" [(ngModel)]="model.R_101" name="R_101" #name="ngModel">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-101-U"><i class="fa fa-inr"></i></span>
<input id="101_U" class="form-control" type="text" aria-describedby="addon-101-U" [(ngModel)]="model.U_101" name="U_101" #name="ngModel">
</div>
</div>
<div class="col-sm-2">
<textarea id="101_H" class="form-control" row="1" [(ngModel)]="model.H_101" name="H_101" #name="ngModel"></textarea>
</div>
</div>
<div class="form-group">
<label for="102" class="col-sm-4 control-label">No. of 1st check up</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-102-R"><i class="fa fa-inr"></i></span>
<input id="102_R" class="form-control" type="" aria-describedby="addon-102-R" [(ngModel)]="model.R_102" name="R_102" #name="ngModel">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-102-U"><i class="fa fa-inr"></i></span>
<input id="102_U" class="form-control" type="" aria-describedby="addon-102-U" [(ngModel)]="model.U_102" name="U_102" #name="ngModel">
</div>
</div>
<div class="col-sm-2">
<textarea id="102_H" class="form-control" row="1" [(ngModel)]="model.H_102" name="H_102" #name="ngModel"></textarea>
</div>
</div>
<div class="form-group">
<label for="103" class="col-sm-4 control-label">No. of 2 nd check up </label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-103-R"><i class="fa fa-inr"></i></span>
<input id="103_R" class="form-control" type="" aria-describedby="addon-103-R" [(ngModel)]="model.R_103" name="R_103" #name="ngModel">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-103-U"><i class="fa fa-inr"></i></span>
<input id="103_U" class="form-control" type="" aria-describedby="addon-103-U" [(ngModel)]="model.U_103" name="U_103" #name="ngModel">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1" [(ngModel)]="model.H_103" name="R_102" #name="ngModel"></textarea>
</div>
</div>
<div class="form-group">
<label for="104" class="col-sm-4 control-label">No. of 3 rd check up</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-104-R"><i class="fa fa-inr"></i></span>
<input id="104_R" class="form-control" type="" aria-describedby="addon-104-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-104-U"><i class="fa fa-inr"></i></span>
<input id="104_U" class="form-control" type="" aria-describedby="addon-104-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="105" class="col-sm-4 control-label">No. of 4 th check up by M.O</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-105-R"><i class="fa fa-inr"></i></span>
<input id="105_R" class="form-control" type="" aria-describedby="addon-105-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-105-U"><i class="fa fa-inr"></i></span>
<input id="105_U" class="form-control" type="" aria-describedby="addon-105-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="106" class="col-sm-4 control-label">No. of Deliveres conducted in PHC/Institutons</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-106-R"><i class="fa fa-inr"></i></span>
<input id="106_R" class="form-control" type="" aria-describedby="addon-106-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-106-U"><i class="fa fa-inr"></i></span>
<input id="106_U" class="form-control" type="" aria-describedby="addon-106-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="107" class="col-sm-4 control-label">No. of Maternal Death reported to Sub Centre</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-107-R"><i class="fa fa-inr"></i></span>
<input id="107_R" class="form-control" type="" aria-describedby="addon-107-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-107-U"><i class="fa fa-inr"></i></span>
<input id="107_U" class="form-control" type="" aria-describedby="addon-107-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
</div>
<div>
<h2>Child Health</h2>
<div class="form-group">
<label for="108" class="col-sm-4 control-label">Postnatal Visits (HBNC) (6 visits in Institutional Delivery, 7 Visits in Home Delivery)</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-108-R"><i class="fa fa-inr"></i></span>
<input id="108_R" class="form-control" type="" aria-describedby="addon-108-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-108-U"><i class="fa fa-inr"></i></span>
<input id="108_U" class="form-control" type="" aria-describedby="addon-108-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="109" class="col-sm-4 control-label">Rreferral & Follow up of SAM Cases to NRC</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-109-R"><i class="fa fa-inr"></i></span>
<input id="109_R" class="form-control" type="" aria-describedby="addon-109-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-109-U"><i class="fa fa-inr"></i></span>
<input id="109_U" class="form-control" type="" aria-describedby="addon-109-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="110" class="col-sm-4 control-label">Follow up of LBW babies (LBW Low Birth Weight Babies)</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-110-R"><i class="fa fa-inr"></i></span>
<input id="110_R" class="form-control" type="" aria-describedby="addon-110-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-110-U"><i class="fa fa-inr"></i></span>
<input id="110_U" class="form-control" type="" aria-describedby="addon-110-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="111" class="col-sm-4 control-label">Follow up of SNCU discharge babies</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-111-R"><i class="fa fa-inr"></i></span>
<input id="111_R" class="form-control" type="" aria-describedby="addon-111-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-111-U"><i class="fa fa-inr"></i></span>
<input id="111_U" class="form-control" type="" aria-describedby="addon-111-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="112" class="col-sm-4 control-label">Infant death reporting to Sub-centre and PHC</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-112-R"><i class="fa fa-inr"></i></span>
<input id="112_R" class="form-control" type="" aria-describedby="addon-112-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-112-U"><i class="fa fa-inr"></i></span>
<input id="112_U" class="form-control" type="" aria-describedby="addon-112-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="113" class="col-sm-4 control-label">Intesive Diarrhoea Control Programme</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-113-R"><i class="fa fa-inr"></i></span>
<input id="113_R" class="form-control" type="" aria-describedby="addon-113-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-113-U"><i class="fa fa-inr"></i></span>
<input id="113_U" class="form-control" type="" aria-describedby="addon-113-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
</div>
<div>
<h2>Immunization</h2>
<div class="form-group">
<label for="114" class="col-sm-4 control-label">Pulse Polio Booth Mobilization</label>
<div class="col-sm-2">
<div class="input-group disabled">
<span class="input-group-addon" id="addon-114-R"><i class="fa fa-inr"></i></span>
<input id="114_R" class="form-control" type="" aria-describedby="addon-114-R" disabled>
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-114-U"><i class="fa fa-inr"></i></span>
<input id="114_U" class="form-control" type="" aria-describedby="addon-114-U" disabled>
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<h3>Full Immunization</h3>
<div class="form-group">
<label for="115" class="col-sm-4 control-label">Complete Immunization in 1st year of age</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-115-R"><i class="fa fa-inr"></i></span>
<input id="115_R" class="form-control" type="" aria-describedby="addon-115-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-115-U"><i class="fa fa-inr"></i></span>
<input id="115U" class="form-control" type="" aria-describedby="addon-115-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="116" class="col-sm-4 control-label">Full Immunization of 2nd year of age</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-116-R"><i class="fa fa-inr"></i></span>
<input id="116" class="form-control" type="" aria-describedby="addon-116-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-116-U"><i class="fa fa-inr"></i></span>
<input id="116" class="form-control" type="" aria-describedby="addon-116-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
</div>
<div>
<h2>Family Planning</h2>
<div class="form-group">
<label for="117" class="col-sm-4 control-label">No. of Counseling & Motivation of women for Tubectomy</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-117-R"><i class="fa fa-inr"></i></span>
<input id="117" class="form-control" type="" aria-describedby="addon-117-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-117-U"><i class="fa fa-inr"></i></span>
<input id="117" class="form-control" type="" aria-describedby="addon-117-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="118" class="col-sm-4 control-label">No. of Counseling & Motivation for men of Vasectomy</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-118-R"><i class="fa fa-inr"></i></span>
<input id="118" class="form-control" type="" aria-describedby="addon-118-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-118-U"><i class="fa fa-inr"></i></span>
<input id="118" class="form-control" type="" aria-describedby="addon-118-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="119" class="col-sm-4 control-label">Accompanying the beneficiary for PPIUCD</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-119-R"><i class="fa fa-inr"></i></span>
<input id="119" class="form-control" type="" aria-describedby="addon-119-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-119-U"><i class="fa fa-inr"></i></span>
<input id="119" class="form-control" type="" aria-describedby="addon-119-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
</div>
<div>
<h2>RKSK (only for HPDs)</h2>
<div class="form-group">
<label for="120" class="col-sm-4 control-label">Support to Peer Educator</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-120-R"><i class="fa fa-inr"></i></span>
<input id="120" class="form-control" type="" aria-describedby="addon-120-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-120-U"><i class="fa fa-inr"></i></span>
<input id="120" class="form-control" type="" aria-describedby="addon-120-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="121" class="col-sm-4 control-label">Mobilizing Adolescents for AHD</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-121-R"><i class="fa fa-inr"></i></span>
<input id="121" class="form-control" type="" aria-describedby="addon-121-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-121-U"><i class="fa fa-inr"></i></span>
<input id="121" class="form-control" type="" aria-describedby="addon-121-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
</div>
<div>
<h2>RNTCP</h2>
<div class="form-group">
<label for="122" class="col-sm-4 control-label">New TB case Catg.I TB (42 contacts 6-7 months treatment)</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-122-R"><i class="fa fa-inr"></i></span>
<input id="122" class="form-control" type="" aria-describedby="addon-122-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-122-U"><i class="fa fa-inr"></i></span>
<input id="122" class="form-control" type="" aria-describedby="addon-122-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="123" class="col-sm-4 control-label">Previous treated TB case (57 contacts, catg.II TB 8-9 months treatment</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-123-R"><i class="fa fa-inr"></i></span>
<input id="123" class="form-control" type="" aria-describedby="addon-123-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-123-U"><i class="fa fa-inr"></i></span>
<input id="123" class="form-control" type="" aria-describedby="addon-123-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="124" class="col-sm-4 control-label">Providing treatment and support to Drug resistant TB patient (MDR)</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-124-R"><i class="fa fa-inr"></i></span>
<input id="124" class="form-control" type="" aria-describedby="addon-124-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-124-U"><i class="fa fa-inr"></i></span>
<input id="124" class="form-control" type="" aria-describedby="addon-124-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="125" class="col-sm-4 control-label">Identification & Successful completion of DOTS for TB</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-125-R"><i class="fa fa-inr"></i></span>
<input id="125" class="form-control" type="" aria-describedby="addon-125-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-125-U"><i class="fa fa-inr"></i></span>
<input id="125" class="form-control" type="" aria-describedby="addon-125-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
</div>
<div>
<h2>NLEP</h2>
<div class="form-group">
<label for="126" class="col-sm-4 control-label">PB - Referring for Diagnostics + Complete treatment</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-126-R"><i class="fa fa-inr"></i></span>
<input id="126" class="form-control" type="" aria-describedby="addon-126-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-126-U"><i class="fa fa-inr"></i></span>
<input id="126" class="form-control" type="" aria-describedby="addon-126-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="127" class="col-sm-4 control-label">MB - Dsetection + complete treatment</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-127-R"><i class="fa fa-inr"></i></span>
<input id="127" class="form-control" type="" aria-describedby="addon-127-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-127-U"><i class="fa fa-inr"></i></span>
<input id="127" class="form-control" type="" aria-describedby="addon-127-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
</div>
<div>
<h2>NVBDC Programme (Srikakulam, Vizianagaram, East Godavari)</h2>
<div class="form-group">
<label for="128" class="col-sm-4 control-label">Preparation of Blood Slide </label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-128-R"><i class="fa fa-inr"></i></span>
<input id="128" class="form-control" type="" aria-describedby="addon-128-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-128-U"><i class="fa fa-inr"></i></span>
<input id="128" class="form-control" type="" aria-describedby="addon-128-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="129" class="col-sm-4 control-label">Complete treatment for RDT +ve PF case & complete Radical treatment to +ve PF & PC cases</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-129-R"><i class="fa fa-inr"></i></span>
<input id="129" class="form-control" type="" aria-describedby="addon-129-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-129-U"><i class="fa fa-inr"></i></span>
<input id="129" class="form-control" type="" aria-describedby="addon-129-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="130" class="col-sm-4 control-label">Lymphatic Filariasis – for One time Line listing of Lymphoedema and Hydrocele cases in non-endemic dist</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-130-R"><i class="fa fa-inr"></i></span>
<input id="130" class="form-control" type="" aria-describedby="addon-130-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-130-U"><i class="fa fa-inr"></i></span>
<input id="130" class="form-control" type="" aria-describedby="addon-130-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="131" class="col-sm-4 control-label">Line listing of Lymphatic Filariasis</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-131-R"><i class="fa fa-inr"></i></span>
<input id="131" class="form-control" type="" aria-describedby="addon-131-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-131-U"><i class="fa fa-inr"></i></span>
<input id="131" class="form-control" type="" aria-describedby="addon-131-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="132" class="col-sm-4 control-label">Referral of AES / JE cases to the nearest CHC / DH / Medical College</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-132-R"><i class="fa fa-inr"></i></span>
<input id="132" class="form-control" type="" aria-describedby="addon-132-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-132-U"><i class="fa fa-inr"></i></span>
<input id="132" class="form-control" type="" aria-describedby="addon-132-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
</div>
<div>
<h2>Routine & Recurrent activities</h2>
<div class="form-group">
<label for="133" class="col-sm-4 control-label">Mobilizing & attending VHND in the month</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-133-R"><i class="fa fa-inr"></i></span>
<input id="133" class="form-control" type="" aria-describedby="addon-133-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-133-U"><i class="fa fa-inr"></i></span>
<input id="133" class="form-control" type="" aria-describedby="addon-133-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="134" class="col-sm-4 control-label">Attending VHSNC meeting</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-134-R"><i class="fa fa-inr"></i></span>
<input id="134" class="form-control" type="" aria-describedby="addon-134-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-134-U"><i class="fa fa-inr"></i></span>
<input id="134" class="form-control" type="" aria-describedby="addon-134-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="135" class="col-sm-4 control-label">Atttending ASHA Day Meeting</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-135-R"><i class="fa fa-inr"></i></span>
<input id="135" class="form-control" type="" aria-describedby="addon-135-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-135-U"><i class="fa fa-inr"></i></span>
<input id="135" class="form-control" type="" aria-describedby="addon-135-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="136" class="col-sm-4 control-label">Line listing of households done at beginning of the year and updated after six months</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-136-R"><i class="fa fa-inr"></i></span>
<input id="136" class="form-control" type="" aria-describedby="addon-136-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-136-U"><i class="fa fa-inr"></i></span>
<input id="136" class="form-control" type="" aria-describedby="addon-136-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="137" class="col-sm-4 control-label">Maintaining village health register and supporting universal registration of births and deaths</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-137-R"><i class="fa fa-inr"></i></span>
<input id="137" class="form-control" type="" aria-describedby="addon-137-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-137-U"><i class="fa fa-inr"></i></span>
<input id="137" class="form-control" type="" aria-describedby="addon-137-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="138" class="col-sm-4 control-label">Preparation of due list of children to be immunized updated on monthly basis</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-138-R"><i class="fa fa-inr"></i></span>
<input id="138" class="form-control" type="" aria-describedby="addon-138-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-138-U"><i class="fa fa-inr"></i></span>
<input id="138" class="form-control" type="" aria-describedby="addon-138-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="139" class="col-sm-4 control-label">Preparation of list of ANC beneficiaries to be updated on monthly basis</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-139-R"><i class="fa fa-inr"></i></span>
<input id="139" class="form-control" type="" aria-describedby="addon-139-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-139-U"><i class="fa fa-inr"></i></span>
<input id="139" class="form-control" type="" aria-describedby="addon-139-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="140" class="col-sm-4 control-label">Preparation of list of eligible couples updated on monthly basis</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-140-R"><i class="fa fa-inr"></i></span>
<input id="140" class="form-control" type="" aria-describedby="addon-140-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-140-U"><i class="fa fa-inr"></i></span>
<input id="140" class="form-control" type="" aria-describedby="addon-140-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
</div>
<div>
<h2>104 (by state budget)</h2>
<div class="form-group">
<label for="141" class="col-sm-4 control-label">No.of ASHA attended 104 Fixed day health services in villages </label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-141-R"><i class="fa fa-inr"></i></span>
<input id="141" class="form-control" type="" aria-describedby="addon-141-R">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon" id="addon-141-U"><i class="fa fa-inr"></i></span>
<input id="141" class="form-control" type="" aria-describedby="addon-141-U">
</div>
</div>
<div class="col-sm-2">
<textarea class="form-control" row="1"></textarea>
</div>
</div>
</div>
<div>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
|
mnjkumar426/asha_front
|
.history/src/app/admin-configuration/manage-activity-payment/manage-activity-payment.component_20170211121927.html
|
HTML
|
mit
| 40,023 |
//
// IMRoomCreateViewController.h
// Pods
//
// Created by FUNTEK Inc. on 2016/5/16.
//
//
#import "IMInviteClient.h"
#import "IMRoomInviteViewController.h"
#import "IMViewController.h"
@protocol IMRoomCreateDelegate;
@interface IMRoomCreateViewController : IMViewController
@property (weak, nonatomic) id <IMRoomCreateDelegate> delegate;
@end
@protocol IMRoomCreateDelegate <NSObject>
@end
|
FUNTEKco/imkit-ios-sdk
|
IMKitSDK.framework/Headers/IMRoomCreateViewController.h
|
C
|
mit
| 400 |
#include "overlapping.hpp"
/* TODO:
* grow seeds from edges, not nodes.
* Why are the results changing?
* Then, speed up delV
* ZEntropy shouldn't consider the number of groups, that should be taken out to another function.
* That factorial expression would be better
* Write down some of the stats, and be sure they're correct.
* unordered_map for efficiency more often?
* a big vector for the comm_count_per_edge?
* keep track of frontier properly in growingSeed
* type tags for the multi_index_container, instead of get<1>
* random tie-breaking in frontier
* update _p_in also.
*
* PLAN:
* Fully abstract interface to grouping
* Track count of types of edges.
* Varying p_in and p_out
* Each edge to know how many communities it's in.
* Calculate global objective function every now and then.
* More efficient finding of seeds
* Random tie breaking
* Stop seed growing at first positive?
*/
/*
* Sources of randomness:
* 246: Choice of initial edge seed
* 249: (arbitrary, not random) Randomized p_in
* 459: (arbitrary, not random) Tie breaker in seed expansion
*/
#include <list>
#include <map>
#include <algorithm>
#include <functional>
#include <math.h>
#include <string.h>
#include <fstream>
#include <sstream>
#include <float.h>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/hashed_index.hpp>
//#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/indexed_by.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/unordered_map.hpp>
#include <boost/unordered_set.hpp>
#include "iterative.hpp"
#include "options.hpp"
#include "Range.hpp"
#include "grouping.hpp"
#include <set>
using namespace std;
using namespace std::tr1 ;
using namespace grouping;
char option_saveMOSESscores[1000] = "";
long option_seed = 0;
int flag_justCalcObjective = 0;
static void runMutual(void) {
//system("echo;echo -n \" >> ;${x};${gt};${me}; \" ; bash -c '~/Code/Mutual3/mutual3/mutual \"${x}\"{\"${me}\",\"${gt}\"}' 1>&2 ");
}
namespace overlapping {
bool flag_save_group_id_in_output = true;
template <class N> static void overlappingT(bloomGraph<N> &g);
void overlapping(SimpleIntGraph &g) { overlappingT(g); }
void overlapping(SimpleStringGraph &g) { overlappingT(g); }
void addSeed(Grouping &ging, const set<V> &nodes, bool randomized_p_in);
static pair<long double, set<V> > growThisEdge(Grouping &ging, V edgeNumber, const long double &boost, bool randomized_p_in);
static void update_p_out(Grouping &ging);
static void estimate_p_in_and_p_out(Grouping &ging);
long double MOSES_objective(const Grouping &ging);
void addSeed(Grouping &ging, const set<V> &nodes, bool randomized_p_in) {
assert(nodes.size()>0);
Group *g = ging.newG(randomized_p_in);
ForeachContainer(V v, nodes) {
ging.addV(g, v);
}
}
void seedGroupingWithPartition(Grouping &ging, const iterative::Partition &p);
template <class N> static void useOneNodeSeeds(Grouping &ging, bloomGraph<N> &g, bool randomize_p_in);
template <class N> static void groupStats(const Grouping &ging, bloomGraph<N> &g);
template <class N> static void save(Grouping &ging, bloomGraph<N> &g);
template <class N> static void louvainStyle(Grouping &ging, bloomGraph<N> &g);
static void tryMerges(Grouping &ging);
static void tryDeletions(Grouping &ging, bool SaveScores = false);
static bool tryAndApplyThisOne(Grouping &ging, V e, bool randomized_p_in);
template <class N> static void overlappingT(bloomGraph<N> &g) {
printf("env: ALLOW_BOOST000 %s\n", getenv("ALLOW_BOOST000"));
printf("env: Lookahead %s\n", getenv("Lookahead"));
printf("env: MaxCommSize %s\n", getenv("MaxCommSize"));
printf("env: OUTER_ITERS %s\n", getenv("OUTER_ITERS"));
printf("env: LOUVAIN_ITERS %s\n", getenv("LOUVAIN_ITERS"));
printf("NoBroken\n");
srand48(option_seed); // default seed. Will be changeable by command line arg.
/*
iterative::Partition p(g);
iterative::findPartition(p, g);
assert(option_planted[0]==0);
strcpy(option_planted, option_overlapping);
strcat(option_planted, "_partition");
savePartition(g, p, -1);
long double p_in = (long double) p.m_i / p.a;
long double p_out;
{
int64 b = p.N * (p.N-1L) / 2L;
int64 m_e = p.m-p.m_i;
p_out = (long double) (m_e) / (b - p.a);
}
PP(p_in);
PP(p_out);
//Grouping ging(g, p_in, p_out);
//seedGroupingWithPartition(ging, p);
*/
Grouping ging(g, option_p_in, option_p_out);
estimate_p_in_and_p_out(ging);
ging.value_of_objective_with_no_communities = MOSES_objective(ging);
//PP(ging._p_in);
//PP(ging._p_out);
if(option_loadOverlapping[0]) { // load preexisting grouping
Pn("Preloading grouping '%s'", option_loadOverlapping);
ifstream inFile(option_loadOverlapping);
//for (int i=0; i<5; ++i)
int lineNo=0;
while(inFile.peek()!=EOF)
{
lineNo ++;
string line;
getline(inFile, line);
if(line.length()==0) break;
Group *grp = ging.newG();
istringstream linestream(line);
//PP(line);//
if(linestream.peek()=='"') {
char ch;
linestream >> ch;
while(linestream.peek() != EOF) {
linestream >> ch;
if(ch=='"')
break;
}
if(linestream.peek()!='\t') Die("grouping file should have a tab after any \" \". line %d {%d '%c'}", lineNo, (int) ch, ch);
}
while(linestream >> ws, linestream.peek() != EOF) {
N n;
linestream >> n;
V v = g.key_for_vertexName(n);
assert(v>=0);
assert(v<g.vcount());
ging.addV(grp, v);
}
}
save(ging, g);
}
estimate_p_in_and_p_out(ging);
groupStats(ging, g);
MOSES_objective(ging);
if(flag_justCalcObjective)
exit(0);
const int max_OuterIters = atoi(getenv("OUTER_ITERS") ? : "20");
PP(max_OuterIters);
for (int k=0; k<max_OuterIters; k++) {
MOSES_objective(ging);
const size_t num_groups_before = ging.groups.size();
ostringstream s;
s << "Whole outer iter " << k << "/" << max_OuterIters;
Timer timer(s.str());
Pn("\ngrow seeds %d/%d", k, max_OuterIters);
bool randomize_p_in;
if(k < max_OuterIters / 2) {
randomize_p_in = true;
Pn("Random p_i for each edge that we try");
estimate_p_in_and_p_out(ging); // this is just to estimate p_out
useOneNodeSeeds(ging, g, true);
estimate_p_in_and_p_out(ging);
tryDeletions(ging);
} else {
randomize_p_in = false;
useOneNodeSeeds(ging, g, false);
tryDeletions(ging);
}
groupStats(ging, g);
save(ging, g);
estimate_p_in_and_p_out(ging);
//tryDeletions(ging);
//save(ging, g);
const size_t num_groups_after = ging.groups.size();
if(!randomize_p_in && /*num_groups_after > 1000 && */ 0.99L * num_groups_after <= num_groups_before) {
Pn("breaking after %d growing passes, as VERY FEW more have been found among the most recent subset", k+1);
break;
}
}
int louvainStyle_iter=0;
const int max_louvainStyleIters = atoi(getenv("LOUVAIN_ITERS") ? : "10");
PP(max_louvainStyleIters);
while(louvainStyle_iter != max_louvainStyleIters) {
MOSES_objective(ging);
Timer timer("Whole Louvain iter");
Pn("\nLouvain-style iteration %d/%d", louvainStyle_iter++, max_louvainStyleIters);
louvainStyle(ging, g);
tryDeletions(ging, louvainStyle_iter==max_louvainStyleIters);
estimate_p_in_and_p_out(ging);
groupStats(ging, g);
save(ging, g);
}
if(0) {
tryMerges(ging);
save(ging, g);
groupStats(ging, g);
}
Pn("\n\nFINAL Grouping");
groupStats(ging, g);
estimate_p_in_and_p_out(ging);
MOSES_objective(ging);
}
static bool tryAndApplyThisOne(Grouping &ging, V e, bool randomized_p_in) {
static long double boost = 0.0L;
if(!getenv("ALLOW_BOOST000"))
boost=0.0L; // reset it back to zero unless ALLOW_BOOST000 is defined in the environment
pair<long double, set<V> > bestSeed = growThisEdge(ging, e, boost, randomized_p_in);
if(bestSeed.first + boost> 0.0L && bestSeed.second.size()>0 ) {
addSeed(ging, bestSeed.second, randomized_p_in);
boost /= 2.0; // if(boost<0.0L) boost=0.0L;
return true;
//Pn("Applied best 1-seed. Now returning. %zd nodes (+%Lg). Now there are %zd communities", bestSeed.second.size(), bestSeed.first, ging.groups.size());
// if(bestSeed.second.size() < 20) ForeachContainer (V v, bestSeed.second) { cout << "|" << g.name(v); } P("\n");
}
boost += 0.1;
return false;
}
template <class N> static void useOneNodeSeeds(Grouping &ging, bloomGraph<N> &g, bool randomize_p_in) {
Timer timer(__FUNCTION__);
const int numTries = g.ecount()/5;
P(" \n Now just use one-EDGE seeds at a time. Try %d edges\n", numTries);
// groupStats(ging, g);
for(int x=0; x<numTries; ++x) {
if(x && numTries>5 && x%(numTries/5)==0) {
PP(x);
PP(ging.groups.size());
}
// choose an edge at random, but prefer to use it iff it's sharedCommunities score is low.
V e = V(drand48() * (2*ging._g.ecount()));
assert(e >= 0);
assert(e < 2*ging._g.ecount());
if(randomize_p_in) {
ging._p_in = 0.01L + 0.98L*drand48();
assert(ging._p_in < 1.0L);
}
tryAndApplyThisOne(ging, e, randomize_p_in);
#if 0
int sharedCommunities = ging.comm_count_per_edge(ging._g.neighbours(0).first[e], &(ging._g.neighbours(0).first[e])); // a little time in here
//PP(sharedCommunities);
if( (double(rand())/RAND_MAX)
< powl(0.5, sharedCommunities))
{
//Pn(" X %d", sharedCommunities);
tryAndApplyThisOne(ging, e);
} else {
//Pn(" %d", sharedCommunities);
}
#endif
}
}
template <class N> static void groupStats(const Grouping &ging, bloomGraph<N> &g) {
map<size_t, int> group_sizes_of_the_randomized;
map<size_t, int> group_sizes;
int64 totalAssignments = 0; // to help calculate average communities per node.
ForeachContainer(Group *group, ging.groups) {
DYINGWORDS(group->vs.size()>0) {
PP(group->vs.size());
}
group_sizes[group->vs.size()]++;
totalAssignments += group->vs.size();
if(group->_randomized_p_in)
group_sizes_of_the_randomized[group->vs.size()]++;
}
//Perror(" %zd\n", ging.groups.size());
Pn("#groups=%zd. %zd nodes, out of %d, are in at least one community. avgs grps/node=%g", ging.groups.size(), ging.vgroups_size(), g.vcount(), (double) totalAssignments / g.vcount());
pair<size_t, int> group_size;
size_t max_group_size = group_sizes.size()==0 ? 0 : group_sizes.rbegin()->first;
int entries_per_row = 15;
int number_of_rows = (max_group_size / entries_per_row) + 1;
for(int r = 0; r<number_of_rows ; r++) {
for(size_t c = r; c <= max_group_size; c+=number_of_rows) {
if(group_sizes[c]>0)
P("%6d{%3zd}", group_sizes[c], c);
else
P(" ");
}
P("\n");
}
{ // now, just the randomized ones
size_t max_group_size = group_sizes_of_the_randomized.size()==0 ? 0 : group_sizes_of_the_randomized.rbegin()->first;
int entries_per_row = 15;
int number_of_rows = (max_group_size / entries_per_row) + 1;
for(int r = 0; r<number_of_rows ; r++) {
for(size_t c = r; c <= max_group_size; c+=number_of_rows) {
if(group_sizes_of_the_randomized[c]>0)
P("%6d{%3zd}", group_sizes_of_the_randomized[c], c);
else
P(" ");
}
P("\n");
}
}
#if 0
set<V> lonelyNodesInLargestGroup;
Group *largestGroup = NULL;
ForeachContainer(Group *group, ging.groups) {
if(group->vs.size() == max_group_size) {
ForeachContainer(V v, group->vs) {
P("(%zd)", ging.vgroups(v).size());
if(1 == ging.vgroups(v).size() && 0 == rand()%2)
lonelyNodesInLargestGroup.insert(v);
}
P("\n");
largestGroup = group;
break;
}
}
#endif
{
int print_count = 0;
for(map<int, V>::const_iterator it = ging.global_edge_counts.begin(); it!=ging.global_edge_counts.end(); ++it) {
P("%6d(%3d)", (int) it->second ,(int) it->first);
print_count++;
if(print_count%15==0)
P("\n");
}
P("\n");
//if(0) update_p_out(ging);
//PP(ging._p_in);
//PP(ging._p_out);
}
}
void seedGroupingWithPartition(Grouping &ging, const iterative::Partition &p) {
for(V c=0; c<p.g.vcount(); ++c) {
if(p.p[c].c == c) { // we're at the head node
//Pn(" order %d", p.p[c].order);
Group *grp = ging.newG();
V v = c;
do {
assert(c == p.p[v].c);
ging.addV(grp, v);
//Pn ("%d is in %d", v ,c);
v = p.p[v].next;
} while (v != c);
}
}
}
template <class It>
static size_t count_intersection(It it1b, It it1e, It it2b, It it2e) {
vector< typename It::value_type > is;
set_intersection(it1b, it1e, it2b, it2e, back_inserter(is));
return is.size();
}
template <class Container>
static size_t count_intersection(const Container &container1, const Container &container2) {
return count_intersection(
container1.begin()
, container1.end()
, container2.begin()
, container2.end()
);
}
struct DeltaSeed {
const V _v; // for this node
const int _group_size_smaller; // ...and this group (which v is NOT currently in)
const Grouping &_ging;
// what'd be the change in entropy (edge+Z+Q) from joining it?
long double _deltadeltaEdgeEntropy;
int count_edges_back_into_this_group;
long double deltadeltaPairEntropy() const {
return _deltadeltaEdgeEntropy + log2l(1.0L - _ging._p_in) * (_group_size_smaller - count_edges_back_into_this_group);
}
explicit DeltaSeed(V v, int group_size_smaller, Grouping &ging) : _v(v), _group_size_smaller(group_size_smaller), _ging(ging), _deltadeltaEdgeEntropy(0.0L), count_edges_back_into_this_group(0) {
//assert(_grp.vs.count(v)==0);
}
void addEdge2(V n, const V* edgeVN_ptr) { // n is connected to _v
assert(*edgeVN_ptr == n);
this->addEdge(n, _ging.comm_count_per_edge(n, edgeVN_ptr));
}
void addEdge(V , int sharedCommunities) { // n is connected to _v // TODO: might be quicker to pass in the count of sharedCommunities too
//assert(_ging._g.are_connected(_v, n)); // TODO: remove these assertions
//assert(_grp.vs.count(n) == 1);
//assert(_grp.vs.count(_v) == 0);
count_edges_back_into_this_group ++;
_deltadeltaEdgeEntropy += log2l(1.0L - (1.0L-_ging._p_out)*powl(1.0L - _ging._p_in, 1+sharedCommunities))
- log2l(1.0L - (1.0L-_ging._p_out)*powl(1.0L - _ging._p_in, sharedCommunities));
}
void redoEdge(V , int previous_sharedCommunities) { // n is connected to _v // TODO: might be quicker to pass in the count of sharedCommunities too
_deltadeltaEdgeEntropy -=(log2l(1.0L - (1.0L-_ging._p_out)*powl(1.0L - _ging._p_in, 1+previous_sharedCommunities))
- log2l(1.0L - (1.0L-_ging._p_out)*powl(1.0L - _ging._p_in, previous_sharedCommunities)));
_deltadeltaEdgeEntropy += log2l(1.0L - (1.0L-_ging._p_out)*powl(1.0L - _ging._p_in, 2+previous_sharedCommunities))
- log2l(1.0L - (1.0L-_ging._p_out)*powl(1.0L - _ging._p_in, 1+previous_sharedCommunities));
}
long double _deltaZentropy() const {
const size_t N = _ging._g.vcount();
const size_t x = _group_size_smaller;
const size_t x2 = 1+x;
return( x2 * log2l(x2) + (N-x2) * log2l(N-x2)
-x * log2l(x) - (N-x ) * log2l(N-x ) );
/*
(x2 * (log2l(x2)-log2l(N)) + (N-x2) * (log2l(N-x2)-log2l(N)) + log2l(1+ging.groups.size()) - log2l(N))
-(x * (log2l(x) -log2l(N)) + (N-x ) * (log2l(N-x )-log2l(N)) + log2l(1+ging.groups.size()) - log2l(N))
= (x2 * (log2l(x2)-log2l(N)) + (N-x2) * (log2l(N-x2)-log2l(N)) )
-(x * (log2l(x) -log2l(N)) + (N-x ) * (log2l(N-x )-log2l(N)) )
= (x2 * (log2l(x2) ) + (N-x2) * (log2l(N-x2) ) )
-(x * (log2l(x) ) + (N-x ) * (log2l(N-x ) ) )
= x2 * log2l(x2) + (N-x2) * log2l(N-x2)
-x * log2l(x) - (N-x ) * log2l(N-x )
*/
}
long double _deltaTotalentropy() const {
return this->deltadeltaPairEntropy() + this->_deltaZentropy();
}
};
struct FrontierNode {
FrontierNode(long double &score, V v) : _score(score), _v(v) {}
long double _score;
V _v;
struct Incrementer {
long double _x;
Incrementer(long double &x) : _x(x) {}
void operator() (FrontierNode &fn) const { fn._score += _x; }
};
};
using namespace boost::multi_index;
struct VertexTag {};
struct Frontier : private multi_index_container < // TODO: Some sort of binary tree sometime?
FrontierNode,
indexed_by<
ordered_non_unique< member<FrontierNode,long double,&FrontierNode::_score>, greater<long double> >,
hashed_unique< tag<VertexTag>, member<FrontierNode,V,&FrontierNode::_v> >
>
> {
// vertices, and their scores.
// easy removal of the highest-score vertices.
// easy increase of score of arbitrary members, adding them if they don't exist already.
public:
static long double __attribute__ ((noinline)) calcddEE(const Grouping &ging, int sharedCommunities) {
return log2l(1.0L - (1.0L-ging._p_out) * powl(1.0L - ging._p_in, 1+sharedCommunities))
- log2l(1.0L - (1.0L-ging._p_out) * powl(1.0L - ging._p_in, sharedCommunities))
- log2l(1.0L - ging._p_in)
+ 1e-20L * drand48() // random tie breaking
;
}
void addNode(const Grouping &ging, V to, const V *edgeFT_ptr) {
// to is being added to the frontier, BUT it may already be in the frontier.
// from is in the seed.
//assert(*edgeFT_ptr == to);
int sharedCommunities = ging.comm_count_per_edge(to, edgeFT_ptr); // a little time in here
long double deltadeltaEdgeEntropy = calcddEE(ging, sharedCommunities /*, to*/); // a little time in here
Frontier::nth_index<1>::type::iterator addOrModifyThis = this->get<1>().find(to);
if(addOrModifyThis==this->get<1>().end()) { // TODO: faster if search for to is done just once?
this->insert(FrontierNode(deltadeltaEdgeEntropy, to));
} else {
this->get<1>().modify(addOrModifyThis, FrontierNode::Incrementer(deltadeltaEdgeEntropy));
}
}
void erase_best_node() {
Frontier::iterator best_node = this->get<0>().begin();
this->erase(best_node);
}
int erase_this_node(V to) {
return this->get<1>().erase(to);
}
long double best_node_score() const {
Frontier::iterator best_node = this->get<0>().begin();
return best_node -> _score;
}
V best_node_v() const {
Frontier::iterator best_node = this->get<0>().begin();
return best_node -> _v;
}
bool Empty() const {
return this->empty();
}
};
static long double logNchoose(int64 N, int64 n_c) {
if(n_c==N)
return 0;
static vector<long double> logNchoose_vector;
// static int64 usedN;
assert(n_c>0);
assert(n_c<=N);
if (logNchoose_vector.size()==0) {
Timer t("logNchoose Initialization");
logNchoose_vector.resize(N+1);
// usedN = N;
long double lN = 0.0L;
for(int64 x1=1; x1<=N; x1++) {
if(x1>1) {
int64 i = x1-1;
lN += log2l(i) - log2l(N-i);
}
logNchoose_vector.at(x1) = lN;
}
}
assert(logNchoose_vector.at(0) == 0);
// DYINGWORDS(logNchoose_vector.at(N) == 0) { // will never be exactly zero, but it should be, in theory
assert(logNchoose_vector.size()>0);
// assert(usedN == N);
assert( size_t(N+1) == logNchoose_vector.size());
assert( size_t(n_c) < logNchoose_vector.size());
return logNchoose_vector.at(n_c);
}
pair<long double, set<V> > growingSeed(Grouping &ging, int lookahead
, set<V> &seed
, pair<long double, set<V> > bestSoFar
, long double seedEdgeEntropy
, int seed_size
, Frontier &frontier
, int edges_in_seed
, const long double &boost // to allow some negative communities to persist. The deletion phase will fix them later. This is to ensure that we have the best chance of filling the graph up quickly.
, bool randomized_p_in
)
// Find the expansion among the frontier that best improves the score. Then recurse to it.
// Stop growing if dead end is reached (empty frontier) or the seed isn't increasing and we already have at least 5 nodes.
// Return the best set of nodes
// TODO: Profile, then make this damn efficient
{
assert((int) seed.size() == seed_size);
if(frontier.Empty())
return bestSoFar;
const V best_v = frontier.best_node_v();
#if 0
{
IteratorRange<const V *> ns(ging._g.neighbours(best_v));
Foreach(V n, ns) {
if(1==seed.count(n)) { // This neighbour is already in the seed. That means the count of edges within the seed is about to be increased. Should update randomized p_in in light of this.
++edges_in_seed;
}
}
int64 pairsInSeed = seed_size * (1+seed_size) / 2;
long double new_p_in = 1.0L * (2*edges_in_seed+1) / (2 * pairsInSeed + 2) ;
if(randomized_p_in) ging._p_in = new_p_in;
/*
cout << edges_in_seed << "/" << (1+seed_size)
<< "\t" << 100.0 * edges_in_seed / (seed_size * (1+seed_size) / 2)
// << "\t" << ging._p_in << "\t" << randomized_p_in
<< "\t" << new_p_in
<< endl;
*/
assert(edges_in_seed <= (seed_size * (1+seed_size) / 2));
}
#endif
const long double newseedEdgeEntropy = seedEdgeEntropy + frontier.best_node_score() + log2l(1.0L-ging._p_in) * seed_size;
const int N = ging._g.vcount();
//const int x = seed_size;
const int x1= 1+seed_size;
//long double seed_totalDeltaEntropy = seedEdgeEntropy + x * (log2l(x)-log2l(N)) + (N-x) * (log2l(N-x)-log2l(N)) + log2l(1+ging.groups.size())/*equivalent groupings*/ - log2l(N)/*encoding of size of the group*/;
UNUSED int64 q = ging.groups.size(); if (q==0) q=1;
UNUSED const int64 q_= 1 + q;
const long double logNchoosen = logNchoose(N,x1);
const long double newseed_totalDeltaEntropy = newseedEdgeEntropy
//+ x1 * (log2l(x1)-log2l(N)) + (N-x1) * (log2l(N-x1)-log2l(N))
+ logNchoosen
- log2l(N+1)/*encoding of size of the group*/
+ log2l(1+ging.groups.size())/*equivalent groupings*/
//+ (getenv("UseBroken") ? ( ( q_ * (log2l(q_) - log2l(exp(1))) + log2l(N+1) - log2l(N+1-q_) ) - ( q * (log2l(q ) - log2l(exp(1))) + log2l(N+1) - log2l(N+1-q ) ) ) : 0)
;
if(bestSoFar.first < newseed_totalDeltaEntropy) {
bestSoFar.first = newseed_totalDeltaEntropy;
bestSoFar.second = seed;
bestSoFar.second.insert(best_v);
}
if( (size_t) seed_size >= lookahead +bestSoFar.second.size() ) // lookahead
return bestSoFar;
const size_t max_commsize = atoi(getenv("MaxCommSize") ? : "10000000");
if( (size_t) seed_size >= max_commsize ) { // max comm size
bestSoFar.first = -10000000; return bestSoFar;
}
//if( bestSoFar.first > 0.0L) // once positive, return immediately!!!!!!!!!!!!!
//return bestSoFar;
if( (size_t) seed_size > bestSoFar.second.size() && bestSoFar.first + boost > 0.0L) // once positive, return immediately if it drops.
return bestSoFar;
//if(bestSoFar.first > 0.0L)
//return bestSoFar; // This isn't working so well. Too many communities (I think), and no faster (for Oklahoma at least)
frontier.erase_best_node();
IteratorRange<const V *> ns(ging._g.neighbours(best_v));
const V *edgeVN_offset = ging._g.neighbours(best_v).first;
Foreach(V n, ns) {
assert( *edgeVN_offset == n);
//assert(ging._g.neighbours(0).first[ging._comm_count_per_edge2[edgeVN_offset].other_index] == best_v);
if(0==seed.count(n))
frontier.addNode(ging, n
, edgeVN_offset
);
++edgeVN_offset;
}
seed.insert(best_v);
return growingSeed(ging
, lookahead
, seed
, bestSoFar
, newseedEdgeEntropy
, 1 + seed_size
, frontier
, edges_in_seed
, boost
, randomized_p_in
);
}
struct ThrowingIterator {
struct Dereferenced {};
V & operator *() { throw Dereferenced(); }
void operator ++() { throw Dereferenced(); }
};
bool emptyIntersection(const pair<const V*, const V*> &l, const pair<const V*, const V*> &r) {
try {
set_intersection(
l.first
,l.second
,r.first
,r.second
,ThrowingIterator()
);
} catch (ThrowingIterator::Dereferenced &) {
return false;
}
return true; //inter.empty();
}
static pair<long double, set<V> > growThisEdge(Grouping &ging, const V edgeNumber, const long double &boost, bool randomized_p_in) {
assert(edgeNumber < 2*ging._g.ecount());
V r = ging._g.neighbours(0).first[edgeNumber];
V l = ging._g.neighbours(0).first[ging.comm_count_per_edge2[edgeNumber].other_index];
// there must be a triangle available
if(emptyIntersection(ging._g.neighbours(l),ging._g.neighbours(r)))
return make_pair(-1.0L, set<V>());
Frontier frontier;
{
IteratorRange<const V *> ns(ging._g.neighbours(l));
const V *edgeIN_ptr = ging._g.neighbours(l).first;
Foreach(V n, ns) {
frontier.addNode(ging, n, edgeIN_ptr);
++edgeIN_ptr;
}
}
//PP(frontier.size());
const int erased = frontier.erase_this_node(r);
DYINGWORDS(erased==1) {
PP(erased);
PP(l);
PP(r);
//PP(frontier.size());
PP(ging._g.degree(l));
PP(ging._g.degree(r));
IteratorRange<const V *> ns(ging._g.neighbours(l));
Foreach(V n, ns) { PP(n); }
}
assert(erased==1);
{
IteratorRange<const V *> ns(ging._g.neighbours(r));
const V *edgeIN_ptr = ging._g.neighbours(r).first;
Foreach(V n, ns) {
if(n!=l)
frontier.addNode(ging, n, edgeIN_ptr);
++edgeIN_ptr;
}
}
set<V> seed;
seed.insert(l);
seed.insert(r);
int sharedCommunities = ging.comm_count_per_edge(r, &(ging._g.neighbours(0).first[edgeNumber])); // a little time in here
pair<long double, set<V> > grownSeed = growingSeed(ging
, atoi(getenv("Lookahead") ? : "2")
, seed
, make_pair(-10000000.0L, seed) // This score is too low, but then we don't expect a singleton community to come out best anyway! Only positive scores are used.
, log2l(1.0L - (1.0L-ging._p_out) * powl(1.0L - ging._p_in, 1+sharedCommunities))
- log2l(1.0L - (1.0L-ging._p_out) * powl(1.0L - ging._p_in, sharedCommunities))
, 2
, frontier
, 1
, boost
, randomized_p_in
);
return grownSeed;
}
template <class N> static void save(Grouping &ging, bloomGraph<N> &g) {
ofstream saveFile(option_overlapping);
ForeachContainer(Group *grp, ging.groups) {
bool firstLine = true;
if(flag_save_group_id_in_output)
saveFile << '\"' << grp->_id << "\"\t";
ForeachContainer(V v, grp->vs) {
saveFile << (firstLine?"":" ") << g.name(v);
firstLine = false;
}
saveFile << endl;
}
runMutual();
}
struct hashGroup {
int operator() (Group *grp) const {
return grp->_id;
}
};
typedef boost::unordered_map<Group *, DeltaSeed, hashGroup> SeedDeltasT;
template <class N> static void louvainStyle(Grouping &ging, bloomGraph<N> &g) {
Timer t(__FUNCTION__);
// find a node, isolate it from its communities, Add back one at a time if appropriate.
const bool DEBUG_louvainStyle = 0;
for(V v=0; v<g.vcount(); v++) {
if(0) update_p_out(ging);
// if(v%(g.vcount()/20)==0) PP(v);
if(DEBUG_louvainStyle)
groupStats(ging, g);
if(DEBUG_louvainStyle)
cout << "removing node in these many groups: " << ging.vgroups(v).size() << endl;
ging.isolate(v);
SeedDeltasT _seedDeltas;
IteratorRange<const V *> ns(ging._g.neighbours(v));
{
const V * edgeVN_ptr = ging._g.neighbours(v).first;
Foreach(V n, ns) {
int sharedCommunities = ging.comm_count_per_edge(n,edgeVN_ptr);
// TODO: Could prepare the results for addEdge of v<>n
ForeachContainer(Group *grp, ging.vgroups(n)) {
_seedDeltas.insert(make_pair(grp, DeltaSeed(v, grp->vs.size(), ging))).first->second.addEdge(n, sharedCommunities);
//_seedDeltas.find(grp)->second.addEdge(n, sharedCommunities);
}
++edgeVN_ptr;
}
}
for(int addedBack = 0; _seedDeltas.size()>0 ; addedBack++) {
// for each neighbouring group, calculate the delta-entropy of expanding back in here.
pair<long double, Group *> bestGroup(-LDBL_MAX, (Group*) NULL);
int num_positive = 0;
for(SeedDeltasT::iterator i = _seedDeltas.begin(); i!=_seedDeltas.end(); ) {
if(i->second._deltaTotalentropy()<=0.0L) {
i = _seedDeltas.erase(i);
continue;
} else {
long double delta2 = i->second._deltaTotalentropy();
// TODO: Count the positive scores. No point proceeding if there aren't any more positive scores, as they can only decrease
if(bestGroup.first < delta2)
bestGroup = make_pair(delta2, i->first);
if(delta2>0.0L)
++num_positive;
}
++i;
}
if(bestGroup.first > 0.0L) {
assert(num_positive>=1);
ging.addV(bestGroup.second, v);
if(num_positive==1) { // if just one was positive, then there's no point continuing, as the rest will only lose more score.
break;
}
_seedDeltas.erase(bestGroup.second);
// the other potential groups on the end of this edge need to have their addEdge undone
const V * edgeVN_ptr = ging._g.neighbours(v).first;
IteratorRange<const V*> ns(ging._g.neighbours(v));
Foreach(V n, ns) {
assert(*edgeVN_ptr == n);
if(bestGroup.second->vs.count(n)) {
int previous_sharedCommunities = ging.comm_count_per_edge(n, edgeVN_ptr) - 1;
ForeachContainer(Group *grp, ging.vgroups(n)) {
SeedDeltasT::iterator grpInSeed =_seedDeltas.find(grp);
if(grpInSeed != _seedDeltas.end())
{
const long double before = grpInSeed->second._deltaTotalentropy();
grpInSeed->second.redoEdge(n, previous_sharedCommunities);
const long double after = grpInSeed->second._deltaTotalentropy();
if(after > before) {
Perror("%s:%d _deltaTotalentropy %Lg -> %Lg\n", __FILE__, __LINE__, before, after);
}
}
}
}
++edgeVN_ptr;
}
}
else
break;
}
}
}
static void update_p_out(Grouping &ging) {
long double new_p_out = 2.0L * ging.global_edge_counts[0] / ging._g.vcount() / (ging._g.vcount()-1) ;
if(new_p_out > 0.1L)
ging._p_out = 0.1L;
else
ging._p_out = new_p_out;
}
struct PairGroupHash {
int operator() (const pair<Group*,Group*> &pg) const {
return pg.first->_id + pg.second->_id;
}
};
static void tryMerges(Grouping &ging) {
Timer timer(__FUNCTION__);
typedef boost::unordered_map< pair<Group*,Group*> , long double, PairGroupHash> MergesT;
MergesT proposed_merges;
size_t counter=0;
for(V e = 0; e <
/*100000 */
2*ging._g.ecount()
; e++) {
//if(e % (2*ging._g.ecount()/10) ==0) { PP(e); }
V e2 = ging.comm_count_per_edge2[e].other_index;
V l = ging._g.neighbours(0).first[e2];
V r = ging._g.neighbours(0).first[e];
if(r<l) continue; // no point considering each edge twice
V sharedCommunities = ging.comm_count_per_edge2[e].shared_comms;
assert(sharedCommunities == ging.comm_count_per_edge2[e2].shared_comms);
//Pn("%d\t%d", l, r);
counter++;
const set<Group *> &lgrps = ging.vgroups(l);
const set<Group *> &rgrps = ging.vgroups(r);
//PP(lgrps.size());
//PP(rgrps.size());
vector<Group *> lonly, ronly;
set_difference(lgrps.begin(),lgrps.end(),rgrps.begin(),rgrps.end(),back_inserter(lonly));
set_difference(rgrps.begin(),rgrps.end(),lgrps.begin(),lgrps.end(),back_inserter(ronly));
//Pn("# unmatched %zd,%zd", lonly.size(), ronly.size());
ForeachContainer(Group *lg, lonly) {
ForeachContainer(Group *rg, ronly) {
long double qi = 1.0L - ging._p_in;
long double qo = 1.0L - ging._p_out;
//const int64 oldQz = ging.groups.size();
Group * lg1 = lg;
Group * rg1 = rg;
if(lg1 > rg1) swap(lg1, rg1);
MergesT::key_type key = make_pair(lg1, rg1);
MergesT::iterator pm = proposed_merges.find(key);
if(pm == proposed_merges.end()) {
const int64 s1 = lg1->vs.size();
const int64 s2 = rg1->vs.size();
vector<V> Union;
set_union(lg1->vs.begin(),lg1->vs.end(),rg1->vs.begin(),rg1->vs.end(),back_inserter(Union));
const int64 N = ging._g.vcount();
pm = proposed_merges.insert(make_pair(key,
log2l(qi)*0.5L* (long double)( Union.size() * (Union.size()-1) - s1*(s1-1) - s2*(s2-1) )
// + ( (oldQz) *log2l(oldQz-1) + log2l(exp(1)) - log2l(oldQz-2-N) )
// - ( (oldQz+1)*log2l(oldQz ) - log2l(oldQz-1-N) )
+ (s1+s2) * (log2l(s1+s2) /*- log2l(N)*/)
- (s1 ) * (log2l(s1 ) /*- log2l(N)*/)
- (s2 ) * (log2l(s2 ) /*- log2l(N)*/)
+ log2l(N) // one fewer community whose pi has to be encoded
)).first;
}
pm -> second+=
log2l(1.0L - qo * powl(qi, 1+sharedCommunities))
- log2l(1.0L - qo * powl(qi, sharedCommunities))
- log2l(qi) // for a given member of the map, each edge will be found exactly once. So here we cancel the affect of assuming it was disconnected
;
}
}
}
for(V e = 0; e <
/*100000 */
2*ging._g.ecount()
; e++) {
if(e % (2*ging._g.ecount()/10) ==0) {
PP(e);
}
V e2 = ging.comm_count_per_edge2[e].other_index;
V l = ging._g.neighbours(0).first[e2];
V r = ging._g.neighbours(0).first[e];
if(r<l) continue; // no point considering each edge twice
V sharedCommunities = ging.comm_count_per_edge2[e].shared_comms;
assert(sharedCommunities == ging.comm_count_per_edge2[e2].shared_comms);
//Pn("%d\t%d", l, r);
counter++;
const set<Group *> &lgrps = ging.vgroups(l);
const set<Group *> &rgrps = ging.vgroups(r);
//PP(lgrps.size());
//PP(rgrps.size());
vector<Group *> inter;
set_intersection(lgrps.begin(),lgrps.end(),rgrps.begin(),rgrps.end(),back_inserter(inter));
//Pn("# unmatched %zd,%zd", lonly.size(), ronly.size());
ForeachContainer(Group *lg, inter) {
ForeachContainer(Group *rg, inter) {
if(lg < rg) { // no point proposing a merge between a group and itself
long double qi = 1.0L - ging._p_in;
long double qo = 1.0L - ging._p_out;
Group * lg1 = lg;
Group * rg1 = rg;
if(lg1 > rg1) swap(lg1, rg1);
MergesT::key_type key = make_pair(lg1, rg1);
MergesT::iterator pm = proposed_merges.find(key);
if(pm != proposed_merges.end())
pm -> second+=
log2l(1.0L - qo * powl(qi, sharedCommunities-1))
- log2l(1.0L - qo * powl(qi, sharedCommunities))
+ log2l(qi) // for a given member of the map, each edge will be found exactly once. So here we cancel the affect of assuming it was disconnected
;
}
}
}
}
int64 merges_accepted = 0;
int64 merges_applied = 0;
for(MergesT::const_iterator pm = proposed_merges.begin(); pm != proposed_merges.end(); ++pm) {
const long double score = pm->second;
//const int64 N = ging._g.vcount();
boost::unordered_set<Group *> already_merged;
if(score >0.0) {
//PP(scoreEdges);
//PP(scoreZ);
merges_accepted++;
MergesT::key_type merge_these = pm->first;
if(already_merged.count(merge_these.first)==0 && already_merged.count(merge_these.second)==0) {
Group * l = merge_these.first;
Group * r = merge_these.second;
const set<V> these_nodes(l->vs); // copy them, so as to iterate properly over them.
//P(" "); PP(ging.groups.size());
ForeachContainer(V v, these_nodes) {
if(r->vs.count(v)==0) {
ging.addV(r,v);
}
assert(r->vs.count(v)==1);
//ging.delV(l,v);
}
//PP(ging.groups.size());
already_merged.insert(merge_these.first);
already_merged.insert(merge_these.second);
merges_applied++;
}
}
//if(score > -25.0) { printf("merge: %-11.2Lf\n", score); }
}
PP(proposed_merges.size());
PP(merges_accepted);
PP(merges_applied);
}
static void tryDeletions(Grouping &ging, bool SaveScores /*= true*/) { // delete groups which aren't making a positive contribution any more.
Timer timer(__FUNCTION__);
typedef boost::unordered_map< Group* , long double, hashGroup> DeletionsT;
DeletionsT proposed_deletions;
const int64 N = ging._g.vcount();
ForeachContainer(Group *grp, ging.groups) { // preseed with all groups, because we want the groups even that don't have an edge in them!
const int64 sz = grp->vs.size();
//int64 q = ging.groups.size() -1; if (q<=0) q=1;
//const int64 q_= 1 + q;
const long double logNchoosen = logNchoose(N,sz);
proposed_deletions.insert(make_pair(grp,
log2l(1.0L - ging._p_in)*(sz*(sz-1)/2)
+ logNchoosen
- log2l(N+1)/*encoding of size of the group*/
+ log2l(1+ging.groups.size())/*equivalent groupings*/
//+ (getenv("UseBroken") ? ( ( q_ * (log2l(q_) - log2l(exp(1))) + log2l(N+1) - log2l(N+1-q_) ) - ( q * (log2l(q ) - log2l(exp(1))) + log2l(N+1) - log2l(N+1-q ) ) ) : 0)
));
}
for(V e = 0; e <
/*100000 */
2*ging._g.ecount()
; e++) {
/*
if(e % (2*ging._g.ecount()/10) ==0) {
PP(e);
}
*/
V e2 = ging.comm_count_per_edge2[e].other_index;
V sharedCommunities = ging.comm_count_per_edge2[e].shared_comms;
assert(sharedCommunities == ging.comm_count_per_edge2[e2].shared_comms);
V l = ging._g.neighbours(0).first[e2];
V r = ging._g.neighbours(0).first[e];
if(r<l) continue; // no point considering each edge twice
const set<Group *> &lgrps = ging.vgroups(l);
const set<Group *> &rgrps = ging.vgroups(r);
vector<Group *> sharedComms;
set_intersection(lgrps.begin(),lgrps.end(),rgrps.begin(),rgrps.end(),back_inserter(sharedComms));
assert((size_t)sharedCommunities == sharedComms.size());
ForeachContainer(Group *grp, sharedComms) {
DeletionsT::iterator pm = proposed_deletions.find(grp);
assert(pm != proposed_deletions.end());
pm -> second+=
log2l(1.0L - (1.0L-ging._p_out) * powl(1.0L - ging._p_in, sharedCommunities))
- log2l(1.0L - (1.0L-ging._p_out) * powl(1.0L - ging._p_in, sharedCommunities-1))
- log2l(1.0L - ging._p_in)
;
}
}
assert(proposed_deletions.size() <= ging.groups.size()); // maybe some communities didn't have an edge in them
V deletions_accepted = 0;
map<V, int> deletions_sizes;
PP(ging.groups.size());
for(DeletionsT::const_iterator pm = proposed_deletions.begin(); pm != proposed_deletions.end(); ++pm) {
const long double score = pm->second;
//const int64 N = ging._g.vcount();
if(score < 0.0) {
//PP(scoreEdges);
//PP(scoreZ);
deletions_accepted++;
deletions_sizes[pm->first->vs.size()]++;
{ // delete the group
set<V> vs = pm->first->vs; // COPY the vertices in
ForeachContainer(V v, vs) {
ging.delV(pm->first, v);
}
// By now, pm->first will be an invalid pointer, as it will be been delete'd
}
}
}
P("deletions_accepted: %d\t", deletions_accepted);
pair<V, int> delete_size;
ForeachContainer(delete_size, deletions_sizes) {
P("%d{%d} ", delete_size.second, delete_size.first);
}
P("\n");
PP(ging.groups.size());
//if(SaveScores && option_saveMOSESscores[0]) Pn("NOT Saving the delta-scores for each comm");
if(SaveScores && option_saveMOSESscores[0]) {
Pn("Saving the MOSES delta-score for each community as per the --saveMOSESscores option");
ofstream saveFile(option_saveMOSESscores);
ForeachContainer(Group *grp, ging.groups) { // preseed with all groups, because we want the groups even that don't have an edge in them!
saveFile << proposed_deletions[grp] << '\t' << grp->vs.size() << endl;
}
}
}
long double P_x_given_z(const Grouping &ging, long double p_o, long double p_i, int sigma_shared_Xis1) {
const int64 N = ging._g.vcount();
const int64 m = ging._g.ecount() / 2L;
long double logP_XgivenZ = 0.0;
logP_XgivenZ += log2l(1.0L - p_o) * (N * (N-1) / 2 - m);
logP_XgivenZ += log2l(1.0L - p_i) * (ging._sigma_shared - sigma_shared_Xis1);
typedef pair <int,V> edge_countT;
ForeachContainer(const edge_countT &edge_count, ging.global_edge_counts) {
const int64 s = edge_count.first;
const int64 m_s = edge_count.second;
logP_XgivenZ += log2l(1.0L - (1.0L - p_o)*powl(1.0L - p_i, s)) * m_s;
}
return logP_XgivenZ;
}
long double MOSES_objective(const Grouping &ging) {
Timer t(__FUNCTION__);
// Three components
// P(x|z)
// Qz!
// product of binomial/N+1
int64 sigma_shared_Xis1 = 0;
pair <int,V> edge_count;
ForeachContainer(edge_count, ging.global_edge_counts) {
sigma_shared_Xis1 += edge_count.first * edge_count.second;
}
long double Pxz = P_x_given_z(ging, ging._p_out, ging._p_in, sigma_shared_Xis1);
long double Pz = 0.0;
for (size_t i = 1; i<=ging.groups.size(); i++) {
Pz += log2l(i); //+ log2l(1+ging.groups.size())/*equivalent groupings*/
//P(Pz);
}
// PP(Pz);
int64 N = ging._g.vcount();
ForeachContainer(const Group *grp, ging.groups) {
long double logNchoosen = logNchoose(N,grp->vs.size());
DYINGWORDS(logNchoosen <= 0.0) {
PP(logNchoosen);
}
assert(logNchoosen <= 0.0);
Pz += logNchoosen - log2l(N+1) ;
}
// PP(Pxz);
// PP(Pz);
// PP(Pxz + Pz);
// PP(ging.value_of_objective_with_no_communities);
if(ging.value_of_objective_with_no_communities==1.0)
Pn("Compression:\t%Lf\t%Lg\t%Lg", 1.0L
,Pz
,Pxz
);
else
Pn("Compression:\t%Lf\t%Lg\t%Lg", (Pxz + Pz) / ging.value_of_objective_with_no_communities
,Pz
,Pxz
);
return Pxz + Pz;
}
static void estimate_p_in_and_p_out(Grouping &ging) {
Timer t(__FUNCTION__);
//PP(ging._sigma_shared);
/*
int64 _sigma_shared2 = 0;
ForeachContainer(const Group *grp, ging.groups) {
_sigma_shared2 += int64(grp->vs.size()) * int64(grp->vs.size()-1);
}
PP(_sigma_shared2/2);
assert(_sigma_shared2 = 2 * ging._sigma_shared);
*/
const int64 N = ging._g.vcount();
const int64 m = ging._g.ecount() / 2L;
int64 sigma_shared_Xis1 = 0;
pair <int,V> edge_count;
ForeachContainer(edge_count, ging.global_edge_counts) {
sigma_shared_Xis1 += edge_count.first * edge_count.second;
}
//PP(sigma_shared_Xis1);
map<long double, pair<long double, long double>, greater<long double> > ALLlogP_XgivenZ;
for(long double p_i = 0.0L; (p_i+=0.001L) < 1.0L; ) {
for(long double p_o = 1e-11L; (p_o*=1.1L) < 1.0L; ) {
long double logP_XgivenZ = 0.0;
logP_XgivenZ += log2l(1.0L - p_o) * (N * (N-1) / 2 - m);
logP_XgivenZ += log2l(1.0L - p_i) * (ging._sigma_shared - sigma_shared_Xis1);
ForeachContainer(edge_count, ging.global_edge_counts) {
const int64 s = edge_count.first;
const int64 m_s = edge_count.second;
logP_XgivenZ += log2l(1.0L - (1.0L - p_o)*powl(1.0L - p_i, s)) * m_s;
}
assert(logP_XgivenZ == P_x_given_z(ging ,p_o ,p_i ,sigma_shared_Xis1));
ALLlogP_XgivenZ[logP_XgivenZ] = make_pair(p_i, p_o);
}
}
pair<long double, pair<long double, long double> > best;
ForeachContainer(best, ALLlogP_XgivenZ) {
Pn("BEST: %Lg,%Lg -> %9.0Lf ", best.second.first, best.second.second, best.first);
ging._p_in = best.second.first;
ging._p_out= best.second.second;
break;
}
}
} // namespace overlapping
|
rabbanyk/CommunityEvaluation
|
execs/CM-Overlapping-MOSES-McDaid/moses-2011-01-26/overlapping.cpp
|
C++
|
mit
| 42,402 |
'use strict';var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
switch (arguments.length) {
case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);
case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);
}
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var collection_1 = require('angular2/src/facade/collection');
var lang_1 = require('angular2/src/facade/lang');
var exceptions_1 = require('angular2/src/facade/exceptions');
var DefaultKeyValueDifferFactory = (function () {
function DefaultKeyValueDifferFactory() {
}
DefaultKeyValueDifferFactory.prototype.supports = function (obj) { return obj instanceof Map || lang_1.isJsObject(obj); };
DefaultKeyValueDifferFactory.prototype.create = function (cdRef) { return new DefaultKeyValueDiffer(); };
DefaultKeyValueDifferFactory = __decorate([
lang_1.CONST(),
__metadata('design:paramtypes', [])
], DefaultKeyValueDifferFactory);
return DefaultKeyValueDifferFactory;
})();
exports.DefaultKeyValueDifferFactory = DefaultKeyValueDifferFactory;
var DefaultKeyValueDiffer = (function () {
function DefaultKeyValueDiffer() {
this._records = new Map();
this._mapHead = null;
this._previousMapHead = null;
this._changesHead = null;
this._changesTail = null;
this._additionsHead = null;
this._additionsTail = null;
this._removalsHead = null;
this._removalsTail = null;
}
Object.defineProperty(DefaultKeyValueDiffer.prototype, "isDirty", {
get: function () {
return this._additionsHead !== null || this._changesHead !== null ||
this._removalsHead !== null;
},
enumerable: true,
configurable: true
});
DefaultKeyValueDiffer.prototype.forEachItem = function (fn) {
var record;
for (record = this._mapHead; record !== null; record = record._next) {
fn(record);
}
};
DefaultKeyValueDiffer.prototype.forEachPreviousItem = function (fn) {
var record;
for (record = this._previousMapHead; record !== null; record = record._nextPrevious) {
fn(record);
}
};
DefaultKeyValueDiffer.prototype.forEachChangedItem = function (fn) {
var record;
for (record = this._changesHead; record !== null; record = record._nextChanged) {
fn(record);
}
};
DefaultKeyValueDiffer.prototype.forEachAddedItem = function (fn) {
var record;
for (record = this._additionsHead; record !== null; record = record._nextAdded) {
fn(record);
}
};
DefaultKeyValueDiffer.prototype.forEachRemovedItem = function (fn) {
var record;
for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
fn(record);
}
};
DefaultKeyValueDiffer.prototype.diff = function (map) {
if (lang_1.isBlank(map))
map = collection_1.MapWrapper.createFromPairs([]);
if (!(map instanceof Map || lang_1.isJsObject(map))) {
throw new exceptions_1.BaseException("Error trying to diff '" + map + "'");
}
if (this.check(map)) {
return this;
}
else {
return null;
}
};
DefaultKeyValueDiffer.prototype.onDestroy = function () { };
DefaultKeyValueDiffer.prototype.check = function (map) {
var _this = this;
this._reset();
var records = this._records;
var oldSeqRecord = this._mapHead;
var lastOldSeqRecord = null;
var lastNewSeqRecord = null;
var seqChanged = false;
this._forEach(map, function (value, key) {
var newSeqRecord;
if (oldSeqRecord !== null && key === oldSeqRecord.key) {
newSeqRecord = oldSeqRecord;
if (!lang_1.looseIdentical(value, oldSeqRecord.currentValue)) {
oldSeqRecord.previousValue = oldSeqRecord.currentValue;
oldSeqRecord.currentValue = value;
_this._addToChanges(oldSeqRecord);
}
}
else {
seqChanged = true;
if (oldSeqRecord !== null) {
oldSeqRecord._next = null;
_this._removeFromSeq(lastOldSeqRecord, oldSeqRecord);
_this._addToRemovals(oldSeqRecord);
}
if (records.has(key)) {
newSeqRecord = records.get(key);
}
else {
newSeqRecord = new KVChangeRecord(key);
records.set(key, newSeqRecord);
newSeqRecord.currentValue = value;
_this._addToAdditions(newSeqRecord);
}
}
if (seqChanged) {
if (_this._isInRemovals(newSeqRecord)) {
_this._removeFromRemovals(newSeqRecord);
}
if (lastNewSeqRecord == null) {
_this._mapHead = newSeqRecord;
}
else {
lastNewSeqRecord._next = newSeqRecord;
}
}
lastOldSeqRecord = oldSeqRecord;
lastNewSeqRecord = newSeqRecord;
oldSeqRecord = oldSeqRecord === null ? null : oldSeqRecord._next;
});
this._truncate(lastOldSeqRecord, oldSeqRecord);
return this.isDirty;
};
/** @internal */
DefaultKeyValueDiffer.prototype._reset = function () {
if (this.isDirty) {
var record;
// Record the state of the mapping
for (record = this._previousMapHead = this._mapHead; record !== null; record = record._next) {
record._nextPrevious = record._next;
}
for (record = this._changesHead; record !== null; record = record._nextChanged) {
record.previousValue = record.currentValue;
}
for (record = this._additionsHead; record != null; record = record._nextAdded) {
record.previousValue = record.currentValue;
}
// todo(vicb) once assert is supported
// assert(() {
// var r = _changesHead;
// while (r != null) {
// var nextRecord = r._nextChanged;
// r._nextChanged = null;
// r = nextRecord;
// }
//
// r = _additionsHead;
// while (r != null) {
// var nextRecord = r._nextAdded;
// r._nextAdded = null;
// r = nextRecord;
// }
//
// r = _removalsHead;
// while (r != null) {
// var nextRecord = r._nextRemoved;
// r._nextRemoved = null;
// r = nextRecord;
// }
//
// return true;
//});
this._changesHead = this._changesTail = null;
this._additionsHead = this._additionsTail = null;
this._removalsHead = this._removalsTail = null;
}
};
/** @internal */
DefaultKeyValueDiffer.prototype._truncate = function (lastRecord, record) {
while (record !== null) {
if (lastRecord === null) {
this._mapHead = null;
}
else {
lastRecord._next = null;
}
var nextRecord = record._next;
// todo(vicb) assert
// assert((() {
// record._next = null;
// return true;
//}));
this._addToRemovals(record);
lastRecord = record;
record = nextRecord;
}
for (var rec = this._removalsHead; rec !== null; rec = rec._nextRemoved) {
rec.previousValue = rec.currentValue;
rec.currentValue = null;
this._records.delete(rec.key);
}
};
/** @internal */
DefaultKeyValueDiffer.prototype._isInRemovals = function (record) {
return record === this._removalsHead || record._nextRemoved !== null ||
record._prevRemoved !== null;
};
/** @internal */
DefaultKeyValueDiffer.prototype._addToRemovals = function (record) {
// todo(vicb) assert
// assert(record._next == null);
// assert(record._nextAdded == null);
// assert(record._nextChanged == null);
// assert(record._nextRemoved == null);
// assert(record._prevRemoved == null);
if (this._removalsHead === null) {
this._removalsHead = this._removalsTail = record;
}
else {
this._removalsTail._nextRemoved = record;
record._prevRemoved = this._removalsTail;
this._removalsTail = record;
}
};
/** @internal */
DefaultKeyValueDiffer.prototype._removeFromSeq = function (prev, record) {
var next = record._next;
if (prev === null) {
this._mapHead = next;
}
else {
prev._next = next;
}
// todo(vicb) assert
// assert((() {
// record._next = null;
// return true;
//})());
};
/** @internal */
DefaultKeyValueDiffer.prototype._removeFromRemovals = function (record) {
// todo(vicb) assert
// assert(record._next == null);
// assert(record._nextAdded == null);
// assert(record._nextChanged == null);
var prev = record._prevRemoved;
var next = record._nextRemoved;
if (prev === null) {
this._removalsHead = next;
}
else {
prev._nextRemoved = next;
}
if (next === null) {
this._removalsTail = prev;
}
else {
next._prevRemoved = prev;
}
record._prevRemoved = record._nextRemoved = null;
};
/** @internal */
DefaultKeyValueDiffer.prototype._addToAdditions = function (record) {
// todo(vicb): assert
// assert(record._next == null);
// assert(record._nextAdded == null);
// assert(record._nextChanged == null);
// assert(record._nextRemoved == null);
// assert(record._prevRemoved == null);
if (this._additionsHead === null) {
this._additionsHead = this._additionsTail = record;
}
else {
this._additionsTail._nextAdded = record;
this._additionsTail = record;
}
};
/** @internal */
DefaultKeyValueDiffer.prototype._addToChanges = function (record) {
// todo(vicb) assert
// assert(record._nextAdded == null);
// assert(record._nextChanged == null);
// assert(record._nextRemoved == null);
// assert(record._prevRemoved == null);
if (this._changesHead === null) {
this._changesHead = this._changesTail = record;
}
else {
this._changesTail._nextChanged = record;
this._changesTail = record;
}
};
DefaultKeyValueDiffer.prototype.toString = function () {
var items = [];
var previous = [];
var changes = [];
var additions = [];
var removals = [];
var record;
for (record = this._mapHead; record !== null; record = record._next) {
items.push(lang_1.stringify(record));
}
for (record = this._previousMapHead; record !== null; record = record._nextPrevious) {
previous.push(lang_1.stringify(record));
}
for (record = this._changesHead; record !== null; record = record._nextChanged) {
changes.push(lang_1.stringify(record));
}
for (record = this._additionsHead; record !== null; record = record._nextAdded) {
additions.push(lang_1.stringify(record));
}
for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
removals.push(lang_1.stringify(record));
}
return "map: " + items.join(', ') + "\n" + "previous: " + previous.join(', ') + "\n" +
"additions: " + additions.join(', ') + "\n" + "changes: " + changes.join(', ') + "\n" +
"removals: " + removals.join(', ') + "\n";
};
/** @internal */
DefaultKeyValueDiffer.prototype._forEach = function (obj, fn) {
if (obj instanceof Map) {
obj.forEach(fn);
}
else {
collection_1.StringMapWrapper.forEach(obj, fn);
}
};
return DefaultKeyValueDiffer;
})();
exports.DefaultKeyValueDiffer = DefaultKeyValueDiffer;
var KVChangeRecord = (function () {
function KVChangeRecord(key) {
this.key = key;
this.previousValue = null;
this.currentValue = null;
/** @internal */
this._nextPrevious = null;
/** @internal */
this._next = null;
/** @internal */
this._nextAdded = null;
/** @internal */
this._nextRemoved = null;
/** @internal */
this._prevRemoved = null;
/** @internal */
this._nextChanged = null;
}
KVChangeRecord.prototype.toString = function () {
return lang_1.looseIdentical(this.previousValue, this.currentValue) ?
lang_1.stringify(this.key) :
(lang_1.stringify(this.key) + '[' + lang_1.stringify(this.previousValue) + '->' +
lang_1.stringify(this.currentValue) + ']');
};
return KVChangeRecord;
})();
exports.KVChangeRecord = KVChangeRecord;
//# sourceMappingURL=default_keyvalue_differ.js.map
|
binariedMe/blogging
|
node_modules/angular2/src/core/change_detection/differs/default_keyvalue_differ.js
|
JavaScript
|
mit
| 14,210 |
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/DjulaHTMLtemplatingsystem.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/DjulaHTMLtemplatingsystem.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/DjulaHTMLtemplatingsystem"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/DjulaHTMLtemplatingsystem"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
|
PuercoPop/djula
|
doc/Makefile
|
Makefile
|
mit
| 6,847 |
#!/bin/bash
fusermount -u ${MNT}/xiaomi
|
GdZ/scriptfile
|
sh/umountmtp.sh
|
Shell
|
mit
| 40 |
window.hideAlert = function () {
$('#alertMessage').addClass("hidden");
$('#alertMessage').text("");
};
window.showAlert = function (msg) {
$('#alertMessage').text(msg);
$('#alertMessage').addClass("alert-danger");
$('#alertMessage').removeClass("hidden");
$('#alertMessage').fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
};
window.showInfo = function (msg) {
$('#alertMessage').text(msg);
$('#alertMessage').removeClass("alert-danger");
$('#alertMessage').removeClass("hidden");
$('#alertMessage').fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
};
window.dataErrorAlert = function (data) {
switch (data.idError) {
case "InvalidFile":
showAlert(Resources["InvalidFile"]);
break;
case "InvalidReg":
showAlert(Resources["WrongRegExpMessage"]);
break;
case "NotFound":
showAlert(Resources["NoSearchResultsMessage"]);
break;
case "InvalidPassword":
showAlert(Resources["UnlockInvalidPassword"]);
break;
default:
showAlert(data.idError);
break;
}
};
window.handleError = function (xhr, exception) {
hideLoader();
$('#workButton').removeClass("hidden");
var msg = '';
if (xhr.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (xhr.status == 404) {
msg = 'Requested page not found. [404]';
} else if (xhr.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + xhr.responseText;
}
showAlert(msg);
};
|
asposebarcode/Aspose_BarCode_NET
|
Demos/src/Aspose.BarCode.Live.Demos.UI/Scripts/Shared/Alert.js
|
JavaScript
|
mit
| 1,886 |
-- #######################################
-- ## Project: HUD iLife ##
-- ## For MTA: San Andreas ##
-- ## Name: HudComponent_Weapons.lua ##
-- ## Author: Noneatme ##
-- ## Version: 1.0 ##
-- ## License: See top Folder ##
-- #######################################
-- FUNCTIONS / METHODS --
local cFunc = {}; -- Local Functions
local cSetting = {}; -- Local Settings
HudComponent_Weapons = {};
HudComponent_Weapons.__index = HudComponent_Weapons;
--[[
]]
-- ///////////////////////////////
-- ///// New //////
-- ///// Returns: Object //////
-- ///////////////////////////////
function HudComponent_Weapons:New(...)
local obj = setmetatable({}, {__index = self});
if obj.Constructor then
obj:Constructor(...);
end
return obj;
end
-- ///////////////////////////////
-- ///// Toggle //////
-- ///// Returns: void //////
-- ///////////////////////////////
function HudComponent_Weapons:Toggle(bBool)
local component_name = "weapons"
if (bBool == nil) then
hud.components[component_name].enabled = not (hud.components[component_name].enabled);
else
hud.components[component_name].enabled = bBool;
end
end
-- ///////////////////////////////
-- ///// Render //////
-- ///// Returns: void //////
-- ///////////////////////////////
function HudComponent_Weapons:Render()
local component_name = "weapons"
local x, y = hud.components[component_name].sx, hud.components[component_name].sy;
local w, h = hud.components[component_name].width*hud.components[component_name].zoom, hud.components[component_name].height*hud.components[component_name].zoom;
local alpha = hud.components[component_name].alpha
-- Hintergrund
dxDrawImage(x, y, w, h, hud.pfade.images.."component_weapons/background.png", 0, 0, 0, tocolor(0, 134, 134, alpha/1.5))
dxDrawRectangle(x, y, w, h, tocolor(0, 0, 0, alpha/4));
local ammo = getPedAmmoInClip(localPlayer)
local weapon = getPedWeapon(localPlayer)
local totalammo = getPedTotalAmmo(localPlayer)-ammo;
-- Image
if(fileExists(hud.pfade.images.."component_weapons/weapons/"..weapon..".png")) then
dxDrawImage(x+(5*hud.components[component_name].zoom), y+(5*hud.components[component_name].zoom), (64*1.5)*hud.components[component_name].zoom, (64*1.5)*hud.components[component_name].zoom, hud.pfade.images.."component_weapons/weapons/"..weapon..".png", 0, 0, 0, tocolor(255, 255, 255, alpha));
end
dxDrawText(getWeaponNameFromID(weapon), x+5*hud.components[component_name].zoom, y+100*hud.components[component_name].zoom, x+(64*1.5)*hud.components[component_name].zoom, y+(64*1.5)*hud.components[component_name].zoom, tocolor(255, 255, 255, alpha/3), 0.2*hud.components[component_name].zoom, hud.fonts.audirmg, "center", "top", false, true)
-- Munition
-- Seite 1
--[[
local dingerProSeite = math.round(totalammo/2);
local offsetX = 0;
local addOffsetX = 50;
local offsetY = 20;
local maxOffsetY = h-10;
local addOffsetY = totalammo/
for i = 1, 2, 1 do
offsetY = 0;
for i = 1, dingerProSeite, 1 do
offsetY = offsetY+addOffsetY;
end
offsetX = offsetX+addOffsetX
end]]
local addx = (94*1.5)*hud.components[component_name].zoom
local addy = 50*hud.components[component_name].zoom
dxDrawText(ammo.."\n"..getPedTotalAmmo(localPlayer)-ammo, x+addx, y+addy, x+addx, y+addy, tocolor(255, 255, 255, alpha/3), 0.35*hud.components[component_name].zoom, hud.fonts.audirmg, "center", "top", false, true)
-- MaxMuninGraph
addx = addx+60*hud.components[component_name].zoom
addy = addy-30*hud.components[component_name].zoom
local max = 110
-- Hintergrund
dxDrawRectangle(x+addx, y+h-32*hud.components[component_name].zoom, 40*hud.components[component_name].zoom, -max*hud.components[component_name].zoom, tocolor(0, 0, 0, alpha/3))
-- Was Vorhanden ist
local vorhanden = max/(tonumber(getWeaponProperty(getWeaponNameFromID(weapon), "pro", "maximum_clip_ammo")) or 0)*ammo
dxDrawRectangle(x+addx, y+h-32*hud.components[component_name].zoom, 40*hud.components[component_name].zoom, -vorhanden*hud.components[component_name].zoom, tocolor(74, 255, 101, alpha/3))
local prozent = math.round(100/(tonumber(getWeaponProperty(getWeaponNameFromID(weapon), "pro", "maximum_clip_ammo")) or 0)*ammo)
if(prozent < 0) then
prozent = 0
end
dxDrawText(prozent.."%", x+170*hud.components[component_name].zoom, y+135*hud.components[component_name].zoom, x+(64*1.5)*hud.components[component_name].zoom+170*hud.components[component_name].zoom, y+(64*1.5)*hud.components[component_name].zoom+135*hud.components[component_name].zoom, tocolor(255, 255, 255, alpha/3), 0.2*hud.components[component_name].zoom, hud.fonts.audirmg, "center", "top")
--[[
local ammo = getPedAmmoInClip(localPlayer)
local weapon = getPedWeapon(localPlayer)
local totalammo = getPedTotalAmmo(localPlayer)-ammo;
if(ammo < 10) then
ammo = "0"..ammo
end
if(self.enabled or hud.hudModifier.state == true) then
-- Schrift
local ammostring = ammo.."/#00B052"..totalammo;
dxDrawText(string.rep("0", #string.gsub(ammostring, '#%x%x%x%x%x%x', '')), x, y+20*hud.components[component_name].zoom, x+w, y+h, tocolor(255, 255, 255, alpha/5), 0.5*hud.components[component_name].zoom, hud.fonts.audirmg, "center", "top")
dxDrawText(ammostring, x, y+20*hud.components[component_name].zoom, x+w, y+h, tocolor(255, 255, 255, alpha), 0.5*hud.components[component_name].zoom, hud.fonts.audirmg, "center", "top", false, false, false, true)
-- Image
if(fileExists(hud.pfade.images.."component_weapons/weapons/"..weapon..".png")) then
dxDrawImage(x+55*hud.components[component_name].zoom, y+70*hud.components[component_name].zoom, (286/2)*hud.components[component_name].zoom, (106/2)*hud.components[component_name].zoom, hud.pfade.images.."component_weapons/weapons/"..weapon..".png", 0, 0, 0, tocolor(255, 255, 255, 200));
end
end]]
end
-- ///////////////////////////////
-- ///// GetTime //////
-- ///// Returns: String //////
-- ///////////////////////////////
function HudComponent_Weapons:GetTime()
local time = getRealTime()
local day = time.monthday
local month = time.month+1
local year = time.year+1900
local hour = time.hour
local minute = time.minute
local second = time.second;
if(hour < 10) then
hour = "0"..hour;
end
if(minute < 10) then
minute = "0"..minute;
end
if(second < 10) then
second = "0"..second;
end
return day.."-"..month.."-"..year.." "..hour.."-"..minute.."-"..second;
end
-- ///////////////////////////////
-- ///// ShowComponent //////
-- ///// Returns: String //////
-- ///////////////////////////////
function HudComponent_Weapons:ShowComponent(bBool, prevSlot, newSlot)
if(isTimer(self.showtimer)) then
killTimer(self.showtimer);
end
self.forceRender = true;
self.showtimer = setTimer(function()
self.forceRender = false;
end, 3000, 1)
if(bBool == true) then
if(getPedWeapon(getLocalPlayer(),newSlot) == 43) then
if(hud) and (hud.enabled) then
-- hud:Toggle(false);
-- self.showHudAgain = true;
-- showChat(false);
end
elseif(getPedWeapon(getLocalPlayer(),prevSlot) == 43) then
if(self.showHudAgain) then
if(hud) then
-- showChat(true);
-- hud:Toggle(true);
end
end
end
elseif(bBool == 43) then
local x, y = guiGetScreenSize();
local tex = dxCreateScreenSource(x, y);
dxUpdateScreenSource(tex);
-- Screenshots --
local pixels = dxGetTexturePixels(tex);
if(pixels) then
cancelEvent();
local image = dxConvertPixels(pixels, "png");
local date = "ilife-"..self:GetTime();
local file = fileCreate("screenshots/"..date..".png");
fileWrite(file, image);
fileFlush(file);
fileClose(file);
else
showInfoBox("error", "Da du deinen Screenshot Upload deaktiviert hast, wird keine Screenshot in deinem iLife ordner gespeichert!")
end
destroyElement(tex);
end
end
-- ///////////////////////////////
-- ///// Constructor //////
-- ///// Returns: void //////
-- ///////////////////////////////
function HudComponent_Weapons:Constructor(...)
self.enabled = true;
self.forceRender = false;
self.showtimer = nil;
self.showComponentFunc = function(...) self:ShowComponent(...) end;
self.showComponentFunc2 = function(...) self:ShowComponent(true, ...) end;
self.showHudAgain = false;
-- Events --
addEventHandler("onClientPlayerWeaponSwitch", getLocalPlayer(),self.showComponentFunc)
addEventHandler("onClientPlayerWeaponFire", getLocalPlayer(),self.showComponentFunc)
addEventHandler("onClientPlayerWeaponSwitch", getLocalPlayer(),self.showComponentFunc2)
-- outputDebugString("[CALLING] HudComponent_Weapons: Constructor");
end
-- EVENT HANDLER --
|
Pandafuchs/iLife
|
client/Classes/Hud/cHudComponent_Weapons.lua
|
Lua
|
mit
| 8,618 |
#### Scripts
##### HashIncidentsFields
- Fixed an issue where custom fields were returned by default as part of the incident object.
|
demisto/content
|
Packs/ML/ReleaseNotes/1_2_1.md
|
Markdown
|
mit
| 134 |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Satrabel.Starter.EntityFramework;
using Abp.Authorization;
using Abp.BackgroundJobs;
using Abp.Notifications;
namespace Satrabel.OpenApp.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20170621153937_Added_Description_And_IsActive_To_Role")]
partial class Added_Description_And_IsActive_To_Role
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.1.2")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Abp.Application.Editions.Edition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64);
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32);
b.HasKey("Id");
b.ToTable("AbpEditions");
});
modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Discriminator")
.IsRequired();
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(2000);
b.HasKey("Id");
b.ToTable("AbpFeatures");
b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting");
});
modelBuilder.Entity("Abp.Auditing.AuditLog", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("BrowserInfo")
.HasMaxLength(256);
b.Property<string>("ClientIpAddress")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasMaxLength(128);
b.Property<string>("CustomData")
.HasMaxLength(2000);
b.Property<string>("Exception")
.HasMaxLength(2000);
b.Property<int>("ExecutionDuration");
b.Property<DateTime>("ExecutionTime");
b.Property<int?>("ImpersonatorTenantId");
b.Property<long?>("ImpersonatorUserId");
b.Property<string>("MethodName")
.HasMaxLength(256);
b.Property<string>("Parameters")
.HasMaxLength(1024);
b.Property<string>("ServiceName")
.HasMaxLength(256);
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.HasKey("Id");
b.HasIndex("TenantId", "ExecutionDuration");
b.HasIndex("TenantId", "ExecutionTime");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpAuditLogs");
});
modelBuilder.Entity("Abp.Authorization.PermissionSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Discriminator")
.IsRequired();
b.Property<bool>("IsGranted");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpPermissions");
b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<int>("RoleId");
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("RoleId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpRoleClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("EmailAddress");
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastLoginTime");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.Property<long?>("UserLinkId");
b.Property<string>("UserName");
b.HasKey("Id");
b.HasIndex("EmailAddress");
b.HasIndex("UserName");
b.HasIndex("TenantId", "EmailAddress");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "UserName");
b.ToTable("AbpUserAccounts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpUserClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("LoginProvider")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.IsRequired()
.HasMaxLength(256);
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "LoginProvider", "ProviderKey");
b.ToTable("AbpUserLogins");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("BrowserInfo")
.HasMaxLength(256);
b.Property<string>("ClientIpAddress")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime");
b.Property<byte>("Result");
b.Property<string>("TenancyName")
.HasMaxLength(64);
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.Property<string>("UserNameOrEmailAddress")
.HasMaxLength(255);
b.HasKey("Id");
b.HasIndex("UserId", "TenantId");
b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result");
b.ToTable("AbpUserLoginAttempts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long>("OrganizationUnitId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("TenantId", "OrganizationUnitId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserOrganizationUnits");
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<int>("RoleId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "RoleId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserRoles");
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.Property<string>("Value");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserTokens");
});
modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<bool>("IsAbandoned");
b.Property<string>("JobArgs")
.IsRequired()
.HasMaxLength(1048576);
b.Property<string>("JobType")
.IsRequired()
.HasMaxLength(512);
b.Property<DateTime?>("LastTryTime");
b.Property<DateTime>("NextTryTime");
b.Property<byte>("Priority");
b.Property<short>("TryCount");
b.HasKey("Id");
b.HasIndex("IsAbandoned", "NextTryTime");
b.ToTable("AbpBackgroundJobs");
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(256);
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.Property<string>("Value")
.HasMaxLength(2000);
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpSettings");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64);
b.Property<string>("Icon")
.HasMaxLength(128);
b.Property<bool>("IsDeleted");
b.Property<bool>("IsDisabled");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(10);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpLanguages");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(256);
b.Property<string>("LanguageName")
.IsRequired()
.HasMaxLength(10);
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Source")
.IsRequired()
.HasMaxLength(128);
b.Property<int?>("TenantId");
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(67108864);
b.HasKey("Id");
b.HasIndex("TenantId", "Source", "LanguageName", "Key");
b.ToTable("AbpLanguageTexts");
});
modelBuilder.Entity("Abp.Notifications.NotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Data")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasMaxLength(250);
b.Property<string>("ExcludedUserIds")
.HasMaxLength(131072);
b.Property<string>("NotificationName")
.IsRequired()
.HasMaxLength(96);
b.Property<byte>("Severity");
b.Property<string>("TenantIds")
.HasMaxLength(131072);
b.Property<string>("UserIds")
.HasMaxLength(131072);
b.HasKey("Id");
b.ToTable("AbpNotifications");
});
modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("EntityId")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.HasMaxLength(96);
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId");
b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId");
b.ToTable("AbpNotificationSubscriptions");
});
modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Data")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.IsRequired()
.HasMaxLength(96);
b.Property<byte>("Severity");
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("TenantId");
b.ToTable("AbpTenantNotifications");
});
modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<int>("State");
b.Property<int?>("TenantId");
b.Property<Guid>("TenantNotificationId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId", "State", "CreationTime");
b.ToTable("AbpUserNotifications");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(95);
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(128);
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<long?>("ParentId");
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("ParentId");
b.HasIndex("TenantId", "Code");
b.ToTable("AbpOrganizationUnits");
});
modelBuilder.Entity("Satrabel.JobManager.Authorization.Roles.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("Description")
.HasMaxLength(5000);
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64);
b.Property<bool>("IsActive");
b.Property<bool>("IsDefault");
b.Property<bool>("IsDeleted");
b.Property<bool>("IsStatic");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32);
b.Property<string>("NormalizedName")
.IsRequired()
.HasMaxLength(32);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedName");
b.ToTable("AbpRoles");
});
modelBuilder.Entity("Satrabel.JobManager.Authorization.Users.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("AuthenticationSource")
.HasMaxLength(64);
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("EmailAddress")
.IsRequired()
.HasMaxLength(256);
b.Property<string>("EmailConfirmationCode")
.HasMaxLength(328);
b.Property<bool>("IsActive");
b.Property<bool>("IsDeleted");
b.Property<bool>("IsEmailConfirmed");
b.Property<bool>("IsLockoutEnabled");
b.Property<bool>("IsPhoneNumberConfirmed");
b.Property<bool>("IsTwoFactorEnabled");
b.Property<DateTime?>("LastLoginTime");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<DateTime?>("LockoutEndDateUtc");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32);
b.Property<string>("NormalizedEmailAddress")
.IsRequired()
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.IsRequired()
.HasMaxLength(32);
b.Property<string>("Password")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("PasswordResetCode")
.HasMaxLength(328);
b.Property<string>("PhoneNumber");
b.Property<string>("SecurityStamp");
b.Property<string>("Surname")
.IsRequired()
.HasMaxLength(32);
b.Property<int?>("TenantId");
b.Property<string>("UserName")
.IsRequired()
.HasMaxLength(32);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedEmailAddress");
b.HasIndex("TenantId", "NormalizedUserName");
b.ToTable("AbpUsers");
});
modelBuilder.Entity("Satrabel.JobManager.MultiTenancy.Tenant", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConnectionString")
.HasMaxLength(1024);
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<int?>("EditionId");
b.Property<bool>("IsActive");
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("TenancyName")
.IsRequired()
.HasMaxLength(64);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("EditionId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenancyName");
b.ToTable("AbpTenants");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.Property<int>("EditionId");
b.HasIndex("EditionId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("EditionFeatureSetting");
});
modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.Property<int>("TenantId");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("TenantFeatureSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<int>("RoleId");
b.HasIndex("RoleId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("RolePermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<long>("UserId");
b.HasIndex("UserId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("UserPermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.HasOne("Satrabel.JobManager.Authorization.Roles.Role")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.HasOne("Satrabel.JobManager.Authorization.Users.User")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.HasOne("Satrabel.JobManager.Authorization.Users.User")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.HasOne("Satrabel.JobManager.Authorization.Users.User")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.HasOne("Satrabel.JobManager.Authorization.Users.User")
.WithMany("Tokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.HasOne("Satrabel.JobManager.Authorization.Users.User")
.WithMany("Settings")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.HasOne("Abp.Organizations.OrganizationUnit", "Parent")
.WithMany("Children")
.HasForeignKey("ParentId");
});
modelBuilder.Entity("Satrabel.JobManager.Authorization.Roles.Role", b =>
{
b.HasOne("Satrabel.JobManager.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("Satrabel.JobManager.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("Satrabel.JobManager.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("Satrabel.JobManager.Authorization.Users.User", b =>
{
b.HasOne("Satrabel.JobManager.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("Satrabel.JobManager.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("Satrabel.JobManager.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("Satrabel.JobManager.MultiTenancy.Tenant", b =>
{
b.HasOne("Satrabel.JobManager.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("Satrabel.JobManager.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId");
b.HasOne("Satrabel.JobManager.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasOne("Satrabel.JobManager.Authorization.Roles.Role")
.WithMany("Permissions")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasOne("Satrabel.JobManager.Authorization.Users.User")
.WithMany("Permissions")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
|
sachatrauwaen/OpenApp
|
src/Satrabel.Starter.Web.Spa/Migrations/20170621153937_Added_Description_And_IsActive_To_Role.Designer.cs
|
C#
|
mit
| 35,419 |
---
weekly_roundup: true
title: "Roundup: Agile subway, retrospectives and appreciation, instant GraphQL API,
fun counterfeits, less workdays"
date: '2018-07-20 13:00:00 BST'
authors:
- 'Elena Tanasoiu'
tags: # (Delete as appropriate)
- Culture
---
## Agile Subway Map - [Richard S](/people#richard-stobart)
https://www.agilealliance.org/agile101/subway-map-to-agile-practices/
Who knew that there was a Subway (Tube) map of the various Agile practices. _Lobs grenade and ducks for cover_
## Retrospectives and Appreciation- [Richard S](/people#richard-Stobart)
https://www.growingagile.co.za/2018/07/full-time-scrum-master-experiment-part-4-retrospectives/
We didn't want another minute to go by without giving you a chance to top up your retro-mojo.
## Hasura - An instant GraphQL API on Postgres - [Elena T](/people#elena-tanasoiu)
https://github.com/hasura/graphql-engine
I love me a well documented tool that you can play around with right away. Docs here: https://docs.hasura.io/1.0/graphql/manual/index.html
Main page here: https://hasura.io/
## A fun teardown of an iPhone X counterfeit - [Elena T](/people#elena-tanasoiu)
https://motherboard.vice.com/en_us/article/qvmkdd/counterfeit-iphone-x-review-and-teardown
I love the attention to detail put into this. It's even got its own (real!) IMEI number and face recognition (ish!).
The notch at the top is re-created by software.
Disclaimer: like any good counterfeit, it has backdoors and malicious code.
Even so, I would still definitely like to try one for myself.
## Work less, get more: New Zealand firm's four-day week an 'unmitigated success' - [Elena T](/people#elena-tanasoiu)
https://www.theguardian.com/world/2018/jul/19/work-less-get-more-new-zealand-firms-four-day-week-an-unmitigated-success
Work-life balance makes more progress, this time in New Zealand.
## Track of the Week - [Dawn T](/people#dawn-turner)
We're going back in time this week as a result of my recent Netflix Mad Men binge in the coolness of my dark living room (I don't like hot weather). They wrote some good tunes back then, including this one.. enjoy!
<iframe width="560" height="315" src="https://www.youtube.com/embed/HT2ao0rcxoA" frameborder="0" allowfullscreen></iframe>
[Patti Page - Old Cape Cod](https://www.youtube.com/watch?reload=9&=&v=HT2ao0rcxoA)
|
unboxed/unboxed.co
|
source/blog/2018-07-20-unboxed-links-roundup-for-w-c-16th-of-july-2018.html.markdown
|
Markdown
|
mit
| 2,340 |
# iTerm2 Puppet Module for Boxen
## Usage
```puppet
# Stable release
include iterm2::stable
# Dev release
include iterm2::dev
```
## Required Puppet Modules
* boxen
* stdlib
|
mootpointer/my-boxen
|
modules/iterm2/README.md
|
Markdown
|
mit
| 180 |
@font-face {
font-family: 'Voltaire';
src: url("assets/Voltaire.eot");
src: url("Voltaire.eot?#iefix") format("embedded-opentype"), url("assets/Voltaire.woff") format("woff"), url("assets/Voltaire.ttf") format("truetype"), url("assets/Voltaire.svg#webfont") format("svg"); }
|
ibrahimbensalah/Xania.Ledger
|
Xania.Public/wwwroot/site.css
|
CSS
|
mit
| 285 |
local pubsub = require "util.pubsub";
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local usermanager = require "core.usermanager";
local xmlns_pubsub = "http://jabber.org/protocol/pubsub";
local xmlns_pubsub_event = "http://jabber.org/protocol/pubsub#event";
local xmlns_pubsub_owner = "http://jabber.org/protocol/pubsub#owner";
local autocreate_on_publish = module:get_option_boolean("autocreate_on_publish", false);
local autocreate_on_subscribe = module:get_option_boolean("autocreate_on_subscribe", false);
local pubsub_disco_name = module:get_option("name");
if type(pubsub_disco_name) ~= "string" then pubsub_disco_name = "Prosody PubSub Service"; end
local expose_publisher = module:get_option_boolean("expose_publisher", false)
local service;
local lib_pubsub = module:require "pubsub";
local handlers = lib_pubsub.handlers;
local pubsub_error_reply = lib_pubsub.pubsub_error_reply;
module:depends("disco");
module:add_identity("pubsub", "service", pubsub_disco_name);
module:add_feature("http://jabber.org/protocol/pubsub");
function handle_pubsub_iq(event)
local origin, stanza = event.origin, event.stanza;
local pubsub = stanza.tags[1];
local action = pubsub.tags[1];
if not action then
return origin.send(st.error_reply(stanza, "cancel", "bad-request"));
end
local handler = handlers[stanza.attr.type.."_"..action.name];
if handler then
handler(origin, stanza, action, service);
return true;
end
end
function simple_broadcast(kind, node, jids, item, actor)
if item then
item = st.clone(item);
item.attr.xmlns = nil; -- Clear the pubsub namespace
if expose_publisher and actor then
item.attr.publisher = actor
end
end
local message = st.message({ from = module.host, type = "headline" })
:tag("event", { xmlns = xmlns_pubsub_event })
:tag(kind, { node = node })
:add_child(item);
for jid in pairs(jids) do
module:log("debug", "Sending notification to %s", jid);
message.attr.to = jid;
module:send(message);
end
end
module:hook("iq/host/"..xmlns_pubsub..":pubsub", handle_pubsub_iq);
module:hook("iq/host/"..xmlns_pubsub_owner..":pubsub", handle_pubsub_iq);
local feature_map = {
create = { "create-nodes", "instant-nodes", "item-ids" };
retract = { "delete-items", "retract-items" };
purge = { "purge-nodes" };
publish = { "publish", autocreate_on_publish and "auto-create" };
delete = { "delete-nodes" };
get_items = { "retrieve-items" };
add_subscription = { "subscribe" };
get_subscriptions = { "retrieve-subscriptions" };
set_configure = { "config-node" };
get_default = { "retrieve-default" };
};
local function add_disco_features_from_service(service)
for method, features in pairs(feature_map) do
if service[method] then
for _, feature in ipairs(features) do
if feature then
module:add_feature(xmlns_pubsub.."#"..feature);
end
end
end
end
for affiliation in pairs(service.config.capabilities) do
if affiliation ~= "none" and affiliation ~= "owner" then
module:add_feature(xmlns_pubsub.."#"..affiliation.."-affiliation");
end
end
end
module:hook("host-disco-info-node", function (event)
local stanza, origin, reply, node = event.stanza, event.origin, event.reply, event.node;
local ok, ret = service:get_nodes(stanza.attr.from);
if not ok or not ret[node] then
return;
end
event.exists = true;
reply:tag("identity", { category = "pubsub", type = "leaf" });
end);
module:hook("host-disco-items-node", function (event)
local stanza, origin, reply, node = event.stanza, event.origin, event.reply, event.node;
local ok, ret = service:get_items(node, stanza.attr.from);
if not ok then
return;
end
for _, id in ipairs(ret) do
reply:tag("item", { jid = module.host, name = id }):up();
end
event.exists = true;
end);
module:hook("host-disco-items", function (event)
local stanza, origin, reply = event.stanza, event.origin, event.reply;
local ok, ret = service:get_nodes(event.stanza.attr.from);
if not ok then
return;
end
for node, node_obj in pairs(ret) do
reply:tag("item", { jid = module.host, node = node, name = node_obj.config.name }):up();
end
end);
local admin_aff = module:get_option_string("default_admin_affiliation", "owner");
local unowned_aff = module:get_option_string("default_unowned_affiliation");
local function get_affiliation(jid, node)
local bare_jid = jid_bare(jid);
if bare_jid == module.host or usermanager.is_admin(bare_jid, module.host) then
return admin_aff;
end
if not node then
return unowned_aff;
end
end
function set_service(new_service)
service = new_service;
module.environment.service = service;
add_disco_features_from_service(service);
end
function module.save()
return { service = service };
end
function module.restore(data)
set_service(data.service);
end
function module.load()
if module.reloading then return; end
set_service(pubsub.new({
capabilities = {
none = {
create = false;
publish = false;
retract = false;
get_nodes = true;
subscribe = true;
unsubscribe = true;
get_subscription = true;
get_subscriptions = true;
get_items = true;
subscribe_other = false;
unsubscribe_other = false;
get_subscription_other = false;
get_subscriptions_other = false;
be_subscribed = true;
be_unsubscribed = true;
set_affiliation = false;
};
publisher = {
create = false;
publish = true;
retract = true;
get_nodes = true;
subscribe = true;
unsubscribe = true;
get_subscription = true;
get_subscriptions = true;
get_items = true;
subscribe_other = false;
unsubscribe_other = false;
get_subscription_other = false;
get_subscriptions_other = false;
be_subscribed = true;
be_unsubscribed = true;
set_affiliation = false;
};
owner = {
create = true;
publish = true;
retract = true;
delete = true;
get_nodes = true;
configure = true;
subscribe = true;
unsubscribe = true;
get_subscription = true;
get_subscriptions = true;
get_items = true;
subscribe_other = true;
unsubscribe_other = true;
get_subscription_other = true;
get_subscriptions_other = true;
be_subscribed = true;
be_unsubscribed = true;
set_affiliation = true;
};
};
autocreate_on_publish = autocreate_on_publish;
autocreate_on_subscribe = autocreate_on_subscribe;
broadcaster = simple_broadcast;
get_affiliation = get_affiliation;
normalize_jid = jid_bare;
}));
end
|
sarumjanuch/prosody
|
plugins/mod_pubsub/mod_pubsub.lua
|
Lua
|
mit
| 6,500 |
#include <rpc/rpc.h>
|
j-hoppe/BlinkenBone
|
projects/3rdparty/oncrpc_win32/win32/include/nm_rpc_old.h
|
C
|
mit
| 20 |
/*
* sha1.h
*
* Copyright (C) 1998, 2009
* Paul E. Jones <[email protected]>
* All Rights Reserved
*
*****************************************************************************
* $Id: sha1.h 12 2009-06-22 19:34:25Z paulej $
*****************************************************************************
*
* Description:
* This class implements the Secure Hashing Standard as defined
* in FIPS PUB 180-1 published April 17, 1995.
*
* Many of the variable names in the SHA1Context, especially the
* single character names, were used because those were the names
* used in the publication.
*
* Please read the file sha1.c for more information.
*
*/
#ifndef _SHA1_H_
#define _SHA1_H_
typedef unsigned int uint32;
typedef unsigned char byte;
/*
* This structure will hold context information for the hashing
* operation
*/
typedef struct SHA1Context {
uint32 Message_Digest[5]; /* Message Digest (output) */
unsigned Length_Low; /* Message length in bits */
unsigned Length_High; /* Message length in bits */
unsigned char Buffer[64]; /* 512-bit message blocks */
int Pos; /* Index into message block array */
} SHA1Context;
/*
* Function Prototypes
*/
void SHA1Reset(SHA1Context *);
void SHA1Input(SHA1Context *, const unsigned char *, unsigned);
void SHA1Finish(SHA1Context *, byte digest[20]);
void ShaHash(const byte *data, int data_size, byte digest[20]);
typedef struct SHA1HmacContext {
SHA1Context sha1, sha2;
} SHA1HmacContext;
void SHA1HmacReset(SHA1HmacContext *, const unsigned char *, unsigned);
void SHA1HmacInput(SHA1HmacContext *, const unsigned char *, unsigned);
void SHA1HmacFinish(SHA1HmacContext *, byte digest[20]);
#endif
|
andoma/vmir
|
test/misc/src/sha1.h
|
C
|
mit
| 1,797 |
---
title: Det nya förbundets präst
date: 03/06/2021
---
Hebreerbrevet betonar starkt Jesus som vår överstepräst i den himmelska helgedomen. Där finns faktiskt Nya testamentets tydligaste utläggning om det nya förbundet med dess betoning på Kristus som överstepräst. Detta är inget sammanträffande. Kristus himmelska prästtjänst är nära sammanbunden med det nya förbundets löften.
Gamla testamentets helgedomstjänst var medlet som undervisade om det gamla förbundets sanningar. Det kretsade kring offer och medling. Djur slaktades och deras blod förmedlades av präster. Alla dessa ritualer var naturligtvis symboler på frälsning enbart i Jesus. I dem själva fanns ingen frälsning.
`Läs Heb. 10:4. Varför fanns det ingen frälsning i dessa djurs död? Varför är inte ett djurs död tillräcklig för att ge frälsning?`
Alla dessa offer och den prästerliga förmedling som följde dem mötte sin uppfyllelse i Kristus. Jesus blev det offer som det nya förbundet är grundat på. Hans blod bekräftade det nya förbundet och gjorde Sinaiförbundet och dess offer ”gamla” och föråldrade. Det sanna offret har getts ”en gång för alla” (Heb. 9:26). När Kristus en gång dog fanns det inte mer något behov av att slakta djur. Den jordiska helgedomen hade fullföljt sin funktion.
`Läs Matt. 27:51, som talar om hur förhänget i den jordiska helgedomen brast när Jesus dog. Hur hjälper det oss att förstå varför den jordiska helgedomen hade blivit ersatt?`
Till dessa djuroffer var prästtjänsten naturligtvis bunden, de leviter som offrade och medlade i den jordiska helgedomen för folket. När offren upphörde fanns det inte längre något behov av deras tjänst. Allting hade uppfyllts i Jesus som nu tjänstgör genom sitt eget blod i helgedomen i himlen (se Heb. 8:1–5). Hebreerbrevet betonar Kristus som överstepräst i himlen dit han trädde in genom att utgjuta sitt eget blod (Heb. 9:12) och nu är vår medlare. Detta är grunden för det hopp och de löften vi har i det nya förbundet.
`Hur känns det för dig när du förstår att Jesus redan nu tjänstgör genom sitt eget blod i himlen för oss? Hur mycket tillit och trygghet ger det dig när det gäller frälsning?`
|
imasaru/sabbath-school-lessons
|
src/sv/2021-02/10/06.md
|
Markdown
|
mit
| 2,246 |
<?php
/*
* Copyright 2007-2013 Charles du Jeu - Abstrium SAS <team (at) pyd.io>
* This file is part of Pydio.
*
* Pydio is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <http://pyd.io/>.
*/
$mess=array(
"Source Viewer" => "Afficheur de sources",
"Syntax Highlighter for all major code source files" => "Coloration syntaxique pour la plupart des fichiers de code source",
);
|
reverserob/pydio-docker
|
pydio-core/plugins/editor.codemirror/i18n/conf/fr.php
|
PHP
|
mit
| 987 |
//
// KRActivityIndicatorView.h
// KRActivityIndicatorView
//
// Created by Krimpedance on 2017/05/10.
// Copyright © 2017年 Krimpedance. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for KRActivityIndicatorView.
FOUNDATION_EXPORT double KRActivityIndicatorViewVersionNumber;
//! Project version string for KRActivityIndicatorView.
FOUNDATION_EXPORT const unsigned char KRActivityIndicatorViewVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <KRActivityIndicatorView/PublicHeader.h>
|
krimpedance/KRActivityIndicatorView
|
KRActivityIndicatorView/KRActivityIndicatorView.h
|
C
|
mit
| 598 |
//
// UIDevice+YYAdd.h
// YYCategories <https://github.com/ibireme/YYCategories>
//
// Created by ibireme on 13/4/3.
// Copyright (c) 2015 ibireme.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
/**
Provides extensions for `UIDevice`.
*/
@interface UIDevice (YYAdd)
#pragma mark - Device Information
///=============================================================================
/// @name Device Information
///=============================================================================
/// Device system version (e.g. 8.1)
+ (float)systemVersion;
/// Whether the device is iPad/iPad mini.
@property (nonatomic, readonly) BOOL isPad;
/// Whether the device is a simulator.
@property (nonatomic, readonly) BOOL isSimulator;
/// Whether the device is jailbroken.
@property (nonatomic, readonly) BOOL isJailbroken;
/// Wherher the device can make phone calls.
@property (nonatomic, readonly) BOOL canMakePhoneCalls NS_EXTENSION_UNAVAILABLE_IOS("");
/// The device's machine model. e.g. "iPhone6,1" "iPad4,6"
/// @see http://theiphonewiki.com/wiki/Models
@property (nonatomic, readonly) NSString *machineModel;
/// The device's machine model name. e.g. "iPhone 5s" "iPad mini 2"
/// @see http://theiphonewiki.com/wiki/Models
@property (nonatomic, readonly) NSString *machineModelName;
/// The System's startup time.
@property (nonatomic, readonly) NSDate *systemUptime;
#pragma mark - Network Information
///=============================================================================
/// @name Network Information
///=============================================================================
/// WIFI IP address of this device (can be nil). e.g. @"192.168.1.111"
@property (nonatomic, readonly) NSString *ipAddressWIFI;
/// Cell IP address of this device (can be nil). e.g. @"10.2.2.222"
@property (nonatomic, readonly) NSString *ipAddressCell;
#pragma mark - Disk Space
///=============================================================================
/// @name Disk Space
///=============================================================================
/// Total disk space in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t diskSpace;
/// Free disk space in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t diskSpaceFree;
/// Used disk space in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t diskSpaceUsed;
#pragma mark - Memory Information
///=============================================================================
/// @name Memory Information
///=============================================================================
/// Total physical memory in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t memoryTotal;
/// Used (active + inactive + wired) memory in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t memoryUsed;
/// Free memory in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t memoryFree;
/// Acvite memory in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t memoryActive;
/// Inactive memory in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t memoryInactive;
/// Wired memory in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t memoryWired;
/// Purgable memory in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t memoryPurgable;
#pragma mark - CPU Information
///=============================================================================
/// @name CPU Information
///=============================================================================
/// Avaliable CPU processor count.
@property (nonatomic, readonly) NSUInteger cpuCount;
/// Current CPU usage, 1.0 means 100%. (-1 when error occurs)
@property (nonatomic, readonly) float cpuUsage;
/// Current CPU usage per processor (array of NSNumber), 1.0 means 100%. (nil when error occurs)
@property (nonatomic, readonly) NSArray *cpuUsagePerProcessor;
@end
#ifndef kSystemVersion
#define kSystemVersion [UIDevice systemVersion]
#endif
#ifndef kiOS6Later
#define kiOS6Later (kSystemVersion >= 6)
#endif
#ifndef kiOS7Later
#define kiOS7Later (kSystemVersion >= 7)
#endif
#ifndef kiOS8Later
#define kiOS8Later (kSystemVersion >= 8)
#endif
#ifndef kiOS9Later
#define kiOS9Later (kSystemVersion >= 9)
#endif
|
MichaelHuyp/YPCommon
|
对YYCategories的学习/对YYCategories的学习/YYCategories/UIKit/UIDevice+YYAdd.h
|
C
|
mit
| 4,457 |
<!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 (1.8.0_101) on Wed Sep 21 04:14:05 CEST 2016 -->
<title>com.snakybo.torch.graphics.shader (Torch Engine 1.0 API)</title>
<meta name="date" content="2016-09-21">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="com.snakybo.torch.graphics.shader (Torch Engine 1.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/snakybo/torch/graphics/renderer/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../com/snakybo/torch/graphics/texture/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/snakybo/torch/graphics/shader/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.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>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package com.snakybo.torch.graphics.shader</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../com/snakybo/torch/graphics/shader/Shader.html" title="class in com.snakybo.torch.graphics.shader">Shader</a></td>
<td class="colLast">
<div class="block">
The shader class is a direct link to the low-level GLSL shaders.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../com/snakybo/torch/graphics/shader/ShaderInternal.html" title="class in com.snakybo.torch.graphics.shader">ShaderInternal</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/snakybo/torch/graphics/renderer/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../com/snakybo/torch/graphics/texture/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/snakybo/torch/graphics/shader/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.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>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
Snakybo/SEngine2
|
docs/com/snakybo/torch/graphics/shader/package-summary.html
|
HTML
|
mit
| 5,293 |
define('controllers/panel',['require','jquery','backbone','utils/metrics','utils/browser','utils/video-player','utils/pubsub','controllers/panel-display'],function(require) {
var $ = require('jquery'),
Backbone = require('backbone'),
Metrics = require('utils/metrics'),
Browser = require('utils/browser'),
VideoPlayer = require('utils/video-player'),
PubSub = require('utils/pubsub'),
PanelDisplay = require('controllers/panel-display')
;
var PanelView = Backbone.View.extend({
events: {
},
panelOn: false,
minWidth: 320,
minHeight: 180,
leftLimit: 100,
topLimit: 100,
offset: 10,
border: 5,
initialize: function() {
Browser.checkMobileTabletDevice();
this.logger = new eventsCore.util.Logger('PanelView');
this.panel1 = new PanelDisplay({el: '#panel1'}).render();
this.panel2 = new PanelDisplay({el: '#panel2'}).render();
//this.logger.info('initialize - panel1:%o panel2:%o', this.panel1, this.panel2);
this.on('route:change', this.checkPage);
this.listenTo(PubSub, 'video:playPanel', this.onPlayPanel);
this.listenTo(PubSub, 'video:exitPanel', this.onExitPanel);
this.listenTo(PubSub, 'video:resetHero', this.onResetHero);
this.listenTo(PubSub, 'video:resetVod', this.onResetVod);
this.listenTo(VideoPlayer, 'player:play', this.onPlayEvent);
this.listenTo(VideoPlayer, 'player:panelOpen', this.onPanelOpenEvent);
this.listenTo(VideoPlayer, 'player:panelClosed', this.onPanelClosedEvent);
},
render: function() {
return this;
},
/**
* checks state/position of each panel and updates initial mute status
* executes on play and route change
*/
checkVolume: function() {
this.logger.info('checkVolume - panel1:%o panel2:%o', this.panel1.state(), this.panel2.state());
if (this.panel1.state() != '' && this.panel2.state() == '') {
this.panel1.mute(false);
this.panel2.mute(true);
}
else if (this.panel2.state() != '' && this.panel1.state() == '') {
this.panel2.mute(false);
this.panel1.mute(true);
}
else if (this.panel1.state() == 'floatVideo' && this.panel2.state() == 'heroVideo') {
this.panel2.mute(false);
this.panel1.mute(true);
}
else if (this.panel1.state() == 'heroVideo' && this.panel2.state() == 'floatVideo') {
this.panel1.mute(false);
this.panel2.mute(true);
}
},
/**
* close any open hero panel
* - used for mobile internal ref to a different watch live channel
*/
onResetHero: function() {
if(this.panel1.state() === 'heroVideo') {
this.panel1.onPanelExit();
} else if(this.panel2.state() === 'heroVideo') {
this.panel2.onPanelExit();
}
},
/**
* close any open vod floated panel
*/
onResetVod: function() {
if(this.panel1.state() === 'floatVideo') {
this.panel1.onPanelExit();
} else if(this.panel2.state() === 'floatVideo') {
this.panel2.onPanelExit();
}
},
/**
* play video in a panel, check for channel existing in panel first and use existing if playing
* @param data - panel video data
* @param channel - this live video data
* @param options - options to be passed to video player, consisting of:
* floated - optional boolean indicating if should start in float mode
* vod - indicates if playing a vod
*/
onPlayPanel: function(data, channel, options) {
options = _.extend({ floated: false, vod: false }, options);
this.logger.info('onPlayPanel - panel1:%o chan1:%o panel2:%o chan2:%o data:%o', this.panel1.state(), this.panel1.channelId(), this.panel2.state(), this.panel2.channelId(), data);
//if panel1 floating and opening the same channel, close to hero (to force back to hero when return to live channel page)
// do not close if float is true, call is trying to open same channel in already open float panel
if (this.panel1.channelId() == data[0].id) {
// if panel has no state, reset it to play channel
if(this.panel1.state() === '') {
this.panel1.playPanel(data, channel, options);
} else if (this.panel1.state() == 'floatVideo' && !options.floated)
this.panel1.panelClose(data, false);
else
this.logger.warn('onPlayPanel - ignoring call, attempted to open same channel already active');
}
//if panel2 floating and opening the same channel, close to hero (to force back to hero when return to live channel page)
// do not close if float is true, call i trying to open same channel in already open float panel
else if (this.panel2.channelId() == data[0].id){
// if panel has no state, reset it to play channel
if(this.panel2.state() === '') {
this.panel2.playPanel(data, channel, options);
} else if (this.panel2.state() == 'floatVideo' && !options.floated)
this.panel2.panelClose(data, false);
else
this.logger.warn('onPlayPanel - ignoring call, attempted to open same channel to floating panel');
}
//if panel1 in hero use it, (if not playing this channel)
else if ((this.panel1.state() == 'heroVideo' || this.panel1.state() == '') && this.panel1.channelId() != data[0].id) {
this.panel1.playPanel(data, channel, options);
}
//else use panel2 (if not playing this channel)
else if (this.panel2.channelId() != data[0].id){
this.panel2.playPanel(data, channel, options);
}
},
/**
* exit video playing in panel, whichever panel is open
*/
onExitPanel: function() {
this.logger.info('onExitPanel - panel1:%o chan1:%o panel2:%o chan2:%o', this.panel1.state(), this.panel1.channelId(), this.panel2.state(), this.panel2.channelId());
// close whichever one is floated
if(this.panel1.state() === 'floatVideo') {
this.panel1.onPanelExit();
} else if(this.panel2.state() === 'floatVideo') {
this.panel2.onPanelExit();
}
},
/**
* on play, initiates check for setting initial mute
* @param data - event data with panel id
*/
onPlayEvent: function(data) {
//this.logger.info('onPlayEvent - data:%o', data.id);
if (data.id == 'panel1' || data.id == 'panel2')
this.checkVolume();
},
/**
* handle panel open event from video player
* triggers panel to transition to float state
* @param data - event data with panel id
*/
onPanelOpenEvent: function(data) {
this.logger.info('onPanelOpenEvent - panel1:%o panel2:%o id:%o', this.panel1.state(), this.panel2.state(), data.id);
if(data.id == 'panel1') {
if (this.panel2.state() == 'floatVideo') {
this.panel2.panelClose(null, false);
}
this.panel1.panelOpen();
}
else if(data.id == 'panel2') {
if (this.panel1.state() == 'floatVideo') {
this.panel1.panelClose(null, false);
}
this.panel2.panelOpen();
}
},
/**
* handle panel close event from video player
* triggers panel to return to hero state
* @param data - event data with panel id
*/
onPanelClosedEvent: function(data) {
this.logger.info('onPanelClosedEvent - panel1:%o panel2:%o id:%o', this.panel1.state(), this.panel2.state(), data.id);
if(data.id == 'panel1') {
this.panel1.panelClose(data, true);
if (this.panel2.state() == 'heroVideo') {
this.panel2.panelClose(data, false);
this.checkVolume();
}
}
else if(data.id == 'panel2') {
this.panel2.panelClose(data, true);
if (this.panel1.state() == 'heroVideo') {
this.panel1.panelClose(data, false);
this.checkVolume();
}
}
},
/**
* initiate page check for closing hero on route change
* also check volume on route change
*/
checkPage: function(){
var route = Backbone.history.getFragment();
this.panel1.checkPage(route);
this.panel2.checkPage(route);
this.checkVolume();
}
});
return PanelView;
})
;
|
rlaj/tmc
|
source/dist/controllers/panel.js
|
JavaScript
|
mit
| 9,409 |
// Design Basic Game Solo Challenge
// This is a solo challenge
// Your mission description:To complete a line of the same figure, horizontal, diagonal or vertical
// Overall mission: To win all the time :)
// Goals: make a line of the same kind before computer does
// Characters:You and the computer
// Objects:tic tac toe
// Functions:clear_board, refresh_board, turn
// Pseudocode
// Make a Tictactoe class
// Initialize the instance
// Paint the board
// Take a turn UNTIL someones win
// Check if some one won
// Clear the board
//
//
//
//
// Initial Code
turns = 0
board_state = [[" "," "," "],
[" "," "," "],
[" "," "," "]];
var Tictactoe = {
take_turn : function(user){
mark = prompt("It is your turn, where do you want to mark?");
horizontal = mark[1];
vertical = mark[0].toUpperCase();
if (vertical == "A"){
vertical = 0
} else if (vertical == "B"){
vertical = 1
} else {
vertical = 2
}
board_state[horizontal-1][vertical] = user
console.log(board_state)
},
print_board : function(){
line = ""
console.log(" A B C")
for (i in board_state){
new_line = "\n ═══╬═══╬═══\n"
for (x in board_state[i]){
ln = parseInt(i);
if (x == 0){line = (ln+1)+" "}
if (x == 2) {
if (i == 2){new_line = "\n"}
line += " "+board_state[i][x]+new_line;
} else {
line += " "+board_state[i][x]+" ║"
}
}
console.log(line);
}
}
}
alert ("Welcome to @cyberpolin's Tic Tac Toe\n So it is the turn of User 1, please select where you want to mark...")
Tictactoe.print_board()
while (turns < 9){
if (turns%2 == 0){
Tictactoe.take_turn("o");
} else {
Tictactoe.take_turn("x");
}
Tictactoe.print_board();
turns++;
}
// RELECTION
// What was the most difficult part of this challenge?
// Order my toughts to make the code works as i wannted, also as javascript is not a language thinked for terminal it was difficult to figure out how it was going to work.
// What did you learn about creating objects and functions that interact with one another?
// Is like in ruby, i think of them as just methods
// Did you learn about any new built-in methods you could use in your refactored solution? If so, what were they and how do they work?
// The only one i used was toUpperCase, ad they are like Ruby methods even tough Javascript have a different syntax.
// How can you access and manipulate properties of objects?
// like in Ruby object[property] = new_value, or the JS way object.property = new_value
// TODO'S
// Check if a place is marked already
// Check if you have winned
// Make it playable with computer
// MAKE IT GRAPHICAL!!!!
|
cyberpolin/Phase-0
|
week-7/tictactoe-game/game.js
|
JavaScript
|
mit
| 2,853 |
from django.conf import settings
from django.conf.urls.defaults import patterns, url
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from django.core.urlresolvers import NoReverseMatch, reverse, resolve, Resolver404
from django.db.models.sql.constants import QUERY_TERMS, LOOKUP_SEP
from django.http import HttpResponse
from django.utils.cache import patch_cache_control
from tastypie.authentication import Authentication
from tastypie.authorization import ReadOnlyAuthorization
from tastypie.bundle import Bundle
from tastypie.cache import NoCache
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from tastypie.exceptions import NotFound, BadRequest, InvalidFilterError, HydrationError, InvalidSortError, ImmediateHttpResponse
from tastypie.fields import *
from tastypie.http import *
from tastypie.paginator import Paginator
from tastypie.serializers import Serializer
from tastypie.throttle import BaseThrottle
from tastypie.utils import is_valid_jsonp_callback_value, dict_strip_unicode_keys, trailing_slash
from tastypie.utils.mime import determine_format, build_content_type
from tastypie.validation import Validation
try:
set
except NameError:
from sets import Set as set
# The ``copy`` module was added in Python 2.5 and ``copycompat`` was added in
# post 1.1.1 Django (r11901)
try:
from django.utils.copycompat import deepcopy
from django.views.decorators.csrf import csrf_exempt
except ImportError:
from copy import deepcopy
def csrf_exempt(func):
return func
class ResourceOptions(object):
"""
A configuration class for ``Resource``.
Provides sane defaults and the logic needed to augment these settings with
the internal ``class Meta`` used on ``Resource`` subclasses.
"""
serializer = Serializer()
authentication = Authentication()
authorization = ReadOnlyAuthorization()
cache = NoCache()
throttle = BaseThrottle()
validation = Validation()
allowed_methods = ['get', 'post', 'put', 'delete']
list_allowed_methods = None
detail_allowed_methods = None
limit = getattr(settings, 'API_LIMIT_PER_PAGE', 20)
api_name = None
resource_name = None
urlconf_namespace = None
default_format = 'application/json'
filtering = {}
ordering = []
object_class = None
queryset = None
fields = []
excludes = []
include_resource_uri = True
include_absolute_url = False
def __new__(cls, meta=None):
overrides = {}
# Handle overrides.
if meta:
for override_name in dir(meta):
# No internals please.
if not override_name.startswith('_'):
overrides[override_name] = getattr(meta, override_name)
allowed_methods = overrides.get('allowed_methods', ['get', 'post', 'put', 'delete'])
if overrides.get('list_allowed_methods', None) is None:
overrides['list_allowed_methods'] = allowed_methods
if overrides.get('detail_allowed_methods', None) is None:
overrides['detail_allowed_methods'] = allowed_methods
if not overrides.get('queryset', None) is None:
overrides['object_class'] = overrides['queryset'].model
return object.__new__(type('ResourceOptions', (cls,), overrides))
class DeclarativeMetaclass(type):
def __new__(cls, name, bases, attrs):
attrs['base_fields'] = {}
declared_fields = {}
# Inherit any fields from parent(s).
try:
parents = [b for b in bases if issubclass(b, Resource)]
for p in parents:
fields = getattr(p, 'base_fields', {})
for field_name, field_object in fields.items():
attrs['base_fields'][field_name] = deepcopy(field_object)
except NameError:
pass
for field_name, obj in attrs.items():
if isinstance(obj, ApiField):
field = attrs.pop(field_name)
declared_fields[field_name] = field
attrs['base_fields'].update(declared_fields)
attrs['declared_fields'] = declared_fields
new_class = super(DeclarativeMetaclass, cls).__new__(cls, name, bases, attrs)
opts = getattr(new_class, 'Meta', None)
new_class._meta = ResourceOptions(opts)
if not getattr(new_class._meta, 'resource_name', None):
# No ``resource_name`` provided. Attempt to auto-name the resource.
class_name = new_class.__name__
name_bits = [bit for bit in class_name.split('Resource') if bit]
resource_name = ''.join(name_bits).lower()
new_class._meta.resource_name = resource_name
if getattr(new_class._meta, 'include_resource_uri', True):
if not 'resource_uri' in new_class.base_fields:
new_class.base_fields['resource_uri'] = CharField(readonly=True)
elif 'resource_uri' in new_class.base_fields and not 'resource_uri' in attrs:
del(new_class.base_fields['resource_uri'])
for field_name, field_object in new_class.base_fields.items():
if hasattr(field_object, 'contribute_to_class'):
field_object.contribute_to_class(new_class, field_name)
return new_class
class Resource(object):
"""
Handles the data, request dispatch and responding to requests.
Serialization/deserialization is handled "at the edges" (i.e. at the
beginning/end of the request/response cycle) so that everything internally
is Python data structures.
This class tries to be non-model specific, so it can be hooked up to other
data sources, such as search results, files, other data, etc.
"""
__metaclass__ = DeclarativeMetaclass
def __init__(self, api_name=None):
self.fields = deepcopy(self.base_fields)
if not api_name is None:
self._meta.api_name = api_name
def __getattr__(self, name):
if name in self.fields:
return self.fields[name]
def wrap_view(self, view):
"""
Wraps methods so they can be called in a more functional way as well
as handling exceptions better.
Note that if ``BadRequest`` or an exception with a ``response`` attr
are seen, there is special handling to either present a message back
to the user or return the response traveling with the exception.
"""
@csrf_exempt
def wrapper(request, *args, **kwargs):
try:
callback = getattr(self, view)
response = callback(request, *args, **kwargs)
if request.is_ajax():
# IE excessively caches XMLHttpRequests, so we're disabling
# the browser cache here.
# See http://www.enhanceie.com/ie/bugs.asp for details.
patch_cache_control(response, no_cache=True)
return response
except (BadRequest, ApiFieldError), e:
return HttpBadRequest(e.args[0])
except Exception, e:
if hasattr(e, 'response'):
return e.response
# A real, non-expected exception.
# Handle the case where the full traceback is more helpful
# than the serialized error.
if settings.DEBUG and getattr(settings, 'TASTYPIE_FULL_DEBUG', False):
raise
# Rather than re-raising, we're going to things similar to
# what Django does. The difference is returning a serialized
# error message.
return self._handle_500(request, e)
return wrapper
def _handle_500(self, request, exception):
import traceback
import sys
the_trace = '\n'.join(traceback.format_exception(*(sys.exc_info())))
if settings.DEBUG:
data = {
"error_message": exception.message,
"traceback": the_trace,
}
desired_format = self.determine_format(request)
serialized = self.serialize(request, data, desired_format)
return HttpApplicationError(content=serialized, content_type=build_content_type(desired_format))
# When DEBUG is False, send an error message to the admins.
from django.core.mail import mail_admins
subject = 'Error (%s IP): %s' % ((request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL'), request.path)
try:
request_repr = repr(request)
except:
request_repr = "Request repr() unavailable"
message = "%s\n\n%s" % (the_trace, request_repr)
mail_admins(subject, message, fail_silently=True)
# Prep the data going out.
data = {
"error_message": getattr(settings, 'TASTYPIE_CANNED_ERROR', "Sorry, this request could not be processed. Please try again later."),
}
desired_format = self.determine_format(request)
serialized = self.serialize(request, data, desired_format)
return HttpApplicationError(content=serialized, content_type=build_content_type(desired_format))
def _build_reverse_url(self, name, args=None, kwargs=None):
"""
A convenience hook for overriding how URLs are built.
See ``NamespacedModelResource._build_reverse_url`` for an example.
"""
return reverse(name, args=args, kwargs=kwargs)
def base_urls(self):
"""
The standard URLs this ``Resource`` should respond to.
"""
# Due to the way Django parses URLs, ``get_multiple`` won't work without
# a trailing slash.
return [
url(r"^(?P<resource_name>%s)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('dispatch_list'), name="api_dispatch_list"),
url(r"^(?P<resource_name>%s)/schema%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_schema'), name="api_get_schema"),
url(r"^(?P<resource_name>%s)/set/(?P<pk_list>\w[\w/;-]*)/$" % self._meta.resource_name, self.wrap_view('get_multiple'), name="api_get_multiple"),
url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
]
def override_urls(self):
"""
A hook for adding your own URLs or overriding the default URLs.
"""
return []
@property
def urls(self):
"""
The endpoints this ``Resource`` responds to.
Mostly a standard URLconf, this is suitable for either automatic use
when registered with an ``Api`` class or for including directly in
a URLconf should you choose to.
"""
urls = self.override_urls() + self.base_urls()
urlpatterns = patterns('',
*urls
)
return urlpatterns
def determine_format(self, request):
"""
Used to determine the desired format.
Largely relies on ``tastypie.utils.mime.determine_format`` but here
as a point of extension.
"""
return determine_format(request, self._meta.serializer, default_format=self._meta.default_format)
def serialize(self, request, data, format, options=None):
"""
Given a request, data and a desired format, produces a serialized
version suitable for transfer over the wire.
Mostly a hook, this uses the ``Serializer`` from ``Resource._meta``.
"""
options = options or {}
if 'text/javascript' in format:
# get JSONP callback name. default to "callback"
callback = request.GET.get('callback', 'callback')
if not is_valid_jsonp_callback_value(callback):
raise BadRequest('JSONP callback name is invalid.')
options['callback'] = callback
return self._meta.serializer.serialize(data, format, options)
def deserialize(self, request, data, format='application/json'):
"""
Given a request, data and a format, deserializes the given data.
It relies on the request properly sending a ``CONTENT_TYPE`` header,
falling back to ``application/json`` if not provided.
Mostly a hook, this uses the ``Serializer`` from ``Resource._meta``.
"""
return self._meta.serializer.deserialize(data, format=request.META.get('CONTENT_TYPE', 'application/json'))
def dispatch_list(self, request, **kwargs):
"""
A view for handling the various HTTP methods (GET/POST/PUT/DELETE) over
the entire list of resources.
Relies on ``Resource.dispatch`` for the heavy-lifting.
"""
return self.dispatch('list', request, **kwargs)
def dispatch_detail(self, request, **kwargs):
"""
A view for handling the various HTTP methods (GET/POST/PUT/DELETE) on
a single resource.
Relies on ``Resource.dispatch`` for the heavy-lifting.
"""
return self.dispatch('detail', request, **kwargs)
def dispatch(self, request_type, request, **kwargs):
"""
Handles the common operations (allowed HTTP method, authentication,
throttling, method lookup) surrounding most CRUD interactions.
"""
allowed_methods = getattr(self._meta, "%s_allowed_methods" % request_type, None)
request_method = self.method_check(request, allowed=allowed_methods)
method = getattr(self, "%s_%s" % (request_method, request_type), None)
if method is None:
raise ImmediateHttpResponse(response=HttpNotImplemented())
self.is_authenticated(request)
self.is_authorized(request)
self.throttle_check(request)
# All clear. Process the request.
request = convert_post_to_put(request)
response = method(request, **kwargs)
# Add the throttled request.
self.log_throttled_access(request)
# If what comes back isn't a ``HttpResponse``, assume that the
# request was accepted and that some action occurred. This also
# prevents Django from freaking out.
if not isinstance(response, HttpResponse):
return HttpAccepted()
return response
def remove_api_resource_names(self, url_dict):
"""
Given a dictionary of regex matches from a URLconf, removes
``api_name`` and/or ``resource_name`` if found.
This is useful for converting URLconf matches into something suitable
for data lookup. For example::
Model.objects.filter(**self.remove_api_resource_names(matches))
"""
kwargs_subset = url_dict.copy()
for key in ['api_name', 'resource_name']:
try:
del(kwargs_subset[key])
except KeyError:
pass
return kwargs_subset
def method_check(self, request, allowed=None):
"""
Ensures that the HTTP method used on the request is allowed to be
handled by the resource.
Takes an ``allowed`` parameter, which should be a list of lowercase
HTTP methods to check against. Usually, this looks like::
# The most generic lookup.
self.method_check(request, self._meta.allowed_methods)
# A lookup against what's allowed for list-type methods.
self.method_check(request, self._meta.list_allowed_methods)
# A useful check when creating a new endpoint that only handles
# GET.
self.method_check(request, ['get'])
"""
if allowed is None:
allowed = []
request_method = request.method.lower()
if not request_method in allowed:
raise ImmediateHttpResponse(response=HttpMethodNotAllowed())
return request_method
def is_authorized(self, request, object=None):
"""
Handles checking of permissions to see if the user has authorization
to GET, POST, PUT, or DELETE this resource. If ``object`` is provided,
the authorization backend can apply additional row-level permissions
checking.
"""
auth_result = self._meta.authorization.is_authorized(request, object)
if isinstance(auth_result, HttpResponse):
raise ImmediateHttpResponse(response=auth_result)
if not auth_result is True:
raise ImmediateHttpResponse(response=HttpUnauthorized())
def is_authenticated(self, request):
"""
Handles checking if the user is authenticated and dealing with
unauthenticated users.
Mostly a hook, this uses class assigned to ``authentication`` from
``Resource._meta``.
"""
# Authenticate the request as needed.
auth_result = self._meta.authentication.is_authenticated(request)
if isinstance(auth_result, HttpResponse):
raise ImmediateHttpResponse(response=auth_result)
if not auth_result is True:
raise ImmediateHttpResponse(response=HttpUnauthorized())
def throttle_check(self, request):
"""
Handles checking if the user should be throttled.
Mostly a hook, this uses class assigned to ``throttle`` from
``Resource._meta``.
"""
identifier = self._meta.authentication.get_identifier(request)
# Check to see if they should be throttled.
if self._meta.throttle.should_be_throttled(identifier):
# Throttle limit exceeded.
raise ImmediateHttpResponse(response=HttpForbidden())
def log_throttled_access(self, request):
"""
Handles the recording of the user's access for throttling purposes.
Mostly a hook, this uses class assigned to ``throttle`` from
``Resource._meta``.
"""
request_method = request.method.lower()
self._meta.throttle.accessed(self._meta.authentication.get_identifier(request), url=request.get_full_path(), request_method=request_method)
def build_bundle(self, obj=None, data=None):
"""
Given either an object, a data dictionary or both, builds a ``Bundle``
for use throughout the ``dehydrate/hydrate`` cycle.
If no object is provided, an empty object from
``Resource._meta.object_class`` is created so that attempts to access
``bundle.obj`` do not fail.
"""
if obj is None:
obj = self._meta.object_class()
return Bundle(obj, data)
def build_filters(self, filters=None):
"""
Allows for the filtering of applicable objects.
This needs to be implemented at the user level.'
``ModelResource`` includes a full working version specific to Django's
``Models``.
"""
return filters
def apply_sorting(self, obj_list, options=None):
"""
Allows for the sorting of objects being returned.
This needs to be implemented at the user level.
``ModelResource`` includes a full working version specific to Django's
``Models``.
"""
return obj_list
# URL-related methods.
def get_resource_uri(self, bundle_or_obj):
"""
This needs to be implemented at the user level.
A ``return reverse("api_dispatch_detail", kwargs={'resource_name':
self.resource_name, 'pk': object.id})`` should be all that would
be needed.
``ModelResource`` includes a full working version specific to Django's
``Models``.
"""
raise NotImplementedError()
def get_resource_list_uri(self):
"""
Returns a URL specific to this resource's list endpoint.
"""
kwargs = {
'resource_name': self._meta.resource_name,
}
if self._meta.api_name is not None:
kwargs['api_name'] = self._meta.api_name
try:
return self._build_reverse_url("api_dispatch_list", kwargs=kwargs)
except NoReverseMatch:
return None
def get_via_uri(self, uri):
"""
This pulls apart the salient bits of the URI and populates the
resource via a ``obj_get``.
If you need custom behavior based on other portions of the URI,
simply override this method.
"""
try:
view, args, kwargs = resolve(uri)
except Resolver404:
raise NotFound("The URL provided '%s' was not a link to a valid resource." % uri)
return self.obj_get(**self.remove_api_resource_names(kwargs))
# Data preparation.
def full_dehydrate(self, obj):
"""
Given an object instance, extract the information from it to populate
the resource.
"""
bundle = Bundle(obj=obj)
# Dehydrate each field.
for field_name, field_object in self.fields.items():
# A touch leaky but it makes URI resolution work.
if isinstance(field_object, RelatedField):
field_object.api_name = self._meta.api_name
field_object.resource_name = self._meta.resource_name
bundle.data[field_name] = field_object.dehydrate(bundle)
# Check for an optional method to do further dehydration.
method = getattr(self, "dehydrate_%s" % field_name, None)
if method:
bundle.data[field_name] = method(bundle)
bundle = self.dehydrate(bundle)
return bundle
def dehydrate(self, bundle):
"""
A hook to allow a final manipulation of data once all fields/methods
have built out the dehydrated data.
Useful if you need to access more than one dehydrated field or want
to annotate on additional data.
Must return the modified bundle.
"""
return bundle
def full_hydrate(self, bundle):
"""
Given a populated bundle, distill it and turn it back into
a full-fledged object instance.
"""
if bundle.obj is None:
bundle.obj = self._meta.object_class()
for field_name, field_object in self.fields.items():
if field_object.attribute:
value = field_object.hydrate(bundle)
if value is not None:
# We need to avoid populating M2M data here as that will
# cause things to blow up.
if not getattr(field_object, 'is_related', False):
setattr(bundle.obj, field_object.attribute, value)
elif not getattr(field_object, 'is_m2m', False):
setattr(bundle.obj, field_object.attribute, value.obj)
# Check for an optional method to do further hydration.
method = getattr(self, "hydrate_%s" % field_name, None)
if method:
bundle = method(bundle)
bundle = self.hydrate(bundle)
return bundle
def hydrate(self, bundle):
"""
A hook to allow a final manipulation of data once all fields/methods
have built out the hydrated data.
Useful if you need to access more than one hydrated field or want
to annotate on additional data.
Must return the modified bundle.
"""
return bundle
def hydrate_m2m(self, bundle):
"""
Populate the ManyToMany data on the instance.
"""
if bundle.obj is None:
raise HydrationError("You must call 'full_hydrate' before attempting to run 'hydrate_m2m' on %r." % self)
for field_name, field_object in self.fields.items():
if not getattr(field_object, 'is_m2m', False):
continue
if field_object.attribute:
# Note that we only hydrate the data, leaving the instance
# unmodified. It's up to the user's code to handle this.
# The ``ModelResource`` provides a working baseline
# in this regard.
bundle.data[field_name] = field_object.hydrate_m2m(bundle)
for field_name, field_object in self.fields.items():
if not getattr(field_object, 'is_m2m', False):
continue
method = getattr(self, "hydrate_%s" % field_name, None)
if method:
method(bundle)
return bundle
def build_schema(self):
"""
Returns a dictionary of all the fields on the resource and some
properties about those fields.
Used by the ``schema/`` endpoint to describe what will be available.
"""
data = {
'fields': {},
'default_format': self._meta.default_format,
}
if self._meta.ordering:
data['ordering'] = self._meta.ordering
if self._meta.filtering:
data['filtering'] = self._meta.filtering
for field_name, field_object in self.fields.items():
data['fields'][field_name] = {
'type': field_object.dehydrated_type,
'nullable': field_object.null,
'readonly': field_object.readonly,
'help_text': field_object.help_text,
}
return data
def dehydrate_resource_uri(self, bundle):
"""
For the automatically included ``resource_uri`` field, dehydrate
the URI for the given bundle.
Returns empty string if no URI can be generated.
"""
try:
return self.get_resource_uri(bundle)
except NotImplementedError:
return ''
except NoReverseMatch:
return ''
def generate_cache_key(self, *args, **kwargs):
"""
Creates a unique-enough cache key.
This is based off the current api_name/resource_name/args/kwargs.
"""
smooshed = []
for key, value in kwargs.items():
smooshed.append("%s=%s" % (key, value))
# Use a list plus a ``.join()`` because it's faster than concatenation.
return "%s:%s:%s:%s" % (self._meta.api_name, self._meta.resource_name, ':'.join(args), ':'.join(smooshed))
# Data access methods.
def get_object_list(self, request):
"""
A hook to allow making returning the list of available objects.
This needs to be implemented at the user level.
``ModelResource`` includes a full working version specific to Django's
``Models``.
"""
raise NotImplementedError()
def apply_authorization_limits(self, request, object_list):
"""
Allows the ``Authorization`` class to further limit the object list.
Also a hook to customize per ``Resource``.
"""
if hasattr(self._meta.authorization, 'apply_limits'):
object_list = self._meta.authorization.apply_limits(request, object_list)
return object_list
def obj_get_list(self, request=None, **kwargs):
"""
Fetches the list of objects available on the resource.
This needs to be implemented at the user level.
``ModelResource`` includes a full working version specific to Django's
``Models``.
"""
raise NotImplementedError()
def cached_obj_get_list(self, request=None, **kwargs):
"""
A version of ``obj_get_list`` that uses the cache as a means to get
commonly-accessed data faster.
"""
cache_key = self.generate_cache_key('list', **kwargs)
obj_list = self._meta.cache.get(cache_key)
if obj_list is None:
obj_list = self.obj_get_list(request=request, **kwargs)
self._meta.cache.set(cache_key, obj_list)
return obj_list
def obj_get(self, request=None, **kwargs):
"""
Fetches an individual object on the resource.
This needs to be implemented at the user level. If the object can not
be found, this should raise a ``NotFound`` exception.
``ModelResource`` includes a full working version specific to Django's
``Models``.
"""
raise NotImplementedError()
def cached_obj_get(self, request=None, **kwargs):
"""
A version of ``obj_get`` that uses the cache as a means to get
commonly-accessed data faster.
"""
cache_key = self.generate_cache_key('detail', **kwargs)
bundle = self._meta.cache.get(cache_key)
if bundle is None:
bundle = self.obj_get(request=request, **kwargs)
self._meta.cache.set(cache_key, bundle)
return bundle
def obj_create(self, bundle, request=None, **kwargs):
"""
Creates a new object based on the provided data.
This needs to be implemented at the user level.
``ModelResource`` includes a full working version specific to Django's
``Models``.
"""
raise NotImplementedError()
def obj_update(self, bundle, request=None, **kwargs):
"""
Updates an existing object (or creates a new object) based on the
provided data.
This needs to be implemented at the user level.
``ModelResource`` includes a full working version specific to Django's
``Models``.
"""
raise NotImplementedError()
def obj_delete_list(self, request=None, **kwargs):
"""
Deletes an entire list of objects.
This needs to be implemented at the user level.
``ModelResource`` includes a full working version specific to Django's
``Models``.
"""
raise NotImplementedError()
def obj_delete(self, request=None, **kwargs):
"""
Deletes a single object.
This needs to be implemented at the user level.
``ModelResource`` includes a full working version specific to Django's
``Models``.
"""
raise NotImplementedError()
def create_response(self, request, data):
"""
Extracts the common "which-format/serialize/return-response" cycle.
Mostly a useful shortcut/hook.
"""
desired_format = self.determine_format(request)
serialized = self.serialize(request, data, desired_format)
return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
def is_valid(self, bundle, request=None):
"""
Handles checking if the data provided by the user is valid.
Mostly a hook, this uses class assigned to ``validation`` from
``Resource._meta``.
If validation fails, an error is raised with the error messages
serialized inside it.
"""
errors = self._meta.validation.is_valid(bundle, request)
if len(errors):
if request:
desired_format = self.determine_format(request)
else:
desired_format = self._meta.default_format
serialized = self.serialize(request, errors, desired_format)
response = HttpBadRequest(content=serialized, content_type=build_content_type(desired_format))
raise ImmediateHttpResponse(response=response)
def rollback(self, bundles):
"""
Given the list of bundles, delete all objects pertaining to those
bundles.
This needs to be implemented at the user level. No exceptions should
be raised if possible.
``ModelResource`` includes a full working version specific to Django's
``Models``.
"""
raise NotImplementedError()
# Views.
def get_list(self, request, **kwargs):
"""
Returns a serialized list of resources.
Calls ``obj_get_list`` to provide the data, then handles that result
set and serializes it.
Should return a HttpResponse (200 OK).
"""
# TODO: Uncached for now. Invalidation that works for everyone may be
# impossible.
objects = self.obj_get_list(request=request, **self.remove_api_resource_names(kwargs))
sorted_objects = self.apply_sorting(objects, options=request.GET)
paginator = Paginator(request.GET, sorted_objects, resource_uri=self.get_resource_list_uri(),
limit=self._meta.limit)
to_be_serialized = paginator.page()
# Dehydrate the bundles in preparation for serialization.
to_be_serialized['objects'] = [self.full_dehydrate(obj=obj) for obj in to_be_serialized['objects']]
return self.create_response(request, to_be_serialized)
def get_detail(self, request, **kwargs):
"""
Returns a single serialized resource.
Calls ``cached_obj_get/obj_get`` to provide the data, then handles that result
set and serializes it.
Should return a HttpResponse (200 OK).
"""
try:
obj = self.cached_obj_get(request=request, **self.remove_api_resource_names(kwargs))
except ObjectDoesNotExist:
return HttpGone()
except MultipleObjectsReturned:
return HttpMultipleChoices("More than one resource is found at this URI.")
bundle = self.full_dehydrate(obj)
return self.create_response(request, bundle)
def put_list(self, request, **kwargs):
"""
Replaces a collection of resources with another collection.
Calls ``delete_list`` to clear out the collection then ``obj_create``
with the provided the data to create the new collection.
Return ``HttpAccepted`` (204 No Content).
"""
deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
if not 'objects' in deserialized:
raise BadRequest("Invalid data sent.")
self.obj_delete_list(request=request, **self.remove_api_resource_names(kwargs))
bundles_seen = []
for object_data in deserialized['objects']:
bundle = self.build_bundle(data=dict_strip_unicode_keys(object_data))
# Attempt to be transactional, deleting any previously created
# objects if validation fails.
try:
self.is_valid(bundle, request)
except ImmediateHttpResponse:
self.rollback(bundles_seen)
raise
self.obj_create(bundle, request=request)
bundles_seen.append(bundle)
return HttpAccepted()
def put_detail(self, request, **kwargs):
"""
Either updates an existing resource or creates a new one with the
provided data.
Calls ``obj_update`` with the provided data first, but falls back to
``obj_create`` if the object does not already exist.
If a new resource is created, return ``HttpCreated`` (201 Created).
If an existing resource is modified, return ``HttpAccepted`` (204 No Content).
"""
deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized))
self.is_valid(bundle, request)
try:
updated_bundle = self.obj_update(bundle, request=request, pk=kwargs.get('pk'))
return HttpAccepted()
except:
updated_bundle = self.obj_create(bundle, request=request, pk=kwargs.get('pk'))
return HttpCreated(location=self.get_resource_uri(updated_bundle))
def post_list(self, request, **kwargs):
"""
Creates a new resource/object with the provided data.
Calls ``obj_create`` with the provided data and returns a response
with the new resource's location.
If a new resource is created, return ``HttpCreated`` (201 Created).
"""
deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized))
self.is_valid(bundle, request)
updated_bundle = self.obj_create(bundle, request=request)
return HttpCreated(location=self.get_resource_uri(updated_bundle))
def post_detail(self, request, **kwargs):
"""
Creates a new subcollection of the resource under a resource.
This is not implemented by default because most people's data models
aren't self-referential.
If a new resource is created, return ``HttpCreated`` (201 Created).
"""
return HttpNotImplemented()
def delete_list(self, request, **kwargs):
"""
Destroys a collection of resources/objects.
Calls ``obj_delete_list``.
If the resources are deleted, return ``HttpAccepted`` (204 No Content).
"""
self.obj_delete_list(request=request, **self.remove_api_resource_names(kwargs))
return HttpAccepted()
def delete_detail(self, request, **kwargs):
"""
Destroys a single resource/object.
Calls ``obj_delete``.
If the resource is deleted, return ``HttpAccepted`` (204 No Content).
If the resource did not exist, return ``HttpGone`` (410 Gone).
"""
try:
self.obj_delete(request=request, **self.remove_api_resource_names(kwargs))
return HttpAccepted()
except NotFound:
return HttpGone()
def get_schema(self, request, **kwargs):
"""
Returns a serialized form of the schema of the resource.
Calls ``build_schema`` to generate the data. This method only responds
to HTTP GET.
Should return a HttpResponse (200 OK).
"""
self.method_check(request, allowed=['get'])
self.is_authenticated(request)
self.throttle_check(request)
self.log_throttled_access(request)
return self.create_response(request, self.build_schema())
def get_multiple(self, request, **kwargs):
"""
Returns a serialized list of resources based on the identifiers
from the URL.
Calls ``obj_get`` to fetch only the objects requested. This method
only responds to HTTP GET.
Should return a HttpResponse (200 OK).
"""
self.method_check(request, allowed=['get'])
self.is_authenticated(request)
self.throttle_check(request)
# Rip apart the list then iterate.
obj_pks = kwargs.get('pk_list', '').split(';')
objects = []
not_found = []
for pk in obj_pks:
try:
obj = self.obj_get(request, pk=pk)
bundle = self.full_dehydrate(obj)
objects.append(bundle)
except ObjectDoesNotExist:
not_found.append(pk)
object_list = {
'objects': objects,
}
if len(not_found):
object_list['not_found'] = not_found
self.log_throttled_access(request)
return self.create_response(request, object_list)
class ModelDeclarativeMetaclass(DeclarativeMetaclass):
def __new__(cls, name, bases, attrs):
new_class = super(ModelDeclarativeMetaclass, cls).__new__(cls, name, bases, attrs)
fields = getattr(new_class._meta, 'fields', [])
excludes = getattr(new_class._meta, 'excludes', [])
field_names = new_class.base_fields.keys()
for field_name in field_names:
if field_name == 'resource_uri':
continue
if field_name in new_class.declared_fields:
continue
if len(fields) and not field_name in fields:
del(new_class.base_fields[field_name])
if len(excludes) and field_name in excludes:
del(new_class.base_fields[field_name])
# Add in the new fields.
new_class.base_fields.update(new_class.get_fields(fields, excludes))
if getattr(new_class._meta, 'include_absolute_url', True):
if not 'absolute_url' in new_class.base_fields:
new_class.base_fields['absolute_url'] = CharField(attribute='get_absolute_url', readonly=True)
elif 'absolute_url' in new_class.base_fields and not 'absolute_url' in attrs:
del(new_class.base_fields['absolute_url'])
return new_class
class ModelResource(Resource):
"""
A subclass of ``Resource`` designed to work with Django's ``Models``.
This class will introspect a given ``Model`` and build a field list based
on the fields found on the model (excluding relational fields).
Given that it is aware of Django's ORM, it also handles the CRUD data
operations of the resource.
"""
__metaclass__ = ModelDeclarativeMetaclass
@classmethod
def should_skip_field(cls, field):
"""
Given a Django model field, return if it should be included in the
contributed ApiFields.
"""
# Ignore certain fields (related fields).
if getattr(field, 'rel'):
return True
return False
@classmethod
def api_field_from_django_field(cls, f, default=CharField):
"""
Returns the field type that would likely be associated with each
Django type.
"""
result = default
if f.get_internal_type() in ('DateField', 'DateTimeField'):
result = DateTimeField
elif f.get_internal_type() in ('BooleanField', 'NullBooleanField'):
result = BooleanField
elif f.get_internal_type() in ('DecimalField', 'FloatField'):
result = FloatField
elif f.get_internal_type() in ('IntegerField', 'PositiveIntegerField', 'PositiveSmallIntegerField', 'SmallIntegerField'):
result = IntegerField
elif f.get_internal_type() in ('FileField', 'ImageField'):
result = FileField
# TODO: Perhaps enable these via introspection. The reason they're not enabled
# by default is the very different ``__init__`` they have over
# the other fields.
# elif f.get_internal_type() == 'ForeignKey':
# result = ForeignKey
# elif f.get_internal_type() == 'ManyToManyField':
# result = ManyToManyField
return result
@classmethod
def get_fields(cls, fields=None, excludes=None):
"""
Given any explicit fields to include and fields to exclude, add
additional fields based on the associated model.
"""
final_fields = {}
fields = fields or []
excludes = excludes or []
if not cls._meta.object_class:
return final_fields
for f in cls._meta.object_class._meta.fields:
# If the field name is already present, skip
if f.name in cls.base_fields:
continue
# If field is not present in explicit field listing, skip
if fields and f.name not in fields:
continue
# If field is in exclude list, skip
if excludes and f.name in excludes:
continue
if cls.should_skip_field(f):
continue
api_field_class = cls.api_field_from_django_field(f)
kwargs = {
'attribute': f.name,
}
if f.null is True:
kwargs['null'] = True
kwargs['unique'] = f.unique
if not f.null and f.blank is True:
kwargs['default'] = ''
if f.get_internal_type() == 'TextField':
kwargs['default'] = ''
if f.has_default():
kwargs['default'] = f.default
final_fields[f.name] = api_field_class(**kwargs)
final_fields[f.name].instance_name = f.name
return final_fields
def build_filters(self, filters=None):
"""
Given a dictionary of filters, create the necessary ORM-level filters.
Keys should be resource fields, **NOT** model fields.
Valid values are either a list of Django filter types (i.e.
``['startswith', 'exact', 'lte']``), the ``ALL`` constant or the
``ALL_WITH_RELATIONS`` constant.
"""
# At the declarative level:
# filtering = {
# 'resource_field_name': ['exact', 'startswith', 'endswith', 'contains'],
# 'resource_field_name_2': ['exact', 'gt', 'gte', 'lt', 'lte', 'range'],
# 'resource_field_name_3': ALL,
# 'resource_field_name_4': ALL_WITH_RELATIONS,
# ...
# }
# Accepts the filters as a dict. None by default, meaning no filters.
if filters is None:
filters = {}
qs_filters = {}
for filter_expr, value in filters.items():
filter_bits = filter_expr.split(LOOKUP_SEP)
if not filter_bits[0] in self.fields:
# It's not a field we know about. Move along citizen.
continue
if not filter_bits[0] in self._meta.filtering:
raise InvalidFilterError("The '%s' field does not allow filtering." % filter_bits[0])
if filter_bits[-1] in QUERY_TERMS.keys():
filter_type = filter_bits.pop()
else:
filter_type = 'exact'
# Check to see if it's allowed lookup type.
if not self._meta.filtering[filter_bits[0]] in (ALL, ALL_WITH_RELATIONS):
# Must be an explicit whitelist.
if not filter_type in self._meta.filtering[filter_bits[0]]:
raise InvalidFilterError("'%s' is not an allowed filter on the '%s' field." % (filter_expr, filter_bits[0]))
# Check to see if it's a relational lookup and if that's allowed.
if len(filter_bits) > 1:
if not self._meta.filtering[filter_bits[0]] == ALL_WITH_RELATIONS:
raise InvalidFilterError("Lookups are not allowed more than one level deep on the '%s' field." % filter_bits[0])
if self.fields[filter_bits[0]].attribute is None:
raise InvalidFilterError("The '%s' field has no 'attribute' for searching with." % filter_bits[0])
if value in ['true', 'True', True]:
value = True
elif value in ['false', 'False', False]:
value = False
elif value in ('nil', 'none', 'None', None):
value = None
db_field_name = LOOKUP_SEP.join([self.fields[filter_bits[0]].attribute] + filter_bits[1:])
qs_filter = "%s%s%s" % (db_field_name, LOOKUP_SEP, filter_type)
qs_filters[qs_filter] = value
return dict_strip_unicode_keys(qs_filters)
def apply_sorting(self, obj_list, options=None):
"""
Given a dictionary of options, apply some ORM-level sorting to the
provided ``QuerySet``.
Looks for the ``sort_by`` key and handles either ascending (just the
field name) or descending (the field name with a ``-`` in front).
The field name should be the resource field, **NOT** model field.
"""
if options is None:
options = {}
if not 'sort_by' in options:
# Nothing to alter the sort order. Return what we've got.
return obj_list
order_by_args = []
if hasattr(options, 'getlist'):
sort_bits = options.getlist('sort_by')
else:
sort_bits = options.get('sort_by')
if not isinstance(sort_bits, (list, tuple)):
sort_bits = [sort_bits]
for sort_by in sort_bits:
sort_by_bits = sort_by.split(LOOKUP_SEP)
field_name = sort_by_bits[0]
order = ''
if sort_by_bits[0].startswith('-'):
field_name = sort_by_bits[0][1:]
order = '-'
if not field_name in self.fields:
# It's not a field we know about. Move along citizen.
raise InvalidSortError("No matching '%s' field for ordering on." % field_name)
if not field_name in self._meta.ordering:
raise InvalidSortError("The '%s' field does not allow ordering." % field_name)
if self.fields[field_name].attribute is None:
raise InvalidSortError("The '%s' field has no 'attribute' for ordering with." % field_name)
order_by_args.append("%s%s" % (order, LOOKUP_SEP.join([self.fields[field_name].attribute] + sort_by_bits[1:])))
return obj_list.order_by(*order_by_args)
def get_object_list(self, request):
"""
An ORM-specific implementation of ``get_object_list``.
Returns a queryset that may have been limited by authorization or other
overrides.
"""
base_object_list = self._meta.queryset
# Limit it as needed.
authed_object_list = self.apply_authorization_limits(request, base_object_list)
return authed_object_list
def obj_get_list(self, request=None, **kwargs):
"""
A ORM-specific implementation of ``obj_get_list``.
Takes an optional ``request`` object, whose ``GET`` dictionary can be
used to narrow the query.
"""
filters = None
if hasattr(request, 'GET'):
filters = request.GET
applicable_filters = self.build_filters(filters=filters)
try:
return self.get_object_list(request).filter(**applicable_filters)
except ValueError, e:
raise NotFound("Invalid resource lookup data provided (mismatched type).")
def obj_get(self, request=None, **kwargs):
"""
A ORM-specific implementation of ``obj_get``.
Takes optional ``kwargs``, which are used to narrow the query to find
the instance.
"""
try:
return self.get_object_list(request).get(**kwargs)
except ValueError, e:
raise NotFound("Invalid resource lookup data provided (mismatched type).")
def obj_create(self, bundle, request=None, **kwargs):
"""
A ORM-specific implementation of ``obj_create``.
"""
bundle.obj = self._meta.object_class()
for key, value in kwargs.items():
setattr(bundle.obj, key, value)
bundle = self.full_hydrate(bundle)
bundle.obj.save()
# Now pick up the M2M bits.
m2m_bundle = self.hydrate_m2m(bundle)
self.save_m2m(m2m_bundle)
return bundle
def obj_update(self, bundle, request=None, **kwargs):
"""
A ORM-specific implementation of ``obj_update``.
"""
if not bundle.obj or not bundle.obj.pk:
# Attempt to hydrate data from kwargs before doing a lookup for the object.
# This step is needed so certain values (like datetime) will pass model validation.
try:
bundle.obj = self.get_object_list(request).model()
bundle.data.update(kwargs)
bundle = self.full_hydrate(bundle)
lookup_kwargs = kwargs.copy()
lookup_kwargs.update(dict(
(k, getattr(bundle.obj, k))
for k in kwargs.keys()
if getattr(bundle.obj, k) is not None))
except:
# if there is trouble hydrating the data, fall back to just
# using kwargs by itself (usually it only contains a "pk" key
# and this will work fine.
lookup_kwargs = kwargs
try:
bundle.obj = self.get_object_list(request).get(**lookup_kwargs)
except ObjectDoesNotExist:
raise NotFound("A model instance matching the provided arguments could not be found.")
bundle = self.full_hydrate(bundle)
bundle.obj.save()
# Now pick up the M2M bits.
m2m_bundle = self.hydrate_m2m(bundle)
self.save_m2m(m2m_bundle)
return bundle
def obj_delete_list(self, request=None, **kwargs):
"""
A ORM-specific implementation of ``obj_delete_list``.
Takes optional ``kwargs``, which can be used to narrow the query.
"""
self.get_object_list(request).filter(**kwargs).delete()
def obj_delete(self, request=None, **kwargs):
"""
A ORM-specific implementation of ``obj_delete``.
Takes optional ``kwargs``, which are used to narrow the query to find
the instance.
"""
try:
obj = self.get_object_list(request).get(**kwargs)
except ObjectDoesNotExist:
raise NotFound("A model instance matching the provided arguments could not be found.")
obj.delete()
def rollback(self, bundles):
"""
A ORM-specific implementation of ``rollback``.
Given the list of bundles, delete all models pertaining to those
bundles.
"""
for bundle in bundles:
if bundle.obj and getattr(bundle.obj, 'pk', None):
bundle.obj.delete()
def save_m2m(self, bundle):
"""
Handles the saving of related M2M data.
Due to the way Django works, the M2M data must be handled after the
main instance, which is why this isn't a part of the main ``save`` bits.
Currently slightly inefficient in that it will clear out the whole
relation and recreate the related data as needed.
"""
for field_name, field_object in self.fields.items():
if not getattr(field_object, 'is_m2m', False):
continue
if not field_object.attribute:
continue
# Get the manager.
related_mngr = getattr(bundle.obj, field_object.attribute)
if hasattr(related_mngr, 'clear'):
# Clear it out, just to be safe.
related_mngr.clear()
related_objs = []
for related_bundle in bundle.data[field_name]:
related_bundle.obj.save()
related_objs.append(related_bundle.obj)
related_mngr.add(*related_objs)
def get_resource_uri(self, bundle_or_obj):
"""
Handles generating a resource URI for a single resource.
Uses the model's ``pk`` in order to create the URI.
"""
kwargs = {
'resource_name': self._meta.resource_name,
}
if isinstance(bundle_or_obj, Bundle):
kwargs['pk'] = bundle_or_obj.obj.pk
else:
kwargs['pk'] = bundle_or_obj.id
if self._meta.api_name is not None:
kwargs['api_name'] = self._meta.api_name
return self._build_reverse_url("api_dispatch_detail", kwargs=kwargs)
class NamespacedModelResource(ModelResource):
"""
A ModelResource subclass that respects Django namespaces.
"""
def _build_reverse_url(self, name, args=None, kwargs=None):
namespaced = "%s:%s" % (self._meta.urlconf_namespace, name)
return reverse(namespaced, args=args, kwargs=kwargs)
# Based off of ``piston.utils.coerce_put_post``. Similarly BSD-licensed.
# And no, the irony is not lost on me.
def convert_post_to_put(request):
"""
Force Django to process the PUT.
"""
if request.method == "PUT":
if hasattr(request, '_post'):
del request._post
del request._files
try:
request.method = "POST"
request._load_post_and_files()
request.method = "PUT"
except AttributeError:
request.META['REQUEST_METHOD'] = 'POST'
request._load_post_and_files()
request.META['REQUEST_METHOD'] = 'PUT'
request.PUT = request.POST
return request
|
colinsullivan/bingo-board
|
bingo_board/tastypie/resources.py
|
Python
|
mit
| 58,556 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Company
{
public partial class Site : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
|
dnmitev/ASPNET-WebForms
|
SiteMaps/Company/Site.Master.cs
|
C#
|
mit
| 315 |
/* Copyright (C) 1986-2001 by Digital Mars. */
#if __SC__ || __RCC__
#pragma once
#endif
#ifndef RC_INVOKED
#pragma pack(__DEFALIGN)
#endif
#include <win32\scdefs.h>
#include <win32\LMCONFIG.H>
#ifndef RC_INVOKED
#pragma pack()
#endif
|
ArcherSys/ArcherSys
|
DCompiler/include/LMCONFIG.H
|
C++
|
mit
| 243 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Dataflow
* @copyright Copyright (c) 2014 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Convert container abstract
*
* @category Mage
* @package Mage_Dataflow
* @author Magento Core Team <[email protected]>
*/
abstract class Mage_Dataflow_Model_Convert_Container_Abstract
implements Mage_Dataflow_Model_Convert_Container_Interface
{
protected $_batchParams = array();
protected $_vars;
protected $_profile;
protected $_action;
protected $_data;
protected $_position;
public function getVar($key, $default=null)
{
if (!isset($this->_vars[$key]) || (!is_array($this->_vars[$key]) && strlen($this->_vars[$key]) == 0)) {
return $default;
}
return $this->_vars[$key];
}
public function getVars()
{
return $this->_vars;
}
public function setVar($key, $value=null)
{
if (is_array($key) && is_null($value)) {
$this->_vars = $key;
} else {
$this->_vars[$key] = $value;
}
return $this;
}
public function getAction()
{
return $this->_action;
}
public function setAction(Mage_Dataflow_Model_Convert_Action_Interface $action)
{
$this->_action = $action;
return $this;
}
public function getProfile()
{
return $this->_profile;
}
public function setProfile(Mage_Dataflow_Model_Convert_Profile_Interface $profile)
{
$this->_profile = $profile;
return $this;
}
public function getData()
{
if (is_null($this->_data) && $this->getProfile()) {
$this->_data = $this->getProfile()->getContainer()->getData();
}
return $this->_data;
}
public function setData($data)
{
if ($this->getProfile()) {
$this->getProfile()->getContainer()->setData($data);
}
$this->_data = $data;
return $this;
}
public function validateDataString($data=null)
{
if (is_null($data)) {
$data = $this->getData();
}
if (!is_string($data)) {
$this->addException("Invalid data type, expecting string.", Mage_Dataflow_Model_Convert_Exception::FATAL);
}
return true;
}
public function validateDataArray($data=null)
{
if (is_null($data)) {
$data = $this->getData();
}
if (!is_array($data)) {
$this->addException("Invalid data type, expecting array.", Mage_Dataflow_Model_Convert_Exception::FATAL);
}
return true;
}
public function validateDataGrid($data=null)
{
if (is_null($data)) {
$data = $this->getData();
}
if (!is_array($data) || !is_array(current($data))) {
if (count($data)==0) {
return true;
}
$this->addException("Invalid data type, expecting 2D grid array.", Mage_Dataflow_Model_Convert_Exception::FATAL);
}
return true;
}
public function getGridFields($grid)
{
$fields = array();
foreach ($grid as $i=>$row) {
foreach ($row as $fieldName=>$data) {
if (!in_array($fieldName, $fields)) {
$fields[] = $fieldName;
}
}
}
return $fields;
}
public function addException($error, $level=null)
{
$e = new Mage_Dataflow_Model_Convert_Exception($error);
$e->setLevel(!is_null($level) ? $level : Mage_Dataflow_Model_Convert_Exception::NOTICE);
$e->setContainer($this);
$e->setPosition($this->getPosition());
if ($this->getProfile()) {
$this->getProfile()->addException($e);
}
return $e;
}
public function getPosition()
{
return $this->_position;
}
public function setPosition($position)
{
$this->_position = $position;
return $this;
}
public function setBatchParams($data)
{
if (is_array($data)) {
$this->_batchParams = $data;
}
return $this;
}
public function getBatchParams($key = null)
{
if (!empty($key)) {
return isset($this->_batchParams[$key]) ? $this->_batchParams[$key] : null;
}
return $this->_batchParams;
}
}
|
almadaocta/lordbike-production
|
errors/includes/src/Mage_Dataflow_Model_Convert_Container_Abstract.php
|
PHP
|
mit
| 5,471 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.monitor;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Part of MultiTenantDiagnosticSettings. Specifies the settings for a
* particular log.
*/
public class LogSettings {
/**
* Name of a Diagnostic Log category for a resource type this setting is
* applied to. To obtain the list of Diagnostic Log categories for a
* resource, first perform a GET diagnostic settings operation.
*/
@JsonProperty(value = "category")
private String category;
/**
* a value indicating whether this log is enabled.
*/
@JsonProperty(value = "enabled", required = true)
private boolean enabled;
/**
* the retention policy for this log.
*/
@JsonProperty(value = "retentionPolicy")
private RetentionPolicy retentionPolicy;
/**
* Get the category value.
*
* @return the category value
*/
public String category() {
return this.category;
}
/**
* Set the category value.
*
* @param category the category value to set
* @return the LogSettings object itself.
*/
public LogSettings withCategory(String category) {
this.category = category;
return this;
}
/**
* Get the enabled value.
*
* @return the enabled value
*/
public boolean enabled() {
return this.enabled;
}
/**
* Set the enabled value.
*
* @param enabled the enabled value to set
* @return the LogSettings object itself.
*/
public LogSettings withEnabled(boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* Get the retentionPolicy value.
*
* @return the retentionPolicy value
*/
public RetentionPolicy retentionPolicy() {
return this.retentionPolicy;
}
/**
* Set the retentionPolicy value.
*
* @param retentionPolicy the retentionPolicy value to set
* @return the LogSettings object itself.
*/
public LogSettings withRetentionPolicy(RetentionPolicy retentionPolicy) {
this.retentionPolicy = retentionPolicy;
return this;
}
}
|
martinsawicki/azure-sdk-for-java
|
azure-mgmt-monitor/src/main/java/com/microsoft/azure/management/monitor/LogSettings.java
|
Java
|
mit
| 2,421 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ConsoleApplication1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ConsoleApplication1")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f058ff68-8743-49cb-bea4-2d80be2d568d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
fabiomargarito/ExemplosCursoFundamentosEmArquiteturaDeSoftware
|
Curso Fundamentos/src/Aula 2/Revisitando OO/Exercício de Fixação 2 - Resolvido/ConsoleApplication1/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,414 |
// GridFS
// Copyright(c) 2013 Siddharth Mahendraker <[email protected]>
// MIT Licensed
exports.GridFS = require('./lib/GridFS');
exports.GridStream = require('./lib/GridStream');
|
SergejKasper/smartkitchen
|
server/node_modules/gridfstore/node_modules/GridFS/index.js
|
JavaScript
|
mit
| 187 |
// @flow
class A {
x = [1, 2, 3];
y = 4;
foo() {
this.x = this.x.map(function (z) {
this.y; // error, function has wrong this
});
}
}
class B {
x = [1, 2, 3];
y = 4;
foo() {
this.x = this.x.map(function (z) {
this.y; // ok, function gets passed correct this
}, this);
}
}
class C {
x = [1, 2, 3];
y = 4;
foo() {
this.x = this.x.map(z => {
this.y; // ok, arrow binds surrounding context this
});
}
}
|
facebook/flow
|
tests/arraylib/callback_this.js
|
JavaScript
|
mit
| 534 |
import collectionClass from "./collections.class";
import collectionColor from "./collections.color";
function collectionBackgroundStyles(contentItem) {
return `
.${collectionClass(contentItem)} {
background-color: #${collectionColor(contentItem)};
}
`;
}
export default collectionBackgroundStyles;
|
NewSpring/apollos-core
|
imports/util/collections/collections.backgroundStyles.js
|
JavaScript
|
mit
| 320 |
<?php
/**
* @Created By ECMall PhpCacheServer
* @Time:2015-01-17 18:28:59
*/
if(filemtime(__FILE__) + 600 < time())return false;
return array (
'inbox' => '0',
'outbox' => '0',
'total' => 0,
);
?>
|
guotao2000/ecmall
|
temp/caches/0220/9021b7cab81e674df1db5e94e51dced1.cache.php
|
PHP
|
mit
| 220 |
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2018, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
#include <assimp/Subdivision.h>
#include <assimp/SceneCombiner.h>
#include <assimp/SpatialSort.h>
#include "ProcessHelper.h"
#include <assimp/Vertex.h>
#include <assimp/ai_assert.h>
#include <stdio.h>
using namespace Assimp;
void mydummy() {}
// ------------------------------------------------------------------------------------------------
/** Subdivider stub class to implement the Catmull-Clarke subdivision algorithm. The
* implementation is basing on recursive refinement. Directly evaluating the result is also
* possible and much quicker, but it depends on lengthy matrix lookup tables. */
// ------------------------------------------------------------------------------------------------
class CatmullClarkSubdivider : public Subdivider
{
public:
void Subdivide (aiMesh* mesh, aiMesh*& out, unsigned int num, bool discard_input);
void Subdivide (aiMesh** smesh, size_t nmesh,
aiMesh** out, unsigned int num, bool discard_input);
// ---------------------------------------------------------------------------
/** Intermediate description of an edge between two corners of a polygon*/
// ---------------------------------------------------------------------------
struct Edge
{
Edge()
: ref(0)
{}
Vertex edge_point, midpoint;
unsigned int ref;
};
typedef std::vector<unsigned int> UIntVector;
typedef std::map<uint64_t,Edge> EdgeMap;
// ---------------------------------------------------------------------------
// Hashing function to derive an index into an #EdgeMap from two given
// 'unsigned int' vertex coordinates (!!distinct coordinates - same
// vertex position == same index!!).
// NOTE - this leads to rare hash collisions if a) sizeof(unsigned int)>4
// and (id[0]>2^32-1 or id[0]>2^32-1).
// MAKE_EDGE_HASH() uses temporaries, so INIT_EDGE_HASH() needs to be put
// at the head of every function which is about to use MAKE_EDGE_HASH().
// Reason is that the hash is that hash construction needs to hold the
// invariant id0<id1 to identify an edge - else two hashes would refer
// to the same edge.
// ---------------------------------------------------------------------------
#define MAKE_EDGE_HASH(id0,id1) (eh_tmp0__=id0,eh_tmp1__=id1,\
(eh_tmp0__<eh_tmp1__?std::swap(eh_tmp0__,eh_tmp1__):mydummy()),(uint64_t)eh_tmp0__^((uint64_t)eh_tmp1__<<32u))
#define INIT_EDGE_HASH_TEMPORARIES()\
unsigned int eh_tmp0__, eh_tmp1__;
private:
void InternSubdivide (const aiMesh* const * smesh,
size_t nmesh,aiMesh** out, unsigned int num);
};
// ------------------------------------------------------------------------------------------------
// Construct a subdivider of a specific type
Subdivider* Subdivider::Create (Algorithm algo)
{
switch (algo)
{
case CATMULL_CLARKE:
return new CatmullClarkSubdivider();
};
ai_assert(false);
return NULL; // shouldn't happen
}
// ------------------------------------------------------------------------------------------------
// Call the Catmull Clark subdivision algorithm for one mesh
void CatmullClarkSubdivider::Subdivide (
aiMesh* mesh,
aiMesh*& out,
unsigned int num,
bool discard_input
)
{
ai_assert(mesh != out);
Subdivide(&mesh,1,&out,num,discard_input);
}
// ------------------------------------------------------------------------------------------------
// Call the Catmull Clark subdivision algorithm for multiple meshes
void CatmullClarkSubdivider::Subdivide (
aiMesh** smesh,
size_t nmesh,
aiMesh** out,
unsigned int num,
bool discard_input
)
{
ai_assert( NULL != smesh );
ai_assert( NULL != out );
// course, both regions may not overlap
ai_assert(smesh<out || smesh+nmesh>out+nmesh);
if (!num) {
// No subdivision at all. Need to copy all the meshes .. argh.
if (discard_input) {
for (size_t s = 0; s < nmesh; ++s) {
out[s] = smesh[s];
smesh[s] = NULL;
}
}
else {
for (size_t s = 0; s < nmesh; ++s) {
SceneCombiner::Copy(out+s,smesh[s]);
}
}
return;
}
std::vector<aiMesh*> inmeshes;
std::vector<aiMesh*> outmeshes;
std::vector<unsigned int> maptbl;
inmeshes.reserve(nmesh);
outmeshes.reserve(nmesh);
maptbl.reserve(nmesh);
// Remove pure line and point meshes from the working set to reduce the
// number of edge cases the subdivider is forced to deal with. Line and
// point meshes are simply passed through.
for (size_t s = 0; s < nmesh; ++s) {
aiMesh* i = smesh[s];
// FIX - mPrimitiveTypes might not yet be initialized
if (i->mPrimitiveTypes && (i->mPrimitiveTypes & (aiPrimitiveType_LINE|aiPrimitiveType_POINT))==i->mPrimitiveTypes) {
ASSIMP_LOG_DEBUG("Catmull-Clark Subdivider: Skipping pure line/point mesh");
if (discard_input) {
out[s] = i;
smesh[s] = NULL;
}
else {
SceneCombiner::Copy(out+s,i);
}
continue;
}
outmeshes.push_back(NULL);inmeshes.push_back(i);
maptbl.push_back(static_cast<unsigned int>(s));
}
// Do the actual subdivision on the preallocated storage. InternSubdivide
// *always* assumes that enough storage is available, it does not bother
// checking any ranges.
ai_assert(inmeshes.size()==outmeshes.size()&&inmeshes.size()==maptbl.size());
if (inmeshes.empty()) {
ASSIMP_LOG_WARN("Catmull-Clark Subdivider: Pure point/line scene, I can't do anything");
return;
}
InternSubdivide(&inmeshes.front(),inmeshes.size(),&outmeshes.front(),num);
for (unsigned int i = 0; i < maptbl.size(); ++i) {
ai_assert(nullptr != outmeshes[i]);
out[maptbl[i]] = outmeshes[i];
}
if (discard_input) {
for (size_t s = 0; s < nmesh; ++s) {
delete smesh[s];
}
}
}
// ------------------------------------------------------------------------------------------------
// Note - this is an implementation of the standard (recursive) Cm-Cl algorithm without further
// optimizations (except we're using some nice LUTs). A description of the algorithm can be found
// here: http://en.wikipedia.org/wiki/Catmull-Clark_subdivision_surface
//
// The code is mostly O(n), however parts are O(nlogn) which is therefore the algorithm's
// expected total runtime complexity. The implementation is able to work in-place on the same
// mesh arrays. Calling #InternSubdivide() directly is not encouraged. The code can operate
// in-place unless 'smesh' and 'out' are equal (no strange overlaps or reorderings).
// Previous data is replaced/deleted then.
// ------------------------------------------------------------------------------------------------
void CatmullClarkSubdivider::InternSubdivide (
const aiMesh* const * smesh,
size_t nmesh,
aiMesh** out,
unsigned int num
)
{
ai_assert(NULL != smesh && NULL != out);
INIT_EDGE_HASH_TEMPORARIES();
// no subdivision requested or end of recursive refinement
if (!num) {
return;
}
UIntVector maptbl;
SpatialSort spatial;
// ---------------------------------------------------------------------
// 0. Offset table to index all meshes continuously, generate a spatially
// sorted representation of all vertices in all meshes.
// ---------------------------------------------------------------------
typedef std::pair<unsigned int,unsigned int> IntPair;
std::vector<IntPair> moffsets(nmesh);
unsigned int totfaces = 0, totvert = 0;
for (size_t t = 0; t < nmesh; ++t) {
const aiMesh* mesh = smesh[t];
spatial.Append(mesh->mVertices,mesh->mNumVertices,sizeof(aiVector3D),false);
moffsets[t] = IntPair(totfaces,totvert);
totfaces += mesh->mNumFaces;
totvert += mesh->mNumVertices;
}
spatial.Finalize();
const unsigned int num_unique = spatial.GenerateMappingTable(maptbl,ComputePositionEpsilon(smesh,nmesh));
#define FLATTEN_VERTEX_IDX(mesh_idx, vert_idx) (moffsets[mesh_idx].second+vert_idx)
#define FLATTEN_FACE_IDX(mesh_idx, face_idx) (moffsets[mesh_idx].first+face_idx)
// ---------------------------------------------------------------------
// 1. Compute the centroid point for all faces
// ---------------------------------------------------------------------
std::vector<Vertex> centroids(totfaces);
unsigned int nfacesout = 0;
for (size_t t = 0, n = 0; t < nmesh; ++t) {
const aiMesh* mesh = smesh[t];
for (unsigned int i = 0; i < mesh->mNumFaces;++i,++n)
{
const aiFace& face = mesh->mFaces[i];
Vertex& c = centroids[n];
for (unsigned int a = 0; a < face.mNumIndices;++a) {
c += Vertex(mesh,face.mIndices[a]);
}
c /= static_cast<float>(face.mNumIndices);
nfacesout += face.mNumIndices;
}
}
{
// we want edges to go away before the recursive calls so begin a new scope
EdgeMap edges;
// ---------------------------------------------------------------------
// 2. Set each edge point to be the average of all neighbouring
// face points and original points. Every edge exists twice
// if there is a neighboring face.
// ---------------------------------------------------------------------
for (size_t t = 0; t < nmesh; ++t) {
const aiMesh* mesh = smesh[t];
for (unsigned int i = 0; i < mesh->mNumFaces;++i) {
const aiFace& face = mesh->mFaces[i];
for (unsigned int p =0; p< face.mNumIndices; ++p) {
const unsigned int id[] = {
face.mIndices[p],
face.mIndices[p==face.mNumIndices-1?0:p+1]
};
const unsigned int mp[] = {
maptbl[FLATTEN_VERTEX_IDX(t,id[0])],
maptbl[FLATTEN_VERTEX_IDX(t,id[1])]
};
Edge& e = edges[MAKE_EDGE_HASH(mp[0],mp[1])];
e.ref++;
if (e.ref<=2) {
if (e.ref==1) { // original points (end points) - add only once
e.edge_point = e.midpoint = Vertex(mesh,id[0])+Vertex(mesh,id[1]);
e.midpoint *= 0.5f;
}
e.edge_point += centroids[FLATTEN_FACE_IDX(t,i)];
}
}
}
}
// ---------------------------------------------------------------------
// 3. Normalize edge points
// ---------------------------------------------------------------------
{unsigned int bad_cnt = 0;
for (EdgeMap::iterator it = edges.begin(); it != edges.end(); ++it) {
if ((*it).second.ref < 2) {
ai_assert((*it).second.ref);
++bad_cnt;
}
(*it).second.edge_point *= 1.f/((*it).second.ref+2.f);
}
if (bad_cnt) {
// Report the number of bad edges. bad edges are referenced by less than two
// faces in the mesh. They occur at outer model boundaries in non-closed
// shapes.
ASSIMP_LOG_DEBUG_F("Catmull-Clark Subdivider: got ", bad_cnt, " bad edges touching only one face (totally ",
static_cast<unsigned int>(edges.size()), " edges). ");
}}
// ---------------------------------------------------------------------
// 4. Compute a vertex-face adjacency table. We can't reuse the code
// from VertexTriangleAdjacency because we need the table for multiple
// meshes and out vertex indices need to be mapped to distinct values
// first.
// ---------------------------------------------------------------------
UIntVector faceadjac(nfacesout), cntadjfac(maptbl.size(),0), ofsadjvec(maptbl.size()+1,0); {
for (size_t t = 0; t < nmesh; ++t) {
const aiMesh* const minp = smesh[t];
for (unsigned int i = 0; i < minp->mNumFaces; ++i) {
const aiFace& f = minp->mFaces[i];
for (unsigned int n = 0; n < f.mNumIndices; ++n) {
++cntadjfac[maptbl[FLATTEN_VERTEX_IDX(t,f.mIndices[n])]];
}
}
}
unsigned int cur = 0;
for (size_t i = 0; i < cntadjfac.size(); ++i) {
ofsadjvec[i+1] = cur;
cur += cntadjfac[i];
}
for (size_t t = 0; t < nmesh; ++t) {
const aiMesh* const minp = smesh[t];
for (unsigned int i = 0; i < minp->mNumFaces; ++i) {
const aiFace& f = minp->mFaces[i];
for (unsigned int n = 0; n < f.mNumIndices; ++n) {
faceadjac[ofsadjvec[1+maptbl[FLATTEN_VERTEX_IDX(t,f.mIndices[n])]]++] = FLATTEN_FACE_IDX(t,i);
}
}
}
// check the other way round for consistency
#ifdef ASSIMP_BUILD_DEBUG
for (size_t t = 0; t < ofsadjvec.size()-1; ++t) {
for (unsigned int m = 0; m < cntadjfac[t]; ++m) {
const unsigned int fidx = faceadjac[ofsadjvec[t]+m];
ai_assert(fidx < totfaces);
for (size_t n = 1; n < nmesh; ++n) {
if (moffsets[n].first > fidx) {
const aiMesh* msh = smesh[--n];
const aiFace& f = msh->mFaces[fidx-moffsets[n].first];
bool haveit = false;
for (unsigned int i = 0; i < f.mNumIndices; ++i) {
if (maptbl[FLATTEN_VERTEX_IDX(n,f.mIndices[i])]==(unsigned int)t) {
haveit = true;
break;
}
}
ai_assert(haveit);
if (!haveit) {
ASSIMP_LOG_DEBUG("Catmull-Clark Subdivider: Index not used");
}
break;
}
}
}
}
#endif
}
#define GET_ADJACENT_FACES_AND_CNT(vidx,fstartout,numout) \
fstartout = &faceadjac[ofsadjvec[vidx]], numout = cntadjfac[vidx]
typedef std::pair<bool,Vertex> TouchedOVertex;
std::vector<TouchedOVertex > new_points(num_unique,TouchedOVertex(false,Vertex()));
// ---------------------------------------------------------------------
// 5. Spawn a quad from each face point to the corresponding edge points
// the original points being the fourth quad points.
// ---------------------------------------------------------------------
for (size_t t = 0; t < nmesh; ++t) {
const aiMesh* const minp = smesh[t];
aiMesh* const mout = out[t] = new aiMesh();
for (unsigned int a = 0; a < minp->mNumFaces; ++a) {
mout->mNumFaces += minp->mFaces[a].mNumIndices;
}
// We need random access to the old face buffer, so reuse is not possible.
mout->mFaces = new aiFace[mout->mNumFaces];
mout->mNumVertices = mout->mNumFaces*4;
mout->mVertices = new aiVector3D[mout->mNumVertices];
// quads only, keep material index
mout->mPrimitiveTypes = aiPrimitiveType_POLYGON;
mout->mMaterialIndex = minp->mMaterialIndex;
if (minp->HasNormals()) {
mout->mNormals = new aiVector3D[mout->mNumVertices];
}
if (minp->HasTangentsAndBitangents()) {
mout->mTangents = new aiVector3D[mout->mNumVertices];
mout->mBitangents = new aiVector3D[mout->mNumVertices];
}
for(unsigned int i = 0; minp->HasTextureCoords(i); ++i) {
mout->mTextureCoords[i] = new aiVector3D[mout->mNumVertices];
mout->mNumUVComponents[i] = minp->mNumUVComponents[i];
}
for(unsigned int i = 0; minp->HasVertexColors(i); ++i) {
mout->mColors[i] = new aiColor4D[mout->mNumVertices];
}
mout->mNumVertices = mout->mNumFaces<<2u;
for (unsigned int i = 0, v = 0, n = 0; i < minp->mNumFaces;++i) {
const aiFace& face = minp->mFaces[i];
for (unsigned int a = 0; a < face.mNumIndices;++a) {
// Get a clean new face.
aiFace& faceOut = mout->mFaces[n++];
faceOut.mIndices = new unsigned int [faceOut.mNumIndices = 4];
// Spawn a new quadrilateral (ccw winding) for this original point between:
// a) face centroid
centroids[FLATTEN_FACE_IDX(t,i)].SortBack(mout,faceOut.mIndices[0]=v++);
// b) adjacent edge on the left, seen from the centroid
const Edge& e0 = edges[MAKE_EDGE_HASH(maptbl[FLATTEN_VERTEX_IDX(t,face.mIndices[a])],
maptbl[FLATTEN_VERTEX_IDX(t,face.mIndices[a==face.mNumIndices-1?0:a+1])
])]; // fixme: replace with mod face.mNumIndices?
// c) adjacent edge on the right, seen from the centroid
const Edge& e1 = edges[MAKE_EDGE_HASH(maptbl[FLATTEN_VERTEX_IDX(t,face.mIndices[a])],
maptbl[FLATTEN_VERTEX_IDX(t,face.mIndices[!a?face.mNumIndices-1:a-1])
])]; // fixme: replace with mod face.mNumIndices?
e0.edge_point.SortBack(mout,faceOut.mIndices[3]=v++);
e1.edge_point.SortBack(mout,faceOut.mIndices[1]=v++);
// d= original point P with distinct index i
// F := 0
// R := 0
// n := 0
// for each face f containing i
// F := F+ centroid of f
// R := R+ midpoint of edge of f from i to i+1
// n := n+1
//
// (F+2R+(n-3)P)/n
const unsigned int org = maptbl[FLATTEN_VERTEX_IDX(t,face.mIndices[a])];
TouchedOVertex& ov = new_points[org];
if (!ov.first) {
ov.first = true;
const unsigned int* adj; unsigned int cnt;
GET_ADJACENT_FACES_AND_CNT(org,adj,cnt);
if (cnt < 3) {
ov.second = Vertex(minp,face.mIndices[a]);
}
else {
Vertex F,R;
for (unsigned int o = 0; o < cnt; ++o) {
ai_assert(adj[o] < totfaces);
F += centroids[adj[o]];
// adj[0] is a global face index - search the face in the mesh list
const aiMesh* mp = NULL;
size_t nidx;
if (adj[o] < moffsets[0].first) {
mp = smesh[nidx=0];
}
else {
for (nidx = 1; nidx<= nmesh; ++nidx) {
if (nidx == nmesh ||moffsets[nidx].first > adj[o]) {
mp = smesh[--nidx];
break;
}
}
}
ai_assert(adj[o]-moffsets[nidx].first < mp->mNumFaces);
const aiFace& f = mp->mFaces[adj[o]-moffsets[nidx].first];
bool haveit = false;
// find our original point in the face
for (unsigned int m = 0; m < f.mNumIndices; ++m) {
if (maptbl[FLATTEN_VERTEX_IDX(nidx,f.mIndices[m])] == org) {
// add *both* edges. this way, we can be sure that we add
// *all* adjacent edges to R. In a closed shape, every
// edge is added twice - so we simply leave out the
// factor 2.f in the amove formula and get the right
// result.
const Edge& c0 = edges[MAKE_EDGE_HASH(org,maptbl[FLATTEN_VERTEX_IDX(
nidx,f.mIndices[!m?f.mNumIndices-1:m-1])])];
// fixme: replace with mod face.mNumIndices?
const Edge& c1 = edges[MAKE_EDGE_HASH(org,maptbl[FLATTEN_VERTEX_IDX(
nidx,f.mIndices[m==f.mNumIndices-1?0:m+1])])];
// fixme: replace with mod face.mNumIndices?
R += c0.midpoint+c1.midpoint;
haveit = true;
break;
}
}
// this invariant *must* hold if the vertex-to-face adjacency table is valid
ai_assert(haveit);
if ( !haveit ) {
ASSIMP_LOG_WARN( "OBJ: no name for material library specified." );
}
}
const float div = static_cast<float>(cnt), divsq = 1.f/(div*div);
ov.second = Vertex(minp,face.mIndices[a])*((div-3.f) / div) + R*divsq + F*divsq;
}
}
ov.second.SortBack(mout,faceOut.mIndices[2]=v++);
}
}
}
} // end of scope for edges, freeing its memory
// ---------------------------------------------------------------------
// 7. Apply the next subdivision step.
// ---------------------------------------------------------------------
if (num != 1) {
std::vector<aiMesh*> tmp(nmesh);
InternSubdivide (out,nmesh,&tmp.front(),num-1);
for (size_t i = 0; i < nmesh; ++i) {
delete out[i];
out[i] = tmp[i];
}
}
}
|
MadManRises/Madgine
|
shared/assimp/code/Subdivision.cpp
|
C++
|
mit
| 23,758 |
--[[
Copyright (c) 2016 Calvin Rose
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
-- A filesystem abstraction on top of luv. Uses non-blocking coroutines
-- when available, otherwise uses blocking calls.
--
-- Modified from https://github.com/luvit/lit/blob/master/deps/coro-fs.lua
--- Abstractions around the libuv filesystem.
-- @module moonmint.fs
-- @author Calvin Rose
-- @copyright 2016
-- @license MIT
local uv = require 'luv'
local pathJoin = require('moonmint.deps.pathjoin').pathJoin
local fs = {}
local corunning = coroutine.running
local coresume = coroutine.resume
local coyield = coroutine.yield
local function noop() end
local function makeCallback(sync)
local thread = corunning()
if thread and not sync then -- Non Blocking callback (coroutines)
return function (err, value, ...)
if err then
assert(coresume(thread, nil, err))
else
assert(coresume(thread, value == nil and true or value, ...))
end
end
else -- Blocking callback
local context = {}
return function (err, first, ...)
context.done = true
context.err = err
context.first = first
context.values = {...}
end, context
end
end
local unpack = unpack or table.unpack
local function tryYield(context)
if context then -- Blocking
while not context.done do
uv.run('once') -- Should we use the default event loop?
end
local err = context.err
local first = context.first
if err then
return nil, err
else
return first == nil and true or first, unpack(context.values)
end
else -- Non blocking
return coyield()
end
end
--- Wrapper around uv.fs_mkdir
function fs.mkdir(sync, path, mode)
local cb, context = makeCallback(sync)
uv.fs_mkdir(path, mode or 511, cb)
return tryYield(context)
end
--- Wrapper around uv.fs_open
function fs.open(sync, path, flags, mode)
local cb, context = makeCallback(sync)
uv.fs_open(path, flags or "r", mode or 428, cb)
return tryYield(context)
end
--- Wrapper around uv.fs_unlink
function fs.unlink(sync, path)
local cb, context = makeCallback(sync)
uv.fs_unlink(path, cb)
return tryYield(context)
end
--- Wrapper around uv.fs_stat
function fs.stat(sync, path)
local cb, context = makeCallback(sync)
uv.fs_stat(path, cb)
return tryYield(context)
end
--- Wrapper around uv.fs_lstat
function fs.lstat(sync, path)
local cb, context = makeCallback(sync)
uv.fs_lstat(path, cb)
return tryYield(context)
end
--- Wrapper around uv.fs_fstat
function fs.fstat(sync, fd)
local cb, context = makeCallback(sync)
uv.fs_fstat(fd, cb)
return tryYield(context)
end
--- Wrapper around uv.fs_chmod
function fs.chmod(sync, path)
local cb, context = makeCallback(sync)
uv.fs_chmod(path, cb)
return tryYield(context)
end
--- Wrapper around uv.fs_fchmod
function fs.fchmod(sync, path)
local cb, context = makeCallback(sync)
uv.fs_fchmod(path, cb)
return tryYield(context)
end
--- Wrapper around uv.fs_read
function fs.read(sync, fd, length, offset)
local cb, context = makeCallback(sync)
uv.fs_read(fd, length or 1024 * 48, offset or -1, cb)
return tryYield(context)
end
--- Wrapper around uv.fs_write
function fs.write(sync, fd, data, offset)
local cb, context = makeCallback(sync)
uv.fs_write(fd, data, offset or -1, cb)
return tryYield(context)
end
--- Wrapper around uv.fs_close
function fs.close(sync, fd)
local cb, context = makeCallback(sync)
uv.fs_close(fd, cb)
return tryYield(context)
end
--- Wrapper around uv.fs_symlink
function fs.symlink(sync, target, path)
local cb, context = makeCallback(sync)
uv.fs_symlink(target, path, cb)
return tryYield(context)
end
--- Wrapper around uv.fs_readlink
function fs.readlink(sync, path)
local cb, context = makeCallback(sync)
uv.fs_readlink(path, cb)
return tryYield(context)
end
--- Wrapper around uv.fs_access
function fs.access(sync, path, flags)
local cb, context = makeCallback(sync)
uv.fs_access(path, flags or '', cb)
return tryYield(context)
end
--- Wrapper around uv.fs_rmdir
function fs.rmdir(sync, path)
local cb, context = makeCallback(sync)
uv.fs_rmdir(path, cb)
return tryYield(context)
end
--- Remove directories recursively like the UNIX command `rm -rf`.
function fs.rmrf(sync, path)
local success, err = fs.rmdir(sync, path)
if success then
return success, err
end
if err:match('^ENOTDIR:') then return fs.unlink(sync, path) end
if not err:match('^ENOTEMPTY:') then return success, err end
for entry in assert(fs.scandir(sync, path)) do
local subPath = pathJoin(path, entry.name)
if entry.type == 'directory' then
success, err = fs.rmrf(sync, pathJoin(path, entry.name))
else
success, err = fs.unlink(sync, subPath)
end
if not success then return success, err end
end
return fs.rmdir(sync, path)
end
--- Smart wrapper around uv.fs_scandir.
-- @treturn function an iterator over file objects
-- in a directory. Each file table has a `name` property
-- and a `type` property.
function fs.scandir(sync, path)
local cb, context = makeCallback(sync)
uv.fs_scandir(path, cb)
local req, err = tryYield(context)
if not req then return nil, err end
return function ()
local name, typ = uv.fs_scandir_next(req)
if not name then return name, typ end
if type(name) == "table" then return name end
return {
name = name,
type = typ
}
end
end
--- Reads a file into a string
function fs.readFile(sync, path)
local fd, stat, data, err
fd, err = fs.open(sync, path)
if err then return nil, err end
stat, err = fs.fstat(sync, fd)
if stat then
data, err = fs.read(sync, fd, stat.size)
end
uv.fs_close(fd, noop)
return data, err
end
--- Writes a string to a file. Overwrites the file
-- if it already exists.
function fs.writeFile(sync, path, data, mkdir)
local fd, success, err
fd, err = fs.open(sync, path, "w")
if err then
if mkdir and err:match("^ENOENT:") then
success, err = fs.mkdirp(sync, pathJoin(path, ".."))
if success then return fs.writeFile(sync, path, data) end
end
return nil, err
end
success, err = fs.write(sync, fd, data)
uv.fs_close(fd, noop)
return success, err
end
--- Append a string to a file.
function fs.appendFile(sync, path, data, mkdir)
local fd, success, err
fd, err = fs.open(sync, path, "w+")
if err then
if mkdir and err:match("^ENOENT:") then
success, err = fs.mkdirp(sync, pathJoin(path, ".."))
if success then return fs.appendFile(sync, path, data) end
end
return nil, err
end
success, err = fs.write(sync, fd, data)
uv.fs_close(fd, noop)
return success, err
end
--- Make directories recursively. Similar to the UNIX `mkdir -p`.
function fs.mkdirp(sync, path, mode)
local success, err = fs.mkdir(sync, path, mode)
if success or err:match("^EEXIST") then
return true
end
if err:match("^ENOENT:") then
success, err = fs.mkdirp(sync, pathJoin(path, ".."), mode)
if not success then return nil, err end
return fs.mkdir(sync, path, mode)
end
return nil, err
end
-- Make sync and async versions
local function makeAliases(module)
local ret = {}
local ext = {}
local sync = {}
for k, v in pairs(module) do
if type(v) == 'function' then
if k == 'chroot' then
sync[k], ext[k], ret[k] = v, v, v
else
sync[k] = function(...)
return v(true, ...)
end
ext[k] = v
ret[k] = function(...)
return v(false, ...)
end
end
end
end
ret.s = sync
ret.sync = sync
ret.ext = ext
return ret
end
--- Creates a clone of fs, but with a different base directory.
function fs.chroot(base)
local chroot = {
base = base,
fstat = fs.fstat,
fchmod = fs.fchmod,
read = fs.read,
write = fs.write,
close = fs.close,
}
local function resolve(path)
assert(path, "path missing")
return pathJoin(base, pathJoin(path))
end
function chroot.mkdir(sync, path, mode)
return fs.mkdir(sync, resolve(path), mode)
end
function chroot.mkdirp(sync, path, mode)
return fs.mkdirp(sync, resolve(path), mode)
end
function chroot.open(sync, path, flags, mode)
return fs.open(sync, resolve(path), flags, mode)
end
function chroot.unlink(sync, path)
return fs.unlink(sync, resolve(path))
end
function chroot.stat(sync, path)
return fs.stat(sync, resolve(path))
end
function chroot.lstat(sync, path)
return fs.lstat(sync, resolve(path))
end
function chroot.symlink(sync, target, path)
-- TODO: should we resolve absolute target paths or treat it as opaque data?
return fs.symlink(sync, target, resolve(path))
end
function chroot.readlink(sync, path)
return fs.readlink(sync, resolve(path))
end
function chroot.chmod(sync, path, mode)
return fs.chmod(sync, resolve(path), mode)
end
function chroot.access(sync, path, flags)
return fs.access(sync, resolve(path), flags)
end
function chroot.rename(sync, path, newPath)
return fs.rename(sync, resolve(path), resolve(newPath))
end
function chroot.rmdir(sync, path)
return fs.rmdir(sync, resolve(path))
end
function chroot.rmrf(sync, path)
return fs.rmrf(sync, resolve(path))
end
function chroot.scandir(sync, path)
return fs.scandir(sync, resolve(path))
end
function chroot.readFile(sync, path)
return fs.readFile(sync, resolve(path))
end
function chroot.writeFile(sync, path, data, mkdir)
return fs.writeFile(sync, resolve(path), data, mkdir)
end
function chroot.appendFile(sync, path, data, mkdir)
return fs.appendFile(sync, resolve(path), data, mkdir)
end
function chroot.chroot(sync, newBase)
return fs.chroot(sync, resolve(newBase))
end
return makeAliases(chroot)
end
return makeAliases(fs)
|
bakpakin/heroku-buildpack-moonmint
|
heroku/share/lua/5.1/moonmint/fs.lua
|
Lua
|
mit
| 11,552 |
namespace SIM.Tool.Windows.MainWindowComponents
{
using System.Windows;
using SIM.Instances;
using SIM.Tool.Base;
using SIM.Tool.Base.Plugins;
using SIM.Tool.Windows.Dialogs;
using JetBrains.Annotations;
[UsedImplicitly]
public class DatabaseManagerButton : IMainWindowButton
{
#region Public methods
public bool IsEnabled(Window mainWindow, Instance instance)
{
return true;
}
public void OnClick(Window mainWindow, Instance instance)
{
if (EnvironmentHelper.CheckSqlServer())
{
WindowHelper.ShowDialog(new DatabasesDialog(), mainWindow);
}
}
#endregion
}
}
|
sergeyshushlyapin/Sitecore-Instance-Manager
|
src/SIM.Tool.Windows/MainWindowComponents/DatabaseManagerButton.cs
|
C#
|
mit
| 649 |
package com.xeiam.xchange.lakebtc.marketdata;
import static org.fest.assertions.api.Assertions.assertThat;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xeiam.xchange.lakebtc.dto.marketdata.LakeBTCOrderBook;
import com.xeiam.xchange.lakebtc.dto.marketdata.LakeBTCTicker;
import com.xeiam.xchange.lakebtc.dto.marketdata.LakeBTCTickers;
public class LakeBTCMarketDataJsonTest {
@Test
public void testDeserializeTicker() throws IOException {
// Read in the JSON from the example resources
InputStream is = LakeBTCMarketDataJsonTest.class.getResourceAsStream("/marketdata/example-ticker-data.json");
// Use Jackson to parse it
ObjectMapper mapper = new ObjectMapper();
LakeBTCTickers tickers = mapper.readValue(is, LakeBTCTickers.class);
LakeBTCTicker cnyTicker = tickers.getCny();
assertThat(cnyTicker.getAsk()).isEqualTo("3524.07");
assertThat(cnyTicker.getBid()).isEqualTo("3517.13");
assertThat(cnyTicker.getLast()).isEqualTo("3524.07");
assertThat(cnyTicker.getHigh()).isEqualTo("3584.97");
assertThat(cnyTicker.getLow()).isEqualTo("3480.07");
assertThat(cnyTicker.getVolume()).isEqualTo("5964.7677");
LakeBTCTicker usdTicker = tickers.getUsd();
assertThat(usdTicker.getAsk()).isEqualTo("564.63");
assertThat(usdTicker.getBid()).isEqualTo("564.63");
assertThat(usdTicker.getLast()).isEqualTo("564.4");
assertThat(usdTicker.getHigh()).isEqualTo("573.83");
assertThat(usdTicker.getLow()).isEqualTo("557.7");
assertThat(usdTicker.getVolume()).isEqualTo("3521.2782");
}
@Test
public void testDeserializeOrderBook() throws IOException {
// Read in the JSON from the example resources
InputStream is = LakeBTCMarketDataJsonTest.class.getResourceAsStream("/marketdata/example-orderbook-data.json");
// Use Jackson to parse it
ObjectMapper mapper = new ObjectMapper();
LakeBTCOrderBook orderBook = mapper.readValue(is, LakeBTCOrderBook.class);
BigDecimal[][] asks = orderBook.getAsks();
assertThat(asks).hasSize(3);
assertThat(asks[0][0]).isEqualTo("564.87");
assertThat(asks[0][1]).isEqualTo("22.371");
BigDecimal[][] bids = orderBook.getBids();
assertThat(bids).hasSize(3);
assertThat(bids[2][0]).isEqualTo("558.08");
assertThat(bids[2][1]).isEqualTo("0.9878");
}
}
|
coingecko/XChange
|
xchange-lakebtc/src/test/java/com/xeiam/xchange/lakebtc/marketdata/LakeBTCMarketDataJsonTest.java
|
Java
|
mit
| 2,443 |
using System;
using BEPUutilities.DataStructures;
namespace BEPUutilities.ResourceManagement
{
/// <summary>
/// Uses a spinlock to safely access resources.
/// </summary>
/// <typeparam name="T">Type of object to store in the pool.</typeparam>
public class LockingResourcePool<T> : ResourcePool<T> where T : class, new()
{
private readonly ConcurrentDeque<T> stack;
/// <summary>
/// Constructs a new thread-unsafe resource pool.
/// </summary>
/// <param name="initialResourceCount">Number of resources to include in the pool by default.</param>
/// <param name="initializer">Function to initialize new instances in the resource pool with.</param>
public LockingResourcePool(int initialResourceCount, Action<T> initializer)
{
InstanceInitializer = initializer;
stack = new ConcurrentDeque<T>(initialResourceCount);
Initialize(initialResourceCount);
}
/// <summary>
/// Constructs a new thread-unsafe resource pool.
/// </summary>
/// <param name="initialResourceCount">Number of resources to include in the pool by default.</param>
public LockingResourcePool(int initialResourceCount)
: this(initialResourceCount, null)
{
}
/// <summary>
/// Constructs a new thread-unsafe resource pool.
/// </summary>
public LockingResourcePool()
: this(10)
{
}
/// <summary>
/// Gets the number of resources in the pool.
/// Even if the resource count hits 0, resources
/// can still be requested; they will be allocated
/// dynamically.
/// </summary>
public override int Count
{
get { return stack.Count; }
}
/// <summary>
/// Gives an item back to the resource pool.
/// </summary>
/// <param name="item">Item to return.</param>
public override void GiveBack(T item)
{
stack.Enqueue(item);
}
/// <summary>
/// Initializes the pool with some resources.
/// Throws away excess resources.
/// </summary>
/// <param name="initialResourceCount">Number of resources to include.</param>
public override void Initialize(int initialResourceCount)
{
while (stack.Count > initialResourceCount)
{
T toRemove;
stack.TryUnsafeDequeueFirst(out toRemove);
}
int length = stack.lastIndex - stack.firstIndex + 1; //lastIndex is inclusive, so add 1.
if (InstanceInitializer != null)
for (int i = 0; i < length; i++)
{
InstanceInitializer(stack.array[(stack.firstIndex + i) % stack.array.Length]);
}
while (stack.Count < initialResourceCount)
{
stack.UnsafeEnqueue(CreateNewResource());
}
}
/// <summary>
/// Takes an item from the resource pool.
/// </summary>
/// <returns>Item to take.</returns>
public override T Take()
{
T toTake;
if (stack.TryDequeueFirst(out toTake))
{
return toTake;
}
return CreateNewResource();
}
/// <summary>
/// Clears out the resource pool.
/// </summary>
public override void Clear()
{
while (stack.Count > 0)
{
T item;
stack.TryDequeueFirst(out item);
}
}
}
}
|
mayermatt/coms-437-trashdroids
|
Trashdroids/BEPUutilities/ResourceManagement/LockingResourcePool.cs
|
C#
|
mit
| 3,717 |
version https://git-lfs.github.com/spec/v1
oid sha256:71736be070607c3c30f4c139b063edf1b1ffa587cf725a0acc1e06c6d3af0e48
size 53235
|
yogeshsaroya/new-cdnjs
|
ajax/libs/ace/1.1.5/mode-objectivec.js
|
JavaScript
|
mit
| 130 |
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
CurrentModel = mongoose.model('Attendance'),
Schedule = mongoose.model('Schedule'),
Group = mongoose.model('Group'),
_ = require('lodash');
exports.attendance = function(req, res, next, id) {
CurrentModel.load(id, function(err, item) {
if (err) return next(err);
if (!item) return next(new Error('Failed to load item ' + id));
req.attendance = item;
next();
});
};
exports.schedule = function(req, res, next, id) {
Schedule.load(id, function(err, item) {
if (err) return next(err);
if (!item) return next(new Error('Failed to load item ' + id));
req.schedule = item;
next();
});
};
exports.group = function(req, res, next, id) {
Group.load(id, function(err, item) {
if (err) return next(err);
if (!item) return next(new Error('Failed to load item ' + id));
req.group = item;
next();
});
};
exports.create = function(req, res) {
var value = new CurrentModel(req.body);
value.group = req.group;
value.schedule = req.schedule;
value.save(function(err) {
if (err) {
return res.send('users/signup', {
errors: err.errors,
object: value
});
} else {
res.jsonp(value);
}
});
};
exports.update = function(req, res) {
var item = req.attendance;
item = _.extend(item, req.body);
item.save(function(err) {
if (err) {
return res.send('users/signup', {
errors: err.errors,
object: item
});
} else {
res.jsonp(item);
}
});
};
exports.destroy = function(req, res) {
var item = req.attendance;
item.remove(function(err) {
if (err) {
return res.send('users/signup', {
errors: err.errors,
object: item
});
} else {
res.jsonp(item);
}
});
};
exports.show = function(req, res) {
res.jsonp(req.attendance);
};
exports.all = function(req, res) {
CurrentModel.find({ group: req.group, schedule: req.schedule }).populate('participant', 'name email').exec(function(err, items) {
if (err) {
res.render('error', {
status: 500
});
} else {
res.jsonp(items);
}
});
};
|
wolf-mtwo/attendance
|
packages/custom/groups/server/controllers/attendances.js
|
JavaScript
|
mit
| 2,206 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><title>Plugin</title>
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
body {
margin: 5px 5px 5px 5px;
background-color: #ffffff;
}
/* ========== Text Styles ========== */
hr { color: #000000}
body, table /* Normal text */
{
font-size: 10pt;
font-family: 'Arial', 'Helvetica', sans-serif;
font-style: normal;
font-weight: normal;
color: #000000;
text-decoration: none;
}
span.rvts1 /* Heading */
{
font-weight: bold;
color: #0000ff;
}
span.rvts2 /* Subheading */
{
font-weight: bold;
color: #000080;
}
span.rvts3 /* Keywords */
{
font-style: italic;
color: #800000;
}
a.rvts4, span.rvts4 /* Jump 1 */
{
color: #008000;
text-decoration: underline;
}
a.rvts5, span.rvts5 /* Jump 2 */
{
color: #008000;
text-decoration: underline;
}
span.rvts6 /* Font Hint */
{
color: #808080;
}
span.rvts7 /* Font Hint Title */
{
font-size: 15pt;
font-family: 'Tahoma', 'Geneva', sans-serif;
font-weight: bold;
color: #404040;
}
span.rvts8 /* Font Hint Bold */
{
font-weight: bold;
color: #808080;
}
span.rvts9 /* Font Hint Italic */
{
font-style: italic;
color: #808080;
}
span.rvts10 /* Font Style */
{
font-size: 16pt;
font-family: 'Tahoma', 'Geneva', sans-serif;
color: #ffffff;
}
span.rvts11 /* Font Style */
{
font-family: 'MS Sans Serif', 'Geneva', sans-serif;
color: #808080;
}
span.rvts12 /* Font Style */
{
font-family: 'Verdana', 'Geneva', sans-serif;
font-style: italic;
color: #c0c0c0;
}
a.rvts13, span.rvts13 /* Font Style */
{
font-family: 'Verdana', 'Geneva', sans-serif;
font-style: italic;
color: #6666ff;
text-decoration: underline;
}
/* ========== Para Styles ========== */
p,ul,ol /* Paragraph Style */
{
text-align: left;
text-indent: 0px;
padding: 0px 0px 0px 0px;
margin: 0px 0px 0px 0px;
}
.rvps1 /* Centered */
{
text-align: center;
}
.rvps2 /* Paragraph Style */
{
background: #c0c0c0;
margin: 0px 0px 20px 0px;
}
.rvps3 /* Paragraph Style */
{
text-align: center;
background: #c0c0c0;
margin: 20px 0px 0px 0px;
}
.rvps4 /* Paragraph Style */
{
border-color: #c0c0c0;
border-style: solid;
border-width: 1px;
border-right: none;
border-bottom: none;
border-left: none;
background: #ffffff;
padding: 3px 0px 0px 0px;
margin: 27px 0px 0px 0px;
}
--></style>
<script type="text/javascript">if(top.frames.length == 0) { top.location.href="../thewebmind.htm?Plugin.html"; }</script>
<meta name="generator" content="HelpNDoc Free"></head>
<body>
<p class=rvps2><span class=rvts10>Plugin</span></p>
<p><br></p>
<p class=rvps3><span class=rvts11>Copyright © 2009, theWebMind.org</span></p>
<p class=rvps4><span class=rvts12>This help file has been generated by the freeware version of </span><a class=rvts13 href="http://www.ibe-software.com/products/software/helpndoc/" target="_blank">HelpNDoc</a></p>
</body></html>
|
thewebmind/mind2.0
|
help_pt/files/Plugin1.html
|
HTML
|
mit
| 3,029 |
#ifndef OSCTOOLS_HPP_INCLUDED
#define OSCTOOLS_HPP_INCLUDED
class OscOptionalUnpacker
{
ofxOscMessage & msg;
int n;
public:
OscOptionalUnpacker(ofxOscMessage & m):msg(m),n(0){}
OscOptionalUnpacker & operator >> (int & i)
{
if(n < msg.getNumArgs())
{
i = msg.getArgAsInt32( n++ );
}
return *this;
}
OscOptionalUnpacker & operator >> (float & i)
{
if(n < msg.getNumArgs())
{
i = msg.getArgAsFloat( n++ );
}
return *this;
}
OscOptionalUnpacker & operator >> (double & i)
{
if(n < msg.getNumArgs())
{
i = msg.getArgAsFloat( n++ );
}
return *this;
}
OscOptionalUnpacker & operator >> (std::string & i)
{
if(n < msg.getNumArgs())
{
i = msg.getArgAsString( n++ );
}
return *this;
}
bool Eos()
{
return n >= msg.getNumArgs();
}
};
class OscPacker
{
ofxOscMessage & msg;
public:
OscPacker(ofxOscMessage & m):msg(m){}
OscPacker & operator << (int i)
{
msg.addIntArg(i);
return *this;
}
OscPacker & operator << (unsigned int i)
{
msg.addIntArg(i);
return *this;
}
OscPacker & operator << (float i)
{
msg.addFloatArg(i);
return *this;
}
OscPacker & operator << (const std::string & i)
{
msg.addStringArg(i);
return *this;
}
};
#endif // OSCTOOLS_HPP_INCLUDED
|
toddberreth/ofxTableGestures
|
src/Utils/OscTools.hpp
|
C++
|
mit
| 1,534 |
package org.magcruise.gaming.executor.api.message;
import org.magcruise.gaming.lang.Message;
import org.magcruise.gaming.lang.SConstructor;
public interface RequestToGameExecutor extends Message {
@Override
public SConstructor<? extends RequestToGameExecutor> toConstructor(ToExpressionStyle style);
@Override
public default SConstructor<? extends RequestToGameExecutor> toConstructor() {
return toConstructor(ToExpressionStyle.DEFAULT);
}
}
|
MAGCruise/magcruise-core
|
src/main/java/org/magcruise/gaming/executor/api/message/RequestToGameExecutor.java
|
Java
|
mit
| 454 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
namespace UnitTests
{
[TestFixture]
public class ProjectTests
{
[TestFixtureSetUp]
public void Initialize()
{
}
[Test]
public void TestCsvRename()
{
}
}
}
|
GorillaOne/FlatRedBall
|
FRBDK/Glue/UnitTests/ProjectTests.cs
|
C#
|
mit
| 352 |
import os
import re
from opsbro.collector import Collector
# DMI have lot of useful information that detectors can use to know lot about the platform/hardware
class Dmidecode(Collector):
def launch(self):
logger = self.logger
logger.debug('getDmidecode: start')
res = {}
# Maybe we are in linux and we can directly read the
linux_dmi_path = '/sys/class/dmi/id/'
if os.path.exists(linux_dmi_path):
file_names = os.listdir(linux_dmi_path)
for fname in file_names:
p = os.path.join(linux_dmi_path, fname)
# There can be a link there, skip them
if os.path.isfile(p):
f = open(p, 'r')
buf = f.read()
f.close()
res[fname] = buf.strip()
logger.debug('getdmidecode: completed, returning')
return res
elif os.name == 'nt':
self.set_not_eligible('Windows is currently not managed for DMI informations')
return False
# Ok not direct access, try to launch with
else: # try dmidecode way, if exists
res = self.execute_shell('LANG=C dmidecode -s')
if res is False:
self.set_not_eligible('Cannot read dmi information')
return False
for p in res.split('\n'):
if re.search('^ ', p):
buf = self.execute_shell('LANG=C dmidecode -s %s' % p).strip()
if 'No such file or directory' in buf:
logger.warning('Cannot access to dmi information with dmidecode command, exiting this collector.')
self.set_not_eligible('Cannot get DMI informations because the dmidecode command is missing.')
return res
res[p.replace('-', '_').strip()] = buf
logger.debug('getdmidecode: completed, returning')
return res
|
naparuba/kunai
|
data/global-configuration/packs/system/collectors/collector_dmidecode.py
|
Python
|
mit
| 2,003 |
# Websocket Module
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
| 2016-08-02 | [Luís Fonseca](https://github.com/luismfonseca) | [Luís Fonseca](https://github.com/luismfonseca) | [websocket.c](../../../app/modules/websocket.c)|
A websocket *client* module that implements [RFC6455](https://tools.ietf.org/html/rfc6455) (version 13) and provides a simple interface to send and receive messages.
The implementation supports fragmented messages, automatically respondes to ping requests and periodically pings if the server isn't communicating.
**SSL/TLS support**
Take note of constraints documented in the [net module](net.md).
## websocket.createClient()
Creates a new websocket client. This client should be stored in a variable and will provide all the functions to handle a connection.
When the connection becomes closed, the same client can still be reused - the callback functions are kept - and you can connect again to any server.
Before disposing the client, make sure to call `ws:close()`.
#### Syntax
`websocket.createClient()`
#### Parameters
none
#### Returns
`websocketclient`
#### Example
```lua
local ws = websocket.createClient()
-- ...
ws:close()
ws = nil
```
## websocket.client:close()
Closes a websocket connection. The client issues a close frame and attemtps to gracefully close the websocket.
If server doesn't reply, the connection is terminated after a small timeout.
This function can be called even if the websocket isn't connected.
This function must *always* be called before disposing the reference to the websocket client.
#### Syntax
`websocket:close()`
#### Parameters
none
#### Returns
`nil`
#### Example
```lua
ws = websocket.createClient()
ws:close()
ws:close() -- nothing will happen
ws = nil -- fully dispose the client as Lua will now gc it
```
## websocket.client:config(params)
Configures websocket client instance.
#### Syntax
`websocket:config(params)`
#### Parameters
- `params` table with configuration parameters. Following keys are recognized:
- `headers` table of extra request headers affecting every request
#### Returns
`nil`
#### Example
```lua
ws = websocket.createClient()
ws:config({headers={['User-Agent']='NodeMCU'}})
```
## websocket.client:connect()
Attempts to estabilish a websocket connection to the given URL.
#### Syntax
`websocket:connect(url)`
#### Parameters
- `url` the URL for the websocket.
#### Returns
`nil`
#### Example
```lua
ws = websocket.createClient()
ws:connect('ws://echo.websocket.org')
```
If it fails, an error will be delivered via `websocket:on("close", handler)`.
## websocket.client:on()
Registers the callback function to handle websockets events (there can be only one handler function registered per event type).
#### Syntax
`websocket:on(eventName, function(ws, ...))`
#### Parameters
- `eventName` the type of websocket event to register the callback function. Those events are: `connection`, `receive` and `close`.
- `function(ws, ...)` callback function.
The function first parameter is always the websocketclient.
Other arguments are required depending on the event type. See example for more details.
If `nil`, any previously configured callback is unregistered.
#### Returns
`nil`
#### Example
```lua
local ws = websocket.createClient()
ws:on("connection", function(ws)
print('got ws connection')
end)
ws:on("receive", function(_, msg, opcode)
print('got message:', msg, opcode) -- opcode is 1 for text message, 2 for binary
end)
ws:on("close", function(_, status)
print('connection closed', status)
ws = nil -- required to Lua gc the websocket client
end)
ws:connect('ws://echo.websocket.org')
```
Note that the close callback is also triggered if any error occurs.
The status code for the close, if not 0 then it represents an error, as described in the following table.
| Status Code | Explanation |
| :----------- | :----------- |
| 0 | User requested close or the connection was terminated gracefully |
| -1 | Failed to extract protocol from URL |
| -2 | Hostname is too large (>256 chars) |
| -3 | Invalid port number (must be >0 and <= 65535) |
| -4 | Failed to extract hostname |
| -5 | DNS failed to lookup hostname |
| -6 | Server requested termination |
| -7 | Server sent invalid handshake HTTP response (i.e. server sent a bad key) |
| -8 to -14 | Failed to allocate memory to receive message |
| -15 | Server not following FIN bit protocol correctly |
| -16 | Failed to allocate memory to send message |
| -17 | Server is not switching protocols |
| -18 | Connect timeout |
| -19 | Server is not responding to health checks nor communicating |
| -99 to -999 | Well, something bad has happenned |
## websocket.client:send()
Sends a message through the websocket connection.
#### Syntax
`websocket:send(message, opcode)`
#### Parameters
- `message` the data to send.
- `opcode` optionally set the opcode (default: 1, text message)
#### Returns
`nil` or an error if socket is not connected
#### Example
```lua
ws = websocket.createClient()
ws:on("connection", function()
ws:send('hello!')
end)
ws:connect('ws://echo.websocket.org')
```
|
luizfeliperj/nodemcu-firmware
|
docs/en/modules/websocket.md
|
Markdown
|
mit
| 5,321 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace It.Uniba.Di.Cdg.SocialTfs.ProxyServer.AdminPanel {
public partial class EditService {
/// <summary>
/// ErrorPA control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl ErrorPA;
/// <summary>
/// Id control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlInputHidden Id;
/// <summary>
/// DataTable control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTable DataTable;
/// <summary>
/// ServiceRW control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow ServiceRW;
/// <summary>
/// ServiceTB control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlInputText ServiceTB;
/// <summary>
/// NameRW control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow NameRW;
/// <summary>
/// NameTB control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlInputText NameTB;
/// <summary>
/// ErrNameRW control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow ErrNameRW;
/// <summary>
/// HostRW control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow HostRW;
/// <summary>
/// HostTB control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlInputText HostTB;
/// <summary>
/// ErrHostRW control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow ErrHostRW;
/// <summary>
/// ConsumerKeyRW control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow ConsumerKeyRW;
/// <summary>
/// ConsumerKeyTB control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlInputText ConsumerKeyTB;
/// <summary>
/// ErrConsumerKeyRW control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow ErrConsumerKeyRW;
/// <summary>
/// ConsumerSecretRW control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow ConsumerSecretRW;
/// <summary>
/// ConsumerSecretTB control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlInputText ConsumerSecretTB;
/// <summary>
/// ErrConsumerSecretRW control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow ErrConsumerSecretRW;
/// <summary>
/// GitHubLabelRW control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow GitHubLabelRW;
/// <summary>
/// GitHubLabelTB control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlInputText GitHubLabelTB;
/// <summary>
/// ErrGitHubLabelRW control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow ErrGitHubLabelRW;
/// <summary>
/// Submit control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlInputButton Submit;
/// <summary>
/// Reset control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlInputReset Reset;
}
}
|
CosimoLovascio/SocialCDE-ProxyServer-VSclient
|
SocialTFS/It.Uniba.Di.Cdg.SocialTfs.ProxyServer/AdminPanel/EditService.aspx.designer.cs
|
C#
|
mit
| 7,721 |
//
// VOKManagedObjectMapper.h
// Vokoder
//
// Copyright © 2015 Vokal.
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import "VOKCoreDataCollectionTypes.h"
#import "VOKNullabilityFeatures.h"
#import "VOKManagedObjectMap.h"
NS_ASSUME_NONNULL_BEGIN
/// An completion block to run after importing each foreign dictionary.
typedef void(^VOKPostImportBlock)(VOKStringToObjectDictionary *inputDict, VOKManagedObjectSubclass *outputObject);
/// A completion block to run after exporting a managed object to a dictionary.
typedef void(^VOKPostExportBlock)(VOKStringToObjectMutableDictionary *outputDict, VOKManagedObjectSubclass *inputObject);
@interface VOKManagedObjectMapper : NSObject
/// Used to identify and update NSManagedObjects. Like a "primary key" in databases.
@property (nonatomic, copy) NSString * __nullable uniqueComparisonKey;
/// Used internally to filter input data. Updates automatically to match the uniqueComparisonKey.
@property (nonatomic, copy) NSString * __nullable foreignUniqueComparisonKey;
/// If set to NO changes are discarded if a local object exists with the same unique comparison key. Defaults to YES.
@property (nonatomic, assign) BOOL overwriteObjectsWithServerChanges;
/// If set to YES remote null/nil values are ignored when updating. Defaults to NO.
@property (nonatomic, assign) BOOL ignoreNullValueOverwrites;
/**
If set to YES, will not warn about incorrect class types when receiving null/nil values for optional properties.
Defaults to NO. Note: regardless of the setting of this property, log messages are only output in DEBUG situations.
*/
@property (nonatomic, assign) BOOL ignoreOptionalNullValues;
/// An optional completion block to run after importing each foreign dictionary. Defaults to nil.
@property (nonatomic, copy) VOKPostImportBlock __nullable importCompletionBlock;
/// An optional completion block to run after exporting a managed object to a dictionary. Defaults to nil.
@property (nonatomic, copy) VOKPostExportBlock __nullable exportCompletionBlock;
/**
Creates a new mapper.
@param comparisonKey An NSString to uniquely identify local entities. Can be nil to enable duplicates.
@param mapsArray An NSArray of VOKManagedObjectMaps to corrdinate input data and the Core Data model.
@return A new mapper with the given unique key and maps.
*/
+ (instancetype)mapperWithUniqueKey:(nullable NSString *)comparisonKey
andMaps:(VOKArrayOfManagedObjectMaps *)mapsArray;
/**
Convenience constructor for default mapper.
@return A default mapper wherein the local keys and foreign keys are identical.
*/
+ (instancetype)defaultMapper;
/**
This override of objectForKeyedSubscript returns the foreign key for a local Core Data key.
@param key The Core Data key.
@return The foreign keypath as a string.
*/
- (id)objectForKeyedSubscript:(id)key;
@end
NS_ASSUME_NONNULL_END
|
chillpop/Vokoder
|
Pod/Classes/VOKManagedObjectMapper.h
|
C
|
mit
| 2,934 |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "m22 6.92-1.41-1.41-2.85 3.21C15.68 6.4 12.83 5 9.61 5 6.72 5 4.07 6.16 2 8l1.42 1.42C5.12 7.93 7.27 7 9.61 7c2.74 0 5.09 1.26 6.77 3.24l-2.88 3.24-4-4L2 16.99l1.5 1.5 6-6.01 4 4 4.05-4.55c.75 1.35 1.25 2.9 1.44 4.55H21c-.22-2.3-.95-4.39-2.04-6.14L22 6.92z"
}), 'MultilineChartOutlined');
exports.default = _default;
|
oliviertassinari/material-ui
|
packages/mui-icons-material/lib/MultilineChartOutlined.js
|
JavaScript
|
mit
| 733 |
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_ctgov_session'
|
tibbs001/ctgov
|
config/initializers/session_store.rb
|
Ruby
|
mit
| 137 |
import dateformat from 'dateformat';
import { map } from "underscore";
import { getAccountById } from 'routes/root/routes/Banking/routes/Accounts/modules/accounts';
import { getCreditCardById, getPrepaidCardById } from 'routes/root/routes/Banking/routes/Cards/modules/cards';
import { getLoanById } from 'routes/root/routes/Banking/routes/Loans/modules/loans';
export const getDebitAccount = (debitAccountType, debitAccountId) => {
switch (debitAccountType) {
case "isAccount":
getAccountById(debitAccountId)
break;
case "isLoan":
getLoanById(debitAccountId)
break;
case "isCreditCard":
getCreditCardById(debitAccountId)
break;
case "isPrepaidCard":
getPrepaidCardById(debitAccountId)
break;
}
}
const findDebitAccount = (debitAccountType, debitAccountId, state) => {
let debitAccount = {};
switch (debitAccountType) {
case "isAccount":
debitAccount = state.accounts.accounts.filter((account) => account.id == debitAccountId)[0]
break;
case "isLoan":
debitAccount = state.loans.loans.filter((loan) => loan.id == debitAccountId)[0]
break;
case "isCreditCard":
debitAccount = state.cards.creditCards.filter((creditCard) => creditCard.id == debitAccountId)[0]
break;
case "isPrepaidCard":
debitAccount = state.cards.prepaidCards.filter((prepaidCard) => prepaidCard.id == debitAccountId)[0]
break;
}
return debitAccount;
}
export const getDebitAccountAvailableBalance = (debitAccountType, debitAccountId, state) => {
const debitAccount = findDebitAccount(debitAccountType, debitAccountId, state);
return getProductAvailableBalance(debitAccount, debitAccountType);
}
export const getProductAvailableBalance = (debitAccount, debitAccountType) => {
let availableBalance = 0;
switch (debitAccountType) {
case "isAccount":
availableBalance = debitAccount.ledgerBalance;
break;
case "isLoan":
case "isCreditCard":
case "isPrepaidCard":
availableBalance = debitAccount.availableBalance;
break;
}
return availableBalance;
}
export const getDebitAccountCurrency = (debitAccountType, debitAccountId, state) => {
return findDebitAccount(debitAccountType, debitAccountId, state).currency;
}
export const isValidDate = (date) => {
return new Date(date).setHours(0,0,0,0) >= new Date(dateformat()).setHours(0,0,0,0)
}
export const isValidInstallmentPaymentAmount = (product, amount, availableBalance) => {
return amount > 0 &&
(parseFloat(amount) <= product.nextInstallmentAmount ||
parseFloat(amount) <= product.debt) &&
parseFloat(amount) <= availableBalance
}
export const isValidInstallmentPaymentForm = (transactionForm) => {
return transactionForm.debitAccount.correct &&
transactionForm.amount.correct &&
transactionForm.date.correct
}
export const getPaymentType = (paymentMethod) => {
let paymentType = '';
switch (paymentMethod) {
case 'ΚΑΡΤΑ AGILE BANK':
paymentType = 'isCreditCardAgile';
break;
case 'ΚΑΡΤΑ ΑΛΛΗΣ ΤΡΑΠΕΖΗΣ':
paymentType = 'isCreditCardThirdParty';
break;
case 'ΔΑΝΕΙΟ AGILE BANK':
paymentType = 'isLoan';
break;
default:
paymentType = 'thirdPartyPayment';
}
return paymentType;
}
export const getCustomerName = (fullCustomerName) => {
return (fullCustomerName.firstName + ' ' + fullCustomerName.lastName)
.replace('ά', 'α')
.replace('έ', 'ε')
.replace('ί', 'ι')
.replace('ή', 'η')
.replace('ό', 'ο')
.replace('ύ', 'υ')
.replace('ώ', 'ω');
}
export const getActualFullName = (fullName, currentFullName) => {
const correctPattern = new RegExp("^[A-Za-zΑ-Ωα-ω ]+$");
return fullName = (correctPattern.test(fullName) || fullName == '' ? fullName : currentFullName).toUpperCase();
}
export const isValidFullName = (fullName) => fullName.split(' ').length == 2
export const isValidDebitAmount = (amount, availableBalance) => {
return amount > 0 && (parseFloat(amount)) <= availableBalance
}
export const isValidChargesBeneficiary = (beneficiary) => {
return beneficiary == 'both' || beneficiary == 'sender' || beneficiary == 'beneficiary'
}
export const findPaymentCharges = (paymentMethods, paymentName) => {
return map(paymentMethods, (paymentMethod) => paymentMethod.map(method => method))
.flatMap(paymentMethod => paymentMethod)
.filter(payment => payment.name == paymentName)[0].charges
}
export const findTransferCharges = (beneficiary) => {
let charges = 0;
switch (beneficiary) {
case 'both':
charges = 3;
break;
case 'sender':
charges = 6;
break;
case 'beneficiary':
charges = 0;
break;
}
return charges;
}
export const getImmediateText = (language) => {
let immediateText = '';
switch (language) {
case 'greek':
immediateText = 'ΑΜΕΣΑ';
break;
case 'english':
immediateText = 'IMMEDIATE';
break;
}
return immediateText;
}
export const formatCardNumber = (cardNumber) => {
return [...cardNumber].map(((num, key) => key % 4 == 0 && key != 0 ? ' ' + num : num ))
}
|
GKotsovos/WebBanking-Front-End
|
src/routes/root/routes/Banking/routes/utils/commonUtils.js
|
JavaScript
|
mit
| 5,183 |
#include <iostream>
#include <map>
#include <stdexcept>
using namespace std;
int main(int argc, char* argv[]){
map<string, int> m;
m["bob"] = 56;
m["alice"] = 89;
m["billy"] = 3;
// print it out
map<string,int>::iterator i;
for(i = m.begin(); i != m.end(); i++){
cout << i->first << ": " << i->second << endl;
}
cout << "size: " << m.size() << endl << endl;
i = m.find("billy");
if(i == m.end()){
cout << "No billy!\n";
}else{
cout << i->first << ": " << i->second << endl;
}
return 0;
}
|
mikehelmick/teaching
|
uc/computerScience2/spring2014/materials/demos/wk14/map.cpp
|
C++
|
mit
| 524 |
This directory contains samples for VMC organization APIs:
Running the samples
$ python organization_operations.py -r <refresh_token>
* Testbed Requirement:
- At least one org associated with the calling user.
|
pgbidkar/vsphere-automation-sdk-python
|
samples/vmc/orgs/README.md
|
Markdown
|
mit
| 221 |
var assert = require('assert');
var num = require('../');
test('sub', function() {
assert.equal(num.sub(0, 0), '0');
assert.equal(num.sub('0', '-0'), '0');
assert.equal(num.sub('1.0', '-1.0'), '2.0');
assert.equal(num('987654321987654321.12345678901').sub(100.012), '987654321987654221.11145678901');
assert.equal(num(100.012).sub(num('987654321987654321.12345678901')), '-987654321987654221.11145678901');
});
test('sub#constness', function() {
var one = num(1.2);
var two = num(-1.2);
assert.equal(one, '1.2');
assert.equal(two, '-1.2');
one.sub(two);
assert.equal(one, '1.2');
assert.equal(two, '-1.2');
two.sub(one);
assert.equal(one, '1.2');
assert.equal(two, '-1.2');
});
|
Rebero/arbitrade
|
server/node_modules/num/test/sub.js
|
JavaScript
|
mit
| 745 |
require File.join(File.dirname(__FILE__), "/../spec_helper")
describe "Firefox" do
before(:each) do
@browser = Firefox.new
@url = "http://localhost"
end
describe "Cross OS Firefox", :shared => true do
it "should be supported" do
@browser.should be_supported
end
end
describe "Mac OS X" do
it_should_behave_like "Cross OS Firefox"
it "should have a path" do
expected = File.expand_path("/Applications/#{@browser.escaped_name}.app")
@browser.path.should == expected
end
it "return name" do
@browser.name.should == "Firefox"
end
it "should visit a given url" do
Kernel.expects(:system).with("open -a #{@browser.name} '#{@url}'")
@browser.visit(@url)
end
end if macos?
describe "Windows" do
it_should_behave_like "Cross OS Firefox"
it "should have a path" do
@browser.path.should == File.join(ENV['ProgramFiles'] || 'c:\Program Files', '\Mozilla Firefox\firefox.exe')
end
it "return name" do
@browser.name.should == "Firefox"
end
it "should visit a given url" do
Kernel.expects(:system).with("#{@browser.path} #{@url}")
@browser.visit(@url)
end
end if windows?
describe "Linux" do
it_should_behave_like "Cross OS Firefox"
it "should have a path" do
path = "/usr/bin/#{@browser.name}"
Firefox.new(path).path.should == path
end
it "should visit a given url" do
Kernel.expects(:system).with("#{@browser.name} #{@url}")
@browser.visit(@url)
end
it "return name" do
@browser.name.should == "firefox"
end
end if linux?
end
|
zfben/zfben_hanoi
|
spec/browsers/firefox_spec.rb
|
Ruby
|
mit
| 1,641 |
<?php
if (!$loader = @require_once __DIR__ . '/../vendor/autoload.php') {
die("You must set up the project dependencies, run the following commands:
wget http://getcomposer.org/composer.phar
php composer.phar install --dev --prefer-source
");
}
/* @var $loader \Composer\Autoload\ClassLoader */
$loader->add('Doctrine\Tests', __DIR__.'/../vendor/doctrine/orm/tests');
|
giosh94mhz/GeonamesBundle
|
Tests/bootstrap.php
|
PHP
|
mit
| 374 |
using System.ComponentModel;
namespace EncompassRest.Loans.Enums
{
/// <summary>
/// PropertyValuationMethodType
/// </summary>
public enum PropertyValuationMethodType
{
/// <summary>
/// Automated Valuation Model
/// </summary>
[Description("Automated Valuation Model")]
AutomatedValuationModel = 0,
/// <summary>
/// Desktop Appraisal
/// </summary>
[Description("Desktop Appraisal")]
DesktopAppraisal = 1,
/// <summary>
/// Drive By
/// </summary>
[Description("Drive By")]
DriveBy = 2,
/// <summary>
/// Estimation
/// </summary>
Estimation = 3,
/// <summary>
/// Full Appraisal
/// </summary>
[Description("Full Appraisal")]
FullAppraisal = 5,
/// <summary>
/// None
/// </summary>
None = 6,
/// <summary>
/// Other
/// </summary>
Other = 7,
/// <summary>
/// Prior Appraisal Used
/// </summary>
[Description("Prior Appraisal Used")]
PriorAppraisalUsed = 8
}
}
|
EncompassRest/EncompassRest
|
src/EncompassRest/Loans/Enums/PropertyValuationMethodType.cs
|
C#
|
mit
| 1,186 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.