code
stringlengths
2
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
991
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/* * Generated by class-dump 3.3.4 (64 bit). * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard. */ #import "NSObject.h" @class NSString, NSURL; // Not exported @interface _GEORegionalResourceDownload : NSObject { NSString *_name; long long _type; NSURL *_url; NSString *_destinationPath; NSString *_expectedChecksum; } @property(copy, nonatomic) NSString *expectedChecksum; // @synthesize expectedChecksum=_expectedChecksum; @property(copy, nonatomic) NSString *destinationPath; // @synthesize destinationPath=_destinationPath; @property(copy, nonatomic) NSURL *url; // @synthesize url=_url; @property(nonatomic) long long type; // @synthesize type=_type; @property(copy, nonatomic) NSString *name; // @synthesize name=_name; - (void)dealloc; @end
matthewsot/CocoaSharp
Headers/PrivateFrameworks/GeoServices/_GEORegionalResourceDownload.h
C
mit
816
name 'google_app_engine' description 'A cookbook to download and install the google app engine SDK on a Linux system.' version '1.0.0' maintainer 'Bernd Hoffmann' maintainer_email 'info@gebeat.com' license 'MIT' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
GeBeater/gae-cookbook
metadata.rb
Ruby
mit
325
TaskManager.module('ContentModule.List', function (List, App, Backbone) { 'use strict'; List.Controller = Marionette.Controller.extend({ initialize: function (options) { var tasksList = App.request('taskList'), listView = this.getView(tasksList); if (options.region) { this.region = options.region; this.listenTo(listView, this.close); this.region.show(listView); } }, getView: function (tasksList) { return new List.View({collection: tasksList}); } }); });
vlyahovich/Task-Manager
src/js/modules/content/list/listController.js
JavaScript
mit
499
namespace SharedWeekends.MVC.Areas.Administration.Controllers { using System.Web.Mvc; using SharedWeekends.Data; using SharedWeekends.MVC.Controllers; [Authorize(Roles = "admin")] public abstract class AdminController : BaseController { public AdminController(IWeekendsData data) : base(data) { } } }
kalinalazarova1/SharedWeekends
SharedWeekends.MVC/Areas/Administration/Controllers/AdminController.cs
C#
mit
369
# VisMod While the ultimate goal of VisMod is to assist in groundwater flow model visualization, the current classes support the export of files that can be used in visualization software such as [http://wci.llnl.gov/codes/visit/]. [![Animation created with VisIt from MODFLOW results](http://i.ytimg.com/vi/v12i04psF2c/mqdefault.jpg)] (http://www.youtube.com/watch?v=v12i04psF2c) ## Dependencies VisMod expects binary head output from modflow [http://water.usgs.gov/ogw/modflow/], and writes BOV (Brick of Values) files for visualization in VisIt [https://wci.llnl.gov/codes/visit/] Currently VisMod supports only uniform grid models (x and y dimensions can differ, but they cannot be variably spaced). ## Input requirements 1. Model layer to be exported for visualization 2. Model precision (single or double) 3. Model cell dimensions in the x and y directions 4. Origin of bottom left of the model grid (if unknown, any values will work) 5. Path and name of binary head output file from MODFLOW 6. Output path for BOV files ## Outputs 1. BOV file for each timestep or stress period specifed as 'SAVE HEAD' in the MODFLOW OC (output control) file. 2. .visit file for use in VisIt, which contains the name of each BOV file produced by VisMod - useful for time series animations ## Workflow 1. Ensure that visMod.py and runVisMod.py exist in the same directory 2. Modify user variables in runVisMod.py 3. Ensure output path exists Example call to class to format MODFLOW heads for VisIt-- ``` origin=[0.0,0.0] #origin of bottom left corner xdim=2000 #cell dimension in the x direction ydim=1000 #cell dimension in the y direction layer=1 #layer to be exported precision='single' #single or double headsfile='MF2005.1_11/test-run/tr2k_s3.hed' outpath='MF2005.1_11/MF2005.1_11/test-run/visit/' v=vm.visMod(layer,precision,xdim,ydim,origin,headsfile,outpath) v.BOVheads() ``` #visGIS visGIS utility tools to visualize GIS files in visualization. Currently one class is included to convert a shapefile of contours into a continous grid in ASCII DEM format. ## Dependencies VisGIS expects a line shapefile with an attribute of values (normally to represent altitude of water table or land surface) and writes a .dem file (ASCII DEM format) files for visualization in VisIt [https://wci.llnl.gov/codes/visit/] VisGIS has been tested with python (x,y) with GDAL installed. required modules are osgeo, numpy, and scipy ## Input requirements 1. Line shapefile with attribute of elevations 2. Output grid cell size 3. Path and name of dem output file ## Outputs 1. ASCII DEM file ## Workflow Example data from [http://www.swfwmd.state.fl.us/data/gis/layer_library/category/potmaps] Example call to class to interpolate shapefile of contours ``` import visGIS as vg c2g=vg.shpTools('may75fl_line.shp', 'may75fl.dem','M75FLEL',500) c2g.getVerts() #required for interp2dem c2g.interp2dem() ```
fluidmotion/visTools
README.md
Markdown
mit
2,930
'use strict'; var Project = require('ember-cli/lib/models/project'); function MockProject() { var root = process.cwd(); var pkg = {}; Project.apply(this, [root, pkg]); } MockProject.prototype.require = function(file) { if (file === './server') { return function() { return { listen: function() { arguments[arguments.length-1](); } }; }; } }; MockProject.prototype.config = function() { return this._config || { baseURL: '/', locationType: 'auto' }; }; MockProject.prototype.has = function(key) { return (/server/.test(key)); }; MockProject.prototype.name = function() { return 'mock-project'; }; MockProject.prototype.initializeAddons = Project.prototype.initializeAddons; MockProject.prototype.buildAddonPackages = Project.prototype.buildAddonPackages; MockProject.prototype.discoverAddons = Project.prototype.discoverAddons; MockProject.prototype.addIfAddon = Project.prototype.addIfAddon; MockProject.prototype.setupBowerDirectory = Project.prototype.setupBowerDirectory; MockProject.prototype.dependencies = function() { return []; }; MockProject.prototype.isEmberCLIAddon = function() { return false; }; module.exports = MockProject;
mattjmorrison/ember-cli-testem
tests/helpers/mock-project.js
JavaScript
mit
1,206
<!DOCTYPE html> <html lang="en" ng-app="App"> <head> <meta charset="UTF-8"> <title>form</title> <link rel="stylesheet" href="../../js/lib/bootstrap/dist/css/bootstrap.min.css"> <style> .container { margin-top: 30px; } </style> </head> <body ng-controller="MyCtrl"> <div class="container"> <div class="row"> <div class="col-md-12"> <form class="form-horizontal" role="form"> <div class="form-group"> <div class="col-sm-2">honors</div> <div class="col-sm-8"> <!-- 从默认数据 model.setting.honors 里面读值 --> <div ng-repeat="honor in model.setting.honors" class="checkbox"> <label> <!-- 被选中的复选框的值(boolean)会直接赋给 model.postData.honors --> <input ng-model="model.postData.honors[$index].value" ng-checked="model.postData.honors[$index].value" ng-value="honor.value" type="checkbox">{{ honor.name }} </label> </div> <p class="small">{{ model.postData.honors }}</p> </div> </div> </form> </div> </div> </div> <script src="../../js/lib/jquery/dist/jquery.min.js"></script> <script src="../../js/lib/bootstrap/dist/js/bootstrap.min.js"></script> <script src="../../js/lib/angular-v1.4.8/angular.min.js"></script> <script> var app = angular.module('App', []); app .controller('MyCtrl', function($scope){ var vm = $scope; vm.model = { setting: { honors: [ { name: 'AllStar', value: 0 },{ name: 'Champion', value: 1 },{ name: 'FMVP', value: 2 } ] }, postData: { // honors: null, honors: [ {value: false}, {value: true}, {value: true} ] } }; }); </script> </body> </html>
GreenMelon/Angular-Notes
app/html/Form/checkbox-001.html
HTML
mit
2,186
import _curry2 from "./_curry2"; /** * Accepts an object and build a function expecting a key to create a "pair" with the key * and its value. * @private * @function * @param {Object} obj * @returns {Function} */ var _keyToPairIn = _curry2(function (obj, key) { return [key, obj[key]]; }); export default _keyToPairIn;
ascartabelli/lamb
src/privates/_keyToPairIn.js
JavaScript
mit
332
//------------------------------------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // // CHeapPtr for VB // //------------------------------------------------------------------------------------------------- #pragma once template <typename T> class VBHeapPtr : public CHeapPtrBase<T, VBAllocator> { public: VBHeapPtr() throw() : CHeapPtrBase<T, VBAllocator>() { } VBHeapPtr(VBHeapPtr<T>& p) throw() : CHeapPtrBase<T, VBAllocator>(p) { } explicit VBHeapPtr(T* p) throw() : CHeapPtrBase<T, VBAllocator>(p) { } explicit VBHeapPtr(size_t elements) { Allocate(elements); } VBHeapPtr<T>& operator=(VBHeapPtr<T>& p) throw() { CHeapPtrBase<T, VBStandardallocator>::operator=(p); return *this; } // Allocate a buffer with the given number of elements. Allocator // will succeed or throw void Allocate(size_t nElements = 1) throw() { SafeInt<size_t> total = nElements; total *= sizeof(T); // Uses VBAllocator::Allocate which will succeed or throw AllocateBytes(total.Value()); } // Reallocate the buffer to hold a given number of elements. Allocator // will succeed or throw void Reallocate(size_t nElements) throw() { SafeInt<size_t> total = nElements; total *= sizeof(T); // Uses VBAllocator::Allocate which will succeed or throw ReallocateBytes(total.Value()); } };
mind0n/hive
Cache/Libs/net46/vb/language/shared/vbheapptr.h
C
mit
1,561
'use strict'; /** * The basic http module, used to create the server. * * @link http://nodejs.org/api/http.html */ alchemy.use('http', 'http'); /** * This module contains utilities for handling and transforming file paths. * Almost all these methods perform only string transformations. * The file system is not consulted to check whether paths are valid. * * @link http://nodejs.org/api/path.html */ alchemy.use('path', 'path'); /** * File I/O is provided by simple wrappers around standard POSIX functions. * * @link http://nodejs.org/api/fs.html */ alchemy.use('graceful-fs', 'fs'); /** * Usefull utilities. * * @link http://nodejs.org/api/util.html */ alchemy.use('util', 'util'); /** * The native mongodb library * * @link https://npmjs.org/package/mongodb */ alchemy.use('mongodb', 'mongodb'); /** * The LESS interpreter. * * @link https://npmjs.org/package/less */ alchemy.use('less', 'less'); /** * Hawkejs view engine * * @link https://npmjs.org/package/hawkejs */ alchemy.use('hawkejs', 'hawkejs'); alchemy.hawkejs = new Classes.Hawkejs.Hawkejs; /** * The function to detect when everything is too busy */ alchemy.toobusy = alchemy.use('toobusy-js', 'toobusy'); // If the config is a number, use that as the lag threshold if (typeof alchemy.settings.toobusy === 'number') { alchemy.toobusy.maxLag(alchemy.settings.toobusy); } /** * Load Sputnik, the stage-based launcher */ alchemy.sputnik = new (alchemy.use('sputnik', 'sputnik'))(); /** * Real-time apps made cross-browser & easy with a WebSocket-like API. * * @link https://npmjs.org/package/socket.io */ alchemy.use('socket.io', 'io'); /** * Recursively mkdir, like `mkdir -p`. * This is a requirement fetched from express * * @link https://npmjs.org/package/mkdirp */ alchemy.use('mkdirp', 'mkdirp'); /** * Base useragent library * * @link https://npmjs.org/package/useragent */ alchemy.use('useragent'); /** * Enable the `satisfies` method in the `useragent` library * * @link https://www.npmjs.com/package/useragent#adding-more-features-to-the-useragent */ require('useragent/features');
skerit/alchemy
lib/init/requirements.js
JavaScript
mit
2,142
package com.eaw1805.data.model.map; import com.eaw1805.data.constants.RegionConstants; import com.eaw1805.data.model.Game; import java.io.Serializable; /** * Represents a region of the world. */ public class Region implements Serializable { /** * Required by Serializable interface. */ static final long serialVersionUID = 42L; //NOPMD /** * Region's identification number. */ private int id; // NOPMD /** * Region's code. */ private char code; /** * The name of the region. */ private String name; /** * The game this region belongs to. */ private Game game; /** * Default constructor. */ public Region() { // Empty constructor } /** * Get the Identification number of the region. * * @return the identification number of the region. */ public int getId() { return id; } /** * Set the Identification number of the region. * * @param identity the identification number of the region. */ public void setId(final int identity) { this.id = identity; } /** * Get the name of the region. * * @return the name of the region. */ public String getName() { return name; } /** * Set the thisName of the region. * * @param thisName the name of the region. */ public void setName(final String thisName) { this.name = thisName; } /** * Get the Single-char code of the region. * * @return the Single-char code of the region. */ public char getCode() { return code; } /** * Set the single-char code of the region. * * @param thisCode the single-char code of the region. */ public void setCode(final char thisCode) { this.code = thisCode; } /** * Get the game this region belongs to. * * @return The game of the region. */ public Game getGame() { return game; } /** * Set the game this region belongs to. * * @param value The game. */ public void setGame(final Game value) { this.game = value; } /** * Indicates whether some other object is "equal to" this one. * The <code>equals</code> method implements an equivalence relation * on non-null object references: * <ul> * <li>It is <i>reflexive</i>: for any non-null reference value * <code>x</code>, <code>x.equals(x)</code> should return * <code>true</code>. * <li>It is <i>symmetric</i>: for any non-null reference values * <code>x</code> and <code>y</code>, <code>x.equals(y)</code> * should return <code>true</code> if and only if * <code>y.equals(x)</code> returns <code>true</code>. * <li>It is <i>transitive</i>: for any non-null reference values * <code>x</code>, <code>y</code>, and <code>z</code>, if * <code>x.equals(y)</code> returns <code>true</code> and * <code>y.equals(z)</code> returns <code>true</code>, then * <code>x.equals(z)</code> should return <code>true</code>. * <li>It is <i>consistent</i>: for any non-null reference values * <code>x</code> and <code>y</code>, multiple invocations of * <tt>x.equals(y)</tt> consistently return <code>true</code> * or consistently return <code>false</code>, provided no * information used in <code>equals</code> comparisons on the * objects is modified. * <li>For any non-null reference value <code>x</code>, * <code>x.equals(null)</code> should return <code>false</code>. * </ul> * The <tt>equals</tt> method for class <code>Object</code> implements * the most discriminating possible equivalence relation on objects; * that is, for any non-null reference values <code>x</code> and * <code>y</code>, this method returns <code>true</code> if and only * if <code>x</code> and <code>y</code> refer to the same object * (<code>x == y</code> has the value <code>true</code>). * Note that it is generally necessary to override the <tt>hashCode</tt> * method whenever this method is overridden, so as to maintain the * general contract for the <tt>hashCode</tt> method, which states * that equal objects must have equal hash codes. * * @param obj the reference object with which to compare. * @return <code>true</code> if this object is the same as the obj * argument; <code>false</code> otherwise. * @see #hashCode() * @see java.util.Hashtable */ @Override public boolean equals(final Object obj) { if (obj == null) { return false; } if (!(obj instanceof Region)) { return false; } final Region region = (Region) obj; if (code != region.code) { return false; } if (id != region.id) { return false; } if (name != null ? !name.equals(region.name) : region.name != null) { return false; } return true; } /** * Returns a hash code value for the object. This method is * supported for the benefit of hashtables such as those provided by * <code>java.util.Hashtable</code>. * The general contract of <code>hashCode</code> is: * <ul> * <li>Whenever it is invoked on the same object more than once during * an execution of a Java application, the <tt>hashCode</tt> method * must consistently return the same integer, provided no information * used in <tt>equals</tt> comparisons on the object is modified. * This integer need not remain consistent from one execution of an * application to another execution of the same application. * <li>If two objects are equal according to the <tt>equals(Object)</tt> * method, then calling the <code>hashCode</code> method on each of * the two objects must produce the same integer result. * <li>It is <em>not</em> required that if two objects are unequal * according to the {@link java.lang.Object#equals(java.lang.Object)} * method, then calling the <tt>hashCode</tt> method on each of the * two objects must produce distinct integer results. However, the * programmer should be aware that producing distinct integer results * for unequal objects may improve the performance of hashtables. * </ul> * As much as is reasonably practical, the hashCode method defined by * class <tt>Object</tt> does return distinct integers for distinct * objects. (This is typically implemented by converting the internal * address of the object into an integer, but this implementation * technique is not required by the * Java<font size="-2"><sup>TM</sup></font> programming language.) * * @return a hash code value for this object. * @see java.lang.Object#equals(java.lang.Object) * @see java.util.Hashtable */ @Override public int hashCode() { return id; } @Override public String toString() { final StringBuilder sbld = new StringBuilder(); switch (id) { case RegionConstants.EUROPE: sbld.append("E"); break; case RegionConstants.CARIBBEAN: sbld.append("C"); break; case RegionConstants.INDIES: sbld.append("I"); break; case RegionConstants.AFRICA: sbld.append("A"); break; default: break; } return sbld.toString(); } }
EaW1805/data
src/main/java/com/eaw1805/data/model/map/Region.java
Java
mit
7,717
h1 { /* inline || block || */ display: inline; /* padding-box || border-box */ box-sizing: content-box; padding: 0; margin: 0; } /* Important Auto */ .auto-parent { width: 500px; } .auto-child { /* With Auto Width - it will fill up to take all the remaining space - 400 px */ margin-left: auto; width: auto; margin-right: 100px; } .three-autos-child { /* With all 3 the Width is taking all the space - 500px */ margin-left: auto; width: auto; margin-right: auto; }
i-den/SoftwareUniversity
Front End Courses/03. CSS - Def Guide/07. Basic Visual Formatting/01. Basic Visual Formatting.css
CSS
mit
529
```js var PlistUtils = (function() { function readTextFile(strPath) { var error; var str = ObjC.unwrap( $.NSString.stringWithContentsOfFileEncodingError( $(strPath).stringByStandardizingPath, $.NSUTF8StringEncoding, error ) ); if (error) throw Error('Could not read file "' + strPath + '"'); return str; } return { convertPlistPartToString: function(plistPart) { var data = $.NSPropertyListSerialization.dataWithPropertyListFormatOptionsError( $(plistPart), $.NSPropertyListXMLFormat_v1_0, 0, null); var nsstring = $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding); return $(nsstring).js; }, convertStringToPlist: function(str) { return ObjC.deepUnwrap( $.NSPropertyListSerialization.propertyListWithDataOptionsFormatError( $(str).dataUsingEncoding($.NSUTF8StringEncoding), 0, 0, null)); }, createEmptyGroupAction: function(actionName) { return this.convertStringToPlist( "<plist version='1.0'> \n" + "<dict> \n" + " <key>" + (actionName || "") + "</key> \n" + " <string>Installer</string> \n" + " <key>Actions</key> \n" + " <array/> \n" + " <key>MacroActionType</key> \n" + " <string>Group</string> \n" + " <key>TimeOutAbortsMacro</key> \n" + " <true/> \n" + "</dict> \n" + "</plist>"); }, getInitialCommentFromMacro: function(macro) { var results = []; if (!macro.Actions || macro.Actions.length === 0) return null; var action = macro.Actions[0]; if (action.MacroActionType !== "Comment") return null; return { name: action.ActionName || action.Title || "", title: action.Title || "", text: action.Text || "" }; }, // File must contain one macro only, or exception is thrown. getMacroFromKMMacrosFile: function(path) { var plist = this.readPlistArrayTextFile(path); if (!plist) throw Error("Could not read file '" + path + "'"); if (plist.length === 0) throw Error("No macros were found in '" + path + "'"); if (plist.length > 1) throw Error("Multiple macros were found in '" + path + "'"); var group = plist[0]; if (!group.Macros || group.Macros.count === 0) throw Error("No macros were found in '" + path + "'"); if (group.Macros.length > 1) throw Error("Multiple macros were found in '" + path + "'"); return group.Macros[0]; }, readPlistArrayTextFile: function(strPath) { // var str = readTextFile(strPath); // return this.convertStringToPlist(str); var strFullPath = $(strPath).stringByStandardizingPath; return ObjC.deepUnwrap($.NSArray.arrayWithContentsOfFile(strFullPath)); }, readPlistBinaryFile: function(path) { var data = $.NSData.dataWithContentsOfFile(path); return ObjC.deepUnwrap( $.NSPropertyListSerialization.propertyListWithDataOptionsFormatError( data, $.NSPropertyListBinaryFormat_v1_0, 0, null)); }, readPlistDictionaryTextFile: function(strPath) { var strFullPath = $(strPath).stringByStandardizingPath; return ObjC.deepUnwrap($.NSDictionary.dictionaryWithContentsOfFile(strFullPath)); }, writePlistTextFile: function(plist, strPath) { var str = this.convertPlistPartToString(plist); $(str).writeToFileAtomically($(strPath).stringByStandardizingPath, true); } }; })(); ```
dagware/DanThomas
JXA/PlistUtils.md
Markdown
mit
3,298
/** * Copyright (c) 2015, Alexander Orzechowski. * * 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. */ /** * Currently in beta stage. Changes can and will be made to the core mechanic * making this not backwards compatible. * * Github: https://github.com/Need4Speed402/tessellator */ Tessellator.Model.prototype.drawObject = Tessellator.Model.prototype.add;
Need4Speed402/tessellator
src/model/modules/DrawObject.js
JavaScript
mit
1,391
#!-*- coding:utf-8 -*- import time def retries(times=3, timeout=1): """对未捕获异常进行重试""" def decorator(func): def _wrapper(*args, **kw): att, retry = 0, 0 while retry < times: retry += 1 try: return func(*args, **kw) except: att += timeout if retry < times: time.sleep(att) return _wrapper return decorator def empty_content_retries(times=3, timeout=2): """响应为空的进行重试""" def decorator(func): def _wrapper(*args, **kw): att, retry = 0, 0 while retry < times: retry += 1 ret = func(*args, **kw) if ret: return ret att += timeout time.sleep(att) return _wrapper return decorator def use_logging(level): """带参数的装饰器""" def decorator(func): print func.__name__ def wrapper(*args, **kwargs): if level == "warn": print ("level:%s, %s is running" % (level, func.__name__)) elif level == "info": print ("level:%s, %s is running" % (level, func.__name__)) return func(*args, **kwargs) return wrapper return decorator if __name__ == "__main__": @use_logging(level="warn") def foo(name='foo'): print("i am %s" % name) foo()
wanghuafeng/spider_tools
decorator.py
Python
mit
1,524
# BKAsciiImage [![Version](https://img.shields.io/cocoapods/v/BKAsciiImage.svg?style=flat)](http://cocoapods.org/pods/BKAsciiImage) [![License](https://img.shields.io/cocoapods/l/BKAsciiImage.svg?style=flat)](http://cocoapods.org/pods/BKAsciiImage) [![Platform](https://img.shields.io/cocoapods/p/BKAsciiImage.svg?style=flat)](http://cocoapods.org/pods/BKAsciiImage) ![Example gif image](./Screenshots/example.gif) ### As seen on Cmd.fm iOS App https://itunes.apple.com/app/cmd.fm-radio-for-geeks-hackers/id935765356 ![Cmd.fm screenshot 1](./Screenshots/cmdfm_01.jpg) ![Cmd.fm screenshot 2](./Screenshots/cmdfm_02.jpg) ## Installation BKAsciiImage is available through [CocoaPods](http://cocoapods.org). To install it, simply add the following line to your Podfile: ```ruby pod "BKAsciiImage" ``` ## Usage ### Using BKAsciiConverter class Import BKAsciiConverter header file ```objective-c #import <BKAsciiImage/BKAsciiConverter.h> ``` Create a BKAsciiConverter instance ```objective-c BKAsciiConverter *converter = [BKAsciiConverter new]; ``` Convert synchronously ```objective-c UIImage *inputImage = [UIImage imageNamed:@"anImage"]; UIImage *asciiImage = [converter convertImage:inputImage]; ``` Convert in the background providing a completion block. Completion block will be called on the main thread. ```objective-c [converter convertImage:self.inputImage completionHandler:^(UIImage *asciiImage) { // do whatever you want with the resulting asciiImage }]; ``` Convert to NSString ```objective-c NSLog(@"%@",[converter convertToString:self.inputImage]); // asynchronous [converter convertToString:self.inputImage completionHandler:^(NSString *asciiString) { NSLog(@"%@",asciiString); }]; ``` #### Converter options ```objective-c converter.backgroundColor = [UIColor whiteColor]; // default: Clear color. Image background is transparent converter.grayscale = YES; // default: NO converter.font = [UIFont fontWithName:@"Monaco" size:13.0]; // default: System font of size 10 converter.reversedLuminance = NO; // Reverses the luminance mapping. Reversing gives better results on a dark bg. default: YES converter.columns = 50; // By default columns is derived by the font size if not set explicitly ``` ### Using UIImage category Import header file ```objective-c #import <BKAsciiImage/UIImage+BKAscii.h> ``` Use the provided category methods ```objective-c UIImage *inputImage = [UIImage imageNamed:@"anImage"]; [inputImage bk_asciiImageCompletionHandler:^(UIImage *asciiImage) { }]; [inputImage bk_asciiStringCompletionHandler:^(NSString *asciiString) { }]; [inputImage bk_asciiImageWithFont: [UIFont fontWithName:@"Monaco" size:13.0] bgColor: [UIColor redColor]; columns: 30 reversed: YES grayscale: NO completionHandler: ^(NSString *asciiString) { // do whatever you want with the resulting asciiImage }]; ``` ## Advanced usage By default luminance values are mapped to strings using ```objective-c NSDictionary *dictionary = @{ @1.0: @" ", @0.95:@"`", @0.92:@".", @0.9 :@",", @0.8 :@"-", @0.75:@"~", @0.7 :@"+", @0.65:@"<", @0.6 :@">", @0.55:@"o", @0.5 :@"=", @0.35:@"*", @0.3 :@"%", @0.1 :@"X", @0.0 :@"@" }; ``` You can instantiate a converter with your own mapping dictionary ```objective-c NSDictionary *dictionary = @{ @1.0: @" ", @0.7 :@"a", @0.65:@"b", @0.6 :@"c", @0.55:@"d", @0.5 :@"e", @0.35:@"f", @0.3 :@"g", @0.1 :@" ", @0.0 :@" " }; BKAsciiConverter *converter = [[BKAsciiConverter alloc] initWithDictionary:dictionary]; UIImage *inputImage = [UIImage imageNamed:@"anImage"]; UIImage *asciiImage = [converter convertImage:inputImage]; ``` ![Mapping example screenshot](./Screenshots/mappingExample.jpg) ## Author Barış Koç, https://github.com/bkoc ## License BKAsciiImage is available under the MIT license. See the LICENSE file for more info.
bkoc/BKAsciiImage
README.md
Markdown
mit
4,737
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="author" content="Ginolhac"> <meta name="generator" content="Hugo 0.42.1" /> <title>Posts &middot; Aurélien&#39; blog</title> <link rel="shortcut icon" href="//ginolhac.github.io/images/favicon.ico"> <link rel="stylesheet" href="//ginolhac.github.io/css/style.css"> <link rel="stylesheet" href="//ginolhac.github.io/css/highlight.css"> <link href="//ginolhac.github.io/styles/github.min.css" rel="stylesheet"> <link rel="stylesheet" href="//ginolhac.github.io/css/font-awesome.min.css"> </head> <body> <nav class="main-nav"> <a href='//ginolhac.github.io/'> <span class="arrow">←</span>Home</a> <a href='//ginolhac.github.io/posts'>Archive</a> <a href='//ginolhac.github.io/karate'>Karate</a> <a href='//ginolhac.github.io/tags'>Tags</a> <a href='//ginolhac.github.io/about'>About</a> </nav> <div class="profile"> <section id="wrapper"> <header id="header"> <a href='//ginolhac.github.io/about'> <img id="avatar" class="2x" src="//ginolhac.github.io/images/avatar.png"/> </a> <h1>Aurélien&#39; blog</h1> <h2>bioinformatic and data science</h2> </header> </section> </div> <section id="wrapper" class="home"> <div class="archive"> <h3>2018</h3> <ul> <div class="post-item"> <div class="post-time">Mar 26</div> <a href="//ginolhac.github.io/posts/latex-modern-cv/" class="post-link"> LaTex modern CV </a> </div> <div class="post-item"> <div class="post-time">Jan 27</div> <a href="//ginolhac.github.io/posts/diy-raspberry-monitored-via-telegram/" class="post-link"> home surveillance monitored via telegram </a> </div> </ul> </div> <div class="archive"> <h3>2016</h3> <ul> <div class="post-item"> <div class="post-time">Dec 8</div> <a href="//ginolhac.github.io/posts/tweening-a-poisson-distribution/" class="post-link"> tweening a Poisson distribution </a> </div> <div class="post-item"> <div class="post-time">Jul 31</div> <a href="//ginolhac.github.io/posts/teething-process/" class="post-link"> teething </a> </div> </ul> </div> <div class="archive"> <h3>2015</h3> <ul> <div class="post-item"> <div class="post-time">Jan 25</div> <a href="//ginolhac.github.io/posts/winter-is-coming/" class="post-link"> winter is coming </a> </div> </ul> </div> <footer id="footer"> <div id="social"> <a class="symbol" href="https://github.com/ginolhac"> <i class="fa fa-github-square"></i> </a> <a class="symbol" href="https://www.linkedin.com/in/aur%c3%a9lien-ginolhac-07b33b92/"> <i class="fa fa-linkedin-square"></i> </a> <a class="symbol" href="https://twitter.com/kingsushigino"> <i class="fa fa-twitter-square"></i> </a> </div> <p class="small"> © Copyright 2021 <i class="fa fa-heart" aria-hidden="true"></i> Ginolhac </p> <p class="small"> Powered by <a href="//www.gohugo.io/">Hugo</a> Theme By <a href="https://github.com/nodejh/hugo-theme-cactus-plus">nodejh</a> </p> <script src="//yihui.name/js/math-code.js"></script> <script async src="//cdn.bootcss.com/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML"> </script> <script src="//ginolhac.github.io/highlight.min.js"></script> <script src="//ginolhac.github.io/languages/r.min.js"></script> <script> hljs.configure({languages: []}); hljs.initHighlightingOnLoad(); </script> </footer> </section> <div class="dd"> </div> <script src="//ginolhac.github.io/js/jquery-3.3.1.min.js"></script> <script src="//ginolhac.github.io/js/main.js"></script> <script src="//ginolhac.github.io/js/highlight.min.js"></script> <script>hljs.initHighlightingOnLoad();</script> <script> var doNotTrack = false; if (!doNotTrack) { (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-29962051-1', 'auto'); ga('send', 'pageview'); } </script> </body> </html>
ginolhac/ginolhac.github.com
posts/index.html
HTML
mit
4,782
{% from "components/table.html" import list_table, field, right_aligned_field_heading, row_heading, notification_status_field %} {% from "components/page-footer.html" import page_footer %} <div class="ajax-block-container" aria-labelledby='pill-selected-item'> <div class="dashboard-table bottom-gutter-3-2"> {% call(item, row_number) list_table( [notification], caption=None, caption_visible=False, empty_message=None, field_headings=[ 'Recipient', 'Status' ], field_headings_visible=False ) %} {% call row_heading() %} <p class="govuk-body">{{ item.to }}</p> {% endcall %} {{ notification_status_field(item) }} {% endcall %} {% if more_than_one_page %} <p class="table-show-more-link"> Only showing the first 50 rows </p> {% endif %} </div> </div>
alphagov/notifications-admin
app/templates/partials/notifications/notifications.html
HTML
mit
840
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <meta name="collection" content="api"> <!-- Generated by javadoc (build 1.5.0-rc) on Wed Aug 11 07:27:53 PDT 2004 --> <TITLE> Binding (Java 2 Platform SE 5.0) </TITLE> <META NAME="keywords" CONTENT="org.omg.CosNaming.Binding class"> <META NAME="keywords" CONTENT="binding_name"> <META NAME="keywords" CONTENT="binding_type"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Binding (Java 2 Platform SE 5.0)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Binding.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <b>Java<sup><font size=-2>TM</font></sup>&nbsp;2&nbsp;Platform<br>Standard&nbsp;Ed. 5.0</b></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../org/omg/CosNaming/_NamingContextStub.html" title="class in org.omg.CosNaming"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../org/omg/CosNaming/BindingHelper.html" title="class in org.omg.CosNaming"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?org/omg/CosNaming/Binding.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Binding.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#methods_inherited_from_class_java.lang.Object">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;METHOD</FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> org.omg.CosNaming</FONT> <BR> Class Binding</H2> <PRE> <A HREF="../../../java/lang/Object.html" title="class in java.lang">java.lang.Object</A> <IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>org.omg.CosNaming.Binding</B> </PRE> <DL> <DT><B>All Implemented Interfaces:</B> <DD><A HREF="../../../java/io/Serializable.html" title="interface in java.io">Serializable</A>, <A HREF="../../../org/omg/CORBA/portable/IDLEntity.html" title="interface in org.omg.CORBA.portable">IDLEntity</A></DD> </DL> <HR> <DL> <DT><PRE>public final class <B>Binding</B><DT>extends <A HREF="../../../java/lang/Object.html" title="class in java.lang">Object</A><DT>implements <A HREF="../../../org/omg/CORBA/portable/IDLEntity.html" title="interface in org.omg.CORBA.portable">IDLEntity</A></DL> </PRE> <P> org/omg/CosNaming/Binding.java . Generated by the IDL-to-Java compiler (portable), version "3.2" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Wednesday, August 11, 2004 5:04:12 AM GMT-08:00 <P> <P> <DL> <DT><B>See Also:</B><DD><A HREF="../../../serialized-form.html#org.omg.CosNaming.Binding">Serialized Form</A></DL> <HR> <P> <!-- =========== FIELD SUMMARY =========== --> <A NAME="field_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Field Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../org/omg/CosNaming/NameComponent.html" title="class in org.omg.CosNaming">NameComponent</A>[]</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../org/omg/CosNaming/Binding.html#binding_name">binding_name</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../org/omg/CosNaming/BindingType.html" title="class in org.omg.CosNaming">BindingType</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../org/omg/CosNaming/Binding.html#binding_type">binding_type</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../org/omg/CosNaming/Binding.html#Binding()">Binding</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../org/omg/CosNaming/Binding.html#Binding(org.omg.CosNaming.NameComponent[], org.omg.CosNaming.BindingType)">Binding</A></B>(<A HREF="../../../org/omg/CosNaming/NameComponent.html" title="class in org.omg.CosNaming">NameComponent</A>[]&nbsp;_binding_name, <A HREF="../../../org/omg/CosNaming/BindingType.html" title="class in org.omg.CosNaming">BindingType</A>&nbsp;_binding_type)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.<A HREF="../../../java/lang/Object.html" title="class in java.lang">Object</A></B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="../../../java/lang/Object.html#clone()">clone</A>, <A HREF="../../../java/lang/Object.html#equals(java.lang.Object)">equals</A>, <A HREF="../../../java/lang/Object.html#finalize()">finalize</A>, <A HREF="../../../java/lang/Object.html#getClass()">getClass</A>, <A HREF="../../../java/lang/Object.html#hashCode()">hashCode</A>, <A HREF="../../../java/lang/Object.html#notify()">notify</A>, <A HREF="../../../java/lang/Object.html#notifyAll()">notifyAll</A>, <A HREF="../../../java/lang/Object.html#toString()">toString</A>, <A HREF="../../../java/lang/Object.html#wait()">wait</A>, <A HREF="../../../java/lang/Object.html#wait(long)">wait</A>, <A HREF="../../../java/lang/Object.html#wait(long, int)">wait</A></CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <A NAME="field_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Field Detail</B></FONT></TH> </TR> </TABLE> <A NAME="binding_name"><!-- --></A><H3> binding_name</H3> <PRE> public <A HREF="../../../org/omg/CosNaming/NameComponent.html" title="class in org.omg.CosNaming">NameComponent</A>[] <B>binding_name</B></PRE> <DL> <DL> </DL> </DL> <HR> <A NAME="binding_type"><!-- --></A><H3> binding_type</H3> <PRE> public <A HREF="../../../org/omg/CosNaming/BindingType.html" title="class in org.omg.CosNaming">BindingType</A> <B>binding_type</B></PRE> <DL> <DL> </DL> </DL> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="Binding()"><!-- --></A><H3> Binding</H3> <PRE> public <B>Binding</B>()</PRE> <DL> </DL> <HR> <A NAME="Binding(org.omg.CosNaming.NameComponent[], org.omg.CosNaming.BindingType)"><!-- --></A><H3> Binding</H3> <PRE> public <B>Binding</B>(<A HREF="../../../org/omg/CosNaming/NameComponent.html" title="class in org.omg.CosNaming">NameComponent</A>[]&nbsp;_binding_name, <A HREF="../../../org/omg/CosNaming/BindingType.html" title="class in org.omg.CosNaming">BindingType</A>&nbsp;_binding_type)</PRE> <DL> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Binding.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <b>Java<sup><font size=-2>TM</font></sup>&nbsp;2&nbsp;Platform<br>Standard&nbsp;Ed. 5.0</b></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../org/omg/CosNaming/_NamingContextStub.html" title="class in org.omg.CosNaming"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../org/omg/CosNaming/BindingHelper.html" title="class in org.omg.CosNaming"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?org/omg/CosNaming/Binding.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Binding.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#methods_inherited_from_class_java.lang.Object">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;METHOD</FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <font size="-1"><a href="http://java.sun.com/cgi-bin/bugreport.cgi">Submit a bug or feature</a><br>For further API reference and developer documentation, see <a href="../../../../relnotes/devdocs-vs-specs.html">Java 2 SDK SE Developer Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples. <p>Copyright &#169; 2004, 2010 Oracle and/or its affiliates. All rights reserved. Use is subject to <a href="../../../../relnotes/license.html">license terms</a>. Also see the <a href="http://java.sun.com/docs/redist.html">documentation redistribution policy</a>.</font> <!-- Start SiteCatalyst code --> <script language="JavaScript" src="http://www.oracle.com/ocom/groups/systemobject/@mktg_admin/documents/systemobject/s_code_download.js"></script> <script language="JavaScript" src="http://www.oracle.com/ocom/groups/systemobject/@mktg_admin/documents/systemobject/s_code.js"></script> <!-- ********** DO NOT ALTER ANYTHING BELOW THIS LINE ! *********** --> <!-- Below code will send the info to Omniture server --> <script language="javascript">var s_code=s.t();if(s_code)document.write(s_code)</script> <!-- End SiteCatalyst code --> </body> </HTML>
Smolations/more-dash-docsets
docsets/Java 5.docset/Contents/Resources/Documents/org/omg/CosNaming/Binding.html
HTML
mit
14,943
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>V8 API Reference Guide for node.js v8.10.0: Class Members</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v8.10.0 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li class="current"><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li class="current"><a href="functions.html"><span>All</span></a></li> <li><a href="functions_func.html"><span>Functions</span></a></li> <li><a href="functions_vars.html"><span>Variables</span></a></li> <li><a href="functions_type.html"><span>Typedefs</span></a></li> <li><a href="functions_enum.html"><span>Enumerations</span></a></li> </ul> </div> <div id="navrow4" class="tabs3"> <ul class="tablist"> <li><a href="functions.html#index_a"><span>a</span></a></li> <li><a href="functions_b.html#index_b"><span>b</span></a></li> <li><a href="functions_c.html#index_c"><span>c</span></a></li> <li><a href="functions_d.html#index_d"><span>d</span></a></li> <li><a href="functions_e.html#index_e"><span>e</span></a></li> <li class="current"><a href="functions_f.html#index_f"><span>f</span></a></li> <li><a href="functions_g.html#index_g"><span>g</span></a></li> <li><a href="functions_h.html#index_h"><span>h</span></a></li> <li><a href="functions_i.html#index_i"><span>i</span></a></li> <li><a href="functions_j.html#index_j"><span>j</span></a></li> <li><a href="functions_k.html#index_k"><span>k</span></a></li> <li><a href="functions_l.html#index_l"><span>l</span></a></li> <li><a href="functions_m.html#index_m"><span>m</span></a></li> <li><a href="functions_n.html#index_n"><span>n</span></a></li> <li><a href="functions_o.html#index_o"><span>o</span></a></li> <li><a href="functions_p.html#index_p"><span>p</span></a></li> <li><a href="functions_r.html#index_r"><span>r</span></a></li> <li><a href="functions_s.html#index_s"><span>s</span></a></li> <li><a href="functions_t.html#index_t"><span>t</span></a></li> <li><a href="functions_u.html#index_u"><span>u</span></a></li> <li><a href="functions_v.html#index_v"><span>v</span></a></li> <li><a href="functions_w.html#index_w"><span>w</span></a></li> <li><a href="functions_0x7e.html#index_0x7e"><span>~</span></a></li> </ul> </div> </div><!-- top --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <div class="textblock">Here is a list of all documented class members with links to the class documentation for each member:</div> <h3><a class="anchor" id="index_f"></a>- f -</h3><ul> <li>FindInstanceInPrototypeChain() : <a class="el" href="classv8_1_1Object.html#ae2ad9fee9db6e0e5da56973ebb8ea2bc">v8::Object</a> </li> <li>FindObjectById() : <a class="el" href="classv8_1_1HeapProfiler.html#ace729f9b7dbb2ca8b2fd67551bf5aae8">v8::HeapProfiler</a> </li> <li>Flags : <a class="el" href="classv8_1_1RegExp.html#aa4718a5c1f18472aff3bf51ed694fc5a">v8::RegExp</a> </li> <li>For() : <a class="el" href="classv8_1_1Symbol.html#a8a4a6bdc7d3e31c71cf48fa5cb811fc8">v8::Symbol</a> </li> <li>ForApi() : <a class="el" href="classv8_1_1Private.html#a0ab8628387166b8a8abc6e9b6f40ad55">v8::Private</a> , <a class="el" href="classv8_1_1Symbol.html#ac3937f0b0b831c4be495a399f26d7301">v8::Symbol</a> </li> <li>Free() : <a class="el" href="classv8_1_1ArrayBuffer_1_1Allocator.html#acaf1ec8820d5b994eb5a11f2c0ee38e0">v8::ArrayBuffer::Allocator</a> </li> <li>FreeBufferMemory() : <a class="el" href="classv8_1_1ValueSerializer_1_1Delegate.html#a6cea3e757221e6e15b0fdb708482a176">v8::ValueSerializer::Delegate</a> </li> <li>FromJust() : <a class="el" href="classv8_1_1Maybe.html#a02b19d7fcb7744d8dba3530ef8e14c8c">v8::Maybe&lt; T &gt;</a> </li> <li>FromMaybe() : <a class="el" href="classv8_1_1Maybe.html#a0bcb5fb0d0e92a3f0cc546f11068a8df">v8::Maybe&lt; T &gt;</a> , <a class="el" href="classv8_1_1MaybeLocal.html#afe1aea162c64385160cc1c83df859eaf">v8::MaybeLocal&lt; T &gt;</a> </li> <li>FromSnapshot() : <a class="el" href="classv8_1_1Context.html#a49a8fb02c04b6ebf4e532755d50d2ff9">v8::Context</a> , <a class="el" href="classv8_1_1FunctionTemplate.html#acd9eaca4c7d6de89949b8e1c41f4ba46">v8::FunctionTemplate</a> , <a class="el" href="classv8_1_1ObjectTemplate.html#a7899f31276e3ca69358005e360e3bc27">v8::ObjectTemplate</a> </li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.11 </small></address> </body> </html>
v8-dox/v8-dox.github.io
2a2c881/html/functions_f.html
HTML
mit
8,002
.loading { margin: 0 auto; width: 100px; padding-top: 50px; } /*! * Load Awesome v1.1.0 (http://github.danielcardoso.net/load-awesome/) * Copyright 2015 Daniel Cardoso <@DanielCardoso> * Licensed under MIT */ .la-ball-fussion, .la-ball-fussion > div { position: relative; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .la-ball-fussion { display: block; font-size: 0; color: #fff; } .la-ball-fussion.la-dark { color: #333; } .la-ball-fussion > div { display: inline-block; float: none; background-color: currentColor; border: 0 solid currentColor; } .la-ball-fussion { width: 8px; height: 8px; } .la-ball-fussion > div { position: absolute; width: 12px; height: 12px; border-radius: 100%; -webkit-transform: translate(-50%, -50%); -moz-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); -o-transform: translate(-50%, -50%); transform: translate(-50%, -50%); -webkit-animation: ball-fussion-ball1 1s 0s ease infinite; -moz-animation: ball-fussion-ball1 1s 0s ease infinite; -o-animation: ball-fussion-ball1 1s 0s ease infinite; animation: ball-fussion-ball1 1s 0s ease infinite; } .la-ball-fussion > div:nth-child(1) { top: 0; left: 50%; z-index: 1; } .la-ball-fussion > div:nth-child(2) { top: 50%; left: 100%; z-index: 2; -webkit-animation-name: ball-fussion-ball2; -moz-animation-name: ball-fussion-ball2; -o-animation-name: ball-fussion-ball2; animation-name: ball-fussion-ball2; } .la-ball-fussion > div:nth-child(3) { top: 100%; left: 50%; z-index: 1; -webkit-animation-name: ball-fussion-ball3; -moz-animation-name: ball-fussion-ball3; -o-animation-name: ball-fussion-ball3; animation-name: ball-fussion-ball3; } .la-ball-fussion > div:nth-child(4) { top: 50%; left: 0; z-index: 2; -webkit-animation-name: ball-fussion-ball4; -moz-animation-name: ball-fussion-ball4; -o-animation-name: ball-fussion-ball4; animation-name: ball-fussion-ball4; } .la-ball-fussion.la-sm { width: 4px; height: 4px; } .la-ball-fussion.la-sm > div { width: 6px; height: 6px; } .la-ball-fussion.la-2x { width: 16px; height: 16px; } .la-ball-fussion.la-2x > div { width: 24px; height: 24px; } .la-ball-fussion.la-3x { width: 24px; height: 24px; } .la-ball-fussion.la-3x > div { width: 36px; height: 36px; } /* * Animations */ @-webkit-keyframes ball-fussion-ball1 { 0% { opacity: .35; } 50% { top: -100%; left: 200%; opacity: 1; } 100% { top: 50%; left: 100%; z-index: 2; opacity: .35; } } @-moz-keyframes ball-fussion-ball1 { 0% { opacity: .35; } 50% { top: -100%; left: 200%; opacity: 1; } 100% { top: 50%; left: 100%; z-index: 2; opacity: .35; } } @-o-keyframes ball-fussion-ball1 { 0% { opacity: .35; } 50% { top: -100%; left: 200%; opacity: 1; } 100% { top: 50%; left: 100%; z-index: 2; opacity: .35; } } @keyframes ball-fussion-ball1 { 0% { opacity: .35; } 50% { top: -100%; left: 200%; opacity: 1; } 100% { top: 50%; left: 100%; z-index: 2; opacity: .35; } } @-webkit-keyframes ball-fussion-ball2 { 0% { opacity: .35; } 50% { top: 200%; left: 200%; opacity: 1; } 100% { top: 100%; left: 50%; z-index: 1; opacity: .35; } } @-moz-keyframes ball-fussion-ball2 { 0% { opacity: .35; } 50% { top: 200%; left: 200%; opacity: 1; } 100% { top: 100%; left: 50%; z-index: 1; opacity: .35; } } @-o-keyframes ball-fussion-ball2 { 0% { opacity: .35; } 50% { top: 200%; left: 200%; opacity: 1; } 100% { top: 100%; left: 50%; z-index: 1; opacity: .35; } } @keyframes ball-fussion-ball2 { 0% { opacity: .35; } 50% { top: 200%; left: 200%; opacity: 1; } 100% { top: 100%; left: 50%; z-index: 1; opacity: .35; } } @-webkit-keyframes ball-fussion-ball3 { 0% { opacity: .35; } 50% { top: 200%; left: -100%; opacity: 1; } 100% { top: 50%; left: 0; z-index: 2; opacity: .35; } } @-moz-keyframes ball-fussion-ball3 { 0% { opacity: .35; } 50% { top: 200%; left: -100%; opacity: 1; } 100% { top: 50%; left: 0; z-index: 2; opacity: .35; } } @-o-keyframes ball-fussion-ball3 { 0% { opacity: .35; } 50% { top: 200%; left: -100%; opacity: 1; } 100% { top: 50%; left: 0; z-index: 2; opacity: .35; } } @keyframes ball-fussion-ball3 { 0% { opacity: .35; } 50% { top: 200%; left: -100%; opacity: 1; } 100% { top: 50%; left: 0; z-index: 2; opacity: .35; } } @-webkit-keyframes ball-fussion-ball4 { 0% { opacity: .35; } 50% { top: -100%; left: -100%; opacity: 1; } 100% { top: 0; left: 50%; z-index: 1; opacity: .35; } } @-moz-keyframes ball-fussion-ball4 { 0% { opacity: .35; } 50% { top: -100%; left: -100%; opacity: 1; } 100% { top: 0; left: 50%; z-index: 1; opacity: .35; } } @-o-keyframes ball-fussion-ball4 { 0% { opacity: .35; } 50% { top: -100%; left: -100%; opacity: 1; } 100% { top: 0; left: 50%; z-index: 1; opacity: .35; } } @keyframes ball-fussion-ball4 { 0% { opacity: .35; } 50% { top: -100%; left: -100%; opacity: 1; } 100% { top: 0; left: 50%; z-index: 1; opacity: .35; } }
ShevaDas/exhibitor-management
src/components/Loading/Loading.css
CSS
mit
6,573
// rd_route.c // Copyright (c) 2014-2015 Dmitry Rodionov // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. #include <stdlib.h> // realloc() #include <libgen.h> // basename() #include <assert.h> // assert() #include <stdio.h> // fprintf() #include <dlfcn.h> // dladdr() #include "TargetConditionals.h" #if defined(__i386__) || defined(__x86_64__) #if !(TARGET_IPHONE_SIMULATOR) #include <mach/mach_vm.h> // mach_vm_* #else #include <mach/vm_map.h> // vm_* #define mach_vm_address_t vm_address_t #define mach_vm_size_t vm_size_t #define mach_vm_allocate vm_allocate #define mach_vm_deallocate vm_deallocate #define mach_vm_write vm_write #define mach_vm_remap vm_remap #define mach_vm_protect vm_protect #define NSLookupSymbolInImage(...) ((void)0) #define NSAddressOfSymbol(...) ((void)0) #endif #else #endif #include <mach-o/dyld.h> // _dyld_* #include <mach-o/nlist.h> // nlist/nlist_64 #include <mach/mach_init.h> // mach_task_self() #include "rd_route.h" #define RDErrorLog(format, ...) fprintf(stderr, "%s:%d:\n\terror: "format"\n", \ __FILE__, __LINE__, ##__VA_ARGS__) #if defined(__x86_64__) typedef struct mach_header_64 mach_header_t; typedef struct segment_command_64 segment_command_t; #define LC_SEGMENT_ARCH_INDEPENDENT LC_SEGMENT_64 typedef struct nlist_64 nlist_t; #else typedef struct mach_header mach_header_t; typedef struct segment_command segment_command_t; #define LC_SEGMENT_ARCH_INDEPENDENT LC_SEGMENT typedef struct nlist nlist_t; #endif typedef struct rd_injection { mach_vm_address_t injected_mach_header; mach_vm_address_t target_address; } rd_injection_t; static void* _function_ptr_within_image(const char *function_name, void *macho_image_header, uintptr_t vm_image_slide); void* function_ptr_from_name(const char *function_name) { assert(function_name); for (uint32_t i = 0; i < _dyld_image_count(); i++) { void *header = (void *)_dyld_get_image_header(i); uintptr_t vmaddr_slide = _dyld_get_image_vmaddr_slide(i); void *ptr = _function_ptr_within_image(function_name, header, vmaddr_slide); if (ptr) { return ptr; } } RDErrorLog("Failed to find symbol `%s` in the current address space.", function_name); return NULL; } static void* _function_ptr_within_image(const char *function_name, void *macho_image_header, uintptr_t vmaddr_slide) { assert(function_name); assert(macho_image_header); /** * Try the system NSLookup API to find out the function's pointer withing the specifed header. */ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated" void *pointer_via_NSLookup = ({ NSSymbol symbol = NSLookupSymbolInImage(macho_image_header, function_name, NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR); NSAddressOfSymbol(symbol); }); #pragma clang diagnostic pop if (pointer_via_NSLookup) return pointer_via_NSLookup; return NULL; }
XVimProject/XVim2
XVim2/Helper/rd_route.c
C
mit
3,016
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 Hotcakes Commerce, 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, // 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. #endregion using System; using DotNetNuke.Entities.Host; using Hotcakes.Commerce.Configuration; namespace Hotcakes.Commerce.Dnn { [Serializable] public class DnnConfigurationManager : IConfigurationManager { public SmtpSettings SmtpSettings { get { var smtpSettings = new SmtpSettings(); var smtpHostParts = Host.SMTPServer.Split(':'); smtpSettings.Host = smtpHostParts[0]; if (smtpHostParts.Length > 1) { smtpSettings.Port = smtpHostParts[1]; } switch (Host.SMTPAuthentication) { case "": case "0": //anonymous smtpSettings.UseAuth = false; break; case "1": //basic smtpSettings.UseAuth = true; break; case "2": //NTLM smtpSettings.UseAuth = false; break; } smtpSettings.EnableSsl = Host.EnableSMTPSSL; smtpSettings.Username = Host.SMTPUsername; smtpSettings.Password = Host.SMTPPassword; return smtpSettings; } } } }
HotcakesCommerce/core
Libraries/Hotcakes.Commerce.Dnn/DnnConfigurationManager.cs
C#
mit
2,605
<!-- Safe sample input : backticks interpretation, reading the file /tmp/tainted.txt SANITIZE : use of preg_replace with another regex File : use of untrusted data in one side of a quoted expression in a script --> <!--Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.--> <!DOCTYPE html> <html> <head> <script> <?php $tainted = `cat /tmp/tainted.txt`; $tainted = preg_replace('/\W/si','',$tainted); echo "x='". $tainted ."'" ; ?> </script> </head> <body> <h1>Hello World!</h1> </body> </html>
stivalet/PHP-Vulnerability-test-suite
XSS/CWE_79/safe/CWE_79__backticks__func_preg_replace2__Use_untrusted_data_script-side_Quoted_Expr.php
PHP
mit
1,351
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>readlines (Buffering)</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" /> </head> <body class="standalone-code"> <pre><span class="ruby-comment cmt"># File lib/openssl/buffering.rb, line 124</span> <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">readlines</span>(<span class="ruby-identifier">eol</span>=<span class="ruby-identifier">$/</span>) <span class="ruby-identifier">ary</span> = [] <span class="ruby-keyword kw">while</span> <span class="ruby-identifier">line</span> = <span class="ruby-keyword kw">self</span>.<span class="ruby-identifier">gets</span>(<span class="ruby-identifier">eol</span>) <span class="ruby-identifier">ary</span> <span class="ruby-operator">&lt;&lt;</span> <span class="ruby-identifier">line</span> <span class="ruby-keyword kw">end</span> <span class="ruby-identifier">ary</span> <span class="ruby-keyword kw">end</span></pre> </body> </html>
enzor/jror-example
doc/jruby-openssl-0.7/rdoc/classes/Buffering.src/M000045.html
HTML
mit
1,249
var crypto = require('crypto'); var lob = require('lob-enc') var hashname = require('hashname'); var log = require("./log")("Handshake") module.exports = { bootstrap : handshake_bootstrap, validate : handshake_validate, from : handshake_from, types : handshake_types, collect : handshake_collect }; var hcache = {} setInterval(function(){hcache = {}}, 60 * 1000) /** * collect incoming handshakes to accept them * @param {object} id * @param {handshake} handshake * @param {pipe} pipe * @param {Buffer} message */ function handshake_collect(mesh, id, handshake, pipe, message) { handshake = handshake_bootstrap(handshake); if (!handshake) return false; var valid = handshake_validate(id,handshake, message, mesh); if (!valid) return false; // get all from cache w/ matching at, by type var types = handshake_types(handshake, id); // bail unless we have a link if(!types.link) { log.debug('handshakes w/ no link yet',id,types); return false; } // build a from json container var from = handshake_from(handshake, pipe, types.link) // if we already linked this hashname, just update w/ the new info if(mesh.index[from.hashname]) { log.debug('refresh link handshake') from.sync = false; // tell .link to not auto-sync! return mesh.link(from); } else { } log.debug('untrusted hashname',from); from.received = {packet:types.link._message, pipe:pipe} // optimization hints as link args from.handshake = types; // include all handshakes if(mesh.accept) mesh.accept(from); return false; } function handshake_bootstrap(handshake){ // default an at for bare key handshakes if not given if(typeof handshake.json.at === 'undefined') handshake.json.at = Date.now(); // verify at if(typeof handshake.json.at != 'number' || handshake.json.at <= 0) { log.debug('invalid handshake at',handshake.json); return false; } // default the handshake type if(typeof handshake.json.type != 'string') handshake.json.type = 'link'; // upvert deprecated key to link type if(handshake.json.type == 'key') { // map only csid keys into attachment header var json = {}; hashname.ids(handshake.json).forEach(function(csid){ if(handshake.json[csid] === true) handshake.json.csid = csid; // cruft json[csid] = handshake.json[csid]; }); if(message) json[message.head.toString('hex')] = true; var attach = lob.encode(json, handshake.body); handshake.json.type = 'link'; handshake.body = attach; } return handshake } function handshake_validate(id,handshake, message, mesh){ if(handshake.json.type == 'link') { // if it came from an encrypted message if(message) { // make sure the link csid matches the message csid handshake.json.csid = message.head.toString('hex'); // stash inside the handshake, can be used later to create the exchange immediately handshake._message = message; } var attach = lob.decode(handshake.body); if(!attach) { log.debug('invalid link handshake attachment',handshake.body); return false; } // make sure key info is at least correct var keys = {}; keys[handshake.json.csid] = attach.body; var csid = hashname.match(mesh.keys, keys, null, attach.json); if(handshake.json.csid != csid) { log.debug('invalid key handshake, unsupported csid',attach.json, keys); return false; } handshake.json.hashname = hashname.fromKeys(keys, attach.json); if(!handshake.json.hashname) { log.debug('invalid key handshake, no hashname',attach.json, keys); return false; } // hashname is valid now, so stash key bytes in handshake handshake.body = attach.body; } // add it to the cache hcache[id] = (hcache[id] || [] ).concat([handshake]); return true; } function handshake_types (handshake, id){ var types = {} hcache[id].forEach(function(hs){ if(hs.json.at === handshake.json.at) types[hs.json.type] = hs; }); return types; } function handshake_from (handshake, pipe, link){ return { paths : (pipe.path) ? [pipe.path] : [], hashname : link.json.hashname, csid : link.json.csid, key : link.body }; }
telehash/telehash-js
lib/util/handshake.js
JavaScript
mit
4,311
# gitflow-publisher-bower > a bower publish processor for gitflow-publisher ![VERSION](https://img.shields.io/npm/v/gitflow-publisher-bower.svg) ![DOWNLOADS](https://img.shields.io/npm/dt/gitflow-publisher-bower.svg) [![ISSUES](https://img.shields.io/github/issues-raw/akonoupakis/gitflow-publisher-bower.svg)](https://github.com/akonoupakis/gitflow-publisher-bower/issues) ![LICENCE](https://img.shields.io/npm/l/gitflow-publisher-bower.svg) [![BUILD](https://api.travis-ci.org/akonoupakis/gitflow-publisher-bower.svg?branch=master)](http://travis-ci.org/akonoupakis/gitflow-publisher-bower) ![STANDARDJS](https://img.shields.io/badge/code%20style-standard-brightgreen.svg) [![DEPENDENCIES](https://david-dm.org/akonoupakis/gitflow-publisher-bower.svg)](https://david-dm.org/akonoupakis/gitflow-publisher-bower) [![NPM](https://nodei.co/npm/gitflow-publisher-bower.png?downloads=true)](https://nodei.co/npm/gitflow-publisher-bower/) ## overview This gitflow-publisher plugin module, deploys to the bower registry upon a successful gitflow release. ## usage ```js var Publisher = require('gitflow-publisher'); var GitflowBowerPublisher = require('gitflow-publisher-bower'); var publisher = new Publisher(); publisher.use(new GitflowBowerPublisher({ name: 'module-name', repository: 'https://github.com/username/packagename.git' })); publisher.publish({...}) ``` ## copyright and license Code and documentation copyright 2016 akon. Code released under [the MIT license](https://cdn.rawgit.com/akonoupakis/gitflow-publisher-bower/master/LICENSE).
akonoupakis/gitflow-publisher-bower
README.md
Markdown
mit
1,558
<?php /* * This file is part of the sfOauthServerPlugin package. * (c) Jean-Baptiste Cayrou <lordartis@gmail.com> * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * */ /** * sfOauthServerRouting configuration. * * @package sfOauthServerPlugin * @subpackage routing * @author Matthias Krauser <matthias@krauser.eu> */ class sfOauthServerRouting { /** * Listens to the routing.load_configuration event. * * @param sfEvent An sfEvent instance * @static */ static public function listenToRoutingLoadConfigurationEvent(sfEvent $event) { $r = $event->getSubject(); /* @var $r sfPatternRouting */ // preprend our routes $r->prependRoute('sf_oauth_server_consumer_sfOauthAdmin', new sfPropelRouteCollection(array( 'name' => 'sf_oauth_server_consumer_sfOauthAdmin', 'model' => 'sfOauthServerConsumer', 'module' => 'sfOauthAdmin', 'prefix_path' => '/oauth/admin', 'with_wildcard_routes' => true ))); } }
lmaxim/cc_oauthplugin
lib/routing/sfOauthServerRouting.class.php
PHP
mit
1,169
'use strict'; /* https://github.com/angular/protractor/blob/master/docs/toc.md */ describe('my app', function() { browser.get('index.html'); it('should automatically redirect to /home when location hash/fragment is empty', function() { expect(browser.getLocationAbsUrl()).toMatch("/home"); }); describe('view1', function() { beforeEach(function() { browser.get('index.html#/home'); }); it('should render home when user navigates to /home', function() { expect(element.all(by.css('[ng-view] p')).first().getText()). toMatch(/partial for view 1/); }); }); describe('view2', function() { beforeEach(function() { browser.get('index.html#/view2'); }); it('should render view2 when user navigates to /view2', function() { expect(element.all(by.css('[ng-view] p')).first().getText()). toMatch(/partial for view 2/); }); }); });
Mschmidt19/MarekSchmidt.com
e2e-tests/scenarios.js
JavaScript
mit
927
--- title: "Bayesian network regression with applications to microbiome data" collection: talks type: "Talk" permalink: /talks/2021_juliacon venue: "JuliaCon" date: 2021-07-30 location: "Online" --- Bayesian network regression with applications to microbiome data, **Samuel Ozminkowski** & Claudia Solís-Lemus, *JuliaCon*, Online, July 28-30, 2021 [Video](https://juliacon2020-uploads.s3.us-east-2.amazonaws.com/public/Bayesian+network+regression+with+applications+to+microbiome+data%3A+movie2.mp4) [Abstract](https://pretalx.com/juliacon2021/talk/review/KMKZLBEXJX3U8ZJQB3QHHWLLVUDXC3CG)
samozm/samozm.github.io
_talks/2021-juliacon.md
Markdown
mit
592
package me.breidenbach.asyncmailer /** * Copyright © Kevin E. Breidenbach, 5/26/15. */ case class MailerException(message: String, cause: Throwable = null) extends Error(message, cause)
kbreidenbach/akka-emailer
src/main/scala/me/breidenbach/asyncmailer/MailerException.scala
Scala
mit
190
#!/bin/bash cp index.html /var/www/ cp -r js /var/www cp -r img /var/www/img
IgorPelevanyuk/CatClicker-Knockout
deploy.sh
Shell
mit
77
<!doctype html> <html> <title>commands</title> <meta http-equiv="content-type" value="text/html;utf-8"> <link rel="stylesheet" type="text/css" href="../static/style.css"> <body> <div id="wrapper"> <h1><a href="../api/commands.html">commands</a></h1> <p>npm commands</p> <h2 id="SYNOPSIS">SYNOPSIS</h2> <pre><code>npm.commands[&lt;command&gt;](args, callback)</code></pre> <h2 id="DESCRIPTION">DESCRIPTION</h2> <p>npm comes with a full set of commands, and each of the commands takes a similar set of arguments.</p> <p>In general, all commands on the command object take an <strong>array</strong> of positional argument <strong>strings</strong>. The last argument to any function is a callback. Some commands are special and take other optional arguments.</p> <p>All commands have their own man page. See <code>man npm-&lt;command&gt;</code> for command-line usage, or <code>man 3 npm-&lt;command&gt;</code> for programmatic usage.</p> <h2 id="SEE-ALSO">SEE ALSO</h2> <ul><li><a href="../doc/index.html">index(1)</a></li></ul> </div> <p id="footer">commands &mdash; npm@1.2.23</p> <script> ;(function () { var wrapper = document.getElementById("wrapper") var els = Array.prototype.slice.call(wrapper.getElementsByTagName("*"), 0) .filter(function (el) { return el.parentNode === wrapper && el.tagName.match(/H[1-6]/) && el.id }) var l = 2 , toc = document.createElement("ul") toc.innerHTML = els.map(function (el) { var i = el.tagName.charAt(1) , out = "" while (i > l) { out += "<ul>" l ++ } while (i < l) { out += "</ul>" l -- } out += "<li><a href='#" + el.id + "'>" + ( el.innerText || el.text || el.innerHTML) + "</a>" return out }).join("\n") toc.id = "toc" document.body.appendChild(toc) })() </script> </body></html>
fschwiet/letscodejavascript
node_modules/npm/html/api/commands.html
HTML
mit
1,813
{% extends "layout.html" %} {% block body %} <title>All Events - Media Services</title> <form id="adminForm" action="" method=post> <div class="container"> <table class="table"> <thead> <td> <ul class="nav nav-pills"> <li class="nav-item"> <a class="nav-link active" href="#">Upcoming Events</a> </li> <li class="nav-item"> <a class="nav-link" href="{{ url_for('past') }}">Past Events</a> </li> </ul> </td> <td> <button type="button" class="btn btn-outline-secondary" onclick="toggleSignUps()"> <span id="signUpText" class="text-muted"> Please Wait...</span> </button> </td> <td style="text-align:right"> <a href="{{ url_for('new') }}" class="btn btn-success"> <i class="fa fa-plus" aria-hidden="true"></i> New Event </a> </td> </thead> </table> <table class="table table-hover"> {% block events %}{% endblock %} </table> <!-- bottom buttons --> </div> </form> <script> currentPage = "edit"; $(window).on('load', function(){ socket.emit("getSignUps") }) function lockEvent(event) { socket.emit("lockEvent", String(event)); document.getElementById("lock_"+event).innerHTML = "Please Wait..."; } function toggleSignUps() { socket.emit("toggleSignUps"); document.getElementById("signUpText").innerHTML = "Please Wait..."; } socket.on('eventLock', function(data) { if (data.locked) { document.getElementById("lock_"+data.event).setAttribute("class", "btn btn-sm btn-danger"); document.getElementById("lock_"+data.event).innerHTML = "<i class=\"fa fa-lock\"> </i> Locked"; } else { document.getElementById("lock_"+data.event).setAttribute("class", "btn btn-sm btn-default"); document.getElementById("lock_"+data.event).innerHTML = "<i class=\"fa fa-unlock\"> </i> Unlocked"; } }); socket.on('signUpsAvailable', function(data) { if (data.available) { document.getElementById("signUpText").setAttribute("class", "text-success"); document.getElementById("signUpText").innerHTML = "<i id=\"signUpIcon\" class=\"fa fa-toggle-on\" aria-hidden=\"true\"></i> Sign-Ups Open"; } else { document.getElementById("signUpText").setAttribute("class", "text-danger"); document.getElementById("signUpText").innerHTML = "<i id=\"signUpIcon\" class=\"fa fa-toggle-off\" aria-hidden=\"true\"></i> Sign-Ups Closed"; } }); </script> {% endblock %}
theapricot/oppapp2
templates/admin.html
HTML
mit
2,480
html, body { font-family: 'Roboto', 'Helvetica', sans-serif; } strong, b { font-weight: 700; } h1, h2, h3 { font-family: "Roboto Slab", "Helvetica", "Arial", sans-serif; } pre, code { font-family: "Roboto mono", monospace; } .ghostdown-edit-content { position: absolute; top: 50px; bottom: 50px; left: 0; right: 0; width: 99%; } .editor-title { font-family: "Roboto Condensed", "Helvetica", "Arial", sans-serif; text-transform: uppercase; font-size: 12px; height: 42px; margin: 0; padding: 0 10px; } .ghostdown-button-save { position: absolute; bottom: 7px; right: 7px; } .ghostdown-container { position: absolute; top: 0; right: 0; bottom: 0; left: 0; } #ghostdown-preview { overflow-y: scroll; position: absolute; top: 42px; right: 0; bottom: 0; left: 0; } #ghostdown-rendered { padding: 0 15px 15px; } #ghostdown-preview img { max-width: 100%; } .ghostdown-panel { position: relative; margin-bottom: 50px; } .ghostdown-footer { position: absolute; left: 0; right: 0; bottom: 0; padding: 15px; } #ghostdown-wordcount { float: right; display: inline-block; margin-top: -42px; padding: 10px 10px 0 0 } /******************************************** * CodeMirror Markup Styling *******************************************/ .CodeMirror { position: absolute; top: 42px; right: 0; bottom: 0; left: 0; height: auto; font-family: "Roboto Mono", monospace; } .CodeMirror-lines{ padding: 0 7px 20px; } .CodeMirror .cm-header{ color: #000; } .CodeMirror .cm-header-1 { font-size: 40px; line-height: 1.35; margin: 18px 0; display: inline-block; } .CodeMirror .cm-header-2 { font-size: 30px; line-height: 1.35; margin: 5px 0; display: inline-block; } .CodeMirror .cm-header-3 { font-size: 24px; line-height: 1.35; margin: 5px 0; display: inline-block; } /******************************************** * Dropzone Styling *******************************************/ p.dropzone { }
THLabs/ghostdown
styles/ghostdown.css
CSS
mit
2,150
function RenderPassManager(renderer) { // not implemented yet throw "Not implemented"; var mRenderPasses = []; return this; } RenderPassManager.prototype.addRenderPass = function(renderPass) { mRenderPasses.push(renderPass); }; RenderPassManager.prototype.render = function() { for(var renderPass in mRenderPasses) { renderPass.sort(); renderPass.render(renderer); renderPass.clear(); } };
RuggeroVisintin/SparkPreviewer
src/js/core/Renderer/RenderPassManager.js
JavaScript
mit
426
--- layout: post title: "IT业编程四大魔道天王" date: 2017-11-10 16:09:16 +0800 tag: [博客] --- IT业编程四大魔道天王的博客地址。 胡正 - [辟支佛胡正 · 阿罗汉尊者 · 功德藏闯菩萨](http://www.huzheng.org/myapps.php) 田春 - [Chun Tian (binghe)](http://tianchunbinghe.blog.163.com/) 李杀 - [Xah Lee Web 李杀网](http://xahlee.org/) 王垠 - [当然我在扯淡](http://www.yinwang.org/)
wangyu892449346/wangyu892449346.github.io
_posts/2017-11-10-IT业编程四大魔道天王.md
Markdown
mit
439
package com.malalaoshi.android.ui.dialogs; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import com.malalaoshi.android.R; import com.malalaoshi.android.core.network.api.ApiExecutor; import com.malalaoshi.android.core.network.api.BaseApiContext; import com.malalaoshi.android.core.stat.StatReporter; import com.malalaoshi.android.core.utils.MiscUtil; import com.malalaoshi.android.entity.Comment; import com.malalaoshi.android.network.Constants; import com.malalaoshi.android.network.api.PostCommentApi; import com.malalaoshi.android.ui.widgets.DoubleImageView; import org.json.JSONException; import org.json.JSONObject; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by donald on 2017/6/29. */ public class CommentDialog extends BaseDialog { private static String ARGS_DIALOG_COMMENT_TYPE = "comment type"; private static String ARGS_DIALOG_TEACHER_NAME = "teacher name"; private static String ARGS_DIALOG_TEACHER_AVATAR = "teacher avatar"; private static String ARGS_DIALOG_LECTURER_NAME = "lecturer name"; private static String ARGS_DIALOG_LECTURER_AVATAR = "lecturer avatar"; private static String ARGS_DIALOG_ASSIST_NAME = "assist name"; private static String ARGS_DIALOG_ASSIST_AVATAR = "assist avatar"; private static String ARGS_DIALOG_COURSE_NAME = "course name"; private static String ARGS_DIALOG_COMMENT = "comment"; private static String ARGS_DIALOG_TIMESLOT = "timeslot"; @Bind(R.id.div_comment_dialog_avatar) DoubleImageView mDivCommentDialogAvatar; @Bind(R.id.tv_comment_dialog_teacher_course) TextView mTvCommentDialogTeacherCourse; @Bind(R.id.rb_comment_dialog_score) RatingBar mRbCommentDialogScore; @Bind(R.id.et_comment_dialog_input) EditText mEtCommentDialogInput; @Bind(R.id.tv_comment_dialog_commit) TextView mTvCommentDialogCommit; @Bind(R.id.iv_comment_dialog_close) ImageView mIvCommentDialogClose; private int mCommentType; private String mTeacherName; private String mTeacherAvatar; private String mLeactureAvatar; private String mLeactureName; private String mAssistantAvatar; private String mAssistantName; private String mCourseName; private Comment mComment; private long mTimeslot; private OnCommentResultListener mResultListener; public CommentDialog(Context context) { super(context); } public CommentDialog(Context context, Bundle bundle) { super(context); if (bundle != null) { mCommentType = bundle.getInt(ARGS_DIALOG_COMMENT_TYPE); if (mCommentType == 0) { mTeacherName = bundle.getString(ARGS_DIALOG_TEACHER_NAME, ""); mTeacherAvatar = bundle.getString(ARGS_DIALOG_TEACHER_AVATAR, ""); } else if (mCommentType == 1) { mLeactureAvatar = bundle.getString(ARGS_DIALOG_LECTURER_AVATAR, ""); mLeactureName = bundle.getString(ARGS_DIALOG_LECTURER_NAME, ""); mAssistantAvatar = bundle.getString(ARGS_DIALOG_ASSIST_AVATAR, ""); mAssistantName = bundle.getString(ARGS_DIALOG_ASSIST_NAME, ""); } mCourseName = bundle.getString(ARGS_DIALOG_COURSE_NAME, ""); mComment = bundle.getParcelable(ARGS_DIALOG_COMMENT); mTimeslot = bundle.getLong(ARGS_DIALOG_TIMESLOT, 0L); } initView(); } private void initView() { setCancelable(false); if (mCommentType == 0) mDivCommentDialogAvatar.loadImg(mTeacherAvatar, "", DoubleImageView.LOAD_SIGNLE_BIG); else if (mCommentType == 1) mDivCommentDialogAvatar.loadImg(mLeactureAvatar, mAssistantAvatar, DoubleImageView.LOAD_DOUBLE); if (mComment != null) { StatReporter.commentPage(true); updateUI(mComment); mRbCommentDialogScore.setIsIndicator(true); mEtCommentDialogInput.setFocusableInTouchMode(false); mEtCommentDialogInput.setCursorVisible(false); mTvCommentDialogCommit.setText("查看评价"); } else { StatReporter.commentPage(false); mTvCommentDialogCommit.setText("提交"); mRbCommentDialogScore.setIsIndicator(false); mEtCommentDialogInput.setFocusableInTouchMode(true); mEtCommentDialogInput.setCursorVisible(true); } mTvCommentDialogTeacherCourse.setText(mCourseName); mRbCommentDialogScore.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() { @Override public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { if (mComment == null){ if (fromUser && rating > 0 && mEtCommentDialogInput.getText().length() > 0){ mTvCommentDialogCommit.setEnabled(true); }else { mTvCommentDialogCommit.setEnabled(false); } } } }); mEtCommentDialogInput.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) { } @Override public void afterTextChanged(Editable s) { if (mComment == null){ if (s.length() > 0 && mRbCommentDialogScore.getRating() > 0){ mTvCommentDialogCommit.setEnabled(true); }else { mTvCommentDialogCommit.setEnabled(false); } } } }); } @Override protected View getView() { View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_comment_v2, null); ButterKnife.bind(this, view); return view; } private void updateUI(Comment comment) { if (comment != null) { mRbCommentDialogScore.setRating(comment.getScore()); mEtCommentDialogInput.setText(comment.getContent()); } else { mRbCommentDialogScore.setRating(0); mEtCommentDialogInput.setText(""); } } @Override protected int getDialogStyleId() { return 0; } public static CommentDialog newInstance(Context context, String lecturerName, String lecturerAvatarUrl, String assistName, String assistAvatarUrl, String courseName, Long timeslot, Comment comment) { Bundle args = new Bundle(); args.putInt(ARGS_DIALOG_COMMENT_TYPE, 1); args.putString(ARGS_DIALOG_LECTURER_NAME, lecturerName); args.putString(ARGS_DIALOG_LECTURER_AVATAR, lecturerAvatarUrl); args.putString(ARGS_DIALOG_ASSIST_NAME, assistName); args.putString(ARGS_DIALOG_ASSIST_AVATAR, assistAvatarUrl); args.putString(ARGS_DIALOG_COURSE_NAME, courseName); args.putParcelable(ARGS_DIALOG_COMMENT, comment); args.putLong(ARGS_DIALOG_TIMESLOT, timeslot); // f.setArguments(args); CommentDialog f = new CommentDialog(context, args); return f; } public void setOnCommentResultListener(OnCommentResultListener listener) { mResultListener = listener; } public static CommentDialog newInstance(Context context, String teacherName, String teacherAvatarUrl, String courseName, Long timeslot, Comment comment) { Bundle args = new Bundle(); args.putInt(ARGS_DIALOG_COMMENT_TYPE, 0); args.putString(ARGS_DIALOG_TEACHER_NAME, teacherName); args.putString(ARGS_DIALOG_TEACHER_AVATAR, teacherAvatarUrl); args.putString(ARGS_DIALOG_COURSE_NAME, courseName); args.putParcelable(ARGS_DIALOG_COMMENT, comment); args.putLong(ARGS_DIALOG_TIMESLOT, timeslot); // f.setArguments(args); CommentDialog f = new CommentDialog(context, args); return f; } @OnClick({R.id.tv_comment_dialog_commit, R.id.iv_comment_dialog_close}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.tv_comment_dialog_commit: commit(); dismiss(); break; case R.id.iv_comment_dialog_close: dismiss(); break; } } private void commit() { StatReporter.commentSubmit(); if (mComment != null) { dismiss(); return; } float score = mRbCommentDialogScore.getRating(); if (score == 0.0) { MiscUtil.toast(R.string.rate_the_course); return; } String content = mEtCommentDialogInput.getText().toString(); if (TextUtils.isEmpty(content)) { MiscUtil.toast(R.string.write_few_reviews); return; } JSONObject json = new JSONObject(); try { json.put(Constants.TIMESLOT, mTimeslot); json.put(Constants.SCORE, score); json.put(Constants.CONTENT, content); } catch (JSONException e) { e.printStackTrace(); return; } ApiExecutor.exec(new PostCommentRequest(this, json.toString())); } public interface OnCommentResultListener { void onSuccess(Comment comment); } private static final class PostCommentRequest extends BaseApiContext<CommentDialog, Comment> { private String body; public PostCommentRequest(CommentDialog commentDialog, String body) { super(commentDialog); this.body = body; } @Override public Comment request() throws Exception { return new PostCommentApi().post(body); } @Override public void onApiSuccess(@NonNull Comment response) { get().commentSucceed(response); } @Override public void onApiFailure(Exception exception) { get().commentFailed(); } } private void commentFailed() { MiscUtil.toast(R.string.comment_failed); } private void commentSucceed(Comment response) { MiscUtil.toast(R.string.comment_succeed); if (mResultListener != null) mResultListener.onSuccess(response); dismiss(); } }
malaonline/Android
app/src/main/java/com/malalaoshi/android/ui/dialogs/CommentDialog.java
Java
mit
10,909
#!/usr/bin/env node var path = require('path'); var fs = require('fs'); var optimist = require('optimist'); var prompt = require('prompt'); var efs = require('efs'); var encext = require('./index'); var defaultAlgorithm = 'aes-128-cbc'; var argv = optimist .usage('usage: encext [-r] [-a algorithm] [file ...]') .describe('r', 'recursively encrypt supported files') .boolean('r') .alias('r', 'recursive') .default('r', false) .describe('a', 'encryption algorithm') .string('a') .alias('a', 'algorithm') .default('a', defaultAlgorithm) .argv; if (argv.help) { optimist.showHelp(); } var pwdPrompt = { name: 'password', description: 'Please enter the encryption password', required: true, hidden: true }; prompt.message = 'encext'; prompt.colors = false; prompt.start(); prompt.get(pwdPrompt, function(err, result) { if (err) { console.error('[ERROR]', err); process.exit(1); } efs = efs.init(argv.algorithm, result.password); argv._.forEach(processPath); }); function processPath(fspath) { fs.stat(fspath, onStat); function onStat(err, stats) { if (err) { return exit(err) } if (stats.isDirectory() && argv.recursive) { fs.readdir(fspath, onReaddir); } else if (stats.isFile() && encext.isSupported(fspath)) { encrypt(fspath); } } function onReaddir(err, fspaths) { if (err) { return exit(err) } fspaths.forEach(function(p) { processPath(path.join(fspath, p)); }); } } function encrypt(fspath) { var encpath = fspath + '_enc'; var writeStream = efs.createWriteStream(encpath); writeStream.on('error', exit); var readStream = fs.createReadStream(fspath); readStream.on('error', exit); readStream.on('end', function() { console.info(fspath, 'encrypted and written to', encpath); }); readStream.pipe(writeStream); } function exit(err) { console.error(err); process.exit(1); }
kunklejr/node-encext
cli.js
JavaScript
mit
1,910
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title> Sebastian Daza | R package to compute statistics from the American Community Survey (ACS) and Decennial US Census </title> <meta name="description" content="A simple, whitespace theme for academics. Based on [*folio](https://github.com/bogoli/-folio) design. "> <!-- Open Graph --> <!-- Bootstrap & MDB --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" integrity="sha512-MoRNloxbStBcD8z3M/2BmnT+rg4IsMxPkXaGh2zD6LGNNFE80W3onsAhRcMAMrSoyWL9xD7Ert0men7vR8LUZg==" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.19.1/css/mdb.min.css" integrity="sha512-RO38pBRxYH3SoOprtPTD86JFOclM51/XTIdEPh5j8sj4tp8jmQIx26twG52UaLi//hQldfrh7e51WzP9wuP32Q==" crossorigin="anonymous" /> <!-- Fonts & Icons --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" integrity="sha512-1PKOgIY59xJ8Co8+NE6FZ+LOAZKjy+KY8iq0G4B3CyeY6wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog==" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.9.0/css/academicons.min.css" integrity="sha512-W4yqoT1+8NLkinBLBZko+dFB2ZbHsYLDdr50VElllRcNt2Q4/GSs6u71UHKxB7S6JEMCp5Ve4xjh3eGQl/HRvg==" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Roboto+Slab:100,300,400,500,700|Material+Icons"> <!-- Code Syntax Highlighting --> <link rel="stylesheet" href="https://gitcdn.xyz/repo/jwarby/jekyll-pygments-themes/master/github.css" /> <!-- Styles --> <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🎯</text></svg>"> <link rel="stylesheet" href="/assets/css/main.css"> <link rel="canonical" href="/blog/2016/acsr/"> <!-- JQuery --> <!-- jQuery --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script> <!-- Theming--> <script src="/assets/js/theme.js"></script> <script src="/assets/js/dark_mode.js"></script> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-34554402-2"></script> <script> window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'UA-34554402-2'); </script> <!-- MathJax --> <script type="text/javascript"> window.MathJax = { tex: { tags: 'ams' } }; </script> <script defer type="text/javascript" id="MathJax-script" src="https://cdn.jsdelivr.net/npm/mathjax@3.2.0/es5/tex-mml-chtml.js"></script> <script defer src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script> </head> <body class="fixed-top-nav "> <!-- Header --> <header> <!-- Nav Bar --> <nav id="navbar" class="navbar navbar-light navbar-expand-sm fixed-top"> <div class="container"> <a class="navbar-brand title font-weight-lighter" href="https://sdaza.com/"> <span class="font-weight-bold">Sebastian</span> Daza </a> <!-- Navbar Toggle --> <button class="navbar-toggler collapsed ml-auto" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar top-bar"></span> <span class="icon-bar middle-bar"></span> <span class="icon-bar bottom-bar"></span> </button> <div class="collapse navbar-collapse text-right" id="navbarNav"> <ul class="navbar-nav ml-auto flex-nowrap"> <!-- About --> <li class="nav-item "> <a class="nav-link" href="/"> about </a> </li> <!-- Blog --> <li class="nav-item active"> <a class="nav-link" href="/blog/"> blog </a> </li> <!-- Other pages --> <li class="nav-item "> <a class="nav-link" href="/cv/"> cv </a> </li> <li class="nav-item "> <a class="nav-link" href="/projects/"> projects </a> </li> <li class="nav-item "> <a class="nav-link" href="/publications/"> publications </a> </li> <div class = "toggle-container"> <a id = "light-toggle"> <i class="fas fa-moon"></i> <i class="fas fa-sun"></i> </a> </div> </ul> </div> </div> </nav> </header> <!-- Content --> <div class="container mt-5"> <div class="post"> <header class="post-header"> <h1 class="post-title">R package to compute statistics from the American Community Survey (ACS) and Decennial US Census</h1> <p class="post-meta">July 6, 2016 • Sebastian Daza</p> </header> <article class="post-content"> <p>The <code class="language-plaintext highlighter-rouge">acsr</code> package helps extracting variables and computing statistics using the America Community Survey and Decennial US Census. It was created for the <a href="http://www.apl.wisc.edu/">Applied Population Laboratory</a> (APL) at the University of Wisconsin-Madison.</p> <h2 class="section-heading">Installation</h2> <p>The functions depend on the <code class="language-plaintext highlighter-rouge">acs</code> and <code class="language-plaintext highlighter-rouge">data.table</code> packages, so it is necessary to install then before using <code class="language-plaintext highlighter-rouge">acsr</code>. The <code class="language-plaintext highlighter-rouge">acsr</code> package is hosted on a github repository and can be installed using <code class="language-plaintext highlighter-rouge">devtools</code>:</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">devtools</span><span class="o">::</span><span class="n">install_github</span><span class="p">(</span><span class="s2">"sdaza/acsr"</span><span class="p">)</span><span class="w"> </span><span class="n">library</span><span class="p">(</span><span class="n">acsr</span><span class="p">)</span></code></pre></figure> <p>Remember to set the ACS API key, to check the help documentation and the default values of the <code class="language-plaintext highlighter-rouge">acsr</code> functions.</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">api.key.install</span><span class="p">(</span><span class="n">key</span><span class="o">=</span><span class="s2">"*"</span><span class="p">)</span><span class="w"> </span><span class="o">?</span><span class="n">sumacs</span><span class="w"> </span><span class="o">?</span><span class="n">acsdata</span></code></pre></figure> <p>The default dataset is <code class="language-plaintext highlighter-rouge">acs</code>, the level is <code class="language-plaintext highlighter-rouge">state</code> (Wisconsin, <code class="language-plaintext highlighter-rouge">state = "WI"</code>), the <code class="language-plaintext highlighter-rouge">endyear</code> is 2014, and the confidence level to compute margins of error (MOEs) is 90%.</p> <h2 class="section-heading">Levels</h2> <p>The <code class="language-plaintext highlighter-rouge">acsr</code> functions can extract all the levels available in the <code class="language-plaintext highlighter-rouge">acs</code> package. The table below shows the summary and required levels when using the <code class="language-plaintext highlighter-rouge">acsdata</code> and <code class="language-plaintext highlighter-rouge">sumacs</code> functions:</p> <table> <thead> <tr> <th>summary number</th> <th>levels</th> </tr> </thead> <tbody> <tr> <td>010</td> <td>us</td> </tr> <tr> <td>020</td> <td>region</td> </tr> <tr> <td>030</td> <td>division</td> </tr> <tr> <td>040</td> <td>state</td> </tr> <tr> <td>050</td> <td>state, county</td> </tr> <tr> <td>060</td> <td>state, county, county.subdivision</td> </tr> <tr> <td>140</td> <td>state, county, tract</td> </tr> <tr> <td>150</td> <td>state, county, tract, block.group</td> </tr> <tr> <td>160</td> <td>state, place</td> </tr> <tr> <td>250</td> <td>american.indian.area</td> </tr> <tr> <td>320</td> <td>state, msa</td> </tr> <tr> <td>340</td> <td>state, csa</td> </tr> <tr> <td>350</td> <td>necta</td> </tr> <tr> <td>400</td> <td>urban.area</td> </tr> <tr> <td>500</td> <td>state, congressional.district</td> </tr> <tr> <td>610</td> <td>state, state.legislative.district.upper</td> </tr> <tr> <td>620</td> <td>state, state.legislative.district.lower</td> </tr> <tr> <td>795</td> <td>state, puma</td> </tr> <tr> <td>860</td> <td>zip.code</td> </tr> <tr> <td>950</td> <td>state, school.district.elementary</td> </tr> <tr> <td>960</td> <td>state, school.district.secondary</td> </tr> <tr> <td>970</td> <td>state, school.district.unified</td> </tr> </tbody> </table> <h2 class="section-heading">Getting variables and statistics</h2> <p>We can use the <code class="language-plaintext highlighter-rouge">sumacs</code> function to extract variable and statistics. We have to specify the corresponding method (e.g., <em>proportion</em> or just <em>variable</em>), and the name of the statistic or variable to be included in the output.</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">sumacs</span><span class="p">(</span><span class="n">formula</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"(b16004_004 + b16004_026 + b16004_048 / b16004_001)"</span><span class="p">,</span><span class="w"> </span><span class="s2">"b16004_026"</span><span class="p">),</span><span class="w"> </span><span class="n">varname</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"mynewvar"</span><span class="p">,</span><span class="w"> </span><span class="s2">"myvar"</span><span class="p">),</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"prop"</span><span class="p">,</span><span class="w"> </span><span class="s2">"variable"</span><span class="p">),</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"division"</span><span class="p">))</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] "Extracting data from: acs 2014" ## [1] ". . . . . . ACS/Census variables : 4" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 2" ## [1] ". . . . . . Getting division data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 50%" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output"</code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## sumlevel geoid division mynewvar_est mynewvar_moe myvar_est myvar_moe ## 1: 030 NA 1 0.0762 0.000347 770306 3490 ## 2: 030 NA 2 0.1182 0.000278 3332150 9171 ## 3: 030 NA 3 0.0599 0.000196 1819417 7209 ## 4: 030 NA 4 0.0411 0.000277 547577 4461 ## 5: 030 NA 5 0.1108 0.000246 4526480 11869 ## 6: 030 NA 6 0.0320 0.000265 402475 3781 ## 7: 030 NA 7 0.2203 0.000469 5318126 13044 ## 8: 030 NA 8 0.1582 0.000602 2279303 10746 ## 9: 030 NA 9 0.2335 0.000501 7765838 20289</code></pre></figure> <p>To download the data can be slow, especially when many levels are being used (e.g., blockgroup). A better approach in those cases is, first, download the data using the function <code class="language-plaintext highlighter-rouge">acsdata</code> , and then use them as input.</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">mydata</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">acsdata</span><span class="p">(</span><span class="n">formula</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"(b16004_004 + b16004_026 + b16004_048 / b16004_001)"</span><span class="p">,</span><span class="w"> </span><span class="s2">"b16004_026"</span><span class="p">),</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"division"</span><span class="p">))</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] ". . . . . . Getting division data"</code></pre></figure> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">sumacs</span><span class="p">(</span><span class="n">formula</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"(b16004_004 + b16004_026 + b16004_048 / b16004_001)"</span><span class="p">,</span><span class="w"> </span><span class="s2">"b16004_026"</span><span class="p">),</span><span class="w"> </span><span class="n">varname</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"mynewvar"</span><span class="p">,</span><span class="w"> </span><span class="s2">"myvar"</span><span class="p">),</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"prop"</span><span class="p">,</span><span class="w"> </span><span class="s2">"variable"</span><span class="p">),</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"division"</span><span class="p">),</span><span class="w"> </span><span class="n">data</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">mydata</span><span class="p">)</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] "Extracting data from: acs 2014" ## [1] ". . . . . . ACS/Census variables : 4" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 2" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 50%" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output"</code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## sumlevel geoid division mynewvar_est mynewvar_moe myvar_est myvar_moe ## 1: 030 NA 1 0.0762 0.000347 770306 3490 ## 2: 030 NA 2 0.1182 0.000278 3332150 9171 ## 3: 030 NA 3 0.0599 0.000196 1819417 7209 ## 4: 030 NA 4 0.0411 0.000277 547577 4461 ## 5: 030 NA 5 0.1108 0.000246 4526480 11869 ## 6: 030 NA 6 0.0320 0.000265 402475 3781 ## 7: 030 NA 7 0.2203 0.000469 5318126 13044 ## 8: 030 NA 8 0.1582 0.000602 2279303 10746 ## 9: 030 NA 9 0.2335 0.000501 7765838 20289</code></pre></figure> <h2 class="section-heading">Standard errors</h2> <p>When computing statistics there are two ways to define the standard errors:</p> <ul> <li>Including all standard errors of the variables used to compute a statistic (<code class="language-plaintext highlighter-rouge">one.zero = FALSE</code>)</li> <li>Include all standard errors except those of variables that are equal to zero. Only the maximum standard error of the variables equal to zero is included (<code class="language-plaintext highlighter-rouge">one.zero = TRUE</code>)</li> <li>The default value is <code class="language-plaintext highlighter-rouge">one.zero = TRUE</code></li> </ul> <p>For more details about how standard errors are computed for proportions, ratios and aggregations look at <a href="https://www.census.gov/content/dam/Census/library/publications/2008/acs/ACSGeneralHandbook.pdf">A Compass for Understanding and Using American Community Survey Data</a>.</p> <p>Below an example when estimating proportions and using <code class="language-plaintext highlighter-rouge">one.zero = FALSE</code>:</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">sumacs</span><span class="p">(</span><span class="n">formula</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"(b16004_004 + b16004_026 + b16004_048) / b16004_001"</span><span class="p">,</span><span class="w"> </span><span class="n">varname</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"mynewvar"</span><span class="p">,</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"prop"</span><span class="p">,</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"tract"</span><span class="p">,</span><span class="w"> </span><span class="n">county</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">1</span><span class="p">,</span><span class="w"> </span><span class="n">tract</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">950501</span><span class="p">,</span><span class="w"> </span><span class="n">endyear</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">2013</span><span class="p">,</span><span class="w"> </span><span class="n">one.zero</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">FALSE</span><span class="p">)</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] "Extracting data from: acs 2013" ## [1] ". . . . . . ACS/Census variables : 4" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 1" ## [1] ". . . . . . Getting tract data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output"</code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## sumlevel geoid st_fips cnty_fips tract_fips mynewvar_est mynewvar_moe ## 1: 140 55001950501 55 1 950501 0.0226 0.0252</code></pre></figure> \[SE = \sqrt{ \frac{(5.47 ^ 2 + 22.49 ^ 2 + 5.47 ^ 2) - ( 0.02 ^ 2 \times 102.13 ^ 2)}{1546} } \times 1.645 = 0.0252\] <p>When <code class="language-plaintext highlighter-rouge">one.zero = TRUE</code>:</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">sumacs</span><span class="p">(</span><span class="n">formula</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"(b16004_004 + b16004_026 + b16004_048) / b16004_001"</span><span class="p">,</span><span class="w"> </span><span class="n">varname</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"mynewvar"</span><span class="p">,</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"prop"</span><span class="p">,</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"tract"</span><span class="p">,</span><span class="w"> </span><span class="n">county</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">1</span><span class="p">,</span><span class="w"> </span><span class="n">tract</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">950501</span><span class="p">,</span><span class="w"> </span><span class="n">endyear</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">2013</span><span class="p">,</span><span class="w"> </span><span class="n">one.zero</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">TRUE</span><span class="p">)</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] "Extracting data from: acs 2013" ## [1] ". . . . . . ACS/Census variables : 4" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 1" ## [1] ". . . . . . Getting tract data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output"</code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## sumlevel geoid st_fips cnty_fips tract_fips mynewvar_est mynewvar_moe ## 1: 140 55001950501 55 1 950501 0.0226 0.0245</code></pre></figure> \[SE_{\text{ one.zero}} \sqrt{ \frac{(5.47 ^ 2 + 22.49 ^ 2) - ( 0.02 ^ 2 \times 102.13 ^ 2)}{1546} } \times 1.645 = 0.0245\] <p>When the square root value in the standard error formula doesn’t exist (e.g., the square root of a negative number), the ratio formula is instead used. The ratio adjustment is done <strong>variable by variable</strong> .</p> <p>It can also be that the <code class="language-plaintext highlighter-rouge">one.zero</code> option makes the square root undefinable. In those cases, the function uses again the <strong>ratio</strong> formula to compute standard errors. There is also a possibility that the standard error estimates using the <strong>ratio</strong> formula are higher than the <strong>proportion</strong> estimates without the <code class="language-plaintext highlighter-rouge">one.zero</code> option.</p> <h2 class="section-heading">Decennial Data from the US Census</h2> <p>Let’s get the African American and Hispanic population by state. In this case, we don’t have any estimation of margin of error.</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">sumacs</span><span class="p">(</span><span class="n">formula</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"p0080004"</span><span class="p">,</span><span class="w"> </span><span class="s2">"p0090002"</span><span class="p">),</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"variable"</span><span class="p">,</span><span class="w"> </span><span class="n">dataset</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"sf1"</span><span class="p">,</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"state"</span><span class="p">,</span><span class="w"> </span><span class="n">state</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"*"</span><span class="p">,</span><span class="w"> </span><span class="n">endyear</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">2010</span><span class="p">)</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] "Extracting data from: sf1 2010" ## [1] ". . . . . . ACS/Census variables : 2" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 2" ## [1] ". . . . . . Getting state data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 50%" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output"</code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## sumlevel geoid st_fips p0080004 p0090002 ## 1: 040 01 01 1251311 185602 ## 2: 040 02 02 23263 39249 ## 3: 040 04 04 259008 1895149 ## 4: 040 05 05 449895 186050 ## 5: 040 06 06 2299072 14013719 ## 6: 040 08 08 201737 1038687 ## 7: 040 09 09 362296 479087 ## 8: 040 10 10 191814 73221 ## 9: 040 11 11 305125 54749 ## 10: 040 12 12 2999862 4223806 ## 11: 040 13 13 2950435 853689 ## 12: 040 15 15 21424 120842 ## 13: 040 16 16 9810 175901 ## 14: 040 17 17 1866414 2027578 ## 15: 040 18 18 591397 389707 ## 16: 040 19 19 89148 151544 ## 17: 040 20 20 167864 300042 ## 18: 040 21 21 337520 132836 ## 19: 040 22 22 1452396 192560 ## 20: 040 23 23 15707 16935 ## 21: 040 24 24 1700298 470632 ## 22: 040 25 25 434398 627654 ## 23: 040 26 26 1400362 436358 ## 24: 040 27 27 274412 250258 ## 25: 040 28 28 1098385 81481 ## 26: 040 29 29 693391 212470 ## 27: 040 30 30 4027 28565 ## 28: 040 31 31 82885 167405 ## 29: 040 32 32 218626 716501 ## 30: 040 33 33 15035 36704 ## 31: 040 34 34 1204826 1555144 ## 32: 040 35 35 42550 953403 ## 33: 040 36 36 3073800 3416922 ## 34: 040 37 37 2048628 800120 ## 35: 040 38 38 7960 13467 ## 36: 040 39 39 1407681 354674 ## 37: 040 40 40 277644 332007 ## 38: 040 41 41 69206 450062 ## 39: 040 42 42 1377689 719660 ## 40: 040 44 44 60189 130655 ## 41: 040 45 45 1290684 235682 ## 42: 040 46 46 10207 22119 ## 43: 040 47 47 1057315 290059 ## 44: 040 48 48 2979598 9460921 ## 45: 040 49 49 29287 358340 ## 46: 040 50 50 6277 9208 ## 47: 040 51 51 1551399 631825 ## 48: 040 53 53 240042 755790 ## 49: 040 54 54 63124 22268 ## 50: 040 55 55 359148 336056 ## 51: 040 56 56 4748 50231 ## 52: 040 72 72 461498 3688455 ## sumlevel geoid st_fips p0080004 p0090002</code></pre></figure> <h2 class="section-heading">Output</h2> <p>The output can be formatted using a wide or long format:</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">sumacs</span><span class="p">(</span><span class="n">formula</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"(b16004_004 + b16004_026 + b16004_048 / b16004_001)"</span><span class="p">,</span><span class="w"> </span><span class="n">varname</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"mynewvar"</span><span class="p">,</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"prop"</span><span class="p">,</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"division"</span><span class="p">,</span><span class="w"> </span><span class="n">format.out</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"long"</span><span class="p">)</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] "Extracting data from: acs 2014" ## [1] ". . . . . . ACS/Census variables : 4" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 1" ## [1] ". . . . . . Getting division data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output"</code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## geoid sumlevel division var_name est moe ## 1: NA 030 1 mynewvar 0.0762 0.000347 ## 2: NA 030 2 mynewvar 0.1182 0.000278 ## 3: NA 030 3 mynewvar 0.0599 0.000196 ## 4: NA 030 4 mynewvar 0.0411 0.000277 ## 5: NA 030 5 mynewvar 0.1108 0.000246 ## 6: NA 030 6 mynewvar 0.0320 0.000265 ## 7: NA 030 7 mynewvar 0.2203 0.000469 ## 8: NA 030 8 mynewvar 0.1582 0.000602 ## 9: NA 030 9 mynewvar 0.2335 0.000501</code></pre></figure> <p>And it can also be exported to a csv file:</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">sumacs</span><span class="p">(</span><span class="n">formula</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"(b16004_004 + b16004_026 + b16004_048 / b16004_001)"</span><span class="p">,</span><span class="w"> </span><span class="n">varname</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"mynewvar"</span><span class="p">,</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"prop"</span><span class="p">,</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"division"</span><span class="p">,</span><span class="w"> </span><span class="n">file</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"myfile.out"</span><span class="p">)</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] "Extracting data from: acs 2014" ## [1] ". . . . . . ACS/Census variables : 4" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 1" ## [1] ". . . . . . Getting division data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output" ## [1] "Data exported to a CSV file! "</code></pre></figure> <h2 class="section-heading">Combining geographic levels</h2> <p>We can combine geographic levels using two methods: (1) <code class="language-plaintext highlighter-rouge">sumacs</code> and (2) <code class="language-plaintext highlighter-rouge">combine.output</code>. The first one allows only single combinations, the second multiple ones.</p> <p>If I want to combine two states (e.g., Wisconsin and Minnesota) I can use:</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">sumacs</span><span class="p">(</span><span class="s2">"(b16004_004 + b16004_026 + b16004_048 / b16004_001)"</span><span class="p">,</span><span class="w"> </span><span class="n">varname</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"mynewvar"</span><span class="p">,</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"prop"</span><span class="p">,</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"state"</span><span class="p">,</span><span class="w"> </span><span class="n">state</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">list</span><span class="p">(</span><span class="s2">"WI"</span><span class="p">,</span><span class="w"> </span><span class="s2">"MN"</span><span class="p">),</span><span class="w"> </span><span class="n">combine</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">TRUE</span><span class="p">,</span><span class="w"> </span><span class="n">print.levels</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">FALSE</span><span class="p">)</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] "Extracting data from: acs 2014" ## [1] ". . . . . . ACS/Census variables : 4" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 1" ## [1] ". . . . . . Getting combined data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output"</code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## geoid combined_group mynewvar_est mynewvar_moe ## 1: NA aggregate 0.042 0.000331</code></pre></figure> <p>If I want to put together multiple combinations (e.g., groups of states):</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">combine.output</span><span class="p">(</span><span class="s2">"(b16004_004 + b16004_026 + b16004_048 / b16004_001)"</span><span class="p">,</span><span class="w"> </span><span class="n">varname</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"mynewvar"</span><span class="p">,</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"prop"</span><span class="p">,</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">list</span><span class="p">(</span><span class="s2">"state"</span><span class="p">,</span><span class="w"> </span><span class="s2">"state"</span><span class="p">),</span><span class="w"> </span><span class="n">state</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">list</span><span class="p">(</span><span class="w"> </span><span class="nf">list</span><span class="p">(</span><span class="s2">"WI"</span><span class="p">,</span><span class="w"> </span><span class="s2">"MN"</span><span class="p">),</span><span class="w"> </span><span class="nf">list</span><span class="p">(</span><span class="s2">"CA"</span><span class="p">,</span><span class="w"> </span><span class="s2">"OR"</span><span class="p">)),</span><span class="w"> </span><span class="c1"># nested list</span><span class="w"> </span><span class="n">combine.names</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"WI+MN"</span><span class="p">,</span><span class="w"> </span><span class="s2">"CA+OR"</span><span class="p">),</span><span class="w"> </span><span class="n">print.levels</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">FALSE</span><span class="p">)</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] ". . . . . . Defining WI+MN" ## [1] "Extracting data from: acs 2014" ## [1] ". . . . . . ACS/Census variables : 4" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 1" ## [1] ". . . . . . Getting combined data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output" ## [1] ". . . . . . Defining CA+OR" ## [1] "Extracting data from: acs 2014" ## [1] ". . . . . . ACS/Census variables : 4" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 1" ## [1] ". . . . . . Getting combined data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output"</code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## combined_group mynewvar_est mynewvar_moe ## 1: WI+MN 0.042 0.000331 ## 2: CA+OR 0.269 0.000565</code></pre></figure> <h2 class="section-heading">A map?</h2> <p>Let’s color a map using poverty by county:</p> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">pov</span><span class="w"> </span><span class="o">&lt;-</span><span class="w"> </span><span class="n">sumacs</span><span class="p">(</span><span class="n">formula</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"b17001_002 / b17001_001 * 100"</span><span class="p">,</span><span class="w"> </span><span class="n">varname</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"pov"</span><span class="p">),</span><span class="w"> </span><span class="n">method</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"prop"</span><span class="p">),</span><span class="w"> </span><span class="n">level</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nf">c</span><span class="p">(</span><span class="s2">"county"</span><span class="p">),</span><span class="w"> </span><span class="n">state</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s2">"*"</span><span class="p">)</span></code></pre></figure> <figure class="highlight"><pre><code class="language-text" data-lang="text">## [1] "Extracting data from: acs 2014" ## [1] ". . . . . . ACS/Census variables : 2" ## [1] ". . . . . . Levels : 1" ## [1] ". . . . . . New variables : 1" ## [1] ". . . . . . Getting county data" ## [1] ". . . . . . Creating variables" ## [1] ". . . . . . 100%" ## [1] ". . . . . . Formatting output"</code></pre></figure> <figure class="highlight"><pre><code class="language-r" data-lang="r"><span class="n">library</span><span class="p">(</span><span class="n">choroplethr</span><span class="p">)</span><span class="w"> </span><span class="n">library</span><span class="p">(</span><span class="n">choroplethrMaps</span><span class="p">)</span><span class="w"> </span><span class="n">pov</span><span class="p">[,</span><span class="w"> </span><span class="n">region</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nf">as.numeric</span><span class="p">(</span><span class="n">geoid</span><span class="p">)]</span><span class="w"> </span><span class="n">setnames</span><span class="p">(</span><span class="n">pov</span><span class="p">,</span><span class="w"> </span><span class="s2">"pov_est"</span><span class="p">,</span><span class="w"> </span><span class="s2">"value"</span><span class="p">)</span><span class="w"> </span><span class="n">county_choropleth</span><span class="p">(</span><span class="n">pov</span><span class="p">,</span><span class="w"> </span><span class="n">num_colors</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="m">5</span><span class="p">)</span></code></pre></figure> <p><img src="/assets/img/2016-07-06-acsr/unnamed-chunk-15-1.png" alt="center" /></p> <p>In sum, the <code class="language-plaintext highlighter-rouge">acsr</code> package:</p> <ul> <li>Reads formulas directly and extracts any ACS/Census variable</li> <li>Provides an automatized and tailored way to obtain indicators and MOEs</li> <li>Allows different outputs’ formats (wide and long, csv)</li> <li>Provides an easy way to adjust MOEs to different confidence levels</li> <li>Includes a variable-by-variable ratio adjustment of standard errors</li> <li>Includes the zero-option when computing standard errors for proportions, ratios, and aggregations</li> <li>Combines geographic levels flexibly</li> </ul> <p><strong>Last Update: 02/07/2016</strong></p> </article> <div id="disqus_thread"></div> <script type="text/javascript"> var disqus_shortname = 'sdaza'; var disqus_identifier = '/blog/2016/acsr'; var disqus_title = "R package to compute statistics from the American Community Survey (ACS) and Decennial US Census"; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> </div> </div> <!-- Footer --> <footer class="fixed-bottom"> <div class="container mt-0"> &copy; Copyright 2021 Sebastian Daza. Powered by <a href="http://jekyllrb.com/" target="_blank">Jekyll</a> with <a href="https://github.com/alshedivat/al-folio">al-folio</a> theme. Hosted by <a href="https://pages.github.com/" target="_blank">GitHub Pages</a>. Last updated: August 28, 2021. </div> </footer> </body> <!-- Bootsrap & MDB scripts --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.4.4/umd/popper.min.js" integrity="sha512-eUQ9hGdLjBjY3F41CScH3UX+4JDSI9zXeroz7hJ+RteoCaY+GP/LDoM8AO+Pt+DRFw3nXqsjh9Zsts8hnYv8/A==" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha512-M5KW3ztuIICmVIhjSqXe01oV2bpe248gOxqmlcYrEzAvws7Pw3z6BK0iGbrwvdrUQUhi3eXgtxp5I8PDo9YfjQ==" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.19.1/js/mdb.min.js" integrity="sha512-Mug9KHKmroQFMLm93zGrjhibM2z2Obg9l6qFG2qKjXEXkMp/VDkI4uju9m4QKPjWSwQ6O2qzZEnJDEeCw0Blcw==" crossorigin="anonymous"></script> <!-- Mansory & imagesLoaded --> <script defer src="https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.min.js"></script> <script defer src="https://unpkg.com/imagesloaded@4/imagesloaded.pkgd.min.js"></script> <script defer src="/assets/js/mansory.js" type="text/javascript"></script> <!-- Enable Tooltips --> <script type="text/javascript"> $(function () {$('[data-toggle="tooltip"]').tooltip()}) </script> <!-- Medium Zoom JS --> <script src="https://cdn.jsdelivr.net/npm/medium-zoom@1.0.6/dist/medium-zoom.min.js" integrity="sha256-EdPgYcPk/IIrw7FYeuJQexva49pVRZNmt3LculEr7zM=" crossorigin="anonymous"></script> <script src="/assets/js/zoom.js"></script> <!-- Load Common JS --> <script src="/assets/js/common.js"></script> </html>
sdaza/sdaza.github.com
blog/2016/acsr/index.html
HTML
mit
45,371
using CertificateManager.Entities; using CertificateManager.Entities.Interfaces; using System.Collections.Generic; using System.Security.Claims; namespace CertificateManager.Logic.Interfaces { public interface IAuditLogic { IEnumerable<AuditEvent> GetAllEvents(); void LogSecurityAuditSuccess(ClaimsPrincipal userContext, ILoggableEntity entity, EventCategory category); void LogSecurityAuditFailure(ClaimsPrincipal userContext, ILoggableEntity entity, EventCategory category); void LogOpsSuccess(ClaimsPrincipal userContext, string target, EventCategory category, string message); void LogOpsError(ClaimsPrincipal userContext, string target, EventCategory category); void LogOpsError(ClaimsPrincipal userContext, string target, EventCategory category, string message); void InitializeMockData(); void ClearLogs(ClaimsPrincipal user); } }
corymurphy/CertificateManager
CertificateManager.Logic/Interfaces/IAuditLogic.cs
C#
mit
919
<?php if (empty($content)) { return; } $title = 'Bank Emulator Authorization Center'; ?> <html lang="ru"> <?= View::make('ff-bank-em::layouts.head', array( 'title' => $title, )); ?> <body> <div class="navbar navbar-default"> <?= View::make('ff-bank-em::layouts.navbar-header', array( 'title' => $title, )); ?> </div> <?= $content ?> <?php require(__DIR__ . '/js.php') ?> </body> </html>
fintech-fab/bank-emulator
src/views/layouts/authorization.php
PHP
mit
398
export function wedgeYZ(a, b) { return a.y * b.z - a.z * b.y; } export function wedgeZX(a, b) { return a.z * b.x - a.x * b.z; } export function wedgeXY(a, b) { return a.x * b.y - a.y * b.x; }
geometryzen/davinci-newton
build/module/lib/math/wedge3.js
JavaScript
mit
204
module Mlblog VERSION = "0.0.1" end
DevMpl/mlblog
lib/mlblog/version.rb
Ruby
mit
38
var scroungejs = require('scroungejs'), startutils = require('./startutil'); startutils.createFileIfNotExist({ pathSrc : './test/indexSrc.html', pathFin : './test/index.html' }, function (err, res) { if (err) return console.log(err); scroungejs.build({ inputPath : [ './test/testbuildSrc', './node_modules', './bttnsys.js' ], outputPath : './test/testbuildFin', isRecursive : true, isSourcePathUnique : true, isCompressed : false, isConcatenated : false, basepage : './test/index.html' }, function (err, res) { return (err) ? console.log(err) : console.log('finished!'); }); });
iambumblehead/bttnsys
test/testrun.js
JavaScript
mit
654
var Struct = ( function() { return function ( members ) { var mode = "default"; var ctor = function( values ) { if ( mode === "new" ) { mode = "void"; return new Struct(); } if ( mode === "void" ) return; mode = "new"; var instance = Struct(); mode = "default"; extend( instance, members, values || {} ); return instance; }; var Struct = function() { return ctor.apply( undefined, arguments ); }; return Struct; }; function extend( instance, members, values ) { var pending = [{ src: values, tmpl: members, dest: instance }]; while ( pending.length ) { var task = pending.shift(); if ( task.array ) { var i = 0, len = task.array.length; for ( ; i < len; i++ ) { switch ( typeOf( task.array[ i ] ) ) { case "object": var template = task.array[ i ]; task.array[ i ] = {}; pending.push({ tmpl: template, dest: task.array[ i ] }); break; case "array": task.array[ i ] = task.array[ i ].slice( 0 ); pending.push({ array: task.array[ i ] }); break; } } } else { for ( var prop in task.tmpl ) { if ( task.src[ prop ] !== undefined ) task.dest[ prop ] = task.src[ prop ]; else { switch ( typeOf( task.tmpl[ prop ] ) ) { case "object": task.dest[ prop ] = {}; pending.push({ tmpl: task.tmpl[ prop ], dest: task.dest[ prop ] }); break; case "array": task.dest[ prop ] = task.tmpl[ prop ].slice( 0 ); pending.push({ array: task.dest[ prop ] }); break; default: task.dest[ prop ] = task.tmpl[ prop ]; break; } } } } } } } () );
stephenbunch/type
src/Struct.js
JavaScript
mit
3,084
var utils = require('./utils') , request = require('request') ; module.exports = { fetchGithubInfo: function(email, cb) { var githubProfile = {}; var api_call = "https://api.github.com/search/users?q="+email+"%20in:email"; var options = { url: api_call, headers: { 'User-Agent': 'Blogdown' } }; console.log("Calling "+api_call); request(options, function(err, res, body) { if(err) return cb(err); res = JSON.parse(body); if(res.total_count==1) githubProfile = res.items[0]; cb(null, githubProfile); }); }, fetchGravatarProfile: function(email, cb) { var gravatarProfile = {}; var hash = utils.getHash(email); var api_call = "http://en.gravatar.com/"+hash+".json"; console.log("Calling "+api_call); var options = { url: api_call, headers: { 'User-Agent': 'Blogdown' } }; request(options, function(err, res, body) { if(err) return cb(err); try { res = JSON.parse(body); } catch(e) { console.error("fetchGravatarProfile: Couldn't parse response JSON ", body, e); return cb(e); } if(res.entry && res.entry.length > 0) gravatarProfile = res.entry[0]; return cb(null, gravatarProfile); }); } };
xdamman/blogdown
core/server/lib/contributors.js
JavaScript
mit
1,262
// // STShare.h // Loopy // // Created by David Jedeikin on 10/23/13. // Copyright (c) 2013 ShareThis. All rights reserved. // #import "STAPIClient.h" #import <Foundation/Foundation.h> #import <Social/Social.h> @interface STShareActivityUI : NSObject @property (nonatomic, strong) UIViewController *parentController; @property (nonatomic, strong) STAPIClient *apiClient; - (id)initWithParent:(UIViewController *)parent apiClient:(STAPIClient *)client; - (NSArray *)getDefaultActivities:(NSArray *)activityItems; - (UIActivityViewController *)newActivityViewController:(NSArray *)shareItems withActivities:(NSArray *)activities; - (SLComposeViewController *)newActivityShareController:(id)activityObj; - (void)showActivityViewDialog:(UIActivityViewController *)activityController completion:(void (^)(void))completion; - (void)handleShareDidBegin:(NSNotification *)notification; - (void)handleShareDidComplete:(NSNotification *)notification; @end
socialize/loopy-ios
Loopy/STShareActivityUI.h
C
mit
954
using Radical.Reflection; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Reflection; namespace Radical.Windows { static class PropertyInfoExtensions { public static string GetDisplayName(this PropertyInfo propertyInfo) { if (propertyInfo != null && propertyInfo.IsAttributeDefined<DisplayAttribute>()) { var a = propertyInfo.GetAttribute<DisplayAttribute>(); return a.GetName(); } if (propertyInfo != null && propertyInfo.IsAttributeDefined<DisplayNameAttribute>()) { var a = propertyInfo.GetAttribute<DisplayNameAttribute>(); return a.DisplayName; } return null; } } }
RadicalFx/Radical.Windows
src/Radical.Windows/PropertyInfoExtensions.cs
C#
mit
801
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SimpleCiphers.Models { public static class ArrayOperations { // Содержится ли text в encAbc. Если да, то возвращаются индексы в encAbc // a b text = 1 // a 1 2 return x = 0, y = 0 // b 3 4 abc[0,0] = aa - расшифрованный // encAbc[0,0] = 1 - зашифрованный public static bool ContainsIn(string text, string[,] encAbc, out int x, out int y) { for (var i = 0; i < encAbc.GetLength(0); i++) { for (var j = 0; j < encAbc.GetLength(1); j++) { if (text != encAbc[i, j]) continue; x = i; y = j; return true; } } x = -1; y = -1; return false; } public static string[,] Turn1DTo2D(string[] encAbc) { var arr = new string[1, encAbc.Length]; for (var i = 0; i < encAbc.Length; i++) { arr[0, i] = $"{encAbc[i]}"; } return arr; } } }
slavitnas/SimpleCiphers
SimpleCiphers/Models/ArrayOperations.cs
C#
mit
1,318
import java.text.NumberFormat; // **************************************************************** // ManageAccounts.java // Use Account class to create and manage Sally and Joe's bank accounts public class ManageAccounts { public static void main(String[] args) { Account acct1, acct2; NumberFormat usMoney = NumberFormat.getCurrencyInstance(); //create account1 for Sally with $1000 acct1 = new Account(1000, "Sally", 1111); //create account2 for Joe with $500 acct2 = new Account(500, "Joe", 1212); //deposit $100 to Joe's account acct2.deposit(100); //print Joe's new balance (use getBalance()) System.out.println("Joe's new balance: " + usMoney.format(acct2.getBalance())); //withdraw $50 from Sally's account acct1.withdraw(50); //print Sally's new balance (use getBalance()) System.out.println("Sally's new balance: " + usMoney.format(acct1.getBalance())); //charge fees to both accounts System.out.println("Sally's new balance after the fee is charged: " + usMoney.format(acct1.chargeFee())); System.out.println("Joe's new balance after the fee is charged: " + usMoney.format(acct2.chargeFee())); //change the name on Joe's account to Joseph acct2.changeName("Joseph"); //print summary for both accounts System.out.println(acct1); System.out.println(acct2); //close and display Sally's account acct1.close(); System.out.println(acct1); //consolidate account test (doesn't work as acct1 Account newAcct = Account.consolidate(acct1, acct2); System.out.println(acct1); } }
pegurnee/2013-03-211
workspace/Lecture 09_18_13/src/ManageAccounts.java
Java
mit
1,595
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <?php include_http_metas() ?> <?php include_metas() ?> <?php include_title() ?> </head> <body id="body" lang="en"> <?php echo $sf_content ?> </body> </html>
appflower/appflower_engine
modules/appFlower/templates/layout.php
PHP
mit
357
from api_request import Api from util import Util from twocheckout import Twocheckout class Sale(Twocheckout): def __init__(self, dict_): super(self.__class__, self).__init__(dict_) @classmethod def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale @classmethod def list(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/list_sales', params)) return response.sale_summary def refund(self, params=None): if params is None: params = dict() if hasattr(self, 'lineitem_id'): params['lineitem_id'] = self.lineitem_id url = 'sales/refund_lineitem' elif hasattr(self, 'invoice_id'): params['invoice_id'] = self.invoice_id url = 'sales/refund_invoice' else: params['sale_id'] = self.sale_id url = 'sales/refund_invoice' return Sale(Api.call(url, params)) def stop(self, params=None): if params is None: params = dict() if hasattr(self, 'lineitem_id'): params['lineitem_id'] = self.lineitem_id return Api.call('sales/stop_lineitem_recurring', params) elif hasattr(self, 'sale_id'): active_lineitems = Util.active(self) if dict(active_lineitems): result = dict() i = 0 for k, v in active_lineitems.items(): lineitem_id = v params = {'lineitem_id': lineitem_id} result[i] = Api.call('sales/stop_lineitem_recurring', params) i += 1 response = { "response_code": "OK", "response_message": str(len(result)) + " lineitems stopped successfully" } else: response = { "response_code": "NOTICE", "response_message": "No active recurring lineitems" } else: response = { "response_code": "NOTICE", "response_message": "This method can only be called on a sale or lineitem" } return Sale(response) def active(self): active_lineitems = Util.active(self) if dict(active_lineitems): result = dict() i = 0 for k, v in active_lineitems.items(): lineitem_id = v result[i] = lineitem_id i += 1 response = { "response_code": "ACTIVE", "response_message": str(len(result)) + " active recurring lineitems" } else: response = { "response_code": "NOTICE","response_message": "No active recurring lineitems" } return Sale(response) def comment(self, params=None): if params is None: params = dict() params['sale_id'] = self.sale_id return Sale(Api.call('sales/create_comment', params)) def ship(self, params=None): if params is None: params = dict() params['sale_id'] = self.sale_id return Sale(Api.call('sales/mark_shipped', params))
2Checkout/2checkout-python
twocheckout/sale.py
Python
mit
3,388
<?php /** * wm.class.php - window manager * * handles window groups and multiple gtkwindow object easily * * This is released under the GPL, see docs/gpl.txt for details * * @author Leon Pegg <leon.pegg@gmail.com> * @author Elizabeth M Smith <emsmith@callicore.net> * @copyright Leon Pegg (c)2006 * @link http://callicore.net/desktop * @license http://www.opensource.org/licenses/gpl-license.php GPL * @version $Id: wm.class.php 64 2006-12-10 18:09:56Z emsmith $ * @since Php 5.1.0 * @package callicore * @subpackage desktop * @category lib * @filesource */ /** * Class for handling multiple GtkWindow objects * * contains all static methods */ class CC_Wm { /** * GtkWindow object array * [string GtkWindow_Name] * array( * GtkWindow - Store GtkWindow object * ) * * @var array */ protected static $windows = array(); /** * GtkWindowGroup - for making grabs work properly (see GtkWidget::grab_add) * * @var object instanceof GtkWindowGroup */ protected static $window_group; /** * public function __construct * * forces only static calls * * @return void */ public function __construct() { throw new CC_Exception('CC_WM contains only static methods and cannot be constructed'); } /** * Adds a GtkWindow object to CC_WM::$windows * * @param object $window instanceof GtkWindow * @return bool */ public static function add_window(GtkWindow $window) { $name = $window->get_name(); if ($name !== '' && !array_key_exists($name, self::$windows)) { if (!is_object(self::$window_group)) { self::$window_group = new GtkWindowGroup(); } self::$window_group->add_window($window); self::$windows[$name] = $window; return true; } return false; } /** * Removes a GtkWindow object from CC_WM::$windows * * @param string $name * @return object instanceof GtkWindow */ public static function remove_window($name) { if ($name !== '' && array_key_exists($name, self::$windows)) { $window = self::$windows[$$name]; unset(self::$windows[$name]); self::$window_group->remove_window($window); return $window; } return false; } /** * Retrives GtkWindow object from CC_WM::$windows * * @param string $name * @return object instanceof GtkWindow */ public static function get_window($name) { if ($name !== '' && array_key_exists($name, self::$windows)) { return self::$windows[$name]; } return false; } /** * Retrives CC_WM::$windows infomation array * Structure: * [int window_id] * array( * name - Name of GtkWindow * class - Name of GtkWindow class * ) * * @return array */ public static function list_windows() { $list = array(); foreach (self::$windows as $name => $class) { $list[] = array('name' => $name, 'class' => $get_class($class)); } return $list; } /** * Shows all windows in the manager */ public static function show_all_windows() { foreach (self::$windows as $window) { $window->show_all(); } } /** * hides all the windows in the manager */ public static function hide_all_windows() { foreach (self::$windows as $window) { $window->hide_all(); } } /** * See if a specific window exists * * @param string $name name of window to check for * @return bool */ public static function is_window($name) { return array_key_exists($name, self::$windows); } /** * public function hide_all * * overrides hide_all for windows manager integration * * @return void */ public function hide_all() { if (class_exists('CC_Wm') && CC_Wm::is_window($this->get_name()) && $this->is_modal) { parent::grab_remove(); $return = parent::hide_all(); $this->is_modal = false; return $return; } else { return parent::hide_all(); } } /** * public function show_all * * overrides show_all for windows manager integration * * @return void */ public function show_all($modal = false) { if (class_exists('CC_Wm') && CC_Wm::is_window($this->get_name())) { $return = parent::show_all(); parent::grab_add(); $this->is_modal = true; return $return; } else { return parent::show_all(); } } }
callicore/library
lib/lib/wm.class.php
PHP
mit
4,546
module.exports = FormButtonsDirective; function FormButtonsDirective () { return { restrict: 'AE', replace: true, scope: { submitClick: '&submitClick', cancelClick: '&cancelClick' }, templateUrl: '/src/utils/views/formButtons.tmpl.html', link: function (scope, elem) { angular.element(elem[0].getElementsByClassName('form-button-submit')).on('click', function () { scope.submitClick(); }); angular.element(elem[0].getElementsByClassName('form-button-cancel')).on('click', function () { scope.cancelClick(); }); } }; }
zazujs/mufasa
app/src/utils/formButtons.directive.js
JavaScript
mit
687
ActionController::Routing::Routes.draw do |map| map.resources :projects map.resources :priorities map.resources :tasks # The priority is based upon order of creation: first created -> highest priority. # Sample of regular route: # map.connect 'products/:id', :controller => 'catalog', :action => 'view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase' # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # map.resources :products # Sample resource route with options: # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get } # Sample resource route with sub-resources: # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller # Sample resource route with more complex sub-resources # map.resources :products do |products| # products.resources :comments # products.resources :sales, :collection => { :recent => :get } # end # Sample resource route within a namespace: # map.namespace :admin do |admin| # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb) # admin.resources :products # end # You can have the root of your site routed with map.root -- just remember to delete public/index.html. # map.root :controller => "welcome" # See how all your routes lay out with "rake routes" # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible via GET requests. You should # consider removing or commenting them out if you're using named routes and resources. map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end
elseano/intervention
test/config/routes.rb
Ruby
mit
1,991
<?php namespace Master\AdvertBundle\Controller; use Elastica\Filter\GeoDistance; use Elastica\Query\Filtered; use Elastica\Query\MatchAll; use Master\AdvertBundle\Document\Advert; use Master\AdvertBundle\Document\Localization; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class DefaultController extends Controller { public function indexAction(Request $request) { $p=1; if($request->query->get('page')!=null) $p=intval($request->query->get('page')); $adverts=$this->advertShow($request,$p); return $this->render('AdvertBundle:Default:index.html.twig',array('advert'=>$adverts)); } public function addAction(Request $request) { if($request->getMethod()=="POST") { $manager=$this->get('doctrine_mongodb'); $localisation=new Localization(); $localisation->setLatitude($request->request->get('lat')); $localisation->setLongitude($request->request->get('long')); $advert = new Advert(); $advert->setTitle($request->request->get('title')); $advert->setDescription($request->request->get('description')); $advert->setFax($request->request->get('fax')); $advert->setTelephone($request->request->get('tel')); $advert->setTokenuser($this->getUser()->getToken()); $advert->setLocalization($localisation); $manager->getManager()->persist($advert); $manager->getManager()->flush(); $adverts=$this->advertShow($request,1); return $this->render('AdvertBundle:Default:index.html.twig',array("advert"=>$adverts)); }else{ return $this->render('AdvertBundle:Advert:add.html.twig'); } } public function testAction(){ $filter = new GeoDistance('location', array('lat' => -2.1741771697998047, 'lon' => 43.28249657890983), '10000km'); $query = new Filtered(new MatchAll(), $filter); $manager=$this->get('fos_elastica.finder.structure.advert'); $test=$manager->find($query); var_dump($test);exit; return new Response("TEST"); } public function advertShow($request,$p) { $manager=$this->get('fos_elastica.finder.structure.advert'); $pagination=$manager->find("",100); // var_dump($pagination);exit; $paginator = $this->get('knp_paginator'); $adverts = $paginator->paginate( $pagination, $request->query->get('page', $p)/*page number*/, 6/*limit per page*/ ); return $adverts; } }
friendsofdigital/structure-symfony
src/Master/AdvertBundle/Controller/DefaultController.php
PHP
mit
2,725
$context.section('Простое связывание', 'Иерархическое связывание с данными с использованием простых и составных ключей'); //= require data-basic $context.section('Форматирование', 'Механизм одностороннего связывания (one-way-binding)'); //= require data-format $context.section('Настройка', 'Управление изменением виджета при обновлении данных'); //= require data-binding $context.section('Динамическое связывание', 'Управление коллекцией элементов виджета через источник данных'); //= require data-dynamic $context.section('Общие данные'); //= require data-share $context.section('"Грязные" данные', 'Уведомление родительских источников данных о том, что значение изменилось'); //= require data-dirty
eliace/ergojs-site
samples/core/widget/data/index.js
JavaScript
mit
1,056
/*The MIT License (MIT) Copyright (c) 2016 Muhammad Hammad 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 Sogiftware. 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.*/ package org.dvare.annotations; import org.dvare.expression.datatype.DataType; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface Type { DataType dataType(); }
hammadirshad/dvare
src/main/java/org/dvare/annotations/Type.java
Java
mit
1,450
import json import os from flask import request, g, render_template, make_response, jsonify, Response from helpers.raw_endpoint import get_id, store_json_to_file from helpers.groups import get_groups from json_controller import JSONController from main import app from pymongo import MongoClient, errors HERE = os.path.dirname(os.path.abspath(__file__)) # setup database connection def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db @app.teardown_appcontext def close_db(error): """Closes connection with Mongo client""" if hasattr(g, 'mongo_client'): g.mongo_client.close() # Begin view routes @app.route('/') @app.route('/index/') def index(): """Landing page for SciNet""" return render_template("index.html") @app.route('/faq/') def faq(): """FAQ page for SciNet""" return render_template("faq.html") @app.route('/leaderboard/') def leaderboard(): """Leaderboard page for SciNet""" get_db() groups = get_groups(g.groups_collection) return render_template("leaderboard.html", groups=groups) @app.route('/ping', methods=['POST']) def ping_endpoint(): """API endpoint determines potential article hash exists in db :return: status code 204 -- hash not present, continue submission :return: status code 201 -- hash already exists, drop submission """ db = get_db() target_hash = request.form.get('hash') if db.raw.find({'hash': target_hash}).count(): return Response(status=201) else: return Response(status=204) @app.route('/articles') def ArticleEndpoint(): """Eventual landing page for searching/retrieving articles""" if request.method == 'GET': return render_template("articles.html") @app.route('/raw', methods=['POST']) def raw_endpoint(): """API endpoint for submitting raw article data :return: status code 405 - invalid JSON or invalid request type :return: status code 400 - unsupported content-type or invalid publisher :return: status code 201 - successful submission """ # Ensure post's content-type is supported if request.headers['content-type'] == 'application/json': # Ensure data is a valid JSON try: user_submission = json.loads(request.data) except ValueError: return Response(status=405) # generate UID for new entry uid = get_id() # store incoming JSON in raw storage file_path = os.path.join( HERE, 'raw_payloads', str(uid) ) store_json_to_file(user_submission, file_path) # hand submission to controller and return Resposne db = get_db() controller_response = JSONController(user_submission, db=db, _id=uid).submit() return controller_response # User submitted an unsupported content-type else: return Response(status=400) #@TODO: Implicit or Explicit group additions? Issue #51 comments on the issues page #@TODO: Add form validation @app.route('/requestnewgroup/', methods=['POST']) def request_new_group(): # Grab submission form data and prepare email message data = request.json msg = "Someone has request that you add {group_name} to the leaderboard \ groups. The groups website is {group_website} and the submitter can \ be reached at {submitter_email}.".format( group_name=data['new_group_name'], group_website=data['new_group_website'], submitter_email=data['submitter_email']) return Response(status=200) ''' try: email( subject="SciNet: A new group has been requested", fro="no-reply@scinet.osf.io", to='harry@scinet.osf.io', msg=msg) return Response(status=200) except: return Response(status=500) ''' # Error handlers @app.errorhandler(404) def not_found(error): return make_response(jsonify( { 'error': 'Page Not Found' } ), 404) @app.errorhandler(405) def method_not_allowed(error): return make_response(jsonify( { 'error': 'Method Not Allowed' } ), 405)
CenterForOpenScience/scinet
scinet/views.py
Python
mit
4,696
package com.arekusu.datamover.model.jaxb; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.arekusu.com}DefinitionType"/> * &lt;/sequence> * &lt;attribute name="version" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "definitionType" }) @XmlRootElement(name = "ModelType", namespace = "http://www.arekusu.com") public class ModelType { @XmlElement(name = "DefinitionType", namespace = "http://www.arekusu.com", required = true) protected DefinitionType definitionType; @XmlAttribute(name = "version") protected String version; /** * Gets the value of the definitionType property. * * @return * possible object is * {@link DefinitionType } * */ public DefinitionType getDefinitionType() { return definitionType; } /** * Sets the value of the definitionType property. * * @param value * allowed object is * {@link DefinitionType } * */ public void setDefinitionType(DefinitionType value) { this.definitionType = value; } /** * Gets the value of the version property. * * @return * possible object is * {@link String } * */ public String getVersion() { return version; } /** * Sets the value of the version property. * * @param value * allowed object is * {@link String } * */ public void setVersion(String value) { this.version = value; } }
Arrekusu/datamover
components/datamover-core/src/main/java/com/arekusu/datamover/model/jaxb/ModelType.java
Java
mit
2,303
<?php namespace PragmaRX\Sdk\Services\Accounts\Exceptions; use PragmaRX\Sdk\Core\HttpResponseException; class InvalidPassword extends HttpResponseException { protected $message = 'paragraphs.invalid-password'; }
antonioribeiro/sdk
src/Services/Accounts/Exceptions/InvalidPassword.php
PHP
mit
218
import React from 'react'; import './skills.scss'; export default () => { return ( <section className="skills-section"> <svg className="bigTriangleColor separator-skills" width="100%" height="100" viewBox="0 0 100 102" preserveAspectRatio="none"> <path d="M0 0 L0 100 L70 0 L100 100 L100 0 Z" /> </svg> <h2 className="skills-header">Skills</h2> <p className="skills tlt"> Javascript/ES6 React Redux Node Express MongoDB GraphQL REST Next.js Mocha Jest JSS PostCSS SCSS LESS AWS nginx jQuery Webpack Rollup UI/Design </p> <button className="button button--wayra button--inverted skills-btn"> View My <i className="fa fa-github skills-github"></i><a className="skills-btn-a" href="https://www.github.com/musicbender" target="_blank"></a> </button> </section> ); }
musicbender/my-portfolio
src/components/skills/skills.js
JavaScript
mit
851
import axios from 'axios'; export default axios.create({ baseURL: 'http://localhost:9000/v1/' });
FrederikS/das-blog-frontend
app/http/client.js
JavaScript
mit
102
/* * THIS FILE IS AUTO GENERATED FROM 'lib/lex/lexer.kep' * DO NOT EDIT */ define(["require", "exports", "bennu/parse", "bennu/lang", "nu-stream/stream", "ecma-ast/token", "ecma-ast/position", "./boolean_lexer", "./comment_lexer", "./identifier_lexer", "./line_terminator_lexer", "./null_lexer", "./number_lexer", "./punctuator_lexer", "./reserved_word_lexer", "./string_lexer", "./whitespace_lexer", "./regular_expression_lexer" ], (function(require, exports, parse, __o, __o0, lexToken, __o1, __o2, comment_lexer, __o3, line_terminator_lexer, __o4, __o5, __o6, __o7, __o8, whitespace_lexer, __o9) { "use strict"; var lexer, lexStream, lex, always = parse["always"], attempt = parse["attempt"], binds = parse["binds"], choice = parse["choice"], eof = parse["eof"], getPosition = parse["getPosition"], modifyState = parse["modifyState"], getState = parse["getState"], enumeration = parse["enumeration"], next = parse["next"], many = parse["many"], runState = parse["runState"], never = parse["never"], ParserState = parse["ParserState"], then = __o["then"], streamFrom = __o0["from"], SourceLocation = __o1["SourceLocation"], SourcePosition = __o1["SourcePosition"], booleanLiteral = __o2["booleanLiteral"], identifier = __o3["identifier"], nullLiteral = __o4["nullLiteral"], numericLiteral = __o5["numericLiteral"], punctuator = __o6["punctuator"], reservedWord = __o7["reservedWord"], stringLiteral = __o8["stringLiteral"], regularExpressionLiteral = __o9["regularExpressionLiteral"], type, type0, type1, type2, type3, p, type4, type5, type6, type7, p0, type8, p1, type9, p2, consume = ( function(tok, self) { switch (tok.type) { case "Comment": case "Whitespace": case "LineTerminator": return self; default: return tok; } }), isRegExpCtx = (function(prev) { if ((!prev)) return true; switch (prev.type) { case "Keyword": case "Punctuator": return true; } return false; }), enterRegExpCtx = getState.chain((function(prev) { return (isRegExpCtx(prev) ? always() : never()); })), literal = choice(((type = lexToken.StringToken.create), stringLiteral.map((function(x) { return [type, x]; }))), ((type0 = lexToken.BooleanToken.create), booleanLiteral.map((function(x) { return [type0, x]; }))), ((type1 = lexToken.NullToken.create), nullLiteral.map((function(x) { return [type1, x]; }))), ((type2 = lexToken.NumberToken.create), numericLiteral.map((function(x) { return [type2, x]; }))), ((type3 = lexToken.RegularExpressionToken.create), (p = next(enterRegExpCtx, regularExpressionLiteral)), p.map((function(x) { return [type3, x]; })))), token = choice(attempt(((type4 = lexToken.IdentifierToken), identifier.map((function(x) { return [type4, x]; })))), literal, ((type5 = lexToken.KeywordToken), reservedWord.map((function(x) { return [type5, x]; }))), ((type6 = lexToken.PunctuatorToken), punctuator.map((function(x) { return [type6, x]; })))), inputElement = choice(((type7 = lexToken.CommentToken), (p0 = comment_lexer.comment), p0.map((function( x) { return [type7, x]; }))), ((type8 = lexToken.WhitespaceToken), (p1 = whitespace_lexer.whitespace), p1.map((function(x) { return [type8, x]; }))), ((type9 = lexToken.LineTerminatorToken), (p2 = line_terminator_lexer.lineTerminator), p2.map( (function(x) { return [type9, x]; }))), token); (lexer = then(many(binds(enumeration(getPosition, inputElement, getPosition), (function(start, __o10, end) { var type10 = __o10[0], value = __o10[1]; return always(new(type10)(new(SourceLocation)(start, end, (start.file || end.file)), value)); })) .chain((function(tok) { return next(modifyState(consume.bind(null, tok)), always(tok)); }))), eof)); (lexStream = (function(s, file) { return runState(lexer, new(ParserState)(s, new(SourcePosition)(1, 0, file), null)); })); var y = lexStream; (lex = (function(z) { return y(streamFrom(z)); })); (exports["lexer"] = lexer); (exports["lexStream"] = lexStream); (exports["lex"] = lex); }));
mattbierner/parse-ecma
dist/lex/lexer.js
JavaScript
mit
4,873
<h1><?=$title?></h1> <h5>Ordered by Points</h5> <?php foreach ($users as $user) : ?> <div class="mini-profile left"> <img class="gravatar left" src="<?= $this->mzHelpers->get_gravatar($user->email, 128); ?>" alt=""> <div class="info"> <a href="<?= $this->url->create('users/id/' . $user->id ); ?>"><?= $user->username ?></a> <br> Points: <?= $user->points ?> </div> </div> <?php endforeach; ?>
nuvalis/GMAQ
app/view/users/list-all.tpl.php
PHP
mit
587
// Multiprocessor support // mist32 is not supported multiprocessor #include "types.h" #include "defs.h" #include "param.h" #include "memlayout.h" #include "mmu.h" #include "proc.h" struct cpu cpus[NCPU]; int ismp; int ncpu; void mpinit(void) { ismp = 0; ncpu = 1; lapic = 0; cpus[ncpu].id = ncpu; ncpu++; return; }
techno/xv6-mist32
mp.c
C
mit
333
#include <stdio.h> #include "cgm_play.h" #include "cgm_list.h" #ifndef _CGM_TYPES_H_ #define _CGM_TYPES_H_ #ifdef __cplusplus extern "C" { #endif typedef int(*CGM_FUNC)(tCGM* cgm); typedef struct { double xmin; double xmax; double ymin; double ymax; } tLimit; typedef struct { unsigned long red; unsigned long green; unsigned long blue; } tRGB; typedef union { unsigned long index; tRGB rgb; } tColor; typedef struct { char *data; int size; /* allocated size */ int len; /* used size */ int bc; /* byte count */ int pc; /* pixel count */ } tData; typedef struct { const char *name; CGM_FUNC func; } tCommand; typedef struct { long index; long type; long linecap; long dashcap; /* unused */ long linejoin; double width; tColor color; } tLineAtt; typedef struct { long index; long type; long linecap; long dashcap; /* unused */ long linejoin; double width; tColor color; short visibility; } tEdgeAtt; typedef struct { long index; long type; double size; tColor color; } tMarkerAtt; typedef struct { long index; long font_index; tList *font_list; short prec; /* unused */ double exp_fact; double char_spacing; /* unused */ tColor color; double height; cgmPoint char_up; /* unused */ cgmPoint char_base; short path; long restr_type; /* unused */ struct { short hor; short ver; double cont_hor; /* unused */ double cont_ver; /* unused */ } alignment; } tTextAtt; typedef struct { long index; short int_style; tColor color; long hatch_index; long pat_index; tList *pat_list; cgmPoint ref_pt; /* unused */ struct { cgmPoint height; /* unused */ cgmPoint width; /* unused */ } pat_size; /* unused */ } tFillAtt; typedef struct { long index; long nx, ny; tColor *pattern; } tPatTable; typedef struct { short type; short value; } tASF; struct _tCGM { FILE *fp; int file_size; tData buff; union { long b_prec; /* 0=8, 1=16, 2=24, 3=32 */ struct { long minint; long maxint; } t_prec ; } int_prec; union { long b_prec; /* 0=float*32, 1=float*64(double), 2=fixed*32, 3=fixed*64 */ struct { double minreal; double maxreal; long digits; } t_prec; } real_prec; union { long b_prec; /* 0=8, 1=16, 2=24, 3=32 */ struct { long minint; long maxint; } t_prec; } ix_prec; long cd_prec; /* used only for binary */ long cix_prec; /* used only for binary */ struct { tRGB black; tRGB white; } color_ext; long max_cix; tRGB* color_table; struct { short mode; /* abstract (pixels, factor is always 1), metric (coordinate * factor = coordinate_mm) */ double factor; } scale_mode; short color_mode; /* indexed, direct */ short linewidth_mode; /* absolute, scaled, fractional, mm */ short markersize_mode; /* absolute, scaled, fractional, mm */ short edgewidth_mode; /* absolute, scaled, fractional, mm */ short interiorstyle_mode; /* absolute, scaled, fractional, mm (unused) */ short vdc_type; /* integer, real */ union { long b_prec; /* 0=8, 1=16, 2=24, 3=32 */ struct { long minint; long maxint; } t_prec; } vdc_int; union { long b_prec; /* 0=float*32, 1=float*64(double), 2=fixed*32, 3=fixed*64 */ struct { double minreal; double maxreal; long digits; } t_prec; } vdc_real; struct { cgmPoint first; /* lower-left corner */ cgmPoint second; /* upper-right corner */ cgmPoint maxFirst; /* maximum lower-left corner */ cgmPoint maxSecond; /* maximum upper-right corner */ short has_max; } vdc_ext; tRGB back_color; tColor aux_color; short transparency; short cell_transp; /* (affects cellarray and pattern) unused */ tColor cell_color; /* unused */ struct { cgmPoint first; cgmPoint second; } clip_rect; short clip_ind; long region_idx; /* unused */ long region_ind; /* unused */ long gdp_sample_type, gdp_n_samples; cgmPoint gdp_pt[4]; char* gdp_data_rec; double mitrelimit; /* unused */ tLineAtt line_att; tMarkerAtt marker_att; tTextAtt text_att; tFillAtt fill_att; tEdgeAtt edge_att; tList* asf_list; /* unused */ cgmPoint* point_list; int point_list_n; cgmPlayFuncs dof; void* userdata; }; #define CGM_CONT 3 enum { CGM_OFF, CGM_ON }; enum { CGM_INTEGER, CGM_REAL }; enum { CGM_STRING, CGM_CHAR, CGM_STROKE }; enum { CGM_ABSOLUTE, CGM_SCALED, CGM_FRACTIONAL, CGM_MM }; enum { CGM_ABSTRACT, CGM_METRIC }; enum { CGM_INDEXED, CGM_DIRECT }; enum { CGM_HOLLOW, CGM_SOLID, CGM_PATTERN, CGM_HATCH, CGM_EMPTY, CGM_GEOPAT, CGM_INTERP }; enum { CGM_INVISIBLE, CGM_VISIBLE, CGM_CLOSE_INVISIBLE, CGM_CLOSE_VISIBLE }; enum { CGM_PATH_RIGHT, CGM_PATH_LEFT, CGM_PATH_UP, CGM_PATH_DOWN }; int cgm_bin_rch(tCGM* cgm); int cgm_txt_rch(tCGM* cgm); void cgm_strupper(char *s); void cgm_calc_arc_3p(cgmPoint start, cgmPoint intermediate, cgmPoint end, cgmPoint *center, double *radius, double *angle1, double *angle2); void cgm_calc_arc(cgmPoint start, cgmPoint end, double *angle1, double *angle2); void cgm_calc_arc_rev(cgmPoint start, cgmPoint end, double *angle1, double *angle2); void cgm_calc_ellipse(cgmPoint center, cgmPoint first, cgmPoint second, cgmPoint start, cgmPoint end, double *angle1, double *angle2); cgmRGB cgm_getcolor(tCGM* cgm, tColor color); cgmRGB cgm_getrgb(tCGM* cgm, tRGB rgb); void cgm_getcolor_ar(tCGM* cgm, tColor color, unsigned char *r, unsigned char *g, unsigned char *b); void cgm_setmarker_attrib(tCGM* cgm); void cgm_setline_attrib(tCGM* cgm); void cgm_setedge_attrib(tCGM* cgm); void cgm_setfill_attrib(tCGM* cgm); void cgm_settext_attrib(tCGM* cgm); int cgm_inccounter(tCGM* cgm); void cgm_polygonset(tCGM* cgm, int np, cgmPoint* pt, short* flags); void cgm_generalizeddrawingprimitive(tCGM* cgm, int id, int np, cgmPoint* pt, const char* data_rec); void cgm_sism5(tCGM* cgm, const char *data_rec); #ifdef __cplusplus } #endif #endif
kmx/mirror-cd
src/intcgm/cgm_types.h
C
mit
6,161
require 'spec_helper' require 'serializables/vector3' describe Moon::Vector3 do context 'Serialization' do it 'serializes' do src = described_class.new(12, 8, 4) result = described_class.load(src.export) expect(result).to eq(src) end end end
polyfox/moon-packages
spec/moon/packages/serializables/vector3_spec.rb
Ruby
mit
274
package org.liquidizer.snippet import scala.xml._ import scala.xml.parsing._ import net.liftweb.util._ import net.liftweb.http._ import net.liftweb.http.js._ import net.liftweb.http.js.JsCmds._ import net.liftweb.common._ import org.liquidizer.model._ object Markup { val URL1= "(https?:/[^\\s\"]*[^\\s!?&.<>])" val URL2= "\\["+URL1+" ([^]]*)\\]" val URL_R= (URL1+"|"+URL2).r def renderComment(in : String) : NodeSeq = { if (in==null || in.length==0) NodeSeq.Empty else toXHTML(in) } def toXHTML(input : String) : NodeSeq = { try { val src= scala.io.Source.fromString("<span>"+input+"</span>") tidy(XhtmlParser(src).first.child, false) } catch { case e:FatalError => <p>{input}</p> } } def tidy(seq : NodeSeq, isLink : Boolean) : NodeSeq = seq.flatMap { tidy(_, isLink) } def tidy(node : Node, isLink : Boolean) : NodeSeq = node match { case Elem(ns, tag, attr, scope, ch @ _*) => tag match { case "img" | "em" | "i" => val allowed= Set("src", "width", "height") val fAttr= attr.filter { n=> allowed.contains(n.key) } Elem(ns, tag, fAttr, scope, tidy(ch, true) :_*) case _ => Text(node.toString) } case Text(text) if !isLink => renderBlock(text.split("\n").toList) case _ => Text(node.toString) } def renderBlock(in : List[String]) : List[Node] = { def tail= renderBlock(in.tail) in match { case Nil => Nil case List(line, _*) if line.matches(" *[*-] .*") => { val li = <li>{ renderLine(line.replaceAll("^ *[*-]","")) }</li> tail match { case <ul>{ c @ _* }</ul> :: t => <ul>{ li ++ c }</ul> :: t case t => <ul>{ li }</ul> :: t } } case List(line, _*) => <p>{ renderLine(line) }</p> :: tail } } def renderLine(in : String) = renderHeader(in, x=>x, x=>x) def renderTagList(in:List[String]) : Node = { <span class="keys">{ var isFirst= true in.map { key => val suff= if (isFirst) NodeSeq.Empty else Text(", ") isFirst= false suff ++ <a class="tag" href={Helpers.appendParams("/queries.html",("search",key) :: Nil)}>{key}</a> }}</span> } def renderHeader(in : String, link : String) : NodeSeq = renderHeader(in, { node => <a href={link}>{node}</a> }) def renderHeader(in : String, link : Node=>Node) : NodeSeq = { var c=0 renderHeader(in, link, x=> {c=c+1; "["+c+"]"}) } /** render a header replacing links with a generic short cut */ def renderHeader(in : String, link : Node=>Node, short : String=>String) : NodeSeq = { URL_R.findFirstMatchIn(in) match { case Some(m) => link(Text(m.before.toString)) ++ { if (m.group(1)==null) { eLink(m.group(2), "["+m.group(3)+"]") } else { eLink(m.matched, short(m.matched)) } } ++ renderHeader(m.after.toString, link, short) case _ => link(Text(in)) } } /** make an external link */ def eLink(url : String, display : String) = <a href={url} title={url} target="_blank" class="extern">{display}</a> } class CategoryView(val keys : List[String], rootLink:String) { def this(keyStr : String, rootLink : String) = this(keyStr.toLowerCase.split(",| ").distinct.toList, rootLink) def isActive(tag : String) = keys.contains(tag.toLowerCase) def link(node : Node, keys : List[String]) = { val sort= S.param("sort").map { v => List(("sort", v)) }.getOrElse(Nil) val uri= Helpers.appendParams(rootLink, ("search" -> keys.mkString(" ")) :: sort) <a href={uri}>{node}</a> } def getStyle(isactive : Boolean) = if (isactive) "active" else "inactive" def getKeysWith(tag : String) = tag :: keys def getKeysWithout(tag : String) = keys.filter{ _ != tag.toLowerCase } def renderTag(tag : String) : Node = { if (isActive(tag)) { link(<div class={getStyle(true)}>{tag}</div>, getKeysWithout(tag)) } else { link(<div class={getStyle(false)}>{tag}</div>, getKeysWith(tag)) } } def renderTagList(in:List[String]) : NodeSeq = { renderTagList(in, in.size+1) } def renderTagList(in : List[String], len : Int) : NodeSeq = { renderTagList(in, len, "tagList") } def renderTagList(in : List[String], len : Int, id: String) : NodeSeq = { <span>{in.slice(0, len).map { tag => renderTag(tag) }}</span> <span id={id}>{ if (len < in.size) SHtml.a(() => SetHtml(id, renderTagList(in.drop(len).toList, len, id+"x")), <div class="inactive">...</div>) else NodeSeq.Empty }</span> } } /** The Localizer provides localization for Text nodes * and attributes starting with $ */ object Localizer { def loc(in : NodeSeq) : NodeSeq = in.flatMap(loc(_)) def loc(in : Node) : NodeSeq = in match { case Text(str) if (str.startsWith("$")) => Text(loc(str)) case _ => in } def loc(in : String) = if (in.startsWith("$")) S.?(in.substring(1)) else in /** localize a number of attributes */ def loc(attr : MetaData) : MetaData = if (attr==Null) Null else attr match { case UnprefixedAttribute(key, value, next) => new UnprefixedAttribute(key, loc(value.text), loc(next)) case _ => throw new Exception("Unknown attribute type : "+attr) } } /** Create menu item elements with links and automatic styles */ class MenuMarker extends InRoom { val user= User.currentUser.map { _.id.is }.getOrElse(0L) var isFirst= true def toUrl(url : Option[Seq[Node]]) = uri(url.map { _.text }.getOrElse(S.uri)) def bind(in :NodeSeq) : NodeSeq = in.flatMap(bind(_)) def bind(in :Node) : NodeSeq = { in match { case Elem("menu", "a", attribs, scope, children @ _*) => // determine target and current link var href= toUrl(attribs.get("href")) var active= if (href.startsWith("/")) S.uri.replaceAll("^/room/[^/]*","") == href.replaceAll("^/room/[^/]+","") else S.uri.replaceAll(".*/","") == href // set up parameters attribs.get("action").foreach { action => val value= attribs.get("value").get.text val field= action.text // set the default order if action is sorting if (isFirst && field=="sort") S.set("defaultOrder", value) // Link leads to the currently viewed page active &&= S.param(field).map { value == _ }.getOrElse(isFirst) val search= S.param("search").map { v => List(("search",v))}.getOrElse(Nil) href = Helpers.appendParams(href, (field, value) :: search) isFirst= false } // make menu entry val entry= attribs.get("icon").map { url => <img src={"/images/menu/"+url.text+".png"} alt="" class="menu"/> }.getOrElse(NodeSeq.Empty) ++ Localizer.loc(children) // format link as either active (currently visited) or inaktive val style= if (active) "active" else "inactive" val title= attribs.get("title").map( Localizer.loc(_) ) <li><a href={href} title={title} alt={title}><div class={style}>{entry}</div></a></li> case Elem("local", "a", attribs, scope, children @ _*) => // keep a number of current request attributes in the target url val keep= attribs.get("keep").map{_.text}.getOrElse("") val para= S.param(keep).map { v => List((keep,v))}.getOrElse(Nil) val url= Helpers.appendParams(toUrl(attribs.get("href")), para ) val title= attribs.get("title").map( Localizer.loc(_) ) <a href={url} alt={title} title={title}>{ children }</a> case Elem(prefix, label, attribs, scope, children @ _*) => Elem(prefix, label, Localizer.loc(attribs), scope, bind(children) : _*) case _ => in } } def render(in : NodeSeq) : NodeSeq = { bind(in) } }
liquidizer/liquidizer
src/main/scala/org/liquidizer/snippet/Markup.scala
Scala
mit
7,634
<?php /* SQL Laboratory - Web based MySQL administration http://projects.deepcode.net/sqllaboratory/ types.php - list of data types MIT-style license 2008 Calvin Lough <http://calv.in>, 2010 Steve Gricci <http://deepcode.net> */ $typeList[] = "varchar"; $typeList[] = "char"; $typeList[] = "text"; $typeList[] = "tinytext"; $typeList[] = "mediumtext"; $typeList[] = "longtext"; $typeList[] = "tinyint"; $typeList[] = "smallint"; $typeList[] = "mediumint"; $typeList[] = "int"; $typeList[] = "bigint"; $typeList[] = "real"; $typeList[] = "double"; $typeList[] = "float"; $typeList[] = "decimal"; $typeList[] = "numeric"; $typeList[] = "date"; $typeList[] = "time"; $typeList[] = "datetime"; $typeList[] = "timestamp"; $typeList[] = "tinyblob"; $typeList[] = "blob"; $typeList[] = "mediumblob"; $typeList[] = "longblob"; $typeList[] = "binary"; $typeList[] = "varbinary"; $typeList[] = "bit"; $typeList[] = "enum"; $typeList[] = "set"; $textDTs[] = "text"; $textDTs[] = "mediumtext"; $textDTs[] = "longtext"; $numericDTs[] = "tinyint"; $numericDTs[] = "smallint"; $numericDTs[] = "mediumint"; $numericDTs[] = "int"; $numericDTs[] = "bigint"; $numericDTs[] = "real"; $numericDTs[] = "double"; $numericDTs[] = "float"; $numericDTs[] = "decimal"; $numericDTs[] = "numeric"; $binaryDTs[] = "tinyblob"; $binaryDTs[] = "blob"; $binaryDTs[] = "mediumblob"; $binaryDTs[] = "longblob"; $binaryDTs[] = "binary"; $binaryDTs[] = "varbinary"; $sqliteTypeList[] = "varchar"; $sqliteTypeList[] = "integer"; $sqliteTypeList[] = "float"; $sqliteTypeList[] = "varchar"; $sqliteTypeList[] = "nvarchar"; $sqliteTypeList[] = "text"; $sqliteTypeList[] = "boolean"; $sqliteTypeList[] = "clob"; $sqliteTypeList[] = "blob"; $sqliteTypeList[] = "timestamp"; $sqliteTypeList[] = "numeric"; ?>
sgricci/sqllaboratory
includes/types.php
PHP
mit
1,775
body { font-family: helvetica, arial, sans-serif; font-size: 24px; line-height: 36px; background: url("3264857348_0cfd8d7e4f_b-lowquality.jpg"); background-position: top center; background-size: cover; background-repeat: none; overflow: hidden; } * { box-sizing: border-box; -moz-box-sizing: border-box; margin: 0; padding: 0; color: #303030; } h1 { height: 25px; width: 640px; position: absolute; top: 50%; left: 50%; margin-left: -322px; margin-top: -290px; font-size: 32px; letter-spacing: -1px; text-shadow: rgba(255, 255, 255, 0.6) 0 0 8px; z-index: 1; } section { display: none; } .bespoke-parent { position: absolute; top: 0; bottom: 0; left: 0; right: 0; } .bespoke-slide { width: 640px; height: 480px; position: absolute; top: 50%; margin-top: -240px; left: 50%; margin-left: -320px; } section.bespoke-slide { -webkit-transition: all .3s ease; -moz-transition: all .3s ease; -ms-transition: all .3s ease; -o-transition: all .3s ease; transition: all .3s ease; display: block; border-radius: 0.5em; padding: 1em; background: -moz-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0.40) 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(255, 255, 255, 1)), color-stop(100%, rgba(255, 255, 255, 0.40))); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0.40) 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0.40) 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0.40) 100%); /* IE10+ */ background: linear-gradient(to bottom, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0.40) 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#40ffffff', GradientType=0); /* IE6-9 */ } .bespoke-inactive { opacity: 0; top: 100%; } .bespoke-active { opacity: 1; } .bespoke-slide aside { display: none; }
joelpurra/bespoke-secondary
demo/style.css
CSS
mit
2,264
#if false using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LionFire.Behaviors { public class Coroutine { } } #endif
jaredthirsk/LionFire.Behaviors
LionFire.Behaviors/Dependencies/Coroutines.cs
C#
mit
208
package SOLID.Exercise.Logger.model.appenders; import SOLID.Exercise.Logger.api.File; import SOLID.Exercise.Logger.api.Layout; import SOLID.Exercise.Logger.model.files.LogFile; public class FileAppender extends BaseAppender { private File file; public FileAppender(Layout layout) { super(layout); this.setFile(new LogFile()); } public void setFile(File file) { this.file = file; } @Override public void append(String message) { this.file.write(message); } @Override public String toString() { return String.format("%s, File size: %d", super.toString(), this.file.getSize()); } }
lmarinov/Exercise-repo
Java_OOP_2021/src/SOLID/Exercise/Logger/model/appenders/FileAppender.java
Java
mit
670
match x: | it?(): true
wcjohnson/babylon-lightscript
test/fixtures/safe-call-expression/lightscript/match-test/actual.js
JavaScript
mit
25
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>circuits: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.5.0~camlp4 / circuits - 8.10.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> circuits <small> 8.10.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2021-12-23 07:49:00 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-12-23 07:49:00 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp4 4.03+1 Camlp4 is a system for writing extensible parsers for programming languages conf-findutils 1 Virtual package relying on findutils conf-which 1 Virtual package relying on which coq 8.5.0~camlp4 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.03.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.03.0 Official 4.03.0 release ocaml-config 1 OCaml Switch Configuration ocamlbuild 0.14.0 OCamlbuild is a build system with builtin rules to easily build most OCaml projects. # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/circuits&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Circuits&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.10&quot; &amp; &lt; &quot;8.11~&quot;} ] tags: [ &quot;keyword: hardware verification&quot; &quot;category: Computer Science/Architecture&quot; ] authors: [ &quot;Laurent Arditi&quot; ] bug-reports: &quot;https://github.com/coq-contribs/circuits/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/circuits.git&quot; synopsis: &quot;Some proofs of hardware (adder, multiplier, memory block instruction)&quot; description: &quot;&quot;&quot; definition and proof of a combinatorial adder, a sequential multiplier, a memory block instruction&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/circuits/archive/v8.10.0.tar.gz&quot; checksum: &quot;md5=791bf534085120bc18d58db26e1123f4&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-circuits.8.10.0 coq.8.5.0~camlp4</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.5.0~camlp4). The following dependencies couldn&#39;t be met: - coq-circuits -&gt; coq &gt;= 8.10 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-circuits.8.10.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.03.0-2.0.5/released/8.5.0~camlp4/circuits/8.10.0.html
HTML
mit
7,038
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>zchinese: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.7.1+1 / zchinese - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> zchinese <small> 8.9.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-02-15 19:37:57 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-15 19:37:57 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.7.1+1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.06.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.06.1 Official 4.06.1 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/zchinese&quot; license: &quot;Unknown&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/ZChinese&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;keyword: number theory&quot; &quot;keyword: chinese remainder&quot; &quot;keyword: primality&quot; &quot;keyword: prime numbers&quot; &quot;category: Mathematics/Arithmetic and Number Theory/Number theory&quot; &quot;category: Miscellaneous/Extracted Programs/Arithmetic&quot; ] authors: [ &quot;Valérie Ménissier-Morain&quot; ] bug-reports: &quot;https://github.com/coq-contribs/zchinese/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/zchinese.git&quot; synopsis: &quot;A proof of the Chinese Remainder Lemma&quot; description: &quot;&quot;&quot; This is a rewriting of the contribution chinese-lemma using Zarith&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/zchinese/archive/v8.9.0.tar.gz&quot; checksum: &quot;md5=a5fddf5409ff7b7053a84bbf9491b8fc&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-zchinese.8.9.0 coq.8.7.1+1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1+1). The following dependencies couldn&#39;t be met: - coq-zchinese -&gt; coq &gt;= 8.9 Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-zchinese.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.06.1-2.0.5/released/8.7.1+1/zchinese/8.9.0.html
HTML
mit
6,988
import {Component} from 'react' export class Greeter { constructor (message) { this.greeting = message; } greetFrom (...names) { let suffix = names.reduce((s, n) => s + ", " + n.toUpperCase()); return "Hello, " + this.greeting + " from " + suffix; } greetNTimes ({name, times}) { let greeting = this.greetFrom(name); for (let i = 0; i < times; i++) { console.log(greeting) } } } new Greeter("foo").greetNTimes({name: "Webstorm", times: 3}) function foo (x, y, z) { var i = 0; var x = {0: "zero", 1: "one"}; var a = [0, 1, 2]; var foo = function () { } var asyncFoo = async (x, y, z) => { } var v = x.map(s => s.length); if (!i > 10) { for (var j = 0; j < 10; j++) { switch (j) { case 0: value = "zero"; break; case 1: value = "one"; break; } var c = j > 5 ? "GT 5" : "LE 5"; } } else { var j = 0; try { while (j < 10) { if (i == j || j > 5) { a[j] = i + j * 12; } i = (j << 2) & 4; j++; } do { j--; } while (j > 0) } catch (e) { alert("Failure: " + e.message); } finally { reset(a, i); } } }
doasync/eslint-config-airbnb-standard
example.js
JavaScript
mit
1,250
<!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>jsGrid - Data Manipulation</title> <link rel="stylesheet" type="text/css" href="demos.css" /> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300,600,400' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="../css/jsgrid.css" /> <link rel="stylesheet" type="text/css" href="../css/theme.css" /> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/cupertino/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script> <script src="db.js"></script> <script src="../src/jsgrid.core.js"></script> <script src="../src/jsgrid.load-indicator.js"></script> <script src="../src/jsgrid.load-strategies.js"></script> <script src="../src/jsgrid.sort-strategies.js"></script> <script src="../src/jsgrid.field.js"></script> <script src="../src/jsgrid.field.text.js"></script> <script src="../src/jsgrid.field.number.js"></script> <script src="../src/jsgrid.field.select.js"></script> <script src="../src/jsgrid.field.checkbox.js"></script> <script src="../src/jsgrid.field.control.js"></script> <style> .details-form-field input, .details-form-field select { width: 250px; float: right; } .details-form-field { margin: 15px 0; } .ui-widget *, .ui-widget input, .ui-widget select, .ui-widget button { font-family: 'Helvetica Neue Light', 'Open Sans', Helvetica; font-size: 14px; font-weight: 300 !important; } </style> </head> <body> <h1>Data Manipulation</h1> <div id="jsGrid"></div> <div id="detailsForm"> <div class="details-form-field"> <label>Name: <input id="name" type="text" /></label> </div> <div class="details-form-field"> <label>Age: <input id="age" type="number" /></label> </div> <div class="details-form-field"> <label>Address: <input id="address" type="text" /></label> </div> <div class="details-form-field"> <label>Country: <select id="country"> <option value="0">(Select)</option> <option value="1">United States</option> <option value="2">Canada</option> <option value="3">United Kingdom</option> <option value="4">France</option> <option value="5">Brazil</option> <option value="6">China</option> <option value="7">Russia</option> </select> </label> </div> <div class="details-form-field"> <label>Is Married: <input id="married" type="checkbox" /></label> </div> <div class="details-form-field"> <button type="button" id="save">Save</button> </div> </div> <script> $(function() { $("#jsGrid").jsGrid({ height: "70%", width: "100%", editing: true, autoload: true, paging: true, deleteConfirm: function(item) { return "The client \"" + item.Name + "\" will be removed. Are you sure?"; }, rowClick: function(args) { showDetailsDialog("Edit", args.item); }, controller: db, fields: [ { name: "Name", type: "text", width: 150 }, { name: "Age", type: "number", width: 50 }, { name: "Address", type: "text", width: 200 }, { name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control", modeSwitchButton: false, editButton: false, headerTemplate: function() { return $("<button>").attr("type", "button").text("Add") .on("click", function () { showDetailsDialog("Add", {}); }); } } ] }); $("#detailsForm").dialog({ autoOpen: false, width: 400 }); var showDetailsDialog = function(dialogType, client) { $("#name").val(client.Name); $("#age").val(client.Age); $("#address").val(client.Address); $("#country").val(client.Country); $("#married").prop("checked", client.Married); $("#save").off("click").on("click", function() { saveClient(client, dialogType === "Add"); }); $("#detailsForm").dialog("option", "title", dialogType + " Client") .dialog("open"); }; var saveClient = function(client, isNew) { $.extend(client, { Name: $("#name").val(), Age: parseInt($("#age").val(), 10), Address: $("#address").val(), Country: parseInt($("#country").val(), 10), Married: $("#married").is(":checked") }); $("#jsGrid").jsGrid(isNew ? "insertItem" : "updateItem", client); $("#detailsForm").dialog("close"); }; }); </script> </body> </html>
afzalbk/Dynamic_Table
demos/data-manipulation.html
HTML
mit
5,917
/* * COPYRIGHT: Stealthy Labs LLC * DATE: 29th May 2015 * AUTHOR: Stealthy Labs * SOFTWARE: Tea Time */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h> #include <teatime.h> static int teatime_check_gl_version(uint32_t *major, uint32_t *minor); static int teatime_check_program_errors(GLuint program); static int teatime_check_shader_errors(GLuint shader); #define TEATIME_BREAKONERROR(FN,RC) if ((RC = teatime_check_gl_errors(__LINE__, #FN )) < 0) break #define TEATIME_BREAKONERROR_FB(FN,RC) if ((RC = teatime_check_gl_fb_errors(__LINE__, #FN )) < 0) break teatime_t *teatime_setup() { int rc = 0; teatime_t *obj = calloc(1, sizeof(teatime_t)); if (!obj) { fprintf(stderr, "Out of memory allocating %zu bytes\n", sizeof(teatime_t)); return NULL; } do { uint32_t version[2] = { 0, 0}; if (teatime_check_gl_version(&version[0], &version[1]) < 0) { fprintf(stderr, "Unable to verify OpenGL version\n"); rc = -1; break; } if (version[0] < 3) { fprintf(stderr, "Minimum Required OpenGL version 3.0. You have %u.%u\n", version[0], version[1]); rc = -1; break; } /* initialize off-screen framebuffer */ /* * This is the EXT_framebuffer_object OpenGL extension that allows us to * use an offscreen buffer as a target for rendering operations such as * vector calculations, providing full precision and removing unwanted * clamping issues. * we are turning off the traditional framebuffer here apparently. */ glGenFramebuffersEXT(1, &(obj->ofb)); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, obj->ofb); TEATIME_BREAKONERROR(glBindFramebufferEXT, rc); fprintf(stderr, "Successfully created off-screen framebuffer with id: %d\n", obj->ofb); /* get the texture size */ obj->maxtexsz = -1; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &(obj->maxtexsz)); fprintf(stderr, "Maximum Texture size for the GPU: %d\n", obj->maxtexsz); obj->itexid = obj->otexid = 0; obj->shader = obj->program = 0; } while (0); if (rc < 0) { teatime_cleanup(obj); obj = NULL; } return obj; } void teatime_cleanup(teatime_t *obj) { if (obj) { teatime_delete_program(obj); teatime_delete_textures(obj); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); glDeleteFramebuffersEXT(1, &(obj->ofb)); glFlush(); free(obj); obj = NULL; } } int teatime_set_viewport(teatime_t *obj, uint32_t ilen) { uint32_t texsz = (uint32_t)((long)(sqrt(ilen / 4.0))); if (obj && texsz > 0 && texsz < (GLuint)obj->maxtexsz) { /* viewport mapping 1:1 pixel = texel = data mapping */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, texsz, 0.0, texsz); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glViewport(0, 0, texsz, texsz); obj->tex_size = texsz; fprintf(stderr, "Texture size: %u x %u\n", texsz, texsz); return 0; } else if (obj) { fprintf(stderr, "Max. texture size is %d. Calculated: %u from input length: %u\n", obj->maxtexsz, texsz, ilen); } return -EINVAL; } int teatime_create_textures(teatime_t *obj, const uint32_t *input, uint32_t ilen) { if (obj && input && ilen > 0) { int rc = 0; do { uint32_t texsz = (uint32_t)((long)(sqrt(ilen / 4.0))); if (texsz != obj->tex_size) { fprintf(stderr, "Viewport texture size(%u) != Input texture size (%u)\n", obj->tex_size, texsz); rc = -EINVAL; break; } glGenTextures(1, &(obj->itexid)); glGenTextures(1, &(obj->otexid)); fprintf(stderr, "Created input texture with ID: %u\n", obj->itexid); fprintf(stderr, "Created output texture with ID: %u\n", obj->otexid); /** BIND ONE TEXTURE AT A TIME **/ /* the texture target can vary depending on GPU */ glBindTexture(GL_TEXTURE_2D, obj->itexid); TEATIME_BREAKONERROR(glBindTexture, rc); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); /* turn off filtering and set proper wrap mode - this is obligatory for * floating point textures */ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); TEATIME_BREAKONERROR(glTexParameteri, rc); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); TEATIME_BREAKONERROR(glTexParameteri, rc); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); TEATIME_BREAKONERROR(glTexParameteri, rc); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); TEATIME_BREAKONERROR(glTexParameteri, rc); /* create a 2D texture of the same size as the data * internal format: GL_RGBA32UI_EXT * texture format: GL_RGBA_INTEGER * texture type: GL_UNSIGNED_INT */ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32UI_EXT, texsz, texsz, 0, GL_RGBA_INTEGER, GL_UNSIGNED_INT, NULL); TEATIME_BREAKONERROR(glTexImage2D, rc); /* transfer data to texture */ #ifdef WIN32 glTexSubImage2D #else glTexSubImage2DEXT #endif (GL_TEXTURE_2D, 0, 0, 0, obj->tex_size, obj->tex_size, GL_RGBA_INTEGER, GL_UNSIGNED_INT, input); #ifdef WIN32 TEATIME_BREAKONERROR(glTexSubImage2D, rc); #else TEATIME_BREAKONERROR(glTexSubImage2DEXT, rc); #endif fprintf(stderr, "Successfully transferred input data to texture ID: %u\n", obj->itexid); /* BIND the OUTPUT texture and work on it */ /* the texture target can vary depending on GPU */ glBindTexture(GL_TEXTURE_2D, obj->otexid); TEATIME_BREAKONERROR(glBindTexture, rc); /* turn off filtering and set proper wrap mode - this is obligatory for * floating point textures */ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); TEATIME_BREAKONERROR(glTexParameteri, rc); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); TEATIME_BREAKONERROR(glTexParameteri, rc); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); TEATIME_BREAKONERROR(glTexParameteri, rc); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); TEATIME_BREAKONERROR(glTexParameteri, rc); /* create a 2D texture of the same size as the data * internal format: GL_RGBA32UI_EXT * texture format: GL_RGBA_INTEGER * texture type: GL_UNSIGNED_INT */ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32UI_EXT, texsz, texsz, 0, GL_RGBA_INTEGER, GL_UNSIGNED_INT, NULL); TEATIME_BREAKONERROR(glTexImage2D, rc); /* change tex-env to replace instead of the default modulate */ glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); TEATIME_BREAKONERROR(glTexEnvi, rc); /* attach texture */ glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, obj->otexid, 0); TEATIME_BREAKONERROR(glFramebufferTexture2DEXT, rc); TEATIME_BREAKONERROR_FB(glFramebufferTexture2DEXT, rc); glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT); TEATIME_BREAKONERROR(glDrawBuffer, rc); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_TEXTURE_2D, obj->otexid, 0); TEATIME_BREAKONERROR(glFramebufferTexture2DEXT, rc); TEATIME_BREAKONERROR_FB(glFramebufferTexture2DEXT, rc); rc = 0; } while (0); return rc; } return -EINVAL; } int teatime_read_textures(teatime_t *obj, uint32_t *output, uint32_t olen) { if (obj && output && olen > 0 && obj->otexid > 0) { int rc = 0; do { uint32_t texsz = (uint32_t)((long)(sqrt(olen / 4.0))); if (texsz != obj->tex_size) { fprintf(stderr, "Viewport texture size(%u) != Input texture size (%u)\n", obj->tex_size, texsz); rc = -EINVAL; break; } /* read the texture back */ glReadBuffer(GL_COLOR_ATTACHMENT0_EXT); TEATIME_BREAKONERROR(glReadBuffer, rc); glReadPixels(0, 0, obj->tex_size, obj->tex_size, GL_RGBA_INTEGER, GL_UNSIGNED_INT, output); TEATIME_BREAKONERROR(glReadPixels, rc); fprintf(stderr, "Successfully read data from the texture\n"); } while (0); return rc; } return -EINVAL; } int teatime_create_program(teatime_t *obj, const char *source) { if (obj && source) { int rc = 0; do { obj->program = glCreateProgram(); TEATIME_BREAKONERROR(glCreateProgram, rc); obj->shader = glCreateShader(GL_FRAGMENT_SHADER_ARB); TEATIME_BREAKONERROR(glCreateShader, rc); glShaderSource(obj->shader, 1, &source, NULL); TEATIME_BREAKONERROR(glShaderSource, rc); glCompileShader(obj->shader); rc = teatime_check_shader_errors(obj->shader); if (rc < 0) break; TEATIME_BREAKONERROR(glCompileShader, rc); glAttachShader(obj->program, obj->shader); TEATIME_BREAKONERROR(glAttachShader, rc); glLinkProgram(obj->program); rc = teatime_check_program_errors(obj->program); if (rc < 0) break; TEATIME_BREAKONERROR(glLinkProgram, rc); obj->locn_input = glGetUniformLocation(obj->program, "idata"); TEATIME_BREAKONERROR(glGetUniformLocation, rc); obj->locn_output = glGetUniformLocation(obj->program, "odata"); TEATIME_BREAKONERROR(glGetUniformLocation, rc); obj->locn_key = glGetUniformLocation(obj->program, "ikey"); TEATIME_BREAKONERROR(glGetUniformLocation, rc); obj->locn_rounds = glGetUniformLocation(obj->program, "rounds"); TEATIME_BREAKONERROR(glGetUniformLocation, rc); rc = 0; } while (0); return rc; } return -EINVAL; } int teatime_run_program(teatime_t *obj, const uint32_t ikey[4], uint32_t rounds) { if (obj && obj->program > 0) { int rc = 0; do { glUseProgram(obj->program); TEATIME_BREAKONERROR(glUseProgram, rc); glActiveTexture(GL_TEXTURE0); TEATIME_BREAKONERROR(glActiveTexture, rc); glBindTexture(GL_TEXTURE_2D, obj->itexid); TEATIME_BREAKONERROR(glBindTexture, rc); glUniform1i(obj->locn_input, 0); TEATIME_BREAKONERROR(glUniform1i, rc); glActiveTexture(GL_TEXTURE1); TEATIME_BREAKONERROR(glActiveTexture, rc); glBindTexture(GL_TEXTURE_2D, obj->otexid); TEATIME_BREAKONERROR(glBindTexture, rc); glUniform1i(obj->locn_output, 1); TEATIME_BREAKONERROR(glUniform1i, rc); glUniform4uiv(obj->locn_key, 1, ikey); TEATIME_BREAKONERROR(glUniform1uiv, rc); glUniform1ui(obj->locn_rounds, rounds); TEATIME_BREAKONERROR(glUniform1ui, rc); glFinish(); glPolygonMode(GL_FRONT, GL_FILL); /* render */ glBegin(GL_QUADS); glTexCoord2i(0, 0); glVertex2i(0, 0); //glTexCoord2i(obj->tex_size, 0); glTexCoord2i(1, 0); glVertex2i(obj->tex_size, 0); //glTexCoord2i(obj->tex_size, obj->tex_size); glTexCoord2i(1, 1); glVertex2i(obj->tex_size, obj->tex_size); glTexCoord2i(0, 1); //glTexCoord2i(0, obj->tex_size); glVertex2i(0, obj->tex_size); glEnd(); glFinish(); TEATIME_BREAKONERROR_FB(Rendering, rc); TEATIME_BREAKONERROR(Rendering, rc); rc = 0; } while (0); return rc; } return -EINVAL; } void teatime_delete_textures(teatime_t *obj) { if (obj) { if (obj->itexid != 0) { glDeleteTextures(1, &(obj->itexid)); obj->itexid = 0; } if (obj->otexid != 0) { glDeleteTextures(1, &(obj->otexid)); obj->otexid = 0; } } } void teatime_delete_program(teatime_t *obj) { if (obj) { if (obj->shader > 0 && obj->program > 0) { glDetachShader(obj->program, obj->shader); } if (obj->shader > 0) glDeleteShader(obj->shader); if (obj->program > 0) glDeleteProgram(obj->program); obj->shader = 0; obj->program = 0; } } void teatime_print_version(FILE *fp) { const GLubyte *version = NULL; version = glGetString(GL_VERSION); fprintf(fp, "GL Version: %s\n", (const char *)version); version = glGetString(GL_SHADING_LANGUAGE_VERSION); fprintf(fp, "GLSL Version: %s\n", (const char *)version); version = glGetString(GL_VENDOR); fprintf(fp, "GL Vendor: %s\n", (const char *)version); } int teatime_check_gl_version(uint32_t *major, uint32_t *minor) { const GLubyte *version = NULL; version = glGetString(GL_VERSION); if (version) { uint32_t ver[2] = { 0, 0 }; char *endp = NULL; char *endp2 = NULL; errno = 0; ver[0] = strtol((const char *)version, &endp, 10); if (errno == ERANGE || (const void *)endp == (const void *)version) { fprintf(stderr, "Version string %s cannot be parsed\n", (const char *)version); return -1; } /* endp[0] = '.' and endp[1] points to minor */ errno = 0; ver[1] = strtol((const char *)&endp[1], &endp2, 10); if (errno == ERANGE || endp2 == &endp[1]) { fprintf(stderr, "Version string %s cannot be parsed\n", (const char *)version); return -1; } if (major) *major = ver[0]; if (minor) *minor = ver[1]; return 0; } return -1; } int teatime_check_gl_errors(int line, const char *fn_name) { GLenum err = glGetError(); if (err != GL_NO_ERROR) { const GLubyte *estr = gluErrorString(err); fprintf(stderr, "%s(): GL Error(%d) on line %d: %s\n", fn_name, err, line, (const char *)estr); return -1; } return 0; } int teatime_check_gl_fb_errors(int line, const char *fn_name) { GLenum st = (GLenum)glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); switch (st) { case GL_FRAMEBUFFER_COMPLETE_EXT: return 0; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT: fprintf(stderr, "%s(): GL FB error on line %d: incomplete attachment\n", fn_name, line); break; case GL_FRAMEBUFFER_UNSUPPORTED_EXT: fprintf(stderr, "%s(): GL FB error on line %d: unsupported\n", fn_name, line); break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT: fprintf(stderr, "%s(): GL FB error on line %d: incomplete missing attachment\n", fn_name, line); break; case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT: fprintf(stderr, "%s(): GL FB error on line %d: incomplete dimensions\n", fn_name, line); break; case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT: fprintf(stderr, "%s(): GL FB error on line %d: incomplete formats\n", fn_name, line); break; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT: fprintf(stderr, "%s(): GL FB error on line %d: incomplete draw buffer\n", fn_name, line); break; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT: fprintf(stderr, "%s(): GL FB error on line %d: incomplete read buffer\n", fn_name, line); break; default: fprintf(stderr, "%s(): GL FB error on line %d: Unknown. Error Value: %d\n", fn_name, line, st); break; } return -1; } int teatime_check_program_errors(GLuint program) { GLint ilen = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &ilen); if (ilen > 1) { GLsizei wb = 0; GLchar *buf = calloc(ilen, sizeof(GLchar)); if (!buf) { fprintf(stderr, "Out of memory allocating %d bytes\n", ilen); return -ENOMEM; } glGetProgramInfoLog(program, ilen, &wb, buf); buf[wb] = '\0'; fprintf(stderr, "Program Errors:\n%s\n", (const char *)buf); free(buf); } return 0; } int teatime_check_shader_errors(GLuint shader) { GLint ilen = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &ilen); if (ilen > 1) { GLsizei wb = 0; GLchar *buf = calloc(ilen, sizeof(GLchar)); if (!buf) { fprintf(stderr, "Out of memory allocating %d bytes\n", ilen); return -ENOMEM; } glGetShaderInfoLog(shader, ilen, &wb, buf); buf[wb] = '\0'; fprintf(stderr, "Shader Errors:\n%s\n", (const char *)buf); free(buf); } return 0; } #define TEA_ENCRYPT_SOURCE \ "#version 130\n" \ "#extension GL_EXT_gpu_shader4 : enable\n" \ "uniform usampler2D idata;\n" \ "uniform uvec4 ikey; \n" \ "uniform uint rounds; \n" \ "out uvec4 odata; \n" \ "void main(void) {\n" \ " uvec4 x = texture(idata, gl_TexCoord[0].st);\n" \ " uint delta = uint(0x9e3779b9); \n" \ " uint sum = uint(0); \n" \ " for (uint i = uint(0); i < rounds; ++i) {\n" \ " sum += delta; \n" \ " x[0] += (((x[1] << 4) + ikey[0]) ^ (x[1] + sum)) ^ ((x[1] >> 5) + ikey[1]);\n" \ " x[1] += (((x[0] << 4) + ikey[2]) ^ (x[0] + sum)) ^ ((x[0] >> 5) + ikey[3]);\n" \ " x[2] += (((x[3] << 4) + ikey[0]) ^ (x[3] + sum)) ^ ((x[3] >> 5) + ikey[1]);\n" \ " x[3] += (((x[2] << 4) + ikey[2]) ^ (x[2] + sum)) ^ ((x[2] >> 5) + ikey[3]);\n" \ " }\n" \ " odata = x; \n" \ "}\n" #define TEA_DECRYPT_SOURCE \ "#version 130\n" \ "#extension GL_EXT_gpu_shader4 : enable\n" \ "uniform usampler2D idata;\n" \ "uniform uvec4 ikey; \n" \ "uniform uint rounds; \n" \ "out uvec4 odata; \n" \ "void main(void) {\n" \ " uvec4 x = texture(idata, gl_TexCoord[0].st);\n" \ " uint delta = uint(0x9e3779b9); \n" \ " uint sum = delta * rounds; \n" \ " for (uint i = uint(0); i < rounds; ++i) {\n" \ " x[1] -= (((x[0] << 4) + ikey[2]) ^ (x[0] + sum)) ^ ((x[0] >> 5) + ikey[3]);\n" \ " x[0] -= (((x[1] << 4) + ikey[0]) ^ (x[1] + sum)) ^ ((x[1] >> 5) + ikey[1]);\n" \ " x[3] -= (((x[2] << 4) + ikey[2]) ^ (x[2] + sum)) ^ ((x[2] >> 5) + ikey[3]);\n" \ " x[2] -= (((x[3] << 4) + ikey[0]) ^ (x[3] + sum)) ^ ((x[3] >> 5) + ikey[1]);\n" \ " sum -= delta; \n" \ " }\n" \ " odata = x; \n" \ "}\n" const char *teatime_encrypt_source() { return TEA_ENCRYPT_SOURCE; } const char *teatime_decrypt_source() { return TEA_DECRYPT_SOURCE; }
stealthylabs/teatime
teatime.c
C
mit
19,398
class CreateLists < ActiveRecord::Migration[5.1] def change create_table :lists do |t| t.string :letter t.string :tax_reference t.string :list_type t.date :date_list t.timestamps end end end
vts-group/sat-lista-negra
db/migrate/20170506210330_create_lists.rb
Ruby
mit
234
var groove = require('groove'); var semver = require('semver'); var EventEmitter = require('events').EventEmitter; var util = require('util'); var mkdirp = require('mkdirp'); var fs = require('fs'); var uuid = require('./uuid'); var path = require('path'); var Pend = require('pend'); var DedupedQueue = require('./deduped_queue'); var findit = require('findit2'); var shuffle = require('mess'); var mv = require('mv'); var MusicLibraryIndex = require('music-library-index'); var keese = require('keese'); var safePath = require('./safe_path'); var PassThrough = require('stream').PassThrough; var url = require('url'); var dbIterate = require('./db_iterate'); var log = require('./log'); var importUrlFilters = require('./import_url_filters'); var youtubeSearch = require('./youtube_search'); var yauzl = require('yauzl'); var importFileFilters = [ { name: 'zip', fn: importFileAsZip, }, { name: 'song', fn: importFileAsSong, }, ]; module.exports = Player; ensureGrooveVersionIsOk(); var cpuCount = 1; var PLAYER_KEY_PREFIX = "Player."; var LIBRARY_KEY_PREFIX = "Library."; var LIBRARY_DIR_PREFIX = "LibraryDir."; var QUEUE_KEY_PREFIX = "Playlist."; var PLAYLIST_KEY_PREFIX = "StoredPlaylist."; var LABEL_KEY_PREFIX = "Label."; var PLAYLIST_META_KEY_PREFIX = "StoredPlaylistMeta."; // db: store in the DB var DB_PROPS = { key: { db: true, clientVisible: true, clientCanModify: false, type: 'string', }, name: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, artistName: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, albumArtistName: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, albumName: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, compilation: { db: true, clientVisible: true, clientCanModify: true, type: 'boolean', }, track: { db: true, clientVisible: true, clientCanModify: true, type: 'integer', }, trackCount: { db: true, clientVisible: true, clientCanModify: true, type: 'integer', }, disc: { db: true, clientVisible: true, clientCanModify: true, type: 'integer', }, discCount: { db: true, clientVisible: true, clientCanModify: true, type: 'integer', }, duration: { db: true, clientVisible: true, clientCanModify: false, type: 'float', }, year: { db: true, clientVisible: true, clientCanModify: true, type: 'integer', }, genre: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, file: { db: true, clientVisible: true, clientCanModify: false, type: 'string', }, mtime: { db: true, clientVisible: false, clientCanModify: false, type: 'integer', }, replayGainAlbumGain: { db: true, clientVisible: false, clientCanModify: false, type: 'float', }, replayGainAlbumPeak: { db: true, clientVisible: false, clientCanModify: false, type: 'float', }, replayGainTrackGain: { db: true, clientVisible: false, clientCanModify: false, type: 'float', }, replayGainTrackPeak: { db: true, clientVisible: false, clientCanModify: false, type: 'float', }, composerName: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, performerName: { db: true, clientVisible: true, clientCanModify: true, type: 'string', }, lastQueueDate: { db: true, clientVisible: false, clientCanModify: false, type: 'date', }, fingerprint: { db: true, clientVisible: false, clientCanModify: false, type: 'array_of_integer', }, playCount: { db: true, clientVisible: false, clientCanModify: false, type: 'integer', }, labels: { db: true, clientVisible: true, clientCanModify: false, type: 'set', }, }; var PROP_TYPE_PARSERS = { 'string': function(value) { return value ? String(value) : ""; }, 'date': function(value) { if (!value) return null; var date = new Date(value); if (isNaN(date.getTime())) return null; return date; }, 'integer': parseIntOrNull, 'float': parseFloatOrNull, 'boolean': function(value) { return value == null ? null : !!value; }, 'array_of_integer': function(value) { if (!Array.isArray(value)) return null; value = value.map(parseIntOrNull); for (var i = 0; i < value.length; i++) { if (value[i] == null) return null; } return value; }, 'set': function(value) { var result = {}; for (var key in value) { result[key] = 1; } return result; }, }; var labelColors = [ "#e11d21", "#eb6420", "#fbca04", "#009800", "#006b75", "#207de5", "#0052cc", "#5319e7", "#f7c6c7", "#fad8c7", "#fef2c0", "#bfe5bf", "#bfdadc", "#bfd4f2", "#c7def8", "#d4c5f9", ]; // how many GrooveFiles to keep open, ready to be decoded var OPEN_FILE_COUNT = 8; var PREV_FILE_COUNT = Math.floor(OPEN_FILE_COUNT / 2); var NEXT_FILE_COUNT = OPEN_FILE_COUNT - PREV_FILE_COUNT; var DB_SCALE = Math.log(10.0) * 0.05; var REPLAYGAIN_PREAMP = 0.75; var REPLAYGAIN_DEFAULT = 0.25; Player.REPEAT_OFF = 0; Player.REPEAT_ALL = 1; Player.REPEAT_ONE = 2; Player.trackWithoutIndex = trackWithoutIndex; Player.setGrooveLoggingLevel = setGrooveLoggingLevel; util.inherits(Player, EventEmitter); function Player(db, config) { EventEmitter.call(this); this.setMaxListeners(0); this.db = db; this.musicDirectory = config.musicDirectory; this.dbFilesByPath = {}; this.dbFilesByLabel = {}; this.libraryIndex = new MusicLibraryIndex({ searchFields: MusicLibraryIndex.defaultSearchFields.concat('file'), }); this.addQueue = new DedupedQueue({ processOne: this.addToLibrary.bind(this), // limit to 1 async operation because we're blocking on the hard drive, // it's faster to read one file at a time. maxAsync: 1, }); this.dirs = {}; this.dirScanQueue = new DedupedQueue({ processOne: this.refreshFilesIndex.bind(this), // only 1 dir scanning can happen at a time // we'll pass the dir to scan as the ID so that not more than 1 of the // same dir can queue up maxAsync: 1, }); this.dirScanQueue.on('error', function(err) { log.error("library scanning error:", err.stack); }); this.disableFsRefCount = 0; this.playlist = {}; this.playlists = {}; this.currentTrack = null; this.tracksInOrder = []; // another way to look at playlist this.grooveItems = {}; // maps groove item id to track this.seekRequestPos = -1; // set to >= 0 when we want to seek this.invalidPaths = {}; // files that could not be opened this.playlistItemDeleteQueue = []; this.dontBelieveTheEndOfPlaylistSentinelItsATrap = false; this.queueClearEncodedBuffers = false; this.repeat = Player.REPEAT_OFF; this.desiredPlayerHardwareState = null; // true: normal hardware playback. false: dummy this.pendingPlayerAttachDetach = null; this.isPlaying = false; this.trackStartDate = null; this.pausedTime = 0; this.autoDjOn = false; this.autoDjHistorySize = 10; this.autoDjFutureSize = 10; this.ongoingScans = {}; this.scanQueue = new DedupedQueue({ processOne: this.performScan.bind(this), maxAsync: cpuCount, }); this.headerBuffers = []; this.recentBuffers = []; this.newHeaderBuffers = []; this.openStreamers = []; this.expectHeaders = true; // when a streaming client connects we send them many buffers quickly // in order to get the stream started, then we slow down. this.encodeQueueDuration = config.encodeQueueDuration; this.groovePlaylist = groove.createPlaylist(); this.groovePlayer = null; this.grooveEncoder = groove.createEncoder(); this.grooveEncoder.encodedBufferSize = 128 * 1024; this.detachEncoderTimeout = null; this.pendingEncoderAttachDetach = false; this.desiredEncoderAttachState = false; this.flushEncodedInterval = null; this.groovePlaylist.pause(); this.volume = this.groovePlaylist.gain; this.grooveEncoder.formatShortName = "mp3"; this.grooveEncoder.codecShortName = "mp3"; this.grooveEncoder.bitRate = config.encodeBitRate * 1000; this.importProgress = {}; this.lastImportProgressEvent = new Date(); // tracking playCount this.previousIsPlaying = false; this.playingStart = new Date(); this.playingTime = 0; this.lastPlayingItem = null; this.googleApiKey = config.googleApiKey; this.ignoreExtensions = config.ignoreExtensions.map(makeLower); } Player.prototype.initialize = function(cb) { var self = this; var startupTrackInfo = null; initLibrary(function(err) { if (err) return cb(err); cacheTracksArray(self); self.requestUpdateDb(); cacheAllOptions(function(err) { if (err) return cb(err); setInterval(doPersistCurrentTrack, 10000); if (startupTrackInfo) { self.seek(startupTrackInfo.id, startupTrackInfo.pos); } else { playlistChanged(self); } lazyReplayGainScanPlaylist(self); cb(); }); }); function initLibrary(cb) { var pend = new Pend(); pend.go(cacheAllDb); pend.go(cacheAllDirs); pend.go(cacheAllQueue); pend.go(cacheAllPlaylists); pend.go(cacheAllLabels); pend.wait(cb); } function cacheAllPlaylists(cb) { cacheAllPlaylistMeta(function(err) { if (err) return cb(err); cacheAllPlaylistItems(cb); }); function cacheAllPlaylistMeta(cb) { dbIterate(self.db, PLAYLIST_META_KEY_PREFIX, processOne, cb); function processOne(key, value) { var playlist = deserializePlaylist(value); self.playlists[playlist.id] = playlist; } } function cacheAllPlaylistItems(cb) { dbIterate(self.db, PLAYLIST_KEY_PREFIX, processOne, cb); function processOne(key, value) { var playlistIdEnd = key.indexOf('.', PLAYLIST_KEY_PREFIX.length); var playlistId = key.substring(PLAYLIST_KEY_PREFIX.length, playlistIdEnd); var playlistItem = JSON.parse(value); self.playlists[playlistId].items[playlistItem.id] = playlistItem; } } } function cacheAllLabels(cb) { dbIterate(self.db, LABEL_KEY_PREFIX, processOne, cb); function processOne(key, value) { var labelId = key.substring(LABEL_KEY_PREFIX.length); var labelEntry = JSON.parse(value); self.libraryIndex.addLabel(labelEntry); } } function cacheAllQueue(cb) { dbIterate(self.db, QUEUE_KEY_PREFIX, processOne, cb); function processOne(key, value) { var plEntry = JSON.parse(value); self.playlist[plEntry.id] = plEntry; } } function cacheAllOptions(cb) { var options = { repeat: null, autoDjOn: null, autoDjHistorySize: null, autoDjFutureSize: null, hardwarePlayback: null, volume: null, currentTrackInfo: null, }; var pend = new Pend(); for (var name in options) { pend.go(makeGetFn(name)); } pend.wait(function(err) { if (err) return cb(err); if (options.repeat != null) { self.setRepeat(options.repeat); } if (options.autoDjOn != null) { self.setAutoDjOn(options.autoDjOn); } if (options.autoDjHistorySize != null) { self.setAutoDjHistorySize(options.autoDjHistorySize); } if (options.autoDjFutureSize != null) { self.setAutoDjFutureSize(options.autoDjFutureSize); } if (options.volume != null) { self.setVolume(options.volume); } startupTrackInfo = options.currentTrackInfo; var hardwarePlaybackValue = options.hardwarePlayback == null ? true : options.hardwarePlayback; // start the hardware player first // fall back to dummy self.setHardwarePlayback(hardwarePlaybackValue, function(err) { if (err) { log.error("Unable to attach hardware player, falling back to dummy.", err.stack); self.setHardwarePlayback(false); } cb(); }); }); function makeGetFn(name) { return function(cb) { self.db.get(PLAYER_KEY_PREFIX + name, function(err, value) { if (!err && value != null) { try { options[name] = JSON.parse(value); } catch (err) { cb(err); return; } } cb(); }); }; } } function cacheAllDirs(cb) { dbIterate(self.db, LIBRARY_DIR_PREFIX, processOne, cb); function processOne(key, value) { var dirEntry = JSON.parse(value); self.dirs[dirEntry.dirName] = dirEntry; } } function cacheAllDb(cb) { var scrubCmds = []; dbIterate(self.db, LIBRARY_KEY_PREFIX, processOne, scrubAndCb); function processOne(key, value) { var dbFile = deserializeFileData(value); // scrub duplicates if (self.dbFilesByPath[dbFile.file]) { scrubCmds.push({type: 'del', key: key}); } else { self.libraryIndex.addTrack(dbFile); self.dbFilesByPath[dbFile.file] = dbFile; for (var labelId in dbFile.labels) { var files = self.dbFilesByLabel[labelId]; if (files == null) files = self.dbFilesByLabel[labelId] = {}; files[dbFile.key] = dbFile; } } } function scrubAndCb() { if (scrubCmds.length === 0) return cb(); log.warn("Scrubbing " + scrubCmds.length + " duplicate db entries"); self.db.batch(scrubCmds, function(err) { if (err) log.error("Unable to scrub duplicate tracks from db:", err.stack); cb(); }); } } function doPersistCurrentTrack() { if (self.isPlaying) { self.persistCurrentTrack(); } } }; function startEncoderAttach(self, cb) { if (self.desiredEncoderAttachState) return; self.desiredEncoderAttachState = true; if (self.pendingEncoderAttachDetach) return; self.pendingEncoderAttachDetach = true; self.grooveEncoder.attach(self.groovePlaylist, function(err) { self.pendingEncoderAttachDetach = false; if (err) { self.desiredEncoderAttachState = false; cb(err); } else if (!self.desiredEncoderAttachState) { startEncoderDetach(self, cb); } }); } function startEncoderDetach(self, cb) { if (!self.desiredEncoderAttachState) return; self.desiredEncoderAttachState = false; if (self.pendingEncoderAttachDetach) return; self.pendingEncoderAttachDetach = true; self.grooveEncoder.detach(function(err) { self.pendingEncoderAttachDetach = false; if (err) { self.desiredEncoderAttachState = true; cb(err); } else if (self.desiredEncoderAttachState) { startEncoderAttach(self, cb); } }); } Player.prototype.getBufferedSeconds = function() { if (this.recentBuffers.length < 2) return 0; var firstPts = this.recentBuffers[0].pts; var lastPts = this.recentBuffers[this.recentBuffers.length - 1].pts; var frameCount = lastPts - firstPts; var sampleRate = this.grooveEncoder.actualAudioFormat.sampleRate; return frameCount / sampleRate; }; Player.prototype.attachEncoder = function(cb) { var self = this; cb = cb || logIfError; if (self.flushEncodedInterval) return cb(); log.debug("first streamer connected - attaching encoder"); self.flushEncodedInterval = setInterval(flushEncoded, 100); startEncoderAttach(self, cb); function flushEncoded() { if (!self.desiredEncoderAttachState || self.pendingEncoderAttachDetach) return; var playHead = self.groovePlayer.position(); if (!playHead.item) return; var plItems = self.groovePlaylist.items(); // get rid of old items var buf; while (buf = self.recentBuffers[0]) { /* log.debug(" buf.item " + buf.item.file.filename + "\n" + "playHead.item " + playHead.item.file.filename + "\n" + " playHead.pos " + playHead.pos + "\n" + " buf.pos " + buf.pos); */ if (isBufOld(buf)) { self.recentBuffers.shift(); } else { break; } } // poll the encoder for more buffers until either there are no buffers // available or we get enough buffered while (self.getBufferedSeconds() < self.encodeQueueDuration) { buf = self.grooveEncoder.getBuffer(); if (!buf) break; if (buf.buffer) { if (buf.item) { if (self.expectHeaders) { log.debug("encoder: got first non-header"); self.headerBuffers = self.newHeaderBuffers; self.newHeaderBuffers = []; self.expectHeaders = false; } self.recentBuffers.push(buf); for (var i = 0; i < self.openStreamers.length; i += 1) { self.openStreamers[i].write(buf.buffer); } } else if (self.expectHeaders) { // this is a header log.debug("encoder: got header"); self.newHeaderBuffers.push(buf.buffer); } else { // it's a footer, ignore the fuck out of it log.debug("ignoring encoded audio footer"); } } else { // end of playlist sentinel log.debug("encoder: end of playlist sentinel"); if (self.queueClearEncodedBuffers) { self.queueClearEncodedBuffers = false; self.clearEncodedBuffer(); self.emit('seek'); } self.expectHeaders = true; } } function isBufOld(buf) { // typical case if (buf.item.id === playHead.item.id) { return playHead.pos > buf.pos; } // edge case var playHeadIndex = -1; var bufItemIndex = -1; for (var i = 0; i < plItems.length; i += 1) { var plItem = plItems[i]; if (plItem.id === playHead.item.id) { playHeadIndex = i; } else if (plItem.id === buf.item.id) { bufItemIndex = i; } } return playHeadIndex > bufItemIndex; } } function logIfError(err) { if (err) { log.error("Unable to attach encoder:", err.stack); } } }; Player.prototype.detachEncoder = function(cb) { cb = cb || logIfError; this.clearEncodedBuffer(); this.queueClearEncodedBuffers = false; clearInterval(this.flushEncodedInterval); this.flushEncodedInterval = null; startEncoderDetach(this, cb); this.grooveEncoder.removeAllListeners(); function logIfError(err) { if (err) { log.error("Unable to detach encoder:", err.stack); } } }; Player.prototype.deleteDbMtimes = function(cb) { cb = cb || logIfDbError; var updateCmds = []; for (var key in this.libraryIndex.trackTable) { var dbFile = this.libraryIndex.trackTable[key]; delete dbFile.mtime; persistDbFile(dbFile, updateCmds); } this.db.batch(updateCmds, cb); }; Player.prototype.requestUpdateDb = function(dirName, cb) { var fullPath = path.resolve(this.musicDirectory, dirName || ""); this.dirScanQueue.add(fullPath, { dir: fullPath, }, cb); }; Player.prototype.refreshFilesIndex = function(args, cb) { var self = this; var dir = args.dir; var dirWithSlash = ensureSep(dir); var walker = findit(dirWithSlash, {followSymlinks: true}); var thisScanId = uuid(); var delCmds = []; walker.on('directory', function(fullDirPath, stat, stop, linkPath) { var usePath = linkPath || fullDirPath; var dirName = path.relative(self.musicDirectory, usePath); var baseName = path.basename(dirName); if (isFileIgnored(baseName)) { stop(); return; } var dirEntry = self.getOrCreateDir(dirName, stat); if (usePath === dirWithSlash) return; // ignore root search path var parentDirName = path.dirname(dirName); if (parentDirName === '.') parentDirName = ''; var parentDirEntry = self.getOrCreateDir(parentDirName); parentDirEntry.dirEntries[baseName] = thisScanId; }); walker.on('file', function(fullPath, stat, linkPath) { var usePath = linkPath || fullPath; var relPath = path.relative(self.musicDirectory, usePath); var dirName = path.dirname(relPath); if (dirName === '.') dirName = ''; var baseName = path.basename(relPath); if (isFileIgnored(baseName)) return; var extName = path.extname(relPath); if (isExtensionIgnored(self, extName)) return; var dirEntry = self.getOrCreateDir(dirName); dirEntry.entries[baseName] = thisScanId; var fileMtime = stat.mtime.getTime(); onAddOrChange(self, relPath, fileMtime); }); walker.on('error', function(err) { walker.stop(); cleanupAndCb(err); }); walker.on('end', function() { var dirName = path.relative(self.musicDirectory, dir); checkDirEntry(self.dirs[dirName]); cleanupAndCb(); function checkDirEntry(dirEntry) { if (!dirEntry) return; var id; var baseName; var i; var deletedFiles = []; var deletedDirs = []; for (baseName in dirEntry.entries) { id = dirEntry.entries[baseName]; if (id !== thisScanId) deletedFiles.push(baseName); } for (i = 0; i < deletedFiles.length; i += 1) { baseName = deletedFiles[i]; delete dirEntry.entries[baseName]; onFileMissing(dirEntry, baseName); } for (baseName in dirEntry.dirEntries) { id = dirEntry.dirEntries[baseName]; var childEntry = self.dirs[path.join(dirEntry.dirName, baseName)]; checkDirEntry(childEntry); if (id !== thisScanId) deletedDirs.push(baseName); } for (i = 0; i < deletedDirs.length; i += 1) { baseName = deletedDirs[i]; delete dirEntry.dirEntries[baseName]; onDirMissing(dirEntry, baseName); } self.persistDirEntry(dirEntry); } }); function cleanupAndCb(err) { if (delCmds.length > 0) { self.db.batch(delCmds, logIfDbError); self.emit('deleteDbTrack'); } cb(err); } function onDirMissing(parentDirEntry, baseName) { var dirName = path.join(parentDirEntry.dirName, baseName); log.debug("directory deleted:", dirName); var dirEntry = self.dirs[dirName]; var watcher = dirEntry.watcher; if (watcher) watcher.close(); delete self.dirs[dirName]; delete parentDirEntry.dirEntries[baseName]; } function onFileMissing(parentDirEntry, baseName) { var relPath = path.join(parentDirEntry.dirName, baseName); log.debug("file deleted:", relPath); delete parentDirEntry.entries[baseName]; var dbFile = self.dbFilesByPath[relPath]; if (dbFile) { // batch up some db delete commands to run after walking the file system delDbEntryCmds(self, dbFile, delCmds); } } }; Player.prototype.watchDirEntry = function(dirEntry) { var self = this; var changeTriggered = null; var fullDirPath = path.join(self.musicDirectory, dirEntry.dirName); var watcher; try { watcher = fs.watch(fullDirPath, onChange); watcher.on('error', onWatchError); } catch (err) { log.warn("Unable to fs.watch:", err.stack); watcher = null; } dirEntry.watcher = watcher; function onChange(eventName) { if (changeTriggered) clearTimeout(changeTriggered); changeTriggered = setTimeout(function() { changeTriggered = null; log.debug("dir updated:", dirEntry.dirName); self.dirScanQueue.add(fullDirPath, { dir: fullDirPath }); }, 100); } function onWatchError(err) { log.error("watch error:", err.stack); } }; Player.prototype.getOrCreateDir = function (dirName, stat) { var dirEntry = this.dirs[dirName]; if (!dirEntry) { dirEntry = this.dirs[dirName] = { dirName: dirName, entries: {}, dirEntries: {}, watcher: null, // will be set just below mtime: stat && stat.mtime, }; } else if (stat && dirEntry.mtime !== stat.mtime) { dirEntry.mtime = stat.mtime; } if (!dirEntry.watcher) this.watchDirEntry(dirEntry); return dirEntry; }; Player.prototype.getCurPos = function() { return this.isPlaying ? ((new Date() - this.trackStartDate) / 1000.0) : this.pausedTime; }; function startPlayerSwitchDevice(self, wantHardware, cb) { self.desiredPlayerHardwareState = wantHardware; if (self.pendingPlayerAttachDetach) return; self.pendingPlayerAttachDetach = true; if (self.groovePlayer) { self.groovePlayer.removeAllListeners(); self.groovePlayer.detach(onDetachComplete); } else { onDetachComplete(); } function onDetachComplete(err) { if (err) return cb(err); self.groovePlayer = groove.createPlayer(); self.groovePlayer.deviceIndex = wantHardware ? null : groove.DUMMY_DEVICE; self.groovePlayer.attach(self.groovePlaylist, function(err) { self.pendingPlayerAttachDetach = false; if (err) return cb(err); if (self.desiredPlayerHardwareState !== wantHardware) { startPlayerSwitchDevice(self, self.desiredPlayerHardwareState, cb); } else { cb(); } }); } } Player.prototype.setHardwarePlayback = function(value, cb) { var self = this; cb = cb || logIfError; value = !!value; if (value === self.desiredPlayerHardwareState) return cb(); startPlayerSwitchDevice(self, value, function(err) { if (err) return cb(err); self.clearEncodedBuffer(); self.emit('seek'); self.groovePlayer.on('nowplaying', onNowPlaying); self.persistOption('hardwarePlayback', self.desiredPlayerHardwareState); self.emit('hardwarePlayback', self.desiredPlayerHardwareState); cb(); }); function onNowPlaying() { var playHead = self.groovePlayer.position(); var decodeHead = self.groovePlaylist.position(); if (playHead.item) { var nowMs = (new Date()).getTime(); var posMs = playHead.pos * 1000; self.trackStartDate = new Date(nowMs - posMs); self.currentTrack = self.grooveItems[playHead.item.id]; playlistChanged(self); self.currentTrackChanged(); } else if (!decodeHead.item) { if (!self.dontBelieveTheEndOfPlaylistSentinelItsATrap) { // both play head and decode head are null. end of playlist. log.debug("end of playlist"); self.currentTrack = null; playlistChanged(self); self.currentTrackChanged(); } } } function logIfError(err) { if (err) { log.error("Unable to set hardware playback mode:", err.stack); } } }; Player.prototype.startStreaming = function(resp) { this.headerBuffers.forEach(function(headerBuffer) { resp.write(headerBuffer); }); this.recentBuffers.forEach(function(recentBuffer) { resp.write(recentBuffer.buffer); }); this.cancelDetachEncoderTimeout(); this.attachEncoder(); this.openStreamers.push(resp); this.emit('streamerConnect', resp.client); }; Player.prototype.stopStreaming = function(resp) { for (var i = 0; i < this.openStreamers.length; i += 1) { if (this.openStreamers[i] === resp) { this.openStreamers.splice(i, 1); this.emit('streamerDisconnect', resp.client); break; } } }; Player.prototype.lastStreamerDisconnected = function() { log.debug("last streamer disconnected"); this.startDetachEncoderTimeout(); if (!this.desiredPlayerHardwareState && this.isPlaying) { this.emit("autoPause"); this.pause(); } }; Player.prototype.cancelDetachEncoderTimeout = function() { if (this.detachEncoderTimeout) { clearTimeout(this.detachEncoderTimeout); this.detachEncoderTimeout = null; } }; Player.prototype.startDetachEncoderTimeout = function() { var self = this; self.cancelDetachEncoderTimeout(); // we use encodeQueueDuration for the encoder timeout so that we are // guaranteed to have audio available for the encoder in the case of // detaching and reattaching the encoder. self.detachEncoderTimeout = setTimeout(timeout, self.encodeQueueDuration * 1000); function timeout() { if (self.openStreamers.length === 0 && self.isPlaying) { log.debug("detaching encoder"); self.detachEncoder(); } } }; Player.prototype.deleteFiles = function(keys) { var self = this; var delCmds = []; for (var i = 0; i < keys.length; i += 1) { var key = keys[i]; var dbFile = self.libraryIndex.trackTable[key]; if (!dbFile) continue; var fullPath = path.join(self.musicDirectory, dbFile.file); delDbEntryCmds(self, dbFile, delCmds); fs.unlink(fullPath, logIfError); } if (delCmds.length > 0) { self.emit('deleteDbTrack'); self.db.batch(delCmds, logIfError); } function logIfError(err) { if (err) { log.error("Error deleting files:", err.stack); } } }; function delDbEntryCmds(self, dbFile, dbCmds) { // delete items from the queue that are being deleted from the library var deleteQueueItems = []; for (var queueId in self.playlist) { var queueItem = self.playlist[queueId]; if (queueItem.key === dbFile.key) { deleteQueueItems.push(queueId); } } self.removeQueueItems(deleteQueueItems); // delete items from playlists that are being deleted from the library var playlistRemovals = {}; for (var playlistId in self.playlists) { var playlist = self.playlists[playlistId]; var removals = []; playlistRemovals[playlistId] = removals; for (var playlistItemId in playlist.items) { var playlistItem = playlist.items[playlistItemId]; if (playlistItem.key === dbFile.key) { removals.push(playlistItemId); } } } self.playlistRemoveItems(playlistRemovals); self.libraryIndex.removeTrack(dbFile.key); delete self.dbFilesByPath[dbFile.file]; var baseName = path.basename(dbFile.file); var parentDirName = path.dirname(dbFile.file); if (parentDirName === '.') parentDirName = ''; var parentDirEntry = self.dirs[parentDirName]; if (parentDirEntry) delete parentDirEntry[baseName]; dbCmds.push({type: 'del', key: LIBRARY_KEY_PREFIX + dbFile.key}); } Player.prototype.setVolume = function(value) { value = Math.min(2.0, value); value = Math.max(0.0, value); this.volume = value; this.groovePlaylist.setGain(value); this.persistOption('volume', this.volume); this.emit("volumeUpdate"); }; Player.prototype.importUrl = function(urlString, cb) { var self = this; cb = cb || logIfError; var filterIndex = 0; tryImportFilter(); function tryImportFilter() { var importFilter = importUrlFilters[filterIndex]; if (!importFilter) return cb(); importFilter.fn(urlString, callNextFilter); function callNextFilter(err, dlStream, filenameHintWithoutPath, size) { if (err || !dlStream) { if (err) { log.error(importFilter.name + " import filter error, skipping:", err.stack); } filterIndex += 1; tryImportFilter(); return; } self.importStream(dlStream, filenameHintWithoutPath, size, cb); } } function logIfError(err) { if (err) { log.error("Unable to import by URL.", err.stack, "URL:", urlString); } } }; Player.prototype.importNames = function(names, cb) { var self = this; var pend = new Pend(); var allDbFiles = []; names.forEach(function(name) { pend.go(function(cb) { youtubeSearch(name, self.googleApiKey, function(err, videoUrl) { if (err) { log.error("YouTube search error, skipping " + name + ": " + err.stack); cb(); return; } self.importUrl(videoUrl, function(err, dbFiles) { if (err) { log.error("Unable to import from YouTube: " + err.stack); } else if (!dbFiles) { log.error("Unrecognized YouTube URL: " + videoUrl); } else if (dbFiles.length > 0) { allDbFiles = allDbFiles.concat(dbFiles); } cb(); }); }); }); }); pend.wait(function() { cb(null, allDbFiles); }); }; Player.prototype.importStream = function(readStream, filenameHintWithoutPath, size, cb) { var self = this; var ext = path.extname(filenameHintWithoutPath); var tmpDir = path.join(self.musicDirectory, '.tmp'); var id = uuid(); var destPath = path.join(tmpDir, id + ext); var calledCallback = false; var writeStream = null; var progressTimer = null; var importEvent = { id: id, filenameHintWithoutPath: filenameHintWithoutPath, bytesWritten: 0, size: size, date: new Date(), }; readStream.on('error', cleanAndCb); self.importProgress[importEvent.id] = importEvent; self.emit('importStart', importEvent); mkdirp(tmpDir, function(err) { if (calledCallback) return; if (err) return cleanAndCb(err); writeStream = fs.createWriteStream(destPath); readStream.pipe(writeStream); progressTimer = setInterval(checkProgress, 100); writeStream.on('close', onClose); writeStream.on('error', cleanAndCb); function checkProgress() { importEvent.bytesWritten = writeStream.bytesWritten; self.maybeEmitImportProgress(); } function onClose(){ if (calledCallback) return; checkProgress(); self.importFile(destPath, filenameHintWithoutPath, function(err, dbFiles) { if (calledCallback) return; if (err) { cleanAndCb(err); } else { calledCallback = true; cleanTimer(); delete self.importProgress[importEvent.id]; self.emit('importEnd', importEvent); cb(null, dbFiles); } }); } }); function cleanTimer() { if (progressTimer) { clearInterval(progressTimer); progressTimer = null; } } function cleanAndCb(err) { if (writeStream) { fs.unlink(destPath, onUnlinkDone); writeStream = null; } cleanTimer(); if (calledCallback) return; calledCallback = true; delete self.importProgress[importEvent.id]; self.emit('importAbort', importEvent); cb(err); function onUnlinkDone(err) { if (err) { log.warn("Unable to clean up temp file:", err.stack); } } } }; Player.prototype.importFile = function(srcFullPath, filenameHintWithoutPath, cb) { var self = this; cb = cb || logIfError; var filterIndex = 0; log.debug("importFile open file:", srcFullPath); disableFsListenRef(self, tryImportFilter); function tryImportFilter() { var importFilter = importFileFilters[filterIndex]; if (!importFilter) return cleanAndCb(); importFilter.fn(self, srcFullPath, filenameHintWithoutPath, callNextFilter); function callNextFilter(err, dbFiles) { if (err || !dbFiles) { if (err) { log.debug(importFilter.name + " import filter error, skipping:", err.message); } filterIndex += 1; tryImportFilter(); return; } cleanAndCb(null, dbFiles); } } function cleanAndCb(err, dbFiles) { if (!dbFiles) { fs.unlink(srcFullPath, logIfUnlinkError); } disableFsListenUnref(self); cb(err, dbFiles); } function logIfUnlinkError(err) { if (err) { log.error("unable to unlink file:", err.stack); } } function logIfError(err) { if (err) { log.error("unable to import file:", err.stack); } } }; Player.prototype.maybeEmitImportProgress = function() { var now = new Date(); var passedTime = now - this.lastImportProgressEvent; if (passedTime > 500) { this.lastImportProgressEvent = now; this.emit("importProgress"); } }; Player.prototype.persistDirEntry = function(dirEntry, cb) { cb = cb || logIfError; this.db.put(LIBRARY_DIR_PREFIX + dirEntry.dirName, serializeDirEntry(dirEntry), cb); function logIfError(err) { if (err) { log.error("unable to persist db entry:", dirEntry, err.stack); } } }; Player.prototype.persistDbFile = function(dbFile, updateCmds) { this.libraryIndex.addTrack(dbFile); this.dbFilesByPath[dbFile.file] = dbFile; persistDbFile(dbFile, updateCmds); }; Player.prototype.persistOneDbFile = function(dbFile, cb) { cb = cb || logIfDbError; var updateCmds = []; this.persistDbFile(dbFile, updateCmds); this.db.batch(updateCmds, cb); }; Player.prototype.persistOption = function(name, value, cb) { this.db.put(PLAYER_KEY_PREFIX + name, JSON.stringify(value), cb || logIfError); function logIfError(err) { if (err) { log.error("unable to persist player option:", err.stack); } } }; Player.prototype.addToLibrary = function(args, cb) { var self = this; var relPath = args.relPath; var mtime = args.mtime; var fullPath = path.join(self.musicDirectory, relPath); log.debug("addToLibrary open file:", fullPath); groove.open(fullPath, function(err, file) { if (err) { self.invalidPaths[relPath] = err.message; cb(); return; } var dbFile = self.dbFilesByPath[relPath]; var filenameHintWithoutPath = path.basename(relPath); var newDbFile = grooveFileToDbFile(file, filenameHintWithoutPath, dbFile); newDbFile.file = relPath; newDbFile.mtime = mtime; var pend = new Pend(); pend.go(function(cb) { log.debug("addToLibrary close file:", file.filename); file.close(cb); }); pend.go(function(cb) { self.persistOneDbFile(newDbFile, function(err) { if (err) log.error("Error saving", relPath, "to db:", err.stack); cb(); }); }); self.emit('updateDb'); pend.wait(cb); }); }; Player.prototype.updateTags = function(obj) { var updateCmds = []; for (var key in obj) { var dbFile = this.libraryIndex.trackTable[key]; if (!dbFile) continue; var props = obj[key]; for (var propName in DB_PROPS) { var prop = DB_PROPS[propName]; if (! prop.clientCanModify) continue; if (! (propName in props)) continue; var parser = PROP_TYPE_PARSERS[prop.type]; dbFile[propName] = parser(props[propName]); } this.persistDbFile(dbFile, updateCmds); } if (updateCmds.length > 0) { this.db.batch(updateCmds, logIfDbError); this.emit('updateDb'); } }; Player.prototype.insertTracks = function(index, keys, tagAsRandom) { if (keys.length === 0) return []; if (index < 0) index = 0; if (index > this.tracksInOrder.length) index = this.tracksInOrder.length; var trackBeforeIndex = this.tracksInOrder[index - 1]; var trackAtIndex = this.tracksInOrder[index]; var prevSortKey = trackBeforeIndex ? trackBeforeIndex.sortKey : null; var nextSortKey = trackAtIndex ? trackAtIndex.sortKey : null; var items = {}; var ids = []; var sortKeys = keese(prevSortKey, nextSortKey, keys.length); keys.forEach(function(key, i) { var id = uuid(); var sortKey = sortKeys[i]; items[id] = { key: key, sortKey: sortKey, }; ids.push(id); }); this.addItems(items, tagAsRandom); return ids; }; Player.prototype.appendTracks = function(keys, tagAsRandom) { return this.insertTracks(this.tracksInOrder.length, keys, tagAsRandom); }; // items looks like {id: {key, sortKey}} Player.prototype.addItems = function(items, tagAsRandom) { var self = this; tagAsRandom = !!tagAsRandom; var updateCmds = []; for (var id in items) { var item = items[id]; var dbFile = self.libraryIndex.trackTable[item.key]; if (!dbFile) continue; dbFile.lastQueueDate = new Date(); self.persistDbFile(dbFile, updateCmds); var queueItem = { id: id, key: item.key, sortKey: item.sortKey, isRandom: tagAsRandom, grooveFile: null, pendingGrooveFile: false, deleted: false, }; self.playlist[id] = queueItem; persistQueueItem(queueItem, updateCmds); } if (updateCmds.length > 0) { self.db.batch(updateCmds, logIfDbError); playlistChanged(self); lazyReplayGainScanPlaylist(self); } }; Player.prototype.playlistCreate = function(id, name) { if (this.playlists[id]) { log.warn("tried to create playlist with same id as existing"); return; } var playlist = { id: id, name: name, mtime: new Date().getTime(), items: {}, }; this.playlists[playlist.id] = playlist; this.persistPlaylist(playlist); this.emit('playlistCreate', playlist); return playlist; }; Player.prototype.playlistRename = function(playlistId, newName) { var playlist = this.playlists[playlistId]; if (!playlist) return; playlist.name = newName; playlist.mtime = new Date().getTime(); this.persistPlaylist(playlist); this.emit('playlistUpdate', playlist); }; Player.prototype.playlistDelete = function(playlistIds) { var delCmds = []; for (var i = 0; i < playlistIds.length; i += 1) { var playlistId = playlistIds[i]; var playlist = this.playlists[playlistId]; if (!playlist) continue; for (var id in playlist.items) { var item = playlist.items[id]; if (!item) continue; delCmds.push({type: 'del', key: playlistItemKey(playlist, item)}); delete playlist.items[id]; } delCmds.push({type: 'del', key: playlistKey(playlist)}); delete this.playlists[playlistId]; } if (delCmds.length > 0) { this.db.batch(delCmds, logIfDbError); this.emit('playlistDelete'); } }; Player.prototype.playlistAddItems = function(playlistId, items) { var playlist = this.playlists[playlistId]; if (!playlist) return; var updateCmds = []; for (var id in items) { var item = items[id]; var dbFile = this.libraryIndex.trackTable[item.key]; if (!dbFile) continue; var playlistItem = { id: id, key: item.key, sortKey: item.sortKey, }; playlist.items[id] = playlistItem; updateCmds.push({ type: 'put', key: playlistItemKey(playlist, playlistItem), value: serializePlaylistItem(playlistItem), }); } if (updateCmds.length > 0) { playlist.mtime = new Date().getTime(); updateCmds.push({ type: 'put', key: playlistKey(playlist), value: serializePlaylist(playlist), }); this.db.batch(updateCmds, logIfDbError); this.emit('playlistUpdate', playlist); } }; Player.prototype.playlistRemoveItems = function(removals) { var updateCmds = []; for (var playlistId in removals) { var playlist = this.playlists[playlistId]; if (!playlist) continue; var ids = removals[playlistId]; var dirty = false; for (var i = 0; i < ids.length; i += 1) { var id = ids[i]; var item = playlist.items[id]; if (!item) continue; dirty = true; updateCmds.push({type: 'del', key: playlistItemKey(playlist, item)}); delete playlist.items[id]; } if (dirty) { playlist.mtime = new Date().getTime(); updateCmds.push({ type: 'put', key: playlistKey(playlist), value: serializePlaylist(playlist), }); } } if (updateCmds.length > 0) { this.db.batch(updateCmds, logIfDbError); this.emit('playlistUpdate'); } }; // items looks like {playlistId: {id: {sortKey}}} Player.prototype.playlistMoveItems = function(updates) { var updateCmds = []; for (var playlistId in updates) { var playlist = this.playlists[playlistId]; if (!playlist) continue; var playlistDirty = false; var update = updates[playlistId]; for (var id in update) { var playlistItem = playlist.items[id]; if (!playlistItem) continue; var updateItem = update[id]; playlistItem.sortKey = updateItem.sortKey; playlistDirty = true; updateCmds.push({ type: 'put', key: playlistItemKey(playlist, playlistItem), value: serializePlaylistItem(playlistItem), }); } if (playlistDirty) { playlist.mtime = new Date().getTime(); updateCmds.push({ type: 'put', key: playlistKey(playlist), value: serializePlaylist(playlist), }); } } if (updateCmds.length > 0) { this.db.batch(updateCmds, logIfDbError); this.emit('playlistUpdate'); } }; Player.prototype.persistPlaylist = function(playlist, cb) { cb = cb || logIfDbError; var key = playlistKey(playlist); var payload = serializePlaylist(playlist); this.db.put(key, payload, cb); }; Player.prototype.labelCreate = function(id, name) { if (id in this.libraryIndex.labelTable) { log.warn("tried to create label that already exists"); return; } var color = labelColors[Math.floor(Math.random() * labelColors.length)]; var labelEntry = {id: id, name: name, color: color}; this.libraryIndex.addLabel(labelEntry); var key = LABEL_KEY_PREFIX + id; this.db.put(key, JSON.stringify(labelEntry), logIfDbError); this.emit('labelCreate'); }; Player.prototype.labelRename = function(id, name) { var labelEntry = this.libraryIndex.labelTable[id]; if (!labelEntry) return; labelEntry.name = name; this.libraryIndex.addLabel(labelEntry); var key = LABEL_KEY_PREFIX + id; this.db.put(key, JSON.stringify(labelEntry), logIfDbError); this.emit('labelRename'); }; Player.prototype.labelColorUpdate = function(id, color) { var labelEntry = this.libraryIndex.labelTable[id]; if (!labelEntry) return; labelEntry.color = color; this.libraryIndex.addLabel(labelEntry); var key = LABEL_KEY_PREFIX + id; this.db.put(key, JSON.stringify(labelEntry), logIfDbError); this.emit('labelColorUpdate'); }; Player.prototype.labelDelete = function(ids) { var updateCmds = []; var libraryChanged = false; for (var i = 0; i < ids.length; i++) { var labelId = ids[i]; if (!(labelId in this.libraryIndex.labelTable)) continue; this.libraryIndex.removeLabel(labelId); var key = LABEL_KEY_PREFIX + labelId; updateCmds.push({type: 'del', key: key}); // clean out references from the library var files = this.dbFilesByLabel[labelId]; for (var fileId in files) { var dbFile = files[fileId]; delete dbFile.labels[labelId]; persistDbFile(dbFile, updateCmds); libraryChanged = true; } delete this.dbFilesByLabel[labelId]; } if (updateCmds.length === 0) return; this.db.batch(updateCmds, logIfDbError); if (libraryChanged) { this.emit('updateDb'); } this.emit('labelDelete'); }; Player.prototype.labelAdd = function(additions) { this.changeLabels(additions, true); }; Player.prototype.labelRemove = function(removals) { this.changeLabels(removals, false); }; Player.prototype.changeLabels = function(changes, isAdd) { var self = this; var updateCmds = []; for (var id in changes) { var labelIds = changes[id]; var dbFile = this.libraryIndex.trackTable[id]; if (!dbFile) continue; if (labelIds.length === 0) continue; var changedTrack = false; for (var i = 0; i < labelIds.length; i++) { var labelId = labelIds[i]; var filesByThisLabel = self.dbFilesByLabel[labelId]; if (isAdd) { if (labelId in dbFile.labels) continue; // already got it dbFile.labels[labelId] = 1; if (filesByThisLabel == null) filesByThisLabel = self.dbFilesByLabel[labelId] = {}; filesByThisLabel[dbFile.key] = dbFile; } else { if (!(labelId in dbFile.labels)) continue; // already gone delete dbFile.labels[labelId]; delete filesByThisLabel[dbFile.key]; } changedTrack = true; } if (changedTrack) { this.persistDbFile(dbFile, updateCmds); } } if (updateCmds.length === 0) return; this.db.batch(updateCmds, logIfDbError); this.emit('updateDb'); }; Player.prototype.clearQueue = function() { this.removeQueueItems(Object.keys(this.playlist)); }; Player.prototype.removeAllRandomQueueItems = function() { var idsToRemove = []; for (var i = 0; i < this.tracksInOrder.length; i += 1) { var track = this.tracksInOrder[i]; if (track.isRandom && track !== this.currentTrack) { idsToRemove.push(track.id); } } return this.removeQueueItems(idsToRemove); }; Player.prototype.shufflePlaylist = function() { if (this.tracksInOrder.length === 0) return; if (this.autoDjOn) return this.removeAllRandomQueueItems(); var sortKeys = this.tracksInOrder.map(function(track) { return track.sortKey; }); shuffle(sortKeys); // fix sortKey and index properties var updateCmds = []; for (var i = 0; i < this.tracksInOrder.length; i += 1) { var track = this.tracksInOrder[i]; track.index = i; track.sortKey = sortKeys[i]; persistQueueItem(track, updateCmds); } this.db.batch(updateCmds, logIfDbError); playlistChanged(this); }; Player.prototype.removeQueueItems = function(ids) { if (ids.length === 0) return; var delCmds = []; var currentTrackChanged = false; for (var i = 0; i < ids.length; i += 1) { var id = ids[i]; var item = this.playlist[id]; if (!item) continue; delCmds.push({type: 'del', key: QUEUE_KEY_PREFIX + id}); if (item.grooveFile) this.playlistItemDeleteQueue.push(item); if (item === this.currentTrack) { var nextPos = this.currentTrack.index + 1; for (;;) { var nextTrack = this.tracksInOrder[nextPos]; var nextTrackId = nextTrack && nextTrack.id; this.currentTrack = nextTrackId && this.playlist[nextTrack.id]; if (!this.currentTrack && nextPos < this.tracksInOrder.length) { nextPos += 1; continue; } break; } if (this.currentTrack) { this.seekRequestPos = 0; } currentTrackChanged = true; } delete this.playlist[id]; } if (delCmds.length > 0) this.db.batch(delCmds, logIfDbError); playlistChanged(this); if (currentTrackChanged) { this.currentTrackChanged(); } }; // items looks like {id: {sortKey}} Player.prototype.moveQueueItems = function(items) { var updateCmds = []; for (var id in items) { var track = this.playlist[id]; if (!track) continue; // race conditions, etc. track.sortKey = items[id].sortKey; persistQueueItem(track, updateCmds); } if (updateCmds.length > 0) { this.db.batch(updateCmds, logIfDbError); playlistChanged(this); } }; Player.prototype.moveRangeToPos = function(startPos, endPos, toPos) { var ids = []; for (var i = startPos; i < endPos; i += 1) { var track = this.tracksInOrder[i]; if (!track) continue; ids.push(track.id); } this.moveIdsToPos(ids, toPos); }; Player.prototype.moveIdsToPos = function(ids, toPos) { var trackBeforeIndex = this.tracksInOrder[toPos - 1]; var trackAtIndex = this.tracksInOrder[toPos]; var prevSortKey = trackBeforeIndex ? trackBeforeIndex.sortKey : null; var nextSortKey = trackAtIndex ? trackAtIndex.sortKey : null; var sortKeys = keese(prevSortKey, nextSortKey, ids.length); var updateCmds = []; for (var i = 0; i < ids.length; i += 1) { var id = ids[i]; var queueItem = this.playlist[id]; if (!queueItem) continue; queueItem.sortKey = sortKeys[i]; persistQueueItem(queueItem, updateCmds); } if (updateCmds.length > 0) { this.db.batch(updateCmds, logIfDbError); playlistChanged(this); } }; Player.prototype.pause = function() { if (!this.isPlaying) return; this.isPlaying = false; this.pausedTime = (new Date() - this.trackStartDate) / 1000; this.groovePlaylist.pause(); this.cancelDetachEncoderTimeout(); playlistChanged(this); this.currentTrackChanged(); }; Player.prototype.play = function() { if (!this.currentTrack) { this.currentTrack = this.tracksInOrder[0]; } else if (!this.isPlaying) { this.trackStartDate = new Date(new Date() - this.pausedTime * 1000); } this.groovePlaylist.play(); this.startDetachEncoderTimeout(); this.isPlaying = true; playlistChanged(this); this.currentTrackChanged(); }; // This function should be avoided in favor of seek. Note that it is called by // some MPD protocol commands, because the MPD protocol is stupid. Player.prototype.seekToIndex = function(index, pos) { var track = this.tracksInOrder[index]; if (!track) return null; this.currentTrack = track; this.seekRequestPos = pos; playlistChanged(this); this.currentTrackChanged(); return track; }; Player.prototype.seek = function(id, pos) { var track = this.playlist[id]; if (!track) return null; this.currentTrack = this.playlist[id]; this.seekRequestPos = pos; playlistChanged(this); this.currentTrackChanged(); return track; }; Player.prototype.next = function() { return this.skipBy(1); }; Player.prototype.prev = function() { return this.skipBy(-1); }; Player.prototype.skipBy = function(amt) { var defaultIndex = amt > 0 ? -1 : this.tracksInOrder.length; var currentIndex = this.currentTrack ? this.currentTrack.index : defaultIndex; var newIndex = currentIndex + amt; return this.seekToIndex(newIndex, 0); }; Player.prototype.setRepeat = function(value) { value = Math.floor(value); if (value !== Player.REPEAT_ONE && value !== Player.REPEAT_ALL && value !== Player.REPEAT_OFF) { return; } if (value === this.repeat) return; this.repeat = value; this.persistOption('repeat', this.repeat); playlistChanged(this); this.emit('repeatUpdate'); }; Player.prototype.setAutoDjOn = function(value) { value = !!value; if (value === this.autoDjOn) return; this.autoDjOn = value; this.persistOption('autoDjOn', this.autoDjOn); this.emit('autoDjOn'); this.checkAutoDj(); }; Player.prototype.setAutoDjHistorySize = function(value) { value = Math.floor(value); if (value === this.autoDjHistorySize) return; this.autoDjHistorySize = value; this.persistOption('autoDjHistorySize', this.autoDjHistorySize); this.emit('autoDjHistorySize'); this.checkAutoDj(); }; Player.prototype.setAutoDjFutureSize = function(value) { value = Math.floor(value); if (value === this.autoDjFutureSize) return; this.autoDjFutureSize = value; this.persistOption('autoDjFutureSize', this.autoDjFutureSize); this.emit('autoDjFutureSize'); this.checkAutoDj(); }; Player.prototype.stop = function() { this.isPlaying = false; this.cancelDetachEncoderTimeout(); this.groovePlaylist.pause(); this.seekRequestPos = 0; this.pausedTime = 0; playlistChanged(this); }; Player.prototype.clearEncodedBuffer = function() { while (this.recentBuffers.length > 0) { this.recentBuffers.shift(); } }; Player.prototype.getSuggestedPath = function(track, filenameHint) { var p = ""; if (track.albumArtistName) { p = path.join(p, safePath(track.albumArtistName)); } else if (track.compilation) { p = path.join(p, safePath(this.libraryIndex.variousArtistsName)); } else if (track.artistName) { p = path.join(p, safePath(track.artistName)); } if (track.albumName) { p = path.join(p, safePath(track.albumName)); } var t = ""; if (track.track != null) { t += safePath(zfill(track.track, 2)) + " "; } t += safePath(track.name + path.extname(filenameHint)); return path.join(p, t); }; Player.prototype.queueScan = function(dbFile) { var self = this; var scanKey, scanType; if (dbFile.albumName) { scanType = 'album'; scanKey = self.libraryIndex.getAlbumKey(dbFile); } else { scanType = 'track'; scanKey = dbFile.key; } if (self.scanQueue.idInQueue(scanKey)) { return; } self.scanQueue.add(scanKey, { type: scanType, key: scanKey, }); }; Player.prototype.performScan = function(args, cb) { var self = this; var scanType = args.type; var scanKey = args.key; // build list of files we want to open var dbFilesToOpen; if (scanType === 'album') { var albumKey = scanKey; self.libraryIndex.rebuildTracks(); var album = self.libraryIndex.albumTable[albumKey]; if (!album) { log.warn("wanted to scan album with key", JSON.stringify(albumKey), "but no longer exists."); cb(); return; } log.debug("Scanning album for loudness:", JSON.stringify(albumKey)); dbFilesToOpen = album.trackList; } else if (scanType === 'track') { var trackKey = scanKey; var dbFile = self.libraryIndex.trackTable[trackKey]; if (!dbFile) { log.warn("wanted to scan track with key", JSON.stringify(trackKey), "but no longer exists."); cb(); return; } log.debug("Scanning track for loudness:", JSON.stringify(trackKey)); dbFilesToOpen = [dbFile]; } else { throw new Error("unexpected scan type: " + scanType); } // open all the files in the list var pend = new Pend(); // we're already doing multiple parallel scans. within each scan let's // read one thing at a time to avoid slamming the system. pend.max = 1; var grooveFileList = []; var files = {}; dbFilesToOpen.forEach(function(dbFile) { pend.go(function(cb) { var fullPath = path.join(self.musicDirectory, dbFile.file); log.debug("performScan open file:", fullPath); groove.open(fullPath, function(err, file) { if (err) { log.error("Error opening", fullPath, "in order to scan:", err.stack); } else { var fileInfo; files[file.id] = fileInfo = { dbFile: dbFile, loudnessDone: false, fingerprintDone: false, }; self.ongoingScans[dbFile.key] = fileInfo; grooveFileList.push(file); } cb(); }); }); }); var scanPlaylist; var endOfPlaylistPend = new Pend(); var scanDetector; var scanDetectorAttached = false; var endOfDetectorCb; var scanFingerprinter; var scanFingerprinterAttached = false; var endOfFingerprinterCb; pend.wait(function() { // emit this because we updated ongoingScans self.emit('scanProgress'); scanPlaylist = groove.createPlaylist(); scanPlaylist.setFillMode(groove.ANY_SINK_FULL); scanDetector = groove.createLoudnessDetector(); scanFingerprinter = groove.createFingerprinter(); scanDetector.on('info', onLoudnessInfo); scanFingerprinter.on('info', onFingerprinterInfo); var pend = new Pend(); pend.go(attachLoudnessDetector); pend.go(attachFingerprinter); pend.wait(onEverythingAttached); }); function onEverythingAttached(err) { if (err) { log.error("Error attaching:", err.stack); cleanupAndCb(); return; } grooveFileList.forEach(function(file) { scanPlaylist.insert(file); }); endOfPlaylistPend.wait(function() { for (var fileId in files) { var fileInfo = files[fileId]; var dbFile = fileInfo.dbFile; self.persistOneDbFile(dbFile); self.emit('scanComplete', dbFile); } cleanupAndCb(); }); } function attachLoudnessDetector(cb) { scanDetector.attach(scanPlaylist, function(err) { if (err) return cb(err); scanDetectorAttached = true; endOfPlaylistPend.go(function(cb) { endOfDetectorCb = cb; }); cb(); }); } function attachFingerprinter(cb) { scanFingerprinter.attach(scanPlaylist, function(err) { if (err) return cb(err); scanFingerprinterAttached = true; endOfPlaylistPend.go(function(cb) { endOfFingerprinterCb = cb; }); cb(); }); } function onLoudnessInfo() { var info; while (info = scanDetector.getInfo()) { var gain = groove.loudnessToReplayGain(info.loudness); var dbFile; var fileInfo; if (info.item) { fileInfo = files[info.item.file.id]; fileInfo.loudnessDone = true; dbFile = fileInfo.dbFile; log.info("loudness scan file complete:", dbFile.name, "gain", gain, "duration", info.duration); dbFile.replayGainTrackGain = gain; dbFile.replayGainTrackPeak = info.peak; dbFile.duration = info.duration; checkUpdateGroovePlaylist(self); self.emit('scanProgress'); } else { log.debug("loudness scan complete:", JSON.stringify(scanKey), "gain", gain); for (var fileId in files) { fileInfo = files[fileId]; dbFile = fileInfo.dbFile; dbFile.replayGainAlbumGain = gain; dbFile.replayGainAlbumPeak = info.peak; } checkUpdateGroovePlaylist(self); if (endOfDetectorCb) { endOfDetectorCb(); endOfDetectorCb = null; } return; } } } function onFingerprinterInfo() { var info; while (info = scanFingerprinter.getInfo()) { if (info.item) { var fileInfo = files[info.item.file.id]; fileInfo.fingerprintDone = true; var dbFile = fileInfo.dbFile; log.info("fingerprint scan file complete:", dbFile.name); dbFile.fingerprint = info.fingerprint; self.emit('scanProgress'); } else { log.debug("fingerprint scan complete:", JSON.stringify(scanKey)); if (endOfFingerprinterCb) { endOfFingerprinterCb(); endOfFingerprinterCb = null; } return; } } } function cleanupAndCb() { grooveFileList.forEach(function(file) { pend.go(function(cb) { var fileInfo = files[file.id]; var dbFile = fileInfo.dbFile; delete self.ongoingScans[dbFile.key]; log.debug("performScan close file:", file.filename); file.close(cb); }); }); if (scanDetectorAttached) pend.go(detachLoudnessScanner); if (scanFingerprinterAttached) pend.go(detachFingerprinter); pend.wait(function(err) { // emit this because we changed ongoingScans above self.emit('scanProgress'); cb(err); }); } function detachLoudnessScanner(cb) { scanDetector.detach(cb); } function detachFingerprinter(cb) { scanFingerprinter.detach(cb); } }; Player.prototype.checkAutoDj = function() { var self = this; if (!self.autoDjOn) return; // if no track is playing, assume the first track is about to be var currentIndex = self.currentTrack ? self.currentTrack.index : 0; var deleteCount = Math.max(currentIndex - self.autoDjHistorySize, 0); if (self.autoDjHistorySize < 0) deleteCount = 0; var addCount = Math.max(self.autoDjFutureSize + 1 - (self.tracksInOrder.length - currentIndex), 0); var idsToDelete = []; for (var i = 0; i < deleteCount; i += 1) { idsToDelete.push(self.tracksInOrder[i].id); } var keys = getRandomSongKeys(addCount); self.removeQueueItems(idsToDelete); self.appendTracks(keys, true); function getRandomSongKeys(count) { if (count === 0) return []; var neverQueued = []; var sometimesQueued = []; for (var key in self.libraryIndex.trackTable) { var dbFile = self.libraryIndex.trackTable[key]; if (dbFile.lastQueueDate == null) { neverQueued.push(dbFile); } else { sometimesQueued.push(dbFile); } } // backwards by time sometimesQueued.sort(function(a, b) { return b.lastQueueDate - a.lastQueueDate; }); // distribution is a triangle for ever queued, and a rectangle for never queued // ___ // /| | // / | | // /__|_| var maxWeight = sometimesQueued.length; var triangleArea = Math.floor(maxWeight * maxWeight / 2); if (maxWeight === 0) maxWeight = 1; var rectangleArea = maxWeight * neverQueued.length; var totalSize = triangleArea + rectangleArea; if (totalSize === 0) return []; // decode indexes through the distribution shape var keys = []; for (var i = 0; i < count; i += 1) { var index = Math.random() * totalSize; if (index < triangleArea) { // triangle keys.push(sometimesQueued[Math.floor(Math.sqrt(index))].key); } else { keys.push(neverQueued[Math.floor((index - triangleArea) / maxWeight)].key); } } return keys; } }; Player.prototype.currentTrackChanged = function() { this.persistCurrentTrack(); this.emit('currentTrack'); }; Player.prototype.persistCurrentTrack = function(cb) { // save the current track and time to db var currentTrackInfo = { id: this.currentTrack && this.currentTrack.id, pos: this.getCurPos(), }; this.persistOption('currentTrackInfo', currentTrackInfo, cb); }; Player.prototype.sortAndQueueTracks = function(tracks) { // given an array of tracks, sort them according to the library sorting // and then queue them in the best place if (!tracks.length) return; var sortedTracks = sortTracks(tracks); this.queueTracks(sortedTracks); }; Player.prototype.sortAndQueueTracksInPlaylist = function(playlist, tracks, previousKey, nextKey) { if (!tracks.length) return; var sortedTracks = sortTracks(tracks); var items = {}; var sortKeys = keese(previousKey, nextKey, tracks.length); for (var i = 0; i < tracks.length; i += 1) { var track = tracks[i]; var sortKey = sortKeys[i]; var id = uuid(); items[id] = { key: track.key, sortKey: sortKey, }; } this.playlistAddItems(playlist.id, items); }; Player.prototype.queueTrackKeys = function(trackKeys, previousKey, nextKey) { if (!trackKeys.length) return; if (previousKey == null && nextKey == null) { var defaultPos = this.getDefaultQueuePosition(); previousKey = defaultPos.previousKey; nextKey = defaultPos.nextKey; } var items = {}; var sortKeys = keese(previousKey, nextKey, trackKeys.length); for (var i = 0; i < trackKeys.length; i += 1) { var trackKey = trackKeys[i]; var sortKey = sortKeys[i]; var id = uuid(); items[id] = { key: trackKey, sortKey: sortKey, }; } this.addItems(items, false); }; Player.prototype.queueTracks = function(tracks, previousKey, nextKey) { // given an array of tracks, and a previous sort key and a next sort key, // call addItems correctly var trackKeys = tracks.map(function(track) { return track.key; }).filter(function(key) { return !!key; }); return this.queueTrackKeys(trackKeys, previousKey, nextKey); }; Player.prototype.getDefaultQueuePosition = function() { var previousKey = this.currentTrack && this.currentTrack.sortKey; var nextKey = null; var startPos = this.currentTrack ? this.currentTrack.index + 1 : 0; for (var i = startPos; i < this.tracksInOrder.length; i += 1) { var track = this.tracksInOrder[i]; var sortKey = track.sortKey; if (track.isRandom) { nextKey = sortKey; break; } previousKey = sortKey; } return { previousKey: previousKey, nextKey: nextKey }; }; function persistDbFile(dbFile, updateCmds) { updateCmds.push({ type: 'put', key: LIBRARY_KEY_PREFIX + dbFile.key, value: serializeFileData(dbFile), }); } function persistQueueItem(item, updateCmds) { updateCmds.push({ type: 'put', key: QUEUE_KEY_PREFIX + item.id, value: serializeQueueItem(item), }); } function onAddOrChange(self, relPath, fileMtime, cb) { cb = cb || logIfError; // check the mtime against the mtime of the same file in the db var dbFile = self.dbFilesByPath[relPath]; if (dbFile) { var dbMtime = dbFile.mtime; if (dbMtime >= fileMtime) { // the info we have in our db for this file is fresh cb(null, dbFile); return; } } self.addQueue.add(relPath, { relPath: relPath, mtime: fileMtime, }); self.addQueue.waitForId(relPath, function(err) { var dbFile = self.dbFilesByPath[relPath]; cb(err, dbFile); }); function logIfError(err) { if (err) { log.error("Unable to add to queue:", err.stack); } } } function checkPlayCount(self) { if (self.isPlaying && !self.previousIsPlaying) { self.playingStart = new Date(new Date() - self.playingTime); self.previousIsPlaying = true; } self.playingTime = new Date() - self.playingStart; if (self.currentTrack === self.lastPlayingItem) return; if (self.lastPlayingItem) { var dbFile = self.libraryIndex.trackTable[self.lastPlayingItem.key]; if (dbFile) { var minAmt = 15 * 1000; var maxAmt = 4 * 60 * 1000; var halfAmt = dbFile.duration / 2 * 1000; if (self.playingTime >= minAmt && (self.playingTime >= maxAmt || self.playingTime >= halfAmt)) { dbFile.playCount += 1; self.persistOneDbFile(dbFile); self.emit('play', self.lastPlayingItem, dbFile, self.playingStart); self.emit('updateDb'); } } } self.lastPlayingItem = self.currentTrack; self.previousIsPlaying = self.isPlaying; self.playingStart = new Date(); self.playingTime = 0; } function disableFsListenRef(self, fn) { self.disableFsRefCount += 1; if (self.disableFsRefCount === 1) { log.debug("pause dirScanQueue"); self.dirScanQueue.setPause(true); self.dirScanQueue.waitForProcessing(fn); } else { fn(); } } function disableFsListenUnref(self) { self.disableFsRefCount -= 1; if (self.disableFsRefCount === 0) { log.debug("unpause dirScanQueue"); self.dirScanQueue.setPause(false); } else if (self.disableFsRefCount < 0) { throw new Error("disableFsListenUnref called too many times"); } } function operatorCompare(a, b) { return a < b ? -1 : a > b ? 1 : 0; } function disambiguateSortKeys(self) { var previousUniqueKey = null; var previousKey = null; self.tracksInOrder.forEach(function(track, i) { if (track.sortKey === previousKey) { // move the repeat back track.sortKey = keese(previousUniqueKey, track.sortKey); previousUniqueKey = track.sortKey; } else { previousUniqueKey = previousKey; previousKey = track.sortKey; } }); } // generate self.tracksInOrder from self.playlist function cacheTracksArray(self) { self.tracksInOrder = Object.keys(self.playlist).map(trackById); self.tracksInOrder.sort(asc); self.tracksInOrder.forEach(function(track, index) { track.index = index; }); function asc(a, b) { return operatorCompare(a.sortKey, b.sortKey); } function trackById(id) { return self.playlist[id]; } } function lazyReplayGainScanPlaylist(self) { // clear the queue since we're going to completely rebuild it anyway // this allows the following priority code to work. self.scanQueue.clear(); // prioritize the currently playing track, followed by the next tracks, // followed by the previous tracks var albumGain = {}; var start1 = self.currentTrack ? self.currentTrack.index : 0; var i; for (i = start1; i < self.tracksInOrder.length; i += 1) { checkScan(self.tracksInOrder[i]); } for (i = 0; i < start1; i += 1) { checkScan(self.tracksInOrder[i]); } function checkScan(track) { var dbFile = self.libraryIndex.trackTable[track.key]; if (!dbFile) return; var albumKey = self.libraryIndex.getAlbumKey(dbFile); var needScan = dbFile.fingerprint == null || dbFile.replayGainAlbumGain == null || dbFile.replayGainTrackGain == null || (dbFile.albumName && albumGain[albumKey] && albumGain[albumKey] !== dbFile.replayGainAlbumGain); if (needScan) { self.queueScan(dbFile); } else { albumGain[albumKey] = dbFile.replayGainAlbumGain; } } } function playlistChanged(self) { cacheTracksArray(self); disambiguateSortKeys(self); if (self.currentTrack) { self.tracksInOrder.forEach(function(track, index) { var prevDiff = self.currentTrack.index - index; var nextDiff = index - self.currentTrack.index; var withinPrev = prevDiff <= PREV_FILE_COUNT && prevDiff >= 0; var withinNext = nextDiff <= NEXT_FILE_COUNT && nextDiff >= 0; var shouldHaveGrooveFile = withinPrev || withinNext; var hasGrooveFile = track.grooveFile != null || track.pendingGrooveFile; if (hasGrooveFile && !shouldHaveGrooveFile) { self.playlistItemDeleteQueue.push(track); } else if (!hasGrooveFile && shouldHaveGrooveFile) { preloadFile(self, track); } }); } else { self.isPlaying = false; self.cancelDetachEncoderTimeout(); self.trackStartDate = null; self.pausedTime = 0; } checkUpdateGroovePlaylist(self); performGrooveFileDeletes(self); self.checkAutoDj(); checkPlayCount(self); self.emit('queueUpdate'); } function performGrooveFileDeletes(self) { while (self.playlistItemDeleteQueue.length) { var item = self.playlistItemDeleteQueue.shift(); // we set this so that any callbacks that return which were trying to // set the grooveItem can check if the item got deleted item.deleted = true; if (!item.grooveFile) continue; log.debug("performGrooveFileDeletes close file:", item.grooveFile.filename); var grooveFile = item.grooveFile; item.grooveFile = null; closeFile(grooveFile); } } function preloadFile(self, track) { var relPath = self.libraryIndex.trackTable[track.key].file; var fullPath = path.join(self.musicDirectory, relPath); track.pendingGrooveFile = true; log.debug("preloadFile open file:", fullPath); // set this so that we know we want the file preloaded track.deleted = false; groove.open(fullPath, function(err, file) { track.pendingGrooveFile = false; if (err) { log.error("Error opening", relPath, err.stack); return; } if (track.deleted) { log.debug("preloadFile close file (already deleted):", file.filename); closeFile(file); return; } track.grooveFile = file; checkUpdateGroovePlaylist(self); }); } function checkUpdateGroovePlaylist(self) { if (!self.currentTrack) { self.groovePlaylist.clear(); self.grooveItems = {}; return; } var groovePlaylist = self.groovePlaylist.items(); var playHead = self.groovePlayer.position(); var playHeadItemId = playHead.item && playHead.item.id; var groovePlIndex = 0; var grooveItem; if (playHeadItemId) { while (groovePlIndex < groovePlaylist.length) { grooveItem = groovePlaylist[groovePlIndex]; if (grooveItem.id === playHeadItemId) break; // this groove playlist item is before the current playhead. delete it! self.groovePlaylist.remove(grooveItem); delete self.grooveItems[grooveItem.id]; groovePlIndex += 1; } } var plItemIndex = self.currentTrack.index; var plTrack; var currentGrooveItem = null; // might be different than playHead.item var groovePlItemCount = 0; var gainAndPeak; while (groovePlIndex < groovePlaylist.length) { grooveItem = groovePlaylist[groovePlIndex]; var grooveTrack = self.grooveItems[grooveItem.id]; // now we have deleted all items before the current track. we are now // comparing the libgroove playlist and the groovebasin playlist // side by side. plTrack = self.tracksInOrder[plItemIndex]; if (grooveTrack === plTrack) { // if they're the same, we advance // but we might have to correct the gain gainAndPeak = calcGainAndPeak(plTrack); self.groovePlaylist.setItemGain(grooveItem, gainAndPeak.gain); self.groovePlaylist.setItemPeak(grooveItem, gainAndPeak.peak); currentGrooveItem = currentGrooveItem || grooveItem; groovePlIndex += 1; incrementPlIndex(); continue; } // this groove track is wrong. delete it. self.groovePlaylist.remove(grooveItem); delete self.grooveItems[grooveItem.id]; groovePlIndex += 1; } // we still need to add more libgroove playlist items, but this one has // not yet finished loading from disk. We must take note of this so that // if we receive the end of playlist sentinel, we start playback again // once this track has finished loading. self.dontBelieveTheEndOfPlaylistSentinelItsATrap = true; while (groovePlItemCount < NEXT_FILE_COUNT) { plTrack = self.tracksInOrder[plItemIndex]; if (!plTrack) { // we hit the end of the groove basin playlist. we're done adding tracks // to the libgroove playlist. self.dontBelieveTheEndOfPlaylistSentinelItsATrap = false; break; } if (!plTrack.grooveFile) { break; } // compute the gain adjustment gainAndPeak = calcGainAndPeak(plTrack); grooveItem = self.groovePlaylist.insert(plTrack.grooveFile, gainAndPeak.gain, gainAndPeak.peak); self.grooveItems[grooveItem.id] = plTrack; currentGrooveItem = currentGrooveItem || grooveItem; incrementPlIndex(); } if (currentGrooveItem && self.seekRequestPos >= 0) { var seekPos = self.seekRequestPos; // we want to clear encoded buffers after the seek completes, e.g. after // we get the end of playlist sentinel self.clearEncodedBuffer(); self.queueClearEncodedBuffers = true; self.groovePlaylist.seek(currentGrooveItem, seekPos); self.seekRequestPos = -1; if (self.isPlaying) { var nowMs = (new Date()).getTime(); var posMs = seekPos * 1000; self.trackStartDate = new Date(nowMs - posMs); } else { self.pausedTime = seekPos; } self.currentTrackChanged(); } function calcGainAndPeak(plTrack) { // if the previous item is the previous item from the album, or the // next item is the next item from the album, use album replaygain. // else, use track replaygain. var dbFile = self.libraryIndex.trackTable[plTrack.key]; var albumMode = albumInfoMatch(-1) || albumInfoMatch(1); var gain = REPLAYGAIN_PREAMP; var peak; if (dbFile.replayGainAlbumGain != null && albumMode) { gain *= dBToFloat(dbFile.replayGainAlbumGain); peak = dbFile.replayGainAlbumPeak || 1.0; } else if (dbFile.replayGainTrackGain != null) { gain *= dBToFloat(dbFile.replayGainTrackGain); peak = dbFile.replayGainTrackPeak || 1.0; } else { gain *= REPLAYGAIN_DEFAULT; peak = 1.0; } return {gain: gain, peak: peak}; function albumInfoMatch(dir) { var otherPlTrack = self.tracksInOrder[plTrack.index + dir]; if (!otherPlTrack) return false; var otherDbFile = self.libraryIndex.trackTable[otherPlTrack.key]; if (!otherDbFile) return false; var albumMatch = self.libraryIndex.getAlbumKey(dbFile) === self.libraryIndex.getAlbumKey(otherDbFile); if (!albumMatch) return false; // if there are no track numbers then it's hardly an album, is it? if (dbFile.track == null || otherDbFile.track == null) { return false; } var trackMatch = dbFile.track + dir === otherDbFile.track; if (!trackMatch) return false; return true; } } function incrementPlIndex() { groovePlItemCount += 1; if (self.repeat !== Player.REPEAT_ONE) { plItemIndex += 1; if (self.repeat === Player.REPEAT_ALL && plItemIndex >= self.tracksInOrder.length) { plItemIndex = 0; } } } } function isFileIgnored(basename) { return (/^\./).test(basename) || (/~$/).test(basename); } function isExtensionIgnored(self, extName) { var extNameLower = extName.toLowerCase(); for (var i = 0; i < self.ignoreExtensions.length; i += 1) { if (self.ignoreExtensions[i] === extNameLower) { return true; } } return false; } function deserializeFileData(dataStr) { var dbFile = JSON.parse(dataStr); for (var propName in DB_PROPS) { var propInfo = DB_PROPS[propName]; if (!propInfo) continue; var parser = PROP_TYPE_PARSERS[propInfo.type]; dbFile[propName] = parser(dbFile[propName]); } return dbFile; } function serializeQueueItem(item) { return JSON.stringify({ id: item.id, key: item.key, sortKey: item.sortKey, isRandom: item.isRandom, }); } function serializePlaylistItem(item) { return JSON.stringify({ id: item.id, key: item.key, sortKey: item.sortKey, }); } function trackWithoutIndex(category, dbFile) { var out = {}; for (var propName in DB_PROPS) { var prop = DB_PROPS[propName]; if (!prop[category]) continue; // save space by leaving out null and undefined values var value = dbFile[propName]; if (value == null) continue; if (prop.type === 'set') { out[propName] = copySet(value); } else { out[propName] = value; } } return out; } function serializeFileData(dbFile) { return JSON.stringify(trackWithoutIndex('db', dbFile)); } function serializeDirEntry(dirEntry) { return JSON.stringify({ dirName: dirEntry.dirName, entries: dirEntry.entries, dirEntries: dirEntry.dirEntries, mtime: dirEntry.mtime, }); } function filenameWithoutExt(filename) { var ext = path.extname(filename); return filename.substring(0, filename.length - ext.length); } function closeFile(file) { file.close(function(err) { if (err) { log.error("Error closing", file, err.stack); } }); } function parseTrackString(trackStr) { if (!trackStr) return {}; var parts = trackStr.split('/'); if (parts.length > 1) { return { value: parseIntOrNull(parts[0]), total: parseIntOrNull(parts[1]), }; } return { value: parseIntOrNull(parts[0]), }; } function parseIntOrNull(n) { n = parseInt(n, 10); if (isNaN(n)) return null; return n; } function parseFloatOrNull(n) { n = parseFloat(n); if (isNaN(n)) return null; return n; } function grooveFileToDbFile(file, filenameHintWithoutPath, object) { object = object || {key: uuid()}; var parsedTrack = parseTrackString(file.getMetadata("track")); var parsedDisc = parseTrackString( file.getMetadata("disc") || file.getMetadata("TPA") || file.getMetadata("TPOS")); object.name = (file.getMetadata("title") || filenameWithoutExt(filenameHintWithoutPath) || "").trim(); object.artistName = (file.getMetadata("artist") || "").trim(); object.composerName = (file.getMetadata("composer") || file.getMetadata("TCM") || "").trim(); object.performerName = (file.getMetadata("performer") || "").trim(); object.albumArtistName = (file.getMetadata("album_artist") || "").trim(); object.albumName = (file.getMetadata("album") || "").trim(); object.compilation = !!(parseInt(file.getMetadata("TCP"), 10) || parseInt(file.getMetadata("TCMP"), 10) || file.getMetadata("COMPILATION") || file.getMetadata("Compilation") || file.getMetadata("cpil") || file.getMetadata("WM/IsCompilation")); object.track = parsedTrack.value; object.trackCount = parsedTrack.total; object.disc = parsedDisc.value; object.discCount = parsedDisc.total; object.duration = file.duration(); object.year = parseIntOrNull(file.getMetadata("date")); object.genre = file.getMetadata("genre"); object.replayGainTrackGain = parseFloatOrNull(file.getMetadata("REPLAYGAIN_TRACK_GAIN")); object.replayGainTrackPeak = parseFloatOrNull(file.getMetadata("REPLAYGAIN_TRACK_PEAK")); object.replayGainAlbumGain = parseFloatOrNull(file.getMetadata("REPLAYGAIN_ALBUM_GAIN")); object.replayGainAlbumPeak = parseFloatOrNull(file.getMetadata("REPLAYGAIN_ALBUM_PEAK")); object.labels = {}; return object; } function uniqueFilename(filename) { // break into parts var dirname = path.dirname(filename); var basename = path.basename(filename); var extname = path.extname(filename); var withoutExt = basename.substring(0, basename.length - extname.length); var match = withoutExt.match(/_(\d+)$/); var withoutMatch; var number; if (match) { number = parseInt(match[1], 10); if (!number) number = 0; withoutMatch = withoutExt.substring(0, match.index); } else { number = 0; withoutMatch = withoutExt; } number += 1; // put it back together var newBasename = withoutMatch + "_" + number + extname; return path.join(dirname, newBasename); } function dBToFloat(dB) { return Math.exp(dB * DB_SCALE); } function ensureSep(dir) { return (dir[dir.length - 1] === path.sep) ? dir : (dir + path.sep); } function ensureGrooveVersionIsOk() { var ver = groove.getVersion(); var verStr = ver.major + '.' + ver.minor + '.' + ver.patch; var reqVer = '>=4.1.1'; if (semver.satisfies(verStr, reqVer)) return; log.fatal("Found libgroove", verStr, "need", reqVer); process.exit(1); } function playlistItemKey(playlist, item) { return PLAYLIST_KEY_PREFIX + playlist.id + '.' + item.id; } function playlistKey(playlist) { return PLAYLIST_META_KEY_PREFIX + playlist.id; } function serializePlaylist(playlist) { return JSON.stringify({ id: playlist.id, name: playlist.name, mtime: playlist.mtime, }); } function deserializePlaylist(str) { var playlist = JSON.parse(str); playlist.items = {}; return playlist; } function zfill(number, size) { number = String(number); while (number.length < size) number = "0" + number; return number; } function setGrooveLoggingLevel() { switch (log.level) { case log.levels.Fatal: case log.levels.Error: case log.levels.Info: case log.levels.Warn: groove.setLogging(groove.LOG_QUIET); break; case log.levels.Debug: groove.setLogging(groove.LOG_INFO); break; } } function importFileAsSong(self, srcFullPath, filenameHintWithoutPath, cb) { groove.open(srcFullPath, function(err, file) { if (err) return cb(err); var newDbFile = grooveFileToDbFile(file, filenameHintWithoutPath); var suggestedPath = self.getSuggestedPath(newDbFile, filenameHintWithoutPath); var pend = new Pend(); pend.go(function(cb) { log.debug("importFileAsSong close file:", file.filename); file.close(cb); }); pend.go(function(cb) { tryMv(suggestedPath, cb); }); pend.wait(function(err) { if (err) return cb(err); cb(null, [newDbFile]); }); function tryMv(destRelPath, cb) { var destFullPath = path.join(self.musicDirectory, destRelPath); // before importFileAsSong is called, file system watching is disabled. // So we can safely move files into the library without triggering an // update db. mv(srcFullPath, destFullPath, {mkdirp: true, clobber: false}, function(err) { if (err) { if (err.code === 'EEXIST') { tryMv(uniqueFilename(destRelPath), cb); } else { cb(err); } return; } onAddOrChange(self, destRelPath, (new Date()).getTime(), function(err, dbFile) { if (err) return cb(err); newDbFile = dbFile; cb(); }); }); } }); } function importFileAsZip(self, srcFullPath, filenameHintWithoutPath, cb) { yauzl.open(srcFullPath, function(err, zipfile) { if (err) return cb(err); var allDbFiles = []; var pend = new Pend(); zipfile.on('error', handleError); zipfile.on('entry', onEntry); zipfile.on('end', onEnd); function onEntry(entry) { if (/\/$/.test(entry.fileName)) { // ignore directories return; } pend.go(function(cb) { zipfile.openReadStream(entry, function(err, readStream) { if (err) { log.warn("Error reading zip file:", err.stack); cb(); return; } var entryBaseName = path.basename(entry.fileName); self.importStream(readStream, entryBaseName, entry.uncompressedSize, function(err, dbFiles) { if (err) { log.warn("unable to import entry from zip file:", err.stack); } else if (dbFiles) { allDbFiles = allDbFiles.concat(dbFiles); } cb(); }); }); }); } function onEnd() { pend.wait(function() { unlinkZipFile(); cb(null, allDbFiles); }); } function handleError(err) { unlinkZipFile(); cb(err); } function unlinkZipFile() { fs.unlink(srcFullPath, function(err) { if (err) { log.error("Unable to remove zip file after importing:", err.stack); } }); } }); } // sort keys according to how they appear in the library function sortTracks(tracks) { var lib = new MusicLibraryIndex(); tracks.forEach(function(track) { lib.addTrack(track); }); lib.rebuildTracks(); var results = []; lib.artistList.forEach(function(artist) { artist.albumList.forEach(function(album) { album.trackList.forEach(function(track) { results.push(track); }); }); }); return results; } function logIfDbError(err) { if (err) { log.error("Unable to update DB:", err.stack); } } function makeLower(str) { return str.toLowerCase(); } function copySet(set) { var out = {}; for (var key in set) { out[key] = 1; } return out; }
dwrensha/groovebasin
lib/player.js
JavaScript
mit
88,399
*** View in [[English](README-en.md)][[中文](README.md)] *** # gocaptcha go语言验证码服务器 Feature ------- * 支持中文验证码 * 支持自定义词库、字库 * 支持自定义滤镜机制,通过滤镜来增加干扰,加大识别难度 * 当前的滤镜包括: * 支持干扰点 * 支持干扰线 * 支持其他模式的干扰 * 更多模式,可实现imagefilter接口来扩展 * 支持自定义存储引擎,存储引擎可扩展 * 目前支持的存储引擎包括: * 内置(buildin) * memcache * redis (from https://github.com/dtynn/gocaptcha) * 如需扩展存储引擎,可实现StoreInterface接口 Useage ------ **安装** go get github.com/hanguofeng/gocaptcha **Quick Start** 参考 [captcha_test.go](captcha_test.go) 参考 [samples/gocaptcha-server](samples/gocaptcha-server) [Demo](http://hanguofeng-gocaptcha.daoapp.io/) **文档** [[captcha.go Wiki](https://github.com/hanguofeng/gocaptcha/wiki)] TODO ---- * 运维管理工具 LICENCE ------- gocaptcha使用[[MIT许可协议](LICENSE)] 使用的开源软件列表,表示感谢 * https://github.com/dchest/captcha * https://github.com/golang/freetype * https://github.com/bradfitz/gomemcache * https://code.google.com/p/zpix/
hanguofeng/gocaptcha
README.md
Markdown
mit
1,242
def add_age puts "How old are you?" age = gets.chomp puts "In 10 years you will be:" puts age.to_i + 10 puts "In 20 years you will be:" puts age.to_i + 20 puts "In 30 years you will be:" puts age.to_i + 30 puts "In 40 years you will be:" puts age.to_i + 40 end add_age
poligen/Tealeaf
prep_course/variables/age.rb
Ruby
mit
291
<!DOCTYPE html> <html class="theme-next mist use-motion" lang="zh-Hans"> <head> <meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/> <meta name="theme-color" content="#222"> <meta http-equiv="Cache-Control" content="no-transform" /> <meta http-equiv="Cache-Control" content="no-siteapp" /> <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" /> <link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" /> <link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" /> <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4"> <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4"> <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4"> <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222"> <meta name="keywords" content="Hexo, NexT" /> <meta name="description" content="About technology and about life."> <meta property="og:type" content="website"> <meta property="og:title" content="Ice summer bug&#39;s notes"> <meta property="og:url" content="https://summerbuger.github.io/archives/2016/index.html"> <meta property="og:site_name" content="Ice summer bug&#39;s notes"> <meta property="og:description" content="About technology and about life."> <meta property="og:locale" content="zh-Hans"> <meta name="twitter:card" content="summary"> <meta name="twitter:title" content="Ice summer bug&#39;s notes"> <meta name="twitter:description" content="About technology and about life."> <script type="text/javascript" id="hexo.configurations"> var NexT = window.NexT || {}; var CONFIG = { root: '/', scheme: 'Mist', version: '5.1.4', sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false}, fancybox: true, tabs: true, motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}, duoshuo: { userId: '0', author: '博主' }, algolia: { applicationID: '', apiKey: '', indexName: '', hits: {"per_page":10}, labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"} } }; </script> <link rel="canonical" href="https://summerbuger.github.io/archives/2016/"/> <title>归档 | Ice summer bug's notes</title> </head> <body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans"> <div class="container sidebar-position-left page-archive"> <div class="headband"></div> <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader"> <div class="header-inner"><div class="site-brand-wrapper"> <div class="site-meta "> <div class="custom-logo-site-title"> <a href="/" class="brand" rel="start"> <span class="logo-line-before"><i></i></span> <span class="site-title">Ice summer bug's notes</span> <span class="logo-line-after"><i></i></span> </a> </div> <p class="site-subtitle"></p> </div> <div class="site-nav-toggle"> <button> <span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span> </button> </div> </div> <nav class="site-nav"> <ul id="menu" class="menu"> <li class="menu-item menu-item-home"> <a href="/" rel="section"> <i class="menu-item-icon fa fa-fw fa-home"></i> <br /> 首页 </a> </li> <li class="menu-item menu-item-tags"> <a href="/tags/" rel="section"> <i class="menu-item-icon fa fa-fw fa-tags"></i> <br /> 标签 </a> </li> <li class="menu-item menu-item-categories"> <a href="/categories/" rel="section"> <i class="menu-item-icon fa fa-fw fa-th"></i> <br /> 分类 </a> </li> <li class="menu-item menu-item-archives"> <a href="/archives/" rel="section"> <i class="menu-item-icon fa fa-fw fa-archive"></i> <br /> 归档 </a> </li> </ul> </nav> </div> </header> <main id="main" class="main"> <div class="main-inner"> <div class="content-wrap"> <div id="content" class="content"> <div class="post-block archive"> <div id="posts" class="posts-collapse"> <span class="archive-move-on"></span> <span class="archive-page-counter"> 好! 目前共计 55 篇日志。 继续努力。 </span> <div class="collection-title"> <h1 class="archive-year" id="archive-year-2016">2016</h1> </div> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/12/10/技术/spring/2016-12-10-SpringMvc-@ControllerAdvice/" itemprop="url"> <span itemprop="name">SpringMVC 中的 @ControllerAdvice</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-12-10T21:00:00+08:00" content="2016-12-10" > 12-10 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/12/01/技术/spring/2016-12-01-SpringMVC源码学习-mvc加载过程/" itemprop="url"> <span itemprop="name">SpringMVC源码学习 —— MVC 配置加载过程</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-12-01T21:00:00+08:00" content="2016-12-01" > 12-01 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/10/26/技术/java/2016-10-26-分布式锁/" itemprop="url"> <span itemprop="name">几种分布式锁的实现方式</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-10-26T21:00:00+08:00" content="2016-10-26" > 10-26 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/10/16/技术/mybatis/2016-10-16-mybatis-XMLMapperBuilder/" itemprop="url"> <span itemprop="name">mybatis 中的 Configuration</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-10-16T21:00:00+08:00" content="2016-10-16" > 10-16 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/10/16/技术/mybatis/2016-10-16-mybatis-MapperBuilderAssistant/" itemprop="url"> <span itemprop="name">mybatis 中的 MapperBuilderAssistant</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-10-16T21:00:00+08:00" content="2016-10-16" > 10-16 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/10/16/技术/mybatis/2016-10-16-mybatis-Configuration/" itemprop="url"> <span itemprop="name">mybatis 中的 Configuration</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-10-16T21:00:00+08:00" content="2016-10-16" > 10-16 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/10/16/技术/mybatis/2016-10-16-mybatis-MapperAnnotationBuilder/" itemprop="url"> <span itemprop="name">mybatis 中的 MapperAnnotationBuilder</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-10-16T21:00:00+08:00" content="2016-10-16" > 10-16 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/10/16/技术/mybatis/2016-10-16-mybatis-MapperMethod/" itemprop="url"> <span itemprop="name">mybatis 中的 MapperMethod</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-10-16T21:00:00+08:00" content="2016-10-16" > 10-16 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/09/20/技术/mybatis/2016-09-20-mybatis源码阅读/" itemprop="url"> <span itemprop="name">mybatis 源码阅读(一)</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-09-20T21:00:00+08:00" content="2016-09-20" > 09-20 </time> </div> </header> </article> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h2 class="post-title"> <a class="post-title-link" href="/2016/09/13/技术/java/2016-09-13-CPU占用过高处理过程/" itemprop="url"> <span itemprop="name">线上应用故障排查</span> </a> </h2> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-09-13T21:00:00+08:00" content="2016-09-13" > 09-13 </time> </div> </header> </article> </div> </div> <nav class="pagination"> <span class="page-number current">1</span><a class="page-number" href="/archives/2016/page/2/">2</a><a class="extend next" rel="next" href="/archives/2016/page/2/"><i class="fa fa-angle-right"></i></a> </nav> </div> </div> <div class="sidebar-toggle"> <div class="sidebar-toggle-line-wrap"> <span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span> </div> </div> <aside id="sidebar" class="sidebar"> <div class="sidebar-inner"> <section class="site-overview-wrap sidebar-panel sidebar-panel-active"> <div class="site-overview"> <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"> <img class="site-author-image" itemprop="image" src="/images/headPicture.png" alt="Liam Chen" /> <p class="site-author-name" itemprop="name">Liam Chen</p> <p class="site-description motion-element" itemprop="description">About technology and about life.</p> </div> <nav class="site-state motion-element"> <div class="site-state-item site-state-posts"> <a href="/archives/"> <span class="site-state-item-count">55</span> <span class="site-state-item-name">日志</span> </a> </div> <div class="site-state-item site-state-categories"> <a href="/categories/index.html"> <span class="site-state-item-count">21</span> <span class="site-state-item-name">分类</span> </a> </div> <div class="site-state-item site-state-tags"> <a href="/tags/index.html"> <span class="site-state-item-count">41</span> <span class="site-state-item-name">标签</span> </a> </div> </nav> </div> </section> </div> </aside> </div> </main> <footer id="footer" class="footer"> <div class="footer-inner"> <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span> <span class="with-love"> <i class="fa fa-user"></i> </span> <span class="author" itemprop="copyrightHolder">Liam Chen</span> </div> <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div> <span class="post-meta-divider">|</span> <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div> </div> </footer> <div class="back-to-top"> <i class="fa fa-arrow-up"></i> </div> </div> <script type="text/javascript"> if (Object.prototype.toString.call(window.Promise) !== '[object Function]') { window.Promise = null; } </script> <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script> <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script> <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script> <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script> <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script> <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script> <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script> <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script> <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script> </body> </html>
SummerBuger/summerbuger.github.io
archives/2016/index.html
HTML
mit
17,538
import { stringify } from 'qs' import _request from '@/utils/request' import mini from '@/utils/mini' import env from '@/config/env' // import { modelApis, commonParams } from './model' // import { version } from '../package.json' let apiBaseUrl apiBaseUrl = `${env.apiBaseUrl}` const regHttp = /^https?/i const isMock = true; // const regMock = /^mock?/i function compact(obj) { for (const key in obj) { if (!obj[key]) { delete obj[key] } } return obj } function request(url, options, success, fail) { const originUrl = regHttp.test(url) ? url : `${apiBaseUrl}${url}` return _request(originUrl, compact(options), success, fail) } /** * API 命名规则 * - 使用 camelCase 命名格式(小驼峰命名) * - 命名尽量对应 RESTful 风格,`${动作}${资源}` * - 假数据增加 fake 前缀 * - 便捷易用大于规则,程序是给人看的 */ // api 列表 const modelApis = { // 初始化配置 test: 'https://easy-mock.com/mock/5aa79bf26701e17a67bde1d7/', getConfig: '/common/initconfig', getWxSign: '/common/getwxsign', // 积分兑换 getPointIndex: '/point/index', getPointList: '/point/skulist', getPointDetail: '/point/iteminfo', getPointDetaiMore: '/product/productdetail', getRList: '/point/recommenditems', // 专题 getPointTopicInfo: '/point/topicinfo', getPointTopicList: '/point/topicbuskulist', // 主站专题 getTopicInfo: '/product/topicskusinfo', getTopicList: '/product/topicskulist', // 个人中心 getProfile: '/user/usercenter', // 拼团相关 getCoupleList: '/product/coupleskulist', getCoupleDetail: '/product/coupleskudetail', getMerchantList: '/merchant/coupleskulist', coupleOrderInit: 'POST /order/coupleorderinit', coupleOrderList: '/user/usercouplelist', coupleOrderDetail: '/user/usercoupleorderdetail', coupleUserList: '/market/pinactivitiesuserlist', // 分享页拼团头像列表 coupleShareDetail: '/user/coupleactivitiedetail', // 分享详情 // 首页 getIndex: '/common/index', getIndexNew: '/common/index_v1', getHotSearch: '/common/hotsearchsug', // 主流程 orderInit: 'POST /order/orderinit', orderSubmit: 'POST /order/submitorder', orderPay: 'POST /order/orderpay', orderPayConfirm: '/order/orderpayconfirm', // 确认支付状态 getUserOrders: '/order/getuserorders', // 订单列表 getNeedCommentOrders: '/order/waitcommentlist', // 待评论 getUserRefundorders: '/order/userrefundorder', // 退款 getUserServiceOrders: '/order/userserviceorders', // 售后 orderCancel: 'POST /order/cancelorder', // 取消订单 orderDetail: '/order/orderdetail', confirmReceived: 'POST /order/userorderconfirm', // 确认收货 orderComplaint: 'POST /refund/complaint', // 订单申诉 // 积分订单相关 pointOrderInit: 'POST /tradecenter/pointorderpreview', pointOrderSubmit: 'POST /tradecenter/pointordersubmit', pointOrderCancel: 'POST /tradecenter/ordercancel', pointOrderList: '/tradecenter/orderlist', pointOrderDetail: '/tradecenter/orderinfo', pointOrderSuccess: '/tradecenter/ordersuccess', // 退款相关 refundInit: '/refund/init', refundDetail: '/refund/detail', refundApply: 'POST /refund/apply', // 登录注销 login: 'POST /user/login', logout: 'POST /user/logout', // 地址管理 addressList: '/user/addresslist', addAddress: 'POST /user/addaddress', updateAddress: 'POST /user/updateaddress', setDefaultAddress: 'POST /user/setdefaultaddress', deleteAddress: 'POST /user/deleteaddress', provinceList: '/nation/provincelist', cityList: '/nation/citylist', districtList: '/nation/districtlist', // 查看物流 getDelivery: '/order/deliverymessage', // 获取七牛 token getQiniuToken: '/common/qiniutoken', } // 仅限本地调试支持 // if (__DEV__ && env.mock) { if (__DEV__ && isMock) { apiBaseUrl = `${env.apiMockUrl}` // Object.assign(modelApis, require('../mock')) } // 线上代理 if (__DEV__ && env.proxy) { const proxyUrl = '/proxy' apiBaseUrl = `${env.origin}${proxyUrl}` } const { width, height, } = window.screen // 公共参数 const commonParams = { uuid: '', // 用户唯一标志 udid: '', // 设备唯一标志 device: '', // 设备 net: '', // 网络 uid: '', token: '', timestamp: '', // 时间 channel: 'h5', // 渠道 spm: 'h5', v: env.version, // 系统版本 terminal: env.terminal, // 终端 swidth: width, // 屏幕宽度 分辨率 sheight: height, // 屏幕高度 location: '', // 地理位置 zoneId: 857, // 必须 } // console.log(Object.keys(modelApis)) const apiList = Object.keys(modelApis).reduce((api, key) => { const val = modelApis[key] const [url, methodType = 'GET'] = val.split(/\s+/).reverse() const method = methodType.toUpperCase() // let originUrl = regHttp.test(url) ? url : `${env.apiBaseUrl}${url}`; // NOTE: headers 在此处设置? // if (__DEV__ && regLocalMock.test(url)) { // api[key] = function postRequest(params, success, fail) { // const res = require(`../${url}.json`) // mini.hideLoading() // res.errno === 0 ? success(res) : fail(res) // } // return api // } switch (method) { case 'POST': // originUrl = `${originUrl}`; api[key] = function postRequest(params, success, fail) { return request(url, { headers: { // Accept: 'application/json', // 我们的 post 请求,使用的这个,不是 application/json // 'Content-Type': 'application/x-www-form-urlencoded', }, method, data: compact(Object.assign({}, getCommonParams(), params)), }, success, fail) } break case 'GET': default: api[key] = function getRequest(params, success, fail) { params = compact(Object.assign({}, getCommonParams(), params)) let query = stringify(params) if (query) query = `?${query}` return request(`${url}${query}`, {}, success, fail) } break } return api }, {}) function setCommonParams(params) { return Object.assign(commonParams, params) } function getCommonParams(key) { return key ? commonParams[key] : { // ...commonParams, } } apiList.getCommonParams = getCommonParams apiList.setCommonParams = setCommonParams // console.log(apiList) export default apiList
jskit/kit-start
src/config/api.js
JavaScript
mit
6,364
import m from 'mithril'; import _ from 'underscore'; import postgrest from 'mithril-postgrest'; import models from '../models'; import h from '../h'; import projectDashboardMenu from '../c/project-dashboard-menu'; import projectContributionReportHeader from '../c/project-contribution-report-header'; import projectContributionReportContent from '../c/project-contribution-report-content'; import projectsContributionReportVM from '../vms/projects-contribution-report-vm'; import FilterMain from '../c/filter-main'; import FilterDropdown from '../c/filter-dropdown'; import InfoProjectContributionLegend from '../c/info-project-contribution-legend'; import ProjectContributionStateLegendModal from '../c/project-contribution-state-legend-modal'; import ProjectContributionDeliveryLegendModal from '../c/project-contribution-delivery-legend-modal'; const projectContributionReport = { controller(args) { const listVM = postgrest.paginationVM(models.projectContribution, 'id.desc', { Prefer: 'count=exact' }), filterVM = projectsContributionReportVM, project = m.prop([{}]), rewards = m.prop([]), contributionStateOptions = m.prop([]), reloadSelectOptions = (projectState) => { let opts = [{ value: '', option: 'Todos' }]; const optionsMap = { online: [{ value: 'paid', option: 'Confirmado' }, { value: 'pending', option: 'Iniciado' }, { value: 'refunded,chargeback,deleted,pending_refund', option: 'Contestado' }, ], waiting_funds: [{ value: 'paid', option: 'Confirmado' }, { value: 'pending', option: 'Iniciado' }, { value: 'refunded,chargeback,deleted,pending_refund', option: 'Contestado' }, ], failed: [{ value: 'pending_refund', option: 'Reembolso em andamento' }, { value: 'refunded', option: 'Reembolsado' }, { value: 'paid', option: 'Reembolso não iniciado' }, ], successful: [{ value: 'paid', option: 'Confirmado' }, { value: 'refunded,chargeback,deleted,pending_refund', option: 'Contestado' }, ] }; opts = opts.concat(optionsMap[projectState] || []); contributionStateOptions(opts); }, submit = () => { if (filterVM.reward_id() === 'null') { listVM.firstPage(filterVM.withNullParameters()).then(null); } else { listVM.firstPage(filterVM.parameters()).then(null); } return false; }, filterBuilder = [{ component: FilterMain, data: { inputWrapperClass: '.w-input.text-field', btnClass: '.btn.btn-medium', vm: filterVM.full_text_index, placeholder: 'Busque por nome ou email do apoiador' } }, { label: 'reward_filter', component: FilterDropdown, data: { label: 'Recompensa selecionada', onchange: submit, name: 'reward_id', vm: filterVM.reward_id, wrapper_class: '.w-sub-col.w-col.w-col-4', options: [] } }, { label: 'delivery_filter', component: FilterDropdown, data: { custom_label: [InfoProjectContributionLegend, { content: [ProjectContributionDeliveryLegendModal], text: 'Status da entrega' }], onchange: submit, name: 'delivery_status', vm: filterVM.delivery_status, wrapper_class: '.w-col.w-col-4', options: [{ value: '', option: 'Todos' }, { value: 'undelivered', option: 'Não enviada' }, { value: 'delivered', option: 'Enviada' }, { value: 'error', option: 'Erro no envio' }, { value: 'received', option: 'Recebida' } ] } }, { label: 'payment_state', component: FilterDropdown, data: { custom_label: [InfoProjectContributionLegend, { text: 'Status do apoio', content: [ProjectContributionStateLegendModal, { project }] }], name: 'state', onchange: submit, vm: filterVM.state, wrapper_class: '.w-sub-col.w-col.w-col-4', options: contributionStateOptions } } ]; filterVM.project_id(args.root.getAttribute('data-id')); const lReward = postgrest.loaderWithToken(models.rewardDetail.getPageOptions({ project_id: `eq.${filterVM.project_id()}` })); const lProject = postgrest.loaderWithToken(models.projectDetail.getPageOptions({ project_id: `eq.${filterVM.project_id()}` })); lReward.load().then(rewards); lProject.load().then((data) => { project(data); reloadSelectOptions(_.first(data).state); }); const mapRewardsToOptions = () => { let options = []; if (!lReward()) { options = _.map(rewards(), r => ({ value: r.id, option: `R$ ${h.formatNumber(r.minimum_value, 2, 3)} - ${r.description.substring(0, 20)}` })); } options.unshift({ value: null, option: 'Sem recompensa' }); options.unshift({ value: '', option: 'Todas' }); return options; }; if (!listVM.collection().length) { listVM.firstPage(filterVM.parameters()); } return { listVM, filterVM, filterBuilder, submit, lReward, lProject, rewards, project, mapRewardsToOptions }; }, view(ctrl) { const list = ctrl.listVM; if (!ctrl.lProject()) { return [ m.component(projectDashboardMenu, { project: m.prop(_.first(ctrl.project())) }), m.component(projectContributionReportHeader, { submit: ctrl.submit, filterBuilder: ctrl.filterBuilder, form: ctrl.filterVM.formDescriber, mapRewardsToOptions: ctrl.mapRewardsToOptions, filterVM: ctrl.filterVM }), m('.divider.u-margintop-30'), m.component(projectContributionReportContent, { submit: ctrl.submit, list, filterVM: ctrl.filterVM, project: m.prop(_.first(ctrl.project())) }) ]; } return h.loader(); } }; export default projectContributionReport;
thiagocatarse/catarse.js
src/root/projects-contribution-report.js
JavaScript
mit
8,807
<?php namespace Faker\Provider\fa_IR; class PhoneNumber extends \Faker\Provider\PhoneNumber { /** * @link https://fa.wikipedia.org/wiki/%D8%B4%D9%85%D8%A7%D8%B1%D9%87%E2%80%8C%D9%87%D8%A7%DB%8C_%D8%AA%D9%84%D9%81%D9%86_%D8%AF%D8%B1_%D8%A7%DB%8C%D8%B1%D8%A7%D9%86#.D8.AA.D9.84.D9.81.D9.86.E2.80.8C.D9.87.D8.A7.DB.8C_.D9.87.D9.85.D8.B1.D8.A7.D9.87 */ protected static $formats = array( // land line formts seprated by province "011########", //Mazandaran "013########", //Gilan "017########", //Golestan "021########", //Tehran "023########", //Semnan "024########", //Zanjan "025########", //Qom "026########", //Alborz "028########", //Qazvin "031########", //Isfahan "034########", //Kerman "035########", //Yazd "038########", //Chaharmahal and Bakhtiari "041########", //East Azerbaijan "044########", //West Azerbaijan "045########", //Ardabil "051########", //Razavi Khorasan "054########", //Sistan and Baluchestan "056########", //South Khorasan "058########", //North Khorasan "061########", //Khuzestan "066########", //Lorestan "071########", //Fars "074########", //Kohgiluyeh and Boyer-Ahmad "076########", //Hormozgan "077########", //Bushehr "081########", //Hamadan "083########", //Kermanshah "084########", //Ilam "086########", //Markazi "087########", //Kurdistan ); protected static $mobileNumberPrefixes = array( '0910#######',//mci '0911#######', '0912#######', '0913#######', '0914#######', '0915#######', '0916#######', '0917#######', '0918#######', '0919#######', '0901#######', '0901#######', '0902#######', '0903#######', '0930#######', '0933#######', '0935#######', '0936#######', '0937#######', '0938#######', '0939#######', '0920#######', '0921#######', '0937#######', '0990#######', // MCI ); public static function mobileNumber() { return static::numerify(static::randomElement(static::$mobileNumberPrefixes)); } }
localheinz/Faker
src/Faker/Provider/fa_IR/PhoneNumber.php
PHP
mit
2,348
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { TPromise, Promise } from 'vs/base/common/winjs.base'; import { xhr } from 'vs/base/common/network'; import { IConfigurationRegistry, Extensions } from 'vs/platform/configuration/common/configurationRegistry'; import strings = require('vs/base/common/strings'); import nls = require('vs/nls'); import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import platform = require('vs/platform/platform'); import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { BaseRequestService } from 'vs/platform/request/common/baseRequestService'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { assign } from 'vs/base/common/objects'; import { IXHROptions, IXHRResponse } from 'vs/base/common/http'; import { request } from 'vs/base/node/request'; import { getProxyAgent } from 'vs/base/node/proxy'; import { createGunzip } from 'zlib'; import { Stream } from 'stream'; interface IHTTPConfiguration { http?: { proxy?: string; proxyStrictSSL?: boolean; }; } export class RequestService extends BaseRequestService { private disposables: IDisposable[]; private proxyUrl: string = null; private strictSSL: boolean = true; constructor( @IWorkspaceContextService contextService: IWorkspaceContextService, @IConfigurationService configurationService: IConfigurationService, @ITelemetryService telemetryService?: ITelemetryService ) { super(contextService, telemetryService); this.disposables = []; const config = configurationService.getConfiguration<IHTTPConfiguration>(); this.configure(config); const disposable = configurationService.onDidUpdateConfiguration(e => this.configure(e.config)); this.disposables.push(disposable); } private configure(config: IHTTPConfiguration) { this.proxyUrl = config.http && config.http.proxy; this.strictSSL = config.http && config.http.proxyStrictSSL; } makeRequest(options: IXHROptions): TPromise<IXHRResponse> { let url = options.url; if (!url) { throw new Error('IRequestService.makeRequest: Url is required.'); } // Support file:// in native environment through XHR if (strings.startsWith(url, 'file://')) { return xhr(options).then(null, (xhr: XMLHttpRequest) => { if (xhr.status === 0 && xhr.responseText) { return xhr; // loading resources locally returns a status of 0 which in WinJS is an error so we need to handle it here } return <any>Promise.wrapError({ status: 404, responseText: nls.localize('localFileNotFound', "File not found.")}); }); } return super.makeRequest(options); } protected makeCrossOriginRequest(options: IXHROptions): TPromise<IXHRResponse> { const { proxyUrl, strictSSL } = this; const agent = getProxyAgent(options.url, { proxyUrl, strictSSL }); options = assign({}, options); options = assign(options, { agent, strictSSL }); return request(options).then(result => new TPromise<IXHRResponse>((c, e, p) => { const res = result.res; let stream: Stream = res; if (res.headers['content-encoding'] === 'gzip') { stream = stream.pipe(createGunzip()); } const data: string[] = []; stream.on('data', c => data.push(c)); stream.on('end', () => { const status = res.statusCode; if (options.followRedirects > 0 && (status >= 300 && status <= 303 || status === 307)) { let location = res.headers['location']; if (location) { let newOptions = { type: options.type, url: location, user: options.user, password: options.password, responseType: options.responseType, headers: options.headers, timeout: options.timeout, followRedirects: options.followRedirects - 1, data: options.data }; xhr(newOptions).done(c, e, p); return; } } const response: IXHRResponse = { responseText: data.join(''), status, getResponseHeader: header => res.headers[header], readyState: 4 }; if ((status >= 200 && status < 300) || status === 1223) { c(response); } else { e(response); } }); }, err => { let message: string; if (agent) { message = 'Unable to to connect to ' + options.url + ' through a proxy . Error: ' + err.message; } else { message = 'Unable to to connect to ' + options.url + '. Error: ' + err.message; } return TPromise.wrapError<IXHRResponse>({ responseText: message, status: 404 }); })); } dispose(): void { this.disposables = dispose(this.disposables); } } // Configuration let confRegistry = <IConfigurationRegistry>platform.Registry.as(Extensions.Configuration); confRegistry.registerConfiguration({ id: 'http', order: 15, title: nls.localize('httpConfigurationTitle', "HTTP configuration"), type: 'object', properties: { 'http.proxy': { type: 'string', pattern: '^https?://[^:]+(:\\d+)?$|^$', description: nls.localize('proxy', "The proxy setting to use. If not set will be taken from the http_proxy and https_proxy environment variables") }, 'http.proxyStrictSSL': { type: 'boolean', default: true, description: nls.localize('strictSSL', "Whether the proxy server certificate should be verified against the list of supplied CAs.") } } });
bsmr-x-script/vscode
src/vs/workbench/services/request/node/requestService.ts
TypeScript
mit
5,651
// // IGViewController.h // KaifKit // // Created by Francis Chong on 04/15/2015. // Copyright (c) 2014 Francis Chong. All rights reserved. // #import <UIKit/UIKit.h> @interface IGViewController : UIViewController @end
siuying/KaifKit
Example/KaifKit/IGViewController.h
C
mit
226
version https://git-lfs.github.com/spec/v1 oid sha256:f5c198d5eef0ca0f41f87746ef8fefe819a727fcd59a6477c76b94b55d27128d size 1730
yogeshsaroya/new-cdnjs
ajax/libs/globalize/0.1.1/cultures/globalize.culture.da.js
JavaScript
mit
129
<?php $news = array( array( 'created_at' => '2015-04-29 00:00:00', 'image' => 'http://fakeimg.pl/768x370/3c3c3c/', 'thumb' => 'http://fakeimg.pl/200x200/3c3c3c/', 'title' => 'Blimps to Defend Washington, D.C. Airspace', 'content' => '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque in pulvinar neque. Duis in pharetra purus. Mauris varius porttitor augue in iaculis. Phasellus tincidunt justo magna, eget porta est sagittis quis. Quisque at ante nec dolor euismod elementum sit amet hendrerit nibh. Etiam ut odio tortor. Mauris blandit purus et mauris gravida, eget gravida nulla convallis.</p><p>Vivamus vehicula dignissim malesuada. Donec cursus luctus mi, ac sagittis arcu scelerisque a. Nullam et metus quis sem mollis accumsan. Aenean in sapien pretium, pretium leo eu, ullamcorper sapien. Nulla tempus, metus eu iaculis posuere, ipsum ex faucibus velit, cursus condimentum ligula ex non enim. Aliquam iaculis pellentesque erat molestie feugiat. Morbi ornare maximus rutrum. Pellentesque id euismod erat, eget aliquam massa.</p>' ), array( 'created_at' => '2015-04-26 00:00:00', 'image' => 'http://fakeimg.pl/768x370/3c3c3c/', 'thumb' => 'http://fakeimg.pl/200x200/3c3c3c/', 'title' => 'Eye Receptor Transplants May Restore Eyesight to the Blind', 'content' => '<p>Praesent cursus lobortis dui eu congue. Phasellus pellentesque posuere commodo. Curabitur dignissim placerat sapien, nec egestas ante. Mauris nec commodo est, ac faucibus massa. Nam et dolor at est dignissim condimentum. Quisque consequat tempus aliquam. Mauris consectetur rutrum efficitur.</p><p>Quisque vulputate massa velit, at facilisis turpis euismod id. Pellentesque molestie lectus ut nisl dignissim sagittis. Sed vitae rutrum turpis. Aenean ex est, sagittis vel lectus nec, suscipit condimentum ligula. Ut vitae vehicula lectus. Morbi sit amet cursus arcu. Curabitur quis nunc ultrices, suscipit erat vel, faucibus diam. Sed odio turpis, consequat eu feugiat a, porttitor eget nisl.</p>' ), array( 'created_at' => '2015-04-27 00:00:00', 'image' => 'http://fakeimg.pl/768x370/3c3c3c/', 'thumb' => 'http://fakeimg.pl/200x200/3c3c3c/', 'title' => 'Researchers Look to Tattoos to Monitor Your Sweat', 'content' => '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ultricies malesuada risus, at pretium elit scelerisque in. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vel risus sed leo suscipit tempus vel vel eros. Suspendisse augue elit, tempor a leo tempus, egestas hendrerit leo. Fusce mattis quam magna, ut mattis nulla ultrices at. Etiam sollicitudin tempus placerat. Nulla facilisi. Praesent non porttitor diam, imperdiet volutpat dolor. Pellentesque viverra consectetur auctor. Etiam metus purus, accumsan ac efficitur et, laoreet ut orci. Phasellus rutrum rhoncus lacus a imperdiet. Nam ac scelerisque quam. Donec vitae est pharetra, consequat risus et, maximus odio.</p>' ), ); ?> <?php if ( isset( $news ) ) : ?> <div class="widget widget-featured-news"> <div class="widget-header"> <h3 class="widget-title"> <i class="glyphicon glyphicon-star"></i> Featured News </h3> <!-- /.widget-title --> </div> <!-- /.widget-header --> <div class="widget-content"> <ul class="list-unstyled"> <?php foreach ( $news as $new ) : ?> <li data-title="<?php echo $new['title']; ?>"> <a href="#"> <img alt="<?php echo $new['title']; ?>" class="img-responsive" height="370" src="<?php echo $new['image']; ?>" width="768"> </a> <h2><a href="#"><?php echo $new['title']; ?></a></h2> <div class="article hidden"> <button class="btn btn-close" type="button"><i class="glyphicon glyphicon-remove"></i></button> <p class="h2"><?php echo $new['title']; ?></p> <!-- /.h2 --> <?php echo $new['content']; ?> </div> <!-- /.article hidden --> </li> <?php endforeach; ?> </ul> <!-- /.list-unstyled --> </div> <!-- /.widget-content --> </div> <!-- /.widget widget-featured-news --> <?php endif; ?>
tonimedina/crobo
app/widgets/featured_news.php
PHP
mit
4,331
# Dreedi To start your this app: 1. Install dependencies with `mix deps.get` 2. Create and migrate your database with `mix ecto.create && mix ecto.migrate` 3. Start Phoenix endpoint with `mix phoenix.server` Now you can visit [`localhost:4000`](http://localhost:4000) from your browser.
Dreedi/Dreedi
README.md
Markdown
mit
296
# mpps web repository
pratheep1231kumar/mpps
README.md
Markdown
mit
22
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreatePlatformsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('platforms', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('short_name'); $table->string('slug')->unique(); $table->string('logo'); $table->string('banner'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('platforms'); } }
g33kidd/bracket
database/migrations/2016_05_25_043614_create_platforms_table.php
PHP
mit
703
package nl.ulso.sprox.json.spotify; import nl.ulso.sprox.Node; import java.time.LocalDate; import java.util.List; /** * Sprox processor for Spotify API album data. This is a very simple processor that ignores most data. * <p> * This implementation creates an Artist object for each and every artist in the response. But only the first one on * album level is kept in the end. * </p> */ public class AlbumFactory { @Node("album") public Album createAlbum(@Node("name") String name, @Node("release_date") LocalDate releaseDate, Artist artist, List<Track> tracks) { return new Album(name, releaseDate, artist, tracks); } @Node("artists") public Artist createArtist(@Node("name") String name) { return new Artist(name); } @Node("items") public Track createTrack(@Node("track_number") Integer trackNumber, @Node("name") String name) { return new Track(trackNumber, name); } }
voostindie/sprox-json
src/test/java/nl/ulso/sprox/json/spotify/AlbumFactory.java
Java
mit
972
from corecat.constants import OBJECT_CODES, MODEL_VERSION from ._sqlalchemy import Base, CoreCatBaseMixin from ._sqlalchemy import Column, \ Integer, \ String, Text class Project(CoreCatBaseMixin, Base): """Project Model class represent for the 'projects' table which is used to store project's basic information.""" # Add the real table name here. # TODO: Add the database prefix here __tablename__ = 'project' # Column definition project_id = Column('id', Integer, primary_key=True, autoincrement=True ) project_name = Column('name', String(100), nullable=False ) project_description = Column('description', Text, nullable=True ) # Relationship # TODO: Building relationship def __init__(self, project_name, created_by_user_id, **kwargs): """ Constructor of Project Model Class. :param project_name: Name of the project. :param created_by_user_id: Project is created under this user ID. :param project_description: Description of the project. """ self.set_up_basic_information( MODEL_VERSION[OBJECT_CODES['Project']], created_by_user_id ) self.project_name = project_name self.project_description = kwargs.get('project_description', None)
DanceCats/CoreCat
corecat/models/project.py
Python
mit
1,533
/** * Angular 2 decorators and services */ import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { environment } from 'environments/environment'; import { AppState } from './app.service'; /** * App Component * Top Level Component */ @Component({ selector: 'my-app', encapsulation: ViewEncapsulation.None, template: ` <nav> <a [routerLink]=" ['./'] " routerLinkActive="active" [routerLinkActiveOptions]= "{exact: true}"> Index </a> </nav> <main> <router-outlet></router-outlet> </main> <pre class="app-state">this.appState.state = {{ appState.state | json }}</pre> <footer> <span>Angular Starter by <a [href]="twitter">@gdi2290</a></span> <div> <a [href]="url"> <img [src]="tipe" width="25%"> </a> </div> </footer> ` }) export class AppComponent implements OnInit { public name = 'Angular Starter'; public tipe = 'assets/img/tipe.png'; public twitter = 'https://twitter.com/gdi2290'; public url = 'https://tipe.io'; public showDevModule: boolean = environment.showDevModule; constructor( public appState: AppState ) {} public ngOnInit() { console.log('Initial App State', this.appState.state); } } /** * Please review the https://github.com/AngularClass/angular2-examples/ repo for * more angular app examples that you may copy/paste * (The examples may not be updated as quickly. Please open an issue on github for us to update it) * For help or questions please contact us at @AngularClass on twitter * or our chat on Slack at https://AngularClass.com/slack-join */
hankaibo/myangular
src/app/app.component.ts
TypeScript
mit
1,649
// Copyright (c) 2016-2020 The ZCash developers // Copyright (c) 2020 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. /* See the Zcash protocol specification for more information. https://github.com/zcash/zips/blob/master/protocol/protocol.pdf */ #ifndef ZC_NOTE_ENCRYPTION_H_ #define ZC_NOTE_ENCRYPTION_H_ #include "uint256.h" #include "sapling/address.h" #include "sapling/sapling.h" #include <array> namespace libzcash { // Ciphertext for the recipient to decrypt typedef std::array<unsigned char, ZC_SAPLING_ENCCIPHERTEXT_SIZE> SaplingEncCiphertext; typedef std::array<unsigned char, ZC_SAPLING_ENCPLAINTEXT_SIZE> SaplingEncPlaintext; // Ciphertext for outgoing viewing key to decrypt typedef std::array<unsigned char, ZC_SAPLING_OUTCIPHERTEXT_SIZE> SaplingOutCiphertext; typedef std::array<unsigned char, ZC_SAPLING_OUTPLAINTEXT_SIZE> SaplingOutPlaintext; //! This is not a thread-safe API. class SaplingNoteEncryption { protected: // Ephemeral public key uint256 epk; // Ephemeral secret key uint256 esk; bool already_encrypted_enc; bool already_encrypted_out; SaplingNoteEncryption(uint256 epk, uint256 esk) : epk(epk), esk(esk), already_encrypted_enc(false), already_encrypted_out(false) { } public: static boost::optional<SaplingNoteEncryption> FromDiversifier(diversifier_t d); boost::optional<SaplingEncCiphertext> encrypt_to_recipient( const uint256 &pk_d, const SaplingEncPlaintext &message ); SaplingOutCiphertext encrypt_to_ourselves( const uint256 &ovk, const uint256 &cv, const uint256 &cm, const SaplingOutPlaintext &message ); uint256 get_epk() const { return epk; } uint256 get_esk() const { return esk; } }; // Attempts to decrypt a Sapling note. This will not check that the contents // of the ciphertext are correct. boost::optional<SaplingEncPlaintext> AttemptSaplingEncDecryption( const SaplingEncCiphertext &ciphertext, const uint256 &ivk, const uint256 &epk ); // Attempts to decrypt a Sapling note using outgoing plaintext. // This will not check that the contents of the ciphertext are correct. boost::optional<SaplingEncPlaintext> AttemptSaplingEncDecryption ( const SaplingEncCiphertext &ciphertext, const uint256 &epk, const uint256 &esk, const uint256 &pk_d ); // Attempts to decrypt a Sapling note. This will not check that the contents // of the ciphertext are correct. boost::optional<SaplingOutPlaintext> AttemptSaplingOutDecryption( const SaplingOutCiphertext &ciphertext, const uint256 &ovk, const uint256 &cv, const uint256 &cm, const uint256 &epk ); } #endif /* ZC_NOTE_ENCRYPTION_H_ */
Darknet-Crypto/Darknet
src/sapling/noteencryption.h
C
mit
2,843
import React from 'react'; import { TypeChooser } from 'react-stockcharts/lib/helper' import Chart from './Chart' import { getData } from './util'; class ChartComponent extends React.Component { componentDidMount () { getData().then(data => { this.setState({ data}) }) } render () { if (this.state == null) { return <div> Loading... </div> } return ( <Chart type='hybrid' data={this.state.data} /> ) } } export default ChartComponent;
kevyu/ctp_demo
app/components/Chart/index.js
JavaScript
mit
516