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
|
|---|---|---|---|---|---|
<!--
MIT License
Copyright 2017-2018 Sabre GLBL Inc.
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.
-->
This example demonstrates _conf4j_ and _Spring Framework_ integration.
|
SabreOSS/conf4j
|
conf4j-examples/conf4j-example-spring/README.md
|
Markdown
|
mit
| 1,189
|
---
uid: SolidEdgeConstants.TextLineSpacingTypeConstants
summary:
remarks:
---
|
SolidEdgeCommunity/docs
|
docfx_project/apidoc/SolidEdgeConstants.TextLineSpacingTypeConstants.md
|
Markdown
|
mit
| 84
|
//
// HMNavigateController.h
// HMMeiTuanHD19
//
// Created by heima on 16/9/14.
// Copyright © 2016年 heima. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface HMNavigateController : UINavigationController
@end
|
DarlingXIe/iPadProject
|
XDLBestReservationHD/XDLBestReservationHD/Classes/Main(主要)/Common/HMNavigateController.h
|
C
|
mit
| 229
|
require File.expand_path "../../spec_helper.rb", __FILE__
RSpec.describe "home" do
it "has a homepage" do
get "/"
expect(last_response).to be_ok
expect(last_response.body).to include(
"an API for movies and UK cinema listings",
)
end
end
|
nickcharlton/moviesapi
|
spec/requests/home_spec.rb
|
Ruby
|
mit
| 266
|
<!DOCTYPE html>
<html>
<head>
<!-- Giga... -->
<meta charset="utf-8">
<title>Test Stuffs</title>
</head>
<body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<script src="new-bot.js"></script>
</body>
</html>
|
JavascriptFTW/livecoding-chat-bot
|
sandbox.html
|
HTML
|
mit
| 296
|
#####################################################
#
# A library for getting match information for a given team at a given event
# out of the Blue Alliance API
#
# Authors: Andrew Merrill and Jacob Bendicksen (Fall 2014)
#
# Requires the blueapi.py library
######################################################
#this doesn't currently fully work
import blueapi
teamNumber = 1540
eventKey = '2014pncmp'
#returns a list of qualification matches that the team played in
def getTeamQualMatches(teamNumber,eventKey):
matches = []
for n in range(0,len(blueapi.getTeamEventMatches(eventKey,teamNumber))):
if blueapi.getTeamEventMatches(teamNumber,eventKey)[n]['comp_level'] == 'qm':
matches.append(blueapi.getTeamEventMatches(eventKey)[n]['match_number'])
matches.sort()
return matches
#returns a list of qualification matches that the team played in
def getQualMatches(eventKey):
matches = []
for n in range(0,len(blueapi.getEventMatches(eventKey))):
if blueapi.getEventMatches(eventKey)[n]['comp_level'] == 'qm':
matches.append(blueapi.getEventMatches(eventKey)[n]['match_number'])
matches.sort()
return matches
#returns a list of quarterfinal matches that the team played in
def getTeamQFMatches(teamNumber, eventKey):
matches = []
for n in range(0,len(blueapi.getTeamEventMatches(eventKey))):
if blueapi.getTeamEventMatches(eventKey)[n]['comp_level'] == 'qf':
matches.append(blueapi.getTeamEventMatches(eventKey)[n]['match_number'])
matches.sort()
return matches
#returns a list of quarterfinal matches that the team played in
def getQFMatches(eventKey):
matches = []
for n in range(0,len(blueapi.getEventMatches(eventKey))):
if blueapi.getEventMatches(eventKey)[n]['comp_level'] == 'qf':
matches.append(blueapi.getEventMatches(eventKey)[n]['match_number'])
matches.sort()
return matches
#returns a list of semifinal matches that the team played in
def getTeamSFMatches(teamNumber, eventKey):
matches = []
for n in range(0,len(blueapi.getTeamEventMatches(eventKey))):
if blueapi.getTeamEventMatches(eventKey)[n]['comp_level'] == 'sf':
matches.append(blueapi.getTeamEventMatches(eventKey)[n]['match_number'])
matches.sort()
return matches
#returns a list of semifinal matches that the team played in
def getSFMatches(eventKey):
matches = []
for n in range(0,len(blueapi.getEventMatches(eventKey))):
if blueapi.getEventMatches(eventKey)[n]['comp_level'] == 'sf':
matches.append(blueapi.getEventMatches(eventKey)[n]['match_number'])
matches.sort()
return matches
#returns a list of finals matches that the team played in
def getTeamFMatches(teamNumber, eventKey):
matches = []
for n in range(0,len(blueapi.getTeamEventMatches(eventKey))):
if blueapi.getTeamEventMatches(eventKey)[n]['comp_level'] == 'f':
matches.append(blueapi.getTeamEventMatches(eventKey)[n]['match_number'])
matches.sort()
return matches
#returns a list of qualification matches that the team played in
def getFMatches(eventKey):
matches = []
for n in range(0,len(blueapi.getEventMatches(eventKey))):
if blueapi.getEventMatches(eventKey)[n]['comp_level'] == 'f':
matches.append(blueapi.getEventMatches(eventKey)[n]['match_number'])
matches.sort()
return matches
def getMatchRedScore(matchNumber,eventKey):
return blueapi.getEventMatches(eventKey)[matchNumber]['alliances']['red']['score']
def getMatchBlueScore(matchNumber,eventKey):
return blueapi.getEventMatches(eventKey)[matchNumber]['alliances']['blue']['teams']
def getMatchRedTeams(matchNumber,eventKey):
return blueapi.getEventMatches(eventKey)[matchNumber]['alliances']['red']['teams']
def getMatchBlueTeams(matchNumber,eventKey):
return blueapi.getEventMatches(eventKey)[matchNumber]['alliances']['blue']['teams']
def getMatchVideo(matchNumber,eventKey):
videos = blueapi.getEventMatches(eventKey)[matchNumber]['videos']
for n in range(0,5):
if videos[n]['type'] == 'youtube':
return "youtu.be/" + videos[n]['key']
elif videos[n]['type'] == 'tba':
return videos[n]['key']
def getSetNumber(matchNumber,eventKey):
return blueapi.getEventMatches(eventKey)[matchNumber]['set_number']
def getTimeString(matchNumber,eventKey):
return blueapi.getEventMatches(eventKey)[matchNumber]['time_string']
def getMatchKey(matchNumber,eventKey):
return blueapi.getEventMatches(eventKey)[matchNumber]['key']
def getMatchTime(matchNumber,eventKey):
return blueapi.getEventMatches(eventKey)[matchNumber]['time']
def getScoreBreakdown(matchNumber,eventKey):
return blueapi.getEventMatches(eventKey)[matchNumber]['score_breakdown']
|
jacobbendicksen/BlueAPI
|
matchinfo.py
|
Python
|
mit
| 4,831
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.apimanagement.v2019_12_01.implementation;
import com.microsoft.azure.management.apimanagement.v2019_12_01.SubscriptionState;
import org.joda.time.DateTime;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.azure.ProxyResource;
/**
* Subscription details.
*/
@JsonFlatten
public class SubscriptionContractInner extends ProxyResource {
/**
* The user resource identifier of the subscription owner. The value is a
* valid relative URL in the format of /users/{userId} where {userId} is a
* user identifier.
*/
@JsonProperty(value = "properties.ownerId")
private String ownerId;
/**
* Scope like /products/{productId} or /apis or /apis/{apiId}.
*/
@JsonProperty(value = "properties.scope", required = true)
private String scope;
/**
* The name of the subscription, or null if the subscription has no name.
*/
@JsonProperty(value = "properties.displayName")
private String displayName;
/**
* Subscription state. Possible states are * active – the subscription is
* active, * suspended – the subscription is blocked, and the subscriber
* cannot call any APIs of the product, * submitted – the subscription
* request has been made by the developer, but has not yet been approved or
* rejected, * rejected – the subscription request has been denied by an
* administrator, * cancelled – the subscription has been cancelled by the
* developer or administrator, * expired – the subscription reached its
* expiration date and was deactivated. Possible values include:
* 'suspended', 'active', 'expired', 'submitted', 'rejected', 'cancelled'.
*/
@JsonProperty(value = "properties.state", required = true)
private SubscriptionState state;
/**
* Subscription creation date. The date conforms to the following format:
* `yyyy-MM-ddTHH:mm:ssZ` as specified by the ISO 8601 standard.
*/
@JsonProperty(value = "properties.createdDate", access = JsonProperty.Access.WRITE_ONLY)
private DateTime createdDate;
/**
* Subscription activation date. The setting is for audit purposes only and
* the subscription is not automatically activated. The subscription
* lifecycle can be managed by using the `state` property. The date
* conforms to the following format: `yyyy-MM-ddTHH:mm:ssZ` as specified by
* the ISO 8601 standard.
*/
@JsonProperty(value = "properties.startDate")
private DateTime startDate;
/**
* Subscription expiration date. The setting is for audit purposes only and
* the subscription is not automatically expired. The subscription
* lifecycle can be managed by using the `state` property. The date
* conforms to the following format: `yyyy-MM-ddTHH:mm:ssZ` as specified by
* the ISO 8601 standard.
*/
@JsonProperty(value = "properties.expirationDate")
private DateTime expirationDate;
/**
* Date when subscription was cancelled or expired. The setting is for
* audit purposes only and the subscription is not automatically cancelled.
* The subscription lifecycle can be managed by using the `state` property.
* The date conforms to the following format: `yyyy-MM-ddTHH:mm:ssZ` as
* specified by the ISO 8601 standard.
*/
@JsonProperty(value = "properties.endDate")
private DateTime endDate;
/**
* Upcoming subscription expiration notification date. The date conforms to
* the following format: `yyyy-MM-ddTHH:mm:ssZ` as specified by the ISO
* 8601 standard.
*/
@JsonProperty(value = "properties.notificationDate")
private DateTime notificationDate;
/**
* Subscription primary key. This property will not be filled on 'GET'
* operations! Use '/listSecrets' POST request to get the value.
*/
@JsonProperty(value = "properties.primaryKey")
private String primaryKey;
/**
* Subscription secondary key. This property will not be filled on 'GET'
* operations! Use '/listSecrets' POST request to get the value.
*/
@JsonProperty(value = "properties.secondaryKey")
private String secondaryKey;
/**
* Optional subscription comment added by an administrator.
*/
@JsonProperty(value = "properties.stateComment")
private String stateComment;
/**
* Determines whether tracing is enabled.
*/
@JsonProperty(value = "properties.allowTracing")
private Boolean allowTracing;
/**
* Get the user resource identifier of the subscription owner. The value is a valid relative URL in the format of /users/{userId} where {userId} is a user identifier.
*
* @return the ownerId value
*/
public String ownerId() {
return this.ownerId;
}
/**
* Set the user resource identifier of the subscription owner. The value is a valid relative URL in the format of /users/{userId} where {userId} is a user identifier.
*
* @param ownerId the ownerId value to set
* @return the SubscriptionContractInner object itself.
*/
public SubscriptionContractInner withOwnerId(String ownerId) {
this.ownerId = ownerId;
return this;
}
/**
* Get scope like /products/{productId} or /apis or /apis/{apiId}.
*
* @return the scope value
*/
public String scope() {
return this.scope;
}
/**
* Set scope like /products/{productId} or /apis or /apis/{apiId}.
*
* @param scope the scope value to set
* @return the SubscriptionContractInner object itself.
*/
public SubscriptionContractInner withScope(String scope) {
this.scope = scope;
return this;
}
/**
* Get the name of the subscription, or null if the subscription has no name.
*
* @return the displayName value
*/
public String displayName() {
return this.displayName;
}
/**
* Set the name of the subscription, or null if the subscription has no name.
*
* @param displayName the displayName value to set
* @return the SubscriptionContractInner object itself.
*/
public SubscriptionContractInner withDisplayName(String displayName) {
this.displayName = displayName;
return this;
}
/**
* Get subscription state. Possible states are * active – the subscription is active, * suspended – the subscription is blocked, and the subscriber cannot call any APIs of the product, * submitted – the subscription request has been made by the developer, but has not yet been approved or rejected, * rejected – the subscription request has been denied by an administrator, * cancelled – the subscription has been cancelled by the developer or administrator, * expired – the subscription reached its expiration date and was deactivated. Possible values include: 'suspended', 'active', 'expired', 'submitted', 'rejected', 'cancelled'.
*
* @return the state value
*/
public SubscriptionState state() {
return this.state;
}
/**
* Set subscription state. Possible states are * active – the subscription is active, * suspended – the subscription is blocked, and the subscriber cannot call any APIs of the product, * submitted – the subscription request has been made by the developer, but has not yet been approved or rejected, * rejected – the subscription request has been denied by an administrator, * cancelled – the subscription has been cancelled by the developer or administrator, * expired – the subscription reached its expiration date and was deactivated. Possible values include: 'suspended', 'active', 'expired', 'submitted', 'rejected', 'cancelled'.
*
* @param state the state value to set
* @return the SubscriptionContractInner object itself.
*/
public SubscriptionContractInner withState(SubscriptionState state) {
this.state = state;
return this;
}
/**
* Get subscription creation date. The date conforms to the following format: `yyyy-MM-ddTHH:mm:ssZ` as specified by the ISO 8601 standard.
*
* @return the createdDate value
*/
public DateTime createdDate() {
return this.createdDate;
}
/**
* Get subscription activation date. The setting is for audit purposes only and the subscription is not automatically activated. The subscription lifecycle can be managed by using the `state` property. The date conforms to the following format: `yyyy-MM-ddTHH:mm:ssZ` as specified by the ISO 8601 standard.
*
* @return the startDate value
*/
public DateTime startDate() {
return this.startDate;
}
/**
* Set subscription activation date. The setting is for audit purposes only and the subscription is not automatically activated. The subscription lifecycle can be managed by using the `state` property. The date conforms to the following format: `yyyy-MM-ddTHH:mm:ssZ` as specified by the ISO 8601 standard.
*
* @param startDate the startDate value to set
* @return the SubscriptionContractInner object itself.
*/
public SubscriptionContractInner withStartDate(DateTime startDate) {
this.startDate = startDate;
return this;
}
/**
* Get subscription expiration date. The setting is for audit purposes only and the subscription is not automatically expired. The subscription lifecycle can be managed by using the `state` property. The date conforms to the following format: `yyyy-MM-ddTHH:mm:ssZ` as specified by the ISO 8601 standard.
*
* @return the expirationDate value
*/
public DateTime expirationDate() {
return this.expirationDate;
}
/**
* Set subscription expiration date. The setting is for audit purposes only and the subscription is not automatically expired. The subscription lifecycle can be managed by using the `state` property. The date conforms to the following format: `yyyy-MM-ddTHH:mm:ssZ` as specified by the ISO 8601 standard.
*
* @param expirationDate the expirationDate value to set
* @return the SubscriptionContractInner object itself.
*/
public SubscriptionContractInner withExpirationDate(DateTime expirationDate) {
this.expirationDate = expirationDate;
return this;
}
/**
* Get date when subscription was cancelled or expired. The setting is for audit purposes only and the subscription is not automatically cancelled. The subscription lifecycle can be managed by using the `state` property. The date conforms to the following format: `yyyy-MM-ddTHH:mm:ssZ` as specified by the ISO 8601 standard.
*
* @return the endDate value
*/
public DateTime endDate() {
return this.endDate;
}
/**
* Set date when subscription was cancelled or expired. The setting is for audit purposes only and the subscription is not automatically cancelled. The subscription lifecycle can be managed by using the `state` property. The date conforms to the following format: `yyyy-MM-ddTHH:mm:ssZ` as specified by the ISO 8601 standard.
*
* @param endDate the endDate value to set
* @return the SubscriptionContractInner object itself.
*/
public SubscriptionContractInner withEndDate(DateTime endDate) {
this.endDate = endDate;
return this;
}
/**
* Get upcoming subscription expiration notification date. The date conforms to the following format: `yyyy-MM-ddTHH:mm:ssZ` as specified by the ISO 8601 standard.
*
* @return the notificationDate value
*/
public DateTime notificationDate() {
return this.notificationDate;
}
/**
* Set upcoming subscription expiration notification date. The date conforms to the following format: `yyyy-MM-ddTHH:mm:ssZ` as specified by the ISO 8601 standard.
*
* @param notificationDate the notificationDate value to set
* @return the SubscriptionContractInner object itself.
*/
public SubscriptionContractInner withNotificationDate(DateTime notificationDate) {
this.notificationDate = notificationDate;
return this;
}
/**
* Get subscription primary key. This property will not be filled on 'GET' operations! Use '/listSecrets' POST request to get the value.
*
* @return the primaryKey value
*/
public String primaryKey() {
return this.primaryKey;
}
/**
* Set subscription primary key. This property will not be filled on 'GET' operations! Use '/listSecrets' POST request to get the value.
*
* @param primaryKey the primaryKey value to set
* @return the SubscriptionContractInner object itself.
*/
public SubscriptionContractInner withPrimaryKey(String primaryKey) {
this.primaryKey = primaryKey;
return this;
}
/**
* Get subscription secondary key. This property will not be filled on 'GET' operations! Use '/listSecrets' POST request to get the value.
*
* @return the secondaryKey value
*/
public String secondaryKey() {
return this.secondaryKey;
}
/**
* Set subscription secondary key. This property will not be filled on 'GET' operations! Use '/listSecrets' POST request to get the value.
*
* @param secondaryKey the secondaryKey value to set
* @return the SubscriptionContractInner object itself.
*/
public SubscriptionContractInner withSecondaryKey(String secondaryKey) {
this.secondaryKey = secondaryKey;
return this;
}
/**
* Get optional subscription comment added by an administrator.
*
* @return the stateComment value
*/
public String stateComment() {
return this.stateComment;
}
/**
* Set optional subscription comment added by an administrator.
*
* @param stateComment the stateComment value to set
* @return the SubscriptionContractInner object itself.
*/
public SubscriptionContractInner withStateComment(String stateComment) {
this.stateComment = stateComment;
return this;
}
/**
* Get determines whether tracing is enabled.
*
* @return the allowTracing value
*/
public Boolean allowTracing() {
return this.allowTracing;
}
/**
* Set determines whether tracing is enabled.
*
* @param allowTracing the allowTracing value to set
* @return the SubscriptionContractInner object itself.
*/
public SubscriptionContractInner withAllowTracing(Boolean allowTracing) {
this.allowTracing = allowTracing;
return this;
}
}
|
selvasingh/azure-sdk-for-java
|
sdk/apimanagement/mgmt-v2019_12_01/src/main/java/com/microsoft/azure/management/apimanagement/v2019_12_01/implementation/SubscriptionContractInner.java
|
Java
|
mit
| 15,027
|
<?php
declare(strict_types=1);
namespace WsdlToPhp\WsSecurity;
class Username extends Element
{
const NAME = 'Username';
public function __construct(string $username, string $namespace = self::NS_WSSE)
{
parent::__construct(self::NAME, $namespace, $username);
}
}
|
WsdlToPhp/WsSecurity
|
src/Username.php
|
PHP
|
mit
| 292
|
---
title: "Web frontend"
menu:
main:
identifier: "technical/plugins/webfrontend"
parent: "technical/plugins"
---
# Web frontend Plugins
### Plugin types
- [Asset detail](types/asset-detail-plugin)
- [Custom data types](types/custom-data-type-plugin)
- [Custom mask splitter](types/custom-mask-splitter-plugin)
- [Detail sidebar](types/detail-sidebar-plugin)
- [Editor](types/editor-plugin)
- [Export manager](types/export-manager-plugin)
### Available plugins
- [Display field values](/en/technical/plugins/webfrontend/display-field-values)
- [Barcode](/en/technical/plugins/webfrontend/barcode)
- [Pdf Creator](/en/technical/plugins/webfrontend/pdf-creator)
---
This overview shows all possible hooks for register custom code inside the Web frontend. Each section mentions at least one example Plugin where such custom code is used and can be found.
### ez5.rootMenu.registerApp
* Server-Status
### ez5.tray.registerApp
* ExportManagerList
### TransportsEditor.registerPlugin
* FTP
### BaseConfig.registerPlugin
* Example
### Presentation.registerDownloadManager
* Presentation-PPTX
### DetailSidebar.plugins.registerPlugin
* HierarchyDetail
### AssetBrowser.plugins.registerPlugin
* Example
### TransitionAction.registerAction
* TransitionActionEmail
### ExportManager.registerPlugin
* EasydbExport
### Editor.plugins.registerPlugin
* Example
### MaskSplitter.plugins.registerPlugin
This plugin allows custom code to be injected into the fields rendering in Detail, Editor, and Text-Result. Two kinds of plugins are provided, one is simple content without inner fields, the other can be used to wrap inner fields (think `<fieldset>`). The design and output of the injected DOM Nodes are entirely up to the plugin. The method `renderFields(opts)` gets all relevant render environment information inside `opts`, e.g. the current `data`which is rendered, or the instance of the `Editor`or `Detail`.
- Example
#### Classes
* **CustomMaskSplitter.coffee**
* CustomMaskSplitterEnd.coffee
* CustomFieldsRenderer.coffee
### Pool.plugins.registerPlugin
This plugin offers the possibility to add custom tabs to the Pool Editor. Using a tab, the plugin can add custom save data to the plugins data record.
* Example
#### Callbacks
* getSaveData(save_data)
* getTabs(tabs)
* getInfoDivRows(rows)
* getInfoDiv(nodes)
Method **getTabs** can add a custom Tab to the Pool Editor. The method **getSaveData** is called to prepare the save data for the pool. In this method the plugin can add the custom data collected inside a Form inside the tab. The ExamplePlugin has an example for that. **getInfoDivRows** and **getInfoDiv** can be used to add information to the ``i``-Button display in the Pool selector.
### User.plugins.registerPlugin
This plugin offers the possibility to add custom tabs to the User. Using a tab, the plugin can add custom save data to the plugins data record.
#### Callbacks
* getSaveData(save_data)
- This method is executed before saving, **save_data** contains the data which will be saved, therefore it's necessary to append data to it.
* getTabs(tabs)
- receives **tabs** which are the current tabs to be shown, a new tab should be added to **tabs** in order to show information (for example, a Form).
* isAllowed()
- returns a boolean, and it could be used to avoid showing the tab under certain circumstances (for example, show only for 'system' users).
## Callbacks
* ez5.load_defaults
* ez5.session_ready
|
programmfabrik/easydb-documentation
|
content/technical/plugins/webfrontend/_index.en.md
|
Markdown
|
mit
| 3,601
|
$(document).ready(function(){
var nbSlots = 1;
var roles = [];
$('.captain-role option').each(function(){
roles.push([$(this).val(), $(this).text()]);
});
$(".crew-slots").append(generateDivSlot(nbSlots));
$('#add_slot').click(function(){
nbSlots++;
$(".crew-slots").append(generateDivSlot(nbSlots));
})
$(document).on('click', '.remove-slot', function(){
var crewSlot = $(this).parent("div");
$('#' + crewSlot.attr('id')).remove();
renameCrewSlotDiv();
})
function generateDivSlot(nbSlots)
{
var str = "<div id=slot" + nbSlots + " class='crew-slot'>";
str += " <label for='crew-role'>Slot " + nbSlots + " : </label>";
str += " <select name='crew-role[]'>";
$(roles).each(function(){
str += " <option value='" + $(this)[0] + "'>" + $(this)[1] + "</option>";
})
str += " </select>";
if(nbSlots > 1){
str += " <button type='button' class='btn btn-default btn-xs remove-slot'>";
str += " <span class='glyphicon glyphicon-remove' aria-hidden='true'></span>";
str += " </button>";
}
str += "<br />";
str += "</div>";
return str;
}
function renameCrewSlotDiv()
{
var slotNum = 0;
$(".crew-slot").each(function(){
slotNum++;
$(this).attr('id', 'slot' + slotNum);
$(this).find("label").text("Slot " + slotNum + " : ");
})
nbSlots = slotNum;
}
})
|
rafatic/starcrew
|
public/js/addCrewSlot.js
|
JavaScript
|
mit
| 1,618
|
/* A Bison parser, made by GNU Bison 2.3. */
/* Skeleton interface for Bison's Yacc-like parsers in C
Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* Tokens. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
/* Put the tokens into the symbol table, so that GDB and other debuggers
know about them. */
enum yytokentype {
ARTICLE = 258,
VERB = 259,
NOUN = 260,
ADJECTIVE = 261,
ADVERB = 262,
PREPOSITION = 263,
END = 264
};
#endif
/* Tokens. */
#define ARTICLE 258
#define VERB 259
#define NOUN 260
#define ADJECTIVE 261
#define ADVERB 262
#define PREPOSITION 263
#define END 264
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef int YYSTYPE;
# define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1
# define YYSTYPE_IS_TRIVIAL 1
#endif
extern YYSTYPE yylval;
|
PurplePilot/lex-yacc
|
adelphi/words2/words2.tab.h
|
C
|
mit
| 2,331
|
FROM tboquet/the7hc5workeralp
MAINTAINER Thomas Boquet <thomas.boquet@hec.ca>
CMD ["celery", "worker", "-A", "alp.backend.keras_backend", "-Q", "keras", "-l", "INFO", "--maxtasksperchild=1", "--autoscale=6,1"]
|
tboquet/okeydockey
|
the7hc5workeralpk/Dockerfile
|
Dockerfile
|
mit
| 212
|
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>RokianStats II</title>
<link rel="shortcut icon" href="/RMLogo.ico" >
<script type="text/javascript">
function updateTextInput(val) {
document.getElementById('textInput').value=val+" PP";
}
</script>
</head>
<img src="RM1.png" alt="" id="blurpic" style="width:100%;max-width:400px">
<body>
<?php
session_start();
$userName = $_POST["username"];
$userName2 = $_POST["username2"];
$securitylvl2 = $_POST["securitylvl"];
$passWord = $_POST["password"];
$submitted = $_POST["submitted"];
if($submitted=="true"){
$_SESSION["username"] = $userName;
$_SESSION["password"] = $passWord;
}
else{
$passWord= $_SESSION["password"];
}
$con=mysqli_connect("127.0.0.1","496970","password","496970");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
$sql="SELECT * FROM members WHERE password='$passWord'";
$passOrNo=mysqli_query($con,$sql);
while($row = mysqli_fetch_array($passOrNo)) {
if($row['password']==$_SESSION["password"] and strtolower($row['username'])==strtolower($_SESSION["username"]))
{
$ok = true;
$securitylvl = $row['security_lvl'];
}
}
}
?>
<br/><br/><br/>
<h2><?php
if($ok==true){
echo("Accounts");}
else{
echo("You do not have access to this page");
}
?>
</h2>
<?php echo("<img id='char' src='http://www.roblox.com/Thumbs/Avatar.ashx?x=100&y=100&format=png&username=" . $_SESSION["username"] . "'></img>"); ?>
<hr>
<?php
if ($ok==true and $securitylvl>2 and $securitylvl>$securitylvl2 and $_SESSION["username"] != $userName2){
echo("<br/><br/>");
$sql="SELECT * FROM members WHERE username = '$userName2'";
$result = mysqli_query($con,$sql);
$userAcc = mysqli_fetch_array($result);
if($userAcc){
if($userAcc['security_lvl'] < $securitylvl){
$sql="UPDATE members SET security_lvl='$securitylvl2' WHERE username='$userName2' AND '$securitylvl2'<5";
$result=mysqli_query($con,$sql);
if(mysqli_error($con)==""){
Header('Location: Users.php');
}
else{
echo("Error changing security level");
}}
else{
echo("<br/><div id='header'><br/><a href='Users.php'class='logbutton'>Refresh</a> | <a href='Log.php'class='logbutton'>Log</a> | <a href='Users.php'class='logbutton'>Back</a> | <a id='logout' href='Google.php'class='logbutton'>Logout</a><p></p></div>");
echo("Your security level is too low.");
}
}
else{
echo("<br/><div id='header'><br/><a href='Users.php'class='logbutton'>Refresh</a> | <a href='Log.php'class='logbutton'>Log</a> | <a href='Users.php'class='logbutton'>Back</a> | <a id='logout' href='Google.php'class='logbutton'>Logout</a><p></p></div>");
echo("Account does not exist.");
}
}
elseif($ok==true){
echo("<br/><div id='header'><br/><a href='Users.php'class='logbutton'>Refresh</a> | <a href='Log.php'class='logbutton'>Log</a> | <a href='Users.php'class='logbutton'>Back</a> | <a id='logout' href='Google.php'class='logbutton'>Logout</a><p></p></div>");
echo("<br/>Your security level is too low.");
}
else{
$_SESSION["password"]="";
echo("<a href='Google.php'>Back</a><br/><br/>Wrong password.<br/><br/>Remember to use exact capitalization<br/>for both username and password.");
}
?>
</body>
</html>
|
billy1234567892/robloxadmin
|
EditUsers.php
|
PHP
|
mit
| 3,163
|
package com.girnar.explorejaipur.jsondata;
/**
* The Class MonumentsData.
*/
public class Monuments {
private String monumentId;
private String name;
private String category;
private String description;
private String location;
private String latitude;
private String longitude;
private String distance;
private String distanceBusStand;
private String image;
/**
* Gets the category.
*
* @return the category
*/
public String getCategory() {
return category;
}
/**
* Sets the category.
*
* @param category the new category
*/
public void setCategory(String category) {
this.category = category;
}
/**
* Gets the latitude.
*
* @return the latitude
*/
public String getLatitude() {
return latitude;
}
/**
* Sets the latitude.
*
* @param latitude the new latitude
*/
public void setLatitude(String latitude) {
this.latitude = latitude;
}
/**
* Gets the longitude.
*
* @return the longitude
*/
public String getLongitude() {
return longitude;
}
/**
* Sets the longitude.
*
* @param longitude the new longitude
*/
public void setLongitude(String longitude) {
this.longitude = longitude;
}
/**
* Gets the name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Sets the name.
*
* @param name the new name
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the location.
*
* @return the location
*/
public String getLocation() {
return location;
}
/**
* Sets the location.
*
* @param location the new location
*/
public void setLocation(String location) {
this.location = location;
}
/**
* @return the monumentId
*/
public String getMonumentId() {
return monumentId;
}
/**
* @param monumentId the monumentId to set
*/
public void setMonumentId(String monumentId) {
this.monumentId = monumentId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
/**
* @return the distanceBusStand
*/
public String getDistanceBusStand() {
return distanceBusStand;
}
/**
* @param distanceBusStand the distanceBusStand to set
*/
public void setDistanceBusStand(String distanceBusStand) {
this.distanceBusStand = distanceBusStand;
}
}
|
tarundixitravi/ExploreJaipur
|
src/com/girnar/explorejaipur/jsondata/Monuments.java
|
Java
|
mit
| 2,582
|
require 'spec_helper'
describe CloudPayments::Namespaces do
subject{ CloudPayments::Client.new }
describe '#payments' do
specify{ expect(subject.payments).to be_instance_of(CloudPayments::Namespaces::Payments) }
end
describe '#subscriptions' do
specify{ expect(subject.subscriptions).to be_instance_of(CloudPayments::Namespaces::Subscriptions) }
end
describe '#ping' do
context 'when successful response' do
before{ stub_api_request('ping/successful').perform }
specify{ expect(subject.ping).to be_truthy }
end
context 'when failed response' do
before{ stub_api_request('ping/failed').perform }
specify{ expect(subject.ping).to be_falsy }
end
context 'when empty response' do
before{ stub_api_request('ping/failed').to_return(body: '') }
specify{ expect(subject.ping).to be_falsy }
end
context 'when error response' do
before{ stub_api_request('ping/failed').to_return(status: 404) }
specify{ expect(subject.ping).to be_falsy }
end
context 'when exception occurs while request' do
before{ stub_api_request('ping/failed').to_raise(::Faraday::Error::ConnectionFailed) }
specify{ expect(subject.ping).to be_falsy }
end
context 'when timeout occurs while request' do
before{ stub_api_request('ping/failed').to_timeout }
specify{ expect(subject.ping).to be_falsy }
end
end
end
|
heretge/cloud_payments
|
spec/cloud_payments/namespaces_spec.rb
|
Ruby
|
mit
| 1,423
|
const { Router } = require('director');
const ReactDOM = require('react-dom');
const { computed, observable } = require('../../core');
const React = require('../../react');
const { Todo, todos } = require('./model');
const { StatsView } = require('./StatsView');
const { TodoView } = require('./TodoView');
const { cat } = require('../../cat');
class AppView extends React.Component {
constructor() {
super();
this.newTodoTitle = observable("");
this.todoFilter = observable("all");
this.todoFiltered = computed(() => todos[this.todoFilter.$].$);
this.footerStyle = computed(() => {
let result = {};
if (todos.all.$.length === 0)
result.display = "none";
return result;
});
this.allComplete = computed({
read: () => !todos.active.$.length,
write: (v) => {
todos.all.$.forEach(todo => {
todo.completed.$ = Boolean(v);
});
},
});
}
componentDidMount() {
let router = Router({
'/': () => {
this.todoFilter.$ = "all";
},
'/active': () => {
this.todoFilter.$ = "active";
},
'/completed': () => {
this.todoFilter.$ = "completed";
},
});
router.init('/');
}
render() {
return <div>
<section className="todoAppView">
<header className="header">
<h1>todos</h1>
<input className="new-todo"
placeholder="What needs to be done?"
autoFocus
value={ this.newTodoTitle }
onKeyPress={ this.createOnEnter.bind(this) }
/>
</header>
<section className="main">
<input className="toggle-all"
id="toggle-all"
type="checkbox"
checked={ this.allComplete }/>
<label htmlFor="toggle-all">Mark all as complete</label>
<ul className="todo-list">
{this.todoFiltered.$.map(todo => <TodoView key={todo.id.$} todo={todo} />)}
</ul>
</section>
<footer className="footer" style={this.footerStyle}>
<StatsView todoFilter={ this.todoFilter }/>
</footer>
</section>
</div>;
}
createOnEnter(event) {
if (event.key === "Enter" && this.newTodoTitle.$.trim().length) {
todos.add(new Todo(this.newTodoTitle.$));
this.newTodoTitle.$ = "";
}
}
}
cat(__filename).providesEach({
AppView,
});
ReactDOM.render(
<AppView/>,
document.getElementById("main")
);
module.exports = {
AppView,
}
|
alastairpatrick/spellbound
|
demo/todomvc/AppView.js
|
JavaScript
|
mit
| 2,721
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
#define REI 'A'
#define HAKUSYU 'B'
int main(int argc, char const *argv[]) {
char input[63], *data, output;
int n, isREI = TRUE;
scanf("%[^\n]", input); // 1 2 3
data = strtok(input, " ");
while (data != NULL) {
output = isREI ? REI : HAKUSYU;
for (int i = 0; i < atoi(data); i++)
printf("%c", output);
isREI = isREI ? FALSE : TRUE;
data = strtok(NULL, " ");
}
puts("");
// output: ABBAAA
return 0;
}
|
sa-inu/algorithm_toybox
|
p__za/D63.c
|
C
|
mit
| 536
|
// Include application headers.
#include "Display.hpp"
namespace wabbit {
Display::Display( )
{
cv::namedWindow( "Hello", cv::WINDOW_AUTOSIZE );
}
wabbit::ImageAndTime*
Display::operator()( wabbit::ImageAndTime* image_and_time )
{
cv::imshow( "Hello", image_and_time->image );
cv::waitKey( 1 );
return image_and_time;
}
} // namespace wabbit.
|
vmlaker/wabbit
|
src/cpp/src/Display.cpp
|
C++
|
mit
| 365
|
---
layout: post
title: Travel a lot? Here's how to stay organized, like professors do
author: Charles Sutton
tags:
- advice
- organizational advice
date: 2017-12-02 17:00:00
---
We had a fun time on the professors' Facebook the other day, swapping stories of the dumbest travel mistakes that we've made. You know, booking flights to the wrong country, forgetting to book a hotel, registering for the conference twice, and other such hilarity.
Let's face it, professors travel a lot. We are also very bad at remembering things. This is a combination that makes for comedy, unless you're the poor sod who has to live through it. (That's *Professor* Sod, to you.)
What this means is, from long and painful experience, I've learned how to not to forget things as often when I travel. And now I will tell you my secrets, if I can remember them.
I keep a *packing list* (shocker!) that I reuse every time I pack my bags. I have a master list that I keep electronically and make a copy of for each trip. The important part is: Every time I arrive somewhere and forget something (toothpaste, underwear, etc), I add it to the master packing list for next time. After many years of this, I am now convinced that this list now contains everything I could possibly want to bring, and now I will never forget to pack something ever again. Well, hardly ever.
For toiletries I have an additional system, as they are too easy to forget. I keep a separate complete set of toiletries in a drawer, for travelling only. When I pack, I just unload the drawer into my luggage, and I know I have everything. When I return, I return the toiletries to the drawer, checking to see if anything needs to be replenished. This includes medicines; I always travel with paracetamol, just in case, except when I travel to the US, in which case I bring acetaminophen instead.
But the packing list can't keep track of everything. For example, if you try to list "make sure hotel is booked" or "tell wife that I'm travelling" on your list of what to pack, it turns out that you see that a little bit too late to be useful. Or that's what my wife says, anyway.
So now I have a "travel prep list" as well, which lists the things I need to do weeks in advance, or after I return. I have a document that keeps track of the lists for all of my upcoming trips: book flights, book hotel, register for conference, submit travel reimbursement, etc. This dramatically reduces the chance that I will book two hotel rooms for the same conference.
And finally, there is [TripIt](http://TripIt.com). TripIt is an amazing service that I have used for over a decade. Every time you get a confirmation email from an airline, hotel, travel agent, etc, you forward it to a special email address plans@tripit.com. TripIt parses all these emails and collects them into a single itinerary, using the dates to figure out which emails belong to the same trip. You never have to root around looking for a confirmation number again. It's great! Especially clever: to sign up, just forward your first confirmation email to plans@tripit.com
Now this leaves one more question. Why are professors always so forgetful in the first place? There's a very good reason for that, actually. But that's a different post...
|
casutton/casutton.github.io
|
_posts/2017-12-02-travel-professor.md
|
Markdown
|
mit
| 3,259
|
body {
font-family: 'Lato', sans-serif;
}
#title {
margin-left: auto;
margin-right: auto;
text-align: center;
padding: 20px;
font-size: 1.7em;
}
svg {
display: block;
margin: 0 auto;
}
path {
fill: none;
}
.axis path, .axis line {
stroke: gray;
stroke-opacity: 0.5;
}
.label {
fill: gray;
opacity: 0.7;
}
.line {
stroke-width: 1.5px;
opacity: 0.7;
}
.point {
fill: white;
stroke-width: 1.5px;
opacity: 0.7;
}
.interpolated {
fill: black;
opacity: 0.5;
}
|
rlucioni/cs171-hw3-lucioni-renzo
|
Problem2/css/linegraph.css
|
CSS
|
mit
| 534
|
package com.zfgc.mappers;
import com.zfgc.dbobj.UserSecuritySettingsDbObj;
import com.zfgc.dbobj.UserSecuritySettingsDbObjExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface UserSecuritySettingsDbObjMapper {
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table USER_SECURITY_SETTINGS
* @mbg.generated Sun Mar 31 13:23:26 EDT 2019
*/
long countByExample(UserSecuritySettingsDbObjExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table USER_SECURITY_SETTINGS
* @mbg.generated Sun Mar 31 13:23:26 EDT 2019
*/
int deleteByExample(UserSecuritySettingsDbObjExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table USER_SECURITY_SETTINGS
* @mbg.generated Sun Mar 31 13:23:26 EDT 2019
*/
int deleteByPrimaryKey(Integer userSecuritySettingsId);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table USER_SECURITY_SETTINGS
* @mbg.generated Sun Mar 31 13:23:26 EDT 2019
*/
int insert(UserSecuritySettingsDbObj record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table USER_SECURITY_SETTINGS
* @mbg.generated Sun Mar 31 13:23:26 EDT 2019
*/
int insertSelective(UserSecuritySettingsDbObj record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table USER_SECURITY_SETTINGS
* @mbg.generated Sun Mar 31 13:23:26 EDT 2019
*/
List<UserSecuritySettingsDbObj> selectByExample(UserSecuritySettingsDbObjExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table USER_SECURITY_SETTINGS
* @mbg.generated Sun Mar 31 13:23:26 EDT 2019
*/
UserSecuritySettingsDbObj selectByPrimaryKey(Integer userSecuritySettingsId);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table USER_SECURITY_SETTINGS
* @mbg.generated Sun Mar 31 13:23:26 EDT 2019
*/
int updateByExampleSelective(@Param("record") UserSecuritySettingsDbObj record,
@Param("example") UserSecuritySettingsDbObjExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table USER_SECURITY_SETTINGS
* @mbg.generated Sun Mar 31 13:23:26 EDT 2019
*/
int updateByExample(@Param("record") UserSecuritySettingsDbObj record,
@Param("example") UserSecuritySettingsDbObjExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table USER_SECURITY_SETTINGS
* @mbg.generated Sun Mar 31 13:23:26 EDT 2019
*/
int updateByPrimaryKeySelective(UserSecuritySettingsDbObj record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table USER_SECURITY_SETTINGS
* @mbg.generated Sun Mar 31 13:23:26 EDT 2019
*/
int updateByPrimaryKey(UserSecuritySettingsDbObj record);
void updateUserPassword(@Param("usersId") Integer usersId, @Param("password") String password);
}
|
ZFGCCP/ZFGC3
|
src/main/java/com/zfgc/mappers/UserSecuritySettingsDbObjMapper.java
|
Java
|
mit
| 3,208
|
(function () {
'use strict';
angular
.module('buildings')
.controller('BuildingsController', BuildingsController);
BuildingsController.$inject = ['$scope', '$state', 'projectResolve', '$window', 'Authentication'];
function BuildingsController ($scope, $state, project, $window, Authentication) {
var vm = this;
// initialization objects
vm.project = project;
vm.project.isNewBuilding = false;
vm.project.removeBuilding = false;
vm.project.isUpdateBuilding = false;
vm.building = {};
// functionality
vm.save = save;
vm.remove = remove;
vm.edit = edit;
// initialization variables
vm.parentName = $state.params.projectName;
vm.index = $state.params.index ? $state.params.index : 0;
// implementation
function save(isValid) {
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'vm.form.buildingForm');
return false;
}
if (vm.project._id) {
vm.project.addBuilding = vm.building;
vm.project.isNewBuilding = true;
vm.project.$update(successCallBack, errorCallBack);
} else {
// throw error , can't exist building without project
}
}
function successCallBack(res) {
$state.go('projects.view', {
projectId: res._id
});
}
function successCallBackUpdateBuilding(res) {
$state.go('buildings.view', {
projectId: res._id,
buildingId: res.buildings[vm.index]._id
});
}
function errorCallBack(res) {
vm.error = res.data + ' ' + res.statusText;
}
function remove(index) {
if ($window.confirm('Are you sure you want to remove building ')) {
vm.project.removeBuilding = true;
vm.project.index = index;
vm.project.$update(successCallBack, errorCallBack);
}
}
function edit(isValid) {
vm.project.isUpdateBuilding = true;
vm.project.index = vm.index;
vm.project.$update(successCallBackUpdateBuilding, errorCallBack);
}
}
}());
|
AlekseyH/buildingCompany
|
modules/buildings/client/controllers/buildings.client.controllers.js
|
JavaScript
|
mit
| 2,046
|
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>CuteDigitalClock</title>
<style type="text/css">
body
{
margin: 0;
padding: 0;
width: 130px;
height: 67px;
vertical-align: middle;
text-align: center;
}
</style>
<script type="text/javascript">
function initTime()
{
initSettings();
var backgroundElement = document.getElementById("background");
timeElement = backgroundElement.addTextObject("00:00", fontFamily, fontSize, fontColor, 0, 0);
timeElement.addGlow(glowColor, glowRadius, glowOpacity);
updateTime();
}
function initSettings()
{
if(System.Gadget.Settings.readString("fontFamily") === "")
{
System.Gadget.Settings.writeString("fontFamily", "Segoe UI");
}
if(System.Gadget.Settings.readString("fontSize") === "")
{
System.Gadget.Settings.writeString("fontSize", "50");
}
if(System.Gadget.Settings.readString("fontColor") === "")
{
System.Gadget.Settings.writeString("fontColor", "#ffffff");
}
if(System.Gadget.Settings.readString("glowColor") === "")
{
System.Gadget.Settings.writeString("glowColor", "#000000");
}
if(System.Gadget.Settings.readString("glowRadius") === "")
{
System.Gadget.Settings.writeString("glowRadius", "10");
}
if(System.Gadget.Settings.readString("glowOpacity") === "")
{
System.Gadget.Settings.writeString("glowOpacity", "20");
}
loadSettings();
}
function loadSettings()
{
fontFamily = System.Gadget.Settings.readString("fontFamily");
fontSize = System.Gadget.Settings.readString("fontSize");
fontColor = convertHexColor(System.Gadget.Settings.readString("fontColor"));
glowColor = convertHexColor(System.Gadget.Settings.readString("glowColor"));
glowRadius = System.Gadget.Settings.readString("glowRadius");
glowOpacity = System.Gadget.Settings.readString("glowOpacity");
}
function convertHexColor(hexColor)
{
var red = parseInt(hexColor.slice(1,3), 16);
var green = parseInt(hexColor.slice(3,5), 16);
var blue = parseInt(hexColor.slice(5,7), 16);
return "Color(0, " + red + ", " + green + ", " + blue + ")";
}
function updateTime()
{
setTimeout("updateTime()", 1000);
var today = new Date(), hours = today.getHours(), minutes = today.getMinutes();
if(hours < 10)
{
timeValue = ("0" + hours);
}
else
{
timeValue = hours;
}
timeValue += ":";
if(minutes < 10)
{
timeValue += ("0" + minutes);
}
else
{
timeValue += minutes;
}
timeElement.value = timeValue;
}
window.attachEvent("onload", initTime);
System.Gadget.settingsUI = "settings.html";
System.Gadget.onSettingsClosed = settingsClosed;
function settingsClosed(event)
{
loadSettings();
timeElement.font = fontFamily;
timeElement.fontsize = fontSize;
timeElement.color = fontColor;
timeElement.addGlow(glowColor, glowRadius, glowOpacity);
}
</script>
</head>
<body>
<g:background id="background" src="background.png" style="width:100%; height:100%; z-index: -1; position: absolute; top: 0; left: 0;" opacity="0"></g:background>
</body>
</html>
|
jana4u/CuteDigitalClock.gadget
|
gadget.html
|
HTML
|
mit
| 3,691
|
// Developed by doiTTeam => devdoiTTeam@gmail.com
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace DHT
{
[DataContract(Name = "FindNodeResult{0}")]
public class FindNodeResult<TKey>
{
public FindNodeResult(IEnumerable<NodeIdentifier<TKey>> nodes)
{
Nodes = nodes;
}
[DataMember]
public IEnumerable<NodeIdentifier<TKey>> Nodes { get; private set; }
}
}
|
dayanruben/DistributedSearchs
|
Src/DHT/Common/FindNodeResult.cs
|
C#
|
mit
| 453
|
<div class="col-sm-12" ng-controller="ObraDetalleController">
<span ng-if="bandera == false">
<small><em>Construyendo Vista</em></small>
<uib-progressbar class="progress-striped active" value="100" type="info">Cargando...</uib-progressbar>
</span>
<span ng-if="bandera == true">
<div class="row">
<div class="col-lg-12">
<div class="widget-box">
<div class="widget-header widget-header-flat">
<h4 class="widget-title smaller">{{obra.nombre}}</h4>
</div>
<div class="widget-body">
<div class="profile-user-info profile-user-info-striped">
<div class="profile-info-row">
<div class="profile-info-name"> Mes </div>
<div class="profile-info-value">
<i class="ace-icon fa fa-calendar bigger-110 blue"></i>
<span>{{obra.mes}}</span>
</div>
</div>
<div class="profile-info-row">
<div class="profile-info-name"> Año </div>
<div class="profile-info-value">
<i class="ace-icon fa fa-calendar bigger-110 blue"></i>
<span>{{obra.anho}}</span>
</div>
</div>
<div class="profile-info-row">
<div class="profile-info-name"> Tema </div>
<div class="profile-info-value">
<i class="ace-icon glyphicon glyphicon-text-width bigger-110 blue"></i>
<span>{{obra.tema}}</span>
</div>
</div>
<div class="profile-info-row">
<div class="profile-info-name"> Autor </div>
<div class="profile-info-value">
<i class="ace-icon glyphicon glyphicon-user bigger-110 blue"></i>
<span>{{obra.autor}}</span>
</div>
</div>
<div class="profile-info-row">
<div class="profile-info-name"> Mensaje </div>
<div class="profile-info-value">
<i class="ace-icon glyphicon glyphicon-align-justify bigger-110 blue"></i>
{{obra.mensaje}}
</div>
</div>
<div class="profile-info-row">
<div class="profile-info-name"> Imagen </div>
<div class="profile-info-value text-center">
<span ng-if="banderaObra == false">
<div class="col-xs-12">
<h3 class="header smaller lighter blue">
<i class="ace-icon fa fa-spinner fa-spin blue bigger-125"></i>
Cargando Obra
</h3>
</div>
</span>
<span ng-if="banderaObra == true">
<img ng-src="{{obra.archivo != null && obra.archivo || ''}}" alt="{{obra.nombre}}" class="imagenVista" title="{{obra.nombre}}">
</span>
</div>
</div>
</div>
</div>
<div class="widget-footer">
<div class="row">
<div class="col-lg-12 text-center">
<button class="btn btn-sm btn-primary" ng-click="Editar()">Editar</button>
<button class="btn btn-sm btn-danger" ng-click="openModal('sm', id)">Anular</button>
</div>
</div>
</div>
</div>
</div>
</div>
</span>
</div>
|
javiomoreno/Calendario-Virtual-AKC
|
app/partes/administrador/imagenes/obras/detalle-obra.html
|
HTML
|
mit
| 4,608
|
export { default } from 'ember-flexberry-gis/components/layer-treenode-contents/base';
|
Flexberry/ember-flexberry-gis
|
app/components/layer-treenode-contents/base.js
|
JavaScript
|
mit
| 87
|
var path = require('path')
var webpack = require('webpack')
const config = {
entry: path.join(__dirname, './src/index.js'),
output: {
filename: 'ajax-manager.js',
library: 'ajaxManager',
libraryTarget: 'umd',
path: path.join(__dirname, './dist')
},
module: {
rules: [
{
test: /\.js$/,
use: [
{ loader: 'babel-loader' }
]
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
sourceMap: true
})
]
}
module.exports = config
|
BboyAwey/ajax-manager
|
webpack.config.js
|
JavaScript
|
mit
| 575
|
"""
WSGI config for gevsckio project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "gevsckio.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
arthuralvim/django-gevsckio-example
|
gevsckio/wsgi.py
|
Python
|
mit
| 391
|
if(typeof exports === 'object') {
var assert = require("assert");
var alasql = require('../alasql.js');
};
if(false) {
describe('Test 16b', function() {
it('Grouping', function(done){
alasql('create database test16;use test16');
alasql.tables.students = new alasql.Table({data: [
{studentid:58,studentname:'Sarah Patrik',courseid:1, startdate: new Date(2014,0,10), amt:10, schoolid:1},
{studentid:102,studentname:'John Stewart', courseid:2, startdate: new Date(2014,0,20), amt:20, schoolid:1},
{studentid:103,studentname:'Joan Blackmore', courseid:2, startdate: new Date(2014,0,20), amt:20, schoolid:1},
{studentid:104,studentname:'Anna Wooden', courseid:4, startdate: new Date(2014,0,15), amt:30, schoolid:2},
{studentid:150,studentname:'Astrid Carlson', courseid:7, startdate: new Date(2014,0,15), amt:30, schoolid:1},
]});
alasql.tables.courses = new alasql.Table({data:[
{courseid:1, coursename: 'first', schoolid:1},
{courseid:2, coursename: 'second', schoolid:1},
{courseid:3, coursename: 'third', schoolid:2},
{courseid:4, coursename: 'fourth', schoolid:2},
{courseid:5, coursename: 'fifth', schoolid:2}
]});
alasql.tables.schools = new alasql.Table({data:[
{schoolid:1, schoolname: 'Northern School', regionid:'north'},
{schoolid:2, schoolname: 'Southern School', regionid:'south'},
{schoolid:3, schoolname: 'Eastern School', regionid:'east'},
{schoolid:4, schoolname: 'Western School', regionid:'west'},
]});
var res = alasql.exec('SELECT * '+
' FROM students '+
' LEFT JOIN courses ON students.courseid = courses.courseid AND students.schoolid = courses.schoolid'+
' LEFT JOIN schools ON students.schoolid = schools.schoolid '+
' GROUP BY schoolid, courseid, studentname '+
' ORDER BY studentname DESC' );
console.log(res);
assert.equal(5, res.length);
assert.equal(1, res[0].courseid);
assert.equal(2, res[1].courseid);
assert.equal(2, res[2].courseid);
assert.equal(7, res[3].courseid);
assert.equal(4, res[4].courseid);
alasql('drop database test16');
done();
});
});
}
|
agershun/alamdx
|
node_modules/alasql/test/test16a.js
|
JavaScript
|
mit
| 2,087
|
/*
* jQuery File Upload Image Preview & Resize Plugin
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
/* jshint nomen:false */
/* global define, require, window, Blob */
;(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'load-image',
'load-image-meta',
'load-image-scale',
'load-image-exif',
'canvas-to-blob',
'jquery.fileupload-process'
], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS:
factory(
require('jquery'),
require('blueimp-load-image/js/load-image'),
require('blueimp-load-image/js/load-image-meta'),
require('blueimp-load-image/js/load-image-scale'),
require('blueimp-load-image/js/load-image-exif'),
require('blueimp-canvas-to-blob'),
require('./jquery.fileupload-process')
);
} else {
// Browser globals:
factory(
window.jQuery,
window.loadImage
);
}
}(function ($, loadImage) {
'use strict';
// Prepend to the default processQueue:
$.blueimp.fileupload.prototype.options.processQueue.unshift(
{
action: 'loadImageMetaData',
disableImageHead: '@',
disableExif: '@',
disableExifThumbnail: '@',
disableExifSub: '@',
disableExifGps: '@',
disabled: '@disableImageMetaDataLoad'
},
{
action: 'loadImage',
// Use the action as prefix for the "@" options:
prefix: true,
fileTypes: '@',
maxFileSize: '@',
noRevoke: '@',
disabled: '@disableImageLoad'
},
{
action: 'resizeImage',
// Use "image" as prefix for the "@" options:
prefix: 'image',
maxWidth: '@',
maxHeight: '@',
minWidth: '@',
minHeight: '@',
crop: '@',
orientation: '@',
forceResize: '@',
disabled: '@disableImageResize'
},
{
action: 'saveImage',
quality: '@imageQuality',
type: '@imageType',
disabled: '@disableImageResize'
},
{
action: 'saveImageMetaData',
disabled: '@disableImageMetaDataSave'
},
{
action: 'resizeImage',
// Use "preview" as prefix for the "@" options:
prefix: 'preview',
maxWidth: '@',
maxHeight: '@',
minWidth: '@',
minHeight: '@',
crop: '@',
orientation: '@',
thumbnail: '@',
canvas: '@',
disabled: '@disableImagePreview'
},
{
action: 'setImage',
name: '@imagePreviewName',
disabled: '@disableImagePreview'
},
{
action: 'deleteImageReferences',
disabled: '@disableImageReferencesDeletion'
}
);
// The File Upload Resize plugin extends the fileupload widget
// with image resize functionality:
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
options: {
// The regular expression for the types of images to load:
// matched against the file type:
loadImageFileTypes: /^image\/(gif|jpeg|png|svg\+xml)$/,
// The maximum file size of images to load:
loadImageMaxFileSize: 10000000, // 10MB
// The maximum width of resized images:
imageMaxWidth: 1920,
// The maximum height of resized images:
imageMaxHeight: 1080,
// Defines the image orientation (1-8) or takes the orientation
// value from Exif data if set to true:
imageOrientation: false,
// Define if resized images should be cropped or only scaled:
imageCrop: false,
// Disable the resize image functionality by default:
disableImageResize: true,
// The maximum width of the preview images:
previewMaxWidth: 80,
// The maximum height of the preview images:
previewMaxHeight: 80,
// Defines the preview orientation (1-8) or takes the orientation
// value from Exif data if set to true:
previewOrientation: true,
// Create the preview using the Exif data thumbnail:
previewThumbnail: true,
// Define if preview images should be cropped or only scaled:
previewCrop: false,
// Define if preview images should be resized as canvas elements:
previewCanvas: true
},
processActions: {
// Loads the image given via data.files and data.index
// as img element, if the browser supports the File API.
// Accepts the options fileTypes (regular expression)
// and maxFileSize (integer) to limit the files to load:
loadImage: function (data, options) {
if (options.disabled) {
return data;
}
var that = this,
file = data.files[data.index],
dfd = $.Deferred();
if (($.type(options.maxFileSize) === 'number' &&
file.size > options.maxFileSize) ||
(options.fileTypes &&
!options.fileTypes.test(file.type)) ||
!loadImage(
file,
function (img) {
if (img.src) {
data.img = img;
}
dfd.resolveWith(that, [data]);
},
options
)) {
return data;
}
return dfd.promise();
},
// Resizes the image given as data.canvas or data.img
// and updates data.canvas or data.img with the resized image.
// Also stores the resized image as preview property.
// Accepts the options maxWidth, maxHeight, minWidth,
// minHeight, canvas and crop:
resizeImage: function (data, options) {
if (options.disabled || !(data.canvas || data.img)) {
return data;
}
options = $.extend({canvas: true}, options);
var that = this,
dfd = $.Deferred(),
img = (options.canvas && data.canvas) || data.img,
resolve = function (newImg) {
if (newImg && (newImg.width !== img.width ||
newImg.height !== img.height ||
options.forceResize)) {
data[newImg.getContext ? 'canvas' : 'img'] = newImg;
}
data.preview = newImg;
dfd.resolveWith(that, [data]);
},
thumbnail;
if (data.exif) {
if (options.orientation === true) {
options.orientation = data.exif.get('Orientation');
}
if (options.thumbnail) {
thumbnail = data.exif.get('Thumbnail');
if (thumbnail) {
loadImage(thumbnail, resolve, options);
return dfd.promise();
}
}
// Prevent orienting the same image twice:
if (data.orientation) {
delete options.orientation;
} else {
data.orientation = options.orientation;
}
}
if (img) {
resolve(loadImage.scale(img, options));
return dfd.promise();
}
return data;
},
// Saves the processed image given as data.canvas
// inplace at data.index of data.files:
saveImage: function (data, options) {
if (!data.canvas || options.disabled) {
return data;
}
var that = this,
file = data.files[data.index],
dfd = $.Deferred();
if (data.canvas.toBlob) {
data.canvas.toBlob(
function (blob) {
if (!blob.name) {
if (file.type === blob.type) {
blob.name = file.name;
} else if (file.name) {
blob.name = file.name.replace(
/\.\w+$/,
'.' + blob.type.substr(6)
);
}
}
// Don't restore invalid meta data:
if (file.type !== blob.type) {
delete data.imageHead;
}
// Store the created blob at the position
// of the original file in the files list:
data.files[data.index] = blob;
dfd.resolveWith(that, [data]);
},
options.type || file.type,
options.quality
);
} else {
return data;
}
return dfd.promise();
},
loadImageMetaData: function (data, options) {
if (options.disabled) {
return data;
}
var that = this,
dfd = $.Deferred();
loadImage.parseMetaData(data.files[data.index], function (result) {
$.extend(data, result);
dfd.resolveWith(that, [data]);
}, options);
return dfd.promise();
},
saveImageMetaData: function (data, options) {
if (!(data.imageHead && data.canvas &&
data.canvas.toBlob && !options.disabled)) {
return data;
}
var file = data.files[data.index],
blob = new Blob([
data.imageHead,
// Resized images always have a head size of 20 bytes,
// including the JPEG marker and a minimal JFIF header:
this._blobSlice.call(file, 20)
], {type: file.type});
blob.name = file.name;
data.files[data.index] = blob;
return data;
},
// Sets the resized version of the image as a property of the
// file object, must be called after "saveImage":
setImage: function (data, options) {
if (data.preview && !options.disabled) {
data.files[data.index][options.name || 'preview'] = data.preview;
}
return data;
},
deleteImageReferences: function (data, options) {
if (!options.disabled) {
delete data.img;
delete data.canvas;
delete data.preview;
delete data.imageHead;
}
return data;
}
}
});
}));
|
SJTU-UMJI-Tech/JI-Student-Web
|
js/file-upload/js/jquery.fileupload-image.js
|
JavaScript
|
mit
| 12,297
|
/*Problem 2. Divisible by 7 and 5
Write a boolean expression that checks for given integer if it can be divided (without remainder) by 7 and 5 in the same time.
Examples:
n Divided by 7 and 5?
3 false
0 true
5 false
7 false
35 true
140 true*/
var number = 35,
devidedBySevenandFive = true;
if (number % 7 == 0 && number % 5 == 0) {
console.log(devidedBySevenandFive)
}
else {
console.log(!devidedBySevenandFive)
}
|
koravski/TelerikAcademy
|
06.JS Fundamentals/02.OperatorsАndExpressions/Problem02DivisibleBy7And5.js
|
JavaScript
|
mit
| 438
|
# -----------------------------------------------------------------------------
# Constants
# -----------------------------------------------------------------------------
SERVICE_UNIT_ENVIRONMENT_KEYS="
DOCKER_CONTAINER_OPTS
DOCKER_IMAGE_PACKAGE_PATH
DOCKER_IMAGE_TAG
DOCKER_PORT_MAP_TCP_22
SSH_AUTHORIZED_KEYS
SSH_AUTOSTART_SSHD
SSH_AUTOSTART_SSHD_BOOTSTRAP
SSH_CHROOT_DIRECTORY
SSH_INHERIT_ENVIRONMENT
SSH_SUDO
SSH_USER
SSH_USER_FORCE_SFTP
SSH_USER_HOME
SSH_USER_ID
SSH_USER_PASSWORD
SSH_USER_PASSWORD_HASHED
SSH_USER_SHELL
"
SERVICE_UNIT_REGISTER_ENVIRONMENT_KEYS="
REGISTER_ETCD_PARAMETERS
REGISTER_TTL
REGISTER_UPDATE_INTERVAL
"
# -----------------------------------------------------------------------------
# Variables
# -----------------------------------------------------------------------------
SERVICE_UNIT_INSTALL_TIMEOUT=${SERVICE_UNIT_INSTALL_TIMEOUT:-5}
|
zeroc0d3/docker-lab
|
application/rootfs/opt/scmi/service-unit.sh
|
Shell
|
mit
| 892
|
<div class="code-box" id="demo-row-selection">
<div class="code-box-demo">
<div id="components-table-demo-row-selection"></div>
<script>(function(){'use strict';
var Table = antd.Table;
var columns = [{
title: '姓名',
dataIndex: 'name',
render: function render(text) {
return React.createElement(
'a',
{ href: 'javascript:;' },
text
);
}
}, {
title: '年龄',
dataIndex: 'age'
}, {
title: '住址',
dataIndex: 'address'
}];
var data = [{
key: '1',
name: '胡彦斌',
age: 32,
address: '西湖区湖底公园1号'
}, {
key: '2',
name: '胡彦祖',
age: 42,
address: '西湖区湖底公园1号'
}, {
key: '3',
name: '李大嘴',
age: 32,
address: '西湖区湖底公园1号'
}];
// 通过 rowSelection 对象表明需要行选择
var rowSelection = {
onSelect: function onSelect(record, selected, selectedRows) {
console.log(record, selected, selectedRows);
},
onSelectAll: function onSelectAll(selected, selectedRows) {
console.log(selected, selectedRows);
}
};
React.render(React.createElement(Table, { rowSelection: rowSelection, columns: columns, dataSource: data }), document.getElementById('components-table-demo-row-selection'));})()</script><div class="highlight"><pre><code class="javascript"><span class="keyword">var</span> Table = antd.Table;
<span class="keyword">var</span> columns = [{
title: <span class="string">'姓名'</span>,
dataIndex: <span class="string">'name'</span>,
render: <span class="function"><span class="keyword">function</span><span class="params">(text)</span> {</span>
<span class="keyword">return</span> <span class="xml"><span class="tag"><<span class="title">a</span> <span class="attribute">href</span>=<span class="value">"javascript:;"</span>></span>{text}<span class="tag"></<span class="title">a</span>></span>;</span>
}
}, {
title: <span class="string">'年龄'</span>,
dataIndex: <span class="string">'age'</span>
}, {
title: <span class="string">'住址'</span>,
dataIndex: <span class="string">'address'</span>
}];
<span class="keyword">var</span> data = [{
key: <span class="string">'1'</span>,
name: <span class="string">'胡彦斌'</span>,
age: <span class="number">32</span>,
address: <span class="string">'西湖区湖底公园1号'</span>
}, {
key: <span class="string">'2'</span>,
name: <span class="string">'胡彦祖'</span>,
age: <span class="number">42</span>,
address: <span class="string">'西湖区湖底公园1号'</span>
}, {
key: <span class="string">'3'</span>,
name: <span class="string">'李大嘴'</span>,
age: <span class="number">32</span>,
address: <span class="string">'西湖区湖底公园1号'</span>
}];
<span class="comment">// 通过 rowSelection 对象表明需要行选择</span>
<span class="keyword">var</span> rowSelection = {
onSelect: <span class="function"><span class="keyword">function</span><span class="params">(record, selected, selectedRows)</span> {</span>
console.log(record, selected, selectedRows);
},
onSelectAll: <span class="function"><span class="keyword">function</span><span class="params">(selected, selectedRows)</span> {</span>
console.log(selected, selectedRows);
}
};
React.render(<span class="xml"><span class="tag"><<span class="title">Table</span> <span class="attribute">rowSelection</span>=<span class="value">{rowSelection}</span> <span class="attribute">columns</span>=<span class="value">{columns}</span> <span class="attribute">dataSource</span>=<span class="value">{data}</span> /></span>
, document.getElementById('components-table-demo-row-selection'));</span></code></pre></div>
</div>
<div class="code-box-meta markdown">
<div class="code-box-title">
<a href="#demo-row-selection">选择</a>
</div>
<p>第一列是联动的选择框。</p>
<span class="collapse anticon anticon-circle-o-right" unselectable="none" style="-webkit-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;"></span>
</div>
</div>
|
ant-design/09x.ant.design
|
components/table/demo/row-selection.html
|
HTML
|
mit
| 4,058
|
# Mailgun plug-in #
Plugin for playframwork 1.x to ease integration of mailgun emails solution.
## Installation ##
1. Add plugin play1-mailgun to your dependencies
2. Add the twoo following declarations to your application.conf file:
`mailgun.domain=your.mailgun.domain
mailgun.api.key=your_mailgun_key`
## Sending an email ##
Create an `MailgunSendForm` object and fill mandatory fields:
* from: `String` email adress of the sender
* to: `List<String>` list of email adresses of recipients
* subject: `String` subject of the mail
* text or html: `String` content of the email (fill at least one of the two fields)
### Static method ###
Once form object is initialized, you can directly use the static method to send the email:
```Promise<Boolean> isSent = MailgunSender.send(form);```
Sending will be done asynchronously (using Job.now() method invocation), form object has to be valid (usage of `@Valid`)
It is not mandatory to use the result of the call since job launch is done.
### Job instanciation ###
`MailgunSender` extends `Job` class, you can use it as any Job class. In this case, form object validation is not used and should be performed prior to invoke now method.
|
corwinAmbre/play1
|
Mailgun/README.md
|
Markdown
|
mit
| 1,191
|
<html><body>
<h4>Windows 10 x64 (18363.657)</h4><br>
<h2>_POP_POWER_SETTING_VALUES</h2>
<font face="arial"> +0x000 StructureSize : Uint4B<br>
+0x004 PopPolicy : <a href="./_SYSTEM_POWER_POLICY.html">_SYSTEM_POWER_POLICY</a><br>
+0x0ec CurrentAcDcPowerState : <a href="./SYSTEM_POWER_CONDITION.html">SYSTEM_POWER_CONDITION</a><br>
+0x0f0 AwayModeEnabled : UChar<br>
+0x0f1 AwayModeEngaged : UChar<br>
+0x0f2 AwayModePolicyAllowed : UChar<br>
+0x0f4 AwayModeIgnoreUserPresent : Int4B<br>
+0x0f8 AwayModeIgnoreAction : Int4B<br>
+0x0fc DisableFastS4 : UChar<br>
+0x0fd DisableStandbyStates : UChar<br>
+0x100 UnattendSleepTimeout : Uint4B<br>
+0x104 DiskIgnoreTime : Uint4B<br>
+0x108 DeviceIdlePolicy : Uint4B<br>
+0x10c VideoDimTimeout : Uint4B<br>
+0x110 VideoNormalBrightness : Uint4B<br>
+0x114 VideoDimBrightness : Uint4B<br>
+0x118 AlsOffset : Uint4B<br>
+0x11c AlsEnabled : Uint4B<br>
+0x120 EsBrightness : Uint4B<br>
+0x124 SwitchShutdownForced : UChar<br>
+0x128 SystemCoolingPolicy : Uint4B<br>
+0x12c MediaBufferingEngaged : UChar<br>
+0x12d AudioActivity : UChar<br>
+0x12e FullscreenVideoPlayback : UChar<br>
+0x130 EsBatteryThreshold : Uint4B<br>
+0x134 EsAggressive : UChar<br>
+0x135 EsUserAwaySetting : UChar<br>
+0x138 ConnectivityInStandby : Uint4B<br>
+0x13c DisconnectedStandbyMode : Uint4B<br>
+0x140 UserPresencePredictionEnabled : Uint4B<br>
+0x144 AirplaneModeEnabled : UChar<br>
+0x145 BluetoothDeviceCharging : UChar<br>
</font></body></html>
|
epikcraw/ggool
|
public/Windows 10 x64 (18363.657)/_POP_POWER_SETTING_VALUES.html
|
HTML
|
mit
| 1,639
|
---
layout: page
title: 留言
comments: yes
---
欢迎留言!
|
canonxu/canonxu.github.io
|
guestbook/index.md
|
Markdown
|
mit
| 73
|
<?php echo $this->getView('default_header', $data) ?>
<div class="container">
<div class="row">
<div class="col-lg-10 col-lg-offset-1 col-md-10 col-md-offset-1">
<?php foreach($data->collection as $key => $post): ?>
<div class="post-list-item">
<?php $newUrl = $this->getHeadlessPermalink($post->ID) ?>
<?php
$featImg = $this->getFeaturedImage($post->ID);
if(!empty($featImg))
echo "<div class=\"teaser-feat-img\"><a href=\"{$newUrl}\"><img src=\"{$featImg}\"><h3>{$post->post_title}</h3></a></div>";
?>
<p class="post-teaser">
<?php
if(empty($post->post_excerpt))
echo $this->getBodyExcerpt($post->post_content);
else
echo $post->post_excerpt;
?>
</p>
<div class="read-more"><a href="<?php echo $newUrl ?>">Read more...</a></div>
</div>
<?php endforeach ?>
</div>
</div>
</div>
<?php if (!empty($data->paging['pages']) && $data->paging['pages'] > 1): ?>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<nav>
<ul class="pagination pagination-lg">
<?php if($data->paging['previous'] !== null): ?>
<li>
<a href="<?php echo $data->url."?page=".$data->paging['previous'] ?>" aria-label="Previous Page">
<span aria-hidden="true">← Previous</span>
</a>
</li>
<?php endif ?>
<?php
for ($i = 1; $i <= $data->paging['pages']; $i++) {
if($i == $data->paging['page']) {
echo '<li class="active"><span>'.$i.' <span class="sr-only">(current)</span></span></li>';
} else {
$url = $data->url."?page=".$i;
echo '<li><a href="'.$url.'">'.$i.'</a></li>';
}
}
?>
<?php if($data->paging['next'] !== null): ?>
<li>
<a href="<?php echo $data->url."?page=".$data->paging['next'] ?>" aria-label="Next Page">
<span aria-hidden="true">Next →</span>
</a>
</li>
<?php endif ?>
</ul>
</nav>
</div>
</div>
</div>
<?php endif ?>
|
ArroyoLabs/erdiko-wordpress
|
src/views/post_list.php
|
PHP
|
mit
| 2,881
|
#!/usr/bin/env bash
# get the pwd of this executable
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# assume this executable is stored in the dotfiles directory
# run macOS native find and sed, they work differently than GNU flavors
# and more reliable than assuming GNU flavors are installed and in $PATH
# find looks for `.git` directories
# sed removes the dotfiles repo itself from the running & rm `/.git`
/usr/bin/find $DIR -name ".git" | \
/usr/bin/sed -E '/.*\.dotfiles\/\.git/d;s/\/\.git//' | \
while IFS= read -r line
do
git --git-dir="$line/.git" --work-tree="$line" checkout master
git --git-dir="$line/.git" --work-tree="$line" fetch --all
git --git-dir="$line/.git" --work-tree="$line" reset --hard origin/master
done
|
cameronmalek/dotfiles
|
update-git-submodules.sh
|
Shell
|
mit
| 761
|
<?php
/**
* ZfDebugModule. WebUI and Console commands for debugging ZF2 apps.
*
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @copyright 2016 Vítor Brandão <vitor@noiselabs.org>
*/
namespace Noiselabs\ZfDebugModuletest\Unit\Factory\Controller\Http;
use Noiselabs\ZfDebugModule\Controller\Http\IndexController;
use Noiselabs\ZfDebugModule\Factory\Controller\Http\IndexControllerFactory;
use PHPUnit_Framework_MockObject_MockObject;
use PHPUnit_Framework_TestCase;
use Zend\Mvc\Controller\ControllerManager;
use Zend\ServiceManager\ServiceManager;
class IndexControllerFactoryTest extends PHPUnit_Framework_TestCase
{
public function testCreateService()
{
/** @var ServiceManager|PHPUnit_Framework_MockObject_MockObject $serviceManager */
$serviceManager = $this
->getMockBuilder(ServiceManager::class)
->getMock();
/** @var ControllerManager|PHPUnit_Framework_MockObject_MockObject $controllerManager */
$controllerManager = $this
->getMockBuilder(ControllerManager::class)
->disableOriginalConstructor()
->getMock();
$controllerManager
->expects($this->any())
->method('getServiceLocator')
->will($this->returnValue($serviceManager));
$factory = new IndexControllerFactory();
$controller = $factory->createService($controllerManager);
$this->assertInstanceOf(IndexController::class, $controller);
}
public function testServiceNameIsDefined()
{
$this->assertTrue(defined(IndexControllerFactory::class . '::SERVICE_NAME'));
}
}
|
noiselabs/zf-debug-utils
|
test/Unit/Factory/Controller/Http/IndexControllerFactoryTest.php
|
PHP
|
mit
| 1,662
|
/*
* This file is included by vm.c
*/
#include "id_table.h"
#define METHOD_DEBUG 0
#if OPT_GLOBAL_METHOD_CACHE
#ifndef GLOBAL_METHOD_CACHE_SIZE
#define GLOBAL_METHOD_CACHE_SIZE 0x800
#endif
#define LSB_ONLY(x) ((x) & ~((x) - 1))
#define POWER_OF_2_P(x) ((x) == LSB_ONLY(x))
#if !POWER_OF_2_P(GLOBAL_METHOD_CACHE_SIZE)
# error GLOBAL_METHOD_CACHE_SIZE must be power of 2
#endif
#ifndef GLOBAL_METHOD_CACHE_MASK
#define GLOBAL_METHOD_CACHE_MASK (GLOBAL_METHOD_CACHE_SIZE-1)
#endif
#define GLOBAL_METHOD_CACHE_KEY(c,m) ((((c)>>3)^(m))&(global_method_cache.mask))
#define GLOBAL_METHOD_CACHE(c,m) (global_method_cache.entries + GLOBAL_METHOD_CACHE_KEY(c,m))
#else
#define GLOBAL_METHOD_CACHE(c,m) (rb_bug("global method cache disabled improperly"), NULL)
#endif
static int vm_redefinition_check_flag(VALUE klass);
static void rb_vm_check_redefinition_opt_method(const rb_method_entry_t *me, VALUE klass);
#define object_id idObject_id
#define added idMethod_added
#define singleton_added idSingleton_method_added
#define removed idMethod_removed
#define singleton_removed idSingleton_method_removed
#define undefined idMethod_undefined
#define singleton_undefined idSingleton_method_undefined
#define attached id__attached__
struct cache_entry {
rb_serial_t method_state;
rb_serial_t class_serial;
ID mid;
rb_method_entry_t* me;
VALUE defined_class;
};
#if OPT_GLOBAL_METHOD_CACHE
static struct {
unsigned int size;
unsigned int mask;
struct cache_entry *entries;
} global_method_cache = {
GLOBAL_METHOD_CACHE_SIZE,
GLOBAL_METHOD_CACHE_MASK,
};
#endif
#define ruby_running (GET_VM()->running)
/* int ruby_running = 0; */
static void
rb_class_clear_method_cache(VALUE klass, VALUE arg)
{
VALUE old_serial = *(rb_serial_t *)arg;
if (RCLASS_SERIAL(klass) > old_serial) {
return;
}
mjit_remove_class_serial(RCLASS_SERIAL(klass));
RCLASS_SERIAL(klass) = rb_next_class_serial();
if (BUILTIN_TYPE(klass) == T_ICLASS) {
struct rb_id_table *table = RCLASS_CALLABLE_M_TBL(klass);
if (table) {
rb_id_table_clear(table);
}
}
else {
VM_ASSERT(RCLASS_CALLABLE_M_TBL(klass) == 0);
}
rb_class_foreach_subclass(klass, rb_class_clear_method_cache, arg);
}
void
rb_clear_constant_cache(void)
{
INC_GLOBAL_CONSTANT_STATE();
}
void
rb_clear_method_cache_by_class(VALUE klass)
{
if (klass && klass != Qundef) {
int global = klass == rb_cBasicObject || klass == rb_cObject || klass == rb_mKernel;
RUBY_DTRACE_HOOK(METHOD_CACHE_CLEAR, (global ? "global" : rb_class2name(klass)));
if (global) {
INC_GLOBAL_METHOD_STATE();
}
else {
rb_serial_t old_serial = PREV_CLASS_SERIAL();
rb_class_clear_method_cache(klass, (VALUE)&old_serial);
}
}
if (klass == rb_mKernel) {
rb_subclass_entry_t *entry = RCLASS_EXT(klass)->subclasses;
for (; entry != NULL; entry = entry->next) {
struct rb_id_table *table = RCLASS_CALLABLE_M_TBL(entry->klass);
if (table)rb_id_table_clear(table);
}
}
}
VALUE
rb_f_notimplement(int argc, const VALUE *argv, VALUE obj, VALUE marker)
{
rb_notimplement();
UNREACHABLE_RETURN(Qnil);
}
static void
rb_define_notimplement_method_id(VALUE mod, ID id, rb_method_visibility_t visi)
{
rb_add_method(mod, id, VM_METHOD_TYPE_NOTIMPLEMENTED, (void *)1, visi);
}
void
rb_add_method_cfunc(VALUE klass, ID mid, VALUE (*func)(ANYARGS), int argc, rb_method_visibility_t visi)
{
if (argc < -2 || 15 < argc) rb_raise(rb_eArgError, "arity out of range: %d for -2..15", argc);
if (func != rb_f_notimplement) {
rb_method_cfunc_t opt;
opt.func = func;
opt.argc = argc;
rb_add_method(klass, mid, VM_METHOD_TYPE_CFUNC, &opt, visi);
}
else {
rb_define_notimplement_method_id(klass, mid, visi);
}
}
static void
rb_method_definition_release(rb_method_definition_t *def, int complemented)
{
if (def != NULL) {
const int alias_count = def->alias_count;
const int complemented_count = def->complemented_count;
VM_ASSERT(alias_count >= 0);
VM_ASSERT(complemented_count >= 0);
if (alias_count + complemented_count == 0) {
if (METHOD_DEBUG) fprintf(stderr, "-%p-%s:%d,%d (remove)\n", (void *)def,
rb_id2name(def->original_id), alias_count, complemented_count);
VM_ASSERT(def->type == VM_METHOD_TYPE_BMETHOD ? def->body.bmethod.hooks == NULL : TRUE);
xfree(def);
}
else {
if (complemented) def->complemented_count--;
else if (def->alias_count > 0) def->alias_count--;
if (METHOD_DEBUG) fprintf(stderr, "-%p-%s:%d->%d,%d->%d (dec)\n", (void *)def, rb_id2name(def->original_id),
alias_count, def->alias_count, complemented_count, def->complemented_count);
}
}
}
void
rb_free_method_entry(const rb_method_entry_t *me)
{
rb_method_definition_release(me->def, METHOD_ENTRY_COMPLEMENTED(me));
}
static inline rb_method_entry_t *search_method(VALUE klass, ID id, VALUE *defined_class_ptr);
extern int rb_method_definition_eq(const rb_method_definition_t *d1, const rb_method_definition_t *d2);
static inline rb_method_entry_t *
lookup_method_table(VALUE klass, ID id)
{
st_data_t body;
struct rb_id_table *m_tbl = RCLASS_M_TBL(klass);
if (rb_id_table_lookup(m_tbl, id, &body)) {
return (rb_method_entry_t *) body;
}
else {
return 0;
}
}
static VALUE
(*call_cfunc_invoker_func(int argc))(VALUE recv, int argc, const VALUE *, VALUE (*func)(ANYARGS))
{
switch (argc) {
case -2: return &call_cfunc_m2;
case -1: return &call_cfunc_m1;
case 0: return &call_cfunc_0;
case 1: return &call_cfunc_1;
case 2: return &call_cfunc_2;
case 3: return &call_cfunc_3;
case 4: return &call_cfunc_4;
case 5: return &call_cfunc_5;
case 6: return &call_cfunc_6;
case 7: return &call_cfunc_7;
case 8: return &call_cfunc_8;
case 9: return &call_cfunc_9;
case 10: return &call_cfunc_10;
case 11: return &call_cfunc_11;
case 12: return &call_cfunc_12;
case 13: return &call_cfunc_13;
case 14: return &call_cfunc_14;
case 15: return &call_cfunc_15;
default:
rb_bug("call_cfunc_func: unsupported length: %d", argc);
}
}
static void
setup_method_cfunc_struct(rb_method_cfunc_t *cfunc, VALUE (*func)(), int argc)
{
cfunc->func = func;
cfunc->argc = argc;
cfunc->invoker = call_cfunc_invoker_func(argc);
}
MJIT_FUNC_EXPORTED void
rb_method_definition_set(const rb_method_entry_t *me, rb_method_definition_t *def, void *opts)
{
*(rb_method_definition_t **)&me->def = def;
if (opts != NULL) {
switch (def->type) {
case VM_METHOD_TYPE_ISEQ:
{
rb_method_iseq_t *iseq_body = (rb_method_iseq_t *)opts;
rb_cref_t *method_cref, *cref = iseq_body->cref;
/* setup iseq first (before invoking GC) */
RB_OBJ_WRITE(me, &def->body.iseq.iseqptr, iseq_body->iseqptr);
if (0) vm_cref_dump("rb_method_definition_create", cref);
if (cref) {
method_cref = cref;
}
else {
method_cref = vm_cref_new_toplevel(GET_EC()); /* TODO: can we reuse? */
}
RB_OBJ_WRITE(me, &def->body.iseq.cref, method_cref);
return;
}
case VM_METHOD_TYPE_CFUNC:
{
rb_method_cfunc_t *cfunc = (rb_method_cfunc_t *)opts;
setup_method_cfunc_struct(UNALIGNED_MEMBER_PTR(def, body.cfunc), cfunc->func, cfunc->argc);
return;
}
case VM_METHOD_TYPE_ATTRSET:
case VM_METHOD_TYPE_IVAR:
{
const rb_execution_context_t *ec = GET_EC();
rb_control_frame_t *cfp;
int line;
def->body.attr.id = (ID)(VALUE)opts;
cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp);
if (cfp && (line = rb_vm_get_sourceline(cfp))) {
VALUE location = rb_ary_new3(2, rb_iseq_path(cfp->iseq), INT2FIX(line));
RB_OBJ_WRITE(me, &def->body.attr.location, rb_ary_freeze(location));
}
else {
VM_ASSERT(def->body.attr.location == 0);
}
return;
}
case VM_METHOD_TYPE_BMETHOD:
RB_OBJ_WRITE(me, &def->body.bmethod.proc, (VALUE)opts);
return;
case VM_METHOD_TYPE_NOTIMPLEMENTED:
setup_method_cfunc_struct(UNALIGNED_MEMBER_PTR(def, body.cfunc), rb_f_notimplement, -1);
return;
case VM_METHOD_TYPE_OPTIMIZED:
def->body.optimize_type = (enum method_optimized_type)opts;
return;
case VM_METHOD_TYPE_REFINED:
{
const rb_method_refined_t *refined = (rb_method_refined_t *)opts;
RB_OBJ_WRITE(me, &def->body.refined.orig_me, refined->orig_me);
RB_OBJ_WRITE(me, &def->body.refined.owner, refined->owner);
return;
}
case VM_METHOD_TYPE_ALIAS:
RB_OBJ_WRITE(me, &def->body.alias.original_me, (rb_method_entry_t *)opts);
return;
case VM_METHOD_TYPE_ZSUPER:
case VM_METHOD_TYPE_UNDEF:
case VM_METHOD_TYPE_MISSING:
return;
}
}
}
static void
method_definition_reset(const rb_method_entry_t *me)
{
rb_method_definition_t *def = me->def;
switch(def->type) {
case VM_METHOD_TYPE_ISEQ:
RB_OBJ_WRITTEN(me, Qundef, def->body.iseq.iseqptr);
RB_OBJ_WRITTEN(me, Qundef, def->body.iseq.cref);
break;
case VM_METHOD_TYPE_ATTRSET:
case VM_METHOD_TYPE_IVAR:
RB_OBJ_WRITTEN(me, Qundef, def->body.attr.location);
break;
case VM_METHOD_TYPE_BMETHOD:
RB_OBJ_WRITTEN(me, Qundef, def->body.bmethod.proc);
/* give up to check all in a list */
if (def->body.bmethod.hooks) rb_gc_writebarrier_remember((VALUE)me);
break;
case VM_METHOD_TYPE_REFINED:
RB_OBJ_WRITTEN(me, Qundef, def->body.refined.orig_me);
RB_OBJ_WRITTEN(me, Qundef, def->body.refined.owner);
break;
case VM_METHOD_TYPE_ALIAS:
RB_OBJ_WRITTEN(me, Qundef, def->body.alias.original_me);
break;
case VM_METHOD_TYPE_CFUNC:
case VM_METHOD_TYPE_ZSUPER:
case VM_METHOD_TYPE_MISSING:
case VM_METHOD_TYPE_OPTIMIZED:
case VM_METHOD_TYPE_UNDEF:
case VM_METHOD_TYPE_NOTIMPLEMENTED:
break;
}
}
MJIT_FUNC_EXPORTED rb_method_definition_t *
rb_method_definition_create(rb_method_type_t type, ID mid)
{
rb_method_definition_t *def;
def = ZALLOC(rb_method_definition_t);
def->type = type;
def->original_id = mid;
static uintptr_t method_serial = 1;
def->method_serial = method_serial++;
return def;
}
static rb_method_definition_t *
method_definition_addref(rb_method_definition_t *def)
{
def->alias_count++;
if (METHOD_DEBUG) fprintf(stderr, "+%p-%s:%d\n", (void *)def, rb_id2name(def->original_id), def->alias_count);
return def;
}
static rb_method_definition_t *
method_definition_addref_complement(rb_method_definition_t *def)
{
def->complemented_count++;
if (METHOD_DEBUG) fprintf(stderr, "+%p-%s:%d\n", (void *)def, rb_id2name(def->original_id), def->complemented_count);
return def;
}
static rb_method_entry_t *
rb_method_entry_alloc(ID called_id, VALUE owner, VALUE defined_class, const rb_method_definition_t *def)
{
rb_method_entry_t *me = (rb_method_entry_t *)rb_imemo_new(imemo_ment, (VALUE)def, (VALUE)called_id, owner, defined_class);
return me;
}
static VALUE
filter_defined_class(VALUE klass)
{
switch (BUILTIN_TYPE(klass)) {
case T_CLASS:
return klass;
case T_MODULE:
return 0;
case T_ICLASS:
break;
}
rb_bug("filter_defined_class: %s", rb_obj_info(klass));
}
rb_method_entry_t *
rb_method_entry_create(ID called_id, VALUE klass, rb_method_visibility_t visi, const rb_method_definition_t *def)
{
rb_method_entry_t *me = rb_method_entry_alloc(called_id, klass, filter_defined_class(klass), def);
METHOD_ENTRY_FLAGS_SET(me, visi, ruby_running ? FALSE : TRUE);
if (def != NULL) method_definition_reset(me);
return me;
}
const rb_method_entry_t *
rb_method_entry_clone(const rb_method_entry_t *src_me)
{
rb_method_entry_t *me = rb_method_entry_alloc(src_me->called_id, src_me->owner, src_me->defined_class,
method_definition_addref(src_me->def));
METHOD_ENTRY_FLAGS_COPY(me, src_me);
return me;
}
MJIT_FUNC_EXPORTED const rb_callable_method_entry_t *
rb_method_entry_complement_defined_class(const rb_method_entry_t *src_me, ID called_id, VALUE defined_class)
{
rb_method_definition_t *def = src_me->def;
rb_method_entry_t *me;
struct {
const struct rb_method_entry_struct *orig_me;
VALUE owner;
} refined = {0};
if (!src_me->defined_class &&
def->type == VM_METHOD_TYPE_REFINED &&
def->body.refined.orig_me) {
const rb_method_entry_t *orig_me =
rb_method_entry_clone(def->body.refined.orig_me);
RB_OBJ_WRITE((VALUE)orig_me, &orig_me->defined_class, defined_class);
refined.orig_me = orig_me;
refined.owner = orig_me->owner;
def = NULL;
}
else {
def = method_definition_addref_complement(def);
}
me = rb_method_entry_alloc(called_id, src_me->owner, defined_class, def);
METHOD_ENTRY_FLAGS_COPY(me, src_me);
METHOD_ENTRY_COMPLEMENTED_SET(me);
if (!def) {
def = rb_method_definition_create(VM_METHOD_TYPE_REFINED, called_id);
rb_method_definition_set(me, def, &refined);
}
VM_ASSERT(RB_TYPE_P(me->owner, T_MODULE));
return (rb_callable_method_entry_t *)me;
}
void
rb_method_entry_copy(rb_method_entry_t *dst, const rb_method_entry_t *src)
{
*(rb_method_definition_t **)&dst->def = method_definition_addref(src->def);
method_definition_reset(dst);
dst->called_id = src->called_id;
RB_OBJ_WRITE((VALUE)dst, &dst->owner, src->owner);
RB_OBJ_WRITE((VALUE)dst, &dst->defined_class, src->defined_class);
METHOD_ENTRY_FLAGS_COPY(dst, src);
}
static void
make_method_entry_refined(VALUE owner, rb_method_entry_t *me)
{
if (me->def->type == VM_METHOD_TYPE_REFINED) {
return;
}
else {
struct {
struct rb_method_entry_struct *orig_me;
VALUE owner;
} refined;
rb_method_definition_t *def;
rb_vm_check_redefinition_opt_method(me, me->owner);
refined.orig_me =
rb_method_entry_alloc(me->called_id, me->owner,
me->defined_class ?
me->defined_class : owner,
method_definition_addref(me->def));
METHOD_ENTRY_FLAGS_COPY(refined.orig_me, me);
refined.owner = owner;
def = rb_method_definition_create(VM_METHOD_TYPE_REFINED, me->called_id);
rb_method_definition_set(me, def, (void *)&refined);
METHOD_ENTRY_VISI_SET(me, METHOD_VISI_PUBLIC);
}
}
void
rb_add_refined_method_entry(VALUE refined_class, ID mid)
{
rb_method_entry_t *me = lookup_method_table(refined_class, mid);
if (me) {
make_method_entry_refined(refined_class, me);
rb_clear_method_cache_by_class(refined_class);
}
else {
rb_add_method(refined_class, mid, VM_METHOD_TYPE_REFINED, 0, METHOD_VISI_PUBLIC);
}
}
static void
check_override_opt_method_i(VALUE klass, VALUE arg)
{
ID mid = (ID)arg;
const rb_method_entry_t *me, *newme;
if (vm_redefinition_check_flag(klass)) {
me = lookup_method_table(RCLASS_ORIGIN(klass), mid);
if (me) {
newme = rb_method_entry(klass, mid);
if (newme != me) rb_vm_check_redefinition_opt_method(me, me->owner);
}
}
rb_class_foreach_subclass(klass, check_override_opt_method_i, (VALUE)mid);
}
static void
check_override_opt_method(VALUE klass, VALUE mid)
{
if (rb_vm_check_optimizable_mid(mid)) {
check_override_opt_method_i(klass, mid);
}
}
/*
* klass->method_table[mid] = method_entry(defined_class, visi, def)
*
* If def is given (!= NULL), then just use it and ignore original_id and otps.
* If not given, then make a new def with original_id and opts.
*/
static rb_method_entry_t *
rb_method_entry_make(VALUE klass, ID mid, VALUE defined_class, rb_method_visibility_t visi,
rb_method_type_t type, rb_method_definition_t *def, ID original_id, void *opts)
{
rb_method_entry_t *me;
struct rb_id_table *mtbl;
st_data_t data;
int make_refined = 0;
if (NIL_P(klass)) {
klass = rb_cObject;
}
if (!FL_TEST(klass, FL_SINGLETON) &&
type != VM_METHOD_TYPE_NOTIMPLEMENTED &&
type != VM_METHOD_TYPE_ZSUPER) {
switch (mid) {
case idInitialize:
case idInitialize_copy:
case idInitialize_clone:
case idInitialize_dup:
case idRespond_to_missing:
visi = METHOD_VISI_PRIVATE;
}
}
rb_class_modify_check(klass);
if (FL_TEST(klass, RMODULE_IS_REFINEMENT)) {
VALUE refined_class = rb_refinement_module_get_refined_class(klass);
rb_add_refined_method_entry(refined_class, mid);
}
if (type == VM_METHOD_TYPE_REFINED) {
rb_method_entry_t *old_me = lookup_method_table(RCLASS_ORIGIN(klass), mid);
if (old_me) rb_vm_check_redefinition_opt_method(old_me, klass);
}
else {
klass = RCLASS_ORIGIN(klass);
}
mtbl = RCLASS_M_TBL(klass);
/* check re-definition */
if (rb_id_table_lookup(mtbl, mid, &data)) {
rb_method_entry_t *old_me = (rb_method_entry_t *)data;
rb_method_definition_t *old_def = old_me->def;
if (rb_method_definition_eq(old_def, def)) return old_me;
rb_vm_check_redefinition_opt_method(old_me, klass);
if (old_def->type == VM_METHOD_TYPE_REFINED) make_refined = 1;
if (RTEST(ruby_verbose) &&
type != VM_METHOD_TYPE_UNDEF &&
(old_def->alias_count == 0) &&
!make_refined &&
old_def->type != VM_METHOD_TYPE_UNDEF &&
old_def->type != VM_METHOD_TYPE_ZSUPER &&
old_def->type != VM_METHOD_TYPE_ALIAS) {
const rb_iseq_t *iseq = 0;
rb_warning("method redefined; discarding old %"PRIsVALUE, rb_id2str(mid));
switch (old_def->type) {
case VM_METHOD_TYPE_ISEQ:
iseq = def_iseq_ptr(old_def);
break;
case VM_METHOD_TYPE_BMETHOD:
iseq = rb_proc_get_iseq(old_def->body.bmethod.proc, 0);
break;
default:
break;
}
if (iseq) {
rb_compile_warning(RSTRING_PTR(rb_iseq_path(iseq)),
FIX2INT(iseq->body->location.first_lineno),
"previous definition of %"PRIsVALUE" was here",
rb_id2str(old_def->original_id));
}
}
}
/* create method entry */
me = rb_method_entry_create(mid, defined_class, visi, NULL);
if (def == NULL) def = rb_method_definition_create(type, original_id);
rb_method_definition_set(me, def, opts);
rb_clear_method_cache_by_class(klass);
/* check mid */
if (klass == rb_cObject) {
switch (mid) {
case idInitialize:
case idRespond_to_missing:
case idMethodMissing:
case idRespond_to:
rb_warn("redefining Object#%s may cause infinite loop", rb_id2name(mid));
}
}
/* check mid */
if (mid == object_id || mid == id__send__) {
if (type == VM_METHOD_TYPE_ISEQ && search_method(klass, mid, 0)) {
rb_warn("redefining `%s' may cause serious problems", rb_id2name(mid));
}
}
if (make_refined) {
make_method_entry_refined(klass, me);
}
rb_id_table_insert(mtbl, mid, (VALUE)me);
RB_OBJ_WRITTEN(klass, Qundef, (VALUE)me);
VM_ASSERT(me->def != NULL);
/* check optimized method override by a prepended module */
if (RB_TYPE_P(klass, T_MODULE)) {
check_override_opt_method(klass, (VALUE)mid);
}
return me;
}
#define CALL_METHOD_HOOK(klass, hook, mid) do { \
const VALUE arg = ID2SYM(mid); \
VALUE recv_class = (klass); \
ID hook_id = (hook); \
if (FL_TEST((klass), FL_SINGLETON)) { \
recv_class = rb_ivar_get((klass), attached); \
hook_id = singleton_##hook; \
} \
rb_funcallv(recv_class, hook_id, 1, &arg); \
} while (0)
static void
method_added(VALUE klass, ID mid)
{
if (ruby_running) {
CALL_METHOD_HOOK(klass, added, mid);
}
}
void
rb_add_method(VALUE klass, ID mid, rb_method_type_t type, void *opts, rb_method_visibility_t visi)
{
rb_method_entry_make(klass, mid, klass, visi, type, NULL, mid, opts);
if (type != VM_METHOD_TYPE_UNDEF && type != VM_METHOD_TYPE_REFINED) {
method_added(klass, mid);
}
}
MJIT_FUNC_EXPORTED void
rb_add_method_iseq(VALUE klass, ID mid, const rb_iseq_t *iseq, rb_cref_t *cref, rb_method_visibility_t visi)
{
struct { /* should be same fields with rb_method_iseq_struct */
const rb_iseq_t *iseqptr;
rb_cref_t *cref;
} iseq_body;
iseq_body.iseqptr = iseq;
iseq_body.cref = cref;
rb_add_method(klass, mid, VM_METHOD_TYPE_ISEQ, &iseq_body, visi);
}
static rb_method_entry_t *
method_entry_set(VALUE klass, ID mid, const rb_method_entry_t *me,
rb_method_visibility_t visi, VALUE defined_class)
{
rb_method_entry_t *newme = rb_method_entry_make(klass, mid, defined_class, visi,
me->def->type, method_definition_addref(me->def), 0, NULL);
method_added(klass, mid);
return newme;
}
rb_method_entry_t *
rb_method_entry_set(VALUE klass, ID mid, const rb_method_entry_t *me, rb_method_visibility_t visi)
{
return method_entry_set(klass, mid, me, visi, klass);
}
#define UNDEF_ALLOC_FUNC ((rb_alloc_func_t)-1)
void
rb_define_alloc_func(VALUE klass, VALUE (*func)(VALUE))
{
Check_Type(klass, T_CLASS);
RCLASS_EXT(klass)->allocator = func;
}
void
rb_undef_alloc_func(VALUE klass)
{
rb_define_alloc_func(klass, UNDEF_ALLOC_FUNC);
}
rb_alloc_func_t
rb_get_alloc_func(VALUE klass)
{
Check_Type(klass, T_CLASS);
for (; klass; klass = RCLASS_SUPER(klass)) {
rb_alloc_func_t allocator = RCLASS_EXT(klass)->allocator;
if (allocator == UNDEF_ALLOC_FUNC) break;
if (allocator) return allocator;
}
return 0;
}
static inline rb_method_entry_t*
search_method(VALUE klass, ID id, VALUE *defined_class_ptr)
{
rb_method_entry_t *me;
for (; klass; klass = RCLASS_SUPER(klass)) {
RB_DEBUG_COUNTER_INC(mc_search_super);
if ((me = lookup_method_table(klass, id)) != 0) break;
}
if (defined_class_ptr)
*defined_class_ptr = klass;
return me;
}
const rb_method_entry_t *
rb_method_entry_at(VALUE klass, ID id)
{
return lookup_method_table(klass, id);
}
/*
* search method entry without the method cache.
*
* if you need method entry with method cache (normal case), use
* rb_method_entry() simply.
*/
static rb_method_entry_t *
method_entry_get_without_cache(VALUE klass, ID id,
VALUE *defined_class_ptr)
{
VALUE defined_class;
rb_method_entry_t *me = search_method(klass, id, &defined_class);
if (ruby_running) {
if (OPT_GLOBAL_METHOD_CACHE) {
struct cache_entry *ent;
ent = GLOBAL_METHOD_CACHE(klass, id);
ent->class_serial = RCLASS_SERIAL(klass);
ent->method_state = GET_GLOBAL_METHOD_STATE();
ent->defined_class = defined_class;
ent->mid = id;
if (UNDEFINED_METHOD_ENTRY_P(me)) {
me = ent->me = NULL;
}
else {
ent->me = me;
}
}
else if (UNDEFINED_METHOD_ENTRY_P(me)) {
me = NULL;
}
}
else if (UNDEFINED_METHOD_ENTRY_P(me)) {
me = NULL;
}
if (defined_class_ptr)
*defined_class_ptr = defined_class;
return me;
}
static void
verify_method_cache(VALUE klass, ID id, VALUE defined_class, rb_method_entry_t *me)
{
if (!VM_DEBUG_VERIFY_METHOD_CACHE) return;
VALUE actual_defined_class;
rb_method_entry_t *actual_me =
method_entry_get_without_cache(klass, id, &actual_defined_class);
if (me != actual_me || defined_class != actual_defined_class) {
rb_bug("method cache verification failed");
}
}
static rb_method_entry_t *
method_entry_get(VALUE klass, ID id, VALUE *defined_class_ptr)
{
struct cache_entry *ent;
if (!OPT_GLOBAL_METHOD_CACHE) goto nocache;
ent = GLOBAL_METHOD_CACHE(klass, id);
if (ent->method_state == GET_GLOBAL_METHOD_STATE() &&
ent->class_serial == RCLASS_SERIAL(klass) &&
ent->mid == id) {
verify_method_cache(klass, id, ent->defined_class, ent->me);
if (defined_class_ptr) *defined_class_ptr = ent->defined_class;
RB_DEBUG_COUNTER_INC(mc_global_hit);
return ent->me;
}
nocache:
RB_DEBUG_COUNTER_INC(mc_global_miss);
return method_entry_get_without_cache(klass, id, defined_class_ptr);
}
MJIT_FUNC_EXPORTED const rb_method_entry_t *
rb_method_entry(VALUE klass, ID id)
{
return method_entry_get(klass, id, NULL);
}
static const rb_callable_method_entry_t *
prepare_callable_method_entry(VALUE defined_class, ID id, const rb_method_entry_t *me)
{
struct rb_id_table *mtbl;
const rb_callable_method_entry_t *cme;
if (me && me->defined_class == 0) {
RB_DEBUG_COUNTER_INC(mc_cme_complement);
VM_ASSERT(RB_TYPE_P(defined_class, T_ICLASS) || RB_TYPE_P(defined_class, T_MODULE));
VM_ASSERT(me->defined_class == 0);
mtbl = RCLASS_CALLABLE_M_TBL(defined_class);
if (mtbl && rb_id_table_lookup(mtbl, id, (VALUE *)&me)) {
RB_DEBUG_COUNTER_INC(mc_cme_complement_hit);
cme = (rb_callable_method_entry_t *)me;
VM_ASSERT(callable_method_entry_p(cme));
}
else {
if (!mtbl) {
mtbl = RCLASS_EXT(defined_class)->callable_m_tbl = rb_id_table_create(0);
}
cme = rb_method_entry_complement_defined_class(me, me->called_id, defined_class);
rb_id_table_insert(mtbl, id, (VALUE)cme);
VM_ASSERT(callable_method_entry_p(cme));
}
}
else {
cme = (const rb_callable_method_entry_t *)me;
VM_ASSERT(callable_method_entry_p(cme));
}
return cme;
}
MJIT_FUNC_EXPORTED const rb_callable_method_entry_t *
rb_callable_method_entry(VALUE klass, ID id)
{
VALUE defined_class;
rb_method_entry_t *me = method_entry_get(klass, id, &defined_class);
return prepare_callable_method_entry(defined_class, id, me);
}
static const rb_method_entry_t *resolve_refined_method(VALUE refinements, const rb_method_entry_t *me, VALUE *defined_class_ptr);
static const rb_method_entry_t *
method_entry_resolve_refinement(VALUE klass, ID id, int with_refinement, VALUE *defined_class_ptr)
{
const rb_method_entry_t *me = method_entry_get(klass, id, defined_class_ptr);
if (me) {
if (me->def->type == VM_METHOD_TYPE_REFINED) {
if (with_refinement) {
const rb_cref_t *cref = rb_vm_cref();
VALUE refinements = cref ? CREF_REFINEMENTS(cref) : Qnil;
me = resolve_refined_method(refinements, me, defined_class_ptr);
}
else {
me = resolve_refined_method(Qnil, me, defined_class_ptr);
}
if (UNDEFINED_METHOD_ENTRY_P(me)) me = NULL;
}
}
return me;
}
const rb_method_entry_t *
rb_method_entry_with_refinements(VALUE klass, ID id, VALUE *defined_class_ptr)
{
return method_entry_resolve_refinement(klass, id, TRUE, defined_class_ptr);
}
MJIT_FUNC_EXPORTED const rb_callable_method_entry_t *
rb_callable_method_entry_with_refinements(VALUE klass, ID id, VALUE *defined_class_ptr)
{
VALUE defined_class, *dcp = defined_class_ptr ? defined_class_ptr : &defined_class;
const rb_method_entry_t *me = method_entry_resolve_refinement(klass, id, TRUE, dcp);
return prepare_callable_method_entry(*dcp, id, me);
}
const rb_method_entry_t *
rb_method_entry_without_refinements(VALUE klass, ID id, VALUE *defined_class_ptr)
{
return method_entry_resolve_refinement(klass, id, FALSE, defined_class_ptr);
}
MJIT_FUNC_EXPORTED const rb_callable_method_entry_t *
rb_callable_method_entry_without_refinements(VALUE klass, ID id, VALUE *defined_class_ptr)
{
VALUE defined_class, *dcp = defined_class_ptr ? defined_class_ptr : &defined_class;
const rb_method_entry_t *me = method_entry_resolve_refinement(klass, id, FALSE, dcp);
return prepare_callable_method_entry(*dcp, id, me);
}
static const rb_method_entry_t *
resolve_refined_method(VALUE refinements, const rb_method_entry_t *me, VALUE *defined_class_ptr)
{
while (me && me->def->type == VM_METHOD_TYPE_REFINED) {
VALUE refinement;
const rb_method_entry_t *tmp_me;
VALUE super;
refinement = find_refinement(refinements, me->owner);
if (!NIL_P(refinement)) {
tmp_me = method_entry_get(refinement, me->called_id, defined_class_ptr);
if (tmp_me && tmp_me->def->type != VM_METHOD_TYPE_REFINED) {
return tmp_me;
}
}
tmp_me = me->def->body.refined.orig_me;
if (tmp_me) {
if (defined_class_ptr) *defined_class_ptr = tmp_me->defined_class;
return tmp_me;
}
super = RCLASS_SUPER(me->owner);
if (!super) {
return 0;
}
me = method_entry_get(super, me->called_id, defined_class_ptr);
}
return me;
}
const rb_method_entry_t *
rb_resolve_refined_method(VALUE refinements, const rb_method_entry_t *me)
{
return resolve_refined_method(refinements, me, NULL);
}
MJIT_FUNC_EXPORTED
const rb_callable_method_entry_t *
rb_resolve_refined_method_callable(VALUE refinements, const rb_callable_method_entry_t *me)
{
VALUE defined_class = me->defined_class;
const rb_method_entry_t *resolved_me = resolve_refined_method(refinements, (const rb_method_entry_t *)me, &defined_class);
if (resolved_me && resolved_me->defined_class == 0) {
return rb_method_entry_complement_defined_class(resolved_me, me->called_id, defined_class);
}
else {
return (const rb_callable_method_entry_t *)resolved_me;
}
}
static void
remove_method(VALUE klass, ID mid)
{
VALUE data;
rb_method_entry_t *me = 0;
VALUE self = klass;
klass = RCLASS_ORIGIN(klass);
rb_class_modify_check(klass);
if (mid == object_id || mid == id__send__ || mid == idInitialize) {
rb_warn("removing `%s' may cause serious problems", rb_id2name(mid));
}
if (!rb_id_table_lookup(RCLASS_M_TBL(klass), mid, &data) ||
!(me = (rb_method_entry_t *)data) ||
(!me->def || me->def->type == VM_METHOD_TYPE_UNDEF) ||
UNDEFINED_REFINED_METHOD_P(me->def)) {
rb_name_err_raise("method `%1$s' not defined in %2$s",
klass, ID2SYM(mid));
}
rb_id_table_delete(RCLASS_M_TBL(klass), mid);
rb_vm_check_redefinition_opt_method(me, klass);
rb_clear_method_cache_by_class(klass);
if (me->def->type == VM_METHOD_TYPE_REFINED) {
rb_add_refined_method_entry(klass, mid);
}
CALL_METHOD_HOOK(self, removed, mid);
}
void
rb_remove_method_id(VALUE klass, ID mid)
{
remove_method(klass, mid);
}
void
rb_remove_method(VALUE klass, const char *name)
{
remove_method(klass, rb_intern(name));
}
/*
* call-seq:
* remove_method(symbol) -> self
* remove_method(string) -> self
*
* Removes the method identified by _symbol_ from the current
* class. For an example, see Module#undef_method.
* String arguments are converted to symbols.
*/
static VALUE
rb_mod_remove_method(int argc, VALUE *argv, VALUE mod)
{
int i;
for (i = 0; i < argc; i++) {
VALUE v = argv[i];
ID id = rb_check_id(&v);
if (!id) {
rb_name_err_raise("method `%1$s' not defined in %2$s",
mod, v);
}
remove_method(mod, id);
}
return mod;
}
static void
rb_export_method(VALUE klass, ID name, rb_method_visibility_t visi)
{
rb_method_entry_t *me;
VALUE defined_class;
VALUE origin_class = RCLASS_ORIGIN(klass);
me = search_method(origin_class, name, &defined_class);
if (!me && RB_TYPE_P(klass, T_MODULE)) {
me = search_method(rb_cObject, name, &defined_class);
}
if (UNDEFINED_METHOD_ENTRY_P(me) ||
UNDEFINED_REFINED_METHOD_P(me->def)) {
rb_print_undef(klass, name, METHOD_VISI_UNDEF);
}
if (METHOD_ENTRY_VISI(me) != visi) {
rb_vm_check_redefinition_opt_method(me, klass);
if (klass == defined_class || origin_class == defined_class) {
METHOD_ENTRY_VISI_SET(me, visi);
if (me->def->type == VM_METHOD_TYPE_REFINED && me->def->body.refined.orig_me) {
METHOD_ENTRY_VISI_SET((rb_method_entry_t *)me->def->body.refined.orig_me, visi);
}
rb_clear_method_cache_by_class(klass);
}
else {
rb_add_method(klass, name, VM_METHOD_TYPE_ZSUPER, 0, visi);
}
}
}
#define BOUND_PRIVATE 0x01
#define BOUND_RESPONDS 0x02
int
rb_method_boundp(VALUE klass, ID id, int ex)
{
const rb_method_entry_t *me;
if (ex & BOUND_RESPONDS) {
me = method_entry_resolve_refinement(klass, id, TRUE, NULL);
}
else {
me = rb_method_entry_without_refinements(klass, id, NULL);
}
if (me != 0) {
if ((ex & ~BOUND_RESPONDS) &&
((METHOD_ENTRY_VISI(me) == METHOD_VISI_PRIVATE) ||
((ex & BOUND_RESPONDS) && (METHOD_ENTRY_VISI(me) == METHOD_VISI_PROTECTED)))) {
return 0;
}
if (me->def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) {
if (ex & BOUND_RESPONDS) return 2;
return 0;
}
return 1;
}
return 0;
}
static void
vm_cref_set_visibility(rb_method_visibility_t method_visi, int module_func)
{
rb_scope_visibility_t *scope_visi = (rb_scope_visibility_t *)&rb_vm_cref()->scope_visi;
scope_visi->method_visi = method_visi;
scope_visi->module_func = module_func;
}
void
rb_scope_visibility_set(rb_method_visibility_t visi)
{
vm_cref_set_visibility(visi, FALSE);
}
static void
scope_visibility_check(void)
{
/* Check for public/protected/private/module_function called inside a method */
rb_control_frame_t *cfp = rb_current_execution_context()->cfp+1;
if (cfp && cfp->iseq && cfp->iseq->body->type == ISEQ_TYPE_METHOD) {
rb_warn("calling %s without arguments inside a method may not have the intended effect",
rb_id2name(rb_frame_this_func()));
}
}
static void
rb_scope_module_func_set(void)
{
scope_visibility_check();
vm_cref_set_visibility(METHOD_VISI_PRIVATE, TRUE);
}
const rb_cref_t *rb_vm_cref_in_context(VALUE self, VALUE cbase);
void
rb_attr(VALUE klass, ID id, int read, int write, int ex)
{
ID attriv;
rb_method_visibility_t visi;
const rb_execution_context_t *ec = GET_EC();
const rb_cref_t *cref = rb_vm_cref_in_context(klass, klass);
if (!ex || !cref) {
visi = METHOD_VISI_PUBLIC;
}
else {
switch (vm_scope_visibility_get(ec)) {
case METHOD_VISI_PRIVATE:
if (vm_scope_module_func_check(ec)) {
rb_warning("attribute accessor as module_function");
}
visi = METHOD_VISI_PRIVATE;
break;
case METHOD_VISI_PROTECTED:
visi = METHOD_VISI_PROTECTED;
break;
default:
visi = METHOD_VISI_PUBLIC;
break;
}
}
attriv = rb_intern_str(rb_sprintf("@%"PRIsVALUE, rb_id2str(id)));
if (read) {
rb_add_method(klass, id, VM_METHOD_TYPE_IVAR, (void *)attriv, visi);
}
if (write) {
rb_add_method(klass, rb_id_attrset(id), VM_METHOD_TYPE_ATTRSET, (void *)attriv, visi);
}
}
void
rb_undef(VALUE klass, ID id)
{
const rb_method_entry_t *me;
if (NIL_P(klass)) {
rb_raise(rb_eTypeError, "no class to undef method");
}
rb_class_modify_check(klass);
if (id == object_id || id == id__send__ || id == idInitialize) {
rb_warn("undefining `%s' may cause serious problems", rb_id2name(id));
}
me = search_method(klass, id, 0);
if (me && me->def->type == VM_METHOD_TYPE_REFINED) {
me = rb_resolve_refined_method(Qnil, me);
}
if (UNDEFINED_METHOD_ENTRY_P(me) ||
UNDEFINED_REFINED_METHOD_P(me->def)) {
rb_method_name_error(klass, rb_id2str(id));
}
rb_add_method(klass, id, VM_METHOD_TYPE_UNDEF, 0, METHOD_VISI_PUBLIC);
CALL_METHOD_HOOK(klass, undefined, id);
}
/*
* call-seq:
* undef_method(symbol) -> self
* undef_method(string) -> self
*
* Prevents the current class from responding to calls to the named
* method. Contrast this with <code>remove_method</code>, which deletes
* the method from the particular class; Ruby will still search
* superclasses and mixed-in modules for a possible receiver.
* String arguments are converted to symbols.
*
* class Parent
* def hello
* puts "In parent"
* end
* end
* class Child < Parent
* def hello
* puts "In child"
* end
* end
*
*
* c = Child.new
* c.hello
*
*
* class Child
* remove_method :hello # remove from child, still in parent
* end
* c.hello
*
*
* class Child
* undef_method :hello # prevent any calls to 'hello'
* end
* c.hello
*
* <em>produces:</em>
*
* In child
* In parent
* prog.rb:23: undefined method `hello' for #<Child:0x401b3bb4> (NoMethodError)
*/
static VALUE
rb_mod_undef_method(int argc, VALUE *argv, VALUE mod)
{
int i;
for (i = 0; i < argc; i++) {
VALUE v = argv[i];
ID id = rb_check_id(&v);
if (!id) {
rb_method_name_error(mod, v);
}
rb_undef(mod, id);
}
return mod;
}
static rb_method_visibility_t
check_definition_visibility(VALUE mod, int argc, VALUE *argv)
{
const rb_method_entry_t *me;
VALUE mid, include_super, lookup_mod = mod;
int inc_super;
ID id;
rb_scan_args(argc, argv, "11", &mid, &include_super);
id = rb_check_id(&mid);
if (!id) return METHOD_VISI_UNDEF;
if (argc == 1) {
inc_super = 1;
}
else {
inc_super = RTEST(include_super);
if (!inc_super) {
lookup_mod = RCLASS_ORIGIN(mod);
}
}
me = rb_method_entry_without_refinements(lookup_mod, id, NULL);
if (me) {
if (me->def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) return METHOD_VISI_UNDEF;
if (!inc_super && me->owner != mod) return METHOD_VISI_UNDEF;
return METHOD_ENTRY_VISI(me);
}
return METHOD_VISI_UNDEF;
}
/*
* call-seq:
* mod.method_defined?(symbol, inherit=true) -> true or false
* mod.method_defined?(string, inherit=true) -> true or false
*
* Returns +true+ if the named method is defined by
* _mod_. If _inherit_ is set, the lookup will also search _mod_'s
* ancestors. Public and protected methods are matched.
* String arguments are converted to symbols.
*
* module A
* def method1() end
* def protected_method1() end
* protected :protected_method1
* end
* class B
* def method2() end
* def private_method2() end
* private :private_method2
* end
* class C < B
* include A
* def method3() end
* end
*
* A.method_defined? :method1 #=> true
* C.method_defined? "method1" #=> true
* C.method_defined? "method2" #=> true
* C.method_defined? "method2", true #=> true
* C.method_defined? "method2", false #=> false
* C.method_defined? "method3" #=> true
* C.method_defined? "protected_method1" #=> true
* C.method_defined? "method4" #=> false
* C.method_defined? "private_method2" #=> false
*/
static VALUE
rb_mod_method_defined(int argc, VALUE *argv, VALUE mod)
{
rb_method_visibility_t visi = check_definition_visibility(mod, argc, argv);
return (visi == METHOD_VISI_PUBLIC || visi == METHOD_VISI_PROTECTED) ? Qtrue : Qfalse;
}
static VALUE
check_definition(VALUE mod, int argc, VALUE *argv, rb_method_visibility_t visi)
{
return (check_definition_visibility(mod, argc, argv) == visi) ? Qtrue : Qfalse;
}
/*
* call-seq:
* mod.public_method_defined?(symbol, inherit=true) -> true or false
* mod.public_method_defined?(string, inherit=true) -> true or false
*
* Returns +true+ if the named public method is defined by
* _mod_. If _inherit_ is set, the lookup will also search _mod_'s
* ancestors.
* String arguments are converted to symbols.
*
* module A
* def method1() end
* end
* class B
* protected
* def method2() end
* end
* class C < B
* include A
* def method3() end
* end
*
* A.method_defined? :method1 #=> true
* C.public_method_defined? "method1" #=> true
* C.public_method_defined? "method1", true #=> true
* C.public_method_defined? "method1", false #=> true
* C.public_method_defined? "method2" #=> false
* C.method_defined? "method2" #=> true
*/
static VALUE
rb_mod_public_method_defined(int argc, VALUE *argv, VALUE mod)
{
return check_definition(mod, argc, argv, METHOD_VISI_PUBLIC);
}
/*
* call-seq:
* mod.private_method_defined?(symbol, inherit=true) -> true or false
* mod.private_method_defined?(string, inherit=true) -> true or false
*
* Returns +true+ if the named private method is defined by
* _mod_. If _inherit_ is set, the lookup will also search _mod_'s
* ancestors.
* String arguments are converted to symbols.
*
* module A
* def method1() end
* end
* class B
* private
* def method2() end
* end
* class C < B
* include A
* def method3() end
* end
*
* A.method_defined? :method1 #=> true
* C.private_method_defined? "method1" #=> false
* C.private_method_defined? "method2" #=> true
* C.private_method_defined? "method2", true #=> true
* C.private_method_defined? "method2", false #=> false
* C.method_defined? "method2" #=> false
*/
static VALUE
rb_mod_private_method_defined(int argc, VALUE *argv, VALUE mod)
{
return check_definition(mod, argc, argv, METHOD_VISI_PRIVATE);
}
/*
* call-seq:
* mod.protected_method_defined?(symbol, inherit=true) -> true or false
* mod.protected_method_defined?(string, inherit=true) -> true or false
*
* Returns +true+ if the named protected method is defined
* _mod_. If _inherit_ is set, the lookup will also search _mod_'s
* ancestors.
* String arguments are converted to symbols.
*
* module A
* def method1() end
* end
* class B
* protected
* def method2() end
* end
* class C < B
* include A
* def method3() end
* end
*
* A.method_defined? :method1 #=> true
* C.protected_method_defined? "method1" #=> false
* C.protected_method_defined? "method2" #=> true
* C.protected_method_defined? "method2", true #=> true
* C.protected_method_defined? "method2", false #=> false
* C.method_defined? "method2" #=> true
*/
static VALUE
rb_mod_protected_method_defined(int argc, VALUE *argv, VALUE mod)
{
return check_definition(mod, argc, argv, METHOD_VISI_PROTECTED);
}
int
rb_method_entry_eq(const rb_method_entry_t *m1, const rb_method_entry_t *m2)
{
return rb_method_definition_eq(m1->def, m2->def);
}
static const rb_method_definition_t *
original_method_definition(const rb_method_definition_t *def)
{
again:
if (def) {
switch (def->type) {
case VM_METHOD_TYPE_REFINED:
if (def->body.refined.orig_me) {
def = def->body.refined.orig_me->def;
goto again;
}
break;
case VM_METHOD_TYPE_ALIAS:
def = def->body.alias.original_me->def;
goto again;
default:
break;
}
}
return def;
}
MJIT_FUNC_EXPORTED int
rb_method_definition_eq(const rb_method_definition_t *d1, const rb_method_definition_t *d2)
{
d1 = original_method_definition(d1);
d2 = original_method_definition(d2);
if (d1 == d2) return 1;
if (!d1 || !d2) return 0;
if (d1->type != d2->type) return 0;
switch (d1->type) {
case VM_METHOD_TYPE_ISEQ:
return d1->body.iseq.iseqptr == d2->body.iseq.iseqptr;
case VM_METHOD_TYPE_CFUNC:
return
d1->body.cfunc.func == d2->body.cfunc.func &&
d1->body.cfunc.argc == d2->body.cfunc.argc;
case VM_METHOD_TYPE_ATTRSET:
case VM_METHOD_TYPE_IVAR:
return d1->body.attr.id == d2->body.attr.id;
case VM_METHOD_TYPE_BMETHOD:
return RTEST(rb_equal(d1->body.bmethod.proc, d2->body.bmethod.proc));
case VM_METHOD_TYPE_MISSING:
return d1->original_id == d2->original_id;
case VM_METHOD_TYPE_ZSUPER:
case VM_METHOD_TYPE_NOTIMPLEMENTED:
case VM_METHOD_TYPE_UNDEF:
return 1;
case VM_METHOD_TYPE_OPTIMIZED:
return d1->body.optimize_type == d2->body.optimize_type;
case VM_METHOD_TYPE_REFINED:
case VM_METHOD_TYPE_ALIAS:
break;
}
rb_bug("rb_method_definition_eq: unsupported type: %d\n", d1->type);
}
static st_index_t
rb_hash_method_definition(st_index_t hash, const rb_method_definition_t *def)
{
hash = rb_hash_uint(hash, def->type);
def = original_method_definition(def);
if (!def) return hash;
switch (def->type) {
case VM_METHOD_TYPE_ISEQ:
return rb_hash_uint(hash, (st_index_t)def->body.iseq.iseqptr);
case VM_METHOD_TYPE_CFUNC:
hash = rb_hash_uint(hash, (st_index_t)def->body.cfunc.func);
return rb_hash_uint(hash, def->body.cfunc.argc);
case VM_METHOD_TYPE_ATTRSET:
case VM_METHOD_TYPE_IVAR:
return rb_hash_uint(hash, def->body.attr.id);
case VM_METHOD_TYPE_BMETHOD:
return rb_hash_proc(hash, def->body.bmethod.proc);
case VM_METHOD_TYPE_MISSING:
return rb_hash_uint(hash, def->original_id);
case VM_METHOD_TYPE_ZSUPER:
case VM_METHOD_TYPE_NOTIMPLEMENTED:
case VM_METHOD_TYPE_UNDEF:
return hash;
case VM_METHOD_TYPE_OPTIMIZED:
return rb_hash_uint(hash, def->body.optimize_type);
case VM_METHOD_TYPE_REFINED:
case VM_METHOD_TYPE_ALIAS:
break; /* unreachable */
}
rb_bug("rb_hash_method_definition: unsupported method type (%d)\n", def->type);
}
st_index_t
rb_hash_method_entry(st_index_t hash, const rb_method_entry_t *me)
{
return rb_hash_method_definition(hash, me->def);
}
void
rb_alias(VALUE klass, ID alias_name, ID original_name)
{
const VALUE target_klass = klass;
VALUE defined_class;
const rb_method_entry_t *orig_me;
rb_method_visibility_t visi = METHOD_VISI_UNDEF;
if (NIL_P(klass)) {
rb_raise(rb_eTypeError, "no class to make alias");
}
rb_class_modify_check(klass);
again:
orig_me = search_method(klass, original_name, &defined_class);
if (orig_me && orig_me->def->type == VM_METHOD_TYPE_REFINED) {
orig_me = rb_resolve_refined_method(Qnil, orig_me);
}
if (UNDEFINED_METHOD_ENTRY_P(orig_me) ||
UNDEFINED_REFINED_METHOD_P(orig_me->def)) {
if ((!RB_TYPE_P(klass, T_MODULE)) ||
(orig_me = search_method(rb_cObject, original_name, &defined_class),
UNDEFINED_METHOD_ENTRY_P(orig_me))) {
rb_print_undef(klass, original_name, METHOD_VISI_UNDEF);
}
}
if (orig_me->def->type == VM_METHOD_TYPE_ZSUPER) {
klass = RCLASS_SUPER(klass);
original_name = orig_me->def->original_id;
visi = METHOD_ENTRY_VISI(orig_me);
goto again;
}
if (visi == METHOD_VISI_UNDEF) visi = METHOD_ENTRY_VISI(orig_me);
if (orig_me->defined_class == 0) {
rb_method_entry_make(target_klass, alias_name, target_klass, visi,
VM_METHOD_TYPE_ALIAS, NULL, orig_me->called_id,
(void *)rb_method_entry_clone(orig_me));
method_added(target_klass, alias_name);
}
else {
rb_method_entry_t *alias_me;
alias_me = method_entry_set(target_klass, alias_name, orig_me, visi, orig_me->owner);
RB_OBJ_WRITE(alias_me, &alias_me->owner, target_klass);
RB_OBJ_WRITE(alias_me, &alias_me->defined_class, defined_class);
}
}
/*
* call-seq:
* alias_method(new_name, old_name) -> self
*
* Makes <i>new_name</i> a new copy of the method <i>old_name</i>. This can
* be used to retain access to methods that are overridden.
*
* module Mod
* alias_method :orig_exit, :exit
* def exit(code=0)
* puts "Exiting with code #{code}"
* orig_exit(code)
* end
* end
* include Mod
* exit(99)
*
* <em>produces:</em>
*
* Exiting with code 99
*/
static VALUE
rb_mod_alias_method(VALUE mod, VALUE newname, VALUE oldname)
{
ID oldid = rb_check_id(&oldname);
if (!oldid) {
rb_print_undef_str(mod, oldname);
}
rb_alias(mod, rb_to_id(newname), oldid);
return mod;
}
static void
set_method_visibility(VALUE self, int argc, const VALUE *argv, rb_method_visibility_t visi)
{
int i;
rb_check_frozen(self);
if (argc == 0) {
rb_warning("%"PRIsVALUE" with no argument is just ignored",
QUOTE_ID(rb_frame_callee()));
return;
}
for (i = 0; i < argc; i++) {
VALUE v = argv[i];
ID id = rb_check_id(&v);
if (!id) {
rb_print_undef_str(self, v);
}
rb_export_method(self, id, visi);
}
}
static VALUE
set_visibility(int argc, const VALUE *argv, VALUE module, rb_method_visibility_t visi)
{
if (argc == 0) {
scope_visibility_check();
rb_scope_visibility_set(visi);
}
else {
set_method_visibility(module, argc, argv, visi);
}
return module;
}
/*
* call-seq:
* public -> self
* public(symbol, ...) -> self
* public(string, ...) -> self
*
* With no arguments, sets the default visibility for subsequently
* defined methods to public. With arguments, sets the named methods to
* have public visibility.
* String arguments are converted to symbols.
*/
static VALUE
rb_mod_public(int argc, VALUE *argv, VALUE module)
{
return set_visibility(argc, argv, module, METHOD_VISI_PUBLIC);
}
/*
* call-seq:
* protected -> self
* protected(symbol, ...) -> self
* protected(string, ...) -> self
*
* With no arguments, sets the default visibility for subsequently
* defined methods to protected. With arguments, sets the named methods
* to have protected visibility.
* String arguments are converted to symbols.
*
* If a method has protected visibility, it is callable only where
* <code>self</code> of the context is the same as the method.
* (method definition or instance_eval). This behavior is different from
* Java's protected method. Usually <code>private</code> should be used.
*
* Note that a protected method is slow because it can't use inline cache.
*
* To show a private method on RDoc, use <code>:doc:</code> instead of this.
*/
static VALUE
rb_mod_protected(int argc, VALUE *argv, VALUE module)
{
return set_visibility(argc, argv, module, METHOD_VISI_PROTECTED);
}
/*
* call-seq:
* private -> self
* private(symbol, ...) -> self
* private(string, ...) -> self
*
* With no arguments, sets the default visibility for subsequently
* defined methods to private. With arguments, sets the named methods
* to have private visibility.
* String arguments are converted to symbols.
*
* module Mod
* def a() end
* def b() end
* private
* def c() end
* private :a
* end
* Mod.private_instance_methods #=> [:a, :c]
*
* Note that to show a private method on RDoc, use <code>:doc:</code>.
*/
static VALUE
rb_mod_private(int argc, VALUE *argv, VALUE module)
{
return set_visibility(argc, argv, module, METHOD_VISI_PRIVATE);
}
/*
* call-seq:
* ruby2_keywords(method_name, ...) -> self
*
* For the given method names, marks the method as passing keywords through
* a normal argument splat. This should only be called on methods that
* accept an argument splat (<tt>*args</tt>) but not explicit keywords or
* a keyword splat. It marks the method such that if the method is called
* with keyword arguments, the final hash argument is marked with a special
* flag such that if it is the final element of a normal argument splat to
* another method call, and that method call does not include explicit
* keywords or a keyword splat, the final element is interpreted as keywords.
* In other words, keywords will be passed through the method to other
* methods.
*
* This should only be used for methods that delegate keywords to another
* method, and only for backwards compatibility with Ruby versions before
* 2.7.
*
* This method will probably be removed at some point, as it exists only
* for backwards compatibility. As it does not exist in Ruby versions
* before 2.7, check that the module responds to this method before calling
* it. Also, be aware that if this method is removed, the behavior of the
* method will change so that it does not pass through keywords.
*
* module Mod
* def foo(meth, *args, &block)
* send(:"do_#{meth}", *args, &block)
* end
* ruby2_keywords(:foo) if respond_to?(:ruby2_keywords, true)
* end
*/
static VALUE
rb_mod_ruby2_keywords(int argc, VALUE *argv, VALUE module)
{
int i;
VALUE origin_class = RCLASS_ORIGIN(module);
rb_check_frozen(module);
for (i = 0; i < argc; i++) {
VALUE v = argv[i];
ID name = rb_check_id(&v);
rb_method_entry_t *me;
VALUE defined_class;
if (!name) {
rb_print_undef_str(module, v);
}
me = search_method(origin_class, name, &defined_class);
if (!me && RB_TYPE_P(module, T_MODULE)) {
me = search_method(rb_cObject, name, &defined_class);
}
if (UNDEFINED_METHOD_ENTRY_P(me) ||
UNDEFINED_REFINED_METHOD_P(me->def)) {
rb_print_undef(module, name, METHOD_VISI_UNDEF);
}
if (module == defined_class || origin_class == defined_class) {
switch (me->def->type) {
case VM_METHOD_TYPE_ISEQ:
if (me->def->body.iseq.iseqptr->body->param.flags.has_rest &&
!me->def->body.iseq.iseqptr->body->param.flags.has_kw &&
!me->def->body.iseq.iseqptr->body->param.flags.has_kwrest) {
me->def->body.iseq.iseqptr->body->param.flags.ruby2_keywords = 1;
rb_clear_method_cache_by_class(module);
}
else {
rb_warn("Skipping set of ruby2_keywords flag for %s (method accepts keywords or method does not accept argument splat)", rb_id2name(name));
}
break;
case VM_METHOD_TYPE_BMETHOD: {
VALUE procval = me->def->body.bmethod.proc;
if (vm_block_handler_type(procval) == block_handler_type_proc) {
procval = vm_proc_to_block_handler(VM_BH_TO_PROC(procval));
}
if (vm_block_handler_type(procval) == block_handler_type_iseq) {
const struct rb_captured_block *captured = VM_BH_TO_ISEQ_BLOCK(procval);
const rb_iseq_t *iseq = rb_iseq_check(captured->code.iseq);
if (iseq->body->param.flags.has_rest &&
!iseq->body->param.flags.has_kw &&
!iseq->body->param.flags.has_kwrest) {
iseq->body->param.flags.ruby2_keywords = 1;
rb_clear_method_cache_by_class(module);
}
else {
rb_warn("Skipping set of ruby2_keywords flag for %s (method accepts keywords or method does not accept argument splat)", rb_id2name(name));
}
return Qnil;
}
}
/* fallthrough */
default:
rb_warn("Skipping set of ruby2_keywords flag for %s (method not defined in Ruby)", rb_id2name(name));
break;
}
}
else {
rb_warn("Skipping set of ruby2_keywords flag for %s (can only set in method defining module)", rb_id2name(name));
}
}
return Qnil;
}
/*
* call-seq:
* mod.public_class_method(symbol, ...) -> mod
* mod.public_class_method(string, ...) -> mod
*
* Makes a list of existing class methods public.
*
* String arguments are converted to symbols.
*/
static VALUE
rb_mod_public_method(int argc, VALUE *argv, VALUE obj)
{
set_method_visibility(rb_singleton_class(obj), argc, argv, METHOD_VISI_PUBLIC);
return obj;
}
/*
* call-seq:
* mod.private_class_method(symbol, ...) -> mod
* mod.private_class_method(string, ...) -> mod
*
* Makes existing class methods private. Often used to hide the default
* constructor <code>new</code>.
*
* String arguments are converted to symbols.
*
* class SimpleSingleton # Not thread safe
* private_class_method :new
* def SimpleSingleton.create(*args, &block)
* @me = new(*args, &block) if ! @me
* @me
* end
* end
*/
static VALUE
rb_mod_private_method(int argc, VALUE *argv, VALUE obj)
{
set_method_visibility(rb_singleton_class(obj), argc, argv, METHOD_VISI_PRIVATE);
return obj;
}
/*
* call-seq:
* public
* public(symbol, ...)
* public(string, ...)
*
* With no arguments, sets the default visibility for subsequently
* defined methods to public. With arguments, sets the named methods to
* have public visibility.
*
* String arguments are converted to symbols.
*/
static VALUE
top_public(int argc, VALUE *argv, VALUE _)
{
return rb_mod_public(argc, argv, rb_cObject);
}
/*
* call-seq:
* private
* private(symbol, ...)
* private(string, ...)
*
* With no arguments, sets the default visibility for subsequently
* defined methods to private. With arguments, sets the named methods to
* have private visibility.
*
* String arguments are converted to symbols.
*/
static VALUE
top_private(int argc, VALUE *argv, VALUE _)
{
return rb_mod_private(argc, argv, rb_cObject);
}
/*
* call-seq:
* ruby2_keywords(method_name, ...) -> self
*
* For the given method names, marks the method as passing keywords through
* a normal argument splat. See Module#ruby2_keywords in detail.
*/
static VALUE
top_ruby2_keywords(int argc, VALUE *argv, VALUE module)
{
return rb_mod_ruby2_keywords(argc, argv, rb_cObject);
}
/*
* call-seq:
* module_function(symbol, ...) -> self
* module_function(string, ...) -> self
*
* Creates module functions for the named methods. These functions may
* be called with the module as a receiver, and also become available
* as instance methods to classes that mix in the module. Module
* functions are copies of the original, and so may be changed
* independently. The instance-method versions are made private. If
* used with no arguments, subsequently defined methods become module
* functions.
* String arguments are converted to symbols.
*
* module Mod
* def one
* "This is one"
* end
* module_function :one
* end
* class Cls
* include Mod
* def call_one
* one
* end
* end
* Mod.one #=> "This is one"
* c = Cls.new
* c.call_one #=> "This is one"
* module Mod
* def one
* "This is the new one"
* end
* end
* Mod.one #=> "This is one"
* c.call_one #=> "This is the new one"
*/
static VALUE
rb_mod_modfunc(int argc, VALUE *argv, VALUE module)
{
int i;
ID id;
const rb_method_entry_t *me;
if (!RB_TYPE_P(module, T_MODULE)) {
rb_raise(rb_eTypeError, "module_function must be called for modules");
}
if (argc == 0) {
rb_scope_module_func_set();
return module;
}
set_method_visibility(module, argc, argv, METHOD_VISI_PRIVATE);
for (i = 0; i < argc; i++) {
VALUE m = module;
id = rb_to_id(argv[i]);
for (;;) {
me = search_method(m, id, 0);
if (me == 0) {
me = search_method(rb_cObject, id, 0);
}
if (UNDEFINED_METHOD_ENTRY_P(me)) {
rb_print_undef(module, id, METHOD_VISI_UNDEF);
}
if (me->def->type != VM_METHOD_TYPE_ZSUPER) {
break; /* normal case: need not to follow 'super' link */
}
m = RCLASS_SUPER(m);
if (!m)
break;
}
rb_method_entry_set(rb_singleton_class(module), id, me, METHOD_VISI_PUBLIC);
}
return module;
}
bool
rb_method_basic_definition_p_with_cc(struct rb_call_data *cd, VALUE klass, ID mid)
{
if (cd->ci.mid != mid) {
*cd = (struct rb_call_data) /* reset */ { .ci = { .mid = mid, }, };
}
vm_search_method_fastpath(cd, klass);
return cd->cc.me && METHOD_ENTRY_BASIC(cd->cc.me);
}
#ifdef __GNUC__
#pragma push_macro("rb_method_basic_definition_p")
#undef rb_method_basic_definition_p
#endif
int
rb_method_basic_definition_p(VALUE klass, ID id)
{
const rb_method_entry_t *me;
if (!klass) return TRUE; /* hidden object cannot be overridden */
me = rb_method_entry(klass, id);
return (me && METHOD_ENTRY_BASIC(me)) ? TRUE : FALSE;
}
#ifdef __GNUC__
#pragma pop_macro("rb_method_basic_definition_p")
#endif
static VALUE
call_method_entry(rb_execution_context_t *ec, VALUE defined_class, VALUE obj, ID id,
const rb_method_entry_t *me, int argc, const VALUE *argv, int kw_splat)
{
const rb_callable_method_entry_t *cme =
prepare_callable_method_entry(defined_class, id, me);
VALUE passed_block_handler = vm_passed_block_handler(ec);
VALUE result = rb_vm_call_kw(ec, obj, id, argc, argv, cme, kw_splat);
vm_passed_block_handler_set(ec, passed_block_handler);
return result;
}
static VALUE
basic_obj_respond_to_missing(rb_execution_context_t *ec, VALUE klass, VALUE obj,
VALUE mid, VALUE priv)
{
VALUE defined_class, args[2];
const ID rtmid = idRespond_to_missing;
const rb_method_entry_t *const me =
method_entry_get(klass, rtmid, &defined_class);
if (!me || METHOD_ENTRY_BASIC(me)) return Qundef;
args[0] = mid;
args[1] = priv;
return call_method_entry(ec, defined_class, obj, rtmid, me, 2, args, RB_NO_KEYWORDS);
}
static inline int
basic_obj_respond_to(rb_execution_context_t *ec, VALUE obj, ID id, int pub)
{
VALUE klass = CLASS_OF(obj);
VALUE ret;
switch (rb_method_boundp(klass, id, pub|BOUND_RESPONDS)) {
case 2:
return FALSE;
case 0:
ret = basic_obj_respond_to_missing(ec, klass, obj, ID2SYM(id),
pub ? Qfalse : Qtrue);
return RTEST(ret) && ret != Qundef;
default:
return TRUE;
}
}
static int
vm_respond_to(rb_execution_context_t *ec, VALUE klass, VALUE obj, ID id, int priv)
{
VALUE defined_class;
const ID resid = idRespond_to;
const rb_method_entry_t *const me =
method_entry_get(klass, resid, &defined_class);
if (!me) return -1;
if (METHOD_ENTRY_BASIC(me)) {
return -1;
}
else {
int argc = 1;
VALUE args[2];
VALUE result;
args[0] = ID2SYM(id);
args[1] = Qtrue;
if (priv) {
argc = rb_method_entry_arity(me);
if (argc > 2) {
rb_raise(rb_eArgError,
"respond_to? must accept 1 or 2 arguments (requires %d)",
argc);
}
if (argc != 1) {
argc = 2;
}
else if (!NIL_P(ruby_verbose)) {
VALUE location = rb_method_entry_location(me);
rb_warn("%"PRIsVALUE"%c""respond_to?(:%"PRIsVALUE") uses"
" the deprecated method signature, which takes one parameter",
(FL_TEST(klass, FL_SINGLETON) ? obj : klass),
(FL_TEST(klass, FL_SINGLETON) ? '.' : '#'),
QUOTE_ID(id));
if (!NIL_P(location)) {
VALUE path = RARRAY_AREF(location, 0);
VALUE line = RARRAY_AREF(location, 1);
if (!NIL_P(path)) {
rb_compile_warn(RSTRING_PTR(path), NUM2INT(line),
"respond_to? is defined here");
}
}
}
}
result = call_method_entry(ec, defined_class, obj, resid, me, argc, args, RB_NO_KEYWORDS);
return RTEST(result);
}
}
int
rb_obj_respond_to(VALUE obj, ID id, int priv)
{
rb_execution_context_t *ec = GET_EC();
VALUE klass = CLASS_OF(obj);
int ret = vm_respond_to(ec, klass, obj, id, priv);
if (ret == -1) ret = basic_obj_respond_to(ec, obj, id, !priv);
return ret;
}
int
rb_respond_to(VALUE obj, ID id)
{
return rb_obj_respond_to(obj, id, FALSE);
}
/*
* call-seq:
* obj.respond_to?(symbol, include_all=false) -> true or false
* obj.respond_to?(string, include_all=false) -> true or false
*
* Returns +true+ if _obj_ responds to the given method. Private and
* protected methods are included in the search only if the optional
* second parameter evaluates to +true+.
*
* If the method is not implemented,
* as Process.fork on Windows, File.lchmod on GNU/Linux, etc.,
* false is returned.
*
* If the method is not defined, <code>respond_to_missing?</code>
* method is called and the result is returned.
*
* When the method name parameter is given as a string, the string is
* converted to a symbol.
*/
static VALUE
obj_respond_to(int argc, VALUE *argv, VALUE obj)
{
VALUE mid, priv;
ID id;
rb_execution_context_t *ec = GET_EC();
rb_scan_args(argc, argv, "11", &mid, &priv);
if (!(id = rb_check_id(&mid))) {
VALUE ret = basic_obj_respond_to_missing(ec, CLASS_OF(obj), obj,
rb_to_symbol(mid), priv);
if (ret == Qundef) ret = Qfalse;
return ret;
}
if (basic_obj_respond_to(ec, obj, id, !RTEST(priv)))
return Qtrue;
return Qfalse;
}
/*
* call-seq:
* obj.respond_to_missing?(symbol, include_all) -> true or false
* obj.respond_to_missing?(string, include_all) -> true or false
*
* DO NOT USE THIS DIRECTLY.
*
* Hook method to return whether the _obj_ can respond to _id_ method
* or not.
*
* When the method name parameter is given as a string, the string is
* converted to a symbol.
*
* See #respond_to?, and the example of BasicObject.
*/
static VALUE
obj_respond_to_missing(VALUE obj, VALUE mid, VALUE priv)
{
return Qfalse;
}
void
Init_Method(void)
{
if (!OPT_GLOBAL_METHOD_CACHE) return;
char *ptr = getenv("RUBY_GLOBAL_METHOD_CACHE_SIZE");
int val;
if (ptr != NULL && (val = atoi(ptr)) > 0) {
if ((val & (val - 1)) == 0) { /* ensure val is a power of 2 */
global_method_cache.size = val;
global_method_cache.mask = val - 1;
}
else {
fprintf(stderr, "RUBY_GLOBAL_METHOD_CACHE_SIZE was set to %d but ignored because the value is not a power of 2.\n", val);
}
}
global_method_cache.entries = (struct cache_entry *)calloc(global_method_cache.size, sizeof(struct cache_entry));
if (global_method_cache.entries == NULL) {
fprintf(stderr, "[FATAL] failed to allocate memory\n");
exit(EXIT_FAILURE);
}
}
void
Init_eval_method(void)
{
#undef rb_intern
#define rb_intern(str) rb_intern_const(str)
rb_define_method(rb_mKernel, "respond_to?", obj_respond_to, -1);
rb_define_method(rb_mKernel, "respond_to_missing?", obj_respond_to_missing, 2);
rb_define_method(rb_cModule, "remove_method", rb_mod_remove_method, -1);
rb_define_method(rb_cModule, "undef_method", rb_mod_undef_method, -1);
rb_define_method(rb_cModule, "alias_method", rb_mod_alias_method, 2);
rb_define_private_method(rb_cModule, "public", rb_mod_public, -1);
rb_define_private_method(rb_cModule, "protected", rb_mod_protected, -1);
rb_define_private_method(rb_cModule, "private", rb_mod_private, -1);
rb_define_private_method(rb_cModule, "module_function", rb_mod_modfunc, -1);
rb_define_private_method(rb_cModule, "ruby2_keywords", rb_mod_ruby2_keywords, -1);
rb_define_method(rb_cModule, "method_defined?", rb_mod_method_defined, -1);
rb_define_method(rb_cModule, "public_method_defined?", rb_mod_public_method_defined, -1);
rb_define_method(rb_cModule, "private_method_defined?", rb_mod_private_method_defined, -1);
rb_define_method(rb_cModule, "protected_method_defined?", rb_mod_protected_method_defined, -1);
rb_define_method(rb_cModule, "public_class_method", rb_mod_public_method, -1);
rb_define_method(rb_cModule, "private_class_method", rb_mod_private_method, -1);
rb_define_private_method(rb_singleton_class(rb_vm_top_self()),
"public", top_public, -1);
rb_define_private_method(rb_singleton_class(rb_vm_top_self()),
"private", top_private, -1);
rb_define_private_method(rb_singleton_class(rb_vm_top_self()),
"ruby2_keywords", top_ruby2_keywords, -1);
{
#define REPLICATE_METHOD(klass, id) do { \
const rb_method_entry_t *me = rb_method_entry((klass), (id)); \
rb_method_entry_set((klass), (id), me, METHOD_ENTRY_VISI(me)); \
} while (0)
REPLICATE_METHOD(rb_eException, idMethodMissing);
REPLICATE_METHOD(rb_eException, idRespond_to);
REPLICATE_METHOD(rb_eException, idRespond_to_missing);
}
}
|
pmq20/ruby-compiler
|
ruby/vm_method.c
|
C
|
mit
| 67,543
|
package se.oxidev.animtools64;
public class Const {
public static String WORKING_DIR = System.getProperty("user.dir");
public static String VICE_PATH = "/Users/mikael/Dropbox/JavaDev/vice-mac/tools/x64";
public static int VISIBLE_SCREEN_WIDTH = 960;
public static int VISIBLE_SCREEN_HEIGHT = 600;
public static int PREVIEW_SCREEN_SIZE_WIDTH = 320;
public static int PREVIEW_SCREEN_SIZE_HEIGHT = 200;
public static int BMPSIZE_WIDTH = 160;
public static int BMPSIZE_HEIGHT = 200;
public static int BMP_PIXELCOUNT = 160 * 200;
public static int ZOOM_2X = 2;
public static int ZOOM_4X = 4;
public static int PREVIEW_INDEX_320X200 = 0;
public static int PREVIEW_INDEX_160X100 = 1;
public static int PREVIEW_INDEX_CLIPBOARD_DATA = 2;
public static int PREVIEW_INDEX_TEMP_STORAGE = 3;
public static int PREVIEW_INDEX_ANIMATE_320X200 = 4;
public static int PREVIEW_INDEX_ANIMATE_160X100 = 5;
public static int UNASSIGNED = 0;
public static int UNDOTYPE_DRAW = 1;
public static int UNDOTYPE_MOVE_PIXELS = 2;
}
|
oxidy/animtools64
|
src/main/java/se/oxidev/animtools64/Const.java
|
Java
|
mit
| 1,038
|
# checkbox example
### run example
```
git clone https://github.com/gorangajic/react-svg-morph
cd react-svg-morph/example/checkbox
npm install
npm start
open http://localhost:8080
```
|
gorangajic/react-svg-morph
|
example/checkbox/README.md
|
Markdown
|
mit
| 186
|
/* global describe, expect, it */
const fishNames = require('../src/index');
const allFish = fishNames.all;
describe('fish names', function() {
describe('all', function() {
it('should return an object containing all 200 fish names', function() {
expect(Object.keys(allFish).length).toEqual(200);
});
});
describe('random', function() {
it('should return a random fish', function() {
expect(Object.keys(allFish).map(fish => allFish[fish])).toContain(
fishNames.random()
);
});
it('should return an array of random fish names if passed a number as a param', function() {
const threeRandomFish = fishNames.random(3);
expect(threeRandomFish.length).toBe(3);
});
});
describe('male/female fish', function() {
const allMaleFish = Object.keys(fishNames.allMaleFish).map(
fish => fishNames.allMaleFish[fish]
);
const allFemaleFish = Object.keys(fishNames.allFemaleFish).map(
fish => fishNames.allFemaleFish[fish]
);
it('should ONLY contain names of male fish', function() {
expect(allMaleFish).not.toEqual(expect.arrayContaining(allFemaleFish));
});
it('should ONLY contain names of female fish', function() {
expect(allFemaleFish).not.toEqual(expect.arrayContaining(allMaleFish));
});
});
});
|
yeskunall/fish-names
|
__test__/index.test.js
|
JavaScript
|
mit
| 1,323
|
---
---
<!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>TransitionHookFn | @uirouter/angular</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../assets/css/main.css">
<link rel="stylesheet" href="../assets/css/uirouter.css">
<script src="../assets/js/modernizr.js"></script>
<script src="../assets/js/reset.js"></script>
</head>
<body>
<header>
<div class="tsd-page-toolbar">
<div class="container">
<div class="table-wrap">
<div class="table-cell" id="tsd-search" data-index="../assets/js/search.js" data-base="..">
<div class="field">
<label for="tsd-search-field" class="tsd-widget search no-caption">Search</label>
<input id="tsd-search-field" type="text" />
</div>
<ul class="results">
<li class="state loading">Preparing search index...</li>
<li class="state failure">The search index is not available</li>
</ul>
<a href="../index.html" class="title">@uirouter/angular</a>
</div>
<div class="table-cell" id="tsd-widgets">
<div id="tsd-filter">
<a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a>
<div class="tsd-filter-group">
<!--
<div class="tsd-select" id="tsd-filter-visibility">
<span class="tsd-select-label">All</span>
<ul class="tsd-select-list">
<li data-value="public">Public</li>
<li data-value="protected">Public/Protected</li>
<li data-value="private" class="selected">All</li>
</ul>
</div>
<input type="checkbox" id="tsd-filter-inherited" checked />
<label class="tsd-widget" for="tsd-filter-inherited">Inherited</label>
-->
<input type="checkbox" id="tsd-filter-externals" checked />
<label class="tsd-widget" for="tsd-filter-externals">Internal UI-Router API</label>
<!--
<input type="checkbox" id="tsd-filter-only-exported" />
<label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label>
-->
</div>
</div>
<a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a>
</div>
</div>
</div>
</div>
<div class="tsd-page-title">
<div class="container">
<ul class="tsd-breadcrumb">
<li>
<a href="../index.html">@uirouter/angular</a>
</li>
<li>
<a href="../modules/transition.html">transition</a>
</li>
<li>
<a href="transition.transitionhookfn.html">TransitionHookFn</a>
</li>
</ul>
<h1>Interface TransitionHookFn</h1>
</div>
</div>
</header>
<div class="container container-main">
<div class="row">
<div class="col-8 col-content">
<section class="tsd-panel tsd-comment">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>The signature for Transition Hooks.</p>
</div>
<p>Transition hooks are callback functions that hook into the lifecycle of transitions.
As a transition runs, it reaches certain lifecycle events.
As each event occurs, the hooks which are registered for the event are called (in priority order).</p>
<p>A transition hook may alter a Transition by returning a <a href="../modules/transition.html#hookresult">HookResult</a>.</p>
<h4 id="see-">See:</h4>
<ul>
<li><a href="transition.ihookregistry.html#onbefore">IHookRegistry.onBefore</a></li>
<li><a href="transition.ihookregistry.html#onstart">IHookRegistry.onStart</a></li>
<li><a href="transition.ihookregistry.html#onfinish">IHookRegistry.onFinish</a></li>
<li><a href="transition.ihookregistry.html#onsuccess">IHookRegistry.onSuccess</a></li>
<li><a href="transition.ihookregistry.html#onerror">IHookRegistry.onError</a></li>
</ul>
</div>
</section>
<section class="tsd-panel tsd-hierarchy">
<h3>Hierarchy</h3>
<ul class="tsd-hierarchy">
<li>
<span class="target">TransitionHookFn</span>
</li>
</ul>
</section>
<section class="tsd-panel">
<h3 class="tsd-before-signature">Callable</h3>
<ul class="tsd-signatures tsd-kind-interface tsd-parent-kind-external-module">
<li class="tsd-signature tsd-kind-icon">__call<span class="tsd-signature-symbol">(</span>transition<span class="tsd-signature-symbol">: </span><a href="../classes/transition.transition-1.html" class="tsd-signature-type">Transition</a><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><a href="../modules/transition.html#hookresult" class="tsd-signature-type">HookResult</a></li>
<li class="tsd-header">
<p> The signature for Transition Hooks. </p>
</li>
</ul>
<ul class="tsd-descriptions">
<li class="tsd-description">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>The signature for Transition Hooks.</p>
</div>
<p>Transition hooks are callback functions that hook into the lifecycle of transitions.
As a transition runs, it reaches certain lifecycle events.
As each event occurs, the hooks which are registered for the event are called (in priority order).</p>
<p>A transition hook may alter a Transition by returning a <a href="../modules/transition.html#hookresult">HookResult</a>.</p>
<h4 id="see-">See:</h4>
<ul>
<li><a href="transition.ihookregistry.html#onbefore">IHookRegistry.onBefore</a></li>
<li><a href="transition.ihookregistry.html#onstart">IHookRegistry.onStart</a></li>
<li><a href="transition.ihookregistry.html#onfinish">IHookRegistry.onFinish</a></li>
<li><a href="transition.ihookregistry.html#onsuccess">IHookRegistry.onSuccess</a></li>
<li><a href="transition.ihookregistry.html#onerror">IHookRegistry.onError</a></li>
</ul>
</div>
<h4 class="tsd-parameters-title">Parameters</h4>
<ul class="tsd-parameters">
<li>
<h5>transition <a href="../classes/transition.transition-1.html" class="tsd-signature-type">Transition</a></h5>
: <div class="tsd-comment tsd-typography">
<div class="lead">
<p>the current <a href="../classes/transition.transition-1.html">Transition</a></p>
</div>
</div>
</li>
</ul>
<div class="tsd-returns">
<h4 class="tsd-returns-title">Returns <a href="../modules/transition.html#hookresult" class="tsd-signature-type">HookResult</a></h4>
: <p>a <a href="../modules/transition.html#hookresult">HookResult</a> which may alter the transition</p>
</div>
<hr>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/83a054e/src/transition/interface.ts#L202">ui-router-core/src/transition/interface.ts:202</a></li>
</ul>
</aside> </li>
</ul>
</section>
</div>
<div class="col-4 col-menu menu-sticky-wrap menu-highlight">
<nav class="tsd-navigation primary">
<ul>
<li class="globals ">
<a href="../index.html"><em>@uirouter/angular</em></a>
</li>
<li class="label tsd-is-external">
<span>Public API</span>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/core.html">core</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/directives.html">directives</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/params.html">params</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/resolve.html">resolve</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/state.html">state</a>
</li>
<li class="current tsd-kind-external-module">
<a href="../modules/transition.html">transition</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/url.html">url</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/view.html">view</a>
</li>
<li class="label tsd-is-external">
<span>Internal UI-<wbr><wbr>Router API</span>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/common.html">common</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/common_hof.html">common_<wbr>hof</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/common_predicates.html">common_<wbr>predicates</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/common_strings.html">common_<wbr>strings</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/hooks.html">hooks</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/ng2.html">ng2</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/path.html">path</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/trace.html">trace</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/vanilla.html">vanilla</a>
</li>
</ul>
</nav>
<nav class="tsd-navigation secondary menu-sticky">
<ul class="before-current">
<li class=" tsd-kind-enum tsd-parent-kind-external-module tsd-is-not-exported">
<a href="../enums/transition.rejecttype.html" class="tsd-kind-icon">Reject<wbr>Type</a>
</li>
<li class=" tsd-kind-enum tsd-parent-kind-external-module tsd-is-not-exported">
<a href="../enums/transition.transitionhookphase.html" class="tsd-kind-icon">Transition<wbr>Hook<wbr>Phase</a>
</li>
<li class=" tsd-kind-enum tsd-parent-kind-external-module tsd-is-not-exported">
<a href="../enums/transition.transitionhookscope.html" class="tsd-kind-icon">Transition<wbr>Hook<wbr>Scope</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-external-module">
<a href="../classes/transition.hookbuilder.html" class="tsd-kind-icon">Hook<wbr>Builder</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-external-module tsd-is-external">
<a href="../classes/transition.registeredhook.html" class="tsd-kind-icon">Registered<wbr>Hook</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-external-module">
<a href="../classes/transition.rejection.html" class="tsd-kind-icon">Rejection</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-external-module">
<a href="../classes/transition.transition-1.html" class="tsd-kind-icon">Transition</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-external-module tsd-is-external">
<a href="../classes/transition.transitioneventtype.html" class="tsd-kind-icon">Transition<wbr>Event<wbr>Type</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-external-module">
<a href="../classes/transition.transitionservice.html" class="tsd-kind-icon">Transition<wbr>Service</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module">
<a href="transition.hookmatchcriteria.html" class="tsd-kind-icon">Hook<wbr>Match<wbr>Criteria</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module">
<a href="transition.hookregoptions.html" class="tsd-kind-icon">Hook<wbr>Reg<wbr>Options</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module tsd-is-not-exported">
<a href="transition.hooktuple.html" class="tsd-kind-icon">Hook<wbr>Tuple</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module">
<a href="transition.ihookregistry.html" class="tsd-kind-icon">IHook<wbr>Registry</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module">
<a href="transition.imatchingnodes.html" class="tsd-kind-icon">IMatching<wbr>Nodes</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module">
<a href="transition.transitioncreatehookfn.html" class="tsd-kind-icon">Transition<wbr>Create<wbr>Hook<wbr>Fn</a>
</li>
</ul>
<ul class="current">
<li class="current tsd-kind-interface tsd-parent-kind-external-module">
<a href="transition.transitionhookfn.html" class="tsd-kind-icon">Transition<wbr>Hook<wbr>Fn</a>
</li>
</ul>
<ul class="after-current">
<li class=" tsd-kind-interface tsd-parent-kind-external-module tsd-is-external">
<a href="transition.transitionhookoptions.html" class="tsd-kind-icon">Transition<wbr>Hook<wbr>Options</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module">
<a href="transition.transitionoptions.html" class="tsd-kind-icon">Transition<wbr>Options</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module tsd-is-external">
<a href="transition.transitionservicepluginapi.html" class="tsd-kind-icon">Transition<wbr>Service<wbr>PluginAPI</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module">
<a href="transition.transitionstatehookfn.html" class="tsd-kind-icon">Transition<wbr>State<wbr>Hook<wbr>Fn</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module">
<a href="transition.treechanges.html" class="tsd-kind-icon">Tree<wbr>Changes</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/transition.html#errorhandler" class="tsd-kind-icon">Error<wbr>Handler</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/transition.html#geterrorhandler" class="tsd-kind-icon">Get<wbr>Error<wbr>Handler</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/transition.html#getresulthandler" class="tsd-kind-icon">Get<wbr>Result<wbr>Handler</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/transition.html#hookfn" class="tsd-kind-icon">Hook<wbr>Fn</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/transition.html#hookmatchcriterion" class="tsd-kind-icon">Hook<wbr>Match<wbr>Criterion</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/transition.html#hookresult" class="tsd-kind-icon">Hook<wbr>Result</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/transition.html#ihookregistration" class="tsd-kind-icon">IHook<wbr>Registration</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/transition.html#istatematch" class="tsd-kind-icon">IState<wbr>Match</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/transition.html#resulthandler" class="tsd-kind-icon">Result<wbr>Handler</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-not-exported">
<a href="../modules/transition.html#tuplesort" class="tsd-kind-icon">tuple<wbr>Sort</a>
</li>
<li class=" tsd-kind-object-literal tsd-parent-kind-external-module tsd-is-not-exported">
<a href="../modules/transition.html#defaultoptions" class="tsd-kind-icon">default<wbr>Options</a>
</li>
<li class=" tsd-kind-object-literal tsd-parent-kind-external-module">
<a href="../modules/transition.html#defaulttransopts" class="tsd-kind-icon">default<wbr>Trans<wbr>Opts</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<footer class="with-border-bottom">
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
<ul class="tsd-legend">
<li class="tsd-kind-module"><span class="tsd-kind-icon">Module</span></li>
<li class="tsd-kind-object-literal"><span class="tsd-kind-icon">Object literal</span></li>
<li class="tsd-kind-variable"><span class="tsd-kind-icon">Variable</span></li>
<li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li>
<li class="tsd-kind-function tsd-has-type-parameter"><span class="tsd-kind-icon">Function with type parameter</span></li>
<li class="tsd-kind-index-signature"><span class="tsd-kind-icon">Index signature</span></li>
<li class="tsd-kind-type-alias"><span class="tsd-kind-icon">Type alias</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li>
<li class="tsd-kind-enum-member"><span class="tsd-kind-icon">Enumeration member</span></li>
<li class="tsd-kind-property tsd-parent-kind-enum"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-enum"><span class="tsd-kind-icon">Method</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li>
<li class="tsd-kind-interface tsd-has-type-parameter"><span class="tsd-kind-icon">Interface with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-interface"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-interface"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li>
<li class="tsd-kind-class tsd-has-type-parameter"><span class="tsd-kind-icon">Class with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-class"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class"><span class="tsd-kind-icon">Accessor</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-constructor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static method</span></li>
</ul>
</div>
</div>
</footer>
<div class="container tsd-generator">
<p>Generated using <a href="http://typedoc.io" target="_blank">TypeDoc</a></p>
</div>
<div class="overlay"></div>
<script src="../assets/js/main.js"></script>
<script>if (location.protocol == 'file:') document.write('<script src="../assets/js/search.js"><' + '/script>');</script>
</body>
</html>
|
ui-router/ui-router.github.io
|
_ng2_docs/2.0.0/interfaces/transition.transitionhookfn.html
|
HTML
|
mit
| 20,936
|
package meetup;
public class Member
{
private String id;
private String name;
private String link;
private String photoUrl;
private String bio;
private String latitude;
private String longitude;
private String country;
private String city;
private String state;
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getLink()
{
return link;
}
public void setLink(String link)
{
this.link = link;
}
public String getPhotoUrl()
{
return photoUrl;
}
public void setPhotoUrl(String photoUrl)
{
this.photoUrl = photoUrl;
}
public String getBio()
{
return bio;
}
public void setBio(String bio)
{
this.bio = bio;
}
public String getLatitude()
{
return latitude;
}
public void setLatitude(String latitude)
{
this.latitude = latitude;
}
public String getLongitude()
{
return longitude;
}
public void setLongitude(String longitude)
{
this.longitude = longitude;
}
public String getCountry()
{
return country;
}
public void setCountry(String country)
{
this.country = country;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
public String toString()
{
return ToStringBuilder.build(this);
}
}
|
cybersecurity-li/vereinsaustausch
|
MeetupClientJava/src/main/meetup/Member.java
|
Java
|
mit
| 1,539
|
# 判斷式
>如果今天颱風假,我就在家耍廢;否則我還是得來上課。
在程式內為了運用各式各樣的狀況,判斷式這樣東西的存在是非常重要的。
為了應付這種狀況,C 語言理所當然地也提供了很多條件判斷式。
## if條件判斷
最為基礎的則是if條件判斷,他的基本語法如下:
```C++
if(條件){
do1;
}
else{
do2;
}
```
所以如果拿我們最上面案例的話就會變成
```C++
if(放颱風假){
在家耍廢;
}
else{
乖乖去上課;
}
```
當然在必要時刻其實不一定有if就要有else
我們也可以只有一個if即可,例如:
```C++
if(放颱風假){
在家耍廢;
}
```
有了最基礎的判斷式之後,其實可以做的事情就更多了
## 練習
給大家一個實例的實作試試看:
假設今天輸入計概分數,分數>=60就顯示"及格",<60則顯示"當掉"。那該如何利用最簡單的if else判斷式去做呢?
### 解答
```C++
#include <stdio.h>
int main(){
int score;
scanf("%d",&score);
if(score >=60){
printf("及格!");
}
else{
printf("當掉!");
}
return 0;
}
```
<h2>巢狀if</h2>
if只能判斷一件事情嗎? 答案當然是否定的。
當我們需要去對某個條件做多重確認的時候,其實可以在一層if內在寫上另一層的if,例如:
```C++
if(放颱風假){
if(大風大雨){
在家耍廢;
}
else{
打球;
}
}
else{
if(大風大雨){
在家耍廢;
}
else{
乖乖去上課;
}
}
```
以上面這個案例來看的話,他會先對"放颱風假"這件事情進行檢查,並根據條件的是否,進而去下一層檢查"大風大雨",才來決定要做哪些事情。
## 練習
計概分數本身如果分數 >100 或者 <0 這都是 **不正常** 的分數,所以應該要顯示 "不正常!" ,請大家根據前一個例子進行修改。
當輸入分數在合理範圍內(即0~100間)則 >=60 就顯示 "及格",<60 則顯示 "當掉"。
## if elseif else條件式
假設今天的分數我想要讓他有更多的區間呢?
我想各位不會想要一直用一堆的if去把它包起來吧
而在C 語言裡面,除了基本的if else以外其實還有更多的用法。
也就是if elseif else的條件式,他的基本語法如下:
```C++
if(條件1){
do1;
}
else if(條件2){
do2;
}
else{
do3;
}
```
而在進行條件檢查時他會依序從上開始檢查,如果所有條件都不符合才會執行至else內部
另外在中間部分的else if的數量其實是可以隨著程式的要求進而去做改變
也就是說可以有 **零到多個** 的else if在原先的if else條件判斷式中間。
## 練習
再次根據上一個練習,請大家練習看看,假設計概分數合理範圍為0~100,當計概分數本身不在合理範圍內(即>100或<0)則顯示"不正常!"。
在合理範圍內時,分數>=90就顯示"A"、介於80~89間則顯示"B"、介於60~79間則顯示"C"、<60則顯示"當掉"。
## switch條件判斷
switch是C 語言提供的另一種條件判斷方式,本身只能比較數值或字元
但是使用適當的話,它可比 if 判斷式來得有效率;switch 的基本語法如下:
```C++
switch (變數名稱或運算式) {
case 符合的數字或字元:
do1;
break;
case 符合的數字或字元:
do2;
break;
default:
do3;
}
```
其中程式再執行時會先看看 switch 的括號,當中置放要取出數值的變數,取出數值之後,會與case 設定的數字或字元比對,符合則執行該case **以下的陳述句直到遇到break為止** 才會離開switch,若case內都沒有相符的則會執行default內的內容,但是default本身並不一定要存在,這部分跟if else中,其實可以不要寫else是一樣的。
這樣講可能大家有點不可以很清楚的理解,假設今天有一個例子利用if elseif else寫法為:
```C++
int a;
if(a == 1){
//do1
}
else if(a == 2) {
//do2
}
else if(a == 3) {
//do3
}
else{
//do4
}
```
那其實也可以將其代換成switch case的寫法如下:
```C++
int a;
switch(a) {
case 1:
//do1
break;
case 2:
//do2
break;
case 3:
//do3
break;
default:
//do4
}
```
當然if跟switch之間並不是具有那麼強烈的優異性,只是遇到複合條件時,switch 就幫不上忙了,你無法在 switch 中組合複雜的條件陳述。
這時後使用 if 就會是比較好的方式,理所當然的,if 與 switch 兩者也可以搭配著靈活使用。
## 練習
一樣的計概分數題目
假設計概分數合理範圍為0~100
當計概分數本身不在合理範圍內(即>100或<0)則顯示"不正常!"
在合理範圍內時「分數>=90」就顯示 "A"、介於80~89間則顯示 "B"、介於60~79間則顯示 "C"、<60則顯示"當掉"。
大家是否能把它改成switch case的寫法呢?
|
FCUIECS/CCDS
|
content/docs/Ch3/05_ifStatement.md
|
Markdown
|
mit
| 5,004
|
# -*- coding: utf-8 -*-
u'''\
:mod:`ecoxipy.pyxom` - Pythonic XML Object Model (PyXOM)
========================================================
This module implements the *Pythonic XML Object Model* (PyXOM) for the
representation of XML structures. To conveniently create PyXOM data structures
use :mod:`ecoxipy.pyxom.output`, for indexing use
:mod:`ecoxipy.pyxom.indexing` (if :attr:`Document.element_by_id` and
:attr:`Document.elements_by_name` are not enough for you).
.. _ecoxipy.pyxom.examples:
Examples
--------
XML Creation
^^^^^^^^^^^^
If you use the constructors be sure to supply the right data types, otherwise
use the :meth:`create` methods or use :class:`ecoxipy.MarkupBuilder`, which
take care of conversion.
>>> from ecoxipy import MarkupBuilder
>>> b = MarkupBuilder()
>>> document = Document.create(
... b.article(
... b.h1(
... b & '<Example>',
... data='to quote: <&>"\\''
... ),
... b.p(
... {'umlaut-attribute': u'äöüß'},
... 'Hello', Element.create('em', ' World',
... attributes={'count':1}), '!'
... ),
... None,
... b.div(
... Element.create('data-element', Text.create(u'äöüß <&>')),
... b(
... '<p attr="value">raw content</p>Some Text',
... b.br,
... (i for i in range(3))
... ),
... (i for i in range(3, 6))
... ),
... Comment.create('<This is a comment!>'),
... ProcessingInstruction.create('pi-target', '<PI content>'),
... ProcessingInstruction.create('pi-without-content'),
... b['foo:somexml'](
... b['foo:somexml']({'foo:bar': 1, 't:test': 2}),
... b['somexml']({'xmlns': ''}),
... b['bar:somexml'],
... {'xmlns:foo': 'foo://bar', 'xmlns:t': '',
... 'foo:bar': 'Hello', 'id': 'foo'}
... ),
... {'xmlns': 'http://www.w3.org/1999/xhtml/'}
... ), doctype_name='article', omit_xml_declaration=True
... )
Enforcing Well-Formedness
^^^^^^^^^^^^^^^^^^^^^^^^^
Using the :meth:`create` methods or passing the parameter
``check_well_formedness`` as :const:`True` to the appropriate constructors
enforces that the element, attribute and document type names are valid XML
names, and that processing instruction target and content as well as comment
contents conform to their constraints:
>>> from ecoxipy import XMLWellFormednessException
>>> def catch_not_well_formed(cls, *args, **kargs):
... try:
... return cls.create(*args, **kargs)
... except XMLWellFormednessException as e:
... print(e)
>>> t = catch_not_well_formed(Document, [], doctype_name='1nvalid-xml-name')
The value "1nvalid-xml-name" is not a valid XML name.
>>> t = catch_not_well_formed(Document, [], doctype_name='html', doctype_publicid='"')
The value "\\"" is not a valid document type public ID.
>>> t = catch_not_well_formed(Document, [], doctype_name='html', doctype_systemid='"\\'')
The value "\\"'" is not a valid document type system ID.
>>> t = catch_not_well_formed(Element, '1nvalid-xml-name', [], {})
The value "1nvalid-xml-name" is not a valid XML name.
>>> t = catch_not_well_formed(Element, 't', [], attributes={'1nvalid-xml-name': 'content'})
The value "1nvalid-xml-name" is not a valid XML name.
>>> t = catch_not_well_formed(ProcessingInstruction, '1nvalid-xml-name')
The value "1nvalid-xml-name" is not a valid XML processing instruction target.
>>> t = catch_not_well_formed(ProcessingInstruction, 'target', 'invalid PI content ?>')
The value "invalid PI content ?>" is not a valid XML processing instruction content because it contains "?>".
>>> t = catch_not_well_formed(Comment, 'invalid XML comment --')
The value "invalid XML comment --" is not a valid XML comment because it contains "--".
Navigation
^^^^^^^^^^
Use list semantics to retrieve child nodes and attribute access to retrieve
node information:
>>> print(document.doctype.name)
article
>>> print(document[0].name)
article
>>> print(document[0].attributes['xmlns'].value)
http://www.w3.org/1999/xhtml/
>>> print(document[0][-3].target)
pi-target
>>> document[0][1].parent is document[0]
True
>>> document[0][0] is document[0][1].previous and document[0][1].next is document[0][2]
True
>>> document.parent is None and document[0].previous is None and document[0].next is None
True
>>> document[0].attributes.parent is document[0]
True
You can retrieve iterators for navigation through the tree:
>>> list(document[0][0].ancestors)
[ecoxipy.pyxom.Element['article', {...}], ecoxipy.pyxom.Document[ecoxipy.pyxom.DocumentType('article', None, None), True, 'UTF-8']]
>>> list(document[0][1].children())
[ecoxipy.pyxom.Text('Hello'), ecoxipy.pyxom.Element['em', {...}], ecoxipy.pyxom.Text('!')]
>>> list(document[0][2].descendants())
[ecoxipy.pyxom.Element['data-element', {...}], ecoxipy.pyxom.Text('\\xe4\\xf6\\xfc\\xdf <&>'), ecoxipy.pyxom.Element['p', {...}], ecoxipy.pyxom.Text('raw content'), ecoxipy.pyxom.Text('Some Text'), ecoxipy.pyxom.Element['br', {...}], ecoxipy.pyxom.Text('0'), ecoxipy.pyxom.Text('1'), ecoxipy.pyxom.Text('2'), ecoxipy.pyxom.Text('3'), ecoxipy.pyxom.Text('4'), ecoxipy.pyxom.Text('5')]
>>> list(document[0][-2].preceding_siblings)
[ecoxipy.pyxom.ProcessingInstruction('pi-target', '<PI content>'), ecoxipy.pyxom.Comment('<This is a comment!>'), ecoxipy.pyxom.Element['div', {...}], ecoxipy.pyxom.Element['p', {...}], ecoxipy.pyxom.Element['h1', {...}]]
>>> list(document[0][2][-1].preceding)
[ecoxipy.pyxom.Text('4'), ecoxipy.pyxom.Text('3'), ecoxipy.pyxom.Text('2'), ecoxipy.pyxom.Text('1'), ecoxipy.pyxom.Text('0'), ecoxipy.pyxom.Element['br', {...}], ecoxipy.pyxom.Text('Some Text'), ecoxipy.pyxom.Element['p', {...}], ecoxipy.pyxom.Element['data-element', {...}], ecoxipy.pyxom.Element['p', {...}], ecoxipy.pyxom.Element['h1', {...}]]
>>> list(document[0][0].following_siblings)
[ecoxipy.pyxom.Element['p', {...}], ecoxipy.pyxom.Element['div', {...}], ecoxipy.pyxom.Comment('<This is a comment!>'), ecoxipy.pyxom.ProcessingInstruction('pi-target', '<PI content>'), ecoxipy.pyxom.ProcessingInstruction('pi-without-content', None), ecoxipy.pyxom.Element['foo:somexml', {...}]]
>>> list(document[0][1][0].following)
[ecoxipy.pyxom.Element['em', {...}], ecoxipy.pyxom.Text('!'), ecoxipy.pyxom.Element['div', {...}], ecoxipy.pyxom.Comment('<This is a comment!>'), ecoxipy.pyxom.ProcessingInstruction('pi-target', '<PI content>'), ecoxipy.pyxom.ProcessingInstruction('pi-without-content', None), ecoxipy.pyxom.Element['foo:somexml', {...}]]
Descendants and children can also be retrieved in reverse document order:
>>> list(document[0][1].children(True)) == list(reversed(list(document[0][1].children())))
True
>>> list(document[0][2].descendants(True))
[ecoxipy.pyxom.Text('5'), ecoxipy.pyxom.Text('4'), ecoxipy.pyxom.Text('3'), ecoxipy.pyxom.Text('2'), ecoxipy.pyxom.Text('1'), ecoxipy.pyxom.Text('0'), ecoxipy.pyxom.Element['br', {...}], ecoxipy.pyxom.Text('Some Text'), ecoxipy.pyxom.Element['p', {...}], ecoxipy.pyxom.Text('raw content'), ecoxipy.pyxom.Element['data-element', {...}], ecoxipy.pyxom.Text('\\xe4\\xf6\\xfc\\xdf <&>')]
Normally :meth:`~ContainerNode.descendants` traverses the XML tree depth-first,
but you can also use breadth-first traversal:
>>> list(document[0][2].descendants(depth_first=False))
[ecoxipy.pyxom.Element['data-element', {...}], ecoxipy.pyxom.Element['p', {...}], ecoxipy.pyxom.Text('Some Text'), ecoxipy.pyxom.Element['br', {...}], ecoxipy.pyxom.Text('0'), ecoxipy.pyxom.Text('1'), ecoxipy.pyxom.Text('2'), ecoxipy.pyxom.Text('3'), ecoxipy.pyxom.Text('4'), ecoxipy.pyxom.Text('5'), ecoxipy.pyxom.Text('\\xe4\\xf6\\xfc\\xdf <&>'), ecoxipy.pyxom.Text('raw content')]
>>> list(document[0][2].descendants(True, False))
[ecoxipy.pyxom.Text('5'), ecoxipy.pyxom.Text('4'), ecoxipy.pyxom.Text('3'), ecoxipy.pyxom.Text('2'), ecoxipy.pyxom.Text('1'), ecoxipy.pyxom.Text('0'), ecoxipy.pyxom.Element['br', {...}], ecoxipy.pyxom.Text('Some Text'), ecoxipy.pyxom.Element['p', {...}], ecoxipy.pyxom.Element['data-element', {...}], ecoxipy.pyxom.Text('raw content'), ecoxipy.pyxom.Text('\\xe4\\xf6\\xfc\\xdf <&>')]
Normally :meth:`~ContainerNode.descendants` can also be given a depth limit:
>>> list(document[0].descendants(max_depth=2))
[ecoxipy.pyxom.Element['h1', {...}], ecoxipy.pyxom.Text('<Example>'), ecoxipy.pyxom.Element['p', {...}], ecoxipy.pyxom.Text('Hello'), ecoxipy.pyxom.Element['em', {...}], ecoxipy.pyxom.Text('!'), ecoxipy.pyxom.Element['div', {...}], ecoxipy.pyxom.Element['data-element', {...}], ecoxipy.pyxom.Element['p', {...}], ecoxipy.pyxom.Text('Some Text'), ecoxipy.pyxom.Element['br', {...}], ecoxipy.pyxom.Text('0'), ecoxipy.pyxom.Text('1'), ecoxipy.pyxom.Text('2'), ecoxipy.pyxom.Text('3'), ecoxipy.pyxom.Text('4'), ecoxipy.pyxom.Text('5'), ecoxipy.pyxom.Comment('<This is a comment!>'), ecoxipy.pyxom.ProcessingInstruction('pi-target', '<PI content>'), ecoxipy.pyxom.ProcessingInstruction('pi-without-content', None), ecoxipy.pyxom.Element['foo:somexml', {...}], ecoxipy.pyxom.Element['foo:somexml', {...}], ecoxipy.pyxom.Element['somexml', {...}], ecoxipy.pyxom.Element['bar:somexml', {...}]]
>>> list(document[0].descendants(depth_first=False, max_depth=2))
[ecoxipy.pyxom.Element['h1', {...}], ecoxipy.pyxom.Element['p', {...}], ecoxipy.pyxom.Element['div', {...}], ecoxipy.pyxom.Comment('<This is a comment!>'), ecoxipy.pyxom.ProcessingInstruction('pi-target', '<PI content>'), ecoxipy.pyxom.ProcessingInstruction('pi-without-content', None), ecoxipy.pyxom.Element['foo:somexml', {...}], ecoxipy.pyxom.Text('<Example>'), ecoxipy.pyxom.Text('Hello'), ecoxipy.pyxom.Element['em', {...}], ecoxipy.pyxom.Text('!'), ecoxipy.pyxom.Element['data-element', {...}], ecoxipy.pyxom.Element['p', {...}], ecoxipy.pyxom.Text('Some Text'), ecoxipy.pyxom.Element['br', {...}], ecoxipy.pyxom.Text('0'), ecoxipy.pyxom.Text('1'), ecoxipy.pyxom.Text('2'), ecoxipy.pyxom.Text('3'), ecoxipy.pyxom.Text('4'), ecoxipy.pyxom.Text('5'), ecoxipy.pyxom.Element['foo:somexml', {...}], ecoxipy.pyxom.Element['somexml', {...}], ecoxipy.pyxom.Element['bar:somexml', {...}]]
Namespaces
""""""""""
PyXOM supports the interpretation of `Namespaces in XML
<http://www.w3.org/TR/REC-xml-names/>`_. Namespace prefix and local names are
calculated from :class:`Element` and :class:`Attribute` names:
>>> document[0].namespace_prefix == None
True
>>> print(document[0].local_name)
article
>>> print(document[0][-1].namespace_prefix)
foo
>>> print(document[0][-1].local_name)
somexml
>>> attr = document[0][-1].attributes['foo:bar']
>>> print(attr.namespace_prefix)
foo
>>> print(attr.local_name)
bar
The namespace URI is available as :attr:`Element.namespace_uri` and
:attr:`Attribute.namespace_uri` (originally defined as
:attr:`NamespaceNameMixin.namespace_uri`), these properties look up the
namespace prefix of the node in the parent elements (this information is
cached, so don't fear multiple retrieval):
>>> xhtml_namespace_uri = u'http://www.w3.org/1999/xhtml/'
>>> document[0][1].namespace_uri == xhtml_namespace_uri
True
>>> document[0][1][1].namespace_uri == xhtml_namespace_uri
True
>>> document[0][-1][0].namespace_uri == u'foo://bar'
True
>>> document[0][-1][0].attributes['foo:bar'].namespace_uri == u'foo://bar'
True
The namespace prefixes active on an element are available as the iterator
:attr:`Element.namespace_prefixes`:
>>> prefixes = sorted(list(document[0][-1][0].namespace_prefixes),
... key=lambda value: '' if value is None else value)
>>> prefixes[0] == None
True
>>> print(u', '.join(prefixes[1:]))
foo, t
>>> document[0][-1][0].get_namespace_uri(u'foo') == u'foo://bar'
True
>>> print(list(document[0].namespace_prefixes))
[None]
>>> document[0].get_namespace_uri(None) == u'http://www.w3.org/1999/xhtml/'
True
If an element or attribute is in no namespace, ``namespace_uri`` is
:const:`None`:
>>> document[0][-1][0].attributes['t:test'].namespace_uri == None
True
>>> document[0][-1][1].namespace_uri == None
True
If an undefined namespace prefix is used, the ``namespace_uri`` is
:const:`False`:
>>> document[0][-1][2].namespace_uri == False
True
Indexes
"""""""
On :class:`Document` instances :class:`ecoxipy.pyxom.indexing.IndexDescriptor`
attributes are defined for fast retrieval (after initially building the
index).
Use :attr:`~Document.element_by_id` to get elements by the value of their
``id`` attribute:
>>> document.element_by_id['foo'] is document[0][-1]
True
>>> 'bar' in document.element_by_id
False
:attr:`~Document.elements_by_name` allows retrieval of elements by their name:
>>> document[0][-1] in list(document.elements_by_name['foo:somexml'])
True
>>> 'html' in document.elements_by_name
False
Retrieve elements and attributes by their namespace data by using
:attr:`~Document.nodes_by_namespace`:
>>> from functools import reduce
>>> elements_and_attributes = set(
... filter(lambda node: isinstance(node, Element),
... document.descendants()
... )
... ).union(
... reduce(lambda x, y: x.union(y),
... map(lambda node: set(node.attributes.values()),
... filter(lambda node: isinstance(node, Element),
... document.descendants()
... )
... )
... )
... )
>>> set(document.nodes_by_namespace()) == set(filter(
... lambda node: node.namespace_uri is not False,
... elements_and_attributes
... ))
True
>>> set(document.nodes_by_namespace('foo://bar')) == set(filter(
... lambda node: node.namespace_uri == u'foo://bar',
... elements_and_attributes
... ))
True
>>> set(document.nodes_by_namespace(local_name='bar')) == set(filter(
... lambda node: node.local_name == u'bar',
... elements_and_attributes
... ))
True
>>> set(document.nodes_by_namespace('foo://bar', 'bar')) == set(filter(
... lambda node: node.namespace_uri == u'foo://bar' and node.local_name == u'bar',
... elements_and_attributes
... ))
True
Manipulation and Equality
^^^^^^^^^^^^^^^^^^^^^^^^^
All :class:`XMLNode` instances have attributes which allow for modification.
:class:`Document` and :class:`Element` instances also allow modification of
their contents like sequences.
Duplication and Comparisons
"""""""""""""""""""""""""""
Use :meth:`XMLNode.duplicate` to create a deep copy of a XML node:
>>> document_copy = document.duplicate()
>>> document is document_copy
False
Equality and inequality recursively compare XML nodes:
>>> document == document_copy
True
>>> document != document_copy
False
Attributes
""""""""""
The attributes of an :class:`Element` instance are available as
:attr:`Element.attributes`. This is an :class:`Attributes` instance which
contains :class:`Attribute` instances:
>>> document_copy[0][0].attributes['data']
ecoxipy.pyxom.Attribute('data', 'to quote: <&>"\\'')
>>> old_data = document_copy[0][0].attributes['data'].value
>>> document_copy[0][0].attributes['data'].value = 'foo bar'
>>> document_copy[0][0].attributes['data'].value == u'foo bar'
True
>>> 'data' in document_copy[0][0].attributes
True
>>> document == document_copy
False
>>> document != document_copy
True
>>> document_copy[0][0].attributes['data'].value = old_data
>>> document == document_copy
True
>>> document != document_copy
False
:class:`Attributes` instances allow for creation of :class:`Attribute`
instances:
>>> somexml = document_copy[0][-1]
>>> foo_attr = somexml[0].attributes.create_attribute('foo:foo', 'bar')
>>> foo_attr is somexml[0].attributes['foo:foo']
True
>>> foo_attr == somexml[0].attributes['foo:foo']
True
>>> foo_attr != somexml[0].attributes['foo:foo']
False
>>> 'foo:foo' in somexml[0].attributes
True
>>> foo_attr.namespace_uri == u'foo://bar'
True
Attributes may be removed:
>>> somexml[0].attributes.remove(foo_attr)
>>> 'foo:foo' in somexml[0].attributes
False
>>> foo_attr.parent == None
True
>>> foo_attr.namespace_uri == False
True
You can also add an attribute to an element's attributes, it is automatically
moved if it belongs to another element's attributes:
>>> somexml[0].attributes.add(foo_attr)
>>> 'foo:foo' in somexml[0].attributes
True
>>> foo_attr.parent == somexml[0].attributes
True
>>> foo_attr.parent != somexml[0].attributes
False
>>> foo_attr.namespace_uri == u'foo://bar'
True
>>> del somexml[0].attributes['foo:foo']
>>> 'foo:foo' in somexml[0].attributes
False
>>> attr = document[0][-1].attributes['foo:bar']
>>> attr.name = 'test'
>>> attr.namespace_prefix is None
True
>>> print(attr.local_name)
test
Documents and Elements
""""""""""""""""""""""
>>> document_copy[0].insert(1, document_copy[0][0])
>>> document_copy[0][0] == document[0][1]
True
>>> document_copy[0][0] != document[0][1]
False
>>> document_copy[0][1] == document[0][0]
True
>>> document_copy[0][1] != document[0][0]
False
>>> p_element = document_copy[0][0]
>>> document_copy[0].remove(p_element)
>>> document_copy[0][0].name == u'h1' and p_element.parent is None
True
>>> p_element in document_copy[0]
False
>>> p_element.namespace_uri == False
True
>>> document_copy[0][0].append(p_element)
>>> document_copy[0][0][-1] is p_element
True
>>> p_element in document_copy[0][0]
True
>>> p_element.namespace_uri == u'http://www.w3.org/1999/xhtml/'
True
>>> p_element in document[0]
False
>>> document[0][1] in document_copy[0][0]
False
>>> document[0][1] is document_copy[0][0][-1]
False
>>> document[0][1] == document_copy[0][0][-1]
True
>>> document[0][1] != document_copy[0][0][-1]
False
>>> document[0][-1].name = 'foo'
>>> document[0][-1].namespace_prefix is None
True
>>> print(document[0][-1].local_name)
foo
Indexes and Manipulation
""""""""""""""""""""""""
If a document is modified, the indexes should be deleted. This can be done
using :func:`del` on the index attribute or calling
:meth:`~Document.delete_indexes`.
>>> del document_copy[0][-1]
>>> document_copy.delete_indexes()
>>> 'foo' in document_copy.element_by_id
False
>>> 'foo:somexml' in document_copy.elements_by_name
False
XML Serialization
^^^^^^^^^^^^^^^^^
First we remove embedded non-HTML XML, as there are multiple attributes on the
element and the order they are rendered in is indeterministic, which makes it
hard to compare:
>>> del document[0][-1]
Getting the Unicode value of an document yields the XML document serialized as
an Unicode string:
>>> document_string = u"""<!DOCTYPE article><article xmlns="http://www.w3.org/1999/xhtml/"><h1 data="to quote: <&>"'"><Example></h1><p umlaut-attribute="äöüß">Hello<em count="1"> World</em>!</p><div><data-element>äöüß <&></data-element><p attr="value">raw content</p>Some Text<br/>012345</div><!--<This is a comment!>--><?pi-target <PI content>?><?pi-without-content?></article>"""
>>> import sys
>>> if sys.version_info[0] < 3:
... unicode(document) == document_string
... else:
... str(document) == document_string
True
Getting the :func:`bytes` value of an :class:`Document` creates a byte string
of the serialized XML with the encoding specified on creation of the instance,
it defaults to "UTF-8":
>>> bytes(document) == document_string.encode('UTF-8')
True
:class:`XMLNode` instances can also generate SAX events, see
:meth:`XMLNode.create_sax_events` (note that the default
:class:`xml.sax.ContentHandler` is :class:`xml.sax.saxutils.ContentHandler`,
which does not support comments):
>>> document_string = u"""<?xml version="1.0" encoding="UTF-8"?>\\n<article xmlns="http://www.w3.org/1999/xhtml/"><h1 data="to quote: <&>"'"><Example></h1><p umlaut-attribute="äöüß">Hello<em count="1"> World</em>!</p><div><data-element>äöüß <&></data-element><p attr="value">raw content</p>Some Text<br></br>012345</div><?pi-target <PI content>?><?pi-without-content ?></article>"""
>>> import sys
>>> from io import BytesIO
>>> string_out = BytesIO()
>>> content_handler = document.create_sax_events(out=string_out)
>>> string_out.getvalue() == document_string.encode('UTF-8')
True
>>> string_out.close()
You can also create indented XML when calling the
:meth:`XMLNode.create_sax_events` by supplying the ``indent_incr`` argument:
>>> indented_document_string = u"""\\
... <?xml version="1.0" encoding="UTF-8"?>
... <article xmlns="http://www.w3.org/1999/xhtml/">
... <h1 data="to quote: <&>"'">
... <Example>
... </h1>
... <p umlaut-attribute="äöüß">
... Hello
... <em count="1">
... World
... </em>
... !
... </p>
... <div>
... <data-element>
... äöüß <&>
... </data-element>
... <p attr="value">
... raw content
... </p>
... Some Text
... <br></br>
... 012345
... </div>
... <?pi-target <PI content>?>
... <?pi-without-content ?>
... </article>
... """
>>> string_out = BytesIO()
>>> content_handler = document.create_sax_events(indent_incr=' ', out=string_out)
>>> string_out.getvalue() == indented_document_string.encode('UTF-8')
True
>>> string_out.close()
Classes
-------
Document
^^^^^^^^
.. autoclass:: Document
.. autoclass:: DocumentType
Element
^^^^^^^
.. autoclass:: Element
.. autoclass:: Attribute
.. autoclass:: Attributes
Other Nodes
^^^^^^^^^^^
.. autoclass:: Text
.. autoclass:: Comment
.. autoclass:: ProcessingInstruction
Base Classes
^^^^^^^^^^^^
.. autoclass:: XMLNode
.. autoclass:: ContainerNode
.. autoclass:: ContentNode
.. autoclass:: NamespaceNameMixin
'''
from ._common import XMLNode, ContainerNode
from ._attributes import NamespaceNameMixin, Attribute, Attributes
from ._document import DocumentType, Document
from ._element import Element
from ._content_nodes import ContentNode, Text, Comment, ProcessingInstruction
|
IvIePhisto/ECoXiPy
|
ecoxipy/pyxom/__init__.py
|
Python
|
mit
| 21,834
|
<?php
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;
/**
* appDevUrlMatcher.
*
* This class has been auto-generated
* by the Symfony Routing Component.
*/
class appDevUrlMatcher extends Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher
{
/**
* Constructor.
*/
public function __construct(RequestContext $context)
{
$this->context = $context;
}
public function match($pathinfo)
{
$allow = array();
$pathinfo = rawurldecode($pathinfo);
$context = $this->context;
$request = $this->request;
if (0 === strpos($pathinfo, '/_')) {
// _wdt
if (0 === strpos($pathinfo, '/_wdt') && preg_match('#^/_wdt/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_wdt')), array ( '_controller' => 'web_profiler.controller.profiler:toolbarAction',));
}
if (0 === strpos($pathinfo, '/_profiler')) {
// _profiler_home
if (rtrim($pathinfo, '/') === '/_profiler') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '_profiler_home');
}
return array ( '_controller' => 'web_profiler.controller.profiler:homeAction', '_route' => '_profiler_home',);
}
if (0 === strpos($pathinfo, '/_profiler/search')) {
// _profiler_search
if ($pathinfo === '/_profiler/search') {
return array ( '_controller' => 'web_profiler.controller.profiler:searchAction', '_route' => '_profiler_search',);
}
// _profiler_search_bar
if ($pathinfo === '/_profiler/search_bar') {
return array ( '_controller' => 'web_profiler.controller.profiler:searchBarAction', '_route' => '_profiler_search_bar',);
}
}
// _profiler_info
if (0 === strpos($pathinfo, '/_profiler/info') && preg_match('#^/_profiler/info/(?P<about>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_info')), array ( '_controller' => 'web_profiler.controller.profiler:infoAction',));
}
// _profiler_phpinfo
if ($pathinfo === '/_profiler/phpinfo') {
return array ( '_controller' => 'web_profiler.controller.profiler:phpinfoAction', '_route' => '_profiler_phpinfo',);
}
// _profiler_search_results
if (preg_match('#^/_profiler/(?P<token>[^/]++)/search/results$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_search_results')), array ( '_controller' => 'web_profiler.controller.profiler:searchResultsAction',));
}
// _profiler
if (preg_match('#^/_profiler/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler')), array ( '_controller' => 'web_profiler.controller.profiler:panelAction',));
}
// _profiler_router
if (preg_match('#^/_profiler/(?P<token>[^/]++)/router$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_router')), array ( '_controller' => 'web_profiler.controller.router:panelAction',));
}
// _profiler_exception
if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception')), array ( '_controller' => 'web_profiler.controller.exception:showAction',));
}
// _profiler_exception_css
if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception\\.css$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception_css')), array ( '_controller' => 'web_profiler.controller.exception:cssAction',));
}
}
// _twig_error_test
if (0 === strpos($pathinfo, '/_error') && preg_match('#^/_error/(?P<code>\\d+)(?:\\.(?P<_format>[^/]++))?$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_twig_error_test')), array ( '_controller' => 'twig.controller.preview_error:previewErrorPageAction', '_format' => 'html',));
}
}
if (0 === strpos($pathinfo, '/log')) {
if (0 === strpos($pathinfo, '/login')) {
// login
if ($pathinfo === '/login') {
return array ( '_controller' => 'BlogBundle\\Controller\\UserController::LoginAction', '_route' => 'login',);
}
// login_check
if ($pathinfo === '/login_check') {
return array('_route' => 'login_check');
}
}
// logout
if ($pathinfo === '/logout') {
return array('_route' => 'logout');
}
}
// blog_homepage
if (0 === strpos($pathinfo, '/home') && preg_match('#^/home(?:/(?P<page>[^/]++))?$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'blog_homepage')), array ( '_controller' => 'BlogBundle\\Controller\\EntryController::indexAction', 'page' => 1,));
}
if (0 === strpos($pathinfo, '/tags')) {
// blog_add_tag
if ($pathinfo === '/tags/add') {
return array ( '_controller' => 'BlogBundle\\Controller\\TagController::addAction', '_route' => 'blog_add_tag',);
}
// blog_index_tag
if ($pathinfo === '/tags') {
return array ( '_controller' => 'BlogBundle\\Controller\\TagController::indexAction', '_route' => 'blog_index_tag',);
}
// blog_delete_tag
if (0 === strpos($pathinfo, '/tags/delete') && preg_match('#^/tags/delete/(?P<id>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'blog_delete_tag')), array ( '_controller' => 'BlogBundle\\Controller\\TagController::deleteAction',));
}
}
if (0 === strpos($pathinfo, '/categor')) {
if (0 === strpos($pathinfo, '/categories')) {
// blog_add_category
if ($pathinfo === '/categories/add') {
return array ( '_controller' => 'BlogBundle\\Controller\\CategoryController::addAction', '_route' => 'blog_add_category',);
}
// blog_index_category
if ($pathinfo === '/categories') {
return array ( '_controller' => 'BlogBundle\\Controller\\CategoryController::indexAction', '_route' => 'blog_index_category',);
}
// blog_delete_category
if (0 === strpos($pathinfo, '/categories/delete') && preg_match('#^/categories/delete/(?P<id>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'blog_delete_category')), array ( '_controller' => 'BlogBundle\\Controller\\CategoryController::deleteAction',));
}
// blog_edit_category
if (0 === strpos($pathinfo, '/categories/edit') && preg_match('#^/categories/edit/(?P<id>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'blog_edit_category')), array ( '_controller' => 'BlogBundle\\Controller\\CategoryController::editAction',));
}
}
// blog_read_category
if (0 === strpos($pathinfo, '/category') && preg_match('#^/category/(?P<id>[^/]++)(?:/(?P<page>[^/]++))?$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'blog_read_category')), array ( '_controller' => 'BlogBundle\\Controller\\CategoryController::categoryAction', 'page' => 1,));
}
}
if (0 === strpos($pathinfo, '/entries')) {
// blog_add_entry
if ($pathinfo === '/entries/add') {
return array ( '_controller' => 'BlogBundle\\Controller\\EntryController::addAction', '_route' => 'blog_add_entry',);
}
// blog_delete_entry
if (0 === strpos($pathinfo, '/entries/delete') && preg_match('#^/entries/delete/(?P<id>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'blog_delete_entry')), array ( '_controller' => 'BlogBundle\\Controller\\EntryController::deleteAction',));
}
// blog_edit_entry
if (0 === strpos($pathinfo, '/entries/edit') && preg_match('#^/entries/edit/(?P<id>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'blog_edit_entry')), array ( '_controller' => 'BlogBundle\\Controller\\EntryController::editAction',));
}
}
// blog_lang
if (0 === strpos($pathinfo, '/lang') && preg_match('#^/lang/(?P<_locale>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'blog_lang')), array ( '_controller' => 'BlogBundle\\Controller\\DefaultController::langAction',));
}
// mi_homepage
if ($pathinfo === '/mi-bundle') {
return array ( '_controller' => 'MiBundle\\Controller\\DefaultController::indexAction', '_route' => 'mi_homepage',);
}
if (0 === strpos($pathinfo, '/pruebas')) {
// pruebas_index
if (preg_match('#^/pruebas/(?P<lang>es|wb|fr)(?:/(?P<name>[a-zA-z]*)(?:/(?P<page>\\d+))?)?$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('GET', 'POST', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'POST', 'HEAD'));
goto not_pruebas_index;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'pruebas_index')), array ( '_controller' => 'AppBundle\\Controller\\PruebasController::indexAction', 'name' => 'valor_defecto', 'page' => 1,));
}
not_pruebas_index:
// pruebas_add
if ($pathinfo === '/pruebas/add') {
return array ( '_controller' => 'AppBundle\\Controller\\PruebasController::addAction', '_route' => 'pruebas_add',);
}
// pruebas_lectura
if ($pathinfo === '/pruebas/read') {
return array ( '_controller' => 'AppBundle\\Controller\\PruebasController::readAction', '_route' => 'pruebas_lectura',);
}
// pruebas_actulizar
if (0 === strpos($pathinfo, '/pruebas/update') && preg_match('#^/pruebas/update/(?P<id>[^/]++)/(?P<titulo>[^/]++)/(?P<descripcion>[^/]++)/(?P<precio>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'pruebas_actulizar')), array ( '_controller' => 'AppBundle\\Controller\\PruebasController::updateAction',));
}
// pruebas_borrar
if (0 === strpos($pathinfo, '/pruebas/borrar') && preg_match('#^/pruebas/borrar/(?P<id>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'pruebas_borrar')), array ( '_controller' => 'AppBundle\\Controller\\PruebasController::deleteAction',));
}
// pruebas_native
if ($pathinfo === '/pruebas/nativo') {
return array ( '_controller' => 'AppBundle\\Controller\\PruebasController::nativeSqlAction', '_route' => 'pruebas_native',);
}
// pruebas_form
if ($pathinfo === '/pruebas/form') {
return array ( '_controller' => 'AppBundle\\Controller\\PruebasController::formAction', '_route' => 'pruebas_form',);
}
// pruebas_validate_email
if (0 === strpos($pathinfo, '/pruebas/validar-email') && preg_match('#^/pruebas/validar\\-email/(?P<email>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => 'pruebas_validate_email')), array ( '_controller' => 'AppBundle\\Controller\\PruebasController::validarEmailAction',));
}
}
// homepage
if (rtrim($pathinfo, '/') === '') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'homepage');
}
return array ( '_controller' => 'AppBundle\\Controller\\DefaultController::indexAction', '_route' => 'homepage',);
}
// holamundo
if ($pathinfo === '/hello-world') {
return array ( '_controller' => 'AppBundle\\Controller\\DefaultController::HolaMundoAction', '_route' => 'holamundo',);
}
throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException();
}
}
|
jcg678/pruebasSymfony
|
var/cache/dev/appDevUrlMatcher.php
|
PHP
|
mit
| 13,895
|
---
author: slowe
categories: Information
comments: true
date: 2009-12-22T23:14:44Z
slug: virtualization-short-take-32
tags:
- Networking
- Storage
- Virtualization
- VMware
- vSphere
title: 'Virtualization Short Take #32'
url: /2009/12/22/virtualization-short-take-32/
wordpress_id: 1772
---
Here it is---the last Virtualization Short Take of 2009! This is just a small collection of various virtualization-related links and articles that I've gathered over the last few weeks (OK, maybe more than a few weeks).
* Scott Drummonds posted a good article with a [performance comparison](http://vpivot.com/2009/11/18/performance-of-thin-provisioned-disks/) of thick provisioned disks vs. thin provisioned disks. This is good information and helps to clear up a lot of misinformation about the behavior of thin provisioned disks.
* Interested in using the software iSCSI initiator with a dvSwitch and multiple paths? [This article](http://goingvirtual.wordpress.com/2009/12/01/vsphere-4-0-update-1-with-software-iscsi-and-2-paths-on-dvswitch/) can give you the information you need to get started.
* Frank Denneman has a great article providing some [details on memory reservations and memory usage](http://frankdenneman.wordpress.com/2009/12/08/impact-of-memory-reservation/). It's definitely worth a read, as is this post on the [impact of guest OS type mismatch](http://frankdenneman.wordpress.com/2009/12/15/impact-of-mismatch-guest-os-type/). See, there is a reason why it's important to make sure you select the _correct_ guest OS type when creating VMs.
* I've written about the paravirtualized SCSI (PVSCSI) driver [before][1], but Scott Sauer over at Virtual Insanity has a great two-part series on PVSCSI that is definitely worth a read ([part 1](http://www.virtualinsanity.com/index.php/2009/11/21/more-bang-for-your-buck-with-pvscsi-part-1/) and [part 2](http://www.virtualinsanity.com/index.php/2009/12/01/more-bang-for-your-buck-with-pvscsi-part-2/)).
* Although a bit dated now, Dave Lawrence has a great [review of some of November's technical white papers](http://vmguy.com/wordpress/index.php/archives/1248). He references the thin provisioning performance paper that's also referenced in Scott Drummond's post above, as well as a white paper on optimizing SRM performance. Thanks for bringing our attention to these documents, Dave!
* The release of VMware View 4 brings with it PCoIP, which is supposed to bring enhanced performance over older display protocols. Unfortunately, everything I was hearing was that PCoIP was incompatible with many WAN acceleration solutions. So I was quite puzzled at [this press release](http://www.businesswire.com/portal/site/home/permalink/?ndmViewId=news_view&newsId=20091207005609&newsLang=en). Reading the press release a bit more closely, though, it would seem that Expand's solution doesn't actually optimize or accelerate PCoIP; rather, it enables it to be tunneled and applies Quality of Service (QoS). Something is better than nothing, I guess.
* Rick Scherer [describes a strange issue](http://vmwaretips.com/wp/2009/12/09/strange-vcenter-40-u1-and-esxi-40-u1-ssl-issue/) with vCenter Server 4.0 Update 1 and VMware ESXi 4.0 Update 1. Rick was seeing a number of strange symptoms, including ESXi hosts suddenly disconnecting from vCenter Server. Last time I checked Rick still hadn't identified the root cause, although the symptoms he was seeing have since disappeared.
* Stu provides [a thorough explanation](http://vinternals.com/2009/12/why-you-shouldnt-update-vcenter-if-using-esxi-yet/) of why VMware is recommending not to install vCenter Server 4.0 Update 1 when managing VMware ESXi 4.0 hosts.
* Need to install the HP Management Agents on VMware ESX 4.0? Here are some [helpful instructions](http://blog.mrpol.nl/2009/11/03/installing-hp-insight-management-agents-on-vmware-vsphere-4-server/).
* Nigel Poulton has started a great series on rack area networks (RANs), of which a key component is I/O virtualization. So far, Nigel has published [part 1](http://blog.nigelpoulton.com/ran-rack-area-networking/) (introducing the concept of a RAN), [part 2](http://blog.nigelpoulton.com/rack-area-networking-iov/) (IOV's role in a RAN), and [part 3](http://blog.nigelpoulton.com/ran-iov-and-hairpin-turns/) (IOV and hairpin turns). Part 2, in particular, has a good discussion of SR-IOV and MR-IOV. Nigel's discussion of SR-IOV is a good complement to [my own][2].
* Greg Schulz also has [a lengthy article](http://storageio.com/blog/?p=729) on I/O virtualization.
* Curious to know why NUMA is important with vSphere? Network Computing blogger Jake McTigue (with whom I had the honor of participating on a recent virtual networking webcast) has a [good overview of NUMA](http://www.networkcomputing.com/virtualization/harnessing-vsphere-performance-benefits-for-numa.php) and what it means for virtualized environments. It's worth a read if you're not already familiar with NUMA.
* Need more information on storage alignment and VMFS block sizes? Check out [this VIOPS document](http://viops.vmware.com/home/docs/DOC-1407).
I also have a whole list of other links that I haven't had the chance to read yet but that look like they might be interesting or useful:
[A handy new addition to the Command Line Tool for View 4](http://www.virtualinsanity.com/index.php/2009/12/08/a-handy-new-addition-to-the-command-line-tool-for-view-4/)
[Whats what in VMware View and VDI Land](http://virtualgeek.typepad.com/virtual_geek/2009/12/whats-what-in-vmware-view-and-vdi-land.html)
[How to get PCoIP with View 4 to work every time!](http://www.thatsmyview.net/2009/12/18/how-to-get-pcoip-with-view-4-to-work-every-time/)
[Revisiting the Components of the Cisco Nexus 1000v](http://jasonnash.wordpress.com/2009/12/18/revisiting-the-components-of-the-cisco-nexus-1000v/)
[File Virtualization The short primer](http://devcentral.f5.com/weblogs/dmacvittie/archive/2009/12/06/file-virtualizationhellip-the-short-primer.aspx)
[Is Your Blade Ready for Virtualization? A Math Lesson](http://www.dailyhypervisor.com/2009/12/19/is-your-blade-ready-for-virtualization-a-math-lesson/comment-page-1/#comment-213)
[RSA SecureBook for VMware View hardening now publicly available!](http://virtualgeek.typepad.com/virtual_geek/2009/12/rsa-securebook-for-vmware-view-hardening-now-publicly-available.html)
I guess that's enough for now. If you have any other useful, unique, or interesting virtualization-related links, feel free to share them in the comments. Thanks for reading!
[1]: {{< relref "2009-07-05-another-reason-not-to-use-pvscsi-or-vmxnet3.md" >}}
[2]: {{< relref "2009-12-02-what-is-sr-iov.md" >}}
|
lowescott/weblog
|
content/post/2009-12-22-virtualization-short-take-32.md
|
Markdown
|
mit
| 6,685
|
## 16: Copying files
Copying files with the [cp][] (copy) command is very similar to moving them. Remember to always specify a source and a target location. Let's create a new file and make a copy of it:
```bash
learner@:learning_unix$ touch file1
learner@:learning_unix$ cp file1 file2
learner@:learning_unix$ ls
file1 file2
```
What if we wanted to copy files from a different directory to our current directory? Let's put a file in our home directory (specified by `~` remember) and copy it to the current directory (`learning_unix`):
```bash
learner@:learning_unix$ touch ~/file3
learner@:learning_unix$ ls ~
file3 learning_unix example_data
learner@:learning_unix$ cp ~/file3 .
learner@:learning_unix$ ls
file1 file2 file3
```
This last step introduces another new concept. In Unix, the current directory can be represented by a `.` (dot) character. You will mostly use this only for copying files to the current directory that you are in. Compare the following:
```bash
ls
ls .
ls ./
```
In this case, using the dot is somewhat pointless because `ls` will already list the contents of the current directory by default. Also note how the trailing slash is optional. You can use `rm` to remove the temporary files.
Finally, let's clean up this directory. Note the use of the `*` wildcard, which allows us to delete all three files at once.
```bash
learner@:learning_unix$ rm file*
```
[cp]: http://en.wikipedia.org/wiki/Cp_(Unix)
|
iracooke/BC2023
|
lessons/chapters_md/16_copying_files.md
|
Markdown
|
mit
| 1,449
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| WARNING: You MUST set this value!
|
| If it is not set, then CodeIgniter will try guess the protocol and path
| your installation, but due to security concerns the hostname will be set
| to $_SERVER['SERVER_ADDR'] if available, or localhost otherwise.
| The auto-detection mechanism exists only for convenience during
| development and MUST NOT be used in production!
|
| If you need to allow multiple domains, remember that this file is still
| a PHP script and you can easily do that on your own.
|
*/
$config['base_url'] = 'oranta.com';
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = 'index.php';
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string. The default setting of 'REQUEST_URI' works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'REQUEST_URI' Uses $_SERVER['REQUEST_URI']
| 'QUERY_STRING' Uses $_SERVER['QUERY_STRING']
| 'PATH_INFO' Uses $_SERVER['PATH_INFO']
|
| WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded!
*/
$config['uri_protocol'] = 'REQUEST_URI';
/*
|--------------------------------------------------------------------------
| URL suffix
|--------------------------------------------------------------------------
|
| This option allows you to add a suffix to all URLs generated by CodeIgniter.
| For more information please see the user guide:
|
| https://codeigniter.com/user_guide/general/urls.html
*/
$config['url_suffix'] = '';
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| This determines which set of language files should be used. Make sure
| there is an available translation if you intend to use something other
| than english.
|
*/
$config['language'] = 'english';
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
| See http://php.net/htmlspecialchars for a list of supported charsets.
|
*/
$config['charset'] = 'UTF-8';
/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the 'hooks' feature you must enable it by
| setting this variable to TRUE (boolean). See the user guide for details.
|
*/
$config['enable_hooks'] = FALSE;
/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries. For more information please see the user guide:
|
| https://codeigniter.com/user_guide/general/core_classes.html
| https://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'MY_';
/*
|--------------------------------------------------------------------------
| Composer auto-loading
|--------------------------------------------------------------------------
|
| Enabling this setting will tell CodeIgniter to look for a Composer
| package auto-loader script in application/vendor/autoload.php.
|
| $config['composer_autoload'] = TRUE;
|
| Or if you have your vendor/ directory located somewhere else, you
| can opt to set a specific path as well:
|
| $config['composer_autoload'] = '/path/to/vendor/autoload.php';
|
| For more information about Composer, please visit http://getcomposer.org/
|
| Note: This will NOT disable or override the CodeIgniter-specific
| autoloading (application/config/autoload.php)
*/
$config['composer_autoload'] = FALSE;
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible. By default only these are allowed: a-z 0-9~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| The configured value is actually a regular expression character group
| and it will be executed as: ! preg_match('/^[<permitted_uri_chars>]+$/i
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
/*
|--------------------------------------------------------------------------
| Enable Query Strings
|--------------------------------------------------------------------------
|
| By default CodeIgniter uses search-engine friendly segment based URLs:
| example.com/who/what/where/
|
| By default CodeIgniter enables access to the $_GET array. If for some
| reason you would like to disable it, set 'allow_get_array' to FALSE.
|
| You can optionally enable standard query string based URLs:
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The other items let you set the query string 'words' that will
| invoke your controllers and its functions:
| example.com/index.php?c=controller&m=function
|
| Please note that some of the helpers won't work as expected when
| this feature is enabled, since CodeIgniter is designed primarily to
| use segment based URLs.
|
*/
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd';
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disables logging, Error logging TURNED OFF
| 1 = Error Messages (including PHP errors)
| 2 = Debug Messages
| 3 = Informational Messages
| 4 = All Messages
|
| You can also pass an array with threshold levels to show individual error types
|
| array(2) = Debug Messages, without Error Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
/*
|--------------------------------------------------------------------------
| Error Logging Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/logs/ directory. Use a full server path with trailing slash.
|
*/
$config['log_path'] = '';
/*
|--------------------------------------------------------------------------
| Log File Extension
|--------------------------------------------------------------------------
|
| The default filename extension for log files. The default 'php' allows for
| protecting the log files via basic scripting, when they are to be stored
| under a publicly accessible directory.
|
| Note: Leaving it blank will default to 'php'.
|
*/
$config['log_file_extension'] = '';
/*
|--------------------------------------------------------------------------
| Log File Permissions
|--------------------------------------------------------------------------
|
| The file system permissions to be applied on newly created log files.
|
| IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
| integer notation (i.e. 0700, 0644, etc.)
*/
$config['log_file_permissions'] = 0644;
/*
|--------------------------------------------------------------------------
| Date Format for Logs
|--------------------------------------------------------------------------
|
| Each item that is logged has an associated date. You can use PHP date
| codes to set your own date formatting
|
*/
$config['log_date_format'] = 'Y-m-d H:i:s';
/*
|--------------------------------------------------------------------------
| Error Views Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/views/errors/ directory. Use a full server path with trailing slash.
|
*/
$config['error_views_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/cache/ directory. Use a full server path with trailing slash.
|
*/
$config['cache_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Include Query String
|--------------------------------------------------------------------------
|
| Whether to take the URL query string into consideration when generating
| output cache files. Valid options are:
|
| FALSE = Disabled
| TRUE = Enabled, take all query parameters into account.
| Please be aware that this may result in numerous cache
| files generated for the same page over and over again.
| array('q') = Enabled, but only take into account the specified list
| of query parameters.
|
*/
$config['cache_query_string'] = FALSE;
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| If you use the Encryption class, you must set an encryption key.
| See the user guide for more info.
|
| https://codeigniter.com/user_guide/libraries/encryption.html
|
*/
$config['encryption_key'] = '';
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'sess_driver'
|
| The storage driver to use: files, database, redis, memcached
|
| 'sess_cookie_name'
|
| The session cookie name, must contain only [0-9a-z_-] characters
|
| 'sess_expiration'
|
| The number of SECONDS you want the session to last.
| Setting to 0 (zero) means expire when the browser is closed.
|
| 'sess_save_path'
|
| The location to save sessions to, driver dependent.
|
| For the 'files' driver, it's a path to a writable directory.
| WARNING: Only absolute paths are supported!
|
| For the 'database' driver, it's a table name.
| Please read up the manual for the format with other session drivers.
|
| IMPORTANT: You are REQUIRED to set a valid save path!
|
| 'sess_match_ip'
|
| Whether to match the user's IP address when reading the session data.
|
| WARNING: If you're using the database driver, don't forget to update
| your session table's PRIMARY KEY when changing this setting.
|
| 'sess_time_to_update'
|
| How many seconds between CI regenerating the session ID.
|
| 'sess_regenerate_destroy'
|
| Whether to destroy session data associated with the old session ID
| when auto-regenerating the session ID. When set to FALSE, the data
| will be later deleted by the garbage collector.
|
| Other session cookie settings are shared with the rest of the application,
| except for 'cookie_prefix' and 'cookie_httponly', which are ignored here.
|
*/
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path' = Typically will be a forward slash
| 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists.
| 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript)
|
| Note: These settings (with the exception of 'cookie_prefix' and
| 'cookie_httponly') will also affect sessions.
|
*/
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
/*
|--------------------------------------------------------------------------
| Standardize newlines
|--------------------------------------------------------------------------
|
| Determines whether to standardize newline characters in input data,
| meaning to replace \r\n, \r, \n occurrences with the PHP_EOL value.
|
| This is particularly useful for portability between UNIX-based OSes,
| (usually \n) and Windows (\r\n).
|
*/
$config['standardize_newlines'] = FALSE;
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
| WARNING: This feature is DEPRECATED and currently available only
| for backwards compatibility purposes!
|
*/
$config['global_xss_filtering'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
| 'csrf_regenerate' = Regenerate token on every submission
| 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks
*/
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
/*
|--------------------------------------------------------------------------
| Output Compression
|--------------------------------------------------------------------------
|
| Enables Gzip output compression for faster page loads. When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| Only used if zlib.output_compression is turned off in your php.ini.
| Please do not use it together with httpd-level output compression.
|
| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts. For
| compression to work, nothing can be sent before the output buffer is called
| by the output class. Do not 'echo' any values with compression enabled.
|
*/
$config['compress_output'] = FALSE;
/*
|--------------------------------------------------------------------------
| Master Time Reference
|--------------------------------------------------------------------------
|
| Options are 'local' or any PHP supported timezone. This preference tells
| the system whether to use your server's local time as the master 'now'
| reference, or convert it to the configured one timezone. See the 'date
| helper' page of the user guide for information regarding date handling.
|
*/
$config['time_reference'] = 'local';
/*
|--------------------------------------------------------------------------
| Rewrite PHP Short Tags
|--------------------------------------------------------------------------
|
| If your PHP installation does not have short tag support enabled CI
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files. Options are TRUE or FALSE (boolean)
|
| Note: You need to have eval() enabled for this to work.
|
*/
$config['rewrite_short_tags'] = FALSE;
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy
| IP addresses from which CodeIgniter should trust headers such as
| HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify
| the visitor's IP address.
|
| You can use both an array or a comma-separated list of proxy addresses,
| as well as specifying whole subnets. Here are a few examples:
|
| Comma-separated: '10.0.1.200,192.168.5.0/24'
| Array: array('10.0.1.200', '192.168.5.0/24')
*/
$config['proxy_ips'] = '';
|
oranta-dev/oranta
|
application/config/config.php
|
PHP
|
mit
| 18,137
|
# encoding: utf-8
# This file is distributed under New Relic's license terms.
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'sinatra', 'sinatra_test_cases'))
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..', 'agent_helper'))
require 'newrelic_rpm'
require 'sinatra'
class DeferredSinatraTestApp < Sinatra::Base
include NewRelic::Agent::Instrumentation::Rack
configure do
# display exceptions so we see what's going on
disable :show_exceptions
# create a condition (sintra's version of a before_filter) that returns the
# value that was passed into it.
set :my_condition do |boolean|
condition do
halt 404 unless boolean
end
end
end
get '/user/login' do
"please log in"
end
# this action will always return 404 because of the condition.
get '/user/:id', :my_condition => false do |id|
"Welcome #{id}"
end
get '/raise' do
raise "Uh-oh"
end
# check that pass works properly
condition { pass { halt 418, "I'm a teapot." } }
get('/pass') { }
get '/pass' do
"I'm not a teapot."
end
class Error < StandardError; end
error(Error) { halt 200, 'nothing happened' }
condition { raise Error }
get('/error') { }
condition do
raise "Boo" if $precondition_already_checked
$precondition_already_checked = true
end
get('/precondition') { 'precondition only happened once' }
get '/route/:name' do |name|
# usually this would be a db test or something
pass if name != 'match'
'first route'
end
get '/route/no_match' do
'second route'
end
before '/filtered' do
@filtered = true
end
get '/filtered' do
@filtered ? 'got filtered' : 'nope'
end
get /\/regex.*/ do
"Yeah, regex's!"
end
end
class DeferredSinatraTest < MiniTest::Unit::TestCase
include SinatraTestCases
def app
Rack::Builder.new( DeferredSinatraTestApp ).to_app
end
def test_ignores_route_metrics
# Can't use 'newrelic_ignore' if newrelic was loaded before sinatra, as the
# instrumentation doesn't load until Rack is building the app to run it.
end
# (RUBY-1169)
def test_only_tries_deferred_detection_once
Rack::Builder.new( DeferredSinatraTestApp ).to_app
::DependencyDetection.expects( :detect! ).never
Rack::Builder.new( DeferredSinatraTestApp ).to_app
end
end
|
jinutm/silvfinal
|
vendor/bundle/ruby/2.1.0/gems/newrelic_rpm-3.6.9.171/test/multiverse/suites/deferred_instrumentation/sinatra_test.rb
|
Ruby
|
mit
| 2,456
|
#pragma once
#include <iostream>
#include "Exception.h"
template<class T>
class List
{
private:
class ListNode
{
public:
/*
Listnode Constructor sets the next and previous pointers to nullptr to make sure they arnt pointing to garbage
no returns
*/
ListNode()
{
Next = nullptr;
Previous = nullptr;
}
/*
List Node Copy Constructor creates a new objects when the list node is created
@param newobj the object being created
no returns
*/
ListNode(T newobj)
{
Next = nullptr;
Previous = nullptr;
obj = newobj;
}
~ListNode()
{
}
/*
Pointers pointing to the next and previous objects in the list.
*/
ListNode * Next;
ListNode * Previous;
T obj;
};
/*
The first and last objects of the list
*/
ListNode * m_first;
ListNode * m_last;
//Number of elements in the list
float m_eleNum = 0;
public:
class Iterator
{
public:
Iterator() {};
/*
Iterator copy Constructor creates copy iterator
@param other another iterator
no returns
*/
Iterator(const Iterator & other) { ptr = other.ptr; };
~Iterator() {};
ListNode * ptr;
/*
++ operator overloader for going to the next object in the list (ptr++)
no returns
*/
void operator++(int) { ptr = ptr->Next; };
/*
++ operator overloader for going to the next object in the list (++ptr)
no returns
*/
void operator++() { ptr = ptr->Next; };
/*
-- operator overloader for going to the previous object in the list (--ptr)
no returns
*/
void operator--() { ptr = ptr->Previous; };
/*
-- operator overloader for going to the previous object in the list (ptr--)
no returns
*/
void operator--(int) { ptr = ptr->Previous; };
/*
+= operator overloader for going to the previous object in the list (--ptr)
no returns
*/
void operator+=(int position)
{
for (int i = 1; i < position; i++)
{
ptr = ptr->Next;
}
};
/*
!= operator overloader for checking whether two iterators dont equal
returns false
*/
bool operator!=(const Iterator & other) { return ptr != other.ptr; };
/*
== operator overloader for checking whether two iterators equal
returns true
*/
bool operator==(const Iterator & other) { return ptr == other.ptr; };
/*
= operator overloader for asigning two iterators
returns iterator
*/
Iterator &operator=(const Iterator & other) { ptr = other.ptr; return *this; };
/*
-> operator overloader for pointing to objects
returns object pointed to
*/
T *operator ->()
{
return &ptr->obj;
};
/*
-> operator overloader for pointing to objects (const correct version)
returns object pointed to
*/
const Iterator *operator ->()const
{
return *this;
}
/*
* operator overloader for pointing to and object
returns object
*/
T &operator*() { return ptr->obj; };
};
/*
Iterator end function that gets the end of the list
returns nullptr
*/
Iterator end()
{
Iterator temp;
temp.ptr = nullptr;
return temp;
};
/*
Iterator begin function that gets the beginning of the list
returns the first node
*/
Iterator begin()
{
Iterator temp;
temp.ptr = m_first;
return temp;
};
/*
get size function gets how many elements in the list
returns nullptr
*/
float getSize() { return m_eleNum; };
List() {};
~List() {};
/*
puts an elemement in the start of the list
@param value the object being put into the list
no returns
*/
void pushFront(const T value);
/*
puts an elemement in the back of the list
@param value the object being put into the list
no returns
*/
void pushBack(const T value);
/*
puts an elemement in the start of the list
@param value the object being put into the list
@param element where in the list to put the object
no returns
*/
void insert(int element, const T & value);
/*
deletes the first element in the list
no returns
*/
void popFront();
/*
deletes the last element in the list
no returns
*/
void popBack();
/*
deletes the list
no returns
*/
void deleteList();
/*
deletes a specific position in the list
@param position what position in the list you want to delete
no returns
*/
void deletePosition(float position);
/*
gets the last element in the list
returns the last object in the list
*/
T& last();
};
template<class T>
inline void List<T>::pushFront(const T value)
{
if (m_eleNum < 0)
{
exceptTHROW("The number of elements in tree is a negative");
}
if (m_eleNum == 0)
{
m_first = new ListNode(value);
m_last = m_first;
}
else
{
ListNode * N = new ListNode();
N->Previous = nullptr;
N->Next = m_first;
m_first->Previous = N;
m_first = N;
m_first->obj = value;
}
m_eleNum++;
}
template<class T>
inline void List<T>::pushBack(const T value)
{
if (m_eleNum < 0)
{
exceptTHROW("The number of elements in tree is a negative");
}
if (m_eleNum == 0)
{
m_last = new ListNode(value);
m_first = m_last;
}
else
{
ListNode * N = new ListNode();
N->Next = nullptr;
N->Previous = m_last;
m_last->Next = N;
m_last = N;
m_last->obj = value;
}
m_eleNum++;
}
template<class T>
inline void List<T>::popFront()
{
if (m_eleNum <= 0)
{
exceptTHROW("Tried to delete a node or list that didnt exist");
}
if (m_eleNum == 1)
{
deleteList();
}
else
{
ListNode * holder = m_first->Next;
delete m_first;
holder->Previous = nullptr;
m_first = holder;
m_eleNum--;
}
}
template<class T>
inline void List<T>::popBack()
{
if (m_eleNum <= 0)
{
exceptTHROW("Tried to delete a node or list that didnt exist");
}
if (m_eleNum == 1)
{
deleteList();
}
else
{
ListNode * holder = m_last->Previous;
delete m_last;
holder->Next = nullptr;
m_last = holder;
m_eleNum--;
}
}
template<class T>
inline void List<T>::insert(int element, const T & value)
{
if (element < 0 || element > m_eleNum)
{
exceptTHROW("Trying to insert outside the boundries of the list");
}
if (element == 0)
{
pushFront(value);
}
else if (element == m_eleNum)
{
pushBack(value);
}
else
{
List<T>::Iterator holder = begin();
holder += (element);
ListNode * N = new ListNode();
N->Next = (holder.ptr);
N->Previous = holder.ptr->Previous;
(holder.ptr)->Previous->Next = N;
//(holder.ptr)->Next = N;
N->obj = value;
m_eleNum++;
}
}
template<class T>
inline void List<T>::deleteList()
{
if (m_eleNum < 0)
{
exceptTHROW("Trying to delete a list that doesnt exist");
}
int listDel = 0;
ListNode * Start = m_first;
for (int i = 0; i < m_eleNum; i++)
{
m_first = m_first->Next;
delete Start;
Start = m_first;
listDel++;
}
m_eleNum = m_eleNum - listDel;
m_first = nullptr;
m_last = nullptr;
}
template<class T>
inline void List<T>::deletePosition(float position)
{
if (position < 0 || position > m_eleNum)
{
exceptTHROW("Trying to delete outside the boundries of the list");
}
if (position == 0)
{
popFront();
}
else if (position == m_eleNum)
{
popBack();
}
else
{
List<T>::Iterator holder = begin();
holder += (position);
(holder.ptr)->Next->Previous = (holder.ptr)->Previous;
(holder.ptr)->Previous->Next = (holder.ptr)->Next;
delete holder.ptr;
m_eleNum--;
}
}
template<class T>
inline T & List<T>::last()
{
if (m_eleNum < 0)
{
exceptTHROW("Trying to get the last element of a list that doesnt exist");
}
return m_last->obj;
}
|
ASharpy/AI-Project
|
Containers/Source/List.h
|
C
|
mit
| 7,404
|
/*
* Copyright © 2013 Intel Corporation
* Copyright © 2013 Jonas Ådahl
*
* 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 (including the
* next paragraph) 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.
*/
#include "config.h"
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <libinput.h>
#include <libudev.h>
#include "compositor.h"
#include "launcher-util.h"
#include "libinput-seat.h"
#include "libinput-device.h"
#include "shared/helpers.h"
static const char default_seat[] = "seat0";
static const char default_seat_name[] = "default";
static void
process_events(struct udev_input *input);
static struct udev_seat *
udev_seat_create(struct udev_input *input, const char *seat_name);
static void
udev_seat_destroy(struct udev_seat *seat);
static void
device_added(struct udev_input *input, struct libinput_device *libinput_device)
{
struct weston_compositor *c;
struct evdev_device *device;
struct weston_output *output;
const char *seat_name;
const char *output_name;
struct libinput_seat *libinput_seat;
struct weston_seat *seat;
struct udev_seat *udev_seat;
c = input->compositor;
libinput_seat = libinput_device_get_seat(libinput_device);
seat_name = libinput_seat_get_logical_name(libinput_seat);
udev_seat = udev_seat_get_named(input, seat_name);
if (!udev_seat)
return;
seat = &udev_seat->base;
device = evdev_device_create(libinput_device, seat);
if (device == NULL)
return;
udev_seat = (struct udev_seat *) seat;
wl_list_insert(udev_seat->devices_list.prev, &device->link);
if (seat->output && seat->pointer)
weston_pointer_clamp(seat->pointer,
&seat->pointer->x,
&seat->pointer->y);
output_name = libinput_device_get_output_name(libinput_device);
if (output_name) {
device->output_name = strdup(output_name);
wl_list_for_each(output, &c->output_list, link)
if (output->name &&
strcmp(output->name, device->output_name) == 0)
evdev_device_set_output(device, output);
} else if (device->output == NULL && !wl_list_empty(&c->output_list)) {
output = container_of(c->output_list.next,
struct weston_output, link);
evdev_device_set_output(device, output);
}
if (!input->suspended)
weston_seat_repick(seat);
}
static void
device_removed(struct udev_input *input, struct libinput_device *libinput_device)
{
struct evdev_device *device;
device = libinput_device_get_user_data(libinput_device);
evdev_device_destroy(device);
}
static void
udev_seat_remove_devices(struct udev_seat *seat)
{
struct evdev_device *device, *next;
wl_list_for_each_safe(device, next, &seat->devices_list, link) {
evdev_device_destroy(device);
}
}
void
udev_input_disable(struct udev_input *input)
{
if (input->suspended)
return;
libinput_suspend(input->libinput);
process_events(input);
input->suspended = 1;
}
static int
udev_input_process_event(struct libinput_event *event)
{
struct libinput *libinput = libinput_event_get_context(event);
struct libinput_device *libinput_device =
libinput_event_get_device(event);
struct udev_input *input = libinput_get_user_data(libinput);
int handled = 1;
switch (libinput_event_get_type(event)) {
case LIBINPUT_EVENT_DEVICE_ADDED:
device_added(input, libinput_device);
break;
case LIBINPUT_EVENT_DEVICE_REMOVED:
device_removed(input, libinput_device);
break;
default:
handled = 0;
}
return handled;
}
static void
process_event(struct libinput_event *event)
{
if (udev_input_process_event(event))
return;
if (evdev_device_process_event(event))
return;
}
static void
process_events(struct udev_input *input)
{
struct libinput_event *event;
while ((event = libinput_get_event(input->libinput))) {
process_event(event);
libinput_event_destroy(event);
}
}
static int
udev_input_dispatch(struct udev_input *input)
{
if (libinput_dispatch(input->libinput) != 0)
weston_log("libinput: Failed to dispatch libinput\n");
process_events(input);
return 0;
}
static int
libinput_source_dispatch(int fd, uint32_t mask, void *data)
{
struct udev_input *input = data;
return udev_input_dispatch(input) != 0;
}
static int
open_restricted(const char *path, int flags, void *user_data)
{
struct udev_input *input = user_data;
struct weston_launcher *launcher = input->compositor->launcher;
return weston_launcher_open(launcher, path, flags);
}
static void
close_restricted(int fd, void *user_data)
{
struct udev_input *input = user_data;
struct weston_launcher *launcher = input->compositor->launcher;
weston_launcher_close(launcher, fd);
}
const struct libinput_interface libinput_interface = {
open_restricted,
close_restricted,
};
int
udev_input_enable(struct udev_input *input)
{
struct wl_event_loop *loop;
struct weston_compositor *c = input->compositor;
int fd;
struct udev_seat *seat;
int devices_found = 0;
loop = wl_display_get_event_loop(c->wl_display);
fd = libinput_get_fd(input->libinput);
input->libinput_source =
wl_event_loop_add_fd(loop, fd, WL_EVENT_READABLE,
libinput_source_dispatch, input);
if (!input->libinput_source) {
return -1;
}
if (input->suspended) {
if (libinput_resume(input->libinput) != 0) {
wl_event_source_remove(input->libinput_source);
input->libinput_source = NULL;
return -1;
}
input->suspended = 0;
process_events(input);
}
wl_list_for_each(seat, &input->compositor->seat_list, base.link) {
evdev_notify_keyboard_focus(&seat->base, &seat->devices_list);
if (!wl_list_empty(&seat->devices_list))
devices_found = 1;
}
if (devices_found == 0) {
weston_log(
"warning: no input devices on entering Weston. "
"Possible causes:\n"
"\t- no permissions to read /dev/input/event*\n"
"\t- seats misconfigured "
"(Weston backend option 'seat', "
"udev device property ID_SEAT)\n");
return -1;
}
return 0;
}
static void
libinput_log_func(struct libinput *libinput,
enum libinput_log_priority priority,
const char *format, va_list args)
{
weston_vlog(format, args);
}
int
udev_input_init(struct udev_input *input, struct weston_compositor *c,
struct udev *udev, const char *seat_id)
{
enum libinput_log_priority priority = LIBINPUT_LOG_PRIORITY_INFO;
const char *log_priority = NULL;
memset(input, 0, sizeof *input);
input->compositor = c;
log_priority = getenv("WESTON_LIBINPUT_LOG_PRIORITY");
input->libinput = libinput_udev_create_context(&libinput_interface,
input, udev);
if (!input->libinput) {
return -1;
}
libinput_log_set_handler(input->libinput, &libinput_log_func);
if (log_priority) {
if (strcmp(log_priority, "debug") == 0) {
priority = LIBINPUT_LOG_PRIORITY_DEBUG;
} else if (strcmp(log_priority, "info") == 0) {
priority = LIBINPUT_LOG_PRIORITY_INFO;
} else if (strcmp(log_priority, "error") == 0) {
priority = LIBINPUT_LOG_PRIORITY_ERROR;
}
}
libinput_log_set_priority(input->libinput, priority);
if (libinput_udev_assign_seat(input->libinput, seat_id) != 0) {
libinput_unref(input->libinput);
return -1;
}
process_events(input);
return udev_input_enable(input);
}
void
udev_input_destroy(struct udev_input *input)
{
struct udev_seat *seat, *next;
wl_event_source_remove(input->libinput_source);
wl_list_for_each_safe(seat, next, &input->compositor->seat_list, base.link)
udev_seat_destroy(seat);
libinput_unref(input->libinput);
}
static void
udev_seat_led_update(struct weston_seat *seat_base, enum weston_led leds)
{
struct udev_seat *seat = (struct udev_seat *) seat_base;
struct evdev_device *device;
wl_list_for_each(device, &seat->devices_list, link)
evdev_led_update(device, leds);
}
static void
notify_output_create(struct wl_listener *listener, void *data)
{
struct udev_seat *seat = container_of(listener, struct udev_seat,
output_create_listener);
struct evdev_device *device;
struct weston_output *output = data;
wl_list_for_each(device, &seat->devices_list, link) {
if (device->output_name &&
strcmp(output->name, device->output_name) == 0) {
evdev_device_set_output(device, output);
}
if (device->output_name == NULL && device->output == NULL)
evdev_device_set_output(device, output);
}
}
static struct udev_seat *
udev_seat_create(struct udev_input *input, const char *seat_name)
{
struct weston_compositor *c = input->compositor;
struct udev_seat *seat;
seat = zalloc(sizeof *seat);
if (!seat)
return NULL;
weston_seat_init(&seat->base, c, seat_name);
seat->base.led_update = udev_seat_led_update;
seat->output_create_listener.notify = notify_output_create;
wl_signal_add(&c->output_created_signal,
&seat->output_create_listener);
wl_list_init(&seat->devices_list);
return seat;
}
static void
udev_seat_destroy(struct udev_seat *seat)
{
udev_seat_remove_devices(seat);
if (seat->base.keyboard)
notify_keyboard_focus_out(&seat->base);
weston_seat_release(&seat->base);
wl_list_remove(&seat->output_create_listener.link);
free(seat);
}
struct udev_seat *
udev_seat_get_named(struct udev_input *input, const char *seat_name)
{
struct udev_seat *seat;
wl_list_for_each(seat, &input->compositor->seat_list, base.link) {
if (strcmp(seat->base.seat_name, seat_name) == 0)
return seat;
}
return udev_seat_create(input, seat_name);
}
|
eyolfson/weston
|
src/libinput-seat.c
|
C
|
mit
| 10,252
|
<?php
/**
* This file is part of RedisClient.
* git: https://github.com/cheprasov/php-redis-client
*
* (C) Alexander Cheprasov <cheprasov.84@ya.ru>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace RedisClient\Protocol;
use RedisClient\Connection\ConnectionInterface;
use RedisClient\Exception\EmptyResponseException;
use RedisClient\Exception\ErrorResponseException;
use RedisClient\Exception\UnknownTypeException;
class RedisProtocol implements ProtocolInterface {
const EOL = "\r\n";
const TYPE_SIMPLE_STRINGS = '+';
const TYPE_ERRORS = '-';
const TYPE_INTEGERS = ':';
const TYPE_BULK_STRINGS = '$';
const TYPE_ARRAYS = '*';
/**
* @var ConnectionInterface
*/
protected $Connection;
/**
* @param ConnectionInterface $Connection
*/
public function __construct(ConnectionInterface $Connection) {
$this->Connection = $Connection;
}
/**
* @param mixed $data
* @return string|string[]
* @throws UnknownTypeException
*/
protected function pack($data) {
if (is_string($data) || is_int($data) || is_bool($data) || is_float($data) || is_null($data)) {
return $this->packProtocolBulkString((string) $data);
}
if (is_array($data)) {
return $this->packProtocolArray($data);
}
throw new UnknownTypeException(gettype($data));
}
/**
* @param array $array
* @return string
*/
protected function packProtocolArray($array) {
$pack = self::TYPE_ARRAYS . count($array) . self::EOL;
foreach ($array as $a) {
$pack .= $this->pack($a);
}
return $pack;
}
/**
* @param string $string
* @return string
*/
protected function packProtocolBulkString($string) {
return self::TYPE_BULK_STRINGS . strlen($string) . self::EOL . $string . self::EOL;
}
/**
* @return string
*/
protected function packProtocolNull() {
return self::TYPE_BULK_STRINGS . '-1' . self::EOL;
}
/**
* @param string $raw
* @return null|string
*/
protected function write($raw) {
return $this->Connection->write($raw);
}
/**
* @return array|int|null|string
* @throws UnknownTypeException
* @throws EmptyResponseException
*/
protected function read() {
if (!$line = $this->Connection->readLine()) {
throw new EmptyResponseException('Empty response. Please, check connection timeout.');
}
$type = $line[0];
$data = substr($line, 1, -2);
if ($type === self::TYPE_BULK_STRINGS) {
$length = (int) $data;
if ($length === -1) {
return null;
}
return substr($this->Connection->read($length + 2), 0, -2);
}
if ($type === self::TYPE_SIMPLE_STRINGS) {
if ($data === 'OK') {
return true;
}
return $data;
}
if ($type === self::TYPE_INTEGERS) {
return (int) $data;
}
if ($type === self::TYPE_ARRAYS) {
$count = (int) $data;
if ($count === -1) {
return null;
}
$array = [];
for ($i = 0; $i < $count; ++$i) {
$array[] = $this->read();
}
return $array;
}
if ($type === self::TYPE_ERRORS) {
return new ErrorResponseException($data);
}
throw new UnknownTypeException('Unknown protocol type '. $type);
}
/**
* @inheritdoc
*/
public function sendRaw($command) {
$this->write($command);
return $response = $this->read();
}
/**
* @inheritdoc
*/
public function send(array $structures) {
return $this->sendRaw($this->packProtocolArray($structures));
}
/**
* @inheritdoc
*/
public function sendMulti(array $structures) {
$raw = '';
foreach ($structures as $structure) {
$raw .= $this->pack($structure);
}
$this->write($raw);
$response = [];
for ($i = count($structures); $i > 0; --$i) {
$response[] = $this->read();
}
return $response;
}
/**
* @inheritdoc
*/
public function subscribe(array $structures, $callback) {
$this->write($this->packProtocolArray($structures));
do {
try {
$response = (array) $this->read();
for ($i = count($response); $i < 4; ++$i) {
$response[] = null;
}
} catch (EmptyResponseException $Ex) {
$response = [null, null, null, null];
}
$continue = call_user_func_array($callback, $response);
} while ($continue);
}
}
|
evnix/cas
|
v1/php-redis-client/src/RedisClient/Protocol/RedisProtocol.php
|
PHP
|
mit
| 4,995
|
package com.grasp.security.jwt;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
public class JWT {
private static final String API_SECRET = System.getenv("API_SECRET");
private final static Key signingKey = new SecretKeySpec(DatatypeConverter.parseBase64Binary(API_SECRET),
SignatureAlgorithm.HS512.getJcaName());
public static String createJwt(String id, String issuer, String subject, long expiration) {
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
JwtBuilder builder = Jwts.builder()
.setId(id)
.setIssuedAt(now)
.setSubject(subject)
.setIssuer(issuer)
.signWith(SignatureAlgorithm.HS512, signingKey);
// check if it's been specified
if (expiration >= 0) {
long expirationMillis = nowMillis + expiration;
Date expirationDate = new Date(expirationMillis);
builder.setExpiration(expirationDate);
}
return builder.compact();
}
public static Claims parseJwt(String jwt) {
return Jwts.parser()
.setSigningKey(signingKey)
.parseClaimsJws(jwt)
.getBody();
}
}
|
Grasp-Team/grasp
|
src/main/java/com/grasp/security/jwt/JWT.java
|
Java
|
mit
| 1,637
|
<b>Public User: </b>{{ adminuser.first_name }} {{ adminuser.last_name }}<br />
<b>Public User Number: </b>{{ adminuser.id }}<br />
<b>Public User Address: </b>{{ adminuser.address }}<br />
<b>Public User City: </b>{{ adminuser.city }}<br />
<b>Public User Postal Code: </b>{{ adminuser.postalcode }}<br />
<b>Public User Create Time: </b>{{ adminuser.createtime|linebreaksbr }}<br />
<a href="/user/list">Back to adminuser list</a>
|
oldpond/gaming---ChicagoBoss-Framework-application
|
src/view/internaluser/view.html
|
HTML
|
mit
| 433
|
import produce from 'immer';
import homeReducer, { initialState } from '../reducer';
import {
loadGalleries,
galleriesLoadingSuccess,
galleriesLoadingError,
} from '../actions';
/* eslint-disable default-case, no-param-reassign */
describe('homeReducer', () => {
let state;
beforeEach(() => {
state = initialState;
});
test('should return the initial state', () => {
const expectedResult = state;
expect(homeReducer(undefined, {})).toEqual(expectedResult);
});
test('should handle the loadGalleries action correctly', () => {
const expectedResult = produce(state, draft => {
draft.galleryLoadings = true;
});
expect(homeReducer(state, loadGalleries())).toEqual(expectedResult);
});
test('should handle the galleriesLoadingSuccess action correctly', () => {
const fixture = {
entries: [{ name: 'demo', path_lower: '/public/galleries/demo' }],
};
const expectedResult = produce(state, draft => {
draft.galleryLoadings = false;
draft.contents = fixture.entries;
});
expect(homeReducer(state, galleriesLoadingSuccess(fixture))).toEqual(
expectedResult,
);
});
test('should handle the galleriesLoadingError action correctly', () => {
const fixture = { type: 'ReferenceError' };
const expectedResult = produce(state, draft => {
draft.galleryErrors = fixture;
draft.host = 'cdn';
});
expect(homeReducer(state, galleriesLoadingError(fixture, 'cdn'))).toEqual(
expectedResult,
);
});
});
|
danactive/history
|
ui/app/containers/HomePage/tests/reducer.jest.js
|
JavaScript
|
mit
| 1,532
|
package operateur;
import entite.Entite;
import entite.GameException;
public class DeplDir extends Mouvement {
Direction dir;
int lg;
public DeplDir(Direction dir, int lg) {
super();
this.dir = dir;
this.lg = lg;
}
@Override
public boolean isDoable() {
// TODO
return false;
}
public void execute(Entite e) throws GameException {
if (!isDoable()) {
throw new GameException("Cette action n'est pas réalisable");
}
e.allerVers(dir, lg);
}
}
|
EnzoMolion/Projet-PLA
|
src/operateur/DeplDir.java
|
Java
|
mit
| 488
|
from abc import abstractmethod
from threading import Timer
from ctx.uncertainty.measurers import clear_dobson_paddy
class Event:
def __init__(self, type, **kwargs):
self.type = type
self.properties = kwargs
class Observer:
def update(self):
raise NotImplementedError("Not implemented")
class Observable:
def __init__(self):
self._observers = []
def register(self, observer):
self._observers.append(observer)
def notify(self, event):
event.source = self
for observer in self._observers:
observer.update(event)
class Widget(Observable, Observer):
@abstractmethod
def update(self, event):
pass
def __init__(self, type, status_name, *generators):
super(Widget, self).__init__()
self.type = type
self.generators = generators
self.status = None
self.status_name = status_name
for generator in generators:
generator.register(self)
def get_property(self, type):
for generator in self.generators:
if generator.type == type:
return generator.property
class Generator(Observable):
def __init__(self, type, relevance, threshold, certainty_measurer=clear_dobson_paddy):
super().__init__()
self.certainty_measurer = certainty_measurer
self.property = None
self.type = type
self.relevance = relevance
self.threshold = threshold
def generate(self):
# generate a dict, e.g.: {"value": 12, "certainty" : 0.9}
raise NotImplementedError("Not implemented")
def has_acceptable_certainty(self, new_property):
certainty_level = self.certainty_measurer(self.relevance, new_property['accuracy'])
is_acceptable = certainty_level > self.threshold
return is_acceptable
def start(self, delay=5):
new_property = self.generate()
if new_property['value'] != self.property and self.has_acceptable_certainty(new_property):
self.property = new_property['value']
event = Event(self.type, property=new_property['value'])
super().notify(event)
timer_task = Timer(delay, lambda: self.start(delay), ())
timer_task.start()
|
fmca/ctxpy
|
ctx/toolkit.py
|
Python
|
mit
| 2,280
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="Minh-Quan Nguyen">
<title>Visit - Landing Craft Support Museum</title>
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="css/grayscale.css" rel="stylesheet">
<link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link href='https://fonts.googleapis.com/css?family=Quantico:700' rel='stylesheet' type='text/css'/>
<link href="https://fonts.googleapis.com/css?family=Fjalla+One" rel="stylesheet" type='text/css'>
<link href="https://fonts.googleapis.com/css?family=Special+Elite" rel="stylesheet" type = 'text/css'>
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet" type = 'text/css'>
<link href="https://fonts.googleapis.com/css?family=Anton" rel="stylesheet" type = 'text/css'>
<link href="https://fonts.googleapis.com/css?family=Arvo:700i" rel="stylesheet" type ='text/css'>
<link href="https://fonts.googleapis.com/css?family=Teko:700" rel="stylesheet" type ='text/css'>
<link href="https://fonts.googleapis.com/css?family=Merriweather+Sans:700" rel="stylesheet" type = 'text/css'>
<link href="https://fonts.googleapis.com/css?family=Shrikhand" rel="stylesheet" type = 'text/css'>
</head>
<body id="page-top">
<nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav">
<div class="container">
<a class="navbar-brand js-scroll-trigger" href="/index.html">Home</a>
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
MENU
<i class="fa fa-bars"></i>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link js-scroll-trigger" href="/history.html">History</a>
</li>
<li class="nav-item">
<a class="nav-link js-scroll-trigger" href="/news.html">News</a>
</li>
<li class="nav-item">
<a class="nav-link js-scroll-trigger" href="/visit.html">Visit</a>
</li>
<li class="nav-item">
<a class="nav-link js-scroll-trigger" href="/contact.html">Contact</a>
</li>
</ul>
</div>
</div>
</nav>
<<h5 class="content-header">Visit the Museum</h5>
<section id="visit_information" class="content-section text-center">
<div class="container">
<div class="row">
<div class="col-md-6">
</div>
<div class="col-md-6">
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d50233.137678234736!2d-122.29991628553181!3d38.10364591842527!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x808574a3763ba953%3A0xd1d04a9d3d8e3e1e!2sUSS+LCS(L)(3)-102!5e0!3m2!1sen!2sus!4v1505603234029" width="400" height="400" frameborder="0" style="border:0" allowfullscreen></iframe>
<a href="http://startbootstrap.com/template-overviews/grayscale/">
<p>This theme features stock photos by
<a href="http://gratisography.com/">Gratisography</a>
along with a custom Google Maps skin courtesy of
<a href="http://snazzymaps.com/">Snazzy Maps</a>.</p>
<p>Landing Craft Support (Large) ships were developed to support amphibious landings and to intercept inter-island barge traffic. Used solely in the Pacific
Theater of operations, they were a further development of gunboats that had been converted from Landing Craft Infantry ships - LCIs.
The need for a close-fire support vessel was demonstrated during the assault on Tarawa on 20 November 1944. After the larger ships had shelled the
beaches and landing zones to disrupt enemy defense efforts, the landing craft headed for shore to deliver the troops. During the time that the naval
bombardment had stopped and the troops had landed, the enemy had time to regroup, and the effect on the Marines was deadly. In order to deliver fire
support to protect them, a new type of vessel was necessary. It needed the ability to get in close to shore and had to have sufficient armament to support
the landings. Previous experiments had resulted in placing additional guns, rockets, and mortars on various LCI(L)s and turning them into gunboats.
These LCI(G), LCI(R), and LCI(M) variations had proven their worth, but were still limited because of their original configuration. They were considered
to be an interim solution the problems encountered in the Pacific Theater. Fortunately, a more advanced gunboat had been in the planning stages as
early as 1942, and the first contracts for the new fire support vessel had been awarded in 1943. The first of these gunboats, the LCS(L) 1, was launched on
15 May 1944 at the George Lawley and Sons Shipyard in Neponset, Massachusetts.</p>
</div>
</div>
</div>
</section>
<!-- Download Section -->
<section id="download" class="download-section content-section text-center">
<div class="container">
<div class="col-lg-8 mx-auto">
<h2>Download Grayscale</h2>
<p>You can download Grayscale for free on the preview page at Start Bootstrap.</p>
<a href="http://startbootstrap.com/template-overviews/grayscale/" class="btn btn-default btn-lg">Visit Download Page</a>
</div>
</div>
</section>
<!-- Contact Section -->
<section id="contact" class="content-section text-center">
<div class="container">
<div class="row">
<div class="col-lg-8 mx-auto">
<h2>Contact Start Bootstrap</h2>
<p>Feel free to leave us a comment on the
<a href="http://startbootstrap.com/template-overviews/grayscale/">Grayscale template overview page</a>
on Start Bootstrap to give some feedback about this theme!</p>
<ul class="list-inline banner-social-buttons">
<li class="list-inline-item">
<a href="https://twitter.com/SBootstrap" class="btn btn-default btn-lg">
<i class="fa fa-twitter fa-fw"></i>
<span class="network-name">Twitter</span>
</a>
</li>
<li class="list-inline-item">
<a href="https://github.com/BlackrockDigital/startbootstrap" class="btn btn-default btn-lg">
<i class="fa fa-github fa-fw"></i>
<span class="network-name">Github</span>
</a>
</li>
<li class="list-inline-item">
<a href="https://plus.google.com/+Startbootstrap/posts" class="btn btn-default btn-lg">
<i class="fa fa-google-plus fa-fw"></i>
<span class="network-name">Google+</span>
</a>
</li>
</ul>
</div>
</div>
</div>
</section>
<footer>
<div class="footerBackground">
<div class="container-fluid">
<div class= "row">
<div class="col-xs-1 col-md-2">
<h5 class= "footerLogo"> 102 </h5>
</div>
<div class="col-xs-1 col-md-3">
<div class="footerContent">
<strong>Landing Craft Support Museum</strong><br>
Mare Island Shipyard<br>
*insert # here*<br>
Vallejo, CA *zip*<br>
<abbr title="Phone">P:</abbr> (123) 456-7890
</div>
</div>
<div class="col-xs-1 col-md-3 text-center">
<div class="footerContent">
<strong>Opening Hours:</strong><br>
Tuesday: 9 AM to 3 PM<br>
Thursday: 9 AM to 3 PM<br>
Saturday: 9 AM to 3 PM<br>
<strong>Admission is Free</strong>
</div>
</div>
<div class="col-xs-4 col-md-4">
<div class="footerContent">
<strong>Find us on Social Media!</strong>
<ul class="list-inline banner-social-buttons">
<li class="list-inline-item">
<a href="https://www.facebook.com/theyankeedollar" class="btn btn-default btn-sm">
<i class="fa fa-facebook fa-fw"></i>
<span class="network-name">Facebook</span>
</a>
</li>
<li class="list-inline-item">
<a href="https://plus.google.com/+Startbootstrap/posts" class="btn btn-default btn-sm">
<i class="fa fa-google-plus fa-fw"></i>
<span class="network-name">Google+</span>
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-12">
<p class="text-center top-margin"> ©Landing Craft Support Museum 2017
<br>Website Developed by Minh-Quan Nguyen </p>
</div>
</div>
</div>
</div>
</footer>
<!-- Bootstrap core JavaScript -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/popper/popper.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- Plugin JavaScript -->
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Custom scripts for this template -->
<script src="js/grayscale.js"></script>
</body>
</html>
|
Minitquan/Minitquan.github.io
|
_site/visit.html
|
HTML
|
mit
| 9,593
|
package net.shafranov.coolbutton.behaviors;
import java.util.HashMap;
import java.util.Map;
import net.shafranov.coolbutton.component.CoolButton;
import org.apache.wicket.Component;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.util.template.PackageTextTemplate;
import org.apache.wicket.util.template.TextTemplate;
/**
* Behavior that adds mouse events handlers to Cool Button component.
*
* @author Artem Shafranov
*/
public abstract class CoolButtonMouseEventsBehavior extends Behavior {
private static final long serialVersionUID = -3168970070789302820L;
/** Target component */
private CoolButton coolButton;
/*
* (non-Javadoc)
* @see org.apache.wicket.behavior.Behavior#onConfigure(org.apache.wicket.Component)
*/
@Override
public void onConfigure(Component component) {
if (!(component instanceof CoolButton)) {
throw new RuntimeException("Behavior should be attached to component of class "
+ CoolButton.class.getCanonicalName());
}
this.coolButton = (CoolButton) component;
}
/*
* (non-Javadoc)
* @see org.apache.wicket.behavior.Behavior#renderHead(org.apache.wicket.Component, org.apache.wicket.markup.html.IHeaderResponse)
*/
@Override
public void renderHead(Component component, IHeaderResponse response) {
super.renderHead(component, response);
renderAddMouseEventHandlersJavaScript(response);
}
/**
* Get onMouseOver event handler JavaScript.
*
* @param coolButton
* event target component
* @return
*/
protected abstract String getMouseOverJavaScript(CoolButton coolButton);
/**
* Get onMouseOut event handler JavaScript.
*
* @param coolButton
* event target component
* @return
*/
protected abstract String getMouseOutJavaScript(CoolButton coolButton);
/**
* Render add mouse events handlers JavaScript for target component.
*
* @param response
*/
private void renderAddMouseEventHandlersJavaScript(IHeaderResponse response) {
// get add onClick handler JavaScript template from file
TextTemplate mouseEventsJSTemplate = new PackageTextTemplate(CoolButtonMouseEventsBehavior.class,
"mouse-events.js.template");
// fill variables map
Map<String, Object> variables = new HashMap<String, Object>();
// JavaScript variable name for target component
variables.put("variableName", coolButton.getJSVariableName());
// mouse events handlers JavaScript
variables.put("onMouseOverJS", getMouseOverJavaScript(coolButton));
variables.put("onMouseOutJS", getMouseOutJavaScript(coolButton));
// render variables into template
mouseEventsJSTemplate.interpolate(variables);
// render JavaScript as OnDomReady event handler
response.renderOnDomReadyJavaScript(mouseEventsJSTemplate.asString());
}
}
|
shafranov/wicket-javascript
|
cool-button/src/net/shafranov/coolbutton/behaviors/CoolButtonMouseEventsBehavior.java
|
Java
|
mit
| 3,097
|
<?php
/**
* This file is part of the Spryker Demoshop.
* For full license information, please view the LICENSE file that was distributed with this source code.
*/
namespace Pyz\Zed\Collector\Persistence\Storage\Propel;
use Orm\Zed\Touch\Persistence\Map\SpyTouchTableMap;
use Orm\Zed\Url\Persistence\Map\SpyUrlRedirectTableMap;
use Orm\Zed\Url\Persistence\Map\SpyUrlTableMap;
use Propel\Runtime\ActiveQuery\Criteria;
use Spryker\Zed\Collector\Persistence\Collector\AbstractPropelCollectorQuery;
class RedirectCollectorQuery extends AbstractPropelCollectorQuery
{
/**
* @return void
*/
protected function prepareQuery()
{
$this->touchQuery->addJoin(
SpyTouchTableMap::COL_ITEM_ID,
SpyUrlRedirectTableMap::COL_ID_URL_REDIRECT,
Criteria::INNER_JOIN
);
$this->touchQuery->addJoin(
SpyUrlRedirectTableMap::COL_ID_URL_REDIRECT,
SpyUrlTableMap::COL_FK_RESOURCE_REDIRECT,
Criteria::INNER_JOIN
);
$this->touchQuery->addAnd(
SpyUrlTableMap::COL_FK_LOCALE,
$this->getLocale()->getIdLocale(),
Criteria::EQUAL
);
$this->touchQuery->withColumn(SpyUrlRedirectTableMap::COL_ID_URL_REDIRECT, 'id');
$this->touchQuery->withColumn(SpyUrlTableMap::COL_URL, 'from_url');
$this->touchQuery->withColumn(SpyUrlRedirectTableMap::COL_STATUS, 'status');
$this->touchQuery->withColumn(SpyUrlRedirectTableMap::COL_TO_URL, 'to_url');
}
}
|
spryker/demoshop
|
src/Pyz/Zed/Collector/Persistence/Storage/Propel/RedirectCollectorQuery.php
|
PHP
|
mit
| 1,530
|
var x;
var y;
var d;
var speedX;
var speedY;
function setup() {
createCanvas(windowWidth, windowHeight);
background(0, 255, 255);
d = 100;
x = random(d, width-d);
y = random(d, height-d);
speedX = random(5, 15);
speedY = random(5, 15);
}
function draw() {
background(0, 255, 255);
ellipse(x, y, d, d);
x = x + speedX;
y = y + speedY;
//d = d + 1;
if(y > height - d/2) {
speedY = -1 * abs(speedY);
fill(random(255), random(255), random(255))
}
if(y < d/2) {
speedY = abs(speedY);
}
if(x > width - d/2) {
speedX = -1 * abs(speedX);
}
if(x < d/2) {
speedX = abs(speedX);
}
}
|
lminsky/9th-Grade-CS
|
2016-2017/Section 3/Classwork/2017-05-03/ball/sketch.js
|
JavaScript
|
mit
| 639
|
@font-face{font-family:Lato;font-style:normal;font-weight:300;src:local('Lato Light'),local('Lato-Light'),url(font/IY9HZVvI1cMoAHxvl0w9LVKPGs1ZzpMvnHX-7fPOuAc.woff2) format('woff2');unicode-range:U+0100-024F,U+1E00-1EFF,U+20A0-20AB,U+20AD-20CF,U+2C60-2C7F,U+A720-A7FF}
@font-face{font-family:Lato;font-style:normal;font-weight:300;src:local('Lato Light'),local('Lato-Light'),url(font/22JRxvfANxSmnAhzbFH8PgLUuEpTyoUstqEm5AMlJo4.woff2) format('woff2');unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02C6,U+02DA,U+02DC,U+2000-206F,U+2074,U+20AC,U+2212,U+2215}
@font-face{font-family:Lato;font-style:normal;font-weight:400;src:local('Lato Regular'),local('Lato-Regular'),url(font/8qcEw_nrk_5HEcCpYdJu8BTbgVql8nDJpwnrE27mub0.woff2) format('woff2');unicode-range:U+0100-024F,U+1E00-1EFF,U+20A0-20AB,U+20AD-20CF,U+2C60-2C7F,U+A720-A7FF}
@font-face{font-family:Lato;font-style:normal;font-weight:400;src:local('Lato Regular'),local('Lato-Regular'),url(font/v13/MDadn8DQ_3oT6kvnUq_2r_esZW2xOQ-xsNqO47m55DA.woff2) format('woff2');unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02C6,U+02DA,U+02DC,U+2000-206F,U+2074,U+20AC,U+2212,U+2215}
@font-face{font-family:Lato;font-style:normal;font-weight:700;src:local('Lato Bold'),local('Lato-Bold'),url(font/rZPI2gHXi8zxUjnybc2ZQFKPGs1ZzpMvnHX-7fPOuAc.woff2) format('woff2');unicode-range:U+0100-024F,U+1E00-1EFF,U+20A0-20AB,U+20AD-20CF,U+2C60-2C7F,U+A720-A7FF}
@font-face{font-family:Lato;font-style:normal;font-weight:700;src:local('Lato Bold'),local('Lato-Bold'),url(font/MgNNr5y1C_tIEuLEmicLmwLUuEpTyoUstqEm5AMlJo4.woff2) format('woff2');unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02C6,U+02DA,U+02DC,U+2000-206F,U+2074,U+20AC,U+2212,U+2215}
*{margin:0;padding:0}
article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}
li{list-style:none}
table{border-collapse:separate;border-spacing:0}
img{border:0}
button:active,input:active,textarea:active{outline:0}
button:focus,input:focus,textarea:focus{outline:0}
button:active,input:active,textarea:active{outline:0}
button{text-transform:uppercase;padding:10px 10px 13px 10px;box-shadow:inset 0 -3px 0 0 rgba(0,0,0,.15);background:#01923f;border:0;margin:5px 10px;min-width:120px;border-radius:3px;color:#fff;letter-spacing:.11em}
button:active{box-shadow:inset 0 -100px 0 0 rgba(0,0,0,.15),inset 0 1px 0 0 rgba(0,0,0,.15)}
button:hover{cursor:pointer}
input{background:#fff;border:1px solid #ddd;padding:8px 13px;border-radius:3px;transition:border .5s ease}
input:focus{border-color:#aaa;transition:border .5s ease}
a{text-decoration:none;color:#3f51b5}
::placeholder{color:#ccc}
input:-webkit-autofill,select:-webkit-autofill,textarea:-webkit-autofill{background:0 0!important;-webkit-box-shadow:0 0 0 30px transparent inset}
.float_left{float:left}
.float_right{float:right}
.clearfix:after{display:table;content:'';clear:both}
.container{width:1200px;margin:0 auto}
body{background:#edeef0;font-family:Roboto,sans-serif;font-size:12px;font-weight:300;color:#666}
.nav_logo img{max-width:100px;padding:5px 10px 5px 0}
.nav_logo h1{font-size:16px;color:#01923f}
.nav_logo h2{font-size:14px;color:#13b057;font-weight:300}
.user_nav>li{display:inline-block;padding:9px}
#dashboard_menu{background:#51739a;padding:20px 10px;position:fixed;left:0;top:63px;bottom:0;width:200px;z-index:999;box-shadow:0 2px 10px rgba(0,0,0,.4)}
#dashboard_menu li{display:block;padding:10px}
#dashboard_menu li:hover{cursor:pointer;background:#f2f4f7}
#dashboard_menu li.active{background:#f2f4f7}
#dashboard_menu li.active:hover{cursor:pointer}
.dashboard_content{background:#fff;margin:95px 20px 50px 240px;padding:20px}
.table_def tr td:first-child{border-left:5px solid transparent}
.table_def tr:hover td{cursor:pointer;background:#fffbe7;border-left-color:#507299}
.table_def tr th{background:#f7f7f7;color:#507299;text-align:left;text-transform:uppercase;font-size:10px;padding:15px 5px;border-bottom:1px solid #eee;border-top:1px solid #eee;font-weight:400}
.table_def tr th:hover{cursor:pointer}
.table_def tr td:first-child{text-align:center}
.table_def tr td{vertical-align:middle;border-bottom:1px solid #eee;vertical-align:middle;padding:10px 5px;font-size:12px;color:#777;background:#fff;max-width:200px;min-width:50px;font-weight:300;overflow:auto;text-overflow:ellipsis}
#popup_box{background:rgba(0,0,0,.7);position:fixed;left:0;right:0;top:0;bottom:0;z-index:10000}
.title_modal{background:#f2f4f7;font-size:14px;line-height:50px;color:#01923f;font-weight:100;padding-left:25px}
.box_modal{background:#fff;position:absolute;left:50%;top:50%;max-height:90vh;max-width:90vw;-moz-transform:translate(-50%,-50%);-webkit-transform:translate(-50%,-50%);-o-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}
#content_modal{box-sizing:border-box;overflow-y:scroll}
div.close_modal{background-position:-4px -4px;width:12px;height:12px;position:absolute;right:0;margin:19px 20px}
.input_dashed{display:block;outline:1px dashed #ddd;margin:0;padding:5px 10px;font-size:11px;color:#aaa;background:#fff;box-sizing:border-box}
.input_dashed input{display:block;height:24px;border:0;padding:0;width:100%;font-size:12px;font-size:12px;box-sizing:border-box}
.input_dashed_file{display:block;outline:1px dashed #ddd;margin:0;line-height:32px;padding:5px 10px;font-size:11px;color:#aaa;background:#fff;box-sizing:border-box;margin-bottom:1px}
.input_dashed_file input{display:none}
.input_dashed_file span{float:right;background:#ddd;text-align:center;border-radius:2px;padding:0 25px;line-height:24px;margin:4px}
.input_dashed_file span:hover{cursor:pointer;background:#507299;color:#fff;transition:all ease 1s}
.input_dashed_file span:active{cursor:pointer;background:#7996b7;color:#fff;transition:all ease 1s}
.notes_modal{background:#f2f4f8;margin-bottom:10px;padding:10px;border-radius:2px;border:1px dotted #ddd}
.custom_autocomplete{background:#fff;border:1px solid #ddd;display:inline-block;margin:10px 20px;border-radius:2px;box-sizing:border-box;width:410px;padding:3px 1px;box-shadow:0 1px 4px rgba(0,0,0,.1)}
.custom_autocomplete select{height:28px;border:0;display:inline-block;width:200px;float:right;margin-right:2px}
.custom_autocomplete input{border:0}
.custom_autocomplete ul{position:absolute;border-top:0;margin:-2px;width:410px;box-sizing:border-box}
.custom_autocomplete ul li{border-right:1px solid #ddd;padding:6px 10px;background:#fff;border-left:1px solid #ddd;margin-top:-1px}
.custom_autocomplete ul li:last-child{border-radius:0 0 3px 3px;border-bottom:1px solid #ddd}
.custom_autocomplete ul li:hover{background-color:#f7f7f7;cursor:pointer}
.btn_submit_assess{background:#01923f;color:#fff;display:inline-block;margin:10px 20px 9px -22px;border-radius:0 2px 2px 0;box-sizing:border-box;padding:0 32px;box-shadow:0 1px 4px rgba(0,0,0,.1);float:left;line-height:37px}
.btn_submit_assess:hover{cursor:pointer;background:#13b057}
.section_iin_file_list{padding:5px 0;border-radius:2px}
.section_iin_file_list>div{color:#2a5885;padding:7px 10px;margin:5px 0;transition:background .5s ease}
.section_iin_file_list>div div{line-height:26px;display:inline-block;max-width:70%;text-overflow:ellipsis;white-space:nowrap;overflow:hidden}
.section_iin_file_list>div div:before{display:inline-block;background:url(file.svg);height:15px;width:15px;content:'';background-size:cover;margin:0 10px -3px 0}
.section_iin_file_list>div:hover{background:#e9edf1;border-radius:2px;transition:background .5s ease}
.section_iin_file_list>div .btn_download{background:rgba(0,0,0,.2);padding:5px 10px;border-radius:2px;color:#777;font-size:12px;transition:all .5s ease}
.section_iin_file_list>div .btn_download:before{display:inline-block;background:url(download.svg);height:10px;width:10px;content:'';background-size:cover;margin:0 10px 0 0}
.section_iin_file_list>div .btn_download:hover{background:#507299;color:#fff;transition:all .5s ease}
.section_upload_list_file{margin:-20px -20px 0 -20px}
.section_upload_list_file .addFileButton{background:rgba(0,0,0,.03);line-height:50px;text-align:center;border-top:1px solid #eee;border-bottom:1px solid #eee;padding:0 0 1px 0;color:#507299}
.section_upload_list_file .addFileButton:hover{cursor:pointer;background:rgba(0,0,0,.05)}
.section_upload_list_file .addFileButton:active{padding:1px 0 0 0}
.section_upload_list_file .addFileButton span{background:url(upload.svg) no-repeat left center;padding-left:24px;background-size:14px 14px;font-weight:400}
.section_upload_list_file .nothing_upload_list{padding:10% 5%;text-align:center;color:#aaa}
.section_upload_list_file .section_upload_list_verify{border-top:1px solid #f2f4f7;margin:20px 0 10px 0;padding:5px 0}
.section_upload_list_file .section_upload_list_verify button{box-shadow:none;padding:8px 20px 9px;min-width:auto;margin:10px 0 0 0}
.section_upload_list_file .item_upload{background:#fff;margin:0 20px;border-bottom:1px solid #eee;line-height:50px;display:block;position:relative}
.section_upload_list_file .item_upload:before{content:'';display:block;float:left;width:20px;height:20px;background:url(file.svg);background-size:cover;margin:15px}
.section_upload_list_file .item_upload span{background:url(delete.svg);background-size:cover;font-size:0;display:block;position:absolute;width:15px;height:15px;margin:17.5px;right:0;top:0}
.section_upload_list_file .item_upload input{display:none}
.slide_comment textarea{width:100%;border:1px solid #ddd;border-radius:2px;margin:10px 0;padding:10px;box-sizing:border-box;font-size:12px}
.btn_plus_upload{position:absolute;right:0;z-index:1;width:30px;height:30px;min-width:auto;margin:10px 30px}
.verify_section{background:#f2f4f8;padding:5px 20px}
.verify_section button{box-shadow:none;padding:8px 20px 9px;min-width:auto;margin:10px 0}
.id_status{box-sizing:border-box}
.id_status span{margin:0 15px 0 0;padding:5px 5%;box-sizing:border-box;border-radius:3px;background-color:#ddd;white-space:nowrap;display:block;overflow:hidden;text-overflow:ellipsis;text-align:center}
.id_status span.ADMIN{background-color:#01923f;color:#fff}
.notif_box{position:absolute;display:none;width:300px;background:#fff;border-radius:3px;top:60px;right:60px;box-shadow:0 3px 6px rgba(0,0,0,.2)}
.notif{background:#fff;border-top:1px solid #eee;font-size:12px;padding:10px 20px}
.notif:first-child{border-top:0}
.main_pagination{display:block;text-align:center;margin-top:10px}
.main_pagination ul{display:inline-block}
.main_pagination li{display:inline-block;padding:6px 12px;font-weight:700;background:#f7f7f7;border-radius:3px;margin:5px;color:#507299;transition:all 1s ease}
.main_pagination li a{color:#507299}
.main_pagination li:hover{cursor:pointer;background:#507299;color:#fff;transition:all 1s ease}
.main_pagination li:hover a{color:#fff}
.parent_table{overflow-x:scroll}
.parent_table table{white-space:nowrap}
#filtertable{display:inline-block;margin:10px;border:1px solid #ddd;border-radius:2px;width:200px;box-shadow:0 2px 4px rgba(0,0,0,.05)}
#filtertable .clickfilter{background:#fafafa;padding:10px 15px}
#filtertable .filtertable{position:absolute;width:200px;box-shadow:0 2px 4px rgba(0,0,0,.2);border-radius:0 0 3px 3px;box-sizing:border-box;padding-bottom:8px;padding-top:8px;background:#fff;margin-top:-1px;display:none}
#filtertable .filtertable label{display:block;padding:7px 20px;background:#fff}
#filtertable .filtertable label input{margin-right:10px}
.z-modal-frame{position:fixed;top:0;right:0;left:0;bottom:0;z-index:10000;background:rgba(0,0,0,.5)}
#z-modal-edit{position:fixed;top:0;right:0;left:0;z-index:10001;max-width:400px;width:100%;background:#fff;margin:10% auto;box-shadow:0 0 8px rgba(0,0,0,.2)}
#z-modal-edit .z-modal-title{height:50px;line-height:50px;background:#eee;font-size:16px;padding-left:20px;color:#01923f;position:relative}
#z-modal-edit .z-modal-close{height:50px;width:50px;background:url(cancel.svg) center no-repeat;background-size:14px;position:absolute;right:0;top:0}
#z-modal-edit .z-modal-form{box-sizing:border-box;padding:15px}
#z-modal-edit .z-modal-form label{display:block;padding:5px;box-sizing:border-box;font-size:10px;line-height:20px;font-weight:500;color:#999;text-transform:uppercase}
#z-modal-edit .z-modal-form input{display:block;width:100%;box-sizing:border-box;background:#f2f4f7;border:0;font-size:14px;line-height:24px}
#z-modal-edit .z-modal-form select{line-height:40px;background:#f2f4f8;height:40px;width:100%;border:0;border-radius:2px!important;padding:0 20px}
.btn-flat{text-transform:uppercase;padding:10px 15px 12px 15px;box-shadow:none;background:#01923f;border:0;margin:10px;min-width:120px;border-radius:2px;color:#fff;letter-spacing:.11em}
.title_content{margin:20px;color:#507299}
.sp-icon,.sp-iconb:before{background-image:url(sprite-colour.png)}
.sp-icon-dark,.sp-icon-darkb:before{background-image:url(sprite-dark.png)}
.sp-icon-white,.sp-icon-whiteb:before{background-image:url(sprite-white.png)}
.sheets_paper{border-radius:2px;box-shadow:0 1px 3px rgba(0,0,0,.1),0 10px 0 -6px #fff,0 9px 5px -5px rgba(0,0,0,.2),0 19px 0 -11px #fff,0 18px 5px -10px rgba(0,0,0,.2)}
header{background:#fff;z-index:1000;box-shadow:0 2px 100px rgba(0,0,0,.1);position:fixed;right:0;left:0;top:0}
.nav-logo{display:inline-block;border-right:1px solid #eee;margin-right:20px}
.nav-logo img{transition:all .5s ease}
@media screen and (min-width:800px){
.nav-logo img{max-height:32px;margin:13px 10px 13px 30px}
}
@media screen and (max-width:800px){
.nav-logo img{max-height:25px;margin:13px 10px 13px 0}
}
.nav-menu{display:none}
.nav-menu div{transition:all ease .5s;font-size:0;background:#009240;height:2px;width:20px;margin:25px;position:relative}
.nav-menu div:after,.nav-menu div:before{transition:all ease .5s;background:#009240;width:100%;display:block;position:absolute;content:'';height:2px}
.nav-menu div:before{margin-top:-6px}
.nav-menu div:after{margin-top:6px}
.nav-menu.active div{background:0 0!important;transition:all ease .5s}
.nav-menu.active div:before{margin-top:0;transform:rotate(45deg)!important;transition:all ease .5s}
.nav-menu.active div:after{margin-top:0;transform:rotate(-45deg)!important;transition:all ease .5s}
.nav-list>li{display:inline-block;line-height:32px;margin:5px 0;text-transform:uppercase;letter-spacing:1px;padding:10px 0}
.nav-list>li>a{color:#777;line-height:32px;transition:all .5s ease;margin-right:15px;font-size:12px}
.nav-list>li>a:hover{color:#01923f}
.nav-list .nav-sess{border-radius:4px;transition:all .5s ease;font-size:11px}
.nav-list .nav-sess a{margin-right:10px}
.nav-list .nav-sess.register a{color:#009240;border:1px solid #009240;padding:6px 12px;border-radius:4px;transition:all .5s ease;font-size:11px}
.nav-list .nav-sess.register a:hover{background:#009240;color:#fff;transition:all .5s ease}
.nav-list .nav-link.parent:hover{cursor:pointer}
.nav-list .nav-link.parent>ul{display:none;position:absolute;background:#fff;box-shadow:0 2px 8px rgba(0,0,0,.3),0 0 2px rgba(0,0,0,.1);border-radius:2px;margin:0 -15px;padding:10px 0;line-height:32px;z-index:100}
.nav-list .nav-link.parent>ul li{padding:2px 15px;transition:all 1s ease}
.nav-list .nav-link.parent>ul li a{font-size:12px;color:#777}
.nav-list .nav-link.parent>ul li:hover{background:rgba(0,146,64,.2);transition:all 1s ease;padding:2px 10px 2px 20px}
.nav-list .nav-link.parent>ul li:hover a{color:#01923f!important}
.nav-list .nav-link.parent.active ul{display:block!important}
.nav-notif{position:relative}
.nav-notif>a span{border:1px solid red;color:red;padding:3px 7px 2px 7px;line-height:0;border-radius:7px}
.nav-notif .box_notif{display:none;position:absolute;background:#fff;box-shadow:0 2px 8px rgba(0,0,0,.3),0 0 2px rgba(0,0,0,.1);border-radius:2px;margin:0 0 0 -15px;padding:5px 0;z-index:100;text-transform:none;font-size:12px;line-height:18px;max-width:300px;width:100vw;right:0;max-height:250px;overflow:scroll}
.nav-notif .box_notif li{padding:10px 15px;font-size:12px;line-height:15px;letter-spacing:0;border-top:1px solid rgba(0,0,0,.05)}
.nav-notif .box_notif li a{color:#999}
.nav-notif .box_notif .false{background:#edf2fa}
.nav-notif .box_notif .false a{color:#555}
.nav-notif:hover .box_notif{display:block}
|
roxao/BSN
|
assets/main-admin.min.css
|
CSS
|
mit
| 16,103
|
/* eslint-disable no-console,func-names,react/no-multi-comp */
const React = require('react');
const ReactDOM = require('react-dom');
const Table = require('table-v7');
require('table-v7/assets/index.less');
const columns = [
{ title: '表头1', dataIndex: 'a', key: 'a', width: 100, fixed: 'left' },
{ title: '表头2', dataIndex: 'b', key: 'b', width: 100, fixed: 'left' },
{ title: '表头3', dataIndex: 'c', key: 'c' },
{ title: '表头4', dataIndex: 'b', key: 'd' },
{ title: '表头5', dataIndex: 'b', key: 'e' },
{ title: '表头6', dataIndex: 'b', key: 'f' },
{ title: '表头7', dataIndex: 'b', key: 'g' },
{ title: '表头8', dataIndex: 'b', key: 'h' },
{ title: '表头9', dataIndex: 'b', key: 'i' },
{ title: '表头10', dataIndex: 'b', key: 'j' },
{ title: '表头11', dataIndex: 'b', key: 'k' },
{ title: '表头12', dataIndex: 'b', key: 'l', width: 100, fixed: 'right' },
];
const data = [
{ a: '123', b: 'xxxxxxxx', d: 3, key: '1' },
{ a: 'cdd', b: 'edd12221', d: 3, key: '2' },
{ a: '133', c: 'edd12221', d: 2, key: '3' },
{ a: '133', c: 'edd12221', d: 2, key: '4' },
{ a: '133', c: 'edd12221', d: 2, key: '5' },
{ a: '133', c: 'edd12221', d: 2, key: '6' },
{ a: '133', c: 'edd12221', d: 2, key: '7' },
{ a: '133', c: 'edd12221', d: 2, key: '8' },
{ a: '133', c: 'edd12221', d: 2, key: '9' },
];
ReactDOM.render(
<div style={{ width: 800 }}>
<h2>Fixed columns</h2>
<Table
columns={columns}
expandedRowRender={record => record.title}
expandIconAsCell
scroll={{ x: 1200 }}
data={data}
/>
</div>
, document.getElementById('__react-content'));
|
ninemilli-song/table-v7
|
examples/fixedColumns.js
|
JavaScript
|
mit
| 1,648
|
---
layout: post
title: Ep. 12 - Prof. Stefan Hell - Inside the mind of a Nobel laureate
date: 2017-06-05 14:00:00 +0100
categories: episode
comments: true
redirect_from:
- /stefanhell
---
In the final episode of Season 1, we met [Prof. Stefan Hell](https://en.wikipedia.org/wiki/Stefan_Hell) - a Nobel prize winning physicist who in his own words was "forced into becoming an applied physicist." (!) He is known for developing a technique of optical microscopy that broke the 125 year reign of Abbe's limit and today allows us to look down at the molecular scale with just a simple microscope.
We talked to him about what kept him motivated, about his views on how present-day science works, and much more! If you're a budding scientist or just someone looking for inspiration from a great man, do listen to what Prof. Hell has to say.
Listen to his lectures delivered at the prestigious **[Wolfgang Pauli Lecture Series](http://www.video.ethz.ch/speakers/pauli/2017.html)** at ETH Zurich here.
Prof. Stefan Hell is currently one of the directors of the Max Planck Institute for Biophysical Chemistry in Göttingen, Germany. You can follow his exciting work on **[his group's webpage.](http://www.mpibpc.mpg.de/hell)**
If you like our podcast, we would love it if you shared it with your friends and colleagues, and gave us feedback in the comments section below.
This is the last episode of Season 1 of Simplifyd. Follow us on [Facebook](https://www.facebook.com/simplifydpodcast) or keep an eye on our website for updates.
And now... let’s begin.
<div id="media-wrapper">
<div id="soundcloud-embed"><iframe width="100%" height="166" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/325983561&color=ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false"></iframe></div>
<div id="youtube-embed">{% include youtube_embed.html id="Brd9xtaEF-g" %}</div>
</div>
|
gsidhu/simplifyd
|
_posts/2017-06-05-ep-12-stefan-hell.md
|
Markdown
|
mit
| 2,003
|
import { EventEmitter } from 'events'
import path from 'path'
import type { URL } from 'url'
import { URLFactory } from './factory'
import logger from '@wdio/logger'
import { transformCommandLogResult } from '@wdio/utils'
import type { Options } from '@wdio/types'
import { isSuccessfulResponse, getErrorFromResponseBody, getTimeoutError } from '../utils'
const pkg = require('../../package.json')
type Agents = Options.Agents
type RequestLibOptions = Options.RequestLibOptions
type RequestLibResponse = Options.RequestLibResponse
type RequestOptions = Omit<Options.WebDriver, 'capabilities'>
export class RequestLibError extends Error {
statusCode?: number
body?: any
code?: string
}
export interface WebDriverResponse {
value: any
/**
* error case
* https://w3c.github.io/webdriver/webdriver-spec.html#dfn-send-an-error
*/
error?: string
message?: string
stacktrace?: string
/**
* JSONWP property
*/
status?: number
sessionId?: string
}
const DEFAULT_HEADERS = {
'Content-Type': 'application/json; charset=utf-8',
'Connection': 'keep-alive',
'Accept': 'application/json',
'User-Agent': 'webdriver/' + pkg.version
}
const log = logger('webdriver')
export default abstract class WebDriverRequest extends EventEmitter {
body?: Record<string, unknown>
method: string
endpoint: string
isHubCommand: boolean
requiresSessionId: boolean
defaultAgents: Agents | null
defaultOptions: RequestLibOptions = {
retry: 0, // we have our own retry mechanism
followRedirect: true,
responseType: 'json',
throwHttpErrors: false
}
constructor (method: string, endpoint: string, body?: Record<string, unknown>, isHubCommand: boolean = false) {
super()
this.body = body
this.method = method
this.endpoint = endpoint
this.isHubCommand = isHubCommand
this.defaultAgents = null
this.requiresSessionId = Boolean(this.endpoint.match(/:sessionId/))
}
makeRequest (options: RequestOptions, sessionId?: string) {
let fullRequestOptions: RequestLibOptions = Object.assign({
method: this.method
}, this.defaultOptions, this._createOptions(options, sessionId))
if (typeof options.transformRequest === 'function') {
fullRequestOptions = options.transformRequest(fullRequestOptions)
}
this.emit('request', fullRequestOptions)
return this._request(fullRequestOptions, options.transformResponse, options.connectionRetryCount, 0)
}
protected _createOptions (options: RequestOptions, sessionId?: string, isBrowser: boolean = false): RequestLibOptions {
const agent = isBrowser ? undefined : (options.agent || this.defaultAgents)
const searchParams = isBrowser ?
undefined :
(typeof options.queryParams === 'object' ? options.queryParams : {})
const requestOptions: RequestLibOptions = {
https: {},
agent,
headers: {
...DEFAULT_HEADERS,
...(typeof options.headers === 'object' ? options.headers : {})
},
searchParams,
timeout: options.connectionRetryTimeout
}
/**
* only apply body property if existing
*/
if (this.body && (Object.keys(this.body).length || this.method === 'POST')) {
const contentLength = Buffer.byteLength(JSON.stringify(this.body), 'utf8')
requestOptions.json = this.body
requestOptions.headers!['Content-Length'] = `${contentLength}`
}
/**
* if we don't have a session id we set it here, unless we call commands that don't require session ids, for
* example /sessions. The call to /sessions is not connected to a session itself and it therefore doesn't
* require it
*/
let endpoint = this.endpoint
if (this.requiresSessionId) {
if (!sessionId) {
throw new Error('A sessionId is required for this command')
}
endpoint = endpoint.replace(':sessionId', sessionId)
}
requestOptions.url = URLFactory.getInstance(
`${options.protocol}://` +
`${options.hostname}:${options.port}` +
(this.isHubCommand ? this.endpoint : path.join(options.path || '', endpoint))
)
/**
* send authentication credentials only when creating new session
*/
if (this.endpoint === '/session' && options.user && options.key) {
requestOptions.username = options.user
requestOptions.password = options.key
}
/**
* if the environment variable "STRICT_SSL" is defined as "false", it doesn't require SSL certificates to be valid.
* Or the requestOptions has strictSSL for an environment which cannot get the environment variable correctly like on an Electron app.
*/
requestOptions.https!.rejectUnauthorized = !(
options.strictSSL === false ||
process.env.STRICT_SSL === 'false' ||
process.env.strict_ssl === 'false'
)
return requestOptions
}
protected async _libRequest(url: URL, options: RequestLibOptions): Promise<RequestLibResponse> { // eslint-disable-line @typescript-eslint/no-unused-vars
throw new Error('This function must be implemented')
}
private async _request (
fullRequestOptions: RequestLibOptions,
transformResponse?: (response: RequestLibResponse, requestOptions: RequestLibOptions) => RequestLibResponse,
totalRetryCount = 0,
retryCount = 0
): Promise<WebDriverResponse> {
log.info(`[${fullRequestOptions.method}] ${(fullRequestOptions.url as URL).href}`)
if (fullRequestOptions.json && Object.keys(fullRequestOptions.json).length) {
log.info('DATA', transformCommandLogResult(fullRequestOptions.json))
}
const { url, ...requestLibOptions } = fullRequestOptions
let response = await this._libRequest(url!, requestLibOptions)
// @ts-ignore
.catch((err: RequestLibError) => {
return err
})
/**
* handle retries for requests
* @param {Error} error error object that causes the retry
* @param {String} msg message that is being shown as warning to user
*/
const retry = (error: Error, msg: string) => {
/**
* stop retrying if totalRetryCount was exceeded or there is no reason to
* retry, e.g. if sessionId is invalid
*/
if (retryCount >= totalRetryCount || error.message.includes('invalid session id')) {
log.error(`Request failed with status ${response.statusCode} due to ${error}`)
this.emit('response', { error })
throw error
}
++retryCount
this.emit('retry', { error, retryCount })
log.warn(msg)
log.info(`Retrying ${retryCount}/${totalRetryCount}`)
return this._request(fullRequestOptions, transformResponse, totalRetryCount, retryCount)
}
/**
* handle request errors
*/
if (response instanceof Error) {
/**
* handle timeouts
*/
if ((response as RequestLibError).code === 'ETIMEDOUT') {
const error = getTimeoutError(response, fullRequestOptions)
return retry(error, 'Request timed out! Consider increasing the "connectionRetryTimeout" option.')
}
/**
* throw if request error is unknown
*/
throw response
}
if (typeof transformResponse === 'function') {
response = transformResponse(response, fullRequestOptions) as RequestLibResponse
}
const error = getErrorFromResponseBody(response.body)
/**
* retry connection refused errors
*/
if (error.message === 'java.net.ConnectException: Connection refused: connect') {
return retry(error, 'Connection to Selenium Standalone server was refused.')
}
/**
* hub commands don't follow standard response formats
* and can have empty bodies
*/
if (this.isHubCommand) {
/**
* if body contains HTML the command was called on a node
* directly without using a hub, therefore throw
*/
if (typeof response.body === 'string' && response.body.startsWith('<!DOCTYPE html>')) {
return Promise.reject(new Error('Command can only be called to a Selenium Hub'))
}
return { value: response.body || null }
}
/**
* Resolve only if successful response
*/
if (isSuccessfulResponse(response.statusCode, response.body)) {
this.emit('response', { result: response.body })
return response.body
}
/**
* stop retrying as this will never be successful.
* we will handle this at the elementErrorHandler
*/
if (error.name === 'stale element reference') {
log.warn('Request encountered a stale element - terminating request')
this.emit('response', { error })
throw error
}
return retry(error, `Request failed with status ${response.statusCode} due to ${error.message}`)
}
}
|
webdriverio/webdriverio
|
packages/webdriver/src/request/index.ts
|
TypeScript
|
mit
| 9,663
|
package p05_randomArrayList;
import java.util.ArrayList;
import java.util.Random;
public class RandomArrayList extends ArrayList {
public Object getRandomElement(ArrayList<Object> inputList) {
Random random = new Random();
Object obj = inputList.get(random.nextInt(inputList.size()));
inputList.remove(obj);
return obj;
}
}
|
ivelin1936/Studing-SoftUni-
|
Java Fundamentals/Java OOP Basic/Lab - Inheritance/src/p05_randomArrayList/RandomArrayList.java
|
Java
|
mit
| 368
|
# Œ 1334 ‰
---
krih pRiqpwl ] Awip ik®pw kir rwKhu hir jIau poih n skY jmkwlu ]2]
qyrI srxweI scI hir jIau nw Eh GtY n jwie ] jo hir Coif dUjY Bwie
lwgY Ehu jMmY qY mir jwie ]3] jo qyrI srxweI hir jIau iqnw dUK BUK ikCu
nwih ] nwnk nwmu slwih sdw qU scY sbid smwih ]4]4] pRBwqI mhlw 3
] gurmuiK hir jIau sdw iDAwvhu jb lgu jIA prwn ] gur sbdI mnu
inrmlu hoAw cUkw min AiBmwnu ] sPlu jnmu iqsu pRwnI kyrw hir kY nwim
smwn ]1] myry mn gur kI isK suxIjY ] hir kw nwmu sdw suKdwqw shjy
hir rsu pIjY ]1] rhwau ] mUlu pCwxin iqn inj Gir vwsw shjy hI suKu
hoeI ] gur kY sbid kmlu prgwisAw haumY durmiq KoeI ] sBnw mih eyko
scu vrqY ivrlw bUJY koeI ]2] gurmqI mnu inrmlu hoAw AMimRqu qqu vKwnY
] hir kw nwmu sdw min visAw ivic mn hI mnu mwnY ] sdw bilhwrI gur
Apuny ivthu ijqu Awqm rwmu pCwnY ]3] mwns jnim siqgurU n syivAw
ibrQw jnmu gvwieAw ] ndir kry qW siqguru myly shjy shij smwieAw ]
nwnk nwmu imlY vifAweI pUrY Bwig iDAwieAw ]4]5] pRBwqI mhlw 3 ]
Awpy BWiq bxwey bhu rMgI issit aupwie pRiB Kylu kIAw ] kir kir vyKY kry
krwey srb jIAw no irjku dIAw ]1] klI kwl mih rivAw rwmu ] Git
Git pUir rihAw pRBu eyko gurmuiK prgtu hir hir nwmu ]1] rhwau ] gupqw
nwmu vrqY ivic kljuig Git Git hir BrpUir rihAw ] nwmu rqnu iqnw
ihrdY pRgitAw jo gur srxweI Bij pieAw ]2] ieMdRI pMc pMcy vis AwxY
iKmw sMqoKu gurmiq pwvY ] so Dnu Dnu hir jnu vf pUrw jo BY bYrwig hir gux
gwvY ]3] gur qy muhu Pyry jy koeI gur kw kihAw n iciq DrY ] kir Awcwr
bhu sMpau sMcY jo ikCu krY su nrik prY ]4] eyko sbdu eyko pRBu vrqY sB
eyksu qy auqpiq clY ] nwnk gurmuiK myil imlwey gurmuiK hir hir jwie
rlY ]5]6] pRBwqI mhlw 3 ] myry mn guru Apxw
####
|
bogas04/SikhJS
|
assets/docs/md/SGGS/Ang 1334.md
|
Markdown
|
mit
| 1,617
|
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
{% block head %}{% endblock %}
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
|
freevoid/yawf
|
yawf/templates/yawf/base.html
|
HTML
|
mit
| 184
|
<!DOCTYPE html>
<html ng-app="ngb2.chp10.demo09">
<head lang="en">
<meta charset="UTF-8">
<title>第10章 指令详解</title>
<script type="text/javascript" src="../../bower_components/angular/angular.js"></script>
</head>
<body>
<p>P84 controller</p>
<div my-directive>
</div>
<script !src="">
var app = angular.module('ngb2.chp10.demo09', []);
app.directive('myDirective', function () {
return {
restrict: 'A',
controller:'SomeController'
};
});
app.controller('SomeController', function ($scope,$element,$attrs,$transclude) {
//$scope 指令的当前作用域
//$element 指令对应的元素
//$attrs 当前元素的属性组成的json对象
//$transclude 嵌入链接函数,实际被执行用来克隆元素和操作DOM
//ng不建议在控制器内部操作DOM;如果有这个需求,请在compile参数中使用transcludeFn。
});
</script>
</body>
</html>
|
nail2008/cookbook-angularjs
|
app/ng-book2/chapter10/demo090.html
|
HTML
|
mit
| 990
|
package C3;
public class Ejercicio08 {
public static void main(String[] args) {
switch (args.length) {
case 0 : System.out.println("Se han introducido 0 argumentos"); break;
case 1 : System.out.println("Se ha introducido 1 argumento"); break;
case 2 : System.out.println("Se han introducido 2 argumentos"); break;
case 3 : System.out.println("Se han introducido 3 argumentos"); break;
default: System.out.println("Se han introducido más de 3 argumentos"); break;
}
}
}
|
xChasingWaves/clase
|
Programacion/Unidad03/C3/Ejercicio08.java
|
Java
|
mit
| 508
|
<h1>Wishlist</h1>
<p>
As most of you may have realized, we live in Japan and will have
difficulty transporting and finding room for physical gifts in our
notoriously small Japanese apartment. Also, electronics are often not
compatible due to wattage differences.
</p>
<p>
So, we would greatly appreciately cash gifts, but if you would like to
give a physical gift, we have prepared a wishlist below. If you email
us which item you'd like and donate the monetary amount in dollars, we
will purchase the item in Japan and send you a picture of it in our
apartment.
</p>
<ul>
<h2>Current list</h2>
<li>
<span class="item"><a href="http://www.amazon.co.jp/%E3%83%96%E3%83%A9%E3%82%A6%E3%83%B3-%E3%83%8F%E3%83%B3%E3%83%89%E3%83%96%E3%83%AC%E3%83%B3%E3%83%80%E3%83%BC-%E3%83%9E%E3%83%AB%E3%83%81%E3%82%AF%E3%82%A4%E3%83%83%E3%82%AF-%E3%83%97%E3%83%AD%E3%83%95%E3%82%A7%E3%83%83%E3%82%B7%E3%83%A7%E3%83%8A%E3%83%AB-MR5555MCA/dp/B002KF2NAI/ref=sr_1_1?ie=UTF8&qid=1348648896&sr=8-1">Braun Multiquick hand blender</a></span>
<span class="cost">$75</span>
</li>
<li>
<span class="item"><a href="http://www.amazon.co.jp/%E3%83%AA%E3%83%BC%E3%83%87%E3%83%AB-RIEDEL-%E3%83%AA%E3%83%BC%E3%83%87%E3%83%AB%E3%83%BB%E3%82%AA%E3%83%BC-%E3%83%94%E3%83%8E%E3%83%BB%E3%83%8E%E3%83%AF%E3%83%BC%E3%83%AB-%E3%83%8D%E3%83%83%E3%83%93%E3%83%BC%E3%83%AD/dp/B0009I6KS4/ref=sr_1_7?ie=UTF8&qid=1349006029&sr=8-7">Riedel wine glass set (4)</a></span>
<span class="cost">65</span>
</li>
<li>
<span class="item"><a href="http://www.amazon.com/Vacu-Vin-0981450-Vacuum-Stoppers/dp/B000GA3KCE/ref=sr_1_1?ie=UTF8&qid=1349010232&sr=8-1&keywords=wine+stopper">Wine saver</a></span>
<span class="cost">10</span>
</li>
<li>
<span class="item"><a href="http://www.amazon.co.jp/BIALETTI-%E3%83%93%E3%82%A2%E3%83%AC%E3%83%83%E3%83%86%E3%82%A3-ES030200-%E3%83%A2%E3%82%AB%E3%82%A8%E3%82%AF%E3%82%B9%E3%83%97%E3%83%AC%E3%82%B93CUP-BEX-3/dp/B0000AN3QI/ref=sr_1_1?s=kitchen&ie=UTF8&qid=1349007876&sr=1-1">Bialetti Moka Express (3 cup)</a></span>
<span class="cost">35</span>
</li>
<li>
<span class="item"><a href="http://www.amazon.co.jp/FRED-%E3%83%9E%E3%83%88%E3%83%AA%E3%83%A7%E3%83%BC%E3%82%B7%E3%82%AB-%E3%82%AB%E3%83%83%E3%83%97/dp/B003ITTNH6/ref=sr_1_1?s=kitchen&ie=UTF8&qid=1349052000&sr=1-1">Matryoshka measuring cups</a></span>
<span class="cost">15</span>
</li>
<li>
<span class="item"><a href="http://www.amazon.com/Complete-Elegant-Regency-Flatware-Stainless/dp/B000S94M8O/ref=sr_1_1?ie=UTF8&qid=1349050641&sr=8-1&keywords=serving+fork+and+spoon">Set of serving forks and spoons</a></span>
<span class="cost">30</span>
</li>
<li>
<span class="item"><a href="http://www.amazon.co.jp/%E3%83%8A%E3%82%AC%E3%82%AA-WY-09-%E3%83%AF%E3%82%A4%E3%83%AF%E3%82%A4%E3%82%AD%E3%83%83%E3%83%81%E3%83%B3-%E3%83%90%E3%82%BF%E3%83%BC%E3%83%8A%E3%82%A4%E3%83%95/dp/B0039MJ21E/ref=sr_1_4?s=kitchen&ie=UTF8&qid=1349050983&sr=1-4">Butter knifes (2)</a></span>
<span class="cost">10</span>
</li>
</ul>
|
brymck/wedding
|
wishlist.php
|
PHP
|
mit
| 3,408
|
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2020_03_01
module Models
#
# Public IP prefix resource.
#
class PublicIPPrefix < Resource
include MsRestAzure
# @return [PublicIPPrefixSku] The public IP prefix SKU.
attr_accessor :sku
# @return [IPVersion] The public IP address version. Possible values
# include: 'IPv4', 'IPv6'
attr_accessor :public_ipaddress_version
# @return [Array<IpTag>] The list of tags associated with the public IP
# prefix.
attr_accessor :ip_tags
# @return [Integer] The Length of the Public IP Prefix.
attr_accessor :prefix_length
# @return [String] The allocated Prefix.
attr_accessor :ip_prefix
# @return [Array<ReferencedPublicIpAddress>] The list of all referenced
# PublicIPAddresses.
attr_accessor :public_ipaddresses
# @return [SubResource] The reference to load balancer frontend IP
# configuration associated with the public IP prefix.
attr_accessor :load_balancer_frontend_ip_configuration
# @return [String] The resource GUID property of the public IP prefix
# resource.
attr_accessor :resource_guid
# @return [ProvisioningState] The provisioning state of the public IP
# prefix resource. Possible values include: 'Succeeded', 'Updating',
# 'Deleting', 'Failed'
attr_accessor :provisioning_state
# @return [String] A unique read-only string that changes whenever the
# resource is updated.
attr_accessor :etag
# @return [Array<String>] A list of availability zones denoting the IP
# allocated for the resource needs to come from.
attr_accessor :zones
#
# Mapper for PublicIPPrefix class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'PublicIPPrefix',
type: {
name: 'Composite',
class_name: 'PublicIPPrefix',
model_properties: {
id: {
client_side_validation: true,
required: false,
serialized_name: 'id',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'type',
type: {
name: 'String'
}
},
location: {
client_side_validation: true,
required: false,
serialized_name: 'location',
type: {
name: 'String'
}
},
tags: {
client_side_validation: true,
required: false,
serialized_name: 'tags',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
},
sku: {
client_side_validation: true,
required: false,
serialized_name: 'sku',
type: {
name: 'Composite',
class_name: 'PublicIPPrefixSku'
}
},
public_ipaddress_version: {
client_side_validation: true,
required: false,
serialized_name: 'properties.publicIPAddressVersion',
type: {
name: 'String'
}
},
ip_tags: {
client_side_validation: true,
required: false,
serialized_name: 'properties.ipTags',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'IpTagElementType',
type: {
name: 'Composite',
class_name: 'IpTag'
}
}
}
},
prefix_length: {
client_side_validation: true,
required: false,
serialized_name: 'properties.prefixLength',
type: {
name: 'Number'
}
},
ip_prefix: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.ipPrefix',
type: {
name: 'String'
}
},
public_ipaddresses: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.publicIPAddresses',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ReferencedPublicIpAddressElementType',
type: {
name: 'Composite',
class_name: 'ReferencedPublicIpAddress'
}
}
}
},
load_balancer_frontend_ip_configuration: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.loadBalancerFrontendIpConfiguration',
type: {
name: 'Composite',
class_name: 'SubResource'
}
},
resource_guid: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.resourceGuid',
type: {
name: 'String'
}
},
provisioning_state: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.provisioningState',
type: {
name: 'String'
}
},
etag: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'etag',
type: {
name: 'String'
}
},
zones: {
client_side_validation: true,
required: false,
serialized_name: 'zones',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
}
}
}
}
end
end
end
end
|
Azure/azure-sdk-for-ruby
|
management/azure_mgmt_network/lib/2020-03-01/generated/azure_mgmt_network/models/public_ipprefix.rb
|
Ruby
|
mit
| 8,048
|
using Robust.Client.Graphics.Shaders;
using Robust.Client.Interfaces.GameObjects.Components;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Prototypes;
namespace Content.Client.GameObjects.Components
{
[RegisterComponent]
public class InteractionOutlineComponent : Component
{
[Dependency] private readonly IPrototypeManager _prototypeManager = default!;
private const string ShaderInRange = "SelectionOutlineInrange";
private const string ShaderOutOfRange = "SelectionOutline";
public override string Name => "InteractionOutline";
private ShaderInstance _selectionShaderInstance;
private ShaderInstance _selectionShaderInRangeInstance;
/// <inheritdoc />
public override void Initialize()
{
base.Initialize();
_selectionShaderInRangeInstance = _prototypeManager.Index<ShaderPrototype>(ShaderInRange).Instance();
_selectionShaderInstance = _prototypeManager.Index<ShaderPrototype>(ShaderOutOfRange).Instance();
}
public void OnMouseEnter(bool inInteractionRange)
{
if (Owner.TryGetComponent(out ISpriteComponent sprite))
{
sprite.PostShader = inInteractionRange ? _selectionShaderInRangeInstance : _selectionShaderInstance;
sprite.RenderOrder = Owner.EntityManager.CurrentTick.Value;
}
}
public void OnMouseLeave()
{
if (Owner.TryGetComponent(out ISpriteComponent sprite))
{
sprite.PostShader = null;
sprite.RenderOrder = 0;
}
}
public void UpdateInRange(bool inInteractionRange)
{
if (Owner.TryGetComponent(out ISpriteComponent sprite))
{
sprite.PostShader = inInteractionRange ? _selectionShaderInRangeInstance : _selectionShaderInstance;
}
}
}
}
|
space-wizards/space-station-14-content
|
Content.Client/GameObjects/Components/InteractionOutlineComponent.cs
|
C#
|
mit
| 1,981
|
---
layout: post
title: "Coursera Course: Intro to Data Science With Python"
modified:
categories: [Programming, MOOC]
excerpt: Intermediate Python for data analysis with Pandas and Numpy libraries.
tags: [Python, Data Analysis, Pandas, MOOC]
image:
feature:
date: 2016-12-07T21:44:58+00:00
---
# Intro to Data Science in Python
University of Michigan, Professor Christopher Brooks, Coursera course
11/2016 - Completed on 04/12/2016
Summary:
Despite the course name, this is an intermediate-level data science course with Python. Familiarity with Numpy and Pandas libraries is not required, but is highly recommended, as the course does get pretty intense really quickly (i.e. Week 2) To be honest, this is a solid course for someone who has a background with Panda and numpy libraries. However, there is a big knowledge gap between the videos and the assignments, so it's challenging for beginners.
Feedback:

> My feeling while taking this course...
04/12/2016:
Finally finished this...was close to giving up on it SO MANY TIMES!
## Week 4 Statistical Analysis in Python and Project
Binomial Distribution in numpy for coin flipping
```
np.random.binomial(1,0.5)
```
First term (1) is the number of times you want it to run, and second term (0.5) is the chance we get a zero
```
np.random.binomial(1000, 0.5)/1000
```
Flip coins 1000 times, and divide the result by 1000
Run 1000 simulations of flipping coins 20 times and getting a number >= 15.
```
x = np.random.binomial(20, .5, 10000)
print((x>=15).mean())
```
Output:
```
0.0219
```
Get the number of events given no. of simulation.
"How many tornados will take place based on 100,000 simulations, given that the chance of a tornado is 0.01%?"
```
chance_of_tornado = 0.01/100
np.random.binomial(100000,chance of tornado)
```
Output:
```
8
```
"Assume the chance of tornado is 1%. How many tornados will take place (what is the chance of tornados taking place) two days in a row based on 1000000 simulations?"
```
chance_of_tornado = 0.01
tornado_events = np.random.binomial(1, chance_of_tornado, 1000000)
two_days_in_a_row = 0
for j in range(1,len(tornado_events)-1):
if tornado_events[j]==1 and tornado_events[j-1]==1:
two_days_in_a_row+=1
print('{} tornadoes back to back in {} years'.format(two_days_in_a_row, 1000000/365))
```
Output:
```
103 tornadoes back to back in 2739.72602739726 years
```
tornado_events[j]== 1 means the day when tornado took place.
#### Standard deviation
Draw 1000 samples of a normal distriubtion, with expected value of 0.75 and a standard deviation of 1. Result is ~ 68% of area.
```
distribution = np.random.normal(0.75,size=1000)
np.sqrt(np.sum((np.mean(distribution)-distribution)**2)/len(distribution))
```
The above code is equivalent to the np.std() function:
```
np.std(distribution)
```
#### Kirtosis (shape of tails) with stats module
Positive value = more chubby than a normal distribution
Negative value = more flat than a normal distribution
```
import scipy.stats as stats
stats.kurtosis(distribution)
```
Output:
```
-0.21162400583818153
```
#### Skew with stats module
If skew = 0.5, then there's no skew (i.e. the distribution is symmetric)
```
stats.skew(distribution)
```
Output:
```
0.051147428570855365
```
#### Chi squared distribution (left-skewed)
As the degree of freedom increases, the plot moves from left to center
Degree of freedom = 2:
```
chi_squared_df2 = np.random.chisquare(2, size=10000)
stats.skew(chi_squared_df2)
```
Output:
```
1.9589902136938178
```
Degree of freemdom = 5:
```
chi_squared_df5 = np.random.chisquare(5, size=10000)
stats.skew(chi_squared_df5)
```
Output:
```
1.3010399138921354
```
#### Bimodal distribution (having 2 peaks)
#### Hypothesis Testing
Alternative Hypothesis vs. Null Hypothesis
Significance level (alpha),
alpha = 0.05 or 5%
#### t-test: compare the means of two different populations
stats.ttest_ind(): compare 2 difference samples to see if they have different means. In this case, we're using ttest_ind() to compare the average grade of assignment 1 between early users('early' dataframe) and late users('late' dataframe).
Output is a tuple with a test statistic and a p-value.
```
import scipy.stats as stats
early = df[df['assignment1_submission'] <= '2015-12-31']
late = df[df['assignment1_submission'] > '2015-12-31']
stats.ttest_ind(early['assignment1_grade'], late['assignment1_grade'])
```
Output:
```
Ttest_indResult(statistic=1.400549944897566, pvalue=0.16148283016060577)
```
If the p-value is >0.05(the significance value/alpha we decided previously), then we cannot reject the null hypothesis.
Do the same test on assignment 2:
```
stats.ttest_ind(early['assignment2_grade'], late['assignment2_grade'])
```
Output:
```
Ttest_indResult(statistic=1.3239868220912567, pvalue=0.18563824610067967)
In [ ]:
```
p-value is still >0.05, so we cannot reject the null hypothesis.
---
## Week 3 Advanced Python Pandas

> Finally finished Week 3's assignment.
11/27/2016 Update
Finally finished this week's assignment! The first one took a long time. I had to relearn regular expression because of it. Learned a lot about dataframes through the practices, so I'm happy about the progress eventually, but Jesus,that was a lot of work...
Merging dataframes based on the same index. "NaN" is assigned when there's a missing value.
#### iloc() and loc()
iloc()for query based on location
loc() for query based on label
#### Outer vs inner join
Outer Join
```
pd.merge(df1,df2,how='outer',left_index=True,right_index=True)
```
Inner Join
```
pd.merge(df1,df2,how='inner,left_index=True,right_index=True)
```
Left Join: keep all information from df1
```
pd.merge(df1,df2,how='left',left_index=True,right_index=True)
```
Right Join: keep all information from df2
```
pd.merge(df1,df2,how='right',left_index=True,right_index=True)
```
Join by Column names
```
pd.merge(df1,df2,how='left',left_on='Name',right_on='Name')
```
Chain indexing - not recommended
```
df.loc['Washtenaw']['Total Population']
```
Method chaining
```
(df.where(df['SUMLEV']==50)
.dropna()
.set_index(['STNAME','CTYNAME'])
.rename(columns={'ESTIMATESBASE2010': 'Estimates Base 2010'}))
```
Drop rows where 'Quantity' is 0, and rename the column 'Weight' to 'Weight(oz.)'
```
df = df[df.Quantity !=0].rename({'Weight':'Weight(oz.)'})
```
Alternatively:
```
print(df.drop(df[df['Quantity'] == 0].index).rename(columns={'Weight': 'Weight (oz.)'}))
```
#### Apply() function which applies a function to all rows in a dataframe
To apply to all columns in the same row(i.e.1 = across), use axis= 1
To apply to all rows in the same column (i.e. 0 = down), use axis = 0
```
import numpy as np
def min_max(row):
data = row[['POPESTIMATE2010',
'POPESTIMATE2011',
'POPESTIMATE2012',
'POPESTIMATE2013',
'POPESTIMATE2014',
'POPESTIMATE2015']]
return pd.Series({'min': np.min(data), 'max': np.max(data)})
df.apply(min_max, axis=1)
```
Adding the applied function to the existing dataframe (instead of creating a new one)
```
import numpy as np
def min_max(row):
data = row[['POPESTIMATE2010',
'POPESTIMATE2011',
'POPESTIMATE2012',
'POPESTIMATE2013',
'POPESTIMATE2014',
'POPESTIMATE2015']]
row['max'] = np.max(data)
row['min'] = np.min(data)
return row
df.apply(min_max, axis=1)
```
Use apply() with lambda function:
create a function with the max of each row
```
rows = ['POPESTIMATE2010',
'POPESTIMATE2011',
'POPESTIMATE2012',
'POPESTIMATE2013',
'POPESTIMATE2014',
'POPESTIMATE2015']
df.apply(lambda x: np.max(x[rows]), axis=1)
```
#### Groupby()
you can use a function to be the criteria for group_by()
```
df = df.set_index('STNAME')
def fun(item):
if item[0]<'M':
return 0
if item[0]<'Q':
return 1
return 2
for group, frame in df.groupby(fun):
print('There are ' + str(len(frame)) + ' records in group ' + str(group) + ' for processing.')
```
Calculate the average/sum of a certain group with groupby() and agg()
```
df.groupby('STNAME').agg({'CENSUS2010POP': np.average})
```
```
print(df.groupby('Category').agg('sum'))
```
#### Use apply() with groupby()
```
def totalweight(df, w, q):
return sum(df[w] * df[q])
print(df.groupby('Category').apply(totalweight, 'Weight (oz.)', 'Quantity'))
```
#### Scales
Use astype() to change the type of scales from one to another
create a list and use astype() to indicate the order with ordered = True. This enables > or < to be used on strings.
```
df = pd.DataFrame(['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D'],
index=['excellent', 'excellent', 'excellent', 'good', 'good', 'good', 'ok', 'ok', 'ok', 'poor', 'poor'])
df.rename(columns={0: 'Grades'}, inplace=True)
grades = df['Grades'].astype('category',
categories=['D', 'D+', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-', 'A', 'A+'],
ordered=True)
grades.head()
```
output is:
```
excellent A+
excellent A
excellent A-
good B+
good B
Name: Grades, dtype: category
Categories (11, object): [D < D+ < C- < C ... B+ < A- < A < A+]
```
Use > or < functions on types, output:
```
excellent True
excellent True
excellent True
good True
good True
good True
ok True
ok False
ok False
poor False
poor False
Name: Grades, dtype: bool
```
Change this series to categorical with ordering Low < Medium < High
```
s = pd.Series(['Low', 'Low', 'High', 'Medium', 'Low', 'High', 'Low'])
s.astype('category', categories=['Low', 'Medium', 'High'], ordered=True)
```
Use get_dummies() to convert boolean values into 0s and 1s
#### cut(): to cut data into bins (i.e. to divide them equally into 10 buckets)
```
df = pd.read_csv('census.csv')
df = df[df['SUMLEV']==50]
df = df.set_index('STNAME').groupby(level=0)['CENSUS2010POP'].agg({'avg': np.average})
pd.cut(df['avg'],10)
```
Cut a series into 3 equal-sized bins
```
s = pd.Series([168, 180, 174, 190, 170, 185, 179, 181, 175, 169, 182, 177, 180, 171])
pd.cut(s, 3)
# You can also add labels for the sizes [Small < Medium < Large].
pd.cut(s, 3, labels=['Small', 'Medium', 'Large'])
```
#### Use pivot_table() to create Pivot Tables
```
df = pd.read_csv('cars.csv')
df.pivot_table(values='(kW)', index='YEAR', columns='Make', aggfunc=np.mean)
```
Create a pivot table that shows mean price and mean ratings for every "Manufacturer"/"Bike Type" combination
```
print(pd.pivot_table(Bikes, index=['Manufacturer','Bike Type']))
import numpy as np
print(Bikes.pivot_table(values ='Price',index = 'Manufacturer',columns = 'Bike Type',aggfunc=np.average))
```
#### Date Functionality in Panda
1. Timestamp
2. DatetimeIndex (the index of 1)
3. Period
4. PeriodIndex (the index of 3)
1. Timestamp, exchangeable to Python's datetime
⋅⋅⋅```
⋅⋅⋅pd.Timestamp('9/1/2016 10:05AM')
⋅⋅⋅```
2. Period
```
pd.Period('1/2016')
```
3. DatetimeIndex and PeriodIndex
DatetimeIndex
```
t1 = pd.Series(list('abc'), [pd.Timestamp('2016-09-01'), pd.Timestamp('2016-09-02'), pd.Timestamp('2016-09-03')])
type(t1.index)
```
Output:
```
pandas.tseries.index.DatetimeIndex
```
PeriodIndex
```
t2 = pd.Series(list('def'), [pd.Period('2016-09'), pd.Period('2016-10'), pd.Period('2016-11')])
type(t2.index)
```
Output:
```
pandas.tseries.period.PeriodIndex
```
Coverts datetimes to the same format with to_datetime()
```
d1 = ['2 June 2013', 'Aug 29, 2014', '2015-06-26', '7/12/16']
ts3 = pd.DataFrame(np.random.randint(10, 100, (4,2)), index=d1, columns=list('ab'))
ts3.index = pd.to_datetime(ts3.index)
```
use dayfirst = True to change the datetime into European format
```
pd.to_datetime('4.7.12', dayfirst=True)
```
#### Timedelta: show difference in times
```
pd.Timestamp('9/3/2016')-pd.Timestamp('9/1/2016')
```
Output:
```
Timedelta('2 days 00:00:00')
```
Calculate datetime with timedelta
```
pd.Timestamp('9/2/2016 8:10AM') + pd.Timedelta('12D 3H')
```
Output:
```
Timestamp('2016-09-14 11:10:00')
```
#### Date_range()
Create a range of dates for bi-weekly on Sundays, starting with a specific date
```
dates = pd.date_range('10-01-2016', periods=9, freq='2W-SUN')
```
#### weekday_name(): check what day of the week it is
```
df.index.weekday_name
```
#### diff(): find difference between each day's value
```
df.diff()
```
#### resample(): frequency conversion. example: find mean count for each month, will show the data as of month end. 'M' stands for month
```
df.resample('M').mean()
```
Find values from a specific year, month or a range of dates
```
df['2017']
df['2016-12']
df['2016-12':]
<!-- from 12/2016 onwards -->
```
#### asfreq(): change frequency from bi-weekly to weekly, and fill NaN value with last week's data point
```
df.asfreq('W', method='ffill')
```
#### matplotlib: visualising a timeseries
```
import matplotlib.pyplot as plt
%matplotlib inline
df.plot()
```
---
## Week 2 Basic Data Processing with Pandas
Dataframe
```
import pandas as pd
purchase_1 = pd.Series({'Name': 'Chris',
'Item Purchased': 'Dog Food',
'Cost': 22.50})
purchase_2 = pd.Series({'Name': 'Kevyn',
'Item Purchased': 'Kitty Litter',
'Cost': 2.50})
purchase_3 = pd.Series({'Name': 'Vinod',
'Item Purchased': 'Bird Seed',
'Cost': 5.00})
df = pd.DataFrame([purchase_1, purchase_2, purchase_3], index=['Store 1', 'Store 1', 'Store 2'])
df.head()
```
df.T.loc --> T transforms data
iloc vs loc: iloc searches by index, loc searches by value
Avoid chaining as it generally create a copy of the data, instead of simply viewing it.
Deleting data with df.drop(). It creates a copy of the dataframe with the given rows removed.
```
df.drop("Store 1")
```
Deleting data with del() function
```
del copy_df['Name']
```
apply 20% discount to cost
```
purchase_1 = pd.Series({'Name': 'Chris',
'Item Purchased': 'Dog Food',
'Cost': 22.50})
purchase_2 = pd.Series({'Name': 'Kevyn',
'Item Purchased': 'Kitty Litter',
'Cost': 2.50})
purchase_3 = pd.Series({'Name': 'Vinod',
'Item Purchased': 'Bird Seed',
'Cost': 5.00})
df = pd.DataFrame([purchase_1, purchase_2, purchase_3], index=['Store 1', 'Store 1', 'Store 2'])
df['Cost'] *= 0.8
print(df)
```
Panda's read_csv() function, making first column the index
```
df = pd.read_csv('olympics.csv', index_col=0, skiprows=1)
```
Change column names with rename() method
```
for col in df.columns:
if col[:2]=='01':
df.rename(columns={col:'Gold' + col[4:]}, inplace=True)
if col[:2]=='02':
df.rename(columns={col:'Silver' + col[4:]}, inplace=True)
if col[:2]=='03':
df.rename(columns={col:'Bronze' + col[4:]}, inplace=True)
if col[:1]=='№':
df.rename(columns={col:'#' + col[1:]}, inplace=True)
df.head()
```
Boolean masking: applying a boolean (True or False) filter/mask to a dataframe/array with where() function
```
only_gold = df.where(df['Gold']>0)
only_gold.head()
```
Drop lines when there is no data with na() function
```
only_gold = only_gold.dropna()
```
Chaining boolean maskes
```
<!-- either -->
len(df[(df['Gold'] > 0) | (df['Gold.1'] > 0)])
<!-- and -->
df[(df['Gold.1'] > 0) & (df['Gold'] == 0)]
```
Return all of names of people who spend more than $3.00
```
purchase_1 = pd.Series({'Name': 'Chris',
'Item Purchased': 'Dog Food',
'Cost': 22.50})
purchase_2 = pd.Series({'Name': 'Kevyn',
'Item Purchased': 'Kitty Litter',
'Cost': 2.50})
purchase_3 = pd.Series({'Name': 'Vinod',
'Item Purchased': 'Bird Seed',
'Cost': 5.00})
df = pd.DataFrame([purchase_1, purchase_2, purchase_3], index=['Store 1', 'Store 1', 'Store 2'])
df['Name'][df['Cost']>3]
```
Set_index() function
Reindex the purchase records Dataframe to be index hierarchically, first by store, then by person. Name these indexes "Location" and "Name". Then add a new entry to it with the value of:
Name: "Kevyn", Item Purchased: "Kitty Food", Cost: 3.00 Location:"Store 2".
```
purchase_1 = pd.Series({'Name': 'Chris',
'Item Purchased': 'Dog Food',
'Cost': 22.50})
purchase_2 = pd.Series({'Name': 'Kevyn',
'Item Purchased': 'Kitty Litter',
'Cost': 2.50})
purchase_3 = pd.Series({'Name': 'Vinod',
'Item Purchased': 'Bird Seed',
'Cost': 5.00})
df = pd.DataFrame([purchase_1, purchase_2, purchase_3], index=['Store 1', 'Store 1', 'Store 2'])
df = df.set_index([df.index, 'Name'])
df.index.names = ['Location', 'Name']
df = df.append(pd.Series(data={'Cost': 3.00, 'Item Purchased': 'Kitty Food'}, name=('Store 2', 'Kevyn')))
```
---
## Week 1
####List Indexing and Slicing
Example 1
```
people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']
titleName = []
def split_title_and_name():
for person in people:
last = person.split(" ")[-1]
title = person.split(" ")[0]
titleName.append(title + " "+last)
print(titleName)
split_title_and_name()
```
Example 2
```
people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']
def split_title_and_name(person):
return person.split(" ")[0] + " " + person.split(" ")[-1]
list(map(split_title_and_name,people))
```
Example 3 (official answer)
```
people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']
def split_title_and_name(person):
title = person.split()[0]
lastname = person.split()[-1]
return '{} {}'.format(title, lastname)
list(map(split_title_and_name, people))
```
Lambda functions (for writing quick one-liner functions)
```
my_function = lambda a,b: a+b
my_function(1,2)
```
list comprehension (list all even numbers in range 0 - 1000)
```
my_list = [number for number in range(0,1000) if number % 2==0]
```
```
def times_tables():
lst = []
for i in range(10):
for j in range (10):
lst.append(i*j)
return lst
times_tables() == [j*i for i in range(10) for j in range(10)]
```
```
lowercase = 'abcdefghijklmnopqrstuvwxyz'
digits = '0123456789'
correct_answer = [a+b+c+d for a in lowercase for b in lowercase for c in digits for d in digits]
correct_answer[:50] # Display first 50 ids
```
|
yanniey/yanniey.github.io
|
_posts/2016-12-07-coursera-course-intro-to-data-science-with-python.markdown
|
Markdown
|
mit
| 19,112
|
using System.Linq;
using Abp.Authorization;
using Abp.Authorization.Roles;
using Abp.Authorization.Users;
using Abp.MultiTenancy;
using FreeInventoryManager.Authorization;
using FreeInventoryManager.Authorization.Roles;
using FreeInventoryManager.EntityFramework;
using FreeInventoryManager.Users;
namespace FreeInventoryManager.Migrations.SeedData
{
public class TenantRoleAndUserBuilder
{
private readonly FreeInventoryManagerDbContext _context;
private readonly int _tenantId;
public TenantRoleAndUserBuilder(FreeInventoryManagerDbContext context, int tenantId)
{
_context = context;
_tenantId = tenantId;
}
public void Create()
{
CreateRolesAndUsers();
}
private void CreateRolesAndUsers()
{
//Admin role
var adminRole = _context.Roles.FirstOrDefault(r => r.TenantId == _tenantId && r.Name == StaticRoleNames.Tenants.Admin);
if (adminRole == null)
{
adminRole = _context.Roles.Add(new Role(_tenantId, StaticRoleNames.Tenants.Admin, StaticRoleNames.Tenants.Admin) { IsStatic = true });
_context.SaveChanges();
//Grant all permissions to admin role
var permissions = PermissionFinder
.GetAllPermissions(new FreeInventoryManagerAuthorizationProvider())
.Where(p => p.MultiTenancySides.HasFlag(MultiTenancySides.Tenant))
.ToList();
foreach (var permission in permissions)
{
_context.Permissions.Add(
new RolePermissionSetting
{
TenantId = _tenantId,
Name = permission.Name,
IsGranted = true,
RoleId = adminRole.Id
});
}
_context.SaveChanges();
}
//admin user
var adminUser = _context.Users.FirstOrDefault(u => u.TenantId == _tenantId && u.UserName == User.AdminUserName);
if (adminUser == null)
{
adminUser = User.CreateTenantAdminUser(_tenantId, "admin@defaulttenant.com", "123qwe");
adminUser.IsEmailConfirmed = true;
adminUser.IsActive = true;
_context.Users.Add(adminUser);
_context.SaveChanges();
//Assign Admin role to admin user
_context.UserRoles.Add(new UserRole(_tenantId, adminUser.Id, adminRole.Id));
_context.SaveChanges();
}
}
}
}
|
FabriDamazio/Free-Inventory-Manager
|
FreeInventoryManager/FreeInventoryManager.EntityFramework/Migrations/SeedData/TenantRoleAndUserBuilder.cs
|
C#
|
mit
| 2,732
|
[‹ AdMob Doc Home](./)
<h1>AdMob 集成指南</h1>
<<[../../shared/-VERSION-/version.md]
## 集成
首先,您需要在 [AdMob](https://www.google.com/admob/) 官网注册一个帐号。
然后,用如下命令来集成 SDKBOX AdMob 插件,请确保您可以正常执行的 SDKBOX 安装器.
```bash
$ sdkbox import admob
```
最后,请您仔细阅读官方的 [iOS FAQ](https://developers.google.com/admob/ios/quick-start#faq) 以及 [Android FAQ](https://developers.google.com/admob/android/quick-start#faq) 。
<<[../../shared/notice.md]
<!--## Configuration
<<[../../shared/sdkbox_cloud.md]
<<[../../shared/remote_application_config.md]-->
### JSON 配置
SDKBOX Installer 将会自动在您的 `sdkbox_config.json` 中插入一份配置样例。请修改这份配置样例,使其能用于您自己的 app 。
#### 智能横幅(smart banner)
设置 width 和 height 的值为 0
```
"width":0,
"height":0
```
#### 自适应横幅(adaptive banner)
```
"width":-1,
"height":-1
```
#### 自动缓存
不需要配置,该插件会自动缓存广告类型中的广告。当 插屏广告/视频广告 关闭时,也会自动缓存它。
失败时,需要开发者调用 `cache` 接口去缓存。
type:
- "banner"
- "interstitial"
- "rewarded_video"
- "rewarded_interstitial"
- "appopen"
alignment:
- "top"
- "bottom"
- "left"
- "right"
- "center"
- "top_left" or "left_top"
- "top_right" or "right_top"
- "bottom_left" or "left_bottom"
- "bottom_right" or "right_bottom"
width x height:
- 320x50
- 468x60
- 320x100
- 728x90
- 300x250
- 160x600
- 0x0 # 0x0 means auto size.
#### Test ID (Google)
[Android](https://developers.google.com/admob/ios/test-ads)
| type | id |
| ------------------ | -------------------------------------- |
| Banner | ca-app-pub-3940256099942544/6300978111 |
| Interstitial | ca-app-pub-3940256099942544/1033173712 |
| Interstitial Video | ca-app-pub-3940256099942544/8691691433 |
| Rewarded Video | ca-app-pub-3940256099942544/5224354917 |
| AppOpen | ca-app-pub-3940256099942544/1033173712 |
[iOS](https://developers.google.com/admob/android/test-ads)
| type | id |
| ------------------ | -------------------------------------- |
| Banner | ca-app-pub-3940256099942544/2934735716 |
| Interstitial | ca-app-pub-3940256099942544/4411468910 |
| Interstitial Video | ca-app-pub-3940256099942544/5135589807 |
| Rewarded Video | ca-app-pub-3940256099942544/1712485313 |
| AppOpen | ca-app-pub-3940256099942544/5662855259 |
Example:
```json
{
"ios": {
"AdMob":{
"ads":{
"home":{
"id":"ca-app-pub-3940256099942544/2934735716",
"type":"banner",
"alignment":"bottom",
"width":300,
"height":50
},
"gameover":{
"id":"ca-app-pub-3940256099942544/4411468910",
"type":"interstitial"
},
"appopen":{
"type": "appopen",
"id": "ca-app-pub-3940256099942544/5662855259"
}
}
}
},
"android": {
"AdMob":{
"ads":{
"home":{
"id":"ca-app-pub-3940256099942544/6300978111",
"type":"banner",
"alignment":"bottom",
"width":300,
"height":100
},
"gameover":{
"id":"ca-app-pub-3940256099942544/1033173712",
"type":"interstitial"
},
"appopen":{
"id":"ca-app-pub-3940256099942544/1033173712",
"type":"appopen"
}
}
}
}
}
```
##Usage
<<[usage.md]
<<[api-reference.md]
<<[manual_integration.md]
<<[manual_ios.md]
<<[../../shared/manual_integration_android_and_android_studio.md]
<<[manual_android.md]
<<[extra-step.md]
<<[proguard.md]
|
sdkbox-doc/zh
|
src/admob/readme.md
|
Markdown
|
mit
| 4,288
|
# vue-webpack2
A simple template webpack 2 + vuejs setup for projects
# Documentation
[Vue 2.0](http://vuejs.org/guide/): general information about how to work with Vuejs, not specific to this template.
[Karma](https://karma-runner.github.io/1.0/index.html): general information about how to work with Karma, not specific to this template.
[Mocha](https://mochajs.org/): general information about how to work with Mocha, not specific to this template.
[Webpack 2](https://webpack.js.org): general information about how to work with Webpack 2, not specific to this template.
|
waka-templates/vue-webpack2
|
README.md
|
Markdown
|
mit
| 578
|
using System;
using System.Collections;
using System.Collections.Generic;
using Bender.Configuration;
using Bender.Nodes;
using Bender.Nodes.Object.Values;
using Bender.Reflection;
using NUnit.Framework;
using Should;
namespace Tests.Nodes.Object.Values
{
[TestFixture]
public class ValueFactoryTests
{
// Simple value
[Test]
public void should_create_empty_simple_value()
{
var value = ValueFactory.Create(typeof(object).ToCachedType());
value.Instance.ShouldBeNull();
value.SpecifiedType.Type.ShouldBe<object>();
value.ActualType.Type.ShouldBe<object>();
value.IsReadonly.ShouldBeFalse();
}
[Test]
[TestCase(true), TestCase(false)]
public void should_create_simple_value(bool @readonly)
{
var backingValue = new List<int>();
var value = ValueFactory.Create(backingValue, typeof(IList).ToCachedType(),
@readonly, Options.Create());
value.Instance.ShouldEqual(backingValue);
value.SpecifiedType.Type.ShouldBe<IList>();
value.ActualType.Type.ShouldBe<List<int>>();
value.IsReadonly.ShouldEqual(@readonly);
}
[Test]
public void should_create_simple_value_and_use_actual_type_when_configured()
{
var backingValue = new List<int>();
var value = ValueFactory.Create(backingValue, typeof(IList).ToCachedType(), Options.Create(x => x
.Serialization(y => y.UseActualType())));
value.Instance.ShouldEqual(backingValue);
value.SpecifiedType.Type.ShouldBe<List<int>>();
value.ActualType.Type.ShouldBe<List<int>>();
value.IsReadonly.ShouldBeFalse();
}
[Test]
public void should_create_simple_value_and_use_actual_type_when_specified_type_is_null()
{
var backingValue = new List<int>();
var value = ValueFactory.Create(backingValue, null, Options.Create());
value.Instance.ShouldEqual(backingValue);
value.SpecifiedType.Type.ShouldBe<List<int>>();
value.ActualType.Type.ShouldBe<List<int>>();
value.IsReadonly.ShouldBeFalse();
}
[Test]
public void should_create_simple_value_and_use_actual_type_when_specified_type_is_object()
{
var value = ValueFactory.Create(5, typeof(object).ToCachedType(), Options.Create());
value.Instance.ShouldEqual(5);
value.SpecifiedType.Type.ShouldBe<int>();
value.ActualType.Type.ShouldBe<int>();
value.IsReadonly.ShouldBeFalse();
}
// Member value
public class Member { public IList Value { get; set; } }
public static IValue CreateMemberValue(Mode mode, object value, Options options = null)
{
return ValueFactory.Create(mode,
new SimpleValue(value, value.GetType().ToCachedType()),
new CachedMember(value.GetType().GetProperty("Value")),
options ?? Options.Create());
}
[Test]
[TestCase(Mode.Deserialize), TestCase(Mode.Serialize)]
public void should_create_member_value(Mode mode)
{
var backingValue = new Member { Value = new List<int>() };
var value = CreateMemberValue(mode, backingValue);
value.Instance.ShouldEqual(backingValue.Value);
value.SpecifiedType.Type.ShouldBe<IList>();
value.ActualType.Type.ShouldBe<List<int>>();
value.IsReadonly.ShouldEqual(false);
}
[Test]
[TestCase(Mode.Deserialize, typeof(IList))]
[TestCase(Mode.Serialize, typeof(List<int>))]
public void should_create_member_value_and_use_actual_type_when_configured
(Mode mode, Type specifiedType)
{
var backingValue = new Member { Value = new List<int>() };
var value = CreateMemberValue(mode, backingValue, Options.Create(
x => x.Serialization(y => y.UseActualType())));
value.Instance.ShouldEqual(backingValue.Value);
value.SpecifiedType.Type.ShouldEqual(specifiedType);
value.ActualType.Type.ShouldBe<List<int>>();
value.IsReadonly.ShouldEqual(false);
}
public class ObjectMember { public object Value { get; set; } }
[Test]
[TestCase(Mode.Deserialize, typeof(object))]
[TestCase(Mode.Serialize, typeof(List<int>))]
public void should_create_member_value_and_use_actual_type_when_specified_type_is_object
(Mode mode, Type specifiedType)
{
var backingValue = new ObjectMember { Value = new List<int>() };
var value = CreateMemberValue(mode, backingValue);
value.Instance.ShouldEqual(backingValue.Value);
value.SpecifiedType.Type.ShouldEqual(specifiedType);
value.ActualType.Type.ShouldBe<List<int>>();
value.IsReadonly.ShouldEqual(false);
}
// Lazy value
[Test]
public void should_create_lazy_value()
{
var type = typeof(int);
var backingValue = new SimpleValue(type.ToCachedType());
var value = ValueFactory.Create(backingValue, () => 5);
value.Instance.ShouldEqual(5);
value.SpecifiedType.Type.ShouldEqual(type);
value.ActualType.Type.ShouldEqual(type);
value.IsReadonly.ShouldBeFalse();
}
}
}
|
mikeobrien/Bender
|
src/Tests/Nodes/Object/Values/ValueFactoryTests.cs
|
C#
|
mit
| 5,759
|
Simple example
===
Example bundling an UMD package with one `vue` file and exporting stylus and CSS (both minified and unminified) to different files.
## Building
### With build script
```
cd example
node build.js
ls dist
```
### With rollup cli
```
cd example
npm i -g rollup
rollup -c --input Hello.vue --output dist/bundle.js
```
|
znck/rollup-plugin-vue
|
example/README.md
|
Markdown
|
mit
| 339
|
# mip-qqy-yuyue
mip-qqy-yuyue 去去游手机预约组件
标题|内容
----|----
类型|通用
支持布局|responsive,fixed-height,fill,container,fixed
所需脚本|https://c.mipcdn.com/static/v1/mip-qqy-yuyue/mip-qqy-yuyue.js
## 示例
### 基本用法
```html
<mip-qqy-yuyue>
自定义内容,可以嵌套其他组件
</mip-qqy-yuyue>
```
### {属性名}
说明:预约元素点击弹层、关闭元素
|
mipengine/mip-extensions-platform
|
mip-qqy-yuyue/README.md
|
Markdown
|
mit
| 420
|
import Ember from 'ember';
const {
Route
} = Ember;
export default Route.extend({
model(params) {
return this.get('store').findRecord('item', params.id);
}
});
|
runspired/ember-history
|
tests/dummy/app/routes/items/single/route.js
|
JavaScript
|
mit
| 176
|
function RegisterExtractorPack()
local goExtractor = GetPlatformToolsDirectory() .. 'go-extractor'
if OperatingSystem == 'windows' then
goExtractor = GetPlatformToolsDirectory() .. 'go-extractor.exe'
end
return {
CreatePatternMatcher({'^go-autobuilder$', '^go-autobuilder%.exe$'},
MatchCompilerName, nil, {trace = false}),
CreatePatternMatcher({'^go$', '^go%.exe$'}, MatchCompilerName,
goExtractor, {prepend = {'--mimic', '${compiler}'}})
}
end
-- Return a list of minimum supported versions of the configuration file format
-- return one entry per supported major version.
function GetCompatibleVersions() return {'1.0.0'} end
|
github/codeql-go
|
codeql-tools/tracing-config.lua
|
Lua
|
mit
| 731
|
FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim
WORKDIR /app
COPY . .
ENTRYPOINT ["dotnet", "AbpODataDemo.Web.Host.dll"]
|
aspnetboilerplate/sample-odata
|
AbpODataDemo-Core-vNext/aspnet-core/src/AbpODataDemo.Web.Host/Dockerfile
|
Dockerfile
|
mit
| 134
|
// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "guiutil.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QFrame(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
ui->payTo->setPlaceholderText(tr("Enter a LGBTCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)"));
#endif
setFocusPolicy(Qt::TabFocus);
setFocusProxy(ui->payTo);
GUIUtil::setupAddressWidget(ui->payTo, this);
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
if(!model)
return;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
ui->addAsLabel->setText(associatedLabel);
}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel())
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged()));
clear();
}
void SendCoinsEntry::setRemoveEnabled(bool enabled)
{
ui->deleteButton->setEnabled(enabled);
}
void SendCoinsEntry::clear()
{
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->payTo->setFocus();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::on_deleteButton_clicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
// Check input validity
bool retval = true;
if(!ui->payAmount->validate())
{
retval = false;
}
else
{
if(ui->payAmount->value() <= 0)
{
// Cannot send 0 coins or less
ui->payAmount->setValid(false);
retval = false;
}
}
if(!ui->payTo->hasAcceptableInput() ||
(model && !model->validateAddress(ui->payTo->text())))
{
ui->payTo->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
SendCoinsRecipient rv;
rv.address = ui->payTo->text();
rv.label = ui->addAsLabel->text();
rv.amount = ui->payAmount->value();
return rv;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel);
return ui->payAmount->setupTabChain(ui->addAsLabel);
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
ui->payTo->setText(value.address);
ui->addAsLabel->setText(value.label);
ui->payAmount->setValue(value.amount);
}
void SendCoinsEntry::setAddress(const QString &address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
|
lgbtcoin/LGBT
|
src/qt/sendcoinsentry.cpp
|
C++
|
mit
| 4,616
|
# smf-flat
Theme for SMF 2.1 that follows modern web design
|
live627/smf-flat
|
README.md
|
Markdown
|
mit
| 60
|
<p align="center">
<img src="https://raw.githubusercontent.com/asowers1/CodableCache/master/CodableCache.png">
</p>
<br>



[][Carthage]
[][Cocoapods]

[Carthage]: https://github.com/carthage/carthage
[Cocoapods]: https://cocoapods.org
# 📦📲 CodableCache
What is `CodableCache`? It's a framework that allows for seamless memory caching and disk persistence of your plain old Swift structs. Simply define a model and conform to [Codable](https://developer.apple.com/documentation/swift/codable) – you're ready to use `CodableCache`.
# 📋🧐 Features
- [x] Simple to use transparent cache based on keys and generic types
- [x] Anything that's `Codable` works automatically
- [x] No serializers to write other than optional custom `Codable` encode/decode
- [x] Works with images via codable wrapper
- [x] Easy to integrate into existing workflows
- [x] backed by battle tested NSCache and NSKeyedArchiver
- [ ] batteries included - by design, it's up to you to create workflows and handle cache errors
# 🎓📕 Some History
Codable Cache is a drop in replacement for my [LeanCache](https://github.com/asowers1/LeanCache) framework, which was backed by specifying generic types conforming to `NSCoding`. It afforded workflows like `let x: NSNumber? = Cache<NSNumber>("some interesting key")` and that's still great, but writing serializers for `NSCoding` is a pain. Hence, `CodableCache` was born.
# 👩💻👨💻 Example Code
To get started, just import CodableCache, define a model that conforms to codable, and get coding. These are just a few examples of how you could use CodableCache.
#### Create a person manager backed by a persistent cache:
```swift
import CodableCache
struct Person: Codable {
let name: String
let age: Double // kids are half ages if you recall 😜
}
final class PersonManager {
let cache: CodableCache<Person>
init(cacheKey: AnyHashable) {
cache = CodableCache<Person>(key: cacheKey)
}
func getPerson() -> Person? {
return cache.get()
}
func set(person: Person) throws {
cache.set(value: person)
}
}
```
##### And later use it like so:
```swift
var myPerson = Person(name: "Andrew", age: 26)
let personManager = PersonManager(cacheKey: "myPerson")
try? personManager.set(value: myPerson)
if let person = personManager.get() {
print(person.name) // "Andrew"
print(person.age) // 26
}
```
#### Cache JSON with confidence:
```swift
import CodableCache
//...
struct TestData: Codable {
let testing: [Int]
}
func saveJSON() {
let json = """
{
"testing": [
1,
2,
3
]
}
"""
guard let data = json.data(using: .utf8) else {
return
}
let decodedTestData: TestData
do {
decodedTestData = try decoder.decode(TestData.self, from: data)
try codableCache.set(value: decodedTestData)
} catch {
// do something else
return
}
}
```
#### Get your cached JSON for later use:
```swift
import CodableCache
final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
let appSettings = CodableCache<Settings>(key: "com.myApp.settings")
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if let settings = appSettings.get() {
doSomethingUseful(with: settings)
}
return true
}
// ...
}
```
#### Specify a different storage directory:
```swift
import CodableCache
struct Person: Codable {
let name: String
let age: Double
}
// this data will not be purged by the system like .cachesDirectory would
let persistentPersonStorage = CodableCache<Person>(key: "myPerson", directory: .applicationSupportDirectory)
```
#### Creating a generic cache:
```swift
import CodableCache
final class GenericCache<Cacheable: Codable> {
let cache: CodableCache<Cacheable>
init(cacheKey: AnyHashable) {
self.cache = CodableCache<Cacheable>(key: cacheKey)
}
func get() -> Cacheable? {
return self.cache.get()
}
func set(value: Cacheable) throws {
try self.cache.set(value: value)
}
func clear() throws {
try self.cache.clear()
}
}
```
##### And later use it like so:
```swift
let myCache = GenericCache<MyType>(cacheKey: String(describing: MyType.self))
```
## 😓🙃 Gotchas
##### Custom Encoders/Decoders
Make sure you're decoding as optional if your values are optionally typed
```swift
func testCustomDecoder() {
struct Foo: Codable {
var bar: String? = ""
private enum CodingKeys: String, CodingKey {
case bar
}
init(bar: String?) {
self.bar = bar
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.bar = try container.decode(String.self, forKey: .bar)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.bar, forKey: .bar)
}
}
let foo0 = Foo(bar: "Hello World")
let foo1 = Foo(bar: nil)
let fooCache = CodableCache<Foo>(key: String(describing: Foo.self))
try? fooCache.set(value: foo0)
// this is not nil because decoder expected `String`
XCTAssertNotNil(fooCache.get())
try? fooCache.set(value: foo1)
// this is nil because decoder expected `String`, but it was given what we'd expect for `String?`
XCTAssertNil(fooCache.get())
}
```
To make the decoder work in this scenario, you would want to decode `Foo.bar` as `String?` like so:
```swift
self.bar = try container.decode(String?.self, forKey: .bar)
```
## 👩🔬 👨🎨 Philosophy
Using something heavyweight like CoreData, Realm, or SQLite is often overkill. More often than not we're just backing up some local state based on some JSON interface – using a spaceship for a walk down the block 🚀. Typically, we display this data to the user if it isn't stale and update it from the network if need be. Sorting and reordering is often a server side task, so relational databases and object graphs might be too expensive in terms of upstart modeling and your management time. With `CodableCache` we take a different approach by allowing you to quickly define models, skip boilerplate / serializers, and start saving your data at a lightning pace.
## 💻 🚀 Installation
#### Cocoapods
[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command:
```bash
$ gem install cocoapods
```
> CocoaPods 1.1+ is required to build CodableCache.
To integrate CodableCache into your Xcode project using CocoaPods, specify it in your `Podfile`:
```ruby
use_frameworks!
target '<Your Target Name>' do
pod 'CodableCache'
end
```
Then, run the following command:
```bash
$ pod install
```
#### Carthage
[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.
You can install Carthage with [Homebrew](http://brew.sh/) using the following command:
```bash
$ brew update
$ brew install carthage
```
To integrate CodableCache into your Xcode project using Carthage, specify it in your `Cartfile`:
```ogdl
github "asowers1/CodableCache" "master"
```
Run
```
carthage update
```
In your application targets “General” tab under the “Linked Frameworks and Libraries” section, drag and drop CodableCache-iOS.framework from the Carthage/Build/iOS directory that `carthage update` produced.
### Swift Package Manager
The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. It is in early development, but Alamofire does support its use on supported platforms.
Once you have your Swift package set up, adding CodableCache as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`.
```swift
dependencies: [
.Package(url: "https://github.com/asowers1/CodableCache.git")
]
```
## 🙋 🙋♂️ Contributing
Feel free to open an issue or pull request – I would be happy to help.
## 👩🔧 👨🔧 Authors and Contributors
[Andrew Sowers](http://asowers.net)
[Joe Fabisevich](https://fabisevi.ch)
|
asowers1/CodableCache
|
README.md
|
Markdown
|
mit
| 9,279
|
Grunt-Boilerplate
=================
A simple grunt project template that I use to build quick grunt projects with the same pattern.
# Install steps
This requires that you install [NodeJS](http://nodejs.org) and have the npm command available.
First you need to get the boilerplate code down to your machine:
$ git clone git@github.com:acolchado/Grunt-Boilerplate.git
You can choose to install grunt globally with this command:
$ npm install -g grunt-cli
Install the dependencies:
$ npm install
#Customizing
Now that you have it installed locally you can use it to to create a new set of files that you can use in your own repo to start it off. Run this step:
$ grunt package
This will create a directory called _package/. You can move the contents of this directory into your project's directory to use it as a starting place. Just be careful that you don't override files you already have, such as .gitignore, etc.
|
nikhilrao89/Grunt-Boilerplate
|
README.md
|
Markdown
|
mit
| 934
|
<?php
/*
This is part of Wedeto, the WEb DEvelopment TOolkit.
It is published under the MIT Open Source License.
Copyright 2017, Egbert van der Wal
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 Wedeto\Application;
use PHPUnit\Framework\TestCase;
use Wedeto\Util\Dictionary;
use Wedeto\Util\Hook;
use Wedeto\Log\Logger;
use Wedeto\Log\Writer\MemLogWriter;
use Wedeto\Application\Dispatch\Dispatcher;
use Wedeto\Resolve\Resolver;
use Wedeto\HTTP\Request;
use Wedeto\HTTP\{Responder, Result};
use Wedeto\HTTP\Response\{StringResponse, DataResponse};
/**
* @covers Wedeto\Application\LogAttachHook
*/
class LogAttachHookTest extends TestCase
{
public function setUp()
{
$this->memlogger = new MemLogWriter("DEBUG");
$root = Logger::getLogger('');
$root->addLogWriter($this->memlogger);
$this->resolver = new Resolver();
$this->resolver
->addResolverType('assets', 'assets')
->addResolverType('template', 'template');
$req = Request::createFromGlobals();
$this->dispatcher = new Dispatcher($req, $this->resolver);
$this->lahook = new LogAttachHook($this->memlogger, $this->dispatcher);
$this->assertSame($this->memlogger, $this->lahook->getMemLogWriter());
$this->assertSame($this->dispatcher, $this->lahook->getDispatcher());
$this->assertSame($this->lahook, $this->lahook->setMemLogWriter($this->memlogger));
$this->lahook->attach();
$wedeto_logger = Logger::getLogger('Wedeto.Test');
$wedeto_logger->info('Foo <>bar');
}
public function tearDown()
{
Logger::resetGlobalState();
}
public function testLogHookWithPlainText()
{
// -------------------------
$req = Request::createFromGlobals();
$_SERVER['HTTP_ACCEPT'] = 'text/plain';
$dispatcher = new Dispatcher($req, $this->resolver);
$this->assertSame($this->lahook, $this->lahook->setDispatcher($dispatcher));
$responder = new MockLogAttachResponder;
$responder->setRequest($req);
$response = new StringResponse("Foobar", "text/plain");
$result = new Result;
$result->setResponse($response);
$this->assertSame($responder, $responder->setResult($result));
$lvl = ob_get_level();
try
{
$responder->respond();
}
catch (StringResponse $e)
{
$this->assertSame($response, $e);
$content = $response->getOutput('text/plain');
$this->assertContains('// DEVELOPMENT LOG', $content);
$this->assertContains('Foo <>bar', $content);
}
while ($lvl !== ob_get_level())
{
ob_start();
}
}
public function testLogHookWithHTMLResponse()
{
$_SERVER['HTTP_ACCEPT'] = 'text/html';
$req = Request::createFromGlobals();
$dispatcher = new Dispatcher($req, $this->resolver);
$this->assertSame($this->lahook, $this->lahook->setDispatcher($dispatcher));
$response = new StringResponse("Foobar", "text/html");
$result = new Result;
$result->setResponse($response);
$responder = new MockLogAttachResponder;
$responder->setRequesT($req);
$this->assertSame($responder, $responder->setResult($result));
$lvl = ob_get_level();
try
{
$responder->respond();
}
catch (StringResponse $e)
{
$this->assertSame($response, $e);
$content = $response->getOutput('text/html');
$this->assertContains('<!-- DEVELOPMENT LOG -->', $content);
$this->assertContains('Foo <>bar', $content);
}
while ($lvl !== ob_get_level())
{
ob_start();
}
}
public function testLogHookWithJSONResponse()
{
$_SERVER['HTTP_ACCEPT'] = 'application/json';
$req = Request::createFromGlobals();
$dispatcher = new Dispatcher($req, $this->resolver);
$this->assertSame($this->lahook, $this->lahook->setDispatcher($dispatcher));
$response = new DataResponse(['foo' => 'bar']);
$result = new Result;
$result->setResponse($response);
$responder = new MockLogAttachResponder;
$responder->setRequest($req);
$this->assertSame($responder, $responder->setResult($result));
$lvl = ob_get_level();
try
{
$responder->respond();
}
catch (DataResponse $e)
{
$this->assertSame($response, $e);
$content = $response->getData();
$this->assertInstanceOf(Dictionary::class, $content);
$this->assertTrue(isset($content['devlog']));
$this->assertEquals(1, count($content['devlog']));
$line = $content['devlog'][0];
$this->assertContains('Foo <>bar', $line);
}
while ($lvl !== ob_get_level())
{
ob_start();
}
}
}
class MockLogAttachResponder extends Responder
{
protected function doOutput(string $mime)
{
throw $this->result->getResponse();
}
}
|
Wedeto/Application
|
tests/LogAttachHookTest.php
|
PHP
|
mit
| 6,193
|
// Copyright (c) Simple Injector Contributors. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for license information.
namespace SimpleInjector
{
using System;
using System.Reflection;
using SimpleInjector.Advanced;
/// <summary>
/// Contextual information the a dependency and its direct consumer for which the dependency is injected
/// into. The consumer's type is given by the <see cref="ImplementationType"/> property, where the
/// <see cref="Target"/> property gives access to the consumer's target element (property or constructor
/// argument) in which the dependency will be injected, and the dependency's type information.
/// </summary>
public class InjectionConsumerInfo : ApiObject, IEquatable<InjectionConsumerInfo?>
{
// Bogus values for implementationType and property. They will never be used, but can't be null.
internal static readonly InjectionConsumerInfo Root =
new InjectionConsumerInfo(
implementationType: typeof(object),
property: typeof(string).GetProperties()[0]);
private readonly Type implementationType;
private readonly InjectionTargetInfo target;
/// <summary>Initializes a new instance of the <see cref="InjectionConsumerInfo"/> class.</summary>
/// <param name="parameter">The constructor parameter for the created component.</param>
public InjectionConsumerInfo(ParameterInfo parameter)
{
Requires.IsNotNull(parameter, nameof(parameter));
this.target = new InjectionTargetInfo(parameter);
this.implementationType = parameter.Member.DeclaringType;
}
/// <summary>Initializes a new instance of the <see cref="InjectionConsumerInfo"/> class.</summary>
/// <param name="implementationType">The implementation type of the consumer of the component that should be created.</param>
/// <param name="property">The property for the created component.</param>
public InjectionConsumerInfo(Type implementationType, PropertyInfo property)
{
Requires.IsNotNull(implementationType, nameof(implementationType));
Requires.IsNotNull(property, nameof(property));
this.target = new InjectionTargetInfo(property);
this.implementationType = implementationType;
}
/// <summary>Gets the implementation type of the consumer of the component that should be created.</summary>
/// <value>The implementation type.</value>
public Type ImplementationType
{
get
{
#if DEBUG
// Check to make sure that this property is never used internally on the Root instance.
if (this.IsRoot)
{
throw new InvalidOperationException("Can't be called on Root.");
}
#endif
return this.implementationType;
}
}
/// <summary>
/// Gets the information about the consumer's target in which the dependency is injected. The target
/// can be either a property or a constructor parameter.
/// </summary>
/// <value>The <see cref="InjectionTargetInfo"/> for this context.</value>
public InjectionTargetInfo Target
{
get
{
#if DEBUG
// Check to make sure that this property is never used internally on the Root instance.
if (this.IsRoot)
{
throw new InvalidOperationException("Can't be called on Root.");
}
#endif
return this.target;
}
}
internal bool IsRoot => object.ReferenceEquals(this, Root);
/// <inheritdoc />
public override int GetHashCode() => Helpers.Hash(this.implementationType, this.target);
/// <inheritdoc />
public override bool Equals(object obj) => this.Equals(obj as InjectionConsumerInfo);
/// <inheritdoc />
public bool Equals(InjectionConsumerInfo? other) =>
other != null
&& this.implementationType.Equals(other.implementationType)
&& this.target.Equals(other.target);
/// <inheritdoc />
public override string ToString() =>
"{ ImplementationType: " + this.implementationType.ToFriendlyName() +
", Target.Name: '" + this.target.Name + "' }";
}
}
|
simpleinjector/SimpleInjector
|
src/SimpleInjector/InjectionConsumerInfo.cs
|
C#
|
mit
| 4,517
|
app.service('UserService', function (FIREBASE_URL, $firebase) {
var connectedUsersRef = new Firebase(FIREBASE_URL + 'whiteBoard/connectedUsers');
this.userRef = null;
this.setCurrentUser = function(user) {
this.userRef = connectedUsersRef.push(user);
this.userRef.onDisconnect().remove();
};
this.getConnectedUsersRef = function() {
return $firebase(connectedUsersRef);
};
this.getCurrentUserKey = function() {
return this.userRef.name();
};
});
|
thomaswinckell/angularfire-white-board
|
src/app/service/userService.js
|
JavaScript
|
mit
| 515
|
package iso20022
// Account to or from which a securities entry is made.
type SubAccountIdentification11 struct {
// Party that legally owns the account.
AccountOwner *PartyIdentification13Choice `xml:"AcctOwnr,omitempty"`
// Account to or from which a securities entry is made.
SafekeepingAccount *SecuritiesAccount14 `xml:"SfkpgAcct"`
// Indicates whether there is activity or information update reported in the statement.
ActivityIndicator *YesNoIndicator `xml:"ActvtyInd"`
// Net position of a segregated holding, in a single security, within the overall position held in a securities subaccount.
BalanceForSubAccount []*AggregateBalanceInformation9 `xml:"BalForSubAcct,omitempty"`
}
func (s *SubAccountIdentification11) AddAccountOwner() *PartyIdentification13Choice {
s.AccountOwner = new(PartyIdentification13Choice)
return s.AccountOwner
}
func (s *SubAccountIdentification11) AddSafekeepingAccount() *SecuritiesAccount14 {
s.SafekeepingAccount = new(SecuritiesAccount14)
return s.SafekeepingAccount
}
func (s *SubAccountIdentification11) SetActivityIndicator(value string) {
s.ActivityIndicator = (*YesNoIndicator)(&value)
}
func (s *SubAccountIdentification11) AddBalanceForSubAccount() *AggregateBalanceInformation9 {
newValue := new(AggregateBalanceInformation9)
s.BalanceForSubAccount = append(s.BalanceForSubAccount, newValue)
return newValue
}
|
fgrid/iso20022
|
SubAccountIdentification11.go
|
GO
|
mit
| 1,384
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34014
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MetaBak.Gui.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MetaBak.Gui.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
|
sirmmo/MetaBack
|
MetaBak/MetaBak.Gui/Properties/Resources.Designer.cs
|
C#
|
mit
| 2,787
|
const server = require('./server')
const port = process.env.PORT || 3000
server.listen(port, () => {
console.log('Listening on port %s', port)
})
|
hexjelly/url-shortener-microservice
|
index.js
|
JavaScript
|
mit
| 149
|
/* eslint-disable */
const NODE_ENV = process.env.NODE_ENV;
if (NODE_ENV !== 'development' && NODE_ENV !== 'production') {
throw new Error('NODE_ENV must either be set to development or production.');
}
global.__DEV__ = NODE_ENV === 'development';
global.requestAnimationFrame = function(callback) {
setTimeout(callback);
};
global.requestIdleCallback = function(callback) {
return setTimeout(() => {
callback({
timeRemaining() {
return Infinity;
},
});
});
};
global.cancelIdleCallback = function(callbackID) {
clearTimeout(callbackID);
};
// By default React console.error()'s any errors, caught or uncaught.
// However it is annoying to assert that a warning fired each time
// we assert that there is an exception in our tests. This lets us
// opt out of extra console error reporting for most tests except
// for the few that specifically test the logging by shadowing this
// property. In real apps, it would usually not be defined at all.
Error.prototype.suppressReactErrorLogging = true;
if (typeof window !== 'undefined') {
// Same as above.
DOMException.prototype.suppressReactErrorLogging = true;
// Also prevent JSDOM from logging intentionally thrown errors.
// TODO: it might make sense to do it the other way around.
// https://github.com/facebook/react/issues/11098#issuecomment-355032539
window.addEventListener('error', event => {
if (event.error != null && event.error.suppressReactErrorLogging) {
event.preventDefault();
}
});
}
// Preserve the empty object identity across module resets.
// This is needed for some tests that rely on string refs
// but reset modules between loading different renderers.
const obj = require.requireActual('fbjs/lib/emptyObject');
jest.mock('fbjs/lib/emptyObject', () => obj);
|
prometheansacrifice/react
|
scripts/jest/setupEnvironment.js
|
JavaScript
|
mit
| 1,804
|
package org.jscala
import scala.reflect.macros.blackbox
/**
* Author: Alexander Nemish
*/
trait SyntaxConverter[C <: blackbox.Context] extends BasisConverter[C] {
import c.universe._
protected lazy val jsReturn1: ToExpr[JsStmt] = {
case Return(expr) => q"org.jscala.JsReturn(${jsExprOrDie(expr)})"
}
protected lazy val jsReturn: ToExpr[JsStmt] = jsReturnStmt orElse jsStmtOrDie
protected lazy val jsReturnStmt: ToExpr[JsReturn] = jsExpr andThen (jsExpr => q"org.jscala.JsReturn($jsExpr)")
protected lazy val jsIfStmt: ToExpr[JsIf] = {
case q"if ($cond) $thenp else $elsep" =>
val condJsExpr = jsExprOrDie(cond)
val thenJsExpr = jsStmtOrDie(thenp)
val elseJsStmt = if (isUnit(elsep)) q"None" else q"Some(${jsStmtOrDie(elsep)})"
q"org.jscala.JsIf($condJsExpr, $thenJsExpr, $elseJsStmt)"
}
protected lazy val jsTernaryExpr: ToExpr[JsTernary] = {
case q"if ($cond) $thenp else $elsep" if !thenp.tpe.=:=(typeOf[Unit]) && !isUnit(elsep) && jsExpr.isDefinedAt(thenp) && jsExpr.isDefinedAt(elsep) =>
val condJsExpr = jsExprOrDie(cond)
val thenJsExpr = jsExprOrDie(thenp)
val elseExpr = jsExprOrDie(elsep)
q"org.jscala.JsTernary($condJsExpr, $thenJsExpr, $elseExpr)"
}
protected lazy val jsWhileStmt: ToExpr[JsWhile] = {
case q"while ($cond) $body" =>
val condJsExpr = jsExprOrDie(cond)
val bodyJsStmt = jsStmtOrDie(body)
q"org.jscala.JsWhile($condJsExpr, $bodyJsStmt)"
}
private def addAssign(tree: Tree, name: Name) = tree match {
case Block(stats, expr) => Block(stats :+ Assign(Ident(name), expr), q"()")
case expr => Block(Assign(Ident(name), expr) :: Nil, q"()")
}
protected lazy val jsIfExpr: PartialFunction[(Name, Tree), Tree] = {
case (name, If(cond, thenp, elsep)) =>
val condJsExpr = jsExprOrDie(cond)
val thenJsExpr = jsStmtOrDie(addAssign(thenp, name))
val elseJsExpr = jsStmtOrDie(addAssign(elsep, name))
q"org.jscala.JsIf($condJsExpr, $thenJsExpr, Some($elseJsExpr))"
}
protected lazy val jsMatchExpr: PartialFunction[(Name, Tree), Tree] = {
case (name, Match(expr, cases)) => jsSwitchGen(expr, cases, body => addAssign(body, name))
}
protected lazy val jsVarDefStmt: ToExpr[JsStmt] = {
case ValDef(_, name, _, rhs) =>
val identifier = name.decodedName.toString
if (jsTernaryExpr.isDefinedAt(rhs)) {
q"org.jscala.JsVarDef($identifier, ${jsTernaryExpr(rhs)})"
} else {
val funcs = Seq(jsIfExpr, jsMatchExpr).reduceLeft(_ orElse _) andThen { expr =>
q"org.jscala.JsStmts(List(org.jscala.JsVarDef($identifier, org.jscala.JsUnit), $expr))"
}
val x = name -> rhs
funcs.applyOrElse(x, (t: (TermName, Tree)) => {
q"org.jscala.JsVarDef($identifier, ${jsExprOrDie(rhs)})"
})
}
}
protected lazy val jsFunBody: ToExpr[JsBlock] = {
case lit@Literal(_) =>
val body = if (isUnit(lit)) Nil else List(jsReturnStmt(lit))
q"org.jscala.JsBlock(${listToExpr(body)})"
case b@Block(stmts, expr) =>
val lastExpr = if (isUnit(expr)) Nil
else if (expr.tpe =:= typeOf[Unit]) List(jsStmtOrDie(expr))
else List(jsReturn(expr))
val ss = listToExpr(stmts.map(jsStmtOrDie) ::: lastExpr)
q"org.jscala.JsBlock($ss)"
case rhs =>
if (rhs.tpe =:= typeOf[Unit]) q"org.jscala.JsBlock(List(${jsStmtOrDie(rhs)}))"
else q"org.jscala.JsBlock(List(${jsReturn(rhs)}))"
}
protected lazy val jsFunDecl: ToExpr[JsFunDecl] = {
case DefDef(_, name, _, vparamss, _, rhs) =>
val ident = name.decodedName.toString
val a = vparamss.headOption.map(vp => vp.map(v => q"${v.name.decodedName.toString}")).getOrElse(Nil)
val params = listToExpr(a)
val body = jsFunBody(rhs)
q"org.jscala.JsFunDecl($ident, $params, $body)"
}
protected lazy val jsAnonFunDecl: ToExpr[JsAnonFunDecl] = {
case Block(Nil, Function(vparams, rhs)) =>
val params = listToExpr(vparams.map(v => q"${v.name.decodedName.toString}"))
val body = jsFunBody(rhs)
q"org.jscala.JsAnonFunDecl($params, $body)"
case Function(vparams, rhs) =>
val params = listToExpr(vparams.map(v => q"${v.name.decodedName.toString}"))
val body = jsFunBody(rhs)
q"org.jscala.JsAnonFunDecl($params, $body)"
}
protected lazy val jsTry: ToExpr[JsTry] = {
case q"try $body catch { case ..$catchBlock } finally $finBody" =>
// case Try(body, catchBlock, finBody) =>
val ctch = catchBlock match {
case Nil => q"None"
case List(CaseDef(Bind(pat, _), EmptyTree, catchBody)) =>
q"Some(org.jscala.JsCatch(org.jscala.JsIdent(${pat.decodedName.toString}), ${jsStmtOrDie(catchBody)}))"
}
val fin = if (finBody.equalsStructure(EmptyTree)) q"None"
else q"Some(${jsStmtOrDie(finBody)})"
q"org.jscala.JsTry(${jsStmtOrDie(body)}, $ctch, $fin)"
}
protected lazy val jsThrowExpr: ToExpr[JsThrow] = {
case Throw(expr) => q"org.jscala.JsThrow(${jsExprOrDie(expr)})"
}
private def jsSwitchGen(expr: Tree, cases: List[CaseDef], f: Tree => Tree) = {
val cs = cases collect {
case CaseDef(const@Literal(Constant(_)), EmptyTree, body) => q"org.jscala.JsCase(List(${jsLit(const)}), ${jsStmtOrDie(f(body))})"
case CaseDef(sel@Select(path, n), EmptyTree, body) =>
q"org.jscala.JsCase(List(${jsExprOrDie(sel)}), ${jsStmtOrDie(f(body))})"
case CaseDef(Alternative(xs), EmptyTree, body) =>
val stmt = jsStmtOrDie(f(body))
val consts = listToExpr(xs map(c => jsLit(c)))
q"org.jscala.JsCase($consts, $stmt)"
}
val df = (cases collect {
case CaseDef(Ident(termNames.WILDCARD), EmptyTree, body) => q"Some(org.jscala.JsDefault(${jsStmtOrDie(f(body))}))"
}).headOption.getOrElse(q"None")
val css = listToExpr(cs)
q"org.jscala.JsSwitch(${jsExprOrDie(expr)}, $css, $df)"
}
protected lazy val jsSwitch: ToExpr[JsSwitch] = {
case Match(expr, cases) => jsSwitchGen(expr, cases, t => t)
}
}
|
nau/jscala
|
jscala/src/main/scala/org/jscala/SyntaxConverter.scala
|
Scala
|
mit
| 6,050
|
import { NgModule } from '@angular/core';
import { SharedModule } from '../shared/shared.module';
import { ArchivesRoutingModule } from './archives-routing.module';
import { ArchiveDetailResolve } from './archive-detail/archive-detail-resolve.service';
import { ArchiveDetailComponent } from './archive-detail/archive-detail.component';
import { ArchivesComponent } from './archives.component';
import { ArchiveService } from './shared/archive.service';
import { ArchiveComponent } from './archive/archive.component';
import { ArchiveListComponent } from './archive-list/archive-list.component';
@NgModule({
imports: [
SharedModule,
ArchivesRoutingModule
],
declarations: [
ArchivesComponent,
ArchiveComponent,
ArchiveDetailComponent,
ArchiveComponent,
ArchiveListComponent
],
providers: [
ArchiveService,
ArchiveDetailResolve
]
})
export class ArchivesModule { }
|
ATConference/atc-website
|
src/app/archives/archives.module.ts
|
TypeScript
|
mit
| 915
|
[](https://godoc.org/github.com/jackc/pgtype)
# pgtype
pgtype implements Go types for over 70 PostgreSQL types. pgtype is the type system underlying the
https://github.com/jackc/pgx PostgreSQL driver. These types support the binary format for enhanced performance with pgx.
They also support the database/sql `Scan` and `Value` interfaces and can be used with https://github.com/lib/pq.
|
dollarshaveclub/furan
|
vendor/github.com/jackc/pgtype/README.md
|
Markdown
|
mit
| 446
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.