code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
import * as React from 'react'
import {Component, ComponentClass, createElement} from 'react'
import * as PropTypes from 'prop-types'
import {connect} from 'react-redux'
import {Store} from '../store'
import ComputedState from '../model/ComputedState'
function connectToStore<P>(component:ComponentClass<P>):ComponentClass<P> {
type PS = P & {store:Store}
const mapStateToProps = (state:ComputedState, ownProps:PS):P => ({
...Object(ownProps),
...state
})
const WrappedComponent = (props:P) => createElement(component, props)
const ConnectedComponent = connect(mapStateToProps)(WrappedComponent)
return class ConnectToStore extends Component<P, any> {
static contextTypes = {
rrnhStore: PropTypes.object.isRequired
}
render() {
const {rrnhStore} = this.context
return <ConnectedComponent store={rrnhStore} {...this.props} />
}
}
}
export default connectToStore | kenfehling/react-router-nested-history | src/react/connectToStore.tsx | TypeScript | mit | 921 |
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app/app.module';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);
| fabricadecodigo/angular2-examples | ToDoAppWithFirebase/src/main.ts | TypeScript | mit | 242 |
from behave import given, when, then
from genosdb.models import User
from genosdb.exceptions import UserNotFound
# 'mongodb://localhost:27017/')
@given('a valid user with values {username}, {password}, {email}, {first_name}, {last_name}')
def step_impl(context, username, password, email, first_name, last_name):
context.base_user = User(username=username, email=email, password=password, first_name=first_name,
last_name=last_name)
@when('I add the user to the collection')
def step_impl(context):
context.user_service.save(context.base_user)
@then('I check {user_name} exists')
def step_impl(context, user_name):
user_exists = context.user_service.exists(user_name)
assert context.base_user.username == user_exists['username']
assert context.base_user.password == user_exists['password']
assert context.base_user.email == user_exists['email']
assert context.base_user.first_name == user_exists['first_name']
assert context.base_user.last_name == user_exists['last_name']
assert user_exists['_id'] is not None
@given('I update {username} {field} with {value}')
def step_impl(context, username, field, value):
user = context.user_service.exists(username)
if user is not None:
user[field] = value
context.user_service.update(user.to_json())
else:
raise UserNotFound(username, "User was not found")
@then('I check {username} {field} is {value}')
def step_impl(context, username, field, value):
user = context.user_service.exists(username)
if user is not None:
assert user[field] == value
else:
raise UserNotFound(username, "User was not found")
| jonrf93/genos | dbservices/tests/functional_tests/steps/user_service_steps.py | Python | mit | 1,685 |
using Mokkosu.AST;
using System.Collections.Generic;
using System.Text;
namespace Mokkosu.ClosureConversion
{
class ClosureConversionResult
{
public Dictionary<string, MExpr> FunctionTable { get; private set; }
public MExpr Main { get; private set; }
public ClosureConversionResult(Dictionary<string, MExpr> table, MExpr main)
{
FunctionTable = table;
Main = main;
}
public override string ToString()
{
var sb = new StringBuilder();
foreach (var item in FunctionTable)
{
sb.AppendFormat("=== {0} ===\n", item.Key);
sb.Append(item.Value);
sb.Append("\n");
}
sb.Append("=== Main ===\n");
sb.Append(Main);
return sb.ToString();
}
}
}
| lambdataro/Mokkosu | VS2013/MokkosuCore/ClosureConversion/ClosureConversionResult.cs | C# | mit | 870 |
package com.ov3rk1ll.kinocast.ui.util.glide;
import com.ov3rk1ll.kinocast.data.ViewModel;
public class ViewModelGlideRequest {
private ViewModel viewModel;
private int screenWidthPx;
private String type;
public ViewModelGlideRequest(ViewModel viewModel, int screenWidthPx, String type) {
this.viewModel = viewModel;
this.screenWidthPx = screenWidthPx;
this.type = type;
}
ViewModel getViewModel() {
return viewModel;
}
int getScreenWidthPx() {
return screenWidthPx;
}
public String getType() {
return type;
}
} | ov3rk1ll/KinoCast | app/src/main/java/com/ov3rk1ll/kinocast/ui/util/glide/ViewModelGlideRequest.java | Java | mit | 609 |
package stat
import (
"fmt"
"time"
// "encoding/json"
)
type RevStat struct {
RevId string `json:"RevId"`
UserName string `json:"UserName"`
WordCount int `json:"WordCount"`
ModDate string `json:"ModDate"`
WordFreq []WordPair `json:"WordFreq"`
}
type DocStat struct {
FileId string `json:"FileId"`
Title string `json:"Title"`
LastMod string `json:"LastMod"`
RevList []RevStat `json:"RevList"`
}
func (rev RevStat) GetTime() string {
x, _ := time.Parse("2006-01-02T15:04:05.000Z", rev.ModDate)
return x.Format("15:04")
}
func (rev RevStat) String() string {
return fmt.Sprintf("[%s %s] %d words by %s. \n\t Words [%s]", rev.ModDate, rev.RevId, rev.WordCount, rev.UserName, rev.WordFreq)
}
func (doc DocStat) String() string {
s := fmt.Sprintf("[%s] '%s' last mod on %s with revs\n", doc.FileId, doc.Title, doc.LastMod)
for i, v := range doc.RevList {
s += fmt.Sprintf("\t %d:%s\n", i, v)
}
return s
}
| Kimau/GoDriveTracker | stat/stat.go | GO | mit | 964 |
package ru.lanbilling.webservice.wsdl;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ret" type="{urn:api3}soapDocument" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"ret"
})
@XmlRootElement(name = "getClientDocumentsResponse")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public class GetClientDocumentsResponse {
@XmlElement(required = true)
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
protected List<SoapDocument> ret;
/**
* Gets the value of the ret property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the ret property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRet().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SoapDocument }
*
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public List<SoapDocument> getRet() {
if (ret == null) {
ret = new ArrayList<SoapDocument>();
}
return this.ret;
}
}
| kanonirov/lanb-client | src/main/java/ru/lanbilling/webservice/wsdl/GetClientDocumentsResponse.java | Java | mit | 2,281 |
#include "ToolbarPanel.h"
#include "StagePanel.h"
#include "SelectSpritesOP.h"
#include "Context.h"
namespace coceditor
{
ToolbarPanel::ToolbarPanel(wxWindow* parent)
: ee::ToolbarPanel(parent, Context::Instance()->stage)
{
Context* context = Context::Instance();
// addChild(new ee::UniversalCMPT(this, wxT("paste"), context->stage,
// new ee::ArrangeSpriteOP<ee::SelectSpritesOP>(context->stage, context->stage)));
addChild(new ee::UniversalCMPT(this, wxT("paste"), context->stage,
new ee::ArrangeSpriteOP<SelectSpritesOP>(context->stage, context->stage, context->property)));
SetSizer(initLayout());
}
wxSizer* ToolbarPanel::initLayout()
{
wxBoxSizer* topSizer = new wxBoxSizer(wxVERTICAL);
topSizer->Add(initChildrenLayout());
return topSizer;
}
} // coceditor | xzrunner/easyeditor | coceditor/src/coceditor/ToolbarPanel.cpp | C++ | mit | 785 |
using System.IO;
using System.Diagnostics;
using NDepend.Path;
namespace NDepend.Test.Unit {
public static class DirForTest {
public static IAbsoluteDirectoryPath ExecutingAssemblyDir {
get {
// If this following line doesn't work, it is because of ShadowCopyCache with NUnit
return System.Reflection.Assembly.GetExecutingAssembly().Location.ToAbsoluteFilePath().ParentDirectoryPath;
}
}
public static IAbsoluteFilePath ExecutingAssemblyFilePath {
get {
return ExecutingAssemblyDir.GetChildFileWithName(ExecutingAssemblyFileName);
}
}
private static string ExecutingAssemblyFileName {
get {
string executingAssemblyFileLocation = System.Reflection.Assembly.GetExecutingAssembly().Location;
return System.IO.Path.GetFileName(executingAssemblyFileLocation);
}
}
public static IAbsoluteDirectoryPath DirAbsolute {
get {
return Dir.ToAbsoluteDirectoryPath();
}
}
public static string Dir {
get {
return ExecutingAssemblyDir.GetChildDirectoryWithName("DirForTest").ToString();
}
}
public static IAbsoluteDirectoryPath GetDirOfUnitTestWithName(string unitTestName) {
IAbsoluteDirectoryPath ndependRootPath = ExecutingAssemblyDir.ParentDirectoryPath;
IAbsoluteDirectoryPath unitTestPath = ndependRootPath.GetChildDirectoryWithName("NDepend.Test.Dirs");
IAbsoluteDirectoryPath result = unitTestPath.GetChildDirectoryWithName(unitTestName);
Debug.Assert(result.Exists);
return result;
}
public static IAbsoluteDirectoryPath GetBinDebugDir() {
IAbsoluteDirectoryPath binDebug = DirAbsolute.ParentDirectoryPath.GetChildDirectoryWithName("Debug");
Debug.Assert(binDebug.Exists);
return binDebug;
}
public static void EnsureDirForTestExistAndEmpty() {
string dir = Dir;
RETRY: // 29Nov2010: retry until it is ok!!
try {
// Clear the older dir
if (!Directory.Exists(dir)) {
Directory.CreateDirectory(dir);
} else {
var subDirs = Directory.GetDirectories(dir);
var subFiles = Directory.GetFiles(dir);
if (subFiles.Length > 0) {
foreach (var filePath in subFiles) {
File.Delete(filePath);
}
}
if (subDirs.Length > 0) {
foreach (var dirPath in subDirs) {
Directory.Delete(dirPath, true);
}
}
}
if (!Directory.Exists(dir)) { goto RETRY; }
if (Directory.GetDirectories(dir).Length > 0) { goto RETRY; }
if (Directory.GetFiles(dir).Length > 0) { goto RETRY; }
} catch {
goto RETRY;
}
var dirInfo = new DirectoryInfo(dir);
Debug.Assert(dirInfo.Exists);
Debug.Assert(dirInfo.GetFiles().Length == 0);
Debug.Assert(dirInfo.GetDirectories().Length == 0);
}
public static void Delete() {
string dir = Dir;
if (Directory.Exists(dir)) {
Directory.Delete(dir, true);
}
}
public static string ExecutingAssemblyFilePathInDirForTest {
get {
return Dir.ToAbsoluteDirectoryPath().GetChildFileWithName(ExecutingAssemblyFileName).ToString();
}
}
public static void CopyExecutingAssemblyFileInDirForTest() {
File.Copy(ExecutingAssemblyDir.GetChildFileWithName(ExecutingAssemblyFileName).ToString(),
ExecutingAssemblyFilePathInDirForTest);
}
}
}
| psmacchia/NDepend.Path | NDepend.Path.Tests/DirForTest.cs | C# | mit | 3,806 |
require 'statsample'
module Grid
class Row
attr_reader :top_y, :bottom_y
def initialize(item)
@data = []
self << item
end
def <<(item)
@data << item
@top_y = quartiles_meam(@data.map(&:y))
@bottom_y = quartiles_meam(@data.map{|item| item.y + item.height})
end
def inbound_y?(y)
@top_y <= y && y <= @bottom_y
end
def include?(item)
@data.include?(item)
end
def height
@bottom_y - @top_y
end
private
def quartiles_meam(array)
quartiles(array).to_scale.mean
end
def quartiles(array)
return array if array.size < 7
lower = (array.size - 3)/4
upper = lower * 3 + 3
array[lower..upper]
end
end
end
| xli/ewall | lib/grid/row.rb | Ruby | mit | 746 |
/* ========================================
* File Name : B.cpp
* Creation Date : 16-11-2020
* Last Modified : Po 16. listopadu 2020, 01:03:10
* Created By : Karel Ha <mathemage@gmail.com>
* URL : https://codeforces.com/problemset/problem/1296/B
* Points Gained (in case of online contest) : AC
==========================================*/
#include <bits/stdc++.h>
using namespace std;
#define REP(I,N) FOR(I,0,N)
#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define ALL(A) (A).begin(), (A).end()
#define MSG(a) cout << #a << " == " << (a) << endl;
const int CLEAN = -1;
template <typename T>
string NumberToString ( T Number ) {
ostringstream ss;
ss << Number;
return ss.str();
}
#define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); }
vector<string> split(const string& s, char c) {
vector<string> v;
stringstream ss(s);
string x;
while (getline(ss, x, c))
v.emplace_back(x);
return move(v);
}
void err(vector<string>::iterator it) {}
template<typename T, typename... Args>
void err(vector<string>::iterator it, T a, Args... args) {
cout << it -> substr((*it)[0] == ' ', it -> length()) << " = " << a << endl;
err(++it, args...);
}
int solve(int s) {
if (s < 10) {
return s;
}
int x = s - s % 10;
return x + solve(s - x + x / 10);
}
int main() {
int t;
cin >> t;
while (t--) {
int s;
cin >> s;
cout << solve(s) << endl;
}
return 0;
}
| mathemage/CompetitiveProgramming | codeforces/div3/1296/B/B.cpp | C++ | mit | 1,574 |
# frozen_string_literal: true
module Wardrobe
module Plugins
module Validation
module Refinements
refine NilClass do
def filled?
'must be filled'
end
def empty?
# Nil is valid as empty
end
end
end
end
end
end
| agensdev/wardrobe | lib/wardrobe/plugins/validation/refinements/nil_class.rb | Ruby | mit | 315 |
from rest_framework.filters import (
FilterSet
)
from trialscompendium.trials.models import Treatment
class TreatmentListFilter(FilterSet):
"""
Filter query list from treatment database table
"""
class Meta:
model = Treatment
fields = {'id': ['exact', 'in'],
'no_replicate': ['exact', 'in', 'gte', 'lte'],
'nitrogen_treatment': ['iexact', 'in', 'icontains'],
'phosphate_treatment': ['iexact', 'in', 'icontains'],
'tillage_practice': ['iexact', 'in', 'icontains'],
'cropping_system': ['iexact', 'in', 'icontains'],
'crops_grown': ['iexact', 'in', 'icontains'],
'farm_yard_manure': ['iexact', 'in', 'icontains'],
'farm_residue': ['iexact', 'in', 'icontains'],
}
order_by = ['tillage_practice', 'cropping_system', 'crops_grown']
| nkoech/trialscompendium | trialscompendium/trials/api/treatment/filters.py | Python | mit | 934 |
import React, { Component } from 'react';
class Main extends Component {
render() {
return (
<main className='Main'>
<h1 className='Main-headline'>Web solutions focused on<br/>Simplicity & Reliability.</h1>
<h2 className='Main-subhead'>Bleeding edge technology paired with amazing <em>talent</em> and <em>creativity</em>.</h2>
<a href='#' className='Main-button'>Work With Us</a>
</main>
);
}
}
export default Main;
| qubed-inc/qubed-io | src/Main/index.js | JavaScript | mit | 466 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SendGrid Webhook Example")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Stack Solutions - www.stack-solutions.com")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5e2f0c44-ee9f-43b9-815e-c862ed19a18b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| paully21/SendGridWebHookExample | Website/Properties/AssemblyInfo.cs | C# | mit | 1,401 |
'use strict';
angular.module('main', ['ngRoute', 'ngResource', 'ui.route', 'main.system', 'main.index', 'main.events']);
angular.module('main.system', []);
angular.module('main.index', []);
angular.module('main.events', []);
'use strict';
//Setting HTML5 Location Mode
angular.module('main').config(['$locationProvider',
function ($locationProvider) {
$locationProvider.hashPrefix('!');
}
]);
'use strict';
angular.module('main.system')
.factory('Global', [
function () {
var obj = this;
obj._data = {
app: window.app || false
};
return obj._data;
}
]);
'use strict';
angular.element(document).ready(function() {
//Fixing facebook bug with redirect
if (window.location.hash === '#_=_') window.location.hash = '#!';
//Then init the app
angular.bootstrap(document, ['main']);
});
'use strict';
angular.module('main').config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '/views/index.html'
})
.otherwise({
redirectTo: '/'
});
}
]);
'use strict';
angular.module('main.index')
.controller('IndexCtrl', ['$scope', '$routeParams', '$http', '$location', 'Global', 'Event',
function ($scope, $routeParams, $http, $location, Global, Event) {
$scope.global = Global;
$scope.getEvents = function(){
Event.query(function(data){
$scope.events = data;
});
};
$scope.init = function(){
$scope.getEvents();
};
}
]);
'use strict';
angular.module('main.events')
.factory('Event', [
'$resource',
function ($resource) {
return $resource("/api/events/:id");
}
]); | NevadaCountyHackers/hackers-web-app | public/dist/app.js | JavaScript | mit | 1,912 |
/**
* StaticText.js
* Text that cannot be changed after loaded by the game
*/
import GamePiece from './GamePiece.js';
import Info from './Info.js';
import Text from './Text.js';
export default class StaticText extends Text {
constructor (config) {
super(config);
this.static = true;
}
}
| javisaurusrex/zookillsoccer | modules/js/StaticText.js | JavaScript | mit | 305 |
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\Core\Tests\Metadata\Property\Factory;
use ApiPlatform\Core\Metadata\Property\Factory\CachedPropertyNameCollectionFactory;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Core\Metadata\Property\PropertyNameCollection;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy;
use ApiPlatform\Core\Tests\ProphecyTrait;
use PHPUnit\Framework\TestCase;
use Psr\Cache\CacheException;
use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;
/**
* @author Baptiste Meyer <baptiste.meyer@gmail.com>
*/
class CachedPropertyNameCollectionFactoryTest extends TestCase
{
use ProphecyTrait;
public function testCreateWithItemHit()
{
$cacheItem = $this->prophesize(CacheItemInterface::class);
$cacheItem->isHit()->willReturn(true)->shouldBeCalled();
$cacheItem->get()->willReturn(new PropertyNameCollection(['id', 'name', 'description', 'dummy']))->shouldBeCalled();
$cacheItemPool = $this->prophesize(CacheItemPoolInterface::class);
$cacheItemPool->getItem($this->generateCacheKey())->willReturn($cacheItem->reveal())->shouldBeCalled();
$decoratedPropertyNameCollectionFactory = $this->prophesize(PropertyNameCollectionFactoryInterface::class);
$cachedPropertyNameCollectionFactory = new CachedPropertyNameCollectionFactory($cacheItemPool->reveal(), $decoratedPropertyNameCollectionFactory->reveal());
$resultedPropertyNameCollection = $cachedPropertyNameCollectionFactory->create(Dummy::class);
$expectedResult = new PropertyNameCollection(['id', 'name', 'description', 'dummy']);
$this->assertEquals($expectedResult, $resultedPropertyNameCollection);
$this->assertEquals($expectedResult, $cachedPropertyNameCollectionFactory->create(Dummy::class), 'Trigger the local cache');
}
public function testCreateWithItemNotHit()
{
$resourceNameCollection = new PropertyNameCollection(['id', 'name', 'description', 'dummy']);
$decoratedPropertyNameCollectionFactory = $this->prophesize(PropertyNameCollectionFactoryInterface::class);
$decoratedPropertyNameCollectionFactory->create(Dummy::class, [])->willReturn($resourceNameCollection)->shouldBeCalled();
$cacheItem = $this->prophesize(CacheItemInterface::class);
$cacheItem->isHit()->willReturn(false)->shouldBeCalled();
$cacheItem->set($resourceNameCollection)->willReturn($cacheItem->reveal())->shouldBeCalled();
$cacheItemPool = $this->prophesize(CacheItemPoolInterface::class);
$cacheItemPool->getItem($this->generateCacheKey())->willReturn($cacheItem->reveal())->shouldBeCalled();
$cacheItemPool->save($cacheItem->reveal())->willReturn(true)->shouldBeCalled();
$cachedPropertyNameCollectionFactory = new CachedPropertyNameCollectionFactory($cacheItemPool->reveal(), $decoratedPropertyNameCollectionFactory->reveal());
$resultedPropertyNameCollection = $cachedPropertyNameCollectionFactory->create(Dummy::class);
$expectedResult = new PropertyNameCollection(['id', 'name', 'description', 'dummy']);
$this->assertEquals($expectedResult, $resultedPropertyNameCollection);
$this->assertEquals($expectedResult, $cachedPropertyNameCollectionFactory->create(Dummy::class), 'Trigger the local cache');
}
public function testCreateWithGetCacheItemThrowsCacheException()
{
$decoratedPropertyNameCollectionFactory = $this->prophesize(PropertyNameCollectionFactoryInterface::class);
$decoratedPropertyNameCollectionFactory->create(Dummy::class, [])->willReturn(new PropertyNameCollection(['id', 'name', 'description', 'dummy']))->shouldBeCalled();
$cacheException = new class() extends \Exception implements CacheException {};
$cacheItemPool = $this->prophesize(CacheItemPoolInterface::class);
$cacheItemPool->getItem($this->generateCacheKey())->willThrow($cacheException)->shouldBeCalled();
$cachedPropertyNameCollectionFactory = new CachedPropertyNameCollectionFactory($cacheItemPool->reveal(), $decoratedPropertyNameCollectionFactory->reveal());
$resultedPropertyNameCollection = $cachedPropertyNameCollectionFactory->create(Dummy::class);
$expectedResult = new PropertyNameCollection(['id', 'name', 'description', 'dummy']);
$this->assertEquals($expectedResult, $resultedPropertyNameCollection);
$this->assertEquals($expectedResult, $cachedPropertyNameCollectionFactory->create(Dummy::class), 'Trigger the local cache');
}
private function generateCacheKey(string $resourceClass = Dummy::class, array $options = [])
{
return CachedPropertyNameCollectionFactory::CACHE_KEY_PREFIX.md5(serialize([$resourceClass, $options]));
}
}
| vincentchalamon/core | tests/Metadata/Property/Factory/CachedPropertyNameCollectionFactoryTest.php | PHP | mit | 5,079 |
<?php
namespace Tests\Behat\Mink;
use Behat\Mink\Session;
/**
* @group unittest
*/
class SessionTest extends \PHPUnit_Framework_TestCase
{
private $driver;
private $selectorsHandler;
private $session;
protected function setUp()
{
$this->driver = $this->getMockBuilder('Behat\Mink\Driver\DriverInterface')->getMock();
$this->selectorsHandler = $this->getMockBuilder('Behat\Mink\Selector\SelectorsHandler')->getMock();
$this->session = new Session($this->driver, $this->selectorsHandler);
}
public function testGetDriver()
{
$this->assertSame($this->driver, $this->session->getDriver());
}
public function testGetPage()
{
$this->assertInstanceOf('Behat\Mink\Element\DocumentElement', $this->session->getPage());
}
public function testGetSelectorsHandler()
{
$this->assertSame($this->selectorsHandler, $this->session->getSelectorsHandler());
}
public function testVisit()
{
$this->driver
->expects($this->once())
->method('visit')
->with($url = 'some_url');
$this->session->visit($url);
}
public function testReset()
{
$this->driver
->expects($this->once())
->method('reset');
$this->session->reset();
}
public function testGetResponseHeaders()
{
$this->driver
->expects($this->once())
->method('getResponseHeaders')
->will($this->returnValue($ret = array(2, 3, 4)));
$this->assertEquals($ret, $this->session->getResponseHeaders());
}
public function testGetStatusCode()
{
$this->driver
->expects($this->once())
->method('getStatusCode')
->will($this->returnValue($ret = 404));
$this->assertEquals($ret, $this->session->getStatusCode());
}
public function testGetCurrentUrl()
{
$this->driver
->expects($this->once())
->method('getCurrentUrl')
->will($this->returnValue($ret = 'http://some.url'));
$this->assertEquals($ret, $this->session->getCurrentUrl());
}
public function testExecuteScript()
{
$this->driver
->expects($this->once())
->method('executeScript')
->with($arg = 'JS');
$this->session->executeScript($arg);
}
public function testEvaluateScript()
{
$this->driver
->expects($this->once())
->method('evaluateScript')
->with($arg = 'JS func')
->will($this->returnValue($ret = '23'));
$this->assertEquals($ret, $this->session->evaluateScript($arg));
}
public function testWait()
{
$this->driver
->expects($this->once())
->method('wait')
->with(1000, 'function() {}');
$this->session->wait(1000, 'function() {}');
}
}
| lrt/lrt | vendor/behat/mink/tests/Behat/Mink/SessionTest.php | PHP | mit | 3,095 |
<?php
namespace DuxCms\Model;
use Think\Model;
/**
* 扩展字段数据操作
*/
class FieldDataModel extends Model {
//设置操作表
public function setTable($name) {
$this->trueTableName = $this->tablePrefix.'ext_'.$name;
}
/**
* 获取列表
* @return array 列表
*/
public function loadList($where,$limit = 0,$order='data_id DESC'){
return $this->where($where)->limit($limit)->order($order)->select();
}
/**
* 获取数量
* @return array 数量
*/
public function countList($where){
return $this->where($where)->count();
}
/**
* 获取信息
* @param int $dataId ID
* @return array 信息
*/
public function getInfo($dataId)
{
$map = array();
$map['data_id'] = $dataId;
return $this->where($map)->find();
}
/**
* 更新信息
* @param string $type 更新类型
* @param array $fieldsetInfo 字段信息
* @param bool $prefix POST前缀
* @return bool 更新状态
*/
public function saveData($type = 'add' , $fieldsetInfo){
//获取字段列表
$fieldList=D('DuxCms/Field')->loadList('fieldset_id='.$fieldsetInfo['fieldset_id']);
if(empty($fieldList)||!is_array($fieldList)){
return;
}
//设置数据列表
$valiRules = array();
$autoRules = array();
$data = array();
foreach ($fieldList as $value) {
$data[$value['field']] = I('Fieldset_'.$value['field']);
$verify_data = base64_decode($value['verify_data']);
if($verify_data){
$valiRules[] = array($value['field'], $verify_data ,$value['errormsg'],$value['verify_condition'],$value['verify_type'],3);
}
$autoRules[] = array($value['field'],'formatField',3,'callback',array($value['field'],$value['type']));
}
$data = $this->auto($autoRules)->validate($valiRules)->create($data);
if(!$data){
return false;
}
if($type == 'add'){
$this->tableName = $this->tableName;
return $this->add($data);
}
if($type == 'edit'){
$data['data_id'] = I('post.data_id');
if(empty($data['data_id'])){
return false;
}
$status = $this->where('data_id='.$data['data_id'])->save();
if($status === false){
return false;
}
return true;
}
return false;
}
/**
* 删除信息
* @param int $dataId ID
* @return bool 删除状态
*/
public function delData($dataId)
{
$map = array();
$map['data_id'] = $dataId;
return $this->where($map)->delete();
}
/**
* 格式化字段信息
* @param string $field 字段名
* @param int $type 字段类型
* @return 格式化后数据
*/
public function formatField($field,$type)
{
$data = $_POST['Fieldset_'.$field];
switch ($type) {
case '2':
case '3':
return $data;
break;
case '6':
$fileData=array();
if(is_array($data)){
foreach ($data['url'] as $key => $value) {
$fileData[$key]['url'] = $value;
$fileData[$key]['title'] = $data['title'][$key];
}
return serialize($fileData);
}
break;
case '7':
case '8':
return intval($data);
break;
case '10':
if(!empty($data)){
return strtotime($data);
}else{
return time();
}
break;
case '9':
if(!empty($data)&&is_array($data)){
return implode(',',$data);
}
break;
default:
return I('post.Fieldset_'.$field);
break;
}
}
/**
* 还原字段信息
* @param string $field 字段名
* @param int $type 字段类型
* @param int $type 字段配置信息
* @return 还原后数据
*/
public function revertField($data,$type,$config)
{
switch ($type) {
case '6':
//文件列表
if(empty($data)){
return ;
}
$list=unserialize($data);
return $list;
break;
case '7':
case '8':
if(empty($config)){
return $data;
}
$list = explode(",",trim($config));
$data = array();
$i = 0;
foreach ($list as $value) {
$i++;
$data[$i] = $value;
}
return array(
'list' => $data,
'value' => intval($data),
);
break;
case '9':
if(empty($config)){
return $data;
}
$list = explode(",",trim($config));
$data = array();
$i = 0;
foreach ($list as $value) {
$i++;
$data[$i] = $value;
}
return array(
'list' => $data,
'value' => explode(",",trim($data)),
);
break;
case '11':
return number_format($data,2);
break;
default:
return html_out($data);
break;
}
}
/**
* 字段列表显示
* @param int $type 字段类型
* @return array 字段类型列表
*/
public function showListField($data,$type,$config)
{
switch ($type) {
case '5':
if($data){
return '<img name="" src="'.$data.'" alt="" style="max-width:170px; max-height:90px;" />';
}else{
return '无';
}
break;
case '6':
//文件列表
if(empty($data)){
return '无';
}
$list=unserialize($data);
$html='';
if(!empty($list)){
foreach ($list as $key => $value) {
$html.=$value['url'].'<br>';
}
}
return $html;
break;
case '7':
case '8':
if(empty($config)){
return $data;
}
$list=explode(",",trim($config));
foreach ($list as $key => $vo) {
if($data==intval($key)+1){
return $vo;
}
}
break;
case '9':
if(empty($config)){
return $data;
}
$list = explode(",",trim($config));
$newList = array();
$i = 0;
foreach ($list as $value) {
$i++;
$newList[$i] = $value;
}
$data = explode(",",trim($data));
$html='';
foreach ($data as $key => $vo) {
$html.=' '.$newList[$vo].' |';
}
return substr($html,0,-1);
break;
case '10':
return date('Y-m-d H:i:s',$data);
break;
case '11':
return number_format($data,2);
break;
default:
return $data;
break;
}
}
}
| coneycode/cmsForMePad | Application/DuxCms/Model/FieldDataModel.class.php | PHP | mit | 8,135 |
"""
WSGI config for Carkinos project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Carkinos.settings")
application = get_wsgi_application()
| LeeYiFang/Carkinos | src/Carkinos/wsgi.py | Python | mit | 393 |
# Smallest Integer
# I worked on this challenge by myself.
# smallest_integer is a method that takes an array of integers as its input
# and returns the smallest integer in the array
#
# +list_of_nums+ is an array of integers
# smallest_integer(list_of_nums) should return the smallest integer in +list_of_nums+
#
# If +list_of_nums+ is empty the method should return nil
# Your Solution Below
def smallest_integer(list_of_nums)
if list_of_nums == []
return nil
else
smallest = list_of_nums[0]
list_of_nums.each do |num|
if num < smallest
smallest = num
end
end
return smallest
end
end
def smallest_integer(list_of_nums)
if list_of_nums.empty?
return nil
else
list_of_nums.sort[0]
end
end | jonwhuang/phase-0 | week-4/smallest-integer/my_solution.rb | Ruby | mit | 753 |
require_relative 'spec_helper'
include LanguageSwitcher
I18n.available_locales = [:pt, :en]
describe "LanguageSwitcher" do
it "should be able to switch to a language" do
language(:pt){ I18n.locale.should == :pt }
language(:en){ I18n.locale.should == :en }
end
it "should not be able to switch to a language unless it is included in I18n.default_locales" do
lambda { language(:es) }.should raise_error
end
it "should pass thought each locale in I18n in order" do
i = 0
each_language do |l|
I18n.locale.should == I18n.available_locales[i]
I18n.locale.should == l
i+=1
end
end
# TODO: Add language_switcher view specs
end
| teonimesic/language_switcher | spec/language_switcher_spec.rb | Ruby | mit | 682 |
import React from 'react';
import { string, node } from 'prop-types';
import classNames from 'classnames';
const TileAction = ({ children, className, ...rest }) => {
return (
<div className={classNames('tile-action', className)} {...rest}>
{children}
</div>
);
};
/**
* TileAction property types.
*/
TileAction.propTypes = {
className: string,
children: node
};
/**
* TileAction default properties.
*/
TileAction.defaultProps = {};
export default TileAction;
| Landish/react-spectre-css | src/components/TileAction/TileAction.js | JavaScript | mit | 489 |
<?php
/**
* @link https://github.com/tigrov/yii2-country
* @author Sergei Tigrov <rrr-r@ya.ru>
*/
namespace tigrov\country;
/**
* This is the model class for table "city_translation".
*
* @property integer $geoname_id
* @property string $language_code
* @property string $value
*/
class CityTranslation extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%city_translation}}';
}
}
| Tigrov/yii2-country | src/CityTranslation.php | PHP | mit | 473 |
/**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package com.archimatetool.editor.actions;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.browser.IWebBrowser;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
import com.archimatetool.editor.ArchiPlugin;
import com.archimatetool.editor.preferences.IPreferenceConstants;
import com.archimatetool.editor.utils.StringUtils;
/**
* Check for New Action
*
* @author Phillip Beauvoir
*/
public class CheckForNewVersionAction extends Action {
public CheckForNewVersionAction() {
super(Messages.CheckForNewVersionAction_0);
}
String getOnlineVersion(URL url) throws IOException {
URLConnection connection = url.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
char[] buf = new char[32];
Reader r = new InputStreamReader(is, "UTF-8"); //$NON-NLS-1$
StringBuilder s = new StringBuilder();
while(true) {
int n = r.read(buf);
if(n < 0) {
break;
}
s.append(buf, 0, n);
}
is.close();
r.close();
return s.toString();
}
@Override
public void run() {
try {
String versionFile = ArchiPlugin.PREFERENCES.getString(IPreferenceConstants.UPDATE_URL);
if(!StringUtils.isSet(versionFile)) {
return;
}
URL url = new URL(versionFile);
String newVersion = getOnlineVersion(url);
// Get this app's main version number
String thisVersion = ArchiPlugin.INSTANCE.getVersion();
if(StringUtils.compareVersionNumbers(newVersion, thisVersion) > 0) {
String downloadURL = ArchiPlugin.PREFERENCES.getString(IPreferenceConstants.DOWNLOAD_URL);
// No download URL
if(!StringUtils.isSet(downloadURL)) {
MessageDialog.openInformation(null, Messages.CheckForNewVersionAction_1,
Messages.CheckForNewVersionAction_2 + " (" + newVersion + "). "); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
// Does have download URL
boolean reply = MessageDialog.openQuestion(null, Messages.CheckForNewVersionAction_1,
Messages.CheckForNewVersionAction_2 + " (" + newVersion + "). " + //$NON-NLS-1$ //$NON-NLS-2$
Messages.CheckForNewVersionAction_3);
if(reply) {
IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport();
IWebBrowser browser = support.getExternalBrowser();
if(browser != null) {
URL url2 = new URL(downloadURL);
browser.openURL(url2);
}
}
}
else {
MessageDialog.openInformation(null, Messages.CheckForNewVersionAction_1, Messages.CheckForNewVersionAction_4);
}
}
catch(MalformedURLException ex) {
ex.printStackTrace();
}
catch(IOException ex) {
ex.printStackTrace();
showErrorMessage(Messages.CheckForNewVersionAction_5 + " " + ex.getMessage()); //$NON-NLS-1$
return;
}
catch(PartInitException ex) {
ex.printStackTrace();
}
};
@Override
public boolean isEnabled() {
String versionFile = ArchiPlugin.PREFERENCES.getString(IPreferenceConstants.UPDATE_URL);
return StringUtils.isSet(versionFile);
}
private void showErrorMessage(String message) {
MessageDialog.openError(null, Messages.CheckForNewVersionAction_6, message);
}
}
| archimatetool/archi | com.archimatetool.editor/src/com/archimatetool/editor/actions/CheckForNewVersionAction.java | Java | mit | 4,513 |
using System;
using System.Collections.Generic;
using EspaceClient.BackOffice.Domaine.Results;
using EspaceClient.BackOffice.Silverlight.Business.Depots;
using EspaceClient.BackOffice.Silverlight.Business.Interfaces;
using EspaceClient.BackOffice.Silverlight.Infrastructure.Services;
using EspaceClient.FrontOffice.Domaine;
using nRoute.Components.Composition;
using EspaceClient.BackOffice.Silverlight.Infrastructure.ServicePieceJointe;
namespace EspaceClient.BackOffice.Silverlight.Data.Depots
{
/// <summary>
/// Dépôt des pieces jointes
/// </summary>
[MapResource(typeof(IDepotPieceJointe), InstanceLifetime.Singleton)]
public class DepotPieceJointe : IDepotPieceJointe
{
private readonly IServiceClientFactory _services;
private readonly IApplicationContext _applicationContext;
/// <summary>
/// Initialise une nouvelle instance du dépôt.
/// </summary>
/// <param name="services">Fournisseur de services.</param>
/// <param name="scheduler">Scheduler de tâches.</param>
[ResolveConstructor]
public DepotPieceJointe(IApplicationContext applicationContext, IServiceClientFactory services)
{
_applicationContext = applicationContext;
_services = services;
}
public void UploadPieceJointeStarted(PieceJointeDto pieceJointe, Action<PieceJointeDto> callback, Action<Exception> error)
{
_services.ServicePieceJointe.Call<UploadPieceJointeStartedCompletedEventArgs>(
s => s.UploadPieceJointeStartedAsync(_applicationContext.Context, pieceJointe),
r =>
{
if (r.Error != null)
error(r.Error);
else
callback(r.Result);
});
}
public void UploadPieceJointeFinished(PieceJointeDto pieceJointe, Action<PieceJointeResult> callback, Action<Exception> error)
{
_services.ServicePieceJointe.Call<UploadPieceJointeFinishedCompletedEventArgs>(
s => s.UploadPieceJointeFinishedAsync(_applicationContext.Context, pieceJointe),
r =>
{
if (r.Error != null)
error(r.Error);
else
callback(r.Result);
});
}
public void AddLink(PieceJointeDto pieceJointe, Action<PieceJointeResult> callback, Action<Exception> error)
{
_services.ServicePieceJointe.Call<AddLinkCompletedEventArgs>(
s => s.AddLinkAsync(_applicationContext.Context, pieceJointe),
r =>
{
if (r.Error != null)
error(r.Error);
else
callback(r.Result);
});
}
public void UploadPieceJointe(PieceJointeDto pieceJointe, byte[] data, long part, Action<PieceJointeDto> callback, Action<Exception> error)
{
_services.ServicePieceJointe.Call<UploadPieceJointeCompletedEventArgs>(
s => s.UploadPieceJointeAsync(_applicationContext.Context, pieceJointe, data, part),
r =>
{
if (r.Error != null)
error(r.Error);
else
callback(r.Result);
});
}
public void GetPieceJointes(long vueId, long idFonctionnel, Action<IEnumerable<PieceJointeResult>> callback, Action<Exception> error)
{
_services.ServicePieceJointe.Call<GetPieceJointesCompletedEventArgs>(
s => s.GetPieceJointesAsync(_applicationContext.Context, vueId, idFonctionnel),
r =>
{
if (r.Error != null)
error(r.Error);
else
callback(r.Result);
});
}
public void GetPieceJointesByIdStarted(long pieceJointeId, Action<PieceJointeDto> callback, Action<Exception> error)
{
_services.ServicePieceJointe.Call<GetPieceJointeByIdStartedCompletedEventArgs>(
s => s.GetPieceJointeByIdStartedAsync(_applicationContext.Context, pieceJointeId),
r =>
{
if (r.Error != null)
error(r.Error);
else
callback(r.Result);
});
}
public void GetPieceJointesById(long pieceJointeId, long part, Action<byte[]> callback, Action<Exception> error)
{
_services.ServicePieceJointe.Call<GetPieceJointeByIdCompletedEventArgs>(
s => s.GetPieceJointeByIdAsync(_applicationContext.Context, pieceJointeId, part),
r =>
{
if (r.Error != null)
error(r.Error);
else
callback(r.Result);
});
}
public void DeletePieceJointe(long pieceJointeId, Action<bool> callback, Action<Exception> error)
{
_services.ServicePieceJointe.Call<DeletePieceJointeCompletedEventArgs>(
s => s.DeletePieceJointeAsync(_applicationContext.Context, pieceJointeId),
r =>
{
if (r.Error != null)
error(r.Error);
else
callback(r.Result);
});
}
}
} | apo-j/Projects_Working | EC/espace-client-dot-net/EspaceClient.BackOffice.Silverlight.Data/Depots/DepotPieceJointe.cs | C# | mit | 5,620 |
from io import BytesIO
from django import forms
from django.http import HttpResponse
from django.template import Context, Template
from braces.views import LoginRequiredMixin
from django.views.generic import DetailView, ListView
from django.views.decorators.http import require_http_methods
from django.contrib import messages
from django.shortcuts import render, redirect
from django.conf import settings
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.units import inch
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.pagesizes import letter, landscape
from reportlab.platypus import Spacer
from reportlab.platypus import Frame
from reportlab.platypus import Paragraph
from reportlab.platypus import PageTemplate
from reportlab.platypus import BaseDocTemplate
from environ import Env
from members.models import Member
@require_http_methods(['GET', 'POST'])
def member_list(request):
env = Env()
MEMBERS_PASSWORD = env('MEMBERS_PASSWORD')
# handle form submission
if request.POST:
pw_form = PasswordForm(request.POST)
if pw_form.is_valid() and pw_form.cleaned_data['password'] == MEMBERS_PASSWORD:
request.session['password'] = pw_form.cleaned_data['password']
return redirect('members:member_list')
messages.error(request, "The password you entered was incorrect, please try again.")
# form not being submitted, check password
if (request.session.get('password') and request.session['password'] == MEMBERS_PASSWORD):
member_list = Member.objects.all()
return render(request, 'members/member_list.html', {
'member_list': member_list,
})
# password is wrong, render form
pw_form = PasswordForm()
return render(request, 'members/members_password_form.html', {
'pw_form': pw_form,
})
class PasswordForm(forms.Form):
password = forms.CharField(max_length=20,
widget=forms.PasswordInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Password',
}))
def build_frames(pwidth, pheight, ncols):
frames = []
for i in range(ncols):
f = Frame(x1=(i*((pwidth-30) / ncols)+15),
y1=0,
width=((pwidth-30) / ncols),
height=pheight+2,
leftPadding=15,
rightPadding=15,
topPadding=15,
bottomPadding=15,
showBoundary=True)
frames.append(f)
frames[0].showBoundary=False
frames[3].showBoundary=False
return frames
def member_list_pdf(request):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="memberlist.pdf"'
buffer = BytesIO()
NCOLUMNS = 4
PAGE_WIDTH, PAGE_HEIGHT = landscape(letter)
styles = getSampleStyleSheet()
ptemplate = PageTemplate(frames=build_frames(PAGE_WIDTH, PAGE_HEIGHT, NCOLUMNS))
doc = BaseDocTemplate(
filename=buffer,
pagesize=landscape(letter),
pageTemplates=[ptemplate],
showBoundary=0,
leftMargin=inch,
rightMargin=inch,
topMargin=inch,
bottomMargin=inch,
allowSplitting=0,
title='SSIP209 Members Listing',
author='Max Shkurygin',
_pageBreakQuick=1,
encrypt=None)
template = Template("""
<font size="14"><strong>{{ member.last_name }}, {{ member.first_name }}</strong></font>
<br/>
{% if member.address or member.town %}
{{ member.address }}<br/>
{% if member.town %} {{ member.town }} NY <br/>{% endif %}
{% endif %}
{% if member.homephone %}
(Home) {{ member.homephone }}
<br/>
{% endif %}
{% if member.cellphone %}
(Cell) {{ member.cellphone }}
<br/>
{% endif %}
{% if member.email %}
Email: {{ member.email }}
<br/>
{% endif %}
{% if member.hobbies %}
<strong>My Hobbies</strong>: {{ member.hobbies }}
<br/>
{% endif %}
{% if member.canhelp %}
<strong>I can help with</strong>: {{ member.canhelp }}
<br/>
{% endif %}
{% if member.needhelp %}
<strong>I could use help with</strong>: {{ member.needhelp }}
<br/>
{% endif %}
""")
content = []
for member in Member.objects.all():
context = Context({"member": member})
p = Paragraph(template.render(context), styles["Normal"])
content.append(p)
content.append(Spacer(1, 0.3*inch))
doc.build(content)
pdf = buffer.getvalue()
buffer.close()
response.write(pdf)
return response
| mooja/ssip3 | app/members/views.py | Python | mit | 4,530 |
import {Component} from "@angular/core";
@Component({
moduleId: module.id,
selector: 'ptc-footer',
templateUrl: 'footer.component.html'
})
export class FooterComponent{
} | puncha/java-petclinic | src/main/webapp/resources/ng2/app/footer/footer.component.ts | TypeScript | mit | 177 |
<?php
namespace Pinq\Iterators\Generators;
use Pinq\Iterators\Standard\IIterator;
/**
* Implementation of the adapter iterator for Pinq\Iterators\IIterator using the generator
*
* @author Elliot Levin <elliotlevin@hotmail.com>
*/
class IIteratorAdapter extends Generator
{
/**
* @var IIterator
*/
private $iterator;
public function __construct(IIterator $iterator)
{
parent::__construct();
$this->iterator = $iterator;
}
public function &getIterator()
{
$this->iterator->rewind();
while ($element = $this->iterator->fetch()) {
yield $element[0] => $element[1];
}
}
}
| TimeToogo/Pinq | Source/Iterators/Generators/IIteratorAdapter.php | PHP | mit | 671 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX ARM/ARM64 Code Generator Common Code XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#ifndef LEGACY_BACKEND // This file is ONLY used for the RyuJIT backend that uses the linear scan register allocator
#ifdef _TARGET_ARMARCH_ // This file is ONLY used for ARM and ARM64 architectures
#include "codegen.h"
#include "lower.h"
#include "gcinfo.h"
#include "emit.h"
//------------------------------------------------------------------------
// genCodeForTreeNode Generate code for a single node in the tree.
//
// Preconditions:
// All operands have been evaluated.
//
void CodeGen::genCodeForTreeNode(GenTreePtr treeNode)
{
regNumber targetReg = treeNode->gtRegNum;
var_types targetType = treeNode->TypeGet();
emitter* emit = getEmitter();
#ifdef DEBUG
// Validate that all the operands for the current node are consumed in order.
// This is important because LSRA ensures that any necessary copies will be
// handled correctly.
lastConsumedNode = nullptr;
if (compiler->verbose)
{
unsigned seqNum = treeNode->gtSeqNum; // Useful for setting a conditional break in Visual Studio
compiler->gtDispLIRNode(treeNode, "Generating: ");
}
#endif // DEBUG
#ifdef _TARGET_ARM64_ // TODO-ARM: is this applicable to ARM32?
// Is this a node whose value is already in a register? LSRA denotes this by
// setting the GTF_REUSE_REG_VAL flag.
if (treeNode->IsReuseRegVal())
{
// For now, this is only used for constant nodes.
assert((treeNode->OperGet() == GT_CNS_INT) || (treeNode->OperGet() == GT_CNS_DBL));
JITDUMP(" TreeNode is marked ReuseReg\n");
return;
}
#endif // _TARGET_ARM64_
// contained nodes are part of their parents for codegen purposes
// ex : immediates, most LEAs
if (treeNode->isContained())
{
return;
}
switch (treeNode->gtOper)
{
case GT_START_NONGC:
getEmitter()->emitDisableGC();
break;
#ifdef _TARGET_ARM64_
case GT_PROF_HOOK:
// We should be seeing this only if profiler hook is needed
noway_assert(compiler->compIsProfilerHookNeeded());
#ifdef PROFILING_SUPPORTED
// Right now this node is used only for tail calls. In future if
// we intend to use it for Enter or Leave hooks, add a data member
// to this node indicating the kind of profiler hook. For example,
// helper number can be used.
genProfilingLeaveCallback(CORINFO_HELP_PROF_FCN_TAILCALL);
#endif // PROFILING_SUPPORTED
break;
#endif // _TARGET_ARM64_
case GT_LCLHEAP:
genLclHeap(treeNode);
break;
case GT_CNS_INT:
case GT_CNS_DBL:
genSetRegToConst(targetReg, targetType, treeNode);
genProduceReg(treeNode);
break;
case GT_NOT:
case GT_NEG:
genCodeForNegNot(treeNode);
break;
case GT_MOD:
case GT_UMOD:
case GT_DIV:
case GT_UDIV:
genCodeForDivMod(treeNode->AsOp());
break;
case GT_OR:
case GT_XOR:
case GT_AND:
assert(varTypeIsIntegralOrI(treeNode));
__fallthrough;
#if !defined(_TARGET_64BIT_)
case GT_ADD_LO:
case GT_ADD_HI:
case GT_SUB_LO:
case GT_SUB_HI:
#endif // !defined(_TARGET_64BIT_)
case GT_ADD:
case GT_SUB:
case GT_MUL:
genConsumeOperands(treeNode->AsOp());
genCodeForBinary(treeNode);
break;
case GT_LSH:
case GT_RSH:
case GT_RSZ:
// case GT_ROL: // No ROL instruction on ARM; it has been lowered to ROR.
case GT_ROR:
genCodeForShift(treeNode);
break;
#if !defined(_TARGET_64BIT_)
case GT_LSH_HI:
case GT_RSH_LO:
genCodeForShiftLong(treeNode);
break;
#endif // !defined(_TARGET_64BIT_)
case GT_CAST:
genCodeForCast(treeNode->AsOp());
break;
case GT_BITCAST:
{
GenTree* op1 = treeNode->gtOp.gtOp1;
if (varTypeIsFloating(treeNode) != varTypeIsFloating(op1))
{
#ifdef _TARGET_ARM64_
inst_RV_RV(INS_fmov, targetReg, genConsumeReg(op1), targetType);
#else // !_TARGET_ARM64_
if (varTypeIsFloating(treeNode))
{
NYI_ARM("genRegCopy from 'int' to 'float'");
}
else
{
assert(varTypeIsFloating(op1));
if (op1->TypeGet() == TYP_FLOAT)
{
inst_RV_RV(INS_vmov_f2i, targetReg, genConsumeReg(op1), targetType);
}
else
{
regNumber otherReg = (regNumber)treeNode->AsMultiRegOp()->gtOtherReg;
assert(otherReg != REG_NA);
inst_RV_RV_RV(INS_vmov_d2i, targetReg, otherReg, genConsumeReg(op1), EA_8BYTE);
}
}
#endif // !_TARGET_ARM64_
}
else
{
inst_RV_RV(ins_Copy(targetType), targetReg, genConsumeReg(op1), targetType);
}
}
break;
case GT_LCL_FLD_ADDR:
case GT_LCL_VAR_ADDR:
genCodeForLclAddr(treeNode);
break;
case GT_LCL_FLD:
genCodeForLclFld(treeNode->AsLclFld());
break;
case GT_LCL_VAR:
genCodeForLclVar(treeNode->AsLclVar());
break;
case GT_STORE_LCL_FLD:
genCodeForStoreLclFld(treeNode->AsLclFld());
break;
case GT_STORE_LCL_VAR:
genCodeForStoreLclVar(treeNode->AsLclVar());
break;
case GT_RETFILT:
case GT_RETURN:
genReturn(treeNode);
break;
case GT_LEA:
// If we are here, it is the case where there is an LEA that cannot be folded into a parent instruction.
genLeaInstruction(treeNode->AsAddrMode());
break;
case GT_INDEX_ADDR:
genCodeForIndexAddr(treeNode->AsIndexAddr());
break;
case GT_IND:
genCodeForIndir(treeNode->AsIndir());
break;
#ifdef _TARGET_ARM_
case GT_MUL_LONG:
genCodeForMulLong(treeNode->AsMultiRegOp());
break;
#endif // _TARGET_ARM_
#ifdef _TARGET_ARM64_
case GT_MULHI:
genCodeForMulHi(treeNode->AsOp());
break;
case GT_SWAP:
genCodeForSwap(treeNode->AsOp());
break;
#endif // _TARGET_ARM64_
case GT_JMP:
genJmpMethod(treeNode);
break;
case GT_CKFINITE:
genCkfinite(treeNode);
break;
case GT_INTRINSIC:
genIntrinsic(treeNode);
break;
#ifdef FEATURE_SIMD
case GT_SIMD:
genSIMDIntrinsic(treeNode->AsSIMD());
break;
#endif // FEATURE_SIMD
case GT_EQ:
case GT_NE:
case GT_LT:
case GT_LE:
case GT_GE:
case GT_GT:
case GT_CMP:
#ifdef _TARGET_ARM64_
case GT_TEST_EQ:
case GT_TEST_NE:
#endif // _TARGET_ARM64_
genCodeForCompare(treeNode->AsOp());
break;
case GT_JTRUE:
genCodeForJumpTrue(treeNode);
break;
#ifdef _TARGET_ARM64_
case GT_JCMP:
genCodeForJumpCompare(treeNode->AsOp());
break;
#endif // _TARGET_ARM64_
case GT_JCC:
genCodeForJcc(treeNode->AsCC());
break;
case GT_SETCC:
genCodeForSetcc(treeNode->AsCC());
break;
case GT_RETURNTRAP:
genCodeForReturnTrap(treeNode->AsOp());
break;
case GT_STOREIND:
genCodeForStoreInd(treeNode->AsStoreInd());
break;
case GT_COPY:
// This is handled at the time we call genConsumeReg() on the GT_COPY
break;
case GT_LIST:
case GT_FIELD_LIST:
// Should always be marked contained.
assert(!"LIST, FIELD_LIST nodes should always be marked contained.");
break;
case GT_PUTARG_STK:
genPutArgStk(treeNode->AsPutArgStk());
break;
case GT_PUTARG_REG:
genPutArgReg(treeNode->AsOp());
break;
#ifdef _TARGET_ARM_
case GT_PUTARG_SPLIT:
genPutArgSplit(treeNode->AsPutArgSplit());
break;
#endif
case GT_CALL:
genCallInstruction(treeNode->AsCall());
break;
case GT_LOCKADD:
case GT_XCHG:
case GT_XADD:
genLockedInstructions(treeNode->AsOp());
break;
case GT_MEMORYBARRIER:
instGen_MemoryBarrier();
break;
case GT_CMPXCHG:
NYI_ARM("GT_CMPXCHG");
#ifdef _TARGET_ARM64_
genCodeForCmpXchg(treeNode->AsCmpXchg());
#endif
break;
case GT_RELOAD:
// do nothing - reload is just a marker.
// The parent node will call genConsumeReg on this which will trigger the unspill of this node's child
// into the register specified in this node.
break;
case GT_NOP:
break;
case GT_NO_OP:
instGen(INS_nop);
break;
case GT_ARR_BOUNDS_CHECK:
#ifdef FEATURE_SIMD
case GT_SIMD_CHK:
#endif // FEATURE_SIMD
genRangeCheck(treeNode);
break;
case GT_PHYSREG:
genCodeForPhysReg(treeNode->AsPhysReg());
break;
case GT_NULLCHECK:
genCodeForNullCheck(treeNode->AsOp());
break;
case GT_CATCH_ARG:
noway_assert(handlerGetsXcptnObj(compiler->compCurBB->bbCatchTyp));
/* Catch arguments get passed in a register. genCodeForBBlist()
would have marked it as holding a GC object, but not used. */
noway_assert(gcInfo.gcRegGCrefSetCur & RBM_EXCEPTION_OBJECT);
genConsumeReg(treeNode);
break;
case GT_PINVOKE_PROLOG:
noway_assert(((gcInfo.gcRegGCrefSetCur | gcInfo.gcRegByrefSetCur) & ~fullIntArgRegMask()) == 0);
// the runtime side requires the codegen here to be consistent
emit->emitDisableRandomNops();
break;
case GT_LABEL:
genPendingCallLabel = genCreateTempLabel();
treeNode->gtLabel.gtLabBB = genPendingCallLabel;
emit->emitIns_R_L(INS_adr, EA_PTRSIZE, genPendingCallLabel, targetReg);
break;
case GT_STORE_OBJ:
case GT_STORE_DYN_BLK:
case GT_STORE_BLK:
genCodeForStoreBlk(treeNode->AsBlk());
break;
case GT_JMPTABLE:
genJumpTable(treeNode);
break;
case GT_SWITCH_TABLE:
genTableBasedSwitch(treeNode);
break;
case GT_ARR_INDEX:
genCodeForArrIndex(treeNode->AsArrIndex());
break;
case GT_ARR_OFFSET:
genCodeForArrOffset(treeNode->AsArrOffs());
break;
#ifdef _TARGET_ARM_
case GT_CLS_VAR_ADDR:
emit->emitIns_R_C(INS_lea, EA_PTRSIZE, targetReg, treeNode->gtClsVar.gtClsVarHnd, 0);
genProduceReg(treeNode);
break;
case GT_LONG:
assert(treeNode->isUsedFromReg());
genConsumeRegs(treeNode);
break;
#endif // _TARGET_ARM_
case GT_IL_OFFSET:
// Do nothing; these nodes are simply markers for debug info.
break;
default:
{
#ifdef DEBUG
char message[256];
_snprintf_s(message, _countof(message), _TRUNCATE, "NYI: Unimplemented node type %s",
GenTree::OpName(treeNode->OperGet()));
NYIRAW(message);
#else
NYI("unimplemented node");
#endif
}
break;
}
}
//------------------------------------------------------------------------
// genSetRegToIcon: Generate code that will set the given register to the integer constant.
//
void CodeGen::genSetRegToIcon(regNumber reg, ssize_t val, var_types type, insFlags flags)
{
// Reg cannot be a FP reg
assert(!genIsValidFloatReg(reg));
// The only TYP_REF constant that can come this path is a managed 'null' since it is not
// relocatable. Other ref type constants (e.g. string objects) go through a different
// code path.
noway_assert(type != TYP_REF || val == 0);
instGen_Set_Reg_To_Imm(emitActualTypeSize(type), reg, val, flags);
}
//---------------------------------------------------------------------
// genIntrinsic - generate code for a given intrinsic
//
// Arguments
// treeNode - the GT_INTRINSIC node
//
// Return value:
// None
//
void CodeGen::genIntrinsic(GenTreePtr treeNode)
{
assert(treeNode->OperIs(GT_INTRINSIC));
// Both operand and its result must be of the same floating point type.
GenTreePtr srcNode = treeNode->gtOp.gtOp1;
assert(varTypeIsFloating(srcNode));
assert(srcNode->TypeGet() == treeNode->TypeGet());
// Right now only Abs/Ceiling/Floor/Round/Sqrt are treated as math intrinsics.
//
switch (treeNode->gtIntrinsic.gtIntrinsicId)
{
case CORINFO_INTRINSIC_Abs:
genConsumeOperands(treeNode->AsOp());
getEmitter()->emitInsBinary(INS_ABS, emitActualTypeSize(treeNode), treeNode, srcNode);
break;
#ifdef _TARGET_ARM64_
case CORINFO_INTRINSIC_Ceiling:
genConsumeOperands(treeNode->AsOp());
getEmitter()->emitInsBinary(INS_frintp, emitActualTypeSize(treeNode), treeNode, srcNode);
break;
case CORINFO_INTRINSIC_Floor:
genConsumeOperands(treeNode->AsOp());
getEmitter()->emitInsBinary(INS_frintm, emitActualTypeSize(treeNode), treeNode, srcNode);
break;
#endif
case CORINFO_INTRINSIC_Round:
NYI_ARM("genIntrinsic for round - not implemented yet");
genConsumeOperands(treeNode->AsOp());
getEmitter()->emitInsBinary(INS_ROUND, emitActualTypeSize(treeNode), treeNode, srcNode);
break;
case CORINFO_INTRINSIC_Sqrt:
genConsumeOperands(treeNode->AsOp());
getEmitter()->emitInsBinary(INS_SQRT, emitActualTypeSize(treeNode), treeNode, srcNode);
break;
default:
assert(!"genIntrinsic: Unsupported intrinsic");
unreached();
}
genProduceReg(treeNode);
}
//---------------------------------------------------------------------
// genPutArgStk - generate code for a GT_PUTARG_STK node
//
// Arguments
// treeNode - the GT_PUTARG_STK node
//
// Return value:
// None
//
void CodeGen::genPutArgStk(GenTreePutArgStk* treeNode)
{
assert(treeNode->OperIs(GT_PUTARG_STK));
GenTreePtr source = treeNode->gtOp1;
var_types targetType = source->TypeGet();
emitter* emit = getEmitter();
// This is the varNum for our store operations,
// typically this is the varNum for the Outgoing arg space
// When we are generating a tail call it will be the varNum for arg0
unsigned varNumOut = (unsigned)-1;
unsigned argOffsetMax = (unsigned)-1; // Records the maximum size of this area for assert checks
// Get argument offset to use with 'varNumOut'
// Here we cross check that argument offset hasn't changed from lowering to codegen since
// we are storing arg slot number in GT_PUTARG_STK node in lowering phase.
unsigned argOffsetOut = treeNode->gtSlotNum * TARGET_POINTER_SIZE;
#ifdef DEBUG
fgArgTabEntryPtr curArgTabEntry = compiler->gtArgEntryByNode(treeNode->gtCall, treeNode);
assert(curArgTabEntry);
assert(argOffsetOut == (curArgTabEntry->slotNum * TARGET_POINTER_SIZE));
#endif // DEBUG
// Whether to setup stk arg in incoming or out-going arg area?
// Fast tail calls implemented as epilog+jmp = stk arg is setup in incoming arg area.
// All other calls - stk arg is setup in out-going arg area.
if (treeNode->putInIncomingArgArea())
{
varNumOut = getFirstArgWithStackSlot();
argOffsetMax = compiler->compArgSize;
#if FEATURE_FASTTAILCALL
// This must be a fast tail call.
assert(treeNode->gtCall->IsFastTailCall());
// Since it is a fast tail call, the existence of first incoming arg is guaranteed
// because fast tail call requires that in-coming arg area of caller is >= out-going
// arg area required for tail call.
LclVarDsc* varDsc = &(compiler->lvaTable[varNumOut]);
assert(varDsc != nullptr);
#endif // FEATURE_FASTTAILCALL
}
else
{
varNumOut = compiler->lvaOutgoingArgSpaceVar;
argOffsetMax = compiler->lvaOutgoingArgSpaceSize;
}
bool isStruct = (targetType == TYP_STRUCT) || (source->OperGet() == GT_FIELD_LIST);
if (!isStruct) // a normal non-Struct argument
{
instruction storeIns = ins_Store(targetType);
emitAttr storeAttr = emitTypeSize(targetType);
// If it is contained then source must be the integer constant zero
if (source->isContained())
{
#ifdef _TARGET_ARM64_
assert(source->OperGet() == GT_CNS_INT);
assert(source->AsIntConCommon()->IconValue() == 0);
emit->emitIns_S_R(storeIns, storeAttr, REG_ZR, varNumOut, argOffsetOut);
#else // !_TARGET_ARM64_
// There is no zero register on ARM32
unreached();
#endif // !_TARGET_ARM64
}
else
{
genConsumeReg(source);
emit->emitIns_S_R(storeIns, storeAttr, source->gtRegNum, varNumOut, argOffsetOut);
#ifdef _TARGET_ARM_
if (targetType == TYP_LONG)
{
// This case currently only occurs for double types that are passed as TYP_LONG;
// actual long types would have been decomposed by now.
assert(source->IsCopyOrReload());
regNumber otherReg = (regNumber)source->AsCopyOrReload()->GetRegNumByIdx(1);
assert(otherReg != REG_NA);
argOffsetOut += EA_4BYTE;
emit->emitIns_S_R(storeIns, storeAttr, otherReg, varNumOut, argOffsetOut);
}
#endif // _TARGET_ARM_
}
argOffsetOut += EA_SIZE_IN_BYTES(storeAttr);
assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area
}
else // We have some kind of a struct argument
{
assert(source->isContained()); // We expect that this node was marked as contained in Lower
if (source->OperGet() == GT_FIELD_LIST)
{
// Deal with the multi register passed struct args.
GenTreeFieldList* fieldListPtr = source->AsFieldList();
// Evaluate each of the GT_FIELD_LIST items into their register
// and store their register into the outgoing argument area
for (; fieldListPtr != nullptr; fieldListPtr = fieldListPtr->Rest())
{
GenTreePtr nextArgNode = fieldListPtr->gtOp.gtOp1;
genConsumeReg(nextArgNode);
regNumber reg = nextArgNode->gtRegNum;
var_types type = nextArgNode->TypeGet();
emitAttr attr = emitTypeSize(type);
// Emit store instructions to store the registers produced by the GT_FIELD_LIST into the outgoing
// argument area
emit->emitIns_S_R(ins_Store(type), attr, reg, varNumOut, argOffsetOut);
argOffsetOut += EA_SIZE_IN_BYTES(attr);
assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area
}
}
else // We must have a GT_OBJ or a GT_LCL_VAR
{
noway_assert((source->OperGet() == GT_LCL_VAR) || (source->OperGet() == GT_OBJ));
var_types targetType = source->TypeGet();
noway_assert(varTypeIsStruct(targetType));
// We will copy this struct to the stack, possibly using a ldp/ldr instruction
// in ARM64/ARM
// Setup loReg (and hiReg) from the internal registers that we reserved in lower.
//
regNumber loReg = treeNode->ExtractTempReg();
#ifdef _TARGET_ARM64_
regNumber hiReg = treeNode->GetSingleTempReg();
#endif // _TARGET_ARM64_
regNumber addrReg = REG_NA;
GenTreeLclVarCommon* varNode = nullptr;
GenTreePtr addrNode = nullptr;
if (source->OperGet() == GT_LCL_VAR)
{
varNode = source->AsLclVarCommon();
}
else // we must have a GT_OBJ
{
assert(source->OperGet() == GT_OBJ);
addrNode = source->gtOp.gtOp1;
// addrNode can either be a GT_LCL_VAR_ADDR or an address expression
//
if (addrNode->OperGet() == GT_LCL_VAR_ADDR)
{
// We have a GT_OBJ(GT_LCL_VAR_ADDR)
//
// We will treat this case the same as above
// (i.e if we just had this GT_LCL_VAR directly as the source)
// so update 'source' to point this GT_LCL_VAR_ADDR node
// and continue to the codegen for the LCL_VAR node below
//
varNode = addrNode->AsLclVarCommon();
addrNode = nullptr;
}
}
// Either varNode or addrNOde must have been setup above,
// the xor ensures that only one of the two is setup, not both
assert((varNode != nullptr) ^ (addrNode != nullptr));
BYTE gcPtrArray[MAX_ARG_REG_COUNT] = {}; // TYPE_GC_NONE = 0
BYTE* gcPtrs = gcPtrArray;
unsigned gcPtrCount; // The count of GC pointers in the struct
int structSize;
bool isHfa;
// This is the varNum for our load operations,
// only used when we have a multireg struct with a LclVar source
unsigned varNumInp = BAD_VAR_NUM;
#ifdef _TARGET_ARM_
// On ARM32, size of reference map can be larger than MAX_ARG_REG_COUNT
gcPtrs = treeNode->gtGcPtrs;
gcPtrCount = treeNode->gtNumberReferenceSlots;
#endif
// Setup the structSize, isHFa, and gcPtrCount
if (varNode != nullptr)
{
varNumInp = varNode->gtLclNum;
assert(varNumInp < compiler->lvaCount);
LclVarDsc* varDsc = &compiler->lvaTable[varNumInp];
// This struct also must live in the stack frame
// And it can't live in a register (SIMD)
assert(varDsc->lvType == TYP_STRUCT);
assert(varDsc->lvOnFrame && !varDsc->lvRegister);
structSize = varDsc->lvSize(); // This yields the roundUp size, but that is fine
// as that is how much stack is allocated for this LclVar
isHfa = varDsc->lvIsHfa();
#ifdef _TARGET_ARM64_
gcPtrCount = varDsc->lvStructGcCount;
for (unsigned i = 0; i < gcPtrCount; ++i)
gcPtrs[i] = varDsc->lvGcLayout[i];
#endif // _TARGET_ARM_
}
else // addrNode is used
{
assert(addrNode != nullptr);
// Generate code to load the address that we need into a register
genConsumeAddress(addrNode);
addrReg = addrNode->gtRegNum;
#ifdef _TARGET_ARM64_
// If addrReg equal to loReg, swap(loReg, hiReg)
// This reduces code complexity by only supporting one addrReg overwrite case
if (loReg == addrReg)
{
loReg = hiReg;
hiReg = addrReg;
}
#endif // _TARGET_ARM64_
CORINFO_CLASS_HANDLE objClass = source->gtObj.gtClass;
structSize = compiler->info.compCompHnd->getClassSize(objClass);
isHfa = compiler->IsHfa(objClass);
#ifdef _TARGET_ARM64_
gcPtrCount = compiler->info.compCompHnd->getClassGClayout(objClass, &gcPtrs[0]);
#endif
}
// If we have an HFA we can't have any GC pointers,
// if not then the max size for the the struct is 16 bytes
if (isHfa)
{
noway_assert(gcPtrCount == 0);
}
#ifdef _TARGET_ARM64_
else
{
noway_assert(structSize <= 2 * TARGET_POINTER_SIZE);
}
noway_assert(structSize <= MAX_PASS_MULTIREG_BYTES);
#endif // _TARGET_ARM64_
int remainingSize = structSize;
unsigned structOffset = 0;
unsigned nextIndex = 0;
#ifdef _TARGET_ARM64_
// For a >= 16-byte structSize we will generate a ldp and stp instruction each loop
// ldp x2, x3, [x0]
// stp x2, x3, [sp, #16]
while (remainingSize >= 2 * TARGET_POINTER_SIZE)
{
var_types type0 = compiler->getJitGCType(gcPtrs[nextIndex + 0]);
var_types type1 = compiler->getJitGCType(gcPtrs[nextIndex + 1]);
if (varNode != nullptr)
{
// Load from our varNumImp source
emit->emitIns_R_R_S_S(INS_ldp, emitTypeSize(type0), emitTypeSize(type1), loReg, hiReg, varNumInp,
0);
}
else
{
// check for case of destroying the addrRegister while we still need it
assert(loReg != addrReg);
noway_assert((remainingSize == 2 * TARGET_POINTER_SIZE) || (hiReg != addrReg));
// Load from our address expression source
emit->emitIns_R_R_R_I(INS_ldp, emitTypeSize(type0), loReg, hiReg, addrReg, structOffset,
INS_OPTS_NONE, emitTypeSize(type0));
}
// Emit stp instruction to store the two registers into the outgoing argument area
emit->emitIns_S_S_R_R(INS_stp, emitTypeSize(type0), emitTypeSize(type1), loReg, hiReg, varNumOut,
argOffsetOut);
argOffsetOut += (2 * TARGET_POINTER_SIZE); // We stored 16-bytes of the struct
assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area
remainingSize -= (2 * TARGET_POINTER_SIZE); // We loaded 16-bytes of the struct
structOffset += (2 * TARGET_POINTER_SIZE);
nextIndex += 2;
}
#else // _TARGET_ARM_
// For a >= 4 byte structSize we will generate a ldr and str instruction each loop
// ldr r2, [r0]
// str r2, [sp, #16]
while (remainingSize >= TARGET_POINTER_SIZE)
{
var_types type = compiler->getJitGCType(gcPtrs[nextIndex]);
if (varNode != nullptr)
{
// Load from our varNumImp source
emit->emitIns_R_S(INS_ldr, emitTypeSize(type), loReg, varNumInp, structOffset);
}
else
{
// check for case of destroying the addrRegister while we still need it
assert(loReg != addrReg || remainingSize == TARGET_POINTER_SIZE);
// Load from our address expression source
emit->emitIns_R_R_I(INS_ldr, emitTypeSize(type), loReg, addrReg, structOffset);
}
// Emit str instruction to store the register into the outgoing argument area
emit->emitIns_S_R(INS_str, emitTypeSize(type), loReg, varNumOut, argOffsetOut);
argOffsetOut += TARGET_POINTER_SIZE; // We stored 4-bytes of the struct
assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area
remainingSize -= TARGET_POINTER_SIZE; // We loaded 4-bytes of the struct
structOffset += TARGET_POINTER_SIZE;
nextIndex += 1;
}
#endif // _TARGET_ARM_
// For a 12-byte structSize we will we will generate two load instructions
// ldr x2, [x0]
// ldr w3, [x0, #8]
// str x2, [sp, #16]
// str w3, [sp, #24]
while (remainingSize > 0)
{
if (remainingSize >= TARGET_POINTER_SIZE)
{
var_types nextType = compiler->getJitGCType(gcPtrs[nextIndex]);
emitAttr nextAttr = emitTypeSize(nextType);
remainingSize -= TARGET_POINTER_SIZE;
if (varNode != nullptr)
{
// Load from our varNumImp source
emit->emitIns_R_S(ins_Load(nextType), nextAttr, loReg, varNumInp, structOffset);
}
else
{
assert(loReg != addrReg);
// Load from our address expression source
emit->emitIns_R_R_I(ins_Load(nextType), nextAttr, loReg, addrReg, structOffset);
}
// Emit a store instruction to store the register into the outgoing argument area
emit->emitIns_S_R(ins_Store(nextType), nextAttr, loReg, varNumOut, argOffsetOut);
argOffsetOut += EA_SIZE_IN_BYTES(nextAttr);
assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area
structOffset += TARGET_POINTER_SIZE;
nextIndex++;
}
else // (remainingSize < TARGET_POINTER_SIZE)
{
int loadSize = remainingSize;
remainingSize = 0;
// We should never have to do a non-pointer sized load when we have a LclVar source
assert(varNode == nullptr);
// the left over size is smaller than a pointer and thus can never be a GC type
assert(varTypeIsGC(compiler->getJitGCType(gcPtrs[nextIndex])) == false);
var_types loadType = TYP_UINT;
if (loadSize == 1)
{
loadType = TYP_UBYTE;
}
else if (loadSize == 2)
{
loadType = TYP_USHORT;
}
else
{
// Need to handle additional loadSize cases here
noway_assert(loadSize == 4);
}
instruction loadIns = ins_Load(loadType);
emitAttr loadAttr = emitAttr(loadSize);
assert(loReg != addrReg);
emit->emitIns_R_R_I(loadIns, loadAttr, loReg, addrReg, structOffset);
// Emit a store instruction to store the register into the outgoing argument area
emit->emitIns_S_R(ins_Store(loadType), loadAttr, loReg, varNumOut, argOffsetOut);
argOffsetOut += EA_SIZE_IN_BYTES(loadAttr);
assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area
}
}
}
}
}
//---------------------------------------------------------------------
// genPutArgReg - generate code for a GT_PUTARG_REG node
//
// Arguments
// tree - the GT_PUTARG_REG node
//
// Return value:
// None
//
void CodeGen::genPutArgReg(GenTreeOp* tree)
{
assert(tree->OperIs(GT_PUTARG_REG));
var_types targetType = tree->TypeGet();
regNumber targetReg = tree->gtRegNum;
assert(targetType != TYP_STRUCT);
GenTree* op1 = tree->gtOp1;
genConsumeReg(op1);
// If child node is not already in the register we need, move it
if (targetReg != op1->gtRegNum)
{
inst_RV_RV(ins_Copy(targetType), targetReg, op1->gtRegNum, targetType);
}
genProduceReg(tree);
}
#ifdef _TARGET_ARM_
//---------------------------------------------------------------------
// genPutArgSplit - generate code for a GT_PUTARG_SPLIT node
//
// Arguments
// tree - the GT_PUTARG_SPLIT node
//
// Return value:
// None
//
void CodeGen::genPutArgSplit(GenTreePutArgSplit* treeNode)
{
assert(treeNode->OperIs(GT_PUTARG_SPLIT));
GenTreePtr source = treeNode->gtOp1;
emitter* emit = getEmitter();
unsigned varNumOut = compiler->lvaOutgoingArgSpaceVar;
unsigned argOffsetMax = compiler->lvaOutgoingArgSpaceSize;
unsigned argOffsetOut = treeNode->gtSlotNum * TARGET_POINTER_SIZE;
if (source->OperGet() == GT_FIELD_LIST)
{
GenTreeFieldList* fieldListPtr = source->AsFieldList();
// Evaluate each of the GT_FIELD_LIST items into their register
// and store their register into the outgoing argument area
for (unsigned idx = 0; fieldListPtr != nullptr; fieldListPtr = fieldListPtr->Rest(), idx++)
{
GenTreePtr nextArgNode = fieldListPtr->gtGetOp1();
regNumber fieldReg = nextArgNode->gtRegNum;
genConsumeReg(nextArgNode);
if (idx >= treeNode->gtNumRegs)
{
var_types type = nextArgNode->TypeGet();
emitAttr attr = emitTypeSize(type);
// Emit store instructions to store the registers produced by the GT_FIELD_LIST into the outgoing
// argument area
emit->emitIns_S_R(ins_Store(type), attr, fieldReg, varNumOut, argOffsetOut);
argOffsetOut += EA_SIZE_IN_BYTES(attr);
assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area
}
else
{
var_types type = treeNode->GetRegType(idx);
regNumber argReg = treeNode->GetRegNumByIdx(idx);
// If child node is not already in the register we need, move it
if (argReg != fieldReg)
{
inst_RV_RV(ins_Copy(type), argReg, fieldReg, type);
}
}
}
}
else
{
var_types targetType = source->TypeGet();
assert(source->OperGet() == GT_OBJ);
assert(varTypeIsStruct(targetType));
regNumber baseReg = treeNode->ExtractTempReg();
regNumber addrReg = REG_NA;
GenTreeLclVarCommon* varNode = nullptr;
GenTreePtr addrNode = nullptr;
addrNode = source->gtOp.gtOp1;
// addrNode can either be a GT_LCL_VAR_ADDR or an address expression
//
if (addrNode->OperGet() == GT_LCL_VAR_ADDR)
{
// We have a GT_OBJ(GT_LCL_VAR_ADDR)
//
// We will treat this case the same as above
// (i.e if we just had this GT_LCL_VAR directly as the source)
// so update 'source' to point this GT_LCL_VAR_ADDR node
// and continue to the codegen for the LCL_VAR node below
//
varNode = addrNode->AsLclVarCommon();
addrNode = nullptr;
}
// Either varNode or addrNOde must have been setup above,
// the xor ensures that only one of the two is setup, not both
assert((varNode != nullptr) ^ (addrNode != nullptr));
// Setup the structSize, isHFa, and gcPtrCount
BYTE* gcPtrs = treeNode->gtGcPtrs;
unsigned gcPtrCount = treeNode->gtNumberReferenceSlots; // The count of GC pointers in the struct
int structSize = treeNode->getArgSize();
// This is the varNum for our load operations,
// only used when we have a struct with a LclVar source
unsigned srcVarNum = BAD_VAR_NUM;
if (varNode != nullptr)
{
srcVarNum = varNode->gtLclNum;
assert(srcVarNum < compiler->lvaCount);
// handle promote situation
LclVarDsc* varDsc = compiler->lvaTable + srcVarNum;
// This struct also must live in the stack frame
// And it can't live in a register (SIMD)
assert(varDsc->lvType == TYP_STRUCT);
assert(varDsc->lvOnFrame && !varDsc->lvRegister);
// We don't split HFA struct
assert(!varDsc->lvIsHfa());
}
else // addrNode is used
{
assert(addrNode != nullptr);
// Generate code to load the address that we need into a register
genConsumeAddress(addrNode);
addrReg = addrNode->gtRegNum;
// If addrReg equal to baseReg, we use the last target register as alternative baseReg.
// Because the candidate mask for the internal baseReg does not include any of the target register,
// we can ensure that baseReg, addrReg, and the last target register are not all same.
assert(baseReg != addrReg);
// We don't split HFA struct
assert(!compiler->IsHfa(source->gtObj.gtClass));
}
// Put on stack first
unsigned nextIndex = treeNode->gtNumRegs;
unsigned structOffset = nextIndex * TARGET_POINTER_SIZE;
int remainingSize = structSize - structOffset;
// remainingSize is always multiple of TARGET_POINTER_SIZE
assert(remainingSize % TARGET_POINTER_SIZE == 0);
while (remainingSize > 0)
{
var_types type = compiler->getJitGCType(gcPtrs[nextIndex]);
if (varNode != nullptr)
{
// Load from our varNumImp source
emit->emitIns_R_S(INS_ldr, emitTypeSize(type), baseReg, srcVarNum, structOffset);
}
else
{
// check for case of destroying the addrRegister while we still need it
assert(baseReg != addrReg);
// Load from our address expression source
emit->emitIns_R_R_I(INS_ldr, emitTypeSize(type), baseReg, addrReg, structOffset);
}
// Emit str instruction to store the register into the outgoing argument area
emit->emitIns_S_R(INS_str, emitTypeSize(type), baseReg, varNumOut, argOffsetOut);
argOffsetOut += TARGET_POINTER_SIZE; // We stored 4-bytes of the struct
assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area
remainingSize -= TARGET_POINTER_SIZE; // We loaded 4-bytes of the struct
structOffset += TARGET_POINTER_SIZE;
nextIndex += 1;
}
// We set up the registers in order, so that we assign the last target register `baseReg` is no longer in use,
// in case we had to reuse the last target register for it.
structOffset = 0;
for (unsigned idx = 0; idx < treeNode->gtNumRegs; idx++)
{
regNumber targetReg = treeNode->GetRegNumByIdx(idx);
var_types type = treeNode->GetRegType(idx);
if (varNode != nullptr)
{
// Load from our varNumImp source
emit->emitIns_R_S(INS_ldr, emitTypeSize(type), targetReg, srcVarNum, structOffset);
}
else
{
// check for case of destroying the addrRegister while we still need it
if (targetReg == addrReg && idx != treeNode->gtNumRegs - 1)
{
assert(targetReg != baseReg);
emit->emitIns_R_R(INS_mov, emitActualTypeSize(type), baseReg, addrReg);
addrReg = baseReg;
}
// Load from our address expression source
emit->emitIns_R_R_I(INS_ldr, emitTypeSize(type), targetReg, addrReg, structOffset);
}
structOffset += TARGET_POINTER_SIZE;
}
}
genProduceReg(treeNode);
}
#endif // _TARGET_ARM_
//----------------------------------------------------------------------------------
// genMultiRegCallStoreToLocal: store multi-reg return value of a call node to a local
//
// Arguments:
// treeNode - Gentree of GT_STORE_LCL_VAR
//
// Return Value:
// None
//
// Assumption:
// The child of store is a multi-reg call node.
// genProduceReg() on treeNode is made by caller of this routine.
//
void CodeGen::genMultiRegCallStoreToLocal(GenTreePtr treeNode)
{
assert(treeNode->OperGet() == GT_STORE_LCL_VAR);
#if defined(_TARGET_ARM_)
// Longs are returned in two return registers on Arm32.
// Structs are returned in four registers on ARM32 and HFAs.
assert(varTypeIsLong(treeNode) || varTypeIsStruct(treeNode));
#elif defined(_TARGET_ARM64_)
// Structs of size >=9 and <=16 are returned in two return registers on ARM64 and HFAs.
assert(varTypeIsStruct(treeNode));
#endif // _TARGET_*
// Assumption: current implementation requires that a multi-reg
// var in 'var = call' is flagged as lvIsMultiRegRet to prevent it from
// being promoted.
unsigned lclNum = treeNode->AsLclVarCommon()->gtLclNum;
LclVarDsc* varDsc = &(compiler->lvaTable[lclNum]);
noway_assert(varDsc->lvIsMultiRegRet);
GenTree* op1 = treeNode->gtGetOp1();
GenTree* actualOp1 = op1->gtSkipReloadOrCopy();
GenTreeCall* call = actualOp1->AsCall();
assert(call->HasMultiRegRetVal());
genConsumeRegs(op1);
ReturnTypeDesc* pRetTypeDesc = call->GetReturnTypeDesc();
unsigned regCount = pRetTypeDesc->GetReturnRegCount();
if (treeNode->gtRegNum != REG_NA)
{
// Right now the only enregistrable multi-reg return types supported are SIMD types.
assert(varTypeIsSIMD(treeNode));
NYI("GT_STORE_LCL_VAR of a SIMD enregisterable struct");
}
else
{
// Stack store
int offset = 0;
for (unsigned i = 0; i < regCount; ++i)
{
var_types type = pRetTypeDesc->GetReturnRegType(i);
regNumber reg = call->GetRegNumByIdx(i);
if (op1->IsCopyOrReload())
{
// GT_COPY/GT_RELOAD will have valid reg for those positions
// that need to be copied or reloaded.
regNumber reloadReg = op1->AsCopyOrReload()->GetRegNumByIdx(i);
if (reloadReg != REG_NA)
{
reg = reloadReg;
}
}
assert(reg != REG_NA);
getEmitter()->emitIns_S_R(ins_Store(type), emitTypeSize(type), reg, lclNum, offset);
offset += genTypeSize(type);
}
varDsc->lvRegNum = REG_STK;
}
}
//------------------------------------------------------------------------
// genRangeCheck: generate code for GT_ARR_BOUNDS_CHECK node.
//
void CodeGen::genRangeCheck(GenTreePtr oper)
{
#ifdef FEATURE_SIMD
noway_assert(oper->OperGet() == GT_ARR_BOUNDS_CHECK || oper->OperGet() == GT_SIMD_CHK);
#else // !FEATURE_SIMD
noway_assert(oper->OperGet() == GT_ARR_BOUNDS_CHECK);
#endif // !FEATURE_SIMD
GenTreeBoundsChk* bndsChk = oper->AsBoundsChk();
GenTreePtr arrLen = bndsChk->gtArrLen;
GenTreePtr arrIndex = bndsChk->gtIndex;
GenTreePtr arrRef = NULL;
int lenOffset = 0;
GenTree* src1;
GenTree* src2;
emitJumpKind jmpKind;
genConsumeRegs(arrIndex);
genConsumeRegs(arrLen);
if (arrIndex->isContainedIntOrIImmed())
{
// To encode using a cmp immediate, we place the
// constant operand in the second position
src1 = arrLen;
src2 = arrIndex;
jmpKind = genJumpKindForOper(GT_LE, CK_UNSIGNED);
}
else
{
src1 = arrIndex;
src2 = arrLen;
jmpKind = genJumpKindForOper(GT_GE, CK_UNSIGNED);
}
var_types bndsChkType = genActualType(src2->TypeGet());
#if DEBUG
// Bounds checks can only be 32 or 64 bit sized comparisons.
assert(bndsChkType == TYP_INT || bndsChkType == TYP_LONG);
// The type of the bounds check should always wide enough to compare against the index.
assert(emitTypeSize(bndsChkType) >= emitActualTypeSize(src1->TypeGet()));
#endif // DEBUG
getEmitter()->emitInsBinary(INS_cmp, emitActualTypeSize(bndsChkType), src1, src2);
genJumpToThrowHlpBlk(jmpKind, SCK_RNGCHK_FAIL, bndsChk->gtIndRngFailBB);
}
//---------------------------------------------------------------------
// genCodeForPhysReg - generate code for a GT_PHYSREG node
//
// Arguments
// tree - the GT_PHYSREG node
//
// Return value:
// None
//
void CodeGen::genCodeForPhysReg(GenTreePhysReg* tree)
{
assert(tree->OperIs(GT_PHYSREG));
var_types targetType = tree->TypeGet();
regNumber targetReg = tree->gtRegNum;
if (targetReg != tree->gtSrcReg)
{
inst_RV_RV(ins_Copy(targetType), targetReg, tree->gtSrcReg, targetType);
genTransferRegGCState(targetReg, tree->gtSrcReg);
}
genProduceReg(tree);
}
//---------------------------------------------------------------------
// genCodeForNullCheck - generate code for a GT_NULLCHECK node
//
// Arguments
// tree - the GT_NULLCHECK node
//
// Return value:
// None
//
void CodeGen::genCodeForNullCheck(GenTreeOp* tree)
{
assert(tree->OperIs(GT_NULLCHECK));
assert(!tree->gtOp1->isContained());
regNumber addrReg = genConsumeReg(tree->gtOp1);
#ifdef _TARGET_ARM64_
regNumber targetReg = REG_ZR;
#else
regNumber targetReg = tree->GetSingleTempReg();
#endif
getEmitter()->emitIns_R_R_I(INS_ldr, EA_4BYTE, targetReg, addrReg, 0);
}
//------------------------------------------------------------------------
// genOffsetOfMDArrayLowerBound: Returns the offset from the Array object to the
// lower bound for the given dimension.
//
// Arguments:
// elemType - the element type of the array
// rank - the rank of the array
// dimension - the dimension for which the lower bound offset will be returned.
//
// Return Value:
// The offset.
// TODO-Cleanup: move to CodeGenCommon.cpp
// static
unsigned CodeGen::genOffsetOfMDArrayLowerBound(var_types elemType, unsigned rank, unsigned dimension)
{
// Note that the lower bound and length fields of the Array object are always TYP_INT
return compiler->eeGetArrayDataOffset(elemType) + genTypeSize(TYP_INT) * (dimension + rank);
}
//------------------------------------------------------------------------
// genOffsetOfMDArrayLength: Returns the offset from the Array object to the
// size for the given dimension.
//
// Arguments:
// elemType - the element type of the array
// rank - the rank of the array
// dimension - the dimension for which the lower bound offset will be returned.
//
// Return Value:
// The offset.
// TODO-Cleanup: move to CodeGenCommon.cpp
// static
unsigned CodeGen::genOffsetOfMDArrayDimensionSize(var_types elemType, unsigned rank, unsigned dimension)
{
// Note that the lower bound and length fields of the Array object are always TYP_INT
return compiler->eeGetArrayDataOffset(elemType) + genTypeSize(TYP_INT) * dimension;
}
//------------------------------------------------------------------------
// genCodeForArrIndex: Generates code to bounds check the index for one dimension of an array reference,
// producing the effective index by subtracting the lower bound.
//
// Arguments:
// arrIndex - the node for which we're generating code
//
// Return Value:
// None.
//
void CodeGen::genCodeForArrIndex(GenTreeArrIndex* arrIndex)
{
emitter* emit = getEmitter();
GenTreePtr arrObj = arrIndex->ArrObj();
GenTreePtr indexNode = arrIndex->IndexExpr();
regNumber arrReg = genConsumeReg(arrObj);
regNumber indexReg = genConsumeReg(indexNode);
regNumber tgtReg = arrIndex->gtRegNum;
noway_assert(tgtReg != REG_NA);
// We will use a temp register to load the lower bound and dimension size values.
regNumber tmpReg = arrIndex->GetSingleTempReg();
assert(tgtReg != tmpReg);
unsigned dim = arrIndex->gtCurrDim;
unsigned rank = arrIndex->gtArrRank;
var_types elemType = arrIndex->gtArrElemType;
unsigned offset;
offset = genOffsetOfMDArrayLowerBound(elemType, rank, dim);
emit->emitIns_R_R_I(ins_Load(TYP_INT), EA_PTRSIZE, tmpReg, arrReg, offset); // a 4 BYTE sign extending load
emit->emitIns_R_R_R(INS_sub, EA_4BYTE, tgtReg, indexReg, tmpReg);
offset = genOffsetOfMDArrayDimensionSize(elemType, rank, dim);
emit->emitIns_R_R_I(ins_Load(TYP_INT), EA_PTRSIZE, tmpReg, arrReg, offset); // a 4 BYTE sign extending load
emit->emitIns_R_R(INS_cmp, EA_4BYTE, tgtReg, tmpReg);
emitJumpKind jmpGEU = genJumpKindForOper(GT_GE, CK_UNSIGNED);
genJumpToThrowHlpBlk(jmpGEU, SCK_RNGCHK_FAIL);
genProduceReg(arrIndex);
}
//------------------------------------------------------------------------
// genCodeForArrOffset: Generates code to compute the flattened array offset for
// one dimension of an array reference:
// result = (prevDimOffset * dimSize) + effectiveIndex
// where dimSize is obtained from the arrObj operand
//
// Arguments:
// arrOffset - the node for which we're generating code
//
// Return Value:
// None.
//
// Notes:
// dimSize and effectiveIndex are always non-negative, the former by design,
// and the latter because it has been normalized to be zero-based.
void CodeGen::genCodeForArrOffset(GenTreeArrOffs* arrOffset)
{
GenTreePtr offsetNode = arrOffset->gtOffset;
GenTreePtr indexNode = arrOffset->gtIndex;
regNumber tgtReg = arrOffset->gtRegNum;
noway_assert(tgtReg != REG_NA);
if (!offsetNode->IsIntegralConst(0))
{
emitter* emit = getEmitter();
regNumber offsetReg = genConsumeReg(offsetNode);
regNumber indexReg = genConsumeReg(indexNode);
regNumber arrReg = genConsumeReg(arrOffset->gtArrObj);
noway_assert(offsetReg != REG_NA);
noway_assert(indexReg != REG_NA);
noway_assert(arrReg != REG_NA);
regNumber tmpReg = arrOffset->GetSingleTempReg();
unsigned dim = arrOffset->gtCurrDim;
unsigned rank = arrOffset->gtArrRank;
var_types elemType = arrOffset->gtArrElemType;
unsigned offset = genOffsetOfMDArrayDimensionSize(elemType, rank, dim);
// Load tmpReg with the dimension size and evaluate
// tgtReg = offsetReg*tmpReg + indexReg.
emit->emitIns_R_R_I(ins_Load(TYP_INT), EA_PTRSIZE, tmpReg, arrReg, offset);
emit->emitIns_R_R_R_R(INS_MULADD, EA_PTRSIZE, tgtReg, tmpReg, offsetReg, indexReg);
}
else
{
regNumber indexReg = genConsumeReg(indexNode);
if (indexReg != tgtReg)
{
inst_RV_RV(INS_mov, tgtReg, indexReg, TYP_INT);
}
}
genProduceReg(arrOffset);
}
//------------------------------------------------------------------------
// indirForm: Make a temporary indir we can feed to pattern matching routines
// in cases where we don't want to instantiate all the indirs that happen.
//
GenTreeIndir CodeGen::indirForm(var_types type, GenTree* base)
{
GenTreeIndir i(GT_IND, type, base, nullptr);
i.gtRegNum = REG_NA;
i.SetContained();
// has to be nonnull (because contained nodes can't be the last in block)
// but don't want it to be a valid pointer
i.gtNext = (GenTree*)(-1);
return i;
}
//------------------------------------------------------------------------
// intForm: Make a temporary int we can feed to pattern matching routines
// in cases where we don't want to instantiate.
//
GenTreeIntCon CodeGen::intForm(var_types type, ssize_t value)
{
GenTreeIntCon i(type, value);
i.gtRegNum = REG_NA;
// has to be nonnull (because contained nodes can't be the last in block)
// but don't want it to be a valid pointer
i.gtNext = (GenTree*)(-1);
return i;
}
//------------------------------------------------------------------------
// genCodeForShift: Generates the code sequence for a GenTree node that
// represents a bit shift or rotate operation (<<, >>, >>>, rol, ror).
//
// Arguments:
// tree - the bit shift node (that specifies the type of bit shift to perform).
//
// Assumptions:
// a) All GenTrees are register allocated.
//
void CodeGen::genCodeForShift(GenTreePtr tree)
{
var_types targetType = tree->TypeGet();
genTreeOps oper = tree->OperGet();
instruction ins = genGetInsForOper(oper, targetType);
emitAttr size = emitActualTypeSize(tree);
assert(tree->gtRegNum != REG_NA);
genConsumeOperands(tree->AsOp());
GenTreePtr operand = tree->gtGetOp1();
GenTreePtr shiftBy = tree->gtGetOp2();
if (!shiftBy->IsCnsIntOrI())
{
getEmitter()->emitIns_R_R_R(ins, size, tree->gtRegNum, operand->gtRegNum, shiftBy->gtRegNum);
}
else
{
unsigned immWidth = emitter::getBitWidth(size); // For ARM64, immWidth will be set to 32 or 64
ssize_t shiftByImm = shiftBy->gtIntCon.gtIconVal & (immWidth - 1);
getEmitter()->emitIns_R_R_I(ins, size, tree->gtRegNum, operand->gtRegNum, shiftByImm);
}
genProduceReg(tree);
}
//------------------------------------------------------------------------
// genCodeForLclAddr: Generates the code for GT_LCL_FLD_ADDR/GT_LCL_VAR_ADDR.
//
// Arguments:
// tree - the node.
//
void CodeGen::genCodeForLclAddr(GenTree* tree)
{
assert(tree->OperIs(GT_LCL_FLD_ADDR, GT_LCL_VAR_ADDR));
var_types targetType = tree->TypeGet();
regNumber targetReg = tree->gtRegNum;
// Address of a local var.
noway_assert(targetType == TYP_BYREF);
inst_RV_TT(INS_lea, targetReg, tree, 0, EA_BYREF);
genProduceReg(tree);
}
//------------------------------------------------------------------------
// genCodeForLclFld: Produce code for a GT_LCL_FLD node.
//
// Arguments:
// tree - the GT_LCL_FLD node
//
void CodeGen::genCodeForLclFld(GenTreeLclFld* tree)
{
assert(tree->OperIs(GT_LCL_FLD));
var_types targetType = tree->TypeGet();
regNumber targetReg = tree->gtRegNum;
emitter* emit = getEmitter();
NYI_IF(targetType == TYP_STRUCT, "GT_LCL_FLD: struct load local field not supported");
assert(targetReg != REG_NA);
emitAttr size = emitTypeSize(targetType);
unsigned offs = tree->gtLclOffs;
unsigned varNum = tree->gtLclNum;
assert(varNum < compiler->lvaCount);
if (varTypeIsFloating(targetType))
{
emit->emitIns_R_S(ins_Load(targetType), size, targetReg, varNum, offs);
}
else
{
#ifdef _TARGET_ARM64_
size = EA_SET_SIZE(size, EA_8BYTE);
#endif // _TARGET_ARM64_
emit->emitIns_R_S(ins_Move_Extend(targetType, false), size, targetReg, varNum, offs);
}
genProduceReg(tree);
}
//------------------------------------------------------------------------
// genCodeForIndexAddr: Produce code for a GT_INDEX_ADDR node.
//
// Arguments:
// tree - the GT_INDEX_ADDR node
//
void CodeGen::genCodeForIndexAddr(GenTreeIndexAddr* node)
{
GenTree* const base = node->Arr();
GenTree* const index = node->Index();
genConsumeReg(base);
genConsumeReg(index);
// NOTE: `genConsumeReg` marks the consumed register as not a GC pointer, as it assumes that the input registers
// die at the first instruction generated by the node. This is not the case for `INDEX_ADDR`, however, as the
// base register is multiply-used. As such, we need to mark the base register as containing a GC pointer until
// we are finished generating the code for this node.
gcInfo.gcMarkRegPtrVal(base->gtRegNum, base->TypeGet());
assert(!varTypeIsGC(index->TypeGet()));
const regNumber tmpReg = node->GetSingleTempReg();
// Generate the bounds check if necessary.
if ((node->gtFlags & GTF_INX_RNGCHK) != 0)
{
// Create a GT_IND(GT_LEA)) tree for the array length access and load the length into a register.
GenTreeAddrMode arrLenAddr(base->TypeGet(), base, nullptr, 0, static_cast<unsigned>(node->gtLenOffset));
arrLenAddr.gtRegNum = REG_NA;
arrLenAddr.SetContained();
arrLenAddr.gtNext = (GenTree*)(-1);
GenTreeIndir arrLen = indirForm(TYP_INT, &arrLenAddr);
arrLen.gtRegNum = tmpReg;
arrLen.ClearContained();
getEmitter()->emitInsLoadStoreOp(ins_Load(TYP_INT), emitTypeSize(TYP_INT), arrLen.gtRegNum, &arrLen);
#ifdef _TARGET_64BIT_
// The CLI Spec allows an array to be indexed by either an int32 or a native int. In the case that the index
// is a native int on a 64-bit platform, we will need to widen the array length and the compare.
if (index->TypeGet() == TYP_I_IMPL)
{
// Extend the array length as needed.
getEmitter()->emitIns_R_R(ins_Move_Extend(TYP_INT, true), EA_8BYTE, arrLen.gtRegNum, arrLen.gtRegNum);
}
#endif
// Generate the range check.
getEmitter()->emitInsBinary(INS_cmp, emitActualTypeSize(TYP_I_IMPL), index, &arrLen);
genJumpToThrowHlpBlk(genJumpKindForOper(GT_GE, CK_UNSIGNED), SCK_RNGCHK_FAIL, node->gtIndRngFailBB);
}
// Compute the address of the array element.
switch (node->gtElemSize)
{
case 1:
// dest = base + index
getEmitter()->emitIns_R_R_R(INS_add, emitActualTypeSize(node), node->gtRegNum, base->gtRegNum,
index->gtRegNum);
break;
case 2:
case 4:
case 8:
case 16:
{
DWORD lsl;
BitScanForward(&lsl, node->gtElemSize);
// dest = base + index * scale
genScaledAdd(emitActualTypeSize(node), node->gtRegNum, base->gtRegNum, index->gtRegNum, lsl);
break;
}
default:
{
// tmp = scale
CodeGen::genSetRegToIcon(tmpReg, (ssize_t)node->gtElemSize, TYP_INT);
// dest = index * tmp + base
getEmitter()->emitIns_R_R_R_R(INS_MULADD, emitActualTypeSize(node), node->gtRegNum, index->gtRegNum, tmpReg,
base->gtRegNum);
break;
}
}
// dest = dest + elemOffs
getEmitter()->emitIns_R_R_I(INS_add, emitActualTypeSize(node), node->gtRegNum, node->gtRegNum, node->gtElemOffset);
gcInfo.gcMarkRegSetNpt(base->gtGetRegMask());
genProduceReg(node);
}
//------------------------------------------------------------------------
// genCodeForIndir: Produce code for a GT_IND node.
//
// Arguments:
// tree - the GT_IND node
//
void CodeGen::genCodeForIndir(GenTreeIndir* tree)
{
assert(tree->OperIs(GT_IND));
var_types targetType = tree->TypeGet();
regNumber targetReg = tree->gtRegNum;
emitter* emit = getEmitter();
emitAttr attr = emitTypeSize(tree);
instruction ins = ins_Load(targetType);
genConsumeAddress(tree->Addr());
if ((tree->gtFlags & GTF_IND_VOLATILE) != 0)
{
bool isAligned = ((tree->gtFlags & GTF_IND_UNALIGNED) == 0);
assert((attr != EA_1BYTE) || isAligned);
#ifdef _TARGET_ARM64_
GenTree* addr = tree->Addr();
bool useLoadAcquire = genIsValidIntReg(targetReg) && !addr->isContained() &&
(varTypeIsUnsigned(targetType) || varTypeIsI(targetType)) &&
!(tree->gtFlags & GTF_IND_UNALIGNED);
if (useLoadAcquire)
{
switch (EA_SIZE(attr))
{
case EA_1BYTE:
assert(ins == INS_ldrb);
ins = INS_ldarb;
break;
case EA_2BYTE:
assert(ins == INS_ldrh);
ins = INS_ldarh;
break;
case EA_4BYTE:
case EA_8BYTE:
assert(ins == INS_ldr);
ins = INS_ldar;
break;
default:
assert(false); // We should not get here
}
}
emit->emitInsLoadStoreOp(ins, attr, targetReg, tree);
if (!useLoadAcquire) // issue a INS_BARRIER_OSHLD after a volatile LdInd operation
instGen_MemoryBarrier(INS_BARRIER_OSHLD);
#else
emit->emitInsLoadStoreOp(ins, attr, targetReg, tree);
// issue a full memory barrier after a volatile LdInd operation
instGen_MemoryBarrier();
#endif // _TARGET_ARM64_
}
else
{
emit->emitInsLoadStoreOp(ins, attr, targetReg, tree);
}
genProduceReg(tree);
}
// Generate code for a CpBlk node by the means of the VM memcpy helper call
// Preconditions:
// a) The size argument of the CpBlk is not an integer constant
// b) The size argument is a constant but is larger than CPBLK_MOVS_LIMIT bytes.
void CodeGen::genCodeForCpBlk(GenTreeBlk* cpBlkNode)
{
// Make sure we got the arguments of the cpblk operation in the right registers
unsigned blockSize = cpBlkNode->Size();
GenTreePtr dstAddr = cpBlkNode->Addr();
assert(!dstAddr->isContained());
genConsumeBlockOp(cpBlkNode, REG_ARG_0, REG_ARG_1, REG_ARG_2);
#ifdef _TARGET_ARM64_
if (blockSize != 0)
{
assert(blockSize > CPBLK_UNROLL_LIMIT);
}
#endif // _TARGET_ARM64_
if (cpBlkNode->gtFlags & GTF_BLK_VOLATILE)
{
// issue a full memory barrier before a volatile CpBlk operation
instGen_MemoryBarrier();
}
genEmitHelperCall(CORINFO_HELP_MEMCPY, 0, EA_UNKNOWN);
if (cpBlkNode->gtFlags & GTF_BLK_VOLATILE)
{
#ifdef _TARGET_ARM64_
// issue a INS_BARRIER_ISHLD after a volatile CpBlk operation
instGen_MemoryBarrier(INS_BARRIER_ISHLD);
#else
// issue a full memory barrier after a volatile CpBlk operation
instGen_MemoryBarrier();
#endif // _TARGET_ARM64_
}
}
//----------------------------------------------------------------------------------
// genCodeForCpBlkUnroll: Generates CpBlk code by performing a loop unroll
//
// Arguments:
// cpBlkNode - Copy block node
//
// Return Value:
// None
//
// Assumption:
// The size argument of the CpBlk node is a constant and <= CPBLK_UNROLL_LIMIT bytes.
//
void CodeGen::genCodeForCpBlkUnroll(GenTreeBlk* cpBlkNode)
{
// Make sure we got the arguments of the cpblk operation in the right registers
unsigned size = cpBlkNode->Size();
GenTreePtr dstAddr = cpBlkNode->Addr();
GenTreePtr source = cpBlkNode->Data();
GenTreePtr srcAddr = nullptr;
assert((size != 0) && (size <= CPBLK_UNROLL_LIMIT));
emitter* emit = getEmitter();
if (dstAddr->isUsedFromReg())
{
genConsumeReg(dstAddr);
}
if (cpBlkNode->gtFlags & GTF_BLK_VOLATILE)
{
// issue a full memory barrier before a volatile CpBlkUnroll operation
instGen_MemoryBarrier();
}
if (source->gtOper == GT_IND)
{
srcAddr = source->gtGetOp1();
if (srcAddr->isUsedFromReg())
{
genConsumeReg(srcAddr);
}
}
else
{
noway_assert(source->IsLocal());
// TODO-Cleanup: Consider making the addrForm() method in Rationalize public, e.g. in GenTree.
// OR: transform source to GT_IND(GT_LCL_VAR_ADDR)
if (source->OperGet() == GT_LCL_VAR)
{
source->SetOper(GT_LCL_VAR_ADDR);
}
else
{
assert(source->OperGet() == GT_LCL_FLD);
source->SetOper(GT_LCL_FLD_ADDR);
}
srcAddr = source;
}
unsigned offset = 0;
// Grab the integer temp register to emit the loads and stores.
regNumber tmpReg = cpBlkNode->ExtractTempReg(RBM_ALLINT);
#ifdef _TARGET_ARM64_
if (size >= 2 * REGSIZE_BYTES)
{
regNumber tmp2Reg = cpBlkNode->ExtractTempReg(RBM_ALLINT);
size_t slots = size / (2 * REGSIZE_BYTES);
while (slots-- > 0)
{
// Load
genCodeForLoadPairOffset(tmpReg, tmp2Reg, srcAddr, offset);
// Store
genCodeForStorePairOffset(tmpReg, tmp2Reg, dstAddr, offset);
offset += 2 * REGSIZE_BYTES;
}
}
// Fill the remainder (15 bytes or less) if there's one.
if ((size & 0xf) != 0)
{
if ((size & 8) != 0)
{
genCodeForLoadOffset(INS_ldr, EA_8BYTE, tmpReg, srcAddr, offset);
genCodeForStoreOffset(INS_str, EA_8BYTE, tmpReg, dstAddr, offset);
offset += 8;
}
if ((size & 4) != 0)
{
genCodeForLoadOffset(INS_ldr, EA_4BYTE, tmpReg, srcAddr, offset);
genCodeForStoreOffset(INS_str, EA_4BYTE, tmpReg, dstAddr, offset);
offset += 4;
}
if ((size & 2) != 0)
{
genCodeForLoadOffset(INS_ldrh, EA_2BYTE, tmpReg, srcAddr, offset);
genCodeForStoreOffset(INS_strh, EA_2BYTE, tmpReg, dstAddr, offset);
offset += 2;
}
if ((size & 1) != 0)
{
genCodeForLoadOffset(INS_ldrb, EA_1BYTE, tmpReg, srcAddr, offset);
genCodeForStoreOffset(INS_strb, EA_1BYTE, tmpReg, dstAddr, offset);
}
}
#else // !_TARGET_ARM64_
size_t slots = size / REGSIZE_BYTES;
while (slots-- > 0)
{
genCodeForLoadOffset(INS_ldr, EA_4BYTE, tmpReg, srcAddr, offset);
genCodeForStoreOffset(INS_str, EA_4BYTE, tmpReg, dstAddr, offset);
offset += REGSIZE_BYTES;
}
// Fill the remainder (3 bytes or less) if there's one.
if ((size & 0x03) != 0)
{
if ((size & 2) != 0)
{
genCodeForLoadOffset(INS_ldrh, EA_2BYTE, tmpReg, srcAddr, offset);
genCodeForStoreOffset(INS_strh, EA_2BYTE, tmpReg, dstAddr, offset);
offset += 2;
}
if ((size & 1) != 0)
{
genCodeForLoadOffset(INS_ldrb, EA_1BYTE, tmpReg, srcAddr, offset);
genCodeForStoreOffset(INS_strb, EA_1BYTE, tmpReg, dstAddr, offset);
}
}
#endif // !_TARGET_ARM64_
if (cpBlkNode->gtFlags & GTF_BLK_VOLATILE)
{
#ifdef _TARGET_ARM64_
// issue a INS_BARRIER_ISHLD after a volatile CpBlkUnroll operation
instGen_MemoryBarrier(INS_BARRIER_ISHLD);
#else
// issue a full memory barrier after a volatile CpBlk operation
instGen_MemoryBarrier();
#endif // !_TARGET_ARM64_
}
}
// Generates code for InitBlk by calling the VM memset helper function.
// Preconditions:
// a) The size argument of the InitBlk is not an integer constant.
// b) The size argument of the InitBlk is >= INITBLK_STOS_LIMIT bytes.
void CodeGen::genCodeForInitBlk(GenTreeBlk* initBlkNode)
{
unsigned size = initBlkNode->Size();
GenTreePtr dstAddr = initBlkNode->Addr();
GenTreePtr initVal = initBlkNode->Data();
if (initVal->OperIsInitVal())
{
initVal = initVal->gtGetOp1();
}
assert(!dstAddr->isContained());
assert(!initVal->isContained());
#ifdef _TARGET_ARM64_
if (size != 0)
{
assert(size > INITBLK_UNROLL_LIMIT);
}
#endif // _TARGET_ARM64_
genConsumeBlockOp(initBlkNode, REG_ARG_0, REG_ARG_1, REG_ARG_2);
if (initBlkNode->gtFlags & GTF_BLK_VOLATILE)
{
// issue a full memory barrier before a volatile initBlock Operation
instGen_MemoryBarrier();
}
genEmitHelperCall(CORINFO_HELP_MEMSET, 0, EA_UNKNOWN);
}
// Generate code for a load from some address + offset
// base: tree node which can be either a local address or arbitrary node
// offset: distance from the base from which to load
void CodeGen::genCodeForLoadOffset(instruction ins, emitAttr size, regNumber dst, GenTree* base, unsigned offset)
{
emitter* emit = getEmitter();
if (base->OperIsLocalAddr())
{
if (base->gtOper == GT_LCL_FLD_ADDR)
offset += base->gtLclFld.gtLclOffs;
emit->emitIns_R_S(ins, size, dst, base->gtLclVarCommon.gtLclNum, offset);
}
else
{
emit->emitIns_R_R_I(ins, size, dst, base->gtRegNum, offset);
}
}
// Generate code for a store to some address + offset
// base: tree node which can be either a local address or arbitrary node
// offset: distance from the base from which to load
void CodeGen::genCodeForStoreOffset(instruction ins, emitAttr size, regNumber src, GenTree* base, unsigned offset)
{
emitter* emit = getEmitter();
if (base->OperIsLocalAddr())
{
if (base->gtOper == GT_LCL_FLD_ADDR)
offset += base->gtLclFld.gtLclOffs;
emit->emitIns_S_R(ins, size, src, base->gtLclVarCommon.gtLclNum, offset);
}
else
{
emit->emitIns_R_R_I(ins, size, src, base->gtRegNum, offset);
}
}
//------------------------------------------------------------------------
// genRegCopy: Generate a register copy.
//
void CodeGen::genRegCopy(GenTree* treeNode)
{
assert(treeNode->OperGet() == GT_COPY);
var_types targetType = treeNode->TypeGet();
regNumber targetReg = treeNode->gtRegNum;
assert(targetReg != REG_NA);
GenTree* op1 = treeNode->gtOp.gtOp1;
// Check whether this node and the node from which we're copying the value have the same
// register type.
// This can happen if (currently iff) we have a SIMD vector type that fits in an integer
// register, in which case it is passed as an argument, or returned from a call,
// in an integer register and must be copied if it's in an xmm register.
if (varTypeIsFloating(treeNode) != varTypeIsFloating(op1))
{
#ifdef _TARGET_ARM64_
inst_RV_RV(INS_fmov, targetReg, genConsumeReg(op1), targetType);
#else // !_TARGET_ARM64_
if (varTypeIsFloating(treeNode))
{
NYI_ARM("genRegCopy from 'int' to 'float'");
}
else
{
assert(varTypeIsFloating(op1));
if (op1->TypeGet() == TYP_FLOAT)
{
inst_RV_RV(INS_vmov_f2i, targetReg, genConsumeReg(op1), targetType);
}
else
{
regNumber otherReg = (regNumber)treeNode->AsCopyOrReload()->gtOtherRegs[0];
assert(otherReg != REG_NA);
inst_RV_RV_RV(INS_vmov_d2i, targetReg, otherReg, genConsumeReg(op1), EA_8BYTE);
}
}
#endif // !_TARGET_ARM64_
}
else
{
inst_RV_RV(ins_Copy(targetType), targetReg, genConsumeReg(op1), targetType);
}
if (op1->IsLocal())
{
// The lclVar will never be a def.
// If it is a last use, the lclVar will be killed by genConsumeReg(), as usual, and genProduceReg will
// appropriately set the gcInfo for the copied value.
// If not, there are two cases we need to handle:
// - If this is a TEMPORARY copy (indicated by the GTF_VAR_DEATH flag) the variable
// will remain live in its original register.
// genProduceReg() will appropriately set the gcInfo for the copied value,
// and genConsumeReg will reset it.
// - Otherwise, we need to update register info for the lclVar.
GenTreeLclVarCommon* lcl = op1->AsLclVarCommon();
assert((lcl->gtFlags & GTF_VAR_DEF) == 0);
if ((lcl->gtFlags & GTF_VAR_DEATH) == 0 && (treeNode->gtFlags & GTF_VAR_DEATH) == 0)
{
LclVarDsc* varDsc = &compiler->lvaTable[lcl->gtLclNum];
// If we didn't just spill it (in genConsumeReg, above), then update the register info
if (varDsc->lvRegNum != REG_STK)
{
// The old location is dying
genUpdateRegLife(varDsc, /*isBorn*/ false, /*isDying*/ true DEBUGARG(op1));
gcInfo.gcMarkRegSetNpt(genRegMask(op1->gtRegNum));
genUpdateVarReg(varDsc, treeNode);
// The new location is going live
genUpdateRegLife(varDsc, /*isBorn*/ true, /*isDying*/ false DEBUGARG(treeNode));
}
}
}
genProduceReg(treeNode);
}
//------------------------------------------------------------------------
// genCallInstruction: Produce code for a GT_CALL node
//
void CodeGen::genCallInstruction(GenTreeCall* call)
{
gtCallTypes callType = (gtCallTypes)call->gtCallType;
IL_OFFSETX ilOffset = BAD_IL_OFFSET;
// all virtuals should have been expanded into a control expression
assert(!call->IsVirtual() || call->gtControlExpr || call->gtCallAddr);
// Consume all the arg regs
for (GenTreePtr list = call->gtCallLateArgs; list; list = list->MoveNext())
{
assert(list->OperIsList());
GenTreePtr argNode = list->Current();
fgArgTabEntryPtr curArgTabEntry = compiler->gtArgEntryByNode(call, argNode);
assert(curArgTabEntry);
// GT_RELOAD/GT_COPY use the child node
argNode = argNode->gtSkipReloadOrCopy();
if (curArgTabEntry->regNum == REG_STK)
continue;
// Deal with multi register passed struct args.
if (argNode->OperGet() == GT_FIELD_LIST)
{
GenTreeArgList* argListPtr = argNode->AsArgList();
unsigned iterationNum = 0;
regNumber argReg = curArgTabEntry->regNum;
for (; argListPtr != nullptr; argListPtr = argListPtr->Rest(), iterationNum++)
{
GenTreePtr putArgRegNode = argListPtr->gtOp.gtOp1;
assert(putArgRegNode->gtOper == GT_PUTARG_REG);
genConsumeReg(putArgRegNode);
if (putArgRegNode->gtRegNum != argReg)
{
inst_RV_RV(ins_Move_Extend(putArgRegNode->TypeGet(), true), argReg, putArgRegNode->gtRegNum);
}
argReg = genRegArgNext(argReg);
#if defined(_TARGET_ARM_)
// A double register is modelled as an even-numbered single one
if (putArgRegNode->TypeGet() == TYP_DOUBLE)
{
argReg = genRegArgNext(argReg);
}
#endif // _TARGET_ARM_
}
}
#ifdef _TARGET_ARM_
else if (curArgTabEntry->isSplit)
{
assert(curArgTabEntry->numRegs >= 1);
genConsumeArgSplitStruct(argNode->AsPutArgSplit());
for (unsigned idx = 0; idx < curArgTabEntry->numRegs; idx++)
{
regNumber argReg = (regNumber)((unsigned)curArgTabEntry->regNum + idx);
regNumber allocReg = argNode->AsPutArgSplit()->GetRegNumByIdx(idx);
if (argReg != allocReg)
{
inst_RV_RV(ins_Move_Extend(argNode->TypeGet(), true), argReg, allocReg);
}
}
}
#endif
else
{
regNumber argReg = curArgTabEntry->regNum;
genConsumeReg(argNode);
if (argNode->gtRegNum != argReg)
{
inst_RV_RV(ins_Move_Extend(argNode->TypeGet(), true), argReg, argNode->gtRegNum);
}
}
}
// Insert a null check on "this" pointer if asked.
if (call->NeedsNullCheck())
{
const regNumber regThis = genGetThisArgReg(call);
#if defined(_TARGET_ARM_)
const regNumber tmpReg = call->ExtractTempReg();
getEmitter()->emitIns_R_R_I(INS_ldr, EA_4BYTE, tmpReg, regThis, 0);
#elif defined(_TARGET_ARM64_)
getEmitter()->emitIns_R_R_I(INS_ldr, EA_4BYTE, REG_ZR, regThis, 0);
#endif // _TARGET_*
}
// Either gtControlExpr != null or gtCallAddr != null or it is a direct non-virtual call to a user or helper method.
CORINFO_METHOD_HANDLE methHnd;
GenTree* target = call->gtControlExpr;
if (callType == CT_INDIRECT)
{
assert(target == nullptr);
target = call->gtCallAddr;
methHnd = nullptr;
}
else
{
methHnd = call->gtCallMethHnd;
}
CORINFO_SIG_INFO* sigInfo = nullptr;
#ifdef DEBUG
// Pass the call signature information down into the emitter so the emitter can associate
// native call sites with the signatures they were generated from.
if (callType != CT_HELPER)
{
sigInfo = call->callSig;
}
#endif // DEBUG
// If fast tail call, then we are done. In this case we setup the args (both reg args
// and stack args in incoming arg area) and call target. Epilog sequence would
// generate "br <reg>".
if (call->IsFastTailCall())
{
// Don't support fast tail calling JIT helpers
assert(callType != CT_HELPER);
// Fast tail calls materialize call target either in gtControlExpr or in gtCallAddr.
assert(target != nullptr);
genConsumeReg(target);
// Use IP0 on ARM64 and R12 on ARM32 as the call target register.
if (target->gtRegNum != REG_FASTTAILCALL_TARGET)
{
inst_RV_RV(INS_mov, REG_FASTTAILCALL_TARGET, target->gtRegNum);
}
return;
}
// For a pinvoke to unmanaged code we emit a label to clear
// the GC pointer state before the callsite.
// We can't utilize the typical lazy killing of GC pointers
// at (or inside) the callsite.
if (compiler->killGCRefs(call))
{
genDefineTempLabel(genCreateTempLabel());
}
// Determine return value size(s).
ReturnTypeDesc* pRetTypeDesc = call->GetReturnTypeDesc();
emitAttr retSize = EA_PTRSIZE;
emitAttr secondRetSize = EA_UNKNOWN;
if (call->HasMultiRegRetVal())
{
retSize = emitTypeSize(pRetTypeDesc->GetReturnRegType(0));
secondRetSize = emitTypeSize(pRetTypeDesc->GetReturnRegType(1));
}
else
{
assert(!varTypeIsStruct(call));
if (call->gtType == TYP_REF || call->gtType == TYP_ARRAY)
{
retSize = EA_GCREF;
}
else if (call->gtType == TYP_BYREF)
{
retSize = EA_BYREF;
}
}
// We need to propagate the IL offset information to the call instruction, so we can emit
// an IL to native mapping record for the call, to support managed return value debugging.
// We don't want tail call helper calls that were converted from normal calls to get a record,
// so we skip this hash table lookup logic in that case.
if (compiler->opts.compDbgInfo && compiler->genCallSite2ILOffsetMap != nullptr && !call->IsTailCall())
{
(void)compiler->genCallSite2ILOffsetMap->Lookup(call, &ilOffset);
}
if (target != nullptr)
{
// A call target can not be a contained indirection
assert(!target->isContainedIndir());
genConsumeReg(target);
// We have already generated code for gtControlExpr evaluating it into a register.
// We just need to emit "call reg" in this case.
//
assert(genIsValidIntReg(target->gtRegNum));
genEmitCall(emitter::EC_INDIR_R, methHnd,
INDEBUG_LDISASM_COMMA(sigInfo) nullptr, // addr
retSize MULTIREG_HAS_SECOND_GC_RET_ONLY_ARG(secondRetSize), ilOffset, target->gtRegNum);
}
else
{
// Generate a direct call to a non-virtual user defined or helper method
assert(callType == CT_HELPER || callType == CT_USER_FUNC);
void* addr = nullptr;
#ifdef FEATURE_READYTORUN_COMPILER
if (call->gtEntryPoint.addr != NULL)
{
assert(call->gtEntryPoint.accessType == IAT_VALUE);
addr = call->gtEntryPoint.addr;
}
else
#endif // FEATURE_READYTORUN_COMPILER
if (callType == CT_HELPER)
{
CorInfoHelpFunc helperNum = compiler->eeGetHelperNum(methHnd);
noway_assert(helperNum != CORINFO_HELP_UNDEF);
void* pAddr = nullptr;
addr = compiler->compGetHelperFtn(helperNum, (void**)&pAddr);
assert(pAddr == nullptr);
}
else
{
// Direct call to a non-virtual user function.
addr = call->gtDirectCallAddress;
}
assert(addr != nullptr);
// Non-virtual direct call to known addresses
#ifdef _TARGET_ARM_
if (!arm_Valid_Imm_For_BL((ssize_t)addr))
{
regNumber tmpReg = call->GetSingleTempReg();
instGen_Set_Reg_To_Imm(EA_HANDLE_CNS_RELOC, tmpReg, (ssize_t)addr);
genEmitCall(emitter::EC_INDIR_R, methHnd, INDEBUG_LDISASM_COMMA(sigInfo) NULL, retSize, ilOffset, tmpReg);
}
else
#endif // _TARGET_ARM_
{
genEmitCall(emitter::EC_FUNC_TOKEN, methHnd, INDEBUG_LDISASM_COMMA(sigInfo) addr,
retSize MULTIREG_HAS_SECOND_GC_RET_ONLY_ARG(secondRetSize), ilOffset);
}
#if 0 && defined(_TARGET_ARM64_)
// Use this path if you want to load an absolute call target using
// a sequence of movs followed by an indirect call (blr instruction)
// Load the call target address in x16
instGen_Set_Reg_To_Imm(EA_8BYTE, REG_IP0, (ssize_t) addr);
// indirect call to constant address in IP0
genEmitCall(emitter::EC_INDIR_R,
methHnd,
INDEBUG_LDISASM_COMMA(sigInfo)
nullptr, //addr
retSize,
secondRetSize,
ilOffset,
REG_IP0);
#endif
}
// if it was a pinvoke we may have needed to get the address of a label
if (genPendingCallLabel)
{
assert(call->IsUnmanaged());
genDefineTempLabel(genPendingCallLabel);
genPendingCallLabel = nullptr;
}
// Update GC info:
// All Callee arg registers are trashed and no longer contain any GC pointers.
// TODO-Bug?: As a matter of fact shouldn't we be killing all of callee trashed regs here?
// For now we will assert that other than arg regs gc ref/byref set doesn't contain any other
// registers from RBM_CALLEE_TRASH
assert((gcInfo.gcRegGCrefSetCur & (RBM_CALLEE_TRASH & ~RBM_ARG_REGS)) == 0);
assert((gcInfo.gcRegByrefSetCur & (RBM_CALLEE_TRASH & ~RBM_ARG_REGS)) == 0);
gcInfo.gcRegGCrefSetCur &= ~RBM_ARG_REGS;
gcInfo.gcRegByrefSetCur &= ~RBM_ARG_REGS;
var_types returnType = call->TypeGet();
if (returnType != TYP_VOID)
{
regNumber returnReg;
if (call->HasMultiRegRetVal())
{
assert(pRetTypeDesc != nullptr);
unsigned regCount = pRetTypeDesc->GetReturnRegCount();
// If regs allocated to call node are different from ABI return
// regs in which the call has returned its result, move the result
// to regs allocated to call node.
for (unsigned i = 0; i < regCount; ++i)
{
var_types regType = pRetTypeDesc->GetReturnRegType(i);
returnReg = pRetTypeDesc->GetABIReturnReg(i);
regNumber allocatedReg = call->GetRegNumByIdx(i);
if (returnReg != allocatedReg)
{
inst_RV_RV(ins_Copy(regType), allocatedReg, returnReg, regType);
}
}
}
else
{
#ifdef _TARGET_ARM_
if (call->IsHelperCall(compiler, CORINFO_HELP_INIT_PINVOKE_FRAME))
{
// The CORINFO_HELP_INIT_PINVOKE_FRAME helper uses a custom calling convention that returns with
// TCB in REG_PINVOKE_TCB. fgMorphCall() sets the correct argument registers.
returnReg = REG_PINVOKE_TCB;
}
else
#endif // _TARGET_ARM_
if (varTypeIsFloating(returnType) && !compiler->opts.compUseSoftFP)
{
returnReg = REG_FLOATRET;
}
else
{
returnReg = REG_INTRET;
}
if (call->gtRegNum != returnReg)
{
#ifdef _TARGET_ARM_
if (compiler->opts.compUseSoftFP && returnType == TYP_DOUBLE)
{
inst_RV_RV_RV(INS_vmov_i2d, call->gtRegNum, returnReg, genRegArgNext(returnReg), EA_8BYTE);
}
else if (compiler->opts.compUseSoftFP && returnType == TYP_FLOAT)
{
inst_RV_RV(INS_vmov_i2f, call->gtRegNum, returnReg, returnType);
}
else
#endif
{
inst_RV_RV(ins_Copy(returnType), call->gtRegNum, returnReg, returnType);
}
}
}
genProduceReg(call);
}
// If there is nothing next, that means the result is thrown away, so this value is not live.
// However, for minopts or debuggable code, we keep it live to support managed return value debugging.
if ((call->gtNext == nullptr) && !compiler->opts.MinOpts() && !compiler->opts.compDbgCode)
{
gcInfo.gcMarkRegSetNpt(RBM_INTRET);
}
}
// Produce code for a GT_JMP node.
// The arguments of the caller needs to be transferred to the callee before exiting caller.
// The actual jump to callee is generated as part of caller epilog sequence.
// Therefore the codegen of GT_JMP is to ensure that the callee arguments are correctly setup.
void CodeGen::genJmpMethod(GenTreePtr jmp)
{
assert(jmp->OperGet() == GT_JMP);
assert(compiler->compJmpOpUsed);
// If no arguments, nothing to do
if (compiler->info.compArgsCount == 0)
{
return;
}
// Make sure register arguments are in their initial registers
// and stack arguments are put back as well.
unsigned varNum;
LclVarDsc* varDsc;
// First move any en-registered stack arguments back to the stack.
// At the same time any reg arg not in correct reg is moved back to its stack location.
//
// We are not strictly required to spill reg args that are not in the desired reg for a jmp call
// But that would require us to deal with circularity while moving values around. Spilling
// to stack makes the implementation simple, which is not a bad trade off given Jmp calls
// are not frequent.
for (varNum = 0; (varNum < compiler->info.compArgsCount); varNum++)
{
varDsc = compiler->lvaTable + varNum;
if (varDsc->lvPromoted)
{
noway_assert(varDsc->lvFieldCnt == 1); // We only handle one field here
unsigned fieldVarNum = varDsc->lvFieldLclStart;
varDsc = compiler->lvaTable + fieldVarNum;
}
noway_assert(varDsc->lvIsParam);
if (varDsc->lvIsRegArg && (varDsc->lvRegNum != REG_STK))
{
// Skip reg args which are already in its right register for jmp call.
// If not, we will spill such args to their stack locations.
//
// If we need to generate a tail call profiler hook, then spill all
// arg regs to free them up for the callback.
if (!compiler->compIsProfilerHookNeeded() && (varDsc->lvRegNum == varDsc->lvArgReg))
continue;
}
else if (varDsc->lvRegNum == REG_STK)
{
// Skip args which are currently living in stack.
continue;
}
// If we came here it means either a reg argument not in the right register or
// a stack argument currently living in a register. In either case the following
// assert should hold.
assert(varDsc->lvRegNum != REG_STK);
assert(varDsc->TypeGet() != TYP_STRUCT);
var_types storeType = genActualType(varDsc->TypeGet());
emitAttr storeSize = emitActualTypeSize(storeType);
#ifdef _TARGET_ARM_
if (varDsc->TypeGet() == TYP_LONG)
{
// long - at least the low half must be enregistered
getEmitter()->emitIns_S_R(ins_Store(TYP_INT), EA_4BYTE, varDsc->lvRegNum, varNum, 0);
// Is the upper half also enregistered?
if (varDsc->lvOtherReg != REG_STK)
{
getEmitter()->emitIns_S_R(ins_Store(TYP_INT), EA_4BYTE, varDsc->lvOtherReg, varNum, sizeof(int));
}
}
else
#endif // _TARGET_ARM_
{
getEmitter()->emitIns_S_R(ins_Store(storeType), storeSize, varDsc->lvRegNum, varNum, 0);
}
// Update lvRegNum life and GC info to indicate lvRegNum is dead and varDsc stack slot is going live.
// Note that we cannot modify varDsc->lvRegNum here because another basic block may not be expecting it.
// Therefore manually update life of varDsc->lvRegNum.
regMaskTP tempMask = genRegMask(varDsc->lvRegNum);
regSet.RemoveMaskVars(tempMask);
gcInfo.gcMarkRegSetNpt(tempMask);
if (compiler->lvaIsGCTracked(varDsc))
{
VarSetOps::AddElemD(compiler, gcInfo.gcVarPtrSetCur, varNum);
}
}
#ifdef PROFILING_SUPPORTED
// At this point all arg regs are free.
// Emit tail call profiler callback.
genProfilingLeaveCallback(CORINFO_HELP_PROF_FCN_TAILCALL);
#endif
// Next move any un-enregistered register arguments back to their register.
regMaskTP fixedIntArgMask = RBM_NONE; // tracks the int arg regs occupying fixed args in case of a vararg method.
unsigned firstArgVarNum = BAD_VAR_NUM; // varNum of the first argument in case of a vararg method.
for (varNum = 0; (varNum < compiler->info.compArgsCount); varNum++)
{
varDsc = compiler->lvaTable + varNum;
if (varDsc->lvPromoted)
{
noway_assert(varDsc->lvFieldCnt == 1); // We only handle one field here
unsigned fieldVarNum = varDsc->lvFieldLclStart;
varDsc = compiler->lvaTable + fieldVarNum;
}
noway_assert(varDsc->lvIsParam);
// Skip if arg not passed in a register.
if (!varDsc->lvIsRegArg)
continue;
// Register argument
noway_assert(isRegParamType(genActualType(varDsc->TypeGet())));
// Is register argument already in the right register?
// If not load it from its stack location.
regNumber argReg = varDsc->lvArgReg; // incoming arg register
regNumber argRegNext = REG_NA;
#ifdef _TARGET_ARM64_
if (varDsc->lvRegNum != argReg)
{
var_types loadType = TYP_UNDEF;
if (varTypeIsStruct(varDsc))
{
// Must be <= 16 bytes or else it wouldn't be passed in registers
noway_assert(EA_SIZE_IN_BYTES(varDsc->lvSize()) <= MAX_PASS_MULTIREG_BYTES);
loadType = compiler->getJitGCType(varDsc->lvGcLayout[0]);
}
else
{
loadType = compiler->mangleVarArgsType(genActualType(varDsc->TypeGet()));
}
emitAttr loadSize = emitActualTypeSize(loadType);
getEmitter()->emitIns_R_S(ins_Load(loadType), loadSize, argReg, varNum, 0);
// Update argReg life and GC Info to indicate varDsc stack slot is dead and argReg is going live.
// Note that we cannot modify varDsc->lvRegNum here because another basic block may not be expecting it.
// Therefore manually update life of argReg. Note that GT_JMP marks the end of the basic block
// and after which reg life and gc info will be recomputed for the new block in genCodeForBBList().
regSet.AddMaskVars(genRegMask(argReg));
gcInfo.gcMarkRegPtrVal(argReg, loadType);
if (compiler->lvaIsMultiregStruct(varDsc))
{
if (varDsc->lvIsHfa())
{
NYI_ARM64("CodeGen::genJmpMethod with multireg HFA arg");
}
// Restore the second register.
argRegNext = genRegArgNext(argReg);
loadType = compiler->getJitGCType(varDsc->lvGcLayout[1]);
loadSize = emitActualTypeSize(loadType);
getEmitter()->emitIns_R_S(ins_Load(loadType), loadSize, argRegNext, varNum, TARGET_POINTER_SIZE);
regSet.AddMaskVars(genRegMask(argRegNext));
gcInfo.gcMarkRegPtrVal(argRegNext, loadType);
}
if (compiler->lvaIsGCTracked(varDsc))
{
VarSetOps::RemoveElemD(compiler, gcInfo.gcVarPtrSetCur, varNum);
}
}
// In case of a jmp call to a vararg method ensure only integer registers are passed.
if (compiler->info.compIsVarArgs)
{
assert((genRegMask(argReg) & RBM_ARG_REGS) != RBM_NONE);
fixedIntArgMask |= genRegMask(argReg);
if (compiler->lvaIsMultiregStruct(varDsc))
{
assert(argRegNext != REG_NA);
fixedIntArgMask |= genRegMask(argRegNext);
}
if (argReg == REG_ARG_0)
{
assert(firstArgVarNum == BAD_VAR_NUM);
firstArgVarNum = varNum;
}
}
#else
bool twoParts = false;
var_types loadType = TYP_UNDEF;
if (varDsc->TypeGet() == TYP_LONG)
{
twoParts = true;
}
else if (varDsc->TypeGet() == TYP_DOUBLE)
{
if (compiler->info.compIsVarArgs || compiler->opts.compUseSoftFP)
{
twoParts = true;
}
}
if (twoParts)
{
argRegNext = genRegArgNext(argReg);
if (varDsc->lvRegNum != argReg)
{
getEmitter()->emitIns_R_S(INS_ldr, EA_PTRSIZE, argReg, varNum, 0);
getEmitter()->emitIns_R_S(INS_ldr, EA_PTRSIZE, argRegNext, varNum, REGSIZE_BYTES);
}
if (compiler->info.compIsVarArgs)
{
fixedIntArgMask |= genRegMask(argReg);
fixedIntArgMask |= genRegMask(argRegNext);
}
}
else if (varDsc->lvIsHfaRegArg())
{
loadType = varDsc->GetHfaType();
regNumber fieldReg = argReg;
emitAttr loadSize = emitActualTypeSize(loadType);
unsigned maxSize = min(varDsc->lvSize(), (LAST_FP_ARGREG + 1 - argReg) * REGSIZE_BYTES);
for (unsigned ofs = 0; ofs < maxSize; ofs += (unsigned)loadSize)
{
if (varDsc->lvRegNum != argReg)
{
getEmitter()->emitIns_R_S(ins_Load(loadType), loadSize, fieldReg, varNum, ofs);
}
assert(genIsValidFloatReg(fieldReg)); // we don't use register tracking for FP
fieldReg = regNextOfType(fieldReg, loadType);
}
}
else if (varTypeIsStruct(varDsc))
{
regNumber slotReg = argReg;
unsigned maxSize = min(varDsc->lvSize(), (REG_ARG_LAST + 1 - argReg) * REGSIZE_BYTES);
for (unsigned ofs = 0; ofs < maxSize; ofs += REGSIZE_BYTES)
{
unsigned idx = ofs / REGSIZE_BYTES;
loadType = compiler->getJitGCType(varDsc->lvGcLayout[idx]);
if (varDsc->lvRegNum != argReg)
{
emitAttr loadSize = emitActualTypeSize(loadType);
getEmitter()->emitIns_R_S(ins_Load(loadType), loadSize, slotReg, varNum, ofs);
}
regSet.AddMaskVars(genRegMask(slotReg));
gcInfo.gcMarkRegPtrVal(slotReg, loadType);
if (genIsValidIntReg(slotReg) && compiler->info.compIsVarArgs)
{
fixedIntArgMask |= genRegMask(slotReg);
}
slotReg = genRegArgNext(slotReg);
}
}
else
{
loadType = compiler->mangleVarArgsType(genActualType(varDsc->TypeGet()));
if (varDsc->lvRegNum != argReg)
{
getEmitter()->emitIns_R_S(ins_Load(loadType), emitTypeSize(loadType), argReg, varNum, 0);
}
regSet.AddMaskVars(genRegMask(argReg));
gcInfo.gcMarkRegPtrVal(argReg, loadType);
if (genIsValidIntReg(argReg) && compiler->info.compIsVarArgs)
{
fixedIntArgMask |= genRegMask(argReg);
}
}
if (compiler->lvaIsGCTracked(varDsc))
{
VarSetOps::RemoveElemD(compiler, gcInfo.gcVarPtrSetCur, varNum);
}
#endif
}
// Jmp call to a vararg method - if the method has fewer than fixed arguments that can be max size of reg,
// load the remaining integer arg registers from the corresponding
// shadow stack slots. This is for the reason that we don't know the number and type
// of non-fixed params passed by the caller, therefore we have to assume the worst case
// of caller passing all integer arg regs that can be max size of reg.
//
// The caller could have passed gc-ref/byref type var args. Since these are var args
// the callee no way of knowing their gc-ness. Therefore, mark the region that loads
// remaining arg registers from shadow stack slots as non-gc interruptible.
if (fixedIntArgMask != RBM_NONE)
{
assert(compiler->info.compIsVarArgs);
assert(firstArgVarNum != BAD_VAR_NUM);
regMaskTP remainingIntArgMask = RBM_ARG_REGS & ~fixedIntArgMask;
if (remainingIntArgMask != RBM_NONE)
{
getEmitter()->emitDisableGC();
for (int argNum = 0, argOffset = 0; argNum < MAX_REG_ARG; ++argNum)
{
regNumber argReg = intArgRegs[argNum];
regMaskTP argRegMask = genRegMask(argReg);
if ((remainingIntArgMask & argRegMask) != 0)
{
remainingIntArgMask &= ~argRegMask;
getEmitter()->emitIns_R_S(INS_ldr, EA_PTRSIZE, argReg, firstArgVarNum, argOffset);
}
argOffset += REGSIZE_BYTES;
}
getEmitter()->emitEnableGC();
}
}
}
//------------------------------------------------------------------------
// genIntToIntCast: Generate code for an integer cast
//
// Arguments:
// treeNode - The GT_CAST node
//
// Return Value:
// None.
//
// Assumptions:
// The treeNode must have an assigned register.
// For a signed convert from byte, the source must be in a byte-addressable register.
// Neither the source nor target type can be a floating point type.
//
// TODO-ARM64-CQ: Allow castOp to be a contained node without an assigned register.
//
void CodeGen::genIntToIntCast(GenTreePtr treeNode)
{
assert(treeNode->OperGet() == GT_CAST);
GenTreePtr castOp = treeNode->gtCast.CastOp();
emitter* emit = getEmitter();
var_types dstType = treeNode->CastToType();
var_types srcType = genActualType(castOp->TypeGet());
emitAttr movSize = emitActualTypeSize(dstType);
bool movRequired = false;
#ifdef _TARGET_ARM_
if (varTypeIsLong(srcType))
{
genLongToIntCast(treeNode);
return;
}
#endif // _TARGET_ARM_
regNumber targetReg = treeNode->gtRegNum;
regNumber sourceReg = castOp->gtRegNum;
// For Long to Int conversion we will have a reserved integer register to hold the immediate mask
regNumber tmpReg = (treeNode->AvailableTempRegCount() == 0) ? REG_NA : treeNode->GetSingleTempReg();
assert(genIsValidIntReg(targetReg));
assert(genIsValidIntReg(sourceReg));
instruction ins = INS_invalid;
genConsumeReg(castOp);
Lowering::CastInfo castInfo;
// Get information about the cast.
Lowering::getCastDescription(treeNode, &castInfo);
if (castInfo.requiresOverflowCheck)
{
emitAttr cmpSize = EA_ATTR(genTypeSize(srcType));
if (castInfo.signCheckOnly)
{
// We only need to check for a negative value in sourceReg
emit->emitIns_R_I(INS_cmp, cmpSize, sourceReg, 0);
emitJumpKind jmpLT = genJumpKindForOper(GT_LT, CK_SIGNED);
genJumpToThrowHlpBlk(jmpLT, SCK_OVERFLOW);
noway_assert(genTypeSize(srcType) == 4 || genTypeSize(srcType) == 8);
// This is only interesting case to ensure zero-upper bits.
if ((srcType == TYP_INT) && (dstType == TYP_ULONG))
{
// cast to TYP_ULONG:
// We use a mov with size=EA_4BYTE
// which will zero out the upper bits
movSize = EA_4BYTE;
movRequired = true;
}
}
else if (castInfo.unsignedSource || castInfo.unsignedDest)
{
// When we are converting from/to unsigned,
// we only have to check for any bits set in 'typeMask'
noway_assert(castInfo.typeMask != 0);
#if defined(_TARGET_ARM_)
if (arm_Valid_Imm_For_Instr(INS_tst, castInfo.typeMask, INS_FLAGS_DONT_CARE))
{
emit->emitIns_R_I(INS_tst, cmpSize, sourceReg, castInfo.typeMask);
}
else
{
noway_assert(tmpReg != REG_NA);
instGen_Set_Reg_To_Imm(cmpSize, tmpReg, castInfo.typeMask);
emit->emitIns_R_R(INS_tst, cmpSize, sourceReg, tmpReg);
}
#elif defined(_TARGET_ARM64_)
emit->emitIns_R_I(INS_tst, cmpSize, sourceReg, castInfo.typeMask);
#endif // _TARGET_ARM*
emitJumpKind jmpNotEqual = genJumpKindForOper(GT_NE, CK_SIGNED);
genJumpToThrowHlpBlk(jmpNotEqual, SCK_OVERFLOW);
}
else
{
// For a narrowing signed cast
//
// We must check the value is in a signed range.
// Compare with the MAX
noway_assert((castInfo.typeMin != 0) && (castInfo.typeMax != 0));
#if defined(_TARGET_ARM_)
if (emitter::emitIns_valid_imm_for_cmp(castInfo.typeMax, INS_FLAGS_DONT_CARE))
#elif defined(_TARGET_ARM64_)
if (emitter::emitIns_valid_imm_for_cmp(castInfo.typeMax, cmpSize))
#endif // _TARGET_*
{
emit->emitIns_R_I(INS_cmp, cmpSize, sourceReg, castInfo.typeMax);
}
else
{
noway_assert(tmpReg != REG_NA);
instGen_Set_Reg_To_Imm(cmpSize, tmpReg, castInfo.typeMax);
emit->emitIns_R_R(INS_cmp, cmpSize, sourceReg, tmpReg);
}
emitJumpKind jmpGT = genJumpKindForOper(GT_GT, CK_SIGNED);
genJumpToThrowHlpBlk(jmpGT, SCK_OVERFLOW);
// Compare with the MIN
#if defined(_TARGET_ARM_)
if (emitter::emitIns_valid_imm_for_cmp(castInfo.typeMin, INS_FLAGS_DONT_CARE))
#elif defined(_TARGET_ARM64_)
if (emitter::emitIns_valid_imm_for_cmp(castInfo.typeMin, cmpSize))
#endif // _TARGET_*
{
emit->emitIns_R_I(INS_cmp, cmpSize, sourceReg, castInfo.typeMin);
}
else
{
noway_assert(tmpReg != REG_NA);
instGen_Set_Reg_To_Imm(cmpSize, tmpReg, castInfo.typeMin);
emit->emitIns_R_R(INS_cmp, cmpSize, sourceReg, tmpReg);
}
emitJumpKind jmpLT = genJumpKindForOper(GT_LT, CK_SIGNED);
genJumpToThrowHlpBlk(jmpLT, SCK_OVERFLOW);
}
ins = INS_mov;
}
else // Non-overflow checking cast.
{
if (genTypeSize(srcType) == genTypeSize(dstType))
{
ins = INS_mov;
}
else
{
var_types extendType = TYP_UNKNOWN;
if (genTypeSize(srcType) < genTypeSize(dstType))
{
// If we need to treat a signed type as unsigned
if ((treeNode->gtFlags & GTF_UNSIGNED) != 0)
{
extendType = genUnsignedType(srcType);
}
else
extendType = srcType;
#ifdef _TARGET_ARM_
movSize = emitTypeSize(extendType);
#endif // _TARGET_ARM_
if (extendType == TYP_UINT)
{
#ifdef _TARGET_ARM64_
// If we are casting from a smaller type to
// a larger type, then we need to make sure the
// higher 4 bytes are zero to gaurentee the correct value.
// Therefore using a mov with EA_4BYTE in place of EA_8BYTE
// will zero the upper bits
movSize = EA_4BYTE;
#endif // _TARGET_ARM64_
movRequired = true;
}
}
else // (genTypeSize(srcType) > genTypeSize(dstType))
{
// If we need to treat a signed type as unsigned
if ((treeNode->gtFlags & GTF_UNSIGNED) != 0)
{
extendType = genUnsignedType(dstType);
}
else
extendType = dstType;
#if defined(_TARGET_ARM_)
movSize = emitTypeSize(extendType);
#elif defined(_TARGET_ARM64_)
if (extendType == TYP_INT)
{
movSize = EA_8BYTE; // a sxtw instruction requires EA_8BYTE
}
#endif // _TARGET_*
}
ins = ins_Move_Extend(extendType, true);
}
}
// We should never be generating a load from memory instruction here!
assert(!emit->emitInsIsLoad(ins));
if ((ins != INS_mov) || movRequired || (targetReg != sourceReg))
{
emit->emitIns_R_R(ins, movSize, targetReg, sourceReg);
}
genProduceReg(treeNode);
}
//------------------------------------------------------------------------
// genFloatToFloatCast: Generate code for a cast between float and double
//
// Arguments:
// treeNode - The GT_CAST node
//
// Return Value:
// None.
//
// Assumptions:
// Cast is a non-overflow conversion.
// The treeNode must have an assigned register.
// The cast is between float and double.
//
void CodeGen::genFloatToFloatCast(GenTreePtr treeNode)
{
// float <--> double conversions are always non-overflow ones
assert(treeNode->OperGet() == GT_CAST);
assert(!treeNode->gtOverflow());
regNumber targetReg = treeNode->gtRegNum;
assert(genIsValidFloatReg(targetReg));
GenTreePtr op1 = treeNode->gtOp.gtOp1;
assert(!op1->isContained()); // Cannot be contained
assert(genIsValidFloatReg(op1->gtRegNum)); // Must be a valid float reg.
var_types dstType = treeNode->CastToType();
var_types srcType = op1->TypeGet();
assert(varTypeIsFloating(srcType) && varTypeIsFloating(dstType));
genConsumeOperands(treeNode->AsOp());
// treeNode must be a reg
assert(!treeNode->isContained());
#if defined(_TARGET_ARM_)
if (srcType != dstType)
{
instruction insVcvt = (srcType == TYP_FLOAT) ? INS_vcvt_f2d // convert Float to Double
: INS_vcvt_d2f; // convert Double to Float
getEmitter()->emitIns_R_R(insVcvt, emitTypeSize(treeNode), treeNode->gtRegNum, op1->gtRegNum);
}
else if (treeNode->gtRegNum != op1->gtRegNum)
{
getEmitter()->emitIns_R_R(INS_vmov, emitTypeSize(treeNode), treeNode->gtRegNum, op1->gtRegNum);
}
#elif defined(_TARGET_ARM64_)
if (srcType != dstType)
{
insOpts cvtOption = (srcType == TYP_FLOAT) ? INS_OPTS_S_TO_D // convert Single to Double
: INS_OPTS_D_TO_S; // convert Double to Single
getEmitter()->emitIns_R_R(INS_fcvt, emitActualTypeSize(treeNode), treeNode->gtRegNum, op1->gtRegNum, cvtOption);
}
else if (treeNode->gtRegNum != op1->gtRegNum)
{
// If double to double cast or float to float cast. Emit a move instruction.
getEmitter()->emitIns_R_R(INS_mov, emitActualTypeSize(treeNode), treeNode->gtRegNum, op1->gtRegNum);
}
#endif // _TARGET_*
genProduceReg(treeNode);
}
//------------------------------------------------------------------------
// genCreateAndStoreGCInfo: Create and record GC Info for the function.
//
void CodeGen::genCreateAndStoreGCInfo(unsigned codeSize,
unsigned prologSize,
unsigned epilogSize DEBUGARG(void* codePtr))
{
IAllocator* allowZeroAlloc = new (compiler, CMK_GC) AllowZeroAllocator(compiler->getAllocatorGC());
GcInfoEncoder* gcInfoEncoder = new (compiler, CMK_GC)
GcInfoEncoder(compiler->info.compCompHnd, compiler->info.compMethodInfo, allowZeroAlloc, NOMEM);
assert(gcInfoEncoder != nullptr);
// Follow the code pattern of the x86 gc info encoder (genCreateAndStoreGCInfoJIT32).
gcInfo.gcInfoBlockHdrSave(gcInfoEncoder, codeSize, prologSize);
// We keep the call count for the second call to gcMakeRegPtrTable() below.
unsigned callCnt = 0;
// First we figure out the encoder ID's for the stack slots and registers.
gcInfo.gcMakeRegPtrTable(gcInfoEncoder, codeSize, prologSize, GCInfo::MAKE_REG_PTR_MODE_ASSIGN_SLOTS, &callCnt);
// Now we've requested all the slots we'll need; "finalize" these (make more compact data structures for them).
gcInfoEncoder->FinalizeSlotIds();
// Now we can actually use those slot ID's to declare live ranges.
gcInfo.gcMakeRegPtrTable(gcInfoEncoder, codeSize, prologSize, GCInfo::MAKE_REG_PTR_MODE_DO_WORK, &callCnt);
#ifdef _TARGET_ARM64_
if (compiler->opts.compDbgEnC)
{
// what we have to preserve is called the "frame header" (see comments in VM\eetwain.cpp)
// which is:
// -return address
// -saved off RBP
// -saved 'this' pointer and bool for synchronized methods
// 4 slots for RBP + return address + RSI + RDI
int preservedAreaSize = 4 * REGSIZE_BYTES;
if (compiler->info.compFlags & CORINFO_FLG_SYNCH)
{
if (!(compiler->info.compFlags & CORINFO_FLG_STATIC))
preservedAreaSize += REGSIZE_BYTES;
preservedAreaSize += 1; // bool for synchronized methods
}
// Used to signal both that the method is compiled for EnC, and also the size of the block at the top of the
// frame
gcInfoEncoder->SetSizeOfEditAndContinuePreservedArea(preservedAreaSize);
}
#endif // _TARGET_ARM64_
gcInfoEncoder->Build();
// GC Encoder automatically puts the GC info in the right spot using ICorJitInfo::allocGCInfo(size_t)
// let's save the values anyway for debugging purposes
compiler->compInfoBlkAddr = gcInfoEncoder->Emit();
compiler->compInfoBlkSize = 0; // not exposed by the GCEncoder interface
}
//-------------------------------------------------------------------------------------------
// genJumpKindsForTree: Determine the number and kinds of conditional branches
// necessary to implement the given GT_CMP node
//
// Arguments:
// cmpTree - (input) The GenTree node that is used to set the Condition codes
// - The GenTree Relop node that was used to set the Condition codes
// jmpKind[2] - (output) One or two conditional branch instructions
// jmpToTrueLabel[2] - (output) On Arm64 both branches will always branch to the true label
//
// Return Value:
// Sets the proper values into the array elements of jmpKind[] and jmpToTrueLabel[]
//
// Assumptions:
// At least one conditional branch instruction will be returned.
// Typically only one conditional branch is needed
// and the second jmpKind[] value is set to EJ_NONE
//
void CodeGen::genJumpKindsForTree(GenTreePtr cmpTree, emitJumpKind jmpKind[2], bool jmpToTrueLabel[2])
{
// On ARM both branches will always branch to the true label
jmpToTrueLabel[0] = true;
jmpToTrueLabel[1] = true;
// For integer comparisons just use genJumpKindForOper
if (!varTypeIsFloating(cmpTree->gtOp.gtOp1))
{
CompareKind compareKind = ((cmpTree->gtFlags & GTF_UNSIGNED) != 0) ? CK_UNSIGNED : CK_SIGNED;
jmpKind[0] = genJumpKindForOper(cmpTree->gtOper, compareKind);
jmpKind[1] = EJ_NONE;
}
else // We have a Floating Point Compare operation
{
assert(cmpTree->OperIsCompare());
// For details on this mapping, see the ARM Condition Code table
// at section A8.3 in the ARMv7 architecture manual or
// at section C1.2.3 in the ARMV8 architecture manual.
// We must check the GTF_RELOP_NAN_UN to find out
// if we need to branch when we have a NaN operand.
//
if ((cmpTree->gtFlags & GTF_RELOP_NAN_UN) != 0)
{
// Must branch if we have an NaN, unordered
switch (cmpTree->gtOper)
{
case GT_EQ:
jmpKind[0] = EJ_eq; // branch or set when equal (and no NaN's)
jmpKind[1] = EJ_vs; // branch or set when we have a NaN
break;
case GT_NE:
jmpKind[0] = EJ_ne; // branch or set when not equal (or have NaN's)
jmpKind[1] = EJ_NONE;
break;
case GT_LT:
jmpKind[0] = EJ_lt; // branch or set when less than (or have NaN's)
jmpKind[1] = EJ_NONE;
break;
case GT_LE:
jmpKind[0] = EJ_le; // branch or set when less than or equal (or have NaN's)
jmpKind[1] = EJ_NONE;
break;
case GT_GT:
jmpKind[0] = EJ_hi; // branch or set when greater than (or have NaN's)
jmpKind[1] = EJ_NONE;
break;
case GT_GE:
jmpKind[0] = EJ_hs; // branch or set when greater than or equal (or have NaN's)
jmpKind[1] = EJ_NONE;
break;
default:
unreached();
}
}
else // ((cmpTree->gtFlags & GTF_RELOP_NAN_UN) == 0)
{
// Do not branch if we have an NaN, unordered
switch (cmpTree->gtOper)
{
case GT_EQ:
jmpKind[0] = EJ_eq; // branch or set when equal (and no NaN's)
jmpKind[1] = EJ_NONE;
break;
case GT_NE:
jmpKind[0] = EJ_gt; // branch or set when greater than (and no NaN's)
jmpKind[1] = EJ_lo; // branch or set when less than (and no NaN's)
break;
case GT_LT:
jmpKind[0] = EJ_lo; // branch or set when less than (and no NaN's)
jmpKind[1] = EJ_NONE;
break;
case GT_LE:
jmpKind[0] = EJ_ls; // branch or set when less than or equal (and no NaN's)
jmpKind[1] = EJ_NONE;
break;
case GT_GT:
jmpKind[0] = EJ_gt; // branch or set when greater than (and no NaN's)
jmpKind[1] = EJ_NONE;
break;
case GT_GE:
jmpKind[0] = EJ_ge; // branch or set when greater than or equal (and no NaN's)
jmpKind[1] = EJ_NONE;
break;
default:
unreached();
}
}
}
}
//------------------------------------------------------------------------
// genCodeForJumpTrue: Generates code for jmpTrue statement.
//
// Arguments:
// tree - The GT_JTRUE tree node.
//
// Return Value:
// None
//
void CodeGen::genCodeForJumpTrue(GenTreePtr tree)
{
GenTree* cmp = tree->gtOp.gtOp1;
assert(cmp->OperIsCompare());
assert(compiler->compCurBB->bbJumpKind == BBJ_COND);
// Get the "kind" and type of the comparison. Note that whether it is an unsigned cmp
// is governed by a flag NOT by the inherent type of the node
emitJumpKind jumpKind[2];
bool branchToTrueLabel[2];
genJumpKindsForTree(cmp, jumpKind, branchToTrueLabel);
assert(jumpKind[0] != EJ_NONE);
// On ARM the branches will always branch to the true label
assert(branchToTrueLabel[0]);
inst_JMP(jumpKind[0], compiler->compCurBB->bbJumpDest);
if (jumpKind[1] != EJ_NONE)
{
// the second conditional branch always has to be to the true label
assert(branchToTrueLabel[1]);
inst_JMP(jumpKind[1], compiler->compCurBB->bbJumpDest);
}
}
//------------------------------------------------------------------------
// genCodeForJcc: Produce code for a GT_JCC node.
//
// Arguments:
// tree - the node
//
void CodeGen::genCodeForJcc(GenTreeCC* tree)
{
assert(compiler->compCurBB->bbJumpKind == BBJ_COND);
CompareKind compareKind = ((tree->gtFlags & GTF_UNSIGNED) != 0) ? CK_UNSIGNED : CK_SIGNED;
emitJumpKind jumpKind = genJumpKindForOper(tree->gtCondition, compareKind);
inst_JMP(jumpKind, compiler->compCurBB->bbJumpDest);
}
//------------------------------------------------------------------------
// genCodeForSetcc: Generates code for a GT_SETCC node.
//
// Arguments:
// setcc - the GT_SETCC node
//
// Assumptions:
// The condition represents an integer comparison. This code doesn't
// have the necessary logic to deal with floating point comparisons,
// in fact it doesn't even know if the comparison is integer or floating
// point because SETCC nodes do not have any operands.
//
void CodeGen::genCodeForSetcc(GenTreeCC* setcc)
{
regNumber dstReg = setcc->gtRegNum;
CompareKind compareKind = setcc->IsUnsigned() ? CK_UNSIGNED : CK_SIGNED;
emitJumpKind jumpKind = genJumpKindForOper(setcc->gtCondition, compareKind);
assert(genIsValidIntReg(dstReg));
// Make sure nobody is setting GTF_RELOP_NAN_UN on this node as it is ignored.
assert((setcc->gtFlags & GTF_RELOP_NAN_UN) == 0);
#ifdef _TARGET_ARM64_
inst_SET(jumpKind, dstReg);
#else
// Emit code like that:
// ...
// bgt True
// movs rD, #0
// b Next
// True:
// movs rD, #1
// Next:
// ...
BasicBlock* labelTrue = genCreateTempLabel();
getEmitter()->emitIns_J(emitter::emitJumpKindToIns(jumpKind), labelTrue);
getEmitter()->emitIns_R_I(INS_mov, emitActualTypeSize(setcc->TypeGet()), dstReg, 0);
BasicBlock* labelNext = genCreateTempLabel();
getEmitter()->emitIns_J(INS_b, labelNext);
genDefineTempLabel(labelTrue);
getEmitter()->emitIns_R_I(INS_mov, emitActualTypeSize(setcc->TypeGet()), dstReg, 1);
genDefineTempLabel(labelNext);
#endif
genProduceReg(setcc);
}
//------------------------------------------------------------------------
// genCodeForStoreBlk: Produce code for a GT_STORE_OBJ/GT_STORE_DYN_BLK/GT_STORE_BLK node.
//
// Arguments:
// tree - the node
//
void CodeGen::genCodeForStoreBlk(GenTreeBlk* blkOp)
{
assert(blkOp->OperIs(GT_STORE_OBJ, GT_STORE_DYN_BLK, GT_STORE_BLK));
if (blkOp->OperIs(GT_STORE_OBJ) && blkOp->OperIsCopyBlkOp())
{
assert(blkOp->AsObj()->gtGcPtrCount != 0);
genCodeForCpObj(blkOp->AsObj());
return;
}
if (blkOp->gtBlkOpGcUnsafe)
{
getEmitter()->emitDisableGC();
}
bool isCopyBlk = blkOp->OperIsCopyBlkOp();
switch (blkOp->gtBlkOpKind)
{
case GenTreeBlk::BlkOpKindHelper:
if (isCopyBlk)
{
genCodeForCpBlk(blkOp);
}
else
{
genCodeForInitBlk(blkOp);
}
break;
case GenTreeBlk::BlkOpKindUnroll:
if (isCopyBlk)
{
genCodeForCpBlkUnroll(blkOp);
}
else
{
genCodeForInitBlkUnroll(blkOp);
}
break;
default:
unreached();
}
if (blkOp->gtBlkOpGcUnsafe)
{
getEmitter()->emitEnableGC();
}
}
//------------------------------------------------------------------------
// genScaledAdd: A helper for genLeaInstruction.
//
void CodeGen::genScaledAdd(emitAttr attr, regNumber targetReg, regNumber baseReg, regNumber indexReg, int scale)
{
emitter* emit = getEmitter();
#if defined(_TARGET_ARM_)
emit->emitIns_R_R_R_I(INS_add, attr, targetReg, baseReg, indexReg, scale, INS_FLAGS_DONT_CARE, INS_OPTS_LSL);
#elif defined(_TARGET_ARM64_)
emit->emitIns_R_R_R_I(INS_add, attr, targetReg, baseReg, indexReg, scale, INS_OPTS_LSL);
#endif
}
//------------------------------------------------------------------------
// genLeaInstruction: Produce code for a GT_LEA node.
//
// Arguments:
// lea - the node
//
void CodeGen::genLeaInstruction(GenTreeAddrMode* lea)
{
genConsumeOperands(lea);
emitter* emit = getEmitter();
emitAttr size = emitTypeSize(lea);
int offset = lea->Offset();
// In ARM we can only load addresses of the form:
//
// [Base + index*scale]
// [Base + Offset]
// [Literal] (PC-Relative)
//
// So for the case of a LEA node of the form [Base + Index*Scale + Offset] we will generate:
// destReg = baseReg + indexReg * scale;
// destReg = destReg + offset;
//
// TODO-ARM64-CQ: The purpose of the GT_LEA node is to directly reflect a single target architecture
// addressing mode instruction. Currently we're 'cheating' by producing one or more
// instructions to generate the addressing mode so we need to modify lowering to
// produce LEAs that are a 1:1 relationship to the ARM64 architecture.
if (lea->Base() && lea->Index())
{
GenTree* memBase = lea->Base();
GenTree* index = lea->Index();
DWORD lsl;
assert(isPow2(lea->gtScale));
BitScanForward(&lsl, lea->gtScale);
assert(lsl <= 4);
if (offset != 0)
{
regNumber tmpReg = lea->GetSingleTempReg();
if (emitter::emitIns_valid_imm_for_add(offset))
{
if (lsl > 0)
{
// Generate code to set tmpReg = base + index*scale
genScaledAdd(size, tmpReg, memBase->gtRegNum, index->gtRegNum, lsl);
}
else // no scale
{
// Generate code to set tmpReg = base + index
emit->emitIns_R_R_R(INS_add, size, tmpReg, memBase->gtRegNum, index->gtRegNum);
}
// Then compute target reg from [tmpReg + offset]
emit->emitIns_R_R_I(INS_add, size, lea->gtRegNum, tmpReg, offset);
}
else // large offset
{
// First load/store tmpReg with the large offset constant
instGen_Set_Reg_To_Imm(EA_PTRSIZE, tmpReg, offset);
// Then add the base register
// rd = rd + base
emit->emitIns_R_R_R(INS_add, size, tmpReg, tmpReg, memBase->gtRegNum);
noway_assert(tmpReg != index->gtRegNum);
// Then compute target reg from [tmpReg + index*scale]
genScaledAdd(size, lea->gtRegNum, tmpReg, index->gtRegNum, lsl);
}
}
else
{
if (lsl > 0)
{
// Then compute target reg from [base + index*scale]
genScaledAdd(size, lea->gtRegNum, memBase->gtRegNum, index->gtRegNum, lsl);
}
else
{
// Then compute target reg from [base + index]
emit->emitIns_R_R_R(INS_add, size, lea->gtRegNum, memBase->gtRegNum, index->gtRegNum);
}
}
}
else if (lea->Base())
{
GenTree* memBase = lea->Base();
if (emitter::emitIns_valid_imm_for_add(offset))
{
if (offset != 0)
{
// Then compute target reg from [memBase + offset]
emit->emitIns_R_R_I(INS_add, size, lea->gtRegNum, memBase->gtRegNum, offset);
}
else // offset is zero
{
if (lea->gtRegNum != memBase->gtRegNum)
{
emit->emitIns_R_R(INS_mov, size, lea->gtRegNum, memBase->gtRegNum);
}
}
}
else
{
// We require a tmpReg to hold the offset
regNumber tmpReg = lea->GetSingleTempReg();
// First load tmpReg with the large offset constant
instGen_Set_Reg_To_Imm(EA_PTRSIZE, tmpReg, offset);
// Then compute target reg from [memBase + tmpReg]
emit->emitIns_R_R_R(INS_add, size, lea->gtRegNum, memBase->gtRegNum, tmpReg);
}
}
else if (lea->Index())
{
// If we encounter a GT_LEA node without a base it means it came out
// when attempting to optimize an arbitrary arithmetic expression during lower.
// This is currently disabled in ARM64 since we need to adjust lower to account
// for the simpler instructions ARM64 supports.
// TODO-ARM64-CQ: Fix this and let LEA optimize arithmetic trees too.
assert(!"We shouldn't see a baseless address computation during CodeGen for ARM64");
}
genProduceReg(lea);
}
//------------------------------------------------------------------------
// isStructReturn: Returns whether the 'treeNode' is returning a struct.
//
// Arguments:
// treeNode - The tree node to evaluate whether is a struct return.
//
// Return Value:
// Returns true if the 'treeNode" is a GT_RETURN node of type struct.
// Otherwise returns false.
//
bool CodeGen::isStructReturn(GenTreePtr treeNode)
{
// This method could be called for 'treeNode' of GT_RET_FILT or GT_RETURN.
// For the GT_RET_FILT, the return is always
// a bool or a void, for the end of a finally block.
noway_assert(treeNode->OperGet() == GT_RETURN || treeNode->OperGet() == GT_RETFILT);
return varTypeIsStruct(treeNode);
}
//------------------------------------------------------------------------
// genStructReturn: Generates code for returning a struct.
//
// Arguments:
// treeNode - The GT_RETURN tree node.
//
// Return Value:
// None
//
// Assumption:
// op1 of GT_RETURN node is either GT_LCL_VAR or multi-reg GT_CALL
void CodeGen::genStructReturn(GenTreePtr treeNode)
{
assert(treeNode->OperGet() == GT_RETURN);
assert(isStructReturn(treeNode));
GenTreePtr op1 = treeNode->gtGetOp1();
if (op1->OperGet() == GT_LCL_VAR)
{
GenTreeLclVarCommon* lclVar = op1->AsLclVarCommon();
LclVarDsc* varDsc = &(compiler->lvaTable[lclVar->gtLclNum]);
var_types lclType = genActualType(varDsc->TypeGet());
// Currently only multireg TYP_STRUCT types such as HFA's(ARM32, ARM64) and 16-byte structs(ARM64) are supported
// In the future we could have FEATURE_SIMD types like TYP_SIMD16
assert(lclType == TYP_STRUCT);
assert(varDsc->lvIsMultiRegRet);
ReturnTypeDesc retTypeDesc;
unsigned regCount;
retTypeDesc.InitializeStructReturnType(compiler, varDsc->lvVerTypeInfo.GetClassHandle());
regCount = retTypeDesc.GetReturnRegCount();
assert(regCount >= 2);
assert(op1->isContained());
// Copy var on stack into ABI return registers
// TODO: It could be optimized by reducing two float loading to one double
int offset = 0;
for (unsigned i = 0; i < regCount; ++i)
{
var_types type = retTypeDesc.GetReturnRegType(i);
regNumber reg = retTypeDesc.GetABIReturnReg(i);
getEmitter()->emitIns_R_S(ins_Load(type), emitTypeSize(type), reg, lclVar->gtLclNum, offset);
offset += genTypeSize(type);
}
}
else // op1 must be multi-reg GT_CALL
{
assert(op1->IsMultiRegCall() || op1->IsCopyOrReloadOfMultiRegCall());
genConsumeRegs(op1);
GenTree* actualOp1 = op1->gtSkipReloadOrCopy();
GenTreeCall* call = actualOp1->AsCall();
ReturnTypeDesc* pRetTypeDesc;
unsigned regCount;
unsigned matchingCount = 0;
pRetTypeDesc = call->GetReturnTypeDesc();
regCount = pRetTypeDesc->GetReturnRegCount();
var_types regType[MAX_RET_REG_COUNT];
regNumber returnReg[MAX_RET_REG_COUNT];
regNumber allocatedReg[MAX_RET_REG_COUNT];
regMaskTP srcRegsMask = 0;
regMaskTP dstRegsMask = 0;
bool needToShuffleRegs = false; // Set to true if we have to move any registers
for (unsigned i = 0; i < regCount; ++i)
{
regType[i] = pRetTypeDesc->GetReturnRegType(i);
returnReg[i] = pRetTypeDesc->GetABIReturnReg(i);
regNumber reloadReg = REG_NA;
if (op1->IsCopyOrReload())
{
// GT_COPY/GT_RELOAD will have valid reg for those positions
// that need to be copied or reloaded.
reloadReg = op1->AsCopyOrReload()->GetRegNumByIdx(i);
}
if (reloadReg != REG_NA)
{
allocatedReg[i] = reloadReg;
}
else
{
allocatedReg[i] = call->GetRegNumByIdx(i);
}
if (returnReg[i] == allocatedReg[i])
{
matchingCount++;
}
else // We need to move this value
{
// We want to move the value from allocatedReg[i] into returnReg[i]
// so record these two registers in the src and dst masks
//
srcRegsMask |= genRegMask(allocatedReg[i]);
dstRegsMask |= genRegMask(returnReg[i]);
needToShuffleRegs = true;
}
}
if (needToShuffleRegs)
{
assert(matchingCount < regCount);
unsigned remainingRegCount = regCount - matchingCount;
regMaskTP extraRegMask = treeNode->gtRsvdRegs;
while (remainingRegCount > 0)
{
// set 'available' to the 'dst' registers that are not currently holding 'src' registers
//
regMaskTP availableMask = dstRegsMask & ~srcRegsMask;
regMaskTP dstMask;
regNumber srcReg;
regNumber dstReg;
var_types curType = TYP_UNKNOWN;
regNumber freeUpReg = REG_NA;
if (availableMask == 0)
{
// Circular register dependencies
// So just free up the lowest register in dstRegsMask by moving it to the 'extra' register
assert(dstRegsMask == srcRegsMask); // this has to be true for us to reach here
assert(extraRegMask != 0); // we require an 'extra' register
assert((extraRegMask & ~dstRegsMask) != 0); // it can't be part of dstRegsMask
availableMask = extraRegMask & ~dstRegsMask;
regMaskTP srcMask = genFindLowestBit(srcRegsMask);
freeUpReg = genRegNumFromMask(srcMask);
}
dstMask = genFindLowestBit(availableMask);
dstReg = genRegNumFromMask(dstMask);
srcReg = REG_NA;
if (freeUpReg != REG_NA)
{
// We will free up the srcReg by moving it to dstReg which is an extra register
//
srcReg = freeUpReg;
// Find the 'srcReg' and set 'curType', change allocatedReg[] to dstReg
// and add the new register mask bit to srcRegsMask
//
for (unsigned i = 0; i < regCount; ++i)
{
if (allocatedReg[i] == srcReg)
{
curType = regType[i];
allocatedReg[i] = dstReg;
srcRegsMask |= genRegMask(dstReg);
}
}
}
else // The normal case
{
// Find the 'srcReg' and set 'curType'
//
for (unsigned i = 0; i < regCount; ++i)
{
if (returnReg[i] == dstReg)
{
srcReg = allocatedReg[i];
curType = regType[i];
}
}
// After we perform this move we will have one less registers to setup
remainingRegCount--;
}
assert(curType != TYP_UNKNOWN);
inst_RV_RV(ins_Copy(curType), dstReg, srcReg, curType);
// Clear the appropriate bits in srcRegsMask and dstRegsMask
srcRegsMask &= ~genRegMask(srcReg);
dstRegsMask &= ~genRegMask(dstReg);
} // while (remainingRegCount > 0)
} // (needToShuffleRegs)
} // op1 must be multi-reg GT_CALL
}
#endif // _TARGET_ARMARCH_
#endif // !LEGACY_BACKEND
| wateret/coreclr | src/jit/codegenarmarch.cpp | C++ | mit | 135,282 |
<nav class="sr-only">
<div class="modal-header">
<div class="row">
<h1 class="h1 col-xs-10 col-sm-10 col-md-11 col-lg-11"><a href="/">WSJ Sections</a></h1>
<a href="" class=" col-xs-1 col-sm-1 col-md-1 col-lg-1" ng-click="NC.cancel()">close </a>
</div>
<div class="row">
<ul class="nav nav-pills nav-sections" >
<!-- <li ng-repeat="category in categories " ><a ng-click="NC.getNavSubCategories(category.slug)" href=""> {{NC.category.name}}</a></li>-->
</ul>
</div>
<div class="row">
<hr style="border-top: 1px solid #444;" />
<!-- <h2 class="text-center modal-title col-md-11">{{ subCategories.section }}</h2>-->
</div>
</div>
<div class="modal-body nav-section-stories">
<!-- <div ng-repeat="subCategory in subCategories" class="row sub-section" >-->
<!-- <article class="col-xs-3 col-sm-2 col-md-2" >-->
<!-- <a href="category/{{NC.subCategory.slug}}" class="story">-->
<!-- <h3> {{subCategory.name}}</h3>-->
<!-- </a>-->
<!-- </article>-->
<!-- <div class="col-xs-9 col-sm-10 col-md-10">-->
<!-- <section class="row">-->
<!-- <article ng-repeat="post in subCategory.posts" class="col-xs-12 col-sm-6 col-md-4" >-->
<!---->
<!-- <!-- <img ng-if="getSource(NC.post.galleries)" class="img-responsive" src="{{NC.getSource(post.galleries)}}" alt="Powell Street"/>-->-->
<!---->
<!-- <a href="/{{post.slug}}" class="story">-->
<!-- <!-- <h2>{{post.name | limitTo:letterLimitHeadline }}</h2>-->-->
<!-- <p>-->
<!-- <!-- {{post.content | limitTo:letterLimit }}-->-->
<!-- </p>-->
<!-- </a>-->
<!-- </article>-->
<!-- </section>-->
<!-- </div>-->
<!---->
<!-- </div> <!-- End/ .row -->-->
</div>
<div class="modal-footer">
<article style="background-color: #a6e1ec; height: 5rem;" class="col-md-4">
Advertisement
</article>
Copyright WSJ
</div>
</nav>
| daniel-rodas/wsj | fuel/app/views/angular/navigation.php | PHP | mit | 2,375 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace AnalyzeThis
{
internal static class RegexExtensions
{
public static bool TryGetMatch(this Regex regex, string input, out Match match)
{
if (input == null)
{
match = null;
return false;
}
match = regex.Match(input);
return match.Success;
}
}
}
| tastott/AnalyzeThis | src/AnalyzeThis/RegexExtensions.cs | C# | mit | 541 |
M.profile("generators");
function* forOfBlockScope() {
let a = [1, 2, 3, 4, 5, 6, 7, 8];
let b = [10, 11, 12, 13, 14, 15, 16];
const funs = [];
for (const i of a) {
let j = 0;
funs.push(function* iter() {
yield `fo1: ${i} ${j++}`;
});
}
for (var i of a) {
var j = 0;
funs.push(function* iter() {
yield `fo2: ${i} ${j++}`;
});
}
for (const i of a) {
for (let j of b) {
funs.push(function* iter() {
yield `fo3: ${i} ${j++}`;
});
}
}
for (const i of a) {
for (let j of b) {
yield `fo4: ${j}`;
funs.push(function* iter() {
yield `fo5: ${i} ${j++}`;
});
}
}
for (const i of a) {
yield `fo6: ${i}`;
for (let j of b) {
funs.push(function* iter() {
yield `fo7: ${i} ${j++}`;
});
}
}
for (const i of a) {
yield `fo8 ${i}`;
for (let j of b) {
yield `fo9: ${i}`;
funs.push(function* iter() {
yield `fo10: ${i} ${j++}`;
});
}
}
for (const i of funs) yield* i();
funs.length = 0;
for (const i of a) {
funs.push(function* iter() {
yield `fo11: ${i}`;
});
}
for (const i of a) {
yield `fo12 ${i}`;
funs.push(function* iter() {
yield `fo13 ${i}`;
});
}
let k = 0;
for (const i of a) {
yield `fo14 ${i} ${k} {m}`;
let m = k;
k++;
if (k === 3) continue;
if (k === 5) break;
funs.push(function* iter() {
yield `fo15 ${i} ${k} {m}`;
});
}
k = 0;
up1: for (const i of a) {
let m = k;
k++;
for (const j of b) {
let n = m;
m++;
if (k === 3) continue up1;
if (k === 5) break up1;
if (n === 3) continue;
if (n === 5) break;
funs.push(function* iter() {
n++;
yield `fo18: ${i} ${j} ${k} ${m} ${n}`;
});
}
}
k = 0;
up2: for (const i of a) {
let m = 0;
k++;
yield `fo16: ${i} ${k} ${m}`;
for (const j of b) {
let n = m;
m++;
if (k === 3) continue up2;
if (k === 5) break up2;
if (n === 3) continue;
if (n === 5) break;
funs.push(function* iter() {
n++;
yield `fo18: ${i} ${j} ${k} ${m} ${n}`;
});
}
}
k = 0;
up3: for (const i of a) {
let m = 0;
k++;
for (const j of b) {
let n = m;
m++;
yield `fo19 ${i} ${j} ${k} ${m} ${n}`;
if (k === 3) {
continue up3;
}
if (k === 5) break up3;
if (n === 3) continue;
if (n === 5) break;
funs.push(function* iter() {
n++;
yield `fo20: ${i} ${j} ${k} ${m} ${n}`;
});
}
}
bl1: {
let k = 0;
yield `fo21: ${i} ${k}`;
up4: for (const i of a) {
let m = 0;
k++;
yield `fo22: ${i} ${k} ${m}`;
for (const j of b) {
let n = m;
m++;
yield `fo23 ${i} ${j} ${k} ${m} ${n}`;
if (k === 3) continue up4;
if (k === 5) break bl1;
if (n === 3) continue;
if (n === 5) break;
funs.push(function* iter() {
n++;
yield `fo24: ${i} ${j} ${k} ${m} ${n}`;
});
}
}
}
bl2: {
let k = 0;
yield `fo25`;
up5: for (const i of a) {
let m = 0;
k++;
yield `fo26: ${i} ${k} ${m}`;
for (const j of b) {
let n = m;
m++;
yield `fo27 ${i} ${j} ${k} ${m} ${n}`;
if (k === 3) continue up5;
if (k === 5) break bl2;
if (n === 3) continue;
if (n === 5) break;
funs.push(function* iter() {
n++;
yield `fo28: ${i} ${j} ${k} ${m} ${n}`;
});
}
}
}
bl3: {
let k = 0;
up6: for (const i of a) {
let m = 0;
k++;
yield `fo29: ${i} ${k} ${m}`;
for (const j of b) {
let n = m;
m++;
yield `fo30 ${i} ${j} ${k} ${m} ${n}`;
if (k === 3) continue up6;
if (k === 5) {
for (const i of funs) yield* i();
return `r: ${i} ${j} ${k} ${m} ${n}`;
}
if (n === 3) continue;
if (n === 5) break;
funs.push(function* iter() {
n++;
yield `fo31: ${i} ${j} ${k} ${m} ${n}`;
});
}
}
}
}
| awto/effectfuljs | packages/core/test/samples/for-of-stmt/closures-in.js | JavaScript | mit | 4,231 |
<?php
/*
* This file is a part of the NeimheadhBootstrapBundle project.
*
* (c) 2017 by Neimheadh
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Neimheadh\Bundle\CodeManipulationBundle\Model\File;
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
use Symfony\Component\Filesystem\Exception\IOException;
/**
* The files models interface.
*
* @author Neimheadh <contact@neimheadh.fr>
*/
interface FileInterface
{
/**
* Get path.
*
* @return string
*/
public function getPath();
/**
* Set path.
*
* @param string $path
* The file path.
* @return \Neimheadh\Bundle\CodeManipulationBundle\Model\File\FileInterface
*/
public function setPath(string $path);
/**
* Get access mode.
*
* @return string
*/
public function getAccessMode();
/**
* Set access mode.
*
* @param string $accessMode
* The access mode.
* @return \Neimheadh\Bundle\CodeManipulationBundle\Model\File\FileInterface
*/
public function setAccessMode(string $accessMode);
/**
* Check file access.
*
* @param bool $read
* Force read checking.
* @param bool $write
* Force write checking.
* @throws FileNotFoundException The file doesn't exist.
* @throws IOException The file cannot be accessed in read mode (code = 1).
* @throws IOException The file cannot be accessed in read mode (code = 2).
* @throws IOException Unknown access mode (code = 3).
*/
public function check(bool $read = false, bool $write = false);
/**
* Is the file existing?
*
* @return bool
*/
public function isExisting();
/**
* Is the file readable?
*
* @return bool
*/
public function isReadable();
/**
* Is the file writable?
*
* @return bool
*/
public function isWritable();
/**
* Process file line by line.
*
* @param callable $callback
* The callback.
*
*/
public function processLines($callback);
/**
* Append content in file.
*
* @param string $content
* Amended content.
* @param int|null $position
* Amend position
*/
public function amend(string $content, int $position = null);
} | neimheadh/code-manipulation-bundle | Model/File/FileInterface.php | PHP | mit | 2,489 |
package fPPPrograms;
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
System.out.println("Enter a year to determine whether it is a leap year or not?");
Scanner yourInput = new Scanner(System.in);
int year = yourInput.nextInt();
//String y = year%400 == 0? (year%4 == 0 ) && (year%100 !=0) ? "Yes" : "Not" : "Not" ;
String y = ((year%4 == 0) && (year%100 != 0) || (year%400 == 0)) ? "Yes" : "Not";
System.out.println("The Year You Entered is " + y + " a Leap Year");
}
}
| haftommit/FPP.github.io | FPPSecondProject/src/week1lesson2/Q2.java | Java | mit | 545 |
<?php
namespace BigD\UbicacionBundle\Form\EventListener;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\PropertyAccess\PropertyAccess;
class AddCityFieldSubscriber implements EventSubscriberInterface {
private $factory;
public function __construct(FormFactoryInterface $factory) {
$this->factory = $factory;
}
public static function getSubscribedEvents() {
return array(
FormEvents::PRE_SET_DATA => 'preSetData',
FormEvents::PRE_BIND => 'preBind'
);
}
private function addLocalidadForm($form, $city, $country) {
$form->add($this->factory->createNamed('city', 'entity', $city, array(
'class' => 'LocationBundle:City',
'auto_initialize' => false,
'empty_value' => 'Select',
'attr' => array(
'class' => 'city_selector',
),
'query_builder' => function (EntityRepository $repository) use ($country) {
$qb = $repository->createQueryBuilder('city')
->innerJoin('city.country', 'country');
if ($country instanceof Country) {
$qb->where('city.country = :country')
->setParameter('country', $country->getId());
} elseif (is_numeric($country)) {
$qb->where('country.id = :country')
->setParameter('country', $country);
} else {
$qb->where('country.name = :country')
->setParameter('country', null);
}
return $qb;
}
)));
}
public function preSetData(FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
if (null === $data) {
$this->addCityForm($form, null, null);
return;
}
$accessor = PropertyAccess::getPropertyAccessor();
$city = $accessor->getValue($data, 'city');
//$province = ($city) ? $city->getProvince() : null ;
//$this->addCityForm($form, $city, $province);
//$country = ($data->getCity()) ? $data->getCity()->getCountry() : null ;
$country = ($city) ? $city->getCountry() : null;
$this->addCityForm($form, $city, $country);
}
public function preBind(FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
if (null === $data) {
return;
}
// $city = array_key_exists('city', $data) ? $data['city'] : null;
// $this->addCityForm($form, $city, $province);
$country = array_key_exists('country', $data) ? $data['country'] : null;
$city = array_key_exists('city', $data) ? $data['city'] : null;
$this->addCityForm($form, $city, $country);
}
}
| matudelatower/BigD | src/BigD/UbicacionBundle/Form/EventListener/AddCityFieldSubscriber.php | PHP | mit | 3,120 |
// This code will add an event listener to each anchor of the topbar after being dynamically replaced by "interchange"
$("body").on("click", function(event){
// If the active element is one of the topbar's links continues
if($(event.target).hasClass("topbarLink")) {
// The parent li element of the current active link is stored
var activeLink = $(event.target).parent();
// Takes each link and checks if its parent li element is active, removing "active" class if so.
$("#topNavContent li:not(.divider)").each(function(){
// If the li element has nested li's with links they are checked also.
if($(this).hasClass("has-dropdown")){
var dropdownList = $(this).children(".dropdown").children().not(".divider");
dropdownList.each(function(){
if($(this).hasClass("active")){
$(this).removeClass("active");
}
});
}
// The direct li element's "active" class is removed
if($(this).hasClass("active")){
$(this).removeClass("active");
}
});
// After having all topbar li elements deactivated, "active" class is added to the currently active link's li parent
if(!$(activeLink).hasClass("active")){
$(activeLink).addClass("active");
}
}
});
// This variable is used to know if this script will be loaded at the time of checking it in the JS manager
activeLinkActivatorLoaded = true; | joseAyudarte91/aterbe_web_project | js/commons/activateCurrentLink.js | JavaScript | mit | 1,381 |
const elixir = require('laravel-elixir');
elixir((mix) => {
// Mix all Sass files into one
mix.sass('app.scss');
// Mix all vendor scripts together
mix.scripts(
[
'jquery/dist/jquery.min.js',
'bootstrap-sass/assets/javascripts/bootstrap.min.js',
'bootstrap-sass/assets/javascripts/bootstrap/dropdown.js'
],
'resources/assets/js/vendor.js',
'node_modules'
);
// Mix all script files into one
mix.scripts(
['vendor.js', 'app.js'],
'public/js/app.js'
);
// Copy vendor assets to public
mix.copy('node_modules/bootstrap-sass/assets/fonts/bootstrap/','public/fonts/bootstrap')
.copy('node_modules/font-awesome/fonts', 'public/fonts');
});
/*
var elixir = require('laravel-elixir');
elixir(function(mix) {
// Mix all scss files into one css file
mix.sass([
'charts.scss',
'app.scss'
], 'public/css/app.css');
// Mix all chart JS files into a master charts file
mix.scriptsIn(
'resources/assets/js/charts',
'public/js/charts.js'
);
// Mix common JS files into one file
mix.scripts([
'app.js'
], 'public/js/app.js');
});
*/
| jamesgifford/perfectlydopey | gulpfile.js | JavaScript | mit | 1,236 |
require 'spec_helper'
describe User do
context 'fields' do
it { should have_field(:email).of_type(String)}
it { should have_field(:encrypted_password).of_type(String)}
it { should have_field(:roles).of_type(Array)}
end
context 'Mass assignment' do
it { should allow_mass_assignment_of(:email) }
it { should allow_mass_assignment_of(:roles) }
it { should allow_mass_assignment_of(:password) }
it { should allow_mass_assignment_of(:password_confirmation) }
end
context 'Required fields' do
it { should validate_presence_of(:roles)}
end
context 'Associations' do
it { should embed_one :profile }
end
end
| techvision/brails | spec/models/user_spec.rb | Ruby | mit | 661 |
import {Map} from 'immutable';
export function getInteractiveLayerIds(mapStyle) {
let interactiveLayerIds = [];
if (Map.isMap(mapStyle) && mapStyle.has('layers')) {
interactiveLayerIds = mapStyle.get('layers')
.filter(l => l.get('interactive'))
.map(l => l.get('id'))
.toJS();
} else if (Array.isArray(mapStyle.layers)) {
interactiveLayerIds = mapStyle.layers.filter(l => l.interactive)
.map(l => l.id);
}
return interactiveLayerIds;
} | RanaRunning/rana | web/src/components/MapGL/utils/style-utils.js | JavaScript | mit | 480 |
package machinelearningservices
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// AllocationState enumerates the values for allocation state.
type AllocationState string
const (
// AllocationStateResizing ...
AllocationStateResizing AllocationState = "Resizing"
// AllocationStateSteady ...
AllocationStateSteady AllocationState = "Steady"
)
// PossibleAllocationStateValues returns an array of possible values for the AllocationState const type.
func PossibleAllocationStateValues() []AllocationState {
return []AllocationState{AllocationStateResizing, AllocationStateSteady}
}
// ApplicationSharingPolicy enumerates the values for application sharing policy.
type ApplicationSharingPolicy string
const (
// ApplicationSharingPolicyPersonal ...
ApplicationSharingPolicyPersonal ApplicationSharingPolicy = "Personal"
// ApplicationSharingPolicyShared ...
ApplicationSharingPolicyShared ApplicationSharingPolicy = "Shared"
)
// PossibleApplicationSharingPolicyValues returns an array of possible values for the ApplicationSharingPolicy const type.
func PossibleApplicationSharingPolicyValues() []ApplicationSharingPolicy {
return []ApplicationSharingPolicy{ApplicationSharingPolicyPersonal, ApplicationSharingPolicyShared}
}
// ClusterPurpose enumerates the values for cluster purpose.
type ClusterPurpose string
const (
// ClusterPurposeDenseProd ...
ClusterPurposeDenseProd ClusterPurpose = "DenseProd"
// ClusterPurposeDevTest ...
ClusterPurposeDevTest ClusterPurpose = "DevTest"
// ClusterPurposeFastProd ...
ClusterPurposeFastProd ClusterPurpose = "FastProd"
)
// PossibleClusterPurposeValues returns an array of possible values for the ClusterPurpose const type.
func PossibleClusterPurposeValues() []ClusterPurpose {
return []ClusterPurpose{ClusterPurposeDenseProd, ClusterPurposeDevTest, ClusterPurposeFastProd}
}
// ComputeInstanceAuthorizationType enumerates the values for compute instance authorization type.
type ComputeInstanceAuthorizationType string
const (
// ComputeInstanceAuthorizationTypePersonal ...
ComputeInstanceAuthorizationTypePersonal ComputeInstanceAuthorizationType = "personal"
)
// PossibleComputeInstanceAuthorizationTypeValues returns an array of possible values for the ComputeInstanceAuthorizationType const type.
func PossibleComputeInstanceAuthorizationTypeValues() []ComputeInstanceAuthorizationType {
return []ComputeInstanceAuthorizationType{ComputeInstanceAuthorizationTypePersonal}
}
// ComputeInstanceState enumerates the values for compute instance state.
type ComputeInstanceState string
const (
// ComputeInstanceStateCreateFailed ...
ComputeInstanceStateCreateFailed ComputeInstanceState = "CreateFailed"
// ComputeInstanceStateCreating ...
ComputeInstanceStateCreating ComputeInstanceState = "Creating"
// ComputeInstanceStateDeleting ...
ComputeInstanceStateDeleting ComputeInstanceState = "Deleting"
// ComputeInstanceStateJobRunning ...
ComputeInstanceStateJobRunning ComputeInstanceState = "JobRunning"
// ComputeInstanceStateRestarting ...
ComputeInstanceStateRestarting ComputeInstanceState = "Restarting"
// ComputeInstanceStateRunning ...
ComputeInstanceStateRunning ComputeInstanceState = "Running"
// ComputeInstanceStateSettingUp ...
ComputeInstanceStateSettingUp ComputeInstanceState = "SettingUp"
// ComputeInstanceStateSetupFailed ...
ComputeInstanceStateSetupFailed ComputeInstanceState = "SetupFailed"
// ComputeInstanceStateStarting ...
ComputeInstanceStateStarting ComputeInstanceState = "Starting"
// ComputeInstanceStateStopped ...
ComputeInstanceStateStopped ComputeInstanceState = "Stopped"
// ComputeInstanceStateStopping ...
ComputeInstanceStateStopping ComputeInstanceState = "Stopping"
// ComputeInstanceStateUnknown ...
ComputeInstanceStateUnknown ComputeInstanceState = "Unknown"
// ComputeInstanceStateUnusable ...
ComputeInstanceStateUnusable ComputeInstanceState = "Unusable"
// ComputeInstanceStateUserSettingUp ...
ComputeInstanceStateUserSettingUp ComputeInstanceState = "UserSettingUp"
// ComputeInstanceStateUserSetupFailed ...
ComputeInstanceStateUserSetupFailed ComputeInstanceState = "UserSetupFailed"
)
// PossibleComputeInstanceStateValues returns an array of possible values for the ComputeInstanceState const type.
func PossibleComputeInstanceStateValues() []ComputeInstanceState {
return []ComputeInstanceState{ComputeInstanceStateCreateFailed, ComputeInstanceStateCreating, ComputeInstanceStateDeleting, ComputeInstanceStateJobRunning, ComputeInstanceStateRestarting, ComputeInstanceStateRunning, ComputeInstanceStateSettingUp, ComputeInstanceStateSetupFailed, ComputeInstanceStateStarting, ComputeInstanceStateStopped, ComputeInstanceStateStopping, ComputeInstanceStateUnknown, ComputeInstanceStateUnusable, ComputeInstanceStateUserSettingUp, ComputeInstanceStateUserSetupFailed}
}
// ComputeType enumerates the values for compute type.
type ComputeType string
const (
// ComputeTypeAKS ...
ComputeTypeAKS ComputeType = "AKS"
// ComputeTypeAmlCompute ...
ComputeTypeAmlCompute ComputeType = "AmlCompute"
// ComputeTypeComputeInstance ...
ComputeTypeComputeInstance ComputeType = "ComputeInstance"
// ComputeTypeDatabricks ...
ComputeTypeDatabricks ComputeType = "Databricks"
// ComputeTypeDataFactory ...
ComputeTypeDataFactory ComputeType = "DataFactory"
// ComputeTypeDataLakeAnalytics ...
ComputeTypeDataLakeAnalytics ComputeType = "DataLakeAnalytics"
// ComputeTypeHDInsight ...
ComputeTypeHDInsight ComputeType = "HDInsight"
// ComputeTypeSynapseSpark ...
ComputeTypeSynapseSpark ComputeType = "SynapseSpark"
// ComputeTypeVirtualMachine ...
ComputeTypeVirtualMachine ComputeType = "VirtualMachine"
)
// PossibleComputeTypeValues returns an array of possible values for the ComputeType const type.
func PossibleComputeTypeValues() []ComputeType {
return []ComputeType{ComputeTypeAKS, ComputeTypeAmlCompute, ComputeTypeComputeInstance, ComputeTypeDatabricks, ComputeTypeDataFactory, ComputeTypeDataLakeAnalytics, ComputeTypeHDInsight, ComputeTypeSynapseSpark, ComputeTypeVirtualMachine}
}
// ComputeTypeBasicCompute enumerates the values for compute type basic compute.
type ComputeTypeBasicCompute string
const (
// ComputeTypeBasicComputeComputeTypeAKS ...
ComputeTypeBasicComputeComputeTypeAKS ComputeTypeBasicCompute = "AKS"
// ComputeTypeBasicComputeComputeTypeAmlCompute ...
ComputeTypeBasicComputeComputeTypeAmlCompute ComputeTypeBasicCompute = "AmlCompute"
// ComputeTypeBasicComputeComputeTypeCompute ...
ComputeTypeBasicComputeComputeTypeCompute ComputeTypeBasicCompute = "Compute"
// ComputeTypeBasicComputeComputeTypeComputeInstance ...
ComputeTypeBasicComputeComputeTypeComputeInstance ComputeTypeBasicCompute = "ComputeInstance"
// ComputeTypeBasicComputeComputeTypeDatabricks ...
ComputeTypeBasicComputeComputeTypeDatabricks ComputeTypeBasicCompute = "Databricks"
// ComputeTypeBasicComputeComputeTypeDataFactory ...
ComputeTypeBasicComputeComputeTypeDataFactory ComputeTypeBasicCompute = "DataFactory"
// ComputeTypeBasicComputeComputeTypeDataLakeAnalytics ...
ComputeTypeBasicComputeComputeTypeDataLakeAnalytics ComputeTypeBasicCompute = "DataLakeAnalytics"
// ComputeTypeBasicComputeComputeTypeHDInsight ...
ComputeTypeBasicComputeComputeTypeHDInsight ComputeTypeBasicCompute = "HDInsight"
// ComputeTypeBasicComputeComputeTypeVirtualMachine ...
ComputeTypeBasicComputeComputeTypeVirtualMachine ComputeTypeBasicCompute = "VirtualMachine"
)
// PossibleComputeTypeBasicComputeValues returns an array of possible values for the ComputeTypeBasicCompute const type.
func PossibleComputeTypeBasicComputeValues() []ComputeTypeBasicCompute {
return []ComputeTypeBasicCompute{ComputeTypeBasicComputeComputeTypeAKS, ComputeTypeBasicComputeComputeTypeAmlCompute, ComputeTypeBasicComputeComputeTypeCompute, ComputeTypeBasicComputeComputeTypeComputeInstance, ComputeTypeBasicComputeComputeTypeDatabricks, ComputeTypeBasicComputeComputeTypeDataFactory, ComputeTypeBasicComputeComputeTypeDataLakeAnalytics, ComputeTypeBasicComputeComputeTypeHDInsight, ComputeTypeBasicComputeComputeTypeVirtualMachine}
}
// ComputeTypeBasicComputeNodesInformation enumerates the values for compute type basic compute nodes
// information.
type ComputeTypeBasicComputeNodesInformation string
const (
// ComputeTypeBasicComputeNodesInformationComputeTypeAmlCompute ...
ComputeTypeBasicComputeNodesInformationComputeTypeAmlCompute ComputeTypeBasicComputeNodesInformation = "AmlCompute"
// ComputeTypeBasicComputeNodesInformationComputeTypeComputeNodesInformation ...
ComputeTypeBasicComputeNodesInformationComputeTypeComputeNodesInformation ComputeTypeBasicComputeNodesInformation = "ComputeNodesInformation"
)
// PossibleComputeTypeBasicComputeNodesInformationValues returns an array of possible values for the ComputeTypeBasicComputeNodesInformation const type.
func PossibleComputeTypeBasicComputeNodesInformationValues() []ComputeTypeBasicComputeNodesInformation {
return []ComputeTypeBasicComputeNodesInformation{ComputeTypeBasicComputeNodesInformationComputeTypeAmlCompute, ComputeTypeBasicComputeNodesInformationComputeTypeComputeNodesInformation}
}
// ComputeTypeBasicComputeSecrets enumerates the values for compute type basic compute secrets.
type ComputeTypeBasicComputeSecrets string
const (
// ComputeTypeBasicComputeSecretsComputeTypeAKS ...
ComputeTypeBasicComputeSecretsComputeTypeAKS ComputeTypeBasicComputeSecrets = "AKS"
// ComputeTypeBasicComputeSecretsComputeTypeComputeSecrets ...
ComputeTypeBasicComputeSecretsComputeTypeComputeSecrets ComputeTypeBasicComputeSecrets = "ComputeSecrets"
// ComputeTypeBasicComputeSecretsComputeTypeDatabricks ...
ComputeTypeBasicComputeSecretsComputeTypeDatabricks ComputeTypeBasicComputeSecrets = "Databricks"
// ComputeTypeBasicComputeSecretsComputeTypeVirtualMachine ...
ComputeTypeBasicComputeSecretsComputeTypeVirtualMachine ComputeTypeBasicComputeSecrets = "VirtualMachine"
)
// PossibleComputeTypeBasicComputeSecretsValues returns an array of possible values for the ComputeTypeBasicComputeSecrets const type.
func PossibleComputeTypeBasicComputeSecretsValues() []ComputeTypeBasicComputeSecrets {
return []ComputeTypeBasicComputeSecrets{ComputeTypeBasicComputeSecretsComputeTypeAKS, ComputeTypeBasicComputeSecretsComputeTypeComputeSecrets, ComputeTypeBasicComputeSecretsComputeTypeDatabricks, ComputeTypeBasicComputeSecretsComputeTypeVirtualMachine}
}
// ComputeTypeBasicCreateServiceRequest enumerates the values for compute type basic create service request.
type ComputeTypeBasicCreateServiceRequest string
const (
// ComputeTypeBasicCreateServiceRequestComputeTypeACI ...
ComputeTypeBasicCreateServiceRequestComputeTypeACI ComputeTypeBasicCreateServiceRequest = "ACI"
// ComputeTypeBasicCreateServiceRequestComputeTypeAKS ...
ComputeTypeBasicCreateServiceRequestComputeTypeAKS ComputeTypeBasicCreateServiceRequest = "AKS"
// ComputeTypeBasicCreateServiceRequestComputeTypeCreateServiceRequest ...
ComputeTypeBasicCreateServiceRequestComputeTypeCreateServiceRequest ComputeTypeBasicCreateServiceRequest = "CreateServiceRequest"
// ComputeTypeBasicCreateServiceRequestComputeTypeCustom ...
ComputeTypeBasicCreateServiceRequestComputeTypeCustom ComputeTypeBasicCreateServiceRequest = "Custom"
)
// PossibleComputeTypeBasicCreateServiceRequestValues returns an array of possible values for the ComputeTypeBasicCreateServiceRequest const type.
func PossibleComputeTypeBasicCreateServiceRequestValues() []ComputeTypeBasicCreateServiceRequest {
return []ComputeTypeBasicCreateServiceRequest{ComputeTypeBasicCreateServiceRequestComputeTypeACI, ComputeTypeBasicCreateServiceRequestComputeTypeAKS, ComputeTypeBasicCreateServiceRequestComputeTypeCreateServiceRequest, ComputeTypeBasicCreateServiceRequestComputeTypeCustom}
}
// ComputeTypeBasicServiceResponseBase enumerates the values for compute type basic service response base.
type ComputeTypeBasicServiceResponseBase string
const (
// ComputeTypeBasicServiceResponseBaseComputeTypeACI ...
ComputeTypeBasicServiceResponseBaseComputeTypeACI ComputeTypeBasicServiceResponseBase = "ACI"
// ComputeTypeBasicServiceResponseBaseComputeTypeAKS ...
ComputeTypeBasicServiceResponseBaseComputeTypeAKS ComputeTypeBasicServiceResponseBase = "AKS"
// ComputeTypeBasicServiceResponseBaseComputeTypeCustom ...
ComputeTypeBasicServiceResponseBaseComputeTypeCustom ComputeTypeBasicServiceResponseBase = "Custom"
// ComputeTypeBasicServiceResponseBaseComputeTypeServiceResponseBase ...
ComputeTypeBasicServiceResponseBaseComputeTypeServiceResponseBase ComputeTypeBasicServiceResponseBase = "ServiceResponseBase"
)
// PossibleComputeTypeBasicServiceResponseBaseValues returns an array of possible values for the ComputeTypeBasicServiceResponseBase const type.
func PossibleComputeTypeBasicServiceResponseBaseValues() []ComputeTypeBasicServiceResponseBase {
return []ComputeTypeBasicServiceResponseBase{ComputeTypeBasicServiceResponseBaseComputeTypeACI, ComputeTypeBasicServiceResponseBaseComputeTypeAKS, ComputeTypeBasicServiceResponseBaseComputeTypeCustom, ComputeTypeBasicServiceResponseBaseComputeTypeServiceResponseBase}
}
// DeploymentType enumerates the values for deployment type.
type DeploymentType string
const (
// DeploymentTypeBatch ...
DeploymentTypeBatch DeploymentType = "Batch"
// DeploymentTypeGRPCRealtimeEndpoint ...
DeploymentTypeGRPCRealtimeEndpoint DeploymentType = "GRPCRealtimeEndpoint"
// DeploymentTypeHTTPRealtimeEndpoint ...
DeploymentTypeHTTPRealtimeEndpoint DeploymentType = "HttpRealtimeEndpoint"
)
// PossibleDeploymentTypeValues returns an array of possible values for the DeploymentType const type.
func PossibleDeploymentTypeValues() []DeploymentType {
return []DeploymentType{DeploymentTypeBatch, DeploymentTypeGRPCRealtimeEndpoint, DeploymentTypeHTTPRealtimeEndpoint}
}
// EncryptionStatus enumerates the values for encryption status.
type EncryptionStatus string
const (
// EncryptionStatusDisabled ...
EncryptionStatusDisabled EncryptionStatus = "Disabled"
// EncryptionStatusEnabled ...
EncryptionStatusEnabled EncryptionStatus = "Enabled"
)
// PossibleEncryptionStatusValues returns an array of possible values for the EncryptionStatus const type.
func PossibleEncryptionStatusValues() []EncryptionStatus {
return []EncryptionStatus{EncryptionStatusDisabled, EncryptionStatusEnabled}
}
// IdentityType enumerates the values for identity type.
type IdentityType string
const (
// IdentityTypeApplication ...
IdentityTypeApplication IdentityType = "Application"
// IdentityTypeKey ...
IdentityTypeKey IdentityType = "Key"
// IdentityTypeManagedIdentity ...
IdentityTypeManagedIdentity IdentityType = "ManagedIdentity"
// IdentityTypeUser ...
IdentityTypeUser IdentityType = "User"
)
// PossibleIdentityTypeValues returns an array of possible values for the IdentityType const type.
func PossibleIdentityTypeValues() []IdentityType {
return []IdentityType{IdentityTypeApplication, IdentityTypeKey, IdentityTypeManagedIdentity, IdentityTypeUser}
}
// LoadBalancerType enumerates the values for load balancer type.
type LoadBalancerType string
const (
// LoadBalancerTypeInternalLoadBalancer ...
LoadBalancerTypeInternalLoadBalancer LoadBalancerType = "InternalLoadBalancer"
// LoadBalancerTypePublicIP ...
LoadBalancerTypePublicIP LoadBalancerType = "PublicIp"
)
// PossibleLoadBalancerTypeValues returns an array of possible values for the LoadBalancerType const type.
func PossibleLoadBalancerTypeValues() []LoadBalancerType {
return []LoadBalancerType{LoadBalancerTypeInternalLoadBalancer, LoadBalancerTypePublicIP}
}
// NodeState enumerates the values for node state.
type NodeState string
const (
// NodeStateIdle ...
NodeStateIdle NodeState = "idle"
// NodeStateLeaving ...
NodeStateLeaving NodeState = "leaving"
// NodeStatePreempted ...
NodeStatePreempted NodeState = "preempted"
// NodeStatePreparing ...
NodeStatePreparing NodeState = "preparing"
// NodeStateRunning ...
NodeStateRunning NodeState = "running"
// NodeStateUnusable ...
NodeStateUnusable NodeState = "unusable"
)
// PossibleNodeStateValues returns an array of possible values for the NodeState const type.
func PossibleNodeStateValues() []NodeState {
return []NodeState{NodeStateIdle, NodeStateLeaving, NodeStatePreempted, NodeStatePreparing, NodeStateRunning, NodeStateUnusable}
}
// OperationName enumerates the values for operation name.
type OperationName string
const (
// OperationNameCreate ...
OperationNameCreate OperationName = "Create"
// OperationNameDelete ...
OperationNameDelete OperationName = "Delete"
// OperationNameReimage ...
OperationNameReimage OperationName = "Reimage"
// OperationNameRestart ...
OperationNameRestart OperationName = "Restart"
// OperationNameStart ...
OperationNameStart OperationName = "Start"
// OperationNameStop ...
OperationNameStop OperationName = "Stop"
)
// PossibleOperationNameValues returns an array of possible values for the OperationName const type.
func PossibleOperationNameValues() []OperationName {
return []OperationName{OperationNameCreate, OperationNameDelete, OperationNameReimage, OperationNameRestart, OperationNameStart, OperationNameStop}
}
// OperationStatus enumerates the values for operation status.
type OperationStatus string
const (
// OperationStatusCreateFailed ...
OperationStatusCreateFailed OperationStatus = "CreateFailed"
// OperationStatusDeleteFailed ...
OperationStatusDeleteFailed OperationStatus = "DeleteFailed"
// OperationStatusInProgress ...
OperationStatusInProgress OperationStatus = "InProgress"
// OperationStatusReimageFailed ...
OperationStatusReimageFailed OperationStatus = "ReimageFailed"
// OperationStatusRestartFailed ...
OperationStatusRestartFailed OperationStatus = "RestartFailed"
// OperationStatusStartFailed ...
OperationStatusStartFailed OperationStatus = "StartFailed"
// OperationStatusStopFailed ...
OperationStatusStopFailed OperationStatus = "StopFailed"
// OperationStatusSucceeded ...
OperationStatusSucceeded OperationStatus = "Succeeded"
)
// PossibleOperationStatusValues returns an array of possible values for the OperationStatus const type.
func PossibleOperationStatusValues() []OperationStatus {
return []OperationStatus{OperationStatusCreateFailed, OperationStatusDeleteFailed, OperationStatusInProgress, OperationStatusReimageFailed, OperationStatusRestartFailed, OperationStatusStartFailed, OperationStatusStopFailed, OperationStatusSucceeded}
}
// OrderString enumerates the values for order string.
type OrderString string
const (
// OrderStringCreatedAtAsc ...
OrderStringCreatedAtAsc OrderString = "CreatedAtAsc"
// OrderStringCreatedAtDesc ...
OrderStringCreatedAtDesc OrderString = "CreatedAtDesc"
// OrderStringUpdatedAtAsc ...
OrderStringUpdatedAtAsc OrderString = "UpdatedAtAsc"
// OrderStringUpdatedAtDesc ...
OrderStringUpdatedAtDesc OrderString = "UpdatedAtDesc"
)
// PossibleOrderStringValues returns an array of possible values for the OrderString const type.
func PossibleOrderStringValues() []OrderString {
return []OrderString{OrderStringCreatedAtAsc, OrderStringCreatedAtDesc, OrderStringUpdatedAtAsc, OrderStringUpdatedAtDesc}
}
// OsType enumerates the values for os type.
type OsType string
const (
// OsTypeLinux ...
OsTypeLinux OsType = "Linux"
// OsTypeWindows ...
OsTypeWindows OsType = "Windows"
)
// PossibleOsTypeValues returns an array of possible values for the OsType const type.
func PossibleOsTypeValues() []OsType {
return []OsType{OsTypeLinux, OsTypeWindows}
}
// PrivateEndpointConnectionProvisioningState enumerates the values for private endpoint connection
// provisioning state.
type PrivateEndpointConnectionProvisioningState string
const (
// PrivateEndpointConnectionProvisioningStateCreating ...
PrivateEndpointConnectionProvisioningStateCreating PrivateEndpointConnectionProvisioningState = "Creating"
// PrivateEndpointConnectionProvisioningStateDeleting ...
PrivateEndpointConnectionProvisioningStateDeleting PrivateEndpointConnectionProvisioningState = "Deleting"
// PrivateEndpointConnectionProvisioningStateFailed ...
PrivateEndpointConnectionProvisioningStateFailed PrivateEndpointConnectionProvisioningState = "Failed"
// PrivateEndpointConnectionProvisioningStateSucceeded ...
PrivateEndpointConnectionProvisioningStateSucceeded PrivateEndpointConnectionProvisioningState = "Succeeded"
)
// PossiblePrivateEndpointConnectionProvisioningStateValues returns an array of possible values for the PrivateEndpointConnectionProvisioningState const type.
func PossiblePrivateEndpointConnectionProvisioningStateValues() []PrivateEndpointConnectionProvisioningState {
return []PrivateEndpointConnectionProvisioningState{PrivateEndpointConnectionProvisioningStateCreating, PrivateEndpointConnectionProvisioningStateDeleting, PrivateEndpointConnectionProvisioningStateFailed, PrivateEndpointConnectionProvisioningStateSucceeded}
}
// PrivateEndpointServiceConnectionStatus enumerates the values for private endpoint service connection status.
type PrivateEndpointServiceConnectionStatus string
const (
// PrivateEndpointServiceConnectionStatusApproved ...
PrivateEndpointServiceConnectionStatusApproved PrivateEndpointServiceConnectionStatus = "Approved"
// PrivateEndpointServiceConnectionStatusDisconnected ...
PrivateEndpointServiceConnectionStatusDisconnected PrivateEndpointServiceConnectionStatus = "Disconnected"
// PrivateEndpointServiceConnectionStatusPending ...
PrivateEndpointServiceConnectionStatusPending PrivateEndpointServiceConnectionStatus = "Pending"
// PrivateEndpointServiceConnectionStatusRejected ...
PrivateEndpointServiceConnectionStatusRejected PrivateEndpointServiceConnectionStatus = "Rejected"
// PrivateEndpointServiceConnectionStatusTimeout ...
PrivateEndpointServiceConnectionStatusTimeout PrivateEndpointServiceConnectionStatus = "Timeout"
)
// PossiblePrivateEndpointServiceConnectionStatusValues returns an array of possible values for the PrivateEndpointServiceConnectionStatus const type.
func PossiblePrivateEndpointServiceConnectionStatusValues() []PrivateEndpointServiceConnectionStatus {
return []PrivateEndpointServiceConnectionStatus{PrivateEndpointServiceConnectionStatusApproved, PrivateEndpointServiceConnectionStatusDisconnected, PrivateEndpointServiceConnectionStatusPending, PrivateEndpointServiceConnectionStatusRejected, PrivateEndpointServiceConnectionStatusTimeout}
}
// ProvisioningState enumerates the values for provisioning state.
type ProvisioningState string
const (
// ProvisioningStateCanceled ...
ProvisioningStateCanceled ProvisioningState = "Canceled"
// ProvisioningStateCreating ...
ProvisioningStateCreating ProvisioningState = "Creating"
// ProvisioningStateDeleting ...
ProvisioningStateDeleting ProvisioningState = "Deleting"
// ProvisioningStateFailed ...
ProvisioningStateFailed ProvisioningState = "Failed"
// ProvisioningStateSucceeded ...
ProvisioningStateSucceeded ProvisioningState = "Succeeded"
// ProvisioningStateUnknown ...
ProvisioningStateUnknown ProvisioningState = "Unknown"
// ProvisioningStateUpdating ...
ProvisioningStateUpdating ProvisioningState = "Updating"
)
// PossibleProvisioningStateValues returns an array of possible values for the ProvisioningState const type.
func PossibleProvisioningStateValues() []ProvisioningState {
return []ProvisioningState{ProvisioningStateCanceled, ProvisioningStateCreating, ProvisioningStateDeleting, ProvisioningStateFailed, ProvisioningStateSucceeded, ProvisioningStateUnknown, ProvisioningStateUpdating}
}
// QuotaUnit enumerates the values for quota unit.
type QuotaUnit string
const (
// QuotaUnitCount ...
QuotaUnitCount QuotaUnit = "Count"
)
// PossibleQuotaUnitValues returns an array of possible values for the QuotaUnit const type.
func PossibleQuotaUnitValues() []QuotaUnit {
return []QuotaUnit{QuotaUnitCount}
}
// ReasonCode enumerates the values for reason code.
type ReasonCode string
const (
// ReasonCodeNotAvailableForRegion ...
ReasonCodeNotAvailableForRegion ReasonCode = "NotAvailableForRegion"
// ReasonCodeNotAvailableForSubscription ...
ReasonCodeNotAvailableForSubscription ReasonCode = "NotAvailableForSubscription"
// ReasonCodeNotSpecified ...
ReasonCodeNotSpecified ReasonCode = "NotSpecified"
)
// PossibleReasonCodeValues returns an array of possible values for the ReasonCode const type.
func PossibleReasonCodeValues() []ReasonCode {
return []ReasonCode{ReasonCodeNotAvailableForRegion, ReasonCodeNotAvailableForSubscription, ReasonCodeNotSpecified}
}
// RemoteLoginPortPublicAccess enumerates the values for remote login port public access.
type RemoteLoginPortPublicAccess string
const (
// RemoteLoginPortPublicAccessDisabled ...
RemoteLoginPortPublicAccessDisabled RemoteLoginPortPublicAccess = "Disabled"
// RemoteLoginPortPublicAccessEnabled ...
RemoteLoginPortPublicAccessEnabled RemoteLoginPortPublicAccess = "Enabled"
// RemoteLoginPortPublicAccessNotSpecified ...
RemoteLoginPortPublicAccessNotSpecified RemoteLoginPortPublicAccess = "NotSpecified"
)
// PossibleRemoteLoginPortPublicAccessValues returns an array of possible values for the RemoteLoginPortPublicAccess const type.
func PossibleRemoteLoginPortPublicAccessValues() []RemoteLoginPortPublicAccess {
return []RemoteLoginPortPublicAccess{RemoteLoginPortPublicAccessDisabled, RemoteLoginPortPublicAccessEnabled, RemoteLoginPortPublicAccessNotSpecified}
}
// ResourceIdentityType enumerates the values for resource identity type.
type ResourceIdentityType string
const (
// ResourceIdentityTypeNone ...
ResourceIdentityTypeNone ResourceIdentityType = "None"
// ResourceIdentityTypeSystemAssigned ...
ResourceIdentityTypeSystemAssigned ResourceIdentityType = "SystemAssigned"
// ResourceIdentityTypeSystemAssignedUserAssigned ...
ResourceIdentityTypeSystemAssignedUserAssigned ResourceIdentityType = "SystemAssigned,UserAssigned"
// ResourceIdentityTypeUserAssigned ...
ResourceIdentityTypeUserAssigned ResourceIdentityType = "UserAssigned"
)
// PossibleResourceIdentityTypeValues returns an array of possible values for the ResourceIdentityType const type.
func PossibleResourceIdentityTypeValues() []ResourceIdentityType {
return []ResourceIdentityType{ResourceIdentityTypeNone, ResourceIdentityTypeSystemAssigned, ResourceIdentityTypeSystemAssignedUserAssigned, ResourceIdentityTypeUserAssigned}
}
// SSHPublicAccess enumerates the values for ssh public access.
type SSHPublicAccess string
const (
// SSHPublicAccessDisabled ...
SSHPublicAccessDisabled SSHPublicAccess = "Disabled"
// SSHPublicAccessEnabled ...
SSHPublicAccessEnabled SSHPublicAccess = "Enabled"
)
// PossibleSSHPublicAccessValues returns an array of possible values for the SSHPublicAccess const type.
func PossibleSSHPublicAccessValues() []SSHPublicAccess {
return []SSHPublicAccess{SSHPublicAccessDisabled, SSHPublicAccessEnabled}
}
// Status enumerates the values for status.
type Status string
const (
// StatusFailure ...
StatusFailure Status = "Failure"
// StatusInvalidQuotaBelowClusterMinimum ...
StatusInvalidQuotaBelowClusterMinimum Status = "InvalidQuotaBelowClusterMinimum"
// StatusInvalidQuotaExceedsSubscriptionLimit ...
StatusInvalidQuotaExceedsSubscriptionLimit Status = "InvalidQuotaExceedsSubscriptionLimit"
// StatusInvalidVMFamilyName ...
StatusInvalidVMFamilyName Status = "InvalidVMFamilyName"
// StatusOperationNotEnabledForRegion ...
StatusOperationNotEnabledForRegion Status = "OperationNotEnabledForRegion"
// StatusOperationNotSupportedForSku ...
StatusOperationNotSupportedForSku Status = "OperationNotSupportedForSku"
// StatusSuccess ...
StatusSuccess Status = "Success"
// StatusUndefined ...
StatusUndefined Status = "Undefined"
)
// PossibleStatusValues returns an array of possible values for the Status const type.
func PossibleStatusValues() []Status {
return []Status{StatusFailure, StatusInvalidQuotaBelowClusterMinimum, StatusInvalidQuotaExceedsSubscriptionLimit, StatusInvalidVMFamilyName, StatusOperationNotEnabledForRegion, StatusOperationNotSupportedForSku, StatusSuccess, StatusUndefined}
}
// Status1 enumerates the values for status 1.
type Status1 string
const (
// Status1Auto ...
Status1Auto Status1 = "Auto"
// Status1Disabled ...
Status1Disabled Status1 = "Disabled"
// Status1Enabled ...
Status1Enabled Status1 = "Enabled"
)
// PossibleStatus1Values returns an array of possible values for the Status1 const type.
func PossibleStatus1Values() []Status1 {
return []Status1{Status1Auto, Status1Disabled, Status1Enabled}
}
// UnderlyingResourceAction enumerates the values for underlying resource action.
type UnderlyingResourceAction string
const (
// UnderlyingResourceActionDelete ...
UnderlyingResourceActionDelete UnderlyingResourceAction = "Delete"
// UnderlyingResourceActionDetach ...
UnderlyingResourceActionDetach UnderlyingResourceAction = "Detach"
)
// PossibleUnderlyingResourceActionValues returns an array of possible values for the UnderlyingResourceAction const type.
func PossibleUnderlyingResourceActionValues() []UnderlyingResourceAction {
return []UnderlyingResourceAction{UnderlyingResourceActionDelete, UnderlyingResourceActionDetach}
}
// UsageUnit enumerates the values for usage unit.
type UsageUnit string
const (
// UsageUnitCount ...
UsageUnitCount UsageUnit = "Count"
)
// PossibleUsageUnitValues returns an array of possible values for the UsageUnit const type.
func PossibleUsageUnitValues() []UsageUnit {
return []UsageUnit{UsageUnitCount}
}
// ValueFormat enumerates the values for value format.
type ValueFormat string
const (
// ValueFormatJSON ...
ValueFormatJSON ValueFormat = "JSON"
)
// PossibleValueFormatValues returns an array of possible values for the ValueFormat const type.
func PossibleValueFormatValues() []ValueFormat {
return []ValueFormat{ValueFormatJSON}
}
// VariantType enumerates the values for variant type.
type VariantType string
const (
// VariantTypeControl ...
VariantTypeControl VariantType = "Control"
// VariantTypeTreatment ...
VariantTypeTreatment VariantType = "Treatment"
)
// PossibleVariantTypeValues returns an array of possible values for the VariantType const type.
func PossibleVariantTypeValues() []VariantType {
return []VariantType{VariantTypeControl, VariantTypeTreatment}
}
// VMPriceOSType enumerates the values for vm price os type.
type VMPriceOSType string
const (
// VMPriceOSTypeLinux ...
VMPriceOSTypeLinux VMPriceOSType = "Linux"
// VMPriceOSTypeWindows ...
VMPriceOSTypeWindows VMPriceOSType = "Windows"
)
// PossibleVMPriceOSTypeValues returns an array of possible values for the VMPriceOSType const type.
func PossibleVMPriceOSTypeValues() []VMPriceOSType {
return []VMPriceOSType{VMPriceOSTypeLinux, VMPriceOSTypeWindows}
}
// VMPriority enumerates the values for vm priority.
type VMPriority string
const (
// VMPriorityDedicated ...
VMPriorityDedicated VMPriority = "Dedicated"
// VMPriorityLowPriority ...
VMPriorityLowPriority VMPriority = "LowPriority"
)
// PossibleVMPriorityValues returns an array of possible values for the VMPriority const type.
func PossibleVMPriorityValues() []VMPriority {
return []VMPriority{VMPriorityDedicated, VMPriorityLowPriority}
}
// VMTier enumerates the values for vm tier.
type VMTier string
const (
// VMTierLowPriority ...
VMTierLowPriority VMTier = "LowPriority"
// VMTierSpot ...
VMTierSpot VMTier = "Spot"
// VMTierStandard ...
VMTierStandard VMTier = "Standard"
)
// PossibleVMTierValues returns an array of possible values for the VMTier const type.
func PossibleVMTierValues() []VMTier {
return []VMTier{VMTierLowPriority, VMTierSpot, VMTierStandard}
}
// WebServiceState enumerates the values for web service state.
type WebServiceState string
const (
// WebServiceStateFailed ...
WebServiceStateFailed WebServiceState = "Failed"
// WebServiceStateHealthy ...
WebServiceStateHealthy WebServiceState = "Healthy"
// WebServiceStateTransitioning ...
WebServiceStateTransitioning WebServiceState = "Transitioning"
// WebServiceStateUnhealthy ...
WebServiceStateUnhealthy WebServiceState = "Unhealthy"
// WebServiceStateUnschedulable ...
WebServiceStateUnschedulable WebServiceState = "Unschedulable"
)
// PossibleWebServiceStateValues returns an array of possible values for the WebServiceState const type.
func PossibleWebServiceStateValues() []WebServiceState {
return []WebServiceState{WebServiceStateFailed, WebServiceStateHealthy, WebServiceStateTransitioning, WebServiceStateUnhealthy, WebServiceStateUnschedulable}
}
| Azure/azure-sdk-for-go | services/machinelearningservices/mgmt/2021-04-01/machinelearningservices/enums.go | GO | mit | 32,878 |
#include "utfgrid_encode.h"
#include <unordered_map>
#include <glog/logging.h>
#include <jsoncpp/json/value.h>
#include <mapnik/unicode.hpp>
struct value_to_json_visitor {
Json::Value operator() (const mapnik::value_null& val) {return Json::Value();}
Json::Value operator() (const mapnik::value_bool& val) {return Json::Value(val);}
Json::Value operator() (const mapnik::value_integer& val) {return Json::Value(static_cast<uint>(val));}
Json::Value operator() (const mapnik::value_double& val) {return Json::Value(val);}
Json::Value operator() (const mapnik::value_unicode_string& val) {
std::string utf8_str;
mapnik::to_utf8(val, utf8_str);
return Json::Value(utf8_str);
}
};
std::string encode_utfgrid(const mapnik::grid_view& utfgrid, uint size) {
Json::Value root(Json::objectValue);
Json::Value& jgrid = root["grid"];
jgrid = Json::Value(Json::arrayValue);
using lookup_type = mapnik::grid::lookup_type;
using value_type = mapnik::grid::value_type;
using feature_type = mapnik::grid::feature_type;
using keys_type = std::unordered_map<lookup_type, value_type>;
std::vector<lookup_type> key_order;
keys_type keys;
const mapnik::grid::feature_key_type& feature_keys = utfgrid.get_feature_keys();
std::uint16_t codepoint = 32;
for (uint y = 0; y < utfgrid.height(); y += size) {
std::string line;
const value_type* row = utfgrid.get_row(y);
for (uint x = 0; x < utfgrid.width(); x += size) {
value_type feature_id = row[x];
auto feature_itr = feature_keys.find(feature_id);
lookup_type val;
if (feature_itr == feature_keys.end()) {
feature_id = mapnik::grid::base_mask;
} else {
val = feature_itr->second;
}
auto key_iter = keys.find(val);
if (key_iter == keys.end()) {
// Create a new entry for this key. Skip the codepoints that
// can't be encoded directly in JSON.
if (codepoint == 34) ++codepoint; // Skip "
else if (codepoint == 92) ++codepoint; // Skip backslash
if (feature_id == mapnik::grid::base_mask) {
keys[""] = codepoint;
key_order.push_back("");
} else {
keys[val] = codepoint;
key_order.push_back(val);
}
line.append(reinterpret_cast<char*>(&codepoint), sizeof(codepoint));
++codepoint;
} else {
line.append(reinterpret_cast<char*>(&key_iter->second), sizeof(key_iter->second));
}
}
jgrid.append(Json::Value(line));
}
Json::Value& jkeys = root["keys"];
jkeys = Json::Value(Json::arrayValue);
for (const auto& key_id : key_order) {
jkeys.append(key_id);
}
Json::Value& jdata = root["data"];
const feature_type& g_features = utfgrid.get_grid_features();
const std::set<std::string>& attributes = utfgrid.get_fields();
feature_type::const_iterator feat_end = g_features.end();
for (const std::string& key_item : key_order)
{
if (key_item.empty()) {
continue;
}
feature_type::const_iterator feat_itr = g_features.find(key_item);
if (feat_itr == feat_end) {
continue;
}
bool found = false;
Json::Value jfeature(Json::objectValue);
mapnik::feature_ptr feature = feat_itr->second;
for (const std::string& attr : attributes) {
value_to_json_visitor val_to_json;
if (attr == "__id__") {
jfeature[attr] = static_cast<uint>(feature->id());
} else if (feature->has_key(attr)) {
found = true;
jfeature[attr] = mapnik::util::apply_visitor(val_to_json, feature->get(attr));
}
}
if (found) {
jdata[feat_itr->first] = jfeature;
}
}
return root.toStyledString();
}
| sputnik-maps/maps-express | src/utfgrid_encode.cpp | C++ | mit | 4,103 |
package me.moodcat.api;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import lombok.Getter;
import me.moodcat.database.embeddables.VAVector;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* A mood represents a vector in the valence-arousal plane which will be attached to song.
*/
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum Mood {
// CHECKSTYLE:OFF
ANGRY(new VAVector(-0.6, 0.6), "Angry"),
CALM(new VAVector(0.3, -0.9), "Calm"),
EXCITING(new VAVector(0.4, 0.8), "Exciting"),
HAPPY(new VAVector(0.7, 0.6), "Happy"),
NERVOUS(new VAVector(-0.7, 0.4), "Nervous"),
PLEASING(new VAVector(0.6, 0.3), "Pleasing"),
PEACEFUL(new VAVector(0.5, -0.7), "Peaceful"),
RELAXED(new VAVector(0.6, -0.3), "Relaxed"),
SAD(new VAVector(-0.7, -0.2), "Sad"),
SLEEPY(new VAVector(-0.2, -0.9), "Sleepy");
// CHECKSTYLE:ON
/**
* List of all names that represent moods. Used in {@link #nameRepresentsMood(String)}.
* By storing this once, we save a lot of unnecessary list creations.
*/
private static final List<String> MOOD_NAMES = Arrays.asList(Mood.values()).stream()
.map(moodValue -> moodValue.getName())
.collect(Collectors.toList());
/**
* The vector that represents this mood.
*
* @return The vector of this mood.
*/
@Getter
@JsonIgnore
private final VAVector vector;
/**
* Readable name for the frontend.
*
* @return The readable name of this mood.
*/
@Getter
private final String name;
private Mood(final VAVector vector, final String name) {
this.vector = vector;
this.name = name;
}
/**
* Get the mood that is closest to the given vector.
*
* @param vector
* The vector to determine the mood for.
* @return The Mood that is closest to the vector.
*/
public static Mood closestTo(final VAVector vector) {
double distance = Double.MAX_VALUE;
Mood mood = null;
for (final Mood m : Mood.values()) {
final double moodDistance = m.vector.distance(vector);
if (moodDistance < distance) {
distance = moodDistance;
mood = m;
}
}
return mood;
}
/**
* Get the vector that represents the average of the provided list of moods.
*
* @param moods
* The textual list of moods.
* @return The average vector, or the zero-vector if no moods were found.
*/
public static VAVector createTargetVector(final List<String> moods) {
final List<VAVector> actualMoods = moods.stream()
.filter(Mood::nameRepresentsMood)
.map(mood -> Mood.valueOf(mood.toUpperCase(Locale.ROOT)))
.map(mood -> mood.getVector())
.collect(Collectors.toList());
return VAVector.average(actualMoods);
}
private static boolean nameRepresentsMood(final String mood) {
return MOOD_NAMES.contains(mood);
}
}
| MoodCat/MoodCat.me-Core | src/main/java/me/moodcat/api/Mood.java | Java | mit | 3,192 |
<?php
$lang = array(
'addons' => 'Add-ons',
'accessories' => 'Accessories',
'modules' => 'Modules',
'extensions' => 'Extensions',
'plugins' => 'Plugins',
'accessory' => 'Accessory',
'module' => 'Module',
'extension' => 'Extension',
'rte_tool' => 'Rich Text Editor Tool',
'addons_accessories' => 'Accessories',
'addons_modules' => 'Modules',
'addons_plugins' => 'Plugins',
'addons_extensions' => 'Extensions',
'addons_fieldtypes' => 'Fieldtypes',
'accessory_name' => 'Accessory Name',
'fieldtype_name' => 'Fieldtype Name',
'install' => 'Install',
'uninstall' => 'Uninstall',
'installed' => 'Installed',
'not_installed' => 'Not Installed',
'uninstalled' => 'Uninstalled',
'remove' => 'Remove',
'preferences_updated' => 'Preferences Updated',
'extension_enabled' => 'Extension Enabled',
'extension_disabled' => 'Extension Disabled',
'extensions_enabled' => 'Extensions Enabled',
'extensions_disabled' => 'Extensions Disabled',
'delete_fieldtype_confirm' => 'Are you sure you want to remove this fieldtype?',
'delete_fieldtype' => 'Remove Fieldtype',
'data_will_be_lost' => 'All data associated with this fieldtype, including all associated channel data, will be permanently deleted!',
'global_settings_saved' => 'Settings Saved',
'package_settings' => 'Package Settings',
'component' => 'Component',
'current_status' => 'Current Status',
'required_by' => 'Required by:',
'available_to_member_groups' => 'Available to Member Groups',
'specific_page' => 'Specific Page?',
'description' => 'Description',
'version' => 'Version',
'status' => 'Status',
'fieldtype' => 'Fieldtype',
'edit_accessory_preferences' => 'Edit Accessory Preferences',
'member_group_assignment' => 'Assigned Member Groups',
'page_assignment' => 'Assigned Pages',
'none' => 'None',
'and_more' => 'and %x more...',
'plugins_not_available' => 'Plugin Feed Disabled in Beta Version.',
'no_extension_id' => 'No Extension Specified',
// IGNORE
''=>'');
/* End of file addons_lang.php */
/* Location: ./system/expressionengine/language/english/addons_lang.php */ | cfox89/EE-Integration-to-API | system/expressionengine/language/english/addons_lang.php | PHP | mit | 2,255 |
import time
import multiprocessing
from flask import Flask
app = Flask(__name__)
backProc = None
def testFun():
print('Starting')
while True:
time.sleep(3)
print('looping')
time.sleep(3)
print('3 Seconds Later')
@app.route('/')
def root():
return 'Started a background process with PID ' + str(backProc.pid) + " is running: " + str(backProc.is_alive())
@app.route('/kill')
def kill():
backProc.terminate()
return 'killed: ' + str(backProc.pid)
@app.route('/kill_all')
def kill_all():
proc = multiprocessing.active_children()
for p in proc:
p.terminate()
return 'killed all'
@app.route('/active')
def active():
proc = multiprocessing.active_children()
arr = []
for p in proc:
print(p.pid)
arr.append(p.pid)
return str(arr)
@app.route('/start')
def start():
global backProc
backProc = multiprocessing.Process(target=testFun, args=(), daemon=True)
backProc.start()
return 'started: ' + str(backProc.pid)
if __name__ == '__main__':
app.run()
| wikomega/wikodemo | test.py | Python | mit | 1,073 |
package forscher.nocket.page.gen.ajax;
import gengui.annotations.Eager;
import java.io.Serializable;
public class AjaxTargetUpdateTestInner implements Serializable {
private String feld1;
private String feld2;
public String getEagerFeld1() {
return feld1;
}
@Eager
public void setEagerFeld1(String feld1) {
this.feld1 = feld1;
}
public String getFeld2() {
return feld2;
}
public void setFeld2(String feld2) {
this.feld2 = feld2;
}
}
| Nocket/nocket | examples/java/forscher/nocket/page/gen/ajax/AjaxTargetUpdateTestInner.java | Java | mit | 518 |
'''
Created by auto_sdk on 2014-12-17 17:22:51
'''
from top.api.base import RestApi
class SubusersGetRequest(RestApi):
def __init__(self,domain='gw.api.taobao.com',port=80):
RestApi.__init__(self,domain, port)
self.user_nick = None
def getapiname(self):
return 'taobao.subusers.get'
| CooperLuan/devops.notes | taobao/top/api/rest/SubusersGetRequest.py | Python | mit | 303 |
var textDivTopIndex = -1;
/**
* Creates a div that contains a textfiled, a plus and a minus button
* @param {String | undefined} textContent string to be added to the given new textField as value
* @returns new div
*/
function createTextDiv( textContent ) {
textDivTopIndex++;
var newTextDiv = document.createElement("DIV");
newTextDiv.className = "inputTextDiv form-group row";
newTextDiv.id = "uriArray"+textDivTopIndex;
newTextDiv.setAttribute("index", textDivTopIndex);
//newTextDiv.innerHTML = "hasznaltauto.hu url:";
//textfield that asks for a car uri and its align-responsible container
var textField = document.createElement("INPUT");
textField.id = uriInputFieldIdPrefix + textDivTopIndex;
textField.type = "url";
textField.name = "carUri"+textDivTopIndex;
textField.className = "form-control";
textField.placeholder = "hasznaltauto.hu url";
textField.value = (textContent === undefined) ? "" : textContent;
//all textfield has it, but there is to be 10 at maximum so the logic overhead would be greater(always the last one should have it) than this efficiency decrease
addEvent( textField, "focus", addOnFocus);
var textFieldAlignerDiv = document.createElement("DIV");
textFieldAlignerDiv.className = "col-xs-10 col-sm-10 col-sm-10";
textFieldAlignerDiv.appendChild(textField);
//add a new input field, or remove current
var inputButtonMinus = document.createElement("BUTTON");
inputButtonMinus.className = "btn btn-default btn-sm col-xs-1 col-sm-1 col-md-1 form-control-static";
inputButtonMinus.type = "button"; //avoid submit, which is default for buttons on forms
inputButtonMinus.innerHTML = "-";
inputButtonMinus.id = "inputButtonMinus" + textDivTopIndex;
newTextDiv.appendChild(textFieldAlignerDiv);
newTextDiv.appendChild(inputButtonMinus);
currentInputUriCount++;
return newTextDiv
}
function addOnFocus(event) {
if ( isLastField(event.target) && currentInputUriCount < 10 ) {
var addedTextDiv = createTextDiv();
formElement.insertBefore(addedTextDiv, sendButtonDiv);
event.stopPropagation();
}
}
function isLastField(field) {
textDivTopIndex = 0;
$(".inputTextDiv").each(function(index) {
textDivTopIndex = ( $(this).attr("index") > textDivTopIndex ) ? $(this).attr("index") : textDivTopIndex;
});
return textDivTopIndex == field.parentElement.parentElement.getAttribute("index") || currentInputUriCount === 1;
} | amdor/skyscraper_fes | DOMBuilder/InputElementBuilder.js | JavaScript | mit | 2,501 |
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace MtgApiManager.Lib.Dto.Set
{
internal class RootSetListDto : IMtgResponse
{
[JsonPropertyName("sets")]
public List<SetDto> Sets { get; set; }
}
} | MagicTheGathering/mtg-sdk-dotnet | src/MtgApiManager.Lib/Dto/Set/RootSetListDto.cs | C# | mit | 258 |
# frozen_string_literal: true
RSpec.describe Faraday::Response::RaiseError do
let(:conn) do
Faraday.new do |b|
b.response :raise_error
b.adapter :test do |stub|
stub.get('ok') { [200, { 'Content-Type' => 'text/html' }, '<body></body>'] }
stub.get('bad-request') { [400, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('unauthorized') { [401, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('forbidden') { [403, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('not-found') { [404, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('proxy-error') { [407, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('conflict') { [409, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('unprocessable-entity') { [422, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('4xx') { [499, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('nil-status') { [nil, { 'X-Reason' => 'nil' }, 'fail'] }
stub.get('server-error') { [500, { 'X-Error' => 'bailout' }, 'fail'] }
end
end
end
it 'raises no exception for 200 responses' do
expect { conn.get('ok') }.not_to raise_error
end
it 'raises Faraday::BadRequestError for 400 responses' do
expect { conn.get('bad-request') }.to raise_error(Faraday::BadRequestError) do |ex|
expect(ex.message).to eq('the server responded with status 400')
expect(ex.response[:headers]['X-Reason']).to eq('because')
expect(ex.response[:status]).to eq(400)
expect(ex.response_status).to eq(400)
expect(ex.response_body).to eq('keep looking')
expect(ex.response_headers['X-Reason']).to eq('because')
end
end
it 'raises Faraday::UnauthorizedError for 401 responses' do
expect { conn.get('unauthorized') }.to raise_error(Faraday::UnauthorizedError) do |ex|
expect(ex.message).to eq('the server responded with status 401')
expect(ex.response[:headers]['X-Reason']).to eq('because')
expect(ex.response[:status]).to eq(401)
expect(ex.response_status).to eq(401)
expect(ex.response_body).to eq('keep looking')
expect(ex.response_headers['X-Reason']).to eq('because')
end
end
it 'raises Faraday::ForbiddenError for 403 responses' do
expect { conn.get('forbidden') }.to raise_error(Faraday::ForbiddenError) do |ex|
expect(ex.message).to eq('the server responded with status 403')
expect(ex.response[:headers]['X-Reason']).to eq('because')
expect(ex.response[:status]).to eq(403)
expect(ex.response_status).to eq(403)
expect(ex.response_body).to eq('keep looking')
expect(ex.response_headers['X-Reason']).to eq('because')
end
end
it 'raises Faraday::ResourceNotFound for 404 responses' do
expect { conn.get('not-found') }.to raise_error(Faraday::ResourceNotFound) do |ex|
expect(ex.message).to eq('the server responded with status 404')
expect(ex.response[:headers]['X-Reason']).to eq('because')
expect(ex.response[:status]).to eq(404)
expect(ex.response_status).to eq(404)
expect(ex.response_body).to eq('keep looking')
expect(ex.response_headers['X-Reason']).to eq('because')
end
end
it 'raises Faraday::ProxyAuthError for 407 responses' do
expect { conn.get('proxy-error') }.to raise_error(Faraday::ProxyAuthError) do |ex|
expect(ex.message).to eq('407 "Proxy Authentication Required"')
expect(ex.response[:headers]['X-Reason']).to eq('because')
expect(ex.response[:status]).to eq(407)
expect(ex.response_status).to eq(407)
expect(ex.response_body).to eq('keep looking')
expect(ex.response_headers['X-Reason']).to eq('because')
end
end
it 'raises Faraday::ConflictError for 409 responses' do
expect { conn.get('conflict') }.to raise_error(Faraday::ConflictError) do |ex|
expect(ex.message).to eq('the server responded with status 409')
expect(ex.response[:headers]['X-Reason']).to eq('because')
expect(ex.response[:status]).to eq(409)
expect(ex.response_status).to eq(409)
expect(ex.response_body).to eq('keep looking')
expect(ex.response_headers['X-Reason']).to eq('because')
end
end
it 'raises Faraday::UnprocessableEntityError for 422 responses' do
expect { conn.get('unprocessable-entity') }.to raise_error(Faraday::UnprocessableEntityError) do |ex|
expect(ex.message).to eq('the server responded with status 422')
expect(ex.response[:headers]['X-Reason']).to eq('because')
expect(ex.response[:status]).to eq(422)
expect(ex.response_status).to eq(422)
expect(ex.response_body).to eq('keep looking')
expect(ex.response_headers['X-Reason']).to eq('because')
end
end
it 'raises Faraday::NilStatusError for nil status in response' do
expect { conn.get('nil-status') }.to raise_error(Faraday::NilStatusError) do |ex|
expect(ex.message).to eq('http status could not be derived from the server response')
expect(ex.response[:headers]['X-Reason']).to eq('nil')
expect(ex.response[:status]).to be_nil
expect(ex.response_status).to be_nil
expect(ex.response_body).to eq('fail')
expect(ex.response_headers['X-Reason']).to eq('nil')
end
end
it 'raises Faraday::ClientError for other 4xx responses' do
expect { conn.get('4xx') }.to raise_error(Faraday::ClientError) do |ex|
expect(ex.message).to eq('the server responded with status 499')
expect(ex.response[:headers]['X-Reason']).to eq('because')
expect(ex.response[:status]).to eq(499)
expect(ex.response_status).to eq(499)
expect(ex.response_body).to eq('keep looking')
expect(ex.response_headers['X-Reason']).to eq('because')
end
end
it 'raises Faraday::ServerError for 500 responses' do
expect { conn.get('server-error') }.to raise_error(Faraday::ServerError) do |ex|
expect(ex.message).to eq('the server responded with status 500')
expect(ex.response[:headers]['X-Error']).to eq('bailout')
expect(ex.response[:status]).to eq(500)
expect(ex.response_status).to eq(500)
expect(ex.response_body).to eq('fail')
expect(ex.response_headers['X-Error']).to eq('bailout')
end
end
describe 'request info' do
let(:conn) do
Faraday.new do |b|
b.response :raise_error
b.adapter :test do |stub|
stub.post(url, request_body, request_headers) do
[400, { 'X-Reason' => 'because' }, 'keep looking']
end
end
end
end
let(:request_body) { JSON.generate({ 'item' => 'sth' }) }
let(:request_headers) { { 'Authorization' => 'Basic 123' } }
let(:url_path) { 'request' }
let(:query_params) { 'full=true' }
let(:url) { "#{url_path}?#{query_params}" }
subject(:perform_request) do
conn.post url do |req|
req.headers['Authorization'] = 'Basic 123'
req.body = request_body
end
end
it 'returns the request info in the exception' do
expect { perform_request }.to raise_error(Faraday::BadRequestError) do |ex|
expect(ex.response[:request][:method]).to eq(:post)
expect(ex.response[:request][:url]).to eq(URI("http:/#{url}"))
expect(ex.response[:request][:url_path]).to eq("/#{url_path}")
expect(ex.response[:request][:params]).to eq({ 'full' => 'true' })
expect(ex.response[:request][:headers]).to match(a_hash_including(request_headers))
expect(ex.response[:request][:body]).to eq(request_body)
end
end
end
end
| lostisland/faraday | spec/faraday/response/raise_error_spec.rb | Ruby | mit | 7,602 |
class CreateBudgetsUsers < ActiveRecord::Migration
def change
create_table :budgets_users do |t|
t.integer :user_id
t.integer :budget_id
t.timestamps
end
end
end
| FAMM/manatee | db/migrate/20140311222555_create_budgets_users.rb | Ruby | mit | 193 |
package org.anodyneos.xp.tagext;
import javax.servlet.jsp.el.ELException;
import org.anodyneos.xp.XpContext;
import org.anodyneos.xp.XpException;
import org.anodyneos.xp.XpOutput;
import org.xml.sax.SAXException;
/**
* @author jvas
*/
public interface XpTag {
void doTag(XpOutput out) throws XpException, ELException, SAXException;
XpTag getParent();
void setXpBody(XpFragment xpBody);
void setXpContext(XpContext xpc);
void setParent(XpTag parent);
}
| jvasileff/aos-xp | src.java/org/anodyneos/xp/tagext/XpTag.java | Java | mit | 480 |
'use strict';
/**
* Stripe library
*
* @module core/lib/c_l_stripe
* @license MIT
* @copyright 2016 Chris Turnbull <https://github.com/christurnbull>
*/
module.exports = function(app, db, lib) {
return {
/**
* Donate
*/
donate: function(inObj, cb) {
var number, expiry, cvc, currency;
try {
number = parseInt(inObj.body.number);
var exp = inObj.body.expiry.split('/');
expiry = {
month: parseInt(exp[0]),
year: parseInt(exp[1])
};
cvc = parseInt(inObj.body.cvc);
currency = inObj.body.currency.toLowerCase();
} catch (e) {
return cb([{
msg: 'Invalid details.',
desc: 'Payment has not been made'
}], null);
}
// stripe supported zero-decimal currencies
var zeroDecimal = {
BIF: 'Burundian Franc',
CLP: 'Chilean Peso',
DJF: 'Djiboutian Franc',
GNF: 'Guinean Franc',
JPY: 'Japanese Yen',
KMF: 'Comorian Franc',
KRW: 'South Korean Won',
MGA: 'Malagasy Ariary',
PYG: 'Paraguayan Guaraní',
RWF: 'Rwandan Franc',
VND: 'Vietnamese Đồng',
VUV: 'Vanuatu Vatu',
XAF: 'Central African Cfa Franc',
XOF: 'West African Cfa Franc',
XPF: 'Cfp Franc'
};
var amount = inObj.body.amount;
if (!zeroDecimal.hasOwnProperty(currency.toUpperCase())) {
// all other supoprted currencies are decimal
amount = amount * 100;
}
var stripeData = {
amount: amount,
currency: currency.toLowerCase(),
description: 'Donation from ' + inObj.body.name,
source: {
number: number,
exp_month: expiry.month,
exp_year: expiry.year,
cvc: cvc,
object: 'card',
customer: inObj.body.customer,
email: inObj.body.email
}
};
lib.core.stripe.charges.create(stripeData, function(err, charge) {
if (err) {
return cb(err, null);
}
// save to database etc...
return cb(null, [charge]);
});
}
};
};
| christurnbull/MEANr-api | src/core/lib/c_l_stripePay.js | JavaScript | mit | 2,158 |
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Xunit;
namespace MR.AspNetCore.Jobs.Server
{
public class InfiniteRetryProcessorTest
{
[Fact]
public async Task Process_ThrowingProcessingCanceledException_Returns()
{
// Arrange
var services = new ServiceCollection();
services.AddLogging();
var loggerFactory = services.BuildServiceProvider().GetService<ILoggerFactory>();
var inner = new ThrowsProcessingCanceledExceptionProcessor();
var p = new InfiniteRetryProcessor(inner, loggerFactory);
var context = new ProcessingContext();
// Act
await p.ProcessAsync(context);
}
private class ThrowsProcessingCanceledExceptionProcessor : IProcessor
{
public Task ProcessAsync(ProcessingContext context)
{
throw new OperationCanceledException();
}
}
}
}
| mrahhal/MR.AspNetCore.Jobs | test/MR.AspNetCore.Jobs.Tests/Server/InfiniteRetryProcessorTest.cs | C# | mit | 891 |
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
struct _notify_raceboss_cry_msg_request_zocl
{
char wszCryMsg[10][65];
};
END_ATF_NAMESPACE
| goodwinxp/Yorozuya | library/ATF/_notify_raceboss_cry_msg_request_zocl.hpp | C++ | mit | 284 |
/*
artifact generator: C:\My\wizzi\v5\node_modules\wizzi-js\lib\artifacts\js\module\gen\main.js
primary source IttfDocument: c:\my\wizzi\v5\plugins\wizzi-core\src\ittf\root\legacy.js.ittf
*/
'use strict';
module.exports = require('wizzi-legacy-v4');
| wizzifactory/wizzi-core | legacy.js | JavaScript | mit | 259 |
#!/bin/env node
'use strict';
var winston = require('winston'),
path = require('path'),
mcapi = require('mailchimp-api'),
Parser = require('./lib/parser'),
ApiWrapper = require('./lib/api-wrapper');
var date = new Date();
date = date.toJSON().replace(/(-|:)/g, '.');
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, { level: 'silly'});
winston.add(winston.transports.File, {
filename: path.join('./', 'logs', 'sxla' + date + '.log'),
level: 'silly',
timestamp: true
});
winston.info('*********** APPLICATION STARTED ***********');
var apiKey = process.env.MAILCHIMP_SXLA_API_KEY;
var listId = process.env.MAILCHIMP_SXLA_LIST_ID;
winston.debug('apiKey: ', apiKey);
winston.debug('listId: ', listId);
var api = new ApiWrapper(mcapi, apiKey, listId, winston);
var parser = new Parser(winston);
parser.parseCsv(__dirname + '/data/soci14-15.csv', function (data) {
api.batchSubscribe(data);
});
| napcoder/sxla-mailchimp-importer | app.js | JavaScript | mit | 959 |
module.exports = {
normalizeEntityName: function() {},
afterInstall: function() {
this.addBowerPackageToProject('jsoneditor');
}
};
| jayphelps/ember-jsoneditor | blueprints/ember-jsoneditor/index.js | JavaScript | mit | 143 |
import AMD from '../../amd/src/amd.e6';
import Core from '../../core/src/core.e6';
import Event from '../../event/src/event.e6';
import Detect from '../../detect/src/detect.e6';
import Module from '../../modules/src/base.es6';
import ModulesApi from '../../modules/src/api.e6';
window.Moff = new Core();
window.Moff.amd = new AMD();
window.Moff.event = new Event();
window.Moff.Module = new Module();
window.Moff.detect = new Detect();
window.Moff.modules = new ModulesApi();
| kfuzaylov/moff | packages/loader/src/loader.e6.js | JavaScript | mit | 477 |
# == Schema Information
#
# Table name: templates
#
# id :integer not null, primary key
# name :string
# image :string
# description :text
# created_at :datetime not null
# updated_at :datetime not null
#
require 'rails_helper'
RSpec.describe Template, type: :model do
describe "relationships" do
it { should have_many(:cards).dependent(:restrict_with_error) }
end
describe "validators" do
it { should validate_presence_of(:name) }
it { should validate_presence_of(:image) }
end
end
| abarrak/card-mine-api | spec/models/template_spec.rb | Ruby | mit | 561 |
namespace RapidFTP.Chilkat.Tests.Utilities
{
using System.Diagnostics;
using RapidFTP.Models;
using RapidFTP.Utilities;
using Xunit;
using Xunit.Extensions;
public class UnixPathTest
{
[InlineData("/lv1", 1)]
[InlineData("/lv1/lv2", 2)]
[InlineData("/lv1/lv2/", 2)]
[InlineData("/lv1/lv2/lv3", 3)]
[InlineData("/lv1/lv2/lv3/lv4", 4)]
[InlineData("/lv1/lv2/lv3/lv4/lv5", 5)]
[Theory]
public void GetRelatedDirectories_GivenPath_ShouldSuccess(string path, int length)
{
var relatedDirectories = UnixPath.GetRelatedDirectories(path);
Assert.Equal(length, relatedDirectories.Length);
foreach (var directory in relatedDirectories)
{
Trace.WriteLine(directory);
}
}
[InlineData("/", true)]
[InlineData("/lv1", true)]
[InlineData("/lv1/lv2", true)]
[InlineData("/lv1/lv2/", true)]
[InlineData("/lv1/lv2/lv_3", true)]
[InlineData("/lv1/lv2/lv-3", true)]
[InlineData("lv1", false)]
[InlineData("lv1/lv2", false)]
[InlineData("", false)]
[InlineData("/lv1/*", false)]
[Theory]
public void IsWellFormed(string path, bool expected)
{
var result = UnixPath.IsWellFormed(path, ItemType.Directory);
Assert.Equal(expected, result);
}
}
} | khoale/RapidFTP | src/RapidFTP.Chilkat.Tests/Utilities/UnixPathTest.cs | C# | mit | 1,453 |
package org.real2space.neumann.evaris.core.structure;
/**
* Project Neumann
*
* @author RealTwo-Space
* @version 0
*
* created 2016/11/01
* added "extends Ring<F>" 2016/11/9
*/
public interface Field<F> extends Ring<F> {
/*
* Multiply this member by an inverse of "other".
*/
public void divide (F other);
/*
* Returns an inverse of this member.
*/
public F inverse ();
} | RealTwo-Space/Neumann | neumann/src/org/real2space/neumann/evaris/core/structure/Field.java | Java | mit | 426 |
# coding: utf-8
import unittest
from config_reader import ConfigReader
class TestConfigReader(unittest.TestCase):
def setUp(self):
self.config = ConfigReader("""
<root>
<person>
<name>山田</name>
<age>15</age>
</person>
<person>
<name>佐藤</name>
<age>43</age>
</person>
</root>
""")
def test_get_names(self):
self.assertEqual(self.config.get_names(), ['山田', '佐藤'])
def test_get_ages(self):
self.assertEqual(self.config.get_ages(), ['15', '43'])
| orangain/jenkins-docker-sample | tests.py | Python | mit | 681 |
inside = lambda x, y: 4*x*x+y*y <= 100
def coll(sx, sy, dx, dy):
m = 0
for p in range(32):
m2 = m + 2**(-p)
if inside(sx + dx * m2, sy + dy * m2): m = m2
return (sx + dx*m, sy + dy*m)
def norm(x, y):
l = (x*x + y*y)**0.5
return (x/l, y/l)
sx, sy = 0, 10.1
dx, dy = 1.4, -19.7
for I in range(999):
sx, sy = coll(sx, sy, dx, dy)
if sy > 0 and abs(sx) <= 0.01:
print(I)
break
mx, my = norm(1, -4*sx/sy)
d = mx*dx + my*dy
dx, dy = -dx + 2 * mx * d, -dy + 2 * my * d
| jokkebk/euler | p144.py | Python | mit | 538 |
/**
* Module dependencies
*/
const express = require('express');
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
const compression = require('compression');
const helmet = require('helmet');
const hpp = require('hpp');
const config = require('./config');
const api = require('./api');
const pages = require('./app');
/**
* Create app and router
*/
const app = express();
/**
* Set express trust proxy
*/
app.set('trust proxy', true);
/**
* Set static directory
*/
app.use(express.static(__dirname + '/public'));
/**
* Add middlewares
*/
app.use(compression());
app.use(helmet());
app.use(hpp());
/**
* Ping route
*/
app.get('/ping', (req, res) => res.send('Pong'));
/**
* Add router
*/
app.use('/api', api);
/**
* Mount template router
*/
app.use('/', pages);
/**
* Port
*/
const port = process.env.PORT || config.server.port;
/**
* Cluster
*/
if (cluster.isMaster) {
for (let i = 0; i < numCPUs; i += 1) {
cluster.fork();
}
cluster.on('online', (worker) => {
console.log(`Worker ${worker.process.pid} is online`);
});
cluster.on('exit', (worker) => {
console.log(`Worker ${worker.process.pid} died`);
console.log('Starting a new worker');
cluster.fork();
});
} else {
app.listen(port, '0.0.0.0', () => {
console.log(`App listening on port ${port}.`);
});
}
/**
* Handle unhandled exceptions
*/
process.on('unhandledException', err => console.log(err.toString()));
/**
* Expose app
*/
module.exports = app;
| pazguille/haysubte | index.js | JavaScript | mit | 1,517 |
class UsersController < ApplicationController
def new
end
def create
user = User.new(
email: params[:email],
password: params[:password],
password_confirmation: params[:password_confirmation])
if user.save
session[:user_id] = user.id
flash[:success] = "Successfully Created User Account"
redirect_to '/'
else
flash[:warning] = "Invalid Email or Password"
redirect_to '/signup'
end
end
end
| acolletti21/braintree-store | app/controllers/users_controller.rb | Ruby | mit | 504 |
#include <vector>
#include <iostream>
struct point
{
double x;
double y;
};
int main()
{
// Generate a lot of uniformly distributed 2d points in the range -1,-1 to +1,+1.
enum { numXSamples = 10000 };
enum { numYSamples = 10000 };
std::vector<point> points;
points.reserve(numXSamples * numYSamples);
for(int x = 0;x < numXSamples;++x)
{
for(int y = 0;y < numXSamples;++y)
{
point p = {-1.0 + 2.0 * x / (numXSamples-1),-1.0 + 2.0 * y / (numYSamples-1)};
points.push_back(p);
}
}
// Count the ratio of points inside the unit circle.
int numerator = 0;
int denominator = 0;
for(auto pointIt = points.begin();pointIt != points.end();++pointIt)
{
if(pointIt->x * pointIt->x + pointIt->y * pointIt->y < 1.0)
{
++numerator;
}
++denominator;
}
// Derive the area of the unit circle.
auto circleArea = 4.0 * (double)numerator / denominator;
std::cout << "result: " << circleArea << std::endl;
return 0;
} | EOSIO/eos | libraries/wasm-jit/Test/Benchmark/Benchmark.cpp | C++ | mit | 944 |
class CreateVersions < ActiveRecord::Migration
def change
create_table :versions do |t|
t.string :item_type, :null => false
t.integer :item_id, :null => false
t.string :event, :null => false
t.string :whodunnit
t.text :object
t.string :locale
t.datetime :created_at
end
add_index :versions, [:item_type, :item_id]
end
end
| kostyakch/rhinoart_cms | db/migrate/20141229155334_create_versions.rb | Ruby | mit | 399 |
using System;
using System.Drawing;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using MahApps.Metro.Controls;
using NHotkey;
using NHotkey.Wpf;
using QuickHelper.ViewModels;
using QuickHelper.Windows;
using Application = System.Windows.Application;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
namespace QuickHelper
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : MetroWindow
{
public MainWindow()
{
InitializeComponent();
this.PreviewKeyDown += MainWindow_PreviewKeyDown;
this.InitTrayIcon();
HotkeyManager.Current.AddOrReplace(
"Bring to focus",
Key.OemQuestion,
ModifierKeys.Control | ModifierKeys.Windows,
OnBringToFocus);
HotkeyManager.Current.AddOrReplace(
"Bring to focus",
Key.Q, ModifierKeys.Control | ModifierKeys.Shift | ModifierKeys.Alt,
OnBringToFocus);
}
public void OnBringToFocus(object sender, HotkeyEventArgs eventArgs)
{
OpenApplication();
}
private void OpenApplication()
{
ViewModel.FilterText = WindowsHelper.GetActiveProcessFileName();
if (!this.IsVisible)
{
this.Show();
}
if (this.WindowState == WindowState.Minimized)
{
this.WindowState = WindowState.Maximized;
}
this.Activate();
this.Topmost = true; // important
this.Topmost = false; // important
this.Focus(); // important
}
protected MainViewModel ViewModel
{
get { return this.DataContext as MainViewModel; }
}
private void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
{
if (string.IsNullOrWhiteSpace(this.ViewModel.FilterText))
{
this.Hide();
}
else
{
this.ViewModel.ClearFilter();
}
}
}
private NotifyIcon _notifyIcon;
private void InitTrayIcon()
{
_notifyIcon = new NotifyIcon();
_notifyIcon.Icon = new Icon(SystemIcons.Question, 40, 40);
_notifyIcon.Visible = true;
_notifyIcon.DoubleClick += (sender, args) =>
{
this.Show();
var menu = this.FindResource("TrayContextMenu") as System.Windows.Controls.ContextMenu;
menu.IsOpen = false;
this.WindowState = WindowState.Normal;
};
_notifyIcon.MouseClick += (sender, args) =>
{
if (args.Button == MouseButtons.Right)
{
var menu = this.FindResource("TrayContextMenu") as System.Windows.Controls.ContextMenu;
menu.IsOpen = true;
}
};
}
protected override void OnStateChanged(EventArgs e)
{
if (WindowState == WindowState.Minimized)
this.Hide();
base.OnStateChanged(e);
}
protected void Menu_Exit(object sender, RoutedEventArgs e)
{
_notifyIcon.Visible = false;
Application.Current.Shutdown();
}
protected void Menu_Open(object sender, RoutedEventArgs e)
{
OpenApplication();
}
}
}
| aburok/quick-helper | QuickHelper/MainWindow.xaml.cs | C# | mit | 3,762 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TrackR")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TrackR")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d9aa4e01-1571-4721-b6b8-a402f67af6b2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| luetm/TrackR | TrackR.Client/Properties/AssemblyInfo.cs | C# | mit | 1,388 |
package fs.command;
import fs.App;
import fs.Disk;
import fs.util.FileUtils;
import java.util.Arrays;
/**
*
* @author José Andrés García Sáenz <jags9415@gmail.com>
*/
public class CreateFileCommand extends Command {
public final static String COMMAND = "mkfile";
@Override
public void execute(String[] args) {
if (args.length != 2 && args.length != 3) {
reportSyntaxError();
return;
}
String path = args[1];
String content = String.join(" ", Arrays.copyOfRange(args, 2, args.length));
App app = App.getInstance();
Disk disk = app.getDisk();
if (disk.exists(path) && !FileUtils.promptForVirtualOverride(path)) {
return;
}
try {
disk.createFile(path, content);
}
catch (Exception ex) {
reportError(ex);
}
}
@Override
protected String getName() {
return CreateFileCommand.COMMAND;
}
@Override
protected String getDescription() {
return "Create a file and set its content.";
}
@Override
protected String getSyntax() {
return getName() + " FILENAME \"<CONTENT>\"";
}
}
| leomv09/FileSystem | src/fs/command/CreateFileCommand.java | Java | mit | 1,247 |
import { A, O } from 'b-o-a';
import { State } from '../types/state';
import currentPage$ from '../props/current-page';
import signIn$ from '../props/sign-in';
import spots$ from '../props/spots';
import spotForm$ from '../props/spot-form';
import stampRallies$ from '../props/stamp-rallies';
import stampRally$ from '../props/stamp-rally';
import stampRallyForm$ from '../props/stamp-rally-form';
import token$ from '../props/token';
const getDefaultState = (): State => {
return {
googleApiKey: process.env.GOOGLE_API_KEY,
currentPage: 'sign_in#index',
signIn: {
email: null,
password: null
},
spots: [],
spotForm: {
name: null
},
stampRallies: [],
stampRally: null,
stampRallyForm: {
name: null
},
token: {
token: null,
userId: null
}
};
};
const $ = (action$: O<A<any>>, state: State): O<State> => {
const s = (state ? state : getDefaultState());
return O
.combineLatest(
currentPage$(s.currentPage, action$),
signIn$(s.signIn, action$),
token$(s.token, action$),
spots$(s.spots, action$),
spotForm$(s.spotForm, action$),
stampRallies$(s.stampRallies, action$),
stampRally$(s.stampRally, action$),
stampRallyForm$(s.stampRallyForm, action$),
(
currentPage,
signIn,
token,
spots,
spotForm,
stampRallies,
stampRally,
stampRallyForm
): State => {
return Object.assign({}, s, {
currentPage,
signIn,
token,
spots,
spotForm,
stampRallies,
stampRally,
stampRallyForm
});
}
)
.do(console.log.bind(console)) // logger for state
.share();
};
export { $ };
| bouzuya/rally-rxjs | src/props/index.ts | TypeScript | mit | 1,793 |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Copyright (c) 2013-2013 Bluecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "netbase.h"
#include "util.h"
#ifndef WIN32
#include <sys/fcntl.h>
#endif
#include "strlcpy.h"
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
using namespace std;
// Settings
typedef std::pair<CService, int> proxyType;
static proxyType proxyInfo[NET_MAX];
static proxyType nameproxyInfo;
int nConnectTimeout = 5000;
bool fNameLookup = false;
static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
enum Network ParseNetwork(std::string net) {
boost::to_lower(net);
if (net == "ipv4") return NET_IPV4;
if (net == "ipv6") return NET_IPV6;
if (net == "tor") return NET_TOR;
if (net == "i2p") return NET_I2P;
return NET_UNROUTABLE;
}
void SplitHostPort(std::string in, int &portOut, std::string &hostOut) {
size_t colon = in.find_last_of(':');
// if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
bool fHaveColon = colon != in.npos;
bool fBracketed = fHaveColon && (in[0]=='[' && in[colon-1]==']'); // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is safe
bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos);
if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
char *endp = NULL;
int n = strtol(in.c_str() + colon + 1, &endp, 10);
if (endp && *endp == 0 && n >= 0) {
in = in.substr(0, colon);
if (n > 0 && n < 0x10000)
portOut = n;
}
}
if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']')
hostOut = in.substr(1, in.size()-2);
else
hostOut = in;
}
bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
{
vIP.clear();
{
CNetAddr addr;
if (addr.SetSpecial(std::string(pszName))) {
vIP.push_back(addr);
return true;
}
}
struct addrinfo aiHint;
memset(&aiHint, 0, sizeof(struct addrinfo));
aiHint.ai_socktype = SOCK_STREAM;
aiHint.ai_protocol = IPPROTO_TCP;
#ifdef WIN32
# ifdef USE_IPV6
aiHint.ai_family = AF_UNSPEC;
# else
aiHint.ai_family = AF_INET;
# endif
aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
#else
# ifdef USE_IPV6
aiHint.ai_family = AF_UNSPEC;
# else
aiHint.ai_family = AF_INET;
# endif
aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
#endif
struct addrinfo *aiRes = NULL;
int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
if (nErr)
return false;
struct addrinfo *aiTrav = aiRes;
while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
{
if (aiTrav->ai_family == AF_INET)
{
assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
}
#ifdef USE_IPV6
if (aiTrav->ai_family == AF_INET6)
{
assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
}
#endif
aiTrav = aiTrav->ai_next;
}
freeaddrinfo(aiRes);
return (vIP.size() > 0);
}
bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
{
if (pszName[0] == 0)
return false;
char psz[256];
char *pszHost = psz;
strlcpy(psz, pszName, sizeof(psz));
if (psz[0] == '[' && psz[strlen(psz)-1] == ']')
{
pszHost = psz+1;
psz[strlen(psz)-1] = 0;
}
return LookupIntern(pszHost, vIP, nMaxSolutions, fAllowLookup);
}
bool LookupHostNumeric(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions)
{
return LookupHost(pszName, vIP, nMaxSolutions, false);
}
bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
{
if (pszName[0] == 0)
return false;
int port = portDefault;
std::string hostname = "";
SplitHostPort(std::string(pszName), port, hostname);
std::vector<CNetAddr> vIP;
bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
if (!fRet)
return false;
vAddr.resize(vIP.size());
for (unsigned int i = 0; i < vIP.size(); i++)
vAddr[i] = CService(vIP[i], port);
return true;
}
bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
{
std::vector<CService> vService;
bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
if (!fRet)
return false;
addr = vService[0];
return true;
}
bool LookupNumeric(const char *pszName, CService& addr, int portDefault)
{
return Lookup(pszName, addr, portDefault, false);
}
bool static Socks4(const CService &addrDest, SOCKET& hSocket)
{
printf("SOCKS4 connecting %s\n", addrDest.ToString().c_str());
if (!addrDest.IsIPv4())
{
closesocket(hSocket);
return error("Proxy destination is not IPv4");
}
char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
if (!addrDest.GetSockAddr((struct sockaddr*)&addr, &len) || addr.sin_family != AF_INET)
{
closesocket(hSocket);
return error("Cannot get proxy destination address");
}
memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
char* pszSocks4 = pszSocks4IP;
int nSize = sizeof(pszSocks4IP);
int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
if (ret != nSize)
{
closesocket(hSocket);
return error("Error sending to proxy");
}
char pchRet[8];
if (recv(hSocket, pchRet, 8, 0) != 8)
{
closesocket(hSocket);
return error("Error reading proxy response");
}
if (pchRet[1] != 0x5a)
{
closesocket(hSocket);
if (pchRet[1] != 0x5b)
printf("ERROR: Proxy returned error %d\n", pchRet[1]);
return false;
}
printf("SOCKS4 connected %s\n", addrDest.ToString().c_str());
return true;
}
bool static Socks5(string strDest, int port, SOCKET& hSocket)
{
printf("SOCKS5 connecting %s\n", strDest.c_str());
if (strDest.size() > 255)
{
closesocket(hSocket);
return error("Hostname too long");
}
char pszSocks5Init[] = "\5\1\0";
char *pszSocks5 = pszSocks5Init;
ssize_t nSize = sizeof(pszSocks5Init) - 1;
ssize_t ret = send(hSocket, pszSocks5, nSize, MSG_NOSIGNAL);
if (ret != nSize)
{
closesocket(hSocket);
return error("Error sending to proxy");
}
char pchRet1[2];
if (recv(hSocket, pchRet1, 2, 0) != 2)
{
closesocket(hSocket);
return error("Error reading proxy response");
}
if (pchRet1[0] != 0x05 || pchRet1[1] != 0x00)
{
closesocket(hSocket);
return error("Proxy failed to initialize");
}
string strSocks5("\5\1");
strSocks5 += '\000'; strSocks5 += '\003';
strSocks5 += static_cast<char>(std::min((int)strDest.size(), 255));
strSocks5 += strDest;
strSocks5 += static_cast<char>((port >> 8) & 0xFF);
strSocks5 += static_cast<char>((port >> 0) & 0xFF);
ret = send(hSocket, strSocks5.c_str(), strSocks5.size(), MSG_NOSIGNAL);
if (ret != (ssize_t)strSocks5.size())
{
closesocket(hSocket);
return error("Error sending to proxy");
}
char pchRet2[4];
if (recv(hSocket, pchRet2, 4, 0) != 4)
{
closesocket(hSocket);
return error("Error reading proxy response");
}
if (pchRet2[0] != 0x05)
{
closesocket(hSocket);
return error("Proxy failed to accept request");
}
if (pchRet2[1] != 0x00)
{
closesocket(hSocket);
switch (pchRet2[1])
{
case 0x01: return error("Proxy error: general failure");
case 0x02: return error("Proxy error: connection not allowed");
case 0x03: return error("Proxy error: network unreachable");
case 0x04: return error("Proxy error: host unreachable");
case 0x05: return error("Proxy error: connection refused");
case 0x06: return error("Proxy error: TTL expired");
case 0x07: return error("Proxy error: protocol error");
case 0x08: return error("Proxy error: address type not supported");
default: return error("Proxy error: unknown");
}
}
if (pchRet2[2] != 0x00)
{
closesocket(hSocket);
return error("Error: malformed proxy response");
}
char pchRet3[256];
switch (pchRet2[3])
{
case 0x01: ret = recv(hSocket, pchRet3, 4, 0) != 4; break;
case 0x04: ret = recv(hSocket, pchRet3, 16, 0) != 16; break;
case 0x03:
{
ret = recv(hSocket, pchRet3, 1, 0) != 1;
if (ret)
return error("Error reading from proxy");
int nRecv = pchRet3[0];
ret = recv(hSocket, pchRet3, nRecv, 0) != nRecv;
break;
}
default: closesocket(hSocket); return error("Error: malformed proxy response");
}
if (ret)
{
closesocket(hSocket);
return error("Error reading from proxy");
}
if (recv(hSocket, pchRet3, 2, 0) != 2)
{
closesocket(hSocket);
return error("Error reading from proxy");
}
printf("SOCKS5 connected %s\n", strDest.c_str());
return true;
}
bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
{
hSocketRet = INVALID_SOCKET;
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
printf("Cannot connect to %s: unsupported network\n", addrConnect.ToString().c_str());
return false;
}
SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hSocket == INVALID_SOCKET)
return false;
#ifdef SO_NOSIGPIPE
int set = 1;
setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
#endif
#ifdef WIN32
u_long fNonblock = 1;
if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
#else
int fFlags = fcntl(hSocket, F_GETFL, 0);
if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
#endif
{
closesocket(hSocket);
return false;
}
if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
{
// WSAEINVAL is here because some legacy version of winsock uses it
if (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINVAL)
{
struct timeval timeout;
timeout.tv_sec = nTimeout / 1000;
timeout.tv_usec = (nTimeout % 1000) * 1000;
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(hSocket, &fdset);
int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
if (nRet == 0)
{
printf("connection timeout\n");
closesocket(hSocket);
return false;
}
if (nRet == SOCKET_ERROR)
{
printf("select() for connection failed: %i\n",WSAGetLastError());
closesocket(hSocket);
return false;
}
socklen_t nRetSize = sizeof(nRet);
#ifdef WIN32
if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
#else
if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
#endif
{
printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
closesocket(hSocket);
return false;
}
if (nRet != 0)
{
printf("connect() failed after select(): %s\n",strerror(nRet));
closesocket(hSocket);
return false;
}
}
#ifdef WIN32
else if (WSAGetLastError() != WSAEISCONN)
#else
else
#endif
{
printf("connect() failed: %i\n",WSAGetLastError());
closesocket(hSocket);
return false;
}
}
// this isn't even strictly necessary
// CNode::ConnectNode immediately turns the socket back to non-blocking
// but we'll turn it back to blocking just in case
#ifdef WIN32
fNonblock = 0;
if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
#else
fFlags = fcntl(hSocket, F_GETFL, 0);
if (fcntl(hSocket, F_SETFL, fFlags & !O_NONBLOCK) == SOCKET_ERROR)
#endif
{
closesocket(hSocket);
return false;
}
hSocketRet = hSocket;
return true;
}
bool SetProxy(enum Network net, CService addrProxy, int nSocksVersion) {
assert(net >= 0 && net < NET_MAX);
if (nSocksVersion != 0 && nSocksVersion != 4 && nSocksVersion != 5)
return false;
if (nSocksVersion != 0 && !addrProxy.IsValid())
return false;
proxyInfo[net] = std::make_pair(addrProxy, nSocksVersion);
return true;
}
bool GetProxy(enum Network net, CService &addrProxy) {
assert(net >= 0 && net < NET_MAX);
if (!proxyInfo[net].second)
return false;
addrProxy = proxyInfo[net].first;
return true;
}
bool SetNameProxy(CService addrProxy, int nSocksVersion) {
if (nSocksVersion != 0 && nSocksVersion != 5)
return false;
if (nSocksVersion != 0 && !addrProxy.IsValid())
return false;
nameproxyInfo = std::make_pair(addrProxy, nSocksVersion);
return true;
}
bool GetNameProxy() {
return nameproxyInfo.second != 0;
}
bool IsProxy(const CNetAddr &addr) {
for (int i=0; i<NET_MAX; i++) {
if (proxyInfo[i].second && (addr == (CNetAddr)proxyInfo[i].first))
return true;
}
return false;
}
bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
{
const proxyType &proxy = proxyInfo[addrDest.GetNetwork()];
// no proxy needed
if (!proxy.second)
return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
SOCKET hSocket = INVALID_SOCKET;
// first connect to proxy server
if (!ConnectSocketDirectly(proxy.first, hSocket, nTimeout))
return false;
// do socks negotiation
switch (proxy.second) {
case 4:
if (!Socks4(addrDest, hSocket))
return false;
break;
case 5:
if (!Socks5(addrDest.ToStringIP(), addrDest.GetPort(), hSocket))
return false;
break;
default:
return false;
}
hSocketRet = hSocket;
return true;
}
bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout)
{
string strDest;
int port = portDefault;
SplitHostPort(string(pszDest), port, strDest);
SOCKET hSocket = INVALID_SOCKET;
CService addrResolved(CNetAddr(strDest, fNameLookup && !nameproxyInfo.second), port);
if (addrResolved.IsValid()) {
addr = addrResolved;
return ConnectSocket(addr, hSocketRet, nTimeout);
}
addr = CService("0.0.0.0:0");
if (!nameproxyInfo.second)
return false;
if (!ConnectSocketDirectly(nameproxyInfo.first, hSocket, nTimeout))
return false;
switch(nameproxyInfo.second)
{
default:
case 4: return false;
case 5:
if (!Socks5(strDest, port, hSocket))
return false;
break;
}
hSocketRet = hSocket;
return true;
}
void CNetAddr::Init()
{
memset(ip, 0, 16);
}
void CNetAddr::SetIP(const CNetAddr& ipIn)
{
memcpy(ip, ipIn.ip, sizeof(ip));
}
static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
static const unsigned char pchGarliCat[] = {0xFD,0x60,0xDB,0x4D,0xDD,0xB5};
bool CNetAddr::SetSpecial(const std::string &strName)
{
if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
if (vchAddr.size() != 16-sizeof(pchOnionCat))
return false;
memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
ip[i + sizeof(pchOnionCat)] = vchAddr[i];
return true;
}
if (strName.size()>11 && strName.substr(strName.size() - 11, 11) == ".oc.b32.i2p") {
std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 11).c_str());
if (vchAddr.size() != 16-sizeof(pchGarliCat))
return false;
memcpy(ip, pchOnionCat, sizeof(pchGarliCat));
for (unsigned int i=0; i<16-sizeof(pchGarliCat); i++)
ip[i + sizeof(pchGarliCat)] = vchAddr[i];
return true;
}
return false;
}
CNetAddr::CNetAddr()
{
Init();
}
CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
{
memcpy(ip, pchIPv4, 12);
memcpy(ip+12, &ipv4Addr, 4);
}
#ifdef USE_IPV6
CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
{
memcpy(ip, &ipv6Addr, 16);
}
#endif
CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
{
Init();
std::vector<CNetAddr> vIP;
if (LookupHost(pszIp, vIP, 1, fAllowLookup))
*this = vIP[0];
}
CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
{
Init();
std::vector<CNetAddr> vIP;
if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
*this = vIP[0];
}
int CNetAddr::GetByte(int n) const
{
return ip[15-n];
}
bool CNetAddr::IsIPv4() const
{
return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
}
bool CNetAddr::IsIPv6() const
{
return (!IsIPv4() && !IsTor() && !IsI2P());
}
bool CNetAddr::IsRFC1918() const
{
return IsIPv4() && (
GetByte(3) == 10 ||
(GetByte(3) == 192 && GetByte(2) == 168) ||
(GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
}
bool CNetAddr::IsRFC3927() const
{
return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
}
bool CNetAddr::IsRFC3849() const
{
return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
}
bool CNetAddr::IsRFC3964() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
}
bool CNetAddr::IsRFC6052() const
{
static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
}
bool CNetAddr::IsRFC4380() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
}
bool CNetAddr::IsRFC4862() const
{
static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
}
bool CNetAddr::IsRFC4193() const
{
return ((GetByte(15) & 0xFE) == 0xFC);
}
bool CNetAddr::IsRFC6145() const
{
static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
}
bool CNetAddr::IsRFC4843() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
}
bool CNetAddr::IsTor() const
{
return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
}
bool CNetAddr::IsI2P() const
{
return (memcmp(ip, pchGarliCat, sizeof(pchGarliCat)) == 0);
}
bool CNetAddr::IsLocal() const
{
// IPv4 loopback
if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
return true;
// IPv6 loopback (::1/128)
static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
if (memcmp(ip, pchLocal, 16) == 0)
return true;
return false;
}
bool CNetAddr::IsMulticast() const
{
return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
|| (GetByte(15) == 0xFF);
}
bool CNetAddr::IsValid() const
{
// Clean up 3-byte shifted addresses caused by garbage in size field
// of addr messages from versions before 0.2.9 checksum.
// Two consecutive addr messages look like this:
// header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
// so if the first length field is garbled, it reads the second batch
// of addr misaligned by 3 bytes.
if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
return false;
// unspecified IPv6 address (::/128)
unsigned char ipNone[16] = {};
if (memcmp(ip, ipNone, 16) == 0)
return false;
// documentation IPv6 address
if (IsRFC3849())
return false;
if (IsIPv4())
{
// INADDR_NONE
uint32_t ipNone = INADDR_NONE;
if (memcmp(ip+12, &ipNone, 4) == 0)
return false;
// 0
ipNone = 0;
if (memcmp(ip+12, &ipNone, 4) == 0)
return false;
}
return true;
}
bool CNetAddr::IsRoutable() const
{
return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || (IsRFC4193() && !IsTor() && !IsI2P()) || IsRFC4843() || IsLocal());
}
enum Network CNetAddr::GetNetwork() const
{
if (!IsRoutable())
return NET_UNROUTABLE;
if (IsIPv4())
return NET_IPV4;
if (IsTor())
return NET_TOR;
if (IsI2P())
return NET_I2P;
return NET_IPV6;
}
std::string CNetAddr::ToStringIP() const
{
if (IsTor())
return EncodeBase32(&ip[6], 10) + ".onion";
if (IsI2P())
return EncodeBase32(&ip[6], 10) + ".oc.b32.i2p";
CService serv(*this, 0);
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t socklen = sizeof(sockaddr);
if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
char name[1025] = "";
if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
return std::string(name);
}
if (IsIPv4())
return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
else
return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
}
std::string CNetAddr::ToString() const
{
return ToStringIP();
}
bool operator==(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) == 0);
}
bool operator!=(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) != 0);
}
bool operator<(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) < 0);
}
bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
{
if (!IsIPv4())
return false;
memcpy(pipv4Addr, ip+12, 4);
return true;
}
#ifdef USE_IPV6
bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
{
memcpy(pipv6Addr, ip, 16);
return true;
}
#endif
// get canonical identifier of an address' group
// no two connections will be attempted to addresses with the same group
std::vector<unsigned char> CNetAddr::GetGroup() const
{
std::vector<unsigned char> vchRet;
int nClass = NET_IPV6;
int nStartByte = 0;
int nBits = 16;
// all local addresses belong to the same group
if (IsLocal())
{
nClass = 255;
nBits = 0;
}
// all unroutable addresses belong to the same group
if (!IsRoutable())
{
nClass = NET_UNROUTABLE;
nBits = 0;
}
// for IPv4 addresses, '1' + the 16 higher-order bits of the IP
// includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
else if (IsIPv4() || IsRFC6145() || IsRFC6052())
{
nClass = NET_IPV4;
nStartByte = 12;
}
// for 6to4 tunneled addresses, use the encapsulated IPv4 address
else if (IsRFC3964())
{
nClass = NET_IPV4;
nStartByte = 2;
}
// for Teredo-tunneled IPv6 addresses, use the encapsulated IPv4 address
else if (IsRFC4380())
{
vchRet.push_back(NET_IPV4);
vchRet.push_back(GetByte(3) ^ 0xFF);
vchRet.push_back(GetByte(2) ^ 0xFF);
return vchRet;
}
else if (IsTor())
{
nClass = NET_TOR;
nStartByte = 6;
nBits = 4;
}
else if (IsI2P())
{
nClass = NET_I2P;
nStartByte = 6;
nBits = 4;
}
// for he.net, use /36 groups
else if (GetByte(15) == 0x20 && GetByte(14) == 0x11 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
nBits = 36;
// for the rest of the IPv6 network, use /32 groups
else
nBits = 32;
vchRet.push_back(nClass);
while (nBits >= 8)
{
vchRet.push_back(GetByte(15 - nStartByte));
nStartByte++;
nBits -= 8;
}
if (nBits > 0)
vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
return vchRet;
}
uint64 CNetAddr::GetHash() const
{
uint256 hash = Hash(&ip[0], &ip[16]);
uint64 nRet;
memcpy(&nRet, &hash, sizeof(nRet));
return nRet;
}
void CNetAddr::print() const
{
printf("CNetAddr(%s)\n", ToString().c_str());
}
// private extensions to enum Network, only returned by GetExtNetwork,
// and only used in GetReachabilityFrom
static const int NET_UNKNOWN = NET_MAX + 0;
static const int NET_TEREDO = NET_MAX + 1;
int static GetExtNetwork(const CNetAddr *addr)
{
if (addr == NULL)
return NET_UNKNOWN;
if (addr->IsRFC4380())
return NET_TEREDO;
return addr->GetNetwork();
}
/** Calculates a metric for how reachable (*this) is from a given partner */
int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
{
enum Reachability {
REACH_UNREACHABLE,
REACH_DEFAULT,
REACH_TEREDO,
REACH_IPV6_WEAK,
REACH_IPV4,
REACH_IPV6_STRONG,
REACH_PRIVATE
};
if (!IsRoutable())
return REACH_UNREACHABLE;
int ourNet = GetExtNetwork(this);
int theirNet = GetExtNetwork(paddrPartner);
bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
switch(theirNet) {
case NET_IPV4:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_IPV4: return REACH_IPV4;
}
case NET_IPV6:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_TEREDO: return REACH_TEREDO;
case NET_IPV4: return REACH_IPV4;
case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunneled
}
case NET_TOR:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
case NET_TOR: return REACH_PRIVATE;
}
case NET_I2P:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_I2P: return REACH_PRIVATE;
}
case NET_TEREDO:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_TEREDO: return REACH_TEREDO;
case NET_IPV6: return REACH_IPV6_WEAK;
case NET_IPV4: return REACH_IPV4;
}
case NET_UNKNOWN:
case NET_UNROUTABLE:
default:
switch(ourNet) {
default: return REACH_DEFAULT;
case NET_TEREDO: return REACH_TEREDO;
case NET_IPV6: return REACH_IPV6_WEAK;
case NET_IPV4: return REACH_IPV4;
case NET_I2P: return REACH_PRIVATE; // assume connections from unroutable addresses are
case NET_TOR: return REACH_PRIVATE; // either from Tor/I2P, or don't care about our address
}
}
}
void CService::Init()
{
port = 0;
}
CService::CService()
{
Init();
}
CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
{
}
CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
{
}
#ifdef USE_IPV6
CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
{
}
#endif
CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
{
assert(addr.sin_family == AF_INET);
}
#ifdef USE_IPV6
CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
{
assert(addr.sin6_family == AF_INET6);
}
#endif
bool CService::SetSockAddr(const struct sockaddr *paddr)
{
switch (paddr->sa_family) {
case AF_INET:
*this = CService(*(const struct sockaddr_in*)paddr);
return true;
#ifdef USE_IPV6
case AF_INET6:
*this = CService(*(const struct sockaddr_in6*)paddr);
return true;
#endif
default:
return false;
}
}
CService::CService(const char *pszIpPort, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(pszIpPort, ip, 0, fAllowLookup))
*this = ip;
}
CService::CService(const char *pszIpPort, int portDefault, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
*this = ip;
}
CService::CService(const std::string &strIpPort, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
*this = ip;
}
CService::CService(const std::string &strIpPort, int portDefault, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
*this = ip;
}
unsigned short CService::GetPort() const
{
return port;
}
bool operator==(const CService& a, const CService& b)
{
return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
}
bool operator!=(const CService& a, const CService& b)
{
return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
}
bool operator<(const CService& a, const CService& b)
{
return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
}
bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
{
if (IsIPv4()) {
if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
return false;
*addrlen = sizeof(struct sockaddr_in);
struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
memset(paddrin, 0, *addrlen);
if (!GetInAddr(&paddrin->sin_addr))
return false;
paddrin->sin_family = AF_INET;
paddrin->sin_port = htons(port);
return true;
}
#ifdef USE_IPV6
if (IsIPv6()) {
if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
return false;
*addrlen = sizeof(struct sockaddr_in6);
struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
memset(paddrin6, 0, *addrlen);
if (!GetIn6Addr(&paddrin6->sin6_addr))
return false;
paddrin6->sin6_family = AF_INET6;
paddrin6->sin6_port = htons(port);
return true;
}
#endif
return false;
}
std::vector<unsigned char> CService::GetKey() const
{
std::vector<unsigned char> vKey;
vKey.resize(18);
memcpy(&vKey[0], ip, 16);
vKey[16] = port / 0x100;
vKey[17] = port & 0x0FF;
return vKey;
}
std::string CService::ToStringPort() const
{
return strprintf("%i", port);
}
std::string CService::ToStringIPPort() const
{
if (IsIPv4() || IsTor() || IsI2P()) {
return ToStringIP() + ":" + ToStringPort();
} else {
return "[" + ToStringIP() + "]:" + ToStringPort();
}
}
std::string CService::ToString() const
{
return ToStringIPPort();
}
void CService::print() const
{
printf("CService(%s)\n", ToString().c_str());
}
void CService::SetPort(unsigned short portIn)
{
port = portIn;
}
| dallen6/bluecoin | src/netbase.cpp | C++ | mit | 32,522 |
'use strict';
/*
* * angular-socialshare v0.0.2
* * ♡ CopyHeart 2014 by Dayanand Prabhu http://djds4rce.github.io
* * Copying is an act of love. Please copy.
* */
angular.module('djds4rce.angular-socialshare', [])
.factory('$FB', ['$window', function($window) {
return {
init: function(fbId) {
if (fbId) {
this.fbId = fbId;
$window.fbAsyncInit = function() {
FB.init({
appId: fbId,
channelUrl: 'app/channel.html',
status: true,
xfbml: true
});
};
(function(d) {
var js,
id = 'facebook-jssdk',
ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement('script');
js.id = id;
js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
} else {
throw ("FB App Id Cannot be blank");
}
}
};
}]).directive('facebook', ['$http', function($http) {
return {
scope: {
callback: '=',
shares: '='
},
transclude: true,
template: '<div class="facebookButton">' +
'<div class="pluginButton">' +
'<div class="pluginButtonContainer">' +
'<div class="pluginButtonImage">' +
'<button type="button">' +
'<i class="pluginButtonIcon img sp_plugin-button-2x sx_plugin-button-2x_favblue"></i>' +
'</button>' +
'</div>' +
'<span class="pluginButtonLabel">Share</span>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="facebookCount">' +
'<div class="pluginCountButton pluginCountNum">' +
'<span ng-transclude></span>' +
'</div>' +
'<div class="pluginCountButtonNub"><s></s><i></i></div>' +
'</div>',
link: function(scope, element, attr) {
attr.$observe('url', function() {
if (attr.shares && attr.url) {
$http.get('https://api.facebook.com/method/links.getStats?urls=' + attr.url + '&format=json', {withCredentials: false}).success(function(res) {
var count = (res[0] && res[0].total_count) ? res[0].total_count.toString() : 0;
var decimal = '';
if (count.length > 6) {
if (count.slice(-6, -5) != "0") {
decimal = '.' + count.slice(-6, -5);
}
count = count.slice(0, -6);
count = count + decimal + 'M';
} else if (count.length > 3) {
if (count.slice(-3, -2) != "0") {
decimal = '.' + count.slice(-3, -2);
}
count = count.slice(0, -3);
count = count + decimal + 'k';
}
scope.shares = count;
}).error(function() {
scope.shares = 0;
});
}
element.unbind();
element.bind('click', function(e) {
FB.ui({
method: 'share',
href: attr.url
}, function(response){
if (scope.callback !== undefined && typeof scope.callback === "function") {
scope.callback(response);
}
});
e.preventDefault();
});
});
}
};
}]).directive('facebookFeedShare', ['$http', function($http) {
return {
scope: {
callback: '=',
shares: '='
},
transclude: true,
template: '<div class="facebookButton">' +
'<div class="pluginButton">' +
'<div class="pluginButtonContainer">' +
'<div class="pluginButtonImage">' +
'<button type="button">' +
'<i class="pluginButtonIcon img sp_plugin-button-2x sx_plugin-button-2x_favblue"></i>' +
'</button>' +
'</div>' +
'<span class="pluginButtonLabel">Share</span>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="facebookCount">' +
'<div class="pluginCountButton pluginCountNum">' +
'<span ng-transclude></span>' +
'</div>' +
'<div class="pluginCountButtonNub"><s></s><i></i></div>' +
'</div>',
link: function(scope, element, attr) {
attr.$observe('url', function() {
if (attr.shares && attr.url) {
$http.get('https://api.facebook.com/method/links.getStats?urls=' + attr.url + '&format=json', {withCredentials: false}).success(function(res) {
var count = res[0] ? res[0].total_count.toString() : 0;
var decimal = '';
if (count.length > 6) {
if (count.slice(-6, -5) != "0") {
decimal = '.' + count.slice(-6, -5);
}
count = count.slice(0, -6);
count = count + decimal + 'M';
} else if (count.length > 3) {
if (count.slice(-3, -2) != "0") {
decimal = '.' + count.slice(-3, -2);
}
count = count.slice(0, -3);
count = count + decimal + 'k';
}
scope.shares = count;
}).error(function() {
scope.shares = 0;
});
}
element.unbind();
element.bind('click', function(e) {
FB.ui({
method: 'feed',
link: attr.url,
picture: attr.picture,
name: attr.name,
caption: attr.caption,
description: attr.description
}, function(response){
if (scope.callback !== undefined && typeof scope.callback === "function") {
scope.callback(response);
}
});
e.preventDefault();
});
});
}
};
}]).directive('twitter', ['$timeout', function($timeout) {
return {
link: function(scope, element, attr) {
var renderTwitterButton = debounce(function() {
if (attr.url) {
$timeout(function() {
element[0].innerHTML = '';
twttr.widgets.createShareButton(
attr.url,
element[0],
function() {}, {
count: attr.count,
text: attr.text,
via: attr.via,
size: attr.size
}
);
});
}
}, 75);
attr.$observe('url', renderTwitterButton);
attr.$observe('text', renderTwitterButton);
}
};
}]).directive('linkedin', ['$timeout', '$http', '$window', function($timeout, $http, $window) {
return {
scope: {
shares: '='
},
transclude: true,
template: '<div class="linkedinButton">' +
'<div class="pluginButton">' +
'<div class="pluginButtonContainer">' +
'<div class="pluginButtonImage">in' +
'</div>' +
'<span class="pluginButtonLabel"><span>Share</span></span>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="linkedinCount">' +
'<div class="pluginCountButton">' +
'<div class="pluginCountButtonRight">' +
'<div class="pluginCountButtonLeft">' +
'<span ng-transclude></span>' +
'</div>' +
'</div>' +
'</div>' +
'</div>',
link: function(scope, element, attr) {
var renderLinkedinButton = debounce(function() {
if (attr.shares && attr.url) {
$http.jsonp('https://www.linkedin.com/countserv/count/share?url=' + attr.url + '&callback=JSON_CALLBACK&format=jsonp').success(function(res) {
scope.shares = res.count.toLocaleString();
}).error(function() {
scope.shares = 0;
});
}
$timeout(function() {
element.unbind();
element.bind('click', function() {
var url = encodeURIComponent(attr.url).replace(/'/g, "%27").replace(/"/g, "%22")
$window.open("//www.linkedin.com/shareArticle?mini=true&url=" + url + "&title=" + attr.title + "&summary=" + attr.summary);
});
});
}, 100);
attr.$observe('url', renderLinkedinButton);
attr.$observe('title', renderLinkedinButton);
attr.$observe('summary', renderLinkedinButton);
}
};
}]).directive('gplus', [function() {
return {
link: function(scope, element, attr) {
var googleShare = debounce(function() {
if (typeof gapi == "undefined") {
(function() {
var po = document.createElement('script');
po.type = 'text/javascript';
po.async = true;
po.src = 'https://apis.google.com/js/platform.js';
po.onload = renderGoogleButton;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
} else {
renderGoogleButton();
}
}, 100);
//voodo magic
var renderGoogleButton = (function(ele, attr) {
return function() {
var googleButton = document.createElement('div');
var id = attr.id || randomString(5);
attr.id = id;
googleButton.setAttribute('id', id);
element.innerHTML = '';
element.append(googleButton);
if (attr.class && attr.class.indexOf('g-plusone') != -1) {
window.gapi.plusone.render(id, attr);
} else {
window.gapi.plus.render(id, attr);
}
}
}(element, attr));
attr.$observe('href', googleShare);
}
};
}]).directive('tumblrText', [function() {
return {
link: function(scope, element, attr) {
var tumblr_button = document.createElement("a");
var renderTumblrText = debounce(function() {
tumblr_button.setAttribute("href", "https://www.tumblr.com/share/link?url=" + encodeURIComponent(attr.url) + "&name=" + encodeURIComponent(attr.name) + "&description=" + encodeURIComponent(attr.description));
tumblr_button.setAttribute("title", attr.title || "Share on Tumblr");
tumblr_button.setAttribute("style", attr.styling || "display:inline-block; text-indent:-9999px; overflow:hidden; width:81px; height:20px; background:url('https://platform.tumblr.com/v1/share_1.png') top left no-repeat transparent;");
element[0].innerHTML = '';
element.append(tumblr_button);
}, 100);
attr.$observe('url', renderTumblrText);
attr.$observe('name', renderTumblrText);
attr.$observe('description', renderTumblrText);
}
}
}]).directive('tumblrQoute', [function() {
return {
link: function(scope, element, attr) {
var tumblr_button = document.createElement("a");
var renderTumblrQoute = debounce(function() {
tumblr_button.setAttribute("href", "https://www.tumblr.com/share/quote?quote=" + encodeURIComponent(attr.qoute) + "&source=" + encodeURIComponent(attr.source));
tumblr_button.setAttribute("title", attr.title || "Share on Tumblr");
tumblr_button.setAttribute("style", attr.styling || "display:inline-block; text-indent:-9999px; overflow:hidden; width:81px; height:20px; background:url('https://platform.tumblr.com/v1/share_1.png') top left no-repeat transparent;");
element[0].innerHTML = '';
element.append(tumblr_button);
}, 100);
attr.$observe('qoute', renderTumblrQoute);
attr.$observe('source', renderTumblrQoute);
}
}
}]).directive('tumblrImage', [function() {
return {
link: function(scope, element, attr) {
var tumblr_button = document.createElement("a");
var renderTumblrImage = debounce(function() {
tumblr_button.setAttribute("href", "https://www.tumblr.com/share/photo?source=" + encodeURIComponent(attr.source) + "&caption=" + encodeURIComponent(attr.caption) + "&clickthru=" + encodeURIComponent(attr.clickthru));
tumblr_button.setAttribute("title", attr.title || "Share on Tumblr");
tumblr_button.setAttribute("style", attr.styling || "display:inline-block; text-indent:-9999px; overflow:hidden; width:81px; height:20px; background:url('https://platform.tumblr.com/v1/share_1.png') top left no-repeat transparent;");
element[0].innerHTML = '';
element.append(tumblr_button);
}, 100);
attr.$observe('source', renderTumblrImage);
attr.$observe('caption', renderTumblrImage);
attr.$observe('clickthru', renderTumblrImage);
}
}
}]).directive('tumblrVideo', [function() {
return {
link: function(scope, element, attr) {
var tumblr_button = document.createElement("a");
var renderTumblrVideo = debounce(function() {
tumblr_button.setAttribute("href", "https://www.tumblr.com/share/video?embed=" + encodeURIComponent(attr.embedcode) + "&caption=" + encodeURIComponent(attr.caption));
tumblr_button.setAttribute("title", attr.title || "Share on Tumblr");
tumblr_button.setAttribute("style", attr.styling || "display:inline-block; text-indent:-9999px; overflow:hidden; width:81px; height:20px; background:url('https://platform.tumblr.com/v1/share_1.png') top left no-repeat transparent;");
element[0].innerHTML = '';
element.append(tumblr_button);
}, 100);
attr.$observe('embedcode', renderTumblrVideo);
attr.$observe('caption', renderTumblrVideo);
}
}
}]).directive('pintrest', ['$window', '$timeout', function($window, $timeout) {
return {
template: '<a href="{{href}}" data-pin-do="{{pinDo}}" data-pin-config="{{pinConfig}}"><img src="//assets.pinterest.com/images/pidgets/pinit_fg_en_rect_gray_20.png" /></a>',
link: function(scope, element, attr) {
var pintrestButtonRenderer = debounce(function() {
var pin_button = document.createElement("a");
pin_button.setAttribute("href", '//www.pinterest.com/pin/create/button/?url=' + encodeURIComponent(attr.href) + '&media=' + encodeURIComponent(attr.img) + '&description=' + encodeURIComponent(attr.description));
pin_button.setAttribute("pinDo", attr.pinDo || "buttonPin");
pin_button.setAttribute("pinConfig", attr.pinConfig || "beside");
element[0].innerHTML = '';
element.append(pin_button);
$timeout(function() {
$window.parsePins(element);
});
}, 100);
attr.$observe('href', pintrestButtonRenderer);
attr.$observe('img', pintrestButtonRenderer);
attr.$observe('description', pintrestButtonRenderer);
}
}
}]);
//Simple Debounce Implementation
//http://davidwalsh.name/javascript-debounce-function
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this,
args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
//http://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript
/**
* RANDOM STRING GENERATOR
*
* Info: http://stackoverflow.com/a/27872144/383904
* Use: randomString(length [,"A"] [,"N"] );
* Default: return a random alpha-numeric string
* Arguments: If you use the optional "A", "N" flags:
* "A" (Alpha flag) return random a-Z string
* "N" (Numeric flag) return random 0-9 string
*/
function randomString(len, an) {
an = an && an.toLowerCase();
var str = "",
i = 0,
min = an == "a" ? 10 : 0,
max = an == "n" ? 10 : 62;
for (; i++ < len;) {
var r = Math.random() * (max - min) + min << 0;
str += String.fromCharCode(r += r > 9 ? r < 36 ? 55 : 61 : 48);
}
return str;
}
| khiettran/gofar | public/scripts/libs/bower/angular-socialshare.js | JavaScript | mit | 14,491 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Globalization;
namespace DevTreks.Extensions
{
/// <summary>
///Purpose: Serialize and deserialize a food nutrition cost object.
/// This calculator is used with inputs to calculate costs.
///Author: www.devtreks.org
///Date: 2014, June
///References: www.devtreks.org/helptreks/linkedviews/help/linkedview/HelpFile/148
///NOTES 1. Extends the base object MNSR1 object
///</summary>
public class MNC1Calculator : MNSR1
{
public MNC1Calculator()
: base()
{
//health care cost object
InitMNC1Properties();
}
//copy constructor
public MNC1Calculator(MNC1Calculator lca1Calc)
: base(lca1Calc)
{
CopyMNC1Properties(lca1Calc);
}
//need to store locals and update parent input.ocprice, aohprice, capprice
public Input MNCInput { get; set; }
public virtual void InitMNC1Properties()
{
//avoid null references to properties
this.InitCalculatorProperties();
this.InitSharedObjectProperties();
this.InitMNSR1Properties();
this.MNCInput = new Input();
}
public virtual void CopyMNC1Properties(
MNC1Calculator calculator)
{
this.CopyCalculatorProperties(calculator);
this.CopySharedObjectProperties(calculator);
this.CopyMNSR1Properties(calculator);
this.MNCInput = new Input(calculator.MNCInput);
}
//set the class properties using the XElement
public virtual void SetMNC1Properties(XElement calculator,
XElement currentElement)
{
this.SetCalculatorProperties(calculator);
//need the aggregating params (label, groupid, typeid and Date for sorting)
this.SetSharedObjectProperties(currentElement);
this.SetMNSR1Properties(calculator);
}
//attname and attvalue generally passed in from a reader
public virtual void SetMNC1Property(string attName,
string attValue)
{
this.SetMNSR1Property(attName, attValue);
}
public void SetMNC1Attributes(string attNameExtension,
ref XElement calculator)
{
//must remove old unwanted attributes
if (calculator != null)
{
//do not remove atts here, they were removed in prior this.MNCInput.SetInputAtts
//and now include good locals
//this also sets the aggregating atts
this.SetAndRemoveCalculatorAttributes(attNameExtension, ref calculator);
}
this.SetMNSR1Attributes(attNameExtension, ref calculator);
}
public virtual void SetMNC1Attributes(string attNameExtension,
ref XmlWriter writer)
{
//note must first use use either setanalyzeratts or SetCalculatorAttributes(attNameExtension, ref writer);
this.SetMNSR1Attributes(attNameExtension, ref writer);
}
public bool SetMNC1Calculations(
MN1CalculatorHelper.CALCULATOR_TYPES calculatorType,
CalculatorParameters calcParameters, ref XElement calculator,
ref XElement currentElement)
{
bool bHasCalculations = false;
string sErrorMessage = string.Empty;
InitMNC1Properties();
//deserialize xml to object
//set the base input properties (updates base input prices)
//locals come from input
this.MNCInput.SetInputProperties(calcParameters,
calculator, currentElement);
//set the calculator
this.SetMNC1Properties(calculator, currentElement);
bHasCalculations = RunMNC1Calculations(calcParameters);
if (calcParameters.SubApplicationType == Constants.SUBAPPLICATION_TYPES.inputprices)
{
//serialize object back to xml and fill in updates list
//this also removes atts
this.MNCInput.SetInputAttributes(calcParameters,
ref currentElement, calcParameters.Updates);
}
else
{
//no db updates outside base output
this.MNCInput.SetInputAttributes(calcParameters,
ref currentElement, null);
}
//this sets and removes some atts
this.SetMNC1Attributes(string.Empty, ref calculator);
//set the totals into calculator
this.MNCInput.SetNewInputAttributes(calcParameters, ref calculator);
//set calculatorid (primary way to display calculation attributes)
CalculatorHelpers.SetCalculatorId(
calculator, currentElement);
calcParameters.ErrorMessage = sErrorMessage;
return bHasCalculations;
}
public bool RunMNC1Calculations(CalculatorParameters calcParameters)
{
bool bHasCalculations = false;
//first figure quantities
UpdateBaseInputUnitPrices(calcParameters);
//then figure whether ocamount or capamount should be used as a multiplier
//times calcd by stock.multiplier
double multiplier = GetMultiplierForMNSR1();
//run cost calcs
bHasCalculations = this.RunMNSR1Calculations(calcParameters, multiplier);
return bHasCalculations;
}
private void UpdateBaseInputUnitPrices(
CalculatorParameters calcParameters)
{
//is being able to change ins and outs in tech elements scalable?? double check
//check illegal divisors
this.ContainerSizeInSSUnits = (this.ContainerSizeInSSUnits == 0)
? -1 : this.ContainerSizeInSSUnits;
this.TypicalServingsPerContainer = this.ContainerSizeInSSUnits / this.TypicalServingSize;
this.ActualServingsPerContainer = this.ContainerSizeInSSUnits / this.ActualServingSize;
//Actual serving size has to be 1 unit of hh measure
if (calcParameters.SubApplicationType == Constants.SUBAPPLICATION_TYPES.inputprices)
{
//tech analysis can change from base
this.MNCInput.OCAmount = 1;
}
//calculate OCPrice as a unit cost per serving (not per each unit of serving or ContainerSizeInSSUnits)
this.MNCInput.OCPrice = this.ContainerPrice / this.ActualServingsPerContainer;
//serving size is the unit cost
this.MNCInput.OCUnit = string.Concat(this.ActualServingSize, " ", this.ServingSizeUnit);
//transfer capprice (benefits need to track the package price using calculator.props)
this.MNCInput.CAPPrice = this.ContainerPrice;
this.MNCInput.CAPUnit = this.ContainerUnit;
if (this.MNCInput.CAPAmount > 0)
{
this.ServingCost = this.MNCInput.CAPPrice * this.MNCInput.CAPAmount;
this.MNCInput.TotalCAP = this.ServingCost;
}
else
{
//calculate cost per actual serving
//note that this can change when the input is added elsewhere
this.ServingCost = this.MNCInput.OCPrice * this.MNCInput.OCAmount;
this.MNCInput.TotalOC = this.ServingCost;
}
}
public double GetMultiplierForMNSR1()
{
double multiplier = 1;
if (this.MNCInput.CAPAmount > 0)
{
//cap budget can use container size for nutrient values
multiplier = this.ActualServingsPerContainer * this.MNCInput.CAPAmount;
}
else if (this.MNCInput.CAPAmount <= 0)
{
//op budget can use ocamount for nutrient values
multiplier = this.MNCInput.OCAmount;
}
return multiplier;
}
}
}
| kpboyle1/devtreks | src/DevTreks.Extensions/MN1/Statistics/MNC1Calculator.cs | C# | mit | 8,301 |
angular.module('myApp.toDoController', []).
controller('ToDoCtrl', ['$scope', '$state', '$http', '$route', function ($scope, $state, $http, $route) {
$scope.$state = $state;
$scope.addToDo = function() {
// Just in case...
if ($scope.toDoList.length > 50) {
alert("Exceeded to-do limit!!!");
return;
}
if (!$scope.newToDoName || !$scope.newToDoDesc) {
alert("Please fill out both fields!");
return;
}
var newToDo = {
'todo': $scope.newToDoName,
'description': $scope.newToDoDesc
};
$http.post('/to-dos/add-to-do', newToDo).
success(function(data, status, headers, config) {
}).
then(function(answer){
$scope.newToDoName = '';
$scope.newToDoDesc = '';
getToDos();
});
};
$scope.editToDoId = '';
$scope.editToDo = function(toDo) {
// Set the ID of the todo being edited
$scope.editToDoId = toDo._id;
// Reset the to do list in case we were editing other to dos
getToDos();
};
$scope.confirmEditToDo = function() {
// Get the data from the ToDo of interest
var toDoToEdit = '';
for (var i=0; i<$scope.toDoList.length; i++) {
if ($scope.toDoList[i]._id === $scope.editToDoId){
toDoToEdit = {
"todo" : $scope.toDoList[i].todo,
"description" : $scope.toDoList[i].description
};
break;
}
}
if (!toDoToEdit) {
alert("Could not get edited to-do!");
return;
} else if (!toDoToEdit.todo || !toDoToEdit.description) {
alert("Please fill out both fields!");
return;
}
$http.put('/to-dos/update-to-do/' + $scope.editToDoId, toDoToEdit).
success(function(data, status, headers, config) {
$scope.editToDoId = '';
}).
then(function(answer){
getToDos();
});
};
$scope.deleteToDo = function(toDo) {
var confirmation = confirm('Are you sure you want to delete?');
if (!confirmation){
return;
}
$http.delete('/to-dos/delete-to-do/' + toDo._id).
success(function(data, status, headers, config) {
}).
then(function(answer){
getToDos();
});
};
$scope.cancelEditToDo = function() {
$scope.editToDoId = '';
getToDos();
};
var getToDos = function() {
$http.get('/to-dos/to-dos').success(function(data, status, headers, config) {
$scope.toDoList = data;
});
};
// Execute these functions on page load
angular.element(document).ready(function () {
getToDos();
});
}]); | The-Lando-System/personal-website | app/to-do/toDoController.js | JavaScript | mit | 2,424 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.data.cosmos.internal.query;
import com.azure.data.cosmos.BadRequestException;
import com.azure.data.cosmos.BridgeInternal;
import com.azure.data.cosmos.CommonsBridgeInternal;
import com.azure.data.cosmos.internal.DocumentCollection;
import com.azure.data.cosmos.FeedOptions;
import com.azure.data.cosmos.Resource;
import com.azure.data.cosmos.SqlQuerySpec;
import com.azure.data.cosmos.internal.HttpConstants;
import com.azure.data.cosmos.internal.OperationType;
import com.azure.data.cosmos.internal.PartitionKeyRange;
import com.azure.data.cosmos.internal.ResourceType;
import com.azure.data.cosmos.internal.RxDocumentServiceRequest;
import com.azure.data.cosmos.internal.Strings;
import com.azure.data.cosmos.internal.Utils;
import com.azure.data.cosmos.internal.caches.RxCollectionCache;
import com.azure.data.cosmos.internal.routing.PartitionKeyInternal;
import com.azure.data.cosmos.internal.routing.Range;
import org.apache.commons.lang3.StringUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
/**
* While this class is public, but it is not part of our published public APIs.
* This is meant to be internally used only by our sdk.
*/
public class DocumentQueryExecutionContextFactory {
private final static int PageSizeFactorForTop = 5;
private static Mono<Utils.ValueHolder<DocumentCollection>> resolveCollection(IDocumentQueryClient client, SqlQuerySpec query,
ResourceType resourceTypeEnum, String resourceLink) {
RxCollectionCache collectionCache = client.getCollectionCache();
RxDocumentServiceRequest request = RxDocumentServiceRequest.create(
OperationType.Query,
resourceTypeEnum,
resourceLink, null
// TODO AuthorizationTokenType.INVALID)
); //this request doesnt actually go to server
return collectionCache.resolveCollectionAsync(request);
}
public static <T extends Resource> Flux<? extends IDocumentQueryExecutionContext<T>> createDocumentQueryExecutionContextAsync(
IDocumentQueryClient client,
ResourceType resourceTypeEnum,
Class<T> resourceType,
SqlQuerySpec query,
FeedOptions feedOptions,
String resourceLink,
boolean isContinuationExpected,
UUID correlatedActivityId) {
// return proxy
Flux<Utils.ValueHolder<DocumentCollection>> collectionObs = Flux.just(new Utils.ValueHolder<>(null));
if (resourceTypeEnum.isCollectionChild()) {
collectionObs = resolveCollection(client, query, resourceTypeEnum, resourceLink).flux();
}
DefaultDocumentQueryExecutionContext<T> queryExecutionContext = new DefaultDocumentQueryExecutionContext<T>(
client,
resourceTypeEnum,
resourceType,
query,
feedOptions,
resourceLink,
correlatedActivityId,
isContinuationExpected);
if (ResourceType.Document != resourceTypeEnum) {
return Flux.just(queryExecutionContext);
}
Mono<PartitionedQueryExecutionInfo> queryExecutionInfoMono =
com.azure.data.cosmos.internal.query.QueryPlanRetriever.getQueryPlanThroughGatewayAsync(client, query, resourceLink);
return collectionObs.single().flatMap(collectionValueHolder ->
queryExecutionInfoMono.flatMap(partitionedQueryExecutionInfo -> {
QueryInfo queryInfo =
partitionedQueryExecutionInfo.getQueryInfo();
// Non value aggregates must go through
// DefaultDocumentQueryExecutionContext
// Single partition query can serve queries like SELECT AVG(c
// .age) FROM c
// SELECT MIN(c.age) + 5 FROM c
// SELECT MIN(c.age), MAX(c.age) FROM c
// while pipelined queries can only serve
// SELECT VALUE <AGGREGATE>. So we send the query down the old
// pipeline to avoid a breaking change.
// Should be fixed by adding support for nonvalueaggregates
if (queryInfo.hasAggregates() && !queryInfo.hasSelectValue()) {
if (feedOptions != null && feedOptions.enableCrossPartitionQuery()) {
return Mono.error(BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.BADREQUEST,
"Cross partition query only supports 'VALUE " +
"<AggreateFunc>' for aggregates"));
}
return Mono.just(queryExecutionContext);
}
Mono<List<PartitionKeyRange>> partitionKeyRanges;
// The partitionKeyRangeIdInternal is no more a public API on FeedOptions, but have the below condition
// for handling ParallelDocumentQueryTest#partitionKeyRangeId
if (feedOptions != null && !StringUtils.isEmpty(CommonsBridgeInternal.partitionKeyRangeIdInternal(feedOptions))) {
partitionKeyRanges = queryExecutionContext.getTargetPartitionKeyRangesById(collectionValueHolder.v.resourceId(),
CommonsBridgeInternal.partitionKeyRangeIdInternal(feedOptions));
} else {
List<Range<String>> queryRanges =
partitionedQueryExecutionInfo.getQueryRanges();
if (feedOptions != null && feedOptions.partitionKey() != null) {
PartitionKeyInternal internalPartitionKey =
feedOptions.partitionKey()
.getInternalPartitionKey();
Range<String> range = Range.getPointRange(internalPartitionKey
.getEffectivePartitionKeyString(internalPartitionKey,
collectionValueHolder.v.getPartitionKey()));
queryRanges = Collections.singletonList(range);
}
partitionKeyRanges = queryExecutionContext
.getTargetPartitionKeyRanges(collectionValueHolder.v.resourceId(), queryRanges);
}
return partitionKeyRanges
.flatMap(pkranges -> createSpecializedDocumentQueryExecutionContextAsync(client,
resourceTypeEnum,
resourceType,
query,
feedOptions,
resourceLink,
isContinuationExpected,
partitionedQueryExecutionInfo,
pkranges,
collectionValueHolder.v.resourceId(),
correlatedActivityId).single());
})).flux();
}
public static <T extends Resource> Flux<? extends IDocumentQueryExecutionContext<T>> createSpecializedDocumentQueryExecutionContextAsync(
IDocumentQueryClient client,
ResourceType resourceTypeEnum,
Class<T> resourceType,
SqlQuerySpec query,
FeedOptions feedOptions,
String resourceLink,
boolean isContinuationExpected,
PartitionedQueryExecutionInfo partitionedQueryExecutionInfo,
List<PartitionKeyRange> targetRanges,
String collectionRid,
UUID correlatedActivityId) {
if (feedOptions == null) {
feedOptions = new FeedOptions();
}
int initialPageSize = Utils.getValueOrDefault(feedOptions.maxItemCount(),
ParallelQueryConfig.ClientInternalPageSize);
BadRequestException validationError = Utils.checkRequestOrReturnException(
initialPageSize > 0 || initialPageSize == -1, "MaxItemCount", "Invalid MaxItemCount %s", initialPageSize);
if (validationError != null) {
return Flux.error(validationError);
}
QueryInfo queryInfo = partitionedQueryExecutionInfo.getQueryInfo();
if (!Strings.isNullOrEmpty(queryInfo.getRewrittenQuery())) {
query = new SqlQuerySpec(queryInfo.getRewrittenQuery(), query.parameters());
}
boolean getLazyFeedResponse = queryInfo.hasTop();
// We need to compute the optimal initial page size for order-by queries
if (queryInfo.hasOrderBy()) {
int top;
if (queryInfo.hasTop() && (top = partitionedQueryExecutionInfo.getQueryInfo().getTop()) > 0) {
int pageSizeWithTop = Math.min(
(int)Math.ceil(top / (double)targetRanges.size()) * PageSizeFactorForTop,
top);
if (initialPageSize > 0) {
initialPageSize = Math.min(pageSizeWithTop, initialPageSize);
}
else {
initialPageSize = pageSizeWithTop;
}
}
// TODO: do not support continuation in string format right now
// else if (isContinuationExpected)
// {
// if (initialPageSize < 0)
// {
// initialPageSize = (int)Math.Max(feedOptions.MaxBufferedItemCount, ParallelQueryConfig.GetConfig().DefaultMaximumBufferSize);
// }
//
// initialPageSize = Math.Min(
// (int)Math.Ceiling(initialPageSize / (double)targetRanges.Count) * PageSizeFactorForTop,
// initialPageSize);
// }
}
return PipelinedDocumentQueryExecutionContext.createAsync(
client,
resourceTypeEnum,
resourceType,
query,
feedOptions,
resourceLink,
collectionRid,
partitionedQueryExecutionInfo,
targetRanges,
initialPageSize,
isContinuationExpected,
getLazyFeedResponse,
correlatedActivityId);
}
}
| navalev/azure-sdk-for-java | sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java | Java | mit | 11,381 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FlatRedBall;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
namespace Anfloga.Rendering
{
public class BloomRenderer : IEffectsRenderer
{
public int Height { get; set; }
public int Width { get; set; }
public float BloomIntensity { get; set; } = 2f;
public float BaseIntensity { get; set; } = 0.9f;
public float BloomSaturation { get; set; } = 1.5f;
public float BaseSaturation { get; set; } = 1.0f;
SpriteBatch spriteBatch;
RenderTarget2D target1;
RenderTarget2D target2;
Effect bloomEffect;
BloomExtractRenderer extractRenderer;
BlurRenderer blurRenderer;
GraphicsDevice device;
bool initialized = false;
public BloomRenderer(Effect bloomCombineEffect)
{
this.bloomEffect = bloomCombineEffect;
}
public void Initialize(GraphicsDevice device, Camera camera)
{
Height = device.PresentationParameters.BackBufferHeight;
Width = device.PresentationParameters.BackBufferWidth;
this.device = device;
spriteBatch = new SpriteBatch(this.device);
// use half size texture for extract and blur
target1 = new RenderTarget2D(device, Width / 2, Height / 2);
target2 = new RenderTarget2D(device, Width, Height);
extractRenderer = new BloomExtractRenderer();
extractRenderer.Initialize(this.device, camera);
blurRenderer = new BlurRenderer();
blurRenderer.Initialize(this.device, camera);
bloomEffect.Parameters["BloomIntensity"].SetValue(BloomIntensity);
bloomEffect.Parameters["BaseIntensity"].SetValue(BaseIntensity);
bloomEffect.Parameters["BloomSaturation"].SetValue(BloomSaturation);
bloomEffect.Parameters["BaseSaturation"].SetValue(BaseSaturation);
initialized = true;
}
public void Draw(RenderTarget2D src, RenderTarget2D dest)
{
if(!initialized)
{
throw new Exception("Draw was called before effect was initialized!");
}
// draw src buffer with extract effect to target1 buffer
extractRenderer.Draw(src, target1);
// draw extract buffer to target2 with blur
blurRenderer.Draw(target1, target2);
int destWidth = dest != null ? dest.Width : Width;
int destHeight = dest != null ? dest.Height : Height;
// finally perform our bloom combine
device.Textures[1] = src; // setting this allows the shader to operate on the src texture
device.SetRenderTarget(dest);
spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone, bloomEffect);
spriteBatch.Draw(target2, new Rectangle(0, 0, destWidth, destHeight), Color.White);
spriteBatch.End();
}
}
}
| vchelaru/Anfloga | Anfloga/Anfloga/Rendering/BloomRenderer.cs | C# | mit | 3,162 |
import CommuniqueApp from './communique-app';
CommuniqueApp.open();
| kramerc/communique | lib/browser/main.js | JavaScript | mit | 68 |
using System.Collections.Generic;
using System.IO;
using Reinforced.Typings.Fluent;
using Xunit;
namespace Reinforced.Typings.Tests.SpecificCases
{
public partial class SpecificTestCases
{
[Fact]
public void ReferencesPart6ByDanielWest()
{
/**
* Specific test case with equal folder names by Daniel West
*/
const string file1 = @"
export namespace Reinforced.Typings.Tests.SpecificCases {
export enum SomeEnum {
One = 0,
Two = 1
}
}";
const string file2 = @"
import * as Enum from '../../APIv2/Models/TimeAndAttendance/Enum';
export namespace Reinforced.Typings.Tests.SpecificCases {
export class SomeViewModel
{
public Enum: Enum.Reinforced.Typings.Tests.SpecificCases.SomeEnum;
}
}";
AssertConfiguration(s =>
{
s.Global(a => a.DontWriteWarningComment().UseModules(discardNamespaces: false));
s.ExportAsEnum<SomeEnum>().ExportTo("Areas/APIv2/Models/TimeAndAttendance/Enum.ts");
s.ExportAsClass<SomeViewModel>().WithPublicProperties().ExportTo("Areas/Reporting/Models/Model.ts");
}, new Dictionary<string, string>
{
{ Path.Combine(TargetDir, "Areas/APIv2/Models/TimeAndAttendance/Enum.ts"), file1 },
{ Path.Combine(TargetDir, "Areas/Reporting/Models/Model.ts"), file2 }
}, compareComments: true);
}
}
} | reinforced/Reinforced.Typings | Reinforced.Typings.Tests/SpecificCases/SpecificTestCases.ReferencesPart6ByDanielWest.cs | C# | mit | 1,466 |
package com.avsystem.scex.util.function;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.Collection;
public class StringUtilImpl implements StringUtil {
public static final StringUtilImpl INSTANCE = new StringUtilImpl();
private StringUtilImpl() {
}
@Override
public String concat(String... parts) {
return StringFunctions.concat(parts);
}
@Override
public boolean contains(String list, String item) {
return StringFunctions.contains(list, item);
}
@Override
public double extract(String string) {
return StringFunctions.extract(string);
}
@Override
public String regexFind(String value, String pattern) {
return StringFunctions.regexFind(value, pattern);
}
@Override
public String regexFindGroup(String value, String pattern) {
return StringFunctions.regexFindGroup(value, pattern);
}
@Override
public boolean regexMatches(String value, String pattern) {
return StringFunctions.regexMatches(value, pattern);
}
@Override
public String regexReplace(String value, String pattern, String replacement) {
return StringFunctions.regexReplace(value, pattern, replacement);
}
@Override
public String regexReplaceAll(String value, String pattern, String replacement) {
return StringFunctions.regexReplaceAll(value, pattern, replacement);
}
@Override
public String slice(String item, int from) {
return StringFunctions.slice(item, from);
}
@Override
public String slice(String item, int from, int to, boolean dot) {
return StringFunctions.slice(item, from, to, dot);
}
@Override
public String stripToAlphanumeric(String source, String replacement) {
return StringFunctions.stripToAlphanumeric(source, replacement);
}
/**
* Remove end for string if exist
*
* @param source source string
* @param end string to remove from the end of source
* @return string with removed end
*/
@Override
public String removeEnd(String source, String end) {
if (source != null && end != null) {
return source.endsWith(end) ? source.substring(0, source.length() - end.length()) : source;
}
return null;
}
/**
* Remove start from string if exist
*
* @param source source string
* @param start string to remove from the start of source
* @return string with removed end
*/
@Override
public String removeStart(String source, String start) {
if (source != null && start != null) {
return source.startsWith(start) ? source.substring(start.length(), source.length()) : source;
}
return null;
}
@Override
public String removeTRRoot(String source) {
if (source != null) {
if (source.startsWith("InternetGatewayDevice.")) {
source = source.replaceFirst("InternetGatewayDevice.", "");
} else if (source.startsWith("Device.")) {
source = source.replaceFirst("Device.", "");
}
}
return source;
}
@Override
public String random(int length) {
return RandomStringUtils.randomAlphanumeric(length);
}
/**
* Left pad a String with a specified String.
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padStr the String to pad with, null or empty treated as single space
* @return right padded String
*/
@Override
public String leftPad(String str, int size, String padStr) {
return StringFunctions.leftPad(str, size, padStr);
}
/**
* Right pad a String with a specified String.
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padStr the String to pad with, null or empty treated as single space
* @return left padded String
*/
@Override
public String rightPad(String str, int size, String padStr) {
return StringFunctions.rightPad(str, size, padStr);
}
@Override
public String subString(String str, int from, int to) {
return StringUtils.substring(str, from, to);
}
@Override
public String[] split(String str, String separator) {
return StringUtils.split(str, separator);
}
@Override
public String trimToEmpty(String str) {
return StringUtils.trimToEmpty(str);
}
@Override
public String replace(String str, String find, String replacement) {
return StringUtils.replace(str, find, replacement);
}
@Override
public String join(Collection<String> list, String separator) {
return StringUtils.join(list, separator);
}
@Override
public boolean stringContains(String source, String item) {
return StringUtils.contains(source, item);
}
@Override
public String hmacMD5(String str, String key) {
return new HmacUtils(HmacAlgorithms.HMAC_MD5, key).hmacHex(str);
}
}
| AVSystem/scex | scex-util/src/main/scala/com/avsystem/scex/util/function/StringUtilImpl.java | Java | mit | 5,283 |
require 'minitest_helper'
require 'mocha/setup'
module Sidekiq
module Statistic
describe 'Middleware' do
def to_number(i)
i.match('\.').nil? ? Integer(i) : Float(i) rescue i.to_s
end
before { Sidekiq.redis(&:flushdb) }
let(:date){ Time.now.utc.to_date }
let(:actual) do
Sidekiq.redis do |conn|
redis_hash = {}
conn
.hgetall(REDIS_HASH)
.each do |keys, value|
*keys, last = keys.split(":")
keys.inject(redis_hash){ |hash, key| hash[key] || hash[key] = {} }[last.to_sym] = to_number(value)
end
redis_hash.values.last
end
end
it 'records statistic for passed worker' do
middlewared {}
assert_equal 1, actual['HistoryWorker'][:passed]
assert_equal nil, actual['HistoryWorker'][:failed]
end
it 'records statistic for failed worker' do
begin
middlewared do
raise StandardError.new('failed')
end
rescue
end
assert_equal nil, actual['HistoryWorker'][:passed]
assert_equal 1, actual['HistoryWorker'][:failed]
end
it 'records statistic for any workers' do
middlewared { sleep 0.001 }
begin
middlewared do
sleep 0.1
raise StandardError.new('failed')
end
rescue
end
middlewared { sleep 0.001 }
assert_equal 2, actual['HistoryWorker'][:passed]
assert_equal 1, actual['HistoryWorker'][:failed]
end
it 'support multithreaded calculations' do
workers = []
20.times do
workers << Thread.new do
25.times { middlewared {} }
end
end
workers.each(&:join)
assert_equal 500, actual['HistoryWorker'][:passed]
end
it 'removes 1/4 the timelist entries after crossing max_timelist_length' do
workers = []
Sidekiq::Statistic.configuration.max_timelist_length = 10
11.times do
middlewared {}
end
assert_equal 8, Sidekiq.redis { |conn| conn.llen("#{Time.now.strftime "%Y-%m-%d"}:HistoryWorker:timeslist") }
end
it 'supports ActiveJob workers' do
message = {
'class' => 'ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper',
'wrapped' => 'RealWorkerClassName'
}
middlewared(ActiveJobWrapper, message) {}
assert_equal actual.keys, ['RealWorkerClassName']
assert_equal 1, actual['RealWorkerClassName'][:passed]
assert_equal nil, actual['RealWorkerClassName'][:failed]
end
it 'supports mailers called from AJ' do
message = {
'class' => 'ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper',
'wrapped' => 'ActionMailer::DeliveryJob',
'args' => [{
'job_class' => 'ActionMailer::DeliveryJob',
'job_id'=>'cdcc67fb-8fdc-490c-9226-9c7f46a2dbaf',
'queue_name'=>'mailers',
'arguments' => ['WrappedMailer', 'welcome_email', 'deliver_now']
}]
}
middlewared(ActiveJobWrapper, message) {}
assert_equal actual.keys, ['WrappedMailer']
assert_equal 1, actual['WrappedMailer'][:passed]
assert_equal nil, actual['WrappedMailer'][:failed]
end
it 'records statistic for more than one worker' do
middlewared{}
middlewared(OtherHistoryWorker){}
assert_equal 1, actual['HistoryWorker'][:passed]
assert_equal nil, actual['HistoryWorker'][:failed]
assert_equal 1, actual['OtherHistoryWorker'][:passed]
assert_equal nil, actual['OtherHistoryWorker'][:failed]
end
it 'records queue statistic for each worker' do
message = { 'queue' => 'default' }
middlewared(HistoryWorker, message){}
message = { 'queue' => 'test' }
middlewared(HistoryWorkerWithQueue, message){}
assert_equal 'default', actual['HistoryWorker'][:queue]
assert_equal 'test', actual['HistoryWorkerWithQueue'][:queue]
end
end
end
end
| business-of-fashion/sidekiq-statistic | test/test_sidekiq/middleware_test.rb | Ruby | mit | 4,165 |
package work.notech.poker.room;
import work.notech.poker.logic.Cards;
import java.util.List;
public class GameRoom {
private Integer roomIds;
private List<Integer> clientIds;
private Cards cards;
public Integer getRoomIds() {
return roomIds;
}
public void setRoomIds(Integer roomIds) {
this.roomIds = roomIds;
}
public List<Integer> getClientIds() {
return clientIds;
}
public void setClientIds(List<Integer> clientIds) {
this.clientIds = clientIds;
}
public Cards getCards() {
return cards;
}
public void setCards(Cards cards) {
this.cards = cards;
}
}
| wangzhaoming/Poker | code/poker-server/src/main/java/work/notech/poker/room/GameRoom.java | Java | mit | 671 |
// Take well-formed json from a sensu check result a context rich html document to be mail to
// one or more addresses.
//
// LICENSE:
// Copyright 2016 Yieldbot. <devops@yieldbot.com>
// Released under the MIT License; see LICENSE
// for details.
package main
import (
"bytes"
"fmt"
"github.com/codegangsta/cli"
// "github.com/yieldbot/sensumailer/lib"
"github.com/yieldbot/sensuplugin/sensuhandler"
"github.com/yieldbot/sensuplugin/sensuutil"
// "log"
"net/smtp"
"os"
// "time"
)
func main() {
var emailAddress string
var smtpHost string
var smtpPort string
var emailSender string
var debug bool
app := cli.NewApp()
app.Name = "handler-mailer"
app.Usage = "Send context rich html alert notifications via email"
app.Action = func(c *cli.Context) {
if debug {
fmt.Printf("This is the sending address: %v \n", emailSender)
fmt.Printf("This is the recieving address: %v\n", emailAddress)
fmt.Printf("This is the smtp address: %v:%v\n", smtpHost, smtpPort)
sensuutil.Exit("debug")
}
// Get the sensu event data
sensuEvent := new(sensuhandler.SensuEvent)
sensuEvent = sensuEvent.AcquireSensuEvent()
// Connect to the remote SMTP server.
s, err := smtp.Dial(smtpHost + ":" + smtpPort)
if err != nil {
sensuutil.EHndlr(err)
}
defer s.Close()
// Set the sender and recipient.
s.Mail(emailSender)
s.Rcpt(emailAddress)
// Send the email body.
ws, err := s.Data()
if err != nil {
sensuutil.EHndlr(err)
}
defer ws.Close()
buf := bytes.NewBufferString("This is the email body.")
if _, err = buf.WriteTo(ws); err != nil {
sensuutil.EHndlr(err)
}
fmt.Printf("Email sent to %s\n", emailAddress)
}
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "address",
Value: "mattjones@yieldbot.com",
Usage: "email address to send to",
EnvVar: "SENSU_HANDLER_EMAIL_ADDRESS",
Destination: &emailAddress,
},
cli.StringFlag{
Name: "host",
Value: "localhost",
Usage: "smtp server",
EnvVar: "SENSU_HANDLER_EMAIL_HOST",
Destination: &smtpHost,
},
cli.StringFlag{
Name: "port",
Value: "25",
Usage: "smtp port",
EnvVar: "SENSU_HANDLER_EMAIL_PORT",
Destination: &smtpPort,
},
cli.StringFlag{
Name: "sender",
Value: "sensu@yieldbot.com",
Usage: "email sender",
EnvVar: "SENSU_HANDLER_EMAIL_SENDER",
Destination: &emailSender,
},
cli.BoolFlag{
Name: "debug",
Usage: "Print debugging info, no alerts will be sent",
Destination: &debug,
},
}
app.Run(os.Args)
}
| yieldbot/sensumailer | cmd/handler-mailer/main.go | GO | mit | 2,623 |
module.exports = [
'babel-polyfill',
'react',
'react-redux',
'react-router',
'react-dom',
'redux',
'redux-thunk',
'seamless-immutable',
'react-router-redux',
'history',
'lodash',
'styled-components',
'prop-types',
];
| CheerfulYeti/React-Redux-Starter-Kit | webpack.vendor.js | JavaScript | mit | 243 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\DataCollector;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\HeaderBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* RequestDataCollector.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class RequestDataCollector extends DataCollector implements EventSubscriberInterface
{
protected $controllers;
public function __construct()
{
$this->controllers = new \SplObjectStorage();
}
/**
* {@inheritdoc}
*/
public function collect(Request $request, Response $response, \Exception $exception = null)
{
$responseHeaders = $response->headers->all();
$cookies = array();
foreach ($response->headers->getCookies() as $cookie) {
$cookies[] = $this->getCookieHeader($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly());
}
if (count($cookies) > 0) {
$responseHeaders['Set-Cookie'] = $cookies;
}
$attributes = array();
foreach ($request->attributes->all() as $key => $value) {
$attributes[$key] = $this->varToString($value);
}
$content = null;
try {
$content = $request->getContent();
} catch (\LogicException $e) {
// the user already got the request content as a resource
$content = false;
}
$sessionMetadata = array();
$sessionAttributes = array();
$flashes = array();
if ($request->hasSession()) {
$session = $request->getSession();
if ($session->isStarted()) {
$sessionMetadata['Created'] = date(DATE_RFC822, $session->getMetadataBag()->getCreated());
$sessionMetadata['Last used'] = date(DATE_RFC822, $session->getMetadataBag()->getLastUsed());
$sessionMetadata['Lifetime'] = $session->getMetadataBag()->getLifetime();
$sessionAttributes = $session->all();
$flashes = $session->getFlashBag()->peekAll();
}
}
$this->data = array(
'format' => $request->getRequestFormat(),
'content' => $content,
'content_type' => $response->headers->get('Content-Type') ? $response->headers->get('Content-Type') : 'text/html',
'status_code' => $response->getStatusCode(),
'request_query' => $request->query->all(),
'request_request' => $request->request->all(),
'request_headers' => $request->headers->all(),
'request_server' => $request->server->all(),
'request_cookies' => $request->cookies->all(),
'request_attributes' => $attributes,
'response_headers' => $responseHeaders,
'session_metadata' => $sessionMetadata,
'session_attributes' => $sessionAttributes,
'flashes' => $flashes,
'path_info' => $request->getPathInfo(),
'controller' => 'n/a',
'locale' => $request->getLocale(),
);
if (isset($this->controllers[$request])) {
$controller = $this->controllers[$request];
if (is_array($controller)) {
$r = new \ReflectionMethod($controller[0], $controller[1]);
$this->data['controller'] = array(
'class' => get_class($controller[0]),
'method' => $controller[1],
'file' => $r->getFilename(),
'line' => $r->getStartLine(),
);
} elseif ($controller instanceof \Closure) {
$this->data['controller'] = 'Closure';
} else {
$this->data['controller'] = (string) $controller ?: 'n/a';
}
unset($this->controllers[$request]);
}
}
public function getPathInfo()
{
return $this->data['path_info'];
}
public function getRequestRequest()
{
return new ParameterBag($this->data['request_request']);
}
public function getRequestQuery()
{
return new ParameterBag($this->data['request_query']);
}
public function getRequestHeaders()
{
return new HeaderBag($this->data['request_headers']);
}
public function getRequestServer()
{
return new ParameterBag($this->data['request_server']);
}
public function getRequestCookies()
{
return new ParameterBag($this->data['request_cookies']);
}
public function getRequestAttributes()
{
return new ParameterBag($this->data['request_attributes']);
}
public function getResponseHeaders()
{
return new ResponseHeaderBag($this->data['response_headers']);
}
public function getSessionMetadata()
{
return $this->data['session_metadata'];
}
public function getSessionAttributes()
{
return $this->data['session_attributes'];
}
public function getFlashes()
{
return $this->data['flashes'];
}
public function getContent()
{
return $this->data['content'];
}
public function getContentType()
{
return $this->data['content_type'];
}
public function getStatusCode()
{
return $this->data['status_code'];
}
public function getFormat()
{
return $this->data['format'];
}
public function getLocale()
{
return $this->data['locale'];
}
/**
* Gets the route name.
*
* The _route request attributes is automatically set by the Router Matcher.
*
* @return string The route
*/
public function getRoute()
{
return isset($this->data['request_attributes']['_route']) ? $this->data['request_attributes']['_route'] : '';
}
/**
* Gets the route parameters.
*
* The _route_params request attributes is automatically set by the RouterListener.
*
* @return array The parameters
*/
public function getRouteParams()
{
return isset($this->data['request_attributes']['_route_params']) ? $this->data['request_attributes']['_route_params'] : array();
}
/**
* Gets the controller.
*
* @return string The controller as a string
*/
public function getController()
{
return $this->data['controller'];
}
public function onKernelController(FilterControllerEvent $event)
{
$this->controllers[$event->getRequest()] = $event->getController();
}
public static function getSubscribedEvents()
{
return array(KernelEvents::CONTROLLER => 'onKernelController');
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'request';
}
private function getCookieHeader($name, $value, $expires, $path, $domain, $secure, $httponly)
{
$cookie = sprintf('%s=%s', $name, urlencode($value));
if (0 !== $expires) {
if (is_numeric($expires)) {
$expires = (int) $expires;
} elseif ($expires instanceof \DateTime) {
$expires = $expires->getTimestamp();
} else {
$expires = strtotime($expires);
if (false === $expires || -1 == $expires) {
throw new \InvalidArgumentException(sprintf('The "expires" cookie parameter is not valid.', $expires));
}
}
$cookie .= '; expires='.substr(\DateTime::createFromFormat('U', $expires, new \DateTimeZone('UTC'))->format('D, d-M-Y H:i:s T'), 0, -5);
}
if ($domain) {
$cookie .= '; domain='.$domain;
}
$cookie .= '; path='.$path;
if ($secure) {
$cookie .= '; secure';
}
if ($httponly) {
$cookie .= '; httponly';
}
return $cookie;
}
}
| ondrejmirtes/symfony | src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php | PHP | mit | 8,681 |
package com.sunilson.pro4.activities;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.sunilson.pro4.R;
import com.sunilson.pro4.baseClasses.Liveticker;
import com.sunilson.pro4.exceptions.LivetickerSetException;
import com.sunilson.pro4.utilities.Constants;
import com.sunilson.pro4.views.SubmitButtonBig;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class AddLivetickerActivity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
private ValueEventListener resultListener;
private DatabaseReference mReference, currentResultReference;
private boolean finished, startNow;
private String privacy = "public";
private String livetickerID;
private Calendar calendar;
private ArrayList<DatabaseReference> references = new ArrayList<>();
private CompoundButton.OnCheckedChangeListener switchListener;
@BindView(R.id.add_liveticker_date)
TextView dateTextView;
@BindView(R.id.add_liveticker_time)
TextView timeTextView;
@BindView(R.id.add_liveticker_title_edittext)
EditText titleEditText;
@BindView(R.id.add_liveticker_description_edittext)
EditText descriptionEditText;
@BindView(R.id.add_liveticker_status_edittext)
EditText statusEditText;
@BindView(R.id.add_liveticker_start_switch)
Switch dateSwitch;
@BindView(R.id.add_liveticker_privacy_switch)
Switch privacySwitch;
@BindView(R.id.add_liveticker_date_layout)
LinearLayout dateLayout;
@BindView(R.id.add_liveticker_privacy_title)
TextView privacyTitle;
@BindView(R.id.submit_button_view)
SubmitButtonBig submitButtonBig;
@OnClick(R.id.submit_button)
public void submit(View view) {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user == null || user.isAnonymous()) {
Toast.makeText(this, R.string.add_liveticker_user_failure, Toast.LENGTH_SHORT).show();
return;
}
final Liveticker liveticker = new Liveticker();
try {
liveticker.setTitle(titleEditText.getText().toString());
liveticker.setDescription(descriptionEditText.getText().toString());
liveticker.setAuthorID(user.getUid());
liveticker.setStateTimestamp(calendar.getTimeInMillis());
liveticker.setPrivacy(privacy);
liveticker.setStatus(statusEditText.getText().toString());
} catch (LivetickerSetException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
loading(true);
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference("/request/" + user.getUid() + "/addLiveticker/").push();
ref.setValue(liveticker).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
//Remove Event Listener from Queue, if it has been started
if (currentResultReference != null && resultListener != null) {
currentResultReference.removeEventListener(resultListener);
}
//Listen for results from Queue
DatabaseReference taskRef = FirebaseDatabase.getInstance().getReference("/result/" + user.getUid() + "/addLiveticker/" + ref.getKey());
//Add Listener to Reference and store Reference so we can later detach Listener
taskRef.addValueEventListener(resultListener);
currentResultReference = taskRef;
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_liveticker);
ButterKnife.bind(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mReference = FirebaseDatabase.getInstance().getReference();
initializeQueueListener();
calendar = Calendar.getInstance();
updateDateTime();
dateTextView.setOnClickListener(this);
timeTextView.setOnClickListener(this);
dateSwitch.setOnCheckedChangeListener(this);
privacySwitch.setOnCheckedChangeListener(this);
submitButtonBig.setText(getString(R.string.channel_edit_save), getString(R.string.loading));
}
@Override
protected void onStop() {
super.onStop();
//Remove Event Listener from Queue, if it has been started
if (currentResultReference != null && resultListener != null) {
currentResultReference.removeEventListener(resultListener);
}
}
@Override
protected void authChanged(FirebaseUser user) {
if (user.isAnonymous()) {
Intent i = new Intent(AddLivetickerActivity.this, MainActivity.class);
startActivity(i);
Toast.makeText(this, R.string.no_access_permission, Toast.LENGTH_SHORT).show();
}
}
/**
* Initialize Listener for "Add Liveticker Queue"
*/
private void initializeQueueListener() {
resultListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!finished) {
//Check what state the Queue event has
if (dataSnapshot.child("state").getValue() != null) {
//Liveticker was added successfully
if (dataSnapshot.child("state").getValue().toString().equals("success")) {
finished = true;
Intent i = new Intent();
i.putExtra("livetickerID", dataSnapshot.child("successDetails").getValue().toString());
setResult(Constants.ADD_LIVETICKER_RESULT_CODE, i);
finish();
} else if (dataSnapshot.child("state").getValue().toString().equals("error")) {
loading(false);
Toast.makeText(AddLivetickerActivity.this, dataSnapshot.child("errorDetails").getValue().toString(), Toast.LENGTH_LONG).show();
}
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
}
/**
* Change visual loading state
*
* @param loading
*/
private void loading(boolean loading) {
if (loading) {
submitButtonBig.loading(true);
} else {
submitButtonBig.loading(false);
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.add_liveticker_date:
showDateDialog();
break;
case R.id.add_liveticker_time:
showTimeDialog();
break;
}
}
/**
* A dialog to pick a date and set the calendar to that date
*/
private void showDateDialog() {
DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDateTime();
}
};
DatePickerDialog datePickerDialog = new DatePickerDialog(this, onDateSetListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis() + 432000000);
datePickerDialog.show();
}
/**
* A dialog to pick a time and set the calendar to that time
*/
private void showTimeDialog() {
TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
updateDateTime();
}
};
TimePickerDialog timePickerDialog = new TimePickerDialog(this, onTimeSetListener, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true);
timePickerDialog.show();
}
/**
* Update the Textviews with the current date from the calendar
*/
private void updateDateTime() {
Date date = calendar.getTime();
SimpleDateFormat formatDate = new SimpleDateFormat("dd.MM.yyyy", Locale.getDefault());
SimpleDateFormat formatTime = new SimpleDateFormat("HH:mm", Locale.getDefault());
dateTextView.setText(formatDate.format(date));
timeTextView.setText(formatTime.format(date));
}
/**
* When a switch gets toggled
*
* @param compoundButton Switch that was toggled
* @param b Value of switch
*/
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
switch (compoundButton.getId()) {
case R.id.add_liveticker_start_switch:
startNow = !startNow;
if (b) {
dateLayout.setVisibility(View.GONE);
} else {
dateLayout.setVisibility(View.VISIBLE);
}
break;
case R.id.add_liveticker_privacy_switch:
if (b) {
privacy = "public";
privacyTitle.setText(getString(R.string.add_liveticker_public_title));
} else {
privacy = "private";
privacyTitle.setText(getString(R.string.add_liveticker_public_title_private));
}
break;
}
}
}
| sunilson/My-Ticker-Android | Android App/app/src/main/java/com/sunilson/pro4/activities/AddLivetickerActivity.java | Java | mit | 11,353 |
import nextConnect from 'next-connect'
import auth from '../../middleware/auth'
import { deleteUser, updateUserByUsername } from '../../lib/db'
const handler = nextConnect()
handler
.use(auth)
.get((req, res) => {
// You do not generally want to return the whole user object
// because it may contain sensitive field such as !!password!! Only return what needed
// const { name, username, favoriteColor } = req.user
// res.json({ user: { name, username, favoriteColor } })
res.json({ user: req.user })
})
.use((req, res, next) => {
// handlers after this (PUT, DELETE) all require an authenticated user
// This middleware to check if user is authenticated before continuing
if (!req.user) {
res.status(401).send('unauthenticated')
} else {
next()
}
})
.put((req, res) => {
const { name } = req.body
const user = updateUserByUsername(req, req.user.username, { name })
res.json({ user })
})
.delete((req, res) => {
deleteUser(req)
req.logOut()
res.status(204).end()
})
export default handler
| flybayer/next.js | examples/with-passport-and-next-connect/pages/api/user.js | JavaScript | mit | 1,087 |
import { injectReducer } from 'STORE/reducers'
export default store => ({
path : 'checkHistoryList.html',
getComponent(nextState, cb) {
require.ensure([], (require) => {
const CheckHistoryList = require('VIEW/CheckHistoryList').default
const reducer = require('REDUCER/checkHistoryList').default
injectReducer(store, { key: 'checkHistoryList', reducer })
cb(null, CheckHistoryList)
}, 'checkHistoryList')
}
})
| OwlAford/IFP | src/routes/main/checkHistoryList.js | JavaScript | mit | 449 |
<?php
declare(strict_types=1);
namespace ShlinkMigrations;
use Doctrine\DBAL\Exception;
use Doctrine\DBAL\Platforms\MySQLPlatform;
use Doctrine\DBAL\Platforms\SqlitePlatform;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\SchemaException;
use Doctrine\Migrations\AbstractMigration;
use function is_subclass_of;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20160819142757 extends AbstractMigration
{
/**
* @throws Exception
* @throws SchemaException
*/
public function up(Schema $schema): void
{
$platformClass = $this->connection->getDatabasePlatform();
$table = $schema->getTable('short_urls');
$column = $table->getColumn('short_code');
match (true) {
is_subclass_of($platformClass, MySQLPlatform::class) => $column
->setPlatformOption('charset', 'utf8mb4')
->setPlatformOption('collation', 'utf8mb4_bin'),
is_subclass_of($platformClass, SqlitePlatform::class) => $column->setPlatformOption('collate', 'BINARY'),
default => null,
};
}
public function down(Schema $schema): void
{
// Nothing to roll back
}
public function isTransactional(): bool
{
return ! ($this->connection->getDatabasePlatform() instanceof MySQLPlatform);
}
}
| shlinkio/shlink | data/migrations/Version20160819142757.php | PHP | mit | 1,364 |
<?php
namespace RectorPrefix20210615;
if (\class_exists('Tx_Extbase_Property_TypeConverter_AbstractFileFolderConverter')) {
return;
}
class Tx_Extbase_Property_TypeConverter_AbstractFileFolderConverter
{
}
\class_alias('Tx_Extbase_Property_TypeConverter_AbstractFileFolderConverter', 'Tx_Extbase_Property_TypeConverter_AbstractFileFolderConverter', \false);
| RectorPHP/Rector | vendor/ssch/typo3-rector/stubs/Tx_Extbase_Property_TypeConverter_AbstractFileFolderConverter.php | PHP | mit | 364 |
;(function() {
angular.module('app.core')
.config(config);
/* @ngInject */
function config($stateProvider, $locationProvider, $urlRouterProvider) {
$stateProvider
/**
* @name landing
* @type {route}
* @description First page for incoming users, and for default routing
* for all failed routes.
*/
.state('landing', {
url: '/',
templateUrl: '/html/modules/landing/landing.html',
controller: 'LandingController',
controllerAs: 'vm'
})
/**
* @name home
* @type {route}
* @description User landing page, the main display.
*/
.state('home', {
url: '',
abstract: true,
views: {
'': {
templateUrl: 'html/modules/home/template.html'
},
'current-routes@home': {
templateUrl: 'html/modules/layout/current-routes.html',
controller: 'CurrentRoutesController',
controllerAs: 'vm'
},
'add-routes@home': {
templateUrl: 'html/modules/layout/add-routes.html',
controller: 'AddRoutesController',
controllerAs: 'vm'
}
}
})
.state('home.home', {
url: '/home',
authenticate: true,
views: {
'container@home': {
templateUrl: 'html/modules/home/welcome.html'
}
}
})
.state('home.new-route', {
url: '/new-route/:route',
authenticate: true,
views: {
'container@home': {
templateUrl: 'html/modules/routes/new-route.html',
controller: 'NewRouteController',
controllerAs: 'vm'
}
}
})
/**
* @name editRoute
* @type {route}
* @description View for editing a specific route. Provides options
* to edit or delete the route.
*/
.state('home.edit-route', {
url: '/routes/{route:.*}',
authenticate: true,
views: {
'container@home': {
templateUrl: '/html/modules/routes/edit-routes.html',
controller: 'EditRoutesController',
controllerAs: 'vm',
}
}
})
/**
* @name Docs
* @type {route}
* @description View for the project documentation
*
*/
.state('docs',{
url:'',
abstract: true,
views: {
'': {
templateUrl: '/html/modules/docs/docs.html'
},
'doc-list@docs': {
templateUrl: '/html/modules/docs/docs-list.html',
controller: 'DocsController',
controllerAs: 'vm'
}
}
})
.state('docs.docs', {
url: '/docs',
views: {
'container@docs': {
templateUrl: '/html/modules/docs/current-doc.html'
}
}
})
.state('docs.current-doc', {
url: '/docs/:doc',
views: {
'container@docs': {
templateUrl: function($stateParams) {
return '/html/modules/docs/pages/' + $stateParams.doc + '.html';
}
}
}
})
.state('home.analytics', {
url: '/analytics/{route:.*}',
authenticate: true,
views: {
'container@home': {
templateUrl: '/html/modules/analytics/analytics.html',
controller: 'AnalyticsController',
controllerAs: 'vm'
}
}
});
// default uncaught routes to landing page
$urlRouterProvider.otherwise('/');
// enable HTML5 mode
$locationProvider.html5Mode(true);
}
}).call(this);
| radiant-persimmons/mockr | src/client/app/core/config/routes.config.js | JavaScript | mit | 3,748 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
namespace CommonTypes
{
/// <summary>
/// BrokerSite hides the replication in a site making the calls transparent.
/// </summary>
[Serializable]
public class BrokerSiteFrontEnd : IBroker
{
private string siteName;
private List<BrokerPairDTO> brokersAlive;
public BrokerSiteFrontEnd(ICollection<BrokerPairDTO> brokers,string siteName)
{
this.brokersAlive = brokers.ToList();
this.siteName = siteName;
}
private void RemoveCrashedBrokers(string brokerName)
{
lock (this)
{
foreach (BrokerPairDTO pair in brokersAlive)
{
if (pair.LogicName.Equals(brokerName))
{
brokersAlive.Remove(pair);
break;
}
}
}
}
private BrokerPairDTO[] GetCopy()
{
lock (this)
{
return brokersAlive.ToArray();
}
}
public void Diffuse(Event e)
{
BrokerPairDTO[] brokers = GetCopy();
foreach (BrokerPairDTO pair in brokers)
{
try
{
(Activator.GetObject(typeof(IBroker), pair.Url) as IBroker).Diffuse(e);
}
catch (Exception)
{
RemoveCrashedBrokers(pair.LogicName);
}
}
}
public void AddRoute(Route route)
{
BrokerPairDTO[] brokers = GetCopy();
foreach (BrokerPairDTO pair in brokers)
{
try
{
(Activator.GetObject(typeof(IBroker), pair.Url) as IBroker).AddRoute(route);
}
catch (Exception e)
{
RemoveCrashedBrokers(pair.LogicName);
Console.WriteLine(e);
}
}
}
public void RemoveRoute(Route route)
{
BrokerPairDTO[] brokers = GetCopy();
foreach (BrokerPairDTO pair in brokers)
{
try
{
(Activator.GetObject(typeof(IBroker), pair.Url) as IBroker).RemoveRoute(route);
}
catch (Exception)
{
RemoveCrashedBrokers(pair.LogicName);
}
}
}
public void Subscribe(Subscription subscription)
{
BrokerPairDTO[] brokers = GetCopy();
foreach (BrokerPairDTO pair in brokers)
{
try
{
(Activator.GetObject(typeof(IBroker), pair.Url) as IBroker).Subscribe(subscription);
}
catch (Exception)
{
RemoveCrashedBrokers(pair.LogicName);
}
}
}
public void Unsubscribe(Subscription subscription)
{
BrokerPairDTO[] brokers = GetCopy();
foreach (BrokerPairDTO pair in brokers)
{
try
{
(Activator.GetObject(typeof(IBroker), pair.Url) as IBroker).Unsubscribe(subscription);
}
catch (Exception)
{
RemoveCrashedBrokers(pair.LogicName);
}
}
}
public void Sequence(Bludger bludger)
{
BrokerPairDTO[] brokers = GetCopy();
foreach (BrokerPairDTO pair in brokers)
{
try
{
(Activator.GetObject(typeof(IBroker), pair.Url) as IBroker).Sequence(bludger);
}
catch (Exception)
{
RemoveCrashedBrokers(pair.LogicName);
}
}
}
public void Bludger(Bludger bludger)
{
BrokerPairDTO[] brokers = GetCopy();
foreach (BrokerPairDTO pair in brokers)
{
try
{
(Activator.GetObject(typeof(IBroker), pair.Url) as IBroker).Bludger(bludger);
}
catch (Exception)
{
RemoveCrashedBrokers(pair.LogicName);
}
}
}
public override string ToString()
{
lock (this)
{
string res = siteName + " :" + Environment.NewLine;
foreach (BrokerPairDTO dto in brokersAlive)
{
res += dto.ToString() + Environment.NewLine;
}
return res;
}
}
}
}
| pasadinhas/dad-project | SESDAD/CommonTypes/BrokerSiteFrontEnd.cs | C# | mit | 4,968 |
import Route from '@ember/routing/route';
import { A } from '@ember/array';
import { hash } from 'rsvp';
import EmberObject from '@ember/object'
export default Route.extend({
model: function() {
return hash({
exampleModel: EmberObject.create(),
disableSubmit: false,
selectedLanguage: null,
selectOptions: A([
{label: 'French', value: 'fr'},
{label: 'English', value: 'en'},
{label: 'German', value: 'gr'}
]),
radioOptions: A([
{label: 'Ruby', value: 'ruby'},
{label: 'Javascript', value: 'js'},
{label: 'Cold Fusion', value: 'cf'}
])
});
},
actions: {
submit: function() {
window.alert('You triggered a form submit!');
},
toggleErrors: function() {
var model = this.get('currentModel').exampleModel;
if(model.get('errors')) {
model.set('errors', null);
}else{
var errors = {
first_name: A(['That first name is wrong']),
last_name: A(['That last name is silly']),
language: A(['Please choose a better language']),
isAwesome: A(['You must be awesome to submit this form']),
bestLanguage: A(['Wrong, Cold Fusion is the best language']),
essay: A(['This essay is not very good'])
};
model.set('errors', errors);
}
},
toggleSelectValue: function() {
if(this.get('currentModel.exampleModel.language')) {
this.set('currentModel.exampleModel.language', null);
}else{
this.set('currentModel.exampleModel.language', 'fr');
}
},
toggleSubmit: function() {
if(this.get('currentModel.disableSubmit')) {
this.set('currentModel.disableSubmit', false);
}else{
this.set('currentModel.disableSubmit', true);
}
},
toggleCheckbox: function() {
if(this.get('currentModel.exampleModel.isAwesome')) {
this.set('currentModel.exampleModel.isAwesome', false);
} else {
this.set('currentModel.exampleModel.isAwesome', true);
}
},
toggleRadio: function() {
if(this.get('currentModel.exampleModel.bestLanguage')) {
this.set('currentModel.exampleModel.bestLanguage', null);
}else{
this.set('currentModel.exampleModel.bestLanguage', 'js');
}
}
}
});
| Emerson/ember-form-master-2000 | tests/dummy/app/routes/application.js | JavaScript | mit | 2,343 |
import lowerCaseFirst from 'lower-case-first';
import {handles} from 'marty';
import Override from 'override-decorator';
function addHandlers(ResourceStore) {
const {constantMappings} = this;
return class ResourceStoreWithHandlers extends ResourceStore {
@Override
@handles(constantMappings.getMany.done)
getManyDone(payload) {
super.getManyDone(payload);
this.hasChanged();
}
@Override
@handles(constantMappings.getSingle.done)
getSingleDone(payload) {
super.getSingleDone(payload);
this.hasChanged();
}
@handles(
constantMappings.postSingle.done,
constantMappings.putSingle.done,
constantMappings.patchSingle.done
)
changeSingleDone(args) {
// These change actions may return the inserted or modified object, so
// update that object if possible.
if (args.result) {
this.getSingleDone(args);
}
}
};
}
function addFetch(
ResourceStore,
{
actionsKey = `${lowerCaseFirst(this.name)}Actions`
}
) {
const {methodNames, name, plural} = this;
const {getMany, getSingle} = methodNames;
const refreshMany = `refresh${plural}`;
const refreshSingle = `refresh${name}`;
return class ResourceStoreWithFetch extends ResourceStore {
getActions() {
return this.app[actionsKey];
}
[getMany](options, {refresh} = {}) {
return this.fetch({
id: `c${this.collectionKey(options)}`,
locally: () => this.localGetMany(options),
remotely: () => this.remoteGetMany(options),
refresh
});
}
[refreshMany](options) {
return this[getMany](options, {refresh: true});
}
localGetMany(options) {
return super[getMany](options);
}
remoteGetMany(options) {
return this.getActions()[getMany](options);
}
[getSingle](id, options, {refresh} = {}) {
return this.fetch({
id: `i${this.itemKey(id, options)}`,
locally: () => this.localGetSingle(id, options),
remotely: () => this.remoteGetSingle(id, options),
refresh
});
}
[refreshSingle](id, options) {
return this[getSingle](id, options, {refresh: true});
}
localGetSingle(id, options) {
return super[getSingle](id, options);
}
remoteGetSingle(id, options) {
return this.getActions()[getSingle](id, options);
}
fetch({refresh, ...options}) {
if (refresh) {
const baseLocally = options.locally;
options.locally = function refreshLocally() {
if (refresh) {
refresh = false;
return undefined;
} else {
return this::baseLocally();
}
};
}
return super.fetch(options);
}
};
}
export default function extendStore(
ResourceStore,
{
useFetch = true,
...options
}
) {
ResourceStore = this::addHandlers(ResourceStore, options);
if (useFetch) {
ResourceStore = this::addFetch(ResourceStore, options);
}
return ResourceStore;
}
| taion/flux-resource-marty | src/store.js | JavaScript | mit | 3,040 |
<?php
namespace proyecto\backendBundle\Entity;
/**
* Entidad Respuesta
* @author Javier Burguillo Sánchez
*/
class Respuesta
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $respuesta;
/**
* @var \proyecto\backendBundle\Entity\Subpregunta
*/
private $idSubpregunta;
/**
* @var \proyecto\backendBundle\Entity\Participante
*/
private $idParticipante;
/**
* Obtener id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Establecer respuesta
*
* @param string
* @return Respuesta
*/
public function setRespuesta($respuesta)
{
$this->respuesta = $respuesta;
return $this;
}
/**
* Obtener respuesta
*
* @return string
*/
public function getRespuesta()
{
return $this->respuesta;
}
/**
* Establecer idSubpregunta
*
* @param \proyecto\backendBundle\Entity\Subpregunta
* @return Respuesta
*/
public function setIdSubpregunta(\proyecto\backendBundle\Entity\Subpregunta $idSubpregunta = null)
{
$this->idSubpregunta = $idSubpregunta;
return $this;
}
/**
* Obtener idSubpregunta
*
* @return \proyecto\backendBundle\Entity\Subpregunta
*/
public function getIdSubpregunta()
{
return $this->idSubpregunta;
}
/**
* Establecer idParticipante
*
* @param \proyecto\backendBundle\Entity\Participante
* @return Respuesta
*/
public function setIdParticipante(\proyecto\backendBundle\Entity\Participante $idParticipante = null)
{
$this->idParticipante = $idParticipante;
return $this;
}
/**
* Obtener idParticipante
*
* @return \proyecto\backendBundle\Entity\Participante
*/
public function getIdParticipante()
{
return $this->idParticipante;
}
} | jburgui/proyecto2.0 | src/proyecto/backendBundle/Entity/Respuesta.php | PHP | mit | 2,024 |
$('.js-toggle-menu').click(function(e){
e.preventDefault();
$(this).siblings().toggle();
});
$('.nav--primary li').click(function(){
$(this).find('ul').toggleClass('active');
});
| sudojesse/sdb | js/main.js | JavaScript | mit | 182 |
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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 org.spongepowered.common.mixin.core.network;
import io.netty.channel.Channel;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.local.LocalAddress;
import net.minecraft.network.NetworkManager;
import org.spongepowered.api.MinecraftVersion;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.common.SpongeMinecraftVersion;
import org.spongepowered.common.bridge.network.NetworkManagerBridge;
import org.spongepowered.common.util.Constants;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import javax.annotation.Nullable;
@SuppressWarnings("rawtypes")
@Mixin(NetworkManager.class)
public abstract class NetworkManagerMixin extends SimpleChannelInboundHandler implements NetworkManagerBridge {
@Shadow private Channel channel;
@Shadow public abstract SocketAddress getRemoteAddress();
@Nullable private InetSocketAddress impl$virtualHost;
@Nullable private MinecraftVersion impl$version;
@Override
public InetSocketAddress bridge$getAddress() {
final SocketAddress remoteAddress = getRemoteAddress();
if (remoteAddress instanceof LocalAddress) { // Single player
return Constants.Networking.LOCALHOST;
}
return (InetSocketAddress) remoteAddress;
}
@Override
public InetSocketAddress bridge$getVirtualHost() {
if (this.impl$virtualHost != null) {
return this.impl$virtualHost;
}
final SocketAddress local = this.channel.localAddress();
if (local instanceof LocalAddress) {
return Constants.Networking.LOCALHOST;
}
return (InetSocketAddress) local;
}
@Override
public void bridge$setVirtualHost(final String host, final int port) {
try {
this.impl$virtualHost = new InetSocketAddress(InetAddress.getByAddress(host,
((InetSocketAddress) this.channel.localAddress()).getAddress().getAddress()), port);
} catch (UnknownHostException e) {
this.impl$virtualHost = InetSocketAddress.createUnresolved(host, port);
}
}
@Override
public MinecraftVersion bridge$getVersion() {
return this.impl$version;
}
@Override
public void bridge$setVersion(final int version) {
this.impl$version = new SpongeMinecraftVersion(String.valueOf(version), version);
}
}
| SpongePowered/SpongeCommon | src/main/java/org/spongepowered/common/mixin/core/network/NetworkManagerMixin.java | Java | mit | 3,754 |
function solve(message) {
let tagValidator = /^<message((?:\s+[a-z]+="[A-Za-z0-9 .]+"\s*?)*)>((?:.|\n)+?)<\/message>$/;
let tokens = tagValidator.exec(message);
if (!tokens) {
console.log("Invalid message format");
return;
}
let [match, attributes, body] = tokens;
let attributeValidator = /\s+([a-z]+)="([A-Za-z0-9 .]+)"\s*?/g;
let sender = '';
let recipient = '';
let attributeTokens = attributeValidator.exec(attributes);
while (attributeTokens) {
if (attributeTokens[1] === 'to') {
recipient = attributeTokens[2];
} else if (attributeTokens[1] === 'from') {
sender = attributeTokens[2];
}
attributeTokens = attributeValidator.exec(attributes);
}
if (sender === '' || recipient === '') {
console.log("Missing attributes");
return;
}
body = body.replace(/\n/g, '</p>\n <p>');
let html = `<article>\n <div>From: <span class="sender">${sender}</span></div>\n`;
html += ` <div>To: <span class="recipient">${recipient}</span></div>\n`;
html += ` <div>\n <p>${body}</p>\n </div>\n</article>`;
console.log(html);
}
solve(`<message from="John Doe" to="Alice">Not much, just chillin. How about you?</message>`);
/*
solve( `<message to="Bob" from="Alice" timestamp="1497254092">Hey man, what's up?</message>`,
`<message from="Ivan Ivanov" to="Grace">Not much, just chillin. How about you?</message>`
);
*/ | kalinmarkov/SoftUni | JS Core/JS Fundamentals/Exams/03. XML Messenger.js | JavaScript | mit | 1,486 |