code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
using System; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace ZendeskApi_v2.Serialization { /// <summary> /// found example here https://dotnetfiddle.net/XG3eRy /// </summary> /// <typeparam name="T"></typeparam> class SingleOrArrayConverter<T> : JsonConverter { public override bool CanConvert(Type objectType) { return (objectType == typeof(List<T>)); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JToken token = JToken.Load(reader); if (token.Type == JTokenType.Array) { return token.ToObject<List<T>>(); } return new List<T> { token.ToObject<T>() }; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { List<T> list = (List<T>)value; if (list.Count == 1) { value = list[0]; } serializer.Serialize(writer, value); } } }
CKCobra/ZendeskApi_v2
src/ZendeskApi_v2/Serialization/SingleOrArrayConverter.cs
C#
apache-2.0
1,158
# -------------------------------------------------------------------------- # # Copyright 2002-2015, OpenNebula Project (OpenNebula.org), C12G Labs # # # # Licensed under the Apache License, Version 2.0 (the "License"); you may # # not use this file except in compliance with the License. You may obtain # # a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # #--------------------------------------------------------------------------- # require 'openssl' require 'digest/sha1' require 'base64' require 'fileutils' module OpenNebula; end # Server authentication class. This method can be used by OpenNebula services # to let access authenticated users by other means. It is based on OpenSSL # symmetric ciphers class OpenNebula::ServerCipherAuth ########################################################################### #Constants with paths to relevant files and defaults ########################################################################### CIPHER = "aes-256-cbc" ########################################################################### def initialize(srv_user, srv_passwd) @srv_user = srv_user @srv_passwd = srv_passwd if !srv_passwd.empty? @key = Digest::SHA1.hexdigest(@srv_passwd) else @key = "" end @cipher = OpenSSL::Cipher::Cipher.new(CIPHER) end ########################################################################### # Client side ########################################################################### # Creates a ServerCipher for client usage def self.new_client(srv_user=nil, srv_passwd=nil) if ( srv_user == nil || srv_passwd == nil ) begin if ENV["ONE_CIPHER_AUTH"] and !ENV["ONE_CIPHER_AUTH"].empty? one_auth = File.read(ENV["ONE_CIPHER_AUTH"]) else raise "ONE_CIPHER_AUTH environment variable not set" end one_auth.rstrip! rc = one_auth.match(/(.*?):(.*)/) if rc.nil? raise "Bad format for one_auth token (<user>:<passwd>)" else srv_user = rc[1] srv_passwd = rc[2] end rescue => e raise e.message end end self.new(srv_user, srv_passwd) end # Generates a login token in the form: # - server_user:target_user:time_expires # The token is then encrypted with the contents of one_auth def login_token(expire, target_user=nil) target_user ||= @srv_user token_txt = "#{@srv_user}:#{target_user}:#{expire}" token = encrypt(token_txt) token64 = Base64::encode64(token).strip.delete("\n") return "#{@srv_user}:#{target_user}:#{token64}" end # Returns a valid password string to create a user using this auth driver def password return @srv_passwd end ########################################################################### # Driver side ########################################################################### # Creates a ServerCipher for driver usage def self.new_driver() self.new("","") end # auth method for auth_mad def authenticate(srv_user,srv_pass, signed_text) begin @key = srv_pass s_user, t_user, expires = decrypt(signed_text).split(':') return "User name missmatch" if s_user != srv_user return "login token expired" if Time.now.to_i >= expires.to_i return true rescue => e return e.message end end private def encrypt(data) @cipher.encrypt @cipher.key = @key rc = @cipher.update(data) rc << @cipher.final return rc end def decrypt(data) @cipher.decrypt @cipher.key = @key rc = @cipher.update(Base64::decode64(data)) rc << @cipher.final return rc end end
spirit03/one
src/authm_mad/remotes/server_cipher/server_cipher_auth.rb
Ruby
apache-2.0
4,910
/*************************GO-LICENSE-START********************************* * Copyright 2018 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *************************GO-LICENSE-END**********************************/ describe("util", function () { beforeEach(function () { setFixtures("<input type=\"hidden\" value=\"1287652847\" name=\"server_time\" id=\"server_timestamp\"/>\n" + "<div class='under_test'>\n" + " <span id=\"clickable\">clickable</span>\n" + " <span title=\"1287651018131\" id=\"time_field\"></span>\n" + " <input type=\"hidden\" value=\"1287651018131\"> \n" + "\n" + " <div id=\"populatable\" class=\"\"></div>\n" + " <input type=\"hidden\" id=\"shilpa_needs_to_work_more\"/>\n" + " <button type=\"button\" id=\"btn\" name=\"button\">Push the button</button>\n" + "\n" + " <a href=\"#\" id=\"foo_link\">name_foo</a>\n" + " <input id=\"baz_input\" value=\"name_baz\"/>\n" + "\n" + " <textarea id=\"id_bar\">id bar text</textarea>\n" + " <textarea id=\"id_quux\">id quux text</textarea>\n" + " <div id=\"update_on_evt\">Original content</div>\n" + "</div>"); }); var populatable; var orignialAjax = jQuery.ajax; afterEach(function () { jQuery.ajax = orignialAjax; } ); beforeEach(function () { populatable = $('populatable'); populatable.update(""); }); afterEach(function () { populatable.update(""); }); it("test_executes_javascript_on_event", function () { Util.on_load(function () { populatable.update("foo bar"); }); window.load; assertEquals("foo bar", populatable.innerHTML); }); it("test_executes_javascript_if_event_has_been_fired", function () { window.load; Util.on_load(function () { populatable.update("foo bar1"); }); assertEquals("foo bar1", populatable.innerHTML); }); it("test_appends_child_with_given_text_to_the_given_id", function () { Util.refresh_child_text('populatable', "This text gets overridden", "success"); Util.refresh_child_text('populatable', "second text", "success"); assertEquals(1, populatable.getElementsBySelector("p").length); var p = populatable.down('p'); assertEquals("second text", p.innerHTML); assertTrue("Should have class name", p.hasClassName("success")); }); it("test_does_not_execute_handler_except_for_the_first_time_the_event_is_fired", function () { Util.on_load(function () { populatable.update("foo bar1"); }); window.load; Util.on_load(function () { populatable.update("foo bar2"); }); populatable.update("bar baz"); window.load; assertEquals("bar baz", populatable.innerHTML); }); it("test_set_value", function () { var call_back = Util.set_value('shilpa_needs_to_work_more', "foo"); call_back(); assertEquals("foo", $('shilpa_needs_to_work_more').value); }); it("test_enable_disable", function () { Util.disable("btn"); assertTrue($("btn").disabled); assertTrue($("btn").hasClassName("disabled")); Util.enable("btn"); assertFalse($("btn").disabled); assertFalse($("btn").hasClassName("disabled")); }); it("test_escapeDotsFromId", function () { assertEquals("#2\\.1\\.1\\.2", Util.escapeDotsFromId("2.1.1.2")); }); it("test_ajax_modal_success", function () { var ajax_options = null; var ajax_request = {}; jQuery.ajax = function (options) { ajax_options = options; return ajax_request; }; ajax_request.done = function (func) { func(); }; ajax_request.fail = function (func) { }; ajax_request.responseText = 'response_body'; var modal_box_options = null; var modal_box_content = null; Modalbox.show = function (data) { modal_box_content = data; }; Util.ajax_modal("some_url", {title: "some_title"}); assertEquals("some_url", ajax_options.url); assertContains('response_body', modal_box_content); }); it("test_ajax_modal_failure", function () { var ajax_options = null; var ajax_request = {}; jQuery.ajax = function (options) { ajax_options = options; return ajax_request; }; ajax_request.done = function (func) { }; ajax_request.fail = function (func) { func(); }; ajax_request.responseText = 'response_body'; var modal_box_options = null; var modal_box_content = null; Modalbox.show = function (data, options) { modal_box_content = data; modal_box_options = options; }; Util.ajax_modal("some_url", {title: "some_title"}); assertEquals("some_url", ajax_options.url); assertContains('response_body', jQuery(modal_box_content)[0].innerHTML); }); it("test_updates_dom_elements_on_callback", function () { var mapping = {name_foo: "id_bar", name_baz: "id_quux"}; jQuery('#foo_link').click(Util.domUpdatingCallback(mapping, jQuery('#update_on_evt'), function () { return this.innerHTML; })); jQuery('#baz_input').click(Util.domUpdatingCallback(mapping, jQuery('#update_on_evt'), function () { return this.value; })); assertEquals("Original content", jQuery('#update_on_evt').text()); fire_event($("foo_link"), 'click'); assertEquals("id bar text", jQuery('#update_on_evt').text()); fire_event($("baz_input"), 'click'); assertEquals("id quux text", jQuery('#update_on_evt').text()); }); }); describe("disable input fields", function () { beforeEach(function () { setFixtures("<div id='search_users_table' class='users_table'>\n" + "<input type='hidden'\n" + "id='foo'\n" + "name='foo'\n" + "value='foo'\n" + "/>\n" + "<input type='hidden'\n" + "id='bar'\n" + "name='bar'\n" + "value='bar'\n" + "/>\n" + "</div>"); }); it("should disable all hidden input fields", function () { assertFalse(jQuery("#foo")[0].disabled); assertFalse(jQuery("#bar")[0].disabled); Util.disable_all_hidden_fields("#search_users_table"); assertTrue(jQuery("#foo")[0].disabled); assertTrue(jQuery("#bar")[0].disabled); }); });
varshavaradarajan/gocd
server/webapp/WEB-INF/rails/spec/javascripts/util_spec.js
JavaScript
apache-2.0
7,270
package org.maltparserx.core.syntaxgraph.reader; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.Iterator; import java.util.SortedMap; import java.util.TreeMap; import java.util.regex.PatternSyntaxException; import org.maltparserx.core.exception.MaltChainedException; import org.maltparserx.core.io.dataformat.ColumnDescription; import org.maltparserx.core.io.dataformat.DataFormatException; import org.maltparserx.core.io.dataformat.DataFormatInstance; import org.maltparserx.core.syntaxgraph.MappablePhraseStructureGraph; import org.maltparserx.core.syntaxgraph.PhraseStructure; import org.maltparserx.core.syntaxgraph.TokenStructure; import org.maltparserx.core.syntaxgraph.edge.Edge; import org.maltparserx.core.syntaxgraph.node.PhraseStructureNode; /** * * * @author Johan Hall */ public class NegraReader implements SyntaxGraphReader { private enum NegraTables { ORIGIN, EDITOR, WORDTAG, MORPHTAG, NODETAG, EDGETAG, SECEDGETAG, SENTENCE, UNDEF }; private BufferedReader reader; private DataFormatInstance dataFormatInstance; private int sentenceCount; private String optionString; private int formatVersion; private NegraTables currentHeaderTable; private int currentTerminalSize; private int currentNonTerminalSize; private SortedMap<Integer,PhraseStructureNode> nonterminals; private StringBuilder edgelabelSymbol; private StringBuilder edgelabelTableName; private int START_ID_OF_NONTERMINALS = 500; private String fileName = null; private URL url = null; private String charsetName; private int nIterations; private int cIterations; private boolean closeStream = true; public NegraReader() { currentHeaderTable = NegraTables.UNDEF; edgelabelSymbol = new StringBuilder(); edgelabelTableName = new StringBuilder(); nonterminals = new TreeMap<Integer,PhraseStructureNode>(); nIterations = 1; cIterations = 1; } private void reopen() throws MaltChainedException { close(); if (fileName != null) { open(fileName, charsetName); } else if (url != null) { open(url, charsetName); } else { throw new DataFormatException("The input stream cannot be reopen. "); } } public void open(String fileName, String charsetName) throws MaltChainedException { setFileName(fileName); setCharsetName(charsetName); try { open(new FileInputStream(fileName), charsetName); } catch (FileNotFoundException e) { throw new DataFormatException("The input file '"+fileName+"' cannot be found. ", e); } } public void open(URL url, String charsetName) throws MaltChainedException { setUrl(url); setCharsetName(charsetName); try { open(url.openStream(), charsetName); } catch (IOException e) { throw new DataFormatException("The URL '"+url.toString()+"' cannot be opened. ", e); } } public void open(InputStream is, String charsetName) throws MaltChainedException { try { if (is == System.in) { closeStream = false; } open(new InputStreamReader(is, charsetName)); } catch (UnsupportedEncodingException e) { throw new DataFormatException("The character encoding set '"+charsetName+"' isn't supported. ", e); } } private void open(InputStreamReader isr) throws MaltChainedException { setReader(new BufferedReader(isr)); setSentenceCount(0); } public void readProlog() throws MaltChainedException { } public boolean readSentence(TokenStructure syntaxGraph) throws MaltChainedException { if (syntaxGraph == null || !(syntaxGraph instanceof PhraseStructure)) { return false; } syntaxGraph.clear(); final PhraseStructure phraseStructure = (PhraseStructure)syntaxGraph; PhraseStructureNode parent = null; PhraseStructureNode child = null; currentHeaderTable = NegraTables.UNDEF; String line = null; syntaxGraph.clear(); nonterminals.clear(); try { while (true) { line = reader.readLine(); if (line == null) { if (syntaxGraph.hasTokens()) { sentenceCount++; if (syntaxGraph instanceof MappablePhraseStructureGraph) { ((MappablePhraseStructureGraph)syntaxGraph).getMapping().updateDependenyGraph(((MappablePhraseStructureGraph)syntaxGraph), ((PhraseStructure)syntaxGraph).getPhraseStructureRoot()); } } if (cIterations < nIterations) { cIterations++; reopen(); return true; } return false; } else if (line.startsWith("#EOS")) { currentTerminalSize = 0; currentNonTerminalSize = 0; currentHeaderTable = NegraTables.UNDEF; if (syntaxGraph instanceof MappablePhraseStructureGraph) { ((MappablePhraseStructureGraph)syntaxGraph).getMapping().updateDependenyGraph(((MappablePhraseStructureGraph)syntaxGraph), ((PhraseStructure)syntaxGraph).getPhraseStructureRoot()); } return true; } else if (line.startsWith("#BOS")) { currentHeaderTable = NegraTables.SENTENCE; int s = -1, e = -1; for (int i = 5, n = line.length(); i < n; i++) { if (Character.isDigit(line.charAt(i)) && s == -1) { s = i; } if (line.charAt(i) == ' ') { e = i; break; } } if (s != e && s != -1 && e != -1) { phraseStructure.setSentenceID(Integer.parseInt(line.substring(s,e))); } sentenceCount++; } else if (currentHeaderTable == NegraTables.SENTENCE) { if (line.length() >= 2 && line.charAt(0) == '#' && Character.isDigit(line.charAt(1))) { // Non-terminal Iterator<ColumnDescription> columns = dataFormatInstance.iterator(); ColumnDescription column = null; currentNonTerminalSize++; char[] lineChars = line.toCharArray(); int start = 0; int secedgecounter = 0; for (int i = 0, n = lineChars.length; i < n; i++) { if (lineChars[i] == '\t' && start == i) { start++; } else if (lineChars[i] == '\t' || i == n - 1) { if (columns.hasNext()) { column = columns.next(); } if (column.getPosition() == 0) { int index = Integer.parseInt((i == n - 1)?line.substring(start+1):line.substring(start+1, i)); child = nonterminals.get(index); if (child == null) { if (index != 0) { child = ((PhraseStructure)syntaxGraph).addNonTerminalNode(index-START_ID_OF_NONTERMINALS+1); } nonterminals.put(index,child); } } else if (column.getPosition() == 2 && child != null) { syntaxGraph.addLabel(child, "CAT", (i == n - 1)?line.substring(start):line.substring(start, i)); } else if (column.getCategory() == ColumnDescription.PHRASE_STRUCTURE_EDGE_LABEL) { edgelabelSymbol.setLength(0); edgelabelSymbol.append((i == n - 1)?line.substring(start):line.substring(start, i)); edgelabelTableName.setLength(0); edgelabelTableName.append(column.getName()); } else if (column.getCategory() == ColumnDescription.PHRASE_STRUCTURE_NODE_LABEL && child != null) { int index = Integer.parseInt((i == n - 1)?line.substring(start):line.substring(start, i)); parent = nonterminals.get(index); if (parent == null) { if (index == 0) { parent = phraseStructure.getPhraseStructureRoot(); } else { parent = phraseStructure.addNonTerminalNode(index-START_ID_OF_NONTERMINALS+1); } nonterminals.put(index,parent); } Edge e = phraseStructure.addPhraseStructureEdge(parent, child); syntaxGraph.addLabel(e, edgelabelTableName.toString(), edgelabelSymbol.toString()); } else if (column.getCategory() == ColumnDescription.SECONDARY_EDGE_LABEL && child != null) { if (secedgecounter % 2 == 0) { edgelabelSymbol.setLength(0); edgelabelSymbol.append((i == n - 1)?line.substring(start):line.substring(start, i)); secedgecounter++; } else { int index = Integer.parseInt((i == n - 1)?line.substring(start):line.substring(start, i)); if (index == 0) { parent = phraseStructure.getPhraseStructureRoot(); } else if (index < START_ID_OF_NONTERMINALS) { parent = phraseStructure.getTokenNode(index); } else { parent = nonterminals.get(index); if (parent == null) { parent = phraseStructure.addNonTerminalNode(index-START_ID_OF_NONTERMINALS+1); nonterminals.put(index,parent); } } Edge e = phraseStructure.addSecondaryEdge(parent, child); e.addLabel(column.getSymbolTable(), edgelabelSymbol.toString()); secedgecounter++; } } start = i + 1; } } } else { // Terminal Iterator<ColumnDescription> columns = dataFormatInstance.iterator(); ColumnDescription column = null; currentTerminalSize++; child = syntaxGraph.addTokenNode(currentTerminalSize); char[] lineChars = line.toCharArray(); int start = 0; int secedgecounter = 0; for (int i = 0, n = lineChars.length; i < n; i++) { if (lineChars[i] == '\t' && start == i) { start++; } else if (lineChars[i] == '\t' || i == n - 1) { if (columns.hasNext()) { column = columns.next(); } if (column.getCategory() == ColumnDescription.INPUT && child != null) { syntaxGraph.addLabel(child, column.getName(), (i == n - 1)?line.substring(start):line.substring(start, i)); } else if (column.getCategory() == ColumnDescription.PHRASE_STRUCTURE_EDGE_LABEL && child != null) { // && column.getName().equals("EDGELABEL")) { edgelabelSymbol.setLength(0); edgelabelSymbol.append((i == n - 1)?line.substring(start):line.substring(start, i)); edgelabelTableName.setLength(0); edgelabelTableName.append(column.getName()); } else if (column.getCategory() == ColumnDescription.PHRASE_STRUCTURE_NODE_LABEL && child != null) { int index = Integer.parseInt((i == n - 1)?line.substring(start):line.substring(start, i)); parent = nonterminals.get(index); if (parent == null) { if (index == 0) { parent = phraseStructure.getPhraseStructureRoot(); } else { parent = phraseStructure.addNonTerminalNode(index-START_ID_OF_NONTERMINALS+1); } nonterminals.put(index,parent); } Edge e = phraseStructure.addPhraseStructureEdge(parent, child); syntaxGraph.addLabel(e, edgelabelTableName.toString(), edgelabelSymbol.toString()); } else if (column.getCategory() == ColumnDescription.SECONDARY_EDGE_LABEL && child != null) { if (secedgecounter % 2 == 0) { edgelabelSymbol.setLength(0); edgelabelSymbol.append((i == n - 1)?line.substring(start):line.substring(start, i)); secedgecounter++; } else { int index = Integer.parseInt((i == n - 1)?line.substring(start):line.substring(start, i)); if (index == 0) { parent = phraseStructure.getPhraseStructureRoot(); } else if (index < START_ID_OF_NONTERMINALS) { parent = phraseStructure.getTokenNode(index); } else { parent = nonterminals.get(index); if (parent == null) { parent = phraseStructure.addNonTerminalNode(index-START_ID_OF_NONTERMINALS+1); nonterminals.put(index,parent); } } Edge e = phraseStructure.addSecondaryEdge(parent, child); e.addLabel(column.getSymbolTable(), edgelabelSymbol.toString()); secedgecounter++; } } start = i + 1; } } } } else if (line.startsWith("%%")) { // comment skip } else if (line.startsWith("#FORMAT")) { // int index = line.indexOf(' '); // if (index > -1) { // try { // formatVersion = Integer.parseInt(line.substring(index+1)); // } catch (NumberFormatException e) { // // } // } } else if (line.startsWith("#BOT")) { // int index = line.indexOf(' '); // if (index > -1) { // if (line.substring(index+1).equals("ORIGIN")) { // currentHeaderTable = NegraTables.ORIGIN; // } else if (line.substring(index+1).equals("EDITOR")) { // currentHeaderTable = NegraTables.EDITOR; // } else if (line.substring(index+1).equals("WORDTAG")) { // currentHeaderTable = NegraTables.WORDTAG; // } else if (line.substring(index+1).equals("MORPHTAG")) { // currentHeaderTable = NegraTables.MORPHTAG; // } else if (line.substring(index+1).equals("NODETAG")) { // currentHeaderTable = NegraTables.NODETAG; // } else if (line.substring(index+1).equals("EDGETAG")) { // currentHeaderTable = NegraTables.EDGETAG; // } else if (line.substring(index+1).equals("SECEDGETAG")) { // currentHeaderTable = NegraTables.SECEDGETAG; // } else { // currentHeaderTable = NegraTables.UNDEF; // } // } } else if (line.startsWith("#EOT")) { currentHeaderTable = NegraTables.UNDEF; } } } catch (IOException e) { throw new DataFormatException("Error when reading from the input file. ", e); } } public void readEpilog() throws MaltChainedException { } public BufferedReader getReader() { return reader; } public void setReader(BufferedReader reader) { this.reader = reader; } public int getSentenceCount() { return sentenceCount; } public void setSentenceCount(int sentenceCount) { this.sentenceCount = sentenceCount; } public int getFormatVersion() { return formatVersion; } public void setFormatVersion(int formatVersion) { this.formatVersion = formatVersion; } public DataFormatInstance getDataFormatInstance() { return dataFormatInstance; } public void setDataFormatInstance(DataFormatInstance inputDataFormatInstance) { this.dataFormatInstance = inputDataFormatInstance; } public String getOptions() { return optionString; } public void setOptions(String optionString) throws MaltChainedException { this.optionString = optionString; String[] argv; try { argv = optionString.split("[_\\p{Blank}]"); } catch (PatternSyntaxException e) { throw new DataFormatException("Could not split the penn writer option '"+optionString+"'. ", e); } for (int i=0; i < argv.length-1; i++) { if(argv[i].charAt(0) != '-') { throw new DataFormatException("The argument flag should start with the following character '-', not with "+argv[i].charAt(0)); } if(++i>=argv.length) { throw new DataFormatException("The last argument does not have any value. "); } switch(argv[i-1].charAt(1)) { case 's': try { START_ID_OF_NONTERMINALS = Integer.parseInt(argv[i]); } catch (NumberFormatException e){ throw new MaltChainedException("The TigerXML Reader option -s must be an integer value. "); } break; default: throw new DataFormatException("Unknown NegraReader parameter: '"+argv[i-1]+"' with value '"+argv[i]+"'. "); } } } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public URL getUrl() { return url; } public void setUrl(URL url) { this.url = url; } public String getCharsetName() { return charsetName; } public void setCharsetName(String charsetName) { this.charsetName = charsetName; } public int getNIterations() { return nIterations; } public void setNIterations(int iterations) { nIterations = iterations; } public int getIterationCounter() { return cIterations; } public void close() throws MaltChainedException { try { if (reader != null) { if (closeStream) { reader.close(); } reader = null; } } catch (IOException e) { throw new DataFormatException("Error when closing the input file.", e); } } }
michaelcapizzi/processors
src/main/java/org/maltparserx/core/syntaxgraph/reader/NegraReader.java
Java
apache-2.0
16,507
using EPiServer.Cms.UI.AspNetIdentity; using EPiServer.Commerce.Order; using Mediachase.Commerce.Customers; using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace EPiServer.Reference.Commerce.Shared.Identity { public class SiteUser : ApplicationUser { public SiteUser() { } /// <summary> /// Returns a new instance of an ApplicationUser based on a previously made purchase order. /// </summary> /// <param name="purchaseOrder"></param> public SiteUser(IPurchaseOrder purchaseOrder) { Addresses = new List<CustomerAddress>(); var billingAddress = purchaseOrder.GetFirstForm().Payments.First().BillingAddress; if (billingAddress != null) { Email = billingAddress.Email; UserName = billingAddress.Email; FirstName = billingAddress.FirstName; LastName = billingAddress.LastName; } var addressesToAdd = new HashSet<IOrderAddress>(purchaseOrder.GetFirstForm().Shipments.Select(x => x.ShippingAddress)); foreach (var shippingAddress in addressesToAdd) { if (shippingAddress.Id != billingAddress.Id) { Addresses.Add(CreateCustomerAddress(shippingAddress, CustomerAddressTypeEnum.Shipping)); } } Addresses.Add(CreateCustomerAddress(billingAddress, CustomerAddressTypeEnum.Billing)); } [NotMapped] public List<CustomerAddress> Addresses { get; set; } [NotMapped] public string FirstName { get; set; } [NotMapped] public string LastName { get; set; } [NotMapped] public string RegistrationSource { get; set; } [NotMapped] public string Password { get; set; } public bool NewsLetter { get; set; } public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<SiteUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here userIdentity.AddClaim(new Claim(ClaimTypes.Email, Email)); if (!String.IsNullOrEmpty(FirstName)) { userIdentity.AddClaim(new Claim(ClaimTypes.GivenName, FirstName)); } if (!String.IsNullOrEmpty(LastName)) { userIdentity.AddClaim(new Claim(ClaimTypes.Surname, LastName)); } return userIdentity; } private CustomerAddress CreateCustomerAddress(IOrderAddress orderAddress, CustomerAddressTypeEnum addressType) { var address = CustomerAddress.CreateInstance(); address.Name = orderAddress.Id; address.AddressType = addressType; address.PostalCode = orderAddress.PostalCode; address.City = orderAddress.City; address.CountryCode = orderAddress.CountryCode; address.CountryName = orderAddress.CountryName; address.State = orderAddress.RegionName; address.Email = orderAddress.Email; address.FirstName = orderAddress.FirstName; address.LastName = orderAddress.LastName; address.Line1 = orderAddress.Line1; address.Line2 = orderAddress.Line2; address.DaytimePhoneNumber = orderAddress.DaytimePhoneNumber; address.EveningPhoneNumber = orderAddress.EveningPhoneNumber; address.RegionCode = orderAddress.RegionCode; address.RegionName = orderAddress.RegionName; return address; } } }
simerc/QuicksilverPlus
Sources/EPiServer.Reference.Commerce.Shared/Identity/SiteUser.cs
C#
apache-2.0
4,044
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.example.transformer.cdi; import org.apache.camel.builder.RouteBuilder; /** * Configures all our Camel routes, components, endpoints and beans */ public class MyRoutes extends RouteBuilder { @Override public void configure() { transformer() .fromType("xml:MyRequest") .toType("xml:MyResponse") .withUri("xslt:transform.xsl"); from("timer:foo?period=5000").id("timer-route") .log("start -->") .setBody(constant("<MyRequest>foobar</MyRequest>")) .log("--> Sending:[${body}]") .to("direct:a") .log("--> Received:[${body}]") .log("<-- end"); from("direct:a").id("xslt-route") .inputType("xml:MyRequest") .outputType("xml:MyResponse") .log("----> Received:[${body}]"); } }
objectiser/camel
examples/camel-example-transformer-cdi/src/main/java/org/apache/camel/example/transformer/cdi/MyRoutes.java
Java
apache-2.0
1,699
//===-- CommandObjectStats.cpp ----------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "CommandObjectStats.h" #include "lldb/Host/Host.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Target/Target.h" using namespace lldb; using namespace lldb_private; class CommandObjectStatsEnable : public CommandObjectParsed { public: CommandObjectStatsEnable(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "enable", "Enable statistics collection", nullptr, eCommandProcessMustBePaused) {} ~CommandObjectStatsEnable() override = default; protected: bool DoExecute(Args &command, CommandReturnObject &result) override { Target &target = GetSelectedOrDummyTarget(); if (target.GetCollectingStats()) { result.AppendError("statistics already enabled"); result.SetStatus(eReturnStatusFailed); return false; } target.SetCollectingStats(true); result.SetStatus(eReturnStatusSuccessFinishResult); return true; } }; class CommandObjectStatsDisable : public CommandObjectParsed { public: CommandObjectStatsDisable(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "disable", "Disable statistics collection", nullptr, eCommandProcessMustBePaused) {} ~CommandObjectStatsDisable() override = default; protected: bool DoExecute(Args &command, CommandReturnObject &result) override { Target &target = GetSelectedOrDummyTarget(); if (!target.GetCollectingStats()) { result.AppendError("need to enable statistics before disabling them"); result.SetStatus(eReturnStatusFailed); return false; } target.SetCollectingStats(false); result.SetStatus(eReturnStatusSuccessFinishResult); return true; } }; class CommandObjectStatsDump : public CommandObjectParsed { public: CommandObjectStatsDump(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "dump", "Dump statistics results", nullptr, eCommandProcessMustBePaused) {} ~CommandObjectStatsDump() override = default; protected: bool DoExecute(Args &command, CommandReturnObject &result) override { Target &target = GetSelectedOrDummyTarget(); uint32_t i = 0; for (auto &stat : target.GetStatistics()) { result.AppendMessageWithFormat( "%s : %u\n", lldb_private::GetStatDescription(static_cast<lldb_private::StatisticKind>(i)) .c_str(), stat); i += 1; } result.SetStatus(eReturnStatusSuccessFinishResult); return true; } }; CommandObjectStats::CommandObjectStats(CommandInterpreter &interpreter) : CommandObjectMultiword(interpreter, "statistics", "Print statistics about a debugging session", "statistics <subcommand> [<subcommand-options>]") { LoadSubCommand("enable", CommandObjectSP(new CommandObjectStatsEnable(interpreter))); LoadSubCommand("disable", CommandObjectSP(new CommandObjectStatsDisable(interpreter))); LoadSubCommand("dump", CommandObjectSP(new CommandObjectStatsDump(interpreter))); } CommandObjectStats::~CommandObjectStats() = default;
apple/swift-lldb
source/Commands/CommandObjectStats.cpp
C++
apache-2.0
3,669
/** * Copyright 2005-2016 Red Hat, Inc. * * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.fabric8.zookeeper.commands; import io.fabric8.boot.commands.support.AbstractCommandComponent; import io.fabric8.commands.support.ZNodeCompleter; import io.fabric8.zookeeper.curator.CuratorFrameworkLocator; import org.apache.curator.framework.CuratorFramework; import org.apache.felix.gogo.commands.Action; import org.apache.felix.gogo.commands.basic.AbstractCommand; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.felix.service.command.Function; @Component(immediate = true) @Service({Function.class, AbstractCommand.class}) @org.apache.felix.scr.annotations.Properties({ @Property(name = "osgi.command.scope", value = Create.SCOPE_VALUE), @Property(name = "osgi.command.function", value = Create.FUNCTION_VALUE) }) public class Create extends AbstractCommandComponent { public static final String SCOPE_VALUE = "zk"; public static final String FUNCTION_VALUE = "create"; public static final String DESCRIPTION = "Create a znode"; // Completers @Reference(referenceInterface = ZNodeCompleter.class, bind = "bindZnodeCompleter", unbind = "unbindZnodeCompleter") private ZNodeCompleter zNodeCompleter; // dummy field @Activate void activate() { activateComponent(); } @Deactivate void deactivate() { deactivateComponent(); } @Override public Action createNewAction() { assertValid(); // this is how we get hold of the curator framework CuratorFramework curator = CuratorFrameworkLocator.getCuratorFramework(); return new CreateAction(curator); } void bindZnodeCompleter(ZNodeCompleter completer) { bindCompleter(completer); } void unbindZnodeCompleter(ZNodeCompleter completer) { unbindCompleter(completer); } }
jludvice/fabric8
fabric/fabric-zookeeper-commands/src/main/java/io/fabric8/zookeeper/commands/Create.java
Java
apache-2.0
2,701
<?php /** * [Discuz!] (C)2001-2099 Comsenz Inc. * This is NOT a freeware, use is subject to license terms * * $Id: cache_fields_connect_register.php 24935 2011-10-17 07:41:48Z zhangguosheng $ */ if(!defined('IN_DISCUZ')) { exit('Access Denied'); } function build_cache_fields_connect_register() { global $_G; $data = array(); $fields = array(); if($_G['setting']['connect']['register_gender']) { $fields[] = 'gender'; } if($_G['setting']['connect']['register_birthday']) { $fields[] = 'birthyear'; $fields[] = 'birthmonth'; $fields[] = 'birthday'; } if($fields) { foreach(C::t('common_member_profile_setting')->fetch_all($fields) as $field) { $choices = array(); if($field['selective']) { foreach(explode("\n", $field['choices']) as $item) { list($index, $choice) = explode('=', $item); $choices[trim($index)] = trim($choice); } $field['choices'] = $choices; } else { unset($field['choices']); } $field['showinregister'] = 1; $field['available'] = 1; $data['field_'.$field['fieldid']] = $field; } } savecache('fields_connect_register', $data); } ?>
isehuo/poled
source/function/cache/cache_fields_connect_register.php
PHP
apache-2.0
1,191
/** * Copyright 2017 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.swarm.ejb.detect; import org.wildfly.swarm.spi.meta.PackageFractionDetector; /** * @author Ken Finnigan */ public class EJBPackageDetector extends PackageFractionDetector { public EJBPackageDetector() { anyPackageOf("javax.ejb"); } @Override public String artifactId() { return "ejb"; } }
gastaldi/wildfly-swarm
fractions/javaee/ejb/src/main/java/org/wildfly/swarm/ejb/detect/EJBPackageDetector.java
Java
apache-2.0
974
#include "drape/utils/gpu_mem_tracker.hpp" #include <iomanip> #include <sstream> namespace dp { std::string GPUMemTracker::GPUMemorySnapshot::ToString() const { std::ostringstream ss; ss << " Summary Allocated = " << m_summaryAllocatedInMb << "Mb\n"; ss << " Summary Used = " << m_summaryUsedInMb << "Mb\n"; ss << " Tags registered = " << m_tagStats.size() << "\n"; for (auto const & it : m_tagStats) { ss << " Tag = " << it.first << " \n"; ss << " Object count = " << it.second.m_objectsCount << "\n"; ss << " Allocated = " << it.second.m_alocatedInMb << "Mb\n"; ss << " Used = " << it.second.m_usedInMb << "Mb\n"; } ss << " Average allocations by hashes:\n"; for (auto const & it : m_averageAllocations) { ss << " " << std::hex << it.first; ss << " : " << std::dec << it.second.GetAverage() << " bytes\n"; } return ss.str(); } GPUMemTracker & GPUMemTracker::Inst() { static GPUMemTracker s_inst; return s_inst; } GPUMemTracker::GPUMemorySnapshot GPUMemTracker::GetMemorySnapshot() { GPUMemorySnapshot memStat; { std::lock_guard<std::mutex> g(m_mutex); for (auto const & kv : m_memTracker) { TagMemorySnapshot & tagStat = memStat.m_tagStats[kv.first.first]; tagStat.m_objectsCount++; tagStat.m_alocatedInMb += kv.second.first; tagStat.m_usedInMb += kv.second.second; memStat.m_summaryAllocatedInMb += kv.second.first; memStat.m_summaryUsedInMb += kv.second.second; } memStat.m_averageAllocations = m_averageAllocations; } auto constexpr kByteToMb = static_cast<float>(1024 * 1024); for (auto & it : memStat.m_tagStats) { it.second.m_alocatedInMb /= kByteToMb; it.second.m_usedInMb /= kByteToMb; } memStat.m_summaryAllocatedInMb /= kByteToMb; memStat.m_summaryUsedInMb /= kByteToMb; return memStat; } void GPUMemTracker::AddAllocated(std::string const & tag, uint32_t id, uint32_t size) { std::lock_guard<std::mutex> g(m_mutex); m_memTracker[make_pair(tag, id)].first = size; } void GPUMemTracker::SetUsed(std::string const & tag, uint32_t id, uint32_t size) { std::lock_guard<std::mutex> g(m_mutex); TAlocUsedMem & node = m_memTracker[make_pair(tag, id)]; node.second = size; ASSERT_LESS_OR_EQUAL(node.second, node.first, ("Can't use more than allocated")); } void GPUMemTracker::RemoveDeallocated(std::string const & tag, uint32_t id) { std::lock_guard<std::mutex> g(m_mutex); m_memTracker.erase(make_pair(tag, id)); } void GPUMemTracker::TrackAverageAllocation(uint64_t hash, uint64_t size) { uint32_t constexpr kBucketMask = 0x7; std::lock_guard<std::mutex> g(m_mutex); auto & allocation = m_averageAllocations[hash & kBucketMask]; allocation.m_totalSizeInBytes += size; allocation.m_count++; } } // namespace dp
darina/omim
drape/utils/gpu_mem_tracker.cpp
C++
apache-2.0
2,815
# Basic setups # pkgs = value_for_platform( %w(redhat centos fedora scientific) => { %w(5.0 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8) => %w(fcgi-perl spawn-fcgi), "default" => %w(perl-FCGI perl-FCGI-ProcManager spawn-fcgi) }, "default" => %w(libfcgi-perl libfcgi-procmanager-perl spawn-fcgi) ) if(platform?(*%w(redhat centos fedora scientific))) include_recipe 'yum::epel' if(node[:nginx_simplecgi][:init_type].to_sym == :upstart) node.set[:nginx_simplecgi][:init_type] = 'init' end end pkgs.each do |package_name| package package_name end if(pkgs.include?('fcgi-perl')) include_recipe 'perl' cpan_module 'FCGI::ProcManager' end directory node[:nginx_simplecgi][:dispatcher_directory] do action :create recursive true owner node[:nginx][:user] group node[:nginx][:group] || node[:nginx][:user] end # Setup our dispatchers include_recipe 'nginx_simplecgi::cgi' if node[:nginx_simplecgi][:cgi] include_recipe 'nginx_simplecgi::php' if node[:nginx_simplecgi][:php] # Setup our init case node[:nginx_simplecgi][:init_type].to_sym when :upstart include_recipe 'nginx_simplecgi::upstart' when :runit include_recipe 'nginx_simplecgi::runit' when :bluepill include_recipe 'nginx_simplecgi::bluepill' when :init include_recipe 'nginx_simplecgi::init' else raise "Not Implemented: #{node[:nginx_simplecgi][:init_type]}" end
chewd/chef-repo
cookbooks/nginx_simplecgi/recipes/setup.rb
Ruby
apache-2.0
1,361
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.oodt.cas.resource.mux; import java.util.List; import org.apache.oodt.cas.resource.batchmgr.Batchmgr; import org.apache.oodt.cas.resource.monitor.Monitor; import org.apache.oodt.cas.resource.scheduler.Scheduler; import org.apache.oodt.cas.resource.structs.exceptions.QueueManagerException; /** * Interface for the backend manager * * @author starchmd */ public interface BackendManager { /** * Add in a backend set to this manager. * @param queue - queue that maps to the given monitor, batchmgr, and scheduler * @param monitor - monitor used for this set * @param batchmgr - batch manager for this set * @param scheduler - scheduler for this set */ void addSet(String queue, Monitor monitor, Batchmgr batchmgr, Scheduler scheduler); /** * Return monitor for the given queue. * @param queue - queue to check * @return montior * @throws QueueManagerException when queue does not exist */ Monitor getMonitor(String queue) throws QueueManagerException; /** * Return batch manager for the given queue. * @param queue - queue to check * @return batchmgr * @throws QueueManagerException when queue does not exist */ Batchmgr getBatchmgr(String queue) throws QueueManagerException; /** * Return scheduler for the given queue. * @param queue - queue to check * @return scheduler * @throws QueueManagerException when queue does not exist */ Scheduler getScheduler(String queue) throws QueueManagerException; /** * Return a list of all monitors. * @return list of all monitors */ List<Monitor> getMonitors(); }
apache/oodt
resource/src/main/java/org/apache/oodt/cas/resource/mux/BackendManager.java
Java
apache-2.0
2,489
package io.airlift.http.client.spnego; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import io.airlift.units.Duration; import org.eclipse.jetty.client.api.Authentication; import org.eclipse.jetty.client.api.AuthenticationStore; import java.net.URI; import java.util.concurrent.TimeUnit; import static java.util.Objects.requireNonNull; public class SpnegoAuthenticationStore implements AuthenticationStore { private static final int CACHE_SIZE = 10000; private static final Duration CACHE_EXPIRE_TIME = new Duration(5, TimeUnit.MINUTES); private static final int CONCURRENCY_LEVEL = 16; private final Cache<URI, Authentication.Result> results; private final SpnegoAuthentication authentication; public SpnegoAuthenticationStore(SpnegoAuthentication authentication) { requireNonNull(authentication, "authentication is null"); this.authentication = authentication; results = CacheBuilder.newBuilder() .concurrencyLevel(CONCURRENCY_LEVEL) .maximumSize(CACHE_SIZE) .expireAfterWrite(CACHE_EXPIRE_TIME.roundTo(TimeUnit.MINUTES), TimeUnit.MINUTES).build(); } @Override public void addAuthentication(Authentication authentication) { throw new UnsupportedOperationException("addAuthentication is not supported"); } @Override public void removeAuthentication(Authentication authentication) { throw new UnsupportedOperationException("removeAuthentication is not supported"); } @Override public void clearAuthentications() { throw new UnsupportedOperationException("clearAuthentications is not supported"); } @Override public Authentication findAuthentication(String type, URI uri, String realm) { if (authentication.matches(type, uri, realm)) { return authentication; } return null; } @Override public void addAuthenticationResult(Authentication.Result result) { results.put(UriUtil.normalizedUri(result.getURI()), result); } @Override public void removeAuthenticationResult(Authentication.Result result) { results.invalidate(UriUtil.normalizedUri(result.getURI())); } @Override public void clearAuthenticationResults() { results.invalidateAll(); } @Override public Authentication.Result findAuthenticationResult(URI uri) { requireNonNull(uri, "uri is null"); if ("https".equalsIgnoreCase(uri.getScheme())) { // TODO: match the longest URI based on Trie for fine grained control return results.getIfPresent(UriUtil.normalizedUri(uri)); } return null; } }
zhenyuy-fb/airlift
http-client/src/main/java/io/airlift/http/client/spnego/SpnegoAuthenticationStore.java
Java
apache-2.0
2,775
package fr.castorflex.android.circularprogressbar; import android.graphics.Canvas; import android.graphics.Paint; import android.os.SystemClock; import android.support.annotation.NonNull; import java.util.concurrent.TimeUnit; /** * Created by castorflex on 9/12/15. */ public class PowerSaveModeDelegate implements PBDelegate { private static final long REFRESH_RATE = TimeUnit.SECONDS.toMillis(1L); private final CircularProgressDrawable mParent; private int mCurrentRotation; public PowerSaveModeDelegate(@NonNull CircularProgressDrawable parent) { mParent = parent; } @Override public void draw(Canvas canvas, Paint paint) { canvas.drawArc(mParent.getDrawableBounds(), mCurrentRotation, 300, false, paint); } @Override public void start() { mParent.invalidate(); mParent.scheduleSelf(mRunnable, SystemClock.uptimeMillis() + REFRESH_RATE); } @Override public void stop() { mParent.unscheduleSelf(mRunnable); } @Override public void progressiveStop(CircularProgressDrawable.OnEndListener listener) { mParent.stop(); } private final Runnable mRunnable = new Runnable() { @Override public void run() { mCurrentRotation += 50; mCurrentRotation %= 360; if (mParent.isRunning()) mParent.scheduleSelf(this, SystemClock.uptimeMillis() + REFRESH_RATE); mParent.invalidate(); } }; }
ifunny/SmoothProgressBar
library-circular/src/main/java/fr.castorflex.android.circularprogressbar/PowerSaveModeDelegate.java
Java
apache-2.0
1,396
package org.wso2.developerstudio.datamapper.diagram.providers.assistants; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import org.wso2.developerstudio.datamapper.diagram.providers.DataMapperElementTypes; import org.wso2.developerstudio.datamapper.diagram.providers.DataMapperModelingAssistantProvider; /** * @generated */ public class DataMapperModelingAssistantProviderOfDataMapperRootEditPart extends DataMapperModelingAssistantProvider { /** * @generated */ @Override public List<IElementType> getTypesForPopupBar(IAdaptable host) { List<IElementType> types = new ArrayList<IElementType>(39); types.add(DataMapperElementTypes.Input_2002); types.add(DataMapperElementTypes.Output_2003); types.add(DataMapperElementTypes.Equal_2005); types.add(DataMapperElementTypes.Subtract_2013); types.add(DataMapperElementTypes.Concat_2006); types.add(DataMapperElementTypes.Add_2012); types.add(DataMapperElementTypes.Split_2007); types.add(DataMapperElementTypes.Constant_2008); types.add(DataMapperElementTypes.LowerCase_2009); types.add(DataMapperElementTypes.Contains_2010); types.add(DataMapperElementTypes.UpperCase_2011); types.add(DataMapperElementTypes.Multiply_2014); types.add(DataMapperElementTypes.Divide_2015); types.add(DataMapperElementTypes.Celi_2016); types.add(DataMapperElementTypes.Floor_2017); types.add(DataMapperElementTypes.Round_2018); types.add(DataMapperElementTypes.SetPrecision_2019); types.add(DataMapperElementTypes.AbsoluteValue_2020); types.add(DataMapperElementTypes.StringLength_2021); types.add(DataMapperElementTypes.StartsWith_2022); types.add(DataMapperElementTypes.EndsWith_2023); types.add(DataMapperElementTypes.Substring_2024); types.add(DataMapperElementTypes.IfElse_2025); types.add(DataMapperElementTypes.AND_2026); types.add(DataMapperElementTypes.OR_2027); types.add(DataMapperElementTypes.NOT_2028); types.add(DataMapperElementTypes.Trim_2029); types.add(DataMapperElementTypes.Replace_2030); types.add(DataMapperElementTypes.Match_2031); types.add(DataMapperElementTypes.Min_2032); types.add(DataMapperElementTypes.Max_2033); types.add(DataMapperElementTypes.CustomFunction_2034); types.add(DataMapperElementTypes.Properties_2035); types.add(DataMapperElementTypes.Compare_2036); types.add(DataMapperElementTypes.StringToNumber_2037); types.add(DataMapperElementTypes.StringToBoolean_2038); types.add(DataMapperElementTypes.Clone_2039); types.add(DataMapperElementTypes.ToString_2040); types.add(DataMapperElementTypes.GlobalVariable_2041); return types; } }
prabushi/devstudio-tooling-esb
plugins/org.wso2.developerstudio.visualdatamapper.diagram/src/org/wso2/developerstudio/datamapper/diagram/providers/assistants/DataMapperModelingAssistantProviderOfDataMapperRootEditPart.java
Java
apache-2.0
2,706
#define BOOST_TEST_MODULE TEST_NODES #include <dynet/functors.h> #include <dynet/dynet.h> #include <dynet/expr.h> #include <dynet/grad-check.h> #include <boost/test/unit_test.hpp> #include "test.h" #include <stdexcept> using namespace dynet; using namespace std; struct NodeTest { NodeTest() { // initialize if necessary if (default_device == nullptr) { for (auto x : {"NodeTest", "--dynet-mem", "100"}) { av.push_back(strdup(x)); } ADD_EXTRA_ARGUMENTS(av) char **argv = &av[0]; int argc = av.size(); dynet::initialize(argc, argv); } ones3_vals = {1.f, 1.f, 1.f}; first_one_vals = {1.f, 0.f, 0.f}; ones2_vals = {1.f, 1.f}; batch_vals = {1.1f, 2.6f, 3.3f, 4.0f, 5.1f, 6.6f}; // Create parameters std::vector<float> param1_vals = {1.1f, -2.2f, 3.3f}; std::vector<float> param2_vals = {2.2f, 3.4f, -1.2f}; std::vector<float> param3_vals = {1.1f, 2.2f, 3.3f}; std::vector<float> param4_vals = {1.1f, 2.2f, 3.3f, -1.2f, 2.1f, 3.4f}; std::vector<float> param5_vals = {-0.2f, 0.0f, 0.1f}; std::vector<float> param_scalar1_vals = {2.2f}; std::vector<float> param_scalar2_vals = {1.1f}; std::vector<float> param_kernel1_vals = {1.1f, 2.2f, -1.0f, 1.2f, -3.4f, -0.2f}; std::vector<float> param_filter1_vals = {1.1f, 2.2f, -1.0f, 1.2f, -3.4f, -0.2f, 11.1f, 12.2f, 13.3f, 11.2f, 12.2f, 13.2f }; std::vector<float> param_square1_vals = {1.1f, 2.2f, 3.4f, 1.2f, 2.5f, 3.2f, 5.3f, 2.3f, 3.3f}; std::vector<float> param_cube1_vals = {.051f, .062f, .073f, .052f, .062f, .072f, .053f, .063f, .073f, .111f, -.122f, -.033f, -.112f, -.022f, -.132f, -.113f, -.123f, -.133f, .211f, .222f, .233f, .212f, .222f, .232f, .213f, .223f, .233f }; std::vector<float> param_cube2_vals = { .011f, 1.011f, .022f, 1.022f, .033f, 1.033f, .012f, 1.012f, .022f, 1.022f, .032f, 1.032f, .013f, 1.013f, .023f, 1.023f, .033f, 1.033f, // 18 .111f, 1.111f, -.122f, -1.122f, -.033f, -1.033f, -.112f, -1.112f, -.022f, -1.022f, -.132f, -1.132f, -.113f, -1.113f, -.123f, -1.123f, -.133f, -1.133f, // 18 .211f, 1.211f, .222f, 1.222f, .233f, 1.233f, .212f, 1.212f, .222f, 1.222f, .232f, 1.232f, .213f, 1.213f, .223f, 1.223f, .233f, 1.233f }; param1 = mod.add_parameters({3}); TensorTools::set_elements(param1.get_storage().values, param1_vals); param2 = mod.add_parameters({3}); TensorTools::set_elements(param2.get_storage().values, param2_vals); param3 = mod.add_parameters({3}); TensorTools::set_elements(param3.get_storage().values, param3_vals); param4 = mod.add_parameters({6}); TensorTools::set_elements(param4.get_storage().values, param4_vals); param5 = mod.add_parameters({3}); TensorTools::set_elements(param5.get_storage().values, param5_vals); param_scalar1 = mod.add_parameters({1}); TensorTools::set_elements(param_scalar1.get_storage().values, param_scalar1_vals); param_scalar2 = mod.add_parameters({1}); TensorTools::set_elements(param_scalar2.get_storage().values, param_scalar2_vals); param_kernel1 = mod.add_parameters({3, 2}); TensorTools::set_elements(param_kernel1.get_storage().values, param_kernel1_vals); param_filter1 = mod.add_parameters({3, 2, 2}); TensorTools::set_elements(param_filter1.get_storage().values, param_filter1_vals); param_square1 = mod.add_parameters({3, 3}); TensorTools::set_elements(param_square1.get_storage().values, param_square1_vals); param_cube1 = mod.add_parameters({3, 3, 3}); TensorTools::set_elements(param_cube1.get_storage().values, param_cube1_vals); param_cube2 = mod.add_parameters({3, 3, 6}); TensorTools::set_elements(param_cube2.get_storage().values, param_cube2_vals); lookup1 = mod.add_lookup_parameters(3, {3}); TensorTools::set_elements(lookup1.get_storage().all_values, param_square1_vals); lookup2 = mod.add_lookup_parameters(10, {3}); lookup3 = mod2.add_lookup_parameters(10, {3}); lookup4 = mod.add_lookup_parameters(10, {2,3,4,5}); } ~NodeTest() { // for (auto x : av) free(x); } template <class T> std::string print_vec(const std::vector<T> vec) { ostringstream oss; if (vec.size()) oss << vec[0]; for (size_t i = 1; i < vec.size(); i++) oss << ' ' << vec[i]; return oss.str(); } // When testing a function that produces a non-scalar result, we need to // convert the tensor to a scalar so that we can backprop. However, if you // aren't careful, you can end up with partial derivatives that have // symmetries that are likely to mask certain bugs. This function provides // "asymmetric" gradients onto the tensor valued function. static Expression to_scalar(const Expression& e) { // square = guarantee element's gradients are not all 1 // sqrt = if e has multiple batches, guarantees the gradients onto the // elements of the batch will be not all 1. return sqrt(sum_elems(square(e))); } std::vector<float> ones3_vals, ones2_vals, first_one_vals, batch_vals; std::vector<char*> av; dynet::ParameterCollection mod, mod2; dynet::Parameter param1, param2, param3, param4, param5, param_scalar1, param_scalar2, param_kernel1, param_filter1, param_square1, param_cube1, param_cube2; dynet::LookupParameter lookup1, lookup2, lookup3, lookup4; }; // define the test suite BOOST_FIXTURE_TEST_SUITE(node_test, NodeTest); // Expression constant(const Dim d, float val); BOOST_AUTO_TEST_CASE( constant_value ) { dynet::ComputationGraph cg; float mystery_constant = 3.14159f; Expression x = constant(cg, Dim({3}), mystery_constant); vector<float> z = as_vector(x.value()); for (unsigned i = 0; i < 3; i++) BOOST_CHECK_EQUAL(z[i], mystery_constant); } // Expression zeros(const Dim d, float val); BOOST_AUTO_TEST_CASE( zeros_value ) { dynet::ComputationGraph cg; Expression x = zeros(cg, Dim({3})); vector<float> z = as_vector(x.value()); for (unsigned i = 0; i < 3; i++) BOOST_CHECK_EQUAL(z[i], 0.f); } // Expression operator-(const Expression& x); BOOST_AUTO_TEST_CASE( negate_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = -x1; Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression operator+(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( add_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression y = x1 + x2; Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression operator+(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( cadd_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression y = x1 + x2; Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression operator+(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( cadd_scalar_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param_scalar2); Expression y = (x1 + x2) + (x2 + x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression operator+(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( cadd_broadcast2_gradient ) { Dim dim_permutations[] = {Dim({3,1},2), Dim({3,2},1)}; dynet::ComputationGraph cg; for(int i=0; i<2; i++){ Dim dim = dim_permutations[i]; Expression x1 = reshape(parameter(cg, param1), Dim({3,1},1)); Expression x2 = reshape(parameter(cg, param4), dim); Expression y = (x1 + x2) + (x2 + x1); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } } // Expression operator+(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( cadd_broadcast3_gradient ) { Dim dim_permutations[] = {Dim({3,3,3},1), Dim({3,3,1},3), Dim({1,3,3},3), Dim({9,3,1},1), Dim({1,3,9},1), Dim({1,3,1},9), Dim({3,3},3), Dim({9,3},1), Dim({1,3},9)}; dynet::ComputationGraph cg; for(int i=0; i<6; i++){ Dim dim = dim_permutations[i]; Expression x1 = reshape(parameter(cg, param1), Dim({1,3,1},1)); Expression x2 = reshape(parameter(cg, param_cube1), dim); Expression y = (x1 + x2) + (x2 - x1); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } } // Expression operator+(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( cadd_broadcast2_neg_val ) { dynet::ComputationGraph cg; Expression x1 = reshape(parameter(cg, param1), Dim({3,1},1)); Expression x2 = reshape(parameter(cg, param4), Dim({3,1},2)); Expression y = x1 - x2; Expression z = sum_batches(sum_elems(y)); BOOST_CHECK_CLOSE(as_scalar(z.value()), -6.5, 0.001); } // Expression cdiv(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( scalar_expr_add_1_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param_scalar2); Expression y = x1 + x2; Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cdiv(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( scalar_expr_add_2_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param_scalar2); Expression x2 = parameter(cg, param1); Expression y = x1 + x2; Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cdiv(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( scalar_expr_add_batch1_gradient ) { dynet::ComputationGraph cg; Expression x1 = reshape(parameter(cg, param_square1), Dim({1, 3}, 3)); Expression x2 = parameter(cg, param_scalar2); Expression y = x1 + x2; Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cdiv(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( scalar_expr_add_batch2_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = reshape(parameter(cg, param_square1), Dim({1}, 9)); Expression y = x1 + x2; Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cdiv(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( scalar_expr_sub_1_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param_scalar2); Expression y = x1 - x2; Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cdiv(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( scalar_expr_sub_2_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param_scalar2); Expression x2 = parameter(cg, param1); Expression y = x1 - x2; Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cdiv(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( scalar_expr_sub_batch1_gradient ) { dynet::ComputationGraph cg; Expression x1 = reshape(parameter(cg, param_square1), Dim({1, 3}, 3)); Expression x2 = parameter(cg, param_scalar2); Expression y = x1 - x2; Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cdiv(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( scalar_expr_sub_batch2_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = reshape(parameter(cg, param_square1), Dim({1}, 9)); Expression y = x1 - x2; Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression sum(const std::initializer_list<Expression>& xs); BOOST_AUTO_TEST_CASE( sum_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression y = sum({x2, x1, x2}); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression sum(const std::initializer_list<Expression>& xs); BOOST_AUTO_TEST_CASE( sum_batch_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression x3 = input(cg, Dim({3}, 2), batch_vals); Expression y = sum({x3, x1, cmult(x2, x3)}); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression sum(const std::initializer_list<Expression>& xs); BOOST_AUTO_TEST_CASE( empty_sum ) { dynet::ComputationGraph cg; vector<Expression> y; BOOST_CHECK_THROW(as_vector(sum(y).value()), std::invalid_argument); } // Expression sum(const std::initializer_list<Expression>& xs); BOOST_AUTO_TEST_CASE( cumsum_gradient ) { dynet::ComputationGraph cg; Expression x = parameter(cg, param_cube1); vector<Expression> y; for (unsigned d=0;d<3;d++){ y.push_back(squared_norm(cumsum(x, d))); } Expression z = sum(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression logsumexp(const std::initializer_list<Expression>& xs); BOOST_AUTO_TEST_CASE( logsumexp_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param_scalar1); Expression x2 = parameter(cg, param_scalar2); Expression z = logsumexp({x1, x2}); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression logsumexp(const std::initializer_list<Expression>& xs); BOOST_AUTO_TEST_CASE( logsumexp_vector_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression z = to_scalar(logsumexp({x1, x2})); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression logsumexp(const std::initializer_list<Expression>& xs); BOOST_AUTO_TEST_CASE( logsumexp_singleelem_batch_gradient ) { dynet::ComputationGraph cg; Expression x = parameter(cg, param1); Expression y = reshape(x, Dim({1}, 3)); Expression z = sum_batches(logsumexp({y})); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression logsumexp(const std::initializer_list<Expression>& xs); BOOST_AUTO_TEST_CASE( logsumexp_inequal_batch_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = input(cg, Dim({3}, 2), batch_vals); Expression x3 = x1 + x2; Expression z = sum_batches(to_scalar(logsumexp({x1, x3}))); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression logsumexp(x); BOOST_AUTO_TEST_CASE( logsumexp_dim_gradient ) { dynet::ComputationGraph cg; Expression x = parameter(cg, param_square1); vector<Expression> exps; for (int d = 1; d >= 0; d--) exps.push_back(logsumexp_dim(x, d)); Expression z = to_scalar(sum(exps)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression operator+(const Expression& x, real y); BOOST_AUTO_TEST_CASE( addscalar_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = x1 + 2.0; Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression operator+(real x, const Expression& y); BOOST_AUTO_TEST_CASE( scalaradd_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = 2.0 + x1; Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression operator-(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( subtract_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression y = x1 - x2; Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression operator-(real x, const Expression& y); BOOST_AUTO_TEST_CASE( scalarsubtract_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = 2.0 - x1; Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression operator-(const Expression& x, real y); BOOST_AUTO_TEST_CASE( subtractscalar_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = x1 - 2.0; Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression operator*(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( multiply_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression y = x1 * transpose(x2); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression operator*(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( multiply_batch_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = input(cg, Dim({3}, 2), batch_vals); Expression y = x1 * transpose(x2); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression operator*(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( affine_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression scalar = parameter(cg, param_scalar1); Expression x2 = parameter(cg, param2); Expression y = sqrt(affine_transform({x1, x2, scalar})); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); BOOST_CHECK(y.dim() == x1.dim()); } // Expression operator*(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( affine_batch_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression scalar = parameter(cg, param_scalar1); Expression x2 = input(cg, Dim({3}, 2), batch_vals); Expression y = sqrt(affine_transform({x1, x2, scalar})); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression operator*(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( affine_batch_col_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression scalar = parameter(cg, param_scalar1); Expression x2 = input(cg, Dim({1, 3}, 2), batch_vals); Expression y = sqrt(affine_transform({transpose(x1), scalar, x2})); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression operator*(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( affine_batch2_gradient ) { dynet::ComputationGraph cg; Expression x1 = input(cg, Dim({1, 3}, 2), batch_vals); Expression scalar = parameter(cg, param_scalar1); Expression x2 = parameter(cg, param2); Expression y = sqrt( affine_transform({x1, scalar, transpose(x2) }) ); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression operator*(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( affine_batch3_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param_square1); Expression inp = input(cg, Dim({3}, 2), batch_vals); Expression y = sqrt( affine_transform({x1, x2, inp }) ); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression operator*(const Expression& x, float y); BOOST_AUTO_TEST_CASE( multiplyscalar_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = x1 * 2.0; Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // inline Expression operator*(float y, const Expression& x) { return x * y; } BOOST_AUTO_TEST_CASE( scalarmultiply_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = 2.0 * x1; Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // inline Expression operator/(const Expression& x, float y) { return x * (1.f / y); } BOOST_AUTO_TEST_CASE( dividescalar_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = x1 / 2.0; Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cdiv(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( cdiv_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression y = cdiv(x1, x2); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cdiv(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( cdiv_batch_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = input(cg, Dim({3}, 2), batch_vals); Expression y = cdiv(x2, x1); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cdiv(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( scalar_cdiv_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param_scalar2); Expression y = cdiv(x1, x2); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cdiv(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( scalar_cdiv_batch1_gradient ) { dynet::ComputationGraph cg; Expression x1 = reshape(parameter(cg, param_square1), Dim({1, 3}, 3)); Expression x2 = parameter(cg, param_scalar2); Expression y = cdiv(x1, x2); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cdiv(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( scalar_cdiv_batch2_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = input(cg, Dim({3}, 2), batch_vals); Expression y = cdiv(x2, x1); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cdiv(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( cdiv_broadcast2_gradient ) { Dim dim_permutations[] = {Dim({3,1},2), Dim({3,2},1)}; dynet::ComputationGraph cg; for(int i=0; i<2; i++){ Dim dim = dim_permutations[i]; Expression x1 = reshape(parameter(cg, param1), Dim({3,1},1)); Expression x2 = reshape(parameter(cg, param4), dim); Expression y = cdiv(x2, x1); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } } // Expression cdiv(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( cdiv_broadcast3_gradient ) { Dim dim_permutations[] = {Dim({3,3,3},1), Dim({3,3,1},3), Dim({1,3,3},3), Dim({9,3,1},1), Dim({1,3,9},1), Dim({1,3,1},9)}; dynet::ComputationGraph cg; for(int i=0; i<6; i++){ Dim dim = dim_permutations[i]; Expression x1 = reshape(parameter(cg, param1), Dim({1,3,1},1)); Expression x2 = reshape(parameter(cg, param_cube1), dim); Expression y = cdiv(x2, x1); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } } // Expression colwise_add(const Expression& x, const Expression& bias); BOOST_AUTO_TEST_CASE( colwise_add_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression y = colwise_add(x1 * transpose(x2), x2); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression colwise_add(const Expression& x, const Expression& bias); BOOST_AUTO_TEST_CASE( colwise_add_batch1_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression x3 = input(cg, Dim({1, 3}, 2), batch_vals); Expression y = colwise_add(x1 * x3, x2); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression colwise_add(const Expression& x, const Expression& bias); BOOST_AUTO_TEST_CASE( colwise_add_batch2_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression x3 = input(cg, Dim({3}, 2), batch_vals); Expression y = colwise_add(x1 * transpose(x2), cmult(x2, x3)); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression concatenate_cols(const std::initializer_list<Expression>& xs); BOOST_AUTO_TEST_CASE( concatenate_cols_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression y = concatenate_cols({x1, x2, x1}); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression concatenate_cols(const std::initializer_list<Expression>& xs); BOOST_AUTO_TEST_CASE( concatenate_cols_vecmatrix_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param_square1); Expression y = concatenate_cols({x1, x2, x1}); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression concatenate_to_batch(const std::initializer_list<Expression>& xs); BOOST_AUTO_TEST_CASE( concatenate_to_batch_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = input(cg, Dim({3}, 2), batch_vals); Expression xsquare = parameter(cg, param_square1); Expression y = concatenate_to_batch({x1, x2}); Expression z = sum_batches(to_scalar(xsquare * y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression concatenate(const std::initializer_list<Expression>& xs); BOOST_AUTO_TEST_CASE( concatenate_gradient ) { dynet::ComputationGraph cg; Expression x1 = transpose(parameter(cg, param1)); Expression x2 = transpose(parameter(cg, param2)); Expression y = concatenate({x1, x2, x1}); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression concatenate(const std::initializer_list<Expression>& xs); BOOST_AUTO_TEST_CASE( concatenate_batch_gradient ) { dynet::ComputationGraph cg; Expression x1 = transpose(parameter(cg, param1)); Expression x2 = transpose(parameter(cg, param2)); Expression x3 = input(cg, Dim({1, 3}, 2), batch_vals); Expression y = concatenate({x1, x2, cmult(x2, x3)}); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression contract3d_1d(const Expression& x, const Expression& y, const Expression& b); BOOST_AUTO_TEST_CASE( contract3d_1d_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression square1 = parameter(cg, param_square1); Expression cube1 = parameter(cg, param_cube1); Expression y = contract3d_1d(cube1, x1, square1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression contract3d_1d(const Expression& x, const Expression& y, const Expression& b); BOOST_AUTO_TEST_CASE( contract3d_batch_1d_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression square1 = parameter(cg, param_square1); Expression cube1 = parameter(cg, param_cube1); Expression batched_cube1 = concatenate_to_batch({cube1, cube1, cube1}); Expression y = contract3d_1d(batched_cube1, x1, square1); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression contract3d_1d(const Expression& x, const Expression& y, const Expression& b); BOOST_AUTO_TEST_CASE( contract3d_1d_batch_gradient ) { dynet::ComputationGraph cg; Expression batched_x1 = reshape(parameter(cg, param_square1), Dim({3}, 3)); Expression square1 = parameter(cg, param_square1); Expression cube1 = parameter(cg, param_cube1); Expression y = contract3d_1d(cube1, batched_x1, square1); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression contract3d_1d(const Expression& x, const Expression& y, const Expression& b); BOOST_AUTO_TEST_CASE( contract3d_batch_1d_batch_gradient ) { dynet::ComputationGraph cg; Expression batched_x1 = reshape(parameter(cg, param_square1), Dim({3}, 3)); Expression square1 = parameter(cg, param_square1); Expression cube1 = parameter(cg, param_cube1); Expression batched_cube1 = concatenate_to_batch({cube1, cube1, cube1}); Expression y = contract3d_1d(batched_cube1, batched_x1, square1); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression contract3d_1d_1d(const Expression& x, const Expression& y, const Expression& z, const Expression& b); BOOST_AUTO_TEST_CASE( contract3d_1d_1d_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression x3 = parameter(cg, param3); Expression cube1 = parameter(cg, param_cube1); Expression y = contract3d_1d_1d(cube1, x1, x2, x3); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression sqrt(const Expression& x); BOOST_AUTO_TEST_CASE( sqrt_gradient ) { dynet::ComputationGraph cg; Expression x3 = parameter(cg, param3); Expression y = sqrt(x3); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression abs(const Expression& x); BOOST_AUTO_TEST_CASE( abs_gradient ) { dynet::ComputationGraph cg; Expression x3 = parameter(cg, param3); Expression y = abs(x3); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression erf(const Expression& x); BOOST_AUTO_TEST_CASE( erf_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = erf(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression sin(const Expression& x); BOOST_AUTO_TEST_CASE( sin_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = sin(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cos(const Expression& x); BOOST_AUTO_TEST_CASE( cos_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = cos(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression tan(const Expression& x); BOOST_AUTO_TEST_CASE( tan_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = tan(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression asin(const Expression& x); BOOST_AUTO_TEST_CASE( asin_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param5); Expression y = asin(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression acos(const Expression& x); BOOST_AUTO_TEST_CASE( acos_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param5); Expression y = acos(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression atan(const Expression& x); BOOST_AUTO_TEST_CASE( atan_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param5); Expression y = atan(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression sinh(const Expression& x); BOOST_AUTO_TEST_CASE( sinh_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = sinh(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cosh(const Expression& x); BOOST_AUTO_TEST_CASE( cosh_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = cosh(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression tanh(const Expression& x); BOOST_AUTO_TEST_CASE( tanh_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = tanh(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression asinh(const Expression& x); BOOST_AUTO_TEST_CASE( asinh_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param3); Expression y = asinh(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression acosh(const Expression& x); BOOST_AUTO_TEST_CASE( acosh_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param3); Expression y = acosh(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression atanh(const Expression& x); BOOST_AUTO_TEST_CASE( atanh_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param5); Expression y = atanh(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression exp(const Expression& x); BOOST_AUTO_TEST_CASE( exp_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = exp(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression square(const Expression& x); BOOST_AUTO_TEST_CASE( square_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = square(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cube(const Expression& x); BOOST_AUTO_TEST_CASE( cube_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = cube(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression log_sigmoid(const Expression& x); BOOST_AUTO_TEST_CASE( log_sigmoid_gradient ) { dynet::ComputationGraph cg; Expression x2 = parameter(cg, param2); Expression y = log_sigmoid(x2); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression lgamma(const Expression& x); BOOST_AUTO_TEST_CASE( lgamma_gradient ) { dynet::ComputationGraph cg; Expression x2 = parameter(cg, param2); Expression y = lgamma(x2); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression log(const Expression& x); BOOST_AUTO_TEST_CASE( log_gradient ) { dynet::ComputationGraph cg; Expression x3 = parameter(cg, param3); Expression y = log(x3); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression logistic(const Expression& x); BOOST_AUTO_TEST_CASE( logistic_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = logistic(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression rectify(const Expression& x); BOOST_AUTO_TEST_CASE( rectify_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = rectify(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression elu(const Expression& x); BOOST_AUTO_TEST_CASE( elu_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = elu(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression selu(const Expression& x); BOOST_AUTO_TEST_CASE( selu_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = selu(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression silu(const Expression& x); BOOST_AUTO_TEST_CASE( silu_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = silu(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression round(const Expression& x, GradientMode gradient_mode); BOOST_AUTO_TEST_CASE( round_forward ) { // batch_vals = {1.1f, 2.6f, 3.3f, 4.0f, 5.1f, 6.6f}; dynet::ComputationGraph cg; Expression x = input(cg, Dim({3}, 2), batch_vals); Expression y = round(x, zero_gradient); std::vector<float> v = as_vector(y.value()); BOOST_CHECK_EQUAL(v[0], 1.0); BOOST_CHECK_EQUAL(v[1], 3.0); BOOST_CHECK_EQUAL(v[2], 3.0); BOOST_CHECK_EQUAL(v[3], 4.0); BOOST_CHECK_EQUAL(v[4], 5.0); BOOST_CHECK_EQUAL(v[5], 7.0); } // Expression ceil(const Expression& x, GradientMode gradient_mode); BOOST_AUTO_TEST_CASE( ceil_forward ) { // batch_vals = {1.1f, 2.6f, 3.3f, 4.0f, 5.1f, 6.6f}; dynet::ComputationGraph cg; Expression x = input(cg, Dim({3}, 2), batch_vals); Expression y = ceil(x, zero_gradient); std::vector<float> v = as_vector(y.value()); BOOST_CHECK_EQUAL(v[0], 2.0); BOOST_CHECK_EQUAL(v[1], 3.0); BOOST_CHECK_EQUAL(v[2], 4.0); BOOST_CHECK_EQUAL(v[3], 4.0); BOOST_CHECK_EQUAL(v[4], 6.0); BOOST_CHECK_EQUAL(v[5], 7.0); } // Expression floor(const Expression& x, GradientMode gradient_mode); BOOST_AUTO_TEST_CASE( floor_forward ) { // batch_vals = {1.1f, 2.6f, 3.3f, 4.0f, 5.1f, 6.6f}; dynet::ComputationGraph cg; Expression x = input(cg, Dim({3}, 2), batch_vals); Expression y = floor(x, zero_gradient); std::vector<float> v = as_vector(y.value()); BOOST_CHECK_EQUAL(v[0], 1.0); BOOST_CHECK_EQUAL(v[1], 2.0); BOOST_CHECK_EQUAL(v[2], 3.0); BOOST_CHECK_EQUAL(v[3], 4.0); BOOST_CHECK_EQUAL(v[4], 5.0); BOOST_CHECK_EQUAL(v[5], 6.0); } // Expression hinge(const Expression& x, unsigned index, float m = 1.0); BOOST_AUTO_TEST_CASE( hinge_gradient ) { unsigned index = 0; dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression z = hinge(x1, index, 0.5); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression hinge(const Expression& x, unsigned index, float m = 1.0); BOOST_AUTO_TEST_CASE( hinge_multiple_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); vector<Expression> exp; for (unsigned index = 3; index > 0; --index) exp.push_back(hinge(x1, index - 1, 0.5)); Expression z = sum(exp); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression hinge(const Expression& x, unsigned index, float m = 1.0); BOOST_AUTO_TEST_CASE( hinge_batch_gradient ) { std::vector<unsigned> idx = {1, 2}; dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = input(cg, Dim({3}, 2), batch_vals); Expression z = sum_batches(hinge(x1 + x2, idx, 2.f)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression hinge(const Expression& x, const unsigned* pindex, float m = 1.0); BOOST_AUTO_TEST_CASE( hingeptr_gradient ) { unsigned index = 0; dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression z = hinge(x1, &index, 0.5); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression hinge_dim(const Expression& x, unsigned index, unsigned dim = 0, float m = 1.0); BOOST_AUTO_TEST_CASE( hinge_dim_gradient ) { std::vector<unsigned> index = {0, 1, 2}; dynet::ComputationGraph cg; Expression x1 = parameter(cg, param_square1); Expression z = to_scalar(hinge_dim(x1, index, 0, 0.5) + hinge_dim(x1, index, 1, 0.5)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression log_softmax(const Expression& x); BOOST_AUTO_TEST_CASE( log_softmax_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = log_softmax(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression log_softmax(const Expression& x); BOOST_AUTO_TEST_CASE( log_softmax_autobatch_gradient ) { auto autobatch_cache = dynet::autobatch_flag; dynet::autobatch_flag = 1; dynet::ComputationGraph cg; vector<Expression> vals; { Expression x1 = parameter(cg, param1); vals.push_back(log_softmax(x1)); } { Expression x2 = parameter(cg, param2); vals.push_back(log_softmax(x2)); } Expression y = sum(vals); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); dynet::autobatch_flag = autobatch_cache; } // Expression log_softmax(const Expression& x, unsigned v); BOOST_AUTO_TEST_CASE( log_softmax_batch_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = input(cg, Dim({3}, 2), batch_vals); Expression y = log_softmax(x1 + x2); Expression z = sum_batches(input(cg, {1, 3}, first_one_vals) * y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression log_softmax(const Expression& x, unsigned v); BOOST_AUTO_TEST_CASE( log_softmax_colbatch_gradient ) { dynet::ComputationGraph cg; Expression x = reshape(parameter(cg, param_cube1), Dim({3, 3}, 3)); Expression y = log_softmax(x); Expression z = sum_batches(input(cg, {1, 3}, first_one_vals) * y * input(cg, {3}, first_one_vals)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression log_softmax(const Expression& x, const std::vector<unsigned>& restriction); BOOST_AUTO_TEST_CASE( restricted_log_softmax_gradient ) { vector<unsigned> restriction = {0, 1}; dynet::ComputationGraph cg; Expression x3 = parameter(cg, param3); Expression y = exp( log_softmax(x3, restriction) ); Expression z = input(cg, {1, 3}, first_one_vals) * y; BOOST_CHECK(check_grad(mod, z, 0)); } // Expression softmax(const Expression& x); BOOST_AUTO_TEST_CASE( softmax_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = log(softmax(x1)); Expression z = input(cg, {1, 3}, first_one_vals) * y; BOOST_CHECK(check_grad(mod, z, 0)); } // Expression softmax(const Expression& x, unsigned v); BOOST_AUTO_TEST_CASE( softmax_batch_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = input(cg, Dim({3}, 2), batch_vals); Expression y = log(softmax(x1 + x2)); Expression z = sum_batches(input(cg, {1, 3}, first_one_vals) * y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression softmax(const Expression& x, unsigned v); BOOST_AUTO_TEST_CASE( softmax_colbatch_gradient ) { dynet::ComputationGraph cg; Expression x = reshape(parameter(cg, param_cube1), Dim({3, 3}, 3)); Expression y = softmax(x); Expression z = sum_batches(input(cg, {1, 3}, first_one_vals) * y * input(cg, {3}, first_one_vals)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression softmax(const Expression& x, unsigned v); BOOST_AUTO_TEST_CASE( softmax_cols_colbatch_gradient ) { dynet::ComputationGraph cg; Expression x = reshape(parameter(cg, param_cube1), Dim({3, 3}, 3)); Expression y = softmax(x, 1); Expression z = sum_batches(input(cg, {1, 3}, first_one_vals) * y * input(cg, {3}, first_one_vals)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression sparsemax(const Expression& x); BOOST_AUTO_TEST_CASE( sparsemax_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = sparsemax(x1); Expression z = input(cg, {1, 3}, first_one_vals) * y; BOOST_CHECK(check_grad(mod, z, 0)); } // Expression sparsemax_loss(const Expression& x); BOOST_AUTO_TEST_CASE( sparsemax_loss_gradient ) { std::vector<unsigned> idxs(2); idxs[0] = 1; idxs[1] = 2; dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression z = sparsemax_loss(x1, idxs); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression softsign(const Expression& x); BOOST_AUTO_TEST_CASE( softsign_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = softsign(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression pow(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( pow_gradient ) { dynet::ComputationGraph cg; Expression x3 = parameter(cg, param3); Expression x_scalar1 = parameter(cg, param_scalar1); Expression y = pow(x3, x_scalar1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression min(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( min_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression y = min(x1, x2); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression max(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( max_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression y = max(x1, x2); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // TODO: Noise is random, so it cannot be tested simply? // Expression noise(const Expression& x, real stddev); BOOST_AUTO_TEST_CASE( noise_forward ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = noise(x1, 0.5); Expression z = to_scalar(y); cg.forward(z); } //TODO: Dropout scales the gradients at training time, so they don't match. // Expression dropout(const Expression& x, real p); BOOST_AUTO_TEST_CASE( dropout_forward ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = dropout(x1, 0.5); Expression z = to_scalar(y); cg.forward(z); } BOOST_AUTO_TEST_CASE( dropout_batch_forward ) { dynet::ComputationGraph cg; Expression x = input(cg, Dim({3}, 2), batch_vals); Expression y = dropout_batch(x, 0.5); Expression z = to_scalar(y); cg.forward(z); } BOOST_AUTO_TEST_CASE( dropout_dim_forward ) { for (unsigned d = 0; d < 3; d++) { dynet::ComputationGraph cg; Expression x = parameter(cg, param_cube1); Expression y = dropout_dim(x, d, 0.5); Expression z = to_scalar(y); cg.forward(z); } } // TODO: Dropout scales the gradients at training time, so they don't match. // Expression block_dropout(const Expression& x, real p); // Expression argmax(const Expression& x, GradientMode gradient_mode); BOOST_AUTO_TEST_CASE( argmax_forward ) { dynet::ComputationGraph cg; Expression x = input(cg, Dim({3}, 2), batch_vals); Expression y = argmax(x, zero_gradient); std::vector<float> v = as_vector(y.value()); BOOST_CHECK_EQUAL(v[0], 0.0); BOOST_CHECK_EQUAL(v[1], 0.0); BOOST_CHECK_EQUAL(v[2], 1.0); BOOST_CHECK_EQUAL(v[3], 0.0); BOOST_CHECK_EQUAL(v[4], 0.0); BOOST_CHECK_EQUAL(v[5], 1.0); } // Expression argmax(const Expression& x, GradientMode gradient_mode); BOOST_AUTO_TEST_CASE( argmax_backward ) { dynet::ComputationGraph cg; Expression x = input(cg, Dim({3}, 2), batch_vals); Expression y = argmax(x, zero_gradient); Expression z = sum_batches(squared_norm(y)); cg.backward(z, true); std::vector<float> g_x = as_vector(x.gradient()); BOOST_CHECK_EQUAL(g_x[0], 0.0); BOOST_CHECK_EQUAL(g_x[1], 0.0); BOOST_CHECK_EQUAL(g_x[2], 0.0); BOOST_CHECK_EQUAL(g_x[3], 0.0); BOOST_CHECK_EQUAL(g_x[4], 0.0); BOOST_CHECK_EQUAL(g_x[5], 0.0); } // Expression argmax(const Expression& x, GradientMode gradient_mode); BOOST_AUTO_TEST_CASE( straight_through_backward ) { dynet::ComputationGraph cg; Expression x = input(cg, Dim({3}, 2), batch_vals); Expression x_ = input(cg, Dim({3}, 2), batch_vals); Expression y = argmax(x, straight_through_gradient); Expression z = sum_batches(dot_product(y, x_)); cg.backward(z, true); std::vector<float> g_x = as_vector(x.gradient()); BOOST_CHECK_EQUAL(g_x[0], batch_vals[0]); BOOST_CHECK_EQUAL(g_x[1], batch_vals[1]); BOOST_CHECK_EQUAL(g_x[2], batch_vals[2]); BOOST_CHECK_EQUAL(g_x[3], batch_vals[3]); BOOST_CHECK_EQUAL(g_x[4], batch_vals[4]); BOOST_CHECK_EQUAL(g_x[5], batch_vals[5]); } // Expression reshape(const Expression& x, const Dim& d); BOOST_AUTO_TEST_CASE( reshape_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = reshape(x1, {1, 3}); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression reshape(const Expression& x, const Dim& d); BOOST_AUTO_TEST_CASE( reshape_batch_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = input(cg, Dim({3}, 2), batch_vals); Expression y1 = x1 * transpose(x2); Expression y2 = reshape(y1, Dim({3, 3}, 2)); Expression z = sum_batches(to_scalar(y2)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression transpose(const Expression& x); BOOST_AUTO_TEST_CASE( transpose_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param_square1); Expression y = x1 * transpose(x1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression transpose(const Expression& x); BOOST_AUTO_TEST_CASE( transpose_higherorder_gradient ) { dynet::ComputationGraph cg; Expression cube1 = parameter(cg, param_cube1); Expression x1 = reshape(transpose(cube1, {2, 0, 1}), Dim({9, 3})); Expression x2 = reshape(transpose(cube1, {1, 2, 0}), Dim({3, 9})); Expression z = to_scalar(x1 * x2); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression logdet(const Expression& x); BOOST_AUTO_TEST_CASE( logdet_gradient ) { dynet::ComputationGraph cg; Expression x = parameter(cg, param_square1); Expression y = logdet(-x); BOOST_CHECK(check_grad(mod, y, 0)); } // Expression inverse(const Expression& x); BOOST_AUTO_TEST_CASE( inverse_gradient ) { dynet::ComputationGraph cg; Expression x = parameter(cg, param_square1); Expression y = inverse(x); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression trace_of_product(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( trace_of_product_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression z = trace_of_product(x1, x2); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cmult(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( cadd_broadcast_gradient_scalar ) { dynet::ComputationGraph cg; Expression x1 = reshape(parameter(cg, param_scalar1), Dim({1},1)); Expression x2 = reshape(parameter(cg, param4), Dim({3,1,1},2)); Expression y = (x1 + x2) + (x2 + x1) + (x1 - x2) + (x2 - x1); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cmult(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( cdiv_broadcast_gradient_scalar ) { dynet::ComputationGraph cg; Expression x1 = reshape(parameter(cg, param_scalar1), Dim({1},1)); Expression x2 = reshape(parameter(cg, param4), Dim({3,1,1},2)); Expression y = cdiv(x2, x1); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cmult(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( cmult_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression y = cmult(x1, x2); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cmult(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( cmult_batch_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = input(cg, Dim({3}, 2), batch_vals); Expression y = cmult(x1, x2) + cmult(x2, x1); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cmult(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( scalar_cmult_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param_scalar1); Expression x2 = parameter(cg, param2); Expression y = cmult(x1, x2); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cmult(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( scalar_cmult_batch_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param_scalar1); Expression x2 = reshape(parameter(cg, param_square1), Dim({1, 3}, 3)); Expression y = cmult(x1, x2) + cmult(x2, x1); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cmult(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( cmult_broadcast_gradient_scalar ) { dynet::ComputationGraph cg; Expression x1 = reshape(parameter(cg, param_scalar1), Dim({1},1)); Expression x2 = reshape(parameter(cg, param4), Dim({3,1,1},2)); Expression y = cmult(x1, x2) + cmult(x2, x1); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression cmult(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( cmult_broadcast2_gradient ) { Dim dim_permutations[] = {Dim({3,1},2), Dim({3,2},1)}; dynet::ComputationGraph cg; for(int i=0; i<2; i++){ Dim dim = dim_permutations[i]; Expression x1 = reshape(parameter(cg, param1), Dim({3,1},1)); Expression x2 = reshape(parameter(cg, param4), dim); Expression y = cmult(x1, x2) + cmult(x2, x1); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } } // Expression cmult(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( cmult_broadcast3_gradient ) { Dim dim_permutations[] = {Dim({3,3,3},1), Dim({3,3,1},3), Dim({1,3,3},3), Dim({9,3,1},1), Dim({1,3,9},1), Dim({1,3,1},9)}; dynet::ComputationGraph cg; for(int i=0; i<6; i++){ Dim dim = dim_permutations[i]; Expression x1 = reshape(parameter(cg, param1), Dim({1,3,1},1)); Expression x2 = reshape(parameter(cg, param_cube1), dim); Expression y = cmult(x1, x2) + cmult(x2, x1); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } } // Expression dot_product(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( dot_product_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression z = dot_product(x1, x2); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression dot_product(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( dot_product_batch_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = input(cg, Dim({3}, 2), batch_vals); Expression z = sum_batches(dot_product(x1, x2) + dot_product(x2, x1) * 2); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression dot_product(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( dot_product_matrix_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param_square1); Expression z = dot_product(x1, x1); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression squared_distance(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( squared_distance_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression z = squared_distance(x1, x2); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression squared_distance(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( squared_distance_batchright_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = input(cg, Dim({3}, 2), batch_vals); Expression z = sum_batches(squared_distance(x1, x1 + x2)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression squared_distance(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( squared_distance_batchleft_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = input(cg, Dim({3}, 2), batch_vals); Expression z = sum_batches(squared_distance(x1 + x2, x1)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression squared_distance(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( squared_distance_batchboth_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = input(cg, Dim({3}, 2), batch_vals); Expression z = sum_batches(squared_distance(x1 + x2, cmult(x1, x2))); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression squared_distance(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( squared_norm_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression z = squared_norm(x1); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression squared_distance(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( squared_norm_batch_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = input(cg, Dim({3}, 2), batch_vals); Expression z = sum_batches(squared_norm(x1 + x2)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression l2_norm(const Expression&); BOOST_AUTO_TEST_CASE( l2_norm_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression z = l2_norm(x1); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression l2_norm(const Expression& x); BOOST_AUTO_TEST_CASE( l2_norm_batch_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = input(cg, Dim({3}, 2), batch_vals); Expression z = sum_batches(l2_norm(x1 + x2)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression huber_distance(const Expression& x, const Expression& y, float c = 1.345f); BOOST_AUTO_TEST_CASE( huber_distance_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression z = huber_distance(x1, x2); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression l1_distance(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( l1_distance_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression z = l1_distance(x1, x2); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression binary_log_loss(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( binary_log_loss_gradient ) { dynet::ComputationGraph cg; Expression x1 = logistic( parameter(cg, param1) ); Expression x2 = input(cg, {3}, ones3_vals); Expression z = binary_log_loss(x1, x2); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression binary_log_loss(const Expression& x, const Expression& y); BOOST_AUTO_TEST_CASE( binary_log_loss_edgecases ) { dynet::ComputationGraph cg; float val, infinity = - log(DYNET_DEVICE_MIN); Expression x, y, z; vector<float> values = {0.0, 0.5, 1.0}; for (float vx : values) { for (float vy : values) { x = input(cg, vx); // and y == 0 y = input(cg, vy); z = binary_log_loss(x, y); val = as_scalar(z.value()); if (vx == 0.5) BOOST_CHECK_CLOSE(val, log(2), 0.1); else if (vx == vy) BOOST_CHECK_CLOSE(val, 0, 0.1); else BOOST_CHECK_CLOSE(val, infinity, 0.1); } } } // Expression pairwise_rank_loss(const Expression& x, const Expression& y, real m=1.0); BOOST_AUTO_TEST_CASE( pairwise_rank_loss_gradient ) { dynet::ComputationGraph cg; Expression x_scalar1 = parameter(cg, param_scalar1); Expression x_scalar2 = parameter(cg, param_scalar2); Expression z = pairwise_rank_loss(x_scalar1, x_scalar2); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression poisson_loss(const Expression& x, unsigned y); BOOST_AUTO_TEST_CASE( possion_loss_gradient ) { dynet::ComputationGraph cg; Expression scalar = parameter(cg, param_scalar1); Expression z = poisson_loss(scalar, 3); BOOST_CHECK(check_grad(mod, z, 0)); } /* // Expression conv1d_narrow(const Expression& x, const Expression& f); BOOST_AUTO_TEST_CASE( conv1d_narrow_gradient ) { dynet::ComputationGraph cg; Expression xsquare = parameter(cg, param_square1); Expression xkernel = parameter(cg, param_kernel1); Expression y = conv1d_narrow(xsquare, xkernel); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression conv1d_wide(const Expression& x, const Expression& f); BOOST_AUTO_TEST_CASE( conv1d_wide_gradient ) { dynet::ComputationGraph cg; Expression xkernel = parameter(cg, param_kernel1); Expression y = conv1d_wide(xkernel, xkernel); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } */ // Expression filter1d_narrow(const Expression& x, const Expression& f); BOOST_AUTO_TEST_CASE( filter1d_narrow_gradient ) { dynet::ComputationGraph cg; Expression xsquare = parameter(cg, param_square1); Expression xfilter = parameter(cg, param_filter1); Expression y = filter1d_narrow(xsquare, xfilter); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression kmax_pooling(const Expression& x, unsigned k); BOOST_AUTO_TEST_CASE( kmax_pooling_keq1_gradient ) { dynet::ComputationGraph cg; Expression xsquare = parameter(cg, param_square1); Expression y = tanh(kmax_pooling(xsquare, 1)); Expression z = pickneglogsoftmax(y, 1); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression kmax_pooling(const Expression& x, unsigned k); BOOST_AUTO_TEST_CASE( kmax_pooling_keq2_gradient ) { dynet::ComputationGraph cg; Expression xsquare = parameter(cg, param_square1); Expression y = tanh(kmax_pooling(xsquare, 2)); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression fold_rows(const Expression& x, unsigned nrows=2); BOOST_AUTO_TEST_CASE( fold_rows_gradient ) { dynet::ComputationGraph cg; Expression x4 = parameter(cg, param4); Expression y = fold_rows(x4, 2); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression circ_corr(const Expression& u, const Expression& v); BOOST_AUTO_TEST_CASE( circ_corr_gradient ) { dynet::ComputationGraph cg; Expression u = parameter(cg, param5); Expression v = parameter(cg, param2); Expression y = circ_corr(u, v); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression circ_conv(const Expression& u, const Expression& v); BOOST_AUTO_TEST_CASE( circ_conv_gradient ) { dynet::ComputationGraph cg; Expression u = parameter(cg, param5); Expression v = parameter(cg, param2); Expression y = circ_conv(u, v); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression average(const Expression& x); BOOST_AUTO_TEST_CASE( average_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression x3 = parameter(cg, param3); Expression y = average({x1, x2, x3}); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression average_cols(const Expression& x); BOOST_AUTO_TEST_CASE( average_cols_gradient ) { dynet::ComputationGraph cg; Expression xsquare = parameter(cg, param_square1); Expression y = tanh(average_cols(xsquare)); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression sum_cols(const Expression& x); BOOST_AUTO_TEST_CASE( sum_cols_gradient ) { dynet::ComputationGraph cg; Expression xsquare = parameter(cg, param_square1); Expression y = tanh(sum_cols(xsquare)); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression conv2d(const Expression& x ,const Expression& f, const std::vector<unsigned>& stride, bool is_valid); BOOST_AUTO_TEST_CASE( conv2d_valid_gradient ) { dynet::ComputationGraph cg; Parameter param_kernel = mod.add_parameters({2, 2, 2, 3}); std::vector<float> param_kernel_vals = {.011f, .022f, .033f, .012f, .022f, .032f, .013f, .023f, .033f, .111f, -.122f, -.033f, -.112f, -.022f, -.132f, -.113f, -.123f, -.133f, .211f, .222f, .233f, .212f, .222f, .232f }; TensorTools::set_elements(param_kernel.get_storage().values, param_kernel_vals); std::vector<float> conv2d_batch_vals(50 * 50 * 2 * 2); for (unsigned i = 0; i < conv2d_batch_vals.size(); ++i) { conv2d_batch_vals[i] = i * 0.011f + (i + 1) * 0.001f; } Expression x = input(cg, Dim({50, 50, 2}, 2), conv2d_batch_vals); Expression kernel = parameter(cg, param_kernel); vector<unsigned> stride = {3, 3}; bool is_valid = true; Expression y = conv2d(x, kernel, stride, is_valid); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression log_softmax(const Expression& x); BOOST_AUTO_TEST_CASE( conv2d_autobatch_gradient ) { auto autobatch_cache = dynet::autobatch_flag; dynet::autobatch_flag = 1; dynet::ComputationGraph cg; Parameter param_kernel = mod.add_parameters({2, 2, 2, 3}); std::vector<float> param_kernel_vals = {.011f, .022f, .033f, .012f, .022f, .032f, .013f, .023f, .033f, .111f, -.122f, -.033f, -.112f, -.022f, -.132f, -.113f, -.123f, -.133f, .211f, .222f, .233f, .212f, .222f, .232f }; TensorTools::set_elements(param_kernel.get_storage().values, param_kernel_vals); Expression kernel = parameter(cg, param_kernel); vector<unsigned> stride = {3, 3}; bool is_valid = true; std::vector<float> conv2d_vals1(50 * 50 * 2), conv2d_vals2(50 * 50 * 2); for (unsigned i = 0; i < conv2d_vals1.size(); ++i) { conv2d_vals1[i] = i * 0.011f + (i + 1) * 0.001f; conv2d_vals2[i] = i * 0.015f + (i + 1) * -0.001f; } vector<Expression> zs; { Expression x = input(cg, Dim({50, 50, 2}), conv2d_vals1); Expression y = conv2d(x, kernel, stride, is_valid); zs.push_back(to_scalar(y)); } { Expression x = input(cg, Dim({50, 50, 2}), conv2d_vals2); Expression y = conv2d(x, kernel, stride, is_valid); zs.push_back(to_scalar(y)); } Expression z = sum(zs); BOOST_CHECK(check_grad(mod, z, 0)); dynet::autobatch_flag = autobatch_cache; } // Expression conv2d(const Expression& x ,const Expression& f, const std::vector<unsigned>& stride, bool is_valid); BOOST_AUTO_TEST_CASE( conv2d_valid_singlefilter_gradient ) { dynet::ComputationGraph cg; Parameter param_kernel = mod.add_parameters({2, 4, 1, 3}); std::vector<float> param_kernel_vals = {.011f, .022f, .033f, .012f, .022f, .032f, .013f, .023f, .033f, .111f, -.122f, -.033f, -.112f, -.022f, -.132f, -.113f, -.123f, -.133f, .211f, .222f, .233f, .212f, .222f, .232f }; TensorTools::set_elements(param_kernel.get_storage().values, param_kernel_vals); std::vector<float> conv2d_batch_vals(50 * 100 * 1 * 2); for (unsigned i = 0; i < conv2d_batch_vals.size(); ++i) { conv2d_batch_vals[i] = i * 0.011f + (i + 1) * 0.001f; } Expression x = input(cg, Dim({50, 100}, 2), conv2d_batch_vals); Expression kernel = parameter(cg, param_kernel); vector<unsigned> stride = {3, 3}; bool is_valid = true; Expression y = conv2d(x, kernel, stride, is_valid); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } BOOST_AUTO_TEST_CASE( conv2d_same_gradient ) { dynet::ComputationGraph cg; Parameter param_kernel = mod.add_parameters({2, 2, 2, 3}); std::vector<float> param_kernel_vals = {.011f, .022f, .033f, .012f, .022f, .032f, .013f, .023f, .033f, .111f, -.122f, -.033f, -.112f, -.022f, -.132f, -.113f, -.123f, -.133f, .211f, .222f, .233f, .212f, .222f, .232f }; TensorTools::set_elements(param_kernel.get_storage().values, param_kernel_vals); Parameter param_kernel2 = mod.add_parameters({2, 2, 3, 2}); TensorTools::set_elements(param_kernel2.get_storage().values, param_kernel_vals); std::vector<float> conv2d_batch_vals(2 * 50 * 50 * 2); for (unsigned i = 0; i < conv2d_batch_vals.size(); ++i) { conv2d_batch_vals[i] = i * 0.011f + (i + 1) * 0.001f; } Expression x = input(cg, Dim({50, 50, 2}, 2), conv2d_batch_vals); Expression kernel = parameter(cg, param_kernel); vector<unsigned> stride = {4, 4}; bool is_valid = false; Expression y = conv2d(x, kernel, stride, is_valid); Expression kernel2 = parameter(cg, param_kernel2); Expression y2 = conv2d(y, kernel2, stride, is_valid); Expression z = sum_batches(to_scalar(y2)); BOOST_CHECK(check_grad(mod, z, 0)); } BOOST_AUTO_TEST_CASE( maxpooling2d_same_gradient ) { dynet::ComputationGraph cg; Parameter param_kernel = mod.add_parameters({2, 2, 1, 1}); std::vector<float> param_kernel_vals = {.011f, .022f, .012f, .022f}; TensorTools::set_elements(param_kernel.get_storage().values, param_kernel_vals); std::vector<float> maxpooling2d_batch_vals(1 * 11 * 11 * 2); for (unsigned i = 0; i < maxpooling2d_batch_vals.size(); ++i) { maxpooling2d_batch_vals[i] = i * 0.011f + (i + 1) * 0.001f; } Expression x = input(cg, Dim({11, 11, 1}, 2), maxpooling2d_batch_vals); Expression kernel = parameter(cg, param_kernel); std::vector<unsigned> ksize = {2, 2}; std::vector<unsigned> stride = {2, 5}; bool is_valid = false; Expression w = conv2d(x, kernel, stride, is_valid); //Expression z = sum_batches(to_scalar(w)); //BOOST_CHECK(check_grad(mod, z, 0)); is_valid = false; Expression y = maxpooling2d(w, ksize, stride, is_valid); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } BOOST_AUTO_TEST_CASE( maxpooling2d_valid_gradient ) { dynet::ComputationGraph cg; Parameter param_kernel = mod.add_parameters({2, 2, 1, 1}); std::vector<float> param_kernel_vals = {.011f, .022f, .012f, .022f}; TensorTools::set_elements(param_kernel.get_storage().values, param_kernel_vals); std::vector<float> maxpooling2d_batch_vals(1 * 21 * 21 * 2); for (unsigned i = 0; i < maxpooling2d_batch_vals.size(); ++i) { maxpooling2d_batch_vals[i] = i * 0.011f + (i + 1) * 0.001f; } Expression x = input(cg, Dim({21, 21, 1}, 2), maxpooling2d_batch_vals); Expression kernel = parameter(cg, param_kernel); std::vector<unsigned> ksize = {2, 2}; std::vector<unsigned> stride = {2, 5}; bool is_valid = false; Expression w = conv2d(x, kernel, stride, is_valid); is_valid = true; Expression y = maxpooling2d(w, ksize, stride, is_valid); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } BOOST_AUTO_TEST_CASE( maxpooling2d_same_gradient_two ) { dynet::ComputationGraph cg; Parameter param_kernel = mod.add_parameters({2, 2, 1, 1}); std::vector<float> param_kernel_vals = {.011f, .022f, .012f, .022f}; TensorTools::set_elements(param_kernel.get_storage().values, param_kernel_vals); std::vector<float> maxpooling2d_batch_vals(1 * 31 * 16 * 2); for (unsigned i = 0; i < maxpooling2d_batch_vals.size(); ++i) { maxpooling2d_batch_vals[i] = i * 0.011f + (i + 1) * 0.001f; } Expression x = input(cg, Dim({31, 16, 1}, 2), maxpooling2d_batch_vals); Expression kernel = parameter(cg, param_kernel); std::vector<unsigned> ksize = {3, 2}; std::vector<unsigned> stride = {3, 3}; bool is_valid = false; Expression w = conv2d(x, kernel, stride, is_valid); is_valid = true; Expression y = maxpooling2d(w, ksize, stride, is_valid); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } // TODO: These are all unimplemented // Expression kmh_ngram(const Expression& x, unsigned n); // Expression pick(const Expression& x, unsigned v); BOOST_AUTO_TEST_CASE( pick_gradient ) { unsigned idx = 1; dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression z = pick(x1, idx); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression pick(const Expression& x, unsigned* pv); BOOST_AUTO_TEST_CASE( pickptr_gradient ) { unsigned idx = 1; dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression z = pick(x1, &idx); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression pick(const Expression& x, unsigned v); BOOST_AUTO_TEST_CASE( pick_batch_gradient ) { std::vector<unsigned> idx = {1, 2}; dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = input(cg, Dim({3}, 2), batch_vals); Expression z = sum_batches(pick(x1 + x2, idx)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression pick(const Expression& x, unsigned v); BOOST_AUTO_TEST_CASE( pick_batch_broadcast_gradient ) { std::vector<unsigned> idx = {1, 2}; dynet::ComputationGraph cg; Expression x1 = parameter(cg, param_square1); Expression z = sum_batches(squared_norm(pick(x1, idx, 0))); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression pick_batch_elem(const Expression& x, unsigned v); BOOST_AUTO_TEST_CASE( pick_batch_elem_gradient ) { unsigned idx = 0; dynet::ComputationGraph cg; Expression x1 = input(cg, Dim({ 3 }, 2), batch_vals); Expression z = sum_rows(pick_batch_elem(x1, idx)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression pick_batch_elems(const Expression& x, cosnt std::vector<unsigned> & v); BOOST_AUTO_TEST_CASE( pick_batch_elems_gradient ) { dynet::ComputationGraph cg; std::vector<unsigned> indices = { 0, 1 }; Expression x1 = input(cg, Dim({ 3 }, 2), batch_vals); Expression picked_x1 = pick_batch_elems(x1, indices); Expression z = sum({ sum_rows(pick_batch_elem(picked_x1, (unsigned) 0)), sum_rows(pick_batch_elem(picked_x1, (unsigned) 1)) }); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression pick_range(const Expression& x, unsigned v, unsigned u); BOOST_AUTO_TEST_CASE( pick_range_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression y = pick_range(x1, 0, 2); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression pick_range(const Expression& x, unsigned v, unsigned u); BOOST_AUTO_TEST_CASE( pick_range_dim_gradient ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param_square1); Expression y = pick_range(x1, 0, 2, 1); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression select_rows(const Expression& x, vector<unsigned>& rows); BOOST_AUTO_TEST_CASE( select_rows_gradient ) { dynet::ComputationGraph cg; vector<unsigned> rows = {1}; Expression x1 = parameter(cg, param_square1); Expression y = select_rows(x1, rows); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression select_rows(const Expression& x, vector<unsigned>& rows); BOOST_AUTO_TEST_CASE( select_rows_multiple_gradient ) { dynet::ComputationGraph cg; vector<unsigned> rows = {0, 2}; Expression x1 = parameter(cg, param_square1); Expression y = select_rows(x1, rows) * x1; Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression select_rows(const Expression& x, vector<unsigned>& rows); BOOST_AUTO_TEST_CASE( select_rows_oob ) { dynet::ComputationGraph cg; vector<unsigned> rows = {3}; Expression x1 = parameter(cg, param_square1); Expression y = select_rows(x1, rows); BOOST_CHECK_THROW(y.value(), std::invalid_argument); } // Expression select_rows(const Expression& x, vector<unsigned>& rows); BOOST_AUTO_TEST_CASE( select_rows_autobatch_gradient ) { auto autobatch_cache = dynet::autobatch_flag; dynet::autobatch_flag = 1; dynet::ComputationGraph cg; Expression x1 = parameter(cg, param_square1); vector<Expression> vals; { vector<unsigned> rows = {0, 2}; Expression y = select_rows(x1, rows) * x1; vals.push_back(to_scalar(y)); } { vector<unsigned> rows = {2, 1}; Expression y = select_rows(x1, rows) * x1; vals.push_back(to_scalar(y)); } { vector<unsigned> rows = {0}; Expression y = select_rows(x1, rows) * x1; vals.push_back(to_scalar(y)); } Expression z = sum(vals); BOOST_CHECK(check_grad(mod, z, 0)); dynet::autobatch_flag = autobatch_cache; } // Expression select_cols(const Expression& x, vector<unsigned>& rows); BOOST_AUTO_TEST_CASE( select_cols_gradient ) { dynet::ComputationGraph cg; vector<unsigned> cols = {1}; Expression x1 = parameter(cg, param_square1); Expression y = select_cols(x1, cols); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression select_cols(const Expression& x, vector<unsigned>& cols); BOOST_AUTO_TEST_CASE( select_cols_multiple_gradient ) { dynet::ComputationGraph cg; vector<unsigned> cols = {0, 2}; Expression x1 = parameter(cg, param_square1); Expression y = x1 * select_cols(x1, cols); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression select_cols(const Expression& x, vector<unsigned>& rows); BOOST_AUTO_TEST_CASE( select_cols_oob ) { dynet::ComputationGraph cg; vector<unsigned> cols = {3}; Expression x1 = parameter(cg, param_square1); Expression y = select_cols(x1, cols); BOOST_CHECK_THROW(y.value(), std::invalid_argument); } // Expression pickneglogsoftmax(const Expression& x, unsigned v); BOOST_AUTO_TEST_CASE( pickneglogsoftmax_gradient ) { unsigned idx = 1; dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression z = pickneglogsoftmax(x1, idx); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression pickneglogsoftmax(const Expression& x, unsigned v); BOOST_AUTO_TEST_CASE( pickneglogsoftmax_batch_gradient ) { std::vector<unsigned> idx = {1, 2}; dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = input(cg, Dim({3}, 2), batch_vals); Expression z = sum_batches(pickneglogsoftmax(x1 + x2, idx)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression strided_select(const Expression& x, vector<unsigned>& indices); BOOST_AUTO_TEST_CASE( strided_select_gradient_noop ) { dynet::ComputationGraph cg; const vector<int> strides = {}; Expression x1 = parameter(cg, param_square1); Expression y = strided_select(x1, strides); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); BOOST_CHECK(x1.dim().size() == y.dim().size()); } // Expression strided_select(const Expression& x, vector<unsigned>& indices); BOOST_AUTO_TEST_CASE( strided_select_gradient ) { dynet::ComputationGraph cg; for(int stride=1;stride<4;stride++){ const vector<int> strides = {stride,stride,stride}; Expression x1 = parameter(cg, param_cube1); Expression y3 = strided_select(x1, strides); Expression z = to_scalar(y3); BOOST_CHECK(check_grad(mod, z, 0)); } } // Expression strided_select(const Expression& x, vector<unsigned>& indices); BOOST_AUTO_TEST_CASE( strided_select_gradient2 ) { dynet::ComputationGraph cg; for(int from=0;from<2;from++){ for(int to=from+1;to<4;to++){ for(int stride=1;stride<4;stride++){ const vector<int> strides = {stride,stride,stride}; const vector<int> to_range = {to,to,to}; const vector<int> from_range = {from,from,from}; Expression x1 = parameter(cg, param_cube1); Expression y = strided_select(x1, strides, from_range, to_range); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } } } } // Expression strided_select(const Expression& x, vector<unsigned>& indices); BOOST_AUTO_TEST_CASE( strided_select_gradient3 ) { dynet::ComputationGraph cg; for(int from=0;from<2;from++){ for(int stride=1;stride<4;stride++){ const vector<int> strides = {stride,stride,stride}; const vector<int> from_range = {from,from,from}; Expression x1 = parameter(cg, param_cube1); Expression y2 = strided_select(x1, strides, from_range); Expression z = to_scalar(y2); BOOST_CHECK(check_grad(mod, z, 0)); } } } // Expression strided_select(const Expression& x, vector<unsigned>& indices); BOOST_AUTO_TEST_CASE( strided_select_gradient4 ) { dynet::ComputationGraph cg; for(int from=0;from<2;from++){ for(int to=from+1;to<4;to++){ for(int stride=1;stride<4;stride++){ const vector<int> strides = {stride,1,stride,stride}; const vector<int> from_range = {from,0,from,from}; const vector<int> to_range = {to,1,to,to}; Expression x1 = reshape(parameter(cg, param_cube1), Dim({3,1,3},3)); Expression y = strided_select(x1, strides, from_range, to_range); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } } } } // Expression strided_select(const Expression& x, vector<unsigned>& indices); BOOST_AUTO_TEST_CASE( strided_select_gradient5 ) { dynet::ComputationGraph cg; for(int from=0;from<2;from++){ for(int to=from+1;to<4;to++){ for(int stride=1;stride<4;stride++){ const vector<int> strides = {stride,stride}; const vector<int> from_range = {from,from}; const vector<int> to_range = {to,to}; Expression x1 = reshape(parameter(cg, param_cube1), Dim({3,3,3,1},1)); Expression y = strided_select(x1, strides, from_range, to_range); Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } } } } // Expression sum_elems(x); BOOST_AUTO_TEST_CASE( sum_elems_gradient ) { dynet::ComputationGraph cg; Expression x = parameter(cg, param4); Expression z = sum_elems(x); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression mean_elems(x); BOOST_AUTO_TEST_CASE( mean_elems_gradient ) { dynet::ComputationGraph cg; Expression x = parameter(cg, param4); Expression z = mean_elems(x); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression moment_elems(x, r); BOOST_AUTO_TEST_CASE( moment_elems_gradient ) { for (unsigned r = 2; r < 5; r++) { dynet::ComputationGraph cg; Expression x = parameter(cg, param4); Expression z = moment_elems(x, r); BOOST_CHECK(check_grad(mod, z, 0)); } } // Expression std_elems(x); BOOST_AUTO_TEST_CASE( std_elems_gradient ) { dynet::ComputationGraph cg; Expression x = parameter(cg, param4); Expression z = std_elems(x); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression sum_batches(x); BOOST_AUTO_TEST_CASE( sum_batches_gradient ) { dynet::ComputationGraph cg; Expression x = parameter(cg, param4); Expression y = reshape(x, Dim({1}, 6)); Expression z = sum_batches(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression mean_batches(x); BOOST_AUTO_TEST_CASE( mean_batches_gradient ) { dynet::ComputationGraph cg; Expression x = parameter(cg, param4); Expression y = reshape(x, Dim({1}, 6)); Expression z = mean_batches(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression mean_batches(x); BOOST_AUTO_TEST_CASE( mean_batches_gradient_multidim ) { dynet::ComputationGraph cg; Expression x = parameter(cg, param4); Expression y = reshape(x, Dim({1, 2}, 3)); Expression z = mean_batches(y); z = mean_dim(z, {1}); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression moment_batches(x, r); BOOST_AUTO_TEST_CASE( moment_batches_gradient ) { for (unsigned r = 2; r < 5; r++) { dynet::ComputationGraph cg; Expression x = parameter(cg, param4); Expression y = reshape(x, Dim({1}, 6)); Expression z = moment_batches(y, r); BOOST_CHECK(check_grad(mod, z, 0)); } } // Expression sum_dim(x, r); BOOST_AUTO_TEST_CASE( sum_dim_gradient ) { dynet::ComputationGraph cg; Expression x = parameter(cg, param_cube1); Expression z = x; for (unsigned d = 3; d > 0; d--) z = sum_dim(z, vector<unsigned>({d - 1}), false); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression std_batches(x); BOOST_AUTO_TEST_CASE( std_batches_gradient ) { dynet::ComputationGraph cg; Expression x = parameter(cg, param4); Expression y = reshape(x, Dim({1}, 6)); Expression z = std_batches(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression mean_dim(x); BOOST_AUTO_TEST_CASE( mean_dim_gradient ) { dynet::ComputationGraph cg; Expression x = parameter(cg, param_cube1); Expression z = x; for (unsigned d = 3; d > 0; d--) z = mean_dim(z, {d - 1}); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression moment_dim(x, r); BOOST_AUTO_TEST_CASE( moment_dim_gradient ) { for (unsigned r = 2; r < 5; r++) { dynet::ComputationGraph cg; Expression x = parameter(cg, param_cube1); Expression z = x; for (unsigned d = 3; d > 0; d--) z = moment_dim(z, vector<unsigned>({d - 1}), r, false); BOOST_CHECK(check_grad(mod, z, 0)); } } // Expression moment_dim(x, r); BOOST_AUTO_TEST_CASE( moment_dim_gradient2 ) { for (unsigned r = 2; r < 5; r++){ dynet::ComputationGraph cg; Expression z = dynet::reshape(parameter(cg, param_cube2), Dim({3,3,3}, 2)) / 10; for (unsigned d = 3; d > 0; d--) z = moment_dim(z, vector<unsigned>({d - 1}), r, false); z = moment_dim(z, vector<unsigned>({}), r, true); BOOST_CHECK(check_grad(mod, z, 0)); } } // Expression moment_dim(x, r); BOOST_AUTO_TEST_CASE( moment_dim_gradient3 ) { for (unsigned r=1;r<5;r++){ dynet::ComputationGraph cg; Expression x = dynet::reshape(parameter(cg, param_cube2), Dim({27}, 2))/10; Expression y = moment_dim(x, vector<unsigned>({0}), r, true); Expression z = moment_dim(x, vector<unsigned>({0}), r, false); z = moment_dim(z, vector<unsigned>({}), r, true); BOOST_CHECK(check_grad(mod, y, 0)); BOOST_CHECK(check_grad(mod, z, 0)); if(r==1) BOOST_CHECK_CLOSE(as_scalar(y.value()), as_scalar(z.value()), 0.001); } } // Expression moment_dim(x, r); BOOST_AUTO_TEST_CASE( moment_dim_gradient4 ) { for (unsigned r=1;r<5;r++){ dynet::ComputationGraph cg; Expression x = dynet::reshape(parameter(cg, param_cube2), Dim({3,9}, 2)) / 10; Expression y = moment_dim(x, vector<unsigned>({0,1}), r, true); Expression z = moment_dim(x, vector<unsigned>({0,1}), r, false); z = moment_dim(z, vector<unsigned>({}), r, true); BOOST_CHECK(check_grad(mod, y, 0)); BOOST_CHECK(check_grad(mod, z, 0)); if(r==1) BOOST_CHECK_CLOSE(as_scalar(y.value()), as_scalar(z.value()), 0.001); } } // Expression std_dim(x); BOOST_AUTO_TEST_CASE( std_dim_gradient3 ) { dynet::ComputationGraph cg; Expression x = dynet::reshape(parameter(cg, param_cube2), Dim({27}, 2))/10; Expression y = std_dim(x, vector<unsigned>({0}), true); Expression z = std_dim(x, vector<unsigned>({0}), false); z = std_dim(z, vector<unsigned>({}), true); BOOST_CHECK(check_grad(mod, y, 0)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression std_dim(x); BOOST_AUTO_TEST_CASE( std_dim_gradient4 ) { dynet::ComputationGraph cg; Expression x = dynet::reshape(parameter(cg, param_cube2), Dim({3,9}, 2))/10; Expression y = std_dim(x, vector<unsigned>({0,1}), true); Expression z = std_dim(x, vector<unsigned>({0,1}), false); z = std_dim(z, vector<unsigned>({}), true); BOOST_CHECK(check_grad(mod, y, 0)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression std_dim(x); BOOST_AUTO_TEST_CASE( std_dim_value ) { dynet::ComputationGraph cg; Expression x = dynet::reshape(parameter(cg, param_cube1), Dim({3,3}, 3)); Expression y = std_dim(x, vector<unsigned>({0}), true); Expression z = mean_dim(y, vector<unsigned>({0}), false); BOOST_CHECK_CLOSE(as_scalar(z.value()), 0.128319368, 0.1); } // Expression mean_dim(x); BOOST_AUTO_TEST_CASE( std_dim_gradient ) { dynet::ComputationGraph cg; Expression x = parameter(cg, param_cube1); Expression z = x; for (unsigned d = 3; d > 0; d--) z = std_dim(z, {d - 1}); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression layer_norm(x,g,b); BOOST_AUTO_TEST_CASE( layer_norm_backward_gradient ) { dynet::ComputationGraph cg; Expression x = parameter(cg, param1); Expression g = parameter(cg, param2); Expression b = parameter(cg, param3); Expression y = layer_norm(x, g, b); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression layer_norm(x,g,b); BOOST_AUTO_TEST_CASE( layer_norm_forward ) { dynet::ComputationGraph cg; Expression x = parameter(cg, param1); Expression g = input(cg, Dim({3}), ones3_vals); Expression b = zeroes(cg, Dim({3})); Expression y = layer_norm(x, g, b); float mu = abs(as_scalar((sum_elems(y) / 3.0).value())); float std = as_scalar(sqrt(sum_elems(square(y)) / 3.0).value()); BOOST_CHECK_LT(mu, 1e-6); BOOST_CHECK_CLOSE(std, 1, 0.01); } // Expression weight_norm(x,g); BOOST_AUTO_TEST_CASE( weight_norm_forward ) { dynet::ComputationGraph cg; Expression w = parameter(cg, param_square1); Expression g = parameter(cg, param_scalar1); Expression y = weight_norm(w, g); float norm = as_scalar(sqrt(sum_elems(square(y))).value()); BOOST_CHECK_CLOSE(norm, 2.2, 0.01); } // Expression layer_norm(x,g); BOOST_AUTO_TEST_CASE( weight_norm_backward_gradient ) { dynet::ComputationGraph cg; Expression w = parameter(cg, param_square1); Expression g = parameter(cg, param_scalar1); Expression y = weight_norm(w, g); Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression sparse_input(vector<unsigned int>& ids, vector<float>& src, float def); BOOST_AUTO_TEST_CASE( sparse_input_test ) { dynet::ComputationGraph cg; std::vector<unsigned int> ids = {0, 4}; Expression z = input(cg, Dim({3}, 2), ids, ones2_vals, 0.5); std::vector<float> exp = {1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.5f}; std::vector<float> act = as_vector(cg.forward(z)); assert(exp.size() == act.size()); for (size_t i = 0; i < exp.size(); ++i) BOOST_CHECK_CLOSE(exp[i], act[i], 0.001); } // Expression one_hot(ComputationGraph& g, unsigned int d, unsigned int idx, Device *device = dynet::default_device); BOOST_AUTO_TEST_CASE( one_hot_test ) { dynet::ComputationGraph cg; unsigned int idx = 5; unsigned int d = 10; Expression z = one_hot(cg, d, idx); std::vector<float> values = as_vector(cg.forward(z)); BOOST_CHECK_EQUAL(d, values.size()); for (size_t i = 0; i < d; ++i) BOOST_CHECK_EQUAL(values[i], i == idx ? 1.0 : 0.0); } // Expression one_hot(ComputationGraph& g, unsigned int d, unsigned int batch_size, const std::vector<unsigned int>& ids, Device *device = dynet::default_device); BOOST_AUTO_TEST_CASE( batched_one_hot_test ) { dynet::ComputationGraph cg; vector<unsigned int> idxs = {1, 6}; unsigned int d = 10; unsigned int batch_size = idxs.size(); Expression z = one_hot(cg, d, idxs); std::vector<float> values = as_vector(cg.forward(z)); BOOST_CHECK_EQUAL(d * batch_size, values.size()); for (size_t b = 0; b < batch_size; ++b) for (size_t i = 0; i < d; ++i) BOOST_CHECK_EQUAL(values[b * d + i], (b * d + i == 1 || b * d + i == 16 ? 1.0 : 0.0)); } // Expression lookup(); BOOST_AUTO_TEST_CASE( lookup_test ) { dynet::ComputationGraph cg; Expression x1 = lookup(cg, lookup1, (unsigned)0); Expression x2 = lookup(cg, lookup1, (unsigned)2); Expression y = x1 + x2; Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression lookup(); BOOST_AUTO_TEST_CASE( lookup_highdim_batched_test ) { dynet::ComputationGraph cg; Expression x = lookup(cg, lookup4, {0, 2}); Expression z = sum_batches(to_scalar(x)); BOOST_CHECK(check_grad(mod, z, 0)); } // Expression lookup(); BOOST_AUTO_TEST_CASE( lookup_autobatch_dim_test ) { auto autobatch_cache = dynet::autobatch_flag; dynet::autobatch_flag = 1; dynet::ComputationGraph cg; Expression x1 = lookup(cg, lookup1, (unsigned)0); Expression x2 = lookup(cg, lookup2, (unsigned)5); Expression y = x1 + x2; Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); dynet::autobatch_flag = autobatch_cache; } // Expression lookup(); BOOST_AUTO_TEST_CASE( lookup_autobatch_diffmodel_test ) { auto autobatch_cache = dynet::autobatch_flag; dynet::autobatch_flag = 1; dynet::ComputationGraph cg; Expression x1 = lookup(cg, lookup1, (unsigned)0); Expression x2 = lookup(cg, lookup3, (unsigned)5); Expression y = x1 + x2; Expression z = to_scalar(y); BOOST_CHECK(check_grad(mod, z, 0)); dynet::autobatch_flag = autobatch_cache; } // Expression lookup(); BOOST_AUTO_TEST_CASE( lookup_autobatch_and_manbatch_test ) { auto autobatch_cache = dynet::autobatch_flag; for (dynet::autobatch_flag = 0; dynet::autobatch_flag < 2; ++dynet::autobatch_flag) { dynet::ComputationGraph cg; Expression x1 = lookup(cg, lookup1, {0, 1}); Expression x2 = lookup(cg, lookup1, {2, 0}); Expression y = x1 + x2; Expression z = sum_batches(to_scalar(y)); BOOST_CHECK(check_grad(mod, z, 0)); } dynet::autobatch_flag = autobatch_cache; } // Expression parameter() with lookup parameter input; BOOST_AUTO_TEST_CASE( lookup_matrix_test ) { dynet::ComputationGraph cg; Expression x = parameter(cg, lookup1); Expression z = to_scalar(x); BOOST_CHECK(check_grad(mod, z, 0)); } BOOST_AUTO_TEST_CASE( backward_test ) { dynet::ComputationGraph cg; Expression x1 = lookup(cg, lookup1, (unsigned)0); Expression x2 = lookup(cg, lookup1, (unsigned)2); Expression y = x1 + x2; Expression z = to_scalar(y); cg.backward(z); } BOOST_AUTO_TEST_CASE( gradient_value_test ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression l = dot_product(x1, x2); cg.backward(l); vector<float> x1_g1 = as_vector(x1.gradient()); vector<float> x1_g2 = as_vector(param1.get_storage().g); for (unsigned i = 0; i < 3; i++) { BOOST_CHECK_CLOSE(x1_g1[i], x1_g2[i], 0.001); } } BOOST_AUTO_TEST_CASE( gradient_sanity_test ) { dynet::ComputationGraph cg; Expression x1 = parameter(cg, param1); Expression x2 = parameter(cg, param2); Expression l = dot_product(x1, x2); cg.forward(l); BOOST_CHECK_THROW(x1.gradient() , std::runtime_error); } // This just makes sure that nothing crashes BOOST_AUTO_TEST_CASE( random_gumbel_test ) { dynet::ComputationGraph cg; Expression x1 = random_gumbel(cg, {20}); x1.value(); } BOOST_AUTO_TEST_CASE( sanity_test ) { Expression x; { dynet::ComputationGraph cg; x = input(cg, {3}, ones3_vals); } BOOST_CHECK_THROW(x.value() , std::runtime_error); } BOOST_AUTO_TEST_SUITE_END()
clab/cnn
tests/test-nodes.cc
C++
apache-2.0
93,122
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package clusterservicebroker import ( "testing" sc "github.com/kubernetes-incubator/service-catalog/pkg/apis/servicecatalog" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func clusterServiceBrokerWithOldSpec() *sc.ClusterServiceBroker { return &sc.ClusterServiceBroker{ ObjectMeta: metav1.ObjectMeta{ Generation: 1, }, Spec: sc.ClusterServiceBrokerSpec{ CommonServiceBrokerSpec: sc.CommonServiceBrokerSpec{ URL: "https://kubernetes.default.svc:443/brokers/template.k8s.io", }, }, Status: sc.ClusterServiceBrokerStatus{ CommonServiceBrokerStatus: sc.CommonServiceBrokerStatus{ Conditions: []sc.ServiceBrokerCondition{ { Type: sc.ServiceBrokerConditionReady, Status: sc.ConditionFalse, }, }, }, }, } } func clusterServiceBrokerWithNewSpec() *sc.ClusterServiceBroker { b := clusterServiceBrokerWithOldSpec() b.Spec.URL = "new" return b } // TestClusterServiceBrokerStrategyTrivial is the testing of the trivial hardcoded // boolean flags. func TestClusterServiceBrokerStrategyTrivial(t *testing.T) { if clusterServiceBrokerRESTStrategies.NamespaceScoped() { t.Errorf("clusterservicebroker must not be namespace scoped") } if clusterServiceBrokerRESTStrategies.AllowCreateOnUpdate() { t.Errorf("clusterservicebroker should not allow create on update") } if clusterServiceBrokerRESTStrategies.AllowUnconditionalUpdate() { t.Errorf("clusterservicebroker should not allow unconditional update") } } // TestClusterServiceBrokerCreate func TestClusterServiceBroker(t *testing.T) { // Create a clusterservicebroker or clusterservicebrokers broker := &sc.ClusterServiceBroker{ Spec: sc.ClusterServiceBrokerSpec{ CommonServiceBrokerSpec: sc.CommonServiceBrokerSpec{ URL: "abcd", }, }, Status: sc.ClusterServiceBrokerStatus{ CommonServiceBrokerStatus: sc.CommonServiceBrokerStatus{ Conditions: nil, }, }, } // Canonicalize the broker clusterServiceBrokerRESTStrategies.PrepareForCreate(nil, broker) if broker.Status.Conditions == nil { t.Fatalf("Fresh clusterservicebroker should have empty status") } if len(broker.Status.Conditions) != 0 { t.Fatalf("Fresh clusterservicebroker should have empty status") } } // TestClusterServiceBrokerUpdate tests that generation is incremented // correctly when the spec of a ClusterServiceBroker is updated. func TestClusterServiceBrokerUpdate(t *testing.T) { cases := []struct { name string older *sc.ClusterServiceBroker newer *sc.ClusterServiceBroker shouldGenerationIncrement bool }{ { name: "no spec change", older: clusterServiceBrokerWithOldSpec(), newer: clusterServiceBrokerWithOldSpec(), shouldGenerationIncrement: false, }, { name: "spec change", older: clusterServiceBrokerWithOldSpec(), newer: clusterServiceBrokerWithNewSpec(), shouldGenerationIncrement: true, }, } for i := range cases { clusterServiceBrokerRESTStrategies.PrepareForUpdate(nil, cases[i].newer, cases[i].older) if cases[i].shouldGenerationIncrement { if e, a := cases[i].older.Generation+1, cases[i].newer.Generation; e != a { t.Fatalf("%v: expected %v, got %v for generation", cases[i].name, e, a) } } else { if e, a := cases[i].older.Generation, cases[i].newer.Generation; e != a { t.Fatalf("%v: expected %v, got %v for generation", cases[i].name, e, a) } } } } // TestClusterServiceBrokerUpdateForRelistRequests tests that the RelistRequests field is // ignored during updates when it is the default value. func TestClusterServiceBrokerUpdateForRelistRequests(t *testing.T) { cases := []struct { name string oldValue int64 newValue int64 expectedValue int64 }{ { name: "both default", oldValue: 0, newValue: 0, expectedValue: 0, }, { name: "old default", oldValue: 0, newValue: 1, expectedValue: 1, }, { name: "new default", oldValue: 1, newValue: 0, expectedValue: 1, }, { name: "neither default", oldValue: 1, newValue: 2, expectedValue: 2, }, } for _, tc := range cases { oldBroker := clusterServiceBrokerWithOldSpec() oldBroker.Spec.RelistRequests = tc.oldValue newClusterServiceBroker := clusterServiceBrokerWithOldSpec() newClusterServiceBroker.Spec.RelistRequests = tc.newValue clusterServiceBrokerRESTStrategies.PrepareForUpdate(nil, newClusterServiceBroker, oldBroker) if e, a := tc.expectedValue, newClusterServiceBroker.Spec.RelistRequests; e != a { t.Errorf("%s: got unexpected RelistRequests: expected %v, got %v", tc.name, e, a) } } }
staebler/service-catalog
pkg/registry/servicecatalog/clusterservicebroker/strategy_test.go
GO
apache-2.0
5,295
class Upx < Formula desc "Compress/expand executable files" homepage "https://upx.github.io/" url "https://github.com/upx/upx/releases/download/v3.96/upx-3.96-src.tar.xz" sha256 "47774df5c958f2868ef550fb258b97c73272cb1f44fe776b798e393465993714" revision 1 head "https://github.com/upx/upx.git", branch: "devel" bottle do sha256 cellar: :any_skip_relocation, big_sur: "5fc54db6b0fb2e8ebfa630d48c893e569e49b5c6795646d8912c447f3b0a1747" sha256 cellar: :any_skip_relocation, catalina: "c04d7040eeaa8d2842449b86789ece0f0a73ee0ac1c013c6a00596288251abbc" sha256 cellar: :any_skip_relocation, mojave: "a2253a74b3531dc9173eac2ae2ea816ff7b8af3657aee2180ca1253f49cd9fec" end depends_on "ucl" => :build uses_from_macos "zlib" patch do # Big Sur fix: https://github.com/upx/upx/issues/424 url "https://github.com/upx/upx/commit/51f69a20e0287904398bbf4c72ba2f809a0b0850.patch?full_index=1" sha256 "2f311ce1e7254085817d3415a687d561f761fb3a2077f0605fc3f39e620485f0" end def install system "make", "all" bin.install "src/upx.out" => "upx" man1.install "doc/upx.1" end test do cp "#{bin}/upx", "." chmod 0755, "./upx" system "#{bin}/upx", "-1", "./upx" system "./upx", "-V" # make sure the binary we compressed works system "#{bin}/upx", "-d", "./upx" end end
spaam/homebrew-core
Formula/upx.rb
Ruby
bsd-2-clause
1,340
/* * Copyright (c) 2009 SpringSource, Inc. * Copyright (c) 2009 VMware, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define UNICODE #define _UNICODE #define _WIN32_DCOM #include <windows.h> #include <objbase.h> #include <comdef.h> #include <wbemidl.h> #include "sigar.h" #pragma comment(lib, "wbemuuid.lib") #ifndef SIGAR_CMDLINE_MAX #define SIGAR_CMDLINE_MAX 4096 #endif class WMI { public: WMI(); ~WMI(); HRESULT Open(LPCTSTR machine=NULL, LPCTSTR user=NULL, LPCTSTR pass=NULL); void Close(); HRESULT GetProcStringProperty(DWORD pid, TCHAR *name, TCHAR *value, DWORD len); HRESULT GetProcExecutablePath(DWORD pid, TCHAR *value); HRESULT GetProcCommandLine(DWORD pid, TCHAR *value); int GetLastError(); private: IWbemServices *wbem; HRESULT result; BSTR GetProcQuery(DWORD pid); }; WMI::WMI() { wbem = NULL; result = S_OK; CoInitializeEx(NULL, COINIT_MULTITHREADED); } WMI::~WMI() { Close(); CoUninitialize(); } /* XXX must be a better way to map HRESULT */ int WMI::GetLastError() { switch (result) { case S_OK: return ERROR_SUCCESS; case WBEM_E_NOT_FOUND: return ERROR_NOT_FOUND; case WBEM_E_ACCESS_DENIED: return ERROR_ACCESS_DENIED; case WBEM_E_NOT_SUPPORTED: return SIGAR_ENOTIMPL; default: return ERROR_INVALID_FUNCTION; } } HRESULT WMI::Open(LPCTSTR machine, LPCTSTR user, LPCTSTR pass) { IWbemLocator *locator; wchar_t path[MAX_PATH]; if (wbem) { result = S_OK; return result; } result = CoInitializeSecurity(NULL, //Security Descriptor -1, //COM authentication NULL, //Authentication services NULL, //Reserved RPC_C_AUTHN_LEVEL_DEFAULT, //Default authentication RPC_C_IMP_LEVEL_IMPERSONATE, //Default Impersonation NULL, //Authentication info EOAC_NONE, //Additional capabilities NULL); //Reserved result = CoCreateInstance(CLSID_WbemLocator, NULL, /* IUnknown */ CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *)&locator); if (FAILED(result)) { return result; } if (machine == NULL) { machine = L"."; } wsprintf(path, L"\\\\%S\\ROOT\\CIMV2", machine); result = locator->ConnectServer(bstr_t(path), //Object path of WMI namespace bstr_t(user), //User name. NULL = current user bstr_t(pass), //User password. NULL = current NULL, //Locale. NULL indicates current 0, //Security flags NULL, //Authority (e.g. Kerberos) NULL, //Context object &wbem); //pointer to IWbemServices proxy locator->Release(); return result; } void WMI::Close() { if (wbem) { wbem->Release(); wbem = NULL; result = S_OK; } } BSTR WMI::GetProcQuery(DWORD pid) { wchar_t query[56]; wsprintf(query, L"Win32_Process.Handle=%d", pid); return bstr_t(query); } HRESULT WMI::GetProcStringProperty(DWORD pid, TCHAR *name, TCHAR *value, DWORD len) { IWbemClassObject *obj; VARIANT var; result = wbem->GetObject(GetProcQuery(pid), 0, 0, &obj, 0); if (FAILED(result)) { return result; } result = obj->Get(name, 0, &var, 0, 0); if (SUCCEEDED(result)) { if (var.vt == VT_NULL) { result = E_INVALIDARG; } else { lstrcpyn(value, var.bstrVal, len); } VariantClear(&var); } obj->Release(); return result; } HRESULT WMI::GetProcExecutablePath(DWORD pid, TCHAR *value) { return GetProcStringProperty(pid, L"ExecutablePath", value, MAX_PATH); } HRESULT WMI::GetProcCommandLine(DWORD pid, TCHAR *value) { return GetProcStringProperty(pid, L"CommandLine", value, SIGAR_CMDLINE_MAX); } /* in peb.c */ extern "C" int sigar_parse_proc_args(sigar_t *sigar, WCHAR *buf, sigar_proc_args_t *procargs); extern "C" int sigar_proc_args_wmi_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_args_t *procargs) { int status; TCHAR buf[SIGAR_CMDLINE_MAX]; WMI *wmi = new WMI(); if (FAILED(wmi->Open())) { return wmi->GetLastError(); } if (FAILED(wmi->GetProcCommandLine((DWORD)pid, buf))) { status = wmi->GetLastError(); } else { status = sigar_parse_proc_args(sigar, buf, procargs); } wmi->Close(); delete wmi; return status; } extern "C" int sigar_proc_exe_wmi_get(sigar_t *sigar, sigar_pid_t pid, sigar_proc_exe_t *procexe) { int status; TCHAR buf[MAX_PATH+1]; WMI *wmi = new WMI(); if (FAILED(wmi->Open())) { return wmi->GetLastError(); } procexe->name[0] = '\0'; if (FAILED(wmi->GetProcExecutablePath((DWORD)pid, buf))) { status = wmi->GetLastError(); } else { status = SIGAR_OK; /* SIGAR_W2A(buf, procexe->name, sizeof(procexe->name)); */ WideCharToMultiByte(CP_ACP, 0, buf, -1, (LPSTR)procexe->name, sizeof(procexe->name), NULL, NULL); } wmi->Close(); delete wmi; return status; }
sarbi127/inviwo
ext/sigar/src/os/win32/wmi.cpp
C++
bsd-2-clause
6,445
cask 'station' do version '1.0.6' sha256 '6100b48431b40fd63a9b390954cf85d8f7f83d0f96033086a43d0d8f53fe4702' # github.com/getstation/desktop-app-releases was verified as official when first introduced to the cask url "https://github.com/getstation/desktop-app-releases/releases/download/#{version}/Station-#{version}-mac.zip" appcast 'https://github.com/getstation/desktop-app-releases/releases.atom', checkpoint: 'd36cc1d20afff418d43b50fa8725dbf90b01cd126582e0eb0eae787e9aa4e271' name 'Station' homepage 'https://getstation.com/' auto_updates true app 'Station.app' uninstall quit: [ 'org.efounders.BrowserX', 'org.efounders.BrowserX.helper', ] zap trash: '~/Library/Application Support/Station/' end
opsdev-ws/homebrew-cask
Casks/station.rb
Ruby
bsd-2-clause
796
class Websocketd < Formula desc "WebSockets the Unix way" homepage "http://websocketd.com" url "https://github.com/joewalnes/websocketd/archive/v0.3.1.tar.gz" sha256 "323700908ca7fe7b69cb2cc492b4746c4cd3449e49fbab15a4b3a5eccf8757f4" license "BSD-2-Clause" bottle do cellar :any_skip_relocation sha256 "614c1bb4d3fdd65e452d7af66d5cac5e397ff452d2b023dbd1261e632ec346e9" => :catalina sha256 "a0ad536184c0f12c3c65710be453e810eda0ffa3b0109a56f69b364c05439703" => :mojave sha256 "a2b5e17e00e1c74b52cf0d44ba802bc6e0eb450e950530cedd7cef38e83437ca" => :high_sierra sha256 "5200608539895835b8faa52b886fe9181c23e94c560c4ef9f2f6afe842de3626" => :sierra end depends_on "go" => :build def install ENV["GOPATH"] = buildpath src = buildpath/"src/github.com/joewalnes/websocketd" src.install buildpath.children src.cd do system "go", "build", "-ldflags", "-X main.version=#{version}", "-o", bin/"websocketd" man1.install "release/websocketd.man" => "websocketd.1" prefix.install_metafiles end end test do port = free_port pid = Process.fork { exec "#{bin}/websocketd", "--port=#{port}", "echo", "ok" } sleep 2 begin assert_equal("404 page not found\n", shell_output("curl -s http://localhost:#{port}")) ensure Process.kill 9, pid Process.wait pid end end end
lembacon/homebrew-core
Formula/websocketd.rb
Ruby
bsd-2-clause
1,372
// This file was procedurally generated from the following sources: // - src/dstr-binding/obj-ptrn-prop-id-get-value-err.case // - src/dstr-binding/error/async-gen-func-named-expr-dflt.template /*--- description: Error thrown when accessing the corresponding property of the value object (async generator named function expression (default parameter)) esid: sec-asyncgenerator-definitions-evaluation features: [async-iteration] flags: [generated] info: | AsyncGeneratorExpression : async [no LineTerminator here] function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } [...] 7. Let closure be ! AsyncGeneratorFunctionCreate(Normal, FormalParameters, AsyncGeneratorBody, funcEnv, strict). [...] 13.3.3.7 Runtime Semantics: KeyedBindingInitialization BindingElement : BindingPattern Initializeropt 1. Let v be GetV(value, propertyName). 2. ReturnIfAbrupt(v). ---*/ var initEvalCount = 0; var poisonedProperty = Object.defineProperty({}, 'poisoned', { get: function() { throw new Test262Error(); } }); var f; f = async function* h({ poisoned: x = ++initEvalCount } = poisonedProperty) { }; assert.throws(Test262Error, function() { f(); }); assert.sameValue(initEvalCount, 0);
sebastienros/jint
Jint.Tests.Test262/test/language/expressions/async-generator/dstr-named-dflt-obj-ptrn-prop-id-get-value-err.js
JavaScript
bsd-2-clause
1,274
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2012, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ajax.org B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ***** END LICENSE BLOCK ***** */ define(function(require, exports, module) { "use strict"; var snippetManager = require("../snippets").snippetManager; var Autocomplete = require("../autocomplete").Autocomplete; var config = require("../config"); var util = require("../autocomplete/util"); var textCompleter = require("../autocomplete/text_completer"); var keyWordCompleter = { getCompletions: function(editor, session, pos, prefix, callback) { var state = editor.session.getState(pos.row); var completions = session.$mode.getCompletions(state, session, pos, prefix); callback(null, completions); } }; var snippetCompleter = { getCompletions: function(editor, session, pos, prefix, callback) { var snippetMap = snippetManager.snippetMap; var completions = []; snippetManager.getActiveScopes(editor).forEach(function(scope) { var snippets = snippetMap[scope] || []; for (var i = snippets.length; i--;) { var s = snippets[i]; var caption = s.name || s.tabTrigger; if (!caption) continue; completions.push({ caption: caption, snippet: s.content, meta: s.tabTrigger && !s.name ? s.tabTrigger + "\u21E5 " : "snippet" }); } }, this); callback(null, completions); } }; var completers = [snippetCompleter, textCompleter, keyWordCompleter]; exports.addCompleter = function(completer) { completers.push(completer); }; // Exports existing completer so that user can construct his own set of completers. exports.textCompleter = textCompleter; exports.keyWordCompleter = keyWordCompleter; exports.snippetCompleter = snippetCompleter; var expandSnippet = { name: "expandSnippet", exec: function(editor) { var success = snippetManager.expandWithTab(editor); if (!success) editor.execCommand("indent"); }, bindKey: "Tab" }; var onChangeMode = function(e, editor) { loadSnippetsForMode(editor.session.$mode); }; var loadSnippetsForMode = function(mode) { var id = mode.$id; if (!snippetManager.files) snippetManager.files = {}; loadSnippetFile(id); if (mode.modes) mode.modes.forEach(loadSnippetsForMode); }; var loadSnippetFile = function(id) { if (!id || snippetManager.files[id]) return; var snippetFilePath = id.replace("mode", "snippets"); snippetManager.files[id] = {}; config.loadModule(snippetFilePath, function(m) { if (m) { snippetManager.files[id] = m; if (!m.snippets && m.snippetText) m.snippets = snippetManager.parseSnippetFile(m.snippetText); snippetManager.register(m.snippets || [], m.scope); if (m.includeScopes) { snippetManager.snippetMap[m.scope].includeScopes = m.includeScopes; m.includeScopes.forEach(function(x) { loadSnippetFile("ace/mode/" + x); }); } } }); }; function getCompletionPrefix(editor) { var pos = editor.getCursorPosition(); var line = editor.session.getLine(pos.row); var prefix = util.retrievePrecedingIdentifier(line, pos.column); // Try to find custom prefixes on the completers editor.completers.forEach(function(completer) { if (completer.identifierRegexps) { completer.identifierRegexps.forEach(function(identifierRegex) { if (!prefix && identifierRegex) prefix = util.retrievePrecedingIdentifier(line, pos.column, identifierRegex); }); } }); return prefix; } var doLiveAutocomplete = function(e) { var editor = e.editor; var text = e.args || ""; var hasCompleter = editor.completer && editor.completer.activated; // We don't want to autocomplete with no prefix if (e.command.name === "backspace") { if (hasCompleter && !getCompletionPrefix(editor)) editor.completer.detach(); } else if (e.command.name === "insertstring") { var prefix = getCompletionPrefix(editor); // Only autocomplete if there's a prefix that can be matched if (prefix && !hasCompleter) { if (!editor.completer) { // Create new autocompleter editor.completer = new Autocomplete(); } // Disable autoInsert editor.completer.autoSelect = false; editor.completer.autoInsert = false; editor.completer.showPopup(editor); } else if (!prefix && hasCompleter) { // When the prefix is empty // close the autocomplete dialog editor.completer.detach(); } } }; var Editor = require("../editor").Editor; require("../config").defineOptions(Editor.prototype, "editor", { enableBasicAutocompletion: { set: function(val) { if (val) { if (!this.completers) this.completers = Array.isArray(val)? val: completers; this.commands.addCommand(Autocomplete.startCommand); } else { this.commands.removeCommand(Autocomplete.startCommand); } }, value: false }, /** * Enable live autocomplete. If the value is an array, it is assumed to be an array of completers * and will use them instead of the default completers. */ enableLiveAutocompletion: { set: function(val) { if (val) { if (!this.completers) this.completers = Array.isArray(val)? val: completers; // On each change automatically trigger the autocomplete this.commands.on('afterExec', doLiveAutocomplete); } else { this.commands.removeListener('afterExec', doLiveAutocomplete); } }, value: false }, enableSnippets: { set: function(val) { if (val) { this.commands.addCommand(expandSnippet); this.on("changeMode", onChangeMode); onChangeMode(null, this); } else { this.commands.removeCommand(expandSnippet); this.off("changeMode", onChangeMode); } }, value: false } }); });
nagyist/ajaxorg-ace-editor
lib/ace/ext/language_tools.js
JavaScript
bsd-3-clause
8,100
/* * Copyright (c) 2016, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file implements UDP/IPv6 sockets. */ #include <stdio.h> #include <common/code_utils.hpp> #include <common/encoding.hpp> #include <net/ip6.hpp> #include <net/udp6.hpp> using Thread::Encoding::BigEndian::HostSwap16; namespace Thread { namespace Ip6 { UdpSocket::UdpSocket(Udp &aUdp) { mTransport = &aUdp; } Message *UdpSocket::NewMessage(uint16_t aReserved) { return static_cast<Udp *>(mTransport)->NewMessage(aReserved); } ThreadError UdpSocket::Open(otUdpReceive aHandler, void *aContext) { memset(&mSockName, 0, sizeof(mSockName)); memset(&mPeerName, 0, sizeof(mPeerName)); mHandler = aHandler; mContext = aContext; return static_cast<Udp *>(mTransport)->AddSocket(*this); } ThreadError UdpSocket::Bind(const SockAddr &aSockAddr) { mSockName = aSockAddr; return kThreadError_None; } ThreadError UdpSocket::Close(void) { ThreadError error = kThreadError_None; SuccessOrExit(error = static_cast<Udp *>(mTransport)->RemoveSocket(*this)); memset(&mSockName, 0, sizeof(mSockName)); memset(&mPeerName, 0, sizeof(mPeerName)); exit: return error; } ThreadError UdpSocket::SendTo(Message &aMessage, const MessageInfo &aMessageInfo) { ThreadError error = kThreadError_None; MessageInfo messageInfoLocal; UdpHeader udpHeader; messageInfoLocal = aMessageInfo; if (messageInfoLocal.GetSockAddr().IsUnspecified()) { messageInfoLocal.SetSockAddr(GetSockName().GetAddress()); } if (GetSockName().mPort == 0) { GetSockName().mPort = static_cast<Udp *>(mTransport)->GetEphemeralPort(); } udpHeader.SetSourcePort(GetSockName().mPort); udpHeader.SetDestinationPort(messageInfoLocal.mPeerPort); udpHeader.SetLength(sizeof(udpHeader) + aMessage.GetLength()); udpHeader.SetChecksum(0); SuccessOrExit(error = aMessage.Prepend(&udpHeader, sizeof(udpHeader))); aMessage.SetOffset(0); SuccessOrExit(error = static_cast<Udp *>(mTransport)->SendDatagram(aMessage, messageInfoLocal, kProtoUdp)); exit: return error; } Udp::Udp(Ip6 &aIp6): mEphemeralPort(kDynamicPortMin), mSockets(NULL), mIp6(aIp6) { } ThreadError Udp::AddSocket(UdpSocket &aSocket) { for (UdpSocket *cur = mSockets; cur; cur = cur->GetNext()) { if (cur == &aSocket) { ExitNow(); } } aSocket.SetNext(mSockets); mSockets = &aSocket; exit: return kThreadError_None; } ThreadError Udp::RemoveSocket(UdpSocket &aSocket) { if (mSockets == &aSocket) { mSockets = mSockets->GetNext(); } else { for (UdpSocket *socket = mSockets; socket; socket = socket->GetNext()) { if (socket->GetNext() == &aSocket) { socket->SetNext(aSocket.GetNext()); break; } } } aSocket.SetNext(NULL); return kThreadError_None; } uint16_t Udp::GetEphemeralPort(void) { uint16_t rval = mEphemeralPort; if (mEphemeralPort < kDynamicPortMax) { mEphemeralPort++; } else { mEphemeralPort = kDynamicPortMin; } return rval; } Message *Udp::NewMessage(uint16_t aReserved) { return mIp6.NewMessage(sizeof(UdpHeader) + aReserved); } ThreadError Udp::SendDatagram(Message &aMessage, MessageInfo &aMessageInfo, IpProto aIpProto) { return mIp6.SendDatagram(aMessage, aMessageInfo, aIpProto); } ThreadError Udp::HandleMessage(Message &aMessage, MessageInfo &aMessageInfo) { ThreadError error = kThreadError_None; UdpHeader udpHeader; uint16_t payloadLength; uint16_t checksum; payloadLength = aMessage.GetLength() - aMessage.GetOffset(); // check length VerifyOrExit(payloadLength >= sizeof(UdpHeader), error = kThreadError_Parse); // verify checksum checksum = Ip6::ComputePseudoheaderChecksum(aMessageInfo.GetPeerAddr(), aMessageInfo.GetSockAddr(), payloadLength, kProtoUdp); checksum = aMessage.UpdateChecksum(checksum, aMessage.GetOffset(), payloadLength); VerifyOrExit(checksum == 0xffff, ;); VerifyOrExit(aMessage.Read(aMessage.GetOffset(), sizeof(udpHeader), &udpHeader) == sizeof(udpHeader),); aMessage.MoveOffset(sizeof(udpHeader)); aMessageInfo.mPeerPort = udpHeader.GetSourcePort(); aMessageInfo.mSockPort = udpHeader.GetDestinationPort(); // find socket for (UdpSocket *socket = mSockets; socket; socket = socket->GetNext()) { if (socket->GetSockName().mPort != udpHeader.GetDestinationPort()) { continue; } if (socket->GetSockName().mScopeId != 0 && socket->GetSockName().mScopeId != aMessageInfo.mInterfaceId) { continue; } if (!aMessageInfo.GetSockAddr().IsMulticast() && !socket->GetSockName().GetAddress().IsUnspecified() && socket->GetSockName().GetAddress() != aMessageInfo.GetSockAddr()) { continue; } // verify source if connected socket if (socket->GetPeerName().mPort != 0) { if (socket->GetPeerName().mPort != udpHeader.GetSourcePort()) { continue; } if (!socket->GetPeerName().GetAddress().IsUnspecified() && socket->GetPeerName().GetAddress() != aMessageInfo.GetPeerAddr()) { continue; } } socket->HandleUdpReceive(aMessage, aMessageInfo); } exit: return error; } ThreadError Udp::UpdateChecksum(Message &aMessage, uint16_t aChecksum) { aChecksum = aMessage.UpdateChecksum(aChecksum, aMessage.GetOffset(), aMessage.GetLength() - aMessage.GetOffset()); if (aChecksum != 0xffff) { aChecksum = ~aChecksum; } aChecksum = HostSwap16(aChecksum); aMessage.Write(aMessage.GetOffset() + UdpHeader::GetChecksumOffset(), sizeof(aChecksum), &aChecksum); return kThreadError_None; } } // namespace Ip6 } // namespace Thread
GiedriusM/openthread
src/core/net/udp6.cpp
C++
bsd-3-clause
7,683
<?php return array( 'controllers' => array( 'invokables' => array( 'Album\Controller\Album' => 'Album\Controller\AlbumController', ), ), // The following section is new and should be added to your file 'router' => array( 'routes' => array( 'album' => array( 'type' => 'segment', 'options' => array( 'route' => '/album[/:action][/:id]', 'constraints' => array( 'action' => '[a-zA-Z][a-zA-Z0-9_-]*', 'id' => '[0-9]+', ), 'defaults' => array( 'controller' => 'Album\Controller\Album', 'action' => 'index', ), ), ), ), ), 'view_manager' => array( 'template_path_stack' => array( 'album' => __DIR__ . '/../view', ), ), );
alimulrazi/fmi
module/Album/config/module.config.php
PHP
bsd-3-clause
1,000
using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace OrchardCore.DisplayManagement.Descriptors.ShapePlacementStrategy { public class PlacementFile : Dictionary<string, PlacementNode[]> { } public class PlacementNode { [JsonProperty(PropertyName = "place")] public string Location { get; set; } [JsonProperty(PropertyName = "displayType")] public string DisplayType { get; set; } [JsonProperty(PropertyName = "differentiator")] public string Differentiator { get; set; } [JsonProperty(PropertyName = "alternates")] public string[] Alternates { get; set; } [JsonProperty(PropertyName = "wrappers")] public string[] Wrappers { get; set; } [JsonProperty(PropertyName = "shape")] public string ShapeType { get; set; } [JsonExtensionData] public IDictionary<string, JToken> Filters { get; set; } = new Dictionary<string, JToken>(); } }
OrchardCMS/Brochard
src/OrchardCore/OrchardCore.DisplayManagement/Descriptors/ShapePlacementStrategy/PlacementFile.cs
C#
bsd-3-clause
1,016
package com.sforce.android.sample; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.sforce.android.soap.partner.BaseResponseListener; import com.sforce.android.soap.partner.OAuthConnectorConfig; import com.sforce.android.soap.partner.OAuthLoginResult; import com.sforce.android.soap.partner.Salesforce; import com.sforce.android.soap.partner.fault.ApiFault; import com.sforce.android.soap.partner.fault.ExceptionCode; public class SforceOAuthLogin extends Activity implements OnClickListener{ String consumerKey=null; String callbackUrl=null; Button loginButton; Context context; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.oauth_login_layout); setTitle("Sforce Toolkit Demo - OAuth Login"); loginButton = (Button)this.findViewById(R.id.loginButton); loginButton.setOnClickListener(this); context=getApplicationContext(); consumerKey=(this.getResources().getString(R.string.consumerKey).toString()); callbackUrl=(this.getResources().getString(R.string.callbackUrl).toString()); Salesforce.init(context); } public void onClick(View v) { OAuthConnectorConfig parameters=new OAuthConnectorConfig(consumerKey, callbackUrl); try { Salesforce.loginOAuth(this, parameters, new LoginResponseListener()); } catch (Exception e){ e.printStackTrace(); } } public class LoginResponseListener extends BaseResponseListener{ @Override public void onComplete(Object sObjects) { OAuthLoginResult result = (OAuthLoginResult) sObjects; String id = result.getUserId(); setResult(RESULT_OK); finish(); } @Override public void onSforceError(ApiFault apiFault){ String msg = apiFault.getExceptionMessage(); String code = apiFault.getExceptionCode().getValue(); if (code.equals(ExceptionCode._ACCESS_DENIED)) { System.out.println("User didn't grant access"); } } @Override public void onException(Exception e){ } } }
reactualize/Force.com-Toolkit-for-Android
SampleApp/src/com/sforce/android/sample/SforceOAuthLogin.java
Java
bsd-3-clause
2,252
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const experimental_utils_1 = require("@typescript-eslint/experimental-utils"); const scope_manager_1 = require("@typescript-eslint/scope-manager"); const util = __importStar(require("../util")); const SENTINEL_TYPE = /^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration)$/; /** * Parses a given value as options. */ function parseOptions(options) { let functions = true; let classes = true; let enums = true; let variables = true; let typedefs = true; let ignoreTypeReferences = true; if (typeof options === 'string') { functions = options !== 'nofunc'; } else if (typeof options === 'object' && options !== null) { functions = options.functions !== false; classes = options.classes !== false; enums = options.enums !== false; variables = options.variables !== false; typedefs = options.typedefs !== false; ignoreTypeReferences = options.ignoreTypeReferences !== false; } return { functions, classes, enums, variables, typedefs, ignoreTypeReferences, }; } /** * Checks whether or not a given variable is a function declaration. */ function isFunction(variable) { return variable.defs[0].type === scope_manager_1.DefinitionType.FunctionName; } /** * Checks whether or not a given variable is a type declaration. */ function isTypedef(variable) { return variable.defs[0].type === scope_manager_1.DefinitionType.Type; } /** * Checks whether or not a given variable is a enum declaration. */ function isOuterEnum(variable, reference) { return (variable.defs[0].type == scope_manager_1.DefinitionType.TSEnumName && variable.scope.variableScope !== reference.from.variableScope); } /** * Checks whether or not a given variable is a class declaration in an upper function scope. */ function isOuterClass(variable, reference) { return (variable.defs[0].type === scope_manager_1.DefinitionType.ClassName && variable.scope.variableScope !== reference.from.variableScope); } /** * Checks whether or not a given variable is a variable declaration in an upper function scope. */ function isOuterVariable(variable, reference) { return (variable.defs[0].type === scope_manager_1.DefinitionType.Variable && variable.scope.variableScope !== reference.from.variableScope); } /** * Recursively checks whether or not a given reference has a type query declaration among it's parents */ function referenceContainsTypeQuery(node) { switch (node.type) { case experimental_utils_1.AST_NODE_TYPES.TSTypeQuery: return true; case experimental_utils_1.AST_NODE_TYPES.TSQualifiedName: case experimental_utils_1.AST_NODE_TYPES.Identifier: if (!node.parent) { return false; } return referenceContainsTypeQuery(node.parent); default: // if we find a different node, there's no chance that we're in a TSTypeQuery return false; } } /** * Checks whether or not a given reference is a type reference. */ function isTypeReference(reference) { return (reference.isTypeReference || referenceContainsTypeQuery(reference.identifier)); } /** * Checks whether or not a given location is inside of the range of a given node. */ function isInRange(node, location) { return !!node && node.range[0] <= location && location <= node.range[1]; } /** * Decorators are transpiled such that the decorator is placed after the class declaration * So it is considered safe */ function isClassRefInClassDecorator(variable, reference) { if (variable.defs[0].type !== scope_manager_1.DefinitionType.ClassName) { return false; } if (!variable.defs[0].node.decorators || variable.defs[0].node.decorators.length === 0) { return false; } for (const deco of variable.defs[0].node.decorators) { if (reference.identifier.range[0] >= deco.range[0] && reference.identifier.range[1] <= deco.range[1]) { return true; } } return false; } /** * Checks whether or not a given reference is inside of the initializers of a given variable. * * @returns `true` in the following cases: * - var a = a * - var [a = a] = list * - var {a = a} = obj * - for (var a in a) {} * - for (var a of a) {} */ function isInInitializer(variable, reference) { var _a; if (variable.scope !== reference.from) { return false; } let node = variable.identifiers[0].parent; const location = reference.identifier.range[1]; while (node) { if (node.type === experimental_utils_1.AST_NODE_TYPES.VariableDeclarator) { if (isInRange(node.init, location)) { return true; } if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) && (node.parent.parent.type === experimental_utils_1.AST_NODE_TYPES.ForInStatement || node.parent.parent.type === experimental_utils_1.AST_NODE_TYPES.ForOfStatement) && isInRange(node.parent.parent.right, location)) { return true; } break; } else if (node.type === experimental_utils_1.AST_NODE_TYPES.AssignmentPattern) { if (isInRange(node.right, location)) { return true; } } else if (SENTINEL_TYPE.test(node.type)) { break; } node = node.parent; } return false; } exports.default = util.createRule({ name: 'no-use-before-define', meta: { type: 'problem', docs: { description: 'Disallow the use of variables before they are defined', recommended: false, extendsBaseRule: true, }, messages: { noUseBeforeDefine: "'{{name}}' was used before it was defined.", }, schema: [ { oneOf: [ { enum: ['nofunc'], }, { type: 'object', properties: { functions: { type: 'boolean' }, classes: { type: 'boolean' }, enums: { type: 'boolean' }, variables: { type: 'boolean' }, typedefs: { type: 'boolean' }, ignoreTypeReferences: { type: 'boolean' }, }, additionalProperties: false, }, ], }, ], }, defaultOptions: [ { functions: true, classes: true, enums: true, variables: true, typedefs: true, ignoreTypeReferences: true, }, ], create(context, optionsWithDefault) { const options = parseOptions(optionsWithDefault[0]); /** * Determines whether a given use-before-define case should be reported according to the options. * @param variable The variable that gets used before being defined * @param reference The reference to the variable */ function isForbidden(variable, reference) { if (options.ignoreTypeReferences && isTypeReference(reference)) { return false; } if (isFunction(variable)) { return options.functions; } if (isOuterClass(variable, reference)) { return options.classes; } if (isOuterVariable(variable, reference)) { return options.variables; } if (isOuterEnum(variable, reference)) { return options.enums; } if (isTypedef(variable)) { return options.typedefs; } return true; } /** * Finds and validates all variables in a given scope. */ function findVariablesInScope(scope) { scope.references.forEach(reference => { const variable = reference.resolved; // Skips when the reference is: // - initializations. // - referring to an undefined variable. // - referring to a global environment variable (there're no identifiers). // - located preceded by the variable (except in initializers). // - allowed by options. if (reference.init || !variable || variable.identifiers.length === 0 || (variable.identifiers[0].range[1] <= reference.identifier.range[1] && !isInInitializer(variable, reference)) || !isForbidden(variable, reference) || isClassRefInClassDecorator(variable, reference) || reference.from.type === experimental_utils_1.TSESLint.Scope.ScopeType.functionType) { return; } // Reports. context.report({ node: reference.identifier, messageId: 'noUseBeforeDefine', data: { name: reference.identifier.name, }, }); }); scope.childScopes.forEach(findVariablesInScope); } return { Program() { findVariablesInScope(context.getScope()); }, }; }, }); //# sourceMappingURL=no-use-before-define.js.map
ChromeDevTools/devtools-frontend
node_modules/@typescript-eslint/eslint-plugin/dist/rules/no-use-before-define.js
JavaScript
bsd-3-clause
10,758
// Copyright 2012, Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package zk // contains the structures used for RPC calls to zkocc. import ( "time" ) type ZkStat struct { czxid int64 mzxid int64 cTime time.Time mTime time.Time version int cVersion int aVersion int ephemeralOwner int64 dataLength int numChildren int pzxid int64 } type ZkPath struct { Path string } type ZkPathV struct { Paths []string } type ZkNode struct { Path string Data string Stat ZkStat Children []string Cached bool // the response comes from the zkocc cache Stale bool // the response is stale because we're not connected } type ZkNodeV struct { Nodes []*ZkNode } // ZkStat methods to match zk.Stat interface func (zkStat *ZkStat) Czxid() int64 { return zkStat.czxid } func (zkStat *ZkStat) Mzxid() int64 { return zkStat.mzxid } func (zkStat *ZkStat) CTime() time.Time { return zkStat.cTime } func (zkStat *ZkStat) MTime() time.Time { return zkStat.mTime } func (zkStat *ZkStat) Version() int { return zkStat.version } func (zkStat *ZkStat) CVersion() int { return zkStat.cVersion } func (zkStat *ZkStat) AVersion() int { return zkStat.aVersion } func (zkStat *ZkStat) EphemeralOwner() int64 { return zkStat.ephemeralOwner } func (zkStat *ZkStat) DataLength() int { return zkStat.dataLength } func (zkStat *ZkStat) NumChildren() int { return zkStat.numChildren } func (zkStat *ZkStat) Pzxid() int64 { return zkStat.pzxid } // helper method func (zkStat *ZkStat) FromZookeeperStat(zStat Stat) { zkStat.czxid = zStat.Czxid() zkStat.mzxid = zStat.Mzxid() zkStat.cTime = zStat.CTime() zkStat.mTime = zStat.MTime() zkStat.version = zStat.Version() zkStat.cVersion = zStat.CVersion() zkStat.aVersion = zStat.AVersion() zkStat.ephemeralOwner = zStat.EphemeralOwner() zkStat.dataLength = zStat.DataLength() zkStat.numChildren = zStat.NumChildren() zkStat.pzxid = zStat.Pzxid() }
fanngyuan/vitess
go/zk/zkocc_structs.go
GO
bsd-3-clause
2,090
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/lib/ui/painting/shader.h" #include "flutter/lib/ui/ui_dart_state.h" namespace flutter { IMPLEMENT_WRAPPERTYPEINFO(ui, Shader); Shader::Shader(flutter::SkiaGPUObject<SkShader> shader) : shader_(std::move(shader)) {} Shader::~Shader() = default; } // namespace flutter
cdotstout/sky_engine
lib/ui/painting/shader.cc
C++
bsd-3-clause
461
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ ``fitsinfo`` is a command-line script based on astropy.io.fits for printing a summary of the HDUs in one or more FITS files(s) to the standard output. Example usage of ``fitsinfo``: 1. Print a summary of the HDUs in a FITS file:: $ fitsinfo filename.fits Filename: filename.fits No. Name Type Cards Dimensions Format 0 PRIMARY PrimaryHDU 138 () 1 SCI ImageHDU 61 (800, 800) int16 2 SCI ImageHDU 61 (800, 800) int16 3 SCI ImageHDU 61 (800, 800) int16 4 SCI ImageHDU 61 (800, 800) int16 2. Print a summary of HDUs of all the FITS files in the current directory:: $ fitsinfo *.fits """ from __future__ import (absolute_import, division, print_function, unicode_literals) import argparse import astropy.io.fits as fits from astropy import log def fitsinfo(filename): """ Print a summary of the HDUs in a FITS file. Parameters ---------- filename : str The path to a FITS file. """ try: fits.info(filename) except IOError as e: log.error(str(e)) return def main(args=None): """The main function called by the `fitsinfo` script.""" parser = argparse.ArgumentParser( description=('Print a summary of the HDUs in a FITS file(s).')) parser.add_argument('filename', nargs='+', help='Path to one or more FITS files. ' 'Wildcards are supported.') args = parser.parse_args(args) for idx, filename in enumerate(args.filename): if idx > 0: print() fitsinfo(filename)
joergdietrich/astropy
astropy/io/fits/scripts/fitsinfo.py
Python
bsd-3-clause
1,784
// bin/sum-mllt.cc // Copyright 2014 LINSE/UFSC; Augusto Henrique Hentz // See ../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "util/common-utils.h" #include "transform/mllt.h" int main(int argc, char *argv[]) { try { using namespace kaldi; typedef kaldi::int32 int32; const char *usage = "Sum stats obtained with gmm-acc-mllt.\n" "Usage: sum-mllt-accs [options] <stats-out> <stats-in1> <stats-in2> " "...\n"; bool binary = true; ParseOptions po(usage); po.Register("binary", &binary, "Write accumulators in binary mode."); po.Read(argc, argv); if (po.NumArgs() < 2) { po.PrintUsage(); exit(1); } MlltAccs mllt_accs; std::string stats_out_filename = po.GetArg(1); for (int32 i = 2; i <= po.NumArgs(); i++) { bool binary_in, add = true; Input ki(po.GetArg(i), &binary_in); mllt_accs.Read(ki.Stream(), binary_in, add); } Output ko(stats_out_filename, binary); mllt_accs.Write(ko.Stream(), binary); return 0; } catch (const std::exception &e) { std::cerr << e.what(); return -1; } }
ypkang/djinn
tonic-suite/asr/src/bin/sum-mllt-accs.cc
C++
bsd-3-clause
1,758
// Copyright (c) 2005-2009 INRIA Sophia-Antipolis (France). // All rights reserved. // // This file is part of CGAL (www.cgal.org); you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 3 of the License, // or (at your option) any later version. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL$ // $Id$ // // // Author(s) : Sebastien Loriot, Sylvain Pion #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/CGAL_Ipelet_base.h> #include <CGAL/Regular_triangulation_euclidean_traits_2.h> #include <CGAL/Regular_triangulation_2.h> #include "include/CGAL_ipelets/k_delaunay.h" namespace CGAL_multi_regular{ typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel; typedef Kernel::FT FT; typedef CGAL::Regular_triangulation_euclidean_traits_2<Kernel,FT> Gt; typedef CGAL::Regular_triangulation_2<Gt> Regular; typedef Regular::Finite_edges_iterator itEdge; // -------------------------------------------------------------------- const std::string sublabel[] = { "Regular", "Regular 2", "Regular 3","Regular n-1", "Regular k", "Power Diagram", "Power Diagram 2", "Power Diagram 3", "Power Diagram n-1", "Power Diagram k", "Help" }; const std::string hlpmsg[] = { "Generate k-th regular triangulation and k-th dual Power diagram. Note : k must be smaller than the number of input circles." }; class MregularIpelet : public CGAL::Ipelet_base<Kernel,11> { public: MregularIpelet() : CGAL::Ipelet_base<Kernel,11>("k-order Regular",sublabel,hlpmsg){} void protected_run(int); }; // -------------------------------------------------------------------- // -------------------------------------------------------------------- void MregularIpelet::protected_run(int fn) { Regular rt; std::vector<Weighted_point_2> input_wpt; if (fn==10) { show_help(false); return; } Iso_rectangle_2 bbox= read_active_objects( CGAL::dispatch_or_drop_output<Point_2,Circle_2>( wpoint_grabber(std::back_inserter(input_wpt)), wpoint_grabber(std::back_inserter(input_wpt)) ) ); if (!input_wpt.size()) { print_error_message("No circle selected"); return; } int order = 0; if(fn==0 || fn==5) order = 1; if(fn==1 || fn==6) order = 2; if(fn==2 || fn==7) order = 3; if(fn==3 || fn==8) order = input_wpt.size()-1;; if(fn==4 || fn==9){ int ret_val; boost::tie(ret_val,order)=request_value_from_user<int>("Enter order"); if (ret_val < 0){ print_error_message("Incorrect value"); return; } if(order<1 || order>=(int) input_wpt.size()){ print_error_message("Not a good order"); return; } } k_delaunay<Kernel>(rt,input_wpt,order); if(fn<5)//Draw k-th regular triangulation draw_in_ipe(rt); else{//Draw kth Power diagram double incr_len=75; bbox=Iso_rectangle_2(bbox.min()+Kernel::Vector_2(-incr_len,-incr_len), bbox.max()+Kernel::Vector_2(incr_len,incr_len)); draw_dual_in_ipe(rt,bbox); //draw Voronoi Diagram } } } CGAL_IPELET(CGAL_multi_regular::MregularIpelet)
hlzz/dotfiles
graphics/cgal/CGAL_ipelets/demo/CGAL_ipelets/multi_regular.cpp
C++
bsd-3-clause
3,617
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Component for generating chart PNGs using Google Chart Server. * * @see ../demos/serverchart.html */ /** * Namespace for chart functions */ goog.provide('goog.ui.ServerChart'); goog.provide('goog.ui.ServerChart.AxisDisplayType'); goog.provide('goog.ui.ServerChart.ChartType'); goog.provide('goog.ui.ServerChart.EncodingType'); goog.provide('goog.ui.ServerChart.Event'); goog.provide('goog.ui.ServerChart.LegendPosition'); goog.provide('goog.ui.ServerChart.MaximumValue'); goog.provide('goog.ui.ServerChart.MultiAxisAlignment'); goog.provide('goog.ui.ServerChart.MultiAxisType'); goog.provide('goog.ui.ServerChart.UriParam'); goog.provide('goog.ui.ServerChart.UriTooLongEvent'); goog.require('goog.Uri'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.events.Event'); goog.require('goog.string'); goog.require('goog.ui.Component'); /** * Will construct a chart using Google's chartserver. * * @param {goog.ui.ServerChart.ChartType} type The chart type. * @param {number=} opt_width The width of the chart. * @param {number=} opt_height The height of the chart. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM Helper. * @param {string=} opt_uri Optional uri used to connect to the chart server, if * different than goog.ui.ServerChart.CHART_SERVER_SCHEME_INDEPENDENT_URI. * @constructor * @extends {goog.ui.Component} */ goog.ui.ServerChart = function(type, opt_width, opt_height, opt_domHelper, opt_uri) { goog.ui.Component.call(this, opt_domHelper); /** * Image URI. * @type {goog.Uri} * @private */ this.uri_ = new goog.Uri( opt_uri || goog.ui.ServerChart.CHART_SERVER_SCHEME_INDEPENDENT_URI); /** * Encoding method for the URI data format. * @type {goog.ui.ServerChart.EncodingType} * @private */ this.encodingType_ = goog.ui.ServerChart.EncodingType.AUTOMATIC; /** * Two-dimensional array of the data sets on the chart. * @type {Array.<Array.<number>>} * @private */ this.dataSets_ = []; /** * Colors for each data set. * @type {Array.<string>} * @private */ this.setColors_ = []; /** * Legend texts for each data set. * @type {Array.<string>} * @private */ this.setLegendTexts_ = []; /** * Labels on the X-axis. * @type {Array.<string>} * @private */ this.xLabels_ = []; /** * Labels on the left along the Y-axis. * @type {Array.<string>} * @private */ this.leftLabels_ = []; /** * Labels on the right along the Y-axis. * @type {Array.<string>} * @private */ this.rightLabels_ = []; /** * Axis type for each multi-axis in the chart. The indices into this array * also work as the reference index for all other multi-axis properties. * @type {Array.<goog.ui.ServerChart.MultiAxisType>} * @private */ this.multiAxisType_ = []; /** * Axis text for each multi-axis in the chart, indexed by the indices from * multiAxisType_ in a sparse array. * @type {Object} * @private */ this.multiAxisLabelText_ = {}; /** * Axis position for each multi-axis in the chart, indexed by the indices * from multiAxisType_ in a sparse array. * @type {Object} * @private */ this.multiAxisLabelPosition_ = {}; /** * Axis range for each multi-axis in the chart, indexed by the indices from * multiAxisType_ in a sparse array. * @type {Object} * @private */ this.multiAxisRange_ = {}; /** * Axis style for each multi-axis in the chart, indexed by the indices from * multiAxisType_ in a sparse array. * @type {Object} * @private */ this.multiAxisLabelStyle_ = {}; this.setType(type); this.setSize(opt_width, opt_height); /** * Minimum value for the chart (used for normalization). By default, * this is set to infinity, and is eventually updated to the lowest given * value in the data. The minimum value is then subtracted from all other * values. For a pie chart, subtracting the minimum value does not make * sense, so minValue_ is set to zero because 0 is the additive identity. * @type {number} * @private */ this.minValue_ = this.isPieChart() ? 0 : Infinity; }; goog.inherits(goog.ui.ServerChart, goog.ui.Component); /** * Base scheme-independent URI for the chart renderer. * @type {string} */ goog.ui.ServerChart.CHART_SERVER_SCHEME_INDEPENDENT_URI = '//chart.googleapis.com/chart'; /** * Base HTTP URI for the chart renderer. * @type {string} */ goog.ui.ServerChart.CHART_SERVER_HTTP_URI = 'http://chart.googleapis.com/chart'; /** * Base HTTPS URI for the chart renderer. * @type {string} */ goog.ui.ServerChart.CHART_SERVER_HTTPS_URI = 'https://chart.googleapis.com/chart'; /** * Base URI for the chart renderer. * @type {string} * @deprecated Use * {@link goog.ui.ServerChart.CHART_SERVER_SCHEME_INDEPENDENT_URI}, * {@link goog.ui.ServerChart.CHART_SERVER_HTTP_URI} or * {@link goog.ui.ServerChart.CHART_SERVER_HTTPS_URI} instead. */ goog.ui.ServerChart.CHART_SERVER_URI = goog.ui.ServerChart.CHART_SERVER_HTTP_URI; /** * The 0 - 1.0 ("fraction of the range") value to use when getMinValue() == * getMaxValue(). This determines, for example, the vertical position * of the line in a flat line-chart. * @type {number} */ goog.ui.ServerChart.DEFAULT_NORMALIZATION = 0.5; /** * The upper limit on the length of the chart image URI, after encoding. * If the URI's length equals or exceeds it, goog.ui.ServerChart.UriTooLongEvent * is dispatched on the goog.ui.ServerChart object. * @type {number} * @private */ goog.ui.ServerChart.prototype.uriLengthLimit_ = 2048; /** * Number of gridlines along the X-axis. * @type {number} * @private */ goog.ui.ServerChart.prototype.gridX_ = 0; /** * Number of gridlines along the Y-axis. * @type {number} * @private */ goog.ui.ServerChart.prototype.gridY_ = 0; /** * Maximum value for the chart (used for normalization). The minimum is * declared in the constructor. * @type {number} * @private */ goog.ui.ServerChart.prototype.maxValue_ = -Infinity; /** * Chart title. * @type {?string} * @private */ goog.ui.ServerChart.prototype.title_ = null; /** * Chart title size. * @type {number} * @private */ goog.ui.ServerChart.prototype.titleSize_ = 13.5; /** * Chart title color. * @type {string} * @private */ goog.ui.ServerChart.prototype.titleColor_ = '333333'; /** * Chart legend. * @type {Array.<string>?} * @private */ goog.ui.ServerChart.prototype.legend_ = null; /** * ChartServer supports using data sets to position markers. A data set * that is being used for positioning only can be made "invisible", in other * words, the caller can indicate to ChartServer that ordinary chart elements * (e.g. bars in a bar chart) should not be drawn on the data points of the * invisible data set. Such data sets must be provided at the end of the * chd parameter, and if invisible data sets are being used, the chd * parameter must indicate the number of visible data sets. * @type {?number} * @private */ goog.ui.ServerChart.prototype.numVisibleDataSets_ = null; /** * Creates the DOM node (image) needed for the Chart * @override */ goog.ui.ServerChart.prototype.createDom = function() { var size = this.getSize(); this.setElementInternal(this.getDomHelper().createDom( 'img', {'src': this.getUri(), 'class': goog.getCssName('goog-serverchart-image'), 'width': size[0], 'height': size[1]})); }; /** * Decorate an image already in the DOM. * Expects the following structure: * <pre> * - img * </pre> * * @param {Element} img Image to decorate. */ goog.ui.ServerChart.prototype.decorateInternal = function(img) { img.src = this.getUri(); this.setElementInternal(img); }; /** * Updates the image if any of the data or settings have changed. */ goog.ui.ServerChart.prototype.updateChart = function() { if (this.getElement()) { this.getElement().src = this.getUri(); } }; /** * Sets the URI of the chart. * * @param {goog.Uri} uri The chart URI. */ goog.ui.ServerChart.prototype.setUri = function(uri) { this.uri_ = uri; }; /** * Returns the URI of the chart. * * @return {goog.Uri} The chart URI. */ goog.ui.ServerChart.prototype.getUri = function() { this.computeDataString_(); return this.uri_; }; /** * Returns the upper limit on the length of the chart image URI, after encoding. * If the URI's length equals or exceeds it, goog.ui.ServerChart.UriTooLongEvent * is dispatched on the goog.ui.ServerChart object. * * @return {number} The chart URI length limit. */ goog.ui.ServerChart.prototype.getUriLengthLimit = function() { return this.uriLengthLimit_; }; /** * Sets the upper limit on the length of the chart image URI, after encoding. * If the URI's length equals or exceeds it, goog.ui.ServerChart.UriTooLongEvent * is dispatched on the goog.ui.ServerChart object. * * @param {number} uriLengthLimit The chart URI length limit. */ goog.ui.ServerChart.prototype.setUriLengthLimit = function(uriLengthLimit) { this.uriLengthLimit_ = uriLengthLimit; }; /** * Sets the 'chg' parameter of the chart Uri. * This is used by various types of charts to specify Grids. * * @param {string} value Value for the 'chg' parameter in the chart Uri. */ goog.ui.ServerChart.prototype.setGridParameter = function(value) { this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.GRID, value); }; /** * Returns the 'chg' parameter of the chart Uri. * This is used by various types of charts to specify Grids. * * @return {string|undefined} The 'chg' parameter of the chart Uri. */ goog.ui.ServerChart.prototype.getGridParameter = function() { return /** @type {string} */ ( this.uri_.getParameterValue(goog.ui.ServerChart.UriParam.GRID)); }; /** * Sets the 'chm' parameter of the chart Uri. * This is used by various types of charts to specify Markers. * * @param {string} value Value for the 'chm' parameter in the chart Uri. */ goog.ui.ServerChart.prototype.setMarkerParameter = function(value) { this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.MARKERS, value); }; /** * Returns the 'chm' parameter of the chart Uri. * This is used by various types of charts to specify Markers. * * @return {string|undefined} The 'chm' parameter of the chart Uri. */ goog.ui.ServerChart.prototype.getMarkerParameter = function() { return /** @type {string} */ ( this.uri_.getParameterValue(goog.ui.ServerChart.UriParam.MARKERS)); }; /** * Sets the 'chp' parameter of the chart Uri. * This is used by various types of charts to specify certain options. * e.g., finance charts use this to designate which line is the 0 axis. * * @param {string|number} value Value for the 'chp' parameter in the chart Uri. */ goog.ui.ServerChart.prototype.setMiscParameter = function(value) { this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.MISC_PARAMS, String(value)); }; /** * Returns the 'chp' parameter of the chart Uri. * This is used by various types of charts to specify certain options. * e.g., finance charts use this to designate which line is the 0 axis. * * @return {string|undefined} The 'chp' parameter of the chart Uri. */ goog.ui.ServerChart.prototype.getMiscParameter = function() { return /** @type {string} */ ( this.uri_.getParameterValue(goog.ui.ServerChart.UriParam.MISC_PARAMS)); }; /** * Enum of chart data encoding types * * @enum {string} */ goog.ui.ServerChart.EncodingType = { AUTOMATIC: '', EXTENDED: 'e', SIMPLE: 's', TEXT: 't' }; /** * Enum of chart types with their short names used by the chartserver. * * @enum {string} */ goog.ui.ServerChart.ChartType = { BAR: 'br', CLOCK: 'cf', CONCENTRIC_PIE: 'pc', FILLEDLINE: 'lr', FINANCE: 'lfi', GOOGLEOMETER: 'gom', HORIZONTAL_GROUPED_BAR: 'bhg', HORIZONTAL_STACKED_BAR: 'bhs', LINE: 'lc', MAP: 't', MAPUSA: 'tuss', MAPWORLD: 'twoc', PIE: 'p', PIE3D: 'p3', RADAR: 'rs', SCATTER: 's', SPARKLINE: 'ls', VENN: 'v', VERTICAL_GROUPED_BAR: 'bvg', VERTICAL_STACKED_BAR: 'bvs', XYLINE: 'lxy' }; /** * Enum of multi-axis types. * * @enum {string} */ goog.ui.ServerChart.MultiAxisType = { X_AXIS: 'x', LEFT_Y_AXIS: 'y', RIGHT_Y_AXIS: 'r', TOP_AXIS: 't' }; /** * Enum of multi-axis alignments. * * @enum {number} */ goog.ui.ServerChart.MultiAxisAlignment = { ALIGN_LEFT: -1, ALIGN_CENTER: 0, ALIGN_RIGHT: 1 }; /** * Enum of legend positions. * * @enum {string} */ goog.ui.ServerChart.LegendPosition = { TOP: 't', BOTTOM: 'b', LEFT: 'l', RIGHT: 'r' }; /** * Enum of line and tick options for an axis. * * @enum {string} */ goog.ui.ServerChart.AxisDisplayType = { LINE_AND_TICKS: 'lt', LINE: 'l', TICKS: 't' }; /** * Enum of chart maximum values in pixels, as listed at: * http://code.google.com/apis/chart/basics.html * * @enum {number} */ goog.ui.ServerChart.MaximumValue = { WIDTH: 1000, HEIGHT: 1000, MAP_WIDTH: 440, MAP_HEIGHT: 220, TOTAL_AREA: 300000 }; /** * Enum of ChartServer URI parameters. * * @enum {string} */ goog.ui.ServerChart.UriParam = { BACKGROUND_FILL: 'chf', BAR_HEIGHT: 'chbh', DATA: 'chd', DATA_COLORS: 'chco', DATA_LABELS: 'chld', DATA_SCALING: 'chds', DIGITAL_SIGNATURE: 'sig', GEOGRAPHICAL_REGION: 'chtm', GRID: 'chg', LABEL_COLORS: 'chlc', LEFT_Y_LABELS: 'chly', LEGEND: 'chdl', LEGEND_POSITION: 'chdlp', LEGEND_TEXTS: 'chdl', LINE_STYLES: 'chls', MARGINS: 'chma', MARKERS: 'chm', MISC_PARAMS: 'chp', MULTI_AXIS_LABEL_POSITION: 'chxp', MULTI_AXIS_LABEL_TEXT: 'chxl', MULTI_AXIS_RANGE: 'chxr', MULTI_AXIS_STYLE: 'chxs', MULTI_AXIS_TYPES: 'chxt', RIGHT_LABELS: 'chlr', RIGHT_LABEL_POSITIONS: 'chlrp', SIZE: 'chs', TITLE: 'chtt', TITLE_FORMAT: 'chts', TYPE: 'cht', X_AXIS_STYLE: 'chx', X_LABELS: 'chl' }; /** * Sets the background fill. * * @param {Array.<Object>} fill An array of background fill specification * objects. Each object may have the following properties: * {string} area The area to fill, either 'bg' for background or 'c' for * chart area. The default is 'bg'. * {string} color (required) The color of the background fill. * // TODO(user): Add support for gradient/stripes, which requires * // a different object structure. */ goog.ui.ServerChart.prototype.setBackgroundFill = function(fill) { var value = []; goog.array.forEach(fill, function(spec) { spec.area = spec.area || 'bg'; spec.effect = spec.effect || 's'; value.push([spec.area, spec.effect, spec.color].join(',')); }); value = value.join('|'); this.setParameterValue(goog.ui.ServerChart.UriParam.BACKGROUND_FILL, value); }; /** * Returns the background fill. * * @return {Array.<Object>} An array of background fill specifications. * If the fill specification string is in an unsupported format, the method * returns an empty array. */ goog.ui.ServerChart.prototype.getBackgroundFill = function() { var value = this.uri_.getParameterValue(goog.ui.ServerChart.UriParam.BACKGROUND_FILL); var result = []; if (goog.isDefAndNotNull(value)) { var fillSpecifications = value.split('|'); var valid = true; goog.array.forEach(fillSpecifications, function(spec) { spec = spec.split(','); if (valid && spec[1] == 's') { result.push({area: spec[0], effect: spec[1], color: spec[2]}); } else { // If the format is unsupported, return an empty array. result = []; valid = false; } }); } return result; }; /** * Sets the encoding type. * * @param {goog.ui.ServerChart.EncodingType} type Desired data encoding type. */ goog.ui.ServerChart.prototype.setEncodingType = function(type) { this.encodingType_ = type; }; /** * Gets the encoding type. * * @return {goog.ui.ServerChart.EncodingType} The encoding type. */ goog.ui.ServerChart.prototype.getEncodingType = function() { return this.encodingType_; }; /** * Sets the chart type. * * @param {goog.ui.ServerChart.ChartType} type The desired chart type. */ goog.ui.ServerChart.prototype.setType = function(type) { this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.TYPE, type); }; /** * Returns the chart type. * * @return {goog.ui.ServerChart.ChartType} The chart type. */ goog.ui.ServerChart.prototype.getType = function() { return /** @type {goog.ui.ServerChart.ChartType} */ ( this.uri_.getParameterValue(goog.ui.ServerChart.UriParam.TYPE)); }; /** * Sets the chart size. * * @param {number=} opt_width Optional chart width, defaults to 300. * @param {number=} opt_height Optional chart height, defaults to 150. */ goog.ui.ServerChart.prototype.setSize = function(opt_width, opt_height) { var sizeString = [opt_width || 300, opt_height || 150].join('x'); this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.SIZE, sizeString); }; /** * Returns the chart size. * * @return {Array.<string>} [Width, Height]. */ goog.ui.ServerChart.prototype.getSize = function() { var sizeStr = this.uri_.getParameterValue(goog.ui.ServerChart.UriParam.SIZE); return sizeStr.split('x'); }; /** * Sets the minimum value of the chart. * * @param {number} minValue The minimum value of the chart. */ goog.ui.ServerChart.prototype.setMinValue = function(minValue) { this.minValue_ = minValue; }; /** * @return {number} The minimum value of the chart. */ goog.ui.ServerChart.prototype.getMinValue = function() { return this.minValue_; }; /** * Sets the maximum value of the chart. * * @param {number} maxValue The maximum value of the chart. */ goog.ui.ServerChart.prototype.setMaxValue = function(maxValue) { this.maxValue_ = maxValue; }; /** * @return {number} The maximum value of the chart. */ goog.ui.ServerChart.prototype.getMaxValue = function() { return this.maxValue_; }; /** * Sets the chart margins. * * @param {number} leftMargin The size in pixels of the left margin. * @param {number} rightMargin The size in pixels of the right margin. * @param {number} topMargin The size in pixels of the top margin. * @param {number} bottomMargin The size in pixels of the bottom margin. */ goog.ui.ServerChart.prototype.setMargins = function(leftMargin, rightMargin, topMargin, bottomMargin) { var margins = [leftMargin, rightMargin, topMargin, bottomMargin].join(','); var UriParam = goog.ui.ServerChart.UriParam; this.uri_.setParameterValue(UriParam.MARGINS, margins); }; /** * Sets the number of grid lines along the X-axis. * * @param {number} gridlines The number of X-axis grid lines. */ goog.ui.ServerChart.prototype.setGridX = function(gridlines) { // Need data for this to work. this.gridX_ = gridlines; this.setGrids_(this.gridX_, this.gridY_); }; /** * @return {number} The number of gridlines along the X-axis. */ goog.ui.ServerChart.prototype.getGridX = function() { return this.gridX_; }; /** * Sets the number of grid lines along the Y-axis. * * @param {number} gridlines The number of Y-axis grid lines. */ goog.ui.ServerChart.prototype.setGridY = function(gridlines) { // Need data for this to work. this.gridY_ = gridlines; this.setGrids_(this.gridX_, this.gridY_); }; /** * @return {number} The number of gridlines along the Y-axis. */ goog.ui.ServerChart.prototype.getGridY = function() { return this.gridY_; }; /** * Sets the grids for the chart * * @private * @param {number} x The number of grid lines along the x-axis. * @param {number} y The number of grid lines along the y-axis. */ goog.ui.ServerChart.prototype.setGrids_ = function(x, y) { var gridArray = [x == 0 ? 0 : 100 / x, y == 0 ? 0 : 100 / y]; this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.GRID, gridArray.join(',')); }; /** * Sets the X Labels for the chart. * * @param {Array.<string>} labels The X Labels for the chart. */ goog.ui.ServerChart.prototype.setXLabels = function(labels) { this.xLabels_ = labels; this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.X_LABELS, this.xLabels_.join('|')); }; /** * @return {Array.<string>} The X Labels for the chart. */ goog.ui.ServerChart.prototype.getXLabels = function() { return this.xLabels_; }; /** * @return {boolean} Whether the chart is a bar chart. */ goog.ui.ServerChart.prototype.isBarChart = function() { var type = this.getType(); return type == goog.ui.ServerChart.ChartType.BAR || type == goog.ui.ServerChart.ChartType.HORIZONTAL_GROUPED_BAR || type == goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR || type == goog.ui.ServerChart.ChartType.VERTICAL_GROUPED_BAR || type == goog.ui.ServerChart.ChartType.VERTICAL_STACKED_BAR; }; /** * @return {boolean} Whether the chart is a pie chart. */ goog.ui.ServerChart.prototype.isPieChart = function() { var type = this.getType(); return type == goog.ui.ServerChart.ChartType.PIE || type == goog.ui.ServerChart.ChartType.PIE3D || type == goog.ui.ServerChart.ChartType.CONCENTRIC_PIE; }; /** * @return {boolean} Whether the chart is a grouped bar chart. */ goog.ui.ServerChart.prototype.isGroupedBarChart = function() { var type = this.getType(); return type == goog.ui.ServerChart.ChartType.HORIZONTAL_GROUPED_BAR || type == goog.ui.ServerChart.ChartType.VERTICAL_GROUPED_BAR; }; /** * @return {boolean} Whether the chart is a horizontal bar chart. */ goog.ui.ServerChart.prototype.isHorizontalBarChart = function() { var type = this.getType(); return type == goog.ui.ServerChart.ChartType.BAR || type == goog.ui.ServerChart.ChartType.HORIZONTAL_GROUPED_BAR || type == goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR; }; /** * @return {boolean} Whether the chart is a line chart. */ goog.ui.ServerChart.prototype.isLineChart = function() { var type = this.getType(); return type == goog.ui.ServerChart.ChartType.FILLEDLINE || type == goog.ui.ServerChart.ChartType.LINE || type == goog.ui.ServerChart.ChartType.SPARKLINE || type == goog.ui.ServerChart.ChartType.XYLINE; }; /** * @return {boolean} Whether the chart is a map. */ goog.ui.ServerChart.prototype.isMap = function() { var type = this.getType(); return type == goog.ui.ServerChart.ChartType.MAP || type == goog.ui.ServerChart.ChartType.MAPUSA || type == goog.ui.ServerChart.ChartType.MAPWORLD; }; /** * @return {boolean} Whether the chart is a stacked bar chart. */ goog.ui.ServerChart.prototype.isStackedBarChart = function() { var type = this.getType(); return type == goog.ui.ServerChart.ChartType.BAR || type == goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR || type == goog.ui.ServerChart.ChartType.VERTICAL_STACKED_BAR; }; /** * @return {boolean} Whether the chart is a vertical bar chart. */ goog.ui.ServerChart.prototype.isVerticalBarChart = function() { var type = this.getType(); return type == goog.ui.ServerChart.ChartType.VERTICAL_GROUPED_BAR || type == goog.ui.ServerChart.ChartType.VERTICAL_STACKED_BAR; }; /** * Sets the Left Labels for the chart. * NOTE: The array should start with the lowest value, and then * move progessively up the axis. So if you want labels * from 0 to 100 with 0 at bottom of the graph, then you would * want to pass something like [0,25,50,75,100]. * * @param {Array.<string>} labels The Left Labels for the chart. */ goog.ui.ServerChart.prototype.setLeftLabels = function(labels) { this.leftLabels_ = labels; this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.LEFT_Y_LABELS, this.leftLabels_.reverse().join('|')); }; /** * @return {Array.<string>} The Left Labels for the chart. */ goog.ui.ServerChart.prototype.getLeftLabels = function() { return this.leftLabels_; }; /** * Sets the given ChartServer parameter. * * @param {goog.ui.ServerChart.UriParam} key The ChartServer parameter to set. * @param {string} value The value to set for the ChartServer parameter. */ goog.ui.ServerChart.prototype.setParameterValue = function(key, value) { this.uri_.setParameterValue(key, value); }; /** * Removes the given ChartServer parameter. * * @param {goog.ui.ServerChart.UriParam} key The ChartServer parameter to * remove. */ goog.ui.ServerChart.prototype.removeParameter = function(key) { this.uri_.removeParameter(key); }; /** * Sets the Right Labels for the chart. * NOTE: The array should start with the lowest value, and then * move progessively up the axis. So if you want labels * from 0 to 100 with 0 at bottom of the graph, then you would * want to pass something like [0,25,50,75,100]. * * @param {Array.<string>} labels The Right Labels for the chart. */ goog.ui.ServerChart.prototype.setRightLabels = function(labels) { this.rightLabels_ = labels; this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.RIGHT_LABELS, this.rightLabels_.reverse().join('|')); }; /** * @return {Array.<string>} The Right Labels for the chart. */ goog.ui.ServerChart.prototype.getRightLabels = function() { return this.rightLabels_; }; /** * Sets the position relative to the chart where the legend is to be displayed. * * @param {goog.ui.ServerChart.LegendPosition} value Legend position. */ goog.ui.ServerChart.prototype.setLegendPosition = function(value) { this.uri_.setParameterValue( goog.ui.ServerChart.UriParam.LEGEND_POSITION, value); }; /** * Returns the position relative to the chart where the legend is to be * displayed. * * @return {goog.ui.ServerChart.LegendPosition} Legend position. */ goog.ui.ServerChart.prototype.getLegendPosition = function() { return /** @type {goog.ui.ServerChart.LegendPosition} */ ( this.uri_.getParameterValue( goog.ui.ServerChart.UriParam.LEGEND_POSITION)); }; /** * Sets the number of "visible" data sets. All data sets that come after * the visible data set are not drawn as part of the chart. Instead, they * are available for positioning markers. * @param {?number} n The number of visible data sets, or null if all data * sets are to be visible. */ goog.ui.ServerChart.prototype.setNumVisibleDataSets = function(n) { this.numVisibleDataSets_ = n; }; /** * Returns the number of "visible" data sets. All data sets that come after * the visible data set are not drawn as part of the chart. Instead, they * are available for positioning markers. * * @return {?number} The number of visible data sets, or null if all data * sets are visible. */ goog.ui.ServerChart.prototype.getNumVisibleDataSets = function() { return this.numVisibleDataSets_; }; /** * Sets the weight function for a Venn Diagram along with the associated * colors and legend text. Weights are assigned as follows: * weights[0] is relative area of circle A. * weights[1] is relative area of circle B. * weights[2] is relative area of circle C. * weights[3] is relative area of overlap of circles A and B. * weights[4] is relative area of overlap of circles A and C. * weights[5] is relative area of overlap of circles B and C. * weights[6] is relative area of overlap of circles A, B and C. * For a two circle Venn Diagram the weights are assigned as follows: * weights[0] is relative area of circle A. * weights[1] is relative area of circle B. * weights[2] is relative area of overlap of circles A and B. * * @param {Array.<number>} weights The relative weights of the circles. * @param {Array.<string>=} opt_legendText The legend labels for the circles. * @param {Array.<string>=} opt_colors The colors for the circles. */ goog.ui.ServerChart.prototype.setVennSeries = function( weights, opt_legendText, opt_colors) { if (this.getType() != goog.ui.ServerChart.ChartType.VENN) { throw Error('Can only set a weight function for a Venn diagram.'); } var dataMin = this.arrayMin_(weights); if (dataMin < this.minValue_) { this.minValue_ = dataMin; } var dataMax = this.arrayMax_(weights); if (dataMax > this.maxValue_) { this.maxValue_ = dataMax; } if (goog.isDef(opt_legendText)) { goog.array.forEach( opt_legendText, goog.bind(function(legend) { this.setLegendTexts_.push(legend); }, this)); this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.LEGEND_TEXTS, this.setLegendTexts_.join('|')); } // If the caller only gave three weights, then they wanted a two circle // Venn Diagram. Create a 3 circle weight function where circle C has // area zero. if (weights.length == 3) { weights[3] = weights[2]; weights[2] = 0.0; } this.dataSets_.push(weights); if (goog.isDef(opt_colors)) { goog.array.forEach(opt_colors, goog.bind(function(color) { this.setColors_.push(color); }, this)); this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.DATA_COLORS, this.setColors_.join(',')); } }; /** * Sets the title of the chart. * * @param {string} title The chart title. */ goog.ui.ServerChart.prototype.setTitle = function(title) { this.title_ = title; this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.TITLE, this.title_.replace(/\n/g, '|')); }; /** * Sets the size of the chart title. * * @param {number} size The title size, in points. */ goog.ui.ServerChart.prototype.setTitleSize = function(size) { this.titleSize_ = size; this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.TITLE_FORMAT, this.titleColor_ + ',' + this.titleSize_); }; /** * @return {number} size The title size, in points. */ goog.ui.ServerChart.prototype.getTitleSize = function() { return this.titleSize_; }; /** * Sets the color of the chart title. * * NOTE: The color string should NOT have a '#' at the beginning of it. * * @param {string} color The hex value for the title color. */ goog.ui.ServerChart.prototype.setTitleColor = function(color) { this.titleColor_ = color; this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.TITLE_FORMAT, this.titleColor_ + ',' + this.titleSize_); }; /** * @return {string} color The hex value for the title color. */ goog.ui.ServerChart.prototype.getTitleColor = function() { return this.titleColor_; }; /** * Adds a legend to the chart. * * @param {Array.<string>} legend The legend to add. */ goog.ui.ServerChart.prototype.setLegend = function(legend) { this.legend_ = legend; this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.LEGEND, this.legend_.join('|')); }; /** * Sets the data scaling. * NOTE: This also changes the encoding type because data scaling will * only work with {@code goog.ui.ServerChart.EncodingType.TEXT} * encoding. * @param {number} minimum The lowest number to apply to the data. * @param {number} maximum The highest number to apply to the data. */ goog.ui.ServerChart.prototype.setDataScaling = function(minimum, maximum) { this.encodingType_ = goog.ui.ServerChart.EncodingType.TEXT; this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.DATA_SCALING, minimum + ',' + maximum); }; /** * Sets the widths of the bars and the spaces between the bars in a bar * chart. * NOTE: If the space between groups is specified but the space between * bars is left undefined, the space between groups will be interpreted * as the space between bars because this is the behavior exposed * in the external developers guide. * @param {number} barWidth The width of a bar in pixels. * @param {number=} opt_spaceBars The width of the space between * bars in a group in pixels. * @param {number=} opt_spaceGroups The width of the space between * groups. */ goog.ui.ServerChart.prototype.setBarSpaceWidths = function(barWidth, opt_spaceBars, opt_spaceGroups) { var widths = [barWidth]; if (goog.isDef(opt_spaceBars)) { widths.push(opt_spaceBars); } if (goog.isDef(opt_spaceGroups)) { widths.push(opt_spaceGroups); } this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.BAR_HEIGHT, widths.join(',')); }; /** * Specifies that the bar width in a bar chart should be calculated * automatically given the space available in the chart, while optionally * setting the spaces between the bars. * NOTE: If the space between groups is specified but the space between * bars is left undefined, the space between groups will be interpreted * as the space between bars because this is the behavior exposed * in the external developers guide. * @param {number=} opt_spaceBars The width of the space between * bars in a group in pixels. * @param {number=} opt_spaceGroups The width of the space between * groups. */ goog.ui.ServerChart.prototype.setAutomaticBarWidth = function(opt_spaceBars, opt_spaceGroups) { var widths = ['a']; if (goog.isDef(opt_spaceBars)) { widths.push(opt_spaceBars); } if (goog.isDef(opt_spaceGroups)) { widths.push(opt_spaceGroups); } this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.BAR_HEIGHT, widths.join(',')); }; /** * Adds a multi-axis to the chart, and sets its type. Multiple axes of the same * type can be added. * * @param {goog.ui.ServerChart.MultiAxisType} axisType The desired axis type. * @return {number} The index of the newly inserted axis, suitable for feeding * to the setMultiAxis*() functions. */ goog.ui.ServerChart.prototype.addMultiAxis = function(axisType) { this.multiAxisType_.push(axisType); this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.MULTI_AXIS_TYPES, this.multiAxisType_.join(',')); return this.multiAxisType_.length - 1; }; /** * Returns the axis type for the given axis, or all of them in an array if the * axis number is not given. * * @param {number=} opt_axisNumber The axis index, as returned by addMultiAxis. * @return {goog.ui.ServerChart.MultiAxisType| * Array.<goog.ui.ServerChart.MultiAxisType>} * The axis type for the given axis, or all of them in an array if the * axis number is not given. */ goog.ui.ServerChart.prototype.getMultiAxisType = function(opt_axisNumber) { if (goog.isDef(opt_axisNumber)) { return this.multiAxisType_[opt_axisNumber]; } return this.multiAxisType_; }; /** * Sets the label text (usually multiple values) for a given axis, overwriting * any existing values. * * @param {number} axisNumber The axis index, as returned by addMultiAxis. * @param {Array.<string>} labelText The actual label text to be added. */ goog.ui.ServerChart.prototype.setMultiAxisLabelText = function(axisNumber, labelText) { this.multiAxisLabelText_[axisNumber] = labelText; var axisString = this.computeMultiAxisDataString_(this.multiAxisLabelText_, ':|', '|', '|'); this.uri_.setParameterValue( goog.ui.ServerChart.UriParam.MULTI_AXIS_LABEL_TEXT, axisString); }; /** * Returns the label text, or all of them in a two-dimensional array if the * axis number is not given. * * @param {number=} opt_axisNumber The axis index, as returned by addMultiAxis. * @return {Object|Array.<string>} The label text, or all of them in a * two-dimensional array if the axis number is not given. */ goog.ui.ServerChart.prototype.getMultiAxisLabelText = function(opt_axisNumber) { if (goog.isDef(opt_axisNumber)) { return this.multiAxisLabelText_[opt_axisNumber]; } return this.multiAxisLabelText_; }; /** * Sets the label positions for a given axis, overwriting any existing values. * The label positions are assumed to be floating-point numbers within the * range of the axis. * * @param {number} axisNumber The axis index, as returned by addMultiAxis. * @param {Array.<number>} labelPosition The actual label positions to be added. */ goog.ui.ServerChart.prototype.setMultiAxisLabelPosition = function( axisNumber, labelPosition) { this.multiAxisLabelPosition_[axisNumber] = labelPosition; var positionString = this.computeMultiAxisDataString_( this.multiAxisLabelPosition_, ',', ',', '|'); this.uri_.setParameterValue( goog.ui.ServerChart.UriParam.MULTI_AXIS_LABEL_POSITION, positionString); }; /** * Returns the label positions for a given axis number, or all of them in a * two-dimensional array if the axis number is not given. * * @param {number=} opt_axisNumber The axis index, as returned by addMultiAxis. * @return {Object|Array.<number>} The label positions for a given axis number, * or all of them in a two-dimensional array if the axis number is not * given. */ goog.ui.ServerChart.prototype.getMultiAxisLabelPosition = function(opt_axisNumber) { if (goog.isDef(opt_axisNumber)) { return this.multiAxisLabelPosition_[opt_axisNumber]; } return this.multiAxisLabelPosition_; }; /** * Sets the label range for a given axis, overwriting any existing range. * The default range is from 0 to 100. If the start value is larger than the * end value, the axis direction is reversed. rangeStart and rangeEnd must * be two different finite numbers. * * @param {number} axisNumber The axis index, as returned by addMultiAxis. * @param {number} rangeStart The new start of the range. * @param {number} rangeEnd The new end of the range. * @param {number=} opt_interval The interval between axis labels. */ goog.ui.ServerChart.prototype.setMultiAxisRange = function(axisNumber, rangeStart, rangeEnd, opt_interval) { goog.asserts.assert(rangeStart != rangeEnd, 'Range start and end cannot be the same value.'); goog.asserts.assert(isFinite(rangeStart) && isFinite(rangeEnd), 'Range start and end must be finite numbers.'); this.multiAxisRange_[axisNumber] = [rangeStart, rangeEnd]; if (goog.isDef(opt_interval)) { this.multiAxisRange_[axisNumber].push(opt_interval); } var rangeString = this.computeMultiAxisDataString_(this.multiAxisRange_, ',', ',', '|'); this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.MULTI_AXIS_RANGE, rangeString); }; /** * Returns the label range for a given axis number as a two-element array of * (range start, range end), or all of them in a two-dimensional array if the * axis number is not given. * * @param {number=} opt_axisNumber The axis index, as returned by addMultiAxis. * @return {Object|Array.<number>} The label range for a given axis number as a * two-element array of (range start, range end), or all of them in a * two-dimensional array if the axis number is not given. */ goog.ui.ServerChart.prototype.getMultiAxisRange = function(opt_axisNumber) { if (goog.isDef(opt_axisNumber)) { return this.multiAxisRange_[opt_axisNumber]; } return this.multiAxisRange_; }; /** * Sets the label style for a given axis, overwriting any existing style. * The default style is as follows: Default is x-axis labels are centered, left * hand y-axis labels are right aligned, right hand y-axis labels are left * aligned. The font size and alignment are optional parameters. * * NOTE: The color string should NOT have a '#' at the beginning of it. * * @param {number} axisNumber The axis index, as returned by addMultiAxis. * @param {string} color The hex value for this label's color. * @param {number=} opt_fontSize The label font size, in pixels. * @param {goog.ui.ServerChart.MultiAxisAlignment=} opt_alignment The label * alignment. * @param {goog.ui.ServerChart.AxisDisplayType=} opt_axisDisplay The axis * line and ticks. */ goog.ui.ServerChart.prototype.setMultiAxisLabelStyle = function(axisNumber, color, opt_fontSize, opt_alignment, opt_axisDisplay) { var style = [color]; if (goog.isDef(opt_fontSize) || goog.isDef(opt_alignment)) { style.push(opt_fontSize || ''); } if (goog.isDef(opt_alignment)) { style.push(opt_alignment); } if (opt_axisDisplay) { style.push(opt_axisDisplay); } this.multiAxisLabelStyle_[axisNumber] = style; var styleString = this.computeMultiAxisDataString_(this.multiAxisLabelStyle_, ',', ',', '|'); this.uri_.setParameterValue( goog.ui.ServerChart.UriParam.MULTI_AXIS_STYLE, styleString); }; /** * Returns the label style for a given axis number as a one- to three-element * array, or all of them in a two-dimensional array if the axis number is not * given. * * @param {number=} opt_axisNumber The axis index, as returned by addMultiAxis. * @return {Object|Array.<number>} The label style for a given axis number as a * one- to three-element array, or all of them in a two-dimensional array if * the axis number is not given. */ goog.ui.ServerChart.prototype.getMultiAxisLabelStyle = function(opt_axisNumber) { if (goog.isDef(opt_axisNumber)) { return this.multiAxisLabelStyle_[opt_axisNumber]; } return this.multiAxisLabelStyle_; }; /** * Adds a data set. * NOTE: The color string should NOT have a '#' at the beginning of it. * * @param {Array.<number|null>} data An array of numbers (values can be * NaN or null). * @param {string} color The hex value for this data set's color. * @param {string=} opt_legendText The legend text, if any, for this data * series. NOTE: If specified, all previously added data sets must also * have a legend text. */ goog.ui.ServerChart.prototype.addDataSet = function(data, color, opt_legendText) { var dataMin = this.arrayMin_(data); if (dataMin < this.minValue_) { this.minValue_ = dataMin; } var dataMax = this.arrayMax_(data); if (dataMax > this.maxValue_) { this.maxValue_ = dataMax; } if (goog.isDef(opt_legendText)) { if (this.setLegendTexts_.length < this.dataSets_.length) { throw Error('Cannot start adding legends text after first element.'); } this.setLegendTexts_.push(opt_legendText); this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.LEGEND_TEXTS, this.setLegendTexts_.join('|')); } this.dataSets_.push(data); this.setColors_.push(color); this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.DATA_COLORS, this.setColors_.join(',')); }; /** * Clears the data sets from the graph. All data, including the colors and * legend text, is cleared. */ goog.ui.ServerChart.prototype.clearDataSets = function() { var queryData = this.uri_.getQueryData(); queryData.remove(goog.ui.ServerChart.UriParam.LEGEND_TEXTS); queryData.remove(goog.ui.ServerChart.UriParam.DATA_COLORS); queryData.remove(goog.ui.ServerChart.UriParam.DATA); this.setLegendTexts_.length = 0; this.setColors_.length = 0; this.dataSets_.length = 0; }; /** * Returns the given data set or all of them in a two-dimensional array if * the set number is not given. * * @param {number=} opt_setNumber Optional data set number to get. * @return {Array} The given data set or all of them in a two-dimensional array * if the set number is not given. */ goog.ui.ServerChart.prototype.getData = function(opt_setNumber) { if (goog.isDef(opt_setNumber)) { return this.dataSets_[opt_setNumber]; } return this.dataSets_; }; /** * Computes the data string using the data in this.dataSets_ and sets * the object's URI accordingly. If the URI's length equals or exceeds the * limit, goog.ui.ServerChart.UriTooLongEvent is dispatched on the * goog.ui.ServerChart object. * @private */ goog.ui.ServerChart.prototype.computeDataString_ = function() { var ok; if (this.encodingType_ != goog.ui.ServerChart.EncodingType.AUTOMATIC) { ok = this.computeDataStringForEncoding_(this.encodingType_); } else { ok = this.computeDataStringForEncoding_( goog.ui.ServerChart.EncodingType.EXTENDED); if (!ok) { ok = this.computeDataStringForEncoding_( goog.ui.ServerChart.EncodingType.SIMPLE); } } if (!ok) { this.dispatchEvent( new goog.ui.ServerChart.UriTooLongEvent(this.uri_.toString())); } }; /** * Computes the data string using the data in this.dataSets_ and the encoding * specified by the encoding parameter, which must not be AUTOMATIC, and sets * the object's URI accordingly. * @param {goog.ui.ServerChart.EncodingType} encoding The data encoding to use; * must not be AUTOMATIC. * @return {boolean} False if the resulting URI is too long. * @private */ goog.ui.ServerChart.prototype.computeDataStringForEncoding_ = function( encoding) { var dataStrings = []; for (var i = 0, setLen = this.dataSets_.length; i < setLen; ++i) { dataStrings[i] = this.getChartServerValues_(this.dataSets_[i], this.minValue_, this.maxValue_, encoding); } var delimiter = encoding == goog.ui.ServerChart.EncodingType.TEXT ? '|' : ','; dataStrings = dataStrings.join(delimiter); var data; if (this.numVisibleDataSets_ == null) { data = goog.string.buildString(encoding, ':', dataStrings); } else { data = goog.string.buildString(encoding, this.numVisibleDataSets_, ':', dataStrings); } this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.DATA, data); return this.uri_.toString().length < this.uriLengthLimit_; }; /** * Computes a multi-axis data string from the given data and separators. The * general data format for each index/element in the array will be * "<arrayIndex><indexSeparator><arrayElement.join(elementSeparator)>", with * axisSeparator used between multiple elements. * @param {Object} data The data to compute the data string for, as a * sparse array of arrays. NOTE: The function uses the length of * multiAxisType_ to determine the upper bound for the outer array. * @param {string} indexSeparator The separator string inserted between each * index and the data itself, commonly a comma (,). * @param {string} elementSeparator The separator string inserted between each * element inside each sub-array in the data, if there are more than one; * commonly a comma (,). * @param {string} axisSeparator The separator string inserted between each * axis specification, if there are more than one; usually a pipe sign (|). * @return {string} The multi-axis data string. * @private */ goog.ui.ServerChart.prototype.computeMultiAxisDataString_ = function( data, indexSeparator, elementSeparator, axisSeparator) { var elementStrings = []; for (var i = 0, setLen = this.multiAxisType_.length; i < setLen; ++i) { if (data[i]) { elementStrings.push(i + indexSeparator + data[i].join(elementSeparator)); } } return elementStrings.join(axisSeparator); }; /** * Array of possible ChartServer data values * @type {string} */ goog.ui.ServerChart.CHART_VALUES = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789'; /** * Array of extended ChartServer data values * @type {string} */ goog.ui.ServerChart.CHART_VALUES_EXTENDED = goog.ui.ServerChart.CHART_VALUES + '-.'; /** * Upper bound for extended values */ goog.ui.ServerChart.EXTENDED_UPPER_BOUND = Math.pow(goog.ui.ServerChart.CHART_VALUES_EXTENDED.length, 2) - 1; /** * Converts a single number to an encoded data value suitable for ChartServer. * The TEXT encoding is the number in decimal; the SIMPLE encoding is a single * character, and the EXTENDED encoding is two characters. See * http://code.google.com/apis/chart/docs/data_formats.html for the detailed * specification of these encoding formats. * * @private * @param {?number} value The value to convert (null for a missing data point). * @param {number} minValue The minimum value (used for normalization). * @param {number} maxValue The maximum value (used for normalization). * @param {goog.ui.ServerChart.EncodingType} encoding The data encoding to use; * must not be AUTOMATIC. * @return {string} The encoded data value. */ goog.ui.ServerChart.prototype.getConvertedValue_ = function(value, minValue, maxValue, encoding) { goog.asserts.assert(minValue <= maxValue, 'minValue should be less than or equal to maxValue'); var isExtended = (encoding == goog.ui.ServerChart.EncodingType.EXTENDED); if (goog.isNull(value) || !goog.isDef(value) || isNaN(value) || value < minValue || value > maxValue) { return isExtended ? '__' : '_'; } if (encoding == goog.ui.ServerChart.EncodingType.TEXT) { return String(value); } var frac = goog.ui.ServerChart.DEFAULT_NORMALIZATION; if (maxValue > minValue) { frac = (value - minValue) / (maxValue - minValue); // Previous checks of value ensure that 0 <= frac <= 1 at this point. } if (isExtended) { var maxIndex = goog.ui.ServerChart.CHART_VALUES_EXTENDED.length; var upperBound = goog.ui.ServerChart.EXTENDED_UPPER_BOUND; var index1 = Math.floor(frac * upperBound / maxIndex); var index2 = Math.floor((frac * upperBound) % maxIndex); var extendedVals = goog.ui.ServerChart.CHART_VALUES_EXTENDED; return extendedVals.charAt(index1) + extendedVals.charAt(index2); } var index = Math.round(frac * (goog.ui.ServerChart.CHART_VALUES.length - 1)); return goog.ui.ServerChart.CHART_VALUES.charAt(index); }; /** * Creates the chd string for chartserver. * * @private * @param {Array.<number>} values An array of numbers to graph. * @param {number} minValue The minimum value (used for normalization). * @param {number} maxValue The maximum value (used for normalization). * @param {goog.ui.ServerChart.EncodingType} encoding The data encoding to use; * must not be AUTOMATIC. * @return {string} The chd string for chartserver. */ goog.ui.ServerChart.prototype.getChartServerValues_ = function(values, minValue, maxValue, encoding) { var s = []; for (var i = 0, valuesLen = values.length; i < valuesLen; ++i) { s.push(this.getConvertedValue_(values[i], minValue, maxValue, encoding)); } return s.join( this.encodingType_ == goog.ui.ServerChart.EncodingType.TEXT ? ',' : ''); }; /** * Finds the minimum value in an array and returns it. * Needed because Math.min does not handle sparse arrays the way we want. * * @param {Array.<number?>} ary An array of values. * @return {number} The minimum value. * @private */ goog.ui.ServerChart.prototype.arrayMin_ = function(ary) { var min = Infinity; for (var i = 0, aryLen = ary.length; i < aryLen; ++i) { var value = ary[i]; if (value != null && value < min) { min = value; } } return min; }; /** * Finds the maximum value in an array and returns it. * Needed because Math.max does not handle sparse arrays the way we want. * * @param {Array.<number?>} ary An array of values. * @return {number} The maximum value. * @private */ goog.ui.ServerChart.prototype.arrayMax_ = function(ary) { var max = -Infinity; for (var i = 0, aryLen = ary.length; i < aryLen; ++i) { var value = ary[i]; if (value != null && value > max) { max = value; } } return max; }; /** @override */ goog.ui.ServerChart.prototype.disposeInternal = function() { goog.ui.ServerChart.superClass_.disposeInternal.call(this); delete this.xLabels_; delete this.leftLabels_; delete this.rightLabels_; delete this.gridX_; delete this.gridY_; delete this.setColors_; delete this.setLegendTexts_; delete this.dataSets_; this.uri_ = null; delete this.minValue_; delete this.maxValue_; this.title_ = null; delete this.multiAxisType_; delete this.multiAxisLabelText_; delete this.multiAxisLabelPosition_; delete this.multiAxisRange_; delete this.multiAxisLabelStyle_; this.legend_ = null; }; /** * Event types dispatched by the ServerChart object * @enum {string} */ goog.ui.ServerChart.Event = { /** * Dispatched when the resulting URI reaches or exceeds the URI length limit. */ URI_TOO_LONG: 'uritoolong' }; /** * Class for the event dispatched on the ServerChart when the resulting URI * exceeds the URI length limit. * @constructor * @param {string} uri The overly-long URI string. * @extends {goog.events.Event} */ goog.ui.ServerChart.UriTooLongEvent = function(uri) { goog.events.Event.call(this, goog.ui.ServerChart.Event.URI_TOO_LONG); /** * The overly-long URI string. * @type {string} */ this.uri = uri; }; goog.inherits(goog.ui.ServerChart.UriTooLongEvent, goog.events.Event);
darkrsw/safe
tests/clone_detector_tests/closure-library-read-only/closure/goog/ui/serverchart.js
JavaScript
bsd-3-clause
55,051
<div class="row"> <div class="col-sm-12"> <h4><strong><?php echo CHtml::link( CHtml::encode($data->title), ['/news/news/show/', 'alias' => $data->alias] ); ?></strong></h4> </div> </div> <div class="row"> <div class="col-sm-12"> <p> <?php echo $data->short_text; ?></p> <p><?php echo CHtml::link( Yii::t('NewsModule.news', 'read...'), ['/news/news/show/', 'alias' => $data->alias], ['class' => 'btn'] ); ?></p> </div> </div> <hr>
EvgSp/yupi.loc
themes/loop_theme/views/news/news/_view.php
PHP
bsd-3-clause
588
""" Sphinx plugin to run example scripts and create a gallery page. Lightly modified from the mpld3 project. """ from __future__ import division import os import os.path as op import re import glob import token import tokenize import shutil from seaborn.external import six import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib import image if six.PY3: # Python 3 has no execfile def execfile(filename, globals=None, locals=None): with open(filename, "rb") as fp: six.exec_(compile(fp.read(), filename, 'exec'), globals, locals) RST_TEMPLATE = """ .. _{sphinx_tag}: {docstring} .. image:: {img_file} **Python source code:** :download:`[download source: {fname}]<{fname}>` .. raw:: html <div class="col-md-9"> .. literalinclude:: {fname} :lines: {end_line}- .. raw:: html </div> """ INDEX_TEMPLATE = """ .. raw:: html <style type="text/css"> .figure {{ position: relative; float: left; margin: 10px; width: 180px; height: 200px; }} .figure img {{ position: absolute; display: inline; left: 0; width: 170px; height: 170px; opacity:1.0; filter:alpha(opacity=100); /* For IE8 and earlier */ }} .figure:hover img {{ -webkit-filter: blur(3px); -moz-filter: blur(3px); -o-filter: blur(3px); -ms-filter: blur(3px); filter: blur(3px); opacity:1.0; filter:alpha(opacity=100); /* For IE8 and earlier */ }} .figure span {{ position: absolute; display: inline; left: 0; width: 170px; height: 170px; background: #000; color: #fff; visibility: hidden; opacity: 0; z-index: 100; }} .figure p {{ position: absolute; top: 45%; width: 170px; font-size: 110%; }} .figure:hover span {{ visibility: visible; opacity: .4; }} .caption {{ position: absolue; width: 180px; top: 170px; text-align: center !important; }} </style> .. _{sphinx_tag}: Example gallery =============== {toctree} {contents} .. raw:: html <div style="clear: both"></div> """ def create_thumbnail(infile, thumbfile, width=275, height=275, cx=0.5, cy=0.5, border=4): baseout, extout = op.splitext(thumbfile) im = image.imread(infile) rows, cols = im.shape[:2] x0 = int(cx * cols - .5 * width) y0 = int(cy * rows - .5 * height) xslice = slice(x0, x0 + width) yslice = slice(y0, y0 + height) thumb = im[yslice, xslice] thumb[:border, :, :3] = thumb[-border:, :, :3] = 0 thumb[:, :border, :3] = thumb[:, -border:, :3] = 0 dpi = 100 fig = plt.figure(figsize=(width / dpi, height / dpi), dpi=dpi) ax = fig.add_axes([0, 0, 1, 1], aspect='auto', frameon=False, xticks=[], yticks=[]) ax.imshow(thumb, aspect='auto', resample=True, interpolation='bilinear') fig.savefig(thumbfile, dpi=dpi) return fig def indent(s, N=4): """indent a string""" return s.replace('\n', '\n' + N * ' ') class ExampleGenerator(object): """Tools for generating an example page from a file""" def __init__(self, filename, target_dir): self.filename = filename self.target_dir = target_dir self.thumbloc = .5, .5 self.extract_docstring() with open(filename, "r") as fid: self.filetext = fid.read() outfilename = op.join(target_dir, self.rstfilename) # Only actually run it if the output RST file doesn't # exist or it was modified less recently than the example if (not op.exists(outfilename) or (op.getmtime(outfilename) < op.getmtime(filename))): self.exec_file() else: print("skipping {0}".format(self.filename)) @property def dirname(self): return op.split(self.filename)[0] @property def fname(self): return op.split(self.filename)[1] @property def modulename(self): return op.splitext(self.fname)[0] @property def pyfilename(self): return self.modulename + '.py' @property def rstfilename(self): return self.modulename + ".rst" @property def htmlfilename(self): return self.modulename + '.html' @property def pngfilename(self): pngfile = self.modulename + '.png' return "_images/" + pngfile @property def thumbfilename(self): pngfile = self.modulename + '_thumb.png' return pngfile @property def sphinxtag(self): return self.modulename @property def pagetitle(self): return self.docstring.strip().split('\n')[0].strip() @property def plotfunc(self): match = re.search(r"sns\.(.+plot)\(", self.filetext) if match: return match.group(1) match = re.search(r"sns\.(.+map)\(", self.filetext) if match: return match.group(1) match = re.search(r"sns\.(.+Grid)\(", self.filetext) if match: return match.group(1) return "" def extract_docstring(self): """ Extract a module-level docstring """ lines = open(self.filename).readlines() start_row = 0 if lines[0].startswith('#!'): lines.pop(0) start_row = 1 docstring = '' first_par = '' line_iter = lines.__iter__() tokens = tokenize.generate_tokens(lambda: next(line_iter)) for tok_type, tok_content, _, (erow, _), _ in tokens: tok_type = token.tok_name[tok_type] if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'): continue elif tok_type == 'STRING': docstring = eval(tok_content) # If the docstring is formatted with several paragraphs, # extract the first one: paragraphs = '\n'.join(line.rstrip() for line in docstring.split('\n') ).split('\n\n') if len(paragraphs) > 0: first_par = paragraphs[0] break thumbloc = None for i, line in enumerate(docstring.split("\n")): m = re.match(r"^_thumb: (\.\d+),\s*(\.\d+)", line) if m: thumbloc = float(m.group(1)), float(m.group(2)) break if thumbloc is not None: self.thumbloc = thumbloc docstring = "\n".join([l for l in docstring.split("\n") if not l.startswith("_thumb")]) self.docstring = docstring self.short_desc = first_par self.end_line = erow + 1 + start_row def exec_file(self): print("running {0}".format(self.filename)) plt.close('all') my_globals = {'pl': plt, 'plt': plt} execfile(self.filename, my_globals) fig = plt.gcf() fig.canvas.draw() pngfile = op.join(self.target_dir, self.pngfilename) thumbfile = op.join("example_thumbs", self.thumbfilename) self.html = "<img src=../%s>" % self.pngfilename fig.savefig(pngfile, dpi=75, bbox_inches="tight") cx, cy = self.thumbloc create_thumbnail(pngfile, thumbfile, cx=cx, cy=cy) def toctree_entry(self): return " ./%s\n\n" % op.splitext(self.htmlfilename)[0] def contents_entry(self): return (".. raw:: html\n\n" " <div class='figure align-center'>\n" " <a href=./{0}>\n" " <img src=../_static/{1}>\n" " <span class='figure-label'>\n" " <p>{2}</p>\n" " </span>\n" " </a>\n" " </div>\n\n" "\n\n" "".format(self.htmlfilename, self.thumbfilename, self.plotfunc)) def main(app): static_dir = op.join(app.builder.srcdir, '_static') target_dir = op.join(app.builder.srcdir, 'examples') image_dir = op.join(app.builder.srcdir, 'examples/_images') thumb_dir = op.join(app.builder.srcdir, "example_thumbs") source_dir = op.abspath(op.join(app.builder.srcdir, '..', 'examples')) if not op.exists(static_dir): os.makedirs(static_dir) if not op.exists(target_dir): os.makedirs(target_dir) if not op.exists(image_dir): os.makedirs(image_dir) if not op.exists(thumb_dir): os.makedirs(thumb_dir) if not op.exists(source_dir): os.makedirs(source_dir) banner_data = [] toctree = ("\n\n" ".. toctree::\n" " :hidden:\n\n") contents = "\n\n" # Write individual example files for filename in glob.glob(op.join(source_dir, "*.py")): ex = ExampleGenerator(filename, target_dir) banner_data.append({"title": ex.pagetitle, "url": op.join('examples', ex.htmlfilename), "thumb": op.join(ex.thumbfilename)}) shutil.copyfile(filename, op.join(target_dir, ex.pyfilename)) output = RST_TEMPLATE.format(sphinx_tag=ex.sphinxtag, docstring=ex.docstring, end_line=ex.end_line, fname=ex.pyfilename, img_file=ex.pngfilename) with open(op.join(target_dir, ex.rstfilename), 'w') as f: f.write(output) toctree += ex.toctree_entry() contents += ex.contents_entry() if len(banner_data) < 10: banner_data = (4 * banner_data)[:10] # write index file index_file = op.join(target_dir, 'index.rst') with open(index_file, 'w') as index: index.write(INDEX_TEMPLATE.format(sphinx_tag="example_gallery", toctree=toctree, contents=contents)) def setup(app): app.connect('builder-inited', main)
phobson/seaborn
doc/sphinxext/gallery_generator.py
Python
bsd-3-clause
10,385
/* * Copyright (c) 2016 Goldman Sachs. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v. 1.0 which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. */ package org.eclipse.collections.impl.lazy.parallel.set; import org.eclipse.collections.api.ParallelIterable; import org.eclipse.collections.api.annotation.Beta; import org.eclipse.collections.api.block.function.Function; import org.eclipse.collections.api.block.function.Function2; import org.eclipse.collections.api.block.predicate.Predicate; import org.eclipse.collections.api.block.predicate.Predicate2; import org.eclipse.collections.api.multimap.set.MutableSetMultimap; import org.eclipse.collections.api.multimap.set.UnsortedSetMultimap; import org.eclipse.collections.api.set.ParallelUnsortedSetIterable; import org.eclipse.collections.impl.block.factory.Functions; import org.eclipse.collections.impl.block.factory.Predicates; import org.eclipse.collections.impl.lazy.parallel.AbstractParallelIterable; import org.eclipse.collections.impl.multimap.set.SynchronizedPutUnifiedSetMultimap; @Beta public abstract class AbstractParallelUnsortedSetIterable<T, B extends UnsortedSetBatch<T>> extends AbstractParallelIterable<T, B> implements ParallelUnsortedSetIterable<T> { @Override protected boolean isOrdered() { return false; } @Override public ParallelUnsortedSetIterable<T> asUnique() { return this; } @Override public ParallelUnsortedSetIterable<T> select(Predicate<? super T> predicate) { return new ParallelSelectUnsortedSetIterable<>(this, predicate); } @Override public <P> ParallelUnsortedSetIterable<T> selectWith(Predicate2<? super T, ? super P> predicate, P parameter) { return this.select(Predicates.bind(predicate, parameter)); } @Override public <S> ParallelUnsortedSetIterable<S> selectInstancesOf(Class<S> clazz) { return (ParallelUnsortedSetIterable<S>) this.select(Predicates.instanceOf(clazz)); } @Override public ParallelUnsortedSetIterable<T> reject(Predicate<? super T> predicate) { return this.select(Predicates.not(predicate)); } @Override public <P> ParallelUnsortedSetIterable<T> rejectWith(Predicate2<? super T, ? super P> predicate, P parameter) { return this.reject(Predicates.bind(predicate, parameter)); } @Override public <V> ParallelIterable<V> collect(Function<? super T, ? extends V> function) { return new ParallelCollectIterable<>(this, function); } @Override public <P, V> ParallelIterable<V> collectWith(Function2<? super T, ? super P, ? extends V> function, P parameter) { return this.collect(Functions.bind(function, parameter)); } @Override public <V> ParallelIterable<V> collectIf(Predicate<? super T> predicate, Function<? super T, ? extends V> function) { return this.select(predicate).collect(function); } @Override public <V> ParallelIterable<V> flatCollect(Function<? super T, ? extends Iterable<V>> function) { return new ParallelFlatCollectIterable<>(this, function); } @Override public <V> UnsortedSetMultimap<V, T> groupBy(Function<? super T, ? extends V> function) { MutableSetMultimap<V, T> result = SynchronizedPutUnifiedSetMultimap.newMultimap(); this.forEach(each -> { V key = function.valueOf(each); result.put(key, each); }); return result; } @Override public <V> UnsortedSetMultimap<V, T> groupByEach(Function<? super T, ? extends Iterable<V>> function) { MutableSetMultimap<V, T> result = SynchronizedPutUnifiedSetMultimap.newMultimap(); this.forEach(each -> { Iterable<V> keys = function.valueOf(each); for (V key : keys) { result.put(key, each); } }); return result; } }
bhav0904/eclipse-collections
eclipse-collections/src/main/java/org/eclipse/collections/impl/lazy/parallel/set/AbstractParallelUnsortedSetIterable.java
Java
bsd-3-clause
4,263
//= require_self //= require spree/backend/handlebars_extensions //= require spree/backend/variant_autocomplete //= require spree/backend/taxon_autocomplete //= require spree/backend/option_type_autocomplete //= require spree/backend/user_picker //= require spree/backend/product_picker //= require spree/backend/option_value_picker //= require spree/backend/taxons //= require spree/backend/highlight_negative_numbers /** This is a collection of javascript functions and whatnot under the spree namespace that do stuff we find helpful. Hopefully, this will evolve into a propper class. **/ Spree.ready(function() { // Highlight hovered table column $('table').on("mouseenter", 'td.actions a, td.actions button', function(){ var tr = $(this).closest('tr'); var klass = 'highlight action-' + $(this).data('action') tr.addClass(klass) var observer = new MutationObserver(function(mutations) { tr.removeClass(klass); this.disconnect(); }); observer.observe(tr.get(0), { childList: true }); // Using .one() instead of .on() prevents multiple callbacks to be attached // to this event if mouseentered multiple times. $(this).one("mouseleave", function() { tr.removeClass(klass); observer.disconnect(); }); }); }); $.fn.visible = function(cond) { this[cond ? 'show' : 'hide' ]() }; // Apply to individual radio button that makes another element visible when checked $.fn.radioControlsVisibilityOfElement = function(dependentElementSelector){ if(!this.get(0)){ return } var showValue = this.get(0).value; var radioGroup = $("input[name='" + this.get(0).name + "']"); radioGroup.each(function(){ $(this).click(function(){ $(dependentElementSelector).visible(this.checked && this.value == showValue) }); if(this.checked){ this.click() } }); } Spree.ready(function(){ var uniqueId = 1; $('.spree_add_fields').click(function() { var target = $(this).data("target"); var new_table_row = $(target + ' tr:visible:last').clone(); var new_id = new Date().getTime() + (uniqueId++); new_table_row.find("input, select").each(function () { var el = $(this); el.val(""); // Replace last occurrence of a number el.prop("id", el.prop("id").replace(/\d+(?=[^\d]*$)/, new_id)) el.prop("name", el.prop("name").replace(/\d+(?=[^\d]*$)/, new_id)) }) // When cloning a new row, set the href of all icons to be an empty "#" // This is so that clicking on them does not perform the actions for the // duplicated row new_table_row.find("a").each(function () { var el = $(this); el.prop('href', '#'); }) $(target).prepend(new_table_row); }) $('body').on('click', '.delete-resource', function() { var el = $(this); if (confirm(el.data("confirm"))) { Spree.ajax({ type: 'POST', url: $(this).prop("href"), data: { _method: 'delete', }, dataType: 'script', success: function(response) { el.parents("tr").fadeOut('hide', function() { $(this).remove(); }); }, error: function(response, textStatus, errorThrown) { show_flash('error', response.responseText); } }); } return false; }); $('body').on('click', 'a.spree_remove_fields', function() { var el = $(this); el.prev("input[type=hidden]").val("1"); el.closest(".fields").hide(); if (el.prop("href").substr(-1) == '#') { el.parents("tr").fadeOut('hide'); }else if (el.prop("href")) { Spree.ajax({ type: 'POST', url: el.prop("href"), data: { _method: 'delete', }, success: function(response) { el.parents("tr").fadeOut('hide'); }, error: function(response, textStatus, errorThrown) { show_flash('error', response.responseText); } }) } return false; }); window.Spree.advanceOrder = function() { Spree.ajax({ type: "PUT", async: false, data: { token: Spree.api_key }, url: Spree.routes.checkouts_api + "/" + window.order_number + "/advance" }).done(function() { window.location.reload(); }); } });
pervino/solidus
backend/app/assets/javascripts/spree/backend/admin.js
JavaScript
bsd-3-clause
4,270
from functools import update_wrapper from django.http import Http404, HttpResponseRedirect from django.contrib.admin import ModelAdmin, actions from django.contrib.admin.forms import AdminAuthenticationForm from django.contrib.auth import logout as auth_logout, REDIRECT_FIELD_NAME from django.contrib.contenttypes import views as contenttype_views from django.views.decorators.csrf import csrf_protect from django.db.models.base import ModelBase from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import reverse, NoReverseMatch from django.template.response import TemplateResponse from django.utils import six from django.utils.text import capfirst from django.utils.translation import ugettext as _ from django.views.decorators.cache import never_cache from django.conf import settings LOGIN_FORM_KEY = 'this_is_the_login_form' class AlreadyRegistered(Exception): pass class NotRegistered(Exception): pass class AdminSite(object): """ An AdminSite object encapsulates an instance of the Django admin application, ready to be hooked in to your URLconf. Models are registered with the AdminSite using the register() method, and the get_urls() method can then be used to access Django view functions that present a full admin interface for the collection of registered models. """ login_form = None index_template = None app_index_template = None login_template = None logout_template = None password_change_template = None password_change_done_template = None def __init__(self, name='admin', app_name='admin'): self._registry = {} # model_class class -> admin_class instance self.name = name self.app_name = app_name self._actions = {'delete_selected': actions.delete_selected} self._global_actions = self._actions.copy() def register(self, model_or_iterable, admin_class=None, **options): """ Registers the given model(s) with the given admin class. The model(s) should be Model classes, not instances. If an admin class isn't given, it will use ModelAdmin (the default admin options). If keyword arguments are given -- e.g., list_display -- they'll be applied as options to the admin class. If a model is already registered, this will raise AlreadyRegistered. If a model is abstract, this will raise ImproperlyConfigured. """ if not admin_class: admin_class = ModelAdmin # Don't import the humongous validation code unless required if admin_class and settings.DEBUG: from django.contrib.admin.validation import validate else: validate = lambda model, adminclass: None if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if model._meta.abstract: raise ImproperlyConfigured('The model %s is abstract, so it ' 'cannot be registered with admin.' % model.__name__) if model in self._registry: raise AlreadyRegistered('The model %s is already registered' % model.__name__) # Ignore the registration if the model has been # swapped out. if not model._meta.swapped: # If we got **options then dynamically construct a subclass of # admin_class with those **options. if options: # For reasons I don't quite understand, without a __module__ # the created class appears to "live" in the wrong place, # which causes issues later on. options['__module__'] = __name__ admin_class = type("%sAdmin" % model.__name__, (admin_class,), options) # Validate (which might be a no-op) validate(admin_class, model) # Instantiate the admin class to save in the registry self._registry[model] = admin_class(model, self) def unregister(self, model_or_iterable): """ Unregisters the given model(s). If a model isn't already registered, this will raise NotRegistered. """ if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if model not in self._registry: raise NotRegistered('The model %s is not registered' % model.__name__) del self._registry[model] def add_action(self, action, name=None): """ Register an action to be available globally. """ name = name or action.__name__ self._actions[name] = action self._global_actions[name] = action def disable_action(self, name): """ Disable a globally-registered action. Raises KeyError for invalid names. """ del self._actions[name] def get_action(self, name): """ Explicitly get a registered global action whether it's enabled or not. Raises KeyError for invalid names. """ return self._global_actions[name] @property def actions(self): """ Get all the enabled actions as an iterable of (name, func). """ return six.iteritems(self._actions) def has_permission(self, request): """ Returns True if the given HttpRequest has permission to view *at least one* page in the admin site. """ return request.user.is_active and request.user.is_staff def check_dependencies(self): """ Check that all things needed to run the admin have been correctly installed. The default implementation checks that LogEntry, ContentType and the auth context processor are installed. """ from django.contrib.admin.models import LogEntry from django.contrib.contenttypes.models import ContentType if not LogEntry._meta.installed: raise ImproperlyConfigured("Put 'django.contrib.admin' in your " "INSTALLED_APPS setting in order to use the admin application.") if not ContentType._meta.installed: raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in " "your INSTALLED_APPS setting in order to use the admin application.") if not ('django.contrib.auth.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS or 'django.core.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS): raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' " "in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.") def admin_view(self, view, cacheable=False): """ Decorator to create an admin view attached to this ``AdminSite``. This wraps the view and provides permission checking by calling ``self.has_permission``. You'll want to use this from within ``AdminSite.get_urls()``: class MyAdminSite(AdminSite): def get_urls(self): from django.conf.urls import patterns, url urls = super(MyAdminSite, self).get_urls() urls += patterns('', url(r'^my_view/$', self.admin_view(some_view)) ) return urls By default, admin_views are marked non-cacheable using the ``never_cache`` decorator. If the view can be safely cached, set cacheable=True. """ def inner(request, *args, **kwargs): if LOGIN_FORM_KEY in request.POST and request.user.is_authenticated(): auth_logout(request) if not self.has_permission(request): if request.path == reverse('admin:logout', current_app=self.name): index_path = reverse('admin:index', current_app=self.name) return HttpResponseRedirect(index_path) return self.login(request) return view(request, *args, **kwargs) if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view) def get_urls(self): from django.conf.urls import patterns, url, include if settings.DEBUG: self.check_dependencies() def wrap(view, cacheable=False): def wrapper(*args, **kwargs): return self.admin_view(view, cacheable)(*args, **kwargs) return update_wrapper(wrapper, view) # Admin-site-wide views. urlpatterns = patterns('', url(r'^$', wrap(self.index), name='index'), url(r'^logout/$', wrap(self.logout), name='logout'), url(r'^password_change/$', wrap(self.password_change, cacheable=True), name='password_change'), url(r'^password_change/done/$', wrap(self.password_change_done, cacheable=True), name='password_change_done'), url(r'^jsi18n/$', wrap(self.i18n_javascript, cacheable=True), name='jsi18n'), url(r'^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$', wrap(contenttype_views.shortcut), name='view_on_site'), url(r'^(?P<app_label>\w+)/$', wrap(self.app_index), name='app_list') ) # Add in each model's views. for model, model_admin in six.iteritems(self._registry): urlpatterns += patterns('', url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)) ) return urlpatterns @property def urls(self): return self.get_urls(), self.app_name, self.name def password_change(self, request): """ Handles the "change password" task -- both form display and validation. """ from django.contrib.auth.views import password_change url = reverse('admin:password_change_done', current_app=self.name) defaults = { 'current_app': self.name, 'post_change_redirect': url } if self.password_change_template is not None: defaults['template_name'] = self.password_change_template return password_change(request, **defaults) def password_change_done(self, request, extra_context=None): """ Displays the "success" page after a password change. """ from django.contrib.auth.views import password_change_done defaults = { 'current_app': self.name, 'extra_context': extra_context or {}, } if self.password_change_done_template is not None: defaults['template_name'] = self.password_change_done_template return password_change_done(request, **defaults) def i18n_javascript(self, request): """ Displays the i18n JavaScript that the Django admin requires. This takes into account the USE_I18N setting. If it's set to False, the generated JavaScript will be leaner and faster. """ if settings.USE_I18N: from django.views.i18n import javascript_catalog else: from django.views.i18n import null_javascript_catalog as javascript_catalog return javascript_catalog(request, packages=['django.conf', 'django.contrib.admin']) @never_cache def logout(self, request, extra_context=None): """ Logs out the user for the given HttpRequest. This should *not* assume the user is already logged in. """ from django.contrib.auth.views import logout defaults = { 'current_app': self.name, 'extra_context': extra_context or {}, } if self.logout_template is not None: defaults['template_name'] = self.logout_template return logout(request, **defaults) @never_cache def login(self, request, extra_context=None): """ Displays the login form for the given HttpRequest. """ from django.contrib.auth.views import login context = { 'title': _('Log in'), 'app_path': request.get_full_path(), REDIRECT_FIELD_NAME: request.get_full_path(), } context.update(extra_context or {}) defaults = { 'extra_context': context, 'current_app': self.name, 'authentication_form': self.login_form or AdminAuthenticationForm, 'template_name': self.login_template or 'admin/login.html', } return login(request, **defaults) @never_cache def index(self, request, extra_context=None): """ Displays the main admin index page, which lists all of the installed apps that have been registered in this site. """ app_dict = {} user = request.user for model, model_admin in self._registry.items(): app_label = model._meta.app_label has_module_perms = user.has_module_perms(app_label) if has_module_perms: perms = model_admin.get_model_perms(request) # Check whether user has any perm for this module. # If so, add the module to the model_list. if True in perms.values(): info = (app_label, model._meta.model_name) model_dict = { 'name': capfirst(model._meta.verbose_name_plural), 'object_name': model._meta.object_name, 'perms': perms, } if perms.get('change', False): try: model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name) except NoReverseMatch: pass if perms.get('add', False): try: model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=self.name) except NoReverseMatch: pass if app_label in app_dict: app_dict[app_label]['models'].append(model_dict) else: app_dict[app_label] = { 'name': app_label.title(), 'app_label': app_label, 'app_url': reverse('admin:app_list', kwargs={'app_label': app_label}, current_app=self.name), 'has_module_perms': has_module_perms, 'models': [model_dict], } # Sort the apps alphabetically. app_list = list(six.itervalues(app_dict)) app_list.sort(key=lambda x: x['name']) # Sort the models alphabetically within each app. for app in app_list: app['models'].sort(key=lambda x: x['name']) context = { 'title': _('Site administration'), 'app_list': app_list, } context.update(extra_context or {}) return TemplateResponse(request, self.index_template or 'admin/index.html', context, current_app=self.name) def app_index(self, request, app_label, extra_context=None): user = request.user has_module_perms = user.has_module_perms(app_label) app_dict = {} for model, model_admin in self._registry.items(): if app_label == model._meta.app_label: if has_module_perms: perms = model_admin.get_model_perms(request) # Check whether user has any perm for this module. # If so, add the module to the model_list. if True in perms.values(): info = (app_label, model._meta.model_name) model_dict = { 'name': capfirst(model._meta.verbose_name_plural), 'object_name': model._meta.object_name, 'perms': perms, } if perms.get('change', False): try: model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name) except NoReverseMatch: pass if perms.get('add', False): try: model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=self.name) except NoReverseMatch: pass if app_dict: app_dict['models'].append(model_dict), else: # First time around, now that we know there's # something to display, add in the necessary meta # information. app_dict = { 'name': app_label.title(), 'app_label': app_label, 'app_url': '', 'has_module_perms': has_module_perms, 'models': [model_dict], } if not app_dict: raise Http404('The requested admin page does not exist.') # Sort the models alphabetically within each app. app_dict['models'].sort(key=lambda x: x['name']) context = { 'title': _('%s administration') % capfirst(app_label), 'app_list': [app_dict], } context.update(extra_context or {}) return TemplateResponse(request, self.app_index_template or [ 'admin/%s/app_index.html' % app_label, 'admin/app_index.html' ], context, current_app=self.name) # This global object represents the default admin site, for the common case. # You can instantiate AdminSite in your own code to create a custom admin site. site = AdminSite()
postrational/django
django/contrib/admin/sites.py
Python
bsd-3-clause
18,932
# Copyright (C) 2010 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest from webkitpy.common.net.buildbot import Builder from webkitpy.common.system.outputcapture import OutputCapture from webkitpy.thirdparty.mock import Mock from webkitpy.tool.bot.sheriff import Sheriff from webkitpy.tool.mocktool import MockTool class MockSheriffBot(object): name = "mock-sheriff-bot" watchers = [ "watcher@example.com", ] def run_webkit_patch(self, args): return "Created bug https://bugs.webkit.org/show_bug.cgi?id=36936\n" class SheriffTest(unittest.TestCase): def test_post_blame_comment_on_bug(self): def run(): sheriff = Sheriff(MockTool(), MockSheriffBot()) builders = [ Builder("Foo", None), Builder("Bar", None), ] commit_info = Mock() commit_info.bug_id = lambda: None commit_info.revision = lambda: 4321 # Should do nothing with no bug_id sheriff.post_blame_comment_on_bug(commit_info, builders, []) sheriff.post_blame_comment_on_bug(commit_info, builders, ["mock-test-1", "mock-test-2"]) # Should try to post a comment to the bug, but MockTool.bugs does nothing. commit_info.bug_id = lambda: 1234 sheriff.post_blame_comment_on_bug(commit_info, builders, []) sheriff.post_blame_comment_on_bug(commit_info, builders, ["mock-test-1"]) sheriff.post_blame_comment_on_bug(commit_info, builders, ["mock-test-1", "mock-test-2"]) expected_stderr = u"""MOCK bug comment: bug_id=1234, cc=['watcher@example.com'] --- Begin comment --- http://trac.webkit.org/changeset/4321 might have broken Foo and Bar --- End comment --- MOCK bug comment: bug_id=1234, cc=['watcher@example.com'] --- Begin comment --- http://trac.webkit.org/changeset/4321 might have broken Foo and Bar The following tests are not passing: mock-test-1 --- End comment --- MOCK bug comment: bug_id=1234, cc=['watcher@example.com'] --- Begin comment --- http://trac.webkit.org/changeset/4321 might have broken Foo and Bar The following tests are not passing: mock-test-1 mock-test-2 --- End comment --- """ OutputCapture().assert_outputs(self, run, expected_stderr=expected_stderr)
leighpauls/k2cro4
third_party/WebKit/Tools/Scripts/webkitpy/tool/bot/sheriff_unittest.py
Python
bsd-3-clause
3,776
/* * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/pacing/bitrate_prober.h" #include <assert.h> #include <limits> #include <sstream> #include "webrtc/system_wrappers/interface/logging.h" namespace webrtc { namespace { int ComputeDeltaFromBitrate(size_t packet_size, int bitrate_bps) { assert(bitrate_bps > 0); // Compute the time delta needed to send packet_size bytes at bitrate_bps // bps. Result is in milliseconds. return static_cast<int>(1000ll * static_cast<int64_t>(packet_size) * 8ll / bitrate_bps); } } // namespace BitrateProber::BitrateProber() : probing_state_(kDisabled), packet_size_last_send_(0), time_last_send_ms_(-1) { } void BitrateProber::SetEnabled(bool enable) { if (enable) { if (probing_state_ == kDisabled) { probing_state_ = kAllowedToProbe; LOG(LS_INFO) << "Initial bandwidth probing enabled"; } } else { probing_state_ = kDisabled; LOG(LS_INFO) << "Initial bandwidth probing disabled"; } } bool BitrateProber::IsProbing() const { return probing_state_ == kProbing; } void BitrateProber::MaybeInitializeProbe(int bitrate_bps) { if (probing_state_ != kAllowedToProbe) return; probe_bitrates_.clear(); // Max number of packets used for probing. const int kMaxNumProbes = 2; const int kPacketsPerProbe = 5; const float kProbeBitrateMultipliers[kMaxNumProbes] = {3, 6}; int bitrates_bps[kMaxNumProbes]; std::stringstream bitrate_log; bitrate_log << "Start probing for bandwidth, bitrates:"; for (int i = 0; i < kMaxNumProbes; ++i) { bitrates_bps[i] = kProbeBitrateMultipliers[i] * bitrate_bps; bitrate_log << " " << bitrates_bps[i]; // We need one extra to get 5 deltas for the first probe. if (i == 0) probe_bitrates_.push_back(bitrates_bps[i]); for (int j = 0; j < kPacketsPerProbe; ++j) probe_bitrates_.push_back(bitrates_bps[i]); } bitrate_log << ", num packets: " << probe_bitrates_.size(); LOG(LS_INFO) << bitrate_log.str().c_str(); probing_state_ = kProbing; } int BitrateProber::TimeUntilNextProbe(int64_t now_ms) { if (probing_state_ != kDisabled && probe_bitrates_.empty()) { probing_state_ = kWait; } if (probe_bitrates_.empty()) { // No probe started, or waiting for next probe. return -1; } int64_t elapsed_time_ms = now_ms - time_last_send_ms_; // We will send the first probe packet immediately if no packet has been // sent before. int time_until_probe_ms = 0; if (packet_size_last_send_ > 0 && probing_state_ == kProbing) { int next_delta_ms = ComputeDeltaFromBitrate(packet_size_last_send_, probe_bitrates_.front()); time_until_probe_ms = next_delta_ms - elapsed_time_ms; // There is no point in trying to probe with less than 1 ms between packets // as it essentially means trying to probe at infinite bandwidth. const int kMinProbeDeltaMs = 1; // If we have waited more than 3 ms for a new packet to probe with we will // consider this probing session over. const int kMaxProbeDelayMs = 3; if (next_delta_ms < kMinProbeDeltaMs || time_until_probe_ms < -kMaxProbeDelayMs) { // We currently disable probing after the first probe, as we only want // to probe at the beginning of a connection. We should set this to // kWait if we later want to probe periodically. probing_state_ = kWait; LOG(LS_INFO) << "Next delta too small, stop probing."; time_until_probe_ms = 0; } } return time_until_probe_ms; } void BitrateProber::PacketSent(int64_t now_ms, size_t packet_size) { assert(packet_size > 0); packet_size_last_send_ = packet_size; time_last_send_ms_ = now_ms; if (probing_state_ != kProbing) return; if (!probe_bitrates_.empty()) probe_bitrates_.pop_front(); } } // namespace webrtc
sgraham/nope
third_party/webrtc/modules/pacing/bitrate_prober.cc
C++
bsd-3-clause
4,240
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Threading; using OpenSim.Framework; using OpenMetaverse; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory { /// <summary> /// Cache root and system inventory folders to reduce number of potentially remote inventory calls and associated holdups. /// </summary> public class InventoryCache { private const double CACHE_EXPIRATION_SECONDS = 3600.0; // 1 hour private static ExpiringCache<UUID, InventoryFolderBase> m_RootFolders = new ExpiringCache<UUID, InventoryFolderBase>(); private static ExpiringCache<UUID, Dictionary<FolderType, InventoryFolderBase>> m_FolderTypes = new ExpiringCache<UUID, Dictionary<FolderType, InventoryFolderBase>>(); private static ExpiringCache<UUID, InventoryCollection> m_Inventories = new ExpiringCache<UUID, InventoryCollection>(); public void Cache(UUID userID, InventoryFolderBase root) { m_RootFolders.AddOrUpdate(userID, root, CACHE_EXPIRATION_SECONDS); } public InventoryFolderBase GetRootFolder(UUID userID) { InventoryFolderBase root = null; if (m_RootFolders.TryGetValue(userID, out root)) return root; return null; } public void Cache(UUID userID, FolderType type, InventoryFolderBase folder) { Dictionary<FolderType, InventoryFolderBase> ff = null; if (!m_FolderTypes.TryGetValue(userID, out ff)) { ff = new Dictionary<FolderType, InventoryFolderBase>(); m_FolderTypes.Add(userID, ff, CACHE_EXPIRATION_SECONDS); } // We need to lock here since two threads could potentially retrieve the same dictionary // and try to add a folder for that type simultaneously. Dictionary<>.Add() is not described as thread-safe in the SDK // even if the folders are identical. lock (ff) { if (!ff.ContainsKey(type)) ff.Add(type, folder); } } public InventoryFolderBase GetFolderForType(UUID userID, FolderType type) { Dictionary<FolderType, InventoryFolderBase> ff = null; if (m_FolderTypes.TryGetValue(userID, out ff)) { InventoryFolderBase f = null; lock (ff) { if (ff.TryGetValue(type, out f)) return f; } } return null; } public void Cache(UUID userID, InventoryCollection inv) { m_Inventories.AddOrUpdate(userID, inv, 120); } public InventoryCollection GetFolderContent(UUID userID, UUID folderID) { InventoryCollection inv = null; InventoryCollection c; if (m_Inventories.TryGetValue(userID, out inv)) { c = new InventoryCollection(); c.OwnerID = userID; c.Folders = inv.Folders.FindAll(delegate(InventoryFolderBase f) { return f.ParentID == folderID; }); c.Items = inv.Items.FindAll(delegate(InventoryItemBase i) { return i.Folder == folderID; }); return c; } return null; } public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID) { InventoryCollection inv = null; if (m_Inventories.TryGetValue(userID, out inv)) { List<InventoryItemBase> items = inv.Items.FindAll(delegate(InventoryItemBase i) { return i.Folder == folderID; }); return items; } return null; } } }
OpenSimian/opensimulator
OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/InventoryCache.cs
C#
bsd-3-clause
5,585
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\rest; use Yii; use yii\base\Arrayable; use yii\base\Component; use yii\base\Model; use yii\data\DataProviderInterface; use yii\data\Pagination; use yii\helpers\ArrayHelper; use yii\web\Link; use yii\web\Request; use yii\web\Response; /** * Serializer converts resource objects and collections into array representation. * * Serializer is mainly used by REST controllers to convert different objects into array representation * so that they can be further turned into different formats, such as JSON, XML, by response formatters. * * The default implementation handles resources as [[Model]] objects and collections as objects * implementing [[DataProviderInterface]]. You may override [[serialize()]] to handle more types. * * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */ class Serializer extends Component { /** * @var string the name of the query parameter containing the information about which fields should be returned * for a [[Model]] object. If the parameter is not provided or empty, the default set of fields as defined * by [[Model::fields()]] will be returned. */ public $fieldsParam = 'fields'; /** * @var string the name of the query parameter containing the information about which fields should be returned * in addition to those listed in [[fieldsParam]] for a resource object. */ public $expandParam = 'expand'; /** * @var string the name of the HTTP header containing the information about total number of data items. * This is used when serving a resource collection with pagination. */ public $totalCountHeader = 'X-Pagination-Total-Count'; /** * @var string the name of the HTTP header containing the information about total number of pages of data. * This is used when serving a resource collection with pagination. */ public $pageCountHeader = 'X-Pagination-Page-Count'; /** * @var string the name of the HTTP header containing the information about the current page number (1-based). * This is used when serving a resource collection with pagination. */ public $currentPageHeader = 'X-Pagination-Current-Page'; /** * @var string the name of the HTTP header containing the information about the number of data items in each page. * This is used when serving a resource collection with pagination. */ public $perPageHeader = 'X-Pagination-Per-Page'; /** * @var string the name of the envelope (e.g. `items`) for returning the resource objects in a collection. * This is used when serving a resource collection. When this is set and pagination is enabled, the serializer * will return a collection in the following format: * * ```php * [ * 'items' => [...], // assuming collectionEnvelope is "items" * '_links' => { // pagination links as returned by Pagination::getLinks() * 'self' => '...', * 'next' => '...', * 'last' => '...', * }, * '_meta' => { // meta information as returned by Pagination::toArray() * 'totalCount' => 100, * 'pageCount' => 5, * 'currentPage' => 1, * 'perPage' => 20, * }, * ] * ``` * * If this property is not set, the resource arrays will be directly returned without using envelope. * The pagination information as shown in `_links` and `_meta` can be accessed from the response HTTP headers. */ public $collectionEnvelope; /** * @var string the name of the envelope (e.g. `_links`) for returning the links objects. * It takes effect only, if `collectionEnvelope` is set. * @since 2.0.4 */ public $linksEnvelope = '_links'; /** * @var string the name of the envelope (e.g. `_meta`) for returning the pagination object. * It takes effect only, if `collectionEnvelope` is set. * @since 2.0.4 */ public $metaEnvelope = '_meta'; /** * @var Request the current request. If not set, the `request` application component will be used. */ public $request; /** * @var Response the response to be sent. If not set, the `response` application component will be used. */ public $response; /** * @var bool whether to preserve array keys when serializing collection data. * Set this to `true` to allow serialization of a collection as a JSON object where array keys are * used to index the model objects. The default is to serialize all collections as array, regardless * of how the array is indexed. * @see serializeDataProvider() * @since 2.0.10 */ public $preserveKeys = false; /** * {@inheritdoc} */ public function init() { if ($this->request === null) { $this->request = Yii::$app->getRequest(); } if ($this->response === null) { $this->response = Yii::$app->getResponse(); } } /** * Serializes the given data into a format that can be easily turned into other formats. * This method mainly converts the objects of recognized types into array representation. * It will not do conversion for unknown object types or non-object data. * The default implementation will handle [[Model]], [[DataProviderInterface]] and [\JsonSerializable](https://www.php.net/manual/en/class.jsonserializable.php). * You may override this method to support more object types. * @param mixed $data the data to be serialized. * @return mixed the converted data. */ public function serialize($data) { if ($data instanceof Model && $data->hasErrors()) { return $this->serializeModelErrors($data); } elseif ($data instanceof \JsonSerializable) { return $data->jsonSerialize(); } elseif ($data instanceof Arrayable) { return $this->serializeModel($data); } elseif ($data instanceof DataProviderInterface) { return $this->serializeDataProvider($data); } elseif (is_array($data)) { $serializedArray = []; foreach ($data as $key => $value) { $serializedArray[$key] = $this->serialize($value); } return $serializedArray; } return $data; } /** * @return array the names of the requested fields. The first element is an array * representing the list of default fields requested, while the second element is * an array of the extra fields requested in addition to the default fields. * @see Model::fields() * @see Model::extraFields() */ protected function getRequestedFields() { $fields = $this->request->get($this->fieldsParam); $expand = $this->request->get($this->expandParam); return [ is_string($fields) ? preg_split('/\s*,\s*/', $fields, -1, PREG_SPLIT_NO_EMPTY) : [], is_string($expand) ? preg_split('/\s*,\s*/', $expand, -1, PREG_SPLIT_NO_EMPTY) : [], ]; } /** * Serializes a data provider. * @param DataProviderInterface $dataProvider * @return array the array representation of the data provider. */ protected function serializeDataProvider($dataProvider) { if ($this->preserveKeys) { $models = $dataProvider->getModels(); } else { $models = array_values($dataProvider->getModels()); } $models = $this->serializeModels($models); if (($pagination = $dataProvider->getPagination()) !== false) { $this->addPaginationHeaders($pagination); } if ($this->request->getIsHead()) { return null; } elseif ($this->collectionEnvelope === null) { return $models; } $result = [ $this->collectionEnvelope => $models, ]; if ($pagination !== false) { return array_merge($result, $this->serializePagination($pagination)); } return $result; } /** * Serializes a pagination into an array. * @param Pagination $pagination * @return array the array representation of the pagination * @see addPaginationHeaders() */ protected function serializePagination($pagination) { return [ $this->linksEnvelope => Link::serialize($pagination->getLinks(true)), $this->metaEnvelope => [ 'totalCount' => $pagination->totalCount, 'pageCount' => $pagination->getPageCount(), 'currentPage' => $pagination->getPage() + 1, 'perPage' => $pagination->getPageSize(), ], ]; } /** * Adds HTTP headers about the pagination to the response. * @param Pagination $pagination */ protected function addPaginationHeaders($pagination) { $links = []; foreach ($pagination->getLinks(true) as $rel => $url) { $links[] = "<$url>; rel=$rel"; } $this->response->getHeaders() ->set($this->totalCountHeader, $pagination->totalCount) ->set($this->pageCountHeader, $pagination->getPageCount()) ->set($this->currentPageHeader, $pagination->getPage() + 1) ->set($this->perPageHeader, $pagination->pageSize) ->set('Link', implode(', ', $links)); } /** * Serializes a model object. * @param Arrayable $model * @return array the array representation of the model */ protected function serializeModel($model) { if ($this->request->getIsHead()) { return null; } list($fields, $expand) = $this->getRequestedFields(); return $model->toArray($fields, $expand); } /** * Serializes the validation errors in a model. * @param Model $model * @return array the array representation of the errors */ protected function serializeModelErrors($model) { $this->response->setStatusCode(422, 'Data Validation Failed.'); $result = []; foreach ($model->getFirstErrors() as $name => $message) { $result[] = [ 'field' => $name, 'message' => $message, ]; } return $result; } /** * Serializes a set of models. * @param array $models * @return array the array representation of the models */ protected function serializeModels(array $models) { list($fields, $expand) = $this->getRequestedFields(); foreach ($models as $i => $model) { if ($model instanceof Arrayable) { $models[$i] = $model->toArray($fields, $expand); } elseif (is_array($model)) { $models[$i] = ArrayHelper::toArray($model); } } return $models; } }
lubosdz/yii2
framework/rest/Serializer.php
PHP
bsd-3-clause
11,112
import re import sublime import sublime_plugin class IndentListItemCommand(sublime_plugin.TextCommand): bullet_pattern = r'([-+*]|([(]?(\d+|#|[a-y]|[A-Y]|[MDCLXVImdclxvi]+))([).]))' bullet_pattern_re = re.compile(bullet_pattern) line_pattern_re = re.compile(r'^\s*' + bullet_pattern) spaces_re = re.compile(r'^\s*') def run(self, edit, reverse=False): for region in self.view.sel(): if region.a != region.b: continue line = self.view.line(region) line_content = self.view.substr(line) new_line = line_content m = self.line_pattern_re.match(new_line) if not m: return # Determine how to indent (tab or spaces) tab_str = self.view.settings().get('tab_size', 4) * ' ' sep_str = ' ' if m.group(4) else '' prev_line = self.view.line(sublime.Region(line.begin() - 1, line.begin() - 1)) prev_line_content = self.view.substr(prev_line) prev_prev_line = self.view.line(sublime.Region(prev_line.begin() - 1, prev_line.begin() - 1)) prev_prev_line_content = self.view.substr(prev_prev_line) if not reverse: # Do the indentation new_line = self.bullet_pattern_re.sub(tab_str + sep_str + r'\1', new_line) # Insert the new item if prev_line_content: new_line = '\n' + new_line else: if not new_line.startswith(tab_str): continue # Do the unindentation new_line = re.sub(tab_str + sep_str + self.bullet_pattern, r'\1', new_line) # Insert the new item if prev_line_content: new_line = '\n' + new_line else: prev_spaces = self.spaces_re.match(prev_prev_line_content).group(0) spaces = self.spaces_re.match(new_line).group(0) if prev_spaces == spaces: line = sublime.Region(line.begin() - 1, line.end()) endings = ['.', ')'] # Transform the bullet to the next/previous bullet type if self.view.settings().get('list_indent_auto_switch_bullet', True): bullets = self.view.settings().get('list_indent_bullets', ['*', '-', '+']) def change_bullet(m): bullet = m.group(1) try: return bullets[(bullets.index(bullet) + (1 if not reverse else -1)) % len(bullets)] except ValueError: pass n = m.group(2) ending = endings[(endings.index(m.group(4)) + (1 if not reverse else -1)) % len(endings)] if n.isdigit(): return '${1:a}' + ending elif n != '#': return '${1:0}' + ending return m.group(2) + ending new_line = self.bullet_pattern_re.sub(change_bullet, new_line) self.view.replace(edit, line, '') self.view.run_command('insert_snippet', {'contents': new_line}) def is_enabled(self): return bool(self.view.score_selector(self.view.sel()[0].a, 'text.restructuredtext'))
Kronuz/sublime-rst-completion
indent_list_item.py
Python
bsd-3-clause
3,382
"""Tools for working with virtualenv environments""" import os import sys import subprocess from pip.exceptions import BadCommand from pip.log import logger def restart_in_venv(venv, base, site_packages, args): """ Restart this script using the interpreter in the given virtual environment """ if base and not os.path.isabs(venv) and not venv.startswith('~'): base = os.path.expanduser(base) # ensure we have an abs basepath at this point: # a relative one makes no sense (or does it?) if os.path.isabs(base): venv = os.path.join(base, venv) if venv.startswith('~'): venv = os.path.expanduser(venv) if not os.path.exists(venv): try: import virtualenv except ImportError: print 'The virtual environment does not exist: %s' % venv print 'and virtualenv is not installed, so a new environment cannot be created' sys.exit(3) print 'Creating new virtualenv environment in %s' % venv virtualenv.logger = logger logger.indent += 2 virtualenv.create_environment(venv, site_packages=site_packages) if sys.platform == 'win32': python = os.path.join(venv, 'Scripts', 'python.exe') # check for bin directory which is used in buildouts if not os.path.exists(python): python = os.path.join(venv, 'bin', 'python.exe') else: python = os.path.join(venv, 'bin', 'python') if not os.path.exists(python): python = venv if not os.path.exists(python): raise BadCommand('Cannot find virtual environment interpreter at %s' % python) base = os.path.dirname(os.path.dirname(python)) file = os.path.join(os.path.dirname(__file__), 'runner.py') if file.endswith('.pyc'): file = file[:-1] proc = subprocess.Popen( [python, file] + args + [base, '___VENV_RESTART___']) proc.wait() sys.exit(proc.returncode)
BadDNA/anolis
web/env/lib/python2.6/site-packages/pip-0.7.2-py2.6.egg/pip/venv.py
Python
bsd-3-clause
1,972
<?php /** * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * @link https://cakephp.org CakePHP(tm) Project * @since 3.3.4 * @license https://opensource.org/licenses/mit-license.php MIT License */ namespace App\Controller; use Cake\Event\Event; /** * Error Handling Controller * * Controller used by ExceptionRenderer to render error responses. */ class ErrorController extends AppController { /** * Initialization hook method. * * @return void */ public function initialize() { $this->loadComponent('RequestHandler', [ 'enableBeforeRedirect' => false, ]); } /** * beforeFilter callback. * * @param \Cake\Event\Event $event Event. * @return \Cake\Http\Response|null|void */ public function beforeFilter(Event $event) { } /** * beforeRender callback. * * @param \Cake\Event\Event $event Event. * @return \Cake\Http\Response|null|void */ public function beforeRender(Event $event) { parent::beforeRender($event); $this->viewBuilder()->setTemplatePath('Error'); } /** * afterFilter callback. * * @param \Cake\Event\Event $event Event. * @return \Cake\Http\Response|null|void */ public function afterFilter(Event $event) { } }
pwerken/va-void
src/Controller/ErrorController.php
PHP
isc
1,731
<?php /** * CakePHP Tags Plugin * * Copyright 2009 - 2010, Cake Development Corporation * 1785 E. Sahara Avenue, Suite 490-423 * Las Vegas, Nevada 89104 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright 2009 - 2010, Cake Development Corporation (http://cakedc.com) * @link http://github.com/CakeDC/Tags * @package plugins.tags * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ $map = array( 1 => array( '001_initialize_tags_schema' => 'M49ac311a54844a9d87o822502jedc423'), 2 => array( '002_create_times_tagged_field' => 'M4c0d42bcd12c4db099c105f40e8f3d6d'), 3 => array( '003_occurrence_fields_for_tags' => 'M8d01880f01c11e0be500800200c9a66'), ); ?>
steinkel/tags
Config/Migration/map.php
PHP
mit
823
# RSpec::Matchers.define :serve_result_image do |result| # match do |request| # path = "#{Rails.root}/public/images/result/#{result}.png" # controller.expects(:send_file).with(path, { :type => 'image/png', :disposition => 'inline' }).once # request.call # end # end RSpec::Matchers.define :issue_queries do |count| match do |code| queries = call(code) failure_message_for_should do (["expected #{count} queries to be issued, but got #{queries.size}:"] + queries).join("\n\n") end queries.size == count end def call(code) queries = [] ActiveSupport::Notifications.subscribe 'sql.active_record' do |name, start, finish, id, payload| queries << payload[:sql] unless payload[:sql] =~ /(?:ROLLBACK|pg_|BEGIN|COMMIT)/ end code.call queries end end RSpec::Matchers.define :publish_instrumentation_event do |data| match do |event| non_matching = data.map { |key, value| [key, value, event[key]] unless event[key] == value }.compact expected_keys = [:uuid, :event, :started_at] missing_keys = expected_keys.select { |key| !event.key?(key) } failure_message do message = "Expected a notification event to be published:\n\n\t#{event.inspect}\n\n" message << "Including:\n\n\t#{data.inspect}\n\n" non_matching.each do |key, expected, actual| message << "#{key.inspect} expected to be\n\n\t#{expected.inspect}\n\nbut was\n\n\t#{actual.inspect}\n\n" end message << "Expected #{missing_keys.map(&:inspect).join(', ')} to be present." if missing_keys.present? message end non_matching.empty? && missing_keys.empty? end end
travis-ci/travis-core
lib/travis/testing/matchers.rb
Ruby
mit
1,662
// 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. #nullable disable using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.Xaml.Features.OrganizeImports; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.OrganizeImports; using Microsoft.VisualStudio.LanguageServices.Xaml; namespace Microsoft.CodeAnalysis.Editor.Xaml.OrganizeImports { [ExportLanguageService(typeof(IOrganizeImportsService), StringConstants.XamlLanguageName), Shared] internal partial class XamlOrganizeImportsService : IOrganizeImportsService { private readonly IXamlOrganizeNamespacesService _organizeService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XamlOrganizeImportsService(IXamlOrganizeNamespacesService organizeService) { _organizeService = organizeService; } public async Task<Document> OrganizeImportsAsync(Document document, OrganizeImportsOptions options, CancellationToken cancellationToken) { return await _organizeService.OrganizeNamespacesAsync(document, options.PlaceSystemNamespaceFirst, cancellationToken).ConfigureAwait(false) ?? document; } public string SortImportsDisplayStringWithAccelerator { get { return Resources.Sort_Namespaces; } } public string SortAndRemoveUnusedImportsDisplayStringWithAccelerator { get { return Resources.RemoveAndSortNamespacesWithAccelerator; } } } }
CyrusNajmabadi/roslyn
src/VisualStudio/Xaml/Impl/Features/OrganizeImports/XamlOrganizeImportsService.cs
C#
mit
1,887
# -*- coding: utf-8 -*- from uuid import uuid4 from gluon import current def rlpcm_person_anonymize(): """ Rules to anonymize a case file """ auth = current.auth s3db = current.s3db ANONYMOUS = "-" # Standard anonymizers from s3db.pr import pr_address_anonymise as anonymous_address, \ pr_person_obscure_dob as obscure_dob # Helper to produce an anonymous ID (pe_label) anonymous_id = lambda record_id, f, v: "NN%s" % uuid4().hex[-8:].upper() anonymous_code = lambda record_id, f, v: uuid4().hex # Case Activity Default Closure activity_closed = s3db.br_case_activity_default_status(closing=True) # General rule for attachments documents = ("doc_document", { "key": "doc_id", "match": "doc_id", "fields": {"name": ("set", ANONYMOUS), "file": "remove", "url": "remove", "comments": "remove", }, "delete": True, }) # Rule for direct offers (from the offerer perspective) direct_offers = ("br_direct_offer", { "key": "offer_id", "match": "id", "delete": True, }) # Rules for user accounts account = ("auth_user", { "key": "id", "match": "user_id", "fields": {"id": auth.s3_anonymise_roles, "first_name": ("set", "-"), "last_name": "remove", "email": anonymous_code, "organisation_id": "remove", "password": auth.s3_anonymise_password, "deleted": ("set", True), }, }) # Rules rules = [ # Rules to remove PID from person record and case file {"name": "default", "title": "Names, IDs, Reference Numbers, Contact Information, Addresses", "fields": {"first_name": ("set", ANONYMOUS), "last_name": ("set", ANONYMOUS), "pe_label": anonymous_id, "date_of_birth": obscure_dob, "comments": "remove", }, "cascade": [("br_case", { "key": "person_id", "match": "id", "fields": {"comments": "remove", }, "cascade": [documents, ], }), ("pr_contact", { "key": "pe_id", "match": "pe_id", "fields": {"contact_description": "remove", "value": ("set", ""), "comments": "remove", }, "delete": True, }), ("pr_contact_emergency", { "key": "pe_id", "match": "pe_id", "fields": {"name": ("set", ANONYMOUS), "relationship": "remove", "phone": "remove", "comments": "remove", }, "delete": True, }), ("pr_address", { "key": "pe_id", "match": "pe_id", "fields": {"location_id": anonymous_address, "comments": "remove", }, }), ("pr_person_details", { "key": "person_id", "match": "id", "fields": {"education": "remove", "occupation": "remove", }, }), ("pr_image", { "key": "pe_id", "match": "pe_id", "fields": {"image": "remove", "url": "remove", "description": "remove", }, "delete": True, }), ("hrm_human_resource", { "key": "person_id", "match": "id", "fields": {"status": ("set", 2), "site_id": "remove", "comments": "remove", }, }), ], }, # Rules to remove PID from activities and offers {"name": "activities", "title": "Needs Reports and Offers of Assistance", "cascade": [("br_case_activity", { "key": "person_id", "match": "id", "fields": {"location_id": anonymous_address, "subject": ("set", ANONYMOUS), "need_details": "remove", "activity_details": "remove", "outcome": "remove", "comments": "remove", "status_id": ("set", activity_closed), }, "cascade": [documents, ], }), ("br_assistance_offer", { "key": "pe_id", "match": "pe_id", "fields": {"name": ("set", ANONYMOUS), "description": "remove", "capacity": "remove", "location_id": anonymous_address, "contact_name": "remove", "contact_phone": "remove", "contact_email": "remove", "availability": ("set", "RTD"), "comments": "remove", }, "cascade": [direct_offers, ], }), ], }, # Rules to unlink and remove user account {"name": "account", "title": "User Account", "cascade": [("pr_person_user", { "key": "pe_id", "match": "pe_id", "cascade": [account, ], "delete": True, }), ], }, ] return rules
flavour/eden
modules/templates/BRCMS/RLP/anonymize.py
Python
mit
7,359
using System; using System.Collections.Generic; using System.Text; namespace MqttLib { public interface IMqttConnectDisconnect { /// <summary> /// Connect to the MQTT message broker /// </summary> void Connect(); /// <summary> /// Connect to the MQTT message broker /// </summary> /// <param name="cleanStart">If true, all previous subscriptions and pending messages for client are lost</param> void Connect(bool cleanStart); /// <summary> /// Connect to the MQTT message broker specifying last will & testament (LWT) /// </summary> /// <param name="willTopic">Destination of LWT</param> /// <param name="willQoS">QoS of LWT</param> /// <param name="willMsg">Message body of LWT</param> /// <param name="willRetain">Whether LWT is retained</param> void Connect(string willTopic, QoS willQoS, MqttPayload willMsg, bool willRetain); /// <summary> /// Connect to the MQTT message broker specifying last will & testament (LWT) /// </summary> /// <param name="willTopic">Destination of LWT</param> /// <param name="willQoS">QoS of LWT</param> /// <param name="willMsg">Message body of LWT</param> /// <param name="willRetain">Whether LWT is retained</param> /// <param name="cleanStart">If true, all previous subscriptions and pending messages for client are lost</param> void Connect(string willTopic, QoS willQoS, MqttPayload willMsg, bool willRetain, bool cleanStart); /// <summary> /// Disconnect from the MQTT message broker /// </summary> void Disconnect(); /// <summary> /// Fired when the connection to the broker is lost /// </summary> event ConnectionDelegate ConnectionLost; /// <summary> /// Fired when a connection is made with a broker /// </summary> event ConnectionDelegate Connected; /// <summary> /// Returns true if the client is connected to a broker, false otherwise /// </summary> bool IsConnected { get;} /// <summary> /// Interval (in seconds) in which Client is expected to Ping Broker to keep session alive. /// If this interval expires without communication, the broker will assume the client /// is disconnected, close the channel, and broker any last will and testament contract. /// </summary> ushort KeepAliveInterval { get; set;} } }
stevenlovegrove/MqttDotNet
MqttLib/IMqttConnectDisconnect.cs
C#
mit
2,434
describe :hash_length, shared: true do it "returns the number of entries" do new_hash(a: 1, b: 'c').send(@method).should == 2 new_hash(a: 1, b: 2, a: 2).send(@method).should == 2 new_hash(a: 1, b: 1, c: 1).send(@method).should == 3 new_hash().send(@method).should == 0 new_hash(5).send(@method).should == 0 new_hash { 5 }.send(@method).should == 0 end end
BanzaiMan/rubyspec
core/hash/shared/length.rb
Ruby
mit
384
/******************************************************************************* * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui.actions; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; /** * Action group that adds the open and show actions to a context menu and * the action bar's navigate menu. This action group reuses the <code> * OpenEditorActionGroup</code> and <code>OpenViewActionGroup</code>. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.0 * * @noextend This class is not intended to be subclassed by clients. */ public class NavigateActionGroup extends ActionGroup { private OpenEditorActionGroup fOpenEditorActionGroup; private OpenViewActionGroup fOpenViewActionGroup; /** * Creates a new <code>NavigateActionGroup</code>. The group requires * that the selection provided by the part's selection provider is of type <code> * org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param part the view part that owns this action group */ public NavigateActionGroup(IViewPart part) { fOpenEditorActionGroup= new OpenEditorActionGroup(part); fOpenViewActionGroup= new OpenViewActionGroup(part); } /** * Creates a new <code>NavigateActionGroup</code>. The group requires * that the selection provided by the given selection provider is of type * {@link IStructuredSelection}. * * @param site the site that will own the action group. * @param specialSelectionProvider the selection provider used instead of the * sites selection provider. * * @since 3.4 */ public NavigateActionGroup(IWorkbenchPartSite site, ISelectionProvider specialSelectionProvider) { fOpenEditorActionGroup= new OpenEditorActionGroup(site, specialSelectionProvider); fOpenViewActionGroup= new OpenViewActionGroup(site, specialSelectionProvider); } /** * Returns the open action managed by this action group. * * @return the open action. Returns <code>null</code> if the group * doesn't provide any open action */ public IAction getOpenAction() { return fOpenEditorActionGroup.getOpenAction(); } /* (non-Javadoc) * Method declared in ActionGroup */ @Override public void dispose() { super.dispose(); fOpenEditorActionGroup.dispose(); fOpenViewActionGroup.dispose(); } /* (non-Javadoc) * Method declared in ActionGroup */ @Override public void fillActionBars(IActionBars actionBars) { super.fillActionBars(actionBars); fOpenEditorActionGroup.fillActionBars(actionBars); fOpenViewActionGroup.fillActionBars(actionBars); } /* (non-Javadoc) * Method declared in ActionGroup */ @Override public void fillContextMenu(IMenuManager menu) { super.fillContextMenu(menu); fOpenEditorActionGroup.fillContextMenu(menu); fOpenViewActionGroup.fillContextMenu(menu); } /* (non-Javadoc) * Method declared in ActionGroup */ @Override public void setContext(ActionContext context) { super.setContext(context); fOpenEditorActionGroup.setContext(context); fOpenViewActionGroup.setContext(context); } /* (non-Javadoc) * Method declared in ActionGroup */ @Override public void updateActionBars() { super.updateActionBars(); fOpenEditorActionGroup.updateActionBars(); fOpenViewActionGroup.updateActionBars(); } }
brunyuriy/quick-fix-scout
org.eclipse.jdt.ui_3.7.1.r371_v20110824-0800/src/org/eclipse/jdt/ui/actions/NavigateActionGroup.java
Java
mit
4,070
/* ----------------------------------------------- /* How to use? : Check the GitHub README /* ----------------------------------------------- */ /* To load a config file (particles.json) you need to host this demo (MAMP/WAMP/local)... */ /* particlesJS.load('particles-js', 'particles.json', function() { console.log('particles.js loaded - callback'); }); */ /* Otherwise just put the config content (json): */ particlesJS('particles-js', { "particles": { "number": { "value": 80, "density": { "enable": true, "value_area": 800 } }, "color": { "value": "#888" }, "shape": { "type": "circle", "stroke": { "width": 0, "color": "#000000" }, "polygon": { "nb_sides": 5 }, "image": { "src": "img/github.svg", "width": 100, "height": 100 } }, "opacity": { "value": 0.5, "random": false, "anim": { "enable": false, "speed": 1, "opacity_min": 0.1, "sync": false } }, "size": { "value": 5, "random": true, "anim": { "enable": false, "speed": 40, "size_min": 0.1, "sync": false } }, "line_linked": { "enable": true, "distance": 150, "color": "#777", "opacity": 0.4, "width": 1 }, "move": { "enable": true, "speed": 6, "direction": "none", "random": false, "straight": false, "out_mode": "out", "attract": { "enable": false, "rotateX": 600, "rotateY": 1200 } } }, "interactivity": { "detect_on": "canvas", "events": { "onhover": { "enable": true, "mode": "repulse" }, "onclick": { "enable": true, "mode": "push" }, "resize": true }, "modes": { "grab": { "distance": 400, "line_linked": { "opacity": 1 } }, "bubble": { "distance": 400, "size": 40, "duration": 2, "opacity": 8, "speed": 3 }, "repulse": { "distance": 200 }, "push": { "particles_nb": 4 }, "remove": { "particles_nb": 2 } } }, "retina_detect": true, "config_demo": { "hide_card": false, "background_color": "#b61924", "background_image": "", "background_position": "50% 50%", "background_repeat": "no-repeat", "background_size": "cover" } } );
Xapuu/SoftUniSoftTech
views/js/app.js
JavaScript
mit
2,815
<?php declare(strict_types=1); /** * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice * * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * @link https://cakephp.org CakePHP(tm) Project * @since 1.2.0 * @license https://opensource.org/licenses/mit-license.php MIT License */ /** * OtherComponent */ namespace TestPlugin\Controller\Component; use Cake\Controller\Component; class OtherComponent extends Component { }
cakephp/cakephp
tests/test_app/Plugin/TestPlugin/src/Controller/Component/OtherComponent.php
PHP
mit
763
// Note: You must restart bin/webpack-watcher for changes to take effect const merge = require('webpack-merge') const sharedConfig = require('./shared.js') module.exports = merge(sharedConfig, { devtool: 'sourcemap', stats: { errorDetails: true }, output: { pathinfo: true } })
fcbajao/chitchat
config/webpack/development.js
JavaScript
mit
300
var global = require('../../global'); module.exports = function (packing, offset) { var items = [].concat.apply([], packing.items); var iso = "FM.FP-GJ-15-003"; // var number = packing.code; // var colorName = packing.colorName; var orderType = (packing.orderType || "").toString().toLowerCase() === "printing" ? "Printing" : "Finishing"; var locale = global.config.locale; var buyerName = packing.buyerName ? packing.buyerName : ""; var colorType = packing.colorType ? packing.colorType : ""; var construction = packing.construction ? packing.construction : ""; var buyerAddress = packing.buyerAddress ? packing.buyerAddress : ""; var moment = require('moment'); moment.locale(locale.name); var footerStack = []; var footerStackValue = []; var footerStackDivide = []; if ((packing.orderType || "").toString().toLowerCase() === "solid") { footerStack = ['Buyer', "Jenis Order", "Jenis Warna", 'Konstruksi', 'Tujuan']; footerStackValue = [buyerName, orderType, colorType, construction, buyerAddress]; footerStackDivide = [':', ":", ":", ':', ':']; } else if ((packing.orderType || "").toString().toLowerCase() === "printing") { footerStack = ['Buyer', "Jenis Order", 'Konstruksi', 'Design/Motif', 'Tujuan']; footerStackValue = [buyerName, orderType, construction, packing.designNumber && packing.designCode ? `${packing.designNumber} - ${packing.designCode}` : "", buyerAddress]; footerStackDivide = [':', ":", ":", ':', ':']; } else { footerStack = ['Buyer', "Jenis Order", 'Konstruksi', 'Tujuan']; footerStackValue = [buyerName, orderType, construction, buyerAddress]; footerStackDivide = [':', ":", ":", ':']; } var header = [{ columns: [{ columns: [{ width: '*', stack: [{ text: 'BON PENYERAHAN PRODUKSI', style: ['size15'], alignment: "center" }] }] }] }]; var line = [{ canvas: [{ type: 'line', x1: 0, y1: 5, x2: 555, y2: 5, lineWidth: 0.5 } ] }]; var subheader = [{ columns: [{ columns: [{ width: '*', stack: [{ text: iso, style: ['size09', 'bold'], alignment: "right" } ] }] }] }]; var subheader2 = [{ columns: [{ width: '60%', columns: [{ width: '*', stack: ['Kepada Yth. Bagian Penjualan ', `Bersama ini kami kirimkan hasil produksi: Inspeksi ${orderType}`], }], style: ['size08'] } , { width: '5%', text: '' }, { width: '40%', columns: [{ width: '40%', stack: ['No', 'Sesuai No Order'], }, { width: '5%', stack: [':', ':'], }, { width: '*', stack: [packing.code, packing.productionOrderNo], }], style: ['size08'] } ] }]; var thead = [{ text: 'NO', style: 'tableHeader' }, { text: 'BARANG', style: 'tableHeader' }, { text: `Jumlah (${packing.packingUom})`, style: 'tableHeader' }, { text: 'Panjang (Meter)', style: 'tableHeader' }, { text: 'Panjang Total (Meter)', style: 'tableHeader' }, { text: 'Berat Total (Kg)', style: 'tableHeader' }, { text: 'Keterangan', style: 'tableHeader' } ]; var gradeItem = ""; var totalJumlah = 0; var totalBerat = 0; var totalPanjang = 0; var totalPanjangTotal = 0; var totalBeratTotal = 0; var tbody = items.map(function (item, index) { // if (item.grade.toLowerCase() == "a" || item.grade.toLowerCase() == "b" || item.grade.toLowerCase() == "c") { if (item.grade.toLowerCase() == "a") { gradeItem = "BQ"; } else { gradeItem = "BS"; } totalJumlah += item.quantity; totalBerat += item.weight; totalPanjang += item.length; totalPanjangTotal += item.length * item.quantity; totalBeratTotal += item.weight * item.quantity; return [{ text: (index + 1).toString() || '', style: ['size08', 'center'] }, { text: packing.colorName + ' ' + item.lot + ' ' + item.grade + ' ' + gradeItem, style: ['size08', 'center'] }, { text: item.quantity, style: ['size08', 'center'] }, { text: item.length, style: ['size08', 'center'] }, { text: (item.length * item.quantity).toFixed(2), style: ['size08', 'center'] }, { text: (item.weight * item.quantity).toFixed(2), style: ['size08', 'center'] }, { text: item.remark, style: ['size08', 'center'] } ]; }); var tfoot = [[{ text: " ", style: ['size08', 'center'] }, { text: "Total", style: ['size08', 'center'] }, { text: totalJumlah.toFixed(2), style: ['size08', 'center'] }, { text: totalPanjang.toFixed(2), style: ['size08', 'center'] }, { text: totalPanjangTotal.toFixed(2), style: ['size08', 'center'] }, { text: totalBeratTotal.toFixed(2), style: ['size08', 'center'] }, "",]]; tbody = tbody.length > 0 ? tbody : [ [{ text: "tidak ada barang", style: ['size08', 'center'], colSpan: 6 }, "", "", "", "", "", ""] ]; var table = [{ table: { widths: ['5%', '35%', '10%', '10%', '10%', '10%', '20%'], headerRows: 1, body: [].concat([thead], tbody, tfoot), } }]; var footer = [{ stack: [{ columns: [{ columns: [{ width: '15%', stack: footerStack }, { width: '2%', stack: footerStackDivide }, { width: '*', stack: footerStackValue }] }] } ], style: ['size08'] }, ]; var footer2 = ['\n', { columns: [{ width: '25%', stack: ['\n', 'Diterima oleh:', '\n\n\n\n', '( )'], style: ['center'] }, { width: '25%', stack: [], }, { width: '25%', stack: [], }, { width: '25%', stack: [`Sukoharjo, ${moment(packing.date).add(offset, 'h').format(locale.date.format)} `, 'Diserahkan oleh :', '\n\n\n\n', `( ${packing._createdBy} )`], style: ['center'] }], style: ['size08'] }]; var packingPDF = { pageSize: 'A5', pageOrientation: 'landscape', pageMargins: 20, // content: [].concat(header, line, subheader, subheader2, table, footer), content: [].concat(header, line, subheader, subheader2, table, footer, footer2), styles: { size06: { fontSize: 8 }, size07: { fontSize: 9 }, size08: { fontSize: 10 }, size09: { fontSize: 11 }, size10: { fontSize: 12 }, size15: { fontSize: 17 }, size30: { fontSize: 32 }, bold: { bold: true }, center: { alignment: 'center' }, left: { alignment: 'left' }, right: { alignment: 'right' }, justify: { alignment: 'justify' }, tableHeader: { bold: true, fontSize: 10, color: 'black', alignment: 'center' } } }; return packingPDF; }
indriHutabalian/dl-module
src/pdf/definitions/packing.js
JavaScript
mit
8,749
/** * Interaction for the faq module * * @author Annelies Van Extergem <annelies@netlash.com> * @author Jelmer Snoeck <jelmer.snoeck@netlash.com> * @author Thomas Deceuninck <thomas@fronto.be> */ jsFrontend.faq = { // init, something like a constructor init: function() { if($('#faqFeedbackForm').length > 0) jsFrontend.faq.feedback.init(); } } // feedback form jsFrontend.faq.feedback = { init: function() { // useful status has been changed $('#usefulY, #usefulN').on('click', function() { // get useful status var useful = ($('#usefulY').attr('checked') ? true : false); // show or hide the form if(useful) { $('#message').prop('required', false); $('form#feedback').submit(); } else { $('#feedbackNoInfo').show(); $('#message').prop('required', true); } }); } } $(jsFrontend.faq.init);
gertjanmeire/davy_portfolio
frontend/modules/faq/js/faq.js
JavaScript
mit
858
/* * jQuery File Upload Plugin 5.32.0 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2010, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint nomen: true, unparam: true, regexp: true */ /*global define, window, document, location, File, Blob, FormData */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define([ 'jquery', 'jquery.ui.widget' ], factory); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; // Detect file input support, based on // http://viljamis.com/blog/2012/file-upload-support-on-mobile/ $.support.fileInput = !(new RegExp( // Handle devices which give false positives for the feature detection: '(Android (1\\.[0156]|2\\.[01]))' + '|(Windows Phone (OS 7|8\\.0))|(XBLWP)|(ZuneWP)' + '|(w(eb)?OSBrowser)|(webOS)' + '|(Kindle/(1\\.0|2\\.[05]|3\\.0))' ).test(window.navigator.userAgent) || // Feature detection for all other devices: $('<input type="file">').prop('disabled')); // The FileReader API is not actually used, but works as feature detection, // as e.g. Safari supports XHR file uploads via the FormData API, // but not non-multipart XHR file uploads: $.support.xhrFileUpload = !!(window.XMLHttpRequestUpload && window.FileReader); $.support.xhrFormDataFileUpload = !!window.FormData; // Detect support for Blob slicing (required for chunked uploads): $.support.blobSlice = window.Blob && (Blob.prototype.slice || Blob.prototype.webkitSlice || Blob.prototype.mozSlice); // The fileupload widget listens for change events on file input fields defined // via fileInput setting and paste or drop events of the given dropZone. // In addition to the default jQuery Widget methods, the fileupload widget // exposes the "add" and "send" methods, to add or directly send files using // the fileupload API. // By default, files added via file input selection, paste, drag & drop or // "add" method are uploaded immediately, but it is possible to override // the "add" callback option to queue file uploads. $.widget('blueimp.fileupload', { options: { // The drop target element(s), by the default the complete document. // Set to null to disable drag & drop support: dropZone: $(document), // The paste target element(s), by the default the complete document. // Set to null to disable paste support: pasteZone: $(document), // The file input field(s), that are listened to for change events. // If undefined, it is set to the file input fields inside // of the widget element on plugin initialization. // Set to null to disable the change listener. fileInput: undefined, // By default, the file input field is replaced with a clone after // each input field change event. This is required for iframe transport // queues and allows change events to be fired for the same file // selection, but can be disabled by setting the following option to false: replaceFileInput: true, // The parameter name for the file form data (the request argument name). // If undefined or empty, the name property of the file input field is // used, or "files[]" if the file input name property is also empty, // can be a string or an array of strings: paramName: undefined, // By default, each file of a selection is uploaded using an individual // request for XHR type uploads. Set to false to upload file // selections in one request each: singleFileUploads: true, // To limit the number of files uploaded with one XHR request, // set the following option to an integer greater than 0: limitMultiFileUploads: undefined, // Set the following option to true to issue all file upload requests // in a sequential order: sequentialUploads: false, // To limit the number of concurrent uploads, // set the following option to an integer greater than 0: limitConcurrentUploads: undefined, // Set the following option to true to force iframe transport uploads: forceIframeTransport: false, // Set the following option to the location of a redirect url on the // origin server, for cross-domain iframe transport uploads: redirect: undefined, // The parameter name for the redirect url, sent as part of the form // data and set to 'redirect' if this option is empty: redirectParamName: undefined, // Set the following option to the location of a postMessage window, // to enable postMessage transport uploads: postMessage: undefined, // By default, XHR file uploads are sent as multipart/form-data. // The iframe transport is always using multipart/form-data. // Set to false to enable non-multipart XHR uploads: multipart: true, // To upload large files in smaller chunks, set the following option // to a preferred maximum chunk size. If set to 0, null or undefined, // or the browser does not support the required Blob API, files will // be uploaded as a whole. maxChunkSize: undefined, // When a non-multipart upload or a chunked multipart upload has been // aborted, this option can be used to resume the upload by setting // it to the size of the already uploaded bytes. This option is most // useful when modifying the options object inside of the "add" or // "send" callbacks, as the options are cloned for each file upload. uploadedBytes: undefined, // By default, failed (abort or error) file uploads are removed from the // global progress calculation. Set the following option to false to // prevent recalculating the global progress data: recalculateProgress: true, // Interval in milliseconds to calculate and trigger progress events: progressInterval: 100, // Interval in milliseconds to calculate progress bitrate: bitrateInterval: 500, // By default, uploads are started automatically when adding files: autoUpload: true, // Error and info messages: messages: { uploadedBytes: 'Uploaded bytes exceed file size' }, // Translation function, gets the message key to be translated // and an object with context specific data as arguments: i18n: function (message, context) { message = this.messages[message] || message.toString(); if (context) { $.each(context, function (key, value) { message = message.replace('{' + key + '}', value); }); } return message; }, // Additional form data to be sent along with the file uploads can be set // using this option, which accepts an array of objects with name and // value properties, a function returning such an array, a FormData // object (for XHR file uploads), or a simple object. // The form of the first fileInput is given as parameter to the function: formData: function (form) { return form.serializeArray(); }, // The add callback is invoked as soon as files are added to the fileupload // widget (via file input selection, drag & drop, paste or add API call). // If the singleFileUploads option is enabled, this callback will be // called once for each file in the selection for XHR file uploads, else // once for each file selection. // // The upload starts when the submit method is invoked on the data parameter. // The data object contains a files property holding the added files // and allows you to override plugin options as well as define ajax settings. // // Listeners for this callback can also be bound the following way: // .bind('fileuploadadd', func); // // data.submit() returns a Promise object and allows to attach additional // handlers using jQuery's Deferred callbacks: // data.submit().done(func).fail(func).always(func); add: function (e, data) { if (data.autoUpload || (data.autoUpload !== false && $(this).fileupload('option', 'autoUpload'))) { data.process().done(function () { data.submit(); }); } }, // Other callbacks: // Callback for the submit event of each file upload: // submit: function (e, data) {}, // .bind('fileuploadsubmit', func); // Callback for the start of each file upload request: // send: function (e, data) {}, // .bind('fileuploadsend', func); // Callback for successful uploads: // done: function (e, data) {}, // .bind('fileuploaddone', func); // Callback for failed (abort or error) uploads: // fail: function (e, data) {}, // .bind('fileuploadfail', func); // Callback for completed (success, abort or error) requests: // always: function (e, data) {}, // .bind('fileuploadalways', func); // Callback for upload progress events: // progress: function (e, data) {}, // .bind('fileuploadprogress', func); // Callback for global upload progress events: // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func); // Callback for uploads start, equivalent to the global ajaxStart event: // start: function (e) {}, // .bind('fileuploadstart', func); // Callback for uploads stop, equivalent to the global ajaxStop event: // stop: function (e) {}, // .bind('fileuploadstop', func); // Callback for change events of the fileInput(s): // change: function (e, data) {}, // .bind('fileuploadchange', func); // Callback for paste events to the pasteZone(s): // paste: function (e, data) {}, // .bind('fileuploadpaste', func); // Callback for drop events of the dropZone(s): // drop: function (e, data) {}, // .bind('fileuploaddrop', func); // Callback for dragover events of the dropZone(s): // dragover: function (e) {}, // .bind('fileuploaddragover', func); // Callback for the start of each chunk upload request: // chunksend: function (e, data) {}, // .bind('fileuploadchunksend', func); // Callback for successful chunk uploads: // chunkdone: function (e, data) {}, // .bind('fileuploadchunkdone', func); // Callback for failed (abort or error) chunk uploads: // chunkfail: function (e, data) {}, // .bind('fileuploadchunkfail', func); // Callback for completed (success, abort or error) chunk upload requests: // chunkalways: function (e, data) {}, // .bind('fileuploadchunkalways', func); // The plugin options are used as settings object for the ajax calls. // The following are jQuery ajax settings required for the file uploads: processData: false, contentType: false, cache: false }, // A list of options that require reinitializing event listeners and/or // special initialization code: _specialOptions: [ 'fileInput', 'dropZone', 'pasteZone', 'multipart', 'forceIframeTransport' ], _blobSlice: $.support.blobSlice && function () { var slice = this.slice || this.webkitSlice || this.mozSlice; return slice.apply(this, arguments); }, _BitrateTimer: function () { this.timestamp = ((Date.now) ? Date.now() : (new Date()).getTime()); this.loaded = 0; this.bitrate = 0; this.getBitrate = function (now, loaded, interval) { var timeDiff = now - this.timestamp; if (!this.bitrate || !interval || timeDiff > interval) { this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8; this.loaded = loaded; this.timestamp = now; } return this.bitrate; }; }, _isXHRUpload: function (options) { return !options.forceIframeTransport && ((!options.multipart && $.support.xhrFileUpload) || $.support.xhrFormDataFileUpload); }, _getFormData: function (options) { var formData; if (typeof options.formData === 'function') { return options.formData(options.form); } if ($.isArray(options.formData)) { return options.formData; } if ($.type(options.formData) === 'object') { formData = []; $.each(options.formData, function (name, value) { formData.push({name: name, value: value}); }); return formData; } return []; }, _getTotal: function (files) { var total = 0; $.each(files, function (index, file) { total += file.size || 1; }); return total; }, _initProgressObject: function (obj) { var progress = { loaded: 0, total: 0, bitrate: 0 }; if (obj._progress) { $.extend(obj._progress, progress); } else { obj._progress = progress; } }, _initResponseObject: function (obj) { var prop; if (obj._response) { for (prop in obj._response) { if (obj._response.hasOwnProperty(prop)) { delete obj._response[prop]; } } } else { obj._response = {}; } }, _onProgress: function (e, data) { if (e.lengthComputable) { var now = ((Date.now) ? Date.now() : (new Date()).getTime()), loaded; if (data._time && data.progressInterval && (now - data._time < data.progressInterval) && e.loaded !== e.total) { return; } data._time = now; loaded = Math.floor( e.loaded / e.total * (data.chunkSize || data._progress.total) ) + (data.uploadedBytes || 0); // Add the difference from the previously loaded state // to the global loaded counter: this._progress.loaded += (loaded - data._progress.loaded); this._progress.bitrate = this._bitrateTimer.getBitrate( now, this._progress.loaded, data.bitrateInterval ); data._progress.loaded = data.loaded = loaded; data._progress.bitrate = data.bitrate = data._bitrateTimer.getBitrate( now, loaded, data.bitrateInterval ); // Trigger a custom progress event with a total data property set // to the file size(s) of the current upload and a loaded data // property calculated accordingly: this._trigger('progress', e, data); // Trigger a global progress event for all current file uploads, // including ajax calls queued for sequential file uploads: this._trigger('progressall', e, this._progress); } }, _initProgressListener: function (options) { var that = this, xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr(); // Accesss to the native XHR object is required to add event listeners // for the upload progress event: if (xhr.upload) { $(xhr.upload).bind('progress', function (e) { var oe = e.originalEvent; // Make sure the progress event properties get copied over: e.lengthComputable = oe.lengthComputable; e.loaded = oe.loaded; e.total = oe.total; that._onProgress(e, options); }); options.xhr = function () { return xhr; }; } }, _isInstanceOf: function (type, obj) { // Cross-frame instanceof check return Object.prototype.toString.call(obj) === '[object ' + type + ']'; }, _initXHRData: function (options) { var that = this, formData, file = options.files[0], // Ignore non-multipart setting if not supported: multipart = options.multipart || !$.support.xhrFileUpload, paramName = options.paramName[0]; options.headers = options.headers || {}; if (options.contentRange) { options.headers['Content-Range'] = options.contentRange; } if (!multipart || options.blob || !this._isInstanceOf('File', file)) { options.headers['Content-Disposition'] = 'attachment; filename="' + encodeURI(file.name) + '"'; } if (!multipart) { options.contentType = file.type; options.data = options.blob || file; } else if ($.support.xhrFormDataFileUpload) { if (options.postMessage) { // window.postMessage does not allow sending FormData // objects, so we just add the File/Blob objects to // the formData array and let the postMessage window // create the FormData object out of this array: formData = this._getFormData(options); if (options.blob) { formData.push({ name: paramName, value: options.blob }); } else { $.each(options.files, function (index, file) { formData.push({ name: options.paramName[index] || paramName, value: file }); }); } } else { if (that._isInstanceOf('FormData', options.formData)) { formData = options.formData; } else { formData = new FormData(); $.each(this._getFormData(options), function (index, field) { formData.append(field.name, field.value); }); } if (options.blob) { formData.append(paramName, options.blob, file.name); } else { $.each(options.files, function (index, file) { // This check allows the tests to run with // dummy objects: if (that._isInstanceOf('File', file) || that._isInstanceOf('Blob', file)) { formData.append( options.paramName[index] || paramName, file, file.name ); } }); } } options.data = formData; } // Blob reference is not needed anymore, free memory: options.blob = null; }, _initIframeSettings: function (options) { var targetHost = $('<a></a>').prop('href', options.url).prop('host'); // Setting the dataType to iframe enables the iframe transport: options.dataType = 'iframe ' + (options.dataType || ''); // The iframe transport accepts a serialized array as form data: options.formData = this._getFormData(options); // Add redirect url to form data on cross-domain uploads: if (options.redirect && targetHost && targetHost !== location.host) { options.formData.push({ name: options.redirectParamName || 'redirect', value: options.redirect }); } }, _initDataSettings: function (options) { if (this._isXHRUpload(options)) { if (!this._chunkedUpload(options, true)) { if (!options.data) { this._initXHRData(options); } this._initProgressListener(options); } if (options.postMessage) { // Setting the dataType to postmessage enables the // postMessage transport: options.dataType = 'postmessage ' + (options.dataType || ''); } } else { this._initIframeSettings(options); } }, _getParamName: function (options) { var fileInput = $(options.fileInput), paramName = options.paramName; if (!paramName) { paramName = []; fileInput.each(function () { var input = $(this), name = input.prop('name') || 'files[]', i = (input.prop('files') || [1]).length; while (i) { paramName.push(name); i -= 1; } }); if (!paramName.length) { paramName = [fileInput.prop('name') || 'files[]']; } } else if (!$.isArray(paramName)) { paramName = [paramName]; } return paramName; }, _initFormSettings: function (options) { // Retrieve missing options from the input field and the // associated form, if available: if (!options.form || !options.form.length) { options.form = $(options.fileInput.prop('form')); // If the given file input doesn't have an associated form, // use the default widget file input's form: if (!options.form.length) { options.form = $(this.options.fileInput.prop('form')); } } options.paramName = this._getParamName(options); if (!options.url) { options.url = options.form.prop('action') || location.href; } // The HTTP request method must be "POST" or "PUT": options.type = (options.type || options.form.prop('method') || '') .toUpperCase(); if (options.type !== 'POST' && options.type !== 'PUT' && options.type !== 'PATCH') { options.type = 'POST'; } if (!options.formAcceptCharset) { options.formAcceptCharset = options.form.attr('accept-charset'); } }, _getAJAXSettings: function (data) { var options = $.extend({}, this.options, data); this._initFormSettings(options); this._initDataSettings(options); return options; }, // jQuery 1.6 doesn't provide .state(), // while jQuery 1.8+ removed .isRejected() and .isResolved(): _getDeferredState: function (deferred) { if (deferred.state) { return deferred.state(); } if (deferred.isResolved()) { return 'resolved'; } if (deferred.isRejected()) { return 'rejected'; } return 'pending'; }, // Maps jqXHR callbacks to the equivalent // methods of the given Promise object: _enhancePromise: function (promise) { promise.success = promise.done; promise.error = promise.fail; promise.complete = promise.always; return promise; }, // Creates and returns a Promise object enhanced with // the jqXHR methods abort, success, error and complete: _getXHRPromise: function (resolveOrReject, context, args) { var dfd = $.Deferred(), promise = dfd.promise(); context = context || this.options.context || promise; if (resolveOrReject === true) { dfd.resolveWith(context, args); } else if (resolveOrReject === false) { dfd.rejectWith(context, args); } promise.abort = dfd.promise; return this._enhancePromise(promise); }, // Adds convenience methods to the data callback argument: _addConvenienceMethods: function (e, data) { var that = this, getPromise = function (data) { return $.Deferred().resolveWith(that, [data]).promise(); }; data.process = function (resolveFunc, rejectFunc) { if (resolveFunc || rejectFunc) { data._processQueue = this._processQueue = (this._processQueue || getPromise(this)) .pipe(resolveFunc, rejectFunc); } return this._processQueue || getPromise(this); }; data.submit = function () { if (this.state() !== 'pending') { data.jqXHR = this.jqXHR = (that._trigger('submit', e, this) !== false) && that._onSend(e, this); } return this.jqXHR || that._getXHRPromise(); }; data.abort = function () { if (this.jqXHR) { return this.jqXHR.abort(); } return that._getXHRPromise(); }; data.state = function () { if (this.jqXHR) { return that._getDeferredState(this.jqXHR); } if (this._processQueue) { return that._getDeferredState(this._processQueue); } }; data.progress = function () { return this._progress; }; data.response = function () { return this._response; }; }, // Parses the Range header from the server response // and returns the uploaded bytes: _getUploadedBytes: function (jqXHR) { var range = jqXHR.getResponseHeader('Range'), parts = range && range.split('-'), upperBytesPos = parts && parts.length > 1 && parseInt(parts[1], 10); return upperBytesPos && upperBytesPos + 1; }, // Uploads a file in multiple, sequential requests // by splitting the file up in multiple blob chunks. // If the second parameter is true, only tests if the file // should be uploaded in chunks, but does not invoke any // upload requests: _chunkedUpload: function (options, testOnly) { options.uploadedBytes = options.uploadedBytes || 0; var that = this, file = options.files[0], fs = file.size, ub = options.uploadedBytes, mcs = options.maxChunkSize || fs, slice = this._blobSlice, dfd = $.Deferred(), promise = dfd.promise(), jqXHR, upload; if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) || options.data) { return false; } if (testOnly) { return true; } if (ub >= fs) { file.error = options.i18n('uploadedBytes'); return this._getXHRPromise( false, options.context, [null, 'error', file.error] ); } // The chunk upload method: upload = function () { // Clone the options object for each chunk upload: var o = $.extend({}, options), currentLoaded = o._progress.loaded; o.blob = slice.call( file, ub, ub + mcs, file.type ); // Store the current chunk size, as the blob itself // will be dereferenced after data processing: o.chunkSize = o.blob.size; // Expose the chunk bytes position range: o.contentRange = 'bytes ' + ub + '-' + (ub + o.chunkSize - 1) + '/' + fs; // Process the upload data (the blob and potential form data): that._initXHRData(o); // Add progress listeners for this chunk upload: that._initProgressListener(o); jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) || that._getXHRPromise(false, o.context)) .done(function (result, textStatus, jqXHR) { ub = that._getUploadedBytes(jqXHR) || (ub + o.chunkSize); // Create a progress event if no final progress event // with loaded equaling total has been triggered // for this chunk: if (currentLoaded + o.chunkSize - o._progress.loaded) { that._onProgress($.Event('progress', { lengthComputable: true, loaded: ub - o.uploadedBytes, total: ub - o.uploadedBytes }), o); } options.uploadedBytes = o.uploadedBytes = ub; o.result = result; o.textStatus = textStatus; o.jqXHR = jqXHR; that._trigger('chunkdone', null, o); that._trigger('chunkalways', null, o); if (ub < fs) { // File upload not yet complete, // continue with the next chunk: upload(); } else { dfd.resolveWith( o.context, [result, textStatus, jqXHR] ); } }) .fail(function (jqXHR, textStatus, errorThrown) { o.jqXHR = jqXHR; o.textStatus = textStatus; o.errorThrown = errorThrown; that._trigger('chunkfail', null, o); that._trigger('chunkalways', null, o); dfd.rejectWith( o.context, [jqXHR, textStatus, errorThrown] ); }); }; this._enhancePromise(promise); promise.abort = function () { return jqXHR.abort(); }; upload(); return promise; }, _beforeSend: function (e, data) { if (this._active === 0) { // the start callback is triggered when an upload starts // and no other uploads are currently running, // equivalent to the global ajaxStart event: this._trigger('start'); // Set timer for global bitrate progress calculation: this._bitrateTimer = new this._BitrateTimer(); // Reset the global progress values: this._progress.loaded = this._progress.total = 0; this._progress.bitrate = 0; } // Make sure the container objects for the .response() and // .progress() methods on the data object are available // and reset to their initial state: this._initResponseObject(data); this._initProgressObject(data); data._progress.loaded = data.loaded = data.uploadedBytes || 0; data._progress.total = data.total = this._getTotal(data.files) || 1; data._progress.bitrate = data.bitrate = 0; this._active += 1; // Initialize the global progress values: this._progress.loaded += data.loaded; this._progress.total += data.total; }, _onDone: function (result, textStatus, jqXHR, options) { var total = options._progress.total, response = options._response; if (options._progress.loaded < total) { // Create a progress event if no final progress event // with loaded equaling total has been triggered: this._onProgress($.Event('progress', { lengthComputable: true, loaded: total, total: total }), options); } response.result = options.result = result; response.textStatus = options.textStatus = textStatus; response.jqXHR = options.jqXHR = jqXHR; this._trigger('done', null, options); }, _onFail: function (jqXHR, textStatus, errorThrown, options) { var response = options._response; if (options.recalculateProgress) { // Remove the failed (error or abort) file upload from // the global progress calculation: this._progress.loaded -= options._progress.loaded; this._progress.total -= options._progress.total; } response.jqXHR = options.jqXHR = jqXHR; response.textStatus = options.textStatus = textStatus; response.errorThrown = options.errorThrown = errorThrown; this._trigger('fail', null, options); }, _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) { // jqXHRorResult, textStatus and jqXHRorError are added to the // options object via done and fail callbacks this._trigger('always', null, options); }, _onSend: function (e, data) { if (!data.submit) { this._addConvenienceMethods(e, data); } var that = this, jqXHR, aborted, slot, pipe, options = that._getAJAXSettings(data), send = function () { that._sending += 1; // Set timer for bitrate progress calculation: options._bitrateTimer = new that._BitrateTimer(); jqXHR = jqXHR || ( ((aborted || that._trigger('send', e, options) === false) && that._getXHRPromise(false, options.context, aborted)) || that._chunkedUpload(options) || $.ajax(options) ).done(function (result, textStatus, jqXHR) { that._onDone(result, textStatus, jqXHR, options); }).fail(function (jqXHR, textStatus, errorThrown) { that._onFail(jqXHR, textStatus, errorThrown, options); }).always(function (jqXHRorResult, textStatus, jqXHRorError) { that._onAlways( jqXHRorResult, textStatus, jqXHRorError, options ); that._sending -= 1; that._active -= 1; if (options.limitConcurrentUploads && options.limitConcurrentUploads > that._sending) { // Start the next queued upload, // that has not been aborted: var nextSlot = that._slots.shift(); while (nextSlot) { if (that._getDeferredState(nextSlot) === 'pending') { nextSlot.resolve(); break; } nextSlot = that._slots.shift(); } } if (that._active === 0) { // The stop callback is triggered when all uploads have // been completed, equivalent to the global ajaxStop event: that._trigger('stop'); } }); return jqXHR; }; this._beforeSend(e, options); if (this.options.sequentialUploads || (this.options.limitConcurrentUploads && this.options.limitConcurrentUploads <= this._sending)) { if (this.options.limitConcurrentUploads > 1) { slot = $.Deferred(); this._slots.push(slot); pipe = slot.pipe(send); } else { this._sequence = this._sequence.pipe(send, send); pipe = this._sequence; } // Return the piped Promise object, enhanced with an abort method, // which is delegated to the jqXHR object of the current upload, // and jqXHR callbacks mapped to the equivalent Promise methods: pipe.abort = function () { aborted = [undefined, 'abort', 'abort']; if (!jqXHR) { if (slot) { slot.rejectWith(options.context, aborted); } return send(); } return jqXHR.abort(); }; return this._enhancePromise(pipe); } return send(); }, _onAdd: function (e, data) { var that = this, result = true, options = $.extend({}, this.options, data), limit = options.limitMultiFileUploads, paramName = this._getParamName(options), paramNameSet, paramNameSlice, fileSet, i; if (!(options.singleFileUploads || limit) || !this._isXHRUpload(options)) { fileSet = [data.files]; paramNameSet = [paramName]; } else if (!options.singleFileUploads && limit) { fileSet = []; paramNameSet = []; for (i = 0; i < data.files.length; i += limit) { fileSet.push(data.files.slice(i, i + limit)); paramNameSlice = paramName.slice(i, i + limit); if (!paramNameSlice.length) { paramNameSlice = paramName; } paramNameSet.push(paramNameSlice); } } else { paramNameSet = paramName; } data.originalFiles = data.files; $.each(fileSet || data.files, function (index, element) { var newData = $.extend({}, data); newData.files = fileSet ? element : [element]; newData.paramName = paramNameSet[index]; that._initResponseObject(newData); that._initProgressObject(newData); that._addConvenienceMethods(e, newData); result = that._trigger('add', e, newData); return result; }); return result; }, _replaceFileInput: function (input) { var inputClone = input.clone(true); $('<form></form>').append(inputClone)[0].reset(); // Detaching allows to insert the fileInput on another form // without loosing the file input value: input.after(inputClone).detach(); // Avoid memory leaks with the detached file input: $.cleanData(input.unbind('remove')); // Replace the original file input element in the fileInput // elements set with the clone, which has been copied including // event handlers: this.options.fileInput = this.options.fileInput.map(function (i, el) { if (el === input[0]) { return inputClone[0]; } return el; }); // If the widget has been initialized on the file input itself, // override this.element with the file input clone: if (input[0] === this.element[0]) { this.element = inputClone; } }, _handleFileTreeEntry: function (entry, path) { var that = this, dfd = $.Deferred(), errorHandler = function (e) { if (e && !e.entry) { e.entry = entry; } // Since $.when returns immediately if one // Deferred is rejected, we use resolve instead. // This allows valid files and invalid items // to be returned together in one set: dfd.resolve([e]); }, dirReader; path = path || ''; if (entry.isFile) { if (entry._file) { // Workaround for Chrome bug #149735 entry._file.relativePath = path; dfd.resolve(entry._file); } else { entry.file(function (file) { file.relativePath = path; dfd.resolve(file); }, errorHandler); } } else if (entry.isDirectory) { dirReader = entry.createReader(); dirReader.readEntries(function (entries) { that._handleFileTreeEntries( entries, path + entry.name + '/' ).done(function (files) { dfd.resolve(files); }).fail(errorHandler); }, errorHandler); } else { // Return an empy list for file system items // other than files or directories: dfd.resolve([]); } return dfd.promise(); }, _handleFileTreeEntries: function (entries, path) { var that = this; return $.when.apply( $, $.map(entries, function (entry) { return that._handleFileTreeEntry(entry, path); }) ).pipe(function () { return Array.prototype.concat.apply( [], arguments ); }); }, _getDroppedFiles: function (dataTransfer) { dataTransfer = dataTransfer || {}; var items = dataTransfer.items; if (items && items.length && (items[0].webkitGetAsEntry || items[0].getAsEntry)) { return this._handleFileTreeEntries( $.map(items, function (item) { var entry; if (item.webkitGetAsEntry) { entry = item.webkitGetAsEntry(); if (entry) { // Workaround for Chrome bug #149735: entry._file = item.getAsFile(); } return entry; } return item.getAsEntry(); }) ); } return $.Deferred().resolve( $.makeArray(dataTransfer.files) ).promise(); }, _getSingleFileInputFiles: function (fileInput) { fileInput = $(fileInput); var entries = fileInput.prop('webkitEntries') || fileInput.prop('entries'), files, value; if (entries && entries.length) { return this._handleFileTreeEntries(entries); } files = $.makeArray(fileInput.prop('files')); if (!files.length) { value = fileInput.prop('value'); if (!value) { return $.Deferred().resolve([]).promise(); } // If the files property is not available, the browser does not // support the File API and we add a pseudo File object with // the input value as name with path information removed: files = [{name: value.replace(/^.*\\/, '')}]; } else if (files[0].name === undefined && files[0].fileName) { // File normalization for Safari 4 and Firefox 3: $.each(files, function (index, file) { file.name = file.fileName; file.size = file.fileSize; }); } return $.Deferred().resolve(files).promise(); }, _getFileInputFiles: function (fileInput) { if (!(fileInput instanceof $) || fileInput.length === 1) { return this._getSingleFileInputFiles(fileInput); } return $.when.apply( $, $.map(fileInput, this._getSingleFileInputFiles) ).pipe(function () { return Array.prototype.concat.apply( [], arguments ); }); }, _onChange: function (e) { var that = this, data = { fileInput: $(e.target), form: $(e.target.form) }; this._getFileInputFiles(data.fileInput).always(function (files) { data.files = files; if (that.options.replaceFileInput) { that._replaceFileInput(data.fileInput); } if (that._trigger('change', e, data) !== false) { that._onAdd(e, data); } }); }, _onPaste: function (e) { var items = e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.items, data = {files: []}; if (items && items.length) { $.each(items, function (index, item) { var file = item.getAsFile && item.getAsFile(); if (file) { data.files.push(file); } }); if (this._trigger('paste', e, data) === false || this._onAdd(e, data) === false) { return false; } } }, _onDrop: function (e) { e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer; var that = this, dataTransfer = e.dataTransfer, data = {}; if (dataTransfer && dataTransfer.files && dataTransfer.files.length) { e.preventDefault(); this._getDroppedFiles(dataTransfer).always(function (files) { data.files = files; if (that._trigger('drop', e, data) !== false) { that._onAdd(e, data); } }); } }, _onDragOver: function (e) { e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer; var dataTransfer = e.dataTransfer; if (dataTransfer) { if (this._trigger('dragover', e) === false) { return false; } if ($.inArray('Files', dataTransfer.types) !== -1) { dataTransfer.dropEffect = 'copy'; e.preventDefault(); } } }, _initEventHandlers: function () { if (this._isXHRUpload(this.options)) { this._on(this.options.dropZone, { dragover: this._onDragOver, drop: this._onDrop }); this._on(this.options.pasteZone, { paste: this._onPaste }); } if ($.support.fileInput) { this._on(this.options.fileInput, { change: this._onChange }); } }, _destroyEventHandlers: function () { this._off(this.options.dropZone, 'dragover drop'); this._off(this.options.pasteZone, 'paste'); this._off(this.options.fileInput, 'change'); }, _setOption: function (key, value) { var reinit = $.inArray(key, this._specialOptions) !== -1; if (reinit) { this._destroyEventHandlers(); } this._super(key, value); if (reinit) { this._initSpecialOptions(); this._initEventHandlers(); } }, _initSpecialOptions: function () { var options = this.options; if (options.fileInput === undefined) { options.fileInput = this.element.is('input[type="file"]') ? this.element : this.element.find('input[type="file"]'); } else if (!(options.fileInput instanceof $)) { options.fileInput = $(options.fileInput); } if (!(options.dropZone instanceof $)) { options.dropZone = $(options.dropZone); } if (!(options.pasteZone instanceof $)) { options.pasteZone = $(options.pasteZone); } }, _getRegExp: function (str) { var parts = str.split('/'), modifiers = parts.pop(); parts.shift(); return new RegExp(parts.join('/'), modifiers); }, _isRegExpOption: function (key, value) { return key !== 'url' && $.type(value) === 'string' && /^\/.*\/[igm]{0,3}$/.test(value); }, _initDataAttributes: function () { var that = this, options = this.options; // Initialize options set via HTML5 data-attributes: $.each( $(this.element[0].cloneNode(false)).data(), function (key, value) { if (that._isRegExpOption(key, value)) { value = that._getRegExp(value); } options[key] = value; } ); }, _create: function () { this._initDataAttributes(); this._initSpecialOptions(); this._slots = []; this._sequence = this._getXHRPromise(true); this._sending = this._active = 0; this._initProgressObject(this); this._initEventHandlers(); }, // This method is exposed to the widget API and allows to query // the number of active uploads: active: function () { return this._active; }, // This method is exposed to the widget API and allows to query // the widget upload progress. // It returns an object with loaded, total and bitrate properties // for the running uploads: progress: function () { return this._progress; }, // This method is exposed to the widget API and allows adding files // using the fileupload API. The data parameter accepts an object which // must have a files property and can contain additional options: // .fileupload('add', {files: filesList}); add: function (data) { var that = this; if (!data || this.options.disabled) { return; } if (data.fileInput && !data.files) { this._getFileInputFiles(data.fileInput).always(function (files) { data.files = files; that._onAdd(null, data); }); } else { data.files = $.makeArray(data.files); this._onAdd(null, data); } }, // This method is exposed to the widget API and allows sending files // using the fileupload API. The data parameter accepts an object which // must have a files or fileInput property and can contain additional options: // .fileupload('send', {files: filesList}); // The method returns a Promise object for the file upload call. send: function (data) { if (data && !this.options.disabled) { if (data.fileInput && !data.files) { var that = this, dfd = $.Deferred(), promise = dfd.promise(), jqXHR, aborted; promise.abort = function () { aborted = true; if (jqXHR) { return jqXHR.abort(); } dfd.reject(null, 'abort', 'abort'); return promise; }; this._getFileInputFiles(data.fileInput).always( function (files) { if (aborted) { return; } data.files = files; jqXHR = that._onSend(null, data).then( function (result, textStatus, jqXHR) { dfd.resolve(result, textStatus, jqXHR); }, function (jqXHR, textStatus, errorThrown) { dfd.reject(jqXHR, textStatus, errorThrown); } ); } ); return this._enhancePromise(promise); } data.files = $.makeArray(data.files); if (data.files.length) { return this._onSend(null, data); } } return this._getXHRPromise(false, data && data.context); } }); }));
gregmoser/muracon2016
www/admin/assets/js/jquery/jquery.fileupload.js
JavaScript
mit
57,130
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Defines the base class for a module. This is used to allow the * code to be modularized, giving the benefits of lazy loading and loading on * demand. * */ goog.provide('goog.module.BaseModule'); goog.require('goog.Disposable'); /** * A basic module object that represents a module of Javascript code that can * be dynamically loaded. * * @constructor * @extends {goog.Disposable} */ goog.module.BaseModule = function() { goog.Disposable.call(this); }; goog.inherits(goog.module.BaseModule, goog.Disposable); /** * Performs any load-time initialization that the module requires. * @param {Object} context The module context. */ goog.module.BaseModule.prototype.initialize = function(context) {};
dmincu/IOC
new_php/closure-library/closure/goog/module/basemodule.js
JavaScript
mit
1,411
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe OmniAuth::Strategies::SmugMug do it_should_behave_like 'an oauth strategy' end
sbhalerao/CIYH_ver3
oa-oauth/spec/omniauth/strategies/smug_mug_spec.rb
Ruby
mit
161
/* * Copyright (c) 2012 Dmitri Melikyan * * 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. */ var nt; var filterKeys; var sampleNum; exports.init = function() { nt = global.nodetime; filterKeys = {}; sampleNum = 0; nt.on('sample', function(sample) { if(!nt.headless && nt.sessionId) { collectKeys(undefined, sample, 0); sampleNum++; if(sampleNum == 1 || sampleNum == 10) { sendKeys(); } } }); setInterval(function() { try { sendKeys(); } catch(e) { nt.error(e); } }, 60000); }; var collectKeys = function(key, obj, depth) { if(depth > 20) return 0; var isArray = Array.isArray(obj); for(var prop in obj) { if(prop.match(/^\_/)) continue; if(typeof obj[prop] === 'object') { collectKeys(prop, obj[prop], depth + 1); } else { if(!isArray) { filterKeys[prop] = true; } else { filterKeys[key] = true; } } } }; var sendKeys = function() { var keys = []; for(var prop in filterKeys) { keys.push(prop); } keys = keys.sort(function(a, b) { a = a.toLowerCase(); b = b.toLowerCase(); if(a > b) return 1; if(a < b) return -1; return 0; }); if(keys.length > 0) { nt.agent.send({cmd: 'updateFilterKeys', args: keys}); } }; var PredicateFilter = function() { } exports.PredicateFilter = PredicateFilter; PredicateFilter.prototype.preparePredicates = function(preds) { preds.forEach(function(pred) { try{ pred.valNum = parseFloat(pred.val) } catch(err) { } try{ if(pred.op === 'match') pred.valRe = new RegExp(pred.val); if(typeof pred.val === 'string') pred.valLc = pred.val.toLowerCase(); } catch(err) { return nt.error(err); } }); this.preds = preds; return true; } PredicateFilter.prototype.filter = function(sample) { var matched = 0; this.preds.forEach(function(pred) { matched += walk(pred, sample, 0); }); return (matched > 0); }; function walk(pred, obj, depth) { if(depth > 20) return 0; var matched = 0; for(var prop in obj) { var val = obj[prop]; if(val === undefined || val === null) { continue; } else if(typeof val === 'object') { matched += walk(pred, val, depth + 1); } else if((pred.key === '*' || pred.key === prop) && test(pred, val)) { matched++; } if(matched) break; } return matched; } function test(pred, val) { var ret = false; if(typeof val === 'number') { if(pred.valNum !== NaN) { if (pred.op === '==') { ret = (val == pred.valNum); } else if (pred.op === '!=') { ret = (val != pred.valNum); } else if (pred.op === '<') { ret = (val < pred.valNum); } else if (pred.op === '>') { ret = (val > pred.valNum); } } } else if(typeof val === 'string') { if(pred.op === 'match' && pred.valRe) { ret = pred.valRe.exec(val); } else if (pred.op === '==') { ret = (val.toLowerCase() == pred.valLc); } else if (pred.op === '!=') { ret = (val.toLowerCase() != pred.valLc); } } return ret; }
umaar/nodetime
lib/filter.js
JavaScript
mit
4,266
/* * Version 0.1.14 * Made By Robin Kuiper * Skype: RobinKuiper.eu * Discord: Atheos#1095 * My Discord Server: https://discord.gg/AcC9VME * Roll20: https://app.roll20.net/users/1226016/robin * Roll20 Wiki: https://wiki.roll20.net/Script:Concentration * Roll20 Thread: https://app.roll20.net/forum/post/6364317/script-concentration/?pageforid=6364317#post-6364317 * Github: https://github.com/RobinKuiper/Roll20APIScripts * Reddit: https://www.reddit.com/user/robinkuiper/ * Patreon: https://patreon.com/robinkuiper * Paypal.me: https://www.paypal.me/robinkuiper */ var Concentration = Concentration || (function() { 'use strict'; let checked = []; // Styling for the chat responses. const styles = { reset: 'padding: 0; margin: 0;', menu: 'background-color: #fff; border: 1px solid #000; padding: 5px; border-radius: 5px;', button: 'background-color: #000; border: 1px solid #292929; border-radius: 3px; padding: 5px; color: #fff; text-align: center;', textButton: 'background-color: transparent; border: none; padding: 0; color: #000; text-decoration: underline', list: 'list-style: none;', float: { right: 'float: right;', left: 'float: left;' }, overflow: 'overflow: hidden;', fullWidth: 'width: 100%;' }, script_name = 'Concentration', state_name = 'CONCENTRATION', markers = ['blue', 'brown', 'green', 'pink', 'purple', 'red', 'yellow', '-', 'all-for-one', 'angel-outfit', 'archery-target', 'arrowed', 'aura', 'back-pain', 'black-flag', 'bleeding-eye', 'bolt-shield', 'broken-heart', 'broken-shield', 'broken-skull', 'chained-heart', 'chemical-bolt', 'cobweb', 'dead', 'death-zone', 'drink-me', 'edge-crack', 'fishing-net', 'fist', 'fluffy-wing', 'flying-flag', 'frozen-orb', 'grab', 'grenade', 'half-haze', 'half-heart', 'interdiction', 'lightning-helix', 'ninja-mask', 'overdrive', 'padlock', 'pummeled', 'radioactive', 'rolling-tomb', 'screaming', 'sentry-gun', 'skull', 'sleepy', 'snail', 'spanner', 'stopwatch','strong', 'three-leaves', 'tread', 'trophy', 'white-tower'], handleInput = (msg) => { if(state[state_name].config.auto_add_concentration_marker && msg && msg.rolltemplate && msg.rolltemplate === 'spell' && (msg.content.includes("{{concentration=1}}"))){ handleConcentrationSpellCast(msg); } if (msg.type != 'api') return; // Split the message into command and argument(s) let args = msg.content.split(' '); let command = args.shift().substring(1); let extracommand = args.shift(); let message; if (command == state[state_name].config.command) { if(playerIsGM(msg.playerid)){ switch(extracommand){ case 'reset': state[state_name] = {}; setDefaults(true); sendConfigMenu(false, '<span style="color: red">The API Library needs to be restarted for this to take effect.</span>'); break; case 'config': if(args.length > 0){ let setting = args.shift().split('|'); let key = setting.shift(); let value = (setting[0] === 'true') ? true : (setting[0] === 'false') ? false : setting[0]; state[state_name].config[key] = value; if(key === 'bar'){ //registerEventHandlers(); message = '<span style="color: red">The API Library needs to be restarted for this to take effect.</span>'; } } sendConfigMenu(false, message); break; case 'advantage-menu': sendAdvantageMenu(); break; case 'toggle-advantage': let id = args[0]; if(state[state_name].advantages[id]){ state[state_name].advantages[id] = !state[state_name].advantages[id]; }else{ state[state_name].advantages[id] = true; } sendAdvantageMenu(); break; case 'roll': let represents = args[0], DC = parseInt(args[1], 10), con_save_mod = parseInt(args[2], 10), name = args[3], target = args[4]; roll(represents, DC, con_save_mod, name, target, false); break; case 'advantage': let represents_a = args[0], DC_a = parseInt(args[1], 10), con_save_mod_a = parseInt(args[2], 10), name_a = args[3], target_a = args[4]; roll(represents_a, DC_a, con_save_mod_a, name_a, target_a, true); break; default: if(msg.selected && msg.selected.length){ msg.selected.forEach(s => { let token = getObj(s._type, s._id); addConcentration(token, msg.playerid, extracommand); }); return; } sendConfigMenu(); break; } }else{ if(msg.selected && msg.selected.length){ msg.selected.forEach(s => { let token = getObj(s._type, s._id); addConcentration(token, msg.playerid, extracommand); }); } } } }, addConcentration = (token, playerid, spell) => { const marker = state[state_name].config.statusmarker let character = getObj('character', token.get('represents')); if((token.get('controlledby').split(',').includes(playerid) || token.get('controlledby').split(',').includes('all')) || (character && (character.get('controlledby').split(',').includes(playerid) || character.get('controlledby').split(',').includes('all'))) || playerIsGM(playerid)){ if(!token.get('status_'+marker)){ let target = state[state_name].config.send_reminder_to; if(target === 'character'){ target = createWhisperName(character_name); }else if(target === 'everyone'){ target = '' } let message; if(spell){ message = '<b>'+token.get('name')+'</b> is now concentrating on <b>'+spell+'</b>.'; }else{ message = '<b>'+token.get('name')+'</b> is now concentrating.'; } makeAndSendMenu(message, '', target); } token.set('status_'+marker, !token.get('status_'+marker)); } }, handleConcentrationSpellCast = (msg) => { const marker = state[state_name].config.statusmarker let character_name = msg.content.match(/charname=([^\n{}]*[^"\n{}])/); character_name = RegExp.$1; let spell_name = msg.content.match(/name=([^\n{}]*[^"\n{}])/); spell_name = RegExp.$1; let player = getObj('player', msg.playerid), characterid = findObjs({ name: character_name, _type: 'character' }).shift().get('id'), represented_tokens = findObjs({ represents: characterid, _type: 'graphic' }), message, target = state[state_name].config.send_reminder_to; if(!character_name || !spell_name || !player || !characterid) return; let search_attributes = { represents: characterid, _type: 'graphic', _pageid: player.get('lastpage') } search_attributes['status_'+marker] = true; let is_concentrating = (findObjs(search_attributes).length > 0); if(is_concentrating){ message = '<b>'+character_name+'</b> is concentrating already.'; }else{ represented_tokens.forEach(token => { let attributes = {}; attributes['status_'+marker] = true; token.set(attributes); message = '<b>'+character_name+'</b> is now concentrating on <b>'+spell_name+'</b>.'; }); } if(target === 'character'){ target = createWhisperName(character_name); }else if(target === 'everyone'){ target = '' } makeAndSendMenu(message, '', target); }, handleStatusMarkerChange = (obj, prev) => { const marker = state[state_name].config.statusmarker if(!obj.get('status_'+marker)){ removeMarker(obj.get('represents')); } }, handleGraphicChange = (obj, prev) => { if(checked.includes(obj.get('represents'))){ return false; } let bar = 'bar'+state[state_name].config.bar+'_value', target = state[state_name].config.send_reminder_to, marker = state[state_name].config.statusmarker; if(prev && obj.get('status_'+marker) && obj.get(bar) < prev[bar]){ let calc_DC = Math.floor((prev[bar] - obj.get(bar))/2), DC = (calc_DC > 10) ? calc_DC : 10, con_save_mod = parseInt(getAttrByName(obj.get('represents'), state[state_name].config.bonus_attribute, 'current')) || 0, chat_text; if(target === 'character'){ chat_text = "Make a Concentration Check - <b>DC " + DC + "</b>."; target = createWhisperName(obj.get('name')); }else if(target === 'everyone'){ chat_text = '<b>'+obj.get('name')+'</b> must make a Concentration Check - <b>DC ' + DC + '</b>.'; target = ''; }else{ chat_text = '<b>'+obj.get('name')+'</b> must make a Concentration Check - <b>DC ' + DC + '</b>.'; target = 'gm'; } if(state[state_name].config.show_roll_button){ chat_text += '<hr>' + makeButton('Advantage', '!' + state[state_name].config.command + ' advantage ' + obj.get('represents') + ' ' + DC + ' ' + con_save_mod + ' ' + obj.get('name') + ' ' + target, styles.button + styles.float.right); chat_text += '&nbsp;' + makeButton('Roll', '!' + state[state_name].config.command + ' roll ' + obj.get('represents') + ' ' + DC + ' ' + con_save_mod + ' ' + obj.get('name') + ' ' + target, styles.button + styles.float.left); } if(state[state_name].config.auto_roll_save){ //&{template:default} {{name='+obj.get('name')+' - Concentration Save}} {{Modifier='+con_save_mod+'}} {{Roll=[[1d20cf<'+(DC-con_save_mod-1)+'cs>'+(DC-con_save_mod-1)+'+'+con_save_mod+']]}} {{DC='+DC+'}} roll(obj.get('represents'), DC, con_save_mod, obj.get('name'), target, state[state_name].advantages[obj.get('represents')]); }else{ makeAndSendMenu(chat_text, '', target); } let length = checked.push(obj.get('represents')); setTimeout(() => { checked.splice(length-1, 1); }, 1000); } }, roll = (represents, DC, con_save_mod, name, target, advantage) => { sendChat(script_name, '[[1d20cf<'+(DC-con_save_mod-1)+'cs>'+(DC-con_save_mod-1)+'+'+con_save_mod+']]', results => { let title = 'Concentration Save <br> <b style="font-size: 10pt; color: gray;">'+name+'</b>', advantageRollResult; let rollresult = results[0].inlinerolls[0].results.rolls[0].results[0].v; let result = rollresult; if(advantage){ advantageRollResult = randomInteger(20); result = (rollresult <= advantageRollResult) ? advantageRollResult : rollresult; } let total = result + con_save_mod; let success = total >= DC; let result_text = (success) ? 'Success' : 'Failed', result_color = (success) ? 'green' : 'red'; let rollResultString = (advantage) ? rollresult + ' / ' + advantageRollResult : rollresult; let contents = ' \ <table style="width: 100%; text-align: left;"> \ <tr> \ <th>DC</th> \ <td>'+DC+'</td> \ </tr> \ <tr> \ <th>Modifier</th> \ <td>'+con_save_mod+'</td> \ </tr> \ <tr> \ <th>Roll Result</th> \ <td>'+rollResultString+'</td> \ </tr> \ </table> \ <div style="text-align: center"> \ <b style="font-size: 16pt;"> \ <span style="border: 1px solid '+result_color+'; padding-bottom: 2px; padding-top: 4px;">[['+result+'+'+con_save_mod+']]</span><br><br> \ '+result_text+' \ </b> \ </div>' makeAndSendMenu(contents, title, target); if(target !== '' && target !== 'gm'){ makeAndSendMenu(contents, title, 'gm'); } if(!success){ removeMarker(represents); } }); }, removeMarker = (represents, type='graphic') => { findObjs({ type, represents }).forEach(o => { o.set('status_'+state[state_name].config.statusmarker, false); }); }, createWhisperName = (name) => { return name.split(' ').shift(); }, ucFirst = (string) => { return string.charAt(0).toUpperCase() + string.slice(1); }, sendConfigMenu = (first, message) => { let markerDropdown = '?{Marker'; markers.forEach((marker) => { markerDropdown += '|'+ucFirst(marker).replace('-', ' ')+','+marker }) markerDropdown += '}'; let markerButton = makeButton(state[state_name].config.statusmarker, '!' + state[state_name].config.command + ' config statusmarker|'+markerDropdown, styles.button + styles.float.right), commandButton = makeButton('!'+state[state_name].config.command, '!' + state[state_name].config.command + ' config command|?{Command (without !)}', styles.button + styles.float.right), barButton = makeButton('bar ' + state[state_name].config.bar, '!' + state[state_name].config.command + ' config bar|?{Bar|Bar 1 (green),1|Bar 2 (blue),2|Bar 3 (red),3}', styles.button + styles.float.right), sendToButton = makeButton(state[state_name].config.send_reminder_to, '!' + state[state_name].config.command + ' config send_reminder_to|?{Send To|Everyone,everyone|Character,character|GM,gm}', styles.button + styles.float.right), addConMarkerButton = makeButton(state[state_name].config.auto_add_concentration_marker, '!' + state[state_name].config.command + ' config auto_add_concentration_marker|'+!state[state_name].config.auto_add_concentration_marker, styles.button + styles.float.right), autoRollButton = makeButton(state[state_name].config.auto_roll_save, '!' + state[state_name].config.command + ' config auto_roll_save|'+!state[state_name].config.auto_roll_save, styles.button + styles.float.right), //advantageButton = makeButton(state[state_name].config.advantage, '!' + state[state_name].config.command + ' config advantage|'+!state[state_name].config.advantage, styles.button + styles.float.right), bonusAttrButton = makeButton(state[state_name].config.bonus_attribute, '!' + state[state_name].config.command + ' config bonus_attribute|?{Attribute|'+state[state_name].config.bonus_attribute+'}', styles.button + styles.float.right), showRollButtonButton = makeButton(state[state_name].config.show_roll_button, '!' + state[state_name].config.command + ' config show_roll_button|'+!state[state_name].config.show_roll_button, styles.button + styles.float.right), listItems = [ '<span style="'+styles.float.left+'">Command:</span> ' + commandButton, '<span style="'+styles.float.left+'">Statusmarker:</span> ' + markerButton, '<span style="'+styles.float.left+'">HP Bar:</span> ' + barButton, '<span style="'+styles.float.left+'">Send Reminder To:</span> ' + sendToButton, '<span style="'+styles.float.left+'">Auto Add Con. Marker: <p style="font-size: 8pt;">Works only for 5e OGL Sheet.</p></span> ' + addConMarkerButton, '<span style="'+styles.float.left+'">Auto Roll Save:</span> ' + autoRollButton, ], resetButton = makeButton('Reset', '!' + state[state_name].config.command + ' reset', styles.button + styles.fullWidth), title_text = (first) ? script_name + ' First Time Setup' : script_name + ' Config'; /*if(state[state_name].config.auto_roll_save){ listItems.push('<span style="'+styles.float.left+'">Advantage:</span> ' + advantageButton); }*/ if(state[state_name].config.auto_roll_save){ listItems.push('<span style="'+styles.float.left+'">Bonus Attribute:</span> ' + bonusAttrButton) } if(!state[state_name].config.auto_roll_save){ listItems.push('<span style="'+styles.float.left+'">Roll Button:</span> ' + showRollButtonButton); } let advantageMenuButton = (state[state_name].config.auto_roll_save) ? makeButton('Advantage Menu', '!' + state[state_name].config.command + ' advantage-menu', styles.button + styles.fullWidth) : ''; message = (message) ? '<p>'+message+'</p>' : ''; let contents = message+makeList(listItems, styles.reset + styles.list + styles.overflow, styles.overflow)+'<br>'+advantageMenuButton+'<hr><p style="font-size: 80%">You can always come back to this config by typing `!'+state[state_name].config.command+' config`.</p><hr>'+resetButton; makeAndSendMenu(contents, title_text, 'gm'); }, sendAdvantageMenu = () => { let menu_text = ""; let characters = findObjs({ type: 'character' }).sort((a, b) => { let nameA = a.get('name').toUpperCase(); let nameB = b.get('name').toUpperCase(); if(nameA < nameB) return -1; if(nameA > nameB) return 1; return 0; }); characters.forEach(character => { let name = (state[state_name].advantages && state[state_name].advantages[character.get('id')]) ? '<b>'+character.get('name')+'</b>' : character.get('name'); menu_text += makeButton(name, '!' + state[state_name].config.command + ' toggle-advantage ' + character.get('id'), styles.textButton) + '<br>'; }); makeAndSendMenu(menu_text, 'Advantage Menu', 'gm'); }, makeAndSendMenu = (contents, title, whisper, callback) => { title = (title && title != '') ? makeTitle(title) : ''; whisper = (whisper && whisper !== '') ? '/w ' + whisper + ' ' : ''; sendChat(script_name, whisper + '<div style="'+styles.menu+styles.overflow+'">'+title+contents+'</div>', null, {noarchive:true}); }, makeTitle = (title) => { return '<h3 style="margin-bottom: 10px;">'+title+'</h3>'; }, makeButton = (title, href, style) => { return '<a style="'+style+'" href="'+href+'">'+title+'</a>'; }, makeList = (items, listStyle, itemStyle) => { let list = '<ul style="'+listStyle+'">'; items.forEach((item) => { list += '<li style="'+itemStyle+'">'+item+'</li>'; }); list += '</ul>'; return list; }, pre_log = (message) => { log('---------------------------------------------------------------------------------------------'); if(!message){ return; } log(message); log('---------------------------------------------------------------------------------------------'); }, checkInstall = () => { if(!_.has(state, state_name)){ state[state_name] = state[state_name] || {}; } setDefaults(); log(script_name + ' Ready! Command: !'+state[state_name].config.command); if(state[state_name].config.debug){ makeAndSendMenu(script_name + ' Ready! Debug On.', '', 'gm') } }, registerEventHandlers = () => { on('chat:message', handleInput); on('change:graphic:bar'+state[state_name].config.bar+'_value', handleGraphicChange); on('change:graphic:statusmarkers', handleStatusMarkerChange); }, setDefaults = (reset) => { const defaults = { config: { command: 'concentration', statusmarker: 'stopwatch', bar: 1, send_reminder_to: 'everyone', // character,gm, auto_add_concentration_marker: true, auto_roll_save: true, advantage: false, bonus_attribute: 'constitution_save_bonus', show_roll_button: true }, advantages: {} }; if(!state[state_name].config){ state[state_name].config = defaults.config; }else{ if(!state[state_name].config.hasOwnProperty('command')){ state[state_name].config.command = defaults.config.command; } if(!state[state_name].config.hasOwnProperty('statusmarker')){ state[state_name].config.statusmarker = defaults.config.statusmarker; } if(!state[state_name].config.hasOwnProperty('bar')){ state[state_name].config.bar = defaults.config.bar; } if(!state[state_name].config.hasOwnProperty('send_reminder_to')){ state[state_name].config.send_reminder_to = defaults.config.send_reminder_to; } if(!state[state_name].config.hasOwnProperty('auto_add_concentration_marker')){ state[state_name].config.auto_add_concentration_marker = defaults.config.auto_add_concentration_marker; } if(!state[state_name].config.hasOwnProperty('auto_roll_save')){ state[state_name].config.auto_roll_save = defaults.config.auto_roll_save; } if(!state[state_name].config.hasOwnProperty('advantage')){ state[state_name].config.advantage = defaults.config.advantage; } if(!state[state_name].config.hasOwnProperty('bonus_attribute')){ state[state_name].config.bonus_attribute = defaults.config.bonus_attribute; } if(!state[state_name].config.hasOwnProperty('show_roll_button')){ state[state_name].config.show_roll_button = defaults.config.show_roll_button; } } if(!state[state_name].advantages){ state[state_name].advantages = defaults.advantages; } if(!state[state_name].config.hasOwnProperty('firsttime') && !reset){ sendConfigMenu(true); state[state_name].config.firsttime = false; } }; return { CheckInstall: checkInstall, RegisterEventHandlers: registerEventHandlers } })(); on('ready',function() { 'use strict'; Concentration.CheckInstall(); Concentration.RegisterEventHandlers(); });
NathaTerrien/Natha-roll20-api-scripts
Concentration/Concentration.js
JavaScript
mit
23,944
""" Strictly internal utilities. """ from __future__ import absolute_import, division, print_function from twisted.web.client import HTTPConnectionPool def default_reactor(reactor): """ Return the specified reactor or the default. """ if reactor is None: from twisted.internet import reactor return reactor _global_pool = [None] def get_global_pool(): return _global_pool[0] def set_global_pool(pool): _global_pool[0] = pool def default_pool(reactor, pool, persistent): """ Return the specified pool or a a pool with the specified reactor and persistence. """ reactor = default_reactor(reactor) if pool is not None: return pool if persistent is False: return HTTPConnectionPool(reactor, persistent=persistent) if get_global_pool() is None: set_global_pool(HTTPConnectionPool(reactor, persistent=True)) return get_global_pool()
glyph/treq
treq/_utils.py
Python
mit
940
Polymer('selection-example', { itemTapAction: function(e, detail, sender) { this.$.selection.select(e.target); }, selectAction: function(e, detail, sender) { detail.item.classList.toggle('selected', detail.isSelected); } });
sunglim/csp_fixer
test_resource/core_elements_expected/src/core-selection/demo.html.0.js
JavaScript
mit
278
<?php if(!class_exists('Aws\S3\S3Client')) { $autoloader = __DIR__ . '/vendor/aws-autoloader.php'; if(file_exists($autoloader)) { require_once($autoloader); } else { throw new Exception("AWS autoloader not found."); } } use Aws\S3\S3Client; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; /** * Class Storage * Based on https://github.com/frostealth/yii2-aws-s3 * * PHP SDK not included, so you have to install it manually: * https://github.com/aws/aws-sdk-php * Remember to install all dependencies listed in * https://github.com/aws/aws-sdk-php/blob/master/composer.json */ class S3StorageHelper { const ACL_PRIVATE = 'private'; const ACL_PUBLIC_READ = 'public-read'; const ACL_PUBLIC_READ_WRITE = 'public-read-write'; const ACL_AUTHENTICATED_READ = 'authenticated-read'; const ACL_BUCKET_OWNER_READ = 'bucket-owner-read'; const ALC_BUCKET_OWNER_FULL_CONTROL = 'bucket-owner-full-control'; /** * @var \Aws\Credentials\CredentialsInterface|array|callable */ public $credentials; /** * @var string */ public $region; /** * @var string */ public $bucket; /** * @var string */ public $cdnHostname; /** * @var string */ public $defaultAcl; /** * @var bool|array */ public $debug = false; /** * @var array */ public $options = []; /** * @var S3Client */ private $client; /** * @throws Exception */ public function init() { if (empty($this->credentials)) { throw new Exception('S3 credentials isn\'t set.'); } if (empty($this->region)) { throw new Exception('Region isn\'t set.'); } if (empty($this->bucket)) { throw new Exception('You must set bucket name.'); } if (!empty($this->cdnHostname)) { $this->cdnHostname = rtrim($this->cdnHostname, '/'); } $args = $this->prepareArgs($this->options, [ 'version' => '2006-03-01', 'region' => $this->region, 'credentials' => $this->credentials, 'debug' => $this->debug, ]); $this->client = new S3Client($args); // to use PHP functions like copy(), rename() etc. // https://docs.aws.amazon.com/aws-sdk-php/v3/guide/service/s3-stream-wrapper.html $this->client->registerStreamWrapper(); } /** * @return S3Client */ public function getClient() { return $this->client; } /** * @inheritDoc */ public function put($key, $data, $acl = null, array $options = []) { $args = $this->prepareArgs($options, [ 'Bucket' => $this->bucket, 'Key' => $key, 'Body' => $data, 'ACL' => !empty($acl) ? $acl : $this->defaultAcl, ]); return $this->execute('PutObject', $args); } /** * @inheritDoc */ public function get($key, $saveAs = null) { $args = $this->prepareArgs([ 'Bucket' => $this->bucket, 'Key' => $key, 'SaveAs' => $saveAs, ]); return $this->execute('GetObject', $args); } /** * @inheritDoc */ public function exist($key, array $options = []) { return $this->getClient()->doesObjectExist($this->bucket, $key, $options); } /** * @inheritDoc */ public function delete($key) { return $this->execute('DeleteObject', [ 'Bucket' => $this->bucket, 'Key' => $key, ]); } /** * @inheritDoc */ public function getUrl($key) { return $this->getClient()->getObjectUrl($this->bucket, $key); } /** * @inheritDoc */ public function getPresignedUrl($key, $expires) { $command = $this->getClient()->getCommand('GetObject', ['Bucket' => $this->bucket, 'Key' => $key]); $request = $this->getClient()->createPresignedRequest($command, $expires); return (string)$request->getUri(); } /** * @inheritDoc */ public function getCdnUrl($key) { return $this->cdnHostname . '/' . $key; } /** * @inheritDoc */ public function getList($prefix = null, array $options = []) { $args = $this->prepareArgs($options, [ 'Bucket' => $this->bucket, 'Prefix' => $prefix, ]); return $this->execute('ListObjects', $args); } /** * @inheritDoc */ public function upload($key, $source, $acl = null, array $options = []) { return $this->getClient()->upload( $this->bucket, $key, $this->toStream($source), !empty($acl) ? $acl : $this->defaultAcl, $options ); } /** * @inheritDoc */ public function uploadAsync( $key, $source, $concurrency = null, $partSize = null, $acl = null, array $options = [] ) { $args = $this->prepareArgs($options, [ 'concurrency' => $concurrency, 'part_size' => $partSize, ]); return $this->getClient()->uploadAsync( $this->bucket, $key, $this->toStream($source), !empty($acl) ? $acl : $this->defaultAcl, $args ); } /** * @param string $name * @param array $args * @return \Aws\ResultInterface */ protected function execute($name, array $args) { $command = $this->getClient()->getCommand($name, $args); return $this->getClient()->execute($command); } /** * @param array $a * @return array */ protected function prepareArgs(array $a) { $result = []; $args = func_get_args(); foreach ($args as $item) { $item = array_filter($item); $result = array_replace($result, $item); } return $result; } /** * Create a new stream based on the input type. * @param resource|string|StreamInterface $source path to a local file, resource or stream * @return StreamInterface */ protected function toStream($source) { if (is_string($source)) { $source = Psr7\try_fopen($source, 'r+'); } return Psr7\stream_for($source); } /** * @param $key * @param bool $handle - returns FALSE if object doesn't exists or access is denied * @return \Aws\ResultInterface|bool */ public function head($key, $handle = false) { $args = [ 'Bucket' => $this->bucket, 'Key' => $key, ]; if(!$handle) { return $this->execute('HeadObject', $args); } else { $command = $this->getClient()->getCommand('HeadObject', $args); /* @see \Aws\S3\S3Client::checkExistenceWithCommand(), moved here to avoid extra request */ try { return $this->getClient()->execute($command); } catch (\Aws\S3\Exception\S3Exception $e) { if ($e->getStatusCode() >= 500) { throw $e; } return false; } } } /** * @param $key * @param $destination * @param $acl * @param $options * @return \Aws\ResultInterface|bool */ public function copy($key, $destination, $acl = null, array $options = []) { return $this->getClient()->copy( $this->bucket, $key, $this->bucket, $destination, !empty($acl) ? $acl : $this->defaultAcl, $options ); } /** * @param $key */ public function batchDelete($key) { $this->getClient()->deleteMatchingObjects($this->bucket, $key); } /** * @param $key * @param $destination * @return bool */ public function rename($key, $destination) { $bucket = $this->bucket; $isDir = is_dir("s3://{$bucket}/{$key}"); if($isDir) { $result = $this->getList($key); if(!isset($result['Contents'])) { return false; } foreach ($result['Contents'] as $object) { $newPath = str_replace($key, $destination, $object['Key']); rename("s3://{$bucket}/{$object['Key']}", "s3://{$bucket}/{$newPath}"); } } else { rename("s3://{$bucket}/{$key}", "s3://{$bucket}/{$destination}"); } return true; } }
dflm25/codeigniteres.club
public/plugins/ckeditor/plugins/RichFilemanager-master/connectors/php/plugins/s3/S3StorageHelper.php
PHP
mit
8,771
from __future__ import absolute_import from django.core.exceptions import PermissionDenied from django.db import models from django.contrib.auth import authenticate from django.contrib.sites.models import Site from django.utils.encoding import python_2_unicode_compatible from django.utils.crypto import get_random_string from django.utils.translation import ugettext_lazy as _ try: from django.utils.encoding import force_text except ImportError: from django.utils.encoding import force_unicode as force_text import allauth.app_settings from allauth.account.models import EmailAddress from allauth.account.utils import get_next_redirect_url, setup_user_email from allauth.utils import (get_user_model, serialize_instance, deserialize_instance) from . import app_settings from . import providers from .fields import JSONField from ..utils import get_request_param class SocialAppManager(models.Manager): def get_current(self, provider): site = Site.objects.get_current() return self.get(sites__id=site.id, provider=provider) @python_2_unicode_compatible class SocialApp(models.Model): objects = SocialAppManager() provider = models.CharField(verbose_name=_('provider'), max_length=30, choices=providers.registry.as_choices()) name = models.CharField(verbose_name=_('name'), max_length=40) client_id = models.CharField(verbose_name=_('client id'), max_length=100, help_text=_('App ID, or consumer key')) secret = models.CharField(verbose_name=_('secret key'), max_length=100, help_text=_('API secret, client secret, or' ' consumer secret')) key = models.CharField(verbose_name=_('key'), max_length=100, blank=True, help_text=_('Key')) # Most apps can be used across multiple domains, therefore we use # a ManyToManyField. Note that Facebook requires an app per domain # (unless the domains share a common base name). # blank=True allows for disabling apps without removing them sites = models.ManyToManyField(Site, blank=True) class Meta: verbose_name = _('social application') verbose_name_plural = _('social applications') def __str__(self): return self.name @python_2_unicode_compatible class SocialAccount(models.Model): user = models.ForeignKey(allauth.app_settings.USER_MODEL) provider = models.CharField(verbose_name=_('provider'), max_length=30, choices=providers.registry.as_choices()) # Just in case you're wondering if an OpenID identity URL is going # to fit in a 'uid': # # Ideally, URLField(max_length=1024, unique=True) would be used # for identity. However, MySQL has a max_length limitation of 255 # for URLField. How about models.TextField(unique=True) then? # Well, that won't work either for MySQL due to another bug[1]. So # the only way out would be to drop the unique constraint, or # switch to shorter identity URLs. Opted for the latter, as [2] # suggests that identity URLs are supposed to be short anyway, at # least for the old spec. # # [1] http://code.djangoproject.com/ticket/2495. # [2] http://openid.net/specs/openid-authentication-1_1.html#limits uid = models.CharField(verbose_name=_('uid'), max_length=255) last_login = models.DateTimeField(verbose_name=_('last login'), auto_now=True) date_joined = models.DateTimeField(verbose_name=_('date joined'), auto_now_add=True) extra_data = JSONField(verbose_name=_('extra data'), default='{}') class Meta: unique_together = ('provider', 'uid') verbose_name = _('social account') verbose_name_plural = _('social accounts') def authenticate(self): return authenticate(account=self) def __str__(self): return force_text(self.user) def get_profile_url(self): return self.get_provider_account().get_profile_url() def get_avatar_url(self): return self.get_provider_account().get_avatar_url() def get_provider(self): return providers.registry.by_id(self.provider) def get_provider_account(self): return self.get_provider().wrap_account(self) @python_2_unicode_compatible class SocialToken(models.Model): app = models.ForeignKey(SocialApp) account = models.ForeignKey(SocialAccount) token = models \ .TextField(verbose_name=_('token'), help_text=_('"oauth_token" (OAuth1) or access token' ' (OAuth2)')) token_secret = models \ .TextField(blank=True, verbose_name=_('token secret'), help_text=_('"oauth_token_secret" (OAuth1) or refresh' ' token (OAuth2)')) expires_at = models.DateTimeField(blank=True, null=True, verbose_name=_('expires at')) class Meta: unique_together = ('app', 'account') verbose_name = _('social application token') verbose_name_plural = _('social application tokens') def __str__(self): return self.token class SocialLogin(object): """ Represents a social user that is in the process of being logged in. This consists of the following information: `account` (`SocialAccount` instance): The social account being logged in. Providers are not responsible for checking whether or not an account already exists or not. Therefore, a provider typically creates a new (unsaved) `SocialAccount` instance. The `User` instance pointed to by the account (`account.user`) may be prefilled by the provider for use as a starting point later on during the signup process. `token` (`SocialToken` instance): An optional access token token that results from performing a successful authentication handshake. `state` (`dict`): The state to be preserved during the authentication handshake. Note that this state may end up in the url -- do not put any secrets in here. It currently only contains the url to redirect to after login. `email_addresses` (list of `EmailAddress`): Optional list of e-mail addresses retrieved from the provider. """ def __init__(self, user=None, account=None, token=None, email_addresses=[]): if token: assert token.account is None or token.account == account self.token = token self.user = user self.account = account self.email_addresses = email_addresses self.state = {} def connect(self, request, user): self.user = user self.save(request, connect=True) def serialize(self): ret = dict(account=serialize_instance(self.account), user=serialize_instance(self.user), state=self.state, email_addresses=[serialize_instance(ea) for ea in self.email_addresses]) if self.token: ret['token'] = serialize_instance(self.token) return ret @classmethod def deserialize(cls, data): account = deserialize_instance(SocialAccount, data['account']) user = deserialize_instance(get_user_model(), data['user']) if 'token' in data: token = deserialize_instance(SocialToken, data['token']) else: token = None email_addresses = [] for ea in data['email_addresses']: email_address = deserialize_instance(EmailAddress, ea) email_addresses.append(email_address) ret = SocialLogin() ret.token = token ret.account = account ret.user = user ret.email_addresses = email_addresses ret.state = data['state'] return ret def save(self, request, connect=False): """ Saves a new account. Note that while the account is new, the user may be an existing one (when connecting accounts) """ assert not self.is_existing user = self.user user.save() self.account.user = user self.account.save() if app_settings.STORE_TOKENS and self.token: self.token.account = self.account self.token.save() if connect: # TODO: Add any new email addresses automatically? pass else: setup_user_email(request, user, self.email_addresses) @property def is_existing(self): """ Account is temporary, not yet backed by a database record. """ return self.account.pk def lookup(self): """ Lookup existing account, if any. """ assert not self.is_existing try: a = SocialAccount.objects.get(provider=self.account.provider, uid=self.account.uid) # Update account a.extra_data = self.account.extra_data self.account = a self.user = self.account.user a.save() # Update token if app_settings.STORE_TOKENS and self.token: assert not self.token.pk try: t = SocialToken.objects.get(account=self.account, app=self.token.app) t.token = self.token.token if self.token.token_secret: # only update the refresh token if we got one # many oauth2 providers do not resend the refresh token t.token_secret = self.token.token_secret t.expires_at = self.token.expires_at t.save() self.token = t except SocialToken.DoesNotExist: self.token.account = a self.token.save() except SocialAccount.DoesNotExist: pass def get_redirect_url(self, request): url = self.state.get('next') return url @classmethod def state_from_request(cls, request): state = {} next_url = get_next_redirect_url(request) if next_url: state['next'] = next_url state['process'] = get_request_param(request, 'process', 'login') state['scope'] = get_request_param(request, 'scope', '') state['auth_params'] = get_request_param(request, 'auth_params', '') return state @classmethod def stash_state(cls, request): state = cls.state_from_request(request) verifier = get_random_string() request.session['socialaccount_state'] = (state, verifier) return verifier @classmethod def unstash_state(cls, request): if 'socialaccount_state' not in request.session: raise PermissionDenied() state, verifier = request.session.pop('socialaccount_state') return state @classmethod def verify_and_unstash_state(cls, request, verifier): if 'socialaccount_state' not in request.session: raise PermissionDenied() state, verifier2 = request.session.pop('socialaccount_state') if verifier != verifier2: raise PermissionDenied() return state
tejesh95/Zubio.in
zubio/allauth/socialaccount/models.py
Python
mit
11,718
/** * Browser platform description */ SB.createPlatform('browser', { keys: { RIGHT: 39, LEFT: 37, DOWN: 40, UP: 38, RETURN: 27,//esc EXIT: 46,//delete TOOLS: 32,//space FF: 33,//page up RW: 34,//page down NEXT: 107,//num+ PREV: 109,//num- ENTER: 13, RED: 65,//A GREEN: 66,//B YELLOW: 67,//C BLUE: 68,//D CH_UP: 221, // ] CH_DOWN: 219, // [ N0: 48, N1: 49, N2: 50, N3: 51, N4: 52, N5: 53, N6: 54, N7: 55, N8: 56, N9: 57, PRECH: 45,//ins SMART: 36,//home PLAY: 97,//numpad 1 STOP: 98,//numpad 2 PAUSE: 99,//numpad 3 SUBT: 76,//l, INFO: 73,//i REC: 82//r }, detect: function () { // always true for browser platform return true; }, getNativeDUID: function () { if (navigator.userAgent.indexOf('Chrome') != -1) { this.DUID = 'CHROMEISFINETOO'; } else { this.DUID = 'FIREFOXISBEST'; } return this.DUID; } });
Shadealex/smartbox
src/platforms/_browser/sb.platform.browser.js
JavaScript
mit
1,192
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace Breeze.Core { /** * @author IdeaBlade * */ public class AndOrPredicate : BasePredicate { private List<BasePredicate> _predicates; public AndOrPredicate(Operator op, params BasePredicate[] predicates) : this(op, predicates.ToList()) { } public AndOrPredicate(Operator op, IEnumerable<BasePredicate> predicates) : base(op) { _predicates = predicates.ToList(); } public IEnumerable<BasePredicate> Predicates { get { return _predicates.AsReadOnly(); } } public override void Validate(Type entityType) { _predicates.ForEach(p => p.Validate(entityType)); } public override Expression ToExpression(ParameterExpression paramExpr) { var exprs = _predicates.Select(p => p.ToExpression(paramExpr)); return BuildAndOrExpr(exprs, Operator); } private Expression BuildAndOrExpr(IEnumerable<Expression> exprs, Operator op) { if (op == Operator.And) { return exprs.Aggregate((result, expr) => Expression.And(result, expr)); } else if (op == Operator.Or) { return exprs.Aggregate((result, expr) => Expression.Or(result, expr)); } else { throw new Exception("Invalid AndOr operator" + op.Name); } } } }
lnu/breeze.server.net
Old/AspNetCore/Breeze.Core/Query/AndOrPredicate.cs
C#
mit
1,414
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > Operator x <= y returns ToString(x) <= ToString(y), if Type(Primitive(x)) is String and Type(Primitive(y)) is String es5id: 11.8.3_A3.2_T1.2 description: > Type(Primitive(x)) and Type(Primitive(y)) vary between Object object and Function object ---*/ //CHECK#1 if (({} <= function(){return 1}) !== ({}.toString() <= function(){return 1}.toString())) { $ERROR('#1: ({} <= function(){return 1}) === ({}.toString() <= function(){return 1}.toString())'); } //CHECK#2 if ((function(){return 1} <= {}) !== (function(){return 1}.toString() <= {}.toString())) { $ERROR('#2: (function(){return 1} <= {}) === (function(){return 1}.toString() <= {}.toString())'); } //CHECK#3 if ((function(){return 1} <= function(){return 1}) !== (function(){return 1}.toString() <= function(){return 1}.toString())) { $ERROR('#3: (function(){return 1} <= function(){return 1}) === (function(){return 1}.toString() <= function(){return 1}.toString())'); } //CHECK#4 if (({} <= {}) !== ({}.toString() <= {}.toString())) { $ERROR('#4: ({} <= {}) === ({}.toString() <= {}.toString())'); }
PiotrDabkowski/Js2Py
tests/test_cases/language/expressions/less-than-or-equal/S11.8.3_A3.2_T1.2.js
JavaScript
mit
1,234
var _ = require('underscore'); var Backbone = require('backbone'); var GRAPHICS = require('../util/constants').GRAPHICS; var VisBase = require('../visuals/visBase').VisBase; var VisEdge = VisBase.extend({ defaults: { tail: null, head: null, animationSpeed: GRAPHICS.defaultAnimationTime, animationEasing: GRAPHICS.defaultEasing }, validateAtInit: function() { var required = ['tail', 'head']; _.each(required, function(key) { if (!this.get(key)) { throw new Error(key + ' is required!'); } }, this); }, getID: function() { return this.get('tail').get('id') + '.' + this.get('head').get('id'); }, initialize: function() { this.validateAtInit(); // shorthand for the main objects this.gitVisuals = this.get('gitVisuals'); this.gitEngine = this.get('gitEngine'); this.get('tail').get('outgoingEdges').push(this); }, remove: function() { this.removeKeys(['path']); this.gitVisuals.removeVisEdge(this); }, genSmoothBezierPathString: function(tail, head) { var tailPos = tail.getScreenCoords(); var headPos = head.getScreenCoords(); return this.genSmoothBezierPathStringFromCoords(tailPos, headPos); }, genSmoothBezierPathStringFromCoords: function(tailPos, headPos) { // we need to generate the path and control points for the bezier. format // is M(move abs) C (curve to) (control point 1) (control point 2) (final point) // the control points have to be __below__ to get the curve starting off straight. var coords = function(pos) { return String(Math.round(pos.x)) + ',' + String(Math.round(pos.y)); }; var offset = function(pos, dir, delta) { delta = delta || GRAPHICS.curveControlPointOffset; return { x: pos.x, y: pos.y + delta * dir }; }; var offset2d = function(pos, x, y) { return { x: pos.x + x, y: pos.y + y }; }; // first offset tail and head by radii tailPos = offset(tailPos, -1, this.get('tail').getRadius()); headPos = offset(headPos, 1, this.get('head').getRadius()); var str = ''; // first move to bottom of tail str += 'M' + coords(tailPos) + ' '; // start bezier str += 'C'; // then control points above tail and below head str += coords(offset(tailPos, -1)) + ' '; str += coords(offset(headPos, 1)) + ' '; // now finish str += coords(headPos); // arrow head var delta = GRAPHICS.arrowHeadSize || 10; str += ' L' + coords(offset2d(headPos, -delta, delta)); str += ' L' + coords(offset2d(headPos, delta, delta)); str += ' L' + coords(headPos); // then go back, so we can fill correctly str += 'C'; str += coords(offset(headPos, 1)) + ' '; str += coords(offset(tailPos, -1)) + ' '; str += coords(tailPos); return str; }, getBezierCurve: function() { return this.genSmoothBezierPathString(this.get('tail'), this.get('head')); }, getStrokeColor: function() { return GRAPHICS.visBranchStrokeColorNone; }, setOpacity: function(opacity) { opacity = (opacity === undefined) ? 1 : opacity; this.get('path').attr({opacity: opacity}); }, genGraphics: function(paper) { var pathString = this.getBezierCurve(); var path = paper.path(pathString).attr({ 'stroke-width': GRAPHICS.visBranchStrokeWidth, 'stroke': this.getStrokeColor(), 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'fill': this.getStrokeColor() }); path.toBack(); this.set('path', path); }, getOpacity: function() { var stat = this.gitVisuals.getCommitUpstreamStatus(this.get('tail')); var map = { 'branch': 1, 'head': GRAPHICS.edgeUpstreamHeadOpacity, 'none': GRAPHICS.edgeUpstreamNoneOpacity }; if (map[stat] === undefined) { throw new Error('bad stat'); } return map[stat]; }, getAttributes: function() { var newPath = this.getBezierCurve(); var opacity = this.getOpacity(); return { path: { path: newPath, opacity: opacity } }; }, animateUpdatedPath: function(speed, easing) { var attr = this.getAttributes(); this.animateToAttr(attr, speed, easing); }, animateFromAttrToAttr: function(fromAttr, toAttr, speed, easing) { // an animation of 0 is essentially setting the attribute directly this.animateToAttr(fromAttr, 0); this.animateToAttr(toAttr, speed, easing); }, animateToAttr: function(attr, speed, easing) { if (speed === 0) { this.get('path').attr(attr.path); return; } this.get('path').toBack(); this.get('path').stop().animate( attr.path, speed !== undefined ? speed : this.get('animationSpeed'), easing || this.get('animationEasing') ); } }); var VisEdgeCollection = Backbone.Collection.extend({ model: VisEdge }); exports.VisEdgeCollection = VisEdgeCollection; exports.VisEdge = VisEdge;
easteregg423/learnGitBranching
src/js/visuals/visEdge.js
JavaScript
mit
4,984
/// <reference path="../../src/bobril.d.ts"/> /// <reference path="../../src/bobril.mouse.d.ts"/> module MouseOwnerApp { var button: IBobrilComponent = { init(ctx: any, me: IBobrilNode): void { ctx.backColor = "#f0f0f0"; }, render(ctx: any, me: IBobrilNode): void { me.tag = "div"; me.style = b.assign({}, ctx.data.style); me.children = ctx.data.children; me.style.backgroundColor = ctx.backColor; }, onMouseDown(ctx: any): boolean { ctx.backColor = "red"; b.registerMouseOwner(ctx); b.invalidate(ctx); return true; }, onMouseUp(ctx: any): boolean { ctx.backColor = "#f0f0f0"; if (b.isMouseOwner(ctx)) { b.releaseMouseOwner(); } b.invalidate(ctx); return true; } }; function twice(obj: any): any[] { return [obj, b.cloneNode(obj)]; } b.init(() => { return twice({ tag: "div", style: { height: 500, width: 500, border: "solid 1px", position: "relative", cssFloat: "left" }, children: { component: button, data: { style: { width: 120, height: 20, position: "absolute", border: "1px solid #000", left: 190, top: 240 }, children: "Click and drag out" } } }); }); }
klesta490/Bobril
examples/mouseowner/app.ts
TypeScript
mit
1,468
<?php class FilesController extends Controller { public function upload($id) { $page = $this->page($id); $upload = new Upload($page->root() . DS . '{safeFilename}', array( 'overwrite' => true, 'accept' => function($file) { $callback = kirby()->option('panel.upload.accept'); if(is_callable($callback)) { return call($callback, $file); } else { return true; } } )); if($file = $upload->file()) { if($file->extension() == 'txt') { $file->delete(); return response::error('Txt files cannot be uploaded'); } return response::success('success'); } else { return response::error($upload->error()->getMessage()); } } public function replace($id) { $filename = get('filename'); $file = $this->file($id, $filename); $upload = new Upload($file->root(), array( 'overwrite' => true, 'accept' => function($upload) use($file) { if($upload->mime() != $file->mime()) { throw new Error(l('files.replace.error.type')); } } )); if($upload->file()) { return response::success('success'); } else { return response::error($upload->error()->getMessage()); } } public function rename($id) { $filename = get('filename'); $file = $this->file($id, $filename); if(!$file) { return response::error(l('files.error.missing.file')); } try { $filename = $file->rename(get('name')); return response::success('success', array( 'filename' => $filename )); } catch(Exception $e) { return response::error(l('files.show.error.rename')); } } public function update($id) { $filename = get('filename'); $page = $this->page($id); if(!$page) { return response::error(l('files.error.missing.page')); } $file = $page->file($filename); if(!$file) { return response::error(l('files.error.missing.file')); } $blueprint = blueprint::find($page); $fields = $blueprint->files()->fields($page); // trigger the validation $form = new Form($fields->toArray()); $form->validate(); // fetch the form data $data = filedata::createByInput($file, $form->serialize()); // stop at invalid fields if(!$form->isValid()) { return response::error(l('files.show.error.form'), 400, array( 'fields' => $form->fields()->filterBy('error', true)->pluck('name') )); } try { $file->update($data); return response::success('success', array( 'data' => $data )); } catch(Exception $e) { return response::error($e->getMessage()); } } public function sort($id) { $page = $this->page($id); if(!$page) { return response::error(l('files.error.missing.page')); } $filenames = get('filenames'); $counter = 0; foreach($filenames as $filename) { $file = $page->file($filename); if(!$file) continue; $counter++; try { $file->update(array('sort' => $counter)); } catch(Exception $e) { } } return response::success('success'); } public function delete($id) { $filename = get('filename'); $file = $this->file($id, $filename); if(!$file) { return response::error(l('files.error.missing.file')); } try { $file->delete(); return response::success('success'); } catch(Exception $e) { return response::error($e->getMessage()); } } protected function page($id) { return empty($id) ? site() : page($id); } protected function file($id, $filename) { if($page = $this->page($id)) { return $page->file($filename); } else { return false; } } }
aizlewood/2015
panel/app/controllers/api/files.php
PHP
mit
3,842
require('../../support/spec_helper'); describe("Cucumber.Ast.Feature", function () { var Cucumber = requireLib('cucumber'); var scenarioCollection, lastScenario; var feature, keyword, name, description, uri, line; beforeEach(function () { lastScenario = createSpy("Last scenario"); scenarioCollection = {}; // bare objects because we need .length // which is not available on jasmine spies spyOnStub(scenarioCollection, 'add'); spyOnStub(scenarioCollection, 'insert'); spyOnStub(scenarioCollection, 'removeAtIndex'); spyOnStub(scenarioCollection, 'indexOf'); spyOnStub(scenarioCollection, 'getLast').andReturn(lastScenario); spyOnStub(scenarioCollection, 'syncForEach'); spyOnStub(scenarioCollection, 'forEach'); spyOn(Cucumber.Type, 'Collection').andReturn(scenarioCollection); keyword = createSpy("keyword"); name = createSpy("name"); description = createSpy("description"); uri = createSpy("uri"); line = createSpy("line number"); feature = Cucumber.Ast.Feature(keyword, name, description, uri, line); }); describe("constructor", function () { it("creates a new collection to store scenarios", function () { expect(Cucumber.Type.Collection).toHaveBeenCalled(); }); }); describe("getKeyword()", function () { it("returns the keyword of the feature", function () { expect(feature.getKeyword()).toBe(keyword); }); }); describe("getName()", function () { it("returns the name of the feature", function () { expect(feature.getName()).toBe(name); }); }); describe("getDescription()", function () { it("returns the description of the feature", function () { expect(feature.getDescription()).toBe(description); }); }); describe("getUri()", function () { it("returns the URI of the feature", function () { expect(feature.getUri()).toBe(uri); }); }); describe("getLine()", function () { it("returns the line number on which the feature starts", function () { expect(feature.getLine()).toBe(line); }); }); describe("getBackground() [setBackground()]", function () { describe("when a background was previously added", function () { var background; beforeEach(function () { background = createSpy("background"); feature.setBackground(background); }); it("returns the background", function () { expect(feature.getBackground()).toBe(background); }); }); describe("when no background was previousyly added", function () { it("returns nothing", function () { expect(feature.getBackground()).toBeUndefined(); }); }); }); describe("hasBackground()", function () { it("returns true when a background was set", function () { var background = createSpy("background"); feature.setBackground(background); expect(feature.hasBackground()).toBeTruthy(); }); it("returns false when no background was set", function () { expect(feature.hasBackground()).toBeFalsy(); }); }); describe("addFeatureElement()", function () { var scenario, background; beforeEach(function () { scenario = createSpyWithStubs("scenario AST element", {setBackground: null}); background = createSpy("scenario background"); spyOn(feature, 'getBackground').andReturn(background); }); it("sets the background on the scenario", function () { feature.addFeatureElement(scenario); expect(scenario.setBackground).toHaveBeenCalledWith(background); }); it("adds the scenario to the scenarios (collection)", function () { feature.addFeatureElement(scenario); expect(scenarioCollection.add).toHaveBeenCalledWith(scenario); }); }); describe("insertFeatureElement()", function () { var index, scenario, background; beforeEach(function () { index = createSpy("index"); scenario = createSpyWithStubs("scenario AST element", {setBackground: null}); background = createSpy("scenario background"); spyOn(feature, 'getBackground').andReturn(background); }); it("sets the background on the scenario", function () { feature.insertFeatureElement(index, scenario); expect(scenario.setBackground).toHaveBeenCalledWith(background); }); it("adds the scenario to the scenarios (collection)", function () { feature.insertFeatureElement(index, scenario); expect(scenarioCollection.insert).toHaveBeenCalledWith(index, scenario); }); }); describe("convertScenarioOutlinesToScenarios()", function () { it ("iterates over the feature elements", function () { feature.convertScenarioOutlinesToScenarios(); expect(scenarioCollection.syncForEach).toHaveBeenCalled(); expect(scenarioCollection.syncForEach).toHaveBeenCalledWithAFunctionAsNthParameter(1); }); describe("for each feature element", function () { var userFunction, featureElement; beforeEach(function () { feature.convertScenarioOutlinesToScenarios(); userFunction = scenarioCollection.syncForEach.mostRecentCall.args[0]; featureElement = createSpyWithStubs("feature element", {isScenarioOutline: null}); spyOn(feature, 'convertScenarioOutlineToScenarios'); }); describe("when the feature element is a scenario outline", function () { beforeEach(function () { featureElement.isScenarioOutline.andReturn(true); userFunction (featureElement); }); it("converts the scenario outline into scenarios", function () { expect(feature.convertScenarioOutlineToScenarios).toHaveBeenCalledWith(featureElement); }); }); describe("when the feature element is not a scenario outline", function () { beforeEach(function () { featureElement.isScenarioOutline.andReturn(false); userFunction (featureElement); }); it("converts the scenario outline into scenarios", function () { expect(feature.convertScenarioOutlineToScenarios).not.toHaveBeenCalled(); }); }); }); }); describe("convertScenarioOutlineToScenarios()", function () { var scenarios, scenarioOutlineTags, scenarioOutline, scenarioOutlineIndex; beforeEach(function () { scenarios = createSpyWithStubs("scenarios", {syncForEach: null}); scenarioOutlineTags = createSpy("tags"); scenarioOutline = createSpyWithStubs("scenario outline", {buildScenarios: scenarios, getTags: scenarioOutlineTags}); scenarioOutlineIndex = 1; scenarioCollection.indexOf.andReturn(scenarioOutlineIndex); feature.convertScenarioOutlineToScenarios(scenarioOutline); }); it ("builds the scenarios for the scenario outline", function () { expect(scenarioOutline.buildScenarios).toHaveBeenCalled(); }); it ("gets the index of the scenario outline in the scenario collection", function () { expect(scenarioCollection.indexOf).toHaveBeenCalledWith(scenarioOutline); }); it("removes the scenario outline from the scenario collection", function () { expect(scenarioCollection.removeAtIndex).toHaveBeenCalledWith(scenarioOutlineIndex); }); it("gets the tags from the scenario outline just once", function () { expect(scenarioOutline.getTags).toHaveBeenCalledNTimes(1); }); it ("iterates over the scenarios", function () { expect(scenarios.syncForEach).toHaveBeenCalled(); expect(scenarios.syncForEach).toHaveBeenCalledWithAFunctionAsNthParameter(1); }); describe("for each scenario", function () { var userFunction, scenario, index; beforeEach(function () { userFunction = scenarios.syncForEach.mostRecentCall.args[0]; scenario = createSpyWithStubs("scenario", {addTags: null}); index = 2; spyOn(feature, 'insertFeatureElement'); userFunction (scenario, index); }); it("adds the scenario outline's tags to the scenario", function () { expect(scenario.addTags).toHaveBeenCalledWith(scenarioOutlineTags); }); it("inserts the scenario into the scenario collection", function () { expect(feature.insertFeatureElement).toHaveBeenCalledWith(scenarioOutlineIndex + index, scenario); }); }); }); describe("getLastScenario()", function () { it("gets the last scenario from the collection", function () { feature.getLastFeatureElement(); expect(scenarioCollection.getLast).toHaveBeenCalled(); }); it("returns the last scenario", function () { expect(feature.getLastFeatureElement()).toBe(lastScenario); }); }); describe("hasScenarios()", function () { beforeEach(function () { spyOnStub(scenarioCollection, 'length'); }); it("gets the number of scenarios", function () { feature.hasFeatureElements(); expect(scenarioCollection.length).toHaveBeenCalled(); }); it("is falsy when there are 0 scenarios", function () { scenarioCollection.length.andReturn(0); expect(feature.hasFeatureElements()).toBeFalsy(); }); it("is truthy when there is 1 scenario", function () { scenarioCollection.length.andReturn(1); expect(feature.hasFeatureElements()).toBeTruthy(); }); it("is truthy when there are more than 1 scenarios", function () { scenarioCollection.length.andReturn(2); expect(feature.hasFeatureElements()).toBeTruthy(); }); }); describe("getTags() [addTags()]", function () { it("returns an empty set when no tags were added", function () { expect(feature.getTags()).toEqual([]); }); it("returns the tags", function () { var tag1 = createSpy("tag 1"); var tag2 = createSpy("tag 2"); var tag3 = createSpy("tag 3"); feature.addTags([tag1, tag2]); feature.addTags([tag3]); expect(feature.getTags()).toEqual([tag1, tag2, tag3]); }); }); describe("acceptVisitor", function () { var visitor, callback; beforeEach(function () { visitor = createSpyWithStubs("visitor", {visitStep: null}); callback = createSpy("callback"); spyOn(feature, 'instructVisitorToVisitBackground'); spyOn(feature, 'instructVisitorToVisitScenarios'); }); it("instructs the visitor to visit the feature background", function () { feature.acceptVisitor(visitor, callback); expect(feature.instructVisitorToVisitBackground).toHaveBeenCalledWithValueAsNthParameter(visitor, 1); expect(feature.instructVisitorToVisitBackground).toHaveBeenCalledWithAFunctionAsNthParameter(2); }); describe("when the visitor has finished visiting the background", function () { var featureStepsVisitCallback; beforeEach(function () { feature.acceptVisitor(visitor, callback); featureStepsVisitCallback = feature.instructVisitorToVisitBackground.mostRecentCall.args[1]; }); it("instructs the visitor to visit the feature steps", function () { featureStepsVisitCallback(); expect(feature.instructVisitorToVisitScenarios).toHaveBeenCalledWith(visitor, callback); }); }); }); describe("instructVisitorToVisitBackground()", function () { var visitor, callback; beforeEach(function () { visitor = createSpyWithStubs("visitor", {visitBackground: undefined}); callback = createSpy("callback"); spyOn(feature, 'hasBackground'); }); it("checks whether the feature has a background", function () { feature.instructVisitorToVisitBackground(visitor, callback); expect(feature.hasBackground).toHaveBeenCalled(); }); describe("when there is a background", function () { var background; beforeEach(function () { background = createSpy("background"); feature.hasBackground.andReturn(true); spyOn(feature, 'getBackground').andReturn(background); }); it("gets the background", function () { feature.instructVisitorToVisitBackground(visitor, callback); expect(feature.getBackground).toHaveBeenCalled(); }); it("instructs the visitor to visit the background", function () { feature.instructVisitorToVisitBackground(visitor, callback); expect(visitor.visitBackground).toHaveBeenCalledWith(background, callback); }); it("does not call back", function () { feature.instructVisitorToVisitBackground(visitor, callback); expect(callback).not.toHaveBeenCalled(); }); }); describe("when there is no background", function () { beforeEach(function () { feature.hasBackground.andReturn(false); }); it("calls back", function () { feature.instructVisitorToVisitBackground(visitor, callback); expect(callback).toHaveBeenCalled(); }); }); }); describe("instructVisitorToVisitScenarios()", function () { var visitor, callback; beforeEach(function () { visitor = createSpyWithStubs("Visitor", {visitScenario: null}); callback = createSpy("Callback"); }); it ("iterates over the scenarios with a user function and the callback", function () { feature.instructVisitorToVisitScenarios(visitor, callback); expect(scenarioCollection.forEach).toHaveBeenCalled(); expect(scenarioCollection.forEach).toHaveBeenCalledWithAFunctionAsNthParameter(1); expect(scenarioCollection.forEach).toHaveBeenCalledWithValueAsNthParameter(callback, 2); }); describe("for each scenario", function () { var userFunction, scenario, forEachCallback; beforeEach(function () { feature.instructVisitorToVisitScenarios(visitor, callback); userFunction = scenarioCollection.forEach.mostRecentCall.args[0]; scenario = createSpy("A scenario from the collection"); forEachCallback = createSpy("forEach() callback"); }); it("tells the visitor to visit the scenario and call back when finished", function () { userFunction (scenario, forEachCallback); expect(visitor.visitScenario).toHaveBeenCalledWith(scenario, forEachCallback); }); }); }); });
arty-name/cucumber-js
spec/cucumber/ast/feature_spec.js
JavaScript
mit
14,337
// Copyright (C) 2006 Tiago de Paula Peixoto <tiago@forked.de> // Copyright (C) 2004,2009 The Trustees of Indiana University. // // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Authors: Douglas Gregor // Jeremiah Willcock // Andrew Lumsdaine // Tiago de Paula Peixoto #define BOOST_GRAPH_SOURCE #include <boost/foreach.hpp> #include <boost/optional.hpp> #include <boost/throw_exception.hpp> #include <boost/graph/graphml.hpp> #include <boost/graph/dll_import_export.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> using namespace boost; namespace { class graphml_reader { public: graphml_reader(mutate_graph& g) : m_g(g) { } static boost::property_tree::ptree::path_type path(const std::string& str) { return boost::property_tree::ptree::path_type(str, '/'); } static void get_graphs(const boost::property_tree::ptree& top, size_t desired_idx /* or -1 for all */, std::vector<const boost::property_tree::ptree*>& result) { using boost::property_tree::ptree; size_t current_idx = 0; BOOST_FOREACH(const ptree::value_type& n, top) { if (n.first == "graph") { if (current_idx == desired_idx || desired_idx == (size_t)(-1)) { result.push_back(&n.second); get_graphs(n.second, (size_t)(-1), result); if (desired_idx != (size_t)(-1)) break; } ++current_idx; } } } void run(std::istream& in, size_t desired_idx) { using boost::property_tree::ptree; ptree pt; read_xml(in, pt, boost::property_tree::xml_parser::no_comments | boost::property_tree::xml_parser::trim_whitespace); ptree gml = pt.get_child(path("graphml")); // Search for attributes BOOST_FOREACH(const ptree::value_type& child, gml) { if (child.first != "key") continue; std::string id = child.second.get(path("<xmlattr>/id"), ""); std::string for_ = child.second.get(path("<xmlattr>/for"), ""); std::string name = child.second.get(path("<xmlattr>/attr.name"), ""); std::string type = child.second.get(path("<xmlattr>/attr.type"), ""); key_kind kind = all_key; if (for_ == "graph") kind = graph_key; else if (for_ == "node") kind = node_key; else if (for_ == "edge") kind = edge_key; else if (for_ == "hyperedge") kind = hyperedge_key; else if (for_ == "port") kind = port_key; else if (for_ == "endpoint") kind = endpoint_key; else if (for_ == "all") kind = all_key; else {BOOST_THROW_EXCEPTION(parse_error("Attribute for is not valid: " + for_));} m_keys[id] = kind; m_key_name[id] = name; m_key_type[id] = type; boost::optional<std::string> default_ = child.second.get_optional<std::string>(path("default")); if (default_) m_key_default[id] = default_.get(); } // Search for graphs std::vector<const ptree*> graphs; get_graphs(gml, desired_idx, graphs); BOOST_FOREACH(const ptree* gr, graphs) { // Search for nodes BOOST_FOREACH(const ptree::value_type& node, *gr) { if (node.first != "node") continue; std::string id = node.second.get<std::string>(path("<xmlattr>/id")); handle_vertex(id); BOOST_FOREACH(const ptree::value_type& attr, node.second) { if (attr.first != "data") continue; std::string key = attr.second.get<std::string>(path("<xmlattr>/key")); std::string value = attr.second.get_value(""); handle_node_property(key, id, value); } } } BOOST_FOREACH(const ptree* gr, graphs) { bool default_directed = gr->get<std::string>(path("<xmlattr>/edgedefault")) == "directed"; // Search for edges BOOST_FOREACH(const ptree::value_type& edge, *gr) { if (edge.first != "edge") continue; std::string source = edge.second.get<std::string>(path("<xmlattr>/source")); std::string target = edge.second.get<std::string>(path("<xmlattr>/target")); std::string local_directed = edge.second.get(path("<xmlattr>/directed"), ""); bool is_directed = (local_directed == "" ? default_directed : local_directed == "true"); if (is_directed != m_g.is_directed()) { if (is_directed) { BOOST_THROW_EXCEPTION(directed_graph_error()); } else { BOOST_THROW_EXCEPTION(undirected_graph_error()); } } size_t old_edges_size = m_edge.size(); handle_edge(source, target); BOOST_FOREACH(const ptree::value_type& attr, edge.second) { if (attr.first != "data") continue; std::string key = attr.second.get<std::string>(path("<xmlattr>/key")); std::string value = attr.second.get_value(""); handle_edge_property(key, old_edges_size, value); } } } } private: /// The kinds of keys. Not all of these are supported enum key_kind { graph_key, node_key, edge_key, hyperedge_key, port_key, endpoint_key, all_key }; void handle_vertex(const std::string& v) { bool is_new = false; if (m_vertex.find(v) == m_vertex.end()) { m_vertex[v] = m_g.do_add_vertex(); is_new = true; } if (is_new) { std::map<std::string, std::string>::iterator iter; for (iter = m_key_default.begin(); iter != m_key_default.end(); ++iter) { if (m_keys[iter->first] == node_key) handle_node_property(iter->first, v, iter->second); } } } any get_vertex_descriptor(const std::string& v) { return m_vertex[v]; } void handle_edge(const std::string& u, const std::string& v) { handle_vertex(u); handle_vertex(v); any source, target; source = get_vertex_descriptor(u); target = get_vertex_descriptor(v); any edge; bool added; boost::tie(edge, added) = m_g.do_add_edge(source, target); if (!added) { BOOST_THROW_EXCEPTION(bad_parallel_edge(u, v)); } size_t e = m_edge.size(); m_edge.push_back(edge); std::map<std::string, std::string>::iterator iter; for (iter = m_key_default.begin(); iter != m_key_default.end(); ++iter) { if (m_keys[iter->first] == edge_key) handle_edge_property(iter->first, e, iter->second); } } void handle_node_property(const std::string& key_id, const std::string& descriptor, const std::string& value) { m_g.set_vertex_property(m_key_name[key_id], m_vertex[descriptor], value, m_key_type[key_id]); } void handle_edge_property(const std::string& key_id, size_t descriptor, const std::string& value) { m_g.set_edge_property(m_key_name[key_id], m_edge[descriptor], value, m_key_type[key_id]); } mutate_graph& m_g; std::map<std::string, key_kind> m_keys; std::map<std::string, std::string> m_key_name; std::map<std::string, std::string> m_key_type; std::map<std::string, std::string> m_key_default; std::map<std::string, any> m_vertex; std::vector<any> m_edge; }; } namespace boost { void BOOST_GRAPH_DECL read_graphml(std::istream& in, mutate_graph& g, size_t desired_idx) { graphml_reader reader(g); reader.run(in, desired_idx); } }
mxrrow/zaicoin
src/deps/boost/libs/graph/src/graphml.cpp
C++
mit
7,850
/* * A reply to a screenshot comment made on a review. * * When created, this must take a parentObject attribute that points to a * Review object. */ RB.ScreenshotCommentReply = RB.BaseCommentReply.extend({ rspNamespace: 'screenshot_comment' });
custode/reviewboard
reviewboard/static/rb/js/resources/models/screenshotCommentReplyModel.js
JavaScript
mit
255
define([ "dojo/_base/declare", "dojo/_base/lang", "dojo/store/Memory", "dojo/query", "dojo/dom-attr", "dijit/_WidgetBase", "dijit/_FocusMixin", "dijit/_TemplatedMixin", "dijit/form/FilteringSelect" ], function(declare, lang, Store, query, domAttr, _WidgetBase, _FocusMixin, _TemplatedMixin, FilteringSelect){ /*===== return declare([_WidgetBase, _FocusMixin, _TemplatedMixin], { // summary: // This grid bar plugin is to switch pages using select widget. // grid: [const] gridx.Grid // The grid widget this plugin works for. grid: null, // stepperClass: Function // The constructor of the select widget stepperClass: FilteringSelect, // stepperProps: Object // The properties passed to select widget when creating it. stepperProps: null, refresh: function(){} }); =====*/ return declare([_WidgetBase, _FocusMixin, _TemplatedMixin], { templateString: '<div class="gridxDropDownPager"><label class="gridxPagerLabel">${pageLabel}</label></div>', constructor: function(args){ lang.mixin(this, args.grid.nls); }, postCreate: function(){ var t = this, g = t.grid, c = 'connect', p = g.pagination; t[c](p, 'onSwitchPage', '_onSwitchPage'); t[c](p, 'onChangePageSize', 'refresh'); t[c](g.model, 'onSizeChange', 'refresh'); g.pagination.loaded.then(function(){ t.refresh(); //Set initial page after pagination module is ready. t._onSwitchPage(g.pagination.currentPage()); }); }, //Public----------------------------------------------------------------------------- grid: null, stepperClass: FilteringSelect, stepperProps: null, refresh: function(){ var t = this, mod = t.module, items = [], selectedItem, p = t.grid.pagination, pageCount = p.pageCount(), currentPage = p.currentPage(), stepper = t._pageStepperSelect, i, v, item; for(i = 0; i < pageCount; ++i){ v = i + 1; item = { id: v, label: v, value: v }; items.push(item); if(currentPage == i){ selectedItem = item; } } var store = new Store({data: items}); if(!stepper){ var cls = t.stepperClass, props = lang.mixin({ store: store, searchAttr: 'label', item: selectedItem, 'class': 'gridxPagerStepperWidget', onChange: function(page){ p.gotoPage(page - 1); } }, t.stepperProps || {}); stepper = t._pageStepperSelect = new cls(props); stepper.placeAt(t.domNode, "last"); stepper.startup(); domAttr.set(query('.gridxPagerLabel', t.domNode)[0], 'for', stepper.id); }else{ stepper.set('store', store); stepper.set('value', currentPage + 1); } stepper.set('disabled', pageCount <= 1); }, //Private---------------------------------------------------------------------------- _onSwitchPage: function(page){ this._pageStepperSelect.set('value', page + 1); } }); });
mbouami/pme
web/js/gridx/support/DropDownPager.js
JavaScript
mit
2,919
<?php namespace Kendo\UI; class SchedulerMessagesRecurrenceEditorOffsetPositions extends \Kendo\SerializableObject { //>> Properties /** * The text similar to "first" displayed in the scheduler recurrence editor. * @param string $value * @return \Kendo\UI\SchedulerMessagesRecurrenceEditorOffsetPositions */ public function first($value) { return $this->setProperty('first', $value); } /** * The text similar to "second" displayed in the scheduler recurrence editor. * @param string $value * @return \Kendo\UI\SchedulerMessagesRecurrenceEditorOffsetPositions */ public function second($value) { return $this->setProperty('second', $value); } /** * The text similar to "third" displayed in the scheduler recurrence editor. * @param string $value * @return \Kendo\UI\SchedulerMessagesRecurrenceEditorOffsetPositions */ public function third($value) { return $this->setProperty('third', $value); } /** * The text similar to "fourth" displayed in the scheduler recurrence editor. * @param string $value * @return \Kendo\UI\SchedulerMessagesRecurrenceEditorOffsetPositions */ public function fourth($value) { return $this->setProperty('fourth', $value); } /** * The text similar to "last" displayed in the scheduler recurrence editor. * @param string $value * @return \Kendo\UI\SchedulerMessagesRecurrenceEditorOffsetPositions */ public function last($value) { return $this->setProperty('last', $value); } //<< Properties } ?>
deviffy/laravel-kendo-ui
wrappers/php/lib/Kendo/UI/SchedulerMessagesRecurrenceEditorOffsetPositions.php
PHP
mit
1,611
/* Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved. The MySQL Connector/J is licensed under the terms of the GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors. There are special exceptions to the terms and conditions of the GPLv2 as it is applied to this software, see the FOSS License Exception <http://www.mysql.com/about/legal/licensing/foss-exception.html>. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.mysql.jdbc; import java.sql.SQLException; public interface LoadBalancedConnection extends MySQLConnection { public boolean addHost(String host) throws SQLException; public void removeHost(String host) throws SQLException; public void removeHostWhenNotInUse(String host) throws SQLException; }
MarAvFe/Footballer
mysql-connector-java-5.1.37/src/com/mysql/jdbc/LoadBalancedConnection.java
Java
mit
1,420
# encoding: UTF-8 module LibXML module XML class Node def property(name) warn('Node#properties is deprecated. Use Node#[] instead.') self[name] end def properties warn('Node#properties is deprecated. Use Node#attributes instead.') self.attributes end def properties? warn('Node#properties? is deprecated. Use Node#attributes? instead.') self.attributes? end end end end
sho-wtag/catarse-2.0
vendor/bundle/ruby/2.2.0/gems/libxml-ruby-2.8.0/lib/libxml/properties.rb
Ruby
mit
494
<?php namespace Symfony\Component\Security\Acl\Permission; /* * This file is part of the Symfony framework. * * (c) Fabien Potencier <fabien.potencier@symfony-project.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ /** * This is the interface that must be implemented by permission maps. * * @author Johannes M. Schmitt <schmittjoh@gmail.com> */ interface PermissionMapInterface { /** * Returns an array of bitmasks. * * The security identity must have been granted access to at least one of * these bitmasks. * * @param string $permission * @return array */ function getMasks($permission); /** * Whether this map contains the given permission * * @param string $permission * @return Boolean */ function contains($permission); }
nresni/AriadneSandbox
src/vendor/symfony/src/Symfony/Component/Security/Acl/Permission/PermissionMapInterface.php
PHP
mit
896
/** PeriodLister Class */ function PeriodDeltaChain(params) { this.period_root_id = params.period_root_id; this.date_format = this.set_or_default(params.date_format, ''); this.set_due_date(params.due_date); this.period_class = this.set_or_default(params.period_class, 'period'); } PeriodDeltaChain.prototype.refresh = function() { var current_time = this.due_date; var format = this.date_format; var period_selector = '#' + this.period_root_id + ' .' + this.period_class; var me = this; jQuery(period_selector).each(function() { var from_time_node = this.querySelector('.PeriodDeltaChain_FromTime'); var to_time_node = this.querySelector('.PeriodDeltaChain_ToTime'); var hours_value = this.querySelector('.PeriodDeltaChain_Hours').value; var from_time = moment(current_time, me.date_format); var to_time = moment(current_time, me.date_format); jQuery(from_time_node).html(from_time.format(format)); jQuery(to_time_node).html(to_time.add('hours', hours_value).format(format)); current_time = to_time; }); if (jQuery(period_selector).length < 2) { jQuery(period_selector + ' a').hide(); } else { jQuery(period_selector + ' a').show(); } } PeriodDeltaChain.prototype.set_due_date = function(new_due_date) { delete this.due_date; this.due_date = convert_date(new_due_date); } PeriodDeltaChain.prototype.set_or_default = function(value, default_value) { if (typeof value == 'undefined') { return default_value; } return value; } /** Converts date string to an actual Date object. */ function convert_date(due_date) { if (due_date.indexOf(' ') > -1) { var arr_date = due_date.split(/[ T]/).filter(function (s) { return s !== ''; }); due_date = arr_date[0] + ' ' + arr_date[1] + ' ' + arr_date[2]; } return due_date; }
binuri/Markus
app/assets/javascripts/PeriodDeltaChain/PeriodDeltaChain.js
JavaScript
mit
1,839
// 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. #nullable enable using System.Collections.Generic; using Microsoft.CodeAnalysis.Formatting.Rules; namespace Microsoft.CodeAnalysis.Formatting { /// <summary> /// this collector gathers formatting operations that are based on a node /// </summary> internal class NodeOperations { public static NodeOperations Empty = new NodeOperations(); public List<IndentBlockOperation> IndentBlockOperation { get; } public List<SuppressOperation> SuppressOperation { get; } public List<AlignTokensOperation> AlignmentOperation { get; } public List<AnchorIndentationOperation> AnchorIndentationOperations { get; } public NodeOperations(List<IndentBlockOperation> indentBlockOperation, List<SuppressOperation> suppressOperation, List<AnchorIndentationOperation> anchorIndentationOperations, List<AlignTokensOperation> alignmentOperation) { this.IndentBlockOperation = indentBlockOperation; this.SuppressOperation = suppressOperation; this.AlignmentOperation = alignmentOperation; this.AnchorIndentationOperations = anchorIndentationOperations; } private NodeOperations() { this.IndentBlockOperation = new List<IndentBlockOperation>(); this.SuppressOperation = new List<SuppressOperation>(); this.AlignmentOperation = new List<AlignTokensOperation>(); this.AnchorIndentationOperations = new List<AnchorIndentationOperation>(); } } }
jmarolf/roslyn
src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/NodeOperations.cs
C#
mit
1,736
using UnityEngine; using System.Collections; using LuaInterface; public class ToLua_UnityEngine_GameObject { public static string SendMessageDefined = @" try { ++LuaException.SendMsgCount; int count = LuaDLL.lua_gettop(L); if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.GameObject), typeof(string))) { UnityEngine.GameObject obj = (UnityEngine.GameObject)ToLua.ToObject(L, 1); string arg0 = ToLua.ToString(L, 2); obj.SendMessage(arg0); --LuaException.SendMsgCount; if (LuaDLL.lua_toboolean(L, LuaDLL.lua_upvalueindex(1))) { string error = LuaDLL.lua_tostring(L, -1); LuaDLL.lua_pop(L, 1); throw new LuaException(error, LuaException.GetLastError()); } return 0; } else if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.GameObject), typeof(string), typeof(UnityEngine.SendMessageOptions))) { UnityEngine.GameObject obj = (UnityEngine.GameObject)ToLua.ToObject(L, 1); string arg0 = ToLua.ToString(L, 2); UnityEngine.SendMessageOptions arg1 = (UnityEngine.SendMessageOptions)ToLua.ToObject(L, 3); obj.SendMessage(arg0, arg1); --LuaException.SendMsgCount; if (LuaDLL.lua_toboolean(L, LuaDLL.lua_upvalueindex(1))) { string error = LuaDLL.lua_tostring(L, -1); LuaDLL.lua_pop(L, 1); throw new LuaException(error, LuaException.GetLastError()); } return 0; } else if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.GameObject), typeof(string), typeof(object))) { UnityEngine.GameObject obj = (UnityEngine.GameObject)ToLua.ToObject(L, 1); string arg0 = ToLua.ToString(L, 2); object arg1 = ToLua.ToVarObject(L, 3); obj.SendMessage(arg0, arg1); --LuaException.SendMsgCount; if (LuaDLL.lua_toboolean(L, LuaDLL.lua_upvalueindex(1))) { string error = LuaDLL.lua_tostring(L, -1); LuaDLL.lua_pop(L, 1); throw new LuaException(error, LuaException.GetLastError()); } return 0; } else if (count == 4 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.GameObject), typeof(string), typeof(object), typeof(UnityEngine.SendMessageOptions))) { UnityEngine.GameObject obj = (UnityEngine.GameObject)ToLua.ToObject(L, 1); string arg0 = ToLua.ToString(L, 2); object arg1 = ToLua.ToVarObject(L, 3); UnityEngine.SendMessageOptions arg2 = (UnityEngine.SendMessageOptions)ToLua.ToObject(L, 4); obj.SendMessage(arg0, arg1, arg2); --LuaException.SendMsgCount; if (LuaDLL.lua_toboolean(L, LuaDLL.lua_upvalueindex(1))) { string error = LuaDLL.lua_tostring(L, -1); LuaDLL.lua_pop(L, 1); throw new LuaException(error, LuaException.GetLastError()); } return 0; } else { --LuaException.SendMsgCount; return LuaDLL.luaL_throw(L, ""invalid arguments to method: UnityEngine.GameObject.SendMessage""); } } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); }"; [UseDefinedAttribute] public void SendMessage(string methodName) { } }
GarfieldJiang/UGFWithToLua
Assets/ToLua/ToLua/Editor/Extend/ToLua_UnityEngine_GameObject.cs
C#
mit
3,573
var parent = require('../../stable/string/match-all'); module.exports = parent;
zloirock/core-js
packages/core-js/actual/string/match-all.js
JavaScript
mit
81
package canal import ( "bytes" "os" "sync" "time" "github.com/BurntSushi/toml" "github.com/siddontang/go-mysql/mysql" "github.com/siddontang/go/ioutil2" "github.com/siddontang/go/log" ) type masterInfo struct { Addr string `toml:"addr"` Name string `toml:"bin_name"` Position uint32 `toml:"bin_pos"` name string l sync.Mutex lastSaveTime time.Time } func loadMasterInfo(name string) (*masterInfo, error) { var m masterInfo m.name = name f, err := os.Open(name) if err != nil && !os.IsNotExist(err) { return nil, err } else if os.IsNotExist(err) { return &m, nil } defer f.Close() _, err = toml.DecodeReader(f, &m) return &m, err } func (m *masterInfo) Save(force bool) error { m.l.Lock() defer m.l.Unlock() n := time.Now() if !force && n.Sub(m.lastSaveTime) < time.Second { return nil } var buf bytes.Buffer e := toml.NewEncoder(&buf) e.Encode(m) var err error if err = ioutil2.WriteFileAtomic(m.name, buf.Bytes(), 0644); err != nil { log.Errorf("canal save master info to file %s err %v", m.name, err) } m.lastSaveTime = n return err } func (m *masterInfo) Update(name string, pos uint32) { m.l.Lock() m.Name = name m.Position = pos m.l.Unlock() } func (m *masterInfo) Pos() mysql.Position { var pos mysql.Position m.l.Lock() pos.Name = m.Name pos.Pos = m.Position m.l.Unlock() return pos } func (m *masterInfo) Close() { m.Save(true) }
baiyunping333/go-mysql-elasticsearch
Godeps/_workspace/src/github.com/siddontang/go-mysql/canal/master.go
GO
mit
1,423
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_InfoCard * @subpackage Zend_InfoCard_Xml_Security * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @namespace */ namespace Zend\InfoCard\XML\Security\Transform; use Zend\InfoCard\XML\Security\Transform, Zend\InfoCard\XML\Security\Exception; /** * A object implementing the EnvelopedSignature XML Transform * * @uses \Zend\InfoCard\XML\Security\Transform\Exception * @uses \Zend\InfoCard\XML\Security\Transform * @category Zend * @package Zend_InfoCard * @subpackage Zend_InfoCard_Xml_Security * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class EnvelopedSignature implements Transform { /** * Transforms the XML Document according to the EnvelopedSignature Transform * * @throws \Zend\InfoCard\XML\Security\Transform\Exception * @param string $strXMLData The input XML data * @return string the transformed XML data */ public function transform($strXMLData) { $sxe = simplexml_load_string($strXMLData); if(!$sxe->Signature) { throw new Exception\InvalidArgumentException("Unable to locate Signature Block for EnvelopedSignature Transform"); } unset($sxe->Signature); return $sxe->asXML(); } }
phphatesme/LiveTest
src/lib/Zend/InfoCard/XML/Security/Transform/EnvelopedSignature.php
PHP
mit
1,980
# encoding: utf-8 # # repeater.rb : Implements repeated page elements. # Heavy inspired by repeating_element() in PDF::Wrapper # http://pdf-wrapper.rubyforge.org/ # # Copyright November 2009, Gregory Brown. All Rights Reserved. # # This is free software. Please see the LICENSE and COPYING files for details. module Prawn class Document # A list of all repeaters in the document. # See Document#repeat for details # def repeaters @repeaters ||= [] end # Provides a way to execute a block of code repeatedly based on a # page_filter. Since Stamp is used under the hood, this method is very space # efficient. # # Available page filters are: # :all -- repeats on every page # :odd -- repeats on odd pages # :even -- repeats on even pages # some_array -- repeats on every page listed in the array # some_range -- repeats on every page included in the range # some_lambda -- yields page number and repeats for true return values # # Also accepts an optional second argument for dynamic content which executes the code # in the context of the filtered pages without using a Stamp. # # Example: # # Prawn::Document.generate("repeat.pdf", :skip_page_creation => true) do # # repeat :all do # draw_text "ALLLLLL", :at => bounds.top_left # end # # repeat :odd do # draw_text "ODD", :at => [0,0] # end # # repeat :even do # draw_text "EVEN", :at => [0,0] # end # # repeat [1,2] do # draw_text "[1,2]", :at => [100,0] # end # # repeat 2..4 do # draw_text "2..4", :at => [200,0] # end # # repeat(lambda { |pg| pg % 3 == 0 }) do # draw_text "Every third", :at => [250, 20] # end # # 10.times do # start_new_page # draw_text "A wonderful page", :at => [400,400] # end # # repeat(:all, :dynamic => true) do # text page_number, :at => [500, 0] # end # # end # def repeat(page_filter, options={}, &block) repeaters << Prawn::Repeater.new(self, page_filter, !!options[:dynamic], &block) end end class Repeater #:nodoc: class << self attr_writer :count def count @count ||= 0 end end attr_reader :name def initialize(document, page_filter, dynamic = false, &block) @document = document @page_filter = page_filter @dynamic = dynamic @stamp_name = "prawn_repeater(#{Repeater.count})" @document.create_stamp(@stamp_name, &block) unless dynamic @block = block if dynamic @graphic_state = document.state.page.graphic_state.dup Repeater.count += 1 end def match?(page_number) @document.page_match?(@page_filter, page_number) end def run(page_number) if !@dynamic @document.stamp(@stamp_name) if match?(page_number) elsif @block @document.save_graphics_state(@graphic_state) do @document.send(:freeze_stamp_graphics) @block.call end end end end end
CrossRef/tinypub
vendor/bundle/ruby/1.9.1/gems/prawn-0.12.0/lib/prawn/repeater.rb
Ruby
mit
3,253
<?php namespace Concrete\Core\Page\Type\Composer\Control\CorePageProperty; use Core; use Concrete\Core\Page\Page; use Concrete\Core\Attribute\FontAwesomeIconFormatter; class DescriptionCorePageProperty extends CorePageProperty { public function __construct() { $this->setCorePagePropertyHandle('description'); $this->setPageTypeComposerControlIconFormatter(new FontAwesomeIconFormatter('font')); } public function getPageTypeComposerControlName() { return tc('PageTypeComposerControlName', 'Description'); } public function publishToPage(Page $c, $data, $controls) { if (!is_array($data)) { $data = []; } $data += [ 'description' => null, ]; $this->addPageTypeComposerControlRequestValue('cDescription', $data['description']); parent::publishToPage($c, $data, $controls); } public function validate() { $e = Core::make('helper/validation/error'); $val = $this->getRequestValue(); if (isset($val['description'])) { $description = $val['description']; } else { $description = $this->getPageTypeComposerControlDraftValue(); } /** @var \Concrete\Core\Utility\Service\Validation\Strings $stringValidator */ $stringValidator = Core::make('helper/validation/strings'); if (!$stringValidator->notempty($description)) { $control = $this->getPageTypeComposerFormLayoutSetControlObject(); $e->add(t('You haven\'t chosen a valid %s', $control->getPageTypeComposerControlDisplayLabel())); return $e; } } public function getRequestValue($args = false) { $data = parent::getRequestValue($args); $data['description'] = Core::make('helper/security')->sanitizeString($data['description'] ?? ''); return $data; } public function getPageTypeComposerControlDraftValue() { if (is_object($this->page)) { $c = $this->page; return $c->getCollectionDescription(); } } }
deek87/concrete5
concrete/src/Page/Type/Composer/Control/CorePageProperty/DescriptionCorePageProperty.php
PHP
mit
2,120
using UnityEngine; using System; using LuaInterface; using SLua; using System.Collections.Generic; public class Lua_UnityEngine_UI_Text : LuaObject { [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int constructor(IntPtr l) { return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int FontTextureChanged(IntPtr l) { try{ UnityEngine.UI.Text self=checkSelf<UnityEngine.UI.Text>(l); self.FontTextureChanged(); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int GetGenerationSettings(IntPtr l) { try{ UnityEngine.UI.Text self=checkSelf<UnityEngine.UI.Text>(l); UnityEngine.Vector2 a1; checkType(l,2,out a1); UnityEngine.TextGenerationSettings ret=self.GetGenerationSettings(a1); pushValue(l,ret); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int GetTextAnchorPivot(IntPtr l) { try{ UnityEngine.TextAnchor a1; checkType(l,1,out a1); UnityEngine.Vector2 ret=UnityEngine.UI.Text.GetTextAnchorPivot(a1); pushValue(l,ret); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int CalculateLayoutInputHorizontal(IntPtr l) { try{ UnityEngine.UI.Text self=checkSelf<UnityEngine.UI.Text>(l); self.CalculateLayoutInputHorizontal(); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int CalculateLayoutInputVertical(IntPtr l) { try{ UnityEngine.UI.Text self=checkSelf<UnityEngine.UI.Text>(l); self.CalculateLayoutInputVertical(); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int OnRebuildRequested(IntPtr l) { try{ UnityEngine.UI.Text self=checkSelf<UnityEngine.UI.Text>(l); self.OnRebuildRequested(); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_cachedTextGenerator(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.cachedTextGenerator); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_cachedTextGeneratorForLayout(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.cachedTextGeneratorForLayout); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_defaultMaterial(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.defaultMaterial); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_mainTexture(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.mainTexture); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_font(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.font); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_font(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); UnityEngine.Font v; checkType(l,2,out v); o.font=v; return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_text(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.text); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_text(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); System.String v; checkType(l,2,out v); o.text=v; return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_supportRichText(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.supportRichText); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_supportRichText(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); System.Boolean v; checkType(l,2,out v); o.supportRichText=v; return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_resizeTextForBestFit(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.resizeTextForBestFit); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_resizeTextForBestFit(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); System.Boolean v; checkType(l,2,out v); o.resizeTextForBestFit=v; return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_resizeTextMinSize(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.resizeTextMinSize); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_resizeTextMinSize(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); System.Int32 v; checkType(l,2,out v); o.resizeTextMinSize=v; return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_resizeTextMaxSize(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.resizeTextMaxSize); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_resizeTextMaxSize(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); System.Int32 v; checkType(l,2,out v); o.resizeTextMaxSize=v; return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_alignment(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.alignment); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_alignment(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); UnityEngine.TextAnchor v; checkType(l,2,out v); o.alignment=v; return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_fontSize(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.fontSize); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_fontSize(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); System.Int32 v; checkType(l,2,out v); o.fontSize=v; return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_horizontalOverflow(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.horizontalOverflow); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_horizontalOverflow(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); UnityEngine.HorizontalWrapMode v; checkType(l,2,out v); o.horizontalOverflow=v; return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_verticalOverflow(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.verticalOverflow); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_verticalOverflow(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); UnityEngine.VerticalWrapMode v; checkType(l,2,out v); o.verticalOverflow=v; return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_lineSpacing(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.lineSpacing); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_lineSpacing(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); System.Single v; checkType(l,2,out v); o.lineSpacing=v; return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_fontStyle(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.fontStyle); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_fontStyle(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); UnityEngine.FontStyle v; checkType(l,2,out v); o.fontStyle=v; return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_pixelsPerUnit(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.pixelsPerUnit); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_minWidth(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.minWidth); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_preferredWidth(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.preferredWidth); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_flexibleWidth(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.flexibleWidth); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_minHeight(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.minHeight); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_preferredHeight(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.preferredHeight); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_flexibleHeight(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.flexibleHeight); return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_layoutPriority(IntPtr l) { UnityEngine.UI.Text o = checkSelf<UnityEngine.UI.Text>(l); pushValue(l,o.layoutPriority); return 1; } static public void reg(IntPtr l) { getTypeTable(l,"UnityEngine.UI.Text"); addMember(l,FontTextureChanged, "FontTextureChanged"); addMember(l,GetGenerationSettings, "GetGenerationSettings"); addMember(l,GetTextAnchorPivot, "GetTextAnchorPivot"); addMember(l,CalculateLayoutInputHorizontal, "CalculateLayoutInputHorizontal"); addMember(l,CalculateLayoutInputVertical, "CalculateLayoutInputVertical"); addMember(l,OnRebuildRequested, "OnRebuildRequested"); addMember(l,get_cachedTextGenerator, "get_cachedTextGenerator"); addMember(l,get_cachedTextGeneratorForLayout, "get_cachedTextGeneratorForLayout"); addMember(l,get_defaultMaterial, "get_defaultMaterial"); addMember(l,get_mainTexture, "get_mainTexture"); addMember(l,get_font, "get_font"); addMember(l,set_font, "set_font"); addMember(l,get_text, "get_text"); addMember(l,set_text, "set_text"); addMember(l,get_supportRichText, "get_supportRichText"); addMember(l,set_supportRichText, "set_supportRichText"); addMember(l,get_resizeTextForBestFit, "get_resizeTextForBestFit"); addMember(l,set_resizeTextForBestFit, "set_resizeTextForBestFit"); addMember(l,get_resizeTextMinSize, "get_resizeTextMinSize"); addMember(l,set_resizeTextMinSize, "set_resizeTextMinSize"); addMember(l,get_resizeTextMaxSize, "get_resizeTextMaxSize"); addMember(l,set_resizeTextMaxSize, "set_resizeTextMaxSize"); addMember(l,get_alignment, "get_alignment"); addMember(l,set_alignment, "set_alignment"); addMember(l,get_fontSize, "get_fontSize"); addMember(l,set_fontSize, "set_fontSize"); addMember(l,get_horizontalOverflow, "get_horizontalOverflow"); addMember(l,set_horizontalOverflow, "set_horizontalOverflow"); addMember(l,get_verticalOverflow, "get_verticalOverflow"); addMember(l,set_verticalOverflow, "set_verticalOverflow"); addMember(l,get_lineSpacing, "get_lineSpacing"); addMember(l,set_lineSpacing, "set_lineSpacing"); addMember(l,get_fontStyle, "get_fontStyle"); addMember(l,set_fontStyle, "set_fontStyle"); addMember(l,get_pixelsPerUnit, "get_pixelsPerUnit"); addMember(l,get_minWidth, "get_minWidth"); addMember(l,get_preferredWidth, "get_preferredWidth"); addMember(l,get_flexibleWidth, "get_flexibleWidth"); addMember(l,get_minHeight, "get_minHeight"); addMember(l,get_preferredHeight, "get_preferredHeight"); addMember(l,get_flexibleHeight, "get_flexibleHeight"); addMember(l,get_layoutPriority, "get_layoutPriority"); newType(l, constructor); createTypeMetatable(l, typeof(UnityEngine.UI.Text),typeof(UnityEngine.UI.MaskableGraphic)); LuaDLL.lua_pop(l, 1); } }
idada/slua
Assets/Slua/LuaObject/Lua_UnityEngine_UI_Text.cs
C#
mit
12,980
<?php namespace Modules\Core\Console\Installers\Scripts\UserProviders; use Modules\Core\Console\Installers\SetupScript; class UsherInstaller extends ProviderInstaller implements SetupScript { /** * @var string */ protected $driver = 'Usher'; /** * Check if the user driver is correctly registered. * @return bool */ public function checkIsInstalled() { return class_exists('Maatwebsite\Usher\UsherServiceProvider') && class_exists('Mitch\LaravelDoctrine\LaravelDoctrineServiceProvider'); } /** * Not called * @return mixed */ public function composer() { $this->application->register('Maatwebsite\Usher\UsherServiceProvider'); } /** * @return mixed */ public function publish() { if ($this->command->option('verbose')) { $this->command->call('vendor:publish', ['--provider' => 'Maatwebsite\Usher\UsherServiceProvider']); return $this->command->call('vendor:publish', ['--provider' => 'Mitch\LaravelDoctrine\LaravelDoctrineServiceProvider']); } $this->command->callSilent('vendor:publish', ['--provider' => 'Maatwebsite\Usher\UsherServiceProvider']); return $this->command->callSilent('vendor:publish', ['--provider' => 'Mitch\LaravelDoctrine\LaravelDoctrineServiceProvider']); } /** * @return mixed */ public function migrate() { if ($this->command->option('verbose')) { return $this->command->call('doctrine:schema:update'); } return $this->command->callSilent('doctrine:schema:update'); } /** * @return mixed */ public function configure() { $path = base_path("config/usher.php"); $config = $this->finder->get($path); $config = str_replace('Maatwebsite\Usher\Domain\Users\UsherUser', "Modules\\User\\Entities\\{$this->driver}\\User", $config); $config = str_replace('Maatwebsite\Usher\Domain\Roles\UsherRole', "Modules\\User\\Entities\\{$this->driver}\\Role", $config); $this->finder->put($path, $config); // Doctrine config $path = base_path("config/doctrine.php"); $config = $this->finder->get($path); $config = str_replace('// Paths to entities here...', 'base_path(\'Modules/User/Entities/Usher\')', $config); $this->finder->put($path, $config); $this->bindUserRepositoryOnTheFly('Usher'); $this->application->register('Maatwebsite\Usher\UsherServiceProvider'); $this->application->register('Mitch\LaravelDoctrine\LaravelDoctrineServiceProvider'); } /** * @return mixed */ public function seed() { if ($this->command->option('verbose')) { return $this->command->call('db:seed', ['--class' => 'Modules\User\Database\Seeders\UsherTableSeeder']); } return $this->command->callSilent('db:seed', ['--class' => 'Modules\User\Database\Seeders\UsherTableSeeder']); } /** * @param $password * @return mixed */ public function getHashedPassword($password) { return $password; } }
ruscon/Core
Console/Installers/Scripts/UserProviders/UsherInstaller.php
PHP
mit
3,182
const Combinatorics = require('js-combinatorics'); const widths = [null, 20, 60]; const heights = [null, 40, 80]; const horizontalAlignments = [null, 'left', 'right', 'center']; const verticalAlignments = [null, 'bottom', 'top', 'center']; const orients = [null, 'horizontal', 'vertical']; const caps = [null, 10, 20]; const results = { bar: { keys: ['width', 'height', 'horizontalAlign', 'verticalAlign'], combinations: Combinatorics.cartesianProduct( widths, // Bar chart needs a width heights.slice(1), horizontalAlignments, verticalAlignments ).toArray() }, boxPlot: { keys: ['width', 'orient', 'cap'], combinations: Combinatorics.cartesianProduct( widths, orients, caps ).toArray() }, candlestick: { keys: ['width'], combinations: Combinatorics.cartesianProduct( widths ).toArray() }, errorBar: { keys: ['width', 'orient'], combinations: Combinatorics.cartesianProduct( widths, orients ).toArray() }, ohlc: { keys: ['width', 'orient'], combinations: Combinatorics.cartesianProduct( widths, orients ).toArray() } }; module.exports = results;
chrisprice/d3fc
packages/d3fc-shape/test/data/options.js
JavaScript
mit
1,363
"use strict"; const Utils = require("../../core/Utils"); const RequestQueue = require("./RequestQueue"); const ChainedBucket = require("./ChainedBucket"); class RequestQueueGroup { constructor(bucketFactory) { this.queues = {}; this.bucketFactory = bucketFactory || null; if (!(bucketFactory instanceof BucketFactory)) { throw new TypeError( "Param 'bucketFactory' is not an instance of BucketFactory" ); } } get(id) { if (!this.queues[id]) { const bucket = (this.bucketFactory && this.bucketFactory.get(id)); this.queues[id] = new RequestQueue(bucket); } this.queues[id].id = id; return this.queues[id]; } delete(id) { if (this.bucketFactory) this.bucketFactory.delete(id); delete this.queues[id]; } deleteContaining(id) { var keys = Object.keys(this.queues); for (var i = 0, len = keys.length; i < len; i++) { var key = keys[i]; if (!key || key.indexOf(id) < 0) continue; this.delete(key); } } } class BucketFactory { constructor(manager, size, duration, name, parent) { this.manager = manager; this.size = size; this.duration = duration; this.name = name; this.parent = parent || null; if (!(manager instanceof RequestQueueManager)) throw new TypeError("Param 'manager' is invalid"); if (typeof size !== "number") throw new TypeError("Param 'size' is not a number"); if (typeof duration !== "number") throw new TypeError("Param 'duration' is not a number"); if (typeof name !== "string") throw new TypeError("Param 'name' is not a string"); } makeName(id) { return this.name + ":" + id; } get(id) { const parent = this.parent instanceof BucketFactory ? this.parent.get(id) : this.parent; return this.manager._createBucket( this.size, this.duration, this.makeName(id), parent ); } delete(id) { delete this.manager.buckets[this.makeName(id)]; } } class RequestQueueManager { constructor(discordie) { this._discordie = discordie; this.isBot = true; this.disabled = false; this.buckets = {}; this.bucketFactories = {}; // whole API, bucket blocks when client gets a HTTP 429 with global flag const _bot_global = this._createBucket(Infinity, 1000, "bot:global"); this.globalBucket = _bot_global; // msg 10/10s const _msg = this._createBucket(10, 10000, "msg", _bot_global); this.userMessageQueue = new RequestQueue(_msg); // per-channel bot:msg:dm 10/10s const _bot_msg_dm = this._createBucketFactory(10, 10000, "bot:msg:dm", _bot_global); this.botDirectMessageQueues = new RequestQueueGroup(_bot_msg_dm); // per-guild bot:msg:server 10/10s const _bot_msg_server = this._createBucketFactory(10, 10000, "bot:msg:server", _bot_global); this.botMessageQueues = new RequestQueueGroup(_bot_msg_server); // per-guild dmsg 5/1s const _dmsg = this._createBucketFactory(5, 1000, "dmsg", _bot_global); this.messageDeleteQueues = new RequestQueueGroup(_dmsg); // per-guild bdmsg 1/1s const _bdmsg = this._createBucketFactory(1, 1000, "bdmsg", _bot_global); this.messageBulkDeleteQueues = new RequestQueueGroup(_bdmsg); // per-guild guild_member 10/10s const _guild_member = this._createBucketFactory(10, 10000, "guild_member", _bot_global); this.guildMemberPatchQueues = new RequestQueueGroup(_guild_member); // per-guild guild_member_nick 1/1s const _guild_member_nick = this._createBucketFactory(1, 1000, "guild_member_nick", _bot_global); this.guildMemberNickQueues = new RequestQueueGroup(_guild_member_nick); // all other requests go here with route as key // bucket size should be set by HTTP headers const _bot_generic = this._createBucketFactory(Infinity, 5000, "bot:generic", _bot_global); this.genericRequestQueues = new RequestQueueGroup(_bot_generic); discordie.Dispatcher.on("GATEWAY_DISPATCH", e => { if (!e.data) return; if (e.type === "READY") { if (!e.data.user) return; this.isBot = e.data.user.bot || false; } if (e.type === "GUILD_DELETE") { this._deleteGuildQueues(e.data.id); } if (e.type === "CHANNEL_DELETE") { this._deleteChannelQueues(e.data.id); } }); Utils.privatify(this); } _reset() { Object.keys(this.buckets).forEach(k => this.buckets[k].refill()); } _createBucket(size, duration, name, parent) { if (!this.buckets[name]) { this.buckets[name] = new ChainedBucket(size, duration, name, parent); } else { this.buckets[name].refill(); } return this.buckets[name]; } _createBucketFactory(size, duration, name, parent) { if (!this.bucketFactories[name]) { this.bucketFactories[name] = new BucketFactory(this, size, duration, name, parent); } return this.bucketFactories[name]; } put(request, sendCallback) { const route = request.path .replace(/\/\d+$/g, "") .replace(/\d+/g, ":id"); // convert to route: <- /api/guilds/:guild_id/bans/:user_id // -> /api/guilds/:id/bans // <- /api/channels/:channel_id // -> /api/channels/ const queue = this.genericRequestQueues.get(route); this._enqueueTo(queue, request, sendCallback); } putToRoute(request, route, sendCallback) { const queue = this.genericRequestQueues.get(route); this._enqueueTo(queue, request, sendCallback); } putMessage(request, channelId, sendCallback) { const channel = this._discordie._channels.get(channelId); var queue = this.userMessageQueue; if (this.isBot && channel) { if (channel.is_private || !channel.guild_id) { queue = this.botDirectMessageQueues.get(channelId); } else { queue = this.botMessageQueues.get(channel.guild_id); } } this._enqueueTo(queue, request, sendCallback); } putDeleteMessage(request, channelId, sendCallback) { const group = this.messageDeleteQueues; this._enqueueToGroup(group, request, channelId, sendCallback); } putBulkDeleteMessage(request, channelId, sendCallback) { const group = this.messageBulkDeleteQueues; this._enqueueToGroup(group, request, channelId, sendCallback); } putGuildMemberPatch(request, guildId, sendCallback) { const queue = this.guildMemberPatchQueues.get(guildId); this._enqueueTo(queue, request, sendCallback); } putGuildMemberNick(request, guildId, sendCallback) { const queue = this.guildMemberNickQueues.get(guildId); this._enqueueTo(queue, request, sendCallback); } _enqueueToGroup(group, request, channelId, sendCallback) { const channel = this._discordie._channels.get(channelId); const guildId = (channel && channel.guild_id) || null; this._enqueueTo(group.get(guildId), request, sendCallback); } _enqueueTo(queue, request, sendCallback) { if (this.disabled) { return request.send(sendCallback); } queue.enqueue(request, sendCallback); } _deleteGuildQueues(guildId) { const groups = [ this.botMessageQueues, this.messageDeleteQueues, this.messageBulkDeleteQueues, this.guildMemberPatchQueues ]; groups.forEach(g => g.delete(guildId)); this.genericRequestQueues.deleteContaining(guildId); } _deleteChannelQueues(channelId) { this.botDirectMessageQueues.delete(channelId); this.genericRequestQueues.deleteContaining(channelId); } } module.exports = RequestQueueManager;
Gamecloud-Solutions/streambot
node_modules/discordie/lib/core/ratelimiting/RequestQueueManager.js
JavaScript
mit
7,655
/******************************************************************************* * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences.cleanup; import java.util.Iterator; import java.util.Map; import org.eclipse.jdt.internal.corext.fix.CleanUpConstants; import org.eclipse.jdt.ui.cleanup.CleanUpOptions; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.preferences.formatter.IProfileVersioner; import org.eclipse.jdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile; public class CleanUpProfileVersioner implements IProfileVersioner { public static final String PROFILE_KIND= "CleanUpProfile"; //$NON-NLS-1$ private static final int VERSION_1= 1; // 3.3M2 private static final int VERSION_2= 2; // 3.3M3 Added ORGANIZE_IMPORTS public static final int CURRENT_VERSION= VERSION_2; /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.preferences.cleanup.IProfileVersioner#getFirstVersion() */ public int getFirstVersion() { return VERSION_1; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.preferences.cleanup.IProfileVersioner#getCurrentVersion() */ public int getCurrentVersion() { return CURRENT_VERSION; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.preferences.cleanup.IProfileVersioner#updateAndComplete(org.eclipse.jdt.internal.ui.preferences.cleanup.ProfileManager.CustomProfile) */ public void update(CustomProfile profile) { final Map<String, String> oldSettings= profile.getSettings(); Map<String, String> newSettings= updateAndComplete(oldSettings, profile.getVersion()); profile.setVersion(CURRENT_VERSION); profile.setSettings(newSettings); } private Map<String, String> updateAndComplete(Map<String, String> oldSettings, int version) { final Map<String, String> newSettings= JavaPlugin.getDefault().getCleanUpRegistry().getDefaultOptions(CleanUpConstants.DEFAULT_CLEAN_UP_OPTIONS).getMap(); switch (version) { case VERSION_1: updateFrom1To2(oldSettings); //$FALL-THROUGH$ default: for (final Iterator<String> iter= oldSettings.keySet().iterator(); iter.hasNext();) { final String key= iter.next(); if (!newSettings.containsKey(key)) continue; final String value= oldSettings.get(key); if (value != null) { newSettings.put(key, value); } } } return newSettings; } /** * {@inheritDoc} */ public String getProfileKind() { return PROFILE_KIND; } private static void updateFrom1To2(Map<String, String> settings) { CleanUpOptions defaultSettings= JavaPlugin.getDefault().getCleanUpRegistry().getDefaultOptions(CleanUpConstants.DEFAULT_CLEAN_UP_OPTIONS); settings.put(CleanUpConstants.ORGANIZE_IMPORTS, defaultSettings.getValue(CleanUpConstants.ORGANIZE_IMPORTS)); } }
brunyuriy/quick-fix-scout
org.eclipse.jdt.ui_3.7.1.r371_v20110824-0800/src/org/eclipse/jdt/internal/ui/preferences/cleanup/CleanUpProfileVersioner.java
Java
mit
3,278
'use strict'; const { Symbol } = primordials; const { kUpdateTimer, onStreamRead, } = require('internal/stream_base_commons'); const { owner_symbol } = require('internal/async_hooks').symbols; const { Readable } = require('stream'); const kHandle = Symbol('kHandle'); class HeapSnapshotStream extends Readable { constructor(handle) { super({ autoDestroy: true }); this[kHandle] = handle; handle[owner_symbol] = this; handle.onread = onStreamRead; } _read() { if (this[kHandle]) this[kHandle].readStart(); } _destroy() { // Release the references on the handle so that // it can be garbage collected. this[kHandle][owner_symbol] = undefined; this[kHandle] = undefined; } [kUpdateTimer]() { // Does nothing } } module.exports = { HeapSnapshotStream };
enclose-io/compiler
lts/lib/internal/heap_utils.js
JavaScript
mit
826
import hasFeature from './has'; export function prop(path) { return function(state, props) { const names = path.split('.'); if (!(names[0] in props)) { throw new Error(`Missing required prop ${names[0]}.`); } return names.reduce((p, name) => (p && p[name]), props); }; } export function has(featureName) { return function(_props, _state, browser) { return hasFeature(featureName, browser); }; }
tf/pageflow-dependabot-test
node_package/src/utils/selectors.js
JavaScript
mit
433
using System; using System.Collections; using System.IO; namespace Wox.Infrastructure { public class IniParser { private Hashtable keyPairs = new Hashtable(); private String iniFilePath; private struct SectionPair { public String Section; public String Key; } /// <summary> /// Opens the INI file at the given path and enumerates the values in the IniParser. /// </summary> /// <param name="iniPath">Full path to INI file.</param> public IniParser(String iniPath) { TextReader iniFile = null; String strLine = null; String currentRoot = null; String[] keyPair = null; iniFilePath = iniPath; if (File.Exists(iniPath)) { try { iniFile = new StreamReader(iniPath); strLine = iniFile.ReadLine(); while (strLine != null) { strLine = strLine.Trim(); if (strLine != "") { if (strLine.StartsWith("[") && strLine.EndsWith("]")) { currentRoot = strLine.Substring(1, strLine.Length - 2).ToUpper(); } else { keyPair = strLine.Split(new char[] { '=' }, 2); SectionPair sectionPair; String value = null; if (currentRoot == null) currentRoot = "ROOT"; sectionPair.Section = currentRoot; sectionPair.Key = keyPair[0].ToUpper().Trim(); if (keyPair.Length > 1) value = keyPair[1]; keyPairs.Add(sectionPair, value.Trim()); } } strLine = iniFile.ReadLine(); } } catch (Exception ex) { throw ex; } finally { if (iniFile != null) iniFile.Close(); } } else throw new FileNotFoundException("Unable to locate " + iniPath); } /// <summary> /// Returns the value for the given section, key pair. /// </summary> /// <param name="sectionName">Section name.</param> /// <param name="settingName">Key name.</param> public String GetSetting(String sectionName, String settingName) { SectionPair sectionPair; sectionPair.Section = sectionName.ToUpper().Trim(); sectionPair.Key = settingName.ToUpper().Trim(); return (String)keyPairs[sectionPair]; } /// <summary> /// Enumerates all lines for given section. /// </summary> /// <param name="sectionName">Section to enum.</param> public String[] EnumSection(String sectionName) { ArrayList tmpArray = new ArrayList(); foreach (SectionPair pair in keyPairs.Keys) { if (pair.Section == sectionName.ToUpper()) tmpArray.Add(pair.Key); } return (String[])tmpArray.ToArray(typeof(String)); } /// <summary> /// Adds or replaces a setting to the table to be saved. /// </summary> /// <param name="sectionName">Section to add under.</param> /// <param name="settingName">Key name to add.</param> /// <param name="settingValue">Value of key.</param> public void AddSetting(String sectionName, String settingName, String settingValue) { SectionPair sectionPair; sectionPair.Section = sectionName.ToUpper(); sectionPair.Key = settingName.ToUpper(); if (keyPairs.ContainsKey(sectionPair)) keyPairs.Remove(sectionPair); keyPairs.Add(sectionPair, settingValue); } /// <summary> /// Adds or replaces a setting to the table to be saved with a null value. /// </summary> /// <param name="sectionName">Section to add under.</param> /// <param name="settingName">Key name to add.</param> public void AddSetting(String sectionName, String settingName) { AddSetting(sectionName, settingName, null); } /// <summary> /// Remove a setting. /// </summary> /// <param name="sectionName">Section to add under.</param> /// <param name="settingName">Key name to add.</param> public void DeleteSetting(String sectionName, String settingName) { SectionPair sectionPair; sectionPair.Section = sectionName.ToUpper(); sectionPair.Key = settingName.ToUpper(); if (keyPairs.ContainsKey(sectionPair)) keyPairs.Remove(sectionPair); } /// <summary> /// Save settings to new file. /// </summary> /// <param name="newFilePath">New file path.</param> public void SaveSettings(String newFilePath) { ArrayList sections = new ArrayList(); String tmpValue = ""; String strToSave = ""; foreach (SectionPair sectionPair in keyPairs.Keys) { if (!sections.Contains(sectionPair.Section)) sections.Add(sectionPair.Section); } foreach (String section in sections) { strToSave += ("[" + section + "]\r\n"); foreach (SectionPair sectionPair in keyPairs.Keys) { if (sectionPair.Section == section) { tmpValue = (String)keyPairs[sectionPair]; if (tmpValue != null) tmpValue = "=" + tmpValue; strToSave += (sectionPair.Key + tmpValue + "\r\n"); } } strToSave += "\r\n"; } try { TextWriter tw = new StreamWriter(newFilePath); tw.Write(strToSave); tw.Close(); } catch (Exception ex) { throw ex; } } /// <summary> /// Save settings back to ini file. /// </summary> public void SaveSettings() { SaveSettings(iniFilePath); } } }
orzFly/Wox
Wox.Infrastructure/IniParser.cs
C#
mit
6,980
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation.Remoting { /// <summary> /// Class that encapsulates the information carried by the RunspaceInitInfo PSRP message. /// </summary> internal class RunspacePoolInitInfo { /// <summary> /// Min Runspaces setting on the server runspace pool. /// </summary> internal int MinRunspaces { get; } /// <summary> /// Max Runspaces setting on the server runspace pool. /// </summary> internal int MaxRunspaces { get; } /// <summary> /// Constructor. /// </summary> /// <param name="minRS"></param> /// <param name="maxRS"></param> internal RunspacePoolInitInfo(int minRS, int maxRS) { MinRunspaces = minRS; MaxRunspaces = maxRS; } } }
JamesWTruher/PowerShell-1
src/System.Management.Automation/engine/remoting/common/RunspaceInitInfo.cs
C#
mit
970
package org.ethereum.core; import org.ethereum.crypto.HashUtil; import org.junit.Assert; import org.junit.Test; import org.spongycastle.util.encoders.Hex; /** * @author Roman Mandeleil * @since 20.11.2014 */ public class BloomTest { @Test /// based on http://bit.ly/1MtXxFg public void test1(){ byte[] address = Hex.decode("095e7baea6a6c7c4c2dfeb977efac326af552d87"); Bloom addressBloom = Bloom.create(HashUtil.sha3(address)); byte[] topic = Hex.decode("0000000000000000000000000000000000000000000000000000000000000000"); Bloom topicBloom = Bloom.create(HashUtil.sha3(topic)); Bloom totalBloom = new Bloom(); totalBloom.or(addressBloom); totalBloom.or(topicBloom); Assert.assertEquals( "00000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000040000000000000000000000000000000000000000000000000000000", totalBloom.toString() ); Assert.assertTrue(totalBloom.matches(addressBloom)); Assert.assertTrue(totalBloom.matches(topicBloom)); Assert.assertFalse(totalBloom.matches(Bloom.create(HashUtil.sha3(Hex.decode("1000000000000000000000000000000000000000000000000000000000000000"))))); Assert.assertFalse(totalBloom.matches(Bloom.create(HashUtil.sha3(Hex.decode("195e7baea6a6c7c4c2dfeb977efac326af552d87"))))); } @Test public void test2() { // todo: more testing } @Test public void test3() { // todo: more testing } @Test public void test4() { // todo: more testing } }
gcc2ge/ethereumj
ethereumj-core/src/test/java/org/ethereum/core/BloomTest.java
Java
mit
1,992