code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
'use strict'; /** * Password based signin and OAuth signin functions. */ var qs = require('querystring'), route = require('koa-route'), parse = require('co-body'), jwt = require('koa-jwt'), request = require('co-request'), config = require('../config/config'), mongo = require('../config/mongo'); // register koa routes exports.init = function (app) { app.use(route.post('/signin', signin)); app.use(route.get('/signin/facebook', facebookSignin)); app.use(route.get('/signin/facebook/callback', facebookCallback)); app.use(route.get('/signin/google', googleSignin)); app.use(route.get('/signin/google/callback', googleCallback)); }; /** * Retrieves the user credentials and returns a JSON Web Token along with user profile info in JSON format. */ function *signin() { var credentials = yield parse(this); var user = yield mongo.users.findOne({email: credentials.email}, {email: 1, name: 1, password: 1}); if (!user) { this.throw(401, 'Incorrect e-mail address.'); } else if (user.password !== credentials.password) { this.throw(401, 'Incorrect password.'); } else { user.id = user._id; delete user._id; delete user.password; user.picture = '/api/users/' + user.id + '/picture'; } // sign and send the token along with the user info var token = jwt.sign(user, config.app.secret, {expiresInMinutes: 90 * 24 * 60 /* 90 days */}); this.body = {token: token, user: user}; } /** * Facebook OAuth 2.0 signin endpoint. */ function *facebookSignin() { this.redirect( 'https://www.facebook.com/dialog/oauth?client_id=' + config.oauth.facebook.clientId + '&redirect_uri=' + config.oauth.facebook.callbackUrl + '&response_type=code&scope=email'); } /** * Facebook OAuth 2.0 callback endpoint. */ function *facebookCallback() { if (this.query.error) { this.redirect('/signin'); return; } // get an access token from facebook in exchange for oauth code var tokenResponse = yield request.get( 'https://graph.facebook.com/oauth/access_token?client_id=' + config.oauth.facebook.clientId + '&redirect_uri=' + config.oauth.facebook.callbackUrl + '&client_secret=' + config.oauth.facebook.clientSecret + '&code=' + this.query.code); var token = qs.parse(tokenResponse.body); if (!token.access_token) { this.redirect('/signin'); return; } // get user profile (including email address) from facebook and save user data in our database if necessary var profileResponse = yield request.get('https://graph.facebook.com/me?fields=name,email,picture&access_token=' + token.access_token); var profile = JSON.parse(profileResponse.body); var user = yield mongo.users.findOne({email: profile.email}, {email: 1, name: 1}); if (!user) { user = { _id: (yield mongo.getNextSequence('userId')), email: profile.email, name: profile.name, picture: (yield request.get(profile.picture.data.url, {encoding: 'base64'})).body }; var results = yield mongo.users.insert(user); } // redirect the user to index page along with user profile object as query string user.id = user._id; delete user._id; user.picture = '/api/users/' + user.id + '/picture'; var token = jwt.sign(user, config.app.secret, {expiresInMinutes: 90 * 24 * 60 /* 90 days */}); this.redirect('/?user=' + encodeURIComponent(JSON.stringify({token: token, user: user}))); } /** * Google OAuth 2.0 signin endpoint. */ function *googleSignin() { this.redirect( 'https://accounts.google.com/o/oauth2/auth?client_id=' + config.oauth.google.clientId + '&redirect_uri=' + config.oauth.google.callbackUrl + '&response_type=code&scope=profile%20email'); } function *googleCallback() { if (this.query.error) { this.redirect('/signin'); return; } // get an access token from google in exchange for oauth code var tokenResponse = yield request.post('https://accounts.google.com/o/oauth2/token', {form: { code: this.query.code, client_id: config.oauth.google.clientId, client_secret: config.oauth.google.clientSecret, redirect_uri: config.oauth.google.callbackUrl, grant_type: 'authorization_code' }}); var token = JSON.parse(tokenResponse.body); if (!token.access_token) { this.redirect('/signin'); return; } // get user profile (including email address) from facebook and save user data in our database if necessary var profileResponse = yield request.get('https://www.googleapis.com/plus/v1/people/me?access_token=' + token.access_token); var profile = JSON.parse(profileResponse.body); var user = yield mongo.users.findOne({email: profile.emails[0].value}, {email: 1, name: 1}); if (!user) { user = { _id: (yield mongo.getNextSequence('userId')), email: profile.emails[0].value, name: profile.displayName, picture: (yield request.get(profile.image.url, {encoding: 'base64'})).body }; var results = yield mongo.users.insert(user); } // redirect the user to index page along with user profile object as query string user.id = user._id; delete user._id; user.picture = '/api/users/' + user.id + '/picture'; var token = jwt.sign(user, config.app.secret, {expiresInMinutes: 90 * 24 * 60 /* 90 days */}); this.redirect('/?user=' + encodeURIComponent(JSON.stringify({token: token, user: user}))); }
nileshlg2003/koan
server/controllers/signin.js
JavaScript
mit
5,541
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-| Briefly, the encryption scheme is a variant of the PBES2 encryption scheme, described in RFC 2898 section 6.2. @ Pass = User-supplied passphrase Salt = 64 bytes of cryptographic salt c = PBKDF2 iteration count DerivedKey = PBKDF2(SHA-512, Pass, Salt, c, 16 + 32) (EncKey, MacKey) = splitAt 16 DerivedKey IV = 0 CipherText = AES-128-CTR(IV, Message, EncKey) MAC = HMAC-SHA-256(MacKey, SHA-256(Salt) + SHA-256(CipherText))) @ The HMAC inputs are hashed before concatenation to avoid leaving "gaps" in the input. Only the derivation parameters and the ciphertext are hashed, to avoid leaking any information about the key material or the plain text. The salt length is set to the output size of the PBKDF2 PRF. TODO: explain why this is done. The HMAC key length is set to the output size of the hash function, the sensible maximum according to RFC 2104. References: * HMAC: Keyed-Hashing for Message Authentication, <https://www.ietf.org/rfc/rfc2104.txt> * PKCS #5: Password-Based Cryptography Specification Version 2.0, <https://www.ietf.org/rfc/rfc2898.txt> -} module Crypto ( getSalt, guessIterCount, encryptAndEncode, decodeAndDecrypt, recrypt, decode, #ifdef TEST encode, encrypt, decrypt, #endif ) where import Control.Applicative ((<$>), (<*>)) import Control.Monad ((>=>)) import Crypto.Hash (SHA256) import Crypto.MAC (HMAC, hmac) import Data.Byteable (toBytes) import qualified Crypto.Cipher.AES as AES import qualified Crypto.Hash.SHA256 as SHA256 import qualified Crypto.PBKDF.ByteString as PBKDF import qualified Data.ByteString.Base64 as Base64 import qualified Data.Serialize as Serialize import Control.Exception (evaluate) import Data.String (fromString) import System.CPUTime (getCPUTime) import qualified Data.ByteString as SB import qualified Data.ByteString.Lazy as LB ------------------------------------------------------------------------ -- Global constants kEncKeyLen, kMacKeyLen, kPrfOutLen :: Int kEncKeyLen = 16 -- encryption key length, in octets kMacKeyLen = 32 -- MAC key length, in octets kPrfOutLen = 64 -- PBKDF2 hash output size, in octets ------------------------------------------------------------------------ -- Tuning parameters guessIterCount :: Double -> IO Int guessIterCount targetSecs = do salt <- getSalt let pass = fromString "Pass" loop !z = do t0 <- getCPUTime _ <- evaluate (kdf pass salt z) t1 <- getCPUTime if (fromIntegral (t1 - t0) * 1e-12) >= targetSecs then return z else loop (z + 1000) loop 0 ------------------------------------------------------------------------ -- High-level interface -- | Update passphrase and encryption parameters. recrypt :: SB.ByteString -- ^ Original passphrase -> SB.ByteString -- ^ New passphrase -> SB.ByteString -- ^ New salt -> Int -- ^ New iteration count -> SB.ByteString -- ^ Original encoded ciphertext -> Either String SB.ByteString -- ^ Either error or new encoded ciphertext recrypt origPass newPass newSalt newIter etxt = do (salt, c, mac, txt) <- decode etxt msg <- decrypt origPass salt c mac txt return $! encryptAndEncode newPass newSalt newIter msg -- | Encrypt the input message and return a base64 encoded string containing -- the encryption parameters along with the ciphertext. encryptAndEncode :: SB.ByteString -- ^ Passphrase -> SB.ByteString -- ^ Salt -> Int -- ^ c -> SB.ByteString -- ^ Message -> SB.ByteString -- ^ Encoded ciphertext encryptAndEncode pass salt c = uncurry (encode salt c) . encrypt pass salt c -- | The inverse of 'encryptAndEncode'. decodeAndDecrypt :: SB.ByteString -- ^ Passphrase -> SB.ByteString -- ^ Encoded ciphertext -> Either String SB.ByteString -- ^ Either an error or original plaintext decodeAndDecrypt pass etxt = do (salt, c, mac, txt) <- decode etxt decrypt pass salt c mac txt ------------------------------------------------------------------------ -- Serialization encode :: SB.ByteString -- ^ Salt -> Int -- ^ c -> SB.ByteString -- ^ MAC -> SB.ByteString -- ^ Ciphertext -> SB.ByteString -- ^ @Base64 (c + Salt + MAC + Ciphertext)@ encode salt c mac txt = Base64.encode . Serialize.runPut $ do Serialize.putWord16le (fromIntegral c) Serialize.putByteString (SB.concat [ salt, mac, txt ]) decode :: SB.ByteString -> Either String (SB.ByteString, Int, SB.ByteString, SB.ByteString) -- ^ Either error or @(Salt, c, MAC, Ciphertext)@. decode = Base64.decode >=> Serialize.runGet (do c <- fromIntegral <$> Serialize.getWord16le s <- Serialize.getByteString kPrfOutLen m <- Serialize.getByteString kMacKeyLen e <- Serialize.getByteString =<< Serialize.remaining return (s, c, m, e)) ------------------------------------------------------------------------ -- Encryption and decryption encrypt :: SB.ByteString -- ^ Passphrase -> SB.ByteString -- ^ Salt -> Int -- ^ Iteration count -> SB.ByteString -- ^ Message -> (SB.ByteString, SB.ByteString) -- ^ @(MAC, Ciphertext)@ encrypt pass salt c plain = let (ekey, hkey) = kdf pass salt c ctx = AES.initAES ekey txt = AES.encryptCTR ctx kNONCE plain mac = hmac256 hkey (sha256 salt `SB.append` sha256 txt) in (mac, txt) decrypt :: SB.ByteString -- ^ Passphrase -> SB.ByteString -- ^ Salt -> Int -- ^ Iteration count -> SB.ByteString -- ^ MAC -> SB.ByteString -- ^ Ciphertext -> Either String SB.ByteString -- ^ Error message or plaintext decrypt pass salt c mac' txt = let (ekey, hkey) = kdf pass salt c ctx = AES.initAES ekey mac = hmac256 hkey (sha256 salt `SB.append` sha256 txt) in if mac' == mac then Right (AES.decryptCTR ctx kNONCE txt) else Left "MAC mismatch" kNONCE :: SB.ByteString kNONCE = SB.pack [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0] ------------------------------------------------------------------------ -- Cryptographic salt getSalt :: IO SB.ByteString getSalt = (LB.toStrict . LB.take (fromIntegral kPrfOutLen)) <$> LB.readFile "/dev/urandom" ------------------------------------------------------------------------ -- Key derivation kdf :: SB.ByteString -> SB.ByteString -> Int -> (SB.ByteString, SB.ByteString) kdf pass salt c = SB.splitAt kEncKeyLen (PBKDF.sha512PBKDF2 pass salt c (kEncKeyLen + kMacKeyLen)) ------------------------------------------------------------------------ -- Internals sha256 :: SB.ByteString -> SB.ByteString sha256 = SHA256.hash hmac256 :: SB.ByteString -> SB.ByteString -> SB.ByteString hmac256 s m = toBytes (hmac s m :: HMAC SHA256)
joachifm/pwcrypt
src/Crypto.hs
Haskell
mit
6,792
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Raectangle Area</title> <link href="../styles/js-console.css" rel="stylesheet" /> </head> <body> <div id="mainHeader"> <label for="tb-range-start">X = </label> <input type="text" placeholder="Enter point X" id="tb-range-start" /> <label for="tb-range-second">Y = </label> <input type="text" placeholder="Enter point Y" id="tb-range-second" /> <a href="#" id="btn-power" onclick="pointInTheCircle()">Proceed</a> </div> <div id="js-console"> </div> <script src="../scripts/js-console.js"> </script> <script src="InTheCircleOutsideRaectangle.js"> </script> </body> </html>
adachenski/JavaScript-Homeworks
OperatorsAndExpressions/InTheCircleOutsideRaectangle/PointInInTheCircleOutsideRaectangle.html
HTML
mit
727
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Lab2PassedOrFailed")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Lab2PassedOrFailed")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e8b901ca-c941-45c3-afb7-4e3a040d854c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
DenicaAtanasova/02.TechModule
01. Programming Fundamentals/Lesson2ConditionsAndLoops/Lab2PassedOrFailed/Properties/AssemblyInfo.cs
C#
mit
1,407
import { I18N } from "../../src/i18n"; import { BindingSignaler } from "aurelia-templating-resources"; import { NfValueConverter } from "../../src/nf/nf-value-converter"; import { EventAggregator } from "aurelia-event-aggregator"; describe("nfvalueconverter tests", () => { let sut: I18N; let nfvc: NfValueConverter; beforeEach(() => { sut = new I18N(new EventAggregator(), new BindingSignaler()); nfvc = new NfValueConverter(sut); sut.setup({ lng: "en", fallbackLng: "en", debug: false }); }); it("should display number in the setup locale format by default", () => { const testNumber = 123456.789; expect(nfvc.toView(testNumber)).toEqual("123,456.789"); }); it("should display number in the previously modified locale", async () => { const testNumber = 123456.789; await sut.setLocale("de"); expect(nfvc.toView(testNumber)).toEqual("123.456,789"); }); it("should return undefined if undefined value given", () => { const val = undefined; expect(nfvc.toView(val)).toBe(undefined); }); it("should return null if null value given", () => { const val = null; expect(nfvc.toView(val)).toBe(null); }); it("should return empty string if empty string value given", () => { const val = ""; expect(nfvc.toView(val)).toBe(""); }); it("should display number as currency", () => { const testNumber = 123456.789; expect(nfvc.toView(testNumber, { style: "currency", currency: "JPY" }, "de")).toBe("123.457 ¥"); }); });
aurelia/i18n
test/unit/nfvalueconverter.spec.ts
TypeScript
mit
1,542
/** * Plural rules for the fi (Finnish, suomi, suomen kieli) language * * This plural file is generated from CLDR-DATA * (http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html) * using js-simple-plurals and universal-i18n * * @param {number} p * @return {number} 0 - one, 1 - other * * @example * function pluralize_en(number, one, many) { * var rules = [one, many]; * var position = plural.en(number) * return rules[position]; * } * * console.log('2 ' + pluralize_en(2, 'day', 'days')); // prints '2 days' */ plural = window.plural || {}; plural.fi = function (p) { var n = Math.abs(p)||0, i = Math.floor(n,10)||0, v = ((p+'').split('.')[1]||'').length; return i === 1 && v === 0 ? 0 : 1; };
megahertz/js-simple-plurals
web/fi.js
JavaScript
mit
750
package controller; import javafx.scene.Node; import javafx.scene.input.KeyCode; import javafx.scene.input.MouseButton; import javafx.stage.Stage; import model.FileManager; import model.FileManagerInterface; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.testfx.api.FxToolkit; import org.testfx.framework.junit.ApplicationTest; import utils.TestUtils; import java.io.FileNotFoundException; import java.util.concurrent.TimeoutException; import static org.junit.Assert.assertEquals; /** * Created by SH on 2016-06-04. */ public class TabPaneSceneControllerTest extends ApplicationTest { private Stage s; private Node leftSplit, rightSplit; private HighlightEditorInterface leftEditor, rightEditor; @Override public void init() throws Exception { FxToolkit.registerStage(Stage::new); } @Override public void start(Stage stage) { s = TestUtils.startStage(stage); if( s.getScene() != null ) { leftSplit = s.getScene().lookup("#leftSplit"); rightSplit = s.getScene().lookup("#rightSplit"); leftEditor = (HighlightEditorController)leftSplit.lookup("#editor"); rightEditor = (HighlightEditorController)rightSplit.lookup("#editor"); } } @Override public void stop() throws Exception { FxToolkit.hideStage(); FxToolkit.cleanupStages(); } @Before public void setUp() throws TimeoutException { FxToolkit.registerPrimaryStage(); } @Test public void TabPaneSceneBothSideLoadTest() throws FileNotFoundException{ String leftFile = getClass().getResource("../test1-1.txt").getPath(); String rightFile = getClass().getResource("../test1-2.txt").getPath(); FileManager.getFileManagerInterface().loadFile(leftFile, FileManagerInterface.SideOfEditor.Left); FileManager.getFileManagerInterface().loadFile(rightFile, FileManagerInterface.SideOfEditor.Right); assertEquals( FileManager.getFileManagerInterface().getString(FileManagerInterface.SideOfEditor.Left), "a\nb\nc\nd\ne\nc\n\ne\nd\nd\ne\nd\nc\n\nd\nd\nd\nd\nd" ); assertEquals( FileManager.getFileManagerInterface().getString(FileManagerInterface.SideOfEditor.Right), "e\nb\nc\nd\ne\nc\n\ne\nd\nd\ne\nd\nc\n\nd\nd\nd\nd\ne" ); } @Test public void TabPaneSceneSplitPaneDragTest(){ Node divider = find(".split-pane-divider"); drag(divider).moveBy(-1000, 0); assertEquals(300, find("#leftSplit").getLayoutBounds().getWidth(), 10); drag(divider).moveBy(1000, 0); assertEquals(300, find("#rightSplit").getLayoutBounds().getWidth(), 10); } @After public void tearDown() throws TimeoutException { FxToolkit.cleanupStages(); FxToolkit.hideStage(); release(new KeyCode[] {}); release(new MouseButton[] {}); } private <T extends Node> T find(final String query) { return lookup(query).query(); } }
leesnhyun/SE2016
src/test/java/controller/TabPaneSceneControllerTest.java
Java
mit
3,085
using Microsoft.SharePoint.Client.NetCore.Runtime; using System; using System.ComponentModel; namespace Microsoft.SharePoint.Client.NetCore { [ScriptType("SP.EventReceiverDefinition", ServerTypeId = "{a8d3515c-1135-4fff-95a6-4e5e5fff4adc}")] public sealed class EventReceiverDefinition : ClientObject { [Remote] public string ReceiverAssembly { get { base.CheckUninitializedProperty("ReceiverAssembly"); return (string)base.ObjectData.Properties["ReceiverAssembly"]; } } [Remote] public string ReceiverClass { get { base.CheckUninitializedProperty("ReceiverClass"); return (string)base.ObjectData.Properties["ReceiverClass"]; } } [Remote] public Guid ReceiverId { get { base.CheckUninitializedProperty("ReceiverId"); return (Guid)base.ObjectData.Properties["ReceiverId"]; } } [Remote] public string ReceiverName { get { base.CheckUninitializedProperty("ReceiverName"); return (string)base.ObjectData.Properties["ReceiverName"]; } } [Remote] public int SequenceNumber { get { base.CheckUninitializedProperty("SequenceNumber"); return (int)base.ObjectData.Properties["SequenceNumber"]; } } [Remote] public EventReceiverSynchronization Synchronization { get { base.CheckUninitializedProperty("Synchronization"); return (EventReceiverSynchronization)base.ObjectData.Properties["Synchronization"]; } } [Remote] public EventReceiverType EventType { get { base.CheckUninitializedProperty("EventType"); return (EventReceiverType)base.ObjectData.Properties["EventType"]; } } [Remote] public string ReceiverUrl { get { base.CheckUninitializedProperty("ReceiverUrl"); return (string)base.ObjectData.Properties["ReceiverUrl"]; } } [EditorBrowsable(EditorBrowsableState.Never)] public EventReceiverDefinition(ClientRuntimeContext context, ObjectPath objectPath) : base(context, objectPath) { } protected override bool InitOnePropertyFromJson(string peekedName, JsonReader reader) { bool flag = base.InitOnePropertyFromJson(peekedName, reader); if (flag) { return flag; } switch (peekedName) { case "ReceiverAssembly": flag = true; reader.ReadName(); base.ObjectData.Properties["ReceiverAssembly"] = reader.ReadString(); break; case "ReceiverClass": flag = true; reader.ReadName(); base.ObjectData.Properties["ReceiverClass"] = reader.ReadString(); break; case "ReceiverId": flag = true; reader.ReadName(); base.ObjectData.Properties["ReceiverId"] = reader.ReadGuid(); break; case "ReceiverName": flag = true; reader.ReadName(); base.ObjectData.Properties["ReceiverName"] = reader.ReadString(); break; case "SequenceNumber": flag = true; reader.ReadName(); base.ObjectData.Properties["SequenceNumber"] = reader.ReadInt32(); break; case "Synchronization": flag = true; reader.ReadName(); base.ObjectData.Properties["Synchronization"] = reader.ReadEnum<EventReceiverSynchronization>(); break; case "EventType": flag = true; reader.ReadName(); base.ObjectData.Properties["EventType"] = reader.ReadEnum<EventReceiverType>(); break; case "ReceiverUrl": flag = true; reader.ReadName(); base.ObjectData.Properties["ReceiverUrl"] = reader.ReadString(); break; } return flag; } [Remote] public void Update() { ClientRuntimeContext context = base.Context; ClientAction query = new ClientActionInvokeMethod(this, "Update", null); context.AddQuery(query); } [Remote] public void DeleteObject() { ClientRuntimeContext context = base.Context; ClientAction query = new ClientActionInvokeMethod(this, "DeleteObject", null); context.AddQuery(query); base.RemoveFromParentCollection(); } } }
OneBitSoftware/NetCore.CSOM
Microsoft.SharePoint.Client.NetCore/EventReceiverDefinition.cs
C#
mit
5,375
from functools import wraps import os from flask import request from werkzeug.utils import redirect ssl_required_flag = os.environ.get('SSL_REQUIRED', False) == 'True' def ssl_required(fn): @wraps(fn) def decorated_view(*args, **kwargs): if ssl_required_flag and not request.is_secure: return redirect(request.url.replace("http://", "https://")) return fn(*args, **kwargs) return decorated_view
hectorbenitez/flask-heroku
flas/decorators.py
Python
mit
408
using System; using System.Collections.Generic; using System.Web.UI; using System.Xml; namespace RSSFeed { public partial class RssView : Page { protected void Page_Load(object sender, EventArgs e) { BindRssRepeater(); } private void BindRssRepeater() { const string rssFeedUrl = "https://www.readability.com/rseero/latest/feed"; try { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(rssFeedUrl); if (xmlDocument.DocumentElement != null) { List<Feed> feedList = new List<Feed>(); XmlNodeList nodeList = xmlDocument.DocumentElement.SelectNodes("/rss/channel/item"); if (nodeList != null) { foreach (XmlNode xmlNode in nodeList) { Feed feed = new Feed(); feed.Title = xmlNode.SelectSingleNode("title") == null ? string.Empty : xmlNode.SelectSingleNode("title").InnerText; feed.Link = xmlNode.SelectSingleNode("link") == null ? string.Empty : xmlNode.SelectSingleNode("link").InnerText; feed.PublishDate = xmlNode.SelectSingleNode("pubDate") == null ? string.Empty : xmlNode.SelectSingleNode("pubDate").InnerText.Substring(0, xmlNode.SelectSingleNode("pubDate").InnerText.Length - 5); feed.Description = xmlNode.SelectSingleNode("description") == null ? string.Empty : xmlNode.SelectSingleNode("description").InnerText; feedList.Add(feed); } } else { errorLabel.Text = "Failed to load RSS feed"; } rssRepeater.DataSource = feedList; rssRepeater.DataBind(); } else { errorLabel.Text = "Failed to load RSS feed"; } } catch (Exception ex) { errorLabel.Text = String.Format("Failed to populate RSS feed, exception: {0}", ex.Message); } } } }
dsjomina/RSSFeed
RSSFeed/RSSFeed/RssView.aspx.cs
C#
mit
2,341
/*global Ghetto*/ (function ($) { $('div').on('click', '.save-button', function (e) { var id = $(this).attr('data-id'); //trim genre off the end of id (it was there for uniqueness on the page) id = id.substring(0, id.indexOf('_')); $('[id^=save-button-div-' + id + ']').collapse('hide'); $('[id^=watched-buttons-' + id + ']').collapse('show'); }); $('.delete-btn').click(function (e) { e.preventDefault(); var id = $(this).attr('data-id'); if (!id) { return; } var req = { url: '/api/user/removeMovie', method: 'POST', contentType: 'application/json', data: JSON.stringify({ id: id }) }; $.ajax(req).then(function (res) { if (res.success === true) { $('.movie-' + id).collapse('hide'); Ghetto.alert('Movie deleted!'); } else { Ghetto.alert(res.error, { level: 'danger' }); } }); }); $('div').on('click', '.watched-btn', function (e) { var id = $(this).attr('data-id'); var state = $(this).attr('data-state'); //trim genre off the end of id (it was there for uniqueness on the page) id = id.substring(0, id.indexOf('_')); var request = { url: '/api/user/watchMovie/' + id, method: 'POST', contentType: 'application/json', data: JSON.stringify({ state: state }) }; $.ajax(request).then(function (response) { if (!response.err) { $('[id^=watched-buttons-' + id + ']').collapse('hide'); if (state == 2) { $('[id^=movie-panel-' + id + ']').unbind('mouseleave mouseenter'); $('[id^=rate-' + id + ']').collapse('show'); } else { $('.save-button[data-id^="' + id + '"]').attr('disabled', 'disabled'); $('[id^=save-button-div-' + id + ']').collapse('show'); } } else { console.log(response.err); } }); }); $('.featured .btn').click( function (e) { e.preventDefault(); var mid = $(this).attr('data-id'); var request = { url: '/movies/my/feature/' + mid, method: 'POST', contentType: 'application/json', data: JSON.stringify({}) }; $.ajax(request).then(function (response) { if(response.err) { console.log(response.err); Ghetto.alert(response.err, { level: 'danger' }); } else { Ghetto.alert('Featured movie saved!'); } }); }); $('.save-rating-btn').click(function (e) { var id = $(this).attr('data-id'); var rating = parseInt($('#rating-' + id).val()); //trim genre off the end of id (it was there for uniqueness on the page) id = id.substring(0, id.indexOf('_')); if (rating) { var request = { url: '/api/movies/' + id + '/vote', method: 'POST', contentType: 'application/json', data: JSON.stringify({ rating: rating }) }; $.ajax(request).then(function (response) { resetButtons(id); }); } }); $('.cancel-rating-btn').click(function (e) { var id = $(this).attr('data-id'); resetButtons(id); }); function resetButtons (id) { // Reset buttons and re-attach event handler $('[id^=rate-' + id + ']').collapse('hide'); $('.save-button[data-id^="' + id + '"]').attr('disabled', 'disabled'); $('[id^=save-button-div-' + id + ']').collapse('show'); $('[id^=movie-panel-' + id + ']').bind('mouseenter', function () { $(this).find('.movie-panel-overlay').finish(); $(this).find('.movie-panel-overlay').fadeIn(150); }).bind('mouseleave', function () { $(this).find('.movie-panel-overlay').fadeOut(150); }); } $('h2').on('click', '.btn-collapse', function (e) { if (this.dataset.expanded === 'true') { $(this).animate({ rotateAmount: -90 }, { step: function (now, fx) { $(this).css('transform', 'rotate(' + now + 'deg)'); }, duration: 150 }); this.dataset.expanded = false; } else { $(this).animate({ rotateAmount: 0 }, { step: function (now, fx) { $(this).css('transform', 'rotate(' + now + 'deg)'); }, duration: 150 }); this.dataset.expanded = true; } }); // For every <li><a href=[path]></a></li>, if the path is equal to the current // browser location, give the anchor the 'active' class so it is properly // highlighted by bootstrap $('.navbar .navbar-nav li').each(function (_, li) { if (li.children instanceof HTMLCollection && li.children.length > 0) { $(li.children).each(function (_, child) { if (child.href === document.location.href.split('#')[0]) { li.classList.add('active'); } }); } }); // Display overlay when the user hovers over a movie panel $('.movie-panel').on('mouseenter', function () { $(this).find('.movie-panel-overlay').finish(); $(this).find('.movie-panel-overlay').fadeIn(150); }).on('mouseleave', function () { $(this).find('.movie-panel-overlay').fadeOut(150); }); // Why do I need to specify this hook? I'm not sure -- maybe because // bootstrap = dick $('.input-group').on('focus', '.form-control', function () { $(this).closest('.form-group, .input-group').addClass('focus'); }).on('blur', '.form-control', function () { $(this).closest('.form-group, .input-group').removeClass('focus'); }); })(window.jQuery);
jajmo/Ghetto-IMDB
static/js/movies.js
JavaScript
mit
6,246
'use strict'; var fs = require( 'fs' ); var path = require( 'path' ); var readlineSync = require( 'readline-sync' ); require( 'plus_arrays' ); require( 'colors' ); var freqTable = require( './freqTable' ); function annotateRandomSample( inputFile, options ) { // if path is not absolute, make it absolute with respect to dirname if ( path.resolve( inputFile ) !== path.normalize( inputFile ) ) { inputFile = path.normalize(__dirname + '/../' + inputFile); } var input = require(inputFile); if ( options.output === undefined ){ throw new TypeError( 'Invalid argument for --output. Must provide a file name. Value: `' + options.output + '`.' ); } if ( options.categories === undefined ) { throw new TypeError('Invalid argument for --categories. Must provide a space-separated list of categories. Value: `' + options.categories + '`.' ); } var categories = options.categories.split(' '); var result = input.map(function( elem, index ) { var o = {}; o.text = elem; console.log('DOCUMENT ' + index + ':'); console.log(elem.green.bold); console.log('CATEGORIES:'); console.log(categories.map(function(e,i){ return i + ':' + e; }).join('\t')); console.log('Please enter correct category:'.grey); var chosenCategories = []; function isSelection(e, i) { return selection.contains(i) === true; } while ( chosenCategories.length === 0 ) { var selection = readlineSync.question('CHOICE(S):'.white.inverse + ': ').split(' '); chosenCategories = categories.filter(isSelection); if ( chosenCategories.length === 0){ console.log('Not a valid input. Try again.'); } } o.categories = chosenCategories; return o; }); fs.writeFileSync(options.output, JSON.stringify(result) ); var table = freqTable( result, categories ); console.log(table); } module.exports = exports = annotateRandomSample;
Planeshifter/node-wordnetify-sample
lib/annotateRandomSample.js
JavaScript
mit
1,860
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="nl"> <head> <!-- Generated by javadoc (1.8.0_51) on Fri Jan 13 16:45:46 CET 2017 --> <title>com.xml2j.tutorial.choice.application</title> <meta name="date" content="2017-01-13"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <h1 class="bar"><a href="../../../../../com/xml2j/tutorial/choice/application/package-summary.html" target="classFrame">com.xml2j.tutorial.choice.application</a></h1> <div class="indexContainer"> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="ChoiceApplication.html" title="class in com.xml2j.tutorial.choice.application" target="classFrame">ChoiceApplication</a></li> <li><a href="ChoiceApplicationTask.html" title="class in com.xml2j.tutorial.choice.application" target="classFrame">ChoiceApplicationTask</a></li> </ul> </div> </body> </html>
lolkedijkstra/xml2j-gen
tutorial/choice/docs/com/xml2j/tutorial/choice/application/package-frame.html
HTML
mit
1,053
<?php /* [UCenter] (C)2001-2099 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: user.php 1078 2011-03-30 02:00:29Z monkey $ */ !defined('IN_UC') && exit('Access Denied'); class usermodel { var $db; var $base; function __construct(&$base) { $this->usermodel($base); } function usermodel(&$base) { $this->base = $base; $this->db = $base->db; } function get_user_by_uid($uid) { $arr = $this->db->fetch_first("SELECT * FROM " . UC_DBTABLEPRE . "members WHERE uid='$uid'"); return $arr; } function get_user_by_email($email) { $arr = $this->db->fetch_first("SELECT * FROM " . UC_DBTABLEPRE . "members WHERE email='$email'"); return $arr; } function check_username($username) { $guestexp = '\xA1\xA1|\xAC\xA3|^Guest|^\xD3\xCE\xBF\xCD|\xB9\x43\xAB\xC8'; $len = $this->dstrlen($username); if ($len > 15 || $len < 3 || preg_match("/\s+|^c:\\con\\con|[%,\*\"\s\<\>\&]|$guestexp/is", $username)) { return FALSE; } else { return TRUE; } } function dstrlen($str) { if (strtolower(UC_CHARSET) != 'utf-8') { return strlen($str); } $count = 0; for ($i = 0; $i < strlen($str); $i++) { $value = ord($str[$i]); if ($value > 127) { $count++; if ($value >= 192 && $value <= 223) $i++; elseif ($value >= 224 && $value <= 239) $i = $i + 2; elseif ($value >= 240 && $value <= 247) $i = $i + 3; } $count++; } return $count; } function check_mergeuser($username) { $data = $this->db->result_first("SELECT count(*) FROM " . UC_DBTABLEPRE . "mergemembers WHERE appid='" . $this->base->app['appid'] . "' AND username='$username'"); return $data; } function check_usernamecensor($username) { $_CACHE['badwords'] = $this->base->cache('badwords'); $censorusername = $this->base->get_setting('censorusername'); $censorusername = $censorusername['censorusername']; $censorexp = '/^(' . str_replace(array('\\*', "\r\n", ' '), array('.*', '|', ''), preg_quote(($censorusername = trim($censorusername)), '/')) . ')$/i'; $usernamereplaced = isset($_CACHE['badwords']['findpattern']) && !empty($_CACHE['badwords']['findpattern']) ? @preg_replace($_CACHE['badwords']['findpattern'], $_CACHE['badwords']['replace'], $username) : $username; if (($usernamereplaced != $username) || ($censorusername && preg_match($censorexp, $username))) { return FALSE; } else { return TRUE; } } function check_usernameexists($username) { $data = $this->db->result_first("SELECT username FROM " . UC_DBTABLEPRE . "members WHERE username='$username'"); return $data; } function check_emailformat($email) { return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email); } function check_emailaccess($email) { $setting = $this->base->get_setting(array('accessemail', 'censoremail')); $accessemail = $setting['accessemail']; $censoremail = $setting['censoremail']; $accessexp = '/(' . str_replace("\r\n", '|', preg_quote(trim($accessemail), '/')) . ')$/i'; $censorexp = '/(' . str_replace("\r\n", '|', preg_quote(trim($censoremail), '/')) . ')$/i'; if ($accessemail || $censoremail) { if (($accessemail && !preg_match($accessexp, $email)) || ($censoremail && preg_match($censorexp, $email))) { return FALSE; } else { return TRUE; } } else { return TRUE; } } function check_emailexists($email, $username = '') { $sqladd = $username !== '' ? "AND username<>'$username'" : ''; $email = $this->db->result_first("SELECT email FROM " . UC_DBTABLEPRE . "members WHERE email='$email' $sqladd"); return $email; } function check_login($username, $password, &$user) { $user = $this->get_user_by_username($username); if (empty($user['username'])) { return -1; } elseif ($user['password'] != md5(md5($password) . $user['salt'])) { return -2; } return $user['uid']; } function get_user_by_username($username) { $arr = $this->db->fetch_first("SELECT * FROM " . UC_DBTABLEPRE . "members WHERE username='$username'"); return $arr; } function add_user($username, $password, $email, $uid = 0, $questionid = '', $answer = '', $regip = '') { $regip = empty($regip) ? $this->base->onlineip : $regip; $salt = substr(uniqid(rand()), -6); $password = md5(md5($password) . $salt); $sqladd = $uid ? "uid='" . intval($uid) . "'," : ''; $sqladd .= $questionid > 0 ? " secques='" . $this->quescrypt($questionid, $answer) . "'," : " secques='',"; $this->db->query("INSERT INTO " . UC_DBTABLEPRE . "members SET $sqladd username='$username', password='$password', email='$email', regip='$regip', regdate='" . $this->base->time . "', salt='$salt'"); $uid = $this->db->insert_id(); $this->db->query("INSERT INTO " . UC_DBTABLEPRE . "memberfields SET uid='$uid'"); return $uid; } function quescrypt($questionid, $answer) { return $questionid > 0 && $answer != '' ? substr(md5($answer . md5($questionid)), 16, 8) : ''; } function edit_user($username, $oldpw, $newpw, $email, $ignoreoldpw = 0, $questionid = '', $answer = '') { $data = $this->db->fetch_first("SELECT username, uid, password, salt FROM " . UC_DBTABLEPRE . "members WHERE username='$username'"); if ($ignoreoldpw) { $isprotected = $this->db->result_first("SELECT COUNT(*) FROM " . UC_DBTABLEPRE . "protectedmembers WHERE uid = '$data[uid]'"); if ($isprotected) { return -8; } } if (!$ignoreoldpw && $data['password'] != md5(md5($oldpw) . $data['salt'])) { return -1; } $sqladd = $newpw ? "password='" . md5(md5($newpw) . $data['salt']) . "'" : ''; $sqladd .= $email ? ($sqladd ? ',' : '') . " email='$email'" : ''; if ($questionid !== '') { if ($questionid > 0) { $sqladd .= ($sqladd ? ',' : '') . " secques='" . $this->quescrypt($questionid, $answer) . "'"; } else { $sqladd .= ($sqladd ? ',' : '') . " secques=''"; } } if ($sqladd) { $this->db->query("UPDATE " . UC_DBTABLEPRE . "members SET $sqladd WHERE username='$username'"); return $this->db->affected_rows(); } else { return -7; } } function delete_user($uidsarr) { $uidsarr = (array)$uidsarr; if (!$uidsarr) { return 0; } $uids = $this->base->implode($uidsarr); $arr = $this->db->fetch_all("SELECT uid FROM " . UC_DBTABLEPRE . "protectedmembers WHERE uid IN ($uids)"); $puids = array(); foreach ((array)$arr as $member) { $puids[] = $member['uid']; } $uids = $this->base->implode(array_diff($uidsarr, $puids)); if ($uids) { $this->db->query("DELETE FROM " . UC_DBTABLEPRE . "members WHERE uid IN($uids)"); $this->db->query("DELETE FROM " . UC_DBTABLEPRE . "memberfields WHERE uid IN($uids)"); uc_user_deleteavatar($uidsarr); $this->base->load('note'); $_ENV['note']->add('deleteuser', "ids=$uids"); return $this->db->affected_rows(); } else { return 0; } } function get_total_num($sqladd = '') { $data = $this->db->result_first("SELECT COUNT(*) FROM " . UC_DBTABLEPRE . "members $sqladd"); return $data; } function get_list($page, $ppp, $totalnum, $sqladd) { $start = $this->base->page_get_start($page, $ppp, $totalnum); $data = $this->db->fetch_all("SELECT * FROM " . UC_DBTABLEPRE . "members $sqladd LIMIT $start, $ppp"); return $data; } function name2id($usernamesarr) { $usernamesarr = uc_addslashes($usernamesarr, 1, TRUE); $usernames = $this->base->implode($usernamesarr); $query = $this->db->query("SELECT uid FROM " . UC_DBTABLEPRE . "members WHERE username IN($usernames)"); $arr = array(); while ($user = $this->db->fetch_array($query)) { $arr[] = $user['uid']; } return $arr; } function id2name($uidarr) { $arr = array(); $query = $this->db->query("SELECT uid, username FROM " . UC_DBTABLEPRE . "members WHERE uid IN (" . $this->base->implode($uidarr) . ")"); while ($user = $this->db->fetch_array($query)) { $arr[$user['uid']] = $user['username']; } return $arr; } } ?>
MyController/ucclient
src/uc_client/model/user.php
PHP
mit
9,134
<?php /** * Configula Library * * @license http://opensource.org/licenses/MIT * @link https://github.com/caseyamcl/configula * @version 4 * @package caseyamcl/configula * @author Casey McLaughlin <caseyamcl@gmail.com> * * For the full copyright and license information, - please view the LICENSE.md * file that was distributed with this source code. * * ------------------------------------------------------------------ */ declare(strict_types=1); namespace Configula\Util; use Generator; use IteratorAggregate; use SplFileInfo; /** * Local/Dist file iterator * * Iterates over files in the following order: * * *.dist.EXT ('.dist' is configurable) * *.EXT * *.local.EXT ('.local' is configurable) * * @author Casey McLaughlin <caseyamcl@gmail.com> */ class LocalDistFileIterator implements IteratorAggregate { /** * @var iterable */ private $iterator; /** * @var string */ private $localSuffix; /** * @var string */ private $distSuffix; /** * LocalDistFileIterator constructor. * @param iterable|SplFileInfo[]|string[] $fileIterator Iterate either file paths or SplFileInfo instances * @param string $localSuffix File suffix denoting 'local' (high priority) files (always comes before extension) * @param string $distSuffix File suffix denoting 'dist' (low priority) files (always comes before extension) */ public function __construct(iterable $fileIterator, string $localSuffix = '.local', string $distSuffix = '.dist') { $this->iterator = $fileIterator; $this->localSuffix = $localSuffix; $this->distSuffix = $distSuffix; } /** * @return Generator|SplFileInfo[] */ public function getIterator() { $localFiles = []; $normalFiles = []; foreach ($this->iterator as $file) { $basename = rtrim($file->getBasename(strtolower($file->getExtension())), '.'); if (strcasecmp(substr($basename, 0 - strlen($this->localSuffix)), $this->localSuffix) === 0) { $localFiles[] = $file; } elseif (strcasecmp(substr($basename, 0 - strlen($this->distSuffix)), $this->distSuffix) === 0) { yield $file; } else { $normalFiles[] = $file; } } foreach (array_merge($normalFiles, $localFiles) as $item) { yield $item; } } }
caseyamcl/Configula
src/Util/LocalDistFileIterator.php
PHP
mit
2,452
package pad // // Paxos library, to be included in an application. // Multiple applications will run, each including // a Paxos peer. // // Manages a sequence of agreed-on values. // The set of peers is fixed. // Copes with network failures (partition, msg loss, &c). // Does not store anything persistently, so cannot handle crash+restart. // // The application interface: // // px = paxos.Make(peers []string, me string) // px.Start(seq int, v interface{}) -- start agreement on new instance // px.Status(seq int) (decided bool, v interface{}) -- get info about an instance // px.Done(seq int) -- ok to forget all instances <= seq // px.Max() int -- highest instance seq known, or -1 // px.Min() int -- instances before this seq have been forgotten // import "net" import "net/rpc" import "log" /*import "os"*/ import "syscall" import "sync" import "fmt" import "math/rand" import "math" type Paxos struct { mu sync.Mutex l net.Listener dead bool unreliable bool rpcCount int peers []string me int // index into peers[] // Your data here. lock sync.Mutex leader bool n int v interface{} // acceptance map A map[int]*AcceptorState //decision state decision map[int]Proposition doneMap map[int]int max int min int } type AcceptorState struct { //acceptor state n_p int //highest prepare seen n_a int //highest accept seen v_a Proposition // highest accept value seen } const ( PrepareOK = "PrepareOK" PrepareNand = "PrepareReject" AcceptOK = "AcceptOK" AcceptNand = "AcceptReject" LearnOK = "LearnOK" ) type PrepareArgs struct { N int Seq int Peer int DoneWith int } type PrepareReply struct { Status string N_a int V_a Proposition } type AcceptArgs struct { N int Seq int Val Proposition } type AcceptReply struct { Status string N int Val Proposition } type LearnArgs struct { Seq int Val Proposition } type LearnReply struct { Status string } type MinArgs struct { } type MinReply struct { Min int } type Proposition struct { Id int64 Val interface{} } // // call() sends an RPC to the rpcname handler on server srv // with arguments args, waits for the reply, and leaves the // reply in reply. the reply argument should be a pointer // to a reply structure. // // the return value is true if the server responded, and false // if call() was not able to contact the server. in particular, // the replys contents are only valid if call() returned true. // // you should assume that call() will time out and return an // error after a while if it does not get a reply from the server. // // please use call() to send all RPCs, in client.go and server.go. // please do not change this function. // func call(srv string, name string, args interface{}, reply interface{}) bool { c, err := rpc.Dial("tcp", srv) if err != nil { err1 := err.(*net.OpError) if err1.Err != syscall.ENOENT && err1.Err != syscall.ECONNREFUSED { fmt.Printf("paxos Dial() failed: %v\n", err1) } return false } defer c.Close() err = c.Call(name, args, reply) if err == nil { return true } return false } func (px *Paxos) Me() string { return px.peers[px.me] } func (px *Paxos) Prepare(args *PrepareArgs, reply *PrepareReply) error { px.lock.Lock() defer px.lock.Unlock() //adjust map of who is done with what and clear memory if possible px.doneMap[args.Peer] = int(math.Max(float64(px.doneMap[args.Peer]), float64(args.DoneWith))) px.delete() state, ok := px.A[args.Seq] if !ok { state = &AcceptorState{-1, -1, Proposition{}} } if args.N > state.n_p { state.n_p = args.N reply.Status = PrepareOK reply.N_a = state.n_a reply.V_a = state.v_a px.A[args.Seq] = state } else { reply.Status = PrepareNand } return nil } func (px *Paxos) Accept(args *AcceptArgs, reply *AcceptReply) error { px.lock.Lock() defer px.lock.Unlock() state, ok := px.A[args.Seq] if !ok { state = &AcceptorState{-1, -1, Proposition{}} } if args.N >= state.n_p { state.n_p = args.N state.n_a = args.N state.v_a = args.Val reply.Status = AcceptOK reply.N = args.N reply.Val = args.Val px.A[args.Seq] = state } else { reply.Status = AcceptNand } return nil } func (px *Paxos) Learn(args *LearnArgs, reply *LearnReply) error { px.lock.Lock() defer px.lock.Unlock() px.decision[args.Seq] = args.Val if args.Seq > px.max { px.max = args.Seq } return nil } func (px *Paxos) Minquery(args *MinArgs, reply *MinReply) error { reply.Min = px.min return nil } func nrand2() int64 { x := rand.Int63() return x } // // the application wants paxos to start agreement on // instance seq, with proposed value v. // Start() returns right away; the application will // call Status() to find out if/when agreement // is reached. // func (px *Paxos) Start(seq int, val interface{}) { v := Proposition{nrand2(), val} //proposer go func(seq int, v Proposition) { _, ok := px.decision[seq] px.lock.Lock() px.A[seq] = &AcceptorState{-1, -1, Proposition{}} px.lock.Unlock() n := px.me for !ok { //choose n, unique and higher than any n seen so far px.lock.Lock() for { if px.A[seq].n_p >= n { n += len(px.peers) } else { break } } px.lock.Unlock() // ------------------------ PREPARE ------------------------- //send prepare(n) to all servers including self prepareResponseChannel := make(chan *PrepareReply, len(px.peers)) for i := 0; i < len(px.peers); i++ { args := PrepareArgs{n, seq, px.me, px.doneMap[px.me]} reply := &PrepareReply{} if i == px.me { px.Prepare(&args, reply) prepareResponseChannel <- reply } else { go func(i int) { success := call(px.peers[i], "Paxos.Prepare", args, reply) if !success { reply.Status = PrepareNand } prepareResponseChannel <- reply return }(i) } } //prepare response handler prepareMajorityChannel := make(chan bool, len(px.peers)) majority := false numReplies := 0 numOK := 0 highestN := -1 value := v go func() { for numReplies < len(px.peers) { reply := <-prepareResponseChannel numReplies += 1 if reply.Status == PrepareOK { numOK += 1 if reply.N_a > highestN { highestN = reply.N_a blank := Proposition{} if reply.V_a.Id != blank.Id { value = reply.V_a } } } if numOK > len(px.peers)/2 { majority = true } } close(prepareResponseChannel) prepareMajorityChannel <- majority return }() prepareMajority := <-prepareMajorityChannel close(prepareMajorityChannel) // ------------------------ ACCEPT ------------------------- // prepare majority achieved -> propose value // begin accept phase if prepareMajority { //send accept to all servers including self acceptResponseChannel := make(chan *AcceptReply, len(px.peers)) for i := 0; i < len(px.peers); i++ { args := AcceptArgs{n, seq, value} reply := &AcceptReply{} if i == px.me { px.Accept(&args, reply) acceptResponseChannel <- reply } else { go func(i int) { success := call(px.peers[i], "Paxos.Accept", args, reply) if !success { reply.Status = AcceptNand } acceptResponseChannel <- reply return }(i) } } //accept response handler acceptMajorityChannel := make(chan bool, len(px.peers)) majority := false numReplies := 0 numOK := 0 go func() { for numReplies < len(px.peers) { reply := <-acceptResponseChannel numReplies += 1 if reply.Status == AcceptOK && reply.Val.Id == value.Id { numOK += 1 } if numOK > len(px.peers)/2 { majority = true } } acceptMajorityChannel <- majority close(acceptResponseChannel) return }() acceptMajority := <-acceptMajorityChannel close(acceptMajorityChannel) // ------------------------ LEARN ------------------------- if acceptMajority { //begin learn phase // accepted by majority for i := 0; i < len(px.peers); i++ { args := LearnArgs{seq, value} reply := &LearnReply{} if i == px.me { px.Learn(&args, reply) } else { go func(i int) { success := false // for !success { success = call(px.peers[i], "Paxos.Learn", args, reply) // } if !success { reply.Status = LearnOK } return }(i) } } break } else { // fmt.Println("Accept did not get majority") } } else { // fmt.Println("Prepare did not get majority") } _, ok = px.decision[seq] } }(seq, v) } // // the application on this machine is done with // all instances <= seq. // // see the comments for Min() for more explanation. // func (px *Paxos) Done(seq int) { // Your code here. if seq > px.min { px.min = seq } px.doneMap[px.me] = int(math.Max(float64(seq), float64(px.doneMap[px.me]))) px.delete() } func (px *Paxos) delete() { px.mu.Lock() defer px.mu.Unlock() // delete only up to min in case server is partitioned globalMin := px.Min() for key := range px.A { if key < globalMin { delete(px.A, key) } } for key := range px.decision { if key < globalMin { delete(px.decision, key) } } } // // the application wants to know the // highest instance sequence known to // this peer. // func (px *Paxos) Max() int { // Your code here. return px.max } // // Min() should return one more than the minimum among z_i, // where z_i is the highest number ever passed // to Done() on peer i. A peers z_i is -1 if it has // never called Done(). // // Paxos is required to have forgotten all information // about any instances it knows that are < Min(). // The point is to free up memory in long-running // Paxos-based servers. // // Paxos peers need to exchange their highest Done() // arguments in order to implement Min(). These // exchanges can be piggybacked on ordinary Paxos // agreement protocol messages, so it is OK if one // peers Min does not reflect another Peers Done() // until after the next instance is agreed to. // // The fact that Min() is defined as a minimum over // *all* Paxos peers means that Min() cannot increase until // all peers have been heard from. So if a peer is dead // or unreachable, other peers Min()s will not increase // even if all reachable peers call Done. The reason for // this is that when the unreachable peer comes back to // life, it will need to catch up on instances that it // missed -- the other peers therefor cannot forget these // instances. // func (px *Paxos) Min() int { globalMin := px.doneMap[px.me] for _, peerMin := range px.doneMap { globalMin = int(math.Min(float64(globalMin), float64(peerMin))) } return globalMin + 1 } // // the application wants to know whether this // peer thinks an instance has been decided, // and if so what the agreed value is. Status() // should just inspect the local peer state; // it should not contact other Paxos peers. // func (px *Paxos) Status(seq int) (bool, interface{}) { // Your code here. if val, ok := px.decision[seq]; ok { return true, val.Val } return false, nil } // // tell the peer to shut itself down. // for testing. // please do not change this function. // func (px *Paxos) Kill() { px.dead = true if px.l != nil { px.l.Close() } } // // the application wants to create a paxos peer. // the ports of all the paxos peers (including this one) // are in peers[]. this servers port is peers[me]. // func MakePaxosInstance(peers []string, me int, rpcs *rpc.Server) *Paxos { px := &Paxos{} px.peers = peers px.me = me // Your initialization code here. px.doneMap = make(map[int]int) for i, _ := range px.peers { px.doneMap[i] = -1 } px.decision = make(map[int]Proposition) px.A = make(map[int]*AcceptorState) px.max = -1 px.min = -1 if rpcs != nil { // caller will create socket &c rpcs.Register(px) } else { rpcs = rpc.NewServer() rpcs.Register(px) // prepare to receive connections from clients. // change "unix" to "tcp" to use over a network. // os.Remove(peers[me]) // only needed for "unix" l, e := net.Listen("tcp", peers[me]) if e != nil { log.Fatal("listen error: ", e) } px.l = l // please do not change any of the following code, // or do anything to subvert it. // create a thread to accept RPC connections go func() { for px.dead == false { conn, err := px.l.Accept() if err == nil && px.dead == false { if px.unreliable && (rand.Int63()%1000) < 100 { // discard the request. conn.Close() } else if px.unreliable && (rand.Int63()%1000) < 200 { // process the request but force discard of reply. c1 := conn.(*net.UnixConn) f, _ := c1.File() err := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR) if err != nil { fmt.Printf("shutdown: %v\n", err) } px.rpcCount++ go rpcs.ServeConn(conn) } else { px.rpcCount++ go rpcs.ServeConn(conn) } } else if err == nil { conn.Close() } if err != nil && px.dead == false { fmt.Printf("Paxos(%v) accept: %v\n", me, err.Error()) } } }() } return px }
jdhenke/pad
server/pad/paxos.go
GO
mit
13,355
<?php namespace Jenny\ImportBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class JennyImportBundle extends Bundle { }
jennydjen/NoteDeFrais
src/Jenny/ImportBundle/JennyImportBundle.php
PHP
mit
130
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.6.0_18) on Thu Dec 18 17:18:42 PST 2014 --> <title>Uses of Class org.omg.CORBA.ORB (Java Platform SE 7 )</title> <meta name="date" content="2014-12-18"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.omg.CORBA.ORB (Java Platform SE 7 )"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;7</strong></em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/omg/CORBA/class-use/ORB.html" target="_top">Frames</a></li> <li><a href="ORB.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.omg.CORBA.ORB" class="title">Uses of Class<br>org.omg.CORBA.ORB</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#javax.rmi.CORBA">javax.rmi.CORBA</a></td> <td class="colLast"> <div class="block">Contains portability APIs for RMI-IIOP.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.omg.CORBA">org.omg.CORBA</a></td> <td class="colLast"> <div class="block">Provides the mapping of the OMG CORBA APIs to the Java<SUP><FONT SIZE=-2>TM</FONT></SUP> programming language, including the class <TT>ORB</TT>, which is implemented so that a programmer can use it as a fully-functional Object Request Broker (ORB).</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.omg.CORBA_2_3">org.omg.CORBA_2_3</a></td> <td class="colLast"> <div class="block">The CORBA_2_3 package defines additions to existing CORBA interfaces in the Java[tm] Standard Edition 6.&nbsp;&nbsp; These changes occurred in recent revisions to the CORBA API defined by the OMG.&nbsp; The new methods were added to&nbsp; interfaces derived from the corresponding interfaces in the CORBA package.&nbsp; This provides backward compatibility and avoids breaking the JCK tests.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.omg.CORBA.portable">org.omg.CORBA.portable</a></td> <td class="colLast"> <div class="block">Provides a portability layer, that is, a set of ORB APIs that makes it possible for code generated by one vendor to run on another vendor's ORB.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.omg.CosNaming">org.omg.CosNaming</a></td> <td class="colLast"> <div class="block">Provides a naming service for Java&nbsp;IDL.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.omg.PortableServer">org.omg.PortableServer</a></td> <td class="colLast"> <div class="block">Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.omg.PortableServer.portable">org.omg.PortableServer.portable</a></td> <td class="colLast"> <div class="block">Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="javax.rmi.CORBA"> <!-- --> </a> <h3>Uses of <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a> in <a href="../../../../javax/rmi/CORBA/package-summary.html">javax.rmi.CORBA</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../javax/rmi/CORBA/package-summary.html">javax.rmi.CORBA</a> that return <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></code></td> <td class="colLast"><span class="strong">Tie.</span><code><strong><a href="../../../../javax/rmi/CORBA/Tie.html#orb()">orb</a></strong>()</code> <div class="block">Returns the ORB for this tie.</div> </td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../javax/rmi/CORBA/package-summary.html">javax.rmi.CORBA</a> with parameters of type <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">Stub.</span><code><strong><a href="../../../../javax/rmi/CORBA/Stub.html#connect(org.omg.CORBA.ORB)">connect</a></strong>(<a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a>&nbsp;orb)</code> <div class="block">Connects this stub to an ORB.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">StubDelegate.</span><code><strong><a href="../../../../javax/rmi/CORBA/StubDelegate.html#connect(javax.rmi.CORBA.Stub,%20org.omg.CORBA.ORB)">connect</a></strong>(<a href="../../../../javax/rmi/CORBA/Stub.html" title="class in javax.rmi.CORBA">Stub</a>&nbsp;self, <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a>&nbsp;orb)</code> <div class="block">Delegation call for <a href="../../../../javax/rmi/CORBA/Stub.html#connect(org.omg.CORBA.ORB)"><code>Stub.connect(org.omg.CORBA.ORB)</code></a>.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a></code></td> <td class="colLast"><span class="strong">Util.</span><code><strong><a href="../../../../javax/rmi/CORBA/Util.html#copyObject(java.lang.Object,%20org.omg.CORBA.ORB)">copyObject</a></strong>(<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>&nbsp;obj, <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a>&nbsp;orb)</code> <div class="block">Copies or connects an object.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a></code></td> <td class="colLast"><span class="strong">UtilDelegate.</span><code><strong><a href="../../../../javax/rmi/CORBA/UtilDelegate.html#copyObject(java.lang.Object,%20org.omg.CORBA.ORB)">copyObject</a></strong>(<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>&nbsp;obj, <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a>&nbsp;orb)</code> <div class="block">Delegation call for <a href="../../../../javax/rmi/CORBA/Util.html#copyObject(java.lang.Object,%20org.omg.CORBA.ORB)"><code>Util.copyObject(java.lang.Object, org.omg.CORBA.ORB)</code></a>.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>[]</code></td> <td class="colLast"><span class="strong">Util.</span><code><strong><a href="../../../../javax/rmi/CORBA/Util.html#copyObjects(java.lang.Object[],%20org.omg.CORBA.ORB)">copyObjects</a></strong>(<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>[]&nbsp;obj, <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a>&nbsp;orb)</code> <div class="block">Copies or connects an array of objects.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>[]</code></td> <td class="colLast"><span class="strong">UtilDelegate.</span><code><strong><a href="../../../../javax/rmi/CORBA/UtilDelegate.html#copyObjects(java.lang.Object[],%20org.omg.CORBA.ORB)">copyObjects</a></strong>(<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>[]&nbsp;obj, <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a>&nbsp;orb)</code> <div class="block">Delegation call for <a href="../../../../javax/rmi/CORBA/Util.html#copyObjects(java.lang.Object[],%20org.omg.CORBA.ORB)"><code>Util.copyObjects(java.lang.Object[], org.omg.CORBA.ORB)</code></a>.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">Tie.</span><code><strong><a href="../../../../javax/rmi/CORBA/Tie.html#orb(org.omg.CORBA.ORB)">orb</a></strong>(<a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a>&nbsp;orb)</code> <div class="block">Sets the ORB for this tie.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.omg.CORBA"> <!-- --> </a> <h3>Uses of <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a> in <a href="../../../../org/omg/CORBA/package-summary.html">org.omg.CORBA</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/omg/CORBA/package-summary.html">org.omg.CORBA</a> that return <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></code></td> <td class="colLast"><span class="strong">LocalObject.</span><code><strong><a href="../../../../org/omg/CORBA/LocalObject.html#_orb()">_orb</a></strong>()</code> <div class="block">Throws an <code>org.omg.CORBA.NO_IMPLEMENT</code> exception with the message "This is a locally constrained object." This method is the default implementation of the <code>org.omg.CORBA.Object</code> method.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></code></td> <td class="colLast"><span class="strong">ORB.</span><code><strong><a href="../../../../org/omg/CORBA/ORB.html#init()">init</a></strong>()</code> <div class="block">Returns the <code>ORB</code> singleton object.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></code></td> <td class="colLast"><span class="strong">ORB.</span><code><strong><a href="../../../../org/omg/CORBA/ORB.html#init(java.applet.Applet,%20java.util.Properties)">init</a></strong>(<a href="../../../../java/applet/Applet.html" title="class in java.applet">Applet</a>&nbsp;app, <a href="../../../../java/util/Properties.html" title="class in java.util">Properties</a>&nbsp;props)</code> <div class="block">Creates a new <code>ORB</code> instance for an applet.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></code></td> <td class="colLast"><span class="strong">ORB.</span><code><strong><a href="../../../../org/omg/CORBA/ORB.html#init(java.lang.String[],%20java.util.Properties)">init</a></strong>(<a href="../../../../java/lang/String.html" title="class in java.lang">String</a>[]&nbsp;args, <a href="../../../../java/util/Properties.html" title="class in java.util">Properties</a>&nbsp;props)</code> <div class="block">Creates a new <code>ORB</code> instance for a standalone application.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.omg.CORBA_2_3"> <!-- --> </a> <h3>Uses of <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a> in <a href="../../../../org/omg/CORBA_2_3/package-summary.html">org.omg.CORBA_2_3</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a> in <a href="../../../../org/omg/CORBA_2_3/package-summary.html">org.omg.CORBA_2_3</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../org/omg/CORBA_2_3/ORB.html" title="class in org.omg.CORBA_2_3">ORB</a></strong></code> <div class="block">A class extending <code>org.omg.CORBA.ORB</code> to make the ORB portable under the OMG CORBA version 2.3 specification.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.omg.CORBA.portable"> <!-- --> </a> <h3>Uses of <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a> in <a href="../../../../org/omg/CORBA/portable/package-summary.html">org.omg.CORBA.portable</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/omg/CORBA/portable/package-summary.html">org.omg.CORBA.portable</a> that return <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></code></td> <td class="colLast"><span class="strong">ObjectImpl.</span><code><strong><a href="../../../../org/omg/CORBA/portable/ObjectImpl.html#_orb()">_orb</a></strong>()</code> <div class="block">Returns a reference to the ORB associated with this object and its delegate.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></code></td> <td class="colLast"><span class="strong">OutputStream.</span><code><strong><a href="../../../../org/omg/CORBA/portable/OutputStream.html#orb()">orb</a></strong>()</code> <div class="block">Returns the ORB that created this OutputStream.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></code></td> <td class="colLast"><span class="strong">InputStream.</span><code><strong><a href="../../../../org/omg/CORBA/portable/InputStream.html#orb()">orb</a></strong>()</code> <div class="block">Returns the ORB that created this InputStream.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></code></td> <td class="colLast"><span class="strong">Delegate.</span><code><strong><a href="../../../../org/omg/CORBA/portable/Delegate.html#orb(org.omg.CORBA.Object)">orb</a></strong>(<a href="../../../../org/omg/CORBA/Object.html" title="interface in org.omg.CORBA">Object</a>&nbsp;obj)</code> <div class="block">Provides a reference to the orb associated with its parameter.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.omg.CosNaming"> <!-- --> </a> <h3>Uses of <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a> in <a href="../../../../org/omg/CosNaming/package-summary.html">org.omg.CosNaming</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/omg/CosNaming/package-summary.html">org.omg.CosNaming</a> with parameters of type <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/omg/CosNaming/BindingIterator.html" title="interface in org.omg.CosNaming">BindingIterator</a></code></td> <td class="colLast"><span class="strong">BindingIteratorPOA.</span><code><strong><a href="../../../../org/omg/CosNaming/BindingIteratorPOA.html#_this(org.omg.CORBA.ORB)">_this</a></strong>(<a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a>&nbsp;orb)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/omg/CosNaming/NamingContextExt.html" title="interface in org.omg.CosNaming">NamingContextExt</a></code></td> <td class="colLast"><span class="strong">NamingContextExtPOA.</span><code><strong><a href="../../../../org/omg/CosNaming/NamingContextExtPOA.html#_this(org.omg.CORBA.ORB)">_this</a></strong>(<a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a>&nbsp;orb)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/omg/CosNaming/NamingContext.html" title="interface in org.omg.CosNaming">NamingContext</a></code></td> <td class="colLast"><span class="strong">NamingContextPOA.</span><code><strong><a href="../../../../org/omg/CosNaming/NamingContextPOA.html#_this(org.omg.CORBA.ORB)">_this</a></strong>(<a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a>&nbsp;orb)</code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.omg.PortableServer"> <!-- --> </a> <h3>Uses of <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a> in <a href="../../../../org/omg/PortableServer/package-summary.html">org.omg.PortableServer</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/omg/PortableServer/package-summary.html">org.omg.PortableServer</a> that return <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></code></td> <td class="colLast"><span class="strong">Servant.</span><code><strong><a href="../../../../org/omg/PortableServer/Servant.html#_orb()">_orb</a></strong>()</code> <div class="block">Returns the instance of the ORB currently associated with the <code>Servant</code> (convenience method).</div> </td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/omg/PortableServer/package-summary.html">org.omg.PortableServer</a> with parameters of type <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/omg/CORBA/Object.html" title="interface in org.omg.CORBA">Object</a></code></td> <td class="colLast"><span class="strong">Servant.</span><code><strong><a href="../../../../org/omg/PortableServer/Servant.html#_this_object(org.omg.CORBA.ORB)">_this_object</a></strong>(<a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a>&nbsp;orb)</code> <div class="block">Allows the servant to obtain the object reference for the target CORBA Object it is incarnating for that request.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/omg/PortableServer/ServantActivator.html" title="interface in org.omg.PortableServer">ServantActivator</a></code></td> <td class="colLast"><span class="strong">ServantActivatorPOA.</span><code><strong><a href="../../../../org/omg/PortableServer/ServantActivatorPOA.html#_this(org.omg.CORBA.ORB)">_this</a></strong>(<a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a>&nbsp;orb)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/omg/PortableServer/ServantLocator.html" title="interface in org.omg.PortableServer">ServantLocator</a></code></td> <td class="colLast"><span class="strong">ServantLocatorPOA.</span><code><strong><a href="../../../../org/omg/PortableServer/ServantLocatorPOA.html#_this(org.omg.CORBA.ORB)">_this</a></strong>(<a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a>&nbsp;orb)</code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.omg.PortableServer.portable"> <!-- --> </a> <h3>Uses of <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a> in <a href="../../../../org/omg/PortableServer/portable/package-summary.html">org.omg.PortableServer.portable</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/omg/PortableServer/portable/package-summary.html">org.omg.PortableServer.portable</a> that return <a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">ORB</a></code></td> <td class="colLast"><span class="strong">Delegate.</span><code><strong><a href="../../../../org/omg/PortableServer/portable/Delegate.html#orb(org.omg.PortableServer.Servant)">orb</a></strong>(<a href="../../../../org/omg/PortableServer/Servant.html" title="class in org.omg.PortableServer">Servant</a>&nbsp;Self)</code> <div class="block">Convenience method that returns the instance of the ORB currently associated with the Servant.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../org/omg/CORBA/ORB.html" title="class in org.omg.CORBA">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;7</strong></em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/omg/CORBA/class-use/ORB.html" target="_top">Frames</a></li> <li><a href="ORB.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://docs.oracle.com/javase/7/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> <a href="../../../../../legal/cpyr.html">Copyright</a> &#x00a9; 1993, 2015, Oracle and/or its affiliates. All rights reserved. </font></small></p> </body> </html>
fbiville/annotation-processing-ftw
doc/java/jdk7/org/omg/CORBA/class-use/ORB.html
HTML
mit
27,144
using System; namespace LexicalAnalysis { /// <summary> /// String literal /// </summary> public sealed class TokenString : Token { public TokenString(String val, String raw) { if (val == null) { throw new ArgumentNullException(nameof(val)); } this.Val = val; this.Raw = raw; } public override TokenKind Kind { get; } = TokenKind.STRING; public String Raw { get; } public String Val { get; } public override String ToString() => $"{this.Kind}: \"{this.Raw}\"\n\"{this.Val}\""; } public sealed class FSAString : FSA { private enum State { START, END, ERROR, L, Q, QQ }; private State _state; private readonly FSAChar _fsachar; private String _val; private String _raw; public FSAString() { this._state = State.START; this._fsachar = new FSAChar('\"'); this._raw = ""; this._val = ""; } public override void Reset() { this._state = State.START; this._fsachar.Reset(); this._raw = ""; this._val = ""; } public override FSAStatus GetStatus() { if (this._state == State.START) { return FSAStatus.NONE; } if (this._state == State.END) { return FSAStatus.END; } if (this._state == State.ERROR) { return FSAStatus.ERROR; } return FSAStatus.RUNNING; } public override Token RetrieveToken() { return new TokenString(this._val, this._raw); } public override void ReadChar(Char ch) { switch (this._state) { case State.END: case State.ERROR: this._state = State.ERROR; break; case State.START: switch (ch) { case 'L': this._state = State.L; break; case '\"': this._state = State.Q; this._fsachar.Reset(); break; default: this._state = State.ERROR; break; } break; case State.L: if (ch == '\"') { this._state = State.Q; this._fsachar.Reset(); } else { this._state = State.ERROR; } break; case State.Q: if (this._fsachar.GetStatus() == FSAStatus.NONE && ch == '\"') { this._state = State.QQ; this._fsachar.Reset(); } else { this._fsachar.ReadChar(ch); switch (this._fsachar.GetStatus()) { case FSAStatus.END: this._state = State.Q; this._val = this._val + this._fsachar.RetrieveChar(); this._raw = this._raw + this._fsachar.RetrieveRaw(); this._fsachar.Reset(); ReadChar(ch); break; case FSAStatus.ERROR: this._state = State.ERROR; break; default: break; } } break; case State.QQ: this._state = State.END; break; default: this._state = State.ERROR; break; } } public override void ReadEOF() { if (this._state == State.QQ) { this._state = State.END; } else { this._state = State.ERROR; } } } }
phisiart/C-Compiler
Scanner/String.cs
C#
mit
4,376
<!doctype html> <!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--> <!--[if (IE 7)&!(IEMobile)]><html class="no-js lt-ie9 lt-ie8" lang="en"><![endif]--> <!--[if (IE 8)&!(IEMobile)]><html class="no-js lt-ie9" lang="en"><![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"><!--<![endif]--> <head> <meta charset="utf-8"> <title>Projects &#8211; Rebecca Morgan</title> <meta name="keywords" content="about, projects, profile, research"> <!-- Twitter Cards --> <meta name="twitter:title" content="Projects"> <meta name="twitter:site" content="@EarthRebecca"> <meta name="twitter:creator" content="@EarthRebecca"> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:image" content="http://localhost:4000/images/louisville_seamounts.png"> <!-- Open Graph --> <meta property="og:locale" content="en_GB"> <meta property="og:type" content="article"> <meta property="og:title" content="Projects"> <meta property="og:url" content="http://localhost:4000/projects/"> <meta property="og:site_name" content="Rebecca Morgan"> <link rel="canonical" href="http://localhost:4000/projects/"> <link href="http://localhost:4000/feed.xml" type="application/atom+xml" rel="alternate" title="Rebecca Morgan Feed"> <!-- http://t.co/dKP3o1e --> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- For all browsers --> <link rel="stylesheet" href="http://localhost:4000/assets/css/main.css"> <meta http-equiv="cleartype" content="on"> <!-- HTML5 Shiv and Media Query Support --> <!--[if lt IE 9]> <script src="http://localhost:4000/assets/js/vendor/html5shiv.min.js"></script> <script src="http://localhost:4000/assets/js/vendor/respond.min.js"></script> <![endif]--> <!-- Modernizr --> <script src="http://localhost:4000/assets/js/vendor/modernizr-2.7.1.custom.min.js"></script> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700%7CPT+Serif:400,700,400italic' rel='stylesheet' type='text/css'> <!-- Icons --> <!-- 16x16 --> <link rel="shortcut icon" href="http://localhost:4000/favicon.ico"> <!-- 32x32 --> <link rel="shortcut icon" href="http://localhost:4000/favicon.png"> <!-- 57x57 (precomposed) for iPhone 3GS, pre-2011 iPod Touch and older Android devices --> <link rel="apple-touch-icon-precomposed" href="http://localhost:4000/images/apple-touch-icon-precomposed.png"> <!-- 72x72 (precomposed) for 1st generation iPad, iPad 2 and iPad mini --> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://localhost:4000/images/apple-touch-icon-72x72-precomposed.png"> <!-- 114x114 (precomposed) for iPhone 4, 4S, 5 and post-2011 iPod Touch --> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://localhost:4000/images/apple-touch-icon-114x114-precomposed.png"> <!-- 144x144 (precomposed) for iPad 3rd and 4th generation --> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://localhost:4000/images/apple-touch-icon-144x144-precomposed.png"> </head> <body class="page"> <!--[if lt IE 9]><div class="browser-upgrade alert alert-info">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</div><![endif]--> <div class="navigation-wrapper"> <div class="site-name"> <a href="http://localhost:4000">Rebecca Morgan</a> </div><!-- /.site-name --> <div class="top-navigation"> <nav role="navigation" id="site-nav" class="nav"> <ul> <li><a href="http://localhost:4000/academic/" >Academic Profile</a></li> <li><a href="http://localhost:4000/blog/" >Blog: Geochronicles</a></li> <li><a href="http://localhost:4000/projects/" >Projects</a></li> <li><a href="http://feeds.feedburner.com/RebeccaMorgan" target="_blank">Feed</a></li> </ul> </nav> </div><!-- /.top-navigation --> </div><!-- /.navigation-wrapper --> <div class="image-wrap"> <img src= "http://localhost:4000/images/louisville_seamounts.png" alt="Projects feature image"> <span class="image-credit">Photo Credit: <a href="">Tony Watts</a></span> </div><!-- /.image-wrap --> <div id="main" role="main"> <div class="article-author-side"> <img src="http://localhost:4000/images/bio-photo.jpg" class="bio-photo" alt="Rebecca Morgan bio photo"> <h3>Rebecca Morgan</h3> <p>DPhil student at the University of Oxford studying marine geophysics with the NERC DTP.</p> <a href="mailto:rebecca.morgan@earth.ox.ac.uk" class="author-social" target="_blank"><i class="fa fa-fw fa-envelope-square"></i> Email</a> <a href="http://twitter.com/EarthRebecca" class="author-social" target="_blank"><i class="fa fa-fw fa-twitter-square"></i> Twitter</a> <a href="http://linkedin.com/in/rebeccamorgan92" class="author-social" target="_blank"><i class="fa fa-fw fa-linkedin-square"></i> LinkedIn</a> <a href="http://github.com/rebeccamorgan" class="author-social" target="_blank"><i class="fa fa-fw fa-github"></i> Github</a> <br> <a href="https://feedburner.google.com/fb/a/mailverify?uri=RebeccaMorgan&amp;loc=en_US" class="author-social" target="_blank" >Click to subscribe to blog posts by email</a> </div> <article class="page"> <h1>Projects</h1> <div class="article-wrap"> <p><em>Listed below are recent research projects, including those completed during my undergraduate degree.</em></p> <h1 id="evolution-of-the-louisville-ridge">Evolution of the Louisville Ridge</h1> <p><em>MEarthSci Research Project 2013-2014, Supervisor: Prof. Tony Watts</em></p> <p><br /></p> <p>Integrating large geophysical dataset including 2D seismic, gravity, magnetics, dredge samples, drill data and swath bathymetry to interpret the structure of the seamount chain and evolution of the hotspot swell.</p> <ul> <li>Interpretation of shallow structure on seismic, particularly carbonate caps on guyots, landsliding and faulting history of seamounts as they are subducted at the Tonga-Kermadec trench.</li> <li>Modelling of subsidence and uplift history of the chain and the implications for the history of the hotspot and large-scale mantle geodynamics using backstripping techniques.</li> <li>Constraining crustal structure using 3D gravity modelling of a loaded, flexed plate in MATLAB.</li> <li>Extensive use of GMT (Generic Mapping Tools), MATLAB and LaTeχ.</li> </ul> <p><br /></p> <h1 id="structure-of-the-vring-basin-norway-using-3d-seismic-reflection-data">Structure of the Vøring Basin, Norway using 3D seismic reflection data</h1> <p><em>Summer Research Project 2013, Supervisor: Prof. Joe Cartwright</em></p> <p><br /></p> <p>Analysed the Opal-A/CT diagenetic boundary and its mechanistic relationship with the initiation and geometry of polygonal faulting systems. Interpreted the structure of a mass transport deposit including complex geometries on 3D seismic surveys using various attributes.</p> <ul> <li>Received training on and used Schlumberger’s Petrel package.</li> <li>Using seismic attributes to determine the depositional history of a MTD.</li> <li>Scientific writing skills and background literature review on short timescale.</li> </ul> <p><br /></p> <h1 id="structure-and-stratigraphy-of-the-cardigan-bay-basin-wales">Structure and stratigraphy of the Cardigan Bay Basin, Wales</h1> <p><em>Undergraduate Research Project 2012, Supervisor: Prof. Stephen Hesselbo</em></p> <p><br /></p> <p>Interpreted the structure and stratigraphy of the Cardigan Bay basin using seismic reflection profiles, core, thin sections and geophysical logs to determine the geological evolution.</p> <ul> <li>Produced MATLAB scripts and functions for cyclostratigraphic signal processing and backstripping.</li> <li>Visited BGS Core Store, Nottingham to collect samples and observe core sections.</li> <li>Attended ICDP Mochras Proposal Workshop, where results of the seismic interpretation were displayed.</li> </ul> </div><!-- /.article-wrap --> </article> </div><!-- /#index --> <div class="footer-wrap"> <footer> <span>&copy; 2014 Rebecca Morgan. Powered by <a href="http://jekyllrb.com">Jekyll</a> using the <a href="http://mademistakes.com/minimal-mistakes/">Minimal Mistakes</a> theme.</span> </footer> </div><!-- /.footer-wrap --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="http://localhost:4000/assets/js/vendor/jquery-1.9.1.min.js"><\/script>')</script> <script src="http://localhost:4000/assets/js/scripts.min.js"></script> <!-- Asynchronous Google Analytics snippet --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-56279969-1', 'auto'); ga('require', 'displayfeatures'); ga('send', 'pageview'); </script> </body> </html>
rebeccamorgan/rebeccamorgan.github.io
_site/projects/index.html
HTML
mit
9,398
# GenericDataSource ## 3.0.2 * Upgrade to Xcode 9.3. ## 3.0.1 * Fix a crash in `CompositeSupplementaryViewCreator`. ## 3.0.0 * Swift 4.0 Support. ## 2.4.5 * Adding `onItemsUpdated` to basic data sources to monitor changes to `items` property. * Adding most non-essential APIs to be `DataSourceSelector` so that, it's delegate methods is not called by default. ## 2.4.4 * Added the ability for `CompositeDataSource` and `SegmentedDataSource` to automatically `ds_responds(to selector: DataSourceSelector)` if the subclass implemented the selector. ## 2.4.3 * Fix registering header/footer class method name to be `func ds_register(headerFooterClass view: UITableViewHeaderFooterView.Type)` instead of incorrect old name `func ds_register(headerFooterNib view: UITableViewHeaderFooterView.Type)`.te ## 2.4.2 * Adding `asCollectionView()` and `asTableView()` methods to `GeneralCollectionView` to convert it to `UICollectionView` and `UITableView` respectively. * Adding `size` property to `GeneralCollectionView` to get the size of the underlying `UICollectionView`/`UITableView`. ## 2.4.1 * `@autoclosure` of casting fatal message. Improves performance since there is string manipulation. ## 2.4.0 * `ds_shouldConsumeItemSizeDelegateCalls` is unavailable, instead use `ds_responds(to selector: DataSourceSelector) -> Bool`, It takes an enum, with `.size` it act the same as `ds_shouldConsumeItemSizeDelegateCalls`. * Fixes a bug that makes all table view cells editable by default. * New `ds_responds(to selector: DataSourceSelector) -> Bool` to make it so easy to make some implementations of `DataSource` methods optional (e.g. we used it to fix the editable table view cells bug). ## 2.3.1 * Fixed a critical crash for `ds_collectionView(_:didEndDisplaying:forItemAt:)` in `CompositeDataSource`. ## 2.3.0 * Adding `SegmentedDataSource`. ## 2.2.1 * Making Supplementary view optional as a workaround for the `UITableView` with .grouped style as it asks for the header/footer view even if the size is set as 0 ## 2.2.0 * `UITableView` Header/Footer support. * `UICollectionView` Supplementary view support. ## 2.1.0 * Renaming methods to match Swift 3.0 conventions. ## 2.0.0 * Swift 3.0 Support. ## 1.0.1 * Deprecating `useDelegateForItemSize` in favor of automatic detection if the user implemented `ds_collectionView(_:sizeForItemAtIndexPath:)` or not. * Adding more code documentation and enhancing the readme file.
GenericDataSource/GenericDataSource
CHANGELOG.md
Markdown
mit
2,436
# naffiq.com website This repository serves as code base for naffiq.com website
naffiq/website
README.md
Markdown
mit
80
package org.common; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.xml.bind.DatatypeConverter; /** * Common utilities and code shared for both the client and server. * */ public class Utils { public static final String SUCCESS_STS = "status 000 OK"; public static final String FAIL_INTERNAL = "status 200 Internal Error"; public static final String FAIL_LOGIN_USERNAME_TAKEN = "status 111 Username Taken"; public static final String FAIL_LOGIN_USERNAME_INVALID = "status 112 Username Invalid"; public static final String FAIL_LOGIN_PASSWORD_INVALID = "status 113 Password Invalid"; public static final String FAIL_LOGIN_PERMISSION_DENIED = "status 212 Permission Denied"; public static final String FAIL_USER_NOT_ONLINE = "status 131 User Not Online"; /** * Does nothing but provide an easy way to test our test harness. * * @return Life, the universe, everything */ public int get42( ) { return 42; } /** * Send message out provided printwriter, terminated with EOT. * * @param out - the output stream for the connected socket associated with the user * @param msg - formatted message to send * * @return integer 0 on success, -1 on fail */ public static int sendMessage(PrintWriter out, String msg) { int EOT = 0x04; msg = msg + Character.toString((char) EOT); out.print(msg); out.flush(); return 0; } /** * Receive an EOT terminated message. * * @param - in - buffered reader for socket to receive on * * @return msg - received message without the EOT character */ public static String receiveMessage(BufferedReader in) { String message = ""; int EOT = 0x04; int character = 0; try { // read until failure or until end of message while((character = in.read()) != -1) { if(character == EOT) { // that's the end of message break; } message = message + Character.toString((char) character); } } catch (IOException e) { System.out.println("Failed to receive message. Make sure to provide proper certificate store."); // error case return empty string return ""; } // now we have the message read in return message; } /** * Given a protocol message, tokenize it into a TokenPair. This * just means that the first word is split out from the rest, and a tuple * of the first and rest is returned. * * @param str - the entire protocol message to tokenize * * @return TokenPair of the tokenized strings */ public static TokenPair tokenize(String str) { String first = str.substring(0, str.indexOf(' ')); String rest = str.substring(str.indexOf(' ') + 1); TokenPair tp = new TokenPair(first, rest); return tp; } /** * Given a plaintext password, return the SHA256 hash for storage and verification. * * @param plaintext - String to calculate SHA-256 hash of * * @return hex string of SHA-256 hash. Empty string on error, which means the algorithm * was not found. Since we do not vary the algorithm, this is never expected. */ public static String hashPass(String plaintext) { // SHA 256 is a 32-byte output, which is too large to store as an integer // in sqlite (max 8 bytes). We could truncate, instead we'll convert to // String and store characters. MessageDigest md; try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { System.out.println("ERR: Unable to calculate hash, Algorithm not found."); return ""; } md.update(plaintext.getBytes()); byte[] result = md.digest(); // Now we have the hash bytes in result, format as a string and return. return DatatypeConverter.printHexBinary(result); } /** * Check of whether a username is valid. * * @param username - String of the username to check * * @return boolean true if OK, false if not */ public static boolean isValidUsername(String username) { // We'll use a single regular expression to allow only regular characters and // digits for the username return username.matches("[a-zA-Z0-9]+"); } /** * Check of whether a password is valid. * * @param password - String of the password to check * * @return boolean true if OK, false if not */ public static boolean isValidPassword(String password) { // Password is more permissive than username, allow some punctuation // as well. return password.matches("[a-zA-Z0-9_!.,@]+"); } }
or-drop-tables-team/sup
common/src/main/java/org/common/Utils.java
Java
mit
5,092
<?php namespace Rareloop\Primer\Commands; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Rareloop\Primer\Primer; class PatternMake extends Command { protected function configure() { $this ->setName('pattern:make') ->setDescription('Create a pattern') ->addArgument( 'id', InputArgument::REQUIRED, 'Full ID of the pattern (e.g. components/group/name' ); } protected function execute(InputInterface $input, OutputInterface $output) { $id = $input->getArgument('id'); $cleanId = Primer::cleanId($id); // Does the pattern already exist? $patternPath = Primer::$PATTERN_PATH . '/' . $cleanId; if (file_exists($patternPath)) { $output->writeln(''); $output->writeln('<error>`'.$cleanId.'` already exists</error>'); $output->writeln(''); return; } $success = @mkdir($patternPath, 0777, true); if (!$success) { $error = error_get_last(); $output->writeln(''); $output->writeln('<error>`'.$error['message'].'` already exists</error>'); $output->writeln(''); return; } $templateClass = Primer::$TEMPLATE_CLASS; $templateExtension = $templateClass::$extension; @touch($patternPath . '/template.' . $templateExtension); @touch($patternPath . '/data.json'); $output->writeln('<info>Pattern `' . $cleanId . '` created</info>'); } }
joelambert/primer-core
src/Primer/Commands/PatternMake.php
PHP
mit
1,788
using System.ComponentModel.DataAnnotations; using KPI.Infrastructure; namespace KPI.Catalog.Domain { public class Brand : Entity { public string Name { get; set; } public string SeoTitle { get; set; } [StringLength(5000)] public string Description { get; set; } public bool IsPublished { get; set; } public bool IsDeleted { get; set; } } }
netcoreangular2group/Dot-Net-Core-Rest-Api
Modules/Catalog/KPI.Catalog.Domain/Brand.cs
C#
mit
409
<?php namespace App\UserBundle\DataFixtures\ORM; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use App\SettingsBundle\Entity\Settings; class SettingsData extends AbstractFixture implements OrderedFixtureInterface { public function load(ObjectManager $manager) { $entity = new Settings(); $entity->setValue("slogan"); $entity->setValue("Twój slogan"); $entity->setValue("company_name"); $entity->setValue("Nazwa Firmy"); $entity->setValue("company_host"); $entity->setValue("www.companyhost.pl"); $entity->setValue("first_name"); $entity->setValue("Imie"); $entity->setValue("last_name"); $entity->setValue("Nazwisko"); $entity->setValue("email_main"); $entity->setValue("info@gisoft.pl"); $entity->setValue("email"); $entity->setValue("ostraszewski@o2.pl"); $entity->setValue("phone"); $entity->setValue("telefin"); $entity->setValue("culture"); $entity->setValue("pl_PL"); $entity->setValue("lang"); $entity->setValue("pl"); $manager->persist($entity); $manager->flush(); } public function getOrder() { return 2; // the order in which fixtures will be loaded } }
gisoftlab/SymfonyCMS
src/App/SettingsBundle/DataFixtures/ORM/SettingsData.php
PHP
mit
1,535
Star Platinum Dark Theme for Brackets ===================================== Inspired by the Stand of Jotaro Kujo; ORAORAORA. A Brackets original. ## HTML ![HTML Screenshot](https://github.com/Brackets-Themes/StarPlatinumDark/blob/master/screenshots/html.png) ## CSS ![CSS Screenshot](https://github.com/Brackets-Themes/StarPlatinumDark/blob/master/screenshots/css.png) ## JS ![JS Screenshot](https://github.com/Brackets-Themes/StarPlatinumDark/blob/master/screenshots/js.png)
Brackets-Themes/StarPlatinumDark
README.md
Markdown
mit
480
using UnityEngine; using System.Collections; public class SelfDestructPS : MonoBehaviour { ParticleSystem ps; // Use this for initialization void Start () { ps = GetComponent<ParticleSystem>(); } // Update is called once per frame void Update () { if (!ps.IsAlive()) Destroy(gameObject); } }
thk123/WizardsRitual
Get Off My Spawn/Assets/SelfDestructPS.cs
C#
mit
338
<!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <!--[if IE]><link rel="shortcut icon" href="../../favicon.ico"><![endif]--> <link rel="icon" href="../../favicon.ico"> <script type="text/javascript" src="../../jquery-2.2.1.min.js"></script> <script type="text/javascript" src="../../header.js"></script> <script type="text/javascript" src="../../contentElements.js"></script> <script type="text/javascript" src="../../button.js"></script> <script type="text/javascript" src="../../utils.js"></script> <script type="text/javascript" src="pagescript.js"></script> <link rel="stylesheet" type="text/css" href="../../lampitosgamesStyle.css" /> <script src="https://use.typekit.net/lgz1rrt.js"></script> </head> <body> <div id="header"> <div id="headerHoverLine"></div> <div id="siteTitle"> <span id="siteTitleText">DANIEL TIMKO</span> </div> <div id="headerLinks"> <table class="headerLinksTable"> <tr class="headerLinkRow"> <td class="headerLinkCell"><a href="../.." class="headerLinkText">HOME</a></td> <td class="headerLinkCell"><a href="" id="headerLinkActive" class="headerLinkText">WORK</a></td> <td class="headerLinkCell"><a href="https://github.com/lampitosgames" class="headerLinkText">GITHUB</a></td> <td class="headerLinkCell"><a href="../.." class="headerLinkText">ABOUT</a></td> <td class="headerLinkCell"><a href="https://drive.google.com/file/d/0B2De2euVaNQJNUtFR2YwX0FKUlk/view?usp=sharing" class="headerLinkText">RESUME</a></td> <td class="headerLinkCell"><a href="mailto:dantimko1@gmail.com" class="headerLinkText">CONTACT</a></td> </tr> </table> </div> <div id="mobileHeaderButton"> <div class="hamburgerButtonWrapper"> <div class="hamburgerButton"> <div class="hamBar"></div> <div class="hamBar"></div> <div class="hamBar"></div> </div> </div> </div> </div> <div id="mobileSidebar"> <div id="mobileLinks"> <a href="../.." class="mobileSBLink"><span class="mobileSBLinkText">HOME</span></a> <a href="" class="mobileSBLink mobileSBLinkActive"><img class="mSBLImage" src="../../Thumbnails/mobileActiveLink.png" /><span class="mobileSBLinkText">WORK</span></a> <a href="https://github.com/lampitosgames" class="mobileSBLink"><span class="mobileSBLinkText">GITHUB</span></a> <a href="../.." class="mobileSBLink"><span class="mobileSBLinkText">ABOUT</span></a> <a href="https://docs.google.com/document/d/1_i5Kuef7ByQH_zhEK1aveBbx-VBZr1Qh-5-DgX-tvlA/edit?usp=sharing" class="mobileSBLink"><span class="mobileSBLinkText">RESUME</span></a> <a href="mailto:dantimko1@gmail.com" class="mobileSBLink"><span class="mobileSBLinkText">CONTACT</span></a> </div> </div> <div class="pageImageHeader"> <div class="pageImageHeaderBackground"> <img class="pageIHContent" src="background.jpg"/> </div> </div> <div class="pageFloatingTitleBox"> <div class="pageTitleTextBox"> <span class="pageTitleText"> <span> SHAPE CLICKER </span> </span> </div> <div class="pTLine"></div> <div class="titleButtons"> <a id="readMore" class="dBoxButtonWrapper"> <div class="dBoxButtonWLine1"></div><div class="dBoxButtonWLine2"></div><div class="dBoxButtonWLine3"><div class="dBBHWLineRR"></div></div><div class="dBoxButtonWLine4"><div class="dBBHWLineBL"></div><div class="dBBHWLineBR"></div></div><div class="dBoxButtonWLine5"><div class="dBBHWLineLL"></div></div><div class="dBoxButtonRLine"><div class="dBBHRLine"></div></div> <div class="dBoxButtonText"> <span> READ MORE </span> </div> </a> <a href="https://github.com/lampitosgames/ShapeClicker" id="viewCode" class="dBoxButtonWrapper"> <div class="dBoxButtonWLine1"></div><div class="dBoxButtonWLine2"></div><div class="dBoxButtonWLine3"><div class="dBBHWLineRR"></div></div><div class="dBoxButtonWLine4"><div class="dBBHWLineBL"></div><div class="dBBHWLineBR"></div></div><div class="dBoxButtonWLine5"><div class="dBBHWLineLL"></div></div><div class="dBoxButtonRLine"><div class="dBBHRLine"></div></div> <div class="dBoxButtonText"> <span> VIEW THE CODE </span> </div> </a> </div> </div> <div class="parallaxBody"> <a id="readMoreTarget"></a> <div class="mainContent" style="top: 100%"> <div class="contentSpacer"></div> <div class="contentSpacer"></div> <div class="separationLine"><div class="separationLineCenter"></div></div> <div class="contentBody"> <div class="cSpacer"></div> <div class="cTitle animIn"> <div class="cTitleDash">//</div> My First Game </div> <div class="cSpacer"></div> <div class="cTextFull animIn"> It was a drowsy Friday afternoon in astrophysics class when Gabe joked that I should program a geometry-themed knockoff of Cookie Clicker (a trending web game at the time). We passed the idea around for a few days, and I eventually took the idea seriously.  Deciding to use only code I wrote myself, I was able learn how games worked under the hood.  Shape Clicker utilizes a fully custom game engine written natively in JavaScript.  The task was daunting.  My knowledge of game design at the time was powerfully dwarfed by knowledge I lacked.  But despite adverse odds, I chose to move forward.  I googled problems I couldn’t solve.  I tried, failed, tried again, and six months later, my first game was born! </div> <div class="cSpacer"></div> <div class="cPictureFrame animIn"> <div class="cPicture"> <img class="cPictureContent" src="screen1.jpg" /> </div> </div> <div class="cSpacer"></div> <div class="separationLine"><div class="separationLineCenter"></div></div> <div style="width: 312px; height: 200px; display: block; position: relative; margin-left: auto; margin-right: auto;" class="animIn customButtonSize"> <a href="game" class="dBoxButtonWrapper"> <div class="dBoxButtonWLine1"></div><div class="dBoxButtonWLine2"></div><div class="dBoxButtonWLine3"><div class="dBBHWLineRR"></div></div><div class="dBoxButtonWLine4"><div class="dBBHWLineBL"></div><div class="dBBHWLineBR"></div></div><div class="dBoxButtonWLine5"><div class="dBBHWLineLL"></div></div><div class="dBoxButtonRLine"><div class="dBBHRLine"></div></div> <div class="dBoxButtonText"> <span> PLAY NOW </span> </div> </a> </div> <div class="separationLine"><div class="separationLineCenter"></div></div> <div class="cSpacer"></div> <div class="cTitle animIn"> <div class="cTitleDash">//</div> Features </div> <div class="cSpacer"></div> <div class="cItemHighlights"> <div class="cIHLeftList"> <div class="cIHLine cIHL1"></div> <div class="cIHItem cIHItem1 animIn"> <div class="cIHItemRedCenterLine"></div> <div class="cIHItemTitle"> Custom Game Engine </div> <div class="cIHItemDesc"> Shape Clicker runs on a game engine I coded myself. The game utilizes the HTML canvas element for visuals and a looping setTimeout() function as a game loop. </div> </div> <div class="cIHLine cIHL2"></div> <div class="cIHItem cIHItem2 animIn"> <div class="cIHItemRedCenterLine"></div> <div class="cIHItemTitle"> Advanced Trigonometry </div> <div class="cIHItemDesc"> Calculating the way an n-sided polygon rotates in an inverse plane was my biggest hurdle. While it is certainly old-hat now, it was extremely daunting at the time. </div> </div> <div class="cIHLine cIHL3"></div> <div class="cIHItem cIHItem3 animIn"> <div class="cIHItemRedCenterLine"></div> <div class="cIHItemTitle"> Supports Any Resolution </div> <div class="cIHItemDesc"> While it doesn't work on mobile, Shape Clicker was created with different sized screens in mind. The canvas will scale up to your native resolution and the game still runs flawlessly. </div> </div> <div class="cIHLine cIHL4"></div> </div> <div class="cIHRightList"> <div class="cIHLine cIHL1"></div> <div class="cIHItem cIHItem1 animIn"> <div class="cIHItemRedCenterLine"></div> <div class="cIHItemTitle"> Variable FPS </div> <div class="cIHItemDesc"> The game engine supports variable framerate. The earned score will be the same regardless of the browser refresh rate. Most indie games don't even do this! </div> </div> <div class="cIHLine cIHL2"></div> <div class="cIHItem cIHItem2 animIn"> <div class="cIHItemRedCenterLine"></div> <div class="cIHItemTitle"> Session-based Savegames </div> <div class="cIHItemDesc"> Shape Clicker uses PHP user sessions to save your data, allowing you to return later and pick up your clicking addiction right where you left off. </div> </div> <div class="cIHLine cIHL3"></div> <div class="cIHItem cIHItem3 animIn"> <div class="cIHItemRedCenterLine"></div> <div class="cIHItemTitle"> Polymorphism and OOP </div> <div class="cIHItemDesc"> This was the first project I ever used object inheritance. Every placeable object inherits properties from a shape superclass that gets used by drawing and update loops. </div> </div> <div class="cIHLine cIHL4"></div> </div> </div> </div> <div class="contentSpacer"></div> <div class="separationLine"><div class="separationLineCenter"></div></div> <div class="contentSpacer"></div> <div class="copyright">Copyright © 2016 Daniel Timko</div> <div class="contentSpacer"></div> </div> </div> </body> </html>
lampitosgames/PortfolioWebsite
Work/ShapeClicker/index.html
HTML
mit
12,417
//@@author A0147996E package seedu.address.testutil; import java.util.ArrayList; import java.util.Collections; import java.util.List; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.model.TaskManager; import seedu.address.model.task.Task; import seedu.address.model.task.UniqueTaskList; public class TypicalTestEvents { public TestEvent gym, gym2, gym3, cs2103, study, assignment, date, date2, date3, date4, meeting, familyDinner, travel, shopping, shopping2; public TypicalTestEvents() { try { gym = new EventBuilder().withName("gym").withDate("20/12/2017").withTime( "20:00").withDescription("50min workout").withStartDate("20/11/2017").withStartTime("19:00"). withTag("personal").withVenue("gym").withPriority("2").withFavorite(true) .withFinished(false).withEvent(true).build(); //gym2 and gym3 are built for findCommandTest gym2 = new EventBuilder().withName("gym").withDate("21/12/2017").withTime( "20:00").withDescription("50min workout").withStartDate("20/11/2017").withStartTime(""). withTag("personal").withVenue("gym").withPriority("2").withFavorite(false) .withFinished(false).withEvent(true).build(); gym3 = new EventBuilder().withName("gym").withDate("22/12/2017").withTime( "20:00").withDescription("50min workout").withStartDate("20/11/2017").withStartTime(""). withTag("personal").withVenue("gym").withPriority("2").withFavorite(false) .withFinished(false).withEvent(true).build(); cs2103 = new EventBuilder().withName("cs2103").withDate("01/02").withTime( "16:00").withDescription("Crazy but useful mod"). withTag("school").withVenue("icube").withPriority("1").withFavorite(true) .withStartDate("20/12/2017").withStartTime("19:00").withFinished(false).withEvent(true).build(); study = new EventBuilder().withName("study").withDate("21/03").withTime( "15:34").withDescription("Study for MTE"). withTag("school").withVenue("Central lib").withPriority("2").withFavorite(true) .withStartDate("20/12/2017").withStartTime("19:00").withFinished(false).withEvent(true).build(); assignment = new EventBuilder().withName("assignment").withDate("10/12/2017").withTime( "10:00").withDescription("IE2150"). withTag("study").withVenue("Utown").withPriority("2").withFavorite(true) .withStartDate("02/12/2017").withStartTime("19:00").withFinished(false).withEvent(true).build(); //The test tasks below are for duplicate task testing date = new EventBuilder().withName("date").withDate("14/02/2018").withTime( "12:00").withDescription("Most important day").withFinished(false). withTag("personal").withVenue("Gardens by the bay").withPriority("3") .withStartDate("11/02/2018").withStartTime("08:00").withFavorite(false).withEvent(true).build(); date2 = new EventBuilder().withName("date").withDate("14/02/2020").withTime( "12:00").withDescription("Most important day").withFinished(false). withTag("personal").withVenue("Gardens by the bay").withPriority("3") .withStartDate("tmr").withStartTime("19:00").withFavorite(false).withEvent(true).build(); date3 = new EventBuilder().withName("date").withDate("14/02/2018").withTime( "12:00").withDescription("Most important day").withFinished(false). withTag("personal").withVenue("Gardens by the bay").withPriority("3") .withStartDate("11/02/2018").withStartTime("09:00").withFavorite(false).withEvent(true).build(); date4 = new EventBuilder().withName("date").withDate("14/02/2018").withTime( "12:00").withDescription("Most important day"). withTag("private").withVenue("Gardens by the bay").withPriority("3").withFinished(false) .withStartDate("11/02/2018").withStartTime("08:00").withFavorite(false).withEvent(true).build(); //The test tasks above are for duplicate task testing meeting = new EventBuilder().withName("meeting").withDate("27/04/2017").withTime( "12:00").withDescription("Meeting old friends"). withTag("school").withVenue("PGP").withPriority("2").withFavorite(false) .withStartDate("25/04/2017").withStartTime("19:00").withFinished(false).withEvent(true).build(); familyDinner = new EventBuilder().withName("family dinner").withDate("1/1").withTime( "20:00").withDescription("Meeting families"). withTag("family").withVenue("home").withPriority("important").withFavorite(true) .withStartDate("20/12/2017").withStartTime("19:00").withFinished(false).withEvent(true).build(); travel = new EventBuilder().withName("travel").withDate("1/01/2018").withTime( "").withDescription("To Africa"). withTag("personal").withVenue("Africa").withPriority("important").withFinished(false) .withStartDate("20/12/2017").withStartTime("").withFavorite(true).withEvent(true).build(); //shopping violates start date constraint shopping = new EventBuilder().withName("shopping").withDate("1/01/2018").withTime( "").withDescription("Shopping in Airport"). withTag("personal").withVenue("Airport").withPriority("3").withFavorite(true) .withStartDate("20/12/2018").withStartTime("").withFinished(false).withEvent(true).build(); } catch (IllegalValueException e) { throw new IllegalStateException("Unable to build task"); } } public static void loadTaskManagerWithSampleData(TaskManager tm) { for (TestEvent task : new TypicalTestEvents().getTypicalEvents()) { try { tm.addTask(new Task(task)); } catch (UniqueTaskList.DuplicateTaskException e) { assert false : "not possible"; } catch (IllegalValueException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public TestEvent[] getTypicalEvents() { TestEvent[] events = {gym, gym2, gym3, cs2103, study, assignment, date}; List<TestEvent> listOfEvents = asList(events); listOfEvents = sort(listOfEvents); return listOfEvents.toArray(new TestEvent[listOfEvents.size()]); } private <T> List<T> asList(T[] objs) { List<T> list = new ArrayList<>(); for (T obj : objs) { list.add(obj); } return list; } private static List<TestEvent> sort(List<TestEvent> list) { Collections.sort(list, (TestEvent t1, TestEvent t2) -> t1.getTag().compareTo(t2.getTag())); Collections.sort(list, (TestEvent t1, TestEvent t2) -> t1.getName().compareTo(t2.getName())); Collections.sort(list, (TestEvent t1, TestEvent t2) -> t1.getTime().compareTo(t2.getTime())); Collections.sort(list, (TestEvent t1, TestEvent t2) -> -t1.getPriority().compareTo(t2.getPriority())); Collections.sort(list, (TestEvent t1, TestEvent t2) -> t1.getDate().compareTo(t2.getDate())); return list; } public TaskManager getTypicalTaskManager() { TaskManager tm = TaskManager.getStub(); loadTaskManagerWithSampleData(tm); return tm; } }
CS2103JAN2017-W10-B1/main
src/test/java/seedu/address/testutil/TypicalTestEvents.java
Java
mit
7,866
/*! * datastructures-js * priorityQueue * Copyright(c) 2015 Eyas Ranjous <eyas@eyasranjous.info> * MIT Licensed */ var queue = require('./queue'); function priorityQueue() { 'use strict'; var prototype = queue(), // queue object as the prototype self = Object.create(prototype); // determine the top priority element self.getTopPriorityIndex = function() { var length = this.elements.length; if (length > 0) { var pIndex = 0; var p = this.elements[0].priority; for (var i = 1; i < length; i++) { var priority = this.elements[i].priority; if (priority < p) { pIndex = i; p = priority; } } return pIndex; } return -1; }; self.enqueue = function(el, p) { p = parseInt(p); if (isNaN(p)) { throw { message: 'priority should be an integer' }; } this.elements.push({ // element is pushed as an object with a priority element: el, priority: p }); }; self.dequeue = function() { var pIndex = self.getTopPriorityIndex(); return pIndex > -1 ? this.elements.splice(pIndex, 1)[0].element : null; }; self.front = function() { return !this.isEmpty() ? this.elements[0].element : null; }; self.back = function() { return !self.isEmpty() ? this.elements[this.elements.length - 1].element : null; }; return self; } module.exports = priorityQueue;
Bryukh/datastructures-js
lib/priorityQueue.js
JavaScript
mit
1,632
# Bulls and Cows Bulls and Cows game coded in python Simply by using **random** and GUI **wx** library ! See this game running by **Telegram bot** (telepot) <https://github.com/Ezpy/telepot/blob/master/examples/chat/bullsandcows.py> 숫자 야구 게임 - 파이썬으로 코딩되어있고 랜덤, GUI, wx 라이브러리를 사용합니다. Why BestPick function is just random? - If you calculate all left 4 digits number possibilities with every 4 digits guesses, the result number of possibilities is same. BestPick 함수가 그냥 랜덤으로 하나 뽑는 이유? - 남은 경우의 수에 모든 4자리 숫자를 대입해보면 어떤걸 하든지 결과는 똑같음. [Screenshot] ![alt tag](https://github.com/Ezpy/BullsandCows/blob/master/Screenshot.png)
Ezpy/BullsandCows
README.md
Markdown
mit
778
# Lexigrapher [![Code Climate](https://codeclimate.com/github/baweaver/lexigrapher.png)](https://codeclimate.com/github/baweaver/lexigrapher) Find the type of a string. In some cases, you have a data type in a string, and you know exactly what it is. Now Ruby can too! It's as simple as: ```ruby Lexigrapher::Parser.new('0xFFF').type ``` ...and voila! You get your type as a symbol! ```ruby :integer ``` ## What does it try and match against? To quote the source, and to give you the parser order: ```ruby def methods [ :int?, :float?, :symbol?, :hash?, :array?, # Primatives :date?, :phone?, :email?, :url?, :ipv4?, :ipv6?, :gender?, # Extensions :str?, :nil?, :unknown? # Primitives fallback ] end ``` Want more checks? Log an issue and let me know!
baweaver/lexigrapher
README.md
Markdown
mit
829
# DeletionTool A gadget for file/directory deletion in Windows. Windows下的删除文件/文件夹的小工具。 [Download](https://github.com/differentrain/DeletionTool/raw/master/src/DeletionTool/bin/Release/DeletionTool.zip) ## Updates 更新 `2017.09.12` New Functionality: drag&drop files or(and) directories on exe, program shoud delete object without GUI, instead of the system sound of "EmptyRecycleBin". `2017.09.12` 新增功能: 拖拽文件或(和)文件夹到exe上面,程序会在不使用GUI的情况下将其删除, 并播放系统声音"EmptyRecycleBin". ## Notice 须知 `DeletionTool` can delete the file/directory that is currently in use or end with special characters, such as `..`, But make it clear that you know what you are doing when using it. `DeletionTool` 可以删除以特殊的字符结尾(如`..`)或正在使用的文件/文件夹, 但使用时应清楚地认识到到自己是在做什么。 ## Demonstrate 演示   ![image](https://github.com/differentrain/DeletionTool/raw/master/imgs/333.gif)   *** ![image](https://github.com/differentrain/DeletionTool/raw/master/imgs/11111.gif)   *** ![image](https://github.com/differentrain/DeletionTool/raw/master/imgs/222.gif)
differentrain/DeletionTool
README.md
Markdown
mit
1,234
<div class="holder padding-zero"> <div class="events-plugin" ng-if="WidgetEvent.event"> <div class="plugin-banner clearfix border-bottom-grey" > <img ng-if="WidgetEvent.data.design.eventTitleImage" load-image="239x1" crop-width="342" crop-height="150" crop-type="crop" data-final-src="{{WidgetEvent.data.design.eventTitleImage}}"> </div> <div class="padded event-intro clearfix padding-bottom-five"> <div class="col-xs-3 event-date text-center pull-left"> <h3 class="margin-zero text-primary text-overlay"> {{WidgetEvent.event.startDate | getMonthFromTimestamp}}</h3> <h1 class="margin-zero text-primary text-overlay"> {{WidgetEvent.event.startDate | getDateFromTimestamp}}</h1> </div> <div class="col-xs-9 text-left pull-left text-overlay"> <p class="margin-bottom-zero ellipsis text-overlay">{{WidgetEvent.event .SUMMARY}}</p> <p class="margin-zero text-overlay" ng-if="WidgetEvent.event.endDate && !WidgetEvent.event.isAllDay">{{WidgetEvent.event.tmpStartDate | date:'h:mm a'}} - {{WidgetEvent.event.endDate | date : 'h:mm a'}} {{WidgetEvent.event.endDate | getTimeZone}}</p> <p class="margin-zero text-overlay" ng-if="WidgetEvent.event.endDate && WidgetEvent.event.isAllDay"> {{WidgetEvent.event.tmpStartDate | date:'mediumDate'}} - {{WidgetEvent.event.endDate | date : 'mediumDate'}}</p> <a class="text-primary text-overlay" href="javascript:void(0)" ng-click="WidgetEvent.addEventsToCalendar(WidgetEvent.event)">Add to Calendar</a> </div> </div> <div class="text-left padded padding-bottom-zero clearfix text-overlay"> <p ng-if="WidgetEvent.event.SUMMARY.length>35">{{WidgetEvent.event.SUMMARY}}</p> <p ng-bind-html="eventDescription" class="break-word"></p> <p class="break-word">{{WidgetEvent.event.LOCATION}}</p> </div> </div> </div>
BuildFire/eventsFeedPlugin
widget/templates/Event_Item_1.html
HTML
mit
2,002
<!DOCTYPE html> <!-- To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Templates and open the template in the editor. --> <html> <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div id="demo"></div> <script src="dist/ogv.js"></script> <script> var player = new OGVPlayer({ enableWebM: true }); // Now treat it just like a video or audio element document.getElementById("demo").appendChild(player); player.src = '../media//Curiosity\'s_Seven_Minutes_of_Terror.ogv.240p.webm'; player.play(); player.addEventListener('ended', function () { }); </script> </body> </html>
jscodec/jsvpx
examples/ogv-simple/index.html
HTML
mit
928
package org.runetranscriber.core; import java.awt.Font; /** * Defines methods required by a rune to font letter transcriber. * * @param <R> Rune type parameter. * @param <F> Font letter type parameter. */ public interface FontTranscriber<R extends Rune, F extends FontLetter> extends Transcriber<RuneList<R>, R, FontLetterList<F>, F> { /** * @return the default font size. */ float getDefaultFontSize(); /** * @return font. */ Font getFont(); /** * @param fontSize Font size. * * @return font. */ Font getFont(float fontSize); /** * @param rune From rune. * @param fontLetter To font letter. */ void put(final R rune, final F fontLetter); }
jmthompson2015/runetranscriber
core/src/main/java/org/runetranscriber/core/FontTranscriber.java
Java
mit
748
Minder.run(function($rootScope) { angular.element("body").fadeIn(300); // Add runtime tasks here });
jeremythuff/minderui
app/config/runTime.js
JavaScript
mit
107
<!DOCTYPE html> <html ng-app="angular-events"> <head> <style> .item-block { min-height: 50px; min-width: 50px; background-color: red; margin: 10px; } .ng-enter { transition:10.4s ease all; opacity:0; transform:translateX(-100%); } .ng-enter.ng-enter-active { opacity:1; transform:translateX(10%); } .ng-leave { transition:0.4s ease all; opacity:1; transform:translateX(0); } .ng-leave.ng-leave-active { opacity:0; transform:translateX(-100%); } .ng-hide-remove { transition: 0.4s ease all; opacity: 0; transform:translateY(-100%); } .ng-hide-remove-active { opacity: 1; transform:translateY(0); } .ng-hide-add { transition: 0.4s ease all; opacity: 1; transform:translateY(0); } .ng-hide-add-active { opacity: 0; transform:translateY(-100%); } .ng-enter-stagger, .ng-leave-stagger { transition-delay: 0.2s; transition-duration:0; } </style> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular-animate.min.js"></script> <script type="text/javascript"> var app = angular.module('angular-events', ['ngAnimate']) .controller('mainCtrl', function ($scope, $log, $timeout) { $scope.isShowing = true; // $scope.items = []; $timeout(function() { $scope.items = [1,2,3,4,5,6]; },400); $scope.toggleFade = function () { $scope.isShowing = !$scope.isShowing; }; $scope.addRow = function () { $scope.items.push("new item"); }; $scope.removeRow = function () { $scope.items.pop(); }; }); </script> </head> <body ng-app="angular-events" ng-cloak> <div class="container" ng-controller="mainCtrl"> <h1 ng-show="isShowing"> I have fancy fade animations and stuff </h1> <button type="button" class="btn btn-default" ng-click="toggleFade()"> fancy fade animation </button> <ul> <li ng-repeat="item in items" class="item-block" ng-bind="item"></li> </ul> <div> <button ng-click="addRow()" type="button"> add item </button> <button ng-click="removeRow()" type="button"> remove row </button> </div> </div> </body> </html>
jjs5286/angular-unit-1
unit1/animations/animations1.html
HTML
mit
2,701
# -*- coding: utf-8 -*- """ Setuptools script for the xbee-helper project. """ import os from textwrap import fill, dedent try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages def required(fname): return open( os.path.join( os.path.dirname(__file__), fname ) ).read().split('\n') setup( name="xbee-helper", version="0.0.7", packages=find_packages( exclude=[ "*.tests", "*.tests.*", "tests.*", "tests", "*.ez_setup", "*.ez_setup.*", "ez_setup.*", "ez_setup", "*.examples", "*.examples.*", "examples.*", "examples" ] ), scripts=[], entry_points={}, include_package_data=True, setup_requires='pytest-runner', tests_require='pytest', install_requires=required('requirements.txt'), test_suite='pytest', zip_safe=False, # Metadata for upload to PyPI author='Ellis Percival', author_email="xbee-helper@failcode.co.uk", description=fill(dedent("""\ This project offers a high level API to an XBee device running an up-to-date version of the ZigBee firmware. It builds upon the existing XBee project by abstracting more functionality into methods. """)), classifiers=[ "Programming Language :: Python", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Topic :: Communications", "Topic :: Home Automation", "Topic :: Software Development :: Embedded Systems", "Topic :: System :: Networking" ], license="MIT", keywords="", url="https://github.com/flyte/xbee-helper" )
flyte/xbee-helper
setup.py
Python
mit
1,972
package HealthAndFitnessBlog.bindingModel; import javax.validation.constraints.NotNull; public class UserBindingModel { @NotNull private String email; @NotNull private String fullName; @NotNull private String password; @NotNull private String confirmPassword; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getConfirmPassword() { return confirmPassword; } public void setConfirmPassword(String confirmPassword) { this.confirmPassword = confirmPassword; } }
HealthAndFitnessBlog/HealthAndFitnessBlog
blog/src/main/java/HealthAndFitnessBlog/bindingModel/UserBindingModel.java
Java
mit
939
<?php namespace Acf\AdminBundle\Form\Autoinc; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; /** * * @author sasedev <seif.salah@gmail.com> */ class UpdateTForm extends AbstractType { /** * Form builder * * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('description', TextareaType::class, array( 'label' => 'Autoinc.description.label', 'required' => false )); } /** * * @return string */ public function getName() { return 'AutoincUpdateForm'; } /** * * {@inheritdoc} @see AbstractType::getBlockPrefix() */ public function getBlockPrefix() { return $this->getName(); } /** * get the default options * * @return multitype:string multitype:string */ public function getDefaultOptions() { return array( 'validation_groups' => array( 'Default' ) ); } /** * * {@inheritdoc} @see AbstractType::configureOptions() */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults($this->getDefaultOptions()); } }
sasedev/acf-expert
src/Acf/AdminBundle/Form/Autoinc/UpdateTForm.php
PHP
mit
1,494
package scratchlib.objects; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import scratchlib.project.ScratchProject; import scratchlib.writer.ScratchOutputStream; /** * Maps instances of {@link ScratchObject} to reference IDs, offering insertion, * lookup and iteration methods. */ public class ScratchReferenceTable implements Iterable<ScratchObject> { private final List<ScratchObject> references = new ArrayList<>(); /** * Performs a reference lookup for the given {@link ScratchObject}. * * @param object The object to look up. * @return The object's reference ID, or -1 if not found. */ public int lookup(ScratchObject object) { int index = references.indexOf(object); return index == -1 ? index : index + 1; } /** * Performs an object lookup for the given reference ID. * * @param referenceID The ID to look up. * @return The referenced object, or null if not found. */ public ScratchObject lookup(int referenceID) { if (referenceID < 1 || referenceID > references.size()) { return null; } return references.get(referenceID - 1); } /** * Inserts the given {@link ScratchObject} into this reference table. The ID * is determined automatically. True is returned if the object was newly * inserted, false otherwise. * * @param object The object to insert. * @return Whether the element was newly inserted (true), or not (false). */ public boolean insert(ScratchObject object) { if (references.contains(object)) { return false; } references.add(object); return true; } /** * @return The number of references stored. */ public int size() { return references.size(); } @Override public Iterator<ScratchObject> iterator() { return references.iterator(); } /** * Convenience method. If the object is inline, it is written out directly * via its {@code writeTo(...)} method; otherwise, the reference stored for * it in this table is written instead. * * <p> * This is useful for fields of other objects. * * @param o The object to write. * @param out The stream to write to. * @param project The project the object is part of. * @throws IOException */ public void writeField(ScratchObject o, ScratchOutputStream out, ScratchProject project) throws IOException { int ref = lookup(o); if (!(o instanceof IScratchReferenceType) || ref < 1) { o.writeTo(out, this, project); return; } out.write(99); out.write24bitUnsignedInt(ref); } }
JangoBrick/scratchlib
src/main/java/scratchlib/objects/ScratchReferenceTable.java
Java
mit
2,833
#include "choice.h" #include "header.h" #include "destination.h" #include <cassert> #include "parse_tree_visitor.h" namespace fabula { namespace parsing { namespace node { Choice::Choice(const std::shared_ptr<Header>& header, const std::shared_ptr<Destination>& destination) : header(header), destination(destination) {} ParseNode::NodeType Choice::nodeType() { return NodeType::Choice; } } } }
lightofanima/Fabula
src/ParseNodes/choice.cpp
C++
mit
517
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Bones</title> <link rel="stylesheet" type="text/css" href="/assets/stylesheets/main.css"> </head> <body> <header> <h1>Bones - A webapp template for the Go programming language</h1> <a href="/">Home</a> <a href="/logout" rel="nofollow">Logout</a> </header> {{template "messages.html" .}}
peterskeide/bones
templates/header.html
HTML
mit
360
var Scene = function(gl) { this.noiseTexture = new Texture2D(gl, "media/lab4_noise.png"); this.brainTexture = new Texture2D(gl, "media/brain-at_1024.jpg"); this.brainTextureHD = new Texture2D(gl, "media/brain-at_4096.jpg"); this.matcapGreen = new Texture2D(gl, "media/Matcap/matcap4.jpg"); this.skyCubeTexture = new TextureCube(gl, [ "media/posx.jpg", "media/negx.jpg", "media/posy.jpg", "media/negy.jpg", "media/posz.jpg", "media/negz.jpg",] ); this.timeAtLastFrame = new Date().getTime(); this.vsEnvirCube = new Shader(gl, gl.VERTEX_SHADER, "cube_vs.essl"); this.fsEnvirCube = new Shader(gl, gl.FRAGMENT_SHADER, "cube_fs.essl"); this.vsNoiseShader = new Shader(gl, gl.VERTEX_SHADER, "vsNoiseShader.essl"); this.fsNoiseShader = new Shader(gl, gl.FRAGMENT_SHADER, "fsNoiseShader.essl"); this.cubeEnvirProgram = new Program (gl, this.vsEnvirCube, this.fsEnvirCube); this.noiseProgram = new Program (gl, this.vsNoiseShader, this.fsNoiseShader); this.quadGeometry = new QuadGeometry(gl); this.brainMaterial = new Material (gl, this.noiseProgram); this.brainMaterial.background.set (this.skyCubeTexture); this.brainMaterial.noiseTexture.set (this.noiseTexture); this.brainMaterial.brainTex.set (this.brainTextureHD); //this.brainMaterial.brainTex.set (this.brainTexture); this.brainMaterial.matcapTex.set (this.matcapGreen); this.NoiseMaterial = new Material(gl, this.noiseProgram); this.NoiseMaterial.background.set (this.skyCubeTexture); this.NoiseMaterial.noiseTexture.set (this.noiseTexture); this.NoiseMesh = new Mesh (this.quadGeometry, this.brainMaterial); this.NoiseObj = new GameObject2D(this.NoiseMesh); this.cubeMaterial = new Material(gl, this.cubeEnvirProgram); this.cubeMaterial. envMapTexture.set ( this.skyCubeTexture); this.envirMesh = new Mesh (this.quadGeometry, this.cubeMaterial); this.environment = new GameObject2D (this.envirMesh); this.gameObjects = [this.NoiseObj /*, this.environment*/]; this.camera = new PerspectiveCamera(); gl.disable(gl.BLEND); gl.enable(gl.DEPTH_TEST); gl.blendFunc( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); this.elapsedTime = 0.0; this.zSetTime = 0.0; this.zValue = 0; }; Scene.prototype.update = function(gl, keysPressed) { //jshint bitwise:false //jshint unused:false var timeAtThisFrame = new Date().getTime(); var dt = (timeAtThisFrame - this.timeAtLastFrame) / 1000.0; this.elapsedTime += dt; this.timeAtLastFrame = timeAtThisFrame; this.zSetTime += dt; if (this.zSetTime > 0.03) { this.zSetTime = 0.0 //this.brainMaterial.z.set (this.zValue); this.zValue += 1; } // clear the screen gl.clearColor(0.6, 0.0, 0.3, 1.0); gl.clearDepth(1.0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); this.camera.move(dt, keysPressed); for(var i=0; i<this.gameObjects.length; i++) { this.gameObjects[i].move (dt); this.gameObjects[i].updateModelTransformation (); this.gameObjects[i].draw(this.camera); } }; Scene.prototype.mouseMove = function(event) { this.camera.mouseMove(event); } Scene.prototype.mouseDown = function(event) { this.camera.mouseDown(event); } Scene.prototype.mouseUp = function(event) { this.camera.mouseUp(event); }
RyperHUN/RenderingExamples
RayMarchingVolumetric_Brain/js/Scene.js
JavaScript
mit
3,266
package nsqd // the core algorithm here was borrowed from: // Blake Mizerany's `noeqd` https://github.com/bmizerany/noeqd // and indirectly: // Twitter's `snowflake` https://github.com/twitter/snowflake // only minor cleanup and changes to introduce a type, combine the concept // of workerID + datacenterId into a single identifier, and modify the // behavior when sequences rollover for our specific implementation needs import ( "encoding/hex" "errors" "time" ) const ( workerIDBits = uint64(10) sequenceBits = uint64(12) workerIDShift = sequenceBits timestampShift = sequenceBits + workerIDBits sequenceMask = int64(-1) ^ (int64(-1) << sequenceBits) // ( 2012-10-28 16:23:42 UTC ).UnixNano() >> 20 twepoch = int64(1288834974288) ) var ErrTimeBackwards = errors.New("time has gone backwards") var ErrSequenceExpired = errors.New("sequence expired") var ErrIDBackwards = errors.New("ID went backward") type guid int64 type guidFactory struct { sequence int64 lastTimestamp int64 lastID guid } func (f *guidFactory) NewGUID(workerID int64) (guid, error) { // divide by 1048576, giving pseudo-milliseconds // ts 是 nano » 20, 也就是 1 ts = 1048576 nano, 而 1 milliseconds = 1000000 nano; // 这就是注释里说的 “giving pseudo-milliseconds” ,ts 近似等于 1毫秒 ts := time.Now().UnixNano() >> 20 if ts < f.lastTimestamp { return 0, ErrTimeBackwards } if f.lastTimestamp == ts { f.sequence = (f.sequence + 1) & sequenceMask if f.sequence == 0 { return 0, ErrSequenceExpired } } else { f.sequence = 0 } f.lastTimestamp = ts // id = [ 37位ts + ?位 workerId + 12位 sequence ] // workerid 必须 小于 1024, 也就是10位; 而这个是靠启动nsqd的时候检查配置项实现的 id := guid(((ts - twepoch) << timestampShift) | (workerID << workerIDShift) | f.sequence) if id <= f.lastID { return 0, ErrIDBackwards } f.lastID = id return id, nil } func (g guid) Hex() MessageID { var h MessageID var b [8]byte b[0] = byte(g >> 56) b[1] = byte(g >> 48) b[2] = byte(g >> 40) b[3] = byte(g >> 32) b[4] = byte(g >> 24) b[5] = byte(g >> 16) b[6] = byte(g >> 8) b[7] = byte(g) hex.Encode(h[:], b[:]) return h }
feixiao/nsq-0.3.7
nsqd/guid.go
GO
mit
2,223
# Shouty Original project can be found at: https://github.com/cucumber-ltd/shouty.rb
paulpires/bddTraining
README.md
Markdown
mit
87
from .base import KaffeError from .core import GraphBuilder, DataReshaper, NodeMapper from . import tensorflow
polltooh/FineGrainedAction
nn/kaffe/__init__.py
Python
mit
111
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _imageWriter = require('./image-writer'); var _imageWriter2 = _interopRequireDefault(_imageWriter); var Message = (function (_DBModel) { _inherits(Message, _DBModel); function Message(conf) { _classCallCheck(this, Message); _get(Object.getPrototypeOf(Message.prototype), 'constructor', this).call(this); this.writer = new _imageWriter2['default'](conf.IMAGE_PATH); } _createClass(Message, [{ key: 'create', value: function create(user, text) { return regeneratorRuntime.async(function create$(context$2$0) { while (1) switch (context$2$0.prev = context$2$0.next) { case 0: context$2$0.next = 2; return regeneratorRuntime.awrap(this.query.getOne('createMessage', [user.id, text])); case 2: return context$2$0.abrupt('return', context$2$0.sent); case 3: case 'end': return context$2$0.stop(); } }, null, this); } }, { key: 'createImage', value: function createImage(user, raw, type) { var name; return regeneratorRuntime.async(function createImage$(context$2$0) { while (1) switch (context$2$0.prev = context$2$0.next) { case 0: context$2$0.next = 2; return regeneratorRuntime.awrap(this.writer.write(raw, type)); case 2: name = context$2$0.sent; context$2$0.next = 5; return regeneratorRuntime.awrap(this.query.getOne('createImageMessage', [user.id, 'img/' + name])); case 5: return context$2$0.abrupt('return', context$2$0.sent); case 6: case 'end': return context$2$0.stop(); } }, null, this); } }, { key: 'getLatest', value: function getLatest(id) { return regeneratorRuntime.async(function getLatest$(context$2$0) { while (1) switch (context$2$0.prev = context$2$0.next) { case 0: if (!id || id == null || id < 1) id = 999999; context$2$0.next = 3; return regeneratorRuntime.awrap(this.query.getAll('getMessageInterval', [id])); case 3: return context$2$0.abrupt('return', context$2$0.sent); case 4: case 'end': return context$2$0.stop(); } }, null, this); } }]); return Message; })(DBModel); exports['default'] = Message; module.exports = exports['default'];
ordinarygithubuser/chat-es7
server/model/message.js
JavaScript
mit
4,285
require 'test_helper' class PlatoonsControllerTest < ActionController::TestCase test "should get index" do get :index assert_response :success assert_not_nil assigns(:platoons) end test "should get new" do get :new assert_response :success end test "should create platoon" do assert_difference('Platoon.count') do post :create, :platoon => { } end assert_redirected_to platoon_path(assigns(:platoon)) end test "should show platoon" do get :show, :id => platoons(:one).to_param assert_response :success end test "should get edit" do get :edit, :id => platoons(:one).to_param assert_response :success end test "should update platoon" do put :update, :id => platoons(:one).to_param, :platoon => { } assert_redirected_to platoon_path(assigns(:platoon)) end test "should destroy platoon" do assert_difference('Platoon.count', -1) do delete :destroy, :id => platoons(:one).to_param end assert_redirected_to platoons_path end end
looloobs/FRGCMS
test/functional/platoons_controller_test.rb
Ruby
mit
1,040
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var RandomFloat = /** @class */ (function () { function RandomFloat() { } RandomFloat.nextFloat = function (min, max) { if (max === void 0) { max = null; } if (max == null) { max = min; min = 0; } if (max - min <= 0) return min; return min + Math.random() * (max - min); }; RandomFloat.updateFloat = function (value, range) { if (range === void 0) { range = null; } if (range == null) range = 0; range = range == 0 ? 0.1 * value : range; var minValue = value - range; var maxValue = value + range; return RandomFloat.nextFloat(minValue, maxValue); }; return RandomFloat; }()); exports.RandomFloat = RandomFloat; //# sourceMappingURL=RandomFloat.js.map
pip-services/pip-services-commons-node
obj/src/random/RandomFloat.js
JavaScript
mit
892
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>poltac: 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.8.1 / poltac - 0.8.11</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> poltac <small> 0.8.11 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-09-01 14:15:30 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-09-01 14:15:30 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 camlp5 7.12 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.8.1 Formal proof management system. num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;thery@sophia.inria.fr&quot; homepage: &quot;https://github.com/thery/PolTac&quot; bug-reports: &quot;https://github.com/thery/PolTac&quot; dev-repo: &quot;git://github.com/thery/PolTac&quot; license: &quot;LGPL&quot; authors: [&quot;Laurent Théry&quot;] install: [ [make] [make &quot;install&quot;] ] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.11~&quot; &amp; &lt; &quot;8.12&quot;} ] synopsis: &quot;A set of tactics to deal with inequalities in Coq over N, Z and R:&quot; tags: [ &quot;logpath:PolTac&quot; ] url { src: &quot;https://github.com/thery/PolTac/archive/v8.11.zip&quot; checksum: &quot;md5=062ba979ec0402f9bb1e1883a2d10a1a&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-poltac.0.8.11 coq.8.8.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.8.1). The following dependencies couldn&#39;t be met: - coq-poltac -&gt; coq &gt;= 8.11~ 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-poltac.0.8.11</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"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </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.05.0-2.0.6/released/8.8.1/poltac/0.8.11.html
HTML
mit
6,467
/****************************************************************************************/ /* */ /* Pegasus */ /* */ /****************************************************************************************/ //! \file DXGpuDataDefs.h //! \author Kleber Garcia //! \date 15th July of 2014 //! \brief Pegasus directx11 definitions of gpu data for render elements #ifndef PEGASUS_DXGPUDATADEF_H #define PEGASUS_DXGPUDATADEF_H #include <d3d11.h> #include <atlbase.h> #include <d3dcompiler.h> #include "Pegasus/Graph/NodeGPUData.h" #include "Pegasus/Shader/Shared/ShaderDefs.h" #include "Pegasus/Mesh/MeshInputLayout.h" #include "Pegasus/Render/Render.h" #define MAX_UNIFORM_NAME 64 #define UNIFORM_DATA_INCREMENT 16 #define GLOBAL_UNIFORM_COUNT 8 namespace Pegasus { namespace Render { struct DXShaderGPUData { PEGASUS_GRAPH_REGISTER_GPUDATA_RTTI(DXShaderGPUData, 0x1); Pegasus::Shader::ShaderType mType; union { ID3D11PixelShader* mPixel; ID3D11VertexShader* mVertex; ID3D11DomainShader* mDomain; ID3D11HullShader* mHull; ID3D11GeometryShader* mGeometry; ID3D11ComputeShader* mCompute; ID3D11DeviceChild* mDeviceChild; }; CComPtr<ID3DBlob> mBlob; CComPtr<ID3D11ShaderReflection> mReflectionInfo; }; struct DXProgramGPUData { PEGASUS_GRAPH_REGISTER_GPUDATA_RTTI(DXProgramGPUData, 0x2); CComPtr<ID3D11PixelShader> mPixel; CComPtr<ID3D11VertexShader> mVertex; CComPtr<ID3D11DomainShader> mDomain; CComPtr<ID3D11HullShader> mHull; CComPtr<ID3D11GeometryShader> mGeometry; CComPtr<ID3D11ComputeShader> mCompute; CComPtr<ID3DBlob> mInputLayoutBlob; struct UniformReflectionData { char mUniformName[MAX_UNIFORM_NAME]; int mStageCount; struct StageBinding { Pegasus::Shader::ShaderType mPipelineType; int mBindPoint; int mBindCount; int mSize; D3D_SHADER_INPUT_TYPE mType; StageBinding() : mPipelineType(Pegasus::Shader::SHADER_STAGE_INVALID), mBindPoint(-1), mBindCount(-1), mSize(-1) { } } mStageBindings[Pegasus::Shader::SHADER_STAGES_COUNT]; UniformReflectionData() : mStageCount(0) { mUniformName[0] = '\0'; } }* mReflectionData; int mReflectionDataCount; int mReflectionDataCapacity; int mProgramGuid; int mProgramVersion; bool mProgramValid; // Global uniforms pushed by render systems. For example, cameras. Render::Uniform mGlobalUniforms[GLOBAL_UNIFORM_COUNT]; Render::BufferRef mGlobalBuffers[GLOBAL_UNIFORM_COUNT]; int mGlobalUniformCount; }; struct DXBufferGPUData { PEGASUS_GRAPH_REGISTER_GPUDATA_RTTI(DXBufferGPUData, 0x3); CComPtr<ID3D11Buffer> mBuffer; CComPtr<ID3D11UnorderedAccessView> mUav; CComPtr<ID3D11ShaderResourceView> mSrv; D3D11_BUFFER_DESC mDesc; D3D11_UNORDERED_ACCESS_VIEW_DESC mUavDesc; D3D11_SHADER_RESOURCE_VIEW_DESC mSrvDesc; }; struct DXMeshGPUData { static const int MAX_INPUT_ELEMENTS_DESC = 16; static const int INPUT_LAYOUT_TABLE_INCREMENT = 8; //input layout info PEGASUS_GRAPH_REGISTER_GPUDATA_RTTI(DXMeshGPUData, 0x4); D3D11_INPUT_ELEMENT_DESC mInputElementsDesc[MAX_INPUT_ELEMENTS_DESC]; UINT mInputElementsCount; //draw info D3D_PRIMITIVE_TOPOLOGY mTopology; bool mIsIndexed; bool mIsIndirect; // buffer description DXBufferGPUData mVertexStreams[MESH_MAX_STREAMS]; DXBufferGPUData mIndexStream; DXBufferGPUData mIndirectDrawStream; // internal buffers so user can access them. Just wrap the vertex streams. Render::BufferRef mVertexBuffers[MESH_MAX_STREAMS]; Render::BufferRef mIndexBuffer; Render::BufferRef mDrawIndirectBuffer; struct InputLayoutEntry { CComPtr<ID3D11InputLayout> mInputLayout; int mProgramGuid; int mProgramVersion; }* mInputLayoutTable; int mInputLayoutTableCount; int mInputLayoutTableCapacity; int mIndexCount; int mVertexCount; }; struct DXTextureGPUData { PEGASUS_GRAPH_REGISTER_GPUDATA_RTTI(DXTextureGPUData, 0x5); D3D11_TEXTURE2D_DESC mDesc; CComPtr<ID3D11Texture2D> mTexture; D3D11_SHADER_RESOURCE_VIEW_DESC mSrvDesc; CComPtr<ID3D11ShaderResourceView> mSrv; D3D11_UNORDERED_ACCESS_VIEW_DESC mUavDesc; CComPtr<ID3D11UnorderedAccessView> mUav; }; struct DXTextureGPUData3d { PEGASUS_GRAPH_REGISTER_GPUDATA_RTTI(DXTextureGPUData3d, 0x6); D3D11_TEXTURE3D_DESC mDesc; CComPtr<ID3D11Texture3D> mTexture; D3D11_SHADER_RESOURCE_VIEW_DESC mSrvDesc; CComPtr<ID3D11ShaderResourceView> mSrv; D3D11_UNORDERED_ACCESS_VIEW_DESC mUavDesc; CComPtr<ID3D11UnorderedAccessView> mUav; }; struct DXRenderTargetGPUData { PEGASUS_GRAPH_REGISTER_GPUDATA_RTTI(DXRenderTargetGPUData, 0x7); enum Dim { Dim_2d, Dim_3d }; Dim mDim; DXTextureGPUData mTextureView; DXTextureGPUData3d mTextureView3d; D3D11_RENDER_TARGET_VIEW_DESC mDesc; CComPtr<ID3D11RenderTargetView> mRenderTarget; }; struct DXDepthStencilGPUData { PEGASUS_GRAPH_REGISTER_GPUDATA_RTTI(DXDepthStencilGPUData, 0x8); bool mUseStencil; D3D11_TEXTURE2D_DESC mTextureDesc; CComPtr<ID3D11Texture2D> mTexture; D3D11_SHADER_RESOURCE_VIEW_DESC mSrvDepthDesc; CComPtr<ID3D11ShaderResourceView> mSrvDepth; D3D11_SHADER_RESOURCE_VIEW_DESC mSrvStencilDesc; CComPtr<ID3D11ShaderResourceView> mSrvStencil; D3D11_DEPTH_STENCIL_VIEW_DESC mDepthViewDesc; CComPtr<ID3D11DepthStencilView> mDepthView; }; struct DXSampler { PEGASUS_GRAPH_REGISTER_GPUDATA_RTTI(DXSampler, 0x9); D3D11_SAMPLER_DESC mDesc; CComPtr<ID3D11SamplerState> mSampler; }; void DXInitBufferData(DXBufferGPUData& outBuffer); void DXCreateBuffer( ID3D11Device * device, int bufferSize, int elementCount, bool isDynamic, void* initData, D3D11_BIND_FLAG bindFlags, DXBufferGPUData& outBuffer, UINT extraMiscFlags = 0); } //namespace Render } //namespace Pegasus #endif
kecho/Pegasus
Source/Pegasus/Render/DX11/DXGpuDataDefs.h
C
mit
6,531
class AddFleetNameAssetFleets < ActiveRecord::Migration[4.2] def change add_column :asset_fleets, :fleet_name, :string, after: :agency_fleet_id end end
camsys/transam_transit
db/migrate/20180124192034_add_fleet_name_asset_fleets.rb
Ruby
mit
160
#!/usr/bin/env python ### # (C) Copyright (2012-2015) Hewlett Packard Enterprise Development LP # # 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. ### from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from builtins import range from future import standard_library standard_library.install_aliases() import sys PYTHON_VERSION = sys.version_info[:3] PY2 = (PYTHON_VERSION[0] == 2) if PY2: if PYTHON_VERSION < (2, 7, 9): raise Exception('Must use Python 2.7.9 or later') elif PYTHON_VERSION < (3, 4): raise Exception('Must use Python 3.4 or later') import hpOneView as hpov from pprint import pprint def acceptEULA(con): # See if we need to accept the EULA before we try to log in con.get_eula_status() try: if con.get_eula_status() is True: print('EULA display needed') con.set_eula('no') except Exception as e: print('EXCEPTION:') print(e) def login(con, credential): # Login with givin credentials try: con.login(credential) except: print('Login failed') def add_network_set(net, name, networks, minbw, maxbw): nset = [] maxbw = int(maxbw * 1000) minbw = int(minbw * 1000) if networks: enets = net.get_enet_networks() for enet in enets: if enet['name'] in networks: nset.append(enet['uri']) nset = net.create_networkset(name, networkUris=nset, typicalBandwidth=minbw, maximumBandwidth=maxbw) if 'connectionTemplateUri' in nset: print('\n\nName: ', nset['name']) print('Type: ', nset['type']) print('Description: ', nset['description']) print('State: ', nset['state']) print('Status: ', nset['status']) print('Created: ', nset['created']) print('Uri: ', nset['uri']) print('networkUris: ') for net in nset['networkUris']: print('\t\t', net) else: pprint(nset) def main(): parser = argparse.ArgumentParser(add_help=True, formatter_class=argparse.RawTextHelpFormatter, description=''' Define new Network Set Usage: ''') parser.add_argument('-a', dest='host', required=True, help=''' HP OneView Appliance hostname or IP address''') parser.add_argument('-u', dest='user', required=False, default='Administrator', help=''' HP OneView Username''') parser.add_argument('-p', dest='passwd', required=True, help=''' HP OneView Password''') parser.add_argument('-c', dest='cert', required=False, help=''' Trusted SSL Certificate Bundle in PEM (Base64 Encoded DER) Format''') parser.add_argument('-y', dest='proxy', required=False, help=''' Proxy (host:port format''') parser.add_argument('-j', dest='domain', required=False, default='Local', help=''' HP OneView Authorized Login Domain''') parser.add_argument('-n', dest='network_set_name', required=True, help=''' Name of the network set''') parser.add_argument('-l', dest='list_of_networks', required=False, nargs='+', help=''' List of network names to add to the network set, seperated by spaces. For example: -t "Net One" "Net Two" "Net Three"''') parser.add_argument('-b', dest='prefered_bandwidth', type=float, required=False, default=2.5, help=''' Typical bandwidth between .1 and 20 Gb/s''') parser.add_argument('-m', dest='max_bandwidth', type=float, required=False, default=10, help=''' Maximum bandwidth between .1 and 20 Gb/s''') args = parser.parse_args() credential = {'authLoginDomain': args.domain.upper(), 'userName': args.user, 'password': args.passwd} con = hpov.connection(args.host) net = hpov.networking(con) if args.proxy: con.set_proxy(args.proxy.split(':')[0], args.proxy.split(':')[1]) if args.cert: con.set_trusted_ssl_bundle(args.cert) login(con, credential) acceptEULA(con) if args.prefered_bandwidth < .1 or args.prefered_bandwidth > 20: print('Error, prefered bandwidth must be between .1 and 20 Gb/s') sys.exit() if args.max_bandwidth < .1 or args.max_bandwidth > 20: print('Error, max bandwidth must be between .1 and 20 Gb/s') sys.exit() if args.prefered_bandwidth > args.max_bandwidth: print('Error, prefered bandwidth must be less than or equal ' 'to the maximum bandwidth') sys.exit() add_network_set(net, args.network_set_name, args.list_of_networks, args.prefered_bandwidth, args.max_bandwidth) if __name__ == '__main__': import sys import argparse sys.exit(main()) # vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
ufcg-lsd/python-hpOneView
examples/scripts/define-network-set.py
Python
mit
6,316
require 'spec_helper' describe RBattlenet::D3::Act, type: :community do describe "#find_act" do it "fetches act data" do with_connection("d3_act") do result = RBattlenet::D3::Act.find(1) expect(result.name).to eq "Act I" end end end describe "#find_multiple_acts" do it "fetches act data" do with_connection("d3_act_multiple") do collection = RBattlenet::D3::Act.find([1, 2]) expect(collection.results.map(&:name).sort).to eq ["Act I", "Act II"] end end end describe "#find_all_acts" do it "fetches all act data" do with_connection("d3_act_all") do result = RBattlenet::D3::Act.all expect(result.acts.size).to be >= 5 end end end end
wingyu/rbattlenet
spec/lib/d3/act_spec.rb
Ruby
mit
758
--- layout: page title: Gray 5th Anniversary date: 2016-05-24 author: Katherine Pope tags: weekly links, java status: published summary: Nam mollis maximus libero et rutrum. banner: images/banner/wedding.jpg booking: startDate: 03/25/2016 endDate: 03/28/2016 ctyhocn: LPLJLHX groupCode: G5A published: true --- Duis molestie non erat in vulputate. Vestibulum nec tristique orci. Maecenas egestas ligula erat, quis facilisis turpis varius efficitur. Nunc auctor, ante vitae commodo ultrices, tellus libero ultricies lacus, hendrerit aliquam felis nisi eu quam. Ut consectetur ut tortor sed feugiat. Mauris nec vestibulum odio. Mauris finibus at lorem eget consectetur. Phasellus sodales nulla ac nisl laoreet semper. Vestibulum at aliquet dolor. Vestibulum laoreet, tortor ac elementum vestibulum, eros tellus ultricies augue, et aliquet massa enim ac augue. In tincidunt massa eros, et lacinia nisl cursus eget. Quisque fringilla efficitur dolor. Etiam gravida augue non eros dignissim, ut faucibus dui mollis. Ut vitae pharetra est. Aliquam nec pharetra ante. Vivamus enim ex, laoreet in ex in, viverra commodo orci. Morbi varius porttitor nisi, non ultrices eros consequat at. Nam posuere condimentum mi at venenatis. Fusce eu sem in diam vulputate gravida. Ut molestie sed magna quis molestie. Vestibulum elementum vitae nisl ac gravida. Praesent nec lorem eget orci commodo egestas id dapibus enim. Morbi et vulputate lacus, sed sagittis ligula. Integer nulla odio, faucibus at nulla nec, dapibus egestas mi. Fusce suscipit enim enim, in imperdiet elit fringilla et. Sed tincidunt dapibus facilisis. In sollicitudin efficitur sem nec ultricies. Duis lectus tellus, pharetra sit amet venenatis sed, lacinia id justo. Nunc tincidunt hendrerit erat et vulputate. Curabitur est nibh, accumsan aliquam fermentum venenatis, finibus at velit. 1 Curabitur eu quam lobortis, elementum est non, pulvinar metus 1 Etiam auctor libero vel tellus imperdiet, a pulvinar est pharetra 1 Mauris pellentesque mi id feugiat gravida 1 Nunc mollis nibh a felis tempus, ut scelerisque sem dignissim 1 Mauris volutpat erat in purus malesuada porttitor 1 Donec ultrices orci eu ligula ullamcorper, nec vulputate tortor molestie. Mauris iaculis sem eget auctor auctor. Ut malesuada, urna in convallis accumsan, nibh nisi venenatis nisl, a consectetur massa lectus vel eros. Sed fermentum eget sem at bibendum. Curabitur ultrices ipsum eget leo semper, eget accumsan lorem interdum. Nullam lorem eros, pharetra nec quam a, sodales eleifend risus. Duis dapibus, libero vel tristique ultricies, sem tortor consequat nunc, vel tincidunt odio quam non nunc. Phasellus iaculis risus sed urna viverra, elementum imperdiet nisi malesuada. Sed iaculis gravida magna nec commodo. Aenean odio libero, lacinia ac felis vitae, tincidunt sodales felis. Aenean at turpis in est porttitor elementum sed sit amet lacus. Cras a interdum arcu. Duis lacinia massa ut mi volutpat, ac consequat augue consectetur. Nullam at ullamcorper lorem. Fusce imperdiet, leo sed dignissim egestas, nibh lectus ultricies orci, nec cursus enim massa eget sem.
KlishGroup/prose-pogs
pogs/L/LPLJLHX/G5A/index.md
Markdown
mit
3,113
--- layout: page title: Cardenas International Trade Fair date: 2016-05-24 author: Kathleen Charles tags: weekly links, java status: published summary: Phasellus ac gravida mauris. Nam. banner: images/banner/meeting-01.jpg booking: startDate: 11/27/2019 endDate: 12/01/2019 ctyhocn: BNAEAHX groupCode: CITF published: true --- Sed lectus turpis, laoreet nec ex id, pharetra hendrerit purus. Donec justo justo, scelerisque a lobortis at, suscipit ut nulla. Donec mattis sapien sit amet orci sodales malesuada. Ut vel convallis ligula. Nunc sodales ante urna, at lacinia elit consequat non. In volutpat porttitor nunc ut congue. Integer mollis ligula a orci commodo, in ullamcorper turpis pellentesque. Curabitur purus nisl, aliquet et lacus non, vulputate mattis sapien. Sed hendrerit aliquet facilisis. Praesent porta rutrum magna ut gravida. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam erat volutpat. Nulla facilisi. Ut quis rutrum mauris. Maecenas vestibulum gravida efficitur. Duis commodo, dolor in pretium ultrices, diam ex vestibulum elit, sed ullamcorper metus sapien at nunc. Aliquam rhoncus diam id nibh porta, sit amet varius ipsum auctor. Quisque non quam sapien. Nullam tristique nunc purus, vitae tempus erat faucibus eget. Proin eu urna nec est dignissim condimentum quis eget erat. * Duis rhoncus ex sit amet eros iaculis molestie * Etiam fermentum orci nec sapien varius auctor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed neque quam, sollicitudin sit amet dui ac, tempus blandit erat. Aenean faucibus, tortor eget lacinia commodo, risus massa tincidunt tellus, at fringilla ipsum felis vitae quam. Nulla nulla quam, posuere sed urna eu, accumsan aliquet nisi. Donec ullamcorper ullamcorper dolor, vel eleifend ante dapibus at. Donec non cursus diam, in sollicitudin lorem. Nunc quis faucibus ante. Morbi non dapibus ligula, at fringilla mauris. Nam commodo neque ut fringilla ultrices. Vivamus vitae congue purus. Nunc finibus ultrices dolor a commodo. Mauris sollicitudin metus non enim blandit, eget gravida libero condimentum. Donec rhoncus velit dictum commodo sagittis. Nunc commodo nulla nec nibh accumsan, a auctor dui euismod. Nullam fringilla, leo eu blandit tempus, ligula leo semper diam, eget posuere dolor neque ut ante. Proin ex tortor, luctus non fermentum id, efficitur vitae nisi. Phasellus pharetra eleifend magna, quis lacinia ante semper vel. Nullam nec faucibus dui.
KlishGroup/prose-pogs
pogs/B/BNAEAHX/CITF/index.md
Markdown
mit
2,519
<?php session_start(); require_once ('conn.php'); $action = $_GET['action']; if ($action == 'login') { $user = stripslashes(trim($_POST['usrname'])); $pass = stripslashes(trim($_POST['password'])); if (empty ($user)) { echo '用户名不能为空'; exit; } if (empty ($pass)) { echo '密码不能为空'; exit; } $sha1pass = sha1($pass); $query = mysql_query("select * from user where usrname='$user'"); $us = is_array($row = mysql_fetch_array($query)); $ps = $us ? $sha1pass == $row['passwd'] : FALSE; if ($ps) { $_SESSION['usrname'] = $row['usrname']; $_SESSION['nickname'] = $row['nickname']; $_SESSION['sex'] = $row['sex']; $_SESSION['qq'] = $row['qq']; $_SESSION['tel'] = $row['tel']; $_SESSION['birth'] = $row['birth']; $_SESSION['group'] = $row['group']; $_SESSION['information'] = $row['information']; $arr['success'] = 1; $arr['msg'] = '登录成功!'; $arr['user'] = $_SESSION['nickname']; } else { $arr['success'] = 0; $arr['msg'] = '用户名或密码错误!'; } echo json_encode($arr); } elseif($action == 'islogin') { if($_SESSION['usrname']){ $user = $_SESSION['usrname']; $query = mysql_query("select * from user where usrname='$user'"); $row = mysql_fetch_array($query); $_SESSION['nickname'] = $row['nickname']; $_SESSION['sex'] = $row['sex']; $_SESSION['qq'] = $row['qq']; $_SESSION['tel'] = $row['tel']; $_SESSION['birth'] = $row['birth']; $_SESSION['group'] = $row['group']; echo '1'; } else echo '0'; } elseif ($action == 'logout') { //退出 unset($_SESSION); session_destroy(); echo '1'; } elseif($action == 'perinfomodify') { if($_SESSION['usrname']) { $user = $_SESSION['usrname']; $pass = sha1(stripslashes(trim($_POST['password']))); $nickname = stripslashes(trim($_POST['nickname'])); $sex = stripslashes(trim($_POST['sex'])); $qq = stripslashes(trim($_POST['qq'])); $tel = stripslashes(trim($_POST['tel'])); if($_POST['birth']) $birth = date("Y-m-d",stripslashes(trim($_POST['birth']))); $group = stripslashes(trim($_POST['group'])); if($_POST['password']) mysql_query("update user set passwd='$pass' where usrname='$user'"); if($_POST['nickname']) mysql_query("update user set nickname='$nickname' where usrname='$user'"); if($_POST['sex']) mysql_query("update user set sex='$sex' where usrname='$user'"); if($_POST['qq']) mysql_query("update user set qq='$qq' where usrname='$user'"); if($_POST['tel']) mysql_query("update user set tel='$tel' where usrname='$user'"); if($_POST['birth']) mysql_query("update user set birth='$birth' where usrname='$user'"); if($_POST['group']) mysql_query("update user set group='$group' where usrname='$user'"); $arr['success'] = 1; echo json_encode($arr); } } ?>
denghongcai/GyBook
login.php
PHP
mit
2,757
using System.Diagnostics; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Wexflow.Tests { [TestClass] public class MessageCorrect { [TestInitialize] public void TestInitialize() { } [TestCleanup] public void TestCleanup() { } [TestMethod] public void MessageCorrectTest() { Stopwatch stopwatch = Stopwatch.StartNew(); Helper.StartWorkflow(117); stopwatch.Stop(); Assert.IsTrue(stopwatch.ElapsedMilliseconds > 1000); } } }
aelassas/Wexflow
src/tests/net/Wexflow.Tests/MessageCorrect.cs
C#
mit
602
! function() { "use strict"; function t(t, i, n, e) { function r(t, i) { for (var n = 0; n < t.length; n++) { var e = t[n]; i(e, n) } } function a(t) { s(t), o(t), u(t) } function s(t) { t.addEventListener("mouseover", function(i) { r(f, function(i, n) { document.getElementById('now').innerHTML = parseInt(t.getAttribute("data-index")) + 1; n <= parseInt(t.getAttribute("data-index")) ? i.classList.add("is-active") : i.classList.remove("is-active") }) }) } function o(t) { t.addEventListener("mouseout", function(t) { document.getElementById('now').innerHTML = i; -1 === f.indexOf(t.relatedTarget) && c(null, !1) }) } function u(t) { t.addEventListener("click", function(i) { i.preventDefault(), c(parseInt(t.getAttribute("data-index")) + 1, !0) }) } function c(t, a) { t && 0 > t || t > n || (void 0 === a && (a = !0), i = t || i, r(f, function(t, n) { i > n ? t.classList.add("is-active") : t.classList.remove("is-active") }), e && a/* && e(d())*/) } function d() { return i } var f = []; return function() { if (!t) throw Error("No element supplied."); if (!n) throw Error("No max rating supplied."); if (i || (i = 0), 0 > i || i > n) throw Error("Current rating is out of bounds."); for (var e = 0; n > e; e++) { var r = document.createElement("li"); r.classList.add("c-rating__item"), r.setAttribute("data-index", e), i > e && r.classList.add("is-active"), t.appendChild(r), f.push(r), a(r) } }(), { setRating: c, getRating: d } } window.rating = t }();
teacher144123/npo_map
server/js/dict/rating.min.js
JavaScript
mit
1,615
/* * The MIT License (MIT) * * Copyright (c) 2015 FTC team 6460 et. al. * * 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. */ package ftc.team6460.javadeck.api.planner; /** * Describes a peripheral that can detect imminent obstacles. */ public interface ObstacleSensor { /** * Determines if there is an obstacle that can be detected by this sensor at this relative position (or closer). * * @param pos The relative position to the current physical robot position to check. * @return True if obstacle detected, false if no obstacle detected, or this position cannot be sensed by this sensor. */ boolean checkObstacle(RelativePosition pos); }
niskyRobotics/javadeck
src/main/java/ftc/team6460/javadeck/api/planner/ObstacleSensor.java
Java
mit
1,706
<?php /* * ServerAuth v3.0 by EvolSoft * Developer: Flavius12 * Website: https://www.evolsoft.tk * Copyright (C) 2015-2018 EvolSoft * Licensed under MIT (https://github.com/EvolSoft/ServerAuth/blob/master/LICENSE) */ namespace ServerAuth\Importers; use pocketmine\command\CommandSender; use ServerAuth\ServerAuth; interface Importer { public function __construct(ServerAuth $plugin); /** * Get Importer ID * * @return string */ public function getId() : string; /** * Export data * * @param CommandSender $sender * @param array $params */ public function export(CommandSender $sender, array $params = null); }
EvolSoft/ServerAuth
ServerAuth/src/ServerAuth/Importers/Importer.php
PHP
mit
726
"use strict"; // INCLUDES if (typeof exports !== "undefined") { global.URL = require("url"); global.fs = require("fs"); global.http = require("http"); global.https = require("https"); global.WSServer = require("websocket").server; global.WebSocketConnection = require("./websocketconnection"); global.logger = require("winston"); } /** * @class WebSocketServer */ function WebSocketServer() { var self = this; var options = {}; var connectionListener = null; var wsServer = null; var webServer = null; self.setConnectionListener = function(listener) { connectionListener = listener; }; self.listen = function(opts, callback) { try { options.host = opts.host || null; options.port = opts.port || ""; options.isSsl = opts.isSsl || false; options.sslKey = opts.sslKey || ""; options.sslCert = opts.sslCert || ""; options.sslAuthCert = opts.sslAuthCert || ""; options.owner = opts.owner || "-"; options.connectionListener = opts.connectionListener || null; options.unknMethodListener = opts.unknownMethodListener || null; options.protocol = (!options.isSsl ? "ws" : "wss"); options.class = "WebSocketServer"; if (!options.isSsl) // Start a http server { webServer = http.createServer(function(request, response) { logger.log("httpServer::on(request)"); response.writeHead(501); response.end("Not implemented"); }); } else // Start a https server { console.log("Trying to start https server: "+ JSON.stringify({ key: options.sslKey, cert: options.sslCert, ca: options.sslAuthCert})); var key = fs.readFileSync(options.sslKey); var crt = fs.readFileSync(options.sslCert); var ca_crt = fs.readFileSync(options.sslAuthCert, "utf8"); //webServer = https.createServer({ key: options.sslKey, cert: options.sslCert, ca: options.sslAuthCert}, function(request, response) webServer = https.createServer({ key: key, cert: crt, ca: ca_crt}, function(request, response) { logger.log("httpsServer::on(request)"); response.writeHead(501); response.end("Not implemented"); }); } webServer.listen(options.port, options.host, 511, function() { console.log("webserver of websocketserver listening"); callback(null, true); }); webServer.on("error", function(err) { console.log(err); callback(err, null); }); // Create the WebSocket server console.log("Creating WSServer"); wsServer = new WSServer( { httpServer: webServer, autoAcceptConnections: false, keepalive: true, // Keepalive connections and keepaliveInterval: 60000, // ping them once a minute and dropConnectionOnKeepaliveTimeout: true, // drop a connection if there's no answer keepaliveGracePeriod: 10000 // within the grace period. }); // Connection request wsServer.on("request", function(request) { logger.info("wsServer::on(request)"); // Accept connection - Should the request.origin be checked somehow?{ request.reject(404, <message>); throw ""; }? try { var connection = new WebSocketConnection(); connection.setSocket(request.accept("json-rpc", request.origin)); connection.setRemoteAddress(request.remoteAddress); connection.setRemotePort(request.remotePort); connection.setOrigin(request.origin); var query = URL.parse(request.resourceURL,true).query; console.log("WebSocketServer::listen() accepting connection, given id was "+query.id); if (query && query.id) connection.setId(query.id); connectionListener.addConnection(connection); } catch(err) { console.log(err); return; } }); // Connection closed wsServer.on("close", function(webSocketConnection, closeReason, description) { logger.info("wsServer::on(close) "); }); } catch (e) { console.log(e); } }; self.close = function() { try { if(wsServer) { wsServer.shutDown(); wsServer = null; } if(webServer) { webServer.close(); webServer = null; } } catch (e) { console.log(e); } }; } if (typeof exports !== "undefined") { module.exports = WebSocketServer; }
ptesavol/webjsonrpc
websocketserver.js
JavaScript
mit
4,196
<html> <head> <script type="text/javascript" src="http://www.artstent.com/media/js/jquery.js"></script> <script type="text/javascript" src="http://www.artstent.com/media/js/jquery-ui.js"></script> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-9960860-2"); pageTracker._trackPageview("/500.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer); } catch(err) {} </script> <meta name="verify-v1" content="/ynBf3xXCYsznW1bhfUb3tB4YWIFaCTiLTov4vvhilg=" /> <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /> <link rel="stylesheet" type="text/css" href='http://www.artstent.com/media/style.css'> </link> <title>ArtsTent {% block title %}{% endblock %}</title> </head> <body> {% autoescape on %} <div id='all'> <div id='masthead'><a href='/'><img src='http://www.artstent.com/media/banner.png' /></a></div> <!-- <div id='menu'> <ul class="righthand"> </ul> <ul class="lefthand"> </ul> </div> --> <div id='logging_id'> <div id='findActor' style='float:left; display: none'> Find users tagged <form action="/accounts/full_search/" method="GET"> <!-- what_to_find=ballerina --> <select name="tag"> <!-- One of tags needs this selected="selected" to be default --> {% for t in all_tags %} <option value="{{ t }}">{{ t }}</option> {% endfor %} </select> <input type='submit' value='Search'> </form> </div> &nbsp; </div> <div id='main'> <div id='default_content'> <h1 style='padding-top:1em'>Mishap!</h1> <p style='padding-top:1.5em'>This page cannot be found, please return <a href='/'>home</a></p> <p style='padding-bottom:2em'>If you think this is a problem, please contact <a href='mailto:support@artstent.com'>support@artstent.com</a></p> </div> </div> <div id='footer'>&copy; ArtsTent</div> </div> {% endautoescape %} </body> </html>
noelevans/sandpit
poolratings/templates/500.html
HTML
mit
2,594
struct Input { enum class Device : unsigned { None, Joypad, Multitap, Mouse, SuperScope, Justifier, Justifiers, USART, }; enum class JoypadID : unsigned { B = 0, Y = 1, Select = 2, Start = 3, Up = 4, Down = 5, Left = 6, Right = 7, A = 8, X = 9, L = 10, R = 11, }; enum class MouseID : unsigned { X = 0, Y = 1, Left = 2, Right = 3, }; enum class SuperScopeID : unsigned { X = 0, Y = 1, Trigger = 2, Cursor = 3, Turbo = 4, Pause = 5, }; enum class JustifierID : unsigned { X = 0, Y = 1, Trigger = 2, Start = 3, }; Controller *port1; Controller *port2; void connect(bool port, Input::Device id); Input(); ~Input(); }; extern Input input;
ircluzar/RTC3
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/snes/system/input.hpp
C++
mit
757
/** * Layout component that queries for data * with Gatsby's useStaticQuery component * * See: https://www.gatsbyjs.org/docs/use-static-query/ */ import React from "react" import PropTypes from "prop-types" import { useStaticQuery, graphql } from "gatsby" import "./layout.css" import "./fonts.css" import "./james_daydreams.css" const Layout = ({ children }) => { const data = useStaticQuery(graphql` query SiteTitleQuery { site { siteMetadata { title } } } `) return ( <> <div style={{ margin: `200px 25% 0 30px`, maxWidth: 960, padding: `0px 1.0875rem 1.45rem`, paddingTop: 0, }} > <main>{children}</main> <footer> {console.log(data)} </footer> </div> </> ) } Layout.propTypes = { children: PropTypes.node.isRequired, } export default Layout
parisminton/james.da.ydrea.ms
src/components/layout.js
JavaScript
mit
928
#include "GameAnims.h" #include "gslib/Core/Core.h" #include "gslib/Game/GameResources.h" namespace { // Helper to easily build an AnimAsset in code class AnimAssetBuilder { public: typedef AnimAssetBuilder ThisType; AnimAssetBuilder() : mpAnimAsset(0) { } ThisType& CreateAndAdd(AnimAssetKey key) { //@TODO: This allocation is never deleted! We're ok for now since we only // allocate anim assets once at Init time, but we should clean this up somewhere. mpAnimAsset = new AnimAsset(); AnimAssetManager::AddAnimAsset(key, mpAnimAsset); return *this; } ThisType& InitPoses(const uint8* pFrameGfx, uint16 frameSize) { mpAnimAsset->mAnimPoses.Init(pFrameGfx, frameSize); return *this; } ThisType& InitTimeline(int firstFrameIndex, int numFrames, AnimTimeType unitsPerFrame, AnimCycle::Type animCycle) { mpAnimAsset->mAnimTimeline.Populate(firstFrameIndex, numFrames, unitsPerFrame, animCycle); return *this; } struct TimelineBuilder { typedef TimelineBuilder ThisType; TimelineBuilder(AnimTimeline& timeline) : mpTimeline(&timeline) { ASSERT(mpTimeline); } ThisType& Looping(bool looping) { mpTimeline->SetLooping(looping); return *this; } // Add frames with operator() ThisType& operator()(int frameIndex, AnimTimeType frameDuration) { mpTimeline->AddKeyFrame(frameIndex, frameDuration); return *this; } private: AnimTimeline* mpTimeline; }; TimelineBuilder BuildTimeline() { return TimelineBuilder(mpAnimAsset->mAnimTimeline); } private: AnimAsset* mpAnimAsset; }; // Helper to create and add four-directional animations void CreateAndAddAnimAssets4( GameActor::Type gameActor, BaseAnim::Type baseAnim, const uint8* pFrameGfx, uint16 frameSize, int firstRightFrameIndex, int numFrames, int framesToSkip, AnimTimeType unitsPerFrame, AnimCycle::Type animCycle) { AnimAssetBuilder builder; for (int d=0; d < SpriteDir::NumTypes; ++d) { const int firstFrameIndex = firstRightFrameIndex + d * (numFrames + framesToSkip); builder.CreateAndAdd(MakeAnimAssetKey(gameActor, baseAnim, (SpriteDir::Type)d)) .InitPoses(pFrameGfx, frameSize) .InitTimeline(firstFrameIndex, numFrames, unitsPerFrame, animCycle); } } // Helper to create and add non-directional animations void CreateAndAddAnimAssets1( GameActor::Type gameActor, BaseAnim::Type baseAnim, const uint8* pFrameGfx, uint16 frameSize, int firstFrameIndex, int numFrames, AnimTimeType unitsPerFrame, AnimCycle::Type animCycle) { AnimAssetBuilder builder; builder.CreateAndAdd(MakeAnimAssetKey(gameActor, baseAnim, SpriteDir::None)) .InitPoses(pFrameGfx, frameSize) .InitTimeline(firstFrameIndex, numFrames, unitsPerFrame, animCycle); } } // anonymous namespace void LoadAllGameAnimAssets() { //@TODO: Externalize into data files //@TODO: Replace SEC_TO_FRAMES() with actual frames below to reduce noise using namespace GameActor; using namespace BaseAnim; using namespace SpriteDir; AnimAssetBuilder builder; // 16x16 characters { const uint8* pFrameGfx = ResourceMgr::Instance().GetResource(GameResource::Gfx_Characters16x16).Data(); const int FrameSize = 16 * 16; // 8bpp sprites const int NumTilesPerRow = 14; // General spawn anim CreateAndAddAnimAssets1(GameActor::None, Spawn, pFrameGfx, FrameSize, 178, 4, SEC_TO_FRAMES(0.1f), AnimCycle::Once); // Manually add the Idle anims (which include a blink frame) { builder.CreateAndAdd(MakeAnimAssetKey(Hero, Idle, Right)).InitPoses (pFrameGfx, FrameSize).BuildTimeline().Looping(true)(1, SEC_TO_FRAMES(2.0f))(22, SEC_TO_FRAMES(0.2f)); builder.CreateAndAdd(MakeAnimAssetKey(Hero, Idle, Left )).InitPoses(pFrameGfx, FrameSize).BuildTimeline().Looping(true)(4, SEC_TO_FRAMES(2.0f))(23, SEC_TO_FRAMES(0.2f)); builder.CreateAndAdd(MakeAnimAssetKey(Hero, Idle, Down )).InitPoses(pFrameGfx, FrameSize).BuildTimeline().Looping(true)(7, SEC_TO_FRAMES(2.0f))(24, SEC_TO_FRAMES(0.2f)); builder.CreateAndAdd(MakeAnimAssetKey(Hero, Idle, Up )).InitPoses(pFrameGfx, FrameSize).BuildTimeline().Looping(true)(10, SEC_TO_FRAMES(0.0f)); } CreateAndAddAnimAssets4(Hero, Move, pFrameGfx, FrameSize, (0 * NumTilesPerRow + 0), 3, 0, SEC_TO_FRAMES(0.15f), AnimCycle::PingPong); CreateAndAddAnimAssets4(Hero, Attack, pFrameGfx, FrameSize, (1 * NumTilesPerRow + 0), 2, 0, SEC_TO_FRAMES(0.10f), AnimCycle::Once); CreateAndAddAnimAssets4(Hero, UseItem, pFrameGfx, FrameSize, (1 * NumTilesPerRow + 1), 1, 1, SEC_TO_FRAMES(0.20f), AnimCycle::Once); // Player Death anim (must face down) { // 7: down // 4: left // 10: up // 1: right builder.CreateAndAdd(MakeAnimAssetKey(Hero, Die, SpriteDir::None)) .InitPoses(pFrameGfx, FrameSize) .BuildTimeline() (7, SEC_TO_FRAMES(0.5f))(4, SEC_TO_FRAMES(0.05f))(10, SEC_TO_FRAMES(0.05f))(1, SEC_TO_FRAMES(0.05f)) (7, SEC_TO_FRAMES(0.05f))(4, SEC_TO_FRAMES(0.05f))(10, SEC_TO_FRAMES(0.05f))(1, SEC_TO_FRAMES(0.05f)) (7, SEC_TO_FRAMES(0.05f))(4, SEC_TO_FRAMES(0.05f))(10, SEC_TO_FRAMES(0.05f))(1, SEC_TO_FRAMES(0.05f)) (7, SEC_TO_FRAMES(0.10f))(4, SEC_TO_FRAMES(0.10f))(10, SEC_TO_FRAMES(0.10f))(1, SEC_TO_FRAMES(0.10f)) (7, SEC_TO_FRAMES(0.15f))(4, SEC_TO_FRAMES(0.15f))(10, SEC_TO_FRAMES(0.15f))(1, SEC_TO_FRAMES(0.15f)) (7, SEC_TO_FRAMES(0.15f)); } // Enemies - note that Idle is used for stunned (enemies don't really idle) CreateAndAddAnimAssets4(Rope, Idle, pFrameGfx, FrameSize, (2 * NumTilesPerRow + 0), 1, 2, SEC_TO_FRAMES(0.0f), AnimCycle::Once); CreateAndAddAnimAssets4(Rope, Move, pFrameGfx, FrameSize, (2 * NumTilesPerRow + 0), 3, 0, SEC_TO_FRAMES(0.25f), AnimCycle::PingPong); CreateAndAddAnimAssets4(Rope, Attack, pFrameGfx, FrameSize, (2 * NumTilesPerRow + 2), 1, 2, SEC_TO_FRAMES(0.25f), AnimCycle::Once); CreateAndAddAnimAssets4(Darknut, Idle, pFrameGfx, FrameSize, (3 * NumTilesPerRow + 1), 1, 2, SEC_TO_FRAMES(0.25f), AnimCycle::Loop); CreateAndAddAnimAssets4(Darknut, Move, pFrameGfx, FrameSize, (3 * NumTilesPerRow + 0), 3, 0, SEC_TO_FRAMES(0.25f), AnimCycle::PingPong); CreateAndAddAnimAssets4(Stalfos, Idle, pFrameGfx, FrameSize, (4 * NumTilesPerRow + 1), 1, 2, SEC_TO_FRAMES(0.25f), AnimCycle::Loop); CreateAndAddAnimAssets4(Stalfos, Move, pFrameGfx, FrameSize, (4 * NumTilesPerRow + 0), 3, 0, SEC_TO_FRAMES(0.25f), AnimCycle::PingPong); CreateAndAddAnimAssets4(Goriya, Idle, pFrameGfx, FrameSize, (5 * NumTilesPerRow + 1), 1, 2, SEC_TO_FRAMES(0.0f), AnimCycle::Loop); CreateAndAddAnimAssets4(Goriya, Move, pFrameGfx, FrameSize, (5 * NumTilesPerRow + 0), 3, 0, SEC_TO_FRAMES(0.25f), AnimCycle::PingPong); CreateAndAddAnimAssets4(Goriya, Attack, pFrameGfx, FrameSize, (5 * NumTilesPerRow + 12), 1, 0, SEC_TO_FRAMES(0.5f), AnimCycle::Once); CreateAndAddAnimAssets1(Gel, Idle, pFrameGfx, FrameSize, (6 * NumTilesPerRow + 5), 1, SEC_TO_FRAMES(1.0f), AnimCycle::Loop); CreateAndAddAnimAssets1(Gel, Move, pFrameGfx, FrameSize, (6 * NumTilesPerRow + 5), 3, SEC_TO_FRAMES(0.25f), AnimCycle::Loop); CreateAndAddAnimAssets1(Keese, Idle, pFrameGfx, FrameSize, (6 * NumTilesPerRow + 8), 1, SEC_TO_FRAMES(1.0f), AnimCycle::Loop); CreateAndAddAnimAssets1(Keese, Move, pFrameGfx, FrameSize, (6 * NumTilesPerRow + 8), 3, SEC_TO_FRAMES(0.25f), AnimCycle::Loop); CreateAndAddAnimAssets1(WallMaster, Idle, pFrameGfx, FrameSize, (6 * NumTilesPerRow + 2), 1, SEC_TO_FRAMES(1.0f), AnimCycle::Loop); CreateAndAddAnimAssets1(WallMaster, Move, pFrameGfx, FrameSize, (6 * NumTilesPerRow + 2), 3, SEC_TO_FRAMES(0.25f), AnimCycle::Loop); } // 32x32 characters { const uint8* pFrameGfx = ResourceMgr::Instance().GetResource(GameResource::Gfx_Characters32x32).Data(); const int FrameSize = 32 * 32; // 8bpp sprites const int NumTilesPerRow = 4; // Override global Spawn with one that fits 32x32 sprites. What sucks is we need to do this for every 32x32 character. //@TODO: Rename BaseAnim::Spawn to Spawn16x16, add BaseAnim::Spawn32x32, create its global anim here, and in the Enemy // state machine, call the specific spawn anim based on the sprite dimenions. CreateAndAddAnimAssets1(Dragon, Spawn, pFrameGfx, FrameSize, (0 * NumTilesPerRow + 0), 4, SEC_TO_FRAMES(0.1f), AnimCycle::Once); CreateAndAddAnimAssets1(Dragon, Idle, pFrameGfx, FrameSize, (1 * NumTilesPerRow + 0), 1, SEC_TO_FRAMES(1.0f), AnimCycle::Loop); CreateAndAddAnimAssets1(Dragon, Move, pFrameGfx, FrameSize, (1 * NumTilesPerRow + 0), 3, SEC_TO_FRAMES(0.25f), AnimCycle::Loop); } // 16x16 items { const uint8* pFrameGfx = ResourceMgr::Instance().GetResource(GameResource::Gfx_Items).Data(); const int FrameSize = 16 * 16; // 8bpp sprites // Boomerang { const int numFramesPerImage = 5; builder.CreateAndAdd(MakeAnimAssetKey(Boomerang, ItemDefault, SpriteDir::None)) .InitPoses(pFrameGfx, FrameSize) .BuildTimeline().Looping(true)(4, numFramesPerImage)(5, numFramesPerImage)(6, numFramesPerImage)(7, numFramesPerImage); } } }
amaiorano/ZeldaDS
Game/ZeldaDS/arm9/source/gslib/Game/GameAnims.cpp
C++
mit
9,026
#include <cmath> #include <cstring> #include <iostream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <boost/format.hpp> #include "../common/util.hpp" using namespace std; using namespace boost; int main(int argc, char* argv[]) { if (argc < 2) { cout << format("Usage: %1% <star>") % argv[0]<< endl; return EXIT_FAILURE; } const int star = atoi(argv[1]); if (!glfwInit()) { throw runtime_error("Failed to initialize GLFW"); } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow* window = glfwCreateWindow(600, 600, "Hexagram", NULL, NULL); if (!window) { throw runtime_error("Failed to open GLFW window"); } glfwMakeContextCurrent(window); glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { throw runtime_error("Failed to initialize GLEW"); } GLuint programID = buildProgram("vertex.shader", "fragment.shader"); glUseProgram(programID); glClearColor(25 / 255.0f, 25 / 255.0, 25 / 255.0, 0.0f); GLuint vertexArrayID; glGenVertexArrays(1, &vertexArrayID); glBindVertexArray(vertexArrayID); GLfloat vertexData[star * 12]; // center vertex GLfloat centerVertex[2]; centerVertex[0] = 0; centerVertex[1] = 0; for (int i = 0; i < star; i++) { vertexData[12 * i] = cos(2 * i * M_PI / star) / 2; vertexData[12 * i + 1] = sin(2 * i * M_PI / star) / 2; vertexData[12 * i + 2] = cos(2 * (i + 1) * M_PI / star) / 2; vertexData[12 * i + 3] = sin(2 * (i + 1) * M_PI / star) / 2; memcpy(vertexData + (12 * i + 4), centerVertex, sizeof(GLfloat) * 2); memcpy(vertexData + (12 * i + 6), vertexData + (12 * i), sizeof(GLfloat) * 4); vertexData[12 * i + 10] = cos((2 * i + 1) * M_PI / star); vertexData[12 * i + 11] = sin((2 * i + 1) * M_PI / star); } GLfloat colorData[star * 18]; // center color GLfloat centerColor[3]; centerColor[0] = float(rand()) / RAND_MAX; centerColor[1] = float(rand()) / RAND_MAX; centerColor[2] = float(rand()) / RAND_MAX; /* * if: most case first * * first star => generate 3 random color * other star => generate 2 random color, copy 1 color * last star => generate 1 random color, copy 2 color * */ for (int i = 0; i < star; i++) { if (i != 0) { memcpy(colorData + (18 * i), colorData + (18 * i - 6), sizeof(GLfloat) * 3); } else { colorData[0] = float(rand()) / RAND_MAX; colorData[1] = float(rand()) / RAND_MAX; colorData[2] = float(rand()) / RAND_MAX; } if (i != (star - 1)) { colorData[18 * i + 3] = float(rand()) / RAND_MAX; colorData[18 * i + 4] = float(rand()) / RAND_MAX; colorData[18 * i + 5] = float(rand()) / RAND_MAX; } else { memcpy(colorData + (18 * i + 3), colorData, sizeof(GLfloat) * 3); } memcpy(colorData + (18 * i + 6), centerColor, sizeof(centerColor)); memcpy(colorData + (18 * i + 9), colorData + (18 * i), sizeof(GLfloat) * 6); colorData[18 * i + 15] = float(rand()) / RAND_MAX; colorData[18 * i + 16] = float(rand()) / RAND_MAX; colorData[18 * i + 17] = float(rand()) / RAND_MAX; } GLuint vertexBuffer; glGenBuffers(1, &vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0); glEnableVertexAttribArray(0); GLuint colorBuffer; glGenBuffers(1, &colorBuffer); glBindBuffer(GL_ARRAY_BUFFER, colorBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(colorData), colorData, GL_STATIC_DRAW); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); glEnableVertexAttribArray(1); do { glClear(GL_COLOR_BUFFER_BIT); glDrawArrays(GL_TRIANGLES, 0, star * 12); glfwSwapBuffers(window); glfwPollEvents(); } while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0); return EXIT_SUCCESS; }
Preffer/learning-opengl
hexagram/main.cpp
C++
mit
3,982
/** * System configuration for Angular samples * Adjust as necessary for your application needs. */ (function (global) { System.config({ paths: { // paths serve as alias 'npm:': 'node_modules/' }, // map tells the System loader where to look for things map: { // our app is within the app folder app: 'app', // angular bundles '@angular/core': 'npm:@angular/core/bundles/core.umd.js', '@angular/common': 'npm:@angular/common/bundles/common.umd.js', '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js', '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js', '@angular/http': 'npm:@angular/http/bundles/http.umd.js', '@angular/router': 'npm:@angular/router/bundles/router.umd.js', '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js', // other libraries 'rxjs': 'npm:rxjs', 'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api', }, // packages tells the System loader how to load when no filename and/or no extension packages: { app: { main: 'main.js', defaultExtension: 'js' }, rxjs: { defaultExtension: 'js' }, 'angular2-in-memory-web-api': { main: './index.js', defaultExtension: 'js' } } }); })(this);
nz-andy/electron-test
systemjs.config.js
JavaScript
mit
1,529
# Yandex.Delivery API JS module A simple Yandex.Delivery API JS module # Purpose It helpes with data preparation before request and saves several hours of time. Basically, it takes the object with params you are going to send to API, sorts all the properties in an alphabetical order and calculates hash in a way, that is described in API documentation. Then just sends the request to specified endpoint. # Installation Just run `npm install --save yandex.delivery.js`. Currently module is only on npm, but you can use it outside of browserify or webpack, through global `window.Yad`. # Configuration ``` var API = new Yad({ client_id: <your_client_id>, sender_id: <your_sender_id>, api_version: <api_version> // without it, the 'last' will be used, methods: { <all_the_methods_keys> } }); ``` # Use ``` var data = { term: 'Мос', type: 'locality' }; //API.request( endpoint, data, success, error, key ); // the last param key can overwrite method key specified earlier // endpoint is the name of the method specified in API docs API.request('autocomplete', data, function( res ){ console.log( res ); }, function( err ){ console.log( err ); } ); ``` # Docs http://docs.yandexdelivery.apiary.io/ #Todo * add some console data based in env config * write tests
keeross/yandex.delivery.js
README.md
Markdown
mit
1,306
import React,{ Component } from 'react' import { {{ name }}List } from './list' export { {{ name }}List }
team4yf/yf-fpm-admin
src_template/index.js
JavaScript
mit
107
--- layout: post title: 【Python数据结构3】Binary Search categories: tags: 8_数据结构与算法 keywords: description: order: 553 --- ## 我总结的一般写法 ```py class Solution: def search(self, nums, target): # step1:定义初始搜索范围 left,right=0,len(nums)-1 if left==right:return None # step1.1 增加鲁棒性,也就是一开始即达到结束条件。需不需要视 step4是否容易写而定 # step2:定义结束时的搜索范围,一般为left==right,但某些问题未必 while left<right: mid=(left+right)//2 if nums[mid]<target: # step2.5:必须把所有的if考虑到,否则有可能死循环 left=mid+1 elif nums[mid]>target: right=mid-1 elif nums[mid]==target: # step3:搜索时遇到解,便直接返回。如果是复杂形式,注意index out of range return mid # step4:搜索结束后的小区域的情况判断。这里小区域范围为1,且必为解,因此无需多做处理。 # 一般情况下,应当处理这个小区域 mid=left # 为了可读性(代码表示的统一性)。注意决不能直接使用之前的mid,因为那个赋值是否运行是不一定的 # if nums[left]==target: # 一般情况下,与while循环中的return出口条件一致 # return mid # else:return -1 return -1 ``` ## LeetCode上的写法 ### 第一种 ```py def binarySearch(nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if len(nums) == 0: return -1 left, right = 0, len(nums) - 1 while left <= right: mid = (left + right) // 2 if nums[mid] == target: return mid elif nums[mid] < target: left = mid + 1 else: right = mid - 1 # End Condition: left > right return -1 ``` - Initial Condition: `left = 0, right = length-1` - Termination: `left > right` - Searching Left: `right = mid-1` - Searching Right: `left = mid+1` ### 第二种 - Initial Condition: `left = 0, right = length` - Termination: `left == right` - Searching Left: `right = mid` - Searching Right: `left = mid+1` ### 第三种 - Initial Condition: `left = 0, right = length-1` - Termination: `left + 1 == right` - Searching Left: `right = mid` - Searching Right: `left = mid`
guofei99987/guofei99987.github.io
_posts/[8] 数据结构与算法/实现/2018-07-06-python_binary_search.md
Markdown
mit
2,452
import argparse import io import unittest import mock import time from imagemounter.cli import AppendDictAction class AppendDictActionTest(unittest.TestCase): def test_with_comma(self): parser = argparse.ArgumentParser() parser.add_argument('--test', action=AppendDictAction) self.assertDictEqual(parser.parse_args(["--test", "x"]).test, {"*": 'x'}) self.assertDictEqual(parser.parse_args(["--test", "y=x"]).test, {"y": 'x'}) self.assertDictEqual(parser.parse_args(["--test", "y=x,z=a"]).test, {"y": 'x', "z": 'a'}) self.assertDictEqual(parser.parse_args(["--test", "*=x"]).test, {"*": 'x'}) self.assertDictEqual(parser.parse_args(["--test", "*=x", "--test", "y=a"]).test, {"*": 'x', 'y': 'a'}) self.assertDictEqual(parser.parse_args(["--test", "x=x", "--test", "x=y"]).test, {'x': 'y'}) self.assertDictEqual(parser.parse_args(["--test", "*=x", "--test", "y"]).test, {"*": 'y'}) self.assertDictEqual(parser.parse_args(["--test", "y", "--test", "*=3"]).test, {"*": '3'}) with self.assertRaises(SystemExit): parser.parse_args(["--test", "y=x,z"]) def test_with_comma_multiple_times(self): parser = argparse.ArgumentParser() parser.add_argument('--test', action=AppendDictAction) self.assertDictEqual(parser.parse_args(["--test", "*=x", "--test", "y=a"]).test, {"*": 'x', 'y': 'a'}) self.assertDictEqual(parser.parse_args(["--test", "x=x", "--test", "x=y"]).test, {'x': 'y'}) self.assertDictEqual(parser.parse_args(["--test", "*=x", "--test", "y"]).test, {"*": 'y'}) self.assertDictEqual(parser.parse_args(["--test", "y", "--test", "*=3"]).test, {"*": '3'}) with self.assertRaises(SystemExit): parser.parse_args(["--test", "y=x,z", "--test", "x"]) def test_without_comma(self): parser = argparse.ArgumentParser() parser.add_argument('--test', action=AppendDictAction, allow_commas=False) self.assertDictEqual(parser.parse_args(["--test", "x"]).test, {"*": 'x'}) self.assertDictEqual(parser.parse_args(["--test", "y=x"]).test, {"y": 'x'}) self.assertDictEqual(parser.parse_args(["--test", "y=x,z=a"]).test, {"y": 'x,z=a'}) self.assertDictEqual(parser.parse_args(["--test", "*=x"]).test, {"*": 'x'}) self.assertDictEqual(parser.parse_args(["--test", "y=x,z"]).test, {"y": 'x,z'}) def test_without_comma_multiple_times(self): parser = argparse.ArgumentParser() parser.add_argument('--test', action=AppendDictAction, allow_commas=False) self.assertDictEqual(parser.parse_args(["--test", "x", "--test", "y"]).test, {"*": 'y'}) self.assertDictEqual(parser.parse_args(["--test", "y=x", "--test", "x=y"]).test, {"y": 'x', 'x': 'y'}) self.assertDictEqual(parser.parse_args(["--test", "y=x,z=a", "--test", "b=c"]).test, {"y": 'x,z=a', 'b': 'c'}) def test_with_default(self): parser = argparse.ArgumentParser() parser.add_argument('--test', action=AppendDictAction, default={"aa": "bb"}) self.assertDictEqual(parser.parse_args(["--test", "x"]).test, {"*": 'x', 'aa': 'bb'})
jdossett/imagemounter
tests/cli_test.py
Python
mit
3,178
angular.module('Techtalk') .factory('socket', function ($rootScope, config) { if (typeof (io) != "undefined") { var socket = io.connect(config.Urls.URLService, { reconnection: false }); return { on: function (eventName, callback) { socket.on(eventName, function () { var args = arguments; $rootScope.$apply(function () { callback.apply(socket, args); }); }); }, emit: function (eventName, data, callback) { socket.emit(eventName, data, function () { var args = arguments; $rootScope.$apply(function () { if (callback) { callback.apply(socket, args); } }); }) } }; } return; }) .directive('serverError', function () { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attrs, ctrl) { element.on('keydown', function () { ctrl.$setValidity('server', true) }); } } }) .directive('ngEnter', function () { return function (scope, element, attrs) { element.bind("keydown keypress", function (event) { if (event.which === 13) { scope.$apply(function () { scope.$eval(attrs.ngEnter); }); var $id = $("." + attrs.ngScrollBottomText); $id.scrollTop($id[0].scrollHeight + 250); event.preventDefault(); } }); }; }) .directive("ngScrollBottom", function () { return { link: function (scope, element, attr) { var $id = $("." + attr.ngScrollBottom); $(element).on("click", function () { $id.scrollTop($id[0].scrollHeight + 250); $('.msg-field').focus(); }); } } });
RafaSousa/techtalk-node
client/app/directives/main-directive.js
JavaScript
mit
1,844
CFLAGS=-g -std=c99 -Wall -Wconversion -Wtype-limits -pedantic -Werror EXEC=correr_pruebas OBJ=testing.o vector_dinamico.o heap.o CC=gcc all: $(EXEC) zip: rm -f ./Heap\ -\ 98373\ -\ Bianchi\ -\ 96251\ -\ Queirolo\ Dominguez.zip zip ./Heap\ -\ 98373\ -\ Bianchi\ -\ 96251\ -\ Queirolo\ Dominguez.zip *.c *.h Makefile vtest: valgrind --leak-check=full --track-origins=yes ./correr_pruebas test: ./correr_pruebas %.o: %.c %.h $(CC) $(CFLAGS) -c $< clear: rm $(OBJ) $(EXEC) $(EXEC): $(OBJ) prueba_heap.c main.c $(CC) $(CFLAGS) $(OBJ) prueba_heap.c main.c -o $(EXEC)
starg09/7541-rw-heap
Makefile
Makefile
mit
575
// Regular expression that matches all symbols with the `IDS_Binary_Operator` property as per Unicode v7.0.0: /[\u2FF0\u2FF1\u2FF4-\u2FFB]/;
mathiasbynens/unicode-data
7.0.0/properties/IDS_Binary_Operator-regex.js
JavaScript
mit
140
# Import the necessary packages and modules import matplotlib.pyplot as plt import numpy as np # Prepare the data x = np.linspace(0, 10, 100) # Plot the data plt.plot(x, x, label='linear') # Add a legend plt.legend() # Show the plot plt.show() print("done")
vadim-ivlev/STUDY
coding/plot.py
Python
mit
262
(function(){ console.log("Message"); })();
curvecode/chrome-ext-js
app/helloworld/js/app.js
JavaScript
mit
46
# My-Portfolio-PHP.v This is the Php version with login system and this is the html version https://george35mk.github.io
George35mk/My-Portfolio-PHP.v
README.md
Markdown
mit
121
using CompartiMoss.BootCamp.Web.Services; using Microsoft.AspNet.Mvc; namespace CompartiMoss.BootCamp.Web.ViewComponents { public class ArticulosByAutor : ViewComponent { private IArticulos _service; public ArticulosByAutor(IArticulos service) { _service = service; } public IViewComponentResult Invoke(string name) { var articulosCollection = _service.GetArticulosByAutor(name); return View(articulosCollection); } } }
AdrianDiaz81/AzureBootCamp2016
CompartiMoss.BootCamp/src/CompartiMoss.BootCamp.Web/ViewComponents/ArticulosByAutor.cs
C#
mit
551
<form ng-controller="Umbraco.Dialogs.MediaPickerController" id="fileupload" method="POST" enctype="multipart/form-data" data-file-upload="options" data-file-upload-progress="" data-ng-class="{'fileupload-processing': processing() || loadingFiles}"> <div class="umb-panel umb-dialogs-mediapicker" ng-if="target"> <div class="umb-panel-body no-header with-footer compact"> <umb-pane> <umb-control-group ng-if="target.url"> <div class="thumbnail span6 clearfix"> <img ng-src="{{target.url}}" /> </div> </umb-control-group> <umb-control-group label="@general_url"> <input type="text" localize="placeholder" placeholder="@general_url" class="umb-editor umb-textstring" ng-model="target.url" ng-disabled="target.id"/> </umb-control-group> <umb-control-group label="@content_titleOptional"> <input type="text" localize="placeholder" placeholder="@placeholders_entername" class="umb-editor umb-textstring" ng-model="target.name" /> </umb-control-group> </umb-pane> </div> <div class="umb-panel-footer" > <div class="umb-el-wrap umb-panel-buttons"> <div class="btn-toolbar umb-btn-toolbar pull-right"> <a href ng-click="exitDetails()" class="btn btn-link"> <localize key="general_cancel">Cancel</localize> </a> <button class="btn btn-primary" ng-click="submit(target)"> <localize key="general_insert">Insert</localize> </button> </div> </div> </div> </div> <div class="umb-panel umb-dialogs-mediapicker" ng-hide="target"> <div class="umb-panel-header"> <div class="umb-el-wrap umb-panel-buttons"> <div class="span5"> <div class="form-search"> <i class="icon-search"></i> <input type="text" ng-model="searchTerm" class="umb-search-field search-query" placeholder="Filter..."> </div> </div> <div class="pull-right"> <span class="btn fileinput-button" ng-class="{disabled: disabled}"> <i class="icon-page-up"></i> <input type="file" name="files[]" multiple ng-disabled="disabled"> </span> </div> </div> <div class="row"> <ul class="breadcrumb span12"> <li ng-hide="startNodeId != -1"> <a href ng-click="gotoFolder()" prevent-default>Media</a> / </li> <li ng-repeat="item in path"> <a href ng-click="gotoFolder(item)" prevent-default>{{item.name}}</a> / </li> <li> <a href ng-hide="showFolderInput" ng-click="showFolderInput = true"> <i class="icon icon-add small"></i> </a> <input type="text" class="input-foldername input-mini inline" ng-show="showFolderInput" ng-model="newFolderName" ng-keydown="submitFolder($event)" on-blur="showFolderInput = false"> </li> </ul> </div> </div> <div class="umb-panel-body with-footer"> <div style="height: 10px; margin: 10px 0px 10px 0px" class="umb-loader" ng-hide="active() == 0"></div> <umb-photo-folder min-height="75" min-width="150" max-height="250" ideal-items-per-row="3" on-click="clickHandler" ng-model="images" filter-by="searchTerm"/> </div> <div class="umb-panel-footer" > <div class="umb-el-wrap umb-panel-buttons"> <div class="btn-toolbar umb-btn-toolbar pull-right"> <a href ng-click="close()" class="btn btn-link"> <localize key="general_cancel">Cancel</localize> </a> <button class="btn btn-primary" ng-show="multiPicker" ng-click="submit(dialogData.selection)"> <localize key="buttons_select">Select</localize>({{dialogData.selection.length}}) </button> </div> </div> </div> </div> </form>
zidad/Umbraco-CMS
src/Umbraco.Web.UI.Client/src/views/common/dialogs/mediapicker.html
HTML
mit
4,160
using System.Collections.ObjectModel; // Copyright (c) 2017 Cyotek Ltd. // http://mantissharp.net/ // Licensed under the MIT License. See LICENSE.txt for the full text. // If you use this control in your applications, attribution, donations or contributions are welcome. namespace MantisSharp { public class UserCollection : KeyedCollection<int, User> { #region Methods protected override int GetKeyForItem(User item) { return item.Id; } #endregion } }
cyotek/MantisSharp
src/UserCollection.cs
C#
mit
493
{% load modelcrud_tags %} <table class="table table-striped" data-toggle="table" data-search="true" data-sort-name="{{ data_sort_name }}" data-sort-order="{{data_sort_order }}" data-pagination="true" data-page-size="25"> <thead> <tr> {% for field in head %} <th data-field="{{field.name}}" data-sortable="true">{{ field.label }} </th> {% endfor %} </tr> </thead> <tbody> {% for row in rows %} <tr> {% for col_label in row.values %} {% if forloop.counter0 == row.obj.crudconf.list_display_detail_link_index %} <td> <a id="{{ col_label }}" href="{{ row.obj.crudconf.get_detail_url }}"> {{ col_label }} </a> </td> {% else %} {% if col_label|isinstance_datetime %} <td><span class="hidden">{{ col_label|date:"c" }}</span>{{ col_label|default_if_none:"" }}</td> {% else %} <td>{{ col_label|default_if_none:"" }}</td> {% endif %} {% endif %} {% endfor %} </tr> {% endfor %} </tbody> </table>
tonimichel/django-modelcrud
modelcrud/templates/modelcrud/list_table.tag.html
HTML
mit
1,403
var express = require('express'); var morphine = require('./api'); var app = express(); // Mounts the rpc layer middleware. This will enable remote function calls app.use(morphine.router); // Serve static files in this folder app.use('/', express.static(__dirname + '/')); // Listen on port 3000 app.listen(3000, function(err) { if (err) return console.log(err.stack); // Creates a user when you boot up the server // This is only to demostrate we can use the same code on server side... var User = morphine.User; User.create({ _id: 5, name: 'someone' }, function(err, user) { if (err) console.error(err.stack); console.log('App listening on http://127.0.0.1:3000'); }); });
d-oliveros/isomorphine
examples/barebone/src/server.js
JavaScript
mit
703
#!/usr/bin/env node require('yargs') .commandDir('cmd') .demand(1) .strict() .help() .argv;
dobbydog/webpack-porter
cli.js
JavaScript
mit
93
<include target="./common/header.html" /> <include target="./common/header_tabs.html" /> <h1>{$lang->maps_module_maps_setting}</h1> <form ruleset="mapsModuleConfig" id="fo_obj" class="x_form-horizontal" action="./" method="post" enctype="multipart/form-data"> <input type="hidden" name="act" value="procMapsAdminCofig" /> <div class="x_control-group"> <label class="x_control-label" for="daum_local_api_key">{$lang->maps_module_daum_local_api_key}</label> <div class="x_controls"> <input type="text" name="daum_local_api_key" id="daum_local_api_key" value="{$daum_local_api_key}"> <span class="x_help-inline">{$lang->about_maps_module_daum_local_api_key}</span> </div> </div> <div class="x_control-group"> <label class="x_control-label" for="map_api_key">{$lang->maps_module_map_api_key}</label> <div class="x_controls"> <input type="text" name="map_api_key" id="map_api_key" value="{$map_api_key}"> <span class="x_help-inline">{$lang->about_maps_module_map_api_key}</span> </div> </div> <div class="x_control-group"> <label class="x_control-label" for="map_api_type">{$lang->maps_module_map_api_key_type}</label> <div class="x_controls"> <select name="map_api_type" id="map_api_type"> <option value="" selected="selected"|cond="!$map_api_type">{$lang->maps_module_key_type_auto}</option> <option loop="$lang->maps_module_key=>$key,$val" value="{$key}" selected="selected"|cond="$map_api_type===$key">{$val}</option> </select> <span class="x_help-inline">{$lang->maps_module_key_type_descri}</span> </div> </div> <div class="x_clearfix btnArea"> <div class="x_pull-right"> <button type="submit" class="x_btn x_btn-primary">{$lang->cmd_save}</button> </div> </div> </form>
xe-public/xe-module-maps
tpl/maps_config.html
HTML
mit
1,734
package main import ( "fmt" "github.com/oreans/virtualizersdk" "io/ioutil" "net/http" ) func main() { string1 := "This is string1" virtualizersdk.Macro(virtualizersdk.TIGER_BLACK_START) string2 := "This is string2" string3 := string1 + string2 fmt.Println(string3) resp, err := http.Get("http://google.com") if err != nil { fmt.Println(err) } else { defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) } fmt.Println(string(body)) } virtualizersdk.Macro(virtualizersdk.TIGER_BLACK_END) string4 := string2 + "...and string 4" fmt.Println(string4) }
ryanskidmore/CodeVirtualizer-Go-Example
main.go
GO
mit
624
# The MIT License (MIT) ## Copyright (c) 2016 Kilian Cirera Sant, Paradem 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.
Paradem/phoenix_timex
LICENSE.md
Markdown
mit
1,099
<?php include_once '../application/services/cases/test'; $model = new case_service(); $rs = $model->get_cases_num(); include_once ('global.php'); //调用数据库 include_once ('ofc/open-flash-chart.php'); //调用OFC库文件 //设置图表标题 $title = new title( '各区域单位场所数量分布图'.date('Y-m-d') ); $title->set_style("font-size:12px; font-weight:bold;"); $pie = new pie(); $pie->set_alpha(0.6); $pie->set_start_angle( 32 ); $pie->add_animation( new pie_fade() ); $pie->set_tooltip( '#val# of #total##percent# of 100%' ); $pie->set_colours( array('#1C9E05','#FF368D','#0099cc','#d853ce','#ff7400','#006e2e', '#d15600','#4096ee','#c79810') ); //读取各区域信息 $model = new case_service(); $rs = $model->get_cases_num(); var_dump($rs);exit(); $sql="select sum(total) as num from ".$prefix."district"; $query=$db->query($sql); $rs=$db->fetch_array($query); $t=$rs[num]; $sql="select name,total from ".$prefix."district"; $query=$db->query($sql); while($row=$db->fetch_array($query)){ $total=$row[total]; if(!empty($t)){ $v=round($total/$t,4)*100; }else{ $v=0; } $dis[]=array("name"=>$row[name],"total"=>$row[total],"v"=>$v); } $len_dis=count($dis); for($i=0;$i<$len_dis;$i++){ $dis_value[]=new pie_value(intval($dis[$i][total]),$dis[$i][name]."(".$dis[$i][v]."%)"); } $pie->set_values($dis_value); $chart = new open_flash_chart(); $chart->set_title( $title ); $chart->add_element( $pie ); $chart->x_axis = null; echo $chart->toPrettyString(); //生成json数据
niuzz/ci
static/cases_data.php
PHP
mit
1,585
# Explo_Data_Analysis-Proj2 ## Project 2 ###Plot 1: #### plots a graph showing Years vs US Nation wide Emissions. ### Plot 2: #### Plots a graph showing Years Vs Baltimore. ### Plot 3: #### Plots a graph showing Years Vs Emisions for types(non-road,point, on-road, non-pint). ### Plot 4: #### Plots a graph showing Years Vs Emisions for US Wide coal combustion. ### Plot 5: #### Plots a graph showing Years Vs Emisions for Baltimore Vehicles. ### Plot 5: #### Plots a graph showing Years Vs Emisions for Baltimore Vehicles. ### Plot 6: #### Plots a graph showing Years Vs Emisions for Baltimore & LA comparisions.
reddytkv/Explo_Data_Analysis-Proj2
README.md
Markdown
mit
623
class CreateRepoUsers < ActiveRecord::Migration def change create_table :repo_users do |t| t.integer :user_id, :null => false t.integer :repo_id, :null => false t.timestamps end add_index :repo_users, [:user_id, :repo_id], :unique => true end end
prashantrajan/gitstars-oss
db/migrate/20120813015611_create_repo_users.rb
Ruby
mit
282
// flow-typed signature: a4cf0a15120e85fc382b90182181b521 // flow-typed version: <<STUB>>/grunt_v^1.0.1/flow_v0.49.1 /** * This is an autogenerated libdef stub for: * * 'grunt' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'grunt' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'grunt/lib/grunt' { declare module.exports: any; } declare module 'grunt/lib/grunt/cli' { declare module.exports: any; } declare module 'grunt/lib/grunt/config' { declare module.exports: any; } declare module 'grunt/lib/grunt/event' { declare module.exports: any; } declare module 'grunt/lib/grunt/fail' { declare module.exports: any; } declare module 'grunt/lib/grunt/file' { declare module.exports: any; } declare module 'grunt/lib/grunt/help' { declare module.exports: any; } declare module 'grunt/lib/grunt/option' { declare module.exports: any; } declare module 'grunt/lib/grunt/task' { declare module.exports: any; } declare module 'grunt/lib/grunt/template' { declare module.exports: any; } declare module 'grunt/lib/util/task' { declare module.exports: any; } // Filename aliases declare module 'grunt/lib/grunt.js' { declare module.exports: $Exports<'grunt/lib/grunt'>; } declare module 'grunt/lib/grunt/cli.js' { declare module.exports: $Exports<'grunt/lib/grunt/cli'>; } declare module 'grunt/lib/grunt/config.js' { declare module.exports: $Exports<'grunt/lib/grunt/config'>; } declare module 'grunt/lib/grunt/event.js' { declare module.exports: $Exports<'grunt/lib/grunt/event'>; } declare module 'grunt/lib/grunt/fail.js' { declare module.exports: $Exports<'grunt/lib/grunt/fail'>; } declare module 'grunt/lib/grunt/file.js' { declare module.exports: $Exports<'grunt/lib/grunt/file'>; } declare module 'grunt/lib/grunt/help.js' { declare module.exports: $Exports<'grunt/lib/grunt/help'>; } declare module 'grunt/lib/grunt/option.js' { declare module.exports: $Exports<'grunt/lib/grunt/option'>; } declare module 'grunt/lib/grunt/task.js' { declare module.exports: $Exports<'grunt/lib/grunt/task'>; } declare module 'grunt/lib/grunt/template.js' { declare module.exports: $Exports<'grunt/lib/grunt/template'>; } declare module 'grunt/lib/util/task.js' { declare module.exports: $Exports<'grunt/lib/util/task'>; }
kaitamkun/frisktol
flow-typed/npm/grunt_vx.x.x.js
JavaScript
mit
2,626
<form method="post" action=""> <h3 id="first">Name:</h3> <? GenerateInputTag("firstname","First name") ?> <br><? GenerateInputTag("lastname","Last name") ?> <h3>Contact details:</h3> <? GenerateInputTag("email","Email") ?> <br><? GenerateInputTag("phone","Home Phone") ?> <br><? GenerateInputTag("position","Position") ?> <h3>Account details:</h3> <? GenerateInputTag("login", "Username") ?>; <br><? GenerateInputTag("password","Password","password") ?> <? include "inc/formend.html"; ?> </form>
ukraine/Vitroff
mad/content/staff/addedit.html
HTML
mit
567
require 'mina/bundler' require 'mina/rails' require 'mina/unicorn/utility' namespace :unicorn do include Mina::Unicorn::Utility # Following recommendations from http://unicorn.bogomips.org/unicorn_1.html#rack-environment set_default :unicorn_env, -> { fetch(:rails_env) == 'development' ? 'development' : 'deployment' } set_default :unicorn_config, -> { "#{deploy_to}/#{current_path}/config/unicorn.rb" } set_default :unicorn_pid, -> { "#{deploy_to}/#{current_path}/tmp/pids/unicorn.pid" } set_default :unicorn_cmd, -> { "#{deploy_to}/#{current_path}/#{bundle_prefix} unicorn" } set_default :unicorn_restart_sleep_time, -> { 2 } set_default :bundle_gemfile, -> { "#{deploy_to}/#{current_path}/Gemfile" } desc "Start Unicorn master process" task start: :environment do queue start_unicorn end desc "Stop Unicorn" task stop: :environment do queue kill_unicorn('QUIT') end desc "Immediately shutdown Unicorn" task shutdown: :environment do queue kill_unicorn('TERM') end desc "Restart unicorn service" task restart: :environment do queue restart_unicorn end end
Rodrigora/mina-unicorn
lib/mina/unicorn/tasks.rb
Ruby
mit
1,147
package com.raizlabs.android.dbflow.test.sql; import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.Table; import com.raizlabs.android.dbflow.test.TestDatabase; import com.raizlabs.android.dbflow.test.structure.TestModel1; /** * Description: */ @Table(database = TestDatabase.class, name = "TestModel32") public class TestModel3 extends TestModel1 { @Column String type; }
mickele/DBFlow
dbflow-tests/src/test/java/com/raizlabs/android/dbflow/test/sql/TestModel3.java
Java
mit
431
/* * JDIVisitor * Copyright (C) 2014 Adrian Herrera * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.jdivisitor.debugger.event; import org.jdivisitor.debugger.event.visitor.EventVisitor; import org.jdivisitor.debugger.event.visitor.Visitable; import com.sun.jdi.event.ThreadStartEvent; /** * Visitable thread start event. * * @author Adrian Herrera * @see ThreadStartEvent */ public class VisitableThreadStartEvent implements Visitable { private final ThreadStartEvent event; public VisitableThreadStartEvent(ThreadStartEvent event) { this.event = event; } @Override public void accept(EventVisitor visitor) { visitor.visit(event); } }
adrianherrera/jdivisitor
src/main/java/org/jdivisitor/debugger/event/VisitableThreadStartEvent.java
Java
mit
1,378
FROM java MAINTAINER Robert Wallis <smilingrob@gmail.com> RUN apt-get update && \ apt-get install -y sudo && \ rm -rf /var/lib/apt/lists/* RUN wget https://d1opms6zj7jotq.cloudfront.net/idea/ideaIC-15.0.4.tar.gz -O /tmp/idea.tar.gz -q && \ mkdir -p /usr/share/intellij && \ tar -xf /tmp/idea.tar.gz --strip-components=1 -C /usr/share/intellij && \ rm /tmp/idea.tar.gz RUN export uid=1000 gid=1000 && \ mkdir -p /home/developer && \ echo "developer:x:${uid}:${gid}:Developer,,,:/home/developer:/bin/bash" >> /etc/passwd && \ echo "developer:x:${uid}:" >> /etc/group && \ echo "developer ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/developer && \ chmod 0440 /etc/sudoers.d/developer && \ chown ${uid}:${gid} -R /home/developer USER developer ENV HOME /home/developer VOLUME /tmp/.X11-unix CMD /usr/share/intellij/bin/idea.sh
robert-wallis/docker-intellij-ce
Dockerfile
Dockerfile
mit
863
package com.limpoxe.fairy.core; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import com.limpoxe.fairy.content.LoadedPlugin; import com.limpoxe.fairy.content.PluginDescriptor; import com.limpoxe.fairy.core.android.HackLayoutInflater; import com.limpoxe.fairy.core.compat.CompatForFragmentClassCache; import com.limpoxe.fairy.core.compat.CompatForSupportv7ViewInflater; import com.limpoxe.fairy.core.proxy.systemservice.AndroidAppIActivityManager; import com.limpoxe.fairy.core.proxy.systemservice.AndroidAppINotificationManager; import com.limpoxe.fairy.core.proxy.systemservice.AndroidAppIPackageManager; import com.limpoxe.fairy.core.proxy.systemservice.AndroidOsServiceManager; import com.limpoxe.fairy.core.proxy.systemservice.AndroidWebkitWebViewFactoryProvider; import com.limpoxe.fairy.core.proxy.systemservice.AndroidWidgetToast; import com.limpoxe.fairy.manager.PluginManagerHelper; import com.limpoxe.fairy.manager.PluginManagerProviderClient; import com.limpoxe.fairy.manager.mapping.StubActivityMappingProcessor; import com.limpoxe.fairy.manager.mapping.StubReceiverMappingProcessor; import com.limpoxe.fairy.manager.mapping.StubServiceMappingProcessor; import com.limpoxe.fairy.util.FreeReflection; import com.limpoxe.fairy.util.LogUtil; import com.limpoxe.fairy.util.ProcessUtil; public class PluginLoader { private PluginLoader() { } /** * 初始化loader, 只可调用一次 * * @param app */ public static synchronized void initLoader(Application app) { if (FairyGlobal.isInited()) { return; } LogUtil.v("插件框架初始化中..."); long t1 = System.currentTimeMillis(); if (Build.VERSION.SDK_INT >= 28) { boolean ret = FreeReflection.exemptAll(app); LogUtil.v("hidden api exempt " + ret); } FairyGlobal.setApplication(app); FairyGlobal.registStubMappingProcessor(new StubActivityMappingProcessor()); FairyGlobal.registStubMappingProcessor(new StubServiceMappingProcessor()); FairyGlobal.registStubMappingProcessor(new StubReceiverMappingProcessor()); //这里的isPluginProcess方法需要在安装AndroidAppIActivityManager之前执行一次。 //原因见AndroidAppIActivityManager的getRunningAppProcesses()方法 boolean isPluginProcess = ProcessUtil.isPluginProcess(); if(ProcessUtil.isPluginProcess()) { AndroidOsServiceManager.installProxy(); AndroidWidgetToast.installProxy(); } AndroidAppIActivityManager.installProxy(); AndroidAppINotificationManager.installProxy(); AndroidAppIPackageManager.installProxy(FairyGlobal.getHostApplication().getPackageManager()); if (isPluginProcess) { HackLayoutInflater.installPluginCustomViewConstructorCache(); CompatForSupportv7ViewInflater.installPluginCustomViewConstructorCache(); CompatForFragmentClassCache.installFragmentClassCache(); CompatForFragmentClassCache.installSupportV4FragmentClassCache(); CompatForFragmentClassCache.installAndroidXFragmentClassCache(); //不可在主进程中同步安装,因为此时ActivityThread还没有准备好, 会导致空指针。 new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { AndroidWebkitWebViewFactoryProvider.installProxy(); } }); } PluginInjector.injectHandlerCallback();//本来宿主进程是不需要注入handlecallback的,这里加上是为了对抗360安全卫士等软件,提高Instrumentation的成功率 PluginInjector.injectInstrumentation(); PluginInjector.injectBaseContext(FairyGlobal.getHostApplication()); PluginInjector.injectAppComponentFactory(); if (isPluginProcess) { if (Build.VERSION.SDK_INT >= 14) { FairyGlobal.getHostApplication().registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() { @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { } @Override public void onActivityStarted(Activity activity) { } @Override public void onActivityResumed(Activity activity) { } @Override public void onActivityPaused(Activity activity) { } @Override public void onActivityStopped(Activity activity) { } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public void onActivityDestroyed(Activity activity) { Intent intent = activity.getIntent(); if (intent != null && intent.getComponent() != null) { LogUtil.v("回收绑定关系"); PluginManagerProviderClient.unBindLaunchModeStubActivity(intent.getComponent().getClassName(), activity.getClass().getName()); } } }); } } FairyGlobal.setIsInited(true); long t2 = System.currentTimeMillis(); LogUtil.w("插件框架初始化完成", "耗时:" + (t2-t1)); } public static Context fixBaseContextForReceiver(Context superApplicationContext) { if (superApplicationContext instanceof ContextWrapper) { return ((ContextWrapper)superApplicationContext).getBaseContext(); } else { return superApplicationContext; } } /** * 根据插件中的classId加载一个插件中的class * * @param clazzId * @return */ @SuppressWarnings("rawtypes") public static Class loadPluginFragmentClassById(String clazzId) { PluginDescriptor pluginDescriptor = PluginManagerHelper.getPluginDescriptorByFragmentId(clazzId); if (pluginDescriptor != null) { String clazzName = pluginDescriptor.getPluginClassNameById(clazzId); return loadPluginClassByName(pluginDescriptor, clazzName); } else { LogUtil.e("PluginDescriptor Not Found for classId ", clazzId); } return null; } @SuppressWarnings("rawtypes") public static Class loadPluginClassByName(String clazzName) { PluginDescriptor pluginDescriptor = PluginManagerHelper.getPluginDescriptorByClassName(clazzName); return loadPluginClassByName(pluginDescriptor, clazzName); } public static Class loadPluginClassByName(PluginDescriptor pluginDescriptor, String clazzName) { if (pluginDescriptor != null && clazzName != null) { //插件可能尚未初始化,确保使用前已经初始化 LoadedPlugin plugin = PluginLauncher.instance().startPlugin(pluginDescriptor); if (plugin != null) { return plugin.loadClassByName(clazzName); } else { LogUtil.e("Plugin is not running", clazzName); } } else { LogUtil.e("loadPluginClass Fail for clazzName ", clazzName, pluginDescriptor==null?"pluginDescriptor = null":"pluginDescriptor not null"); } return null; } /** * 获取当前class所在插件的Context * 每个插件只有1个DefaultContext, * 是当前插件中所有class公用的Context * * @param clazz * @return */ public static Context getDefaultPluginContext(@SuppressWarnings("rawtypes") Class clazz) { Context pluginContext = null; PluginDescriptor pluginDescriptor = PluginManagerHelper.getPluginDescriptorByClassName(clazz.getName()); if (pluginDescriptor != null) { LoadedPlugin plugin = PluginLauncher.instance().getRunningPlugin(pluginDescriptor.getPackageName()); if (plugin != null) { pluginContext = plugin.pluginContext;; } else { LogUtil.e("Plugin is not running", clazz.getName()); } } else { LogUtil.e("PluginDescriptor Not Found for ", clazz.getName()); } if (pluginContext == null) { LogUtil.e("Context Not Found for ", clazz.getName()); } return pluginContext; } }
limpoxe/Android-Plugin-Framework
FairyPlugin/src/main/java/com/limpoxe/fairy/core/PluginLoader.java
Java
mit
8,547