code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
---
title: "Overview of Windows 8 Metro App Development"
date: 2011-12-10 00:00
---
My employer, the fabulous [500px](http://500px.com/), was invited by Microsoft to attend a three-day workshop on writing Metro-style apps for Windows 8. Since this is a new mobile development field, and mobile is kind of my thing, I jumped at the opportunity to get it straight from the horse's mouth.<!--more-->
## Metro
Windows 8 is still a Developer Preview. Practically, this means "pre-beta." It's very rough around the edges. This was apparent while using it for three days. Three days on a French keyboard. Three days where Alt-Tab didn't work correctly. But I digress. It looks promising and I think they'll have it cleared up in a year when it goes public. Besides, there are other reviews of the OS; this is about developing Metro apps, not about Windows 8 itself.
Windows 8 Metro app templates encourage consumption of media. It is strongly encouraged that Metro-style apps support horizontal scrolling with very specific margins; these margins are one of the defining, consistent features Microsoft has decided for Metro apps. However, any non-trivial form is going to need vertical scrolling, too. In fact, all the Microsoft controls examples use vertical scrolling. I can't help but feel that this is going to lead to a kind of schizophrenic experience; consuming media means scrolling horizontally while creating it means scrolling vertically.
Microsoft is expecting that 10.7" tablets with a widescreen aspect ratio, running 1366x768 resolution, are going to be the most common form factor for tablets running Metro. They've designed their interface with this in mind, and provide the "snap" feature (where two applications can be open on the screen at once) only to users with screens at least 1366 pixels wide.
## Architecture
Contracts are amazing. They're a great way for users to use different apps in a standard, consistent way. There has been a lot [written about how they work](http://www.pcworld.com/article/239893/windows_8_going_indepth_with_microsofts_massive_update_to_windows.html), and they're widely regard as a great feature. Integrating Search and Share contracts into your app is almost trivially easy. Kudos to Microsoft for doing something so great for users and making it so easy for developers.
Metro drops a lot of APIs from .Net. They introduced asynchronous variants of a lot of their APIs and have removed their synchronous counterparts. Microsoft did a lot to remove crud to create a great developer experience, which is why I'm so frustrated to learn they're keeping support for Visual Basic. It makes sense to keep Visual Basic around, since there are developers familiar with it, and Microsoft needs those developers making apps for their platform. You could, even, write Metro apps in JavaScript, or even all three at once. That's right, Microsoft has made it possible for your JavaScript code to interact with your C# and VB classes. Very cool.
In regards to multitasking, iOS 4 made it easier to, say, write a blogging platform (like [Storygram](http://itunes.apple.com/us/app/storygram/id482507340?mt=8&ls=1)) by letting you continue to upload photos, for instance, after the user closes your app. The time limit is something like 10 minutes. Microsoft has chosen to limit your app to 5 seconds after the user leaves before it's suspended. Literally - suspended - it's program counter stops incrementing. You're notified about pending suspension, but the intention is that you stop what you're doing, not finish a task.
There _are_ background tasks available for Metro apps, but they're limited to real-time communication apps: VoIP, Instant Messaging, and Mail. The intention is that these tasks run to update UI present on the Start and Lock screen, like how many unread emails you have. There are exceptions, apparently, but Microsoft appears to be dealing with these on a case-by-case basis. As a developer, I'd be reluctant to make something like an image-uploading app if Microsoft decided to reject it. I wish they had better app store guidelines, but they beta isn't coming out until (late) February 2012.
Background tasks are very cool, though, since they can operate even after your app has been completely terminated. These tasks are triggered after a certain time interval or a network event. It's a great compromise for user performance, constant connectivity, and battery life.
A huge benefit of writing a Metro-style app is that you get a lot for very little work. Implementing the Search Contract, which takes only a few dozen lines of code, gets your app included in the OS-wide search. How cool would it be if iOS users could search data within my apps using spotlight?
The templates Microsoft has provided in the developer preview of the tools are rich, multimedia-centric apps for which you only need to drop in content. However, this makes writing apps that don't conform to one of the pre-made templates not immediately apparent. Visual Studio 2011 is currently only a developer preview and I hope they'll add some new templates as they receive feedback from developers.

I see this problem with iOS on Stack Overflow where developers are so used to Xcode templates providing the basic structure of their app that the developers have no concept of what's actually going on. Many iOS devs can't construct a navigation-based app from an empty Xcode file. With these more complete templates in Visual Studio, I think the problem is going to be even worse. Since developers will be more relying heavily on these templates, when they try to develop innovative interfaces outside of what Microsoft has envisioned (something Microsoft is ostensibly encouraging, within their guidelines, of course), they're not going to know how. More templates with graduated levels of sophistication could definitely help.
Apple introduced an architecture of app launching very similar to Metro's in 2008. They kind of yelled at developers "make sure you remember the app's state somehow so it can be restored!" and developers kind of shrugged and did whatever they wanted to. Many apps didn't bother and presented the user with the start screen every time the app was opened. While Apple said "do this somehow", Microsoft is being much more accommodating and saying "here's how you do it." They've actually built a system (with code demos) to show you how to launch your app from any state it could be in - re-entering the foreground, from a share or search contract, a pinned secondary tile, or a toast notification. I really appreciate how much support they're giving developers in terms of direction on how to do this, leading to a better customer experience in the end.
Microsoft's Push Notification Service (WNS) is a HTTP-based, which is awesome. Apple introduce a TCP-based approach to push notifications that basically requires you to write a dedicated sever (again, somehow, Apple didn't specify how to do) to send your push notifications through their APNS. No one rolls their own APNS server because it's too hard and there's [Urban Airship](http://urbanairship.com/). However, Microsoft has provided a simple POST endpoint that specifies how to push to a user's Windows Live account, which is pretty freaking amazing. Of course, parsing the notifications on the client-side is XML-based, but you knew it would be, didn't you? A quick poll I conducted on twitter yielded that developers would prefer a JSON, TCP/IP-based protocol to XML, though .Net's XML libraries are pretty robust.
Metro is based on the HTML-like XAML and CSS, which means that it scales well across devices with varying screen resolutions, aspect ratios, and pixel densities. Metro's runtime handles loading files very similarly to iOS' "@2x" designation: rasterized assets can be named at 100%, 140%, and 180% variants in order to accomodate different screens. These variants are automatically selected by the runtime on the developer's behalf. It's heavily suggested that developers use CSS primitives, Scalable Vector Graphics (SVG), and font-based glyphs as UI components, since they scale perfectly. Microsoft is developing Wingdings 3 (that's right) to include glyphs for common elements like a back button.
## Tools
I really missed Visual Studio. I last used Visual Studio 2008 two years ago and I was a huge advocate of .Net, specifically Linq. Coming back to Visual Studio, it hasn't changed much, but it turns out that _I_ had changed. While there are a few key features in Visual Studio that I really miss in Xcode, like "Find all References" and chords for keyboard shortcuts, I'm so used to Xcode that it was a big change to go back to Visual Studio.
I could criticize XAML or the concept defining so much of your app logic in XML, but that's just the nature of the .Net platform. XAML is Microsoft's new Windows Forms, so it makes complete sense to use it to build Metro apps. But I don't like it. It's everything I hated about ASP.Net.
Writing interface code means a lot of back-and-forth between the XAML file and the codebehind; it feels like a compromise just so they could define the UI in XML. It feels very unnatural and cumbersome to me. However, an experienced .Net developer might feel right at home. To me, defining an animation in a series of Obj-C blocks is far easier than defining them in XML.

Designing an app is going to be really tricky. Designers could have access to the project in order to directly implement their designs in CSS (a good thing), but it's so tightly coupled to the codebehind that I think developers and designers might get in each others' ways.
## Interface
Coming from the Apple camp, I had to shed some of my preconceptions about how the interface should behave. Apple instills the idea that everything in your app should be intuitive and easily discoverable by the user. Microsoft has taken a slightly different approach; they dictate that in order to use a PC running Metro, you'll need to learn a few key gestures. After that, you're set. Swipe up from the bottom, to get a context menu. From the right to get to the "charms" (sharing, settings, seach). And so on.
I see the appeal of both approaches. Microsoft's solves the design problem of having no intuitive gestures that correspond to complex actions - and the gestures are consistent across all apps. Since Microsoft has a strangle hold on the Metro app market (and **will** be enforcing adherence to these conventions), I think it'll create a consistent user experience. This contrasts with the Android context menu button that few developers actually use, leading to its removal from new Android handsets
The kind of experience Microsoft is pushing in its templates isn't necessarily what you want. You're supposed to present the user with many items grouped into categories. Use Semantic Zoom (a neat concept) to zoom out to a higher level to navigate the vast sea of these items. When you tap any one item, you're taken to it's detail page. However, when you tap "back", you're taken to the summary of that item's category group, a level of navigation you passed over when you tapped the item. It's a little jarring at first, but I did get used to it.
## Conclusion
Microsoft is making a concerted effort to be inviting to developers so Metro users can get some great apps. This is really beneficial to Microsoft, but also to developers, particularly with the flexible store policies and gratuitous revenue sharing model. Microsoft has been inclusive (to a fault) towards many of their established technologies, including VB, C#, JavaScript, XAML, and HTML. They're trying hard to be inclusive to garner great app developers that will make their platform great.
I was admittedly intimidated by XAML because I'm used to defining my interfaces either graphically or completely in code, not in XML. Maybe an Android dev would be more comfortable designing Metro interfaces. I certainly feel comfortable in writing basic media-consumption applications, but not much more. If all Windows 8 developers are writing apps using the same layouts, then the only thing to differentiate apps will be the content they display. Maybe that will lead to the consistent user experience Microsoft wants, but it could lead to a lack of innovation with regards to the user interface.
Let's face it: Metro will be a success. As a company, Microsoft isn't going anywhere and they've learned lessons from Apple, Amazon, and Google on how to create an excellent app ecosystem. Personally, I'm too entrenched in the Obj-C/iOS ways to develop my own, personal Metro app. But based on what I've seen about Metro, I can see a lot of Enterprise ASP.Net corporate developers going home at night to tinker on their Metro apps, and who can argue against that?
<!-- more -->
|
yogoo/ashfurrow-blog
|
source/blog/2011-12-10-overview-of-windows-8-metro-app-development.markdown
|
Markdown
|
mit
| 13,019
|
export const addTestCase = function() {
return {
type: 'EDITOR/VARIABLE_ADD_CASE'
};
};
export const setProperty = function(index, name, value) {
return {
type: 'EDITOR/VARIABLE_SET_PROPERTY',
payload: {
index,
name,
value
}
};
};
export const addVariable = function(index) {
return {
type: 'EDITOR/VARIABLE_ADD_VARIABLE',
payload: {
index
}
};
};
export const setVariable = function(checkIndex, index, name, value, type) {
return {
type: 'EDITOR/VARIABLE_SET_VARIABLE',
payload: {
checkIndex,
index,
name,
value,
type
}
};
};
export default {
addTestCase,
addVariable,
setProperty,
setVariable,
};
|
vkaravir/js-parsons-editor
|
src/actions/editors/variable.js
|
JavaScript
|
mit
| 721
|
"""
WSGI config for asteria project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "asteria.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
tunegoon/asteria
|
asteria/wsgi.py
|
Python
|
mit
| 1,136
|
'use strict';
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
doneFilters: false
};
}
componentDidUpdate() {
if (this.props.filters && !this.state.doneFilters) {
$('.button-collapse').sideNav();
this.setState({ doneFilters: true });
}
}
render() {
var buttonClasses = 'button-collapse';
var filters = null;
if (!this.props.filters) {
buttonClasses += ' hidden';
} else {
filters = React.createElement(Filters, this.props);
}
return React.createElement(
'nav',
{ className: 'red', role: 'navigation' },
React.createElement(
'div',
{ className: 'nav-wrapper container' },
React.createElement(
'a',
{ id: 'logo-container', href: '#', className: 'brand-logo' },
'ExQuery'
),
React.createElement(
'div',
{ id: 'slide-out', className: 'side-nav' },
filters
),
React.createElement(
'a',
{
href: '#',
'data-activates': 'slide-out',
className: buttonClasses },
React.createElement('i', { className: 'mdi-navigation-menu' })
)
)
);
}
}
|
kar288/exquery
|
gettingstarted/static/build/header.js
|
JavaScript
|
mit
| 1,273
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_112-google-v7) on Mon Dec 18 13:35:09 PST 2017 -->
<title>ConfigurationV25</title>
<meta name="date" content="2017-12-18">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ConfigurationV25";
}
}
catch(err) {
}
//-->
var methods = {"i0":9,"i1":9};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/robolectric/android/Bootstrap.html" title="class in org.robolectric.android"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../org/robolectric/android/DeviceConfig.html" title="class in org.robolectric.android"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/robolectric/android/ConfigurationV25.html" target="_top">Frames</a></li>
<li><a href="ConfigurationV25.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.robolectric.android</div>
<h2 title="Class ConfigurationV25" class="title">Class ConfigurationV25</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.robolectric.android.ConfigurationV25</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">ConfigurationV25</span>
extends java.lang.Object</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../org/robolectric/android/ConfigurationV25.html#ConfigurationV25--">ConfigurationV25</a></span>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/android/ConfigurationV25.html#resourceQualifierString-android.content.res.Configuration-android.util.DisplayMetrics-">resourceQualifierString</a></span>(android.content.res.Configuration config,
android.util.DisplayMetrics displayMetrics)</code>
<div class="block">Returns a string representation of the configuration that can be parsed by build tools (like AAPT).</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/android/ConfigurationV25.html#resourceQualifierString-android.content.res.Configuration-android.util.DisplayMetrics-boolean-">resourceQualifierString</a></span>(android.content.res.Configuration config,
android.util.DisplayMetrics displayMetrics,
boolean includeSdk)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="ConfigurationV25--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>ConfigurationV25</h4>
<pre>public ConfigurationV25()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="resourceQualifierString-android.content.res.Configuration-android.util.DisplayMetrics-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>resourceQualifierString</h4>
<pre>public static java.lang.String resourceQualifierString(android.content.res.Configuration config,
android.util.DisplayMetrics displayMetrics)</pre>
<div class="block"><p>Returns a string representation of the configuration that can be parsed by build tools (like AAPT).</p></div>
</li>
</ul>
<a name="resourceQualifierString-android.content.res.Configuration-android.util.DisplayMetrics-boolean-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>resourceQualifierString</h4>
<pre>public static java.lang.String resourceQualifierString(android.content.res.Configuration config,
android.util.DisplayMetrics displayMetrics,
boolean includeSdk)</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><script type="text/javascript" src="../../../highlight.pack.js"></script>
<script type="text/javascript"><!--
hljs.initHighlightingOnLoad();
//--></script></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/robolectric/android/Bootstrap.html" title="class in org.robolectric.android"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../org/robolectric/android/DeviceConfig.html" title="class in org.robolectric.android"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/robolectric/android/ConfigurationV25.html" target="_top">Frames</a></li>
<li><a href="ConfigurationV25.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
robolectric/robolectric.github.io
|
javadoc/3.6/org/robolectric/android/ConfigurationV25.html
|
HTML
|
mit
| 10,972
|
package org.concurrent.queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 有界阻塞缓冲队列
* User: krisjin
* Date: 2016/2/16
*/
public class BoundedBufferQueue<E> {
private final ReentrantLock lock;
private final Condition notEmpty;
private final Condition notFull;
private Object[] buffer;
private int count;
private int putIndex;
private int takeIndex;
/**
* 初始化队列大小
*
* @param size
*/
public BoundedBufferQueue(int size) {
buffer = new Object[size];
lock = new ReentrantLock();
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
public void put(E e) throws InterruptedException {
lock.lock();
try {
while (count == buffer.length) {
notFull.await();
}
buffer[putIndex] = e;
if (++putIndex == buffer.length) {
putIndex = 0;
}
count++;
notEmpty.signal();
} finally {
lock.unlock();
}
}
public E take() throws InterruptedException {
lock.lock();
try {
while (count == 0) {
notEmpty.await();
}
E e = (E) buffer[takeIndex];
count--;
if (++takeIndex == buffer.length) {
takeIndex = 0;
}
notFull.signal();
return e;
} finally {
lock.unlock();
}
}
}
|
zoopaper/concurrent-programming
|
src/main/java/org/concurrent/queue/BoundedBufferQueue.java
|
Java
|
mit
| 1,591
|
@main("Ruby Programming Language"){
<div class="row">
<div class="col-sm-8" style="padding-top: 7%;">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi varius, libero molestie accumsan tempor, tellus ipsum pretium nulla, sit amet faucibus dolor nunc at velit.
Maecenas ornare ut magna id pretium. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent a nisi ante. Proin aliquet erat nisi. Aenean mauris arcu, commodo eget erat sed, lobortis rhoncus tortor.
Nulla dictum arcu sit amet facilisis varius. Donec venenatis maximus velit rhoncus euismod. Maecenas blandit facilisis sem, nec lobortis nunc dignissim nec.
</p>
<br>
<p>
Sed elementum varius nibh fermentum iaculis. Ut sit amet quam a tortor tempor ullamcorper et in nisl. Aenean sodales est eros, id dictum mi bibendum ac. Integer non ex a elit tempus interdum a eget massa. Etiam sagittis diam aliquet facilisis aliquam. Nunc a malesuada leo.
Maecenas eu est iaculis, luctus mi in, fringilla nunc. Sed tincidunt vitae lacus quis ornare. Sed convallis tortor vel tellus tincidunt, vel pulvinar tellus elementum. Nunc sit amet libero at nibh sollicitudin vehicula. Nam accumsan volutpat magna non ornare. Maecenas mattis, leo id pretium posuere, orci lacus tristique diam, id fringilla mauris urna non turpis. Morbi tincidunt augue id scelerisque sagittis.
Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</p>
<br>
<p>
Aliquam ante ipsum, malesuada et risus quis, ultrices euismod tellus. Nam vel aliquet mauris, aliquet aliquet mauris. Ut eget diam eget justo lacinia rhoncus id eget ex.
Sed dapibus eros sed tempor convallis. Praesent in turpis sed felis luctus eleifend eget egestas purus. Aenean nec libero et sapien rutrum ultrices eu vel mauris. Suspendisse a bibendum eros.
Vivamus sed purus enim. Morbi varius porta sem in pretium. Quisque non porta nibh. Cras ac nisi eros. Fusce nibh dolor, mollis in sollicitudin finibus, ultricies quis tortor.
Vivamus sollicitudin, leo id consectetur scelerisque, justo magna sollicitudin turpis, vel tristique justo lectus sed risus. Integer scelerisque orci nec ex euismod, a cursus elit consequat.
</p>
</div>
<div class="col-sm-4"><img class="img-responsive" src="@routes.Assets.versioned("img/ruby.png")" style="padding-top: 30%;" class="img-rounded" alt="Cinque Terre" width="304" height="236"></div>
</div>
}
|
cwrobertson/WebApp
|
app/views/RubyPage.scala.html
|
HTML
|
mit
| 2,594
|
<?php
class DataTest extends \PHPUnit_Framework_TestCase
{
public function testCanCreateInstance()
{
$this->assertInstanceOf(
'\Snscripts\HtmlHelper\Services\Basic\Data',
new \Snscripts\HtmlHelper\Services\Basic\Data
);
}
public function testGetValueReturnsNullWhenInvalidNamePassed()
{
$FormData = new \Snscripts\HtmlHelper\Services\Basic\Data;
$this->assertNull(
$FormData->getValue(123)
);
$this->assertNull(
$FormData->getValue([])
);
$this->assertNull(
$FormData->getValue(new \stdClass)
);
}
public function testGetValueReturnsCorrectDataFromPostData()
{
$FormData = new \Snscripts\HtmlHelper\Services\Basic\Data;
$_POST = [
'User' => [
'email' => 'john@example.com'
],
'agreed_terms' => 'yes'
];
$this->assertSame(
'john@example.com',
$FormData->getValue('User.email')
);
$this->assertSame(
[
'email' => 'john@example.com'
],
$FormData->getValue('User')
);
$this->assertSame(
'yes',
$FormData->getValue('agreed_terms')
);
}
}
|
snscripts/html-helper
|
Tests/Services/Basic/DataTest.php
|
PHP
|
mit
| 1,334
|
// Routes everything '/helper' related.
exports.index = function(app) {
app.get('/datasets', function(req, res) {
res.render('misc/error', {
'info': 'Work in Progress'
});
});
}
|
skepticfx/domstorm
|
controllers/datasets.js
|
JavaScript
|
mit
| 197
|
var core = require("./core").dom.level2.core,
events = require("./core").dom.level2.events,
applyDocumentFeatures = require('../browser/documentfeatures').applyDocumentFeatures,
URL = require("url"),
Path = require('path'),
fs = require("fs"),
http = require('http'),
https = require('https');
// modify cloned instance for more info check: https://github.com/tmpvar/jsdom/issues/325
core = Object.create(core);
// Setup the javascript language processor
core.languageProcessors = {
javascript : require("./languages/javascript").javascript
};
core.resourceLoader = {
load: function(element, href, callback) {
var ownerImplementation = element._ownerDocument.implementation;
if (ownerImplementation.hasFeature('FetchExternalResources', element.tagName.toLowerCase())) {
var full = this.resolve(element._ownerDocument, href);
var url = URL.parse(full);
if (ownerImplementation.hasFeature('SkipExternalResources', full)) {
return false;
}
if (url.hostname) {
this.download(url, this.baseUrl(element._ownerDocument), this.enqueue(element, callback, full));
}
else {
this.readFile(url.pathname, this.enqueue(element, callback, full));
}
}
},
enqueue: function(element, callback, filename) {
var loader = this,
doc = element.nodeType === core.Node.DOCUMENT_NODE ?
element :
element._ownerDocument;
if (!doc._queue) {
return function() {};
}
return doc._queue.push(function(err, data) {
var ev = doc.createEvent('HTMLEvents');
if (!err) {
try {
callback.call(element, data, filename || doc.URL);
ev.initEvent('load', false, false);
}
catch(e) {
err = e;
}
}
if (err) {
ev.initEvent('error', false, false);
ev.error = err;
}
element.dispatchEvent(ev);
});
},
baseUrl: function(document) {
var baseElements = document.getElementsByTagName('base'),
baseUrl = document.URL;
if (baseElements.length > 0) {
baseUrl = baseElements.item(0).href || baseUrl;
}
return baseUrl;
},
resolve: function(document, href) {
if (href.match(/^\w+:\/\//)) {
return href;
}
var baseUrl = this.baseUrl(document);
// See RFC 2396 section 3 for this weirdness. URLs without protocol
// have their protocol default to the current one.
// http://www.ietf.org/rfc/rfc2396.txt
if (href.match(/^\/\//)) {
return baseUrl ? baseUrl.match(/^(\w+:)\/\//)[1] + href : null;
} else if (!href.match(/^\/[^\/]/)) {
href = href.replace(/^\//, "");
}
return URL.resolve(baseUrl, href);
},
download: function(url, referrer, callback) {
var path = url.pathname + (url.search || ''),
options = {'method': 'GET', 'host': url.hostname, 'path': path},
request;
if (url.protocol === 'https:') {
options.port = url.port || 443;
request = https.request(options);
} else {
options.port = url.port || 80;
request = http.request(options);
}
// set header.
if (referrer) {
request.setHeader('Referer', referrer);
}
request.on('response', function (response) {
var data = '';
function success () {
if ([301, 302, 303, 307].indexOf(response.statusCode) > -1) {
var redirect = URL.resolve(url, response.headers["location"]);
core.resourceLoader.download(URL.parse(redirect), referrer, callback);
} else {
callback(null, data);
}
}
response.setEncoding('utf8');
response.on('data', function (chunk) {
data += chunk.toString();
});
response.on('end', function() {
// According to node docs, 'close' can fire after 'end', but not
// vice versa. Remove 'close' listener so we don't call success twice.
response.removeAllListeners('close');
success();
});
response.on('close', function (err) {
if (err) {
callback(err);
} else {
success();
}
});
});
request.on('error', callback);
request.end();
},
readFile: function(url, callback) {
fs.readFile(url.replace(/^file:\/\//, "").replace(/^\/([a-z]):\//i, '$1:/').replace(/%20/g, ' '), 'utf8', callback);
}
};
function define(elementClass, def) {
var tagName = def.tagName,
tagNames = def.tagNames || (tagName? [tagName] : []),
parentClass = def.parentClass || core.HTMLElement,
attrs = def.attributes || [],
proto = def.proto || {};
var elem = core[elementClass] = function(document, name) {
parentClass.call(this, document, name || tagName.toUpperCase());
if (elem._init) {
elem._init.call(this);
}
};
elem._init = def.init;
elem.prototype = proto;
elem.prototype.__proto__ = parentClass.prototype;
attrs.forEach(function(n) {
var prop = n.prop || n,
attr = n.attr || prop.toLowerCase();
if (!n.prop || n.read !== false) {
elem.prototype.__defineGetter__(prop, function() {
var s = this.getAttribute(attr);
if (n.type && n.type === 'boolean') {
return !!s;
}
if (n.type && n.type === 'long') {
return +s;
}
if (typeof n === 'object' && n.normalize) { // see GH-491
return n.normalize(s);
}
return s;
});
}
if (!n.prop || n.write !== false) {
elem.prototype.__defineSetter__(prop, function(val) {
if (!val) {
this.removeAttribute(attr);
}
else {
var s = val.toString();
if (n.normalize) {
s = n.normalize(s);
}
this.setAttribute(attr, s);
}
});
}
});
tagNames.forEach(function(tag) {
core.Document.prototype._elementBuilders[tag.toLowerCase()] = function(doc, s) {
var el = new elem(doc, s);
return el;
};
});
}
core.HTMLCollection = function HTMLCollection(element, query) {
core.NodeList.call(this, element, query);
};
core.HTMLCollection.prototype = {
namedItem : function(name) {
var results = this.toArray(),
l = results.length,
node,
matchingName = null;
for (var i=0; i<l; i++) {
node = results[i];
if (node.getAttribute('id') === name) {
return node;
} else if (node.getAttribute('name') === name) {
matchingName = node;
}
}
return matchingName;
},
toString: function() {
return '[ jsdom HTMLCollection ]: contains ' + this.length + ' items';
}
};
core.HTMLCollection.prototype.__proto__ = core.NodeList.prototype;
core.HTMLOptionsCollection = core.HTMLCollection;
function closest(e, tagName) {
tagName = tagName.toUpperCase();
while (e) {
if (e.nodeName.toUpperCase() === tagName ||
(e.tagName && e.tagName.toUpperCase() === tagName))
{
return e;
}
e = e._parentNode;
}
return null;
}
function descendants(e, tagName, recursive) {
var owner = recursive ? e._ownerDocument || e : e;
return new core.HTMLCollection(owner, core.mapper(e, function(n) {
return n.nodeName === tagName && typeof n._publicId == 'undefined';
}, recursive));
}
function firstChild(e, tagName) {
if (!e) {
return null;
}
var c = descendants(e, tagName, false);
return c.length > 0 ? c[0] : null;
}
function ResourceQueue(paused) {
this.paused = !!paused;
}
ResourceQueue.prototype = {
push: function(callback) {
var q = this;
var item = {
prev: q.tail,
check: function() {
if (!q.paused && !this.prev && this.fired){
callback(this.err, this.data);
if (this.next) {
this.next.prev = null;
this.next.check();
}else{//q.tail===this
q.tail = null;
}
}
}
};
if (q.tail) {
q.tail.next = item;
}
q.tail = item;
return function(err, data) {
item.fired = 1;
item.err = err;
item.data = data;
item.check();
};
},
resume: function() {
if(!this.paused){
return;
}
this.paused = false;
var head = this.tail;
while(head && head.prev){
head = head.prev;
}
if(head){
head.check();
}
}
};
core.HTMLDocument = function HTMLDocument(options) {
options = options || {};
if (!options.contentType) {
options.contentType = 'text/html';
}
core.Document.call(this, options);
this._referrer = options.referrer;
this._cookie = options.cookie;
this._URL = options.url || '/';
this._documentRoot = options.documentRoot || Path.dirname(this._URL);
this._queue = new ResourceQueue(options.deferClose);
this.readyState = 'loading';
// Add level2 features
this.implementation.addFeature('core' , '2.0');
this.implementation.addFeature('html' , '2.0');
this.implementation.addFeature('xhtml' , '2.0');
this.implementation.addFeature('xml' , '2.0');
};
core.HTMLDocument.prototype = {
_referrer : "",
get referrer() {
return this._referrer || '';
},
get domain() {
return "";
},
_URL : "",
get URL() {
return this._URL;
},
get images() {
return this.getElementsByTagName('IMG');
},
get applets() {
return new core.HTMLCollection(this, core.mapper(this, function(el) {
if (el && el.tagName) {
var upper = el.tagName.toUpperCase();
if (upper === "APPLET") {
return true;
} else if (upper === "OBJECT" &&
el.getElementsByTagName('APPLET').length > 0)
{
return true;
}
}
}));
},
get links() {
return new core.HTMLCollection(this, core.mapper(this, function(el) {
if (el && el.tagName) {
var upper = el.tagName.toUpperCase();
if (upper === "AREA" || (upper === "A" && el.href)) {
return true;
}
}
}));
},
get forms() {
return this.getElementsByTagName('FORM');
},
get anchors() {
return this.getElementsByTagName('A');
},
open : function() {
this._childNodes = [];
this._documentElement = null;
this._modified();
},
close : function() {
this._queue.resume();
// Set the readyState to 'complete' once all resources are loaded.
// As a side-effect the document's load-event will be dispatched.
core.resourceLoader.enqueue(this, function() {
this.readyState = 'complete';
var ev = this.createEvent('HTMLEvents');
ev.initEvent('DOMContentLoaded', false, false);
this.dispatchEvent(ev);
})(null, true);
},
write : function(text) {
if (this.readyState === "loading") {
// During page loading, document.write appends to the current element
// Find the last child that has been added to the document.
var node = this;
while (node.lastChild && node.lastChild.nodeType === this.ELEMENT_NODE) {
node = node.lastChild;
}
node.innerHTML = text;
} else {
this.innerHTML = text;
}
},
writeln : function(text) {
this.write(text + '\n');
},
getElementsByName : function(elementName) {
return new core.HTMLCollection(this, core.mapper(this, function(el) {
return (el.getAttribute && el.getAttribute("name") === elementName);
}));
},
get title() {
var head = this.head,
title = head ? firstChild(head, 'TITLE') : null;
return title ? title.textContent : '';
},
set title(val) {
var title = firstChild(this.head, 'TITLE');
if (!title) {
title = this.createElement('TITLE');
var head = this.head;
if (!head) {
head = this.createElement('HEAD');
this.documentElement.insertBefore(head, this.documentElement.firstChild);
}
head.appendChild(title);
}
title.textContent = val;
},
get head() {
return firstChild(this.documentElement, 'HEAD');
},
set head() { /* noop */ },
get body() {
var body = firstChild(this.documentElement, 'BODY');
if (!body) {
body = firstChild(this.documentElement, 'FRAMESET');
}
return body;
},
get documentElement() {
if (!this._documentElement) {
this._documentElement = firstChild(this, 'HTML');
}
return this._documentElement;
},
_cookie : "",
get cookie() { return this._cookie || ''; },
set cookie(val) { this._cookie = val; }
};
core.HTMLDocument.prototype.__proto__ = core.Document.prototype;
define('HTMLElement', {
parentClass: core.Element,
proto : {
// Add default event behavior (click link to navigate, click button to submit
// form, etc). We start by wrapping dispatchEvent so we can forward events to
// the element's _eventDefault function (only events that did not incur
// preventDefault).
dispatchEvent : function (event) {
var outcome = core.Node.prototype.dispatchEvent.call(this, event)
if (!event._preventDefault &&
event.target._eventDefaults[event.type] &&
typeof event.target._eventDefaults[event.type] === 'function')
{
event.target._eventDefaults[event.type](event)
}
return outcome;
},
_eventDefaults : {}
},
attributes: [
'id',
'title',
'lang',
'dir',
{prop: 'className', attr: 'class', normalize: function(s) { return s || ''; }}
]
});
core.Document.prototype._defaultElementBuilder = function(document, tagName) {
return new core.HTMLElement(document, tagName);
};
//http://www.w3.org/TR/html5/forms.html#category-listed
var listedElements = /button|fieldset|input|keygen|object|select|textarea/i;
define('HTMLFormElement', {
tagName: 'FORM',
proto: {
get elements() {
return new core.HTMLCollection(this._ownerDocument, core.mapper(this, function(e) {
return listedElements.test(e.nodeName) ; // TODO exclude <input type="image">
}));
},
get length() {
return this.elements.length;
},
_dispatchSubmitEvent: function() {
var ev = this._ownerDocument.createEvent('HTMLEvents');
ev.initEvent('submit', true, true);
if (!this.dispatchEvent(ev)) {
this.submit();
};
},
submit: function() {
},
reset: function() {
this.elements.toArray().forEach(function(el) {
el.value = el.defaultValue;
});
}
},
attributes: [
'name',
{prop: 'acceptCharset', attr: 'accept-charset'},
'action',
'enctype',
'method',
'target'
]
});
define('HTMLLinkElement', {
tagName: 'LINK',
proto: {
get href() {
return core.resourceLoader.resolve(this._ownerDocument, this.getAttribute('href'));
}
},
attributes: [
{prop: 'disabled', type: 'boolean'},
'charset',
'href',
'hreflang',
'media',
'rel',
'rev',
'target',
'type'
]
});
define('HTMLMetaElement', {
tagName: 'META',
attributes: [
'content',
{prop: 'httpEquiv', attr: 'http-equiv'},
'name',
'scheme'
]
});
define('HTMLHtmlElement', {
tagName: 'HTML',
attributes: [
'version'
]
});
define('HTMLHeadElement', {
tagName: 'HEAD',
attributes: [
'profile'
]
});
define('HTMLTitleElement', {
tagName: 'TITLE',
proto: {
get text() {
return this.innerHTML;
},
set text(s) {
this.innerHTML = s;
}
}
});
define('HTMLBaseElement', {
tagName: 'BASE',
attributes: [
'href',
'target'
]
});
//**Deprecated**
define('HTMLIsIndexElement', {
tagName : 'ISINDEX',
parentClass : core.Element,
proto : {
get form() {
return closest(this, 'FORM');
}
},
attributes : [
'prompt'
]
});
define('HTMLStyleElement', {
tagName: 'STYLE',
attributes: [
{prop: 'disabled', type: 'boolean'},
'media',
'type',
]
});
define('HTMLBodyElement', {
proto: (function() {
var proto = {};
// The body element's "traditional" event handlers are proxied to the
// window object.
// See: http://dev.w3.org/html5/spec/Overview.html#the-body-element
['onafterprint', 'onbeforeprint', 'onbeforeunload', 'onblur', 'onerror',
'onfocus', 'onhashchange', 'onload', 'onmessage', 'onoffline', 'ononline',
'onpagehide', 'onpageshow', 'onpopstate', 'onresize', 'onscroll',
'onstorage', 'onunload'].forEach(function (name) {
proto.__defineSetter__(name, function (handler) {
this._ownerDocument.parentWindow[name] = handler;
});
proto.__defineGetter__(name, function () {
return this._ownerDocument.parentWindow[name];
});
});
return proto;
})(),
tagName: 'BODY',
attributes: [
'aLink',
'background',
'bgColor',
'link',
'text',
'vLink'
]
});
define('HTMLSelectElement', {
tagName: 'SELECT',
proto: {
get options() {
return new core.HTMLOptionsCollection(this, core.mapper(this, function(n) {
return n.nodeName === 'OPTION';
}));
},
get length() {
return this.options.length;
},
get selectedIndex() {
return this.options.toArray().reduceRight(function(prev, option, i) {
return option.selected ? i : prev;
}, -1);
},
set selectedIndex(index) {
this.options.toArray().forEach(function(option, i) {
option.selected = i === index;
});
},
get value() {
var i = this.selectedIndex;
if (this.options.length && (i === -1)) {
i = 0;
}
if (i === -1) {
return '';
}
return this.options[i].value;
},
set value(val) {
var self = this;
this.options.toArray().forEach(function(option) {
if (option.value === val) {
option.selected = true;
} else {
if (!self.hasAttribute('multiple')) {
// Remove the selected bit from all other options in this group
// if the multiple attr is not present on the select
option.selected = false;
}
}
});
},
get form() {
return closest(this, 'FORM');
},
get type() {
return this.multiple ? 'select-multiple' : 'select-one';
},
add: function(opt, before) {
if (before) {
this.insertBefore(opt, before);
}
else {
this.appendChild(opt);
}
},
remove: function(index) {
var opts = this.options.toArray();
if (index >= 0 && index < opts.length) {
var el = opts[index];
el._parentNode.removeChild(el);
}
},
blur : function() {
this._ownerDocument.activeElement = this._ownerDocument.body;
},
focus : function() {
this._ownerDocument.activeElement = this;
}
},
attributes: [
{prop: 'disabled', type: 'boolean'},
{prop: 'multiple', type: 'boolean'},
'name',
{prop: 'size', type: 'long'},
{prop: 'tabIndex', type: 'long'},
]
});
define('HTMLOptGroupElement', {
tagName: 'OPTGROUP',
attributes: [
{prop: 'disabled', type: 'boolean'},
'label'
]
});
define('HTMLOptionElement', {
tagName: 'OPTION',
proto: {
_attrModified: function(name, value) {
if (name === 'selected') {
this.selected = this.defaultSelected;
}
core.HTMLElement.prototype._attrModified.call(this, arguments);
},
get form() {
return closest(this, 'FORM');
},
get defaultSelected() {
return !!this.getAttribute('selected');
},
set defaultSelected(s) {
if (s) this.setAttribute('selected', 'selected');
else this.removeAttribute('selected');
},
get text() {
return this.innerHTML;
},
get value() {
return (this.hasAttribute('value')) ? this.getAttribute('value') : this.innerHTML;
},
set value(val) {
this.setAttribute('value', val);
},
get index() {
return closest(this, 'SELECT').options.toArray().indexOf(this);
},
get selected() {
if (this._selected === undefined) {
this._selected = this.defaultSelected;
}
return this._selected;
},
set selected(s) {
// TODO: The 'selected' content attribute is the initial value of the
// IDL attribute, but the IDL attribute should not relfect the content
this._selected = !!s;
if (s) {
//Remove the selected bit from all other options in this select
var select = this._parentNode;
if (!select) return;
if (select.nodeName !== 'SELECT') {
select = select._parentNode;
if (!select) return;
if (select.nodeName !== 'SELECT') return;
}
if (!select.multiple) {
var o = select.options;
for (var i = 0; i < o.length; i++) {
if (o[i] !== this) {
o[i].selected = false;
}
}
}
}
}
},
attributes: [
{prop: 'disabled', type: 'boolean'},
'label'
]
});
define('HTMLInputElement', {
tagName: 'INPUT',
proto: {
_initDefaultValue: function() {
if (this._defaultValue === undefined) {
var attr = this.getAttributeNode('value');
this._defaultValue = attr ? attr.value : null;
}
return this._defaultValue;
},
_initDefaultChecked: function() {
if (this._defaultChecked === undefined) {
this._defaultChecked = !!this.getAttribute('checked');
}
return this._defaultChecked;
},
get form() {
return closest(this, 'FORM');
},
get defaultValue() {
return this._initDefaultValue();
},
get defaultChecked() {
return this._initDefaultChecked();
},
get checked() {
return !!this._attributes.getNamedItem('checked');
},
set checked(checked) {
this._initDefaultChecked();
if (checked) {
this.setAttribute('checked', 'checked');
} else {
this.removeAttribute('checked');
}
},
get value() {
return this.getAttribute('value');
},
set value(val) {
this._initDefaultValue();
if (val === null) {
this.removeAttribute('value');
}
else {
this.setAttribute('value', val);
}
},
blur : function() {
this._ownerDocument.activeElement = this._ownerDocument.body;
},
focus : function() {
this._ownerDocument.activeElement = this;
},
select: function() {
},
click: function() {
if (this.type === 'checkbox' || this.type === 'radio') {
this.checked = !this.checked;
}
else if (this.type === 'submit') {
var form = this.form;
if (form) {
form._dispatchSubmitEvent();
}
}
}
},
attributes: [
'accept',
'accessKey',
'align',
'alt',
{prop: 'disabled', type: 'boolean'},
{prop: 'maxLength', type: 'long'},
'name',
{prop: 'readOnly', type: 'boolean'},
{prop: 'size', type: 'long'},
'src',
{prop: 'tabIndex', type: 'long'},
{prop: 'type', normalize: function(val) {
return val ? val.toLowerCase() : 'text';
}},
'useMap'
]
});
define('HTMLTextAreaElement', {
tagName: 'TEXTAREA',
proto: {
_initDefaultValue: function() {
if (this._defaultValue === undefined) {
this._defaultValue = this.textContent;
}
return this._defaultValue;
},
get form() {
return closest(this, 'FORM');
},
get defaultValue() {
return this._initDefaultValue();
},
get value() {
return this.textContent;
},
set value(val) {
this._initDefaultValue();
this.textContent = val;
},
get type() {
return 'textarea';
},
blur : function() {
this._ownerDocument.activeElement = this._ownerDocument.body;
},
focus : function() {
this._ownerDocument.activeElement = this;
},
select: function() {
}
},
attributes: [
'accessKey',
{prop: 'cols', type: 'long'},
{prop: 'disabled', type: 'boolean'},
{prop: 'maxLength', type: 'long'},
'name',
{prop: 'readOnly', type: 'boolean'},
{prop: 'rows', type: 'long'},
{prop: 'tabIndex', type: 'long'}
]
});
define('HTMLButtonElement', {
tagName: 'BUTTON',
proto: {
get form() {
return closest(this, 'FORM');
},
focus : function() {
this._ownerDocument.activeElement = this;
},
blur : function() {
this._ownerDocument.activeElement = this._ownerDocument.body;
}
},
attributes: [
'accessKey',
{prop: 'disabled', type: 'boolean'},
'name',
{prop: 'tabIndex', type: 'long'},
'type',
'value'
]
});
define('HTMLLabelElement', {
tagName: 'LABEL',
proto: {
get form() {
return closest(this, 'FORM');
}
},
attributes: [
'accessKey',
{prop: 'htmlFor', attr: 'for'}
]
});
define('HTMLFieldSetElement', {
tagName: 'FIELDSET',
proto: {
get form() {
return closest(this, 'FORM');
}
}
});
define('HTMLLegendElement', {
tagName: 'LEGEND',
proto: {
get form() {
return closest(this, 'FORM');
}
},
attributes: [
'accessKey',
'align'
]
});
define('HTMLUListElement', {
tagName: 'UL',
attributes: [
{prop: 'compact', type: 'boolean'},
'type'
]
});
define('HTMLOListElement', {
tagName: 'OL',
attributes: [
{prop: 'compact', type: 'boolean'},
{prop: 'start', type: 'long'},
'type'
]
});
define('HTMLDListElement', {
tagName: 'DL',
attributes: [
{prop: 'compact', type: 'boolean'}
]
});
define('HTMLDirectoryElement', {
tagName: 'DIR',
attributes: [
{prop: 'compact', type: 'boolean'}
]
});
define('HTMLMenuElement', {
tagName: 'MENU',
attributes: [
{prop: 'compact', type: 'boolean'}
]
});
define('HTMLLIElement', {
tagName: 'LI',
attributes: [
'type',
{prop: 'value', type: 'long'}
]
});
define('HTMLDivElement', {
tagName: 'DIV',
attributes: [
'align'
]
});
define('HTMLParagraphElement', {
tagName: 'P',
attributes: [
'align'
]
});
define('HTMLHeadingElement', {
tagNames: ['H1','H2','H3','H4','H5','H6'],
attributes: [
'align'
]
});
define('HTMLQuoteElement', {
tagNames: ['Q','BLOCKQUOTE'],
attributes: [
'cite'
]
});
define('HTMLPreElement', {
tagName: 'PRE',
attributes: [
{prop: 'width', type: 'long'}
]
});
define('HTMLBRElement', {
tagName: 'BR',
attributes: [
'clear'
]
});
define('HTMLBaseFontElement', {
tagName: 'BASEFONT',
attributes: [
'color',
'face',
{prop: 'size', type: 'long'}
]
});
define('HTMLFontElement', {
tagName: 'FONT',
attributes: [
'color',
'face',
'size'
]
});
define('HTMLHRElement', {
tagName: 'HR',
attributes: [
'align',
{prop: 'noShade', type: 'boolean'},
'size',
'width'
]
});
define('HTMLModElement', {
tagNames: ['INS', 'DEL'],
attributes: [
'cite',
'dateTime'
]
});
define('HTMLAnchorElement', {
tagName: 'A',
proto: {
blur : function() {
this._ownerDocument.activeElement = this._ownerDocument.body;
},
focus : function() {
this._ownerDocument.activeElement = this;
},
get href() {
return core.resourceLoader.resolve(this._ownerDocument, this.getAttribute('href'));
},
get hostname() {
return URL.parse(this.href).hostname;
},
get pathname() {
return URL.parse(this.href).pathname;
}
},
attributes: [
'accessKey',
'charset',
'coords',
{prop: 'href', type: 'string', read: false},
'hreflang',
'name',
'rel',
'rev',
'shape',
{prop: 'tabIndex', type: 'long'},
'target',
'type'
]
});
define('HTMLImageElement', {
tagName: 'IMG',
attributes: [
'name',
'align',
'alt',
'border',
{prop: 'height', type: 'long'},
{prop: 'hspace', type: 'long'},
{prop: 'isMap', type: 'boolean'},
'longDesc',
'src',
'useMap',
{prop: 'vspace', type: 'long'},
{prop: 'width', type: 'long'}
]
});
define('HTMLObjectElement', {
tagName: 'OBJECT',
proto: {
get form() {
return closest(this, 'FORM');
},
get contentDocument() {
return null;
}
},
attributes: [
'code',
'align',
'archive',
'border',
'codeBase',
'codeType',
'data',
{prop: 'declare', type: 'boolean'},
{prop: 'height', type: 'long'},
{prop: 'hspace', type: 'long'},
'name',
'standby',
{prop: 'tabIndex', type: 'long'},
'type',
'useMap',
{prop: 'vspace', type: 'long'},
{prop: 'width', type: 'long'}
]
});
define('HTMLParamElement', {
tagName: 'PARAM',
attributes: [
'name',
'type',
'value',
'valueType'
]
});
define('HTMLAppletElement', {
tagName: 'APPLET',
attributes: [
'align',
'alt',
'archive',
'code',
'codeBase',
'height',
{prop: 'hspace', type: 'long'},
'name',
'object',
{prop: 'vspace', type: 'long'},
'width'
]
});
define('HTMLMapElement', {
tagName: 'MAP',
proto: {
get areas() {
return this.getElementsByTagName("AREA");
}
},
attributes: [
'name'
]
});
define('HTMLAreaElement', {
tagName: 'AREA',
attributes: [
'accessKey',
'alt',
'coords',
'href',
{prop: 'noHref', type: 'boolean'},
'shape',
{prop: 'tabIndex', type: 'long'},
'target'
]
});
define('HTMLScriptElement', {
tagName: 'SCRIPT',
init: function() {
this.addEventListener('DOMNodeInsertedIntoDocument', function() {
if (this.src) {
core.resourceLoader.load(this, this.src, this._eval);
}
else {
var src = this.sourceLocation || {},
filename = src.file || this._ownerDocument.URL;
if (src) {
filename += ':' + src.line + ':' + src.col;
}
filename += '<script>';
core.resourceLoader.enqueue(this, this._eval, filename)(null, this.text);
}
});
},
proto: {
_eval: function(text, filename) {
if (this._ownerDocument.implementation.hasFeature("ProcessExternalResources", "script") &&
this.language &&
core.languageProcessors[this.language])
{
core.languageProcessors[this.language](this, text, filename);
}
},
get language() {
var type = this.type || "text/javascript";
return type.split("/").pop().toLowerCase();
},
get text() {
var i=0, children = this.childNodes, l = children.length, ret = [];
for (i; i<l; i++) {
ret.push(children.item(i).nodeValue);
}
return ret.join("");
},
set text(text) {
while (this.childNodes.length) {
this.removeChild(this.childNodes[0]);
}
this.appendChild(this._ownerDocument.createTextNode(text));
}
},
attributes : [
{prop: 'defer', 'type': 'boolean'},
'htmlFor',
'event',
'charset',
'type',
'src'
]
})
define('HTMLTableElement', {
tagName: 'TABLE',
proto: {
get caption() {
return firstChild(this, 'CAPTION');
},
get tHead() {
return firstChild(this, 'THEAD');
},
get tFoot() {
return firstChild(this, 'TFOOT');
},
get rows() {
if (!this._rows) {
var table = this;
this._rows = new core.HTMLCollection(this._ownerDocument, function() {
var sections = [table.tHead].concat(table.tBodies.toArray(), table.tFoot).filter(function(s) { return !!s });
if (sections.length === 0) {
return core.mapDOMNodes(table, false, function(el) {
return el.tagName === 'TR';
});
}
return sections.reduce(function(prev, s) {
return prev.concat(s.rows.toArray());
}, []);
});
}
return this._rows;
},
get tBodies() {
if (!this._tBodies) {
this._tBodies = descendants(this, 'TBODY', false);
}
return this._tBodies;
},
createTHead: function() {
var el = this.tHead;
if (!el) {
el = this._ownerDocument.createElement('THEAD');
this.appendChild(el);
}
return el;
},
deleteTHead: function() {
var el = this.tHead;
if (el) {
el._parentNode.removeChild(el);
}
},
createTFoot: function() {
var el = this.tFoot;
if (!el) {
el = this._ownerDocument.createElement('TFOOT');
this.appendChild(el);
}
return el;
},
deleteTFoot: function() {
var el = this.tFoot;
if (el) {
el._parentNode.removeChild(el);
}
},
createCaption: function() {
var el = this.caption;
if (!el) {
el = this._ownerDocument.createElement('CAPTION');
this.appendChild(el);
}
return el;
},
deleteCaption: function() {
var c = this.caption;
if (c) {
c._parentNode.removeChild(c);
}
},
insertRow: function(index) {
var tr = this._ownerDocument.createElement('TR');
if (this.childNodes.length === 0) {
this.appendChild(this._ownerDocument.createElement('TBODY'));
}
var rows = this.rows.toArray();
if (index < -1 || index > rows.length) {
throw new core.DOMException(core.INDEX_SIZE_ERR);
}
if (index === -1 || (index === 0 && rows.length === 0)) {
this.tBodies.item(0).appendChild(tr);
}
else if (index === rows.length) {
var ref = rows[index-1];
ref._parentNode.appendChild(tr);
}
else {
var ref = rows[index];
ref._parentNode.insertBefore(tr, ref);
}
return tr;
},
deleteRow: function(index) {
var rows = this.rows.toArray(), l = rows.length;
if (index === -1) {
index = l-1;
}
if (index < 0 || index >= l) {
throw new core.DOMException(core.INDEX_SIZE_ERR);
}
var tr = rows[index];
tr._parentNode.removeChild(tr);
}
},
attributes: [
'align',
'bgColor',
'border',
'cellPadding',
'cellSpacing',
'frame',
'rules',
'summary',
'width'
]
});
define('HTMLTableCaptionElement', {
tagName: 'CAPTION',
attributes: [
'align'
]
});
define('HTMLTableColElement', {
tagNames: ['COL','COLGROUP'],
attributes: [
'align',
{prop: 'ch', attr: 'char'},
{prop: 'chOff', attr: 'charoff'},
{prop: 'span', type: 'long'},
'vAlign',
'width',
]
});
define('HTMLTableSectionElement', {
tagNames: ['THEAD','TBODY','TFOOT'],
proto: {
get rows() {
if (!this._rows) {
this._rows = descendants(this, 'TR', false);
}
return this._rows;
},
insertRow: function(index) {
var tr = this._ownerDocument.createElement('TR');
var rows = this.rows.toArray();
if (index < -1 || index > rows.length) {
throw new core.DOMException(core.INDEX_SIZE_ERR);
}
if (index === -1 || index === rows.length) {
this.appendChild(tr);
}
else {
var ref = rows[index];
this.insertBefore(tr, ref);
}
return tr;
},
deleteRow: function(index) {
var rows = this.rows.toArray();
if (index === -1) {
index = rows.length-1;
}
if (index < 0 || index >= rows.length) {
throw new core.DOMException(core.INDEX_SIZE_ERR);
}
var tr = this.rows[index];
this.removeChild(tr);
}
},
attributes: [
'align',
{prop: 'ch', attr: 'char'},
{prop: 'chOff', attr: 'charoff'},
{prop: 'span', type: 'long'},
'vAlign',
'width',
]
});
define('HTMLTableRowElement', {
tagName: 'TR',
proto: {
get cells() {
if (!this._cells) {
this._cells = new core.HTMLCollection(this, core.mapper(this, function(n) {
return n.nodeName === 'TD' || n.nodeName === 'TH';
}, false));
}
return this._cells;
},
get rowIndex() {
return closest(this, 'TABLE').rows.toArray().indexOf(this);
},
get sectionRowIndex() {
return this._parentNode.rows.toArray().indexOf(this);
},
insertCell: function(index) {
var td = this._ownerDocument.createElement('TD');
var cells = this.cells.toArray();
if (index < -1 || index > cells.length) {
throw new core.DOMException(core.INDEX_SIZE_ERR);
}
if (index === -1 || index === cells.length) {
this.appendChild(td);
}
else {
var ref = cells[index];
this.insertBefore(td, ref);
}
return td;
},
deleteCell: function(index) {
var cells = this.cells.toArray();
if (index === -1) {
index = cells.length-1;
}
if (index < 0 || index >= cells.length) {
throw new core.DOMException(core.INDEX_SIZE_ERR);
}
var td = this.cells[index];
this.removeChild(td);
}
},
attributes: [
'align',
'bgColor',
{prop: 'ch', attr: 'char'},
{prop: 'chOff', attr: 'charoff'},
'vAlign'
]
});
define('HTMLTableCellElement', {
tagNames: ['TH','TD'],
proto: {
_headers: null,
set headers(h) {
if (h === '') {
//Handle resetting headers so the dynamic getter returns a query
this._headers = null;
return;
}
if (!(h instanceof Array)) {
h = [h];
}
this._headers = h;
},
get headers() {
if (this._headers) {
return this._headers.join(' ');
}
var cellIndex = this.cellIndex,
headings = [],
siblings = this._parentNode.getElementsByTagName(this.tagName);
for (var i=0; i<siblings.length; i++) {
if (siblings.item(i).cellIndex >= cellIndex) {
break;
}
headings.push(siblings.item(i).id);
}
this._headers = headings;
return headings.join(' ');
},
get cellIndex() {
return closest(this, 'TR').cells.toArray().indexOf(this);
}
},
attributes: [
'abbr',
'align',
'axis',
'bgColor',
{prop: 'ch', attr: 'char'},
{prop: 'chOff', attr: 'charoff'},
{prop: 'colSpan', type: 'long'},
'height',
{prop: 'noWrap', type: 'boolean'},
{prop: 'rowSpan', type: 'long'},
'scope',
'vAlign',
'width'
]
});
define('HTMLFrameSetElement', {
tagName: 'FRAMESET',
attributes: [
'cols',
'rows'
]
});
function loadFrame (frame) {
if (frame._contentDocument) {
// We don't want to access document.parentWindow, since the getter will
// cause a new window to be allocated if it doesn't exist. Probe the
// private variable instead.
if (frame._contentDocument._parentWindow) {
// close calls delete on its document.
frame._contentDocument.parentWindow.close();
} else {
delete frame._contentDocument;
}
}
var src = frame.src;
var parentDoc = frame._ownerDocument;
var url = core.resourceLoader.resolve(parentDoc, src);
var contentDoc = frame._contentDocument = new core.HTMLDocument({
url: url,
documentRoot: Path.dirname(url)
});
applyDocumentFeatures(contentDoc, parentDoc.implementation._features);
var parent = parentDoc.parentWindow;
var contentWindow = contentDoc.parentWindow;
contentWindow.parent = parent;
contentWindow.top = parent.top;
core.resourceLoader.load(frame, url, function(html, filename) {
contentDoc.write(html);
contentDoc.close();
});
}
define('HTMLFrameElement', {
tagName: 'FRAME',
init : function () {
// Set up the frames array. window.frames really just returns a reference
// to the window object, so the frames array is just implemented as indexes
// on the window.
var parent = this._ownerDocument.parentWindow;
var frameID = parent._length++;
var self = this;
parent.__defineGetter__(frameID, function () {
return self.contentWindow;
});
// The contentDocument/contentWindow shouldn't be created until the frame
// is inserted:
// "When an iframe element is first inserted into a document, the user
// agent must create a nested browsing context, and then process the
// iframe attributes for the first time."
// (http://dev.w3.org/html5/spec/Overview.html#the-iframe-element)
this._initInsertListener = this.addEventListener('DOMNodeInsertedIntoDocument', function () {
var parentDoc = self._ownerDocument;
// Calling contentDocument creates the Document if it doesn't exist.
var doc = self.contentDocument;
applyDocumentFeatures(doc, parentDoc.implementation._features);
var window = self.contentWindow;
window.parent = parent;
window.top = parent.top;
}, false);
},
proto: {
setAttribute: function(name, value) {
core.HTMLElement.prototype.setAttribute.call(this, name, value);
var self = this;
if (name === 'name') {
// Set up named frame access.
this._ownerDocument.parentWindow.__defineGetter__(value, function () {
return self.contentWindow;
});
} else if (name === 'src') {
// Page we don't fetch the page until the node is inserted. This at
// least seems to be the way Chrome does it.
if (!this._attachedToDocument) {
if (!this._waitingOnInsert) {
// First, remove the listener added in 'init'.
this.removeEventListener('DOMNodeInsertedIntoDocument',
this._initInsertListener, false)
// If we aren't already waiting on an insert, add a listener.
// This guards against src being set multiple times before the frame
// is inserted into the document - we don't want to register multiple
// callbacks.
this.addEventListener('DOMNodeInsertedIntoDocument', function loader () {
self.removeEventListener('DOMNodeInsertedIntoDocument', loader, false);
this._waitingOnInsert = false;
loadFrame(self);
}, false);
this._waitingOnInsert = true;
}
} else {
loadFrame(self);
}
}
},
_contentDocument : null,
get contentDocument() {
if (this._contentDocument == null) {
this._contentDocument = new core.HTMLDocument();
}
return this._contentDocument;
},
get contentWindow() {
return this.contentDocument.parentWindow;
}
},
attributes: [
'frameBorder',
'longDesc',
'marginHeight',
'marginWidth',
'name',
{prop: 'noResize', type: 'boolean'},
'scrolling',
{prop: 'src', type: 'string', write: false}
]
});
define('HTMLIFrameElement', {
tagName: 'IFRAME',
parentClass: core.HTMLFrameElement,
attributes: [
'align',
'frameBorder',
'height',
'longDesc',
'marginHeight',
'marginWidth',
'name',
'scrolling',
'src',
'width'
]
});
exports.define = define;
exports.dom = {
level2 : {
html : core
}
}
|
godmar/jsdom
|
lib/jsdom/level2/html.js
|
JavaScript
|
mit
| 43,247
|
#
# Kyle Poore
# March 3, 2014
CC = gcc -O3
BUILDDIR = ../build
BINDIR = ../bin
MODDIR = modules
TESTDIR = ../public
MODULES = GET.c POST.c
TESTS = helloworld.c reflect.c ngen.c
FRAMEWORK = dispatch.c server.c process_request.c request.c helpers.c
MODULE_OBJS = $(MODULES:%.c=$(BUILDDIR)/$(MODDIR)/%.o)
FRAMEWORK_OBJS = $(FRAMEWORK:%.c=$(BUILDDIR)/%.o)
TESTPROGS = $(TESTS:%.c=$(TESTDIR)/%)
EXEC = server
all: directories ${TESTPROGS} ${EXEC}
directories:
mkdir -p ${BUILDDIR}/${MODDIR} ${BINDIR}
../public/%: ../public/%.c
${CC} $< -o $@
${EXEC}: ${FRAMEWORK_OBJS} ${MODULE_OBJS}
${CC} ${FRAMEWORK_OBJS} ${MODULE_OBJS} -o ${BINDIR}/${EXEC}
${BUILDDIR}/server.o: ${FRAMEWORK} ${BUILDDIR}/dispatch.o \
${BUILDDIR}/process_request.o \
${BUILDDIR}/request.o \
${BUILDDIR}/helpers.o
${CC} -c server.c -o ${BUILDDIR}/server.o
${BUILDDIR}/dispatch.o: dispatch.c dispatch.h ${MODULE_OBJS}
${CC} -c dispatch.c -o ${BUILDDIR}/dispatch.o
${BUILDDIR}/process_request.o: process_request.c process_request.h
${CC} -c process_request.c -o ${BUILDDIR}/process_request.o
${BUILDDIR}/request.o: request.c request.h
${CC} -c request.c -o ${BUILDDIR}/request.o
${BUILDDIR}/helpers.o: helpers.c helpers.h
${CC} -c helpers.c -o ${BUILDDIR}/helpers.o
${BUILDDIR}/${MODDIR}/%.o: ${MODDIR}/%.c ${MODDIR}/%.h
${CC} -c $< -o $@
run:
../bin/server -v ../public
submit:
svn commit -m "submitted for grade"
clean:
-rm -rf ${BUILDDIR} ${BINDIR} ${TESTPROGS}
|
Kylepoore/mini-http-server
|
src/Makefile
|
Makefile
|
mit
| 1,519
|
define(['components/home-page/home'], function(homePage) {
var HomePageViewModel = homePage.viewModel;
var instance;
describe('Home page view model', function() {
beforeEach(function() {
spyOn(HomePageViewModel.prototype, 'loadYelpPlaces').and.callThrough();
instance = new HomePageViewModel();
});
it('should call loadYelpPlaces', function() {
expect(instance.loadYelpPlaces).toHaveBeenCalled();
});
it('filterOptions array should eqal ["all"]', function() {
expect(instance.filterOptions()).toEqual(['all']);
});
});
});
|
mradenovic/neighborhood-map
|
test/components/home-page.js
|
JavaScript
|
mit
| 585
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `atomic_fence` fn in crate `core`.">
<meta name="keywords" content="rust, rustlang, rust-lang, atomic_fence">
<title>core::intrinsics::atomic_fence - Rust</title>
<link rel="stylesheet" type="text/css" href="../../main.css">
<link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<section class="sidebar">
<a href='../../core/index.html'><img src='http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='' width='100'></a>
<p class='location'><a href='../index.html'>core</a>::<wbr><a href='index.html'>intrinsics</a></p><script>window.sidebarCurrent = {name: 'atomic_fence', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</section>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press 'S' to search, '?' for more options..."
type="search">
</div>
</form>
</nav>
<section id='main' class="content fn">
<h1 class='fqn'><span class='in-band'><a href='../index.html'>core</a>::<wbr><a href='index.html'>intrinsics</a>::<wbr><a class='fn' href=''>atomic_fence</a><wbr><a class='stability Unstable' title=''>Unstable</a></span><span class='out-of-band'><span id='render-detail'>
<a id="collapse-all" href="#">[-]</a> <a id="expand-all" href="#">[+]</a>
</span><a id='src-23758' href='../../src/core/intrinsics.rs.html#155'>[src]</a></span></h1>
<pre class='rust fn'>pub unsafe fn atomic_fence()</pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<div id="help" class="hidden">
<div class="shortcuts">
<h1>Keyboard shortcuts</h1>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h1>Search tricks</h1>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>typedef</code> (or
<code>tdef</code>).
</p>
</div>
</div>
<script>
window.rootPath = "../../";
window.currentCrate = "core";
window.playgroundUrl = "http://play.rust-lang.org/";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script src="../../playpen.js"></script>
<script async src="../../search-index.js"></script>
</body>
</html>
|
ArcherSys/ArcherSys
|
Rust/share/doc/rust/html/core/intrinsics/fn.atomic_fence.html
|
HTML
|
mit
| 3,715
|
---
layout: fr
body_class: page
---
<div class="container postcontent">
<div class="band">
<div class="row wide-gutter-row">
<div class="col-md-7 col-lg-8 wide-gutter-col">
<h2>{{ page.title }}</h2>
{% comment %}Date needs to be translated.{% endcomment %}
{{ content }}
</div>
</div>
</div>
</div>
|
jpmckinney/opengovdialogue.ca-jekyll
|
_layouts/post-fr.html
|
HTML
|
mit
| 340
|
from copy import copy
import sys
from textwrap import dedent
import warnings
import logging
import numpy
from six.moves import xrange
import theano
from theano.compat import izip
from six import integer_types
from theano.gradient import DisconnectedType
from theano import gof
from theano.gof import Apply, Constant, hashtype, Op, Type, MethodNotDefined
from theano.printing import pprint
from theano import scalar as scal
from theano.tensor.basic import alloc
from theano.tensor.basic import (addbroadcast, clip, get_scalar_constant_value,
ARange, TensorType, NotScalarConstantError)
from theano.tensor.elemwise import DimShuffle
from theano.tensor.type_other import NoneConst, SliceType, make_slice
from theano import config
inplace_increment = None
if config.cxx:
import theano.gof.cutils # needed to import cutils_ext
try:
from cutils_ext.cutils_ext import inplace_increment
except ImportError:
pass
_logger = logging.getLogger("theano.tensor.subtensor")
# Do a lazy import of the sparse module
sparse_module_ref = None
class AdvancedIndexingError(TypeError):
"""
Raised when Subtensor is asked to perform advanced indexing.
"""
def __init__(self, *args):
TypeError.__init__(self, *args)
##########
# Helpful functions to deal with Subtensor and IncSubtensor
##########
def make_constant(args):
"""
Convert python litterals to theano constants in subtensor arguments.
"""
def conv(a):
if a is None:
return a
elif isinstance(a, slice):
return slice(conv(a.start),
conv(a.stop),
conv(a.step))
elif isinstance(a, (integer_types, numpy.integer)):
return scal.ScalarConstant(scal.int64, a)
else:
return a
return tuple(map(conv, args))
def get_idx_list(inputs, idx_list, get_count=False):
'''
Given a list of inputs to the subtensor and its idx_list reorders
the inputs according to the idx list to get the right values.
If get_counts=True, instead returns the number of inputs consumed
during this process.
'''
# The number of indices
n = len(inputs) - 1
# The subtensor (or idx_list) does not depend on the inputs.
if n == 0:
return tuple(idx_list)
indices = list(reversed(list(inputs[1:])))
# General case
def convert(entry):
if isinstance(entry, gof.Type):
return indices.pop()
elif isinstance(entry, slice):
return slice(convert(entry.start),
convert(entry.stop),
convert(entry.step))
else:
return entry
cdata = tuple(map(convert, idx_list))
if get_count:
return n - len(indices)
else:
return cdata
def get_canonical_form_slice(theslice, length):
'''
Given a slice [start:stop:step] transform it into a canonical form
that respects the conventions imposed by python and numpy.
In a canonical form a slice is represented by a canonical form slice,
in which 0 <= start <= stop <= length and step > 0, and a flag which says
if the resulting set of numbers needs to be reversed or not.
'''
from theano.tensor import switch, lt, ge, sgn
if isinstance(theslice, slice):
def analyze(x):
try:
x_constant = get_scalar_constant_value(x)
is_constant = True
except theano.tensor.NotScalarConstantError:
x_constant = theano.tensor.extract_constant(x)
is_constant = False
return x_constant, is_constant
start, is_start_constant = analyze(theslice.start)
stop, is_stop_constant = analyze(theslice.stop)
step, is_step_constant = analyze(theslice.step)
length, is_length_constant = analyze(length)
if step is None:
step = 1
is_step_constant = True
# First handle the easier and common case where `step` is 1 and
# either `start` or `stop` is a range boundary. More specializations
# could be added later. This makes the resulting graph smaller than
# in the generic case below.
if step == 1:
is_start_0 = (
start is None or start == 0 or
(is_start_constant and is_length_constant and
start < 0 and start + length <= 0))
is_stop_length = (
stop is None or stop in [length, sys.maxsize] or
(is_stop_constant and is_length_constant and
stop >= length))
if is_start_0:
# 0:stop:1
if is_stop_length:
# Full slice.
return slice(0, length, 1), 1
if is_stop_constant and stop >= 0:
return (slice(0, switch(lt(stop, length), stop, length),
1), 1)
stop_plus_len = stop + length
stop = switch(
lt(stop, 0),
# stop < 0
switch(
lt(stop_plus_len, 0),
# stop + len < 0
0,
# stop + len >= 0
stop_plus_len),
# stop >= 0: use min(stop, length)
switch(lt(stop, length), stop, length))
return slice(0, stop, 1), 1
elif is_stop_length:
# start:length:1
if is_start_constant and start >= 0:
return slice(switch(lt(start, length), start, length),
length, 1), 1
start_plus_len = start + length
start = switch(
lt(start, 0),
# start < 0
switch(
lt(start_plus_len, 0),
# start + len < 0
0,
# start + len >= 0
start_plus_len),
# start >= 0: use min(start, length)
switch(lt(start, length), start, length))
return slice(start, length, 1), 1
# This is the generic case.
if is_step_constant:
# When we know the sign of `step`, the graph can be made simpler.
assert step != 0
if step > 0:
def switch_neg_step(a, b):
return b
abs_step = step
sgn_step = 1
else:
def switch_neg_step(a, b):
return a
abs_step = -step
sgn_step = -1
else:
is_step_neg = lt(step, 0)
def switch_neg_step(a, b):
return switch(is_step_neg, a, b)
abs_step = abs(step)
sgn_step = sgn(step)
defstart = switch_neg_step(length - 1, 0)
defstop = switch_neg_step(-1, length)
if start is None:
start = defstart
else:
start = switch(lt(start, 0), start + length, start)
start = switch(lt(start, 0), switch_neg_step(-1, 0), start)
start = switch(ge(start, length),
switch_neg_step(length - 1, length),
start)
if stop is None or stop == sys.maxsize:
# The special "maxsize" case is probably not needed here,
# as slices containing maxsize are not generated by
# __getslice__ anymore.
stop = defstop
else:
stop = switch(lt(stop, 0), stop + length, stop)
stop = switch(lt(stop, 0), -1, stop)
stop = switch(ge(stop, length), length, stop)
nw_stop = switch_neg_step(start + 1, stop)
slice_len = (start - stop - 1) // abs_step + 1
slice_len = switch(lt(slice_len, 0), 0, slice_len)
neg_start = nw_stop - (slice_len - 1) * abs_step - 1
neg_start = switch(lt(neg_start, 0), (nw_stop - 1), neg_start)
nw_start = switch_neg_step(neg_start, start)
nw_start = switch(lt(nw_start, 0), 0, nw_start)
nw_stop = switch(lt(nw_stop, 0), 0, nw_stop)
# Ensure start <= stop.
nw_start = switch(lt(nw_start, nw_stop), nw_start, nw_stop)
nw_step = abs_step
if step != 1:
reverse = sgn_step
return slice(nw_start, nw_stop, nw_step), reverse
else:
return slice(nw_start, nw_stop, nw_step), 1
else:
value = theano.tensor.extract_constant(theslice)
value = switch(lt(value, 0), (value + length), value)
return value, 1
class Subtensor(Op):
"""Return a subtensor view
The inputs array is the tensor x, followed by scalar integer types.
TODO: WRITEME: how are the scalar integer variables formatted?
This class uses a relatively complex internal representation of the inputs
to remember how the input tensor x should be sliced.
idx_list: instance variable TODO: WRITEME: is this a list or a tuple?
(old docstring gives two conflicting
descriptions)
elements are either integers, theano scalar types, or slices.
one element per "explicitly named dimension"
TODO: WRITEME: what is an "explicitly named dimension" ?
if integer:
indexes into the inputs array
if slice:
start/stop/step members of each slice are integer indices
into the inputs array or None
integer indices be actual integers or theano scalar types
Note that the idx_list defines the Op, so two Subtensor instances are
considered to be different Ops if they have different idx_list fields.
This means that the entries in it are theano Types, not theano Variables.
@todo: add support for advanced tensor indexing (in Subtensor_dx too).
"""
e_invalid = ('The index list is longer (size %d) than the number of '
'dimensions of the tensor(namely %d). You are asking for '
'a dimension of the tensor that does not exist! You might '
'need to use dimshuffle to add extra dimension to your '
'tensor.')
e_subslice = 'nested slicing is not supported'
e_indextype = "Invalid index type or slice for Subtensor"
debug = 0
check_input = False
view_map = {0: [0]}
_f16_ok = True
__props__ = ("idx_list",)
@staticmethod
def collapse(idxs, cond):
"""
idxs: a list of indices or slices.
cond: a callable that returns a bool
returns: idxs, with the slices flattened out into a list.
if cond is true for an entry, does not flatten it.
"""
ret = []
def helper(entry):
if cond(entry):
ret.append(entry)
elif isinstance(entry, slice):
helper(entry.start)
helper(entry.stop)
helper(entry.step)
for idx in idxs:
helper(idx)
return ret
@staticmethod
def convert(entry, slice_ok=True):
"""
The "idx_list" field is unique to each Subtensor instance.
It is not unique to each Apply node, so it should not refer to
specific Variables. This method changes references to Variables
into references to Types.
TODO: WRITEME: This method also accepts "entry" already being a Type;
when would that happen?
"""
invalid_scal_types = [scal.float64, scal.float32, scal.float16]
scal_types = [scal.int64, scal.int32, scal.int16, scal.int8]
tensor_types = [theano.tensor.lscalar, theano.tensor.iscalar,
theano.tensor.wscalar, theano.tensor.bscalar]
invalid_tensor_types = [theano.tensor.fscalar, theano.tensor.dscalar,
theano.tensor.cscalar, theano.tensor.zscalar]
if (isinstance(entry, gof.Variable) and
(entry.type in invalid_scal_types or
entry.type in invalid_tensor_types)):
raise TypeError("Expected an integer")
if isinstance(entry, gof.Variable) and entry.type in scal_types:
return entry.type
elif isinstance(entry, gof.Type) and entry in scal_types:
return entry
if (isinstance(entry, gof.Variable) and
entry.type in tensor_types and
numpy.all(entry.type.broadcastable)):
return scal.get_scalar_type(entry.type.dtype)
elif (isinstance(entry, gof.Type) and
entry in tensor_types and
numpy.all(entry.broadcastable)):
return scal.get_scalar_type(entry.dtype)
elif slice_ok and isinstance(entry, slice):
a = entry.start
b = entry.stop
c = entry.step
if a is not None:
slice_a = Subtensor.convert(a, False)
else:
slice_a = None
if b is not None and b != sys.maxsize:
# The special "maxsize" case is probably not needed here,
# as slices containing maxsize are not generated by
# __getslice__ anymore.
slice_b = Subtensor.convert(b, False)
else:
slice_b = None
if c is not None:
slice_c = Subtensor.convert(c, False)
else:
slice_c = None
return slice(slice_a, slice_b, slice_c)
elif isinstance(entry, (integer_types, numpy.integer)):
# Disallow the use of python scalars in idx_list
raise TypeError("Python scalar in idx_list."
"Please report this error to theano-dev.")
else:
raise AdvancedIndexingError(Subtensor.e_indextype, entry)
def get_constant_idx(self, inputs, allow_partial=False,
only_process_constants=False):
"""
Return the idx_list with constant inputs replaced by their
python scalar equivalent. May raise
`theano.tensor.NotScalarConstantError` if the idx contains
non-constant entries.
If allow_partial is True, then entries that are not constant
will stay as their input variable rather than raising an
exception.
None entries are always left as-is.
Example usage (where v, a are appropriately typed theano variables):
>>> b = a[v, 1:3]
>>> b.owner.op.idx_list
(Scalar(int64), slice(Scalar(int64), Scalar(int64), None))
>>> b.owner.op.get_constant_idx(b.owner.inputs, allow_partial=True)
[v, slice(1, 3, None)]
>>> b.owner.op.get_constant_idx(b.owner.inputs)
NotScalarConstantError: v
:param only_process_constants: If True, we only attempt to obtain
the value of an index/slice if it's directly constant and don't
try to dig through dimshuffles, fills, allocs, and other to figure
out its value.
"""
real_idx = get_idx_list(inputs, self.idx_list)
def conv(val):
if val is None:
return None
elif isinstance(val, slice):
return slice(conv(val.start),
conv(val.stop),
conv(val.step))
else:
try:
return get_scalar_constant_value(
val,
only_process_constants=only_process_constants)
except theano.tensor.NotScalarConstantError:
if allow_partial:
return val
else:
raise
return list(map(conv, real_idx))
def __init__(self, idx_list):
self.idx_list = tuple(map(self.convert, idx_list))
@staticmethod
def my_as_scalar(a):
# Since scal.as_scalar does not know about tensor types (it would
# create a circular import) , this method converts either a
# TensorVariable or a ScalarVariable to a scalar.
if isinstance(a, gof.Variable) and isinstance(a.type, TensorType):
return theano.tensor.scalar_from_tensor(a)
else:
return scal.as_scalar(a)
def make_node(self, x, *inputs):
"""
x: the tensor to take a subtensor of
inputs: a list of theano Scalars
"""
x = theano.tensor.as_tensor_variable(x)
inputs = tuple(self.my_as_scalar(a) for a in inputs)
idx_list = list(self.idx_list)
if len(idx_list) > x.type.ndim:
exception = ValueError(Subtensor.e_invalid % (
len(idx_list), x.type.ndim))
exception.subtensor_invalid = True
raise exception
input_types = Subtensor.collapse(idx_list,
lambda entry: isinstance(entry,
gof.Type))
if len(inputs) != len(input_types):
raise IndexError(
"Not enough inputs to fill in the Subtensor template.",
inputs, idx_list)
for input, expected_type in izip(inputs, input_types):
if input.type != expected_type:
raise TypeError(
"Wrong type for Subtensor template. Expected %s, got %s."
% (input.type, expected_type))
# infer the broadcasting pattern
padded = (self.get_constant_idx((None,) + inputs, allow_partial=True) +
[slice(None, None, None)] * (x.type.ndim - len(idx_list)))
broadcastable = []
for i, (p, bc) in enumerate(izip(padded, x.type.broadcastable)):
if isinstance(p, slice):
if bc:
start = p.start
try:
start = get_scalar_constant_value(start)
except NotScalarConstantError:
pass
if start is None or start == 0:
start = p.start
if start is None:
start = 0
if (p.stop is None or
(isinstance(p.stop, (int, numpy.integer,
numpy.ndarray)) and
p.stop > start)):
broadcastable.append(True)
continue
broadcastable.append(False)
return gof.Apply(self,
(x, ) + inputs,
[theano.tensor.tensor(dtype=x.type.dtype,
broadcastable=broadcastable)])
def perform(self, node, inputs, out_):
out, = out_
x = inputs[0]
cdata = get_idx_list(inputs, self.idx_list)
if len(cdata) == 1:
cdata = cdata[0]
out[0] = numpy.asarray(x.__getitem__(cdata))
def infer_shape(self, node, shapes):
xshp = shapes[0]
assert len(xshp) == node.inputs[0].ndim
outshp = []
actual_idx_list = list(get_idx_list(node.inputs, self.idx_list))
padded = (actual_idx_list +
[slice(None, None, None)] * (len(xshp) - len(self.idx_list)))
i = 0
for idx, xl in izip(padded, xshp):
if isinstance(idx, slice):
# If it is the default (None, None, None) slice, or a variant,
# the shape will be xl
if ((idx.start in [None, 0]) and
(idx.stop in [None, sys.maxsize]) and
(idx.step is None or idx.step == 1)):
outshp.append(xl)
else:
cnf = get_canonical_form_slice(idx, xl)[0]
if cnf.step == 1:
length = cnf.stop - cnf.start
else:
length = (cnf.stop - cnf.start - 1) // cnf.step + 1
outshp.append(length)
i += 1
else:
# That dimension is dropped
pass
assert i == node.outputs[0].ndim
assert len(outshp) == node.outputs[0].ndim
return [outshp]
def grad(self, inputs, grads):
gz, = grads
x = inputs[0]
rest = inputs[1:]
output = self(*inputs)
if output.dtype.find('int') != -1:
first = x.zeros_like().astype(theano.config.floatX)
else:
first = IncSubtensor(self.idx_list)(x.zeros_like(), gz, *rest)
return ([first] + [DisconnectedType()()] * len(rest))
def connection_pattern(self, node):
rval = [[True]]
for ipt in node.inputs[1:]:
rval.append([False])
return rval
def __hash__(self):
# TODO: optimize by cache this hash value
msg = []
for entry in self.idx_list:
if isinstance(entry, slice):
msg += [(entry.start, entry.stop, entry.step)]
else:
msg += [entry]
idx_list = tuple(msg)
# backport
# idx_list = tuple((entry.start, entry.stop, entry.step)
# if isinstance(entry, slice)
# else entry
# for entry in self.idx_list)
return hash(idx_list)
@staticmethod
def str_from_slice(entry):
msg = []
for x in [entry.start, entry.stop, entry.step]:
if x is None:
msg.append("")
else:
msg.append(str(x))
return ":".join(msg)
def __str__(self):
indices = []
for entry in self.idx_list:
if isinstance(entry, slice):
indices.append(self.str_from_slice(entry))
else:
indices.append(str(entry))
return "%s{%s}" % (self.__class__.__name__, ", ".join(indices))
@staticmethod
def default_helper_c_code_args():
"""
Returns a dictionary of default arguments to
helper_c_code
"""
return {"c_prefix": "PyArray",
"strides_mul": 1}
@staticmethod
def helper_c_code(node, name, inputs, outputs, sub, idx_list, view_ndim,
c_prefix=None,
strides_mul=None):
"""
The parameters c_prefix are there to allow reusing this
function on PyArray and CudaNdarray object.
This fct take as input the x,
"""
default_args = Subtensor.default_helper_c_code_args()
if strides_mul is None:
strides_mul = default_args['strides_mul']
if c_prefix is None:
c_prefix = default_args['c_prefix']
#
# two arrays are created in C code:
# is_slice: len == ndim, 0 means int, 1 means slice
# subtensor_spec: len = n_ints + 3 * n_slices
#
fail = sub['fail']
init_cmds = [] # initialization for subtensor_spec
is_slice = []
# TODO: change that, it might lead to unexpected results,
# see assembla-#767
NONE_CODE = sys.maxsize - 1
pos = [0, 1] # annoying version of global variable for init_entry
def inc_spec_pos(amt):
pos[0] += amt
def inc_input_pos(amt):
pos[1] += amt
def spec_pos():
return pos[0]
def input_pos():
return pos[1]
def init_entry(entry, depth=0):
if isinstance(entry, (numpy.integer, int)):
init_cmds.append(
"subtensor_spec[%i] = %i;" % (spec_pos(),
entry))
inc_spec_pos(1)
if depth == 0:
is_slice.append(0)
elif isinstance(entry, Type):
init_cmds.append(
"subtensor_spec[%i] = %s;" % (spec_pos(),
inputs[input_pos()]))
inc_spec_pos(1)
inc_input_pos(1)
if depth == 0:
is_slice.append(0)
elif entry is None:
init_cmds.append(
"subtensor_spec[%i] = %i;" % (spec_pos(),
NONE_CODE))
inc_spec_pos(1)
if depth == 0:
is_slice.append(0)
elif depth == 0 and isinstance(entry, slice):
init_entry(entry.start, depth + 1)
init_entry(entry.stop, depth + 1)
init_entry(entry.step, depth + 1)
is_slice.append(1)
else:
assert 0, entry
for entry in idx_list:
init_entry(entry)
# make sure we used all inputs
assert input_pos() == len(inputs), input_pos()
assert len(is_slice) <= node.inputs[0].ndim, node.inputs[0].ndim
len_is_slice = len(is_slice)
len_subtensor_spec = spec_pos()
subensor_spec = "npy_intp subtensor_spec[%(len_subtensor_spec)s];" % locals()
if len_subtensor_spec == 0:
subensor_spec = "npy_intp * subtensor_spec = NULL;"
if is_slice:
is_slice_init = "int is_slice[] = {" + ",".join([str(s) for s in
is_slice]) + "};"
else:
is_slice_init = "int* is_slice = NULL;"
subtensor_init = "\n".join(init_cmds)
x, = inputs[:1]
z, = outputs
if view_ndim:
rval = """
// Argument of the view
npy_intp xview_dims[%(view_ndim)s];
npy_intp xview_strides[%(view_ndim)s];
""" % locals()
else:
rval = """
// Argument of the view
npy_intp* xview_dims = NULL;
npy_intp* xview_strides = NULL;
"""
rval += """
// One more argument of the view
npy_intp xview_offset = 0;
// The subtensor is created by iterating over the dimensions
// and updating stride, shape, and data pointers
%(is_slice_init)s
%(subensor_spec)s
%(subtensor_init)s;
int spec_pos = 0; //position in subtensor_spec
int inner_ii = 0; // the current dimension of zview
int outer_ii = 0; // current dimension of z
for (; outer_ii < %(len_is_slice)s; ++outer_ii)
{
if (is_slice[outer_ii])
{
npy_intp length = %(c_prefix)s_DIMS(%(x)s)[outer_ii];
npy_intp slicelength;
npy_intp start = subtensor_spec[spec_pos+0];
npy_intp stop = subtensor_spec[spec_pos+1];
npy_intp step = subtensor_spec[spec_pos+2];
if (step == %(NONE_CODE)s) step = 1;
npy_intp defstart = step < 0 ? length-1 : 0;
npy_intp defstop = step < 0 ? -1 : length;
// logic adapted from
// PySlice_GetIndicesEx in python source
if (!step)
{
PyErr_Format(PyExc_ValueError,
"slice step cannot be zero");
%(fail)s;
}
if (start == %(NONE_CODE)s)
{
start = defstart;
}
else
{
if (start < 0) start += length;
if (start < 0) start = (step < 0) ? -1 : 0;
if (start >= length)
start = (step < 0) ? length - 1 : length;
}
if (stop == %(NONE_CODE)s)
{
stop = defstop;
}
else
{
if (stop < 0) stop += length;
if (stop < 0) stop = (step < 0) ? -1 : 0;
if (stop >= length)
stop = (step < 0) ? length - 1 : length;
}
if ((step < 0 && stop >= start)
|| (step > 0 && start >= stop)) {
slicelength = 0;
}
else if (step < 0) {
slicelength = (stop-start+1)/step+1;
}
else {
slicelength = (stop-start-1)/step+1;
}
if (0){
fprintf(stdout, "start %%zi\\n", start);
fprintf(stdout, "stop %%zi\\n", stop);
fprintf(stdout, "step %%zi\\n", step);
fprintf(stdout, "length %%zi\\n", length);
fprintf(stdout, "slicelength %%zi\\n", slicelength);
}
assert (slicelength <= length);
xview_offset += (npy_intp)%(c_prefix)s_STRIDES(%(x)s)[outer_ii]
* start * %(strides_mul)s;
xview_dims[inner_ii] = slicelength;
xview_strides[inner_ii] = (npy_intp)%(c_prefix)s_STRIDES(%(x)s)[outer_ii] * step;
inner_ii += 1;
spec_pos += 3;
}
else // tuple coord `outer_ii` is an int
{
int idx = subtensor_spec[spec_pos];
if (idx < 0) idx += %(c_prefix)s_DIMS(%(x)s)[outer_ii];
if (idx >= 0)
{
if (idx < %(c_prefix)s_DIMS(%(x)s)[outer_ii])
{
xview_offset += (npy_intp)%(c_prefix)s_STRIDES(%(x)s)[outer_ii] * idx *
%(strides_mul)s;
}
else
{
PyErr_Format(PyExc_IndexError,"index out of bounds");
%(fail)s;
}
}
else
{
PyErr_Format(PyExc_IndexError,"index out of bounds");
%(fail)s;
}
spec_pos += 1;
}
}
assert (inner_ii <= %(view_ndim)s);
while (inner_ii < %(view_ndim)s)
{
assert (outer_ii < %(c_prefix)s_NDIM(%(x)s));
xview_dims[inner_ii] = %(c_prefix)s_DIMS(%(x)s)[outer_ii];
xview_strides[inner_ii] = %(c_prefix)s_STRIDES(%(x)s)[outer_ii];
inner_ii += 1;
outer_ii += 1;
}
""" % locals()
# print rval
return rval
@staticmethod
def helper_c_code_cache_version():
return (9,)
def c_code(self, node, name, inputs, outputs, sub): # DEBUG
if not isinstance(node.inputs[0].type, theano.tensor.TensorType):
raise NotImplementedError()
x = inputs[0]
z, = outputs
ndim = node.inputs[0].ndim
view_ndim = node.outputs[0].ndim
fail = sub['fail']
decl = "PyArrayObject * xview = NULL;"
checkNDim = """
if (PyArray_NDIM(%(x)s) != %(ndim)s){
PyErr_SetString(PyExc_ValueError,
"Expected %(ndim)s dimensions input"
);
%(fail)s
}
""" % locals()
get_xview = self.helper_c_code(node, name, inputs, outputs, sub,
self.idx_list, view_ndim)
build_view = """
//TODO: give this Op a second output so that this view can be cached
//TODO: alternatively, fix the memory leak on failure
Py_INCREF(PyArray_DESCR(%(x)s));
xview = (PyArrayObject*)PyArray_NewFromDescr(
&PyArray_Type,
PyArray_DESCR(%(x)s),
%(view_ndim)s,
xview_dims,
xview_strides,
PyArray_BYTES(%(x)s) + xview_offset,
PyArray_FLAGS(%(x)s),
NULL);
assert (PyArray_NDIM(xview) == %(view_ndim)s);
if (!xview)
{
%(fail)s;
}
""" % locals()
finish_view = """
//This is needed for NumPy 1.5, but not 1.7.2
PyArray_UpdateFlags(xview, NPY_ARRAY_C_CONTIGUOUS| NPY_ARRAY_F_CONTIGUOUS);
Py_XDECREF(%(z)s);
Py_INCREF(py_%(x)s);
#if NPY_API_VERSION < 0x00000007
PyArray_BASE(xview) = py_%(x)s;
#else
PyArray_SetBaseObject(xview, py_%(x)s);
#endif
assert(py_%(x)s == (PyObject*)%(x)s);
%(z)s = xview;
""" % locals()
return (decl + checkNDim +
"{" + get_xview + build_view + finish_view + "}")
def c_code_cache_version(self):
hv = self.helper_c_code_cache_version()
# If `helper_c_code_cache_version` is not versioned we do not want to
# have a versioned version of this op's C code.
if len(hv) == 0:
return ()
return (4, hv)
def R_op(self, inputs, eval_points):
# Subtensor is not differentiable wrt to its indices, therefore we
# do not even need to consider the eval_points provided for those
# (they should be defaulted to zeros_like by the global R_op)
if eval_points[0] is None:
return [None]
return self(eval_points[0], *inputs[1:], **dict(return_list=True))
class SubtensorPrinter:
def process(self, r, pstate):
if r.owner is None:
raise TypeError("Can only print Subtensor.")
elif isinstance(r.owner.op, Subtensor):
idxs = r.owner.op.idx_list
inputs = list(r.owner.inputs)
input = inputs.pop()
sidxs = []
inbrack_pstate = pstate.clone(precedence=-1000)
for entry in idxs:
if isinstance(entry, int):
sidxs.append(str(entry))
elif isinstance(entry, scal.Scalar):
sidxs.append(inbrack_pstate.pprinter.process(inputs.pop()))
elif isinstance(entry, slice):
if entry.start is None or entry.start == 0:
msg1 = ""
else:
msg1 = entry.start
if entry.stop is None or entry.stop == sys.maxsize:
msg2 = ""
else:
msg2 = entry.stop
if entry.step is None:
msg3 = ""
else:
msg3 = ":%s" % entry.step
sidxs.append("%s:%s%s" % (msg1, msg2, msg3))
return "%s[%s]" % (pstate.pprinter.process(
input,
pstate.clone(precedence=1000)),
", ".join(sidxs))
else:
raise TypeError("Can only print Subtensor.")
pprint.assign(lambda pstate, r: r.owner and isinstance(r.owner.op, Subtensor),
SubtensorPrinter())
def set_subtensor(x, y, inplace=False,
tolerate_inplace_aliasing=False):
"""Return x with the given subtensor overwritten by y.
Example: To replicate the numpy expression "r[10:] = 5", type
>>> r = ivector()
>>> new_r = set_subtensor(r[10:], 5)
:param x: symbolic variable for the lvalue of = operation
:param y: symbolic variable for the rvalue of = operation
:param tolerate_inplace_aliasing: see inc_subtensor for documentation.
"""
return inc_subtensor(x, y, inplace, set_instead_of_inc=True,
tolerate_inplace_aliasing=tolerate_inplace_aliasing)
def inc_subtensor(x, y, inplace=False, set_instead_of_inc=False,
tolerate_inplace_aliasing=False):
"""Return x with the given subtensor incremented by y.
:param x: the symbolic result of a Subtensor operation.
:param y: the amount by which to increment ths subtensor in question
:param inplace: Don't use. Theano will do it when possible.
:param set_instead_of_inc: If True, do a set_subtensor instead.
:param tolerate_inplace_aliasing: allow x and y to be views of a single
underlying array even while working inplace. For correct results,
x and y must not be overlapping views; if they overlap, the result
of this Op will generally be incorrect. This value has no effect if
inplace=False.
Example: To replicate the numpy expression "r[10:] += 5", type
>>> r = ivector()
>>> new_r = inc_subtensor(r[10:], 5)
"""
# First of all, y cannot have a higher dimension than x,
# nor have non-broadcastable dimensions where x is broadcastable.
x = theano.tensor.as_tensor_variable(x)
y = theano.tensor.as_tensor_variable(y)
if y.ndim > x.ndim:
raise TypeError(("Trying to increment a %d-dimensional "
"subtensor with a %d-dimensional value.") % (x.ndim,
y.ndim))
dim_offset = x.ndim - y.ndim
for dim in xrange(y.ndim):
if (x.broadcastable[dim + dim_offset] and not y.broadcastable[dim]):
# It is acceptable to try to increment a subtensor with a
# broadcastable dim with a tensor that is not broadcastable
# on that dimension. However, its length must then be 1.
# We insert a Rebroadcast Op to make sure it is the case.
y = addbroadcast(y, dim)
if not x.owner:
raise TypeError('x must be the result of a subtensor operation')
# retrieve idx_list from x.owner
if isinstance(x.owner.op, Subtensor):
if tolerate_inplace_aliasing:
destroyhandler_tolerate_aliased = [[0, 1]]
else:
destroyhandler_tolerate_aliased = []
the_op = IncSubtensor(
x.owner.op.idx_list, inplace, set_instead_of_inc,
destroyhandler_tolerate_aliased=destroyhandler_tolerate_aliased)
real_x = x.owner.inputs[0]
real_idxargs = x.owner.inputs[1:]
return the_op(real_x, y, *real_idxargs)
elif isinstance(x.owner.op, AdvancedSubtensor1):
real_x = x.owner.inputs[0]
ilist = x.owner.inputs[1]
the_op = AdvancedIncSubtensor1(inplace,
set_instead_of_inc=set_instead_of_inc)
return the_op(real_x, y, ilist)
elif isinstance(x.owner.op, AdvancedSubtensor):
real_x = x.owner.inputs[0]
ilist = x.owner.inputs[1:]
the_op = AdvancedIncSubtensor(inplace,
set_instead_of_inc=set_instead_of_inc)
return the_op(real_x, y, *ilist)
elif isinstance(x.owner.op, DimShuffle):
inner_x = x.owner.inputs[0]
# In the dimshuffle case, there are in fact two dimshuffles:
# one to make the indexed dimension the last one,
# and one to put it back where it was. So, in the case where we have
# inc_subtensor(x[:,i], y), the graph is actually
# inc_subtensor((x.T)[i].T, y).
# We could get all the way to x, and then get rid of the dimshuffles
# completely, but the problem is that advanced_inc_subtensor1 can only
# work on the first (outer-most, left-most) dimension of x,
# just like advanced_subtensor1.
# So we call advanced_inc_subtensor1(x.T, i, y.T) (as we also need to
# transpose y if it is not a scalar or a vector), but then we need to
# return something that has the same shape as x, not as x.T (inner_x).
# So re-apply the outer dimshuffle on the new inc_subtensor,
# and return advanced_inc_subtensor1(x.T, i, y.T).T.
# Get the dimshuffle pattern to apply to y.
x_order = x.owner.op.new_order
y_order = ['x'] * x.ndim
for i, v in enumerate(x_order):
if v != 'x' and (v - dim_offset) >= 0:
y_order[v - dim_offset] = i
# Warn if this code path would have produced wrong results in the past
if config.warn.inc_set_subtensor1:
# Dimshuffle pattern for y that would be equivalent to past code
prev_y_order = ['x'] * (dim_offset) + list(range(y.ndim))
if y_order != prev_y_order:
warnings.warn(
'Although your current code is fine, please note that '
'earlier versions prior to 0.7 (or this development '
'version) may have yielded an incorrect result in '
'this `inc_subtensor` or `set_subtensor` operation. '
'To remove this warning, you can either set the '
'`warn.inc_set_subtensor1` config option to `False`, '
'or `warn.ignore_bug_before` to at least "0.7".',
stacklevel=2)
inner_incsubtensor = inc_subtensor(
inner_x,
y.dimshuffle(y_order),
inplace=inplace,
set_instead_of_inc=set_instead_of_inc,
tolerate_inplace_aliasing=tolerate_inplace_aliasing)
return x.owner.op(inner_incsubtensor, *x.owner.inputs[1:])
elif isinstance(x.owner.op, theano.tensor.Reshape):
# This case happens when the indices are not arranged as a vector, but
# as a higher-dimensional array. This is handled by the subtensor
# by flattening this list, taking the subtensor, then reshaping the
# result.
inner_x = x.owner.inputs[0]
# Try to apply inc_subtensor on inner_x.
# If it works, there is no need to reshape, as the inc_subtensor
# will have the same shape as inner_x, which is what we want.
# We also explicitly duplicate y to its broadcasted shape
# before we partially flatten it to inner_x dimension. This is
# not strictly needed in all cases, but it is easier this way.
if y.ndim > 0:
# This if is needed to prevent some useless warning about
# old code bug.
expanded_y = alloc(y, *[x.shape[i] for i in xrange(x.ndim)])
flattened_y = expanded_y.flatten(inner_x.ndim)
else:
flattened_y = y
# Warn if this code path would have produced wrong results in the past
if config.warn.inc_set_subtensor1:
if inner_x.ndim > 1 and sum(y.broadcastable) > 0:
warnings.warn(
'Although your current code is fine, please note that '
'earlier versions prior to 0.7 (or this development '
'version) may have yielded an incorrect result in '
'this `inc_subtensor` or `set_subtensor` operation. '
'To remove this warning, you can either set the '
'`warn.inc_set_subtensor1` config option to `False`, '
'or `warn.ignore_bug_before` to at least "0.7".',
stacklevel=2)
inner_incsubtensor = inc_subtensor(
inner_x,
flattened_y,
inplace=inplace,
set_instead_of_inc=set_instead_of_inc,
tolerate_inplace_aliasing=tolerate_inplace_aliasing)
return inner_incsubtensor
else:
raise TypeError('x must be the result of a subtensor operation')
class IncSubtensor(Op):
"""Increment a subtensor.
This is like numpy's
x[i,j,k] += y
It is used internally to implement the gradient on SubTensor.
:param set_instead_of_inc: if True set the subtensor to the value instead
of incrementing it by that value.
"""
check_input = False
__props__ = ("idx_list", "inplace", "set_instead_of_inc")
def __init__(self, idx_list, inplace=False, set_instead_of_inc=False,
destroyhandler_tolerate_aliased=None):
if destroyhandler_tolerate_aliased is None:
destroyhandler_tolerate_aliased = []
self.idx_list = list(map(Subtensor.convert, idx_list))
self.inplace = inplace
if inplace:
self.destroy_map = {0: [0]}
self.destroyhandler_tolerate_aliased = list(
destroyhandler_tolerate_aliased)
self.set_instead_of_inc = set_instead_of_inc
def __hash__(self):
msg = []
for entry in self.idx_list:
if isinstance(entry, slice):
msg += [(entry.start, entry.stop, entry.step)]
else:
msg += [entry]
idx_list = tuple(msg)
# backport
# idx_list = tuple((entry.start, entry.stop, entry.step)
# if isinstance(entry, slice)
# else entry
# for entry in self.idx_list)
return (hashtype(self) ^ hash(idx_list) ^ hash(self.inplace) ^
hash(self.set_instead_of_inc))
def __str__(self):
indices = []
for entry in self.idx_list:
if isinstance(entry, slice):
indices.append(Subtensor.str_from_slice(entry))
else:
indices.append(str(entry))
if self.inplace:
msg = 'Inplace'
else:
msg = ''
if not self.set_instead_of_inc:
msg += 'Inc'
else:
msg += 'Set'
return "%s{%s;%s}" % (
self.__class__.__name__,
msg,
", ".join(indices))
def make_node(self, x, y, *inputs):
"""
x: the tensor to increment
y: the value to increment by
inputs: TODO WRITEME
"""
x, y = map(theano.tensor.as_tensor_variable, [x, y])
if y.ndim > x.ndim:
raise ValueError(("Trying to increment a %d-dimensional "
"subtensor with a %d-dimensional value.") % (
x.ndim, y.ndim))
inputs = tuple(map(Subtensor.my_as_scalar, inputs))
idx_list = list(self.idx_list)
if len(idx_list) > x.type.ndim:
exception = ValueError(
Subtensor.e_invalid % (
len(idx_list),
x.type.ndim))
exception.subtensor_invalid = True
raise exception
input_types = Subtensor.collapse(
idx_list,
lambda entry: isinstance(entry, gof.Type))
if len(inputs) != len(input_types):
raise IndexError(
"Not enough inputs to fill in the Subtensor template.",
inputs, idx_list)
for input, expected_type in izip(inputs, input_types):
if input.type != expected_type:
raise TypeError(
"Wrong type for Subtensor template. Expected %s, got %s."
% (input.type, expected_type))
return gof.Apply(self,
(x, y) + inputs,
[x.type()])
def decl_view(self):
return "PyArrayObject * zview = NULL;"
def perform(self, node, inputs, out_):
out, = out_
x, y = inputs[:2]
indices = list(reversed(inputs[2:]))
def convert(entry):
if isinstance(entry, gof.Type):
rval = indices.pop()
if sys.version_info < (2, 5):
# Before Python 2.5, PySlice_GetIndicesEx requires
# Python int to be passed.
rval_ = int(rval)
if rval_ != rval:
raise IndexError((
"Invalid value for indexing: %s. "
"That value may be too big.") % rval)
return rval_
return rval
elif isinstance(entry, slice):
return slice(convert(entry.start),
convert(entry.stop),
convert(entry.step))
else:
return entry
cdata = tuple(map(convert, self.idx_list))
if len(cdata) == 1:
cdata = cdata[0]
if not self.inplace:
x = x.copy()
sub_x = x.__getitem__(cdata)
if sub_x.shape:
# we've sliced out an N-D tensor with N > 0
if not self.set_instead_of_inc:
sub_x += y
else:
# sub_x += -sub_x + y
x.__setitem__(cdata, y)
else:
# scalar case
if not self.set_instead_of_inc:
x.__setitem__(cdata, sub_x + y)
else:
x.__setitem__(cdata, y)
out[0] = x
def c_code(self, node, name, inputs, outputs, sub):
# This method delegates much of the work to helper
# methods. This method implements the main logic
# but subclasses may override the helper methods
# to change the particulars, e.g. GpuIncSubtensor
# turns the view/copy operations on numpy arrays
# into the same operations on cuda arrays.
self.do_type_checking(node)
if self.inplace: # convert bool to int
inplace = 1
else:
inplace = 0
x = inputs[0]
y = inputs[1]
z, = outputs
if self.set_instead_of_inc: # convert bool to int
op_is_set = 1
else:
op_is_set = 0
fail = sub['fail']
view_ndim = (node.inputs[0].ndim -
numpy.sum([not isinstance(idx, slice)
for idx in self.idx_list]))
copy_of_x = self.copy_of_x(x)
copy_input_if_necessary = """
if (%(inplace)s)
{
if (%(x)s != %(z)s)
{
Py_XDECREF(%(z)s);
Py_INCREF(%(x)s);
%(z)s = %(x)s;
}
}
else
{
Py_XDECREF(%(z)s);
%(z)s = %(copy_of_x)s;
}
""" % locals()
# get info needed to make zview: a view of %(z)s
helper_args = self.get_helper_c_code_args()
get_zview = Subtensor.helper_c_code(
node=node,
name=name,
inputs=outputs[:1] + inputs[2:],
outputs=outputs,
sub=sub,
idx_list=self.idx_list,
view_ndim=view_ndim,
** helper_args
)
# Make a view on the output, as we will write into it.
alloc_zview = self.make_view_array(z, view_ndim)
build_view = """
//TODO: give this Op a second output so that this view can be cached
//TODO: alternatively, fix the memory leak on failure
%(alloc_zview)s;
if (!zview)
{
%(fail)s;
}
""" % locals()
copy_into = self.copy_into("zview", y)
add_to_zview = self.add_to_zview(name, y, fail)
make_modification = """
if (%(op_is_set)s)
{
if (%(copy_into)s) // does broadcasting
{
Py_DECREF(zview);
%(fail)s;
}
}
else
{
%(add_to_zview)s
}
""" % locals()
return (self.decl_view() +
copy_input_if_necessary +
get_zview +
build_view +
make_modification +
"Py_DECREF(zview);"
)
def do_type_checking(self, node):
""" Should raise NotImplementedError if c_code does not support
the types involved in this node.
"""
if not isinstance(node.inputs[0].type, theano.tensor.TensorType):
raise NotImplementedError()
def c_code_cache_version(self):
hv = Subtensor.helper_c_code_cache_version()
if hv:
return (1, hv)
else:
return ()
def copy_of_x(self, x):
"""
:param x: a string giving the name of a C variable
pointing to an array
:return: C code expression to make a copy of x
Base class uses PyArrayObject *, subclasses may override for
different types of arrays.
"""
# Parameters of PyArrary_FromAny are:
# array
# dtype: we pass NULL to say any dtype is acceptable, so the existing
# dtype will be copied
# min_depth: we pass 0 to have this parameter ignored
# max_depth: we pass 0 to have this parameter ignored
# requirements: here we pass NPY_ARRAY_ENSURECOPY to force a copy
# context: this is almost always NULL, I'm not sure what it's used for
return """(PyArrayObject*)PyArray_FromAny(py_%(x)s, NULL, 0, 0,
NPY_ARRAY_ENSURECOPY, NULL)""" % locals()
def make_view_array(self, x, view_ndim):
"""
:param x: a string identifying an array to be viewed
:param view_ndim: a string specifying the number of dimensions
to have in the view
This doesn't need to actually set up the view with the
right indexing; we'll do that manually later.
"""
return """Py_INCREF(PyArray_DESCR(%(x)s));
zview = (PyArrayObject*)PyArray_NewFromDescr(
&PyArray_Type,
PyArray_DESCR(%(x)s),
%(view_ndim)s,
xview_dims, //PyArray_DIMS(%(x)s),
xview_strides, //PyArray_STRIDES(%(x)s),
PyArray_BYTES(%(x)s) + xview_offset, //PyArray_DATA(%(x)s),
PyArray_FLAGS(%(x)s),
NULL);
//This is needed for NumPy 1.5, but not 1.7.2
PyArray_UpdateFlags(zview, NPY_ARRAY_C_CONTIGUOUS| NPY_ARRAY_F_CONTIGUOUS);
""" % locals()
def get_helper_c_code_args(self):
""" Return a dictionary of arguments to pass to helper_c_code."""
return Subtensor.default_helper_c_code_args()
def copy_into(self, view, source):
"""
view: string, C code expression for an array
source: string, C code expression for an array
returns a C code expression to copy source into view, and
return 0 on success
"""
return """PyArray_CopyInto(%(view)s, %(source)s)""" % locals()
def add_to_zview(self, name, x, fail):
""" Return C code to add x to zview. Should DECREF zview if the
add fails."""
return """
PyArrayObject * add_rval = (PyArrayObject*)PyNumber_InPlaceAdd(
(PyObject*)zview, py_%(x)s);
if (add_rval)
{
assert (PyArray_Check((PyObject*)add_rval));
assert (PyArray_DATA(add_rval) == PyArray_DATA(zview));
Py_DECREF(add_rval);
}
else
{
Py_DECREF(zview);
%(fail)s;
}""" % locals()
def infer_shape(self, node, shapes):
return [shapes[0]]
def R_op(self, inputs, eval_points):
if eval_points[0] is None or eval_points[1] is None:
return [None]
# Again we ignore eval points for indices because incsubtensor is
# not differentiable wrt to those
return self(eval_points[0], eval_points[1], *inputs[2:],
**dict(return_list=True))
def connection_pattern(self, node):
rval = [[True], [True]]
for ipt in node.inputs[2:]:
rval.append([False])
return rval
def grad(self, inputs, grads):
g_output, = grads
x, y = inputs[:2]
idx_list = inputs[2:]
if x.dtype in theano.tensor.discrete_dtypes:
# The output dtype is the same as x
gx = x.zeros_like(dtype=theano.config.floatX)
if y.dtype in theano.tensor.discrete_dtypes:
gy = y.zeros_like(dtype=theano.config.floatX)
else:
gy = y.zeros_like()
elif x.dtype in theano.tensor.complex_dtypes:
raise NotImplementedError("No support for complex grad yet")
else:
if self.set_instead_of_inc:
gx = set_subtensor(
Subtensor(idx_list=self.idx_list)(g_output, *idx_list),
theano.tensor.zeros_like(y))
else:
gx = g_output
gy = Subtensor(idx_list=self.idx_list)(g_output, *idx_list)
gy = _sum_grad_over_bcasted_dims(y, gy)
return [gx, gy] + [DisconnectedType()()] * len(idx_list)
def _sum_grad_over_bcasted_dims(x, gx):
"""Sum of gx over dimensions to reproduce x.broadcastable.
This is useful to sum gradients over certain dimensions when
x has been broadcasted, and we need to sum the gradient contributions
over all duplications.
"""
if gx.broadcastable != x.broadcastable:
x_dim_added = gx.ndim - x.ndim
x_broad = (True,) * x_dim_added + x.broadcastable
assert sum(gx.broadcastable) < sum(x_broad)
axis_to_sum = []
for i in xrange(gx.ndim):
if gx.broadcastable[i] is False and x_broad[i] is True:
axis_to_sum.append(i)
elif (gx.broadcastable[i] is True and
x_broad[i] is False):
# This means that Theano was able to infer that
# gx.shape[i] is 1, so x.shape[i] is 1, but we
# didn't know it. It is fine.
pass
else:
assert gx.broadcastable[i] == x_broad[i]
gx = gx.sum(axis=axis_to_sum, keepdims=True)
if gx.ndim != x.ndim:
assert gx.ndim > x.ndim
for i in xrange(x_dim_added):
assert gx.broadcastable[i]
gx = gx.dimshuffle(*list(range(x_dim_added, gx.ndim)))
assert gx.broadcastable == x.broadcastable
return gx
#########################
# Advanced indexing
#########################
#
# Should reproduce numpy's behaviour, see url:
# docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing
class AdvancedSubtensor1(Op):
"""Implement x[ilist] where ilist is a vector of integers."""
# sparse_grad doesn't go in here since it only affects the output
# of the grad() method.
__props__ = ()
_f16_ok = True
def __init__(self, sparse_grad=False):
self.sparse_grad = sparse_grad
def make_node(self, x, ilist):
x_ = theano.tensor.as_tensor_variable(x)
ilist_ = theano.tensor.as_tensor_variable(ilist)
if ilist_.type.dtype[:3] not in ('int', 'uin'):
raise TypeError('index must be integers')
if ilist_.type.ndim != 1:
raise TypeError('index must be vector')
if x_.type.ndim == 0:
raise TypeError('cannot index into a scalar')
bcast = (ilist_.broadcastable[0],) + x_.broadcastable[1:]
return Apply(self, [x_, ilist_], [TensorType(dtype=x.dtype,
broadcastable=bcast)()])
def perform(self, node, inp, out_):
x, i = inp
out, = out_
# Copy always implied by numpy advanced indexing semantic.
if out[0] is not None and out[0].shape == (len(i),) + x.shape[1:]:
o = out[0]
else:
o = None
# If i.dtype is more precise than numpy.intp (int32 on 32-bit machines,
# int64 on 64-bit machines), numpy may raise the following error:
# TypeError: array cannot be safely cast to required type.
# We need to check if values in i can fit in numpy.intp, because
# if they don't, that should be an error (no array can have that
# many elements on a 32-bit arch).
if i.dtype != numpy.intp:
i_ = theano._asarray(i, dtype=numpy.intp)
if not numpy.can_cast(i.dtype, numpy.intp):
# Check if there was actually an incorrect conversion
if numpy.any(i != i_):
raise IndexError(
'index contains values that are bigger '
'than the maximum array size on this system.', i)
i = i_
out[0] = x.take(i, axis=0, out=o)
def connection_pattern(self, node):
rval = [[True]]
for ipt in node.inputs[1:]:
rval.append([False])
return rval
def grad(self, inputs, grads):
global sparse_module_ref
x, ilist = inputs
gz, = grads
assert len(inputs) == 2
if self.sparse_grad:
if x.type.ndim != 2:
raise TypeError(
"AdvancedSubtensor1: you can't take the sparse grad"
" from a tensor with ndim != 2. ndim is " +
str(x.type.ndim))
if sparse_module_ref is None:
import theano.sparse as sparse_module_ref
rval1 = [sparse_module_ref.construct_sparse_from_list(x, gz,
ilist)]
else:
rval1 = [advanced_inc_subtensor1(x.zeros_like(), gz, ilist)]
return rval1 + [DisconnectedType()()] * (len(inputs) - 1)
def R_op(self, inputs, eval_points):
if eval_points[0] is None:
return [None]
return self.make_node(eval_points[0], *inputs[1:]).outputs
def infer_shape(self, node, ishapes):
x, ilist = ishapes
return [ilist + x[1:]]
def c_support_code(self):
# In some versions of numpy, NPY_MIN_INTP is defined as MIN_LONG,
# which is not defined. It should be NPY_MIN_LONG instead in that case.
return dedent("""\
#ifndef MIN_LONG
#define MIN_LONG NPY_MIN_LONG
#endif""")
def c_code(self, node, name, input_names, output_names, sub):
if self.__class__ is not AdvancedSubtensor1:
raise MethodNotDefined(
"c_code defined for AdvancedSubtensor1,"
" not for child class", type(self))
a_name, i_name = input_names[0], input_names[1]
output_name = output_names[0]
fail = sub['fail']
return """
PyArrayObject *indices;
int i_type = PyArray_TYPE(%(i_name)s);
if (i_type != NPY_INTP) {
// Cast %(i_name)s to NPY_INTP (expected by PyArray_TakeFrom),
// if all values fit.
if (!PyArray_CanCastSafely(i_type, NPY_INTP)) {
npy_int64 min_val, max_val;
PyObject* py_min_val = PyArray_Min(%(i_name)s, NPY_MAXDIMS,
NULL);
if (py_min_val == NULL) {
%(fail)s;
}
min_val = PyLong_AsLongLong(py_min_val);
Py_DECREF(py_min_val);
if (min_val == -1 && PyErr_Occurred()) {
%(fail)s;
}
PyObject* py_max_val = PyArray_Max(%(i_name)s, NPY_MAXDIMS,
NULL);
if (py_max_val == NULL) {
%(fail)s;
}
max_val = PyLong_AsLongLong(py_max_val);
Py_DECREF(py_max_val);
if (max_val == -1 && PyErr_Occurred()) {
%(fail)s;
}
if (min_val < NPY_MIN_INTP || max_val > NPY_MAX_INTP) {
PyErr_SetString(PyExc_IndexError,
"Index contains values "
"that are bigger than the maximum array "
"size on this system.");
%(fail)s;
}
}
indices = (PyArrayObject*) PyArray_Cast(%(i_name)s, NPY_INTP);
if (indices == NULL) {
%(fail)s;
}
}
else {
indices = %(i_name)s;
Py_INCREF(indices);
}
if (%(output_name)s != NULL) {
npy_intp nd, i, *shape;
nd = PyArray_NDIM(%(a_name)s) + PyArray_NDIM(indices) - 1;
if (PyArray_NDIM(%(output_name)s) != nd) {
Py_CLEAR(%(output_name)s);
}
else {
shape = PyArray_DIMS(%(output_name)s);
for (i = 0; i < PyArray_NDIM(indices); i++) {
if (shape[i] != PyArray_DIMS(indices)[i]) {
Py_CLEAR(%(output_name)s);
break;
}
}
if (%(output_name)s != NULL) {
for (; i < nd; i++) {
if (shape[i] != PyArray_DIMS(%(a_name)s)[
i-PyArray_NDIM(indices)+1]) {
Py_CLEAR(%(output_name)s);
break;
}
}
}
}
}
%(output_name)s = (PyArrayObject*)PyArray_TakeFrom(
%(a_name)s, (PyObject*)indices, 0, %(output_name)s, NPY_RAISE);
Py_DECREF(indices);
if (%(output_name)s == NULL) %(fail)s;
""" % locals()
def c_code_cache_version(self):
return (0, 1, 1)
advanced_subtensor1 = AdvancedSubtensor1()
class AdvancedIncSubtensor1(Op):
"""Increments a subtensor using advanced slicing (list of index)"""
__props__ = ('inplace', 'set_instead_of_inc')
def __init__(self, inplace=False, set_instead_of_inc=False):
self.inplace = inplace
self.set_instead_of_inc = set_instead_of_inc
if inplace:
self.destroy_map = {0: [0]}
def clone_inplace(self):
return self.__class__(
inplace=True,
set_instead_of_inc=self.set_instead_of_inc)
def __str__(self):
if self.inplace:
msg = "inplace"
else:
msg = "no_inplace"
if self.set_instead_of_inc:
msg += ",set"
else:
msg += ",inc"
return self.__class__.__name__ + "{%s}" % msg
def make_node(self, x, y, ilist):
x_ = theano.tensor.as_tensor_variable(x)
y_ = theano.tensor.as_tensor_variable(y)
ilist_ = theano.tensor.as_tensor_variable(ilist)
if ilist_.type.dtype[:3] not in ('int', 'uin'):
raise TypeError('index must be integers')
if ilist_.type.ndim != 1:
raise TypeError('index must be vector')
if x_.type.ndim == 0:
raise TypeError('cannot index into a scalar')
if y_.type.ndim > x_.type.ndim:
if self.set_instead_of_inc:
opname = 'set'
else:
opname = 'increment'
raise TypeError(
'cannot %s x subtensor with ndim=%s'
' by y with ndim=%s to x subtensor with ndim=%s ' % (
opname, x_.type.ndim, y_.type.ndim))
return Apply(self, [x_, y_, ilist_], [x_.type()])
def copy_of_x(self, x):
"""
:param x: a string giving the name of a C variable
pointing to an array
:return: C code expression to make a copy of x
Base class uses PyArrayObject *, subclasses may override for
different types of arrays.
"""
# Parameters of PyArrary_FromAny are:
# array
# dtype: we pass NULL to say any dtype is acceptable, so the existing
# dtype will be copied
# min_depth: we pass 0 to have this parameter ignored
# max_depth: we pass 0 to have this parameter ignored
# requirements: here we pass NPY_ARRAY_ENSURECOPY to force a copy
# context: this is almost always NULL, I'm not sure what it's used for
return """(PyArrayObject*)PyArray_FromAny(py_%(x)s, NULL, 0, 0,
NPY_ARRAY_ENSURECOPY, NULL)""" % locals()
def c_support_code(self):
from theano.gof.cutils import compile_cutils_code
return compile_cutils_code()
def c_code(self, node, name, input_names, output_names, sub):
numpy_ver = [int(n) for n in numpy.__version__.split('.')[:2]]
if bool(numpy_ver < [1, 8]):
raise NotImplementedError
x, y, idx = input_names
out = output_names[0]
fail = sub['fail']
inc_or_set = 1 - self.set_instead_of_inc
if self.inplace: # convert bool to int
inplace = 1
else:
inplace = 0
copy_of_x = self.copy_of_x(x)
return """
if (%(inplace)s)
{
if (%(x)s != %(out)s)
{
Py_XDECREF(%(out)s);
Py_INCREF(%(x)s);
%(out)s = %(x)s;
}
}
else
{
Py_XDECREF(%(out)s);
%(out)s = %(copy_of_x)s;
}
PyObject *arglist = Py_BuildValue("OOOi",%(out)s, %(idx)s, %(y)s, %(inc_or_set)d);
inplace_increment(NULL, arglist);
Py_XDECREF(arglist);
""" % locals()
def c_code_cache_version(self):
return (1,)
def perform(self, node, inp, out_):
# TODO opt to make this inplace
x, y, idx = inp
out, = out_
if not self.inplace:
x = x.copy()
# In Numpy, x[idx] += y doesn't work if the same index is present
# many times: it does it only once. Is it a bug? In any case, for
# this reason we implement our own 'inc' iteration.
if self.set_instead_of_inc:
x[idx] = y
else:
increment = inplace_increment
if increment is None:
increment = self.inplace_increment1d_slow
increment(x, idx, y)
out[0] = x
def inplace_increment1d_slow(self, x, idx, y):
# If `y` has as many dimensions as `x`, then we want to iterate
# jointly on `x` and `y`. Otherwise, it means `y` should be
# broadcasted to fill all relevant rows of `x`.
assert y.ndim <= x.ndim # Should be guaranteed by `make_node`
if y.ndim == x.ndim:
if len(y) == 1:
# Allow broadcasting of y[0]
y_0 = y[0]
for i in idx:
x[i] += y_0
else:
assert len(y) == len(idx)
j = 0
for i in idx:
x[i] += y[j]
j += 1
else:
for i in idx:
x[i] += y
def infer_shape(self, node, ishapes):
x, y, ilist = ishapes
return [x]
def R_op(self, inputs, eval_points):
if None in eval_points[:2]:
return [None]
return self.make_node(eval_points[0], eval_points[1],
*inputs[2:]).outputs
def connection_pattern(self, node):
rval = [[True], [True], [False]]
return rval
def grad(self, inputs, grads):
g_output, = grads
x, y, idx_list = inputs
if x.dtype in theano.tensor.discrete_dtypes:
# The output dtype is the same as x
gx = x.zeros_like(dtype=theano.config.floatX)
if y.dtype in theano.tensor.discrete_dtypes:
gy = y.zeros_like(dtype=theano.config.floatX)
else:
gy = y.zeros_like()
elif x.dtype in theano.tensor.complex_dtypes:
raise NotImplementedError("No support for complex grad yet")
else:
if self.set_instead_of_inc:
gx = advanced_set_subtensor1(
g_output,
y.zeros_like(),
idx_list)
else:
gx = g_output
gy = advanced_subtensor1(g_output, idx_list)
gy = _sum_grad_over_bcasted_dims(y, gy)
return [gx, gy] + [DisconnectedType()()]
advanced_inc_subtensor1 = AdvancedIncSubtensor1()
advanced_set_subtensor1 = AdvancedIncSubtensor1(set_instead_of_inc=True)
def as_index_variable(idx):
if idx is None:
return NoneConst.clone()
if isinstance(idx, slice):
return make_slice(idx)
if isinstance(idx, gof.Variable) and isinstance(idx.type, SliceType):
return idx
idx = theano.tensor.as_tensor_variable(idx)
if idx.type.dtype[:3] not in ('int', 'uin'):
raise TypeError('index must be integers')
return idx
def adv_index_broadcastable_pattern(a, idx):
"""
This function is only used to determine the broadcast pattern for
AdvancedSubtensor output variable.
For this, we make a fake ndarray and a fake idx and call use ask numpy
the output. From this, we find the output broadcast pattern.
"""
def replace_slice(v):
if isinstance(v, gof.Apply):
if len(v.outputs) != 1:
raise ValueError(
"It is ambiguous which output of a multi-output Op has"
" to be fetched.", v)
else:
v = v.outputs[0]
if NoneConst.equals(v):
return None
if isinstance(v.type, SliceType):
return slice(None, None)
return numpy.zeros((2,) * v.ndim, int)
newidx = tuple(map(replace_slice, idx))
# 2 - True = 1; 2 - False = 2
fakeshape = [2 - bc for bc in a.broadcastable]
retshape = numpy.empty(fakeshape)[newidx].shape
return tuple([dim == 1 for dim in retshape])
class AdvancedSubtensor(Op):
"""Return a subtensor copy, using advanced indexing.
"""
# Should be used by __getitem__ and __getslice__, as follow:
# AdvancedSubtensor()(self, *args),
# if args contains and advanced indexing pattern
__props__ = ()
def make_node(self, x, *index):
x = theano.tensor.as_tensor_variable(x)
index = tuple(map(as_index_variable, index))
bcast = adv_index_broadcastable_pattern(x, index)
return gof.Apply(self,
(x,) + index,
[theano.tensor.tensor(dtype=x.type.dtype,
broadcastable=bcast)])
def R_op(self, inputs, eval_points):
if eval_points[0] is None:
return [None]
return self.make_node(eval_points[0], *inputs[1:]).outputs
def infer_shape(self, node, ishapes):
# Really special case
if len(ishapes) == 3:
xshp, ind1shp, ind2shp = ishapes
if (len(xshp) == 2 and
ind1shp is not None and len(ind1shp) == 1 and
ind2shp is not None and len(ind2shp) == 1):
# if the graph is correct, we can assume ind1shp[0] and
# ind2shp[0] will have the same value.
# Try to return the one closest to the graph input.
if node.inputs[2].owner is None:
return [ind2shp]
else:
return [ind1shp]
# Default case, we don't know
raise theano.tensor.basic.ShapeError("case not implemented")
def perform(self, node, inputs, out_):
out, = out_
# TODO: in general, we need to re-pack the inputs into a valid
# index, just like subtensor
out[0] = inputs[0].__getitem__(inputs[1:])
if (numpy.__version__ <= '1.6.1' and
out[0].size != numpy.uint32(out[0].size)):
warnings.warn(
'Numpy versions 1.6.1 and below have a bug preventing '
'advanced indexing from correctly filling arrays that '
'are too big (>= 2^32 elements). It is possible that '
'out[0] (%s), with shape %s, is not correctly filled.'
% (out[0], out[0].shape))
def connection_pattern(self, node):
rval = [[True]]
for ipt in node.inputs[1:]:
rval.append([False])
return rval
def grad(self, inputs, grads):
gz, = grads
x = inputs[0]
rest = inputs[1:]
return [advanced_inc_subtensor(theano.tensor.zeros_like(x), gz,
*rest)] + \
[DisconnectedType()()] * len(rest)
advanced_subtensor = AdvancedSubtensor()
class AdvancedIncSubtensor(Op):
"""Increments a subtensor using advanced indexing.
:note: We need the numpy.inplace_increment() function currently
numpy's PR 326 to be able to make an inplace version of this
op.
"""
__props__ = ("inplace", "set_instead_of_inc")
def __init__(self, inplace=False, set_instead_of_inc=False):
self.inplace = inplace
self.set_instead_of_inc = set_instead_of_inc
# The assert is needed as in the pass the first argument was
# something else that was not used.
assert isinstance(inplace, bool)
if self.inplace:
raise NotImplementedError('In place computation is not'
' implemented')
self.allow_legacy_perform = False
def __str__(self):
return "%s{%s, %s}" % (self.__class__.__name__,
"inplace=" + str(self.inplace),
" set_instead_of_inc=" +
str(self. set_instead_of_inc))
def make_node(self, x, y, *inputs):
x = theano.tensor.as_tensor_variable(x)
y = theano.tensor.as_tensor_variable(y)
op = self
# If we are incrementing, but the increment compiled function is not
# available, we need to support legacy cases.
if not self.set_instead_of_inc and inplace_increment is None:
legacy_conditions = False
if x.ndim == 2 and y.ndim == 1 and len(inputs) == 2:
ind1 = theano.tensor.as_tensor_variable(inputs[0])
ind2 = theano.tensor.as_tensor_variable(inputs[1])
if ind1.ndim == 1 and ind2.ndim == 1:
if ind1.owner and isinstance(ind1.owner.op, ARange):
legacy_conditions = True
elif isinstance(ind1, Constant):
# Make sure no index is duplicated
val = ind1.value
if numpy.unique(val).size == val.size:
legacy_conditions = True
elif ind2.owner and isinstance(ind2.owner.op, ARange):
legacy_conditions = True
elif isinstance(ind2, Constant):
# Make sure no index is duplicated
val = ind2.value
if numpy.unique(val).size == val.size:
legacy_conditions = True
if legacy_conditions:
op = copy(self)
op.allow_legacy_perform = True
else:
raise NotImplementedError(
'Could not import inplace_increment, so some advanced '
'indexing features are disabled. They will be '
'available if you update NumPy to version 1.8 or '
'later, or to the latest development version. '
'You may need to clear the cache (theano-cache clear) '
'afterwards.')
new_inputs = []
for inp in inputs:
if isinstance(inp, (list, tuple)):
inp = theano.tensor.as_tensor_variable(inp)
new_inputs.append(inp)
return gof.Apply(op,
(x, y) + tuple(new_inputs),
[theano.tensor.tensor(
dtype=x.type.dtype,
broadcastable=x.type.broadcastable)])
def perform(self, node, inputs, out_):
# TODO: 1. opt to make this in place 2. generalize as described in
# AdvancedSubtensor's perform TODO
out, = out_
if not self.inplace:
out[0] = inputs[0].copy()
else:
out[0] = inputs[0]
if self.set_instead_of_inc:
out[0][inputs[2:]] = inputs[1]
elif inplace_increment is not None:
inplace_increment(out[0], tuple(inputs[2:]), inputs[1])
elif self.allow_legacy_perform:
out[0][inputs[2:]] += inputs[1]
else:
raise NotImplementedError(
'Could not import inplace_increment, so some advanced '
'indexing features are disabled. They will be '
'available if you update NumPy to version 1.8 or '
'later, or to the latest development version. '
'You may need to clear the cache (theano-cache clear) '
'afterwards.')
if (numpy.__version__ <= '1.6.1' and
out[0].size != numpy.uint32(out[0].size)):
warnings.warn(
'Numpy versions 1.6.1 and below have a bug preventing '
'advanced indexing from correctly filling arrays that '
'are too big (>= 2^32 elements). It is possible that '
'out[0] (%s), with shape %s, is not correctly filled.'
% (out[0], out[0].shape))
def infer_shape(self, node, ishapes):
return [ishapes[0]]
def connection_pattern(self, node):
rval = [[True], [True]]
for ipt in node.inputs[2:]:
rval.append([False])
return rval
def grad(self, inpt, output_gradients):
x, y = inpt[:2]
idxs = inpt[2:]
outgrad, = output_gradients
if x.dtype in theano.tensor.discrete_dtypes:
# The output dtype is the same as x
gx = x.zeros_like(dtype=theano.config.floatX)
if y.dtype in theano.tensor.discrete_dtypes:
gy = y.zeros_like(dtype=theano.config.floatX)
else:
gy = y.zeros_like()
elif x.dtype in theano.tensor.complex_dtypes:
raise NotImplementedError("No support for complex grad yet")
else:
if self.set_instead_of_inc:
gx = advanced_set_subtensor(
outgrad,
y.zeros_like(),
*idxs)
else:
gx = outgrad
gy = advanced_subtensor(outgrad, *idxs)
# Make sure to sum gy over the dimensions of y that have been
# added or broadcasted
gy = _sum_grad_over_bcasted_dims(y, gy)
return [gx, gy] + \
[DisconnectedType()() for _ in idxs]
def R_op(self, inputs, eval_points):
if None in eval_points[:2]:
return [None]
return self.make_node(eval_points[0], eval_points[1],
*inputs[2:]).outputs
advanced_inc_subtensor = AdvancedIncSubtensor()
advanced_set_subtensor = AdvancedIncSubtensor(set_instead_of_inc=True)
def take(a, indices, axis=None, mode='raise'):
a = theano.tensor.as_tensor_variable(a)
indices = theano.tensor.as_tensor_variable(indices)
# Reuse advanced_subtensor1 if indices is a vector
if indices.ndim == 1:
if mode == 'clip':
indices = clip(indices, 0, a.shape[axis] - 1)
elif mode == 'wrap':
indices = indices % a.shape[axis]
if axis is None:
return advanced_subtensor1(a.flatten(), indices)
elif axis == 0:
return advanced_subtensor1(a, indices)
else:
if axis < 0:
axis += a.ndim
assert axis >= 0
shuffle = list(range(a.ndim))
shuffle[0] = axis
shuffle[axis] = 0
return advanced_subtensor1(
a.dimshuffle(shuffle), indices).dimshuffle(shuffle)
if axis is None:
shape = indices.shape
ndim = indices.ndim
else:
# If axis is 0, don't generate a useless concatenation.
if axis == 0:
shape = theano.tensor.concatenate(
[indices.shape, a.shape[axis + 1:]])
else:
shape = theano.tensor.concatenate(
[a.shape[:axis], indices.shape, a.shape[axis + 1:]])
ndim = a.ndim + indices.ndim - 1
return take(a, indices.flatten(), axis, mode).reshape(shape, ndim)
|
nke001/attention-lvcsr
|
libs/Theano/theano/tensor/subtensor.py
|
Python
|
mit
| 84,816
|
<?php
/*
* This file is part of the webmozart/expression package.
*
* (c) Bernhard Schussek <bschussek@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Webmozart\Expression\Tests\Logic;
use PHPUnit_Framework_TestCase;
use Webmozart\Expression\Comparison\GreaterThan;
use Webmozart\Expression\Comparison\LessThan;
use Webmozart\Expression\Comparison\StartsWith;
use Webmozart\Expression\Logic\Disjunction;
use Webmozart\Expression\Logic\Not;
/**
* @since 1.0
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class NotTest extends PHPUnit_Framework_TestCase
{
public function testEvaluate()
{
$expr = new Not(new StartsWith('Thomas'));
$this->assertTrue($expr->evaluate('Mr. Thomas Edison'));
$this->assertFalse($expr->evaluate('Thomas Edison'));
}
public function testEquivalentTo()
{
$expr1 = new Not(new Disjunction(array(new LessThan(0), new GreaterThan(10))));
$expr2 = new Not(new Disjunction(array(new GreaterThan(10), new LessThan(0))));
$expr3 = new Not(new Disjunction(array(new GreaterThan(10))));
$this->assertTrue($expr1->equivalentTo($expr2));
$this->assertFalse($expr2->equivalentTo($expr3));
$this->assertFalse($expr1->equivalentTo($expr3));
}
public function testToString()
{
$expr1 = new Not(new StartsWith('Thomas'));
$expr2 = new Not(new Disjunction(array(new GreaterThan(10), new LessThan(0))));
$this->assertSame('not(startsWith("Thomas"))', $expr1->toString());
$this->assertSame('not(>10 || <0)', $expr2->toString());
}
}
|
mickaelandrieu/expression
|
tests/Logic/NotTest.php
|
PHP
|
mit
| 1,710
|
define([
"dojo/_base/array", // array.indexOf
"dojo/_base/declare", // declare
"dojo/dom", // dom.isDescendant domClass.replace
"dojo/dom-attr",
"dojo/dom-class", // domClass.replace
"dojo/_base/lang", // lang.hitch
"dojo/mouse", // mouse.enter, mouse.leave
"dojo/on",
"dojo/window",
"./a11yclick",
"./popup",
"./registry",
"./_Widget",
"./_CssStateMixin",
"./_KeyNavContainer",
"./_TemplatedMixin"
], function(array, declare, dom, domAttr, domClass, lang, mouse, on, winUtils, a11yclick, pm,
registry, _Widget, _CssStateMixin, _KeyNavContainer, _TemplatedMixin){
// module:
// dijit/_MenuBase
return declare("dijit._MenuBase", [_Widget, _TemplatedMixin, _KeyNavContainer, _CssStateMixin], {
// summary:
// Base class for Menu and MenuBar
// parentMenu: [readonly] Widget
// pointer to menu that displayed me
parentMenu: null,
// popupDelay: Integer
// number of milliseconds before hovering (without clicking) causes the popup to automatically open.
popupDelay: 500,
// autoFocus: Boolean
// A toggle to control whether or not a Menu gets focused when opened as a drop down from a MenuBar
// or DropDownButton/ComboButton. Note though that it always get focused when opened via the keyboard.
autoFocus: false,
childSelector: function(/*DOMNode*/ node){
// summary:
// Selector (passed to on.selector()) used to identify MenuItem child widgets, but exclude inert children
// like MenuSeparator. If subclass overrides to a string (ex: "> *"), the subclass must require dojo/query.
// tags:
// protected
var widget = registry.byNode(node);
return node.parentNode == this.containerNode && widget && widget.focus;
},
postCreate: function(){
var self = this,
matches = typeof this.childSelector == "string" ? this.childSelector : lang.hitch(this, "childSelector");
this.own(
on(this.containerNode, on.selector(matches, mouse.enter), function(){
self.onItemHover(registry.byNode(this));
}),
on(this.containerNode, on.selector(matches, mouse.leave), function(){
self.onItemUnhover(registry.byNode(this));
}),
on(this.containerNode, on.selector(matches, a11yclick), function(evt){
self.onItemClick(registry.byNode(this), evt);
evt.stopPropagation();
evt.preventDefault();
})
);
this.inherited(arguments);
},
onKeyboardSearch: function(/*MenuItem*/ item, /*Event*/ evt, /*String*/ searchString, /*Number*/ numMatches){
// summary:
// Attach point for notification about when a menu item has been searched for
// via the keyboard search mechanism.
// tags:
// protected
this.inherited(arguments);
if(!!item && (numMatches == -1 || (!!item.popup && numMatches == 1))){
this.onItemClick(item, evt);
}
},
_keyboardSearchCompare: function(/*dijit/_WidgetBase*/ item, /*String*/ searchString){
// summary:
// Compares the searchString to the widget's text label, returning:
// -1: a high priority match and stop searching
// 0: no match
// 1: a match but keep looking for a higher priority match
// tags:
// private
if(!!item.shortcutKey){
// accessKey matches have priority
return searchString == item.shortcutKey.toLowerCase() ? -1 : 0;
}
return this.inherited(arguments) ? 1 : 0; // change return value of -1 to 1 so that searching continues
},
onExecute: function(){
// summary:
// Attach point for notification about when a menu item has been executed.
// This is an internal mechanism used for Menus to signal to their parent to
// close them, because they are about to execute the onClick handler. In
// general developers should not attach to or override this method.
// tags:
// protected
},
onCancel: function(/*Boolean*/ /*===== closeAll =====*/){
// summary:
// Attach point for notification about when the user cancels the current menu
// This is an internal mechanism used for Menus to signal to their parent to
// close them. In general developers should not attach to or override this method.
// tags:
// protected
},
_moveToPopup: function(/*Event*/ evt){
// summary:
// This handles the right arrow key (left arrow key on RTL systems),
// which will either open a submenu, or move to the next item in the
// ancestor MenuBar
// tags:
// private
if(this.focusedChild && this.focusedChild.popup && !this.focusedChild.disabled){
this.onItemClick(this.focusedChild, evt);
}else{
var topMenu = this._getTopMenu();
if(topMenu && topMenu._isMenuBar){
topMenu.focusNext();
}
}
},
_onPopupHover: function(/*Event*/ /*===== evt =====*/){
// summary:
// This handler is called when the mouse moves over the popup.
// tags:
// private
// if the mouse hovers over a menu popup that is in pending-close state,
// then stop the close operation.
// This can't be done in onItemHover since some popup targets don't have MenuItems (e.g. ColorPicker)
if(this.currentPopup && this.currentPopup._pendingClose_timer){
var parentMenu = this.currentPopup.parentMenu;
// highlight the parent menu item pointing to this popup
if(parentMenu.focusedChild){
parentMenu.focusedChild._setSelected(false);
}
parentMenu.focusedChild = this.currentPopup.from_item;
parentMenu.focusedChild._setSelected(true);
// cancel the pending close
this._stopPendingCloseTimer(this.currentPopup);
}
},
onItemHover: function(/*MenuItem*/ item){
// summary:
// Called when cursor is over a MenuItem.
// tags:
// protected
// Don't do anything unless user has "activated" the menu by:
// 1) clicking it
// 2) opening it from a parent menu (which automatically focuses it)
if(this.isActive){
this.focusChild(item);
if(item.popup && !item.disabled && !this.hover_timer){
this.hover_timer = this.defer(lang.hitch(this, "_openPopup", item), this.popupDelay);
}
}
// if the user is mixing mouse and keyboard navigation,
// then the menu may not be active but a menu item has focus,
// but it's not the item that the mouse just hovered over.
// To avoid both keyboard and mouse selections, use the latest.
if(this.focusedChild){
this.focusChild(item);
}
this._hoveredChild = item;
item._set("hovering", true);
},
_onChildBlur: function(item){
// summary:
// Called when a child MenuItem becomes inactive because focus
// has been removed from the MenuItem *and* it's descendant menus.
// tags:
// private
this._stopPopupTimer();
item._setSelected(false);
// Close all popups that are open and descendants of this menu
var itemPopup = item.popup;
if(itemPopup){
this._stopPendingCloseTimer(itemPopup);
itemPopup._pendingClose_timer = this.defer(function(){
itemPopup._pendingClose_timer = null;
if(itemPopup.parentMenu){
itemPopup.parentMenu.currentPopup = null;
}
pm.close(itemPopup); // this calls onClose
}, this.popupDelay);
}
},
onItemUnhover: function(/*MenuItem*/ item){
// summary:
// Callback fires when mouse exits a MenuItem
// tags:
// protected
if(this.isActive){
this._stopPopupTimer();
}
if(this._hoveredChild == item){
this._hoveredChild = null;
}
item._set("hovering", false);
},
_stopPopupTimer: function(){
// summary:
// Cancels the popup timer because the user has stop hovering
// on the MenuItem, etc.
// tags:
// private
if(this.hover_timer){
this.hover_timer = this.hover_timer.remove();
}
},
_stopPendingCloseTimer: function(/*dijit/_WidgetBase*/ popup){
// summary:
// Cancels the pending-close timer because the close has been preempted
// tags:
// private
if(popup._pendingClose_timer){
popup._pendingClose_timer = popup._pendingClose_timer.remove();
}
},
_stopFocusTimer: function(){
// summary:
// Cancels the pending-focus timer because the menu was closed before focus occured
// tags:
// private
if(this._focus_timer){
this._focus_timer = this._focus_timer.remove();
}
},
_getTopMenu: function(){
// summary:
// Returns the top menu in this chain of Menus
// tags:
// private
for(var top = this; top.parentMenu; top = top.parentMenu){
;
}
return top;
},
onItemClick: function(/*dijit/_WidgetBase*/ item, /*Event*/ evt){
// summary:
// Handle clicks on an item.
// tags:
// private
// this can't be done in _onFocus since the _onFocus events occurs asynchronously
if(typeof this.isShowingNow == 'undefined'){ // non-popup menu
this._markActive();
}
this.focusChild(item);
if(item.disabled){
return false;
}
if(item.popup){
this._openPopup(item, /^key/.test(evt.type));
}else{
// before calling user defined handler, close hierarchy of menus
// and restore focus to place it was when menu was opened
this.onExecute();
// user defined handler for click
item._onClick ? item._onClick(evt) : item.onClick(evt);
}
},
_openPopup: function(/*dijit/MenuItem*/ from_item, /*Boolean*/ focus){
// summary:
// Open the popup to the side of/underneath the current menu item, and optionally focus first item
// tags:
// protected
this._stopPopupTimer();
var popup = from_item.popup;
if(!popup.isShowingNow){
if(this.currentPopup){
this._stopPendingCloseTimer(this.currentPopup);
pm.close(this.currentPopup);
}
popup.parentMenu = this;
popup.from_item = from_item; // helps finding the parent item that should be focused for this popup
var self = this;
pm.open({
parent: this,
popup: popup,
around: from_item.domNode,
orient: this._orient || ["after", "before"],
onCancel: function(){ // called when the child menu is canceled
// set isActive=false (_closeChild vs _cleanUp) so that subsequent hovering will NOT open child menus
// which seems aligned with the UX of most applications (e.g. notepad, wordpad, paint shop pro)
self.focusChild(from_item); // put focus back on my node
self._cleanUp(); // close the submenu (be sure this is done _after_ focus is moved)
from_item._setSelected(true); // oops, _cleanUp() deselected the item
self.focusedChild = from_item; // and unset focusedChild
},
onExecute: lang.hitch(this, "_cleanUp")
});
this.currentPopup = popup;
this.currentPopupParent = from_item;
// detect mouseovers to handle lazy mouse movements that temporarily focus other menu items
popup.own(on(popup.domNode, "mouseenter", lang.hitch(self, "_onPopupHover"))); // cleaned up when the popped-up widget is destroyed on close
}
if(focus && popup.focus){
// If user is opening the popup via keyboard (right arrow, or down arrow for MenuBar), then focus the popup.
// If the cursor happens to collide with the popup, it will generate an onmouseover event
// even though the mouse wasn't moved. Use defer() to call popup.focus so that
// our focus() call overrides the onmouseover event, rather than vice-versa. (#8742)
popup._focus_timer = this.defer(lang.hitch(popup, function(){
this._focus_timer = null;
this.focus();
}));
}
},
_markActive: function(){
// summary:
// Mark this menu's state as active.
// Called when this Menu gets focus from:
//
// 1. clicking it (mouse or via space/arrow key)
// 2. being opened by a parent menu.
//
// This is not called just from mouse hover.
// Focusing a menu via TAB does NOT automatically set isActive
// since TAB is a navigation operation and not a selection one.
// For Windows apps, pressing the ALT key focuses the menubar
// menus (similar to TAB navigation) but the menu is not active
// (ie no dropdown) until an item is clicked.
this.isActive = true;
domClass.replace(this.domNode, "dijitMenuActive", "dijitMenuPassive");
},
onOpen: function(/*Event*/ /*===== e =====*/){
// summary:
// Callback when this menu is opened.
// This is called by the popup manager as notification that the menu
// was opened.
// tags:
// private
this.isShowingNow = true;
this._markActive();
},
_markInactive: function(){
// summary:
// Mark this menu's state as inactive.
this.isActive = false; // don't do this in _onBlur since the state is pending-close until we get here
domClass.replace(this.domNode, "dijitMenuPassive", "dijitMenuActive");
},
onClose: function(){
// summary:
// Callback when this menu is closed.
// This is called by the popup manager as notification that the menu
// was closed.
// tags:
// private
this._stopFocusTimer();
this._markInactive();
this.isShowingNow = false;
this.parentMenu = null;
},
_closeChild: function(){
// summary:
// Called when submenu is clicked or focus is lost. Close hierarchy of menus.
// tags:
// private
this._stopPopupTimer();
if(this.currentPopup){
// If focus is on a descendant MenuItem then move focus to me,
// because IE doesn't like it when you display:none a node with focus,
// and also so keyboard users don't lose control.
// Likely, immediately after a user defined onClick handler will move focus somewhere
// else, like a Dialog.
if(this.focused){
domAttr.set(this.currentPopupParent.focusNode, "tabIndex", this.tabIndex);
this.currentPopupParent.focusNode.focus();
}
// Close all popups that are open and descendants of this menu
pm.close(this.currentPopup);
this.currentPopup = this.currentPopupParent = null;
}
if(this.focusedChild){ // unhighlight the focused item
this.focusedChild._setSelected(false);
this.onItemUnhover(this.focusedChild);
}
// Repeat what _KeyNavContainer.onBlur() does, so that the MenuBar gets treated as blurred even though the user
// hasn't clicked or focused anywhere outside of the MenuBar yet. Otherwise, the Menu code gets confused since
// the menu is in a passive state but this.focusedChild is still set.
domAttr.set(this.domNode, "tabIndex", this.tabIndex);
if(this.focusedChild){
this.focusedChild.set("tabIndex", "-1");
this._set("focusedChild", null);
}
},
_onItemFocus: function(/*MenuItem*/ item){
// summary:
// Called when child of this Menu gets focus from:
//
// 1. clicking it
// 2. tabbing into it
// 3. being opened by a parent menu.
//
// This is not called just from mouse hover.
if(this._hoveredChild && this._hoveredChild != item){
this.onItemUnhover(this._hoveredChild); // any previous mouse movement is trumped by focus selection
}
},
_onBlur: function(){
// summary:
// Called when focus is moved away from this Menu and it's submenus.
// tags:
// protected
this._cleanUp();
this.inherited(arguments);
},
_cleanUp: function(){
// summary:
// Called when the user is done with this menu. Closes hierarchy of menus.
// tags:
// private
this._closeChild(); // don't call this.onClose since that's incorrect for MenuBar's that never close
if(typeof this.isShowingNow == 'undefined'){ // non-popup menu doesn't call onClose
this._markInactive();
}
}
});
});
|
aguadev/aguadev
|
html/dojo-1.8.3/dijit/_MenuBase.js
|
JavaScript
|
mit
| 15,420
|
<?php
/**
* @link http://zoopcommerce.github.io/shard
* @package Zoop
* @license MIT
*/
namespace Zoop\Shard\Core;
use Doctrine\Common\Annotations\Reader;
use Doctrine\Common\EventArgs as BaseEventArgs;
use Doctrine\Common\EventManager as BaseEventManager;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
/**
*
* @since 1.0
* @author Tim Roediger <superdweebie@gmail.com>
*/
class LoadMetadataEventArgs extends BaseEventArgs
{
protected $metadata;
protected $parentMetadata;
protected $annotationReader;
protected $eventManager;
public function getMetadata()
{
return $this->metadata;
}
public function getParentMetadata()
{
return $this->parentMetadata;
}
public function getAnnotationReader()
{
return $this->annotationReader;
}
public function getEventManager()
{
return $this->eventManager;
}
public function __construct(
ClassMetadata $metadata,
array $parentMetadata,
Reader $annotationReader,
BaseEventManager $eventManager
) {
$this->metadata = $metadata;
$this->parentMetadata = $parentMetadata;
$this->annotationReader = $annotationReader;
$this->eventManager = $eventManager;
}
}
|
zoopcommerce/shard
|
lib/Zoop/Shard/Core/LoadMetadataEventArgs.php
|
PHP
|
mit
| 1,303
|
import { Item, Items, ODataEntityArray, ODataEntity, ODataParser, FetchOptions, Logger, LogLevel } from "sp-pnp-js";
import { select, expand } from "../sharepoint/utils/decorators";
import { SelectDecoratorsParser, SelectDecoratorsArrayParser } from "../sharepoint/parser/SelectDecoratorsParsers";
import { getSymbol } from "../sharepoint/utils/symbol";
export class FRS extends Item {
@select()
public ID: number;
@select()
public Title: string;
@select()
public Modified: Date;
@select()
public Created: Date;
@select()
public Author: string; //Пользователь или группа
@select()
public Editor: string; //Пользователь или группа
@select()
public RegionalTechnicalCenter: number;
@select()
public ProductAreas: number;
@select()
public SpecialistCategory: number;
@select()
public Town: string;
@select()
public BidSpecialist: string;
// override get to enfore select and expand for our fields to always optimize
public get(parser?: ODataParser<any>, getOptions?: FetchOptions): Promise<any> {
this
._setCustomQueryFromDecorator("select")
._setCustomQueryFromDecorator("expand");
if (parser === undefined) {
parser = ODataEntity(FRS);
}
return super.get.call(this, parser, getOptions);
}
// overrise getAs method with custom parser
public getAs<T>(parser?: ODataParser<any>, getOptions?: FetchOptions): Promise<T> {
this
._setCustomQueryFromDecorator("select")
._setCustomQueryFromDecorator("expand");
if (parser === undefined) {
parser = new SelectDecoratorsParser<FRS>(FRS);
}
return super.get.call(this, parser, getOptions);
}
private _setCustomQueryFromDecorator(parameter: string): FRS {
const sym: string = getSymbol(parameter);
// get pre-saved select and expand props from decorators
const arrayprops: { propName: string, queryName: string }[] = this[sym];
let list: string = "";
if (arrayprops !== undefined && arrayprops !== null) {
list = arrayprops.map(i => i.queryName).join(",");
} else {
Logger.log({
level: LogLevel.Warning,
message: "[_setCustomQueryFromDecorator] - empty property: " + parameter + "."
});
}
// use apply and call to manipulate the request into the form we want
// if another select isn't in place, let's default to only ever getting our fields.
// implement method chain
return this._query.getKeys().indexOf("$" + parameter) > -1
? this
: this[parameter].call(this, list);
}
}
export class FRSList extends Items {
private ItemTemplate: FRS = new FRS("");
public CustomCollectionProps: string = "Custom Collection Prop to pass";
// override get to enfore select and expand for our fields to always optimize
public get(parser?: ODataParser<any>, getOptions?: FetchOptions): Promise<any> {
// public get(): Promise<MyDocument> {
this
._setCustomQueryFromDecorator("select")
._setCustomQueryFromDecorator("expand");
if (parser === undefined) {
// default parser
parser = ODataEntityArray(FRS);
}
return super.get.call(this, parser, getOptions);
}
// create new method using custom parser
public getAsMyDocument(parser?: ODataParser<FRS[]>, getOptions?: FetchOptions): Promise<FRS[]> {
this
._setCustomQueryFromDecorator("select")
._setCustomQueryFromDecorator("expand");
if (parser === undefined) {
parser = new SelectDecoratorsArrayParser<FRS>(FRS);
}
return super.get.call(this, parser, getOptions);
}
private _setCustomQueryFromDecorator(parameter: string): FRSList {
const sym: string = getSymbol(parameter);
// get pre-saved select and expand props from decorators
const arrayprops: { propName: string, queryName: string }[] = this.ItemTemplate[sym];
let list: string = "";
if (arrayprops !== undefined && arrayprops !== null) {
list = arrayprops.map(i => i.queryName).join(",");
} else {
Logger.log({
level: LogLevel.Warning,
message: "[_setCustomQueryFromDecorator] - empty property: " + parameter + "."
});
}
// use apply and call to manipulate the request into the form we want
// if another select isn't in place, let's default to only ever getting our fields.
// implement method chain
return this._query.getKeys().indexOf("$" + parameter) > -1
? this
: this[parameter].call(this, list);
}
}
|
aTsirkov/sp-ng2-primeng
|
src/app/entities/frs.entities.ts
|
TypeScript
|
mit
| 4,904
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example of joining two rectangles</title>
<script type="application/javascript" src="../../build/diaframer.js"></script>
<script type="application/javascript" src="scripts/example.js"></script>
<style>
#canvas {
display: block;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<canvas id="canvas" height="700" width="800"></canvas>
</body>
</html>
|
saeschdivara/Diaframer
|
examples/join/index.html
|
HTML
|
mit
| 512
|
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 3.6
# Relative path conversion top directories.
set(CMAKE_RELATIVE_PATH_TOP_SOURCE "/Users/yujifan/CLionProjects/output route final")
set(CMAKE_RELATIVE_PATH_TOP_BINARY "/Users/yujifan/CLionProjects/output route final/cmake-build-debug")
# Force unix paths in dependencies.
set(CMAKE_FORCE_UNIX_PATHS 1)
# The C and CXX include file regular expressions for this directory.
set(CMAKE_C_INCLUDE_REGEX_SCAN "^.*$")
set(CMAKE_C_INCLUDE_REGEX_COMPLAIN "^$")
set(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN})
set(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN ${CMAKE_C_INCLUDE_REGEX_COMPLAIN})
|
framefreeze/HangDriver
|
lane_mentor/output_route_final/cmake-build-debug/CMakeFiles/CMakeDirectoryInformation.cmake
|
CMake
|
mit
| 687
|
import { vec2, vec3, vec4, quat, mat4 } from 'gl-matrix';
import toNDC from '../../util/toNDC';
export default class RotateMode {
constructor(entity, ndc, alignAxis = null) {
this.entity = entity;
this.startQuat = quat.create();
this.mouseHeld = true;
this.ndc = ndc;
this.angle = 0;
this.lastAngle = 0;
this.align = alignAxis != null;
this.alignAxis = alignAxis || [1, 1, 1];
this.alignGlobal = false;
}
enter(manager) {
this.manager = manager;
this.engine = manager.engine;
this.renderer = manager.renderer;
this.engine.actions.renderer.effect.add('axis');
this.setEffect();
let matrixSys = this.engine.systems.matrix;
let mat = matrixSys.get(this.entity);
mat4.getRotation(this.startQuat, mat);
quat.normalize(this.startQuat, this.startQuat);
this.camera = this.engine.systems.renderer.viewportList[0].camera;
let perspPos = vec4.fromValues(0, 0, 0, 1);
vec4.transformMat4(perspPos, perspPos,
this.engine.systems.matrix.get(this.entity));
vec4.transformMat4(perspPos, perspPos,
this.engine.systems.cameraMatrix.getProjectionView(this.camera));
let aspect = this.engine.systems.cameraMatrix.getCurrentAspect(this.camera);
vec4.scale(perspPos, perspPos, 1 / perspPos[3]);
vec2.subtract(perspPos, this.ndc, perspPos);
this.lastAngle = Math.atan2(perspPos[1], perspPos[0] * aspect);
}
exit() {
// Remove axis effect
this.engine.actions.renderer.effect.remove('axis');
}
setEffect() {
this.renderer.effects.axis.direction = this.align ? this.alignAxis : null;
this.renderer.effects.axis.color = this.align && this.alignAxis.concat([1]);
}
setRotation() {
let tmpQuat = quat.create();
let axis = this.alignAxis;
let modifier = 1;
// Shoot a ray from camera to model
let matrixSys = this.engine.systems.matrix;
let cameraPos = matrixSys.getPosition(this.camera);
let entityPos = matrixSys.getPosition(this.entity);
let cameraRay = vec3.create();
vec3.subtract(cameraRay, cameraPos, entityPos);
vec3.normalize(cameraRay, cameraRay);
if (!this.align) {
axis = cameraRay;
} else {
// Compare align axis and camera axis
let cos = vec3.dot(axis, cameraRay);
if (cos < 0) modifier = -1;
}
// Convert it to local space (if any)
let parentMat = matrixSys.getParent(this.entity);
let parentQuat = quat.create();
mat4.getRotation(parentQuat, parentMat);
quat.normalize(parentQuat, parentQuat);
quat.conjugate(parentQuat, parentQuat);
quat.setAxisAngle(tmpQuat, axis, this.angle * modifier);
quat.multiply(tmpQuat, parentQuat, tmpQuat);
quat.multiply(tmpQuat, tmpQuat, this.startQuat);
this.engine.actions.external.execute('transform.setRotation',
this.entity, tmpQuat);
}
mousemove(e) {
let ndc = toNDC(e.clientX, e.clientY, this.renderer);
this.ndc = ndc;
// Get angle :S
let perspPos = vec4.fromValues(0, 0, 0, 1);
vec4.transformMat4(perspPos, perspPos,
this.engine.systems.matrix.get(this.entity));
vec4.transformMat4(perspPos, perspPos,
this.engine.systems.cameraMatrix.getProjectionView(this.camera));
vec4.scale(perspPos, perspPos, 1 / perspPos[3]);
let aspect = this.engine.systems.cameraMatrix.getCurrentAspect(this.camera);
vec2.subtract(perspPos, this.ndc, perspPos);
let angle = Math.atan2(perspPos[1], perspPos[0] * aspect);
let diff = angle - this.lastAngle;
if (diff > Math.PI) diff -= Math.PI * 2;
if (diff < -Math.PI) diff += Math.PI * 2;
this.angle += diff;
this.lastAngle = angle;
this.setRotation();
}
mouseup(e) {
if (e.buttons === 0) this.manager.pop();
}
keydown(e) {
if (e.keyCode === 27) {
this.engine.actions.external.execute('transform.setRotation',
this.entity, this.startQuat, true);
this.manager.pop();
} else if (e.keyCode === 67) {
this.align = false;
this.alignAxis = [1, 1, 1];
this.setRotation();
this.setEffect();
} else if (e.keyCode === 88) {
this.align = true;
this.alignAxis = [1, 0, 0];
this.setRotation();
this.setEffect();
} else if (e.keyCode === 89) {
this.align = true;
this.alignAxis = [0, 1, 0];
this.setRotation();
this.setEffect();
} else if (e.keyCode === 90) {
this.align = true;
this.alignAxis = [0, 0, 1];
this.setRotation();
this.setEffect();
}
}
}
|
yoo2001818/kkiro3d
|
src/view/mode/rotate.js
|
JavaScript
|
mit
| 4,505
|
<?php
use Snail\App\Model;
class TestModel extends Model {
public function __construct() {
parent::__construct();
}
}
|
dennisslimmers01/Snail-MVC
|
models/TestModel.php
|
PHP
|
mit
| 135
|
using UnityEngine;
using System.Collections;
public class VideoController : MonoBehaviour {
public bool isStop = false;
public MovieTexture myMovie;
private GameObject menuBox;
private Camera menuCamera;
void Start () {
PlayerPrefs.DeleteAll ();
myMovie.Play ();
menuBox = GameObject.Find ("menu");
// menuCamera = menuBox.
// menuCamera = GameObject.Find ("MenuCamera").;
}
// Update is called once per frame
void OnGUI () {
if (isStop == false) {
GUI.DrawTexture (new Rect (0, 0, Screen.width, Screen.height), myMovie, ScaleMode.StretchToFill);
// Camera.main.Render();
} else {
// Camera.main.Render ();
}
if (Input.GetKeyDown (KeyCode.Return)) {
myMovie.Stop();
isStop = true;
// Application.LoadLevel ("Level_1");
}
}
}
|
gormanate/Rolling-Cube
|
Assets/Scripts/VideoController.cs
|
C#
|
mit
| 776
|
import * as React from "react";
import ReactTable, {TableProps, Column} from "react-table";
import selectTableHoc from "react-table/lib/hoc/selectTable";
import {DEPAccount, DEPProfile} from "../../store/dep/types";
import {DEPProfileName} from "../react-table/DEPProfileName";
import {JSONAPIDataObject} from "../../store/json-api";
// import "react-table/react-table.css";
export interface IDEPProfilesTableProps {
loading: boolean;
data: Array<JSONAPIDataObject<DEPProfile>>;
onToggleSelection: () => void;
onToggleAll: () => void;
}
const columns: Column[] = [
{
Cell: DEPProfileName,
Header: "Name",
accessor: "attributes.profile_name",
id: "profile_name",
},
{
Header: "UUID",
accessor: "attributes.uuid",
id: "uuid",
},
];
const ReactSelectTable = selectTableHoc(ReactTable);
export const DEPProfilesTable = ({ data, ...props }: IDEPProfilesTableProps & Partial<TableProps>) => (
<ReactSelectTable
keyField="id"
selectType="checkbox"
data={data}
columns={columns}
{...props}
/>
);
|
jessepeterson/commandment
|
ui/src/components/react-tables/DEPProfilesTable.tsx
|
TypeScript
|
mit
| 1,128
|
<?php
namespace JuniorEsiee\BusinessBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use JMS\DiExtraBundle\Annotation as DI;
use JuniorEsiee\BusinessBundle\Entity\Project;
/**
* @DI\FormType
*/
class ProjectType extends AbstractType
{
/**
* @DI\Inject("security.context")
*/
public $securityContext;
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('clientLastName', null, array(
'label' => 'Nom de famille'
))
->add('clientFirstName', null, array(
'label' => 'Prénom'
))
->add('clientCompany', null, array(
'required' => false,
'label' => 'Entreprise'
))
->add('clientPhone', null, array(
'label' => 'Téléphone',
'required' => false,
'attr' => array(
'data-inputmask' => "'mask': '9999999999'"
),
))
->add('clientEmail', null, array(
'label' => 'Email',
'required' => false,
))
->add('clientAddress', null, array(
'label' => 'Adresse',
'required' => false,
))
->add('clientZipCode', null, array(
'label' => 'Code Postal',
'required' => false,
))
->add('clientCity', null, array(
'label' => 'Ville',
'required' => false,
))
->add('depositDate', 'sonata_type_date_picker', array(
'required' => false,
'label' => 'Date de dépôt',
'attr' => array(
'class' => 'datepicker',
),
))
->add('title', null, array(
'required' => false,
'label' => 'Titre'
))
->add('description', null, array(
'required' => false,
'label' => 'Description'
))
->add('delay', 'sonata_type_date_picker', array(
'required' => false,
'label' => 'Délais',
'attr' => array(
'class' => 'datepicker',
),
))
;
if ($this->securityContext->isGranted('ROLE_ADMIN'))
{
$builder
->add('commercial', 'association_list', array(
'required' => false,
'class' => 'ApplicationSonataUserBundle:User',
'properties' => array('id', 'username'),
'role' => 'ROLE_CHARGE',
'empty_value' => 'Choisissez une option',
'empty_data' => null,
))
->add('rbu', 'association_list', array(
'required' => false,
'class' => 'ApplicationSonataUserBundle:User',
'properties' => array('id', 'username'),
'role' => 'ROLE_ADMIN',
'empty_value' => 'Choisissez une option',
'empty_data' => null,
))
->add('students', 'association_list', array(
'required' => false,
'class' => 'ApplicationSonataUserBundle:User',
'properties' => array('id', 'username'),
'multiple' => true,
))
;
}
if ($this->securityContext->isGranted('ROLE_CHARGE'))
{
$builder
->add('skillCategories', null, array(
'required' => false,
'multiple' => true,
'expanded' => true,
'label' => 'Majeur(s)'
))
->add('skills', null, array(
'required' => false,
'multiple' => true,
'expanded' => true,
'label' => 'Compétence(s)'
))
// ->add('state', 'choice', array(
// 'required' => false,
// 'expanded' => true,
// 'multiple' => false,
// 'empty_value' => false,
// 'choices' => array_combine(Project::getStates(), Project::getStates()),
// 'translation_domain' => 'JuniorEsieeBusinessBundle',
// 'label' => 'Statut'
// ))
->add('scopeStatement', 'sonata_media_type', array(
'required' => false,
'provider' => 'sonata.media.provider.file',
'context' => 'scopeStatement',
'new_on_update' => false,
'label' => 'Cahier des charges',
))
->add('graphicCharter', 'sonata_media_type', array(
'required' => false,
'provider' => 'sonata.media.provider.file',
'context' => 'graphicCharter',
'new_on_update' => false,
'label' => 'Charte graphique',
))
;
}
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'JuniorEsiee\BusinessBundle\Entity\Project'
));
}
/**
* @return string
*/
public function getName()
{
return 'junioresiee_businessbundle_project';
}
}
|
na-ji/junior-esiee
|
src/JuniorEsiee/BusinessBundle/Form/ProjectType.php
|
PHP
|
mit
| 6,121
|
__all__ = ["melfilterbank", "windowing", "spectrogram", "resample"]
import melfilterbank
import windowing
import spectrogram
import resample
|
twerkmeister/iLID
|
preprocessing/audio/__init__.py
|
Python
|
mit
| 141
|
import Relay from 'react-relay/classic';
class FindPublicTeamRoute extends Relay.Route {
static queries = {
team: () => Relay.QL`query FindPublicTeam { find_public_team(slug: $teamSlug) }`,
};
static paramDefinitions = {
teamSlug: { required: true },
};
static routeName = 'FindPublicTeamRoute';
}
export default FindPublicTeamRoute;
|
meedan/check-web
|
src/app/relay/FindPublicTeamRoute.js
|
JavaScript
|
mit
| 354
|
<header class="header-tit">
<a class="goBack fl" href="#static/investManage"><i></i>返回</a>
<p class="txt_c">优秀的投资管理能力</p>
</header>
<section class="word-pd1 bg-fff">
<p class="fs16 fw_bd cl-333">优秀的投资管理能力</p>
<p class="fs15 fw_bd cl-333 m-t10">1、时间最长的投资管理团队</p>
<p class="fs14 cl-666 m-t10">平安养老拥有一支完全独立的年金投资管理团队,并且投资经理平均拥有6年的年金投资管理经验,是市场上管理年金时间最长的投资队伍;</p>
<p class="fs15 fw_bd cl-333 m-t10">2、稳定的长期投资业绩</p>
<p class="fs14 cl-666 m-t10">平安养老历年来的投资收益均超过业界平均水平。2008年市场暴跌,平安养老年金组合年均收益12.54%;2009年年均收益9.27%;2010年市场继续震荡行情,在经历了市场大涨大跌后,平安养老凭借稳健的投资风格,仍然取得了4.76%的市场收益率;2011市场出现了罕见“股债双杀”的局面,平安养老是业内首家为年金组合配置协议存款的机构,最大程度的减少了资本市场波动对年金资产的影响,管理的年金组合的平均业绩0.79%,超越了人社部公布的行业平均收益水平-0.78%。</p>
<p class="fs15 fw_bd cl-333 m-t10">3、最优的风险控制能力,零违规风控记录</p>
<p class="fs14 cl-666 m-t10">公司配置了专业的风险控制团队,制定了10项风险控制制度和7项风险控制措施来保障年金的安全。在严格的风险控制下,平安养老保持着零违规记录的风控历史,资本市场发生了多起违规事件,违规主角涉及国内知名保险资产管理公司、基金管理公司等,平安从未牵涉其中。</p>
</section>
|
Wooleners/AnnuityTouch
|
src/modules/static/investBestAbility.html
|
HTML
|
mit
| 1,803
|
<?php include_once "includes/templates/header.php" ;?>
<section class="seccion contenedor">
<h2>GDLWEBCAMP</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor, quae aspernatur explicabo voluptatem iusto inventore amet, illum quas nisi vitae repudiandae! Exercitationem id, odio tempore iure provident aspernatur, voluptate reiciendis. Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</section> <!-- seccion contenedor -->
<section class="programa">
<div class="contenedor-video">
<video autoplay loop poster="img/bg-talleres.jpg">
<source src="video/video.mp4" type="video/mp4">
<source src="video/video.webm" type="video/webm">
<source src="video/video.ogv" type="video/ogv">
</video>
</div> <!-- contenedor video -->
<div class="contenido-programa">
<div class="contenedor">
<div class="programa-evento">
<h2>Programa del Evento</h2>
<?php
try {
require_once('includes/funciones/bd_conexion.php');
$sql = "SELECT * FROM `categoria_evento` ";
$resultado = $conn->query($sql);
} catch (Exception $e) {
$error = $e->getMessage();
}
?>
<nav class="menu-programa">
<?php while($cat = $resultado->fetch_array(MYSQLI_ASSOC)) { ?>
<?php $categoria = $cat['cat_evento']; ?>
<a href="#<?php echo strtolower($categoria) ?>">
<i class="fa <?php echo $cat['icono'] ?>" aria-hidden="true"></i> <?php echo $categoria ?>
</a>
<?php } ?>
</nav>
<?php
try {
require_once('includes/funciones/bd_conexion.php');
$sql = "SELECT `evento_id`, `nombre_evento`, `fecha_evento`, `hora_evento`, `cat_evento`, `nombre_invitado`, `apellido_invitado` ";
$sql .= "FROM `eventos` ";
$sql .= "INNER JOIN `categoria_evento` ";
$sql .= "ON eventos.id_cat_evento=categoria_evento.id_categoria ";
$sql .= "INNER JOIN `invitados` ";
$sql .= "ON eventos.id_inv=invitados.invitado_id ";
$sql .= "AND eventos.id_cat_evento = 1 ";
$sql .= "ORDER BY `evento_id` LIMIT 2;";
$sql .= "SELECT `evento_id`, `nombre_evento`, `fecha_evento`, `hora_evento`, `cat_evento`, `nombre_invitado`, `apellido_invitado` ";
$sql .= "FROM `eventos` ";
$sql .= "INNER JOIN `categoria_evento` ";
$sql .= "ON eventos.id_cat_evento=categoria_evento.id_categoria ";
$sql .= "INNER JOIN `invitados` ";
$sql .= "ON eventos.id_inv=invitados.invitado_id ";
$sql .= "AND eventos.id_cat_evento = 2 ";
$sql .= "ORDER BY `evento_id` LIMIT 2;";
$sql .= "SELECT `evento_id`, `nombre_evento`, `fecha_evento`, `hora_evento`, `cat_evento`, `nombre_invitado`, `apellido_invitado` ";
$sql .= "FROM `eventos` ";
$sql .= "INNER JOIN `categoria_evento` ";
$sql .= "ON eventos.id_cat_evento=categoria_evento.id_categoria ";
$sql .= "INNER JOIN `invitados` ";
$sql .= "ON eventos.id_inv=invitados.invitado_id ";
$sql .= "AND eventos.id_cat_evento = 3 ";
$sql .= "ORDER BY `evento_id` LIMIT 2;";
} catch (Exception $e) {
$error = $e->getMessage();
}
?>
<?php $conn->multi_query($sql); ?>
<?php
do {
$resultado = $conn->store_result();
$row = $resultado->fetch_all(MYSQLI_ASSOC); ?>
<?php $i = 0; ?>
<?php foreach($row as $evento): ?>
<?php if($i % 2 == 0) { ?>
<div id="<?php echo strtolower($evento['cat_evento']) ?>" class="info-curso ocultar clearfix">
<?php } ?>
<div class="detalle-evento">
<h3><?php echo html_entity_decode($evento['nombre_evento']) ?></h3>
<p><i class="fa fa-clock-o" aria-hidden="true"></i> <?php echo $evento['hora_evento']; ?></p>
<p><i class="fa fa-calendar" aria-hidden="true"></i> <?php echo $evento['fecha_evento']; ?></p>
<p><i class="fa fa-user" aria-hidden="true"></i> <?php echo $evento['nombre_invitado'] . " " . $evento['apellido_invitado']; ?></p>
</div>
<?php if($i % 2 == 1): ?>
<a href="calendario.php" class="button float-right">Ver todos</a>
</div> <!--#talleres-->
<?php endif; ?>
<?php $i++; ?>
<?php endforeach; ?>
<?php $resultado->free(); ?>
<?php } while ($conn->more_results() && $conn->next_result());?>
</div> <!--.programa-evento-->
</div> <!--.contenedor-->
</div><!--.contenido-programa-->
</section> <!-- seccion programa -->
<?php include_once "includes/templates/invitados.php" ;?>
<div class="contador parallax">
<div class="contenedor">
<ul class="resumen-evento clearfix">
<li> <p class="numero">0</p>Invitados</li>
<li> <p class="numero">0</p>Talleres</li>
<li> <p class="numero">0</p>Días</li>
<li> <p class="numero">0</p>Conferencias</li>
</ul>
</div>
</div>
<section class="precios seccion">
<h2>Precios</h2>
<div class="contenedor">
<ul class="lista-precios clearfix">
<li>
<div class="tabla-precio">
<h3>Pase por día </h3>
<p class="numero">$30</p>
<ul>
<li>Servicio Alimentación</li>
<li>Todas las conferencias</li>
<li>Todas los talleres</li>
</ul>
<a href="#" class="button hollow">Comprar</a>
</div>
</li>
<li>
<div class="tabla-precio">
<h3>Todos los días </h3>
<p class="numero">$50</p>
<ul>
<li>Servicio Alimentación</li>
<li>Todas las conferencias</li>
<li>Todas los talleres</li>
</ul>
<a href="#" class="button">Comprar</a>
</div>
</li>
<li>
<div class="tabla-precio">
<h3>Pase por 2 días </h3>
<p class="numero">$45</p>
<ul>
<li>Servicio Alimentación</li>
<li>Todas las conferencias</li>
<li>Todas los talleres</li>
</ul>
<a href="#" class="button hollow">Comprar</a>
</div>
</li>
</ul>
</div>
</section>
<div id="mapa" class="mapa">
</div>
<section class="seccion">
<h2>Testimoniales</h2>
<div class="testimoniales contenedor clearfix">
<div class="testimonial">
<blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo laborum dolore nihil numquam quod dicta perferendis minima voluptatum recusandae fugiat necessitatibus sed, veniam maiores consequuntur pariatur autem natus laudantium, cupiditate.
</p>
<footer class="info-testimonial clearfix">
<img src="img/testimonial.jpg" alt="image testimonial">
<cite>Oswaldo Palma Palma <span>Diseñador @prisma</span></cite>
</footer>
</blockquote>
</div> <!-- Fin Testimonial -->
<div class="testimonial">
<blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo laborum dolore nihil numquam quod dicta perferendis minima voluptatum recusandae fugiat necessitatibus sed, veniam maiores consequuntur pariatur autem natus laudantium, cupiditate.
</p>
<footer class="info-testimonial clearfix">
<img src="img/testimonial.jpg" alt="image testimonial">
<cite>Oswaldo Palma <span>Diseñador @prisma</span></cite>
</footer>
</blockquote>
</div> <!-- Fin Testimonial -->
<div class="testimonial">
<blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo laborum dolore nihil numquam quod dicta perferendis minima voluptatum recusandae fugiat necessitatibus sed, veniam maiores consequuntur pariatur autem natus laudantium, cupiditate.
</p>
<footer class="info-testimonial clearfix">
<img src="img/testimonial.jpg" alt="image testimonial">
<cite>Oswaldo Palma <span>Diseñador @prisma</span></cite>
</footer>
</blockquote>
</div> <!-- Fin Testimonial -->
</div> <!-- Fin testimoniales -->
</section>
<div class="newsletter parallax">
<div class="contenido contenedor">
<p>resgistrate en el newsletter</p>
<h3>gdlwebcamp</h3>
<a href="#" class="button transparente">Registro</a>
</div> <!-- Contenido -->
</div> <!-- Newsletter -->
<section class="seccion">
<h2>Faltan</h2>
<div class="cuenta-regresiva contenedor">
<ul class="clearfix">
<li><p id="dias" class="numero"></p>días</li>
<li><p id="horas" class="numero"></p>horas</li>
<li><p id="minutos" class="numero"></p>minutos</li>
<li><p id="segundos" class="numero"></p>segundos</li>
</ul>
</div>
</section>
<?php include_once "includes/templates/footer.php" ;?>
|
frank-ec/gdlwebcamp
|
index1.php
|
PHP
|
mit
| 12,362
|
package handlers_test
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/zefer/gompd/mpd"
"github.com/zefer/mothership/handlers"
)
type mockPlClient struct{}
var mockStatus map[string]string = map[string]string{}
func (c mockPlClient) Status() (mpd.Attrs, error) {
return mockStatus, nil
}
var requestedRange [2]int
func (c mockPlClient) PlaylistInfo(start, end int) ([]mpd.Attrs, error) {
requestedRange = [2]int{start, end}
pls := []mpd.Attrs{
{
"file": "Led Zeppelin - Houses Of The Holy/08 - Led Zeppelin - The Ocean.mp3",
"Artist": "Led Zeppelin",
"Title": "The Ocean",
"Album": "Houses of the Holy",
"Last-Modified": "2010-12-09T21:32:02Z",
"Pos": "0",
},
{
"file": "Johnny Cash – Unchained/Johnny Cash – Sea Of Heartbreak.mp3",
"Last-Modified": "2011-10-09T11:45:11Z",
"Pos": "1",
},
{
"file": "http://somestream",
"Name": "HTTP stream from pls",
"Last-Modified": "2011-10-09T11:45:11Z",
"Pos": "2",
},
}
return pls, nil
}
var clearCalled bool = false
func (c mockPlClient) Clear() error {
clearCalled = true
return nil
}
var loadedURI string = ""
func (c mockPlClient) PlaylistLoad(uri string, start, end int) error {
loadedURI = uri
return nil
}
var addedURI string = ""
func (c mockPlClient) Add(uri string) error {
addedURI = uri
return nil
}
var playCalled bool = false
var playedPos int = 0
func (c mockPlClient) Play(pos int) error {
playCalled = true
playedPos = pos
return nil
}
var _ = Describe("PlayListHandler", func() {
var handler http.Handler
var w *httptest.ResponseRecorder
BeforeEach(func() {
called = false
w = httptest.NewRecorder()
})
Context("with disallowed HTTP methods", func() {
var client *mockPlClient
BeforeEach(func() {
client = &mockPlClient{}
handler = handlers.PlayListHandler(client)
})
It("responds with 405 method not allowed", func() {
for _, method := range []string{"PUT", "PATCH", "DELETE"} {
req, _ := http.NewRequest(method, "/playlist", nil)
handler.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusMethodNotAllowed))
Expect(w.Body.String()).To(Equal(""))
}
})
})
Context("with a GET request (list the current playlist)", func() {
var client *mockPlClient
BeforeEach(func() {
client = &mockPlClient{}
handler = handlers.PlayListHandler(client)
})
Describe("the MPD query", func() {
Context("when there are less than 500 items on the playlist", func() {
BeforeEach(func() {
mockStatus = map[string]string{"playlistlength": "12"}
req, _ := http.NewRequest("GET", "/playlist", nil)
handler.ServeHTTP(w, req)
})
It("requests the full playlist from MPD", func() {
Expect(requestedRange[0]).To(Equal(-1))
Expect(requestedRange[1]).To(Equal(-1))
})
})
Context("when there are more than 500 items on the playlist", func() {
Context("when the current playlist position isn't the first song", func() {
BeforeEach(func() {
mockStatus = map[string]string{"playlistlength": "501", "song": "123"}
req, _ := http.NewRequest("GET", "/playlist", nil)
handler.ServeHTTP(w, req)
})
It("requests a slice of the playlist from MPD. Current pos -1 to +500", func() {
Expect(requestedRange[0]).To(Equal(122))
Expect(requestedRange[1]).To(Equal(623))
})
})
Context("when the current playlist position is the first song", func() {
BeforeEach(func() {
mockStatus = map[string]string{"playlistlength": "501", "song": "0"}
req, _ := http.NewRequest("GET", "/playlist", nil)
handler.ServeHTTP(w, req)
})
// Checking we don't query with a negative start index.
It("requests a slice of the playlist from MPD. 0 to 500", func() {
Expect(requestedRange[0]).To(Equal(0))
Expect(requestedRange[1]).To(Equal(500))
})
})
})
})
Describe("the response", func() {
It("responds with 200 OK", func() {
req, _ := http.NewRequest("GET", "/playlist", nil)
handler.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusOK))
})
It("responds with the JSON content-type", func() {
req, _ := http.NewRequest("GET", "/playlist", nil)
handler.ServeHTTP(w, req)
Expect(w.HeaderMap["Content-Type"][0]).To(Equal("application/json"))
})
It("responds with a JSON array of playlist items", func() {
req, _ := http.NewRequest("GET", "/playlist", nil)
handler.ServeHTTP(w, req)
var pls []map[string]interface{}
if err := json.NewDecoder(w.Body).Decode(&pls); err != nil {
Fail(fmt.Sprintf("Could not parse JSON %v", err))
}
Expect(len(pls)).To(Equal(3))
// Item 1 has artist & track parts, so we expect "artist - track".
Expect(len(pls[0])).To(Equal(2))
Expect(pls[0]["pos"]).To(BeEquivalentTo(1))
Expect(pls[0]["name"]).To(Equal("Led Zeppelin - The Ocean"))
// Item 2 doesn't have artist & track parts, so we expect "file.mp3".
Expect(len(pls[1])).To(Equal(2))
Expect(pls[1]["pos"]).To(BeEquivalentTo(2))
Expect(pls[1]["name"]).To(Equal("Johnny Cash – Sea Of Heartbreak.mp3"))
// Item 3 has a 'name' field, such as from a loaded pls playlist.
Expect(len(pls[2])).To(Equal(2))
Expect(pls[2]["pos"]).To(BeEquivalentTo(3))
Expect(pls[2]["name"]).To(Equal("HTTP stream from pls"))
})
})
})
Context("with a POST request (update the current playlist)", func() {
var validParams map[string]interface{}
BeforeEach(func() {
validParams = map[string]interface{}{
"uri": "gorilla.mp3", "type": "file", "replace": true, "play": true,
}
})
Describe("POST data validation", func() {
Context("with valid params", func() {
It("responds 204 no content", func() {
json, _ := json.Marshal(validParams)
req, _ := http.NewRequest("POST", "/playlist", bytes.NewBuffer(json))
handler.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusNoContent))
})
})
Context("with un-parseable JSON", func() {
It("responds 400 bad request", func() {
var json = []byte(`{not-json`)
req, _ := http.NewRequest("POST", "/playlist", bytes.NewBuffer(json))
handler.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusBadRequest))
})
})
Context("with missing required fields", func() {
It("responds 400 bad request", func() {
for _, f := range []string{"uri", "type", "replace", "play"} {
// d = map[string]string{"uri": "", "type": "", "replace": "", "play": ""}
params := make(map[string]interface{})
for k, v := range validParams {
params[k] = v
}
delete(params, f)
json, _ := json.Marshal(params)
req, _ := http.NewRequest("POST", "/playlist", bytes.NewBuffer(json))
handler.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusBadRequest))
}
})
})
// Without URI, we don't know what to add to the playlist.
Context("with an empty 'uri' field", func() {
It("responds 400 bad request", func() {
validParams["uri"] = ""
json, _ := json.Marshal(validParams)
req, _ := http.NewRequest("POST", "/playlist", bytes.NewBuffer(json))
handler.ServeHTTP(w, req)
Expect(w.Code).To(Equal(http.StatusBadRequest))
})
})
})
Context("with replace=true", func() {
It("clears the playlist", func() {
clearCalled = false
validParams["replace"] = true
json, _ := json.Marshal(validParams)
req, _ := http.NewRequest("POST", "/playlist", bytes.NewBuffer(json))
handler.ServeHTTP(w, req)
Expect(clearCalled).To(BeTrue())
})
})
Context("with replace=false", func() {
It("does not clear the playlist", func() {
clearCalled = false
validParams["replace"] = false
json, _ := json.Marshal(validParams)
req, _ := http.NewRequest("POST", "/playlist", bytes.NewBuffer(json))
handler.ServeHTTP(w, req)
Expect(clearCalled).To(BeFalse())
})
})
Context("when type='playlist'", func() {
It("loads the given URI", func() {
loadedURI = ""
addedURI = ""
validParams["type"] = "playlist"
validParams["uri"] = "http://gorillas"
json, _ := json.Marshal(validParams)
req, _ := http.NewRequest("POST", "/playlist", bytes.NewBuffer(json))
handler.ServeHTTP(w, req)
Expect(loadedURI).To(Equal("http://gorillas"))
Expect(addedURI).To(Equal(""))
})
})
Context("when type='directory' or type='file'", func() {
It("adds the given URI", func() {
for _, t := range []string{"directory", "file"} {
loadedURI = ""
addedURI = ""
validParams["type"] = t
validParams["uri"] = "http://gorillas"
json, _ := json.Marshal(validParams)
req, _ := http.NewRequest("POST", "/playlist", bytes.NewBuffer(json))
handler.ServeHTTP(w, req)
Expect(addedURI).To(Equal("http://gorillas"))
Expect(loadedURI).To(Equal(""))
}
})
})
Context("when play=true", func() {
BeforeEach(func() {
validParams["play"] = true
mockStatus = map[string]string{"playlistlength": "66"}
playedPos = 123
playCalled = false
})
Context("and replace=true", func() {
It("it tells MPD to play from position 0", func() {
validParams["replace"] = true
json, _ := json.Marshal(validParams)
req, _ := http.NewRequest("POST", "/playlist", bytes.NewBuffer(json))
handler.ServeHTTP(w, req)
Expect(playCalled).To(BeTrue())
Expect(playedPos).To(Equal(0))
})
})
Context("and replace=false", func() {
It("it tells MPD to play from the start of the new added items", func() {
validParams["replace"] = false
json, _ := json.Marshal(validParams)
req, _ := http.NewRequest("POST", "/playlist", bytes.NewBuffer(json))
handler.ServeHTTP(w, req)
Expect(playCalled).To(BeTrue())
Expect(playedPos).To(Equal(66))
})
})
})
Context("when play=false", func() {
It("it does not tell MPD to play", func() {
playCalled = false
validParams["play"] = false
json, _ := json.Marshal(validParams)
req, _ := http.NewRequest("POST", "/playlist", bytes.NewBuffer(json))
handler.ServeHTTP(w, req)
Expect(playCalled).To(BeFalse())
})
})
})
})
|
zefer/mothership
|
handlers/playlist_test.go
|
GO
|
mit
| 10,362
|
# Pull base image
FROM node:6.11.0
MAINTAINER Venkata krishna "vkvenkat94@gmail.com"
# Copy to work directory
ADD . ./badgeit-front
# Move to work directory
WORKDIR ./badgeit-front
# Install app dependencies
RUN ["npm", "install"]
# Binds to port 8080
EXPOSE 8080
CMD ["npm", "start"]
|
argonlaser/badgeit-front
|
Dockerfile
|
Dockerfile
|
mit
| 291
|
/*
* Copyright (c) 2016, 2017, 2020 Konstantin Tcholokachvili
* All rights reserved.
* Use of this source code is governed by a MIT license that can be
* found in the LICENSE file.
*/
#pragma once
#include <io/console.h>
#define FORTH_DICTIONARY 0
#define MACRO_DICTIONARY 1
typedef int32_t cell_t;
typedef struct colorforth_word
{
cell_t name;
void *code_address;
} word_t;
struct editor_args
{
struct console *cons;
uint32_t initrd_start;
uint32_t initrd_end;
};
void editor(void *args);
cell_t pack(const char *word_name);
char *unpack(cell_t word);
void run_block(const cell_t nb_block);
void dot_s(void);
void dispatch_word(cell_t word);
word_t lookup_word(cell_t name, const bool_t force_dictionary);
void colorforth_initialize(void);
void erase_stack(void);
|
narke/Einherjar
|
kernel/colorforth/colorforth.h
|
C
|
mit
| 815
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>BOOST_COMP compiler macros</title>
<link rel="stylesheet" href="../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="Predef 1.3">
<link rel="up" href="../reference.html" title="Reference">
<link rel="prev" href="boost_arch_architecture_macros.html" title="BOOST_ARCH architecture macros">
<link rel="next" href="boost_lang_language_standards_ma.html" title="BOOST_LANG language standards macros">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<div class="spirit-nav">
<a accesskey="p" href="boost_arch_architecture_macros.html"><img src="../../images/prev.png" alt="Prev"></a><a accesskey="u" href="../reference.html"><img src="../../images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../images/home.png" alt="Home"></a><a accesskey="n" href="boost_lang_language_standards_ma.html"><img src="../../images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h3 class="title">
<a name="predef.reference.boost_comp_compiler_macros"></a><a class="link" href="boost_comp_compiler_macros.html" title="BOOST_COMP compiler macros"><code class="computeroutput"><span class="identifier">BOOST_COMP</span></code> compiler macros</a>
</h3></div></div></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h0"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_borland"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_borland"><code class="computeroutput"><span class="identifier">BOOST_COMP_BORLAND</span></code></a>
</h5>
<p>
<a href="http://en.wikipedia.org/wiki/C_plus_plus_builder" target="_top">Borland C++</a>
compiler. Version number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__BORLANDC__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__CODEGEARC__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__BORLANDC__</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__CODEGEARC__</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h1"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_clang"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_clang"><code class="computeroutput"><span class="identifier">BOOST_COMP_CLANG</span></code></a>
</h5>
<p>
<a href="http://en.wikipedia.org/wiki/Clang" target="_top">Clang</a> compiler. Version
number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__clang__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__clang_major__</span></code>,
<code class="computeroutput"><span class="identifier">__clang_minor__</span></code>,
<code class="computeroutput"><span class="identifier">__clang_patchlevel__</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h2"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_como"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_como"><code class="computeroutput"><span class="identifier">BOOST_COMP_COMO</span></code></a>
</h5>
<p>
<a href="http://en.wikipedia.org/wiki/Comeau_C/C%2B%2B" target="_top">Comeau C++</a>
compiler. Version number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__COMO__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__COMO_VERSION__</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h3"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_dec"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_dec"><code class="computeroutput"><span class="identifier">BOOST_COMP_DEC</span></code></a>
</h5>
<p>
<a href="http://www.openvms.compaq.com/openvms/brochures/deccplus/" target="_top">Compaq
C/C++</a> compiler. Version number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__DECCXX</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__DECC</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__DECCXX_VER</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__DECC_VER</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h4"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_diab"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_diab"><code class="computeroutput"><span class="identifier">BOOST_COMP_DIAB</span></code></a>
</h5>
<p>
<a href="http://www.windriver.com/products/development_suite/wind_river_compiler/" target="_top">Diab
C/C++</a> compiler. Version number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__DCC__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__VERSION_NUMBER__</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h5"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_dmc"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_dmc"><code class="computeroutput"><span class="identifier">BOOST_COMP_DMC</span></code></a>
</h5>
<p>
<a href="http://en.wikipedia.org/wiki/Digital_Mars" target="_top">Digital Mars</a>
compiler. Version number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__DMC__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__DMC__</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h6"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_sysc"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_sysc"><code class="computeroutput"><span class="identifier">BOOST_COMP_SYSC</span></code></a>
</h5>
<p>
<a href="http://www.dignus.com/dcxx/" target="_top">Dignus Systems/C++</a> compiler.
Version number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__SYSC__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__SYSC_VER__</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h7"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_edg"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_edg"><code class="computeroutput"><span class="identifier">BOOST_COMP_EDG</span></code></a>
</h5>
<p>
<a href="http://en.wikipedia.org/wiki/Edison_Design_Group" target="_top">EDG C++ Frontend</a>
compiler. Version number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__EDG__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__EDG_VERSION__</span></code>
</p>
</td>
<td>
<p>
V.R.0
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h8"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_path"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_path"><code class="computeroutput"><span class="identifier">BOOST_COMP_PATH</span></code></a>
</h5>
<p>
<a href="http://en.wikipedia.org/wiki/PathScale" target="_top">EKOpath</a> compiler.
Version number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__PATHCC__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__PATHCC__</span></code>, <code class="computeroutput"><span class="identifier">__PATHCC_MINOR__</span></code>, <code class="computeroutput"><span class="identifier">__PATHCC_PATCHLEVEL__</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h9"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_gnuc"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_gnuc"><code class="computeroutput"><span class="identifier">BOOST_COMP_GNUC</span></code></a>
</h5>
<p>
<a href="http://en.wikipedia.org/wiki/GNU_Compiler_Collection" target="_top">Gnu GCC
C/C++</a> compiler. Version number available as major, minor, and patch
(if available).
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__GNUC__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__GNUC__</span></code>, <code class="computeroutput"><span class="identifier">__GNUC_MINOR__</span></code>, <code class="computeroutput"><span class="identifier">__GNUC_PATCHLEVEL__</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__GNUC__</span></code>, <code class="computeroutput"><span class="identifier">__GNUC_MINOR__</span></code>
</p>
</td>
<td>
<p>
V.R.0
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h10"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_gccxml"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_gccxml"><code class="computeroutput"><span class="identifier">BOOST_COMP_GCCXML</span></code></a>
</h5>
<p>
<a href="http://www.gccxml.org/" target="_top">GCC XML</a> compiler.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody><tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__GCCXML__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr></tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h11"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_ghs"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_ghs"><code class="computeroutput"><span class="identifier">BOOST_COMP_GHS</span></code></a>
</h5>
<p>
<a href="http://en.wikipedia.org/wiki/Green_Hills_Software" target="_top">Green Hills
C/C++</a> compiler. Version number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__ghs</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__ghs__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__GHS_VERSION_NUMBER__</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__ghs</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h12"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_hpacc"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_hpacc"><code class="computeroutput"><span class="identifier">BOOST_COMP_HPACC</span></code></a>
</h5>
<p>
HP aC++ compiler. Version number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__HP_aCC</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__HP_aCC</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h13"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_iar"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_iar"><code class="computeroutput"><span class="identifier">BOOST_COMP_IAR</span></code></a>
</h5>
<p>
IAR C/C++ compiler. Version number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__IAR_SYSTEMS_ICC__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__VER__</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h14"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_ibm"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_ibm"><code class="computeroutput"><span class="identifier">BOOST_COMP_IBM</span></code></a>
</h5>
<p>
<a href="http://en.wikipedia.org/wiki/VisualAge" target="_top">IBM XL C/C++</a>
compiler. Version number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__IBMCPP__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__xlC__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__xlc__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__COMPILER_VER__</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__xlC__</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__xlc__</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__IBMCPP__</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h15"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_intel"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_intel"><code class="computeroutput"><span class="identifier">BOOST_COMP_INTEL</span></code></a>
</h5>
<p>
<a href="http://en.wikipedia.org/wiki/Intel_C%2B%2B" target="_top">Intel C/C++</a>
compiler. Version number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__INTEL_COMPILER</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__ICL</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__ICC</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__ECC</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__INTEL_COMPILER</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h16"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_kcc"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_kcc"><code class="computeroutput"><span class="identifier">BOOST_COMP_KCC</span></code></a>
</h5>
<p>
Kai C++ compiler. Version number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__KCC</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__KCC_VERSION</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h17"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_llvm"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_llvm"><code class="computeroutput"><span class="identifier">BOOST_COMP_LLVM</span></code></a>
</h5>
<p>
<a href="http://en.wikipedia.org/wiki/LLVM" target="_top">LLVM</a> compiler.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody><tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__llvm__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr></tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h18"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_highc"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_highc"><code class="computeroutput"><span class="identifier">BOOST_COMP_HIGHC</span></code></a>
</h5>
<p>
MetaWare High C/C++ compiler.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody><tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__HIGHC__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr></tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h19"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_mwerks"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_mwerks"><code class="computeroutput"><span class="identifier">BOOST_COMP_MWERKS</span></code></a>
</h5>
<p>
<a href="http://en.wikipedia.org/wiki/CodeWarrior" target="_top">Metrowerks CodeWarrior</a>
compiler. Version number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__MWERKS__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__CWCC__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__CWCC__</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__MWERKS__</span></code>
</p>
</td>
<td>
<p>
V.R.P >= 4.2.0
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__MWERKS__</span></code>
</p>
</td>
<td>
<p>
9.R.0
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__MWERKS__</span></code>
</p>
</td>
<td>
<p>
8.R.0
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h20"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_mri"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_mri"><code class="computeroutput"><span class="identifier">BOOST_COMP_MRI</span></code></a>
</h5>
<p>
<a href="http://www.mentor.com/microtec/" target="_top">Microtec C/C++</a> compiler.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody><tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">_MRI</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr></tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h21"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_mpw"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_mpw"><code class="computeroutput"><span class="identifier">BOOST_COMP_MPW</span></code></a>
</h5>
<p>
<a href="http://en.wikipedia.org/wiki/Macintosh_Programmer%27s_Workshop" target="_top">MPW
C++</a> compiler. Version number available as major, and minor.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__MRC__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">MPW_C</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">MPW_CPLUS</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__MRC__</span></code>
</p>
</td>
<td>
<p>
V.R.0
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h22"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_palm"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_palm"><code class="computeroutput"><span class="identifier">BOOST_COMP_PALM</span></code></a>
</h5>
<p>
Palm C/C++ compiler. Version number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">_PACC_VER</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">_PACC_VER</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h23"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_pgi"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_pgi"><code class="computeroutput"><span class="identifier">BOOST_COMP_PGI</span></code></a>
</h5>
<p>
<a href="http://en.wikipedia.org/wiki/The_Portland_Group" target="_top">Portland Group
C/C++</a> compiler.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__PGI</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__PGIC__</span></code>, <code class="computeroutput"><span class="identifier">__PGIC_MINOR__</span></code>, <code class="computeroutput"><span class="identifier">__PGIC_PATCHLEVEL__</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h24"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_sgi"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_sgi"><code class="computeroutput"><span class="identifier">BOOST_COMP_SGI</span></code></a>
</h5>
<p>
<a href="http://en.wikipedia.org/wiki/MIPSpro" target="_top">SGI MIPSpro</a> compiler.
Version number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__sgi</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">sgi</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">_SGI_COMPILER_VERSION</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">_COMPILER_VERSION</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h25"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_sunpro"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_sunpro"><code class="computeroutput"><span class="identifier">BOOST_COMP_SUNPRO</span></code></a>
</h5>
<p>
<a href="http://en.wikipedia.org/wiki/Oracle_Solaris_Studio" target="_top">Oracle Solaris
Studio</a> compiler. Version number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__SUNPRO_CC</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__SUNPRO_C</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__SUNPRO_CC</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__SUNPRO_C</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__SUNPRO_CC</span></code>
</p>
</td>
<td>
<p>
VV.RR.P
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__SUNPRO_C</span></code>
</p>
</td>
<td>
<p>
VV.RR.P
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h26"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_tendra"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_tendra"><code class="computeroutput"><span class="identifier">BOOST_COMP_TENDRA</span></code></a>
</h5>
<p>
<a href="http://en.wikipedia.org/wiki/TenDRA_Compiler" target="_top">TenDRA C/C++</a>
compiler.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody><tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__TenDRA__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr></tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h27"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_msvc"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_msvc"><code class="computeroutput"><span class="identifier">BOOST_COMP_MSVC</span></code></a>
</h5>
<p>
<a href="http://en.wikipedia.org/wiki/Visual_studio" target="_top">Microsoft Visual
C/C++</a> compiler. Version number available as major, minor, and patch.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">_MSC_VER</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">_MSC_FULL_VER</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">_MSC_VER</span></code>
</p>
</td>
<td>
<p>
V.R.0
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="predef.reference.boost_comp_compiler_macros.h28"></a>
<span class="phrase"><a name="predef.reference.boost_comp_compiler_macros.boost_comp_watcom"></a></span><a class="link" href="boost_comp_compiler_macros.html#predef.reference.boost_comp_compiler_macros.boost_comp_watcom"><code class="computeroutput"><span class="identifier">BOOST_COMP_WATCOM</span></code></a>
</h5>
<p>
<a href="http://en.wikipedia.org/wiki/Watcom" target="_top">Watcom C++</a> compiler.
Version number available as major, and minor.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Symbol
</p>
</th>
<th>
<p>
Version
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__WATCOMC__</span></code>
</p>
</td>
<td>
<p>
<span class="bold"><strong>detection</strong></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">__WATCOMC__</span></code>
</p>
</td>
<td>
<p>
V.R.P
</p>
</td>
</tr>
</tbody>
</table></div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2005, 2008-2015 Rene
Rivera<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="boost_arch_architecture_macros.html"><img src="../../images/prev.png" alt="Prev"></a><a accesskey="u" href="../reference.html"><img src="../../images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../images/home.png" alt="Home"></a><a accesskey="n" href="boost_lang_language_standards_ma.html"><img src="../../images/next.png" alt="Next"></a>
</div>
</body>
</html>
|
Franky666/programmiersprachen-raytracer
|
external/boost_1_59_0/libs/predef/doc/html/predef/reference/boost_comp_compiler_macros.html
|
HTML
|
mit
| 53,644
|
require 'quickbuild/config/result_saver'
module Quickbuild::Config
RSpec.describe ResultSaver do
let(:mock_output) do
output = double('mock_output')
allow(output).to receive(:puts)
output
end
subject do
ResultSaver.new(mock_output)
end
describe '#save' do
it 'saves configuration and content' do
expect(subject.save('configuration/path', 'configuration content')).to eql nil
end
end
describe '#create_by_output' do
it 'creates STDOUT saver for "-"' do
expect(ResultSaver.create_by_output('-')).to eql ResultSaverSTDOUT.new
end
it 'creates STDOUT saver for nil' do
expect(ResultSaver.create_by_output(nil)).to eql ResultSaverSTDOUT.new
end
it 'creates saver for directory' do
expect(ResultSaver.create_by_output('directory')).to eql ResultSaverToDirectory.new('directory')
end
end
end
RSpec.describe ResultSaverToDirectory do
describe '#save' do
let(:test_config) { 'test/config' }
let(:tmp_dir) do
File.expand_path('../../../tmp/', __FILE__)
end
let(:tmp_test_config) do
File.join(tmp_dir, test_config)
end
let(:tmp_test_config_xml) do
tmp_test_config + '.xml'
end
def read_file_content(file)
content = ''
File.open(file, 'r') do |f|
content = f.readlines
end
content
end
subject do
ResultSaverToDirectory.new(tmp_dir)
end
before do
File.unlink(tmp_test_config) if File.exist?(tmp_test_config)
end
it 'saves to a directory' do
subject.save(test_config, 'test config content')
expect(read_file_content(tmp_test_config_xml)).to eql ['test config content']
end
it 'saves to a directory multiline text' do
subject.save(test_config, "first line\nsecond line")
expect(read_file_content(tmp_test_config_xml)).to eql ["first line\n", "second line"]
end
end
end
end
|
ashumkin/quickbuild-config-gem
|
spec/quickbuild/config/result_saver_spec.rb
|
Ruby
|
mit
| 1,931
|
#include "PlayerInputSystem.h"
#include <iostream>
void PlayerInputSystem::update(int elapsedTimeMs, World &world) {
for (auto ev: world.entities) {
Entity *entity = ev.second;
if(!entity->hasComponents(ComponentTypes::K_PLAYER_INPUT_MAP))
{
continue;
}
SDL_assert(entity->getId() == 0);
Velocity *v = static_cast<Velocity *>(entity->getComponentForType(ComponentTypes::K_VELOCITY));
PlayerInputMap *inputMap = static_cast<PlayerInputMap *>(entity->getComponentForType(ComponentTypes::K_PLAYER_INPUT_MAP));
PlayerInput *input = static_cast<PlayerInput *>(entity->getComponentForType(ComponentTypes::K_PLAYER_INPUT));
SDL_assert(v != nullptr);
SDL_assert(inputMap != nullptr);
SDL_assert(input != nullptr);
bool dirty = false;
input->input.clear();
for(auto im : inputMap->keyMap) {
if(keyboardState[im.first])
{
switch(im.second)
{
case PlayerActions::moveLeft:
input->input[PlayerActions::moveLeft] = true;
dirty = true;
break;
case PlayerActions::moveRight:
input->input[PlayerActions::moveRight] = true;
dirty = true;
break;
case PlayerActions::jump:
input->input[PlayerActions::jump] = true;
dirty = true;
break;
case PlayerActions::shoot:
//Fire!
input->input[PlayerActions::shoot] = true;
break;
default:
dirty = false;
break;
}
}
}
//This feels weird here
Rendered *render = static_cast<Rendered *>(entity->getComponentForType(ComponentTypes::K_RENDERED));
if(dirty == false)
{
if(v->velX > 0.0) {
render->spriteName = "playerStandLeft";
}
if(v->velX < 0.0) {
render->spriteName = "playerStandRight";
}
//No keys touched, default to standing
render->currentFrame = 0;
entity->removeComponent(ComponentTypes::K_ANIMATION);
v->velX = 0;
}
}
}
|
recursivefaults/mustached-wight
|
src/systems/PlayerInputSystem.cpp
|
C++
|
mit
| 2,493
|
'use strict';
describe('Authentication Identity Specification', function()
{
var _authIdentity;
var _httpBackend;
var _identity = {
key1: 'value1',
key2: 'value2',
key3: {
subKey1: 'subValue1',
subKey2: 'subValue2'
}
};
var _authRequests;
beforeEach(angular.mock.module('dgAuth'));
beforeEach(function()
{
inject(function($injector)
{
_authIdentity = $injector.get('authIdentity');
_authRequests = $injector.get('authRequests');
_httpBackend = $injector.get('$httpBackend');
var http = $injector.get('$http');
spyOn(_authRequests, 'getPromise').andCallFake(function()
{
return http.post('/fake');
});
_httpBackend.whenPOST('/fake').respond(function()
{
return [201, '', ''];
});
});
});
afterEach(function()
{
_httpBackend.verifyNoOutstandingExpectation();
_httpBackend.verifyNoOutstandingRequest();
});
describe('tests access methods', function()
{
it('should get null values', function()
{
expect(_authIdentity.has()).toBeFalsy();
expect(_authIdentity.get()).toBeNull();
expect(_authIdentity.get('some_key')).toBeNull();
});
it('should set the values and gets them', function()
{
_authIdentity.set(null, _identity);
expect(_authIdentity.has()).toBeTruthy();
expect(_authIdentity.get('key1')).toEqual(_identity.key1);
expect(_authIdentity.get('key2')).toEqual(_identity.key2);
expect(_authIdentity.get('key3')).toEqual(_identity.key3);
expect(_authIdentity.get('fake')).toBeNull();
expect(_authIdentity.get()).toEqual(_identity);
});
it('should set one value and gets it', function()
{
_authIdentity.set('key', 'value');
expect(_authIdentity.has()).toBeTruthy();
expect(_authIdentity.get('key')).toEqual('value');
_authIdentity.set(null, _identity);
expect(_authIdentity.get()).toEqual(_identity);
expect(_authIdentity.get('key')).toBeNull();
});
it('should clear the identity', function()
{
_authIdentity.set(null, _identity);
expect(_authIdentity.has()).toBeTruthy();
_authIdentity.clear();
expect(_authIdentity.has()).toBeFalsy();
expect(_authIdentity.get()).toBeNull();
});
});
});
|
tafax/angular-digest-auth
|
tests/authIdentitySpec.js
|
JavaScript
|
mit
| 2,665
|
<div class="vertical-scroll">
<table class="table table-striped">
<thead>
<tr>
<th class="table-id">#</th>
<th>Name</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of smartTableData.test_cases; let i = index">
<td class="table-id">{{ i + 1 }}</td>
<td>{{ item.name }}</td>
<td>{{ item.result }}</td>
</tr>
</tbody>
</table>
</div>
|
iandian/testmgui
|
src/app/pages/report/stripedTable/stripedTable.html
|
HTML
|
mit
| 420
|
class CreateIncidents < ActiveRecord::Migration
def change
create_table :incidents do |t|
t.string :name
t.text :description
t.string :image
t.string :location
t.integer :user_id
t.decimal :latitude
t.decimal :longitude
t.timestamps null: false
end
end
end
|
dnajjar/Candid_Sidewalk
|
db/migrate/20150529140725_create_incidents.rb
|
Ruby
|
mit
| 316
|
---
layout: post
title: "介绍一篇Jekyll+github建立自己博客的文章"
date: 2016-03-06 22:34:39 +0800
category: Jekyll
---
介绍一篇我自己看到过的算是讲解的比较详细的Jekyll+github建立博客的文章,我现在的这个Jekyll博客就是通过学习这篇文章自己建立的,有需要可以借鉴
<br />感谢原文博主
[戳此链接](http://pizida.com/technology/2016/03/03/use-jekyll-create-blog-on-github/)
|
352512482/eric
|
_posts/2016-03-06-介绍一篇Jekyll+github建立自己博客的文章.markdown
|
Markdown
|
mit
| 450
|
/**
* Automatically generated file. Please do not edit.
* @author Highcharts Config Generator by Karasiq
* @see [[http://api.highcharts.com/highmaps]]
*/
package com.highmaps.config
import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._
/**
* @note JavaScript name: <code>series<ikh>-dragDrop-guideBox-default</code>
*/
@js.annotation.ScalaJSDefined
class SeriesIkhDragDropGuideBoxDefault extends com.highcharts.HighchartsGenericObject {
/**
* <p>CSS class name of the guide box in this state. Defaults to
* <code>highcharts-drag-box-default</code>.</p>
* @since 6.2.0
*/
val className: js.UndefOr[String] = js.undefined
/**
* <p>Width of the line around the guide box.</p>
* @since 6.2.0
*/
val lineWidth: js.UndefOr[Double] = js.undefined
/**
* <p>Color of the border around the guide box.</p>
* @since 6.2.0
*/
val lineColor: js.UndefOr[String | js.Object] = js.undefined
/**
* <p>Guide box fill color.</p>
* @since 6.2.0
*/
val color: js.UndefOr[String | js.Object] = js.undefined
/**
* <p>Guide box cursor.</p>
* @since 6.2.0
*/
val cursor: js.UndefOr[String] = js.undefined
/**
* <p>Guide box zIndex.</p>
* @since 6.2.0
*/
val zIndex: js.UndefOr[Double] = js.undefined
}
object SeriesIkhDragDropGuideBoxDefault {
/**
* @param className <p>CSS class name of the guide box in this state. Defaults to. <code>highcharts-drag-box-default</code>.</p>
* @param lineWidth <p>Width of the line around the guide box.</p>
* @param lineColor <p>Color of the border around the guide box.</p>
* @param color <p>Guide box fill color.</p>
* @param cursor <p>Guide box cursor.</p>
* @param zIndex <p>Guide box zIndex.</p>
*/
def apply(className: js.UndefOr[String] = js.undefined, lineWidth: js.UndefOr[Double] = js.undefined, lineColor: js.UndefOr[String | js.Object] = js.undefined, color: js.UndefOr[String | js.Object] = js.undefined, cursor: js.UndefOr[String] = js.undefined, zIndex: js.UndefOr[Double] = js.undefined): SeriesIkhDragDropGuideBoxDefault = {
val classNameOuter: js.UndefOr[String] = className
val lineWidthOuter: js.UndefOr[Double] = lineWidth
val lineColorOuter: js.UndefOr[String | js.Object] = lineColor
val colorOuter: js.UndefOr[String | js.Object] = color
val cursorOuter: js.UndefOr[String] = cursor
val zIndexOuter: js.UndefOr[Double] = zIndex
com.highcharts.HighchartsGenericObject.toCleanObject(new SeriesIkhDragDropGuideBoxDefault {
override val className: js.UndefOr[String] = classNameOuter
override val lineWidth: js.UndefOr[Double] = lineWidthOuter
override val lineColor: js.UndefOr[String | js.Object] = lineColorOuter
override val color: js.UndefOr[String | js.Object] = colorOuter
override val cursor: js.UndefOr[String] = cursorOuter
override val zIndex: js.UndefOr[Double] = zIndexOuter
})
}
}
|
Karasiq/scalajs-highcharts
|
src/main/scala/com/highmaps/config/SeriesIkhDragDropGuideBoxDefault.scala
|
Scala
|
mit
| 3,001
|
if defined?(Rails::Railtie)
module Kumade
class Railtie < ::Rails::Railtie
rake_tasks do
load "kumade/tasks/deploy.rake"
end
end
end
end
|
thoughtbot/kumade
|
lib/kumade/railtie.rb
|
Ruby
|
mit
| 169
|
<?php
declare(strict_types=1);
namespace Scyzoryck\GridBundle\DataSource;
class IteratorData implements Data
{
/**
* @var \Iterator
*/
private $iterator;
public function __construct(\Iterator $iterator)
{
$this->iterator = $iterator;
}
/**
* @inheritdoc
*/
public function count(): int
{
return iterator_count($this->iterator);
}
/**
* @inheritdoc
*/
public function getSlice(int $start = 0, int $limit = null): \Iterator
{
if (is_null($limit)) {
return new \LimitIterator($this->iterator, $start);
}
return new \LimitIterator($this->iterator, $start, $limit);
}
}
|
scyzoryck/grid-bundle
|
DataSource/IteratorData.php
|
PHP
|
mit
| 705
|
angular.module('keyringLogin', ['auth'])
.component('keyringLogin', {
templateUrl : 'users/login',
controllerAs: 'login',
controller: ['$scope', '$http', '$location', '$httpParamSerializerJQLike', 'auth', function($scope, $http, $location, $httpParamSerializerJQLike, auth) {
this.username = '';
this.password = '';
this.submit = function(e, url) {
var url = e.target.action;
e.preventDefault();
e.stopPropagation();
$http({
method: 'POST',
url: url,
data: $httpParamSerializerJQLike({
username: this.username,
password: this.password
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data) {
auth.setToken(data.token);
$location.path('/');
}).error(function(e) {
this.error = e;
}.bind(this));
return false;
};
}]
})
|
vincentdieltiens/secure-keychain-php-backend
|
app/Resources/public/js/login.js
|
JavaScript
|
mit
| 850
|
package de.slgdev.messenger.network;
import de.slgdev.leoapp.service.SocketService;
import de.slgdev.leoapp.utility.Utils;
import de.slgdev.messenger.activity.AddGroupChatActivity;
import de.slgdev.messenger.activity.ChatActivity;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
public class SocketListener extends WebSocketListener {
private SocketService socketService;
private MessageHandler messageHandler;
public SocketListener(SocketService socketService, MessageHandler messageHandler) {
this.socketService = socketService;
this.messageHandler = messageHandler;
}
@Override
public void onOpen(WebSocket webSocket, Response response) {
Utils.logDebug(response.headers().toString());
Utils.logDebug(response.message());
socketService.setSocketRunning(true);
}
@Override
public void onMessage(WebSocket webSocket, String message) {
if (message.startsWith("+OK id")) {
int cid = Integer.parseInt(
message.substring(6)
);
ChatActivity chatActivity = Utils.getController().getChatActivity();
if (chatActivity != null) {
chatActivity.setCid(cid);
}
AddGroupChatActivity addGroupChatActivity = Utils.getController().getAddGroupChatActivity();
if (addGroupChatActivity != null) {
addGroupChatActivity.setCid(cid);
}
} else {
messageHandler.append(message);
}
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
Utils.logDebug("Socket closed!");
socketService.setSocketRunning(false);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
if (response != null) {
Utils.logDebug(response.headers().toString());
Utils.logDebug(response.message());
}
Utils.logError(t);
socketService.setSocketRunning(false);
socketService.startSocket();
}
}
|
LCA311/leoapp-sources
|
app/src/main/java/de/slgdev/messenger/network/SocketListener.java
|
Java
|
mit
| 2,112
|
var ffi = require('ffi'),
ref = require('ref'),
RefArray = require('ref-array'),
Struct = require('ref-struct'),
Union = require('ref-union'),
_library = require('./');
loadDependentSymbols();
_library._preload['the_dependent'] = [function () {
_library.the_dependent = _library.dependent;
}];
_library.my_enum = {
five: 555,
VAR_THREE: 24,
VAR_TWO: 23,
VAR_FOUR: 25,
VAR_ONE: -1
};
_library._preload['my_function'] = [function () {
_library.my_function = ['double', ['int32', 'int', ref.refType('uint'), 'float']];
_library._functions['my_function'] = _library.my_function;
}];
_library._preload['my_other_function'] = ['pointer', function () {
_library.my_other_function = [ref.refType('double'), [ref.refType('int32'), ref.refType('int'), ref.refType(ref.refType('uint')), ref.refType('float')]];
_library._functions['my_other_function'] = _library.my_other_function;
}];
_library.nothing = Struct({});
_library.nothing.size = 1;
_library._preload['nothing'] = [function () {
_library.nothing.size = 0;
_library.nothing.defineProperty("__ignore", 'char');
}];
_library._preload['nill'] = [function () {
_library.nill = _library.nothing;
}];
_library._preload['zilch'] = ['nill', function () {
_library.zilch = _library.nill;
}];
_library.something = Struct({});
_library.something.size = 1;
_library._preload['something'] = ['nothing', 'nothing', 'dependent', 'dependent', function () {
_library.something.size = 0;
_library.something.defineProperty("field", 'int');
_library.something.defineProperty("another", 'int32');
_library.something.defineProperty("firstfield", _library.__RefArray('int', 4));
_library.something.defineProperty("message", ref.refType('char'));
_library.something.defineProperty("nillo", _library.nothing);
_library.something.defineProperty("dependent", _library.dependent);
}];
_library.flying_struct = Struct({});
_library.flying_struct.size = 1;
_library._preload['flying_struct'] = ['something', 'something', 'flying_struct', function () {
_library.flying_struct.size = 0;
_library.flying_struct.defineProperty("identity", 'longlong');
_library.flying_struct.defineProperty("object", _library.something);
_library.flying_struct.defineProperty("recursive_pointer", ref.refType(_library.flying_struct));
}];
_library._preload['invasion_force'] = [function () {
_library.invasion_force = _library.__RefArray(_library.flying_struct, 64);
}];
_library.variant1 = Union({});
_library.variant1.size = 1;
_library._preload['variant1'] = ['flying_struct', 'flying_struct', 'something', 'something', 'zilch', 'nothing', function () {
_library.variant1.size = 0;
_library.variant1.defineProperty("val1", _library.flying_struct);
_library.variant1.defineProperty("val2", _library.something);
_library.variant1.defineProperty("val3", _library.zilch);
}];
_library.variant2 = Union({});
_library.variant2.size = 1;
_library._preload['variant2'] = ['variant1', 'variant1', 'stat', 'stat', function () {
_library.variant2.size = 0;
_library.variant2.defineProperty("v1", _library.variant1);
_library.variant2.defineProperty("v2", _library.__RefArray('int', 5));
_library.variant2.defineProperty("str", (function () {
var temp = Struct({});
temp.defineProperty("text", ref.refType('char'));
temp.defineProperty("length", 'ulong');
return temp;
})());
_library.variant2.defineProperty("gs", _library.stat);
}];
_library._preload['my_function_pointer'] = ['void (int, int *, struct flying_struct *)', function () {
_library.my_function_pointer = ffi.Function('void', ['int', ref.refType('int'), ref.refType(_library.flying_struct)]);
}];
_library._preload['my_other_function_pointer'] = ['unsigned int (long double, long double, long long)', function () {
_library.my_other_function_pointer = ffi.Function('uint', ['double', 'double', 'longlong']);
}];
_library._preload['my_undefined_struct_typedef'] = [function () {
_library.my_undefined_struct_typedef = 'void';
}];
_library._preload['my_struct_function'] = ['variant1', function () {
_library.my_struct_function = ['void', [ref.refType(_library.variant1)]];
_library._functions['my_struct_function'] = _library.my_struct_function;
}];
_library.my_unused_struct = Struct({});
_library.my_unused_struct.size = 1;
_library._preload['my_unused_struct'] = [function () {
_library.my_unused_struct.size = 0;
_library.my_unused_struct.defineProperty("a", 'int');
}];
function loadDependentSymbols() {
require('./used.js');
}
|
diosmosis/node-ffi-generator
|
tests/smoke/out/input.js
|
JavaScript
|
mit
| 4,638
|
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Mike Murach & Associates - Professional Programming Books</title>
<link rel="stylesheet" type="text/css" href="styles/main.css" media="screen">
<!-- JavaScript HTML requirements -->
<script src="tabs_library.js"></script>
<script src="tabs.js"></script>
</head>
<body>
<section>
<h1>Murach's JavaScript and DOM Scripting</h1><br>
<ul id="tab_list">
<li><a href="" id="tab1" class="active">Contents</a></li>
<li><a href="" id="tab2" class="">Author</a></li>
<li><a href="" id="tab3" class="">Downloads</a></li>
</ul>
<div id="tab_contents">
<div class="">
<h2>The table of contents</h2>
<p>The descriptive text for this tab.</p>
</div>
<div class="hide">
<h2>About the author</h2>
</div>
<div class="hide">
<h2>About the downloads</h2>
</div>
</div>
</section>
</body>
</html>
|
JaimeLynSchatz/project-stash
|
murach/html5_css3/book_examples/ch13/09_tabs/index.html
|
HTML
|
mit
| 1,126
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_31) on Mon Apr 06 20:32:39 EDT 2015 -->
<title>All Classes</title>
<meta name="date" content="2015-04-06">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<h1 class="bar">All Classes</h1>
<div class="indexContainer">
<ul>
<li><a href="net/datastructures/AbstractBinaryTree.html" title="class in net.datastructures" target="classFrame">AbstractBinaryTree</a></li>
<li><a href="net/datastructures/AbstractTree.html" title="class in net.datastructures" target="classFrame">AbstractTree</a></li>
<li><a href="net/datastructures/BinaryTree.html" title="interface in net.datastructures" target="classFrame"><span class="interfaceName">BinaryTree</span></a></li>
<li><a href="BinaryTreeTest.html" title="class in <Unnamed>" target="classFrame">BinaryTreeTest</a></li>
<li><a href="net/datastructures/LinkedBinaryTree.html" title="class in net.datastructures" target="classFrame">LinkedBinaryTree</a></li>
<li><a href="net/datastructures/LinkedBinaryTree.Node.html" title="class in net.datastructures" target="classFrame">LinkedBinaryTree.Node</a></li>
<li><a href="net/datastructures/LinkedQueue.html" title="class in net.datastructures" target="classFrame">LinkedQueue</a></li>
<li><a href="net/datastructures/Position.html" title="interface in net.datastructures" target="classFrame"><span class="interfaceName">Position</span></a></li>
<li><a href="net/datastructures/Queue.html" title="interface in net.datastructures" target="classFrame"><span class="interfaceName">Queue</span></a></li>
<li><a href="net/datastructures/SinglyLinkedList.html" title="class in net.datastructures" target="classFrame">SinglyLinkedList</a></li>
<li><a href="net/datastructures/Tree.html" title="interface in net.datastructures" target="classFrame"><span class="interfaceName">Tree</span></a></li>
</ul>
</div>
</body>
</html>
|
patkub/java-data-structures-algorithms
|
LinkedBST/javadoc/allclasses-frame.html
|
HTML
|
mit
| 2,092
|
<!DOCTYPE html>
<html>
<head>
<title>Awesome All</title>
<meta name="description" content="A curated list of all the awesome lists of awesome frameworks, libraries and software" />
</head>
<body>
<textarea theme="united" style="display:none;">
# [Awesome all](https://github.com/bradoyler/awesome-all)
A curated list of all the awesome lists of awesome frameworks, libraries and software
### Contributing
Please take a quick gander at the [contribution guidelines](https://github.com/bradoyler/awesome-all/blob/master/CONTRIBUTING.md) first. Thanks to all [contributors](https://github.com/bradoyler/awesome-all/graphs/contributors); you rock!
### Contents
- [Android](https://github.com/JStumpp/awesome-android)
- [AutoIt](https://github.com/J2TeaM/awesome-AutoIt)
- [Bash](https://github.com/alebcay/awesome-shell)
- [Big data](https://github.com/onurakpolat/awesome-bigdata)
- [C](https://github.com/kozross/awesome-c)
- [C++](https://github.com/fffaraz/awesome-cpp)
- [Clojure](https://github.com/razum2um/awesome-clojure)
- [Cobol](https://github.com/dshimy/awesome-cobol)
- [Common Lisp](https://github.com/kozross/awesome-cl)
- [Community](https://github.com/peterkokot/awesome-community)
- [D](https://github.com/zhaopuming/awesome-d)
- [Dojo Toolkit](https://github.com/peterkokot/awesome-dojo)
- [Elixir](https://github.com/h4cc/awesome-elixir)
- [Frontend Dev](https://github.com/dypsilon/frontend-dev-bookmarks)
- [Go](https://github.com/avelino/awesome-go)
- [Hadoop](https://github.com/youngwookim/awesome-hadoop)
- [iOS](https://github.com/vsouza/awesome-ios)
- [IoT](https://github.com/HQarroum/awesome-iot)
- [Java](https://github.com/akullpp/awesome-java)
- [JavaScript](https://github.com/sorrycc/awesome-javascript)
- [jQuery](https://github.com/peterkokot/awesome-jquery)
- [Lists](https://github.com/jnv/lists)
- [Node.js](https://github.com/vndmtrx/awesome-nodejs)
- [PHP](https://github.com/ziadoz/awesome-php)
- [Python](https://github.com/vinta/awesome-python)
- [React-Native](https://github.com/jondot/awesome-react-native)
- [Ruby](https://github.com/markets/awesome-ruby)
- [Scala](https://github.com/lauris/awesome-scala)
- [Search Engine Optimization (SEO)](https://github.com/marcobiedermann/search-engine-optimization)
- [Swift](https://awesome-swift.zeef.com/robin.eggenkamp)
- [Sysadmin](https://github.com/kahun/awesome-sysadmin)
- [Talks](https://github.com/JanVanRyswyck/awesome-talks)
- [Wikipedia](https://github.com/emijrp/awesome-wikipedia)
<a href="https://github.com/bradoyler/awesome-all"><img style="position: fixed; top: 0; right: 0; border: 0; z-index: 1000; margin: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub"></a>
</textarea>
<script src="http://strapdownjs.com/v/0.2/strapdown.js"></script>
</body>
</html>
|
bradoyler/awesome-all
|
index.html
|
HTML
|
mit
| 2,835
|
package testing
import (
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/transport/ray"
)
type TestPacketDispatcher struct {
LastPacket chan v2net.Packet
Handler func(packet v2net.Packet, traffic ray.OutboundRay)
}
func NewTestPacketDispatcher(handler func(packet v2net.Packet, traffic ray.OutboundRay)) *TestPacketDispatcher {
if handler == nil {
handler = func(packet v2net.Packet, traffic ray.OutboundRay) {
for payload := range traffic.OutboundInput() {
traffic.OutboundOutput() <- payload.Prepend([]byte("Processed: "))
}
close(traffic.OutboundOutput())
}
}
return &TestPacketDispatcher{
LastPacket: make(chan v2net.Packet, 16),
Handler: handler,
}
}
func (this *TestPacketDispatcher) DispatchToOutbound(packet v2net.Packet) ray.InboundRay {
traffic := ray.NewRay()
this.LastPacket <- packet
go this.Handler(packet, traffic)
return traffic
}
|
evolsnow/v2ray-core
|
app/dispatcher/testing/dispatcher.go
|
GO
|
mit
| 919
|
/*!
*************************************************************************************
* \file sei.h
*
* \brief
* Prototypes for sei.c
*************************************************************************************
*/
#ifndef SEI_H
#define SEI_H
typedef enum {
SEI_BUFFERING_PERIOD = 0,
SEI_PIC_TIMING,
SEI_PAN_SCAN_RECT,
SEI_FILLER_PAYLOAD,
SEI_USER_DATA_REGISTERED_ITU_T_T35,
SEI_USER_DATA_UNREGISTERED,
SEI_RECOVERY_POINT,
SEI_DEC_REF_PIC_MARKING_REPETITION,
SEI_SPARE_PIC,
SEI_SCENE_INFO,
SEI_SUB_SEQ_INFO,
SEI_SUB_SEQ_LAYER_CHARACTERISTICS,
SEI_SUB_SEQ_CHARACTERISTICS,
SEI_FULL_FRAME_FREEZE,
SEI_FULL_FRAME_FREEZE_RELEASE,
SEI_FULL_FRAME_SNAPSHOT,
SEI_PROGRESSIVE_REFINEMENT_SEGMENT_START,
SEI_PROGRESSIVE_REFINEMENT_SEGMENT_END,
SEI_MOTION_CONSTRAINED_SLICE_GROUP_SET,
SEI_FILM_GRAIN_CHARACTERISTICS,
SEI_DEBLOCKING_FILTER_DISPLAY_PREFERENCE,
SEI_STEREO_VIDEO_INFO,
SEI_POST_FILTER_HINT,
SEI_TONE_MAPPING_INFO,
SEI_SCALABILITY_INFO,
SEI_SUB_PIC_SCALABLE_LAYER,
SEI_NON_REQUIRED_LAYER_REP,
SEI_PRIORITY_LAYER_INFO,
SEI_LAYERS_NO_PRESENT,
SEI_LAYER_DEPENDENCY_CHANGE,
SEI_SCALABLE_NESTING,
SEI_BASE_LAYER_TEMPORAL_HRD,
SEI_QUALITY_LAYER_INTEGRITY_CHECK,
SEI_REDUNDANT_PIC_PROPERTY,
SEI_TL0_DEP_REP_INDEX,
SEI_TL_SWITCHING_POINT,
SEI_PARALLEL_DECODING_INFO,
SEI_MVC_SCALABLE_NESTING,
SEI_VIEW_SCALABILITY_INFO,
SEI_MULTIVIEW_SCENE_INFO,
SEI_MULTIVIEW_ACQUISITION_INFO,
SEI_NON_REQUIRED_VIEW_COMPONENT,
SEI_VIEW_DEPENDENCY_CHANGE,
SEI_OPERATION_POINTS_NOT_PRESENT,
SEI_BASE_VIEW_TEMPORAL_HRD,
SEI_MAX_ELEMENTS //!< number of maximum syntax elements
} SEI_type;
#define MAX_FN 256
CREL_RETURN InterpretSEIMessage PARGS2(byte* msg, int size);
void interpret_spare_pic PARGS2( byte* payload, int size);
void interpret_subsequence_info PARGS2( byte* payload, int size);
void interpret_subsequence_layer_characteristics_info PARGS2( byte* payload, int size);
void interpret_subsequence_characteristics_info PARGS2( byte* payload, int size);
void interpret_scene_information PARGS2( byte* payload, int size); // JVT-D099
void interpret_user_data_registered_itu_t_t35_info( byte* payload, int size);
void interpret_user_data_unregistered_info PARGS2( byte* payload, int size);
void interpret_pan_scan_rect_info PARGS2( byte* payload, int size);
void interpret_recovery_point_info PARGS2( byte* payload, int size);
void interpret_filler_payload_info( byte* payload, int size);
void interpret_dec_ref_pic_marking_repetition_info PARGS3( byte* payload, int size, unsigned int view_index);
void interpret_full_frame_freeze_info( byte* payload, int size);
void interpret_full_frame_freeze_release_info( byte* payload, int size);
void interpret_full_frame_snapshot_info PARGS2( byte* payload, int size);
void interpret_progressive_refinement_start_info( byte* payload, int size);
void interpret_progressive_refinement_end_info PARGS2( byte* payload, int size);
void interpret_motion_constrained_slice_group_set_info PARGS2( byte* payload, int size);
void interpret_reserved_info( byte* payload, int size);
CREL_RETURN interpret_buffering_period_info PARGS3( byte* payload, int size, unsigned int view_index);
void interpret_picture_timing_info PARGS3( byte* payload, int size, unsigned int view_index);
void interpret_mvc_scalable_nesting PARGS4( byte* payload, int *size, int *num_views, int* view_indexs);
void interpret_offset_metadata PARGS2(byte* payload, int size);
#endif
|
goodspeed24e/2011Corel
|
Video/Dec/Core/H264VDec/Main/H264VDec/H264VDecHP/sei.h
|
C
|
mit
| 3,436
|
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/php-git.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/php-git.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/php-git"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/php-git"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
make -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
|
rsky/php-git
|
docs/Makefile
|
Makefile
|
mit
| 4,594
|
/**
* Created by ZhiyuanSun on 16/9/22.
*/
import React, {Component} from 'react';
import EventSelectionItemImage from './event-selection-item-image';
export default class EventSelectionItem extends Component{
static defaultProps = {
showImage: false,
lazyLoading: false
};
constructor(props){
super(props);
this.state = {
showImage: false
}
}
componentWillMount(){
}
componentWillUpdate(){
}
componentDidMount(){
}
render(){
let {item, lazyLoading} = this.props;
return (
<li>
<a href={item.url}>
<EventSelectionItemImage {...this.props} img={item.img}></EventSelectionItemImage>
<p>{item.description}</p>
</a>
</li>
);
}
}
|
sunzy0212/local-event
|
UI/src/components/event-selection/js/event-selection-item.js
|
JavaScript
|
mit
| 743
|
---
title: Country Assignments
date: 2017-10-14 11:06:57 -0400
type: page
menu:
sidebar:
pre: "<i class='fa fa-globe'></i>"
weight: 12
---
## DAYMUNC Country Assignments
---
We are accepting Country Assignments starting November 13th to November 19th (early preference submission). Country Assignments
can absolutely change after the early preference submission deadline.
### Country Assignment Rules:
- If you are attending NMUN, and we have your team’s country assignment, your delegation will have special preference for that country. Meaning your delegates are guaranteed that country for committees. (For example, if your delegation is representing the United Kingdom at NMUN. Your team size is 20. 4 of your delegates will be representing United Kingdom at DAYMUNC)
- Trading Country Assignments between schools is allowed and encouraged. You are more than welcome to begin the trade process between delegations and have both delegations send the Secretary-General an email confirming the trade. The Secretary-General can also help with this process by facilitating the conversation or providing contact information.
- As long as there are open slots and your team has enough delegates, you may request for more Country Assignments. Model UN teams fluctuate throughout the year; thus it is perfectly acceptable to withdraw or request Assignments.
- Exemptions can be made if new delegates are added to the team. Again, if there are open spots, you can request an assignment.
If you have any questions regarding Country Assignments, never hesitate to contact the Secretary-General ({{< variables sg_email >}})!
All delegations will be automatically granted their NMUN Member State assignments. If you have not received the full list, please contact the Secretary-General.
<!-- {{< CountryAssignmentTable >}} -->
|
daymunc/daymunc_website
|
content/country.md
|
Markdown
|
mit
| 1,833
|
require 'avro_turf/confluent_schema_registry'
require 'avro_turf/in_memory_cache'
require 'avro_turf/disk_cache'
# Caches registrations and lookups to the schema registry in memory.
class AvroTurf::CachedConfluentSchemaRegistry
# Instantiate a new CachedConfluentSchemaRegistry instance with the given configuration.
# By default, uses a provided InMemoryCache to prevent repeated calls to the upstream registry.
#
# upstream - The upstream schema registry object that fully responds to all methods in the
# AvroTurf::ConfluentSchemaRegistry interface.
# cache - Optional user provided Cache object that responds to all methods in the AvroTurf::InMemoryCache interface.
def initialize(upstream, cache: nil)
@upstream = upstream
@cache = cache || AvroTurf::InMemoryCache.new()
end
# Delegate the following methods to the upstream
%i(subjects subject_versions check compatible?
global_config update_global_config subject_config update_subject_config).each do |name|
define_method(name) do |*args|
instance_variable_get(:@upstream).send(name, *args)
end
end
def fetch(id)
@cache.lookup_by_id(id) || @cache.store_by_id(id, @upstream.fetch(id))
end
def register(subject, schema)
@cache.lookup_by_schema(subject, schema) || @cache.store_by_schema(subject, schema, @upstream.register(subject, schema))
end
def subject_version(subject, version = 'latest')
return @upstream.subject_version(subject, version) if version == 'latest'
@cache.lookup_by_version(subject, version) ||
@cache.store_by_version(subject, version, @upstream.subject_version(subject, version))
end
end
|
dasch/avro_turf
|
lib/avro_turf/cached_confluent_schema_registry.rb
|
Ruby
|
mit
| 1,674
|
<?php
/*
* The MIT License
*
* Copyright (c) 2010 Johannes Mueller <circus2(at)web.de>
*
* 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 MwbExporter\Formatter\Doctrine2\Yaml\Model;
use MwbExporter\Core\Model\ForeignKeys as Base;
class ForeignKeys extends Base
{
public function __construct($data, $parent)
{
parent::__construct($data, $parent);
}
}
|
allansun/mysql-workbench-schema-exporter
|
lib/MwbExporter/Formatter/Doctrine2/Yaml/Model/ForeignKeys.php
|
PHP
|
mit
| 1,430
|
<div class="form-group">
<select
class="form-control"
ng-model="$ctrl.mode"
ng-options="mode | translate for mode in $ctrl.modes"
ng-click="$ctrl.hasError = false">
</select>
</div>
<div>
<form
name="idsl_form"
novalidate
ng-show="$ctrl.mode === 'Local'">
<div class="form-group">
<div class="input-group">
<input
name="file"
type="file"
required
/>
<input
class="form-control"
placeholder="{{'No file' | translate}}"
readonly
type="text"
value="{{$ctrl.fileNameAndSize}}"
ng-click="$ctrl.browse()"
/>
<span class="input-group-btn">
<button
class="btn btn-default"
type="button"
ng-click="$ctrl.browse()"
translate>Browse</button>
</span>
</div>
</div>
<div class="form-group">
<button
class="btn btn-sm btn-default form-control"
ng-class="{'has-error': $ctrl.hasError}"
title="{{'Load a file from local' | translate}}"
type="submit"
ng-click="idsl_form.$valid && $ctrl.load()"
ng-disabled="$ctrl.file === undefined || $ctrl.hasError"
>
<span ng-if="!$ctrl.hasError">{{'Load local file' | translate}}</span>
<span ng-if="$ctrl.hasError">{{'Unable to load the file' | translate}}</span>
</button>
</div>
</form>
<form
name="idsc_form"
novalidate
ng-show="$ctrl.mode === 'Online'">
<div class="form-group gmf-importdatasource-url-form-group">
<input
autocomplete="off"
class="form-control"
name="url"
placeholder="{{'Choose or enter online resource URL' | translate}}"
required
type="url"
ng-disabled="$ctrl.pending"
ng-model="$ctrl.url"
/>
</div>
<div class="form-group">
<button
class="btn btn-sm btn-default form-control gmf-importdatasource-connect-btn"
ng-class="{'has-error': $ctrl.hasError}"
title="{{'Connect to online resource' | translate}}"
type="submit"
ng-click="idsc_form.$valid && $ctrl.connect()"
ng-disabled="idsc_form.$invalid || $ctrl.pending"
>
<span
ng-if="$ctrl.pending"
>{{'Connecting, please wait...' | translate}}</span>
<span
ng-if="!$ctrl.pending && $ctrl.hasError"
>{{'Failed to connect' | translate}}</span>
<span
ng-if="!$ctrl.pending && !$ctrl.hasError"
>{{'Connect' | translate}}</span>
</button>
</div>
</form>
</div>
<div
class="gmf-importdatasource-layers"
ng-if="$ctrl.wmsCapabilities !== null || $ctrl.wmtsCapabilities !== null">
<hr />
<gmf-wmscapabilitylayertreenode
capabilities="::$ctrl.wmsCapabilities"
layer="::$ctrl.wmsCapabilities.Capability.Layer"
url="::$ctrl.url"
ng-if="$ctrl.wmsCapabilities !== null">
</gmf-wmscapabilitylayertreenode>
<gmf-wmtscapabilitylayertree
capabilities="::$ctrl.wmtsCapabilities"
layers="::$ctrl.wmtsCapabilities.Contents.Layer"
url="::$ctrl.url"
ng-if="$ctrl.wmtsCapabilities !== null">
</gmf-wmtscapabilitylayertree>
</div>
|
Geoportail-Luxembourg/geoportailv3
|
geoportal/geoportailv3_geoportal/static-ngeo/ngeo/contribs/gmf/src/import/importdatasourceComponent.html
|
HTML
|
mit
| 3,244
|
/* FONT AWESOME */
[class*="fa-"]:before {
font-family: 'FontAwesome', sans-serif;
}
/* QUIZ STYLES */
.quiz hr {
margin: 20px 0;
}
.quiz hr:first-child {
margin-top: 30px;
}
.quiz hr: last-child {
margin-bottom: 30px;
}
.quiz h3 {
margin-top: 5px;
}
.quiz ol {
list-style-type: none;
padding: 0;
}
.quiz input[type=radio] {
width: 20px;
height: 20px;
}
.quiz-question {
padding: 10px;
margin: 10px 0;
}
.quiz-question.incomplete {
border: 1px solid rgba(200, 56, 0, 0.25);
background-color: rgba(200, 56, 0, 0.02);
-webkit-border-radius: 5px;
border-radius: 5px;
}
.quiz-question .question-text {
float: left;
width: 620px;
margin: 0;
}
.quiz-question ol.sub-question-text {
list-style-position: outside;
list-style-type: upper-alpha;
padding-left: 40px;
}
.quiz-question .mc-question-text {
float: right;
}
.quiz-question ol.mc-sub-question-text li {
display: inline-block;
margin-right: 10px;
text-align: center;
min-width: 37px;
max-width: 90px;
}
.quiz-question ol.mc-sub-question-text li:last-child {
margin-right: 0;
}
.mc-question-text textarea.mc-sub-question-text {
width: 400px;
height: 100px;
}
/* QUIZ RESULTS STYLES */
.quiz-answer h4 {
font-weight: bold;
margin-top: 20px;
}
.quiz-results hr,
.quiz-scorecard hr {
margin-top: 30px;
margin-bottom: 30px;
border-color: rgba(64, 179, 79, 0.25);
}
.quiz-answer ol {
margin-bottom: 20px;
list-style-type: upper-alpha;
}
.quiz-answer i {
width: 35px;
display: inline-block;
}
.quiz-answer .correct {
color: #40B34F;
}
.quiz-answer .incorrect {
color: rgb(200, 56, 0);
}
/* QUIZ SCORECARD STYLES */
.quiz-scorecard table {
margin: 30px auto;
}
.pretest-scorecard table {
width: 520px;
}
.posttest-scorecard table {
width: 880px;
}
.quiz-scorecard thead,
.quiz-scorecard tfoot {
font-weight: bold;
}
.quiz-scorecard thead {
font-size: 13px;
}
.quiz-scorecard th,
.quiz-scorecard td {
border: 1px solid #CCC;
padding: 10px;
}
.quiz-scorecard td:nth-child(2),
.quiz-scorecard td:nth-child(4) {
border-right: none;
}
.quiz-scorecard td:nth-child(3),
.quiz-scorecard td:nth-child(5) {
border-left: none;
}
.quiz-scorecard th {
text-align: center;
background-color: #EEE;
}
.quiz-scorecard ol,
.quiz-scorecard ul {
margin: 0;
padding: 0;
list-style-type: none;
}
/* Correct/Incorrect Questions */
.quiz-scorecard td:nth-child(2),
.quiz-scorecard td:nth-child(4) {
width: 151px;
padding: 5px;
text-align: center;
}
.quiz-scorecard ol li {
float: left;
margin: 5px;
}
/* Percent Correct and Percent Difference */
.quiz-scorecard td:nth-child(3),
.quiz-scorecard td:nth-child(5),
.quiz-scorecard td:nth-child(6) {
width: 100px;
text-align: center;
}
.quiz-scorecard .score-percent-container,
.quiz-scorecard .difference-percent-container {
position: relative;
margin: 0;
padding: 0;
}
.quiz-scorecard .score-percent-container {
width: 90px;
height: 90px;
}
.quiz-scorecard .score-percent {
font-size: 18px;
font-weight: bold;
position: absolute;
top: 31px;
width: 93px;
text-align: center;
}
.quiz-scorecard .difference-percent {
font-size: 30px;
font-weight: bold;
}
.quiz-scorecard circle {
stroke-width: 7px;
stroke-linecap: butt;
}
.quiz-scorecard circle: last-child {
/* The actual % stroke */
stroke: #40B34F;
}
.quiz-scorecard .better {
color: rgb(64, 179, 79);
}
.quiz-scorecard .worse {
color: rgb(200, 56, 0);
}
/* Core Competency */
.quiz-scorecard td:nth-child(1) {
font-size: 14px;
}
/* Totals */
.quiz-scorecard .quiz-scorecard-subtotal td:not(:last-child),
.quiz-scorecard .quiz-scorecard-total td:not(:last-child),
.quiz-scorecard .quiz-scorecard-subtotal td:nth-child(1),
.quiz-scorecard .quiz-scorecard-total td:nth-child(1) {
/* Last rule necessary to out-specify another */
font-size: 30px;
text-align: center;
}
.quiz-scorecard .quiz-scorecard-subtotal td,
.quiz-scorecard .quiz-scorecard-subtotal td:nth-child(1) {
/* Last rule necessary to out-specify another */
background-color: #FFD;
}
.quiz-scorecard .quiz-scorecard-total td,
.quiz-scorecard .quiz-scorecard-total td:nth-child(1) {
/* Last rule necessary to out-specify another */
background-color: #EFF;
}
/* Scorecard Question Buttons */
.quiz-scorecard-question button {
background-color: #FFF;
color: #333;
padding: 3px 0;
width: 60px;
-webkit-border-radius: 5px;
border-radius: 5px;
}
.quiz-scorecard-question span {
font-size: 17px;
font-weight: bold;
}
.quiz-scorecard-question i.correct {
color: rgb(64, 179, 79);
}
.quiz-scorecard-question i.incorrect {
color: rgb(200, 56, 0);
}
.quiz-scorecard-question button.correct {
border: 1px solid rgba(64, 179, 79, 0.5);
background-color: rgba(64, 179, 79, 0.15);
}
.quiz-scorecard-question button.incorrect {
border: 1px solid rgba(200, 56, 0, 0.5);
background-color: rgba(200, 56, 0, 0.15);
}
.quiz-scorecard-question button.correct:hover {
background-color: rgba(64, 179, 79, 0.35);
}
.quiz-scorecard-question button.incorrect:hover {
background-color: rgba(200, 56, 0, 0.35);
}
/* Submission History */
.submission-history td,
.submission-history th {
height: 35px;
}
.submission-history td.submissionNum,
.submission-history th.submissionNum {
text-align: left;
padding-left: 20px;
width: 60px;
}
.submission-history td.submissionDate,
.submission-history th.submissionDate {
text-align: left;
width: 180px;
}
.submission-history td.submissionScore,
.submission-history th.submissionScore {
text-align: left;
width: 120px;
}
|
AxonInteractive/angularjs-quizzes
|
app/app.css
|
CSS
|
mit
| 5,571
|
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="../img/favicon.ico">
<title>More Conduit Metaphor notes - Thesis Notes and drafts</title>
<link href='https://fonts.googleapis.com/css?family=Lato:400,700|Roboto+Slab:400,700|Inconsolata:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="../css/theme.css" type="text/css" />
<link rel="stylesheet" href="../css/theme_extra.css" type="text/css" />
<link rel="stylesheet" href="../css/highlight.css">
<script>
// Current page data
var mkdocs_page_name = "More Conduit Metaphor notes";
var mkdocs_page_input_path = "more_conduit_metaphor_notes.md";
var mkdocs_page_url = "/more_conduit_metaphor_notes/";
</script>
<script src="../js/jquery-2.1.1.min.js"></script>
<script src="../js/modernizr-2.8.3.min.js"></script>
<script type="text/javascript" src="../js/highlight.pack.js"></script>
</head>
<body class="wy-body-for-nav" role="document">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side stickynav">
<div class="wy-side-nav-search">
<a href=".." class="icon icon-home"> Thesis Notes and drafts</a>
<div role="search">
<form id ="rtd-search-form" class="wy-form" action="../search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<ul class="current">
<li class="toctree-l1">
<a class="" href="..">Index</a>
</li>
<li class="toctree-l1">
<a class="" href="../carver_proposal_draft_v4/">Proposal Draft</a>
</li>
<li class="toctree-l1">
<a class="" href="../wittgenstein_PI_readers_guide/">Notes for Philosophical Investgations readers guide</a>
</li>
<li class="toctree-l1">
<a class="" href="../keith-wittgenstein-notes/">From Language Games to Forms of Life reading notes</a>
</li>
<li class="toctree-l1">
<a class="" href="../carver_outline_04082017/">Initial Outline 04.08.2017</a>
</li>
<li class="toctree-l1">
<a class="" href="../cimcil_rethinking_PM_actuality/">Rethinking Actuality reading notes</a>
</li>
<li class="toctree-l1">
<a class="" href="../enh-work_oriented_design_notes/">Ehn - Work Oriented Design reading notes</a>
</li>
<li class="toctree-l1">
<a class="" href="../pleasants_wittgenstein_crit_theory/">Pleasants - Wittgenstein and Critical Theory reading notes</a>
</li>
<li class="toctree-l1">
<a class="" href="../rethinking_communication_mckay/">McKay - Rethinking Communication reading notes</a>
</li>
<li class="toctree-l1">
<a class="" href="../schatzki-bourdieu-giddens/">Schatzki critique of Bourdieu Giddens reading notes</a>
</li>
<li class="toctree-l1">
<a class="" href="../johnson_ben_thesis_notes/">Across the Divide: Reconciling Scrum and Enterprise with genre ecologies reading notes</a>
</li>
<li class="toctree-l1">
<a class="" href="../watson_practice_theory_notes/">Watson Practice Theory reading notes</a>
</li>
<li class="toctree-l1">
<a class="" href="../conduit_metaphor_notes/">Conduit Metaphor reading notes</a>
</li>
<li class="toctree-l1">
<a class="" href="../list_of_practices/">List of Practices</a>
</li>
<li class="toctree-l1 current">
<a class="current" href="./">More Conduit Metaphor notes</a>
<ul class="subnav">
<li class="toctree-l2"><a href="#conduit-metaphor-notes">Conduit metaphor notes</a></li>
</ul>
</li>
<li class="toctree-l1">
<a class="" href="../meeting_questions_notes/">Meeting Questions and Notes</a>
</li>
<li class="toctree-l1">
<a class="" href="../email_to_bill_4_29_2017/">email_to_bill_4_29_2017</a>
</li>
<li class="toctree-l1">
<a class="" href="../CM_appendix_table_dc_notes/">Coduit Metaphor Appendex</a>
</li>
</ul>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" role="navigation" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="..">Thesis Notes and drafts</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="..">Docs</a> »</li>
<li>More Conduit Metaphor notes</li>
<li class="wy-breadcrumbs-aside">
</li>
</ul>
<hr/>
</div>
<div role="main">
<div class="section">
<h4 id="conduit-metaphor-notes">Conduit metaphor notes</h4>
<p>p. 287</p>
<blockquote>
<p>If there are dead metaphors in (1) through (3), then, they all seem
to involve the figurative assertion that language transfers human
thoughts and feelings. Notice that this assertion, even in its present,
very general form, leads already to a distinct viewpoint on communications
problems. A person who speaks poorly does not know how to use
language to send people his thoughts; and, conversely, a good speaker
knows how to transfer his thoughts perfectly via language. If we were
to follow this viewpoint, the next question would be: What must the
poor speaker do with his thoughts if he is to transfer them more accurately
by means of language? The surprising thing is that, whether we
like it or not, the English language does follow this veiwpoint. It provides,
in the form of a wealth of metaphorical expressions, answers to
this and other questions, all of which answers are perfectly coherent
with the assumption that human communication achieves the physical
transfer of thoughts and feelings. If there were only a few such expressions
involved, or if they were random, incoherent figures of speech
arising from different paradigms - or if they were abstract, not particularly
graphic images - then one might just succeed in dismissing
them as harmless analogies. But in fact, none of these mitigating circumstances
comes into play.</p>
</blockquote>
<ul>
<li>
<p>Conduit metaphors always have to do with inserting thoughts, feelings, ideas, mental activity into words; that there is an "inside" and an "outside" to a word.</p>
</li>
<li>
<p>P.289</p>
<ul>
<li>"Repertoire" = Baggage - all your mental and emotional stuff that you bring to a given situation and probably some other stuff too (i.e. I think it might be best to understand "repertoire" as similar to Habitus).<ul>
<li>what other things?<ul>
<li>Genre (ecologies)</li>
<li>Practices</li>
<li>Whatever Gidden's was on about</li>
<li>At some point going to have to think about what W would have to say about Reddy.</li>
</ul>
</li>
</ul>
</li>
<li>RM = repertoire member - a term or expression that can be understood as referring to mental and emotional stuff...IOW, refering to or evincing some trait recognizable as originating from the speaker's mind. A <em>feeling or thought</em> that one is attempting to "insert" into a word or sentence.</li>
</ul>
</li>
<li>
<p>p.290</p>
<ul>
<li><em>s</em> = signal or vessel<ul>
<li>so, "physically put <em>RM</em> (thoughts, feelings) into <em>s</em> (word/phrase/sentence/poem)</li>
</ul>
</li>
<li><strong>Major Framework</strong> = core expressions that:<ul>
<li>language is a conduit for transferring thoughts between people</li>
<li>people insert thoughts and feelings into words</li>
<li>words are able to transfer thoughts and feelings because they (words) can "contain" thoughts and feelings.</li>
<li>People are able to received and extract the sender's thoughts and feelings and derive meaning.</li>
</ul>
</li>
</ul>
</li>
<li>
<p>p.291 <strong>Minor framework</strong> - generally speaking, does not require the "container" aspect</p>
<ul>
<li>Thoughts and feelings are sent out into the "idea space"</li>
<li>"Thoguhts and feelings are <strong><em>reified</em></strong> in this space (apparently means that once written or uttered, thoughts and feelings exist independently of the human mind - they are "out there" or "external."</li>
<li>Reified thoughts and feelings sometimes find their way back into the minds of other humans</li>
</ul>
</li>
<li>
<p>p.292 - 295 <strong>Toolmaker's paradigm</strong></p>
</li>
<li>
<p>295</p>
<blockquote>
<p>Both models offer an explanation of the phenomenon of communication. But they come to totally different conclusions about what, in that phenomenon, are more natural states of affairs, and what are less natural, or constrained, states. In terms of the conduit metaphor, what requires explanation is failure to communicate. Success appears to be automatic. But if we think in terms of the toolmaker's paradigm, our expectation is precisely the opposite. Partial miscommunication, or divergence of readings from a single text are not aberrations. They are tendencies inherent in the systems, which can only be counteracted by continuous effort and by larges amounts of verbal interaction.</p>
</blockquote>
</li>
<li>
<p>p.296</p>
<blockquote>
<ul>
<li>But I do not want to argue too strongly either for or against either of these models in this paper.</li>
<li>To me, from my vantage point now, it seems that the toolmakers paradigm and radical subjectivity simply for a coherent, common-sense view of what happens when we talk.</li>
<li>...the conduit metaphor is a real and powerful semantic structure in English, which can influence our thinking - then if follows that "common-sense" about language may be confused.</li>
</ul>
</blockquote>
</li>
<li>
<p>p. 297: <strong>Semantic Pathology</strong></p>
<blockquote>
<ul>
<li>The logic of the framework [the conduit metaphor] runs like threads in many directions through the syntactic and semantic fabric of our speech habits. Merely becoming cognizant of this in no way alters the situation. Nor does it appear that one can adopt a new framework and develop it while ignoring the cloth of the language. For everywhere one runs into the old thread, and each one pushes conversation and thought back a little way toward the established pattern.</li>
</ul>
</blockquote>
</li>
<li>
<p>We commonly misuderstand the Whorf hypothesis</p>
</li>
<li>
<p>it doesn't mean that we can't ever think in terms of another model, but those moments will be fragmented and isolated.</p>
</li>
<li>
<p>p.298</p>
<ul>
<li>Characteristics of (core) expressions that eschew "conduit" language<ul>
<li>
<ol>
<li>Expressions are multisyllabic, abstract and therefore neither "graphic" (helpful for "showing" not "telling"??) nor metaphorically coherent. IOW, they're boring, $10 dictionary words. they do not propose an alternative to "putting thoughts and feelings into words" which remains the only available explanation.</li>
<li>ex. communicate, disseminate</li>
</ol>
</li>
<li>\2. Can be used in conjunction with "in words" - words that imply that words have an "inside" and are capable of containing ideas.</li>
</ul>
</li>
</ul>
</li>
<li>
<p>p.299
> A "Semantic Pathology" - arises "whenever two or more incompatible senses capable of figuring meaningfully in the same context develop around the same name." (<em>Principles of Semantics</em>, Stephen Ullmann)</p>
</li>
<li>
<p>Example of the difficultly in avoiding the conduit metaphor:</p>
<ul>
<li>Distinction between sympathy and apology - "I'm sorry" can mean "I empathize with your suffering," or "I admit fault and aplogize."</li>
<li>The issue becomes terms that could be RMs (term indiciating a thought or feeling or idea) or <em>s</em>'s (signals - the the thing which "contains" the idea or feeling - often referring to a word or text).</li>
</ul>
</li>
</ul>
</div>
</div>
<footer>
<div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
<a href="../meeting_questions_notes/" class="btn btn-neutral float-right" title="Meeting Questions and Notes">Next <span class="icon icon-circle-arrow-right"></span></a>
<a href="../list_of_practices/" class="btn btn-neutral" title="List of Practices"><span class="icon icon-circle-arrow-left"></span> Previous</a>
</div>
<hr/>
<div role="contentinfo">
<!-- Copyright etc -->
</div>
Built with <a href="http://www.mkdocs.org">MkDocs</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<div class="rst-versions" role="note" style="cursor: pointer">
<span class="rst-current-version" data-toggle="rst-current-version">
<span><a href="../list_of_practices/" style="color: #fcfcfc;">« Previous</a></span>
<span style="margin-left: 15px"><a href="../meeting_questions_notes/" style="color: #fcfcfc">Next »</a></span>
</span>
</div>
<script src="../js/theme.js"></script>
</body>
</html>
|
lexicondevil12/thesis_notes
|
site/more_conduit_metaphor_notes/index.html
|
HTML
|
mit
| 13,899
|
using Microsoft.CodeAnalysis.Emit;
namespace NoiseLab.PolyGen.Core.Domain
{
public class CodeGenerationArtifact
{
internal CodeGenerationArtifact(EmitResult emitResult, byte[] peBytes, byte[] pdbBytes, byte[] xmlBytes)
{
EmitResult = emitResult;
PeBytes = peBytes;
PdbBytes = pdbBytes;
XmlBytes = xmlBytes;
}
public EmitResult EmitResult { get; }
public byte[] PeBytes { get; }
public byte[] PdbBytes { get; }
public byte[] XmlBytes { get; }
}
}
|
dr-noise/PolyGen
|
src/NoiseLab.PolyGen.Core/Domain/CodeGenerationArtifact.cs
|
C#
|
mit
| 563
|
<?php return unserialize('a:1:{i:0;O:27:"Doctrine\\ORM\\Mapping\\Column":9:{s:4:"name";s:17:"COM_CREATION_DATE";s:4:"type";s:8:"datetime";s:6:"length";N;s:9:"precision";i:0;s:5:"scale";i:0;s:6:"unique";b:0;s:8:"nullable";b:0;s:7:"options";a:0:{}s:16:"columnDefinition";N;}}');
|
solag/Sofia
|
app/cache/dev/annotations/ac7c2577d746463f0adeebf9373c37cdc16a0582$creationdate.cache.php
|
PHP
|
mit
| 276
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Injectable } from '@angular/core';
@Injectable()
export class Service31Service {
constructor() { }
}
|
angular/angular-cli-stress-test
|
src/app/services/service-31.service.ts
|
TypeScript
|
mit
| 319
|
require 'active_support/core_ext'
require 'protojson/codec/codec_interface'
module Protojson
module Codec
class JsonIndexed
extend Protojson::Codec::CodecInterface
class << self
def encode(message)
data = Protojson::Codec::Hash.encode(message, :tag)
serialize_hash_to_indexed(data).to_s
end
def decode(message, data)
data.is_a?(String) and data = ActiveSupport::JSON.decode(data)
values = parse_indexed_to_hash(message.new, data)
Protojson::Codec::Hash.decode(message, values, :tag)
end
# This class method serializes a Hash
def serialize_hash_to_indexed(value)
!value.is_a?(::Hash) and raise ArgumentError, "value must be a hash"
# index value
index = ""
index.respond_to?(:force_encoding) and index.force_encoding("UTF-8") # 1.9.2
# field values
result = []
value.each_pair { |key, value|
index << key.to_i+48 # ASCII integer. 1 => 49, ...
# recursive call if value is a Hash
if value.is_a?(::Hash)
value = serialize_hash_to_indexed(value)
# array => serializes each element
elsif value.is_a?(Array)
value.map! { |val|
if val.is_a?(::Hash)
serialize_hash_to_indexed(val)
else
val
end
}
end
# insert encoded value in Array
result.push value
}
# include index as first element
result.unshift(index)
end
# This method parses a INDEXED encoded message to a hash using
# message message as model.
# We need to know the specific message to decode to differenciate between
# vectors and message fields
def parse_indexed_to_hash(message, data)
values = {}
index = data.shift
index.each_codepoint { |tag|
tag = tag-48
field = message.get_field_by_tag(tag)
val = data.shift
if val.is_a?(Array) && field.is_a?(Protobuf::Field::MessageField)
if field.repeated?
val.map! { |v|
v = parse_indexed_to_hash(field.type, v)
}
else
val = parse_indexed_to_hash(field.type, val)
end
end
values[tag.to_s] = val
}
values
end
end
end
end
end
|
juandebravo/ProtoJSON4Ruby
|
lib/protojson/codec/json_indexed.rb
|
Ruby
|
mit
| 2,568
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter;
using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Rsvd;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
namespace Microsoft.Protocols.TestSuites.FileSharing.RSVD.TestSuite
{
[TestClass]
public class ReadWriteSharedVHD : RSVDTestBase
{
#region Test Suite Initialization
// Use ClassInitialize to run code before running the first test in the class
[ClassInitialize()]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
// Use ClassCleanup to run code after all tests in a class have run
[ClassCleanup()]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
[TestMethod]
[TestCategory(TestCategories.Bvt)]
[TestCategory(TestCategories.RsvdVersion1)]
[TestCategory(TestCategories.RsvdVersion2)]
[Description("Check if server handles Read request to a shared virtual disk file correctly.")]
public void BVT_ReadSharedVHD()
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "1. Client opens a shared virtual disk file successfully.");
OpenSharedVHD(TestConfig.NameOfSharedVHDX);
BaseTestSite.Log.Add(LogEntryKind.TestStep, "2. Client reads file content and expects success.");
byte[] payload;
uint status = client.Read(0, 512, out payload);
BaseTestSite.Assert.AreEqual(
(uint)Smb2Status.STATUS_SUCCESS,
status,
"Read content of shared virtual disk file should succeed, actual status: {0}",
GetStatus(status));
BaseTestSite.Log.Add(LogEntryKind.TestStep, "3. Client closes the file.");
client.CloseSharedVirtualDisk();
}
[TestMethod]
[TestCategory(TestCategories.Bvt)]
[TestCategory(TestCategories.RsvdVersion1)]
[TestCategory(TestCategories.RsvdVersion2)]
[Description("Check if server handles Write request to a shared virtual disk file correctly.")]
public void BVT_WriteSharedVHD()
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "1. Client opens a shared virtual disk file successfully.");
OpenSharedVHD(TestConfig.NameOfSharedVHDX);
BaseTestSite.Log.Add(LogEntryKind.TestStep, "2. Client writes file content and expects success.");
byte[] payload = new byte[512];
uint status = client.Write(0, payload);
BaseTestSite.Assert.AreEqual(
(uint)Smb2Status.STATUS_SUCCESS,
status,
"Write content of shared virtual disk file should succeed, actual status: {0}",
GetStatus(status));
BaseTestSite.Log.Add(LogEntryKind.TestStep, "3. Client closes the file.");
client.CloseSharedVirtualDisk();
}
}
}
|
chenlu0616/WindowsProtocolTestSuites
|
TestSuites/FileServer/src/RSVD/TestSuite/ReadWriteSharedVHD.cs
|
C#
|
mit
| 3,426
|
new (require('front.js').Front)().init().start();
|
unau/gmx
|
start_gmxd.js
|
JavaScript
|
mit
| 51
|
System.register([], function (exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var RestMethod;
return {
setters: [],
execute: function () {
(function (RestMethod) {
RestMethod[RestMethod["POST"] = 0] = "POST";
RestMethod[RestMethod["GET"] = 1] = "GET";
RestMethod[RestMethod["PUT"] = 2] = "PUT";
RestMethod[RestMethod["DELETE"] = 3] = "DELETE";
})(RestMethod || (RestMethod = {}));
exports_1("RestMethod", RestMethod);
}
};
});
//# sourceMappingURL=type-rest-method.js.map
|
gobiiproject/GOBii-System
|
gobiiproject/gobii-web/src/main/webapp/js/gobii_modules/model/type-rest-method.js
|
JavaScript
|
mit
| 651
|
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
* Copyright 2015 Chiori-chan. All Right Reserved.
*/
package com.chiorichan.packet;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import com.chiorichan.util.ObjectUtil;
import com.chiorichan.util.PacketUtils;
/**
* @author Chiori Greene
* @email chiorigreene@gmail.com
*/
public class PayloadValue
{
enum ValueType
{
NULL, TRUE, FALSE, BYTES, STRING, PAYLOAD, LONG;
public static ValueType Boolean( boolean val )
{
return ( val ) ? ValueType.TRUE : ValueType.FALSE;
}
}
public static final PayloadValue NULL = new PayloadValue();
public static final PayloadValue TRUE = new PayloadValue( true );
public static final PayloadValue FALSE = new PayloadValue( false );
public static final PayloadValue EMPTY = new PayloadValue( new byte[0] );
ValueType type = ValueType.NULL;
Object value = null;
public PayloadValue()
{
if ( this instanceof PacketPayload )
type = ValueType.PAYLOAD;
}
public PayloadValue( boolean value )
{
type = ValueType.Boolean( value );
}
public PayloadValue( byte[] value )
{
type = ValueType.BYTES;
this.value = value;
}
public PayloadValue( String value )
{
type = ValueType.STRING;
this.value = value;
}
public PacketPayload asPayload()
{
return ( PacketPayload ) this;
}
protected ByteBuf encode()
{
ByteBuf buf = Unpooled.buffer();
byte[] value = getBytes();
if ( value == null )
switch ( type )
{
case TRUE:
buf.writeByte( 0x08 ); // true???
break;
case FALSE:
buf.writeByte( 0x07 ); // false???
break;
}
else if ( value.length == 0 )
buf.writeByte( 0x02 ); // empty
else if ( value.length == 1 && value[0] == 0x0a )
buf.writeByte( 0x0a );
else if ( type == ValueType.LONG )
{
buf.writeByte( 0x03 );
buf.writeBytes( value );
}
else
{
buf.writeByte( 0x06 );
buf.writeByte( ( byte ) value.length );
buf.writeBytes( value );
}
return buf;
}
public boolean getBoolean()
{
return ObjectUtil.castToBool( value );
}
public byte[] getBytes()
{
if ( type == ValueType.BYTES )
return ( byte[] ) value;
if ( type == ValueType.LONG )
{
ByteBuf buf = Unpooled.directBuffer( 8 );
buf.writeLong( ( Long ) value );
return buf.array();
}
if ( type == ValueType.STRING )
return ( ( String ) value ).getBytes();
return null;
}
public PacketPayload getPayload()
{
if ( type == ValueType.PAYLOAD )
return ( ( PacketPayload ) this );
return null;
}
public String getString()
{
if ( type == ValueType.STRING )
return ( ( String ) value );
if ( type == ValueType.BYTES )
return new String( ( ( byte[] ) value ) );
if ( type == ValueType.TRUE )
return "true";
if ( type == ValueType.FALSE )
return "false";
return null;
}
public ValueType getType()
{
return type;
}
public boolean isBoolean()
{
return type == ValueType.TRUE || type == ValueType.FALSE;
}
public boolean isBytes()
{
return type == ValueType.BYTES;
}
public boolean isLong()
{
return type == ValueType.LONG;
}
public boolean isNull()
{
return type == ValueType.NULL;
}
public boolean isPayload()
{
return type == ValueType.PAYLOAD;
}
public boolean isString()
{
return type == ValueType.STRING;
}
protected void putValue( Object val )
{
if ( val instanceof Long )
type = ValueType.LONG;
if ( val instanceof String )
type = ValueType.STRING;
else if ( val instanceof byte[] )
type = ValueType.BYTES;
else if ( val instanceof Boolean )
{
type = ValueType.Boolean( ( boolean ) val );
return;
}
else
return;
value = val;
}
@Override
public String toString()
{
String val = "";
if ( isBytes() )
val = PacketUtils.hex2Readable( getBytes() );
else if ( isBoolean() )
val = ObjectUtil.castToString( getBoolean() );
else if ( isNull() )
val = "null";
else
val = value.toString();
return val;
}
}
|
ChioriGreene/GreenetreeESM
|
API/src/main/java/com/chiorichan/packet/PayloadValue.java
|
Java
|
mit
| 4,148
|
<!-- Se expone el controlador myCtrl como objeto saludoCtlr, tener en cuenta que asi perdemos la herencia ya que no
estaremos accediendo a propiedades del $scope sino del objeto que exponemos en el controlador. Otro punto a
tener en cuenta es que al no usar el $scope para unir el controlador con la vista, se pierde la posibilidad
de utilizar las demás bondades que brinda el objeto $scope en sí.
Basicamente se está haciendo un new del controller y la referencia se está pasando al <<this>>
nota: Como se puede ver, ahora al controller no se le inyecta el servicio $scope, esto se llama función anónima-->
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="UTF-8">
<title ng-bind="titulo"></title>
</head>
<body>
<p>Try to change the names.</p>
<div ng-controller="myCtrl as saludoCtrl">
First Name: <input type="text" ng-model="saludoCtrl.firstName"><br>
Last Name: <input type="text" ng-model="saludoCtrl.lastName"><br>
<br>
Full Name: {{saludoCtrl.firstName + " " + saludoCtrl.lastName}}
<p ng-bind="saludoCtrl.firstName +' '+ saludoCtrl.lastName"></p>
</div>
<script src="bower_components/angular/angular.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function() {
/*
Puede declararse asi, pero como no se esta perdiendo
el ambito de this, se utiliza en este ejemplo de forma
directa.
var vm= this;
vm.firstName= "Andres";
vm.lastName= "Mirabal";
vm.titulo= "un titulo";*/
this.firstName= "Andres";
this.lastName= "Mirabal";
this.titulo= "un titulo";
});
</script>
</body>
</html>
|
zeeeros/nglr-by-my-own
|
app/6ctrlAsObject.html
|
HTML
|
mit
| 1,662
|
<?php
namespace SearchBundle\Controller;
use CommonBundle\Controller\BaseController;
use SearchBundle\Form\SearchType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class SearchController extends BaseController
{
/**
* @return Response
*/
public function indexAction()
{
$form = $this->createForm(new SearchType());
return $this->render('SearchBundle:Search:index.html.twig', [
'form' => $form->createView(),
]);
}
/**
* @param Request $request
* @return Response
*/
public function getAdvertsAction(Request $request)
{
$form = $this->createForm(new SearchType());
$form->handleRequest($request);
$adverts = $this->get('advert.advert_repository')->search($form->getData());
return $this->render('@Search/Search/adverts.html.twig', [
'adverts' => $adverts,
]);
}
}
|
morcov/traktor
|
src/SearchBundle/Controller/SearchController.php
|
PHP
|
mit
| 963
|
<!DOCTYPE html>
<html style="height: 100%">
<head lang="en">
<meta charset="UTF-8">
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<link href="monthlySales.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<!-- you don't need ignore=notused in your code, this is just here to trick the cache -->
<script src="../dist/angular-grid.js?ignore=notused1"></script>
<link rel="stylesheet" type="text/css" href="../dist/angular-grid.css?ignore=notused1">
<link rel="stylesheet" type="text/css" href="../dist/theme-fresh.css?ignore=notused1">
<script src="monthlySales.js"></script>
<style>
.ag-basic .ag-cell {
padding-top: 2px !important;
padding-bottom: 2px !important;
}
label {
font-weight: normal !important;
}
body {
padding: 0px;
margin: 0px;
}
.cell-act {
background: rgba(255,0,0,0.1);
}
.cell-bud {
background: rgba(0,255,0,0.1);
}
.cell-negative {
color: darkred;
}
.cell-figure {
text-align: right;
}
.ag-row-group {
font-weight: bold;
}
</style>
</head>
<body ng-app="monthlySales" style="height: 100%">
<div ng-controller="monthlySalesController" style="width: 100%; height: 100%;">
<div style="height: 10%; padding: 10px;">
<input type="text" style="width: 100px;" ng-model="gridOptions.quickFilterText" placeholder="Filter..."/>
<span style="padding-left: 20px;">
<b>Rows (visible / total):</b> {{rowCount}}
</span>
<span style="padding-left: 20px;">
<b>Period:</b> {{monthName}}
<button ng-click="onChangeMonth(-1)"><i class="fa fa-chevron-left"></i></button>
<button ng-click="onChangeMonth(1)"><i class="fa fa-chevron-right"></i></button>
</span>
<span style="padding-left: 20px;">
<b>Legend:</b>
<span class="cell-bud" style="border: 1px solid black;">
</span> Actual
<span class="cell-act" style="border: 1px solid black;">
</span> Budget
</span>
</div>
<div style="width: 100%; height: 90%; padding: 10px;"
ag-grid="gridOptions"
class="ag-fresh">
</div>
</div>
</body>
</html>
|
bpbhat77/angular-grid
|
docs/example-expressions-and-context/monthlySales.html
|
HTML
|
mit
| 3,167
|
CREATE DATABASE IF NOT EXISTS local_tsmean;
CREATE DATABASE IF NOT EXISTS test_tsmean;
|
tsmean/tsmean
|
docker/mysql/init-db.sql
|
SQL
|
mit
| 87
|
AmsterdamCoin is a PoS-based cryptocurrency.
AmsterdamCoin uses libsecp256k1,
libgmp,
Boost1.55,
OR Boost1.57,
Openssl1.01p,
Berkeley DB 4.8,
QT5 to compile
Block Spacing: 60 Seconds
Stake Minimum Age: 24 Hours
Port: 61510
RPC Port: 61511
BUILD LINUX
-----------
1) git clone https://github.com/CoinProjects/amsterdamcoin.git amsterdamcoin
2) cd amsterdamcoin/src
3) sudo make -f makefile.unix # Headless amsterdamcoin
(optional)
4) strip amsterdamcoind
5) sudo cp amsterdamcoind /usr/local/bin
BUILD WINDOWS
-------------
1) Download Qt.zip from https://github.com/CoinProjects/AmsterdamCoin/releases/tag/1.2.3B and unpack to C:/
2) Download AmsterdamCoin source from https://github.com/CoinProjects/AmsterdamCoin/archive/master.zip
2.1) Unpack to C:/AmsterdamCoin
3) Install Perl for windows from the homepage http://www.activestate.com/activeperl/downloads
4) Download Python 2.7 https://www.python.org/downloads/windows/
4.1) While installing python make sure to add python.exe to the path.
5) Run msys.bat located in C:\MinGW49-32\msys\1.0
6) cd /C/AmsterdamCoin/src/leveldb
7) Type "TARGET_OS=NATIVE_WINDOWS make libleveldb.a libmemenv.a" and hit enter to build leveldb
8) Exit msys shell
9) Open windows command prompt
10) cd C:/dev
11) Type "49-32-qt5.bat" and hit enter to run
12) cd ../AmsterdamCoin
13) Type "qmake USE_UPNP=0" and hit enter to run
14) Type "mingw32-make" and hit enter to start building. When it's finished you can find your .exe in the release folder.
|
CoinProjects/AmsterdamCoin
|
README.md
|
Markdown
|
mit
| 1,557
|
# Mdl-vue-hints
|
Jameswilliamquinn2016/Mdl-vue-hints
|
README.md
|
Markdown
|
mit
| 15
|
<?php
namespace Application\View\Helper;
use Dashboard\Model\Dashboard;
use Dashboard\Data\ApiDashboardResource;
use DvsaCommon\Auth\MotAuthorisationServiceInterface;
use DvsaCommon\Auth\MotIdentityProviderInterface;
use DvsaCommon\Auth\PermissionAtSite;
use DvsaCommon\Utility\ArrayUtils;
use DvsaFeature\FeatureToggles;
use Zend\View\Helper\AbstractHelper;
/**
* DashboardDataProvider - helper for view.
*
* accessible by this->dashboardDataProvider() in any *.phtml file
*/
class DashboardDataProvider extends AbstractHelper
{
/**
* @var MotIdentityProviderInterface
*/
protected $identityProvider;
/**
* @var ApiDashboardResource
*/
protected $apiService;
/**
* @var FeatureToggles $featureToggles
*/
protected $featureToggles;
/**
* @param MotIdentityProviderInterface $identityProvider
* @param ApiDashboardResource $apiService
*/
public function __construct(
MotIdentityProviderInterface $identityProvider,
ApiDashboardResource $apiService,
MotAuthorisationServiceInterface $authorisationService,
FeatureToggles $featureToggles
) {
$this->identityProvider = $identityProvider;
$this->apiService = $apiService;
$this->authorisationService = $authorisationService;
$this->featureToggles = $featureToggles;
}
/**
* @return Dashboard
*/
public function __invoke()
{
$identity = $this->identityProvider->getIdentity();
if ($identity) {
$data = $this->apiService->get($identity->getUserId());
$data['testingVehicle'] = null;
$dashboard = new Dashboard($data, $this->featureToggles);
$aeList = $dashboard->getAuthorisedExaminers();
foreach ($aeList as $ae) {
$sites = ArrayUtils::filter($ae->getSites(), function ($site) {
return $this->authorisationService->isGrantedAtSite(PermissionAtSite::VEHICLE_TESTING_STATION_READ, $site->getId());
});
$ae->setSites($sites);
}
$dashboard->setAuthorisedExaminers($aeList);
return $dashboard;
}
}
}
|
dvsa/mot
|
mot-web-frontend/module/Application/src/Application/View/Helper/DashboardDataProvider.php
|
PHP
|
mit
| 2,221
|
import {Path, PathMatcher, IMatchResult} from './Path';
/**
* Route
*
* @class Route
*/
export class Route {
public currentRoute: Route;
/**
* The url paths of the route
*
* @type {Array<string>}
*/
public paths: Array<Path> = [];
/**
* The path of the component loaded by this route
*
* @type {string}
*/
public componentPath: string;
/**
* Title of the route
*
* @type {string}
*/
public title: string;
/**
* The custom data of the route
*
* @type {*} The custom data of the workflow can be any user defined type
*/
public metaData: any = {};
/**
* Returns the first path of the route
*
* @returns {string}
*/
public path: string;
/**
* Indicates if te route is the active route
*
* @type {boolean}
*/
public isActive: boolean;
/**
* Creates an instance of Route.
*
* @param {Array<string>} paths The url paths of the route
* @param {string} componentPath The component loaded by the router for given its route paths
* @param {string} title The title of the route
* @param {*} [metaData] The medata of the route
*/
constructor(paths: Array<string> | string, componentPath: string, title: string, metaData?: any) {
let pathsArray: Array<string> = typeof paths === 'string' ? [paths] : paths;
this.path = '#' + pathsArray[0];
pathsArray.forEach(path => {
this.paths.push(Path.parsePath(path));
});
this.componentPath = componentPath;
this.title = title;
this.metaData = metaData;
}
public matches(pathMatcher: PathMatcher): IMatchResult {
var bestMatch: IMatchResult = null;
for (let i = 0; i < this.paths.length; i++) {
var match = this.paths[i].match(pathMatcher);
if (bestMatch === null || bestMatch.score < match.score)
bestMatch = match;
}
return bestMatch;
}
}
|
rzvpopescu/typy
|
lib/Router/Route.ts
|
TypeScript
|
mit
| 2,064
|
package com.slowhand.monaka.view;
import java.util.List;
import com.slowhand.monaka.log.MoAppJournalLog;
import com.slowhand.monaka.log.MoJournalLogManager;
import com.slowhand.monaka.util.MoStringUtil;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
/**
* 基底Activityクラス<br>
* android.support.v4.app.FragmentActivity
*
* @author slowhand0309
*/
public abstract class MoBaseActivity extends FragmentActivity {
private static final String TAG = MoBaseActivity.class.getSimpleName();
private MoAppJournalLog mAppLog;
/**
* Activity起動
*/
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
/* LogManager取得 */
MoJournalLogManager lm
= MoJournalLogManager.getInstance(getApplicationContext());
mAppLog = lm.getAppJournalLog();
mAppLog.outputLog(TAG, this.getClass().getSimpleName() + "#onCreate");
}
/**
* Activity終了
*/
@Override
protected void onDestroy() {
mAppLog.outputLog(TAG, this.getClass().getSimpleName() + "#onDestory");
super.onDestroy();
}
/**
* アプリケーションジャーナルログ出力
*
* @param __LEVEL__ 出力レベル
* @param value 値
*/
protected void outputAppLog(String __LEVEL__, String value) {
if (MoStringUtil.isNotEmpty(value)) {
mAppLog.outputLog(__LEVEL__, value);
}
}
/**
* アプリケーションジャーナルログ出力
* <br>strings.xmlのリソースID指定
*
* @param __LEVEL__ 出力レベル
* @param resId strings.xmlのリソースID
* @param args 引数
*/
protected void outputAppLog(String __LEVEL__, int resId, Object ... args) {
String format = getString(resId);
if (MoStringUtil.isNotEmpty(format)) {
String message = format;
if (args != null) {
message = String.format(format, args);
}
outputAppLog(__LEVEL__, message);
}
}
/**
* アプリケーションジャーナルログ出力
*
* @param __LEVEL__ 出力レベル
* @param values 値
*/
protected void outputAppLog(String __LEVEL__, List<String> values) {
for (String value : values) {
outputAppLog(__LEVEL__, value);
}
}
/**
* 表示可否
*
* @param id リソースID
* @param visible VISIBLE, INVISIBLE, GONE
*/
protected void setVisible(int id, int visible) {
View view = findViewById(id);
if (view != null) {
view.setVisibility(visible);
}
}
/**
* 有効/無効判定
*
* @param id リソースID
* @param enabled true : 有効 false : 無効
*/
protected void setEnabled(int id, boolean enabled) {
View view = findViewById(id);
if (view != null) {
view.setEnabled(enabled);
}
}
/**
* テキスト設定
*
* @param id リソースID
* @param value 値
*/
protected void setText(int id, String value) {
if (MoStringUtil.isEmpty(value)) {
return;
}
View view = findViewById(id);
if (view != null && view instanceof TextView) {
((TextView) view).setText(value);
}
}
/**
* {@link TextView}空判定
*
* @param id リソースID
* @return true : 空 / false : 空でない
*/
protected boolean isTextEmpty(int id) {
View view = findViewById(id);
if (view != null && view instanceof TextView) {
String value = (String) ((TextView) view).getText();
if (MoStringUtil.isNotEmpty(value)) {
/* TextViewの設定文字が空 */
return false;
}
}
return true;
}
/**
* {@link EditText}へエラーメッセージ設定
*
* @param id リソースID
* @param message 設定メッセージ
*/
protected void setErrorMsg(int id, String message) {
View view = findViewById(id);
if (view instanceof EditText) {
setErrorMsg((EditText) view, message);
}
}
/**
* {@link EditText}へエラーメッセージ設定
*
* @param edit {@link EditText}
* @param message エラーメッセージ
*/
protected void setErrorMsg(EditText edit, String message) {
if (edit != null && message != null) {
edit.setFocusableInTouchMode(true);
edit.requestFocus();
edit.setError(message);
}
}
/**
* {@link EditText}からエラーメッセージクリア
*
* @param id リソースID
*/
protected void clearErrorMsg(int id) {
View view = findViewById(id);
if (view instanceof EditText) {
clearErrorMsg((EditText) view);
}
}
/**
* {@link EditText}からエラーメッセージクリア
*
* @param edit {@link EditText}
*/
protected void clearErrorMsg(EditText edit) {
if (edit != null) {
edit.setFocusableInTouchMode(false);
edit.setError(null);
edit.clearFocus();
}
}
}
|
Slowhand0309/Monaka
|
src/com/slowhand/monaka/view/MoBaseActivity.java
|
Java
|
mit
| 5,428
|
package com.sudwood.advancedutilities.items;
import java.util.List;
import com.sudwood.advancedutilities.AdvancedUtilities;
import com.sudwood.advancedutilities.container.InventoryBag;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
public class ItemBag extends Item
{
IIcon[] icons = new IIcon[16];
private String[] names = {"WhiteBag", "OrangeBag", "MagentaBag", "LightBlueBag", "YellowBag", "LimeGreenBag", "PinkBag", "GreyBag", "LightGreyBag", "CyanBag", "PurpleBag", "BlueBag", "BrownBag", "GreenBag", "RedBag", "BlackBag"};
public ItemBag()
{
this.setHasSubtypes(true);
this.setMaxDamage(0);
this.maxStackSize = 1;
}
public String getUnlocalizedName(ItemStack par1ItemStack)
{
int i = MathHelper.clamp_int(par1ItemStack.getItemDamage(), 0, 15);
return super.getUnlocalizedName() + "." + names[i];
}
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack stack, EntityPlayer par2EntityPlayer, List par3List, boolean par4)
{
InventoryBag bag = new InventoryBag(stack);
if(bag.getStackInSlot(bag.INV_SIZE-1)!= null)
{
int total = bag.getTotalItemsWithInventoryItems(bag.getStackInSlot(27).getItem(), AdvancedUtilitiesItems.bag);
par3List.add("Contains: "+total+" "+bag.getStackInSlot(bag.INV_SIZE-1).getDisplayName());
}
}
@SideOnly(Side.CLIENT)
public void getSubItems(Item item, CreativeTabs tabs, List list)
{
for (int i = 0; i < 16; ++i)
{
list.add(new ItemStack(item, 1, i));
item.setCreativeTab(AdvancedUtilities.advancedBEToolsTab);
}
}
public CreativeTabs[] getCreativeTabs()
{
return new CreativeTabs[]{ AdvancedUtilities.advancedBEToolsTab };
}
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister par1IconRegister)
{
for(int i = 0; i < 16; i++)
{
icons[i] = par1IconRegister.registerIcon("advancedutilities:"+names[i].toLowerCase());
}
}
@SideOnly(Side.CLIENT)
public IIcon getIconFromDamage(int dmg)
{
return icons[dmg];
}
@Override
public int getMaxItemUseDuration(ItemStack stack)
{
return 68000; // return any value greater than zero
}
public ItemStack onItemRightClick(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer)
{
par3EntityPlayer.openGui(AdvancedUtilities.instance, AdvancedUtilities.bagGui, par2World, (int) par3EntityPlayer.posX, (int) par3EntityPlayer.posY, (int) par3EntityPlayer.posZ);
return par1ItemStack;
}
}
|
Sudwood/AdvancedUtilities
|
java/com/sudwood/advancedutilities/items/ItemBag.java
|
Java
|
mit
| 2,918
|
(function () {
"use strict";
// ReSharper disable once UndeclaredGlobalVariableUsing
angular
.module("umbraco.resources")
.filter("ujetAsGroup", ujetAsGroupFilter);
function ujetAsGroupFilter() {
return function (object) {
object.label = object.name;
return object;
};
};
})();
|
logikfabrik/uJetSocial
|
src/Logikfabrik.Umbraco.Jet.Social/Web/App_Plugins/uJetSocial/js/app/filters/asGroupFilter.js
|
JavaScript
|
mit
| 359
|
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Node {
public int x;
public int y;
public int id;
public Node(int x, int y, int id) {
this.x = x;
this.y = y;
this.id = id;
}
}
class Step {
public int type;
public int param;
public Step(int type, int param) {
this.type = type;
this.param = param;
}
}
class Transport {
public List<Step> steps;
public int id;
public Transport(int id) {
this.steps = new ArrayList<Step>();
this.id = id;
}
}
public class GMap {
public List<Node> nodes;
public Map<Integer, Transport> transports;
public int id;
public GMap(int id) {
this.nodes = new ArrayList<Node>();
this.transports = new HashMap<Integer, Transport>();
this.id = id;
}
}
|
marcaddeo/MAMBot
|
Java/MAMBot/src/GMap.java
|
Java
|
mit
| 798
|
var _ = require('@sailshq/lodash');
var async = require('async');
var Promise = require('bluebird');
module.exports = function(self, options) {
// Every time a doc is saved, check whether its type is included in
// workflow. If so invoke `ensureWorkflowLocale` and
// `ensurePageSlugPrefix`.
self.docBeforeSave = function(req, doc, options) {
if (!self.includeType(doc.type)) {
return;
}
self.ensureWorkflowLocale(req, doc);
self.ensurePageSlugPrefix(doc);
};
// Every time a doc is saved, check whether its type is included in workflow. If it is,
// check for locales in which that workflowGuid does not exist yet, and bring it into existence
// there.
//
// These newly created docs in other locales are initially trash so they
// don't clutter reorganize as "unpublished."
//
// If `options.workflowMissingLocalesLocales` is set to an array of locales, the
// document is exported if needed only to those locales. Otherwise, by default,
// the document is exported if needed to all locales. If `replicateAcrossLocales` is
// `false` as a module-level option, it is replicated only between "draft" and "live"
// unless it is a parked page.
self.docAfterSave = function(req, doc, options, callback) {
var missingLocales;
if (doc._workflowPropagating) {
// Recursion guard
return callback(null);
}
if (!self.includeType(doc.type)) {
return callback(null);
}
return async.series([
findMissingLocales,
insertInMissingLocales,
permissionsAcrossLocales
], function(err) {
if (err) {
self.apos.utils.error(err);
}
return callback(err);
});
function findMissingLocales(callback) {
var criteria = {
workflowGuid: doc.workflowGuid,
workflowLocale: { $in: relevantLocales() }
};
return self.apos.docs.db.findWithProjection(criteria, { workflowLocale: 1 }).toArray(function(err, docs) {
if (err) {
return callback(err);
}
var locales = _.pluck(docs, 'workflowLocale');
missingLocales = _.filter(relevantLocales(), function(locale) {
if (_.contains(locales, locale)) {
return false;
}
return true;
});
return callback(null);
});
function relevantLocales() {
var candidates;
if (options.workflowMissingLocalesLocales) {
candidates = options.workflowMissingLocalesLocales;
} else {
candidates = _.keys(self.locales);
if ((!options.forceReplicate) && (!self.replicates(req, doc))) {
// We are not auto-replicating across locales, but we are still
// maintaining at least draft/live relationship for all workflow docs
candidates = [ self.draftify(doc.workflowLocale), self.liveify(doc.workflowLocale) ];
}
}
return _.filter(candidates, function(locale) {
if (locale === doc.workflowLocale) {
return false;
}
if (options.workflowMissingLocalesSubset === 'draft') {
if (!locale.match(/-draft$/)) {
return false;
}
}
if (options.workflowMissingLocalesSubset === 'live') {
if (locale.match(/-draft$/)) {
return false;
}
}
if (options.workflowMissingLocalesDescendantsOf) {
if (!self.isAncestorOf(options.workflowMissingLocalesDescendantsOf, locale)) {
return false;
}
}
return true;
});
}
}
function insertInMissingLocales(callback) {
if (!missingLocales.length) {
return callback(null);
}
// A new doc needs to be brought into existence across all locales.
// For performance, do this with a moderate degree of parallelism
return async.eachLimit(missingLocales, 5, function(locale, callback) {
var _doc = self.apos.utils.clonePermanent(doc);
if (locale === doc.workflowLocale) {
return setImmediate(callback);
}
// Strip the prefix that came from the originating locale
// so that the new locale can prepend its own successfully
var prefix = self.prefixes && self.prefixes[self.liveify(_doc.workflowLocale)];
if (prefix && (_doc.slug.indexOf(prefix) === 0)) {
_doc.slug = _doc.slug.substr(prefix.length);
}
delete _doc._id;
_doc.workflowLocale = locale;
_doc._workflowPropagating = true;
// Otherwise you can make something happen in public across
// all locales just by creating a new doc
// and watching it propagate.
//
// If the doc in question is the home page or global doc let it through
// for chicken and egg reasons. If the page is any other page trash it
// in the other locales, it can be activated for those locales later
// by removing it from the trash, or via exporting to it, which will
// export the fact that it is not trash.
if ((_doc.level === 0) || _doc.parked) {
// Let it through: for chicken and egg reasons, the home page
// exists in published form right away in all locales.
// Ditto any parked page
} else if (_doc.slug === 'global') {
// The global doc
} else if (options.workflowDefaultLocaleNotTrash && (doc.workflowLocale === self.defaultLocale)) {
// In default locale, and we've received the flag to ensure that is not in the trash; this flag
// is used when adding workflow for the first time, because it is the sensible migration path
// for a site that did not have workflow before
} else if ((options.workflowMissingLocalesLive === 'liveOnly') ||
(self.isAncestorOf(doc.workflowLocale, _doc.workflowLocale) && _doc.workflowLocale.match(/-draft$/))) {
// If it's a draft let it through matching the parent, otherwise
// start it in the trash. This is the least confusing behavior
// for the add-missing-locales task, or for manual creation of
// a new doc in the default locale.
if (!_doc.workflowLocale.match(/-draft$/)) {
_doc.trash = true;
}
} else if (!options.workflowMissingLocalesLive) {
_doc.trash = true;
}
self.ensureWorkflowLocaleForPathIndex(_doc);
return async.series([
resolve,
insert
], callback);
function resolve(callback) {
if (options.workflowResolveDeferred || _doc.workflowResolveDeferred) {
return callback(null);
}
return self.resolveRelationships(req, _doc, _doc.workflowLocale, callback);
}
function insert(callback) {
// This is tricky: for pieces, we need the beforeInsert/afterInsert etc.
// callbacks to run. Whereas for pages, not all of those exist, and those
// that do are methods of the pages module, not the manager for a
// particular page type.
var manager = self.apos.docs.getManager(_doc.type);
if (self.apos.instanceOf(manager, 'apostrophe-custom-pages')) {
// All page type managers extend apostrophe-custom-pages (eventually)
return async.series([ fixTree, beforeInsert, beforeSave, insertDoc ], callback);
} else if (manager.insert) {
// A piece, or something else with a direct insert method;
// simple
return manager.insert(req, _doc, { permissions: false, workflowMissingLocalesLive: options.workflowMissingLocalesLive }, callback);
} else {
// Something Else. Currently, nothing in this category, but
// inserting via docs.insert is a good fallback
return insertDoc(callback);
}
function fixTree(callback) {
if ((self.options.replicateAcrossLocales === true) || _doc.parkedId) {
// This is not necessary if we are replicating 100% of the time, could
// cause unnecessary peer order changes, and will lead to errors if we don't replicate
// in tree order, so skip it.
//
// Also unnecessary for parked pages because they are guaranteed to
// exist across all locales by the end of the replication.
return callback(null);
}
// Make the child a subpage of the closest ancestor that actually exists
// in the destination locale. The immediate parent might not exist
// if `replicateAcrossLocales` is `false`.
//
// If the parent does not change, we still need to reset the rank.
// Figuring out if various peers are exported or not would be
// expensive, and in a typical batch export or even manual export
// situation things will happen in the right order.
var components = _doc.path.split('/');
if (!_doc.level) {
// Homepage has no parent
return callback(null);
}
var paths = [];
var path = '';
_.each(components, function(component) {
path += component;
// Special case: the path of the homepage
// is /, not an empty string
var queryPath = path;
if (queryPath === '') {
queryPath = '/';
}
// Don't redundantly load ourselves
if (queryPath === _doc.path) {
return;
}
paths.push(queryPath);
path += '/';
});
return self.apos.docs.db.find({
path: {
$in: paths
},
workflowLocale: _doc.workflowLocale
}).project({
path: 1,
level: 1
}).sort({
path: -1
}).limit(1).toArray(function(err, pages) {
if (err) {
return callback(err);
}
if (!pages.length) {
return callback(new Error('Non-home page has no parent, should not be possible: ' + self.options.replicateAcrossLocales));
}
const newParent = pages[pages.length - 1];
const newPath = self.apos.utils.addSlashIfNeeded(newParent.path) + require('path').basename(_doc.path);
// Even though the parent may not have changed, we still need to fix the rank,
// so keep going on this path either way
_doc.path = newPath;
_doc.level = newParent.level + 1;
// Now we need to make it the last subpage of the new parent
const matchNewPeers = new RegExp('^' + self.apos.utils.regExpQuote(self.apos.utils.addSlashIfNeeded(newParent.path)));
return self.apos.docs.db.find({
path: matchNewPeers,
level: newParent.level + 1,
workflowLocale: _doc.workflowLocale
}).project({ _id: 1, rank: 1 }).sort({ rank: -1 }).limit(1).toArray(function(err, previous) {
if (err) {
return callback(err);
}
previous = previous[0];
if (previous) {
_doc.rank = (previous.rank || 0) + 1;
} else {
_doc.rank = 0;
}
return callback(null);
});
});
}
function beforeInsert(callback) {
return self.apos.pages.beforeInsert(req, _doc, { permissions: false, workflowMissingLocalesLive: options.workflowMissingLocalesLive }, callback);
}
function beforeSave(callback) {
return self.apos.pages.beforeSave(req, _doc, { permissions: false, workflowMissingLocalesLive: options.workflowMissingLocalesLive }, callback);
}
function insertDoc(callback) {
return self.apos.docs.insert(req, _doc, { permissions: false, workflowMissingLocalesLive: options.workflowMissingLocalesLive }, callback);
}
}
}, callback);
}
function permissionsAcrossLocales(callback) {
// If I can edit a specific page in ch-fr, I can also edit that same page in gb-en,
// PROVIDED THAT I can edit pages in gb-en at all (we have locale-specific
// permission checks). This eliminates complexities in the permissions interface.
if (!doc.docPermissions) {
return callback(null);
}
return self.apos.docs.db.update({
workflowGuid: doc.workflowGuid
}, {
$set: {
'loginRequired': doc.loginRequired,
'viewUsersIds': doc.viewUsersIds || [],
'viewGroupsIds': doc.viewGroupsIds || [],
'editUsersIds': doc.editUsersIds || [],
'editGroupsIds': doc.editGroupsIds || [],
'viewUsersRelationships': doc.viewUsersRelationships || {},
'viewGroupsRelationships': doc.viewGroupsRelationships || {},
'editUsersRelationships': doc.editUsersRelationships || {},
'editGroupsRelationships': doc.editGroupsRelationships || {},
'docPermissions': doc.docPermissions
}
}, {
multi: true
}, callback);
}
};
self.pageBeforeSend = function(req, callback) {
self.apos.templates.addBodyDataAttribute(req, 'locale', req.locale);
// If looking at a live locale, disable inline editing
// Also adds a class on <body> for both workflow modes
if (req.user) {
var workflowMode = req.session.workflowMode;
req.data.workflowPreview = req.session.workflowPreview;
if (workflowMode === 'live' || req.session.workflowPreview) {
req.disableEditing = true;
}
self.apos.templates.addBodyClass(req, 'apos-workflow-' + workflowMode + '-page');
}
// Pass on `data.workflow.context` which will be the page or piece
// the user thinks of as the "context" for the current page rendering
var context = self.getContext(req);
if (context && context.workflowGuid) {
req.data.workflow.context = context;
}
req.data.workflow.locale = self.liveify(req.locale);
return async.series([
getLocalizations,
userOnly
], callback);
function getLocalizations(callback) {
if (!(req.data.workflow.context && req.data.workflow.context.workflowGuid)) {
return callback(null);
}
return self.getLocalizations(req, req.data.workflow.context.workflowGuid, false, function(err, localizations) {
if (err) {
return callback(err);
}
req.data.workflow.localizations = localizations;
return callback(null);
});
}
function userOnly(callback) {
var id;
// If we're not logged in, this is as far as we need to go
if (!req.user) {
return callback(null);
}
// Invoke pushCreateSingleton after we have all this groovy information,
// so we get options.localizations on the browser side to power the
// locale picker modal
self.pushCreateSingleton(req);
if (req.query.workflowPreview) {
req.disableEditing = true;
id = self.apos.launder.id(req.query.workflowPreview);
self.apos.templates.addBodyClass(req, 'apos-workflow-preview-page');
req.browserCall('apos.modules["apostrophe-workflow"].enablePreviewIframe({ id: ? })', id);
}
// If we're not reviewing an old commit, this is as far as
// we need to go
if (!req.query.workflowReview) {
return callback(null);
}
req.disableEditing = true;
// A commit id, not a doc id
id = self.apos.launder.id(req.query.workflowReview);
self.apos.templates.addBodyClass(req, 'apos-workflow-preview-page');
var commit;
var contexts = [];
return async.series([
findDocAndCommit,
after
], function(err) {
if (err) {
return callback(err);
}
req.browserCall('apos.modules["apostrophe-workflow"].enablePreviewIframe({ commitId: ? })', id);
return callback(null);
});
function findDocAndCommit(callback) {
return self.findDocAndCommit(req, id, function(err, _doc, _commit) {
if (err) {
return callback(err);
}
commit = _commit;
// Walk recursively through req.data looking for instances of the doc of interest.
// Working in place, modify them to be copies of commit.from, which will be
// an older version of the doc. Since we're working in place, make
// an array of these to pass to after() later for joining
contexts = [];
self.apos.docs.walk(req.data, function(o, k, v, dotPath) {
if (v && (typeof (v) === 'object')) {
if (v._id === commit.fromId) {
_.each(_.keys(v), function(key) {
delete v[key];
});
_.assign(v, commit.from);
contexts.push(v);
}
}
});
return callback(null);
});
}
function after(callback) {
return self.after(req, contexts, callback);
}
}
};
self.loginDeserialize = function(user) {
user._permissionsLocales = {};
_.each(user._groups, function(group) {
_.merge(user._permissionsLocales, group.permissionsLocales || {});
});
};
// An afterSave handler is a good place to set or clear the
// workflowModified flag because it guarantees any properties
// added by beforeSave handlers are taken into account. It would
// be nice if promise events had a way to say "after all the
// others," but they don't so far.
self.on('apostrophe-docs:afterSave', 'setWorkflowModified', function(req, doc, options) {
if (!self.includeType(doc.type)) {
return;
}
if (!(doc.workflowLocale && doc.workflowLocale.match(/-draft$/))) {
// Only interested in changes to drafts
return;
}
const isModified = Promise.promisify(self.isModified);
return isModified(req, doc).then(function(modified) {
// If there is no modification and that's not news, no update.
// Otherwise always update so we get the last editor's name
if ((modified === doc.workflowModified) && (!modified)) {
return;
}
const $set = {
workflowModified: modified
};
if (req.user && req.user._id && req.user.title) {
$set.workflowLastEditor = req.user.title;
$set.workflowLastEditorId = req.user._id;
}
return self.apos.docs.db.update({
_id: doc._id
}, {
$set: $set
});
});
});
};
|
punkave/apostrophe-workflow
|
lib/callAll.js
|
JavaScript
|
mit
| 18,958
|
/*!
* Chicago - Drag.min.css
* A front-end JavaScript library for user-interface developers.
*
* Copyright (c) 2015 Erik Nielsen
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* https://nielse63.github.io/Chicago/
*
* Version: 1.1.0
*
*/
.drag{position:absolute;touch-action:none;-ms-touch-action:none}
|
nielse63/Chicago
|
dist/css/drag.min.css
|
CSS
|
mit
| 389
|
<?php namespace FileModifier;
use FileModifier\Code\Factory\CodeFactory;
use FileModifier\Code\Generator\Generator;
use FileModifier\Code\Generator\GeneratorContract;
use FileModifier\Errors\PHPErrorThrower;
use FileModifier\File\File;
use FileModifier\File\FileFactory;
use FileModifier\File\FileFactoryContract;
use FileModifier\Parsers\Parser;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use PhpParser\Lexer;
use PhpParser\Parser as PHPParser;
class FileModifier
{
/**
* @var Filesystem
*/
private $filesystem;
/**
* @var FileFactoryContract
*/
private $fileFactory;
/**
* @var GeneratorContract
*/
private $generator;
/**
* Construct a new FileModifier object
*
* @param FileFactoryContract $fileFactory
* @param Filesystem $filesystem
* @param GeneratorContract $generator
*/
public function __construct(FileFactoryContract $fileFactory, Filesystem $filesystem, GeneratorContract $generator)
{
$this->filesystem = $filesystem;
$this->fileFactory = $fileFactory;
$this->generator = $generator;
}
/**
* @return static
*/
public static function build()
{
$codeFactory = new CodeFactory();
$parser = new Parser($codeFactory, new PHPErrorThrower());
$PHPParser = new PHPParser(new Lexer());
$fileFactory = new FileFactory($parser, $PHPParser, $codeFactory);
$filesystem = new Filesystem(new Local(getcwd()));
$generator = new Generator();
return new static($fileFactory, $filesystem, $generator);
}
/**
* @param string $path
*
* @return File
*/
public function open($path)
{
$contents = $this->filesystem->read($path);
return $this->fileFactory->build($contents);
}
/**
* @param File $file
* @param string $path
*/
public function save(File $file, $path)
{
$code = $this->generator->generate($file);
$this->filesystem->put($path, $code);
}
}
|
thomasruiz/file-modifier
|
src/FileModifier.php
|
PHP
|
mit
| 2,109
|
require 'mirth_connect/helpers'
class MirthConnect::ChannelStatus
## Filter Params
attr_reader :channelId, :name, :state, :deployedRevisionDelta, :deployedDate
HELPERS = MirthConnect::Helpers
def initialize( raw_status )
if raw_status.is_a?(Nokogiri::XML::Element) && raw_status.name == 'channelStatus'
xml = raw_status
elsif raw_status.is_a?(String) && raw_status.start_with?('<channelStatus>')
xml = Nokogiri::XML(raw_status).child
else
raise Exception, 'incorrect format for channel status'
end
node_set = xml.children
node_set.each do |element|
next unless element.is_a?(Nokogiri::XML::Element)
if element.name.to_sym == :deployedDate
@deployedDate = Time.at( element.search('time').text.to_i / 1000 )
@timezone = element.search('timezone').text
else
instance_variable_set("@#{element.name}", element.text)
end
end
end
def [](key)
instance_variable_get("@#{key.to_s}")
end
end
|
lhaber-carecloud/MirthConnect
|
lib/mirth_connect/channel_status.rb
|
Ruby
|
mit
| 1,008
|
/**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
/* Generated By:JJTree: Do not edit this line. ASTSingleMemberAnnotation.java */
package net.sourceforge.pmd.lang.java.ast;
public class ASTSingleMemberAnnotation extends AbstractJavaTypeNode {
public ASTSingleMemberAnnotation(int id) {
super(id);
}
public ASTSingleMemberAnnotation(JavaParser p, int id) {
super(p, id);
}
/**
* Accept the visitor. *
*/
public Object jjtAccept(JavaParserVisitor visitor, Object data) {
return visitor.visit(this, data);
}
}
|
byronka/xenos
|
utils/pmd-bin-5.2.2/src/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTSingleMemberAnnotation.java
|
Java
|
mit
| 612
|
require "t10/rooms/under_construction"
module T10
module Rooms
class BossRoom < Room
include Rooms::UnderConstruction
DOORS = 1
def initialize
super
@has_left = false
@has_right = false
@has_ahead = false
end
def desc_name
"forgotten realm "
end
end
end
end
|
mbrand12/t10
|
lib/t10/rooms/boss_room.rb
|
Ruby
|
mit
| 350
|
<?php
/**
* Copyright (C) 2013 Emay Komarudin
* 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 3 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, see <http://www.gnu.org/licenses/>.
*
* @author Emay Komarudin
*
* Proses Bussiness Sysprodhistory dengan Array Support
*
**/
namespace Emayk\Ics\Repo\Sysprodhistory;
class SysprodhistoryArray implements SysprodhistoryInterface{
protected $sysprodhistory;
/*function __construct() { }*/
/**
* @return mixed
*/
public function all()
{
// TODO: Implement all() method.
}
/**
* Simpan Sysprodhistory
*
* @return mixed
*/
public function store()
{
// TODO: Implement store() method.
}
/**
* Menghapus Sysprodhistory
*
* @param $id
* @return mixed
*
*/
public function delete($id)
{
// TODO: Implement delete() method.
}
/**
* Update Informasi Sysprodhistory
*
* @param $id
* @param array $sysprodhistory
* @return mixed
*/
public function update($id)
{
// TODO: Implement update() method.
}
/**
*
* Mendapatkan Sysprodhistory berdasarkan id yang diberikan
*
* @param $id
* @return mixed
*/
public function find($id)
{
// TODO: Implement find() method.
}
/**
*
* Menampilkan Page Untuk Buat Data
*
**/
public function create()
{
// TODO: Implement create() method.
}
/**
* Menampilkan Resource
*
* @param int $id
* @return Response
*/
public function show($id)
{
// TODO: Implement show() method.
}
/**
* Menampilkan Data Untuk di edit
*
* @param int $id
* @return Response
*/
public function edit($id)
{
// TODO: Implement edit() method.
}
/**
* Remove from Storage
*
*/
public function destroy($id)
{
// TODO: Implement destroy() method.
}
}
|
emayk/ics
|
src/Emayk/Ics/Repo/Sysprodhistory/SysprodhistoryArray.php
|
PHP
|
mit
| 2,528
|
<?php
declare(strict_types=1);
namespace Marein\Nchan\Http;
interface Response
{
public const OK = 200;
public const CREATED = 201;
public const ACCEPTED = 202;
public const FORBIDDEN = 403;
public const NOT_FOUND = 404;
public function statusCode(): int;
public function body(): string;
}
|
marein/php-nchan-client
|
src/Http/Response.php
|
PHP
|
mit
| 323
|
const StdLib = require('@doctormckay/stdlib');
const SteamID = require('steamid');
const Helpers = require('./helpers.js');
const EMsg = require('../enums/EMsg.js');
const SteamUserEcon = require('./econ.js');
class SteamUserFamilySharing extends SteamUserEcon {
/**
* Add new borrowers.
* @param {SteamID[]|string[]|SteamID|string} borrowersSteamID
* @param {function} [callback]
* @returns {Promise}
*/
addAuthorizedBorrowers(borrowersSteamID, callback) {
return StdLib.Promises.timeoutCallbackPromise(5000, null, callback, true, (resolve, reject) => {
if (!Array.isArray(borrowersSteamID)) {
borrowersSteamID = [borrowersSteamID];
}
this._sendUnified('DeviceAuth.AddAuthorizedBorrowers#1', {
steamid: this.steamID.getSteamID64(),
steamid_borrower: borrowersSteamID.map(sid => Helpers.steamID(sid).getSteamID64())
}, (body, hdr) => {
let err = Helpers.eresultError(hdr.proto);
return err ? reject(err) : resolve();
});
});
};
/**
* Remove borrowers.
* @param {SteamID[]|string[]} borrowersSteamID
* @param {function} [callback]
* @returns {Promise}
*/
removeAuthorizedBorrowers(borrowersSteamID, callback) {
return StdLib.Promises.timeoutCallbackPromise(5000, null, callback, true, (resolve, reject) => {
if (!Array.isArray(borrowersSteamID)) {
return reject(new Error('The \'borrowersSteamID\' argument must be an array'));
}
this._sendUnified('DeviceAuth.RemoveAuthorizedBorrowers#1', {
steamid: this.steamID.getSteamID64(),
steamid_borrower: borrowersSteamID.map(sid => Helpers.steamID(sid).getSteamID64())
}, (body, hdr) => {
let err = Helpers.eresultError(hdr.proto);
return err ? reject(err) : resolve();
});
});
};
/**
* Retrieve a list of Steam accounts authorized to borrow your library.
* @param {{includeCanceled?: boolean, includePending?: boolean}} [options]
* @param {function} [callback]
* @returns {Promise}
*/
getAuthorizedBorrowers(options, callback) {
return StdLib.Promises.timeoutCallbackPromise(5000, null, callback, (resolve, reject) => {
if (typeof options == 'function') {
callback = options;
}
options = options || {};
this._sendUnified('DeviceAuth.GetAuthorizedBorrowers#1', {
steamid: this.steamID.getSteamID64(),
include_canceled: options.includeCanceled || false,
include_pending: options.includePending || false
}, (body, hdr) => {
let err = Helpers.eresultError(hdr.proto);
return err ? reject(err) : resolve({
borrowers: body.borrowers.map((borrower) => {
return {
steamid: new SteamID(borrower.steamid),
isPending: borrower.is_pending,
isCanceled: borrower.is_canceled,
timeCreated: new Date(borrower.time_created * 1000)
};
})
});
})
});
};
/**
* Get a list of devices we have authorized.
* @param {{includeCanceled?: boolean}} [options]
* @param {function} [callback]
* @returns {Promise}
*/
getAuthorizedSharingDevices(options, callback) {
if (typeof options == 'function') {
callback = options;
options = {};
}
options = options || {};
return StdLib.Promises.timeoutCallbackPromise(5000, null, callback, (resolve, reject) => {
this._sendUnified('DeviceAuth.GetOwnAuthorizedDevices#1', {
steamid: this.steamID.getSteamID64(),
includeCancelled: !!options.includeCanceled
}, (body, hdr) => {
let err = Helpers.eresultError(hdr.proto);
return err ? reject(err) : resolve({
devices: body.devices.map((device) => {
return {
deviceToken: device.auth_device_token,
deviceName: device.device_name,
isPending: device.is_pending,
isCanceled: device.is_canceled,
isLimited: device.is_limited,
lastTimeUsed: device.last_time_used ? new Date(device.last_time_used * 1000) : null,
lastBorrower: device.last_borrower_id && device.last_borrower_id != '76561197960265728' ? new SteamID(device.last_borrower_id) : null,
lastAppPlayed: device.last_app_played || null
};
})
});
});
});
};
/**
* Authorize local device for library sharing.
* @param {string} deviceName
* @param {function} [callback]
* @returns {Promise}
*/
authorizeLocalSharingDevice(deviceName, callback) {
return StdLib.Promises.timeoutCallbackPromise(5000, null, callback, true, (resolve, reject) => {
if (!deviceName) {
return reject(new Error('The \'deviceName\' argument is required.'));
}
this._send(EMsg.ClientAuthorizeLocalDeviceRequest, {
device_description: deviceName,
owner_account_id: this.steamID.accountid
}, (body) => {
let err = Helpers.eresultError(body.eresult);
return err ? reject(err) : resolve({deviceToken: body.authed_device_token});
});
});
};
/**
* Deauthorize a device from family sharing.
* @param {string|{deviceToken: string}} deviceToken
* @param {function} [callback]
*/
deauthorizeSharingDevice(deviceToken, callback) {
return StdLib.Promises.timeoutCallbackPromise(5000, null, callback, true, (resolve, reject) => {
if (typeof deviceToken == 'object' && typeof deviceToken.deviceToken == 'string') {
deviceToken = deviceToken.deviceToken;
}
if (typeof deviceToken != 'string') {
return reject(new Error('The \'deviceToken\' parameter is required.'));
}
this._send(EMsg.ClientDeauthorizeDeviceRequest, {
deauthorization_account_id: this.steamID.accountid,
deauthorization_device_token: deviceToken
}, (body) => {
let err = Helpers.eresultError(body.eresult);
return err ? reject(err) : resolve();
});
});
};
/**
* Use local device authorizations to allow usage of shared licenses.
* If successful, `licenses` will be emitted with the newly-acquired licenses.
* @param {SteamID|string} ownerSteamID
* @param {string|{deviceToken: string}} deviceToken
*/
activateSharingAuthorization(ownerSteamID, deviceToken) {
if (!ownerSteamID) {
throw new Error('The \'ownerSteamID\' argument is required.');
}
if (typeof deviceToken == 'object' && typeof deviceToken.deviceToken == 'string') {
deviceToken = deviceToken.deviceToken;
}
if (typeof deviceToken != 'string') {
throw new Error('The \'deviceToken\' argument is required.');
}
ownerSteamID = Helpers.steamID(ownerSteamID);
this._send(EMsg.ClientUseLocalDeviceAuthorizations, {
authorization_account_id: [ownerSteamID.accountid],
device_tokens: [{owner_account_id: ownerSteamID.accountid, token_id: deviceToken}]
});
};
/**
* Deactivate family sharing authorizations. Removes shared licenses.
*/
deactivateSharingAuthorization() {
this._send(EMsg.ClientUseLocalDeviceAuthorizations, {
authorization_account_id: [],
device_tokens: []
});
};
}
module.exports = SteamUserFamilySharing;
|
DoctorMcKay/node-steam-user
|
components/familysharing.js
|
JavaScript
|
mit
| 6,803
|
require File.dirname(__FILE__) + '/test_helper'
class ErrorTest < Test::Unit::TestCase
def setup
@container = OldAWS::S3
@error = Error.new(Parsing::XmlParser.new(Fixtures::Errors.access_denied))
@container.send(:remove_const, :NotImplemented) if @container.const_defined?(:NotImplemented)
end
def test_error_class_is_automatically_generated
assert !@container.const_defined?('NotImplemented')
error = Error.new(Parsing::XmlParser.new(Fixtures::Errors.not_implemented))
assert @container.const_defined?('NotImplemented')
end
def test_error_contains_attributes
assert_equal 'Access Denied', @error.message
end
def test_error_is_raisable_as_exception
assert_raises(@container::AccessDenied) do
@error.raise
end
end
def test_error_message_is_passed_along_to_exception
@error.raise
rescue @container::AccessDenied => e
assert_equal 'Access Denied', e.message
end
def test_response_is_passed_along_to_exception
response = Error::Response.new(FakeResponse.new(:code => 409, :body => Fixtures::Errors.access_denied))
response.error.raise
rescue @container::ResponseError => e
assert e.response
assert_kind_of Error::Response, e.response
assert_equal response.error, e.response.error
end
def test_exception_class_clash
assert !@container.const_defined?(:NotImplemented)
# Create a class that does not inherit from exception that has the same name as the class
# the Error instance is about to attempt to find or create
@container.const_set(:NotImplemented, Class.new)
assert @container.const_defined?(:NotImplemented)
assert_raises(ExceptionClassClash) do
Error.new(Parsing::XmlParser.new(Fixtures::Errors.not_implemented))
end
end
def test_error_response_handles_attributes_with_no_value
mock_connection_for(Bucket, :returns => {:body => Fixtures::Errors.error_with_no_message, :code => 500})
begin
Bucket.create('foo', 'invalid-argument' => 'bad juju')
rescue ResponseError => error
end
assert_nothing_raised do
error.response.error.message
end
assert_nil error.response.error.message
assert_raises(NoMethodError) do
error.response.error.non_existant_method
end
end
end
|
bcarpenter/oldaws-s3
|
test/error_test.rb
|
Ruby
|
mit
| 2,301
|
---
layout: post
date: 2020-05-16 09:43:00 +0000
title: Moving messages between SQS queues
summary: You can send messages to a DLQ if they fail processing. What if you fix the bug, and you want to resend the failed messages?
category: Amazon Web Services
tags: aws amazon-sqs
---
At work, we make heavy use of [Amazon SQS](https://en.wikipedia.org/wiki/Amazon_Simple_Queue_Service) for message queues.
We write tasks to an SQS queue, and then a worker application reads the tasks from the queue and does some processing.
When the worker is done, it sends the message to another queue, where another worker can pick it up.
This is a classic microservices pattern.
<figure style="width: 600px;">
{% inline_svg "_images/2020/sqs_queue_worker.svg" %}
</figure>
Sometimes a task can't be processed successfully -- for example, if there's a bug in the worker code.
You can [configure SQS][sqs_dlq] to send such problematic messages to a [dead-letter queue (DLQ)][dlq], where you can inspect them in isolation and work out what went wrong.
[sqs_dlq]: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html
[dlq]: https://en.wikipedia.org/wiki/Dead_letter_queue
Once we've found the problem in the worker, fixed the bug and deployed a new version, we want to send all the messages from the DLQ back to the original input queue, so they can be processed by the updated worker.
There's no way to do this in SQS directly, so we've written a script to do it for us.
Although we primarily use this to redrive problematic messages that went to a DLQ, **this script allows you to move messages between an arbitrary pair of SQS queues**.
It uses code I shared two years ago [to dump the contents of an SQS queue][dump_q].
[dump_q]: /2018/01/downloading-sqs-queues/
[send_message_batch]: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sqs.html?highlight=sqs#SQS.Client.send_message_batch
[fixed_chunks]: /2018/12/iterating-in-fixed-size-chunks/
Be careful running this code -- if the worker is running, and it picks up the messages immediately, they might go back to the DLQ if there's another problem with the worker.
The script would then resend them to the input queue, and the worker would send them back to the DLQ.
The messages would bounce back-and-forth forever.
Our queue-backed workers scale down to zero when the queue is empty, and they take a few minutes to start up when the queue starts filling.
Usually that's enough time for the script to finish running, so it's not an issue for us, but it is something to be aware of.
As with most of my scripts, this is written in Python.
You can [download the file](/files/2020/redrive_sqs_queue.py), or copy/paste the source code below.
Run it by passing the URL of the source and destination queue as arguments:
```
python3 redrive_sqs_queue.py \
--src-url=https://sqs.amazonaws.com/123456789/my-queue-dlq \
--dst-url=https://sqs.amazonaws.com/123456789/my-queue
```
Here's the code:
{% inline_code python _files/2020/redrive_sqs_queue.py %}
|
alexwlchan/alexwlchan.net
|
src/_posts/2020/2020-05-16-moving-messages-between-sqs-queues.md
|
Markdown
|
mit
| 3,079
|
from models.team import Team
from models.tournament import Tournament
from models.tree import ProbableTournamentTree
import unittest
import pdb
class TestTeam(unittest.TestCase):
def setUp(self):
self.tournament = Tournament()
self.teams = self.tournament.teams
self.usa = Team.get_for_country(self.teams, 'United States')
self.brazil = Team.get_for_country(self.teams, 'Brazil')
def test_add_friendly_result(self):
self.usa.add_friendly_result(opponent=self.brazil)
self.usa.add_friendly_result(opponent=self.brazil, result=Team.DRAW)
self.usa.add_friendly_result(opponent=self.brazil, result=Team.LOSS)
self.assertIn(self.brazil, self.usa.friendly_results['wins'])
self.assertIn(self.brazil, self.usa.friendly_results['draws'])
self.assertIn(self.brazil, self.usa.friendly_results['losses'])
# try adding a friendly result for a team not in the tourney
prev_draws = len(self.usa.friendly_results['draws'])
self.usa.add_friendly_result(opponent=Team.get_for_country(self.teams, "Israel"), result=Team.DRAW)
self.assertEqual(prev_draws + 1, len(self.usa.friendly_results['draws']))
def test_base_score(self):
# these tests operate using some basic, commonly held assumptions (which could actually be a source of human error)
self.assertGreater(self.brazil.base_score, self.usa.base_score)
self.assertGreater(self.usa.base_score, Team.get_for_country(self.teams, "Ghana").base_score)
def test_get_for_country(self):
self.assertEqual(Team.get_for_country(self.teams, 'Brazil').country, 'Brazil')
def test_get_for_group(self):
self.assertIn(Team.get_for_country(self.teams, 'Brazil'), Team.get_for_group(self.teams, 'A'))
self.assertNotIn(Team.get_for_country(self.teams, 'Brazil'), Team.get_for_group(self.teams, 'B'))
class TestTournament(unittest.TestCase):
def setUp(self):
self.tournament = Tournament()
self.teams = self.tournament.teams
def test_get_group_winners(self):
winners = self.tournament.get_group_winners('A')
self.assertEqual(winners[0].country, 'Brazil')
self.assertEqual(winners[1].country, 'Mexico')
class TestTree(unittest.TestCase):
def setUp(self):
self.tournament = Tournament()
self.teams = self.tournament.teams
self.tree = ProbableTournamentTree(self.tournament)
def test_get_opponent_at_stage(self):
brazil = Team.get_for_country(self.teams, 'Brazil')
mexico = Team.get_for_country(self.teams, 'Mexico')
cameroon = Team.get_for_country(self.teams, 'Cameroon')
spain = Team.get_for_country(self.teams, 'Spain')
netherlands = Team.get_for_country(self.teams, 'Netherlands')
opp = self.tree.get_opponent_at_stage(brazil, 0)
self.assertEqual(opp.country, netherlands.country)
opp = self.tree.get_opponent_at_stage(brazil, 1)
self.assertEqual(opp.country, Team.get_for_country(self.teams, 'Colombia').country)
opp = self.tree.get_opponent_at_stage(brazil, 3)
self.assertEqual(opp.country, spain.country)
opp = self.tree.get_opponent_at_stage(netherlands, 0)
self.assertEqual(opp.country, brazil.country)
opp = self.tree.get_opponent_at_stage(mexico, 0)
self.assertEqual(opp.country, spain.country)
# test for a team that isn't in the probability tree
self.assertEqual(self.tree.get_opponent_at_stage(cameroon, 0).country, self.tree.get_opponent_at_stage(mexico, 0).country)
if __name__ == '__main__':
unittest.main()
|
steinbachr/world-cup-challenge
|
tests/test_models.py
|
Python
|
mit
| 3,657
|
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
namespace Igor
{
public class MonsterTestInputOutputBox : InputOutputBox<MonsterTestBase>
{
public MonsterTestInputOutputBox(MonsterTestWindow Owner, MonsterTestBase EntityToWatch, string InBoxTitle, bool InbIsInputBox) : base(Owner, EntityToWatch, InBoxTitle, InbIsInputBox)
{
}
public override string GetTypeName()
{
return bIsInputBox ? "StartingTestStates" : "EndingTestStates";
}
public override string GetBoxKey()
{
return bIsInputBox ? "StartingTestStates" : "EndingTestStates";
}
public override bool HandleContextMenu(GenericMenu GenericContextMenu)
{
return true;
}
public override LinkedEntityManager<MonsterTestBase> GetManager()
{
return MonsterTestManager.GetActiveInstance();
}
public override List<EntityLink<MonsterTestBase>> GetInputEvents()
{
if(!bIsInputBox)
{
return GetManager().EndingEntities;
}
return new List<EntityLink<MonsterTestBase>>();
}
public override List<EntityLink<MonsterTestBase>> GetOutputEvents()
{
if(bIsInputBox)
{
return GetManager().StartingEntities;
}
return new List<EntityLink<MonsterTestBase>>();
}
public override bool WrapsInstance(LinkedEntity<MonsterTestBase> InstToCheck)
{
return GetManager().GetFilename() == InstToCheck.GetFilename();
}
public override void OnInspectorGUIClickedSaveButton()
{
MonsterTestManager.SaveTest();
Owner.SerializeBoxMetadata(true);
}
public override List<EntityLink<MonsterTestBase>> GetStartEntities()
{
return GetManager().StartingEntities;
}
public override List<EntityLink<MonsterTestBase>> GetEndEntities()
{
return GetManager().EndingEntities;
}
public override EntityLink<MonsterTestBase> GetLinkByName(string AnchorName)
{
return GetManager().GetLinkByName(AnchorName);
}
public override void InspectorDrawStartWidgets()
{
InspectorGUIList<EntityLink<MonsterTestBase>>("Outputs", "Name", ref GetManager().StartingEntities, bReadOnlyInputList);
}
public override void InspectorDrawEndWidgets()
{
InspectorGUIList<EntityLink<MonsterTestBase>>("Inputs", "Name", ref GetManager().EndingEntities, bReadOnlyOutputList);
}
}
}
|
mikamikem/Igor
|
Modules/MonsterTest/Core/Editor/Test/MonsterTestInputOutputBox.cs
|
C#
|
mit
| 2,230
|
import pytest
from click.testing import CliRunner
from parkour import cli
import md5
def file_checksums_equal(file1, file2):
with open(file1) as f:
checksum1 = md5.new(f.read()).digest()
with open(file2) as f:
checksum2 = md5.new(f.read()).digest()
return checksum1==checksum2
def test_trimmed_output():
runner = CliRunner()
result = runner.invoke(cli.main, ['-a', 'fastq/s3_1.fastq.gz', '-b', 'fastq/s3_2.fastq.gz', '-u', 'trim'])
print(result.output)
assert file_checksums_equal('p.s3_1.trim.fastq', 'correct_output/p.s3_1.trim.fastq')
|
buenrostrolab/proatac
|
tests/test_cli.py
|
Python
|
mit
| 575
|
const { expect } = require('chai');
const nock = require('nock');
const timekeeper = require('timekeeper');
const jose2 = require('jose2');
const { Issuer } = require('../../lib');
const fail = () => {
throw new Error('expected promise to be rejected');
};
describe('Validating Self-Issued OP responses', () => {
afterEach(timekeeper.reset);
afterEach(nock.cleanAll);
before(function () {
const issuer = new Issuer({
authorization_endpoint: 'openid:',
issuer: 'https://self-issued.me',
scopes_supported: ['openid', 'profile', 'email', 'address', 'phone'],
response_types_supported: ['id_token'],
subject_types_supported: ['pairwise'],
id_token_signing_alg_values_supported: ['RS256'],
request_object_signing_alg_values_supported: ['none', 'RS256'],
registration_endpoint: 'https://self-issued.me/registration/1.0/',
});
const client = new issuer.Client({
client_id: 'https://rp.example.com/cb',
response_types: ['id_token'],
token_endpoint_auth_method: 'none',
id_token_signed_response_alg: 'ES256',
});
Object.assign(this, { issuer, client });
});
const idToken = (claims = {}) => {
const jwk = jose2.JWK.generateSync('EC');
return jose2.JWT.sign(
{
sub_jwk: jwk.toJWK(),
sub: jwk.thumbprint,
...claims,
},
jwk,
{ expiresIn: '2h', issuer: 'https://self-issued.me', audience: 'https://rp.example.com/cb' },
);
};
describe('consuming an ID Token response', () => {
it('consumes a self-issued response', function () {
const { client } = this;
return client.callback(undefined, { id_token: idToken() });
});
it('expects sub_jwk to be in the ID Token claims', function () {
const { client } = this;
return client
.callback(undefined, { id_token: idToken({ sub_jwk: undefined }) })
.then(fail, (err) => {
expect(err.name).to.equal('RPError');
expect(err.message).to.equal('missing required JWT property sub_jwk');
expect(err).to.have.property('jwt');
});
});
it('expects sub_jwk to be a public JWK', function () {
const { client } = this;
return client
.callback(undefined, { id_token: idToken({ sub_jwk: 'foobar' }) })
.then(fail, (err) => {
expect(err.name).to.equal('RPError');
expect(err.message).to.equal('failed to use sub_jwk claim as an asymmetric JSON Web Key');
expect(err).to.have.property('jwt');
});
});
it('expects sub to be the thumbprint of the sub_jwk', function () {
const { client } = this;
return client.callback(undefined, { id_token: idToken({ sub: 'foo' }) }).then(fail, (err) => {
expect(err.name).to.equal('RPError');
expect(err.message).to.equal('failed to match the subject with sub_jwk');
expect(err).to.have.property('jwt');
});
});
});
});
|
panva/node-openid-client
|
test/client/self_issued.test.js
|
JavaScript
|
mit
| 2,964
|
# Azure VM Disk 크기 조정(ARM)
Azure VM에 있는 OS 디스크 또는 데이터 디스크의 크기를 조정하는 PowerShell 스크립트 입니다.
물론 Azure 포털에서도 VM > [일반] > [디스크] > 크기(GiB)에서 조정이 가능합니다만, 여러 디스크를 한번에 수정하는 작업은 상당한 노동력을 필요로 하죠.
이런 경우에 PowerShell이 강력한 기능을 발휘합니다.
아래의 설명은 __ARM(Azure Resource Manager)__ 을 기준으로 하고 있습니다.
PowerShell 콘솔(powershell.exe)이나, PowerShell ISE(powershell_ise.exe)를 실행합니다.
먼저, 로그인을 합니다.
```PowerShell
Login-AzureRmAccount
```
다음에는 변경하려는 VM이 있는 구독(subscription)을 선택합니다.
```PowerShell
$subscriptionName = "your subscription"
Select-AzureRmSubscription -SubscriptionName $subscriptionName
```
다음에는 변경하려는 VM의 리소스 그룹과 VM의 이름을 통하여 VM 개체를 반환합니다.
```PowerShell
$rgName = "your resource group name"
$vmName = "your VM Name"
$vm = Get-AzureRmVM -ResourceGroupName $rgName -Name $vmName
```
만약 변경하려는 디스크가 OS 디스크라면, 다음과 같이 기술합니다.
아래의 코드에서는 OS 디스크를 500GB로 변경하고 있습니다.
```PowerShell
$vm.StorageProfile[0].OsDisk.DiskSizeGB = 500
```
만약, 데이터 디스크를 변경하고 싶다면, 다음과 같이 사용하면 됩니다.
DataDisks[0]의 인덱스는 데이터 디스크의 인덱스 번호 입니다.
```PowerShell
$vm.StorageProfile[0].DataDisks[0].DiskSizeGB = 1023
```
이제, VM 개체를 업데이트하여 변경사항을 적용합니다.
```PowerShell
Update-AzureRmVM -ResourceGroupName $rgName -VM $vm
```
|
jiyongseong/AzureIaaSHol
|
powershell/resize-disk-size/README.md
|
Markdown
|
mit
| 1,783
|
from flask import Flask
app = Flask(__name__)
@app.route('/')
def CMC():
return 'Welcome to the Container Master Class by Cerulean Canvas'
if __name__ == '__main__':
app.run(host='0.0.0.0')
|
tarsoqueiroz/Docker
|
Study/Oreilly Kubernetes and Docker/s2d9/app.py
|
Python
|
mit
| 198
|
# -*- coding: utf-8 -*-
require 'zip'
module Bio
module FastQC
class Data
class << self
def read(file)
read_zipfile(file)
rescue Zip::Error
read_flatfile(file)
rescue Errno::EISDIR
read_dir(file)
end
def read_zipfile(file)
Zip::File.open(file) do |zipfile|
d = zipfile.glob('*/fastqc_data.txt').first
filenotfound(file) if !d
d.get_input_stream.read
end
end
def read_flatfile(file)
open(file).read
end
def read_dir(file)
open(File.join(file, "fastqc_data.txt")).read
rescue Errno::ENOENT
filenotfound(file)
end
def filenotfound(file)
raise "FastQC data file fastqc_data.txt not found, input file: #{file}"
end
end
end
end
end
|
inutano/bioruby-fastqc
|
lib/bio/fastqc/data.rb
|
Ruby
|
mit
| 886
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us" lang="en">
<head>
<title>STE Template Engine</title>
<style type="text/css" media="screen">
code, code pre {
font-family: monospace;
background: #eee;
}
* {
font-family: sans-serif;
}
table {
border-collapse: collapse;
}
table td, table th {
border: thin solid #ccc;
padding: 1mm;
margin: 0mm;
}
table th {
font-weight: bold;
background: #eee;
}
</style>
</head>
<body>
<h1>STE Template Engine</h1>
<p>This documentation is splitted in two parts:</p>
<ol>
<li><a href="language_definition.html">The definition of the STE template language</a>, including the documentation of the <a href="language_definition.html#builtin">builtin tags</a> and the <a href="language_definition.html#stdlib">standard library</a></li>
<li><a href="phpdoc/index.html">The documentation of the PHP implementation</a></li>
</ol>
<p>It could also be helpful to take a look at the example program (the "example" directory).</p>
</body>
</html>
|
kch42/ste
|
docu/index.html
|
HTML
|
mit
| 1,149
|
# screeps-vivero sandbox
A sandbox for testing individual functions and routines.
|
Vivero/screeps-vivero
|
test/README.md
|
Markdown
|
mit
| 82
|
package containerregistry
import "github.com/Azure/azure-sdk-for-go/version"
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string {
return "Azure-SDK-For-Go/" + Version() + " containerregistry/2018-09-01"
}
// Version returns the semantic version (see http://semver.org) of the client.
func Version() string {
return version.Number
}
|
Azure/azure-sdk-for-go
|
services/containerregistry/mgmt/2018-09-01/containerregistry/version.go
|
GO
|
mit
| 693
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.