code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
line_mean
float64
0.5
100
line_max
int64
1
1k
alpha_frac
float64
0.25
1
autogenerated
bool
1 class
import QUnit from 'qunit'; import { registerDeprecationHandler } from '@ember/debug'; let isRegistered = false; let deprecations = new Set(); let expectedDeprecations = new Set(); // Ignore deprecations that are not caused by our own code, and which we cannot fix easily. const ignoredDeprecations = [ // @todo remove when we can land https://github.com/emberjs/ember-render-modifiers/pull/33 here /Versions of modifier manager capabilities prior to 3\.22 have been deprecated/, /Usage of the Ember Global is deprecated./, /import .* directly from/, /Use of `assign` has been deprecated/, ]; export default function setupNoDeprecations({ beforeEach, afterEach }) { beforeEach(function () { deprecations.clear(); expectedDeprecations.clear(); if (!isRegistered) { registerDeprecationHandler((message, options, next) => { if (!ignoredDeprecations.some((regex) => message.match(regex))) { deprecations.add(message); } next(message, options); }); isRegistered = true; } }); afterEach(function (assert) { // guard in if instead of using assert.equal(), to not make assert.expect() fail if (deprecations.size > expectedDeprecations.size) { assert.ok( false, `Expected ${expectedDeprecations.size} deprecations, found: ${[...deprecations] .map((msg) => `"${msg}"`) .join(', ')}` ); } }); QUnit.assert.deprecations = function (count) { if (count === undefined) { this.ok(deprecations.size, 'Expected deprecations during test.'); } else { this.equal(deprecations.size, count, `Expected ${count} deprecation(s) during test.`); } deprecations.forEach((d) => expectedDeprecations.add(d)); }; QUnit.assert.deprecationsInclude = function (expected) { let found = [...deprecations].find((deprecation) => deprecation.includes(expected)); this.pushResult({ result: !!found, actual: deprecations, message: `expected to find \`${expected}\` deprecation. Found ${[...deprecations] .map((d) => `"${d}"`) .join(', ')}`, }); if (found) { expectedDeprecations.add(found); } }; }
kaliber5/ember-bootstrap
tests/helpers/setup-no-deprecations.js
JavaScript
mit
2,205
31.426471
97
0.639002
false
/* The MIT License (MIT) Copyright (c) 2014 Manni Wood Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.manniwood.cl4pg.v1.exceptions; public class Cl4pgConfFileException extends Cl4pgException { private static final long serialVersionUID = 1L; public Cl4pgConfFileException() { super(); } public Cl4pgConfFileException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public Cl4pgConfFileException(String message, Throwable cause) { super(message, cause); } public Cl4pgConfFileException(String message) { super(message); } public Cl4pgConfFileException(Throwable cause) { super(cause); } }
manniwood/cl4pg
src/main/java/com/manniwood/cl4pg/v1/exceptions/Cl4pgConfFileException.java
Java
mit
1,781
34.62
123
0.764177
false
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("10.TraverseDirectoryXDocument")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("10.TraverseDirectoryXDocument")] [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("0db1c3e2-162a-4e14-b304-0f69cce18d90")] // 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")]
emilti/Telerik-Academy-My-Courses
DataBases/03.Processing Xml/Processing XML/10.TraverseDirectoryXDocument/Properties/AssemblyInfo.cs
C#
mit
1,434
38.75
84
0.749825
false
package com.cosium.spring.data.jpa.entity.graph.repository.support; import com.google.common.base.MoreObjects; import org.springframework.core.ResolvableType; import org.springframework.data.jpa.repository.query.JpaEntityGraph; import static java.util.Objects.requireNonNull; /** * Wrapper class allowing to hold a {@link JpaEntityGraph} with its associated domain class. Created * on 23/11/16. * * @author Reda.Housni-Alaoui */ class EntityGraphBean { private final JpaEntityGraph jpaEntityGraph; private final Class<?> domainClass; private final ResolvableType repositoryMethodReturnType; private final boolean optional; private final boolean primary; private final boolean valid; public EntityGraphBean( JpaEntityGraph jpaEntityGraph, Class<?> domainClass, ResolvableType repositoryMethodReturnType, boolean optional, boolean primary) { this.jpaEntityGraph = requireNonNull(jpaEntityGraph); this.domainClass = requireNonNull(domainClass); this.repositoryMethodReturnType = requireNonNull(repositoryMethodReturnType); this.optional = optional; this.primary = primary; this.valid = computeValidity(); } private boolean computeValidity() { Class<?> resolvedReturnType = repositoryMethodReturnType.resolve(); if (Void.TYPE.equals(resolvedReturnType) || domainClass.isAssignableFrom(resolvedReturnType)) { return true; } for (Class genericType : repositoryMethodReturnType.resolveGenerics()) { if (domainClass.isAssignableFrom(genericType)) { return true; } } return false; } /** @return The jpa entity graph */ public JpaEntityGraph getJpaEntityGraph() { return jpaEntityGraph; } /** @return The jpa entity class */ public Class<?> getDomainClass() { return domainClass; } /** @return True if this entity graph is not mandatory */ public boolean isOptional() { return optional; } /** @return True if this EntityGraph seems valid */ public boolean isValid() { return valid; } /** * @return True if this EntityGraph is a primary one. Default EntityGraph is an example of non * primary EntityGraph. */ public boolean isPrimary() { return primary; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("jpaEntityGraph", jpaEntityGraph) .add("domainClass", domainClass) .add("repositoryMethodReturnType", repositoryMethodReturnType) .add("optional", optional) .toString(); } }
Cosium/spring-data-jpa-entity-graph
core/src/main/java/com/cosium/spring/data/jpa/entity/graph/repository/support/EntityGraphBean.java
Java
mit
2,555
28.034091
100
0.715851
false
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Page', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('title', models.CharField(unique=True, max_length=150)), ('slug', models.SlugField(unique=True, max_length=150)), ('posted', models.DateTimeField(auto_now_add=True, db_index=True)), ], options={ }, bases=(models.Model,), ), ]
vollov/i18n-django-api
page/migrations/0001_initial.py
Python
mit
723
27.92
114
0.544952
false
module.exports = function(grunt) { // Add our custom tasks. grunt.loadTasks('../../../tasks'); // Project configuration. grunt.initConfig({ mochaTest: { options: { reporter: 'spec', grep: 'tests that match grep', invert: true }, all: { src: ['*.js'] } } }); // Default task. grunt.registerTask('default', ['mochaTest']); };
quantumlicht/collarbone
node_modules/grunt-mocha-test/test/scenarios/invertOption/Gruntfile.js
JavaScript
mit
425
18.238095
47
0.491765
false
<?php namespace App\Service; class Message { public function get() { if (isset($_SESSION['message'])) { $array = explode(',', $_SESSION['message']); unset($_SESSION['message']); return $array; } return ''; } public function set($message, $type = null) { $_SESSION['message'] = implode(',', [$message, $type]); } }
QA-Games/QA-tools
app/Service/Message.php
PHP
mit
421
17.347826
66
0.470309
false
package mqttpubsub import ( "encoding/json" "fmt" "sync" "time" log "github.com/Sirupsen/logrus" "github.com/brocaar/loraserver/api/gw" "github.com/brocaar/lorawan" "github.com/eclipse/paho.mqtt.golang" ) // Backend implements a MQTT pub-sub backend. type Backend struct { conn mqtt.Client txPacketChan chan gw.TXPacketBytes gateways map[lorawan.EUI64]struct{} mutex sync.RWMutex } // NewBackend creates a new Backend. func NewBackend(server, username, password string) (*Backend, error) { b := Backend{ txPacketChan: make(chan gw.TXPacketBytes), gateways: make(map[lorawan.EUI64]struct{}), } opts := mqtt.NewClientOptions() opts.AddBroker(server) opts.SetUsername(username) opts.SetPassword(password) opts.SetOnConnectHandler(b.onConnected) opts.SetConnectionLostHandler(b.onConnectionLost) log.WithField("server", server).Info("backend: connecting to mqtt broker") b.conn = mqtt.NewClient(opts) if token := b.conn.Connect(); token.Wait() && token.Error() != nil { return nil, token.Error() } return &b, nil } // Close closes the backend. func (b *Backend) Close() { b.conn.Disconnect(250) // wait 250 milisec to complete pending actions } // TXPacketChan returns the TXPacketBytes channel. func (b *Backend) TXPacketChan() chan gw.TXPacketBytes { return b.txPacketChan } // SubscribeGatewayTX subscribes the backend to the gateway TXPacketBytes // topic (packets the gateway needs to transmit). func (b *Backend) SubscribeGatewayTX(mac lorawan.EUI64) error { defer b.mutex.Unlock() b.mutex.Lock() topic := fmt.Sprintf("gateway/%s/tx", mac.String()) log.WithField("topic", topic).Info("backend: subscribing to topic") if token := b.conn.Subscribe(topic, 0, b.txPacketHandler); token.Wait() && token.Error() != nil { return token.Error() } b.gateways[mac] = struct{}{} return nil } // UnSubscribeGatewayTX unsubscribes the backend from the gateway TXPacketBytes // topic. func (b *Backend) UnSubscribeGatewayTX(mac lorawan.EUI64) error { defer b.mutex.Unlock() b.mutex.Lock() topic := fmt.Sprintf("gateway/%s/tx", mac.String()) log.WithField("topic", topic).Info("backend: unsubscribing from topic") if token := b.conn.Unsubscribe(topic); token.Wait() && token.Error() != nil { return token.Error() } delete(b.gateways, mac) return nil } // PublishGatewayRX publishes a RX packet to the MQTT broker. func (b *Backend) PublishGatewayRX(mac lorawan.EUI64, rxPacket gw.RXPacketBytes) error { topic := fmt.Sprintf("gateway/%s/rx", mac.String()) return b.publish(topic, rxPacket) } // PublishGatewayStats publishes a GatewayStatsPacket to the MQTT broker. func (b *Backend) PublishGatewayStats(mac lorawan.EUI64, stats gw.GatewayStatsPacket) error { topic := fmt.Sprintf("gateway/%s/stats", mac.String()) return b.publish(topic, stats) } func (b *Backend) publish(topic string, v interface{}) error { bytes, err := json.Marshal(v) if err != nil { return err } log.WithField("topic", topic).Info("backend: publishing packet") if token := b.conn.Publish(topic, 0, false, bytes); token.Wait() && token.Error() != nil { return token.Error() } return nil } func (b *Backend) txPacketHandler(c mqtt.Client, msg mqtt.Message) { log.WithField("topic", msg.Topic()).Info("backend: packet received") var txPacket gw.TXPacketBytes if err := json.Unmarshal(msg.Payload(), &txPacket); err != nil { log.Errorf("backend: decode tx packet error: %s", err) return } b.txPacketChan <- txPacket } func (b *Backend) onConnected(c mqtt.Client) { defer b.mutex.RUnlock() b.mutex.RLock() log.Info("backend: connected to mqtt broker") if len(b.gateways) > 0 { for { log.WithField("topic_count", len(b.gateways)).Info("backend: re-registering to gateway topics") topics := make(map[string]byte) for k := range b.gateways { topics[fmt.Sprintf("gateway/%s/tx", k)] = 0 } if token := b.conn.SubscribeMultiple(topics, b.txPacketHandler); token.Wait() && token.Error() != nil { log.WithField("topic_count", len(topics)).Errorf("backend: subscribe multiple failed: %s", token.Error()) time.Sleep(time.Second) continue } return } } } func (b *Backend) onConnectionLost(c mqtt.Client, reason error) { log.Errorf("backend: mqtt connection error: %s", reason) }
kumara0093/loraserver
backend/mqttpubsub/backend.go
GO
mit
4,289
28.784722
109
0.70879
false
package stage2; public class DecafError { int numErrors; DecafError(){ } public static String errorPos(Position p){ return "(L: " + p.startLine + ", Col: " + p.startCol + ") -- (L: " + p.endLine + ", Col: " + p.endCol + ")"; } public void error(String s, Position p) { System.out.println("Error found at location "+ errorPos(p) + ":\n"+s); } public boolean haveErrors() { return (numErrors>0); } }
bigfatnoob/Decaf
src/stage2/DecafError.java
Java
mit
471
15.821429
48
0.543524
false
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>../plugins/plugins_2d/bar/bar.vlib.js</title> <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css"> <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css"> <link rel="stylesheet" href="../assets/css/main.css" id="site_styles"> <link rel="shortcut icon" type="image/png" href="../assets/favicon.png"> <script src="http://yui.yahooapis.com/combo?3.9.1/build/yui/yui-min.js"></script> </head> <body class="yui3-skin-sam"> <div id="doc"> <div id="hd" class="yui3-g header"> <div class="yui3-u-3-4"> <h1><img src="../assets/css/logo.png" title=""></h1> </div> <div class="yui3-u-1-4 version"> <em>API Docs for: </em> </div> </div> <div id="bd" class="yui3-g"> <div class="yui3-u-1-4"> <div id="docs-sidebar" class="sidebar apidocs"> <div id="api-list"> <h2 class="off-left">APIs</h2> <div id="api-tabview" class="tabview"> <ul class="tabs"> <li><a href="#api-classes">Classes</a></li> <li><a href="#api-modules">Modules</a></li> </ul> <div id="api-tabview-filter"> <input type="search" id="api-filter" placeholder="Type to filter APIs"> </div> <div id="api-tabview-panel"> <ul id="api-classes" class="apis classes"> <li><a href="../classes/AbstractPlugin.html">AbstractPlugin</a></li> <li><a href="../classes/Config.html">Config</a></li> <li><a href="../classes/Controls.html">Controls</a></li> <li><a href="../classes/Plot.html">Plot</a></li> <li><a href="../classes/Plugin 3D.html">Plugin 3D</a></li> <li><a href="../classes/Plugin Axes.html">Plugin Axes</a></li> <li><a href="../classes/Plugin BasicMaterial.html">Plugin BasicMaterial</a></li> <li><a href="../classes/Plugin CameraControl.html">Plugin CameraControl</a></li> <li><a href="../classes/Plugin Color.html">Plugin Color</a></li> <li><a href="../classes/Plugin Dataset.html">Plugin Dataset</a></li> <li><a href="../classes/Plugin File.html">Plugin File</a></li> <li><a href="../classes/Plugin Function.html">Plugin Function</a></li> <li><a href="../classes/Plugin Heatmap.html">Plugin Heatmap</a></li> <li><a href="../classes/Plugin Light.html">Plugin Light</a></li> <li><a href="../classes/Plugin LinePlot.html">Plugin LinePlot</a></li> <li><a href="../classes/Plugin Plane.html">Plugin Plane</a></li> <li><a href="../classes/Plugin ScatterPlot.html">Plugin ScatterPlot</a></li> <li><a href="../classes/Plugin SurfacePlot.html">Plugin SurfacePlot</a></li> <li><a href="../classes/Plugin WireframeMaterial.html">Plugin WireframeMaterial</a></li> <li><a href="../classes/SceneGraph.html">SceneGraph</a></li> <li><a href="../classes/Templates.html">Templates</a></li> <li><a href="../classes/Toolbox.html">Toolbox</a></li> <li><a href="../classes/UTILS.html">UTILS</a></li> <li><a href="../classes/VLib.html">VLib</a></li> <li><a href="../classes/VMediator.html">VMediator</a></li> </ul> <ul id="api-modules" class="apis modules"> <li><a href="../modules/Controls.html">Controls</a></li> <li><a href="../modules/main.html">main</a></li> <li><a href="../modules/Plot.html">Plot</a></li> <li><a href="../modules/SceneGraph.html">SceneGraph</a></li> <li><a href="../modules/Templates.html">Templates</a></li> <li><a href="../modules/Toolbox.html">Toolbox</a></li> <li><a href="../modules/VLib.html">VLib</a></li> </ul> </div> </div> </div> </div> </div> <div class="yui3-u-3-4"> <div id="api-options"> Show: <label for="api-show-inherited"> <input type="checkbox" id="api-show-inherited" checked> Inherited </label> <label for="api-show-protected"> <input type="checkbox" id="api-show-protected"> Protected </label> <label for="api-show-private"> <input type="checkbox" id="api-show-private"> Private </label> <label for="api-show-deprecated"> <input type="checkbox" id="api-show-deprecated"> Deprecated </label> </div> <div class="apidocs"> <div id="docs-main"> <div class="content"> <h1 class="file-heading">File: ../plugins/plugins_2d/bar/bar.vlib.js</h1> <div class="file"> <pre class="code prettyprint linenums"> define([&#x27;require&#x27;,&#x27;config&#x27;],function(require,Config) { var plugin = (function() { /** ********************************** */ /** PUBLIC VARIABLES * */ /** ********************************** */ this.context = Config.PLUGINTYPE.CONTEXT_2D; this.type = Config.PLUGINTYPE.LINETYPE; this.name = &#x27;bar&#x27;; /** path to plugin-template file * */ this.accepts = { predecessors : [ Config.PLUGINTYPE.DATA ], successors : [ ] } this.icon = Config.absPlugins + &#x27;/plugins_2d/bar/icon.png&#x27;; this.description = &#x27;Requires: [ &#x27;+this.accepts.predecessors.join(&#x27;, &#x27;)+&#x27; ] Accepts: [ &#x27;+this.accepts.successors.join(&#x27;, &#x27;)+&#x27; ]&#x27;; /** ********************************** */ /** PUBLIC METHODS * */ /** ********************************** */ /** /***/ this.exec = function(config) { console.log(&quot;[ bar ] \t\t EXEC&quot;); if(config == &#x27;&#x27; || config === undefined){ config = {area:false,bar:true}; } return { pType : this.type, response : { type : config } }; } }); return plugin; }); </pre> </div> </div> </div> </div> </div> </div> </div> <script src="../assets/vendor/prettify/prettify-min.js"></script> <script>prettyPrint();</script> <script src="../assets/js/yui-prettify.js"></script> <script src="../assets/../api.js"></script> <script src="../assets/js/api-filter.js"></script> <script src="../assets/js/api-list.js"></script> <script src="../assets/js/api-search.js"></script> <script src="../assets/js/apidocs.js"></script> </body> </html>
ndyGit/vPlot
wp-vlib/js/VLib/docu/out/files/.._plugins_plugins_2d_bar_bar.vlib.js.html
HTML
mit
7,249
33.032864
180
0.489585
false
<!DOCTYPE html> <!DOCTYPE html> <html lang=sl> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Kje lahko najdem datoteke katerih varnostno kopijo želim ustvariti?</title> <script type="text/javascript" src="jquery.js"></script><script type="text/javascript" src="jquery.syntax.js"></script><script type="text/javascript" src="yelp.js"></script><link rel="shortcut icon" href="https://www.ubuntu.si/favicon.ico"> <link rel="stylesheet" type="text/css" href="../vodnik_1404.css"> </head> <body id="home"><div id="wrapper" class="hfeed"> <div id="header"> <div id="branding"> <div id="blog-title"><span><a rel="home" title="Ubuntu Slovenija | Uradna spletna stran slovenske skupnosti Linux distribucije Ubuntu" href="//www.ubuntu.si">Ubuntu Slovenija | Uradna spletna stran slovenske skupnosti Linux distribucije Ubuntu</a></span></div> <h1 id="blog-description"></h1> </div> <div id="access"><div id="loco-header-menu"><ul id="primary-header-menu"><li class="widget-container widget_nav_menu" id="nav_menu-3"><div class="menu-glavni-meni-container"><ul class="menu" id="menu-glavni-meni"> <li id="menu-item-15" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-15"><a href="//www.ubuntu.si">Domov</a></li> <li id="menu-item-2776" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-2776"><a href="//www.ubuntu.si/category/novice/">Novice</a></li> <li id="menu-item-16" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-16"><a href="//www.ubuntu.si/forum/">Forum</a></li> <li id="menu-item-19" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-19"><a href="//www.ubuntu.si/kaj-je-ubuntu/">Kaj je Ubuntu?</a></li> <li id="menu-item-20" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-20"><a href="//www.ubuntu.si/pogosta_vprasanja/">Pogosta vprašanja</a></li> <li id="menu-item-17" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-17"><a href="//www.ubuntu.si/skupnost/">Skupnost</a></li> <li id="menu-item-18" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-18"><a href="//www.ubuntu.si/povezave/">Povezave</a></li> </ul></div></li></ul></div></div> </div> <div id="main"><div id="cwt-content" class="clearfix content-area"><div id="page"> <div class="trails" role="navigation"><div class="trail"> <span style="color: #333">Ubuntu 16.10</span> » <a class="trail" href="index.html" title="Namizni vodnik Ubuntu"><span class="media"><span class="media media-image"><img src="figures/ubuntu-logo.png" height="16" width="16" class="media media-inline" alt="Pomoč"></span></span> Namizni vodnik Ubuntu</a> » <a class="trail" href="files.html" title="Datoteke, mape in iskanje">Datoteke</a> › <a class="trail" href="files.html#backup" title="Ustvarjanje varnostnih kopij">Ustvarjanje varnostnih kopij</a> » </div></div> <div id="content"> <div class="hgroup"><h1 class="title"><span class="title">Kje lahko najdem datoteke katerih varnostno kopijo želim ustvariti?</span></h1></div> <div class="region"> <div class="contents"> <p class="p">Spodaj so izpisana najbolj pogosta mesta pomembnih datotek in nastavitev, ki si jih morda želite varnostno kopirati.</p> <div class="list"><div class="inner"><div class="region"><ul class="list"> <li class="list"> <p class="p">Osebne datoteke (dokumenti, glasba, fotografije in videoposnetki)</p> <p class="p">Te so ponavadi shranjene v vaši domači mapi (<span class="file">/home/vaše_ime</span>). Lahko so v podmapah kot je Namizje, Dokumenti, Slike, Glasba in Videi.</p> <p class="p">Če je na vašem mediju varnostne kopije dovolj prostora (na primer če je to zunanji trdi disk), razmislite o ustvarjanju varnostne kopije celotne Domače mape. Koliko prostora zavzema Domača mapa lahko ugotovite z orodjem <span class="app">Preučevalnik porabe diska</span>.</p> </li> <li class="list"> <p class="p">Skrite datoteke</p> <p class="p">Katerokoli ime datoteke ali mape, ki se začne s piko (.), je privzeto skrito. Za ogled skritih datotek kliknite <span class="guiseq"><span class="gui">Pogled</span> ▸ <span class="gui">Pokaži skrite datoteke</span></span> ali pritisnite <span class="keyseq"><span class="key"><kbd>Ctrl</kbd></span>+<span class="key"><kbd>H</kbd></span></span>.</p> </li> <li class="list"> <p class="p">Osebne nastavitve (možnosti namizja, teme in nastavitve programov)</p> <p class="p">Večina programov shrani svoje nastavitve v skrite mape v vaši Domači mapi (glejte zgoraj za podrobnosti o skritih datotekah).</p> <p class="p">Večina vaših nastavitev programov je shranjena v skritih mapah <span class="file">.config</span>, <span class="file">.gconf</span>, <span class="file">.gnome2</span> in <span class="file">.local</span> v vaši Domači mapi.</p> </li> <li class="list"> <p class="p">Sistemske nastavitve</p> <p class="p">Nastavitve pomembnih delov sistema niso shranjene v Domači mapi. Obstajajo številna mesta, kjer so lahko shranjena, vendar jih je večina shranjena v mapi <span class="file">/etc</span>. V splošnem vam varnostne kopije teh datotek na domačem računalniku ni treba ustvariti. Če imate strežnik, je pametno ustvariti varnostno kopijo datotek za storitve, ki jih strežnik poganja.</p> </li> </ul></div></div></div> </div> <div class="sect sect-links" role="navigation"> <div class="hgroup"></div> <div class="contents"><div class="links guidelinks"><div class="inner"> <div class="title"><h2><span class="title">Več podrobnosti</span></h2></div> <div class="region"><ul><li class="links "><a href="files.html#backup" title="Ustvarjanje varnostnih kopij">Ustvarjanje varnostnih kopij</a></li></ul></div> </div></div></div> </div> </div> <div class="clear"></div> </div> </div></div></div> <div id="footer"> <img src="https://piwik-ubuntusi.rhcloud.com/piwik.php?idsite=1&amp;rec=1" style="border:0" alt=""><div id="siteinfo"><p>Material v tem dokumentu je na voljo pod prosto licenco. To je prevod dokumentacije Ubuntu, ki jo je sestavila <a href="https://wiki.ubuntu.com/DocumentationTeam">Ubuntu dokumentacijska ekipa za Ubuntu</a>. V slovenščino jo je prevedla skupina <a href="https://wiki.lugos.si/slovenjenje:ubuntu">Ubuntu prevajalcev</a>. Za poročanje napak v prevodih v tej dokumentaciji ali Ubuntuju pošljite sporočilo na <a href="mailto:ubuntu-l10n-slv@lists.ubuntu.com?subject=Prijava%20napak%20v%20prevodih">dopisni seznam</a>.</p></div> </div> </div></body> </html>
ubuntu-si/ubuntu.si
vodnik/16.10/backup-thinkabout.html
HTML
mit
6,504
91.185714
643
0.723539
false
"use strict"; define("ace/mode/asciidoc_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function (require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var AsciidocHighlightRules = function AsciidocHighlightRules() { var identifierRe = "[a-zA-Z\xA1-\uFFFF]+\\b"; this.$rules = { "start": [{ token: "empty", regex: /$/ }, { token: "literal", regex: /^\.{4,}\s*$/, next: "listingBlock" }, { token: "literal", regex: /^-{4,}\s*$/, next: "literalBlock" }, { token: "string", regex: /^\+{4,}\s*$/, next: "passthroughBlock" }, { token: "keyword", regex: /^={4,}\s*$/ }, { token: "text", regex: /^\s*$/ }, { token: "empty", regex: "", next: "dissallowDelimitedBlock" }], "dissallowDelimitedBlock": [{ include: "paragraphEnd" }, { token: "comment", regex: '^//.+$' }, { token: "keyword", regex: "^(?:NOTE|TIP|IMPORTANT|WARNING|CAUTION):" }, { include: "listStart" }, { token: "literal", regex: /^\s+.+$/, next: "indentedBlock" }, { token: "empty", regex: "", next: "text" }], "paragraphEnd": [{ token: "doc.comment", regex: /^\/{4,}\s*$/, next: "commentBlock" }, { token: "tableBlock", regex: /^\s*[|!]=+\s*$/, next: "tableBlock" }, { token: "keyword", regex: /^(?:--|''')\s*$/, next: "start" }, { token: "option", regex: /^\[.*\]\s*$/, next: "start" }, { token: "pageBreak", regex: /^>{3,}$/, next: "start" }, { token: "literal", regex: /^\.{4,}\s*$/, next: "listingBlock" }, { token: "titleUnderline", regex: /^(?:={2,}|-{2,}|~{2,}|\^{2,}|\+{2,})\s*$/, next: "start" }, { token: "singleLineTitle", regex: /^={1,5}\s+\S.*$/, next: "start" }, { token: "otherBlock", regex: /^(?:\*{2,}|_{2,})\s*$/, next: "start" }, { token: "optionalTitle", regex: /^\.[^.\s].+$/, next: "start" }], "listStart": [{ token: "keyword", regex: /^\s*(?:\d+\.|[a-zA-Z]\.|[ixvmIXVM]+\)|\*{1,5}|-|\.{1,5})\s/, next: "listText" }, { token: "meta.tag", regex: /^.+(?::{2,4}|;;)(?: |$)/, next: "listText" }, { token: "support.function.list.callout", regex: /^(?:<\d+>|\d+>|>) /, next: "text" }, { token: "keyword", regex: /^\+\s*$/, next: "start" }], "text": [{ token: ["link", "variable.language"], regex: /((?:https?:\/\/|ftp:\/\/|file:\/\/|mailto:|callto:)[^\s\[]+)(\[.*?\])/ }, { token: "link", regex: /(?:https?:\/\/|ftp:\/\/|file:\/\/|mailto:|callto:)[^\s\[]+/ }, { token: "link", regex: /\b[\w\.\/\-]+@[\w\.\/\-]+\b/ }, { include: "macros" }, { include: "paragraphEnd" }, { token: "literal", regex: /\+{3,}/, next: "smallPassthrough" }, { token: "escape", regex: /\((?:C|TM|R)\)|\.{3}|->|<-|=>|<=|&#(?:\d+|x[a-fA-F\d]+);|(?: |^)--(?=\s+\S)/ }, { token: "escape", regex: /\\[_*'`+#]|\\{2}[_*'`+#]{2}/ }, { token: "keyword", regex: /\s\+$/ }, { token: "text", regex: identifierRe }, { token: ["keyword", "string", "keyword"], regex: /(<<[\w\d\-$]+,)(.*?)(>>|$)/ }, { token: "keyword", regex: /<<[\w\d\-$]+,?|>>/ }, { token: "constant.character", regex: /\({2,3}.*?\){2,3}/ }, { token: "keyword", regex: /\[\[.+?\]\]/ }, { token: "support", regex: /^\[{3}[\w\d =\-]+\]{3}/ }, { include: "quotes" }, { token: "empty", regex: /^\s*$/, next: "start" }], "listText": [{ include: "listStart" }, { include: "text" }], "indentedBlock": [{ token: "literal", regex: /^[\s\w].+$/, next: "indentedBlock" }, { token: "literal", regex: "", next: "start" }], "listingBlock": [{ token: "literal", regex: /^\.{4,}\s*$/, next: "dissallowDelimitedBlock" }, { token: "constant.numeric", regex: '<\\d+>' }, { token: "literal", regex: '[^<]+' }, { token: "literal", regex: '<' }], "literalBlock": [{ token: "literal", regex: /^-{4,}\s*$/, next: "dissallowDelimitedBlock" }, { token: "constant.numeric", regex: '<\\d+>' }, { token: "literal", regex: '[^<]+' }, { token: "literal", regex: '<' }], "passthroughBlock": [{ token: "literal", regex: /^\+{4,}\s*$/, next: "dissallowDelimitedBlock" }, { token: "literal", regex: identifierRe + "|\\d+" }, { include: "macros" }, { token: "literal", regex: "." }], "smallPassthrough": [{ token: "literal", regex: /[+]{3,}/, next: "dissallowDelimitedBlock" }, { token: "literal", regex: /^\s*$/, next: "dissallowDelimitedBlock" }, { token: "literal", regex: identifierRe + "|\\d+" }, { include: "macros" }], "commentBlock": [{ token: "doc.comment", regex: /^\/{4,}\s*$/, next: "dissallowDelimitedBlock" }, { token: "doc.comment", regex: '^.*$' }], "tableBlock": [{ token: "tableBlock", regex: /^\s*\|={3,}\s*$/, next: "dissallowDelimitedBlock" }, { token: "tableBlock", regex: /^\s*!={3,}\s*$/, next: "innerTableBlock" }, { token: "tableBlock", regex: /\|/ }, { include: "text", noEscape: true }], "innerTableBlock": [{ token: "tableBlock", regex: /^\s*!={3,}\s*$/, next: "tableBlock" }, { token: "tableBlock", regex: /^\s*|={3,}\s*$/, next: "dissallowDelimitedBlock" }, { token: "tableBlock", regex: /\!/ }], "macros": [{ token: "macro", regex: /{[\w\-$]+}/ }, { token: ["text", "string", "text", "constant.character", "text"], regex: /({)([\w\-$]+)(:)?(.+)?(})/ }, { token: ["text", "markup.list.macro", "keyword", "string"], regex: /(\w+)(footnote(?:ref)?::?)([^\s\[]+)?(\[.*?\])?/ }, { token: ["markup.list.macro", "keyword", "string"], regex: /([a-zA-Z\-][\w\.\/\-]*::?)([^\s\[]+)(\[.*?\])?/ }, { token: ["markup.list.macro", "keyword"], regex: /([a-zA-Z\-][\w\.\/\-]+::?)(\[.*?\])/ }, { token: "keyword", regex: /^:.+?:(?= |$)/ }], "quotes": [{ token: "string.italic", regex: /__[^_\s].*?__/ }, { token: "string.italic", regex: quoteRule("_") }, { token: "keyword.bold", regex: /\*\*[^*\s].*?\*\*/ }, { token: "keyword.bold", regex: quoteRule("\\*") }, { token: "literal", regex: quoteRule("\\+") }, { token: "literal", regex: /\+\+[^+\s].*?\+\+/ }, { token: "literal", regex: /\$\$.+?\$\$/ }, { token: "literal", regex: quoteRule("`") }, { token: "keyword", regex: quoteRule("^") }, { token: "keyword", regex: quoteRule("~") }, { token: "keyword", regex: /##?/ }, { token: "keyword", regex: /(?:\B|^)``|\b''/ }] }; function quoteRule(ch) { var prefix = /\w/.test(ch) ? "\\b" : "(?:\\B|^)"; return prefix + ch + "[^" + ch + "].*?" + ch + "(?![\\w*])"; } var tokenMap = { macro: "constant.character", tableBlock: "doc.comment", titleUnderline: "markup.heading", singleLineTitle: "markup.heading", pageBreak: "string", option: "string.regexp", otherBlock: "markup.list", literal: "support.function", optionalTitle: "constant.numeric", escape: "constant.language.escape", link: "markup.underline.list" }; for (var state in this.$rules) { var stateRules = this.$rules[state]; for (var i = stateRules.length; i--;) { var rule = stateRules[i]; if (rule.include || typeof rule == "string") { var args = [i, 1].concat(this.$rules[rule.include || rule]); if (rule.noEscape) { args = args.filter(function (x) { return !x.next; }); } stateRules.splice.apply(stateRules, args); } else if (rule.token in tokenMap) { rule.token = tokenMap[rule.token]; } } } }; oop.inherits(AsciidocHighlightRules, TextHighlightRules); exports.AsciidocHighlightRules = AsciidocHighlightRules; }); define("ace/mode/folding/asciidoc", ["require", "exports", "module", "ace/lib/oop", "ace/mode/folding/fold_mode", "ace/range"], function (require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function () {}; oop.inherits(FoldMode, BaseFoldMode); (function () { this.foldingStartMarker = /^(?:\|={10,}|[\.\/=\-~^+]{4,}\s*$|={1,5} )/; this.singleLineHeadingRe = /^={1,5}(?=\s+\S)/; this.getFoldWidget = function (session, foldStyle, row) { var line = session.getLine(row); if (!this.foldingStartMarker.test(line)) return ""; if (line[0] == "=") { if (this.singleLineHeadingRe.test(line)) return "start"; if (session.getLine(row - 1).length != session.getLine(row).length) return ""; return "start"; } if (session.bgTokenizer.getState(row) == "dissallowDelimitedBlock") return "end"; return "start"; }; this.getFoldWidgetRange = function (session, foldStyle, row) { var line = session.getLine(row); var startColumn = line.length; var maxRow = session.getLength(); var startRow = row; var endRow = row; if (!line.match(this.foldingStartMarker)) return; var token; function getTokenType(row) { token = session.getTokens(row)[0]; return token && token.type; } var levels = ["=", "-", "~", "^", "+"]; var heading = "markup.heading"; var singleLineHeadingRe = this.singleLineHeadingRe; function getLevel() { var match = token.value.match(singleLineHeadingRe); if (match) return match[0].length; var level = levels.indexOf(token.value[0]) + 1; if (level == 1) { if (session.getLine(row - 1).length != session.getLine(row).length) return Infinity; } return level; } if (getTokenType(row) == heading) { var startHeadingLevel = getLevel(); while (++row < maxRow) { if (getTokenType(row) != heading) continue; var level = getLevel(); if (level <= startHeadingLevel) break; } var isSingleLineHeading = token && token.value.match(this.singleLineHeadingRe); endRow = isSingleLineHeading ? row - 1 : row - 2; if (endRow > startRow) { while (endRow > startRow && (!getTokenType(endRow) || token.value[0] == "[")) { endRow--; } } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } } else { var state = session.bgTokenizer.getState(row); if (state == "dissallowDelimitedBlock") { while (row-- > 0) { if (session.bgTokenizer.getState(row).lastIndexOf("Block") == -1) break; } endRow = row + 1; if (endRow < startRow) { var endColumn = session.getLine(row).length; return new Range(endRow, 5, startRow, startColumn - 5); } } else { while (++row < maxRow) { if (session.bgTokenizer.getState(row) == "dissallowDelimitedBlock") break; } endRow = row; if (endRow > startRow) { var endColumn = session.getLine(row).length; return new Range(startRow, 5, endRow, endColumn - 5); } } } }; }).call(FoldMode.prototype); }); define("ace/mode/asciidoc", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text", "ace/mode/asciidoc_highlight_rules", "ace/mode/folding/asciidoc"], function (require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var AsciidocHighlightRules = require("./asciidoc_highlight_rules").AsciidocHighlightRules; var AsciidocFoldMode = require("./folding/asciidoc").FoldMode; var Mode = function Mode() { this.HighlightRules = AsciidocHighlightRules; this.foldingRules = new AsciidocFoldMode(); }; oop.inherits(Mode, TextMode); (function () { this.type = "text"; this.getNextLineIndent = function (state, line, tab) { if (state == "listblock") { var match = /^((?:.+)?)([-+*][ ]+)/.exec(line); if (match) { return new Array(match[1].length + 1).join(" ") + match[2]; } else { return ""; } } else { return this.$getIndent(line); } }; this.$id = "ace/mode/asciidoc"; }).call(Mode.prototype); exports.Mode = Mode; });
IonicaBizau/arc-assembler
clients/ace-builds/src/mode-asciidoc.js
JavaScript
mit
13,207
59.310502
717
0.492088
false
/* * * Copyright (c) 2013 - 2014 INT - National Institute of Technology & COPPE - Alberto Luiz Coimbra Institute - Graduate School and Research in Engineering. * See the file license.txt for copyright permission. * */ package cargaDoSistema; import modelo.TipoUsuario; import modelo.Usuario; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import service.TipoUsuarioAppService; import service.UsuarioAppService; import service.controleTransacao.FabricaDeAppService; import service.exception.AplicacaoException; import util.JPAUtil; /** * Classe responsável pela inclusão de Tipos de Usuário e de Usuário. * É usada na carga do sistema e deve ser a primeira a ser executada. * Está criando um usuário para cada tipo. (dma) * * @author marques * */ public class CargaUsuario { // Services public TipoUsuarioAppService tipoUsuarioService; public UsuarioAppService usuarioService; @BeforeClass public void setupClass(){ try { tipoUsuarioService = FabricaDeAppService.getAppService(TipoUsuarioAppService.class); usuarioService = FabricaDeAppService.getAppService(UsuarioAppService.class); } catch (Exception e) { e.printStackTrace(); } } @Test public void incluirTiposDeUsuario() { TipoUsuario tipoUsuarioAdmin = new TipoUsuario(); TipoUsuario tipoUsuarioAluno = new TipoUsuario(); TipoUsuario tipoUsuarioGestor = new TipoUsuario(); TipoUsuario tipoUsuarioEngenheiro = new TipoUsuario(); tipoUsuarioAdmin.setTipoUsuario(TipoUsuario.ADMINISTRADOR); tipoUsuarioAdmin.setDescricao("O usuário ADMINISTRADOR pode realizar qualquer operação no Sistema."); tipoUsuarioAluno.setTipoUsuario(TipoUsuario.ALUNO); tipoUsuarioAluno.setDescricao("O usuário ALUNO pode realizar apenas consultas e impressão de relatórios nas telas " + "relativas ao Horizonte de Planejamento (HP,Periodo PMP, Periodo PAP) e não acessa " + "Administração e Eng. Conhecimento"); tipoUsuarioGestor.setTipoUsuario(TipoUsuario.GESTOR); tipoUsuarioGestor.setDescricao("O usuário GESTOR pode realizar qualquer operação no Sistema, porém não possui acesso" + "as áreas de Administração e Engenharia de Conhecimento."); tipoUsuarioEngenheiro.setTipoUsuario(TipoUsuario.ENGENHEIRO_DE_CONHECIMENTO); tipoUsuarioEngenheiro.setDescricao("O usuário ENGENHEIRO pode realizar a parte de Logica Fuzzy (Engenharia de Conhecimento)" + "no Sistema. Porém, não possui acesso a área Administrativa."); tipoUsuarioService.inclui(tipoUsuarioAdmin); tipoUsuarioService.inclui(tipoUsuarioAluno); tipoUsuarioService.inclui(tipoUsuarioGestor); tipoUsuarioService.inclui(tipoUsuarioEngenheiro); Usuario usuarioAdmin = new Usuario(); Usuario usuarioAluno = new Usuario(); Usuario usuarioGestor = new Usuario(); Usuario usuarioEngenheiro = new Usuario(); usuarioAdmin.setNome("Administrador"); usuarioAdmin.setLogin("dgep"); usuarioAdmin.setSenha("admgesplan2@@8"); usuarioAdmin.setTipoUsuario(tipoUsuarioAdmin); usuarioAluno.setNome("Alberto da Silva"); usuarioAluno.setLogin("alberto"); usuarioAluno.setSenha("alberto"); usuarioAluno.setTipoUsuario(tipoUsuarioAluno); usuarioEngenheiro.setNome("Bernadete da Silva"); usuarioEngenheiro.setLogin("bernadete"); usuarioEngenheiro.setSenha("bernadete"); usuarioEngenheiro.setTipoUsuario(tipoUsuarioEngenheiro); usuarioGestor.setNome("Carlos da Silva"); usuarioGestor.setLogin("carlos"); usuarioGestor.setSenha("carlos"); usuarioGestor.setTipoUsuario(tipoUsuarioGestor); try { usuarioService.inclui(usuarioAdmin, usuarioAdmin.getSenha()); usuarioService.inclui(usuarioEngenheiro, usuarioEngenheiro.getSenha()); usuarioService.inclui(usuarioGestor, usuarioGestor.getSenha()); usuarioService.inclui(usuarioAluno, usuarioAluno.getSenha()); } catch (AplicacaoException e) { //e.printStackTrace(); System.out.println("Erro na inclusao do usuario: "+ e.getMessage()); } } }
dayse/gesplan
test/cargaDoSistema/CargaUsuario.java
Java
mit
4,187
33.786325
128
0.738715
false
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
29.733333
75
0.711183
false
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.4.2_05) on Thu Sep 30 22:16:01 GMT+01:00 2004 --> <TITLE> org.springframework.web.multipart.support Class Hierarchy (Spring Framework) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="org.springframework.web.multipart.support Class Hierarchy (Spring Framework)"; } </SCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/springframework/web/multipart/cos/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/springframework/web/servlet/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> Hierarchy For Package org.springframework.web.multipart.support </H2> </CENTER> <DL> <DT><B>Package Hierarchies:</B><DD><A HREF="../../../../../overview-tree.html">All Packages</A></DL> <HR> <H2> Class Hierarchy </H2> <UL> <LI TYPE="circle">class java.lang.Object<UL> <LI TYPE="circle">class org.springframework.web.filter.<A HREF="../../../../../org/springframework/web/filter/GenericFilterBean.html" title="class in org.springframework.web.filter"><B>GenericFilterBean</B></A> (implements javax.servlet.Filter) <UL> <LI TYPE="circle">class org.springframework.web.filter.<A HREF="../../../../../org/springframework/web/filter/OncePerRequestFilter.html" title="class in org.springframework.web.filter"><B>OncePerRequestFilter</B></A><UL> <LI TYPE="circle">class org.springframework.web.multipart.support.<A HREF="../../../../../org/springframework/web/multipart/support/MultipartFilter.html" title="class in org.springframework.web.multipart.support"><B>MultipartFilter</B></A></UL> </UL> <LI TYPE="circle">class java.beans.PropertyEditorSupport (implements java.beans.PropertyEditor) <UL> <LI TYPE="circle">class org.springframework.web.multipart.support.<A HREF="../../../../../org/springframework/web/multipart/support/ByteArrayMultipartFileEditor.html" title="class in org.springframework.web.multipart.support"><B>ByteArrayMultipartFileEditor</B></A><LI TYPE="circle">class org.springframework.web.multipart.support.<A HREF="../../../../../org/springframework/web/multipart/support/StringMultipartFileEditor.html" title="class in org.springframework.web.multipart.support"><B>StringMultipartFileEditor</B></A></UL> <LI TYPE="circle">class javax.servlet.ServletRequestWrapper (implements javax.servlet.ServletRequest) <UL> <LI TYPE="circle">class javax.servlet.http.HttpServletRequestWrapper (implements javax.servlet.http.HttpServletRequest) <UL> <LI TYPE="circle">class org.springframework.web.multipart.support.<A HREF="../../../../../org/springframework/web/multipart/support/AbstractMultipartHttpServletRequest.html" title="class in org.springframework.web.multipart.support"><B>AbstractMultipartHttpServletRequest</B></A> (implements org.springframework.web.multipart.<A HREF="../../../../../org/springframework/web/multipart/MultipartHttpServletRequest.html" title="interface in org.springframework.web.multipart">MultipartHttpServletRequest</A>) <UL> <LI TYPE="circle">class org.springframework.web.multipart.support.<A HREF="../../../../../org/springframework/web/multipart/support/DefaultMultipartHttpServletRequest.html" title="class in org.springframework.web.multipart.support"><B>DefaultMultipartHttpServletRequest</B></A></UL> </UL> </UL> </UL> </UL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/springframework/web/multipart/cos/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/springframework/web/servlet/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright (C) 2003-2004 The Spring Framework Project.</i> </BODY> </HTML>
dachengxi/spring1.1.1_source
docs/api/org/springframework/web/multipart/support/package-tree.html
HTML
mit
8,329
50.41358
529
0.658663
false
--- published: true author: Robin Wen layout: post title: MacBook Pro 更换电池 category: 工具 summary: "自从今年大修了一次主力 MacBook 后,笔者考虑准备一台随时可以上阵的备用机。笔者除了主力的 2018 年款 MacBook Pro,还有一台 2015 年出厂的 MacBook Pro。2015 年的这台机器可用性极强,外壳没有磕过,性能也还不错,唯一美中不足的电池鼓包严重,导致笔记本盖子都不能完全合上。不得不感慨,苹果的设备做工是真得精细啊。笔者一直认为,2015 年的 Retina MacBook Pro 是最好用的苹果笔记本(性能稳定、散热稳定、转接口方便、剪刀式键盘、没有鸡肋的 Touch Bar、有灵魂的发光的 Logo),电池续航不行了,还能动手更换。2016 年之后的 MacBook 要自己更换就没那么容易了。" tags: - 工具 - MacBook - 比特币 - Bitcoin - 水龙头 - ExinEarn --- `文/Robin` *** ![](https://cdn.dbarobin.com/s0yv3o7.png) 自从今年大修了一次主力 MacBook 后,笔者考虑准备一台随时可以上阵的备用机。笔者除了主力的 2018 年款 MacBook Pro,还有一台 2015 年出厂的 MacBook Pro。2015 年的这台机器可用性极强,外壳没有磕过,性能也还不错,唯一美中不足的电池鼓包严重,导致笔记本盖子都不能完全合上。 电池鼓包严重,那就要想办法解决。只是笔者的拖延症严重,导致一直没有时间去更换。最近看到一些群里聊了这个话题,于是去研究了下,发现官方渠道更换电池的费用在 3000~4000 元(2015 年的机子早已过保)。于是又找了些其他渠道,线下的一些非官方渠道在 600~1000 元不等,闪电修 588 元。 由于之前笔者在闪电修更换过几次 iPhone 电池(苹果的设备除了电池,是真耐用),所以对于他们的服务还是比较满意的。于是我在闪电修下了个上门更换电池的订单,没多久他们告知这个服务是才开通的,暂时不能上门,需要送到福田他们的门店维修。虽然是备用机,但是寄修对于我而言,是不能接受的,于是放弃了这个渠道。 线下的非官方渠道,水挺深的,师傅的技术也是因人而异,于是这个渠道也不考虑了。最后就只剩下「**自己动手,丰衣足食**」了。笔者去京东找了下适配机型的电池,发现绿巨能有一款评价不错,还附赠工具,价格 359 元,于是下了单,使用「水龙头」还返 20 元等值的比特币。第二天一到,就去寻找一些教程,准备着手更换。 iFixit 网站上有一个非常详细的教程,步骤多达 36 步。笔者看了下犯愁了,绿巨能的电池送的工具就一把塑胶铲子、两把螺丝刀,挺多工具都没有啊。于是笔者去 B 站重新找了个视频教程,看了一遍,没那么难啊,就是关键的几步注意下就行了。于是按照这个视频教程开始动手更换电池。打开背壳,发现这电池膨胀太吓人了,什么时候爆炸都难说啊。如果读者发现电池鼓包了,得尽快处理。整个过程耗时 40 分钟左右,除了拆卸电池比较费劲之外,其他的都挺容易的。除了更换电池,笔者还是用压缩空气对电路板除了下尘。 更换电池之后,开机,查看电池性能,测试电池充放,一切正常。MacBook Pro 就这样满血复活了。不过有一点需要注意,为了最低地降低风险,在更换电池之前,先打开您的 MacBook 直到完全耗尽电池电量。 不得不感慨,苹果的设备做工是真的精细啊。笔者一直认为,2015 年的 Retina MacBook Pro 是最好用的苹果笔记本(性能稳定、散热稳定、转接口方便、剪刀式键盘、没有鸡肋的 Touch Bar、有灵魂的发光的 Logo),电池续航不行了,还能动手更换。2016 年之后的 MacBook 要自己更换就没那么容易了。 这就是笔者动手更换电池的经验,希望对读者有所帮助。有任何问题,欢迎交流。 对了,关于文中提到的绿巨能笔记本电池(适配 2015 款 13 英寸 Retina MacBook Pro,型号是 A1502),如果读者有需求的话,可以扫描以下二维码购买。 ![](https://cdn.dbarobin.com/unbe9nq.jpg) 最后,本文提到的水龙头,App Store、各大安卓市场均有下载,关键词「水龙头」​,也可以扫描​下图的二维码注册。​我的邀请码:**3XKXJB**。​ ![](https://cdn.dbarobin.com/kwdjijt.png) *** 我是区块链罗宾,博客 [dbarobin.com](https://dbarobin.com/) 如果您想和我交流,我的 Mixin: **26930** ![](https://cdn.dbarobin.com/zrau1cb.png) *** **本站推广** 币安是全球领先的数字货币交易平台,提供比特币、以太坊、BNB 以及 USDT 交易。 > 币安注册: [https://accounts.binancezh.io/cn/register/?ref=11190872](https://accounts.binancezh.io/cn/register/?ref=11190872) > 邀请码: **11190872** *** 本博客开通了 Donate Cafe 打赏,支持 Mixin Messenger、Blockin Wallet、imToken、Blockchain Wallet、Ownbit、Cobo Wallet、bitpie、DropBit、BRD、Pine、Secrypto 等任意钱包扫码转账。 <center> <div class="--donate-button" data-button-id="f8b9df0d-af9a-460d-8258-d3f435445075" ></div> </center> *** –EOF– 版权声明:[自由转载-非商用-非衍生-保持署名(创意共享4.0许可证)](http://creativecommons.org/licenses/by-nc-nd/4.0/deed.zh)
dbarobin/dbarobin.github.io
_posts/工具/2020-10-28-battery.md
Markdown
mit
5,549
33.961039
330
0.784838
false
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
39.333333
75
0.772727
false
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
30.792453
102
0.687834
false
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
25.30303
83
0.528802
false
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
20.785714
87
0.673235
false
# core-data-ipc Share a Core Data store between multiple processes
ddeville/core-data-ipc
README.md
Markdown
mit
67
32.5
50
0.80597
false
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
24.368421
129
0.631743
false
<html> <head> <meta charset="utf-8"> <title>Example React.js using NPM, Babel6 and Webpack</title> </head> <body> <div id="app" /> <script src="public/bundle.js" type="text/javascript"></script> </body> </html>
Tabares/react-example-webpack-babel
src/client/index.html
HTML
mit
235
22.5
67
0.604255
false
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> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="ret" type="{urn:api3}soapDocument" maxOccurs="unbounded"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </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
29.013158
116
0.644016
false
#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
26.103448
96
0.733758
false
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
32.368421
119
0.614616
false
--- layout: page title: php 文件管理 category: blog description: --- # Preface 以下是php文件管理函数归纳 # 文件属性(file attribute) filetype($path) block(块设备:分区,软驱,光驱) char(字符设备键盘打打印机) dir file fifo (命名管道,用于进程之间传递信息) link unknown file_exits() 文件存在性 filesize() 返回文件大小(字节数,用pow()去转化 为MB吧) is_readable()检查是否可读 is_writeable()检查是否可写 is_excuteable()检查是否可执行 filectime()检查文件创建的时间 filemtime()检查文件的修改时间 fileatime()检查文件访问时间 stat()获取文件的属性值 0 dev device number - 设备名 1 ino inode number - inode 号码 2 mode inode protection mode - inode 保护模式 3 nlink number of links - 被连接数目 4 uid userid of owner - 所有者的用户 id 5 gid groupid of owner- 所有者的组 id 6 rdev device type, if inode device * - 设备类型,如果是 inode 设备的话 7 size size in bytes - 文件大小的字节数 8 atime time of last access (unix timestamp) - 上次访问时间(Unix 时间戳) 9 mtime time of last modification (unix timestamp) - 上次修改时间(Unix 时间戳) 10 ctime time of last change (unix timestamp) - 上次改变时间(Unix 时间戳) 11 blksize blocksize of filesystem IO * - 文件系统 IO 的块大小 12 blocks number of blocks allocated - 所占据块的数目 # Dir, 文件目录 ## Path ### Pathinfo pathinfo()返回一个数组‘dirname’,'basename’,'filename', 'extension’ realpath('.'); dirname() basename();filename+.+extension ### File location __DIR__ //脚本目录 getcwd();//当前目录 __FILE__ realpath($file); //获取链接文件的绝对路径 #### _SERVER中的path: http://localhost/a/b/c/?var1=val1 #按脚本 **************** SCRIPT_FILENAME = DOCUMENT_ROOT + truePath /data1/www/htdocs/912/hilo/1/phpinfo.php DOCUMENT_ROOT /data1/www/htdocs/912/hilo/1 #按url path: SCRIPT_NAME /PHP_SELF / DOCUMENT_URI (nginx: SCRIPT_URL 默认是空的) nginx: $fastcgi_script_name , 这可以被 rewrite 改写, 以上path 都会变 /a/b/c/ SCRIPT_URI = HTTP_HOST+path 可能为空 http://hilojack.com/a/b/c/ REQUEST_URI = path + QUERY_STRING nginx: $request_uri /a/b/c/?test=1 Refer to: [](/p/linux-nginx) 其它: $_SERVER['OLDPWD'] The definition of OLDPWD is the *p*revious *w*orking *d*irectory as set by the cd command ## Dir Access $dirp=opendir() readdir($dirp);结尾时返回false rewinddir($dirp);返回目录开头 closedir($dirp); ### Match file 用`glob` 代替`opendir` foreach (glob("*.txt") as $filename) { echo "$filename size " . filesize($filename) . "\n"; } ## Dir Operation mkdir ( string $pathname [, int $mode [, bool $recursive [, resource $context ]]] ) rmdir($pathname);必须为空 # Upload File move_uploaded_file($_FILES['userfile']['tmp_name'], $dir.$file)) # File Operation ## Open: fopen ( string $filename , string $mode [, bool $use_include_path [, resource $zcontext ]] ) ‘r’ 只读方式打开,将文件指针指向文件头。 ‘r+’ 读写方式打开,将文件指针指向文件头。 ‘w’ 写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。 ‘w+’ 读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。 ‘a’ 写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。 ‘a+’ 读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。 ‘x’ 创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。此选项被 PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。 ‘x+’ 创建并以读写方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。此选项被 PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。 Windows 下提供了一个文本转换标记(’t')可以透明地将 \n 转换为 \r\n。与此对应还可以使用 ‘b’ 来强制使用二进制模式,这样就不会转换数据。要使用这些标记,要么用 ‘b’ 或者用 ‘t’ 作为 mode 参数的最后一个字符。 ## Close fclose($fp); ## File:read - write fread ( int $handle , int $length )最长8192 –fwrite ( resource $handle , string $string [, int $length ] ) fgets ( int $handle [, int $length=1024 ] ) 读取一行 fgetss ( resource $handle [, int $length])读取一行并且去掉html+php标记 fgetc();读取一个字符 //格式化 while($log = fscanf($handler, '%s-%d-%d')){ list($name, $uid, $phone) = $log; } //csv fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = ',' [, string $enclosure = '"' [, string $escape = '\\' ]]]] ); 读入一行并解析csv 其它: 获取内容 file_get_contents() —file_put_contents() 返回行数组 file ( string $filename [, int $use_include_path [, resource $context ]] ) 输出一个文件 readfile ( string $filename [, bool $use_include_path [, resource $context ]] ) 文件截取 ftruncate ( resource $handle , int $size ),当$size=0,文件就变为空 文件删除 unlink(); 文件复制 copy($src,$dst); Access a.php , a.php include ../b.php, b.php include htm/c.php, in c.php file_put_contents('a.txt', 'a');// write to ./a.txt not to ../htm/a.txt ## 指针移动 ftell($fp);//Returns the current position of the file read/write pointer fseek($fp,$offset[,SEEK_CUR OR SEEK_END OR SEEK_SET),SEEK_SET是默认值,SEEK_END时offset应该为负值 可选。可能的值: SEEK_SET - 设定位置等于 offset 字节。默认。 SEEK_CUR - 设定位置为当前位置加上 offset。 SEEK_END - 设定位置为文件末尾加上 offset (要移动到文件尾之前的位置,offset 必须是一个负值)。 # 并发访问中的文件锁 flock ( int $handle , int $operation [, int &$wouldblock ] ) $operation flock($f, LOCK_SH); 默认值, 没有意义? 不是的,当LOCK_EX 时,这句会返回失败 flock($f, LOCK_EX) 独占锁,带阻塞等待 flock($f, LOCK_EX | LOCK_NB) or die('Another process is running!'); 独占锁,不阻塞 flock($f, LOCK_UN); 释锁 $wouldblock 遇到阻塞时会被设为1 可以用`php -a` 开两个进程测试a.txt # 上传下载 ## 上传 1.1表单:enctype="multipart/form-data" array(1) { ["upload"]=>array(5) { ["name"]=>array(3) { [0]=>string(9)"file0.txt" [1]=>string(9)"file1.txt" [2]=>string(9)"file2.txt" } ["type"]=>array(3) { [0]=>string(10)"text/plain" [1]=>string(10)"text/plain" [2]=>string(10)"text/plain" } ["tmp_name"]=>array(3) { [0]=>string(14)"/tmp/blablabla" [1]=>string(14)"/tmp/phpyzZxta" [2]=>string(14)"/tmp/phpn3nopO" } ["error"]=>array(3) { [0]=>int(0) [1]=>int(0) [2]=>int(0) } ["size"]=>array(3) { [0]=>int(0) [1]=>int(0) [2]=>int(0) } } } 1.2处理上传 move_uploaded_file();必须要在http.conf中设置documentRoot文件 ## 下载 header("Content-Type:application/octet-stream"); //打开始终下载的mimetype header("Content-Disposition: attachment; filename=文件名.后缀名"); // 文件名.后缀名 换成你的文件名这里的文件名是下载后的文件名,和你的源文件名没有关系。 header("Pragma: no-cache"); // 缓存 header("Expires: 0″); header("Content-Length:3390″); 记得加enctype="multipart/form-data"
alskjstl/hilojack.github.io
_posts/2013-2-3-php-file.md
Markdown
mit
8,412
26.22467
181
0.636246
false
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
16.761905
72
0.546917
false
import unittest from src.data_structures.mockdata import MockData class TestMockData (unittest.TestCase): def setUp(self): self.data = MockData() def test_random_data(self): data = MockData() a_set = data.get_random_elements(10) self.assertTrue(len(a_set) == 10, "the data should have 10 elements!") if __name__ == '__main__': unittest.main()
alcemirsantos/algorithms-py
tests/data_stuctures/test_mockdata.py
Python
mit
400
22.588235
78
0.625
false
// // Person.h // SJDBMapProject // // Created by BlueDancer on 2017/6/4. // Copyright © 2017年 SanJiang. All rights reserved. // #import <Foundation/Foundation.h> #import "SJDBMapUseProtocol.h" @class Book; @class PersonTag; @class Goods; @class TestTest; @interface Person : NSObject<SJDBMapUseProtocol> @property (nonatomic, strong) Book *aBook; @property (nonatomic, assign) NSInteger personID; @property (nonatomic, strong) NSString *name; @property (nonatomic, strong) NSArray<PersonTag *> *tags; @property (nonatomic, strong) NSString *test; @property (nonatomic, strong) NSString *teet; @property (nonatomic, strong) NSString *ttttt; @property (nonatomic, strong) NSArray<Goods *> *goods; @property (nonatomic, assign) NSInteger age; @property (nonatomic, assign) NSInteger group; @property (nonatomic, assign) NSInteger index; @property (nonatomic, assign) NSInteger ID; @property (nonatomic, assign) NSInteger unique; @property (nonatomic, strong) NSURL *tessss; @property (nonatomic, strong) NSString *teesssf; @property (nonatomic, strong) TestTest *testTest; @end
changsanjiang/SJDBMap
SJDBMapProject/Model/Person.h
C
mit
1,103
20.568627
57
0.742727
false
/* ======================================== * 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
20.805556
142
0.520382
false
# 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
15.578947
35
0.526984
false
# fish-p2p FISH: FIle SHaring, a Distributed File System - Decentralised P2P system
tobiajo/fish-p2p
README.md
Markdown
mit
84
41
72
0.785714
false
<!DOCTYPE html> <html> <head> <title>Poet -- node.js blogging platform</title> <link rel="stylesheet" href="styles/prettify.css"> <link rel="stylesheet" href="styles/poet.css"> <link href="http://fonts.googleapis.com/cs?family=La+Belle+Aurore" rel="stylesheet" type="text/css"> <script src="js/ga.js"></script> </head> <body> <div class="header"> <div class="wrap"><a href="http://github.com/jsantell/poet"> <h1>Poet</h1> <h2>write your code love poem</h2></a></div> </div> <div class="wrap"> <div class="cartoon"></div> <h2 id="what-is-poet-">What is Poet?</h2> <p><a href="http://github.com/jsantell/poet" title="Poet"><strong>Poet</strong></a> is a blog generator in <a href="http://nodejs.org" title="node.js">node.js</a> to generate routing, render markdown/pug/whatever posts, and get a blog up and running <em>fast</em>. Poet may not make you blog-famous, and it may give you one less excuse for not having a blog, but just imagine the insane hipster cred you get for having node power your blog. <em>&quot;Cool blog, is this Wordpress or something?&quot;</em> your square friend asks. <em>&quot;Nah dude, this is in node,&quot;</em> you respond, while skateboarding off into the sunset, doing mad flips and stuff. Little do they know you just used Poet&#39;s autoroute generation to get your content in, like, seconds, up on that internet.</p> <h2 id="getting-started">Getting Started</h2> <p>First thing first, throw <strong>Poet</strong> into your express app&#39;s package.json, or just install it locally with:</p> <pre> npm install poet </pre> <p>Once you have the <strong>Poet</strong> module in your app, just instantiate an instance with your Express app and options, and call the <code>init</code> method:</p> <pre> var express = require('express'), app = express(), Poet = require('poet'); var poet = Poet(app, { posts: './_posts/', postsPerPage: 5, metaFormat: 'json' }); poet.init().then(function () { // ready to go! }); /* set up the rest of the express app */ </pre> <p>If using Express 3, be sure to use Poet version &lt;= <code>1.1.0</code>. For Express 4+, use Poet <code>2.0.0+</code>.</p> <h2 id="posts">Posts</h2> <p>Posts are constructed in <a href="http://daringfireball.net/projects/markdown/">markdown</a>/<a href="https://pugjs.org">pug</a>/<a href="#Templates">whatever-you-want</a>, prefixed by front matter via <a href="https://github.com/mojombo/jekyll/wiki/YAML-Front-Matter">YAML</a> or <a href="https://github.com/jsantell/node-json-front-matter">JSON</a>. All attributes are stored in the posts object. An example of a blog post formatted with JSON Front Matter is below:</p> <pre> {{{ "title": "Hello World!", "tags": ["blog", "fun"], "category": "javascript", "date": "7-29-2013" }}} Here goes the content that belongs to the post... </pre> <h3 id="post-previews">Post Previews</h3> <p>There are several ways of specifying the text of your post preview. <strong>Poet</strong> checks several properties and the first valid option is used. The order and ways to accomplish this are below.</p> <ul> <li>A <code>preview</code> property on a post. The text of this property runs through the appropriate template and be saved as the preview for a post</li> <li>A <code>previewLength</code> property on a post, which will take the first <code>n</code> characters of your post (before running through a templating engine), becoming your preview.</li> <li>The last, and most likely easiest, is specifying a <code>readMoreTag</code> option in your <strong>Poet</strong> configuration, which by default is <code>&lt;!--more--&gt;</code>. Whenever the <code>readMoreTag</code> is found int he post, anything proceeding it becomes the preview. You can set this globally in your <strong>Poet</strong> config, or specify a <code>readMoreTag</code> property for each post individually</li> </ul> <h2 id="options">Options</h2> <ul> <li><code>posts</code> path to directory of your files of posts (default: <code>./\_posts/</code>)</li> <li><code>metaFormat</code> format of your front matter on every blog post. Can be <code>yaml</code> or <code>json</code> (default: <code>json</code>)</li> <li><code>postsPerPage</code> How many posts are displayed per page in the page route (default: <code>5</code>)</li> <li><code>readMoreLink</code> A function taking the post object as the only parameter, returning a string that is appended to the post&#39;s preview value. By default will be a function returning <code>&lt;a href=&quot;{post.link}&quot;&gt;{post.title}&lt;/a&gt;</code></li> <li><code>readMoreTag</code> A string in a post that is rendered as a read more link when parsed. (default: <code>&lt;!--more--&gt;</code>)</li> <li><code>showDrafts</code> An option on whether or not to display posts that have <code>drafts</code> meta set to true (default: <code>process.env.NODE\_ENV !== &#39;production&#39;</code>)</li> <li><code>routes</code> A hash of route keys (ex: <code>&#39;/post/:post&#39;</code> and the related view file (ex: <code>&#39;post&#39;</code>). More information in the <a href="#Routes">routes</a> section below.</li> </ul> <h2 id="methods">Methods</h2> <h3 id="poet-init-callback-">Poet::init([callback])</h3> <p>The <code>init</code> method traverses the directory of posts and stores all the information in memory, sets up the internal structures for retrieval and returns a promise resolving to the instance upon completion. An optional callback may be provided for a node style callback with <code>err</code> and <code>poet</code> arguments passed in, called upon completion. This is used when initializing the application, or if reconstructing the internal storage is needed.</p> <h3 id="poet-watch-callback-">Poet::watch([callback])</h3> <p>Sets up the <strong>Poet</strong> instance to watch the posts directory for changes (a new post, updated post, etc.) and reinitializes the engine and storage. An optional <code>callback</code> may be provided to signify the completion of the reinitialization.</p> <p>For an example of using <code>watch</code>, check out <a href="https://github.com/jsantell/poet/blob/master/examples/watcher.js">the watcher example</a></p> <h3 id="poet-unwatch-">Poet::unwatch()</h3> <p>Removes all watchers currently bound to the <strong>Poet</strong> instance.</p> <h3 id="poet-clearcache-">Poet::clearCache()</h3> <p>Used internally, this clears the <strong>Poet</strong> instance&#39;s internal cache, allowing it to be rebuilt on it&#39;s next use. This should not be used in most cases. Returns the <strong>Poet</strong> instance.</p> <h3 id="Templates">Poet::addTemplate(data)</h3> <p><strong>Poet</strong> comes with two templating engines by default (pug and markdown). To specify your own templating language, the <code>addTemplate</code> method may be used, taking a <code>data</code> object with two keys: <code>ext</code> and <code>fn</code>. <code>ext</code> may be a string or an array of strings, specifiying which extensions should use this templating engine, and <code>fn</code> does the rendering, where it is a function that passes an object with several properties: <code>source</code>, <code>filename</code> and <code>locals</code> for rendering engine local variables, and returns the formatted string. Here&#39;s an example of using your own YAML formatter:</p> <pre> var express = require('express'), app = express(), yaml = require('yaml'), Poet = require('poet'); var poet = Poet(app); poet.addTemplate({ ext: 'yaml', fn : function (options) { return yaml.eval(options.source); } }).init(); </pre> <p>This runs any post with the file extension <code>yaml</code> (ex: <code>my_post.yaml</code>) through the <code>fn</code> specified (by calling the <code>yaml</code> module&#39;s <code>eval</code> method.</p> <h3 id="poet-addroute-route-handler-">Poet::addRoute(route, handler)</h3> <p><code>addRoute</code> allows you to specify the handler for a specific route type. Accepting a <code>route</code> string (ex: &#39;/myposts/:post&#39;) and a function <code>handler</code>, the route is parsed based off of parameter name (<code>:post</code> for example in the route <code>/myposts/:post</code>), and the previously stored route for that route type (post) is replaced.</p> <p>The below example uses all default routes except for the post route, and gives full control over how the request is handled. Obviously extra code is needed to specify this, but we can add arbitrary code here, for example, to do some sort of logging:</p> <pre> var express = require('express'), app = express(), Poet = require('poet'); var poet = Poet(app); poet.addRoute('/myposts/:post', function (req, res, next) { var post = poet.helpers.getPost(req.params.post); if (post) { // Do some fancy logging here res.render('post', { post: post }); } else { res.send(404); } }).init(); </pre> <p>For more examples on custom routing, check out the <a href="https://github.com/jsantell/poet/blob/master/examples/customRoutes.js">examples in the repository</a>.</p> <h2 id="routing">Routing</h2> <p>The default configuration uses the default routes with the view names below:</p> <ul> <li>&#39;/post/:post&#39;: &#39;post&#39;</li> <li>&#39;/page/:page&#39;: &#39;page&#39;</li> <li>&#39;/tag/:tag&#39;: &#39;tag&#39;</li> <li>&#39;/category/:category&#39;: &#39;category&#39;</li> </ul> <p>For example, if your site root is <code>http://mysite.com</code>, going to the page <code>http://mysite.com/post/hello-world</code> will call the &#39;post&#39; view in your view directory and render the appropriate post. The options passed into the instantiation of the <strong>Poet</strong> instance can have a <code>routes</code> key, with an object containing key/value pairs of strings mapping a route to a view. Based off of the paramter in the route (ex: <code>:post</code> in <code>/post/:post</code>), the previous route will be replaced.</p> <p>For an example of customizing your route names and views, view the <a href="https://github.com/jsantell/poet/blob/master/examples/configuredSetup.js">example in the repository</a>. To override the default handlers of, check out the <code>Poet::addRoute(route, handler)</code> method.</p> <h2 id="helpers">Helpers</h2> <p>Built in helper methods are stored on the <strong>Poet</strong> instance&#39;s <code>helper</code> property. Used internally, and in the view locals, they can be used outside of <strong>Poet</strong> as well.</p> <ul> <li><code>getPosts(from, to)</code> - an array of reverse chronologically ordered post objects. May specify <code>from</code> and <code>to</code> based on their index, to limit which posts should be returned.</li> <li><code>getTags()</code> - an array of tag names</li> <li><code>getCategories</code> - an array of category names</li> <li><code>tagURL(tag)</code> - a function that takes a name of a tag and returns the corresponding URL based off of the routing configuration</li> <li><code>pageURL(page)</code> - a function that takes the number of a page and returns the corresponding URL based off of the routing configuration</li> <li><code>categoryURL(category)</code> - a function that takes a name of a category and returns the corresponding URL based off of the routing configuration</li> <li><code>getPostCount()</code> - a function that returns the number of total posts registered</li> <li><code>getPost(title)</code> - a function that returns the corresponding post based off of <code>title</code></li> <li><code>getPageCount()</code> - a function that returns the total number of pages, based off of number of posts registered and the <code>postsPerPage</code> option.</li> <li><code>postsWithTag(tag)</code> - returns an array of posts that contain <code>tag</code></li> <li><code>postsWithCategory(cat)</code> - returns an array of posts are in category `cat</li> <li><code>options</code> - all of the option configurations</li> </ul> <h2 id="locals">Locals</h2> <p>In addition to all of the helpers being available to each view, there are additional variables accessible inside specific views.</p> <h3 id="post-locals">Post Locals</h3> <ul> <li><code>post.url</code> - the URL of the current post</li> <li><code>post.content</code> - the content of the current post</li> <li><code>post.preview</code> - the preview of the current post</li> </ul> <h3 id="page-locals">Page Locals</h3> <ul> <li><code>posts</code> - an array of post objects that are within the current post range</li> <li><code>page</code> - the number of the current page</li> </ul> <h3 id="tag-locals">Tag Locals</h3> <ul> <li><code>posts</code> - an array of all post objects that contain the current tag</li> <li><code>tag</code> - a string of the current tag&#39;s name</li> </ul> <h3 id="category-locals">Category Locals</h3> <ul> <li><code>posts</code> - an array of all post objects with the current category</li> <li><code>category</code> - a string of the current category&#39;s name</li> </ul> <h2 id="additional-examples">Additional Examples</h2> <p>Be sure to check out the examples in the repository</p> <ul> <li><a href="https://github.com/jsantell/poet/blob/master/examples/defaultSetup.js">Default configuration</a></li> <li><a href="https://github.com/jsantell/poet/blob/master/examples/configuredSetup.js">Specifying some options</a></li> <li><a href="https://github.com/jsantell/poet/blob/master/examples/customRoutes.js">Using your own custom routes</a></li> <li><a href="https://github.com/jsantell/poet/blob/master/examples/rss.js">Setting up an RSS feed</a></li> <li><a href="https://github.com/jsantell/poet/blob/master/examples/watcher.js">Using a watcher</a></li> </ul> <h2 id="get-bloggin-">Get Bloggin&#39;!</h2> <p>Time to start writing your sweet, beautiful words. For more development information, check out the <a href="https://github.com/jsantell/poet">repository</a>, or scope out the examples in there to get a better idea. If you have any comments, questions, or suggestions, hit me up <a href="http://twitter.com/jsantell">@jsantell</a>!</p> </div> </div> <script src="js/prettify.js"></script> <script> prettyPrint(); </script> <a href="https://github.com/jsantell/poet"><img style="position:absolute;top:0;right:0;border:0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub"></a> </body> </html>
jsantell/poet
docs/public/index.html
HTML
mit
14,428
69.380488
696
0.715137
false
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
39.608696
73
0.520343
false
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
30.066667
127
0.639485
false
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
38.942857
84
0.749642
false
<!DOCTYPE html> <!--[if lt IE 9]><html class="no-js lt-ie9" lang="en" dir="ltr"><![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en" dir="ltr"> <!--<![endif]--> <!-- Usage: /eic/site/ccc-rec.nsf/tpl-eng/template-1col.html?Open&id=3 (optional: ?Open&page=filename.html&id=x) --> <!-- Created: ; Product Code: 536; Server: stratnotes2.ic.gc.ca --> <head> <!-- Title begins / Début du titre --> <title> Canada Custom Shutters Ltd. - Complete profile - Canadian Company Capabilities - Industries and Business - Industry Canada </title> <!-- Title ends / Fin du titre --> <!-- Meta-data begins / Début des métadonnées --> <meta charset="utf-8" /> <meta name="dcterms.language" title="ISO639-2" content="eng" /> <meta name="dcterms.title" content="" /> <meta name="description" content="" /> <meta name="dcterms.description" content="" /> <meta name="dcterms.type" content="report, data set" /> <meta name="dcterms.subject" content="businesses, industry" /> <meta name="dcterms.subject" content="businesses, industry" /> <meta name="dcterms.issued" title="W3CDTF" content="" /> <meta name="dcterms.modified" title="W3CDTF" content="" /> <meta name="keywords" content="" /> <meta name="dcterms.creator" content="" /> <meta name="author" content="" /> <meta name="dcterms.created" title="W3CDTF" content="" /> <meta name="dcterms.publisher" content="" /> <meta name="dcterms.audience" title="icaudience" content="" /> <meta name="dcterms.spatial" title="ISO3166-1" content="" /> <meta name="dcterms.spatial" title="gcgeonames" content="" /> <meta name="dcterms.format" content="HTML" /> <meta name="dcterms.identifier" title="ICsiteProduct" content="536" /> <!-- EPI-11240 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- MCG-202 --> <meta content="width=device-width,initial-scale=1" name="viewport"> <!-- EPI-11567 --> <meta name = "format-detection" content = "telephone=no"> <!-- EPI-12603 --> <meta name="robots" content="noarchive"> <!-- EPI-11190 - Webtrends --> <script> var startTime = new Date(); startTime = startTime.getTime(); </script> <!--[if gte IE 9 | !IE ]><!--> <link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="icon" type="image/x-icon"> <link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/wet-boew.min.css"> <!--<![endif]--> <link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/theme.min.css"> <!--[if lt IE 9]> <link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="shortcut icon" /> <link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/ie8-wet-boew.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew.min.js"></script> <![endif]--> <!--[if lte IE 9]> <![endif]--> <noscript><link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/noscript.min.css" /></noscript> <!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER --> <script>dataLayer1 = [];</script> <!-- End Google Tag Manager --> <!-- EPI-11235 --> <link rel="stylesheet" href="/eic/home.nsf/css/add_WET_4-0_Canada_Apps.css"> <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"> <link href="/app/ccc/srch/css/print.css" media="print" rel="stylesheet" type="text/css" /> </head> <body class="home" vocab="http://schema.org/" typeof="WebPage"> <!-- EPIC HEADER BEGIN --> <!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER --> <noscript><iframe title="Google Tag Manager" src="//www.googletagmanager.com/ns.html?id=GTM-TLGQ9K" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer1'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer1','GTM-TLGQ9K');</script> <!-- End Google Tag Manager --> <!-- EPI-12801 --> <span typeof="Organization"><meta property="legalName" content="Department_of_Industry"></span> <ul id="wb-tphp"> <li class="wb-slc"> <a class="wb-sl" href="#wb-cont">Skip to main content</a> </li> <li class="wb-slc visible-sm visible-md visible-lg"> <a class="wb-sl" href="#wb-info">Skip to "About this site"</a> </li> </ul> <header role="banner"> <div id="wb-bnr" class="container"> <section id="wb-lng" class="visible-md visible-lg text-right"> <h2 class="wb-inv">Language selection</h2> <div class="row"> <div class="col-md-12"> <ul class="list-inline mrgn-bttm-0"> <li><a href="nvgt.do?V_TOKEN=1492272358519&V_SEARCH.docsCount=3&V_DOCUMENT.docRank=7972&V_SEARCH.docsStart=7971&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=/prfl.do&lang=fra&redirectUrl=/app/scr/imbs/ccc/rgstrtn/updt.sec?_flId?_flxKy=e1s1&amp;estblmntNo=234567041301&amp;profileId=61&amp;_evId=bck&amp;lang=eng&amp;V_SEARCH.showStricts=false&amp;prtl=1&amp;_flId?_flId?_flxKy=e1s1" title="Français" lang="fr">Français</a></li> </ul> </div> </div> </section> <div class="row"> <div class="brand col-xs-8 col-sm-9 col-md-6"> <a href="http://www.canada.ca/en/index.html"><object type="image/svg+xml" tabindex="-1" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/sig-blk-en.svg"></object><span class="wb-inv"> Government of Canada</span></a> </div> <section class="wb-mb-links col-xs-4 col-sm-3 visible-sm visible-xs" id="wb-glb-mn"> <h2>Search and menus</h2> <ul class="list-inline text-right chvrn"> <li><a href="#mb-pnl" title="Search and menus" aria-controls="mb-pnl" class="overlay-lnk" role="button"><span class="glyphicon glyphicon-search"><span class="glyphicon glyphicon-th-list"><span class="wb-inv">Search and menus</span></span></span></a></li> </ul> <div id="mb-pnl"></div> </section> <!-- Site Search Removed --> </div> </div> <nav role="navigation" id="wb-sm" class="wb-menu visible-md visible-lg" data-trgt="mb-pnl" data-ajax-fetch="//cdn.canada.ca/gcweb-cdn-dev/sitemenu/sitemenu-en.html" typeof="SiteNavigationElement"> <h2 class="wb-inv">Topics menu</h2> <div class="container nvbar"> <div class="row"> <ul class="list-inline menu"> <li><a href="https://www.canada.ca/en/services/jobs.html">Jobs</a></li> <li><a href="http://www.cic.gc.ca/english/index.asp">Immigration</a></li> <li><a href="https://travel.gc.ca/">Travel</a></li> <li><a href="https://www.canada.ca/en/services/business.html">Business</a></li> <li><a href="https://www.canada.ca/en/services/benefits.html">Benefits</a></li> <li><a href="http://healthycanadians.gc.ca/index-eng.php">Health</a></li> <li><a href="https://www.canada.ca/en/services/taxes.html">Taxes</a></li> <li><a href="https://www.canada.ca/en/services.html">More services</a></li> </ul> </div> </div> </nav> <!-- EPIC BODY BEGIN --> <nav role="navigation" id="wb-bc" class="" property="breadcrumb"> <h2 class="wb-inv">You are here:</h2> <div class="container"> <div class="row"> <ol class="breadcrumb"> <li><a href="/eic/site/icgc.nsf/eng/home" title="Home">Home</a></li> <li><a href="/eic/site/icgc.nsf/eng/h_07063.html" title="Industries and Business">Industries and Business</a></li> <li><a href="/eic/site/ccc-rec.nsf/tpl-eng/../eng/home" >Canadian Company Capabilities</a></li> </ol> </div> </div> </nav> </header> <main id="wb-cont" role="main" property="mainContentOfPage" class="container"> <!-- End Header --> <!-- Begin Body --> <!-- Begin Body Title --> <!-- End Body Title --> <!-- Begin Body Head --> <!-- End Body Head --> <!-- Begin Body Content --> <br> <!-- Complete Profile --> <!-- Company Information above tabbed area--> <input id="showMore" type="hidden" value='more'/> <input id="showLess" type="hidden" value='less'/> <h1 id="wb-cont"> Company profile - Canadian Company Capabilities </h1> <div class="profileInfo hidden-print"> <ul class="list-inline"> <li><a href="cccSrch.do?lang=eng&profileId=&prtl=1&key.hitsPerPage=25&searchPage=%252Fapp%252Fccc%252Fsrch%252FcccBscSrch.do%253Flang%253Deng%2526amp%253Bprtl%253D1%2526amp%253Btagid%253D&V_SEARCH.scopeCategory=CCC.Root&V_SEARCH.depth=1&V_SEARCH.showStricts=false&V_SEARCH.sortSpec=title+asc&amp;rstBtn.x=" class="btn btn-link">New Search</a>&nbsp;|</li> <li><form name="searchForm" method="post" action="/app/ccc/srch/bscSrch.do"> <input type="hidden" name="lang" value="eng" /> <input type="hidden" name="profileId" value="" /> <input type="hidden" name="prtl" value="1" /> <input type="hidden" name="searchPage" value="%2Fapp%2Fccc%2Fsrch%2FcccBscSrch.do%3Flang%3Deng%26amp%3Bprtl%3D1%26amp%3Btagid%3D" /> <input type="hidden" name="V_SEARCH.scopeCategory" value="CCC.Root" /> <input type="hidden" name="V_SEARCH.depth" value="1" /> <input type="hidden" name="V_SEARCH.showStricts" value="false" /> <input id="repeatSearchBtn" class="btn btn-link" type="submit" value="Return to search results" /> </form></li> <li>|&nbsp;<a href="nvgt.do?V_SEARCH.docsStart=7970&amp;V_DOCUMENT.docRank=7971&amp;V_SEARCH.docsCount=3&amp;lang=eng&amp;prtl=1&amp;sbPrtl=&amp;profile=cmpltPrfl&amp;V_TOKEN=1492272390390&amp;V_SEARCH.command=navigate&amp;V_SEARCH.resultsJSP=%2fprfl.do&amp;estblmntNo=234567090223&amp;profileId=&amp;key.newSearchLabel=">Previous Company</a></li> <li>|&nbsp;<a href="nvgt.do?V_SEARCH.docsStart=7972&amp;V_DOCUMENT.docRank=7973&amp;V_SEARCH.docsCount=3&amp;lang=eng&amp;prtl=1&amp;sbPrtl=&amp;profile=cmpltPrfl&amp;V_TOKEN=1492272390390&amp;V_SEARCH.command=navigate&amp;V_SEARCH.resultsJSP=%2fprfl.do&amp;estblmntNo=234567009478&amp;profileId=&amp;key.newSearchLabel=">Next Company</a></li> </ul> </div> <details> <summary>Third-Party Information Liability Disclaimer</summary> <p>Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.</p> </details> <h2> Canada Custom Shutters Ltd. </h2> <div class="row"> <div class="col-md-5"> <h2 class="h5 mrgn-bttm-0">Legal/Operating Name:</h2> <p>Canada Custom Shutters Ltd.</p> <div class="mrgn-tp-md"></div> <p class="mrgn-bttm-0" ><a href="http://www.canadacustomshutters.com" target="_blank" title="Website URL">http://www.canadacustomshutters.com</a></p> <p><a href="mailto:goran@canadacustomshutters.com" title="goran@canadacustomshutters.com">goran@canadacustomshutters.com</a></p> </div> <div class="col-md-4 mrgn-sm-sm"> <h2 class="h5 mrgn-bttm-0">Mailing Address:</h2> <address class="mrgn-bttm-md"> 140 Toll Rd<br/> HOLLAND LANDING, Ontario<br/> L9N 1G8 <br/> </address> <h2 class="h5 mrgn-bttm-0">Location Address:</h2> <address class="mrgn-bttm-md"> 140 Toll Rd<br/> HOLLAND LANDING, Ontario<br/> L9N 1G8 <br/> </address> <p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>: (905) 953-0801 </p> <p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>: (866) 532-5893</p> <p class="mrgn-bttm-lg"><abbr title="Facsimile">Fax</abbr>: (905) 953-8247</p> </div> <div class="col-md-3 mrgn-tp-md"> </div> </div> <div class="row mrgn-tp-md mrgn-bttm-md"> <div class="col-md-12"> </div> </div> <!-- <div class="wb-tabs ignore-session update-hash wb-eqht-off print-active"> --> <div class="wb-tabs ignore-session"> <div class="tabpanels"> <details id="details-panel1"> <summary> Full profile </summary> <!-- Tab 1 --> <h2 class="wb-invisible"> Full profile </h2> <!-- Contact Information --> <h3 class="page-header"> Contact information </h3> <section class="container-fluid"> <div class="row mrgn-tp-lg"> <div class="col-md-3"> <strong> Milan Gigic </strong></div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Title: </strong> </div> <div class="col-md-7"> <!--if client gender is not null or empty we use gender based job title--> Manager </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Area of Responsibility: </strong> </div> <div class="col-md-7"> Management Executive. </div> </div> <div class="row mrgn-tp-lg"> <div class="col-md-3"> <strong> Goran Gigic </strong></div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Title: </strong> </div> <div class="col-md-7"> <!--if client gender is not null or empty we use gender based job title--> Treasurer </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Telephone: </strong> </div> <div class="col-md-7"> (905) 953-0801 </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Facsimile: </strong> </div> <div class="col-md-7"> (905) 953-8247 </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Email: </strong> </div> <div class="col-md-7"> goran@canadacustomshutters.com </div> </div> </section> <p class="mrgn-tp-lg text-right small hidden-print"> <a href="#wb-cont">top of page</a> </p> <!-- Company Description --> <h3 class="page-header"> Company description </h3> <section class="container-fluid"> <div class="row"> <div class="col-md-5"> <strong> Country of Ownership: </strong> </div> <div class="col-md-7"> Canada &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Year Established: </strong> </div> <div class="col-md-7"> 1987 </div> </div> <div class="row"> <div class="col-md-5"> <strong> Exporting: </strong> </div> <div class="col-md-7"> Yes &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Primary Industry (NAICS): </strong> </div> <div class="col-md-7"> 321919 - Other Millwork </div> </div> <div class="row"> <div class="col-md-5"> <strong> Primary Business Activity: </strong> </div> <div class="col-md-7"> Manufacturer / Processor / Producer &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Total Sales ($CDN): </strong> </div> <div class="col-md-7"> $1,000,000 to $4,999,999&nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Export Sales ($CDN): </strong> </div> <div class="col-md-7"> $1 to $99,999&nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Number of Employees: </strong> </div> <div class="col-md-7"> 20&nbsp; </div> </div> </section> <!-- Products / Services / Licensing --> <h3 class="page-header"> Product / Service / Licensing </h3> <section class="container-fluid"> <div class="row mrgn-bttm-md"> <div class="col-md-3"> <strong> Product Name: </strong> </div> <div class="col-md-9"> SHUTTERS, WOODEN <br> </div> </div> </section> <p class="mrgn-tp-lg text-right small hidden-print"> <a href="#wb-cont">top of page</a> </p> <!-- Technology Profile --> <!-- Market Profile --> <h3 class="page-header"> Market profile </h3> <section class="container-fluid"> <h4> Geographic markets: </h4> <h5> Export experience: </h5> <ul> <li>United States</li> </ul> </section> <p class="mrgn-tp-lg text-right small hidden-print"> <a href="#wb-cont">top of page</a> </p> <!-- Sector Information --> <details class="mrgn-tp-md mrgn-bttm-md"> <summary> Third-Party Information Liability Disclaimer </summary> <p> Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements. </p> </details> </details> <details id="details-panel2"> <summary> Contacts </summary> <h2 class="wb-invisible"> Contact information </h2> <!-- Contact Information --> <section class="container-fluid"> <div class="row mrgn-tp-lg"> <div class="col-md-3"> <strong> Milan Gigic </strong></div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Title: </strong> </div> <div class="col-md-7"> <!--if client gender is not null or empty we use gender based job title--> Manager </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Area of Responsibility: </strong> </div> <div class="col-md-7"> Management Executive. </div> </div> <div class="row mrgn-tp-lg"> <div class="col-md-3"> <strong> Goran Gigic </strong></div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Title: </strong> </div> <div class="col-md-7"> <!--if client gender is not null or empty we use gender based job title--> Treasurer </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Telephone: </strong> </div> <div class="col-md-7"> (905) 953-0801 </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Facsimile: </strong> </div> <div class="col-md-7"> (905) 953-8247 </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Email: </strong> </div> <div class="col-md-7"> goran@canadacustomshutters.com </div> </div> </section> </details> <details id="details-panel3"> <summary> Description </summary> <h2 class="wb-invisible"> Company description </h2> <section class="container-fluid"> <div class="row"> <div class="col-md-5"> <strong> Country of Ownership: </strong> </div> <div class="col-md-7"> Canada &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Year Established: </strong> </div> <div class="col-md-7"> 1987 </div> </div> <div class="row"> <div class="col-md-5"> <strong> Exporting: </strong> </div> <div class="col-md-7"> Yes &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Primary Industry (NAICS): </strong> </div> <div class="col-md-7"> 321919 - Other Millwork </div> </div> <div class="row"> <div class="col-md-5"> <strong> Primary Business Activity: </strong> </div> <div class="col-md-7"> Manufacturer / Processor / Producer &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Total Sales ($CDN): </strong> </div> <div class="col-md-7"> $1,000,000 to $4,999,999&nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Export Sales ($CDN): </strong> </div> <div class="col-md-7"> $1 to $99,999&nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Number of Employees: </strong> </div> <div class="col-md-7"> 20&nbsp; </div> </div> </section> </details> <details id="details-panel4"> <summary> Products, services and licensing </summary> <h2 class="wb-invisible"> Product / Service / Licensing </h2> <section class="container-fluid"> <div class="row mrgn-bttm-md"> <div class="col-md-3"> <strong> Product Name: </strong> </div> <div class="col-md-9"> SHUTTERS, WOODEN <br> </div> </div> </section> </details> <details id="details-panel6"> <summary> Market </summary> <h2 class="wb-invisible"> Market profile </h2> <section class="container-fluid"> <h4> Geographic markets: </h4> <h5> Export experience: </h5> <ul> <li>United States</li> </ul> </section> </details> </div> </div> <div class="row"> <div class="col-md-12 text-right"> Last Update Date 2017-03-06 </div> </div> <!-- - Artifact ID: CBW - IMBS - CCC Search WAR - Group ID: ca.gc.ic.strategis.imbs.ccc.search - Version: 3.26 - Built-By: bamboo - Build Timestamp: 2017-03-02T21:29:28Z --> <!-- End Body Content --> <!-- Begin Body Foot --> <!-- End Body Foot --> <!-- END MAIN TABLE --> <!-- End body --> <!-- Begin footer --> <div class="row pagedetails"> <div class="col-sm-5 col-xs-12 datemod"> <dl id="wb-dtmd"> <dt class=" hidden-print">Date Modified:</dt> <dd class=" hidden-print"> <span><time>2017-03-02</time></span> </dd> </dl> </div> <div class="clear visible-xs"></div> <div class="col-sm-4 col-xs-6"> </div> <div class="col-sm-3 col-xs-6 text-right"> </div> <div class="clear visible-xs"></div> </div> </main> <footer role="contentinfo" id="wb-info"> <nav role="navigation" class="container wb-navcurr"> <h2 class="wb-inv">About government</h2> <!-- EPIC FOOTER BEGIN --> <!-- EPI-11638 Contact us --> <ul class="list-unstyled colcount-sm-2 colcount-md-3"> <li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07026.html#pageid=E048-H00000&amp;from=Industries">Contact us</a></li> <li><a href="https://www.canada.ca/en/government/dept.html">Departments and agencies</a></li> <li><a href="https://www.canada.ca/en/government/publicservice.html">Public service and military</a></li> <li><a href="https://www.canada.ca/en/news.html">News</a></li> <li><a href="https://www.canada.ca/en/government/system/laws.html">Treaties, laws and regulations</a></li> <li><a href="https://www.canada.ca/en/transparency/reporting.html">Government-wide reporting</a></li> <li><a href="http://pm.gc.ca/eng">Prime Minister</a></li> <li><a href="https://www.canada.ca/en/government/system.html">How government works</a></li> <li><a href="http://open.canada.ca/en/">Open government</a></li> </ul> </nav> <div class="brand"> <div class="container"> <div class="row"> <nav class="col-md-10 ftr-urlt-lnk"> <h2 class="wb-inv">About this site</h2> <ul> <li><a href="https://www.canada.ca/en/social.html">Social media</a></li> <li><a href="https://www.canada.ca/en/mobile.html">Mobile applications</a></li> <li><a href="http://www1.canada.ca/en/newsite.html">About Canada.ca</a></li> <li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html">Terms and conditions</a></li> <li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html#p1">Privacy</a></li> </ul> </nav> <div class="col-xs-6 visible-sm visible-xs tofpg"> <a href="#wb-cont">Top of Page <span class="glyphicon glyphicon-chevron-up"></span></a> </div> <div class="col-xs-6 col-md-2 text-right"> <object type="image/svg+xml" tabindex="-1" role="img" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/wmms-blk.svg" aria-label="Symbol of the Government of Canada"></object> </div> </div> </div> </div> </footer> <!--[if gte IE 9 | !IE ]><!--> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/wet-boew.min.js"></script> <!--<![endif]--> <!--[if lt IE 9]> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew2.min.js"></script> <![endif]--> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/theme.min.js"></script> <!-- EPI-10519 --> <span class="wb-sessto" data-wb-sessto='{"inactivity": 1800000, "reactionTime": 180000, "sessionalive": 1800000, "logouturl": "/app/ccc/srch/cccSrch.do?lang=eng&prtl=1"}'></span> <script src="/eic/home.nsf/js/jQuery.externalOpensInNewWindow.js"></script> <!-- EPI-11190 - Webtrends --> <script src="/eic/home.nsf/js/webtrends.js"></script> <script>var endTime = new Date();</script> <noscript> <div><img alt="" id="DCSIMG" width="1" height="1" src="//wt-sdc.ic.gc.ca/dcs6v67hwe0ei7wsv8g9fv50d_3k6i/njs.gif?dcsuri=/nojavascript&amp;WT.js=No&amp;WT.tv=9.4.0&amp;dcssip=www.ic.gc.ca"/></div> </noscript> <!-- /Webtrends --> <!-- JS deps --> <script src="/eic/home.nsf/js/jquery.imagesloaded.js"></script> <!-- EPI-11262 - Util JS --> <script src="/eic/home.nsf/js/_WET_4-0_utils_canada.min.js"></script> <!-- EPI-11383 --> <script src="/eic/home.nsf/js/jQuery.icValidationErrors.js"></script> <span style="display:none;" id='app-info' data-project-groupid='' data-project-artifactid='' data-project-version='' data-project-build-timestamp='' data-issue-tracking='' data-scm-sha1='' data-scm-sha1-abbrev='' data-scm-branch='' data-scm-commit-date=''></span> </body></html> <!-- End Footer --> <!-- - Artifact ID: CBW - IMBS - CCC Search WAR - Group ID: ca.gc.ic.strategis.imbs.ccc.search - Version: 3.26 - Built-By: bamboo - Build Timestamp: 2017-03-02T21:29:28Z -->
GoC-Spending/data-corporations
html/123456204733.html
HTML
mit
39,817
14.779231
444
0.407601
false
// // SwiftMan.h // SwiftMan // // Created by yangjun on 16/4/29. // Copyright © 2016年 yangjun. All rights reserved. // #import "TargetConditionals.h" #if TARGET_OS_IPHONE #import <UIKit/UIKit.h> #elif TARGET_OS_MAC #import <Cocoa/Cocoa.h> #elif TARGET_OS_WATCH #import <WatchKit/WatchKit.h> #endif //! Project version number for SwiftMan. FOUNDATION_EXPORT double SwiftManVersionNumber; //! Project version string for SwiftMan. FOUNDATION_EXPORT const unsigned char SwiftManVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <SwiftMan/PublicHeader.h>
easyui/SwiftMan
SwiftMan/SwiftMan.h
C
mit
641
21.785714
133
0.750784
false
/* * @brief This file contains USB HID Keyboard example using USB ROM Drivers. * * @note * Copyright(C) NXP Semiconductors, 2013 * All rights reserved. * * @par * Software that is described herein is for illustrative purposes only * which provides customers with programming information regarding the * LPC products. This software is supplied "AS IS" without any warranties of * any kind, and NXP Semiconductors and its licensor disclaim any and * all warranties, express or implied, including all implied warranties of * merchantability, fitness for a particular purpose and non-infringement of * intellectual property rights. NXP Semiconductors assumes no responsibility * or liability for the use of the software, conveys no license or rights under any * patent, copyright, mask work right, or any other intellectual property rights in * or to any products. NXP Semiconductors reserves the right to make changes * in the software without notification. NXP Semiconductors also makes no * representation or warranty that such application will be suitable for the * specified use without further testing or modification. * * @par * Permission to use, copy, modify, and distribute this software and its * documentation is hereby granted, under NXP Semiconductors' and its * licensor's relevant copyrights in the software, without fee, provided that it * is used in conjunction with NXP Semiconductors microcontrollers. This * copyright, permission, and disclaimer notice must appear in all copies of * this code. */ #include "board.h" #include <stdint.h> #include <string.h> #include "usbd_rom_api.h" #include "hid_keyboard.h" #include "ms_timer.h" /***************************************************************************** * Private types/enumerations/variables ****************************************************************************/ /** * @brief Structure to hold Keyboard data */ typedef struct { USBD_HANDLE_T hUsb; /*!< Handle to USB stack. */ uint8_t report[KEYBOARD_REPORT_SIZE]; /*!< Last report data */ uint8_t tx_busy; /*!< Flag indicating whether a report is pending in endpoint queue. */ ms_timer_t tmo; /*!< Timer to track when to send next report. */ } Keyboard_Ctrl_T; /** Singleton instance of Keyboard control */ static Keyboard_Ctrl_T g_keyBoard; /***************************************************************************** * Public types/enumerations/variables ****************************************************************************/ extern const uint8_t Keyboard_ReportDescriptor[]; extern const uint16_t Keyboard_ReportDescSize; /***************************************************************************** * Private functions ****************************************************************************/ /* Routine to update keyboard state */ static void Keyboard_UpdateReport(void) { uint8_t joystick_status = Joystick_GetStatus(); HID_KEYBOARD_CLEAR_REPORT(&g_keyBoard.report[0]); switch (joystick_status) { case JOY_PRESS: HID_KEYBOARD_REPORT_SET_KEY_PRESS(g_keyBoard.report, 0x53); break; case JOY_LEFT: HID_KEYBOARD_REPORT_SET_KEY_PRESS(g_keyBoard.report, 0x5C); break; case JOY_RIGHT: HID_KEYBOARD_REPORT_SET_KEY_PRESS(g_keyBoard.report, 0x5E); break; case JOY_UP: HID_KEYBOARD_REPORT_SET_KEY_PRESS(g_keyBoard.report, 0x60); break; case JOY_DOWN: HID_KEYBOARD_REPORT_SET_KEY_PRESS(g_keyBoard.report, 0x5A); break; } } /* HID Get Report Request Callback. Called automatically on HID Get Report Request */ static ErrorCode_t Keyboard_GetReport(USBD_HANDLE_T hHid, USB_SETUP_PACKET *pSetup, uint8_t * *pBuffer, uint16_t *plength) { /* ReportID = SetupPacket.wValue.WB.L; */ switch (pSetup->wValue.WB.H) { case HID_REPORT_INPUT: Keyboard_UpdateReport(); memcpy(*pBuffer, &g_keyBoard.report[0], KEYBOARD_REPORT_SIZE); *plength = KEYBOARD_REPORT_SIZE; break; case HID_REPORT_OUTPUT: /* Not Supported */ case HID_REPORT_FEATURE: /* Not Supported */ return ERR_USBD_STALL; } return LPC_OK; } /* HID Set Report Request Callback. Called automatically on HID Set Report Request */ static ErrorCode_t Keyboard_SetReport(USBD_HANDLE_T hHid, USB_SETUP_PACKET *pSetup, uint8_t * *pBuffer, uint16_t length) { /* we will reuse standard EP0Buf */ if (length == 0) { return LPC_OK; } /* ReportID = SetupPacket.wValue.WB.L; */ switch (pSetup->wValue.WB.H) { case HID_REPORT_OUTPUT: /* If the USB host tells us to turn on the NUM LOCK LED, * then turn on LED#2. */ if (**pBuffer & 0x01) { Board_LED_Set(0, 1); } else { Board_LED_Set(0, 0); } break; case HID_REPORT_INPUT: /* Not Supported */ case HID_REPORT_FEATURE: /* Not Supported */ return ERR_USBD_STALL; } return LPC_OK; } /* HID interrupt IN endpoint handler */ static ErrorCode_t Keyboard_EpIN_Hdlr(USBD_HANDLE_T hUsb, void *data, uint32_t event) { switch (event) { case USB_EVT_IN: g_keyBoard.tx_busy = 0; break; } return LPC_OK; } /***************************************************************************** * Public functions ****************************************************************************/ /* HID keyboard init routine */ ErrorCode_t Keyboard_init(USBD_HANDLE_T hUsb, USB_INTERFACE_DESCRIPTOR *pIntfDesc, uint32_t *mem_base, uint32_t *mem_size) { USBD_HID_INIT_PARAM_T hid_param; USB_HID_REPORT_T reports_data[1]; ErrorCode_t ret = LPC_OK; /* Do a quick check of if the interface descriptor passed is the right one. */ if ((pIntfDesc == 0) || (pIntfDesc->bInterfaceClass != USB_DEVICE_CLASS_HUMAN_INTERFACE)) { return ERR_FAILED; } /* init joystick control */ Board_Joystick_Init(); /* Init HID params */ memset((void *) &hid_param, 0, sizeof(USBD_HID_INIT_PARAM_T)); hid_param.max_reports = 1; hid_param.mem_base = *mem_base; hid_param.mem_size = *mem_size; hid_param.intf_desc = (uint8_t *) pIntfDesc; /* user defined functions */ hid_param.HID_GetReport = Keyboard_GetReport; hid_param.HID_SetReport = Keyboard_SetReport; hid_param.HID_EpIn_Hdlr = Keyboard_EpIN_Hdlr; /* Init reports_data */ reports_data[0].len = Keyboard_ReportDescSize; reports_data[0].idle_time = 0; reports_data[0].desc = (uint8_t *) &Keyboard_ReportDescriptor[0]; hid_param.report_data = reports_data; ret = USBD_API->hid->init(hUsb, &hid_param); /* update memory variables */ *mem_base = hid_param.mem_base; *mem_size = hid_param.mem_size; /* store stack handle for later use. */ g_keyBoard.hUsb = hUsb; /* start the mouse timer */ ms_timerInit(&g_keyBoard.tmo, HID_KEYBRD_REPORT_INTERVAL_MS); return ret; } /* Keyboard tasks */ void Keyboard_Tasks(void) { /* check if moue report timer expired */ if (ms_timerExpired(&g_keyBoard.tmo)) { /* reset timer */ ms_timerStart(&g_keyBoard.tmo); /* check device is configured before sending report. */ if ( USB_IsConfigured(g_keyBoard.hUsb)) { /* update report based on board state */ Keyboard_UpdateReport(); /* send report data */ if (g_keyBoard.tx_busy == 0) { g_keyBoard.tx_busy = 1; USBD_API->hw->WriteEP(g_keyBoard.hUsb, HID_EP_IN, &g_keyBoard.report[0], KEYBOARD_REPORT_SIZE); } } } }
miragecentury/M2_SE_RTOS_Project
Project/LPC1549_Keil/examples/usbd_rom/usbd_rom_hid_keyboard/hid_keyboard.c
C
mit
7,219
31.084444
120
0.643995
false
'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
22.9125
106
0.515167
false
/** * 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
15.944444
55
0.67541
false
PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\ call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" msbuild steamworks4j.sln /p:Configuration=ReleaseDLL /p:Platform=Win32 /t:Rebuild move steamworks4j.dll ..\natives\libs\steamworks4j.dll copy ..\sdk\redistributable_bin\steam_api.dll ..\natives\libs\steam_api.dll msbuild steamworks4j.sln /p:Configuration=ReleaseDLL /p:Platform=x64 /t:Rebuild move steamworks4j.dll ..\natives\libs\steamworks4j64.dll copy ..\sdk\redistributable_bin\win64\steam_api64.dll ..\natives\libs\steam_api64.dll pause
franzbischoff/steamworks4j
build-natives/build-win.bat
Batchfile
mit
631
68.333333
104
0.789223
false
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_101) on Mon Sep 19 15:00:46 UTC 2016 --> <title>org.springframework.oxm.xmlbeans Class Hierarchy (Spring Framework 4.3.3.RELEASE API)</title><script>var _hmt = _hmt || [];(function() {var hm = document.createElement("script");hm.src = "//hm.baidu.com/hm.js?dd1361ca20a10cc161e72d4bc4fef6df";var s = document.getElementsByTagName("script")[0];s.parentNode.insertBefore(hm, s);})();</script> <meta name="date" content="2016-09-19"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.springframework.oxm.xmlbeans Class Hierarchy (Spring Framework 4.3.3.RELEASE API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Spring Framework</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/springframework/oxm/support/package-tree.html">Prev</a></li> <li><a href="../../../../org/springframework/oxm/xstream/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/springframework/oxm/xmlbeans/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For Package org.springframework.oxm.xmlbeans</h1> <span class="packageHierarchyLabel">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">org.springframework.oxm.support.<a href="../../../../org/springframework/oxm/support/AbstractMarshaller.html" title="class in org.springframework.oxm.support"><span class="typeNameLink">AbstractMarshaller</span></a> (implements org.springframework.oxm.<a href="../../../../org/springframework/oxm/Marshaller.html" title="interface in org.springframework.oxm">Marshaller</a>, org.springframework.oxm.<a href="../../../../org/springframework/oxm/Unmarshaller.html" title="interface in org.springframework.oxm">Unmarshaller</a>) <ul> <li type="circle">org.springframework.oxm.xmlbeans.<a href="../../../../org/springframework/oxm/xmlbeans/XmlBeansMarshaller.html" title="class in org.springframework.oxm.xmlbeans"><span class="typeNameLink">XmlBeansMarshaller</span></a></li> </ul> </li> <li type="circle">org.springframework.oxm.xmlbeans.<a href="../../../../org/springframework/oxm/xmlbeans/XmlOptionsFactoryBean.html" title="class in org.springframework.oxm.xmlbeans"><span class="typeNameLink">XmlOptionsFactoryBean</span></a> (implements org.springframework.beans.factory.<a href="../../../../org/springframework/beans/factory/FactoryBean.html" title="interface in org.springframework.beans.factory">FactoryBean</a>&lt;T&gt;)</li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Spring Framework</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/springframework/oxm/support/package-tree.html">Prev</a></li> <li><a href="../../../../org/springframework/oxm/xstream/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/springframework/oxm/xmlbeans/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
piterlin/piterlin.github.io
doc/spring4.3.3-docs/javadoc-api/org/springframework/oxm/xmlbeans/package-tree.html
HTML
mit
6,315
43.471831
543
0.654473
false
<?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
51.350515
172
0.749705
false
<?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
24.452991
107
0.527625
false
<?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
26.665493
139
0.371516
false
# Install on Laravel Forge 1. Disable nginx with `sudo update-rc.d -f nginx disable` 2. Create a new site for your blog, and install this Git Repository 3. Execute `npm install --production` in `/home/forge/{YOUR_GHOST_BLOG_SITE_NAME}`. 4. Reboot your server 5. Add a daenom for the root user that executes `npm start /home/forge/{YOUR_GHOST_BLOG_SITE_NAME} --production` 6. Update your deploy script to look like this: cd /home/forge/{YOUR_GHOST_BLOG_SITE_NAME} git pull origin master npm install --production forge daemon:restart {YOUR_DAEMON_ID} 7. Ta da!
adamgoose/ghost-blog
README.md
Markdown
mit
593
38.6
112
0.711636
false
""" 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
23.5625
78
0.770992
false
# 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
20.542857
85
0.689243
false
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
25.230769
98
0.675953
false
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
17.807692
68
0.650307
false
<?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
17.92
56
0.636364
false
package com.mvas.webproxy.portals; import com.mvas.webproxy.DeviceConnectionInfo; import com.mvas.webproxy.RequestData; import com.mvas.webproxy.WebServer; import com.mvas.webproxy.config.PortalConfiguration; import org.apache.commons.io.IOUtils; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StalkerRequestHandler implements AbstractRequestHandler { private static final Logger logger = LoggerFactory.getLogger(StalkerRequestHandler.class); public static final String GET_PARAM_DEVICE_ID = "device_id"; public static final String GET_PARAM_DEVICE_ID2 = "device_id2"; public static final String GET_PARAM_SIGNATURE = "signature"; public static final String GET_PARAM_SESSION = "session"; public static final String CONFIG_PORTAL_URL = "portal"; public static final String GET_PARAM_MAC_ADDRESS = "mac"; public static final String ACTION_HANDSHAKE = "action=handshake"; Pattern cookiePattern = Pattern.compile(".*mac=(([0-9A-F]{2}[:-]){5}([0-9A-F]{2})).*"); Pattern handshakePattern = Pattern.compile(ACTION_HANDSHAKE); public static final String HEADER_AUTHORIZATION = "Authorization"; public static final class HeadersList { public HashMap<String, String> getList() { return list; } private HashMap<String, String> list = new HashMap<>(); } public static final class ParamsList { public HashMap<String, String> getList() { return list; } private HashMap<String, String> list = new HashMap<>(); } public HashMap<String, HeadersList> staticHeadersForMac = new HashMap<>(); public HashMap<String, ParamsList> staticParamsForMac = new HashMap<>(); DeviceConnectionInfo deviceConnectionInfo; static HashMap<String, Pattern> replacements = new HashMap<>(); static String[] configOptions; static String[] getParamNames; static { getParamNames = new String[] { GET_PARAM_DEVICE_ID, GET_PARAM_DEVICE_ID2, GET_PARAM_SIGNATURE, GET_PARAM_SESSION }; for (String name : getParamNames) { replacements.put(name, Pattern.compile("([\\?&])?(" + name + ")=([a-zA-Z0-9/+]*)")); } configOptions = new String[] { GET_PARAM_DEVICE_ID, GET_PARAM_DEVICE_ID2, GET_PARAM_SIGNATURE, GET_PARAM_SESSION, CONFIG_PORTAL_URL, GET_PARAM_MAC_ADDRESS }; } private HeadersList getHeadersForRequest(final RequestData requestData) { return staticHeadersForMac.get(requestData.getMacAddress()); } private ParamsList getParamsForRequest(final RequestData requestData) { return staticParamsForMac.get(requestData.getMacAddress()); } public StalkerRequestHandler(DeviceConnectionInfo deviceConnectionInfo) { this.deviceConnectionInfo = deviceConnectionInfo; } @Override public String getURL(final RequestData requestData) { logger.debug("StalkerRequestHandler::getURL()"); String result = requestData.getRealUrl().toString(); HashMap<String, String> staticParams = getParamsForRequest(requestData).getList(); for(Map.Entry<String, Pattern> entry: replacements.entrySet()) { Matcher matcher = entry.getValue().matcher(result); if(matcher.find()) { String name = matcher.group(2); if(staticParams.get(name) == null) { String value = matcher.group(3); staticParams.put(name, value); logger.debug("set static param [" + name + "] to [" + value + "]"); if(name.equals(GET_PARAM_DEVICE_ID)) WebServer.getPortalConfiguration().set(requestData.getConnectionName(), name, value); if(name.equals(GET_PARAM_DEVICE_ID2)) WebServer.getPortalConfiguration().set(requestData.getConnectionName(), name, value); } } } for(Map.Entry<String, Pattern> rep: replacements.entrySet()) { Pattern from = rep.getValue(); String to = rep.getKey(); result = result.replaceAll(from.pattern(), "$1$2=" + staticParams.get(to)); } logger.debug("New query string: " + result); return result; } @Override public void onRequest(final RequestData requestData, final URLConnection urlConnection) { logger.debug("StalkerRequestHandler::onRequest()"); HashMap<String, String> staticHeaders = getHeadersForRequest(requestData).getList(); for(Map.Entry<String, String> header: requestData.getHeaders().entrySet()) { String headerName = header.getKey(); String headerValue = header.getValue(); if(headerName.equals(HEADER_AUTHORIZATION)) { if(staticHeaders.get(HEADER_AUTHORIZATION) == null) staticHeaders.put(HEADER_AUTHORIZATION, headerValue); else { String authorizationHeader = staticHeaders.get(HEADER_AUTHORIZATION); if(headerValue.equals(authorizationHeader)) continue; logger.debug("Overwriting [" + HEADER_AUTHORIZATION + "] from {" + headerValue + " } to {" + authorizationHeader + "}"); urlConnection.setRequestProperty(HEADER_AUTHORIZATION, authorizationHeader); } } } } @Override public InputStream onResponse(final RequestData requestData, final InputStream iStream) { logger.debug("StalkerRequestHandler::onResponse()"); String target = requestData.getTarget(); if(!target.contains(".php")) return iStream; try { String data = IOUtils.toString(iStream); Matcher matcher = handshakePattern.matcher(requestData.getRealUrl().toString()); if(matcher.find()) { processHandshake(requestData, data); } return IOUtils.toInputStream(data); } catch (IOException e) { e.printStackTrace(); } return iStream; } @Override public void onBeforeRequest(final RequestData requestData, final PortalConfiguration portalConfiguration) { logger.debug("StalkerRequestHandler::onBeforeRequest()"); String macAddress = requestData.getMacAddress(); if(macAddress == null || macAddress.isEmpty()) { String cookie = requestData.getCookie().replace("%3A", ":"); Matcher matcher = cookiePattern.matcher(cookie); if(matcher.find()) { requestData.setMacAddress(matcher.group(1)); macAddress = matcher.group(1); logger.debug("MAC: " + matcher.group(1)); } else macAddress = "empty"; } if(!staticHeadersForMac.containsKey(macAddress)) staticHeadersForMac.put(macAddress, new HeadersList()); HashMap<String, String> staticHeaders = getHeadersForRequest(requestData).getList(); String token = portalConfiguration.get(requestData.getConnectionName(), "token"); if(token != null) staticHeaders.put(HEADER_AUTHORIZATION, "Bearer " + token); if(!staticParamsForMac.containsKey(macAddress)) { ParamsList params = new ParamsList(); HashMap<String, String> list = params.getList(); for(String name: configOptions) { String value = portalConfiguration.get(requestData.getConnectionName(), name); if(value == null) { logger.debug("Skipping NULL config value [" + name + "]"); continue; } logger.debug("Loading {" + name + "} -> {" + value + "}"); list.put(name, value); } staticParamsForMac.put(macAddress, params); } try { requestData.setRealUrl(new URL(getURL(requestData))); } catch (MalformedURLException e) { e.printStackTrace(); } } public void processHandshake(final RequestData requestData, final String data) { logger.debug("StalkerRequestHandler::processHandshake()"); HashMap<String, String> staticHeaders = getHeadersForRequest(requestData).getList(); JSONObject json; try { json = new JSONObject(data); JSONObject js = json.getJSONObject("js"); String token = js.getString("token"); staticHeaders.put(HEADER_AUTHORIZATION, "Bearer " + token); WebServer.getPortalConfiguration().set(requestData.getConnectionName(), "token", token); } catch (JSONException e) { e.printStackTrace(); } } }
mvasilchuk/webproxy
src/main/java/com/mvas/webproxy/portals/StalkerRequestHandler.java
Java
mit
9,322
35.272374
140
0.615104
false
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> :head :fbthumb </head> <body> <div id="wrapper"> <header> <div class="container"> <h1 class="col four"> <a href="@root_path/" class="logo">@name</a> </h1> <div class="col six nav"> <div class=navItems> :pages </div> </div> </div> </header> <div id="content" class="container" role="main"> <div class="description col four"> <h1>@title</h1> <p>@description</p> </div> <div class="col seven"> :media @content </div> <hr class="push"> </div> :footer </div> :analytics </body> </html>
senordavis/drawings
templates/contact.html
HTML
mit
741
13.54902
50
0.504723
false
/** * 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
33.257813
126
0.580988
false
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
39.402878
147
0.564737
false
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
26.454545
93
0.648344
false
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
18.777778
40
0.723164
false
version https://git-lfs.github.com/spec/v1 oid sha256:8ecad6ce4ab24b16dd86e293b01f4b3d0ea62911d34288c6c78a9e6fe6b7da46 size 4972
yogeshsaroya/new-cdnjs
ajax/libs/semantic-ui/1.11.3/components/image.css
CSS
mit
129
42
75
0.883721
false
<?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
19.333333
90
0.61699
false
// 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
34.600526
120
0.568575
false
<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
44.673077
183
0.424842
false
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
20.56
87
0.586271
false
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
20.368687
49
0.364453
false
<?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
21.844037
80
0.592607
false
<!DOCTYPE html> <html> <head> <link href="css/awsdocs.css" rel="stylesheet" type="text/css"> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/awsdocs.min.js"></script> <meta charset="utf-8"> </head> <body> <div id="content" style="padding: 10px 30px;"> <h1 class="topictitle" id="aws-resource-route53-hostedzone">AWS::Route53::HostedZone</h1><p>The <code class="code">AWS::Route53::HostedZone</code> resource creates a hosted zone, which can contain a collection of record sets for a domain. You cannot create a hosted zone for a top-level domain (TLD). For more information, see <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_CreateHostedZone.html">POST CreateHostedZone</a> or <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API-create-hosted-zone-private.html">POST CreateHostedZone (Private)</a> in the <em>Amazon Route&#xA0;53 API Reference</em>. </p><h2 id="aws-resource-route53-hostedzone-syntax">Syntax</h2><p>To declare this entity in your AWS CloudFormation template, use the following syntax:</p><div id="JSON" name="JSON" class="section langfilter"> <h3 id="aws-resource-route53-hostedzone-syntax.json">JSON</h3> <pre class="programlisting"><div class="code-btn-container"><div class="btn-copy-code" title="Copy"></div><div class="btn-dark-theme" title="Dark theme" title-dark="Dark theme" title-light="Light theme"></div></div><code class="nohighlight">{ &quot;Type&quot; : &quot;AWS::Route53::HostedZone&quot;, &quot;Properties&quot; : { &quot;<a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-hostedzoneconfig">HostedZoneConfig</a>&quot; : <a href="aws-properties-route53-hostedzone-hostedzoneconfig.html">HostedZoneConfig</a>, &quot;<a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-hostedzonetags">HostedZoneTags</a>&quot; : [ <a href="aws-properties-route53-hostedzone-hostedzonetags.html">HostedZoneTags</a>, ... ], &quot;<a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-name">Name</a>&quot; : <em class="replaceable"><code>String</code></em>, &quot;<a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-queryloggingconfig">QueryLoggingConfig</a>&quot; : <a href="aws-properties-route53-hostedzone-queryloggingconfig.html">QueryLoggingConfig</a>, &quot;<a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-vpcs">VPCs</a>&quot; : [ <a href="aws-resource-route53-hostedzone-hostedzonevpcs.html">HostedZoneVPCs</a>, ... ] } }</code></pre> </div><div id="YAML" name="YAML" class="section langfilter"> <h3 id="aws-resource-route53-hostedzone-syntax.yaml">YAML</h3> <pre class="programlisting"><div class="code-btn-container"><div class="btn-copy-code" title="Copy"></div><div class="btn-dark-theme" title="Dark theme" title-dark="Dark theme" title-light="Light theme"></div></div><code class="nohighlight">Type: &quot;AWS::Route53::HostedZone&quot; Properties: <a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-hostedzoneconfig">HostedZoneConfig</a>: <a href="aws-properties-route53-hostedzone-hostedzoneconfig.html">HostedZoneConfig</a> <a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-hostedzonetags">HostedZoneTags</a>: - <a href="aws-properties-route53-hostedzone-hostedzonetags.html">HostedZoneTags</a> <a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-name">Name</a>: <em class="replaceable"><code>String</code></em> <a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-queryloggingconfig">QueryLoggingConfig</a>: <a href="aws-properties-route53-hostedzone-queryloggingconfig.html">QueryLoggingConfig</a> <a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-vpcs">VPCs</a>: - <a href="aws-resource-route53-hostedzone-hostedzonevpcs.html">HostedZoneVPCs</a> </code></pre> </div><h2 id="w2ab1c21c10d201c18b7">Properties</h2><div class="variablelist"> <dl> <dt><a id="cfn-route53-hostedzone-hostedzoneconfig"></a><span class="term"><code class="code">HostedZoneConfig</code></span></dt> <dd> <p>A complex type that contains an optional comment about your hosted zone.</p> <p><em>Required</em>: No </p> <p><em>Type</em>: <a href="aws-properties-route53-hostedzone-hostedzoneconfig.html">Route&#xA0;53 HostedZoneConfig Property</a></p> <p><em>Update requires</em>: <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-no-interrupt">No interruption</a></p> </dd> <dt><a id="cfn-route53-hostedzone-hostedzonetags"></a><span class="term"><code class="code">HostedZoneTags</code></span></dt> <dd> <p>An arbitrary set of tags (key&#x2013;value pairs) for this hosted zone.</p> <p><em>Required</em>: No </p> <p><em>Type</em>: List of <a href="aws-properties-route53-hostedzone-hostedzonetags.html">Amazon Route&#xA0;53 HostedZoneTags</a></p> <p><em>Update requires</em>: <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-no-interrupt">No interruption</a></p> </dd> <dt><a id="cfn-route53-hostedzone-name"></a><span class="term"><code class="code">Name</code></span></dt> <dd> <p>The name of the domain. For resource record types that include a domain name, specify a fully qualified domain name. </p> <p><em>Required</em>: Yes </p> <p><em>Type</em>: String </p> <p><em>Update requires</em>: <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-replacement">Replacement</a></p> </dd> <dt><a id="cfn-route53-hostedzone-queryloggingconfig"></a><span class="term"><code class="code">QueryLoggingConfig</code></span></dt> <dd> <p>The configuration for DNS query logging.</p> <p><em>Required</em>: No </p> <p><em>Type</em>: <a href="aws-properties-route53-hostedzone-queryloggingconfig.html">Route&#xA0;53 QueryLoggingConfig</a></p> <p><em>Update requires</em>: <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-no-interrupt">No interruption</a></p> </dd> <dt><a id="cfn-route53-hostedzone-vpcs"></a><span class="term"><code class="code">VPCs</code></span></dt> <dd> <p>One or more VPCs that you want to associate with this hosted zone. When you specify this property, AWS CloudFormation creates a private hosted zone. </p> <p><em>Required</em>: No </p> <p><em>Type</em>: List of <a href="aws-resource-route53-hostedzone-hostedzonevpcs.html">Route&#xA0;53 HostedZoneVPCs</a></p> <p>If this property was specified previously and you&apos;re modifying values, updates require <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-no-interrupt">no interruption</a>. If this property wasn&apos;t specified and you add values, updates require <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-replacement">replacement</a>. Also, if this property was specified and you remove all values, updates require <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-replacement">replacement</a>. </p> </dd> </dl> </div><h2 id="w2ab1c21c10d201c18b9">Return Values</h2><h3 id="w2ab1c21c10d201c18b9b2">Ref</h3><p>When the logical ID of this resource is provided to the <code class="code">Ref</code> intrinsic function, <code class="code">Ref</code> returns the hosted zone ID, such as <code class="code">Z23ABC4XYZL05B</code>. </p><p>For more information about using the <code class="code">Ref</code> function, see <a href="intrinsic-function-reference-ref.html">Ref</a>. </p><h3 id="w2ab1c21c10d201c18b9b4">Fn::GetAtt</h3><p><code class="code">Fn::GetAtt</code> returns a value for a specified attribute of this type. The following are the available attributes and sample return values. </p><div class="variablelist"> <dl> <dt><span class="term"><code class="literal">NameServers</code></span></dt> <dd> <p>Returns the set of name servers for the specific hosted zone. For example: <code class="code">ns1.example.com</code>. </p> <p>This attribute is not supported for private hosted zones.</p> </dd> </dl> </div><p>For more information about using <code class="code">Fn::GetAtt</code>, see <a href="intrinsic-function-reference-getatt.html">Fn::GetAtt</a>. </p><h2 id="w2ab1c21c10d201c18c11">Example</h2><p>The following template snippet creates a private hosted zone for the <code class="code">example.com</code> domain. </p><div id="JSON" name="JSON" class="section langfilter"> <h3 id="aws-resource-route53-hostedzone-example.json">JSON</h3> <pre class="programlisting"><div class="code-btn-container"><div class="btn-copy-code" title="Copy"></div><div class="btn-dark-theme" title="Dark theme" title-dark="Dark theme" title-light="Light theme"></div></div><code class="nohighlight ">&quot;DNS&quot;: { &quot;Type&quot;: &quot;AWS::Route53::HostedZone&quot;, &quot;Properties&quot;: { &quot;HostedZoneConfig&quot;: { &quot;Comment&quot;: &quot;My hosted zone for example.com&quot; }, &quot;Name&quot;: &quot;example.com&quot;, &quot;VPCs&quot;: [{ &quot;VPCId&quot;: &quot;vpc-abcd1234&quot;, &quot;VPCRegion&quot;: &quot;ap-northeast-1&quot; }, { &quot;VPCId&quot;: &quot;vpc-efgh5678&quot;, &quot;VPCRegion&quot;: &quot;us-west-2&quot; }], &quot;HostedZoneTags&quot; : [{ &quot;Key&quot;: &quot;SampleKey1&quot;, &quot;Value&quot;: &quot;SampleValue1&quot; }, { &quot;Key&quot;: &quot;SampleKey2&quot;, &quot;Value&quot;: &quot;SampleValue2&quot; }] } }</code></pre> </div><div id="YAML" name="YAML" class="section langfilter"> <h3 id="aws-resource-route53-hostedzone-example.yaml">YAML</h3> <pre class="programlisting"><div class="code-btn-container"><div class="btn-copy-code" title="Copy"></div><div class="btn-dark-theme" title="Dark theme" title-dark="Dark theme" title-light="Light theme"></div></div><code class="nohighlight ">DNS: Type: &quot;AWS::Route53::HostedZone&quot; Properties: HostedZoneConfig: Comment: &quot;My hosted zone for example.com&quot; Name: &quot;example.com&quot; VPCs: - VPCId: &quot;vpc-abcd1234&quot; VPCRegion: &quot;ap-northeast-1&quot; - VPCId: &quot;vpc-efgh5678&quot; VPCRegion: &quot;us-west-2&quot; HostedZoneTags: - Key: &quot;SampleKey1&quot; Value: &quot;SampleValue1&quot; - Key: &quot;SampleKey2&quot; Value: &quot;SampleValue2&quot;</code></pre> </div></div> </body> </html>
pdhodgkinson/AWSCloudFormationTemplateReference-dash-docset
AWS_CloudFormation_Template_Reference.docset/Contents/Resources/Documents/aws-resource-route53-hostedzone.html
HTML
mit
14,906
65.847534
308
0.524688
false
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
26.25
88
0.59633
false
2020-02-24: Development Meeting =============================== Kacper, Craig, Mike H, Tim, Elias, Mike L, Tommy Agenda ------ * Updates * AHM - [name=Kacper] * 03/04/2020 10am - 5pm CDT * https://illinois.zoom.us/j/583802454 * for people @ NCSA: we gather in NCSA-2000 * optionally 04/04/2020 10am - 1pm (tbd) * THE NEWS * v0.10 / v1.0 planning? - [name=Craig] * v1.0: Tommy / v0.10: Kacper * Angular migration (waiting on the rest of us) * Versioning (backend close, needs testing; UI partially defined) * r2d composability (needs testing) * Sharing * Current activities: * Prov model * What we could get from just reprozip * Expansion out from that (~2 months) that could be part of a reproducible run * On deck * Git integration * Dataverse publishing * Image preservation * Reproducible run * MATLAB support (doable now) * Stata support * Ability to configure resources * Associate tale with manuscript * Link directly to tales from publication Updates ------- * Kacper * Related identifiers * Tale model update + import [girder_wholetale#391](https://github.com/whole-tale/girder_wholetale/pull/391) * Changes to Tale's metadata view [dashboard#595](https://github.com/whole-tale/dashboard/pull/595) * Use related identifiers to populate Zenodo's metadata [gwvolman#102](https://github.com/whole-tale/gwvolman/pull/102) * Refactored AinWT import jobs - [girder_wholetale#389](https://github.com/whole-tale/girder_wholetale/pull/389) * Imported (AinWT) Tales are singletons now [girder_wholetale#396](https://github.com/whole-tale/girder_wholetale/pull/396) * Minor fix to our bag export - [girder_wholetale#395](https://github.com/whole-tale/girder_wholetale/pull/395) * Hopefully tag and deploy rc2 today (demo tomorrow) * Craig * PresQT integration testing n * PR review and testing * Annual report * Mike H * Continue to work on versioning * Tim * Working on EarthCube proposal for next 2.5 weeks. * Implemented the example "script" (RMarkdown) for WT-C2Metadata project as a repo that can be run in place with Docker: https://github.com/tmcphillips/all-harvest-rippo * To run from outside a container: * git clone * git status * make clean * git status * make run * git status * To run with rstudio running in the container: * make rstudio * connect to http://localhost:8787 * Will be dropping in the ReproZip stuff to see what we can see. * Will we see downloading of input data sets? * Tommy * Few small fixes to file uploading UI * Few small fixes for error messages on various tale creation methods * Review * Prioritizing PR reviews for RC2 * Did a some work on a WT screencast/intro video * I estimate 2 hours fo work left before it's a complete rough draft * Elias * Began testing on staging * Web UI: Server notification counter shows up on top of logs * Mike L * Reviewed open dashboard PRs from Tommy and Kacper * Made a couple of other minor PRs * [Update label on Select Data submit button](https://github.com/whole-tale/dashboard/pull/598) * [Save filter state on Browse view across refresh / navigation](https://github.com/whole-tale/dashboard/pull/599) * [Tale title truncation on Run view](https://github.com/whole-tale/dashboard/pull/600)
whole-tale/wt-design-docs
development/meetings/2020-02-24.md
Markdown
mit
3,620
39.674157
174
0.653591
false
<?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
32.913043
95
0.531731
false
/* * Webpack development server configuration * * This file is set up for serving the webpack-dev-server, which will watch for changes and recompile as required if * the subfolder /webpack-dev-server/ is visited. Visiting the root will not automatically reload. */ 'use strict'; import webpack from 'webpack'; import path from 'path'; import autoprefixer from 'autoprefixer'; const API_URL = process.env['__API_URL__'] || 'http://localhost:3001/'; //eslint-disable-line export default { output: { path: path.join(__dirname, '.tmp'), filename: 'bundle.js', publicPath: '/static/' }, devtool: 'eval-source-map', entry: [ 'whatwg-fetch', 'webpack-dev-server/client?http://0.0.0.0:3000', 'webpack/hot/only-dev-server', 'react-hot-loader/patch', './src/index.js' ], module: { preLoaders: [{ test: /\.(js|jsx)$/, exclude: [/node_modules/, /vendor/], loader: 'eslint-loader' }], loaders: [{ test: /\.(js|jsx)$/, include: path.join(__dirname, 'src'), loader: 'babel-loader' }, { test: /\.scss/, loader: 'style-loader!css-loader!postcss-loader!sass-loader' }, { test: /\.json/, loader: 'json-loader' }, { test: /\.(png|jpg|ttf|svg|eot|woff|woff2)/, loader: 'url-loader?limit=8192' }] }, postcss: [ autoprefixer({ browsers: 'last 2 versions' }) ], plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.DefinePlugin({ __DEV__: true, __DEVTOOLS__: false, __API_URL__: `\'${API_URL}\'` }) ] };
RiddleMan/giant-privacy-spy
client/webpack.config.js
JavaScript
mit
1,796
25.80597
116
0.525056
false
// 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
42.612903
122
0.664012
false
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
21.888889
92
0.581715
false
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
25.44
66
0.679274
false
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
27.294118
68
0.647917
false
<!doctype html> <html> <head> </head> <body> <h1>Milestones - Codenautas</h1> <div id=milestones></div> <script src=milestones.js></script> </body> </html>
codenautas/pruebas_de_concepto
milestones/milestones.html
HTML
mit
186
16.6
39
0.55914
false
/* * Created on 24/02/2014 * */ package net.rlviana.pricegrabber.model.entity.common; import net.rlviana.pricegrabber.context.JPAPersistenceContext; import net.rlviana.pricegrabber.model.entity.AbstractReadOnlyEntityTest; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; /** * @author ramon */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {JPAPersistenceContext.class}) @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false) @Transactional public class CurrencyTest extends AbstractReadOnlyEntityTest<Currency, String> { private static final Logger LOGGER = LoggerFactory.getLogger(CurrencyTest.class); @Test public void testFindAll() { } @Test public void testFindByCriteria() { } /** * @return * @see net.rlviana.pricegrabber.model.entity.AbstractReadOnlyEntityTest#getEntityPKFindOK() */ @Override protected String getEntityPKFindOK() { return "EU"; } /** * @return * @see net.rlviana.pricegrabber.model.entity.AbstractReadOnlyEntityTest#getEntityPKFindKO() */ @Override protected String getEntityPKFindKO() { return "NEU"; } /** * @return * @see net.rlviana.pricegrabber.model.entity.AbstractReadOnlyEntityTest#getTestClass() */ @Override protected Class<Currency> getTestClass() { return Currency.class; } }
rlviana/pricegrabber-app
pricegrabber-model/src/test/java/net/rlviana/pricegrabber/model/entity/common/CurrencyTest.java
Java
mit
1,712
25.338462
94
0.770444
false
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
44.224209
501
0.847406
false
#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
35.309735
107
0.553741
false
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
28.831776
91
0.614035
false
<?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
33.181818
138
0.613747
false
# ux - Micro Xylph ux は軽量でシンプルな動作を目標としたソフトウェアシンセサイザです。C# で作られており、Mono 上でも動作します。 ## 概要 ux は [Xylph](http://www.johokagekkan.go.jp/2011/u-20/xylph.html) (シルフ) の後継として開発されています。Xylph の開発で得られた最低限必要な機能を絞り、なおかつ Xylph よりも軽快に動作するよう設計されています。C# で記述しつつ、極力高速な動作が目標です。 ux は モノフォニック、複数パート、ポルタメント、ビブラートなどの機能を持ち、音源として矩形波、16 段三角波、ユーザ波形、線形帰還シフトレジスタによる擬似ノイズ、4 オペレータ FM 音源を搭載しています。 現在 Wiki を構築中です。ハンドルの詳細など仕様については Wiki を参照してください: https://github.com/nanase/ux/wiki ## バイナリ 過去のリリース(v0.1.5-dev以前)は [Releases](//github.com/nanase/ux/releases) よりダウンロード可能です。これらは uxPlayer を同梱しており実行可能となっています。 それ以降の最新リリースでは DLL のみの配布とします。uxPlayer のバイナリダウンロードは[こちらのリポジトリ](//github.com/nanase/uxPlayer)をご参照ください。 ## TODO in v0.3-dev * 音源 - [ ] エフェクト(リバーヴ)の追加 * セレクタ(Selector) - [ ] 新ポリフォニックアルゴリズムの追加 ## 姉妹リポジトリ * [ux++](//github.com/nanase/uxpp) - C++ 実装 * [rbux](//github.com/nanase/rbux) - Ruby 実装 ## 備考 * _ux_ と表記して _Micro Xylph (マイクロシルフ)_ と呼称し、プロジェクト内での表記も `ux` です(TeX のようなものです)。 * 性能を重視するためモノフォニック実装(1パート1音)です。ただし uxMidi でのドラムパートのみ 8 音のポリフォニックです。 * この仕様により大抵の MIDI ファイルは正常に再生できません。特に和音を持っている部分は音が抜けます。 * 音色がとにかく_貧弱_です。これは音源定義XMLファイルに充分な定義が無いためです。 - リポジトリ内の以下のファイルが音源定義XMLファイルです。 + [nanase/ux/uxConsole/ux_preset.xml](//github.com/nanase/ux/blob/v0.2-dev/uxConsole/ux_preset.xml) + [nanase/ux/uxPlayer/ux_preset.xml](//github.com/nanase/ux/blob/v0.2-dev/uxPlayer/ux_preset.xml) - 最新の定義ファイルを Gist に置いています: [gist.github.com/nanase/6068233](//gist.github.com/nanase/6068233) ## 動作確認 * Mono 2.10.8.1 (Linux Mint 14 64 bit) * .NET Framework 4.5 (Windows 7 64 bit) * (内部プロジェクトは互換性を理由に .NET Framework 4.0 をターゲットにしています) ## ライセンス **[MIT ライセンス](//github.com/nanase/ux/blob/v0.2-dev/LICENSE)** Copyright &copy; 2013-2014 Tomona Nanase
nanase/ux
README.md
Markdown
mit
3,064
28.655172
167
0.74593
false
--- title: L.esri.Layers.TiledMapLayer layout: documentation.hbs --- # {{page.data.title}} Inherits from [`L.TileLayer`](http://leafletjs.com/reference.html#tilelayer) Access tiles from ArcGIS Online and ArcGIS Server as well as visualize and identify features. Is you have Feature Services published in ArcGIS Online you can create a static set of tiles using your Feature Service. You can find details about that process in the [ArcGIS Online Help](http://doc.arcgis.com/en/arcgis-online/share-maps/publish-tiles.htm#ESRI_SECTION1_F68FCBD33BD54117B23232D41A762E89) **Your map service must be published using the Web Mercator Auxiliary Sphere tiling scheme (WKID 102100/3857) and the default scale options used by Google Maps, Bing Maps and [ArcGIS Online](http://resources.arcgis.com/en/help/arcgisonline-content/index.html#//011q00000002000000). Esri Leaflet will not support any other spatial reference for tile layers.** ### Constructor <table> <thead> <tr> <th>Constructor</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code class="nobr">L.esri.tiledMapLayer({{{param 'Object' 'options'}}})</code></td> <td>The <code>options</code> parameter can accept the same options as <a href="http://leafletjs.com/reference.html#tilelayer"><code>L.ImageOverlay</code></a>. You also must pass a <code>url</code> key in your <code>options</code>.</td> </tr> </tbody> </table> ### Options `L.esri.TiledMapLayer` also accepts all [`L.TileLayer`](http://leafletjs.com/reference.html#tilelayer-options) options. | Option | Type | Default | Description | | --- | --- | --- | --- | `url` | `String` | | *Required* URL of the [Map Service](http://resources.arcgis.com/en/help/arcgis-rest-api/#/Map_Service/02r3000000w2000000) with a tile cache. | `correctZoomLevels` | `Boolean` | `true` | If your tiles were generated in web mercator but at non-standard zoom levels this will remap then to the standard zoom levels. | `zoomOffsetAllowance` | `Number` | `0.1` | If `correctZoomLevels` is enabled this controls the amount of tolerance if the difference at each scale level for remapping tile levels. | `proxy` | `String` | `false` | URL of an [ArcGIS API for JavaScript proxy](https://developers.arcgis.com/javascript/jshelp/ags_proxy.html) or [ArcGIS Resource Proxy](https://github.com/Esri/resource-proxy) to use for proxying POST requests. | | `useCors` | `Boolean` | `true` | Dictates if the service should use CORS when making GET requests. | | `token` | `String` | `null` | Will use this token to authenticate all calls to the service. ### Methods `L.esri.BasemapLayer` inherits all methods from [`L.TileLayer`](http://leafletjs.com/reference.html#tilelayer). <table> <thead> <tr> <th>Method</th> <th>Returns</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>authenticate(&lt;String&gt; token)</code></td> <td><code>this</code></td> <td>Authenticates this service with a new token and runs any pending requests that required a token.</td> </tr> <tr> <td><code>metadata(&lt;Function&gt; callback, &lt;Object&gt; context)</code></td> <td><code>this</code></td> <td> Requests metadata about this Feature Layer. Callback will be called with `error` and `metadata`. <pre class="js"><code>featureLayer.metadata(function(error, metadata){ console.log(metadata); });</code></pre> </td> </tr> <tr> <td><code>identify()</code></td> <td><code>this</code></td> <td> Returns a new <a href="/api-reference/tasks/identify-features.html"><code>L.esri.services.IdentifyFeatures</code></a> object that can be used to identify features on this layer. Your callback function will be passed a GeoJSON FeatureCollection with the results or an error. <pre class="js"><code>featureLayer.identify() .at(latlng, latlngbounds, 5) .run(function(error, featureCollection){ console.log(featureCollection); });</code></pre> </td> </tr> </tbody> </table> ### Events `L.esri.TiledMapLayer` fires all [`L.TileLayer`](http://leafletjs.com/reference.html#tilelayer) events. ### Example ```js var map = L.map('map').setView([37.7614, -122.3911], 12); L.esri.tiledMapLayer("http://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer", { maxZoom: 15 }).addTo(map); ```
ZhangDubhe/Tropical-Cyclone-Information-System
components/esri-leaflet/site/source/pages/api-reference/layers/tiled-map-layer.md
Markdown
mit
4,575
44.29703
358
0.666011
false
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
19.634615
116
0.612302
false
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
16.862069
64
0.658301
false
--- layout: single title: Vue와 Firebase로 모던웹사이트 만들기 43 파이어베이스 함수에서 권한 확인하기 category: vf tag: [vue,node,express,vuetify,firebase,vscode] comments: true sidebar: nav: "vf" toc: true toc_label: "목차" toc_icon: "list" --- 파이어베이스 함수(functions)에서 토큰을 확인하고 풀어헤친 토큰정보(claims)로 권한에 따른 결과를 보냅니다. # 영상 {% include video id="x6_Q0GvDu74" provider="youtube" %}
fkkmemi/fkkmemi.github.io
_posts/2019-08-23-vf 043.md
Markdown
mit
489
18.5
67
0.7151
false
''' 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
25.545455
55
0.683168
false
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
40.7
164
0.721311
false
#pragma once #include "ofMain.h" #include "ofxOsc.h" #include "VHPtriggerArea.h" #include "ofxXmlSettings.h" class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); // variables // Cam ofVideoGrabber vidGrabber; ofTexture videoTexture; ofTexture contrastTexture; ofTexture backgroundTexture; unsigned char * background; unsigned char * pixels; unsigned char * buffer; unsigned char * timeBuffer; int camWidth; int camHeight; int totalPixels; float contrast_e[2]; float contrast_f[2]; float percent; float colorFactor[3]; // triggerArea VHPtriggerArea area; // OSC ofxOscReceiver receiver; // info ofTrueTypeFont font; // settings ofxXmlSettings XML; };
alg-a/herm3TICa
exploracion pruebas y juegos/backgroundSubtraction/src/ofApp.h
C
mit
1,372
23.5
47
0.560496
false
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
22.363636
48
0.691406
false
--- tags: perl layout: post title: "Chris, meet testing" --- <p>I need to start writing software as if it will be released to lots of people tomorrow :) Interestingly, the potential (up to 90% I'd say) release of OpenInteract has coincided with my first reading of Kent Beck's book <a href="http://www1.fatbrain.com/asp/bookinfo/bookinfo.asp?theisbn=0201616416">Extreme Programming Explained</a>. I know, I'm probably a whole 18 months (meaning: eternity) behind the rest of the software development community, but it's new to me. <p>Anyway, XP places a lot of emphasis on testing, an area where my discipline is sorely lacking. The happy coincidence is that releasing for other people also forces me to write tests, just so they'll know everything at least nominally works. This way, I have an excuse to get in the habit of doing something I should be doing anyway. Happy day! <p>A nice side benefit of the SPOPS DBI tests is that it should be easy to find out whether particular DBD drivers support the necessary <tt>{NAME}</tt> and <tt>{TYPE}</tt> attributes or not. (I think drivers for most 'modern' databases do.) <p>Cleaning up the code (which isn't much of the work) and making it presentable (read: installable by someone other than me) also means that I get to hack around a bit in the <tt>Makefile.PL</tt> and <tt>ExtUtils::MakeMaker</tt> land. Eeek! But it's coming along -- it's done for SPOPS, I just need to figure out how to get a normal script (to install the packages, etc.) to run after 'make install'. This is a very powerful software package, and the perl way is to make easy things easy, so... where's the easy part? (Personally, I don't qualify editing a Makefile as easy, but I can be a little dense sometimes.) <p>The nutty thing is that you can (apparently) use E::MM to create PPM files (for ActivePerl users) and for this you can use the 'PPM_INSTALL_SCRIPT' key to specify a program to run after the package/module is installed. So someone recognized this as a good idea to do. Double eeek! <p><em>(Originally posted <a href="http://www.advogato.org/person/cwinters/diary.html?start=20">elsewhere</a>)</em></p>
cwinters/cwinters.github.io
_posts/2000-09-14-chris_meet_testing.md
Markdown
mit
2,190
41.156863
119
0.741553
false
# 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
43.197674
105
0.634175
false
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
18.3
50
0.668394
false
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
20.818182
75
0.752083
false
'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
26.265823
72
0.531105
false
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
25.205882
84
0.765432
false
// 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
22.666667
108
0.707746
false
/* 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
36
96
0.733591
false
--- title: "Puppet" description: "Deregister Sensu clients from the client registry if they no longer have an associated Puppet node." version: 1.0 weight: 12 --- **ENTERPRISE: Built-in integrations are available for [Sensu Enterprise][1] users only.** # Puppet Integration - [Overview](#overview) - [Configuration](#configuration) - [Example(s)](#examples) - [Integration Specification](#integration-specification) - [`puppet` attributes](#puppet-attributes) - [`ssl` attributes](#ssl-attributes) ## Overview Deregister Sensu clients from the client registry if they no longer have an associated [Puppet][2] node. The `puppet` enterprise handler requires access to a SSL truststore and keystore, containing a valid (and whitelisted) Puppet certificate, private key, and CA. The local Puppet agent certificate, private key, and CA can be used. ## Configuration ### Example(s) The following is an example global configuration for the `puppet` enterprise handler (integration). ~~~ json { "puppet": { "endpoint": "https://10.0.1.12:8081/pdb/query/v4/nodes/", "ssl": { "keystore_file": "/etc/sensu/ssl/puppet/keystore.jks", "keystore_password": "secret", "truststore_file": "/etc/sensu/ssl/puppet/truststore.jks", "truststore_password": "secret" }, "timeout": 10 } } ~~~ The Puppet enterprise handler is most commonly used as part of the `keepalive` set handler. For example: ~~~ json { "handlers": { "keepalive": { "type": "set", "handlers": [ "pagerduty", "puppet" ] } } } ~~~ When querying PuppetDB for a node, by default, Sensu will use the Sensu client's name for the Puppet node name. Individual Sensu clients can override the name of their corresponding Puppet node, using specific client definition attributes. The following is an example client definition, specifying its Puppet node name. ~~~ json { "client": { "name": "i-424242", "address": "8.8.8.8", "subscriptions": [ "production", "webserver" ], "puppet": { "node_name": "webserver01.example.com" } } } ~~~ ### Integration Specification _NOTE: the following integration definition attributes may be overwritten by the corresponding Sensu [client definition `puppet` attributes][3], which are included in [event data][4]._ #### `puppet` attributes The following attributes are configured within the `{"puppet": {} }` [configuration scope][5]. `endpoint` : description : The PuppetDB API endpoint (URL). If an API path is not specified, `/pdb/query/v4/nodes/` will be used. : required : true : type : String : example : ~~~ shell "endpoint": "https://10.0.1.12:8081/pdb/query/v4/nodes/" ~~~ `ssl` : description : A set of attributes that configure SSL for PuppetDB API queries. : required : true : type : Hash : example : ~~~ shell "ssl": {} ~~~ #### `ssl` attributes The following attributes are configured within the `{"puppet": { "ssl": {} } }` [configuration scope][3]. ##### EXAMPLE {#ssl-attributes-example} ~~~ json { "puppet": { "endpoint": "https://10.0.1.12:8081/pdb/query/v4/nodes/", "...": "...", "ssl": { "keystore_file": "/etc/sensu/ssl/puppet/keystore.jks", "keystore_password": "secret", "truststore_file": "/etc/sensu/ssl/puppet/truststore.jks", "truststore_password": "secret" } } } ~~~ ##### ATTRIBUTES {#ssl-attributes-specification} `keystore_file` : description : The file path for the SSL certificate keystore. : required : true : type : String : example : ~~~ shell "keystore_file": "/etc/sensu/ssl/puppet/keystore.jks" ~~~ `keystore_password` : description : The SSL certificate keystore password. : required : true : type : String : example : ~~~ shell "keystore_password": "secret" ~~~ `truststore_file` : description : The file path for the SSL certificate truststore. : required : true : type : String : example : ~~~ shell "truststore_file": "/etc/sensu/ssl/puppet/truststore.jks" ~~~ `truststore_password` : description : The SSL certificate truststore password. : required : true : type : String : example : ~~~ shell "truststore_password": "secret" ~~~ [?]: # [1]: /enterprise [2]: https://puppet.com?ref=sensu-enterprise [3]: ../../reference/clients.html#puppet-attributes [4]: ../../reference/events.html#event-data [5]: ../../reference/configuration.html#configuration-scopes
palourde/sensu-docs
docs/1.0/enterprise/integrations/puppet.md
Markdown
mit
4,504
21.078431
80
0.658082
false
#!/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
28.060606
68
0.652763
false