repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
Reaver01/mhowebsite | monsters/gypceros/data.js | 3211 | var weaknessArray = [
{
"iID": "8000042",
"data": [
"8000042",
"毒怪鸟",
"Head",
"2",
"4",
"4",
"3",
"1",
"0",
"1",
"0",
"3",
"3",
"3",
"3",
"3",
"0",
"0",
"0",
"",
"0"
]
},
{
"iID": "8000043",
"data": [
"8000043",
"毒怪鸟",
"Neck",
"3",
"2",
"3",
"2",
"0",
"0",
"0",
"0",
"3",
"",
"",
"",
"",
"",
"",
"",
"",
"0"
]
},
{
"iID": "8000044",
"data": [
"8000044",
"毒怪鸟",
"Torso",
"4",
"2",
"1",
"1",
"0",
"0",
"0",
"0",
"0",
"",
"",
"",
"",
"",
"",
"",
"",
"0"
]
},
{
"iID": "8000045",
"data": [
"8000045",
"毒怪鸟",
"Tail",
"4",
"4",
"4",
"2",
"0",
"0",
"0",
"0",
"0",
"",
"",
"",
"",
"",
"",
"",
"",
"0"
]
},
{
"iID": "8000046",
"data": [
"8000046",
"毒怪鸟",
"Left Wing",
"3",
"2",
"2",
"2",
"1",
"0",
"0",
"1",
"0",
"",
"",
"",
"",
"",
"",
"",
"",
"0"
]
},
{
"iID": "8000047",
"data": [
"8000047",
"毒怪鸟",
"Right Wing",
"3",
"2",
"2",
"2",
"1",
"0",
"0",
"1",
"0",
"",
"",
"",
"",
"",
"",
"",
"",
"0"
]
},
{
"iID": "8000048",
"data": [
"8000048",
"毒怪鸟",
"Left Leg",
"2",
"2",
"2",
"0",
"0",
"0",
"0",
"0",
"0",
"",
"",
"",
"",
"",
"",
"",
"",
"0"
]
},
{
"iID": "8000049",
"data": [
"8000049",
"毒怪鸟",
"Right Leg",
"2",
"2",
"2",
"0",
"0",
"0",
"0",
"0",
"0",
"",
"",
"",
"",
"",
"",
"",
"",
"0"
]
}
]; | mit |
thorkd1t/lurkbot | gogogo.py | 226 | import lurkbotclass
import joinlist
import sys
bots = {}
thename = sys.argv[1]
def gobots(name):
global bots
bots[name] = lurkbotclass.LurkBot(name)
bots[name].ircJoin(name)
gobots(thename)
| mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_network/lib/2018-06-01/generated/azure_mgmt_network/load_balancer_load_balancing_rules.rb | 14785 | # 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::V2018_06_01
#
# LoadBalancerLoadBalancingRules
#
class LoadBalancerLoadBalancingRules
include MsRestAzure
#
# Creates and initializes a new instance of the LoadBalancerLoadBalancingRules class.
# @param client service class for accessing basic functionality.
#
def initialize(client)
@client = client
end
# @return [NetworkManagementClient] reference to the NetworkManagementClient
attr_reader :client
#
# Gets all the load balancing rules in a load balancer.
#
# @param resource_group_name [String] The name of the resource group.
# @param load_balancer_name [String] The name of the load balancer.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<LoadBalancingRule>] operation results.
#
def list(resource_group_name, load_balancer_name, custom_headers:nil)
first_page = list_as_lazy(resource_group_name, load_balancer_name, custom_headers:custom_headers)
first_page.get_all_items
end
#
# Gets all the load balancing rules in a load balancer.
#
# @param resource_group_name [String] The name of the resource group.
# @param load_balancer_name [String] The name of the load balancer.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_with_http_info(resource_group_name, load_balancer_name, custom_headers:nil)
list_async(resource_group_name, load_balancer_name, custom_headers:custom_headers).value!
end
#
# Gets all the load balancing rules in a load balancer.
#
# @param resource_group_name [String] The name of the resource group.
# @param load_balancer_name [String] The name of the load balancer.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_async(resource_group_name, load_balancer_name, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'load_balancer_name is nil' if load_balancer_name.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/loadBalancingRules'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'loadBalancerName' => load_balancer_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2018_06_01::Models::LoadBalancerLoadBalancingRuleListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets the specified load balancer load balancing rule.
#
# @param resource_group_name [String] The name of the resource group.
# @param load_balancer_name [String] The name of the load balancer.
# @param load_balancing_rule_name [String] The name of the load balancing rule.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [LoadBalancingRule] operation results.
#
def get(resource_group_name, load_balancer_name, load_balancing_rule_name, custom_headers:nil)
response = get_async(resource_group_name, load_balancer_name, load_balancing_rule_name, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Gets the specified load balancer load balancing rule.
#
# @param resource_group_name [String] The name of the resource group.
# @param load_balancer_name [String] The name of the load balancer.
# @param load_balancing_rule_name [String] The name of the load balancing rule.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def get_with_http_info(resource_group_name, load_balancer_name, load_balancing_rule_name, custom_headers:nil)
get_async(resource_group_name, load_balancer_name, load_balancing_rule_name, custom_headers:custom_headers).value!
end
#
# Gets the specified load balancer load balancing rule.
#
# @param resource_group_name [String] The name of the resource group.
# @param load_balancer_name [String] The name of the load balancer.
# @param load_balancing_rule_name [String] The name of the load balancing rule.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def get_async(resource_group_name, load_balancer_name, load_balancing_rule_name, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'load_balancer_name is nil' if load_balancer_name.nil?
fail ArgumentError, 'load_balancing_rule_name is nil' if load_balancing_rule_name.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/loadBalancingRules/{loadBalancingRuleName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'loadBalancerName' => load_balancer_name,'loadBalancingRuleName' => load_balancing_rule_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2018_06_01::Models::LoadBalancingRule.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets all the load balancing rules in a load balancer.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [LoadBalancerLoadBalancingRuleListResult] operation results.
#
def list_next(next_page_link, custom_headers:nil)
response = list_next_async(next_page_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Gets all the load balancing rules in a load balancer.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_next_with_http_info(next_page_link, custom_headers:nil)
list_next_async(next_page_link, custom_headers:custom_headers).value!
end
#
# Gets all the load balancing rules in a load balancer.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_next_async(next_page_link, custom_headers:nil)
fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
skip_encoding_path_params: {'nextLink' => next_page_link},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2018_06_01::Models::LoadBalancerLoadBalancingRuleListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets all the load balancing rules in a load balancer.
#
# @param resource_group_name [String] The name of the resource group.
# @param load_balancer_name [String] The name of the load balancer.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [LoadBalancerLoadBalancingRuleListResult] which provide lazy access
# to pages of the response.
#
def list_as_lazy(resource_group_name, load_balancer_name, custom_headers:nil)
response = list_async(resource_group_name, load_balancer_name, custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_page_link|
list_next_async(next_page_link, custom_headers:custom_headers)
end
page
end
end
end
end
| mit |
hail-is/hail | libhail/src/hail/vtype.hpp | 3028 | #ifndef HAIL_VTYPE_HPP_INCLUDED
#define HAIL_VTYPE_HPP_INCLUDED 1
#include "hail/type.hpp"
namespace hail {
class TBool;
class TInt32;
class TInt64;
class TFloat32;
class TFloat64;
class TStr;
class TArray;
class TTuple;
class VType {
public:
using BaseType = VType;
enum class Tag {
VOID,
BOOL,
INT32,
INT64,
FLOAT32,
FLOAT64,
STR,
ARRAY,
STREAM,
TUPLE
};
const Tag tag;
const Type *type;
size_t alignment;
size_t byte_size;
VType(Tag tag, const Type *type, size_t alignment, size_t byte_size)
: tag(tag),
type(type),
alignment(alignment),
byte_size(byte_size) {}
virtual ~VType();
};
class VBool : public VType {
public:
static bool is_instance_tag(Tag tag) { return tag == VType::Tag::BOOL; }
VBool(TypeContextToken, const TBool *type) : VType(VType::Tag::BOOL, type, 1, 1) {}
};
class VInt32 : public VType {
public:
static bool is_instance_tag(Tag tag) { return tag == VType::Tag::INT32; }
VInt32(TypeContextToken, const TInt32 *type) : VType(VType::Tag::INT32, type, 4, 4) {}
};
class VInt64 : public VType {
public:
static bool is_instance_tag(Tag tag) { return tag == VType::Tag::INT64; }
VInt64(TypeContextToken, const TInt64 *type) : VType(VType::Tag::INT64, type, 8, 8) {}
};
class VFloat32 : public VType {
public:
static bool is_instance_tag(Tag tag) { return tag == VType::Tag::FLOAT32; }
VFloat32(TypeContextToken, const TFloat32 *type) : VType(VType::Tag::FLOAT32, type, 4, 4) {}
};
class VFloat64 : public VType {
public:
static bool is_instance_tag(Tag tag) { return tag == VType::Tag::FLOAT64; }
VFloat64(TypeContextToken, const TFloat64 *type) : VType(VType::Tag::FLOAT64, type, 8, 8) {}
};
class VStr : public VType {
public:
static bool is_instance_tag(Tag tag) { return tag == VType::Tag::STR; }
VStr(TypeContextToken, const TStr *type) : VType(VType::Tag::STR, type, 8, 8) {}
};
class VArray : public VType {
public:
static bool is_instance_tag(Tag tag) { return tag == VType::Tag::ARRAY; }
const VType *const element_vtype;
size_t elements_alignment;
size_t element_stride;
VArray(TypeContextToken, const TArray *type, const VType *element_vtype)
: VType(VType::Tag::ARRAY, type, 8, 8),
element_vtype(element_vtype),
elements_alignment(make_aligned(element_vtype->byte_size, element_vtype->alignment)),
element_stride(make_aligned(element_vtype->byte_size, element_vtype->alignment)) {}
};
class VTuple : public VType {
friend class TypeContext;
public:
static bool is_instance_tag(Tag tag) { return tag == VType::Tag::TUPLE; }
const std::vector<const VType *> element_vtypes;
const std::vector<size_t> element_offsets;
VTuple(TypeContextToken,
const TTuple *type,
std::vector<const VType *> element_vtypes,
std::vector<size_t> element_offsets,
size_t alignment,
size_t byte_size)
: VType(VType::Tag::TUPLE, type, alignment, byte_size),
element_vtypes(element_vtypes),
element_offsets(element_offsets) {}
};
}
#endif
| mit |
novandypurnadrd/GradeControl | application/controllers/Closingstock/Boulder.php | 25935 |
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Boulder extends CI_Controller {
public function Boulder(){
parent::__construct();
$this->load->helper(array('url','form'));
$this->load->model('User_model');
$this->load->model('Oreline_model');
$this->load->model('OreInventory_model');
$this->load->model('Stockpile_model');
$this->load->model('ClosingStock_model');
$this->load->model('Pit_model');
$this->load->library('session');
}
public function Index(){
if ($this->session->userdata('GradeControl')) {
$data['main'] = "Boulder";
$data['dateStart'] = '';
$data['dateEnd'] = '';
$data['date'] = '';
$selectedstockpile = "";
$selectedyear = '0000-00-00';
$data['Table'] = $this->ClosingStock_model->GetBoulderbyDate($data['dateStart'],$data['dateEnd']);
$this->load->view('ClosingStock/Boulder', $data);
}else {
redirect(base_url());
}
}
public function InputBoulder()
{
if ($this->session->userdata('GradeControl')) {
$Date = $this->input->post('Date');
$Date = explode('/', $Date)[2].'-'.explode('/', $Date)[0].'-'.explode('/', $Date)[1];
$Volume = $this->input->post("Volume");
$Density = $this->input->post("Density");
$Tonnes = round(($Volume*$Density),2);
$Au = $this->input->post("Augt");
$Ag = $this->input->post("Aggt");
$AuEq75 = round($Au+($Ag/75),2);
$DryTon = $Tonnes;
$Boulder = array(
'Date' => $Date,
'Stockpile' => "Boulder",
'Volume' => $Volume,
'Density' => $Density,
'Tonnes' => $Tonnes,
'Au' => $Au,
'Ag' => $Ag,
'AuEq75' => $AuEq75,
'usrid' => $this->session->userdata('usernameGradeControl'),
);
$this->ClosingStock_model->InputBoulder($Boulder);
$v_Au = $Au;
$v_Ag = $Ag;
if (0.65<=$AuEq75 && $AuEq75<2.00){
$Class="Marginal";
}
elseif(2<=$AuEq75 && $AuEq75<4.00){
$Class="Medium Grade";
}
elseif(4<=$AuEq75 && $AuEq75<6.00){
$Class="High Grade";
}
else{
$Class="SHG";
}
$name = "Boulder";
$Stockpile = $this->ClosingStock_model->GetStockpilebyName($name);
$Stockpileboulder ="";
foreach ($Stockpile as $stockpile) {
$Stockpileboulder = $stockpile->id;
}
$Temp = $this->ClosingStock_model->GetClosingStockTonnesStockpile($Stockpileboulder);
foreach ($Temp as $temp) {
$Tonnes = $temp->Tonnes + $DryTon;
$Density = (($temp->Density*$temp->Tonnes)+($Density*$DryTon))/$Tonnes;
$v_Au = (($temp->Au*$temp->Tonnes)+($Au*$DryTon))/$Tonnes;
$v_Ag = (($temp->Ag*$temp->Tonnes)+($Ag*$DryTon))/$Tonnes;
$AuEq75 = round($v_Au+($v_Ag/75),2);
if (0.65<=$AuEq75 && $AuEq75<2.00){
$Class="Marginal";
}
elseif(2<=$AuEq75 && $AuEq75<4.00){
$Class="Medium Grade";
}
elseif(4<=$AuEq75 && $AuEq75<6.00){
$Class="High Grade";
}
else{
$Class="SHG";
}
$Volume = $Tonnes / $Density;
}
$Closing = array(
'Volume' => round($Volume,2),
'Au' => round($v_Au,2),
'Ag' => round($v_Ag,2),
'AuEq75' => round($AuEq75,2),
'Class' =>$Class,
'Tonnes' => $Tonnes,
'Density' => round($Density,2),
'Stockpile' => $Stockpileboulder,
'Date' => $Date,
'Status' => "Pending",
);
if($Temp){
$this->ClosingStock_model->UpdateClosingStockByStockpile($Closing,$Stockpileboulder);
}
else{
$this->ClosingStock_model->InputClosingStock($Closing);
}
//Check for Closing Stock Grade
$Volume = $this->input->post("Volume");
$Density = $this->input->post("Density");
$Au = $this->input->post("Augt");
$Ag = $this->input->post("Aggt");
$Temp = $this->ClosingStock_model->GetClosingStockByStockpileandDateGrade($Stockpileboulder,$Date);
foreach ($Temp as $temp) {
$Tonnes = $temp->Tonnes + $DryTon;
$Density = (($temp->Density*$temp->Tonnes)+($Density*$DryTon))/$Tonnes;
$v_Au = (($temp->Au*$temp->Tonnes)+($Au*$DryTon))/$Tonnes;
$v_Ag = (($temp->Ag*$temp->Tonnes)+($Ag*$DryTon))/$Tonnes;
$AuEq75 = round($v_Au+($v_Ag/75),2);
if (0.65<=$AuEq75 && $AuEq75<2.00){
$Class="Marginal";
}
elseif(2<=$AuEq75 && $AuEq75<4.00){
$Class="Medium Grade";
}
elseif(4<=$AuEq75 && $AuEq75<6.00){
$Class="High Grade";
}
else{
$Class="SHG";
}
$Volume = $Tonnes / $Density;
}
$Closing = array(
'Volume' => round($Volume,2),
'Au' => round($v_Au,2),
'Ag' => round($v_Ag,2),
'AuEq75' => round($AuEq75,2),
'Class' =>$Class,
'Tonnes' => $Tonnes,
'Density' => round($Density,2),
'Stockpile' => $Stockpileboulder,
'Date' => $Date,
//'Status' => "Pending",
);
if($Temp){
$this->ClosingStock_model->UpdateClosingStockByDateGrade($Closing,$Stockpileboulder,$Date);
}
else{
$this->ClosingStock_model->InputClosingStockGrade($Closing);
}
//Input To Stockpile
$Volume = $this->input->post("Volume");
$Density = $this->input->post("Density");
$Au = $this->input->post("Augt");
$Ag = $this->input->post("Aggt");
$Temp = $this->Stockpile_model->GetToStockpileCalcStockpile($Stockpileboulder);
foreach ($Temp as $temp) {
$Tonnes = $temp->Tonnes + $DryTon;
$Density = (($temp->Density*$temp->Tonnes)+($Density*$DryTon))/$Tonnes;
$v_Au = (($temp->Au*$temp->Tonnes)+($Au*$DryTon))/$Tonnes;
$v_Ag = (($temp->Ag*$temp->Tonnes)+($Ag*$DryTon))/$Tonnes;
$AuEq75 = round($v_Au+($v_Ag/75),2);
if (0.65 <= $AuEq75 && $AuEq75 < 2.00){
$Class="Marginal";
}
elseif(2<=$AuEq75 && $AuEq75<4.00){
$Class="Medium Grade";
}
elseif(4<=$AuEq75 && $AuEq75<6.00){
$Class="High Grade";
}
else{
$Class="SHG";
}
$Volume = round(($Tonnes / $Density),2);
$checker = 1;
}
$ToStockpile = array(
'Volume' => round($Volume,2),
'RL' => "",
'Au' => round($v_Au,2),
'Ag' => round($v_Ag,2),
'AuEq75' => round($AuEq75,2),
'Class' =>$Class,
'Tonnes' => $Tonnes,
'Density' => round($Density,2),
'Stockpile' => $Stockpileboulder,
'Date' => $Date,
);
if ($checker == 0) {
$this->Stockpile_model->InputToStockpile($ToStockpile);
}
else {
$this->Stockpile_model->UpdateToStockpilebyStockpile($ToStockpile, $Stockpileboulder);
}
redirect('ClosingStock/Boulder');
}
else {
redirect(base_url());
}
}
public function DeleteBoulder($id)
{
if ($this->session->userdata('GradeControl')) {
$StockpileBoulder = "";
$BoulderClosingstock = $this->ClosingStock_model->getBoulderbyId($id);
foreach ($BoulderClosingstock as $boulder) {
$BoulderTonnes = $boulder->Tonnes;
$BoulderVolume = $boulder->Volume;
$BoulderDensity = $boulder->Density;
$BoulderAu = $boulder->Au;
$BoulderAg = $boulder->Ag;
$Date = $boulder->Date;
$StockpileBoulder = $boulder->Stockpile;
}
$StockpileId = $this->Stockpile_model->getScatId($StockpileBoulder);
$Stockpile = "";
foreach ($StockpileId as $key) {
$Stockpile = $key->id;
}
//Update Closing Stock
$Closingstock = $this->ClosingStock_model->GetClosingStockTonnesStockpileNew($Stockpile);
foreach ($Closingstock as $key) {
$IdClosingstock = $key->id;
$TonnesClosingstock = $key->Tonnes;
$VolumeClosingstock = $key->Volume;
$AuClosingstock = $key->Au;
$AgClosingstock = $key->Ag;
$DensityClosingstock = $key->Density;
$Tonnes = $key->Tonnes;
}
$UpdateTonnes = $TonnesClosingstock-$BoulderTonnes;
if($UpdateTonnes > 0){
$UpdateAu = ((($AuClosingstock*$Tonnes)-($BoulderAu*$BoulderTonnes))/$UpdateTonnes);
$UpdateAg = round(((($AgClosingstock*$Tonnes)-($BoulderAg*$BoulderTonnes))/$UpdateTonnes),2);
$UpdateAuEq75 = round((($UpdateAu)+($UpdateAg/75)),2);
$UpdateDensity = round(((($DensityClosingstock*$TonnesClosingstock)-($BoulderDensity*$BoulderTonnes))/$UpdateTonnes),2);
$UpdateVolume = round(($UpdateTonnes/$UpdateDensity),2);
if (0.65 <= $UpdateAuEq75 && $UpdateAuEq75 < 2.00){
$Class="Marginal";
}
elseif(2<=$UpdateAuEq75 && $UpdateAuEq75<4.00){
$Class="Medium Grade";
}
elseif(4<=$UpdateAuEq75 && $UpdateAuEq75<6.00){
$Class="High Grade";
}
else{
$Class="SHG";
}
}
else{
$UpdateTonnes = 0;
$UpdateAu = 0;
$UpdateAg = 0;
$UpdateAuEq75 = 0;
$UpdateDensity = 0;
$UpdateVolume = 0;
$Class = "-";
}
$ClosingstockUpdate = array(
'Tonnes'=>$UpdateTonnes,
'Volume'=>$UpdateVolume,
'Density'=>$UpdateDensity,
'Au'=>round($UpdateAu,2),
'Ag'=>$UpdateAg,
'AuEq75'=>$UpdateAuEq75,
'Class'=>$Class,
);
$this->ClosingStock_model->UpdateClosingStock($ClosingstockUpdate,$IdClosingstock);
//Update Closng Stock Grade
$Closingstock = $this->ClosingStock_model->GetClosingStockByStockpileandDateGrade($Stockpile,$Date);
foreach ($Closingstock as $key) {
$IdClosingstock = $key->id;
$TonnesClosingstock = $key->Tonnes;
$VolumeClosingstock = $key->Volume;
$AuClosingstock = $key->Au;
$AgClosingstock = $key->Ag;
$DensityClosingstock = $key->Density;
$Tonnes = $key->Tonnes;
$UpdateTonnes = $TonnesClosingstock-$BoulderTonnes;
if($UpdateTonnes > 0){
$UpdateAu = ((($AuClosingstock*$Tonnes)-($BoulderAu*$BoulderTonnes))/$UpdateTonnes);
$UpdateAg = round(((($AgClosingstock*$Tonnes)-($BoulderAg*$BoulderTonnes))/$UpdateTonnes),2);
$UpdateAuEq75 = round((($UpdateAu)+($UpdateAg/75)),2);
$UpdateDensity = round(((($DensityClosingstock*$TonnesClosingstock)-($BoulderDensity*$BoulderTonnes))/$UpdateTonnes),2);
$UpdateVolume = round(($UpdateTonnes/$UpdateDensity),2);
if (0.65 <= $UpdateAuEq75 && $UpdateAuEq75 < 2.00){
$Class="Marginal";
}
elseif(2<=$UpdateAuEq75 && $UpdateAuEq75<4.00){
$Class="Medium Grade";
}
elseif(4<=$UpdateAuEq75 && $UpdateAuEq75<6.00){
$Class="High Grade";
}
else{
$Class="SHG";
}
}
else{
$UpdateTonnes = 0;
$UpdateAu = 0;
$UpdateAg = 0;
$UpdateAuEq75 = 0;
$UpdateDensity = 0;
$UpdateVolume = 0;
$Class = "-";
}
$ClosingstockUpdate = array(
'Tonnes'=>$UpdateTonnes,
'Volume'=>$UpdateVolume,
'Density'=>$UpdateDensity,
'Au'=>round($UpdateAu,2),
'Ag'=>$UpdateAg,
'AuEq75'=>$UpdateAuEq75,
'Class'=>$Class,
);
$this->ClosingStock_model->UpdateClosingStockGrade($ClosingstockUpdate,$IdClosingstock);
}
//Update To Stockpile
$Stockpile = $this->Stockpile_model->GetStockpileByStockpile($Stockpile);
foreach ($Stockpile as $stockpile) {
$AuStockpile = $stockpile->Au;
$AgStockpile = $stockpile->Ag;
$TonnesStockpile = $stockpile->Tonnes;
$DensityStockpile = $stockpile->Density;
$VolumeStockpile = $stockpile->Volume;
$RLStockpile = $stockpile->RL;
$StockpileMined = $stockpile->Stockpile;
$IdStockpile = $stockpile->id;
}
$UpdateTonnesStockpile = $TonnesStockpile-$BoulderTonnes;
if($UpdateTonnesStockpile > 0){
$UpdateAuStockpile = round(((($AuStockpile*$TonnesStockpile)-($BoulderAu*$BoulderTonnes))/$UpdateTonnesStockpile),2);
$UpdateAgStockpile = round(((($AgStockpile*$TonnesStockpile)-($BoulderAg*$BoulderTonnes))/$UpdateTonnesStockpile),2);
$UpdateDensityStockpile = round(((($DensityStockpile*$TonnesStockpile)-($BoulderDensity*$BoulderTonnes))/$UpdateTonnesStockpile),2);
$UpdateAuEq75Stockpile = round((($UpdateAuStockpile)+($UpdateAgStockpile/75)),2);
$UpdateStockpileVolume = round(($UpdateTonnesStockpile/$UpdateDensityStockpile),2);
$UpdateStockpileRL = $RLStockpile;
if (0.65 <= $UpdateAuEq75Stockpile && $UpdateAuEq75Stockpile < 2.00){
$ClassStockpile="Marginal";
}
elseif(2<=$UpdateAuEq75Stockpile && $UpdateAuEq75Stockpile<4.00){
$ClassStockpile="Medium Grade";
}
elseif(4<=$UpdateAuEq75Stockpile && $UpdateAuEq75Stockpile<6.00){
$ClassStockpile="High Grade";
}
else{
$ClassStockpile="SHG";
}
}
else{
$UpdateTonnesStockpile = 0;
$UpdateAuStockpile = 0;
$UpdateAgStockpile = 0;
$UpdateDensityStockpile = 0;
$UpdateAuEq75Stockpile = 0;
$UpdateStockpileVolume = 0;
$UpdateStockpileRL = "-";
$ClassStockpile ="-";
}
$UpdateStockpileStockpile = $StockpileMined;
$ToStockpile = array(
'Volume' => $UpdateStockpileVolume,
'RL' => $UpdateStockpileRL,
'Au' => $UpdateAuStockpile,
'Ag' => $UpdateAgStockpile,
'AuEq75' => $UpdateAuEq75Stockpile,
'Class' =>$ClassStockpile,
'Tonnes' => $UpdateTonnesStockpile,
'Density' => $UpdateDensityStockpile,
'Stockpile' => $UpdateStockpileStockpile,
'Date' => $Date,
);
$this->Stockpile_model->UpdateToStockpilebyStockpile($ToStockpile,$UpdateStockpileStockpile);
$this->ClosingStock_model->DeleteBoulder($id);
redirect('ClosingStock/Boulder');
}
else {
redirect(base_url());
}
}
public function index_update($id){
if ($this->session->userdata('GradeControl')) {
$data['main'] = "Boulder";
$data['View'] = $this->ClosingStock_model->getBoulderbyId($id);
$this->load->view('ClosingStock/Boulder_Update', $data);
}
else {
redirect(base_url());
}
}
public function UpdateBoulder($id)
{
if ($this->session->userdata('GradeControl')) {
$Boulder = $this->ClosingStock_model->getBoulderbyId($id);
foreach ($Boulder as $boulder) {
$BoulderTonnes = $boulder->Tonnes;
$BoulderStockpile = $boulder->Stockpile;
$BoulderDate = $boulder->Date;
$BoulderAu = $boulder->Au;
$BoulderAg = $boulder->Ag;
$BoulderDensity = $boulder->Density;
$BoulderVolume = $boulder->Volume;
}
$StockpileId = $this->Stockpile_model->getScatId($BoulderStockpile);
$Stockpile = "";
foreach ($StockpileId as $key) {
$Stockpile = $key->id;
}
//Update Closing Stock
$Closingstock = $this->ClosingStock_model->GetClosingStockTonnesStockpileNew($Stockpile);
foreach ($Closingstock as $key) {
$IdClosingstock = $key->id;
$TonnesClosingstock = $key->Tonnes;
$VolumeClosingstock = $key->Volume;
$AuClosingstock = $key->Au;
$AgClosingstock = $key->Ag;
$DensityClosingstock = $key->Density;
$Tonnes = $key->Tonnes;
}
$UpdateTonnes = $TonnesClosingstock-$BoulderTonnes;
if($UpdateTonnes > 0){
$UpdateAu = round(((($AuClosingstock*$Tonnes)-($BoulderAu*$BoulderTonnes))/$UpdateTonnes),2);
$UpdateAg = round(((($AgClosingstock*$Tonnes)-($BoulderAg*$BoulderTonnes))/$UpdateTonnes),2);
$UpdateAuEq75 = round((($UpdateAu)+($UpdateAg/75)),2);
$UpdateDensity = round(((($DensityClosingstock*$TonnesClosingstock)-($BoulderDensity*$BoulderTonnes))/$UpdateTonnes),2);
$UpdateVolume = round(($UpdateTonnes/$UpdateDensity),2);
if (0.65 <= $UpdateAuEq75 && $UpdateAuEq75 < 2.00){
$Class="Marginal";
}
elseif(2<=$UpdateAuEq75 && $UpdateAuEq75<4.00){
$Class="Medium Grade";
}
elseif(4<=$UpdateAuEq75 && $UpdateAuEq75<6.00){
$Class="High Grade";
}
else{
$Class="SHG";
}
}
else{
$UpdateTonnes = 0;
$UpdateAu = 0;
$UpdateAg = 0;
$UpdateAuEq75 = 0;
$UpdateDensity = 0;
$UpdateVolume = 0;
$Class = "-";
}
$ClosingstockUpdate = array(
'Tonnes'=>$UpdateTonnes,
'Volume'=>$UpdateVolume,
'Density'=>$UpdateDensity,
'Au'=>$UpdateAu,
'Ag'=>$UpdateAg,
'AuEq75'=>$UpdateAuEq75,
'Class'=>$Class,
);
$this->ClosingStock_model->UpdateClosingStock($ClosingstockUpdate,$IdClosingstock);
//Insert Closing Stock
$Date = $this->input->post('Date');
$Date = explode('/', $Date)[2].'-'.explode('/', $Date)[0].'-'.explode('/', $Date)[1];
$Volume = $this->input->post("Volume");
$Density = $this->input->post("Density");
$Au = $this->input->post("Augt");
$Ag = $this->input->post("Aggt");
$Tonnes = round(($Volume*$Density),2);
$DryTon = $Tonnes;
$Temp = $this->ClosingStock_model->GetClosingStockTonnesStockpile($Stockpile);
foreach ($Temp as $temp) {
$Tonnes = $temp->Tonnes + $DryTon;
$Density = (($temp->Density*$temp->Tonnes)+($Density*$DryTon))/$Tonnes;
$v_Au = (($temp->Au*$temp->Tonnes)+($Au*$DryTon))/$Tonnes;
$v_Ag = (($temp->Ag*$temp->Tonnes)+($Ag*$DryTon))/$Tonnes;
$AuEq75 = round($v_Au+($v_Ag/75),2);
if (0.65<=$AuEq75 && $AuEq75<2.00){
$Class="Marginal";
}
elseif(2<=$AuEq75 && $AuEq75<4.00){
$Class="Medium Grade";
}
elseif(4<=$AuEq75 && $AuEq75<6.00){
$Class="High Grade";
}
else{
$Class="SHG";
}
$Volume = $Tonnes / $Density;
}
$Closing = array(
'Volume' => round($Volume,2),
'Au' => round($v_Au,2),
'Ag' => round($v_Ag,2),
'AuEq75' => round($AuEq75,2),
'Class' =>$Class,
'Tonnes' => $Tonnes,
'Density' => round($Density,2),
'Stockpile' => $Stockpile,
'Status' => "Pending",
);
$this->ClosingStock_model->UpdateClosingStockByStockpile($Closing,$Stockpile);
//Update Closng Stock Grade
$Closingstock = $this->ClosingStock_model->GetClosingStockByStockpileandDateGrade($Stockpile,$Date);
foreach ($Closingstock as $key) {
$IdClosingstock = $key->id;
$TonnesClosingstock = $key->Tonnes;
$VolumeClosingstock = $key->Volume;
$AuClosingstock = $key->Au;
$AgClosingstock = $key->Ag;
$DensityClosingstock = $key->Density;
$Tonnes = $key->Tonnes;
$UpdateTonnes = $TonnesClosingstock-$BoulderTonnes;
if($UpdateTonnes > 0){
$UpdateAu = round(((($AuClosingstock*$Tonnes)-($BoulderAu*$ScatTonnes))/$UpdateTonnes),2);
$UpdateAg = round(((($AgClosingstock*$Tonnes)-($BoulderAg*$ScatTonnes))/$UpdateTonnes),2);
$UpdateAuEq75 = round((($UpdateAu)+($UpdateAg/75)),2);
$UpdateDensity = round(((($DensityClosingstock*$TonnesClosingstock)-($BoulderDensity*$BoulderTonnes))/$UpdateTonnes),2);
$UpdateVolume = round(($UpdateTonnes/$UpdateDensity),2);
if (0.65 <= $UpdateAuEq75 && $UpdateAuEq75 < 2.00){
$Class="Marginal";
}
elseif(2<=$UpdateAuEq75 && $UpdateAuEq75<4.00){
$Class="Medium Grade";
}
elseif(4<=$UpdateAuEq75 && $UpdateAuEq75<6.00){
$Class="High Grade";
}
else{
$Class="SHG";
}
}
else{
$UpdateTonnes = 0;
$UpdateAu = 0;
$UpdateAg = 0;
$UpdateAuEq75 = 0;
$UpdateDensity = 0;
$UpdateVolume = 0;
$Class = "-";
}
$ClosingstockUpdate = array(
'Tonnes'=>$UpdateTonnes,
'Volume'=>$UpdateVolume,
'Density'=>$UpdateDensity,
'Au'=>$UpdateAu,
'Ag'=>$UpdateAg,
'AuEq75'=>$UpdateAuEq75,
'Class'=>$Class,
);
$this->ClosingStock_model->UpdateClosingStockGrade($ClosingstockUpdate,$IdClosingstock);
}
//Check for Closing Stock Grade
$Volume = $this->input->post("Volume");
$Density = $this->input->post("Density");
$Au = $this->input->post("Augt");
$Ag = $this->input->post("Aggt");
$Tonnes = round(($Volume*$Density),2);
$DryTon = $Tonnes;
$Temp = $this->ClosingStock_model->GetClosingStockByStockpileandDateGrade($Stockpile,$Date);
foreach ($Temp as $temp) {
$Tonnes = $temp->Tonnes + $DryTon;
$Density = (($temp->Density*$temp->Tonnes)+($Density*$DryTon))/$Tonnes;
$v_Au = (($temp->Au*$temp->Tonnes)+($Au*$DryTon))/$Tonnes;
$v_Ag = (($temp->Ag*$temp->Tonnes)+($Ag*$DryTon))/$Tonnes;
$AuEq75 = round($v_Au+($v_Ag/75),2);
if (0.65<=$AuEq75 && $AuEq75<2.00){
$Class="Marginal";
}
elseif(2<=$AuEq75 && $AuEq75<4.00){
$Class="Medium Grade";
}
elseif(4<=$AuEq75 && $AuEq75<6.00){
$Class="High Grade";
}
else{
$Class="SHG";
}
$Volume = $Tonnes / round($Density,2);
$IdClosingstock = $temp->id;
$Closing = array(
'Volume' => round($Volume,2),
'Au' => round($v_Au,2),
'Ag' => round($v_Ag,2),
'AuEq75' => round($AuEq75,2),
'Class' =>$Class,
'Tonnes' => $Tonnes,
'Density' => round($Density,2),
'Stockpile' => $Stockpile,
//'Status' => "Pending",
);
$this->ClosingStock_model->UpdateClosingStockGrade($Closing,$IdClosingstock);
}
//Update To Stockpile
$StockpileA = $this->Stockpile_model->GetStockpileByStockpile($Stockpile);
foreach ($StockpileA as $stockpile) {
$AuStockpile = $stockpile->Au;
$AgStockpile = $stockpile->Ag;
$TonnesStockpile = $stockpile->Tonnes;
$DensityStockpile = $stockpile->Density;
$VolumeStockpile = $stockpile->Volume;
$RLStockpile = $stockpile->RL;
$StockpileMined = $stockpile->Stockpile;
$IdStockpile = $stockpile->id;
}
$UpdateTonnesStockpile = $TonnesStockpile-$BoulderTonnes;
if($UpdateTonnesStockpile > 0){
$UpdateAuStockpile = round(((($AuStockpile*$TonnesStockpile)-($BoulderAu*$BoulderTonnes))/$UpdateTonnesStockpile),2);
$UpdateAgStockpile = round(((($AgStockpile*$TonnesStockpile)-($BoulderAg*$BoulderTonnes))/$UpdateTonnesStockpile),2);
$UpdateDensityStockpile = round(((($DensityStockpile*$TonnesStockpile)-($BoulderDensity*$BoulderTonnes))/$UpdateTonnesStockpile),2);
$UpdateAuEq75Stockpile = round((($UpdateAuStockpile)+($UpdateAgStockpile/75)),2);
$UpdateStockpileVolume = round(($UpdateTonnesStockpile/$UpdateDensityStockpile),2);
$UpdateStockpileRL = $RLStockpile;
$UpdateStockpileStockpile = $StockpileMined;
if (0.65 <= $UpdateAuEq75Stockpile && $UpdateAuEq75Stockpile < 2.00){
$ClassStockpile="Marginal";
}
elseif(2<=$UpdateAuEq75Stockpile && $UpdateAuEq75Stockpile<4.00){
$ClassStockpile="Medium Grade";
}
elseif(4<=$UpdateAuEq75Stockpile && $UpdateAuEq75Stockpile<6.00){
$ClassStockpile="High Grade";
}
else{
$ClassStockpile="SHG";
}
}
else{
$UpdateTonnesStockpile = 0;
$UpdateAuStockpile = 0;
$UpdateAgStockpile = 0;
$UpdateDensityStockpile = 0;
$UpdateAuEq75Stockpile = 0;
$UpdateStockpileVolume = 0;
$UpdateStockpileRL = "-";
$ClassStockpile ="-";
$UpdateStockpileStockpile = $StockpileMined;
}
$ToStockpile = array(
'Volume' => $UpdateStockpileVolume,
'RL' => $UpdateStockpileRL,
'Au' => $UpdateAuStockpile,
'Ag' => $UpdateAgStockpile,
'AuEq75' => $UpdateAuEq75Stockpile,
'Class' =>$ClassStockpile,
'Tonnes' => $UpdateTonnesStockpile,
'Density' => $UpdateDensityStockpile,
'Stockpile' => $UpdateStockpileStockpile,
);
$this->Stockpile_model->UpdateToStockpilebyStockpile($ToStockpile,$UpdateStockpileStockpile);
//Input To Stockpile
$Volume = $this->input->post("Volume");
$Density = $this->input->post("Density");
$Au = $this->input->post("Augt");
$Ag = $this->input->post("Aggt");
$Tonnes = round(($Volume*$Density),2);
$DryTon = $Tonnes;
$Temp = $this->Stockpile_model->GetToStockpileCalcStockpile($Stockpile);
foreach ($Temp as $temp) {
$Tonnes = $temp->Tonnes + $DryTon;
$Density = (($temp->Density*$temp->Tonnes)+($Density*$DryTon))/$Tonnes;
$v_Au = (($temp->Au*$temp->Tonnes)+($Au*$DryTon))/$Tonnes;
$v_Ag = (($temp->Ag*$temp->Tonnes)+($Ag*$DryTon))/$Tonnes;
$AuEq75 = round($v_Au+($v_Ag/75),2);
if (0.65 <= $AuEq75 && $AuEq75 < 2.00){
$Class="Marginal";
}
elseif(2<=$AuEq75 && $AuEq75<4.00){
$Class="Medium Grade";
}
elseif(4<=$AuEq75 && $AuEq75<6.00){
$Class="High Grade";
}
else{
$Class="SHG";
}
$Volume = round(($Tonnes / $Density),2);
$checker = 1;
}
$ToStockpile = array(
'Volume' => round($Volume,2),
'RL' => "",
'Au' => round($v_Au,2),
'Ag' => round($v_Ag,2),
'AuEq75' => round($AuEq75,2),
'Class' =>$Class,
'Tonnes' => $Tonnes,
'Density' => round($Density,2),
'Stockpile' => $Stockpile,
);
$this->Stockpile_model->UpdateToStockpilebyStockpile($ToStockpile, $Stockpile);
//update tabel boulder
$Date = $this->input->post('Date');
$Date = explode('/', $Date)[2].'-'.explode('/', $Date)[0].'-'.explode('/', $Date)[1];
$Volume = $this->input->post("Volume");
$Density = $this->input->post("Density");
$Tonnes = round(($Volume*$Density),2);
$Au = $this->input->post("Augt");
$Ag = $this->input->post("Aggt");
$AuEq75 = round($Au+($Ag/75),2);
$DryTon = $Tonnes;
$Boulder = array(
'Date' => $Date,
'Stockpile' => "Boulder",
'Tonnes' => $Tonnes,
'Volume' => $Volume,
'Density' => $Density,
'Au' => $Au,
'Ag' => $Ag,
'AuEq75' => $AuEq75,
'usrid' => $this->session->userdata('usernameGradeControl'),
);
$this->ClosingStock_model->UpdateBoulder($Boulder,$id);
redirect('ClosingStock/Boulder');
}else {
redirect(base_url());
}
}
public function Filter(){
if ($this->session->userdata('GradeControl')) {
$data['main'] = "Boulder";
$data['dateStart'] = $this->input->post('start');
$data['dateEnd'] = $this->input->post('end');
$data['date'] = '';
$dateStart = explode('/',$data['dateStart'])[2].'-'.explode('/',$data['dateStart'])[0].'-'.explode('/',$data['dateStart'])[1];
$dateEnd = explode('/',$data['dateEnd'])[2].'-'.explode('/',$data['dateEnd'])[0].'-'.explode('/',$data['dateEnd'])[1];
$data['Table'] = $this->ClosingStock_model->GetBoulderbyDate($dateStart,$dateEnd);
$this->load->view('ClosingStock/Boulder', $data);
}else {
redirect(base_url());
}
}
}
?>
| mit |
digitalheir/lombok | src/core/lombok/javac/handlers/HandleToString.java | 10241 | /*
* Copyright © 2009-2011 Reinier Zwitserloot and Roel Spilker.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package lombok.javac.handlers;
import static lombok.javac.handlers.JavacHandlerUtil.*;
import lombok.ToString;
import lombok.core.AnnotationValues;
import lombok.core.AST.Kind;
import lombok.javac.Javac;
import lombok.javac.JavacAnnotationHandler;
import lombok.javac.JavacNode;
import lombok.javac.handlers.JavacHandlerUtil.FieldAccess;
import org.mangosdk.spi.ProviderFor;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import com.sun.tools.javac.tree.JCTree.JCModifiers;
import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
/**
* Handles the {@code ToString} annotation for javac.
*/
@ProviderFor(JavacAnnotationHandler.class)
public class HandleToString extends JavacAnnotationHandler<ToString> {
private void checkForBogusFieldNames(JavacNode type, AnnotationValues<ToString> annotation) {
if (annotation.isExplicit("exclude")) {
for (int i : createListOfNonExistentFields(List.from(annotation.getInstance().exclude()), type, true, false)) {
annotation.setWarning("exclude", "This field does not exist, or would have been excluded anyway.", i);
}
}
if (annotation.isExplicit("of")) {
for (int i : createListOfNonExistentFields(List.from(annotation.getInstance().of()), type, false, false)) {
annotation.setWarning("of", "This field does not exist.", i);
}
}
}
@Override public void handle(AnnotationValues<ToString> annotation, JCAnnotation ast, JavacNode annotationNode) {
deleteAnnotationIfNeccessary(annotationNode, ToString.class);
ToString ann = annotation.getInstance();
List<String> excludes = List.from(ann.exclude());
List<String> includes = List.from(ann.of());
JavacNode typeNode = annotationNode.up();
checkForBogusFieldNames(typeNode, annotation);
Boolean callSuper = ann.callSuper();
if (!annotation.isExplicit("callSuper")) callSuper = null;
if (!annotation.isExplicit("exclude")) excludes = null;
if (!annotation.isExplicit("of")) includes = null;
if (excludes != null && includes != null) {
excludes = null;
annotation.setWarning("exclude", "exclude and of are mutually exclusive; the 'exclude' parameter will be ignored.");
}
FieldAccess fieldAccess = ann.doNotUseGetters() ? FieldAccess.PREFER_FIELD : FieldAccess.GETTER;
generateToString(typeNode, annotationNode, excludes, includes, ann.includeFieldNames(), callSuper, true, fieldAccess);
}
public void generateToStringForType(JavacNode typeNode, JavacNode errorNode) {
for (JavacNode child : typeNode.down()) {
if (child.getKind() == Kind.ANNOTATION) {
if (Javac.annotationTypeMatches(ToString.class, child)) {
//The annotation will make it happen, so we can skip it.
return;
}
}
}
boolean includeFieldNames = true;
try {
includeFieldNames = ((Boolean)ToString.class.getMethod("includeFieldNames").getDefaultValue()).booleanValue();
} catch (Exception ignore) {}
generateToString(typeNode, errorNode, null, null, includeFieldNames, null, false, FieldAccess.GETTER);
}
private void generateToString(JavacNode typeNode, JavacNode source, List<String> excludes, List<String> includes,
boolean includeFieldNames, Boolean callSuper, boolean whineIfExists, FieldAccess fieldAccess) {
boolean notAClass = true;
if (typeNode.get() instanceof JCClassDecl) {
long flags = ((JCClassDecl)typeNode.get()).mods.flags;
notAClass = (flags & (Flags.INTERFACE | Flags.ANNOTATION)) != 0;
}
if (callSuper == null) {
try {
callSuper = ((Boolean)ToString.class.getMethod("callSuper").getDefaultValue()).booleanValue();
} catch (Exception ignore) {}
}
if (notAClass) {
source.addError("@ToString is only supported on a class or enum.");
return;
}
ListBuffer<JavacNode> nodesForToString = ListBuffer.lb();
if (includes != null) {
for (JavacNode child : typeNode.down()) {
if (child.getKind() != Kind.FIELD) continue;
JCVariableDecl fieldDecl = (JCVariableDecl) child.get();
if (includes.contains(fieldDecl.name.toString())) nodesForToString.append(child);
}
} else {
for (JavacNode child : typeNode.down()) {
if (child.getKind() != Kind.FIELD) continue;
JCVariableDecl fieldDecl = (JCVariableDecl) child.get();
//Skip static fields.
if ((fieldDecl.mods.flags & Flags.STATIC) != 0) continue;
//Skip excluded fields.
if (excludes != null && excludes.contains(fieldDecl.name.toString())) continue;
//Skip fields that start with $.
if (fieldDecl.name.toString().startsWith("$")) continue;
nodesForToString.append(child);
}
}
switch (methodExists("toString", typeNode)) {
case NOT_EXISTS:
JCMethodDecl method = createToString(typeNode, nodesForToString.toList(), includeFieldNames, callSuper, fieldAccess, source.get());
injectMethod(typeNode, method);
break;
case EXISTS_BY_LOMBOK:
break;
default:
case EXISTS_BY_USER:
if (whineIfExists) {
source.addWarning("Not generating toString(): A method with that name already exists");
}
break;
}
}
private JCMethodDecl createToString(JavacNode typeNode, List<JavacNode> fields, boolean includeFieldNames, boolean callSuper, FieldAccess fieldAccess, JCTree source) {
TreeMaker maker = typeNode.getTreeMaker();
JCAnnotation overrideAnnotation = maker.Annotation(chainDots(maker, typeNode, "java", "lang", "Override"), List.<JCExpression>nil());
JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.of(overrideAnnotation));
JCExpression returnType = chainDots(maker, typeNode, "java", "lang", "String");
boolean first = true;
String typeName = getTypeName(typeNode);
String infix = ", ";
String suffix = ")";
String prefix;
if (callSuper) {
prefix = typeName + "(super=";
} else if (fields.isEmpty()) {
prefix = typeName + "()";
} else if (includeFieldNames) {
prefix = typeName + "(" + ((JCVariableDecl)fields.iterator().next().get()).name.toString() + "=";
} else {
prefix = typeName + "(";
}
JCExpression current = maker.Literal(prefix);
if (callSuper) {
JCMethodInvocation callToSuper = maker.Apply(List.<JCExpression>nil(),
maker.Select(maker.Ident(typeNode.toName("super")), typeNode.toName("toString")),
List.<JCExpression>nil());
current = maker.Binary(Javac.getCtcInt(JCTree.class, "PLUS"), current, callToSuper);
first = false;
}
for (JavacNode fieldNode : fields) {
JCVariableDecl field = (JCVariableDecl) fieldNode.get();
JCExpression expr;
JCExpression fieldAccessor = createFieldAccessor(maker, fieldNode, fieldAccess);
if (getFieldType(fieldNode, fieldAccess) instanceof JCArrayTypeTree) {
boolean multiDim = ((JCArrayTypeTree)field.vartype).elemtype instanceof JCArrayTypeTree;
boolean primitiveArray = ((JCArrayTypeTree)field.vartype).elemtype instanceof JCPrimitiveTypeTree;
boolean useDeepTS = multiDim || !primitiveArray;
JCExpression hcMethod = chainDots(maker, typeNode, "java", "util", "Arrays", useDeepTS ? "deepToString" : "toString");
expr = maker.Apply(List.<JCExpression>nil(), hcMethod, List.<JCExpression>of(fieldAccessor));
} else expr = fieldAccessor;
if (first) {
current = maker.Binary(Javac.getCtcInt(JCTree.class, "PLUS"), current, expr);
first = false;
continue;
}
if (includeFieldNames) {
current = maker.Binary(Javac.getCtcInt(JCTree.class, "PLUS"), current, maker.Literal(infix + fieldNode.getName() + "="));
} else {
current = maker.Binary(Javac.getCtcInt(JCTree.class, "PLUS"), current, maker.Literal(infix));
}
current = maker.Binary(Javac.getCtcInt(JCTree.class, "PLUS"), current, expr);
}
if (!first) current = maker.Binary(Javac.getCtcInt(JCTree.class, "PLUS"), current, maker.Literal(suffix));
JCStatement returnStatement = maker.Return(current);
JCBlock body = maker.Block(0, List.of(returnStatement));
return Javac.recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName("toString"), returnType,
List.<JCTypeParameter>nil(), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), body, null), source);
}
private String getTypeName(JavacNode typeNode) {
String typeName = ((JCClassDecl) typeNode.get()).name.toString();
JavacNode upType = typeNode.up();
while (upType.getKind() == Kind.TYPE) {
typeName = ((JCClassDecl) upType.get()).name.toString() + "." + typeName;
upType = upType.up();
}
return typeName;
}
}
| mit |
jskjevling/legal-hover-text | gulpfile.js | 934 | var gulp = require('gulp');
var sass = require('gulp-sass');
var changed = require('gulp-changed');
var sassdoc = require('sassdoc');
var connect = require('gulp-connect');
gulp.task('styles', function() {
gulp.src('sass/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css/'))
.pipe(connect.reload());
});
//html change
gulp.task('htmlChange', function() {
gulp.src('./*.html')
.pipe(changed('/**/*.html'))
.pipe(connect.reload());
});
//js change
gulp.task('jsChange', function() {
gulp.src('script/*.js')
.pipe(changed('/**/*.js'))
.pipe(connect.reload());
});
//watch task
gulp.task('watch', function() {
gulp.watch('sass/**/*.scss', ['styles']);
gulp.watch('./*.html', ['htmlChange']);
gulp.watch('script/*.js', ['jsChange']);
});
//connect server
gulp.task('connect', function(){
connect.server({
livereload: true
});
});
//default
gulp.task('default', ['watch','connect']); | mit |
p-org/PSharpModels | Orleans/OrleansModel/OrleansModel/Model/GrainReminder.cs | 1357 | //-----------------------------------------------------------------------
// <copyright file="GrainReminder.cs">
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// 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.
// </copyright>
//-----------------------------------------------------------------------
using Orleans.Runtime;
using Microsoft.PSharp;
using Microsoft.PSharp.Actors;
namespace OrleansModel
{
internal class GrainReminder : ReminderCancellationSource, IGrainReminder
{
/// <summary>
/// Name of this Reminder.
/// </summary>
public string ReminderName
{
get;
private set;
}
public GrainReminder(MachineId actor, MachineId reminder, string reminderName)
: base(actor, reminder)
{
this.ReminderName = reminderName;
}
}
}
| mit |
Tec-Ptraktickcenter-Projects/Website | Site/include/Equipment_Handling/Show_equipment.php | 11292 | <style type="text/css">
.centerText{
text-align: center;
}
.even{
background-color:lightgray;
}
.uneven{
background-color:darkgray;
}
</style>
<?php
if(isset($_POST['create_item'])){
header("location:?administration=Opret udstyr");
}
if(isset($_POST['show_gant'])){
header("location:?administration=Gant-diagram");
}
function countEquipment($Equip_result,$db_conn,$Equip_sql)
{
?>
<hr>
<table border="0" width="755">
<tr class="uneven">
<th align="center">Type</th>
<th align="center">Producent</th>
<th align="center">Produkt navn</th>
<th align="center">Beskrivelse</th>
<th align="center">Antal</th>
</tr>
<?php
//Counting equipment
$temp_counter=1;
$type=array();
$producent=array();
$spec=array();
$unique_name = 0;
$name2_temp=array();
$name2_count=array();
while($Equip_row = mysqli_fetch_assoc($Equip_result))
{
if($unique_name==0)
{
array_unshift($name2_temp,$Equip_row['name2']);
array_unshift($type,$Equip_row['name']);
array_unshift($producent,$Equip_row['name1']);
array_unshift($spec,$Equip_row['spec']);
$unique_name++;
array_unshift($name2_count,1);
}
else
{
$count=0;
foreach($name2_temp as $value)
{
if($Equip_row['name2']==$value)
{
$name2_count[$count]++;
break;
}
else
{
array_unshift($type,$Equip_row['name']);
array_unshift($producent,$Equip_row['name1']);
array_unshift($spec,$Equip_row['spec']);
array_unshift($name2_temp,$Equip_row['name2']);
$unique_name++;
array_unshift($name2_count,1);
break;
}
$count++;
}
}
}
$Equip_result = mysqli_query($db_conn, $Equip_sql) or die(mysqli_error($db_conn));
$count=0;
foreach($name2_temp as $values)
{
if($temp_counter%2 == 0){
$even_uneven = "uneven";
}else{
$even_uneven = "even";
}
?>
<tr class="<?php echo $even_uneven; ?>">
<td><?php echo $type[$count]; ?></td>
<td><?php echo $producent[$count]; ?></td>
<td><?php echo $name2_temp[$count]; ?></td>
<td><?php echo $spec[$count]; ?></td>
<td><?php echo $name2_count[$count] ; ?></td>
</tr>
<?php
$temp_counter++;
$count++;
}
$temp_counter=1;
//End of counting and setup
}
function searchEquipment($Equip_result,$db_conn,$Equip_sql)
{
?>
<hr>
<table border="0" width="755">
<tr class="uneven">
<th align="center">Type</th>
<th align="center">Producent</th>
<th align="center">Produkt navn</th>
<th align="center">Beskrivelse</th>
<th align="center">Lokation</th>
</tr>
<?php
$temp_counter = 1;
while($Equip_row = mysqli_fetch_assoc($Equip_result)){
if($temp_counter%2 == 0){
$even_uneven = "uneven";
}else{
$even_uneven = "even";
}
?>
<tr class="<?php echo $even_uneven; ?>">
<td><?php echo $Equip_row['name']; ?></td>
<td><?php echo $Equip_row['name1']; ?></td>
<td><?php echo $Equip_row['name2']; ?></td>
<td><?php echo $Equip_row['spec']; ?></td>
<td><?php echo $Equip_row['lokation']; ?></td>
</tr>
<?php
$temp_counter++;
}
}
?>
<div>
<div style="position:relative" class="gantt" id="GanttChartDIV">
<script type="text/javascript">
var g= new JSGantt.GanttChart(document.getElementById('GanttChartDIV'), 'day');
</script>
</div>
<div class="centerText"><h2>Praktikcenterets udstyrs liste</h2></div>
<hr>
<?php
// Fetch all equipment types
$sql_equipment_type="select * from eqType";
$equipment_type_result = mysqli_query($db_conn, $sql_equipment_type) or die (mysqli_error($db_conn));
// Fetch all producents
$sql_producent="select * from producent ";
$producent_result = mysqli_query($db_conn, $sql_producent) or die (mysqli_error($db_conn));
// ===============================================================
?>
<div class="centerText">
<form method="post">
Type:
<select required name="eqType">
<option selected name="eqType" value="eqType">Vælg</option>
<?php
while ($equipment_type = mysqli_fetch_assoc($equipment_type_result)){
echo "<option value='".$equipment_type['id']."'>".$equipment_type['name']."</option>";
}
?>
</select>
Producent:
<select required name="producent">
<option selected name="producent" value="producent">Vælg</option>
<?php
while ($producent_list_row = mysqli_fetch_assoc($producent_result)){
echo "<option value='".$producent_list_row['id']."'>".$producent_list_row['name']."</option>";
}
?>
</select>
<input type="submit" id="show_info" name="show_info" value="Find">
</form>
<?php
if(isset($_SESSION['AddEquipment']) == 1)
{
?>
<form method="post">
<input type="submit" id="create_item" name="create_item" value="Opret udstyr">
</form>
<form method="post">
<input type="submit" id="show_gant" name="show_gant" value="Vis Gant-diagram">
</form>
<?php
}
?>
</div>
<?php/?>
<?php
if (isset($_POST['create_item'])){
}
if(isset($_POST['show_info'])){
$eqType = $_POST['eqType'];
$producent = $_POST['producent'];
// if producent and priduct type isset
if ($producent != 'producent' && $eqType != 'eqType'){
$Equip_sql="select eqType.name,
producent.name As name1,
equipment.spec,
equipment.name As name2,
equipment.fk_prodId,
equipment.sn,
equipment.fk_department As lokation From equipment,
Inner Join eqType On eqType.id = equipment.fk_eqTypeId
Inner Join producent On producent.id = equipment.fk_prodId
where fk_prodId = '$producent' AND fk_eqTypeId = '$eqType'
Order By name2 ASC, name1 ASC, sn ASC"; //WIP
$Equip_result = mysqli_query($db_conn, $Equip_sql) or die(mysqli_error($db_conn));
searchEquipment($Equip_result,$db_conn,$Equip_sql);
}
// if producent isset
elseif ($producent != 'producent') {
$Equip_sql="select eqType.name,
producent.name As name1,
equipment.spec,
equipment.name As name2,
equipment.fk_prodId,
equipment.sn,
equipment.fk_department as lokation From equipment
Inner Join departments on departments.id = equipment.fk_department
Inner Join eqType On eqType.id = equipment.fk_eqTypeId
Inner Join producent On producent.id = equipment.fk_prodId
where fk_prodId = '$producent'
Order By name2 ASC, name1 ASC, sn ASC"; //WIP
$Equip_result = mysqli_query($db_conn, $Equip_sql) or die(mysqli_error($db_conn));
searchEquipment($Equip_result,$db_conn,$Equip_sql);
}
// if product type isset
elseif($eqType != 'eqType'){
$Equip_sql="select eqType.name,
producent.name As name1,
equipment.spec,
equipment.name As name2,
equipment.fk_prodId,
equipment.sn,
equipment.fk_department As lokation From equipment
Inner Join eqType On eqType.id = equipment.fk_eqTypeId
Inner Join producent On producent.id = equipment.fk_prodId
where fk_eqTypeId = '$eqType'
Order By name2 ASC, name1 ASC, sn ASC"; //WIP
$Equip_result = mysqli_query($db_conn, $Equip_sql) or die(mysqli_error($db_conn));
searchEquipment($Equip_result,$db_conn,$Equip_sql);
}
else{
$Equip_sql = "Select eqType.name,
producent.name As name1,
equipment.spec,
equipment.name As name2,
equipment.fk_prodId,
equipment.sn,
equipment.fk_department As lokation From equipment
Inner Join eqType On eqType.id = equipment.fk_eqTypeId
Inner Join producent On producent.id = equipment.fk_prodId
Order By name2 ASC, name1 ASC, sn ASC";
$Equip_result = mysqli_query($db_conn, $Equip_sql) or die(mysqli_error($db_conn));
countEquipment($Equip_result,$db_conn,$Equip_sql);
}
}
else{
$Equip_sql = "Select eqType.name,
producent.name As name1,
equipment.spec,
equipment.name As name2,
equipment.fk_prodId,
equipment.sn,
equipment.fk_department As lokation From equipment
Inner Join eqType On eqType.id = equipment.fk_eqTypeId
Inner Join producent On producent.id = equipment.fk_prodId
Order By name2 ASC, name1 ASC, sn ASC";
$Equip_result = mysqli_query($db_conn, $Equip_sql) or die(mysqli_error($db_conn));
countEquipment($Equip_result,$db_conn,$Equip_sql);
}
?>
</table>
</div> | mit |
codenothing/CSSCompressor | lib/formats/None.js | 2673 | var CSSCompressor = global.CSSCompressor,
rvalueseparator = /^\/|,$/,
rselectorbreak = /^[\~\+\*\,>]$/;
// Const
CSSCompressor.FORMAT_NONE = 'none';
// Tree rendering
function render( css, branches ) {
branches.forEach(function( branch, branchIndex ) {
var newparts = [], nextBranch = branches[ branchIndex + 1 ], selector = '';
// Comments
if ( branch.comment ) {
css += branch.comment;
}
// Ruleset
else if ( branch.selector ) {
branch.parts.forEach(function( part, i ) {
var prev = branch.parts[ i - 1 ];
if ( selector.length && ! rselectorbreak.exec( part ) && ! rselectorbreak.exec( prev ) ) {
selector += ' ';
}
selector += CSSCompressor.isArray( part ) ? part.join( '' ) : part;
});
// Add selector
css += selector + "{";
// Add rules
branch.rules.forEach(function( rule, i ) {
var value = '';
rule.parts.forEach(function( part, ri ) {
var prev = rule.parts[ ri - 1 ];
if ( value.length && part != '!important' && ! rvalueseparator.exec( part ) && ! rvalueseparator.exec( prev ) ) {
value += ' ';
}
value += part;
});
// Prop:val
css += rule.property + ":" + value;
// Skip last semi-colon
if ( i < branch.rules.length - 1 ) {
css += ';';
}
});
// Closing brace
css += "}";
}
// At rules
else if ( branch.atrule ) {
selector = '';
branch.parts.forEach(function( part, i ) {
var prev = branch.parts[ i - 1 ];
if ( selector.length && part != ',' && prev != ',' ) {
selector += ' ';
}
selector += part;
});
// Nested selectors
if ( branch.branches || branch.rules ) {
// TODO: Handle atrule selector parts
css += selector + "{";
// Add rules
( branch.rules || [] ).forEach(function( rule, i ) {
var value = '';
rule.parts.forEach(function( part, ri ) {
var prev = rule.parts[ ri - 1 ];
if ( value.length && ! rvalueseparator.exec( part ) && ! rvalueseparator.exec( prev ) ) {
value += ' ';
}
value += part;
});
// Prop:val
css += rule.property + ":" + value;
// Skip last semi-colon
if ( i < branch.rules.length - 1 ) {
css += ';';
}
});
// Add nested selectors
if ( branch.branches ) {
css += branch.rules && branch.rules.length ? ';' : '';
css = render( css, branch.branches );
}
// Closing brace
css += "}";
}
// One-liners, @imports
else {
css += selector + ";";
}
}
});
return css;
}
// Format addition
CSSCompressor.format( CSSCompressor.FORMAT_NONE, function( compressor ) {
return render( '', compressor.branches );
});
| mit |
darcamo/python-crash-course | code/dicionarios.py | 187 |
# sample(for)
d = {"pi": 3.141592,
"e": 2.718282,
"número de ouro": 1.6180}
for chave, valor in d.items():
pass # Faça alguma coisa com a chave e o valor
# end-sample
| mit |
hadrianmontes/Plotter2 | ui/preferences_dialog.py | 11270 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'preferences_dialog.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Options(object):
def setupUi(self, Options):
Options.setObjectName(_fromUtf8("Options"))
Options.resize(668, 480)
self.gridLayout = QtGui.QGridLayout(Options)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.widget = QtGui.QWidget(Options)
self.widget.setObjectName(_fromUtf8("widget"))
self.gridLayout_2 = QtGui.QGridLayout(self.widget)
self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
self.widget_2 = QtGui.QWidget(self.widget)
self.widget_2.setObjectName(_fromUtf8("widget_2"))
self.gridLayout_3 = QtGui.QGridLayout(self.widget_2)
self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3"))
self.widget_4 = QtGui.QWidget(self.widget_2)
self.widget_4.setObjectName(_fromUtf8("widget_4"))
self.gridLayout_4 = QtGui.QGridLayout(self.widget_4)
self.gridLayout_4.setObjectName(_fromUtf8("gridLayout_4"))
self.label_4 = QtGui.QLabel(self.widget_4)
self.label_4.setObjectName(_fromUtf8("label_4"))
self.gridLayout_4.addWidget(self.label_4, 1, 2, 1, 1, QtCore.Qt.AlignRight)
self.topcheck = QtGui.QCheckBox(self.widget_4)
self.topcheck.setText(_fromUtf8(""))
self.topcheck.setObjectName(_fromUtf8("topcheck"))
self.gridLayout_4.addWidget(self.topcheck, 1, 3, 1, 1, QtCore.Qt.AlignLeft)
self.label_2 = QtGui.QLabel(self.widget_4)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.gridLayout_4.addWidget(self.label_2, 1, 0, 1, 1, QtCore.Qt.AlignLeft)
self.xtickcombo = QtGui.QComboBox(self.widget_4)
self.xtickcombo.setObjectName(_fromUtf8("xtickcombo"))
self.xtickcombo.addItem(_fromUtf8(""))
self.xtickcombo.addItem(_fromUtf8(""))
self.gridLayout_4.addWidget(self.xtickcombo, 1, 1, 1, 1, QtCore.Qt.AlignLeft)
self.leftcheck = QtGui.QCheckBox(self.widget_4)
self.leftcheck.setText(_fromUtf8(""))
self.leftcheck.setObjectName(_fromUtf8("leftcheck"))
self.gridLayout_4.addWidget(self.leftcheck, 2, 3, 1, 1, QtCore.Qt.AlignLeft)
self.label_3 = QtGui.QLabel(self.widget_4)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.gridLayout_4.addWidget(self.label_3, 2, 0, 1, 1, QtCore.Qt.AlignLeft)
self.ytickcombo = QtGui.QComboBox(self.widget_4)
self.ytickcombo.setObjectName(_fromUtf8("ytickcombo"))
self.ytickcombo.addItem(_fromUtf8(""))
self.ytickcombo.addItem(_fromUtf8(""))
self.gridLayout_4.addWidget(self.ytickcombo, 2, 1, 1, 1, QtCore.Qt.AlignLeft)
self.label_5 = QtGui.QLabel(self.widget_4)
self.label_5.setObjectName(_fromUtf8("label_5"))
self.gridLayout_4.addWidget(self.label_5, 2, 2, 1, 1, QtCore.Qt.AlignRight)
self.gridLayout_3.addWidget(self.widget_4, 3, 0, 1, 3)
self.line = QtGui.QFrame(self.widget_2)
self.line.setFrameShape(QtGui.QFrame.HLine)
self.line.setFrameShadow(QtGui.QFrame.Sunken)
self.line.setObjectName(_fromUtf8("line"))
self.gridLayout_3.addWidget(self.line, 1, 0, 1, 3)
self.label = QtGui.QLabel(self.widget_2)
font = QtGui.QFont()
font.setPointSize(20)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName(_fromUtf8("label"))
self.gridLayout_3.addWidget(self.label, 0, 0, 1, 1)
self.gridLayout_2.addWidget(self.widget_2, 1, 0, 1, 1)
self.buttonBox = QtGui.QDialogButtonBox(self.widget)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
self.gridLayout_2.addWidget(self.buttonBox, 3, 0, 1, 1)
self.widget_3 = QtGui.QWidget(self.widget)
self.widget_3.setObjectName(_fromUtf8("widget_3"))
self.gridLayout_5 = QtGui.QGridLayout(self.widget_3)
self.gridLayout_5.setObjectName(_fromUtf8("gridLayout_5"))
self.label_9 = QtGui.QLabel(self.widget_3)
self.label_9.setObjectName(_fromUtf8("label_9"))
self.gridLayout_5.addWidget(self.label_9, 4, 0, 1, 1)
self.legendsize = QtGui.QComboBox(self.widget_3)
self.legendsize.setObjectName(_fromUtf8("legendsize"))
self.legendsize.addItem(_fromUtf8(""))
self.legendsize.addItem(_fromUtf8(""))
self.legendsize.addItem(_fromUtf8(""))
self.gridLayout_5.addWidget(self.legendsize, 4, 3, 1, 1)
self.label_7 = QtGui.QLabel(self.widget_3)
self.label_7.setObjectName(_fromUtf8("label_7"))
self.gridLayout_5.addWidget(self.label_7, 3, 0, 1, 1)
self.linewidth = QtGui.QDoubleSpinBox(self.widget_3)
self.linewidth.setObjectName(_fromUtf8("linewidth"))
self.gridLayout_5.addWidget(self.linewidth, 3, 1, 1, 1)
self.fontsize = QtGui.QDoubleSpinBox(self.widget_3)
self.fontsize.setObjectName(_fromUtf8("fontsize"))
self.gridLayout_5.addWidget(self.fontsize, 4, 1, 1, 1)
self.label_8 = QtGui.QLabel(self.widget_3)
self.label_8.setObjectName(_fromUtf8("label_8"))
self.gridLayout_5.addWidget(self.label_8, 3, 2, 1, 1)
self.line_2 = QtGui.QFrame(self.widget_3)
self.line_2.setFrameShape(QtGui.QFrame.HLine)
self.line_2.setFrameShadow(QtGui.QFrame.Sunken)
self.line_2.setObjectName(_fromUtf8("line_2"))
self.gridLayout_5.addWidget(self.line_2, 1, 0, 1, 4)
self.label_10 = QtGui.QLabel(self.widget_3)
self.label_10.setObjectName(_fromUtf8("label_10"))
self.gridLayout_5.addWidget(self.label_10, 4, 2, 1, 1)
self.markersize = QtGui.QDoubleSpinBox(self.widget_3)
self.markersize.setObjectName(_fromUtf8("markersize"))
self.gridLayout_5.addWidget(self.markersize, 3, 3, 1, 1)
self.label_6 = QtGui.QLabel(self.widget_3)
font = QtGui.QFont()
font.setPointSize(20)
font.setBold(True)
font.setWeight(75)
self.label_6.setFont(font)
self.label_6.setObjectName(_fromUtf8("label_6"))
self.gridLayout_5.addWidget(self.label_6, 0, 0, 1, 1)
self.widget_6 = QtGui.QWidget(self.widget_3)
self.widget_6.setObjectName(_fromUtf8("widget_6"))
self.gridLayout_7 = QtGui.QGridLayout(self.widget_6)
self.gridLayout_7.setObjectName(_fromUtf8("gridLayout_7"))
self.newlegend = QtGui.QCheckBox(self.widget_6)
self.newlegend.setObjectName(_fromUtf8("newlegend"))
self.gridLayout_7.addWidget(self.newlegend, 0, 1, 1, 1)
self.scaledash = QtGui.QCheckBox(self.widget_6)
self.scaledash.setObjectName(_fromUtf8("scaledash"))
self.gridLayout_7.addWidget(self.scaledash, 0, 0, 1, 1)
self.newcycle = QtGui.QCheckBox(self.widget_6)
self.newcycle.setObjectName(_fromUtf8("newcycle"))
self.gridLayout_7.addWidget(self.newcycle, 0, 2, 1, 1)
self.gridLayout_5.addWidget(self.widget_6, 2, 0, 1, 5)
self.gridLayout_2.addWidget(self.widget_3, 2, 0, 1, 1)
self.widget_5 = QtGui.QWidget(self.widget)
self.widget_5.setObjectName(_fromUtf8("widget_5"))
self.gridLayout_6 = QtGui.QGridLayout(self.widget_5)
self.gridLayout_6.setObjectName(_fromUtf8("gridLayout_6"))
self.label_11 = QtGui.QLabel(self.widget_5)
font = QtGui.QFont()
font.setPointSize(20)
font.setBold(True)
font.setWeight(75)
self.label_11.setFont(font)
self.label_11.setObjectName(_fromUtf8("label_11"))
self.gridLayout_6.addWidget(self.label_11, 0, 0, 1, 1)
self.tickmat2 = QtGui.QRadioButton(self.widget_5)
self.tickmat2.setObjectName(_fromUtf8("tickmat2"))
self.gridLayout_6.addWidget(self.tickmat2, 2, 1, 1, 1)
self.tickmat1 = QtGui.QRadioButton(self.widget_5)
self.tickmat1.setObjectName(_fromUtf8("tickmat1"))
self.gridLayout_6.addWidget(self.tickmat1, 2, 0, 1, 1)
self.tickcust = QtGui.QRadioButton(self.widget_5)
self.tickcust.setObjectName(_fromUtf8("tickcust"))
self.gridLayout_6.addWidget(self.tickcust, 2, 2, 1, 1)
self.line_3 = QtGui.QFrame(self.widget_5)
self.line_3.setFrameShape(QtGui.QFrame.HLine)
self.line_3.setFrameShadow(QtGui.QFrame.Sunken)
self.line_3.setObjectName(_fromUtf8("line_3"))
self.gridLayout_6.addWidget(self.line_3, 1, 0, 1, 3)
self.gridLayout_2.addWidget(self.widget_5, 0, 0, 1, 1)
self.gridLayout.addWidget(self.widget, 0, 0, 1, 1)
self.retranslateUi(Options)
QtCore.QMetaObject.connectSlotsByName(Options)
def retranslateUi(self, Options):
Options.setWindowTitle(_translate("Options", "Preferences", None))
self.label_4.setText(_translate("Options", "Top ticks", None))
self.label_2.setText(_translate("Options", "Xtick Direction", None))
self.xtickcombo.setItemText(0, _translate("Options", "in", None))
self.xtickcombo.setItemText(1, _translate("Options", "out", None))
self.label_3.setText(_translate("Options", "Ytick DIrection", None))
self.ytickcombo.setItemText(0, _translate("Options", "in", None))
self.ytickcombo.setItemText(1, _translate("Options", "out", None))
self.label_5.setText(_translate("Options", "Left ticks", None))
self.label.setText(_translate("Options", "Ticks", None))
self.label_9.setText(_translate("Options", "Font Size", None))
self.legendsize.setItemText(0, _translate("Options", "large", None))
self.legendsize.setItemText(1, _translate("Options", "medium", None))
self.legendsize.setItemText(2, _translate("Options", "small", None))
self.label_7.setText(_translate("Options", "Line Width", None))
self.label_8.setText(_translate("Options", "Marker Size", None))
self.label_10.setText(_translate("Options", "Legend Font Size", None))
self.label_6.setText(_translate("Options", "Plotting Style", None))
self.newlegend.setText(_translate("Options", "New Style Legend", None))
self.scaledash.setText(_translate("Options", "Scale dashes", None))
self.newcycle.setText(_translate("Options", "New Color Cycle", None))
self.label_11.setText(_translate("Options", "General Options", None))
self.tickmat2.setText(_translate("Options", "Matplotlib2", None))
self.tickmat1.setText(_translate("Options", "Matplotlib 1", None))
self.tickcust.setText(_translate("Options", "Custom", None))
| mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_container_service/lib/2019-09-30-preview/generated/azure_mgmt_container_service/models/open_shift_container_service_vmsize.rb | 1674 | # 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::ContainerService::Mgmt::V2019_09_30_preview
module Models
#
# Defines values for OpenShiftContainerServiceVMSize
#
module OpenShiftContainerServiceVMSize
StandardD2sV3 = "Standard_D2s_v3"
StandardD4sV3 = "Standard_D4s_v3"
StandardD8sV3 = "Standard_D8s_v3"
StandardD16sV3 = "Standard_D16s_v3"
StandardD32sV3 = "Standard_D32s_v3"
StandardD64sV3 = "Standard_D64s_v3"
StandardDS4V2 = "Standard_DS4_v2"
StandardDS5V2 = "Standard_DS5_v2"
StandardF8sV2 = "Standard_F8s_v2"
StandardF16sV2 = "Standard_F16s_v2"
StandardF32sV2 = "Standard_F32s_v2"
StandardF64sV2 = "Standard_F64s_v2"
StandardF72sV2 = "Standard_F72s_v2"
StandardF8s = "Standard_F8s"
StandardF16s = "Standard_F16s"
StandardE4sV3 = "Standard_E4s_v3"
StandardE8sV3 = "Standard_E8s_v3"
StandardE16sV3 = "Standard_E16s_v3"
StandardE20sV3 = "Standard_E20s_v3"
StandardE32sV3 = "Standard_E32s_v3"
StandardE64sV3 = "Standard_E64s_v3"
StandardGS2 = "Standard_GS2"
StandardGS3 = "Standard_GS3"
StandardGS4 = "Standard_GS4"
StandardGS5 = "Standard_GS5"
StandardDS12V2 = "Standard_DS12_v2"
StandardDS13V2 = "Standard_DS13_v2"
StandardDS14V2 = "Standard_DS14_v2"
StandardDS15V2 = "Standard_DS15_v2"
StandardL4s = "Standard_L4s"
StandardL8s = "Standard_L8s"
StandardL16s = "Standard_L16s"
StandardL32s = "Standard_L32s"
end
end
end
| mit |
alefteris/timerx3 | Gruntfile.js | 11996 | 'use strict';
var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({port: LIVERELOAD_PORT});
var mountFolder = function (connect, dir) {
return connect.static(require('path').resolve(dir));
};
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// load all grunt tasks
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
// configurable paths
var yeomanConfig = {
app: 'app',
dist: 'dist'
};
grunt.initConfig({
yeoman: yeomanConfig,
watch: {
options: {
nospawn: true
},
coffee: {
files: ['<%= yeoman.app %>/scripts/{,*/}*.coffee'],
tasks: ['coffee:dist']
},
coffeeTest: {
files: ['test/spec/{,*/}*.coffee'],
tasks: ['coffee:test']
},
compass: {
files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
tasks: ['compass:server']
},
livereload: {
options: {
livereload: LIVERELOAD_PORT
},
files: [
'<%= yeoman.app %>/*.html',
'{.tmp,<%= yeoman.app %>}/styles/{,*/}*.css',
'{.tmp,<%= yeoman.app %>}/scripts/{,*/}*.js',
'<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
},
connect: {
options: {
port: 9000,
// change this to '0.0.0.0' to access the server from outside
hostname: '0.0.0.0'
},
livereload: {
options: {
middleware: function (connect) {
return [
lrSnippet,
mountFolder(connect, '.tmp'),
mountFolder(connect, yeomanConfig.app)
];
}
}
},
test: {
options: {
middleware: function (connect) {
return [
mountFolder(connect, '.tmp'),
mountFolder(connect, 'test'),
mountFolder(connect, yeomanConfig.app)
];
}
}
},
dist: {
options: {
middleware: function (connect) {
return [
mountFolder(connect, yeomanConfig.dist)
];
}
}
}
},
open: {
server: {
path: 'http://localhost:<%= connect.options.port %>'
}
},
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/*',
'!<%= yeoman.dist %>/.git*'
]
}]
},
server: '.tmp',
smoosher: {
files: [{
src: [
'<%= yeoman.dist %>/*.tmp.html',
'<%= yeoman.dist %>/styles',
'<%= yeoman.dist %>/scripts'
]
}]
}
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js',
'!<%= yeoman.app %>/scripts/vendor/*',
'test/spec/{,*/}*.js'
]
},
mocha: {
all: {
options: {
run: true,
urls: ['http://localhost:<%= connect.options.port %>/index.html']
}
}
},
coffee: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/scripts',
src: '{,*/}*.coffee',
dest: '.tmp/scripts',
ext: '.js'
}]
},
test: {
files: [{
expand: true,
cwd: 'test/spec',
src: '{,*/}*.coffee',
dest: '.tmp/spec',
ext: '.js'
}]
}
},
compass: {
options: {
sassDir: '<%= yeoman.app %>/styles',
cssDir: '.tmp/styles',
generatedImagesDir: '.tmp/images/generated',
imagesDir: '<%= yeoman.app %>/images',
javascriptsDir: '<%= yeoman.app %>/scripts',
fontsDir: '<%= yeoman.app %>/styles/fonts',
importPath: '<%= yeoman.app %>/bower_components',
httpImagesPath: '/images',
httpGeneratedImagesPath: '/images/generated',
relativeAssets: false
},
dist: {},
server: {
options: {
debugInfo: true
}
}
},
// not used since Uglify task does concat,
// but still available if needed
/*concat: {
dist: {}
},*/
// not enabled since usemin task does concat and uglify
// check index.html to edit your build targets
// enable this task if you prefer defining your build targets here
/*uglify: {
dist: {}
},*/
rev: {
dist: {
files: {
src: [
'<%= yeoman.dist %>/scripts/{,*/}*.js',
'<%= yeoman.dist %>/styles/{,*/}*.css',
'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp}',
'<%= yeoman.dist %>/styles/fonts/*'
]
}
}
},
useminPrepare: {
options: {
dest: '<%= yeoman.dist %>'
},
html: '<%= yeoman.app %>/index.html'
},
usemin: {
options: {
dirs: ['<%= yeoman.dist %>']
},
html: ['<%= yeoman.dist %>/{,*/}*.html'],
css: ['<%= yeoman.dist %>/styles/{,*/}*.css']
},
imagemin: {
dist: {
options: {
optimizationLevel: 2
},
files: [{
expand: true,
cwd: '<%= yeoman.app %>',
src: '{,*/}*.{png,jpg,jpeg}',
dest: '<%= yeoman.dist %>'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/images'
}]
}
},
cssmin: {
dist: {
files: {
'<%= yeoman.dist %>/styles/main.css': [
'.tmp/styles/{,*/}*.css',
'<%= yeoman.app %>/styles/{,*/}*.css'
]
}
}
},
htmlmin: {
dist: {
options: {
/*removeCommentsFromCDATA: true,
// https://github.com/yeoman/grunt-usemin/issues/44
//collapseWhitespace: true,
collapseBooleanAttributes: true,
removeAttributeQuotes: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeOptionalTags: true*/
},
files: [{
expand: true,
cwd: '<%= yeoman.app %>',
src: '*.html',
dest: '<%= yeoman.dist %>'
}]
}
},
// Put files not handled in other tasks here
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,txt}',
'.htaccess',
'images/{,*/}*.{webp,gif}',
'styles/fonts/*',
'.nojekyll',
'*.webapp',
'media/*.ogg',
'google09270ac9ac4a3a5d.html',
'CNAME'
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/images',
src: [
'generated/*'
]
}, {
src: '<%= yeoman.app %>/index.html',
dest: '<%= yeoman.dist %>/index.tmp.html'
}]
}
},
concurrent: {
server: [
'coffee:dist',
'compass:server'
],
test: [
'coffee',
'compass'
],
dist: [
'coffee',
'compass:dist',
'imagemin',
'svgmin'
// 'htmlmin'
]
},
manifest: {
generate: {
options: {
basePath: '<%= yeoman.dist %>',
network: ['http://*', 'https://*'],
verbose: false,
timestamp: true
},
src: [
'index.html',
'scripts/*.js',
'styles/*.css',
'images/*.{png,jpg,jpeg,gif,webp,svg}',
'media/*.ogg'
],
dest: '<%= yeoman.dist %>/manifest.appcache'
}
},
githubPages: {
target: {
options: {
commitMessage: 'New deployment to github pages'
},
src: 'dist'
}
},
smoosher: {
dist: {
files: {
'<%= yeoman.dist %>/index.html': '<%= yeoman.dist %>/index.tmp.html'
}
}
}
});
grunt.registerTask('server', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'open', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'concurrent:server',
'connect:livereload',
'open',
'watch'
]);
});
grunt.registerTask('test', [
'clean:server',
'concurrent:test',
'connect:test',
'mocha'
]);
grunt.registerTask('build', [
'clean:dist',
'useminPrepare',
'concurrent:dist',
'cssmin',
'concat',
'uglify',
'copy',
'rev',
'usemin',
'smoosher',
'clean:smoosher'
]);
grunt.registerTask('deploy', [
'manifest',
'githubPages:target'
]);
grunt.registerTask('default', [
'jshint',
'test',
'build'
]);
};
| mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_network/lib/2018-04-01/generated/azure_mgmt_network/usages.rb | 8950 | # 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::V2018_04_01
#
# Usages
#
class Usages
include MsRestAzure
#
# Creates and initializes a new instance of the Usages class.
# @param client service class for accessing basic functionality.
#
def initialize(client)
@client = client
end
# @return [NetworkManagementClient] reference to the NetworkManagementClient
attr_reader :client
#
# List network usages for a subscription.
#
# @param location [String] The location where resource usage is queried.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<Usage>] operation results.
#
def list(location, custom_headers:nil)
first_page = list_as_lazy(location, custom_headers:custom_headers)
first_page.get_all_items
end
#
# List network usages for a subscription.
#
# @param location [String] The location where resource usage is queried.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_with_http_info(location, custom_headers:nil)
list_async(location, custom_headers:custom_headers).value!
end
#
# List network usages for a subscription.
#
# @param location [String] The location where resource usage is queried.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_async(location, custom_headers:nil)
fail ArgumentError, 'location is nil' if location.nil?
fail ArgumentError, "'location' should satisfy the constraint - 'Pattern': '^[-\w\._]+$'" if !location.nil? && location.match(Regexp.new('^^[-\w\._]+$$')).nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/usages'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'location' => location,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2018_04_01::Models::UsagesListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# List network usages for a subscription.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [UsagesListResult] operation results.
#
def list_next(next_page_link, custom_headers:nil)
response = list_next_async(next_page_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# List network usages for a subscription.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_next_with_http_info(next_page_link, custom_headers:nil)
list_next_async(next_page_link, custom_headers:custom_headers).value!
end
#
# List network usages for a subscription.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_next_async(next_page_link, custom_headers:nil)
fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
skip_encoding_path_params: {'nextLink' => next_page_link},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2018_04_01::Models::UsagesListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# List network usages for a subscription.
#
# @param location [String] The location where resource usage is queried.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [UsagesListResult] which provide lazy access to pages of the
# response.
#
def list_as_lazy(location, custom_headers:nil)
response = list_async(location, custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_page_link|
list_next_async(next_page_link, custom_headers:custom_headers)
end
page
end
end
end
end
| mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_mysql/lib/2017-12-01/generated/azure_mgmt_mysql/my_sqlmanagement_client.rb | 6601 | # 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::Mysql::Mgmt::V2017_12_01
#
# A service client - single point of access to the REST API.
#
class MySQLManagementClient < MsRestAzure::AzureServiceClient
include MsRestAzure
include MsRestAzure::Serialization
# @return [String] the base URI of the service.
attr_accessor :base_url
# @return Credentials needed for the client to connect to Azure.
attr_reader :credentials
# @return [String] The subscription ID that identifies an Azure
# subscription.
attr_accessor :subscription_id
# @return [String] The API version to use for the request.
attr_reader :api_version
# @return [String] The preferred language for the response.
attr_accessor :accept_language
# @return [Integer] The retry timeout in seconds for Long Running
# Operations. Default value is 30.
attr_accessor :long_running_operation_retry_timeout
# @return [Boolean] Whether a unique x-ms-client-request-id should be
# generated. When set to true a unique x-ms-client-request-id value is
# generated and included in each request. Default is true.
attr_accessor :generate_client_request_id
# @return [Servers] servers
attr_reader :servers
# @return [Replicas] replicas
attr_reader :replicas
# @return [FirewallRules] firewall_rules
attr_reader :firewall_rules
# @return [VirtualNetworkRules] virtual_network_rules
attr_reader :virtual_network_rules
# @return [Databases] databases
attr_reader :databases
# @return [Configurations] configurations
attr_reader :configurations
# @return [LogFiles] log_files
attr_reader :log_files
# @return [LocationBasedPerformanceTier] location_based_performance_tier
attr_reader :location_based_performance_tier
# @return [CheckNameAvailability] check_name_availability
attr_reader :check_name_availability
# @return [ServerSecurityAlertPolicies] server_security_alert_policies
attr_reader :server_security_alert_policies
# @return [Operations] operations
attr_reader :operations
#
# Creates initializes a new instance of the MySQLManagementClient class.
# @param credentials [MsRest::ServiceClientCredentials] credentials to authorize HTTP requests made by the service client.
# @param base_url [String] the base URI of the service.
# @param options [Array] filters to be applied to the HTTP requests.
#
def initialize(credentials = nil, base_url = nil, options = nil)
super(credentials, options)
@base_url = base_url || 'https://management.azure.com'
fail ArgumentError, 'invalid type of credentials input parameter' unless credentials.is_a?(MsRest::ServiceClientCredentials) unless credentials.nil?
@credentials = credentials
@servers = Servers.new(self)
@replicas = Replicas.new(self)
@firewall_rules = FirewallRules.new(self)
@virtual_network_rules = VirtualNetworkRules.new(self)
@databases = Databases.new(self)
@configurations = Configurations.new(self)
@log_files = LogFiles.new(self)
@location_based_performance_tier = LocationBasedPerformanceTier.new(self)
@check_name_availability = CheckNameAvailability.new(self)
@server_security_alert_policies = ServerSecurityAlertPolicies.new(self)
@operations = Operations.new(self)
@api_version = '2017-12-01'
@accept_language = 'en-US'
@long_running_operation_retry_timeout = 30
@generate_client_request_id = true
add_telemetry
end
#
# Makes a request and returns the body of the response.
# @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete.
# @param path [String] the path, relative to {base_url}.
# @param options [Hash{String=>String}] specifying any request options like :body.
# @return [Hash{String=>String}] containing the body of the response.
# Example:
#
# request_content = "{'location':'westus','tags':{'tag1':'val1','tag2':'val2'}}"
# path = "/path"
# options = {
# body: request_content,
# query_params: {'api-version' => '2016-02-01'}
# }
# result = @client.make_request(:put, path, options)
#
def make_request(method, path, options = {})
result = make_request_with_http_info(method, path, options)
result.body unless result.nil?
end
#
# Makes a request and returns the operation response.
# @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete.
# @param path [String] the path, relative to {base_url}.
# @param options [Hash{String=>String}] specifying any request options like :body.
# @return [MsRestAzure::AzureOperationResponse] Operation response containing the request, response and status.
#
def make_request_with_http_info(method, path, options = {})
result = make_request_async(method, path, options).value!
result.body = result.response.body.to_s.empty? ? nil : JSON.load(result.response.body)
result
end
#
# Makes a request asynchronously.
# @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete.
# @param path [String] the path, relative to {base_url}.
# @param options [Hash{String=>String}] specifying any request options like :body.
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def make_request_async(method, path, options = {})
fail ArgumentError, 'method is nil' if method.nil?
fail ArgumentError, 'path is nil' if path.nil?
request_url = options[:base_url] || @base_url
if(!options[:headers].nil? && !options[:headers]['Content-Type'].nil?)
@request_headers['Content-Type'] = options[:headers]['Content-Type']
end
request_headers = @request_headers
request_headers.merge!({'accept-language' => @accept_language}) unless @accept_language.nil?
options.merge!({headers: request_headers.merge(options[:headers] || {})})
options.merge!({credentials: @credentials}) unless @credentials.nil?
super(request_url, method, path, options)
end
private
#
# Adds telemetry information.
#
def add_telemetry
sdk_information = 'azure_mgmt_mysql'
sdk_information = "#{sdk_information}/0.17.2"
add_user_agent_information(sdk_information)
end
end
end
| mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_network/lib/2020-05-01/generated/azure_mgmt_network/models/hub_ip_configuration.rb | 4289 | # 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_05_01
module Models
#
# IpConfigurations.
#
class HubIpConfiguration < SubResource
include MsRestAzure
# @return [String] The private IP address of the IP configuration.
attr_accessor :private_ipaddress
# @return [IPAllocationMethod] The private IP address allocation method.
# Possible values include: 'Static', 'Dynamic'
attr_accessor :private_ipallocation_method
# @return [Subnet] The reference to the subnet resource.
attr_accessor :subnet
# @return [PublicIPAddress] The reference to the public IP resource.
attr_accessor :public_ipaddress
# @return [ProvisioningState] The provisioning state of the IP
# configuration resource. Possible values include: 'Succeeded',
# 'Updating', 'Deleting', 'Failed'
attr_accessor :provisioning_state
# @return [String] Name of the Ip Configuration.
attr_accessor :name
# @return [String] A unique read-only string that changes whenever the
# resource is updated.
attr_accessor :etag
# @return [String] Ipconfiguration type.
attr_accessor :type
#
# Mapper for HubIpConfiguration class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'HubIpConfiguration',
type: {
name: 'Composite',
class_name: 'HubIpConfiguration',
model_properties: {
id: {
client_side_validation: true,
required: false,
serialized_name: 'id',
type: {
name: 'String'
}
},
private_ipaddress: {
client_side_validation: true,
required: false,
serialized_name: 'properties.privateIPAddress',
type: {
name: 'String'
}
},
private_ipallocation_method: {
client_side_validation: true,
required: false,
serialized_name: 'properties.privateIPAllocationMethod',
type: {
name: 'String'
}
},
subnet: {
client_side_validation: true,
required: false,
serialized_name: 'properties.subnet',
type: {
name: 'Composite',
class_name: 'Subnet'
}
},
public_ipaddress: {
client_side_validation: true,
required: false,
serialized_name: 'properties.publicIPAddress',
type: {
name: 'Composite',
class_name: 'PublicIPAddress'
}
},
provisioning_state: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.provisioningState',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
serialized_name: 'name',
type: {
name: 'String'
}
},
etag: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'etag',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'type',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| mit |
Aiursoft2018/WebApp | src/OSS/Controllers/ApiController.cs | 16932 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using static System.IO.Directory;
using Microsoft.AspNetCore.Mvc;
using AiursoftBase.Services;
using AiursoftBase.Services.ToAPIServer;
using OSS.Data;
using OSS.Models;
using AiursoftBase.Models;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using AiursoftBase.Exceptions;
using AiursoftBase.Models.OSS.ApiViewModels;
using AiursoftBase.Models.OSS;
using AiursoftBase.Models.API.ApiViewModels;
using AiursoftBase.Attributes;
using AiursoftBase.Models.OSS.ApiAddressModels;
using AiursoftBase;
namespace OSS.Controllers
{
[AiurExceptionHandler]
[ForceValidateModelState]
[AiurRequireHttps]
public class ApiController : AiurController
{
private readonly char _ = Path.DirectorySeparatorChar;
private readonly OSSDbContext _dbContext;
public ApiController(OSSDbContext dbContext)
{
this._dbContext = dbContext;
}
[Route(template: "/{BucketName}/{FileName}.{FileExtension}")]
public async Task<IActionResult> DownloadFile(string BucketName, string FileName, string FileExtension, string sd = "")
{
var targetBucket = await _dbContext.Bucket.SingleOrDefaultAsync(t => t.BucketName == BucketName);
var targetFile = await _dbContext
.OSSFile
.Where(t => t.BucketId == targetBucket.BucketId)
.SingleOrDefaultAsync(t => t.RealFileName == FileName + "." + FileExtension);
if (targetBucket == null || targetFile == null)
return NotFound();
if (targetFile.BucketId != targetBucket.BucketId)
return Unauthorized();
targetFile.DownloadTimes++;
await _dbContext.SaveChangesAsync();
var path = GetCurrentDirectory() + $"{_}Storage{_}{targetBucket.BucketName}{_}{targetFile.FileKey}.dat";
try
{
var file = System.IO.File.ReadAllBytes(path);
HttpContext.Response.Headers.Add("Content-Length", new FileInfo(path).Length.ToString());
HttpContext.Response.Headers.Add("cache-control", "max-age=3600");
if (string.IsNullOrWhiteSpace(sd))
return new FileContentResult(file, MIME.MIMETypesDictionary[FileExtension.ToLower()]);
else
return new FileContentResult(file, "application/octet-stream");
}
catch (Exception e) when (e is DirectoryNotFoundException || e is FileNotFoundException)
{
return NotFound();
}
}
[HttpPost]
public async Task<JsonResult> DeleteApp(DeleteAppAddressModel model)
{
var app = await ApiService.ValidateAccessTokenAsync(model.AccessToken);
if (app.AppId != model.AppId)
{
return Json(new AiurProtocal { code = ErrorType.Unauthorized, message = "The app you try to delete is not the accesstoken you granted!" });
}
var target = await _dbContext.Apps.FindAsync(app.AppId);
if (target != null)
{
_dbContext.OSSFile.RemoveRange(_dbContext.OSSFile.Include(t => t.BelongingBucket).Where(t => t.BelongingBucket.BelongingAppId == target.AppId));
_dbContext.Bucket.Delete(t => t.BelongingAppId == target.AppId);
_dbContext.Apps.Remove(target);
await _dbContext.SaveChangesAsync();
return Json(new AiurProtocal { code = ErrorType.Success, message = "Successfully deleted that app and all files." });
}
return Json(new AiurProtocal { code = ErrorType.HasDoneAlready, message = "That app do not exists in our database." });
}
public async Task<JsonResult> ViewMyBuckets(ViewMyBucketsAddressModel model)
{
var app = await ApiService.ValidateAccessTokenAsync(model.AccessToken);
var appLocal = await _dbContext.Apps.SingleOrDefaultAsync(t => t.AppId == app.AppId);
if (appLocal == null)
{
appLocal = new OSSApp
{
AppId = app.AppId,
MyBuckets = new List<Bucket>()
};
_dbContext.Apps.Add(appLocal);
await _dbContext.SaveChangesAsync();
}
var buckets = await _dbContext
.Bucket
.Include(t => t.Files)
.Where(t => t.BelongingAppId == app.AppId)
.ToListAsync();
buckets.ForEach(t => t.FileCount = t.Files.Count());
var viewModel = new ViewMyBucketsViewModel
{
AppId = appLocal.AppId,
Buckets = buckets,
code = ErrorType.Success,
message = "Successfully get your buckets!"
};
return Json(viewModel);
}
[HttpPost]
public async Task<JsonResult> CreateBucket([FromForm]CreateBucketAddressModel model)
{
//Update app info
var app = await ApiService.ValidateAccessTokenAsync(model.AccessToken);
var appLocal = await _dbContext.Apps.Include(t => t.MyBuckets).SingleOrDefaultAsync(t => t.AppId == app.AppId);
if (appLocal == null)
{
appLocal = new OSSApp
{
AppId = app.AppId,
MyBuckets = new List<Bucket>()
};
_dbContext.Apps.Add(appLocal);
}
//Ensure not exists
var existing = await _dbContext.Bucket.SingleOrDefaultAsync(t => t.BucketName == model.BucketName);
if (existing != null)
{
return Json(new AiurProtocal
{
code = ErrorType.NotEnoughResources,
message = "There is one bucket already called that name!"
});
}
//Create and save to database
var newBucket = new Bucket
{
BucketName = model.BucketName,
Files = new List<OSSFile>(),
OpenToRead = model.OpenToRead,
OpenToUpload = model.OpenToUpload
};
appLocal.MyBuckets.Add(newBucket);
await _dbContext.SaveChangesAsync();
//Create an empty folder
string DirectoryPath = GetCurrentDirectory() + $@"{_}Storage{_}{newBucket.BucketName}{_}";
if (Directory.Exists(DirectoryPath) == false)
{
Directory.CreateDirectory(DirectoryPath);
}
//return model
var viewModel = new CreateBucketViewModel
{
BucketId = newBucket.BucketId,
code = ErrorType.Success,
message = "Successfully created your bucket!"
};
return Json(viewModel);
}
[HttpPost]
public async Task<JsonResult> EditBucket([FromForm]EditBucketAddressModel model)
{
var app = await ApiService.ValidateAccessTokenAsync(model.AccessToken);
var existing = await _dbContext.Bucket.SingleOrDefaultAsync(t => t.BucketName == model.NewBucketName && t.BucketId != model.BucketId);
if (existing != null)
{
return Json(new AiurProtocal
{
code = ErrorType.NotEnoughResources,
message = "There is one bucket already called that name!"
});
}
var target = await _dbContext.Bucket.FindAsync(model.BucketId);
if (target == null)
{
return Json(new AiurProtocal { code = ErrorType.NotFound, message = "Not found bucket!" });
}
else if (target.BelongingAppId != app.AppId)
{
return Json(new AiurProtocal { code = ErrorType.Unauthorized, message = "Not your bucket!" });
}
var oldpath = GetCurrentDirectory() + $@"{_}Storage{_}{target.BucketName}";
var newpath = GetCurrentDirectory() + $@"{_}Storage{_}{model.NewBucketName}";
if (oldpath != newpath)
{
new DirectoryInfo(oldpath).MoveTo(newpath);
}
target.BucketName = model.NewBucketName;
target.OpenToRead = model.OpenToRead;
target.OpenToUpload = model.OpenToUpload;
await _dbContext.SaveChangesAsync();
return Json(new AiurProtocal { code = ErrorType.Success, message = "Successfully edited your bucket!" });
}
public async Task<JsonResult> ViewBucketDetail(ViewBucketDetailAddressModel model)
{
var targetBucket = await _dbContext.Bucket.FindAsync(model.BucketId);
if (targetBucket == null)
{
return Json(new AiurProtocal { code = ErrorType.NotFound, message = "Can not find your bucket!" });
}
var viewModel = new ViewBucketViewModel(targetBucket)
{
code = ErrorType.Success,
message = "Successfully get your bucket info!",
FileCount = await _dbContext.OSSFile.Where(t => t.BucketId == targetBucket.BucketId).CountAsync()
};
return Json(viewModel);
}
[HttpPost]
public async Task<JsonResult> DeleteBucket([FromForm]DeleteBucketAddressModel model)
{
var app = await ApiService.ValidateAccessTokenAsync(model.AccessToken);
var bucket = await _dbContext.Bucket.FindAsync(model.BucketId);
if (bucket.BelongingAppId != app.AppId)
{
return Json(new AiurProtocal { code = ErrorType.Unauthorized, message = "The bucket you try to delete is not your app's bucket!" });
}
_dbContext.Bucket.Remove(bucket);
_dbContext.OSSFile.RemoveRange(_dbContext.OSSFile.Where(t => t.BucketId == bucket.BucketId));
await _dbContext.SaveChangesAsync();
return Json(new AiurProtocal { code = ErrorType.Success, message = "Successfully deleted your bucket!" });
}
public async Task<JsonResult> ViewOneFile(ViewOneFileAddressModel model)
{
var file = await _dbContext
.OSSFile
.Include(t => t.BelongingBucket)
.SingleOrDefaultAsync(t => t.FileKey == model.FileKey);
var path = GetCurrentDirectory() + $@"{_}Storage{_}{file.BelongingBucket.BucketName}{_}{file.FileKey}.dat";
file.JFileSize = new FileInfo(path).Length;
var viewModel = new ViewOneFileViewModel
{
File = file,
code = ErrorType.Success,
message = "Successfully get that file!"
};
return Json(viewModel);
}
[HttpPost]
public async Task<JsonResult> UploadFile(CommonAddressModel model)
{
var app = await ApiService.ValidateAccessTokenAsync(model.AccessToken);
//try find the target bucket
var targetBucket = await _dbContext.Bucket.FindAsync(model.BucketId);
if (targetBucket == null || targetBucket.BelongingAppId != app.AppId)
{
return Json(new AiurProtocal
{
code = ErrorType.Unauthorized,
message = "The bucket you try to upload is not your app's bucket!"
});
}
//try get the file from form
var file = Request.Form.Files.First();
if (file == null)
{
return Json(new AiurProtocal
{
code = ErrorType.InvalidInput,
message = "Please upload your file!"
});
}
//Test the extension
bool validExtension = MIME.MIMETypesDictionary.ContainsKey(Path.GetExtension(file.FileName).Replace(".", "").ToLower());
if (!validExtension)
{
return Json(new AiurProtocal
{
code = ErrorType.InvalidInput,
message = "The extension of your file is not supported!"
});
}
//Save to database
var newFile = new OSSFile
{
RealFileName = Path.GetFileName(file.FileName.Replace(" ", "")),
FileExtension = Path.GetExtension(file.FileName),
BucketId = targetBucket.BucketId,
};
_dbContext.OSSFile.Add(newFile);
await _dbContext.SaveChangesAsync();
//Try saving file.
string DirectoryPath = GetCurrentDirectory() + $"{_}Storage{_}{targetBucket.BucketName}{_}";
if (Exists(DirectoryPath) == false)
{
CreateDirectory(DirectoryPath);
}
var fileStream = new FileStream(DirectoryPath + newFile.FileKey + ".dat", FileMode.Create);
await file.CopyToAsync(fileStream);
fileStream.Close();
//Return json
return Json(new UploadFileViewModel
{
code = ErrorType.Success,
FileKey = newFile.FileKey,
message = "Successfully uploaded your file.",
Path = newFile.GetInternetPath
});
}
public async Task<JsonResult> ViewAllFiles(CommonAddressModel model)
{
//Analyse app
var app = await ApiService.ValidateAccessTokenAsync(model.AccessToken);
var bucket = await _dbContext.Bucket.FindAsync(model.BucketId);
//Security
if (bucket.BelongingAppId != app.AppId)
{
return Json(new AiurProtocal
{
code = ErrorType.Unauthorized,
message = "The bucket you tried to view is not that app's bucket."
});
}
//Get all files.
var allFiles = _dbContext.OSSFile.Include(t => t.BelongingBucket).Where(t => t.BucketId == bucket.BucketId).Take(200);
foreach (var file in allFiles)
{
var path = GetCurrentDirectory() + $@"{_}Storage{_}{file.BelongingBucket.BucketName}{_}{file.FileKey}.dat";
file.JFileSize = new FileInfo(path).Length;
}
var viewModel = new ViewAllFilesViewModel
{
AllFiles = allFiles,
BucketId = bucket.BucketId,
message = "Successfully get all your files of that bucket.",
code = ErrorType.Success
};
return Json(viewModel);
}
[HttpPost]
public async Task<JsonResult> DeleteFile(DeleteFileAddressModel model)
{
//Analyse app
var app = await ApiService.ValidateAccessTokenAsync(model.AccessToken);
var bucket = await _dbContext.Bucket.FindAsync(model.BucketId);
var file = await _dbContext.OSSFile.FindAsync(model.FileKey);
if (bucket == null || file == null)
{
return Json(new AiurProtocal { code = ErrorType.NotFound, message = "We did not find that file in that bucket!" });
}
//Security
if (bucket.BelongingAppId != app.AppId)
{
return Json(new AiurProtocal
{
code = ErrorType.Unauthorized,
message = "The bucket you tried is not that app's bucket."
});
}
if (file.BucketId != bucket.BucketId)
{
return Json(new AiurProtocal
{
code = ErrorType.Unauthorized,
message = "The file and the bucket are both found but it is not in that bucket."
});
}
//Delete file in disk
var path = GetCurrentDirectory() + $@"{_}Storage{_}{bucket.BucketName}{_}{file.FileKey}.dat";
System.IO.File.Delete(path);
//Delete file in database
_dbContext.OSSFile.Remove(file);
await _dbContext.SaveChangesAsync();
return Json(new AiurProtocal
{
code = ErrorType.Success,
message = "Successfully deleted your file!"
});
}
private JsonResult _InvalidInput(string Message)
{
return Json(new AiurProtocal
{
code = ErrorType.InvalidInput,
message = Message
});
}
}
} | mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_api_management/lib/2019-12-01/generated/azure_mgmt_api_management/models/connectivity_status_type.rb | 427 | # 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::ApiManagement::Mgmt::V2019_12_01
module Models
#
# Defines values for ConnectivityStatusType
#
module ConnectivityStatusType
Initializing = "initializing"
Success = "success"
Failure = "failure"
end
end
end
| mit |
beeglebug/symbol | src/Point.js | 1333 | /**
* a 2D Point
* @constructor
* @param {Number} x horizontal position
* @param {Number} y vertical position
* @param {Number} id path id
*/
var Point = function(x, y, id) {
this.x = x;
this.y = y;
this.id = id;
};
/**
* Calculate the distance to another Point
* @param {Point} point another Point
* @return {Number} the euclidean distance between the two points
*/
Point.prototype.distanceTo = function(point) {
var dx = point.x - this.x;
var dy = point.y - this.y;
return Math.sqrt(dx * dx + dy * dy);
};
/**
* Create a copy of this Point
* @returns {Point} a copy of this Point
*/
Point.prototype.clone = function() {
return new Point(this.x, this.y, this.id);
};
/**
* [[Description]]
* @param {Object} point [[Description]]
* @returns {[[Type]]} [[Description]]
*/
Point.prototype.add = function(point) {
this.x += point.x;
this.y += point.y;
return this;
};
/**
* [[Description]]
* @param {Object} point [[Description]]
* @returns {[[Type]]} [[Description]]
*/
Point.prototype.subtract = function(point) {
this.x -= point.x;
this.y -= point.y;
return this;
};
/**
* [[Description]]
* @param {[[Type]]} scalar [[Description]]
* @returns {[[Type]]} [[Description]]
*/
Point.prototype.divide = function(scalar) {
this.x /= scalar;
this.y /= scalar;
return this;
};
| mit |
euskadi31/search-php | src/Search/Test/Unit.php | 604 | <?php
/**
* @package Search
* @author Axel Etcheverry <axel@etcheverry.biz>
* @copyright Copyright (c) 2014 Axel Etcheverry (https://twitter.com/euskadi31)
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* @namespace
*/
namespace Search\Test;
use \mageekguy\atoum;
use \mageekguy\atoum\factory;
abstract class Unit extends atoum\test
{
public function __construct(factory $factory = null)
{
$this->setTestNamespace('Tests\\Units');
parent::__construct($factory);
}
}
| mit |
cdnjs/cdnjs | ajax/libs/highcharts/9.1.0/modules/vector.js | 3134 | /*
Highcharts JS v9.1.0 (2021-05-03)
Vector plot series module
(c) 2010-2021 Torstein Honsi
License: www.highcharts.com/license
*/
(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/vector",["highcharts"],function(d){a(d);a.Highcharts=d;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function d(a,g,d,e){a.hasOwnProperty(g)||(a[g]=e.apply(null,d))}a=a?a._modules:{};d(a,"Series/Vector/VectorSeries.js",[a["Core/Animation/AnimationUtilities.js"],a["Core/Globals.js"],a["Core/Series/SeriesRegistry.js"],
a["Core/Utilities.js"]],function(a,d,h,e){var g=this&&this.__extends||function(){var a=function(c,b){a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,a){b.__proto__=a}||function(b,a){for(var f in a)a.hasOwnProperty(f)&&(b[f]=a[f])};return a(c,b)};return function(c,b){function f(){this.constructor=c}a(c,b);c.prototype=null===b?Object.create(b):(f.prototype=b.prototype,new f)}}(),l=a.animObject,m=h.series,k=h.seriesTypes.scatter,n=e.arrayMax;a=e.extend;var p=e.merge,q=e.pick;e=function(a){function c(){var b=
null!==a&&a.apply(this,arguments)||this;b.data=void 0;b.lengthMax=void 0;b.options=void 0;b.points=void 0;return b}g(c,a);c.prototype.animate=function(b){b?this.markerGroup.attr({opacity:.01}):this.markerGroup.animate({opacity:1},l(this.options.animation))};c.prototype.arrow=function(b){b=b.length/this.lengthMax*this.options.vectorLength/20;var a={start:10*b,center:0,end:-10*b}[this.options.rotationOrigin]||0;return[["M",0,7*b+a],["L",-1.5*b,7*b+a],["L",0,10*b+a],["L",1.5*b,7*b+a],["L",0,7*b+a],["L",
0,-10*b+a]]};c.prototype.drawPoints=function(){var a=this.chart;this.points.forEach(function(b){var c=b.plotX,d=b.plotY;!1===this.options.clip||a.isInsidePlot(c,d,{inverted:a.inverted})?(b.graphic||(b.graphic=this.chart.renderer.path().add(this.markerGroup).addClass("highcharts-point highcharts-color-"+q(b.colorIndex,b.series.colorIndex))),b.graphic.attr({d:this.arrow(b),translateX:c,translateY:d,rotation:b.direction}),this.chart.styledMode||b.graphic.attr(this.pointAttribs(b))):b.graphic&&(b.graphic=
b.graphic.destroy())},this)};c.prototype.pointAttribs=function(b,a){var c=this.options;b=b.color||this.color;var d=this.options.lineWidth;a&&(b=c.states[a].color||b,d=(c.states[a].lineWidth||d)+(c.states[a].lineWidthPlus||0));return{stroke:b,"stroke-width":d}};c.prototype.translate=function(){m.prototype.translate.call(this);this.lengthMax=n(this.lengthData)};c.defaultOptions=p(k.defaultOptions,{lineWidth:2,marker:null,rotationOrigin:"center",states:{hover:{lineWidthPlus:1}},tooltip:{pointFormat:"<b>[{point.x}, {point.y}]</b><br/>Length: <b>{point.length}</b><br/>Direction: <b>{point.direction}\u00b0</b><br/>"},
vectorLength:20});return c}(k);a(e.prototype,{drawGraph:d.noop,getSymbol:d.noop,markerAttribs:d.noop,parallelArrays:["x","y","length","direction"],pointArrayMap:["y","length","direction"]});h.registerSeriesType("vector",e);"";return e});d(a,"masters/modules/vector.src.js",[],function(){})});
//# sourceMappingURL=vector.js.map | mit |
huixt/hxvux | src/plugins/confirm/index.js | 1594 | import ConfirmComponent from '../../components/confirm'
import { mergeOptions } from '../../libs/plugin_helper'
let $vm
const plugin = {
install (vue, options = {}) {
const Confirm = vue.extend(ConfirmComponent)
if (!$vm) {
$vm = new Confirm({
el: document.createElement('div'),
propsData: {
title: ''
}
})
document.body.appendChild($vm.$el)
}
const confirm = {
show (options) {
if (typeof options === 'object') {
mergeOptions($vm, options)
}
if (typeof options === 'object' && (options.onShow || options.onHide)) {
options.onShow && options.onShow()
}
this.$watcher && this.$watcher()
this.$watcher = $vm.$watch('showValue', (val) => {
if (!val && options && options.onHide) {
options.onHide()
}
})
$vm.$off('on-cancel')
$vm.$off('on-confirm')
$vm.$on('on-cancel', () => {
options && options.onCancel && options.onCancel()
})
$vm.$on('on-confirm', () => {
options && options.onConfirm && options.onConfirm()
})
$vm.showValue = true
},
hide () {
$vm.showValue = false
}
}
// all Vux's plugins are included in this.$vux
if (!vue.$vux) {
vue.$vux = {
confirm
}
} else {
vue.$vux.confirm = confirm
}
vue.mixin({
created: function () {
this.$vux = vue.$vux
}
})
}
}
export default plugin
export const install = plugin.install
| mit |
jhullfly/BetterFriendsServer | public/modules/ngCordova/ng-cordova-PATCHED.js | 69446 | /*!
* ngCordova
* Copyright 2014 Drifty Co. http://drifty.com/
* See LICENSE in this repository for license information
*/
(function(){
angular.module('ngCordova', [
'ngCordova.plugins'
]);
// install : cordova plugin add com.google.cordova.admob
// link : https://github.com/floatinghotpot/cordova-admob-pro
angular.module('ngCordova.plugins.adMob', [])
.factory('$cordovaAdMob', [function () {
return {
createBannerView: function (options, success, fail) {
return window.plugins.AdMob.createBannerView(options, success, fail);
},
createInterstitialView: function (options, success, fail) {
return window.plugins.AdMob.createInterstitialView(options, success, fail);
},
requestAd: function (options, success, fail) {
return window.plugins.AdMob.requestAd(options, success, fail);
},
showAd: function (options, success, fail) {
return window.plugins.AdMob.showAd(options, success, fail);
},
requestInterstitialAd: function (options, success, fail) {
return window.plugins.AdMob.requestInterstitialAd(options, success, fail);
}
}
}]);
// install : cordova plugin add https://github.com/ohh2ahh/AppAvailability.git
// link : https://github.com/ohh2ahh/AppAvailability
angular.module('ngCordova.plugins.appAvailability', [])
.factory('$cordovaAppAvailability', ['$q', function ($q) {
return {
check: function(urlScheme) {
var q = $q.defer();
appAvailability.check(urlScheme, function (result) {
q.resolve(result);
}, function (err) {
q.reject(err);
});
return q.promise;
}
}
}]);
// install : cordova plugin add https://github.com/christocracy/cordova-plugin-background-geolocation.git
// link : https://github.com/christocracy/cordova-plugin-background-geolocation
angular.module('ngCordova.plugins.backgroundGeolocation', [])
.factory('$cordovaBackgroundGeolocation', ['$q', function ($q) {
return {
init: function () {
window.navigator.geolocation.getCurrentPosition(function (location) {
return location;
});
},
configure: function (options) {
this.init();
var q = $q.defer();
window.plugins.backgroundGeoLocation.configure(
function (result) {
q.resolve(result);
window.plugins.backgroundGeoLocation.finish();
},
function (err) {
q.reject(err);
}, options);
this.start();
return q.promise;
},
start: function () {
var q = $q.defer();
window.plugins.backgroundGeoLocation.start(
function (result) {
q.resolve(result);
},
function (err) {
q.reject(err);
});
return q.promise;
},
stop: function () {
var q = $q.defer();
window.plugins.backgroundGeoLocation.stop(
function (result) {
q.resolve(result);
},
function (err) {
q.reject(err);
});
return q.promise;
}
};
}
]);
// install : cordova plugin add https://github.com/wildabeast/BarcodeScanner.git
// link : https://github.com/wildabeast/BarcodeScanner/#using-the-plugin
angular.module('ngCordova.plugins.barcodeScanner', [])
.factory('$cordovaBarcodeScanner', ['$q', function ($q) {
return {
scan: function (options) {
var q = $q.defer();
cordova.plugins.barcodeScanner.scan(function (result) {
q.resolve(result);
}, function (err) {
q.reject(err);
});
return q.promise;
},
encode: function (type, data) {
var q = $q.defer();
/* TODO needs work for type:
make the default: BarcodeScanner.Encode.TEXT_TYPE
other options: .EMAIL_TYPE, .PHONE_TYPE, .SMS_TYPE
docs: https://github.com/wildabeast/BarcodeScanner#encoding-a-barcode
*/
cordova.plugins.barcodeScanner.encode(type, data, function (result) {
q.resolve(result);
}, function (err) {
q.reject(err);
});
return q.promise;
}
}
}]);
// install : cordova plugin add org.apache.cordova.battery-status
// link : https://github.com/apache/cordova-plugin-battery-status/blob/master/doc/index.md
angular.module('ngCordova.plugins.battery-status', [])
.factory('$cordovaBatteryStatus', [function () {
return {
onBatteryStatus: function (handler) {
window.addEventListener('batterystatus', handler, false);
},
onBatteryCritical: function (handler) {
window.addEventListener('batterycritical', handler, false);
},
onBatteryLow: function (handler) {
window.addEventListener('batterylow', handler, false);
}
}
}]);
// install :
// link :
angular.module('ngCordova.plugins.bluetoothSerial', [])
.factory('$cordovaBluetoothSerial', ['$q' , function ($q) {
var promise_f = function () {
var q = $q.defer();
// callbacks
var success = function (success) {
q.resolve(success);
};
var failure = function (failure) {
q.reject(failure);
};
// get func and set args
var f_name = arguments[0];
var args = Array.prototype.slice.call(arguments, 1, arguments.length);
args.push(success);
args.push(failure);
window.bluetoothSerial[f_name].apply(this, args);
return q.promise;
};
return {
connect: function (macAddress) {
return promise_f('connect', macAddress);
},
connectInsecure: function (macAddress) {
return promise_f('connectInsecure', macAddress);
},
disconnect: function () {
return promise_f('disconnect');
},
list: function () {
return promise_f('list');
},
isEnabled: function () {
return promise_f('isEnabled');
},
isConnected: function () {
return promise_f('isConnected');
},
available: function () {
return promise_f('available');
},
read: function () {
return promise_f('read');
},
readUntil: function (delimiter) {
return promise_f('readUntil', delimiter);
},
write: function (data) {
return promise_f('write', data);
},
subscribe: function (delimiter) {
return promise_f('subscribe', delimiter);
},
unsubscribe: function () {
return promise_f('unsubscribe');
},
clear: function () {
return promise_f('clear');
},
readRSSI: function () {
return promise_f('readRSSI');
}
};
}]);
// install : cordova plugin add org.apache.cordova.camera
// link : https://github.com/apache/cordova-plugin-camera/blob/master/doc/index.md#orgapachecordovacamera
angular.module('ngCordova.plugins.camera', [])
.factory('$cordovaCamera', ['$q', function ($q) {
return {
getPicture: function (options) {
var q = $q.defer();
if (!navigator.camera) {
q.resolve(null);
return q.promise;
}
navigator.camera.getPicture(function (imageData) {
q.resolve(imageData);
}, function (err) {
q.reject(err);
}, options);
return q.promise;
},
cleanup: function (options) {
var q = $q.defer();
navigator.camera.cleanup(function () {
q.resolve(arguments);
}, function (err) {
q.reject(err);
});
return q.promise;
}
}
}]);
// install : cordova plugin add org.apache.cordova.media-capture
// link : https://github.com/apache/cordova-plugin-media-capture/blob/master/doc/index.md
angular.module('ngCordova.plugins.capture', [])
.factory('$cordovaCapture', ['$q', function ($q) {
return {
captureAudio: function (options) {
var q = $q.defer();
if (!navigator.device.capture) {
q.resolve(null);
return q.promise;
}
navigator.device.capture.captureAudio(function (audioData) {
q.resolve(audioData);
}, function (err) {
q.reject(err);
}, options);
return q.promise;
},
captureImage: function (options) {
var q = $q.defer();
if (!navigator.device.capture) {
q.resolve(null);
return q.promise;
}
navigator.device.capture.captureImage(function (imageData) {
q.resolve(imageData);
}, function (err) {
q.reject(err);
}, options);
return q.promise;
},
captureVideo: function (options) {
var q = $q.defer();
if (!navigator.device.capture) {
q.resolve(null);
return q.promise;
}
navigator.device.capture.captureVideo(function (videoData) {
q.resolve(videoData);
}, function (err) {
q.reject(err);
}, options);
return q.promise;
}
}
}]);
// install : cordova plugin add https://github.com/VersoSolutions/CordovaClipboard
// link : https://github.com/VersoSolutions/CordovaClipboard
angular.module('ngCordova.plugins.clipboard', [])
.factory('$cordovaClipboard', ['$q', function ($q) {
return {
copy: function (text) {
var q = $q.defer();
window.cordova.plugins.clipboard.copy(text,
function () {
q.resolve();
}, function () {
q.reject();
});
return q.promise;
},
paste: function () {
var q = $q.defer();
window.cordova.plugins.clipboard.paste(function (text) {
q.resolve(text);
}, function () {
q.reject();
});
return q.promise;
}
}
}]);
// install : cordova plugin add org.apache.cordova.contacts
// link : https://github.com/apache/cordova-plugin-contacts/blob/master/doc/index.md
angular.module('ngCordova.plugins.contacts', [])
.factory('$cordovaContacts', ['$q', function ($q) {
return {
save: function (contact) {
var q = $q.defer();
var deviceContact = navigator.contacts.create(contact);
deviceContact.save(function (result) {
q.resolve(result);
},
function (err) {
q.reject(err);
});
return q.promise;
},
remove: function (contact) {
var q = $q.defer();
var deviceContact = navigator.contacts.create(contact);
deviceContact.remove(function (result) {
q.resolve(result);
},
function (err) {
q.reject(err);
});
return q.promise;
},
clone: function (contact) {
var deviceContact = navigator.contacts.create(contact);
return deviceContact.clone(contact)
},
find: function (options) {
var q = $q.defer();
var fields = options.fields || ['id', 'displayName'];
delete options.fields;
navigator.contacts.find(fields, function (results) {
q.resolve(results);
},
function (err) {
q.reject(err);
},
options);
return q.promise;
}
/*
getContact: function (contact) {
var q = $q.defer();
navigator.contacts.pickContact(function (contact) {
})
}
*/
// TODO: method to set / get ContactAddress
// TODO: method to set / get ContactError
// TODO: method to set / get ContactField
// TODO: method to set / get ContactName
// TODO: method to set / get ContactOrganization
}
}]);
angular.module('ngCordova.plugins.datePicker', [])
.factory('$cordovaDatePicker', ['$window', function ($window) {
return {
show: function(options, fn) {
return $window.datePicker.show(options, fn);
}
}
}]);
// install : cordova plugin add org.apache.cordova.device
// link : https://github.com/apache/cordova-plugin-device/blob/master/doc/index.md
angular.module('ngCordova.plugins.device', [])
.factory('$cordovaDevice', [function () {
return {
getDevice: function () {
return device;
},
getCordova: function () {
return device.cordova;
},
getModel: function () {
return device.model;
},
// Warning: device.name is deprecated as of version 2.3.0. Use device.model instead.
getName: function () {
return device.name;
},
getPlatform: function () {
return device.platform;
},
getUUID: function () {
return device.uuid;
},
getVersion: function () {
return device.version;
}
}
}]);
// install : cordova plugin add org.apache.cordova.device-motion
// link : https://github.com/apache/cordova-plugin-device-motion/blob/master/doc/index.md
angular.module('ngCordova.plugins.deviceMotion', [])
.factory('$cordovaDeviceMotion', ['$q', function ($q) {
return {
getCurrentAcceleration: function () {
var q = $q.defer();
navigator.accelerometer.getCurrentAcceleration(function (result) {
// Do any magic you need
q.resolve(result);
}, function (err) {
q.reject(err);
});
return q.promise;
},
watchAcceleration: function (options) {
var q = $q.defer();
var watchId = navigator.accelerometer.watchAcceleration(function (result) {
// Do any magic you need
//q.resolve(watchID);
q.notify(result);
}, function (err) {
q.reject(err);
}, options);
return {
watchId: watchId,
promise: q.promise
}
},
clearWatch: function (watchID) {
return navigator.accelerometer.clearWatch(watchID);
}
}
}]);
// install : cordova plugin add org.apache.cordova.device-orientation
// link : https://github.com/apache/cordova-plugin-device-orientation/blob/master/doc/index.md
angular.module('ngCordova.plugins.deviceOrientation', [])
.factory('$cordovaDeviceOrientation', ['$q', function ($q) {
return {
getCurrentHeading: function () {
var q = $q.defer();
navigator.compass.getCurrentHeading(function (heading) {
q.resolve(heading);
}, function (err) {
q.reject(err);
});
return q.promise;
},
watchHeading: function (options) {
var q = $q.defer();
var watchId = navigator.compass.watchHeading(function (result) {
q.notify(result);
}, function (err) {
q.reject(err);
}, options);
return {
watchId: watchId,
promise: q.promise
}
},
clearWatch: function (watchID) {
navigator.compass.clearWatch(watchID);
}
}
}]);
// install : cordova plugin add org.apache.cordova.dialogs
// link : https://github.com/apache/cordova-plugin-dialogs/blob/master/doc/index.md
angular.module('ngCordova.plugins.dialogs', [])
.factory('$cordovaDialogs', ['$q', function ($q) {
return {
alert: function (message, title, buttonName) {
var d = $q.defer();
navigator.notification.alert(message, function () {
d.resolve();
}, title, buttonName);
return d.promise;
},
confirm: function (message, title, buttonLabels) {
var d = $q.defer();
navigator.notification.confirm(message, function () {
d.resolve();
}, title, buttonLabels);
return d.promise;
},
prompt: function (message, title, buttonLabels, defaultText) {
var d = $q.defer();
navigator.notification.confirm(message, function () {
d.resolve();
}, title, buttonLabels, defaultText);
return d.promise;
},
beep: function (times) {
return navigator.notification.beep(times);
}
};
}]);
// install :
// link :
'use strict';
angular.module('ngCordova.plugins.facebookConnect', [])
.provider('$cordova', [
function () {
this.FacebookAppId = undefined;
this.setFacebookAppId = function (id) {
this.FacebookAppId = id;
};
this.$get = [
function () {
var FbAppId = this.FacebookAppId;
return {
getFacebookAppId: function () {
return FbAppId;
}
};
}];
}
])
.factory('$cordovaFacebookConnect', ['$q', '$cordova', function ($q, $cordova) {
return {
init: function (appId) {
if (!window.cordova) {
facebookConnectPlugin.browserInit(appId);
}
},
login: function (o) {
this.init($cordova.getFacebookAppId());
var q = $q.defer();
facebookConnectPlugin.login(o,
function (res) {
q.resolve(res);
}, function (res) {
q.reject(res);
});
return q.promise;
},
showDialog: function (o) {
var q = $q.defer();
facebookConnectPlugin.showDialog(o,
function (res) {
q.resolve(res);
},
function (err) {
q.reject(err);
});
return q.promise;
},
api: function (path, permission) {
var q = $q.defer();
facebookConnectPlugin.api(path, permission,
function (res) {
q.resolve(res);
},
function (err) {
q.reject(err);
});
return q.promise;
},
getAccessToken: function () {
var q = $q.defer();
facebookConnectPlugin.getAccessToken(function (res) {
q.resolve(res);
},
function (err) {
q.reject(err);
});
return q.promise;
},
getLoginStatus: function () {
var q = $q.defer();
facebookConnectPlugin.getLoginStatus(function (res) {
q.resolve(res);
},
function (err) {
q.reject(err);
});
return q.promise;
},
logout: function () {
var q = $q.defer();
facebookConnectPlugin.logout(function (res) {
q.resolve(res);
},
function (err) {
q.reject(err);
});
return q.promise;
}
};
}]);
// install : cordova plugin add org.apache.cordova.file
// link : https://github.com/apache/cordova-plugin-file/blob/master/doc/index.md
// TODO: add functionality to define storage size in the getFilesystem() -> requestFileSystem() method
// TODO: add documentation for FileError types
// TODO: add abort() option to downloadFile and uploadFile methods.
// TODO: add support for downloadFile and uploadFile options. (or detailed documentation) -> for fileKey, fileName, mimeType, headers
// TODO: add support for onprogress property
angular.module('ngCordova.plugins.file', [])
//Filesystem (checkDir, createDir, checkFile, creatFile, removeFile, writeFile, readFile)
.factory('$cordovaFile', ['$q', function ($q) {
return {
checkDir: function (dir) {
var q = $q.defer();
getFilesystem().then(
function (filesystem) {
filesystem.root.getDirectory(dir, {create: false},
//Dir exists
function (entry) {
q.resolve(entry);
},
//Dir doesn't exist
function (error_code) {
q.reject(error_code);
}
);
}
);
return q.promise;
},
createDir: function (dir, replaceBOOL) {
var q = $q.defer();
getFilesystem().then(
function (filesystem) {
filesystem.root.getDirectory(dir, {create: true, exclusive: replaceBOOL},
//Dir exists or is created successfully
function (entry) {
q.resolve(entry);
},
//Dir doesn't exist and is not created
function (error_code) {
q.reject(error_code);
}
);
}
);
return q.promise;
},
listDir: function (filePath) {
var q = $q.defer();
getFilesystem().then(
function (filesystem) {
filesystem.root.getDirectory(filePath, {create: false}, function (parent) {
var reader = parent.createReader();
reader.readEntries(
function (entries) {
q.resolve(entries);
},
function () {
q.reject('DIR_READ_ERROR : ' + filePath);
}
);
}, function () {
q.reject('DIR_NOT_FOUND : ' + filePath);
});
}
);
return q.promise;
},
checkFile: function (filePath) {
var q = $q.defer();
// Backward compatibility for previous function checkFile(dir, file)
if (arguments.length == 2) {
filePath = '/' + filePath + '/' + arguments[1];
}
getFilesystem().then(
function (filesystem) {
filesystem.root.getFile(filePath, {create: false},
// File exists
function (file) {
q.resolve(file);
},
// File doesn't exist
function (error_code) {
q.reject(error_code);
}
);
}
);
return q.promise;
},
createFile: function (filePath, replaceBOOL) {
// Backward compatibility for previous function createFile(filepath replaceBOOL)
var q = $q.defer();
if (arguments.length == 3) {
filePath = '/' + filePath + '/' + arguments[1];
replaceBOOL = arguments[2];
}
getFilesystem().then(
function (filesystem) {
filesystem.root.getFile(filePath, {create: true, exclusive: replaceBOOL},
function (success) {
q.resolve(success);
},
function (err) {
q.reject(err);
});
}
);
return q.promise;
},
removeFile: function (filePath) {
var q = $q.defer();
// Backward compatibility for previous function removeFile(dir, file)
if (arguments.length == 2) {
filePath = '/' + filePath + '/' + arguments[1];
}
getFilesystem().then(
function (filesystem) {
filesystem.root.getFile(filePath, {create: false}, function (fileEntry) {
fileEntry.remove(function () {
q.resolve();
});
});
}
);
return q.promise;
},
writeFile: function (filePath, data) {
var q = $q.defer();
getFilesystem().then(
function (filesystem) {
filesystem.root.getFile(filePath, {create: true},
function (fileEntry) {
fileEntry.createWriter(
function (fileWriter) {
fileWriter.onwriteend = function (evt) {
q.resolve(evt);
};
fileWriter.write(data);
},
function (error) {
q.reject(error);
}
);
},
function (error) {
q.reject(error);
}
);
},
function (error) {
q.reject(error);
}
);
return q.promise;
},
readFile: function (filePath) { /// now deprecated in new ng-cordova version
var q = $q.defer();
console.log('readFile is now deprecated as of v0.1.4-alpha, use readAsText instead');
// Backward compatibility for previous function readFile(dir, file)
if (arguments.length == 2) {
filePath = '/' + filePath + '/' + arguments[1];
}
getFilesystem().then(
function (filesystem) {
filesystem.root.getFile(filePath, {create: false},
// success
function (fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function () {
q.resolve(this.result);
};
reader.readAsText(file);
});
},
// error
function (error) {
q.reject(error);
});
}
);
return q.promise;
},
readAsText: function (filePath) {
var q = $q.defer();
// Backward compatibility for previous function readFile(dir, file)
if (arguments.length == 2) {
filePath = '/' + filePath + '/' + arguments[1];
}
getFilesystem().then(
function (filesystem) {
filesystem.root.getFile(filePath, {create: false},
// success
function (fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function () {
q.resolve(this.result);
};
reader.readAsText(file);
});
},
// error
function (error) {
q.reject(error);
});
}
);
return q.promise;
},
readAsDataURL: function (filePath) {
var q = $q.defer();
// Backward compatibility for previous function readFile(dir, file)
if (arguments.length == 2) {
filePath = '/' + filePath + '/' + arguments[1];
}
getFilesystem().then(
function (filesystem) {
filesystem.root.getFile(filePath, {create: false},
// success
function (fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function () {
q.resolve(this.result);
};
reader.readAsDataURL(file);
});
},
// error
function (error) {
q.reject(error);
});
}
);
return q.promise;
},
readAsBinaryString: function (filePath) {
var q = $q.defer();
// Backward compatibility for previous function readFile(dir, file)
if (arguments.length == 2) {
filePath = '/' + filePath + '/' + arguments[1];
}
getFilesystem().then(
function (filesystem) {
filesystem.root.getFile(filePath, {create: false},
// success
function (fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function () {
q.resolve(this.result);
};
reader.readAsBinaryString(file);
});
},
// error
function (error) {
q.reject(error);
});
}
);
return q.promise;
},
readAsArrayBuffer: function (filePath) {
var q = $q.defer();
// Backward compatibility for previous function readFile(dir, file)
if (arguments.length == 2) {
filePath = '/' + filePath + '/' + arguments[1];
}
getFilesystem().then(
function (filesystem) {
filesystem.root.getFile(filePath, {create: false},
// success
function (fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function () {
q.resolve(this.result);
};
reader.readAsArrayBuffer(file);
});
},
// error
function (error) {
q.reject(error);
});
}
);
return q.promise;
},
readFileMetadata: function (filePath) {
var q = $q.defer();
getFilesystem().then(
function (filesystem) {
filesystem.root.getFile(filePath, {create: false},
// success
function (fileEntry) {
fileEntry.file(function (file) {
q.resolve(file);
});
},
// error
function (error) {
q.reject(error);
});
}
);
return q.promise;
},
readFileAbsolute: function () {
var q = $q.defer();
window.resolveLocalFileSystemURI(filePath,
function (fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function () {
q.resolve(this.result);
};
reader.readAsText(file);
})
},
function (error) {
q.reject(error);
}
);
},
readFileMetadataAbsolute: function (filePath) {
var q = $q.defer();
window.resolveLocalFileSystemURI(filePath,
function (fileEntry) {
fileEntry.file(function (file) {
q.resolve(file);
})
},
function (error) {
q.reject(error);
}
);
return q.promise;
},
downloadFile: function (source, filePath, trustAllHosts, options) {
var q = $q.defer();
var fileTransfer = new FileTransfer();
var uri = encodeURI(source);
fileTransfer.onprogress = function (progressEvent) {
q.notify(progressEvent);
};
fileTransfer.download(
uri,
filePath,
function (entry) {
q.resolve(entry);
},
function (error) {
q.reject(error);
},
trustAllHosts, options);
return q.promise;
},
uploadFile: function (server, filePath, options) {
var q = $q.defer();
var fileTransfer = new FileTransfer();
var uri = encodeURI(server);
fileTransfer.onprogress = function (progressEvent) {
q.notify(progressEvent);
};
fileTransfer.upload(
filePath,
uri,
function (result) {
q.resolve(result);
},
function (error) {
q.reject(error);
},
options);
return q.promise
}
};
function getFilesystem() {
var q = $q.defer();
window.requestFileSystem(LocalFileSystem.PERSISTENT, 1024 * 1024, function (filesystem) {
q.resolve(filesystem);
},
function (err) {
q.reject(err);
});
return q.promise;
}
}]);
// install : cordova plugin add https://github.com/EddyVerbruggen/Flashlight-PhoneGap-Plugin.git
// link : https://github.com/EddyVerbruggen/Flashlight-PhoneGap-Plugin
angular.module('ngCordova.plugins.flashlight', [])
.factory('$cordovaFlashlight', ['$q', function ($q) {
return {
available: function () {
var q = $q.defer();
window.plugins.flashlight.available(function (isAvailable) {
q.resolve(isAvailable);
});
return q.promise;
},
switchOn: function () {
var q = $q.defer();
window.plugins.flashlight.switchOn(function (response) {
q.resolve(response);
}, function (error) {
q.reject(error)
});
return q.promise;
},
switchOff: function () {
var q = $q.defer();
window.plugins.flashlight.switchOff(function (response) {
q.resolve(response);
}, function (error) {
q.reject(error)
});
return q.promise;
}
}
}]);
// install : cordova plugin add https://github.com/phonegap-build/GAPlugin.git
// link : https://github.com/phonegap-build/GAPlugin
angular.module('ngCordova.plugins.ga', [])
.factory('$cordovaGA', ['$q', function ($q) {
return {
init: function (id, mingap) {
var q = $q.defer();
mingap = (mingap >= 0) ? mingap : 10;
window.plugins.gaPlugin.init(function (result) {
q.resolve(result);
},
function (error) {
q.reject(error);
},
id, mingap);
return q.promise;
},
trackEvent: function (success, fail, category, eventAction, eventLabel, eventValue) {
var q = $q.defer();
window.plugins.gaPlugin.trackEvent(function (result) {
q.resolve(result);
},
function (error) {
q.reject(error);
},
category, eventAction, eventLabel, eventValue);
return q.promise;
},
trackPage: function (success, fail, pageURL) {
var q = $q.defer();
window.plugins.gaPlugin.trackPage(function (result) {
q.resolve(result);
},
function (error) {
q.reject(error);
},
pageURL);
return q.promise;
},
setVariable: function (success, fail, index, value) {
var q = $q.defer();
window.plugins.gaPlugin.setVariable(function (result) {
q.resolve(result);
},
function (error) {
q.reject(error);
},
index, value);
return q.promise;
},
exit: function (success, fail) {
var q = $q.defer();
window.plugins.gaPlugin.exit(function (result) {
q.resolve(result);
},
function (error) {
q.reject(error);
});
return q.promise;
}
};
}]);
// install : cordova plugin add org.apache.cordova.geolocation
// link : https://github.com/apache/cordova-plugin-geolocation/blob/master/doc/index.md
angular.module('ngCordova.plugins.geolocation', [])
.factory('$cordovaGeolocation', ['$q', function ($q) {
return {
getCurrentPosition: function (options) {
var q = $q.defer();
navigator.geolocation.getCurrentPosition(function (result) {
// Do any magic you need
q.resolve(result);
}, function (err) {
q.reject(err);
}, options);
return q.promise;
},
watchPosition: function (options) {
var q = $q.defer();
var watchId = navigator.geolocation.watchPosition(function (result) {
// Do any magic you need
q.notify(result);
}, function (err) {
q.reject(err);
}, options);
return {
watchId: watchId,
promise: q.promise
}
},
clearWatch: function (watchID) {
return navigator.geolocation.clearWatch(watchID);
}
}
}]);
// install : cordova plugin add org.apache.cordova.globalization
// link : https://github.com/apache/cordova-plugin-globalization/blob/master/doc/index.md
angular.module('ngCordova.plugins.globalization', [])
.factory('$cordovaGlobalization', ['$q', function ($q) {
return {
getPreferredLanguage: function () {
var q = $q.defer();
navigator.globalization.getPreferredLanguage(function (result) {
q.resolve(result);
},
function (err) {
q.reject(err);
});
return q.promise;
},
getLocaleName: function () {
var q = $q.defer();
navigator.globalization.getLocaleName(function (result) {
q.resolve(result);
},
function (err) {
q.reject(err);
});
return q.promise;
},
getFirstDayOfWeek: function () {
var q = $q.defer();
navigator.globalization.getFirstDayOfWeek(function (result) {
q.resolve(result);
},
function (err) {
q.reject(err);
});
return q.promise;
},
// "date" parameter must be a JavaScript Date Object.
dateToString: function (date, options) {
var q = $q.defer();
navigator.globalization.dateToString(
date,
function (result) {
q.resolve(result);
},
function (err) {
q.reject(err);
},
options);
return q.promise;
},
stringToDate: function (dateString, options) {
var q = $q.defer();
navigator.globalization.stringToDate(
dateString,
function (result) {
q.resolve(result);
},
function (err) {
q.reject(err);
},
options);
return q.promise;
},
getDatePattern: function (options) {
var q = $q.defer();
navigator.globalization.getDatePattern(
function (result) {
q.resolve(result);
},
function (err) {
q.reject(err);
},
options);
return q.promise;
},
getDateNames: function (options) {
var q = $q.defer();
navigator.globalization.getDateNames(
function (result) {
q.resolve(result);
},
function (err) {
q.reject(err);
},
options);
return q.promise;
},
// "date" parameter must be a JavaScript Date Object.
isDayLightSavingsTime: function (date) {
var q = $q.defer();
navigator.globalization.isDayLightSavingsTime(
date,
function (result) {
q.resolve(result);
},
function (err) {
q.reject(err);
});
return q.promise;
},
numberToString: function (number, options) {
var q = $q.defer();
navigator.globalization.numberToString(
number,
function (result) {
q.resolve(result);
},
function (err) {
q.reject(err);
},
options);
return q.promise;
},
stringToNumber: function (numberString, options) {
var q = $q.defer();
navigator.globalization.stringToNumber(
numberString,
function (result) {
q.resolve(result);
},
function (err) {
q.reject(err);
},
options);
return q.promise;
},
getNumberPattern: function (options) {
var q = $q.defer();
navigator.globalization.getNumberPattern(
function (result) {
q.resolve(result);
},
function (err) {
q.reject(err);
},
options);
return q.promise;
},
getCurrencyPattern: function (currencyCode) {
var q = $q.defer();
navigator.globalization.getCurrencyPattern(
currencyCode,
function (result) {
q.resolve(result);
},
function (err) {
q.reject(err);
});
return q.promise;
}
}
}]);
// install :
// link :
// Google Maps needs ALOT of work!
// Not for production use
angular.module('ngCordova.plugins.googleMap', [])
.factory('$cordovaGoogleMap', ['$q', function ($q) {
var map = null;
return {
getMap: function (options) {
var q = $q.defer();
if (!window.plugin.google.maps) {
q.reject(null);
}
else {
var div = document.getElementById("map_canvas");
map = window.plugin.google.maps.Map.getMap(options);
map.setDiv(div);
q.resolve(map);
}
return q.promise;
},
isMapLoaded: function () { // check if an instance of the map exists
return !!map;
},
addMarker: function (markerOptions) { // add a marker to the map with given markerOptions
var q = $q.defer();
map.addMarker(markerOptions, function (marker) {
q.resolve(marker);
});
return q.promise;
},
getMapTypeIds: function () {
return window.plugin.google.maps.mapTypeId;
},
setVisible: function (isVisible) {
var q = $q.defer();
map.setVisible(isVisible);
return q.promise;
},
// I don't know how to deallocate te map and the google map plugin.
cleanup: function () {
map = null;
// delete map;
}
}
}]);
// install : cordova plugin add https://github.com/driftyco/ionic-plugins-keyboard.git
// link : https://github.com/driftyco/ionic-plugins-keyboard
//TODO: add support for native.keyboardshow + native.keyboardhide
angular.module('ngCordova.plugins.keyboard', [])
.factory('$cordovaKeyboard', [function () {
return {
hideAccessoryBar: function (bool) {
return cordova.plugins.Keyboard.hideKeyboardAccessoryBar(bool);
},
close: function () {
return cordova.plugins.Keyboard.close();
},
disableScroll: function (bool) {
return cordova.plugins.Keyboard.disableScroll(bool);
},
isVisible: function () {
return cordova.plugins.Keyboard.isVisible
}
}
}]);
// install : cordova plugin add https://github.com/shazron/KeychainPlugin.git
// link : https://github.com/shazron/KeychainPlugin
angular.module('ngCordova.plugins.keychain', [])
.factory('$cordovaKeychain', ['$q', function ($q) {
var kc = new Keychain();
return {
getForKey: function (key, serviceName) {
var defer = $q.defer();
kc.getForKey(function (value) {
defer.resolve(value);
}, function (error) {
defer.reject(error);
}, key, serviceName);
return defer.promise;
},
setForKey: function (key, serviceName, value) {
var defer = $q.defer();
kc.setForKey(function () {
defer.resolve();
}, function (error) {
defer.reject(error);
}, key, serviceName, value);
return defer.promise;
},
removeForKey: function (ey, serviceName) {
var defer = $q.defer();
kc.removeForKey(function () {
defer.resolve();
}, function (error) {
defer.reject(error);
}, key, serviceName);
return defer.promise;
}
}
}]);
// install :
// link :
angular.module('ngCordova.plugins.localNotification', [])
.factory('$cordovaLocalNotification', ['$q',
function ($q) {
return {
add: function (options, scope) {
var q = $q.defer();
window.plugin.notification.local.add(
options,
function (result) {
q.resolve(result);
},
scope);
return q.promise;
},
cancel: function (id, scope) {
var q = $q.defer();
window.plugin.notification.local.cancel(
id, function (result) {
q.resolve(result);
}, scope);
return q.promise;
},
cancelAll: function (scope) {
var q = $q.defer();
window.plugin.notification.local.cancelAll(
function (result) {
q.resolve(result);
}, scope);
return q.promise;
},
isScheduled: function (id, scope) {
var q = $q.defer();
window.plugin.notification.local.isScheduled(
id,
function (result) {
q.resolve(result);
}, scope);
return q.promise;
},
getScheduledIds: function (scope) {
var q = $q.defer();
window.plugin.notification.local.getScheduledIds(
function (result) {
q.resolve(result);
}, scope);
return q.promise;
},
isTriggered: function (id, scope) {
var q = $q.defer();
window.plugin.notification.local.isTriggered(
id, function (result) {
q.resolve(result);
}, scope);
return q.promise;
},
getTriggeredIds: function (scope) {
var q = $q.defer();
window.plugin.notification.local.getTriggeredIds(
function (result) {
q.resolve(result);
}, scope);
return q.promise;
},
getDefaults: function () {
return window.plugin.notification.local.getDefaults();
},
setDefaults: function (Object) {
window.plugin.notification.local.setDefaults(Object);
},
onadd: function () {
return window.plugin.notification.local.onadd;
},
ontrigger: function () {
return window.plugin.notification.local.ontrigger;
},
onclick: function () {
return window.plugin.notification.local.onclick;
},
oncancel: function () {
return window.plugin.notification.local.oncancel;
}
}
}
]);
// install :
// link :
angular.module('ngCordova.plugins.media', [])
.factory('$cordovaMedia', ['$q', function ($q) {
return {
newMedia: function (src) {
var q = $q.defer();
var mediaStatus = null;
var media = new Media(src,
function (success) {
q.resolve(success);
}, function (error) {
q.reject(error);
}, function (status) {
mediaStatus = status;
});
return {
media: media,
mediaStatus: mediaStatus,
promise: q.promise
}
},
getCurrentPosition: function (source) {
var q = $q.defer();
source.getCurrentPosition(function (success) {
q.resolve(success);
}, function (error) {
q.reject(error);
});
return q.promise;
},
getDuration: function (source) {
return source.getDuration();
},
play: function (source) {
return source.play();
// iOS quirks :
// - myMedia.play({ numberOfLoops: 2 }) -> looping
// - myMedia.play({ playAudioWhenScreenIsLocked : false })
},
pause: function (source) {
return source.pause();
},
release: function (source) {
return source.release();
},
seekTo: function (source, milliseconds) {
return source.seekTo(milliseconds);
},
setVolume: function (source, volume) {
return source.setVolume(volume);
},
startRecord: function (source) {
return source.startRecord();
},
stopRecord: function (source) {
return source.stopRecord();
},
stop: function (source) {
return source.stop();
}
}
}]);
angular.module('ngCordova.plugins', [
'ngCordova.plugins.deviceMotion',
'ngCordova.plugins.camera',
'ngCordova.plugins.geolocation',
'ngCordova.plugins.deviceOrientation',
'ngCordova.plugins.dialogs',
'ngCordova.plugins.vibration',
'ngCordova.plugins.network',
'ngCordova.plugins.device',
'ngCordova.plugins.barcodeScanner',
'ngCordova.plugins.splashscreen',
'ngCordova.plugins.keyboard',
'ngCordova.plugins.contacts',
'ngCordova.plugins.statusbar',
'ngCordova.plugins.file',
'ngCordova.plugins.socialSharing',
'ngCordova.plugins.globalization',
'ngCordova.plugins.sqlite',
'ngCordova.plugins.ga',
'ngCordova.plugins.push',
'ngCordova.plugins.spinnerDialog',
'ngCordova.plugins.sms',
'ngCordova.plugins.pinDialog',
'ngCordova.plugins.localNotification',
'ngCordova.plugins.toast',
'ngCordova.plugins.flashlight',
'ngCordova.plugins.capture',
'ngCordova.plugins.appAvailability',
'ngCordova.plugins.prefs',
'ngCordova.plugins.printer',
'ngCordova.plugins.bluetoothSerial',
'ngCordova.plugins.backgroundGeolocation',
'ngCordova.plugins.facebookConnect',
'ngCordova.plugins.adMob',
'ngCordova.plugins.googleMap',
'ngCordova.plugins.clipboard',
'ngCordova.plugins.nativeAudio',
'ngCordova.plugins.media',
'ngCordova.plugins.battery-status',
'ngCordova.plugins.keychain',
'ngCordova.plugins.progressIndicator',
'ngCordova.plugins.datePicker'
]);
// install : cordova plugin add https://github.com/sidneys/cordova-plugin-nativeaudio.git
// link : https://github.com/sidneys/cordova-plugin-nativeaudio
angular.module('ngCordova.plugins.nativeAudio', [])
.factory('$cordovaNativeAudio', ['$q', function ($q) {
return {
preloadSimple: function (id, assetPath) {
var q = $q.defer();
window.plugins.NativeAudio.preloadSimple(id, assetPath,
function (result) {
q.resolve(result)
},
function (err) {
q.reject(err);
}
);
return q.promise;
},
preloadComplex: function (id, assetPath, volume, voices) {
var q = $q.defer();
window.plugins.NativeAudio.preloadComplex(id, assetPath, volume, voices,
function (result) {
q.resolve(result)
},
function (err) {
q.reject(err);
}
);
return q.promise;
},
play: function (id, completeCallback) {
var q = $q.defer();
window.plugins.NativeAudio.play(id, completeCallback,
function (result) {
q.resolve(result)
},
function (err) {
q.reject(err);
}
);
return q.promise;
},
stop: function (id) {
var q = $q.defer();
window.plugins.NativeAudio.stop(id,
function (result) {
q.resolve(result)
},
function (err) {
q.reject(err);
}
);
return q.promise;
},
loop: function (id) {
var q = $q.defer();
window.plugins.NativeAudio.loop(id,
function (result) {
q.resolve(result)
},
function (err) {
q.reject(err);
}
);
return q.promise;
},
unload: function (id) {
var q = $q.defer();
window.plugins.NativeAudio.unload(id,
function (result) {
q.resolve(result)
},
function (err) {
q.reject(err);
}
);
return q.promise;
},
setVolumeForComplexAsset: function (id, volume) {
var q = $q.defer();
window.plugins.NativeAudio.setVolumeForComplexAsset(id, volume,
function (result) {
q.resolve(result)
},
function (err) {
q.reject(err);
}
);
return q.promise;
}
}
}]);
// install : cordova plugin add org.apache.cordova.network-information
// link : https://github.com/apache/cordova-plugin-network-information/blob/master/doc/index.md
angular.module('ngCordova.plugins.network', [])
.factory('$cordovaNetwork', [function () {
return {
getNetwork: function () {
return navigator.connection.type;
},
isOnline: function () {
var networkState = navigator.connection.type;
return networkState !== Connection.UNKNOWN && networkState !== Connection.NONE;
},
isOffline: function () {
var networkState = navigator.connection.type;
return networkState === Connection.UNKNOWN || networkState === Connection.NONE;
}
}
}]);
// install : cordova plugin add https://github.com/Paldom/PinDialog.git
// link : https://github.com/Paldom/PinDialog
angular.module('ngCordova.plugins.pinDialog', [])
.factory('$cordovaPinDialog', [function () {
return {
prompt: function (message, promptCallback, title, buttonLabels, defaultText) {
return window.plugins.pinDialog.prompt.apply(navigator.notification, arguments);
}
}
}]);
// install :
// link :
angular.module('ngCordova.plugins.prefs', [])
.factory('$cordovaPreferences', ['$window', '$q', function ($window, $q) {
return {
set: function (key, value) {
var q = $q.defer();
$window.applicationPreferences.set(key, value, function (result) {
q.resolve(result);
}, function (err) {
q.reject(err);
});
return q.promise;
},
get: function (key) {
var q = $q.defer();
$window.applicationPreferences.get(key, function (value) {
q.resolve(value);
}, function (err) {
q.reject(err);
});
return q.promise;
}
}
}]);
// install : cordova plugin add de.appplant.cordova.plugin.printer
// link : https://github.com/katzer/cordova-plugin-printer
angular.module('ngCordova.plugins.printer', [])
.factory('$cordovaPrinter', ['$q', function ($q) {
return {
isAvailable: function () {
var d = $q.defer();
window.plugin.printer.isServiceAvailable(function (isAvailable) {
d.resolve(isAvailable);
});
return d.promise;
},
print: function (doc) {
window.plugin.printer.print(doc);
}
}
}
]);
// install : cordova plugin add org.pbernasconi.progressindicator
// link : http://pbernasconi.github.io/cordova-progressIndicator/
angular.module('ngCordova.plugins.progressIndicator', [])
.factory('$cordovaProgressIndicator', ['$q', function ($q) {
return {
showSimple: function (_dim) {
var dim = _dim || false;
return ProgressIndicator.showSimple(dim)
},
showSimpleWithLabel: function (_dim, _label) {
var dim = _dim || false;
var label = _label || "Loading...";
return ProgressIndicator.showSimpleWithLabel(dim, label);
},
showSimpleWithLabelDetail: function (_dim, _label, _detail) {
var dim = _dim || false;
var label = _label || "Loading...";
var detail = _detail || "Please wait";
return ProgressIndicator.showSimpleWithLabelDetail(dim, label, detail);
},
showDeterminate: function (_dim, _timeout) {
var dim = _dim || false;
var timeout = _timeout || 50000;
return ProgressIndicator.showDeterminate(dim, timeout)
},
showDeterminateWithLabel: function (_dim, _timeout, _label) {
var dim = _dim || false;
var timeout = _timeout || 50000;
var label = _label || "Loading...";
return ProgressIndicator.showDeterminateWithLabel(dim, timeout, label)
},
showAnnular: function (_dim, _timeout) {
var dim = _dim || false;
var timeout = _timeout || 50000;
return ProgressIndicator.showAnnular(dim, timeout)
},
showAnnularWithLabel: function (_dim, _timeout, _label) {
var dim = _dim || false;
var timeout = _timeout || 50000;
var label = _label || "Loading...";
return ProgressIndicator.showAnnularWithLabel(dim, timeout, label)
},
showBar: function (_dim, _timeout) {
var dim = _dim || false;
var timeout = _timeout || 50000;
return ProgressIndicator.showBar(dim, timeout)
},
showBarWithLabel: function (_dim, _timeout, _label) {
var dim = _dim || false;
var timeout = _timeout || 50000;
var label = _label || "Loading...";
return ProgressIndicator.showBarWithLabel(dim, timeout, label)
},
showSuccess: function (_dim) {
var dim = _dim || false;
return ProgressIndicator.showSuccess(dim)
},
showText: function (_dim, _text, _position) {
var dim = _dim || false;
var text = _text || "Warning";
var position = _position || "center";
return ProgressIndicator.showText(dim, text, position);
},
hide: function () {
return ProgressIndicator.hide();
}
}
}]);
// install : cordova plugin add https://github.com/phonegap-build/PushPlugin.git
// link : https://github.com/phonegap-build/PushPlugin
angular.module('ngCordova.plugins.push', [])
.factory('$cordovaPush', ['$q', function ($q) {
return {
register: function (config) {
var q = $q.defer();
window.plugins.pushNotification.register(
function (result) {
q.resolve(result);
},
function (error) {
q.reject(error);
},
config);
return q.promise;
},
unregister: function (options) {
var q = $q.defer();
window.plugins.pushNotification.unregister(
function (result) {
q.resolve(result);
},
function (error) {
q.reject(error);
},
options);
return q.promise;
},
// iOS only
setBadgeNumber: function (number) {
var q = $q.defer();
window.plugins.pushNotification.setApplicationIconBadgeNumber(
function (result) {
q.resolve(result);
},
function (error) {
q.reject(error);
},
number);
return q.promise;
}
};
}]);
// install : cordova plugin add com.jsmobile.plugins.sms
// link : https://github.com/hazems/cordova-sms-plugin.git
angular.module('ngCordova.plugins.sms', [])
.factory('$cordovaSms', ['$q', function ($q) {
return {
send: function (messageInfo) {
var q = $q.defer();
sms.sendMessage(messageInfo, function (res) {
q.resolve(res);
}, function (err) {
q.reject(err)
});
return q.promise;
}
}
}]);
// install : cordova plugin add https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin.git
// link : https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin
// NOTE: shareViaEmail -> if user cancels sharing email, success is still called
// NOTE: shareViaEmail -> TO, CC, BCC must be an array, Files can be either null, string or array
// TODO: add support for iPad
// TODO: detailed docs for each social sharing types (each social platform has different requirements)
angular.module('ngCordova.plugins.socialSharing', [])
.factory('$cordovaSocialSharing', ['$q', function ($q) {
return {
share: function (message, subject, file, link) {
var q = $q.defer();
window.plugins.socialsharing.share(message, subject, file, link,
function () {
q.resolve(true); // success
},
function () {
q.reject(false); // error
});
return q.promise;
},
shareViaTwitter: function (message, file, link) {
var q = $q.defer();
window.plugins.socialsharing.shareViaTwitter(message, file, link,
function () {
q.resolve(true); // success
},
function () {
q.reject(false); // error
});
return q.promise;
},
shareViaWhatsApp: function (message, file, link) {
var q = $q.defer();
window.plugins.socialsharing.shareViaWhatsApp(message, file, link,
function () {
q.resolve(true); // success
},
function () {
q.reject(false); // error
});
return q.promise;
},
shareViaFacebook: function (message, file, link) {
var q = $q.defer();
window.plugins.socialsharing.shareViaFacebook(message, file, link,
function () {
q.resolve(true); // success
},
function () {
q.reject(false); // error
});
return q.promise;
},
shareViaSMS: function (message, commaSeparatedPhoneNumbers) {
var q = $q.defer();
window.plugins.socialsharing.shareViaSMS(message, commaSeparatedPhoneNumbers,
function () {
q.resolve(true); // success
},
function () {
q.reject(false); // error
});
return q.promise;
},
shareViaEmail: function (message, subject, toArr, ccArr, bccArr, fileArr) {
var q = $q.defer();
window.plugins.socialsharing.shareViaEmail(message, subject, toArr, ccArr, bccArr, fileArr,
function () {
q.resolve(true); // success
},
function () {
q.reject(false); // error
});
return q.promise;
},
canShareViaEmail: function () {
var q = $q.defer();
window.plugins.socialsharing.canShareViaEmail(
function () {
q.resolve(true); // success
},
function () {
q.reject(false); // error
});
return q.promise;
},
canShareVia: function (via, message, subject, file, link) {
var q = $q.defer();
window.plugins.socialsharing.canShareVia(via, message, subject, file, link,
function (success) {
q.resolve(success); // success
},
function (error) {
q.reject(error); // error
});
return q.promise;
},
shareVia: function (via, message, subject, file, link) {
var q = $q.defer();
window.plugins.socialsharing.shareVia(via, message, subject, file, link,
function () {
q.resolve(true); // success
},
function () {
q.reject(false); // error
});
return q.promise;
}
}
}]);
// install : cordova plugin add https://github.com/Paldom/SpinnerDialog.git
// link : https://github.com/Paldom/SpinnerDialog
angular.module('ngCordova.plugins.spinnerDialog', [])
.factory('$cordovaSpinnerDialog', [function () {
return {
show: function (title, message) {
return window.plugins.spinnerDialog.show(title, message);
},
hide: function () {
return window.plugins.spinnerDialog.hide();
}
}
}]);
// install : cordova plugin add org.apache.cordova.splashscreen
// link : https://github.com/apache/cordova-plugin-splashscreen/blob/master/doc/index.md
angular.module('ngCordova.plugins.splashscreen', [])
.factory('$cordovaSplashscreen', [ function () {
return {
hide: function () {
return navigator.splashscreen.hide();
},
show: function () {
return navigator.splashscreen.show();
}
};
}]);
// install : cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin.git
// link : https://github.com/brodysoft/Cordova-SQLitePlugin/blob/master/README.md
angular.module('ngCordova.plugins.sqlite', [])
.factory('$cordovaSQLite', ['$q', function ($q) {
return {
openDB: function (dbName) {
return window.sqlitePlugin.openDatabase({name: dbName});
},
openDBBackground: function (dbName) {
return window.sqlitePlugin.openDatabase({name: dbName, bgType: 1});
},
execute: function (db, query, binding) {
var q = $q.defer();
db.transaction(function (tx) {
tx.executeSql(query, binding, function (tx, result) {
q.resolve(result);
},
function (transaction, error) {
q.reject(error);
});
});
return q.promise;
},
nestedExecute: function (db, query1, query2, binding1, binding2) {
var q = $q.defer();
db.transaction(function (tx) {
tx.executeSql(query1, binding1, function (tx, result) {
q.resolve(result);
tx.executeSql(query2, binding2, function (tx, res) {
q.resolve(res);
})
})
},
function (transaction, error) {
q.reject(error);
});
return q.promise;
}
// more methods here
}
}]);
// install : cordova plugin add org.apache.cordova.statusbar
// link : https://github.com/apache/cordova-plugin-statusbar/blob/master/doc/index.md
angular.module('ngCordova.plugins.statusbar', [])
.factory('$cordovaStatusbar', [function () {
return {
overlaysWebView: function (bool) {
return StatusBar.overlaysWebView(true);
},
// styles: Default, LightContent, BlackTranslucent, BlackOpaque
style: function (style) {
switch (style) {
case 0: // Default
return StatusBar.styleDefault();
break;
case 1: // LightContent
return StatusBar.styleLightContent();
break;
case 2: // BlackTranslucent
return StatusBar.styleBlackTranslucent();
break;
case 3: // BlackOpaque
return StatusBar.styleBlackOpaque();
break;
default: // Default
return StatusBar.styleDefault();
}
},
// supported names: black, darkGray, lightGray, white, gray, red, green, blue, cyan, yellow, magenta, orange, purple, brown
styleColor: function (color) {
return StatusBar.backgroundColorByName(color);
},
styleHex: function (colorHex) {
return StatusBar.backgroundColorByHexString(colorHex);
},
hide: function () {
return StatusBar.hide();
},
show: function () {
return StatusBar.show()
},
isVisible: function () {
return StatusBar.isVisible();
}
}
}]);
// install : cordova plugin add https://github.com/EddyVerbruggen/Toast-PhoneGap-Plugin.git
// link : https://github.com/EddyVerbruggen/Toast-PhoneGap-Plugin
angular.module('ngCordova.plugins.toast', [])
.factory('$cordovaToast', ['$q', function ($q) {
return {
showShortTop: function (message) {
var q = $q.defer();
window.plugins.toast.showShortTop(message, function (response) {
q.resolve(response);
}, function (error) {
q.reject(error)
});
return q.promise;
},
showShortCenter: function (message) {
var q = $q.defer();
window.plugins.toast.showShortCenter(message, function (response) {
q.resolve(response);
}, function (error) {
q.reject(error)
});
return q.promise;
},
showShortBottom: function (message) {
var q = $q.defer();
window.plugins.toast.showShortBottom(message, function (response) {
q.resolve(response);
}, function (error) {
q.reject(error)
});
return q.promise;
},
showLongTop: function (message) {
var q = $q.defer();
window.plugins.toast.showLongTop(message, function (response) {
q.resolve(response);
}, function (error) {
q.reject(error)
});
return q.promise;
},
showLongCenter: function (message) {
var q = $q.defer();
window.plugins.toast.showLongCenter(message, function (response) {
q.resolve(response);
}, function (error) {
q.reject(error)
});
return q.promise;
},
showLongBottom: function (message) {
var q = $q.defer();
window.plugins.toast.showLongBottom(message, function (response) {
q.resolve(response);
}, function (error) {
q.reject(error)
});
return q.promise;
},
show: function (message, duration, position) {
var q = $q.defer();
window.plugins.toast.show(message, duration, position, function (response) {
q.resolve(response);
}, function (error) {
q.reject(error)
});
return q.promise;
}
}
}]);
// install : cordova plugin add org.apache.cordova.vibration
// link : https://github.com/apache/cordova-plugin-vibration/blob/master/doc/index.md
angular.module('ngCordova.plugins.vibration', [])
.factory('$cordovaVibration', [function () {
return {
vibrate: function (times) {
return navigator.notification.vibrate(times);
},
vibrateWithPattern: function (pattern, repeat) {
return navigator.notification.vibrateWithPattern(pattern, repeat);
},
cancelVibration: function () {
return navigator.notification.cancelVibration();
}
}
}]);
})(); | mit |
drumanagh/sufficiently-cleaned | sufficiently-cleaned.user.js | 3866 | // ==UserScript==
// @name Sufficiently Cleaned
// @description Removes layout annoyances from Sufficient Velocity
// @author Drumanagh Wilpole
// @namespace https://github.com/drumanagh/sufficiently-cleaned/
// @downloadURL https://github.com/drumanagh/sufficiently-cleaned/raw/master/sufficiently-cleaned.user.js
// @version 1.2.0
// @license https://github.com/drumanagh/sufficiently-cleaned/blob/master/LICENSE
// @include https://forums.sufficientvelocity.com
// @include https://forums.sufficientvelocity.com/*
// @require https://code.jquery.com/jquery-1.12.4.min.js
// @grant GM_addStyle
// @grant GM_getResourceText
// ==/UserScript==
this.$ = this.jQuery = jQuery.noConflict(true);
(function ($) {
/**
* The possible themes for the site
* @readonly
* @enum {String}
*/
var THEMES = {
GLOBAL: 'Global',
FLEX_DARK: 'FlexDark',
FLEX_GOLD: 'FlexGold',
FLEX_GRAY: 'FlexGray',
FLEX_PINK: 'FlexPink',
FLEX_SPACE: 'FlexSpace',
FLEX_STARS: 'FlexStars',
FLEX_WHITE: 'FlexWhite',
FLEX_DARK_OLD: 'Flexile Dark - old',
FLEX_GOLD_OLD: 'Flexile Gold - old',
FLEX_STARS_OLD: 'Flexile Stars - old',
SPACE_OLD: 'Space - old',
WHITE_OLD: 'White - old',
UNKNOWN: 'Unknown'
};
/**
* The jQuery criteria to determine each particular theme
* @readonly
* @enum {String}
*/
var CRITERIA = {};
CRITERIA[THEMES.FLEX_DARK] = 'link[href^="css.php?css=flexile,\\&style=14"]';
CRITERIA[THEMES.FLEX_GOLD] = 'link[href^="css.php?css=flexile,\\&style=15"]';
CRITERIA[THEMES.FLEX_GRAY] = 'link[href^="css.php?css=flexile,\\&style=20"]';
CRITERIA[THEMES.FLEX_PINK] = 'link[href^="css.php?css=flexile,\\&style=16"]';
CRITERIA[THEMES.FLEX_SPACE] = 'link[href^="css.php?css=flexile,\\&style=17"]';
CRITERIA[THEMES.FLEX_STARS] = 'link[href^="css.php?css=flexile,\\&style=18"]';
CRITERIA[THEMES.FLEX_WHITE] = 'link[href^="css.php?css=flexile,\\&style=19"]';
CRITERIA[THEMES.FLEX_DARK_OLD] = 'link[href^="css.php?css=flexile,flexile_dark\\&style=2"]';
CRITERIA[THEMES.FLEX_GOLD_OLD] = 'link[href^="css.php?css=flexile,flexile_dark\\&style=3"]';
CRITERIA[THEMES.FLEX_STARS_OLD] = 'link[href^="css.php?css=flexile,flexile_dark\\&style=11"]';
CRITERIA[THEMES.SPACE_OLD] = 'link[href^="css.php?css=xenforo,form,public\\&style=7"]';
CRITERIA[THEMES.WHITE_OLD] = 'link[href^="css.php?css=xenforo,form,public\\&style=1"]';
CRITERIA[THEMES.UNKNOWN] = 'body';
/**
* The possible user styles for the site by theme
* @readonly
* @enum {String}
*/
var STYLES = {};
STYLES[THEMES.GLOBAL] = 'https://github.com/drumanagh/sufficiently-cleaned/raw/master/sufficiently-cleaned.global.css';
STYLES[THEMES.FLEX_WHITE] = 'https://github.com/drumanagh/sufficiently-cleaned/raw/master/sufficiently-cleaned.flex-white.css';
/**
* Find which SV theme the page is using.
* @return {Enumeration} - A value from {@link THEMES}
*/
function getSvTheme() {
for (var theme in THEMES) {
if (!THEMES.hasOwnProperty(theme)) continue;
var themeEnum = THEMES[theme];
if ($(CRITERIA[themeEnum]).length > 0) {
return themeEnum;
}
}
}
function init() {
// Note that just adding in a stylesheet tag doesn't work, on account of
// strict mode errors about mime types. Ugh.
$.ajax({
url: STYLES[THEMES.GLOBAL],
success: function (data) {
$("<style></style>").appendTo("head").html(data);
}
});
// figure out which theme we're on
var currentTheme = getSvTheme();
console.log('Found SV theme:', currentTheme);
if (STYLES[currentTheme]) {
$.ajax({
url: STYLES[currentTheme],
success: function (data) {
$("<style></style>").appendTo("head").html(data);
}
});
}
}
init();
})(this.$);
| mit |
agentada/agentada | config/apis.js | 347 | module.exports.apis = {
facebook: {
id: process.env.API_KEY_FACEBOOK_ID || 'ENTER_YOUR_CLIENT_ID',
secret: process.env.API_KEY_FACEBOOK_SECRET || 'ENTER_YOUR_SECRET'
},
foursquare: {
id: process.env.API_KEY_FOURSQUARE_ID || 'ENTER_YOUR_CLIENT_ID',
secret: process.env.API_KEY_FOURSQUARE_SECRET || 'ENTER_YOUR_SECRET'
}
};
| mit |
aftaberski/valentines-app | app/models/vote.rb | 78 | class Vote < ActiveRecord::Base
belongs_to :article
belongs_to :user
end
| mit |
Rimbit/Wallets | src/test/Checkpoints_tests.cpp | 1040 | //
// Unit tests for block-chain checkpoints
//
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/test/unit_test.hpp>
#include <boost/foreach.hpp>
#include "../checkpoints.h"
#include "../util.h"
using namespace std;
BOOST_AUTO_TEST_SUITE(Checkpoints_tests)
BOOST_AUTO_TEST_CASE(sanity)
{
uint256 p0 = uint256("0x3cdd9c2facce405f5cc220fb21a10e493041451c463a22e1ff6fe903fc5769fc");
uint256 p1 = uint256("0x00000df334b33e08c9e10b351a4be5f5f11d0ce7c3b882150b0514174a23862a");
BOOST_CHECK(Checkpoints::CheckHardened(0, p0));
BOOST_CHECK(Checkpoints::CheckHardened(1, p1));
// Wrong hashes at checkpoints should fail:
BOOST_CHECK(!Checkpoints::CheckHardened(0, p1));
BOOST_CHECK(!Checkpoints::CheckHardened(1, p0));
// ... but any hash not at a checkpoint should succeed:
BOOST_CHECK(Checkpoints::CheckHardened(0+1, p1));
BOOST_CHECK(Checkpoints::CheckHardened(1+1, p0));
BOOST_CHECK(Checkpoints::GetTotalBlocksEstimate() >= 1);
}
BOOST_AUTO_TEST_SUITE_END()
| mit |
artsmia/griot | js/controllers/object.js | 8414 | /**
* Controller for object template.
*/
app.controller('ObjectCtrl', ['$scope', '$routeParams', '$location', '$sce', 'resolvedNotes', 'segmentio', '$rootScope', 'miaMediaMetaAdapter', 'miaObjectMetaAdapter', 'miaThumbnailAdapter', 'email', 'envConfig', '$timeout', 'resolvedObjectMeta',
function($scope, $routeParams, $location, $sce, notes, segmentio, $rootScope, mediaMeta, objectMetaAdapter, miaThumbs, email, config, $timeout, objectMeta) {
// Defaults
$scope.movedZoomer = false;
$scope.currentAttachment = null;
$scope.contentMinimized = window.outerWidth < 1024;
$scope.enableSharing = config.miaEmailSharingActive
$scope.translucent = false;
$scope.id = $routeParams.id
$rootScope.lastObjectId = $scope.id = $routeParams.id
_wp = notes
$scope.wp = _wp.objects[$scope.id]
segmentio.track('Browsed an Object', {id: $scope.id, name: $scope.wp.title})
$scope.wp.meta3 = $sce.trustAsHtml( $scope.wp.meta3 );
// Replace object metadata if using adapter
if( objectMetaAdapter.isActive ) {
$scope.wp.meta1 = $scope.wp.meta1 || objectMeta.meta1;
$scope.wp.meta2 = $scope.wp.meta2 || objectMeta.meta2;
$scope.wp.meta3 = $scope.wp.meta3 || objectMeta.meta3;
$scope.wp.location = objectMeta.location;
}
$scope.relatedStories = []
angular.forEach($scope.wp.relatedStories, function(story_id){
if( _wp.stories[story_id] ) {
$scope.relatedStories.push({
'id':story_id,
'title':_wp.stories[story_id].title
})
}
})
if($scope.wp) {
$scope.mainImage = $scope.wp.views[0].image
$scope.wp.trustedDescription = $sce.trustAsHtml($scope.wp.description)
$scope.$on('viewChanged', loadDetails)
$scope.$watch('mapLoaded', function(v) { v && loadDetails() }) // TODO: once details load, cancel this watch
// Open the More tab when returning from a story via the 'Back' button
if($rootScope.nextView) {
$scope.activeSection = $rootScope.nextView
$rootScope.nextView = undefined
// make sure the drawer is open, if we have one
var drawer = angular.element($('.object-content-container')).scope().drawerify
if(drawer) drawer.to('open', 0)
}
$scope.$$phase || $scope.$apply()
}
var loadDetails = function() {
$scope.notes = $scope.wp.views;
$scope.allNotes = [];
$scope.allAttachments = [];
angular.forEach($scope.notes, function(view) {
angular.forEach(view.annotations, function(ann) {
ann.trustedDescription = $sce.trustAsHtml(ann.description)
ann.view = view;
$scope.allNotes.push( ann );
// Replace attachment metadata if using adapter
angular.forEach( ann.attachments, function(att) {
att.thumbnail = miaThumbs.get(att.image_id)
if( mediaMeta.isActive ) {
// Hacky! We need to only trustAsHtml(att.meta) once. Or find a better way generally.
att.meta = mediaMeta.get( att.image_id ) || ( typeof att.meta === 'object' ? att.meta : $sce.trustAsHtml(att.meta) );
}
att.trustedDescription = $sce.trustAsHtml(att.description);
$scope.allAttachments.push( att );
})
})
})
$scope.$$phase || $scope.$apply()
}
$scope.next = function(direction) {
var next = $scope.objects.ids[$scope.objects.ids.indexOf(parseInt($scope.id))+1]
if(next) $location.url('/o/'+next)
}
$scope.prev = function(direction) {
var prev = $scope.objects.ids[$scope.objects.ids.indexOf(parseInt($scope.id))-1]
if(prev) $location.url('/o/'+prev)
}
$scope.viewEnabled = function(nextView, debug) {
return (nextView == 'more' && $scope.relatedStories && $scope.relatedStories.length > 0 ||
nextView == 'annotations' && getFirstDetail() ||
nextView == 'about')
}
// return the first annotation, falsey if there aren't any
function getFirstDetail() {
var i = 0, view = $scope.notes && $scope.notes[i], firstDetail
while(view && view.annotations.length == 0) {
view = $scope.notes && $scope.notes[i]
i++
}
firstDetail = view && view.annotations && view.annotations[0]
return firstDetail
}
$scope.toggleView = function(nextView, dontTrack) {
if(!dontTrack) segmentio.track('Changed Sections within an Object', {view: nextView})
nextView = nextView || 'about'
if(!$scope.viewEnabled(nextView)) return
if(nextView == 'annotations') {
if(!$scope.notes) $scope.notes = $scope.wp.views
var firstDetail = getFirstDetail()
if(firstDetail && !$scope.flatmapScope.lastActiveNote) {
$scope.activateNote(firstDetail, $scope.notes[0])
} else if($scope.flatmapScope.lastActiveNote) {
// If there's an active annotation, center the map over it.
$scope.glanceText = $sce.trustAsHtml( "Press to view detail <span class='annotation-index'>" + $scope.flatmapScope.lastActiveNote.index + "</span>" );
if(!$scope.flatmapScope.zoom.map.getBounds().contains($scope.flatmapScope.jsonLayer.getBounds())) {
$scope.$broadcast('changeGeometry', $scope.flatmapScope.lastActiveNote.geoJSON.geometry)
}
}
} else {
$scope.glanceText = $sce.trustAsHtml( "Press to view object" );
}
// Reset image to the primary when changing back to about
if(nextView == 'about' && $scope.flatmapScope && $scope.notes[0].image != $scope.flatmapScope.image) {
$scope.activateView($scope.notes[0])
}
$scope.activeSection = nextView
}
$scope.toggleAttachment = function(attachment, closeAttachmentIfOpen, $event){
if($scope.currentAttachment==attachment){
if(!closeAttachmentIfOpen) return;
$scope.currentAttachment = $scope.showAttachmentCredits = null;
} else {
$scope.currentAttachment = attachment;
$scope.showAttachmentCredits = false
setTimeout(Zoomer.windowResized, 0);
}
if($event) $event.stopPropagation();
}
$scope.toggleAttachmentCredits = function(attachment) {
$scope.showAttachmentCredits = !$scope.showAttachmentCredits
setTimeout(Zoomer.windowResized, 125)
}
$scope.toggleView($scope.activeSection, true)
$scope.$on('showAnnotationsPanel', function(view) {
$scope.activeSection = 'annotations'
})
$scope.changeZoomerForViews = function(map, flatmapScope) {
$scope.$apply(function() { $scope.showViews = true })
}
$scope.activateNote = function(note, view) {
/*
$scope.translucent = true;
*/
$scope.showViews = false
$scope.activeView = view
note.active = !note.active
$scope.glanceText = $sce.trustAsHtml( "Press to view detail <span class='annotation-index'>" + note.index + "</span>" );
/*
$timeout( function(){
$scope.translucent = false;
}, 1000 );
*/
}
$scope.deactivateAllNotes = function() {
angular.forEach($scope.notes, function(view) {
angular.forEach(view.annotations, function(ann) { ann.active = false; })
})
$scope.$$phase || $scope.$apply()
}
$scope.activateView = function(view) {
// TODO: encapsulate active view the same way I do notes, with view.active?
$scope.showViews = false
$scope.activeView = view
$scope.deactivateAllNotes()
$scope.flatmapScope.$broadcast('changeView', view)
}
$scope.activateViewAndShowFirstAnnotation = function(view) {
$scope.activateView(view)
var note = view.annotations[0]
if(note) activateNote(note)
}
$scope.toggleSixbar = function(element) {
$scope.sixBarClosed = !$scope.sixBarClosed
setTimeout(Zoomer.windowResized, 0)
}
$scope.toggleExtendedTombstone = function(event) {
$scope.showExtendedTombstone = !$scope.showExtendedTombstone
$scope.$broadcast( 'recalculateCustomDrawerStates' );
if(event) event.stopPropagation()
}
$scope.toggleMinimizeContent = function() {
$scope.contentMinimized = !$scope.contentMinimized;
//setTimeout( Zoomer.windowResized, 125); // Zoomer now stays put behind content
}
$scope.glanceText = $sce.trustAsHtml( "Press to view object" );
}
])
| mit |
gustavojm/CodeIgniter4 | system/Filters/FilterInterface.php | 2885 | <?php
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014-2019 British Columbia Institute of Technology
* Copyright (c) 2019-2020 CodeIgniter Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package CodeIgniter
* @author CodeIgniter Dev Team
* @copyright 2019-2020 CodeIgniter Foundation
* @license https://opensource.org/licenses/MIT MIT License
* @link https://codeigniter.com
* @since Version 4.0.0
* @filesource
*/
namespace CodeIgniter\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Filter interface
*/
interface FilterInterface
{
/**
* Do whatever processing this filter needs to do.
* By default it should not return anything during
* normal execution. However, when an abnormal state
* is found, it should return an instance of
* CodeIgniter\HTTP\Response. If it does, script
* execution will end and that Response will be
* sent back to the client, allowing for error pages,
* redirects, etc.
*
* @param \CodeIgniter\HTTP\RequestInterface $request
*
* @return mixed
*/
public function before(RequestInterface $request);
//--------------------------------------------------------------------
/**
* Allows After filters to inspect and modify the response
* object as needed. This method does not allow any way
* to stop execution of other after filters, short of
* throwing an Exception or Error.
*
* @param \CodeIgniter\HTTP\RequestInterface $request
* @param \CodeIgniter\HTTP\ResponseInterface $response
*
* @return mixed
*/
public function after(RequestInterface $request, ResponseInterface $response);
//--------------------------------------------------------------------
}
| mit |
spatialaudio/nbsphinx | src/nbsphinx.py | 83463 | # Copyright (c) 2015-2021 Matthias Geier
#
# 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.
"""Jupyter Notebook Tools for Sphinx.
https://nbsphinx.readthedocs.io/
"""
__version__ = '0.8.8'
import collections.abc
import copy
import html
import json
import os
import re
import subprocess
import sys
from urllib.parse import unquote
import uuid
import docutils
from docutils.parsers import rst
import jinja2
import nbconvert
import nbformat
import sphinx
import sphinx.directives
import sphinx.directives.other
import sphinx.environment
import sphinx.errors
import sphinx.transforms.post_transforms.images
from sphinx.util.matching import patmatch
import traitlets
if sys.version_info >= (3, 8) and sys.platform == 'win32':
# See: https://github.com/jupyter/jupyter_client/issues/583
import asyncio
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
_ipynbversion = 4
logger = sphinx.util.logging.getLogger(__name__)
_BROKEN_THUMBNAIL = None
# See nbconvert/exporters/html.py:
DISPLAY_DATA_PRIORITY_HTML = (
'application/vnd.jupyter.widget-state+json',
'application/vnd.jupyter.widget-view+json',
'application/javascript',
'text/html',
'text/markdown',
'image/svg+xml',
'text/latex',
'image/png',
'image/jpeg',
'text/plain',
)
# See nbconvert/exporters/latex.py:
DISPLAY_DATA_PRIORITY_LATEX = (
'text/latex',
'application/pdf',
'image/png',
'image/jpeg',
'image/svg+xml',
'text/markdown',
'text/plain',
)
# The default rst template name is changing in nbconvert 6, so we substitute
# it in to the *extends* directive.
RST_TEMPLATE = """
{% extends '__RST_DEFAULT_TEMPLATE__' %}
{% macro insert_empty_lines(text) %}
{%- set before, after = text | get_empty_lines %}
{%- if before %}
:empty-lines-before: {{ before }}
{%- endif %}
{%- if after %}
:empty-lines-after: {{ after }}
{%- endif %}
{%- endmacro %}
{% block any_cell %}
{%- if cell.metadata.nbsphinx != 'hidden' %}
{{ super() }}
..
{# Empty comment to make sure the preceding directive (if any) is closed #}
{% endif %}
{%- endblock any_cell %}
{% block input -%}
.. nbinput:: {% if cell.metadata.magics_language -%}
{{ cell.metadata.magics_language }}
{%- elif nb.metadata.language_info -%}
{{ nb.metadata.language_info.pygments_lexer or nb.metadata.language_info.name }}
{%- else -%}
{{ resources.codecell_lexer }}
{%- endif -%}
{{ insert_empty_lines(cell.source) }}
{%- if cell.execution_count %}
:execution-count: {{ cell.execution_count }}
{%- endif %}
{%- if not cell.outputs %}
:no-output:
{%- endif %}
{{ cell.source.strip('\n') | indent }}
{% endblock input %}
{% macro insert_nboutput(datatype, output, cell) -%}
.. nboutput::
{%- if output.output_type == 'execute_result' and cell.execution_count %}
:execution-count: {{ cell.execution_count }}
{%- endif %}
{%- if output != cell.outputs[-1] %}
:more-to-come:
{%- endif %}
{%- if output.name == 'stderr' %}
:class: stderr
{%- endif %}
{%- if datatype != 'text/plain' %}
:fancy:
{%- endif %}
{%- if datatype == 'text/plain' %}
.. rst-class:: highlight
.. raw:: html
<pre>
{{ output.data[datatype] | ansi2html | indent | indent }}
</pre>
.. raw:: latex
\\begin{sphinxVerbatim}[commandchars=\\\\\\{\\}]
{{ output.data[datatype] | escape_latex | ansi2latex | indent | indent }}
\\end{sphinxVerbatim}
{# NB: The "raw" directive doesn't work with empty content #}
{%- if output.data[datatype].strip() %}
.. raw:: text
{{ output.data[datatype] | indent | indent }}
{%- endif %}
{%- elif datatype in ['image/svg+xml', 'image/png', 'image/jpeg', 'application/pdf'] %}
.. image:: {{ output.metadata.filenames[datatype] | posix_path }}
{%- if datatype in output.metadata %}
:class: no-scaled-link
{%- set width = output.metadata[datatype].width %}
{%- if width %}
:width: {{ width }}
{%- endif %}
{%- set height = output.metadata[datatype].height %}
{%- if height %}
:height: {{ height }}
{% endif %}
{% endif %}
{%- elif datatype in ['text/markdown'] %}
{{ output.data['text/markdown'] | markdown2rst | indent }}
{%- elif datatype in ['text/latex'] %}
.. math::
:nowrap:
{{ output.data['text/latex'] | indent | indent }}
{%- elif datatype == 'text/html' %}
:class: rendered_html
.. raw:: html
{{ (output.data['text/html'] or '<!-- empty output -->') | indent | indent }}
{%- elif datatype == 'application/javascript' %}
.. raw:: html
<div class="output_javascript"></div>
<script type="text/javascript">
var element = document.currentScript.previousSibling.previousSibling;
{{ output.data['application/javascript'] | indent | indent }}
</script>
{%- elif datatype.startswith('application/vnd.jupyter') and datatype.endswith('+json') %}
.. raw:: html
<script type="{{ datatype }}">{{ output.data[datatype] | json_dumps }}</script>
{%- elif datatype == '' %}
{# Empty output data #}
..
{% else %}
.. nbwarning:: Data type cannot be displayed: {{ datatype }}
{%- endif %}
{% endmacro %}
{% block nboutput -%}
..
{# Empty comment to make sure the preceding directive (if any) is closed #}
{%- set html_datatype, latex_datatype = output | get_output_type %}
{%- if html_datatype == latex_datatype %}
{{ insert_nboutput(html_datatype, output, cell) }}
{% else %}
.. only:: html
{{ insert_nboutput(html_datatype, output, cell) | indent }}
.. only:: latex
{{ insert_nboutput(latex_datatype, output, cell) | indent }}
{% endif %}
{% endblock nboutput %}
{% block execute_result %}{{ self.nboutput() }}{% endblock execute_result %}
{% block display_data %}{{ self.nboutput() }}{% endblock display_data %}
{% block stream %}{{ self.nboutput() }}{% endblock stream %}
{% block error %}{{ self.nboutput() }}{% endblock error %}
{% block markdowncell %}
{%- if 'nbsphinx-gallery' in cell.metadata
or 'nbsphinx-gallery' in cell.metadata.get('tags', [])
or 'nbsphinx-toctree' in cell.metadata
or 'nbsphinx-toctree' in cell.metadata.get('tags', []) %}
{{ cell | extract_gallery_or_toctree }}
{%- else %}
{{ cell | save_attachments or super() | replace_attachments }}
{% endif %}
{% endblock markdowncell %}
{% block rawcell %}
{%- set raw_mimetype = cell.metadata.get('raw_mimetype', '').lower() %}
{%- if raw_mimetype == '' %}
.. raw:: html
{{ (cell.source or '<!-- empty raw cell -->') | indent }}
.. raw:: latex
{{ (cell.source or '% empty raw cell') | indent }}
{%- elif raw_mimetype == 'text/html' %}
.. raw:: html
{{ (cell.source or '<!-- empty raw cell -->') | indent }}
{%- elif raw_mimetype == 'text/latex' %}
.. raw:: latex
{{ (cell.source or '% empty raw cell') | indent }}
{%- elif raw_mimetype == 'text/markdown' %}
{{ cell.source | markdown2rst }}
{%- elif raw_mimetype == 'text/restructuredtext' %}
{{ cell.source }}
{% endif %}
{% endblock rawcell %}
{% block footer %}
{% if 'application/vnd.jupyter.widget-state+json' in nb.metadata.get('widgets', {})%}
.. raw:: html
<script type="application/vnd.jupyter.widget-state+json">
{{ nb.metadata.widgets['application/vnd.jupyter.widget-state+json'] | json_dumps }}
</script>
{% endif %}
{{ super() }}
{% endblock footer %}
""".replace('__RST_DEFAULT_TEMPLATE__', nbconvert.RSTExporter().template_file)
LATEX_PREAMBLE = r"""
% Jupyter Notebook code cell colors
\definecolor{nbsphinxin}{HTML}{307FC1}
\definecolor{nbsphinxout}{HTML}{BF5B3D}
\definecolor{nbsphinx-code-bg}{HTML}{F5F5F5}
\definecolor{nbsphinx-code-border}{HTML}{E0E0E0}
\definecolor{nbsphinx-stderr}{HTML}{FFDDDD}
% ANSI colors for output streams and traceback highlighting
\definecolor{ansi-black}{HTML}{3E424D}
\definecolor{ansi-black-intense}{HTML}{282C36}
\definecolor{ansi-red}{HTML}{E75C58}
\definecolor{ansi-red-intense}{HTML}{B22B31}
\definecolor{ansi-green}{HTML}{00A250}
\definecolor{ansi-green-intense}{HTML}{007427}
\definecolor{ansi-yellow}{HTML}{DDB62B}
\definecolor{ansi-yellow-intense}{HTML}{B27D12}
\definecolor{ansi-blue}{HTML}{208FFB}
\definecolor{ansi-blue-intense}{HTML}{0065CA}
\definecolor{ansi-magenta}{HTML}{D160C4}
\definecolor{ansi-magenta-intense}{HTML}{A03196}
\definecolor{ansi-cyan}{HTML}{60C6C8}
\definecolor{ansi-cyan-intense}{HTML}{258F8F}
\definecolor{ansi-white}{HTML}{C5C1B4}
\definecolor{ansi-white-intense}{HTML}{A1A6B2}
\definecolor{ansi-default-inverse-fg}{HTML}{FFFFFF}
\definecolor{ansi-default-inverse-bg}{HTML}{000000}
% Define an environment for non-plain-text code cell outputs (e.g. images)
\makeatletter
\newenvironment{nbsphinxfancyoutput}{%
% Avoid fatal error with framed.sty if graphics too long to fit on one page
\let\sphinxincludegraphics\nbsphinxincludegraphics
\nbsphinx@image@maxheight\textheight
\advance\nbsphinx@image@maxheight -2\fboxsep % default \fboxsep 3pt
\advance\nbsphinx@image@maxheight -2\fboxrule % default \fboxrule 0.4pt
\advance\nbsphinx@image@maxheight -\baselineskip
\def\nbsphinxfcolorbox{\spx@fcolorbox{nbsphinx-code-border}{white}}%
\def\FrameCommand{\nbsphinxfcolorbox\nbsphinxfancyaddprompt\@empty}%
\def\FirstFrameCommand{\nbsphinxfcolorbox\nbsphinxfancyaddprompt\sphinxVerbatim@Continues}%
\def\MidFrameCommand{\nbsphinxfcolorbox\sphinxVerbatim@Continued\sphinxVerbatim@Continues}%
\def\LastFrameCommand{\nbsphinxfcolorbox\sphinxVerbatim@Continued\@empty}%
\MakeFramed{\advance\hsize-\width\@totalleftmargin\z@\linewidth\hsize\@setminipage}%
\lineskip=1ex\lineskiplimit=1ex\raggedright%
}{\par\unskip\@minipagefalse\endMakeFramed}
\makeatother
\newbox\nbsphinxpromptbox
\def\nbsphinxfancyaddprompt{\ifvoid\nbsphinxpromptbox\else
\kern\fboxrule\kern\fboxsep
\copy\nbsphinxpromptbox
\kern-\ht\nbsphinxpromptbox\kern-\dp\nbsphinxpromptbox
\kern-\fboxsep\kern-\fboxrule\nointerlineskip
\fi}
\newlength\nbsphinxcodecellspacing
\setlength{\nbsphinxcodecellspacing}{0pt}
% Define support macros for attaching opening and closing lines to notebooks
\newsavebox\nbsphinxbox
\makeatletter
\newcommand{\nbsphinxstartnotebook}[1]{%
\par
% measure needed space
\setbox\nbsphinxbox\vtop{{#1\par}}
% reserve some space at bottom of page, else start new page
\needspace{\dimexpr2.5\baselineskip+\ht\nbsphinxbox+\dp\nbsphinxbox}
% mimick vertical spacing from \section command
\addpenalty\@secpenalty
\@tempskipa 3.5ex \@plus 1ex \@minus .2ex\relax
\addvspace\@tempskipa
{\Large\@tempskipa\baselineskip
\advance\@tempskipa-\prevdepth
\advance\@tempskipa-\ht\nbsphinxbox
\ifdim\@tempskipa>\z@
\vskip \@tempskipa
\fi}
\unvbox\nbsphinxbox
% if notebook starts with a \section, prevent it from adding extra space
\@nobreaktrue\everypar{\@nobreakfalse\everypar{}}%
% compensate the parskip which will get inserted by next paragraph
\nobreak\vskip-\parskip
% do not break here
\nobreak
}% end of \nbsphinxstartnotebook
\newcommand{\nbsphinxstopnotebook}[1]{%
\par
% measure needed space
\setbox\nbsphinxbox\vbox{{#1\par}}
\nobreak % it updates page totals
\dimen@\pagegoal
\advance\dimen@-\pagetotal \advance\dimen@-\pagedepth
\advance\dimen@-\ht\nbsphinxbox \advance\dimen@-\dp\nbsphinxbox
\ifdim\dimen@<\z@
% little space left
\unvbox\nbsphinxbox
\kern-.8\baselineskip
\nobreak\vskip\z@\@plus1fil
\penalty100
\vskip\z@\@plus-1fil
\kern.8\baselineskip
\else
\unvbox\nbsphinxbox
\fi
}% end of \nbsphinxstopnotebook
% Ensure height of an included graphics fits in nbsphinxfancyoutput frame
\newdimen\nbsphinx@image@maxheight % set in nbsphinxfancyoutput environment
\newcommand*{\nbsphinxincludegraphics}[2][]{%
\gdef\spx@includegraphics@options{#1}%
\setbox\spx@image@box\hbox{\includegraphics[#1,draft]{#2}}%
\in@false
\ifdim \wd\spx@image@box>\linewidth
\g@addto@macro\spx@includegraphics@options{,width=\linewidth}%
\in@true
\fi
% no rotation, no need to worry about depth
\ifdim \ht\spx@image@box>\nbsphinx@image@maxheight
\g@addto@macro\spx@includegraphics@options{,height=\nbsphinx@image@maxheight}%
\in@true
\fi
\ifin@
\g@addto@macro\spx@includegraphics@options{,keepaspectratio}%
\fi
\setbox\spx@image@box\box\voidb@x % clear memory
\expandafter\includegraphics\expandafter[\spx@includegraphics@options]{#2}%
}% end of "\MakeFrame"-safe variant of \sphinxincludegraphics
\makeatother
\makeatletter
\renewcommand*\sphinx@verbatim@nolig@list{\do\'\do\`}
\begingroup
\catcode`'=\active
\let\nbsphinx@noligs\@noligs
\g@addto@macro\nbsphinx@noligs{\let'\PYGZsq}
\endgroup
\makeatother
\renewcommand*\sphinxbreaksbeforeactivelist{\do\<\do\"\do\'}
\renewcommand*\sphinxbreaksafteractivelist{\do\.\do\,\do\:\do\;\do\?\do\!\do\/\do\>\do\-}
\makeatletter
\fvset{codes*=\sphinxbreaksattexescapedchars\do\^\^\let\@noligs\nbsphinx@noligs}
\makeatother
"""
CSS_STRING = """
/* CSS for nbsphinx extension */
/* remove conflicting styling from Sphinx themes */
div.nbinput.container div.prompt *,
div.nboutput.container div.prompt *,
div.nbinput.container div.input_area pre,
div.nboutput.container div.output_area pre,
div.nbinput.container div.input_area .highlight,
div.nboutput.container div.output_area .highlight {
border: none;
padding: 0;
margin: 0;
box-shadow: none;
}
div.nbinput.container > div[class*=highlight],
div.nboutput.container > div[class*=highlight] {
margin: 0;
}
div.nbinput.container div.prompt *,
div.nboutput.container div.prompt * {
background: none;
}
div.nboutput.container div.output_area .highlight,
div.nboutput.container div.output_area pre {
background: unset;
}
div.nboutput.container div.output_area div.highlight {
color: unset; /* override Pygments text color */
}
/* avoid gaps between output lines */
div.nboutput.container div[class*=highlight] pre {
line-height: normal;
}
/* input/output containers */
div.nbinput.container,
div.nboutput.container {
display: -webkit-flex;
display: flex;
align-items: flex-start;
margin: 0;
width: 100%%;
}
@media (max-width: %(nbsphinx_responsive_width)s) {
div.nbinput.container,
div.nboutput.container {
flex-direction: column;
}
}
/* input container */
div.nbinput.container {
padding-top: 5px;
}
/* last container */
div.nblast.container {
padding-bottom: 5px;
}
/* input prompt */
div.nbinput.container div.prompt pre {
color: #307FC1;
}
/* output prompt */
div.nboutput.container div.prompt pre {
color: #BF5B3D;
}
/* all prompts */
div.nbinput.container div.prompt,
div.nboutput.container div.prompt {
width: %(nbsphinx_prompt_width)s;
padding-top: 5px;
position: relative;
user-select: none;
}
div.nbinput.container div.prompt > div,
div.nboutput.container div.prompt > div {
position: absolute;
right: 0;
margin-right: 0.3ex;
}
@media (max-width: %(nbsphinx_responsive_width)s) {
div.nbinput.container div.prompt,
div.nboutput.container div.prompt {
width: unset;
text-align: left;
padding: 0.4em;
}
div.nboutput.container div.prompt.empty {
padding: 0;
}
div.nbinput.container div.prompt > div,
div.nboutput.container div.prompt > div {
position: unset;
}
}
/* disable scrollbars on prompts */
div.nbinput.container div.prompt pre,
div.nboutput.container div.prompt pre {
overflow: hidden;
}
/* input/output area */
div.nbinput.container div.input_area,
div.nboutput.container div.output_area {
-webkit-flex: 1;
flex: 1;
overflow: auto;
}
@media (max-width: %(nbsphinx_responsive_width)s) {
div.nbinput.container div.input_area,
div.nboutput.container div.output_area {
width: 100%%;
}
}
/* input area */
div.nbinput.container div.input_area {
border: 1px solid #e0e0e0;
border-radius: 2px;
/*background: #f5f5f5;*/
}
/* override MathJax center alignment in output cells */
div.nboutput.container div[class*=MathJax] {
text-align: left !important;
}
/* override sphinx.ext.imgmath center alignment in output cells */
div.nboutput.container div.math p {
text-align: left;
}
/* standard error */
div.nboutput.container div.output_area.stderr {
background: #fdd;
}
/* ANSI colors */
.ansi-black-fg { color: #3E424D; }
.ansi-black-bg { background-color: #3E424D; }
.ansi-black-intense-fg { color: #282C36; }
.ansi-black-intense-bg { background-color: #282C36; }
.ansi-red-fg { color: #E75C58; }
.ansi-red-bg { background-color: #E75C58; }
.ansi-red-intense-fg { color: #B22B31; }
.ansi-red-intense-bg { background-color: #B22B31; }
.ansi-green-fg { color: #00A250; }
.ansi-green-bg { background-color: #00A250; }
.ansi-green-intense-fg { color: #007427; }
.ansi-green-intense-bg { background-color: #007427; }
.ansi-yellow-fg { color: #DDB62B; }
.ansi-yellow-bg { background-color: #DDB62B; }
.ansi-yellow-intense-fg { color: #B27D12; }
.ansi-yellow-intense-bg { background-color: #B27D12; }
.ansi-blue-fg { color: #208FFB; }
.ansi-blue-bg { background-color: #208FFB; }
.ansi-blue-intense-fg { color: #0065CA; }
.ansi-blue-intense-bg { background-color: #0065CA; }
.ansi-magenta-fg { color: #D160C4; }
.ansi-magenta-bg { background-color: #D160C4; }
.ansi-magenta-intense-fg { color: #A03196; }
.ansi-magenta-intense-bg { background-color: #A03196; }
.ansi-cyan-fg { color: #60C6C8; }
.ansi-cyan-bg { background-color: #60C6C8; }
.ansi-cyan-intense-fg { color: #258F8F; }
.ansi-cyan-intense-bg { background-color: #258F8F; }
.ansi-white-fg { color: #C5C1B4; }
.ansi-white-bg { background-color: #C5C1B4; }
.ansi-white-intense-fg { color: #A1A6B2; }
.ansi-white-intense-bg { background-color: #A1A6B2; }
.ansi-default-inverse-fg { color: #FFFFFF; }
.ansi-default-inverse-bg { background-color: #000000; }
.ansi-bold { font-weight: bold; }
.ansi-underline { text-decoration: underline; }
div.nbinput.container div.input_area div[class*=highlight] > pre,
div.nboutput.container div.output_area div[class*=highlight] > pre,
div.nboutput.container div.output_area div[class*=highlight].math,
div.nboutput.container div.output_area.rendered_html,
div.nboutput.container div.output_area > div.output_javascript,
div.nboutput.container div.output_area:not(.rendered_html) > img{
padding: 5px;
margin: 0;
}
/* fix copybtn overflow problem in chromium (needed for 'sphinx_copybutton') */
div.nbinput.container div.input_area > div[class^='highlight'],
div.nboutput.container div.output_area > div[class^='highlight']{
overflow-y: hidden;
}
/* hide copybtn icon on prompts (needed for 'sphinx_copybutton') */
.prompt .copybtn {
display: none;
}
/* Some additional styling taken form the Jupyter notebook CSS */
.jp-RenderedHTMLCommon table,
div.rendered_html table {
border: none;
border-collapse: collapse;
border-spacing: 0;
color: black;
font-size: 12px;
table-layout: fixed;
}
.jp-RenderedHTMLCommon thead,
div.rendered_html thead {
border-bottom: 1px solid black;
vertical-align: bottom;
}
.jp-RenderedHTMLCommon tr,
.jp-RenderedHTMLCommon th,
.jp-RenderedHTMLCommon td,
div.rendered_html tr,
div.rendered_html th,
div.rendered_html td {
text-align: right;
vertical-align: middle;
padding: 0.5em 0.5em;
line-height: normal;
white-space: normal;
max-width: none;
border: none;
}
.jp-RenderedHTMLCommon th,
div.rendered_html th {
font-weight: bold;
}
.jp-RenderedHTMLCommon tbody tr:nth-child(odd),
div.rendered_html tbody tr:nth-child(odd) {
background: #f5f5f5;
}
.jp-RenderedHTMLCommon tbody tr:hover,
div.rendered_html tbody tr:hover {
background: rgba(66, 165, 245, 0.2);
}
"""
CSS_STRING_READTHEDOCS = """
/* CSS overrides for sphinx_rtd_theme */
/* 24px margin */
.nbinput.nblast.container,
.nboutput.nblast.container {
margin-bottom: 19px; /* padding has already 5px */
}
/* ... except between code cells! */
.nblast.container + .nbinput.container {
margin-top: -19px;
}
.admonition > p:before {
margin-right: 4px; /* make room for the exclamation icon */
}
/* Fix math alignment, see https://github.com/rtfd/sphinx_rtd_theme/pull/686 */
.math {
text-align: unset;
}
"""
CSS_STRING_CLOUD = """
/* CSS overrides for cloud theme */
/* nicer titles and more space for info and warning logos */
div.admonition p.admonition-title {
background: rgba(0, 0, 0, .05);
margin: .5em -1em;
margin-top: -.5em !important;
padding: .5em .5em .5em 2.65em;
}
/* indent single paragraph */
div.admonition {
text-indent: 20px;
}
/* don't indent multiple paragraphs */
div.admonition > p {
text-indent: 0;
}
/* remove excessive padding */
div.admonition.inline-title p.admonition-title {
padding-left: .2em;
}
"""
class Exporter(nbconvert.RSTExporter):
"""Convert Jupyter notebooks to reStructuredText.
Uses nbconvert to convert Jupyter notebooks to a reStructuredText
string with custom reST directives for input and output cells.
Notebooks without output cells are automatically executed before
conversion.
"""
def __init__(self, execute='auto', kernel_name='', execute_arguments=[],
allow_errors=False, timeout=None, codecell_lexer='none'):
"""Initialize the Exporter."""
# NB: The following stateful Jinja filters are a hack until
# template-based processing is dropped
# (https://github.com/spatialaudio/nbsphinx/issues/36) or someone
# comes up with a better idea.
# NB: This instance-local state makes the methods non-reentrant!
attachment_storage = []
def save_attachments(cell):
for filename, bundle in cell.get('attachments', {}).items():
attachment_storage.append((filename, bundle))
def replace_attachments(text):
for filename, bundle in attachment_storage:
# For now, this works only if there is a single MIME bundle
(mime_type, data), = bundle.items()
text = re.sub(
r'^(\s*\.\. ((\|[^|]*\| )?image|figure)::) attachment:{0}$'
.format(filename),
r'\1 data:{0};base64,{1}'.format(mime_type, data),
text, flags=re.MULTILINE)
del attachment_storage[:]
return text
self._execute = execute
self._kernel_name = kernel_name
self._execute_arguments = execute_arguments
self._allow_errors = allow_errors
self._timeout = timeout
self._codecell_lexer = codecell_lexer
loader = jinja2.DictLoader({'nbsphinx-rst.tpl': RST_TEMPLATE})
super(Exporter, self).__init__(
template_file='nbsphinx-rst.tpl', extra_loaders=[loader],
config=traitlets.config.Config({
'HighlightMagicsPreprocessor': {'enabled': True},
# Work around https://github.com/jupyter/nbconvert/issues/720:
'RegexRemovePreprocessor': {'enabled': False},
}),
filters={
'convert_pandoc': convert_pandoc,
'markdown2rst': markdown2rst,
'get_empty_lines': _get_empty_lines,
'extract_gallery_or_toctree': _extract_gallery_or_toctree,
'save_attachments': save_attachments,
'replace_attachments': replace_attachments,
'get_output_type': _get_output_type,
'json_dumps': lambda s: re.sub(
r'<(/script)',
r'<\\\1',
json.dumps(s),
flags=re.IGNORECASE,
),
'basename': os.path.basename,
'dirname': os.path.dirname,
})
def from_notebook_node(self, nb, resources=None, **kw):
nb = copy.deepcopy(nb)
if resources is None:
resources = {}
else:
resources = copy.deepcopy(resources)
# Set default codecell lexer
resources['codecell_lexer'] = self._codecell_lexer
nbsphinx_metadata = nb.metadata.get('nbsphinx', {})
execute = nbsphinx_metadata.get('execute', self._execute)
if execute not in ('always', 'never', 'auto'):
raise ValueError('invalid execute option: {!r}'.format(execute))
auto_execute = (
execute == 'auto' and
# At least one code cell actually containing source code:
any(c.source for c in nb.cells if c.cell_type == 'code') and
# No outputs, not even a prompt number:
not any(c.get('outputs') or c.get('execution_count')
for c in nb.cells if c.cell_type == 'code')
)
if auto_execute or execute == 'always':
allow_errors = nbsphinx_metadata.get(
'allow_errors', self._allow_errors)
timeout = nbsphinx_metadata.get('timeout', self._timeout)
pp = nbconvert.preprocessors.ExecutePreprocessor(
kernel_name=self._kernel_name,
extra_arguments=self._execute_arguments,
allow_errors=allow_errors, timeout=timeout)
nb, resources = pp.preprocess(nb, resources)
if 'nbsphinx_save_notebook' in resources:
# Save *executed* notebook *before* the Exporter can change it:
nbformat.write(nb, resources['nbsphinx_save_notebook'])
# Call into RSTExporter
rststr, resources = super(Exporter, self).from_notebook_node(
nb, resources, **kw)
orphan = nbsphinx_metadata.get('orphan', False)
if orphan is True:
resources['nbsphinx_orphan'] = True
elif orphan is not False:
raise ValueError('invalid orphan option: {!r}'.format(orphan))
if 'application/vnd.jupyter.widget-state+json' in nb.metadata.get(
'widgets', {}):
resources['nbsphinx_widgets'] = True
thumbnail = {}
def warning(msg, *args):
logger.warning(
'"nbsphinx-thumbnail": ' + msg, *args,
location=resources.get('nbsphinx_docname'),
type='nbsphinx', subtype='thumbnail')
thumbnail['filename'] = _BROKEN_THUMBNAIL
for cell_index, cell in enumerate(nb.cells):
if 'nbsphinx-thumbnail' in cell.metadata:
data = cell.metadata['nbsphinx-thumbnail'].copy()
output_index = data.pop('output-index', -1)
tooltip = data.pop('tooltip', '')
if data:
warning('Invalid key(s): %s', set(data))
break
elif 'nbsphinx-thumbnail' in cell.metadata.get('tags', []):
output_index = -1
tooltip = ''
else:
continue
if cell.cell_type != 'code':
warning('Only allowed in code cells; cell %s has type "%s"',
cell_index, cell.cell_type)
break
if thumbnail:
warning('Only allowed once per notebook')
break
if not cell.outputs:
warning('No outputs in cell %s', cell_index)
break
if tooltip:
thumbnail['tooltip'] = tooltip
if output_index == -1:
output_index = len(cell.outputs) - 1
elif output_index >= len(cell.outputs):
warning('Invalid "output-index" in cell %s: %s',
cell_index, output_index)
break
out = cell.outputs[output_index]
if out.output_type not in {'display_data', 'execute_result'}:
warning('Unsupported output type in cell %s/output %s: "%s"',
cell_index, output_index, out.output_type)
break
for mime_type in DISPLAY_DATA_PRIORITY_HTML:
if mime_type not in out.data:
continue
if mime_type == 'image/svg+xml':
suffix = '.svg'
elif mime_type == 'image/png':
suffix = '.png'
elif mime_type == 'image/jpeg':
suffix = '.jpg'
else:
continue
thumbnail['filename'] = '{}_{}_{}{}'.format(
resources['unique_key'],
cell_index,
output_index,
suffix,
)
break
else:
warning('Unsupported MIME type(s) in cell %s/output %s: %s',
cell_index, output_index, set(out.data))
break
resources['nbsphinx_thumbnail'] = thumbnail
return rststr, resources
class NotebookParser(rst.Parser):
"""Sphinx source parser for Jupyter notebooks.
Uses nbsphinx.Exporter to convert notebook content to a
reStructuredText string, which is then parsed by Sphinx's built-in
reST parser.
"""
supported = 'jupyter_notebook',
def get_transforms(self):
"""List of transforms for documents parsed by this parser."""
return rst.Parser.get_transforms(self) + [
CreateNotebookSectionAnchors,
ReplaceAlertDivs,
CopyLinkedFiles,
ForceEquations,
]
def parse(self, inputstring, document):
"""Parse *inputstring*, write results to *document*.
*inputstring* is either the JSON representation of a notebook,
or a paragraph of text coming from the Sphinx translation
machinery.
Note: For now, the translation strings use reST formatting,
because the NotebookParser uses reST as intermediate
representation.
However, there are plans to remove this intermediate step
(https://github.com/spatialaudio/nbsphinx/issues/36), and after
that, the translated strings will most likely be parsed as
CommonMark.
If the configuration value "nbsphinx_custom_formats" is
specified, the input string is converted to the Jupyter notebook
format with the given conversion function.
"""
env = document.settings.env
formats = {
'.ipynb': lambda s: nbformat.reads(s, as_version=_ipynbversion)}
formats.update(env.config.nbsphinx_custom_formats)
srcfile = env.doc2path(env.docname, base=None)
for format, converter in formats.items():
if srcfile.endswith(format):
break
else:
raise NotebookError(
'No converter was found for {!r}'.format(srcfile))
if (isinstance(converter, collections.abc.Sequence) and
not isinstance(converter, str)):
if len(converter) != 2:
raise NotebookError(
'The values of nbsphinx_custom_formats must be '
'either strings or 2-element sequences')
converter, kwargs = converter
else:
kwargs = {}
if isinstance(converter, str):
converter = sphinx.util.import_object(converter)
try:
nb = converter(inputstring, **kwargs)
except Exception:
# NB: The use of the RST parser is temporary!
rst.Parser.parse(self, inputstring, document)
return
srcdir = os.path.dirname(env.doc2path(env.docname))
auxdir = env.nbsphinx_auxdir
resources = {}
# Working directory for ExecutePreprocessor
resources['metadata'] = {'path': srcdir}
# Sphinx doesn't accept absolute paths in images etc.
resources['output_files_dir'] = os.path.relpath(auxdir, srcdir)
resources['unique_key'] = re.sub('[/ ]', '_', env.docname)
resources['nbsphinx_docname'] = env.docname
# NB: The source file could have a different suffix
# if nbsphinx_custom_formats is used.
notebookfile = env.docname + '.ipynb'
env.nbsphinx_notebooks[env.docname] = notebookfile
auxfile = os.path.join(auxdir, notebookfile)
sphinx.util.ensuredir(os.path.dirname(auxfile))
resources['nbsphinx_save_notebook'] = auxfile
exporter = Exporter(
execute=env.config.nbsphinx_execute,
kernel_name=env.config.nbsphinx_kernel_name,
execute_arguments=env.config.nbsphinx_execute_arguments,
allow_errors=env.config.nbsphinx_allow_errors,
timeout=env.config.nbsphinx_timeout,
codecell_lexer=env.config.nbsphinx_codecell_lexer,
)
try:
rststring, resources = exporter.from_notebook_node(nb, resources)
except nbconvert.preprocessors.execute.CellExecutionError as e:
lines = str(e).split('\n')
lines[0] = 'CellExecutionError in {}:'.format(
env.doc2path(env.docname, base=None))
lines.append("You can ignore this error by setting the following "
"in conf.py:\n\n nbsphinx_allow_errors = True\n")
raise NotebookError('\n'.join(lines))
except Exception as e:
raise NotebookError(type(e).__name__ + ' in ' +
env.doc2path(env.docname, base=None) + ':\n' +
str(e))
rststring = """
.. role:: nbsphinx-math(raw)
:format: latex + html
:class: math
..
""" + rststring
# Create additional output files (figures etc.),
# see nbconvert.writers.FilesWriter.write()
for filename, data in resources.get('outputs', {}).items():
dest = os.path.normpath(os.path.join(srcdir, filename))
with open(dest, 'wb') as f:
f.write(data)
if resources.get('nbsphinx_orphan', False):
rst.Parser.parse(self, ':orphan:', document)
if env.config.nbsphinx_prolog:
prolog = exporter.environment.from_string(
env.config.nbsphinx_prolog).render(env=env)
rst.Parser.parse(self, prolog, document)
rst.Parser.parse(self, '.. highlight:: none', document)
if 'sphinx_codeautolink' in env.config.extensions:
rst.Parser.parse(self, '.. autolink-concat:: on', document)
rst.Parser.parse(self, rststring, document)
if env.config.nbsphinx_epilog:
epilog = exporter.environment.from_string(
env.config.nbsphinx_epilog).render(env=env)
rst.Parser.parse(self, epilog, document)
if resources.get('nbsphinx_widgets', False):
env.nbsphinx_widgets.add(env.docname)
env.nbsphinx_thumbnails[env.docname] = resources.get(
'nbsphinx_thumbnail', {})
class NotebookError(sphinx.errors.SphinxError):
"""Error during notebook parsing."""
category = 'Notebook error'
class CodeAreaNode(docutils.nodes.Element):
"""Input area or plain-text output area of a Jupyter notebook code cell."""
class FancyOutputNode(docutils.nodes.Element):
"""A custom node for non-plain-text output of code cells."""
def _create_code_nodes(directive):
"""Create nodes for an input or output code cell."""
directive.state.document['nbsphinx_include_css'] = True
execution_count = directive.options.get('execution-count')
config = directive.state.document.settings.env.config
if isinstance(directive, NbInput):
outer_classes = ['nbinput']
if 'no-output' in directive.options:
outer_classes.append('nblast')
inner_classes = ['input_area']
prompt_template = config.nbsphinx_input_prompt
if not execution_count:
execution_count = ' '
elif isinstance(directive, NbOutput):
outer_classes = ['nboutput']
if 'more-to-come' not in directive.options:
outer_classes.append('nblast')
inner_classes = ['output_area']
inner_classes.append(directive.options.get('class', ''))
prompt_template = config.nbsphinx_output_prompt
else:
assert False
outer_node = docutils.nodes.container(classes=outer_classes)
if execution_count:
prompt = prompt_template % (execution_count,)
prompt_node = docutils.nodes.literal_block(
prompt, prompt, language='none', classes=['prompt'])
else:
prompt = ''
prompt_node = docutils.nodes.container(classes=['prompt', 'empty'])
# NB: Prompts are added manually in LaTeX output
outer_node += sphinx.addnodes.only('', prompt_node, expr='html')
if isinstance(directive, NbInput):
text = '\n'.join(directive.content.data)
if directive.arguments:
language = directive.arguments[0]
else:
language = 'none'
inner_node = docutils.nodes.literal_block(
text, text, language=language, classes=inner_classes)
else:
inner_node = docutils.nodes.container(classes=inner_classes)
sphinx.util.nodes.nested_parse_with_titles(
directive.state, directive.content, inner_node)
if 'fancy' in directive.options:
outer_node += FancyOutputNode('', inner_node, prompt=prompt)
else:
codearea_node = CodeAreaNode(
'', inner_node, prompt=prompt, stderr='stderr' in inner_classes)
# See http://stackoverflow.com/q/34050044/.
for attr in 'empty-lines-before', 'empty-lines-after':
value = directive.options.get(attr, 0)
if value:
codearea_node[attr] = value
outer_node += codearea_node
return [outer_node]
class AdmonitionNode(docutils.nodes.Element):
"""A custom node for info and warning boxes."""
class GalleryToc(docutils.nodes.Element):
"""A wrapper node used for creating galleries."""
class GalleryNode(docutils.nodes.Element):
"""A custom node for thumbnail galleries."""
# See http://docutils.sourceforge.net/docs/howto/rst-directives.html
class NbInput(rst.Directive):
"""A notebook input cell with prompt and code area."""
required_arguments = 0
optional_arguments = 1 # lexer name
final_argument_whitespace = False
option_spec = {
'execution-count': rst.directives.positive_int,
'empty-lines-before': rst.directives.nonnegative_int,
'empty-lines-after': rst.directives.nonnegative_int,
'no-output': rst.directives.flag,
}
has_content = True
def run(self):
"""This is called by the reST parser."""
return _create_code_nodes(self)
class NbOutput(rst.Directive):
"""A notebook output cell with optional prompt."""
required_arguments = 0
final_argument_whitespace = False
option_spec = {
'execution-count': rst.directives.positive_int,
'more-to-come': rst.directives.flag,
'fancy': rst.directives.flag,
'class': rst.directives.unchanged,
}
has_content = True
def run(self):
"""This is called by the reST parser."""
return _create_code_nodes(self)
class _NbAdmonition(rst.Directive):
"""Base class for NbInfo and NbWarning."""
required_arguments = 0
optional_arguments = 0
option_spec = {}
has_content = True
def run(self):
"""This is called by the reST parser."""
node = AdmonitionNode(classes=['admonition', self._class])
self.state.nested_parse(self.content, self.content_offset, node)
return [node]
class NbInfo(_NbAdmonition):
"""An information box."""
_class = 'note'
class NbWarning(_NbAdmonition):
"""A warning box."""
_class = 'warning'
class NbGallery(sphinx.directives.other.TocTree):
"""A thumbnail gallery for notebooks."""
def run(self):
"""Wrap GalleryToc arount toctree."""
ret = super().run()
try:
toctree_wrapper = ret[-1]
toctree, = toctree_wrapper
except (IndexError, TypeError, ValueError):
return ret
if not isinstance(toctree, sphinx.addnodes.toctree):
return ret
gallerytoc = GalleryToc()
gallerytoc.extend(ret)
return [gallerytoc]
def convert_pandoc(text, from_format, to_format):
"""Simple wrapper for markdown2rst.
In nbconvert version 5.0, the use of markdown2rst in the RST
template was replaced by the new filter function convert_pandoc.
"""
if from_format != 'markdown' and to_format != 'rst':
raise ValueError('Unsupported conversion')
return markdown2rst(text)
class CitationParser(html.parser.HTMLParser):
def handle_starttag(self, tag, attrs):
if self._check_cite(attrs):
self.starttag = tag
def handle_endtag(self, tag):
self.endtag = tag
def handle_startendtag(self, tag, attrs):
self._check_cite(attrs)
def _check_cite(self, attrs):
for name, value in attrs:
if name == 'data-cite':
self.cite = ':cite:`' + value + '`'
return True
elif name == 'data-footcite':
self.cite = ':footcite:`' + value + '`'
return True
return False
def reset(self):
super().reset()
self.starttag = ''
self.endtag = ''
self.cite = ''
class ImgParser(html.parser.HTMLParser):
"""Turn HTML <img> tags into raw RST blocks."""
def handle_starttag(self, tag, attrs):
self._check_img(tag, attrs)
def handle_startendtag(self, tag, attrs):
self._check_img(tag, attrs)
def _check_img(self, tag, attrs):
if tag != 'img':
return
# NB: attrs is a list of pairs
attrs = dict(attrs)
if 'src' not in attrs:
return
img_path = nbconvert.filters.posix_path(attrs['src'])
if img_path.startswith('data'):
# Allow multi-line data, see issue #474
img_path = img_path.replace('\n', '')
lines = ['image:: ' + img_path]
indent = ' ' * 4
classes = []
if 'class' in attrs:
classes.append(attrs['class'])
if 'alt' in attrs:
lines.append(indent + ':alt: ' + attrs['alt'])
if 'width' in attrs:
lines.append(indent + ':width: ' + attrs['width'])
if 'height' in attrs:
lines.append(indent + ':height: ' + attrs['height'])
if {'width', 'height'}.intersection(attrs):
classes.append('no-scaled-link')
if classes:
lines.append(indent + ':class: ' + ' '.join(classes))
definition = '\n'.join(lines)
hex_id = uuid.uuid4().hex
definition = '.. |' + hex_id + '| ' + definition
self.obj = {'t': 'RawInline', 'c': ['rst', '|' + hex_id + '|']}
self.definition = definition
def reset(self):
super().reset()
self.obj = {}
def markdown2rst(text):
"""Convert a Markdown string to reST via pandoc.
This is very similar to nbconvert.filters.markdown.markdown2rst(),
except that it uses a pandoc filter to convert raw LaTeX blocks to
"math" directives (instead of "raw:: latex" directives).
NB: At some point, pandoc changed its behavior! In former times,
it converted LaTeX math environments to RawBlock ("latex"), at some
later point this was changed to RawInline ("tex").
Either way, we convert it to Math/DisplayMath.
"""
def parse_citation(obj):
p = CitationParser()
p.feed(obj['c'][1])
p.close()
return p
def parse_img(obj):
p = ImgParser()
p.feed(obj['c'][1])
p.close()
return p
def object_hook(obj):
if object_hook.open_cite_tag:
if obj.get('t') == 'RawInline' and obj['c'][0] == 'html':
p = parse_citation(obj)
if p.endtag == object_hook.open_cite_tag:
object_hook.open_cite_tag = ''
return {'t': 'Str', 'c': ''} # Object is replaced by empty string
if obj.get('t') == 'RawBlock' and obj['c'][0] == 'latex':
obj['t'] = 'Para'
obj['c'] = [{
't': 'Math',
'c': [
{'t': 'DisplayMath', 'c': []},
# Special marker characters are removed below:
'\x0e:nowrap:\x0f\n\n' + obj['c'][1],
]
}]
elif obj.get('t') == 'RawInline' and obj['c'][0] == 'tex':
obj = {'t': 'RawInline',
'c': ['rst', ':nbsphinx-math:`{}`'.format(obj['c'][1])]}
elif obj.get('t') == 'RawInline' and obj['c'][0] == 'html':
p = parse_citation(obj)
if p.starttag:
object_hook.open_cite_tag = p.starttag
if p.cite:
obj = {'t': 'RawInline', 'c': ['rst', p.cite]}
if not p.starttag and not p.cite:
p = parse_img(obj)
if p.obj:
obj = p.obj
object_hook.image_definitions.append(p.definition)
return obj
object_hook.open_cite_tag = ''
object_hook.image_definitions = []
def filter_func(text):
json_data = json.loads(text, object_hook=object_hook)
return json.dumps(json_data)
input_format = 'markdown'
input_format += '-implicit_figures'
v = nbconvert.utils.pandoc.get_pandoc_version()
if nbconvert.utils.version.check_version(v, '1.13'):
input_format += '-native_divs+raw_html'
rststring = pandoc(text, input_format, 'rst', filter_func=filter_func)
rststring = re.sub(
r'^\n( *)\x0e:nowrap:\x0f$',
r'\1:nowrap:',
rststring,
flags=re.MULTILINE)
rststring += '\n\n'
rststring += '\n'.join(object_hook.image_definitions)
return rststring
def pandoc(source, fmt, to, filter_func=None):
"""Convert a string in format `from` to format `to` via pandoc.
This is based on nbconvert.utils.pandoc.pandoc() and extended to
allow passing a filter function.
"""
def encode(text):
return text if isinstance(text, bytes) else text.encode('utf-8')
def decode(data):
return data.decode('utf-8') if isinstance(data, bytes) else data
nbconvert.utils.pandoc.check_pandoc_version()
v = nbconvert.utils.pandoc.get_pandoc_version()
cmd = ['pandoc']
if nbconvert.utils.version.check_version(v, '2.0'):
# see issue #155
cmd += ['--eol', 'lf']
cmd1 = cmd + ['--from', fmt, '--to', 'json']
cmd2 = cmd + ['--from', 'json', '--to', to]
cmd2 += ['--columns=500'] # Avoid breaks in tables, see issue #240
p = subprocess.Popen(cmd1, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
json_data, _ = p.communicate(encode(source))
if filter_func:
json_data = encode(filter_func(decode(json_data)))
p = subprocess.Popen(cmd2, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, _ = p.communicate(json_data)
return decode(out).rstrip('\n')
def _extract_gallery_or_toctree(cell):
"""Extract links from Markdown cell and create gallery/toctree."""
# If both are available, "gallery" takes precedent
if 'nbsphinx-gallery' in cell.metadata:
lines = ['.. nbgallery::']
options = cell.metadata['nbsphinx-gallery']
elif 'nbsphinx-gallery' in cell.metadata.get('tags', []):
lines = ['.. nbgallery::']
options = {}
elif 'nbsphinx-toctree' in cell.metadata:
lines = ['.. toctree::']
options = cell.metadata['nbsphinx-toctree']
elif 'nbsphinx-toctree' in cell.metadata.get('tags', []):
lines = ['.. toctree::']
options = {}
else:
assert False
try:
for option, value in options.items():
if value is True:
lines.append(':{}:'.format(option))
elif value is False:
pass
else:
lines.append(':{}: {}'.format(option, value))
except AttributeError:
raise ValueError(
'invalid nbsphinx-gallery/nbsphinx-toctree option: {!r}'
.format(options))
text = nbconvert.filters.markdown2rst(cell.source)
settings = docutils.frontend.OptionParser(
components=(rst.Parser,)).get_default_values()
node = docutils.utils.new_document('gallery_or_toctree', settings)
parser = rst.Parser()
parser.parse(text, node)
if 'caption' not in options:
for sec in node.traverse(docutils.nodes.section):
assert sec.children
assert isinstance(sec.children[0], docutils.nodes.title)
title = sec.children[0].astext()
lines.append(':caption: ' + title)
break
lines.append('') # empty line
for ref in node.traverse(docutils.nodes.reference):
lines.append(ref.astext().replace('\n', '') +
' <' + unquote(ref.get('refuri')) + '>')
return '\n '.join(lines)
def _get_empty_lines(text):
"""Get number of empty lines before and after code."""
before = len(text) - len(text.lstrip('\n'))
after = len(text) - len(text.strip('\n')) - before
return before, after
def _get_output_type(output):
"""Choose appropriate output data types for HTML and LaTeX."""
if output.output_type == 'stream':
html_datatype = latex_datatype = 'text/plain'
text = output.text
output.data = {'text/plain': text[:-1] if text.endswith('\n') else text}
elif output.output_type == 'error':
html_datatype = latex_datatype = 'text/plain'
output.data = {'text/plain': '\n'.join(output.traceback)}
else:
for datatype in DISPLAY_DATA_PRIORITY_HTML:
if datatype in output.data:
html_datatype = datatype
break
else:
html_datatype = ', '.join(output.data.keys())
for datatype in DISPLAY_DATA_PRIORITY_LATEX:
if datatype in output.data:
latex_datatype = datatype
break
else:
latex_datatype = ', '.join(output.data.keys())
return html_datatype, latex_datatype
def _local_file_from_reference(node, document):
"""Get local file path from reference and detect fragment identifier."""
# NB: Anonymous hyperlinks must be already resolved at this point!
refuri = node.get('refuri')
if not refuri:
refname = node.get('refname')
if refname:
refid = document.nameids.get(refname)
else:
# NB: This can happen for anonymous hyperlinks
refid = node.get('refid')
target = document.ids.get(refid)
if not target:
# No corresponding target, Sphinx may warn later
return '', ''
refuri = target.get('refuri')
if not refuri:
# Target doesn't have URI
return '', ''
if '://' in refuri:
# Not a local link
return '', ''
elif refuri.startswith('#') or refuri.startswith('mailto:'):
# Not a local link
return '', ''
# NB: We look for "fragment identifier" before unquoting
match = re.match(r'^([^#]*)(#.*)$', refuri)
if match:
filename = unquote(match.group(1))
# NB: The "fragment identifier" is not unquoted
fragment = match.group(2)
else:
filename = unquote(refuri)
fragment = ''
return filename, fragment
class RewriteLocalLinks(docutils.transforms.Transform):
"""Turn links to source files into ``:doc:``/``:ref:`` links.
Links to subsections are possible with ``...#Subsection-Title``.
These links use the labels created by CreateSectionLabels.
Links to subsections use ``:ref:``, links to whole source files use
``:doc:``. Latter can be useful if you have an ``index.rst`` but
also want a distinct ``index.ipynb`` for use with Jupyter.
In this case you can use such a link in a notebook::
[Back to main page](index.ipynb)
In Jupyter, this will create a "normal" link to ``index.ipynb``, but
in the files generated by Sphinx, this will become a link to the
main page created from ``index.rst``.
"""
default_priority = 500 # After AnonymousHyperlinks (440)
def apply(self):
env = self.document.settings.env
for node in self.document.traverse(docutils.nodes.reference):
filename, fragment = _local_file_from_reference(
node, self.document)
if not filename:
continue
for s in env.config.source_suffix:
if filename.lower().endswith(s.lower()):
assert len(s) > 0
target = filename[:-len(s)]
suffix = filename[-len(s):]
if fragment:
target_ext = suffix + fragment
reftype = 'ref'
else:
target_ext = ''
reftype = 'doc'
break
else:
continue # Not a link to a potential Sphinx source file
target_docname = nbconvert.filters.posix_path(os.path.normpath(
os.path.join(os.path.dirname(env.docname), target)))
if target_docname in env.found_docs:
reftarget = '/' + target_docname + target_ext
if reftype == 'ref':
reftarget = reftarget.lower()
linktext = node.astext()
xref = sphinx.addnodes.pending_xref(
reftype=reftype, reftarget=reftarget, refdomain='std',
refwarn=True, refexplicit=True, refdoc=env.docname)
xref += docutils.nodes.Text(linktext, linktext)
node.replace_self(xref)
else:
# NB: This is a link to an ignored (via exclude_patterns)
# source file.
pass
class CreateNotebookSectionAnchors(docutils.transforms.Transform):
"""Create section anchors for Jupyter notebooks.
Note: Sphinx lower-cases the HTML section IDs, Jupyter doesn't.
This transform creates anchors in the Jupyter style.
"""
default_priority = 200 # Before CreateSectionLabels (250)
def apply(self):
all_ids = set()
for section in self.document.traverse(docutils.nodes.section):
title = section.children[0].astext()
link_id = title.replace(' ', '-')
if link_id in all_ids:
# Avoid duplicated anchors on the same page
continue
all_ids.add(link_id)
section['ids'] = [link_id]
if not all_ids:
logger.warning(
'Each notebook should have at least one section title',
location=self.document[0],
type='nbsphinx', subtype='notebooktitle')
class CreateSectionLabels(docutils.transforms.Transform):
"""Make labels for each document and each section thereof.
These labels are referenced in RewriteLocalLinks but can also be
used manually with ``:ref:``.
"""
default_priority = 250 # Before references.PropagateTargets (260)
def apply(self):
env = self.document.settings.env
file_ext = env.doc2path(env.docname, base=None)[len(env.docname):]
i_still_have_to_create_the_document_label = True
for section in self.document.traverse(docutils.nodes.section):
assert section.children
assert isinstance(section.children[0], docutils.nodes.title)
title = section.children[0].astext()
link_id = section['ids'][0]
label = '/' + env.docname + file_ext + '#' + link_id
label = label.lower()
env.domaindata['std']['labels'][label] = (
env.docname, link_id, title)
env.domaindata['std']['anonlabels'][label] = (
env.docname, link_id)
# Create a label for the whole document using the first section:
if i_still_have_to_create_the_document_label:
label = '/' + env.docname.lower() + file_ext
env.domaindata['std']['labels'][label] = (
env.docname, '', title)
env.domaindata['std']['anonlabels'][label] = (
env.docname, '')
i_still_have_to_create_the_document_label = False
class CreateDomainObjectLabels(docutils.transforms.Transform):
"""Create labels for domain-specific object signatures."""
default_priority = 250 # About the same as CreateSectionLabels
def apply(self):
env = self.document.settings.env
file_ext = env.doc2path(env.docname, base=None)[len(env.docname):]
for sig in self.document.traverse(sphinx.addnodes.desc_signature):
try:
title = sig['ids'][0]
except IndexError:
# Object has same name as another, so skip it
continue
link_id = title.replace(' ', '-')
sig['ids'] = [link_id]
label = '/' + env.docname + file_ext + '#' + link_id
label = label.lower()
env.domaindata['std']['labels'][label] = (
env.docname, link_id, title)
env.domaindata['std']['anonlabels'][label] = (
env.docname, link_id)
class ReplaceAlertDivs(docutils.transforms.Transform):
"""Replace certain <div> elements with AdmonitionNode containers.
This is a quick-and-dirty work-around until a proper
Mardown/CommonMark extension for note/warning boxes is available.
"""
default_priority = 500 # Doesn't really matter
_start_re = re.compile(
r'\s*<div\s*class\s*=\s*(?P<q>"|\')([a-z\s-]*)(?P=q)\s*>\s*\Z',
flags=re.IGNORECASE)
_class_re = re.compile(r'\s*alert\s*alert-(info|warning)\s*\Z')
_end_re = re.compile(r'\s*</div\s*>\s*\Z', flags=re.IGNORECASE)
def apply(self):
start_tags = []
for node in self.document.traverse(docutils.nodes.raw):
if node['format'] != 'html':
continue
start_match = self._start_re.match(node.astext())
if not start_match:
continue
class_match = self._class_re.match(start_match.group(2))
if not class_match:
continue
admonition_class = class_match.group(1)
if admonition_class == 'info':
admonition_class = 'note'
start_tags.append((node, admonition_class))
# Reversed order to allow nested <div> elements:
for node, admonition_class in reversed(start_tags):
content = []
for sibling in node.traverse(include_self=False, descend=False,
siblings=True, ascend=False):
end_tag = (isinstance(sibling, docutils.nodes.raw) and
sibling['format'] == 'html' and
self._end_re.match(sibling.astext()))
if end_tag:
admonition_node = AdmonitionNode(
classes=['admonition', admonition_class])
admonition_node.extend(content)
parent = node.parent
parent.replace(node, admonition_node)
for n in content:
parent.remove(n)
parent.remove(sibling)
break
else:
content.append(sibling)
class CopyLinkedFiles(docutils.transforms.Transform):
"""Mark linked (local) files to be copied to the HTML output."""
default_priority = 600 # After RewriteLocalLinks
def apply(self):
env = self.document.settings.env
for node in self.document.traverse(docutils.nodes.reference):
filename, fragment = _local_file_from_reference(
node, self.document)
if not filename:
continue # Not a local link
relpath = filename + fragment
file = os.path.normpath(
os.path.join(os.path.dirname(env.docname), relpath))
if not os.path.isfile(os.path.join(env.srcdir, file)):
logger.warning(
'File not found: %r', file, location=node,
type='nbsphinx', subtype='localfile')
continue # Link is ignored
elif file.startswith('..'):
logger.warning(
'Link outside source directory: %r', file, location=node,
type='nbsphinx', subtype='localfile')
continue # Link is ignored
env.nbsphinx_files.setdefault(env.docname, []).append(file)
class ForceEquations(docutils.transforms.Transform):
"""Unconditionally enable equations on notebooks.
Except if ``nbsphinx_assume_equations`` is set to ``False``.
"""
default_priority = 900 # after checking for equations in MathDomain
def apply(self):
env = self.document.settings.env
if env.config.nbsphinx_assume_equations:
env.get_domain('math').data['has_equations'][env.docname] = True
class GetSizeFromImages(
sphinx.transforms.post_transforms.images.BaseImageConverter):
"""Get size from images and store it as node attributes.
This is only done for LaTeX output.
"""
# After ImageDownloader (100) and DataURIExtractor (150):
default_priority = 200
def match(self, node):
return self.app.builder.format == 'latex'
def handle(self, node):
if 'width' not in node and 'height' not in node:
srcdir = os.path.dirname(self.env.doc2path(self.env.docname))
image_path = os.path.normpath(os.path.join(srcdir, node['uri']))
size = sphinx.util.images.get_image_size(image_path)
if size is not None:
node['width'], node['height'] = map(str, size)
original_toctree_resolve = sphinx.environment.adapters.toctree.TocTree.resolve
def patched_toctree_resolve(self, docname, builder, toctree, *args, **kwargs):
"""Method for monkey-patching Sphinx's TocTree adapter.
The list of section links is never shown, regardless of the
``:hidden:`` option.
However, this option can still be used to control whether the
section links are shown in higher-level tables of contents.
"""
gallery = toctree.get('nbsphinx_gallery', False)
if gallery:
toctree = toctree.copy()
toctree['hidden'] = False
node = original_toctree_resolve(
self, docname, builder, toctree, *args, **kwargs)
if not gallery or node is None:
return node
if isinstance(node[0], docutils.nodes.caption):
del node[1:]
else:
del node[:]
return node
def config_inited(app, config):
if '.ipynb' not in config.source_suffix:
app.add_source_suffix('.ipynb', 'jupyter_notebook')
for suffix in config.nbsphinx_custom_formats:
app.add_source_suffix(suffix, 'jupyter_notebook')
if '**.ipynb_checkpoints' not in config.exclude_patterns:
config.exclude_patterns.append('**.ipynb_checkpoints')
# Make sure require.js is loaded after all other extensions,
# see https://github.com/spatialaudio/nbsphinx/issues/409
app.connect('builder-inited', load_requirejs)
# http://docs.mathjax.org/en/v3.1-latest/options/document.html
# http://docs.mathjax.org/en/v2.7-latest/options/preprocessors/tex2jax.html
mathjax_inline_math = [['$', '$'], ['\\(', '\\)']]
mathjax_ignore_class = (
'tex2jax_ignore' # MathJax 2 default
'|'
'mathjax_ignore' # Mathjax 3 default
'|'
'document' # Main page content
)
mathjax_process_class = (
'tex2jax_process' # MathJax 2 default
'|'
'mathjax_process' # Mathjax 3 default
'|'
'math' # Used by Sphinx
'|'
'output_area' # Jupyter code cells
)
# See also https://github.com/sphinx-doc/sphinx/pull/5504
if hasattr(config, 'mathjax3_config') and config.mathjax2_config is None:
# NB: If mathjax_path is used in Sphinx >= 4 to load MathJax v2,
# this only works if mathjax_config or mathjax2_config is specified.
if config.mathjax3_config is None:
config.mathjax3_config = {}
mathjax3_config = config.mathjax3_config
tex = {
'inlineMath': mathjax_inline_math,
'processEscapes': True,
}
tex.update(mathjax3_config.get('tex', {}))
mathjax3_config['tex'] = tex
options = {
'ignoreHtmlClass': mathjax_ignore_class,
'processHtmlClass': mathjax_process_class,
}
options.update(mathjax3_config.get('options', {}))
mathjax3_config['options'] = options
else:
if hasattr(config, 'mathjax2_config'):
# Sphinx >= 4.0
if config.mathjax2_config is None:
config.mathjax2_config = {}
mathjax2_config = config.mathjax2_config
else:
# Sphinx < 4.0
if config.mathjax_config is None:
config.mathjax_config = {}
mathjax2_config = config.mathjax_config
tex2jax = {
'inlineMath': mathjax_inline_math,
'processEscapes': True,
'ignoreClass': mathjax_ignore_class,
'processClass': mathjax_process_class,
}
tex2jax.update(mathjax2_config.get('tex2jax', {}))
mathjax2_config['tex2jax'] = tex2jax
def load_requirejs(app):
config = app.config
if config.nbsphinx_requirejs_path is None:
config.nbsphinx_requirejs_path = 'https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js'
if config.nbsphinx_requirejs_options is None:
config.nbsphinx_requirejs_options = {
'integrity': 'sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=',
'crossorigin': 'anonymous',
}
if config.nbsphinx_requirejs_path:
# TODO: Add only on pages created from notebooks?
app.add_js_file(
config.nbsphinx_requirejs_path,
**config.nbsphinx_requirejs_options)
def builder_inited(app):
env = app.env
env.settings['line_length_limit'] = 100_000_000
env.nbsphinx_notebooks = {}
env.nbsphinx_files = {}
if not hasattr(env, 'nbsphinx_thumbnails'):
env.nbsphinx_thumbnails = {}
env.nbsphinx_widgets = set()
env.nbsphinx_auxdir = os.path.join(env.doctreedir, 'nbsphinx')
sphinx.util.ensuredir(env.nbsphinx_auxdir)
def env_merge_info(app, env, docnames, other):
env.nbsphinx_notebooks.update(other.nbsphinx_notebooks)
env.nbsphinx_files.update(other.nbsphinx_files)
env.nbsphinx_thumbnails.update(other.nbsphinx_thumbnails)
env.nbsphinx_widgets.update(other.nbsphinx_widgets)
def env_purge_doc(app, env, docname):
"""Remove list of local files for a given document."""
try:
del env.nbsphinx_notebooks[docname]
except KeyError:
pass
try:
del env.nbsphinx_files[docname]
except KeyError:
pass
try:
del env.nbsphinx_thumbnails[docname]
except KeyError:
pass
env.nbsphinx_widgets.discard(docname)
def html_page_context(app, pagename, templatename, context, doctree):
"""Add CSS string to HTML pages that contain code cells."""
style = ''
if doctree and doctree.get('nbsphinx_include_css'):
style += CSS_STRING % app.config
if doctree and app.config.html_theme in (
'sphinx_rtd_theme',
'julia',
'dask_sphinx_theme',
):
style += CSS_STRING_READTHEDOCS
if doctree and app.config.html_theme.endswith('cloud'):
style += CSS_STRING_CLOUD
if style:
context['body'] = '\n<style>' + style + '</style>\n' + context['body']
def html_collect_pages(app):
"""This event handler is abused to copy local files around."""
files = set()
for file_list in app.env.nbsphinx_files.values():
files.update(file_list)
status_iterator = sphinx.util.status_iterator
for file in status_iterator(files, 'copying linked files... ',
sphinx.util.console.brown, len(files)):
target = os.path.join(app.builder.outdir, file)
sphinx.util.ensuredir(os.path.dirname(target))
try:
sphinx.util.copyfile(os.path.join(app.env.srcdir, file), target)
except OSError as err:
logger.warning(
'Cannot copy local file %r: %s', file, err,
type='nbsphinx', subtype='localfile')
notebooks = app.env.nbsphinx_notebooks.values()
for notebook in status_iterator(
notebooks, 'copying notebooks ... ',
'brown', len(notebooks)):
sphinx.util.copyfile(
os.path.join(app.env.nbsphinx_auxdir, notebook),
os.path.join(app.builder.outdir, notebook))
return [] # No new HTML pages are created
def env_updated(app, env):
widgets_path = app.config.nbsphinx_widgets_path
if widgets_path is None:
if env.nbsphinx_widgets:
try:
from ipywidgets.embed import DEFAULT_EMBED_REQUIREJS_URL
except ImportError:
logger.warning(
'nbsphinx_widgets_path not given '
'and ipywidgets module unavailable',
type='nbsphinx', subtype='ipywidgets')
else:
widgets_path = DEFAULT_EMBED_REQUIREJS_URL
else:
widgets_path = ''
if widgets_path:
app.add_js_file(widgets_path, **app.config.nbsphinx_widgets_options)
def doctree_resolved(app, doctree, fromdocname):
# Replace GalleryToc with toctree + GalleryNode
for node in doctree.traverse(GalleryToc):
toctree_wrapper, = node
if (len(toctree_wrapper) != 1 or
not isinstance(toctree_wrapper[0], sphinx.addnodes.toctree)):
# This happens for LaTeX output
node.replace_self(node.children)
continue
toctree, = toctree_wrapper
entries = []
for title, doc in toctree['entries']:
if doc in toctree['includefiles']:
if title is None:
title = app.env.titles[doc].astext()
uri = app.builder.get_relative_uri(fromdocname, doc)
base = sphinx.util.osutil.relative_uri(
app.builder.get_target_uri(fromdocname), '')
# NB: This is how Sphinx implements the "html_sidebars"
# config value in StandaloneHTMLBuilder.add_sidebars()
def has_wildcard(pattern):
return any(char in pattern for char in '*?[')
matched = None
conf_py_thumbnail = None
conf_py_thumbnails = app.env.config.nbsphinx_thumbnails.items()
for pattern, candidate in conf_py_thumbnails:
if patmatch(doc, pattern):
if matched:
if has_wildcard(pattern):
# warn if both patterns contain wildcards
if has_wildcard(matched):
logger.warning(
'page %s matches two patterns in '
'nbsphinx_thumbnails: %r and %r',
doc, matched, pattern,
type='nbsphinx', subtype='thumbnail')
# else the already matched pattern is more
# specific than the present one, because it
# contains no wildcard
continue
matched = pattern
conf_py_thumbnail = candidate
thumbnail = app.env.nbsphinx_thumbnails.get(doc, {})
tooltip = thumbnail.get('tooltip', '')
filename = thumbnail.get('filename', '')
if filename is _BROKEN_THUMBNAIL:
filename = os.path.join(
base, '_static', 'broken_example.png')
elif filename:
filename = os.path.join(
base, app.builder.imagedir, filename)
elif conf_py_thumbnail:
# NB: Settings from conf.py can be overwritten in notebook
filename = os.path.join(base, conf_py_thumbnail)
else:
filename = os.path.join(base, '_static', 'no_image.png')
entries.append((title, uri, filename, tooltip))
else:
logger.warning(
'External links are not supported in gallery: %s', doc,
location=fromdocname, type='nbsphinx', subtype='gallery')
gallery = GalleryNode()
gallery['entries'] = entries
toctree['nbsphinx_gallery'] = True
toctree_wrapper[:] = toctree,
node.replace_self([toctree_wrapper, gallery])
# NB: Further processing happens in patched_toctree_resolve()
def depart_codearea_html(self, node):
"""Add empty lines before and after the code."""
text = self.body[-1]
text = text.replace('<pre>',
'<pre>' + '<br/>' * node.get('empty-lines-before', 0))
text = text.replace('</pre>',
'<br/>' * node.get('empty-lines-after', 0) + '</pre>')
self.body[-1] = text
def visit_codearea_latex(self, node):
self.pushbody([]) # See popbody() below
def depart_codearea_latex(self, node):
"""Some changes to code blocks.
* Change frame color and background color
* Add empty lines before and after the code
* Add prompt
"""
lines = ''.join(self.popbody()).strip('\n').split('\n')
out = []
out.append('')
out.append('{') # Start a scope for colors
if 'nbinput' in node.parent['classes']:
promptcolor = 'nbsphinxin'
out.append(r'\sphinxsetup{VerbatimColor={named}{nbsphinx-code-bg}}')
else:
out.append(r"""
\kern-\sphinxverbatimsmallskipamount\kern-\baselineskip
\kern+\FrameHeightAdjust\kern-\fboxrule
\vspace{\nbsphinxcodecellspacing}
""")
promptcolor = 'nbsphinxout'
if node['stderr']:
out.append(r'\sphinxsetup{VerbatimColor={named}{nbsphinx-stderr}}')
else:
out.append(r'\sphinxsetup{VerbatimColor={named}{white}}')
out.append(
r'\sphinxsetup{VerbatimBorderColor={named}{nbsphinx-code-border}}')
if lines[0].startswith(r'\fvset{'): # Sphinx >= 1.6.6 and < 1.8.3
out.append(lines[0])
del lines[0]
# Sphinx 4.1.0 added "sphinxuseclass" environments around "sphinxVerbatim"
for begin_verbatim, line in enumerate(lines):
if line.startswith(r'\begin{sphinxVerbatim}'):
break
else:
assert False
for end_verbatim, line in enumerate(reversed(lines)):
if line == r'\end{sphinxVerbatim}':
break
else:
assert False
out.extend(lines[:begin_verbatim + 1])
code_lines = (
[''] * node.get('empty-lines-before', 0) +
lines[begin_verbatim + 1:-end_verbatim - 1] +
[''] * node.get('empty-lines-after', 0)
)
prompt = node['prompt']
if prompt:
prompt = nbconvert.filters.latex.escape_latex(prompt)
prefix = r'\llap{\color{' + promptcolor + '}' + prompt + \
r'\,\hspace{\fboxrule}\hspace{\fboxsep}}'
assert code_lines
code_lines[0] = prefix + code_lines[0]
out.extend(code_lines)
out.extend(lines[-end_verbatim - 1:])
out.append('}') # End of scope for colors
out.append('')
self.body.append('\n'.join(out))
def visit_fancyoutput_latex(self, node):
out = r"""
\hrule height -\fboxrule\relax
\vspace{\nbsphinxcodecellspacing}
"""
prompt = node['prompt']
if prompt:
prompt = nbconvert.filters.latex.escape_latex(prompt)
out += r"""
\savebox\nbsphinxpromptbox[0pt][r]{\color{nbsphinxout}\Verb|\strut{%s}\,|}
""" % (prompt,)
else:
out += r"""
\makeatletter\setbox\nbsphinxpromptbox\box\voidb@x\makeatother
"""
out += r"""
\begin{nbsphinxfancyoutput}
"""
self.body.append(out)
def depart_fancyoutput_latex(self, node):
self.body.append('\n\\end{nbsphinxfancyoutput}\n')
def visit_admonition_html(self, node):
self.body.append(self.starttag(node, 'div'))
if len(node.children) >= 2:
node[0]['classes'].append('admonition-title')
html_theme = self.settings.env.config.html_theme
if html_theme in ('sphinx_rtd_theme', 'julia', 'dask_sphinx_theme'):
node.children[0]['classes'].extend(['fa', 'fa-exclamation-circle'])
def depart_admonition_html(self, node):
self.body.append('</div>\n')
def visit_admonition_latex(self, node):
# See http://tex.stackexchange.com/q/305898/:
self.body.append(
'\n\\begin{sphinxadmonition}{' + node['classes'][1] + '}{}\\unskip')
def depart_admonition_latex(self, node):
self.body.append('\\end{sphinxadmonition}\n')
def visit_admonition_text(self, node):
self.new_state(0)
def depart_admonition_text(self, node):
self.end_state()
def depart_gallery_html(self, node):
for title, uri, filename, tooltip in node['entries']:
if tooltip:
tooltip = ' tooltip="{}"'.format(html.escape(tooltip))
self.body.append("""\
<div class="sphx-glr-thumbcontainer"{tooltip}>
<div class="figure align-center">
<img alt="thumbnail" src="{filename}" />
<p class="caption">
<span class="caption-text">
<a class="reference internal" href="{uri}">
<span class="std std-ref">{title}</span>
</a>
</span>
</p>
</div>
</div>
""".format(
uri=html.escape(uri),
title=html.escape(title),
tooltip=tooltip,
filename=html.escape(filename),
))
self.body.append('<div class="sphx-glr-clear"></div>')
def do_nothing(self, node):
pass
def setup(app):
"""Initialize Sphinx extension."""
app.add_source_parser(NotebookParser)
app.add_config_value('nbsphinx_execute', 'auto', rebuild='env')
app.add_config_value('nbsphinx_kernel_name', '', rebuild='env')
app.add_config_value('nbsphinx_execute_arguments', [], rebuild='env')
app.add_config_value('nbsphinx_allow_errors', False, rebuild='')
app.add_config_value('nbsphinx_timeout', None, rebuild='')
app.add_config_value('nbsphinx_codecell_lexer', 'none', rebuild='env')
app.add_config_value('nbsphinx_prompt_width', '4.5ex', rebuild='html')
app.add_config_value('nbsphinx_responsive_width', '540px', rebuild='html')
app.add_config_value('nbsphinx_prolog', None, rebuild='env')
app.add_config_value('nbsphinx_epilog', None, rebuild='env')
app.add_config_value('nbsphinx_input_prompt', '[%s]:', rebuild='env')
app.add_config_value('nbsphinx_output_prompt', '[%s]:', rebuild='env')
app.add_config_value('nbsphinx_custom_formats', {}, rebuild='env')
# Default value is set in config_inited():
app.add_config_value('nbsphinx_requirejs_path', None, rebuild='html')
# Default value is set in config_inited():
app.add_config_value('nbsphinx_requirejs_options', None, rebuild='html')
# This will be updated in env_updated():
app.add_config_value('nbsphinx_widgets_path', None, rebuild='html')
app.add_config_value('nbsphinx_widgets_options', {}, rebuild='html')
app.add_config_value('nbsphinx_thumbnails', {}, rebuild='html')
app.add_config_value('nbsphinx_assume_equations', True, rebuild='env')
app.add_directive('nbinput', NbInput)
app.add_directive('nboutput', NbOutput)
app.add_directive('nbinfo', NbInfo)
app.add_directive('nbwarning', NbWarning)
app.add_directive('nbgallery', NbGallery)
app.add_node(CodeAreaNode,
html=(do_nothing, depart_codearea_html),
latex=(visit_codearea_latex, depart_codearea_latex),
text=(do_nothing, do_nothing))
app.add_node(FancyOutputNode,
html=(do_nothing, do_nothing),
latex=(visit_fancyoutput_latex, depart_fancyoutput_latex),
text=(do_nothing, do_nothing))
app.add_node(AdmonitionNode,
html=(visit_admonition_html, depart_admonition_html),
latex=(visit_admonition_latex, depart_admonition_latex),
text=(visit_admonition_text, depart_admonition_text))
app.add_node(GalleryNode,
html=(do_nothing, depart_gallery_html),
latex=(do_nothing, do_nothing),
text=(do_nothing, do_nothing))
app.connect('builder-inited', builder_inited)
app.connect('config-inited', config_inited)
app.connect('html-page-context', html_page_context)
app.connect('html-collect-pages', html_collect_pages)
app.connect('env-purge-doc', env_purge_doc)
app.connect('env-updated', env_updated)
app.connect('doctree-resolved', doctree_resolved)
app.connect('env-merge-info', env_merge_info)
app.add_transform(CreateSectionLabels)
app.add_transform(CreateDomainObjectLabels)
app.add_transform(RewriteLocalLinks)
app.add_post_transform(GetSizeFromImages)
# Make docutils' "code" directive (generated by markdown2rst/pandoc)
# behave like Sphinx's "code-block",
# see https://github.com/sphinx-doc/sphinx/issues/2155:
rst.directives.register_directive('code', sphinx.directives.code.CodeBlock)
# Add LaTeX definitions to preamble
latex_elements = app.config._raw_config.setdefault('latex_elements', {})
latex_elements['preamble'] = '\n'.join([
LATEX_PREAMBLE,
latex_elements.get('preamble', ''),
])
# Monkey-patch Sphinx TocTree adapter
sphinx.environment.adapters.toctree.TocTree.resolve = \
patched_toctree_resolve
return {
'version': __version__,
'parallel_read_safe': True,
'parallel_write_safe': True,
'env_version': 4,
}
| mit |
shibafu528/yukari-exvoice | build_config.rb | 3876 | # disable pkg-config
ENV['PKG_CONFIG_LIBDIR'] = ''
MRuby::Lockfile.disable
configure = -> (conf) {
enable_debug
# default.gembox without commands
conf.gem :core => 'mruby-metaprog'
conf.gem :core => 'mruby-io'
conf.gem :core => 'mruby-pack'
conf.gem :core => 'mruby-sprintf'
conf.gem :core => 'mruby-print'
conf.gem :core => 'mruby-math'
conf.gem :core => 'mruby-time'
conf.gem :core => 'mruby-struct'
conf.gem :core => 'mruby-compar-ext'
conf.gem :core => 'mruby-enum-ext'
conf.gem :core => 'mruby-string-ext'
conf.gem :core => 'mruby-numeric-ext'
conf.gem :core => 'mruby-array-ext'
conf.gem :core => 'mruby-hash-ext'
conf.gem :core => 'mruby-range-ext'
conf.gem :core => 'mruby-proc-ext'
conf.gem :core => 'mruby-symbol-ext'
conf.gem :core => 'mruby-random'
conf.gem :core => 'mruby-object-ext'
conf.gem :core => 'mruby-objectspace'
conf.gem :core => 'mruby-fiber'
conf.gem :core => 'mruby-enumerator'
conf.gem :core => 'mruby-enum-lazy'
conf.gem :core => 'mruby-toplevel-ext'
conf.gem :core => 'mruby-kernel-ext'
conf.gem :core => 'mruby-class-ext'
conf.gem :core => 'mruby-error'
conf.gem :core => 'mruby-rational'
conf.gem :core => 'mruby-complex'
conf.gem :core => 'mruby-compiler'
# exvoice dependencies
# libyamlをsubmoduleでcheckoutするようになったあたりから上手くクロスコンパイルできない
conf.gem :github => 'mrbgems/mruby-yaml', :checksum_hash => '0606652a6e99d902cd3101cf2d757a7c0c37a7fd'
conf.gem :github => 'shibafu528/mruby-mix', :path => 'mruby-mix'
conf.gem :github => 'shibafu528/mruby-mix', :path => 'mruby-mix-miquire-fs'
conf.gem :github => 'shibafu528/mruby-mix', :path => 'mruby-mix-polyfill-gtk'
conf.gem :github => 'shibafu528/mruby-mix', :path => 'mruby-mix-command-conditions'
conf.gem :github => 'shibafu528/mruby-mix', :path => 'mruby-mix-twitter-models'
conf.gem :github => 'matsumoto-r/mruby-sleep'
conf.gem :github => 'mattn/mruby-json'
conf.gem :github => 'shibafu528/mruby-thread', :branch => 'patch-android'
conf.gem :github => 'iij/mruby-dir'
conf.gem :github => 'iij/mruby-require'
conf.gem :github => 'ksss/mruby-singleton'
conf.cc.defines << %w(MRB_INT64 MRB_UTF8_STRING)
conf.cc.flags << '-std=gnu99'
# expose libyaml.a (mruby-yaml)
file conf.libfile("#{conf.build_dir}/lib/libyaml") => conf.libfile("#{conf.build_dir}/lib/libmruby") do |t|
cp Dir.glob(File.join(conf.build_dir, 'mrbgems/**/libyaml.a')).first, t.name
end
task :all => conf.libfile("#{conf.build_dir}/lib/libyaml")
}
MRuby::Build.new do |conf|
if ENV['VisualStudioVersion'] || ENV['VSINSTALLDIR']
toolchain :visualcpp
else
toolchain :gcc
end
conf.gem :core => 'mruby-bin-mirb'
conf.gem :core => 'mruby-bin-mruby'
conf.gem :core => 'mruby-bin-strip'
enable_debug
instance_exec conf, &configure
end
MRuby::CrossBuild.new('armv7-linux-androideabi') do |conf|
toolchain :android, arch: 'armeabi-v7a', platform: 'android-14', toolchain: :gcc
conf.host_target = 'armv7-linux-androideabi'
conf.build_target = 'x86_64-pc-linux-gnu'
instance_exec conf, &configure
end
MRuby::CrossBuild.new('aarch64-linux-androideabi') do |conf|
toolchain :android, arch: 'arm64-v8a', platform: 'android-21', toolchain: :gcc
conf.host_target = 'aarch64-linux-androideabi'
conf.build_target = 'x86_64-pc-linux-gnu'
instance_exec conf, &configure
end
# MRuby::CrossBuild.new('x86-linux-androideabi') do |conf|
# toolchain :android, arch: 'x86', platform: 'android-14', toolchain: :gcc
# conf.host_target = 'x86-linux-androideabi'
# conf.build_target = 'x86_64-pc-linux-gnu'
# instance_exec conf, &configure
# end
# MRuby::CrossBuild.new('x86_64-linux-androideabi') do |conf|
# toolchain :android, arch: 'x86_64', platform: 'android-21', toolchain: :gcc
# instance_exec conf, &configure
# end
| mit |
cripplet/SE-800 | src/classes/event.cc | 261 | #include "event.h"
#include "../engines/physics/projectile.h"
Event::Event(Projectile *obj, int event_type) : obj(obj), event_type(event_type) {
}
int Event::get_id() {
return this->obj->get_id();
}
int Event::get_event_type() {
return this->event_type;
}
| mit |
zestyr/lbry | lbrynet/core/StreamDescriptor.py | 9680 | from collections import defaultdict
import json
import logging
from twisted.internet import threads, defer
from lbrynet.core.client.StandaloneBlobDownloader import StandaloneBlobDownloader
from lbrynet.core.Error import UnknownStreamTypeError, InvalidStreamDescriptorError
log = logging.getLogger(__name__)
class StreamDescriptorReader(object):
"""Classes which derive from this class read a stream descriptor file return
a dictionary containing the fields in the file"""
def __init__(self):
pass
def _get_raw_data(self):
"""This method must be overridden by subclasses. It should return a deferred
which fires with the raw data in the stream descriptor"""
pass
def get_info(self):
"""Return the fields contained in the file"""
d = self._get_raw_data()
d.addCallback(json.loads)
return d
class PlainStreamDescriptorReader(StreamDescriptorReader):
"""Read a stream descriptor file which is not a blob but a regular file"""
def __init__(self, stream_descriptor_filename):
StreamDescriptorReader.__init__(self)
self.stream_descriptor_filename = stream_descriptor_filename
def _get_raw_data(self):
def get_data():
with open(self.stream_descriptor_filename) as file_handle:
raw_data = file_handle.read()
return raw_data
return threads.deferToThread(get_data)
class BlobStreamDescriptorReader(StreamDescriptorReader):
"""Read a stream descriptor file which is a blob"""
def __init__(self, blob):
StreamDescriptorReader.__init__(self)
self.blob = blob
def _get_raw_data(self):
def get_data():
f = self.blob.open_for_reading()
if f is not None:
raw_data = f.read()
self.blob.close_read_handle(f)
return raw_data
else:
raise ValueError("Could not open the blob for reading")
return threads.deferToThread(get_data)
class StreamDescriptorWriter(object):
"""Classes which derive from this class write fields from a dictionary
of fields to a stream descriptor"""
def __init__(self):
pass
def create_descriptor(self, sd_info):
return self._write_stream_descriptor(json.dumps(sd_info))
def _write_stream_descriptor(self, raw_data):
"""This method must be overridden by subclasses to write raw data to
the stream descriptor
"""
pass
class PlainStreamDescriptorWriter(StreamDescriptorWriter):
def __init__(self, sd_file_name):
StreamDescriptorWriter.__init__(self)
self.sd_file_name = sd_file_name
def _write_stream_descriptor(self, raw_data):
def write_file():
log.debug("Writing the sd file to disk")
with open(self.sd_file_name, 'w') as sd_file:
sd_file.write(raw_data)
return self.sd_file_name
return threads.deferToThread(write_file)
class BlobStreamDescriptorWriter(StreamDescriptorWriter):
def __init__(self, blob_manager):
StreamDescriptorWriter.__init__(self)
self.blob_manager = blob_manager
@defer.inlineCallbacks
def _write_stream_descriptor(self, raw_data):
log.debug("Creating the new blob for the stream descriptor")
blob_creator = self.blob_manager.get_blob_creator()
blob_creator.write(raw_data)
log.debug("Wrote the data to the new blob")
sd_hash = yield blob_creator.close()
yield self.blob_manager.creator_finished(blob_creator, should_announce=True)
defer.returnValue(sd_hash)
class StreamMetadata(object):
FROM_BLOB = 1
FROM_PLAIN = 2
def __init__(self, validator, options, factories):
self.validator = validator
self.options = options
self.factories = factories
self.metadata_source = None
self.source_blob_hash = None
self.source_file = None
class StreamDescriptorIdentifier(object):
"""Tries to determine the type of stream described by the stream descriptor using the
'stream_type' field. Keeps a list of StreamDescriptorValidators and StreamDownloaderFactorys
and returns the appropriate ones based on the type of the stream descriptor given
"""
def __init__(self):
# {stream_type: IStreamDescriptorValidator}
self._sd_info_validators = {}
# {stream_type: IStreamOptions
self._stream_options = {}
# {stream_type: [IStreamDownloaderFactory]}
self._stream_downloader_factories = defaultdict(list)
def add_stream_type(self, stream_type, sd_info_validator, stream_options):
"""This is how the StreamDescriptorIdentifier learns about new types of stream descriptors.
There can only be one StreamDescriptorValidator for each type of stream.
@param stream_type: A string representing the type of stream
descriptor. This must be unique to this stream descriptor.
@param sd_info_validator: A class implementing the
IStreamDescriptorValidator interface. This class's
constructor will be passed the raw metadata in the stream
descriptor file and its 'validate' method will then be
called. If the validation step fails, an exception will be
thrown, preventing the stream descriptor from being
further processed.
@param stream_options: A class implementing the IStreamOptions
interface. This class's constructor will be passed the
sd_info_validator object containing the raw metadata from
the stream descriptor file.
@return: None
"""
self._sd_info_validators[stream_type] = sd_info_validator
self._stream_options[stream_type] = stream_options
def add_stream_downloader_factory(self, stream_type, factory):
"""Register a stream downloader factory with the StreamDescriptorIdentifier.
This is how the StreamDescriptorIdentifier determines what
factories may be used to process different stream descriptor
files. There must be at least one factory for each type of
stream added via "add_stream_info_validator".
@param stream_type: A string representing the type of stream
descriptor which the factory knows how to process.
@param factory: An object implementing the IStreamDownloaderFactory interface.
@return: None
"""
self._stream_downloader_factories[stream_type].append(factory)
def _return_metadata(self, options_validator_factories, source_type, source):
validator, options, factories = options_validator_factories
m = StreamMetadata(validator, options, factories)
m.metadata_source = source_type
if source_type == StreamMetadata.FROM_BLOB:
m.source_blob_hash = source
if source_type == StreamMetadata.FROM_PLAIN:
m.source_file = source
return m
def get_metadata_for_sd_file(self, sd_path):
sd_reader = PlainStreamDescriptorReader(sd_path)
d = sd_reader.get_info()
d.addCallback(self._return_options_and_validator_and_factories)
d.addCallback(self._return_metadata, StreamMetadata.FROM_PLAIN, sd_path)
return d
def get_metadata_for_sd_blob(self, sd_blob):
sd_reader = BlobStreamDescriptorReader(sd_blob)
d = sd_reader.get_info()
d.addCallback(self._return_options_and_validator_and_factories)
d.addCallback(self._return_metadata, StreamMetadata.FROM_BLOB, sd_blob.blob_hash)
return d
def _get_factories(self, stream_type):
if not stream_type in self._stream_downloader_factories:
raise UnknownStreamTypeError(stream_type)
return self._stream_downloader_factories[stream_type]
def _get_validator(self, stream_type):
if not stream_type in self._sd_info_validators:
raise UnknownStreamTypeError(stream_type)
return self._sd_info_validators[stream_type]
def _get_options(self, stream_type):
if not stream_type in self._stream_downloader_factories:
raise UnknownStreamTypeError(stream_type)
return self._stream_options[stream_type]
def _return_options_and_validator_and_factories(self, sd_info):
if not 'stream_type' in sd_info:
raise InvalidStreamDescriptorError('No stream_type parameter in stream descriptor.')
stream_type = sd_info['stream_type']
validator = self._get_validator(stream_type)(sd_info)
factories = [f for f in self._get_factories(stream_type) if f.can_download(validator)]
d = validator.validate()
def get_options():
options = self._get_options(stream_type)
return validator, options, factories
d.addCallback(lambda _: get_options())
return d
def download_sd_blob(session, blob_hash, payment_rate_manager, timeout=None):
"""
Downloads a single blob from the network
@param session:
@param blob_hash:
@param payment_rate_manager:
@return: An object of type HashBlob
"""
downloader = StandaloneBlobDownloader(blob_hash,
session.blob_manager,
session.peer_finder,
session.rate_limiter,
payment_rate_manager,
session.wallet,
timeout)
return downloader.download()
| mit |
softwarica/musclefactorygym | application/models/modelImage.php | 1067 | <?php
class ModelImage extends CI_Model{
public function retriveCategory(){
return $this->db->get('tblexcategory');
}
public function saveImage($iname,$icat,$image){
$arr=array(
'iname'=>$iname,
'icat'=>$icat,
'image'=>$image
);
$this->db->insert('tblimage',$arr);
}
public function retriveImage(){
return $this->db->get('tblimage');
}
public function retriveImageById($id){
$this->db->where('id',$id);
return $this->db->get('tblimage');
}
public function updateImage($id,$image){
$arr=array(
'id'=>$id,
'image'=>$image
);
$this->db->where('id',$id);
$this->db->update('tblimage',$arr);
}
public function deleteImage($id){
$this->db->where('id',$id);
$this->db->delete('tblimage');
}
public function updateImageDetails($id,$iname,$icat){
$arr=array(
'id'=>$id,
'iname'=>$iname,
'icat'=>$icat
);
$this->db->where('id',$id);
$this->db->update('tblimage',$arr);
}
public function retriveSearchImage($forsearch){
$this->db->like('iname',$forsearch);
return $this->db->get('tblimage');
}
}
?> | mit |
VertekCorp/ember-materialize | tests/integration/components/em-card-content-test.js | 671 | import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('em-card-content', 'Integration | Component | em card content', {
integration: true
});
test('it renders', function(assert) {
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{em-card-content}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:
this.render(hbs`
{{#em-card-content}}
template block text
{{/em-card-content}}
`);
assert.equal(this.$().text().trim(), 'template block text');
});
| mit |
glas-it/rom-app | src/ar/com/glasit/rom/Helpers/BackendHelper.java | 2222 | package ar.com.glasit.rom.Helpers;
import ar.com.glasit.rom.R;
public class BackendHelper {
private static final String PREF_NAME = "PREFS_BACKEND";
private static final String BASE_URL = "BASE_URL";
private static final String USER = "USER";
private static final String KEY = "KEY";
private static final String APP_TYPE = "APP_TYPE";
private static final String COMPANY = "COMPANY";
private BackendHelper(){}
public static String getBackendUrl(){
String url = ContextHelper.getContextInstance().getString(R.string.backend_url);
String preferedUrl = ContextHelper.getSharedPrefenrece(BackendHelper.PREF_NAME, BackendHelper.BASE_URL);
if (preferedUrl != null && !preferedUrl.isEmpty()) {
return preferedUrl;
}
return url;
}
public static String getCompany(){
return ContextHelper.getSharedPrefenrece(BackendHelper.PREF_NAME, BackendHelper.COMPANY);
}
public static void setCompany(String company){
ContextHelper.putSharedPrefenrece(BackendHelper.PREF_NAME, BackendHelper.COMPANY, company);
}
public static String getSecretKey(){
return ContextHelper.getSharedPrefenrece(BackendHelper.PREF_NAME, BackendHelper.KEY);
}
public static String getLoggedUser(){
return ContextHelper.getSharedPrefenrece(BackendHelper.PREF_NAME, BackendHelper.USER);
}
public static void setBackendUrl(String url) {
ContextHelper.putSharedPrefenrece(BackendHelper.PREF_NAME, BackendHelper.BASE_URL, url);
}
public static void setSecretKey(String key) {
ContextHelper.putSharedPrefenrece(BackendHelper.PREF_NAME, BackendHelper.KEY, key);
}
public static void setAppType(String key) {
ContextHelper.putSharedPrefenrece(BackendHelper.PREF_NAME, BackendHelper.APP_TYPE, key);
}
public static String getAppType(){
return ContextHelper.getSharedPrefenrece(BackendHelper.PREF_NAME, BackendHelper.APP_TYPE);
}
public static void setLoggedUser(String user) {
ContextHelper.putSharedPrefenrece(BackendHelper.PREF_NAME, BackendHelper.USER, user);
}
}
| mit |
YoonHunHee/petplace_server | application/controllers/api/v1/User.php | 5094 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends API_Controller {
function __construct()
{
parent::__construct();
$this->load->model('user_model');
$this->load->library('encrypt');
}
/**
* [authorize description]
* @return [type] [description]
*/
public function login()
{
if($this->checkAccessToken())
{
if($this->checkPost())
{
// set parameters
$email = $this->input->post('email');
$password = $this->input->post('password');
// check parameter
if(!isset($email) || empty($email)) {
$this->json(501, '이메일을 입력해주세요.');
$this->_userSessionReset();
return;
}
if(!isset($password) || empty($password)) {
$this->json(501, '비밀번호를 입력해주세요.');
$this->_userSessionReset();
return;
}
if($this->user_model->is_check($email) != 1) {
$this->json(301, '이미 등록된 이메일주소입니다.');
$this->_userSessionReset();
return;
}
// get user info
$user = $this->user_model->get_email($email);
if($password != $this->encrypt->decode($user->password)) {
$this->json(302, '일치하는 정보가 존재하지 않습니다.');
$this->_userSessionReset();
return;
}
$user_session = array(
'user_email' => $row->email,
'user_nick_name' => $row->nick_name
);
$this->session->set_userdata($user_session);
$this->json(200, 'success');
}
}
}
/**
* [logout description]
* @return [type] [description]
*/
public function logout()
{
$array_items = array('user_email', 'user_nick_name');
$this->session->unset_userdata($array_items);
$this->json(200, 'success');
}
/**
* [_userSessionReset description]
* @return [type] [description]
*/
function _userSessionReset()
{
$array_items = array('user_email', 'user_nick_name');
$this->session->unset_userdata($array_items);
}
/**
* [regist description]
* @return [type] [description]
*/
public function regist()
{
if($this->checkAccessToken())
{
if($this->checkPost())
{
$email = $this->input->post('email');
$nick_name = $this->input->post('nick_name');
$password = $this->input->post('password');
$password_confirm = $this->input->post('password_confirm');
// check parameter
if(!isset($email) || empty($email)) {
$this->json(501, '이메일을 입력해주세요.');
return;
}
if(!isset($nick_name) || empty($nick_name)) {
$this->json(501, '닉네임을 입력해주세요.');
return;
}
if(!isset($password) || empty($password)) {
$this->json(501, '비밀번호를 입력해주세요.');
return;
}
if(!isset($password_confirm) || empty($password_confirm)) {
$this->json(501, '비밀번호확인을 입력해주세요.');
return;
}
if($password != $password_confirm) {
$this->json(501, '비밀번호가 일치하지 않습니다.');
return;
}
if($this->user_model->is_check($email) > 0) {
$this->json(301, '이미 등록된 이메일주소입니다.');
return;
}
$insert['email'] = $email;
$insert['nick_name'] = $nick_name;
$insert['password'] = $this->encrypt->encode($password);
$insert['create_at'] = date('Y-m-d H:i:s', time());
$insert['update_at'] = date('Y-m-d H:i:s', time());
$result = $this->user_model->insert($insert);
if($result) {
//session create
$user = array(
'user_email' => $email,
'user_nick_name' => $nick_name
);
$this->session->set_userdata($user);
$this->json(200, 'success');
return;
} else {
$this->json(900, '죄송합니다. 데이터를 처리할 수 없습니다.');
}
}
}
}
}
| mit |
esteladiaz/esteladiaz.github.io | node_modules/babel-plugin-transform-define/test/0/expected.js | 112 | 'use strict';
var x = 0;
if (!0) {
console.log('Debug info');
}
if (0) {
console.log('Production log');
}
| mit |
zertico/softlayer | lib/softlayer/billing/order.rb | 7662 | module Softlayer
module Billing
class Order < Softlayer::Entity
SERVICE = 'SoftLayer_Billing_Order'
autoload :Cart, 'softlayer/billing/order/cart'
autoload :Item, 'softlayer/billing/order/item'
autoload :Note, 'softlayer/billing/order/note'
autoload :Quote, 'softlayer/billing/order/quote'
autoload :Type, 'softlayer/billing/order/type'
attr_accessor :account_id
attr_accessor :create_date
attr_accessor :id
attr_accessor :impersonating_user_record_id
attr_accessor :modify_date
attr_accessor :order_quote_id
attr_accessor :order_type_id
attr_accessor :presale_event_id
attr_accessor :private_cloud_order_flag
attr_accessor :status
attr_accessor :user_record_id
attr_accessor :core_restricted_item_count
attr_accessor :credit_card_transaction_count
attr_accessor :item_count
attr_accessor :order_top_level_item_count
attr_accessor :paypal_transaction_count
attr_accessor :account
attr_accessor :brand
attr_accessor :cart
attr_accessor :core_restricted_items
attr_accessor :credit_card_transactions
attr_accessor :exchange_rate
attr_accessor :initial_invoice
attr_accessor :items
attr_accessor :order_approval_date
attr_accessor :order_non_server_monthly_amount
attr_accessor :order_server_monthly_amount
attr_accessor :order_top_level_items
attr_accessor :order_total_amount
attr_accessor :order_total_one_time
attr_accessor :order_total_one_time_amount
attr_accessor :order_total_one_time_tax_amount
attr_accessor :order_total_recurring
attr_accessor :order_total_recurring_amount
attr_accessor :order_total_recurring_tax_amount
attr_accessor :order_total_setup_amount
attr_accessor :order_type
attr_accessor :paypal_transactions
attr_accessor :presale_event
attr_accessor :quote
attr_accessor :referral_partner
attr_accessor :upgrade_request_flag
attr_accessor :user_record
def approve_modified_order
request(:approve_modified_order, Boolean)
end
def get_account
request(:get_account, Softlayer::Account)
end
def self.get_all_objects
request(:get_all_objects, Array[Softlayer::Billing::Order])
end
def get_brand
request(:get_brand, Softlayer::Brand)
end
def get_cart
request(:get_cart, Softlayer::Billing::Order::Cart)
end
def get_core_restricted_items
request(:get_core_restricted_items, Array[Softlayer::Billing::Order::Item])
end
def get_credit_card_transactions
request(:get_credit_card_transactions, Array[Softlayer::Billing::Payment::Card::Transaction])
end
def get_exchange_rate
request(:get_exchange_rate, Softlayer::Billing::Currency::ExchangeRate)
end
def get_initial_invoice
request(:get_initial_invoice, Softlayer::Billing::Invoice)
end
def get_items
request(:get_items, Array[Softlayer::Billing::Order::Item])
end
def get_object
request(:get_object, Softlayer::Billing::Order)
end
def get_order_approval_date
request(:get_order_approval_date, DateTime)
end
def get_order_non_server_monthly_amount
request(:get_order_non_server_monthly_amount, Float)
end
def get_order_server_monthly_amount
request(:get_order_server_monthly_amount, Float)
end
def self.get_order_statuses
request(:get_order_statuses, Array[Softlayer::Container::Billing::Order::Status])
end
def get_order_top_level_items
request(:get_order_top_level_items, Array[Softlayer::Billing::Order::Item])
end
def get_order_total_amount
request(:get_order_total_amount, Float)
end
def get_order_total_one_time
request(:get_order_total_one_time, Float)
end
def get_order_total_one_time_amount
request(:get_order_total_one_time_amount, Float)
end
def get_order_total_one_time_tax_amount
request(:get_order_total_one_time_tax_amount, Float)
end
def get_order_total_recurring
request(:get_order_total_recurring, Float)
end
def get_order_total_recurring_amount
request(:get_order_total_recurring_amount, Float)
end
def get_order_total_recurring_tax_amount
request(:get_order_total_recurring_tax_amount, Float)
end
def get_order_total_setup_amount
request(:get_order_total_setup_amount, Float)
end
def get_order_type
request(:get_order_type, Softlayer::Billing::Order::Type)
end
def get_paypal_transactions
request(:get_paypal_transactions, Array[Softlayer::Billing::Payment::PayPal::Transaction])
end
def get_pdf
request(:get_pdf, Softlayer::Base64Binary)
end
def get_pdf_filename
request(:get_pdf_filename, String)
end
def get_presale_event
request(:get_presale_event, Softlayer::Sales::Presale::Event)
end
def get_quote
request(:get_quote, Softlayer::Billing::Order::Quote)
end
# message
# ignore_discounts_flag
def get_recalculated_order_container(message)
request(:get_recalculated_order_container, Softlayer::Container::Product::Order, message)
end
def get_receipt
request(:get_receipt, Softlayer::Container::Product::Order::Receipt)
end
def get_referral_partner
request(:get_referral_partner, Softlayer::Account)
end
def get_upgrade_request_flag
request(:get_upgrade_request_flag, Boolean)
end
def get_user_record
request(:get_user_record, Softlayer::User::Customer)
end
def is_pending_edit_approval
request(:is_pending_edit_approval, Boolean)
end
class Representer < Softlayer::Entity::Representer
include Representable::Hash
include Representable::Coercion
property :account_id, type: Integer
property :create_date, type: DateTime
property :id, type: Integer
property :impersonating_user_record_id, type: Integer
property :modify_date, type: DateTime
property :order_quote_id, type: Integer
property :order_type_id, type: Integer
property :presale_event_id, type: Integer
property :private_cloud_order_flag, type: Boolean
property :status, type: String
property :user_record_id, type: Integer
property :core_restricted_item_count, type: BigDecimal
property :credit_card_transaction_count, type: BigDecimal
property :item_count, type: BigDecimal
property :order_top_level_item_count, type: BigDecimal
property :paypal_transaction_count, type: BigDecimal
property :order_approval_date, type: DateTime
property :order_non_server_monthly_amount, type: Float
property :order_server_monthly_amount, type: Float
property :order_total_amount, type: Float
property :order_total_one_time, type: Float
property :order_total_one_time_amount, type: Float
property :order_total_one_time_tax_amount, type: Float
property :order_total_recurring, type: Float
property :order_total_recurring_amount, type: Float
property :order_total_recurring_tax_amount, type: Float
property :order_total_setup_amount, type: Float
property :upgrade_request_flag, type: Boolean
end
end
end
end
| mit |
futurechimp/diffrent | lib/diffrent.rb | 1195 | module Diffrent
# Get a diff between two arbitrary versions of an ActiveRecord object.
#
# @param [Symbol] attr the attribute you want to diff.
# @param [Integer] old_version the version you want to start your diff at.
# @param [Integer] new_version the version you want to diff to.
# @param [Hash] options an options hash allowing you to pass a :format.
# @return [String] a diff string. If :format was nil, this could be a [Diffy::Diff].
def diff_for(attr, old_version, new_version, options={:format => :html})
changes = self.changes_between(new_version, old_version)
if changes.key?(attr)
Diffy::Diff.new(changes[attr].first, changes[attr].last).to_s(options[:format])
else
self.send(attr)
end
end
# Are there previous versions?
# @param [Integer] v the version number to check.
# @return [Boolean] whether there are any versions before version v.
def has_versions_before?(v)
self.versions.at(v - 1)
end
# Are there later versions?
# @param [Integer] v the version number to check.
# @return [Boolean] whether there are any versions after version v.
def has_versions_after?(v)
self.versions.at(v + 1)
end
end | mit |
lukhnos/doubleshot | lib/coffee-script/coffee-script.js | 5582 | // Generated by CoffeeScript 1.3.3
(function() {
var Lexer, RESERVED, compile, compileWithExtraOutput, fs, lexer, parser, path, vm, _ref,
__hasProp = {}.hasOwnProperty;
fs = require('fs');
path = require('path');
_ref = require('./lexer'), Lexer = _ref.Lexer, RESERVED = _ref.RESERVED;
parser = require('./parser').parser;
vm = require('vm');
if (require.extensions) {
require.extensions['.coffee'] = function(module, filename) {
var content;
content = compile(fs.readFileSync(filename, 'utf8'), {
filename: filename
});
return module._compile(content, filename);
};
} else if (require.registerExtension) {
require.registerExtension('.coffee', function(content) {
return compile(content);
});
}
exports.VERSION = '1.3.3';
exports.RESERVED = RESERVED;
exports.helpers = require('./helpers');
exports.compile = compile = function(code, options) {
var header, js, merge;
if (options == null) {
options = {};
}
merge = exports.helpers.merge;
try {
js = (parser.parse(lexer.tokenize(code))).compile(options);
if (!options.header) {
return js;
}
} catch (err) {
if (options.filename) {
err.message = "In " + options.filename + ", " + err.message;
}
throw err;
}
header = "Generated by CoffeeScript " + this.VERSION;
return "// " + header + "\n" + js;
};
exports.compileWithExtraOutput = compileWithExtraOutput = function(code, options) {
var header, js, merge, root;
if (options == null) {
options = {};
}
merge = exports.helpers.merge;
try {
root = parser.parse(lexer.tokenize(code));
js = root.compile(options);
if (!options.header) {
return {
js: js,
modules: root.submoduleCode
};
}
} catch (err) {
if (options.filename) {
err.message = "In " + options.filename + ", " + err.message;
}
throw err;
}
header = "Generated by CoffeeScript " + this.VERSION;
return {
js: "// " + header + "\n" + js,
modules: root.submoduleCode
};
};
exports.tokens = function(code, options) {
return lexer.tokenize(code, options);
};
exports.nodes = function(source, options) {
if (typeof source === 'string') {
return parser.parse(lexer.tokenize(source, options));
} else {
return parser.parse(source);
}
};
exports.run = function(code, options) {
var mainModule;
if (options == null) {
options = {};
}
mainModule = require.main;
mainModule.filename = process.argv[1] = options.filename ? fs.realpathSync(options.filename) : '.';
mainModule.moduleCache && (mainModule.moduleCache = {});
mainModule.paths = require('module')._nodeModulePaths(path.dirname(fs.realpathSync(options.filename)));
if (path.extname(mainModule.filename) !== '.coffee' || require.extensions) {
return mainModule._compile(compile(code, options), mainModule.filename);
} else {
return mainModule._compile(code, mainModule.filename);
}
};
exports["eval"] = function(code, options) {
var Module, Script, js, k, o, r, sandbox, v, _i, _len, _module, _ref1, _ref2, _require;
if (options == null) {
options = {};
}
if (!(code = code.trim())) {
return;
}
Script = vm.Script;
if (Script) {
if (options.sandbox != null) {
if (options.sandbox instanceof Script.createContext().constructor) {
sandbox = options.sandbox;
} else {
sandbox = Script.createContext();
_ref1 = options.sandbox;
for (k in _ref1) {
if (!__hasProp.call(_ref1, k)) continue;
v = _ref1[k];
sandbox[k] = v;
}
}
sandbox.global = sandbox.root = sandbox.GLOBAL = sandbox;
} else {
sandbox = global;
}
sandbox.__filename = options.filename || 'eval';
sandbox.__dirname = path.dirname(sandbox.__filename);
if (!(sandbox !== global || sandbox.module || sandbox.require)) {
Module = require('module');
sandbox.module = _module = new Module(options.modulename || 'eval');
sandbox.require = _require = function(path) {
return Module._load(path, _module, true);
};
_module.filename = sandbox.__filename;
_ref2 = Object.getOwnPropertyNames(require);
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
r = _ref2[_i];
if (r !== 'paths') {
_require[r] = require[r];
}
}
_require.paths = _module.paths = Module._nodeModulePaths(process.cwd());
_require.resolve = function(request) {
return Module._resolveFilename(request, _module);
};
}
}
o = {};
for (k in options) {
if (!__hasProp.call(options, k)) continue;
v = options[k];
o[k] = v;
}
o.bare = true;
js = compile(code, o);
if (sandbox === global) {
return vm.runInThisContext(js);
} else {
return vm.runInContext(js, sandbox);
}
};
lexer = new Lexer;
parser.lexer = {
lex: function() {
var tag, _ref1;
_ref1 = this.tokens[this.pos++] || [''], tag = _ref1[0], this.yytext = _ref1[1], this.yylineno = _ref1[2];
return tag;
},
setInput: function(tokens) {
this.tokens = tokens;
return this.pos = 0;
},
upcomingInput: function() {
return "";
}
};
parser.yy = require('./nodes');
}).call(this);
| mit |
MiniverCheevy/spa-starter-kit | src/React/ClientApp/components/forms/input-dropdown.tsx | 1929 | import * as React from 'react';
import { ErrorIcon } from './error-icon';
import { Services } from './../../root';
import { InputComponent } from './input-component';
import { InputHelper } from './input-helper';
import { InputShell } from './input-shell';
export class InputDropdown extends InputComponent {
private isLabel = false;
private isDropdown = false;
private selectedText = '';
constructor(props) {
super(props);
this.helper = new InputHelper(this);
}
onChange = (event) => {
this.helper.handleChange(event);
}
preRender = () => {
if (this.state.readOnly) {
this.isLabel = true;
const items = this.props.items.filter((item) => { return item.id == this.state.value; });
if (items.length > 0)
this.selectedText = items[0].name;
}
else
this.isDropdown = true;
}
doRender = () => {
var config = this.helper.getState();
var value = config.rawValue;
var items = this.props.items || [];
var options = items.map((item, index) => {
var key = this.state.name + '_o_' + index;
return <option key={key}
value={item.id}
className="mdc-list-item">{item.name}</option>;
}
);
return <InputShell {...this.state}
label={config.label}
isValid={config.isValid}
validationMessage={config.validationMessage} >
<select className="mdc-select input-component form-control"
onChange={this.onChange}
value={config.rawValue}
key={this.state.key}
name={this.state.name}
>
<option></option>
{options}
</select >
</InputShell>;
}
} | mit |
mathemage/CompetitiveProgramming | fbhackcup/2021/quals/A2/A2.cpp | 6189 | /* ========================================
ID: mathema6
TASK: A2
LANG: C++14
* File Name : A2.cpp
* Creation Date : 28-08-2021
* Last Modified : Sat 28 Aug 2021 03:25:42 PM CEST
* Created By : Karel Ha <mathemage@gmail.com>
* URL :
* Points/Time :
* Total/ETA :
* Status :
==========================================*/
#define PROBLEMNAME "A2"
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define REP(i,n) for(ll i=0;i<(n);i++)
#define FOR(i,a,b) for(ll i=(a);i<=(b);i++)
#define FORD(i,a,b) for(ll i=(a);i>=(b);i--)
#define REPi(i,n) for(int i=0;i<(n);i++)
#define FORi(i,a,b) for(int i=(a);i<=(b);i++)
#define FORDi(i,a,b) for(int i=(a);i>=(b);i--)
#define ALL(A) (A).begin(), (A).end()
#define REVALL(A) (A).rbegin(), (A).rend()
#define F first
#define S second
#define OP first
#define CL second
#define PB push_back
#define MP make_pair
#define MTP make_tuple
#define SGN(X) ((X) ? ( (X)>0?1:-1 ) : 0)
#define CONTAINS(S,E) ((S).find(E) != (S).end())
#define SZ(x) ((ll) (x).size())
// #define SZi(x) ((int) (x).size())
#define YES cout << "YES" << endl;
#define NO cout << "NO" << endl;
#define YN(b) cout << ((b)?"YES":"NO") << endl;
#define Yes cout << "Yes" << endl;
#define No cout << "No" << endl;
#define Yn(b) cout << ((b)?"Yes":"No") << endl;
#define Imp cout << "Impossible" << endl;
#define IMP cout << "IMPOSSIBLE" << endl;
using ll = long long;
using ul = unsigned long long;
// using ulul = pair<ul, ul>;
using ld = long double;
using graph_unord = unordered_map<ll, vector<ll>>;
using graph_ord = map<ll, set<ll>>;
using graph_t = graph_unord;
#ifdef ONLINE_JUDGE
#undef MATHEMAGE_DEBUG
#endif
#ifdef MATHEMAGE_DEBUG
#define MSG(a) cerr << "> " << (#a) << ": " << (a) << endl;
#define MSG_VEC_VEC(v) cerr << "> " << (#v) << ":\n" << (v) << endl;
#define LINESEP1 cerr << "----------------------------------------------- " << endl;
#define LINESEP2 cerr << "_________________________________________________________________" << endl;
#else
#define MSG(a)
#define MSG_VEC_VEC(v)
#define LINESEP1
#define LINESEP2
#endif
ostream& operator<<(ostream& os, const vector<string> & vec) { os << endl; for (const auto & s: vec) os << s << endl; return os; }
template<typename T>
ostream& operator<<(ostream& os, const vector<T> & vec) { for (const auto & x: vec) os << x << " "; return os; }
template<typename T>
ostream& operator<<(ostream& os, const vector<vector<T>> & vec) { for (const auto & v: vec) os << v << endl; return os; }
template<typename T>
inline ostream& operator<<(ostream& os, const vector<vector<vector<T>>> & vec) {
for (const auto & row: vec) {
for (const auto & col: row) {
os << "[ " << col << "] ";
}
os << endl;
}
return os;
}
template<typename T, class Compare>
ostream& operator<<(ostream& os, const set<T, Compare>& vec) { for (const auto & x: vec) os << x << " "; os << endl; return os; }
template<typename T, class Compare>
ostream& operator<<(ostream& os, const multiset<T, Compare>& vec) { for (const auto & x: vec) os << x << " "; os << endl; return os; }
template<typename T1, typename T2>
ostream& operator<<(ostream& os, const map<T1, T2>& vec) { for (const auto & x: vec) os << x.F << ":" << x.S << " | "; return os; }
template<typename T1, typename T2>
ostream& operator<<(ostream& os, const unordered_map<T1, T2>& vec) { for (const auto & x: vec) os << x.F << ":" << x.S << " | "; return os; }
template<typename T1, typename T2>
ostream& operator<<(ostream& os, const pair<T1, T2>& p) { return os << "(" << p.F << ", " << p.S << ")"; }
template<typename T>
istream& operator>>(istream& is, vector<T> & vec) { for (auto & x: vec) is >> x; return is; }
template<typename T>
inline bool bounded(const T & x, const T & u, const T & l=0) { return min(l,u)<=x && x<max(l,u); }
template<class T> bool umin(T& a, const T& b) { return b < a ? a = b, 1 : 0; }
template<class T> bool umax(T& a, const T& b) { return a < b ? a = b, 1 : 0; }
inline bool eqDouble(double a, double b) { return fabs(a-b) < 1e-9; }
#ifndef MATHEMAGE_LOCAL
void setIO(string filename) { // the argument is the filename without the extension
freopen((filename+".in").c_str(), "r", stdin);
freopen((filename+".out").c_str(), "w", stdout);
MSG(filename);
}
#endif
const vector<int> DX8 = {-1, -1, -1, 0, 0, 1, 1, 1};
const vector<int> DY8 = {-1, 0, 1, -1, 1, -1, 0, 1};
const vector<pair<int,int>> DXY8 = {
{-1,-1}, {-1,0}, {-1,1},
{ 0,-1}, { 0,1},
{ 1,-1}, { 1,0}, { 1,1}
};
const vector<int> DX4 = {0, 1, 0, -1};
const vector<int> DY4 = {1, 0, -1, 0};
const vector<pair<int,int>> DXY4 = { {0,1}, {1,0}, {0,-1}, {-1,0} };
const string dues="NESW";
const int CLEAN = -1;
const int UNDEF = -42;
const long long MOD = 1000000007;
const double EPS = 1e-8;
const ld PI = acos((ld)-1);
const int INF = INT_MAX;
const long long INF_LL = LLONG_MAX;
const long long INF_ULL = ULLONG_MAX;
const ll mx=26;
void solve() {
string S; cin >> S;
ll K; cin >> K;
vector<vector<ll>> dist(mx, vector<ll>(mx, INF));
// #warning TODO change back to INF
// vector<vector<ll>> dist(mx, vector<ll>(mx, -1));
// vector<vector<ll>> dist(mx, vector<ll>(mx, 100));
REP(i,mx) {
dist[i][i]=0;
}
char Ai,Bi;
REP(_,K) {
cin >> Ai >> Bi;
// MSG(Ai); MSG(Bi);
dist[Ai-'A'][Bi-'A']=1;
}
// Floyd-Warshall
REP(k,mx) {
REP(i,mx) {
REP(j,mx) {
umin(dist[i][j], dist[i][k]+dist[k][j]);
}
}
}
MSG_VEC_VEC(dist); LINESEP1;
ll result = INF;
REP(dest,mx) {
ll cur=0;
for (auto & ch: S) {
ll src=ch-'A';
if (dist[src][dest]<INF) {
cur+=dist[src][dest];
} else {
cur=INF;
break;
}
}
umin(result, cur);
}
if (result>=INF) {
result=-1;
}
cout << result << endl;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout << std::setprecision(10) << std::fixed;
#ifndef MATHEMAGE_LOCAL
// setIO(PROBLEMNAME);
#endif
int cases = 1;
cin >> cases;
FOR(tt,1,cases) {
cout << "Case #" << tt << ": ";
solve();
LINESEP2;
}
return 0;
}
| mit |
cdnjs/cdnjs | ajax/libs/impetus/0.8.8/impetus.js | 16239 | (function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'module'], factory);
} else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
factory(exports, module);
} else {
var mod = {
exports: {}
};
factory(mod.exports, mod);
global.Impetus = mod.exports;
}
})(this, function (exports, module) {
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var stopThresholdDefault = 0.3;
var bounceDeceleration = 0.04;
var bounceAcceleration = 0.11;
// fixes weird safari 10 bug where preventDefault is prevented
// @see https://github.com/metafizzy/flickity/issues/457#issuecomment-254501356
window.addEventListener('touchmove', function () {});
var Impetus = function Impetus(_ref) {
var _ref$source = _ref.source;
var sourceEl = _ref$source === undefined ? document : _ref$source;
var updateCallback = _ref.update;
var _ref$multiplier = _ref.multiplier;
var multiplier = _ref$multiplier === undefined ? 1 : _ref$multiplier;
var _ref$friction = _ref.friction;
var friction = _ref$friction === undefined ? 0.92 : _ref$friction;
var initialValues = _ref.initialValues;
var boundX = _ref.boundX;
var boundY = _ref.boundY;
var _ref$bounce = _ref.bounce;
var bounce = _ref$bounce === undefined ? true : _ref$bounce;
_classCallCheck(this, Impetus);
var boundXmin, boundXmax, boundYmin, boundYmax, pointerLastX, pointerLastY, pointerCurrentX, pointerCurrentY, pointerId, decVelX, decVelY;
var targetX = 0;
var targetY = 0;
var stopThreshold = stopThresholdDefault * multiplier;
var ticking = false;
var pointerActive = false;
var paused = false;
var decelerating = false;
var trackingPoints = [];
/**
* Initialize instance
*/
(function init() {
sourceEl = typeof sourceEl === 'string' ? document.querySelector(sourceEl) : sourceEl;
if (!sourceEl) {
throw new Error('IMPETUS: source not found.');
}
if (!updateCallback) {
throw new Error('IMPETUS: update function not defined.');
}
if (initialValues) {
if (initialValues[0]) {
targetX = initialValues[0];
}
if (initialValues[1]) {
targetY = initialValues[1];
}
callUpdateCallback();
}
// Initialize bound values
if (boundX) {
boundXmin = boundX[0];
boundXmax = boundX[1];
}
if (boundY) {
boundYmin = boundY[0];
boundYmax = boundY[1];
}
sourceEl.addEventListener('touchstart', onDown);
sourceEl.addEventListener('mousedown', onDown);
})();
/**
* In edge cases where you may need to
* reinstanciate Impetus on the same sourceEl
* this will remove the previous event listeners
*/
this.destroy = function () {
sourceEl.removeEventListener('touchstart', onDown);
sourceEl.removeEventListener('mousedown', onDown);
cleanUpRuntimeEvents();
// however it won't "destroy" a reference
// to instance if you'd like to do that
// it returns null as a convinience.
// ex: `instance = instance.destroy();`
return null;
};
/**
* Disable movement processing
* @public
*/
this.pause = function () {
cleanUpRuntimeEvents();
pointerActive = false;
paused = true;
};
/**
* Enable movement processing
* @public
*/
this.resume = function () {
paused = false;
};
/**
* Update the current x and y values
* @public
* @param {Number} x
* @param {Number} y
*/
this.setValues = function (x, y) {
if (typeof x === 'number') {
targetX = x;
}
if (typeof y === 'number') {
targetY = y;
}
};
/**
* Update the multiplier value
* @public
* @param {Number} val
*/
this.setMultiplier = function (val) {
multiplier = val;
stopThreshold = stopThresholdDefault * multiplier;
};
/**
* Update boundX value
* @public
* @param {Number[]} boundX
*/
this.setBoundX = function (boundX) {
boundXmin = boundX[0];
boundXmax = boundX[1];
};
/**
* Update boundY value
* @public
* @param {Number[]} boundY
*/
this.setBoundY = function (boundY) {
boundYmin = boundY[0];
boundYmax = boundY[1];
};
/**
* Removes all events set by this instance during runtime
*/
function cleanUpRuntimeEvents() {
// Remove all touch events added during 'onDown' as well.
document.removeEventListener('touchmove', onMove, getPassiveSupported() ? { passive: false } : false);
document.removeEventListener('touchend', onUp);
document.removeEventListener('touchcancel', stopTracking);
document.removeEventListener('mousemove', onMove, getPassiveSupported() ? { passive: false } : false);
document.removeEventListener('mouseup', onUp);
}
/**
* Add all required runtime events
*/
function addRuntimeEvents() {
cleanUpRuntimeEvents();
// @see https://developers.google.com/web/updates/2017/01/scrolling-intervention
document.addEventListener('touchmove', onMove, getPassiveSupported() ? { passive: false } : false);
document.addEventListener('touchend', onUp);
document.addEventListener('touchcancel', stopTracking);
document.addEventListener('mousemove', onMove, getPassiveSupported() ? { passive: false } : false);
document.addEventListener('mouseup', onUp);
}
/**
* Executes the update function
*/
function callUpdateCallback() {
updateCallback.call(sourceEl, targetX, targetY);
}
/**
* Creates a custom normalized event object from touch and mouse events
* @param {Event} ev
* @returns {Object} with x, y, and id properties
*/
function normalizeEvent(ev) {
if (ev.type === 'touchmove' || ev.type === 'touchstart' || ev.type === 'touchend') {
var touch = ev.targetTouches[0] || ev.changedTouches[0];
return {
x: touch.clientX,
y: touch.clientY,
id: touch.identifier
};
} else {
// mouse events
return {
x: ev.clientX,
y: ev.clientY,
id: null
};
}
}
/**
* Initializes movement tracking
* @param {Object} ev Normalized event
*/
function onDown(ev) {
var event = normalizeEvent(ev);
if (!pointerActive && !paused) {
pointerActive = true;
decelerating = false;
pointerId = event.id;
pointerLastX = pointerCurrentX = event.x;
pointerLastY = pointerCurrentY = event.y;
trackingPoints = [];
addTrackingPoint(pointerLastX, pointerLastY);
addRuntimeEvents();
}
}
/**
* Handles move events
* @param {Object} ev Normalized event
*/
function onMove(ev) {
ev.preventDefault();
var event = normalizeEvent(ev);
if (pointerActive && event.id === pointerId) {
pointerCurrentX = event.x;
pointerCurrentY = event.y;
addTrackingPoint(pointerLastX, pointerLastY);
requestTick();
}
}
/**
* Handles up/end events
* @param {Object} ev Normalized event
*/
function onUp(ev) {
var event = normalizeEvent(ev);
if (pointerActive && event.id === pointerId) {
stopTracking();
}
}
/**
* Stops movement tracking, starts animation
*/
function stopTracking() {
pointerActive = false;
addTrackingPoint(pointerLastX, pointerLastY);
startDecelAnim();
cleanUpRuntimeEvents();
}
/**
* Records movement for the last 100ms
* @param {number} x
* @param {number} y [description]
*/
function addTrackingPoint(x, y) {
var time = Date.now();
while (trackingPoints.length > 0) {
if (time - trackingPoints[0].time <= 100) {
break;
}
trackingPoints.shift();
}
trackingPoints.push({ x: x, y: y, time: time });
}
/**
* Calculate new values, call update function
*/
function updateAndRender() {
var pointerChangeX = pointerCurrentX - pointerLastX;
var pointerChangeY = pointerCurrentY - pointerLastY;
targetX += pointerChangeX * multiplier;
targetY += pointerChangeY * multiplier;
if (bounce) {
var diff = checkBounds();
if (diff.x !== 0) {
targetX -= pointerChangeX * dragOutOfBoundsMultiplier(diff.x) * multiplier;
}
if (diff.y !== 0) {
targetY -= pointerChangeY * dragOutOfBoundsMultiplier(diff.y) * multiplier;
}
} else {
checkBounds(true);
}
callUpdateCallback();
pointerLastX = pointerCurrentX;
pointerLastY = pointerCurrentY;
ticking = false;
}
/**
* Returns a value from around 0.5 to 1, based on distance
* @param {Number} val
*/
function dragOutOfBoundsMultiplier(val) {
return 0.000005 * Math.pow(val, 2) + 0.0001 * val + 0.55;
}
/**
* prevents animating faster than current framerate
*/
function requestTick() {
if (!ticking) {
requestAnimFrame(updateAndRender);
}
ticking = true;
}
/**
* Determine position relative to bounds
* @param {Boolean} restrict Whether to restrict target to bounds
*/
function checkBounds(restrict) {
var xDiff = 0;
var yDiff = 0;
if (boundXmin !== undefined && targetX < boundXmin) {
xDiff = boundXmin - targetX;
} else if (boundXmax !== undefined && targetX > boundXmax) {
xDiff = boundXmax - targetX;
}
if (boundYmin !== undefined && targetY < boundYmin) {
yDiff = boundYmin - targetY;
} else if (boundYmax !== undefined && targetY > boundYmax) {
yDiff = boundYmax - targetY;
}
if (restrict) {
if (xDiff !== 0) {
targetX = xDiff > 0 ? boundXmin : boundXmax;
}
if (yDiff !== 0) {
targetY = yDiff > 0 ? boundYmin : boundYmax;
}
}
return {
x: xDiff,
y: yDiff,
inBounds: xDiff === 0 && yDiff === 0
};
}
/**
* Initialize animation of values coming to a stop
*/
function startDecelAnim() {
var firstPoint = trackingPoints[0];
var lastPoint = trackingPoints[trackingPoints.length - 1];
var xOffset = lastPoint.x - firstPoint.x;
var yOffset = lastPoint.y - firstPoint.y;
var timeOffset = lastPoint.time - firstPoint.time;
var D = timeOffset / 15 / multiplier;
decVelX = xOffset / D || 0; // prevent NaN
decVelY = yOffset / D || 0;
var diff = checkBounds();
if (Math.abs(decVelX) > 1 || Math.abs(decVelY) > 1 || !diff.inBounds) {
decelerating = true;
requestAnimFrame(stepDecelAnim);
}
}
/**
* Animates values slowing down
*/
function stepDecelAnim() {
if (!decelerating) {
return;
}
decVelX *= friction;
decVelY *= friction;
targetX += decVelX;
targetY += decVelY;
var diff = checkBounds();
if (Math.abs(decVelX) > stopThreshold || Math.abs(decVelY) > stopThreshold || !diff.inBounds) {
if (bounce) {
var reboundAdjust = 2.5;
if (diff.x !== 0) {
if (diff.x * decVelX <= 0) {
decVelX += diff.x * bounceDeceleration;
} else {
var adjust = diff.x > 0 ? reboundAdjust : -reboundAdjust;
decVelX = (diff.x + adjust) * bounceAcceleration;
}
}
if (diff.y !== 0) {
if (diff.y * decVelY <= 0) {
decVelY += diff.y * bounceDeceleration;
} else {
var adjust = diff.y > 0 ? reboundAdjust : -reboundAdjust;
decVelY = (diff.y + adjust) * bounceAcceleration;
}
}
} else {
if (diff.x !== 0) {
if (diff.x > 0) {
targetX = boundXmin;
} else {
targetX = boundXmax;
}
decVelX = 0;
}
if (diff.y !== 0) {
if (diff.y > 0) {
targetY = boundYmin;
} else {
targetY = boundYmax;
}
decVelY = 0;
}
}
callUpdateCallback();
requestAnimFrame(stepDecelAnim);
} else {
decelerating = false;
}
}
}
/**
* @see http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
*/
;
module.exports = Impetus;
var requestAnimFrame = (function () {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
function getPassiveSupported() {
var passiveSupported = false;
try {
var options = Object.defineProperty({}, "passive", {
get: function get() {
passiveSupported = true;
}
});
window.addEventListener("test", null, options);
} catch (err) {}
getPassiveSupported = function () {
return passiveSupported;
};
return passiveSupported;
}
});
| mit |
kav-it/SharpLib | Source/SharpLib.Docking/Source/Interfaces/Layout/ILayoutPaneSerializable.cs | 178 | namespace SharpLib.Docking
{
internal interface ILayoutPaneSerializable
{
#region Свойства
string Id { get; set; }
#endregion
}
} | mit |
purjayadi/purjayadi.github.io | application/modules/panelIMS/views/p_artikel/p_artikel_form.php | 2202 | <script src='<?php echo base_url('ckeditor/ckeditor.js');?>'></script>
<form method='post' action="<?php echo base_url('panelIMS/p_artikel/s_artikel');?>">
<div class='form-group'>
<label for='posisi'><b>Posisi</b></label>
<select id='posisi' name='posisi' class="form-control" autofocus required>
<option disabled selected>Pilih Posisi Menu dimana Artikel akan Ditampilkan</option>
<option value='0'>0 - Homepage</option>
<option value='1'>1 - Halaman Kategori</option>
<option value='2'>2 - Halaman Produk</option>
<option value='3'>3 - Halaman Artikel</option>
<option value='4'>4 - Halaman Hubungi Kami</option>
</select>
</div>
<div class='form-group'>
<label for='id'><b>ID</b></label>
<select name="id_produk" class="form-control">
<option disabled selected>Pilih ID Produk</option>
<?php
$produk = $this->db->query("SELECT * FROM produk");
foreach ($produk->result() as $key) {
?>
<option value="<?php echo $key->id_produk; ?>"><?php echo $key->id_produk;?></option>
<?php
}
?>
</select>
</div>
<div class='form-group'>
<label for='judul'><b>Judul Artikel</b></label>
<input id='judul' name='judul_artikel' type='text' placeholder='Judul Artikel' class="form-control" required/>
</div>
<div class='form-group'>
<label for='isi'><b>Ringkasan Artikel</b></label>
<textarea id='ringkasan_artikel' name='ringkasan_artikel' rows='4' class="form-control" required></textarea>
</div>
<div class='form-group'>
<label for='isi_full'><b>Konten Artikel Lengkap</b></label>
<textarea class='ckeditor' id='konteks_artikel' name='konteks_artikel' class="form-control"></textarea>
</div>
<button type='submit' class="btn btn-primary btn-sm" name="submit">Save</button>
<input type="hidden" name="<?=$this->security->get_csrf_token_name();?>" value="<?=$this->security->get_csrf_hash();?>" style="display: none">
<a class="btn btn-success btn-sm" href="<?php echo base_url('panelIMS/p_artikel');?>">Cancel</a>
<input name='form' type='hidden' value='form-input-1000-artikel'/>
</form> | mit |
nomad-mystic/nomadmystic | fileSystem/school-projects/development/softwaredesignandcomputerlogiccis122/cis122lab4/python/last_name_functions.py | 2426 | # programmer = Keith Murphy
# File = last_name_functions.py
# Date Created = 2-26-2015
# Last Mod = 2-26-2015
# Import regular expressions external library
import re
# Declare str last_name_input_value
# Declare str valid_matched_last_name
# Declare str valid_last_name
# Declare Boolean tested_last_name_validation
# Function last_name_input
# Declare name_input_value
# Display Please Type your last name:
# Input name_input_value
# Return name_input_value
# End Function
def last_name_input():
name_input_value = str(input('Please Type your last name: '))
return name_input_value
# Function str run_last_name_validation(str last_name_input_value)
# Declare str valid
# Declare str valid_last_name
# Declare boolean tested_last_name_validation
#
# Set valid = re.compile('^[a-zA-Z]+$')
# Set valid_last_name = valid.match(last_name_input_value)
#
# If valid_last_name Then
# Return True, valid_last_name.group()
# Else:
# Set tested_last_name_validation = False
# Return tested_last_name_validation, False
# End If
# End Function
def run_last_name_validation(last_name_input_value):
valid = re.compile('^[a-zA-Z]+$')
valid_last_name = valid.match(last_name_input_value)
if valid_last_name:
return True, valid_last_name.group()
else:
tested_last_name_validation = False
return tested_last_name_validation, False
# Function str last_name_validation_loop(str last_name_input_value)
# Declare Boolean valid_matched_last_name
# Declare Boolean tested_last_name_validation
# Declare str last_name_input_value
#
# Set tested_last_name_validation, valid_matched_last_name = run_last_name_validation(last_name_input_value)
# While Not tested_last_name_validation
# Set last_name_input_value = last_name_input()
# Set tested_last_name_validation, valid_matched_last_name = run_last_name_validation(last_name_input_value)
# End While
#
# Return valid_matched_last_name
# End Function
def last_name_validation_loop(last_name_input_value):
tested_last_name_validation, valid_matched_last_name = run_last_name_validation(last_name_input_value)
while not tested_last_name_validation:
last_name_input_value = last_name_input()
tested_last_name_validation, valid_matched_last_name = run_last_name_validation(last_name_input_value)
return valid_matched_last_name | mit |
dawings1/Side-Quest-City | Side Quest City/src/us/terracraft/sqc/npc/TestNPC.java | 1160 | package us.terracraft.sqc.npc;
import java.awt.event.KeyEvent;
import java.util.Random;
import KTech.components.*;
import KTech.core.*;
import KTech.core.*;
import KTech.graphics.Image;
public class TestNPC extends GameObject {
Image Test = new Image("/characters/NPC.png");
int x, y;
boolean up, left;
public TestNPC(int x, int y, String displayName) {
setName("TestNPC");
this.x = x;
this.y = y;
addComponent(new Collider());
}
@Override
public void update(KTech kt, float time) {
if (y > 30) {
up = true;
}
if (y == 30) {
up = false;
left = true;
}
if (x < 30) {
left = false;
}
if (up == true) {
y--;
}
if (left == true) {
x--;
}
updateComponents(kt, time);
}
@Override
public void render(KTech kt, Renderer r) {
r.drawImage(Test, x, y);
}
@Override
public void dispose() {
}
@Override
public void componentEvent(String name, GameObject object) {
if (name.equalsIgnoreCase("Collider")) {
if (object.getX() < x) {
left = false;
} else {
//left = true;
}
if (object.getY() > y) {
up = false;
} else {
//up = true;
}
}
}
}
| mit |
realdoug/omniauth-salesforce | lib/omniauth-salesforce.rb | 79 | require 'omniauth-salesforce/version'
require 'omniauth/strategies/salesforce'
| mit |
waitman/red | library/jquery.timeago.js | 4530 | /**
* Timeago is a jQuery plugin that makes it easy to support automatically
* updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago").
*
* @name timeago
* @version 0.11.4
* @requires jQuery v1.2.3+
* @author Ryan McGeary
* @license MIT License - http://www.opensource.org/licenses/mit-license.php
*
* For usage and examples, visit:
* http://timeago.yarp.com/
*
* Copyright (c) 2008-2012, Ryan McGeary (ryan -[at]- mcgeary [*dot*] org)
*/
(function($) {
$.timeago = function(timestamp) {
if (timestamp instanceof Date) {
return inWords(timestamp);
} else if (typeof timestamp === "string") {
return inWords($.timeago.parse(timestamp));
} else if (typeof timestamp === "number") {
return inWords(new Date(timestamp));
} else {
return inWords($.timeago.datetime(timestamp));
}
};
var $t = $.timeago;
$.extend($.timeago, {
settings: {
refreshMillis: 60000,
allowFuture: false,
strings: {
prefixAgo: null,
prefixFromNow: null,
suffixAgo: "ago",
suffixFromNow: "from now",
seconds: "less than a minute",
minute: "about a minute",
minutes: "%d minutes",
hour: "about an hour",
hours: "about %d hours",
day: "a day",
days: "%d days",
month: "about a month",
months: "%d months",
year: "about a year",
years: "%d years",
wordSeparator: " ",
numbers: []
}
},
inWords: function(distanceMillis) {
var $l = this.settings.strings;
var prefix = $l.prefixAgo;
var suffix = $l.suffixAgo;
if (this.settings.allowFuture) {
if (distanceMillis < 0) {
prefix = $l.prefixFromNow;
suffix = $l.suffixFromNow;
}
}
var seconds = Math.abs(distanceMillis) / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
var years = days / 365;
function substitute(stringOrFunction, number) {
var string = $.isFunction(stringOrFunction) ? stringOrFunction(number, distanceMillis) : stringOrFunction;
var value = ($l.numbers && $l.numbers[number]) || number;
return string.replace(/%d/i, value);
}
var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
seconds < 90 && substitute($l.minute, 1) ||
minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
minutes < 90 && substitute($l.hour, 1) ||
hours < 24 && substitute($l.hours, Math.round(hours)) ||
hours < 42 && substitute($l.day, 1) ||
days < 30 && substitute($l.days, Math.round(days)) ||
days < 45 && substitute($l.month, 1) ||
days < 365 && substitute($l.months, Math.round(days / 30)) ||
years < 1.5 && substitute($l.year, 1) ||
substitute($l.years, Math.round(years));
var separator = $l.wordSeparator === undefined ? " " : $l.wordSeparator;
return $.trim([prefix, words, suffix].join(separator));
},
parse: function(iso8601) {
var s = $.trim(iso8601);
s = s.replace(/\.\d+/,""); // remove milliseconds
s = s.replace(/-/,"/").replace(/-/,"/");
s = s.replace(/T/," ").replace(/Z/," UTC");
s = s.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
return new Date(s);
},
datetime: function(elem) {
var iso8601 = $t.isTime(elem) ? $(elem).attr("datetime") : $(elem).attr("title");
return $t.parse(iso8601);
},
isTime: function(elem) {
// jQuery's `is()` doesn't play well with HTML5 in IE
return $(elem).get(0).tagName.toLowerCase() === "time"; // $(elem).is("time");
}
});
$.fn.timeago = function() {
var self = this;
self.each(refresh);
var $s = $t.settings;
if ($s.refreshMillis > 0) {
setInterval(function() { self.each(refresh); }, $s.refreshMillis);
}
return self;
};
function refresh() {
var data = prepareData(this);
if (!isNaN(data.datetime)) {
$(this).text(inWords(data.datetime));
}
return this;
}
function prepareData(element) {
element = $(element);
if (!element.data("timeago")) {
element.data("timeago", { datetime: $t.datetime(element) });
var text = $.trim(element.text());
if (text.length > 0 && !($t.isTime(element) && element.attr("title"))) {
element.attr("title", text);
}
}
return element.data("timeago");
}
function inWords(date) {
return $t.inWords(distance(date));
}
function distance(date) {
return (new Date().getTime() - date.getTime());
}
// fix for IE6 suckage
document.createElement("abbr");
document.createElement("time");
}(jQuery));
| mit |
hail-is/hail | hail/src/main/scala/is/hail/expr/ir/AggOp.scala | 3387 | package is.hail.expr.ir
import is.hail.expr.ir.agg._
import is.hail.types.TypeWithRequiredness
import is.hail.types.physical._
import is.hail.types.virtual._
import is.hail.utils.FastSeq
object AggSignature {
def prune(agg: AggSignature, requestedType: Type): AggSignature = agg match {
case AggSignature(Collect(), Seq(), Seq(_)) =>
AggSignature(Collect(), FastSeq(), FastSeq(requestedType.asInstanceOf[TArray].elementType))
case AggSignature(Take(), Seq(n), Seq(_)) =>
AggSignature(Take(), FastSeq(n), FastSeq(requestedType.asInstanceOf[TArray].elementType))
case AggSignature(TakeBy(reverse), Seq(n), Seq(_, k)) =>
AggSignature(TakeBy(reverse), FastSeq(n), FastSeq(requestedType.asInstanceOf[TArray].elementType, k))
case AggSignature(PrevNonnull(), Seq(), Seq(_)) =>
AggSignature(PrevNonnull(), FastSeq(), FastSeq(requestedType))
case AggSignature(Densify(), Seq(), Seq(_)) =>
AggSignature(Densify(), FastSeq(), FastSeq(requestedType))
case _ => agg
}
}
case class AggSignature(
op: AggOp,
initOpArgs: Seq[Type],
seqOpArgs: Seq[Type]) {
// only to be used with virtual non-nested signatures on ApplyAggOp and ApplyScanOp
lazy val returnType: Type = Extract.getResultType(this)
}
sealed trait AggOp {}
final case class ApproxCDF() extends AggOp
final case class CallStats() extends AggOp
final case class Collect() extends AggOp
final case class CollectAsSet() extends AggOp
final case class Count() extends AggOp
final case class Downsample() extends AggOp
final case class LinearRegression() extends AggOp
final case class Max() extends AggOp
final case class Min() extends AggOp
final case class Product() extends AggOp
final case class Sum() extends AggOp
final case class Take() extends AggOp
final case class Densify() extends AggOp
final case class TakeBy(so: SortOrder = Ascending) extends AggOp
final case class Group() extends AggOp
final case class AggElements() extends AggOp
final case class AggElementsLengthCheck() extends AggOp
final case class PrevNonnull() extends AggOp
final case class ImputeType() extends AggOp
final case class NDArraySum() extends AggOp
final case class NDArrayMultiplyAdd() extends AggOp
final case class Fold() extends AggOp
// exists === map(p).sum, needs short-circuiting aggs
// forall === map(p).product, needs short-circuiting aggs
object AggOp {
val fromString: PartialFunction[String, AggOp] = {
case "approxCDF" | "ApproxCDF" => ApproxCDF()
case "collect" | "Collect" => Collect()
case "collectAsSet" | "CollectAsSet" => CollectAsSet()
case "sum" | "Sum" => Sum()
case "product" | "Product" => Product()
case "max" | "Max" => Max()
case "min" | "Min" => Min()
case "count" | "Count" => Count()
case "take" | "Take" => Take()
case "densify" | "Densify" => Densify()
case "takeBy" | "TakeBy" => TakeBy()
case "callStats" | "CallStats" => CallStats()
case "linreg" | "LinearRegression" => LinearRegression()
case "downsample" | "Downsample" => Downsample()
case "prevnonnull" | "PrevNonnull" => PrevNonnull()
case "Group" => Group()
case "AggElements" => AggElements()
case "AggElementsLengthCheck" => AggElementsLengthCheck()
case "ImputeType" => ImputeType()
case "NDArraySum" => NDArraySum()
case "NDArrayMutiplyAdd" => NDArrayMultiplyAdd()
case "Fold" => Fold()
}
}
| mit |
cdnjs/cdnjs | ajax/libs/highcharts/9.3.1/indicators/bollinger-bands.src.js | 20494 | /**
* @license Highstock JS v9.3.1 (2021-11-05)
*
* Indicator series type for Highcharts Stock
*
* (c) 2010-2021 Paweł Fus
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/indicators/bollinger-bands', ['highcharts', 'highcharts/modules/stock'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'Stock/Indicators/MultipleLinesComposition.js', [_modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (SeriesRegistry, U) {
/**
*
* (c) 2010-2021 Wojciech Chmiel
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var SMAIndicator = SeriesRegistry.seriesTypes.sma;
var defined = U.defined,
error = U.error,
merge = U.merge;
/* *
*
* Composition
*
* */
/**
* Composition useful for all indicators that have more than one line. Compose
* it with your implementation where you will provide the `getValues` method
* appropriate to your indicator and `pointArrayMap`, `pointValKey`,
* `linesApiNames` properties. Notice that `pointArrayMap` should be consistent
* with the amount of lines calculated in the `getValues` method.
*
* @private
* @mixin multipleLinesMixin
*/
var MultipleLinesComposition;
(function (MultipleLinesComposition) {
/* *
*
* Declarations
*
* */
/* *
*
* Constants
*
* */
var composedClasses = [];
/**
* Additional lines DOCS names. Elements of linesApiNames array should
* be consistent with DOCS line names defined in your implementation.
* Notice that linesApiNames should have decreased amount of elements
* relative to pointArrayMap (without pointValKey).
*
* @private
* @name multipleLinesMixin.linesApiNames
* @type {Array<string>}
*/
var linesApiNames = ['bottomLine'];
/**
* Lines ids. Required to plot appropriate amount of lines.
* Notice that pointArrayMap should have more elements than
* linesApiNames, because it contains main line and additional lines ids.
* Also it should be consistent with amount of lines calculated in
* getValues method from your implementation.
*
* @private
* @name multipleLinesMixin.pointArrayMap
* @type {Array<string>}
*/
var pointArrayMap = ['top', 'bottom'];
/**
* Main line id.
*
* @private
* @name multipleLinesMixin.pointValKey
* @type {string}
*/
var pointValKey = 'top';
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
/**
* @private
*/
function compose(IndicatorClass) {
if (composedClasses.indexOf(IndicatorClass) === -1) {
composedClasses.push(IndicatorClass);
var proto = IndicatorClass.prototype;
proto.linesApiNames = (proto.linesApiNames ||
linesApiNames.slice());
proto.pointArrayMap = (proto.pointArrayMap ||
pointArrayMap.slice());
proto.pointValKey = (proto.pointValKey ||
pointValKey);
proto.drawGraph = drawGraph;
proto.toYData = toYData;
proto.translate = translate;
proto.getTranslatedLinesNames = getTranslatedLinesNames;
}
return IndicatorClass;
}
MultipleLinesComposition.compose = compose;
/**
* Draw main and additional lines.
*
* @private
* @function multipleLinesMixin.drawGraph
* @return {void}
*/
function drawGraph() {
var indicator = this,
pointValKey = indicator.pointValKey,
linesApiNames = indicator.linesApiNames,
mainLinePoints = indicator.points,
mainLineOptions = indicator.options,
mainLinePath = indicator.graph,
gappedExtend = {
options: {
gapSize: mainLineOptions.gapSize
}
},
// additional lines point place holders:
secondaryLines = [],
secondaryLinesNames = indicator.getTranslatedLinesNames(pointValKey);
var pointsLength = mainLinePoints.length,
point;
// Generate points for additional lines:
secondaryLinesNames.forEach(function (plotLine, index) {
// create additional lines point place holders
secondaryLines[index] = [];
while (pointsLength--) {
point = mainLinePoints[pointsLength];
secondaryLines[index].push({
x: point.x,
plotX: point.plotX,
plotY: point[plotLine],
isNull: !defined(point[plotLine])
});
}
pointsLength = mainLinePoints.length;
});
// Modify options and generate additional lines:
linesApiNames.forEach(function (lineName, i) {
if (secondaryLines[i]) {
indicator.points = secondaryLines[i];
if (mainLineOptions[lineName]) {
indicator.options = merge(mainLineOptions[lineName].styles, gappedExtend);
}
else {
error('Error: "There is no ' + lineName +
' in DOCS options declared. Check if linesApiNames' +
' are consistent with your DOCS line names."' +
' at mixin/multiple-line.js:34');
}
indicator.graph = indicator['graph' + lineName];
SMAIndicator.prototype.drawGraph.call(indicator);
// Now save lines:
indicator['graph' + lineName] = indicator.graph;
}
else {
error('Error: "' + lineName + ' doesn\'t have equivalent ' +
'in pointArrayMap. To many elements in linesApiNames ' +
'relative to pointArrayMap."');
}
});
// Restore options and draw a main line:
indicator.points = mainLinePoints;
indicator.options = mainLineOptions;
indicator.graph = mainLinePath;
SMAIndicator.prototype.drawGraph.call(indicator);
}
/**
* Create translatedLines Collection based on pointArrayMap.
*
* @private
* @function multipleLinesMixin.getTranslatedLinesNames
* @param {string} [excludedValue]
* Main line id
* @return {Array<string>}
* Returns translated lines names without excluded value.
*/
function getTranslatedLinesNames(excludedValue) {
var translatedLines = [];
(this.pointArrayMap || []).forEach(function (propertyName) {
if (propertyName !== excludedValue) {
translatedLines.push('plot' +
propertyName.charAt(0).toUpperCase() +
propertyName.slice(1));
}
});
return translatedLines;
}
/**
* @private
* @function multipleLinesMixin.toYData
* @param {Highcharts.Point} point
* Indicator point
* @return {Array<number>}
* Returns point Y value for all lines
*/
function toYData(point) {
var pointColl = [];
(this.pointArrayMap || []).forEach(function (propertyName) {
pointColl.push(point[propertyName]);
});
return pointColl;
}
/**
* Add lines plot pixel values.
*
* @private
* @function multipleLinesMixin.translate
* @return {void}
*/
function translate() {
var indicator = this,
pointArrayMap = indicator.pointArrayMap;
var LinesNames = [],
value;
LinesNames = indicator.getTranslatedLinesNames();
SMAIndicator.prototype.translate.apply(indicator, arguments);
indicator.points.forEach(function (point) {
pointArrayMap.forEach(function (propertyName, i) {
value = point[propertyName];
// If the modifier, like for example compare exists,
// modified the original value by that method, #15867.
if (indicator.dataModify) {
value = indicator.dataModify.modifyValue(value);
}
if (value !== null) {
point[LinesNames[i]] = indicator.yAxis.toPixels(value, true);
}
});
});
}
})(MultipleLinesComposition || (MultipleLinesComposition = {}));
/* *
*
* Default Export
*
* */
return MultipleLinesComposition;
});
_registerModule(_modules, 'Stock/Indicators/BB/BBIndicator.js', [_modules['Stock/Indicators/MultipleLinesComposition.js'], _modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (MultipleLinesComposition, SeriesRegistry, U) {
/**
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var SMAIndicator = SeriesRegistry.seriesTypes.sma;
var extend = U.extend,
isArray = U.isArray,
merge = U.merge;
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
// Utils:
/**
* @private
*/
function getStandardDeviation(arr, index, isOHLC, mean) {
var variance = 0,
arrLen = arr.length,
std = 0,
i = 0,
value;
for (; i < arrLen; i++) {
value = (isOHLC ? arr[i][index] : arr[i]) - mean;
variance += value * value;
}
variance = variance / (arrLen - 1);
std = Math.sqrt(variance);
return std;
}
/* *
*
* Class
*
* */
/**
* Bollinger Bands series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.bb
*
* @augments Highcharts.Series
*/
var BBIndicator = /** @class */ (function (_super) {
__extends(BBIndicator, _super);
function BBIndicator() {
/* *
*
* Static Properties
*
* */
var _this = _super !== null && _super.apply(this,
arguments) || this;
/* *
*
* Properties
*
* */
_this.data = void 0;
_this.options = void 0;
_this.points = void 0;
return _this;
}
/* *
*
* Functions
*
* */
BBIndicator.prototype.init = function () {
SeriesRegistry.seriesTypes.sma.prototype.init.apply(this, arguments);
// Set default color for lines:
this.options = merge({
topLine: {
styles: {
lineColor: this.color
}
},
bottomLine: {
styles: {
lineColor: this.color
}
}
}, this.options);
};
BBIndicator.prototype.getValues = function (series, params) {
var period = params.period,
standardDeviation = params.standardDeviation,
xVal = series.xData,
yVal = series.yData,
yValLen = yVal ? yVal.length : 0,
// 0- date, 1-middle line, 2-top line, 3-bottom line
BB = [],
// middle line, top line and bottom line
ML,
TL,
BL,
date,
xData = [],
yData = [],
slicedX,
slicedY,
stdDev,
isOHLC,
point,
i;
if (xVal.length < period) {
return;
}
isOHLC = isArray(yVal[0]);
for (i = period; i <= yValLen; i++) {
slicedX = xVal.slice(i - period, i);
slicedY = yVal.slice(i - period, i);
point = SeriesRegistry.seriesTypes.sma.prototype.getValues.call(this, {
xData: slicedX,
yData: slicedY
}, params);
date = point.xData[0];
ML = point.yData[0];
stdDev = getStandardDeviation(slicedY, params.index, isOHLC, ML);
TL = ML + standardDeviation * stdDev;
BL = ML - standardDeviation * stdDev;
BB.push([date, TL, ML, BL]);
xData.push(date);
yData.push([TL, ML, BL]);
}
return {
values: BB,
xData: xData,
yData: yData
};
};
/**
* Bollinger bands (BB). This series requires the `linkedTo` option to be
* set and should be loaded after the `stock/indicators/indicators.js` file.
*
* @sample stock/indicators/bollinger-bands
* Bollinger bands
*
* @extends plotOptions.sma
* @since 6.0.0
* @product highstock
* @requires stock/indicators/indicators
* @requires stock/indicators/bollinger-bands
* @optionparent plotOptions.bb
*/
BBIndicator.defaultOptions = merge(SMAIndicator.defaultOptions, {
params: {
period: 20,
/**
* Standard deviation for top and bottom bands.
*/
standardDeviation: 2,
index: 3
},
/**
* Bottom line options.
*/
bottomLine: {
/**
* Styles for a bottom line.
*/
styles: {
/**
* Pixel width of the line.
*/
lineWidth: 1,
/**
* Color of the line. If not set, it's inherited from
* [plotOptions.bb.color](#plotOptions.bb.color).
*
* @type {Highcharts.ColorString}
*/
lineColor: void 0
}
},
/**
* Top line options.
*
* @extends plotOptions.bb.bottomLine
*/
topLine: {
styles: {
lineWidth: 1,
/**
* @type {Highcharts.ColorString}
*/
lineColor: void 0
}
},
tooltip: {
pointFormat: '<span style="color:{point.color}">\u25CF</span><b> {series.name}</b><br/>Top: {point.top}<br/>Middle: {point.middle}<br/>Bottom: {point.bottom}<br/>'
},
marker: {
enabled: false
},
dataGrouping: {
approximation: 'averages'
}
});
return BBIndicator;
}(SMAIndicator));
extend(BBIndicator.prototype, {
pointArrayMap: ['top', 'middle', 'bottom'],
pointValKey: 'middle',
nameComponents: ['period', 'standardDeviation'],
linesApiNames: ['topLine', 'bottomLine']
});
MultipleLinesComposition.compose(BBIndicator);
SeriesRegistry.registerSeriesType('bb', BBIndicator);
/* *
*
* Default Export
*
* */
/**
* A bollinger bands indicator. If the [type](#series.bb.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.bb
* @since 6.0.0
* @excluding dataParser, dataURL
* @product highstock
* @requires stock/indicators/indicators
* @requires stock/indicators/bollinger-bands
* @apioption series.bb
*/
''; // to include the above in the js output
return BBIndicator;
});
_registerModule(_modules, 'masters/indicators/bollinger-bands.src.js', [], function () {
});
})); | mit |
cdnjs/cdnjs | ajax/libs/react-imgix/8.6.4/constructUrl.js | 5003 | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.buildURLPublic = buildURLPublic;
exports.default = void 0;
var _extractQueryParams3 = _interopRequireDefault(require("./extractQueryParams"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
/*
Copyright © 2015 by Coursera
Licensed under the Apache License 2.0, seen https://github.com/coursera/react-imgix/blob/master/LICENSE
Minor syntax modifications have been made
*/
var Base64 = require("js-base64").Base64;
var PACKAGE_VERSION = "8.6.4";
// @see https://www.imgix.com/docs/reference
var PARAM_EXPANSION = Object.freeze({
// Adjustment
brightness: "bri",
contrast: "con",
exposure: "exp",
gamma: "gam",
highlights: "high",
hue: "hue",
invert: "invert",
saturation: "sat",
shaddows: "shad",
sharpness: "sharp",
"unsharp-mask": "usm",
"unsharp-radius": "usmrad",
vibrance: "vib",
// Automatic
"auto-features": "auto",
// Background
"background-color": "bg",
// Blend
blend: "blend",
"blend-mode": "bm",
"blend-align": "ba",
"blend-alpha": "balph",
"blend-padding": "bp",
"blend-width": "bw",
"blend-height": "bh",
"blend-fit": "bf",
"blend-crop": "bc",
"blend-size": "bs",
"blend-x": "bx",
"blend-y": "by",
// Border & Padding
border: "border",
padding: "pad",
// Face Detection
"face-index": "faceindex",
"face-padding": "facepad",
faces: "faces",
// Format
"chroma-subsampling": "chromasub",
"color-quantization": "colorquant",
download: "dl",
DPI: "dpi",
format: "fm",
"lossless-compression": "lossless",
quality: "q",
// Mask
"mask-image": "mask",
// Mask
"noise-blur": "nr",
"noise-sharpen": "nrs",
// Palette n/a
// PDF n/a
// Pixel Density n/a
// Rotation
"flip-direction": "flip",
orientation: "or",
"rotation-angle": "rot",
// Size
"crop-mode": "crop",
"fit-mode": "fit",
"image-height": "h",
"image-width": "w",
// Stylize
blurring: "blur",
halftone: "htn",
monotone: "mono",
pixelate: "px",
"sepia-tone": "sepia",
// Trim TODO
// Watermark TODO
// Extra
height: "h",
width: "w"
});
var DEFAULT_OPTIONS = Object.freeze({
auto: "format" // http://www.imgix.com/docs/reference/automatic#param-auto
});
/**
* Construct a URL for an image with an Imgix proxy, expanding image options
* per the [API reference docs](https://www.imgix.com/docs/reference).
* @param {String} src src of raw image
* @param {Object} longOptions map of image API options, in long or short form per expansion rules
* @return {String} URL of image src transformed by Imgix
*/
function constructUrl(src, longOptions) {
if (!src) {
return "";
}
var keys = Object.keys(longOptions);
var keysLength = keys.length;
var url = src + "?";
for (var i = 0; i < keysLength; i++) {
var key = keys[i];
var val = longOptions[key];
if (PARAM_EXPANSION[key]) {
key = PARAM_EXPANSION[key];
} else {
key = encodeURIComponent(key);
}
if (key.substr(-2) === "64") {
val = Base64.encodeURI(val);
}
url += key + "=" + encodeURIComponent(val) + "&";
}
return url.slice(0, -1);
}
function buildURLPublic(src) {
var imgixParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var disableLibraryParam = options.disableLibraryParam;
var _extractQueryParams = (0, _extractQueryParams3.default)(src),
_extractQueryParams2 = _slicedToArray(_extractQueryParams, 2),
rawSrc = _extractQueryParams2[0],
params = _extractQueryParams2[1];
return constructUrl(rawSrc, _extends({}, params, imgixParams, disableLibraryParam ? {} : {
ixlib: "react-".concat(PACKAGE_VERSION)
}));
}
var _default = constructUrl;
exports.default = _default;
//# sourceMappingURL=constructUrl.js.map | mit |
lfreneda/cepdb | api/v1/79033490.jsonp.js | 165 | jsonp({"cep":"79033490","logradouro":"Rua Tertuliana Ghersel Cattaneo","bairro":"Mata do Jacinto","cidade":"Campo Grande","uf":"MS","estado":"Mato Grosso do Sul"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/51345780.jsonp.js | 135 | jsonp({"cep":"51345780","logradouro":"Rua Alexandre Gusm\u00e3o","bairro":"COHAB","cidade":"Recife","uf":"PE","estado":"Pernambuco"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/21941562.jsonp.js | 134 | jsonp({"cep":"21941562","logradouro":"Rua Dois","bairro":"Itacolomi","cidade":"Rio de Janeiro","uf":"RJ","estado":"Rio de Janeiro"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/38700364.jsonp.js | 152 | jsonp({"cep":"38700364","logradouro":"Rua Patroc\u00ednio","bairro":"Santo Ant\u00f4nio","cidade":"Patos de Minas","uf":"MG","estado":"Minas Gerais"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/59122040.jsonp.js | 133 | jsonp({"cep":"59122040","logradouro":"Rua da Quadra","bairro":"Redinha","cidade":"Natal","uf":"RN","estado":"Rio Grande do Norte"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/96202330.jsonp.js | 145 | jsonp({"cep":"96202330","logradouro":"Rua Raul Barlem","bairro":"S\u00e3o Paulo","cidade":"Rio Grande","uf":"RS","estado":"Rio Grande do Sul"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/60184275.jsonp.js | 149 | jsonp({"cep":"60184275","logradouro":"Rua Maria Eunice dos Santos","bairro":"Vicente Pinzon","cidade":"Fortaleza","uf":"CE","estado":"Cear\u00e1"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/87206110.jsonp.js | 148 | jsonp({"cep":"87206110","logradouro":"Rua Tr\u00eas Marias","bairro":"Jardim C\u00e9u Azul","cidade":"Cianorte","uf":"PR","estado":"Paran\u00e1"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/86055752.jsonp.js | 143 | jsonp({"cep":"86055752","logradouro":"Rua do Guamirim","bairro":"Vivendas do Arvoredo","cidade":"Londrina","uf":"PR","estado":"Paran\u00e1"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/44013510.jsonp.js | 128 | jsonp({"cep":"44013510","logradouro":"Via Pedestre 30","bairro":"CIS","cidade":"Feira de Santana","uf":"BA","estado":"Bahia"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/12213631.jsonp.js | 181 | jsonp({"cep":"12213631","logradouro":"Rua P\u00f4r do Sol","bairro":"Conjunto Residencial Boa Vista","cidade":"S\u00e3o Jos\u00e9 dos Campos","uf":"SP","estado":"S\u00e3o Paulo"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/09431460.jsonp.js | 145 | jsonp({"cep":"09431460","logradouro":"Rua Universo","bairro":"Santa Luzia","cidade":"Ribeir\u00e3o Pires","uf":"SP","estado":"S\u00e3o Paulo"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/88812740.jsonp.js | 149 | jsonp({"cep":"88812740","logradouro":"Travessa Buenos Aires","bairro":"Buenos Aires","cidade":"Crici\u00fama","uf":"SC","estado":"Santa Catarina"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/80620360.jsonp.js | 156 | jsonp({"cep":"80620360","logradouro":"Rua Jo\u00e3o Ant\u00f4nio Xavier","bairro":"\u00c1gua Verde","cidade":"Curitiba","uf":"PR","estado":"Paran\u00e1"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/06886508.jsonp.js | 148 | jsonp({"cep":"06886508","logradouro":"Rua Varginha","bairro":"Potuver\u00e1","cidade":"Itapecerica da Serra","uf":"SP","estado":"S\u00e3o Paulo"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/62325000.jsonp.js | 84 | jsonp({"cep":"62325000","cidade":"Caruata\u00ed","uf":"CE","estado":"Cear\u00e1"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/75114040.jsonp.js | 154 | jsonp({"cep":"75114040","logradouro":"Avenida C","bairro":"JK Parque Industrial Nova Capital","cidade":"An\u00e1polis","uf":"GO","estado":"Goi\u00e1s"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/13323362.jsonp.js | 165 | jsonp({"cep":"13323362","logradouro":"Rua Fern\u00e3o \u00c1lvares de Andrade","bairro":"Jardim Santa Marta","cidade":"Salto","uf":"SP","estado":"S\u00e3o Paulo"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/86812548.jsonp.js | 143 | jsonp({"cep":"86812548","logradouro":"Rua Carlos Zanon","bairro":"Jardim Colonial II","cidade":"Apucarana","uf":"PR","estado":"Paran\u00e1"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/26061200.jsonp.js | 143 | jsonp({"cep":"26061200","logradouro":"Rua Graziela","bairro":"Miguel Couto","cidade":"Nova Igua\u00e7u","uf":"RJ","estado":"Rio de Janeiro"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/35164246.jsonp.js | 143 | jsonp({"cep":"35164246","logradouro":"Rua Wilson Teixeira","bairro":"Jardim Panorama","cidade":"Ipatinga","uf":"MG","estado":"Minas Gerais"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/96072052.jsonp.js | 137 | jsonp({"cep":"96072052","logradouro":"Rua Doze","bairro":"Tr\u00eas Vendas","cidade":"Pelotas","uf":"RS","estado":"Rio Grande do Sul"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/82030274.jsonp.js | 143 | jsonp({"cep":"82030274","logradouro":"Rua Paulo Wasserman","bairro":"Santa Felicidade","cidade":"Curitiba","uf":"PR","estado":"Paran\u00e1"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/31730120.jsonp.js | 144 | jsonp({"cep":"31730120","logradouro":"Rua Pedro Labatut","bairro":"Campo Alegre","cidade":"Belo Horizonte","uf":"MG","estado":"Minas Gerais"});
| cc0-1.0 |
chgu82837/Class_CloudCompute_Works | HW1_PythonHW1_s101056017/PythonHW1_s101056017.py | 3282 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from Tkinter import *
import random
Proj_name = "PythonHW1_s101056017 ID generator"
random.seed()
root = Tk(Proj_name)
sex = 0
sexOption = [1,2]
sexOptionBtn = []
locationOption = [
# [ID,Location_name],
['F',"新北市"],
['A','臺北市'],
['B','臺中市'],
['C','基隆市'],
['D','臺南市'],
['E','高雄市'],
['G','宜蘭市'],
['H','桃園市'],
['I','嘉義市'],
['J','新竹縣'],
['K','苗栗縣'],
['M','南投縣'],
['N','彰化縣'],
['O','新竹市'],
['P','雲林縣'],
['Q','嘉義縣'],
['T','屏東縣'],
['U','花蓮縣'],
['V','臺東縣'],
['W','金門縣'],
['X','澎湖縣'],
['Z','連江縣'],
['L','臺中縣'],
['R','臺南縣'],
['S','高雄縣'],
['Y','陽明山管理局'],
]
locationLabel = Label(root,text="Location:")
hintLabel = Label(root,text="Generate ID randomly:")
locationList = Listbox(root,selectmode=SINGLE)
resultLabel = Label(root,text="")
for l in locationOption:
locationList.insert(END,l[1])
sexFrame = Frame(root)
def clearSex():
global sex
sex = 0
for b in sexOptionBtn:
b['text'] = b['text'].replace("*","")
def setSexOpt(i):
global sex
clearSex()
sex = sexOption[i]
sexOptionBtn[i]['text'] = "%s*" % sexOptionBtn[i]['text']
maleBtn = Button(sexFrame,text="Man",command=lambda:setSexOpt(0))
sexOptionBtn.append(maleBtn)
femaleBtn = Button(sexFrame,text="Woman",command=lambda:setSexOpt(1))
sexOptionBtn.append(femaleBtn)
def clear():
selected = locationList.curselection()
if selected:
locationList.selection_clear(selected[0])
clearSex()
clearBtn = Button(root,height=1,text="Clear",command=clear)
def chk(alpha,sex_val):
id=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
num=[10, 11, 12, 13, 14, 15, 16, 17, 34, 18, 19, 20, 21, 22, 35, 23, 24, 25, 26, 27, 28, 29, 32, 30, 31, 33]
a2n=dict(zip(id, num))
# alpha = random.choice(id)
r = [sex_val]+random.sample(range(0, 10), 7)
k = [ v*(8-i) for i,v in enumerate(r) ]
chk = (a2n[alpha]/10)+(a2n[alpha]%10*9) + sum(k)
chk = (10 - (chk % 10)) % 10
return alpha+''.join(map(str, r))+str(chk)
def gen_digi():
return random.randint(0,9)
def gen():
selected = locationList.curselection()
if selected:
selected = selected[0]
else:
selected = random.randint(0,len(locationOption) - 1)
locationChar = locationOption[selected][0]
if sex:
sex_val = sex
else:
sex_val = sexOption[random.randint(0,len(sexOption) - 1)]
result = chk(locationChar,sex_val)
# print(result,sex)
resultLabel['text'] = result
genBtn = Button(root,text="Generate!",command=gen)
locationLabel.pack(side='top',fill=BOTH)
locationList.pack(side='top',fill=BOTH,expand=1)
sexFrame.pack(side='top',fill=BOTH)
maleBtn.pack(side='left',fill=BOTH,expand=1)
femaleBtn.pack(side='left',fill=BOTH,expand=1)
clearBtn.pack(side='top',fill=BOTH)
genBtn.pack(side='top',fill=BOTH)
hintLabel.pack(side='top',fill=BOTH)
resultLabel.pack(side='top',fill=BOTH)
root.minsize(200, 400)
root.mainloop()
| cc0-1.0 |
lfreneda/cepdb | api/v1/87075790.jsonp.js | 157 | jsonp({"cep":"87075790","logradouro":"Rua Jos\u00e9 Antonio Rodrigues","bairro":"Jardim Everest","cidade":"Maring\u00e1","uf":"PR","estado":"Paran\u00e1"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/12093200.jsonp.js | 166 | jsonp({"cep":"12093200","logradouro":"Rua Ant\u00f4nio Mello J\u00fanior","bairro":"Morada dos Nobres","cidade":"Taubat\u00e9","uf":"SP","estado":"S\u00e3o Paulo"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/13480385.jsonp.js | 155 | jsonp({"cep":"13480385","logradouro":"Rua Carolina Kuntz Busch","bairro":"Vila S\u00e3o Geraldo","cidade":"Limeira","uf":"SP","estado":"S\u00e3o Paulo"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/74474384.jsonp.js | 149 | jsonp({"cep":"74474384","logradouro":"Rua RB 49","bairro":"Residencial Recanto do Bosque","cidade":"Goi\u00e2nia","uf":"GO","estado":"Goi\u00e1s"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/13053241.jsonp.js | 156 | jsonp({"cep":"13053241","logradouro":"Avenida Jos\u00e9 Lopes Serra","bairro":"Vila Palmeiras I","cidade":"Campinas","uf":"SP","estado":"S\u00e3o Paulo"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/87083675.jsonp.js | 155 | jsonp({"cep":"87083675","logradouro":"Rua Pioneiro Olinto Mariani","bairro":"Jardim Monte Rei","cidade":"Maring\u00e1","uf":"PR","estado":"Paran\u00e1"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/13061352.jsonp.js | 160 | jsonp({"cep":"13061352","logradouro":"Rua Canind\u00e9","bairro":"Vila Padre Manoel de N\u00f3brega","cidade":"Campinas","uf":"SP","estado":"S\u00e3o Paulo"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/78115831.jsonp.js | 152 | jsonp({"cep":"78115831","logradouro":"Rua Jaime Campos","bairro":"Cassira L\u00facia","cidade":"V\u00e1rzea Grande","uf":"MT","estado":"Mato Grosso"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/41120095.jsonp.js | 151 | jsonp({"cep":"41120095","logradouro":"2\u00aa Travessa S\u00e3o Raimundo","bairro":"Pernambu\u00e9s","cidade":"Salvador","uf":"BA","estado":"Bahia"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/72862516.jsonp.js | 144 | jsonp({"cep":"72862516","logradouro":"Quadra Quadra 16","bairro":"Loteamento Lunabel 3","cidade":"Novo Gama","uf":"GO","estado":"Goi\u00e1s"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/74974270.jsonp.js | 155 | jsonp({"cep":"74974270","logradouro":"Rua Piau\u00ed","bairro":"Setor dos Estados","cidade":"Aparecida de Goi\u00e2nia","uf":"GO","estado":"Goi\u00e1s"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/30820050.jsonp.js | 166 | jsonp({"cep":"30820050","logradouro":"Rua Crucifica\u00e7\u00e3o","bairro":"Jardim S\u00e3o Jos\u00e9","cidade":"Belo Horizonte","uf":"MG","estado":"Minas Gerais"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/90690390.jsonp.js | 151 | jsonp({"cep":"90690390","logradouro":"Rua Mariz e Barros","bairro":"Petr\u00f3polis","cidade":"Porto Alegre","uf":"RS","estado":"Rio Grande do Sul"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/28907250.jsonp.js | 136 | jsonp({"cep":"28907250","logradouro":"Avenida do Contorno","bairro":"Braga","cidade":"Cabo Frio","uf":"RJ","estado":"Rio de Janeiro"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/26315608.jsonp.js | 136 | jsonp({"cep":"26315608","logradouro":"Rua S\u00e1tiro","bairro":"Queimados","cidade":"Queimados","uf":"RJ","estado":"Rio de Janeiro"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/69073381.jsonp.js | 130 | jsonp({"cep":"69073381","logradouro":"Beco Santa Rita","bairro":"Bet\u00e2nia","cidade":"Manaus","uf":"AM","estado":"Amazonas"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/07123170.jsonp.js | 146 | jsonp({"cep":"07123170","logradouro":"Rua Praia Grande","bairro":"Jardim Santa Clara","cidade":"Guarulhos","uf":"SP","estado":"S\u00e3o Paulo"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/65913350.jsonp.js | 142 | jsonp({"cep":"65913350","logradouro":"Rua do Sol","bairro":"Jardim Morada do Sol","cidade":"Imperatriz","uf":"MA","estado":"Maranh\u00e3o"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/58407520.jsonp.js | 152 | jsonp({"cep":"58407520","logradouro":"Rua Professor Miron","bairro":"Jos\u00e9 Pinheiro","cidade":"Campina Grande","uf":"PB","estado":"Para\u00edba"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/95060580.jsonp.js | 156 | jsonp({"cep":"95060580","logradouro":"Rua Padre Jos\u00e9 Lorencini","bairro":"Ana Rech","cidade":"Caxias do Sul","uf":"RS","estado":"Rio Grande do Sul"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/14020489.jsonp.js | 156 | jsonp({"cep":"14020489","logradouro":"Rua Aziz Secaf","bairro":"Jardim S\u00e3o Luiz","cidade":"Ribeir\u00e3o Preto","uf":"SP","estado":"S\u00e3o Paulo"});
| cc0-1.0 |