text
stringlengths
2
1.04M
meta
dict
<?php /** * BaseAnhang * * This class has been auto-generated by the Doctrine ORM Framework * * @property string $path * @property string $name * @property integer $anlage_id * @property Anlage $Anlage * * @method string getPath() Returns the current record's "path" value * @method string getName() Returns the current record's "name" value * @method integer getAnlageId() Returns the current record's "anlage_id" value * @method Anlage getAnlage() Returns the current record's "Anlage" value * @method Anhang setPath() Sets the current record's "path" value * @method Anhang setName() Sets the current record's "name" value * @method Anhang setAnlageId() Sets the current record's "anlage_id" value * @method Anhang setAnlage() Sets the current record's "Anlage" value * * @package openZIM * @subpackage model * @author Your name here * @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $ */ abstract class BaseAnhang extends sfDoctrineRecord { public function setTableDefinition() { $this->setTableName('anhang'); $this->hasColumn('path', 'string', 255, array( 'type' => 'string', 'notnull' => true, 'unique' => true, 'length' => 255, )); $this->hasColumn('name', 'string', 255, array( 'type' => 'string', 'length' => 255, )); $this->hasColumn('anlage_id', 'integer', null, array( 'type' => 'integer', 'notnull' => true, )); } public function setUp() { parent::setUp(); $this->hasOne('Anlage', array( 'local' => 'anlage_id', 'foreign' => 'id', 'onDelete' => 'CASCADE')); $timestampable0 = new Doctrine_Template_Timestampable(); $this->actAs($timestampable0); } }
{ "content_hash": "ac7644270ac349f80c09e4908e8b2e47", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 80, "avg_line_length": 32.59322033898305, "alnum_prop": 0.5746229849193968, "repo_name": "maggsta/openzim", "id": "679b6cd15fa646e7152184bfd58c28486c0a99a2", "size": "1923", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/model/doctrine/base/BaseAnhang.class.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "19069" }, { "name": "JavaScript", "bytes": "57474" }, { "name": "PHP", "bytes": "806963" }, { "name": "Perl", "bytes": "3220" }, { "name": "Shell", "bytes": "1067" }, { "name": "XSLT", "bytes": "108993" } ], "symlink_target": "" }
angular.module('myApp') .controller('UserController', function ($scope, UserFactory, DataTable, UserService, $localStorage,$state) { //fetch du lieu Role if ($localStorage.user.role.name === 'admin') { UserService.fetchRole() .then(function (response) { $scope.roles = response.data; }) .catch(function (err) { alert('Load role that bai' + {message: err}); }); $scope.edit = function (data) { $scope.$apply(function () { $scope.user = angular.copy(data); $scope.user.role = $scope.user.role._id; }); }; //reset data khi nhập mới $scope.addNew = function () { $scope.user = {} }; //xóa object $scope.delete = function (data) { $scope.$apply(function () { $scope.user = data; }); UserService.deleteUser($scope.user._id) .then(function () { alert('Delete Success'); angular.element('#user_table').DataTable().ajax.reload(null, false); }) .catch(function (ex) { alert(err.toString()) }) ; }; //khi click vào nút save $scope.save = function (data) { //kiểm tra có id ko,có thì update,ko thì create var checkIdExit = ($scope.user._id ) ? UserService.updateUser : UserService.createUser; checkIdExit.call(null, $scope.user) .then(function () { alert('Success'); angular.element('#userModal').modal('hide'); angular.element('#user_table').DataTable().ajax.reload(null, false); }) .catch(function (err) { alert("Data is invalid"); console.log(err.toString); }) }; UserFactory.fetchAllProducts() .then(function (response) { $scope.products = response.data; }) .catch(function () { $scope.products = []; }); var loadUser = function () { var options = { url: 'http://localhost:8081/user/fetch', columns: [ {'title': 'Id', 'data': '_id'}, {'title': 'Username', 'data': 'username'}, {'title': 'Password', 'data': 'password'}, {'title': 'Role Name', 'data': 'role.name', "defaultContent": "Not available"}, {'title': 'Create Date', 'data': 'createdAt', "defaultContent": "Not available"}, {'title': 'Modifined Date', 'data': 'updatedAt', "defaultContent": "Not available"}, {'title': 'Action', 'data': null} ], columnDefs: [ { "render": function (data, type, row) { return '<button class="btn btn-danger" id="btn-delete"><i class="fa fa-trash-o" aria-hidden="true"></i></button>' + '<button class="btn btn-info" id="btn-edit" ' + 'data-toggle="modal" data-target="#userModal" data-whatever="@mdo">' + '<i class="fa fa-pencil" aria-hidden = "true"></i></button>' }, "targets": 6 } ] }; options.delete = function (data) { $scope.delete(data); }; options.edit = function (data) { $scope.edit(data); }; DataTable.generateDataTable(options, angular.element('#user_table')); }; loadUser(); } else{ $state.go('dashboard'); } });
{ "content_hash": "e96be881912da743a1e91f0276651362", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 145, "avg_line_length": 40.23148148148148, "alnum_prop": 0.3995397008055236, "repo_name": "thuanprovp1/thuan", "id": "003d25b8d29e5d0d92800bd33f31817517b4c352", "size": "4358", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/admin/user/user.controller.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "333143" }, { "name": "HTML", "bytes": "110001" }, { "name": "JavaScript", "bytes": "435347" } ], "symlink_target": "" }
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Composition Imports Microsoft.NetCore.Analyzers.InteropServices Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Namespace Microsoft.NetCore.VisualBasic.Analyzers.InteropServices ''' <summary> ''' CA1414: Mark boolean PInvoke arguments with MarshalAs ''' </summary> <ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]> Public NotInheritable Class BasicMarkBooleanPInvokeArgumentsWithMarshalAsFixer Inherits MarkBooleanPInvokeArgumentsWithMarshalAsFixer End Class End Namespace
{ "content_hash": "70dd50dd1873e5da8448658d0f2f5a28", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 159, "avg_line_length": 42.23529411764706, "alnum_prop": 0.8064066852367688, "repo_name": "mavasani/roslyn-analyzers", "id": "27353e580005c7302f08eb98e5beef220779edc6", "size": "718", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/InteropServices/BasicMarkBooleanPInvokeArgumentsWithMarshalAs.Fixer.vb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5365" }, { "name": "C#", "bytes": "13544666" }, { "name": "CMake", "bytes": "9446" }, { "name": "PowerShell", "bytes": "160438" }, { "name": "Rich Text Format", "bytes": "123141" }, { "name": "Shell", "bytes": "107224" }, { "name": "Smalltalk", "bytes": "705" }, { "name": "Vim Snippet", "bytes": "2225" }, { "name": "Visual Basic .NET", "bytes": "195294" } ], "symlink_target": "" }
/* */ package com.hundsun.network.gates.genshan.web.action.trade; /* */ /* */ import com.hundsun.network.gates.genshan.biz.domain.query.TradeSubstationQuery; /* */ import com.hundsun.network.gates.genshan.biz.domain.trade.TradeSubstation; /* */ import com.hundsun.network.gates.genshan.biz.service.trade.TradeSubstationService; /* */ import com.hundsun.network.gates.genshan.common.UserAgent; /* */ import com.hundsun.network.gates.genshan.security.AdminAccess; /* */ import com.hundsun.network.gates.genshan.web.action.BaseAction; /* */ import com.hundsun.network.gates.genshan.web.validator.TradeSubstationAddValidator; /* */ import org.springframework.beans.factory.annotation.Autowired; /* */ import org.springframework.stereotype.Controller; /* */ import org.springframework.ui.Model; /* */ import org.springframework.ui.ModelMap; /* */ import org.springframework.validation.BindingResult; /* */ import org.springframework.web.bind.annotation.ModelAttribute; /* */ import org.springframework.web.bind.annotation.RequestMapping; /* */ import org.springframework.web.bind.annotation.RequestParam; /* */ /* */ @Controller /* */ public class TradeSubstationAction extends BaseAction /* */ { /* */ /* */ @Autowired /* */ private TradeSubstationService tradeSubstationService; /* */ /* */ @Autowired /* */ private TradeSubstationAddValidator tradeSubstationAddValidator; /* */ /* */ @AdminAccess({com.hundsun.network.gates.genshan.common.PermissionEnum.SUBSTATION_R_LIST}) /* */ @RequestMapping({"/substation/list"}) /* */ public void substationList(@ModelAttribute("query") TradeSubstationQuery query, Model model) /* */ { /* 41 */ if (null == query) { /* 42 */ query = new TradeSubstationQuery(); /* */ } /* 44 */ if ((query.getName() != null) && (query.getName().length() > 0)) { /* 45 */ query.setName(query.getName().trim()); /* */ } /* 47 */ this.tradeSubstationService.getTradeSubstationList(query); /* */ } /* */ /* */ @AdminAccess({com.hundsun.network.gates.genshan.common.PermissionEnum.SUBSTATION_C_ADD}) /* */ @RequestMapping(value={"/substation/add"}, method={org.springframework.web.bind.annotation.RequestMethod.GET}) /* */ public String substationAdd(@ModelAttribute("tradeSubstation") TradeSubstation tradeSubstation, ModelMap model) /* */ { /* 57 */ return "/substation/add"; /* */ } /* */ /* */ @AdminAccess({com.hundsun.network.gates.genshan.common.PermissionEnum.SUBSTATION_C_ADD}) /* */ @RequestMapping(value={"/substation/add"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) /* */ public String substationAdd(@ModelAttribute("tradeSubstation") TradeSubstation tradeSubstation, BindingResult bindingResult, ModelMap model, UserAgent userAgent) /* */ { /* 69 */ this.tradeSubstationAddValidator.validate(tradeSubstation, bindingResult); /* */ /* 71 */ if (!bindingResult.hasErrors()) { /* 72 */ TradeSubstation old = this.tradeSubstationService.getTradeSubstationById(tradeSubstation.getId()); /* 73 */ if (old != null) { /* 74 */ bindingResult.rejectValue("id", null, null, "分中心ID已存在"); /* */ } /* */ } /* 77 */ if (bindingResult.hasErrors()) { /* 78 */ return "/substation/add"; /* */ } /* 80 */ tradeSubstation.setOperator(userAgent.getUserAccount()); /* 81 */ this.tradeSubstationService.insert(tradeSubstation); /* 82 */ model.put("url", "/substation/list"); /* 83 */ return success(model); /* */ } /* */ /* */ @AdminAccess({com.hundsun.network.gates.genshan.common.PermissionEnum.SUBSTATION_D_DEL}) /* */ @RequestMapping(value={"/substation/del"}, method={org.springframework.web.bind.annotation.RequestMethod.GET}) /* */ public String substationDel(@RequestParam("id") Long id, ModelMap model) /* */ { /* 92 */ model.put("url", "/substation/list"); /* 93 */ Integer result = this.tradeSubstationService.delete(id); /* 94 */ if ((null == result) || (result.intValue() <= 0)) { /* 95 */ model.put("message", "删除交易分中心失败!"); /* 96 */ return error(model); /* */ } /* 98 */ return success(model); /* */ } /* */ /* */ @AdminAccess({com.hundsun.network.gates.genshan.common.PermissionEnum.SUBSTATION_U_EDIT}) /* */ @RequestMapping(value={"/substation/edit"}, method={org.springframework.web.bind.annotation.RequestMethod.GET}) /* */ public String edit(@RequestParam("id") Long id, ModelMap model) /* */ { /* 108 */ TradeSubstation tradeSubstation = this.tradeSubstationService.getTradeSubstationById(id); /* 109 */ if (null == tradeSubstation) { /* 110 */ model.put("message", "无此交易分中心!"); /* 111 */ return error(model); /* */ } /* 113 */ model.put("tradeSubstation", tradeSubstation); /* 114 */ return "/substation/edit"; /* */ } /* */ /* */ @AdminAccess({com.hundsun.network.gates.genshan.common.PermissionEnum.SUBSTATION_U_EDIT}) /* */ @RequestMapping(value={"/substation/edit"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) /* */ public String edit(@ModelAttribute("tradeSubstation") TradeSubstation tradeSubstation, BindingResult bindingResult, ModelMap model, UserAgent userAgent) /* */ { /* 126 */ this.tradeSubstationAddValidator.validate(tradeSubstation, bindingResult); /* 127 */ if (bindingResult.hasErrors()) { /* 128 */ return "/substation/edit"; /* */ } /* 130 */ tradeSubstation.setOperator(userAgent.getUserAccount()); /* 131 */ Integer result = this.tradeSubstationService.update(tradeSubstation); /* 132 */ model.put("url", "/substation/list"); /* 133 */ if ((null == result) || (result.intValue() <= 0)) { /* 134 */ model.put("message", "修改交易分中心失败!"); /* 135 */ return error(model); /* */ } /* 137 */ return success(model); /* */ } /* */ } /* Location: E:\__安装归档\linquan-20161112\deploy15\genshan\webroot\WEB-INF\classes\ * Qualified Name: com.hundsun.network.gates.genshan.web.action.trade.TradeSubstationAction * JD-Core Version: 0.6.0 */
{ "content_hash": "a4f8c533f0e395a5235c657bb1f17a55", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 173, "avg_line_length": 54.940677966101696, "alnum_prop": 0.6245565324695357, "repo_name": "hnccfr/ccfrweb", "id": "6fb03acbf3bf59eab1815ab1ea16dcb1b0685380", "size": "6559", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "admin/src/com/hundsun/network/gates/genshan/web/action/trade/TradeSubstationAction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "876270" }, { "name": "ColdFusion", "bytes": "11076" }, { "name": "FreeMarker", "bytes": "365900" }, { "name": "HTML", "bytes": "954968" }, { "name": "Java", "bytes": "6773229" }, { "name": "JavaScript", "bytes": "4104546" }, { "name": "PHP", "bytes": "11708" }, { "name": "Perl", "bytes": "9673" } ], "symlink_target": "" }
package com.leetcode3; import java.util.Arrays; import java.util.Comparator; /** * https://leetcode.com/problems/course-schedule-iii/solution/ * Diary: Had to reference solution. 4th solution is very smart! * Explanation: See approach 3 * - Sort the course array by ascending order of end date * - Keep 1 running variable of time indicating the current time finishing a course ith */ public class CourseSchedule3 { // solution: dynamic programming public int scheduleCourse(int[][] cs) { if (cs==null) return 0; int n = cs.length; if (n==0) return 0; // first sort all course by deadline date - time-spent day count Arrays.sort( cs, Comparator.comparing((int[] c) -> c[1]) ); int time = 0; int count = 0; for (int i=0; i<n; i++) { // if can take course ith, increment the number of course takne if (time + cs[i][0] <= cs[i][1]) { time += cs[i][0]; ++count; } // if cannot take course ith, find the previous course with maximum duration that is > duration of course ith // replace that course by course ith. Why doing this: We're greedily fitting number of course by removing // the course with too big time duration else { int maxith = i; for (int j=0; j < count; j++) if (cs[j][0] > cs[maxith][0]) maxith = j; if (maxith != i) { // remove that time-consuming course, replace it by current course ith time = time - cs[maxith][0] + cs[i][0]; // truly replace cs[maxith] = cs[i]; } } } return count; } }
{ "content_hash": "3ca7b18975095bcf047346ff413b6482", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 121, "avg_line_length": 34.94117647058823, "alnum_prop": 0.5471380471380471, "repo_name": "hiryou/MLPractice", "id": "97663efe2353a0deb3d09547ac8fa8426cd3740f", "size": "1782", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "HelloWorld/src/com/leetcode3/CourseSchedule3.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "374211" } ], "symlink_target": "" }
<resources> <string name="app_name">SwypeTweaks</string> <!-- Color Picker --> <string name="dialog_color_picker">Color Picker</string> <string name="press_color_to_apply">Press on Color to apply</string> <!-- Preferences --> <string name="pref_category">Category</string> <string name="color1_title">Color 1</string> <string name="color1_summary">black color by default, set by reference</string> <string name="color2_title">Color 2</string> <string name="color2_summary">not persistent color\nalpha slider added via code</string> <string name="color3_title">Color 3</string> <string name="color3_summary">picker with alpha slider</string> <string name="color4_title">Color 4</string> <string name="color4_summary">color set with HEX code in xml</string> </resources>
{ "content_hash": "537b055f227ac5276c043c20ac31a082", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 92, "avg_line_length": 46.388888888888886, "alnum_prop": 0.6874251497005988, "repo_name": "Danation/SwypeTweaks", "id": "f85d65eaf1710920677cbe9b40836f4b3627899a", "size": "835", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Source/res/values/strings.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "55972" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright 2016 The Chromium Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> <shortcuts xmlns:android="http://schemas.android.com/apk/res/android" > <shortcut android:shortcutId="new-tab-shortcut" android:icon="@drawable/shortcut_newtab" android:shortcutShortLabel="@string/menu_new_tab" > <intent android:action="chromium.shortcut.action.OPEN_NEW_TAB" android:targetPackage="{{manifest_package}}" android:targetClass="org.chromium.chrome.browser.LauncherShortcutActivity" > </intent> </shortcut> <shortcut android:shortcutId="new-incognito-tab-shortcut" android:enabled="false" android:icon="@drawable/shortcut_incognito" android:shortcutShortLabel="@string/accessibility_tabstrip_incognito_identifier" android:shortcutLongLabel="@string/menu_new_incognito_tab" android:shortcutDisabledMessage="@string/disabled_incognito_launcher_shortcut_message" > <intent android:action="chromium.shortcut.action.OPEN_NEW_INCOGNITO_TAB" android:targetPackage="{{manifest_package}}" android:targetClass="org.chromium.chrome.browser.LauncherShortcutActivity" > </intent> </shortcut> </shortcuts>
{ "content_hash": "dc73944acb47efec414463e1efa8d043", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 96, "avg_line_length": 45.54838709677419, "alnum_prop": 0.6841359773371105, "repo_name": "scheib/chromium", "id": "bd6cd4af0f9725283d828ee81741b6f3925ba2b9", "size": "1412", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "chrome/android/java/res_template/xml/launchershortcuts.xml", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<?xml version="1.0" ?><!DOCTYPE TS><TS language="af_ZA" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Preiscoin</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;Preiscoin&lt;/b&gt; version</source> <translation>&lt;b&gt;Preiscoin&lt;/b&gt; weergawe</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The Preiscoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Adres Boek</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Dubbel-klik om die adres of etiket te wysig</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Skep &apos;n nuwe adres</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Maak &apos;n kopie van die huidige adres na die stelsel klipbord</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Preiscoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Preiscoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Teken &amp;Boodskap</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Preiscoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Verwyder</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Preiscoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Stuur &amp;Muntstukke</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Voer die Adresboek Data Uit</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Fout uitvoering</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kon nie na die %1 lêer skryf nie</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Etiket</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(geen etiket)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Tik Wagwoord in</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nuwe wagwoord</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Herhaal nuwe wagwoord</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Tik die nuwe wagwoord vir die beursie in.&lt;br/&gt;Gebruik asseblief &apos;n wagwoord van &lt;b&gt;ten minste 10 ewekansige karakters&lt;/b&gt;, of &lt;b&gt;agt (8) of meer woorde.&lt;/b&gt;</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Enkripteer beursie</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Hierdie operasie benodig &apos;n wagwoord om die beursie oop te sluit.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Sluit beursie oop</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Hierdie operasie benodig &apos;n wagwoord om die beursie oop te sluit.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Sluit beursie oop</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Verander wagwoord</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Tik asseblief die ou en nuwe wagwoord vir die beursie in.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Bevestig beursie enkripsie.</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR PreiscoinS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Die beursie is nou bewaak</translation> </message> <message> <location line="-56"/> <source>Preiscoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your Preiscoins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Die beursie kon nie bewaak word nie</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Beursie bewaaking het misluk as gevolg van &apos;n interne fout. Die beursie is nie bewaak nie!</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Die wagwoord stem nie ooreen nie</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Beursie oopsluiting het misluk</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Die wagwoord wat ingetik was om die beursie oop te sluit, was verkeerd.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Beursie dekripsie het misluk</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Sinchroniseer met die netwerk ...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Oorsig</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Wys algemene oorsig van die beursie</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transaksies</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Besoek transaksie geskiedenis</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Wysig die lys van gestoorde adresse en etikette</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Wys die lys van adresse vir die ontvangs van betalings</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>S&amp;luit af</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Sluit af</translation> </message> <message> <location line="+4"/> <source>Show information about Preiscoin</source> <translation>Wys inligting oor Preiscoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opsies</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a Preiscoin address</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Modify configuration options for Preiscoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-165"/> <location line="+530"/> <source>Preiscoin</source> <translation>Preiscoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Beursie</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About Preiscoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your Preiscoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Preiscoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Lêer</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Instellings</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Hulp</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Blad nutsbalk</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Preiscoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Preiscoin network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>%1 agter</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>Ontvangs van laaste blok is %1 terug.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation>Fout</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation>Informasie</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Preiscoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Preiscoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Preiscoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Preiscoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Gebruik:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start Preiscoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start Preiscoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the Preiscoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the Preiscoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Preiscoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show Preiscoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Preiscoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Preiscoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Beursie</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start Preiscoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the Preiscoin-Qt help message to get a list with possible Preiscoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>Preiscoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Preiscoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the Preiscoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Preiscoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>S&amp;tuur</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Die adres waarheen die betaling gestuur moet word (b.v. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Preiscoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Teken boodskap</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Handtekening</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Preiscoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Teken &amp;Boodskap</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Preiscoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Preiscoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter Preiscoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Preiscoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Van</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Na</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>eie adres</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>etiket</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Krediet</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>nie aanvaar nie</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debiet</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Transaksie fooi</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Netto bedrag</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Boodskap</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Transaksie ID</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Bedrag</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>waar</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>onwaar</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipe</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Bedrag</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Ontvang met</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Gestuur na</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Gemyn</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n.v.t)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Datum en tyd wat die transaksie ontvang was.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tipe transaksie.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Alles</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Vandag</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Hierdie week</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Hierdie maand</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Verlede maand</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Hierdie jaar</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Ontvang met</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Gestuur na</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Aan/na jouself</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Gemyn</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Ander</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Min bedrag</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Maak kopie van adres</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipe</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etiket</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Bedrag</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Fout uitvoering</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kon nie na die %1 lêer skryf nie</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Preiscoin version</source> <translation>Preiscoin weergawe</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Gebruik:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or Preiscoind</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <source>List commands</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Options:</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Specify configuration file (default: Preiscoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Specify pid file (default: Preiscoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=Preiscoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Preiscoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Preiscoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Preiscoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Fout: Hardeskyf spasie is baie laag!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation>Informasie</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>SSL options: (see the Preiscoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Sisteem fout:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+165"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Laai adresse...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Preiscoin</source> <translation type="unfinished"/> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Preiscoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Laai blok indeks...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Preiscoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Laai beursie...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Klaar gelaai</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation>Fout</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
{ "content_hash": "b6dcfa897a9b4a31e726fcbab36ddd2a", "timestamp": "", "source": "github", "line_count": 2917, "max_line_length": 395, "avg_line_length": 33.68906410695921, "alnum_prop": 0.5913748715287318, "repo_name": "Preiscoin/1", "id": "6787d088a0cb631a726d8a1c057672a7eb1a0fc6", "size": "98274", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qt/locale/bitcoin_af_ZA.ts", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "98809" }, { "name": "C++", "bytes": "15122611" }, { "name": "CSS", "bytes": "1127" }, { "name": "IDL", "bytes": "15019" }, { "name": "Nu", "bytes": "264" }, { "name": "Objective-C++", "bytes": "5864" }, { "name": "Perl", "bytes": "10948" }, { "name": "Python", "bytes": "37268" }, { "name": "Shell", "bytes": "9702" }, { "name": "TypeScript", "bytes": "5246561" } ], "symlink_target": "" }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using TIKSN.Finance.ForeignExchange.Bank; using TIKSN.Globalization; using Xunit; namespace TIKSN.Finance.ForeignExchange.IntegrationTests { public class NationalBankOfUkraineTests { private readonly ICurrencyFactory _currencyFactory; public NationalBankOfUkraineTests() { var services = new ServiceCollection(); _ = services.AddMemoryCache(); _ = services.AddSingleton<ICurrencyFactory, CurrencyFactory>(); _ = services.AddSingleton<IRegionFactory, RegionFactory>(); var serviceProvider = services.BuildServiceProvider(); this._currencyFactory = serviceProvider.GetRequiredService<ICurrencyFactory>(); } [Fact] public async Task ConvertCurrencyAsync001Async() { var date = new DateTimeOffset(2016, 05, 06, 0, 0, 0, TimeSpan.Zero); var nbu = new NationalBankOfUkraine(this._currencyFactory); var pairs = await nbu.GetCurrencyPairsAsync(date, default).ConfigureAwait(true); foreach (var pair in pairs) { var baseMoney = new Money(pair.BaseCurrency, 100); var convertedMoney = await nbu.ConvertCurrencyAsync(baseMoney, pair.CounterCurrency, date, default).ConfigureAwait(true); Assert.Equal(pair.CounterCurrency, convertedMoney.Currency); Assert.True(convertedMoney.Amount > decimal.Zero); } } [Fact] public async Task GetCurrencyPairsAsync001Async() { var nbu = new NationalBankOfUkraine(this._currencyFactory); var pairs = await nbu.GetCurrencyPairsAsync(new DateTimeOffset(2016, 05, 06, 0, 0, 0, TimeSpan.Zero), default).ConfigureAwait(true); Assert.True(pairs.Any()); } [Fact] public async Task GetExchangeRateAsync001Async() { var date = new DateTimeOffset(2016, 05, 06, 0, 0, 0, TimeSpan.Zero); var nbu = new NationalBankOfUkraine(this._currencyFactory); var pairs = await nbu.GetCurrencyPairsAsync(date, default).ConfigureAwait(true); foreach (var pair in pairs) { var rate = await nbu.GetExchangeRateAsync(pair, date, default).ConfigureAwait(true); Assert.True(rate > decimal.Zero); } } } }
{ "content_hash": "8d994625ae91217af2280180a3248f0c", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 144, "avg_line_length": 36.88235294117647, "alnum_prop": 0.6375598086124402, "repo_name": "tiksn/TIKSN-Framework", "id": "978759171aa542b205c5ffc20b473f7731e393e3", "size": "2508", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "TIKSN.Framework.IntegrationTests/Finance/ForeignExchange/NationalBankOfUkraineTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "899203" }, { "name": "PowerShell", "bytes": "10679" } ], "symlink_target": "" }
#include "SIM.h" #include "GUI.h" void SIM_X_Init() { if ((LCD_GetDevCap(LCD_DEVCAP_XSIZE) == 320) && (LCD_GetDevCap(LCD_DEVCAP_YSIZE) == 240)) { SIM_SetLCDPos(71,38); // Define the position of the LCD in the bitmap SIM_SetTransColor (0xff0000); // Define the transparent color // SIM_SetLCDColorBlack(0, 0x808080); // Define the transparent color // SIM_SetLCDColorWhite(0, 0xc0c0c0); // Define the transparent color } }
{ "content_hash": "301f85f977f945e81b0718685272fbd4", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 93, "avg_line_length": 37.84615384615385, "alnum_prop": 0.6117886178861789, "repo_name": "byxob/calendar", "id": "6db69276fb71fe7dac78a9efba04d93f87a20327", "size": "1544", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Simulation/SIM_X.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "17761" }, { "name": "C", "bytes": "13326850" }, { "name": "C++", "bytes": "60565" } ], "symlink_target": "" }
package com.google.errorprone.refaster; import com.google.auto.value.AutoValue; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.collect.Iterables; import com.google.errorprone.refaster.ControlFlowVisitor.Result; import com.sun.source.tree.IfTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.TreeVisitor; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.util.List; import javax.annotation.Nullable; /** * {@link UTree} representation of an {@link IfTree}. * * @author lowasser@google.com (Louis Wasserman) */ @AutoValue abstract class UIf implements UStatement, IfTree { public static UIf create( UExpression condition, UStatement thenStatement, UStatement elseStatement) { return new AutoValue_UIf(condition, thenStatement, elseStatement); } @Override public abstract UExpression getCondition(); @Override public abstract UStatement getThenStatement(); @Override @Nullable public abstract UStatement getElseStatement(); @Override public <R, D> R accept(TreeVisitor<R, D> visitor, D data) { return visitor.visitIf(this, data); } @Override public Kind getKind() { return Kind.IF; } private static Function<Unifier, Choice<Unifier>> unifyUStatementWithSingleStatement( @Nullable final UStatement toUnify, @Nullable final StatementTree target) { return (Unifier unifier) -> { if (toUnify == null) { return (target == null) ? Choice.of(unifier) : Choice.<Unifier>none(); } List<StatementTree> list = (target == null) ? List.<StatementTree>nil() : List.of(target); return toUnify .apply(UnifierWithUnconsumedStatements.create(unifier, list)) .condition(s -> s.unconsumedStatements().isEmpty()) .transform(UnifierWithUnconsumedStatements::unifier); }; } @Override @Nullable public Choice<UnifierWithUnconsumedStatements> apply(UnifierWithUnconsumedStatements state) { java.util.List<? extends StatementTree> unconsumedStatements = state.unconsumedStatements(); if (unconsumedStatements.isEmpty()) { return Choice.none(); } final java.util.List<? extends StatementTree> unconsumedStatementsTail = unconsumedStatements.subList(1, unconsumedStatements.size()); StatementTree firstStatement = unconsumedStatements.get(0); if (firstStatement.getKind() != Kind.IF) { return Choice.none(); } final IfTree ifTree = (IfTree) firstStatement; Unifier unifier = state.unifier(); Choice<UnifierWithUnconsumedStatements> forwardMatch = getCondition() .unify(ifTree.getCondition(), unifier.fork()) .thenChoose( unifyUStatementWithSingleStatement(getThenStatement(), ifTree.getThenStatement())) .thenChoose( unifierAfterThen -> { if (getElseStatement() != null && ifTree.getElseStatement() == null && ControlFlowVisitor.INSTANCE.visitStatement(ifTree.getThenStatement()) == Result.ALWAYS_RETURNS) { Choice<UnifierWithUnconsumedStatements> result = getElseStatement() .apply( UnifierWithUnconsumedStatements.create( unifierAfterThen.fork(), unconsumedStatementsTail)); if (getElseStatement() instanceof UBlock) { Choice<UnifierWithUnconsumedStatements> alternative = Choice.of( UnifierWithUnconsumedStatements.create( unifierAfterThen.fork(), unconsumedStatementsTail)); for (UStatement stmt : ((UBlock) getElseStatement()).getStatements()) { alternative = alternative.thenChoose(stmt); } result = result.or(alternative); } return result; } else { return unifyUStatementWithSingleStatement( getElseStatement(), ifTree.getElseStatement()) .apply(unifierAfterThen) .transform( unifierAfterElse -> UnifierWithUnconsumedStatements.create( unifierAfterElse, unconsumedStatementsTail)); } }); Choice<UnifierWithUnconsumedStatements> backwardMatch = getCondition() .negate() .unify(ifTree.getCondition(), unifier.fork()) .thenChoose( unifierAfterCond -> { if (getElseStatement() == null) { return Choice.none(); } return getElseStatement() .apply( UnifierWithUnconsumedStatements.create( unifierAfterCond, List.of(ifTree.getThenStatement()))) .thenOption( (UnifierWithUnconsumedStatements stateAfterThen) -> stateAfterThen.unconsumedStatements().isEmpty() ? Optional.of(stateAfterThen.unifier()) : Optional.<Unifier>absent()); }) .thenChoose( unifierAfterThen -> { if (ifTree.getElseStatement() == null && ControlFlowVisitor.INSTANCE.visitStatement(ifTree.getThenStatement()) == Result.ALWAYS_RETURNS) { Choice<UnifierWithUnconsumedStatements> result = getThenStatement() .apply( UnifierWithUnconsumedStatements.create( unifierAfterThen.fork(), unconsumedStatementsTail)); if (getThenStatement() instanceof UBlock) { Choice<UnifierWithUnconsumedStatements> alternative = Choice.of( UnifierWithUnconsumedStatements.create( unifierAfterThen.fork(), unconsumedStatementsTail)); for (UStatement stmt : ((UBlock) getThenStatement()).getStatements()) { alternative = alternative.thenChoose(stmt); } result = result.or(alternative); } return result; } else { return unifyUStatementWithSingleStatement( getThenStatement(), ifTree.getElseStatement()) .apply(unifierAfterThen) .transform( unifierAfterElse -> UnifierWithUnconsumedStatements.create( unifierAfterElse, unconsumedStatementsTail)); } }); return forwardMatch.or(backwardMatch); } @Override public List<JCStatement> inlineStatements(Inliner inliner) throws CouldNotResolveImportException { return List.<JCStatement>of( inliner .maker() .If( getCondition().inline(inliner), Iterables.getOnlyElement(getThenStatement().inlineStatements(inliner)), (getElseStatement() == null) ? null : Iterables.getOnlyElement(getElseStatement().inlineStatements(inliner)))); } }
{ "content_hash": "2c0b4be3dd2147a31d89f107fb938bad", "timestamp": "", "source": "github", "line_count": 180, "max_line_length": 100, "avg_line_length": 43.15, "alnum_prop": 0.5664992918758851, "repo_name": "cushon/error-prone", "id": "88b624e65c581fde18b04fe60a17366bf957a88e", "size": "8372", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/com/google/errorprone/refaster/UIf.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "2061" }, { "name": "Java", "bytes": "7364383" }, { "name": "Python", "bytes": "10499" }, { "name": "Shell", "bytes": "1815" } ], "symlink_target": "" }
package com.yazilimokulu.mvc.services; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.yazilimokulu.mvc.daos.LikeNotificationRepository; import com.yazilimokulu.mvc.daos.PostRepository; import com.yazilimokulu.mvc.entities.LikeNotification; import com.yazilimokulu.mvc.entities.Post; import com.yazilimokulu.mvc.entities.User; @Service public class LikeNotificationServiceImpl implements LikeNotificationService { @Autowired LikeNotificationRepository likeNotificationRepository; @Autowired PostRepository postRepository; @Autowired UserService userService; @Override public void save(Post post) { LikeNotification likeNotification; List<User> creatorList; if(likeNotificationRepository.findByPostId(post.getId()) !=null){ likeNotification=likeNotificationRepository.findByPostId(post.getId()); creatorList=likeNotification.getCreatorUsers(); }else{ likeNotification = new LikeNotification(); creatorList = new ArrayList<>(); } User currentUser=userService.currentUser(); creatorList.add(currentUser); currentUser.getCreatedNotificaitons().add(likeNotification); likeNotification.setCreatorUsers(creatorList); likeNotification.setPost(post); likeNotification.setUser(post.getUser()); likeNotification.setChecked(false); post.getUser().getNotifications().add(likeNotification); post.setLikeNotification(likeNotification); likeNotificationRepository.save(likeNotification); } @Override public List<LikeNotification> getAllUnCheckedNotifiacitons() { return likeNotificationRepository.findByChecked(false); } }
{ "content_hash": "5f2da932d9ccc5dd03f90d31d586190b", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 77, "avg_line_length": 30.43103448275862, "alnum_prop": 0.7852691218130312, "repo_name": "codescrackers/turkninja", "id": "199b6de8b7003bb1df54cbc3b1a3352872aa2382", "size": "1765", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/yazilimokulu/mvc/services/LikeNotificationServiceImpl.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "343552" }, { "name": "HTML", "bytes": "140886" }, { "name": "Java", "bytes": "247825" }, { "name": "JavaScript", "bytes": "57093" }, { "name": "PureBasic", "bytes": "928" } ], "symlink_target": "" }
FROM balenalib/odroid-u3+-alpine:edge-build ENV NODE_VERSION 15.7.0 ENV YARN_VERSION 1.22.4 # Install dependencies RUN apk add --no-cache libgcc libstdc++ libuv \ && apk add --no-cache libssl1.0 || apk add --no-cache libssl1.1 RUN for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \ done \ && curl -SLO "http://resin-packages.s3.amazonaws.com/node/v$NODE_VERSION/node-v$NODE_VERSION-linux-alpine-armv7hf.tar.gz" \ && echo "73984242011b816117126c546702a7892b0ddd39cd51f672445b430161e2b903 node-v$NODE_VERSION-linux-alpine-armv7hf.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-alpine-armv7hf.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-alpine-armv7hf.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \ && echo "Running test-stack@node" \ && chmod +x test-stack@node.sh \ && bash test-stack@node.sh \ && rm -rf test-stack@node.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Alpine Linux edge \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.7.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && ln -f /bin/sh /bin/sh.real \ && ln -f /bin/sh-shim /bin/sh
{ "content_hash": "c0fdfc516d0db3a06e145a4c6422f20e", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 698, "avg_line_length": 65.2, "alnum_prop": 0.7113156100886162, "repo_name": "nghiant2710/base-images", "id": "19e424536f12dc92fa851d69f3043a3496889a30", "size": "2955", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/node/odroid-u3+/alpine/edge/15.7.0/build/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "144558581" }, { "name": "JavaScript", "bytes": "16316" }, { "name": "Shell", "bytes": "368690" } ], "symlink_target": "" }
package org.ngscript.runtime.vo; import org.ngscript.runtime.VirtualMachine; /** * @author wssccc */ public interface VmMethod { void invoke(VirtualMachine vm, Object[] vars) throws Exception; }
{ "content_hash": "a91821af53c350db4eff2707962c47ad", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 67, "avg_line_length": 15.846153846153847, "alnum_prop": 0.7330097087378641, "repo_name": "wssccc/ngscript", "id": "b0a7e5b4954e579f1e80cbbcb0721efb735ceb96", "size": "795", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ngscript-core/src/main/java/org/ngscript/runtime/vo/VmMethod.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "189660" } ], "symlink_target": "" }
package com.redmadrobot.chronos; import com.redmadrobot.chronos.mock.gui.SimpleMockActivity; import com.redmadrobot.chronos.mock.gui.SimpleMockFragment; import com.redmadrobot.chronos.mock.operation.SimpleOperation; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; import static com.redmadrobot.chronos.TestSettings.INPUT; import static com.redmadrobot.chronos.util.TimingUtils.sleep; /** * Test for broadcast operation runs. * * @author maximefimov */ public class BroadcastRunTest extends AndroidTestCase { @SmallTest public void testNormalRunFromActivity() { final SimpleMockActivity firstActivity = new SimpleMockActivity(); final SimpleMockFragment fragment = new SimpleMockFragment(); firstActivity.addFragment(fragment); final SimpleMockActivity secondActivity = new SimpleMockActivity(); firstActivity.start(); secondActivity.start(); secondActivity.runBroadcast(INPUT); sleep(); assertTrue(secondActivity.getResultObtained() == 1); assertTrue(SimpleOperation.isTransform(INPUT, secondActivity.getResult())); assertNull(secondActivity.getError()); assertFalse(secondActivity.gotBroadcastResult()); assertFalse(firstActivity.gotResult()); assertTrue(firstActivity.getBroadcastResultObtained() == 1); assertTrue(SimpleOperation.isTransform(INPUT, firstActivity.getBroadcastResult())); assertNull(firstActivity.getBroadcastError()); assertFalse(fragment.gotResult()); assertTrue(fragment.getBroadcastResultObtained() == 1); assertTrue(SimpleOperation.isTransform(INPUT, fragment.getBroadcastResult())); assertNull(fragment.getBroadcastError()); } @SmallTest public void testNormalRunFromFragment() { final SimpleMockActivity firstActivity = new SimpleMockActivity(); final SimpleMockFragment fragment = new SimpleMockFragment(); firstActivity.addFragment(fragment); final SimpleMockActivity secondActivity = new SimpleMockActivity(); firstActivity.start(); secondActivity.start(); fragment.runBroadcast(INPUT); sleep(); assertTrue(fragment.getResultObtained() == 1); assertTrue(SimpleOperation.isTransform(INPUT, fragment.getResult())); assertNull(fragment.getError()); assertFalse(fragment.gotBroadcastResult()); assertFalse(firstActivity.gotResult()); assertTrue(firstActivity.getBroadcastResultObtained() == 1); assertTrue(SimpleOperation.isTransform(INPUT, firstActivity.getBroadcastResult())); assertNull(firstActivity.getBroadcastError()); assertFalse(secondActivity.gotResult()); assertTrue(secondActivity.getBroadcastResultObtained() == 1); assertTrue(SimpleOperation.isTransform(INPUT, secondActivity.getBroadcastResult())); assertNull(secondActivity.getBroadcastError()); } @SmallTest public void testCancelRun() { final SimpleMockActivity firstActivity = new SimpleMockActivity(); final SimpleMockFragment fragment = new SimpleMockFragment(); firstActivity.addFragment(fragment); final SimpleMockActivity secondActivity = new SimpleMockActivity(); firstActivity.start(); secondActivity.start(); final int runId = secondActivity.runBroadcast(INPUT); final boolean cancelResult = secondActivity.cancel(runId); assertTrue(cancelResult); sleep(); assertFalse(secondActivity.gotResult()); assertFalse(secondActivity.gotBroadcastResult()); assertFalse(firstActivity.gotResult()); assertFalse(firstActivity.gotBroadcastResult()); assertFalse(fragment.gotResult()); assertFalse(fragment.gotBroadcastResult()); } @SmallTest public void testNormalRunFromActivityRotate() { final SimpleMockActivity firstActivity = new SimpleMockActivity(); final SimpleMockFragment fragment = new SimpleMockFragment(); firstActivity.addFragment(fragment); final SimpleMockActivity secondActivity = new SimpleMockActivity(); firstActivity.start(); secondActivity.start(); secondActivity.runBroadcast(INPUT); firstActivity.stop(); sleep(); assertTrue(secondActivity.getResultObtained() == 1); assertTrue(SimpleOperation.isTransform(INPUT, secondActivity.getResult())); assertNull(secondActivity.getError()); assertFalse(secondActivity.gotBroadcastResult()); assertFalse(firstActivity.gotResult()); assertFalse(firstActivity.gotBroadcastResult()); assertFalse(fragment.gotResult()); assertFalse(fragment.gotBroadcastResult()); firstActivity.start(); assertFalse(firstActivity.gotResult()); assertTrue(firstActivity.getBroadcastResultObtained() == 1); assertTrue(SimpleOperation.isTransform(INPUT, firstActivity.getBroadcastResult())); assertNull(firstActivity.getBroadcastError()); assertFalse(fragment.gotResult()); assertTrue(fragment.getBroadcastResultObtained() == 1); assertTrue(SimpleOperation.isTransform(INPUT, fragment.getBroadcastResult())); assertNull(fragment.getBroadcastError()); } }
{ "content_hash": "2e2f9fbcd406edaa55271be9b8f39c72", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 92, "avg_line_length": 37.291666666666664, "alnum_prop": 0.7162011173184357, "repo_name": "RedMadRobot/Chronos", "id": "87846dc836f33eaa93a6c56bd4670d4f032f1110", "size": "5370", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chronos/src/androidTest/java/com/redmadrobot/chronos/BroadcastRunTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "140098" } ], "symlink_target": "" }
package com.mygdx.game.screens; import com.badlogic.gdx.Application.ApplicationType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.controllers.Controller; import com.badlogic.gdx.controllers.ControllerAdapter; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Matrix4; import com.mygdx.game.Invaders; /** The main menu screen showing a background, the logo of the game and a label telling the user to touch the screen to start the * game. Waits for the touch and returns isDone() == true when it's done so that the ochestrating GdxInvaders class can switch to * the next screen. * @author mzechner */ public class MainMenu extends InvadersScreen { /** the SpriteBatch used to draw the background, logo and text **/ private final SpriteBatch spriteBatch; /** the background texture **/ private final Texture background; /** the logo texture **/ private final Texture logo; /** the font **/ private final BitmapFont font; /** is done flag **/ private boolean isDone = false; /** view & transform matrix **/ private final Matrix4 viewMatrix = new Matrix4(); private final Matrix4 transformMatrix = new Matrix4(); private final GlyphLayout glyphLayout = new GlyphLayout(); public MainMenu (Invaders invaders) { super(invaders); spriteBatch = new SpriteBatch(); background = new Texture(Gdx.files.internal("data/planet.jpg")); background.setFilter(TextureFilter.Linear, TextureFilter.Linear); logo = new Texture(Gdx.files.internal("data/title.png")); logo.setFilter(TextureFilter.Linear, TextureFilter.Linear); font = new BitmapFont(Gdx.files.internal("data/font16.fnt"), Gdx.files.internal("data/font16.png"), false); if (invaders.getController() != null) { invaders.getController().addListener(new ControllerAdapter() { @Override public boolean buttonUp(Controller controller, int buttonIndex) { controller.removeListener(this); isDone = true; return false; } }); } } @Override public boolean isDone () { return isDone; } @Override public void update (float delta) { if (Gdx.input.justTouched()) { isDone = true; } } @Override public void draw (float delta) { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); viewMatrix.setToOrtho2D(0, 0, 480, 320); spriteBatch.setProjectionMatrix(viewMatrix); spriteBatch.setTransformMatrix(transformMatrix); spriteBatch.begin(); spriteBatch.disableBlending(); spriteBatch.setColor(Color.WHITE); spriteBatch.draw(background, 0, 0, 480, 320, 0, 0, 512, 512, false, false); spriteBatch.enableBlending(); spriteBatch.draw(logo, 0, 320 - 128, 480, 128, 0, 0, 512, 256, false, false); spriteBatch.setBlendFunction(GL20.GL_ONE, GL20.GL_ONE_MINUS_SRC_ALPHA); glyphLayout.setText(font, "Touch screen to start!"); font.draw(spriteBatch, glyphLayout, 240 - glyphLayout.width / 2, 128); if (Gdx.app.getType() == ApplicationType.WebGL) { glyphLayout.setText(font, "Press Enter for Fullscreen Mode"); font.draw(spriteBatch, glyphLayout, 240 - glyphLayout.width / 2, 128 - font.getLineHeight()); } spriteBatch.end(); } @Override public void dispose () { spriteBatch.dispose(); background.dispose(); logo.dispose(); font.dispose(); } }
{ "content_hash": "e0fd03a4d9ccf708b97ab90a39020cbf", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 129, "avg_line_length": 33.12264150943396, "alnum_prop": 0.7359726573625748, "repo_name": "Motsai/neblina-android", "id": "11e15ba73725ccbf50ffe866deae43f1d0fcf7c8", "size": "4168", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "LibExperiments/core/src/com/mygdx/game/screens/MainMenu.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1069" }, { "name": "GLSL", "bytes": "1859" }, { "name": "HTML", "bytes": "1524" }, { "name": "Java", "bytes": "284839" }, { "name": "JavaScript", "bytes": "24" }, { "name": "Kotlin", "bytes": "42157" } ], "symlink_target": "" }
package net.ontopia.topicmaps.rest.v1.query; import java.io.IOException; import java.io.OutputStream; import net.ontopia.topicmaps.query.core.QueryResultIF; import net.ontopia.topicmaps.query.utils.QueryResultIterator; import net.ontopia.topicmaps.rest.converters.jackson.JacksonRepresentationImpl; import net.ontopia.topicmaps.rest.resources.AbstractTransactionalResource; import net.ontopia.topicmaps.rest.resources.Parameters; import org.restlet.representation.Representation; import org.restlet.resource.Post; public class QueryResource extends AbstractTransactionalResource { @Post public Representation query(String query) { String language = Parameters.LANGUAGE.optional(this); final QueryResultIF result = getController(QueryController.class).query(getTopicMap(), language, query); return new JacksonRepresentationImpl<QueryResultIterator>(new QueryResultIterator(result)) { @Override public void write(OutputStream outputStream) throws IOException { try { super.write(outputStream); } finally { result.close(); } } }; } }
{ "content_hash": "94c35762109dfba2ac66f8d101647018", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 106, "avg_line_length": 32.75757575757576, "alnum_prop": 0.7964847363552267, "repo_name": "ontopia/ontopia", "id": "7d7fc0ddf457e5a1c9f7595a61e92b3a737d76cf", "size": "1734", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ontopia-rest/src/main/java/net/ontopia/topicmaps/rest/v1/query/QueryResource.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "229" }, { "name": "CSS", "bytes": "102701" }, { "name": "GAP", "bytes": "55644" }, { "name": "HTML", "bytes": "56107" }, { "name": "Java", "bytes": "11884136" }, { "name": "JavaScript", "bytes": "365763" }, { "name": "Lex", "bytes": "19344" }, { "name": "Python", "bytes": "27528" }, { "name": "SCSS", "bytes": "6338" }, { "name": "Shell", "bytes": "202" } ], "symlink_target": "" }
package test.proto.custom_generator import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers._ class DummyGeneratorTest extends AnyFlatSpec with should.Matchers { "dummy generator" should "generate a dummy object" in { noException should be thrownBy Class.forName("custom_generator.dummy") } }
{ "content_hash": "a038241d9b8aeb5a3e1a9162318e7c3f", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 74, "avg_line_length": 26.75, "alnum_prop": 0.7912772585669782, "repo_name": "bazelbuild/rules_scala", "id": "ccaf6ce0e43f3da65f59185dea93d65042049d4f", "size": "321", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/proto/custom_generator/DummyGeneratorTest.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "101279" }, { "name": "Python", "bytes": "173" }, { "name": "Scala", "bytes": "134408" }, { "name": "Shell", "bytes": "119167" }, { "name": "Starlark", "bytes": "402942" }, { "name": "Thrift", "bytes": "3441" } ], "symlink_target": "" }
#import SQL snapins #add-pssnapin sqlservercmdletsnapin100 #add-pssnapin sqlserverprovidersnapin100 import-module sqlps import-module activedirectory $m=Read-Host "Enter MAC address (No colons) " $macs=$m -split (",") foreach($mac in $macs) { #create new user account, add it to MACAccounts group, change the password #$mac New-ADUser -Name $mac -Path "OU=MACAccounts,DC=pbso,DC=org" Set-ADAccountPassword -Identity $mac -NewPassword (ConvertTo-SecureString "pbso@1999" -AsPlainText -Force) Set-ADUser -Identity $mac -Enabled $true Add-ADGroupMember MACAccounts $mac Set-ADAccountPassword -Identity $mac -NewPassword (ConvertTo-SecureString $mac -AsPlainText -Force) #set MACaccounts as primary group and remove user from Domain Users group $group = get-adgroup "MACAccounts" $groupSid = $group.sid #$groupSid [int]$GroupID = $groupSid.Value.Substring($groupSid.Value.LastIndexOf("-")+1) Start-Sleep 5 Get-ADUser $mac | Set-ADObject -Replace @{primaryGroupID="$GroupID"} remove-adgroupmember -Identity "Domain Users" -Member $mac -Confirm:$false #get values for all attributes $model=Read-Host "Enter Model " $type=Read-Host "Enter Type " $serial=Read-Host "Enter Serial No. " $manu=Read-Host "Enter Manufacturer " $description=Read-Host "Enter Description " #insert the information in SQL table invoke-sqlcmd -query "insert into mac_info (mac,model,type,serial,manu,description) VALUES ('$mac','$model','$type','$serial','$manu','$description')" -database "MAC" -serverinstance "HQ-S-TEST-T1" }
{ "content_hash": "6bf656aae16798833380071b0c50c6cb", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 201, "avg_line_length": 38.023809523809526, "alnum_prop": 0.7175954915466499, "repo_name": "failbringerUD/powershell", "id": "6b760b07192660675648cfa0e648387d5da38a21", "size": "1599", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PBSO/MacAccounts.ps1", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1095" }, { "name": "PowerShell", "bytes": "1126373" }, { "name": "Visual Basic", "bytes": "541" } ], "symlink_target": "" }
export enum BuildStatus { NEW = 'New', RUNNING = 'Running', PENDING = 'Pending', COMPLETE = 'Complete', CANCELLED = 'Cancelled', ERROR = 'Error', FAILED = 'Failed' } export class BuildStatusUtils { public static buildEnded(status: string): boolean { return status === BuildStatus.COMPLETE || status === BuildStatus.FAILED || status === BuildStatus.CANCELLED || status === BuildStatus.ERROR; } } export enum BuildStageStatus { SUCCESS = 'SUCCESS', FAILED = 'FAILED', PAUSED_PENDING_INPUT = 'PAUSED_PENDING_INPUT', ABORTED = 'ABORTED', IN_PROGRESS = 'IN_PROGRESS' } export class BuildStageStatusUtils { public static buildEnded(status: string): boolean { return status === BuildStageStatus.SUCCESS || status === BuildStageStatus.FAILED || status === BuildStageStatus.ABORTED; } }
{ "content_hash": "82309258ac9a1db7ace2980a22fa995a", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 55, "avg_line_length": 26.25, "alnum_prop": 0.6010582010582011, "repo_name": "ldimaggi/fabric8-test", "id": "4b46cc40f9837e6112564e53fb9a8af7d6856dc6", "size": "945", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ee_tests/src/support/build_status.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "1493" }, { "name": "Gherkin", "bytes": "3938" }, { "name": "Go", "bytes": "27601" }, { "name": "Java", "bytes": "6903" }, { "name": "Python", "bytes": "283379" }, { "name": "Ruby", "bytes": "8233" }, { "name": "Shell", "bytes": "153894" }, { "name": "TypeScript", "bytes": "172729" } ], "symlink_target": "" }
package org.apache.commons.pool2.impl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.apache.commons.pool2.BasePooledObjectFactory; import org.apache.commons.pool2.PooledObject; import org.junit.After; import org.junit.Test; /** * @version $Revision: 1627961 $ */ public class TestSoftRefOutOfMemory { private SoftReferenceObjectPool<String> pool; @After public void tearDown() throws Exception { if (pool != null) { pool.close(); pool = null; } System.gc(); } @Test public void testOutOfMemory() throws Exception { pool = new SoftReferenceObjectPool<String>(new SmallPoolableObjectFactory()); String obj = pool.borrowObject(); assertEquals("1", obj); pool.returnObject(obj); obj = null; assertEquals(1, pool.getNumIdle()); final List<byte[]> garbage = new LinkedList<byte[]>(); final Runtime runtime = Runtime.getRuntime(); while (pool.getNumIdle() > 0) { try { long freeMemory = runtime.freeMemory(); if (freeMemory > Integer.MAX_VALUE) { freeMemory = Integer.MAX_VALUE; } garbage.add(new byte[Math.min(1024 * 1024, (int)freeMemory/2)]); } catch (OutOfMemoryError oome) { System.gc(); } System.gc(); } garbage.clear(); System.gc(); obj = pool.borrowObject(); assertEquals("2", obj); pool.returnObject(obj); obj = null; assertEquals(1, pool.getNumIdle()); } @Test public void testOutOfMemory1000() throws Exception { pool = new SoftReferenceObjectPool<String>(new SmallPoolableObjectFactory()); for (int i = 0 ; i < 1000 ; i++) { pool.addObject(); } String obj = pool.borrowObject(); assertEquals("1000", obj); pool.returnObject(obj); obj = null; assertEquals(1000, pool.getNumIdle()); final List<byte[]> garbage = new LinkedList<byte[]>(); final Runtime runtime = Runtime.getRuntime(); while (pool.getNumIdle() > 0) { try { long freeMemory = runtime.freeMemory(); if (freeMemory > Integer.MAX_VALUE) { freeMemory = Integer.MAX_VALUE; } garbage.add(new byte[Math.min(1024 * 1024, (int)freeMemory/2)]); } catch (OutOfMemoryError oome) { System.gc(); } System.gc(); } garbage.clear(); System.gc(); obj = pool.borrowObject(); assertEquals("1001", obj); pool.returnObject(obj); obj = null; assertEquals(1, pool.getNumIdle()); } @Test public void testOutOfMemoryLarge() throws Exception { pool = new SoftReferenceObjectPool<String>(new LargePoolableObjectFactory(1000000)); String obj = pool.borrowObject(); assertTrue(obj.startsWith("1.")); pool.returnObject(obj); obj = null; assertEquals(1, pool.getNumIdle()); final List<byte[]> garbage = new LinkedList<byte[]>(); final Runtime runtime = Runtime.getRuntime(); while (pool.getNumIdle() > 0) { try { long freeMemory = runtime.freeMemory(); if (freeMemory > Integer.MAX_VALUE) { freeMemory = Integer.MAX_VALUE; } garbage.add(new byte[Math.min(1024 * 1024, (int)freeMemory/2)]); } catch (OutOfMemoryError oome) { System.gc(); } System.gc(); } garbage.clear(); System.gc(); obj = pool.borrowObject(); assertTrue(obj.startsWith("2.")); pool.returnObject(obj); obj = null; assertEquals(1, pool.getNumIdle()); } /** * Makes sure an {@link OutOfMemoryError} isn't swallowed. * * @throws Exception May occur in some failure modes */ @Test public void testOutOfMemoryError() throws Exception { pool = new SoftReferenceObjectPool<String>( new OomeFactory(OomeTrigger.CREATE)); try { pool.borrowObject(); fail("Expected out of memory."); } catch (OutOfMemoryError ex) { // expected } pool.close(); pool = new SoftReferenceObjectPool<String>( new OomeFactory(OomeTrigger.VALIDATE)); try { pool.borrowObject(); fail("Expected out of memory."); } catch (OutOfMemoryError ex) { // expected } pool.close(); pool = new SoftReferenceObjectPool<String>( new OomeFactory(OomeTrigger.DESTROY)); try { pool.borrowObject(); fail("Expected out of memory."); } catch (OutOfMemoryError ex) { // expected } pool.close(); } public static class SmallPoolableObjectFactory extends BasePooledObjectFactory<String> { private int counter = 0; @Override public String create() { counter++; // It seems that as of Java 1.4 String.valueOf may return an // intern()'ed String this may cause problems when the tests // depend on the returned object to be eventually garbaged // collected. Either way, making sure a new String instance // is returned eliminated false failures. return new String(String.valueOf(counter)); } @Override public PooledObject<String> wrap(String value) { return new DefaultPooledObject<String>(value); } } public static class LargePoolableObjectFactory extends BasePooledObjectFactory<String> { private final String buffer; private int counter = 0; public LargePoolableObjectFactory(int size) { char[] data = new char[size]; Arrays.fill(data, '.'); buffer = new String(data); } @Override public String create() { counter++; return String.valueOf(counter) + buffer; } @Override public PooledObject<String> wrap(String value) { return new DefaultPooledObject<String>(value); } } private static class OomeFactory extends BasePooledObjectFactory<String> { private final OomeTrigger trigger; public OomeFactory(OomeTrigger trigger) { this.trigger = trigger; } @Override public String create() throws Exception { if (trigger.equals(OomeTrigger.CREATE)) { throw new OutOfMemoryError(); } // It seems that as of Java 1.4 String.valueOf may return an // intern()'ed String this may cause problems when the tests // depend on the returned object to be eventually garbaged // collected. Either way, making sure a new String instance // is returned eliminated false failures. return new String(); } @Override public PooledObject<String> wrap(String value) { return new DefaultPooledObject<String>(value); } @Override public boolean validateObject(PooledObject<String> p) { if (trigger.equals(OomeTrigger.VALIDATE)) { throw new OutOfMemoryError(); } if (trigger.equals(OomeTrigger.DESTROY)) { return false; } else { return true; } } @Override public void destroyObject(PooledObject<String> p) throws Exception { if (trigger.equals(OomeTrigger.DESTROY)) { throw new OutOfMemoryError(); } super.destroyObject(p); } } private static enum OomeTrigger { CREATE, VALIDATE, DESTROY } }
{ "content_hash": "2d5237789c154aed3a48676d23ba7074", "timestamp": "", "source": "github", "line_count": 283, "max_line_length": 92, "avg_line_length": 29.363957597173144, "alnum_prop": 0.5570397111913358, "repo_name": "kmiku7/apache-commons-pool-annotated", "id": "889e2f6ff06816ff4dc78dabba8c46904fb6412c", "size": "9112", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/java/org/apache/commons/pool2/impl/TestSoftRefOutOfMemory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "8297" }, { "name": "Java", "bytes": "828209" }, { "name": "Shell", "bytes": "1100" } ], "symlink_target": "" }
SERIALIZE_MATERIALIZE=0 LOAD_STABLE=0 VM_PATH="/devel/VM" IMAGE_PATH="/devel/fuel" COG_VM="$VM_PATH/CogVM.app/Contents/MacOS/CogVM" PHARO_VM="$VM_PATH/Pharo.app/Contents/MacOS/Pharo" STACK_VM="$VM_PATH/Squeak 4.2.5beta1U.app/Contents/MacOS/Squeak VM Opt" PREPARATION_SCRIPT="$IMAGE_PATH/fuel_fix_installer_for_squeak.st" LOADER_SCRIPT_STABLE="$IMAGE_PATH/fuel_load_packages_stable.st" LOADER_SCRIPT_BLEEDING_EDGE="$IMAGE_PATH/fuel_load_packages_bleeding_edge.st" TEST_RUNNER_SCRIPT="$IMAGE_PATH/fuel_run_all_tests.st" SERIALIZATION_SCRIPT="$IMAGE_PATH/fuel_serialize_all_objects.st" MATERIALIZATION_SCRIPT="$IMAGE_PATH/fuel_materialize_all_objects.st" FINAL_SCRIPT_BASE="$IMAGE_PATH/run_it" FINAL_SCRIPT="" PHARO_IMAGES_COG_VM=("Pharo111" "Pharo112" "Pharo12" "Pharo122" "Pharo13" "Pharo14" "Pharo20") PHARO_IMAGES_PHARO_VM=("Pharo30") SQUEAK_IMAGES_STACK_VM=("Squeak41") SQUEAK_IMAGES_COG_VM=("Squeak42" "Squeak43" "Squeak44" "Squeak45") # help function function display_help() { echo "$(basename $0) [-ms]" echo " -m serialize / materialize all objects to / from all images (tests will not be run)" echo " -s load latest stable (instead of bleeding edge)" } function prepare_final_script(){ IMAGE_NAME=$1 FINAL_SCRIPT="${FINAL_SCRIPT_BASE}_${IMAGE_NAME}.st" cat "$PREPARATION_SCRIPT" > "$FINAL_SCRIPT" if [ $LOAD_STABLE = 1 ]; then cat "$LOADER_SCRIPT_STABLE" >> "$FINAL_SCRIPT" else cat "$LOADER_SCRIPT_BLEEDING_EDGE" >> "$FINAL_SCRIPT" fi if [ $SERIALIZE_MATERIALIZE = 0 ]; then cat "$TEST_RUNNER_SCRIPT" >> "$FINAL_SCRIPT" else echo "Smalltalk at: #FuelFormatTestScriptsPath put: '$IMAGE_PATH'." >> "$FINAL_SCRIPT" echo "Smalltalk at: #FuelFormatTestImageNames put: #(" >> "$FINAL_SCRIPT" for image_name in ${PHARO_IMAGES_COG_VM[@]}; do echo "'${image_name}' " >> "$FINAL_SCRIPT" done for image_name in ${PHARO_IMAGES_PHARO_VM[@]}; do echo "'${image_name}' " >> "$FINAL_SCRIPT" done for image_name in ${SQUEAK_IMAGES_STACK_VM[@]}; do echo "'${image_name}' " >> "$FINAL_SCRIPT" done for image_name in ${SQUEAK_IMAGES_COG_VM[@]}; do echo "'${image_name}' " >> "$FINAL_SCRIPT" done echo ")." >> "$FINAL_SCRIPT" echo "Smalltalk at: #FuelFormatTestFilename put: '$IMAGE_NAME.fuel'." >> "$FINAL_SCRIPT" cat "$SERIALIZATION_SCRIPT" >> "$FINAL_SCRIPT" cat "$MATERIALIZATION_SCRIPT" >> "$FINAL_SCRIPT" fi } while getopts ":msh?" OPT ; do case "$OPT" in # serialize / materialize objects m) SERIALIZE_MATERIALIZE=1 ;; # load latest stable s) LOAD_STABLE=1 ;; # show help h) display_help ;; # show help \?) display_help exit 1 ;; esac done if [ $LOAD_STABLE = 1 ]; then echo "loading stable" else echo "loading bleeding edge" fi if [ $SERIALIZE_MATERIALIZE = 1 ]; then echo "serializing / materializing all objects" else echo "running all tests" fi # #pharo cog # for image in ${PHARO_IMAGES_COG_VM[@]}; do # prepare_final_script ${image} # echo "running $COG_VM $IMAGE_PATH/${image}/${image}.image $FINAL_SCRIPT" # exec "$COG_VM" "$IMAGE_PATH/${image}/${image}.image" "$FINAL_SCRIPT" & # done # # #pharo vm # for image in ${PHARO_IMAGES_PHARO_VM[@]}; do # prepare_final_script ${image} # echo "running $PHARO_VM $IMAGE_PATH/${image}/${image}.image $FINAL_SCRIPT" # exec "$PHARO_VM" "$IMAGE_PATH/${image}/${image}.image" "$FINAL_SCRIPT" & # done #squeak stack for image in ${SQUEAK_IMAGES_STACK_VM[@]}; do prepare_final_script ${image} echo "running $STACK_VM $IMAGE_PATH/${image}/${image}.image $FINAL_SCRIPT" exec "$STACK_VM" "$IMAGE_PATH/${image}/${image}.image" "$FINAL_SCRIPT" & done # #squeak cog # for image in ${SQUEAK_IMAGES_COG_VM[@]}; do # prepare_final_script ${image} # echo "running $COG_VM $IMAGE_PATH/${image}/${image}.image $FINAL_SCRIPT" # exec "$COG_VM" "$IMAGE_PATH/${image}/${image}.image" "$FINAL_SCRIPT" & # done exit 0
{ "content_hash": "f23a9985059dd5eb279e9aea75ff017c", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 94, "avg_line_length": 29.81679389312977, "alnum_prop": 0.6684587813620072, "repo_name": "theseion/Fuel", "id": "8815d18c4ad9f2d884e106b4022e61e978a1b86d", "size": "4142", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/fuel_test_automator.sh", "mode": "33261", "license": "mit", "language": [ { "name": "Shell", "bytes": "4142" }, { "name": "Smalltalk", "bytes": "388835" }, { "name": "StringTemplate", "bytes": "120" } ], "symlink_target": "" }
package com.cjj.mousepaint.fragment; import android.animation.Animator; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.view.ViewPager; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.animation.OvershootInterpolator; import android.widget.Button; import android.widget.ImageButton; import android.widget.RelativeLayout; import android.widget.TextView; import com.cjj.listener.CallbackListener; import com.cjj.mousepaint.R; import com.cjj.mousepaint.adapter.CardPagerAdapter; import com.cjj.mousepaint.contral.control.IRhythmItemListener; import com.cjj.mousepaint.contral.control.RhythmAdapter; import com.cjj.mousepaint.contral.control.RhythmLayout; import com.cjj.mousepaint.contral.control.ViewPagerScroller; import com.cjj.mousepaint.dao.AppDao; import com.cjj.mousepaint.model.AllBookModels; import com.cjj.mousepaint.model.Card; import com.cjj.mousepaint.utils.AnimatorUtils; import com.cjj.mousepaint.utils.HexUtils; import com.cjj.view.ViewSelectorLayout; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; /** * User: shine * Date: 2014-12-13 * Time: 19:45 * Description: */ public class CardViewPagerFragment extends AbsBaseFragment { private View mMainView; private Button mSideMenuOrBackBtn; private RhythmLayout mRhythmLayout; private ViewPager mViewPager; private CardPagerAdapter mCardPagerAdapter; private int mPreColor; private boolean mHasNext = true; private boolean mIsRequesting; private boolean isAdapterUpdated; private int mCurrentViewPagerPage; private ViewSelectorLayout mViewSelectorLayout; private List<Card> mCardList; // private ProgressHUD mProgressHUD; private RhythmAdapter mRhythmAdapter; private static CardViewPagerFragment mFragment; private IRhythmItemListener rhythmItemListener = new IRhythmItemListener() { public void onRhythmItemChanged(int paramInt) { } public void onSelected(final int paramInt) { CardViewPagerFragment.this.mHandler.postDelayed(new Runnable() { public void run() { mViewPager.setCurrentItem(paramInt); } }, 100L); } public void onStartSwipe() { } }; private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() { public void onPageScrollStateChanged(int paramInt) { } public void onPageScrolled(int paramInt1, float paramFloat, int paramInt2) { } public void onPageSelected(int position) { onAppPagerChange(position); // if (mHasNext && (position > -10 + mCardList.size()) && !mIsRequesting) { //// fetchData(); // } } }; public static CardViewPagerFragment getInstance() { if (mFragment == null) { mFragment = new CardViewPagerFragment(); } return mFragment; } @Override protected View initViews(LayoutInflater inflater) { View view = inflater.inflate(R.layout.fragment_niceapp, null); mViewSelectorLayout = new ViewSelectorLayout(getActivity(),view); mMainView = view.findViewById(R.id.main_view); mRhythmLayout = (RhythmLayout) view.findViewById(R.id.box_rhythm); mViewPager = (ViewPager) view.findViewById(R.id.pager); setViewPagerScrollSpeed(mViewPager, 400); mRhythmLayout.setScrollRhythmStartDelayTime(400); int height = (int) mRhythmLayout.getRhythmItemWidth() + (int) TypedValue.applyDimension(1, 10.0F, getResources().getDisplayMetrics()); mRhythmLayout.getLayoutParams().height = height; // ((RelativeLayout.LayoutParams) mPullToRefreshViewPager.getLayoutParams()).bottomMargin = height; ((RelativeLayout.LayoutParams) mViewPager.getLayoutParams()).bottomMargin = height; return mViewSelectorLayout; } @Override protected void initActions(View paramView) { mRhythmLayout.setRhythmListener(rhythmItemListener); mViewPager.setOnPageChangeListener(onPageChangeListener); } @Override protected void initData() { mCardList = new ArrayList<>(); } private void setViewPagerScrollSpeed(ViewPager viewPager, int speed) { try { Field field = ViewPager.class.getDeclaredField("mScroller"); field.setAccessible(true); ViewPagerScroller viewPagerScroller = new ViewPagerScroller(viewPager.getContext(), new OvershootInterpolator(0.6F)); field.set(viewPager, viewPagerScroller); viewPagerScroller.setDuration(speed); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } private void onAppPagerChange(int position) { mRhythmLayout.showRhythmAtPosition(position); Card post = this.mCardList.get(position); int currColor = HexUtils.getHexColor(post.getBackgroundColor()); AnimatorUtils.showBackgroundColorAnimation(this.mMainView, mPreColor, currColor, 400); mPreColor = currColor; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mViewSelectorLayout.show_LoadingView(); fetchData(); } private void fetchData() { AppDao.getInstance().subscribeByUser("0", new CallbackListener<AllBookModels>() { @Override public void onStringResult(String result) { super.onStringResult(result); Log.i("scirbe", "result---->" + result); } @Override public void onSuccess(AllBookModels result) { super.onSuccess(result); mViewSelectorLayout.show_ContentView(); handData(result.Return.List); } @Override public void onError(Exception e) { super.onError(e); } }); // ArrayList<Card> cardList = new ArrayList<>(); // for (int i = 0; i < 10; i++) { // int m = i % 10; // Card card = addData(m); // cardList.add(card); // } // mPreColor = HexUtils.getHexColor(cardList.get(0).getBackgroundColor()); } private void handData(ArrayList<AllBookModels.ReturnClazz.AllBook> list) { ArrayList<Card> cardList = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { Card card = new Card(); card.setId(list.get(i).Id); card.setTitle(list.get(i).Title); if(list.get(i).LastChapter != null) card.setSubTitle(list.get(i).LastChapter.Title); card.setDigest(list.get(i).Explain); card.setAuthorName(list.get(i).Author); if(list.get(i).LastChapter != null) card.setUpNum(Integer.valueOf(list.get(i).LastChapter.ChapterNo)); card.setBackgroundColor("#795548"); card.setCoverImgerUrl(list.get(i).FrontCover); card.setIconUrl(list.get(i).FrontCover); cardList.add(card); } updateAppAdapter(cardList); onAppPagerChange(0); } private void updateAppAdapter(List<Card> cardList) { if ((getActivity() == null) || (getActivity().isFinishing())) { return; } if (cardList.isEmpty()) { this.mMainView.setBackgroundColor(this.mPreColor); return; } int size = mCardList.size(); if (mCardPagerAdapter == null) { mCurrentViewPagerPage = 0; mCardPagerAdapter = new CardPagerAdapter(getActivity().getSupportFragmentManager(), cardList); mViewPager.setAdapter(mCardPagerAdapter); } else { mCardPagerAdapter.addCardList(cardList); mCardPagerAdapter.notifyDataSetChanged(); } addCardIconsToDock(cardList); this.mCardList = mCardPagerAdapter.getCardList(); if (mViewPager.getCurrentItem() == size - 1) mViewPager.setCurrentItem(1 + mViewPager.getCurrentItem(), true); } private void addCardIconsToDock(final List<Card> cardList) { if (mRhythmAdapter == null) { resetRhythmLayout(cardList); return; } mRhythmAdapter.addCardList(cardList); mRhythmAdapter.notifyDataSetChanged(); } private void resetRhythmLayout(List<Card> cardList) { if (getActivity() == null) return; if (cardList == null) cardList = new ArrayList<>(); mRhythmAdapter = new RhythmAdapter(getActivity(), mRhythmLayout, cardList); mRhythmLayout.setAdapter(mRhythmAdapter); } }
{ "content_hash": "91771468388db7398d8de5db63280a1e", "timestamp": "", "source": "github", "line_count": 282, "max_line_length": 142, "avg_line_length": 31.9822695035461, "alnum_prop": 0.6531766271205234, "repo_name": "android-cjj/MousePaint", "id": "dfe9e846e2e2d982834a1e4100e63cc10c2ecad0", "size": "9019", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/cjj/mousepaint/fragment/CardViewPagerFragment.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "908209" } ], "symlink_target": "" }
import { registerVersion, _registerComponent, _getProvider, getApp } from 'https://www.gstatic.com/firebasejs/9.9.0-20220707215600/firebase-app.js'; /** * The JS SDK supports 5 log levels and also allows a user the ability to * silence the logs altogether. * * The order is a follows: * DEBUG < VERBOSE < INFO < WARN < ERROR * * All of the log types above the current log level will be captured (i.e. if * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and * `VERBOSE` logs will not) */ var LogLevel; (function (LogLevel) { LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG"; LogLevel[LogLevel["VERBOSE"] = 1] = "VERBOSE"; LogLevel[LogLevel["INFO"] = 2] = "INFO"; LogLevel[LogLevel["WARN"] = 3] = "WARN"; LogLevel[LogLevel["ERROR"] = 4] = "ERROR"; LogLevel[LogLevel["SILENT"] = 5] = "SILENT"; })(LogLevel || (LogLevel = {})); const levelStringToEnum = { 'debug': LogLevel.DEBUG, 'verbose': LogLevel.VERBOSE, 'info': LogLevel.INFO, 'warn': LogLevel.WARN, 'error': LogLevel.ERROR, 'silent': LogLevel.SILENT }; /** * The default log level */ const defaultLogLevel = LogLevel.INFO; /** * By default, `console.debug` is not displayed in the developer console (in * chrome). To avoid forcing users to have to opt-in to these logs twice * (i.e. once for firebase, and once in the console), we are sending `DEBUG` * logs to the `console.log` function. */ const ConsoleMethod = { [LogLevel.DEBUG]: 'log', [LogLevel.VERBOSE]: 'log', [LogLevel.INFO]: 'info', [LogLevel.WARN]: 'warn', [LogLevel.ERROR]: 'error' }; /** * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR * messages on to their corresponding console counterparts (if the log method * is supported by the current log level) */ const defaultLogHandler = (instance, logType, ...args) => { if (logType < instance.logLevel) { return; } const now = new Date().toISOString(); const method = ConsoleMethod[logType]; if (method) { console[method](`[${now}] ${instance.name}:`, ...args); } else { throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`); } }; class Logger { /** * Gives you an instance of a Logger to capture messages according to * Firebase's logging scheme. * * @param name The name that the logs will be associated with */ constructor(name) { this.name = name; /** * The log level of the given Logger instance. */ this._logLevel = defaultLogLevel; /** * The main (internal) log handler for the Logger instance. * Can be set to a new function in internal package code but not by user. */ this._logHandler = defaultLogHandler; /** * The optional, additional, user-defined log handler for the Logger instance. */ this._userLogHandler = null; } get logLevel() { return this._logLevel; } set logLevel(val) { if (!(val in LogLevel)) { throw new TypeError(`Invalid value "${val}" assigned to \`logLevel\``); } this._logLevel = val; } // Workaround for setter/getter having to be the same type. setLogLevel(val) { this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val; } get logHandler() { return this._logHandler; } set logHandler(val) { if (typeof val !== 'function') { throw new TypeError('Value assigned to `logHandler` must be a function'); } this._logHandler = val; } get userLogHandler() { return this._userLogHandler; } set userLogHandler(val) { this._userLogHandler = val; } /** * The functions below are all based on the `console` interface */ debug(...args) { this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args); this._logHandler(this, LogLevel.DEBUG, ...args); } log(...args) { this._userLogHandler && this._userLogHandler(this, LogLevel.VERBOSE, ...args); this._logHandler(this, LogLevel.VERBOSE, ...args); } info(...args) { this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args); this._logHandler(this, LogLevel.INFO, ...args); } warn(...args) { this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args); this._logHandler(this, LogLevel.WARN, ...args); } error(...args) { this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args); this._logHandler(this, LogLevel.ERROR, ...args); } } /** * @license * Copyright 2017 Google LLC * * 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. */ function isBrowserExtension() { const runtime = typeof chrome === 'object' ? chrome.runtime : typeof browser === 'object' ? browser.runtime : undefined; return typeof runtime === 'object' && runtime.id !== undefined; } /** * This method checks if indexedDB is supported by current browser/service worker context * @return true if indexedDB is supported by current browser/service worker context */ function isIndexedDBAvailable() { return typeof indexedDB === 'object'; } /** * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject * if errors occur during the database open operation. * * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox * private browsing) */ function validateIndexedDBOpenable() { return new Promise((resolve, reject) => { try { let preExist = true; const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module'; const request = self.indexedDB.open(DB_CHECK_NAME); request.onsuccess = () => { request.result.close(); // delete database only when it doesn't pre-exist if (!preExist) { self.indexedDB.deleteDatabase(DB_CHECK_NAME); } resolve(true); }; request.onupgradeneeded = () => { preExist = false; }; request.onerror = () => { var _a; reject(((_a = request.error) === null || _a === void 0 ? void 0 : _a.message) || ''); }; } catch (error) { reject(error); } }); } /** * * This method checks whether cookie is enabled within current browser * @return true if cookie is enabled within current browser */ function areCookiesEnabled() { if (typeof navigator === 'undefined' || !navigator.cookieEnabled) { return false; } return true; } /** * @license * Copyright 2017 Google LLC * * 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 Standardized Firebase Error. * * Usage: * * // Typescript string literals for type-safe codes * type Err = * 'unknown' | * 'object-not-found' * ; * * // Closure enum for type-safe error codes * // at-enum {string} * var Err = { * UNKNOWN: 'unknown', * OBJECT_NOT_FOUND: 'object-not-found', * } * * let errors: Map<Err, string> = { * 'generic-error': "Unknown error", * 'file-not-found': "Could not find file: {$file}", * }; * * // Type-safe function - must pass a valid error code as param. * let error = new ErrorFactory<Err>('service', 'Service', errors); * * ... * throw error.create(Err.GENERIC); * ... * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName}); * ... * // Service: Could not file file: foo.txt (service/file-not-found). * * catch (e) { * assert(e.message === "Could not find file: foo.txt."); * if ((e as FirebaseError)?.code === 'service/file-not-found') { * console.log("Could not read file: " + e['file']); * } * } */ const ERROR_NAME = 'FirebaseError'; // Based on code from: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types class FirebaseError extends Error { constructor( /** The error code for this error. */ code, message, /** Custom data for this error. */ customData) { super(message); this.code = code; this.customData = customData; /** The custom name for all FirebaseErrors. */ this.name = ERROR_NAME; // Fix For ES5 // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work Object.setPrototypeOf(this, FirebaseError.prototype); // Maintains proper stack trace for where our error was thrown. // Only available on V8. if (Error.captureStackTrace) { Error.captureStackTrace(this, ErrorFactory.prototype.create); } } } class ErrorFactory { constructor(service, serviceName, errors) { this.service = service; this.serviceName = serviceName; this.errors = errors; } create(code, ...data) { const customData = data[0] || {}; const fullCode = `${this.service}/${code}`; const template = this.errors[code]; const message = template ? replaceTemplate(template, customData) : 'Error'; // Service Name: Error message (service/code). const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`; const error = new FirebaseError(fullCode, fullMessage, customData); return error; } } function replaceTemplate(template, data) { return template.replace(PATTERN, (_, key) => { const value = data[key]; return value != null ? String(value) : `<${key}?>`; }); } const PATTERN = /\{\$([^}]+)}/g; /** * Deep equal two objects. Support Arrays and Objects. */ function deepEqual(a, b) { if (a === b) { return true; } const aKeys = Object.keys(a); const bKeys = Object.keys(b); for (const k of aKeys) { if (!bKeys.includes(k)) { return false; } const aProp = a[k]; const bProp = b[k]; if (isObject(aProp) && isObject(bProp)) { if (!deepEqual(aProp, bProp)) { return false; } } else if (aProp !== bProp) { return false; } } for (const k of bKeys) { if (!aKeys.includes(k)) { return false; } } return true; } function isObject(thing) { return thing !== null && typeof thing === 'object'; } /** * @license * Copyright 2019 Google LLC * * 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. */ /** * The amount of milliseconds to exponentially increase. */ const DEFAULT_INTERVAL_MILLIS = 1000; /** * The factor to backoff by. * Should be a number greater than 1. */ const DEFAULT_BACKOFF_FACTOR = 2; /** * The maximum milliseconds to increase to. * * <p>Visible for testing */ const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android. /** * The percentage of backoff time to randomize by. * See * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic * for context. * * <p>Visible for testing */ const RANDOM_FACTOR = 0.5; /** * Based on the backoff method from * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js. * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around. */ function calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) { // Calculates an exponentially increasing value. // Deviation: calculates value from count and a constant interval, so we only need to save value // and count to restore state. const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount); // A random "fuzz" to avoid waves of retries. // Deviation: randomFactor is required. const randomWait = Math.round( // A fraction of the backoff value to add/subtract. // Deviation: changes multiplication order to improve readability. RANDOM_FACTOR * currBaseValue * // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines // if we add or subtract. (Math.random() - 0.5) * 2); // Limits backoff to max to avoid effectively permanent backoff. return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait); } /** * @license * Copyright 2021 Google LLC * * 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. */ function getModularInstance(service) { if (service && service._delegate) { return service._delegate; } else { return service; } } /** * Component for service name T, e.g. `auth`, `auth-internal` */ class Component { /** * * @param name The public service name, e.g. app, auth, firestore, database * @param instanceFactory Service factory responsible for creating the public interface * @param type whether the service provided by the component is public or private */ constructor(name, instanceFactory, type) { this.name = name; this.instanceFactory = instanceFactory; this.type = type; this.multipleInstances = false; /** * Properties to be added to the service namespace */ this.serviceProps = {}; this.instantiationMode = "LAZY" /* LAZY */; this.onInstanceCreated = null; } setInstantiationMode(mode) { this.instantiationMode = mode; return this; } setMultipleInstances(multipleInstances) { this.multipleInstances = multipleInstances; return this; } setServiceProps(props) { this.serviceProps = props; return this; } setInstanceCreatedCallback(callback) { this.onInstanceCreated = callback; return this; } } const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c); let idbProxyableTypes; let cursorAdvanceMethods; // This is a function to prevent it throwing up in node environments. function getIdbProxyableTypes() { return (idbProxyableTypes || (idbProxyableTypes = [ IDBDatabase, IDBObjectStore, IDBIndex, IDBCursor, IDBTransaction, ])); } // This is a function to prevent it throwing up in node environments. function getCursorAdvanceMethods() { return (cursorAdvanceMethods || (cursorAdvanceMethods = [ IDBCursor.prototype.advance, IDBCursor.prototype.continue, IDBCursor.prototype.continuePrimaryKey, ])); } const cursorRequestMap = new WeakMap(); const transactionDoneMap = new WeakMap(); const transactionStoreNamesMap = new WeakMap(); const transformCache = new WeakMap(); const reverseTransformCache = new WeakMap(); function promisifyRequest(request) { const promise = new Promise((resolve, reject) => { const unlisten = () => { request.removeEventListener('success', success); request.removeEventListener('error', error); }; const success = () => { resolve(wrap(request.result)); unlisten(); }; const error = () => { reject(request.error); unlisten(); }; request.addEventListener('success', success); request.addEventListener('error', error); }); promise .then((value) => { // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval // (see wrapFunction). if (value instanceof IDBCursor) { cursorRequestMap.set(value, request); } // Catching to avoid "Uncaught Promise exceptions" }) .catch(() => { }); // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This // is because we create many promises from a single IDBRequest. reverseTransformCache.set(promise, request); return promise; } function cacheDonePromiseForTransaction(tx) { // Early bail if we've already created a done promise for this transaction. if (transactionDoneMap.has(tx)) return; const done = new Promise((resolve, reject) => { const unlisten = () => { tx.removeEventListener('complete', complete); tx.removeEventListener('error', error); tx.removeEventListener('abort', error); }; const complete = () => { resolve(); unlisten(); }; const error = () => { reject(tx.error || new DOMException('AbortError', 'AbortError')); unlisten(); }; tx.addEventListener('complete', complete); tx.addEventListener('error', error); tx.addEventListener('abort', error); }); // Cache it for later retrieval. transactionDoneMap.set(tx, done); } let idbProxyTraps = { get(target, prop, receiver) { if (target instanceof IDBTransaction) { // Special handling for transaction.done. if (prop === 'done') return transactionDoneMap.get(target); // Polyfill for objectStoreNames because of Edge. if (prop === 'objectStoreNames') { return target.objectStoreNames || transactionStoreNamesMap.get(target); } // Make tx.store return the only store in the transaction, or undefined if there are many. if (prop === 'store') { return receiver.objectStoreNames[1] ? undefined : receiver.objectStore(receiver.objectStoreNames[0]); } } // Else transform whatever we get back. return wrap(target[prop]); }, set(target, prop, value) { target[prop] = value; return true; }, has(target, prop) { if (target instanceof IDBTransaction && (prop === 'done' || prop === 'store')) { return true; } return prop in target; }, }; function replaceTraps(callback) { idbProxyTraps = callback(idbProxyTraps); } function wrapFunction(func) { // Due to expected object equality (which is enforced by the caching in `wrap`), we // only create one new func per func. // Edge doesn't support objectStoreNames (booo), so we polyfill it here. if (func === IDBDatabase.prototype.transaction && !('objectStoreNames' in IDBTransaction.prototype)) { return function (storeNames, ...args) { const tx = func.call(unwrap(this), storeNames, ...args); transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]); return wrap(tx); }; } // Cursor methods are special, as the behaviour is a little more different to standard IDB. In // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense // with real promises, so each advance methods returns a new promise for the cursor object, or // undefined if the end of the cursor has been reached. if (getCursorAdvanceMethods().includes(func)) { return function (...args) { // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use // the original object. func.apply(unwrap(this), args); return wrap(cursorRequestMap.get(this)); }; } return function (...args) { // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use // the original object. return wrap(func.apply(unwrap(this), args)); }; } function transformCachableValue(value) { if (typeof value === 'function') return wrapFunction(value); // This doesn't return, it just creates a 'done' promise for the transaction, // which is later returned for transaction.done (see idbObjectHandler). if (value instanceof IDBTransaction) cacheDonePromiseForTransaction(value); if (instanceOfAny(value, getIdbProxyableTypes())) return new Proxy(value, idbProxyTraps); // Return the same value back if we're not going to transform it. return value; } function wrap(value) { // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached. if (value instanceof IDBRequest) return promisifyRequest(value); // If we've already transformed this value before, reuse the transformed value. // This is faster, but it also provides object equality. if (transformCache.has(value)) return transformCache.get(value); const newValue = transformCachableValue(value); // Not all types are transformed. // These may be primitive types, so they can't be WeakMap keys. if (newValue !== value) { transformCache.set(value, newValue); reverseTransformCache.set(newValue, value); } return newValue; } const unwrap = (value) => reverseTransformCache.get(value); /** * Open a database. * * @param name Name of the database. * @param version Schema version. * @param callbacks Additional callbacks. */ function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) { const request = indexedDB.open(name, version); const openPromise = wrap(request); if (upgrade) { request.addEventListener('upgradeneeded', (event) => { upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction)); }); } if (blocked) request.addEventListener('blocked', () => blocked()); openPromise .then((db) => { if (terminated) db.addEventListener('close', () => terminated()); if (blocking) db.addEventListener('versionchange', () => blocking()); }) .catch(() => { }); return openPromise; } const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count']; const writeMethods = ['put', 'add', 'delete', 'clear']; const cachedMethods = new Map(); function getMethod(target, prop) { if (!(target instanceof IDBDatabase && !(prop in target) && typeof prop === 'string')) { return; } if (cachedMethods.get(prop)) return cachedMethods.get(prop); const targetFuncName = prop.replace(/FromIndex$/, ''); const useIndex = prop !== targetFuncName; const isWrite = writeMethods.includes(targetFuncName); if ( // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge. !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName))) { return; } const method = async function (storeName, ...args) { // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :( const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly'); let target = tx.store; if (useIndex) target = target.index(args.shift()); // Must reject if op rejects. // If it's a write operation, must reject if tx.done rejects. // Must reject with op rejection first. // Must resolve with op value. // Must handle both promises (no unhandled rejections) return (await Promise.all([ target[targetFuncName](...args), isWrite && tx.done, ]))[0]; }; cachedMethods.set(prop, method); return method; } replaceTraps((oldTraps) => ({ ...oldTraps, get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver), has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop), })); const name$1 = "@firebase/installations"; const version$1 = "0.5.12-20220707215600"; /** * @license * Copyright 2019 Google LLC * * 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. */ const PENDING_TIMEOUT_MS = 10000; const PACKAGE_VERSION = `w:${version$1}`; const INTERNAL_AUTH_VERSION = 'FIS_v2'; const INSTALLATIONS_API_URL = 'https://firebaseinstallations.googleapis.com/v1'; const TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour const SERVICE = 'installations'; const SERVICE_NAME = 'Installations'; /** * @license * Copyright 2019 Google LLC * * 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. */ const ERROR_DESCRIPTION_MAP = { ["missing-app-config-values" /* MISSING_APP_CONFIG_VALUES */]: 'Missing App configuration value: "{$valueName}"', ["not-registered" /* NOT_REGISTERED */]: 'Firebase Installation is not registered.', ["installation-not-found" /* INSTALLATION_NOT_FOUND */]: 'Firebase Installation not found.', ["request-failed" /* REQUEST_FAILED */]: '{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"', ["app-offline" /* APP_OFFLINE */]: 'Could not process request. Application offline.', ["delete-pending-registration" /* DELETE_PENDING_REGISTRATION */]: "Can't delete installation while there is a pending registration request." }; const ERROR_FACTORY$1 = new ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP); /** Returns true if error is a FirebaseError that is based on an error from the server. */ function isServerError(error) { return (error instanceof FirebaseError && error.code.includes("request-failed" /* REQUEST_FAILED */)); } /** * @license * Copyright 2019 Google LLC * * 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. */ function getInstallationsEndpoint({ projectId }) { return `${INSTALLATIONS_API_URL}/projects/${projectId}/installations`; } function extractAuthTokenInfoFromResponse(response) { return { token: response.token, requestStatus: 2 /* COMPLETED */, expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn), creationTime: Date.now() }; } async function getErrorFromResponse(requestName, response) { const responseJson = await response.json(); const errorData = responseJson.error; return ERROR_FACTORY$1.create("request-failed" /* REQUEST_FAILED */, { requestName, serverCode: errorData.code, serverMessage: errorData.message, serverStatus: errorData.status }); } function getHeaders$1({ apiKey }) { return new Headers({ 'Content-Type': 'application/json', Accept: 'application/json', 'x-goog-api-key': apiKey }); } function getHeadersWithAuth(appConfig, { refreshToken }) { const headers = getHeaders$1(appConfig); headers.append('Authorization', getAuthorizationHeader(refreshToken)); return headers; } /** * Calls the passed in fetch wrapper and returns the response. * If the returned response has a status of 5xx, re-runs the function once and * returns the response. */ async function retryIfServerError(fn) { const result = await fn(); if (result.status >= 500 && result.status < 600) { // Internal Server Error. Retry request. return fn(); } return result; } function getExpiresInFromResponseExpiresIn(responseExpiresIn) { // This works because the server will never respond with fractions of a second. return Number(responseExpiresIn.replace('s', '000')); } function getAuthorizationHeader(refreshToken) { return `${INTERNAL_AUTH_VERSION} ${refreshToken}`; } /** * @license * Copyright 2019 Google LLC * * 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. */ async function createInstallationRequest({ appConfig, heartbeatServiceProvider }, { fid }) { const endpoint = getInstallationsEndpoint(appConfig); const headers = getHeaders$1(appConfig); // If heartbeat service exists, add the heartbeat string to the header. const heartbeatService = heartbeatServiceProvider.getImmediate({ optional: true }); if (heartbeatService) { const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader(); if (heartbeatsHeader) { headers.append('x-firebase-client', heartbeatsHeader); } } const body = { fid, authVersion: INTERNAL_AUTH_VERSION, appId: appConfig.appId, sdkVersion: PACKAGE_VERSION }; const request = { method: 'POST', headers, body: JSON.stringify(body) }; const response = await retryIfServerError(() => fetch(endpoint, request)); if (response.ok) { const responseValue = await response.json(); const registeredInstallationEntry = { fid: responseValue.fid || fid, registrationStatus: 2 /* COMPLETED */, refreshToken: responseValue.refreshToken, authToken: extractAuthTokenInfoFromResponse(responseValue.authToken) }; return registeredInstallationEntry; } else { throw await getErrorFromResponse('Create Installation', response); } } /** * @license * Copyright 2019 Google LLC * * 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. */ /** Returns a promise that resolves after given time passes. */ function sleep(ms) { return new Promise(resolve => { setTimeout(resolve, ms); }); } /** * @license * Copyright 2019 Google LLC * * 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. */ function bufferToBase64UrlSafe(array) { const b64 = btoa(String.fromCharCode(...array)); return b64.replace(/\+/g, '-').replace(/\//g, '_'); } /** * @license * Copyright 2019 Google LLC * * 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. */ const VALID_FID_PATTERN = /^[cdef][\w-]{21}$/; const INVALID_FID = ''; /** * Generates a new FID using random values from Web Crypto API. * Returns an empty string if FID generation fails for any reason. */ function generateFid() { try { // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5 // bytes. our implementation generates a 17 byte array instead. const fidByteArray = new Uint8Array(17); const crypto = self.crypto || self.msCrypto; crypto.getRandomValues(fidByteArray); // Replace the first 4 random bits with the constant FID header of 0b0111. fidByteArray[0] = 0b01110000 + (fidByteArray[0] % 0b00010000); const fid = encode(fidByteArray); return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID; } catch (_a) { // FID generation errored return INVALID_FID; } } /** Converts a FID Uint8Array to a base64 string representation. */ function encode(fidByteArray) { const b64String = bufferToBase64UrlSafe(fidByteArray); // Remove the 23rd character that was added because of the extra 4 bits at the // end of our 17 byte array, and the '=' padding. return b64String.substr(0, 22); } /** * @license * Copyright 2019 Google LLC * * 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. */ /** Returns a string key that can be used to identify the app. */ function getKey(appConfig) { return `${appConfig.appName}!${appConfig.appId}`; } /** * @license * Copyright 2019 Google LLC * * 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. */ const fidChangeCallbacks = new Map(); /** * Calls the onIdChange callbacks with the new FID value, and broadcasts the * change to other tabs. */ function fidChanged(appConfig, fid) { const key = getKey(appConfig); callFidChangeCallbacks(key, fid); broadcastFidChange(key, fid); } function callFidChangeCallbacks(key, fid) { const callbacks = fidChangeCallbacks.get(key); if (!callbacks) { return; } for (const callback of callbacks) { callback(fid); } } function broadcastFidChange(key, fid) { const channel = getBroadcastChannel(); if (channel) { channel.postMessage({ key, fid }); } closeBroadcastChannel(); } let broadcastChannel = null; /** Opens and returns a BroadcastChannel if it is supported by the browser. */ function getBroadcastChannel() { if (!broadcastChannel && 'BroadcastChannel' in self) { broadcastChannel = new BroadcastChannel('[Firebase] FID Change'); broadcastChannel.onmessage = e => { callFidChangeCallbacks(e.data.key, e.data.fid); }; } return broadcastChannel; } function closeBroadcastChannel() { if (fidChangeCallbacks.size === 0 && broadcastChannel) { broadcastChannel.close(); broadcastChannel = null; } } /** * @license * Copyright 2019 Google LLC * * 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. */ const DATABASE_NAME = 'firebase-installations-database'; const DATABASE_VERSION = 1; const OBJECT_STORE_NAME = 'firebase-installations-store'; let dbPromise = null; function getDbPromise() { if (!dbPromise) { dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, { upgrade: (db, oldVersion) => { // We don't use 'break' in this switch statement, the fall-through // behavior is what we want, because if there are multiple versions between // the old version and the current version, we want ALL the migrations // that correspond to those versions to run, not only the last one. // eslint-disable-next-line default-case switch (oldVersion) { case 0: db.createObjectStore(OBJECT_STORE_NAME); } } }); } return dbPromise; } /** Assigns or overwrites the record for the given key with the given value. */ async function set(appConfig, value) { const key = getKey(appConfig); const db = await getDbPromise(); const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite'); const objectStore = tx.objectStore(OBJECT_STORE_NAME); const oldValue = (await objectStore.get(key)); await objectStore.put(value, key); await tx.done; if (!oldValue || oldValue.fid !== value.fid) { fidChanged(appConfig, value.fid); } return value; } /** Removes record(s) from the objectStore that match the given key. */ async function remove(appConfig) { const key = getKey(appConfig); const db = await getDbPromise(); const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite'); await tx.objectStore(OBJECT_STORE_NAME).delete(key); await tx.done; } /** * Atomically updates a record with the result of updateFn, which gets * called with the current value. If newValue is undefined, the record is * deleted instead. * @return Updated value */ async function update(appConfig, updateFn) { const key = getKey(appConfig); const db = await getDbPromise(); const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite'); const store = tx.objectStore(OBJECT_STORE_NAME); const oldValue = (await store.get(key)); const newValue = updateFn(oldValue); if (newValue === undefined) { await store.delete(key); } else { await store.put(newValue, key); } await tx.done; if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) { fidChanged(appConfig, newValue.fid); } return newValue; } /** * @license * Copyright 2019 Google LLC * * 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. */ /** * Updates and returns the InstallationEntry from the database. * Also triggers a registration request if it is necessary and possible. */ async function getInstallationEntry(installations) { let registrationPromise; const installationEntry = await update(installations.appConfig, oldEntry => { const installationEntry = updateOrCreateInstallationEntry(oldEntry); const entryWithPromise = triggerRegistrationIfNecessary(installations, installationEntry); registrationPromise = entryWithPromise.registrationPromise; return entryWithPromise.installationEntry; }); if (installationEntry.fid === INVALID_FID) { // FID generation failed. Waiting for the FID from the server. return { installationEntry: await registrationPromise }; } return { installationEntry, registrationPromise }; } /** * Creates a new Installation Entry if one does not exist. * Also clears timed out pending requests. */ function updateOrCreateInstallationEntry(oldEntry) { const entry = oldEntry || { fid: generateFid(), registrationStatus: 0 /* NOT_STARTED */ }; return clearTimedOutRequest(entry); } /** * If the Firebase Installation is not registered yet, this will trigger the * registration and return an InProgressInstallationEntry. * * If registrationPromise does not exist, the installationEntry is guaranteed * to be registered. */ function triggerRegistrationIfNecessary(installations, installationEntry) { if (installationEntry.registrationStatus === 0 /* NOT_STARTED */) { if (!navigator.onLine) { // Registration required but app is offline. const registrationPromiseWithError = Promise.reject(ERROR_FACTORY$1.create("app-offline" /* APP_OFFLINE */)); return { installationEntry, registrationPromise: registrationPromiseWithError }; } // Try registering. Change status to IN_PROGRESS. const inProgressEntry = { fid: installationEntry.fid, registrationStatus: 1 /* IN_PROGRESS */, registrationTime: Date.now() }; const registrationPromise = registerInstallation(installations, inProgressEntry); return { installationEntry: inProgressEntry, registrationPromise }; } else if (installationEntry.registrationStatus === 1 /* IN_PROGRESS */) { return { installationEntry, registrationPromise: waitUntilFidRegistration(installations) }; } else { return { installationEntry }; } } /** This will be executed only once for each new Firebase Installation. */ async function registerInstallation(installations, installationEntry) { try { const registeredInstallationEntry = await createInstallationRequest(installations, installationEntry); return set(installations.appConfig, registeredInstallationEntry); } catch (e) { if (isServerError(e) && e.customData.serverCode === 409) { // Server returned a "FID can not be used" error. // Generate a new ID next time. await remove(installations.appConfig); } else { // Registration failed. Set FID as not registered. await set(installations.appConfig, { fid: installationEntry.fid, registrationStatus: 0 /* NOT_STARTED */ }); } throw e; } } /** Call if FID registration is pending in another request. */ async function waitUntilFidRegistration(installations) { // Unfortunately, there is no way of reliably observing when a value in // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers), // so we need to poll. let entry = await updateInstallationRequest(installations.appConfig); while (entry.registrationStatus === 1 /* IN_PROGRESS */) { // createInstallation request still in progress. await sleep(100); entry = await updateInstallationRequest(installations.appConfig); } if (entry.registrationStatus === 0 /* NOT_STARTED */) { // The request timed out or failed in a different call. Try again. const { installationEntry, registrationPromise } = await getInstallationEntry(installations); if (registrationPromise) { return registrationPromise; } else { // if there is no registrationPromise, entry is registered. return installationEntry; } } return entry; } /** * Called only if there is a CreateInstallation request in progress. * * Updates the InstallationEntry in the DB based on the status of the * CreateInstallation request. * * Returns the updated InstallationEntry. */ function updateInstallationRequest(appConfig) { return update(appConfig, oldEntry => { if (!oldEntry) { throw ERROR_FACTORY$1.create("installation-not-found" /* INSTALLATION_NOT_FOUND */); } return clearTimedOutRequest(oldEntry); }); } function clearTimedOutRequest(entry) { if (hasInstallationRequestTimedOut(entry)) { return { fid: entry.fid, registrationStatus: 0 /* NOT_STARTED */ }; } return entry; } function hasInstallationRequestTimedOut(installationEntry) { return (installationEntry.registrationStatus === 1 /* IN_PROGRESS */ && installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now()); } /** * @license * Copyright 2019 Google LLC * * 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. */ async function generateAuthTokenRequest({ appConfig, heartbeatServiceProvider }, installationEntry) { const endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry); const headers = getHeadersWithAuth(appConfig, installationEntry); // If heartbeat service exists, add the heartbeat string to the header. const heartbeatService = heartbeatServiceProvider.getImmediate({ optional: true }); if (heartbeatService) { const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader(); if (heartbeatsHeader) { headers.append('x-firebase-client', heartbeatsHeader); } } const body = { installation: { sdkVersion: PACKAGE_VERSION, appId: appConfig.appId } }; const request = { method: 'POST', headers, body: JSON.stringify(body) }; const response = await retryIfServerError(() => fetch(endpoint, request)); if (response.ok) { const responseValue = await response.json(); const completedAuthToken = extractAuthTokenInfoFromResponse(responseValue); return completedAuthToken; } else { throw await getErrorFromResponse('Generate Auth Token', response); } } function getGenerateAuthTokenEndpoint(appConfig, { fid }) { return `${getInstallationsEndpoint(appConfig)}/${fid}/authTokens:generate`; } /** * @license * Copyright 2019 Google LLC * * 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. */ /** * Returns a valid authentication token for the installation. Generates a new * token if one doesn't exist, is expired or about to expire. * * Should only be called if the Firebase Installation is registered. */ async function refreshAuthToken(installations, forceRefresh = false) { let tokenPromise; const entry = await update(installations.appConfig, oldEntry => { if (!isEntryRegistered(oldEntry)) { throw ERROR_FACTORY$1.create("not-registered" /* NOT_REGISTERED */); } const oldAuthToken = oldEntry.authToken; if (!forceRefresh && isAuthTokenValid(oldAuthToken)) { // There is a valid token in the DB. return oldEntry; } else if (oldAuthToken.requestStatus === 1 /* IN_PROGRESS */) { // There already is a token request in progress. tokenPromise = waitUntilAuthTokenRequest(installations, forceRefresh); return oldEntry; } else { // No token or token expired. if (!navigator.onLine) { throw ERROR_FACTORY$1.create("app-offline" /* APP_OFFLINE */); } const inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry); tokenPromise = fetchAuthTokenFromServer(installations, inProgressEntry); return inProgressEntry; } }); const authToken = tokenPromise ? await tokenPromise : entry.authToken; return authToken; } /** * Call only if FID is registered and Auth Token request is in progress. * * Waits until the current pending request finishes. If the request times out, * tries once in this thread as well. */ async function waitUntilAuthTokenRequest(installations, forceRefresh) { // Unfortunately, there is no way of reliably observing when a value in // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers), // so we need to poll. let entry = await updateAuthTokenRequest(installations.appConfig); while (entry.authToken.requestStatus === 1 /* IN_PROGRESS */) { // generateAuthToken still in progress. await sleep(100); entry = await updateAuthTokenRequest(installations.appConfig); } const authToken = entry.authToken; if (authToken.requestStatus === 0 /* NOT_STARTED */) { // The request timed out or failed in a different call. Try again. return refreshAuthToken(installations, forceRefresh); } else { return authToken; } } /** * Called only if there is a GenerateAuthToken request in progress. * * Updates the InstallationEntry in the DB based on the status of the * GenerateAuthToken request. * * Returns the updated InstallationEntry. */ function updateAuthTokenRequest(appConfig) { return update(appConfig, oldEntry => { if (!isEntryRegistered(oldEntry)) { throw ERROR_FACTORY$1.create("not-registered" /* NOT_REGISTERED */); } const oldAuthToken = oldEntry.authToken; if (hasAuthTokenRequestTimedOut(oldAuthToken)) { return Object.assign(Object.assign({}, oldEntry), { authToken: { requestStatus: 0 /* NOT_STARTED */ } }); } return oldEntry; }); } async function fetchAuthTokenFromServer(installations, installationEntry) { try { const authToken = await generateAuthTokenRequest(installations, installationEntry); const updatedInstallationEntry = Object.assign(Object.assign({}, installationEntry), { authToken }); await set(installations.appConfig, updatedInstallationEntry); return authToken; } catch (e) { if (isServerError(e) && (e.customData.serverCode === 401 || e.customData.serverCode === 404)) { // Server returned a "FID not found" or a "Invalid authentication" error. // Generate a new ID next time. await remove(installations.appConfig); } else { const updatedInstallationEntry = Object.assign(Object.assign({}, installationEntry), { authToken: { requestStatus: 0 /* NOT_STARTED */ } }); await set(installations.appConfig, updatedInstallationEntry); } throw e; } } function isEntryRegistered(installationEntry) { return (installationEntry !== undefined && installationEntry.registrationStatus === 2 /* COMPLETED */); } function isAuthTokenValid(authToken) { return (authToken.requestStatus === 2 /* COMPLETED */ && !isAuthTokenExpired(authToken)); } function isAuthTokenExpired(authToken) { const now = Date.now(); return (now < authToken.creationTime || authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER); } /** Returns an updated InstallationEntry with an InProgressAuthToken. */ function makeAuthTokenRequestInProgressEntry(oldEntry) { const inProgressAuthToken = { requestStatus: 1 /* IN_PROGRESS */, requestTime: Date.now() }; return Object.assign(Object.assign({}, oldEntry), { authToken: inProgressAuthToken }); } function hasAuthTokenRequestTimedOut(authToken) { return (authToken.requestStatus === 1 /* IN_PROGRESS */ && authToken.requestTime + PENDING_TIMEOUT_MS < Date.now()); } /** * @license * Copyright 2019 Google LLC * * 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. */ /** * Creates a Firebase Installation if there isn't one for the app and * returns the Installation ID. * @param installations - The `Installations` instance. * * @public */ async function getId(installations) { const installationsImpl = installations; const { installationEntry, registrationPromise } = await getInstallationEntry(installationsImpl); if (registrationPromise) { registrationPromise.catch(console.error); } else { // If the installation is already registered, update the authentication // token if needed. refreshAuthToken(installationsImpl).catch(console.error); } return installationEntry.fid; } /** * @license * Copyright 2019 Google LLC * * 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. */ /** * Returns a Firebase Installations auth token, identifying the current * Firebase Installation. * @param installations - The `Installations` instance. * @param forceRefresh - Force refresh regardless of token expiration. * * @public */ async function getToken(installations, forceRefresh = false) { const installationsImpl = installations; await completeInstallationRegistration(installationsImpl); // At this point we either have a Registered Installation in the DB, or we've // already thrown an error. const authToken = await refreshAuthToken(installationsImpl, forceRefresh); return authToken.token; } async function completeInstallationRegistration(installations) { const { registrationPromise } = await getInstallationEntry(installations); if (registrationPromise) { // A createInstallation request is in progress. Wait until it finishes. await registrationPromise; } } /** * @license * Copyright 2019 Google LLC * * 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. */ function extractAppConfig(app) { if (!app || !app.options) { throw getMissingValueError('App Configuration'); } if (!app.name) { throw getMissingValueError('App Name'); } // Required app config keys const configKeys = [ 'projectId', 'apiKey', 'appId' ]; for (const keyName of configKeys) { if (!app.options[keyName]) { throw getMissingValueError(keyName); } } return { appName: app.name, projectId: app.options.projectId, apiKey: app.options.apiKey, appId: app.options.appId }; } function getMissingValueError(valueName) { return ERROR_FACTORY$1.create("missing-app-config-values" /* MISSING_APP_CONFIG_VALUES */, { valueName }); } /** * @license * Copyright 2020 Google LLC * * 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. */ const INSTALLATIONS_NAME = 'installations'; const INSTALLATIONS_NAME_INTERNAL = 'installations-internal'; const publicFactory = (container) => { const app = container.getProvider('app').getImmediate(); // Throws if app isn't configured properly. const appConfig = extractAppConfig(app); const heartbeatServiceProvider = _getProvider(app, 'heartbeat'); const installationsImpl = { app, appConfig, heartbeatServiceProvider, _delete: () => Promise.resolve() }; return installationsImpl; }; const internalFactory = (container) => { const app = container.getProvider('app').getImmediate(); // Internal FIS instance relies on public FIS instance. const installations = _getProvider(app, INSTALLATIONS_NAME).getImmediate(); const installationsInternal = { getId: () => getId(installations), getToken: (forceRefresh) => getToken(installations, forceRefresh) }; return installationsInternal; }; function registerInstallations() { _registerComponent(new Component(INSTALLATIONS_NAME, publicFactory, "PUBLIC" /* PUBLIC */)); _registerComponent(new Component(INSTALLATIONS_NAME_INTERNAL, internalFactory, "PRIVATE" /* PRIVATE */)); } /** * Firebase Installations * * @packageDocumentation */ registerInstallations(); registerVersion(name$1, version$1); // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation registerVersion(name$1, version$1, 'esm2017'); /** * @license * Copyright 2019 Google LLC * * 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. */ /** * Type constant for Firebase Analytics. */ const ANALYTICS_TYPE = 'analytics'; // Key to attach FID to in gtag params. const GA_FID_KEY = 'firebase_id'; const ORIGIN_KEY = 'origin'; const FETCH_TIMEOUT_MILLIS = 60 * 1000; const DYNAMIC_CONFIG_URL = 'https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig'; const GTAG_URL = 'https://www.googletagmanager.com/gtag/js'; /** * @license * Copyright 2019 Google LLC * * 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. */ const logger = new Logger('@firebase/analytics'); /** * @license * Copyright 2019 Google LLC * * 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. */ /** * Makeshift polyfill for Promise.allSettled(). Resolves when all promises * have either resolved or rejected. * * @param promises Array of promises to wait for. */ function promiseAllSettled(promises) { return Promise.all(promises.map(promise => promise.catch(e => e))); } /** * Inserts gtag script tag into the page to asynchronously download gtag. * @param dataLayerName Name of datalayer (most often the default, "_dataLayer"). */ function insertScriptTag(dataLayerName, measurementId) { const script = document.createElement('script'); // We are not providing an analyticsId in the URL because it would trigger a `page_view` // without fid. We will initialize ga-id using gtag (config) command together with fid. script.src = `${GTAG_URL}?l=${dataLayerName}&id=${measurementId}`; script.async = true; document.head.appendChild(script); } /** * Get reference to, or create, global datalayer. * @param dataLayerName Name of datalayer (most often the default, "_dataLayer"). */ function getOrCreateDataLayer(dataLayerName) { // Check for existing dataLayer and create if needed. let dataLayer = []; if (Array.isArray(window[dataLayerName])) { dataLayer = window[dataLayerName]; } else { window[dataLayerName] = dataLayer; } return dataLayer; } /** * Wrapped gtag logic when gtag is called with 'config' command. * * @param gtagCore Basic gtag function that just appends to dataLayer. * @param initializationPromisesMap Map of appIds to their initialization promises. * @param dynamicConfigPromisesList Array of dynamic config fetch promises. * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId. * @param measurementId GA Measurement ID to set config for. * @param gtagParams Gtag config params to set. */ async function gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, measurementId, gtagParams) { // If config is already fetched, we know the appId and can use it to look up what FID promise we /// are waiting for, and wait only on that one. const correspondingAppId = measurementIdToAppId[measurementId]; try { if (correspondingAppId) { await initializationPromisesMap[correspondingAppId]; } else { // If config is not fetched yet, wait for all configs (we don't know which one we need) and // find the appId (if any) corresponding to this measurementId. If there is one, wait on // that appId's initialization promise. If there is none, promise resolves and gtag // call goes through. const dynamicConfigResults = await promiseAllSettled(dynamicConfigPromisesList); const foundConfig = dynamicConfigResults.find(config => config.measurementId === measurementId); if (foundConfig) { await initializationPromisesMap[foundConfig.appId]; } } } catch (e) { logger.error(e); } gtagCore("config" /* CONFIG */, measurementId, gtagParams); } /** * Wrapped gtag logic when gtag is called with 'event' command. * * @param gtagCore Basic gtag function that just appends to dataLayer. * @param initializationPromisesMap Map of appIds to their initialization promises. * @param dynamicConfigPromisesList Array of dynamic config fetch promises. * @param measurementId GA Measurement ID to log event to. * @param gtagParams Params to log with this event. */ async function gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementId, gtagParams) { try { let initializationPromisesToWaitFor = []; // If there's a 'send_to' param, check if any ID specified matches // an initializeIds() promise we are waiting for. if (gtagParams && gtagParams['send_to']) { let gaSendToList = gtagParams['send_to']; // Make it an array if is isn't, so it can be dealt with the same way. if (!Array.isArray(gaSendToList)) { gaSendToList = [gaSendToList]; } // Checking 'send_to' fields requires having all measurement ID results back from // the dynamic config fetch. const dynamicConfigResults = await promiseAllSettled(dynamicConfigPromisesList); for (const sendToId of gaSendToList) { // Any fetched dynamic measurement ID that matches this 'send_to' ID const foundConfig = dynamicConfigResults.find(config => config.measurementId === sendToId); const initializationPromise = foundConfig && initializationPromisesMap[foundConfig.appId]; if (initializationPromise) { initializationPromisesToWaitFor.push(initializationPromise); } else { // Found an item in 'send_to' that is not associated // directly with an FID, possibly a group. Empty this array, // exit the loop early, and let it get populated below. initializationPromisesToWaitFor = []; break; } } } // This will be unpopulated if there was no 'send_to' field , or // if not all entries in the 'send_to' field could be mapped to // a FID. In these cases, wait on all pending initialization promises. if (initializationPromisesToWaitFor.length === 0) { initializationPromisesToWaitFor = Object.values(initializationPromisesMap); } // Run core gtag function with args after all relevant initialization // promises have been resolved. await Promise.all(initializationPromisesToWaitFor); // Workaround for http://b/141370449 - third argument cannot be undefined. gtagCore("event" /* EVENT */, measurementId, gtagParams || {}); } catch (e) { logger.error(e); } } /** * Wraps a standard gtag function with extra code to wait for completion of * relevant initialization promises before sending requests. * * @param gtagCore Basic gtag function that just appends to dataLayer. * @param initializationPromisesMap Map of appIds to their initialization promises. * @param dynamicConfigPromisesList Array of dynamic config fetch promises. * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId. */ function wrapGtag(gtagCore, /** * Allows wrapped gtag calls to wait on whichever intialization promises are required, * depending on the contents of the gtag params' `send_to` field, if any. */ initializationPromisesMap, /** * Wrapped gtag calls sometimes require all dynamic config fetches to have returned * before determining what initialization promises (which include FIDs) to wait for. */ dynamicConfigPromisesList, /** * Wrapped gtag config calls can narrow down which initialization promise (with FID) * to wait for if the measurementId is already fetched, by getting the corresponding appId, * which is the key for the initialization promises map. */ measurementIdToAppId) { /** * Wrapper around gtag that ensures FID is sent with gtag calls. * @param command Gtag command type. * @param idOrNameOrParams Measurement ID if command is EVENT/CONFIG, params if command is SET. * @param gtagParams Params if event is EVENT/CONFIG. */ async function gtagWrapper(command, idOrNameOrParams, gtagParams) { try { // If event, check that relevant initialization promises have completed. if (command === "event" /* EVENT */) { // If EVENT, second arg must be measurementId. await gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, idOrNameOrParams, gtagParams); } else if (command === "config" /* CONFIG */) { // If CONFIG, second arg must be measurementId. await gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, idOrNameOrParams, gtagParams); } else if (command === "consent" /* CONSENT */) { // If CONFIG, second arg must be measurementId. gtagCore("consent" /* CONSENT */, 'update', gtagParams); } else { // If SET, second arg must be params. gtagCore("set" /* SET */, idOrNameOrParams); } } catch (e) { logger.error(e); } } return gtagWrapper; } /** * Creates global gtag function or wraps existing one if found. * This wrapped function attaches Firebase instance ID (FID) to gtag 'config' and * 'event' calls that belong to the GAID associated with this Firebase instance. * * @param initializationPromisesMap Map of appIds to their initialization promises. * @param dynamicConfigPromisesList Array of dynamic config fetch promises. * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId. * @param dataLayerName Name of global GA datalayer array. * @param gtagFunctionName Name of global gtag function ("gtag" if not user-specified). */ function wrapOrCreateGtag(initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, dataLayerName, gtagFunctionName) { // Create a basic core gtag function let gtagCore = function (..._args) { // Must push IArguments object, not an array. window[dataLayerName].push(arguments); }; // Replace it with existing one if found if (window[gtagFunctionName] && typeof window[gtagFunctionName] === 'function') { // @ts-ignore gtagCore = window[gtagFunctionName]; } window[gtagFunctionName] = wrapGtag(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId); return { gtagCore, wrappedGtag: window[gtagFunctionName] }; } /** * Returns first script tag in DOM matching our gtag url pattern. */ function findGtagScriptOnPage() { const scriptTags = window.document.getElementsByTagName('script'); for (const tag of Object.values(scriptTags)) { if (tag.src && tag.src.includes(GTAG_URL)) { return tag; } } return null; } /** * @license * Copyright 2019 Google LLC * * 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. */ const ERRORS = { ["already-exists" /* ALREADY_EXISTS */]: 'A Firebase Analytics instance with the appId {$id} ' + ' already exists. ' + 'Only one Firebase Analytics instance can be created for each appId.', ["already-initialized" /* ALREADY_INITIALIZED */]: 'initializeAnalytics() cannot be called again with different options than those ' + 'it was initially called with. It can be called again with the same options to ' + 'return the existing instance, or getAnalytics() can be used ' + 'to get a reference to the already-intialized instance.', ["already-initialized-settings" /* ALREADY_INITIALIZED_SETTINGS */]: 'Firebase Analytics has already been initialized.' + 'settings() must be called before initializing any Analytics instance' + 'or it will have no effect.', ["interop-component-reg-failed" /* INTEROP_COMPONENT_REG_FAILED */]: 'Firebase Analytics Interop Component failed to instantiate: {$reason}', ["invalid-analytics-context" /* INVALID_ANALYTICS_CONTEXT */]: 'Firebase Analytics is not supported in this environment. ' + 'Wrap initialization of analytics in analytics.isSupported() ' + 'to prevent initialization in unsupported environments. Details: {$errorInfo}', ["indexeddb-unavailable" /* INDEXEDDB_UNAVAILABLE */]: 'IndexedDB unavailable or restricted in this environment. ' + 'Wrap initialization of analytics in analytics.isSupported() ' + 'to prevent initialization in unsupported environments. Details: {$errorInfo}', ["fetch-throttle" /* FETCH_THROTTLE */]: 'The config fetch request timed out while in an exponential backoff state.' + ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.', ["config-fetch-failed" /* CONFIG_FETCH_FAILED */]: 'Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}', ["no-api-key" /* NO_API_KEY */]: 'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field to' + 'contain a valid API key.', ["no-app-id" /* NO_APP_ID */]: 'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field to' + 'contain a valid app ID.' }; const ERROR_FACTORY = new ErrorFactory('analytics', 'Analytics', ERRORS); /** * @license * Copyright 2020 Google LLC * * 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. */ /** * Backoff factor for 503 errors, which we want to be conservative about * to avoid overloading servers. Each retry interval will be * BASE_INTERVAL_MILLIS * LONG_RETRY_FACTOR ^ retryCount, so the second one * will be ~30 seconds (with fuzzing). */ const LONG_RETRY_FACTOR = 30; /** * Base wait interval to multiplied by backoffFactor^backoffCount. */ const BASE_INTERVAL_MILLIS = 1000; /** * Stubbable retry data storage class. */ class RetryData { constructor(throttleMetadata = {}, intervalMillis = BASE_INTERVAL_MILLIS) { this.throttleMetadata = throttleMetadata; this.intervalMillis = intervalMillis; } getThrottleMetadata(appId) { return this.throttleMetadata[appId]; } setThrottleMetadata(appId, metadata) { this.throttleMetadata[appId] = metadata; } deleteThrottleMetadata(appId) { delete this.throttleMetadata[appId]; } } const defaultRetryData = new RetryData(); /** * Set GET request headers. * @param apiKey App API key. */ function getHeaders(apiKey) { return new Headers({ Accept: 'application/json', 'x-goog-api-key': apiKey }); } /** * Fetches dynamic config from backend. * @param app Firebase app to fetch config for. */ async function fetchDynamicConfig(appFields) { var _a; const { appId, apiKey } = appFields; const request = { method: 'GET', headers: getHeaders(apiKey) }; const appUrl = DYNAMIC_CONFIG_URL.replace('{app-id}', appId); const response = await fetch(appUrl, request); if (response.status !== 200 && response.status !== 304) { let errorMessage = ''; try { // Try to get any error message text from server response. const jsonResponse = (await response.json()); if ((_a = jsonResponse.error) === null || _a === void 0 ? void 0 : _a.message) { errorMessage = jsonResponse.error.message; } } catch (_ignored) { } throw ERROR_FACTORY.create("config-fetch-failed" /* CONFIG_FETCH_FAILED */, { httpStatus: response.status, responseMessage: errorMessage }); } return response.json(); } /** * Fetches dynamic config from backend, retrying if failed. * @param app Firebase app to fetch config for. */ async function fetchDynamicConfigWithRetry(app, // retryData and timeoutMillis are parameterized to allow passing a different value for testing. retryData = defaultRetryData, timeoutMillis) { const { appId, apiKey, measurementId } = app.options; if (!appId) { throw ERROR_FACTORY.create("no-app-id" /* NO_APP_ID */); } if (!apiKey) { if (measurementId) { return { measurementId, appId }; } throw ERROR_FACTORY.create("no-api-key" /* NO_API_KEY */); } const throttleMetadata = retryData.getThrottleMetadata(appId) || { backoffCount: 0, throttleEndTimeMillis: Date.now() }; const signal = new AnalyticsAbortSignal(); setTimeout(async () => { // Note a very low delay, eg < 10ms, can elapse before listeners are initialized. signal.abort(); }, timeoutMillis !== undefined ? timeoutMillis : FETCH_TIMEOUT_MILLIS); return attemptFetchDynamicConfigWithRetry({ appId, apiKey, measurementId }, throttleMetadata, signal, retryData); } /** * Runs one retry attempt. * @param appFields Necessary app config fields. * @param throttleMetadata Ongoing metadata to determine throttling times. * @param signal Abort signal. */ async function attemptFetchDynamicConfigWithRetry(appFields, { throttleEndTimeMillis, backoffCount }, signal, retryData = defaultRetryData // for testing ) { var _a, _b; const { appId, measurementId } = appFields; // Starts with a (potentially zero) timeout to support resumption from stored state. // Ensures the throttle end time is honored if the last attempt timed out. // Note the SDK will never make a request if the fetch timeout expires at this point. try { await setAbortableTimeout(signal, throttleEndTimeMillis); } catch (e) { if (measurementId) { logger.warn(`Timed out fetching this Firebase app's measurement ID from the server.` + ` Falling back to the measurement ID ${measurementId}` + ` provided in the "measurementId" field in the local Firebase config. [${(_a = e) === null || _a === void 0 ? void 0 : _a.message}]`); return { appId, measurementId }; } throw e; } try { const response = await fetchDynamicConfig(appFields); // Note the SDK only clears throttle state if response is success or non-retriable. retryData.deleteThrottleMetadata(appId); return response; } catch (e) { const error = e; if (!isRetriableError(error)) { retryData.deleteThrottleMetadata(appId); if (measurementId) { logger.warn(`Failed to fetch this Firebase app's measurement ID from the server.` + ` Falling back to the measurement ID ${measurementId}` + ` provided in the "measurementId" field in the local Firebase config. [${error === null || error === void 0 ? void 0 : error.message}]`); return { appId, measurementId }; } else { throw e; } } const backoffMillis = Number((_b = error === null || error === void 0 ? void 0 : error.customData) === null || _b === void 0 ? void 0 : _b.httpStatus) === 503 ? calculateBackoffMillis(backoffCount, retryData.intervalMillis, LONG_RETRY_FACTOR) : calculateBackoffMillis(backoffCount, retryData.intervalMillis); // Increments backoff state. const throttleMetadata = { throttleEndTimeMillis: Date.now() + backoffMillis, backoffCount: backoffCount + 1 }; // Persists state. retryData.setThrottleMetadata(appId, throttleMetadata); logger.debug(`Calling attemptFetch again in ${backoffMillis} millis`); return attemptFetchDynamicConfigWithRetry(appFields, throttleMetadata, signal, retryData); } } /** * Supports waiting on a backoff by: * * <ul> * <li>Promisifying setTimeout, so we can set a timeout in our Promise chain</li> * <li>Listening on a signal bus for abort events, just like the Fetch API</li> * <li>Failing in the same way the Fetch API fails, so timing out a live request and a throttled * request appear the same.</li> * </ul> * * <p>Visible for testing. */ function setAbortableTimeout(signal, throttleEndTimeMillis) { return new Promise((resolve, reject) => { // Derives backoff from given end time, normalizing negative numbers to zero. const backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0); const timeout = setTimeout(resolve, backoffMillis); // Adds listener, rather than sets onabort, because signal is a shared object. signal.addEventListener(() => { clearTimeout(timeout); // If the request completes before this timeout, the rejection has no effect. reject(ERROR_FACTORY.create("fetch-throttle" /* FETCH_THROTTLE */, { throttleEndTimeMillis })); }); }); } /** * Returns true if the {@link Error} indicates a fetch request may succeed later. */ function isRetriableError(e) { if (!(e instanceof FirebaseError) || !e.customData) { return false; } // Uses string index defined by ErrorData, which FirebaseError implements. const httpStatus = Number(e.customData['httpStatus']); return (httpStatus === 429 || httpStatus === 500 || httpStatus === 503 || httpStatus === 504); } /** * Shims a minimal AbortSignal (copied from Remote Config). * * <p>AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects * of networking, such as retries. Firebase doesn't use AbortController enough to justify a * polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be * swapped out if/when we do. */ class AnalyticsAbortSignal { constructor() { this.listeners = []; } addEventListener(listener) { this.listeners.push(listener); } abort() { this.listeners.forEach(listener => listener()); } } /** * @license * Copyright 2019 Google LLC * * 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. */ /** * Event parameters to set on 'gtag' during initialization. */ let defaultEventParametersForInit; /** * Logs an analytics event through the Firebase SDK. * * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event * @param eventName Google Analytics event name, choose from standard list or use a custom string. * @param eventParams Analytics event parameters. */ async function logEvent$1(gtagFunction, initializationPromise, eventName, eventParams, options) { if (options && options.global) { gtagFunction("event" /* EVENT */, eventName, eventParams); return; } else { const measurementId = await initializationPromise; const params = Object.assign(Object.assign({}, eventParams), { 'send_to': measurementId }); gtagFunction("event" /* EVENT */, eventName, params); } } /** * Set screen_name parameter for this Google Analytics ID. * * @deprecated Use {@link logEvent} with `eventName` as 'screen_view' and add relevant `eventParams`. * See {@link https://firebase.google.com/docs/analytics/screenviews | Track Screenviews}. * * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event * @param screenName Screen name string to set. */ async function setCurrentScreen$1(gtagFunction, initializationPromise, screenName, options) { if (options && options.global) { gtagFunction("set" /* SET */, { 'screen_name': screenName }); return Promise.resolve(); } else { const measurementId = await initializationPromise; gtagFunction("config" /* CONFIG */, measurementId, { update: true, 'screen_name': screenName }); } } /** * Set user_id parameter for this Google Analytics ID. * * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event * @param id User ID string to set */ async function setUserId$1(gtagFunction, initializationPromise, id, options) { if (options && options.global) { gtagFunction("set" /* SET */, { 'user_id': id }); return Promise.resolve(); } else { const measurementId = await initializationPromise; gtagFunction("config" /* CONFIG */, measurementId, { update: true, 'user_id': id }); } } /** * Set all other user properties other than user_id and screen_name. * * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event * @param properties Map of user properties to set */ async function setUserProperties$1(gtagFunction, initializationPromise, properties, options) { if (options && options.global) { const flatProperties = {}; for (const key of Object.keys(properties)) { // use dot notation for merge behavior in gtag.js flatProperties[`user_properties.${key}`] = properties[key]; } gtagFunction("set" /* SET */, flatProperties); return Promise.resolve(); } else { const measurementId = await initializationPromise; gtagFunction("config" /* CONFIG */, measurementId, { update: true, 'user_properties': properties }); } } /** * Set whether collection is enabled for this ID. * * @param enabled If true, collection is enabled for this ID. */ async function setAnalyticsCollectionEnabled$1(initializationPromise, enabled) { const measurementId = await initializationPromise; window[`ga-disable-${measurementId}`] = !enabled; } /** * Consent parameters to default to during 'gtag' initialization. */ let defaultConsentSettingsForInit; /** * Sets the variable {@link defaultConsentSettingsForInit} for use in the initialization of * analytics. * * @param consentSettings Maps the applicable end user consent state for gtag.js. */ function _setConsentDefaultForInit(consentSettings) { defaultConsentSettingsForInit = consentSettings; } /** * Sets the variable `defaultEventParametersForInit` for use in the initialization of * analytics. * * @param customParams Any custom params the user may pass to gtag.js. */ function _setDefaultEventParametersForInit(customParams) { defaultEventParametersForInit = customParams; } /** * @license * Copyright 2020 Google LLC * * 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. */ async function validateIndexedDB() { var _a; if (!isIndexedDBAvailable()) { logger.warn(ERROR_FACTORY.create("indexeddb-unavailable" /* INDEXEDDB_UNAVAILABLE */, { errorInfo: 'IndexedDB is not available in this environment.' }).message); return false; } else { try { await validateIndexedDBOpenable(); } catch (e) { logger.warn(ERROR_FACTORY.create("indexeddb-unavailable" /* INDEXEDDB_UNAVAILABLE */, { errorInfo: (_a = e) === null || _a === void 0 ? void 0 : _a.toString() }).message); return false; } } return true; } /** * Initialize the analytics instance in gtag.js by calling config command with fid. * * NOTE: We combine analytics initialization and setting fid together because we want fid to be * part of the `page_view` event that's sent during the initialization * @param app Firebase app * @param gtagCore The gtag function that's not wrapped. * @param dynamicConfigPromisesList Array of all dynamic config promises. * @param measurementIdToAppId Maps measurementID to appID. * @param installations _FirebaseInstallationsInternal instance. * * @returns Measurement ID. */ async function _initializeAnalytics(app, dynamicConfigPromisesList, measurementIdToAppId, installations, gtagCore, dataLayerName, options) { var _a; const dynamicConfigPromise = fetchDynamicConfigWithRetry(app); // Once fetched, map measurementIds to appId, for ease of lookup in wrapped gtag function. dynamicConfigPromise .then(config => { measurementIdToAppId[config.measurementId] = config.appId; if (app.options.measurementId && config.measurementId !== app.options.measurementId) { logger.warn(`The measurement ID in the local Firebase config (${app.options.measurementId})` + ` does not match the measurement ID fetched from the server (${config.measurementId}).` + ` To ensure analytics events are always sent to the correct Analytics property,` + ` update the` + ` measurement ID field in the local config or remove it from the local config.`); } }) .catch(e => logger.error(e)); // Add to list to track state of all dynamic config promises. dynamicConfigPromisesList.push(dynamicConfigPromise); const fidPromise = validateIndexedDB().then(envIsValid => { if (envIsValid) { return installations.getId(); } else { return undefined; } }); const [dynamicConfig, fid] = await Promise.all([ dynamicConfigPromise, fidPromise ]); // Detect if user has already put the gtag <script> tag on this page. if (!findGtagScriptOnPage()) { insertScriptTag(dataLayerName, dynamicConfig.measurementId); } // Detects if there are consent settings that need to be configured. if (defaultConsentSettingsForInit) { gtagCore("consent" /* CONSENT */, 'default', defaultConsentSettingsForInit); _setConsentDefaultForInit(undefined); } // This command initializes gtag.js and only needs to be called once for the entire web app, // but since it is idempotent, we can call it multiple times. // We keep it together with other initialization logic for better code structure. // eslint-disable-next-line @typescript-eslint/no-explicit-any gtagCore('js', new Date()); // User config added first. We don't want users to accidentally overwrite // base Firebase config properties. const configProperties = (_a = options === null || options === void 0 ? void 0 : options.config) !== null && _a !== void 0 ? _a : {}; // guard against developers accidentally setting properties with prefix `firebase_` configProperties[ORIGIN_KEY] = 'firebase'; configProperties.update = true; if (fid != null) { configProperties[GA_FID_KEY] = fid; } // It should be the first config command called on this GA-ID // Initialize this GA-ID and set FID on it using the gtag config API. // Note: This will trigger a page_view event unless 'send_page_view' is set to false in // `configProperties`. gtagCore("config" /* CONFIG */, dynamicConfig.measurementId, configProperties); // Detects if there is data that will be set on every event logged from the SDK. if (defaultEventParametersForInit) { gtagCore("set" /* SET */, defaultEventParametersForInit); _setDefaultEventParametersForInit(undefined); } return dynamicConfig.measurementId; } /** * @license * Copyright 2019 Google LLC * * 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. */ /** * Analytics Service class. */ class AnalyticsService { constructor(app) { this.app = app; } _delete() { delete initializationPromisesMap[this.app.options.appId]; return Promise.resolve(); } } /** * Maps appId to full initialization promise. Wrapped gtag calls must wait on * all or some of these, depending on the call's `send_to` param and the status * of the dynamic config fetches (see below). */ let initializationPromisesMap = {}; /** * List of dynamic config fetch promises. In certain cases, wrapped gtag calls * wait on all these to be complete in order to determine if it can selectively * wait for only certain initialization (FID) promises or if it must wait for all. */ let dynamicConfigPromisesList = []; /** * Maps fetched measurementIds to appId. Populated when the app's dynamic config * fetch completes. If already populated, gtag config calls can use this to * selectively wait for only this app's initialization promise (FID) instead of all * initialization promises. */ const measurementIdToAppId = {}; /** * Name for window global data layer array used by GA: defaults to 'dataLayer'. */ let dataLayerName = 'dataLayer'; /** * Name for window global gtag function used by GA: defaults to 'gtag'. */ let gtagName = 'gtag'; /** * Reproduction of standard gtag function or reference to existing * gtag function on window object. */ let gtagCoreFunction; /** * Wrapper around gtag function that ensures FID is sent with all * relevant event and config calls. */ let wrappedGtagFunction; /** * Flag to ensure page initialization steps (creation or wrapping of * dataLayer and gtag script) are only run once per page load. */ let globalInitDone = false; /** * Configures Firebase Analytics to use custom `gtag` or `dataLayer` names. * Intended to be used if `gtag.js` script has been installed on * this page independently of Firebase Analytics, and is using non-default * names for either the `gtag` function or for `dataLayer`. * Must be called before calling `getAnalytics()` or it won't * have any effect. * * @public * * @param options - Custom gtag and dataLayer names. */ function settings(options) { if (globalInitDone) { throw ERROR_FACTORY.create("already-initialized" /* ALREADY_INITIALIZED */); } if (options.dataLayerName) { dataLayerName = options.dataLayerName; } if (options.gtagName) { gtagName = options.gtagName; } } /** * Returns true if no environment mismatch is found. * If environment mismatches are found, throws an INVALID_ANALYTICS_CONTEXT * error that also lists details for each mismatch found. */ function warnOnBrowserContextMismatch() { const mismatchedEnvMessages = []; if (isBrowserExtension()) { mismatchedEnvMessages.push('This is a browser extension environment.'); } if (!areCookiesEnabled()) { mismatchedEnvMessages.push('Cookies are not available.'); } if (mismatchedEnvMessages.length > 0) { const details = mismatchedEnvMessages .map((message, index) => `(${index + 1}) ${message}`) .join(' '); const err = ERROR_FACTORY.create("invalid-analytics-context" /* INVALID_ANALYTICS_CONTEXT */, { errorInfo: details }); logger.warn(err.message); } } /** * Analytics instance factory. * @internal */ function factory(app, installations, options) { warnOnBrowserContextMismatch(); const appId = app.options.appId; if (!appId) { throw ERROR_FACTORY.create("no-app-id" /* NO_APP_ID */); } if (!app.options.apiKey) { if (app.options.measurementId) { logger.warn(`The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest` + ` measurement ID for this Firebase app. Falling back to the measurement ID ${app.options.measurementId}` + ` provided in the "measurementId" field in the local Firebase config.`); } else { throw ERROR_FACTORY.create("no-api-key" /* NO_API_KEY */); } } if (initializationPromisesMap[appId] != null) { throw ERROR_FACTORY.create("already-exists" /* ALREADY_EXISTS */, { id: appId }); } if (!globalInitDone) { // Steps here should only be done once per page: creation or wrapping // of dataLayer and global gtag function. getOrCreateDataLayer(dataLayerName); const { wrappedGtag, gtagCore } = wrapOrCreateGtag(initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, dataLayerName, gtagName); wrappedGtagFunction = wrappedGtag; gtagCoreFunction = gtagCore; globalInitDone = true; } // Async but non-blocking. // This map reflects the completion state of all promises for each appId. initializationPromisesMap[appId] = _initializeAnalytics(app, dynamicConfigPromisesList, measurementIdToAppId, installations, gtagCoreFunction, dataLayerName, options); const analyticsInstance = new AnalyticsService(app); return analyticsInstance; } /* eslint-disable @typescript-eslint/no-explicit-any */ /** * Returns an {@link Analytics} instance for the given app. * * @public * * @param app - The {@link https://www.gstatic.com/firebasejs/9.9.0-20220707215600/firebase-app.js#FirebaseApp} to use. */ function getAnalytics(app = getApp()) { app = getModularInstance(app); // Dependencies const analyticsProvider = _getProvider(app, ANALYTICS_TYPE); if (analyticsProvider.isInitialized()) { return analyticsProvider.getImmediate(); } return initializeAnalytics(app); } /** * Returns an {@link Analytics} instance for the given app. * * @public * * @param app - The {@link https://www.gstatic.com/firebasejs/9.9.0-20220707215600/firebase-app.js#FirebaseApp} to use. */ function initializeAnalytics(app, options = {}) { // Dependencies const analyticsProvider = _getProvider(app, ANALYTICS_TYPE); if (analyticsProvider.isInitialized()) { const existingInstance = analyticsProvider.getImmediate(); if (deepEqual(options, analyticsProvider.getOptions())) { return existingInstance; } else { throw ERROR_FACTORY.create("already-initialized" /* ALREADY_INITIALIZED */); } } const analyticsInstance = analyticsProvider.initialize({ options }); return analyticsInstance; } /** * This is a public static method provided to users that wraps four different checks: * * 1. Check if it's not a browser extension environment. * 2. Check if cookies are enabled in current browser. * 3. Check if IndexedDB is supported by the browser environment. * 4. Check if the current browser context is valid for using `IndexedDB.open()`. * * @public * */ async function isSupported() { if (isBrowserExtension()) { return false; } if (!areCookiesEnabled()) { return false; } if (!isIndexedDBAvailable()) { return false; } try { const isDBOpenable = await validateIndexedDBOpenable(); return isDBOpenable; } catch (error) { return false; } } /** * Use gtag `config` command to set `screen_name`. * * @public * * @deprecated Use {@link logEvent} with `eventName` as 'screen_view' and add relevant `eventParams`. * See {@link https://firebase.google.com/docs/analytics/screenviews | Track Screenviews}. * * @param analyticsInstance - The {@link Analytics} instance. * @param screenName - Screen name to set. */ function setCurrentScreen(analyticsInstance, screenName, options) { analyticsInstance = getModularInstance(analyticsInstance); setCurrentScreen$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], screenName, options).catch(e => logger.error(e)); } /** * Use gtag `config` command to set `user_id`. * * @public * * @param analyticsInstance - The {@link Analytics} instance. * @param id - User ID to set. */ function setUserId(analyticsInstance, id, options) { analyticsInstance = getModularInstance(analyticsInstance); setUserId$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], id, options).catch(e => logger.error(e)); } /** * Use gtag `config` command to set all params specified. * * @public */ function setUserProperties(analyticsInstance, properties, options) { analyticsInstance = getModularInstance(analyticsInstance); setUserProperties$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], properties, options).catch(e => logger.error(e)); } /** * Sets whether Google Analytics collection is enabled for this app on this device. * Sets global `window['ga-disable-analyticsId'] = true;` * * @public * * @param analyticsInstance - The {@link Analytics} instance. * @param enabled - If true, enables collection, if false, disables it. */ function setAnalyticsCollectionEnabled(analyticsInstance, enabled) { analyticsInstance = getModularInstance(analyticsInstance); setAnalyticsCollectionEnabled$1(initializationPromisesMap[analyticsInstance.app.options.appId], enabled).catch(e => logger.error(e)); } /** * Adds data that will be set on every event logged from the SDK, including automatic ones. * With gtag's "set" command, the values passed persist on the current page and are passed with * all subsequent events. * @public * @param customParams - Any custom params the user may pass to gtag.js. */ function setDefaultEventParameters(customParams) { // Check if reference to existing gtag function on window object exists if (wrappedGtagFunction) { wrappedGtagFunction("set" /* SET */, customParams); } else { _setDefaultEventParametersForInit(customParams); } } /** * Sends a Google Analytics event with given `eventParams`. This method * automatically associates this logged event with this Firebase web * app instance on this device. * List of official event parameters can be found in the gtag.js * reference documentation: * {@link https://developers.google.com/gtagjs/reference/ga4-events * | the GA4 reference documentation}. * * @public */ function logEvent(analyticsInstance, eventName, eventParams, options) { analyticsInstance = getModularInstance(analyticsInstance); logEvent$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], eventName, eventParams, options).catch(e => logger.error(e)); } /** * Sets the applicable end user consent state for this web app across all gtag references once * Firebase Analytics is initialized. * * Use the {@link ConsentSettings} to specify individual consent type values. By default consent * types are set to "granted". * @public * @param consentSettings - Maps the applicable end user consent state for gtag.js. */ function setConsent(consentSettings) { // Check if reference to existing gtag function on window object exists if (wrappedGtagFunction) { wrappedGtagFunction("consent" /* CONSENT */, 'update', consentSettings); } else { _setConsentDefaultForInit(consentSettings); } } const name = "@firebase/analytics"; const version = "0.8.0-20220707215600"; /** * Firebase Analytics * * @packageDocumentation */ function registerAnalytics() { _registerComponent(new Component(ANALYTICS_TYPE, (container, { options: analyticsOptions }) => { // getImmediate for FirebaseApp will always succeed const app = container.getProvider('app').getImmediate(); const installations = container .getProvider('installations-internal') .getImmediate(); return factory(app, installations, analyticsOptions); }, "PUBLIC" /* PUBLIC */)); _registerComponent(new Component('analytics-internal', internalFactory, "PRIVATE" /* PRIVATE */)); registerVersion(name, version); // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation registerVersion(name, version, 'esm2017'); function internalFactory(container) { try { const analytics = container.getProvider(ANALYTICS_TYPE).getImmediate(); return { logEvent: (eventName, eventParams, options) => logEvent(analytics, eventName, eventParams, options) }; } catch (e) { throw ERROR_FACTORY.create("interop-component-reg-failed" /* INTEROP_COMPONENT_REG_FAILED */, { reason: e }); } } } registerAnalytics(); export { getAnalytics, initializeAnalytics, isSupported, logEvent, setAnalyticsCollectionEnabled, setConsent, setCurrentScreen, setDefaultEventParameters, setUserId, setUserProperties, settings }; //# sourceMappingURL=firebase-analytics.js.map
{ "content_hash": "62e39646d729260b41b9770e20af7322", "timestamp": "", "source": "github", "line_count": 2911, "max_line_length": 196, "avg_line_length": 39.178976296805224, "alnum_prop": 0.6559842174484876, "repo_name": "cdnjs/cdnjs", "id": "a9334c37e828e25a16610e30e96989bee4ba96b1", "size": "114669", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ajax/libs/firebase/9.9.0-20220707215600/firebase-analytics.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package com.aol.cyclops.matcher.builders; import static com.aol.cyclops.matcher.builders.SeqUtils.seq; import java.lang.invoke.MethodType; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.val; import lombok.experimental.Wither; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import com.aol.cyclops.lambda.api.Decomposable; import com.aol.cyclops.matcher.Action; import com.aol.cyclops.matcher.ActionWithReturn; import com.aol.cyclops.matcher.Case; import com.aol.cyclops.matcher.Cases; import com.aol.cyclops.matcher.ChainOfResponsibility; import com.aol.cyclops.matcher.Extractor; import com.aol.cyclops.matcher.Extractors; import com.aol.cyclops.matcher.Two; import com.nurkiewicz.lazyseq.LazySeq; /** * PatternMatcher supports advanced pattern matching for Java 8 * * This is an API for creating Case instances and allows new type definitions to be supplied for each Case * * Features include * * -cases match by value * -cases match by type * -cases using predicates * inCaseOfXXX * caseOfXXX * -cases using hamcrest Matchers * inMatchOfXXX * matchOfXXX * -cases as expressions (return value) - inCaseOfXXX, inMatchOfXXX * -cases as statements (no return value) - caseOfXXX, matchOfXXX * -pre &amp; post variable extraction via Extractor (@see com.aol.cyclops.matcher.Extractors) * -match using iterables of predicates or hamcrest Matchers * - see caseOfIterable, matchOfIterable, inCaseOfIterable, matchOfIterable * -match using tuples of predicates or hamcreate Matchers * - see caseOfTuple, matchOfTuple, inCaseOfTuple, inMatchOfTuple * * - single match (match method) * - match many (matchMany) * - match against a stream (single match, match many) * * @author johnmcclean * */ @SuppressWarnings("unchecked") @AllArgsConstructor public class PatternMatcher implements Function{ @Wither @Getter private final Cases cases; public PatternMatcher(){ cases = Cases.of(); } /** * @return Pattern Matcher as function that will return the 'unwrapped' result when apply is called. * i.e. Optional#get will be called. * */ public <T,X> Function<T,X> asUnwrappedFunction(){ return cases.asUnwrappedFunction(); } /** * @return Pattern Matcher as a function that will return a Stream of results */ public <T,X> Function<T,Stream<X>> asStreamFunction(){ return cases.asStreamFunction(); } /* * @param t Object to match against * @return Value from matched case if present * @see java.util.function.Function#apply(java.lang.Object) */ public Optional<Object> apply(Object t){ return match(t); } /** * Each input element can generated multiple matched values * * @param s Stream of data to match against (input to matcher) * @return Stream of values from matched cases */ public<R> Stream<R> matchManyFromStream(Stream s){ return s.flatMap(this::matchMany); } /** * * @param t input to match against - can generate multiple values * @return Stream of values from matched cases for the input */ public<R> Stream<R> matchMany(Object t) { return cases.matchMany(t); } /** * Each input element can generated a single matched value * * @param s Stream of data to match against (input to matcher) * @return Stream of matched values, one case per input value can match */ public <R> Stream<R> matchFromStream(Stream s){ return cases.matchFromStream(s); } /** * Aggregates supplied objects into a List for matching against * * * @param t Array to match on * @return Matched value wrapped in Optional */ public <R> Optional<R> match(Object... t){ return cases.match(t); } /** * Decomposes the supplied input via it's unapply method * Provides a List to the Matcher of values to match on * * @param t Object to decompose and match on * @return Matched result wrapped in an Optional */ public <R> Optional<R> unapply(Decomposable t){ return cases.unapply(t); } /** * @param t Object to match against supplied cases * @return Value returned from matched case (if present) otherwise Optional.empty() */ public <R> Optional<R> match(Object t){ return cases.match(t); } /** * Match by type specified in Extractor as input, if user provided type via match, matches the Action (Action extends Consumer) * will be executed and provided with the result of the extraction. * e.g. * <pre> * new PatternMatcher().caseOfType(Person::getAge, (Integer i) -&gt; value = i) .match(new Person(100)); * </pre> * * This case will be triggered and the action will recieve the age of the Person (100). * * * @param ext will be used to extract a value from the user input to the matcher. * @param a A consumer that will accept value from the extractor if user input matches the extractor input type * @return self * * (type V is not R to allow matching of V against R) */ public <R,T,X,V> PatternMatcher caseOfType( Extractor<T,R> ext,Action<V> a){ val extractor = Extractors.memoised(ext); val type = a.getType(); val clazz = type.parameterType(type.parameterCount()-1); Predicate predicate = extractorPredicate(extractor,it -> it.getClass().isAssignableFrom(clazz)); return this.withCases(cases.append( index(),Case.of(predicate,extractorAction(extractor,new ActionWithReturnWrapper(a))))); } Object extractIfType(Object t,Extractor extractor){ try{ MethodType type = extractor.getType(); if(type.parameterCount()==0) return t; //can't get parameter types for MethodReferences return type.parameterType(type.parameterCount() - 1).isAssignableFrom(t.getClass()) ? extractor.apply(t) : t; }catch(ClassCastException e){ // MethodReferences will result in ClassCastExceptions } return t; } Predicate extractorPredicate(Extractor extractor, Predicate p){ if(extractor ==null) return p; return t -> p.test(extractIfType(t,extractor)); } ActionWithReturn extractorAction(Extractor extractor, ActionWithReturn action){ if(extractor==null) return action; return input -> action.apply(extractor.apply(input)); } /** * Match by specified value against the extracted value from user input. Data will only be extracted from user input if * user input is of a type acceptable to the extractor * * <pre> * new PatternMatcher.caseOfValue(100, Person::getAge, (Integer i) -&gt; value = i) .match(new Person(100)); * </pre> * * This case will be triggered and the users age will be extracted, it matches 100 so the action will then be triggered. * * * @param value Value to match against (via equals method) * @param extractor will be used to extract a value from the user input to the matcher. * @param a A consumer that will accept value from the extractor if user input matches the extractor input type * @return */ public <R,V,T,X> PatternMatcher caseOfValue(R value, Extractor<T,R> extractor,Action<V> a){ return inCaseOfValue(value,extractor,new ActionWithReturnWrapper(a)); } /** * Match by specified value and then execute supplied action. * * <pre> * new PatternMatcher.caseOfValue(100, (Person p) -&gt; value = p.getAge()) .match(new Person(100)); * </pre> * * @param value to compare against, if Objects.equals(value,matching-input) is true, action is triggered * @param a Action to be consumed (no return value) * @return new PatternMatcher */ public <V,X> PatternMatcher caseOfValue(V value,Action<V> a){ return caseOfThenExtract(it -> Objects.equals(it, value), a, null); } /** * Match against an iterable using supplied predicates. Each predicate will be tested a against a different sequential element in the user * supplied iterable. e.g. * * <pre> * new PatternMatcher() * .caseOfMany((List&lt;String&gt; list) -&gt; language = list.get(1) , * v -&gt; v.equals(&quot;-l&quot;) || v.equals(&quot;---lang&quot;),v-&gt;true) * .match(asList(&quot;-l&quot;,&quot;java&quot;)); * * assertThat(language,is(&quot;java&quot;)); * </pre> * * @param a Action to execute if case passes * @param predicates To match against each sequential element in the iterable * @return New PatternMatcher */ @SafeVarargs public final <V> PatternMatcher caseOfMany(Action<List<V>> a,Predicate<V>... predicates){ LazySeq<Predicate<V>> pred = LazySeq.of(predicates); return caseOfThenExtract(it -> seq(it).zip(pred,(a1,b1)->Two.tuple(a1,b1)) .map(t -> t.v2.test((V)t.v1)).allMatch(v-> v), a, this::wrapInList); } /** * Match against an iterable using supplied hamcrest matchers. Each matcher will be tested a against a different sequential element in the user * supplied iterable. e.g. * * <pre> * new PatternMatcher() * .matchOfMany( (List&lt;String&gt; list) -&gt; language = list.get(1) , * equalTo(&quot;-l&quot;),any(String.class)) * .match(asList(&quot;-l&quot;,&quot;java&quot;)); * * assertThat(language,is(&quot;java&quot;)); * * </pre> * * @param a Action to execute if case passes * @param predicates To match against each sequential element in the iterable * @return New PatternMatcher */ @SafeVarargs public final <V> PatternMatcher matchOfMany(Action<List<V>> a,Matcher<V>... predicates){ LazySeq<Matcher<V>> pred = LazySeq.of(predicates); return matchOfThenExtract(new BaseMatcher(){ @Override public boolean matches(Object item) { return seq(item).zip(pred,(a1,b1)->Two.tuple(a1,b1)) .map(t -> t.v2.matches((V)t.v1)).allMatch(v->v==true); } @Override public void describeTo(Description description) { } }, a, this::wrapInList); } /** * Run both matchers in the supplied tuple against the first two elements of a supplied iterable for matching * <pre> * new PatternMatcher() * .matchOfMatchers(tuple( equalTo(&quot;-l&quot;), * anything()), * lang -&gt; language = lang,Extractors.&lt;String&gt;at(1) ) * .match(tuple(&quot;-l&quot;,&quot;java&quot;)); * * assertThat(language,is(&quot;java&quot;)); * </pre> * * * @param predicates Tuple of 2 hamcrest matchers * @param a Action to be triggered on successful match, will receive data via the extractor * @param extractor Extractor to extract data out of incoming iterable after matchers have matched * @return New Pattern Matcher */ public <T,R,V,V1> PatternMatcher matchOfMatchers(Two<Matcher<V>,Matcher<V1>> predicates, Action<R> a,Extractor<T,R> extractor){ LazySeq<Object> pred = LazySeq.of(predicates); return matchOfThenExtract(new BaseMatcher(){ @Override public boolean matches(Object item) { return seq(item).zip(pred,(a1,b1)->Two.tuple(a1,b1)).map(t -> ((Matcher)t.v2).matches(t.v1)).allMatch(v->v==true); } @Override public void describeTo(Description description) { } }, a, extractor); } /** * Run both predicates in the supplied tuple against the first two elements of a supplied iterable for matching * <pre> * new PatternMatcher() * .caseOfPredicates(tuple( v -&gt; v.equals(&quot;-l&quot;) || v.equals(&quot;---lang&quot;), * v-&gt;true), * lang -&gt; language =lang,Extractors.&lt;String&gt;at(1) ) * .match(tuple(&quot;-l&quot;,&quot;java&quot;)); * * assertThat(language,is(&quot;java&quot;)); * * </pre> * * @param predicates Tuple of 2 predicates * @param a Action to be triggered on successful match, will receive data via the extractor * @param extractor Extractor to extract data out of incoming iterable after predicates have matched * @return New Pattern Matcher */ public <T,R,V,V1> PatternMatcher caseOfPredicates(Two<Predicate<V>,Predicate<V1>> predicates, Action<R> a,Extractor<T,R> extractor){ LazySeq<Object> pred = LazySeq.of(predicates); return caseOfThenExtract(it -> seq(it).zip(pred,(a1,b1)->Two.tuple(a1,b1)).map(t -> ((Predicate)t.v2).test(t.v1)).allMatch(v->v==true), a, extractor); } /** * Match against a tuple of predicates (or prototype values, or hamcrest matchers). Each predicate will match against an element in an iterable. * * <pre> * new PatternMatcher() * .caseOfTuple(tuple(p( v -&gt; v.equals(&quot;-l&quot;) || v.equals(&quot;---lang&quot;)), * p(v-&gt;true)), * lang -&gt; language =lang,Extractors.&lt;String&gt;at(1) ) * .match(tuple(&quot;-l&quot;,&quot;java&quot;)); * * assertThat(language,is(&quot;java&quot;)); * </pre> * @param predicates Predicates to match with * @param a Action triggered if predicates hold * @param extractor * @return */ public <T,R> PatternMatcher caseOfTuple(Iterable predicates, Action<R> a,Extractor<T,R> extractor){ LazySeq<Object> pred = LazySeq.of(predicates); return caseOfThenExtract(it -> seq(it).zip(pred,(a1,b1)->Two.tuple(a1,b1)).map(t -> (convertToPredicate(t.v2)).test(t.v1)).allMatch(v->v==true), a, extractor); } private Predicate convertToPredicate(Object o){ if(o instanceof Predicate) return (Predicate)o; if(o instanceof Matcher) return test -> ((Matcher)o).matches(test); return test -> Objects.equals(test,o); } public <T,R> PatternMatcher matchOfTuple(Iterable predicates, Action<R> a,Extractor<T,R> extractor){ LazySeq<Object> pred = LazySeq.of(predicates); return matchOfThenExtract(new BaseMatcher(){ @Override public boolean matches(Object item) { return seq(item).zip(pred,(a1,b1)->Two.tuple(a1,b1)).map(t -> ((Matcher)t.v2).matches(t.v1)).allMatch(v->v==true); } @Override public void describeTo(Description description) { } }, a, extractor); } public <V,X> PatternMatcher selectFromChain(Stream<? extends ChainOfResponsibility<V,X>> stream){ return selectFrom(stream.map(n->new Two(n,n))); } public <V,X> PatternMatcher selectFrom(Stream<Two<Predicate<V>,Function<V,X>>> stream){ PatternMatcher[] matcher = {this}; stream.forEach(t -> matcher[0] = matcher[0].inCaseOf(t.v1,a->t.v2.apply(a))); return matcher[0]; } public <T,V,X> PatternMatcher inCaseOfManyType(Predicate master,ActionWithReturn<T,X> a, Predicate<V>... predicates){ LazySeq<Predicate<V>> pred = LazySeq.of(predicates); return inCaseOf(it -> master.test(it) && seq(Extractors.decompose().apply(it)).zip(pred,(a1,b1)->Two.tuple(a1,b1)) .map(t -> t.v2.test((V)t.v1)).allMatch(v->v==true), a); } public <V,X> PatternMatcher inCaseOfMany(ActionWithReturn<List<V>,X> a, Predicate<V>... predicates){ LazySeq<Predicate<V>> pred = LazySeq.of(predicates); return inCaseOfThenExtract(it -> seq(it).zip(pred,(a1,b1)->Two.tuple(a1,b1)) .map(t -> t.v2.test((V)t.v1)).allMatch(v->v==true), a, e-> wrapInList(e)); } private List wrapInList(Object a) { if(a instanceof List) return (List)a; else return Arrays.asList(a); } public <V,X> PatternMatcher inMatchOfMany(ActionWithReturn<List<V>,X> a, Matcher<V>... predicates){ LazySeq<Matcher<V>> pred = (LazySeq<Matcher<V>>) LazySeq.of(predicates); return inMatchOfThenExtract(new BaseMatcher(){ @Override public boolean matches(Object item) { return seq(item).zip(pred,(a1,b1)->Two.tuple(a1,b1)) .map(t -> t.v2.matches((V)t.v1)).allMatch(v->v==true); } @Override public void describeTo(Description description) { } }, a, this::wrapInList); } public <T,R,V,V1,X> PatternMatcher inMatchOfMatchers(Two<Matcher<V>,Matcher<V1>> predicates, ActionWithReturn<R,X> a,Extractor<T,R> extractor){ LazySeq<Object> pred = LazySeq.of(predicates); return inMatchOfThenExtract(new BaseMatcher(){ @Override public boolean matches(Object item) { return seq(item).zip(pred,(a1,b1)->Two.tuple(a1,b1)).map(t -> ((Matcher)t.v2).matches(t.v1)).allMatch(v->v==true); } @Override public void describeTo(Description description) { } }, a, extractor); } public <T,R,V,V1,X> PatternMatcher inCaseOfPredicates(Two<Predicate<V>,Predicate<V1>> predicates, ActionWithReturn<R,X> a,Extractor<T,R> extractor){ LazySeq<Object> pred = LazySeq.of(predicates); return inCaseOfThenExtract(it -> seq(it).zip(pred,(a1,b1)->Two.tuple(a1,b1)).map(t -> ((Predicate)t.v2).test(t.v1)).allMatch(v->v==true), a, extractor); } public <T,R,X> PatternMatcher inCaseOfStream(Stream<Predicate> predicates, ActionWithReturn<R,X> a,Extractor<T,R> extractor){ LazySeq<Object> pred = LazySeq.<Object>of((Iterator)predicates.iterator()); return inCaseOfThenExtract(it -> seq(it).zip(pred,(a1,b1)->Two.tuple(a1,b1)).map(t -> ((Predicate)t.v2).test(t.v1)).allMatch(v->v==true), a, extractor); } public <T,R,X> PatternMatcher inMatchOfSeq(Stream<Matcher> predicates, ActionWithReturn<R,X> a,Extractor<T,R> extractor){ LazySeq<Object> pred = LazySeq.of(predicates); return inMatchOfThenExtract(new BaseMatcher(){ @Override public boolean matches(Object item) { return LazySeq.of(item).zip(pred,(a1,b1)->Two.tuple(a1,b1)).map(t -> ((Matcher)t.v2).matches(t.v1)).allMatch(v->v==true); } @Override public void describeTo(Description description) { } }, a, extractor); } public <V,X> PatternMatcher caseOfType(Action<V> a){ val type = a.getType(); val clazz = type.parameterType(type.parameterCount()-1); return caseOfThenExtract(it -> it.getClass().isAssignableFrom(clazz), a, null); } public <V> PatternMatcher matchOf(Matcher<V> match,Action<V> a){ return inCaseOfThenExtract(it->match.matches(it), new ActionWithReturnWrapper(a), null); } public <V> PatternMatcher caseOf(Predicate<V> match,Action<V> a){ return inCaseOfThenExtract(match, new ActionWithReturnWrapper(a), null); } public <R,V,T> PatternMatcher caseOfThenExtract(Predicate<V> match,Action<R> a, Extractor<T,R> extractor){ return withCases(cases.append(index(),Case.of(match, extractorAction(extractor,new ActionWithReturnWrapper(a))))); } public <R,V,T> PatternMatcher matchOfThenExtract(Matcher<V> match,Action<V> a, Extractor<T,R> extractor){ Predicate<V> predicate = it->match.matches(it); return withCases(cases.append(index(),Case.of(predicate, extractorAction(extractor,new ActionWithReturnWrapper(a))))); } public <R,V,T> PatternMatcher caseOf( Extractor<T,R> ext,Predicate<R> match,Action<V> a){ val extractor = Extractors.memoised(ext); return withCases(cases.append(index(),Case.of(extractorPredicate(extractor,match),extractorAction(extractor,new ActionWithReturnWrapper(a))))); } public <R,V,T> PatternMatcher matchOf( Extractor<T,R> ext,Matcher<R> match,Action<V> a){ val extractor = Extractors.memoised(ext); Predicate<V> predicate = it->match.matches(it); return withCases(cases.append(index(),Case.of(extractorPredicate(extractor,predicate),extractorAction(extractor,new ActionWithReturnWrapper(a))))); } public <V,X> PatternMatcher inCaseOfValue(V value,ActionWithReturn<V,X> a){ return inCaseOfThenExtract(it -> Objects.equals(it, value), a, null); } public <V,X> PatternMatcher inCaseOfType(ActionWithReturn<V,X> a){ val type = a.getType(); val clazz = type.parameterType(type.parameterCount()-1); return inCaseOfThenExtract(it -> it.getClass().isAssignableFrom(clazz), a, null); } public <V,X> PatternMatcher inCaseOf(Predicate<V> match,ActionWithReturn<V,X> a){ return inCaseOfThenExtract(match, a, null); } public <R,T,X> PatternMatcher inCaseOfThenExtract(Predicate<T> match,ActionWithReturn<R,X> a, Extractor<T,R> extractor){ return withCases(cases.append(index(),Case.of(match,extractorAction(extractor,a)))); } public <R,V,T,X> PatternMatcher inCaseOf( Extractor<T,R> ext,Predicate<V> match,ActionWithReturn<V,X> a){ val extractor = Extractors.memoised(ext); return withCases(cases.append(index(),Case.of(extractorPredicate(extractor,match),extractorAction(extractor,a)))); } public <R,V,T,X> PatternMatcher inCaseOfType( Extractor<T,R> ext,ActionWithReturn<V,X> a){ val extractor = Extractors.memoised(ext); val type = a.getType(); val clazz = type.parameterType(type.parameterCount()-1); Predicate predicate = it -> it.getClass().isAssignableFrom(clazz); return withCases(cases.append(index(),Case.of(extractorPredicate(extractor,predicate),extractorAction(extractor,a)))); } public <R,V,T,X> PatternMatcher inCaseOfValue(V value, Extractor<T,R> ext,ActionWithReturn<V,X> a){ val extractor = Extractors.memoised(ext); Predicate predicate = it -> Objects.equals(it, value); return withCases(cases.append(index(),Case.of(extractorPredicate(extractor,predicate),extractorAction(extractor,a)))); } /**hamcrest **/ public <V,X> PatternMatcher inMatchOf(Matcher<V> match,ActionWithReturn<V,X> a){ Predicate<V> predicate = it->match.matches(it); return inCaseOfThenExtract(predicate, a, null); } public <R,T,X> PatternMatcher inMatchOfThenExtract(Matcher<T> match,ActionWithReturn<R,X> a, Extractor<T,R> extractor){ Predicate<T> predicate = it->match.matches(it); return withCases(cases.append(index(),Case.of(predicate, extractorAction(extractor,a)))); } public <R,V,T,X> PatternMatcher inMatchOf( Extractor<T,R> ext,Matcher<V> match,ActionWithReturn<V,X> a){ val extractor = Extractors.memoised(ext); Predicate<V> predicate = it->match.matches(it); return withCases(cases.append(index(),Case.of(extractorPredicate(extractor,predicate),extractorAction(extractor,a)))); } private int index() { return cases.size(); } }
{ "content_hash": "2c8508db8c06c6a846cb57222e86b6bf", "timestamp": "", "source": "github", "line_count": 673, "max_line_length": 163, "avg_line_length": 32.61961367013373, "alnum_prop": 0.6952580512913953, "repo_name": "sjfloat/cyclops", "id": "e9859d1a4d70a965baff4a30bcdb399251452634", "size": "21953", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cyclops-pattern-matching/src/main/java/com/aol/cyclops/matcher/builders/PatternMatcher.java", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "16212" }, { "name": "Java", "bytes": "1336491" } ], "symlink_target": "" }
import java.io.{File, PrintWriter} import java.nio.charset.Charset import java.nio.file.{Files, Paths} import SchemaGenerators.CompiledSchema import com.google.protobuf import com.google.protobuf.{Message, TextFormat => GTextFormat} import scalapb.{GeneratedMessage, JavaProtoSupport, TextFormat} import org.scalatest.propspec.AnyPropSpec import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.scalatest.tagobjects.Slow import scalapb.descriptors.ScalaType import scala.jdk.CollectionConverters._ class GeneratedCodeSpec extends AnyPropSpec with ScalaCheckDrivenPropertyChecks with Matchers { val printer = GTextFormat.printer().escapingNonAscii(false) property("min and max id are consecutive over files") { forAll(GraphGen.genRootNode) { node => def validateMinMax(pairs: Seq[(Int, Int)]) = pairs.sliding(2).filter(_.size == 2).forall { case Seq((min1, max1), (min2, max2)) => min2 == max1 + 1 && min1 <= max1 && min2 <= max2 } val messageIdPairs: Seq[(Int, Int)] = node.files.flatMap { f => (f.minMessageId.map((_, f.maxMessageId.get))) } val enumIdPairs: Seq[(Int, Int)] = node.files.flatMap { f => (f.minEnumId.map((_, f.maxEnumId.get))) } validateMinMax(messageIdPairs) && validateMinMax(enumIdPairs) } } property("Java and Scala protos are equivalent", Slow) { forAll(SchemaGenerators.genCompiledSchema, workers(1), minSuccessful(20)) { (schema: CompiledSchema) => forAll(GenData.genMessageValueInstance(schema.rootNode)) { case (message, messageValue) => // Ascii to binary is the same. val messageAscii = messageValue.toAscii try { val builder = schema.javaBuilder(message) GTextFormat.merge(messageAscii, builder) val javaProto: protobuf.Message = builder.build() val companion = schema.scalaObject(message) val scalaProto = companion.fromAscii(messageValue.toAscii) val scalaBytes = scalaProto.toByteArray // Parsing in Scala the serialized bytes should give the same object. val scalaParsedFromBytes = companion.parseFrom(scalaBytes) scalaParsedFromBytes.toProtoString should be(scalaProto.toProtoString) scalaParsedFromBytes should be(scalaProto) // Parsing in Java the bytes serialized by Scala should give back javaProto: val javaProto2 = schema.javaParse(message, scalaBytes) javaProto2 should be(javaProto) // toJavaProto, fromJava should bring back the same object. val javaConversions = companion.asInstanceOf[JavaProtoSupport[GeneratedMessage, protobuf.Message]] javaConversions.fromJavaProto(javaProto) should be(scalaProto) javaConversions.toJavaProto(scalaProto) should be(javaProto) def javaParse(s: String): Message = { val builder = schema.javaBuilder(message) GTextFormat.merge(s, builder) builder.build() } // String representation are not always the same since maps do not preserve // the order. val scalaAscii = TextFormat.printToString(scalaProto) val scalaUnicodeAscii = TextFormat.printToUnicodeString(scalaProto) // Scala can parse the ASCII format generated by Java: companion.fromAscii(javaProto.toString) should be(scalaProto) companion.fromAscii(printer.printToString(javaProto)) should be(scalaProto) // Scala can parse the ASCII format generated by Scala: companion.fromAscii(scalaAscii) should be(scalaProto) try { companion.fromAscii(scalaUnicodeAscii) should be(scalaProto) } catch { case e: Exception => Files.write( Paths.get(s"/tmp/unicode.txt"), scalaUnicodeAscii.getBytes(Charset.forName("UTF-8")) ) throw e } // Java can parse the ASCII format generated by Scala: javaParse(scalaAscii) should be(javaProto) javaParse(scalaUnicodeAscii) should be(javaProto) // Java and Scala Descriptors have the same full names. // Enum and message fields have same full name references. companion.javaDescriptor.getFullName should be(companion.scalaDescriptor.fullName) companion.javaDescriptor.getFields.size should be( companion.scalaDescriptor.fields.size ) (companion.javaDescriptor.getFields.asScala zip companion.scalaDescriptor.fields) .foreach { case (jf, sf) => jf.getFullName should be(sf.fullName) jf.getJavaType() match { case com.google.protobuf.Descriptors.FieldDescriptor.JavaType.MESSAGE => jf.getMessageType().getFullName should be( sf.scalaType.asInstanceOf[ScalaType.Message].descriptor.fullName ) case com.google.protobuf.Descriptors.FieldDescriptor.JavaType.ENUM => jf.getEnumType().getFullName should be( sf.scalaType.asInstanceOf[ScalaType.Enum].descriptor.fullName ) case _ => } } } catch { case e: Exception => println(e.printStackTrace) println("Message: " + message.name) val pw = new PrintWriter(new File("/tmp/message.ascii")) pw.print(messageAscii) pw.close() throw new RuntimeException(e.getMessage, e) } } } } }
{ "content_hash": "b4893ca6b1c6c5b5e1d379b2c9f73f0f", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 98, "avg_line_length": 45.44615384615385, "alnum_prop": 0.6274542992552471, "repo_name": "scalapb/ScalaPB", "id": "e1af3c8090f53cdec033f86ddee5374780e94137", "size": "5908", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "proptest/src/test/scala/GeneratedCodeSpec.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1956" }, { "name": "HTML", "bytes": "9354" }, { "name": "JavaScript", "bytes": "7962" }, { "name": "Nix", "bytes": "263" }, { "name": "Python", "bytes": "848" }, { "name": "Scala", "bytes": "2559282" }, { "name": "Shell", "bytes": "3281" } ], "symlink_target": "" }
require 'net/http' require 'json' @host = "localhost" @port = ENV.fetch('PORT', '9292') @name = "Simon #{(rand() * 1000).round}" @debug = true def log_response(where, res) puts "--- #{where} ---" puts "Response: #{res.code}" puts "Token: #{res["X-Turn-Token"]}" puts res.body puts "--- -------- ---" end def get(path) req = Net::HTTP::Get.new(path) Net::HTTP.new(@host, @port).start { |http| http.request(req) } end def post(path, json, headers = nil) json = json.to_json if json.is_a?(Hash) req = Net::HTTP::Post.new(path, initheader = {'Content-Type' =>'application/json'}) headers.each { |k,v| req.add_field(k,v) } if !headers.nil? req.body = json Net::HTTP.new(@host, @port).start { |http| http.request(req) } end # returns <game_path> def create_game(rows, cols) response = post("/", { :rows => rows, :cols => cols }) response['Location'] end # returns <game_path> def match_game response = get("/match") response['Location'] end # returns [game, token] def join_game(game_path) response = post("#{game_path}/players", { :name => @name }) log_response("join", response) if @debug [JSON.parse(response.body), response['X-Turn-Token']] if response.code.to_i == 200 end # returns game def view_game(game_path) response = get(game_path) JSON.parse(response.body) end # returns [<game_delta>, token] def make_move(game_path, move, token) response = post("#{game_path}/moves", move, { "X-Turn-Token" => token }) log_response("move", response) if @debug [JSON.parse(response.body), response['X-Turn-Token']] if response.code.to_i == 200 end # returns game def update_game(game, game_delta) game['draw_size'] = game_delta['draw_size'] game['state'] = game_delta['state'] (game_delta['players'] || []).each do |player| game['players'].delete_if { |p| p['id'] == player['id'] } game['players'] << player end (game_delta['claims'] || []).each do |claim| game['claims'].delete_if { |c| c['tile'] == claim['tile'] } game['claims'] << claim end game end # returns <new_move> def choose_move(game) me = game['players'].detect { |p| p['name'] == @name } { :tile => me['hand'].sample } end game_path = ARGV[0] game_path ||= create_game(10,10) if ARGV[0] == 'create' game_path ||= match_game puts game_path if @debug || ARGV[0] == 'create' puts "Joining Game as #{@name}" if @debug game, token = join_game(game_path) exit if token.nil? puts "Entering Loop" if @debug loop do puts "Choosing Move" if @debug move = choose_move(game) puts "Chose Move: #{move}" if @debug game_delta, token = make_move(game_path, move, token) break if token.nil? game = update_game(game, game_delta) puts "Current Game: #{game}" if @debug break if game['state'] == 'completed' end
{ "content_hash": "711f858a50dc5611b51102827222313f", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 85, "avg_line_length": 27.306930693069308, "alnum_prop": 0.6316171138506164, "repo_name": "stringham/contests", "id": "ea57d9df871e07bae2a6070e740eaff6ebd3036f", "size": "2758", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "2012-mebipenny/finals/simon/client.rb", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "909" }, { "name": "CSS", "bytes": "96899" }, { "name": "HTML", "bytes": "47226" }, { "name": "Haskell", "bytes": "717" }, { "name": "JavaScript", "bytes": "2487359" }, { "name": "Python", "bytes": "47134" }, { "name": "Ruby", "bytes": "163243" }, { "name": "Shell", "bytes": "122" } ], "symlink_target": "" }
package com.dgrlucky.extend.config; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.PixelFormat; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.RandomAccessFile; import java.io.Serializable; import java.math.BigDecimal; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * @author dgrlucky * @date 16/8/25 下午6:45 * @company dgrlucky * @desc 轻量级缓存 */ public class ACache { private ACache() { } public static final int TIME_HOUR = 60 * 60; public static final int TIME_DAY = TIME_HOUR * 24; private static final int MAX_SIZE = 1000 * 1000 * 64; // 64 mb private static final int MAX_COUNT = Integer.MAX_VALUE; // 缓存数据数量 private static Map<String, ACache> mInstanceMap = new HashMap<>(); private ACacheManager mCache; public static ACache get(Context ctx) { return get(ctx, "ACache"); } public static ACache get(Context ctx, String cacheName) { File f = new File(ctx.getCacheDir(), cacheName); return get(f, MAX_SIZE, MAX_COUNT); } public static ACache get(File cacheDir) { return get(cacheDir, MAX_SIZE, MAX_COUNT); } public static ACache get(Context ctx, long maxSise, int maxCount) { File f = new File(ctx.getCacheDir(), "ACache"); return get(f, maxSise, maxCount); } public static ACache get(File cacheDir, long maxZise, int maxCount) { ACache manager = mInstanceMap.get(cacheDir.getAbsoluteFile() + myPid()); if (manager == null) { manager = new ACache(cacheDir, maxZise, maxCount); mInstanceMap.put(cacheDir.getAbsolutePath() + myPid(), manager); } return manager; } public static boolean deleteDir(File dir) { if (dir != null && dir.isDirectory()) { String[] children = dir.list(); for (String aChildren : children) { boolean success = deleteDir(new File(dir, aChildren)); if (!success) { return false; } } } assert dir != null; return dir.delete(); } public static String getCacheSize(File file) { return getFormatSize(getFolderSize(file)); } public static long getFolderSize(File file) { long size = 0; try { File[] fileList = file.listFiles(); for (File aFileList : fileList) { // 如果下面还有文件 if (aFileList.isDirectory()) { size = size + getFolderSize(aFileList); } else { size = size + aFileList.length(); } } } catch (Exception e) { e.printStackTrace(); } return size; } public static String getFormatSize(double size) { double kiloByte = size / 1024; if (kiloByte < 1) { // return size + "Byte"; return "0K"; } double megaByte = kiloByte / 1024; if (megaByte < 1) { BigDecimal result1 = new BigDecimal(Double.toString(kiloByte)); return result1.setScale(2, BigDecimal.ROUND_HALF_UP) .toPlainString() + "KB"; } double gigaByte = megaByte / 1024; if (gigaByte < 1) { BigDecimal result2 = new BigDecimal(Double.toString(megaByte)); return result2.setScale(2, BigDecimal.ROUND_HALF_UP) .toPlainString() + "MB"; } double teraBytes = gigaByte / 1024; if (teraBytes < 1) { BigDecimal result3 = new BigDecimal(Double.toString(gigaByte)); return result3.setScale(2, BigDecimal.ROUND_HALF_UP) .toPlainString() + "GB"; } BigDecimal result4 = new BigDecimal(teraBytes); return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB"; } private static String myPid() { return "_" + android.os.Process.myPid(); } private ACache(File cacheDir, long maxSize, int maxCount) { if (!cacheDir.exists() && !cacheDir.mkdirs()) { throw new RuntimeException("can't make dirs in " + cacheDir.getAbsolutePath()); } mCache = new ACacheManager(cacheDir, maxSize, maxCount); } /** * Provides a means to save a cached file before the data are available. * Since writing about the file is complete, and its close method is called, * its contents will be registered in the cache. Example of use: * <p> * ACache cache = new ACache(this) try { OutputStream stream = * cache.put("myFileName") stream.write("some bytes".getBytes()); // now * update cache! stream.close(); } catch(FileNotFoundException e){ * e.printStackTrace() } */ class xFileOutputStream extends FileOutputStream { File file; public xFileOutputStream(File file) throws FileNotFoundException { super(file); this.file = file; } public void close() throws IOException { super.close(); mCache.put(file); } } // ======================================= // ============ String数据 读写 ============== // ======================================= /** * 保存 String数据 到 缓存中 * * @param key 保存的key * @param value 保存的String数据 */ public void put(String key, String value) { File file = mCache.newFile(key); BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(file), 1024); out.write(value); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } mCache.put(file); } } /** * 保存 String数据 到 缓存中 * * @param key 保存的key * @param value 保存的String数据 * @param saveTime 保存的时间,单位:秒 */ public void put(String key, String value, int saveTime) { put(key, Utils.newStringWithDateInfo(saveTime, value)); } /** * 读取 String数据 * * @param key * @return String 数据 */ public String getAsString(String key) { File file = mCache.get(key); if (!file.exists()) return null; boolean removeFile = false; BufferedReader in = null; try { in = new BufferedReader(new FileReader(file)); String readString = ""; String currentLine; while ((currentLine = in.readLine()) != null) { readString += currentLine; } if (!Utils.isDue(readString)) { return Utils.clearDateInfo(readString); } else { removeFile = true; return null; } } catch (IOException e) { e.printStackTrace(); return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (removeFile) remove(key); } } // ======================================= // ============= JSONObject 数据 读写 ============== // ======================================= /** * 保存 JSONObject数据 到 缓存中 * * @param key 保存的key * @param value 保存的JSON数据 */ public void put(String key, JSONObject value) { put(key, value.toString()); } /** * 保存 JSONObject数据 到 缓存中 * * @param key 保存的key * @param value 保存的JSONObject数据 * @param saveTime 保存的时间,单位:秒 */ public void put(String key, JSONObject value, int saveTime) { put(key, value.toString(), saveTime); } /** * 读取JSONObject数据 * * @param key * @return JSONObject数据 */ public JSONObject getAsJSONObject(String key) { String jsonString = getAsString(key); try { JSONObject obj = new JSONObject(jsonString); return obj; } catch (Exception e) { return null; } } // ======================================= // ============ JSONArray 数据 读写 ============= // ======================================= /** * 保存 JSONArray数据 到 缓存中 * * @param key 保存的key * @param value 保存的JSONArray数据 */ public void put(String key, JSONArray value) { put(key, value.toString()); } /** * 保存 JSONArray数据 到 缓存中 * * @param key 保存的key * @param value 保存的JSONArray数据 * @param saveTime 保存的时间,单位:秒 */ public void put(String key, JSONArray value, int saveTime) { put(key, value.toString(), saveTime); } /** * 读取JSONArray数据 * * @param key * @return JSONArray数据 */ public JSONArray getAsJSONArray(String key) { String jsonstring = getAsString(key); try { JSONArray obj = new JSONArray(jsonstring); return obj; } catch (Exception e) { //e.printStackTrace(); return null; } } // ======================================= // ============== byte 数据 读写 ============= // ======================================= /** * 保存 byte数据 到 缓存中 * * @param key 保存的key * @param value 保存的数据 */ public void put(String key, byte[] value) { File file = mCache.newFile(key); FileOutputStream out = null; try { out = new FileOutputStream(file); out.write(value); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } mCache.put(file); } } /** * Cache for a stream * * @param key the file name. * @return OutputStream stream for writing data. * @throws FileNotFoundException if the file can not be created. */ public OutputStream put(String key) throws FileNotFoundException { return new xFileOutputStream(mCache.newFile(key)); } /** * @param key the file name. * @return (InputStream or null) stream previously saved in cache. * @throws FileNotFoundException if the file can not be opened */ public InputStream get(String key) throws FileNotFoundException { File file = mCache.get(key); if (!file.exists()) return null; return new FileInputStream(file); } /** * 保存 byte数据 到 缓存中 * * @param key 保存的key * @param value 保存的数据 * @param saveTime 保存的时间,单位:秒 */ public void put(String key, byte[] value, int saveTime) { put(key, Utils.newByteArrayWithDateInfo(saveTime, value)); } /** * 获取 byte 数据 * * @param key * @return byte 数据 */ public byte[] getAsBinary(String key) { RandomAccessFile raFile = null; boolean removeFile = false; try { File file = mCache.get(key); if (!file.exists()) return null; raFile = new RandomAccessFile(file, "r"); byte[] byteArray = new byte[(int) raFile.length()]; raFile.read(byteArray); if (!Utils.isDue(byteArray)) { return Utils.clearDateInfo(byteArray); } else { removeFile = true; return null; } } catch (Exception e) { e.printStackTrace(); return null; } finally { if (raFile != null) { try { raFile.close(); } catch (IOException e) { e.printStackTrace(); } } if (removeFile) remove(key); } } // ======================================= // ============= 序列化 数据 读写 =============== // ======================================= /** * 保存 Serializable数据 到 缓存中 * * @param key 保存的key * @param value 保存的value */ public void put(String key, Serializable value) { put(key, value, -1); } /** * 保存 Serializable数据到 缓存中 * * @param key 保存的key * @param value 保存的value * @param saveTime 保存的时间,单位:秒 */ public void put(String key, Serializable value, int saveTime) { ByteArrayOutputStream baos; ObjectOutputStream oos = null; try { baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(value); byte[] data = baos.toByteArray(); if (saveTime != -1) { put(key, data, saveTime); } else { put(key, data); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (oos != null) { oos.close(); } } catch (IOException ignored) { } } } /** * 读取 Serializable数据 * * @param key * @return Serializable 数据 */ public Object getAsObject(String key) { byte[] data = getAsBinary(key); if (data != null) { ByteArrayInputStream bais = null; ObjectInputStream ois = null; try { bais = new ByteArrayInputStream(data); ois = new ObjectInputStream(bais); Object reObject = ois.readObject(); return reObject; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { if (bais != null) bais.close(); } catch (IOException e) { e.printStackTrace(); } try { if (ois != null) ois.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } // ======================================= // ============== bitmap 数据 读写 ============= // ======================================= /** * 保存 bitmap 到 缓存中 * * @param key 保存的key * @param value 保存的bitmap数据 */ public void put(String key, Bitmap value) { put(key, Utils.bitmap2Bytes(value)); } /** * 保存 bitmap 到 缓存中 * * @param key 保存的key * @param value 保存的 bitmap 数据 * @param saveTime 保存的时间,单位:秒 */ public void put(String key, Bitmap value, int saveTime) { put(key, Utils.bitmap2Bytes(value), saveTime); } /** * 读取 bitmap 数据 * * @param key * @return bitmap 数据 */ public Bitmap getAsBitmap(String key) { if (getAsBinary(key) == null) { return null; } return Utils.bytes2Bimap(getAsBinary(key)); } // ======================================= // ============= drawable 数据 读写 ============= // ======================================= /** * 保存 drawable 到 缓存中 * * @param key 保存的key * @param value 保存的drawable数据 */ public void put(String key, Drawable value) { put(key, Utils.drawable2Bitmap(value)); } /** * 保存 drawable 到 缓存中 * * @param key 保存的key * @param value 保存的 drawable 数据 * @param saveTime 保存的时间,单位:秒 */ public void put(String key, Drawable value, int saveTime) { put(key, Utils.drawable2Bitmap(value), saveTime); } /** * 读取 Drawable 数据 * * @param key * @return Drawable 数据 */ public Drawable getAsDrawable(String key) { if (getAsBinary(key) == null) { return null; } return Utils.bitmap2Drawable(Utils.bytes2Bimap(getAsBinary(key))); } /** * 获取缓存文件 * * @param key * @return value 缓存的文件 */ public File file(String key) { File f = mCache.newFile(key); if (f.exists()) return f; return null; } /** * 移除某个key * * @param key * @return 是否移除成功 */ public boolean remove(String key) { return mCache.remove(key); } /** * 清除所有数据 */ public void clear() { mCache.clear(); } /** * @author 杨福海(michael) www.yangfuhai.com * @version 1.0 * @title 缓存管理器 */ public class ACacheManager { private final AtomicLong cacheSize; private final AtomicInteger cacheCount; private final long sizeLimit; private final int countLimit; private final Map<File, Long> lastUsageDates = Collections.synchronizedMap(new HashMap<File, Long>()); protected File cacheDir; private ACacheManager(File cacheDir, long sizeLimit, int countLimit) { this.cacheDir = cacheDir; this.sizeLimit = sizeLimit; this.countLimit = countLimit; cacheSize = new AtomicLong(); cacheCount = new AtomicInteger(); calculateCacheSizeAndCacheCount(); } /** * 计算 cacheSize和cacheCount */ private void calculateCacheSizeAndCacheCount() { new Thread(new Runnable() { @Override public void run() { int size = 0; int count = 0; File[] cachedFiles = cacheDir.listFiles(); if (cachedFiles != null) { for (File cachedFile : cachedFiles) { size += calculateSize(cachedFile); count += 1; lastUsageDates.put(cachedFile, cachedFile.lastModified()); } cacheSize.set(size); cacheCount.set(count); } } }).start(); } private void put(File file) { int curCacheCount = cacheCount.get(); while (curCacheCount + 1 > countLimit) { long freedSize = removeNext(); cacheSize.addAndGet(-freedSize); curCacheCount = cacheCount.addAndGet(-1); } cacheCount.addAndGet(1); long valueSize = calculateSize(file); long curCacheSize = cacheSize.get(); while (curCacheSize + valueSize > sizeLimit) { long freedSize = removeNext(); curCacheSize = cacheSize.addAndGet(-freedSize); } cacheSize.addAndGet(valueSize); Long currentTime = System.currentTimeMillis(); file.setLastModified(currentTime); lastUsageDates.put(file, currentTime); } private File get(String key) { File file = newFile(key); Long currentTime = System.currentTimeMillis(); file.setLastModified(currentTime); lastUsageDates.put(file, currentTime); return file; } private File newFile(String key) { return new File(cacheDir, key.hashCode() + ""); } private boolean remove(String key) { File image = get(key); return image.delete(); } private void clear() { lastUsageDates.clear(); cacheSize.set(0); File[] files = cacheDir.listFiles(); if (files != null) { for (File f : files) { f.delete(); } } } /** * 移除旧的文件 * * @return */ private long removeNext() { if (lastUsageDates.isEmpty()) { return 0; } Long oldestUsage = null; File mostLongUsedFile = null; Set<Entry<File, Long>> entries = lastUsageDates.entrySet(); synchronized (lastUsageDates) { for (Entry<File, Long> entry : entries) { if (mostLongUsedFile == null) { mostLongUsedFile = entry.getKey(); oldestUsage = entry.getValue(); } else { Long lastValueUsage = entry.getValue(); if (lastValueUsage < oldestUsage) { oldestUsage = lastValueUsage; mostLongUsedFile = entry.getKey(); } } } } long fileSize = calculateSize(mostLongUsedFile); assert mostLongUsedFile != null; if (mostLongUsedFile.delete()) { lastUsageDates.remove(mostLongUsedFile); } return fileSize; } private long calculateSize(File file) { return file.length(); } } /** * @author 杨福海(michael) www.yangfuhai.com * @version 1.0 * @title 时间计算工具类 */ private static class Utils { /** * 判断缓存的String数据是否到期 * * @param str * @return true:到期了 false:还没有到期 */ private static boolean isDue(String str) { return isDue(str.getBytes()); } /** * 判断缓存的byte数据是否到期 * * @param data * @return true:到期了 false:还没有到期 */ private static boolean isDue(byte[] data) { String[] strs = getDateInfoFromDate(data); if (strs != null && strs.length == 2) { String saveTimeStr = strs[0]; while (saveTimeStr.startsWith("0")) { saveTimeStr = saveTimeStr.substring(1, saveTimeStr.length()); } long saveTime = Long.parseLong(saveTimeStr); long deleteAfter = Long.parseLong(strs[1]); if (System.currentTimeMillis() > saveTime + deleteAfter * 1000) { return true; } } return false; } private static String newStringWithDateInfo(int second, String strInfo) { return createDateInfo(second) + strInfo; } private static byte[] newByteArrayWithDateInfo(int second, byte[] data2) { byte[] data1 = createDateInfo(second).getBytes(); byte[] retdata = new byte[data1.length + data2.length]; System.arraycopy(data1, 0, retdata, 0, data1.length); System.arraycopy(data2, 0, retdata, data1.length, data2.length); return retdata; } private static String clearDateInfo(String strInfo) { if (strInfo != null && hasDateInfo(strInfo.getBytes())) { strInfo = strInfo.substring(strInfo.indexOf(mSeparator) + 1, strInfo.length()); } return strInfo; } private static byte[] clearDateInfo(byte[] data) { if (hasDateInfo(data)) { return copyOfRange(data, indexOf(data, mSeparator) + 1, data.length); } return data; } private static boolean hasDateInfo(byte[] data) { return data != null && data.length > 15 && data[13] == '-' && indexOf(data, mSeparator) > 14; } private static String[] getDateInfoFromDate(byte[] data) { if (hasDateInfo(data)) { String saveDate = new String(copyOfRange(data, 0, 13)); String deleteAfter = new String(copyOfRange(data, 14, indexOf(data, mSeparator))); return new String[]{saveDate, deleteAfter}; } return null; } private static int indexOf(byte[] data, char c) { for (int i = 0; i < data.length; i++) { if (data[i] == c) { return i; } } return -1; } private static byte[] copyOfRange(byte[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); byte[] copy = new byte[newLength]; System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; } private static final char mSeparator = ' '; private static String createDateInfo(int second) { String currentTime = Long.toString(System.currentTimeMillis()); while (currentTime.length() < 13) { currentTime = "0" + currentTime; } return currentTime + "-" + second + mSeparator; } /* * Bitmap → byte[] */ private static byte[] bitmap2Bytes(Bitmap bm) { if (bm == null) { return null; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); } /* * byte[] → Bitmap */ private static Bitmap bytes2Bimap(byte[] b) { if (b.length == 0) { return null; } return BitmapFactory.decodeByteArray(b, 0, b.length); } /* * Drawable → Bitmap */ private static Bitmap drawable2Bitmap(Drawable drawable) { if (drawable == null) { return null; } // 取 drawable 的长宽 int w = drawable.getIntrinsicWidth(); int h = drawable.getIntrinsicHeight(); // 取 drawable 的颜色格式 Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config .ARGB_8888 : Bitmap.Config.RGB_565; // 建立对应 bitmap Bitmap bitmap = Bitmap.createBitmap(w, h, config); // 建立对应 bitmap 的画布 Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, w, h); // 把 drawable 内容画到画布中 drawable.draw(canvas); return bitmap; } /* * Bitmap → Drawable */ @SuppressWarnings("deprecation") private static Drawable bitmap2Drawable(Bitmap bm) { if (bm == null) { return null; } BitmapDrawable bd = new BitmapDrawable(bm); bd.setTargetDensity(bm.getDensity()); return new BitmapDrawable(bm); } } }
{ "content_hash": "03879abe529981dcfc0ec2a3756f05a5", "timestamp": "", "source": "github", "line_count": 953, "max_line_length": 99, "avg_line_length": 29.426023084994753, "alnum_prop": 0.49944727739542844, "repo_name": "dgrlucky/Awesome", "id": "e2c5d878e2a3af81f5fd0930feb79268d58dd219", "size": "29061", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/dgrlucky/extend/config/ACache.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1709" }, { "name": "Java", "bytes": "2366511" }, { "name": "Kotlin", "bytes": "23462" } ], "symlink_target": "" }
/*************************************************************************/ /* editor_export_platform.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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. */ /*************************************************************************/ #ifndef EDITOR_EXPORT_PLATFORM_H #define EDITOR_EXPORT_PLATFORM_H class EditorFileSystemDirectory; struct EditorProgress; #include "core/io/dir_access.h" #include "editor_export_preset.h" #include "editor_export_shared_object.h" #include "scene/gui/rich_text_label.h" #include "scene/main/node.h" class EditorExportPlugin; class EditorExportPlatform : public RefCounted { GDCLASS(EditorExportPlatform, RefCounted); public: typedef Error (*EditorExportSaveFunction)(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key); typedef Error (*EditorExportSaveSharedObject)(void *p_userdata, const SharedObject &p_so); enum ExportMessageType { EXPORT_MESSAGE_NONE, EXPORT_MESSAGE_INFO, EXPORT_MESSAGE_WARNING, EXPORT_MESSAGE_ERROR, }; struct ExportMessage { ExportMessageType msg_type; String category; String text; }; private: struct SavedData { uint64_t ofs = 0; uint64_t size = 0; bool encrypted = false; Vector<uint8_t> md5; CharString path_utf8; bool operator<(const SavedData &p_data) const { return path_utf8 < p_data.path_utf8; } }; struct PackData { Ref<FileAccess> f; Vector<SavedData> file_ofs; EditorProgress *ep = nullptr; Vector<SharedObject> *so_files = nullptr; }; struct ZipData { void *zip = nullptr; EditorProgress *ep = nullptr; }; Vector<ExportMessage> messages; void _export_find_resources(EditorFileSystemDirectory *p_dir, HashSet<String> &p_paths); void _export_find_dependencies(const String &p_path, HashSet<String> &p_paths); void gen_debug_flags(Vector<String> &r_flags, int p_flags); static Error _save_pack_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key); static Error _save_zip_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key); void _edit_files_with_filter(Ref<DirAccess> &da, const Vector<String> &p_filters, HashSet<String> &r_list, bool exclude); void _edit_filter_list(HashSet<String> &r_list, const String &p_filter, bool exclude); static Error _add_shared_object(void *p_userdata, const SharedObject &p_so); struct FileExportCache { uint64_t source_modified_time = 0; String source_md5; String saved_path; bool used = false; }; bool _export_customize_dictionary(Dictionary &dict, LocalVector<Ref<EditorExportPlugin>> &customize_resources_plugins); bool _export_customize_array(Array &array, LocalVector<Ref<EditorExportPlugin>> &customize_resources_plugins); bool _export_customize_object(Object *p_object, LocalVector<Ref<EditorExportPlugin>> &customize_resources_plugins); bool _export_customize_scene_resources(Node *p_root, Node *p_node, LocalVector<Ref<EditorExportPlugin>> &customize_resources_plugins); String _export_customize(const String &p_path, LocalVector<Ref<EditorExportPlugin>> &customize_resources_plugins, LocalVector<Ref<EditorExportPlugin>> &customize_scenes_plugins, HashMap<String, FileExportCache> &export_cache, const String &export_base_path, bool p_force_save); protected: struct ExportNotifier { ExportNotifier(EditorExportPlatform &p_platform, const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags); ~ExportNotifier(); }; HashSet<String> get_features(const Ref<EditorExportPreset> &p_preset, bool p_debug) const; bool exists_export_template(String template_file_name, String *err) const; String find_export_template(String template_file_name, String *err = nullptr) const; void gen_export_flags(Vector<String> &r_flags, int p_flags); public: virtual void get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) const = 0; struct ExportOption { PropertyInfo option; Variant default_value; bool update_visibility = false; ExportOption(const PropertyInfo &p_info, const Variant &p_default, bool p_update_visibility = false) : option(p_info), default_value(p_default), update_visibility(p_update_visibility) { } ExportOption() {} }; virtual Ref<EditorExportPreset> create_preset(); virtual void clear_messages() { messages.clear(); } virtual void add_message(ExportMessageType p_type, const String &p_category, const String &p_message) { ExportMessage msg; msg.category = p_category; msg.text = p_message; msg.msg_type = p_type; messages.push_back(msg); switch (p_type) { case EXPORT_MESSAGE_INFO: { print_line(vformat("%s: %s", msg.category, msg.text)); } break; case EXPORT_MESSAGE_WARNING: { WARN_PRINT(vformat("%s: %s", msg.category, msg.text)); } break; case EXPORT_MESSAGE_ERROR: { ERR_PRINT(vformat("%s: %s", msg.category, msg.text)); } break; default: break; } } virtual int get_message_count() const { return messages.size(); } virtual ExportMessage get_message(int p_index) const { ERR_FAIL_INDEX_V(p_index, messages.size(), ExportMessage()); return messages[p_index]; } virtual ExportMessageType get_worst_message_type() const { ExportMessageType worst_type = EXPORT_MESSAGE_NONE; for (int i = 0; i < messages.size(); i++) { worst_type = MAX(worst_type, messages[i].msg_type); } return worst_type; } virtual bool fill_log_messages(RichTextLabel *p_log, Error p_err); virtual void get_export_options(List<ExportOption> *r_options) = 0; virtual bool should_update_export_options() { return false; } virtual bool get_export_option_visibility(const EditorExportPreset *p_preset, const String &p_option, const HashMap<StringName, Variant> &p_options) const { return true; } virtual String get_os_name() const = 0; virtual String get_name() const = 0; virtual Ref<Texture2D> get_logo() const = 0; Error export_project_files(const Ref<EditorExportPreset> &p_preset, bool p_debug, EditorExportSaveFunction p_func, void *p_udata, EditorExportSaveSharedObject p_so_func = nullptr); Error save_pack(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, Vector<SharedObject> *p_so_files = nullptr, bool p_embed = false, int64_t *r_embedded_start = nullptr, int64_t *r_embedded_size = nullptr); Error save_zip(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path); virtual bool poll_export() { return false; } virtual int get_options_count() const { return 0; } virtual String get_options_tooltip() const { return ""; } virtual Ref<ImageTexture> get_option_icon(int p_index) const; virtual String get_option_label(int p_device) const { return ""; } virtual String get_option_tooltip(int p_device) const { return ""; } enum DebugFlags { DEBUG_FLAG_DUMB_CLIENT = 1, DEBUG_FLAG_REMOTE_DEBUG = 2, DEBUG_FLAG_REMOTE_DEBUG_LOCALHOST = 4, DEBUG_FLAG_VIEW_COLLISONS = 8, DEBUG_FLAG_VIEW_NAVIGATION = 16, }; virtual Error run(const Ref<EditorExportPreset> &p_preset, int p_device, int p_debug_flags) { return OK; } virtual Ref<Texture2D> get_run_icon() const { return get_logo(); } String test_etc2() const; bool can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const; virtual bool has_valid_export_configuration(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const = 0; virtual bool has_valid_project_configuration(const Ref<EditorExportPreset> &p_preset, String &r_error) const = 0; virtual List<String> get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const = 0; virtual Error export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags = 0) = 0; virtual Error export_pack(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags = 0); virtual Error export_zip(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags = 0); virtual void get_platform_features(List<String> *r_features) const = 0; virtual void resolve_platform_feature_priorities(const Ref<EditorExportPreset> &p_preset, HashSet<String> &p_features) = 0; virtual String get_debug_protocol() const { return "tcp://"; } EditorExportPlatform(); }; #endif // EDITOR_EXPORT_PLATFORM_H
{ "content_hash": "b23b2b9afff172e986235c77a84776bb", "timestamp": "", "source": "github", "line_count": 236, "max_line_length": 278, "avg_line_length": 45.21186440677966, "alnum_prop": 0.6760074976569822, "repo_name": "Shockblast/godot", "id": "93bc54284f3307e932704c8faac6b4583a98e7e4", "size": "10670", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "editor/export/editor_export_platform.h", "mode": "33188", "license": "mit", "language": [ { "name": "AIDL", "bytes": "1633" }, { "name": "C", "bytes": "1045182" }, { "name": "C#", "bytes": "1603520" }, { "name": "C++", "bytes": "39294736" }, { "name": "CMake", "bytes": "606" }, { "name": "GAP", "bytes": "62" }, { "name": "GDScript", "bytes": "66163" }, { "name": "GLSL", "bytes": "831699" }, { "name": "Java", "bytes": "596117" }, { "name": "JavaScript", "bytes": "188470" }, { "name": "Kotlin", "bytes": "93069" }, { "name": "Makefile", "bytes": "1421" }, { "name": "Objective-C", "bytes": "20550" }, { "name": "Objective-C++", "bytes": "390808" }, { "name": "PowerShell", "bytes": "2713" }, { "name": "Python", "bytes": "463987" }, { "name": "Shell", "bytes": "32416" } ], "symlink_target": "" }
<?php namespace common\models; use Yii; use \common\models\base\AttributeValue as BaseAttributeValue; /** * This is the model class for table "attribute_value". */ class AttributeValue extends BaseAttributeValue { public $attribute_value; /** * @inheritdoc */ public function attributeLabels() { return array_merge([ 'attribute_value' => Yii::t('gip', 'Value'), ], parent::attributeLabels()); } public function getListOfValues() { if($ea = $this->getEntityAttribute()->one()) { if($at = $ea->getAttributeType()->one()) { if($lv = $at->getListOfValues()->one()) { return $lv->getValues(); } } } return null; } }
{ "content_hash": "6624fd09f91e6e040fab89e8e7bb20dc", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 61, "avg_line_length": 19.62162162162162, "alnum_prop": 0.5840220385674931, "repo_name": "devleaks/gip", "id": "f7c32bd03f57e1d6c25421f6b02b25987ca5e663", "size": "726", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/models/AttributeValue.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "515" }, { "name": "CSS", "bytes": "528038" }, { "name": "HTML", "bytes": "37956" }, { "name": "JavaScript", "bytes": "1189305" }, { "name": "PHP", "bytes": "1169698" }, { "name": "Shell", "bytes": "218" } ], "symlink_target": "" }
using System.Collections.Generic; namespace BrightWire.TabularData.Helper { /// <summary> /// Classifies data table column types /// </summary> static class ColumnTypeClassifier { static readonly HashSet<ColumnType> _continuousType = new HashSet<ColumnType> { ColumnType.Date, ColumnType.Double, ColumnType.Float, ColumnType.Int, ColumnType.Long, ColumnType.Byte, }; static readonly HashSet<ColumnType> _categoricalType = new HashSet<ColumnType> { ColumnType.Boolean, ColumnType.String, }; static readonly HashSet<ColumnType> _numericType = new HashSet<ColumnType> { ColumnType.Boolean, ColumnType.Date, ColumnType.Double, ColumnType.Float, ColumnType.Int, ColumnType.Long, ColumnType.Byte }; public static bool IsNumeric(IColumn column) { return _numericType.Contains(column.Type); } public static bool IsContinuous(IColumn column) { return _continuousType.Contains(column.Type); } public static bool IsCategorical(IColumn column) { return _categoricalType.Contains(column.Type); } } }
{ "content_hash": "495f44a450b72f57a9ffcf3c843e9c23", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 88, "avg_line_length": 30, "alnum_prop": 0.5837037037037037, "repo_name": "jdermody/brightwire", "id": "1bb827c8e7a0759c8caff10d8028626a34c9e6bc", "size": "1352", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BrightWire/TabularData/Helper/ColumnTypeClassifier.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1167" }, { "name": "C#", "bytes": "6787987" }, { "name": "Cuda", "bytes": "32424" } ], "symlink_target": "" }
.class public Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpReceiver; .super Landroid/content/BroadcastReceiver; .source "BluetoothAvrcpReceiver.java" # static fields .field public static final TAG:Ljava/lang/String; = "AVRCP" .field public static sAvrcpServer:Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpService; # instance fields .field private mNativeData:I # direct methods .method static constructor <clinit>()V .locals 1 .prologue .line 48 const/4 v0, 0x0 sput-object v0, Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpReceiver;->sAvrcpServer:Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpService; return-void .end method .method public constructor <init>()V .locals 0 .prologue .line 45 invoke-direct {p0}, Landroid/content/BroadcastReceiver;-><init>()V return-void .end method # virtual methods .method public destroyMyself(Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpService;)V .locals 2 .parameter "server" .prologue .line 115 sget-object v0, Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpReceiver;->sAvrcpServer:Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpService; if-ne p1, v0, :cond_0 .line 116 const-string v0, "AVRCP" const-string v1, "destroyMyself" invoke-static {v0, v1}, Landroid/util/Log;->v(Ljava/lang/String;Ljava/lang/String;)I .line 118 :cond_0 return-void .end method .method public initalConnect(Ljava/lang/String;)V .locals 2 .parameter "sAddr" .prologue .line 121 sget-object v0, Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpReceiver;->sAvrcpServer:Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpService; if-eqz v0, :cond_0 .line 122 const-string v0, "AVRCP" const-string v1, "AVRCP initConnect connectReqNative used!" invoke-static {v0, v1}, Landroid/util/Log;->v(Ljava/lang/String;Ljava/lang/String;)I .line 123 sget-object v0, Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpReceiver;->sAvrcpServer:Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpService; invoke-virtual {v0, p1}, Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpService;->connectReqNative(Ljava/lang/String;)Z .line 127 :goto_0 return-void .line 125 :cond_0 const-string v0, "AVRCP" const-string v1, "AVRCP initConnect fail !!! no mAvrcpServer" invoke-static {v0, v1}, Landroid/util/Log;->v(Ljava/lang/String;Ljava/lang/String;)I goto :goto_0 .end method .method public onReceive(Landroid/content/Context;Landroid/content/Intent;)V .locals 10 .parameter "context" .parameter "intent" .prologue const/4 v9, 0x3 const/4 v8, 0x0 .line 56 invoke-virtual {p2}, Landroid/content/Intent;->getAction()Ljava/lang/String; move-result-object v0 .line 58 .local v0, action:Ljava/lang/String; const-string v5, "[BT][AVRCP] onReceive " invoke-virtual {v5, v0}, Ljava/lang/String;->concat(Ljava/lang/String;)Ljava/lang/String; move-result-object v4 .line 60 .local v4, textMessage:Ljava/lang/String; const-string v5, "AVRCP" invoke-static {v5, v4}, Landroid/util/Log;->v(Ljava/lang/String;Ljava/lang/String;)I .line 62 const-string v5, "android.bluetooth.adapter.action.STATE_CHANGED" invoke-virtual {v0, v5}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z move-result v5 if-eqz v5, :cond_1 .line 63 const/4 v3, 0x0 .line 64 .local v3, state:I const-string v5, "android.bluetooth.adapter.extra.STATE" const/high16 v6, -0x8000 invoke-virtual {p2, v5, v6}, Landroid/content/Intent;->getIntExtra(Ljava/lang/String;I)I move-result v3 .line 65 const/16 v5, 0xc if-eq v5, v3, :cond_0 const/16 v5, 0xa if-ne v5, v3, :cond_1 .line 67 :cond_0 new-instance v2, Landroid/content/Intent; invoke-direct {v2}, Landroid/content/Intent;-><init>()V .line 68 .local v2, in:Landroid/content/Intent; invoke-virtual {v2, p2}, Landroid/content/Intent;->putExtras(Landroid/content/Intent;)Landroid/content/Intent; .line 69 const-class v5, Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpService; invoke-virtual {v2, p1, v5}, Landroid/content/Intent;->setClass(Landroid/content/Context;Ljava/lang/Class;)Landroid/content/Intent; .line 70 const-string v5, "action" invoke-virtual {v2, v5, v0}, Landroid/content/Intent;->putExtra(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent; .line 72 invoke-virtual {p1, v2}, Landroid/content/Context;->startService(Landroid/content/Intent;)Landroid/content/ComponentName; .line 76 .end local v2 #in:Landroid/content/Intent; .end local v3 #state:I :cond_1 const-string v5, "android.provider.Telephony.SECRET_CODE" invoke-virtual {v0, v5}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z move-result v5 if-eqz v5, :cond_3 .line 77 invoke-virtual {p2}, Landroid/content/Intent;->getDataString()Ljava/lang/String; move-result-object v1 .line 78 .local v1, data:Ljava/lang/String; const-string v5, "AVRCP" new-instance v6, Ljava/lang/StringBuilder; invoke-direct {v6}, Ljava/lang/StringBuilder;-><init>()V const-string v7, "[BT][AVRCP] Get the securty code (" invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v6 invoke-virtual {v0}, Ljava/lang/String;->toString()Ljava/lang/String; move-result-object v7 invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v6 const-string v7, ")" invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v6 invoke-virtual {v6}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v6 invoke-static {v5, v6}, Landroid/util/Log;->v(Ljava/lang/String;Ljava/lang/String;)I .line 79 if-eqz v1, :cond_2 .line 80 const-string v5, "AVRCP" new-instance v6, Ljava/lang/StringBuilder; invoke-direct {v6}, Ljava/lang/StringBuilder;-><init>()V const-string v7, "[BT][AVRCP] Get the securty code data: (" invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v6 invoke-virtual {v6, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v6 const-string v7, ")" invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v6 invoke-virtual {v6}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v6 invoke-static {v5, v6}, Landroid/util/Log;->v(Ljava/lang/String;Ljava/lang/String;)I .line 83 :cond_2 const-string v4, "AVRCP PTS enable mode (Source:Telephone)" .line 84 if-eqz v1, :cond_7 const-string v5, "2872710" invoke-virtual {v1, v5}, Ljava/lang/String;->indexOf(Ljava/lang/String;)I move-result v5 const/4 v6, -0x1 if-eq v5, v6, :cond_7 .line 85 const-string v5, "00:00:00:00:00:00" invoke-virtual {p0, v5}, Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpReceiver;->initalConnect(Ljava/lang/String;)V .line 86 const-string v4, "AVRCP PTS connect mode (Source:Telephone)" .line 90 :goto_0 invoke-static {p1, v4, v8}, Landroid/widget/Toast;->makeText(Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast; move-result-object v5 invoke-virtual {v5}, Landroid/widget/Toast;->show()V .line 92 .end local v1 #data:Ljava/lang/String; :cond_3 const-string v5, "android.mediatek.bluetooth.avrcp.pts" invoke-virtual {v0, v5}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z move-result v5 if-eqz v5, :cond_4 .line 93 const-string v5, "AVRCP" const-string v6, "Get the avrcp.pts code" invoke-static {v5, v6}, Landroid/util/Log;->v(Ljava/lang/String;Ljava/lang/String;)I .line 94 sput v9, Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpService;->sPTSDebugMode:I .line 95 const-string v4, "AVRCP PTS enable mode (Source:pts action)" .line 96 invoke-static {p1, v4, v8}, Landroid/widget/Toast;->makeText(Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast; move-result-object v5 invoke-virtual {v5}, Landroid/widget/Toast;->show()V .line 98 :cond_4 const-string v5, "android.mediatek.bluetooth.avrcp.connect" invoke-virtual {v0, v5}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z move-result v5 if-eqz v5, :cond_5 .line 99 const-string v5, "AVRCP" const-string v6, "Get the avrcp.connect code" invoke-static {v5, v6}, Landroid/util/Log;->v(Ljava/lang/String;Ljava/lang/String;)I .line 100 const-string v4, "AVRCP PTS connect (Source: action)" .line 101 invoke-static {p1, v4, v8}, Landroid/widget/Toast;->makeText(Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast; move-result-object v5 invoke-virtual {v5}, Landroid/widget/Toast;->show()V .line 102 const-string v5, "00:00:00:00:00:00" invoke-virtual {p0, v5}, Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpReceiver;->initalConnect(Ljava/lang/String;)V .line 104 :cond_5 const-string v5, "android.mediatek.bluetooth.avrcp.disconnect" invoke-virtual {v0, v5}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z move-result v5 if-eqz v5, :cond_6 .line 105 const-string v5, "AVRCP" const-string v6, "Get the avrcp.disconnect code" invoke-static {v5, v6}, Landroid/util/Log;->v(Ljava/lang/String;Ljava/lang/String;)I .line 106 sget-object v5, Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpReceiver;->sAvrcpServer:Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpService; if-eqz v5, :cond_6 .line 107 const-string v4, "AVRCP PTS disconnect (Source: action)" .line 108 invoke-static {p1, v4, v8}, Landroid/widget/Toast;->makeText(Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast; move-result-object v5 invoke-virtual {v5}, Landroid/widget/Toast;->show()V .line 109 sget-object v5, Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpReceiver;->sAvrcpServer:Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpService; invoke-virtual {v5}, Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpService;->disconnectNative()Z .line 112 :cond_6 return-void .line 88 .restart local v1 #data:Ljava/lang/String; :cond_7 sput v9, Lcom/mediatek/bluetooth/avrcp/BluetoothAvrcpService;->sPTSDebugMode:I goto :goto_0 .end method
{ "content_hash": "b3e10ad5867b81226651ada02ee0d72a", "timestamp": "", "source": "github", "line_count": 409, "max_line_length": 140, "avg_line_length": 26.52567237163814, "alnum_prop": 0.6941653608627524, "repo_name": "baidurom/devices-g520", "id": "ef69c86a41f17200db4875445d8508bac7c02427", "size": "10849", "binary": false, "copies": "1", "ref": "refs/heads/coron-4.1", "path": "MtkBt/smali/com/mediatek/bluetooth/avrcp/BluetoothAvrcpReceiver.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "12575" }, { "name": "Python", "bytes": "1261" }, { "name": "Shell", "bytes": "2159" } ], "symlink_target": "" }
class EAsset < ActiveRecord::Base validates :tag_id, presence: true, uniqueness: true, length: {is: 8} def self.latest EAsset.order(:updated_at).last end end
{ "content_hash": "93c97fdc1e90f3acbcd55d8c27e18042", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 69, "avg_line_length": 20.625, "alnum_prop": 0.7212121212121212, "repo_name": "chapmanderek/Asset_Manager", "id": "816876ee9cca4f01e8c2e8e6de40277c9ae6e466", "size": "165", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/e_asset.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3297" }, { "name": "CoffeeScript", "bytes": "633" }, { "name": "HTML", "bytes": "11495" }, { "name": "JavaScript", "bytes": "638" }, { "name": "Ruby", "bytes": "30561" }, { "name": "Shell", "bytes": "159" } ], "symlink_target": "" }
package servicedefinition import ( "github.com/zenoss/glog" "encoding/json" "fmt" "io/ioutil" "os" "path/filepath" "strings" ) func getServiceDefinition(path string) (serviceDef *ServiceDefinition, err error) { // is path a dir fi, err := os.Stat(path) if err != nil { return nil, err } if !fi.IsDir() { return nil, fmt.Errorf("given path is not a directory") } // look for service.json serviceFile := fmt.Sprintf("%s/service.json", path) blob, err := ioutil.ReadFile(serviceFile) if err != nil { return nil, err } // load blob svc := ServiceDefinition{} err = json.Unmarshal(blob, &svc) if err != nil { glog.Errorf("Could not unmarshal service at %s", path) return nil, err } //Launch isn't usually in a file but it is required, this sets it to a default value if not set svc.NormalizeLaunch() svc.Name = filepath.Base(path) if svc.ConfigFiles == nil { svc.ConfigFiles = make(map[string]ConfigFile) } // look at sub services subServices := make(map[string]*ServiceDefinition) subpaths, err := ioutil.ReadDir(path) if err != nil { return nil, err } for _, subpath := range subpaths { switch { case subpath.Name() == "service.json": continue case subpath.Name() == "makefile": // ignoring makefiles present in service defs continue case subpath.Name() == "-CONFIGS-": if !subpath.IsDir() { return nil, fmt.Errorf("-CONFIGS- must be a director: %s", path) } getFiles := func(p string, f os.FileInfo, err error) error { if f.IsDir() { return nil } buffer, err := ioutil.ReadFile(p) if err != nil { return err } path, err := filepath.Rel(filepath.Join(path, subpath.Name()), p) if err != nil { return err } path = "/" + path if _, ok := svc.ConfigFiles[path]; !ok { svc.ConfigFiles[path] = ConfigFile{ Filename: path, Content: string(buffer), } } else { configFile := svc.ConfigFiles[path] configFile.Content = string(buffer) svc.ConfigFiles[path] = configFile } return nil } err = filepath.Walk(path+"/"+subpath.Name(), getFiles) if err != nil { return nil, err } case subpath.Name() == "FILTERS": if !subpath.IsDir() { return nil, fmt.Errorf(path + "/-FILTERS- must be a directory.") } filters, err := getFiltersFromDirectory(path + "/" + subpath.Name()) if err != nil { glog.Errorf("Error fetching filters at "+path, err) } else { svc.LogFilters = filters } case subpath.IsDir(): subsvc, err := getServiceDefinition(path + "/" + subpath.Name()) if err != nil { return nil, err } subServices[subpath.Name()] = subsvc default: glog.V(4).Infof("Unrecognized file %s at %s", subpath.Name(), path) } } svc.Services = make([]ServiceDefinition, len(subServices)) i := 0 for _, subsvc := range subServices { svc.Services[i] = *subsvc i++ } return &svc, err } // this function takes a filter directory and creates a map // of filters by looking at the content in that directory. // it is assumed the filter name is the name of the file minus // the .conf part. So test.conf would be a filter named "test" func getFiltersFromDirectory(path string) (filters map[string]string, err error) { filters = make(map[string]string) subpaths, err := ioutil.ReadDir(path) if err != nil { return nil, err } for _, subpath := range subpaths { filterName := subpath.Name() // make sure it is a valid filter if !strings.HasSuffix(filterName, ".conf") { glog.Warning("Skipping %s because it doesn't have a .conf extension", filterName) continue } // read the contents and add it to our map contents, err := ioutil.ReadFile(path + "/" + filterName) if err != nil { glog.Errorf("Unable to read the file %s, skipping", path+"/"+filterName) continue } filterName = strings.TrimSuffix(filterName, ".conf") filters[filterName] = string(contents) } glog.V(2).Infof("Here are the filters %v from path %s", filters, path) return filters, nil }
{ "content_hash": "219b4feb1bebe755388370b16e4e7c90", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 96, "avg_line_length": 26.993288590604028, "alnum_prop": 0.6489308801591248, "repo_name": "spindance/serviced-precomp", "id": "e886e52bd0227cb34d5cf421d41b6ac7725585c4", "size": "4618", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "domain/servicedefinition/utils.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "7462" }, { "name": "CSS", "bytes": "225064" }, { "name": "Cucumber", "bytes": "50746" }, { "name": "Go", "bytes": "3043363" }, { "name": "HTML", "bytes": "1470612" }, { "name": "Java", "bytes": "1884" }, { "name": "JavaScript", "bytes": "2938807" }, { "name": "Makefile", "bytes": "31068" }, { "name": "Python", "bytes": "61874" }, { "name": "Ruby", "bytes": "57584" }, { "name": "Shell", "bytes": "53783" } ], "symlink_target": "" }
<!DOCTYPE html> <meta charset=utf-8> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>BarcodeDetector Polyfill Example</title> </head> <body> <div id="container"> <input id="Take-Picture" type="file" accept="image/*;capture=camera" /><br/> <canvas width="320" height="240" id="picture"></canvas> <p id="textbit"></p> </div> <script type="text/javascript"> (function () { function loadScript(src, done) { var $script = document.createElement('script'); $script.src = src; $script.onload = function() { done(); }; $script.onerror = function() { done(new Error('Failed to load script ' + src)); }; document.head.appendChild($script); } if ('BarcodeDetector' in window) { startTheApp(); } else { console.log('Loading polyfill'); loadScript( "../BarcodeDetector.min.js", startTheApp ); } })() function startTheApp() { var takePicture = document.querySelector("#Take-Picture"), showPicture = document.createElement("img"); Result = document.querySelector("#textbit"); var canvas =document.getElementById("picture"); var ctx = canvas.getContext("2d"); var barcodeDetector = new BarcodeDetector(); function handleResults (result) { if (result.length > 0){ ctx.beginPath(); ctx.lineWIdth = "2"; ctx.strokeStyle="red"; var tempArray = []; for (var i = 0; i < result.length; i++) { tempArray.push(result[i].rawValue); ctx.rect( result[i].boundingBox.x, result[i].boundingBox.y, result[i].boundingBox.width, result[i].boundingBox.height ); } Result.innerHTML = tempArray.join("<br />"); ctx.stroke(); } else { if(result.length === 0) { Result.innerHTML = "Decoding failed."; } } } if (takePicture && showPicture) { takePicture.onchange = function (event) { var files = event.target.files; if (files && files.length > 0) { file = files[0]; try { var URL = window.URL || window.webkitURL; showPicture.onload = function(event) { Result.innerHTML=""; // JOB.DecodeImage(showPicture); ctx.drawImage(showPicture, 0, 0, canvas.width, canvas.height); barcodeDetector.detect(showPicture).then(handleResults) URL.revokeObjectURL(showPicture.src); }; showPicture.src = URL.createObjectURL(file); } catch (e) { try { var fileReader = new FileReader(); fileReader.onload = function (event) { showPicture.onload = function(event) { Result.innerHTML=""; ctx.drawImage(showPicture, 0, 0, canvas.width, canvas.height); // JOB.DecodeImage(showPicture); barcodeDetector.detect(showPicture).then(handleResults) }; showPicture.src = event.target.result; }; fileReader.readAsDataURL(file); } catch (e) { Result.innerHTML = "Neither createObjectURL or FileReader are supported"; } } } }; } } </script> </body> </html>
{ "content_hash": "c3019ce6b7f8b9b6a7e93d303130d4d9", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 91, "avg_line_length": 34.580357142857146, "alnum_prop": 0.4892847921507875, "repo_name": "giladaya/barcode-detector-polyfill", "id": "9abd3710929ebb676d5b352e4b5bb726c483d486", "size": "3873", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/single/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "74686" } ], "symlink_target": "" }
package org.springframework.aop.support; import java.io.IOException; import org.junit.Before; import org.junit.Test; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; import static org.junit.Assert.*; /** * @author Rod Johnson * @author Dmitriy Kopylenko * @author Chris Beams */ public abstract class AbstractRegexpMethodPointcutTests { private AbstractRegexpMethodPointcut rpc; @Before public void setUp() { rpc = getRegexpMethodPointcut(); } protected abstract AbstractRegexpMethodPointcut getRegexpMethodPointcut(); @Test public void testNoPatternSupplied() throws Exception { noPatternSuppliedTests(rpc); } @Test public void testSerializationWithNoPatternSupplied() throws Exception { rpc = (AbstractRegexpMethodPointcut) SerializationTestUtils.serializeAndDeserialize(rpc); noPatternSuppliedTests(rpc); } protected void noPatternSuppliedTests(AbstractRegexpMethodPointcut rpc) throws Exception { assertFalse(rpc.matches(Object.class.getMethod("hashCode"), String.class)); assertFalse(rpc.matches(Object.class.getMethod("wait"), Object.class)); assertEquals(0, rpc.getPatterns().length); } @Test public void testExactMatch() throws Exception { rpc.setPattern("java.lang.Object.hashCode"); exactMatchTests(rpc); rpc = (AbstractRegexpMethodPointcut) SerializationTestUtils.serializeAndDeserialize(rpc); exactMatchTests(rpc); } protected void exactMatchTests(AbstractRegexpMethodPointcut rpc) throws Exception { // assumes rpc.setPattern("java.lang.Object.hashCode"); assertTrue(rpc.matches(Object.class.getMethod("hashCode"), String.class)); assertTrue(rpc.matches(Object.class.getMethod("hashCode"), Object.class)); assertFalse(rpc.matches(Object.class.getMethod("wait"), Object.class)); } @Test public void testSpecificMatch() throws Exception { rpc.setPattern("java.lang.String.hashCode"); assertTrue(rpc.matches(Object.class.getMethod("hashCode"), String.class)); assertFalse(rpc.matches(Object.class.getMethod("hashCode"), Object.class)); } @Test public void testWildcard() throws Exception { rpc.setPattern(".*Object.hashCode"); assertTrue(rpc.matches(Object.class.getMethod("hashCode"), Object.class)); assertFalse(rpc.matches(Object.class.getMethod("wait"), Object.class)); } @Test public void testWildcardForOneClass() throws Exception { rpc.setPattern("java.lang.Object.*"); assertTrue(rpc.matches(Object.class.getMethod("hashCode"), String.class)); assertTrue(rpc.matches(Object.class.getMethod("wait"), String.class)); } @Test public void testMatchesObjectClass() throws Exception { rpc.setPattern("java.lang.Object.*"); assertTrue(rpc.matches(Exception.class.getMethod("hashCode"), IOException.class)); // Doesn't match a method from Throwable assertFalse(rpc.matches(Exception.class.getMethod("getMessage"), Exception.class)); } @Test public void testWithExclusion() throws Exception { this.rpc.setPattern(".*get.*"); this.rpc.setExcludedPattern(".*Age.*"); assertTrue(this.rpc.matches(TestBean.class.getMethod("getName"), TestBean.class)); assertFalse(this.rpc.matches(TestBean.class.getMethod("getAge"), TestBean.class)); } }
{ "content_hash": "e80a266c3eefa3f1faa53218bb96c52b", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 91, "avg_line_length": 32.29, "alnum_prop": 0.769278414369774, "repo_name": "shivpun/spring-framework", "id": "39cbed336eaf322027bafecf3a66afc1f77fae9e", "size": "3849", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spring-aop/src/test/java/org/springframework/aop/support/AbstractRegexpMethodPointcutTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GAP", "bytes": "6137" }, { "name": "Groovy", "bytes": "3685" }, { "name": "HTML", "bytes": "713" }, { "name": "Java", "bytes": "9777605" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" href="../assets/img/icon.ico"> <link rel="stylesheet" href="https://use.fontawesome.com/0fee7aa685.css" media="all"> <!-- Eden Stylesheet--> <link href="../css/eden.css" rel="stylesheet"> <title>Responsive Media by Eden.</title> <link href="../css/style.css" rel="stylesheet"> </head> <body> <div id="responsive-media-pg" class="universe"> <div id="responsive-media"> <div class="container"> <h1 class="text-center">Responsive Media by Eden.</h1> <div class="responsive-media"><iframe src="https://www.youtube.com/embed/O2mtwscNBOc" frameborder="0" allowfullscreen></iframe></div> <div class="responsive-media"><iframe src="https://player.vimeo.com/video/191710919" width="100%" height="360" frameborder="0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe></div> </div> </div> </div> <script src="../js/jquery.js"></script> <script src="../js/eden.js"></script> <script src="../js/function.js"></script> </body> </html>
{ "content_hash": "add4f7443bd9cfd92f754746e1029e19", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 218, "avg_line_length": 45.714285714285715, "alnum_prop": 0.63515625, "repo_name": "aaronconway7/Eden", "id": "5fa8db5df0447922f630eac2eab4c28aa268ec7e", "size": "1280", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/components/responsive-media.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "103741" }, { "name": "HTML", "bytes": "101272" }, { "name": "JavaScript", "bytes": "35161" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace Lighthouse.Web.Models { public class CreateAnnotationModel { [Required] [Display(Name = "Panel")] public string Panel { get; set; } [Required] [Display(Name = "Deidentified Case ID")] public string CaseId { get; set; } [Required] [Display(Name = "VCF File")] public HttpPostedFileBase VcfFile { get; set; } } }
{ "content_hash": "1bc6cd71580199a4e7a8d2cc25bc53fc", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 55, "avg_line_length": 25.434782608695652, "alnum_prop": 0.6495726495726496, "repo_name": "wadeschulz/lighthouse", "id": "4ea80a5340c45ee1dd15e54d7184766391be743a", "size": "587", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Lighthouse.Web/Models/AnnotationModels.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "105" }, { "name": "C#", "bytes": "131089" }, { "name": "CSS", "bytes": "12927" }, { "name": "HTML", "bytes": "5127" }, { "name": "JavaScript", "bytes": "285729" } ], "symlink_target": "" }
Configuration: ================= Your configuration drives the usage of link. You need to create your configuration in your home directory (~/.link/link.config):: mkdir ~/.link vi ~/.link/link.config Everything that is in your configuration can be treated like an object which will be explained later. For now, Here is an example JSON config:: { "apis": { "my_api": { "wrapper": "APIRequestWrapper", "base_url": "http://123fakestreet.net", "user": "<user>", "password": "<password>" }, "my_api_2": { "wrapper": "APIRequestWrapper", "base_url": "http://123fakestreet.net", "user": "<user>", "password": "<password>" }, }, "dbs":{ "my_db": { "wrapper": "MysqlDB", "host": "mysql-master.123fakestreet.net", "password": "<password>", "user": "<user>", "database": "<database_name>" } } } You can organize your configuration anyway you would like, using any names you wish. For example, you could create an environment centric structure like this:: { "prod": { "my_api":..., "my_db":...}, "sand": { "my_api":..., "my_db":...} } You can also nest resources as deep as you would like:: { "prod": { "dbs":{ "my_db":... }, "apis":{ "my_api":... } }, "sand": { "dbs":{ "my_db":... }, "apis":{ "my_api":... } } } The only rule is that names cannot have a "." in them, you will see why below. Create a structure that fits your usecase, by environment, by client (if you are a consultant)...etc.
{ "content_hash": "9498efe9eb8e87962f963cb0a023b4ee", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 81, "avg_line_length": 25.97222222222222, "alnum_prop": 0.47593582887700536, "repo_name": "dhrod5/link", "id": "8718e7927740c5900a6b72afbb043f76378587fd", "size": "1870", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/configuration.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "163150" }, { "name": "Vim script", "bytes": "883" } ], "symlink_target": "" }
package com.example.yuyu.slideactivity.demo; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import com.example.yuyu.slideactivity.R; import java.util.ArrayList; import java.util.List; /** * Created by yuyu on 2015/10/29. */ public class TestActivity extends AppCompatActivity { View mRootView; private GestureDetector mGestureDetector; private static List<TestActivity> mActivitys = new ArrayList<>(); /** * 移动距离 */ private float mWindowWidth; private TestActivity mBeforeActivity; /** * 上一个Activity偏移量 */ private float mOffsetX; /** * 上一个页面移出的位置 */ private float mOutsideWidth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_demo); /** * 把当前Activity加到列表里面 */ mActivitys.add(this); initScrollBack(); } /** * 初始化左滑退出功能 */ private void initScrollBack() { mWindowWidth = getWindowManager().getDefaultDisplay().getWidth(); mOutsideWidth = -mWindowWidth / 4; mOffsetX = mOutsideWidth; mGestureDetector = new GestureDetector(this, new GestureListener()); mRootView = getWindow().getDecorView(); mRootView.setBackgroundColor(Color.BLUE); } /** * 控制分发事件 */ @Override public boolean dispatchTouchEvent(@NonNull MotionEvent ev) { if (ev.getX() < mWindowWidth / 10) { if (mActivitys.size() > 1) { mBeforeActivity = mActivitys.get(mActivitys.size() - 2); beforeActivityTranslationX(mOutsideWidth); } return onTouchEvent(ev); } return super.dispatchTouchEvent(ev); } @Override public void finish() { mActivitys.remove(this); if (mOffsetX < 0.0001 || mOffsetX > 0.0001) { beforeActivityTranslationX(0); } super.finish(); } public void onClick(View view) { Intent intent = new Intent(this, Activity5.class); startActivity(intent); } public View getRootView() { return mRootView; } /** * 控制上一个Activity移动 */ private void beforeActivityTranslationX(float translationX) { if (mBeforeActivity != null) { mBeforeActivity.getRootView().setTranslationX(translationX); } } @Override public boolean onTouchEvent(MotionEvent event) { return mGestureDetector.onTouchEvent(event); } /** * 手势监听 */ private class GestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (e1 != null) { handlerCurrentActivityScroll(e2); handleBeforeActivityScroll(e2, distanceX); } return super.onScroll(e1, e2, distanceX, distanceY); } /** * 处理当前页面滑动 */ private void handlerCurrentActivityScroll(MotionEvent e2) { mRootView.setTranslationX(e2.getX()); if (e2.getX() > mWindowWidth - 20) { finish(); } } /** * 处理上一个页面滑动 */ private void handleBeforeActivityScroll(MotionEvent e2, float distanceX) { if (mBeforeActivity != null) { mOffsetX = distanceX < 0 ? mOffsetX + Math.abs(distanceX) / 4 : mOffsetX - Math.abs(distanceX) / 4; if (mOffsetX > 0.0001) { mOffsetX = 0f; } mBeforeActivity.getRootView().setTranslationX(mOffsetX); } } } }
{ "content_hash": "dc673d298bb8cef174f4f8ac4435c705", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 115, "avg_line_length": 27.67361111111111, "alnum_prop": 0.6012547051442911, "repo_name": "AriaLyy/BlogDemo", "id": "f2006536454fffd1fe7292fbcde565484f1290b1", "size": "4129", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SlidingActivityDemo/app/src/main/java/com/example/yuyu/slideactivity/demo/TestActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "247" }, { "name": "C++", "bytes": "2896" }, { "name": "CMake", "bytes": "1671" }, { "name": "Java", "bytes": "327161" }, { "name": "JavaScript", "bytes": "3227" } ], "symlink_target": "" }
/** * Created by mr470 on 04.04.2016. */ import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router' import styles from './menu.scss'; class MenuItem extends Component{ static PropTypes = { id: PropTypes.number.isRequired, name: PropTypes.string.isRequired, setActiveMenu: PropTypes.func.isRequired }; onItemClick(e){ this.props.setActiveMenu(this.props.id, e); } render(){ const { id, name } = this.props; return ( // see https://github.com/reactjs/redux/tree/master/examples/real-world <Link className={`${styles.item}`} to={`/${id}`} onClick={this.onItemClick.bind(this)} activeClassName={styles.itemActive}>{name}</Link> ); } } export { MenuItem } export default MenuItem;
{ "content_hash": "c6273bb8df82259308d06c35dfd1e231", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 148, "avg_line_length": 27.677419354838708, "alnum_prop": 0.6282051282051282, "repo_name": "mr47/react-redux-kit", "id": "77b5400c433213224ec99920d908f7d58b01963c", "size": "858", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/menu/item.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1398" }, { "name": "HTML", "bytes": "686" }, { "name": "JavaScript", "bytes": "114119" } ], "symlink_target": "" }
namespace Redola.Rpc { public class MethodArgumentEncoder : IMethodArgumentEncoder { private IObjectEncoder _encoder; public MethodArgumentEncoder(IObjectEncoder encoder) { _encoder = encoder; } public byte[] Encode(object argument) { return _encoder.Encode(argument); } public byte[] Encode<T>(T argument) { return _encoder.Encode(argument); } } }
{ "content_hash": "ad907349f4d021233fca25bdf21ded15", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 63, "avg_line_length": 21.863636363636363, "alnum_prop": 0.5654885654885655, "repo_name": "gaochundong/Redola", "id": "b1f26d26932963e52134253eedbdebc5e75296df", "size": "483", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Redola/Redola.Rpc/Rpc/Method/Argument/Encoding/MethodArgumentEncoder.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "420640" } ], "symlink_target": "" }
package com.amazonaws.services.identitymanagement.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UntagSAMLProvider" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UntagSAMLProviderRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The ARN of the SAML identity provider in IAM from which you want to remove tags. * </p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of * characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of * the following characters: _+=,.@- * </p> */ private String sAMLProviderArn; /** * <p> * A list of key names as a simple array of strings. The tags with matching keys are removed from the specified SAML * identity provider. * </p> */ private com.amazonaws.internal.SdkInternalList<String> tagKeys; /** * <p> * The ARN of the SAML identity provider in IAM from which you want to remove tags. * </p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of * characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of * the following characters: _+=,.@- * </p> * * @param sAMLProviderArn * The ARN of the SAML identity provider in IAM from which you want to remove tags.</p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string * of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also * include any of the following characters: _+=,.@- */ public void setSAMLProviderArn(String sAMLProviderArn) { this.sAMLProviderArn = sAMLProviderArn; } /** * <p> * The ARN of the SAML identity provider in IAM from which you want to remove tags. * </p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of * characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of * the following characters: _+=,.@- * </p> * * @return The ARN of the SAML identity provider in IAM from which you want to remove tags.</p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string * of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also * include any of the following characters: _+=,.@- */ public String getSAMLProviderArn() { return this.sAMLProviderArn; } /** * <p> * The ARN of the SAML identity provider in IAM from which you want to remove tags. * </p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of * characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of * the following characters: _+=,.@- * </p> * * @param sAMLProviderArn * The ARN of the SAML identity provider in IAM from which you want to remove tags.</p> * <p> * This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string * of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also * include any of the following characters: _+=,.@- * @return Returns a reference to this object so that method calls can be chained together. */ public UntagSAMLProviderRequest withSAMLProviderArn(String sAMLProviderArn) { setSAMLProviderArn(sAMLProviderArn); return this; } /** * <p> * A list of key names as a simple array of strings. The tags with matching keys are removed from the specified SAML * identity provider. * </p> * * @return A list of key names as a simple array of strings. The tags with matching keys are removed from the * specified SAML identity provider. */ public java.util.List<String> getTagKeys() { if (tagKeys == null) { tagKeys = new com.amazonaws.internal.SdkInternalList<String>(); } return tagKeys; } /** * <p> * A list of key names as a simple array of strings. The tags with matching keys are removed from the specified SAML * identity provider. * </p> * * @param tagKeys * A list of key names as a simple array of strings. The tags with matching keys are removed from the * specified SAML identity provider. */ public void setTagKeys(java.util.Collection<String> tagKeys) { if (tagKeys == null) { this.tagKeys = null; return; } this.tagKeys = new com.amazonaws.internal.SdkInternalList<String>(tagKeys); } /** * <p> * A list of key names as a simple array of strings. The tags with matching keys are removed from the specified SAML * identity provider. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setTagKeys(java.util.Collection)} or {@link #withTagKeys(java.util.Collection)} if you want to override * the existing values. * </p> * * @param tagKeys * A list of key names as a simple array of strings. The tags with matching keys are removed from the * specified SAML identity provider. * @return Returns a reference to this object so that method calls can be chained together. */ public UntagSAMLProviderRequest withTagKeys(String... tagKeys) { if (this.tagKeys == null) { setTagKeys(new com.amazonaws.internal.SdkInternalList<String>(tagKeys.length)); } for (String ele : tagKeys) { this.tagKeys.add(ele); } return this; } /** * <p> * A list of key names as a simple array of strings. The tags with matching keys are removed from the specified SAML * identity provider. * </p> * * @param tagKeys * A list of key names as a simple array of strings. The tags with matching keys are removed from the * specified SAML identity provider. * @return Returns a reference to this object so that method calls can be chained together. */ public UntagSAMLProviderRequest withTagKeys(java.util.Collection<String> tagKeys) { setTagKeys(tagKeys); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getSAMLProviderArn() != null) sb.append("SAMLProviderArn: ").append(getSAMLProviderArn()).append(","); if (getTagKeys() != null) sb.append("TagKeys: ").append(getTagKeys()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof UntagSAMLProviderRequest == false) return false; UntagSAMLProviderRequest other = (UntagSAMLProviderRequest) obj; if (other.getSAMLProviderArn() == null ^ this.getSAMLProviderArn() == null) return false; if (other.getSAMLProviderArn() != null && other.getSAMLProviderArn().equals(this.getSAMLProviderArn()) == false) return false; if (other.getTagKeys() == null ^ this.getTagKeys() == null) return false; if (other.getTagKeys() != null && other.getTagKeys().equals(this.getTagKeys()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getSAMLProviderArn() == null) ? 0 : getSAMLProviderArn().hashCode()); hashCode = prime * hashCode + ((getTagKeys() == null) ? 0 : getTagKeys().hashCode()); return hashCode; } @Override public UntagSAMLProviderRequest clone() { return (UntagSAMLProviderRequest) super.clone(); } }
{ "content_hash": "7a5579a93665d94a609e3c0c141fee9a", "timestamp": "", "source": "github", "line_count": 240, "max_line_length": 120, "avg_line_length": 37.97083333333333, "alnum_prop": 0.6288818171842423, "repo_name": "aws/aws-sdk-java", "id": "d5b82eab24622048daf5052075034017dac2d546", "size": "9693", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-iam/src/main/java/com/amazonaws/services/identitymanagement/model/UntagSAMLProviderRequest.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php // Check for empty fields if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } $name = $_POST['name']; $email_address = $_POST['email']; $phone = $_POST['phone']; $message = $_POST['message']; // Create the email and send the message $to = 'brian@mcshiz.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to. $email_subject = "Website Contact Form: $name"; $email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message"; $headers = "From: noreply@mcshiz.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com. $headers .= "Reply-To: $email_address"; mail($to,$email_subject,$email_body,$headers); return true; ?>
{ "content_hash": "0098696429ec889c6ec2637ea966f3f9", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 187, "avg_line_length": 41.76923076923077, "alnum_prop": 0.6721915285451197, "repo_name": "mcshiz/portfolio-v2", "id": "5cd0a2f107d07edb40034eeaacc41150f9b3990f", "size": "1086", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mail/contact_me.php", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "144575" }, { "name": "HTML", "bytes": "16149" }, { "name": "JavaScript", "bytes": "42528" }, { "name": "PHP", "bytes": "1086" } ], "symlink_target": "" }
&{$Branch='dev';iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.ps1'))} # load up the global.json so we can find the DNX version $globalJson = Get-Content -Path $PSScriptRoot\global.json -Raw -ErrorAction Ignore | ConvertFrom-Json -ErrorAction Ignore if($globalJson) { $dnxVersion = $globalJson.sdk.version } else { Write-Warning "Unable to locate global.json to determine using 'latest'" $dnxVersion = "latest" } # install DNX # only installs the default (x86, clr) runtime of the framework. # If you need additional architectures or runtimes you should add additional calls # ex: & $env:USERPROFILE\.dnx\bin\dnvm install $dnxVersion -r coreclr & $env:USERPROFILE\.dnx\bin\dnvm install $dnxVersion -Persistent npm install -g jspm # run DNU restore on all project.json files in the src folder including 2>1 to redirect stderr to stdout for badly behaved tools Get-ChildItem -Path $PSScriptRoot\Source -Filter project.json -Recurse | ForEach-Object { & dnu restore $_.FullName 2>1 }
{ "content_hash": "554dd3813dd32a6ea9de1dde4eea7d64", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 133, "avg_line_length": 42.44, "alnum_prop": 0.7558906691800189, "repo_name": "msdevno/ChristmasDemo", "id": "0393feb4175d7f96df1a12e992d7831ba2b26ea5", "size": "1097", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Prebuild.ps1", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "3264" }, { "name": "CSS", "bytes": "60" }, { "name": "HTML", "bytes": "1798" }, { "name": "JavaScript", "bytes": "214418" }, { "name": "PowerShell", "bytes": "2047" } ], "symlink_target": "" }
// // AdstirConfig.h // AdstirAds // // Copyright (c) 2015 UNITED, Inc. All rights reserved. // #import <Foundation/Foundation.h> @interface AdstirConfig : NSObject /** Turn SSL mode on / off SSLモードの有効/無効を切り替えます @param enabled */ + (void)setSSLModeEnabled:(BOOL)enabled; /** Get SSL mode status デバッグモードの状態を取得します */ + (BOOL)SSLModeEnabled; /** Turn debug mode on / off デバッグモードの有効/無効を切り替えます @param enabled */ + (void)setDebugModeEnabled:(BOOL)enabled; /** Get debug mode status デバッグモードの状態を取得します */ + (BOOL)debugModeEnabled; @end
{ "content_hash": "03d2ca1586d17b1a5a30dd38877e8063", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 56, "avg_line_length": 13.875, "alnum_prop": 0.6954954954954955, "repo_name": "Fig-leaves/curation", "id": "3078cdf7addd6de1b4edf8a9559260663a3d279b", "size": "687", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AdstirAds.framework/Versions/A/Headers/AdstirConfig.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "17652" }, { "name": "Ruby", "bytes": "100" }, { "name": "Swift", "bytes": "116951" } ], "symlink_target": "" }
package de.fu_berlin.agdb.importer.payload; import org.json.JSONObject; import java.sql.Date; public class LocationWeatherData { private LocationMetaData locationMetaData; private Long timestamp; private DataType dataType; private Date date; private Double windChill; private Double windDirection; private Double windSpeed; private Double atmosphereHumidity; private Double atmospherePressure; private Double atmosphereRising; private Double atmosphereVisibility; private String astronomySunrise; private String astronomySunset; private Double temperature; private Double temperatureHigh; private Double temperatureLow; private Integer qualityLevel; private Double steamPressure; private Double cloudage; private Double minimumAirGroundTemperature; private Double maximumWindSpeed; private Double precipitationDepth; private Double sunshineDuration; private Double snowHeight; public LocationWeatherData(LocationMetaData locationMetaData, long timestamp, DataType dataType) { this.locationMetaData = locationMetaData; this.timestamp = timestamp; this.dataType = dataType; } public LocationMetaData getLocationMetaData(){ return locationMetaData; } public Long getTimestamp() { return timestamp; } public DataType getDataType() { return dataType; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Double getWindChill() { return windChill; } public void setWindChill(Double windChill) { this.windChill = windChill; } public Double getWindDirection() { return windDirection; } public void setWindDirection(Double windDirection) { this.windDirection = windDirection; } public Double getWindSpeed() { return windSpeed; } public void setWindSpeed(Double windSpeed) { this.windSpeed = windSpeed; } public Double getAtmosphereHumidity() { return atmosphereHumidity; } public void setAtmosphereHumidity(Double atmosphereHumidity) { this.atmosphereHumidity = atmosphereHumidity; } public Double getAtmospherePressure() { return atmospherePressure; } public void setAtmospherePressure(Double atmospherePressure) { this.atmospherePressure = atmospherePressure; } public Double getAtmosphereRising() { return atmosphereRising; } public void setAtmosphereRising(Double atmosphereRising) { this.atmosphereRising = atmosphereRising; } public Double getAtmosphereVisibility() { return atmosphereVisibility; } public void setAtmosphereVisibility(Double atmosphereVisibility) { this.atmosphereVisibility = atmosphereVisibility; } public String getAstronomySunrise() { return astronomySunrise; } public void setAstronomySunrise(String astronomySunrise) { this.astronomySunrise = astronomySunrise; } public String getAstronomySunset() { return astronomySunset; } public void setAstronomySunset(String astronomySunset) { this.astronomySunset = astronomySunset; } public Double getTemperature() { return temperature; } public void setTemperature(Double temperature) { this.temperature = temperature; } public Double getTemperatureHigh() { return temperatureHigh; } public void setTemperatureHigh(Double temperatureHigh) { this.temperatureHigh = temperatureHigh; } public Double getTemperatureLow() { return temperatureLow; } public void setTemperatureLow(Double temperatureLow) { this.temperatureLow = temperatureLow; } public Integer getQualityLevel() { return qualityLevel; } public void setQualityLevel(Integer qualityLevel) { this.qualityLevel = qualityLevel; } public Double getSteamPressure() { return steamPressure; } public void setSteamPressure(Double steamPressure) { this.steamPressure = steamPressure; } public Double getCloudage() { return cloudage; } public void setCloudage(Double cloudage) { this.cloudage = cloudage; } public Double getMinimumAirGroundTemperature() { return minimumAirGroundTemperature; } public void setMinimumAirGroundTemperature(Double minimumAirGroundTemperature) { this.minimumAirGroundTemperature = minimumAirGroundTemperature; } public Double getMaximumWindSpeed() { return maximumWindSpeed; } public void setMaximumWindSpeed(Double maximumWindSpeed) { this.maximumWindSpeed = maximumWindSpeed; } public Double getPrecipitationDepth() { return precipitationDepth; } public void setPrecipitationDepth(Double precipitationDepth) { this.precipitationDepth = precipitationDepth; } public Double getSunshineDuration() { return sunshineDuration; } public void setSunshineDuration(Double sunshineDuration) { this.sunshineDuration = sunshineDuration; } public Double getSnowHeight() { return snowHeight; } public void setSnowHeight(Double snowHeight) { this.snowHeight = snowHeight; } public JSONObject asJSONObject() { JSONObject currentEvent = new JSONObject(); currentEvent.put("timestamp", timestamp); currentEvent.put("stationMetaData", locationMetaData.asJSONObject()); currentEvent.put("dataType", dataType); currentEvent.put("date", date); currentEvent.put("windChill", windChill); currentEvent.put("windDirection", windDirection); currentEvent.put("windSpeed", windSpeed); currentEvent.put("atmosphereHumidity", atmosphereHumidity); currentEvent.put("atmospherePressure", atmospherePressure); currentEvent.put("atmosphereRising", atmosphereRising); currentEvent.put("atmosphereVisibility", atmosphereVisibility); currentEvent.put("astronomySunrise", astronomySunrise); currentEvent.put("astronomySunset", astronomySunset); currentEvent.put("temperature", temperature); currentEvent.put("temperatureHigh", temperatureHigh); currentEvent.put("temperatureLow", temperatureLow); currentEvent.put("qualityLevel", qualityLevel); currentEvent.put("steamPressure", steamPressure); currentEvent.put("cloudage", cloudage); currentEvent.put("minimumAirGroundTemperature", minimumAirGroundTemperature); currentEvent.put("maximumWindSpeed", maximumWindSpeed); currentEvent.put("precipitationDepth", precipitationDepth); currentEvent.put("sunshineDuration", sunshineDuration); currentEvent.put("snowHeight", snowHeight); return currentEvent; } }
{ "content_hash": "eb04fadd78d68adb47fa129deef6e4fa", "timestamp": "", "source": "github", "line_count": 256, "max_line_length": 99, "avg_line_length": 24.4609375, "alnum_prop": 0.7801022037687639, "repo_name": "CEPFU/importer", "id": "e092d2aa067185eeb018f4e4593844b57c0a7450", "size": "6262", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/de/fu_berlin/agdb/importer/payload/LocationWeatherData.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "62781" } ], "symlink_target": "" }
package executor import ( "k8s.io/kubernetes/contrib/mesos/pkg/node" "k8s.io/kubernetes/pkg/api" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_2" ) type kubeAPI interface { killPod(ns, name string) error } type nodeAPI interface { createOrUpdate(hostname string, slaveAttrLabels, annotations map[string]string) (*api.Node, error) } // clientAPIWrapper implements kubeAPI and node API, which serve to isolate external dependencies // such that they're easier to mock in unit test. type clientAPIWrapper struct { client *clientset.Clientset } func (cw *clientAPIWrapper) killPod(ns, name string) error { return cw.client.Legacy().Pods(ns).Delete(name, api.NewDeleteOptions(0)) } func (cw *clientAPIWrapper) createOrUpdate(hostname string, slaveAttrLabels, annotations map[string]string) (*api.Node, error) { return node.CreateOrUpdate(cw.client, hostname, slaveAttrLabels, annotations) }
{ "content_hash": "5f5b9d4f65685b9a26bbf9a505919610", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 128, "avg_line_length": 29.870967741935484, "alnum_prop": 0.7775377969762419, "repo_name": "dcbw/kubernetes", "id": "ae98fd6f7f5c93d7844f7bd832f5671ee05ae657", "size": "1515", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "contrib/mesos/pkg/executor/apis.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "18484218" }, { "name": "HTML", "bytes": "1193991" }, { "name": "Makefile", "bytes": "46385" }, { "name": "Nginx", "bytes": "1013" }, { "name": "Python", "bytes": "68276" }, { "name": "SaltStack", "bytes": "44807" }, { "name": "Shell", "bytes": "1163008" } ], "symlink_target": "" }
This is the base image for all docker-in-docker images. The difference between this and the official `docker` images are that this will choose the best filesystem automatically. The official ones use `vfs` (bad) by default unless you pass in a flag. It will also attempt to mirror the default external interface's MTU to the dind network; this addresses a problem with running dind-based images on a kubernetes cluster with an overlay network that takes a chunk out of pods' MTUs. ## Usage Just use this as your base image and use CMD for your program, **NOT ENTRYPOINT**. This will handle the rest. ```Dockerfile FROM fnproject/dind # OTHER STUFF CMD ["./myproggie"] ```
{ "content_hash": "7a49d43e1eb811fabae4ada7a71433ff", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 109, "avg_line_length": 37.611111111111114, "alnum_prop": 0.7710487444608567, "repo_name": "fnproject/fn", "id": "94f6e40c9e9a697008eff73c0996be58d693e126", "size": "708", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "images/dind/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "3760" }, { "name": "Go", "bytes": "979933" }, { "name": "Makefile", "bytes": "4164" }, { "name": "PowerShell", "bytes": "1012" }, { "name": "Ruby", "bytes": "5879" }, { "name": "Shell", "bytes": "11982" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="org.camunda.bpm.engine.impl.history.event.HistoricExternalTaskLogEntity"> <!-- INSERT --> <insert id="insertHistoricExternalTaskLog" parameterType="org.camunda.bpm.engine.impl.history.event.HistoricExternalTaskLogEntity"> insert into ${prefix}ACT_HI_EXT_TASK_LOG ( ID_, TIMESTAMP_, EXT_TASK_ID_, RETRIES_, TOPIC_NAME_, WORKER_ID_, PRIORITY_, ERROR_MSG_, ERROR_DETAILS_ID_, ACT_ID_, ACT_INST_ID_, EXECUTION_ID_, PROC_INST_ID_, PROC_DEF_ID_, PROC_DEF_KEY_, TENANT_ID_, STATE_ ) values (#{id, jdbcType=VARCHAR}, #{timestamp, jdbcType=TIMESTAMP}, #{externalTaskId, jdbcType=VARCHAR}, #{retries, jdbcType=INTEGER}, #{topicName, jdbcType=VARCHAR}, #{workerId, jdbcType=VARCHAR}, #{priority, jdbcType=BIGINT}, #{errorMessage, jdbcType=VARCHAR}, #{errorDetailsByteArrayId, jdbcType=VARCHAR}, #{activityId, jdbcType=VARCHAR}, #{activityInstanceId, jdbcType=VARCHAR}, #{executionId, jdbcType=VARCHAR}, #{processInstanceId, jdbcType=VARCHAR}, #{processDefinitionId, jdbcType=VARCHAR}, #{processDefinitionKey, jdbcType=VARCHAR}, #{tenantId, jdbcType=VARCHAR}, #{state, jdbcType=INTEGER} ) </insert> <!-- DELETE --> <delete id="deleteHistoricExternalTaskLogByProcessInstanceId"> delete from ${prefix}ACT_HI_EXT_TASK_LOG where PROC_INST_ID_ = #{processInstanceId} </delete> <delete id="deleteHistoricExternalTaskLogByProcessInstanceIds"> delete from ${prefix}ACT_HI_EXT_TASK_LOG where PROC_INST_ID_ IN <foreach item="processInstanceId" index="index" collection="list" open="(" separator="," close=")"> #{processInstanceId} </foreach> </delete> <!-- BYTE ARRAY DELETE --> <delete id="deleteErrorDetailsByteArraysByIds"> delete from ${prefix}ACT_GE_BYTEARRAY <where> ID_ in (<include refid="selectErrorDetailsByteArrayIds"/>) </where> </delete> <!-- RESULT MAP --> <resultMap id="historicExternalTaskLogMap" type="org.camunda.bpm.engine.impl.history.event.HistoricExternalTaskLogEntity"> <id property="id" column="ID_" jdbcType="VARCHAR" /> <result property="timestamp" column="TIMESTAMP_" jdbcType="TIMESTAMP" /> <result property="externalTaskId" column="EXT_TASK_ID_" jdbcType="VARCHAR" /> <result property="retries" column="RETRIES_" jdbcType="INTEGER" /> <result property="topicName" column="TOPIC_NAME_" jdbcType="VARCHAR" /> <result property="workerId" column="WORKER_ID_" jdbcType="VARCHAR" /> <result property="priority" column="PRIORITY_" jdbcType="BIGINT" /> <result property="errorMessage" column="ERROR_MSG_" jdbcType="VARCHAR" /> <result property="errorDetailsByteArrayId" column="ERROR_DETAILS_ID_" jdbcType="VARCHAR" /> <result property="activityId" column="ACT_ID_" jdbcType="VARCHAR" /> <result property="activityInstanceId" column="ACT_INST_ID_" jdbcType="VARCHAR" /> <result property="executionId" column="EXECUTION_ID_" jdbcType="VARCHAR" /> <result property="processInstanceId" column="PROC_INST_ID_" jdbcType="VARCHAR" /> <result property="processDefinitionId" column="PROC_DEF_ID_" jdbcType="VARCHAR" /> <result property="processDefinitionKey" column="PROC_DEF_KEY_" jdbcType="VARCHAR" /> <result property="tenantId" column="TENANT_ID_" jdbcType="VARCHAR" /> <result property="state" column="STATE_" jdbcType="VARCHAR" /> </resultMap> <!-- SELECT --> <sql id="selectErrorDetailsByteArrayIds"> select ERROR_DETAILS_ID_ from ${prefix}ACT_HI_EXT_TASK_LOG <where> ERROR_DETAILS_ID_ is not null <if test="id != null"> and ID_ = #{id, jdbcType=VARCHAR} </if> <if test="externalTaskId != null"> and RES.EXT_TASK_ID_ = #{externalTaskId, jdbcType=VARCHAR} </if> <if test="topicName != null"> and RES.TOPIC_NAME_ = #{topicName, jdbcType=VARCHAR} </if> <if test="workerId != null"> and RES.WORKER_ID_ = #{workerId, jdbcType=VARCHAR} </if> <if test="executionId != null"> and EXECUTION_ID_ = #{executionId, jdbcType=VARCHAR} </if> <if test="processInstanceId != null"> and PROC_INST_ID_ = #{processInstanceId, jdbcType=VARCHAR} </if> <if test="processInstanceIdIn != null &amp;&amp; processInstanceIdIn.length > 0"> and PROC_INST_ID_ in <foreach item="item" index="index" collection="processInstanceIdIn" open="(" separator="," close=")"> #{item} </foreach> </if> <if test="processDefinitionId != null"> and PROC_DEF_ID_ = #{processDefinitionId, jdbcType=VARCHAR} </if> <if test="processDefinitionKey != null"> and PROC_DEF_KEY_ = #{processDefinitionKey, jdbcType=VARCHAR} </if> </where> </sql> <select id="selectHistoricExternalTaskLog" resultMap="historicExternalTaskLogMap"> select * from ${prefix}ACT_HI_EXT_TASK_LOG where ID_ = #{id} </select> <select id="selectHistoricExternalTaskLogByQueryCriteria" parameterType="org.camunda.bpm.engine.impl.HistoricExternalTaskLogQueryImpl" resultMap="historicExternalTaskLogMap"> <include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.bindOrderBy"/> ${limitBefore} select ${distinct} RES.* ${limitBetween} <include refid="selectHistoricExternalTaskLogByQueryCriteriaSql"/> ${orderBy} ${limitAfter} </select> <select id="selectHistoricExternalTaskLogCountByQueryCriteria" parameterType="org.camunda.bpm.engine.impl.HistoricExternalTaskLogQueryImpl" resultType="long"> select count(distinct RES.ID_) <include refid="selectHistoricExternalTaskLogByQueryCriteriaSql"/> </select> <sql id="selectHistoricExternalTaskLogByQueryCriteriaSql"> from ( SELECT SELF.* FROM ${prefix}ACT_HI_EXT_TASK_LOG SELF <if test="authCheck.isAuthorizationCheckEnabled &amp;&amp; !authCheck.revokeAuthorizationCheckEnabled &amp;&amp; authCheck.authUserId != null"> <include refid="org.camunda.bpm.engine.impl.persistence.entity.AuthorizationEntity.authCheckJoinWithoutOnClause"/> AUTH ON (AUTH.RESOURCE_ID_ in (SELF.PROC_DEF_KEY_, '*')) </if> <where> <if test="id != null"> SELF.ID_ = #{id} </if> <if test="externalTaskId != null"> and SELF.EXT_TASK_ID_ = #{externalTaskId} </if> <if test="errorMessage != null"> and SELF.ERROR_MSG_ = #{errorMessage} </if> <if test="topicName != null"> and SELF.TOPIC_NAME_ = #{topicName} </if> <if test="workerId != null"> and SELF.WORKER_ID_ = #{workerId} </if> <if test="activityIds != null &amp;&amp; activityIds.length > 0"> and SELF.ACT_ID_ in <foreach item="item" index="index" collection="activityIds" open="(" separator="," close=")"> #{item} </foreach> </if> <if test="activityInstanceIds != null &amp;&amp; activityInstanceIds.length > 0"> and SELF.ACT_INST_ID_ in <foreach item="item" index="index" collection="activityInstanceIds" open="(" separator="," close=")"> #{item} </foreach> </if> <if test="executionIds != null &amp;&amp; executionIds.length > 0"> and SELF.EXECUTION_ID_ in <foreach item="item" index="index" collection="executionIds" open="(" separator="," close=")"> #{item} </foreach> </if> <if test="processInstanceId != null"> and SELF.PROC_INST_ID_ = #{processInstanceId} </if> <if test="processDefinitionId != null"> and SELF.PROC_DEF_ID_ = #{processDefinitionId} </if> <if test="processDefinitionKey != null"> and SELF.PROC_DEF_KEY_ = #{processDefinitionKey} </if> <if test="priorityHigherThanOrEqual != null"> and SELF.PRIORITY_ &gt;= #{priorityHigherThanOrEqual} </if> <if test="priorityLowerThanOrEqual != null"> and SELF.PRIORITY_ &lt;= #{priorityLowerThanOrEqual} </if> <if test="tenantIds != null &amp;&amp; tenantIds.length > 0"> and SELF.TENANT_ID_ in <foreach item="tenantId" index="index" collection="tenantIds" open="(" separator="," close=")"> #{tenantId} </foreach> </if> <if test="state != null"> and SELF.STATE_ = #{state.stateCode} </if> <if test="authCheck.isAuthorizationCheckEnabled &amp;&amp; authCheck.authUserId != null"> <include refid="org.camunda.bpm.engine.impl.persistence.entity.AuthorizationEntity.queryAuthorizationCheck"/> </if> <include refid="org.camunda.bpm.engine.impl.persistence.entity.TenantEntity.queryTenantCheckWithSelfPrefix"/> </where> ) RES </sql> </mapper>
{ "content_hash": "950e7ca4a3c0fb854121c6fe5b7711c1", "timestamp": "", "source": "github", "line_count": 240, "max_line_length": 176, "avg_line_length": 38.525, "alnum_prop": 0.627839065541856, "repo_name": "AlexMinsk/camunda-bpm-platform", "id": "b712ca6d881a2d8fd0cb2926152c4fdbaf3e3f92", "size": "9246", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "engine/src/main/resources/org/camunda/bpm/engine/impl/mapping/entity/HistoricExternalTaskLog.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "9836" }, { "name": "CSS", "bytes": "2750" }, { "name": "Groovy", "bytes": "1594" }, { "name": "HTML", "bytes": "42436" }, { "name": "Java", "bytes": "26909881" }, { "name": "JavaScript", "bytes": "43" }, { "name": "PLpgSQL", "bytes": "26834" }, { "name": "Python", "bytes": "187" }, { "name": "Ruby", "bytes": "60" }, { "name": "Shell", "bytes": "10937" } ], "symlink_target": "" }
var app = (function(app) { app.renderable = function() { }; app.renderable.prototype.render = function(ctx) { throw "'renderable.render' is a pure virtual function, override it in subclass." }; return app; })(app || {});
{ "content_hash": "41c34570e2baa63a00500c7abb259ced", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 88, "avg_line_length": 25, "alnum_prop": 0.608, "repo_name": "wmatex/hexagonmines", "id": "363052ef75276367071530aad7d76b8939e29239", "size": "250", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/Render.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4989" }, { "name": "HTML", "bytes": "5213" }, { "name": "JavaScript", "bytes": "32590" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Wymuszone przeglądanie</title> </head> <body bgcolor="#ffffff"> <h1>Wymuszone przeglądanie</h1> <p> ZAP allows you to try to discover directories and files using forced browsing.<br> A set of files are provided which contain a large number of file and directory names.<br> ZAP attempts to directly access all of the files and directories listed in the selected file directly rather than relying on finding links to them. <p> Forced Browse is configured using the <a href="options.html">Options Forced Browse screen</a>.<br /> <p>This functionality is based on code from the OWASP DirBuster project. <h2>Accessed via</h2> <table> <tr> <td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td><a href="tab.html">Forced Browse tab</a></td> <td></td> </tr> <tr> <td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td><i>Sites tab</i></td> <td>'Attack/Forced Browse site' right click menu item</td> </tr> <tr> <td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td><i>Sites tab</i></td> <td>'Attack/Forced Browse directory' right click menu item</td> </tr> <tr> <td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td><i>Sites tab</i></td> <td>'Attack/Forced Browse directory (and children)' right click menu item</td> </tr> </table> <h2>Linki zewnętrzne</h2> <table> <tr> <td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td>http://www.owasp.org/index.php/Category:OWASP_DirBuster_Project</td> <td>strona domowa OWASP DirBuster</td> </tr> </table> </body> </html>
{ "content_hash": "45b234df684c380730537578ce7d5d5e", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 91, "avg_line_length": 30.942307692307693, "alnum_prop": 0.6631448104412678, "repo_name": "zapbot/zap-extensions", "id": "56c2c369cccb7d7cc52ed80a80f30e30783a62dc", "size": "1612", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "addOns/bruteforce/src/main/javahelp/org/zaproxy/zap/extension/bruteforce/resources/help_pl_PL/contents/concepts.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "29979" }, { "name": "HTML", "bytes": "6653830" }, { "name": "Haskell", "bytes": "1533212" }, { "name": "Java", "bytes": "10514059" }, { "name": "JavaScript", "bytes": "160056" }, { "name": "Kotlin", "bytes": "80437" }, { "name": "Python", "bytes": "26411" }, { "name": "Ruby", "bytes": "16551" }, { "name": "XSLT", "bytes": "78761" } ], "symlink_target": "" }
import os import logging from hashlib import md5 from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import (scoped_session, sessionmaker, relationship, joinedload) from zope.sqlalchemy import ZopeTransactionExtension from sqlalchemy.ext.hybrid import Comparator, hybrid_property from sqlalchemy import (Column, Integer, Text, Boolean, ForeignKey, DateTime, func, UniqueConstraint, or_, event) from .utils import local_packages, local_releases, get_search_names from .axle import get_package_name, split_package_name DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) Base = declarative_base() log = logging.getLogger(__name__) class CaseInsensitiveComparator(Comparator): def __eq__(self, other): return func.lower(self.__clause_element__()) == func.lower(other) class Package(Base): __tablename__ = 'package' __mapper_args__ = {'order_by': 'name'} id = Column(Integer, primary_key=True) name = Column(Text, unique=True) releases = relationship('Release', backref='package', collection_class=set, cascade='all, delete-orphan', passive_deletes=True) def __init__(self, name, package_dir=None): self.name = name self.package_dir = package_dir def __repr__(self): return u'package: {}'.format(self.name) @hybrid_property def name_insensitive(self): return self.name.lower() @name_insensitive.comparator def name_insensitive(cls): return CaseInsensitiveComparator(cls.name) @classmethod def by_name(cls, name): names = get_search_names(name) or_query = or_(*[Package.name_insensitive == n for n in names]) joined = joinedload(Package.releases, Release.files) return DBSession.query(Package).options(joined).filter(or_query).one() @classmethod def create_from_pypi(cls, name, package_dir): name = get_package_name(name) return cls(name=name, package_dir=package_dir) class Release(Base): __tablename__ = 'release' __table_args__ = (UniqueConstraint('version', 'package_id'), ) id = Column(Integer, primary_key=True) local = Column(Boolean, default=False) package_id = Column(Integer, ForeignKey('package.id', ondelete='CASCADE')) version = Column(Text) created = Column(DateTime(timezone=True), nullable=False, server_default=func.now()) modified = Column(DateTime(timezone=True), nullable=False, server_default=func.now(), onupdate=func.now()) files = relationship('File', backref='release', collection_class=set) def __repr__(self): if self.package: pkg_name = self.package.name else: pkg_name = u'UNKNOWN' return u'release: {}-{}'.format(pkg_name, self.version) @classmethod def for_package(cls, package, version): return (DBSession.query(Release).join(Release.package) .filter(Release.version == version, Package.name == package) .one()) class File(Base): __tablename__ = 'file' __table_args__ = (UniqueConstraint('kind', 'release_id', 'filename'), ) id = Column(Integer, primary_key=True) created = Column(DateTime(timezone=True), nullable=False, server_default=func.now()) modified = Column(DateTime(timezone=True), nullable=False, server_default=func.now(), onupdate=func.now()) release_id = Column(Integer, ForeignKey('release.id', ondelete='CASCADE')) location = Column(Text, nullable=False, default=u'') filename = Column(Text, nullable=False, default=u'') md5 = Column(Text, nullable=False, default=u'') kind = Column(Text, nullable=False, default='source') download_url = Column(Text, unique=True) @property def fullpath(self): return os.path.join(self.location, self.filename) @classmethod def for_release(cls, package, version): return (DBSession .query(File) .join(File.release, Release.package) .filter(Release.version == version, Package.name == package) .all()) @classmethod def by_filename(cls, filename): name, version = split_package_name(filename) return (DBSession .query(File) .join(File.release, Release.package) .filter(Release.version == version, Package.name_insensitive == name, File.filename == filename.lower()) .one()) @event.listens_for(File, 'before_insert') def lowercase_filename(mapper, connect, target): target.filename = target.filename.lower() from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.exc import NoResultFound def get_or_create(session, model, defaults=None, **kwargs): query = session.query(model).filter_by(**kwargs) created = False try: instance = query.one() except NoResultFound: session.begin(nested=True) defaults = defaults or {} kwargs.update(defaults) instance = model(**kwargs) session.add(instance) try: session.flush() except IntegrityError: session.rollback() instance = query.one() else: created = True return instance, created def seed_packages(package_dir): packages = [] for pkg in local_packages(package_dir): releases = {} package = Package(name=pkg) for rel in local_releases(package_dir, pkg): _, ext = os.path.splitext(rel.fullpath) if ext in ['.md5', '.whl']: continue release = releases.setdefault(rel.number, Release(version=rel.number)) with open(rel.fullpath) as fo: hashed_content = md5(fo .read()).hexdigest() release.files.add(File(filename=rel.fullname, location=rel.package_dir, md5=hashed_content)) for k, v in releases.items(): package.releases.add(v) packages.append(package) return packages
{ "content_hash": "957facd99367e5d77e0af57e905118a7", "timestamp": "", "source": "github", "line_count": 183, "max_line_length": 81, "avg_line_length": 34.513661202185794, "alnum_prop": 0.6152628245725142, "repo_name": "rob-b/belt", "id": "de7bc4012897799f1cdec7976c93ed1c4230cabf", "size": "6316", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "belt/models.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "4356" }, { "name": "Python", "bytes": "58633" }, { "name": "Ruby", "bytes": "678" }, { "name": "Shell", "bytes": "2024" } ], "symlink_target": "" }
''' Adapted from https://github.com/tornadomeet/ResNet/blob/master/symbol_resnet.py Original author Wei Wu Implemented the following paper: Saining Xie, Ross Girshick, Piotr Dollar, Zhuowen Tu, Kaiming He. "Aggregated Residual Transformations for Deep Neural Network" ''' import mxnet as mx import numpy as np def residual_unit(data, num_filter, stride, dim_match, name, bottle_neck=True, num_group=32, bn_mom=0.9, workspace=256, memonger=False): """Return ResNet Unit symbol for building ResNet Parameters ---------- data : str Input data num_filter : int Number of output channels bnf : int Bottle neck channels factor with regard to num_filter stride : tuple Stride used in convolution dim_match : Boolean True means channel number between input and output is the same, otherwise means differ name : str Base name of the operators workspace : int Workspace used in convolution operator """ if bottle_neck: # the same as https://github.com/facebook/fb.resnet.torch#notes, a bit difference with origin paper conv1 = mx.sym.Convolution(data=data, num_filter=int(num_filter*0.5), kernel=(1,1), stride=(1,1), pad=(0,0), no_bias=True, workspace=workspace, name=name + '_conv1') bn1 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn1') act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1') conv2 = mx.sym.Convolution(data=act1, num_filter=int(num_filter*0.5), num_group=num_group, kernel=(3,3), stride=stride, pad=(1,1), no_bias=True, workspace=workspace, name=name + '_conv2') bn2 = mx.sym.BatchNorm(data=conv2, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn2') act2 = mx.sym.Activation(data=bn2, act_type='relu', name=name + '_relu2') conv3 = mx.sym.Convolution(data=act2, num_filter=num_filter, kernel=(1,1), stride=(1,1), pad=(0,0), no_bias=True, workspace=workspace, name=name + '_conv3') bn3 = mx.sym.BatchNorm(data=conv3, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn3') if dim_match: shortcut = data else: shortcut_conv = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True, workspace=workspace, name=name+'_sc') shortcut = mx.sym.BatchNorm(data=shortcut_conv, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_sc_bn') if memonger: shortcut._set_attr(mirror_stage='True') eltwise = bn3 + shortcut return mx.sym.Activation(data=eltwise, act_type='relu', name=name + '_relu') else: conv1 = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=(3,3), stride=stride, pad=(1,1), no_bias=True, workspace=workspace, name=name + '_conv1') bn1 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn1') act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1') conv2 = mx.sym.Convolution(data=act1, num_filter=num_filter, kernel=(3,3), stride=(1,1), pad=(1,1), no_bias=True, workspace=workspace, name=name + '_conv2') bn2 = mx.sym.BatchNorm(data=conv2, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn2') if dim_match: shortcut = data else: shortcut_conv = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True, workspace=workspace, name=name+'_sc') shortcut = mx.sym.BatchNorm(data=shortcut_conv, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_sc_bn') if memonger: shortcut._set_attr(mirror_stage='True') eltwise = bn2 + shortcut return mx.sym.Activation(data=eltwise, act_type='relu', name=name + '_relu') def resnext(units, num_stages, filter_list, num_classes, num_group, image_shape, bottle_neck=True, bn_mom=0.9, workspace=256, dtype='float32', memonger=False): """Return ResNeXt symbol of Parameters ---------- units : list Number of units in each stage num_stages : int Number of stage filter_list : list Channel size of each stage num_classes : int Ouput size of symbol num_groupes: int Number of conv groups dataset : str Dataset type, only cifar10 and imagenet supports workspace : int Workspace used in convolution operator dtype : str Precision (float32 or float16) """ num_unit = len(units) assert(num_unit == num_stages) data = mx.sym.Variable(name='data') if dtype == 'float32': data = mx.sym.identity(data=data, name='id') else: if dtype == 'float16': data = mx.sym.Cast(data=data, dtype=np.float16) data = mx.sym.BatchNorm(data=data, fix_gamma=True, eps=2e-5, momentum=bn_mom, name='bn_data') (nchannel, height, width) = image_shape if height <= 32: # such as cifar10 body = mx.sym.Convolution(data=data, num_filter=filter_list[0], kernel=(3, 3), stride=(1,1), pad=(1, 1), no_bias=True, name="conv0", workspace=workspace) else: # often expected to be 224 such as imagenet body = mx.sym.Convolution(data=data, num_filter=filter_list[0], kernel=(7, 7), stride=(2,2), pad=(3, 3), no_bias=True, name="conv0", workspace=workspace) body = mx.sym.BatchNorm(data=body, fix_gamma=False, eps=2e-5, momentum=bn_mom, name='bn0') body = mx.sym.Activation(data=body, act_type='relu', name='relu0') body = mx.sym.Pooling(data=body, kernel=(3, 3), stride=(2,2), pad=(1,1), pool_type='max') for i in range(num_stages): body = residual_unit(body, filter_list[i+1], (1 if i==0 else 2, 1 if i==0 else 2), False, name='stage%d_unit%d' % (i + 1, 1), bottle_neck=bottle_neck, num_group=num_group, bn_mom=bn_mom, workspace=workspace, memonger=memonger) for j in range(units[i]-1): body = residual_unit(body, filter_list[i+1], (1,1), True, name='stage%d_unit%d' % (i + 1, j + 2), bottle_neck=bottle_neck, num_group=num_group, bn_mom=bn_mom, workspace=workspace, memonger=memonger) pool1 = mx.sym.Pooling(data=body, global_pool=True, kernel=(7, 7), pool_type='avg', name='pool1') flat = mx.sym.Flatten(data=pool1) fc1 = mx.sym.FullyConnected(data=flat, num_hidden=num_classes, name='fc1') if dtype == 'float16': fc1 = mx.sym.Cast(data=fc1, dtype=np.float32) return mx.sym.SoftmaxOutput(data=fc1, name='softmax') def get_symbol(num_classes, num_layers, image_shape, num_group=32, conv_workspace=256, dtype='float32', **kwargs): """ Adapted from https://github.com/tornadomeet/ResNet/blob/master/train_resnet.py Original author Wei Wu """ (nchannel, height, width) = (image_shape[0], image_shape[1], image_shape[2]) if height <= 32: num_stages = 3 if (num_layers-2) % 9 == 0 and num_layers >= 164: per_unit = [(num_layers-2)//9] filter_list = [16, 64, 128, 256] bottle_neck = True elif (num_layers-2) % 6 == 0 and num_layers < 164: per_unit = [(num_layers-2)//6] filter_list = [16, 16, 32, 64] bottle_neck = False else: raise ValueError("no experiments done on num_layers {}, you can do it yourself".format(num_layers)) units = per_unit * num_stages else: if num_layers >= 50: filter_list = [64, 256, 512, 1024, 2048] bottle_neck = True else: filter_list = [64, 64, 128, 256, 512] bottle_neck = False num_stages = 4 if num_layers == 18: units = [2, 2, 2, 2] elif num_layers == 34: units = [3, 4, 6, 3] elif num_layers == 50: units = [3, 4, 6, 3] elif num_layers == 101: units = [3, 4, 23, 3] elif num_layers == 152: units = [3, 8, 36, 3] elif num_layers == 200: units = [3, 24, 36, 3] elif num_layers == 269: units = [3, 30, 48, 8] else: raise ValueError("no experiments done on num_layers {}, you can do it yourself".format(num_layers)) return resnext(units = units, num_stages = num_stages, filter_list = filter_list, num_classes = num_classes, num_group = num_group, image_shape = image_shape, bottle_neck = bottle_neck, workspace = conv_workspace, dtype = dtype)
{ "content_hash": "bd6dff15bd1382964d58ab861e94ed30", "timestamp": "", "source": "github", "line_count": 195, "max_line_length": 159, "avg_line_length": 46.784615384615385, "alnum_prop": 0.5774416310424203, "repo_name": "gu-yan/mlAlgorithms", "id": "ecf87f1f61a007949de1b34dca497d2d8a9d8ae8", "size": "9909", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mxnet/model/resnext.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "159631" } ], "symlink_target": "" }
import RcModule from 'ringcentral-integration/lib/RcModule'; import { Module } from 'ringcentral-integration/lib/di'; <% if (dependencies.length > 0) { %> import getReducer from './getReducer'; import actionTypes from './actionTypes'; <% } %> @Module({ deps: [ <%_ dependencies.forEach(function(dependence) { -%> <%- `{ dep: '${dependence}' },` %> <%_ }) -%> { dep: '<%- name %>Options', optional: true, spread: true }, ], }) export default class <%- name %> extends RcModule { constructor({ <%_ dependencies.forEach(function(dependence) { -%> <%- `${dependence.charAt(0).toLowerCase()}${dependence.slice(1)},` %> <%_ }) -%> ...options, }) { super({ <% if (dependencies.length > 0) { %> actionTypes, <% } %> ...options, }); <%_ dependencies.forEach(function(dependence) { -%> <%- `this._${dependence.charAt(0).toLowerCase()}${dependence.slice(1)} = ${dependence.charAt(0).toLowerCase()}${dependence.slice(1)};` %> <%_ }) -%> <% if (dependencies.length > 0) { %> this._reducer = getReducer(this.actionTypes); <% } %> // your codes here } // your codes here <% if (dependencies.length > 0) { %> // Codes on state change async _onStateChange() { if (this._shouldInit()) { this.store.dispatch({ type: this.actionTypes.initSuccess }); } else if (this._shouldReset()) { this.store.dispatch({ type: this.actionTypes.resetSuccess, }); } } _shouldInit() { return ( <%_ dependencies.forEach(function(dependence) { -%> <%- `this._${dependence.charAt(0).toLowerCase()}${dependence.slice(1)}.ready &&` %> <%_ }) -%> this.pending ); } _shouldReset() { return ( ( <%_ dependencies.forEach(function(dependence, index) { -%> <%- `!this._${dependence.charAt(0).toLowerCase()}${dependence.slice(1)}.ready${index === (dependencies.length - 1) ? '' : ' ||'}` %> <%_ }) -%> ) && this.ready ); } get status() { return this.state.status; } <% } %> <% if (dependencies.length === 0) { %> get ready() { return true; } <% } %> }
{ "content_hash": "07b2222fb3569aa39de65a8ca2c40204", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 141, "avg_line_length": 26.313253012048193, "alnum_prop": 0.5425824175824175, "repo_name": "u9520107/ringcentral-js-widget", "id": "0c0f81bfce4399bef9d035ce16d5c1e804cc40a6", "size": "2184", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "packages/ringcentral-widgets-cli/templates/Module/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "90533" }, { "name": "HTML", "bytes": "2967" }, { "name": "JavaScript", "bytes": "433434" }, { "name": "Shell", "bytes": "1001" } ], "symlink_target": "" }
@interface PodsDummy_Pods_bsbdj : NSObject @end @implementation PodsDummy_Pods_bsbdj @end
{ "content_hash": "7507bc7e3e5efbbce0d3a5593915c108", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 42, "avg_line_length": 22.5, "alnum_prop": 0.8111111111111111, "repo_name": "watayouxiang/bsbdj", "id": "d56b143c49abfa9c3158529f0e7cc8a9187999cd", "size": "124", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bsbdj/Pods/Target Support Files/Pods-bsbdj/Pods-bsbdj-dummy.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "54687" }, { "name": "Objective-C", "bytes": "1854046" }, { "name": "Objective-C++", "bytes": "124423" }, { "name": "Ruby", "bytes": "293" }, { "name": "Shell", "bytes": "8861" } ], "symlink_target": "" }
namespace ml { namespace map_impl { namespace test { extern void run_getall_tests(); } // test } // map_impl } // ml #endif // __ML_MAP_IMPL_TEST_GETALL_H__
{ "content_hash": "09d86870bda1b3c3be8f4528c1577d98", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 39, "avg_line_length": 14.545454545454545, "alnum_prop": 0.6375, "repo_name": "sugawaray/filemanager", "id": "2f96d636b6cf1d5f0d323a116ab30f22b78b4494", "size": "237", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/map_impl/getall.h", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "307932" }, { "name": "Makefile", "bytes": "6062" }, { "name": "Shell", "bytes": "16552" } ], "symlink_target": "" }
/* * @lc app=leetcode id=33 lang=cpp * * [33] Search in Rotated Sorted Array * * https://leetcode.com/problems/search-in-rotated-sorted-array/description/ * * algorithms * Medium (33.15%) * Total Accepted: 498.4K * Total Submissions: 1.5M * Testcase Example: '[4,5,6,7,0,1,2]\n0' * * Suppose an array sorted in ascending order is rotated at some pivot unknown * to you beforehand. * * (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). * * You are given a target value to search. If found in the array return its * index, otherwise return -1. * * You may assume no duplicate exists in the array. * * Your algorithm's runtime complexity must be in the order of O(log n). * * Example 1: * * * Input: nums = [4,5,6,7,0,1,2], target = 0 * Output: 4 * * * Example 2: * * * Input: nums = [4,5,6,7,0,1,2], target = 3 * Output: -1 * */ #include "common.hpp" class Solution { private: // from [start, end) int searchHelper(vector<int>& nums, size_t start, size_t end, int target) { if (end - start <= 1) { if (nums[start] == target) return start; else return -1; } int mid = (start + end) / 2; // [start, mid) if (start == mid - 1) { if (nums[start] == target) return start; return searchHelper(nums, mid, end, target); } else if (mid == end - 1) { if (nums[mid] == target) return mid; else searchHelper(nums, start, mid, target); } if (nums[start] < nums[mid - 1]) { if (target >= nums[start] && target <= nums[mid - 1]) { return searchHelper(nums, start, mid, target); } else { return searchHelper(nums, mid, end, target); } } else { if (target >= nums[mid] && target <= nums[end - 1]) { return searchHelper(nums, mid, end, target); } else { return searchHelper(nums, start, mid, target); } } } public: int search(vector<int>& nums, int target) { if (nums.size() <= 0) return -1; else return searchHelper(nums, 0, nums.size(), target); } };
{ "content_hash": "c51e44d8f5fe682fde325e9902f90c47", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 79, "avg_line_length": 26.759036144578314, "alnum_prop": 0.5371454299864926, "repo_name": "vermouth1992/Leetcode", "id": "a0e5a0a3f51e9e83ecebe3b1f425ecfe2816d48b", "size": "2223", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cpp/33.search-in-rotated-sorted-array.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "369467" }, { "name": "Java", "bytes": "14251" }, { "name": "Python", "bytes": "232732" }, { "name": "Shell", "bytes": "62" } ], "symlink_target": "" }
@org.checkerframework.framework.qual.DefaultQualifier(org.checkerframework.checker.nullness.qual.NonNull.class) package org.lanternpowered.server.item.recipe.crafting;
{ "content_hash": "f6a8079dc61e038fd38840d9ef12cf99", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 111, "avg_line_length": 56.333333333333336, "alnum_prop": 0.863905325443787, "repo_name": "LanternPowered/LanternServer", "id": "3a595a7d6ef3544fae93b8c85d08c5b08588e03b", "size": "492", "binary": false, "copies": "1", "ref": "refs/heads/1.16", "path": "src/main/java/org/lanternpowered/server/item/recipe/crafting/package-info.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "8613522" }, { "name": "Kotlin", "bytes": "825665" } ], "symlink_target": "" }
package com.isjfk.android.rac.activity; import java.util.ArrayList; import java.util.List; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.ToggleButton; import com.isjfk.android.rac.R; import com.isjfk.android.rac.RegularAlarmDataService.ResultCode; import com.isjfk.android.rac.RegularAlarmDataServiceClient; import com.isjfk.android.rac.bean.AlarmRule; import com.isjfk.android.rac.bean.DateRule; import com.isjfk.android.rac.callback.AlarmRuleCallback; import com.isjfk.android.rac.callback.ConnectionCallback; import com.isjfk.android.rac.common.Log; import com.isjfk.android.rac.common.RACContext; import com.isjfk.android.rac.common.RACException; import com.isjfk.android.rac.common.RACUtil; import com.isjfk.android.rac.rule.RuleDesc; import com.isjfk.android.rac.widget.TimeView; import com.isjfk.android.util.AndroidUtil; import com.isjfk.android.util.JavaUtil; /** * 闹铃规则列表界面。 * * @author Jimmy F. Klarke * @version 1.0, 2011-8-2 */ public class AlarmRuleListActivity extends ListActivity implements ConnectionCallback, AlarmRuleCallback { private boolean closeOnStop = false; private RegularAlarmDataServiceClient client = new RegularAlarmDataServiceClient(this, this); private OnCheckedChangeListener enabledListener = new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (buttonView.getTag() instanceof Integer) { client.updateAlarmRuleEnabled((Integer) buttonView.getTag(), isChecked); } } }; /** * {@inheritDoc} * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.alarmrule_list); Button scheduleButton = (Button) findViewById(R.id.scheduleButton); scheduleButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { closeOnStop = true; Intent intent = new Intent(AlarmRuleListActivity.this, ScheduleListActivity.class); startActivity(intent); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); } }); Button optionsMenuButton = (Button) findViewById(R.id.optionsMenuButton); optionsMenuButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { openOptionsMenu(); } }); Button addButton = (Button) findViewById(R.id.titleBarAddButton); addButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View paramView) { Intent intent = new Intent(AlarmRuleListActivity.this, AlarmRuleEditActivity.class); AndroidUtil.putExtra(intent, AlarmRuleEditActivity.MODE_KEY, AlarmRuleEditActivity.MODE_ADD); startActivity(intent); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } }); registerForContextMenu(findViewById(android.R.id.list)); } /** * {@inheritDoc} * @see android.app.Activity#onStart() */ @Override protected void onStart() { super.onStart(); setListAdapter(new AlarmRuleAdapter(this, new ArrayList<AlarmRule>())); ((TextView) findViewById(android.R.id.empty)).setText(R.string.loading); closeOnStop = false; client.bindService(); } /** * {@inheritDoc} * @see android.app.Activity#onStop() */ @Override protected void onStop() { super.onStop(); client.unbindService(); if (closeOnStop && !isFinishing()) { finish(); } } /** * {@inheritDoc} * @see android.app.Activity#onBackPressed() */ @Override public void onBackPressed() { finish(); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); } /** * {@inheritDoc} * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu) */ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.options_menu, menu); return true; } /** * {@inheritDoc} * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menuWorkday: startActivity(new Intent(this, WorkdayListActivity.class)); return true; case R.id.menuPreferences: startActivity(new Intent(this, RACPreferenceActivity.class)); return true; case R.id.menuHelp: RACUtil.openHelpActivity(this, "alarm"); return true; case R.id.menuAbout: startActivity(new Intent(this, AboutActivity.class)); return true; default: return super.onOptionsItemSelected(item); } } /** * {@inheritDoc} * @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo) */ @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); getMenuInflater().inflate(R.menu.alarmrule_list_context_menu, menu); } /** * {@inheritDoc} * @see android.app.Activity#onContextItemSelected(android.view.MenuItem) */ @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); AlarmRule selectedAlarmRule = ((AlarmRuleAdapter) getListAdapter()).getAlarmRule(info.position); Intent intent = null; switch (item.getItemId()) { case R.id.contextMenuView: intent = new Intent(this, AlarmRuleViewActivity.class); AndroidUtil.putExtra(intent, AlarmRuleViewActivity.ALARMRULE_KEY, selectedAlarmRule); startActivity(intent); return true; case R.id.contextMenuClone: intent = new Intent(this, AlarmRuleEditActivity.class); AndroidUtil.putExtra(intent, AlarmRuleEditActivity.MODE_KEY, AlarmRuleEditActivity.MODE_ADD); AndroidUtil.putExtra(intent, AlarmRuleEditActivity.ALARMRULE_KEY, selectedAlarmRule); startActivity(intent); return true; case R.id.contextMenuDelete: client.deleteAlarmRule(selectedAlarmRule.getId()); return true; default: return super.onContextItemSelected(item); } } /** * {@inheritDoc} * @see android.app.ListActivity#onListItemClick(android.widget.ListView, android.view.View, int, long) */ @Override protected void onListItemClick(ListView l, View v, int position, long id) { AlarmRule alarmRule = (AlarmRule) getListView().getItemAtPosition(position); Intent intent = new Intent(this, AlarmRuleEditActivity.class); AndroidUtil.putExtra(intent, AlarmRuleEditActivity.MODE_KEY, AlarmRuleEditActivity.MODE_EDIT); AndroidUtil.putExtra(intent, AlarmRuleEditActivity.ALARMRULE_KEY, alarmRule); startActivity(intent); } /** * {@inheritDoc} * @see com.isjfk.android.rac.callback.ConnectionCallback#onConnected(android.content.Context) */ @Override public void onConnected(Context context) { client.queryAllAlarmRules(); } /** * {@inheritDoc} * @see com.isjfk.android.rac.callback.AlarmRuleCallback#onQueryAllAlarmRules(android.content.Context, java.lang.Integer, java.util.List) */ @Override public void onQueryAllAlarmRules(Context context, Integer resultCode, List<AlarmRule> alarmRuleList) { if (alarmRuleList.isEmpty()) { ((TextView) findViewById(android.R.id.empty)).setText(R.string.alarmRuleNoRecord); } showAlarmRuleList(alarmRuleList); RACContext.setAdKeywordsForAlarmRule(alarmRuleList); } /** * {@inheritDoc} * @see com.isjfk.android.rac.callback.AlarmRuleCallback#onDeleteAlarmRule(android.content.Context, java.lang.Integer) */ @Override public void onDeleteAlarmRule(Context context, Integer resultCode) { if (ResultCode.SUCCESS.equals(resultCode)) { RACUtil.popupNotify(this, R.string.alarmRuleDeleteSuccess); client.queryAllAlarmRules(); } else { RACUtil.popupError(this, R.string.errAlarmRuleDeleteFailed); } } /** * {@inheritDoc} * @see com.isjfk.android.rac.callback.AlarmRuleCallback#onUpdateAlarmRuleEnabled(android.content.Context, java.lang.Integer) */ @Override public void onUpdateAlarmRuleEnabled(Context context, Integer resultCode) { if (ResultCode.SUCC_ENABLED.equals(resultCode)) { RACUtil.popupNotify(this, R.string.alarmRuleEnabled); } else if (ResultCode.SUCC_DISABLED.equals(resultCode)) { RACUtil.popupNotify(this, R.string.alarmRuleDisabled); } else if (ResultCode.FAILED.equals(resultCode)) { RACUtil.popupError(this, R.string.errAlarmRuleUpdateEnabledFailed); } else { String errMsg = "unknown alarm rule enabled update result: " + resultCode; Log.e(errMsg); throw new RACException(errMsg); } } /** * 将闹铃规则显示在界面上。 * * @param alamrRuleList 闹铃规则列表 */ private void showAlarmRuleList(List<AlarmRule> alamrRuleList) { setListAdapter(new AlarmRuleAdapter(this, alamrRuleList)); } /** * 将闹铃规则展示在ListView上的Adapter。 * * @author Jimmy F. Klarke * @version 1.0, 2011-8-31 */ class AlarmRuleAdapter extends BaseAdapter { private LayoutInflater inflater; private List<AlarmRule> alarmRuleList; public AlarmRuleAdapter(Context context, List<AlarmRule> alarmRuleList) { this.inflater = LayoutInflater.from(context); this.alarmRuleList = alarmRuleList; } @Override public int getCount() { return alarmRuleList.size(); } @Override public Object getItem(int position) { return getAlarmRule(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View itemView = null; if ((convertView != null) && (convertView instanceof LinearLayout) && (convertView.findViewById(R.id.alarmRuleTime) != null) && (convertView.findViewById(R.id.alarmRuleName) != null) && (convertView.findViewById(R.id.alarmRuleDesc) != null)) { itemView = convertView; } if (itemView == null) { int itemId = R.layout.alarmrule_list_item; itemView = inflater.inflate(itemId, null); } AlarmRule alarmRule = getAlarmRule(position); TimeView timeView = (TimeView) itemView.findViewById(R.id.alarmRuleTime); if (alarmRule.isActived()) { timeView.setTextColor(getResources().getColorStateList(R.color.text_normal)); } else { timeView.setTextColor(getResources().getColorStateList(R.color.text_dim2)); } timeView.setTime(alarmRule.getTimeAsCalendar()); ((TextView)itemView.findViewById(R.id.alarmRuleName)).setText(alarmRule.getName()); ((TextView)itemView.findViewById(R.id.alarmRuleDesc)).setText(desc(alarmRule.getDateRuleList())); ToggleButton button = (ToggleButton)itemView.findViewById(R.id.alarmRuleEnabled); button.setOnCheckedChangeListener(null); // 防止重用组件时调用Listener button.setTag(alarmRule.getId()); button.setChecked(alarmRule.isEnabled()); button.setOnCheckedChangeListener(enabledListener); return itemView; } public AlarmRule getAlarmRule(Integer index) { return alarmRuleList.get(index); } } private String desc(List<DateRule> ruleList) { String ruleDesc = RuleDesc.descSingleLine(getResources(), ruleList); if (JavaUtil.isEmpty(ruleDesc)) { ruleDesc = getResources().getString(R.string.alarmRuleNoRepeatRule); } return ruleDesc; } @Override public void onDisconnected(Context context) { // do nothing } @Override public void onAddAlarmRule(Context context, Integer resultCode, AlarmRule alarmRule) { // not used } @Override public void onUpdateAlarmRule(Context context, Integer resultCode) { // not used } }
{ "content_hash": "17fc303286398581d468e24b1fcc1419", "timestamp": "", "source": "github", "line_count": 398, "max_line_length": 141, "avg_line_length": 34.87185929648241, "alnum_prop": 0.6565314503926796, "repo_name": "isjfk/poweralarm", "id": "1996380f4d3101d7edf674fa89fa23db62ac3f21", "size": "14051", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "archive/RegularAlarmClock/src/com/isjfk/android/rac/activity/AlarmRuleListActivity.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "HTML", "bytes": "21186" }, { "name": "Java", "bytes": "780923" } ], "symlink_target": "" }
#ifndef TUDAT_EMPIRICALACCELERATIONPARTIAL_H #define TUDAT_EMPIRICALACCELERATIONPARTIAL_H #include <functional> #include <boost/lambda/lambda.hpp> #include <memory> #include "tudat/astro/orbit_determination/acceleration_partials/accelerationPartial.h" #include "tudat/astro/orbit_determination/estimatable_parameters/empiricalAccelerationCoefficients.h" #include "tudat/math/basic/linearAlgebra.h" #include "tudat/astro/basic_astro/empiricalAcceleration.h" namespace tudat { namespace acceleration_partials { //! Function determine the numerical partial derivative of the true anomaly wrt the elements of the Cartesian state /*! * unction determine the numerical partial derivative of the true anomaly wrt the elements of the Cartesian state, * from the Cartesian state as input. * A first-order central difference with a user-defined Cartesian state perturbation vector is used. * \param cartesianElements Nominal Cartesian elements at which the partials are to be computed * \param gravitationalParameter Gravitational parameter of central body around which Keplerian orbit is given * \param cartesianStateElementPerturbations Numerical perturbations of Cartesian state that are to be used * \return Partial of Cartesian state wrt true anomaly of orbit. */ Eigen::Matrix< double, 1, 6 > calculateNumericalPartialOfTrueAnomalyWrtState( const Eigen::Vector6d& cartesianElements, const double gravitationalParameter, const Eigen::Vector6d& cartesianStateElementPerturbations ); class EmpiricalAccelerationPartial: public AccelerationPartial { public: using AccelerationPartial::getParameterPartialFunction; EmpiricalAccelerationPartial( std::shared_ptr< basic_astrodynamics::EmpiricalAcceleration > empiricalAcceleration, std::string acceleratedBody, std::string acceleratingBody ): AccelerationPartial( acceleratedBody, acceleratingBody, basic_astrodynamics::empirical_acceleration ), empiricalAcceleration_( empiricalAcceleration ){ cartesianStateElementPerturbations << 0.1, 0.1, 0.1, 0.001, 0.001, 0.001; } //! Function for calculating the partial of the acceleration w.r.t. the position of body undergoing acceleration.. /*! * Function for calculating the partial of the acceleration w.r.t. the position of body undergoing acceleration * and adding it to the existing partial block * Update( ) function must have been called during current time step before calling this function. * \param partialMatrix Block of partial derivatives of acceleration w.r.t. Cartesian position of body * undergoing acceleration where current partial is to be added. * \param addContribution Variable denoting whether to return the partial itself (true) or the negative partial (false). * \param startRow First row in partialMatrix block where the computed partial is to be added. * \param startColumn First column in partialMatrix block where the computed partial is to be added. */ void wrtPositionOfAcceleratedBody( Eigen::Block< Eigen::MatrixXd > partialMatrix, const bool addContribution = 1, const int startRow = 0, const int startColumn = 0 ) { if( addContribution ) { partialMatrix.block( startRow, startColumn, 3, 3 ) += currentPositionPartial_; } else { partialMatrix.block( startRow, startColumn, 3, 3 ) -= currentPositionPartial_; } } //! Function for calculating the partial of the acceleration w.r.t. the position of body undergoing acceleration.. /*! * Function for calculating the partial of the acceleration w.r.t. the position of body undergoing acceleration and * adding it to the existing partial block. * The update( ) function must have been called during current time step before calling this function. * \param partialMatrix Block of partial derivatives of acceleration w.r.t. Cartesian position of body * exerting acceleration where current partial is to be added. * \param addContribution Variable denoting whether to return the partial itself (true) or the negative partial (false). * \param startRow First row in partialMatrix block where the computed partial is to be added. * \param startColumn First column in partialMatrix block where the computed partial is to be added. */ void wrtPositionOfAcceleratingBody( Eigen::Block< Eigen::MatrixXd > partialMatrix, const bool addContribution = 1, const int startRow = 0, const int startColumn = 0 ) { if( addContribution ) { partialMatrix.block( startRow, startColumn, 3, 3 ) -= currentPositionPartial_; } else { partialMatrix.block( startRow, startColumn, 3, 3 ) += currentPositionPartial_; } } //! Function for calculating the partial of the acceleration w.r.t. the velocity of body undergoing acceleration.. /*! * Function for calculating the partial of the acceleration w.r.t. the velocity of body undergoing acceleration * and adding it to the existing partial block * Update( ) function must have been called during current time step before calling this function. * \param partialMatrix Block of partial derivatives of acceleration w.r.t. Cartesian position of body * undergoing acceleration where current partial is to be added. * \param addContribution Variable denoting whether to return the partial itself (true) or the negative partial (false). * \param startRow First row in partialMatrix block where the computed partial is to be added. * \param startColumn First column in partialMatrix block where the computed partial is to be added. */ void wrtVelocityOfAcceleratedBody( Eigen::Block< Eigen::MatrixXd > partialMatrix, const bool addContribution = 1, const int startRow = 0, const int startColumn = 0 ) { if( addContribution ) { partialMatrix.block( startRow, startColumn, 3, 3 ) += currentVelocityPartial_; } else { partialMatrix.block( startRow, startColumn, 3, 3 ) -= currentVelocityPartial_; } } //! Function for calculating the partial of the acceleration w.r.t. the velocity of body undergoing acceleration.. /*! * Function for calculating the partial of the acceleration w.r.t. the velocity of body undergoing acceleration and * adding it to the existing partial block. * The update( ) function must have been called during current time step before calling this function. * \param partialMatrix Block of partial derivatives of acceleration w.r.t. Cartesian position of body * exerting acceleration where current partial is to be added. * \param addContribution Variable denoting whether to return the partial itself (true) or the negative partial (false). * \param startRow First row in partialMatrix block where the computed partial is to be added. * \param startColumn First column in partialMatrix block where the computed partial is to be added. */ void wrtVelocityOfAcceleratingBody( Eigen::Block< Eigen::MatrixXd > partialMatrix, const bool addContribution = 1, const int startRow = 0, const int startColumn = 0 ) { if( addContribution ) { partialMatrix.block( startRow, startColumn, 3, 3 ) -= currentVelocityPartial_; } else { partialMatrix.block( startRow, startColumn, 3, 3 ) += currentVelocityPartial_; } } //! Function for setting up and retrieving a function returning a partial w.r.t. a vector parameter. /*! * Function for setting up and retrieving a function returning a partial w.r.t. a vector parameter. * Function returns empty function and zero size indicator for parameters with no dependency for current acceleration. * \param parameter Parameter w.r.t. which partial is to be taken. * \return Pair of parameter partial function and number of columns in partial */ std::pair< std::function< void( Eigen::MatrixXd& ) >, int > getParameterPartialFunction( std::shared_ptr< estimatable_parameters::EstimatableParameter< Eigen::VectorXd > > parameter ); //! Function for updating common blocks of partial to current state. /*! * Function for updating common blocks of partial to current state. Position and velocity partials are computed and set. * \param currentTime Time at which partials are to be calculated */ void update( const double currentTime = TUDAT_NAN ); //! Function to compute the partial w.r.t. arcwise empirical acceleration components /*! * Function to compute the partial w.r.t. arcwise empirical acceleration components * \param parameter Object defining the properties of the arcwise components that are to be estimated. * \param partialDerivativeMatrix Matrix of partial derivatives of accelerations w.r.t. empirical accelerations (returned * by reference) */ void wrtArcWiseEmpiricalAccelerationCoefficient( std::shared_ptr< estimatable_parameters::ArcWiseEmpiricalAccelerationCoefficientsParameter > parameter, Eigen::MatrixXd& partialDerivativeMatrix ); //! Function to compute the partial w.r.t. time-independent empirical acceleration components /*! * Function to compute the partial w.r.t. time-independent empirical acceleration components * \param parameter Object defining the properties of the components that are to be estimated. * \param partialDerivativeMatrix Matrix of partial derivatives of accelerations w.r.t. empirical accelerations (returned * by reference) */ void wrtEmpiricalAccelerationCoefficient( std::shared_ptr< estimatable_parameters::EmpiricalAccelerationCoefficientsParameter > parameter, Eigen::MatrixXd& partialDerivativeMatrix ) { return wrtEmpiricalAccelerationCoefficientFromIndices( parameter->getParameterSize( ), parameter->getIndices( ), partialDerivativeMatrix ); } //! Function to compute the partial w.r.t. time-independent empirical acceleration components /*! * Function to compute the partial w.r.t. time-independent empirical acceleration components from list of components and * functional shapes. * \param numberOfAccelerationComponents Total number of empirical acceleration components w.r.t. which partials are to * be computed. * \param accelerationIndices Map denoting list of components of accelerations that are to be computed. Key: functional * shape of empirical accelerations. Value: list of acceleration vaector entries that are to be used (0: radial (R), * 1: along-track (S), 2: cross-track (W)). * \param partialDerivativeMatrix Matrix of partial derivatives of accelerations w.r.t. empirical accelerations (returned * by reference) */ void wrtEmpiricalAccelerationCoefficientFromIndices( const int numberOfAccelerationComponents, const std::map< basic_astrodynamics::EmpiricalAccelerationFunctionalShapes, std::vector< int > >& accelerationIndices, Eigen::MatrixXd& partialDerivativeMatrix ); private: //! Acceleration w.r.t. which partials are to be computed. std::shared_ptr< basic_astrodynamics::EmpiricalAcceleration > empiricalAcceleration_; //! Current partial of empirical acceleration w.r.t. position of body undergoing acceleration. Eigen::Matrix3d currentPositionPartial_; //! Current partial of empirical acceleration w.r.t. velocity of body undergoing acceleration. Eigen::Matrix3d currentVelocityPartial_; //! Perturbations to use on Cartesian state elements when computing partial of true anomaly w.r.t. state. Eigen::Matrix< double, 1, 6 > cartesianStateElementPerturbations; }; } } #endif // TUDAT_EMPIRICALACCELERATIONPARTIAL_H
{ "content_hash": "bb01837f8ed06c5d1195405151c9092f", "timestamp": "", "source": "github", "line_count": 224, "max_line_length": 132, "avg_line_length": 54.120535714285715, "alnum_prop": 0.7211911243091644, "repo_name": "Tudat/tudat", "id": "5d6bdbe54508b0f21f59f3c0c3659cb2c01aebca", "size": "12552", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/tudat/astro/orbit_determination/acceleration_partials/empiricalAccelerationPartial.h", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1372" }, { "name": "C", "bytes": "47041" }, { "name": "C++", "bytes": "14445148" }, { "name": "CMake", "bytes": "206040" }, { "name": "Python", "bytes": "810" }, { "name": "Shell", "bytes": "1396" }, { "name": "Xonsh", "bytes": "1143" } ], "symlink_target": "" }
using System; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Xml; using Framework.Utility; namespace Doozestan.Common.Util { public static class AmberUtil { public static string Beautify(this XmlDocument doc) { StringBuilder sb = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = " ", NewLineChars = "\r\n", NewLineHandling = NewLineHandling.Replace }; using (XmlWriter writer = XmlWriter.Create(sb, settings)) { doc.Save(writer); } return sb.ToString(); } public static string RemoveControlCharacters(string inString) { if (inString == null) return null; StringBuilder newString = new StringBuilder(); char ch; foreach (char t in inString) { ch = t; if (!char.IsControl(ch)) { newString.Append(ch); } else { continue; } } return newString.ToString(); } public static string SafeSpace(string str, string replacement = "") { if (String.IsNullOrEmpty(str)) return str; str = str.Replace(" ", " "); str = str.Replace(" ", " "); str = str.Replace(" ", " "); str = str.Replace("¬", " "); str = str.Replace(" ", " "); str = str.Replace(" ", " "); str = str.Replace(" ", " "); str = str.Replace("\x200E", replacement); str = str.Replace("\x200F", replacement); str = str.Replace('\x0640'.ToString(), replacement); str = str.Replace(((char)65279).ToString(), replacement); string str1 = str; char ch = ' '; string oldValue1 = ch.ToString(); string newValue1 = replacement; str = str1.Replace(oldValue1, newValue1); string str2 = str; ch = ' '; string oldValue2 = ch.ToString(); string newValue2 = replacement; str = str2.Replace(oldValue2, newValue2); string str3 = str; ch = '\x200B'; string oldValue3 = ch.ToString(); string newValue3 = replacement; str = str3.Replace(oldValue3, newValue3); string str4 = str; ch = '\x200C'; string oldValue4 = ch.ToString(); string newValue4 = replacement; str = str4.Replace(oldValue4, newValue4); string str5 = str; ch = '\x200D'; string oldValue5 = ch.ToString(); string newValue5 = replacement; str = str5.Replace(oldValue5, newValue5); string str6 = str; ch = '\x200E'; string oldValue6 = ch.ToString(); string newValue6 = replacement; str = str6.Replace(oldValue6, newValue6); string str7 = str; ch = '\x200F'; string oldValue7 = ch.ToString(); string newValue7 = replacement; str = str7.Replace(oldValue7, newValue7); string str8 = str; ch = '‐'; string oldValue8 = ch.ToString(); string newValue8 = replacement; str = str8.Replace(oldValue8, newValue8); string str9 = str; ch = '‑'; string oldValue9 = ch.ToString(); string newValue9 = replacement; str = str9.Replace(oldValue9, newValue9); str = str.Replace("¬", replacement); str = str.Trim(); return str; } public static string RmoveIllegalChars(this string illegal) { string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()); Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch))); illegal = r.Replace(illegal, ""); return illegal; } public static string PadLeftString(string input, int totalWidth) { return input.PadLeft(totalWidth, '0'); } public static string PadLeftString(int input, int totalWidth) { return input.ToString().PadLeft(totalWidth, '0'); } public static string ToFirstMarketISIN(this string isin) { if (isin.EndsWith("02")) { return isin.Replace("02", "01"); } if (isin.EndsWith("03")) { return isin.Replace("03", "01"); } if (isin.EndsWith("A2")) { return isin.Replace("A2", "A1"); } if (isin.EndsWith("C2")) { return isin.Replace("C2", "C1"); } if (isin.StartsWith("IRB") && isin.EndsWith("12")) { return isin.Replace("12", "11"); } if (isin.StartsWith("IRB") && isin.EndsWith("52")) { return isin.Replace("52", "51"); } return isin; } public static string SafePersianPhrase(this string str) { if (!string.IsNullOrEmpty(str)) { return str.SafePersianEncode().RemoveNoise() .Replace((char)8204, (char)32) .TrimStart() .TrimEnd(); } return str; } public static string ToRightISIN(this string isin) { return isin.Replace("IRO", "IRR").Replace("0001", "0101"); } public static string ToStockISIN(this string isin) { return isin.Replace("IRR", "IRO").Replace("0101", "0001"); } public static string RemoveNoise(this string str) { if (string.IsNullOrEmpty(str)) { return string.Empty; } return str.Replace("‏", ""); } public static string ToSimpleSymbol(this string symbol) { char last = symbol[symbol.Length - 1]; if (last == '1') return symbol.Remove(symbol.Length - 1); else { return symbol; } } public static decimal ToPercentage(this decimal value,int round) { return Math.Round(value * 100, round); } public static bool IsRight(this string isin) { return isin.StartsWith("IRR"); } /// <summary> /// برای سلف متفاوت خواهد بود /// </summary> /// <param name="str"></param> /// <returns></returns> /// public static bool IsProductBond(this string str) { if (!string.IsNullOrEmpty(str)) { return str.StartsWith("IRB") && !str.StartsWith("IRBE") && !str.StartsWith("IRBK"); } return false; } /// <summary> ///آیا سلف می باشد؟ /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsProductForward(this string str) { if (!string.IsNullOrEmpty(str)) { return str.StartsWith("IRBE") || str.StartsWith("IRBK"); } return false; } } }
{ "content_hash": "2e88b42d03b33fdb29a49003c9794f90", "timestamp": "", "source": "github", "line_count": 248, "max_line_length": 117, "avg_line_length": 31.31451612903226, "alnum_prop": 0.47437548287406645, "repo_name": "MostafaEsmaeili/DOOOZestan", "id": "093cadb9d69fc6c9f037c0c878c8bb2dabb86d54", "size": "7815", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BackEnd/Core/Common/Src/ِDoozestan.Common/Util/AmberUtil.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "208" }, { "name": "C#", "bytes": "1476160" }, { "name": "CSS", "bytes": "731732" }, { "name": "HTML", "bytes": "81408" }, { "name": "JavaScript", "bytes": "392523" }, { "name": "PowerShell", "bytes": "25003" } ], "symlink_target": "" }
package com.aspose.slides.examples.charts; import com.aspose.slides.*; import com.aspose.slides.examples.RunExamples; public class SetCategoryAxisLabelDistance { public static void main(String[] args) { //ExStart:SetCategoryAxisLabelDistance // The path to the documents directory. String dataDir = RunExamples.getDataDir_Charts(); Presentation presentation = new Presentation(); try { // Get reference of the slide ISlide sld = presentation.getSlides().get_Item(0); // Adding a chart on slide IChart ch = sld.getShapes().addChart(ChartType.ClusteredColumn, 20, 20, 500, 300); // Setting the position of label from axis ch.getAxes().getHorizontalAxis().setLabelOffset(500); // Write the presentation file to disk presentation.save(dataDir + "SetCategoryAxisLabelDistance_out.pptx", SaveFormat.Pptx); } finally { if (presentation != null) presentation.dispose(); } //ExEnd:SetCategoryAxisLabelDistance } }
{ "content_hash": "3062fdc081344e064004dfc1ae1b97cf", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 98, "avg_line_length": 31.11111111111111, "alnum_prop": 0.6330357142857143, "repo_name": "asposeslides/Aspose_Slides_Java", "id": "4e0e336ad4f48a18e015f752f05b992abe02a78f", "size": "1120", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Examples/src/main/java/com/aspose/slides/examples/charts/SetCategoryAxisLabelDistance.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "17962" }, { "name": "Java", "bytes": "344919" }, { "name": "PHP", "bytes": "146397" }, { "name": "Python", "bytes": "132116" }, { "name": "Ruby", "bytes": "166824" } ], "symlink_target": "" }
package com.intellij.openapi.actionSystem.ex; import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.ide.HelpTooltip; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.ListPopup; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.WindowManager; import com.intellij.ui.UserActivityProviderComponent; import com.intellij.util.ui.*; import com.intellij.util.ui.accessibility.ScreenReader; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; public abstract class ComboBoxAction extends AnAction implements CustomComponentAction { private static Icon myIcon = null; private static Icon myDisabledIcon = null; private static Icon myWin10ComboDropTriangleIcon = null; public static Icon getArrowIcon(boolean enabled) { if (UIUtil.isUnderWin10LookAndFeel()) { if (myWin10ComboDropTriangleIcon == null) { myWin10ComboDropTriangleIcon = IconLoader.findLafIcon("win10/comboDropTriangle", ComboBoxAction.class, true); } return myWin10ComboDropTriangleIcon; } Icon icon = UIUtil.isUnderDarcula() ? AllIcons.General.ComboArrow : AllIcons.General.ComboBoxButtonArrow; if (myIcon != icon) { myIcon = icon; myDisabledIcon = IconLoader.getDisabledIcon(myIcon); } return enabled ? myIcon : myDisabledIcon; } private boolean mySmallVariant = true; private String myPopupTitle; protected ComboBoxAction() { } @Override public void actionPerformed(AnActionEvent e) { Project project = e.getProject(); if (project == null) return; JFrame frame = WindowManager.getInstance().getFrame(project); if (!(frame instanceof IdeFrame)) return; ListPopup popup = createActionPopup(e.getDataContext(), ((IdeFrame)frame).getComponent(), null); popup.showCenteredInCurrentWindow(project); } @NotNull private ListPopup createActionPopup(@NotNull DataContext context, @NotNull JComponent component, @Nullable Runnable disposeCallback) { DefaultActionGroup group = createPopupActionGroup(component, context); ListPopup popup = JBPopupFactory.getInstance().createActionGroupPopup( myPopupTitle, group, context, false, shouldShowDisabledActions(), false, disposeCallback, getMaxRows(), getPreselectCondition()); popup.setMinimumSize(new Dimension(getMinWidth(), getMinHeight())); return popup; } @Override public JComponent createCustomComponent(Presentation presentation) { JPanel panel = new JPanel(new GridBagLayout()); ComboBoxButton button = createComboBoxButton(presentation); panel.add(button, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH, JBUI.insets(0, 3), 0, 0)); return panel; } protected ComboBoxButton createComboBoxButton(Presentation presentation) { return new ComboBoxButton(presentation); } public boolean isSmallVariant() { return mySmallVariant; } public void setSmallVariant(boolean smallVariant) { mySmallVariant = smallVariant; } public void setPopupTitle(String popupTitle) { myPopupTitle = popupTitle; } protected boolean shouldShowDisabledActions() { return false; } @NotNull protected abstract DefaultActionGroup createPopupActionGroup(JComponent button); @NotNull protected DefaultActionGroup createPopupActionGroup(JComponent button, @NotNull DataContext dataContext) { return createPopupActionGroup(button); } protected int getMaxRows() { return 30; } protected int getMinHeight() { return 1; } protected int getMinWidth() { return 1; } protected class ComboBoxButton extends JButton implements UserActivityProviderComponent { private final Presentation myPresentation; private boolean myForcePressed = false; private PropertyChangeListener myButtonSynchronizer; public ComboBoxButton(Presentation presentation) { myPresentation = presentation; setModel(new MyButtonModel()); getModel().setEnabled(myPresentation.isEnabled()); setVisible(presentation.isVisible()); setHorizontalAlignment(LEFT); setFocusable(ScreenReader.isActive()); putClientProperty("styleCombo", ComboBoxAction.this); setMargin(JBUI.insets(0, 5, 0, 2)); if (isSmallVariant()) { setFont(JBUI.Fonts.toolbarSmallComboBoxFont()); } //noinspection HardCodedStringLiteral addMouseListener(new MouseAdapter() { @Override public void mousePressed(final MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { e.consume(); doClick(); } } }); addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { mouseMoved(MouseEventAdapter.convert(e, e.getComponent(), MouseEvent.MOUSE_MOVED, e.getWhen(), e.getModifiers() | e.getModifiersEx(), e.getX(), e.getY())); } }); } @Override protected void fireActionPerformed(ActionEvent event) { if (!myForcePressed) { IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> showPopup()); } } @NotNull private Runnable setForcePressed() { myForcePressed = true; repaint(); return () -> { // give the button a chance to handle action listener ApplicationManager.getApplication().invokeLater(() -> { myForcePressed = false; repaint(); }, ModalityState.any()); repaint(); fireStateChanged(); }; } @Nullable @Override public String getToolTipText() { return myForcePressed || Registry.is("ide.helptooltip.enabled") ? null : super.getToolTipText(); } public void showPopup() { JBPopup popup = createPopup(setForcePressed()); if (Registry.is("ide.helptooltip.enabled")) { HelpTooltip.setMasterPopup(this, popup); } popup.showUnderneathOf(this); } protected JBPopup createPopup(Runnable onDispose) { return createActionPopup(getDataContext(), this, onDispose); } protected DataContext getDataContext() { return DataManager.getInstance().getDataContext(this); } @Override public void removeNotify() { if (myButtonSynchronizer != null) { myPresentation.removePropertyChangeListener(myButtonSynchronizer); myButtonSynchronizer = null; } super.removeNotify(); } @Override public void addNotify() { super.addNotify(); if (myButtonSynchronizer == null) { myButtonSynchronizer = new MyButtonSynchronizer(); myPresentation.addPropertyChangeListener(myButtonSynchronizer); } initButton(); } private void initButton() { setIcon(myPresentation.getIcon()); setText(myPresentation.getText()); updateTooltipText(myPresentation.getDescription()); updateButtonSize(); } private void updateTooltipText(String description) { String tooltip = KeymapUtil.createTooltipText(description, ComboBoxAction.this); if (Registry.is("ide.helptooltip.enabled") && StringUtil.isNotEmpty(tooltip)) { HelpTooltip.dispose(this); new HelpTooltip().setDescription(tooltip).setLocation(HelpTooltip.Alignment.BOTTOM).installOn(this); } else { setToolTipText(!tooltip.isEmpty() ? tooltip : null); } } protected class MyButtonModel extends DefaultButtonModel { @Override public boolean isPressed() { return myForcePressed || super.isPressed(); } @Override public boolean isArmed() { return myForcePressed || super.isArmed(); } } private class MyButtonSynchronizer implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if (Presentation.PROP_TEXT.equals(propertyName)) { setText((String)evt.getNewValue()); updateButtonSize(); } else if (Presentation.PROP_DESCRIPTION.equals(propertyName)) { updateTooltipText((String)evt.getNewValue()); } else if (Presentation.PROP_ICON.equals(propertyName)) { setIcon((Icon)evt.getNewValue()); updateButtonSize(); } else if (Presentation.PROP_ENABLED.equals(propertyName)) { setEnabled(((Boolean)evt.getNewValue()).booleanValue()); } } } @Override public boolean isOpaque() { return !isSmallVariant(); } @Override public Dimension getPreferredSize() { Dimension prefSize = super.getPreferredSize(); int width = prefSize.width + (myPresentation != null && isArrowVisible(myPresentation) ? getArrowIcon(isEnabled()).getIconWidth() : 0) + (StringUtil.isNotEmpty(getText()) ? getIconTextGap() : 0) + (UIUtil.isUnderWin10LookAndFeel() ? JBUI.scale(6) : 0); Dimension size = new Dimension(width, isSmallVariant() ? JBUI.scale(24) : Math.max(JBUI.scale(24), prefSize.height)); JBInsets.addTo(size, getMargin()); return size; } @Override public Dimension getMinimumSize() { return new Dimension(super.getMinimumSize().width, getPreferredSize().height); } @Override public Font getFont() { return isSmallVariant() ? UIUtil.getToolbarFont() : UIUtil.getLabelFont(); } @Override protected Graphics getComponentGraphics(Graphics graphics) { return JBSwingUtilities.runGlobalCGTransform(this, super.getComponentGraphics(graphics)); } @Override public void paint(Graphics g) { super.paint(g); if (!isArrowVisible(myPresentation)) { return; } Icon icon = getArrowIcon(isEnabled()); int x = getWidth() - icon.getIconWidth() - getInsets().right - getMargin().right - (UIUtil.isUnderWin10LookAndFeel() ? JBUI.scale(3) : 0); // Different icons correction icon.paintIcon(null, g, x, (getHeight() - icon.getIconHeight()) / 2); } protected boolean isArrowVisible(@NotNull Presentation presentation) { return true; } @Override public void updateUI() { super.updateUI(); setMargin(JBUI.insets(0, 5, 0, 2)); updateButtonSize(); } protected void updateButtonSize() { invalidate(); repaint(); setSize(getPreferredSize()); repaint(); } } protected Condition<AnAction> getPreselectCondition() { return null; } }
{ "content_hash": "74669d0f342227ac1443fda23c3980bc", "timestamp": "", "source": "github", "line_count": 350, "max_line_length": 136, "avg_line_length": 33.02571428571429, "alnum_prop": 0.678259364996972, "repo_name": "jk1/intellij-community", "id": "fc251ce311fa341d464682d8dfe9f5fcbe486b08", "size": "11700", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "platform/platform-api/src/com/intellij/openapi/actionSystem/ex/ComboBoxAction.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8" ?> <lom:lom xmlns="https://ocw.mit.edu/xmlns/LOM" xmlns:lom="https://ocw.mit.edu/xmlns/LOM" xmlns:ocwlom="https://ocw.mit.edu/xmlns/ocwLOM" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://ocw.mit.edu/xmlns/LOM https://ocw.mit.edu/xsd/LOM/lomv1.0/lomv1.0.xsd https://ocw.mit.edu/xmlns/ocwLOM https://ocw.mit.edu/xsd/ocwLOM/ocwlomv1.0/ocwlomv1.0.xsd"> <!--************************************************************ This LOM record was produced by an automatic transformation to IEEE LOM, from OpenCourseWare's (OCW) initial version of Learning Object Metadata (LOM). (The initial version was based on IMS Global Consortium's LOM.) ********************************************************--> <!--***************************--> <!--**** GENERAL ****--> <!--***************************--> <lom:general uniqueElementName="general"> <lom:title uniqueElementName="title"> <lom:string language="en">Lecture 9 Summary</lom:string> </lom:title> <lom:description> <lom:string language="en"></lom:string> </lom:description> <lom:language>en</lom:language> <lom:aggregationLevel uniqueElementName="aggregationLevel"> <lom:source uniqueElementName="source">LOMv1.0</lom:source> <lom:value uniqueElementName="value">3</lom:value> </lom:aggregationLevel> </lom:general> <!--***************************--> <!--**** LIFECYCLE ****--> <!--***************************--> <lom:lifeCycle uniqueElementName="lifeCycle"> <lom:version uniqueElementName="version"> <lom:string language="en">Fall 2010</lom:string> </lom:version> <lom:contribute> <lom:role> <lom:source uniqueElementName="source">OCW_LOMv1.0</lom:source> <lom:value uniqueElementName="value">Author</lom:value> </lom:role> <lom:entity>Johnson, Steven G.</lom:entity> <lom:date uniqueElementName="date"> <lom:dateTime uniqueElementName="dateTime">2017-11-2</lom:dateTime> </lom:date> </lom:contribute> </lom:lifeCycle> <!--***************************--> <!--**** TECHNICAL ****--> <!--***************************--> <lom:technical uniqueElementName="technical"> <lom:location>/courses/mathematics/18-335j-introduction-to-numerical-methods-fall-2010/lecture-notes/lecture-9-summary/index.htm</lom:location> <lom:requirement> <lom:orComposite> <lom:type uniqueElementName="type"> <lom:source uniqueElementName="source">LOMv1.0</lom:source> <lom:value uniqueElementName="value">Browser</lom:value> </lom:type> <lom:name uniqueElementName="name"> <lom:source uniqueElementName="source">LOMv1.0</lom:source> <lom:value uniqueElementName="value">Chrome</lom:value> </lom:name> <lom:minimumVersion uniqueElementName="minimumVersion">40.0</lom:minimumVersion> </lom:orComposite> <lom:orComposite> <lom:type uniqueElementName="type"> <lom:source uniqueElementName="source">LOMv1.0</lom:source> <lom:value uniqueElementName="value">Browser</lom:value> </lom:type> <lom:name uniqueElementName="name"> <lom:source uniqueElementName="source">LOMv1.0</lom:source> <lom:value uniqueElementName="value">Safari</lom:value> </lom:name> <lom:minimumVersion uniqueElementName="minimumVersion">8.0</lom:minimumVersion> </lom:orComposite> <lom:orComposite> <lom:type uniqueElementName="type"> <lom:source uniqueElementName="source">LOMv1.0</lom:source> <lom:value uniqueElementName="value">Browser</lom:value> </lom:type> <lom:name uniqueElementName="name"> <lom:source uniqueElementName="source">LOMv1.0</lom:source> <lom:value uniqueElementName="value">Mozilla Firefox</lom:value> </lom:name> <lom:minimumVersion uniqueElementName="minimumVersion">38.0</lom:minimumVersion> </lom:orComposite> <lom:orComposite> <lom:type uniqueElementName="type"> <lom:source uniqueElementName="source">LOMv1.0</lom:source> <lom:value uniqueElementName="value">Browser</lom:value> </lom:type> <lom:name uniqueElementName="name"> <lom:source uniqueElementName="source">LOMv1.0</lom:source> <lom:value uniqueElementName="value">Internet Explorer</lom:value> </lom:name> <lom:minimumVersion uniqueElementName="minimumVersion">9.0</lom:minimumVersion> </lom:orComposite> <lom:orComposite> <lom:type uniqueElementName="type"> <lom:source uniqueElementName="source">LOMv1.0</lom:source> <lom:value uniqueElementName="value">Browser</lom:value> </lom:type> <lom:name uniqueElementName="name"> <lom:source uniqueElementName="source">LOMv1.0</lom:source> <lom:value uniqueElementName="value">Edge</lom:value> </lom:name> <lom:minimumVersion uniqueElementName="minimumVersion">13.1</lom:minimumVersion> </lom:orComposite> </lom:requirement> </lom:technical> <!--***************************--> <!--**** EDUCATIONAL ****--> <!--***************************--> <lom:educational> <lom:context> <lom:source uniqueElementName="source">OCW_LOMv1.0</lom:source> <lom:value uniqueElementName="value">Graduate</lom:value> </lom:context> </lom:educational> <!--***************************--> <!--**** RIGHTS ****--> <!--***************************--> <lom:rights uniqueElementName="rights"> <lom:copyrightAndOtherRestrictions uniqueElementName="copyrightAndOtherRestrictions"> <lom:source uniqueElementName="source">LOMv1.0</lom:source> <lom:value uniqueElementName="value">yes</lom:value> </lom:copyrightAndOtherRestrictions> <lom:description> <lom:string language="en">This site (c) Massachusetts Institute of Technology 2017. Content within individual courses is (c) by the individual authors unless otherwise noted. The Massachusetts Institute of Technology is providing this Work (as defined below) under the terms of this Creative Commons public license ("CCPL" or "license") unless otherwise noted. The Work is protected by copyright and/or other applicable law. Any use of the work other than as authorized under this license is prohibited. By exercising any of the rights to the Work provided here, You (as defined below) accept and agree to be bound by the terms of this license. The Licensor, the Massachusetts Institute of Technology, grants You the rights contained here in consideration of Your acceptance of such terms and conditions.</lom:string> </lom:description> </lom:rights> <!--***************************--> <!--**** RELATION ****--> <!--***************************--> <lom:relation> <lom:kind uniqueElementName="kind"> <lom:source uniqueElementName="source">LOMv1.0</lom:source> <lom:value uniqueElementName="value">ispartof</lom:value> </lom:kind> <lom:resource uniqueElementName="resource"> <lom:identifier> <lom:catalog uniqueElementName="catalog">OCW Master Course Number</lom:catalog> <lom:entry uniqueElementName="entry">18.335J Introduction to Numerical Methods Fall 2010</lom:entry> </lom:identifier> <lom:description> <lom:string language="en">This course offers an advanced introduction to numerical linear algebra. Topics include direct and iterative methods for linear systems, eigenvalue decompositions and QR/SVD factorizations, stability and accuracy of numerical algorithms, the IEEE floating point standard, sparse and structured matrices, preconditioning, linear algebra software. Problem sets require some knowledge of MATLAB&amp;reg;.</lom:string> </lom:description> </lom:resource> </lom:relation> <!--***************************--> <!--**** CLASSIFICATION ****--> <!--***************************--> <lom:classification> <lom:taxonPath> <lom:source uniqueElementName="source"> <lom:string language="en">CIP</lom:string> </lom:source> <lom:taxon> <lom:id uniqueElementName="id">270102</lom:id> <lom:entry uniqueElementName="entry"> <lom:string language="en"></lom:string> </lom:entry> </lom:taxon> </lom:taxonPath> </lom:classification> </lom:lom>
{ "content_hash": "bf09bc6358dcd62cdf55685ab1c0e261", "timestamp": "", "source": "github", "line_count": 172, "max_line_length": 830, "avg_line_length": 54.13953488372093, "alnum_prop": 0.5730240549828178, "repo_name": "miguelraz/PathToPerformance", "id": "9bfa765676a1c43ac460389f5e5f5cfd546e4b7e", "size": "9312", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "coursestodo/18.335-introtonumericalmethods-sgj/18-335j-fall-2010/contents/lecture-notes/lecture-9-summary/index.htm.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "1526" }, { "name": "C", "bytes": "107617" }, { "name": "C++", "bytes": "314160" }, { "name": "CSS", "bytes": "172291" }, { "name": "HTML", "bytes": "1509500" }, { "name": "JavaScript", "bytes": "260729" }, { "name": "Julia", "bytes": "61425" }, { "name": "Jupyter Notebook", "bytes": "4126812" }, { "name": "M", "bytes": "101" }, { "name": "Makefile", "bytes": "2766" }, { "name": "Matlab", "bytes": "5266" }, { "name": "Objective-C", "bytes": "242" }, { "name": "Python", "bytes": "4249" }, { "name": "TeX", "bytes": "16463" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Coq bench</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../../..">Unstable</a></li> <li><a href=".">dev / contrib:tortoise-hare-algorithm 8.4.dev</a></li> <li class="active"><a href="">2014-12-04 06:17:00</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="../../../../../about.html">About</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href=".">« Up</a> <h1> contrib:tortoise-hare-algorithm <small> 8.4.dev <span class="label label-info">Not compatible with this Coq</span> </small> </h1> <p><em><script>document.write(moment("2014-12-04 06:17:00 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2014-12-04 06:17:00 UTC)</em><p> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>ruby lint.rb unstable ../unstable/packages/coq:contrib:tortoise-hare-algorithm/coq:contrib:tortoise-hare-algorithm.8.4.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> <dt>Output</dt> <dd><pre>The package is valid. </pre></dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --dry-run coq:contrib:tortoise-hare-algorithm.8.4.dev coq.dev</code></dd> <dt>Return code</dt> <dd>768</dd> <dt>Duration</dt> <dd>0 s</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is dev). Your request can&#39;t be satisfied: - No package matches coq:contrib:tortoise-hare-algorithm. No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq, to test if the problem was incompatibility with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --dry-run coq:contrib:tortoise-hare-algorithm.8.4.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>3 s</dd> <dt>Output</dt> <dd><pre>The following actions will be performed: - remove coq.dev === 1 to remove === =-=- Removing Packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Removing coq.dev. [WARNING] Directory /home/bench/.opam/system/lib/coq is not empty, not removing The following actions will be performed: - install coq.8.4.dev [required by coq:contrib:tortoise-hare-algorithm] - install coq:contrib:tortoise-hare-algorithm.8.4.dev === 2 to install === =-=- Synchronizing package archives -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= =-=- Installing packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Building coq.8.4.dev: ./configure -configdir /home/bench/.opam/system/lib/coq/config -mandir /home/bench/.opam/system/man -docdir /home/bench/.opam/system/doc -prefix /home/bench/.opam/system -usecamlp5 -camlp5dir /home/bench/.opam/system/lib/camlp5 -coqide no make -j4 make install Installing coq.8.4.dev. Building coq:contrib:tortoise-hare-algorithm.8.4.dev: coq_makefile -f Make -o Makefile make -j4 make install Installing coq:contrib:tortoise-hare-algorithm.8.4.dev. </pre></dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "983f0649c197b1accd733abd8930fbae", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 240, "avg_line_length": 41.74698795180723, "alnum_prop": 0.5093795093795094, "repo_name": "coq-bench/coq-bench.github.io-old", "id": "3b91b2e76342c3d7eb8593419862a6044ea81802", "size": "6932", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.02.1-1.2.0/unstable/dev/contrib:tortoise-hare-algorithm/8.4.dev/2014-12-04_06-17-00.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
// // INameRecognizer.h // CardRecognizer // // Created by Vladimir Tchernitski on 08/02/16. // Copyright © 2016 Vladimir Tchernitski. All rights reserved. // #ifndef INameRecognizer_h #define INameRecognizer_h #include "IBaseObj.h" #include "Enums.h" class INeuralNetworkResultList; class IRecognitionCoreDelegate; using namespace std; class INameRecognizer : public IBaseObj { public: virtual ~INameRecognizer() {} public: virtual shared_ptr<INeuralNetworkResultList> Process(cv::Mat& frame, vector<cv::Mat>& samples, std::string& postprocessedName) = 0; virtual bool Deploy() = 0; virtual void SetRecognitionMode(PayCardsRecognizerMode flag) = 0; virtual void SetDelegate(const shared_ptr<IRecognitionCoreDelegate>& delegate) = 0; virtual void SetPathNameYLocalizationViola(const string& path) = 0; virtual void SetPathNameLocalizationXModel(const string& path) = 0; virtual void SetPathNameLocalizationXStruct(const string& path) = 0; virtual void SetPathNameSpaceCharModel(const string& path) = 0; virtual void SetPathNameSpaceCharStruct(const string& path) = 0; virtual void SetPathNameListTxt(const string& path) = 0; }; #endif /* INameRecognizer_h */
{ "content_hash": "7b6483fe0930b73403a0f3fcf50c840f", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 135, "avg_line_length": 26.25, "alnum_prop": 0.726984126984127, "repo_name": "zalexej/PayCards_iOS_Source", "id": "c3277a1cfba278a066a2d45c66b012e8ece4b79f", "size": "1261", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PayCardsRecognizer/CrossPlatform/Include/Recognizer/INameRecognizer.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "269553" }, { "name": "C++", "bytes": "8697780" }, { "name": "CMake", "bytes": "7012" }, { "name": "Objective-C", "bytes": "179051" }, { "name": "Objective-C++", "bytes": "44022" }, { "name": "Ruby", "bytes": "726" }, { "name": "Shell", "bytes": "1870" }, { "name": "Swift", "bytes": "7352" } ], "symlink_target": "" }
- Use JDBC connection pooling By default the pool has a size of 10 and a timeout of 30s to acquire a connection. These settings can be changed with the following configuration properties: - `org.osiam.resource-server.db.maximum-pool-size` - `org.osiam.resource-server.db.connection-timeout-ms` - Populate the `type` field of a `Group`'s members Members of a `Group` have their `type` field set to either `User` or `Group`. - Make number of parallel connections to the auth-server configurable The default is 40 and can be changed with the following configuration property: - `org.osiam.auth-server.connector.max-connections` - Make timeouts of connections to auth-server configurable By default the read timeout is set to 10000ms and the connect timeout to 5000ms. These settings can be changed with the following configuration properties: - `org.osiam.auth-server.connector.read-timeout-ms` - `org.osiam.auth-server.connector.connect-timeout-ms` ### Changes - Increase default timeouts for connections to auth-server By default the read timeout is set to 10000ms and the connect timeout to 5000ms. - Increase default maximum number of parallel connections to auth-server The default is 40. - Switch to Spring Boot - Refactor database schema **Note:** Some fields in table `scim_extension_field` have been renamed: - `extension_internal_id` becomes `extension`; - `is_required` becomes `required`; Update your SQL scripts, if you add SCIM 2 extensions via direct database manipulation. - Produce a meaningful log message and respond with `503 TEMPORARILY UNAVAILABLE` instead of `409 CONFLICT` if the auth-server cannot be reached to validate or revoke an access token. - All invalid search queries now respond with a `400 BAD REQUEST` instead of `409 CONFLICT` status code. - Respond with `401 UNAUTHORIZED` when revoking or validating an access token fails because of invalid access token. - Remove configuration property `org.osiam.resource-server.db.dialect` - Remove self written profiling solution since we now use the [Metrics](https://github.com/dropwizard/metrics) framework. This removes the configuration property `org.osiam.resource-server.profiling` - Make the generated errors SCIM compliant Error responses look like this according to [Scim 2](http://tools.ietf.org/html/rfc7644): { "schemas": ["urn:ietf:params:scim:api:messages:2.0:Error"], "detail": "Resource 2819c223-7f76-453a-919d-413861904646 not found", "status": "404" } ### Fixes - Only set `UserEntity#active` if value is not null Prevents a NPE when storing users that have no value for the `active` field. - Use correct schema for Scim resources Affected resources and the changes are: - `User`: `urn:scim:schemas:core:2.0:User` becomes `urn:ietf:params:scim:schemas:core:2.0:User` - `Group`: `urn:scim:schemas:core:2.0:Group` becomes `urn:ietf:params:scim:schemas:core:2.0:Group` - `ListResponse`: `urn:scim:schemas:core:2.0:User`/`urn:scim:schemas:core:2.0:Group` becomes `urn:ietf:params:scim:api:messages:2.0:ListResponse` - `ServiceProviderConfig`: `urn:scim:schemas:core:2.0:ServiceProviderConfig` becomes `urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig` ### Updates - OSIAM connector4java 1.8 - MySQL JDBC driver 5.1.37 - PostgreSQL JDBC driver 9.4-1205 - AspectJ 1.8.7 - Metrics Spring Integration 3.1.2 ## 2.4 Skipped to synchronize OSIAM main version with versions of the core servers ## 2.3 - 2015-10-09 Revoked, see 2.5 ## 2.2 - 2015-06-18 ### Changes - Bump connector to make use of more concurrent HTTP connections ## 2.1 - 2015-06-02 ### Features - Support for new `ME` scope - Support for new `ADMIN` scope ### Fixes - Secure search endpoint on `/` - PostalCode should not be retrieved as literal `null` string when not set ### Other - resource-server now lives in its own Git repo - Changed artifact id from `osiam-resource-server` to `resource-server` ## 2.0 - 2015-04-29 **Breaking changes!** This release introduces breaking changes, due to the introduction of automatic database schema updates powered by Flyway. See the [migration notes](docs/Migration.md#from-13x-to-20) for further details. - [feature] Support automatic database migrations - [feature] create JAR containing the classes of app - [fix] lower constraint index lengths for MySQL - [fix] replace Windows line endings with Unix ones in SQL scripts - [change] decrease default verbosity - [change] bump dependency versions - [docs] move documentation from Wiki to repo - [docs] rename file RELEASE.NOTES to CHANGELOG.md ## 1.3 - 2014-10-17 - [fix] Infinite recursion when filtering or sorting by x509certivicates.value - [fix] Sorting by name sub-attribute breaks the result list For a detailed description and migration see: https://github.com/osiam/server/wiki/Migration#from-12-to-13 ## 1.2 - 2014-09-30 - [feature] Introduced an interface to get the extension definitions (/osiam/extension-definition) ## 1.1 - 2014-09-19 - [feature] support for mysql as database - [enhancement] Force UTF-8 encoding of requests and responses - [enhancement] better error message on search When searching for resources and forgetting the surrounding double quotes for values, a non-understandable error message was responded. the error message was changed to explicitly tell that the error occurred due to missing double quotes. - [enhancement] updated dependencies: Spring 4.1.0, Spring Security 3.2.5, Spring Metrics 3.0.2, Jackson 2.4.2, Hibernate 4.3.6, AspectJ 1.8.2, Joda Time 2.4, Joda Convert 1.7, Apache Commons Logging 1.2, Guava 18.0, Postgres JDBC Driver 9.3-1102-jdbc41
{ "content_hash": "5ca52db1df204b1f7b7aeab62ad17536", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 150, "avg_line_length": 34.04117647058823, "alnum_prop": 0.7411439433212372, "repo_name": "osiam/resource-server", "id": "45f0d81427cfb4f1dc6fc31f59b538cc4d4b54d0", "size": "5847", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CHANGELOG.md", "mode": "33188", "license": "mit", "language": [ { "name": "ANTLR", "bytes": "1447" }, { "name": "Groovy", "bytes": "246575" }, { "name": "Java", "bytes": "468018" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <View android:layout_width="match_parent" android:layout_height="1px" android:background="#1A000000" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/cover" android:layout_width="match_parent" android:layout_height="280dp" android:src="@drawable/cover_background" android:scaleType="fitXY" /> <ImageView android:id="@+id/live_logo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="12dp" android:layout_marginTop="10dp" android:src="@drawable/icon_livewhite" /> </RelativeLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="55dp" android:background="@color/colorPrimary" android:orientation="horizontal"> <ImageView android:id="@+id/avatar" android:layout_width="45dp" android:layout_height="45dp" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:layout_marginLeft="15dp" android:layout_gravity="center_vertical" android:focusable="false" android:focusableInTouchMode="false" android:src="@drawable/icon_tab_profile_default" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginLeft="14dp" android:orientation="vertical"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="4dp" android:orientation="horizontal"> <TextView android:id="@+id/live_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/colorGray6" android:text="Live_title" android:textSize="@dimen/h10" /> <TextView android:id="@+id/host_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/colorTextG3" android:layout_marginLeft="15dp" android:text="\@host_name" android:textSize="@dimen/h6"/> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="2dp" android:gravity="center_vertical" android:orientation="horizontal"> <TextView android:id="@+id/live_members" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="1000" android:drawableLeft="@drawable/icon_visitors" android:drawablePadding="5dp" android:layout_gravity="center" android:textSize="@dimen/h6" android:textColor="@color/colorTextG3" /> <TextView android:id="@+id/praises" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:text="1000" android:drawableLeft="@drawable/icon_red_hearts" android:drawablePadding="10dp" android:layout_gravity="center" android:textSize="@dimen/h6" android:textColor="@color/colorGray4" /> <TextView android:id="@+id/live_lbs" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:drawableLeft="@drawable/position_red" android:drawablePadding="5dp" android:text="new york" android:textSize="@dimen/h6" android:textColor="@color/colorTextG3" /> </LinearLayout> </LinearLayout> </LinearLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="#1A000000" /> </LinearLayout>
{ "content_hash": "0c5f20e4137da2be2f00fad74fe644b1", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 72, "avg_line_length": 38.06716417910448, "alnum_prop": 0.5347970986081161, "repo_name": "456838/usefulCode", "id": "7d4f46b5a004c086a46e229bfb971d31a4c1f924", "size": "5101", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "YHamburgGit/app/src/main/res/layout/item_liveshow.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "6258" }, { "name": "HTML", "bytes": "245591" }, { "name": "Java", "bytes": "1498326" }, { "name": "Python", "bytes": "454881" }, { "name": "Shell", "bytes": "10632" } ], "symlink_target": "" }
/** * $Id: ActionKeysMappings.java 2 2005-06-30 12:47:28Z yaric $ */ package ng.games.bombman.screens; import javax.microedition.lcdui.Canvas; /** * Nokia 3650 specific. * * Holds constants to define action keys mappings. * <p>Company: NewGround</p> * @author Yaroslav Omelyanenko * @version 1.0 */ public interface ActionKeysMappings { // // Additional action keys mappings // public static final int GAME_KEY_LEFT = Canvas.KEY_NUM2; public static final int GAME_KEY_RIGHT = Canvas.KEY_STAR; public static final int GAME_KEY_UP = Canvas.KEY_NUM1; public static final int GAME_KEY_DOWN = Canvas.KEY_NUM3; public static final int GAME_KEY_FIRE = Canvas.KEY_POUND; }
{ "content_hash": "14157fe6226b4741b01743de1fc63e1f", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 62, "avg_line_length": 27.53846153846154, "alnum_prop": 0.6941340782122905, "repo_name": "yaricom/bombman-RL-AI-J2ME", "id": "253bb7062aa94cadb473045987c6c7313def1d26", "size": "716", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/specific/3650/ng/games/bombman/screens/ActionKeysMappings.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "501621" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="zh"> <head> <link href="http://gmpg.org/xfn/11" rel="profile"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <!-- Enable responsiveness on mobile devices--> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1"> <title>Shajiquan's Island - sqlalchemy</title> <!-- CSS --> <link href="//fonts.googleapis.com/" rel="dns-prefetch"> <link href="//fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic|Abril+Fatface|PT+Sans:400,400italic,700&amp;subset=latin,latin-ext" rel="stylesheet"> <link href="//cdn.bootcss.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="/theme/css/style.min.css?6b1824bf"> <script src="/theme/js/jquery-2.1.4.min.js"></script> <link rel="icon" type="image/x-icon" href="/static/images/hugme.png"> <link rel="apple-touch-icon" sizes="57x57" href="/static/images/hugme.png"> <link rel="apple-touch-icon" sizes="114x114" href="/static/images/hugme.png"> <link rel="apple-touch-icon" sizes="72x72" href="/static/images/hugme.png"> <link rel="apple-touch-icon" sizes="144x144" href="/static/images/hugme.png"> <!-- RSS --> <link rel="alternate" type="application/rss+xml" title="RSS" href="https://shajiquan.com/feed.xml"> <script type="text/javascript"> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-66785549-2', 'auto'); ga('send', 'pageview'); </script> </head> <body class="layout-reverse"> <div id="sidebar" class="sidebar"> <div class="container sidebar-sticky-no"> <div class="sidebar-header-menus"> <nav class="sidebar-nav sidebar-menus"> <a class="sidebar-nav-item" href="/" title="Home">Home</a> <a class="sidebar-nav-item" href="/about" title="About">About</a> </nav> </div> <div class="sidebar-about"> <a href="/" title="shajiquan: 欢迎来到沙吉泉之岛。岛上居民有蟒蛇、地鼠、大象...当然,还有我..."> <img id="profile-picture" class="profile-picture" src="/static/images/hugme.png"> <h1>Shajiquan's Island</h1> </a> <p class="lead"></p> <p class="lead">欢迎来到沙吉泉之岛。岛上居民有蟒蛇、地鼠、大象...当然,还有我... </p> </div> <div class="sidebar-box clearfix hidden-xs"> <!-- <h3 class="hidden-xs"><i class="fa fa-list-ul "></i></i></h3> --> <nav class="sidebar-nav"> <a class="sidebar-nav-item" href="https://github.com/shajiquan" title="github"> <i class="fa fa-github"></i> </a> <a class="sidebar-nav-item" href="https://twitter.com/shajiquan" title="twitter"> <i class="fa fa-twitter"></i> </a> <a class="sidebar-nav-item" href="https://weibo.com/shajiquan" title="weibo"> <i class="fa fa-weibo"></i> </a> <a class="sidebar-nav-item" href="feed.xml"> <i class="fa fa-feed"></i> </a> <a class="sidebar-nav-item" href="https://shajiquan.com/about" title="More about..."> <i class="fa fa-plus-circle"></i> </a> </nav> </div> <div class="clearfix sidebar-box copyright hidden-xs hidden-sm text-muted small"> <p class="lead"></p> <p class="lead"></p> <p class="text-muted small">© 2016. All rights reserved.</p> <p class="small text-muted">Powered by <a class="text-muted" href="https://github.com/shajiquan/pelican-hyde-theme">Pelican with Hyde Theme</a>.</p> </div> </div> </div> <div class="content container"> <div class="page-heading"> <h1>Posts in Tag: sqlalchemy</h1> <small class="archive-description text-muted tag-description">sqlalchemy</small> <div class="clearfix"> <small class="text-muted clearfix"> <a href='/tag'>All Tags</a> </small> </div> </div> <div class="posts"> <div class="post"> <h2 class="post-title" href="https://shajiquan.com/2014/12/message-system-sql-schema-sqlalchemy/#message-system-sql-schema-sqlalchemy"> <a href="https://shajiquan.com/2014/12/message-system-sql-schema-sqlalchemy/">私信系统的数据库设计及业务处理 - Sqlalchemy 版</a> </h2> <span class="post-date"> 2014-12-21 in <a href="https://shajiquan.com/category/qa" title="Q & A 系列文章是我在 Segmentfault 等社区的回答。发在 Blog 时可能略做调整。">问与答</a>, with tags: <a href="https://shajiquan.com/tag/python/">python</a>, <a href="https://shajiquan.com/tag/sql/">sql</a>, <a href="https://shajiquan.com/tag/database/">database</a>, <a href="https://shajiquan.com/tag/sqlalchemy/">sqlalchemy</a>, </span> </div> </div> <div class="copyright-footer text-center"> <div class="clearfix sidebar-box copyright text-muted small hidden-sm hidden-lg hidden-md"> <p class="lead"></p> <p class="text-muted small">© 2016. All rights reserved.</p> <p class="small text-muted">Powered by <a class="text-muted" href="https://github.com/shajiquan/pelican-hyde-theme">Pelican with Hyde Theme</a>.</p> </div> </div> </div> </body> <script> $(document).ready(function(){ console.log('from-blog',$(window).width()); }); </script> </html>
{ "content_hash": "047bc8a153f8fd06fc86b2b0ba847b41", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 163, "avg_line_length": 38.54347826086956, "alnum_prop": 0.6410979507426208, "repo_name": "shajiquan/shajiquan.github.io", "id": "7cb2ee611894c88d43a8bf609297c4640ff15e9b", "size": "5523", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tag/sqlalchemy/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "23358" }, { "name": "HTML", "bytes": "447064" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="sq-AL"> <title>TLS Debug | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
{ "content_hash": "a89b7d4b75cb5915a19996ce664412e3", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 146, "avg_line_length": 24.897435897435898, "alnum_prop": 0.6374871266735325, "repo_name": "zapbot/zap-extensions", "id": "ffad774dfff3373464d5a6c5a3599306c72422c5", "size": "971", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "addOns/tlsdebug/src/main/javahelp/org/zaproxy/zap/extension/tlsdebug/resources/help_sq_AL/helpset_sq_AL.hs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "29979" }, { "name": "HTML", "bytes": "6653830" }, { "name": "Haskell", "bytes": "1533212" }, { "name": "Java", "bytes": "10514059" }, { "name": "JavaScript", "bytes": "160056" }, { "name": "Kotlin", "bytes": "80437" }, { "name": "Python", "bytes": "26411" }, { "name": "Ruby", "bytes": "16551" }, { "name": "XSLT", "bytes": "78761" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World, Acceleration!</string> <string name="app_name">Acceleration</string> <string name="Button01_str">Press! </string> </resources>
{ "content_hash": "f50e886d2b2b8d98df86bc3648f2b048", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 60, "avg_line_length": 37.333333333333336, "alnum_prop": 0.6785714285714286, "repo_name": "SvenKratz/three-dollar-gesture-recognizer", "id": "0b4e58a8e0a998ad680a9ee7afc49293dff86eb5", "size": "224", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "android/Acceleration (3DollarGestureRecognizer)/res/values/strings.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "69028" }, { "name": "Objective-C", "bytes": "124243" }, { "name": "Python", "bytes": "48995" } ], "symlink_target": "" }
@interface TGConversationAddMemberRequestActor () @property (nonatomic) int uid; @end @implementation TGConversationAddMemberRequestActor @synthesize uid = _uid; + (NSString *)genericPath { return @"/tg/conversation/@/addMember/@"; } - (void)execute:(NSDictionary *)options { NSNumber *nConversationId = [options objectForKey:@"conversationId"]; NSNumber *nUid = [options objectForKey:@"uid"]; if (nConversationId == nil || nUid == nil) { [ActionStageInstance() actionFailed:self.path reason:-1]; } _uid = [nUid intValue]; self.cancelToken = [TGTelegraphInstance doAddConversationMember:[nConversationId longLongValue] uid:[nUid intValue] actor:self]; } - (void)addMemberSuccess:(TLmessages_StatedMessage *)statedMessage { [TGUserDataRequestBuilder executeUserDataUpdate:statedMessage.users]; TGConversation *chatConversation = nil; if (statedMessage.chats.count != 0) { NSMutableDictionary *chats = [[NSMutableDictionary alloc] init]; TGMessage *message = [[TGMessage alloc] initWithTelegraphMessageDesc:statedMessage.message]; for (TLChat *chatDesc in statedMessage.chats) { TGConversation *conversation = [[TGConversation alloc] initWithTelegraphChatDesc:chatDesc]; if (conversation != nil) { if (chatConversation == nil) { chatConversation = conversation; TGConversation *oldConversation = [TGDatabaseInstance() loadConversationWithId:chatConversation.conversationId]; chatConversation.chatParticipants = [oldConversation.chatParticipants copy]; if ([chatDesc isKindOfClass:[TLChat$chat class]]) { chatConversation.chatParticipants.version = ((TLChat$chat *)chatDesc).version; chatConversation.chatVersion = ((TLChat$chat *)chatDesc).version; } if (![chatConversation.chatParticipants.chatParticipantUids containsObject:@(_uid)]) { NSMutableArray *newUids = [[NSMutableArray alloc] initWithArray:chatConversation.chatParticipants.chatParticipantUids]; [newUids addObject:@(_uid)]; chatConversation.chatParticipants.chatParticipantUids = newUids; NSMutableDictionary *newInvitedBy = [[NSMutableDictionary alloc] initWithDictionary:chatConversation.chatParticipants.chatInvitedBy]; [newInvitedBy setObject:@(TGTelegraphInstance.clientUserId) forKey:@(_uid)]; chatConversation.chatParticipants.chatInvitedBy = newInvitedBy; NSMutableDictionary *newInvitedDates = [[NSMutableDictionary alloc] initWithDictionary:chatConversation.chatParticipants.chatInvitedDates]; [newInvitedDates setObject:@(message.date) forKey:@(_uid)]; chatConversation.chatParticipants.chatInvitedDates = newInvitedDates; } conversation = chatConversation; } [chats setObject:conversation forKey:[[NSNumber alloc] initWithLongLong:conversation.conversationId]]; } } static int actionId = 0; [[[TGConversationAddMessagesActor alloc] initWithPath:[[NSString alloc] initWithFormat:@"/tg/addmessage/(addMember%d)", actionId++] ] execute:[[NSDictionary alloc] initWithObjectsAndKeys:chats, @"chats", @[message], @"messages", nil]]; } [[TGTelegramNetworking instance] updatePts:statedMessage.pts date:0 seq:statedMessage.seq]; int version = chatConversation.chatVersion; NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; [dict setObject:[[NSNumber alloc] initWithInt:version] forKey:@"conversationVersion"]; [dict setObject:[NSNumber numberWithInt:_uid] forKey:@"uid"]; [ActionStageInstance() actionCompleted:self.path result:[[SGraphObjectNode alloc] initWithObject:dict]]; } - (void)addMemberFailed:(int)reason { [ActionStageInstance() actionFailed:self.path reason:reason]; } @end
{ "content_hash": "4fd8bae481e247c99dac00ec8d83530c", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 243, "avg_line_length": 43.254901960784316, "alnum_prop": 0.6316863100634633, "repo_name": "DZamataev/TelegramAppKit", "id": "c450b3af73a32a2f2ec09d2dc0fdf09dbfecc3ff", "size": "4724", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "Telegram-2.8/Telegraph/Telegraph/TGConversationAddMemberRequestActor.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6466296" }, { "name": "C++", "bytes": "459710" }, { "name": "Mathematica", "bytes": "3121" }, { "name": "Objective-C", "bytes": "5824211" }, { "name": "Objective-C++", "bytes": "4427056" }, { "name": "Python", "bytes": "38234" }, { "name": "Ruby", "bytes": "1736" }, { "name": "Shell", "bytes": "29947" } ], "symlink_target": "" }
<?php /** * ContactsTest * * PHP version 5 * * @category Class * @package SidneyAllen\XeroPHP * @author OpenAPI Generator team * @link https://openapi-generator.tech */ /** * Accounting API * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2.0.0 * Contact: api@xero.com * Generated by: https://openapi-generator.tech * OpenAPI Generator version: 3.3.4 */ /** * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Please update the test case below to test the model. */ namespace SidneyAllen\XeroPHP; /** * ContactsTest Class Doc Comment * * @category Class * @description Contacts * @package SidneyAllen\XeroPHP * @author OpenAPI Generator team * @link https://openapi-generator.tech */ class ContactsTest extends \PHPUnit_Framework_TestCase { /** * Setup before running any test case */ public static function setUpBeforeClass() { } /** * Setup before running each test case */ public function setUp() { } /** * Clean up after running each test case */ public function tearDown() { } /** * Clean up after running all test cases */ public static function tearDownAfterClass() { } /** * Test "Contacts" */ public function testContacts() { } /** * Test attribute "contacts" */ public function testPropertyContacts() { } }
{ "content_hash": "c87eb6104beb0e157ae207941b262b22", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 109, "avg_line_length": 18.847058823529412, "alnum_prop": 0.6260923845193508, "repo_name": "unaio/una", "id": "7a24de8a8ab84a5ad30f606a5ad385b848793a1f", "size": "1602", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/boonex/xero/plugins/xeroapi/xero-php-oauth2/test/Model/ContactsTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9522763" }, { "name": "Dockerfile", "bytes": "2367" }, { "name": "HTML", "bytes": "6194660" }, { "name": "JavaScript", "bytes": "24733694" }, { "name": "Less", "bytes": "3020615" }, { "name": "Makefile", "bytes": "1196" }, { "name": "PHP", "bytes": "158741504" }, { "name": "Ruby", "bytes": "210" }, { "name": "Shell", "bytes": "3327" }, { "name": "Smarty", "bytes": "3461" } ], "symlink_target": "" }
<script src="js/menuSetup.js"></script> <script src="js/dynamicPopup.js"></script>
{ "content_hash": "8928e9f061ab59fe9567761186daeafd", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 50, "avg_line_length": 49.5, "alnum_prop": 0.5959595959595959, "repo_name": "pontual/kitweb", "id": "a92491e43da3ba9a0bbcb35e3c958013a26ca0aa", "size": "99", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "v2/public/last_js_scripts.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "48192" }, { "name": "HTML", "bytes": "63137" }, { "name": "JavaScript", "bytes": "38470" }, { "name": "PHP", "bytes": "169501" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "b226919960fda6de2c95a3822cf96a51", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "22d5d6d089227ebbf4f7426e493d72b4b9575d5f", "size": "192", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Malvaceae/Sida/Sida diffusa/Sida diffusa setosa/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
jest.autoMockOff(); // 关闭自动模拟数据 describe('collection utilities module', function() { var CollectionUtils = require('../collectionutils'); var collectionTweetsMock = { collectionTweet7: {}, collectionTweet8: {}, collectionTweet9: {} }; it('return a number of tweets in collection', function() { var actualNumberOfTweetsInCollection = CollectionUtils.getNumberOfTweetsInCollection(collectionTweetsMock); var expectedNumberOfTweetsInCollection = 3; expect(actualNumberOfTweetsInCollection).toBe(expectedNumberOfTweetsInCollection); }); it('checks if collection is not empty', function() { var isCollectionEmpty = CollectionUtils.isEmptyCollection(collectionTweetsMock); expect(isCollectionEmpty).toBeDefined(); expect(isCollectionEmpty).toBe(false); expect(isCollectionEmpty).not.toBe(true); }); });
{ "content_hash": "6ae1d0da522b1b581bc4f3400cf9a10a", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 109, "avg_line_length": 41.15, "alnum_prop": 0.778857837181045, "repo_name": "xincyang/snapterest-react", "id": "9c2285b828b30e881f3941bb39602d4155f097f2", "size": "839", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/utils/__tests__/collectionutils-test.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "192" }, { "name": "JavaScript", "bytes": "981979" } ], "symlink_target": "" }
package com.blackducksoftware.integration.jira.web.model; import java.io.Serializable; import java.util.Arrays; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.apache.commons.lang3.StringUtils; import com.synopsys.integration.util.Stringable; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class BlackDuckServerConfigSerializable extends Stringable implements Serializable { private static final long serialVersionUID = -8136935284749275566L; @XmlElement private String testConnectionError; @XmlElement private String hubUrl; @XmlElement private String hubUrlError; @XmlElement private String timeout; @XmlElement private String timeoutError; @XmlElement private String apiToken; private int apiTokenLength; @XmlElement private String apiTokenError; @XmlElement private Boolean trustCert; @XmlElement private String trustCertError; @XmlElement private String hubProxyHost; @XmlElement private String hubProxyHostError; @XmlElement private String hubProxyPort; @XmlElement private String hubProxyPortError; @XmlElement private String hubProxyUser; @XmlElement private String hubProxyUserError; @XmlElement private String hubProxyPassword; @XmlElement private String hubProxyPasswordError; private int hubProxyPasswordLength; public BlackDuckServerConfigSerializable() { } public BlackDuckServerConfigSerializable(final BlackDuckServerConfigSerializable blackDuckServerConfigSerializable) { this.hubUrl = blackDuckServerConfigSerializable.getHubUrl(); this.timeout = blackDuckServerConfigSerializable.getTimeout(); this.apiToken = blackDuckServerConfigSerializable.getApiToken(); this.trustCert = Boolean.valueOf(blackDuckServerConfigSerializable.getTrustCert()); this.hubProxyHost = blackDuckServerConfigSerializable.getHubProxyHost(); this.hubProxyPort = blackDuckServerConfigSerializable.getHubProxyPort(); this.hubProxyUser = blackDuckServerConfigSerializable.getHubProxyUser(); this.hubProxyPassword = blackDuckServerConfigSerializable.getHubProxyPassword(); this.hubProxyPasswordLength = blackDuckServerConfigSerializable.getHubProxyPasswordLength(); } public static String getMaskedString(final int length) { if (length == 0) { return null; } final char[] array = new char[length]; Arrays.fill(array, '*'); return new String(array); } public boolean hasErrors() { boolean hasErrors = false; if (StringUtils.isNotBlank(getHubUrlError())) { hasErrors = true; } else if (StringUtils.isNotBlank(getTimeoutError())) { hasErrors = true; } else if (StringUtils.isNotBlank(getTrustCertError())) { hasErrors = true; } else if (StringUtils.isNotBlank(getApiTokenError())) { hasErrors = true; } else if (StringUtils.isNotBlank(getTestConnectionError())) { hasErrors = true; } else if (StringUtils.isNotBlank(getHubProxyHostError())) { hasErrors = true; } else if (StringUtils.isNotBlank(getHubProxyPortError())) { hasErrors = true; } else if (StringUtils.isNotBlank(getHubProxyUserError())) { hasErrors = true; } else if (StringUtils.isNotBlank(getHubProxyPasswordError())) { hasErrors = true; } return hasErrors; } public String getMaskedProxyPassword() { return getMaskedString(hubProxyPasswordLength); } public boolean isProxyPasswordMasked() { return isStringMasked(hubProxyPassword); } public String getMaskedApiToken() { return getMaskedString(apiTokenLength); } public boolean isApiTokenMasked() { return isStringMasked(apiToken); } private boolean isStringMasked(final String value) { if (StringUtils.isBlank(value)) { return false; } final String masked = getMaskedString(value.length()); if (value.equals(masked)) { return true; } return false; } public String getHubUrl() { return hubUrl; } public void setHubUrl(final String hubUrl) { this.hubUrl = hubUrl; } public String getHubUrlError() { return hubUrlError; } public void setHubUrlError(final String hubUrlError) { this.hubUrlError = hubUrlError; } public String getTimeout() { return timeout; } public void setTimeout(final String timeout) { this.timeout = timeout; } public String getTimeoutError() { return timeoutError; } public void setTimeoutError(final String timeoutError) { this.timeoutError = timeoutError; } public String getTrustCert() { return trustCert != null ? trustCert.toString() : Boolean.FALSE.toString(); } public void setTrustCert(final String trustCert) { if (trustCert != null) { setTrustCert(Boolean.parseBoolean(trustCert)); } else { setTrustCert(Boolean.FALSE); } } public void setTrustCert(final Boolean trustCert) { this.trustCert = trustCert; } public String getTrustCertError() { return trustCertError; } public void setTrustCertError(final String trustCertError) { this.trustCertError = trustCertError; } public String getApiToken() { return apiToken; } public void setApiToken(final String apiToken) { this.apiToken = apiToken; } public int getApiTokenLength() { return apiTokenLength; } public void setApiTokenLength(final int apiTokenLength) { this.apiTokenLength = apiTokenLength; } public String getApiTokenError() { return apiTokenError; } public void setApiTokenError(final String apiTokenError) { this.apiTokenError = apiTokenError; } public String getHubProxyHost() { return hubProxyHost; } public void setHubProxyHost(final String hubProxyHost) { this.hubProxyHost = hubProxyHost; } public String getHubProxyHostError() { return hubProxyHostError; } public void setHubProxyHostError(final String hubProxyHostError) { this.hubProxyHostError = hubProxyHostError; } public String getHubProxyPort() { return hubProxyPort; } public void setHubProxyPort(final String hubProxyPort) { this.hubProxyPort = hubProxyPort; } public String getHubProxyPortError() { return hubProxyPortError; } public void setHubProxyPortError(final String hubProxyPortError) { this.hubProxyPortError = hubProxyPortError; } public String getHubProxyUser() { return hubProxyUser; } public void setHubProxyUser(final String hubProxyUser) { this.hubProxyUser = hubProxyUser; } public String getHubProxyUserError() { return hubProxyUserError; } public void setHubProxyUserError(final String hubProxyUserError) { this.hubProxyUserError = hubProxyUserError; } public String getHubProxyPassword() { return hubProxyPassword; } public void setHubProxyPassword(final String hubProxyPassword) { this.hubProxyPassword = hubProxyPassword; } public String getHubProxyPasswordError() { return hubProxyPasswordError; } public void setHubProxyPasswordError(final String hubProxyPasswordError) { this.hubProxyPasswordError = hubProxyPasswordError; } public int getHubProxyPasswordLength() { return hubProxyPasswordLength; } public void setHubProxyPasswordLength(final int hubProxyPasswordLength) { this.hubProxyPasswordLength = hubProxyPasswordLength; } public String getTestConnectionError() { return testConnectionError; } public void setTestConnectionError(final String testConnectionError) { this.testConnectionError = testConnectionError; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("HubServerConfigSerializable [testConnectionError="); builder.append(testConnectionError); builder.append(", hubUrl="); builder.append(hubUrl); builder.append(", hubUrlError="); builder.append(hubUrlError); builder.append(", timeout="); builder.append(timeout); builder.append(", timeoutError="); builder.append(timeoutError); builder.append(", trustCert="); builder.append(trustCert); builder.append(", trustCertError="); builder.append(trustCertError); builder.append(", apiToken="); builder.append(apiToken); builder.append(", apiTokenError="); builder.append(apiTokenError); builder.append(", hubProxyHost="); builder.append(hubProxyHost); builder.append(", hubProxyHostError="); builder.append(hubProxyHostError); builder.append(", hubProxyPort="); builder.append(hubProxyPort); builder.append(", hubProxyPortError="); builder.append(hubProxyPortError); builder.append(", hubProxyUser="); builder.append(hubProxyUser); builder.append(", hubProxyUserError="); builder.append(hubProxyUserError); builder.append(", hubProxyPassword="); builder.append(hubProxyPassword); builder.append(", hubProxyPasswordError="); builder.append(hubProxyPasswordError); builder.append(", hubProxyPasswordLength="); builder.append(hubProxyPasswordLength); builder.append("]"); return builder.toString(); } }
{ "content_hash": "035fcd8fb8a96cdd12bd11329f903915", "timestamp": "", "source": "github", "line_count": 356, "max_line_length": 121, "avg_line_length": 28.314606741573034, "alnum_prop": 0.6743055555555556, "repo_name": "blackducksoftware/hub-jira", "id": "1879f0aa784d5e86a4937b3cd82e7a8ba55f9153", "size": "10980", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/blackducksoftware/integration/jira/web/model/BlackDuckServerConfigSerializable.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "142996" }, { "name": "Java", "bytes": "1217085" }, { "name": "JavaScript", "bytes": "70302" }, { "name": "Shell", "bytes": "1934" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>V8 API Reference Guide for node.js v9.0.0 - v9.1.0: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v9.0.0 - v9.1.0 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1TracingController.html">TracingController</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">v8::TracingController Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classv8_1_1TracingController.html">v8::TracingController</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1TracingController.html#ad1e234b340ea8f9f1e3386aa21dad5dd">AddTraceEvent</a>(char phase, const uint8_t *category_enabled_flag, const char *name, const char *scope, uint64_t id, uint64_t bind_id, int32_t num_args, const char **arg_names, const uint8_t *arg_types, const uint64_t *arg_values, std::unique_ptr&lt; ConvertableToTraceFormat &gt; *arg_convertables, unsigned int flags)</td><td class="entry"><a class="el" href="classv8_1_1TracingController.html">v8::TracingController</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1TracingController.html#a7b86361ffadff46018a348fd2aa01061">AddTraceStateObserver</a>(TraceStateObserver *)</td><td class="entry"><a class="el" href="classv8_1_1TracingController.html">v8::TracingController</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1TracingController.html#af3c0fcec8fe93b18a89392686cfedfe5">GetCategoryGroupEnabled</a>(const char *name)</td><td class="entry"><a class="el" href="classv8_1_1TracingController.html">v8::TracingController</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1TracingController.html#ab8d5b3ac795188effb423fa2c0514353">RemoveTraceStateObserver</a>(TraceStateObserver *)</td><td class="entry"><a class="el" href="classv8_1_1TracingController.html">v8::TracingController</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1TracingController.html#ac1fda6cdae5f6515b896b3df05d5a97e">UpdateTraceEventDuration</a>(const uint8_t *category_enabled_flag, const char *name, uint64_t handle)</td><td class="entry"><a class="el" href="classv8_1_1TracingController.html">v8::TracingController</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>~TracingController</b>()=default (defined in <a class="el" href="classv8_1_1TracingController.html">v8::TracingController</a>)</td><td class="entry"><a class="el" href="classv8_1_1TracingController.html">v8::TracingController</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.11 </small></address> </body> </html>
{ "content_hash": "edc4ff3b4946f8e46f204e7ccec31878", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 651, "avg_line_length": 62.4070796460177, "alnum_prop": 0.6799489506522972, "repo_name": "v8-dox/v8-dox.github.io", "id": "99c6615c5d6d888931c2c3d422b0eb49d457610e", "size": "7052", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "c087502/html/classv8_1_1TracingController-members.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package com.hazelcast.durableexecutor; import com.hazelcast.config.SplitBrainProtectionConfig; import com.hazelcast.core.DistributedObject; import javax.annotation.Nonnull; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; /** * Durable implementation of {@link ExecutorService}. * DurableExecutor provides additional methods like executing tasks on a member who is owner of a specific key * DurableExecutor also provides a way to retrieve the result of an execution with the given taskId. * * @see ExecutorService * <p> * Supports split brain protection {@link SplitBrainProtectionConfig} since 3.10 in cluster versions 3.10 and higher. */ public interface DurableExecutorService extends ExecutorService, DistributedObject { /** * Submits a value-returning task for execution and returns a * Future representing the pending results of the task. The * Future's {@code get} method will return the task's result upon * successful completion. * <p> * If you would like to immediately block waiting * for a task, you can use constructions of the form * {@code result = exec.submit(aCallable).get();} * <p>Note: The {@link Executors} class includes a set of methods * that can convert some other common closure-like objects, * for example, {@link java.security.PrivilegedAction} to * {@link Callable} form so they can be submitted. * * @param task the task to submit * @param <T> the type of the task's result * @return a Future representing pending completion of the task * @throws RejectedExecutionException if the task cannot be * scheduled for execution * @throws NullPointerException if the task is null */ @Nonnull <T> DurableExecutorServiceFuture<T> submit(@Nonnull Callable<T> task); /** * Submits a Runnable task for execution and returns a Future * representing that task. The Future's {@code get} method will * return the given result upon successful completion. * * @param task the task to submit * @param result the result to return * @param <T> the type of the result * @return a Future representing pending completion of the task * @throws RejectedExecutionException if the task cannot be * scheduled for execution * @throws NullPointerException if the task is null */ @Nonnull <T> DurableExecutorServiceFuture<T> submit(@Nonnull Runnable task, T result); /** * Submits a Runnable task for execution and returns a Future * representing that task. The Future's {@code get} method will * return {@code null} upon <em>successful</em> completion. * * @param task the task to submit * @return a Future representing pending completion of the task * @throws RejectedExecutionException if the task cannot be * scheduled for execution * @throws NullPointerException if the task is null */ @Override @Nonnull DurableExecutorServiceFuture<?> submit(@Nonnull Runnable task); /** * Retrieves the result with the given taskId * * @param taskId combination of partitionId and sequence * @param <T> the type of the task's result * @return a Future representing pending completion of the task */ <T> Future<T> retrieveResult(long taskId); /** * Disposes the result with the given taskId * * @param taskId combination of partitionId and sequence */ void disposeResult(long taskId); /** * Retrieves and disposes the result with the given taskId * * @param taskId combination of partitionId and sequence * @param <T> the type of the task's result * @return a Future representing pending completion of the task */ <T> Future<T> retrieveAndDisposeResult(long taskId); /** * Executes a task on the owner of the specified key. * * @param command a task executed on the owner of the specified key * @param key the specified key */ void executeOnKeyOwner(@Nonnull Runnable command, @Nonnull Object key); /** * Submits a task to the owner of the specified key and returns a Future * representing that task. * * @param task task submitted to the owner of the specified key * @param key the specified key * @param <T> the return type of the task * @return a Future representing pending completion of the task */ <T> DurableExecutorServiceFuture<T> submitToKeyOwner(@Nonnull Callable<T> task, @Nonnull Object key); /** * Submits a task to the owner of the specified key and returns a Future * representing that task. * * @param task task submitted to the owner of the specified key * @param key the specified key * @return a Future representing pending completion of the task */ DurableExecutorServiceFuture<?> submitToKeyOwner(@Nonnull Runnable task, @Nonnull Object key); }
{ "content_hash": "91c0243fa62605eea4056a6b0133d3e9", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 117, "avg_line_length": 39.40875912408759, "alnum_prop": 0.6636414150768661, "repo_name": "emre-aydin/hazelcast", "id": "7fd02a3496cffb0a461353e022f1e465367e1fa9", "size": "6024", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "hazelcast/src/main/java/com/hazelcast/durableexecutor/DurableExecutorService.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1261" }, { "name": "C", "bytes": "353" }, { "name": "Java", "bytes": "39634758" }, { "name": "Shell", "bytes": "29479" } ], "symlink_target": "" }
''' Cloudforms.TagManager ~~~~~~~~~~~~~~~~~~~~~~ Tag Manager :license: MIT, see LICENSE for more details. ''' from Cloudforms.utils import ( update_params, normalize_object, normalize_collection ) class ServiceTagManager(object): '''Manages Tags for Services. :param Cloudforms.API.Client client: an API client instance :param string svc: a service name to bind to ''' def __init__(self, client, svc): self.client = client self.svc = svc def assign(self, _id, names): '''Assigns one or more tags to a service :param string _id: Specifies which service item the request is for :param list names: Names of tags to assign (['/my/tag', '/a/tag']) Example:: # Add the tag /environment/prod to all providers for prov in prov_mgr.list_providers(): prov_mgr.tags.assign(prov.get('id'), [ '/environment/prod' ]) ''' self.client.call('post', '/%s/%s/tags' % (self.svc, _id), data={ 'action': 'assign', 'resources': [{'name': name} for name in names] }) def unassign(self, _id, names): '''Un-assigns one or more tags to a service :param string _id: Specifies which service item the request is for :param list names: Names of tags to un-assign (['/my/tag', '/a/tag']) Example:: # Removes the tag /environment/prod from all providers for prov in prov_mgr.list_providers(): prov_mgr.tags.unassign(prov.get('id'), [ '/environment/prod' ]) ''' self.client.call('post', '/%s/%s/tags' % (self.svc, _id), data={ 'action': 'unassign', 'resources': [{'name': name} for name in names] }) class TagManager(object): '''Manages Tags. :param Cloudforms.API.Client client: an API client instance Example:: import Cloudforms client = Cloudforms.Client() tag_mgr = Cloudforms.TagManager(client) ''' def __init__(self, client): self.client = client def get(self, _id, params=None): '''Retrieve details about a tag on the account :param string _id: Specifies which tag the request is for :param dict params: response-level options (attributes, limit, etc.) :returns: Dictionary representing the matching tag Example:: # Gets a list of all tags (returns IDs only) tags = tag_mgr.list({'attributes': 'id'}) for tag in tags: tag_details = tag_mgr.get(tag['id']) ''' params = update_params(params, {'expand': 'resources'}) return normalize_object( self.client.call('get', '/tags/%s' % _id, params=params)) def list(self, params=None): '''Retrieve a list of all tags on the account :param dict params: response-level options (attributes, limit, etc.) :returns: List of dictionaries representing the matching tags Example:: # Gets a list of all tags (returns IDs only) tags = tag_mgr.list({'attributes': 'id'}) ''' params = update_params(params, {'expand': 'resources'}) return normalize_collection( self.client.call('get', '/tags', params=params))
{ "content_hash": "f13feb93b4b4dcc16461aaca9bdddb1e", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 77, "avg_line_length": 31.201834862385322, "alnum_prop": 0.5642458100558659, "repo_name": "01000101/python-cloudforms", "id": "f9b96bb979b540fc57f4e517c4bcb0ecaef4d856", "size": "3401", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Cloudforms/managers/tag.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "33667" } ], "symlink_target": "" }
from os.path import join from django.db import models, connection from django.utils.text import slugify class BaseModel(models.Model): """ Todos los modelos deben heredar de esta clase. """ class Meta: abstract = True creado_el = models.DateTimeField(verbose_name=u"Fecha de creación", auto_now_add=True) modificado_el = models.DateTimeField(verbose_name=u"Fecha de modificación", auto_now=True) def uploadTenantFilename(basepath, instance, filename): """ Helper to upload files in FileField fields with multitenant support To use in FiledField argument 'upload_to': upload_to=partial(uploadFilename, basepath ) Where basepath is the path where the file will save. @param basepath: Base path to save the file (list or string) @param instance: Model instance @param filename: The filename that was originally given to the file. @return: string with file path. """ if isinstance(basepath, str): # Converts to lowercase, removes non-word characters # (alphanumerics and underscores) and converts spaces # to hyphens. Also strips leading and trailing whitespace. basepath = slugify(basepath) else: # if basepath is a list basepath = join(*map(slugify, basepath)) return join(connection.tenant.domain_url, basepath, filename)
{ "content_hash": "ed2d6af3d468cb1ae2c0928770d45c14", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 79, "avg_line_length": 33.095238095238095, "alnum_prop": 0.6913669064748201, "repo_name": "mava-ar/sgk", "id": "5beef2859543f4d2065172b2109c8cfc72a8f651", "size": "1392", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/dj_utils/models.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "20411" }, { "name": "HTML", "bytes": "81338" }, { "name": "JavaScript", "bytes": "34107" }, { "name": "Python", "bytes": "197385" }, { "name": "Shell", "bytes": "1349" } ], "symlink_target": "" }
GOPKGNAME = github.com/yahoo/athenz/libs/go/ztsroletoken PKG_DATE=$(shell date '+%Y-%m-%dT%H:%M:%S') BINARY=ztsroletoken FMT_LOG=/tmp/ztsroletoken-fmt.log IMPORTS_LOG=/tmp/ztsroletoken-imports.log # check to see if go utility is installed GO := $(shell command -v go 2> /dev/null) export GOPATH=$(PWD) ifdef GO # we need to make sure we have go 1.7+ # the output for the go version command is: # go version go1.7.3 darwin/amd64 GO_VER_GTEQ7 := $(shell expr `go version | cut -f 3 -d' ' | cut -f2 -d.` \>= 7) ifneq "$(GO_VER_GTEQ7)" "1" all: @echo "Please install 1.7.x or newer version of golang" else .PHONY: source vet fmt imports build test all: source vet fmt imports build test endif else all: @echo "go is not available please install golang" endif # we need to build the ztsroletoken with the local copy # of zts-go-client so that any changes can be reflected # right away. So we are going to copy the source directories # into our source tree and compile them source: @echo "Cleanup up local GOPATH src directory..." rm -rf src @echo "Setting up the source code..." mkdir -p /tmp/ztsroletoken-build/src/$(GOPKGNAME) cp -r * /tmp/ztsroletoken-build/src/$(GOPKGNAME)/. mv /tmp/ztsroletoken-build/src . @echo "Copying local source files..." mkdir -p $(GOPATH)/src/github.com/yahoo/athenz/clients/go cp -r ../../../clients/go/zts $(GOPATH)/src/github.com/yahoo/athenz/clients/go mkdir -p $(GOPATH)/src/github.com/yahoo/athenz/libs/go cp -r ../../../libs/go/zmssvctoken $(GOPATH)/src/github.com/yahoo/athenz/libs/go @echo "Getting dependency packages..." go get -t -d -tags testing $(GOPKGNAME)/... vet: go vet $(GOPKGNAME)/... # we are going to verify our library fmt: go list $(GOPKGNAME)/... | sed "s:^:$(GOPATH)/src/:" | xargs gofmt -d >$(FMT_LOG) @if [ -s $(FMT_LOG) ]; then echo gofmt FAIL; cat $(FMT_LOG); false; fi # we are going to verify our library imports: go get golang.org/x/tools/cmd/goimports go list $(GOPKGNAME)/... | sed "s:^:$(GOPATH)/src/:" | xargs $(GOPATH)/bin/goimports -d >$(IMPORTS_LOG) @if [ -s $(IMPORTS_LOG) ]; then echo goimports FAIL; cat $(IMPORTS_LOG); false; fi build: @echo "Building ztsroletoken library..." go install -v $(GOPKGNAME)/... test: go test -v $(GOPKGNAME)/... clean: rm -rf target src bin pkg /tmp/ztsroletoken-build $(FMT_LOG) $(IMPORTS_LOG)
{ "content_hash": "36404cef892e8b6e75a3684473470487", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 104, "avg_line_length": 30.736842105263158, "alnum_prop": 0.6875, "repo_name": "tatyano/athenz", "id": "ed4d74b8c6890aa9f03dfd8e063d848dab10dfdf", "size": "2568", "binary": false, "copies": "1", "ref": "refs/heads/tatyano", "path": "libs/go/ztsroletoken/Makefile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "42737" }, { "name": "Go", "bytes": "716990" }, { "name": "HTML", "bytes": "32049" }, { "name": "Java", "bytes": "5109892" }, { "name": "JavaScript", "bytes": "488664" }, { "name": "Makefile", "bytes": "32516" }, { "name": "Perl", "bytes": "951" }, { "name": "Shell", "bytes": "41610" } ], "symlink_target": "" }
namespace Alamut.Data.Entity { /// <summary> /// provides language based contract for Entity /// </summary> public interface IMultiLanguageEnity { string Lang { get; set; } } }
{ "content_hash": "78d96e2be1e49b73cf416d2ed36cb198", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 51, "avg_line_length": 21, "alnum_prop": 0.6047619047619047, "repo_name": "SorenZ/Alamut", "id": "351370bdd03eef7fcaee14c49a1c51d4d275beeb", "size": "212", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Alamut.Data/Entity/IMultiLanguageEnity.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "128940" }, { "name": "PowerShell", "bytes": "13708" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "580f185353d192183b4e87f16282d3ce", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "b5bc1d27cfaadab0002fc8e1b475a374b4cf95f0", "size": "191", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Liliales/Melanthiaceae/Trillium/Trillium grandiflorum/ Syn. Trillium grandiflorum minimum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
@interface OADottedLine : NSView { } @end
{ "content_hash": "152aa8ccfcf228477128cd2e0def5678", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 32, "avg_line_length": 8.6, "alnum_prop": 0.6976744186046512, "repo_name": "thekarladam/fluidium", "id": "4f6598cb70188831d112cf20442b977a674b897d", "size": "405", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Fluidium/lib/OmniGroup/Frameworks/OmniAppKit/Widgets.subproj/OADottedLine.h", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using logging::LOG_WARNING; using std::vector; using testing::HasSubstr; using testing::Message; using testing::_; namespace net { namespace test { class RttStatsTest : public ::testing::Test { protected: RttStats rtt_stats_; }; TEST_F(RttStatsTest, DefaultsBeforeUpdate) { EXPECT_LT(0u, rtt_stats_.initial_rtt_us()); EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.min_rtt()); EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.smoothed_rtt()); } TEST_F(RttStatsTest, SmoothedRtt) { // Verify that ack_delay is corrected for in Smoothed RTT. rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(300), QuicTime::Delta::FromMilliseconds(100), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.latest_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.smoothed_rtt()); // Verify that effective RTT of zero does not change Smoothed RTT. rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(200), QuicTime::Delta::FromMilliseconds(200), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.latest_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.smoothed_rtt()); // Verify that large erroneous ack_delay does not change Smoothed RTT. rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(200), QuicTime::Delta::FromMilliseconds(300), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.latest_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.smoothed_rtt()); } TEST_F(RttStatsTest, PreviousSmoothedRtt) { // Verify that ack_delay is corrected for in Smoothed RTT. rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(300), QuicTime::Delta::FromMilliseconds(100), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.latest_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.smoothed_rtt()); EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.previous_srtt()); // Ensure the previous SRTT is 200ms after a 100ms sample. rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(100), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(100), rtt_stats_.latest_rtt()); EXPECT_EQ(QuicTime::Delta::FromMicroseconds(187500).ToMicroseconds(), rtt_stats_.smoothed_rtt().ToMicroseconds()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.previous_srtt()); } TEST_F(RttStatsTest, MinRtt) { rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(200), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.min_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.WindowedMinRtt()); rtt_stats_.UpdateRtt( QuicTime::Delta::FromMilliseconds(10), QuicTime::Delta::Zero(), QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(10)); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.WindowedMinRtt()); rtt_stats_.UpdateRtt( QuicTime::Delta::FromMilliseconds(50), QuicTime::Delta::Zero(), QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(20)); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.WindowedMinRtt()); rtt_stats_.UpdateRtt( QuicTime::Delta::FromMilliseconds(50), QuicTime::Delta::Zero(), QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(30)); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.WindowedMinRtt()); rtt_stats_.UpdateRtt( QuicTime::Delta::FromMilliseconds(50), QuicTime::Delta::Zero(), QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(40)); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.WindowedMinRtt()); // Verify that ack_delay does not go into recording of min_rtt_. rtt_stats_.UpdateRtt( QuicTime::Delta::FromMilliseconds(7), QuicTime::Delta::FromMilliseconds(2), QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(50)); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(7), rtt_stats_.min_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(7), rtt_stats_.WindowedMinRtt()); } TEST_F(RttStatsTest, WindowedMinRtt) { rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(10), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.WindowedMinRtt()); rtt_stats_.SampleNewWindowedMinRtt(4); for (int i = 0; i < 3; ++i) { rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(50), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.WindowedMinRtt()); } rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(50), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(50), rtt_stats_.WindowedMinRtt()); } TEST_F(RttStatsTest, ExpireSmoothedMetrics) { QuicTime::Delta initial_rtt = QuicTime::Delta::FromMilliseconds(10); rtt_stats_.UpdateRtt(initial_rtt, QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_EQ(initial_rtt, rtt_stats_.min_rtt()); EXPECT_EQ(initial_rtt, rtt_stats_.WindowedMinRtt()); EXPECT_EQ(initial_rtt, rtt_stats_.smoothed_rtt()); EXPECT_EQ(0.5 * initial_rtt, rtt_stats_.mean_deviation()); // Update once with a 20ms RTT. QuicTime::Delta doubled_rtt = 2 * initial_rtt; rtt_stats_.UpdateRtt(doubled_rtt, QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_EQ(1.125 * initial_rtt, rtt_stats_.smoothed_rtt()); // Expire the smoothed metrics, increasing smoothed rtt and mean deviation. rtt_stats_.ExpireSmoothedMetrics(); EXPECT_EQ(doubled_rtt, rtt_stats_.smoothed_rtt()); EXPECT_EQ(0.875 * initial_rtt, rtt_stats_.mean_deviation()); // Now go back down to 5ms and expire the smoothed metrics, and ensure the // mean deviation increases to 15ms. QuicTime::Delta half_rtt = 0.5 * initial_rtt; rtt_stats_.UpdateRtt(half_rtt, QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_GT(doubled_rtt, rtt_stats_.smoothed_rtt()); EXPECT_LT(initial_rtt, rtt_stats_.mean_deviation()); } TEST_F(RttStatsTest, UpdateRttWithBadSendDeltas) { // Make sure we ignore bad RTTs. base::test::MockLog log; QuicTime::Delta initial_rtt = QuicTime::Delta::FromMilliseconds(10); rtt_stats_.UpdateRtt(initial_rtt, QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_EQ(initial_rtt, rtt_stats_.min_rtt()); EXPECT_EQ(initial_rtt, rtt_stats_.WindowedMinRtt()); EXPECT_EQ(initial_rtt, rtt_stats_.smoothed_rtt()); vector<QuicTime::Delta> bad_send_deltas; bad_send_deltas.push_back(QuicTime::Delta::Zero()); bad_send_deltas.push_back(QuicTime::Delta::Infinite()); bad_send_deltas.push_back(QuicTime::Delta::FromMicroseconds(-1000)); log.StartCapturingLogs(); for (QuicTime::Delta bad_send_delta : bad_send_deltas) { SCOPED_TRACE(Message() << "bad_send_delta = " << bad_send_delta.ToMicroseconds()); EXPECT_CALL(log, Log(LOG_WARNING, _, _, _, HasSubstr("Ignoring"))); rtt_stats_.UpdateRtt(bad_send_delta, QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_EQ(initial_rtt, rtt_stats_.min_rtt()); EXPECT_EQ(initial_rtt, rtt_stats_.WindowedMinRtt()); EXPECT_EQ(initial_rtt, rtt_stats_.smoothed_rtt()); } } TEST_F(RttStatsTest, ResetAfterConnectionMigrations) { rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(300), QuicTime::Delta::FromMilliseconds(100), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.latest_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.smoothed_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(300), rtt_stats_.min_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(300), rtt_stats_.WindowedMinRtt()); // Reset rtt stats on connection migrations. rtt_stats_.OnConnectionMigration(); EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.latest_rtt()); EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.smoothed_rtt()); EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.min_rtt()); EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.WindowedMinRtt()); } } // namespace test } // namespace net
{ "content_hash": "366035f51aaf13b98195085fdf8b7404", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 80, "avg_line_length": 47.84574468085106, "alnum_prop": 0.6808226792662591, "repo_name": "danakj/chromium", "id": "6848e9b8f31b2f4b8c2b0629272a9e34c52ce516", "size": "9429", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "net/quic/core/congestion_control/rtt_stats_test.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
@interface LiveVC : UIViewController @end
{ "content_hash": "518951a435a3643915cb548bd3be0c0f", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 36, "avg_line_length": 14.333333333333334, "alnum_prop": 0.7906976744186046, "repo_name": "qinting513/Learning-QT", "id": "de815b7e1080050843f63a8f8662377f349de920", "size": "197", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "2016 Plan/10月/家居的面试题/Decoration 2/Decoration/Controller/LiveVC.h", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1773653" }, { "name": "C++", "bytes": "616556" }, { "name": "CSS", "bytes": "14772" }, { "name": "DTrace", "bytes": "6180" }, { "name": "HTML", "bytes": "780741" }, { "name": "JavaScript", "bytes": "60127" }, { "name": "Objective-C", "bytes": "32993916" }, { "name": "Objective-C++", "bytes": "135277" }, { "name": "Ruby", "bytes": "8377" }, { "name": "Shell", "bytes": "272766" }, { "name": "Swift", "bytes": "2330800" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns:msxsl="urn:schemas-microsoft-com:xslt"> <head> <meta content="en-us" http-equiv="Content-Language" /> <meta content="text/html; charset=utf-16" http-equiv="Content-Type" /> <title _locid="PortabilityAnalysis0">.NET Portability Report</title> <style> /* Body style, for the entire document */ body { background: #F3F3F4; color: #1E1E1F; font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 0; margin: 0; } /* Header1 style, used for the main title */ h1 { padding: 10px 0px 10px 10px; font-size: 21pt; background-color: #E2E2E2; border-bottom: 1px #C1C1C2 solid; color: #201F20; margin: 0; font-weight: normal; } /* Header2 style, used for "Overview" and other sections */ h2 { font-size: 18pt; font-weight: normal; padding: 15px 0 5px 0; margin: 0; } /* Header3 style, used for sub-sections, such as project name */ h3 { font-weight: normal; font-size: 15pt; margin: 0; padding: 15px 0 5px 0; background-color: transparent; } h4 { font-weight: normal; font-size: 12pt; margin: 0; padding: 0 0 0 0; background-color: transparent; } /* Color all hyperlinks one color */ a { color: #1382CE; } /* Paragraph text (for longer informational messages) */ p { font-size: 10pt; } /* Table styles */ table { border-spacing: 0 0; border-collapse: collapse; font-size: 10pt; } table th { background: #E7E7E8; text-align: left; text-decoration: none; font-weight: normal; padding: 3px 6px 3px 6px; } table td { vertical-align: top; padding: 3px 6px 5px 5px; margin: 0px; border: 1px solid #E7E7E8; background: #F7F7F8; } .NoBreakingChanges { color: darkgreen; font-weight:bold; } .FewBreakingChanges { color: orange; font-weight:bold; } .ManyBreakingChanges { color: red; font-weight:bold; } .BreakDetails { margin-left: 30px; } .CompatMessage { font-style: italic; font-size: 10pt; } .GoodMessage { color: darkgreen; } /* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */ .localLink { color: #1E1E1F; background: #EEEEED; text-decoration: none; } .localLink:hover { color: #1382CE; background: #FFFF99; text-decoration: none; } /* Center text, used in the over views cells that contain message level counts */ .textCentered { text-align: center; } /* The message cells in message tables should take up all avaliable space */ .messageCell { width: 100%; } /* Padding around the content after the h1 */ #content { padding: 0px 12px 12px 12px; } /* The overview table expands to width, with a max width of 97% */ #overview table { width: auto; max-width: 75%; } /* The messages tables are always 97% width */ #messages table { width: 97%; } /* All Icons */ .IconSuccessEncoded, .IconInfoEncoded, .IconWarningEncoded, .IconErrorEncoded { min-width: 18px; min-height: 18px; background-repeat: no-repeat; background-position: center; } /* Success icon encoded */ .IconSuccessEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconSuccess#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABPElEQVR4Xp1Tv0vDUBi8FqeA4NpBcBLcWnQSApncOnTo4FSnjP0DsnXpH5CxiwbHDg4Zuj4oOEXiJgiC4FDcCkLWmIMc1Pfw+eMgQ77v3Xf3Pe51YKGqqisAEwCR1TIAsiAIblSo6xrdHeJR85Xle3mdmCQKb0PsfqyxxzM8K15HZADl/H5+sHpZwYfxyRjTs+kWwKBx8yoHd2mRiuzF8mkJniWH/13u3Fjrs/EdhsdDFHGB/DLXEJBDLh1MWPAhPo1BLB4WX5yQywHR+m3tVe/t97D52CB/ziG0nIgD/qDuYg8WuCcVZ2YGwlJ3YDugkpR/VNcAEx6GEKhERSr71FuO4YCM4XBdwKvecjIlkSnsO0Hyp/GxSeJAdzBKzpOtnPwyyiPdAZhpZptT04tU+zk7s8czeges//s5C5+CwqrR4/gw+AAAAABJRU5ErkJggg==); } /* Information icon encoded */ .IconInfoEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconInformation#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHElEQVR4Xs2TsUoDQRRF7wwoziokjZUKadInhdhukR9YP8DMX1hYW+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/mv9gkhtyMDhcAxgzRsp7flj8B/HF1RsMXq+NZMkopaHe7lbKxQUEIGbKsYNoGn969060hZBkQex/W8oRQwsQaW2o3Ago2SVcJUzAgY3N0lTCZZm+zPS8HB51gMmS1DEYyOz9acKO1D8JWTlafKIMxdhvlfdyT94Vv5h7P8Ky7nQzACmhvKq3zk3PjW9asz9D/1oigecsioooAAAAASUVORK5CYII=); } /* Warning icon encoded */ .IconWarningEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconWarning#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/QGTCxdWJgiQYWKXJWKIXHIlyw5lqr34tQgEOdcBsCOx5yZK3hCCKdYXneQkh4pEfqzLfu+wVDSyyzFoJjfz9NB+pAF+eizx2Vruts0k15mPgvS6GYvpVtQhB61IB/dk6AF6fS4Ben0uIX5odtFe8Q/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/gFq44JaVSCXeQAAAABJRU5ErkJggg==); } /* Error icon encoded */ .IconErrorEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconError#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABQElEQVR4XqWTvUoEQRCE6wYPZUA80AfwAQz23uCMjA7MDRQEIzPBVEyNTQUFIw00vcQTTMzuAh/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+GsHRk0fQmPAH1GfmZirbCfDJ61tw3Px8/8pZsPAG4jlVhcPgZ7adwNWBB68lkRQWFiTgFlbnLY3DGGM7izIJIyT/jjIvEJw6fdJTc6krDzh6aMwMP9bvDH4ADSsa9uSWVJkAAAAASUVORK5CYII=); } </style> </head> <body> <h1 _locid="PortabilityReport">.NET Portability Report</h1> <div id="content"> <div id="submissionId" style="font-size:8pt;"> <p> <i> Submission Id&nbsp; b455486d-8e22-4485-8154-fcd77c721197 </i> </p> </div> <h2 _locid="SummaryTitle"> <a name="Portability Summary"></a>Portability Summary </h2> <div id="summary"> <table> <tbody> <tr> <th>Assembly</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> </tr> <tr> <td><strong><a href="#Xuni.Xamarin.Core">Xuni.Xamarin.Core</a></strong></td> <td class="text-center">100.00 %</td> <td class="text-center">100.00 %</td> <td class="text-center">100.00 %</td> <td class="text-center">100.00 %</td> </tr> </tbody> </table> </div> <div id="details"> </div> </div> </body> </html>
{ "content_hash": "8797905eeec0166d68b7178efe6656cc", "timestamp": "", "source": "github", "line_count": 240, "max_line_length": 562, "avg_line_length": 40.204166666666666, "alnum_prop": 0.573427298165613, "repo_name": "kuhlenh/port-to-core", "id": "07d5724905a9c08a39983cf8211bac3f3d1223e7", "size": "9649", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "Reports/xu/xuni.core.1.4.20151.27/Xuni.Xamarin.Core-MonoAndroid10.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2323514650" } ], "symlink_target": "" }
module ProgrammesHelper def list_item_programme_attribute(project) html = content_tag :p, class: 'list_item_attribute' do label = content_tag :b do t('programme') end label + ': ' + programme_link(project) end html.html_safe end def programme_administrators_input_box(programme) administrators = programme.programme_administrators box = '' unless User.admin_logged_in? administrators.delete(User.current_user.person) box << content_tag(:p) do "Below you can add or remove additional administrators. You cannot remove yourself, to remove yourself first add another administrator and then ask them to remove you. This is to protect against a #{t('programme')} having no administrators" end end box << objects_input('programme[administrator_ids]', administrators, typeahead: { values: Person.all.map { |p| { id: p.id, name: p.name, hint: p.typeahead_hint } } }) box.html_safe end def programme_administrator_link_list(programme) link_list_for_role("#{t('programme')} Administrator", programme.programme_administrators, 'programme') end def can_create_programmes? Programme.can_create? end end
{ "content_hash": "78509225f6a4879bfadbb1c8f652f5d2", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 170, "avg_line_length": 35.970588235294116, "alnum_prop": 0.6868356500408831, "repo_name": "HITS-SDBV/seek", "id": "91920ad89186fffda331ac6db92e17dc56d7e486", "size": "1223", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/helpers/programmes_helper.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "37470" }, { "name": "Dockerfile", "bytes": "1866" }, { "name": "HTML", "bytes": "945737" }, { "name": "JavaScript", "bytes": "237557" }, { "name": "Ruby", "bytes": "3855118" }, { "name": "Shell", "bytes": "5899" } ], "symlink_target": "" }
package cz.krtinec.telka.provider; import gnu.java.nio.charset.Windows1250; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Collection; import java.util.List; import java.util.Map; import org.xml.sax.SAXException; import android.content.Context; import android.preference.PreferenceManager; import android.util.Log; import android.util.Xml; import cz.krtinec.telka.CannotLoadProgrammeException; import cz.krtinec.telka.IProgrammeProvider; import cz.krtinec.telka.dto.Channel; import cz.krtinec.telka.dto.Programme; /** * Default implementation. * @author krtek * */ public class ProgrammeProvider implements IProgrammeProvider { private static final String CACHE_FILENAME = "program.cache"; private static final String CACHE_TIMESTAMP = "program.timestamp"; private static final String CLASS_NAME = ProgrammeProvider.class.getSimpleName(); private ChannelCacheHolder holder = null; private Context context = null; private static final String URL = "http://xmltv.arcao.com/xml.php?gids[]=ct1.ceskatelevize.cz&" + "gids[]=ct2.ceskatelevize.cz&" + "gids[]=nova.nova.cz&" + "gids[]=prima.iprima.cz&" + "gids[]=cool.iprima.cz&" + "gids[]=ct24.ct24.cz&" + "gids[]=ct4sport.ct24.cz&" + "gids[]=ocko.idnes.cz&" + "gids[]=sport.nova.cz&" + "gids[]=cinema.nova.cz&" + "gids[]=mtv.nova.cz"; public ProgrammeProvider(Context context) { this.context = context; } public void disable(Channel channel) { throw new NoSuchMethodError("Not yet implemented!"); } public void enable(Channel channel) { throw new NoSuchMethodError("Not yet implemented!"); } public Collection<Channel> getAllChannels(int reloadInterval) { if (this.holder == null) { this.holder = loadChannels(reloadInterval); //determine state... for (Channel ch : holder.channels.keySet()) { for (Programme p: holder.channels.get(ch)) { p.getState(); } } } return holder.channels.keySet(); } public Collection<Channel> getEnabledChannels(int reloadInterval) { return getAllChannels(reloadInterval); } public List<Programme> getProgrammes(Channel channel) { //channels cannot be null -> or can? return holder.channels.get(channel); } public Integer nowPlaying(Channel channel) { List<Programme> programmes = holder.channels.get(channel); int i = 0; for (Programme p : programmes) { if (p.getState().isRunning()) { //Log.d("ProgrammeProvider", "isRunning() returns " + p); return i; } i++; } //Log.d("ProgrammeProvider", "isRunning() returns nothing."); return i; } private ChannelCacheHolder loadChannels(int reloadInterval) { Log.i(CLASS_NAME, "ReloadInterval: " + reloadInterval); try { ObjectInputStream ois = new ObjectInputStream(context.openFileInput(CACHE_TIMESTAMP)); long timestamp = ois.readLong(); ois.close(); long interval = System.currentTimeMillis() - timestamp; if (interval < reloadInterval) { Log.i(CLASS_NAME, "Last reloaded before " + interval + " [ms], going to reuse."); ois = new ObjectInputStream(context.openFileInput(CACHE_FILENAME)); ChannelCacheHolder holder = (ChannelCacheHolder) ois.readObject(); ois.close(); Log.i(CLASS_NAME, "Programme loaded from cache."); return holder; } else { Log.i(CLASS_NAME, "Last reloaded before " + interval + " [ms], going to load again."); } } catch (IOException e) { Log.i(CLASS_NAME, "No stored programme found - going to load from net..."); } catch (ClassNotFoundException e) { Log.i(CLASS_NAME, "ClassNotFoundException - going to load from net..."); } try { ChannelCacheHolder holder = loadChannelsFromNetAndStore(); return holder; } catch (Exception e) { Log.e(CLASS_NAME, "Exception: ", e); throw new CannotLoadProgrammeException("Cannot load TV programme" ,e); } } private ChannelCacheHolder loadChannelsFromNetAndStore() throws IOException, MalformedURLException, SAXException, FileNotFoundException { Map<Channel, List<Programme>> channels = loadChannelsFromNet(); ChannelCacheHolder holder = new ChannelCacheHolder(channels, System.currentTimeMillis()); long timestamp = System.currentTimeMillis(); ObjectOutputStream oos = new ObjectOutputStream(context.openFileOutput(CACHE_FILENAME, Context.MODE_PRIVATE)); oos.writeObject(holder); oos.close(); oos = new ObjectOutputStream(context.openFileOutput(CACHE_TIMESTAMP, Context.MODE_PRIVATE)); oos.writeLong(timestamp); oos.close(); Log.i(CLASS_NAME, "Programme stored to cache."); return holder; } private Map<Channel, List<Programme>> loadChannelsFromNet() throws IOException, MalformedURLException, SAXException { Log.i(CLASS_NAME, "Going to parse programmes"); HttpURLConnection uc = (HttpURLConnection) new URL(URL).openConnection(); uc.setDoInput(true); uc.setDoOutput(true); InputStream is = uc.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, new Windows1250()), 8096*4); ProgrammeHandler handler = new ProgrammeHandler(); long start = System.currentTimeMillis(); Xml.parse(br, handler); long stop = System.currentTimeMillis(); Log.i(CLASS_NAME, "Parsed in " + (stop - start) + " millis"); Map <Channel, List<Programme>> channels = handler.getChannels(); return channels; } public void reload() { try { this.holder = loadChannelsFromNetAndStore(); } catch (Exception e) { Log.e(CLASS_NAME, "Reload failed"); } } } class ChannelCacheHolder implements Serializable { ChannelCacheHolder(Map <Channel, List<Programme>> channels, long timestamp) { this.channels = channels; this.timestamp = timestamp; } Map <Channel, List<Programme>> channels; long timestamp; }
{ "content_hash": "871c0ef22fd43fefaff986b824837906", "timestamp": "", "source": "github", "line_count": 189, "max_line_length": 112, "avg_line_length": 31.8994708994709, "alnum_prop": 0.7230054735445347, "repo_name": "krtek/telka", "id": "ff1f61535414015283162d1059b5417be15a375b", "size": "6029", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/cz/krtinec/telka/provider/ProgrammeProvider.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "66683" } ], "symlink_target": "" }
<?php namespace Aztech\Rpc; use Aztech\Net\Reader; interface RawPduParser { /** * * @param Reader $reader * @return RawProtocolDataUnit */ public function parse(Reader $reader); }
{ "content_hash": "e00f89a678414c645533924bafd90312", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 42, "avg_line_length": 14.066666666666666, "alnum_prop": 0.6303317535545023, "repo_name": "aztech-labs/msmq", "id": "625b2863327a3d611ab715e09075e599a8fec2f0", "size": "211", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Rpc/RawPduParser.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "158014" } ], "symlink_target": "" }
package condition import ( "reflect" "time" "github.com/rancher/wrangler/pkg/generic" "github.com/sirupsen/logrus" ) type Cond string func (c Cond) GetStatus(obj interface{}) string { return getStatus(obj, string(c)) } func (c Cond) SetError(obj interface{}, reason string, err error) { if err == nil || err == generic.ErrSkip { c.True(obj) c.Message(obj, "") c.Reason(obj, reason) return } if reason == "" { reason = "Error" } c.False(obj) c.Message(obj, err.Error()) c.Reason(obj, reason) } func (c Cond) MatchesError(obj interface{}, reason string, err error) bool { if err == nil { return c.IsTrue(obj) && c.GetMessage(obj) == "" && c.GetReason(obj) == reason } if reason == "" { reason = "Error" } return c.IsFalse(obj) && c.GetMessage(obj) == err.Error() && c.GetReason(obj) == reason } func (c Cond) SetStatus(obj interface{}, status string) { setStatus(obj, string(c), status) } func (c Cond) SetStatusBool(obj interface{}, val bool) { if val { setStatus(obj, string(c), "True") } else { setStatus(obj, string(c), "False") } } func (c Cond) True(obj interface{}) { setStatus(obj, string(c), "True") } func (c Cond) IsTrue(obj interface{}) bool { return getStatus(obj, string(c)) == "True" } func (c Cond) False(obj interface{}) { setStatus(obj, string(c), "False") } func (c Cond) IsFalse(obj interface{}) bool { return getStatus(obj, string(c)) == "False" } func (c Cond) Unknown(obj interface{}) { setStatus(obj, string(c), "Unknown") } func (c Cond) IsUnknown(obj interface{}) bool { return getStatus(obj, string(c)) == "Unknown" } func (c Cond) LastUpdated(obj interface{}, ts string) { setTS(obj, string(c), ts) } func (c Cond) GetLastUpdated(obj interface{}) string { return getTS(obj, string(c)) } func (c Cond) CreateUnknownIfNotExists(obj interface{}) { condSlice := getValue(obj, "Status", "Conditions") cond := findCond(obj, condSlice, string(c)) if cond == nil { c.Unknown(obj) } } func (c Cond) Reason(obj interface{}, reason string) { cond := findOrCreateCond(obj, string(c)) getFieldValue(cond, "Reason").SetString(reason) } func (c Cond) GetReason(obj interface{}) string { cond := findOrNotCreateCond(obj, string(c)) if cond == nil { return "" } return getFieldValue(*cond, "Reason").String() } func (c Cond) SetMessageIfBlank(obj interface{}, message string) { if c.GetMessage(obj) == "" { c.Message(obj, message) } } func (c Cond) Message(obj interface{}, message string) { cond := findOrCreateCond(obj, string(c)) setValue(cond, "Message", message) } func (c Cond) GetMessage(obj interface{}) string { cond := findOrNotCreateCond(obj, string(c)) if cond == nil { return "" } return getFieldValue(*cond, "Message").String() } func touchTS(value reflect.Value) { now := time.Now().Format(time.RFC3339) getFieldValue(value, "LastUpdateTime").SetString(now) } func getStatus(obj interface{}, condName string) string { cond := findOrNotCreateCond(obj, condName) if cond == nil { return "" } return getFieldValue(*cond, "Status").String() } func setTS(obj interface{}, condName, ts string) { cond := findOrCreateCond(obj, condName) getFieldValue(cond, "LastUpdateTime").SetString(ts) } func getTS(obj interface{}, condName string) string { cond := findOrNotCreateCond(obj, condName) if cond == nil { return "" } return getFieldValue(*cond, "LastUpdateTime").String() } func setStatus(obj interface{}, condName, status string) { if reflect.TypeOf(obj).Kind() != reflect.Ptr { panic("obj passed must be a pointer") } cond := findOrCreateCond(obj, condName) setValue(cond, "Status", status) } func setValue(cond reflect.Value, fieldName, newValue string) { value := getFieldValue(cond, fieldName) if value.String() != newValue { value.SetString(newValue) touchTS(cond) } } func findOrNotCreateCond(obj interface{}, condName string) *reflect.Value { condSlice := getValue(obj, "Status", "Conditions") if !condSlice.IsValid() { condSlice = getValue(obj, "Conditions") } return findCond(obj, condSlice, condName) } func findOrCreateCond(obj interface{}, condName string) reflect.Value { condSlice := getValue(obj, "Status", "Conditions") if !condSlice.IsValid() { condSlice = getValue(obj, "Conditions") } cond := findCond(obj, condSlice, condName) if cond != nil { return *cond } newCond := reflect.New(condSlice.Type().Elem()).Elem() newCond.FieldByName("Type").SetString(condName) newCond.FieldByName("Status").SetString("Unknown") condSlice.Set(reflect.Append(condSlice, newCond)) return *findCond(obj, condSlice, condName) } func findCond(obj interface{}, val reflect.Value, name string) *reflect.Value { defer func() { if recover() != nil { logrus.Fatalf("failed to find .Status.Conditions field on %v", reflect.TypeOf(obj)) } }() for i := 0; i < val.Len(); i++ { cond := val.Index(i) typeVal := getFieldValue(cond, "Type") if typeVal.String() == name { return &cond } } return nil } func getValue(obj interface{}, name ...string) reflect.Value { if obj == nil { return reflect.Value{} } v := reflect.ValueOf(obj) t := v.Type() if t.Kind() == reflect.Ptr { v = v.Elem() t = v.Type() } field := v.FieldByName(name[0]) if len(name) == 1 { return field } return getFieldValue(field, name[1:]...) } func getFieldValue(v reflect.Value, name ...string) reflect.Value { if !v.IsValid() { return v } field := v.FieldByName(name[0]) if len(name) == 1 { return field } return getFieldValue(field, name[1:]...) } func Error(reason string, err error) error { return &conditionError{ reason: reason, message: err.Error(), } } type conditionError struct { reason string message string } func (e *conditionError) Error() string { return e.message }
{ "content_hash": "9b2929d3a1d8c91d01482f7120daa940", "timestamp": "", "source": "github", "line_count": 258, "max_line_length": 86, "avg_line_length": 22.44573643410853, "alnum_prop": 0.6732861336556726, "repo_name": "rancher/vm", "id": "906a4213eba6173a7e31f659dc3b084fe76cb74c", "size": "5791", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/github.com/rancher/wrangler/pkg/condition/condition.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2106" }, { "name": "Dockerfile", "bytes": "3993" }, { "name": "Go", "bytes": "282426" }, { "name": "HTML", "bytes": "428" }, { "name": "Makefile", "bytes": "5832" }, { "name": "Python", "bytes": "20768" }, { "name": "Shell", "bytes": "16519" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="pl"> <head> <!-- Generated by javadoc --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class com.google.code.play2.provider.play22.Play22CoffeescriptCompiler (Play! 2.x Provider for Play! 2.2.x 1.0.0-rc5 API)</title> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.google.code.play2.provider.play22.Play22CoffeescriptCompiler (Play! 2.x Provider for Play! 2.2.x 1.0.0-rc5 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../com/google/code/play2/provider/play22/Play22CoffeescriptCompiler.html" title="class in com.google.code.play2.provider.play22">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?com/google/code/play2/provider/play22/class-use/Play22CoffeescriptCompiler.html" target="_top">Frames</a></li> <li><a href="Play22CoffeescriptCompiler.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class com.google.code.play2.provider.play22.Play22CoffeescriptCompiler" class="title">Uses of Class<br>com.google.code.play2.provider.play22.Play22CoffeescriptCompiler</h2> </div> <div class="classUseContainer">No usage of com.google.code.play2.provider.play22.Play22CoffeescriptCompiler</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../com/google/code/play2/provider/play22/Play22CoffeescriptCompiler.html" title="class in com.google.code.play2.provider.play22">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?com/google/code/play2/provider/play22/class-use/Play22CoffeescriptCompiler.html" target="_top">Frames</a></li> <li><a href="Play22CoffeescriptCompiler.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2013&#x2013;2019. All rights reserved.</small></p> </body> </html>
{ "content_hash": "90ab7a1a35c282604c42b035a4401663", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 191, "avg_line_length": 39.544, "alnum_prop": 0.6204733967226381, "repo_name": "play2-maven-plugin/play2-maven-plugin.github.io", "id": "b50f5a4846c3be240954c397f9887ebe5e8a94c1", "size": "4943", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "play2-maven-plugin/1.0.0-rc5/play2-providers/play2-provider-play22/apidocs/com/google/code/play2/provider/play22/class-use/Play22CoffeescriptCompiler.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2793124" }, { "name": "HTML", "bytes": "178221432" }, { "name": "JavaScript", "bytes": "120742" } ], "symlink_target": "" }
<?php namespace WildPHP\Core\Commands\Parameters; use PHPUnit\Framework\TestCase; use WildPHP\Core\Entities\IrcChannel; use WildPHP\Core\Entities\IrcUser; use WildPHP\Core\Storage\IrcChannelStorage; use WildPHP\Core\Storage\IrcUserStorage; use WildPHP\Core\Storage\Providers\MemoryStorageProvider; class UserParameterTest extends TestCase { /** * @var UserParameter */ private $testObject; protected function setUp(): void { parent::setUp(); $userStorage = new IrcUserStorage(new MemoryStorageProvider()); $userStorage->store( new IrcUser( [ 'nickname' => 'Test' ] ) ); $this->testObject = new UserParameter($userStorage); } public function testConvert() { self::assertInstanceOf(IrcUser::class, $this->testObject->convert('Test')); self::assertFalse($this->testObject->convert('Testing')); } public function testValidate() { self::assertTrue($this->testObject->validate('Test')); self::assertFalse($this->testObject->validate('Testing')); } }
{ "content_hash": "46022382e53973dafae4a536382c6cc1", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 83, "avg_line_length": 23.612244897959183, "alnum_prop": 0.6274848746758859, "repo_name": "WildPHP/Wild-IRC-Bot", "id": "c339e248ac8495b1e9a23eceef6175e31697b500", "size": "1320", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/Commands/Parameters/UserParameterTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "312665" } ], "symlink_target": "" }
function newData = fretSelector(data, settings) % Selects of traces from a data file that are likely to show % anti-correlated fluorescence resonace energy transfer (FRET) behavior. % % Tested in Matlab R2012a % % INPUTS: % % -data: Array. where each row is an observation frame and each column is fluorescence intensity from each fluorophore in that frame. % First column is time of each frame (assumed ot be in seconds with each frame representing the same ammount of time). % Following columns are groups of fluorophores grouped by columns. One % column should represent a FRET DONOR signal, another column should % specify FRET ACCEPTOR SIGNAL. Which is which is specified in settings. % % For example: % % data = % 1 1 0 0 0 % 2 1 0 0 0 % 3 0 1 0 0 % 4 1 0 1 0 % % is a single trace, taken over four seconds at a 1 second framerate, with % four colors. the first is the FRET DONOR, the second the FRET ACCEPTOR, the third and fourth are additional channels % The FRET event happened at second 3. The third color fluoresced at second 4. The fourth color never fluoresced. % % -settings: Structure. Summarizes all of the settings for the % function. The fields are: % -numColors: Integer. Specifies number of different colors per trace % -donorSD, acceptorSD, fretSD: Float. Spefies number of standard deviations above % background that should be considered as a donor, acceptor, or FRET event. Determined % empirically based on experimental conditions. % -fretPair: 1X2 vector. number positions of the donor and acceptor % signals in the data file. In the example above the fretPair vector % would be: [1 2] % -smoothFlag: 1 or 0. Indicates whether user wants data to be % smoothed using a discrete transfer function. 1 indicates yes, 0 % indicates no. % -smoothFrames: Integer from 1-5. If smoothFlag = 1, number of frames overwhich the % smoothing should be done. % % OUTPUT: % % -newData: Array. Version of data with only the traces that only includes the traces that might have anti-correlated FRET events. % characterize data file ttotal = data; t = ttotal(:,1); ttotal(:,1) = []; nCol = size(ttotal,2); traces = nCol/settings.numColors; assert(round(std(diff(t))) <=1e-3, 'Time column in data is not equally spaced') assert(mod(nCol,settings.numColors) == 0, 'numColor setting is wrong') % Smooths the data if smoothFlag is set to 1 if settings.smoothFlag == 1 ttotal = double(ttotal); for n = 1:size(ttotal,2) ttotal(:,n) = filtfilt(ones(1,settings.smoothFrames),settings.smoothFrames,ttotal(:,n)); end end % extract FRET, donor, and acceptor traces nTraces = 1:traces; donor = ttotal(:,(nTraces * settings.numColors - (settings.numColors-settings.fretPair(1)))); acceptor = ttotal(:,(nTraces * settings.numColors -(settings.numColors-settings.fretPair(2)))); fret = acceptor./(donor+acceptor); % make donor, acceptor and FRET trace-by-trace frame-by-frame variation % matrices differenceDonor = diff(donor); differenceAcceptor = diff(acceptor); differenceFret = diff(fret); % determine summary statistics meanDonor = mean(differenceDonor); stdDonor = std(differenceDonor); meanAcceptor = mean(differenceAcceptor); stdAcceptor = std(differenceAcceptor); meanFret = mean(differenceFret); stdFret = std(differenceFret); % determine cutoffs based on settings file parameters cutDonorUp = meanDonor + settings.donorSD * stdDonor; cutDonorDown = meanDonor - settings.donorSD * stdDonor; cutAcceptorUp = meanAcceptor + settings.acceptorSD * stdAcceptor; cutAcceptorDown = meanAcceptor - settings.acceptorSD * stdAcceptor; cutFretUp = meanFret + settings.fretSD * stdFret; cutFretDown = meanFret - settings.fretSD * stdFret; % find all points in traces where all three cutoffs (FRET, donor, and % acceptor) are met in rising (up) FRET events. Point-by-point comparisons % is important because it assures temporal anti-correlation. % initialize summary with tally of rising (up) FRET events testUp = zeros(1,traces); for i = nTraces indexFretUp = find(differenceFret(:,i) > cutFretUp(i)); indexDonorDown = find(differenceDonor(:,i) < cutDonorDown(i)); indexAcceptorUp = find(differenceAcceptor(:,i) > cutAcceptorUp(i)); finalOneUp = indexFretUp(ismember(indexFretUp,indexDonorDown)); finalTwoUp = finalOneUp(ismember(finalOneUp,indexAcceptorUp)); if ~isempty(finalTwoUp) testUp(i) = 1; end end % find all points in traces where all three cutoffs (FRET, donor, and % acceptor) are met in falling (down) FRET events. Point-by-point comparisons % is important because it assures temporal anti-correlation. % initialize summary with tally of falling (down) FRET events testDown = zeros(1,traces); for i = nTraces indexFretDown = find(differenceFret(:,i) < cutFretDown(i)); indexDonorUp = find(differenceDonor(:,i) > cutDonorUp(i)); indexAcceptorDown = find(differenceAcceptor(:,i) < cutAcceptorDown(i)); finalOneDown = indexFretDown(ismember(indexFretDown,indexDonorUp)); finalTwoDown = finalOneDown(ismember(finalOneDown,indexAcceptorDown)); if ~isempty(finalTwoDown) testDown(i) = 1; end end % make a new data array with only traces that have anti-correlated donor % and acceptor signal (either up or down) tracesFinal = testUp + testDown; tracesFinal = tracesFinal > 0; indexFinal = zeros(1, traces*settings.numColors); for i = 0:settings.numColors-1 indexFinal(:, nTraces*settings.numColors - i) = tracesFinal; end newData = ttotal(:, logical(indexFinal)); newData = [t newData]; end
{ "content_hash": "e3e5e8d1d7c2757048d24cf3101ceeda", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 133, "avg_line_length": 37.729729729729726, "alnum_prop": 0.7376432664756447, "repo_name": "trnoriega/Matlab-Single-Molecule", "id": "0ce75bd62055050013df143a349b0f95d8c8311b", "size": "5584", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fretSelector_script/fretSelector.m", "mode": "33188", "license": "mit", "language": [ { "name": "Matlab", "bytes": "38405" } ], "symlink_target": "" }
var result = false; var elem = document.createElement('canvas'); if (elem.getContext && elem.getContext('2d')) { // was able or not to get WebP representation result = /^data:image\/webp/.test(elem.toDataURL('image/webp')); } module.exports = () => { return result; };
{ "content_hash": "1f2b07e068d48bf2f2e0cae31d3929ce", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 66, "avg_line_length": 23.083333333333332, "alnum_prop": 0.6678700361010831, "repo_name": "nolanlawson/pokedex.org", "id": "985f6509dcfd451fa5c478ee5035b4f9de3593f6", "size": "277", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/js/shared/util/supportsWebp.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "16147" }, { "name": "HTML", "bytes": "3408" }, { "name": "JavaScript", "bytes": "105336" }, { "name": "Shell", "bytes": "427" } ], "symlink_target": "" }
require 'test_helper' class CharacterTypeTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
{ "content_hash": "979e67761e381bf3ac3284dae266a7f7", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 49, "avg_line_length": 18.142857142857142, "alnum_prop": 0.7086614173228346, "repo_name": "dimitardanailov/hobbit-hackconf-2015", "id": "f6826277895e7c5754894bcde90e3731f3cb8b7f", "size": "127", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/models/character_type_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2612" }, { "name": "CoffeeScript", "bytes": "1055" }, { "name": "HTML", "bytes": "12487" }, { "name": "JavaScript", "bytes": "661" }, { "name": "Ruby", "bytes": "39633" } ], "symlink_target": "" }
// Low-level API for building off-memory data structures with riegeli. // // `SequencedChunkWriter` writes chunks of records to an abstracted destination. // This class abstract out the generic chunk writing logic from concrete logic // that builds up the data structures for future access. This class is // thread-safe and allows users to encode each chunk concurrently while // maintaining the sequence order of the chunks. #ifndef ARRAY_RECORD_CPP_SEQUENCED_CHUNK_WRITER_H_ #define ARRAY_RECORD_CPP_SEQUENCED_CHUNK_WRITER_H_ #include <functional> #include <future> // NOLINT(build/c++11) #include <optional> #include <queue> #include <type_traits> #include <utility> #include "absl/base/thread_annotations.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/synchronization/mutex.h" #include "cpp/common.h" #include "riegeli/base/object.h" #include "riegeli/bytes/writer.h" #include "riegeli/chunk_encoding/chunk.h" #include "riegeli/records/chunk_writer.h" namespace array_record { // Template parameter independent part of `SequencedChunkWriter`. class SequencedChunkWriterBase : public riegeli::Object { SequencedChunkWriterBase(const SequencedChunkWriterBase&) = delete; SequencedChunkWriterBase& operator=(const SequencedChunkWriterBase&) = delete; SequencedChunkWriterBase(SequencedChunkWriterBase&&) = delete; SequencedChunkWriterBase& operator=(SequencedChunkWriterBase&&) = delete; public: // The `SequencedChunkWriter` invokes `SubmitChunkCallback` for every // successful chunk writing. In other words, the invocation only happens when // none of the errors occur (SequencedChunkWriter internal state, chunk // correctness, underlying writer state, etc.) The callback consists of four // arguments: // // chunk_seq: sequence number of the chunk in the file. Indexed from 0. // chunk_offset: byte offset of the chunk in the file. A reader can seek this // offset and decode the chunk without other information. // decoded_data_size: byte size of the decoded data. Users may serialize this // field for readers to allocate memory for the decoded data. // num_records: number of records in the chunk. class SubmitChunkCallback { public: virtual ~SubmitChunkCallback() {} virtual void operator()(uint64_t chunk_seq, uint64_t chunk_offset, uint64_t decoded_data_size, uint64_t num_records) = 0; }; // Commits a future chunk to the `SequencedChunkWriter` before materializing // the chunk. Users can encode the chunk in a separated thread at the cost of // larger temporal memory usage. `SequencedChunkWriter` serializes the chunks // at the order of this function call. // // Example 1: packaged_task // // std::packaged_task<absl::StatusOr<riegeli::Chunk>()> encoding_task( // []() -> absl::StatusOr<riegeli::Chunk> { // ... returns a riegeli::Chunk on success. // }); // std::future<absl::StatusOr<riegeli::Chunk>> task_future = // encoding_task.get(); // sequenced_chunk_writer->CommitFutureChunk(std::move(task_future)); // // // Computes the encoding task in a thread pool. // pool->Schedule(std::move(encoding_task)); // // Example 2: promise and future // // std::promise<absl::StatusOr<riegeli::Chunk>> chunk_promise; // RET_CHECK(sequenced_chunk_writer->CommitFutureChunk( // chunk_promise.get_future())) << sequenced_chunk_writer->status(); // pool->Schedule([chunk_promise = std::move(chunk_promise)] { // // computes chunk // chunk_promise.set_value(status_or_chunk); // }); // // Although `SequencedChunkWriter` is thread-safe, this method should be // invoked from a single thread because it doesn't make sense to submit future // chunks without a proper order. bool CommitFutureChunk( std::future<absl::StatusOr<riegeli::Chunk>>&& future_chunk); // Extracts the future chunks and submits them to the underlying destination. // This operation may block if the argument `block` was true. This method is // thread-safe, and we recommend users invoke it with `block=false` in each // thread to reduce the temporal memory usage. // // Example 1: single thread usage // // std::promise<absl::StatusOr<riegeli::Chunk>> chunk_promise; // RET_CHECK(sequenced_chunk_writer->CommitFutureChunk( // chunk_promise.get_future())) << sequenced_chunk_writer->status(); // chunk_promise.set_value(ComputesChunk()); // RET_CHECK(writer->SubmitFutureChunks(true)) << writer->status(); // // Example 2: concurrent access // // auto writer = std::make_shared<SequencedChunkWriter<>(...) // // pool->Schedule([writer, // chunk_promise = std::move(chunk_promise)]() mutable { // chunk_promise.set_value(status_or_chunk); // // Should not block otherwise would enter deadlock! // writer->SubmitFutureChunks(false); // }); // // Blocking the main thread is fine. // RET_CHECK(writer->SubmitFutureChunks(true)) << writer->status(); // bool SubmitFutureChunks(bool block = false); // Pads to 64KB boundary for future chunk submission. (Default false). void set_pad_to_block_boundary(bool pad_to_block_boundary) { absl::MutexLock l(&mu_); pad_to_block_boundary_ = pad_to_block_boundary; } bool pad_to_block_boundary() { absl::MutexLock l(&mu_); return pad_to_block_boundary_; } // Setup a callback for each committed chunk. See CommitChunkCallback // comments for details. void set_submit_chunk_callback(SubmitChunkCallback* callback) { absl::MutexLock l(&mu_); callback_ = callback; } // Guard the status access. absl::Status status() const { absl::ReaderMutexLock l(&mu_); return riegeli::Object::status(); } protected: SequencedChunkWriterBase() {} virtual riegeli::ChunkWriter* get_writer() = 0; // Initializes and validates the underlying writer states. void Initialize(); // Callback for riegeli::Object::Close. void Done() override; private: mutable absl::Mutex mu_; bool pad_to_block_boundary_ ABSL_GUARDED_BY(mu_) = false; SubmitChunkCallback* callback_ ABSL_GUARDED_BY(mu_) = nullptr; // Records the sequence number of submitted chunks. uint64_t submitted_chunks_ ABSL_GUARDED_BY(mu_) = 0; // Queue for storing the future chunks. std::queue<std::future<absl::StatusOr<riegeli::Chunk>>> queue_ ABSL_GUARDED_BY(mu_); }; // A `SequencedChunkWriter` writes chunks (a blob of multiple and possibly // compressed records) rather than individual records to an abstracted // destination. `SequencedChunkWriter` allows users to encode each chunk // concurrently while keeping the chunk sequence order as the input order. // // Users can also supply a `CommitChunkCallback` to collect chunk sequence // numbers, offsets in the file, decoded data size, and the number of records in // each chunk. Users may use the callback information to produce a lookup table // in the footer for an efficient reader to decode multiple chunks in parallel. // // Example usage: // // // Step 1: open the writer with file backend. // File* file = file::OpenOrDie(...); // auto writer = std::make_shared<SequencedChunkWriter<riegeli::FileWriter<>>( // std::make_tuple(file)); // // // Step 2: create a chunk encoding task. // std::packaged_task<absl::StatusOr<riegeli::Chunk>()> encoding_task( // []() -> absl::StatusOr<riegeli::Chunk> { // ... returns a riegeli::Chunk on success. // }); // // // Step 3: book a slot for writing the encoded chunk. // RET_CHECK(writer->CommitFutureChunk( // encoding_task.get_future())) << writer->status(); // // // Step 4: Computes the encoding task in a thread pool. // pool->Schedule([=,encoding_task=std::move(encoding_task)]() mutable { // encoding_task(); // std::promise fulfilled. // // shared_ptr pevents the writer to go out of scope, so it is safe to // // invoke the method here. // writer->SubmitFutureChunks(false); // }); // // // Repeats step 2 to 4. // // // Finally, close the writer. // RET_CHECK(writer->Close()) << writer->status(); // // // It is necessary to call `Close()` at the end of a successful writing session, // and it is recommended to call `Close()` at the end of a successful reading // session. It is not needed to call `Close()` on early returns, assuming that // contents of the destination do not matter after all, e.g. because a failure // is being reported instead; the destructor releases resources in any case. // // `SequencedChunkWriter` inherits riegeli::Object which provides useful // abstractions for state management of IO-like operations. Instead of the // common absl::Status/StatusOr for each method, the riegeli::Object's error // handling mechanism uses bool and separated `status()`, `ok()`, `is_open()` // for users to handle different types of failure states. // // // `SequencedChunkWriter` use templated backend abstraction. To serialize the // output to a string, user simply write: // // std::string dest; // auto writes_to_string = // SequencedChunkWriter<riegeli::StringWriter<>>(std::make_tuple(&dest)); // // Similarly, user can write the output to a cord or to a file. // // absl::Cord cord; // auto writes_to_cord = // SequencedChunkWriter<riegeli::CordWriter<>>(std::make_tuple(&cord)); // // File* file = ...; // auto writes_to_file = // SequencedChunkWriter<riegeli::FileWriter<>>(std::make_tuple(file)); // // User may also use std::make_shared<...> or std::make_unique to construct the // instance, as shown in the previous example. template <typename Dest> class SequencedChunkWriter : public SequencedChunkWriterBase { public: DECLARE_IMMOBILE_CLASS(SequencedChunkWriter); // Ctor by taking the ownership of the other riegeli writer. explicit SequencedChunkWriter(Dest&& dest) : dest_(std::move(dest)) { Initialize(); } // Ctor by forwarding arguments as tuple to the underlying riegeli writer. template <typename... DestArgs> explicit SequencedChunkWriter(std::tuple<DestArgs...> dest_args) : dest_(std::move(dest_args)) { Initialize(); } protected: riegeli::ChunkWriter* get_writer() final { return &dest_; } private: riegeli::DefaultChunkWriter<Dest> dest_; }; } // namespace array_record #endif // ARRAY_RECORD_CPP_SEQUENCED_CHUNK_WRITER_H_
{ "content_hash": "b43ea38480fe95df808678f351f310c0", "timestamp": "", "source": "github", "line_count": 268, "max_line_length": 80, "avg_line_length": 39.235074626865675, "alnum_prop": 0.6912981455064194, "repo_name": "google/array_record", "id": "cb8374f2c4ea48062f3feabf1c52bb074702ce41", "size": "11171", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "cpp/sequenced_chunk_writer.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "187655" }, { "name": "Dockerfile", "bytes": "1542" }, { "name": "Python", "bytes": "4949" }, { "name": "Shell", "bytes": "3168" }, { "name": "Starlark", "bytes": "15242" } ], "symlink_target": "" }