repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
heymrcarter/generator-tfstask | generators/app/templates/_README.md | 44 | #<%= taskname %>
<%= description %>
##Usage | mit |
redisliu/chrome-extensions | vivintsolar-monitor/content_script.js | 5501 |
console.log("VS: loading content_script.js..." + new Date());
// Check if the communication between page and background.js has broken.
var last_message_time = new Date().getTime();
new Promise((resolve) => setTimeout(resolve, 1000000)).then(() => {
var now = new Date().getTime();
if (now - last_message_time > 500000) {
sendAlert('Not having message from background for at least 500s, force reloading');
reloadPage();
}
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
// Update timestamp first.
last_message_time = new Date().getTime();
console.log("VS: received data from content_script.js" + new Date());
console.log(request);
var action = request["action"];
takeAction(action, request);
});
var already_logging_in = false;
function takeAction(action, request) {
var url = window.location.href;
console.log("VS: Taking action: " + action + " in " + url);
if (action === ACTION_FOR_HOMEPAGE) {
homePage(request);
} else if (action === ACTION_FOR_LOGIN_PAGE) {
loginPage(request);
} else if (action === ACTION_FOR_ASYNC_LOGIN) {
loginPage(request);
} else if (action === ACTION_FOR_DASHBOARD_PAGE) {
dashboardPage(request);
} else {
// Other cases.
console.log("VS: unknown action:" + new Date());
console.log(action);
return;
}
}
function dashboardPage(request) {
console.log("VS: In dashboard page" + new Date());
//var val = $('[data-reactid=".0.0.3.0.0.0.0.0.1.0.0.1.0"]');
//if (val) {
// var ts = new Date().getTime();
// var amount = val.text();
// if (!amount) {
// console.log("Failed to parse data from html page. " + new Date());
// } else {
// saveGenerationData({'amount': amount, 'time': ts});
// }
//} else {
// sendAlert('Failed to read data from Dashboard page' + window.location.href);
//}
//console.log("VS: setting to reload page in 60s: " + new Date());
//window.setInterval(function() {
console.log("VS: polling account data" + new Date());
$.ajax({url: "/api/fusion/accounts"}).done(function(msg) {
console.log("VS: got account data" + new Date());
var j = msg;
if (typeof(j) === "object" && 'accounts' in j) {
console.log(j['accounts']);
var acct = j['accounts'][0]['account_no'];
var newUrl = '/api/fusion/accounts/' + acct;
console.log("VS: polling account detail data" + new Date());
$.ajax({url: newUrl}).done(function(msg) {
console.log("VS: got account detail data" + new Date());
var j = msg;
if (typeof(j) === "object" && 'energyToday' in j) {
var ts = new Date().getTime();
var amount = j['energyToday'] / 1000.0;
console.log("VS: saveing energy data" + new Date());
saveGenerationData({'time': ts, 'amount': amount});
return;
}
sendAlert("Failed parse detailed account info from AJAX for: " + textStatus);
reloadPage();
}).fail(function(jqXHR, textStatus) {
sendAlert("Request failed for loading detailed account info from AJAX for: " + textStatus);
reloadPage();
});
return;
}
sendAlert('Failed to parse account data');
reloadPage();
}).fail(function(jqXHR, textStatus) {
sendAlert("Request failed for loading accounts AJAX for: " + textStatus);
reloadPage();
});
//}, 60000);
}
function loginPage(request) {
if (request) {
asyncLogin(request);
} else {
chrome.runtime.sendMessage({"action": ACTION_FOR_ASYNC_LOGIN});
}
}
function homePage(request) {
var links = $('A');
for (var i in links) {
var link = links[i];
if (link.href == LOGIN_PAGE) {
link.click();
}
}
}
function asyncLogin(request) {
if (already_logging_in) {
console.log("VS: already logging in. This is possible, ignoring.." + new Date());
return;
}
already_logging_in = true;
console.log("VS: gettting new data to login" + new Date());
console.log(request);
context = request['data'];
if ($("INPUT[data-reactid='.0.0.0.0.0.1.1']").val(context.username).length > 0
&& $("INPUT[data-reactid='.0.0.0.0.0.2.0']").val(context.passwd).length > 0) {
$("BUTTON[data-reactid='.0.0.0.0.0.4.0']").click();
new Promise((resolve) => setTimeout(resolve, 100000)).then(() => {
sendAlert('Login failed for username' + context.username + ' and passwd: ' + context.passwd);
});
}
$('.email-input.js-initial-focus').val(context.username);
$('.js-password-field').val(context.passwd);
new Promise((resolve) => setTimeout(resolve, 1500)).then(() => {
$('button.submit').click();
});
}
var action = urlToAction(window.location.href);
console.log("VS: intercepted action:" + action + " at " + new Date());
if (action != '') {
takeAction(action, null);
}
console.log("VS: loaded:" + window.location.href);
console.log("VS: registered on load event here handler in content_script.js" + new Date());
| mit |
parkjoon/iOS_Applications | Flappy_Flyer/README.md | 108 | Flappy_Flyer
============
A Flappy Birds clone for iOS.
Raw XCode project along with original artwork. | mit |
krsrk/laravel-5.3-web-app | app/Models/Books.php | 319 | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Books extends Model
{
protected $table = 'books';
protected $fillable = [
'guid',
'author',
'title',
'description',
'abstract',
'edition',
'publish_date',
'status'];
}
| mit |
nushackers/nushackers-site | content/post/2011-04-16-motivations.md | 7639 | ---
author: ejames
categories:
- Essay
comments: true
date: 2011-04-16T00:00:00.000Z
title: Motivations
url: /2011/04/motivations/
aliases:
- /2011/04/16/motivations/
---
Over the past couple months or so we've had a number of non-programmers contacting us, looking for hackers to hire for their startup/project/idea/next-Facebook-to-be.
The logic goes — and you can <em>almost </em>hear it in their emails — that a university hacker is a good, cheap resource. One particular ad asked us for a candidate with 'many scholarships, lots of research papers, and we'll pay you $1000!' — which might be a joke, but if true ignores the fact that such a candidate would be Google material, for close to $80,000 a year. I find most of these shoutouts rather sad. "Saw the email from x?" I'd sometimes ask Angad. "What do you think of it?" And in fact good ads are so rare that when we get one we rush to post it to our mailing list.
What most of these ads lack is an understanding of hacker motivations. When you're posting a help-wanted ad, what you're really asking a potential candidate to do is to weigh the cost/benefits of working for your unknown, unproven startup, when they can:
<ol>
<li><strong>Code for Google Summer of Code </strong>— which is incredibly attractive because you not only earn USD$5000 for 3 months of work, but you also get to work on an open source project (good for your resume); learn several new programming practices; and give back to the world.</li>
<li><strong>Intern with a elite program such as <a href="//sg.startuproots.org/">Startup Roots</a></strong> — (which we endorse, by the way).</li>
<li><strong>Code on personal projects</strong> — all hackers have one or two on the side, for fun; or</li>
<li><strong>Intern at a bank</strong></li>
</ol>
But then there's an added problem. Some people who email us are business founders looking for technical people. And more often than not the ideas that they have are either laughably bad, or of unknown quality. (The only way to make that unknown known is to implement it yourself and see the response. Which is a chicken and egg problem.)
So how do you hire a hacker if you're not one yourself? One answer is to get the motivations for hacking right. Chris Dixon wrote a post recently titled <em><a href="//cdixon.org/2011/04/12/showing-up/">Showing Up</a></em>, where he says:
<blockquote>We went to places like the Media Lab and basically just sat ourselves down at lunch counters and awkwardly introduced ourselves: “Hi, my name is Chris Dixon and this is Tom Pinckney and we are starting a company and would love to talk to you about it.” Most students ignored us or thought we were annoying. I remember one student staring at us quizzically saying “startups still exist?” Most of our trips were fruitless. At one point after a failed trip we were on the Redline back to our office in downtown Boston and joked, depressingly, that we felt so out of place that people looked at us like time travelers from the dot-com bubble.
Our first breakthough came after a series of trips when a particularly talented programmer/designer named <a href="//larifari.org/">Hugo Liu</a> re-approached us and said something like “hey, actually I thought about it and your idea doesn’t suck.” Then his friend <a href="//www.linkedin.com/profile/view?id=2104665&authType=NAME_SEARCH&authToken=xHpy&locale=en_US&srchid=6b2a8ef5-cf44-4377-ab54-7557dc9d5472-0&srchindex=1&srchtotal=8&pvs=ps&pohelp=&goback=%2Efps_*1_David_Gatenby_*1_*1_*1_*1_*51_*1_Y_*1_*1_*1_false_1_R_true_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2_*2">David Gatenby</a> talked to about joining us. We eventually recruited Hugo and David along with a brilliant undergraduate <a href="//mattgattis.com/about/">Matt Gattis</a>. We had finally broken through. Matt and Hugo now work with us at <a href="//hunch.com/">Hunch</a> along with some of their friends from MIT they brought along.</blockquote>
When you're asking a student programmer to work for you, you're selling him two things: 1) your idea, and 2) yourself. If you're not demonstrably smart, or if your project isn't interesting, then it's not likely that any hacker would want to work for you. Not with so many other options on the table.
This is, however, a cop-out. The truth is that it's hard to sell your idea when you have bad ideas, and it's even harder to sell yourself if you're not already a hacker (Pinkney, Dixon's friend, is a <a href="//cdixon.posterous.com/mit-is-a-national-treasure"><em>brilliant</em> programmer</a>). The non-technical people who start companies and go on to do great things tend to do so with hackers who they're <em>already</em> friends with. Which leaves us with: if you have bad ideas, or if you have absolutely no freaking clue of hacker culture, than nothing mentioned here will ever help you.
So what <em>can</em> help you? Here are a couple of things that I've found to be attractive in a <em>'programmer-wanted'</em> ad:
<ol>
<li><strong>Know your problem space really, really well.</strong> Hackers have finely-tuned sensors for bullshit, because we absolutely hate it, and know it when we see it. This is a function of preferring to build things vs sitting around and talking about them. If you're not a domain expert in whatever you're doing — it's harder to get a hacker interested.</li>
<li><strong>Sell the problem.</strong> If you know something really deeply, it's also likely that you know the problems that people in the aforementioned field need to solve. Problems are very attractive to programmers. In fact, problems are <em>especially </em>attractive to programmers if they're well defined. Fortunately for you, problems in the real world are rarely as clear as problems in programming puzzles, even if real world problems are ultimately more important. Your job as a startup founder is to make that problem space definable, and then sell <em>that</em> to a hacker.</li>
<li><strong>Sell experience, not money</strong>. Most of us are attracted to people who try very hard to solve interesting problems. Some of us — the ones you <em>can </em>hire — think that the experience of doing something like that is more valuable than the money. It helps to take money (as an issue) off the table as soon as possible; know that there's no way you can compete with Google Summer of Code, or even a bank internship.</li>
</ol>
In a nutshell: give us interesting problems to solve. Because if you can't do that, then it's a signal that you either have a lame startup, or you're not particularly good at doing startups, or you're a copycat. And there's nothing to save you from that.
(Note: notice that 'interesting problem' can mean a lot more than a 'startup that solves an interesting problem'. For instance, travel search engines are boring, but a travel search engine written in node.js (or Haskell, say) is <em>incredibly </em>attractive to a hacker. Unfortunately you have to be a hacker to understand that, and so we're back at square one.)
Semi-related: <a href="//metacog.tumblr.com/post/1436899565/why-business-co-founders-should-learn-to-code">why business co-founders should learn to code</a>.
<strong>Update:</strong> A number of people have observed that point 3 was 'off the mark'. It's not. What I mean by it is that you should pay market rate — or enough, whatever that amount is — to take the issue off the table. Don't sell yourself based on salary; it's unlikely that you'll win.
<a href="//news.ycombinator.com/item?id=2455323">Discuss this article at HN.</a>
| mit |
jugstalt/gViewGisOS | gView.Plugins.DbTools/Plugins/DbTools/Relates/TableRelationsDialog.Designer.cs | 5681 | namespace gView.Plugins.DbTools.Relates
{
partial class TableRelationsDialog
{
/// <summary>
/// Erforderliche Designervariable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Verwendete Ressourcen bereinigen.
/// </summary>
/// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Vom Windows Form-Designer generierter Code
/// <summary>
/// Erforderliche Methode für die Designerunterstützung.
/// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
/// </summary>
private void InitializeComponent()
{
this.btnRemove = new System.Windows.Forms.Button();
this.btnEdit = new System.Windows.Forms.Button();
this.btnAdd = new System.Windows.Forms.Button();
this.btnClose = new System.Windows.Forms.Button();
this.lstRelates = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// btnRemove
//
this.btnRemove.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnRemove.Enabled = false;
this.btnRemove.Location = new System.Drawing.Point(323, 60);
this.btnRemove.Name = "btnRemove";
this.btnRemove.Size = new System.Drawing.Size(125, 23);
this.btnRemove.TabIndex = 9;
this.btnRemove.Text = "Remove";
this.btnRemove.UseVisualStyleBackColor = true;
this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click);
//
// btnEdit
//
this.btnEdit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnEdit.Enabled = false;
this.btnEdit.Location = new System.Drawing.Point(323, 31);
this.btnEdit.Name = "btnEdit";
this.btnEdit.Size = new System.Drawing.Size(125, 23);
this.btnEdit.TabIndex = 8;
this.btnEdit.Text = "Edit...";
this.btnEdit.UseVisualStyleBackColor = true;
this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click);
//
// btnAdd
//
this.btnAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnAdd.Location = new System.Drawing.Point(323, 2);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(125, 23);
this.btnAdd.TabIndex = 7;
this.btnAdd.Text = "Add...";
this.btnAdd.UseVisualStyleBackColor = true;
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// btnClose
//
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnClose.Location = new System.Drawing.Point(323, 180);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(125, 23);
this.btnClose.TabIndex = 6;
this.btnClose.Text = "Close";
this.btnClose.UseVisualStyleBackColor = true;
//
// lstRelates
//
this.lstRelates.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lstRelates.FormattingEnabled = true;
this.lstRelates.Location = new System.Drawing.Point(2, 2);
this.lstRelates.Name = "lstRelates";
this.lstRelates.Size = new System.Drawing.Size(315, 199);
this.lstRelates.TabIndex = 5;
this.lstRelates.SelectedIndexChanged += new System.EventHandler(this.lstRelates_SelectedIndexChanged);
//
// TableRelatesDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(450, 206);
this.Controls.Add(this.btnRemove);
this.Controls.Add(this.btnEdit);
this.Controls.Add(this.btnAdd);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.lstRelates);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
this.Name = "TableRelatesDialog";
this.Text = "Relates Dialog";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button btnRemove;
private System.Windows.Forms.Button btnEdit;
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.Button btnClose;
private System.Windows.Forms.ListBox lstRelates;
}
} | mit |
eloquent/schemer | src/Eloquent/Schemer/Constraint/SchemaInterface.php | 325 | <?php
/*
* This file is part of the Schemer package.
*
* Copyright © 2013 Erin Millard
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eloquent\Schemer\Constraint;
interface SchemaInterface extends ConstraintInterface
{
}
| mit |
Cosmologist/collectd-network-bandwidth-usage | README.md | 601 | collectd-network-bandwidth-usage
================================
Collectd exec plugin for monitoring the network bandwitdh usage.
Installation
-----------
Uncomment exec plugin in your collectd.conf:
```bash
LoadPlugin exec
```
Configure plugin:
```bash
<Plugin exec>
Exec username "/path/to/exec-network-bandwidth-usage.sh" "your-network-interface-name"
</Plugin>
```
Restart collectd:
```bash
service collectd restart
```
Screenshots
-----------

| mit |
praneeth-kongara/image-viewer | public/css/style.css | 508 | /* header bar */
.navbar {
margin-bottom:0;
}
/* aside */
.content,aside {
margin-top:20px;
margin-bottom:30px;
margin-left:0px;
margin-right:0px;
}
.home {
background: url(/images/home.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
aside .nav {
margin-top:10px;
margin-left:10px;
margin-right:10px;
}
/* footer formatting */
footer {
margin-bottom:25px;
}
| mit |
CrazyJacky/flip-1 | demos/bootstrap/index.html | 4583 | <!DOCTYPE html>
<html lang="en">
<head>
<title>Basic Demo</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;"/>
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="red" />
<link href="../../dist/flip.css" rel="stylesheet">
<link href="../../dist/transitions/fade.css" rel="stylesheet">
<link rel="stylesheet" href="assets/css/bootstrap.css">
<link rel="stylesheet" href="assets/css/bootstrap-responsive.css">
<style>
@media (min-width: 980px) {
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
}
</style>
</head>
<body class="flipper" onload="flip()">
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container-fluid">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">Main</a>
<div class="nav-collapse">
<ul class="nav">
<li class="active"><a href="home">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="settings.html">Settings</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div id="main" class="container-fluid">
<section class="row-fluid" data-route="/">
<div class="span12">
<ul>
<li><a href="about.html">About</a></li>
<li><a href="settings.html">Settings</a></li>
<li><a href="deferred.html">Deferred Example</a></li>
<li><a href="multi.html">Multi Flip Example</a></li>
</ul>
</div>
</section>
<section class="row-fluid" id="settings" data-route="settings.html" data-title="Settings">
<form class="well">
<label>Label name</label>
<input type="text" class="span3" placeholder="Type something…"> <span class="help-inline">Associated help text!</span>
<label class="checkbox">
<input type="checkbox"> Check me out
</label>
<button type="submit" class="btn">Submit</button>
</form>
</section>
<section class="row-fluid" id="about" data-route="about.html">
<h2>About</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc pharetra eros id quam vestibulum faucibus. In a libero ipsum, eu pulvinar nibh. Nulla non congue lacus. Pellentesque ligula risus, mollis vel placerat vel, consectetur ac ante. Vestibulum convallis fringilla est quis accumsan. Aliquam mollis neque eu turpis euismod eget blandit lectus lacinia. Proin purus dolor, scelerisque sed tempor volutpat, aliquet in lectus. Fusce euismod mauris sed enim suscipit id laoreet arcu imperdiet.</p>
<p>Vestibulum vel aliquam lectus. Quisque ipsum nibh, auctor mollis dictum eget, sodales ut lectus. Vivamus fermentum dictum odio quis hendrerit. Nam cursus varius metus, a varius lorem mollis sit amet. Nulla imperdiet ultrices lorem non egestas. Praesent faucibus magna vel dui tempus eget commodo sem lacinia. Quisque iaculis magna nec metus suscipit dapibus pellentesque felis convallis. Donec diam nibh, varius sed viverra suscipit, bibendum sed lacus. Aenean eu nunc et ipsum viverra ullamcorper. Quisque lacus eros, suscipit sed sollicitudin eget, lacinia sed metus.</p>
</section>
<section class="row-fluid" id="not-found">
<h1>Whoops!</h1>
<p>The page you're looking for cannot be found. Sorry!</p>
</section>
</div>
<script src="../modernizr.custom.js"></script>
<script src="https://raw.github.com/DmitryBaranovskiy/eve/master/eve.min.js"></script>
<script src="https://raw.github.com/DamonOehlman/classtweak/master/classtweak.min.js"></script>
<script src="https://raw.github.com/cujojs/when/master/when.js"></script>
<script src="../../dist/flip.js"></script>
<script src="../../dist/plugins/bootstrap.js"></script>
<script src="../../dist/plugins/history.js"></script>
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
</body>
</html> | mit |
morozko108/Tilde | src/test/java/com/carbon108/tilde/PrimaryModelFactoryTest.java | 1725 | package com.carbon108.tilde;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author K Moroz
* @version 1.0
*/
public class PrimaryModelFactoryTest {
private PrimaryModelFactory factory;
@Before
public void setUp() {
factory = new PrimaryModelFactory();
}
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void getIDsGetsAllValidModelIDs() {
Collection<String> factoryIDs = factory.getIDs();
assertEquals(2, factoryIDs.size());
assertEquals(true, factoryIDs.contains(ModelID.LINEAR));
assertEquals(true, factoryIDs.contains(ModelID.CONSTANT));
// check immutability
exception.expect(UnsupportedOperationException.class);
factoryIDs.add("someString");
}
@Test
public void makeValidModelIDGetsModel() {
TildeModel model1 = factory.make(ModelID.LINEAR);
TildeModel model2 = factory.make(ModelID.CONSTANT);
assertEquals(ModelID.LINEAR, model1.getID());
assertEquals(ModelID.CONSTANT, model2.getID());
}
@Test
public void makeInvalidIDGetsNullModel() {
TildeModel m1null = factory.make(null);
TildeModel m1blank = factory.make("");
TildeModel m2invalid = factory.make("invalidModelID");
assertTrue(m1null.isNullModel());
assertTrue(m1blank.isNullModel());
assertTrue(m2invalid.isNullModel());
}
@Test
public void makeAll() {
Collection<TildeModel> models = factory.makeAll();
assertEquals(2, models.size());
assertEquals(true, models.contains(new LinearModel()));
assertEquals(true, models.contains(new ConstantModel()));
}
}
| mit |
KlusterKite/KlusterKite | Docs/Doxygen/html/namespace_kluster_kite_1_1_large_objects_1_1_tests.js | 222 | var namespace_kluster_kite_1_1_large_objects_1_1_tests =
[
[ "ParcelsTest", "class_kluster_kite_1_1_large_objects_1_1_tests_1_1_parcels_test.html", "class_kluster_kite_1_1_large_objects_1_1_tests_1_1_parcels_test" ]
]; | mit |
F4Team-DHCN1A/QLSV | QuanLySinhVien_MaNguonMo/QuanLySinhVien_GUI/frmtimkiemdiemsinhvientheomasv.Designer.cs | 6855 | namespace QuanLySinhVien_GUI
{
partial class frmtimkiemdiemsinhvientheomasv
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmtimkiemdiemsinhvientheomasv));
this.btnThoat = new System.Windows.Forms.Button();
this.cmbMaMH = new System.Windows.Forms.ComboBox();
this.dgvKetQua = new System.Windows.Forms.DataGridView();
this.btnTim = new System.Windows.Forms.Button();
this.txtMaSV = new System.Windows.Forms.TextBox();
this.lblMaMH = new System.Windows.Forms.Label();
this.lblMaSV = new System.Windows.Forms.Label();
this.lblTittle = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.dgvKetQua)).BeginInit();
this.SuspendLayout();
//
// btnThoat
//
this.btnThoat.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnThoat.BackgroundImage")));
this.btnThoat.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
this.btnThoat.Location = new System.Drawing.Point(580, 418);
this.btnThoat.Name = "btnThoat";
this.btnThoat.Size = new System.Drawing.Size(72, 30);
this.btnThoat.TabIndex = 32;
this.btnThoat.Text = " Thoát";
this.btnThoat.UseVisualStyleBackColor = true;
//
// cmbMaMH
//
this.cmbMaMH.FormattingEnabled = true;
this.cmbMaMH.Location = new System.Drawing.Point(382, 109);
this.cmbMaMH.Name = "cmbMaMH";
this.cmbMaMH.Size = new System.Drawing.Size(121, 21);
this.cmbMaMH.TabIndex = 31;
//
// dgvKetQua
//
this.dgvKetQua.AllowUserToAddRows = false;
this.dgvKetQua.AllowUserToDeleteRows = false;
this.dgvKetQua.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvKetQua.Location = new System.Drawing.Point(96, 183);
this.dgvKetQua.Name = "dgvKetQua";
this.dgvKetQua.ReadOnly = true;
this.dgvKetQua.Size = new System.Drawing.Size(537, 214);
this.dgvKetQua.TabIndex = 30;
//
// btnTim
//
this.btnTim.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnTim.BackgroundImage")));
this.btnTim.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
this.btnTim.Location = new System.Drawing.Point(580, 105);
this.btnTim.Name = "btnTim";
this.btnTim.Size = new System.Drawing.Size(72, 30);
this.btnTim.TabIndex = 29;
this.btnTim.Text = " Tìm";
this.btnTim.UseVisualStyleBackColor = true;
//
// txtMaSV
//
this.txtMaSV.Location = new System.Drawing.Point(114, 111);
this.txtMaSV.Name = "txtMaSV";
this.txtMaSV.Size = new System.Drawing.Size(125, 20);
this.txtMaSV.TabIndex = 28;
//
// lblMaMH
//
this.lblMaMH.AutoSize = true;
this.lblMaMH.Location = new System.Drawing.Point(302, 111);
this.lblMaMH.Name = "lblMaMH";
this.lblMaMH.Size = new System.Drawing.Size(60, 13);
this.lblMaMH.TabIndex = 26;
this.lblMaMH.Text = "Mã Học Kỳ";
//
// lblMaSV
//
this.lblMaSV.AutoSize = true;
this.lblMaSV.Location = new System.Drawing.Point(43, 111);
this.lblMaSV.Name = "lblMaSV";
this.lblMaSV.Size = new System.Drawing.Size(39, 13);
this.lblMaSV.TabIndex = 27;
this.lblMaSV.Text = "Mã SV";
//
// lblTittle
//
this.lblTittle.AutoSize = true;
this.lblTittle.Font = new System.Drawing.Font("Times New Roman", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblTittle.ForeColor = System.Drawing.Color.Red;
this.lblTittle.Location = new System.Drawing.Point(151, 30);
this.lblTittle.Name = "lblTittle";
this.lblTittle.Size = new System.Drawing.Size(408, 31);
this.lblTittle.TabIndex = 25;
this.lblTittle.Text = "Tìm Kiếm Điểm Theo Mã Sinh Viên";
//
// frmtimkiemdiemsinhvientheomasv
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(695, 479);
this.Controls.Add(this.btnThoat);
this.Controls.Add(this.cmbMaMH);
this.Controls.Add(this.dgvKetQua);
this.Controls.Add(this.btnTim);
this.Controls.Add(this.txtMaSV);
this.Controls.Add(this.lblMaMH);
this.Controls.Add(this.lblMaSV);
this.Controls.Add(this.lblTittle);
this.Name = "frmtimkiemdiemsinhvientheomasv";
this.Text = "TÌM KIẾM ĐIỂM SINH VIÊN";
((System.ComponentModel.ISupportInitialize)(this.dgvKetQua)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnThoat;
private System.Windows.Forms.ComboBox cmbMaMH;
private System.Windows.Forms.DataGridView dgvKetQua;
private System.Windows.Forms.Button btnTim;
private System.Windows.Forms.TextBox txtMaSV;
private System.Windows.Forms.Label lblMaMH;
private System.Windows.Forms.Label lblMaSV;
private System.Windows.Forms.Label lblTittle;
}
} | mit |
coq-bench/coq-bench.github.io | clean/Linux-x86_64-4.10.0-2.0.6/released/8.11.2/cantor/8.9.0.html | 7481 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>cantor: 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.11.2 / cantor - 8.9.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
cantor
<small>
8.9.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-08-17 11:46:38 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-17 11:46:38 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.11.2 Formal proof management system
num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.10.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.10.0 Official release 4.10.0
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/cantor"
license: "LGPL"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Cantor"]
depends: [
"ocaml"
"coq" {>= "8.9" & < "8.10~"}
]
tags: [
"keyword: ordinals"
"keyword: well-foundedness"
"keyword: termination"
"keyword: rpo"
"keyword: Goodstein sequences"
"category: Mathematics/Logic/See also"
"category: Mathematics/Arithmetic and Number Theory/Number theory"
"date: 2006-05-22"
]
authors: [
"Pierre Castéran <[email protected]> [http://www.labri.fr/~casteran/]"
"Évelyne Contejean <[email protected]> [http://www.lri.fr/~contejea]"
]
bug-reports: "https://github.com/coq-contribs/cantor/issues"
dev-repo: "git+https://github.com/coq-contribs/cantor.git"
synopsis: "On Ordinal Notations"
description: """
This contribution contains data structures for ordinals
less than Gamma0 under Cantor and Veblen normal
forms. Well-foundedness is established thanks to RPO with status for
generic terms. This contribution also includes termination proofs of
Hydra battles and Goodstein sequences as well as a computation of the
length of the Goodstein sequence starting from 4 in base 2.
This work is supported by INRIA-Futurs (Logical project-team), CNRS
and the French ANR via the A3PAT project (http://www3.iie.cnam.fr/~urbain/a3pat/)."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/cantor/archive/v8.9.0.tar.gz"
checksum: "md5=00ebfdf7bee8dea49d327079fdcf1048"
}
</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-cantor.8.9.0 coq.8.11.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.11.2).
The following dependencies couldn't be met:
- coq-cantor -> coq < 8.10~ -> ocaml < 4.10
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-cantor.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<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>
| mit |
omnicoin/eurobit | src/checkqueue.h | 6431 | // Copyright (c) 2012 The Eurobit developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef CHECKQUEUE_H
#define CHECKQUEUE_H
#include <boost/thread/mutex.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/condition_variable.hpp>
#include <vector>
#include <algorithm>
template<typename T> class CCheckQueueControl;
/** Queue for verifications that have to be performed.
* The verifications are represented by a type T, which must provide an
* operator(), returning a bool.
*
* One thread (the master) is assumed to push batches of verifications
* onto the queue, where they are processed by N-1 worker threads. When
* the master is done adding work, it temporarily joins the worker pool
* as an N'th worker, until all jobs are done.
*/
template<typename T> class CCheckQueue {
private:
// Mutex to protect the inner state
boost::mutex mutex;
// Worker threads block on this when out of work
boost::condition_variable condWorker;
// Master thread blocks on this when out of work
boost::condition_variable condMaster;
// The queue of elements to be processed.
// As the order of booleans doesn't matter, it is used as a LIFO (stack)
std::vector<T> queue;
// The number of workers (including the master) that are idle.
int nIdle;
// The total number of workers (including the master).
int nTotal;
// The temporary evaluation result.
bool fAllOk;
// Number of verifications that haven't completed yet.
// This includes elements that are not anymore in queue, but still in
// worker's own batches.
unsigned int nTodo;
// Whether we're shutting down.
bool fQuit;
// The maximum number of elements to be processed in one batch
unsigned int nBatchSize;
// Internal function that does bulk of the verification work.
bool Loop(bool fMaster = false) {
boost::condition_variable &cond = fMaster ? condMaster : condWorker;
std::vector<T> vChecks;
vChecks.reserve(nBatchSize);
unsigned int nNow = 0;
bool fOk = true;
do {
{
boost::unique_lock<boost::mutex> lock(mutex);
// first do the clean-up of the previous loop run (allowing us to do it in the same critsect)
if (nNow) {
fAllOk &= fOk;
nTodo -= nNow;
if (nTodo == 0 && !fMaster)
// We processed the last element; inform the master he can exit and return the result
condMaster.notify_one();
} else {
// first iteration
nTotal++;
}
// logically, the do loop starts here
while (queue.empty()) {
if ((fMaster || fQuit) && nTodo == 0) {
nTotal--;
bool fRet = fAllOk;
// reset the status for new work later
if (fMaster)
fAllOk = true;
// return the current status
return fRet;
}
nIdle++;
cond.wait(lock); // wait
nIdle--;
}
// Decide how many work units to process now.
// * Do not try to do everything at once, but aim for increasingly smaller batches so
// all workers finish approximately simultaneously.
// * Try to account for idle jobs which will instantly start helping.
// * Don't do batches smaller than 1 (duh), or larger than nBatchSize.
nNow = std::max(1U, std::min(nBatchSize, (unsigned int)queue.size() / (nTotal + nIdle + 1)));
vChecks.resize(nNow);
for (unsigned int i = 0; i < nNow; i++) {
// We want the lock on the mutex to be as short as possible, so swap jobs from the global
// queue to the local batch vector instead of copying.
vChecks[i].swap(queue.back());
queue.pop_back();
}
// Check whether we need to do work at all
fOk = fAllOk;
}
// execute work
BOOST_FOREACH(T &check, vChecks)
if (fOk)
fOk = check();
vChecks.clear();
} while(true);
}
public:
// Create a new check queue
CCheckQueue(unsigned int nBatchSizeIn) :
nIdle(0), nTotal(0), fAllOk(true), nTodo(0), fQuit(false), nBatchSize(nBatchSizeIn) {}
// Worker thread
void Thread() {
Loop();
}
// Wait until execution finishes, and return whether all evaluations where succesful.
bool Wait() {
return Loop(true);
}
// Add a batch of checks to the queue
void Add(std::vector<T> &vChecks) {
boost::unique_lock<boost::mutex> lock(mutex);
BOOST_FOREACH(T &check, vChecks) {
queue.push_back(T());
check.swap(queue.back());
}
nTodo += vChecks.size();
if (vChecks.size() == 1)
condWorker.notify_one();
else if (vChecks.size() > 1)
condWorker.notify_all();
}
~CCheckQueue() {
}
friend class CCheckQueueControl<T>;
};
/** RAII-style controller object for a CCheckQueue that guarantees the passed
* queue is finished before continuing.
*/
template<typename T> class CCheckQueueControl {
private:
CCheckQueue<T> *pqueue;
bool fDone;
public:
CCheckQueueControl(CCheckQueue<T> *pqueueIn) : pqueue(pqueueIn), fDone(false) {
// passed queue is supposed to be unused, or NULL
if (pqueue != NULL) {
assert(pqueue->nTotal == pqueue->nIdle);
assert(pqueue->nTodo == 0);
assert(pqueue->fAllOk == true);
}
}
bool Wait() {
if (pqueue == NULL)
return true;
bool fRet = pqueue->Wait();
fDone = true;
return fRet;
}
void Add(std::vector<T> &vChecks) {
if (pqueue != NULL)
pqueue->Add(vChecks);
}
~CCheckQueueControl() {
if (!fDone)
Wait();
}
};
#endif
| mit |
andrewherren/sicp | exercises/Chapter01.02.md | 9303 | ## [Section 1.2 - Procedures and the Processes They Generate](https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_1.2)
## Exercises
```scheme
;; ======================================================
;; Load definitions and functions from earlier chapters
;; ======================================================
(load "c01s01.scm")
;; ======================================================
```
**Exercise 1.9** Each of the following two procedures defines a method for adding two positive integers in terms of the procedures inc, which increments its argument by 1, and dec, which decrements its argument by 1.
```scheme
(define (+ a b)
(if (= a 0)
b
(inc (+ (dec a) b))))
(define (+ a b)
(if (= a 0)
b
(+ (dec a) (inc b))))
```
Using the substitution model, illustrate the process generated by each procedure in evaluating (+ 4 5). Are these processes iterative or recursive?
**Exercise 1.10** The following procedure computes a mathematical function called Ackermann's function.
```scheme
(define (A x y)
(cond ((= y 0) 0)
((= x 0) (* 2 y))
((= y 1) 2)
(else (A (- x 1)
(A x (- y 1))))))
```
What are the values of the following expressions?
```scheme
(A 1 10)
(A 2 4)
(A 3 3)
```
Consider the following procedures, where A is the procedure defined above:
```scheme
(define (f n) (A 0 n))
(define (g n) (A 1 n))
(define (h n) (A 2 n))
(define (k n) (* 5 n n))
```
Give concise mathematical definitions for the functions computed by the procedures f, g, and h for positive integer values of n. For example, (k n) computes 5n^2.
```scheme
(A 1 10)
; 2^10 because the final argument, (A x (- y 1))
; will evaluate 9 times before y = 1 and the
; function stops at 2
(A 2 4)
; 2^16 because the function first evaluates to (A 1 (A 2 3))
; = (A 1 (A 1 (A 2 2)))
; = (A 1 (A 1 (A 1 (A 2 1))))
; = (A 1 (A 1 (A 1 2)))
; = (A 1 (A 1 (A 0 (A 1 1))))
; = (A 1 (A 1 (A 0 2)))
; = (A 1 (A 1 (2 * 2)))
; = (A 1 (A 1 4))
; = (A 1 (A 0 (A 1 3)))
; = (A 1 (A 0 (A 0 (A 1 2))))
; = (A 1 (A 0 (A 0 (A 1 2))))
; = (A 1 (A 0 (A 0 (A 0 (A 1 1)))))
; = (A 1 (A 0 (A 0 (A 0 2))))
; = (A 1 (A 0 (A 0 (2 * 2))))
; = (A 1 (A 0 (A 0 4)))
; = (A 1 (A 0 (2 * 4)))
; = (A 1 (A 0 8))
; = (A 1 (2 * 8))
; = (A 1 16)
; which as we saw above will evaluate to 2^16
(A 3 3)
; 2^16 because the function first evaluates to (A 2 (A 3 2))
; = (A 2 (A 2 (A 3 1)))
; = (A 2 (A 2 2))
; = (A 2 (A 1 (A 2 1)))
; = (A 2 (A 1 2))
; = (A 2 (A 0 (A 1 1)))
; = (A 2 (A 0 2))
; = (A 2 (2 * 2))
; = (A 2 4)
; which as we saw above will evaluate to 2^16
(define (f n) (A 0 n))
; f(n) = 2*n
(define (g n) (A 1 n))
; g(n) = 2^n
(define (h n) (A 2 n))
; h(n) = 2^(n^2)
```
**Exercise 1.11** A function f is defined by the rule that f(n) = n if n < 3 and f(n) = f(n-1) + f(n-2) + f(n-3) if n >= 3.
Write a procedure that computes f by means of a recursive process. Write a procedure that computes f by means of an iterative process.
```scheme
; Recursive solution
(define (f n)
(cond ((< n 3) n)
(else (+ (+ (f (- n 1)) (* 2 (f (- n 2))))
(* 3 (f (- n 3)))))))
; Iterative solution
; a <- a + 2*b + 3*c
; b <- a
; c <- b
(define (f n)
(f-iter 2 1 0 n))
(define (f-iter a b c count)
(if (= count 0)
c
(f-iter (+ a (* b 2) (* c 3)) a b (- count 1))))
```
**Exercise 1.12** The following pattern of numbers is called Pascal's triangle.
```Tex
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
The numbers at the edge of the triangle are all 1, and each number inside the triangle is the sum of the two numbers above it. Write a procedure that computes elements of Pascal's triangle by means of a recursive process.
```scheme
(define (pascal row col)
(cond ((= row 1) 1)
((= row col) 1)
((= col 1) 1)
(else (+ (pascal (- row 1) (- col 1))
(pascal (- row 1) col)))))
(pascal 1 1)
;Value: 1
(pascal 2 1)
;Value: 1
(pascal 2 2)
;Value: 1
(pascal 3 1)
;Value: 1
(pascal 3 2)
;Value: 2
(pascal 3 3)
;Value: 1
(pascal 4 2)
;Value: 3
(pascal 4 3)
;Value: 3
(pascal 5 3)
;Value: 6
```
**Exercise 1.13** Prove that Fib(n) is the closest integer to (phi^n)/5, where phi = (1 + sqrt(5))/2. Hint: Let psi = (1 - sqrt(5))/2. Use induction and the definition of the Fibonacci numbers (see section 1.2.2) to prove that Fib(n) = (n - n)/5.
```Text
Base case: show for n = 0 and n = 1
n=0: Fib(0) = (phi^0 - rho^0)/sqrt(5)
0 = (0 - 0)/sqrt(5)
0 = 0
n=1: Fib(1) = (phi^1 - rho^1)/sqrt(5)
1 = ((1 + sqrt(5))/2 - (1 - sqrt(5))/2)/sqrt(5)
1 = ((2*(sqrt(5)))/2) / sqrt(5)
1 = (sqrt(5)) / sqrt(5)
1 = 1
Induction case: take k >= 1 as given and assume relation is true for all n >= 0
Fib(k + 1) = Fib(k) + Fib(k - 1)
By the induction hypothesis, we have that
Fib(k + 1) = ((phi^(k) - rho^(k))/sqrt(5)) + ((phi^(k - 1) - rho^(k - 1))/sqrt(5))
Fib(k + 1) = ((phi)^(k) + (phi)^(k - 1))/sqrt(5) - ((rho)^(k) + (rho)^(k - 1))/sqrt(5)
Since phi^2 = phi + 1 and rho^2 = rho + 1, we observe that
Fib(k + 1) = (((phi)^(k - 1)(phi + 1)) - ((rho)^(k - 1)(rho + 1)))/sqrt(5)
Fib(k + 1) = (((phi)^(k - 1)(phi^2)) - ((rho)^(k - 1)(rho^2)))/sqrt(5)
Fib(k + 1) = ((phi)^(k + 1) - (rho)^(k + 1))/sqrt(5)
```
**Exercise 1.14** Draw the tree illustrating the process generated by the count-change procedure of section 1.2.2 in making change for 11 cents. What are the orders of growth of the space and number of steps used by this process as the amount to be changed increases?
**Exercise 1.15** The sine of an angle (specified in radians) can be computed by making use of the approximation sin x ~ x if x is sufficiently small, and the trigonometric identity
sin r = 3 sin r/3 - 4 sin^3 r/3
to reduce the size of the argument of sin. (For purposes of this exercise an angle is considered "sufficiently small" if its magnitude is not greater than 0.1 radians.) These ideas are incorporated in the following procedures:
```scheme
(define (cube x) (* x x x))
(define (p x) (- (* 3 x) (* 4 (cube x))))
(define (sine angle)
(if (not (> (abs angle) 0.1))
angle
(p (sine (/ angle 3.0)))))
```
a. How many times is the procedure p applied when (sine 12.15) is evaluated?
> 6
b. What is the order of growth in space and number of steps (as a function of a) used by the process generated by the sine procedure when (sine a) is evaluated?
> n
**Exercise 1.16** Design a procedure that evolves an iterative exponentiation process that uses successive squaring and uses a logarithmic number of steps, as does fast-expt. (Hint: Using the observation that (b^(n/2))^2 = (b^2)^(n/2), keep, along with the exponent n and the base b, an additional state variable a, and define the state transformation in such a way that the product a bn is unchanged from state to state. At the beginning of the process a is taken to be 1, and the answer is given by the value of a at the end of the process. In general, the technique of defining an invariant quantity that remains unchanged from state to state is a powerful way to think about the design of iterative algorithms.)
```scheme
; define the iterative algorithm
(define (rapid-expt-iter b n product)
(cond ((= n 0) product)
; use successive squaring for even powers greater than 2
((and (even? n) (> n 2)) (rapid-expt-iter b (/ n 2) (* product (* b b))))
; else use simple iteration
(else (rapid-expt-iter b (- n 1) (* product b)))))
; call iterative algorithm in a shorter-form function which initializes a to be 1
(define (rapid-expt b n)
(rapid-expt-iter b n 1))
; Test some outputs
(rapid-expt 2 4)
; Value: 16
(rapid-expt 3 5)
; Value: 243
```
**Exercise 1.17** The exponentiation algorithms in this section are based on performing exponentiation by means of repeated multiplication. In a similar way, one can perform integer multiplication by means of repeated addition. The following multiplication procedure (in which it is assumed that our language can only add, not multiply) is analogous to the expt procedure:
```scheme
(define (* a b)
(if (= b 0)
0
(+ a (* a (- b 1)))))
```
This algorithm takes a number of steps that is linear in b. Now suppose we include, together with addition, operations double, which doubles an integer, and halve, which divides an (even) integer by 2. Using these, design a multiplication procedure analogous to fast-expt that uses a logarithmic number of steps.
```scheme
; define double
(define (double x) (* x 2))
; define halve
(define (halve x) (/ x 2))
; define the iterative algorithm
(define (rapid-mult-iter a b product)
(cond ((= b 0) product)
; if b can be halved and is greater than 2, halve it and double the product of the multiplication
((and (even? b) (> b 2)) (+ product (double (rapid-mult-iter a (halve b) 0))))
; else use simple iteration
(else (rapid-mult-iter a (- b 1) (+ product a)))))
; call iterative algorithm in a shorter-form function which initializes a to be 1
(define (rapid-mult a b)
(rapid-mult-iter a b 0))
```
| mit |
xaroth8088/beautiful-components | README.md | 114 | # beautiful-components
A collection of webcomponents, inspired by the design work at http://tympanus.net/codrops/
| mit |
wokenshin/KenshinPro | KenshinPro/KenshinPro/Classes/Controller/subNav/one/精通iOS开发第6版本/陀螺仪和加速计/滚弹珠程序/BallVC.h | 241 | //
// BallVC.h
// KenshinPro
//
// Created by apple on 2019/1/31.
// Copyright © 2019 Kenshin. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface BallVC : UIViewController
@end
NS_ASSUME_NONNULL_END
| mit |
MichaelYao88/phase-0 | week-6/gps.rb | 1806 | ## Your Names
# 1) Michael Yao
# 2) Benjamin Heidebrink
# We spent [1.25] hours on this challenge.
# Bakery Serving Size portion calculator.
def serving_size_calc(item_to_make, num_of_ingredients)
library = {"cookie" => 1, "cake" => 5, "pie" => 7}
raise ArgumentError.new("#{item_to_make} is not a valid input") unless library[item_to_make]
# fail ArgumentError, "#{item_to_make} is not a valid input" unless library.key?(item_to_make)
serving_size = library[item_to_make]
remaining_ingredients = num_of_ingredients % serving_size
baking_plan = "Calculations complete: Make #{num_of_ingredients / serving_size} of #{item_to_make}"
return baking_plan if remaining_ingredients.zero?
baking_plan + ", you have #{remaining_ingredients} leftover ingredients. Suggested baking items: #{leftovers(remaining_ingredients)}"
end
def leftovers(remaining_ingredients)
cakes=remaining_ingredients/5
cookies=remaining_ingredients%5
"#{cakes} cakes and #{cookies} cookies."
end
p serving_size_calc("pie", 7)
p serving_size_calc("pie", 8)
p serving_size_calc("cake", 5)
p serving_size_calc("cake", 7)
p serving_size_calc("cookie", 1)
p serving_size_calc("cookie", 10)
p serving_size_calc("THIS IS AN ERROR", 5)
# Reflection
# What did you learn about making code readable by working on this challenge?
# It's preeettty important. Also we learned some new methods/syntax to make it more readable and truthy/falsey
# Did you learn any new methods? What did you learn about them?
# .zero? .key? .nil? .values_at
# What did you learn about accessing data in hashes?
# .values_at returns an array, .key checks for keys., if we show one argument it will return an array of hash/key
# What concepts were solidified when working through this challenge?
# refactoring, some syntax | mit |
wizardbeard/agency-iq | app/helpers/palm_tasks_helper.rb | 27 | module PalmTasksHelper
end
| mit |
goblindegook/littlefoot | src/dom/document.ts | 7139 | import 'css.escape'
import { createFootnote, FootnoteElements } from './footnote'
import { bindScrollHandler } from './scroll'
import { Adapter } from '../core'
import { addClass, removeClass, unmount } from './element'
export const CLASS_CONTENT = 'littlefoot__content'
export const CLASS_WRAPPER = 'littlefoot__wrapper'
export type HTMLAdapterSettings = Readonly<{
allowDuplicates: boolean
anchorParentSelector: string
anchorPattern: RegExp
buttonTemplate: string
contentTemplate: string
footnoteSelector: string
numberResetSelector: string
scope: string
}>
type TemplateData = Readonly<{
number: number
id: string
content: string
reference: string
}>
type Original = Readonly<{
reference: HTMLElement
referenceId: string
body: HTMLElement
}>
type OriginalData = Readonly<{
original: Original
data: TemplateData
}>
const CLASS_PRINT_ONLY = 'littlefoot--print'
const CLASS_HOST = 'littlefoot'
const setPrintOnly = (el: Element) => addClass(el, CLASS_PRINT_ONLY)
function queryAll<E extends Element>(
parent: ParentNode,
selector: string
): readonly E[] {
return Array.from(parent.querySelectorAll<E>(selector))
}
function getByClassName<E extends Element>(element: E, className: string): E {
return (
element.querySelector<E>('.' + className) ||
(element.firstElementChild as E | null) ||
element
)
}
function createElementFromHTML(html: string): HTMLElement {
const container = document.createElement('div')
container.innerHTML = html
return container.firstElementChild as HTMLElement
}
function children(element: Element, selector: string): readonly Element[] {
return Array.from(element.children).filter(
(child) => child.nodeType !== 8 && child.matches(selector)
)
}
function isDefined<T>(value?: T): value is T {
return value !== undefined
}
function findFootnoteLinks(
document: Document,
pattern: RegExp,
scope: string
): readonly HTMLAnchorElement[] {
return queryAll<HTMLAnchorElement>(document, scope + ' a[href*="#"]').filter(
(link) => (link.href + link.rel).match(pattern)
)
}
function findReference(
document: Document,
allowDuplicates: boolean,
anchorParentSelector: string,
footnoteSelector: string
) {
const processed: Element[] = []
return (link: HTMLAnchorElement): Original | undefined => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const fragment = link.href.split('#')[1]!
const related = queryAll(document, '#' + CSS.escape(fragment)).find(
(footnote) => allowDuplicates || !processed.includes(footnote)
)
const body = related?.closest<HTMLElement>(footnoteSelector)
if (body) {
processed.push(body)
const reference = link.closest<HTMLElement>(anchorParentSelector) || link
const referenceId = reference.id || link.id
return { reference, referenceId, body }
}
}
}
function recursiveHideFootnoteContainer(element: HTMLElement): void {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const container = element.parentElement!
const visibleElements = children(container, `:not(.${CLASS_PRINT_ONLY})`)
const visibleSeparators = visibleElements.filter((el) => el.tagName === 'HR')
if (visibleElements.length === visibleSeparators.length) {
visibleSeparators.concat(container).forEach(setPrintOnly)
recursiveHideFootnoteContainer(container)
}
}
function recursiveUnmount(element: HTMLElement) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const parent = element.parentElement!
unmount(element)
const html = parent.innerHTML.replace('[]', '').replace(' ', ' ').trim()
if (!html) {
recursiveUnmount(parent)
}
}
function prepareTemplateData(original: Original, idx: number): OriginalData {
const content = createElementFromHTML(original.body.outerHTML)
const backlinkSelector = '[href$="#' + original.referenceId + '"]'
queryAll<HTMLElement>(content, backlinkSelector).forEach(recursiveUnmount)
const html = content.innerHTML.trim()
return {
original,
data: {
id: String(idx + 1),
number: idx + 1,
reference: 'lf-' + original.referenceId,
content: html.startsWith('<') ? html : '<p>' + html + '</p>',
},
}
}
const resetNumbers = (resetSelector: string) => {
let current = 0
let previousParent: Element | null = null
return ({ original, data }: OriginalData): OriginalData => {
const parent = original.reference.closest(resetSelector)
current = previousParent === parent ? current + 1 : 1
previousParent = parent
return { original, data: { ...data, number: current } }
}
}
function interpolate(template: string) {
const pattern = /<%=?\s*(\w+?)\s*%>/g
return (replacement: TemplateData) =>
template.replace(pattern, (_, key: keyof TemplateData) =>
String(replacement[key] ?? '')
)
}
function createElements(buttonTemplate: string, popoverTemplate: string) {
const renderButton = interpolate(buttonTemplate)
const renderPopover = interpolate(popoverTemplate)
return ({
original,
data,
}: OriginalData): OriginalData & FootnoteElements => {
const id = data.id
const host = createElementFromHTML(
`<span class="${CLASS_HOST}">${renderButton(data)}</span>`
)
const button = host.firstElementChild as HTMLElement
button.setAttribute('aria-expanded', 'false')
button.dataset.footnoteButton = ''
button.dataset.footnoteId = id
const popover = createElementFromHTML(renderPopover(data))
popover.dataset.footnotePopover = ''
popover.dataset.footnoteId = id
const wrapper = getByClassName(popover, CLASS_WRAPPER)
const content = getByClassName(popover, CLASS_CONTENT)
bindScrollHandler(content, popover)
return { original, data, id, button, host, popover, content, wrapper }
}
}
function attachFootnote(reference: HTMLElement, host: HTMLElement): void {
reference.insertAdjacentElement('beforebegin', host)
}
export function setup({
allowDuplicates,
anchorParentSelector,
anchorPattern,
buttonTemplate,
contentTemplate,
footnoteSelector,
numberResetSelector,
scope,
}: HTMLAdapterSettings): Adapter<HTMLElement> {
const footnoteElements = findFootnoteLinks(document, anchorPattern, scope)
.map(
findReference(
document,
allowDuplicates,
anchorParentSelector,
footnoteSelector
)
)
.filter(isDefined)
.map(prepareTemplateData)
.map(numberResetSelector ? resetNumbers(numberResetSelector) : (i) => i)
.map(createElements(buttonTemplate, contentTemplate))
footnoteElements.forEach(({ original, host }) => {
setPrintOnly(original.reference)
setPrintOnly(original.body)
recursiveHideFootnoteContainer(original.body)
attachFootnote(original.reference, host)
})
const footnotes = footnoteElements.map(createFootnote)
return {
footnotes,
unmount() {
footnotes.forEach((footnote) => footnote.destroy())
queryAll(document, '.' + CLASS_PRINT_ONLY).forEach((element) =>
removeClass(element, CLASS_PRINT_ONLY)
)
},
}
}
| mit |
janko-m/roda | spec/plugin/caching_spec.rb | 10994 | require File.expand_path("spec_helper", File.dirname(File.dirname(__FILE__)))
describe 'response.cache_control' do
it 'sets the Cache-Control header' do
app(:caching) do |r|
response.cache_control :public=>true, :no_cache=>true, :max_age => 60
end
header('Cache-Control').split(', ').sort.should == ['max-age=60', 'no-cache', 'public']
end
it 'does not add a Cache-Control header if it would be empty' do
app(:caching) do |r|
response.cache_control({})
end
header('Cache-Control').should == nil
end
end
describe 'response.expires' do
it 'sets the Cache-Control and Expires header' do
app(:caching) do |r|
response.expires 60, :public=>true, :no_cache=>true
end
header('Cache-Control').split(', ').sort.should == ['max-age=60', 'no-cache', 'public']
((Time.httpdate(header('Expires')) - Time.now).round - 60).abs.should <= 1
end
it 'can be called with only one argument' do
app(:caching) do |r|
response.expires 60
end
header('Cache-Control').split(', ').sort.should == ['max-age=60']
((Time.httpdate(header('Expires')) - Time.now).round - 60).abs.should <= 1
end
end
describe 'response.finish' do
it 'removes Content-Type and Content-Length for 304 responses' do
app(:caching) do |r|
response.status = 304
end
header('Content-Type').should == nil
header('Content-Length').should == nil
end
it 'does not change non-304 responses' do
app(:caching) do |r|
response.status = 200
end
header('Content-Type').should == 'text/html'
header('Content-Length').should == '0'
end
end
describe 'request.last_modified' do
it 'ignores nil' do
app(:caching) do |r|
r.last_modified nil
end
header('Last-Modified').should == nil
end
it 'does not change a status other than 200' do
app(:caching) do |r|
response.status = 201
r.last_modified Time.now
end
status.should == 201
status('HTTP_IF_MODIFIED_SINCE' => 'Sun, 26 Sep 2030 23:43:52 GMT').should == 201
status('HTTP_IF_MODIFIED_SINCE' => 'Sun, 26 Sep 2000 23:43:52 GMT').should == 201
end
end
describe 'request.last_modified' do
def res(a={})
s, h, b = req(a)
h['Last-Modified'].should == @last_modified.httpdate
[s, b.join]
end
before(:all) do
lm = @last_modified = Time.now
app(:caching) do |r|
r.last_modified lm
'ok'
end
end
it 'just sets Last-Modified if no If-Modified-Since header' do
res.should == [200, 'ok']
end
it 'just sets Last-Modified if bogus If-Modified-Since header' do
res('HTTP_IF_MODIFIED_SINCE' => 'a really weird date').should == [200, 'ok']
end
it 'just sets Last-Modified if modified since If-Modified-Since header' do
res('HTTP_IF_MODIFIED_SINCE' => (@last_modified - 1).httpdate).should == [200, 'ok']
end
it 'sets Last-Modified and returns 304 if modified on If-Modified-Since header' do
res('HTTP_IF_MODIFIED_SINCE' => @last_modified.httpdate).should == [304, '']
end
it 'sets Last-Modified and returns 304 if modified before If-Modified-Since header' do
res('HTTP_IF_MODIFIED_SINCE' => (@last_modified + 1).httpdate).should == [304, '']
end
it 'sets Last-Modified if If-None-Match header present' do
res('HTTP_IF_NONE_MATCH' => '*', 'HTTP_IF_MODIFIED_SINCE' => (@last_modified + 1).httpdate).should == [200, 'ok']
end
it 'sets Last-Modified if modified before If-Unmodified-Since header' do
res('HTTP_IF_UNMODIFIED_SINCE' => (@last_modified + 1).httpdate).should == [200, 'ok']
end
it 'sets Last-Modified if modified on If-Unmodified-Since header' do
res('HTTP_IF_UNMODIFIED_SINCE' => @last_modified.httpdate).should == [200, 'ok']
end
it 'sets Last-Modified and returns 412 if modified after If-Unmodified-Since header' do
res('HTTP_IF_UNMODIFIED_SINCE' => (@last_modified - 1).httpdate).should == [412, '']
end
end
describe 'request.etag' do
before(:all) do
app(:caching) do |r|
r.is "" do
response.status = r.env['status'] if r.env['status']
etag_opts = {}
etag_opts[:new_resource] = r.env['new_resource'] if r.env.has_key?('new_resource')
etag_opts[:weak] = r.env['weak'] if r.env.has_key?('weak')
r.etag 'foo', etag_opts
'ok'
end
end
end
it 'uses a weak etag with the :weak option' do
header('ETag', 'weak'=>true).should == 'W/"foo"'
end
describe 'for GET requests' do
def res(a={})
s, h, b = req(a)
h['ETag'].should == '"foo"'
[s, b.join]
end
it "sets etag if no If-None-Match" do
res.should == [200, 'ok']
end
it "sets etag and returns 304 if If-None-Match is *" do
res('HTTP_IF_NONE_MATCH' => '*').should == [304, '']
end
it "sets etag and if If-None-Match is * and it is a new resource" do
res('HTTP_IF_NONE_MATCH' => '*', 'new_resource'=>true).should == [200, 'ok']
end
it "sets etag and returns 304 if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"').should == [304, '']
end
it "sets etag and returns 304 if If-None-Match includes etag" do
res('HTTP_IF_NONE_MATCH' => '"bar", "foo"').should == [304, '']
end
it "sets etag if If-None-Match does not include etag" do
res('HTTP_IF_NONE_MATCH' => '"bar", "baz"').should == [200, 'ok']
end
it "sets etag and does not change status code if status code set and not 2xx or 304 if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>499).should == [499, 'ok']
end
it "sets etag and returns 304 if status code set to 2xx if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>201).should == [304, '']
end
it "sets etag and returns 304 if status code is already 304 if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>304).should == [304, '']
end
it "sets etag if If-Match is *" do
res('HTTP_IF_MATCH' => '*').should == [200, 'ok']
end
it "sets etag if If-Match is etag" do
res('HTTP_IF_MATCH' => '"foo"').should == [200, 'ok']
end
it "sets etag if If-Match includes etag" do
res('HTTP_IF_MATCH' => '"bar", "foo"').should == [200, 'ok']
end
it "sets etag and returns 412 if If-Match is * for new resources" do
res('HTTP_IF_MATCH' => '*', 'new_resource'=>true).should == [412, '']
end
it "sets etag if If-Match does not include etag" do
res('HTTP_IF_MATCH' => '"bar", "baz"', 'new_resource'=>true).should == [412, '']
end
end
describe 'for PUT requests' do
def res(a={})
s, h, b = req(a.merge('REQUEST_METHOD'=>'PUT'))
h['ETag'].should == '"foo"'
[s, b.join]
end
it "sets etag if no If-None-Match" do
res.should == [200, 'ok']
end
it "sets etag and returns 412 if If-None-Match is *" do
res('HTTP_IF_NONE_MATCH' => '*').should == [412, '']
end
it "sets etag and if If-None-Match is * and it is a new resource" do
res('HTTP_IF_NONE_MATCH' => '*', 'new_resource'=>true).should == [200, 'ok']
end
it "sets etag and returns 412 if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"').should == [412, '']
end
it "sets etag and returns 412 if If-None-Match includes etag" do
res('HTTP_IF_NONE_MATCH' => '"bar", "foo"').should == [412, '']
end
it "sets etag if If-None-Match does not include etag" do
res('HTTP_IF_NONE_MATCH' => '"bar", "baz"').should == [200, 'ok']
end
it "sets etag and does not change status code if status code set and not 2xx or 304 if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>499).should == [499, 'ok']
end
it "sets etag and returns 304 if status code set to 2xx if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>201).should == [412, '']
end
it "sets etag and returns 304 if status code is already 304 if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>304).should == [412, '']
end
it "sets etag if If-Match is *" do
res('HTTP_IF_MATCH' => '*').should == [200, 'ok']
end
it "sets etag if If-Match is etag" do
res('HTTP_IF_MATCH' => '"foo"').should == [200, 'ok']
end
it "sets etag if If-Match includes etag" do
res('HTTP_IF_MATCH' => '"bar", "foo"').should == [200, 'ok']
end
it "sets etag and returns 412 if If-Match is * for new resources" do
res('HTTP_IF_MATCH' => '*', 'new_resource'=>true).should == [412, '']
end
it "sets etag if If-Match does not include etag" do
res('HTTP_IF_MATCH' => '"bar", "baz"', 'new_resource'=>true).should == [412, '']
end
end
describe 'for POST requests' do
def res(a={})
s, h, b = req(a.merge('REQUEST_METHOD'=>'POST'))
h['ETag'].should == '"foo"'
[s, b.join]
end
it "sets etag if no If-None-Match" do
res.should == [200, 'ok']
end
it "sets etag and returns 412 if If-None-Match is * and it is not a new resource" do
res('HTTP_IF_NONE_MATCH' => '*', 'new_resource'=>false).should == [412, '']
end
it "sets etag and if If-None-Match is *" do
res('HTTP_IF_NONE_MATCH' => '*').should == [200, 'ok']
end
it "sets etag and returns 412 if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"').should == [412, '']
end
it "sets etag and returns 412 if If-None-Match includes etag" do
res('HTTP_IF_NONE_MATCH' => '"bar", "foo"').should == [412, '']
end
it "sets etag if If-None-Match does not include etag" do
res('HTTP_IF_NONE_MATCH' => '"bar", "baz"').should == [200, 'ok']
end
it "sets etag and does not change status code if status code set and not 2xx or 304 if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>499).should == [499, 'ok']
end
it "sets etag and returns 304 if status code set to 2xx if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>201).should == [412, '']
end
it "sets etag and returns 304 if status code is already 304 if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>304).should == [412, '']
end
it "sets etag if If-Match is * and this is not a new resource" do
res('HTTP_IF_MATCH' => '*', 'new_resource'=>false).should == [200, 'ok']
end
it "sets etag if If-Match is etag" do
res('HTTP_IF_MATCH' => '"foo"').should == [200, 'ok']
end
it "sets etag if If-Match includes etag" do
res('HTTP_IF_MATCH' => '"bar", "foo"').should == [200, 'ok']
end
it "sets etag and returns 412 if If-Match is * for new resources" do
res('HTTP_IF_MATCH' => '*').should == [412, '']
end
it "sets etag if If-Match does not include etag" do
res('HTTP_IF_MATCH' => '"bar", "baz"', 'new_resource'=>true).should == [412, '']
end
end
end
| mit |
charliezon/stock | www/templates/advanced_create_account.html | 4636 | {% extends '__base__.html' %}
{% block title %}创建账户{% endblock %}
{% block beforehead %}
<script>
var
action = '{{ action }}';
function initVM(account) {
var vm = new Vue({
el: '#vm',
data: account,
methods: {
submit: function (event) {
this.$data.date = $('#date').val();
event.preventDefault();
var $form = $('#vm').find('form');
$form.postJSON(action, this.$data, function (err, r) {
if (err) {
$form.showFormError(err);
}
else {
return location.assign('/account/' + r.id);
}
});
}
}
});
$('#vm').show();
}
$(function () {
$('#loading').hide();
initVM({
name: '',
buy_strategy: '',
sell_strategy: '',
commission_rate: 0.0002,
initial_funding: 0,
initial_bank_funding: 0,
initial_security_funding: 0,
date: getTodayString()
});
});
</script>
{% endblock %}
{% block content %}
<div id="error" class="uk-width-1-1">
</div>
<div id="loading" class="uk-width-1-1 uk-text-center">
<span><i class="uk-icon-spinner uk-icon-medium uk-icon-spin"></i> 正在加载...</span>
</div>
<div id="vm" class="uk-width-1-1">
<form v-on="submit: submit" class="uk-form uk-form-stacked">
<div class="uk-alert uk-alert-danger uk-hidden"></div>
<div class="uk-form-row">
<label class="uk-form-label">账户名称:</label>
<div class="uk-form-controls">
<input v-model="name" name="name" type="text" placeholder="账户名称" class="uk-width-1-1">
</div>
</div>
<div class="uk-form-row">
<label class="uk-form-label">买入策略:</label>
<div class="uk-form-controls">
<input v-model="buy_strategy" name="buy_strategy" type="text" placeholder="买入策略" class="uk-width-1-1">
</div>
</div>
<div class="uk-form-row">
<label class="uk-form-label">卖出策略:</label>
<div class="uk-form-controls">
<input v-model="sell_strategy" name="sell_strategy" type="text" placeholder="卖出策略" class="uk-width-1-1">
</div>
</div>
<div class="uk-form-row">
<label class="uk-form-label">手续费率:</label>
<div class="uk-form-controls">
<input v-model="commission_rate" name="commission_rate" type="text" placeholder="手续费率" class="uk-width-1-1">
</div>
</div>
<div class="uk-form-row">
<label class="uk-form-label">初始本金:</label>
<div class="uk-form-controls">
<input v-model="initial_funding" name="initial_funding" type="text" placeholder="初始本金" class="uk-width-1-1">
</div>
</div>
<div class="uk-form-row">
<label class="uk-form-label">现有银行资金:</label>
<div class="uk-form-controls">
<input v-model="initial_bank_funding" name="initial_bank_funding" type="text" placeholder="现有银行资金" class="uk-width-1-1">
</div>
</div>
<div class="uk-form-row">
<label class="uk-form-label">现有银证资金:</label>
<div class="uk-form-controls">
<input v-model="initial_security_funding" name="initial_security_funding" type="text" placeholder="现有银证资金" class="uk-width-1-1">
</div>
</div>
<div class="uk-form-row">
<label class="uk-form-label">起始日期:</label>
<div class="uk-form-controls">
<input id="date" v-model="date" name="date" type="text" data-uk-datepicker="{format:'YYYY-MM-DD'}" class="uk-width-1-1">
</div>
</div>
<div class="uk-form-row">
<button type="submit" class="uk-button uk-button-primary"><i class="uk-icon-save"></i> 保存</button>
<a href="/account/create" class="uk-button"><i class="uk-icon-compress"></i> 基本选项</a>
<a href="/" class="uk-button"><i class="uk-icon-times"></i> 取消</a>
</div>
</form>
</div>
{% endblock %}
| mit |
jphager2/john-hager-info | db/migrate/20160627182212_remove_od_token_from_users.rb | 114 | class RemoveOdTokenFromUsers < ActiveRecord::Migration
def change
remove_column :users, :od_token
end
end
| mit |
jyen/corporate-challenge | mobile/www/app/car/detail/detail.controller.js | 401 | (function() {
angular.module('starter.controllers').controller('DetailController', DetailController);
DetailController.$inject = ['CarService', '$stateParams'];
function DetailController (CarService, $stateParams) {
var vm = this;
CarService.getCar($stateParams.id).$promise.then(function(data) {
vm.car = data;
CarService.setCurrentCar(data);
}
);
}
})();
| mit |
comblox/PnP-Guidance | articles/Move-O365Api-Project-from-Dev-To-Prod.md | 9923 | # Deploying Development Office 365 Sites to Microsoft Azure #
### Summary ###
When developing any type a web application, most development is done locally using http://localhost. Some projects use local resources or a mix of local and remote resources. Taking these projects from local development environments involves a handful of tasks to perform like changing database connection strings, URLs, configurations, etc.
Web projects that leverage the Office 365 APIs are no different. These projects leverage Microsoft's Azure AD service to authenticate the applications and obtain OAuth 2.0 access tokens. These tokens are used by the web applications to authenticate with the Office 365 APIs.
This page explains the steps involved in taking an Office 365 API development project and launching it to a working sample hosted entirely in Microsoft Azure using [Office 365](http://products.office.com/en-us/business/explore-office-365-for-business), [Azure Active Directory](http://azure.microsoft.com/en-us/services/active-directory/) & [Azure Websites](http://azure.microsoft.com/en-us/services/websites/.
Deploying an Office 365 API web application to Microsoft Azure from a local development environment requires three high-level steps to be performed as outlined in this page:
- [Create and Configure an Azure Website](#create-and-configure-an-azure-website)
- [Configure the Azure AD Application](#configure-the-azure-ad-application)
- [Configure the ASP.NET Project](#configure-the-aspnet-project)
- [Deploy the Office 365 API ASP.NET Web Application](#deploy-the-office-365-api-aspnet-web-application)
> This page assumes that you have a local working ASP.NET application that uses the Office 365 APIs. For reference, it will use the **[O365-WebApp-SingleTenant](https://github.com/OfficeDev/O365-WebApp-SingleTenant)** project found in the **[OfficeDev](https://github.com/OfficeDev)** account in GitHub.
# Create and Configure an Azure Website
In this step you will create an Azure website that will be used to host the web application.
1. Navigate to the [Azure Management Portal](https://manage.windowsazure.com) and login using your Organization ID account.
1. After logging in, using the navigation sidebar, select **WEBSITES**.
1. On the **websites** page, click the **NEW** link in the footer found in the lower-left corner of the page.
1. In the wizard that appears, select **Quick Create**, enter a name for the site in the **URL** field, select a **Web Hosting Plan** and **Subscription**.

> Make sure to keep a note of the name of the website you create as it will be needed later.
1. Finally click the **Create Website** link to create the site.
Give Azure a few moments to create the site. After creating the site you can specify *app settings* through the web interface. This allows you to override any `<appSettings>` within the project's `web.config` file through the web administration interface for the website without deploying your site codebase for simple `web.config` changes.
1. Click the website that you just created within the **Azure Management Portal**.
1. CLick the **CONFIGURE** link in the top navigation.
1. Scroll down to the **App Settings** section and add three new entries:
- **ida:ClientID**
- **ida:Password**
- **ida:TenantID**
1. Copy the corresponding values from the working project's `web.config` to these settings values in your Azure website as shown in the following figure:

1. In the footer, click the **SAVE** button to save your changes.
At this point the Azure website is setup and configured to host the Office 365 API web project that you will deploy in a later step.
[back to top](#deploying-development-office-365-sites-to-microsoft-azure)
# Configure the Azure AD Application
In this step you will modify the Azure AD application used in the development & testing of the Office 365 application.
1. Navigate to the [Azure Management Portal](https://manage.windowsazure.com) and login using your Organization ID account.
1. After logging in, using the navigation sidebar, select **ACTIVE DIRECTORY**.
1. On the **active directory** page, select the directory that is linked to your Office 365 tenant.
1. Next, click the **APPLICATIONS** item in the top navigation.
1. Within the **Properties** section, update the **SIGN-ON URL** to point to the default URL of the Azure Website you created. Take note to use the HTTPS endpoint that is provided with all Azure websites.

1. Within the **Single Sign-On** section, update the **App ID URI** to use the domain for the Azure website (shown in the following figure).
1. Next, update the **REPLY URL** so the only URL listed is the homepage of the Azure website:

1. In the footer, click the **SAVE** button to save your changes.
At this point, the Azure AD application used by the Office 365 API web project has been configured to work with the new Azure website.
[back to top](#deploying-development-office-365-sites-to-microsoft-azure)
# Configure the ASP.NET Project
In this step you will configure the ASP.NET project in your application to use the new Azure Website.
For the sample application used in the example for this guidance, no extra work is actually required. However the web application does contain the settings within the `web.config` file for the Azure AD application and Azure AD tenant used during development. Some developers may choose to use different Azure AD applications or even different Azure subscriptions for their development and production instances.
In a previous step outlined in this page, when you created the Azure website you set the add-in settings for the application that are typically found in the `web.config`. To ensure the web application receives these values from the Azure website configuration, it's recommended you replace the values within the `web.config` with placeholder values instead.
1. Open the project's `web.config` file.
1. Locate the add-in settings for the **ida:ClientID**, **ida:Password** and **ida:TenantId**.
1. Replace the values of these settings with a placeholder value:
````xml
<add key="ida:TenantId" value="set-in-azure-website-config" />
<add key="ida:ClientID" value="set-in-azure-website-config" />
<add key="ida:Password" value="set-in-azure-website-config" />
````
1. Save you changes.
At this point the web application, Azure website & application in Azure AD are all configured correctly and ready to be deployed.
[back to top](#deploying-development-office-365-sites-to-microsoft-azure)
# Deploy the Office 365 API ASP.NET Web Application
In this step you will publish the Office 365 API web application to the Azure website. Once the site has been deployed you will test it to ensure everything works as desired.
> This step assumes you have he Microsoft [Azure SDK](http://azure.microsoft.com/en-us/downloads/), version 2.0 or higher, installed.
## Deploy the ASP.NET Web Application
1. Open your Office 365 API web application in Visual Studio 2013.
1. Within the Solution Explorer tool window, right-click the project and select **Publish** start the **Publish Web** wizard.
1. On the **Profile** tab, select **Microsoft Azure Website**.
At this point you will be prompted to login to your Azure subscription using your Organization ID.
1. After logging in, select the website that you created in a previous step from this page and click **OK**.

1. On the **Connection** tab, click the **Validate Connection** button to ensure the connection profile was successfully downloaded and applied.

1. Click the **Publish** button to publish the web application to the Azure website.
## Test the ASP.NET Web Application
After publishing the web application to the Azure website, Visual Studio will open a browser and navigate to the site's homepage.
By default this is the HTTP endpoint. Recall from the previous step when you configured the Azure AD application that you set it to only accept sign ons from the HTTPS endpoint. Before you use the application update the url to point to the HTTPS endpoint.
1. In the browser, update the URL to go to the HTTPS homepage for the Azure website. In the example in this page, that is https://o365api-01.azurewebsites.net.
1. Click the **Sign In** link in the header at the top-right of the page. This will redirect you to the Azure AD sign on page.
> If you get an error at this point, it's likely an issue with the three add-in settings you created for the Azure website. Go back and make sure the values are the correct values from the Azure AD tenant & application. You should see a URL that looks
1. After successfully logging in, you will be redirected back to the homepage for the web application of the Azure website you created.
At this point you have successfully deployed your Office 365 API web application project to run in an Azure website.
[back to top](#deploying-development-office-365-sites-to-microsoft-azure)
----------
### Related links ###
- [O365-WebApp-SingleTenant](https://github.com/OfficeDev/O365-WebApp-SingleTenant)
### Applies to ###
- Office 365 Multi Tenant (MT)
- Office 365 Dedicated (D)
### Author
Andrew Connell - [@andrewconnell](https://twitter.com/andrewconnell)
### Version history ###
Version | Date | Comments
---------| -----| --------
0.1 | January 2, 2015 | First draft
| mit |
ssut/py-hanspell | tests.py | 2729 | # -*- coding: utf-8 -*-
import unittest
from hanspell import spell_checker
from hanspell.constants import CheckResult
from textwrap import dedent as trim
class SpellCheckerTests(unittest.TestCase):
def setUp(self):
pass
def test_basic_check(self):
result = spell_checker.check(u'안녕 하세요. 저는 한국인 입니다. 이문장은 한글로 작성됬습니다.')
assert result.errors == 4
assert result.checked == u'안녕하세요. 저는 한국인입니다. 이 문장은 한글로 작성됐습니다.'
def test_words(self):
result = spell_checker.check(u'한아이가 장난깜을 갖고놀고있다. 그만하게 할가?')
assert result.errors == 4
items = result.words
assert items[u'한'] == CheckResult.WRONG_SPACING
assert items[u'아이가'] == CheckResult.WRONG_SPACING
assert items[u'장난감을'] == CheckResult.STATISTICAL_CORRECTION
assert items[u'갖고'] == CheckResult.WRONG_SPACING
assert items[u'놀고'] == CheckResult.WRONG_SPACING
assert items[u'있다.'] == CheckResult.WRONG_SPACING
assert items[u'그만하게'] == CheckResult.PASSED
assert items[u'할까?'] == CheckResult.WRONG_SPELLING
def test_list(self):
results = spell_checker.check([u'안녕 하세요.', u'저는 한국인 입니다.'])
assert results[0].checked == u'안녕하세요.'
assert results[1].checked == u'저는 한국인입니다.'
def test_long_paragraph(self):
paragraph = trim("""
ubit.info(유빗인포)는 코나미 리듬게임, 유비트의 플레이 데이터 관리 및 열람 서비스입니다. 등록 후에 자신과 친구의 기록을 p.eagate.573.jp에 접속할 필요 없이 본 웹 사이트에서 바로 확인할 수 있습니다.
등록 후에는 "https://ubit.info/별칭"으로 자신의 개인 페이지가 생성되며 이 주소(별칭)를 아는 사람만 접속할 수 있습니다. 다른 친구에게 기록을 보여주고 싶다면 본인의 인포 주소를 알려주면 됩니다.
이 사이트는 최신 브라우저 환경만을 제대로 지원합니다. 만약 크롬, 파이어폭스 등의 최신 브라우저 안정버전(stable)을 사용하고 있는데도 페이지 레이아웃이 깨지는 경우 사이트 관리자에게 문의해주세요.
등록 과정은 간단합니다. 상단 메뉴에서 등록을 클릭한 후 양식에 맞게 입력하시면 자동으로 공개설정이 완료됨과 동시에 유빗인포 계정이 생성됩니다.
""")
result = spell_checker.check(paragraph)
if __name__ == '__main__':
unittest.main()
| mit |
composer/composer | src/Composer/DependencyResolver/RuleSetGenerator.php | 13501 | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <[email protected]>
* Jordi Boggiano <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
use Composer\Filter\PlatformRequirementFilter\IgnoreListPlatformRequirementFilter;
use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterFactory;
use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterInterface;
use Composer\Package\BasePackage;
use Composer\Package\AliasPackage;
/**
* @author Nils Adermann <[email protected]>
* @phpstan-import-type ReasonData from Rule
*/
class RuleSetGenerator
{
/** @var PolicyInterface */
protected $policy;
/** @var Pool */
protected $pool;
/** @var RuleSet */
protected $rules;
/** @var array<int, BasePackage> */
protected $addedMap = array();
/** @var array<string, BasePackage[]> */
protected $addedPackagesByNames = array();
public function __construct(PolicyInterface $policy, Pool $pool)
{
$this->policy = $policy;
$this->pool = $pool;
$this->rules = new RuleSet;
}
/**
* Creates a new rule for the requirements of a package
*
* This rule is of the form (-A|B|C), where B and C are the providers of
* one requirement of the package A.
*
* @param BasePackage $package The package with a requirement
* @param BasePackage[] $providers The providers of the requirement
* @param Rule::RULE_* $reason A RULE_* constant describing the reason for generating this rule
* @param mixed $reasonData Any data, e.g. the requirement name, that goes with the reason
* @return Rule|null The generated rule or null if tautological
*
* @phpstan-param ReasonData $reasonData
*/
protected function createRequireRule(BasePackage $package, array $providers, $reason, $reasonData = null): ?Rule
{
$literals = array(-$package->id);
foreach ($providers as $provider) {
// self fulfilling rule?
if ($provider === $package) {
return null;
}
$literals[] = $provider->id;
}
return new GenericRule($literals, $reason, $reasonData);
}
/**
* Creates a rule to install at least one of a set of packages
*
* The rule is (A|B|C) with A, B and C different packages. If the given
* set of packages is empty an impossible rule is generated.
*
* @param BasePackage[] $packages The set of packages to choose from
* @param Rule::RULE_* $reason A RULE_* constant describing the reason for
* generating this rule
* @param mixed $reasonData Additional data like the root require or fix request info
* @return Rule The generated rule
*
* @phpstan-param ReasonData $reasonData
*/
protected function createInstallOneOfRule(array $packages, $reason, $reasonData): Rule
{
$literals = array();
foreach ($packages as $package) {
$literals[] = $package->id;
}
return new GenericRule($literals, $reason, $reasonData);
}
/**
* Creates a rule for two conflicting packages
*
* The rule for conflicting packages A and B is (-A|-B). A is called the issuer
* and B the provider.
*
* @param BasePackage $issuer The package declaring the conflict
* @param BasePackage $provider The package causing the conflict
* @param Rule::RULE_* $reason A RULE_* constant describing the reason for generating this rule
* @param mixed $reasonData Any data, e.g. the package name, that goes with the reason
* @return ?Rule The generated rule
*
* @phpstan-param ReasonData $reasonData
*/
protected function createRule2Literals(BasePackage $issuer, BasePackage $provider, $reason, $reasonData = null): ?Rule
{
// ignore self conflict
if ($issuer === $provider) {
return null;
}
return new Rule2Literals(-$issuer->id, -$provider->id, $reason, $reasonData);
}
/**
* @param BasePackage[] $packages
* @param Rule::RULE_* $reason A RULE_* constant
* @param mixed $reasonData
* @return Rule
*
* @phpstan-param ReasonData $reasonData
*/
protected function createMultiConflictRule(array $packages, $reason, $reasonData): Rule
{
$literals = array();
foreach ($packages as $package) {
$literals[] = -$package->id;
}
if (\count($literals) == 2) {
return new Rule2Literals($literals[0], $literals[1], $reason, $reasonData);
}
return new MultiConflictRule($literals, $reason, $reasonData);
}
/**
* Adds a rule unless it duplicates an existing one of any type
*
* To be able to directly pass in the result of one of the rule creation
* methods null is allowed which will not insert a rule.
*
* @param RuleSet::TYPE_* $type A TYPE_* constant defining the rule type
* @param Rule $newRule The rule about to be added
*
* @return void
*/
private function addRule($type, Rule $newRule = null): void
{
if (!$newRule) {
return;
}
$this->rules->add($newRule, $type);
}
/**
* @return void
*/
protected function addRulesForPackage(BasePackage $package, PlatformRequirementFilterInterface $platformRequirementFilter): void
{
/** @var \SplQueue<BasePackage> */
$workQueue = new \SplQueue;
$workQueue->enqueue($package);
while (!$workQueue->isEmpty()) {
$package = $workQueue->dequeue();
if (isset($this->addedMap[$package->id])) {
continue;
}
$this->addedMap[$package->id] = $package;
if (!$package instanceof AliasPackage) {
foreach ($package->getNames(false) as $name) {
$this->addedPackagesByNames[$name][] = $package;
}
} else {
$workQueue->enqueue($package->getAliasOf());
$this->addRule(RuleSet::TYPE_PACKAGE, $this->createRequireRule($package, array($package->getAliasOf()), Rule::RULE_PACKAGE_ALIAS, $package));
// aliases must be installed with their main package, so create a rule the other way around as well
$this->addRule(RuleSet::TYPE_PACKAGE, $this->createRequireRule($package->getAliasOf(), array($package), Rule::RULE_PACKAGE_INVERSE_ALIAS, $package->getAliasOf()));
// if alias package has no self.version requires, its requirements do not
// need to be added as the aliased package processing will take care of it
if (!$package->hasSelfVersionRequires()) {
continue;
}
}
foreach ($package->getRequires() as $link) {
$constraint = $link->getConstraint();
if ($platformRequirementFilter->isIgnored($link->getTarget())) {
continue;
} elseif ($platformRequirementFilter instanceof IgnoreListPlatformRequirementFilter) {
$constraint = $platformRequirementFilter->filterConstraint($link->getTarget(), $constraint);
}
$possibleRequires = $this->pool->whatProvides($link->getTarget(), $constraint);
$this->addRule(RuleSet::TYPE_PACKAGE, $this->createRequireRule($package, $possibleRequires, Rule::RULE_PACKAGE_REQUIRES, $link));
foreach ($possibleRequires as $require) {
$workQueue->enqueue($require);
}
}
}
}
/**
* @return void
*/
protected function addConflictRules(PlatformRequirementFilterInterface $platformRequirementFilter): void
{
/** @var BasePackage $package */
foreach ($this->addedMap as $package) {
foreach ($package->getConflicts() as $link) {
// even if conlict ends up being with an alias, there would be at least one actual package by this name
if (!isset($this->addedPackagesByNames[$link->getTarget()])) {
continue;
}
$constraint = $link->getConstraint();
if ($platformRequirementFilter->isIgnored($link->getTarget())) {
continue;
} elseif ($platformRequirementFilter instanceof IgnoreListPlatformRequirementFilter) {
$constraint = $platformRequirementFilter->filterConstraint($link->getTarget(), $constraint);
}
$conflicts = $this->pool->whatProvides($link->getTarget(), $constraint);
foreach ($conflicts as $conflict) {
// define the conflict rule for regular packages, for alias packages it's only needed if the name
// matches the conflict exactly, otherwise the name match is by provide/replace which means the
// package which this is an alias of will conflict anyway, so no need to create additional rules
if (!$conflict instanceof AliasPackage || $conflict->getName() === $link->getTarget()) {
$this->addRule(RuleSet::TYPE_PACKAGE, $this->createRule2Literals($package, $conflict, Rule::RULE_PACKAGE_CONFLICT, $link));
}
}
}
}
foreach ($this->addedPackagesByNames as $name => $packages) {
if (\count($packages) > 1) {
$reason = Rule::RULE_PACKAGE_SAME_NAME;
$this->addRule(RuleSet::TYPE_PACKAGE, $this->createMultiConflictRule($packages, $reason, $name));
}
}
}
/**
* @return void
*/
protected function addRulesForRequest(Request $request, PlatformRequirementFilterInterface $platformRequirementFilter): void
{
foreach ($request->getFixedPackages() as $package) {
if ($package->id == -1) {
// fixed package was not added to the pool as it did not pass the stability requirements, this is fine
if ($this->pool->isUnacceptableFixedOrLockedPackage($package)) {
continue;
}
// otherwise, looks like a bug
throw new \LogicException("Fixed package ".$package->getPrettyString()." was not added to solver pool.");
}
$this->addRulesForPackage($package, $platformRequirementFilter);
$rule = $this->createInstallOneOfRule(array($package), Rule::RULE_FIXED, array(
'package' => $package,
));
$this->addRule(RuleSet::TYPE_REQUEST, $rule);
}
foreach ($request->getRequires() as $packageName => $constraint) {
if ($platformRequirementFilter->isIgnored($packageName)) {
continue;
} elseif ($platformRequirementFilter instanceof IgnoreListPlatformRequirementFilter) {
$constraint = $platformRequirementFilter->filterConstraint($packageName, $constraint);
}
$packages = $this->pool->whatProvides($packageName, $constraint);
if ($packages) {
foreach ($packages as $package) {
$this->addRulesForPackage($package, $platformRequirementFilter);
}
$rule = $this->createInstallOneOfRule($packages, Rule::RULE_ROOT_REQUIRE, array(
'packageName' => $packageName,
'constraint' => $constraint,
));
$this->addRule(RuleSet::TYPE_REQUEST, $rule);
}
}
}
/**
* @return void
*/
protected function addRulesForRootAliases(PlatformRequirementFilterInterface $platformRequirementFilter): void
{
foreach ($this->pool->getPackages() as $package) {
// ensure that rules for root alias packages and aliases of packages which were loaded are also loaded
// even if the alias itself isn't required, otherwise a package could be installed without its alias which
// leads to unexpected behavior
if (!isset($this->addedMap[$package->id]) &&
$package instanceof AliasPackage &&
($package->isRootPackageAlias() || isset($this->addedMap[$package->getAliasOf()->id]))
) {
$this->addRulesForPackage($package, $platformRequirementFilter);
}
}
}
/**
* @return RuleSet
*/
public function getRulesFor(Request $request, PlatformRequirementFilterInterface $platformRequirementFilter = null): RuleSet
{
$platformRequirementFilter = $platformRequirementFilter ?: PlatformRequirementFilterFactory::ignoreNothing();
$this->addRulesForRequest($request, $platformRequirementFilter);
$this->addRulesForRootAliases($platformRequirementFilter);
$this->addConflictRules($platformRequirementFilter);
// Remove references to packages
$this->addedMap = $this->addedPackagesByNames = array();
$rules = $this->rules;
$this->rules = new RuleSet;
return $rules;
}
}
| mit |
VinaLx/farm-spider | src/main/scala/spider/cli/cli.scala | 544 | package spider.cli
import command._
import spider.Util.errorExit
import com.typesafe.scalalogging.Logger
object CLI {
lazy val logger = Logger("spider.cli")
def go(args: Array[String]): Unit = args.toSeq match {
case e if args.isEmpty ⇒ Help(args)
case "scrape" +: tail ⇒ Scrape(tail)
case "wait" +: tail ⇒ Wait(tail)
case "help" +: tail ⇒ Help(tail)
case "remove" +: tail ⇒ Remove(tail)
case "getcat" +: tail ⇒ GetCategory(tail)
case other +: tail ⇒ errorExit(s"unknown command $other")
}
} | mit |
BenediktS/three.js | examples/js/renderers/plugins/DepthPassPlugin.js | 5549 | /**
* @author alteredq / http://alteredqualia.com/
*/
THREE.DepthPassPlugin = function () {
this.enabled = false;
this.renderTarget = null;
var _gl,
_renderer,
_lights, _webglObjects, _webglObjectsImmediate,
_depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
_frustum = new THREE.Frustum(),
_projScreenMatrix = new THREE.Matrix4(),
_renderList = [];
this.init = function ( renderer, lights, webglObjects, webglObjectsImmediate ) {
_gl = renderer.context;
_renderer = renderer;
_lights = lights;
_webglObjects = webglObjects;
_webglObjectsImmediate = webglObjectsImmediate;
var depthShader = THREE.ShaderLib[ "depthRGBA" ];
var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
_depthMaterial = new THREE.ShaderMaterial( {
fragmentShader: depthShader.fragmentShader,
vertexShader: depthShader.vertexShader,
uniforms: depthUniforms
} );
_depthMaterialMorph = new THREE.ShaderMaterial( {
fragmentShader: depthShader.fragmentShader,
vertexShader: depthShader.vertexShader,
uniforms: depthUniforms,
morphTargets: true
} );
_depthMaterialSkin = new THREE.ShaderMaterial( {
fragmentShader: depthShader.fragmentShader,
vertexShader: depthShader.vertexShader,
uniforms: depthUniforms,
skinning: true
} );
_depthMaterialMorphSkin = new THREE.ShaderMaterial( {
fragmentShader: depthShader.fragmentShader,
vertexShader: depthShader.vertexShader,
uniforms: depthUniforms,
morphTargets: true,
skinning: true
} );
_depthMaterial._shadowPass = true;
_depthMaterialMorph._shadowPass = true;
_depthMaterialSkin._shadowPass = true;
_depthMaterialMorphSkin._shadowPass = true;
};
this.render = function ( scene, camera ) {
if ( ! this.enabled ) return;
this.update( scene, camera );
};
this.update = function ( scene, camera ) {
var i, il, j, jl, n,
program, buffer, material,
webglObject, object, light,
renderList,
fog = null;
// set GL state for depth map
_gl.clearColor( 1, 1, 1, 1 );
_gl.disable( _gl.BLEND );
_renderer.state.setDepthTest( true );
// update scene
if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
// update camera matrices and frustum
camera.matrixWorldInverse.getInverse( camera.matrixWorld );
_projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
_frustum.setFromMatrix( _projScreenMatrix );
// render depth map
_renderer.setRenderTarget( this.renderTarget );
_renderer.clear();
// set object matrices & frustum culling
_renderList.length = 0;
projectObject(scene, scene, camera);
// render regular objects
var objectMaterial, useMorphing, useSkinning;
for ( j = 0, jl = _renderList.length; j < jl; j ++ ) {
webglObject = _renderList[ j ];
object = webglObject.object;
buffer = webglObject.buffer;
// todo: create proper depth material for particles
if ( object instanceof THREE.PointCloud && ! object.customDepthMaterial ) continue;
objectMaterial = getObjectMaterial( object );
if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
if ( object.customDepthMaterial ) {
material = object.customDepthMaterial;
} else if ( useSkinning ) {
material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
} else if ( useMorphing ) {
material = _depthMaterialMorph;
} else {
material = _depthMaterial;
}
if ( buffer instanceof THREE.BufferGeometry ) {
_renderer.renderBufferDirect( camera, _lights, fog, material, buffer, object );
} else {
_renderer.renderBuffer( camera, _lights, fog, material, buffer, object );
}
}
// set matrices and render immediate objects
for ( j = 0, jl = _webglObjectsImmediate.length; j < jl; j ++ ) {
webglObject = _webglObjectsImmediate[ j ];
object = webglObject.object;
if ( object.visible ) {
object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
_renderer.renderImmediateObject( camera, _lights, fog, _depthMaterial, object );
}
}
// restore GL state
var clearColor = _renderer.getClearColor(),
clearAlpha = _renderer.getClearAlpha();
_gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
_gl.enable( _gl.BLEND );
};
function projectObject(scene, object,camera) {
if ( object.visible ) {
var webglObjects = _webglObjects[object.id];
if (webglObjects && (object.frustumCulled === false || _frustum.intersectsObject( object ) === true) ) {
for (var i = 0, l = webglObjects.length; i < l; i ++) {
var webglObject = webglObjects[i];
object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
_renderList.push(webglObject);
}
}
for (var i = 0, l = object.children.length; i < l; i ++) {
projectObject(scene, object.children[i], camera);
}
}
}
// For the moment just ignore objects that have multiple materials with different animation methods
// Only the first material will be taken into account for deciding which depth material to use
function getObjectMaterial( object ) {
return object.material instanceof THREE.MeshFaceMaterial
? object.material.materials[ 0 ]
: object.material;
}
};
| mit |
Capt-Slow/wdio-mocha-framework | test/fixtures/tests.options.compilers.js | 264 | import path from 'path'
let { context, file, mocha, options } = module.parent.context
let { it } = context
context.it = function (name, callback) {
if (callback) {
return it(...arguments);
} else {
callback = name
name = path.basename(file, '.js')
}
}
| mit |
docusign/docusign-soap-sdk | Java/DocuSignSample/src/net/docusign/sample/GetStatusAndDocs.java | 8102 | /**
* @copyright Copyright (C) DocuSign, Inc. All rights reserved.
*
* This source code is intended only as a supplement to DocuSign SDK
* and/or on-line documentation.
*
* This sample is designed to demonstrate DocuSign features and is not intended
* for production use. Code and policy for a production application must be
* developed to meet the specific data and security requirements of the
* application.
*
* THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
* PARTICULAR PURPOSE.
*/
package net.docusign.sample;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import net.docusign.api_3_0.APIServiceSoap;
import net.docusign.api_3_0.ArrayOfString2;
import net.docusign.api_3_0.EnvelopePDF;
import net.docusign.api_3_0.EnvelopeStatusFilter;
import net.docusign.api_3_0.FilteredEnvelopeStatuses;
import net.docusign.api_3_0.RequestRecipientTokenAuthenticationAssertion;
import net.docusign.api_3_0.RequestRecipientTokenAuthenticationAssertionAuthenticationMethod;
import net.docusign.api_3_0.RequestRecipientTokenClientURLs;
/**
* Servlet implementation class GetStatusAndDocs
*/
public class GetStatusAndDocs extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GetStatusAndDocs() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getSession().setAttribute(Utils.SESSION_EMBEDTOKEN, "");
HttpSession session = request.getSession();
// Make sure we're logged in
if (session.getAttribute(Utils.SESSION_LOGGEDIN) == null ||
session.getAttribute(Utils.SESSION_LOGGEDIN).equals(false)) {
response.sendRedirect(Utils.CONTROLLER_LOGIN);
}
else {
// Do we have envelope IDs in this session?
if (session.getAttribute(Utils.SESSION_ENVELOPEIDS) != null) {
APIServiceSoap api = Utils.getAPI(request);
// Grab all the envelope IDs in this session
ArrayOfString2 envIDs = new ArrayOfString2();
envIDs.getEnvelopeId().addAll((List<String>) session.getAttribute(Utils.SESSION_ENVELOPEIDS));
// Create a filter so we only retrieve these envelope statuses
EnvelopeStatusFilter filter = new EnvelopeStatusFilter();
filter.setAccountId(session.getAttribute(Utils.SESSION_ACCOUNT_ID).toString());
filter.setEnvelopeIds(envIDs);
try {
// Call requestStatusesEx on these envelopes
FilteredEnvelopeStatuses statuses = api.requestStatusesEx(filter);
session.setAttribute(Utils.SESSION_STATUSES,
statuses.getEnvelopeStatuses().getEnvelopeStatus());
} catch (Exception e) {
}
}
response.sendRedirect(Utils.PAGE_GETSTATUS);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Get the parameter names
Enumeration paramNames = request.getParameterNames();
// Loop through the parameter names
while (paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
if (paramName.startsWith(Utils.NAME_STARTSIGNING)) {
// We want to start this user signing
startSigning(paramName, request);
response.sendRedirect(Utils.PAGE_GETSTATUS);
} else if (paramName.startsWith(Utils.NAME_DOWNLOAD)) {
// We want to download the specified envelope
downloadEnvelope(paramName, request, response);
}
}
}
protected void downloadEnvelope(String param, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String eid = param.split("\\+")[1];
// Request the PDF of the envelope
APIServiceSoap api = Utils.getAPI(request);
EnvelopePDF pdf = api.requestPDF(eid);
// Start download of the resulting PDF
byte[] documentBytes = pdf.getPDFBytes();
response.setHeader("Content-Disposition", "attachment;filename=Envelope.pdf");
response.setContentLength(documentBytes.length);
response.setContentType("application/pdf");
response.getOutputStream().write(documentBytes);
return;
}
protected void startSigning(String param, HttpServletRequest request) throws ServletException, IOException {
// Parse out envelope id, email, username, client user id
String[] params = param.split("\\&");
String eid = "", cid = "", uname = "", email = "";
for (int i = 0; i < params.length; i++) {
String[] pair = params[i].split("\\+");
if(pair[0].equals("SignDocEnvelope")) {
eid = pair[1];
} else if (pair[0].equals("Email")) {
email = pair[1];
} else if (pair[0].equals("UserName")) {
uname = pair[1];
} else if (pair[0].equals("CID")) {
cid = pair[1];
}
}
// Request the token
try {
getToken(request, eid, email, uname, cid);
} catch (DatatypeConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void getToken(HttpServletRequest request, String eid, String email, String username, String CID) throws DatatypeConfigurationException {
String token = null;
// Create the assertion
RequestRecipientTokenAuthenticationAssertion assertion = new RequestRecipientTokenAuthenticationAssertion();
assertion.setAssertionID(UUID.randomUUID().toString());
// wsdl2java translates this to XMLGregorianCalendar
GregorianCalendar gcal = new GregorianCalendar();
gcal.setTime(new Date());
assertion.setAuthenticationInstant(DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal));
assertion.setAuthenticationMethod(RequestRecipientTokenAuthenticationAssertionAuthenticationMethod.PASSWORD);
assertion.setSecurityDomain("DocuSign2010Q1Sample");
// Create the URLs that DocuSign will redirect the iframe to after different events
RequestRecipientTokenClientURLs urls = new RequestRecipientTokenClientURLs();
String urlbase = Utils.getCallbackURL(request, Utils.PAGE_POP);
urls.setOnAccessCodeFailed(urlbase + "?event=AccessCodeFailed&uname=" + username);
urls.setOnCancel(urlbase + "?event=Cancel&uname=" + username);
urls.setOnDecline(urlbase + "?event=Decline&uname=" + username);
urls.setOnException(urlbase + "?event=Exception&uname=" + username);
urls.setOnFaxPending(urlbase + "?event=FaxPending&uname=" + username);
urls.setOnIdCheckFailed(urlbase + "?event=IdCheckFailed&uname=" + username);
urls.setOnSessionTimeout(urlbase + "?event=SessionTimeout&uname=" + username);
urls.setOnTTLExpired(urlbase + "?event=TTLExpired&uname=" + username);
urls.setOnViewingComplete(urlbase + "?event=ViewingComplete&uname=" + username);
urls.setOnSigningComplete(urlbase + "?event=SigningComplete&uname=" + username);
// Get the API service and call RequestRecipientToken for this recipient
APIServiceSoap api = Utils.getAPI(request);
token = api.requestRecipientToken(eid,
CID,
username,
email,
assertion,
urls);
// Set the iframe to the token
request.getSession().setAttribute(Utils.SESSION_EMBEDTOKEN, token);
}
}
| mit |
ptaylor/ppool | lib/basic_process_controller.rb | 2168 | #
# MIT License
#
# Copyright (c) 2016 Paul Taylor
#
# 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.
#
module PPool
class BasicProcessController
def initialize
@time_started = Time.now.to_i
end
def running?
return true
end
def num_processes
return 1
end
def process_started(pid, num_processes)
puts "> process started #{pid}; num_processes #{num_processes}"
end
def run_process
info "#{Process.pid} running"
exit 0
end
def process_ended(pid, status)
puts "> process ended - pid #{pid}, status #{status}"
end
def progress(stats)
puts "> active #{stats[:active_processes]} started #{stats[:processes_started]} ended #{stats[:processes_ended]} errors #{stats[:errors]}"
end
def delay
return 0.1
end
def info(m)
puts "+ #{m}"
end
def time_running
secs = time_running_secs
hours = (secs / (60 * 60)) % 24
mins = (secs / 60) % 60
secs = secs % 60
return "%.2d:%.2d:%.2d" % [hours, mins,secs]
end
def time_running_secs
Time.now.to_i - @time_started
end
end
end
| mit |
KeldOelykke/FailFast | Java/Web/war/releases/1.3/api/starkcoder/failfast/fails/objects/floats/class-use/IObjectFloatNullFail.html | 11686 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_45) on Mon Aug 31 23:15:52 CEST 2015 -->
<title>Uses of Interface starkcoder.failfast.fails.objects.floats.IObjectFloatNullFail (FailFast v.1.3)</title>
<meta name="date" content="2015-08-31">
<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 Interface starkcoder.failfast.fails.objects.floats.IObjectFloatNullFail (FailFast v.1.3)";
}
//-->
</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="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">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-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?starkcoder/failfast/fails/objects/floats/class-use/IObjectFloatNullFail.html" target="_top">Frames</a></li>
<li><a href="IObjectFloatNullFail.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 Interface starkcoder.failfast.fails.objects.floats.IObjectFloatNullFail" class="title">Uses of Interface<br>starkcoder.failfast.fails.objects.floats.IObjectFloatNullFail</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="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">IObjectFloatNullFail</a></span><span class="tabEnd"> </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="#starkcoder.failfast.fails">starkcoder.failfast.fails</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#starkcoder.failfast.fails.objects">starkcoder.failfast.fails.objects</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#starkcoder.failfast.fails.objects.floats">starkcoder.failfast.fails.objects.floats</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="starkcoder.failfast.fails">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">IObjectFloatNullFail</a> in <a href="../../../../../../starkcoder/failfast/fails/package-summary.html">starkcoder.failfast.fails</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subinterfaces, and an explanation">
<caption><span>Subinterfaces of <a href="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">IObjectFloatNullFail</a> in <a href="../../../../../../starkcoder/failfast/fails/package-summary.html">starkcoder.failfast.fails</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Interface and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>interface </code></td>
<td class="colLast"><code><strong><a href="../../../../../../starkcoder/failfast/fails/IFailer.html" title="interface in starkcoder.failfast.fails">IFailer</a></strong></code>
<div class="block">Failer specification.</div>
</td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../starkcoder/failfast/fails/package-summary.html">starkcoder.failfast.fails</a> that implement <a href="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">IObjectFloatNullFail</a></span><span class="tabEnd"> </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 </code></td>
<td class="colLast"><code><strong><a href="../../../../../../starkcoder/failfast/fails/AFailer.html" title="class in starkcoder.failfast.fails">AFailer</a></strong></code>
<div class="block">Abstract implementation of <a href="../../../../../../starkcoder/failfast/fails/IFailer.html" title="interface in starkcoder.failfast.fails"><code>IFailer</code></a>.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../starkcoder/failfast/fails/Failer.html" title="class in starkcoder.failfast.fails">Failer</a></strong></code>
<div class="block">Default concrete implementation of <a href="../../../../../../starkcoder/failfast/fails/IFailer.html" title="interface in starkcoder.failfast.fails"><code>IFailer</code></a> using abstract implementation <a href="../../../../../../starkcoder/failfast/fails/AFailer.html" title="class in starkcoder.failfast.fails"><code>AFailer</code></a>.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="starkcoder.failfast.fails.objects">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">IObjectFloatNullFail</a> in <a href="../../../../../../starkcoder/failfast/fails/objects/package-summary.html">starkcoder.failfast.fails.objects</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subinterfaces, and an explanation">
<caption><span>Subinterfaces of <a href="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">IObjectFloatNullFail</a> in <a href="../../../../../../starkcoder/failfast/fails/objects/package-summary.html">starkcoder.failfast.fails.objects</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Interface and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>interface </code></td>
<td class="colLast"><code><strong><a href="../../../../../../starkcoder/failfast/fails/objects/IObjectFailer.html" title="interface in starkcoder.failfast.fails.objects">IObjectFailer</a></strong></code>
<div class="block">Specification grouping all object fail specifications.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="starkcoder.failfast.fails.objects.floats">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">IObjectFloatNullFail</a> in <a href="../../../../../../starkcoder/failfast/fails/objects/floats/package-summary.html">starkcoder.failfast.fails.objects.floats</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subinterfaces, and an explanation">
<caption><span>Subinterfaces of <a href="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">IObjectFloatNullFail</a> in <a href="../../../../../../starkcoder/failfast/fails/objects/floats/package-summary.html">starkcoder.failfast.fails.objects.floats</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Interface and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>interface </code></td>
<td class="colLast"><code><strong><a href="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatFailer.html" title="interface in starkcoder.failfast.fails.objects.floats">IObjectFloatFailer</a></strong></code>
<div class="block">Specification grouping all Float fail specifications.</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="../../../../../../starkcoder/failfast/fails/objects/floats/IObjectFloatNullFail.html" title="interface in starkcoder.failfast.fails.objects.floats">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-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?starkcoder/failfast/fails/objects/floats/class-use/IObjectFloatNullFail.html" target="_top">Frames</a></li>
<li><a href="IObjectFloatNullFail.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><i>The MIT License (MIT) - Copyright © 2014-2015 Keld Oelykke. All Rights Reserved.</i></small></p>
</body>
</html>
| mit |
apo-j/Projects_Working | EC/espace-client-dot-net/EspaceClient.FrontOffice.Data/Depots/DepotTypeRenduBloc.BackOffice.cs | 604 | using System.Linq;
using EspaceClient.FrontOffice.Business.Depots;
using EspaceClient.FrontOffice.Domaine;
namespace EspaceClient.FrontOffice.Data.Depots
{
public partial class DepotTypeRenduBloc : Depot<TypeRenduBloc>, IDepotTypeRenduBloc
{
public TypeRenduBloc GetByCode(string code, string codeTypeBloc)
{
var query = from trb in DbContext.TypeRenduBlocs
where trb.Code == code
where trb.TypeBloc.Code == codeTypeBloc
select trb;
return query.FirstOrDefault();
}
}
}
| mit |
xphh/lnet | README.md | 2864 | # lnet update 2015-03-28
Now multi-httpserver supported! See 'httpserver.lua'.
# lnet update 2015-03-25
Now cosocket supported!
What is cosocket? 'cosocket' is a socket API wapper for http handlers in lnet httpserver. It provides tcp/udp block operations but actually non-block in lnet httpserver thread. Yes, the name 'cosocket' means 'coroutine socket'. We yield out of the running corouine while doing some block operation (like connect and etc.), and resume back when the socket is ready.
To use cosocket, you have to require 'lnet.cosocket' explicitly in your lua code, and it returns an object:
local Socket = require "lnet.cosocket"
- tcp = Socket:tcp(ip, port) -- create a tcp socket object
- udp = Socket:udp(ip, port) -- create a udp socket object
- ret, err = Socket:connect(ip, port)
- sndlen, err = Socket:send(data, ip, port)
- rcvlen, data, ip, port = Socket:recv(condition)
- Socket.settimeout(sec)
To learn more, see 'lnet/cosocket.lua' and 'lnet/model_http/handler/test_socket.lua'.
# lnet update 2015-03-18
Now webpage supported!
1. static web pages: custom root directory, default pages, mime types, and etc.
2. dynamic web pages: Lua code embedded in html (very similar to PHP), see 'lnet/model_http/root/index.lua' for example.
So far, the Lua APIs for webpage and handler:
- echo (output messages into html, like php)
- http.peer.ip
- http.peer.port
- http.req.headline
- http.req.protocol
- http.req.method
- http.req.uri
- http.req.uri_path
- http.req.uri_args[key] = value
- http.req.headers[header] = info
- http.req.content
- http.resp.statusline
- http.resp.protocol
- http.resp.code
- http.resp.desc
- http.resp.headers[header] = info
- http.resp.content
- http:exit(code, err)
# lnet
This new toy is for those people who believe in that Lua can do everything, including httpserver.
The name 'lnet' is short for 'Lua Net', and what I have done here are as below:
1. Lua socket API (C extension library)
2. Lua IO poll API with multi-thread support (C extension library)
3. An event-model TCP server framework (Lua code)
4. An httpserver with restful HTTP services framework (Lua code)
You can use 'lnet' to do:
1. Normal socket develop
2. Custom TCP server develop
3. Server(backend) REST API develop
How to make, configure, and use 'lnet' httpserver:
1. Make sure you have already installed 'lua' or 'luajit'.
2. Make C library 'lnet/core.dll' (if Linux, run 'make').
3. Modify 'lnet/model_http/config/default.lua' as you like. How to configue? See annotations in config file, and to learn it yourself.
4. Modify 'httpserver.lua', set server parameters.
5. Run 'httpserver.lua'.
'lnet' is designed for good at restful HTTP services developping. As 'lnet' and its restful HTTP services framework is not perfect so far, it is still under construction, so you have to read source code for more infomations.
Thank you!
| mit |
libp2p/js-libp2p | src/circuit/listener.js | 2218 | 'use strict'
const { EventEmitter } = require('events')
const { Multiaddr } = require('multiaddr')
/**
* @typedef {import('libp2p-interfaces/src/transport/types').Listener} Listener
*/
/**
* @param {import('../')} libp2p
* @returns {Listener} a transport listener
*/
module.exports = (libp2p) => {
const listeningAddrs = new Map()
/**
* Add swarm handler and listen for incoming connections
*
* @param {Multiaddr} addr
* @returns {Promise<void>}
*/
async function listen (addr) {
const addrString = String(addr).split('/p2p-circuit').find(a => a !== '')
const relayConn = await libp2p.dial(new Multiaddr(addrString))
const relayedAddr = relayConn.remoteAddr.encapsulate('/p2p-circuit')
listeningAddrs.set(relayConn.remotePeer.toB58String(), relayedAddr)
listener.emit('listening')
}
/**
* Get fixed up multiaddrs
*
* NOTE: This method will grab the peers multiaddrs and expand them such that:
*
* a) If it's an existing /p2p-circuit address for a specific relay i.e.
* `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit` this method will expand the
* address to `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit/ipfs/QmPeer` where
* `QmPeer` is this peers id
* b) If it's not a /p2p-circuit address, it will encapsulate the address as a /p2p-circuit
* addr, such when dialing over a relay with this address, it will create the circuit using
* the encapsulated transport address. This is useful when for example, a peer should only
* be dialed over TCP rather than any other transport
*
* @returns {Multiaddr[]}
*/
function getAddrs () {
const addrs = []
for (const addr of listeningAddrs.values()) {
addrs.push(addr)
}
return addrs
}
/** @type Listener */
const listener = Object.assign(new EventEmitter(), {
close: () => Promise.resolve(),
listen,
getAddrs
})
// Remove listeningAddrs when a peer disconnects
libp2p.connectionManager.on('peer:disconnect', (connection) => {
const deleted = listeningAddrs.delete(connection.remotePeer.toB58String())
if (deleted) {
// Announce listen addresses change
listener.emit('close')
}
})
return listener
}
| mit |
jhkimnew/iistest | temp/BlobTransfer/src/TransferResult.cs | 324 | using System.Collections.Generic;
namespace BlobTransfer
{
public class TransferResult
{
public List<string> Succeeded { get; set; } = new List<string>();
public List<string> Skipped { get; set; } = new List<string>();
public List<string> Failed { get; set; } = new List<string>();
}
}
| mit |
immibajwa/project | app/card/card.html | 93 | <H1>CARDS LIST</h1>
<div ng-repeat="card in CardCtrl.cardlist" ng-bind="card.title"></div>
| mit |
fdeitelhoff/Twainsoft.FHDO.Compiler | src/Twainsoft.FHDO.Compiler.App/Properties/AssemblyInfo.cs | 1391 | using System.Reflection;
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("Twainsoft.FHDO.Compiler.App")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Twainsoft.FHDO.Compiler.App")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("c67323cd-9d0c-4fbd-9ff4-3c0cad27d20c")]
// 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")]
| mit |
lifeandscience/experimonth.lifeandscience.org | public/venera/js/main.js | 1521 | (function() {
$(function() {
$('.tooltip-examples a, .tooltip-paragraph-examples a').tooltip({
animation: false
});
$('.top-sign-in').on("click", function(e) {
$('.login-box').fadeIn("fast");
return false;
});
$('.login-box-close').on("click", function(e) {
$(this).closest(".login-box").fadeOut("fast");
return false;
});
prettyPrint();
$(".slider-browser-center").animate({
bottom: $(".slider-browser-center").data('position-bottom')
}, "fast", function() {
return $(".slider-browser-left").animate({
bottom: $(".slider-browser-left").data('position-bottom')
}, "fast", function() {
return $(".slider-browser-right").animate({
bottom: $(".slider-browser-right").data('position-bottom')
}, "fast");
});
});
$('.carousel').carousel({
interval: false
});
return $('a[data-toggle="testimonial"]').on("click", function(e) {
$(this).closest('.testimonials-users').find('a[data-toggle="testimonial"]').removeClass("active");
$(this).addClass("active");
$('.testimonials-speech').removeClass('active');
$('.testimonials-speech' + $(this).attr('href')).addClass('active');
return false;
});
});
$("body").on("touchstart.dropdown", ".dropdown-menu", function(e) {
return e.stopPropagation();
});
return $(document).on("click", ".dropdown-menu a", function() {
return document.location = $(this).attr("href");
});
}).call(this);
| mit |
jmettraux/rufus-sixjo | test/ft_8_head.rb | 482 |
#
# Testing rufus-sixjo
#
# jmettraux at gmail.org
#
# Fri Aug 8 15:14:45 JST 2008
#
require 'test/unit'
require 'testmixins'
#
# the "test" app
#
module HeadApp
extend Rufus::Sixjo
get '/toto' do
"toto"
end
end
class HeadTest < Test::Unit::TestCase
include SixjoTestMixin
def setup
@app = HeadApp.new_sixjo_rack_app(nil, :environment => 'test')
end
def test_0
assert_equal 200, head('/toto').status
assert_equal '', @response.body
end
end
| mit |
jemsz95/ehr | frontend/fonts/ubuntu-fontfacekit/stylesheet.css | 3382 | /* Generated by Font Squirrel (http://www.fontsquirrel.com) on April 1, 2011 08:28:28 AM America/New_York */
@font-face {
font-family: 'UbuntuRegular';
src: url('Ubuntu-Regular-webfont.eot');
src: url('Ubuntu-Regular-webfont.eot?iefix') format('eot'),
url('Ubuntu-Regular-webfont.woff') format('woff'),
url('Ubuntu-Regular-webfont.ttf') format('truetype'),
url('Ubuntu-Regular-webfont.svg#webfontHLBpjp3B') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'UbuntuItalic';
src: url('Ubuntu-Italic-webfont.eot');
src: url('Ubuntu-Italic-webfont.eot?iefix') format('eot'),
url('Ubuntu-Italic-webfont.woff') format('woff'),
url('Ubuntu-Italic-webfont.ttf') format('truetype'),
url('Ubuntu-Italic-webfont.svg#webfontthRLUYUD') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'UbuntuBold';
src: url('Ubuntu-Bold-webfont.eot');
src: url('Ubuntu-Bold-webfont.eot?iefix') format('eot'),
url('Ubuntu-Bold-webfont.woff') format('woff'),
url('Ubuntu-Bold-webfont.ttf') format('truetype'),
url('Ubuntu-Bold-webfont.svg#webfont1d3fIoP8') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'UbuntuBoldItalic';
src: url('Ubuntu-BoldItalic-webfont.eot');
src: url('Ubuntu-BoldItalic-webfont.eot?iefix') format('eot'),
url('Ubuntu-BoldItalic-webfont.woff') format('woff'),
url('Ubuntu-BoldItalic-webfont.ttf') format('truetype'),
url('Ubuntu-BoldItalic-webfont.svg#webfontir7CsQCC') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'UbuntuLight';
src: url('Ubuntu-Light-webfont.eot');
src: url('Ubuntu-Light-webfont.eot?iefix') format('eot'),
url('Ubuntu-Light-webfont.woff') format('woff'),
url('Ubuntu-Light-webfont.ttf') format('truetype'),
url('Ubuntu-Light-webfont.svg#webfontRPnMKj6g') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'UbuntuLightItalic';
src: url('Ubuntu-LightItalic-webfont.eot');
src: url('Ubuntu-LightItalic-webfont.eot?iefix') format('eot'),
url('Ubuntu-LightItalic-webfont.woff') format('woff'),
url('Ubuntu-LightItalic-webfont.ttf') format('truetype'),
url('Ubuntu-LightItalic-webfont.svg#webfontpehCzxnt') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'UbuntuMedium';
src: url('Ubuntu-Medium-webfont.eot');
src: url('Ubuntu-Medium-webfont.eot?iefix') format('eot'),
url('Ubuntu-Medium-webfont.woff') format('woff'),
url('Ubuntu-Medium-webfont.ttf') format('truetype'),
url('Ubuntu-Medium-webfont.svg#webfontcsgXxJIo') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'UbuntuMediumItalic';
src: url('Ubuntu-MediumItalic-webfont.eot');
src: url('Ubuntu-MediumItalic-webfont.eot?iefix') format('eot'),
url('Ubuntu-MediumItalic-webfont.woff') format('woff'),
url('Ubuntu-MediumItalic-webfont.ttf') format('truetype'),
url('Ubuntu-MediumItalic-webfont.svg#webfonteCMdxuKx') format('svg');
font-weight: normal;
font-style: normal;
}
| mit |
007slm/jquery-plugins | transform/index.html | 646 | <!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<!-- [Dependencies[ -->
<script src="transform.js"></script>
<!-- ]] -->
<style type="text/css">
body {
background: #00406c;
padding: 60px 10px 20px 20px;
}
div {
padding: 10px;
margin: 10px;
background: #fff;
float: left;
}
</style>
</head>
<body>
<div id="test1">
Click to transform (rotate)
</div>
<div id="test2">
Click for transition (opacity)
</div>
<div id="test3">
Click for transform-transtion
</div>
</body>
</html> | mit |
darjanbogdan/reporter | src/Reporter.WebAPI/Infrastructure/Owin/OwinContextExecutionScopeMiddleware.cs | 725 | using Owin;
using SimpleInjector;
using SimpleInjector.Extensions.ExecutionContextScoping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Reporter.WebAPI.Infrastructure.Owin
{
public static class OwinContextExecutionScopeMiddleware
{
public static void UseOwinContextExecutionScope(this IAppBuilder app, Container container)
{
// Create an OWIN middleware to create an execution context scope
app.Use(async (context, next) =>
{
using (var scope = container.BeginExecutionContextScope())
{
await next.Invoke();
}
});
}
}
} | mit |
ebothmann/heppyplot | README.md | 512 | # heppyplot
A package for plotting histogrammed data with special support for high energy physics applications.


## Installation
Currently we use a custom fork of the excellent [seaborn](http://stanford.edu/~mwaskom/software/seaborn/) package.
```
git clone https://github.com/ebothmann/heppyplot.git
cd heppyplot
git submodule update --init
cd seaborn
pip install -e .
cd ..
pip install -e .
```
| mit |
Samhane/taverna-player-portal | app/controllers/taverna_player/runs_controller.rb | 1563 | #------------------------------------------------------------------------------
# Copyright (c) 2013 The University of Manchester, UK.
#
# BSD Licenced. See LICENCE.rdoc for details.
#
# Taverna Player was developed in the BioVeL project, funded by the European
# Commission 7th Framework Programme (FP7), through grant agreement
# number 283359.
#
# Author: Robert Haines
#------------------------------------------------------------------------------
class TavernaPlayer::RunsController < ApplicationController
# Do not remove the next line.
include TavernaPlayer::Concerns::Controllers::RunsController
# Extend the RunsController here.
private
alias_method :old_find_run, :find_run
def update_params
params.require(:run).permit(:name, :policy_attributes => [:id, :public_permissions => []])
end
def run_params
params.require(:run).permit(
:create_time, :delayed_job, :embedded, :finish_time, :inputs_attributes,
:log, :name, :parent_id, :results, :run_id, :start_time,
:status_message_key, :user_id, :workflow_id,
:inputs_attributes => [:depth, :file, :metadata, :name, :value],
:policy_attributes => [:id, :public_permissions => []]
)
end
def find_runs
select = { :embedded => false }
select[:workflow_id] = params[:workflow_id] if params[:workflow_id]
@runs = TavernaPlayer::Run.where(select).order("created_at DESC").with_permissions(current_user, :view).page(params[:page])
end
def find_run
old_find_run
authorize(@run.can?(current_user, action_name))
end
end
| mit |
pablopdomingos/nfse | nfse-bh/src/test/java/com/pablodomingos/classes/rps/servicos/LoteRpsConsultaTest.java | 696 | package com.pablodomingos.classes.rps.servicos;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import com.pablodomingos.classes.FabricaDeObjetosFake;
public class LoteRpsConsultaTest {
@Test
public void xmlDeveSerGeradoCorretamente() throws IOException{
String xmlTest = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("loteRPSConsulta.xml"));
LoteRpsConsulta consultaLote = new LoteRpsConsulta("AP1057893n16X103sfhF4RPm", FabricaDeObjetosFake.getRpsPrestador());
String xml = consultaLote.converterParaXml();
Assert.assertEquals(xml, xmlTest);
}
}
| mit |
cheekujodhpur/ipho2015 | node_modules/mysql/test/integration/test-host-denied-error.js | 662 | var common = require('../common');
var connection = common.createConnection({port: common.fakeServerPort});
var assert = require('assert');
var server = common.createFakeServer();
var connectErr;
server.listen(common.fakeServerPort, function(err) {
if (err) throw err;
connection.connect(function(err) {
connectErr = err;
server.destroy();
});
});
server.on('connection', function(incomingConnection) {
var errno = 1130; // ER_HOST_NOT_PRIVILEGED
incomingConnection.deny('You suck.', errno);
});
process.on('exit', function() {
assert.equal(connectErr.code, 'ER_HOST_NOT_PRIVILEGED');
assert.equal(connectErr.fatal, true);
});
| mit |
wtfcoderz/chacal | initdb.sql | 1439 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- Export de la structure de la base pour chacal
CREATE DATABASE IF NOT EXISTS `chacal` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `chacal`;
-- Export de la structure de table chacal. items
CREATE TABLE IF NOT EXISTS `items` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`category` varchar(255) NOT NULL DEFAULT '""',
`desc` text NOT NULL DEFAULT '""',
`notation` time NOT NULL DEFAULT '00:00:00',
`positionlat` double DEFAULT NULL,
`postionlong` double DEFAULT NULL,
`date` datetime NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Export de la structure de table chacal. what
CREATE TABLE IF NOT EXISTS `what` (
`item_id` bigint(20) NOT NULL,
`what` varchar(255) NOT NULL,
`how` varchar(255) NOT NULL,
KEY `FK_what_items` (`item_id`),
CONSTRAINT `FK_what_items` FOREIGN KEY (`item_id`) REFERENCES `items` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
| mit |
cloukit/cloukit.github.io | src/app/components/component-info-header.component.ts | 6127 | /*!
* @license MIT
* Copyright (c) 2017 Bernhard Grünewaldt - codeclou.io
* https://github.com/cloukit/legal
*/
import { Component, Input } from '@angular/core';
import * as _ from 'lodash';
@Component({
selector: 'app-component-info-header',
template: `
<div class="info-header">
<div class="info-header-buttons">
<span
class="vendor-logo-link"
[ngStyle]="getButtonStyle(getStatusSwitchNameForComponentStatus(componentStatus))"
(mouseover)="hoverStatus(componentStatus)"
(mouseleave)="resetSwitchState()"
><img [src]="getComponentStatusUri()" class="vendor-logo"></span>
<a
href="https://www.npmjs.com/package/@cloukit/{{componentName}}"
target="_blank"
class="vendor-logo-link"
[ngStyle]="getButtonStyle('npm')"
(mouseover)="switchState.npm=true"
(mouseleave)="resetSwitchState()"
><img [src]="getVendorLogo('npm')" class="vendor-logo"></a>
<a
href="https://github.com/cloukit/{{componentName}}/tree/{{componentVersion}}"
target="_blank"
class="vendor-logo-link"
[ngStyle]="getButtonStyle('github')"
(mouseover)="switchState.github=true"
(mouseleave)="resetSwitchState()"
><img [src]="getVendorLogo('github')" class="vendor-logo"></a>
<a
href="https://unpkg.com/@cloukit/{{componentName}}@{{componentVersion}}/"
target="_blank"
class="vendor-logo-link"
[ngStyle]="getButtonStyle('unpkg')"
(mouseover)="switchState.unpkg=true"
(mouseleave)="resetSwitchState()"
><img [src]="getVendorLogo('unpkg')" class="vendor-logo"></a>
<a
href="https://cloukit.github.io/{{componentName}}/{{componentVersion}}/documentation/"
target="_blank"
class="vendor-logo-link"
[ngStyle]="getButtonStyle('compodoc')"
(mouseover)="switchState.compodoc=true"
(mouseleave)="resetSwitchState()"
><img [src]="getVendorLogo('compodoc')" class="vendor-logo"></a>
</div>
<div class="info-header-bar" [ngStyle]="getInfoHeaderStyle()">
<div class="info-header-bar-content">
<div *ngIf="isSwitchStateOn()">
{{switchState.statusExperimental ? 'API might change unexpectedly. Use at own risk. It is alive!' : ''}}
{{switchState.statusStable ? 'API should be stable.' : ''}}
{{switchState.npm ? 'Show package page on npmjs.com' : ''}}
{{switchState.github ? 'Show example project on github.com' : ''}}
{{switchState.unpkg ? 'Show dist contents on unpkg.com' : ''}}
{{switchState.compodoc ? 'Show detailed Component Documentation' : ''}}
</div>
</div>
</div>
</div>`,
styles: [
'.vendor-logo { width:120px; }',
'.info-header-bar { height:40px; width:100%; }',
'.info-header-bar-content { width:100%; padding: 10px; text-align:center; }',
'.info-header-buttons { display: flex; justify-content: space-between; }',
'.vendor-logo-link { display:flex; width: 120px; min-width:120px; max-width: 120px; padding:0; height:65px; }',
],
})
export class ComponentInfoHeaderComponent {
@Input()
componentName: string;
@Input()
componentVersion: string;
@Input()
componentStatus: string;
private initialSwitchState = {
npm: false,
unpkg: false,
github: false,
compodoc: false,
statusStable: false,
statusExperimental: false,
};
private colors = {
npm: {
bg: '#cb3837',
fg: '#fff',
},
unpkg: {
bg: '#000',
fg: '#fff',
},
github: {
bg: '#0366d6',
fg: '#fff',
},
compodoc: {
bg: '#2582d5',
fg: '#fff',
},
statusStable: {
bg: '#4ad57d',
fg: '#fff',
},
statusExperimental: {
bg: '#d55900',
fg: '#fff',
},
};
switchState = Object.assign({}, this.initialSwitchState);
getSwitchState(name: string) {
return this.switchState[name] ? 'on' : 'off';
}
isSwitchStateOn() {
for (let pair of _.toPairs(this.switchState)) {
if (pair[1]) {
return true;
}
}
return false;
}
getOnSwitchName() {
for (let pair of _.toPairs(this.switchState)) {
if (pair[1]) {
return pair[0];
}
}
return null;
}
getVendorLogo(name: string) {
return `/assets/images/vendor-logos/${name}-${this.getSwitchState(name)}.svg`;
}
resetSwitchState() {
this.switchState = Object.assign({}, this.initialSwitchState);
}
getButtonStyle(name: string) {
return this.switchState[name] ? {
border: `3px solid ${this.colors[name]['bg']}`,
transition: 'border-color 200ms linear'
} : {
border: `3px solid transparent`,
transition: 'border-color 200ms linear'
};
}
getInfoHeaderStyle() {
return this.isSwitchStateOn() ? {
backgroundColor: this.colors[this.getOnSwitchName()]['bg'],
color: this.colors[this.getOnSwitchName()]['fg'],
transition: 'background-color 200ms linear'
} : {
backgroundColor: 'transparent',
transition: 'background-color 200ms linear'
};
}
//
// STATUS
//
getStatusSwitchNameForComponentStatus(status: string) {
if (status === 'STABLE') {
return 'statusStable';
}
if (status === 'EXPERIMENTAL') {
return 'statusExperimental';
}
return null;
}
hoverStatus(status: string) {
if (status === 'STABLE') {
this.switchState.statusStable = true;
}
if (status === 'EXPERIMENTAL') {
this.switchState.statusExperimental = true;
}
}
getComponentStatusUri() {
if (this.componentStatus === 'STABLE') {
if (this.switchState.statusStable) {
return '/assets/images/status-icons/status-stable-on.svg';
}
return '/assets/images/status-icons/status-stable-off.svg';
}
if (this.componentStatus === 'EXPERIMENTAL') {
if (this.switchState.statusExperimental) {
return '/assets/images/status-icons/status-experimental-on.svg';
}
return '/assets/images/status-icons/status-experimental-off.svg';
}
}
}
| mit |
coq-bench/coq-bench.github.io | clean/Linux-x86_64-4.08.1-2.0.5/released/8.7.1+1/elpi/1.12.1.html | 7654 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>elpi: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.7.1+1 / elpi - 1.12.1</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
elpi
<small>
1.12.1
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-02-11 17:12:35 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-11 17:12:35 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.7.1+1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.08.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.08.1 Official release 4.08.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Enrico Tassi <[email protected]>"
authors: [ "Enrico Tassi" ]
license: "LGPL-2.1-or-later"
homepage: "https://github.com/LPCIC/coq-elpi"
bug-reports: "https://github.com/LPCIC/coq-elpi/issues"
dev-repo: "git+https://github.com/LPCIC/coq-elpi"
build: [ [ make "build" "COQBIN=%{bin}%/" "ELPIDIR=%{prefix}%/lib/elpi" "OCAMLWARN=" ]
[ make "test" "COQBIN=%{bin}%/" "ELPIDIR=%{prefix}%/lib/elpi" ] {with-test}
]
install: [ make "install" "COQBIN=%{bin}%/" "ELPIDIR=%{prefix}%/lib/elpi" ]
depends: [
"stdlib-shims"
"ocaml" {>= "4.07"}
"elpi" {>= "1.13.6" & < "1.14.0~"}
"coq" {>= "8.15" & < "8.16~" }
]
tags: [ "logpath:elpi" ]
synopsis: "Elpi extension language for Coq"
description: """
Coq-elpi provides a Coq plugin that embeds ELPI.
It also provides a way to embed Coq's terms into λProlog using
the Higher-Order Abstract Syntax approach
and a way to read terms back. In addition to that it exports to ELPI a
set of Coq's primitives, e.g. printing a message, accessing the
environment of theorems and data types, defining a new constant and so on.
For convenience it also provides a quotation and anti-quotation for Coq's
syntax in λProlog. E.g. `{{nat}}` is expanded to the type name of natural
numbers, or `{{A -> B}}` to the representation of a product by unfolding
the `->` notation. Finally it provides a way to define new vernacular commands
and
new tactics."""
url {
src: "https://github.com/LPCIC/coq-elpi/archive/v1.12.1.tar.gz"
checksum: "sha256=32eac6be5172eb945df6e80b1b6e0b784cbf1d7dca15ee780bb60716a0bb9ce5"
}
</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-elpi.1.12.1 coq.8.7.1+1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1+1).
The following dependencies couldn't be met:
- coq-elpi -> coq >= 8.15
Your request can'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-elpi.1.12.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| mit |
conwid/IL-boss | DynamicSerializer.Test/TestClasses.cs | 2153 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
namespace DynamicSerializer.Test
{
public class IX
{
public int IP { get; set; }
}
[Serializable]
public class A
{
public A()
{
}
public A(string _name, C _c)
{
name = _name;
cref = _c;
}
public string name { get; set; }
public C cref { get; set; }
public override bool Equals(object obj)
{
return ((obj is A) && ((A) obj).name == this.name);
}
public override int GetHashCode()
{
return 1;
}
public static bool operator ==(A a, A b)
{
return a.Equals(b);
}
public static bool operator !=(A a, A b)
{
return !(a == b);
}
}
public class B : A
{
public B()
{
}
public int number { get { return Number; } set { Number = value; } }
[NonSerialized]
private int Number;
public B(string name, int num, C c)
: base(name, c)
{
number = num;
}
}
[Serializable]
public class C
{
public C()
{
}
public int adat { get; set; }
public C(int _b)
{
adat = _b;
}
}
public class CircularA
{
public List<CircularB> BArray { get; set; }
public List<CircularB> CArray { get; set; }
public CircularB BField { get; set; }
}
public class CircularB
{
public CircularA A { get; set; }
public int Id { get; set; }
public CircularB(int id)
{
Id = id;
}
}
public class NoCtor
{
public int i;
//public string s { get; set; }
public string s;
public NoCtor(int i, string s)
{
this.i = i;
this.s = s;
}
}
public class Basic
{
public int num;
}
}
| mit |
crockeo/hc | src/hcexception.hpp | 707 | #ifndef _HC_EXCEPTION_HPP_
#define _HC_EXCEPTION_HPP_
//////////////
// Includes //
#include <exception>
#include <string>
//////////
// Code //
// To distinguish between different HCExceptions.
enum HCType {
// When the game cannot open the SDL window.
HC_WINDOW_EXCEPTION,
// When the game cannot load an asset, or it has been destroyed.
HC_ASSET_EXCEPTION
};
// A custom exception for this project.
class HCException : public std::exception {
private:
std::string msg;
HCType type;
public:
// Creating an HCException with a message and a type.
HCException(std::string, HCType);
// The message of this HCException.
const char* what() throw();
};
#endif
| mit |
houcine88/Cabinet | app/cache/prod/doctrine/orm/Proxies/__CG__CabinetPatientBundleEntityPatient.php | 4377 | <?php
namespace Proxies\__CG__\Cabinet\PatientBundle\Entity;
/**
* THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE.
*/
class Patient extends \Cabinet\PatientBundle\Entity\Patient implements \Doctrine\ORM\Proxy\Proxy
{
private $_entityPersister;
private $_identifier;
public $__isInitialized__ = false;
public function __construct($entityPersister, $identifier)
{
$this->_entityPersister = $entityPersister;
$this->_identifier = $identifier;
}
/** @private */
public function __load()
{
if (!$this->__isInitialized__ && $this->_entityPersister) {
$this->__isInitialized__ = true;
if (method_exists($this, "__wakeup")) {
// call this after __isInitialized__to avoid infinite recursion
// but before loading to emulate what ClassMetadata::newInstance()
// provides.
$this->__wakeup();
}
if ($this->_entityPersister->load($this->_identifier, $this) === null) {
throw new \Doctrine\ORM\EntityNotFoundException();
}
unset($this->_entityPersister, $this->_identifier);
}
}
/** @private */
public function __isInitialized()
{
return $this->__isInitialized__;
}
public function getId()
{
if ($this->__isInitialized__ === false) {
return (int) $this->_identifier["id"];
}
$this->__load();
return parent::getId();
}
public function setNom($nom)
{
$this->__load();
return parent::setNom($nom);
}
public function getNom()
{
$this->__load();
return parent::getNom();
}
public function setPrenom($prenom)
{
$this->__load();
return parent::setPrenom($prenom);
}
public function getPrenom()
{
$this->__load();
return parent::getPrenom();
}
public function setDateNaissance($dateNaissance)
{
$this->__load();
return parent::setDateNaissance($dateNaissance);
}
public function getDateNaissance()
{
$this->__load();
return parent::getDateNaissance();
}
public function setAdresse($adresse)
{
$this->__load();
return parent::setAdresse($adresse);
}
public function getAdresse()
{
$this->__load();
return parent::getAdresse();
}
public function setTel($tel)
{
$this->__load();
return parent::setTel($tel);
}
public function getTel()
{
$this->__load();
return parent::getTel();
}
public function setCin($cin)
{
$this->__load();
return parent::setCin($cin);
}
public function getCin()
{
$this->__load();
return parent::getCin();
}
public function setMedecin(\Cabinet\UserBundle\Entity\Medecin $medecin = NULL)
{
$this->__load();
return parent::setMedecin($medecin);
}
public function getMedecin()
{
$this->__load();
return parent::getMedecin();
}
public function setFiche(\Cabinet\PatientBundle\Entity\Fiche $fiche = NULL)
{
$this->__load();
return parent::setFiche($fiche);
}
public function getFiche()
{
$this->__load();
return parent::getFiche();
}
public function __toString()
{
$this->__load();
return parent::__toString();
}
public function __sleep()
{
return array('__isInitialized__', 'id', 'nom', 'prenom', 'dateNaissance', 'adresse', 'tel', 'cin', 'medecin', 'fiche');
}
public function __clone()
{
if (!$this->__isInitialized__ && $this->_entityPersister) {
$this->__isInitialized__ = true;
$class = $this->_entityPersister->getClassMetadata();
$original = $this->_entityPersister->load($this->_identifier);
if ($original === null) {
throw new \Doctrine\ORM\EntityNotFoundException();
}
foreach ($class->reflFields as $field => $reflProperty) {
$reflProperty->setValue($this, $reflProperty->getValue($original));
}
unset($this->_entityPersister, $this->_identifier);
}
}
} | mit |
regb/scala-game-library | core/src/main/scala/sgl/scene/ui/Widget.scala | 481 | //package sgl.scene
//package ui
//
///** SceneElement that is part of a layout
// *
// * This is the root class providing logic for
// * how to render widgets in a hierarchical user
// * interface.
// */
//abstract class Widget(_x: Float, _y: Float) extends SceneElement(_x, _y) {
//
// def minWidth: Float
// def minHeight: Float
//
// def preferredWidth: Float
// def preferredHeight: Float
//
// def maxWidth: Option[Float]
// def maxHeight: Option[Float]
//
//
//}
| mit |
akshayvenugopal/angular2-Node.JS-CRUD | Angular JS/newApp/src/app/components/topbar/topbar.component.css | 492 | ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
box-shadow: 0 6px 25px 0 rgba(0,0,0,.25);
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
cursor:pointer;
}
li a:hover:not(.active) {
background-color: #464C5C;
}
.active {
background-color: #8C98B8;
}
.img-right{
float: right;
padding-left: 1000px;
}
| mit |
luoshi0429/vue2-yanxuan | src/store/getters.js | 424 | export default {
// 购物车的商品数量
cartCommodityCount: state => {
const totalCount = state.cartList.reduce((total, commodity) => {
return total + Number(commodity.count)
}, 0)
return totalCount
},
removeCommodityCount: state => {
const totalCount = state.removeCartList.reduce((total, commodity) => {
return total + Number(commodity.count)
}, 0)
return totalCount
}
}
| mit |
radislavsplichal/phoneticsphonology | templates/exercises/odd-one-out/exerciseDetailodd-one-out.html | 683 | <template name="odd-one-out">
<!-- Template for odd-one-out exercise -->
<section class="mainSection">
<form>
<input name=exercisesID type="hidden" value={{_id}}>
<input name=type type="hidden" value={{type}}>
{{#each options}}
<div class="checkbox">
<label>
<input name="option" type="radio" value={{this}}>
{{this}}
</label>
</div>
{{/each}}
<br>
<button type="submit" class="btn btn-default btn-primary js-verify">Submit your Answer</button>
</form>
</section>
</template>
| mit |
nioteam/jingdong_fu | lib/rest.rb | 2853 | require "uri"
require "net/http"
module JingdongFu
module Rest
class << self
def get(url, hashed_vars)
res = request(url, 'GET', hashed_vars)
process_result(res, url)
end
def post(url, hashed_vars)
res = request(url, 'POST', hashed_vars)
process_result(res, url)
end
def put(url, hashed_vars)
res = request(url, 'PUT', hashed_vars)
process_result(res, url)
end
def delete(url, hashed_vars)
res = request(url, 'DELETE', hashed_vars)
process_result(res, url)
end
protected
def request(url, method=nil, params = {})
if !url || url.length < 1
raise ArgumentError, 'Invalid url parameter'
end
if method && !['GET', 'POST', 'DELETE', 'PUT'].include?(method)
raise NotImplementedError, 'HTTP %s not implemented' % method
end
if method && method == 'GET'
url = build_get_uri(url, params)
end
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
if method && method == 'GET'
req = Net::HTTP::Get.new(uri.request_uri)
elsif method && method == 'DELETE'
req = Net::HTTP::Delete.new(uri.request_uri)
elsif method && method == 'PUT'
req = Net::HTTP::Put.new(uri.request_uri)
req.set_form_data(params)
else
req = Net::HTTP::Post.new(uri.request_uri)
req.set_form_data(params)
end
http.request(req)
end
def build_get_uri(uri, params)
if params && params.length > 0
uri += '?' unless uri.include?('?')
uri += urlencode(params)
end
URI.escape(uri)
end
def urlencode(params)
params.to_a.collect! { |k, v| "#{k.to_s}=#{v.to_s}" }.join("&")
end
def process_result(res, raw_url)
if res.code =~ /\A2\d{2}\z/
res.body
elsif %w(301 302 303).include? res.code
url = res.header['Location']
if url !~ /^http/
uri = URI.parse(raw_url)
uri.path = "/#{url}".squeeze('/')
url = uri.to_s
end
raise RuntimeError, "Redirect #{url}"
elsif res.code == "304"
raise RuntimeError, "NotModified #{res}"
elsif res.code == "401"
raise RuntimeError, "Unauthorized #{res}"
elsif res.code == "404"
raise RuntimeError, "Resource not found #{res}"
else
raise RuntimeError, "Maybe request timed out #{res}. HTTP status code #{res.code}"
end
end
end
end
end
| mit |
howardplus/lirest | source/extract.go | 3669 | package source
import (
log "github.com/Sirupsen/logrus"
"github.com/howardplus/lirest/describe"
"github.com/howardplus/lirest/util"
"os"
"strconv"
"strings"
"time"
)
// Extractor returns a generic data based
// on the converter.
// An object that implements the Extractor interface needs
// to know where to get the data, which then feeds to the
// converter.
type Extractor interface {
Extract() (*ExtractOutput, error)
}
// ExtractOutput is the output of the extracted data
// with json tags
type ExtractOutput struct {
Name string `json:"name"`
Time time.Time `json:"time"`
Data interface{} `json:"data"`
}
// NewExtractor create a new extractor based on the description
func NewExtractor(s describe.DescriptionSource, rd describe.DescriptionReadFormat, c Converter, vars map[string]string) (Extractor, error) {
var extractor Extractor
refresh := time.Duration(0)
switch s.Refresh {
case "never":
// never say never, 10 day is long enough
refresh = 240 * time.Hour
default:
// something s/m/h
v, err := strconv.Atoi(s.Refresh[:len(s.Refresh)-1])
if err == nil {
if strings.HasSuffix(s.Refresh, "s") {
refresh = time.Duration(v) * time.Second
} else if strings.HasSuffix(s.Refresh, "m") {
refresh = time.Duration(v) * time.Minute
} else if strings.HasSuffix(s.Refresh, "h") {
refresh = time.Duration(v) * time.Hour
}
}
case "":
// Did not specify, which implies always refresh
}
switch s.Type {
case "procfs", "sysfs", "sysctl":
extractor = NewGenericExtractor(rd.Path, refresh, c, vars)
case "command":
extractor = NewCommandExtractor(rd.Command, c, vars)
}
// found an extractor, use it
if extractor != nil {
return extractor, nil
}
// return error on default
return nil, util.NewError("Internal error: unknown input type")
}
// GenericExtractor extract data from reading from a file
// use this until it's not enough
type GenericExtractor struct {
path string
conv Converter
refresh time.Duration
vars map[string]string
}
// NewGenericExtractor creates a GenericExtractor
func NewGenericExtractor(path string, refresh time.Duration, conv Converter, vars map[string]string) *GenericExtractor {
return &GenericExtractor{path: path, refresh: refresh, conv: conv, vars: vars}
}
func (e *GenericExtractor) Extract() (*ExtractOutput, error) {
log.WithFields(log.Fields{
"path": e.path,
"vars": e.vars,
}).Debug("Extract from file system")
// create path from variables
path, err := util.FillVars(e.path, e.vars)
if err != nil {
return nil, util.NewError("Failed to generate path")
}
// ask data from cache
var hash string
if e.refresh != time.Duration(0) {
hash = CacheHash("command" + path)
if data, time, err := Cache(hash); err == nil {
log.WithFields(log.Fields{
"hash": hash,
"path": e.path,
}).Debug("Serve from cache")
return &ExtractOutput{
Name: e.conv.Name(),
Time: time,
Data: data,
}, nil
}
}
// open file from path
f, err := os.Open(path)
if err != nil {
return nil, util.NewError("Failed to open system path")
}
defer f.Close()
// TODO: verify the rw format on this path
// give it to the converter
data, err := e.conv.ConvertStream(f)
if err != nil {
return nil, err
}
// send to cache
if e.refresh != time.Duration(0) {
if err := SendCache(hash, data, e.refresh); err != nil {
// cache error, non-fatal
log.WithFields(log.Fields{
"path": e.path,
}).Debug("Failed to send cache")
}
}
log.WithFields(log.Fields{
"path": e.path,
}).Debug("Convert successful")
return &ExtractOutput{
Name: e.conv.Name(),
Time: time.Now(),
Data: data,
}, nil
}
| mit |
ostat/Console | Cognifide.PowerShell/Commandlets/Presentation/GetRenderingCommand.cs | 716 | using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Cognifide.PowerShell.Core.Extensions;
using Sitecore.Data.Items;
using Sitecore.Layouts;
namespace Cognifide.PowerShell.Commandlets.Presentation
{
[Cmdlet(VerbsCommon.Get, "Rendering")]
[OutputType(typeof (RenderingDefinition))]
public class GetRenderingCommand : BaseRenderingCommand
{
protected override void ProcessRenderings(Item item, LayoutDefinition layout, DeviceDefinition device,
IEnumerable<RenderingDefinition> renderings)
{
renderings.ToList().ForEach(r => WriteObject(ItemShellExtensions.WrapInItemOwner(SessionState, item, r)));
}
}
} | mit |
Crim/pardot-java-client | src/main/java/com/darksci/pardot/api/parser/user/UserAbilitiesParser.java | 1801 | /**
* Copyright 2017, 2018, 2019, 2020 Stephen Powis https://github.com/Crim/pardot-java-client
*
* 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 com.darksci.pardot.api.parser.user;
import com.darksci.pardot.api.parser.JacksonFactory;
import com.darksci.pardot.api.parser.ResponseParser;
import com.darksci.pardot.api.response.user.UserAbilitiesResponse;
import java.io.IOException;
/**
* Handles parsing UserAbilities API responses into POJOs.
*/
public class UserAbilitiesParser implements ResponseParser<UserAbilitiesResponse.Result> {
@Override
public UserAbilitiesResponse.Result parseResponse(final String responseStr) throws IOException {
return JacksonFactory.newInstance().readValue(responseStr, UserAbilitiesResponse.class).getResult();
}
}
| mit |
jersobh/edge-framework | src/controller/main.php | 300 | <?php
namespace App\Controller;
use Core\http;
use Core\view;
use Core\db;
class main
{
protected $http;
protected $view;
protected $db;
public function __construct()
{
$this->http = new http();
$this->view = new view();
$this->db = new db();
}
} | mit |
academiae/RestfulExpressiveSkeleton | module/Employee/test/ModuleConfigTest.php | 1417 | <?php
/**
* The MIT License
*
* Copyright (c) 2016, Coding Matters, Inc. (Gab Amba <[email protected]>)
*
* 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.
*/
namespace CodingMatters\EmployeeTest;
use PHPUnit\Framework\TestCase;
class ModuleConfigTest extends TestCase
{
public function testConfigProvider()
{
$this->markTestIncomplete("Not yet implemented");
}
}
| mit |
ipconfiger/NSObject-Serialize | Example/Pods/Target Support Files/Pods-NSObject-Serialize_Tests-NSObject-Serialize/Pods-NSObject-Serialize_Tests-NSObject-Serialize-umbrella.h | 158 | #import <UIKit/UIKit.h>
FOUNDATION_EXPORT double NSObject_SerializeVersionNumber;
FOUNDATION_EXPORT const unsigned char NSObject_SerializeVersionString[];
| mit |
zidad/Umbraco-CMS | src/Umbraco.Web.UI.Client/src/views/propertyeditors/imagecropper/imagecropper.controller.js | 4659 | //this controller simply tells the dialogs service to open a mediaPicker window
//with a specified callback, this callback will receive an object with a selection on it
angular.module('umbraco')
.controller("Umbraco.PropertyEditors.ImageCropperController",
function ($rootScope, $routeParams, $scope, $log, mediaHelper, cropperHelper, $timeout, editorState, umbRequestHelper, fileManager) {
var config = angular.copy($scope.model.config);
//move previously saved value to the editor
if ($scope.model.value) {
//backwards compat with the old file upload (incase some-one swaps them..)
if (angular.isString($scope.model.value)) {
config.src = $scope.model.value;
$scope.model.value = config;
} else if ($scope.model.value.crops) {
//sync any config changes with the editor and drop outdated crops
_.each($scope.model.value.crops, function (saved) {
var configured = _.find(config.crops, function (item) { return item.alias === saved.alias });
if (configured && configured.height === saved.height && configured.width === saved.width) {
configured.coordinates = saved.coordinates;
}
});
$scope.model.value.crops = config.crops;
//restore focalpoint if missing
if (!$scope.model.value.focalPoint) {
$scope.model.value.focalPoint = { left: 0.5, top: 0.5 };
}
}
$scope.imageSrc = $scope.model.value.src;
}
//crop a specific crop
$scope.crop = function (crop) {
$scope.currentCrop = crop;
$scope.currentPoint = undefined;
};
//done cropping
$scope.done = function () {
$scope.currentCrop = undefined;
$scope.currentPoint = undefined;
};
//crop a specific crop
$scope.clear = function (crop) {
//clear current uploaded files
fileManager.setFiles($scope.model.alias, []);
//clear the ui
$scope.imageSrc = undefined;
if ($scope.model.value) {
delete $scope.model.value;
}
};
//show previews
$scope.togglePreviews = function () {
if ($scope.showPreviews) {
$scope.showPreviews = false;
$scope.tempShowPreviews = false;
} else {
$scope.showPreviews = true;
}
};
//on image selected, update the cropper
$scope.$on("filesSelected", function (ev, args) {
$scope.model.value = config;
if (args.files && args.files[0]) {
fileManager.setFiles($scope.model.alias, args.files);
var reader = new FileReader();
reader.onload = function (e) {
$scope.$apply(function () {
$scope.imageSrc = e.target.result;
});
};
reader.readAsDataURL(args.files[0]);
}
});
})
.run(function (mediaHelper, umbRequestHelper) {
if (mediaHelper && mediaHelper.registerFileResolver) {
mediaHelper.registerFileResolver("Umbraco.ImageCropper", function (property, entity, thumbnail) {
if (property.value.src) {
if (thumbnail === true) {
return property.value.src + "?width=600&mode=max";
}
else {
return property.value.src;
}
//this is a fallback in case the cropper has been asssigned a upload field
}
else if (angular.isString(property.value)) {
if (thumbnail) {
if (mediaHelper.detectIfImageByExtension(property.value)) {
var thumbnailUrl = umbRequestHelper.getApiUrl(
"imagesApiBaseUrl",
"GetBigThumbnail",
[{ originalImagePath: property.value }]);
return thumbnailUrl;
}
else {
return null;
}
}
else {
return property.value;
}
}
return null;
});
}
}); | mit |
lucumt/ghblog | content/post/java-concurrency/concurrency-models.md | 18775 | +++
author = "飞狐"
categories = ["Java编程","翻译"]
tags = ["Java","Java Concurrency"]
date = "2017-08-05T00:10:11+08:00"
description = "Blog of Rosen Lu"
keywords = ["java concurrency"]
title = "4. [译]并发的模型"
+++
本文翻译自**[Java Concurrency / Concurrency Models](http://tutorials.jenkov.com/java-concurrency/concurrency-models.html)**
并发系统可以使用不同的并发模型来实现,并发模型是指线程在系统中如何写作来完成给定的任务。不同的并发模型以不同的方式拆分任务,线程间以不同的方式协作和通信,本文将深入研究在撰写本文时最流行并发模型(2015年)。
<!--more-->
## 并发模型和分布式系统相似之处
本文中描述的并发模型与分布式系统中使用的架构类似,在一个并发系统中,不同的线程之间互相通信,在一个分布式系统中,不同的进程间彼此通信(这些进程可能在不同的电脑上)。线程和进程在本质上时非常相似的,这就是为什么不同的并发模型与不同的分布式系统架构通常看起来相似。
虽然分布式系统还有额外的挑战,如网络故障、远程计算机或进程关闭等,但一个运行在大型服务器上的并发系统也可能会遇到类似的问题,如CPU故障、网卡故障、硬盘故障等,虽然其发生的概率较低,但理论上仍然可以发生。
由于并发模型和分布式系统架构类似,它们通常可以相互借鉴,比如在线程中分配工作的模型通常与分布式系统中的负载均衡类似,它们的错误处理手段也类似,例如日志(logging)、故障切换(fail-over)和等幂性任务(idempotency of jobs)等。
## 并行工作者模型(Parallel Workers model)
并行工作者模型是本文要说明的第一个并发模型,该模型会将系统中到来的任务分配给不同的工作者,如下图所示:

并发模型中有一个“委托者”将到来的任务分配给不同的工作者,每个工作者完成整个任务,每个工作者在不同的线程中(也有可能在不同的CPU)并行工作。
如果一个汽车厂采用了并行工作者模型,那么每辆汽车将由一个工人根据说明书从头到尾来制造。
并行工作者模型是Java应用程序中使用最广泛的并发模型(尽管这种情形正在发生变化),**[java.util.concurrent ](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-summary.html)** 中的许多包都被设计用于此模型,你也可以在Java企业级服务器的设计中找到此模型的应用踪迹。
## 并行工作者模型的优点
并行工作者模型的优点是理解容易,当要增加应用程序的并行能力时我们只需添加更多的工作者即可。
例如,假设你想实现一个网络爬虫,你可以使用不同数量的工作者线程来爬取制定数量的页面,根据结果来决定使用多少个工作者线程具有最短的抓取时间(同时意味着最优性能)。由于网络爬虫是IO密集型工作,在等待下载数据时会浪费大量时间,若每个CPU只运行一个线程时效率不高,所以最终的结果可能会是在电脑中一个CPU/内核运行多个线程。
## 并行工作者模型的缺点
并行工作者模式在其简单外表之下还有若干缺点,我将在以下部分说明其中最为明显的几个。
### 状态共享将使复杂性增加
实际上并行工作者模型比上面说明的还要复杂一些,并行工作者通常需要访问一些共享数据,它们可能存储在内存中也可能存在数据库中,下面的图标展示了这种情形是如何是的并行工作者模型变得复杂的。

其中的一些共享状态可能在类似于任务队列的通信过程中,但是另外一些共享状态可能是商业数据、缓存数据、数据库的连接池等。一旦共享状态引入到了并行工作者模型,问题就开始变得复杂。线程需要一种方式来访问共享数据以确保一个线程对共享数据的更改对其它线程是可见的(将其推送到主内存中,而不是仅停留在执行线程的CPU缓存中)。线程间需要避免竞争条件、死锁和其它共享状态相关的问题。
另外,当线程间在等待彼此访问共享数据结构时,会降低应用程序的并行性。许多并发数据结构都是阻塞式的,这意味着在给定时间只有一个或一组有限的线程可以访问它们,这可能导致线程对这些共享数据的竞争,高度竞争将会导致访问共享数据的代码从本质上变为串行执行。
现代的 **[非阻塞并行算法(non-blocking concurrency algorithms )](http://tutorials.jenkov.com/java-concurrency/non-blocking-algorithms.html)** 可能会减少竞争和提高性能,但是非阻塞算法很难实现。
持久化数据结构是另外一种选择,一个持久化数据在自身被修改时会始终保留之前的值。因此,如果多个线程同时操作一个持久化数据并且其中一个修改了该数据,该线程会得到新数据的引用,而其它线程在则保持着对未修改的旧数据的引用,从而依旧保持一致。在Scala编程中包含若干个持久化的数据结构。
虽然持久化数据结构是并发修改共享数据的一种看似优雅的解决方案,但其执行性能并不理想。例如,一个持久化的列表会把新元素加入其首部并且返回对该新增元素的引用(它将会指向列表的其余元素)。所有其它的线程仍然保持着对先前列表中第一个元素的引用,对这些线程而言该列表并没有发生修改,它们看不见新增加的元素。
这种持久化的列表可以用链表来实现,不幸的是,现在的硬件并不能很好的支持链表,链表中的每一个元素都是一个单独的对象,这些对象可以遍布计算机的内存。现在的CPU在访问连续的内存地址时速度更快,因此实现为数组(Array)结构会获得更高的性能。对于一个以数组方式存储的数据而言,CPU缓存可以一次将更大的数组块加载到缓存中,一旦数据加载完毕,CPU可以直接在缓存中访问这些数据,而这对于元素分散在RAM中的链表而言是不太可能实现的。
### 无状态的工作者
共享状态可以被系统中的其它线程修改,因此工作者(workers)在每次需要它们时都必须重新读取该状态,以确保它在最新的副本上工作,无论共享状态是保存在内存还是外部数据库中,都是如此。一个工作者不在其内部保存状态(而是在每次需要时都重新读取),我们称之为无状态。
### 任务顺序的不确定
并行工作者模型的另一个缺点是任务执行的顺序无法确定。没有办法来确保某个任务最先执行或最后执行,任务A在任务B之前分配给一个工作者,但是任务B可能先于任务A执行。
并能工作者模型的不确定性使得很难在任何给定的时间点推理系统的状态,它同样使得确保一个任务在另外一个任务之前执行变得更难(如果可能)。
## 流水线模型(Assembly Line)
第二种并发模型我称之为流水线模型,我选择名称以符合早期“并行工作者”的含义。在不同的平台/社区中,其他的开发人员或许使用其它的名称,如反应式系统(reactive systems),或事件驱动系统(event driven systems),下图是流水线并发模型的一个展示

这些工作者就像工厂里的工人一样组织起来,每个工作者只完成整个任务的一部分,当该部分任务完成时,该工作者将任务转移到下一个工作者。每个工作者都在自己的线程中运行,并且没有与其它的工作者共享状态,因此流水线模型有时也被称之为无共享的并发模型。
流水线模型通常用于系统中的非阻塞IO操作,非阻塞IO意味着当一个工作者(worker)开始一个IO操作时(如从网络读取文件或数据),该工作者(worker)不必等待IO操作结束。IO操作通常较慢,因此等待IO操作完成是对CPU时间的浪费,CPU可以在此时做一些其它事情。当IO操作完成时,IO操作的结果(如数据状态读取或输入写入)会传给下一个工作者(worker)。
使用非阻塞IO时,IO操作的结果决定了工作者(worker)之间的边界,一个工作者(worker)在不得不开始IO操作之前可以尽可能的完成任务,然后放弃对该任务的控制,当IO操作结束时,在流水线上的另一个工作者(worker)以类似的方式继续完成该任务,直到它不得不开始IO操作。

实际中,上述这些任务可能不会沿着一条流水线流动,因为大多数操作系统可以同时运行多个任务,这些任务根据实际需求沿着流水线逐个的被工作者处理。在实际使用中可能会有多个虚拟流水线同时运行,下图展示了在实际使用中任务如何在这种流水线上流转。

任务甚至可以转发给多个工作者进行并发处理,例如,一个任务可以被同时转发给一个任务执行器和一个任务日志记录器。下图展示了如何将三条装配线的中任务转发给同一个工作者完成(中间装配线上的最后一个工人):

流水线甚至可以做的比上面展示的更复杂。
### 响应式、事件驱动系统
使用流水线并发模型的系统有时候也被称之为 *响应式系统* 或 *事件驱动系统* 。系统工作者在事件发生时做出对应的响应:从外部接收消息或转发给其它工作者等。事件驱动的例子可能是传入的HTTP请求,也可能是某个文件完成加载到内存中等。
在写作本文时,已经有一些有趣的响应式/事件驱动平台可以使用,并且在将来会出现更多的。其中一些比较受欢迎的如下:
* **[Vert.x](http://tutorials.jenkov.com/vert.x/index.html)**
* Akka
* Node.JS (JavaScript)
对我个人而言,我发现Vert.x十分有趣(尤其是像我这种对Java/JVM落伍的人)。
### 参与者(Actors)与管道(Channels)对比
参与者(Actors)和管道(Channels)是两种类似的流水线(响应式/事件驱动)模型。
在参与者模型中,每个工作者被称之为一个参与者,参与者之间可以直接发消息给对方,这些消息以异步方式来发送和处理。参与者可以用于处理如前所述的一个或多个流水线任务,下图展示了这种模型:

在管道(Channel)模型中,工作者之间不直接互相沟通,相反地,他们会将消息发布到不同的管道中,其他的工作者可以在这些管道上收听消息,同时消息发送者不必知道谁在收听消息。下图展示了该模型:

在写作本文时,管道模型对我而言似乎更灵活:一个工作者不必知道在流水线上的哪个工作者要处理接下来的任务,它只需要知道需要将任务转发到哪个管道(或发送消息哪个管道等),在管道中的收听者可以订阅和取消订阅而不会影响到往管道中正在写入的工作者,这允许工作者之间有某种程度的低耦合。
## 流水线模型(Assembly Line)的优点
相对于并行工作者模型,流水线模型有一些优点,在接下来的部分,我会叙述其中最突出的几个优点。
### 无共享状态
工作者之间不共享状态的情形意味着它们可以在实现时不必考虑在状态共享时所遇到的各种并发问题,这让工作者的实现变得更加容易,在实现工作者时可以假设只有一个线程在处理该工作,本质上就是一个单线程实现。
### 有状态的工作者
由于工作者知道没有其它线程修改它们的数据,这些工作者可以具有状态。在说有状态时我的意思是它们可以保留在内存中操作所需的数据,只有写入才会改变最终的外部存储系统。因此,一个有状态的工作者通常比无状态的工作者执行更快。
### 更好的硬件协同
单线程代码的优点在于它通常更符合底层硬件的工作原理。首先你通常可以创建更优化的数据结构和算法当你能假定代码会以单线程模式执行。
其次,如前所述单线程有状态的工作者可以在内存中缓存数据,当数据在内存中缓存时,有很大的概率该数据也会被缓存到CPU缓存中,这样数据获取变得更快。
当代码以一种自然受益于底层硬件工作原理的方式编写时,我称之为 *硬件协调*,有些开发者称之为 *mechanical sympathy* ,我更倾向于硬件协同因为计算机只有很少的机械部件,同时单词“sympathy”在这种情况下被用作比喻“更高的匹配”,而我认为单词“conform”能更高的传达其含义。不管怎么说,这些都是吹毛求疵,可以使用你喜欢的任何术语来描述。
### 任务可排序
根据流水线模型实现的并发系统使得排序变得可能,任务排序使得在任何给定时间点更容易理解系统的状态。此外,你可以将所有传入的任务写入日志,如果系统的任何部分发生故障,则可以使用该日志从头重建系统的状态。这些任务以某种顺序写入日志,这个顺序称为该任务顺序,下图展示了这种设置如何实现:

确保一个任务的顺序实现起来不一定容易,但通常是可能的。如果你可以实现的话,它将会大大简化类似于数据备份、恢复数据、复制数据等的任务,这些都可以通过日志文件来完成。
## 流水线模型(Assembly Line)的缺点
流水线模型的最主要缺点是通常将执行一个任务分配到多个工作者,因此,当项目中有多个类时,将难以准确的看出哪段代码在执行给定的任务。
代码编写也可能会变得更难,工作者代码有时候被写作回调处理器(callback handlers)。在代码中有太多嵌套的回调处理器时可能会导致某些开发人员所谓的 *回调陷阱(callback hell)* 。回调陷阱简单的说就是在所有的回调中很难追踪代码真正在干啥以及确保每个回调都可以访问它需要的数据。
而使用并行工作者模型,这往往很容易。你可以打开对应的工作者代码,并从头到尾读取要执行的代码。当然,并行工作者模型也可能传播到不同的类中,但是要执行的序列通常更容易从代码中读取。
## 功能并行(Functional Parallelism)模型
功能\函数并行模型是第三种并发模型,最近谈论得很多(2015)。
功能\函数并行性的基本思想是通过函数调用实现程序,功能可以被看作是发送消息到彼此的“代理”或“角色”,就像流水线并发模型(AKA反应或事件驱动系统)一样,当一个函数调用另一个函数时,类似于消息发送。
传递给函数的所有参数都被复制,所以在接收函数之外没有任何实体可以操纵数据,这种复制对于对于避免共享数据的条件竞争至关重要,它使得函数执行类似于原子操作,每个函数调用都可以独立于任何其他函数调用执行。
当每个函数调用可以独立执行时,可以在单独的CPU上执行每个函数调用,这意味着,在多个CPU上可以并行执行功能实现的算法。
使用Java 7,我们得到了包含 *ForkJoinPool* 模型的 **java.util.concurrent** 包,可以帮助您实现类似于功能并行性的功能,而使用Java 8,我们将得到并行流,可以帮助您并行化大型集合的迭代。请记住,有开发人员批评 *ForkAndJoinPool* 模型(您可以在我的ForkAndJoinPool教程中找到一个相应的批评链接)。
关于功能\函数并行的难点在于知道哪个函数调用需要并行化,跨CPU的协调功能调用带来了一定的开销。只有由功能/函数完成的工作单位具有一定的大小,才能值得这个开销,如果函数调用非常小,尝试并行化它们可能比单个线程的单个CPU执行更慢。
从我的理解(事实上根本不完美),您可以使用事件响应驱动模型来实现实现算法,并实现与功能并行性相似的工作分解。在我看来,通过事件响应驱动模型,你可以掌握如何来实现并行化。
另外,只有当前任务是程序执行的唯一任务时,将任务分配给多个CPU,协调开销才有意义。然而,如果系统同时执行多个其他任务(如Web服务器,数据库服务器和许多其它系统),则无需尝试并行化单个任务。计算机中的其它CPU可能正在忙于处理其它任务,所以没有理由试图用较慢的功能并行任务来打扰他们。如有可能,你最好使用流水线并发模型,因为它在以单线程模式顺序执行的程序中具有更少的开销,并且更好的符合底层硬件的工作原理。
## 孰优孰劣
那么,哪种并发模型更好呢?
通常情况下,答案取决于你的系统应该做什么。 如果你的工作自然并行,独立,无需共享状态,则可以使用并行工作模型来实现系统。但许多任务不是自然并行和独立的,对于这些类型的系统,我相信流水线并发模型比缺点有更多的优点,比并行工作模型更有优势。你甚至不需要自己编写所有的流水线路基础设施,像Vert.x这样的现代平台为你已经实现了很多。 就个人而言,我将探索在Vert.x等平台上运行的设计,以便我的下一个项目。我个人感觉JavaEE没有尽头。
<–翻译结束!–> | mit |
pegurnee/2013-03-211 | complete/src/data_struct/in_class/d10_02/Sam.java | 817 | package data_struct.in_class.d10_02;
/**
* A class to test basic 'Object' methods
*
* @author Eddie Gurnee
* @version 10/02/13
* @see TestingSam
*
*/
public class Sam {
public int mikesplan = 8;
/**
* No argument constructor for the Sam class
*
*/
public Sam() {
}
/**
* Indicates if some other "Sam" object is equal to this one.
*
*/
public boolean equals(Sam otherObject) {
if (otherObject == null) {
System.out.println("check1");
return false;
}
else if (this.getClass() != otherObject.getClass()) {
System.out.println("check2");
return false;
}
else {
System.out.println("if this shows then fuck the police");
Sam otherSam = (Sam)otherObject;
return this.mikesplan == otherSam.mikesplan;
}
}
public int getMikesPlan() {
return mikesplan;
}
} | mit |
medialize/URI.js | uri-template.html | 14623 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>URI.js - URI-Template</title>
<meta name="description" content="URI.js is a Javascript library for working with URLs." />
<script src="jquery-3.6.0.min.js" type="text/javascript"></script>
<script src="prettify/prettify.js" type="text/javascript"></script>
<script src="screen.js" type="text/javascript"></script>
<link href="screen.css" rel="stylesheet" type="text/css" />
<link href="prettify/prettify.sunburst.css" rel="stylesheet" type="text/css" />
<script src="src/URI.min.js" type="text/javascript"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-8922143-3']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<style type="text/css">
.tpl-operator {
font-weight: bold;
color: #669933;
}
.tpl-variable {
font-weight: bold;
color: #336699;
}
.tpl-modifier {
font-weight: bold;
color: #663399;
}
pre {
padding: 10px;
background: #EEE;
}
table {
width: 100%;
border: 1px solid #AAA;
border-collapse: collapse;
}
td, th {
border: 1px solid #AAA;
text-align: left;
padding: 3px;
}
th {
background: #EEE;
}
</style>
</head>
<body>
<a id="github-forkme" href="https://github.com/medialize/URI.js"><img src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" /></a>
<div id="container">
<h1><a href="https://github.com/medialize/URI.js">URI.js</a></h1>
<ul class="menu">
<li><a href="/URI.js/">Intro</a></li>
<li><a href="about-uris.html">Understanding URIs</a></li>
<li><a href="docs.html">API-Documentation</a></li>
<li><a href="jquery-uri-plugin.html">jQuery Plugin</a></li>
<li class="active"><a href="uri-template.html">URI Template</a></li>
<li><a href="build.html">Build</a></li>
<li><a href="http://rodneyrehm.de/en/">Author</a></li>
</ul>
<h2>URI Template</h2>
<p>As of version 1.7.0 URI.js includes an implementation of URI Templates, as specified in <a href="http://tools.ietf.org/html/rfc6570">RFC 6570</a> (Level 4, March 2012).</p>
<h2>Using URI Templates</h2>
<pre class="prettyprint lang-js">
// creating a new URI Template
var template = new URITemplate("http://example.org/{file}");
var result = template.expand({file: "hello world.html"});
result === "http://example.org/hello%20world.html";
// of course you can call the constructor like a function and chain things:
result = URITemplate("http://example.org/{file}")
.expand({file: "hello world.html"});
result === "http://example.org/hello%20world.html";
// access via URI
result = URI.expand("http://example.org/{file}", {file: "hello world.html"});
// result == new URI("http://example.org/hello%20world.html");
// expand() accepts data-callbacks:
template.expand(function(key) {
var data = {file: "hello world.html"};
return data[key];
});
// expand() accepts key-callbacks:
template.expand({file : function(key) {
return "hello world.html";
}});
// Using strict mode
var template = new URITemplate("http://example.org/{file}");
var result = template.expand({filename: "hello world.html"}, { strict: true });
// Uncaught Error: Missing expansion value for variable "file"
</pre>
<h2>URI Template Syntax</h2>
<p><em>Expressions</em> are placeholders which are to be substituted by the values their variables reference.</p>
<ul>
<li><code>http://example.org/~<strong>{<em class="tpl-variable">username</em>}</strong>/</code></li>
<li><code>http://example.org/dictionary/<strong>{<em class="tpl-variable">term</em><span class="tpl-modifier">:1</span>}</strong>/<strong>{<em class="tpl-variable">term</em>}</strong></code></li>
<li><code>http://example.org/search<strong>{<span class="tpl-operator">?</span><em class="tpl-variable">q</em><span class="tpl-modifier">*</span>,<em class="tpl-variable">lang</em>}</strong></code></li>
</ul>
<p>
An expression consists of an <span class="tpl-operator">operator</span> and a (comma-separated) list of <em>variable-specifications</em>.
A variable-specification consists of a <em class="tpl-variable">variable</em> and an optional <em class="tpl-modifier">modifier</em>.
</p>
<hr>
<p>Given the template</p>
<pre><code>http://example.org/~<strong>{<em class="tpl-variable">username</em>}</strong>/<strong>{<em class="tpl-variable">term</em><span class="tpl-modifier">:1</span>}</strong>/<strong>{<em class="tpl-variable">term</em>}</strong><strong>{<span class="tpl-operator">?</span><em class="tpl-variable">q</em><span class="tpl-modifier">*</span>,<em class="tpl-variable">lang</em>}</strong></code></pre>
<p>and the following data: </p>
<pre><code>{username: "rodneyrehm", term: "hello world", q: {a: "mars", b: "jupiter"}, lang: "en"}</code></pre>
<p>the expansion looks as follows:
<pre><code>"http://example.org/~rodneyrehm/h/hello%20world?a=mars&b=jupiter&lang=en"</code></pre>
<hr>
<p>List of supported <span class="tpl-operator">operators</span>:</p>
<table>
<tr><th>Operator</th><th>Description</th></tr>
<tr><td><code><em>None</em></code></td><td>Simple String Expansion;</td></tr>
<tr><td><code>+</code></td><td>Reserved character strings;</td></tr>
<tr><td><code>#</code></td><td>Fragment identifiers prefixed by "#";</td></tr>
<tr><td><code>.</code></td><td>Name labels or extensions prefixed by ".";</td></tr>
<tr><td><code>/</code></td><td>Path segments prefixed by "/";</td></tr>
<tr><td><code>;</code></td><td>Path parameter name or name=value pairs prefixed by ";";</td></tr>
<tr><td><code>?</code></td><td>Query component beginning with "?" and consisting of name=value pairs separated by "&"; and,</td></tr>
<tr><td><code>&</code></td><td>Continuation of query-style &name=value pairs within a literal query component.</td></tr>
</table>
<p>List of supported <span class="tpl-modifier">modifiers</span>:</p>
<table>
<tr><th>Modifier</th><th>Description</th></tr>
<tr><td><code><em>None</em></code></td><td>No modification, arrays and objects are joined with ","</td></tr>
<tr><td><code>*</code></td><td>Explode arrays and objects (see tables below)</td></tr>
<tr><td><code>:3</code></td><td>Substring of the first 3 characters of the variable's value</td></tr>
</table>
<h3>Strings and Numbers</h3>
<p>
Given <code>{"var": "hello[world]"}</code>, the expression <code>{var}</code> expands to <code>hello%5Bworld%5D</code>.
The following table shows an output matrix for every possible operator/modifier combination produced for <code>string</code> input.
</p>
<table>
<tr><th></th><th colspan="3">Modifier</th></tr>
<tr><th>Operator</th><th><em>None</em></th><th>*</th><th>:2</th></tr>
<tr><td><code><em>None</em></code></td><td><code>hello%5Bworld%5D</code></td><td><code>hello%5Bworld%5D</code></td><td><code>he</code></td></tr>
<tr><td><code><em>+</em></code></td><td><code>hello[world]</code></td><td><code>hello[world]</code></td><td><code>he</code></td></tr>
<tr><td><code>#</code></td><td><code>#hello[world]</code></td><td><code>#hello[world]</code></td><td><code>#he</code></td></tr>
<tr><td><code>.</code></td><td><code>.hello%5Bworld%5D</code></td><td><code>.hello%5Bworld%5D</code></td><td><code>.he</code></td></tr>
<tr><td><code>/</code></td><td><code>/hello%5Bworld%5D</code></td><td><code>/hello%5Bworld%5D</code></td><td><code>/he</code></td></tr>
<tr><td><code>;</code></td><td><code>;var=hello%5Bworld%5D</code></td><td><code>;var=hello%5Bworld%5D</code></td><td><code>;var=he</code></td></tr>
<tr><td><code>?</code></td><td><code>?var=hello%5Bworld%5D</code></td><td><code>?var=hello%5Bworld%5D</code></td><td><code>?var=he</code></td></tr>
<tr><td><code>&</code></td><td><code>&var=hello%5Bworld%5D</code></td><td><code>&var=hello%5Bworld%5D</code></td><td><code>&var=he</code></td></tr>
</table>
<h3>Arrays</h3>
<p>
Given <code>{"var": ["one", "two", "three"]}</code>, the expression <code>{var}</code> expands to <code>one,two,three</code>.
The following table shows an output matrix for every possible operator/modifier combination produced for <code>array</code> input.
</p>
<table>
<tr><th></th><th colspan="3">Modifier</th></tr>
<tr><th>Operator</th><th><em>None</em></th><th>*</th><th>:2</th></tr>
<tr><td><code><em>None</em></code></td><td><code>one,two,three</code></td><td><code>one,two,three</code></td><td><code>on,tw,th</code></td></tr>
<tr><td><code><em>+</em></code></td><td><code>one,two,three</code></td><td><code>one,two,three</code></td><td><code>on,tw,th</code></td></tr>
<tr><td><code>#</code></td><td><code>#one,two,three</code></td><td><code>#one,two,three</code></td><td><code>#on,tw,th</code></td></tr>
<tr><td><code>.</code></td><td><code>.one,two,three</code></td><td><code>.one.two.three</code></td><td><code>.on,tw,th</code></td></tr>
<tr><td><code>/</code></td><td><code>/one,two,three</code></td><td><code>/one/two/three</code></td><td><code>/on,tw,th</code></td></tr>
<tr><td><code>;</code></td><td><code>;var=one,two,three</code></td><td><code>;var=one;var=two;var=three</code></td><td><code>;var=on,tw,th</code></td></tr>
<tr><td><code>?</code></td><td><code>?var=one,two,three</code></td><td><code>?var=one&var=two&var=three</code></td><td><code>?var=on,tw,th</code></td></tr>
<tr><td><code>&</code></td><td><code>&var=one,two,three</code></td><td><code>&var=one&var=two&var=three</code></td><td><code>&var=on,tw,th</code></td></tr>
</table>
<h3>Objects ("plain objects" / "hash maps")</h3>
<p>
Given <code>{"var": {"one": "alpha", "two": "bravo"}}</code>, the expression <code>{var}</code> expands to <code>one,two,three</code>.
The following table shows an output matrix for every possible operator/modifier combination produced for <code>object</code> input.
</p>
<table>
<tr><th></th><th colspan="3">Modifier</th></tr>
<tr><th>Operator</th><th><em>None</em></th><th>*</th><th>:2</th></tr>
<tr><td><code><em>None</em></code></td><td><code>one,alpha,two,bravo</code></td><td><code>one=alpha,two=bravo</code></td><td><code>on,al,tw,br</code></td></tr>
<tr><td><code><em>+</em></code></td><td><code>one,alpha,two,bravo</code></td><td><code>one=alpha,two=bravo</code></td><td><code>on,al,tw,br</code></td></tr>
<tr><td><code>#</code></td><td><code>#one,alpha,two,bravo</code></td><td><code>#one=alpha,two=bravo</code></td><td><code>#on,al,tw,br</code></td></tr>
<tr><td><code>.</code></td><td><code>.one,alpha,two,bravo</code></td><td><code>.one=alpha.two=bravo</code></td><td><code>.on,al,tw,br</code></td></tr>
<tr><td><code>/</code></td><td><code>/one,alpha,two,bravo</code></td><td><code>/one=alpha/two=bravo</code></td><td><code>/on,al,tw,br</code></td></tr>
<tr><td><code>;</code></td><td><code>;var=one,alpha,two,bravo</code></td><td><code>;one=alpha;two=bravo</code></td><td><code>;var=on,al,tw,br</code></td></tr>
<tr><td><code>?</code></td><td><code>?var=one,alpha,two,bravo</code></td><td><code>?one=alpha&two=bravo</code></td><td><code>?var=on,al,tw,br</code></td></tr>
<tr><td><code>&</code></td><td><code>&var=one,alpha,two,bravo</code></td><td><code>&one=alpha&two=bravo</code></td><td><code>&var=on,al,tw,br</code></td></tr>
</table>
<h2>Limitations</h2>
<p>URI Template is a <em>Proposed Standard</em> and because of that I did not want to deviate from it. That said I'm not at all happy with how the specification turned out. Here are some of my thoughts:</p>
<ul>
<li>The <em>explode modifier</em> works the wrong way. <code>{?some_object}</code> should lead to <code>?foo=bar&hello=world</code>, as this is the common expansion</li>
<li>The <em>prefix modifier</em> (which I would've named <em>truncate modifier</em>) only has an end-offset.
The specification says it's »used to partition an identifier space hierarchically«. <code>abc</code> may become <code>a/bc</code> or <code>a/ab/abc</code>.
But there is no way of modifying output to <code>a/b/c</code> or <code>a/b/abc</code>. Whenever I had to partition identifier spaces, I used one of the latter patterns.</li>
<li>Operators like <code>.</code> automatically prefix the expansion. So <code>{"var": ["filename", "extension"]}</code> and <code>{.var*}</code> results in <code>.filename.extension</code> - obviously not what I wanted.</li>
<li>Variable names (<em>varname</em>) may only contain <code>ALPHA / DIGIT / "_" / pct-encoded</code> and may not be decoded for resolving the reference. This simply feels weird, especially the "may not be decoded" part.</li>
<li>Other possible modifiers could include some simple character-munging like <em>UPPERCASE</em>, <em>LOWERCASE</em>, <em>CAPITALCASE</em></li>
<li><code>{/var,empty,empty}</code> results in <code>/foobar//</code> - clearly not what one intended</li>
<li><code>{var}</code> and <code>{"var" : {"a": "1", "b": "2"}}</code> results in <code>a,1,b,2</code> - excusemewhat? I would've expected <code>a=1,b=2</code> or <code>a:1,b:2</code> (in a perverse parallel universe).</li>
<li>Spaces in the <em>query string</em> should be encoded to <code>+</code>, not <code>%20</code> according to <a href="http://www.w3.org/TR/html401/interact/forms.html#form-content-type">application/x-www-form-urlencoded</a></li>
</ul>
</div>
</body>
</html>
| mit |
OctoEnigma/shiny-octo-system | lua/vgui/dvscrollbar.lua | 5940 | --[[
DVScrollBar
Usage:
Place this control in your panel. You will ideally have another panel or
control which is bigger than the original panel. This is the Canvas.
scrollbar:SetUp( _barsize_, _canvassize_ ) should be called whenever
the size of your 'canvas' changes.
scrollbar:GetOffset() can be called to get the offset of the canvas.
You should call this in your PerformLayout function and set the Y
pos of your canvas to this value.
Example:
function PANEL:PerformLayout()
local Wide = self:GetWide()
local YPos = 0
-- Place the scrollbar
self.VBar:SetPos( self:GetWide() - 16, 0 )
self.VBar:SetSize( 16, self:GetTall() )
-- Make sure the scrollbar knows how big our canvas is
self.VBar:SetUp( self:GetTall(), self.pnlCanvas:GetTall() )
-- Get data from the scrollbar
YPos = self.VBar:GetOffset()
-- If the scrollbar is enabled make the canvas thinner so it will fit in.
if ( self.VBar.Enabled ) then Wide = Wide - 16 end
-- Position the canvas according to the scrollbar's data
self.pnlCanvas:SetPos( self.Padding, YPos + self.Padding )
self.pnlCanvas:SetSize( Wide - self.Padding * 2, self.pnlCanvas:GetTall() )
end
--]]
local PANEL = {}
function PANEL:Init()
self.Offset = 0
self.Scroll = 0
self.CanvasSize = 1
self.BarSize = 1
self.btnUp = vgui.Create( "DButton", self )
self.btnUp:SetText( "" )
self.btnUp.DoClick = function( self ) self:GetParent():AddScroll( -1 ) end
self.btnUp.Paint = function( panel, w, h ) derma.SkinHook( "Paint", "ButtonUp", panel, w, h ) end
self.btnDown = vgui.Create( "DButton", self )
self.btnDown:SetText( "" )
self.btnDown.DoClick = function( self ) self:GetParent():AddScroll( 1 ) end
self.btnDown.Paint = function( panel, w, h ) derma.SkinHook( "Paint", "ButtonDown", panel, w, h ) end
self.btnGrip = vgui.Create( "DScrollBarGrip", self )
self:SetSize( 15, 15 )
end
function PANEL:SetEnabled( b )
if ( !b ) then
self.Offset = 0
self:SetScroll( 0 )
self.HasChanged = true
end
self:SetMouseInputEnabled( b )
self:SetVisible( b )
-- We're probably changing the width of something in our parent
-- by appearing or hiding, so tell them to re-do their layout.
if ( self.Enabled != b ) then
self:GetParent():InvalidateLayout()
if ( self:GetParent().OnScrollbarAppear ) then
self:GetParent():OnScrollbarAppear()
end
end
self.Enabled = b
end
function PANEL:Value()
return self.Pos
end
function PANEL:BarScale()
if ( self.BarSize == 0 ) then return 1 end
return self.BarSize / ( self.CanvasSize + self.BarSize )
end
function PANEL:SetUp( _barsize_, _canvassize_ )
self.BarSize = _barsize_
self.CanvasSize = math.max( _canvassize_ - _barsize_, 1 )
self:SetEnabled( _canvassize_ > _barsize_ )
self:InvalidateLayout()
end
function PANEL:OnMouseWheeled( dlta )
if ( !self:IsVisible() ) then return false end
-- We return true if the scrollbar changed.
-- If it didn't, we feed the mousehweeling to the parent panel
return self:AddScroll( dlta * -2 )
end
function PANEL:AddScroll( dlta )
local OldScroll = self:GetScroll()
dlta = dlta * 25
self:SetScroll( self:GetScroll() + dlta )
return OldScroll != self:GetScroll()
end
function PANEL:SetScroll( scrll )
if ( !self.Enabled ) then self.Scroll = 0 return end
self.Scroll = math.Clamp( scrll, 0, self.CanvasSize )
self:InvalidateLayout()
-- If our parent has a OnVScroll function use that, if
-- not then invalidate layout (which can be pretty slow)
local func = self:GetParent().OnVScroll
if ( func ) then
func( self:GetParent(), self:GetOffset() )
else
self:GetParent():InvalidateLayout()
end
end
function PANEL:AnimateTo( scrll, length, delay, ease )
local anim = self:NewAnimation( length, delay, ease )
anim.StartPos = self.Scroll
anim.TargetPos = scrll
anim.Think = function( anim, pnl, fraction )
pnl:SetScroll( Lerp( fraction, anim.StartPos, anim.TargetPos ) )
end
end
function PANEL:GetScroll()
if ( !self.Enabled ) then self.Scroll = 0 end
return self.Scroll
end
function PANEL:GetOffset()
if ( !self.Enabled ) then return 0 end
return self.Scroll * -1
end
function PANEL:Think()
end
function PANEL:Paint( w, h )
derma.SkinHook( "Paint", "VScrollBar", self, w, h )
return true
end
function PANEL:OnMousePressed()
local x, y = self:CursorPos()
local PageSize = self.BarSize
if ( y > self.btnGrip.y ) then
self:SetScroll( self:GetScroll() + PageSize )
else
self:SetScroll( self:GetScroll() - PageSize )
end
end
function PANEL:OnMouseReleased()
self.Dragging = false
self.DraggingCanvas = nil
self:MouseCapture( false )
self.btnGrip.Depressed = false
end
function PANEL:OnCursorMoved( x, y )
if ( !self.Enabled ) then return end
if ( !self.Dragging ) then return end
local x, y = self:ScreenToLocal( 0, gui.MouseY() )
-- Uck.
y = y - self.btnUp:GetTall()
y = y - self.HoldPos
local TrackSize = self:GetTall() - self:GetWide() * 2 - self.btnGrip:GetTall()
y = y / TrackSize
self:SetScroll( y * self.CanvasSize )
end
function PANEL:Grip()
if ( !self.Enabled ) then return end
if ( self.BarSize == 0 ) then return end
self:MouseCapture( true )
self.Dragging = true
local x, y = self.btnGrip:ScreenToLocal( 0, gui.MouseY() )
self.HoldPos = y
self.btnGrip.Depressed = true
end
function PANEL:PerformLayout()
local Wide = self:GetWide()
local Scroll = self:GetScroll() / self.CanvasSize
local BarSize = math.max( self:BarScale() * ( self:GetTall() - ( Wide * 2 ) ), 10 )
local Track = self:GetTall() - ( Wide * 2 ) - BarSize
Track = Track + 1
Scroll = Scroll * Track
self.btnGrip:SetPos( 0, Wide + Scroll )
self.btnGrip:SetSize( Wide, BarSize )
self.btnUp:SetPos( 0, 0, Wide, Wide )
self.btnUp:SetSize( Wide, Wide )
self.btnDown:SetPos( 0, self:GetTall() - Wide, Wide, Wide )
self.btnDown:SetSize( Wide, Wide )
end
derma.DefineControl( "DVScrollBar", "A Scrollbar", PANEL, "Panel" )
| mit |
Twangist/log_calls | tests/set_reset_defaults/global_defaults.py | 211 | __author__ = 'brianoneill'
from log_calls import log_calls
global_settings = dict(
log_call_numbers=True,
log_exit=False,
log_retval=True,
)
log_calls.set_defaults(global_settings, args_sep=' $ ')
| mit |
bhushankalvani/PFrepo | angularApp/user/user.routes.js | 461 | angular.module('phonebook')
.config(['$urlRouterProvider','$stateProvider',function($urlRouterProvider,$stateProvider){
$stateProvider
// Greeting State
.state('user.main',{
url : '/',
templateUrl : 'user/view/welcome.html',
controller : 'welcomeCtrl'
})
// Phonebook Display State
.state('user.PB',{
url : '/contacts',
templateUrl : 'user/view/displayContacts.html',
controller : 'cntctCtrl'
})
}]); | mit |
madhawa-se/scpost | application/views/home.php | 3962 |
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="<?php echo base_url() ?>css/bootstrap.min.css">
<style>
</style>
<script src="<?php echo base_url() ?>js/libs/jquery-2.2.1.min.js"></script>
<script src="<?php echo base_url() ?>js/libs/angular.min.js"></script>
<script src="<?php echo base_url() ?>js/libs/bootstrap.min.js"></script>
<script>
var app = angular.module('myapp', []);
app.controller('articlesCtrl', function ($scope, $http) {
var latestLastIndex = 0;
var popularLastIndex = 0;
$scope.hotArticles = [];
$scope.latestArticles = [];
$scope.loadPopular = function () {
$http({
method: 'GET',
url: '../index.php/article/getPopularPosts/' + popularLastIndex
}).then(function successCallback(response) {
popularLastIndex += 10;
$scope.hotArticles = $scope.hotArticles.concat(response.data);
}, function errorCallback(response) {
});
};
$scope.loadLatest = function () {
$http({
method: 'GET',
url: '../index.php/article/getLatestPosts/1'
}).then(function successCallback(response) {
latestLastIndex += 10;
$scope.latestArticles = response.data;
}, function errorCallback(response) {
});
};
$scope.loadPopular();
$scope.loadLatest();
});
</script>
</head>
<body>
<div class="container">
<div class="">
<div class="form-inline">
<input class="form-control" ><button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-search"></span> </button>
</div>
</div>
<div class="" ng-controller="articlesCtrl">
<h2> posts for you </h2>
<div class="pops-post row" >
<h4>popular articles</h4>
<div class="pops-block col-sm-3" ng-repeat="articlex in hotArticles">
<a ng-href="../index.php/article/{{articlex.post_id}}">
<h3>{{articlex.title}}</h3>
<img ng-src="http://lorempixel.com/300/200/transport/{{$index}}" alt="" class="img-responsive">
<div class="des">
discription of the post
</div>
</a>
</div>
</div>
<div class="">
<button class="btn btn-info" ng-click="loadPopular()">load more</button>
</div>
<h2> Latest posts</h2>
<div class="pops-post row">
<h4>popular articles</h4>
<div class="pops-block col-sm-3" ng-repeat="articlex in latestArticles">
<h3>{{articlex.title}}</h3>
<img ng-src="http://lorempixel.com/300/200/transport/{{$index}}" alt="" class="img-responsive">
<div class="des">
discription of the post
</div>
</div>
</div>
<div class="">
<button class="btn btn-info" ng-click="loadLatest()">load more</button>
</div>
</div>
</div>
</body>
</html> | mit |
seaboy1234/PineTreeLanguage | PineTree.Language/Syntax/ExpressionTerminal.cs | 228 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PineTree.Language.Syntax
{
public abstract class ExpressionTerminal : Expression
{
}
} | mit |
psklf/my-config-file | cnblogs_style/footer.html | 998 | <script>
var detail = $("#cb_post_title_url");
if (detail.text() !== ""){$("div#sideBar").hide();var mainArticleArea = $("div#mainContent");mainArticleArea.width("100%");mainArticleArea.css("margin-left","0");
$("div.forFlow #comment_form").css("margin-left","40px");
$("div.post h1.postTitle").after("<div id='mycpright'><strong>严正声明:</strong><br/>作者:<a href='http://www.cnblogs.com/psklf/' target='_blank'>psklf</a></br>出处: <a href=''>" + window.location.href + "</a></br>欢迎转载,但未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任!</div>");
}
window.onload = function() {};
</script>
<ul id="my_admin"><li id="nav_newpost" class="inline_li"><a id="MyLinks1_NewPostLink" class="menu" rel="nofollow" href="https://i.cnblogs.com/EditPosts.aspx?opt=1">新随笔</a></li><li id="nav_admin" class="inline_li"><a id="MyLinks1_Admin" class="menu" rel="nofollow" href="https://i.cnblogs.com/">admin</a></li><ul>
| mit |
Picturepark/Picturepark.SDK.TypeScript | docs/picturepark-sdk-v1-pickers/api/interfaces/_crypto_.keyexportoptions.html | 9186 | <!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>KeyExportOptions | picturepark-sdk-v1-pickers API</title>
<meta name="description" content="Documentation for picturepark-sdk-v1-pickers API">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../assets/css/main.css">
</head>
<body>
<header>
<div class="tsd-page-toolbar">
<div class="container">
<div class="table-wrap">
<div class="table-cell" id="tsd-search" data-index="../assets/js/search.json" data-base="..">
<div class="field">
<label for="tsd-search-field" class="tsd-widget search no-caption">Search</label>
<input id="tsd-search-field" type="text" />
</div>
<ul class="results">
<li class="state loading">Preparing search index...</li>
<li class="state failure">The search index is not available</li>
</ul>
<a href="../index.html" class="title">picturepark-sdk-v1-pickers API</a>
</div>
<div class="table-cell" id="tsd-widgets">
<div id="tsd-filter">
<a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a>
<div class="tsd-filter-group">
<div class="tsd-select" id="tsd-filter-visibility">
<span class="tsd-select-label">All</span>
<ul class="tsd-select-list">
<li data-value="public">Public</li>
<li data-value="protected">Public/Protected</li>
<li data-value="private" class="selected">All</li>
</ul>
</div>
<input type="checkbox" id="tsd-filter-inherited" checked />
<label class="tsd-widget" for="tsd-filter-inherited">Inherited</label>
<input type="checkbox" id="tsd-filter-externals" checked />
<label class="tsd-widget" for="tsd-filter-externals">Externals</label>
<input type="checkbox" id="tsd-filter-only-exported" />
<label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label>
</div>
</div>
<a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a>
</div>
</div>
</div>
</div>
<div class="tsd-page-title">
<div class="container">
<ul class="tsd-breadcrumb">
<li>
<a href="../globals.html">Globals</a>
</li>
<li>
<a href="../modules/_crypto_.html">"crypto"</a>
</li>
<li>
<a href="_crypto_.keyexportoptions.html">KeyExportOptions</a>
</li>
</ul>
<h1>Interface KeyExportOptions<T></h1>
</div>
</div>
</header>
<div class="container container-main">
<div class="row">
<div class="col-8 col-content">
<section class="tsd-panel tsd-type-parameters">
<h3>Type parameters</h3>
<ul class="tsd-type-parameters">
<li>
<h4>T<span class="tsd-signature-symbol">: </span><a href="../modules/_crypto_.html#keyformat" class="tsd-signature-type">KeyFormat</a></h4>
</li>
</ul>
</section>
<section class="tsd-panel tsd-hierarchy">
<h3>Hierarchy</h3>
<ul class="tsd-hierarchy">
<li>
<span class="target">KeyExportOptions</span>
</li>
</ul>
</section>
<section class="tsd-panel-group tsd-index-group">
<h2>Index</h2>
<section class="tsd-panel tsd-index-panel">
<div class="tsd-index-content">
<section class="tsd-index-section tsd-is-external">
<h3>Properties</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-property tsd-parent-kind-interface tsd-is-external"><a href="_crypto_.keyexportoptions.html#cipher" class="tsd-kind-icon">cipher</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface tsd-is-external"><a href="_crypto_.keyexportoptions.html#format" class="tsd-kind-icon">format</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface tsd-is-external"><a href="_crypto_.keyexportoptions.html#passphrase" class="tsd-kind-icon">passphrase</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface tsd-is-external"><a href="_crypto_.keyexportoptions.html#type" class="tsd-kind-icon">type</a></li>
</ul>
</section>
</div>
</section>
</section>
<section class="tsd-panel-group tsd-member-group tsd-is-external">
<h2>Properties</h2>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a name="cipher" class="tsd-anchor"></a>
<h3><span class="tsd-flag ts-flagOptional">Optional</span> cipher</h3>
<div class="tsd-signature tsd-kind-icon">cipher<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">string</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in node_modules/@types/node/crypto.d.ts:150</li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a name="format" class="tsd-anchor"></a>
<h3>format</h3>
<div class="tsd-signature tsd-kind-icon">format<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">T</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in node_modules/@types/node/crypto.d.ts:149</li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a name="passphrase" class="tsd-anchor"></a>
<h3><span class="tsd-flag ts-flagOptional">Optional</span> passphrase</h3>
<div class="tsd-signature tsd-kind-icon">passphrase<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">string</span><span class="tsd-signature-symbol"> | </span><a href="../classes/buffer.html" class="tsd-signature-type">Buffer</a></div>
<aside class="tsd-sources">
<ul>
<li>Defined in node_modules/@types/node/crypto.d.ts:151</li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a name="type" class="tsd-anchor"></a>
<h3>type</h3>
<div class="tsd-signature tsd-kind-icon">type<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">"pkcs1"</span><span class="tsd-signature-symbol"> | </span><span class="tsd-signature-type">"spki"</span><span class="tsd-signature-symbol"> | </span><span class="tsd-signature-type">"pkcs8"</span><span class="tsd-signature-symbol"> | </span><span class="tsd-signature-type">"sec1"</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in node_modules/@types/node/crypto.d.ts:148</li>
</ul>
</aside>
</section>
</section>
</div>
<div class="col-4 col-menu menu-sticky-wrap menu-highlight">
<nav class="tsd-navigation primary">
<ul>
<li class="globals ">
<a href="../globals.html"><em>Globals</em></a>
</li>
<li class="current tsd-kind-module tsd-is-external">
<a href="../modules/_crypto_.html">"crypto"</a>
<ul>
<li class=" tsd-kind-namespace tsd-parent-kind-module tsd-is-external">
<a href="../modules/_crypto_.constants.html">constants</a>
</li>
<li class=" tsd-kind-namespace tsd-parent-kind-module tsd-is-external">
<a href="../modules/_crypto_.generatekeypair.html">generate<wbr>Key<wbr>Pair</a>
</li>
</ul>
</li>
</ul>
</nav>
<nav class="tsd-navigation secondary menu-sticky">
<ul class="before-current">
</ul>
<ul class="current">
<li class="current tsd-kind-interface tsd-parent-kind-module tsd-has-type-parameter tsd-is-external">
<a href="_crypto_.keyexportoptions.html" class="tsd-kind-icon">Key<wbr>Export<wbr>Options</a>
<ul>
<li class=" tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a href="_crypto_.keyexportoptions.html#cipher" class="tsd-kind-icon">cipher</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a href="_crypto_.keyexportoptions.html#format" class="tsd-kind-icon">format</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a href="_crypto_.keyexportoptions.html#passphrase" class="tsd-kind-icon">passphrase</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a href="_crypto_.keyexportoptions.html#type" class="tsd-kind-icon">type</a>
</li>
</ul>
</li>
</ul>
<ul class="after-current">
</ul>
</nav>
</div>
</div>
</div>
<footer class="with-border-bottom">
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
<ul class="tsd-legend">
<li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li>
</ul>
</div>
</div>
</footer>
<div class="container tsd-generator">
<p>Generated using <a href="https://typedoc.org/" target="_blank">TypeDoc</a></p>
</div>
<div class="overlay"></div>
<script src="../assets/js/main.js"></script>
</body>
</html> | mit |
friedlP/FTail | STextViewControl/Properties/Settings.Designer.cs | 1097 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace STextViewControl.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| mit |
chrilith/Passerelle | Lua Module/Device.cpp | 6949 | #include "Common.h"
#include "Script.h"
#include <atlimage.h>
#include <hidsdi.h>
#include <SetupAPI.h>
#define HID_SFIP 'SFIP'
#define HID_X52P 'X52P'
#define HID_UNKN 'UNKN'
// CHECKME : Do we still need all this code since we now have a GetSerialNumber() in the DO API?
DeviceManager *DevMan = DeviceManager::GetInstance();
SaitekDevice HID[HID_COUNT];
int HIDCount = HID_EMPTY;
int ToDeviceShortName(const char *type) {
if (strcmp(type, "SFIP") == 0)
return HID_SFIP;
if (strcmp(type, "X52P") == 0)
return HID_X52P;
return HID_UNKN;
}
int GetDeviceShortName(GUID type) {
if (type == DeviceType_Fip)
return HID_SFIP;
if (type == DeviceType_X52Pro)
return HID_X52P;
return HID_UNKN;
}
const char *GetDeviceStringName(GUID type) {
if (type == DeviceType_Fip)
return "SFIP";
if (type == DeviceType_X52Pro)
return "X52P";
return "UNKN";
}
int HIDLookupByType(const char *type, int index) {
int count = 1; // Index starts at 1 in Lua
int dev = ToDeviceShortName(type);
for (int i = 0; i < HIDCount; i++) {
if (GetDeviceShortName(HID[i].type) == dev/* && HID[i].isActive*/) {
if (count++ == index)
return i;
}
}
return HID_NOTFOUND;
}
int HIDLookupByIndex(int index) {
int count = 1; // Index starts at 1 in Lua
int dev = GetDeviceShortName(HID[index].type);
for (int i = 0; i < HIDCount; i++) {
if (GetDeviceShortName(HID[i].type) == dev/* && HID[i].isActive*/) {
if (index == i)
return count;
count++;
}
}
return HID_NOTFOUND;
}
static void CALLBACK DO_Enumerate(void* hDevice, void* pCtxt) {
DevMan->HandleDeviceChange(hDevice, true);
}
static void CALLBACK DO_DeviceChange(void* hDevice, bool bAdded, void* pCtxt) {
int index = DevMan->HandleDeviceChange(hDevice, bAdded);
LuaMan->CallDeviceChangeCallbacks(index, bAdded);
}
void DeviceManager::Initialize() {
_lockInit.Acquire();
if (_initializedCounter > 0) {
_initializedCounter++;
_lockInit.Release();
return;
}
// Initialize...
memset(HID, 0, sizeof(SaitekDevice) * HID_COUNT);
HIDCount = HID_EMPTY;
//Initialize DirectInput
HRESULT hdi = DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (LPVOID *)&this->_di, NULL);
if (!SUCCEEDED(hdi)) {
_lockInit.Release();
return;
}
//Initialize Saitek DirectOutput
_do = new CDirectOutput();
HRESULT hdo = _do->Initialize(L"" LUALIB_IDENT);
if (!SUCCEEDED(hdo)) {
_di->Release();
_lockInit.Release();
return;
}
// Register callbacks
HRESULT h1 = _do->Enumerate((Pfn_DirectOutput_EnumerateCallback)DO_Enumerate, NULL);
HRESULT h2 = _do->RegisterDeviceCallback((Pfn_DirectOutput_DeviceChange)DO_DeviceChange, NULL);
// Everything OK
_initializedCounter = 1;
_lockInit.Release();
}
void DeviceManager::Release() {
_lockInit.Acquire();
if (_initializedCounter-- > 1) {
_lockInit.Release();
return;
}
_do->Deinitialize();
_di->Release();
_initializedCounter = 0;
_lockInit.Release();
}
void DeviceManager::GetDeviceInfo(void *hDevice, DeviceData &dd) {
GUID gi;
HRESULT hr = DO()->GetDeviceInstance(hDevice, &gi);
GetDeviceInfo(gi, dd);
}
void DeviceManager::GetDeviceInfo(const GUID &iid, DeviceData &dd) {
SP_DEVINFO_DATA DeviceInfoData;
SP_DEVICE_INTERFACE_DATA did;
struct { DWORD cbSize; TCHAR DevicePath[256]; } ciddd;
TCHAR s[64];
GUID HidGuid;
//Empty
dd.instanceID[0] = 0;
dd.name[0] = 0;
dd.serialNumber[0] = 0;
// Try to create a device
LPDIRECTINPUTDEVICE8 pDevice;
HRESULT hd = DevMan->DI()->CreateDevice(iid, &pDevice, NULL);
if (FAILED(hd)) {
return;
}
// Get the GUID and Path
DIPROPGUIDANDPATH h;
h.diph.dwSize = sizeof(DIPROPGUIDANDPATH);
h.diph.dwHeaderSize = sizeof(DIPROPHEADER);
h.diph.dwObj = 0;
h.diph.dwHow = DIPH_DEVICE;
HRESULT hp = pDevice->GetProperty(DIPROP_GUIDANDPATH, (LPDIPROPHEADER)&h);
if (FAILED(hd))
return;
// Change # to \ to match structure of instance ID
for (size_t i = 0; i < wcslen(h.wszPath); i++) {
if (h.wszPath[i] == L'#') {
h.wszPath[i] = L'\\';
}
}
// Prepare enumeration
HidD_GetHidGuid(&HidGuid);
HDEVINFO hdi = SetupDiGetClassDevs(&HidGuid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
did.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
ciddd.cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA);
for (int i = 0; SetupDiEnumDeviceInterfaces(hdi, 0, &HidGuid, i, &did); i++) {
if (!SetupDiGetDeviceInterfaceDetail(hdi, &did, PSP_INTERFACE_DEVICE_DETAIL_DATA(&ciddd), sizeof(ciddd.DevicePath), 0, &DeviceInfoData))
continue;
if (!SetupDiGetDeviceInstanceId(hdi, &DeviceInfoData, s, sizeof(s), 0))
continue;
_wcslwr_s(s);
if(!wcsstr(h.wszPath, s))
continue;
strncpy_s(dd.instanceID, CT2A(s), sizeof(dd.instanceID) - 1);
HANDLE h = CreateFile(ciddd.DevicePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
if (HidD_GetProductString(h, s, sizeof(s)))
strncpy_s(dd.name, CT2A(s), sizeof(dd.name) - 1);
if (HidD_GetSerialNumberString(h, s, sizeof(s)))
strncpy_s(dd.serialNumber, CT2A(s), sizeof(dd.serialNumber) - 1);
CloseHandle(h);
}
SetupDiDestroyDeviceInfoList(hdi);
}
int DeviceManager::Prepare(void *hDevice) {
if (HIDCount == HID_COUNT)
return HID_NOTFOUND;
int index = HIDCount++;
HID[index].hDevice = hDevice;
return index;
}
void DeviceManager::Set(int index) {
void *hDevice = HID[index].hDevice;
GUID gt, gi;
DeviceData dd;
GetDeviceInfo(hDevice, dd);
DO()->GetDeviceType(hDevice, >);
DO()->GetDeviceInstance(hDevice, &gi);
HID[index].type = gt;
HID[index].instance = gi;
strcpy_s(HID[index].instanceID, dd.instanceID);
strcpy_s(HID[index].name, dd.name);
strcpy_s(HID[index].serialNumber, dd.serialNumber);
}
int DeviceManager::HandleDeviceChange(void *hDevice, bool bAdded) {
int index = LookupByHandle(hDevice);
_lockHID.Acquire();
if (bAdded) {
if (index == HID_NOTFOUND)
index = LookupByDeviceInfo(hDevice, false);
if (index == HID_NOTFOUND)
index = Prepare(hDevice);
}
if (index != HID_NOTFOUND) {
HID[index].isActive = bAdded;
if (bAdded) {
HID[index].hDevice = hDevice;
Set(index);
}
}
_lockHID.Release();
return index;
}
int DeviceManager::LookupByHandle(void* hDevice) {
_lockHID.Acquire();
for (int i = 0; i < HIDCount; i++) {
if (hDevice == HID[i].hDevice) {
_lockHID.Release();
return i;
}
}
_lockHID.Release();
return HID_NOTFOUND;
}
int DeviceManager::LookupByDeviceInfo(void *hDevice, bool isActive) {
GUID gt;
DeviceData dd;
DO()->GetDeviceType(hDevice, >);
GetDeviceInfo(hDevice, dd);
return LookupByDeviceInfo(gt, dd, isActive);
}
int DeviceManager::LookupByDeviceInfo(GUID &type, DeviceData &dd, bool isActive) {
for (int i = 0; i < HIDCount; i++) {
if (HID[i].isActive == isActive && HID[i].type == type &&
strcmp(dd.instanceID, HID[i].instanceID) == 0 &&
strcmp(dd.serialNumber, HID[i].serialNumber) == 0) {
return i;
}
}
return HID_NOTFOUND;
}
| mit |
jeshuamaxey/flappy-tom | js/screens/title.js | 2176 | game.TitleScreen = me.ScreenObject.extend({
init: function(){
this.font = null;
},
onResetEvent: function() {
me.audio.stop("theme");
game.data.newHiScore = false;
me.game.world.addChild(new BackgroundLayer('bg', 1));
me.input.bindKey(me.input.KEY.ENTER, "enter", true);
me.input.bindKey(me.input.KEY.SPACE, "enter", true);
me.input.bindMouse(me.input.mouse.LEFT, me.input.KEY.ENTER);
this.handler = me.event.subscribe(me.event.KEYDOWN, function (action, keyCode, edge) {
if (action === "enter") {
me.state.change(me.state.PLAY);
}
});
//logo
var logoImg = me.loader.getImage('logo');
var logo = new me.SpriteObject (
me.game.viewport.width/2 - 170,
-logoImg,
logoImg
);
me.game.world.addChild(logo, 10);
var logoTween = new me.Tween(logo.pos).to({y: me.game.viewport.height/2 - 100},
1000).easing(me.Tween.Easing.Exponential.InOut).start();
this.ground = new TheGround();
me.game.world.addChild(this.ground, 11);
me.game.world.addChild(new (me.Renderable.extend ({
// constructor
init: function() {
// size does not matter, it's just to avoid having a zero size
// renderable
this.parent(new me.Vector2d(), 100, 100);
//this.font = new me.Font('Arial Black', 20, 'black', 'left');
this.text = me.device.touch ? 'Tap to start' : 'PRESS SPACE OR CLICK LEFT MOUSE BUTTON TO START';
this.font = new me.Font('gamefont', 20, '#000');
},
update: function () {
return true;
},
draw: function (context) {
var measure = this.font.measureText(context, this.text);
this.font.draw(context, this.text, me.game.viewport.width/2 - measure.width/2, me.game.viewport.height/2 + 50);
}
})), 12);
},
onDestroyEvent: function() {
// unregister the event
me.event.unsubscribe(this.handler);
me.input.unbindKey(me.input.KEY.ENTER);
me.input.unbindKey(me.input.KEY.SPACE);
me.input.unbindMouse(me.input.mouse.LEFT);
me.game.world.removeChild(this.ground);
}
});
| mit |
colincwilliams/Extensions | README.md | 57 | # Extensions
A collection of useful, generic extensions.
| mit |
leonnybg/SoftUni-SoftwareTechnologies-july2017 | L8-PHP-Syntax- Basic-Web-Ex/04. Product of 3 Numbers.php | 895 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>First Steps Into PHP</title>
</head>
<body>
<form>
X: <input type="text" name="num1" />
Y: <input type="text" name="num2" />
Z: <input type="text" name="num3" />
<input type="submit" />
</form>
<?php
if (!isset($_GET['num1']) || !isset($_GET['num2']) || !isset($_GET['num3'])){
exit(1);
}
$numbers = [$_GET['num1'], $_GET['num2'], $_GET['num3']];
$numbers = array_map('intval',$numbers);
if (in_array(0, $numbers)){
echo "Positive";
exit(0);
}
$numbers = array_filter($numbers,function ($num){
return $num<0;
});
$negativeNumbersCount = count($numbers);
$isPositive = $negativeNumbersCount%2==0;
if ($isPositive){
echo "Positive";
}
else{
echo "Negative";
}
?>
</body>
</html> | mit |
DirtyHairy/mayrogue-deathmatch | goldmine/server/brain/strategy/randomWalk.js | 1069 | 'use strict';
var _ = require('underscore'),
Util = require('../../shared/util'),
Base = require('./base'),
Action = require('../../action'),
Types = require('./types');
var _parent = Base.prototype;
var RandomWalk = Util.extend(Base, {
properties: ['walkPropability'],
type: Types.RANDOM_WALK,
_walkPropability: 0.3,
create: function(config) {
var me = this;
me.getConfig(config, ['walkPropability']);
_parent.create.apply(me, arguments);
},
decide: function() {
var me = this;
if (Math.random() > me._walkPropability) {
return null;
}
switch (_.random(3)) {
case 0:
return new Action.Move({deltaX: 1});
case 1:
return new Action.Move({deltaX: -1});
case 2:
return new Action.Move({deltaY: 1});
case 3:
return new Action.Move({deltaY: -1});
}
return null;
}
});
module.exports = RandomWalk; | mit |
youcefboukersi/serveurdevoeux | app/cache/dev/twig/1b/1bf602c2860b97f0808215b5052e0f5850091179d1670e489003312b329f5b04.php | 3227 | <?php
/* SRVDVServerBundle:ChangePassword:changePassword.html.twig */
class __TwigTemplate_e5da0f0553fed635f2774271a2ef3982b389e99e651b1a8527dd0c0b6ca90bd7 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
'fos_user_content' => array($this, 'block_fos_user_content'),
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$__internal_dba29332523289305b524aa02b65cdc5bbca3fb6efbdc513d345b9889461d749 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
$__internal_dba29332523289305b524aa02b65cdc5bbca3fb6efbdc513d345b9889461d749->enter($__internal_dba29332523289305b524aa02b65cdc5bbca3fb6efbdc513d345b9889461d749_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "SRVDVServerBundle:ChangePassword:changePassword.html.twig"));
// line 1
echo "
";
// line 3
$this->displayBlock('fos_user_content', $context, $blocks);
$__internal_dba29332523289305b524aa02b65cdc5bbca3fb6efbdc513d345b9889461d749->leave($__internal_dba29332523289305b524aa02b65cdc5bbca3fb6efbdc513d345b9889461d749_prof);
}
public function block_fos_user_content($context, array $blocks = array())
{
$__internal_88a9de92c19248f7d08ce7d00e126ae41ccc9a58d5b4ae6e4fbe4c1d49a1a1db = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
$__internal_88a9de92c19248f7d08ce7d00e126ae41ccc9a58d5b4ae6e4fbe4c1d49a1a1db->enter($__internal_88a9de92c19248f7d08ce7d00e126ae41ccc9a58d5b4ae6e4fbe4c1d49a1a1db_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "fos_user_content"));
// line 4
echo " ";
$this->loadTemplate("SRVDVServerBundle:ChangePassword:changePassword_content.html.twig", "SRVDVServerBundle:ChangePassword:changePassword.html.twig", 4)->display($context);
$__internal_88a9de92c19248f7d08ce7d00e126ae41ccc9a58d5b4ae6e4fbe4c1d49a1a1db->leave($__internal_88a9de92c19248f7d08ce7d00e126ae41ccc9a58d5b4ae6e4fbe4c1d49a1a1db_prof);
}
public function getTemplateName()
{
return "SRVDVServerBundle:ChangePassword:changePassword.html.twig";
}
public function getDebugInfo()
{
return array ( 39 => 4, 27 => 3, 23 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("
{% block fos_user_content %}
{% include \"SRVDVServerBundle:ChangePassword:changePassword_content.html.twig\" %}
{% endblock fos_user_content %}
", "SRVDVServerBundle:ChangePassword:changePassword.html.twig", "C:\\wamp64\\www\\serveurDeVoeux\\src\\SRVDV\\ServerBundle/Resources/views/ChangePassword/changePassword.html.twig");
}
}
| mit |
zwirec/TravelMate | models/baseManager.h | 1656 | //
// Created by root on 07.05.17.
//
#ifndef BASICMODEL_BASEMANAGER_H
#define BASICMODEL_BASEMANAGER_H
#include <mysql++.h>
#include <vector>
#include "dbConfig.h"
namespace model {
namespace manager {
template<class ModelName>
class baseManager {
public:
baseManager() {
try {
_con.connect(db_name, db_ip, db_user, db_password);
}
catch (...) {
return;
}
}
baseManager(const std::string &table) : _tableName(table) {
try {
_con.connect(db_name, db_ip, db_user, db_password);
}
catch (...) {
return;
}
}
baseManager(const baseManager &rhs) : _con(rhs._con), _query(rhs._query),
_tableName(rhs._tableName) {}
virtual ~baseManager() {
_con.disconnect();
}
virtual void update(ModelName &model) = 0;
virtual void get(const std::string &filter) = 0;
virtual void get() = 0;
virtual void all() = 0;
virtual void filter(const std::string &filter) = 0;
virtual void execute() = 0;
virtual void execute(ModelName &result) = 0;
virtual void execute(std::vector<ModelName> &result) = 0;
protected:
mysqlpp::Connection _con;
std::string _query;
std::string _tableName;
};
}
}
#endif //BASICMODEL_BASEMANAGER_H
| mit |
junming4/eelly-sdk-php | src/SDK/Order/Api/Offline.php | 641 | <?php
declare(strict_types=1);
/*
* This file is part of eelly package.
*
* (c) eelly.com
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eelly\SDK\Order\Api;
use Eelly\SDK\Order\Service\OfflineInterface;
/**
* @author shadonTools<[email protected]>
*/
class Offline implements OfflineInterface
{
/**
* @return self
*/
public static function getInstance(): self
{
static $instance;
if (null === $instance) {
$instance = new self();
}
return $instance;
}
}
| mit |
sbishopwta/WTCalendarController | Example/Pods/Target Support Files/Pods-WTCalendarController_Example/Pods-WTCalendarController_Example-frameworks.sh | 3624 | #!/bin/sh
set -e
echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}"
install_framework()
{
if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then
local source="${BUILT_PRODUCTS_DIR}/$1"
elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then
local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")"
elif [ -r "$1" ]; then
local source="$1"
fi
local destination="${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
if [ -L "${source}" ]; then
echo "Symlinked..."
source="$(readlink "${source}")"
fi
# use filter instead of exclude so missing patterns dont' throw errors
echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\""
rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}"
local basename
basename="$(basename -s .framework "$1")"
binary="${destination}/${basename}.framework/${basename}"
if ! [ -r "$binary" ]; then
binary="${destination}/${basename}"
fi
# Strip invalid architectures so "fat" simulator / device frameworks work on device
if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then
strip_invalid_archs "$binary"
fi
# Resign the code if required by the build settings to avoid unstable apps
code_sign_if_enabled "${destination}/$(basename "$1")"
# Embed linked Swift runtime libraries. No longer necessary as of Xcode 7.
if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then
local swift_runtime_libs
swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]})
for lib in $swift_runtime_libs; do
echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\""
rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}"
code_sign_if_enabled "${destination}/${lib}"
done
fi
}
# Signs a framework with the provided identity
code_sign_if_enabled() {
if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then
# Use the current code_sign_identitiy
echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}"
echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements \"$1\""
/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements "$1"
fi
}
# Strip invalid architectures
strip_invalid_archs() {
binary="$1"
# Get architectures for current file
archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)"
stripped=""
for arch in $archs; do
if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then
# Strip non-valid architectures in-place
lipo -remove "$arch" -output "$binary" "$binary" || exit 1
stripped="$stripped $arch"
fi
done
if [[ "$stripped" ]]; then
echo "Stripped $binary of architectures:$stripped"
fi
}
if [[ "$CONFIGURATION" == "Debug" ]]; then
install_framework "$CONFIGURATION_BUILD_DIR/WTCalendarController/WTCalendarController.framework"
fi
if [[ "$CONFIGURATION" == "Release" ]]; then
install_framework "$CONFIGURATION_BUILD_DIR/WTCalendarController/WTCalendarController.framework"
fi
| mit |
benIT/github-blog | source/_posts/2017-03-29-consumming-a-moodle-webservice.md | 2353 | ---
title: Consuming a Moodle webservice
categories:
- Moodle
- dev
- webservices
tags:
---
This post describes how to consume a Moodle core webservice.
##Set up Moodle
### Enable REST protocol
In `Dashboard / ► Site administration / ► Plugins / ► Web services / ► Manage protocols`
- enable REST protocol.
- enable `Web services documentation` too.
###Create a custom webservice
In `Dashboard / ► Site administration / ► Plugins / ► Web services / ► External services`
- add a custom services named `test ws` for example
###Create a custom user for webservice
In `Dashboard / ► Site administration / ► Users / ► Accounts / ► Add a new user`
- create a `wsuser` user.
###Create a custom role for webservice
In `Dashboard / ► Site administration / ► Users / ► Permissions / ► Define roles`
- create a `ws_user_role`.
- allow at least `Create a web service token`
###Assign role to user
`Dashboard / ► Site administration / ► Users / ► Permissions / ► Assign system roles`
##Test
### Get a cool REST client
Getting a user friendly REST client is important, [POSTMAN is pretty cool](https://www.getpostman.com/).
###Get a token
Make a GET request to get a token.
For instance:`https://192.168.33.10/login/token.php?service=test_ws&username=wsuser&password=Wsuser123456-`. You should get:
{
"token": "19f315a127eef1f7f381da40fefd7b75"
}
###Consuming a Moodle core webservice
Now we get a token! So let's consume the `core_course_get_courses` WS. Results in JSON with `moodlewsrestformat=json`.
Make a POST request on `https://192.168.33.10/webservice/rest/server.php?wstoken=19f315a127eef1f7f381da40fefd7b75&wsfunction=core_course_get_courses&options[ids][0]=1&moodlewsrestformat=json`. You should get :
[
{
"id": 1,
"shortname": "test",
"categoryid": 0,
"fullname": "Site de test",
"summary": "",
"summaryformat": 1,
"format": "site",
"startdate": 0,
"numsections": 1
}
]
###API DOCUMENTATION
This can be found at `Dashboard / ► Site administration / ► Plugins / ► Web services / ► API Documentation` | mit |
wasit7/tutorials | arduino_python/weatherstation/scituweather/templates/3.html | 2799 | <!DOCTYPE html>
<html lang="en">
<head>
<title>Rice Diseases</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="static/bootstrap.min.css">
<script src="static/jquery.min.js"></script>
<script src="static/bootstrap.min.js"></script>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/">Forecast</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="/">Home</a></li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Rice Diseases
<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="/1">Brown Spot Disease</a></li>
<li><a href="/2">Blast Disease</a></li>
<li><a href="/3">Bacterial Leaf Streak Disease</a></li>
<li><a href="/4">Dirty Panicle Disease</a></li>
<li><a href="/5">Bacterial Leaf Blight Disease</a></li>
</ul>
</li>
<li><a href="/graph">Graph</a></li>
<li><a href="/read">Data</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<h1>Bacterial Leaf Streak Disease</h1>
<h2>Symptoms</h2>
<p>
Symptoms are narrow, dark-greenish, water-soaked, interveinal streaks of various lengths, initially restricted to the leaf blades. The lesions enlarge, turn yellowish-orange to brown (depending on cultivar), and eventually coalesce. Tiny amber droplets of bacterial exudate are often present on the lesions.</p>
<p>Causal agent : <i>Xanthomonas oryzae pv. oryzicola</i>
<br>
Percentage of damage: Seedling 70%, Grains production period 30%
</p>
<div class="container">
<div style="float:left;"><img class="img-responsive" src="static/31.png" alt="Bacterial leaf streak disease" width="200"></div>
<div style="float:left;"><img class="img-responsive" src="static/32.png" alt="Bacterial leaf streak disease" width="200"></div>
<div style="float:left;"><img class="img-responsive" src="static/33.png" alt="Bacterial leaf streak disease" width="200"></div>
</div>
<h2>Managements</h2>
<p>
1. Phytosanitary measures to prevent the distribution of seed infected.
<br>
2. Healthy seed is used.
<br>
3. Suitable using nitrogenous fertilizer because the use of excess nitrogenous fertilizer has shown an increase in incidence.
<br>
4. Biological control such as Trichoderma spp., Bacillus subtilis, Pseudomonas fluorescens.
<br>
5. Other control measures are not likely to be necessary.
<p>
</div>
</div>
</div>
</body>
</html>
| mit |
Kanma/Athena-Math | unittests/scripting/js/Matrix3/CreationWithValues.js | 282 | import_module('Athena.Math');
m1 = new Athena.Math.Matrix3(1, 2, 3,
4, 5, 6,
7, 8, 9);
for (var row = 0; row < 3; ++row)
{
for (var col = 0; col < 3; ++col)
CHECK_CLOSE(row * 3 + col + 1, m1.get(row, col));
}
| mit |
yogeshsaroya/new-cdnjs | ajax/libs/timelinejs/2.35.6/js/locale/el.js | 129 | version https://git-lfs.github.com/spec/v1
oid sha256:27606576bf3cd46c15755bdec387cc97145a4a0c0a5b3933c11d30ab8c6c5ec7
size 1825
| mit |
fredlincoln/sprcorp | template-parts/content.php | 624 | <?php
/**
* The default template for displaying content
*
* Used for both single and index/archive/search.
*
* @package FoundationPress
* @since FoundationPress 1.0.0
*/
?>
<div id="post-<?php the_ID(); ?>" <?php post_class('blogpost-entry'); ?>>
<header>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php foundationpress_entry_meta(); ?>
</header>
<div class="entry-content">
<?php the_content( __( 'Continue reading...', 'foundationpress' ) ); ?>
</div>
<footer>
<?php $tag = get_the_tags(); if ( $tag ) { ?><p><?php the_tags(); ?></p><?php } ?>
</footer>
<hr />
</div>
| mit |
Photosynq/PhotosynQ-Documentation | docs/enterprise-edition/users.md | 987 | # Users
With the **Enterprise Edition** there are two categories of users which have different roles and permissions.
## General Users
General users of the **Enterprise Edition** have the same permissions and features at hand as compared to users of the **Community Edition**. The only difference is, that new users need to be invited by an administrator and can't simply sign up. Further they are not allowed to invite or add new users.
## Administrators
Administrators (admins) of the **Enterprise Edition** have access to the administration area of the website to manage general users, admin users, but also Projects, Protocols, Measurements, etc. The purpose of the admin is purely to manage the page, content and users.
::: warning Note
An admin user is not permitted to login to the web app, desktop app, or mobile app. The admin must also be added as a general user in order to contribute data and collaborate on projects via the web, desktop, and mobile applications.
:::
| mit |
dtulibrary/toshokan | db/migrate/20130827081527_ensure_no_limit_on_user_data_field.rb | 157 | class EnsureNoLimitOnUserDataField < ActiveRecord::Migration
def up
change_column :users, :user_data, :text, :limit => nil
end
def down
end
end
| mit |
TelemarkAlpint/telemark-2004 | bilder/gallery/classes/postnuke0.7.1/User.php | 2614 | <?php
/*
* Gallery - a web based photo album viewer and editor
* Copyright (C) 2000-2004 Bharat Mediratta
*
* 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* $Id: User.php,v 1.7 2004/03/23 17:53:16 cryptographite Exp $
*/
?>
<?php
class PostNuke_User extends Abstract_User {
function loadByUid($uid) {
global $name; /* Gallery PN module name */
/*
* Consider the case where we're trying to load a $uid
* that stemmed from a user created by a standalone
* Gallery. That $uid won't be valid for PostNuke.
* We don't want this to cause problems, so in that
* case we'll just pretend that it was Nobody.
*
* But how do we detect those users? Well, let's take
* the quick and dirty approach of making sure that
* the uid is numeric.
*/
if (ereg("[^0-9]", $uid)) {
$newuser = new NobodyUser();
foreach ($newuser as $k => $v) {
$this->$k = $v;
}
return;
}
$this->username = pnUserGetVar('uname', $uid);
$this->fullname = pnUserGetVar('name', $uid);
$this->email = pnUserGetVar('email', $uid);
$this->canCreateAlbums = 0;
$this->uid = $uid;
/*
* XXX: this sets the admin-ness according to the user who's
* currently logged in -- NOT the $uid in question! This would
* be an issue, except that it just so happens that it doesn't
* affect anything we're doing in the app level code.
*/
$this->isAdmin = (pnSecAuthAction(0, "$name::", '::', ACCESS_ADMIN));
}
function loadByUserName($uname) {
list($dbconn) = pnDBGetConn();
$pntable = pnDBGetTables();
$userscolumn = &$pntable['users_column'];
$userstable = $pntable['users'];
/* Figure out the uid for this uname */
$query = "SELECT $userscolumn[uid] " .
"FROM $userstable " .
"WHERE $userscolumn[uname] = '" . pnVarPrepForStore($uname) ."'";
$result = $dbconn->Execute($query);
list($uid) = $result->fields;
$result->Close();
$this->loadByUid($uid);
}
}
?>
| mit |
dsandber/muhr_table | lib/muhr_table/version.rb | 42 | module MuhrTable
VERSION = "1.0.22"
end
| mit |
gaudeon/interstice | src/stage/objectives/kill_ships.js | 622 | import Objective from '../objective';
export default class KillShipsObjective extends Objective {
constructor (game, ships) {
super(game);
if (!Array.isArray(ships)) {
ships = [ships];
}
this.bots = _.filter(ships, ship => { return ship.alive; });
this.ships = ships;
}
isComplete () {
var all_dead = true;
for (var i = 0; i < this.ships.length; i++) {
if (this.ships[i].alive) {
all_dead = false;
break;
}
}
return all_dead;
}
};
| mit |
kavun/guvercinguitars | include/layout_minified.css | 1738 | body {
background-color:#948664;
font-size:16px;
font-family:Georgia, "Times New Roman", Times, serif;
color:#F4ECD3;
text-shadow:-1px -1px 5px #000;
padding:0;
margin:0;
}
a {
color:#fbfcef;
}
a:visited {
color:#eed69b;
}
a:hover {
color:#d7bc7b;
}
a:active {
color:#eed69b;
}
h1 {
font-size:11px;
text-transform:uppercase;
background-color:#948664;
padding:5px 15px;
margin:0
}
h2 {
font-size:24px;
font-weight:normal;
padding:5px 10px;
margin:0;
color:#F4ECD3;
}
h3 {
font-size:16px;
font-weight:bold;
font-variant:small-caps;
padding:5px 10px;
margin:0;
}
h3 img {
border:1px solid #e3d9ac;
width:170px;
height:auto;
}
img.download {
vertical-align:middle;
}
#container {
width:900px;
margin-bottom:10px;
margin:0 auto;
background-color:#948664;
}
#banner {
background-color:#948664;
text-align:right;
padding:0px;
margin:0px;
}
#banner img {
padding:0px 0px;
}
#content {
background-color:#3a2514;
padding:0px;
margin:0 200px;
text-align:center;
}
#content_left {
float:left;
width:250px;
height:250px;
}
#content_left img{
padding-top:5px;
padding-bottom:5px;
}
#content_right {
float:right;
width:250px;
height:250px;
}
#content li {
text-align:left;
}
div#content {
min-height:1100px;
height:expression(this.scrollHeight > 1100 ?"auto":"1100px");
}
p, pre {
padding:5px 10px;
margin:0px;
}
#left {
float:left;
width:200px;
height:1100px;
background-image:url(../img/left.gif);
text-align:center;
}
#left_center {
margin-top:30px;
}
#right {
float:right;
width:200px;
height:1100px;
background-image:url(../img/right.gif);
text-align:center;
}
#right_center {
margin-top:55px;
margin-left:9px;
}
#footer {
clear:both;
margin:0;
padding:0;
text-align:right;
}
| mit |
liligga/storegine | app/models/storegine/category.rb | 133 | module Storegine
class Category
include Mongoid::Document
field :title, type: String
has_many :products
end
end
| mit |
asadsahi/AspNetCoreSpa | src/Presentation/Web/ClientApp/src/app/components/privacy/index.ts | 37 | export * from './privacy.component';
| mit |
Subsets and Splits