text
stringlengths
2
1.04M
meta
dict
package com.networknt.eventuate.customer.command.handler; import com.networknt.server.Server; import org.junit.rules.ExternalResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.atomic.AtomicInteger; import com.networknt.server.Server; import com.networknt.server.ServerConfig; public class TestServer extends ExternalResource { static final Logger logger = LoggerFactory.getLogger(TestServer.class); private static final AtomicInteger refCount = new AtomicInteger(0); private static Server server; private static final TestServer instance = new TestServer(); public static TestServer getInstance () { return instance; } private TestServer() { } public ServerConfig getServerConfig() { return Server.config; } @Override protected void before() { try { if (refCount.get() == 0) { Server.start(); } } finally { refCount.getAndIncrement(); } } @Override protected void after() { refCount.getAndDecrement(); if (refCount.get() == 0) { Server.stop(); } } }
{ "content_hash": "4e1a9add2d0d917a8619c05123fec466", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 75, "avg_line_length": 23.647058823529413, "alnum_prop": 0.6451077943615257, "repo_name": "networknt/light-java-example", "id": "e10b0eb8a1ee011366c8c5f03882b436c49a5f40", "size": "1207", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "eventuate/account-management/customer-service/src/test/java/com/networknt/eventuate/customer/command/handler/TestServer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1251" }, { "name": "Java", "bytes": "562730" }, { "name": "JavaScript", "bytes": "20118" }, { "name": "PLSQL", "bytes": "1936" } ], "symlink_target": "" }
package com.thinkgem.jeesite.modules.mms.vo; import com.thinkgem.jeesite.common.utils.excel.annotation.ExcelField; import java.util.Date; /** * 送检导出清单字段 * Created by jiang on 2017/4/3. */ public class InspectionExportProductVo { private String productNumber; // 产品编号 private String englishName; // 英文名称 private String chineseName; // 中文名称 private String productLeader; // 产品负责人 private String enterpriseApplicationAddress; // 申请企业地址 private String enterpriseApplicationPhone; // 申请企业电话 private String enterpriseApplicationContacts; // 申请企业联系人 private String responsibleUnitInChina; // 在华责任单位 private String responsibleUnitInChinaAddress; // 在华责任单位地址 private String responsibleUnitInChinaPhone; // 在华责任单位电话 private String responsibleUnitInChinaFax; // 在华责任单位传真 private String responsibleUnitInChinaZipCode; // 在华责任单位邮编 private String colorCharacter; // 颜色性状 private String sampleMarking; // 样品标记(生产日期或批号) private String dateOfExpiry; // 保质期或限期使用日期(包装标注的保质期或限期使用日期) private String technologyDateOfExpiry; // 保质期(技术要求中显示的保质期)---(多的) private String smell; // 气味 ----(多的) private String specifications; // 规格 private Date administrativeLicenseInspectionTime; // 行政许可送检时间 private String administrativeLicenseInspectionOrganization; // 行政许可检验机构 private String administrativeLicenseInspectionProject; // 行政许可检验项目 private String administrativeLicenseInspectionNumber; // 行政许可送检数量 @ExcelField(title = "产品编号",sort = 10) public String getProductNumber() { return productNumber; } public void setProductNumber(String productNumber) { this.productNumber = productNumber; } @ExcelField(title = "英文名称",sort = 30) public String getEnglishName() { return englishName; } public void setEnglishName(String englishName) { this.englishName = englishName; } @ExcelField(title = "中文名称",sort = 20) public String getChineseName() { return chineseName; } public void setChineseName(String chineseName) { this.chineseName = chineseName; } @ExcelField(title = "产品负责人",sort = 40) public String getProductLeader() { return productLeader; } public void setProductLeader(String productLeader) { this.productLeader = productLeader; } @ExcelField(title = "申请企业地址",sort = 50) public String getEnterpriseApplicationAddress() { return enterpriseApplicationAddress; } public void setEnterpriseApplicationAddress(String enterpriseApplicationAddress) { this.enterpriseApplicationAddress = enterpriseApplicationAddress; } @ExcelField(title = "申请企业电话",sort = 60) public String getEnterpriseApplicationPhone() { return enterpriseApplicationPhone; } public void setEnterpriseApplicationPhone(String enterpriseApplicationPhone) { this.enterpriseApplicationPhone = enterpriseApplicationPhone; } @ExcelField(title = "申请企业联系人",sort = 70) public String getEnterpriseApplicationContacts() { return enterpriseApplicationContacts; } public void setEnterpriseApplicationContacts(String enterpriseApplicationContacts) { this.enterpriseApplicationContacts = enterpriseApplicationContacts; } @ExcelField(title = "在华责任单位",sort = 80) public String getResponsibleUnitInChina() { return responsibleUnitInChina; } public void setResponsibleUnitInChina(String responsibleUnitInChina) { this.responsibleUnitInChina = responsibleUnitInChina; } @ExcelField(title = "在华责任单位地址",sort = 90) public String getResponsibleUnitInChinaAddress() { return responsibleUnitInChinaAddress; } public void setResponsibleUnitInChinaAddress(String responsibleUnitInChinaAddress) { this.responsibleUnitInChinaAddress = responsibleUnitInChinaAddress; } @ExcelField(title = "在华责任单位电话",sort = 100) public String getResponsibleUnitInChinaPhone() { return responsibleUnitInChinaPhone; } public void setResponsibleUnitInChinaPhone(String responsibleUnitInChinaPhone) { this.responsibleUnitInChinaPhone = responsibleUnitInChinaPhone; } @ExcelField(title = "在华责任单位传真",sort = 110) public String getResponsibleUnitInChinaFax() { return responsibleUnitInChinaFax; } public void setResponsibleUnitInChinaFax(String responsibleUnitInChinaFax) { this.responsibleUnitInChinaFax = responsibleUnitInChinaFax; } @ExcelField(title = "在华责任单位邮编",sort = 120) public String getResponsibleUnitInChinaZipCode() { return responsibleUnitInChinaZipCode; } public void setResponsibleUnitInChinaZipCode(String responsibleUnitInChinaZipCode) { this.responsibleUnitInChinaZipCode = responsibleUnitInChinaZipCode; } @ExcelField(title = "颜色性状",sort = 130) public String getColorCharacter() { return colorCharacter; } public void setColorCharacter(String colorCharacter) { this.colorCharacter = colorCharacter; } @ExcelField(title = "样品标记(生产日期或批号)",sort = 140) public String getSampleMarking() { return sampleMarking; } public void setSampleMarking(String sampleMarking) { this.sampleMarking = sampleMarking; } @ExcelField(title = "保质期或限期使用日期(包装标注的保质期或限期使用日期)",sort = 150) public String getDateOfExpiry() { return dateOfExpiry; } public void setDateOfExpiry(String dateOfExpiry) { this.dateOfExpiry = dateOfExpiry; } // @ExcelField(title = "保质期(技术要求中显示的保质期",sort = 160) public String getTechnologyDateOfExpiry() { return technologyDateOfExpiry; } public void setTechnologyDateOfExpiry(String technologyDateOfExpiry) { this.technologyDateOfExpiry = technologyDateOfExpiry; } // @ExcelField(title = "气味",sort = 170) public String getSmell() { return smell; } public void setSmell(String smell) { this.smell = smell; } @ExcelField(title = "规格",sort = 180) public String getSpecifications() { return specifications; } public void setSpecifications(String specifications) { this.specifications = specifications; } @ExcelField(title = "行政许可送检时间",sort = 190) public Date getAdministrativeLicenseInspectionTime() { return administrativeLicenseInspectionTime; } public void setAdministrativeLicenseInspectionTime(Date administrativeLicenseInspectionTime) { this.administrativeLicenseInspectionTime = administrativeLicenseInspectionTime; } @ExcelField(title = "行政许可检验机构",sort = 200) public String getAdministrativeLicenseInspectionOrganization() { return administrativeLicenseInspectionOrganization; } public void setAdministrativeLicenseInspectionOrganization(String administrativeLicenseInspectionOrganization) { this.administrativeLicenseInspectionOrganization = administrativeLicenseInspectionOrganization; } @ExcelField(title = "行政许可检验项目",sort = 210) public String getAdministrativeLicenseInspectionProject() { return administrativeLicenseInspectionProject; } public void setAdministrativeLicenseInspectionProject(String administrativeLicenseInspectionProject) { this.administrativeLicenseInspectionProject = administrativeLicenseInspectionProject; } @ExcelField(title = "行政许可送检数量",sort = 220) public String getAdministrativeLicenseInspectionNumber() { return administrativeLicenseInspectionNumber; } public void setAdministrativeLicenseInspectionNumber(String administrativeLicenseInspectionNumber) { this.administrativeLicenseInspectionNumber = administrativeLicenseInspectionNumber; } }
{ "content_hash": "b4d8d74f9027817f4faac72d6afb6622", "timestamp": "", "source": "github", "line_count": 218, "max_line_length": 116, "avg_line_length": 35.78440366972477, "alnum_prop": 0.7317010639661582, "repo_name": "jjeejj/huaxia-messagae-manage", "id": "e85dc5fae66e2d35e04d6d38400a9245754558ab", "size": "8511", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/thinkgem/jeesite/modules/mms/vo/InspectionExportProductVo.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "3753" }, { "name": "ApacheConf", "bytes": "768" }, { "name": "Batchfile", "bytes": "6110" }, { "name": "CSS", "bytes": "889012" }, { "name": "HTML", "bytes": "2486102" }, { "name": "Java", "bytes": "1539149" }, { "name": "JavaScript", "bytes": "7021996" }, { "name": "PHP", "bytes": "8060" }, { "name": "Shell", "bytes": "39" } ], "symlink_target": "" }
package blobstore import ( "os" "path" bosherr "github.com/cloudfoundry/bosh-utils/errors" boshsys "github.com/cloudfoundry/bosh-utils/system" boshuuid "github.com/cloudfoundry/bosh-utils/uuid" ) const ( blobstorePathPermissions = os.FileMode(0770) ) type localBlobstore struct { fs boshsys.FileSystem uuidGen boshuuid.Generator options map[string]interface{} } func NewLocalBlobstore( fs boshsys.FileSystem, uuidGen boshuuid.Generator, options map[string]interface{}, ) Blobstore { return localBlobstore{ fs: fs, uuidGen: uuidGen, options: options, } } func (b localBlobstore) Get(blobID, _ string) (fileName string, err error) { file, err := b.fs.TempFile("bosh-blobstore-external-Get") if err != nil { return "", bosherr.WrapError(err, "Creating temporary file") } fileName = file.Name() err = b.fs.CopyFile(path.Join(b.path(), blobID), fileName) if err != nil { b.fs.RemoveAll(fileName) return "", bosherr.WrapError(err, "Copying file") } return fileName, nil } func (b localBlobstore) CleanUp(fileName string) error { b.fs.RemoveAll(fileName) return nil } func (b localBlobstore) Delete(blobID string) error { blobPath := path.Join(b.path(), blobID) return b.fs.RemoveAll(blobPath) } func (b localBlobstore) Create(fileName string) (blobID string, fingerprint string, err error) { blobID, err = b.uuidGen.Generate() if err != nil { err = bosherr.WrapError(err, "Generating blobID") return } err = b.fs.MkdirAll(b.path(), blobstorePathPermissions) if err != nil { err = bosherr.WrapError(err, "Making blobstore path") blobID = "" return } err = b.fs.CopyFile(fileName, path.Join(b.path(), blobID)) if err != nil { err = bosherr.WrapError(err, "Copying file to blobstore path") blobID = "" return } return } func (b localBlobstore) Validate() error { path, found := b.options["blobstore_path"] if !found { return bosherr.Error("missing blobstore_path") } _, ok := path.(string) if !ok { return bosherr.Error("blobstore_path must be a string") } return nil } func (b localBlobstore) path() string { // Validate() makes sure that it's a string return b.options["blobstore_path"].(string) }
{ "content_hash": "6b49d4c45a5a4ab8bb701b6b660f18f5", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 96, "avg_line_length": 21.742574257425744, "alnum_prop": 0.7017304189435337, "repo_name": "forrestsill/bosh-init", "id": "7530b68cdc37f6f21b3b4dc28f21ea0c63d69941", "size": "2196", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "vendor/github.com/cloudfoundry/bosh-utils/blobstore/local_blobstore.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "2758972" }, { "name": "Ruby", "bytes": "974" }, { "name": "Shell", "bytes": "18137" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "0ba68e38ab143895d43989197d09f525", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "4951d191ff45506c60c774083cd2bbfd1fb7b6a6", "size": "189", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Garnotia/Garnotia fergusonii/ Syn. Garnotia deflexa ferruginea/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "9e594880bd378c734d67287e815fd46f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "c66200dc32b16f816e4e3cd9b1bd5c3a619cc26e", "size": "187", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Dipsacales/Adoxaceae/Viburnum/Viburnum microcarpum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<img src="https://img.shields.io/badge/build-passing-brightgreen.svg" alt="build-passing"> <img src="https://img.shields.io/badge/issues-1%20open-yellow.svg" alt="issues-1"> <img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="license-mit"> <img src="https://img.shields.io/badge/platform-windows%20%7C%20linux-lightgrey.svg" alt="platform-win-lin"> It is a web sraper software which uses Wikipedia database to extract the episode titles of the TV show requested by the user. It asks the user to provide the directory of the TV show. The program uses the scraped data to rename the episodes. The program uses a command line interface. The program has been tested on Windows and Linux platfoms ## Screenshots <img src="screenshots/Screenshot-1.png" alt="main-screen"> <img src="screenshots/Screenshot-2.png" alt="renaming"> <img src="screenshots/Screenshot-3.png" alt="end-screen"> ## Libraries required <ul> <li>requests: For loading webpages</li> <li>BeautifulSoup: For extracting required data from the webpage</li> <li>os: For accessing directories and renaming files</li> <li>re: For sorting lists using Regular Expression</li> </ul> ## Issues The program asks the user for the name of the TV show and then look for the respective URL to its list of episodes. Something like this: `https://en.wikipedia.org/wiki/List_of_<insert episode name>_episodes` In some cases, if the episode name isn't poperly capitalized, the webpage fails to load. Therefore, user is required to manually enter the name of the episodes. ## Installation To run this script, Python3 must be installed. Linux comes pre-installed with Python, nut in case it is not installed, open the terminal and type the following commands: ``` $ sudo apt-get python3 ``` If you're a distro other than Ubuntu, then change `apt-get` with you're package manager. If you're a Windows user, you can download Python from its <a href="https://www.python.org/downloads/windows/">official website</a>. Follow the installation guide from there. You also need t download the `requests` and `BeautifulSoup` libraries. To do so, open terminal (Command propmt in Windows) and type the following commads: ``` $ pip install requests $ pip install beautifulsoup4 ``` To build the project file open the project directory, right click and select 'Open in Terminal' on Linux. For Windows, hold Shift key and click right button, select the 'Open command window here' option. ``` In Linux type: python3 ./sample.py In Windows type: python ./sample.py ``` ## References You can find more information related to the project on <a href="http://quarkbits.com" title="QuarkBits">QuarkBits</a>. The web scraping part of the project is discussed <a href="http://quarkbits.com/tv-show-rename" title="Part 1">here</a>. To know more about how to manipulate the exracted data <a href="http://quarkbits.com/tv-show-rename-2" title="Part 2">click here</a>. ## License TV-Show-Rename is licensed under MIT License. Read the LICENSE file for futher information.
{ "content_hash": "fedadc4c041dd28f6f3813ed1ad600fd", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 342, "avg_line_length": 50.35, "alnum_prop": 0.759682224428997, "repo_name": "bhatushar/TV-Show-Rename", "id": "ad24c748d8db212fc8f81fef7f9ca3abc962b326", "size": "3039", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "6192" } ], "symlink_target": "" }
package com.paypal.selion.reader; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.paypal.selion.elements.HtmlSeLionElementSet.HtmlSeLionElement; import com.paypal.selion.platform.web.GUIElement; import com.paypal.selion.platform.web.HtmlContainerElement; import com.paypal.selion.plugins.CodeGeneratorLoggerFactory; import com.paypal.selion.platform.web.Page; import com.paypal.selion.platform.web.PageFactory; import com.paypal.selion.plugins.TestPlatform; /** * Concrete YAML reader that is capable of reading YAML V2 format file. */ // TODO Merge this with "clients" version of a class by the same name.. Move merged result to "common" class YamlV2Reader extends AbstractYamlReader { /** * This is a public constructor to create an input stream and YAML instance for the input file. * * @param fileName * the name of the YAML data file. * @throws IOException */ public YamlV2Reader(String fileName) throws IOException { super(); FileSystemResource resource = new FileSystemResource(fileName); processPage(resource); } @Override public void processPage(FileSystemResource resource) throws IOException { try { InputStream is = resource.getInputStream(); String fileName = resource.getFileName(); Page page = PageFactory.getPage(is); setBaseClassName(page.getBaseClass()); CodeGeneratorLoggerFactory.getLogger().debug( String.format("++ Attempting to process %s as PageYAML V2", fileName)); TestPlatform currentPlatform = TestPlatform.identifyPlatform(page.getPlatform()); if (currentPlatform == null) { throw new IllegalArgumentException("Missing or invalid platform specified in " + fileName); } setPlatform(currentPlatform); for (Entry<String, GUIElement> eachElement : page.getElements().entrySet()) { if (!eachElement.getKey().isEmpty()) { appendKey(eachElement.getKey()); if ((currentPlatform == TestPlatform.WEB) && HtmlSeLionElement.CONTAINER.looksLike(eachElement.getKey()) && !eachElement.getValue().getContainerElements().isEmpty()) { Map<String, HtmlContainerElement> allElements = eachElement.getValue().getContainerElements(); List<String> elementKeys = parseKeysForContainer(fileName, allElements); for (String elementKey : elementKeys) { // concat parent key separated with # to retain association appendKey(eachElement.getKey() + DELIMITER + elementKey); } } } } setProcessed(true); } catch (Exception e) { // NOSONAR // Just log an debug message. The input is probably not a V2 PageYAML CodeGeneratorLoggerFactory.getLogger().debug( String.format("Unable to process %s as PageYAML V2.\n\t %s", resource.getFileName(), e.getLocalizedMessage())); } } }
{ "content_hash": "8da2051473a73269ee10adb02517cedb", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 118, "avg_line_length": 42.794871794871796, "alnum_prop": 0.628220491312163, "repo_name": "paypal/SeLion", "id": "6384a888b4d6bce515ff6e6d751d26125a3f177d", "size": "5017", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "codegen/src/main/java/com/paypal/selion/reader/YamlV2Reader.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "53471" }, { "name": "HTML", "bytes": "88618" }, { "name": "Java", "bytes": "3238900" }, { "name": "JavaScript", "bytes": "158386" }, { "name": "Objective-C", "bytes": "24249" }, { "name": "Shell", "bytes": "10114" } ], "symlink_target": "" }
<div class="container" ng-controller="HeaderController as vm"> <div class="navbar-header"> <button class="navbar-toggle" type="button" ng-click="vm.isCollapsed = !vm.isCollapsed"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a ui-sref="home" class="navbar-brand">MEAN.JS</a> </div> <nav class="navbar-collapse" uib-collapse="!vm.isCollapsed" role="navigation"> <ul class="nav navbar-nav" ng-if="vm.menu.shouldRender(vm.authentication.user);"> <li ng-repeat="item in vm.menu.items | orderBy: 'position'" ng-if="item.shouldRender(vm.authentication.user);" ng-switch="item.type" ng-class="{ dropdown: item.type === 'dropdown' }" ui-sref-active="active" class="{{item.class}}" uib-dropdown="item.type === 'dropdown'"> <a ng-switch-when="dropdown" class="dropdown-toggle" uib-dropdown-toggle role="button">{{::item.title}}&nbsp;<span class="caret"></span></a> <ul ng-switch-when="dropdown" class="dropdown-menu"> <li ng-repeat="subitem in item.items | orderBy: 'position'" ng-if="subitem.shouldRender(vm.authentication.user);"> <a ui-sref="{{subitem.state}}({{subitem.params}})" ng-bind="subitem.title"></a> </li> </ul> <a ng-switch-default ui-sref="{{item.state}}" ng-bind="item.title"></a> </li> </ul> <ul class="nav navbar-nav navbar-right" ng-hide="vm.authentication.user"> <li ui-sref-active="active"> <a ui-sref="authentication.signup">Sign Up</a> </li> <li class="divider-vertical"></li> <li ui-sref-active="active"> <a ui-sref="authentication.signin">Sign In</a> </li> </ul> <ul class="nav navbar-nav navbar-right" ng-show="vm.authentication.user"> <li class="dropdown" uib-dropdown> <a class="dropdown-toggle user-header-dropdown-toggle" uib-dropdown-toggle role="button"> <img ng-src="/{{vm.authentication.user.profileImageURL}}" alt="{{vm.authentication.user.displayName}}" class="header-profile-image" /> <span ng-bind="vm.authentication.user.displayName"></span> <b class="caret"></b> </a> <ul class="dropdown-menu" role="menu"> <li ui-sref-active="active" ng-repeat="item in vm.accountMenu.items"> <a ui-sref="{{item.state}}" ng-bind="item.title"></a> </li> <li class="divider"></li> <li> <a ng-click="vm.signout()" href="/api/auth/signout" target="_self">Signout</a> </li> </ul> </li> </ul> </nav> </div>
{ "content_hash": "540c52f9c303d741e37be17a76d79cab", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 276, "avg_line_length": 52.98, "alnum_prop": 0.6096640241600604, "repo_name": "ninox92/cookiebot-web", "id": "5ad730ff178a5d314b690c94fbb9f8543fa097b5", "size": "2649", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/core/client/views/header.client.view.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "61" }, { "name": "CSS", "bytes": "1295" }, { "name": "HTML", "bytes": "44575" }, { "name": "JavaScript", "bytes": "408348" }, { "name": "Ruby", "bytes": "138" }, { "name": "Shell", "bytes": "685" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> Week 1: Git </title> </head> <body> <main> <h1>Week 1</h1> <article> <h2>Git and Version Control</h2> <h4>Thursday November 12th, 2015</h4> <p> What are the benefits of version control? Before discussing the benefits of version control we should define it beforehand. Version control is a system of tracking that allows any modifications or changes to be traced back to. What this means is simply if any changes are made that could potentially negatively affect a "version" of a project we can return to any previous version before this error or mistake and work from there. The benefits are enormous as it saves time and makes work more efficient. It also avoids work overlap when working and collaborating with others on more complicated projects. Git, the version control we will be discussing in this blog post, is the version control tool used on the website GitHub. It thus allows us to see who made which changes and when and makes work a lot more efficient. </p> <p> How does git help you keep track of changes? There are three stanges to a change on git. The first,the working stage, is basically the first step when you are working on a file in a directory and making any modifications. This stage is untracked or isn't saved yet. The second stage when you would like to add the modifications before "committing" them or saving them is the "staged". When you are done working and want to save your progress ( just like a checkpoint in a videogame) you then "commit" the last stage of git stages. These three steps allow to ensure modifications are made properly and once saved you can see when the change was made and who made the change as well with a simple "git log" command on the command line. </p> <p> Why use GitHub to store your code? GitHub is a remote hub. On GitHub you can store your code and collaborate on projects with other developers. This community and "social" coding website is a great haven to store code because it allows others to look at your code before you submit to your master branch ( where all your working code is!) and adds an extra layer of protection. Not too get too much in depth with GitHub lingo, but you do this by making a "Pull request" which basically lets others know that you'd like your code to be reviewed. </p> </article> </main> </body> </html> <!-- What HTML5 tags have you used in this challenge and continue to return to often? Why? The HTML5 tags I've used over and over are section and article because they help define the content of the page. These tags help to organize your information in a logical way; this important for people reading your code and it makes it easier on yourself when writing the CSS. How do elements get laid out on a page? What is the order the browser uses to display elements? Elements get laid out on a page like an outline. You lay out the main components such as <html>, <header>, and <body> and then fill in with more specific content using headers, paragraphs, sections, etc. The browser reads the html form the top down. So a header put above a paragraph will display in that order. What did you learn about Sublime in this challenge? Do you think you'll create more handy snippets at a later date? What about research some shortcuts that already exist? I did not know that you could create your own snippets in Sublime before this challenge. I knew about packages like Emmett but it's nice to know that I can create my own snippets specific to my needs. Now that I know about this I will definitely keep it in mind and create some some that might apply for other languages. I did do a quick search and quickly found some pre-existing snippets that I can start using. -->
{ "content_hash": "3951e2470d4d2eff803c95faeb5bb76c", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 787, "avg_line_length": 94.04878048780488, "alnum_prop": 0.754408713692946, "repo_name": "cstallings1/phase-0", "id": "aafd5416a15e67b8253cec132ff7e1ff938cda32", "size": "3856", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "week-3/dissect-me.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5153" }, { "name": "HTML", "bytes": "23634" }, { "name": "JavaScript", "bytes": "45878" }, { "name": "Ruby", "bytes": "177284" } ], "symlink_target": "" }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.dac2014equipe3.sujet2.model.entity; import com.dac2014equipe3.sujet2.vo.MemberVo; import com.dac2014equipe3.sujet2.vo.MemberbacksProjectVo; import com.dac2014equipe3.sujet2.vo.ProjectVo; import com.dac2014equipe3.sujet2.vo.RewardVo; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * * @author Jummartinezro */ @Entity @Table(name = "Project", catalog = "sujet2", schema = "") @NamedQueries({ @NamedQuery(name = "Project.findAll", query = "SELECT p FROM Project p"), @NamedQuery(name = "Project.findByProjectId", query = "SELECT p FROM Project p " + "WHERE p.projectId = :projectId"), @NamedQuery(name = "Project.findByProjectTitle", query = "SELECT p FROM Project p " + "WHERE p.projectTitle = :projectTitle"), @NamedQuery(name = "Project.findByProjectFundingGoal", query = "SELECT p FROM Project p " + "WHERE p.projectFundingGoal = :projectFundingGoal"), @NamedQuery(name = "Project.findByProjectCreationDate", query = "SELECT p FROM Project p " + "WHERE p.projectCreationDate = :projectCreationDate"), @NamedQuery(name = "Project.findByProjectEndDate", query = "SELECT p FROM Project p " + "WHERE p.projectEndDate = :projectEndDate"), @NamedQuery(name = "Project.findByProjectDescription", query = "SELECT p FROM Project p " + "WHERE p.projectDescription = :projectDescription"), @NamedQuery(name = "Project.findByProjectIsSuppressed", query = "SELECT p FROM Project p " + "WHERE p.projectIsSuppressed = :projectIsSuppressed"), @NamedQuery(name = "Project.findByProjectIsClosed", query = "SELECT p FROM Project p " + "WHERE p.projectIsClosed = :projectIsClosed"), @NamedQuery(name = "Project.findByProjectIsClosedAndIsSuppressed", query = "SELECT p FROM Project p " + "WHERE p.projectIsClosed = :projectIsClosed and p.projectIsSuppressed = :projectIsSuppressed")}) public class Project implements Serializable, IEntity<ProjectVo> { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Basic(optional = false) @Column(name = "projectId") private Integer projectId; @Basic(optional = false) @NotNull @Size(min = 1, max = 45) @Column(name = "ProjectTitle") private String projectTitle; @Basic(optional = false) @NotNull @Column(name = "projectFundingGoal") private int projectFundingGoal; @Basic(optional = false) @NotNull @Column(name = "projectCreationDate") @Temporal(TemporalType.DATE) private Date projectCreationDate; @Basic(optional = false) @NotNull @Column(name = "projectEndDate") @Temporal(TemporalType.DATE) private Date projectEndDate; @Basic(optional = false) @NotNull @Size(min = 1, max = 2000) @Column(name = "projectDescription") private String projectDescription; @Column(name = "projectIsSuppressed") private Boolean projectIsSuppressed; @Column(name = "projectIsClosed") private Boolean projectIsClosed; @ManyToMany(mappedBy = "projectList") private List<Member> memberList; @JoinColumn(name = "projectCategory", referencedColumnName = "categoryId") @ManyToOne(optional = false) private ProjectCategory projectCategory; @OneToMany(cascade = CascadeType.ALL, mappedBy = "projectprojectId") private List<Media> mediaList; @OneToMany(cascade = CascadeType.ALL, mappedBy = "project") private List<MemberbacksProject> memberbacksProjectList; @OneToMany(cascade = CascadeType.ALL, mappedBy = "project") private List<Reward> reward; public Project() { } public Project(Integer projectId) { this.projectId = projectId; } public Project(Integer projectId, String projectTitle, int projectFundingGoal, Date projectCreationDate, Date projectEndDate, String projectDescription) { this.projectId = projectId; this.projectTitle = projectTitle; this.projectFundingGoal = projectFundingGoal; this.projectCreationDate = projectCreationDate; this.projectEndDate = projectEndDate; this.projectDescription = projectDescription; } public Project(ProjectVo projectVo){ List<Reward> rewardList = new ArrayList<Reward>(); int i=0; for(Reward reward : rewardList){ rewardList.add(new Reward(projectVo.getListReward().get(i++))); } this.setMediaList(projectVo.getMediaList()); this.setMemberList(projectVo.getMemberList()); this.setMemberbacksProjectList(projectVo.getMemberbacksProjectList()); this.setProjectCategory(projectVo.getProjectCategory()); this.setProjectCreationDate(projectVo.getProjectCreationDate()); this.setProjectDescription(projectVo.getProjectDescription()); this.setProjectEndDate(projectVo.getProjectEndDate()); this.setProjectFundingGoal(projectVo.getProjectFundingGoal()); this.setProjectId(projectVo.getProjectId()); this.setProjectIsSuppressed(projectVo.getProjectIsSuppressed()); this.setProjectTitle(projectVo.getProjectTitle()); this.setReward(rewardList); } public Integer getProjectId() { return projectId; } public void setProjectId(Integer projectId) { this.projectId = projectId; } public String getProjectTitle() { return projectTitle; } public void setProjectTitle(String projectTitle) { this.projectTitle = projectTitle; } public int getProjectFundingGoal() { return projectFundingGoal; } public void setProjectFundingGoal(int projectFundingGoal) { this.projectFundingGoal = projectFundingGoal; } public Date getProjectCreationDate() { return projectCreationDate; } public void setProjectCreationDate(Date projectCreationDate) { this.projectCreationDate = projectCreationDate; } public Date getProjectEndDate() { return projectEndDate; } public void setProjectEndDate(Date projectEndDate) { this.projectEndDate = projectEndDate; } public String getProjectDescription() { return projectDescription; } public void setProjectDescription(String projectDescription) { this.projectDescription = projectDescription; } public Boolean getProjectIsSuppressed() { return projectIsSuppressed; } public void setProjectIsSuppressed(Boolean projectIsSuppressed) { this.projectIsSuppressed = projectIsSuppressed; } public List<Member> getMemberList() { return memberList; } public void setMemberList(List<Member> memberList) { this.memberList = memberList; } public ProjectCategory getProjectCategory() { return projectCategory; } public void setProjectCategory(ProjectCategory projectCategory) { this.projectCategory = projectCategory; } public List<Media> getMediaList() { return mediaList; } public void setMediaList(List<Media> mediaList) { this.mediaList = mediaList; } public List<MemberbacksProject> getMemberbacksProjectList() { return memberbacksProjectList; } public void setMemberbacksProjectList(List<MemberbacksProject> memberbacksProjectList) { this.memberbacksProjectList = memberbacksProjectList; } public List<Reward> getReward() { return reward; } public void setReward(List<Reward> reward) { this.reward = reward; } public Boolean getProjectIsClosed() { return projectIsClosed; } public void setProjectIsClosed(Boolean projectIsClosed) { this.projectIsClosed = projectIsClosed; } @Override public int hashCode() { int hash = 0; hash += (projectId != null ? projectId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Project)) { return false; } Project other = (Project) object; if ((this.projectId == null && other.projectId != null) || (this.projectId != null && !this.projectId.equals(other.projectId))) { return false; } return true; } @Override public String toString() { return "com.dac2014equipe3.sujet2.model.entity.Project[ projectId=" + projectId + " ]"; } @Override public ProjectVo toVo() { ProjectVo vo = new ProjectVo(); List<RewardVo> rewardList = new ArrayList<RewardVo>(); int i=0; for(RewardVo reward : rewardList){ rewardList.add(new RewardVo(this.getReward().get(i).getRewardId(), this.getReward().get(i).getRewardName(), this.getReward().get(i).getRewardDescription(), this.getReward().get(i++).getRewardMinPrice())); } vo.setMediaList(mediaList); vo.setMemberList(memberList); vo.setMemberbacksProjectList(memberbacksProjectList); vo.setProjectCategory(projectCategory); vo.setProjectCreationDate(projectCreationDate); vo.setProjectDescription(projectDescription); vo.setProjectEndDate(projectEndDate); vo.setProjectFundingGoal(projectFundingGoal); vo.setProjectId(projectId); vo.setProjectIsSuppressed(projectIsSuppressed); vo.setProjectIsClosed(projectIsClosed); vo.setProjectTitle(projectTitle); vo.setListReward(rewardList); return vo; } }
{ "content_hash": "bfa4d7738b468f16b2519589ad7b1cb8", "timestamp": "", "source": "github", "line_count": 308, "max_line_length": 108, "avg_line_length": 34.51623376623377, "alnum_prop": 0.6906217665318408, "repo_name": "DAC-2014-Equipe-3/sujet-2", "id": "5f8f6641cf23de31fe0b9f52c7d31c73272925eb", "size": "10631", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sujet2/src/main/java/com/dac2014equipe3/sujet2/model/entity/Project.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1025" }, { "name": "Java", "bytes": "783702" } ], "symlink_target": "" }
// Copyright 2017 The Kubernetes Dashboard Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {IntegerValidator} from './integervalidator'; /** * Validators factory allows to register component related validators on demand in place where * they are used. Simply inject 'kdValidatorFactory' into controller and register validator * using 'registerValidator' method. * * Validator object has to fulfill validator object contract which is to implement 'Validator' * class and 'isValid(value)' method. * * @final */ export class ValidatorFactory { /** * @constructs ValidatorFactory */ constructor() { /** @private {Map<string, !./validator.Validator>} */ this.validatorMap_ = new Map(); // Register common validators here this.registerValidator('integer', new IntegerValidator()); } /** * Used to register validators on demand. * * @param {string} validatorName * @param {!./validator.Validator} validatorObject */ registerValidator(validatorName, validatorObject) { if (this.validatorMap_.has(validatorName)) { throw new Error(`Validator with name ${validatorName} is already registered.`); } this.validatorMap_.set(validatorName, validatorObject); } /** * Returns specific Type class based on given type name. * * @param {string} validatorName * @returns {!./validator.Validator} */ getValidator(validatorName) { let validatorObject = this.validatorMap_.get(validatorName); if (!validatorObject) { throw new Error(`Given validator '${validatorName}' is not supported.`); } return validatorObject; } }
{ "content_hash": "8f033fd23bab20321c0338c93d7a8cdd", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 94, "avg_line_length": 31.61764705882353, "alnum_prop": 0.7102325581395349, "repo_name": "vlal/dashboard", "id": "2698d5827c53f9cbce09957dfd3968cd8d42f1b8", "size": "2150", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/app/frontend/common/validators/factory.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "65478" }, { "name": "Go", "bytes": "921687" }, { "name": "HTML", "bytes": "460526" }, { "name": "JavaScript", "bytes": "1524499" }, { "name": "Shell", "bytes": "7094" }, { "name": "XSLT", "bytes": "2542" } ], "symlink_target": "" }
<pre> Tehtävien palautuksen deadline su 3.12. klo 23.59 ohjausta tehtävien tekoon to ja pe klo 14-16 salissa B221 </pre> ## palautetaan GitHubin kautta * palautusta varten voit käyttää samaa repoa kuin aiemman viikon palautuksissasi * palautusrepositorion nimi ilmoitetaan tehtävien lopussa olevalla palautuslomakkeella ## typokorjaukset ja vihjeet Jos huomaat tehtävissä tai muussa materiaalissa kirjoitusvirheitä, toimi [ohjeen](https://github.com/mluukkai/ohjelmistotuotanto2017/blob/master/laskarit/3.md#typokorjauksia--vinkkejä) mukaan. Kannattaa myös lukea ja tarvittaessa täydentää viikon tehtäviin liittyviä [vihjeitä](https://github.com/mluukkai/ohjelmistotuotanto2017/blob/master/laskarit/5-tips.md#) ## Oliosuunnittelun itseopiskelumateriaali Ennen tehtävien 1 ja 2 tekemistä, lue oliosuunnittelun [itseopiskelumateriaalia](https://github.com/mluukkai/ohjelmistotuotanto2017/blob/master/web/oliosuunnittelu.md) alusta osan [koheesio metoditasolla](https://github.com/mluukkai/ohjelmistotuotanto2017/blob/master/web/oliosuunnittelu.md#koheesio-metoditasolla) loppuun. Enempää et tarvitse tämän viikon tehtäviin. Materiaaliin palataan tarkemmin ensi viikon laskareissa. ## 1. IntJoukon testaus ja siistiminen * Hae [kurssirepositorion](https://github.com/mluukkai/ohjelmistotuotanto2017) hakemistossa [koodi/viikko5/IntJoukkoSovellus](https://github.com/mluukkai/ohjelmistotuotanto2017/tree/master/koodi/viikko5/IntJoukkoSovellus) aloittelevan ohjelmoijan ratkaisu syksyn 2011 Ohjelmoinnin Jatkokurssin viikon 2 tehtävään 3 (ks. http://www.cs.helsinki.fi/u/wikla/ohjelmointi/jatko/s2011/harjoitukset/2/ * ratkaisussa joukko-operaatiot on toteutettu suoraan luokkaan IntJoukko staattisina metodeina * koodi jättää hieman toivomisen varaa ylläpidettävyyden suhteen * refaktoroi luokan IntJoukko koodi mahdollisimman siistiksi * copypaste pois * muuttujille selkeät nimet * ei pitkiä (yli 10 rivisiä) metodeja * koodissa on refaktorointia helpottamaan joukko yksikkötestejä *HUOM* refaktoroi mahdollisimman pienin askelin ja pidä koodi koko ajan toimivana. Suorita testit aina jokaisen refaktorointiaskeleen jälkeen! Järkevä refaktorointiaskeleen koko pieni muutos yhteen metodiin. ## 2. Tenniksen pisteenlaskun refaktorointi [Kurssirepositorion](https://github.com/mluukkai/ohjelmistotuotanto2017) hakemistossa [koodi/viikko5/Tennis](https://github.com/mluukkai/ohjelmistotuotanto2017/tree/master/koodi/viikko5/Tennis), löytyy ohjelma joka on tarkoitettu tenniksen [pisteenlaskentaan](https://github.com/emilybache/Tennis-Refactoring-Kata#tennis-kata). Pisteenlaskennan rajapinta on yksinkertainen. Metodi <code>void getScore()</code> kertoo voimassa olevan tilanteen tennispisteenlaskennan määrittelemän tavan mukaan. Sitä mukaa kun jompi kumpi pelaajista voittaa palloja, kutsutaan metodia <code>void wonPoint(String player)</code> jossa parametrina on pallon voittanut pelaaja. Esim. käytettäessä pisteenlaskentaa seuraavasti: ``` java public static void main(String[] args) { TennisGame game = new TennisGame("player1", "player2"); System.out.println(game.getScore()); game.wonPoint("player1"); System.out.println(game.getScore()); game.wonPoint("player1"); System.out.println(game.getScore()); game.wonPoint("player2"); System.out.println(game.getScore()); game.wonPoint("player1"); System.out.println(game.getScore()); game.wonPoint("player1"); System.out.println(game.getScore()); } ``` tulostuu ``` java Love-All Fifteen-Love Thirty-Love Thirty-Fifteen Forty-Fifteen Win for player1 ``` Tulostuksessa siis kerrotaan mikä on pelitilanne kunkin pallon jälkeen kun _player1_ voittaa ensimmäiset 2 palloa, _player2_ kolmannen pallon ja _player1_ loput 2 palloa. Pisteenlaskentaohjelman koodi toimii ja sillä on erittäin kattavat testit. Koodi on kuitenkin luettavuudeltaan erittäin huonossa kunnossa. Tehtävänä on refaktoroida koodi luettavuudeltaan mahdollisimman ymmärrettäväksi. Koodissa tulee välttää "taikanumeroita" ja huonosti nimettyjä muuttujia. Koodi kannattaa jakaa moniin pieniin metodeihin, jotka nimennällään paljastavat oman toimintalogiikkansa. Etene refaktoroinnissa __todella pienin askelin__. Aja testejä mahdollisimman usein. Yritä pitää ohjelma koko ajan toimintakunnossa. Jos haluat käyttää jotain muuta kieltä kuin Javaa, löytyy koodista ja testeistä versioita useilla eri kielillä osoitteesta [https://github.com/emilybache/Tennis-Refactoring-Kata](https://github.com/emilybache/Tennis-Refactoring-Kata) Tehtävä on kenties hauskinta tehdä pariohjelmoiden. Itse tutustuin tehtävään kesällä 2013 Extreme Programming -konferenssissa järjestetyssä Coding Dojossa, jossa tehtävä tehtiin satunnaisesti valitun parin kanssa pariohjelmoiden. Lisää samantapaisia refaktorointitehtäviä osoitteessa Emily Bachen [GitHub-sivulta](https://github.com/emilybache) ## 3. git: vahingossa tuhotun tiedoston palautus _tehtävien 3-6 ei tarvitse näkyä palautuksessa, riittää kun teet tehtävät_ * viikon 4 [tehtävässä 1](https://github.com/mluukkai/ohjelmistotuotanto2017/blob/master/laskarit/4.md#1-git-tägit) palasimme jo menneisyyteen checkouttaamalla tagillä merkittyyn kohtaan * katsotaan nyt miten voimme palauttaa jonkun menneisyydessä olevan tilanteen uudelleen voimaan * tee tiedosto xxx, lisää ja committaa se * poista tiedosto ja committaa * tee jotain muutoksia johonkin tiedostoon ja committaa * historiasi näyttää seuraavalta <pre> (1) - (2) - (3) </pre> * Nykyhetki eli HEAD on (3). Commitissa (1) tiedosto xxx on olemassa, nykyhetkellä ja (2):ssa xxx:ää ei ole. * huom: komennolla <code>gitk</code> voit tutkia historiaa * haluamme palauttaa tiedoston * selvitä sen commitin id, jossa tiedosto vielä on olemassa, tämä onnistuu gitk:lla tai <code>git log</code> -komennolla * anna komento <code>git checkout 3290b03cea08af987ee7ea57bb98a4886b97efe0 -- xxx</code> missä pitkä merkkijono on siis kyseisen commitin id * varmista että tiedosto on ilmestynyt staging-alueelle komennolla <code>git status</code> * tee commit * xxx on palannut! * HUOM: koko id:tä ei komennossa tarvitse antaa, riittää antaa alusta niin monta merkkiä, että niiden perusteella id voidaan päätellä yksikäsitteisesti repositoriosi historiassa * "Generally, eight to ten characters are more than enough to be unique within a project. For example, as of October 2017, the Linux kernel (which is a fairly sizable project) has over 700,000 commits and almost six million objects, with no two objects whose SHA-1s are identical in the first 11 characters." [7.1 Git Tools - Revision Selection ](https://git-scm.com/book/en/v2/Git-Tools-Revision-Selection#Short-SHA-1) * Täsmälleen samalla tavalla onnistuu olemassaolevan tiedoston vanhan version palauttaminen. ## 4. git: commitin muutosten kumoaminen * huomaamme, että juuri tehty commit oli virhe, kumotaan se sanomalla <code>git revert HEAD --no-edit</code> * HEAD siis viittaa siihen committiin minkä kohdalla nyt ollaan * syntyy uusi commit, jossa edellisessä tehdyt muutokset on kumottu * ilman optiota __no-edit__ pääset editoimaan kumoamiseen liittyvään commitiin tulevaa viestiä * huom: sanomalla <code>git checkout HEAD^</code> pääsemme takaisin kumottuun tilanteeseen, eli mitään ei ole lopullisesti kadotettu * vastaavalla tavalla voidaan revertata mikä tahansa commit eli: <code>git revert kumottavancommitinid</code> ## 5. git: branchin "siirtäminen" * tee repoosi branchi nimeltä haara ja tee masteriin ja haaraan committeja siten että saat aikaan seuraavankaltaisen tilanteen: <pre> /------master -- \---haara </pre> * eli sekä master että haara ovat edenneet muutamien commitien verran haarautumisen tapahduttua * huom: komennolla <code>gitk --all</code> näet kaikki haarat, kokeile! * yhtäkkiä huomaat, että master:iin tekemäsi asiat eivät olekaan kovin hyviä ja haara:ssa on paljon parempaa tavaraa, haluaisitkin että haara:sta tulisi uusi master * tämä onnistuu kun menet masteriin ja annat komennon <code>git reset --hard haara</code> * varmista että komento toimii oikein * vanhan master-haarankaan tavarat eivät katoa mihinkään, jos niihin jostain syystä vielä halutaan palata * vanhaan committiin palaaminen onnistuu jos commitin id on tiedossa, jos ei on olemassa [muutamia keinoja](http://stackoverflow.com/questions/4786972/list-of-all-git-commits) sen selvittämiseksi ## 6. Git: rebase Lue <http://git-scm.com/book/en/Git-Branching-Rebasing> ja <https://www.atlassian.com/git/tutorials/rewriting-history#git-rebase> Aikaansaa seuraavankaltainen tilanne <pre> ------- master \ \--- haara </pre> "rebeissaa" haara masteriin, eli aikaansaa seuraava tilanne: <pre> ------- master \ \--- haara </pre> Varmista komennolla <code>gitk --all</code> että tilanne on haluttu. "mergeä" master vielä haaraan: <pre> ------- \ master \--- haara </pre> Lopputuloksena pitäisi siis olla lineaarinen historia ja master sekä haara samassa. Varmista jälleen komennolla <code>gitk --all</code> että kaikki on kunnossa. Poista branch haara. Etsi googlaamalla komento jolla saat tuhottua branchin. ## tehtävien kirjaaminen palautetuksi tehtävien kirjaus: * Kirjaa tekemäsi tehtävät osoitteeseen https://studies.cs.helsinki.fi/ohtustats * huom: tehtävien palautuksen deadline on su 3.12. klo 23.59 palaute tehtävistä: * tee viikon 1 viimeisessä forkaamasi repositorioon jokin muutos * tee viime viikon tehtävän tapaan pull-request * anna tehtävistä palautetta avautuvaan lomakkeeseen * huom: jos teeh tehtävät alkuviikosta, voi olla, että edellistä pull-requestiasi ei ole vielä ehditty hyväksyä ja et pääse vielä tekemään uutta requestia
{ "content_hash": "3a2bb900c642daa48d990f4925855069", "timestamp": "", "source": "github", "line_count": 196, "max_line_length": 346, "avg_line_length": 49.38265306122449, "alnum_prop": 0.7968798429589834, "repo_name": "mluukkai/ohjelmistotuotanto2017", "id": "01c05b680e05eab3f1167c83a17c94726d4b6ab0", "size": "9880", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "laskarit/5.md", "mode": "33188", "license": "mit", "language": [ { "name": "Gherkin", "bytes": "3622" }, { "name": "HTML", "bytes": "4460" }, { "name": "Java", "bytes": "96701" } ], "symlink_target": "" }
package dao.impl; import dao.BaseDao; import dao.PointRecordDao; import model.pointrecord.PointRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; import utils.IDGenerator; import utils.ResponseCode; import utils.ResultData; import vo.pointrecord.PointValueVO; import java.util.List; import java.util.Map; @Repository public class PointRecordDaoImpl extends BaseDao implements PointRecordDao{ private Logger logger = LoggerFactory.getLogger(PointRecordDaoImpl.class); private final static Object lock = new Object(); @Override public ResultData insert(PointRecord pointRecord) { ResultData resultData = new ResultData(); pointRecord.setRecordId(IDGenerator.generate("PRD")); synchronized (lock) { try { sqlSession.insert("management.pointrecord.insert", pointRecord); resultData.setData(pointRecord); } catch (Exception e) { resultData.setResponseCode(ResponseCode.RESPONSE_ERROR); logger.error(e.getMessage()); resultData.setDescription(e.getMessage()); return resultData; } } return resultData; } @Override public ResultData query(Map<String, Object> condition) { ResultData resultData = new ResultData(); try { List<PointRecord> list = sqlSession.selectList("management.pointrecord.query", condition); if (list.size() == 0) { resultData.setResponseCode(ResponseCode.RESPONSE_NULL); return resultData; } resultData.setData(list); } catch (Exception e) { resultData.setResponseCode(ResponseCode.RESPONSE_ERROR); logger.error(e.getMessage()); resultData.setDescription(e.getMessage()); return resultData; } return resultData; } // 查询用户的积分值 @Override public ResultData queryPoint(Map<String, Object> condition) { ResultData resultData = new ResultData(); try { List<PointValueVO> list = sqlSession.selectList("management.pointvalue.query", condition); if (list.size() == 0) { resultData.setResponseCode(ResponseCode.RESPONSE_NULL); return resultData; } resultData.setData(list); } catch (Exception e) { resultData.setResponseCode(ResponseCode.RESPONSE_ERROR); logger.error(e.getMessage()); resultData.setDescription(e.getMessage()); return resultData; } return resultData; } @Override public ResultData update(PointRecord pointRecord) { return null; } }
{ "content_hash": "d3084924817180f904ba99d692707c82", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 102, "avg_line_length": 32.58139534883721, "alnum_prop": 0.6331192005710207, "repo_name": "gitminingOrg/AirDevice", "id": "711c4cd3f06cc207a0212ccee9e7ab926456b04d", "size": "2818", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "management/src/main/java/dao/impl/PointRecordDaoImpl.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1868830" }, { "name": "HTML", "bytes": "1341685" }, { "name": "Java", "bytes": "792078" }, { "name": "JavaScript", "bytes": "12130539" }, { "name": "SQLPL", "bytes": "1147" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cen.comp313.student_portal" android:versionCode="1" android:versionName="1.0" > <uses-permission android:name="android.permission.INTERNET" /> <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="cen.comp313.student_portal.Login" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="cen.comp313.student_portal.Student_Home" android:label="@string/studentHome"></activity> <activity android:name="cen.comp313.student_portal.SignUp" android:label="@string/signUpStudent"></activity> <activity android:name="cen.comp313.student_portal.Grade_ForeCast" android:label="@string/gradeForcast"></activity> <activity android:name="cen.comp313.student_portal.test" android:label="@string/app_name"></activity> <activity android:name="cen.comp313.student_portal.AllProductsActivity" android:label="@string/allCourse"></activity> <activity android:name="cen.comp313.student_portal.EditCourse" android:label="@string/editCourse"></activity> <activity android:name="cen.comp313.student_portal.EditAsses" android:label="@string/editAddAssessment"></activity> <activity android:name="cen.comp313.student_portal.AddCourse" android:label="@string/addNewCourse"></activity> <activity android:name="cen.comp313.student_portal.Tab_Activity" android:label="@string/studentHome"></activity> <activity android:name="com.project2.meeting.activity.SelectMeetingTimeActivity" android:label="@string/app_name" > <intent-filter> <action android:name="com.project2.meeting.activity.SelectMeetingTimeActivity" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> </application> </manifest>
{ "content_hash": "f50e6ec95509c1b9b35f9b8b54d70da1", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 97, "avg_line_length": 45.41818181818182, "alnum_prop": 0.6493194555644516, "repo_name": "ssasvathan/gradeforcast", "id": "05a131cf4cf94a598f323ee28b27eb671e251385", "size": "2498", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "After_presatation_Copy/Project_two/bin/AndroidManifest.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1" }, { "name": "C++", "bytes": "1" }, { "name": "Java", "bytes": "86951" }, { "name": "PHP", "bytes": "20867" } ], "symlink_target": "" }
''' New Integration Test for Starting Windows VM with Multi Data Volumes. @author: Mirabel ''' import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import zstackwoodpecker.operations.resource_operations as res_ops import os import telnetlib import time test_stub = test_lib.lib_get_test_stub() test_obj_dict = test_state.TestStateDict() def test(): cpuNum = 6 memorySize = 2048 * 1024 * 1024 new_offering = test_lib.lib_create_instance_offering(cpuNum = cpuNum,\ memorySize = memorySize) test_obj_dict.add_instance_offering(new_offering) new_offering_uuid = new_offering.uuid l3_name = os.environ.get('l3VlanNetworkName1') disk_offering = test_lib.lib_get_disk_offering_by_name(os.environ.get('smallDiskOfferingName')) data_volume_uuids = [disk_offering.uuid,disk_offering.uuid,disk_offering.uuid] data_volume_num = 3 volume_list = [] try: vm = test_stub.create_windows_vm_2(l3_name, instance_offering_uuid = new_offering_uuid) test_obj_dict.add_vm(vm) for i in range(data_volume_num): volume_list.append(test_stub.create_volume()) test_obj_dict.add_volume(volume_list[i]) volume_list[i].attach(vm) except: test_lib.lib_robot_cleanup(test_obj_dict) test_util.test_fail('Create Windows VM with Multi Data volumes Test Fail') vm_inv = vm.get_vm() print"vm_uuid:%s"%(vm_inv.uuid) host_inv = test_lib.lib_find_host_by_vm(vm_inv) host_ip = host_inv.managementIp host_username = host_inv.username print"host_username%s"%(host_username) host_password = host_inv.password cmd = "virsh domiflist %s|grep vnic|awk '{print $3}'"% (vm_inv.uuid) br_eth0 = test_lib.lib_execute_ssh_cmd(host_ip, host_username, host_password, cmd, 60) cmd2 = 'ip a add 10.11.254.254/8 dev %s'% (br_eth0) test_lib.lib_execute_ssh_cmd(host_ip, host_username, host_password, cmd2, 60) vm_ip = vm.get_vm().vmNics[0].ip test_lib.lib_wait_target_up(vm_ip, '23', 1200) vm_username = os.environ.get('winImageUsername') vm_password = os.environ.get('winImagePassword') tn=telnetlib.Telnet(vm_ip) tn.read_until("login: ") tn.write(vm_username+"\r\n") tn.read_until("password: ") tn.write(vm_password+"\r\n") tn.read_until(vm_username+">") tn.write("wmic diskdrive\r\n") vm_data_volumes=tn.read_until(vm_username+">") tn.close() if len(vm_data_volumes.split('\r\n')) != (data_volume_num + 6): test_lib.lib_robot_cleanup(test_obj_dict) test_util.test_fail('Create Windows VM with Multi Data volumes Test Fail') try: vm.reboot() except: test_lib.lib_robot_cleanup(test_obj_dict) test_util.test_fail('Reboot Windows VM with Multi Data volumes fail') vm_ip = vm.get_vm().vmNics[0].ip test_lib.lib_wait_target_up(vm_ip, '23', 1200) vm_username = os.environ.get('winImageUsername') vm_password = os.environ.get('winImagePassword') tn=telnetlib.Telnet(vm_ip) tn.read_until("login: ") tn.write(vm_username+"\r\n") tn.read_until("password: ") tn.write(vm_password+"\r\n") tn.read_until(vm_username+">") tn.write("wmic diskdrive\r\n") vm_data_volumes=tn.read_until(vm_username+">") tn.close() if len(vm_data_volumes.split('\r\n')) == (data_volume_num + 6): test_lib.lib_robot_cleanup(test_obj_dict) test_util.test_pass('Create Windows VM with Multi Data Volumes Test Success') else: test_lib.lib_robot_cleanup(test_obj_dict) test_util.test_fail('Create Windows VM with Multi Data volumes Test Fail') #Will be called only if exception happens in test(). def error_cleanup(): global vm if vm: vm.destroy()
{ "content_hash": "858ea2407d523fa274a225438aa924ca", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 99, "avg_line_length": 37.61904761904762, "alnum_prop": 0.6453164556962026, "repo_name": "zstackorg/zstack-woodpecker", "id": "4c53f224f8004891a9fd7e126faa34fd10939cfa", "size": "3950", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "integrationtest/vm/virtualrouter/windows/test_windows_vm_multi_data_volumes.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "46522" }, { "name": "Makefile", "bytes": "692" }, { "name": "Puppet", "bytes": "875" }, { "name": "Python", "bytes": "2891030" }, { "name": "Shell", "bytes": "54266" } ], "symlink_target": "" }
define( /** * @class Confirm * @extends Dialog * @inheritable */ function (require) { var blend = require('../blend'); var lib = require('../lib'); var Dialog = require('../Dialog'); var Confirm = function (content, title, callbackOk, callbackCancel) { Dialog.call(this, { content: content, title: title, buttons: [ { text: blend.configs.dialogBtnCancel, onclick: callbackCancel }, { text: blend.configs.dialogBtnOK, bold: true, onclick: callbackOk } ] }); return this; }; lib.inherits(Confirm, Dialog); Confirm.prototype.title = blend.configs.dialogTitle; Confirm.prototype.content = ""; return Confirm; } );
{ "content_hash": "9eabb7571f16c2b762aa74c257a7b399", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 77, "avg_line_length": 21.75, "alnum_prop": 0.45141065830721006, "repo_name": "guotao2000/ecmall", "id": "abde4a68d042133d5a25e8c4f60fd5b8faa05ba0", "size": "957", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "touch/demo/usecase/www/src/web/dialog/Confirm.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "3753632" }, { "name": "HTML", "bytes": "9733640" }, { "name": "JavaScript", "bytes": "6901890" }, { "name": "PHP", "bytes": "54456938" }, { "name": "Shell", "bytes": "6" } ], "symlink_target": "" }
<?php namespace EntityManager527a624ed9863_546a8d27f194334ee012bfe64f629947b07e4919\__CG__\Doctrine\ORM; /** * CG library enhanced proxy class. * * This code was generated automatically by the CG library, manual changes to it * will be lost upon next generation. */ class EntityManager extends \Doctrine\ORM\EntityManager { private $delegate; private $container; /** * Executes a function in a transaction. * * The function gets passed this EntityManager instance as an (optional) parameter. * * {@link flush} is invoked prior to transaction commit. * * If an exception occurs during execution of the function or flushing or transaction commit, * the transaction is rolled back, the EntityManager closed and the exception re-thrown. * * @param callable $func The function to execute transactionally. * @return mixed Returns the non-empty value returned from the closure or true instead */ public function transactional($func) { return $this->delegate->transactional($func); } /** * Performs a rollback on the underlying database connection. */ public function rollback() { return $this->delegate->rollback(); } /** * Removes an entity instance. * * A removed entity will be removed from the database at or before transaction commit * or as a result of the flush operation. * * @param object $entity The entity instance to remove. */ public function remove($entity) { return $this->delegate->remove($entity); } /** * Refreshes the persistent state of an entity from the database, * overriding any local changes that have not yet been persisted. * * @param object $entity The entity to refresh. */ public function refresh($entity) { return $this->delegate->refresh($entity); } /** * Tells the EntityManager to make an instance managed and persistent. * * The entity will be entered into the database at or before transaction * commit or as a result of the flush operation. * * NOTE: The persist operation always considers entities that are not yet known to * this EntityManager as NEW. Do not pass detached entities to the persist operation. * * @param object $object The instance to make managed and persistent. */ public function persist($entity) { return $this->delegate->persist($entity); } /** * Create a new instance for the given hydration mode. * * @param int $hydrationMode * @return \Doctrine\ORM\Internal\Hydration\AbstractHydrator */ public function newHydrator($hydrationMode) { return $this->delegate->newHydrator($hydrationMode); } /** * Merges the state of a detached entity into the persistence context * of this EntityManager and returns the managed copy of the entity. * The entity passed to merge will not become associated/managed with this EntityManager. * * @param object $entity The detached entity to merge into the persistence context. * @return object The managed copy of the entity. */ public function merge($entity) { return $this->delegate->merge($entity); } /** * Acquire a lock on the given entity. * * @param object $entity * @param int $lockMode * @param int $lockVersion * @throws OptimisticLockException * @throws PessimisticLockException */ public function lock($entity, $lockMode, $lockVersion = NULL) { return $this->delegate->lock($entity, $lockMode, $lockVersion); } /** * Check if the Entity manager is open or closed. * * @return bool */ public function isOpen() { return $this->delegate->isOpen(); } /** * Checks whether the state of the filter collection is clean. * * @return boolean True, if the filter collection is clean. */ public function isFiltersStateClean() { return $this->delegate->isFiltersStateClean(); } /** * Helper method to initialize a lazy loading proxy or persistent collection. * * This method is a no-op for other objects * * @param object $obj */ public function initializeObject($obj) { return $this->delegate->initializeObject($obj); } /** * Checks whether the Entity Manager has filters. * * @return True, if the EM has a filter collection. */ public function hasFilters() { return $this->delegate->hasFilters(); } /** * Gets the UnitOfWork used by the EntityManager to coordinate operations. * * @return \Doctrine\ORM\UnitOfWork */ public function getUnitOfWork() { return $this->delegate->getUnitOfWork(); } /** * Gets the repository for an entity class. * * @param string $entityName The name of the entity. * @return EntityRepository The repository class. */ public function getRepository($className) { $repository = $this->delegate->getRepository($className); if ($repository instanceof \Symfony\Component\DependencyInjection\ContainerAwareInterface) { $repository->setContainer($this->container); return $repository; } if (null !== $metadata = $this->container->get("jms_di_extra.metadata.metadata_factory")->getMetadataForClass(get_class($repository))) { foreach ($metadata->classMetadata as $classMetadata) { foreach ($classMetadata->methodCalls as $call) { list($method, $arguments) = $call; call_user_func_array(array($repository, $method), $this->prepareArguments($arguments)); } } } return $repository; } /** * Gets a reference to the entity identified by the given type and identifier * without actually loading it, if the entity is not yet loaded. * * @param string $entityName The name of the entity type. * @param mixed $id The entity identifier. * @return object The entity reference. */ public function getReference($entityName, $id) { return $this->delegate->getReference($entityName, $id); } /** * Gets the proxy factory used by the EntityManager to create entity proxies. * * @return ProxyFactory */ public function getProxyFactory() { return $this->delegate->getProxyFactory(); } /** * Gets a partial reference to the entity identified by the given type and identifier * without actually loading it, if the entity is not yet loaded. * * The returned reference may be a partial object if the entity is not yet loaded/managed. * If it is a partial object it will not initialize the rest of the entity state on access. * Thus you can only ever safely access the identifier of an entity obtained through * this method. * * The use-cases for partial references involve maintaining bidirectional associations * without loading one side of the association or to update an entity without loading it. * Note, however, that in the latter case the original (persistent) entity data will * never be visible to the application (especially not event listeners) as it will * never be loaded in the first place. * * @param string $entityName The name of the entity type. * @param mixed $identifier The entity identifier. * @return object The (partial) entity reference. */ public function getPartialReference($entityName, $identifier) { return $this->delegate->getPartialReference($entityName, $identifier); } /** * Gets the metadata factory used to gather the metadata of classes. * * @return \Doctrine\ORM\Mapping\ClassMetadataFactory */ public function getMetadataFactory() { return $this->delegate->getMetadataFactory(); } /** * Gets a hydrator for the given hydration mode. * * This method caches the hydrator instances which is used for all queries that don't * selectively iterate over the result. * * @param int $hydrationMode * @return \Doctrine\ORM\Internal\Hydration\AbstractHydrator */ public function getHydrator($hydrationMode) { return $this->delegate->getHydrator($hydrationMode); } /** * Gets the enabled filters. * * @return FilterCollection The active filter collection. */ public function getFilters() { return $this->delegate->getFilters(); } /** * Gets an ExpressionBuilder used for object-oriented construction of query expressions. * * Example: * * <code> * $qb = $em->createQueryBuilder(); * $expr = $em->getExpressionBuilder(); * $qb->select('u')->from('User', 'u') * ->where($expr->orX($expr->eq('u.id', 1), $expr->eq('u.id', 2))); * </code> * * @return \Doctrine\ORM\Query\Expr */ public function getExpressionBuilder() { return $this->delegate->getExpressionBuilder(); } /** * Gets the EventManager used by the EntityManager. * * @return \Doctrine\Common\EventManager */ public function getEventManager() { return $this->delegate->getEventManager(); } /** * Gets the database connection object used by the EntityManager. * * @return \Doctrine\DBAL\Connection */ public function getConnection() { return $this->delegate->getConnection(); } /** * Gets the Configuration used by the EntityManager. * * @return \Doctrine\ORM\Configuration */ public function getConfiguration() { return $this->delegate->getConfiguration(); } /** * Returns the ORM metadata descriptor for a class. * * The class name must be the fully-qualified class name without a leading backslash * (as it is returned by get_class($obj)) or an aliased class name. * * Examples: * MyProject\Domain\User * sales:PriceRequest * * @return \Doctrine\ORM\Mapping\ClassMetadata * @internal Performance-sensitive method. */ public function getClassMetadata($className) { return $this->delegate->getClassMetadata($className); } /** * Flushes all changes to objects that have been queued up to now to the database. * This effectively synchronizes the in-memory state of managed objects with the * database. * * If an entity is explicitly passed to this method only this entity and * the cascade-persist semantics + scheduled inserts/removals are synchronized. * * @param object $entity * @throws \Doctrine\ORM\OptimisticLockException If a version check on an entity that * makes use of optimistic locking fails. */ public function flush($entity = NULL) { return $this->delegate->flush($entity); } /** * Finds an Entity by its identifier. * * @param string $entityName * @param mixed $id * @param integer $lockMode * @param integer $lockVersion * * @return object */ public function find($entityName, $id, $lockMode = 0, $lockVersion = NULL) { return $this->delegate->find($entityName, $id, $lockMode, $lockVersion); } /** * Detaches an entity from the EntityManager, causing a managed entity to * become detached. Unflushed changes made to the entity if any * (including removal of the entity), will not be synchronized to the database. * Entities which previously referenced the detached entity will continue to * reference it. * * @param object $entity The entity to detach. */ public function detach($entity) { return $this->delegate->detach($entity); } /** * Create a QueryBuilder instance * * @return QueryBuilder $qb */ public function createQueryBuilder() { return $this->delegate->createQueryBuilder(); } /** * Creates a new Query object. * * @param string $dql The DQL string. * @return \Doctrine\ORM\Query */ public function createQuery($dql = '') { return $this->delegate->createQuery($dql); } /** * Creates a native SQL query. * * @param string $sql * @param ResultSetMapping $rsm The ResultSetMapping to use. * @return NativeQuery */ public function createNativeQuery($sql, \Doctrine\ORM\Query\ResultSetMapping $rsm) { return $this->delegate->createNativeQuery($sql, $rsm); } /** * Creates a Query from a named query. * * @param string $name * @return \Doctrine\ORM\Query */ public function createNamedQuery($name) { return $this->delegate->createNamedQuery($name); } /** * Creates a NativeQuery from a named native query. * * @param string $name * @return \Doctrine\ORM\NativeQuery */ public function createNamedNativeQuery($name) { return $this->delegate->createNamedNativeQuery($name); } /** * Creates a copy of the given entity. Can create a shallow or a deep copy. * * @param object $entity The entity to copy. * @return object The new entity. * @todo Implementation need. This is necessary since $e2 = clone $e1; throws an E_FATAL when access anything on $e: * Fatal error: Maximum function nesting level of '100' reached, aborting! */ public function copy($entity, $deep = false) { return $this->delegate->copy($entity, $deep); } /** * Determines whether an entity instance is managed in this EntityManager. * * @param object $entity * @return boolean TRUE if this EntityManager currently manages the given entity, FALSE otherwise. */ public function contains($entity) { return $this->delegate->contains($entity); } /** * Commits a transaction on the underlying database connection. */ public function commit() { return $this->delegate->commit(); } /** * Closes the EntityManager. All entities that are currently managed * by this EntityManager become detached. The EntityManager may no longer * be used after it is closed. */ public function close() { return $this->delegate->close(); } /** * Clears the EntityManager. All entities that are currently managed * by this EntityManager become detached. * * @param string $entityName if given, only entities of this type will get detached */ public function clear($entityName = NULL) { return $this->delegate->clear($entityName); } /** * Starts a transaction on the underlying database connection. */ public function beginTransaction() { return $this->delegate->beginTransaction(); } public function __construct($objectManager, \Symfony\Component\DependencyInjection\ContainerInterface $container) { $this->delegate = $objectManager; $this->container = $container; } private function prepareArguments(array $arguments) { $processed = array(); foreach ($arguments as $arg) { if ($arg instanceof \Symfony\Component\DependencyInjection\Reference) { $processed[] = $this->container->get((string) $arg, $arg->getInvalidBehavior()); } else if ($arg instanceof \Symfony\Component\DependencyInjection\Parameter) { $processed[] = $this->container->getParameter((string) $arg); } else { $processed[] = $arg; } } return $processed; } }
{ "content_hash": "2305877fab4644ab58893c9085cd09c3", "timestamp": "", "source": "github", "line_count": 531, "max_line_length": 144, "avg_line_length": 30.173258003766477, "alnum_prop": 0.6280738983897142, "repo_name": "sanzodown/symfohetic", "id": "946417c5eb6368b62a946520e1b19492b13bf9b4", "size": "16022", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/cache/dev/jms_diextra/doctrine/EntityManager_527a624ed9863.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "2282" }, { "name": "CSS", "bytes": "459496" }, { "name": "CoffeeScript", "bytes": "5086" }, { "name": "HTML", "bytes": "1075885" }, { "name": "JavaScript", "bytes": "17894" }, { "name": "PHP", "bytes": "624551" }, { "name": "Ruby", "bytes": "19" } ], "symlink_target": "" }
package info.u250.c2d.engine; import info.u250.c2d.engine.resources.AliasResourceManager; /** * A game must has a {@link EngineDrive} to supply a game logic . You game should begin here. * * @author xjjdog */ public interface EngineDrive extends com.badlogic.gdx.utils.Disposable { /** * setup the engine's config , its the config panel here */ EngineOptions onSetupEngine(); /** * the game init should be here , you may init the game scene and sence group */ void onLoadedResourcesCompleted(); /** * the rescources's full path is a long key , we make its alias to identify it . such as use RES instead of "data/res/res/res/res/haha.png" */ void onResourcesRegister(AliasResourceManager<String> reg); /** * the game config * * @author xjjdog */ final class EngineOptions { public boolean catchBackKey = false; /** * load all the resources atomically * its a "String[]", so you can supply a dictionary or a full path of the resources * or exclude some resources paths * * @see {@link AliasResourceManager} */ public String[] assets = new String[]{"data/"}; /** * the scene width and scene height . we support two android devices very well :800x480,480x320 */ public float width = 480; /** * the scene height */ public float height = 320; /** * if the global debug flag , if it is true , we will always show the debuginfomation label on the bottom of the screen */ public boolean debug = true; /** * auto resume manager the Engine's running state . If you set it false , you must call * {@link Engine#doResume() } manually to resume the game or it will keep pause */ public boolean autoResume = false; /** * if set true , we will reset the engine's {@link #width} and {@link #height} */ public boolean resizeSync = false; /** * the game config xml file ,to store some attributes such as the sound state */ public String configFile = "c2d.temp.xml"; public boolean useGL20 = false; public EngineOptions(String[] assets, float width, float height) { this.assets = assets; this.width = width; this.height = height; } } }
{ "content_hash": "500a45184073785941c36dd9b45a90ad", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 143, "avg_line_length": 31.51851851851852, "alnum_prop": 0.5746180963572268, "repo_name": "lycying/c2d-engine", "id": "d9b4e88067171a5ae960d3edc167e29c45bc4849", "size": "2553", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "c2d-core/src/main/java/info/u250/c2d/engine/EngineDrive.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "178" }, { "name": "GLSL", "bytes": "640" }, { "name": "HTML", "bytes": "972" }, { "name": "Java", "bytes": "897788" }, { "name": "Puppet", "bytes": "27809" } ], "symlink_target": "" }
namespace Google.Cloud.Monitoring.V3.Snippets { // [START monitoring_v3_generated_AlertPolicyService_DeleteAlertPolicy_sync] using Google.Cloud.Monitoring.V3; public sealed partial class GeneratedAlertPolicyServiceClientSnippets { /// <summary>Snippet for DeleteAlertPolicy</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void DeleteAlertPolicyRequestObject() { // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest { AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"), }; // Make the request alertPolicyServiceClient.DeleteAlertPolicy(request); } } // [END monitoring_v3_generated_AlertPolicyService_DeleteAlertPolicy_sync] }
{ "content_hash": "ebe06104a446c05021354215ba87dbd8", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 104, "avg_line_length": 42.77777777777778, "alnum_prop": 0.6727272727272727, "repo_name": "jskeet/google-cloud-dotnet", "id": "6a08c11075673627520b5c41b6c5a32d55b69df7", "size": "1777", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "apis/Google.Cloud.Monitoring.V3/Google.Cloud.Monitoring.V3.GeneratedSnippets/AlertPolicyServiceClient.DeleteAlertPolicyRequestObjectSnippet.g.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "767" }, { "name": "C#", "bytes": "268415427" }, { "name": "CSS", "bytes": "1346" }, { "name": "Dockerfile", "bytes": "3173" }, { "name": "HTML", "bytes": "3823" }, { "name": "JavaScript", "bytes": "226" }, { "name": "PowerShell", "bytes": "3303" }, { "name": "Python", "bytes": "2744" }, { "name": "Shell", "bytes": "65260" }, { "name": "sed", "bytes": "1030" } ], "symlink_target": "" }
package diaryruapi import ( "crypto/md5" "encoding/hex" "github.com/yastrov/charmap" "net/http" "net/url" "strconv" ) func makeDiaryRuPassword(password string) string { hash := md5.Sum([]byte(key + password)) return hex.EncodeToString(hash[:]) } func makeDiaryRuLogin(username string) string { strcp1251, _ := charmap.Encode(username, "cp-1251") return strcp1251 } func diaryPostForm(values url.Values) (*http.Response, error) { dURL, _ := url.Parse(DiaryMainUrl) resp, err := http.PostForm(dURL.String(), values) return resp, err } func diaryGet(values url.Values) (*http.Response, error) { dURL, _ := url.Parse(DiaryMainUrl) dURL.RawQuery = values.Encode() resp, err := http.Get(dURL.String()) return resp, err } func (post *PostStruct) CountComments() uint64 { if post.Comments_count_data == "" { return 0 } i, err := strconv.ParseUint(post.Comments_count_data, 10, 64) if err != nil || i == 0 { return i } return i }
{ "content_hash": "1282449c9852ba07f5de7a957a015ce1", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 63, "avg_line_length": 21.681818181818183, "alnum_prop": 0.689727463312369, "repo_name": "yastrov/diaryrusearchserver", "id": "42352a71a152ef90025b6cff71ece4fdfbd5062e", "size": "954", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "diaryruapi/helper.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "18323" } ], "symlink_target": "" }
package org.deckfour.xes.model.impl; import java.util.Collections; import java.util.Set; import org.deckfour.xes.extension.XExtension; import org.deckfour.xes.model.XAttributable; import org.deckfour.xes.model.XAttribute; import org.deckfour.xes.model.XAttributeCollection; import org.deckfour.xes.model.XAttributeMap; import org.deckfour.xes.model.XVisitor; import org.deckfour.xes.util.XAttributeUtils; /** * This class implements the abstract base class for strongly-typed attributes. * * @author Christian W. Guenther ([email protected]) * */ public abstract class XAttributeImpl implements XAttribute { /** * Key, i.e. unique name, of this attribute. If the attribute is defined in * an extension, its key will be prepended with the extension's defined * prefix string. */ private final String key; /** * The extension defining this attribute. May be <code>null</code>, if this * attribute is not defined by an extension. */ private final XExtension extension; /** * Map of meta-attributes, i.e. attributes of this attribute. */ private XAttributeMap attributes; /** * Creates a new, empty attribute. * * @param key * The key, i.e. unique name identifier, of this attribute. */ protected XAttributeImpl(String key) { this(key, null); } /** * Creates a new attribute. * * @param key * The key, i.e. unique name identifier, of this attribute. * @param extension * The extension used for defining this attribute. */ protected XAttributeImpl(String key, XExtension extension) { this.key = key; this.extension = extension; } /* * (non-Javadoc) * * @see org.deckfour.xes.model.impl.XAttribute#getKey() */ public String getKey() { return key; } /* * (non-Javadoc) * * @see org.deckfour.xes.model.impl.XAttribute#getExtension() */ public XExtension getExtension() { return extension; } /* * (non-Javadoc) * * @see org.deckfour.xes.model.impl.XAttribute#getAttributes() */ public XAttributeMap getAttributes() { // This is not thread-safe, but we don't give any thread safety guarantee anyway if (attributes == null) { this.attributes = new XAttributeMapLazyImpl<XAttributeMapImpl>( XAttributeMapImpl.class); // uses lazy implementation by default } return attributes; } /* * (non-Javadoc) * * @see * org.deckfour.xes.model.impl.XAttribute#setAttributes(org.deckfour.xes * .model.XAttributeMap) */ public void setAttributes(XAttributeMap attributes) { this.attributes = attributes; } /* (non-Javadoc) * @see org.deckfour.xes.model.XAttributable#hasAttributes() */ @Override public boolean hasAttributes() { return attributes != null && !attributes.isEmpty(); } /* * (non-Javadoc) * * @see org.deckfour.xes.model.impl.XAttribute#getExtensions() */ public Set<XExtension> getExtensions() { if (attributes != null) { return XAttributeUtils.extractExtensions(getAttributes()); } else { return Collections.emptySet(); } } /* * (non-Javadoc) * * @see org.deckfour.xes.model.impl.XAttribute#clone() */ public Object clone() { XAttributeImpl clone = null; try { clone = (XAttributeImpl) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } if (attributes != null) { clone.attributes = (XAttributeMap) getAttributes().clone(); } return clone; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (obj instanceof XAttribute) { XAttribute other = (XAttribute) obj; return other.getKey().equals(key); } else { return false; } } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return key.hashCode(); } /* * (non-Javadoc) * * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(XAttribute o) { return key.compareTo(o.getKey()); } /* * Runs the given visitor for the given parent on this attribute. * * (non-Javadoc) * @see org.deckfour.xes.model.XAttribute#accept(org.deckfour.xes.model.XVisitor, org.deckfour.xes.model.XAttributable) */ public void accept(XVisitor visitor, XAttributable parent) { /* * First call. */ visitor.visitAttributePre(this, parent); if (this instanceof XAttributeCollection) { /* * Visit the (meta) attributes using the order a specified by the collection. */ for (XAttribute attribute: ((XAttributeCollection) this).getCollection()) { attribute.accept(visitor, this); } } else { /* * Visit the (meta) attributes. */ if (attributes != null) { for (XAttribute attribute: getAttributes().values()) { attribute.accept(visitor, this); } } } /* * Last call. */ visitor.visitAttributePost(this, parent); } }
{ "content_hash": "84d36ff223b41169f3c50f2db4f54ca7", "timestamp": "", "source": "github", "line_count": 213, "max_line_length": 120, "avg_line_length": 23.070422535211268, "alnum_prop": 0.6754171754171754, "repo_name": "nicksi/xestools", "id": "9ddd04d24acbeea3a6cef9e2ab6756a6102072d4", "size": "6325", "binary": false, "copies": "2", "ref": "refs/heads/xes-tools", "path": "src/main/java/org/deckfour/xes/model/impl/XAttributeImpl.java", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "2148" }, { "name": "HTML", "bytes": "90518" }, { "name": "Java", "bytes": "788467" }, { "name": "Shell", "bytes": "314" } ], "symlink_target": "" }
NS_ASSUME_NONNULL_BEGIN @interface DWPhraseRepairChildViewController () @property (null_resettable, nonatomic, strong) UILabel *titleLabel; @property (null_resettable, nonatomic, strong) DWProgressView *progressView; @end NS_ASSUME_NONNULL_END @implementation DWPhraseRepairChildViewController - (NSString *)title { return self.titleLabel.text; } - (void)setTitle:(NSString *)title { self.titleLabel.text = title; } - (void)setProgress:(float)progress { _progress = progress; [self.progressView setProgress:progress animated:YES]; } - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor clearColor]; [self.view addSubview:self.titleLabel]; [self.view addSubview:self.progressView]; [NSLayoutConstraint activateConstraints:@[ [self.titleLabel.topAnchor constraintEqualToAnchor:self.view.topAnchor], [self.titleLabel.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:16.0], [self.view.trailingAnchor constraintEqualToAnchor:self.titleLabel.trailingAnchor constant:16.0], [self.progressView.topAnchor constraintEqualToAnchor:self.titleLabel.bottomAnchor constant:32.0], [self.progressView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor], [self.view.trailingAnchor constraintEqualToAnchor:self.progressView.trailingAnchor], [self.view.bottomAnchor constraintEqualToAnchor:self.progressView.bottomAnchor], [self.progressView.heightAnchor constraintEqualToConstant:5.0], ]]; } - (UILabel *)titleLabel { if (_titleLabel == nil) { _titleLabel = [[UILabel alloc] init]; _titleLabel.translatesAutoresizingMaskIntoConstraints = NO; _titleLabel.font = [UIFont dw_fontForTextStyle:UIFontTextStyleHeadline]; _titleLabel.adjustsFontSizeToFitWidth = YES; _titleLabel.minimumScaleFactor = 0.5; _titleLabel.numberOfLines = 0; _titleLabel.textColor = [UIColor dw_darkTitleColor]; _titleLabel.textAlignment = NSTextAlignmentCenter; } return _titleLabel; } - (DWProgressView *)progressView { if (_progressView == nil) { _progressView = [[DWProgressView alloc] initWithFrame:CGRectZero]; _progressView.translatesAutoresizingMaskIntoConstraints = NO; _progressView.layer.cornerRadius = 2.0; _progressView.layer.masksToBounds = YES; } return _progressView; } @end
{ "content_hash": "3d62f5f6fc5d3bcd9dd77ee953d2c608", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 92, "avg_line_length": 34.18421052631579, "alnum_prop": 0.6878367975365666, "repo_name": "QuantumExplorer/breadwallet", "id": "670c60a22dacd78e932a77efb3fefac6a5532bf2", "size": "3333", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "DashWallet/Sources/UI/Setup/RecoverWallet/PhraseRepair/DWPhraseRepairChildViewController.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "495752" }, { "name": "C++", "bytes": "13127" }, { "name": "Java", "bytes": "2100" }, { "name": "Objective-C", "bytes": "1430773" }, { "name": "Shell", "bytes": "586" } ], "symlink_target": "" }
#region License // Copyright (c) 2007 James Newton-King // // 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. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; #if !(NET35 || NET20 || PORTABLE40) using System.ComponentModel; using System.Dynamic; #endif using System.Diagnostics; using System.Globalization; #if !(PORTABLE || PORTABLE40 || NET35 || NET20) using System.Numerics; #endif using System.Reflection; using System.Runtime.Serialization; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Utilities; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Serialization { internal class JsonSerializerInternalReader : JsonSerializerInternalBase { internal enum PropertyPresence { None = 0, Null = 1, Value = 2 } public JsonSerializerInternalReader(JsonSerializer serializer) : base(serializer) { } public void Populate(JsonReader reader, object target) { ValidationUtils.ArgumentNotNull(target, nameof(target)); Type objectType = target.GetType(); JsonContract contract = Serializer._contractResolver.ResolveContract(objectType); if (!reader.MoveToContent()) { throw JsonSerializationException.Create(reader, "No JSON content found."); } if (reader.TokenType == JsonToken.StartArray) { if (contract.ContractType == JsonContractType.Array) { JsonArrayContract arrayContract = (JsonArrayContract)contract; PopulateList((arrayContract.ShouldCreateWrapper) ? arrayContract.CreateWrapper(target) : (IList)target, reader, arrayContract, null, null); } else { throw JsonSerializationException.Create(reader, "Cannot populate JSON array onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); } } else if (reader.TokenType == JsonToken.StartObject) { reader.ReadAndAssert(); string id = null; if (Serializer.MetadataPropertyHandling != MetadataPropertyHandling.Ignore && reader.TokenType == JsonToken.PropertyName && string.Equals(reader.Value.ToString(), JsonTypeReflector.IdPropertyName, StringComparison.Ordinal)) { reader.ReadAndAssert(); id = (reader.Value != null) ? reader.Value.ToString() : null; reader.ReadAndAssert(); } if (contract.ContractType == JsonContractType.Dictionary) { JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)contract; PopulateDictionary((dictionaryContract.ShouldCreateWrapper) ? dictionaryContract.CreateWrapper(target) : (IDictionary)target, reader, dictionaryContract, null, id); } else if (contract.ContractType == JsonContractType.Object) { PopulateObject(target, reader, (JsonObjectContract)contract, null, id); } else { throw JsonSerializationException.Create(reader, "Cannot populate JSON object onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); } } else { throw JsonSerializationException.Create(reader, "Unexpected initial token '{0}' when populating object. Expected JSON object or array.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } } private JsonContract GetContractSafe(Type type) { if (type == null) { return null; } return Serializer._contractResolver.ResolveContract(type); } public object Deserialize(JsonReader reader, Type objectType, bool checkAdditionalContent) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } JsonContract contract = GetContractSafe(objectType); try { JsonConverter converter = GetConverter(contract, null, null, null); if (reader.TokenType == JsonToken.None && !ReadForType(reader, contract, converter != null)) { if (contract != null && !contract.IsNullable) { throw JsonSerializationException.Create(reader, "No JSON content found and type '{0}' is not nullable.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); } return null; } object deserializedValue; if (converter != null && converter.CanRead) { deserializedValue = DeserializeConvertable(converter, reader, objectType, null); } else { deserializedValue = CreateValueInternal(reader, objectType, contract, null, null, null, null); } if (checkAdditionalContent) { if (reader.Read() && reader.TokenType != JsonToken.Comment) { throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object."); } } return deserializedValue; } catch (Exception ex) { if (IsErrorHandled(null, contract, null, reader as IJsonLineInfo, reader.Path, ex)) { HandleError(reader, false, 0); return null; } else { // clear context in case serializer is being used inside a converter // if the converter wraps the error then not clearing the context will cause this error: // "Current error context error is different to requested error." ClearErrorContext(); throw; } } } private JsonSerializerProxy GetInternalSerializer() { if (InternalSerializer == null) { InternalSerializer = new JsonSerializerProxy(this); } return InternalSerializer; } private JToken CreateJToken(JsonReader reader, JsonContract contract) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); if (contract != null) { if (contract.UnderlyingType == typeof(JRaw)) { return JRaw.Create(reader); } if (reader.TokenType == JsonToken.Null && !(contract.UnderlyingType == typeof(JValue) || contract.UnderlyingType == typeof(JToken))) { return null; } } JToken token; using (JTokenWriter writer = new JTokenWriter()) { writer.WriteToken(reader); token = writer.Token; } return token; } private JToken CreateJObject(JsonReader reader) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); // this is needed because we've already read inside the object, looking for metadata properties using (JTokenWriter writer = new JTokenWriter()) { writer.WriteStartObject(); do { if (reader.TokenType == JsonToken.PropertyName) { string propertyName = (string)reader.Value; if (!reader.ReadAndMoveToContent()) { break; } if (CheckPropertyName(reader, propertyName)) { continue; } writer.WritePropertyName(propertyName); writer.WriteToken(reader, true, true, false); } else if (reader.TokenType == JsonToken.Comment) { // eat } else { writer.WriteEndObject(); return writer.Token; } } while (reader.Read()); throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object."); } } private object CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue) { if (contract != null && contract.ContractType == JsonContractType.Linq) { return CreateJToken(reader, contract); } do { switch (reader.TokenType) { // populate a typed object or generic dictionary/array // depending upon whether an objectType was supplied case JsonToken.StartObject: return CreateObject(reader, objectType, contract, member, containerContract, containerMember, existingValue); case JsonToken.StartArray: return CreateList(reader, objectType, contract, member, existingValue, null); case JsonToken.Integer: case JsonToken.Float: case JsonToken.Boolean: case JsonToken.Date: case JsonToken.Bytes: return EnsureType(reader, reader.Value, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.String: string s = (string)reader.Value; // convert empty string to null automatically for nullable types if (CoerceEmptyStringToNull(objectType, contract, s)) { return null; } // string that needs to be returned as a byte array should be base 64 decoded if (objectType == typeof(byte[])) { return Convert.FromBase64String(s); } return EnsureType(reader, s, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.StartConstructor: string constructorName = reader.Value.ToString(); return EnsureType(reader, constructorName, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.Null: case JsonToken.Undefined: #if !(DOTNET || PORTABLE40 || PORTABLE) if (objectType == typeof(DBNull)) { return DBNull.Value; } #endif return EnsureType(reader, reader.Value, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.Raw: return new JRaw((string)reader.Value); case JsonToken.Comment: // ignore break; default: throw JsonSerializationException.Create(reader, "Unexpected token while deserializing object: " + reader.TokenType); } } while (reader.Read()); throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object."); } private static bool CoerceEmptyStringToNull(Type objectType, JsonContract contract, string s) { return string.IsNullOrEmpty(s) && objectType != null && objectType != typeof(string) && objectType != typeof(object) && contract != null && contract.IsNullable; } internal string GetExpectedDescription(JsonContract contract) { switch (contract.ContractType) { case JsonContractType.Object: case JsonContractType.Dictionary: #if !(DOTNET || PORTABLE || PORTABLE40) case JsonContractType.Serializable: #endif #if !(NET35 || NET20 || PORTABLE40) case JsonContractType.Dynamic: #endif return @"JSON object (e.g. {""name"":""value""})"; case JsonContractType.Array: return @"JSON array (e.g. [1,2,3])"; case JsonContractType.Primitive: return @"JSON primitive value (e.g. string, number, boolean, null)"; case JsonContractType.String: return @"JSON string value"; default: throw new ArgumentOutOfRangeException(); } } private JsonConverter GetConverter(JsonContract contract, JsonConverter memberConverter, JsonContainerContract containerContract, JsonProperty containerProperty) { JsonConverter converter = null; if (memberConverter != null) { // member attribute converter converter = memberConverter; } else if (containerProperty != null && containerProperty.ItemConverter != null) { converter = containerProperty.ItemConverter; } else if (containerContract != null && containerContract.ItemConverter != null) { converter = containerContract.ItemConverter; } else if (contract != null) { JsonConverter matchingConverter; if (contract.Converter != null) { // class attribute converter converter = contract.Converter; } else if ((matchingConverter = Serializer.GetMatchingConverter(contract.UnderlyingType)) != null) { // passed in converters converter = matchingConverter; } else if (contract.InternalConverter != null) { // internally specified converter converter = contract.InternalConverter; } } return converter; } private object CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue) { string id; Type resolvedObjectType = objectType; if (Serializer.MetadataPropertyHandling == MetadataPropertyHandling.Ignore) { // don't look for metadata properties reader.ReadAndAssert(); id = null; } else if (Serializer.MetadataPropertyHandling == MetadataPropertyHandling.ReadAhead) { JTokenReader tokenReader = reader as JTokenReader; if (tokenReader == null) { JToken t = JToken.ReadFrom(reader); tokenReader = (JTokenReader)t.CreateReader(); tokenReader.Culture = reader.Culture; tokenReader.DateFormatString = reader.DateFormatString; tokenReader.DateParseHandling = reader.DateParseHandling; tokenReader.DateTimeZoneHandling = reader.DateTimeZoneHandling; tokenReader.FloatParseHandling = reader.FloatParseHandling; tokenReader.SupportMultipleContent = reader.SupportMultipleContent; // start tokenReader.ReadAndAssert(); reader = tokenReader; } object newValue; if (ReadMetadataPropertiesToken(tokenReader, ref resolvedObjectType, ref contract, member, containerContract, containerMember, existingValue, out newValue, out id)) { return newValue; } } else { reader.ReadAndAssert(); object newValue; if (ReadMetadataProperties(reader, ref resolvedObjectType, ref contract, member, containerContract, containerMember, existingValue, out newValue, out id)) { return newValue; } } if (HasNoDefinedType(contract)) { return CreateJObject(reader); } switch (contract.ContractType) { case JsonContractType.Object: { bool createdFromNonDefaultCreator = false; JsonObjectContract objectContract = (JsonObjectContract)contract; object targetObject; // check that if type name handling is being used that the existing value is compatible with the specified type if (existingValue != null && (resolvedObjectType == objectType || resolvedObjectType.IsAssignableFrom(existingValue.GetType()))) { targetObject = existingValue; } else { targetObject = CreateNewObject(reader, objectContract, member, containerMember, id, out createdFromNonDefaultCreator); } // don't populate if read from non-default creator because the object has already been read if (createdFromNonDefaultCreator) { return targetObject; } return PopulateObject(targetObject, reader, objectContract, member, id); } case JsonContractType.Primitive: { JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract; // if the content is inside $value then read past it if (Serializer.MetadataPropertyHandling != MetadataPropertyHandling.Ignore && reader.TokenType == JsonToken.PropertyName && string.Equals(reader.Value.ToString(), JsonTypeReflector.ValuePropertyName, StringComparison.Ordinal)) { reader.ReadAndAssert(); // the token should not be an object because the $type value could have been included in the object // without needing the $value property if (reader.TokenType == JsonToken.StartObject) { throw JsonSerializationException.Create(reader, "Unexpected token when deserializing primitive value: " + reader.TokenType); } object value = CreateValueInternal(reader, resolvedObjectType, primitiveContract, member, null, null, existingValue); reader.ReadAndAssert(); return value; } break; } case JsonContractType.Dictionary: { JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)contract; object targetDictionary; if (existingValue == null) { bool createdFromNonDefaultCreator; IDictionary dictionary = CreateNewDictionary(reader, dictionaryContract, out createdFromNonDefaultCreator); if (createdFromNonDefaultCreator) { if (id != null) { throw JsonSerializationException.Create(reader, "Cannot preserve reference to readonly dictionary, or dictionary created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); } if (contract.OnSerializingCallbacks.Count > 0) { throw JsonSerializationException.Create(reader, "Cannot call OnSerializing on readonly dictionary, or dictionary created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); } if (contract.OnErrorCallbacks.Count > 0) { throw JsonSerializationException.Create(reader, "Cannot call OnError on readonly list, or dictionary created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); } if (!dictionaryContract.HasParameterizedCreatorInternal) { throw JsonSerializationException.Create(reader, "Cannot deserialize readonly or fixed size dictionary: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); } } PopulateDictionary(dictionary, reader, dictionaryContract, member, id); if (createdFromNonDefaultCreator) { ObjectConstructor<object> creator = dictionaryContract.OverrideCreator ?? dictionaryContract.ParameterizedCreator; return creator(dictionary); } else if (dictionary is IWrappedDictionary) { return ((IWrappedDictionary)dictionary).UnderlyingDictionary; } targetDictionary = dictionary; } else { targetDictionary = PopulateDictionary(dictionaryContract.ShouldCreateWrapper ? dictionaryContract.CreateWrapper(existingValue) : (IDictionary)existingValue, reader, dictionaryContract, member, id); } return targetDictionary; } #if !(NET35 || NET20 || PORTABLE40) case JsonContractType.Dynamic: JsonDynamicContract dynamicContract = (JsonDynamicContract)contract; return CreateDynamic(reader, dynamicContract, member, id); #endif #if !(DOTNET || PORTABLE40 || PORTABLE) case JsonContractType.Serializable: JsonISerializableContract serializableContract = (JsonISerializableContract)contract; return CreateISerializable(reader, serializableContract, member, id); #endif } string message = @"Cannot deserialize the current JSON object (e.g. {{""name"":""value""}}) into type '{0}' because the type requires a {1} to deserialize correctly." + Environment.NewLine + @"To fix this error either change the JSON to a {1} or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object." + Environment.NewLine; message = message.FormatWith(CultureInfo.InvariantCulture, resolvedObjectType, GetExpectedDescription(contract)); throw JsonSerializationException.Create(reader, message); } private bool ReadMetadataPropertiesToken(JTokenReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue, out object newValue, out string id) { id = null; newValue = null; if (reader.TokenType == JsonToken.StartObject) { JObject current = (JObject)reader.CurrentToken; JToken refToken = current[JsonTypeReflector.RefPropertyName]; if (refToken != null) { if (refToken.Type != JTokenType.String && refToken.Type != JTokenType.Null) { throw JsonSerializationException.Create(refToken, refToken.Path, "JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName), null); } JToken property = refToken.Parent; JToken additionalContent = null; if (property.Next != null) { additionalContent = property.Next; } else if (property.Previous != null) { additionalContent = property.Previous; } string reference = (string)refToken; if (reference != null) { if (additionalContent != null) { throw JsonSerializationException.Create(additionalContent, additionalContent.Path, "Additional content found in JSON reference object. A JSON reference object should only have a {0} property.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName), null); } newValue = Serializer.GetReferenceResolver().ResolveReference(this, reference); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Resolved object reference '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, reference, newValue.GetType())), null); } reader.Skip(); return true; } } JToken typeToken = current[JsonTypeReflector.TypePropertyName]; if (typeToken != null) { string qualifiedTypeName = (string)typeToken; JsonReader typeTokenReader = typeToken.CreateReader(); typeTokenReader.ReadAndAssert(); ResolveTypeName(typeTokenReader, ref objectType, ref contract, member, containerContract, containerMember, qualifiedTypeName); JToken valueToken = current[JsonTypeReflector.ValuePropertyName]; if (valueToken != null) { while (true) { reader.ReadAndAssert(); if (reader.TokenType == JsonToken.PropertyName) { if ((string)reader.Value == JsonTypeReflector.ValuePropertyName) { return false; } } reader.ReadAndAssert(); reader.Skip(); } } } JToken idToken = current[JsonTypeReflector.IdPropertyName]; if (idToken != null) { id = (string)idToken; } JToken valuesToken = current[JsonTypeReflector.ArrayValuesPropertyName]; if (valuesToken != null) { JsonReader listReader = valuesToken.CreateReader(); listReader.ReadAndAssert(); newValue = CreateList(listReader, objectType, contract, member, existingValue, id); reader.Skip(); return true; } } reader.ReadAndAssert(); return false; } private bool ReadMetadataProperties(JsonReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue, out object newValue, out string id) { id = null; newValue = null; if (reader.TokenType == JsonToken.PropertyName) { string propertyName = reader.Value.ToString(); if (propertyName.Length > 0 && propertyName[0] == '$') { // read metadata properties // $type, $id, $ref, etc bool metadataProperty; do { propertyName = reader.Value.ToString(); if (string.Equals(propertyName, JsonTypeReflector.RefPropertyName, StringComparison.Ordinal)) { reader.ReadAndAssert(); if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null) { throw JsonSerializationException.Create(reader, "JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName)); } string reference = (reader.Value != null) ? reader.Value.ToString() : null; reader.ReadAndAssert(); if (reference != null) { if (reader.TokenType == JsonToken.PropertyName) { throw JsonSerializationException.Create(reader, "Additional content found in JSON reference object. A JSON reference object should only have a {0} property.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName)); } newValue = Serializer.GetReferenceResolver().ResolveReference(this, reference); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Resolved object reference '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, reference, newValue.GetType())), null); } return true; } else { metadataProperty = true; } } else if (string.Equals(propertyName, JsonTypeReflector.TypePropertyName, StringComparison.Ordinal)) { reader.ReadAndAssert(); string qualifiedTypeName = reader.Value.ToString(); ResolveTypeName(reader, ref objectType, ref contract, member, containerContract, containerMember, qualifiedTypeName); reader.ReadAndAssert(); metadataProperty = true; } else if (string.Equals(propertyName, JsonTypeReflector.IdPropertyName, StringComparison.Ordinal)) { reader.ReadAndAssert(); id = (reader.Value != null) ? reader.Value.ToString() : null; reader.ReadAndAssert(); metadataProperty = true; } else if (string.Equals(propertyName, JsonTypeReflector.ArrayValuesPropertyName, StringComparison.Ordinal)) { reader.ReadAndAssert(); object list = CreateList(reader, objectType, contract, member, existingValue, id); reader.ReadAndAssert(); newValue = list; return true; } else { metadataProperty = false; } } while (metadataProperty && reader.TokenType == JsonToken.PropertyName); } } return false; } private void ResolveTypeName(JsonReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, string qualifiedTypeName) { TypeNameHandling resolvedTypeNameHandling = ((member != null) ? member.TypeNameHandling : null) ?? ((containerContract != null) ? containerContract.ItemTypeNameHandling : null) ?? ((containerMember != null) ? containerMember.ItemTypeNameHandling : null) ?? Serializer._typeNameHandling; if (resolvedTypeNameHandling != TypeNameHandling.None) { string typeName; string assemblyName; ReflectionUtils.SplitFullyQualifiedTypeName(qualifiedTypeName, out typeName, out assemblyName); Type specifiedType; try { specifiedType = Serializer._binder.BindToType(assemblyName, typeName); } catch (Exception ex) { throw JsonSerializationException.Create(reader, "Error resolving type specified in JSON '{0}'.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName), ex); } if (specifiedType == null) { throw JsonSerializationException.Create(reader, "Type specified in JSON '{0}' was not resolved.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName)); } if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) { TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Resolved type '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName, specifiedType)), null); } if (objectType != null #if !(NET35 || NET20 || PORTABLE40) && objectType != typeof(IDynamicMetaObjectProvider) #endif && !objectType.IsAssignableFrom(specifiedType)) { throw JsonSerializationException.Create(reader, "Type specified in JSON '{0}' is not compatible with '{1}'.".FormatWith(CultureInfo.InvariantCulture, specifiedType.AssemblyQualifiedName, objectType.AssemblyQualifiedName)); } objectType = specifiedType; contract = GetContractSafe(specifiedType); } } private JsonArrayContract EnsureArrayContract(JsonReader reader, Type objectType, JsonContract contract) { if (contract == null) { throw JsonSerializationException.Create(reader, "Could not resolve type '{0}' to a JsonContract.".FormatWith(CultureInfo.InvariantCulture, objectType)); } JsonArrayContract arrayContract = contract as JsonArrayContract; if (arrayContract == null) { string message = @"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type '{0}' because the type requires a {1} to deserialize correctly." + Environment.NewLine + @"To fix this error either change the JSON to a {1} or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array." + Environment.NewLine; message = message.FormatWith(CultureInfo.InvariantCulture, objectType, GetExpectedDescription(contract)); throw JsonSerializationException.Create(reader, message); } return arrayContract; } private object CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, object existingValue, string id) { object value; if (HasNoDefinedType(contract)) { return CreateJToken(reader, contract); } JsonArrayContract arrayContract = EnsureArrayContract(reader, objectType, contract); if (existingValue == null) { bool createdFromNonDefaultCreator; IList list = CreateNewList(reader, arrayContract, out createdFromNonDefaultCreator); if (createdFromNonDefaultCreator) { if (id != null) { throw JsonSerializationException.Create(reader, "Cannot preserve reference to array or readonly list, or list created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); } if (contract.OnSerializingCallbacks.Count > 0) { throw JsonSerializationException.Create(reader, "Cannot call OnSerializing on an array or readonly list, or list created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); } if (contract.OnErrorCallbacks.Count > 0) { throw JsonSerializationException.Create(reader, "Cannot call OnError on an array or readonly list, or list created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); } if (!arrayContract.HasParameterizedCreatorInternal && !arrayContract.IsArray) { throw JsonSerializationException.Create(reader, "Cannot deserialize readonly or fixed size list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); } } if (!arrayContract.IsMultidimensionalArray) { PopulateList(list, reader, arrayContract, member, id); } else { PopulateMultidimensionalArray(list, reader, arrayContract, member, id); } if (createdFromNonDefaultCreator) { if (arrayContract.IsMultidimensionalArray) { list = CollectionUtils.ToMultidimensionalArray(list, arrayContract.CollectionItemType, contract.CreatedType.GetArrayRank()); } else if (arrayContract.IsArray) { Array a = Array.CreateInstance(arrayContract.CollectionItemType, list.Count); list.CopyTo(a, 0); list = a; } else { ObjectConstructor<object> creator = arrayContract.OverrideCreator ?? arrayContract.ParameterizedCreator; return creator(list); } } else if (list is IWrappedCollection) { return ((IWrappedCollection)list).UnderlyingCollection; } value = list; } else { if (!arrayContract.CanDeserialize) { throw JsonSerializationException.Create(reader, "Cannot populate list type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.CreatedType)); } value = PopulateList((arrayContract.ShouldCreateWrapper) ? arrayContract.CreateWrapper(existingValue) : (IList)existingValue, reader, arrayContract, member, id); } return value; } private bool HasNoDefinedType(JsonContract contract) { return (contract == null || contract.UnderlyingType == typeof(object) || contract.ContractType == JsonContractType.Linq #if !(NET35 || NET20 || PORTABLE40) || contract.UnderlyingType == typeof(IDynamicMetaObjectProvider) #endif ); } private object EnsureType(JsonReader reader, object value, CultureInfo culture, JsonContract contract, Type targetType) { if (targetType == null) { return value; } Type valueType = ReflectionUtils.GetObjectType(value); // type of value and type of target don't match // attempt to convert value's type to target's type if (valueType != targetType) { if (value == null && contract.IsNullable) { return null; } try { if (contract.IsConvertable) { JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract; if (contract.IsEnum) { if (value is string) { return Enum.Parse(contract.NonNullableUnderlyingType, value.ToString(), true); } if (ConvertUtils.IsInteger(primitiveContract.TypeCode)) { return Enum.ToObject(contract.NonNullableUnderlyingType, value); } } #if !(PORTABLE || PORTABLE40 || NET35 || NET20) if (value is BigInteger) { return ConvertUtils.FromBigInteger((BigInteger)value, contract.NonNullableUnderlyingType); } #endif // this won't work when converting to a custom IConvertible return Convert.ChangeType(value, contract.NonNullableUnderlyingType, culture); } return ConvertUtils.ConvertOrCast(value, culture, contract.NonNullableUnderlyingType); } catch (Exception ex) { throw JsonSerializationException.Create(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.FormatValueForPrint(value), targetType), ex); } } return value; } private bool SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, object target) { object currentValue; bool useExistingValue; JsonContract propertyContract; bool gottenCurrentValue; if (CalculatePropertyDetails(property, ref propertyConverter, containerContract, containerProperty, reader, target, out useExistingValue, out currentValue, out propertyContract, out gottenCurrentValue)) { return false; } object value; if (propertyConverter != null && propertyConverter.CanRead) { if (!gottenCurrentValue && target != null && property.Readable) { currentValue = property.ValueProvider.GetValue(target); } value = DeserializeConvertable(propertyConverter, reader, property.PropertyType, currentValue); } else { value = CreateValueInternal(reader, property.PropertyType, propertyContract, property, containerContract, containerProperty, (useExistingValue) ? currentValue : null); } // always set the value if useExistingValue is false, // otherwise also set it if CreateValue returns a new value compared to the currentValue // this could happen because of a JsonConverter against the type if ((!useExistingValue || value != currentValue) && ShouldSetPropertyValue(property, value)) { property.ValueProvider.SetValue(target, value); if (property.SetIsSpecified != null) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) { TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "IsSpecified for property '{0}' on {1} set to true.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType)), null); } property.SetIsSpecified(target, true); } return true; } // the value wasn't set be JSON was populated onto the existing value return useExistingValue; } private bool CalculatePropertyDetails(JsonProperty property, ref JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, object target, out bool useExistingValue, out object currentValue, out JsonContract propertyContract, out bool gottenCurrentValue) { currentValue = null; useExistingValue = false; propertyContract = null; gottenCurrentValue = false; if (property.Ignored) { return true; } JsonToken tokenType = reader.TokenType; if (property.PropertyContract == null) { property.PropertyContract = GetContractSafe(property.PropertyType); } ObjectCreationHandling objectCreationHandling = property.ObjectCreationHandling.GetValueOrDefault(Serializer._objectCreationHandling); if ((objectCreationHandling != ObjectCreationHandling.Replace) && (tokenType == JsonToken.StartArray || tokenType == JsonToken.StartObject) && property.Readable) { currentValue = property.ValueProvider.GetValue(target); gottenCurrentValue = true; if (currentValue != null) { propertyContract = GetContractSafe(currentValue.GetType()); useExistingValue = (!propertyContract.IsReadOnlyOrFixedSize && !propertyContract.UnderlyingType.IsValueType()); } } if (!property.Writable && !useExistingValue) { return true; } // test tokentype here because null might not be convertable to some types, e.g. ignoring null when applied to DateTime if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore && tokenType == JsonToken.Null) { return true; } // test tokentype here because default value might not be convertable to actual type, e.g. default of "" for DateTime if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore) && !HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate) && JsonTokenUtils.IsPrimitiveToken(tokenType) && MiscellaneousUtils.ValueEquals(reader.Value, property.GetResolvedDefaultValue())) { return true; } if (currentValue == null) { propertyContract = property.PropertyContract; } else { propertyContract = GetContractSafe(currentValue.GetType()); if (propertyContract != property.PropertyContract) { propertyConverter = GetConverter(propertyContract, property.MemberConverter, containerContract, containerProperty); } } return false; } private void AddReference(JsonReader reader, string id, object value) { try { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) { TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Read object reference Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, id, value.GetType())), null); } Serializer.GetReferenceResolver().AddReference(this, id, value); } catch (Exception ex) { throw JsonSerializationException.Create(reader, "Error reading object reference '{0}'.".FormatWith(CultureInfo.InvariantCulture, id), ex); } } private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag) { return ((value & flag) == flag); } private bool ShouldSetPropertyValue(JsonProperty property, object value) { if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore && value == null) { return false; } if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore) && !HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate) && MiscellaneousUtils.ValueEquals(value, property.GetResolvedDefaultValue())) { return false; } if (!property.Writable) { return false; } return true; } private IList CreateNewList(JsonReader reader, JsonArrayContract contract, out bool createdFromNonDefaultCreator) { // some types like non-generic IEnumerable can be serialized but not deserialized if (!contract.CanDeserialize) { throw JsonSerializationException.Create(reader, "Cannot create and populate list type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.CreatedType)); } if (contract.OverrideCreator != null) { if (contract.HasParameterizedCreator) { createdFromNonDefaultCreator = true; return contract.CreateTemporaryCollection(); } else { createdFromNonDefaultCreator = false; return (IList)contract.OverrideCreator(); } } else if (contract.IsReadOnlyOrFixedSize) { createdFromNonDefaultCreator = true; IList list = contract.CreateTemporaryCollection(); if (contract.ShouldCreateWrapper) { list = contract.CreateWrapper(list); } return list; } else if (contract.DefaultCreator != null && (!contract.DefaultCreatorNonPublic || Serializer._constructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor)) { object list = contract.DefaultCreator(); if (contract.ShouldCreateWrapper) { list = contract.CreateWrapper(list); } createdFromNonDefaultCreator = false; return (IList)list; } else if (contract.HasParameterizedCreatorInternal) { createdFromNonDefaultCreator = true; return contract.CreateTemporaryCollection(); } else { if (!contract.IsInstantiable) { throw JsonSerializationException.Create(reader, "Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); } throw JsonSerializationException.Create(reader, "Unable to find a constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); } } private IDictionary CreateNewDictionary(JsonReader reader, JsonDictionaryContract contract, out bool createdFromNonDefaultCreator) { if (contract.OverrideCreator != null) { if (contract.HasParameterizedCreator) { createdFromNonDefaultCreator = true; return contract.CreateTemporaryDictionary(); } else { createdFromNonDefaultCreator = false; return (IDictionary)contract.OverrideCreator(); } } else if (contract.IsReadOnlyOrFixedSize) { createdFromNonDefaultCreator = true; return contract.CreateTemporaryDictionary(); } else if (contract.DefaultCreator != null && (!contract.DefaultCreatorNonPublic || Serializer._constructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor)) { object dictionary = contract.DefaultCreator(); if (contract.ShouldCreateWrapper) { dictionary = contract.CreateWrapper(dictionary); } createdFromNonDefaultCreator = false; return (IDictionary)dictionary; } else if (contract.HasParameterizedCreatorInternal) { createdFromNonDefaultCreator = true; return contract.CreateTemporaryDictionary(); } else { if (!contract.IsInstantiable) { throw JsonSerializationException.Create(reader, "Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); } throw JsonSerializationException.Create(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); } } private void OnDeserializing(JsonReader reader, JsonContract contract, object value) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Started deserializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null); } contract.InvokeOnDeserializing(value, Serializer._context); } private void OnDeserialized(JsonReader reader, JsonContract contract, object value) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Finished deserializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null); } contract.InvokeOnDeserialized(value, Serializer._context); } private object PopulateDictionary(IDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty containerProperty, string id) { IWrappedDictionary wrappedDictionary = dictionary as IWrappedDictionary; object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : dictionary; if (id != null) { AddReference(reader, id, underlyingDictionary); } OnDeserializing(reader, contract, underlyingDictionary); int initialDepth = reader.Depth; if (contract.KeyContract == null) { contract.KeyContract = GetContractSafe(contract.DictionaryKeyType); } if (contract.ItemContract == null) { contract.ItemContract = GetContractSafe(contract.DictionaryValueType); } JsonConverter dictionaryValueConverter = contract.ItemConverter ?? GetConverter(contract.ItemContract, null, contract, containerProperty); PrimitiveTypeCode keyTypeCode = (contract.KeyContract is JsonPrimitiveContract) ? ((JsonPrimitiveContract)contract.KeyContract).TypeCode : PrimitiveTypeCode.Empty; bool finished = false; do { switch (reader.TokenType) { case JsonToken.PropertyName: object keyValue = reader.Value; if (CheckPropertyName(reader, keyValue.ToString())) { continue; } try { try { // this is for correctly reading ISO and MS formatted dictionary keys switch (keyTypeCode) { case PrimitiveTypeCode.DateTime: case PrimitiveTypeCode.DateTimeNullable: { DateTime dt; if (DateTimeUtils.TryParseDateTime(keyValue.ToString(), reader.DateTimeZoneHandling, reader.DateFormatString, reader.Culture, out dt)) { keyValue = dt; } else { keyValue = EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType); } break; } #if !NET20 case PrimitiveTypeCode.DateTimeOffset: case PrimitiveTypeCode.DateTimeOffsetNullable: { DateTimeOffset dt; if (DateTimeUtils.TryParseDateTimeOffset(keyValue.ToString(), reader.DateFormatString, reader.Culture, out dt)) { keyValue = dt; } else { keyValue = EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType); } break; } #endif default: keyValue = EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType); break; } } catch (Exception ex) { throw JsonSerializationException.Create(reader, "Could not convert string '{0}' to dictionary key type '{1}'. Create a TypeConverter to convert from the string to the key type object.".FormatWith(CultureInfo.InvariantCulture, reader.Value, contract.DictionaryKeyType), ex); } if (!ReadForType(reader, contract.ItemContract, dictionaryValueConverter != null)) { throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object."); } object itemValue; if (dictionaryValueConverter != null && dictionaryValueConverter.CanRead) { itemValue = DeserializeConvertable(dictionaryValueConverter, reader, contract.DictionaryValueType, null); } else { itemValue = CreateValueInternal(reader, contract.DictionaryValueType, contract.ItemContract, null, contract, containerProperty, null); } dictionary[keyValue] = itemValue; } catch (Exception ex) { if (IsErrorHandled(underlyingDictionary, contract, keyValue, reader as IJsonLineInfo, reader.Path, ex)) { HandleError(reader, true, initialDepth); } else { throw; } } break; case JsonToken.Comment: break; case JsonToken.EndObject: finished = true; break; default: throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType); } } while (!finished && reader.Read()); if (!finished) { ThrowUnexpectedEndException(reader, contract, underlyingDictionary, "Unexpected end when deserializing object."); } OnDeserialized(reader, contract, underlyingDictionary); return underlyingDictionary; } private object PopulateMultidimensionalArray(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, string id) { int rank = contract.UnderlyingType.GetArrayRank(); if (id != null) { AddReference(reader, id, list); } OnDeserializing(reader, contract, list); JsonContract collectionItemContract = GetContractSafe(contract.CollectionItemType); JsonConverter collectionItemConverter = GetConverter(collectionItemContract, null, contract, containerProperty); int? previousErrorIndex = null; Stack<IList> listStack = new Stack<IList>(); listStack.Push(list); IList currentList = list; bool finished = false; do { int initialDepth = reader.Depth; if (listStack.Count == rank) { try { if (ReadForType(reader, collectionItemContract, collectionItemConverter != null)) { switch (reader.TokenType) { case JsonToken.EndArray: listStack.Pop(); currentList = listStack.Peek(); previousErrorIndex = null; break; default: object value; if (collectionItemConverter != null && collectionItemConverter.CanRead) { value = DeserializeConvertable(collectionItemConverter, reader, contract.CollectionItemType, null); } else { value = CreateValueInternal(reader, contract.CollectionItemType, collectionItemContract, null, contract, containerProperty, null); } currentList.Add(value); break; } } else { break; } } catch (Exception ex) { JsonPosition errorPosition = reader.GetPosition(initialDepth); if (IsErrorHandled(list, contract, errorPosition.Position, reader as IJsonLineInfo, reader.Path, ex)) { HandleError(reader, true, initialDepth); if (previousErrorIndex != null && previousErrorIndex == errorPosition.Position) { // reader index has not moved since previous error handling // break out of reading array to prevent infinite loop throw JsonSerializationException.Create(reader, "Infinite loop detected from error handling.", ex); } else { previousErrorIndex = errorPosition.Position; } } else { throw; } } } else { if (reader.Read()) { switch (reader.TokenType) { case JsonToken.StartArray: IList newList = new List<object>(); currentList.Add(newList); listStack.Push(newList); currentList = newList; break; case JsonToken.EndArray: listStack.Pop(); if (listStack.Count > 0) { currentList = listStack.Peek(); } else { finished = true; } break; case JsonToken.Comment: break; default: throw JsonSerializationException.Create(reader, "Unexpected token when deserializing multidimensional array: " + reader.TokenType); } } else { break; } } } while (!finished); if (!finished) { ThrowUnexpectedEndException(reader, contract, list, "Unexpected end when deserializing array."); } OnDeserialized(reader, contract, list); return list; } private void ThrowUnexpectedEndException(JsonReader reader, JsonContract contract, object currentObject, string message) { try { throw JsonSerializationException.Create(reader, message); } catch (Exception ex) { if (IsErrorHandled(currentObject, contract, null, reader as IJsonLineInfo, reader.Path, ex)) { HandleError(reader, false, 0); } else { throw; } } } private object PopulateList(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, string id) { IWrappedCollection wrappedCollection = list as IWrappedCollection; object underlyingList = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : list; if (id != null) { AddReference(reader, id, underlyingList); } // can't populate an existing array if (list.IsFixedSize) { reader.Skip(); return underlyingList; } OnDeserializing(reader, contract, underlyingList); int initialDepth = reader.Depth; if (contract.ItemContract == null) { contract.ItemContract = GetContractSafe(contract.CollectionItemType); } JsonConverter collectionItemConverter = GetConverter(contract.ItemContract, null, contract, containerProperty); int? previousErrorIndex = null; bool finished = false; do { try { if (ReadForType(reader, contract.ItemContract, collectionItemConverter != null)) { switch (reader.TokenType) { case JsonToken.EndArray: finished = true; break; default: object value; if (collectionItemConverter != null && collectionItemConverter.CanRead) { value = DeserializeConvertable(collectionItemConverter, reader, contract.CollectionItemType, null); } else { value = CreateValueInternal(reader, contract.CollectionItemType, contract.ItemContract, null, contract, containerProperty, null); } list.Add(value); break; } } else { break; } } catch (Exception ex) { JsonPosition errorPosition = reader.GetPosition(initialDepth); if (IsErrorHandled(underlyingList, contract, errorPosition.Position, reader as IJsonLineInfo, reader.Path, ex)) { HandleError(reader, true, initialDepth); if (previousErrorIndex != null && previousErrorIndex == errorPosition.Position) { // reader index has not moved since previous error handling // break out of reading array to prevent infinite loop throw JsonSerializationException.Create(reader, "Infinite loop detected from error handling.", ex); } else { previousErrorIndex = errorPosition.Position; } } else { throw; } } } while (!finished); if (!finished) { ThrowUnexpectedEndException(reader, contract, underlyingList, "Unexpected end when deserializing array."); } OnDeserialized(reader, contract, underlyingList); return underlyingList; } #if !(DOTNET || PORTABLE40 || PORTABLE) private object CreateISerializable(JsonReader reader, JsonISerializableContract contract, JsonProperty member, string id) { Type objectType = contract.UnderlyingType; if (!JsonTypeReflector.FullyTrusted) { string message = @"Type '{0}' implements ISerializable but cannot be deserialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine + @"To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine; message = message.FormatWith(CultureInfo.InvariantCulture, objectType); throw JsonSerializationException.Create(reader, message); } if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Deserializing {0} using ISerializable constructor.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null); } SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new JsonFormatterConverter(this, contract, member)); bool finished = false; do { switch (reader.TokenType) { case JsonToken.PropertyName: string memberName = reader.Value.ToString(); if (!reader.Read()) { throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); } serializationInfo.AddValue(memberName, JToken.ReadFrom(reader)); break; case JsonToken.Comment: break; case JsonToken.EndObject: finished = true; break; default: throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType); } } while (!finished && reader.Read()); if (!finished) { ThrowUnexpectedEndException(reader, contract, serializationInfo, "Unexpected end when deserializing object."); } if (contract.ISerializableCreator == null) { throw JsonSerializationException.Create(reader, "ISerializable type '{0}' does not have a valid constructor. To correctly implement ISerializable a constructor that takes SerializationInfo and StreamingContext parameters should be present.".FormatWith(CultureInfo.InvariantCulture, objectType)); } object createdObject = contract.ISerializableCreator(serializationInfo, Serializer._context); if (id != null) { AddReference(reader, id, createdObject); } // these are together because OnDeserializing takes an object but for an ISerializable the object is fully created in the constructor OnDeserializing(reader, contract, createdObject); OnDeserialized(reader, contract, createdObject); return createdObject; } internal object CreateISerializableItem(JToken token, Type type, JsonISerializableContract contract, JsonProperty member) { JsonContract itemContract = GetContractSafe(type); JsonConverter itemConverter = GetConverter(itemContract, null, contract, member); JsonReader tokenReader = token.CreateReader(); tokenReader.ReadAndAssert(); // Move to first token object result; if (itemConverter != null && itemConverter.CanRead) { result = DeserializeConvertable(itemConverter, tokenReader, type, null); } else { result = CreateValueInternal(tokenReader, type, itemContract, null, contract, member, null); } return result; } #endif #if !(NET35 || NET20 || PORTABLE40) private object CreateDynamic(JsonReader reader, JsonDynamicContract contract, JsonProperty member, string id) { IDynamicMetaObjectProvider newObject; if (!contract.IsInstantiable) { throw JsonSerializationException.Create(reader, "Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); } if (contract.DefaultCreator != null && (!contract.DefaultCreatorNonPublic || Serializer._constructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor)) { newObject = (IDynamicMetaObjectProvider)contract.DefaultCreator(); } else { throw JsonSerializationException.Create(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); } if (id != null) { AddReference(reader, id, newObject); } OnDeserializing(reader, contract, newObject); int initialDepth = reader.Depth; bool finished = false; do { switch (reader.TokenType) { case JsonToken.PropertyName: string memberName = reader.Value.ToString(); try { if (!reader.Read()) { throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); } // first attempt to find a settable property, otherwise fall back to a dynamic set without type JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName); if (property != null && property.Writable && !property.Ignored) { if (property.PropertyContract == null) { property.PropertyContract = GetContractSafe(property.PropertyType); } JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.MemberConverter, null, null); if (!SetPropertyValue(property, propertyConverter, null, member, reader, newObject)) { reader.Skip(); } } else { Type t = (JsonTokenUtils.IsPrimitiveToken(reader.TokenType)) ? reader.ValueType : typeof(IDynamicMetaObjectProvider); JsonContract dynamicMemberContract = GetContractSafe(t); JsonConverter dynamicMemberConverter = GetConverter(dynamicMemberContract, null, null, member); object value; if (dynamicMemberConverter != null && dynamicMemberConverter.CanRead) { value = DeserializeConvertable(dynamicMemberConverter, reader, t, null); } else { value = CreateValueInternal(reader, t, dynamicMemberContract, null, null, member, null); } contract.TrySetMember(newObject, memberName, value); } } catch (Exception ex) { if (IsErrorHandled(newObject, contract, memberName, reader as IJsonLineInfo, reader.Path, ex)) { HandleError(reader, true, initialDepth); } else { throw; } } break; case JsonToken.EndObject: finished = true; break; default: throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType); } } while (!finished && reader.Read()); if (!finished) { ThrowUnexpectedEndException(reader, contract, newObject, "Unexpected end when deserializing object."); } OnDeserialized(reader, contract, newObject); return newObject; } #endif internal class CreatorPropertyContext { public string Name; public JsonProperty Property; public JsonProperty ConstructorProperty; public PropertyPresence? Presence; public object Value; public bool Used; } private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObjectContract contract, JsonProperty containerProperty, ObjectConstructor<object> creator, string id) { ValidationUtils.ArgumentNotNull(creator, nameof(creator)); // only need to keep a track of properies presence if they are required or a value should be defaulted if missing bool trackPresence = (contract.HasRequiredOrDefaultValueProperties || HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Populate)); Type objectType = contract.UnderlyingType; if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { string parameters = string.Join(", ", contract.CreatorParameters.Select(p => p.PropertyName).ToArray()); TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Deserializing {0} using creator with parameters: {1}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType, parameters)), null); } List<CreatorPropertyContext> propertyContexts = ResolvePropertyAndCreatorValues(contract, containerProperty, reader, objectType); if (trackPresence) { foreach (JsonProperty property in contract.Properties) { if (propertyContexts.All(p => p.Property != property)) { propertyContexts.Add(new CreatorPropertyContext { Property = property, Name = property.PropertyName, Presence = PropertyPresence.None }); } } } object[] creatorParameterValues = new object[contract.CreatorParameters.Count]; foreach (CreatorPropertyContext context in propertyContexts) { // set presence of read values if (trackPresence) { if (context.Property != null && context.Presence == null) { object v = context.Value; PropertyPresence propertyPresence; if (v == null) { propertyPresence = PropertyPresence.Null; } else if (v is string) { propertyPresence = CoerceEmptyStringToNull(context.Property.PropertyType, context.Property.PropertyContract, (string)v) ? PropertyPresence.Null : PropertyPresence.Value; } else { propertyPresence = PropertyPresence.Value; } context.Presence = propertyPresence; } } JsonProperty constructorProperty = context.ConstructorProperty; if (constructorProperty == null && context.Property != null) { constructorProperty = contract.CreatorParameters.ForgivingCaseSensitiveFind(p => p.PropertyName, context.Property.UnderlyingName); } if (constructorProperty != null && !constructorProperty.Ignored) { // handle giving default values to creator parameters // this needs to happen before the call to creator if (trackPresence) { if (context.Presence == PropertyPresence.None || context.Presence == PropertyPresence.Null) { if (constructorProperty.PropertyContract == null) { constructorProperty.PropertyContract = GetContractSafe(constructorProperty.PropertyType); } if (HasFlag(constructorProperty.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate)) { context.Value = EnsureType( reader, constructorProperty.GetResolvedDefaultValue(), CultureInfo.InvariantCulture, constructorProperty.PropertyContract, constructorProperty.PropertyType); } } } int i = contract.CreatorParameters.IndexOf(constructorProperty); creatorParameterValues[i] = context.Value; context.Used = true; } } object createdObject = creator(creatorParameterValues); if (id != null) { AddReference(reader, id, createdObject); } OnDeserializing(reader, contract, createdObject); // go through unused values and set the newly created object's properties foreach (CreatorPropertyContext context in propertyContexts) { if (context.Used || context.Property == null || context.Property.Ignored || context.Presence == PropertyPresence.None) { continue; } JsonProperty property = context.Property; object value = context.Value; if (ShouldSetPropertyValue(property, value)) { property.ValueProvider.SetValue(createdObject, value); context.Used = true; } else if (!property.Writable && value != null) { // handle readonly collection/dictionary properties JsonContract propertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType); if (propertyContract.ContractType == JsonContractType.Array) { JsonArrayContract propertyArrayContract = (JsonArrayContract)propertyContract; object createdObjectCollection = property.ValueProvider.GetValue(createdObject); if (createdObjectCollection != null) { IWrappedCollection createdObjectCollectionWrapper = propertyArrayContract.CreateWrapper(createdObjectCollection); IWrappedCollection newValues = propertyArrayContract.CreateWrapper(value); foreach (object newValue in newValues) { createdObjectCollectionWrapper.Add(newValue); } } } else if (propertyContract.ContractType == JsonContractType.Dictionary) { JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)propertyContract; object createdObjectDictionary = property.ValueProvider.GetValue(createdObject); if (createdObjectDictionary != null) { IDictionary targetDictionary = (dictionaryContract.ShouldCreateWrapper) ? dictionaryContract.CreateWrapper(createdObjectDictionary) : (IDictionary)createdObjectDictionary; IDictionary newValues = (dictionaryContract.ShouldCreateWrapper) ? dictionaryContract.CreateWrapper(value) : (IDictionary)value; foreach (DictionaryEntry newValue in newValues) { targetDictionary.Add(newValue.Key, newValue.Value); } } } context.Used = true; } } if (contract.ExtensionDataSetter != null) { foreach (CreatorPropertyContext propertyValue in propertyContexts) { if (!propertyValue.Used) { contract.ExtensionDataSetter(createdObject, propertyValue.Name, propertyValue.Value); } } } if (trackPresence) { foreach (CreatorPropertyContext context in propertyContexts) { if (context.Property == null) { continue; } EndProcessProperty( createdObject, reader, contract, reader.Depth, context.Property, context.Presence.GetValueOrDefault(), !context.Used); } } OnDeserialized(reader, contract, createdObject); return createdObject; } private object DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, object existingValue) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Started deserializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, objectType, converter.GetType())), null); } object value = converter.ReadJson(reader, objectType, existingValue, GetInternalSerializer()); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Finished deserializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, objectType, converter.GetType())), null); } return value; } private List<CreatorPropertyContext> ResolvePropertyAndCreatorValues(JsonObjectContract contract, JsonProperty containerProperty, JsonReader reader, Type objectType) { List<CreatorPropertyContext> propertyValues = new List<CreatorPropertyContext>(); bool exit = false; do { switch (reader.TokenType) { case JsonToken.PropertyName: string memberName = reader.Value.ToString(); CreatorPropertyContext creatorPropertyContext = new CreatorPropertyContext { Name = reader.Value.ToString(), ConstructorProperty = contract.CreatorParameters.GetClosestMatchProperty(memberName), Property = contract.Properties.GetClosestMatchProperty(memberName) }; propertyValues.Add(creatorPropertyContext); JsonProperty property = creatorPropertyContext.ConstructorProperty ?? creatorPropertyContext.Property; if (property != null && !property.Ignored) { if (property.PropertyContract == null) { property.PropertyContract = GetContractSafe(property.PropertyType); } JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.MemberConverter, contract, containerProperty); if (!ReadForType(reader, property.PropertyContract, propertyConverter != null)) { throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); } if (propertyConverter != null && propertyConverter.CanRead) { creatorPropertyContext.Value = DeserializeConvertable(propertyConverter, reader, property.PropertyType, null); } else { creatorPropertyContext.Value = CreateValueInternal(reader, property.PropertyType, property.PropertyContract, property, contract, containerProperty, null); } continue; } else { if (!reader.Read()) { throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); } if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) { TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Could not find member '{0}' on {1}.".FormatWith(CultureInfo.InvariantCulture, memberName, contract.UnderlyingType)), null); } if (Serializer._missingMemberHandling == MissingMemberHandling.Error) { throw JsonSerializationException.Create(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, objectType.Name)); } } if (contract.ExtensionDataSetter != null) { creatorPropertyContext.Value = ReadExtensionDataValue(contract, containerProperty, reader); } else { reader.Skip(); } break; case JsonToken.Comment: break; case JsonToken.EndObject: exit = true; break; default: throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType); } } while (!exit && reader.Read()); return propertyValues; } private bool ReadForType(JsonReader reader, JsonContract contract, bool hasConverter) { // don't read properties with converters as a specific value // the value might be a string which will then get converted which will error if read as date for example if (hasConverter) { return reader.Read(); } ReadType t = (contract != null) ? contract.InternalReadType : ReadType.Read; switch (t) { case ReadType.Read: return reader.ReadAndMoveToContent(); case ReadType.ReadAsInt32: reader.ReadAsInt32(); break; case ReadType.ReadAsDecimal: reader.ReadAsDecimal(); break; case ReadType.ReadAsDouble: reader.ReadAsDouble(); break; case ReadType.ReadAsBytes: reader.ReadAsBytes(); break; case ReadType.ReadAsBoolean: reader.ReadAsBoolean(); break; case ReadType.ReadAsString: reader.ReadAsString(); break; case ReadType.ReadAsDateTime: reader.ReadAsDateTime(); break; #if !NET20 case ReadType.ReadAsDateTimeOffset: reader.ReadAsDateTimeOffset(); break; #endif default: throw new ArgumentOutOfRangeException(); } return (reader.TokenType != JsonToken.None); } public object CreateNewObject(JsonReader reader, JsonObjectContract objectContract, JsonProperty containerMember, JsonProperty containerProperty, string id, out bool createdFromNonDefaultCreator) { object newObject = null; if (objectContract.OverrideCreator != null) { if (objectContract.CreatorParameters.Count > 0) { createdFromNonDefaultCreator = true; return CreateObjectUsingCreatorWithParameters(reader, objectContract, containerMember, objectContract.OverrideCreator, id); } newObject = objectContract.OverrideCreator(new object[0]); } else if (objectContract.DefaultCreator != null && (!objectContract.DefaultCreatorNonPublic || Serializer._constructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor || objectContract.ParameterizedCreator == null)) { // use the default constructor if it is... // public // non-public and the user has change constructor handling settings // non-public and there is no other creator newObject = objectContract.DefaultCreator(); } else if (objectContract.ParameterizedCreator != null) { createdFromNonDefaultCreator = true; return CreateObjectUsingCreatorWithParameters(reader, objectContract, containerMember, objectContract.ParameterizedCreator, id); } if (newObject == null) { if (!objectContract.IsInstantiable) { throw JsonSerializationException.Create(reader, "Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, objectContract.UnderlyingType)); } throw JsonSerializationException.Create(reader, "Unable to find a constructor to use for type {0}. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute.".FormatWith(CultureInfo.InvariantCulture, objectContract.UnderlyingType)); } createdFromNonDefaultCreator = false; return newObject; } private object PopulateObject(object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, string id) { OnDeserializing(reader, contract, newObject); // only need to keep a track of properies presence if they are required or a value should be defaulted if missing Dictionary<JsonProperty, PropertyPresence> propertiesPresence = (contract.HasRequiredOrDefaultValueProperties || HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Populate)) ? contract.Properties.ToDictionary(m => m, m => PropertyPresence.None) : null; if (id != null) { AddReference(reader, id, newObject); } int initialDepth = reader.Depth; bool finished = false; do { switch (reader.TokenType) { case JsonToken.PropertyName: { string memberName = reader.Value.ToString(); if (CheckPropertyName(reader, memberName)) { continue; } try { // attempt exact case match first // then try match ignoring case JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName); if (property == null) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) { TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Could not find member '{0}' on {1}".FormatWith(CultureInfo.InvariantCulture, memberName, contract.UnderlyingType)), null); } if (Serializer._missingMemberHandling == MissingMemberHandling.Error) { throw JsonSerializationException.Create(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, contract.UnderlyingType.Name)); } if (!reader.Read()) { break; } SetExtensionData(contract, member, reader, memberName, newObject); continue; } if (property.Ignored || !ShouldDeserialize(reader, property, newObject)) { if (!reader.Read()) { break; } SetPropertyPresence(reader, property, propertiesPresence); SetExtensionData(contract, member, reader, memberName, newObject); } else { if (property.PropertyContract == null) { property.PropertyContract = GetContractSafe(property.PropertyType); } JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.MemberConverter, contract, member); if (!ReadForType(reader, property.PropertyContract, propertyConverter != null)) { throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); } SetPropertyPresence(reader, property, propertiesPresence); // set extension data if property is ignored or readonly if (!SetPropertyValue(property, propertyConverter, contract, member, reader, newObject)) { SetExtensionData(contract, member, reader, memberName, newObject); } } } catch (Exception ex) { if (IsErrorHandled(newObject, contract, memberName, reader as IJsonLineInfo, reader.Path, ex)) { HandleError(reader, true, initialDepth); } else { throw; } } break; } case JsonToken.EndObject: finished = true; break; case JsonToken.Comment: // ignore break; default: throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType); } } while (!finished && reader.Read()); if (!finished) { ThrowUnexpectedEndException(reader, contract, newObject, "Unexpected end when deserializing object."); } if (propertiesPresence != null) { foreach (KeyValuePair<JsonProperty, PropertyPresence> propertyPresence in propertiesPresence) { JsonProperty property = propertyPresence.Key; PropertyPresence presence = propertyPresence.Value; EndProcessProperty(newObject, reader, contract, initialDepth, property, presence, true); } } OnDeserialized(reader, contract, newObject); return newObject; } private bool ShouldDeserialize(JsonReader reader, JsonProperty property, object target) { if (property.ShouldDeserialize == null) { return true; } bool shouldDeserialize = property.ShouldDeserialize(target); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) { TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, reader.Path, "ShouldDeserialize result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, shouldDeserialize)), null); } return shouldDeserialize; } private bool CheckPropertyName(JsonReader reader, string memberName) { if (Serializer.MetadataPropertyHandling == MetadataPropertyHandling.ReadAhead) { switch (memberName) { case JsonTypeReflector.IdPropertyName: case JsonTypeReflector.RefPropertyName: case JsonTypeReflector.TypePropertyName: case JsonTypeReflector.ArrayValuesPropertyName: reader.Skip(); return true; } } return false; } private void SetExtensionData(JsonObjectContract contract, JsonProperty member, JsonReader reader, string memberName, object o) { if (contract.ExtensionDataSetter != null) { try { object value = ReadExtensionDataValue(contract, member, reader); contract.ExtensionDataSetter(o, memberName, value); } catch (Exception ex) { throw JsonSerializationException.Create(reader, "Error setting value in extension data for type '{0}'.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType), ex); } } else { reader.Skip(); } } private object ReadExtensionDataValue(JsonObjectContract contract, JsonProperty member, JsonReader reader) { object value; if (contract.ExtensionDataIsJToken) { value = JToken.ReadFrom(reader); } else { value = CreateValueInternal(reader, null, null, null, contract, member, null); } return value; } private void EndProcessProperty(object newObject, JsonReader reader, JsonObjectContract contract, int initialDepth, JsonProperty property, PropertyPresence presence, bool setDefaultValue) { if (presence == PropertyPresence.None || presence == PropertyPresence.Null) { try { Required resolvedRequired = property._required ?? contract.ItemRequired ?? Required.Default; switch (presence) { case PropertyPresence.None: if (resolvedRequired == Required.AllowNull || resolvedRequired == Required.Always) { throw JsonSerializationException.Create(reader, "Required property '{0}' not found in JSON.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName)); } if (setDefaultValue && !property.Ignored) { if (property.PropertyContract == null) { property.PropertyContract = GetContractSafe(property.PropertyType); } if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate) && property.Writable) { property.ValueProvider.SetValue(newObject, EnsureType(reader, property.GetResolvedDefaultValue(), CultureInfo.InvariantCulture, property.PropertyContract, property.PropertyType)); } } break; case PropertyPresence.Null: if (resolvedRequired == Required.Always) { throw JsonSerializationException.Create(reader, "Required property '{0}' expects a value but got null.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName)); } if (resolvedRequired == Required.DisallowNull) { throw JsonSerializationException.Create(reader, "Required property '{0}' expects a non-null value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName)); } break; } } catch (Exception ex) { if (IsErrorHandled(newObject, contract, property.PropertyName, reader as IJsonLineInfo, reader.Path, ex)) { HandleError(reader, true, initialDepth); } else { throw; } } } } private void SetPropertyPresence(JsonReader reader, JsonProperty property, Dictionary<JsonProperty, PropertyPresence> requiredProperties) { if (property != null && requiredProperties != null) { PropertyPresence propertyPresence; switch (reader.TokenType) { case JsonToken.String: propertyPresence = (CoerceEmptyStringToNull(property.PropertyType, property.PropertyContract, (string)reader.Value)) ? PropertyPresence.Null : PropertyPresence.Value; break; case JsonToken.Null: case JsonToken.Undefined: propertyPresence = PropertyPresence.Null; break; default: propertyPresence = PropertyPresence.Value; break; } requiredProperties[property] = propertyPresence; } } private void HandleError(JsonReader reader, bool readPastError, int initialDepth) { ClearErrorContext(); if (readPastError) { reader.Skip(); while (reader.Depth > (initialDepth + 1)) { if (!reader.Read()) { break; } } } } } }
{ "content_hash": "1ac9a64ed239f9a97ae7e371fed8dcd4", "timestamp": "", "source": "github", "line_count": 2584, "max_line_length": 400, "avg_line_length": 45.7469040247678, "alnum_prop": 0.5207427459605787, "repo_name": "CallumCarmicheal/Keyboard-Tracker", "id": "7864da5c8748f36da2a624c2c361ce9b30d75f7e", "size": "118212", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "dep/JSON.Net/Source/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "657" }, { "name": "C#", "bytes": "4629287" }, { "name": "PowerShell", "bytes": "74741" } ], "symlink_target": "" }
package sh.isaac.provider.query.lucene.indexers; import org.junit.Assert; import org.junit.Test; /** * {@link DescriptionIndexerTest}. * * @author <a href="mailto:[email protected]">Dan Armbrust</a> */ public class DescriptionIndexerTest { @Test public void adjustBrackets() throws Exception { Assert.assertEquals("A long \\[test\\] string", DescriptionIndexer.handleBrackets("A long [test] string", '[', ']')); Assert.assertEquals("A long \\]test\\[ string", DescriptionIndexer.handleBrackets("A long ]test[ string", '[', ']')); Assert.assertEquals("Another [5 TO 6] string \\[ with random \\[stuff\\]", DescriptionIndexer.handleBrackets("Another [5 TO 6] string [ with random [stuff]", '[', ']')); Assert.assertEquals("\\[\\[\\[\\[", DescriptionIndexer.handleBrackets("[[[[", '[', ']')); Assert.assertEquals("\\]\\[\\]\\[", DescriptionIndexer.handleBrackets("][][", '[', ']')); Assert.assertEquals("\\[query\\] [a to b] for a bunch of \\[stuff\\]", DescriptionIndexer.handleBrackets("[query] [a to b] for a bunch of [stuff]", '[', ']')); Assert.assertEquals("A long \\{test\\} string", DescriptionIndexer.handleBrackets("A long {test} string", '{', '}')); Assert.assertEquals("A long \\[test\\] string", DescriptionIndexer.handleBrackets("A long \\[test\\] string", '[', ']')); //Ignore regexp Assert.assertEquals("/A long [test] string/", DescriptionIndexer.handleBrackets("/A long [test] string/", '[', ']')); } @Test public void adjustOthers() throws Exception { Assert.assertEquals("http\\://foo.com", DescriptionIndexer.handleUnsupportedEscapeChars("http://foo.com")); Assert.assertEquals("http\\://foo.com", DescriptionIndexer.handleUnsupportedEscapeChars("http\\://foo.com")); Assert.assertEquals("fred\\^jane", DescriptionIndexer.handleUnsupportedEscapeChars("fred^jane")); Assert.assertEquals("/fred^jane/", DescriptionIndexer.handleUnsupportedEscapeChars("/fred^jane/")); Assert.assertEquals("foo\\/bar", DescriptionIndexer.handleUnsupportedEscapeChars("foo/bar")); Assert.assertEquals("foo/bar with another foo/bar", DescriptionIndexer.handleUnsupportedEscapeChars("foo/bar with another foo/bar")); } }
{ "content_hash": "1dfcccb2b6a0692a69089e286e38a842", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 171, "avg_line_length": 53.146341463414636, "alnum_prop": 0.6961909132629647, "repo_name": "OSEHRA/ISAAC", "id": "92eafd1c1c5a380152991b8ed8c0604e41038be9", "size": "3570", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "provider/query/src/test/java/sh/isaac/provider/query/lucene/indexers/DescriptionIndexerTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AppleScript", "bytes": "1499" }, { "name": "CSS", "bytes": "80251" }, { "name": "HTML", "bytes": "35085" }, { "name": "Java", "bytes": "12855254" }, { "name": "Swift", "bytes": "98" }, { "name": "XSLT", "bytes": "362" } ], "symlink_target": "" }
package org.apache.river.test.spec.security.proxytrust.util; import java.util.logging.Level; // java import java.io.Serializable; import java.rmi.RemoteException; // net.jini import net.jini.security.TrustVerifier; /** * Class implementing TrustVerifier interface whose 'isTrustedObject' method * always returns false. */ public class FalseTrustVerifier extends BaseTrustVerifier implements Serializable { /** * Always returns false. * * @return false */ public boolean isTrustedObject(Object obj, TrustVerifier.Context ctx) throws RemoteException { this.obj = obj; this.ctx = ctx; srcArray.add(this); return false; } }
{ "content_hash": "80c10bb29b991636b1061d8a10ea0e70", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 76, "avg_line_length": 20.88235294117647, "alnum_prop": 0.6873239436619718, "repo_name": "pfirmstone/river-internet", "id": "e0b5d1e36abe3a3e301b3d85e2cdaaf0390d84a3", "size": "1516", "binary": false, "copies": "2", "ref": "refs/heads/trunk", "path": "qa/src/org/apache/river/test/spec/security/proxytrust/util/FalseTrustVerifier.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2047" }, { "name": "Groff", "bytes": "863" }, { "name": "Groovy", "bytes": "35711" }, { "name": "HTML", "bytes": "4398920" }, { "name": "Java", "bytes": "33660467" }, { "name": "Makefile", "bytes": "3046" }, { "name": "Shell", "bytes": "69126" } ], "symlink_target": "" }
using UniversalGrid.Geometry; namespace UniversalGrid { public interface IGridContainer<T> : IGrid, ISpatialContainer<T> { } }
{ "content_hash": "1c9b8d218567c8c9f2224088d7b7e0a2", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 68, "avg_line_length": 17.5, "alnum_prop": 0.7214285714285714, "repo_name": "roberino/UniversalGrid", "id": "b770dc2b93f1eb3ce6deaf3cb110d6b74db4a9ae", "size": "142", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/UniversalGrid/IGridContainer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "269" }, { "name": "C#", "bytes": "93632" } ], "symlink_target": "" }
define(['underscore', 'backbone'], function(_, Backbone){ var MessagingModel = Backbone.Model.extend({ initialize: function(skills) { this.set("skills", skills); }, createFinalObj: function(formData){ var formattedData = {}; var matchingInfo = {"matchingInfo": this.get("skills")}; for (var i = 0; i < formData.length; i++) { var field = formData[i]; formattedData[field.name] = field.value; } const formSummary = {...formattedData, ...matchingInfo}; return formSummary; } }); return MessagingModel; });
{ "content_hash": "660d794e78887f431151f9d8ee2fa40e", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 65, "avg_line_length": 31.3, "alnum_prop": 0.5686900958466453, "repo_name": "designforsf/brigade-matchmaker", "id": "203625f203c352e5e04befb6f55e04d25d972ab7", "size": "627", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/messaging/js/models/MessagingModel.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12667" }, { "name": "HTML", "bytes": "50835" }, { "name": "JavaScript", "bytes": "2077249" }, { "name": "Python", "bytes": "39112" }, { "name": "Shell", "bytes": "4597" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "836a7ef8325440b1c1561a1ad9a01c0d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "569b676d5e5f5d0bd629d7245de1d426c03b21d1", "size": "179", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Chrysobalanaceae/Parinari/Parinari excelsa/ Syn. Parinari holstii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
@interface BCInstantStoryboardSegue : UIStoryboardSegue @end
{ "content_hash": "1597aff9c6b8788e10a9cda77aa78d62", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 55, "avg_line_length": 20.666666666666668, "alnum_prop": 0.8548387096774194, "repo_name": "sethk/BushidoCore", "id": "336966606a98584714925218fe78cb6ed5021e12", "size": "244", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Sources/UIKit/BCInstantStoryboardSegue.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Objective-C", "bytes": "65819" }, { "name": "Ruby", "bytes": "2358" } ], "symlink_target": "" }
package mobi.inthepocket.android.beacons.ibeaconscanner.utils; import android.Manifest; import android.annotation.TargetApi; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.support.annotation.NonNull; import java.security.InvalidParameterException; /** * PermissionUtils to help determine if a particular permission is granted. */ public final class PermissionUtils { private PermissionUtils() { } /** * Determine whether the location permission has been granted (ACCESS_COARSE_LOCATION or * ACCESS_FINE_LOCATION). Below Android M, will always return true. * * @param context to determine with if the permission is granted * @return true if you have any location permission or the sdk is below Android M. * @throws InvalidParameterException if {@code context} is null */ public static boolean isLocationGranted(@NonNull final Context context) throws InvalidParameterException { if (context == null) { throw new InvalidParameterException("context is null"); } return (!isMarshmallowOrLater() || (isPermissionGranted(context, Manifest.permission.ACCESS_COARSE_LOCATION) || isPermissionGranted(context, Manifest.permission.ACCESS_FINE_LOCATION))); } /** * @return true if the current sdk is above or equal to Android M */ private static boolean isMarshmallowOrLater() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M; } /** * Determine whether the provided context has been granted a particular permission. * * @param context where from you determine if a permission is granted * @param permission you want to determinie if it is granted * @return true if you have the permission, or false if not */ @TargetApi(Build.VERSION_CODES.M) private static boolean isPermissionGranted(@NonNull final Context context, @NonNull final String permission) { return context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED; } }
{ "content_hash": "7d447b625bac5b4f5674e630d2848445", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 169, "avg_line_length": 34.41935483870968, "alnum_prop": 0.7108716026241799, "repo_name": "inthepocket/ibeacon-scanner-android", "id": "ea5f04e7a739075b62d10076f2b63c9a67f50c86", "size": "2134", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ibeaconscanner/src/main/java/mobi/inthepocket/android/beacons/ibeaconscanner/utils/PermissionUtils.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "119906" } ], "symlink_target": "" }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.Extensions.Hosting { /// <summary> /// Options for <see cref="IHost"/> /// </summary> public class HostOptions { /// <summary> /// The default timeout for <see cref="IHost.StopAsync(System.Threading.CancellationToken)"/>. /// </summary> public TimeSpan ShutdownTimeout { get; set; } = TimeSpan.FromSeconds(5); } }
{ "content_hash": "1c6b857045d0ce060cc0a1c6c1a45459", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 111, "avg_line_length": 31.833333333333332, "alnum_prop": 0.6527050610820244, "repo_name": "RabbitTeam/Rabbit-Extensions", "id": "45fb9a187fe2ca261e5952be42ae299f1496a677", "size": "575", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Rabbit.Extensions.Boot/Microsoft.Extensions.Hosting/HostOptions.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "135538" } ], "symlink_target": "" }
namespace Urho3D { void Texture2D::OnDeviceLost() { // No-op on Direct3D11 } void Texture2D::OnDeviceReset() { // No-op on Direct3D11 } void Texture2D::Release() { if (graphics_ && object_.ptr_) { for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i) { if (graphics_->GetTexture(i) == this) graphics_->SetTexture(i, nullptr); } } if (renderSurface_) renderSurface_->Release(); URHO3D_SAFE_RELEASE(object_.ptr_); URHO3D_SAFE_RELEASE(resolveTexture_); URHO3D_SAFE_RELEASE(shaderResourceView_); URHO3D_SAFE_RELEASE(sampler_); } bool Texture2D::SetData(unsigned level, int x, int y, int width, int height, const void* data) { URHO3D_PROFILE(SetTextureData); if (!object_.ptr_) { URHO3D_LOGERROR("No texture created, can not set data"); return false; } if (!data) { URHO3D_LOGERROR("Null source for setting data"); return false; } if (level >= levels_) { URHO3D_LOGERROR("Illegal mip level for setting data"); return false; } int levelWidth = GetLevelWidth(level); int levelHeight = GetLevelHeight(level); if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || width <= 0 || height <= 0) { URHO3D_LOGERROR("Illegal dimensions for setting data"); return false; } // If compressed, align the update region on a block if (IsCompressed()) { x &= ~3; y &= ~3; width += 3; width &= 0xfffffffc; height += 3; height &= 0xfffffffc; } unsigned char* src = (unsigned char*)data; unsigned rowSize = GetRowDataSize(width); unsigned rowStart = GetRowDataSize(x); unsigned subResource = D3D11CalcSubresource(level, 0, levels_); if (usage_ == TEXTURE_DYNAMIC) { if (IsCompressed()) { height = (height + 3) >> 2; y >>= 2; } D3D11_MAPPED_SUBRESOURCE mappedData; mappedData.pData = nullptr; HRESULT hr = graphics_->GetImpl()->GetDeviceContext()->Map((ID3D11Resource*)object_.ptr_, subResource, D3D11_MAP_WRITE_DISCARD, 0, &mappedData); if (FAILED(hr) || !mappedData.pData) { URHO3D_LOGD3DERROR("Failed to map texture for update", hr); return false; } else { for (int row = 0; row < height; ++row) memcpy((unsigned char*)mappedData.pData + (row + y) * mappedData.RowPitch + rowStart, src + row * rowSize, rowSize); graphics_->GetImpl()->GetDeviceContext()->Unmap((ID3D11Resource*)object_.ptr_, subResource); } } else { D3D11_BOX destBox; destBox.left = (UINT)x; destBox.right = (UINT)(x + width); destBox.top = (UINT)y; destBox.bottom = (UINT)(y + height); destBox.front = 0; destBox.back = 1; graphics_->GetImpl()->GetDeviceContext()->UpdateSubresource((ID3D11Resource*)object_.ptr_, subResource, &destBox, data, rowSize, 0); } return true; } bool Texture2D::SetData(Image* image, bool useAlpha) { if (!image) { URHO3D_LOGERROR("Null image, can not load texture"); return false; } // Use a shared ptr for managing the temporary mip images created during this function SharedPtr<Image> mipImage; unsigned memoryUse = sizeof(Texture2D); int quality = QUALITY_HIGH; Renderer* renderer = GetSubsystem<Renderer>(); if (renderer) quality = renderer->GetTextureQuality(); if (!image->IsCompressed()) { // Convert unsuitable formats to RGBA unsigned components = image->GetComponents(); if ((components == 1 && !useAlpha) || components == 2 || components == 3) { mipImage = image->ConvertToRGBA(); image = mipImage; if (!image) return false; components = image->GetComponents(); } unsigned char* levelData = image->GetData(); int levelWidth = image->GetWidth(); int levelHeight = image->GetHeight(); unsigned format = 0; // Discard unnecessary mip levels for (unsigned i = 0; i < mipsToSkip_[quality]; ++i) { mipImage = image->GetNextLevel(); image = mipImage; levelData = image->GetData(); levelWidth = image->GetWidth(); levelHeight = image->GetHeight(); } switch (components) { case 1: format = Graphics::GetAlphaFormat(); break; case 4: format = Graphics::GetRGBAFormat(); break; default: break; } // If image was previously compressed, reset number of requested levels to avoid error if level count is too high for new size if (IsCompressed() && requestedLevels_ > 1) requestedLevels_ = 0; SetSize(levelWidth, levelHeight, format); for (unsigned i = 0; i < levels_; ++i) { SetData(i, 0, 0, levelWidth, levelHeight, levelData); memoryUse += levelWidth * levelHeight * components; if (i < levels_ - 1) { mipImage = image->GetNextLevel(); image = mipImage; levelData = image->GetData(); levelWidth = image->GetWidth(); levelHeight = image->GetHeight(); } } } else { int width = image->GetWidth(); int height = image->GetHeight(); unsigned levels = image->GetNumCompressedLevels(); unsigned format = graphics_->GetFormat(image->GetCompressedFormat()); bool needDecompress = false; if (!format) { format = Graphics::GetRGBAFormat(); needDecompress = true; } unsigned mipsToSkip = mipsToSkip_[quality]; if (mipsToSkip >= levels) mipsToSkip = levels - 1; while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4)) --mipsToSkip; width /= (1 << mipsToSkip); height /= (1 << mipsToSkip); SetNumLevels(Max((levels - mipsToSkip), 1U)); SetSize(width, height, format); for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i) { CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip); if (!needDecompress) { SetData(i, 0, 0, level.width_, level.height_, level.data_); memoryUse += level.rows_ * level.rowSize_; } else { unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * 4]; level.Decompress(rgbaData); SetData(i, 0, 0, level.width_, level.height_, rgbaData); memoryUse += level.width_ * level.height_ * 4; delete[] rgbaData; } } } SetMemoryUse(memoryUse); return true; } bool Texture2D::GetData(unsigned level, void* dest) const { if (!object_.ptr_) { URHO3D_LOGERROR("No texture created, can not get data"); return false; } if (!dest) { URHO3D_LOGERROR("Null destination for getting data"); return false; } if (level >= levels_) { URHO3D_LOGERROR("Illegal mip level for getting data"); return false; } if (multiSample_ > 1 && !autoResolve_) { URHO3D_LOGERROR("Can not get data from multisampled texture without autoresolve"); return false; } if (resolveDirty_) graphics_->ResolveToTexture(const_cast<Texture2D*>(this)); int levelWidth = GetLevelWidth(level); int levelHeight = GetLevelHeight(level); D3D11_TEXTURE2D_DESC textureDesc; memset(&textureDesc, 0, sizeof textureDesc); textureDesc.Width = (UINT)levelWidth; textureDesc.Height = (UINT)levelHeight; textureDesc.MipLevels = 1; textureDesc.ArraySize = 1; textureDesc.Format = (DXGI_FORMAT)format_; textureDesc.SampleDesc.Count = 1; textureDesc.SampleDesc.Quality = 0; textureDesc.Usage = D3D11_USAGE_STAGING; textureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; ID3D11Texture2D* stagingTexture = nullptr; HRESULT hr = graphics_->GetImpl()->GetDevice()->CreateTexture2D(&textureDesc, nullptr, &stagingTexture); if (FAILED(hr)) { URHO3D_LOGD3DERROR("Failed to create staging texture for GetData", hr); URHO3D_SAFE_RELEASE(stagingTexture); return false; } ID3D11Resource* srcResource = (ID3D11Resource*)(resolveTexture_ ? resolveTexture_ : object_.ptr_); unsigned srcSubResource = D3D11CalcSubresource(level, 0, levels_); D3D11_BOX srcBox; srcBox.left = 0; srcBox.right = (UINT)levelWidth; srcBox.top = 0; srcBox.bottom = (UINT)levelHeight; srcBox.front = 0; srcBox.back = 1; graphics_->GetImpl()->GetDeviceContext()->CopySubresourceRegion(stagingTexture, 0, 0, 0, 0, srcResource, srcSubResource, &srcBox); D3D11_MAPPED_SUBRESOURCE mappedData; mappedData.pData = nullptr; unsigned rowSize = GetRowDataSize(levelWidth); unsigned numRows = (unsigned)(IsCompressed() ? (levelHeight + 3) >> 2 : levelHeight); hr = graphics_->GetImpl()->GetDeviceContext()->Map((ID3D11Resource*)stagingTexture, 0, D3D11_MAP_READ, 0, &mappedData); if (FAILED(hr) || !mappedData.pData) { URHO3D_LOGD3DERROR("Failed to map staging texture for GetData", hr); URHO3D_SAFE_RELEASE(stagingTexture); return false; } else { for (unsigned row = 0; row < numRows; ++row) memcpy((unsigned char*)dest + row * rowSize, (unsigned char*)mappedData.pData + row * mappedData.RowPitch, rowSize); graphics_->GetImpl()->GetDeviceContext()->Unmap((ID3D11Resource*)stagingTexture, 0); URHO3D_SAFE_RELEASE(stagingTexture); return true; } } bool Texture2D::Create() { Release(); if (!graphics_ || !width_ || !height_) return false; levels_ = CheckMaxLevels(width_, height_, requestedLevels_); D3D11_TEXTURE2D_DESC textureDesc; memset(&textureDesc, 0, sizeof textureDesc); textureDesc.Format = (DXGI_FORMAT)(sRGB_ ? GetSRGBFormat(format_) : format_); // Disable multisampling if not supported if (multiSample_ > 1 && !graphics_->GetImpl()->CheckMultiSampleSupport(textureDesc.Format, multiSample_)) { multiSample_ = 1; autoResolve_ = false; } // Set mipmapping if (usage_ == TEXTURE_DEPTHSTENCIL) levels_ = 1; else if (usage_ == TEXTURE_RENDERTARGET && levels_ != 1 && multiSample_ == 1) textureDesc.MiscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS; textureDesc.Width = (UINT)width_; textureDesc.Height = (UINT)height_; // Disable mip levels from the multisample texture. Rather create them to the resolve texture textureDesc.MipLevels = multiSample_ == 1 ? levels_ : 1; textureDesc.ArraySize = 1; textureDesc.SampleDesc.Count = (UINT)multiSample_; textureDesc.SampleDesc.Quality = graphics_->GetImpl()->GetMultiSampleQuality(textureDesc.Format, multiSample_); textureDesc.Usage = usage_ == TEXTURE_DYNAMIC ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT; textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; if (usage_ == TEXTURE_RENDERTARGET) textureDesc.BindFlags |= D3D11_BIND_RENDER_TARGET; else if (usage_ == TEXTURE_DEPTHSTENCIL) textureDesc.BindFlags |= D3D11_BIND_DEPTH_STENCIL; textureDesc.CPUAccessFlags = usage_ == TEXTURE_DYNAMIC ? D3D11_CPU_ACCESS_WRITE : 0; // D3D feature level 10.0 or below does not support readable depth when multisampled if (usage_ == TEXTURE_DEPTHSTENCIL && multiSample_ > 1 && graphics_->GetImpl()->GetDevice()->GetFeatureLevel() < D3D_FEATURE_LEVEL_10_1) textureDesc.BindFlags &= ~D3D11_BIND_SHADER_RESOURCE; HRESULT hr = graphics_->GetImpl()->GetDevice()->CreateTexture2D(&textureDesc, nullptr, (ID3D11Texture2D**)&object_); if (FAILED(hr)) { URHO3D_LOGD3DERROR("Failed to create texture", hr); URHO3D_SAFE_RELEASE(object_.ptr_); return false; } // Create resolve texture for multisampling if necessary if (multiSample_ > 1 && autoResolve_) { textureDesc.MipLevels = levels_; textureDesc.SampleDesc.Count = 1; textureDesc.SampleDesc.Quality = 0; if (levels_ != 1) textureDesc.MiscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS; HRESULT hr = graphics_->GetImpl()->GetDevice()->CreateTexture2D(&textureDesc, nullptr, (ID3D11Texture2D**)&resolveTexture_); if (FAILED(hr)) { URHO3D_LOGD3DERROR("Failed to create resolve texture", hr); URHO3D_SAFE_RELEASE(resolveTexture_); return false; } } if (textureDesc.BindFlags & D3D11_BIND_SHADER_RESOURCE) { D3D11_SHADER_RESOURCE_VIEW_DESC resourceViewDesc; memset(&resourceViewDesc, 0, sizeof resourceViewDesc); resourceViewDesc.Format = (DXGI_FORMAT)GetSRVFormat(textureDesc.Format); resourceViewDesc.ViewDimension = (multiSample_ > 1 && !autoResolve_) ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D; resourceViewDesc.Texture2D.MipLevels = (UINT)levels_; // Sample the resolve texture if created, otherwise the original ID3D11Resource* viewObject = resolveTexture_ ? (ID3D11Resource*)resolveTexture_ : (ID3D11Resource*)object_.ptr_; hr = graphics_->GetImpl()->GetDevice()->CreateShaderResourceView(viewObject, &resourceViewDesc, (ID3D11ShaderResourceView**)&shaderResourceView_); if (FAILED(hr)) { URHO3D_LOGD3DERROR("Failed to create shader resource view for texture", hr); URHO3D_SAFE_RELEASE(shaderResourceView_); return false; } } if (usage_ == TEXTURE_RENDERTARGET) { D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc; memset(&renderTargetViewDesc, 0, sizeof renderTargetViewDesc); renderTargetViewDesc.Format = textureDesc.Format; renderTargetViewDesc.ViewDimension = multiSample_ > 1 ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D; hr = graphics_->GetImpl()->GetDevice()->CreateRenderTargetView((ID3D11Resource*)object_.ptr_, &renderTargetViewDesc, (ID3D11RenderTargetView**)&renderSurface_->renderTargetView_); if (FAILED(hr)) { URHO3D_LOGD3DERROR("Failed to create rendertarget view for texture", hr); URHO3D_SAFE_RELEASE(renderSurface_->renderTargetView_); return false; } } else if (usage_ == TEXTURE_DEPTHSTENCIL) { D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; memset(&depthStencilViewDesc, 0, sizeof depthStencilViewDesc); depthStencilViewDesc.Format = (DXGI_FORMAT)GetDSVFormat(textureDesc.Format); depthStencilViewDesc.ViewDimension = multiSample_ > 1 ? D3D11_DSV_DIMENSION_TEXTURE2DMS : D3D11_DSV_DIMENSION_TEXTURE2D; hr = graphics_->GetImpl()->GetDevice()->CreateDepthStencilView((ID3D11Resource*)object_.ptr_, &depthStencilViewDesc, (ID3D11DepthStencilView**)&renderSurface_->renderTargetView_); if (FAILED(hr)) { URHO3D_LOGD3DERROR("Failed to create depth-stencil view for texture", hr); URHO3D_SAFE_RELEASE(renderSurface_->renderTargetView_); return false; } // Create also a read-only version of the view for simultaneous depth testing and sampling in shader // Requires feature level 11 if (graphics_->GetImpl()->GetDevice()->GetFeatureLevel() >= D3D_FEATURE_LEVEL_11_0) { depthStencilViewDesc.Flags = D3D11_DSV_READ_ONLY_DEPTH; hr = graphics_->GetImpl()->GetDevice()->CreateDepthStencilView((ID3D11Resource*)object_.ptr_, &depthStencilViewDesc, (ID3D11DepthStencilView**)&renderSurface_->readOnlyView_); if (FAILED(hr)) { URHO3D_LOGD3DERROR("Failed to create read-only depth-stencil view for texture", hr); URHO3D_SAFE_RELEASE(renderSurface_->readOnlyView_); } } } return true; } }
{ "content_hash": "ffc28d9365dce8a4f85d2724cf03253e", "timestamp": "", "source": "github", "line_count": 475, "max_line_length": 140, "avg_line_length": 34.717894736842105, "alnum_prop": 0.6109999393608635, "repo_name": "codemon66/Urho3D", "id": "ce6c6645357e948ccaaa6ce7910eaf009f723bd5", "size": "18080", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "Source/Urho3D/Graphics/Direct3D11/D3D11Texture2D.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "1358047" }, { "name": "Batchfile", "bytes": "19519" }, { "name": "C++", "bytes": "8026326" }, { "name": "CMake", "bytes": "431544" }, { "name": "GLSL", "bytes": "161353" }, { "name": "HLSL", "bytes": "185424" }, { "name": "HTML", "bytes": "1375" }, { "name": "Java", "bytes": "78058" }, { "name": "Lua", "bytes": "501285" }, { "name": "MAXScript", "bytes": "94704" }, { "name": "Objective-C", "bytes": "6539" }, { "name": "Ruby", "bytes": "64636" }, { "name": "Shell", "bytes": "26397" } ], "symlink_target": "" }
package bigdata.apex.examples; import org.apache.hadoop.conf.Configuration; import com.datatorrent.api.annotation.ApplicationAnnotation; import com.datatorrent.api.StreamingApplication; import com.datatorrent.api.DAG; import com.datatorrent.api.DAG.Locality; import com.datatorrent.lib.io.ConsoleOutputOperator; @ApplicationAnnotation(name="MyFirstApplication") public class Application implements StreamingApplication { @Override public void populateDAG(DAG dag, Configuration conf) { // Sample DAG with 2 operators // Replace this code with the DAG you want to build RandomNumberGenerator randomGenerator = dag.addOperator("randomGenerator", RandomNumberGenerator.class); randomGenerator.setNumTuples(500); ConsoleOutputOperator cons = dag.addOperator("console", new ConsoleOutputOperator()); dag.addStream("randomData", randomGenerator.out, cons.input).setLocality(Locality.CONTAINER_LOCAL); } }
{ "content_hash": "0b89b2a464ad788422433f06f864f92c", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 108, "avg_line_length": 33.37931034482759, "alnum_prop": 0.7737603305785123, "repo_name": "PuneetKadian/bigdata-examples", "id": "8ba849d262f31aba458339db719c868311b0a294", "size": "1022", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bigdata-apex/apex.examples/src/main/java/bigdata/apex/examples/Application.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "228197" }, { "name": "XSLT", "bytes": "1802" } ], "symlink_target": "" }
import { Route, Switch, BrowserRouter } from "react-router-dom"; import * as React from "react"; import { Header } from "../components/header_component"; import { HomePage } from "../pages/home_page"; import { MoviePage } from "../pages/movies_page"; import { ActorPage } from "../pages/actors_page"; import "../stores/movie_store"; import "../stores/actor_store"; export const Layout = () => ( <BrowserRouter> <div> <Header bg="primary" title="TsMovies" rootPath="/" links={[ { path: "/movies", text: "Movies"}, { path: "/actors", text: "Actors"} ]} /> <main style={{ paddingTop: "60px" }}> <Switch> <Route exact path="/" component={HomePage}/> <Route path="/movies" component={MoviePage}/> <Route path="/actors" component={ActorPage}/> </Switch> </main> </div> </BrowserRouter> );
{ "content_hash": "322705a2631d45cd1054d7d28c6653eb", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 65, "avg_line_length": 34.45161290322581, "alnum_prop": 0.4868913857677903, "repo_name": "remojansen/LearningTypeScript", "id": "df2f78dd64220d85df796436482b4296e94a8258", "size": "1068", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chapters/chapter_11/web/frontend/config/layout.tsx", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "552" }, { "name": "HTML", "bytes": "1455" }, { "name": "JavaScript", "bytes": "9555" }, { "name": "TypeScript", "bytes": "286009" } ], "symlink_target": "" }
''' Created on Oct 29, 2015 @author: ev0l ''' from handlers import BaseHandler class LogOutHandler(BaseHandler): def get(self): self.clear_all_cookies() self.redirect("/") route = [(r"/logout", LogOutHandler), ]
{ "content_hash": "14e4ffa0ace07a81b490d0f664ffb289", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 39, "avg_line_length": 16.857142857142858, "alnum_prop": 0.6440677966101694, "repo_name": "evolsnow/tornado-web", "id": "578961f695b1d3e728efe2fd01f3595bdcd4743c", "size": "236", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "handlers/logout.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3702" }, { "name": "HTML", "bytes": "7391" }, { "name": "JavaScript", "bytes": "3233" }, { "name": "Python", "bytes": "17326" } ], "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" xml:lang="en" lang="en"> <!-- Mirrored from bvs.wikidot.com/forum/t-1116880/just-a-piece by HTTrack Website Copier/3.x [XR&CO'2014], Sun, 10 Jul 2022 05:18:34 GMT --> <!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=utf-8" /><!-- /Added by HTTrack --> <head> <title>Just a Piece - Billy Vs. SNAKEMAN Wiki</title> <script type="text/javascript" src="http://d3g0gp89917ko0.cloudfront.net/v--291054f06006/common--javascript/init.combined.js"></script> <script type="text/javascript"> var URL_HOST = 'www.wikidot.com'; var URL_DOMAIN = 'wikidot.com'; var USE_SSL = true ; var URL_STATIC = 'http://d3g0gp89917ko0.cloudfront.net/v--291054f06006'; // global request information var WIKIREQUEST = {}; WIKIREQUEST.info = {}; WIKIREQUEST.info.domain = "bvs.wikidot.com"; WIKIREQUEST.info.siteId = 32011; WIKIREQUEST.info.siteUnixName = "bvs"; WIKIREQUEST.info.categoryId = 182512; WIKIREQUEST.info.themeId = 9564; WIKIREQUEST.info.requestPageName = "forum:thread"; OZONE.request.timestamp = 1657429525; OZONE.request.date = new Date(); WIKIREQUEST.info.lang = 'en'; WIKIREQUEST.info.pageUnixName = "forum:thread"; WIKIREQUEST.info.pageId = 2987325; WIKIREQUEST.info.lang = "en"; OZONE.lang = "en"; var isUAMobile = !!/Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); </script> <script type="text/javascript"> require.config({ baseUrl: URL_STATIC + '/common--javascript', paths: { 'jquery.ui': 'jquery-ui.min', 'jquery.form': 'jquery.form' } }); </script> <meta http-equiv="content-type" content="text/html;charset=UTF-8"/> <link rel="canonical" href="../../trophy_just-a-piece.html" /> <meta http-equiv="content-language" content="en"/> <script type="text/javascript" src="http://d3g0gp89917ko0.cloudfront.net/v--291054f06006/common--javascript/WIKIDOT.combined.js"></script> <style type="text/css" id="internal-style"> /* modules */ /* theme */ @import url(http://d3g0gp89917ko0.cloudfront.net/v--291054f06006/common--theme/base/css/style.css); @import url(http://bvs.wdfiles.com/local--theme/north/style.css); </style> <link rel="shortcut icon" href="../../local--favicon/favicon.gif"/> <link rel="icon" type="image/gif" href="../../local--favicon/favicon.gif"/> <link rel="apple-touch-icon" href="../../common--images/apple-touch-icon-57x57.png" /> <link rel="apple-touch-icon" sizes="72x72" href="../../common--images/apple-touch-icon-72x72.png" /> <link rel="apple-touch-icon" sizes="114x114" href="../../common--images/apple-touch-icon-114x114.png" /> <link rel="alternate" type="application/wiki" title="Edit this page" href="javascript:WIKIDOT.page.listeners.editClick()"/> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-18234656-1']); _gaq.push(['_setDomainName', 'none']); _gaq.push(['_setAllowLinker', true]); _gaq.push(['_trackPageview']); _gaq.push(['old._setAccount', 'UA-68540-5']); _gaq.push(['old._setDomainName', 'none']); _gaq.push(['old._setAllowLinker', true]); _gaq.push(['old._trackPageview']); _gaq.push(['userTracker._setAccount', 'UA-3581307-1']); _gaq.push(['userTracker._trackPageview']); </script> <script type="text/javascript"> window.google_analytics_uacct = 'UA-18234656-1'; window.google_analytics_domain_name = 'none'; </script> <link rel="manifest" href="../../onesignal/manifest.html" /> <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" acync=""></script> <script> var OneSignal = window.OneSignal || []; OneSignal.push(function() { OneSignal.init({ appId: null, }); }); </script> <link rel="alternate" type="application/rss+xml" title="Posts in the discussion thread &quot;Just a Piece&quot;" href="../../feed/forum/t-1116880.xml"/><script type="text/javascript" src="http://d3g0gp89917ko0.cloudfront.net/v--291054f06006/common--modules/js/forum/ForumViewThreadModule.js"></script> <script type="text/javascript" src="http://d3g0gp89917ko0.cloudfront.net/v--291054f06006/common--modules/js/forum/ForumViewThreadPostsModule.js"></script> </head> <body id="html-body"> <div id="skrollr-body"> <a name="page-top"></a> <div id="container-wrap-wrap"> <div id="container-wrap"> <div id="container"> <div id="header"> <h1><a href="../../index.html"><span>Billy Vs. SNAKEMAN Wiki</span></a></h1> <h2><span>Be the Ultimate Ninja.</span></h2> <!-- google_ad_section_start(weight=ignore) --> <div id="search-top-box" class="form-search"> <form id="search-top-box-form" action="http://bvs.wikidot.com/forum/t-1116880/dummy" class="input-append"> <input id="search-top-box-input" class="text empty search-query" type="text" size="15" name="query" value="Search this site" onfocus="if(YAHOO.util.Dom.hasClass(this, 'empty')){YAHOO.util.Dom.removeClass(this,'empty'); this.value='';}"/><input class="button btn" type="submit" name="search" value="Search"/> </form> </div> <div id="top-bar"> <ul> <li><a href="../../allies.html">Allies</a> <ul> <li><strong><a href="../../untabbed_allies.html">Allies Untabbed</a></strong></li> <li><a href="../../allies.html#toc7">Burger Ninja</a></li> <li><a href="../../allies.html#toc5">Reaper</a></li> <li><a href="../../allies.html#toc0">Regular</a></li> <li><a href="../../allies.html#toc8">R00t</a></li> <li><a href="../../allies.html#toc1">Season 2+</a></li> <li><a href="../../allies.html#toc2">Season 3+</a></li> <li><a href="../../allies.html#toc3">Season 4+</a></li> <li><a href="../../allies.html#toc4">The Trade</a></li> <li><a href="../../allies.html#toc6">Wasteland</a></li> <li><a href="../../allies.html#toc9">World Kaiju</a></li> <li><strong><a href="../../summons.html">Summons</a></strong></li> <li><strong><a href="../../teams.html">Teams</a></strong></li> </ul> </li> <li><a href="../../missions.html">Missions</a> <ul> <li><strong><a href="../../untabbed_missions.html">Missions Untabbed</a></strong></li> <li><strong><em><a href="../../missions.html#toc0">D-Rank</a></em></strong></li> <li><strong><em><a href="../../missions.html#toc1">C-Rank</a></em></strong></li> <li><strong><em><a href="../../missions.html#toc2">B-Rank</a></em></strong></li> <li><strong><em><a href="../../missions.html#toc3">A-Rank</a></em></strong></li> <li><strong><em><a href="../../missions.html#toc4">AA-Rank</a></em></strong></li> <li><strong><em><a href="../../missions.html#toc5">S-Rank</a></em></strong></li> <li><a href="../../missions.html#toc10">BurgerNinja</a></li> <li><a href="../../missions.html#toc14">Cave</a></li> <li><a href="../../missions.html#toc13">Jungle</a></li> <li><a href="../../missions.html#toc7">Monochrome</a></li> <li><a href="../../missions.html#toc8">Outskirts</a></li> <li><a href="../../missions.html#toc11">PizzaWitch</a></li> <li><a href="../../missions.html#toc6">Reaper</a></li> <li><a href="../../missions.html#toc9">Wasteland</a></li> <li><a href="../../missions.html#toc12">Witching Hour</a></li> <li><strong><em><a href="../../missions.html#toc14">Quests</a></em></strong></li> <li><a href="../../wota.html">Mission Lady Alley</a></li> </ul> </li> <li><a href="../../items.html">Items</a> <ul> <li><strong><a href="../../untabbed_items.html">Items Untabbed</a></strong></li> <li><a href="../../items.html#toc6">Ally Drops and Other</a></li> <li><a href="../../items.html#toc0">Permanent Items</a></li> <li><a href="../../items.html#toc1">Potions/Crafting Items</a> <ul> <li><a href="../../items.html#toc4">Crafting</a></li> <li><a href="../../items.html#toc3">Ingredients</a></li> <li><a href="../../items.html#toc2">Potions</a></li> </ul> </li> <li><a href="../../items.html#toc5">Wasteland Items</a></li> <li><a href="../../sponsored-items.html">Sponsored Items</a></li> </ul> </li> <li><a href="../../village.html">Village</a> <ul> <li><a href="../../billycon.html">BillyCon</a> <ul> <li><a href="../../billycon_billy-idol.html">Billy Idol</a></li> <li><a href="../../billycon_cosplay.html">Cosplay</a></li> <li><a href="../../billycon_dealer-s-room.html">Dealer's Room</a></li> <li><a href="../../billycon_events.html">Events</a></li> <li><a href="../../billycon_glowslinging.html">Glowslinging</a></li> <li><a href="../../billycon_rave.html">Rave</a></li> <li><a href="../../billycon_squee.html">Squee</a></li> <li><a href="../../billycon_video-game-tournament.html">Video Game Tournament</a></li> <li><a href="../../billycon_wander.html">Wander</a></li> </ul> </li> <li><a href="../../billytv.html">BillyTV</a></li> <li><a href="../../bingo-ing.html">Bingo'ing</a></li> <li><a href="../../candyween.html">Candyween</a></li> <li><a href="../../festival.html">Festival Day</a> <ul> <li><a href="../../festival_bargltron.html">Bargltron</a></li> <li><a href="../../festival_billymaze.html">BillyMaze</a></li> <li><a href="../../festival_dance-party.html">Dance Party</a></li> <li><a href="../../festival_elevensnax.html">ElevenSnax</a></li> <li><a href="../../festival_marksman.html">Marksman</a></li> <li><a href="../../festival_raffle.html">Raffle</a></li> <li><a href="../../festival_rngshack.html">RNGShack</a></li> <li><a href="../../festival_tsukiroll.html">TsukiRoll</a></li> <li><a href="../../festival_tunnel.html">Tunnel</a></li> </ul> </li> <li><a href="../../hidden-hoclaus.html">Hidden HoClaus</a></li> <li><a href="../../kaiju.html">Kaiju</a></li> <li><a href="../../marketplace.html">Marketplace</a></li> <li><a href="../../pizzawitch-garage.html">PizzaWitch Garage</a></li> <li><a href="../../robo-fighto.html">Robo Fighto</a></li> <li>R00t <ul> <li><a href="../../fields.html">Fields</a></li> <li><a href="../../keys.html">Keys</a></li> <li><a href="../../phases.html">Phases</a></li> </ul> </li> <li><a href="../../upgrade_science-facility.html#toc2">SCIENCE!</a></li> <li><a href="../../upgrades.html">Upgrades</a></li> <li><a href="../../zombjas.html">Zombjas</a></li> </ul> </li> <li><a href="../../misc_party-house.html">Party House</a> <ul> <li><a href="../../partyhouse_11dbhk-s-lottery.html">11DBHK's Lottery</a></li> <li><a href="../../partyhouse_akatsukiball.html">AkaTsukiBall</a></li> <li><a href="../../upgrade_claw-machines.html">Crane Game!</a></li> <li><a href="../../upgrade_darts-hall.html">Darts!</a></li> <li><a href="../../partyhouse_flower-wars.html">Flower Wars</a></li> <li><a href="../../upgrade_juice-bar.html">'Juice' Bar</a></li> <li><a href="../../partyhouse_mahjong.html">Mahjong</a></li> <li><a href="../../partyhouse_ninja-jackpot.html">Ninja Jackpot!</a></li> <li><a href="../../partyhouse_over-11-000.html">Over 11,000</a></li> <li><a href="../../partyhouse_pachinko.html">Pachinko</a></li> <li><a href="../../partyhouse_party-room.html">Party Room</a></li> <li><a href="../../partyhouse_pigeons.html">Pigeons</a></li> <li><a href="../../partyhouse_prize-wheel.html">Prize Wheel</a></li> <li><a href="../../partyhouse_roulette.html">Roulette</a></li> <li><a href="../../partyhouse_scratchy-tickets.html">Scratchy Tickets</a></li> <li><a href="../../partyhouse_snakeman.html">SNAKEMAN</a></li> <li><a href="../../partyhouse_superfail.html">SUPERFAIL</a></li> <li><a href="../../partyhouse_tip-line.html">Tip Line</a></li> <li><a href="../../partyhouse_the-big-board.html">The Big Board</a></li> <li><a href="../../partyhouse_the-first-loser.html">The First Loser</a></li> </ul> </li> <li><a href="../../guides.html">Guides</a> <ul> <li><a href="../../guide_billycon.html">BillyCon Guide</a></li> <li><a href="../../guide_burgerninja.html">BurgerNinja Guide</a></li> <li><a href="../../guide_candyween.html">Candyween Guide</a></li> <li><a href="../../guide_glossary.html">Glossary</a></li> <li><a href="../../guide_gs.html">Glowslinging Strategy Guide</a></li> <li><a href="../../guide_hq.html">Hero's Quest</a></li> <li><a href="../../guide_looping.html">Looping Guide</a></li> <li><a href="../../guide_monochrome.html">Monochrome Guide</a></li> <li><a href="../../overnight-bonuses.html">Overnight Bonuses</a></li> <li><a href="../../guide_pizzawitch.html">PizzaWitch Guide</a></li> <li><a href="../../tabbed_potions-crafting.html">Potions / Crafting</a> <ul> <li><a href="../../tabbed_potions-crafting.html#toc3">Crafting</a> <ul> <li><a href="../../tabbed_potions-crafting.html#toc4">Items</a></li> <li><a href="../../tabbed_potions-crafting.html#toc5">Materials</a></li> </ul> </li> <li><a href="../../tabbed_potions-crafting.html#toc0">Potion Mixing</a> <ul> <li><a href="../../tabbed_potions-crafting.html#toc2">Mixed Ingredients</a></li> <li><a href="../../tabbed_potions-crafting.html#toc1">Potions</a></li> </ul> </li> <li><a href="../../tabbed_potions-crafting.html#toc6">Reduction Laboratory</a> <ul> <li><a href="../../tabbed_potions-crafting.html#toc8">Potions and Ingredients</a></li> <li><a href="../../tabbed_potions-crafting.html#toc7">Wasteland Items</a></li> </ul> </li> </ul> </li> <li><a href="../../guide_impossible-mission.html">Impossible Mission Guide</a></li> <li><a href="../../guide_xp.html">Ranking Guide</a></li> <li><a href="../../guide_reaper.html">Reaper Guide</a></li> <li><a href="../../guide_rgg.html">Reaper's Game Guide</a></li> <li><a href="../../guide_r00t.html">R00t Guide</a></li> <li><a href="../../guide_speed-content.html">Speed Content Guide</a></li> <li><a href="../../guide_speedlooping.html">Speedlooping Guide</a></li> <li><a href="../../guide_thetrade.html">The Trade Guide</a></li> <li><a href="../../guide_wasteland.html">Wasteland Guide</a></li> </ul> </li> <li>Other <ul> <li><a href="../../arena.html">Arena</a></li> <li><a href="../../billy-club.html">Billy Club</a> <ul> <li><a href="../../boosters.html">Boosters</a></li> <li><a href="../../karma.html">Karma</a></li> </ul> </li> <li><a href="../../bloodline.html">Bloodlines</a></li> <li><a href="../../jutsu.html">Jutsu</a> <ul> <li><a href="../../jutsu.html#toc2">Bloodline Jutsu</a></li> <li><a href="../../jutsu.html#toc0">Regular Jutsu</a></li> <li><a href="../../jutsu.html#toc1">Special Jutsu</a></li> </ul> </li> <li><a href="../../mission-bonus.html">Mission Bonus</a></li> <li><a href="../../news-archive.html">News Archive</a></li> <li><a href="../../number-one.html">Number One</a></li> <li><a href="../../old-news-archive.html">Old News Archive</a></li> <li><a href="../../retail_perfect-poker.html">Perfect Poker Bosses</a></li> <li><a href="../../pets.html">Pets</a></li> <li><a href="../../retail.html">Retail</a></li> <li><a href="../../ryo.html">Ryo</a></li> <li><a href="../../spar.html">Spar With Friends</a></li> <li><a href="../../sponsored-items.html">Sponsored Items</a></li> <li><a href="../../store.html">Store</a></li> <li><a href="../../themes.html">Themes</a></li> <li><a href="../../trophies.html">Trophies</a></li> <li><a href="../../untabbed.html">Untabbed</a> <ul> <li><a href="../../untabbed_allies.html">Allies</a></li> <li><a href="../../untabbed_items.html">Items</a></li> <li><a href="../../untabbed_jutsu.html">Jutsu</a></li> <li><a href="../../untabbed_missions.html">Missions</a></li> <li><a href="../../untabbed_potions-crafting.html">Potions / Crafting</a></li> </ul> </li> <li><a href="../../world-kaiju.html">World Kaiju</a></li> </ul> </li> <li><a href="../../utilities.html">Utilities</a> <ul> <li><a href="http://www.cobaltknight.clanteam.com/awesomecalc.html">Awesome Calculator</a></li> <li><a href="http://timothydryke.byethost17.com/billy/itemchecker.php">Item Checker</a></li> <li><a href="../../utility_calculator.html">Mission Calculator</a></li> <li><a href="../../utility_r00t-calculator.html">R00t Calculator</a></li> <li><a href="../../utility_success-calculator.html">Success Calculator</a></li> <li><a href="../../templates.html">Templates</a></li> <li><a href="../../utility_chat.html">Wiki Chat Box</a></li> </ul> </li> </ul> </div> <div id="login-status"><a href="javascript:;" onclick="WIKIDOT.page.listeners.createAccount(event)" class="login-status-create-account btn">Create account</a> <span>or</span> <a href="javascript:;" onclick="WIKIDOT.page.listeners.loginClick(event)" class="login-status-sign-in btn btn-primary">Sign in</a> </div> <div id="header-extra-div-1"><span></span></div><div id="header-extra-div-2"><span></span></div><div id="header-extra-div-3"><span></span></div> </div> <div id="content-wrap"> <div id="side-bar"> <h3 ><span><a href="http://www.animecubed.com/billy/?57639" onclick="window.open(this.href, '_blank'); return false;">Play BvS Now!</a></span></h3> <ul> <li><a href="../../system_members.html">Site members</a></li> <li><a href="../../system_join.html">Wiki Membership</a></li> </ul> <hr /> <ul> <li><a href="../../forum_start.html">Forum Main</a></li> <li><a href="../../forum_recent-posts.html">Recent Posts</a></li> </ul> <hr /> <ul> <li><a href="../../system_recent-changes.html">Recent changes</a></li> <li><a href="../../system_list-all-pages.html">List all pages</a></li> <li><a href="../../system_page-tags-list.html">Page Tags</a></li> </ul> <hr /> <ul> <li><a href="../../players.html">Players</a></li> <li><a href="../../villages.html">Villages</a></li> <li><a href="../../other-resources.html">Other Resources</a></li> </ul> <hr /> <p style="text-align: center;"><span style="font-size:smaller;">Notice: Do not send bug reports based on the information on this site. If this site is not matching up with what you're experiencing in game, that is a problem with this site, not with the game.</span></p> </div> <!-- google_ad_section_end --> <div id="main-content"> <div id="action-area-top"></div> <div id="page-title"><a href="../../trophy_just-a-piece.html">Just a Piece</a> / Discussion</h1></div> <div id="page-content"> <div class="forum-thread-box "> <div class="forum-breadcrumbs"> <a href="../start.html">Forum</a> &raquo; <a href="../c-30019/per-page-discussions.html">Hidden / Per page discussions</a> &raquo; Just a Piece </div> <div class="description-block well"> <div class="statistics"> Started by: <span class="printuser">Wikidot</span><br/> Date: <span class="odate time_1424247837 format_%25e%20%25b%20%25Y%2C%20%25H%3A%25M%7Cagohover">18 Feb 2015 08:23</span><br/> Number of posts: 0<br/> <span class="rss-icon"><img src="http://www.wikidot.com/common--theme/base/images/feed/feed-icon-14x14.png" alt="rss icon"/></span> RSS: <a href="../../feed/forum/t-1116880.xml">New posts</a> </div> This is the discussion related to the wiki page <a href="../../trophy_just-a-piece.html">Just a Piece</a>. </div> <div class="options"> <a href="javascript:;" onclick="WIKIDOT.modules.ForumViewThreadModule.listeners.unfoldAll(event)" class="btn btn-default btn-small btn-sm">Unfold All</a> <a href="javascript:;" onclick="WIKIDOT.modules.ForumViewThreadModule.listeners.foldAll(event)" class="btn btn-default btn-small btn-sm">Fold All</a> <a href="javascript:;" id="thread-toggle-options" onclick="WIKIDOT.modules.ForumViewThreadModule.listeners.toggleThreadOptions(event)" class="btn btn-default btn-small btn-sm"><i class="icon-plus"></i> More Options</a> </div> <div id="thread-options-2" class="options" style="display: none"> <a href="javascript:;" onclick="WIKIDOT.modules.ForumViewThreadModule.listeners.editThreadBlock(event)" class="btn btn-default btn-small btn-sm">Lock Thread</a> <a href="javascript:;" onclick="WIKIDOT.modules.ForumViewThreadModule.listeners.moveThread(event)" class="btn btn-default btn-small btn-sm">Move Thread</a> </div> <div id="thread-action-area" class="action-area well" style="display: none"></div> <div id="thread-container" class="thread-container"> <div id="thread-container-posts" style="display: none"> </div> </div> <div class="new-post"> <a href="javascript:;" id="new-post-button" onclick="WIKIDOT.modules.ForumViewThreadModule.listeners.newPost(event,null)" class="btn btn-default">New Post</a> </div> <div style="display:none" id="post-options-template"> <a href="javascript:;" onclick="WIKIDOT.modules.ForumViewThreadModule.listeners.showPermalink(event,'%POST_ID%')" class="btn btn-default btn-small btn-sm">Permanent Link</a> <a href="javascript:;" onclick="WIKIDOT.modules.ForumViewThreadModule.listeners.editPost(event,'%POST_ID%')" class="btn btn-default btn-small btn-sm">Edit</a> <a href="javascript:;" onclick="WIKIDOT.modules.ForumViewThreadModule.listeners.deletePost(event,'%POST_ID%')"class="btn btn-danger btn-small btn-sm">Delete</a> </div> <div style="display:none" id="post-options-permalink-template">/forum/t-1116880/just-a-piece#post-</div> </div> <script type="text/javascript"> WIKIDOT.forumThreadId = 1116880; </script> </div> <div id="page-info-break"></div> <div id="page-options-container"> </div> <div id="action-area" style="display: none;"></div> </div> </div> <div id="footer" style="display: block; visibility: visible;"> <div class="options" style="display: block; visibility: visible;"> <a href="http://www.wikidot.com/doc" id="wikidot-help-button">Help</a> &nbsp;| <a href="http://www.wikidot.com/legal:terms-of-service" id="wikidot-tos-button">Terms of Service</a> &nbsp;| <a href="http://www.wikidot.com/legal:privacy-policy" id="wikidot-privacy-button">Privacy</a> &nbsp;| <a href="javascript:;" id="bug-report-button" onclick="WIKIDOT.page.listeners.pageBugReport(event)">Report a bug</a> &nbsp;| <a href="javascript:;" id="abuse-report-button" onclick="WIKIDOT.page.listeners.flagPageObjectionable(event)">Flag as objectionable</a> </div> Powered by <a href="http://www.wikidot.com/">Wikidot.com</a> </div> <div id="license-area" class="license-area"> Unless otherwise stated, the content of this page is licensed under <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-ShareAlike 3.0 License</a> </div> <div id="extrac-div-1"><span></span></div><div id="extrac-div-2"><span></span></div><div id="extrac-div-3"><span></span></div> </div> </div> <!-- These extra divs/spans may be used as catch-alls to add extra imagery. --> <div id="extra-div-1"><span></span></div><div id="extra-div-2"><span></span></div><div id="extra-div-3"><span></span></div> <div id="extra-div-4"><span></span></div><div id="extra-div-5"><span></span></div><div id="extra-div-6"><span></span></div> </div> </div> <div id="dummy-ondomready-block" style="display: none;" ></div> <!-- Google Analytics load --> <script type="text/javascript"> (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <!-- Quantcast --> <script type="text/javascript"> _qoptions={ qacct:"p-edL3gsnUjJzw-" }; (function() { var qc = document.createElement('script'); qc.type = 'text/javascript'; qc.async = true; qc.src = ('https:' == document.location.protocol ? 'https://secure' : 'http://edge') + '.quantserve.com/quant.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(qc, s); })(); </script> <noscript> <img src="http://pixel.quantserve.com/pixel/p-edL3gsnUjJzw-.gif" style="display: none;" border="0" height="1" width="1" alt="Quantcast"/> </noscript> <div id="page-options-bottom-tips" style="display: none;"> <div id="edit-button-hovertip"> Click here to edit contents of this page. </div> </div> <div id="page-options-bottom-2-tips" style="display: none;"> <div id="edit-sections-button-hovertip"> Click here to toggle editing of individual sections of the page (if possible). Watch headings for an &quot;edit&quot; link when available. </div> <div id="edit-append-button-hovertip"> Append content without editing the whole page source. </div> <div id="history-button-hovertip"> Check out how this page has evolved in the past. </div> <div id="discuss-button-hovertip"> If you want to discuss contents of this page - this is the easiest way to do it. </div> <div id="files-button-hovertip"> View and manage file attachments for this page. </div> <div id="site-tools-button-hovertip"> A few useful tools to manage this Site. </div> <div id="backlinks-button-hovertip"> See pages that link to and include this page. </div> <div id="rename-move-button-hovertip"> Change the name (also URL address, possibly the category) of the page. </div> <div id="view-source-button-hovertip"> View wiki source for this page without editing. </div> <div id="parent-page-button-hovertip"> View/set parent page (used for creating breadcrumbs and structured layout). </div> <div id="abuse-report-button-hovertip"> Notify administrators if there is objectionable content in this page. </div> <div id="bug-report-button-hovertip"> Something does not work as expected? Find out what you can do. </div> <div id="wikidot-help-button-hovertip"> General Wikidot.com documentation and help section. </div> <div id="wikidot-tos-button-hovertip"> Wikidot.com Terms of Service - what you can, what you should not etc. </div> <div id="wikidot-privacy-button-hovertip"> Wikidot.com Privacy Policy. </div> </div> </body> <!-- Mirrored from bvs.wikidot.com/forum/t-1116880/just-a-piece by HTTrack Website Copier/3.x [XR&CO'2014], Sun, 10 Jul 2022 05:18:34 GMT --> </html>
{ "content_hash": "1c76906727ad2dff8aca72bdae3fe9f2", "timestamp": "", "source": "github", "line_count": 637, "max_line_length": 328, "avg_line_length": 43.95918367346939, "alnum_prop": 0.5954931790586386, "repo_name": "tn5421/tn5421.github.io", "id": "330b3e9871adb7307a608663c1a8cf7931be8a59", "size": "28002", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "bvs.wikidot.com/forum/t-1116880/just-a-piece.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "400301089" } ], "symlink_target": "" }
<!doctype html public "-//w3c//dtd html 4.0 transitional//en"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="Generator" content="Microsoft Word 97"> <meta name="Template" content="C:\PROGRAM FILES\MICROSOFT OFFICE\OFFICE\html.dot"> <meta name="GENERATOR" content="Mozilla/4.7 [en] (Win98; I) [Netscape]"> <title>FFT</title> </head> <body text="#000000" bgcolor="#FDF5E6" link="#FF00FF" vlink="#800080" alink="#FF0000"> <a href="Algorithms.html">Algorithms Index</a> , <a href="FreqFiltering.html">Filtering in Triana</a> , <a href="FreqStoreModel.html">Triana Spectral Storage Model</a> <p> <hr WIDTH="95%" SIZE=4> <center> <p><b><font face="Arial"><font size=+1>FFT : Fast Fourier Transform Unit</font></font></b> <p> <LARGE><b><i><font face="Arial">Authors: Bernard Schutz, Ian Taylor</font></i></b> <p><b>Input Types :</b> <p><b><a href="../../../../help/JavaDoc/triana/types/VectorType.html">VectorType</a>, <a href="../../../../help/JavaDoc/triana/types/MatrixType.html">MatrixType</a></b> <p><b>Output Types :</b> <p><b><a href="../../../../help/JavaDoc/triana/types/SampleSet.html">SampleSet</a>, <a href="../../../../help/JavaDoc/triana/types/ComplexSpectrum.html">ComplexSpectrum</a></b>, <b><a href="../../../../help/JavaDoc/triana/types/ComplexSampleSet.html">ComplexSampleSet</a></b>, <b><a href="../../../../help/JavaDoc/triana/types/Spectrum.html">Spectrum</a>, <a href="../../../../help/JavaDoc/triana/types/Spectrum2D.html">Spectrum2D</a></b> <p><b>Date : 09<sup>th</sup> March 2001</b> <p></LARGE> </center> <p> <hr WIDTH="95%" SIZE=4> <h2> <a NAME="contents"></a>Contents</h2> <ul> <li> <a href="#description">Description of FFT</a></li> <li> <a href="#using">Using FFT</a></li> <li> See also: <a href="FreqFiltering.html">Filtering in Triana</a> , <a href="FreqStoreModel.html">Triana Spectral Storage Model</a></li> </ul> <hr WIDTH="15%" SIZE=4> <h2> <a NAME="description"></a>Description of FFT</h2> The FFT is a unit which performs a fast Fourier transform (i.e. an FFT) or its inverse on one-dimensional or two-dimensional data sets. This is an efficient way to perform the discrete Fourier transform of the data. The FFT implemented here can handle input data sets of any length, although it will work most efficiently if the prime factors of the input number are all small. The input can be any (1D) VectorType or (2D) MatrixType. If the input has signal information, this is used in creating the output, as described in what follows. To understand the properties of spectral data sets, such as being one-sided, see <a href="../../../../help/JavaDoc/triana/types/ComplexSpectrum.html">ComplexSpectrum</a> or <a href="../../../../help/JavaDoc/triana/types/Spectrum.html">Spectrum</a>. <p>If the user chooses <b>automatic</b> operation in the user interface window, and if the input is a <a href="../../../../help/JavaDoc/triana/types/Signal.html">Signal</a> or <a href="../../../../help/JavaDoc/triana/types/Spectral.html">Spectral</a> data type, then the unit automatically performs the correct type of transform.&nbsp; Therefore, two successive applications of the FFT unit, starting with either a SampleSet or a ComplexSpectrum, will produce a final output identical to the original input, to within roundoff error. Here is how the unit makes its choices: <p>If the input is a <a href="../../../../help/JavaDoc/triana/types/Spectral.html">Spectral</a> data type, FFT performs the direct FFT. The output data type is a Spectrum or ComplexSpectrum. A normalization is applied to ensure that the FFT output is a sampled representation of the continuous Fourier transform X(f) of the function of time x(t) represented by the input set, according to the following equation <p>X(f) = integral[ x(t) exp( -2 Pi i f t )] dt. <p>This transfroms the input signal from a time representation to a frequency one. The output data is a one-sided representation of the spectrum (negative frequencies are not stored) if the input is a SampleSet.&nbsp; The output is normally a ComplexSpectrum, but if the input is a ComplexSampleSet with sufficient symmetry, the output will be a real Spectrum. For display or further work, the ComplexSpectrum can then be transformed into an <a href="../../triana/doc/help/tools/AmpSpect.html">amplitude </a>spectrum or a <a href="../../triana/doc/help/tools/PwrSpect.html">power </a>spectrum. <p>If the input is a <a href="../../../../help/JavaDoc/triana/types/Spectrum.html">Spectrum</a> or a <a href="../../../../help/JavaDoc/triana/types/ComplexSpectrum.html">ComplexSpectrum</a>, the unit performs the inverse FFT.&nbsp; The output data type is a <a href="../../../../help/JavaDoc/triana/types/SampleSet.html">SampleSet</a> or a <a href="../../../../help/JavaDoc/triana/types/ComplexSampleSet.html">ComplexSampleSet</a>, depending on whether the input set is one-sided or two-sided and what symmetry it has. A normalization factor ensures that the inverse FFT output is a sampled representation of the continuous data set x(t) represented by the following continuous transform of the input set X(f): <p>x(t) = (1/ 2 Pi ) integral[ X(f) exp( 2 Pi i f t )] df. <p>This transforms the input spectrum back to the time domain. <p>If the user chooses <b>direct</b> or <b>inverse</b> operation, then the unit ignores the type of the input data set and performs the requested operation. It applies <b>normalizing factors</b> (1/N) if the appropriate factor is chosen. <p>For some purposes, a windowing function should be applied to data <i>before</i> it is transformed. The user interface gives a choice of some standard windows. The choices are Bartlett, Blackman, Gaussian, Hamming, Hanning, and Welch. These are described in the help file for <a href="WindowFnc.html">WindowFnc</a>. <p>For convenience, the user has an option to maximize speed of the transform in the 1D case, or to minimize storage. The minimum storage option produces a one-sided output, while the maximum speed option produces a two-sided output. <p>For efficient operation, it is best that the input length should be a power of 2. The unit allows the user to choose that the input is padded to the nearest larger power of two. <p> <hr WIDTH="15%" SIZE=4> <h2> <a NAME="using"></a>Using FFT</h2> <center> <p><br><img SRC="image82Q.JPG" height=179 width=370></center> <p>The FFT's parameter window allows the user to choose the type of operation of the transform. There are 5 modes : Automatic, Direct, Direct/normalizated(1/N), inverse or inverse/normalized(1/N). For one-dimensional data sets there are three further options. One is to optimize the speed of the calculation or the storage space of the result. A second option allows the user to specify the windowing function required (if any). The third is a choice of whether the unit should automatically pad out with zero's to the right when applying the FFT. <p> <hr WIDTH="95%" SIZE=4> </body> </html>
{ "content_hash": "14bbce10ce2b7f096015e3d0bb12db59", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 128, "avg_line_length": 48.76973684210526, "alnum_prop": 0.6813705652232565, "repo_name": "CSCSI/Triana", "id": "3ef468b1f490a452c4a0c31b199cb252480c23a6", "size": "7413", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "triana-toolboxes/signalproc/help/algorithms/FFT.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "35699" }, { "name": "CSS", "bytes": "13201" }, { "name": "Java", "bytes": "10215563" }, { "name": "JavaScript", "bytes": "10926" }, { "name": "Shell", "bytes": "1610" } ], "symlink_target": "" }
package org.elasticsearch.cluster; import org.elasticsearch.Version; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.common.component.Lifecycle; import org.elasticsearch.common.component.LifecycleListener; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.BoundTransportAddress; import org.elasticsearch.common.transport.LocalTransportAddress; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.util.concurrent.ConcurrentCollections; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.ConnectTransportException; import org.elasticsearch.transport.Transport; import org.elasticsearch.transport.TransportException; import org.elasticsearch.transport.TransportRequest; import org.elasticsearch.transport.TransportRequestOptions; import org.elasticsearch.transport.TransportService; import org.elasticsearch.transport.TransportServiceAdapter; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import static org.hamcrest.Matchers.equalTo; public class NodeConnectionsServiceTests extends ESTestCase { private static ThreadPool THREAD_POOL; private MockTransport transport; private TransportService transportService; private List<DiscoveryNode> generateNodes() { List<DiscoveryNode> nodes = new ArrayList<>(); for (int i = randomIntBetween(20, 50); i > 0; i--) { Set<DiscoveryNode.Role> roles = new HashSet<>(randomSubsetOf(Arrays.asList(DiscoveryNode.Role.values()))); nodes.add(new DiscoveryNode("node_" + i, "" + i, LocalTransportAddress.buildUnique(), Collections.emptyMap(), roles, Version.CURRENT)); } return nodes; } private ClusterState clusterStateFromNodes(List<DiscoveryNode> nodes) { final DiscoveryNodes.Builder builder = DiscoveryNodes.builder(); for (DiscoveryNode node : nodes) { builder.add(node); } return ClusterState.builder(new ClusterName("test")).nodes(builder).build(); } public void testConnectAndDisconnect() { List<DiscoveryNode> nodes = generateNodes(); NodeConnectionsService service = new NodeConnectionsService(Settings.EMPTY, THREAD_POOL, transportService); ClusterState current = clusterStateFromNodes(Collections.emptyList()); ClusterChangedEvent event = new ClusterChangedEvent("test", clusterStateFromNodes(randomSubsetOf(nodes)), current); service.connectToAddedNodes(event); assertConnected(event.nodesDelta().addedNodes()); service.disconnectFromRemovedNodes(event); assertConnectedExactlyToNodes(event.state()); current = event.state(); event = new ClusterChangedEvent("test", clusterStateFromNodes(randomSubsetOf(nodes)), current); service.connectToAddedNodes(event); assertConnected(event.nodesDelta().addedNodes()); service.disconnectFromRemovedNodes(event); assertConnectedExactlyToNodes(event.state()); } public void testReconnect() { List<DiscoveryNode> nodes = generateNodes(); NodeConnectionsService service = new NodeConnectionsService(Settings.EMPTY, THREAD_POOL, transportService); ClusterState current = clusterStateFromNodes(Collections.emptyList()); ClusterChangedEvent event = new ClusterChangedEvent("test", clusterStateFromNodes(randomSubsetOf(nodes)), current); transport.randomConnectionExceptions = true; service.connectToAddedNodes(event); for (int i = 0; i < 3; i++) { // simulate disconnects for (DiscoveryNode node : randomSubsetOf(nodes)) { transport.disconnectFromNode(node); } service.new ConnectionChecker().run(); } // disable exceptions so things can be restored transport.randomConnectionExceptions = false; service.new ConnectionChecker().run(); assertConnectedExactlyToNodes(event.state()); } private void assertConnectedExactlyToNodes(ClusterState state) { assertConnected(state.nodes()); assertThat(transport.connectedNodes.size(), equalTo(state.nodes().getSize())); } private void assertConnected(Iterable<DiscoveryNode> nodes) { for (DiscoveryNode node : nodes) { assertTrue("not connected to " + node, transport.connectedNodes.contains(node)); } } private void assertNotConnected(Iterable<DiscoveryNode> nodes) { for (DiscoveryNode node : nodes) { assertFalse("still connected to " + node, transport.connectedNodes.contains(node)); } } @Override @Before public void setUp() throws Exception { super.setUp(); this.transport = new MockTransport(); transportService = new TransportService(Settings.EMPTY, transport, THREAD_POOL, TransportService.NOOP_TRANSPORT_INTERCEPTOR); transportService.start(); transportService.acceptIncomingRequests(); } @Override @After public void tearDown() throws Exception { transportService.stop(); super.tearDown(); } @AfterClass public static void stopThreadPool() { ThreadPool.terminate(THREAD_POOL, 30, TimeUnit.SECONDS); THREAD_POOL = null; } final class MockTransport implements Transport { Set<DiscoveryNode> connectedNodes = ConcurrentCollections.newConcurrentSet(); volatile boolean randomConnectionExceptions = false; @Override public void transportServiceAdapter(TransportServiceAdapter service) { } @Override public BoundTransportAddress boundAddress() { return null; } @Override public Map<String, BoundTransportAddress> profileBoundAddresses() { return null; } @Override public TransportAddress[] addressesFromString(String address, int perAddressLimit) throws Exception { return new TransportAddress[0]; } @Override public boolean addressSupported(Class<? extends TransportAddress> address) { return false; } @Override public boolean nodeConnected(DiscoveryNode node) { return connectedNodes.contains(node); } @Override public void connectToNode(DiscoveryNode node) throws ConnectTransportException { if (connectedNodes.contains(node) == false && randomConnectionExceptions && randomBoolean()) { throw new ConnectTransportException(node, "simulated"); } connectedNodes.add(node); } @Override public void connectToNodeLight(DiscoveryNode node) throws ConnectTransportException { } @Override public void disconnectFromNode(DiscoveryNode node) { connectedNodes.remove(node); } @Override public void sendRequest(DiscoveryNode node, long requestId, String action, TransportRequest request, TransportRequestOptions options) throws IOException, TransportException { } @Override public long serverOpen() { return 0; } @Override public List<String> getLocalAddresses() { return null; } @Override public Lifecycle.State lifecycleState() { return null; } @Override public void addLifecycleListener(LifecycleListener listener) { } @Override public void removeLifecycleListener(LifecycleListener listener) { } @Override public void start() {} @Override public void stop() {} @Override public void close() {} } }
{ "content_hash": "7a596c2368c5bf5a8c89345365853ec9", "timestamp": "", "source": "github", "line_count": 247, "max_line_length": 133, "avg_line_length": 33.412955465587046, "alnum_prop": 0.6854477159820671, "repo_name": "dongjoon-hyun/elasticsearch", "id": "5bf2bc38c3e9663f73e119a6c4a7454295068f92", "size": "9041", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "core/src/test/java/org/elasticsearch/cluster/NodeConnectionsServiceTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "10561" }, { "name": "Batchfile", "bytes": "13128" }, { "name": "Emacs Lisp", "bytes": "3341" }, { "name": "FreeMarker", "bytes": "45" }, { "name": "Groovy", "bytes": "268616" }, { "name": "HTML", "bytes": "3397" }, { "name": "Java", "bytes": "38526900" }, { "name": "Perl", "bytes": "7271" }, { "name": "Python", "bytes": "78203" }, { "name": "Shell", "bytes": "105126" } ], "symlink_target": "" }
<?php namespace Magento\Paypal\Test\Unit\Helper; use Magento\Config\Model\Config; use Magento\Config\Model\Config\ScopeDefiner; use Magento\Directory\Helper\Data; use Magento\Framework\App\Helper\Context; use Magento\Paypal\Helper\Backend; use Magento\Paypal\Model\Config\StructurePlugin; class BackendTest extends \PHPUnit_Framework_TestCase { const SCOPE = 'website'; const SCOPE_ID = 1; /** * @var Context|\PHPUnit_Framework_MockObject_MockObject */ private $context; /** * @var \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject */ private $request; /** * @var Data|\PHPUnit_Framework_MockObject_MockObject */ private $directoryHelperMock; /** * @var Config|\PHPUnit_Framework_MockObject_MockObject */ private $backendConfig; /** * @var ScopeDefiner|\PHPUnit_Framework_MockObject_MockObject */ private $scopeDefiner; /** * @var Backend */ private $helper; protected function setUp() { $this->context = $this->getMockBuilder('Magento\Framework\App\Helper\Context') ->disableOriginalConstructor() ->getMock(); $this->request = $this->getMock('Magento\Framework\App\RequestInterface'); $this->context->expects(static::once()) ->method('getRequest') ->willReturn($this->request); $this->directoryHelperMock = $this->getMockBuilder('Magento\Directory\Helper\Data') ->disableOriginalConstructor() ->getMock(); $this->backendConfig = $this->getMockBuilder('Magento\Config\Model\Config') ->disableOriginalConstructor() ->getMock(); $this->scopeDefiner = $this->getMockBuilder('Magento\Config\Model\Config\ScopeDefiner') ->disableOriginalConstructor() ->getMock(); $this->helper = new Backend( $this->context, $this->directoryHelperMock, $this->backendConfig, $this->scopeDefiner ); } public function testGetConfigurationCountryCodeFromRequest() { $this->configurationCountryCodePrepareRequest('US'); $this->configurationCountryCodeAssertResult('US'); } /** * @param string|null $request * @dataProvider getConfigurationCountryCodeFromConfigDataProvider */ public function testGetConfigurationCountryCodeFromConfig($request) { $this->configurationCountryCodePrepareRequest($request); $this->configurationCountryCodePrepareConfig('GB'); $this->configurationCountryCodeAssertResult('GB'); } public function getConfigurationCountryCodeFromConfigDataProvider() { return [ [null], ['not country code'], ]; } /** * @param string|null $request * @param string|null|false $config * @param string|null $default * @dataProvider getConfigurationCountryCodeFromDefaultDataProvider */ public function testGetConfigurationCountryCodeFromDefault($request, $config, $default) { $this->configurationCountryCodePrepareRequest($request); $this->configurationCountryCodePrepareConfig($config); $this->directoryHelperMock->expects($this->once()) ->method('getDefaultCountry') ->will($this->returnValue($default)); $this->configurationCountryCodeAssertResult($default); } public function getConfigurationCountryCodeFromDefaultDataProvider() { return [ [null, false, 'DE'], ['not country code', false, 'DE'], ['not country code', '', 'any final result'] ]; } /** * Prepare request for test * * @param string|null $request */ private function configurationCountryCodePrepareRequest($request) { $this->request->expects($this->atLeastOnce()) ->method('getParam') ->willReturnMap( [ [StructurePlugin::REQUEST_PARAM_COUNTRY, null, $request], [self::SCOPE, null, self::SCOPE_ID] ] ); } /** * Prepare backend config for test * * @param string|null|false $config */ private function configurationCountryCodePrepareConfig($config) { $this->scopeDefiner->expects($this->once()) ->method('getScope') ->willReturn(self::SCOPE); $this->backendConfig->expects($this->once()) ->method('setData') ->with(self::SCOPE, self::SCOPE_ID); $this->backendConfig->expects($this->once()) ->method('getConfigDataValue') ->with(\Magento\Paypal\Block\Adminhtml\System\Config\Field\Country::FIELD_CONFIG_PATH) ->willReturn($config); } /** * Assert result of getConfigurationCountryCode method * * @param string $expected */ private function configurationCountryCodeAssertResult($expected) { $this->assertEquals($expected, $this->helper->getConfigurationCountryCode()); } }
{ "content_hash": "0c1eea8f73abff618dffd923e9f6fd72", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 98, "avg_line_length": 29.85549132947977, "alnum_prop": 0.6180058083252662, "repo_name": "j-froehlich/magento2_wk", "id": "f8a580a45a10e69105035526b0da74719caf4448", "size": "5273", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/magento/module-paypal/Test/Unit/Helper/BackendTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "13636" }, { "name": "CSS", "bytes": "2076720" }, { "name": "HTML", "bytes": "6151072" }, { "name": "JavaScript", "bytes": "2488727" }, { "name": "PHP", "bytes": "12466046" }, { "name": "Shell", "bytes": "6088" }, { "name": "XSLT", "bytes": "19979" } ], "symlink_target": "" }
$ETHGOPATH/go-ethereum/build/bin/geth attach
{ "content_hash": "535770faebc297d8a0c6bc843cdf0980", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 44, "avg_line_length": 15.666666666666666, "alnum_prop": 0.7872340425531915, "repo_name": "zekaf/eth-go-sh", "id": "ca24ae5d2f526d03d8d040defb075c00ddd8db42", "size": "96", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "eth-scripts/console_go-ethereum.sh", "mode": "33261", "license": "mit", "language": [ { "name": "Shell", "bytes": "23559" } ], "symlink_target": "" }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_AMOUNT_H #define BITCOIN_AMOUNT_H #include <serialize.h> #include <stdint.h> #include <string> /** Amount in satoshis (Can be negative) */ typedef int64_t CAmount; static const CAmount COIN = 100000000; static const CAmount CENT = 1000000; static const CAmount MIN_TX_FEE = 100; static const CAmount MIN_TXOUT_AMOUNT = 1; static const CAmount MAX_MINT_PROOF_OF_WORK = 9999 * COIN; static const std::string CURRENCY_UNIT = "GCH"; static const CAmount MAX_MONEY = 92233720368 * COIN; inline bool MoneyRange(const CAmount& nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); } class CFeeRate { private: CAmount nSatoshisPerK; // unit is satoshis-per-1,000-bytes public: CFeeRate() : nSatoshisPerK(0) {} explicit CFeeRate(const CAmount& _nSatoshisPerK) : nSatoshisPerK(_nSatoshisPerK) {} CFeeRate(const CAmount& nFeePaid, size_t nSize); CFeeRate(const CFeeRate& other) { nSatoshisPerK = other.nSatoshisPerK; } CAmount GetFee(size_t size) const; // unit returned is satoshis CAmount GetFeePerK() const { return GetFee(1000); } // satoshis-per-1000-bytes friend bool operator<(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK < b.nSatoshisPerK; } friend bool operator>(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK > b.nSatoshisPerK; } friend bool operator==(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK == b.nSatoshisPerK; } friend bool operator<=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK <= b.nSatoshisPerK; } friend bool operator>=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK >= b.nSatoshisPerK; } std::string ToString() const; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(nSatoshisPerK); } }; #endif // BITCOIN_AMOUNT_H
{ "content_hash": "bab831ae39e42652b908dbb1d00b416b", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 111, "avg_line_length": 39.49090909090909, "alnum_prop": 0.7173112338858195, "repo_name": "galaxycash/galaxycash", "id": "d576e6a0897f4ff6444afec1a152262bd6bf7bee", "size": "2172", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/amount.h", "mode": "33261", "license": "mit", "language": [ { "name": "Assembly", "bytes": "28453" }, { "name": "C", "bytes": "979081" }, { "name": "C++", "bytes": "7789333" }, { "name": "HTML", "bytes": "20970" }, { "name": "Java", "bytes": "30291" }, { "name": "M4", "bytes": "194790" }, { "name": "Makefile", "bytes": "113826" }, { "name": "Objective-C", "bytes": "3274" }, { "name": "Objective-C++", "bytes": "6766" }, { "name": "Python", "bytes": "198483" }, { "name": "QMake", "bytes": "759" }, { "name": "Roff", "bytes": "24267" }, { "name": "Ruby", "bytes": "1036" }, { "name": "Shell", "bytes": "79150" } ], "symlink_target": "" }
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "optionsdialog.h" #include "ui_optionsdialog.h" #include "bitcoinunits.h" #include "monitoreddatamapper.h" #include "netbase.h" #include "optionsmodel.h" #include <QDir> #include <QIntValidator> #include <QLocale> #include <QMessageBox> OptionsDialog::OptionsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::OptionsDialog), model(0), mapper(0), fRestartWarningDisplayed_Proxy(false), fRestartWarningDisplayed_Lang(false), fProxyIpValid(true) { ui->setupUi(this); /* Network elements init */ #ifndef USE_UPNP ui->mapPortUpnp->setEnabled(false); #endif ui->proxyIp->setEnabled(false); ui->proxyPort->setEnabled(false); ui->proxyPort->setValidator(new QIntValidator(1, 65535, this)); ui->socksVersion->setEnabled(false); ui->socksVersion->addItem("5", 5); ui->socksVersion->addItem("4", 4); ui->socksVersion->setCurrentIndex(0); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy())); ui->proxyIp->installEventFilter(this); /* Window elements init */ #ifdef Q_OS_MAC /* remove Window tab on Mac */ ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow)); #endif /* Display elements init */ QDir translations(":translations"); ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant("")); foreach(const QString &langStr, translations.entryList()) { QLocale locale(langStr); /** check if the locale name consists of 2 parts (language_country) */ if(langStr.contains("_")) { #if QT_VERSION >= 0x040800 /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } else { #if QT_VERSION >= 0x040800 /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language (locale name)", e.g. "German (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } } ui->unit->setModel(new BitcoinUnits(this)); /* Widget-to-option mapper */ mapper = new MonitoredDataMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); /* enable apply button when data modified */ connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton())); /* disable apply button when new data loaded */ connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton())); /* setup/change UI elements when proxy IP is invalid/valid */ connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool))); } OptionsDialog::~OptionsDialog() { delete ui; } void OptionsDialog::setModel(OptionsModel *model) { this->model = model; if(model) { connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); mapper->setModel(model); setMapper(); mapper->toFirst(); } /* update the display unit, to not use the default ("SPD") */ updateDisplayUnit(); /* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */ connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang())); /* disable apply button after settings are loaded as there is nothing to save */ disableApplyButton(); } void OptionsDialog::setMapper() { /* Main */ mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup); /* Wallet */ mapper->addMapping(ui->transactionFee, OptionsModel::Fee); mapper->addMapping(ui->spendZeroConfChange, OptionsModel::SpendZeroConfChange); /* Network */ mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP); mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse); mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP); mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort); mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion); /* Window */ #ifndef Q_OS_MAC mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray); mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose); #endif /* Display */ mapper->addMapping(ui->lang, OptionsModel::Language); mapper->addMapping(ui->unit, OptionsModel::DisplayUnit); mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses); mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures); } void OptionsDialog::enableApplyButton() { ui->applyButton->setEnabled(true); } void OptionsDialog::disableApplyButton() { ui->applyButton->setEnabled(false); } void OptionsDialog::enableSaveButtons() { /* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */ if(fProxyIpValid) setSaveButtonState(true); } void OptionsDialog::disableSaveButtons() { setSaveButtonState(false); } void OptionsDialog::setSaveButtonState(bool fState) { ui->applyButton->setEnabled(fState); ui->okButton->setEnabled(fState); } void OptionsDialog::on_resetButton_clicked() { if(model) { // confirmation dialog QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm options reset"), tr("Some settings may require a client restart to take effect.") + "<br><br>" + tr("Do you want to proceed?"), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if(btnRetVal == QMessageBox::Cancel) return; disableApplyButton(); /* disable restart warning messages display */ fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = true; /* reset all options and save the default values (QSettings) */ model->Reset(); mapper->toFirst(); mapper->submit(); /* re-enable restart warning messages display */ fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = false; } } void OptionsDialog::on_okButton_clicked() { mapper->submit(); accept(); } void OptionsDialog::on_cancelButton_clicked() { reject(); } void OptionsDialog::on_applyButton_clicked() { mapper->submit(); disableApplyButton(); } void OptionsDialog::showRestartWarning_Proxy() { if(!fRestartWarningDisplayed_Proxy) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Speedcoin."), QMessageBox::Ok); fRestartWarningDisplayed_Proxy = true; } } void OptionsDialog::showRestartWarning_Lang() { if(!fRestartWarningDisplayed_Lang) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Speedcoin."), QMessageBox::Ok); fRestartWarningDisplayed_Lang = true; } } void OptionsDialog::updateDisplayUnit() { if(model) { /* Update transactionFee with the current unit */ ui->transactionFee->setDisplayUnit(model->getDisplayUnit()); } } void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState) { // this is used in a check before re-enabling the save buttons fProxyIpValid = fState; if(fProxyIpValid) { enableSaveButtons(); ui->statusLabel->clear(); } else { disableSaveButtons(); object->setValid(fProxyIpValid); ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied proxy address is invalid.")); } } bool OptionsDialog::eventFilter(QObject *object, QEvent *event) { if(event->type() == QEvent::FocusOut) { if(object == ui->proxyIp) { CService addr; /* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */ emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr)); } } return QDialog::eventFilter(object, event); }
{ "content_hash": "b4318d6ec9f06c6a683c42c19e4dd872", "timestamp": "", "source": "github", "line_count": 289, "max_line_length": 198, "avg_line_length": 32.30449826989619, "alnum_prop": 0.6724507283633248, "repo_name": "spdcoin/Speedcoin", "id": "42ad593aab25410481dd41fabf1b510bcceb1a8b", "size": "9336", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qt/optionsdialog.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "32412" }, { "name": "C++", "bytes": "2616700" }, { "name": "CSS", "bytes": "1127" }, { "name": "HTML", "bytes": "50615" }, { "name": "Makefile", "bytes": "13723" }, { "name": "NSIS", "bytes": "6503" }, { "name": "Objective-C", "bytes": "1052" }, { "name": "Objective-C++", "bytes": "5864" }, { "name": "Python", "bytes": "69723" }, { "name": "QMake", "bytes": "15502" }, { "name": "Roff", "bytes": "18420" }, { "name": "Shell", "bytes": "16485" } ], "symlink_target": "" }
class Program { void CookieDefault() { var cookie = new System.Web.HttpCookie("cookieName"); // BAD: requireSSL is set to false by default } void CookieDirectTrue() { var cookie = new System.Web.HttpCookie("cookieName"); cookie.Secure = true; // GOOD } void CookieDirectTrueInitializer() { var cookie = new System.Web.HttpCookie("cookieName") { Secure = true }; // GOOD } void CookieIntermediateTrue() { var cookie = new System.Web.HttpCookie("cookieName"); bool v = true; cookie.Secure = v; // GOOD: should track local data flow } void CookieIntermediateTrueInitializer() { bool v = true; var cookie = new System.Web.HttpCookie("cookieName") { Secure = v }; // GOOD: should track local data flow } }
{ "content_hash": "bf267534bdc060030bb0a343a9d8ca74", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 114, "avg_line_length": 27.032258064516128, "alnum_prop": 0.6085918854415274, "repo_name": "github/codeql", "id": "00922eb2bd419aa71eb77cec1c34df91fb4dce8e", "size": "962", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "csharp/ql/test/experimental/Security Features/CWE-614/RequireSSLSystemWeb/ConfigEmpty/Program.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "3739" }, { "name": "Batchfile", "bytes": "3534" }, { "name": "C", "bytes": "410440" }, { "name": "C#", "bytes": "21146000" }, { "name": "C++", "bytes": "1352639" }, { "name": "CMake", "bytes": "1809" }, { "name": "CodeQL", "bytes": "32583145" }, { "name": "Dockerfile", "bytes": "496" }, { "name": "EJS", "bytes": "1478" }, { "name": "Emacs Lisp", "bytes": "3445" }, { "name": "Go", "bytes": "697562" }, { "name": "HTML", "bytes": "58008" }, { "name": "Handlebars", "bytes": "1000" }, { "name": "Java", "bytes": "5417683" }, { "name": "JavaScript", "bytes": "2432320" }, { "name": "Kotlin", "bytes": "12163740" }, { "name": "Lua", "bytes": "13113" }, { "name": "Makefile", "bytes": "8631" }, { "name": "Mustache", "bytes": "17025" }, { "name": "Nunjucks", "bytes": "923" }, { "name": "Perl", "bytes": "1941" }, { "name": "PowerShell", "bytes": "1295" }, { "name": "Python", "bytes": "1649035" }, { "name": "RAML", "bytes": "2825" }, { "name": "Ruby", "bytes": "299268" }, { "name": "Rust", "bytes": "234024" }, { "name": "Shell", "bytes": "23973" }, { "name": "Smalltalk", "bytes": "23" }, { "name": "Starlark", "bytes": "27062" }, { "name": "Swift", "bytes": "204309" }, { "name": "Thrift", "bytes": "3020" }, { "name": "TypeScript", "bytes": "219623" }, { "name": "Vim Script", "bytes": "1949" }, { "name": "Vue", "bytes": "2881" } ], "symlink_target": "" }
Number.prototype.round = function(precision) { var factor = Math.pow(10, precision || 0); return Math.round(this * factor) / factor; }; Number.prototype.to_kilometers = function() { return this / 1000.0; }; Number.prototype.to_kilometers_per_hour = function() { return this / 1000.0 * 3600.0; }; Number.prototype.to_feet = function() { return this / 0.3048; }; Number.prototype.to_miles = function() { return this / 1609.344; }; Number.prototype.to_miles_per_hour = function() { return this / 1609.344 * 3600.0; };
{ "content_hash": "db6a11afdfb139f3068c1f952a1e946b", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 54, "avg_line_length": 22.25, "alnum_prop": 0.6704119850187266, "repo_name": "sudhirsb2003/tracklog", "id": "80bef3c48fc541e7bffbe63763bd054da3c571bb", "size": "534", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/assets/javascripts/tracklog/core_ext.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "23693" }, { "name": "JavaScript", "bytes": "82796" }, { "name": "Ruby", "bytes": "74043" } ], "symlink_target": "" }
require 'set' require 'active_support/inflector' require 'sinatra/base' require 'sinatra/namespace' require 'sinja/helpers/nested' require 'sinja/helpers/relationships' require 'sinja/relationship_routes/has_many' require 'sinja/relationship_routes/has_one' require 'sinja/resource_routes' module Sinja module Resource ARITIES = { :create=>2, :index=>-1, :fetch=>-1, :show_many=>-1 }.tap { |h| h.default = 1 }.freeze def self.registered(app) app.helpers Helpers::Relationships do attr_accessor :resource end app.register ResourceRoutes end def def_action_helper(context, action, allow_opts=[]) abort "Action helper names can't overlap with Sinatra DSL" \ if Sinatra::Base.respond_to?(action) context.define_singleton_method(action) do |**opts, &block| abort "Unexpected option(s) for `#{action}' action helper" \ unless (opts.keys - Array(allow_opts)).empty? resource_config[action].each do |k, v| v.replace(Array(opts[k])) if opts.key?(k) end return unless block ||= case !method_defined?(action) && action when :show proc { resource } if method_defined?(:find) end required_arity = ARITIES[action] define_method(action) do |*args| raise ArgumentError, "Unexpected argument(s) for `#{action}' action helper" \ unless args.length == block.arity public_send("before_#{action}", *args.take(method("before_#{action}").arity.abs)) \ if respond_to?("before_#{action}") case result = instance_exec(*args, &block) when Array opts = {} if result.last.instance_of?(Hash) opts = result.pop elsif required_arity < 0 && !result.first.is_a?(Array) result = [result] end raise ActionHelperError, "Unexpected return value(s) from `#{action}' action helper" \ unless result.length == required_arity.abs result.push(opts) when Hash Array.new(required_arity.abs).push(result) else [result, nil].take(required_arity.abs).push({}) end end define_singleton_method("remove_#{action}") do remove_method(action) if respond_to?(action) end end end %i[has_one has_many].each do |rel_type| define_method(rel_type) do |rel, &block| rel = rel.to_s .send(rel_type == :has_one ? :singularize : :pluralize) .dasherize .to_sym config = _resource_config[rel_type][rel] # trigger default proc namespace %r{/#{_resource_config[:route_opts][:pkre]}(?<r>/relationships)?/#{rel}(?![^/])} do define_singleton_method(:resource_config) { config } helpers Helpers::Nested do define_method(:can?) do |action, *args| parent = sideloaded? && env['sinja.passthru'].to_sym roles, sideload_on = config.fetch(action, {}).values_at(:roles, :sideload_on) roles.nil? || roles.empty? || roles.intersect?(role) || parent && sideload_on.include?(parent) && super(parent, *args) end define_method(:serialize_linkage) do |*args| super(resource, rel, *args) end end register RelationshipRoutes.const_get(rel_type.to_s.camelize) instance_eval(&block) if block end end end end end
{ "content_hash": "723c5e57820d03f4fef8d6e293e61eac", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 101, "avg_line_length": 30.82758620689655, "alnum_prop": 0.5771812080536913, "repo_name": "mwpastore/sinja", "id": "d036a090398b092b40627116ed625c5486babcd2", "size": "3606", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/sinja/resource.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "108119" }, { "name": "Shell", "bytes": "682" } ], "symlink_target": "" }
define(function () { // Hungarian return { inputTooLong: function (args) { var overChars = args.input.length - args.maximum; return 'Túl hosszú. ' + overChars + ' karakterrel több, mint kellene.'; }, inputTooShort: function (args) { var remainingChars = args.minimum - args.input.length; return 'Túl rövid. Még ' + remainingChars + ' karakter hiányzik.'; }, loadingMore: function () { return 'Töltés…'; }, maximumSelected: function (args) { return 'Csak ' + args.maximum + ' elemet lehet kiválasztani.'; }, noResults: function () { return 'Nincs találat.'; }, searching: function () { return 'Keresés…'; } }; });
{ "content_hash": "38ca89b541a74708e536d43a1c14a23b", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 77, "avg_line_length": 24.79310344827586, "alnum_prop": 0.588317107093185, "repo_name": "N00bface/Real-Dolmen-Stage-Opdrachten", "id": "b7c0072a8631cc9fbe6574bff778cf3902541115", "size": "980", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "stageopdracht/src/main/resources/static/vendors/gentelella/vendors/select2/src/js/select2/i18n/hu.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "212672" }, { "name": "HTML", "bytes": "915596" }, { "name": "Java", "bytes": "78870" }, { "name": "JavaScript", "bytes": "9181" } ], "symlink_target": "" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #ifndef __HOSTFXR_H__ #define __HOSTFXR_H__ #include <stddef.h> #include <stdint.h> #if defined(_WIN32) #define HOSTFXR_CALLTYPE __cdecl #ifdef _WCHAR_T_DEFINED typedef wchar_t char_t; #else typedef unsigned short char_t; #endif #else #define HOSTFXR_CALLTYPE typedef char char_t; #endif enum hostfxr_delegate_type { hdt_com_activation, hdt_load_in_memory_assembly, hdt_winrt_activation, hdt_com_register, hdt_com_unregister, hdt_load_assembly_and_get_function_pointer }; typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_main_fn)(const int argc, const char_t **argv); typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_main_startupinfo_fn)( const int argc, const char_t **argv, const char_t *host_path, const char_t *dotnet_root, const char_t *app_path); typedef void(HOSTFXR_CALLTYPE *hostfxr_error_writer_fn)(const char_t *message); typedef hostfxr_error_writer_fn(HOSTFXR_CALLTYPE *hostfxr_set_error_writer_fn)(hostfxr_error_writer_fn error_writer); typedef void* hostfxr_handle; struct hostfxr_initialize_parameters { size_t size; const char_t *host_path; const char_t *dotnet_root; }; typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_initialize_for_dotnet_command_line_fn)( int argc, const char_t **argv, const struct hostfxr_initialize_parameters *parameters, /*out*/ hostfxr_handle *host_context_handle); typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_initialize_for_runtime_config_fn)( const char_t *runtime_config_path, const struct hostfxr_initialize_parameters *parameters, /*out*/ hostfxr_handle *host_context_handle); typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_get_runtime_property_value_fn)( const hostfxr_handle host_context_handle, const char_t *name, /*out*/ const char_t **value); typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_set_runtime_property_value_fn)( const hostfxr_handle host_context_handle, const char_t *name, const char_t *value); typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_get_runtime_properties_fn)( const hostfxr_handle host_context_handle, /*inout*/ size_t * count, /*out*/ const char_t **keys, /*out*/ const char_t **values); typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_run_app_fn)(const hostfxr_handle host_context_handle); typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_get_runtime_delegate_fn)( const hostfxr_handle host_context_handle, enum hostfxr_delegate_type type, /*out*/ void **delegate); typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_close_fn)(const hostfxr_handle host_context_handle); #endif //__HOSTFXR_H__
{ "content_hash": "d04512d494c35090d6256ee8e3615ac4", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 117, "avg_line_length": 33.357142857142854, "alnum_prop": 0.7177016416845111, "repo_name": "MichaelSimons/core-setup", "id": "040b7c78d87b14340f42fb30cf64b9236aaeafaa", "size": "2802", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/corehost/cli/hostfxr.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "10625" }, { "name": "Batchfile", "bytes": "9767" }, { "name": "C", "bytes": "45725" }, { "name": "C#", "bytes": "1477203" }, { "name": "C++", "bytes": "1378184" }, { "name": "CMake", "bytes": "65382" }, { "name": "Dockerfile", "bytes": "12774" }, { "name": "HTML", "bytes": "44274" }, { "name": "Makefile", "bytes": "248" }, { "name": "PowerShell", "bytes": "136501" }, { "name": "Python", "bytes": "19560" }, { "name": "Rich Text Format", "bytes": "47653" }, { "name": "Roff", "bytes": "6044" }, { "name": "Shell", "bytes": "187994" } ], "symlink_target": "" }
package shapeless package syntax import scala.collection.{ GenTraversable, GenTraversableLike } object sized { implicit def genTraversableSizedConv[CC[X] <: GenTraversable[X], T](cc : CC[T]) (implicit conv : CC[T] => GenTraversableLike[T, CC[T]]) = new SizedConv[T, CC[T]](cc) implicit def stringSizedConv(s : String) = new SizedConv[Char, String](s) } final class SizedConv[A, Repr <% GenTraversableLike[A, Repr]](r : Repr) { import ops.nat._ import Sized._ def sized[L <: Nat](implicit toInt : ToInt[L]) = if(r.size == toInt()) Some(wrap[Repr, L](r)) else None def sized(l: Nat)(implicit toInt : ToInt[l.N]) = if(r.size == toInt()) Some(wrap[Repr, l.N](r)) else None def ensureSized[L <: Nat](implicit toInt : ToInt[L]) = { assert(r.size == toInt()) wrap[Repr, L](r) } }
{ "content_hash": "4045ce5f545b0791855c3273e0433b6d", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 89, "avg_line_length": 28.551724137931036, "alnum_prop": 0.642512077294686, "repo_name": "rorygraves/shapeless", "id": "d65763a76ce846bb29197751dd6cbccc00d88a42", "size": "1430", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "core/src/main/scala/shapeless/syntax/sized.scala", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.springframework.cloud.autoconfigure; import java.util.LinkedHashMap; import java.util.Map; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration; import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.actuate.endpoint.InfoEndpoint; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.bootstrap.config.PropertySourceBootstrapConfiguration; import org.springframework.cloud.context.environment.EnvironmentChangeEvent; import org.springframework.cloud.context.restart.RestartEndpoint; import org.springframework.cloud.context.scope.refresh.RefreshScope; import org.springframework.cloud.endpoint.RefreshEndpoint; import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.integration.monitor.IntegrationMBeanExporter; @Configuration @ConditionalOnClass(Endpoint.class) @AutoConfigureAfter(EndpointAutoConfiguration.class) public class RefreshEndpointAutoConfiguration { @ConditionalOnBean(EndpointAutoConfiguration.class) @Bean InfoEndpointRebinderConfiguration infoEndpointRebinderConfiguration() { return new InfoEndpointRebinderConfiguration(); } @ConditionalOnClass(IntegrationMBeanExporter.class) protected static class RestartEndpointWithIntegration { @Autowired(required = false) private IntegrationMBeanExporter exporter; @Bean @ConditionalOnMissingBean public RestartEndpoint restartEndpoint() { RestartEndpoint endpoint = new RestartEndpoint(); if (this.exporter != null) { endpoint.setIntegrationMBeanExporter(this.exporter); } return endpoint; } } @ConditionalOnMissingClass("org.springframework.integration.monitor.IntegrationMBeanExporter") protected static class RestartEndpointWithoutIntegration { @Bean @ConditionalOnMissingBean public RestartEndpoint restartEndpoint() { return new RestartEndpoint(); } } @Bean @ConfigurationProperties("endpoints.pause") public Endpoint<Boolean> pauseEndpoint(RestartEndpoint restartEndpoint) { return restartEndpoint.getPauseEndpoint(); } @Bean @ConfigurationProperties("endpoints.resume") public Endpoint<Boolean> resumeEndpoint(RestartEndpoint restartEndpoint) { return restartEndpoint.getResumeEndpoint(); } @Configuration @ConditionalOnProperty(value = "endpoints.refresh.enabled", matchIfMissing = true) @ConditionalOnBean(PropertySourceBootstrapConfiguration.class) protected static class RefreshEndpointConfiguration { @Bean @ConditionalOnMissingBean public RefreshEndpoint refreshEndpoint(ConfigurableApplicationContext context, RefreshScope scope) { RefreshEndpoint endpoint = new RefreshEndpoint(context, scope); return endpoint; } } private static class InfoEndpointRebinderConfiguration implements ApplicationListener<EnvironmentChangeEvent>, BeanPostProcessor { @Autowired private ConfigurableEnvironment environment; private Map<String, Object> map = new LinkedHashMap<String, Object>(); @Override public void onApplicationEvent(EnvironmentChangeEvent event) { for (String key : event.getKeys()) { if (key.startsWith("info.")) { this.map.put(key.substring("info.".length()), this.environment.getProperty(key)); } } } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof InfoEndpoint) { return infoEndpoint((InfoEndpoint) bean); } return bean; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } private InfoEndpoint infoEndpoint(InfoEndpoint endpoint) { return new InfoEndpoint(endpoint.invoke()) { @Override public Map<String, Object> invoke() { Map<String, Object> info = new LinkedHashMap<String, Object>( super.invoke()); info.putAll(InfoEndpointRebinderConfiguration.this.map); return info; } }; } } }
{ "content_hash": "a190d349614d328a7a71223fdffcb410", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 95, "avg_line_length": 33.50684931506849, "alnum_prop": 0.812142273098937, "repo_name": "jmnarloch/spring-cloud-commons", "id": "091c1e3e131df648b81ca8b160c3af23ecaa6472", "size": "5512", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/RefreshEndpointAutoConfiguration.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5150" }, { "name": "Java", "bytes": "316348" }, { "name": "Shell", "bytes": "7096" } ], "symlink_target": "" }
import Ember from 'ember'; const { Mixin, on, $, K, run } = Ember; export default Mixin.create({ _setupResizeListener: on('didInsertElement', function() { $(window).on(`resize.${this.elementId}`, (event) => { run.next(this, this.didResize, event); }); }), _teardownResizeListener: on('willDestroyElement', function() { $(window).off(`resize.${this.elementId}`); }), didResize: K });
{ "content_hash": "e1af6822dbd88e1e01455f0a675342df", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 64, "avg_line_length": 24.41176470588235, "alnum_prop": 0.6240963855421687, "repo_name": "ivanvanderbyl/maximum-plaid", "id": "778645175a492685979e1211483d0ede05b8055c", "size": "415", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "addon/mixins/global-resize.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "330" }, { "name": "HTML", "bytes": "4432" }, { "name": "JavaScript", "bytes": "62966" } ], "symlink_target": "" }
<eml xmlns:ns0="eml://ecoinformatics.org/eml-2.1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" packageId="kubi.lifemapper.sdm.layers.589" system="kubi.lifemapper" xsi:schemaLocation="eml://ecoinformatics.org/eml-2.1.1 https://code.ecoinformatics.org/code/eml/tags/RELEASE_EML_2_1_1/eml.xsd"> <dataset> <title>BIO14, Precipitation of Driest Month, 2040-2069, IPCC AR4 Scenario A2, NIES</title> <creator> <organizationName>Lifemapper</organizationName> </creator> <keywordSet> <keyword>Predicted</keyword> <keyword>driest</keyword> <keyword>precipitation</keyword> <keyword>month</keyword> </keywordSet> <coverage> <geographicCoverage> <geographicDescription>Bounding box (EPSG:4326) - (-180.0, -60.0, 180.0, 90.0)</geographicDescription> <boundingCoordinates> <westBoundingCoordinate>-180.0</westBoundingCoordinate> <eastBoundingCoordinate>180.0</eastBoundingCoordinate> <northBoundingCoordinate>90.0</northBoundingCoordinate> <southBoundingCoordinate>-60.0</southBoundingCoordinate> </boundingCoordinates> </geographicCoverage> <temporalCoverage> <rangeOfDates> <beginDate> <calendarDate>2040</calendarDate> </beginDate> <endDate> <calendarDate>2069</calendarDate> </endDate> </rangeOfDates> </temporalCoverage> </coverage> <contact> <organizationName>University of Kansas Biodiversity Institute</organizationName> <address> <deliveryPoint>1345 Jayhawk Boulevard, Room 606</deliveryPoint> <city>Lawrence</city> <administrativeArea>Kansas</administrativeArea> <postalCode>66045</postalCode> <country>United States</country> </address> <electronicMailAddress>[email protected]</electronicMailAddress> <onlineUrl>http://lifemapper.org</onlineUrl> </contact> <spatialRaster> <entityName>http://lifemapper.org/services/sdm/layers/589</entityName> <physical> <objectName>bio_14.tif</objectName> <dataFormat> <externallyDefinedFormat> <formatName>GeoTIFF</formatName> </externallyDefinedFormat> </dataFormat> <distribution> <online> <url function="download"> https://bidataone.nhm.ku.edu/mn/v1/object/kubi.lifemapper.sdm.layers.589.tif </url> </online> </distribution> </physical> <attributeList> <attribute> <attributeName>Value</attributeName> <attributeDefinition>BIO14, Precipitation of Driest Month, 2040-2069, IPCC AR4 Scenario A2, NIES</attributeDefinition> <storageType>Real</storageType> <measurementScale> <interval> <unit> <standardUnit>millimeter</standardUnit> </unit> <numericDomain> <numberType>real</numberType> <bounds> <minimum exclusive="false">0.0</minimum> <maximum exclusive="false">752.0</maximum> </bounds> </numericDomain> </interval> </measurementScale> </attribute> </attributeList> <spatialReference> <horizCoordSysDef name="WGS 84"> <geogCoordSys> <datum name="WGS_1984" /> <spheroid denomFlatRatio="298.257223563" name="WGS 84" semiAxisMajor="6378137.0" /> <primeMeridian longitude="0.0" name="Greenwich" /> <unit name="degree" /> </geogCoordSys> </horizCoordSysDef> </spatialReference> <horizontalAccuracy> <accuracyReport>Unknown</accuracyReport> </horizontalAccuracy> <verticalAccuracy> <accuracyReport>Unknown</accuracyReport> </verticalAccuracy> <cellSizeXDirection>0.00833333333333</cellSizeXDirection> <cellSizeYDirection>0.00833333333333</cellSizeYDirection> <numberOfBands>1</numberOfBands> <rasterOrigin>Upper Left</rasterOrigin> <rows>18000</rows> <columns>43200</columns> <verticals>1</verticals> <cellGeometry>pixel</cellGeometry> </spatialRaster> </dataset> </eml>
{ "content_hash": "2984aae862a060fedbeb09fad46b8cae", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 332, "avg_line_length": 43.64545454545455, "alnum_prop": 0.5623828369089773, "repo_name": "NCEAS/metadig", "id": "959f63ce3e662a56921a8710c5e848e8398f9d7c", "size": "4801", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "collections/DataOne/KUBI/EML/xml/04038-metadata.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "2361" }, { "name": "Python", "bytes": "42696" }, { "name": "Shell", "bytes": "5798" }, { "name": "XSLT", "bytes": "207495" } ], "symlink_target": "" }
FROM balenalib/up-board-alpine:3.10-build ENV NODE_VERSION 14.16.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-amd64.tar.gz" \ && echo "74a2857b06b800f7acc1831f02d5a2ee6d27d9b28699a938396caf669def10b8 node-v$NODE_VERSION-linux-alpine-amd64.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-alpine-amd64.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-alpine-amd64.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/[email protected]" \ && echo "Running test-stack@node" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] 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: Intel 64-bit (x86-64) \nOS: Alpine Linux 3.10 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v14.16.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": "231933c5af67ab3243d3b9f971b5ea40", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 714, "avg_line_length": 65.35555555555555, "alnum_prop": 0.7099625977558653, "repo_name": "nghiant2710/base-images", "id": "e5ce218b91a9b46082100cb68e01c1382b6afe7e", "size": "2962", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/node/up-board/alpine/3.10/14.16.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.scenarioo.example.e4.ui.removeorder; import org.eclipse.swtbot.swt.finder.junit.SWTBotJunit4ClassRunner; import org.eclipse.swtbot.swt.finder.widgets.SWTBotMenu; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTable; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTableItem; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.scenarioo.example.e4.ScenariooTestWrapper; import org.scenarioo.example.e4.UseCaseName; import org.scenarioo.example.e4.pages.SearchOrdersDialogPageObject; import org.scenarioo.example.e4.rules.InitOrderOverviewRule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(SWTBotJunit4ClassRunner.class) public class RemoveOrderFromOrderOverviewAndVerifyThatTheOrderStillExistsTest extends ScenariooTestWrapper { private static final String REMOVED_ORDER_NUMBER = "Order 2"; private static final Logger LOGGER = LoggerFactory.getLogger(RemoveOrderFromOrderOverviewAndVerifyThatTheOrderStillExistsTest.class); @Rule public InitOrderOverviewRule initOrderOverview = new InitOrderOverviewRule(); /** * @see org.scenarioo.example.e4.ScenariooTestWrapper#getUseCaseName() */ @Override protected UseCaseName getUseCaseName() { return UseCaseName.REMOVE_ORDER; } /** * @see org.scenarioo.example.e4.ScenariooTestWrapper#getScenariooDescription() */ @Override protected String getScenarioDescription() { return "Removes an order from the order overview via Context menu. Then it showes that " + "the removed order is still available in the repository."; } @Test public void execute() { generateInitialViewDocuForOrderOverview(); SWTBotTree tree = bot.tree(); SWTBotMenu menu = getContextMenuAndGenerateDocu(tree, REMOVED_ORDER_NUMBER, "Remove Order"); LOGGER.info(menu.toString()); clickMenuEntryAndGenerateDocu(menu); // Assert 3 Orders available in OrderOverview Assert.assertEquals(initOrderOverview.getInitializedOrdersInOrderOverview() - 1, tree.rowCount()); verifyRemovedOrderHasNotBeenDeleted(); LOGGER.info(getClass().getSimpleName() + " successful!"); } private void verifyRemovedOrderHasNotBeenDeleted() { SearchOrdersDialogPageObject searchOrdersDialog = new SearchOrdersDialogPageObject( scenariooWriterHelper); searchOrdersDialog.open(); searchOrdersDialog.enterOrderNumber("Order"); searchOrdersDialog.startSearch(); SWTBotTable table = bot.table(); SWTBotTableItem item = table.getTableItem(REMOVED_ORDER_NUMBER); LOGGER.info(item.toString()); Assert.assertNotNull(item); bot.button("Cancel").click(); } }
{ "content_hash": "084ff36ed297bf6f57ece19885992dff", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 134, "avg_line_length": 30.545454545454547, "alnum_prop": 0.7979910714285714, "repo_name": "scenarioo/scenarioo-example-swtbot-e4", "id": "58a2854b509dc12d13c1fea66bd597c5723b7fb2", "size": "4205", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugins/org.scenarioo.example.e4.test/src/org/scenarioo/example/e4/ui/removeorder/RemoveOrderFromOrderOverviewAndVerifyThatTheOrderStillExistsTest.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "5272" }, { "name": "Java", "bytes": "463974" }, { "name": "Shell", "bytes": "7261" } ], "symlink_target": "" }
.. title: 21 - Configuration .. slug: 21 - Configuration .. date: 2016-01-23 06:51:57 UTC-08:00 .. tags: notes, mathjax .. category: .. link: .. description: .. type: text ================== 21 - Configuration ================== 01 - Preview ------------ Today, we'll talk about configuration. Configuration is a very routine kind of design task in which all the components of the design are already known. The task now is to assign values to the variables of those components so they can be arranged according to some constraints. Configuration will be your first part under the unit on designing creativity. We'll start by talking about design, then we'll define configuration. Then we trace through the process of configuration, a specific measure called planned refinement. Finally, we'll connect configuration to several earlier topics we have discussed such as classification, case based reasoning, and planning. 02 - Define Design ------------------ Let us talk about what is design. Design in journal takes us input some sort of needs, so goals or functions. It gives us output that's specification of this structure of some artifact that satisfies those needs and goals and functions. Note that the artifact need not be a physical product. It can be a process. A program, a policy. Some example for design, design a robot that can walk on water. Design a search engine that can return the most relevant answer to a query. The Federal Reserve Bank designs and monitor the policy to optimize the economy. Note the design is very wide ranging, open ended and ill-defined. In problem solving, typically the problem remains fixed, even as the solution evolves. In design, both the problem and the solution co-evolve. The problem evolves as the solution evolves. We are studying design and AI because we are working with AI agents that can do design. At least potentially, we want AI agents that can design other AI agents. 03 - Exercise Designing a Basement ---------------------------------- >> Thanks, Isuke so right now, my wife and I are actually building a house and as part of that, we need to configure the basement for the house. I've taken a list of some of the requirements for this basement and listed them over here on the left. And on the right, I have the variables that we need to assign values to, we have things like the width of the utility closet, the length of the stairwell, we also had two additional rooms, each must have their own length and width. So try to configure our basement, such that we meet all the different requirements listed over here on the left, write a number in each of these blanks. 04 - Exercise Designing a Basement ---------------------------------- >> Thank you, David. There are several things to note from David's analysis. One is that, in configuration final, we want an arrangement of all the components of all the parts. So in this case, finally, we want an arrangement of all the rooms and these tables, and the utility closets, and so on. Not just the size of each one of them, but the actual spatial layout. Second, they would begin by assigning values to some variables here. Because he thought that these variables were more restricted. One can use a number of different heuristics for ordering the variables. Perhaps, we can choose those variables which are most restricted first, or we can choose those variables that restrict. Others the most first. We can choose the most important variables, first. The point is, there can be a large number of variables, and we can impose an ordering on them. 05 - Defining Configuration --------------------------- >> Designing journal is a very common information processing activity and configuration is the most common kind of design. Now that we have looked at the definition of the configuration task, we are going to look at matters for addressing the task. Once again, recall that the components in case of configuration are already known. We are deciding on the arrangement of those components. We are assigning values to specific variables of those components, for example, sizes. 06 - The Configuration Process ------------------------------ >> So for an example that might hit a little bit closer to home for many of you, as you've been designing your agents that can solve the Raven's test, you've done a process somewhat like this. You start with some specifications, general specifications that your agent must be able to solve as mini problems on the Raven's test as possible. You can start with an abstract solution of just the general problem solving process, that you may have then refined to be more specific about the particular transformations to look for or the particular problem solving methods to use. That got you to your final result. But when you ran your final result, you may have found something like, it would work but it would take a very, very long time to run, weeks or months. So that thing causes you to revise your specifications. You not only need an agent that can solve as many problems as possible, but you also need one that can solve it in minutes or seconds instead of weeks or months. 07 - Example Representing a Chair --------------------------------- Let us look at how the process of configuration would work in detail. Recorder will met a file of represent in reason, will represent knowledge and then reason over it. So suppose it asked the configure a chair. We must then somehow represent all of the knowledge of this chair then we can reason over it. So we will represent all of our knowledge of the chair in the form of a frame. Here's is the frame, here are the beta slots. For the time being, let's just assume that there are six slots that are important. The last four of the slots may point to their own frames. So there might be a frame for legs, a frame for seat, and so on. Now some of these frames have slots like size, and material, and cost. For legs, you may have an additional slot like count. What is the number of legs on the chair? And this particular frame representation captures of the knowledge of the generic, prototypical chair. To do configuration design is to come up with a specific arrangement of all the parts to this particular chair, to assign values to each of the variables, which means filling out the fillers for each of the slots. Of course, the values of these variables depends in part on the global constraints of mass and cost. We may, for example, have a global constraint on the mass of the chair, or in the cost of the chair, or both. We may have additional constraint as well. For example in material of a chair might become an, perhaps the material needs to be metal. 08 - Example Ranges of Values ----------------------------- Now in configuration design, we not only know all the components like legs, and set, and arms, and so on. We not only know the variables for each of the components, like size and material, and cost. But we also know the ranges of values that any of these variables can take. Thus the seat of a chair may have a certain weight, or length, or depth. Here between the sides and the seat in a very simple matter in terms of the mass of the seat as measured in grams. So 10 to 100 grams, you'll see in minute why we're using this simple measure. So when it is brackets for this material slot suggests that there is a range here, it will show the range on the left [UNKNOWN]. TThe cost then will be determined by the size and the materials. Let us suppose that this table captures the cost per gram for certain kinds of materials. Now you can see why we're using gram as a measure for the size of the seat. We wanted to very easily relate the size to the cost. The material slot now can take one of these three values. This is the range of values that can go into the material slot. Given a particular size and a particular material, we can calculate this cost. Note that this representation allows us to calculate the total mass of the chair and the total cost of the chair, given the total mass and the total cost at least of the components. 09 - Example Applying a Constraint ---------------------------------- Now let us suppose that we get a new order in which a customer wants a chair that weighs over 200 grams, costs at most $20, and has four legs. Given the specification, what configuration process can use this knowledge to fill in the values of all the variables to satisfy the specification. So the first thing the process might do is to write down all the constraints that are given as part of the input specification. So the mass is greater than 200 grams, the cost is less than $20, and the count of legs is 4. Now suppose that a configuration process has an abstract plan which first decides on the value of the cost variable before it decides on other variables. Let us also further suppose that this plan for deciding the cost evenly distributes the cost between the greatest components until unless specified otherwise by the specification. In this case the cost plan distributes this cost of $20 between the four components and assigns less than five for each one of them. Now we define an expanding plan. This is two aspects to it, refine and expand. Index and aspect we deal with the components instead of the chair as a whole. And the define aspect we deal with more detailed variables that were not there in the chair. Consider the component legs, for example. We already know the count, four, in the input specification. We know the cost, no more than $5 from the higher level plan. Now we can design by using the other two variables, 25 grams and wood, for example. We can do the same for the other components. As we assign values to the variables of each of these components, we get a complete arrangement of all these components here, with values assigned to each of the variables. Given the specific values we assign to the variables for each of the components, we can now compute whether the constraint given in the input specification are satisfied. In this particular example, both the mass and the cost of the chair satisfy the input constraints. Note that the define and expands step in this particular process might have operated a little differently. It is also possible that define and expand step might say, the less, decide on the material before we decide on any of the other features. Plus within thin complex configuration process, different designers may use different plans and different plans to find expansion mechanisms. Of course it is also possible that once we have a candidate solution, the candidate solution may not necessarily satisfy the input constraints. So the cost may turn out to be more than $20, for example. In that case there are two options. Either we can iterate on the process, loading the cost, or we can go about changing the specification. 10 - Exercise Applying a Constraint ----------------------------------- Let us do an exercise together. This exercise again deals with the configuration of a chair. The input specification is a chair that costs at most $16 to make, and has 100 grams metal seat. Please fill out the values of all of these boxes. Try to use a configuration process that we just described, and make a note of the process that you actually did use 11 - Exercise Applying a Constraint ----------------------------------- >> That's good, David. It's important to note that David used several different kinds of knowledge. First, he had knowledge of the generic chair. He knew about the components. He know about the slots, but not necessarily all the fellows for these slots. Second, he had heuristic knowledge. He used the term heuristic, recall that down here, heuristic stands for rule of thumb. So, heuristic knowledge about how to go what filling the values of some of these slots. Third, explicit in this is not just the knowledge about legs and seats and arms and so on, but also how does chair as a whole is decomposed in these components. That is one of the fundamental rules of knowledge and knowledge based AI. It allows to struck to the problem so this problem can be addressed efficiently. Note this process of configuration design is closely related to the method of constraint propagation that we discussed in our previous lesson. Here, are some constraints, and these constraints have been propagated downwards in the pan obstruction hierarchy. 12 - Connection to Classification --------------------------------- >> So it sounds to me like, while classification is a way of making sense of the world, configuration is a way of creating the world. With classification we perceive certain details in the world and decide what they are. With configuration, we're given something to create and we decide on those individual variables 13 - Contrast with Case-Based Reasoning --------------------------------------- We can also can cross configuration with case based reasoning. Both configuration and case based reasoning are typically applied to routine design problems, problems of the kind that we've often encountered in the past. Gives a configuration, we start with a prototypical concept, then assign values to all the variables as we saw in this chair example. In case of case-based reasoning we start with the design of a specific chair that we had designed earlier. Look at its variables and tweak it as needed to satisfy this constraint so the current problem. Case-based reasoning assumes that we already designed our other chairs, and we have stored examples of the chairs for designing the memory. Configuration assumes, that we already designed enough chairs so that we can in fact extract the plan. When a specific problem is presented to an IA agent, the IA agent, if it is going to use the method of configuration, is going to call upon the plan obstruction hierarchy and then start defining plans. If the AI agent uses the method of case based reasoning, then it'll go into the case memory, retrieve the closest matching case, and then start tweaking the case. Little bit later we will see how an AI agent select between different methods that were able to address the task. As we have mentioned earlier in the course, the chemical periodic table was one of the really important scientific discoveries. Similar to chemical periodic table, we are trying to build a periodic table of intelligence. Unlike the chemical periodic table which deals with balance electrons. Our periodic table of intelligence, deals with tasks and methods. In this particular course, we have considered both a large number of tasks, configuration being one of them, as well as a large number of methods, [UNKNOWN] instantiation and case-based reasoning being two of them. 14 - Connection to Planning --------------------------- The process of configuration is also related to planning. You can consider a planner that actually generates the plan in this plan obstruction hierarchy. But then for any plan in this plan obstruction hierarchy, then it converts a plan in this plan obstruction hierarchy into a skeletal plan. It drops the values of the variables in the plans and constructs it into a plan it's simply specify the variable without specifying the values. The process of configuration planning then, takes these plans, organizes them into obstruction hierarchy and goes about [INAUDIBLE] shading and refining and expanding them. We already discussed how configuration is connected to a number of other lessons like case based reasoning, planning and classification. You may also consider this plan to be kind of strict for physical object. In addition, this plans have been learned, through learning methods similar to the method of incremental concept learning. In addition, this plan hierarchy might be learned through learning methods similar to the method for incremental concept learning. One of the things that we are doing in knowledge based AI is, to describe the kinds of knowledge that we need to learn. Before we decide on what is a good learning method, we need to decide on what is it we need to learn? The configuration process tells us of the different kinds of knowledge that then become targets of learning. To connect this lesson back to our cognitive architecture, consider this figure once again. So knowledge of the prototypical chair, as well as knowledge about the radius, plans, and the abstraction hierarchy are stored in memory. As the input gives specification with the design problem, the reasoning component instantiates those plans, refines them and expands them. The knowledge itself is learned through examples of configuration of chairs that presumably, the agent is already encountered previously. 15 - Assignment Configuration ----------------------------- So how might you use the idea of configuration to design an agent that can answer Raven's progressive matrices? We've talked in the past about how constraint propagation can help us solving these problems. If configuration is a type of constraint propagation, how can you leverage the idea of variables and values in designing your agent? What are the variables and what values can they take? We've also discussed how planning can be applied to Raven's progressive matrices. If configuration leverages old plans, how you build your agent to remember those old plans and reconfigure them for new problems? Will it develop the old plans based on existing problems, or will you hand it the problems in advance? 16 - Wrap Up ------------ So today we've talked about configuration, a kind of routine design task. We do configuration when we're dealing with a plan that we've used a lot in the past, we need to modify to deal with some specific new constraints. So for example, we've built thousands of buildings, and thousands of cars, and thousands of computers, and each of them is largely the same. But there's certain parameters, like the number of floors in a building, or the portability of the computer, that differ from design to design. So we need to tweak individual variables to meet those new constraints. We started this off by defining design in general, and then we used that to define configuration, as a certain type of routine design task. We then discussed the process of configuration and how it's actually very similar to constraint propagation that we've talked about earlier. Then we connected this to earlier topics like classification, planning and case-based reasoning, and saw how in many ways, configuration is a task, while other things we've talked about provide us the method for accomplishing that task. So now we'll move on to diagnosis, which is another topic related to design, where we try to uncover the cause of a malfunction in something that we may have designed. In some ways, we'll see that diagnosis is a lot like configuration in reverse. 17 - The Cognitive Connection ----------------------------- Design is a very common cognitive activity. Some people even claim that design is a single cognitive activity that has the most economic value of all such activities. Configuration is a type of routine design, that occurs every single day. For example, you need to run some errands. You know the roads, you know the vehicle, you know the traffic patterns. Now you need to configure the specific route that can optimize some constraint such as time. Cooking is another everyday example of configuration. We know the recipes, which tell us about the high level plans and the ingredients we need to assign values to specific variables that can optimize some constraints such as taste. Notice that we can separate task from method. Configuration is a task that can be addressed by many methods. We will look as several of them, such as [UNKNOWN]. Plant refinement, [UNKNOWN] test, and so on. [BLANK_AUDIO] 18 - Final Quiz --------------- Please summarize what you learned in this lesson in this blue box. 19 - Final Quiz --------------- Great, thank you very much.
{ "content_hash": "283323fdb53182a1ff9f509720348957", "timestamp": "", "source": "github", "line_count": 420, "max_line_length": 120, "avg_line_length": 47.84761904761905, "alnum_prop": 0.7704020700636943, "repo_name": "orsenthil/coursedocs", "id": "889668857af29406dca7a9fe85245f0c7b1ae206", "size": "20096", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gatech/cs7637/21---configuration.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "47" }, { "name": "Lua", "bytes": "5998" }, { "name": "Makefile", "bytes": "7637" }, { "name": "Python", "bytes": "74899" }, { "name": "Shell", "bytes": "1963" } ], "symlink_target": "" }
namespace blink { class WebIDBCursor; // Handle the indexed db related communication for this context thread - the // main thread and each worker thread have their own copies. class MODULES_EXPORT IndexedDBDispatcher { DISALLOW_NEW(); public: static void RegisterCursor(WebIDBCursor* cursor); static void UnregisterCursor(WebIDBCursor* cursor); // Reset cursor prefetch caches for all cursors except |except_cursor|. // In most callers, |except_cursor| is passed as nullptr, causing all cursors // to have their prefetch cache to be reset. In 2 WebIDBCursor callers, // specifically from |Advance| and |CursorContinue|, these want to reset all // cursor prefetch caches except the cursor the calls are running from. They // get that behavior by passing |this| to |ResetCursorPrefetchCaches| which // skips calling |ResetPrefetchCache| on them. static void ResetCursorPrefetchCaches(int64_t transaction_id, WebIDBCursor* except_cursor); private: friend class WTF::ThreadSpecific<IndexedDBDispatcher>; static IndexedDBDispatcher* GetInstanceForCurrentThread(); IndexedDBDispatcher(); WTF::HashSet<WebIDBCursor*> cursors_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_INDEXEDDB_INDEXED_DB_DISPATCHER_H_
{ "content_hash": "2f72df4f83de3111e7444c13960fb511", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 80, "avg_line_length": 37.4, "alnum_prop": 0.7448433919022154, "repo_name": "chromium/chromium", "id": "f170bfd0d77fc8074910fb6fec683db55a487a1c", "size": "2078", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "third_party/blink/renderer/modules/indexeddb/indexed_db_dispatcher.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
/** * Input/output package */ package kr.jihee.text_toolkit.io; import java.awt.image.RenderedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Stream; import java.util.stream.Stream.Builder; import javax.imageio.ImageIO; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import kr.jihee.text_toolkit.lang.JFunction.Thrower; import kr.jihee.text_toolkit.util.JTime; /** * Class for handling files * * @author Jihee */ public class JFile { protected static Logger log = LogManager.getLogger(JFile.class); public static File asFile(String path) { Optional<File> local = Optional.of(new File(path)).filter(File::exists); if (local.isPresent()) return local.get(); else return Optional.ofNullable(Object.class.getResource(path)).map(URL::getPath).map(File::new).orElse(null); } public static InputStream asStream(String path) throws FileNotFoundException { Optional<File> local = Optional.of(new File(path)).filter(File::exists); if (local.isPresent()) return new FileInputStream(local.get()); else return Optional.ofNullable(Object.class.getResourceAsStream(path)).orElseThrow(FileNotFoundException::new); } public static File getTempFile(String project, String prefix, String suffix) { File parent = new File(System.getProperty("java.io.tmpdir"), project); if (!parent.exists()) parent.mkdirs(); try { return File.createTempFile(prefix, suffix, parent); } catch (IOException e) { e.printStackTrace(); return null; } } public static File getTempFile(String project, String prefix) { return getTempFile(project, prefix, ".log"); } public static File getTempFile(String project) { return getTempFile(project, String.format("[%s] ", JTime.now()), ".log"); } public static Stream<File> list(File path, Predicate<File> filter) { try { return Files.list(path.toPath()).map(p -> p.toFile()).filter(filter); } catch (Throwable e) { Thrower.throwing(e); return Stream.empty(); } } public static Stream<File> listDirs(File path) { return list(path, p -> p.isDirectory()); } public static Stream<File> listFiles(File path) { return list(path, p -> p.isFile()); } public static Stream<File> listAllDirs(File path) { Builder<File> builder = Stream.builder(); listDirs(path).peek(builder::add).forEach(sub -> listAllDirs(sub).forEach(builder::add)); return builder.build(); } public static Stream<File> listAllFiles(File path) { Builder<File> builder = Stream.builder(); listFiles(path).forEach(builder::add); listAllDirs(path).forEach(sub -> listFiles(sub).forEach(builder::add)); return builder.build(); } public static boolean writeImage(RenderedImage im, String formatName, File output) { try { return ImageIO.write(im, formatName, output); } catch (Throwable e) { Thrower.throwing(e); return false; } } }
{ "content_hash": "a0c1b0c509f30bb4857bb5ea6f26d40c", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 110, "avg_line_length": 28.55045871559633, "alnum_prop": 0.7249357326478149, "repo_name": "chrisjihee/text_toolkit", "id": "5dbd37df55eaecd273a8cdbb0f70beb27e9a631c", "size": "3112", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/kr/jihee/text_toolkit/io/JFile.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "150941" } ], "symlink_target": "" }
package org.apache.cassandra.hadoop2; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import org.apache.cassandra.thrift.*; import org.apache.hadoop.mapreduce.*; /** * The <code>ColumnFamilyOutputFormat</code> acts as a Hadoop-specific * OutputFormat that allows reduce tasks to store keys (and corresponding * values) as Cassandra rows (and respective columns) in a given ColumnFamily. * * <p> * As is the case with the {@link ColumnFamilyInputFormat}, you need to set the * Keyspace and ColumnFamily in your Hadoop job Configuration. The * {@link ConfigHelper} class, through its * {@link ConfigHelper#setOutputColumnFamily} method, is provided to make this * simple. * </p> * * <p> * For the sake of performance, this class employs a lazy write-back caching * mechanism, where its record writer batches mutations created based on the * reduce's inputs (in a task-specific map), and periodically makes the changes * official by sending a batch mutate request to Cassandra. * </p> */ public class ColumnFamilyOutputFormat extends AbstractColumnFamilyOutputFormat<ByteBuffer, List<Mutation>> { /** * Fills the deprecated OutputFormat interface for streaming. */ @Deprecated public ColumnFamilyRecordWriter getRecordWriter(org.apache.hadoop.fs.FileSystem filesystem, org.apache.hadoop.mapred.JobConf job, String name, org.apache.hadoop.util.Progressable progress) { return new ColumnFamilyRecordWriter(job, new Progressable(progress)); } /** * Get the {@link RecordWriter} for the given task. * * @param context the information about the current task. * @return a {@link RecordWriter} to write the output for the job. * @throws IOException */ public ColumnFamilyRecordWriter getRecordWriter(final TaskAttemptContext context) throws InterruptedException { return new ColumnFamilyRecordWriter(context); } }
{ "content_hash": "1f2af40ff8bab1961bf41cbc0f4ad59a", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 194, "avg_line_length": 38.86, "alnum_prop": 0.7447246525990736, "repo_name": "amjadshabani/hive-cassandra", "id": "5d55c0b8e8ebbc127386da19be166857755a9f19", "size": "2748", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "src/main/java/org/apache/cassandra/hadoop2/ColumnFamilyOutputFormat.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "434727" } ], "symlink_target": "" }
package com.google.firebase.messaging; import static com.google.common.truth.Truth.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import android.app.Application; import android.content.Intent; import android.os.PowerManager.WakeLock; import androidx.test.core.app.ApplicationProvider; import com.google.android.gms.tasks.TaskCompletionSource; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.shadows.ShadowLooper; import org.robolectric.shadows.ShadowPowerManager; @RunWith(RobolectricTestRunner.class) public class WakeLockHolderRoboTest { private Application context; @Before public void setUp() { WakeLockHolder.reset(); context = ApplicationProvider.getApplicationContext(); } @Test public void testStartWakefulService_InitsWakeLock() throws Exception { WakeLockHolder.startWakefulService(context, newIntent("Any_Action")); assertThat(ShadowPowerManager.getLatestWakeLock()).isNotNull(); } @Test public void testStartWakefulService_AcquiresWakeLock() throws Exception { Intent intent = newIntent("Any_Action"); WakeLockHolder.startWakefulService(context, intent); assertThat(ShadowPowerManager.getLatestWakeLock().isHeld()).isTrue(); } @Test public void testSendWakefulServiceIntent_AcquiresWakeLock() { TaskCompletionSource<Void> taskCompletionSource = new TaskCompletionSource<>(); WithinAppServiceConnection mockConnection = mock(WithinAppServiceConnection.class); when(mockConnection.sendIntent(any(Intent.class))).thenReturn(taskCompletionSource.getTask()); WakeLockHolder.sendWakefulServiceIntent(context, mockConnection, new Intent()); assertThat(ShadowPowerManager.getLatestWakeLock()).isNotNull(); assertThat(ShadowPowerManager.getLatestWakeLock().isHeld()).isTrue(); } @Test public void testSendWakefulServiceIntent_ReleasesWakeLock() { TaskCompletionSource<Void> taskCompletionSource = new TaskCompletionSource<>(); WithinAppServiceConnection mockConnection = mock(WithinAppServiceConnection.class); when(mockConnection.sendIntent(any(Intent.class))).thenReturn(taskCompletionSource.getTask()); WakeLockHolder.sendWakefulServiceIntent(context, mockConnection, new Intent()); // Verify that the WakeLock is released once the Intent has been handled by the Service. WakeLock wakeLock = ShadowPowerManager.getLatestWakeLock(); taskCompletionSource.setResult(null); ShadowLooper.idleMainLooper(); assertThat(wakeLock.isHeld()).isFalse(); } @Test public void testCompleteWakefulIntent_ReleasesWakeLockIfPresent() throws Exception { Intent intent = newIntent("Any_Action"); WakeLockHolder.startWakefulService(context, intent); WakeLock wl = ShadowPowerManager.getLatestWakeLock(); WakeLockHolder.completeWakefulIntent(intent); assertThat(wl.isHeld()).isFalse(); } @Test public void testCompleteWakefulIntent_ReleasesWakeLockMultipleTimesTest() throws Exception { Intent intent1 = newIntent("1"); WakeLockHolder.startWakefulService(context, intent1); WakeLock wl = ShadowPowerManager.getLatestWakeLock(); assertThat(wl.isHeld()).isTrue(); // WL Count = 1 Intent intent2 = newIntent("2"); WakeLockHolder.startWakefulService(context, intent2); assertThat(wl.isHeld()).isTrue(); // WL Count = 2 Intent intent3 = newIntent("3"); WakeLockHolder.startWakefulService(context, intent3); assertThat(wl.isHeld()).isTrue(); // WL Count = 3 WakeLockHolder.completeWakefulIntent(intent1); assertThat(wl.isHeld()).isTrue(); // WL Count = 2 WakeLockHolder.completeWakefulIntent(intent2); assertThat(wl.isHeld()).isTrue(); // WL Count = 1 Intent intent4 = newIntent("4"); WakeLockHolder.startWakefulService(context, intent4); assertThat(wl.isHeld()).isTrue(); // WL Count = 2 WakeLockHolder.completeWakefulIntent(intent3); assertThat(wl.isHeld()).isTrue(); // WL Count = 1 WakeLockHolder.completeWakefulIntent(intent4); assertThat(wl.isHeld()).isFalse(); // WL Count = 0 } @Test public void testCompleteWakefulIntent_doesNotCrashOnDuplicateCalls() throws Exception { Intent intent = newIntent("1"); WakeLockHolder.startWakefulService(context, intent); WakeLock wl = ShadowPowerManager.getLatestWakeLock(); WakeLockHolder.completeWakefulIntent(intent); // Normal case assertThat(wl.isHeld()).isFalse(); WakeLockHolder.completeWakefulIntent(intent); // Should not crash when No wake lock present } @Test public void testStartWakefulService_createsWakefulIntent() throws Exception { Intent intent = newIntent(null); WakeLockHolder.startWakefulService(context, intent); assertThat(WakeLockHolder.isWakefulIntent(intent)).isTrue(); } @Test public void testCompleteWakefulIntent_removesWakefulMarker() throws Exception { Intent intent = newIntent(null); WakeLockHolder.startWakefulService(context, intent); WakeLockHolder.completeWakefulIntent(intent); assertThat(WakeLockHolder.isWakefulIntent(intent)).isFalse(); } @Test public void testOnlyWakefulIntentsCauseWakeLockToBeReleased() throws Exception { Intent intent = newIntent("1"); WakeLockHolder.startWakefulService(context, intent); WakeLock wl = ShadowPowerManager.getLatestWakeLock(); assertThat(wl.isHeld()).isTrue(); WakeLockHolder.completeWakefulIntent(newIntent("2")); assertThat(wl.isHeld()).isTrue(); WakeLockHolder.completeWakefulIntent(intent); assertThat(wl.isHeld()).isFalse(); } @Test public void testStartWakefulService_multipleCallsOnlyAcquiresWakeLockOnce() throws Exception { Intent intent = newIntent("1"); WakeLockHolder.startWakefulService(context, intent); // Called once WakeLock wl = ShadowPowerManager.getLatestWakeLock(); assertThat(wl.isHeld()).isTrue(); WakeLockHolder.startWakefulService(context, intent); // Called twice assertThat(wl.isHeld()).isTrue(); WakeLockHolder.completeWakefulIntent(intent); // Should be false since the same intent should not acquire wakelock more than once. assertThat(wl.isHeld()).isFalse(); } private Intent newIntent(String action) { return new Intent(action).setPackage(context.getPackageName()); } }
{ "content_hash": "b6c570615855af1fd613554d4e78e642", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 98, "avg_line_length": 36.53977272727273, "alnum_prop": 0.7614678899082569, "repo_name": "firebase/firebase-android-sdk", "id": "3600c6ee8fc71ebac8e87ec95bfff450cb46aa40", "size": "7019", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "firebase-messaging/src/test/java/com/google/firebase/messaging/WakeLockHolderRoboTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AIDL", "bytes": "1486" }, { "name": "C", "bytes": "6703" }, { "name": "C++", "bytes": "86300" }, { "name": "Java", "bytes": "12705758" }, { "name": "JavaScript", "bytes": "5242" }, { "name": "Kotlin", "bytes": "360846" }, { "name": "Makefile", "bytes": "21550" }, { "name": "Mustache", "bytes": "4739" }, { "name": "PureBasic", "bytes": "10781995" }, { "name": "Python", "bytes": "79496" }, { "name": "Ruby", "bytes": "2545" }, { "name": "Shell", "bytes": "4240" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE401_Memory_Leak__int_malloc_44.c Label Definition File: CWE401_Memory_Leak.c.label.xml Template File: sources-sinks-44.tmpl.c */ /* * @description * CWE: 401 Memory Leak * BadSource: malloc Allocate data using malloc() * GoodSource: Allocate data on the stack * Sinks: * GoodSink: call free() on data * BadSink : no deallocation of data * Flow Variant: 44 Data/control flow: data passed as an argument from one function to a function in the same source file called via a function pointer * * */ #include "std_testcase.h" #include <wchar.h> #ifndef OMITBAD static void badSink(int * data) { /* POTENTIAL FLAW: No deallocation */ ; /* empty statement needed for some flow variants */ } void CWE401_Memory_Leak__int_malloc_44_bad() { int * data; /* define a function pointer */ void (*funcPtr) (int *) = badSink; data = NULL; /* POTENTIAL FLAW: Allocate memory on the heap */ data = (int *)malloc(100*sizeof(int)); /* Initialize and make use of data */ data[0] = 5; printIntLine(data[0]); /* use the function pointer */ funcPtr(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2BSink(int * data) { /* POTENTIAL FLAW: No deallocation */ ; /* empty statement needed for some flow variants */ } static void goodG2B() { int * data; void (*funcPtr) (int *) = goodG2BSink; data = NULL; /* FIX: Use memory allocated on the stack with ALLOCA */ data = (int *)ALLOCA(100*sizeof(int)); /* Initialize and make use of data */ data[0] = 5; printIntLine(data[0]); funcPtr(data); } /* goodB2G() uses the BadSource with the GoodSink */ static void goodB2GSink(int * data) { /* FIX: Deallocate memory */ free(data); } static void goodB2G() { int * data; void (*funcPtr) (int *) = goodB2GSink; data = NULL; /* POTENTIAL FLAW: Allocate memory on the heap */ data = (int *)malloc(100*sizeof(int)); /* Initialize and make use of data */ data[0] = 5; printIntLine(data[0]); funcPtr(data); } void CWE401_Memory_Leak__int_malloc_44_good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE401_Memory_Leak__int_malloc_44_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE401_Memory_Leak__int_malloc_44_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "content_hash": "b29db0edcede99275259a43e99702db9", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 151, "avg_line_length": 25.916666666666668, "alnum_prop": 0.6270096463022508, "repo_name": "maurer/tiamat", "id": "29219cfdc9f0f7ed5e9aabe2dc0905b6be3a7cc6", "size": "3110", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "samples/Juliet/testcases/CWE401_Memory_Leak/s01/CWE401_Memory_Leak__int_malloc_44.c", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package org.pac4j.core.matching; import org.junit.Test; import org.pac4j.core.context.MockWebContext; import org.pac4j.core.exception.TechnicalException; import org.pac4j.core.util.TestsHelper; import java.util.regex.PatternSyntaxException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * Tests {@link ExcludedPathMatcher}. * * @author Jerome Leleu * @since 1.8.1 */ public final class ExcludedPathMatcherTests { private ExcludedPathMatcher matcher = new ExcludedPathMatcher("^/(img/.*|css/.*|page\\.html)$"); @Test public void testBlankPath() { final ExcludedPathMatcher pathMatcher = new ExcludedPathMatcher(); assertTrue(pathMatcher.matches(MockWebContext.create().setPath("/page.html"))); assertTrue(pathMatcher.matches(MockWebContext.create())); } @Test public void testMissingStartCharacterInRegexp() { TestsHelper.expectException(() -> new ExcludedPathMatcher("/img/.*$"), TechnicalException.class, "Your regular expression: '/img/.*$' must start with a ^ and end with a $ to define a full path matching"); } @Test public void testMissingEndCharacterInRegexp() { TestsHelper.expectException(() -> new ExcludedPathMatcher("^/img/.*"), TechnicalException.class, "Your regular expression: '^/img/.*' must start with a ^ and end with a $ to define a full path matching"); } @Test(expected = PatternSyntaxException.class) public void testBadRegexp() { new ExcludedPathMatcher("^/img/**$"); } @Test public void testNoPath() { final ExcludedPathMatcher pathMatcher = new ExcludedPathMatcher("^/$"); assertFalse(pathMatcher.matches(MockWebContext.create().setPath("/"))); } @Test public void testMatch() { assertTrue(matcher.matches(MockWebContext.create().setPath("/js/app.js"))); assertTrue(matcher.matches(MockWebContext.create().setPath("/"))); assertTrue(matcher.matches(MockWebContext.create().setPath("/page.htm"))); } @Test public void testDontMatch() { assertFalse(matcher.matches(MockWebContext.create().setPath("/css/app.css"))); assertFalse(matcher.matches(MockWebContext.create().setPath("/img/"))); assertFalse(matcher.matches(MockWebContext.create().setPath("/page.html"))); } }
{ "content_hash": "a6b2d5a21607031f05c5ca53b2d18709", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 212, "avg_line_length": 36.796875, "alnum_prop": 0.6955414012738853, "repo_name": "topicusonderwijs/pac4j", "id": "e41127477136550e4190ebca90e8e66203a9528f", "size": "2355", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "pac4j-core/src/test/java/org/pac4j/core/matching/ExcludedPathMatcherTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1745609" }, { "name": "Shell", "bytes": "2383" } ], "symlink_target": "" }
<rom> <romid> <xmlid>88580014</xmlid> <internalidaddress>f52</internalidaddress> <internalidhex>88580014</internalidhex> <make>Mitsubishi</make> <market>AUSDM</market> <model>Lancer</model> <submodel>Evolution IX</submodel> <transmission>Manual</transmission> <year>2007</year> <flashmethod>mitsukernelocp</flashmethod> <memmodel>SH7055</memmodel> </romid> <notes> 2012/11/14 [Tactrix] cleaned file to correspond to latest Evo 9 base file. Updated to standard file naming. 2012/11/19 [Tactrix] Visually examined tables for obvious errors, but no in-car verification has been done. </notes> <include>88580013</include> </rom>
{ "content_hash": "612892fd75963244b372ba53c4b07b3c", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 112, "avg_line_length": 32.47826086956522, "alnum_prop": 0.6506024096385542, "repo_name": "ripnet/evo", "id": "e555af0d420caf9e2b7db9b84a6d4895f005718d", "size": "747", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ROM-XMLs/88580014 2007 ADM Lancer Evolution MT.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "115903" }, { "name": "JavaScript", "bytes": "4488" }, { "name": "PHP", "bytes": "124825" } ], "symlink_target": "" }
package net.sf.appia.protocols.total.hybrid; import java.io.Serializable; import net.sf.appia.core.message.Message; /** * Message Header to be added to the protocol events. */ public class TotalHybridHeader implements Serializable{ private static final long serialVersionUID = -1164279713630259319L; private int type; private int source; private int sequence; private int sequencer; private Ticket tickets[]; //in case of reassing private int from; private int to; //constants /** * The Event carries a data message. */ public final static int DATA=0; /** * The event carries information that a certain node is going to change to active. */ public final static int GOINGACTIVE=1; /** * The event carries information that a certain node is going to change to passive. */ public final static int GOINGPASSIVE=2; /** * The event carries information that a certain node needs to change the sequencer * to a certain set of messages. */ public final static int REASSING=3; /** * * */ public final static int PERIODIC=4; /** * */ public final static int PENDING=5; /** * Default constructor */ public TotalHybridHeader() {} /** * Constructs a header object for normal messages (DATA, GOINGACTIVE, GOINGPASSIVE). * @param type Type of header. Should be DATA, GOINGACTIVE or GOINGPASSIVE. * @param source Sender of the message. * @param seq Sequence number. * @param sequencer the sequencer ID of the message * @param tickets Array of tickets that are piggybanked in the messages. */ public TotalHybridHeader(int type, int source, int seq, int sequencer, Ticket[] tickets){ this.type=type; this.source=source; this.sequence=seq; this.sequencer=sequencer; this.tickets=tickets; this.from=-1; this.to=-1; } /** * Construcs an header object for REASSING messages. * @param source Sender of the message. * @param from The new sequencer must order from this message. * @param to The last message that the new sequencer must order. * @param sequencer The new sequencer. */ public TotalHybridHeader(int source,int from, int to, int sequencer){ this.type=REASSING; this.source=source; this.sequencer=sequencer; this.from=from; this.to=to; this.tickets=new Ticket[0]; this.sequence=-1; } /** * Construct an header for messages only with ticket information * @param t array of tickets */ public TotalHybridHeader(Ticket[] t){ this.type= PERIODIC; this.tickets=t; this.source=-1; this.sequencer=-1; this.from=-1; this.to=-1; this.sequence=-1; } /** * Contructs a PENDING header * @param source source of the message * @param seq sequence of the message */ public TotalHybridHeader(int source, int seq){ this.type = PENDING; this.source = source; this.sequence = seq; } /** * Contructs a header from a Appia Message * @param om Appia Message * @param f source */ public TotalHybridHeader(Message om, int f){ type = om.popInt(); source = f; sequence = om.popInt(); sequencer = om.popInt(); from = om.popInt(); to = om.popInt(); int tid, idsource, idseq; int size = om.popInt(); if(size!=-1){ tickets = new Ticket[size]; for(int i=0 ; i!=tickets.length ; i++){ idseq = om.popInt(); idsource = om.popInt(); tid = om.popInt(); tickets[i] = new Ticket(f,tid,new MsgId(idsource,idseq)); } } else tickets = new Ticket[0]; } /** * Return the type of the event. * @return Type of the event. */ public int getType(){ return type; } /** * Return the rank of the sender of the event. * @return Sender of the event. */ public int getSource(){ return source; } /** * Return the sequence number of the event * @return Sequence number. */ public int getSequence(){ return sequence; } /** * Return the new sequencer of a set of messages. * This should only be used in REASSING events. * @return The new Sequencer. */ public int getSequencer(){ return sequencer; } /** * Return an array of tickets. * @return Tickets. */ public Ticket[] getTickets(){ return tickets; } /** * Return the first message that the sequencer must change. * Only to be used by the REASSING event. * @return The first message. */ public int getFrom(){ return from; } /** * Return the last message that the sequencer must change. * Only to be used by the REASSING event. * @return The last message. * */ public int getTo(){ return to; } /** * Change the sequencer of an event. * @param newseq The new sequencer. */ public void setSequencer(int newseq){ sequencer=newseq; } /** * Serializes the header into an Appia Message * @param om Appia Message where to put the header information */ public void writeHeader(Message om){ if(tickets!=null){ for(int i=tickets.length-1;i>=0;i--){ om.pushInt(tickets[i].getTicketId()); om.pushInt(tickets[i].getMsgId().getSource()); om.pushInt(tickets[i].getMsgId().getSequence()); } om.pushInt(tickets.length); } else om.pushInt(-1); om.pushInt(to); om.pushInt(from); om.pushInt(sequencer); om.pushInt(sequence); om.pushInt(type); } }
{ "content_hash": "561111264f04b8ddb6931059ecdffeef", "timestamp": "", "source": "github", "line_count": 246, "max_line_length": 90, "avg_line_length": 21.32520325203252, "alnum_prop": 0.6675562333206252, "repo_name": "wmalik/appia-byzantine", "id": "11f55031eefdc9a633c628cc73939f4e832a5c58", "size": "5246", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/groupcomm/net/sf/appia/protocols/total/hybrid/TotalHybridHeader.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1920874" }, { "name": "Shell", "bytes": "1887" } ], "symlink_target": "" }
module Mongoid module Extensions module Array # Evolve the array into an array of object ids. # # @example Evolve the array to object ids. # [ id ].__evolve_object_id__ # # @return [ Array<BSON::ObjectId> ] The converted array. # # @since 3.0.0 def __evolve_object_id__ map!(&:__evolve_object_id__) self end # Get the array of args as arguments for a find query. # # @example Get the array as find args. # [ 1, 2, 3 ].__find_args__ # # @return [ Array ] The array of args. # # @since 3.0.0 def __find_args__ flat_map{ |a| a.__find_args__ }.uniq{ |a| a.to_s } end # Mongoize the array into an array of object ids. # # @example Evolve the array to object ids. # [ id ].__mongoize_object_id__ # # @return [ Array<BSON::ObjectId> ] The converted array. # # @since 3.0.0 def __mongoize_object_id__ map!(&:__mongoize_object_id__).compact! self end # Converts the array for storing as a time. # # @note Returns a local time in the default time zone. # # @example Convert the array to a time. # [ 2010, 1, 1 ].__mongoize_time__ # # => 2010-01-01 00:00:00 -0500 # # @return [ Time | ActiveSupport::TimeWithZone ] Local time in the # configured default time zone corresponding to date/time components # in this array. # # @since 3.0.0 def __mongoize_time__ ::Time.configured.local(*self) end # Check if the array is part of a blank association criteria. # # @example Is the array blank criteria? # [].blank_criteria? # # @return [ true, false ] If the array is blank criteria. # # @since 3.1.0 def blank_criteria? any?(&:blank_criteria?) end # Is the array a set of multiple arguments in a method? # # @example Is this multi args? # [ 1, 2, 3 ].multi_arged? # # @return [ true, false ] If the array is multi args. # # @since 3.0.0 def multi_arged? !first.is_a?(Hash) && first.resizable? || size > 1 end # Turn the object from the ruby type we deal with to a Mongo friendly # type. # # @example Mongoize the object. # object.mongoize # # @return [ Array ] The object. # # @since 3.0.0 def mongoize ::Array.mongoize(self) end # Delete the first object in the array that is equal to the supplied # object and return it. This is much faster than performing a standard # delete for large arrays ince it attempt to delete multiple in the # other. # # @example Delete the first object. # [ "1", "2", "1" ].delete_one("1") # # @param [ Object ] object The object to delete. # # @return [ Object ] The deleted object. # # @since 2.1.0 def delete_one(object) position = index(object) position ? delete_at(position) : nil end # Is the object's size changable? # # @example Is the object resizable? # object.resizable? # # @return [ true ] true. # # @since 3.0.0 def resizable? true end module ClassMethods # Convert the provided object to a proper array of foreign keys. # # @example Mongoize the object. # Array.__mongoize_fk__(constraint, object) # # @param [ Association ] association The association metadata. # @param [ Object ] object The object to convert. # # @return [ Array ] The array of ids. # # @since 3.0.0 def __mongoize_fk__(association, object) if object.resizable? object.blank? ? object : association.convert_to_foreign_key(object) else object.blank? ? [] : association.convert_to_foreign_key(Array(object)) end end # Turn the object from the ruby type we deal with to a Mongo friendly # type. # # @example Mongoize the object. # Array.mongoize([ 1, 2, 3 ]) # # @param [ Object ] object The object to mongoize. # # @return [ Array ] The object mongoized. # # @since 3.0.0 def mongoize(object) if object.is_a?(::Array) evolve(object).collect{ |obj| obj.class.mongoize(obj) } else evolve(object) end end # Is the object's size changable? # # @example Is the object resizable? # Array.resizable? # # @return [ true ] true. # # @since 3.0.0 def resizable? true end end end end end ::Array.__send__(:include, Mongoid::Extensions::Array) ::Array.extend(Mongoid::Extensions::Array::ClassMethods)
{ "content_hash": "d2ac8e42f47fa94a38a16ed2567aad6d", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 82, "avg_line_length": 27.516304347826086, "alnum_prop": 0.5297254592139048, "repo_name": "Welovroi/mongoid", "id": "4d92dfdf034cb8a0b18ae740429bde75341e27fa", "size": "5111", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/mongoid/extensions/array.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "3607617" }, { "name": "Shell", "bytes": "3961" } ], "symlink_target": "" }
import { render } from "@testing-library/react"; import { Footer } from "./Footer"; import { versionService } from "services"; jest.mock("services"); beforeEach(() => { jest.clearAllMocks(); }); test("renders version data", async () => { (versionService.getVersion as jest.Mock).mockResolvedValueOnce({ buildDate: "testDate", buildSha: "testSha" }); const { getByText, findByText, findAllByRole } = render(<Footer />); const info = getByText(/Bootzooka - application scaffolding by /); await findAllByRole("loader"); const buildSha = await findByText(/testSha/i); expect(versionService.getVersion).toBeCalledWith(); expect(info).toBeInTheDocument(); expect(buildSha).toBeInTheDocument(); });
{ "content_hash": "a747717aa95822d2f0982733a26bc417", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 113, "avg_line_length": 28.72, "alnum_prop": 0.7075208913649025, "repo_name": "softwaremill/bootzooka", "id": "18267a74fe78b64b2501c0baade0ff36ec067866", "size": "718", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ui/src/main/Footer/Footer.test.tsx", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "33" }, { "name": "CSS", "bytes": "38" }, { "name": "HTML", "bytes": "1733" }, { "name": "Mustache", "bytes": "1091" }, { "name": "Scala", "bytes": "111696" }, { "name": "Shell", "bytes": "76" }, { "name": "TypeScript", "bytes": "83350" } ], "symlink_target": "" }
class Vote < ActiveRecord::Base # Remember to create a migration! belongs_to :user belongs_to :votable, polymorphic: true end
{ "content_hash": "f0e053aadfebbd3b3a72e3ad2b6a7867", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 40, "avg_line_length": 26.4, "alnum_prop": 0.7424242424242424, "repo_name": "hanniedong/DBC_Overflow", "id": "e3449f56e1edd5c5cf322f1f7e8483a41d6dab40", "size": "132", "binary": false, "copies": "1", "ref": "refs/heads/development_branch", "path": "dbc_overflow/app/models/vote.rb", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "7979" }, { "name": "JavaScript", "bytes": "283" }, { "name": "Ruby", "bytes": "19678" } ], "symlink_target": "" }
package report; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.concurrent.TimeUnit; import javax.swing.JOptionPane; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class emulator { WebDriver driver; public void setUp() throws MalformedURLException { DesiredCapabilities capabilities= new DesiredCapabilities(); capabilities.setCapability(CapabilityType.BROWSER_NAME,"Google Chrome"); capabilities.setCapability(CapabilityType.VERSION,"4.4.4"); capabilities.setCapability(CapabilityType.PLATFORM,"windows"); capabilities.setCapability("platformName","Android"); capabilities.setCapability("devices","Android"); capabilities.setCapability("avd","samsung"); capabilities.setCapability("deviceName",""); capabilities.setCapability("appPackage", "com.android.googlechrome"); capabilities.setCapability("appActivity", "com.android.googlechrome.BrowserActivity"); driver=new RemoteWebDriver(new URL("http://google.com"), capabilities); } public void cal(){ driver.get("http://www.google.com"); } public static void main(String[] args) throws MalformedURLException { emulator a=new emulator(); a.setUp(); a.cal(); } }
{ "content_hash": "fd1b136bc8d52453682bc6bf7dee47c1", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 89, "avg_line_length": 31.470588235294116, "alnum_prop": 0.794392523364486, "repo_name": "NodeAndroidjs/AndroidUtils", "id": "8336a7fa620788eafcaa0313b0820ae2b8eba93f", "size": "1607", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Emulator.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1658" }, { "name": "Shell", "bytes": "187" } ], "symlink_target": "" }
<?php /** * DO NOT EDIT THIS FILE! * * This file was automatically generated from external sources. * * Any manual change here will be lost the next time the SDK * is updated. You've been warned! */ namespace DTS\eBaySDK\Test\PostOrder\Types; use DTS\eBaySDK\PostOrder\Types\GetCaseRestRequest; class GetCaseRestRequestTest extends \PHPUnit_Framework_TestCase { private $obj; protected function setUp() { $this->obj = new GetCaseRestRequest(); } public function testCanBeCreated() { $this->assertInstanceOf('\DTS\eBaySDK\PostOrder\Types\GetCaseRestRequest', $this->obj); } public function testExtendsBaseType() { $this->assertInstanceOf('\DTS\eBaySDK\Types\BaseType', $this->obj); } }
{ "content_hash": "3624f5869cab41ca9c4128b505ea04d8", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 95, "avg_line_length": 23.09090909090909, "alnum_prop": 0.6876640419947506, "repo_name": "davidtsadler/ebay-sdk-php", "id": "eddf5bf92ac4bb05cc16790247c890a3a77d3f66", "size": "762", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/PostOrder/Types/GetCaseRestRequestTest.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "10944" }, { "name": "PHP", "bytes": "9958599" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "57cac49cf7459dc910a00b632ed22f63", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "11ce3f3839f40d34aee738a4469402944c033d1b", "size": "197", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Mitracarpus/Mitracarpus megapotamicus/Mitracarpus sellowianus tenella/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import unittest from .test_oauth import UAOauth2ClientTest def suite(): tests = ['UAOauth2ClientTest'] return unittest.TestSuite(map(WidgetTestCase, tests)) if __name__ == '__main__': suite()
{ "content_hash": "a8b5d2a16cb1fb15bc0cb2e7d09da841", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 57, "avg_line_length": 20.7, "alnum_prop": 0.6859903381642513, "repo_name": "igorfala/python-under-armour", "id": "1f953934f7e77a792a7a271571302e4b3a8a7d11", "size": "207", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "15601" } ], "symlink_target": "" }
using System.Data; using System.Data.SqlClient; using Appleseed.Framework.Settings; namespace Appleseed.Framework.Content.Data { /// <summary> /// Appleseed EnhancedHtml Module /// Written by: José Viladiu, [email protected] /// Class that encapsulates all data logic necessary to add/query/delete /// EnhancedHtml Pages within the Portal database. /// </summary> public class EnhancedHtmlDB { /// <summary> /// The GetAllPages method returns a SqlDataReader containing all of the /// pages for a specific portal module from database. /// </summary> /// <param name="moduleID">The module ID.</param> /// <param name="version">The version.</param> /// <returns></returns> public SqlDataReader GetAllPages(int moduleID, WorkFlowVersion version) { SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetEnhancedHtml", myConnection); myCommand.CommandType = CommandType.StoredProcedure; SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterWorkflowVersion = new SqlParameter("@WorkflowVersion", SqlDbType.Int, 4); parameterWorkflowVersion.Value = (int) version; myCommand.Parameters.Add(parameterWorkflowVersion); myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); return result; } /// <summary> /// The GetAllPages method returns a SqlDataReader containing all of the /// pages for a specific portal module from database. /// </summary> /// <param name="moduleID">The module ID.</param> /// <param name="cultureCode">The culture code.</param> /// <param name="version">The version.</param> /// <returns></returns> public SqlDataReader GetLocalizedPages(int moduleID, int cultureCode, WorkFlowVersion version) { SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetEnhancedLocalizedHtml", myConnection); myCommand.CommandType = CommandType.StoredProcedure; SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterCultureCode = new SqlParameter("@CultureCode", SqlDbType.Int, 4); parameterCultureCode.Value = cultureCode; myCommand.Parameters.Add(parameterCultureCode); SqlParameter parameterWorkflowVersion = new SqlParameter("@WorkflowVersion", SqlDbType.Int, 4); parameterWorkflowVersion.Value = (int) version; myCommand.Parameters.Add(parameterWorkflowVersion); myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); return result; } /// <summary> /// The GetSinglePage method returns a SqlDataReader containing details /// about a specific page from the EnhancedHtml database table. /// </summary> /// <param name="itemID">The item ID.</param> /// <param name="version">The version.</param> /// <returns></returns> public SqlDataReader GetSinglePage(int itemID, WorkFlowVersion version) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetSingleEnhancedHtml", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = itemID; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterWorkflowVersion = new SqlParameter("@WorkflowVersion", SqlDbType.Int, 4); parameterWorkflowVersion.Value = (int) version; myCommand.Parameters.Add(parameterWorkflowVersion); // Execute the command myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); // Return the datareader return result; } /// <summary> /// The DeleteLink method deletes a specified page from /// the EnhancedHtml database table. /// </summary> /// <param name="itemID">The item ID.</param> public void DeletePage(int itemID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_DeleteEnhancedHtml", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = itemID; myCommand.Parameters.Add(parameterItemID); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } } /// <summary> /// The AddPage method adds a new page within the /// EnhancedHtml database table, and returns ItemID value as a result. /// </summary> /// <param name="moduleID">The module ID.</param> /// <param name="itemID">The item ID.</param> /// <param name="userName">Name of the user.</param> /// <param name="title">The title.</param> /// <param name="viewOrder">The view order.</param> /// <param name="cultureCode">The culture code.</param> /// <param name="desktopHtml">The desktop HTML.</param> /// <returns></returns> public int AddPage(int moduleID, int itemID, string userName, string title, int viewOrder, int cultureCode, string desktopHtml) { if (userName.Length < 1) { userName = "unknown"; } // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_AddEnhancedHtml", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterUserName = new SqlParameter("@UserName", SqlDbType.NVarChar, 100); parameterUserName.Value = userName; myCommand.Parameters.Add(parameterUserName); SqlParameter parameterTitle = new SqlParameter("@Title", SqlDbType.NVarChar, 100); parameterTitle.Value = title; myCommand.Parameters.Add(parameterTitle); SqlParameter parameterViewOrder = new SqlParameter("@ViewOrder", SqlDbType.Int, 4); parameterViewOrder.Value = viewOrder; myCommand.Parameters.Add(parameterViewOrder); SqlParameter parameterCultureCode = new SqlParameter("@CultureCode", SqlDbType.Int, 4); parameterCultureCode.Value = cultureCode; myCommand.Parameters.Add(parameterCultureCode); SqlParameter parameterDesktopHtml = new SqlParameter("@DesktopHtml", SqlDbType.NText); parameterDesktopHtml.Value = desktopHtml; myCommand.Parameters.Add(parameterDesktopHtml); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return (int) parameterItemID.Value; } /// <summary> /// The UpdateLink method updates a specified page within /// the EnhancedHtml database table. /// </summary> /// <param name="moduleID">The module ID.</param> /// <param name="itemID">The item ID.</param> /// <param name="userName">Name of the user.</param> /// <param name="title">The title.</param> /// <param name="viewOrder">The view order.</param> /// <param name="cultureCode">The culture code.</param> /// <param name="desktopHtml">The desktop HTML.</param> public void UpdatePage(int moduleID, int itemID, string userName, string title, int viewOrder, int cultureCode, string desktopHtml) { if (userName.Length < 1) { userName = "unknown"; } // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_UpdateEnhancedHtml", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = itemID; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterUserName = new SqlParameter("@UserName", SqlDbType.NVarChar, 100); parameterUserName.Value = userName; myCommand.Parameters.Add(parameterUserName); SqlParameter parameterTitle = new SqlParameter("@Title", SqlDbType.NVarChar, 100); parameterTitle.Value = title; myCommand.Parameters.Add(parameterTitle); SqlParameter parameterViewOrder = new SqlParameter("@ViewOrder", SqlDbType.Int, 4); parameterViewOrder.Value = viewOrder; myCommand.Parameters.Add(parameterViewOrder); SqlParameter parameterCultureCode = new SqlParameter("@CultureCode", SqlDbType.Int, 4); parameterCultureCode.Value = cultureCode; myCommand.Parameters.Add(parameterCultureCode); SqlParameter parameterDesktopHtml = new SqlParameter("@DesktopHtml", SqlDbType.NText); parameterDesktopHtml.Value = desktopHtml; myCommand.Parameters.Add(parameterDesktopHtml); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } } } }
{ "content_hash": "7f572dc3728b57bcf83d1b6d1c546776", "timestamp": "", "source": "github", "line_count": 269, "max_line_length": 119, "avg_line_length": 42.37918215613383, "alnum_prop": 0.6212280701754386, "repo_name": "Appleseed/portal", "id": "4e0f3f26b7864a364f95550d019243f91b94d502", "size": "11400", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Master/Appleseed/Projects/Appleseed.Framework/DAL/Modules/EnhancedHtmlDB.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "701416" }, { "name": "Batchfile", "bytes": "5824" }, { "name": "C#", "bytes": "5437355" }, { "name": "CSS", "bytes": "3097267" }, { "name": "ColdFusion", "bytes": "166069" }, { "name": "Gherkin", "bytes": "225" }, { "name": "HTML", "bytes": "1084272" }, { "name": "JavaScript", "bytes": "5781627" }, { "name": "Lasso", "bytes": "34435" }, { "name": "PHP", "bytes": "111194" }, { "name": "PLpgSQL", "bytes": "353788" }, { "name": "Perl", "bytes": "38719" }, { "name": "Perl 6", "bytes": "25708" }, { "name": "PowerShell", "bytes": "3737" }, { "name": "Python", "bytes": "46471" }, { "name": "SQLPL", "bytes": "6479" }, { "name": "Smalltalk", "bytes": "25790" }, { "name": "XSLT", "bytes": "39762" } ], "symlink_target": "" }
require File.expand_path('../../spec_helper.rb', __FILE__) describe 'Backup::Configuration::Store' do let(:store) { Backup::Configuration::Store.new } before do store.foo = 'one' store.bar = 'two' end it 'should be a subclass of OpenStruct' do Backup::Configuration::Store.superclass.should == OpenStruct end it 'should return nil for unset attributes' do store.foobar.should be_nil end describe '#_attribues' do it 'should return an array of attribute names' do store._attributes.should be_an Array store._attributes.count.should be(2) store._attributes.should include(:foo, :bar) end end describe '#reset!' do it 'should clear all attributes set' do store.reset! store._attributes.should be_an Array store._attributes.should be_empty store.foo.should be_nil store.bar.should be_nil end end end
{ "content_hash": "4f1d3da7cb08f1676ff2a0777b6e53ad", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 64, "avg_line_length": 24.45945945945946, "alnum_prop": 0.6685082872928176, "repo_name": "bernd/backup", "id": "189c66a6ab3fcc361d4904d72826acd88cb38398", "size": "924", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "spec/configuration/store_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "997755" }, { "name": "Shell", "bytes": "1692" } ], "symlink_target": "" }
package org.apache.storm.daemon.drpc; import org.apache.storm.generated.AuthorizationException; import org.apache.storm.generated.DRPCExecutionException; import org.apache.storm.generated.DRPCRequest; import org.apache.storm.generated.DistributedRPC; import org.apache.storm.generated.DistributedRPCInvocations; public class DRPCThrift implements DistributedRPC.Iface, DistributedRPCInvocations.Iface { private final DRPC _drpc; public DRPCThrift(DRPC drpc) { _drpc = drpc; } @Override public void result(String id, String result) throws AuthorizationException { _drpc.returnResult(id, result); } @Override public DRPCRequest fetchRequest(String functionName) throws AuthorizationException { return _drpc.fetchRequest(functionName); } @Override public void failRequest(String id) throws AuthorizationException { _drpc.failRequest(id, null); } @Override public void failRequestV2(String id, DRPCExecutionException e) throws AuthorizationException { _drpc.failRequest(id, e); } @Override public String execute(String functionName, String funcArgs) throws DRPCExecutionException, AuthorizationException { return _drpc.executeBlocking(functionName, funcArgs); } }
{ "content_hash": "c5839839bf8e68d014d928a19e5cf2e2", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 98, "avg_line_length": 30.186046511627907, "alnum_prop": 0.7419106317411402, "repo_name": "srdo/storm", "id": "01d23924a24cce00cbc821127bdb154b126f9f2e", "size": "2099", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "storm-server/src/main/java/org/apache/storm/daemon/drpc/DRPCThrift.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "53871" }, { "name": "CSS", "bytes": "12597" }, { "name": "Clojure", "bytes": "494628" }, { "name": "Fancy", "bytes": "6234" }, { "name": "FreeMarker", "bytes": "3512" }, { "name": "HTML", "bytes": "187245" }, { "name": "Java", "bytes": "11668041" }, { "name": "JavaScript", "bytes": "74069" }, { "name": "M4", "bytes": "1522" }, { "name": "Makefile", "bytes": "1302" }, { "name": "PowerShell", "bytes": "3405" }, { "name": "Python", "bytes": "954624" }, { "name": "Ruby", "bytes": "15777" }, { "name": "Shell", "bytes": "23774" }, { "name": "Thrift", "bytes": "31552" }, { "name": "XSLT", "bytes": "1365" } ], "symlink_target": "" }
export default class FakeSession { constructor (runResponse, fakeConnection) { this._runResponse = runResponse this._fakeConnection = fakeConnection this._closed = false } static successful (result) { return new FakeSession(Promise.resolve(result), null) } static failed (error) { return new FakeSession(Promise.reject(error), null) } static withFakeConnection (connection) { return new FakeSession(null, connection) } _run (ignoreQuery, ignoreParameters, queryRunner) { if (this._runResponse) { return this._runResponse } queryRunner(this._fakeConnection) return Promise.resolve() } withBookmarks (bookmarks) { this._lastBookmarks = bookmarks return this } withDatabase (database) { this._database = database || '' return this } withMode (mode) { this._mode = mode return this } withOnComplete (onComplete) { this._onComplete = onComplete return this } close () { this._closed = true return Promise.resolve() } isClosed () { return this._closed } }
{ "content_hash": "cf38297481c32252007fa07898b49d7b", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 57, "avg_line_length": 18.896551724137932, "alnum_prop": 0.6587591240875912, "repo_name": "neo4j/neo4j-javascript-driver", "id": "8f37f2aa6c3230a77012cbe9c05031088fbcccbd", "size": "1758", "binary": false, "copies": "1", "ref": "refs/heads/5.0", "path": "packages/neo4j-driver/test/internal/fake-session.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "1904" }, { "name": "HTML", "bytes": "9633" }, { "name": "JavaScript", "bytes": "1917419" }, { "name": "PowerShell", "bytes": "554" }, { "name": "Python", "bytes": "4878" }, { "name": "Shell", "bytes": "579" }, { "name": "TypeScript", "bytes": "984166" } ], "symlink_target": "" }
import Controller from '@ember/controller'; import { run } from '@ember/runloop'; export default Controller.extend({ isLoadingcsv: false, isLoadingpdf: false, actions: { export(mode) { this.set(`isLoading${mode}`, true); this.get('loader') .load(`/events/${this.get('model.id')}/export/attendees/${mode}`) .then(exportJobInfo => { this.requestLoop(exportJobInfo, mode); }) .catch(() => { this.set(`isLoading${mode}`, false); this.get('notify').error(this.get('l10n').t('An unexpected error has occurred.')); }); } }, requestLoop(exportJobInfo, mode) { run.later(() => { this.get('loader') .load(exportJobInfo.task_url, { withoutPrefix: true }) .then(exportJobStatus => { if (exportJobStatus.state === 'SUCCESS') { window.location = exportJobStatus.result.download_url; this.get('notify').success(this.get('l10n').t('Download Ready')); } else if (exportJobStatus.state === 'WAITING') { this.requestLoop(exportJobInfo); this.get('notify').alert(this.get('l10n').t('Task is going on.')); } else { this.get('notify').error(this.get('l10n').t(`${mode.toUpperCase()} Export has failed.`)); } }) .catch(() => { this.get('notify').error(this.get('l10n').t(`${mode.toUpperCase()} Export has failed.`)); }) .finally(() => { this.set('isLoading', false); }); }, 3000); } });
{ "content_hash": "cfb8c9151b9c14da9c5e83560abd7633", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 101, "avg_line_length": 33.891304347826086, "alnum_prop": 0.5458627325208467, "repo_name": "ritikamotwani/open-event-frontend", "id": "94d39f3c65a7a3b9ca6c676f87ee1053daef4ccf", "size": "1559", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "app/controllers/events/view/tickets/attendees.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "35008" }, { "name": "Dockerfile", "bytes": "643" }, { "name": "HTML", "bytes": "392265" }, { "name": "JavaScript", "bytes": "727448" }, { "name": "Shell", "bytes": "3008" } ], "symlink_target": "" }
interface IAllianceChatMessage extends IChatMessage { id_alliance_member: number; } class AllianceChatMessage extends ChatMessage implements IAllianceChatMessage { id_alliance_member: number; constructor(obj: IAllianceChatMessage){ //default constructor super({ id: obj.id, text: obj.text, timestamp: obj.timestamp, }); this.id_alliance_member = obj.id_alliance_member; } public getIdAllianceMember(): number{ return this.id_alliance_member; } public setIdAllianceMember(id_alliance_member: number): void{ this.id_alliance_member = id_alliance_member; } }
{ "content_hash": "368b89fe96052f42957f865346ac5c98", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 79, "avg_line_length": 21.88888888888889, "alnum_prop": 0.7495769881556683, "repo_name": "Bergiu/stadt-land-fluss", "id": "34f7de48a3875b2624287affc0cb910bd985e620", "size": "591", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/App/src/items/alliance_chat_message.class.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "159386" }, { "name": "HTML", "bytes": "15760" }, { "name": "PHP", "bytes": "92590" }, { "name": "Shell", "bytes": "2453" }, { "name": "TypeScript", "bytes": "47559" } ], "symlink_target": "" }
using Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.Azure.Commands.Sql.Database.Model; using Microsoft.Azure.Commands.Sql.Database.Services; using Microsoft.Azure.Commands.Sql.FailoverGroup.Model; using Microsoft.Azure.Commands.Sql.Server.Adapter; using Microsoft.Azure.Commands.Sql.Services; using Microsoft.Azure.Management.Sql.LegacySdk.Models; using System.Collections.Generic; using System.Linq; using Microsoft.Azure.Commands.Common.Authentication.Abstractions; namespace Microsoft.Azure.Commands.Sql.FailoverGroup.Services { /// <summary> /// Adapter for FailoverGroup operations /// </summary> public class AzureSqlFailoverGroupAdapter { /// <summary> /// Gets or sets the AzureEndpointsCommunicator which has all the needed management clients /// </summary> private AzureSqlFailoverGroupCommunicator Communicator { get; set; } /// <summary> /// Gets or sets the Azure profile /// </summary> public IAzureContext Context { get; set; } /// <summary> /// Gets or sets the Azure Subscription /// </summary> private IAzureSubscription _subscription { get; set; } /// <summary> /// Constructs a database adapter /// </summary> /// <param name="profile">The current azure profile</param> /// <param name="subscription">The current azure subscription</param> public AzureSqlFailoverGroupAdapter(IAzureContext context) { _subscription = context.Subscription; Context = context; Communicator = new AzureSqlFailoverGroupCommunicator(Context); } /// <summary> /// Gets an Azure Sql Database FailoverGroup by name. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="failoverGroupName">The name of the Azure Sql Database FailoverGroup</param> /// <returns>The Azure Sql Database FailoverGroup object</returns> internal AzureSqlFailoverGroupModel GetFailoverGroup(string resourceGroupName, string serverName, string failoverGroupName) { var resp = Communicator.Get(resourceGroupName, serverName, failoverGroupName); return CreateFailoverGroupModelFromResponse(resp); } /// <summary> /// Gets a list of Azure Sql Databases FailoverGroup. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <returns>A list of database objects</returns> internal ICollection<AzureSqlFailoverGroupModel> ListFailoverGroups(string resourceGroupName, string serverName) { var resp = Communicator.List(resourceGroupName, serverName); return resp.Select((db) => { return CreateFailoverGroupModelFromResponse(db); }).ToList(); } /// <summary> /// Creates or updates an Azure Sql Database FailoverGroup. /// </summary> /// <param name="resourceGroup">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="model">The input parameters for the create/update operation</param> /// <returns>The upserted Azure Sql Database FailoverGroup</returns> internal AzureSqlFailoverGroupModel UpsertFailoverGroup(AzureSqlFailoverGroupModel model) { List < FailoverGroupPartnerServer > partnerServers = new List<FailoverGroupPartnerServer>(); FailoverGroupPartnerServer partnerServer = new FailoverGroupPartnerServer(); partnerServer.Id = string.Format( AzureSqlFailoverGroupModel.PartnerServerIdTemplate, _subscription.Id.ToString(), model.PartnerResourceGroupName, model.PartnerServerName); partnerServers.Add(partnerServer); ReadOnlyEndpoint readOnlyEndpoint = new ReadOnlyEndpoint(); readOnlyEndpoint.FailoverPolicy = model.ReadOnlyFailoverPolicy; ReadWriteEndpoint readWriteEndpoint = new ReadWriteEndpoint(); readWriteEndpoint.FailoverPolicy = model.ReadWriteFailoverPolicy; if (model.FailoverWithDataLossGracePeriodHours.HasValue) { readWriteEndpoint.FailoverWithDataLossGracePeriodMinutes = checked(model.FailoverWithDataLossGracePeriodHours * 60); } var resp = Communicator.CreateOrUpdate(model.ResourceGroupName, model.ServerName, model.FailoverGroupName, new FailoverGroupCreateOrUpdateParameters() { Location = model.Location, Properties = new FailoverGroupCreateOrUpdateProperties() { PartnerServers = partnerServers, ReadOnlyEndpoint = readOnlyEndpoint, ReadWriteEndpoint = readWriteEndpoint, } }); return CreateFailoverGroupModelFromResponse(resp); } /// <summary> /// Patch updates an Azure Sql Database FailoverGroup. /// </summary> /// <param name="resourceGroup">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="model">The input parameters for the create/update operation</param> /// <returns>The upserted Azure Sql Database FailoverGroup</returns> internal AzureSqlFailoverGroupModel PatchUpdateFailoverGroup(AzureSqlFailoverGroupModel model) { ReadOnlyEndpoint readOnlyEndpoint = new ReadOnlyEndpoint(); readOnlyEndpoint.FailoverPolicy = model.ReadOnlyFailoverPolicy; ReadWriteEndpoint readWriteEndpoint = new ReadWriteEndpoint(); readWriteEndpoint.FailoverPolicy = model.ReadWriteFailoverPolicy; if (model.FailoverWithDataLossGracePeriodHours.HasValue) { readWriteEndpoint.FailoverWithDataLossGracePeriodMinutes = checked(model.FailoverWithDataLossGracePeriodHours * 60); } var resp = Communicator.PatchUpdate(model.ResourceGroupName, model.ServerName, model.FailoverGroupName, new FailoverGroupPatchUpdateParameters() { Location = model.Location, Properties = new FailoverGroupPatchUpdateProperties() { ReadOnlyEndpoint = readOnlyEndpoint, ReadWriteEndpoint = readWriteEndpoint, } }); return CreateFailoverGroupModelFromResponse(resp); } /// <summary> /// Deletes a failvoer group /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="failvoerGroupName">The name of the Azure SQL Database Failover Group to delete</param> public void RemoveFailoverGroup(string resourceGroupName, string serverName, string failoverGroupName) { Communicator.Remove(resourceGroupName, serverName, failoverGroupName); } /// <summary> /// Gets a list of Azure Sql Databases in a secondary server. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <returns>A list of database objects</returns> internal ICollection<AzureSqlDatabaseModel> ListDatabasesOnServer(string resourceGroupName, string serverName) { var resp = Communicator.ListDatabasesOnServer(resourceGroupName, serverName); return resp.Select((db) => { return AzureSqlDatabaseAdapter.CreateDatabaseModelFromResponse(resourceGroupName, serverName, db); }).ToList(); } /// <summary> /// Patch updates an Azure Sql Database FailoverGroup. /// </summary> /// <param name="resourceGroup">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="model">The input parameters for the create/update operation</param> /// <returns>The updated Azure Sql Database FailoverGroup</returns> internal AzureSqlFailoverGroupModel AddOrRemoveDatabaseToFailoverGroup(string resourceGroupName, string serverName, string failoverGroupName, AzureSqlFailoverGroupModel model) { var resp = Communicator.PatchUpdate(resourceGroupName, serverName, failoverGroupName, new FailoverGroupPatchUpdateParameters() { Location = model.Location, Properties = new FailoverGroupPatchUpdateProperties() { Databases = model.Databases, } }); return CreateFailoverGroupModelFromResponse(resp); } /// <summary> /// Finds and removes the Secondary Link by the secondary resource group and Azure SQL Server /// </summary> /// <param name="resourceGroupName">The name of the Resource Group containing the primary database</param> /// <param name="serverName">The name of the Azure SQL Server containing the primary database</param> /// <param name="databaseName">The name of primary database</param> /// <param name="partnerResourceGroupName">The name of the Resource Group containing the secondary database</param> /// <param name="partnerServerName">The name of the Azure SQL Server containing the secondary database</param> /// <param name="allowDataLoss">Whether the failover operation will allow data loss</param> /// <returns>The Azure SQL Database ReplicationLink object</returns> internal AzureSqlFailoverGroupModel Failover(string resourceGroupName, string serverName, string failoverGroupName, bool allowDataLoss) { if (!allowDataLoss) { Communicator.Failover(resourceGroupName, serverName, failoverGroupName); } else { Communicator.ForceFailoverAllowDataLoss(resourceGroupName, serverName, failoverGroupName); } return null; } /// <summary> /// Gets the Location of the server. /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the server</param> /// <returns></returns> public string GetServerLocation(string resourceGroupName, string serverName) { AzureSqlServerAdapter serverAdapter = new AzureSqlServerAdapter(Context); var server = serverAdapter.GetServer(resourceGroupName, serverName); return server.Location; } /// <summary> /// Converts the response from the service to a powershell database object /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="pool">The service response</param> /// <returns>The converted model</returns> private AzureSqlFailoverGroupModel CreateFailoverGroupModelFromResponse(Management.Sql.LegacySdk.Models.FailoverGroup failoverGroup) { AzureSqlFailoverGroupModel model = new AzureSqlFailoverGroupModel(); model.FailoverGroupName = failoverGroup.Name; model.Databases = failoverGroup.Properties.Databases; model.ReadOnlyFailoverPolicy = failoverGroup.Properties.ReadOnlyEndpoint.FailoverPolicy; model.ReadWriteFailoverPolicy = failoverGroup.Properties.ReadWriteEndpoint.FailoverPolicy; model.ReplicationRole = failoverGroup.Properties.ReplicationRole; model.ReplicationState = failoverGroup.Properties.ReplicationState; model.PartnerServers = failoverGroup.Properties.PartnerServers; model.FailoverWithDataLossGracePeriodHours = failoverGroup.Properties.ReadWriteEndpoint.FailoverWithDataLossGracePeriodMinutes == null ? null : failoverGroup.Properties.ReadWriteEndpoint.FailoverWithDataLossGracePeriodMinutes / 60; model.Id = failoverGroup.Id; model.Location = failoverGroup.Location; model.DatabaseNames = failoverGroup.Properties.Databases .Select(dbId => GetUriSegment(dbId, 10)) .ToList(); model.ResourceGroupName = GetUriSegment(failoverGroup.Id, 4); model.ServerName = GetUriSegment(failoverGroup.Id, 8); FailoverGroupPartnerServer partnerServer = failoverGroup.Properties.PartnerServers.FirstOrDefault(); if (partnerServer != null) { model.PartnerResourceGroupName = GetUriSegment(partnerServer.Id, 4); model.PartnerServerName = GetUriSegment(partnerServer.Id, 8); model.PartnerLocation = partnerServer.Location; } return model; } private string GetUriSegment(string uri, int segmentNum) { if (uri != null) { var segments = uri.Split('/'); if (segments.Length > segmentNum) { return segments[segmentNum]; } } return null; } } }
{ "content_hash": "d0bedc2bf845caba3f518f20644bd55d", "timestamp": "", "source": "github", "line_count": 293, "max_line_length": 183, "avg_line_length": 48.12627986348123, "alnum_prop": 0.6511594922345932, "repo_name": "devigned/azure-powershell", "id": "eeaf12029d57e0b901cb07867ba32335756472fc", "size": "14857", "binary": false, "copies": "14", "ref": "refs/heads/preview", "path": "src/ResourceManager/Sql/Commands.Sql/Failover Group/Services/AzureSqlFailoverGroupAdapter.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "18388" }, { "name": "C#", "bytes": "60706952" }, { "name": "HTML", "bytes": "209" }, { "name": "JavaScript", "bytes": "4979" }, { "name": "PHP", "bytes": "41" }, { "name": "PowerShell", "bytes": "7187413" }, { "name": "Ruby", "bytes": "398" }, { "name": "Shell", "bytes": "50" }, { "name": "Smalltalk", "bytes": "2510" }, { "name": "XSLT", "bytes": "6114" } ], "symlink_target": "" }
/*************************************************************************************************/ /*! * \brief ATT client optional read PDU processing functions. */ /*************************************************************************************************/ #include <string.h> #include "wsf_types.h" #include "wsf_assert.h" #include "wsf_trace.h" #include "wsf_msg.h" #include "util/bstream.h" #include "att_api.h" #include "att_main.h" #include "attc_main.h" /*************************************************************************************************/ /*! * \brief Process received Find By Type response packet. * * \param pCcb Connection control block. * \param len The length of the L2CAP payload data in pPacket. * \param pPacket A buffer containing the packet. * \param pEvt Pointer to callback event structure. * * \return None. */ /*************************************************************************************************/ void attcProcFindByTypeRsp(attcCcb_t *pCcb, uint16_t len, uint8_t *pPacket, attEvt_t *pEvt) { uint8_t *p; uint8_t *pEnd; uint16_t startHandle; uint16_t endHandle; uint16_t nextHandle; p = pPacket + L2C_PAYLOAD_START + ATT_HDR_LEN; pEnd = pPacket + L2C_PAYLOAD_START + len; /* get and verify all handles */ nextHandle = pCcb->outReqParams.h.startHandle; while (p < pEnd) { /* get handle pair */ BSTREAM_TO_UINT16(startHandle, p); BSTREAM_TO_UINT16(endHandle, p); /* * start handle of handle pair must be: * not greater than end handle of handle pair * not less than than start handle of request or end handle of previous handle pair * not greater than end handle of request * and no additional handle pairs following end handle = 0xFFFF */ if ((startHandle > endHandle) || (startHandle < nextHandle) || (startHandle > pCcb->outReqParams.h.endHandle) || (nextHandle == 0)) { pEvt->hdr.status = ATT_ERR_INVALID_RSP; break; } /* set next expected handle, with special case for max handle */ if (endHandle == ATT_HANDLE_MAX) { nextHandle = 0; } else { nextHandle = endHandle + 1; } /* check for truncated response */ if (p > pEnd) { pEvt->hdr.status = ATT_ERR_INVALID_RSP; break; } } /* if response was correct */ if (pEvt->hdr.status == ATT_SUCCESS) { /* if continuing */ if (pCcb->outReq.hdr.status == ATTC_CONTINUING) { /* if all handles read */ if (nextHandle == 0 || nextHandle > pCcb->outReqParams.h.endHandle) { /* we're done */ pCcb->outReq.hdr.status = ATTC_NOT_CONTINUING; } /* else set up for next request */ else { pCcb->outReqParams.h.startHandle = nextHandle; pCcb->outReq.handle = nextHandle; } } } } /*************************************************************************************************/ /*! * \brief Process received Read Long response packet. * * \param pCcb Connection control block. * \param len The length of the L2CAP payload data in pPacket. * \param pPacket A buffer containing the packet. * \param pEvt Pointer to callback event structure. * * \return None. */ /*************************************************************************************************/ void attcProcReadLongRsp(attcCcb_t *pCcb, uint16_t len, uint8_t *pPacket, attEvt_t *pEvt) { /* if continuing */ if (pCcb->outReq.hdr.status == ATTC_CONTINUING) { /* length of response is less than mtu */ if (len < pCcb->pMainCcb->mtu) { /* we're done */ pCcb->outReq.hdr.status = ATTC_NOT_CONTINUING; } /* else set up for next request */ else { pCcb->outReqParams.o.offset += pEvt->valueLen; } } } /*************************************************************************************************/ /*! * \brief Initiate an attribute protocol Find By Type Value Request. * * \param connId DM connection ID. * \param startHandle Attribute start handle. * \param endHandle Attribute end handle. * \param uuid16 16-bit UUID to find. * \param valueLen Length of value data. * \param pValue Pointer to value data. * \param continuing TRUE if ATTC continues sending requests until complete. * * \return None. */ /*************************************************************************************************/ void AttcFindByTypeValueReq(dmConnId_t connId, uint16_t startHandle, uint16_t endHandle, uint16_t uuid16, uint16_t valueLen, uint8_t *pValue, bool_t continuing) { attcPktParam_t *pPkt; uint8_t *p; /* allocate packet and parameter buffer */ if ((pPkt = attMsgAlloc(ATT_FIND_TYPE_REQ_BUF_LEN + valueLen)) != NULL) { /* set parameters */ pPkt->len = ATT_FIND_TYPE_REQ_LEN + valueLen; pPkt->h.startHandle = startHandle; pPkt->h.endHandle = endHandle; /* build partial packet */ p = (uint8_t *) pPkt + L2C_PAYLOAD_START; UINT8_TO_BSTREAM(p, ATT_PDU_FIND_TYPE_REQ); /* skip start and end handle fields */ p += (2 * sizeof(uint16_t)); UINT16_TO_BSTREAM(p, uuid16); memcpy(p, pValue, valueLen); /* send message */ attcSendMsg(connId, startHandle, ATTC_MSG_API_FIND_BY_TYPE_VALUE, pPkt, continuing); } } /*************************************************************************************************/ /*! * \brief Initiate an attribute protocol Read By Type Request. * * \param connId DM connection ID. * \param startHandle Attribute start handle. * \param endHandle Attribute end handle. * \param uuidLen Length of UUID (2 or 16). * \param pUuid Pointer to UUID data. * \param continuing TRUE if ATTC continues sending requests until complete. * * \return None. */ /*************************************************************************************************/ void AttcReadByTypeReq(dmConnId_t connId, uint16_t startHandle, uint16_t endHandle, uint8_t uuidLen, uint8_t *pUuid, bool_t continuing) { attcPktParam_t *pPkt; uint8_t *p; /* allocate packet and parameter buffer */ if ((pPkt = attMsgAlloc(ATT_READ_TYPE_REQ_BUF_LEN + uuidLen)) != NULL) { /* set parameters */ pPkt->len = ATT_READ_TYPE_REQ_LEN + uuidLen; pPkt->h.startHandle = startHandle; pPkt->h.endHandle = endHandle; /* build partial packet */ p = (uint8_t *) pPkt + L2C_PAYLOAD_START; UINT8_TO_BSTREAM(p, ATT_PDU_READ_TYPE_REQ); /* skip start and end handle fields */ p += (2 * sizeof(uint16_t)); memcpy(p, pUuid, uuidLen); /* send message */ attcSendMsg(connId, startHandle, ATTC_MSG_API_READ_BY_TYPE, pPkt, continuing); } } /*************************************************************************************************/ /*! * \brief Initiate an attribute protocol Read Request. * * \param connId DM connection ID. * \param handle Attribute handle. * \param offset Read attribute data starting at this offset. * \param continuing TRUE if ATTC continues sending requests until complete. * * \return None. */ /*************************************************************************************************/ void AttcReadLongReq(dmConnId_t connId, uint16_t handle, uint16_t offset, bool_t continuing) { attcPktParam_t *pPkt; uint8_t *p; /* allocate packet and parameter buffer */ if ((pPkt = attMsgAlloc(ATT_READ_BLOB_REQ_BUF_LEN)) != NULL) { /* set parameters */ pPkt->len = ATT_READ_BLOB_REQ_LEN; pPkt->o.offset = offset; /* build partial packet */ p = (uint8_t *) pPkt + L2C_PAYLOAD_START; UINT8_TO_BSTREAM(p, ATT_PDU_READ_BLOB_REQ); UINT16_TO_BSTREAM(p, handle); /* send message */ attcSendMsg(connId, handle, ATTC_MSG_API_READ_LONG, pPkt, continuing); } } /*************************************************************************************************/ /*! * \brief Initiate an attribute protocol Read Multiple Request. * * \param connId DM connection ID. * \param numHandles Number of handles in attribute handle list. * \param pHandles List of attribute handles. * * \return None. */ /*************************************************************************************************/ void AttcReadMultipleReq(dmConnId_t connId, uint8_t numHandles, uint16_t *pHandles) { attcPktParam_t *pPkt; uint8_t *p; uint16_t handle; /* allocate packet and parameter buffer */ if ((pPkt = attMsgAlloc(ATT_READ_MULT_REQ_BUF_LEN + (numHandles * sizeof(uint16_t)))) != NULL) { /* set length */ pPkt->len = ATT_READ_MULT_REQ_LEN + (numHandles * sizeof(uint16_t)); /* save first handle */ handle = pHandles[0]; /* build packet */ p = (uint8_t *) pPkt + L2C_PAYLOAD_START; UINT8_TO_BSTREAM(p, ATT_PDU_READ_MULT_REQ); while (numHandles--) { UINT16_TO_BSTREAM(p, *pHandles); pHandles++; } /* send message */ attcSendMsg(connId, handle, ATTC_MSG_API_READ_MULTIPLE, pPkt, FALSE); } } /*************************************************************************************************/ /*! * \brief Initiate an attribute protocol Read By Group Type Request. * * \param connId DM connection ID. * \param startHandle Attribute start handle. * \param endHandle Attribute end handle. * \param uuidLen Length of UUID (2 or 16). * \param pUuid Pointer to UUID data. * \param continuing TRUE if ATTC continues sending requests until complete. * * \return None. */ /*************************************************************************************************/ void AttcReadByGroupTypeReq(dmConnId_t connId, uint16_t startHandle, uint16_t endHandle, uint8_t uuidLen, uint8_t *pUuid, bool_t continuing) { attcPktParam_t *pPkt; uint8_t *p; /* allocate packet and parameter buffer */ if ((pPkt = attMsgAlloc(ATT_READ_GROUP_TYPE_REQ_BUF_LEN + uuidLen)) != NULL) { /* set parameters */ pPkt->len = ATT_READ_GROUP_TYPE_REQ_LEN + uuidLen; pPkt->h.startHandle = startHandle; pPkt->h.endHandle = endHandle; /* build partial packet */ p = (uint8_t *) pPkt + L2C_PAYLOAD_START; UINT8_TO_BSTREAM(p, ATT_PDU_READ_GROUP_TYPE_REQ); /* skip start and end handle fields */ p += (2 * sizeof(uint16_t)); memcpy(p, pUuid, uuidLen); /* send message */ attcSendMsg(connId, startHandle, ATTC_MSG_API_READ_BY_GROUP_TYPE, pPkt, continuing); } }
{ "content_hash": "e840458689cd9ad2c34e17e48cce5ed6", "timestamp": "", "source": "github", "line_count": 331, "max_line_length": 99, "avg_line_length": 32.368580060422964, "alnum_prop": 0.5353742766473772, "repo_name": "kjbracey-arm/mbed", "id": "20ad89797d25f391abfc1e1813e9d21952c57913", "size": "11349", "binary": false, "copies": "16", "ref": "refs/heads/master", "path": "features/FEATURE_BLE/targets/TARGET_CORDIO/stack/ble-host/sources/stack/att/attc_read.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "4905917" }, { "name": "C", "bytes": "121674109" }, { "name": "C++", "bytes": "7228843" }, { "name": "CMake", "bytes": "4724" }, { "name": "HTML", "bytes": "1107049" }, { "name": "Makefile", "bytes": "4212" }, { "name": "Objective-C", "bytes": "61382" }, { "name": "Python", "bytes": "1766" } ], "symlink_target": "" }
namespace v8 { namespace internal { namespace interpreter { // Source code position information. class BytecodeSourceInfo final { public: static const int kUninitializedPosition = -1; BytecodeSourceInfo() : position_type_(PositionType::kNone), source_position_(kUninitializedPosition) {} BytecodeSourceInfo(int source_position, bool is_statement) : position_type_(is_statement ? PositionType::kStatement : PositionType::kExpression), source_position_(source_position) { DCHECK_GE(source_position, 0); } // Makes instance into a statement position. void MakeStatementPosition(int source_position) { // Statement positions can be replaced by other statement // positions. For example , "for (x = 0; x < 3; ++x) 7;" has a // statement position associated with 7 but no bytecode associated // with it. Then Next is emitted after the body and has // statement position and overrides the existing one. position_type_ = PositionType::kStatement; source_position_ = source_position; } // Makes instance into an expression position. Instance should not // be a statement position otherwise it could be lost and impair the // debugging experience. void MakeExpressionPosition(int source_position) { DCHECK(!is_statement()); position_type_ = PositionType::kExpression; source_position_ = source_position; } // Forces an instance into an expression position. void ForceExpressionPosition(int source_position) { position_type_ = PositionType::kExpression; source_position_ = source_position; } int source_position() const { DCHECK(is_valid()); return source_position_; } bool is_statement() const { return position_type_ == PositionType::kStatement; } bool is_expression() const { return position_type_ == PositionType::kExpression; } bool is_valid() const { return position_type_ != PositionType::kNone; } void set_invalid() { position_type_ = PositionType::kNone; source_position_ = kUninitializedPosition; } bool operator==(const BytecodeSourceInfo& other) const { return position_type_ == other.position_type_ && source_position_ == other.source_position_; } bool operator!=(const BytecodeSourceInfo& other) const { return position_type_ != other.position_type_ || source_position_ != other.source_position_; } private: enum class PositionType : uint8_t { kNone, kExpression, kStatement }; PositionType position_type_; int source_position_; }; V8_EXPORT_PRIVATE std::ostream& operator<<(std::ostream& os, const BytecodeSourceInfo& info); } // namespace interpreter } // namespace internal } // namespace v8 #endif // V8_INTERPRETER_BYTECODE_SOURCE_INFO_H_
{ "content_hash": "250f8ef706fffc0ad8556c91318d0d7e", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 75, "avg_line_length": 31.95505617977528, "alnum_prop": 0.6838959212376934, "repo_name": "weolar/miniblink49", "id": "790a6b2aa21de1cff4fc6c87c760bc03e4eb6723", "size": "3133", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "v8_7_5/src/interpreter/bytecode-source-info.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "11324372" }, { "name": "Batchfile", "bytes": "52488" }, { "name": "C", "bytes": "32157305" }, { "name": "C++", "bytes": "280103993" }, { "name": "CMake", "bytes": "88548" }, { "name": "CSS", "bytes": "20839" }, { "name": "DIGITAL Command Language", "bytes": "226954" }, { "name": "HTML", "bytes": "202637" }, { "name": "JavaScript", "bytes": "32539485" }, { "name": "Lua", "bytes": "32432" }, { "name": "M4", "bytes": "125191" }, { "name": "Makefile", "bytes": "1517330" }, { "name": "NASL", "bytes": "42" }, { "name": "Objective-C", "bytes": "5320" }, { "name": "Objective-C++", "bytes": "35037" }, { "name": "POV-Ray SDL", "bytes": "307541" }, { "name": "Perl", "bytes": "3283676" }, { "name": "Prolog", "bytes": "29177" }, { "name": "Python", "bytes": "4331616" }, { "name": "R", "bytes": "10248" }, { "name": "Scheme", "bytes": "25457" }, { "name": "Shell", "bytes": "264021" }, { "name": "TypeScript", "bytes": "166033" }, { "name": "Vim Script", "bytes": "11362" }, { "name": "XS", "bytes": "4319" }, { "name": "eC", "bytes": "4383" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <script src="../../../resources/js-test.js"></script> </head> <body> <p>When an option element became 'disabled' or not-'disabled', distribution should happen.</p> <p>Since an option element does not create a renderer, we cannot check this using reftest.</p> <div id="container"> <div id="host1"> <option id="option1">option 1</option> <option id="option2">option 2</option> </div> <div id="host2"> <option id="option3" disabled>option 3</option> <option id="option4" disabled>option 4</option> </div> </div> <pre id="console"></pre> <script> jsTestIsAsync = true; var shadowRoot1 = host1.createShadowRoot(); var shadowRoot2 = host2.createShadowRoot(); shadowRoot1.innerHTML = '<content select=":disabled">'; shadowRoot2.innerHTML = '<content select=":disabled">'; var content1 = shadowRoot1.querySelector('content'); var content2 = shadowRoot2.querySelector('content'); setTimeout(function() { option2.setAttribute('disabled', true); option4.removeAttribute('disabled'); nodes1 = content1.getDistributedNodes(); shouldBe('nodes1.length', '1'); shouldBe('nodes1.item(0).innerHTML', '"option 2"'); nodes2 = content2.getDistributedNodes(); shouldBe('nodes2.length', '1'); shouldBe('nodes2.item(0).innerHTML', '"option 3"'); container.innerHTML = ""; finishJSTest(); }, 0); </script> </body> </html>
{ "content_hash": "961d63b1eb65479ef751e2ec39a8c2f2", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 94, "avg_line_length": 25.517857142857142, "alnum_prop": 0.6655003498950315, "repo_name": "jtg-gg/blink", "id": "da80c9fa9b75427f9f3dda0001e072181ebe7527", "size": "1429", "binary": false, "copies": "10", "ref": "refs/heads/dev12-m41", "path": "LayoutTests/fast/dom/shadow/pseudoclass-update-disabled-option.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "28126" }, { "name": "Assembly", "bytes": "12983" }, { "name": "Bison", "bytes": "64327" }, { "name": "C", "bytes": "68435" }, { "name": "C++", "bytes": "41623716" }, { "name": "CSS", "bytes": "536676" }, { "name": "GLSL", "bytes": "11578" }, { "name": "Groff", "bytes": "28067" }, { "name": "HTML", "bytes": "53137251" }, { "name": "Java", "bytes": "66510" }, { "name": "JavaScript", "bytes": "26485747" }, { "name": "Makefile", "bytes": "677" }, { "name": "Objective-C", "bytes": "46814" }, { "name": "Objective-C++", "bytes": "378647" }, { "name": "PHP", "bytes": "166434" }, { "name": "Perl", "bytes": "585757" }, { "name": "Python", "bytes": "3997910" }, { "name": "Ruby", "bytes": "141818" }, { "name": "Shell", "bytes": "8806" }, { "name": "XSLT", "bytes": "49099" } ], "symlink_target": "" }
namespace RealTime.Web { using System.Web.Optimization; public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); // Set EnableOptimizations to false for debugging. For more information, // visit http://go.microsoft.com/fwlink/?LinkId=301862 BundleTable.EnableOptimizations = true; } } }
{ "content_hash": "787609444c52580c0a6d81fd72246241", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 109, "avg_line_length": 40.26470588235294, "alnum_prop": 0.6070124178232287, "repo_name": "acraven/real-time-web", "id": "2da0d3c55b82d22094a49931af0e96998f839508", "size": "1371", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/RealTime.Web/App_Start/BundleConfig.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "103" }, { "name": "C#", "bytes": "67325" }, { "name": "CSS", "bytes": "513" }, { "name": "JavaScript", "bytes": "19947" } ], "symlink_target": "" }
import Helmet from 'react-helmet'; import React, { Component } from 'react'; import { FormattedMessage, defineMessages } from 'react-intl'; const messages = defineMessages({ title: { defaultMessage: 'Profile', id: 'me.profilePage.title', }, }); export default class ProfilePage extends Component { render() { return ( <div className="profile-page"> <FormattedMessage {...messages.title}> {message => <Helmet title={message} /> } </FormattedMessage> <p> <FormattedMessage {...messages.title} /> </p> </div> ); } }
{ "content_hash": "6e7b2a6b43844d6fe391bb8bf331f5d3", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 62, "avg_line_length": 21.620689655172413, "alnum_prop": 0.5773524720893142, "repo_name": "abelaska/este", "id": "692d921ea12be5c7cdafe043eb9166c0b53de4a5", "size": "627", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/browser/me/ProfilePage.react.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4663" }, { "name": "Java", "bytes": "2254" }, { "name": "JavaScript", "bytes": "223616" }, { "name": "Objective-C", "bytes": "5128" }, { "name": "Python", "bytes": "1633" } ], "symlink_target": "" }
{% extends "registration/registration_base.html" %} {% load i18n %} {% block title %}{% trans "Reset password" %}{% endblock %} {% block main %} <p> {% blocktrans %} Forgot your password? Enter your email in the form below and we'll send you instructions for creating a new one. {% endblocktrans %} </p> <form method="post" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit" value="{% trans 'Reset password' %}" /> </form> {% endblock %} {# This is used by django.contrib.auth #}
{ "content_hash": "e22f25ab10e6f020e34914c585659609", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 117, "avg_line_length": 26.1, "alnum_prop": 0.6168582375478927, "repo_name": "gatita/django-imager", "id": "b71b0ac6022dde04104b2e66f9b33aad787708c9", "size": "522", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "imagersite/imagersite/templates/registration/password_reset_form.html", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "10537" }, { "name": "HTML", "bytes": "27190" }, { "name": "JavaScript", "bytes": "54533" }, { "name": "Python", "bytes": "58895" } ], "symlink_target": "" }
namespace xwalk { namespace extensions { class XWalkExtensionInstance; // This struct is passed to the function handler, usually assigned to the // signature of a method in JavaScript. The struct can be safely passed around. class XWalkExtensionFunctionInfo { public: typedef base::Callback<void(scoped_ptr<base::ListValue> result)> PostResultCallback; XWalkExtensionFunctionInfo(const std::string& name, scoped_ptr<base::ListValue> arguments, const PostResultCallback& post_result_cb); ~XWalkExtensionFunctionInfo(); // Convenience method for posting the results back to the renderer process. // The object identifier is already wrapped at the |post_result_cb|. This // will ultimately dispatch the result to the appropriated instance or // do nothing in case the instance doesn't exist anymore. PostResult can // be called from any thread. void PostResult(scoped_ptr<base::ListValue> result) const { post_result_cb_.Run(result.Pass()); }; std::string name() const { return name_; } base::ListValue* arguments() const { return arguments_.get(); } PostResultCallback post_result_cb() const { return post_result_cb_; } private: std::string name_; scoped_ptr<base::ListValue> arguments_; PostResultCallback post_result_cb_; DISALLOW_COPY_AND_ASSIGN(XWalkExtensionFunctionInfo); }; // Helper for handling JavaScript method calls in the native side. Allows you to // register a handler for a function with a given signature. This class takes an // XWalkExtensionInstance in the constructor and should never outlive this // instance. class XWalkExtensionFunctionHandler { public: typedef base::Callback<void( scoped_ptr<XWalkExtensionFunctionInfo> info)> FunctionHandler; explicit XWalkExtensionFunctionHandler(XWalkExtensionInstance* instance); ~XWalkExtensionFunctionHandler(); // Converts a raw message from the renderer to a XWalkExtensionFunctionInfo // data structure and invokes HandleFunction(). void HandleMessage(scoped_ptr<base::Value> msg); // Executes the handler associated to the |name| tag of the |info| argument // passed as parameter. bool HandleFunction(scoped_ptr<XWalkExtensionFunctionInfo> info); // This method will register a callback to handle a message tagged as // |function_name|. When invoked, the handler will get a // XWalkExtensionFunctionInfo struct with the function |name| (which can be // used in case a handler is in charge of more than one function). |arguments| // contains the list of parameters ready to be used as input for // Params::Create() generated from the IDL description of the API. The reply, // if necessary, should be posted back using the PostResult() method of the // XWalkExtensionFunctionInfo provided. // // The signature of a function handler should be like the following: // // void Foobar::OnShow(scoped_ptr<XWalkExtensionFunctionInfo> info); // // And register them like this, preferable at the Foobar constructor: // // Register("show", base::Bind(&Foobar::OnShow, base::Unretained(this))); // Register("getStuff", base::Bind(&Foobar::OnGetStuff)); // Static method. // ... void Register(const std::string& function_name, FunctionHandler callback) { handlers_[function_name] = callback; } private: static void DispatchResult( const base::WeakPtr<XWalkExtensionFunctionHandler>& handler, scoped_refptr<base::MessageLoopProxy> client_task_runner, const std::string& callback_id, scoped_ptr<base::ListValue> result); void PostMessageToInstance(scoped_ptr<base::Value> msg); typedef std::map<std::string, FunctionHandler> FunctionHandlerMap; FunctionHandlerMap handlers_; XWalkExtensionInstance* instance_; base::WeakPtrFactory<XWalkExtensionFunctionHandler> weak_factory_; DISALLOW_COPY_AND_ASSIGN(XWalkExtensionFunctionHandler); }; } // namespace extensions } // namespace xwalk #endif // XWALK_EXTENSIONS_BROWSER_XWALK_EXTENSION_FUNCTION_HANDLER_H_
{ "content_hash": "5dd2d6f8244b72a606f28b97825fd01a", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 80, "avg_line_length": 36.339285714285715, "alnum_prop": 0.7343980343980344, "repo_name": "fujunwei/crosswalk", "id": "75c8a2b403b27d1772994daad511e12915839137", "size": "4542", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "extensions/browser/xwalk_extension_function_handler.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "30701" }, { "name": "C++", "bytes": "1847757" }, { "name": "CSS", "bytes": "485" }, { "name": "Diff", "bytes": "1889" }, { "name": "HTML", "bytes": "103804" }, { "name": "Java", "bytes": "997057" }, { "name": "JavaScript", "bytes": "65123" }, { "name": "Objective-C", "bytes": "688" }, { "name": "Objective-C++", "bytes": "16628" }, { "name": "Python", "bytes": "255998" }, { "name": "Shell", "bytes": "5080" } ], "symlink_target": "" }
using namespace System.Security.Cryptography using namespace System.Security.Cryptography.X509Certificates # Use same parameter names as declared in eng/New-TestResources.ps1 (assume validation therein). [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')] param ( # Captures any arguments from eng/New-TestResources.ps1 not declared here (no parameter errors). [Parameter(ValueFromRemainingArguments = $true)] $RemainingArguments ) $ServiceRegionMap = @{ "east asia" = "EastAsia"; "southeast asia" = "SoutheastAsia"; "east us" = "EastUS"; "east us 2" = "EastUS2"; "west us" = "WestUS"; "west us 2" = "WestUS2"; "central us" = "CentralUS"; "north central us" = "NorthCentralUS"; "south central us" = "SouthCentralUS"; "north europe" = "NorthEurope"; "west europe" = "WestEurope"; "japan east" = "JapanEast"; "japan west" = "JapanWest"; "brazil south" = "BrazilSouth"; "australia east" = "AustraliaEast"; "australia southeast" = "AustraliaSoutheast"; "central india" = "CentralIndia"; "south india" = "SouthIndia"; "west india" = "WestIndia"; "china east" = "ChinaEast"; "china north" = "ChinaNorth"; "us gov iowa" = "USGovIowa"; "usgov virginia" = "USGovVirginia"; "germany central" = "GermanyCentral"; "germany northeast" = "GermanyNortheast"; "uk south" = "UKSouth"; "canada east" = "CanadaEast"; "canada central" = "CanadaCentral"; "canada west" = "CanadaWest"; "central us euap" = "CentralUSEUAP"; } $AbbreviatedRegionMap = @{ "eastasia" = "easia"; "southeastasia" = "sasia"; "eastus" = "eus"; "eastus2" = "eus2"; "westus" = "wus"; "westus2" = "wus2"; "centralus" = "cus"; "northcentralus" = "ncus"; "southcentralus" = "scus"; "northeurope" = "neu"; "westeurope" = "weu"; "japaneast" = "ejp"; "japanwest" = "wjp"; "brazilsouth" = "sbr"; "australiaeast" = "eau"; "australiasoutheast" = "sau"; "centralindia" = "cin"; "southindia" = "sin"; "westindia" = "win"; "chinaeast" = "ecn"; "chinanorth" = "ncn"; "usgoviowa" = "iusg"; "usgovvirginia" = "vusg"; "germanycentral" = "cde"; "germanynortheast" = "nde"; "uksouth" = "uks"; "canadaeast" = "cae"; "canadacentral" = "cac"; "canadawest" = "caw"; "centraluseuap" = "cuse"; } # By default stop for any error. if (!$PSBoundParameters.ContainsKey('ErrorAction')) { $ErrorActionPreference = 'Stop' } function Log($Message) { Write-Host ('{0} - {1}' -f [DateTime]::Now.ToLongTimeString(), $Message) } function New-X509Certificate2([RSA] $rsa, [string] $SubjectName) { try { $req = [CertificateRequest]::new( [string] $SubjectName, $rsa, [HashAlgorithmName]::SHA256, [RSASignaturePadding]::Pkcs1 ) # TODO: Add any KUs necessary to $req.CertificateExtensions $req.CertificateExtensions.Add([X509BasicConstraintsExtension]::new($true, $false, 0, $false)) $NotBefore = [DateTimeOffset]::Now.AddDays(-1) $NotAfter = $NotBefore.AddDays(365) $req.CreateSelfSigned($NotBefore, $NotAfter) } finally { } } function Export-X509Certificate2([string] $Path, [X509Certificate2] $Certificate) { $Certificate.Export([X509ContentType]::Pfx) | Set-Content $Path -AsByteStream } function Export-X509Certificate2PEM([string] $Path, [X509Certificate2] $Certificate) { @" -----BEGIN CERTIFICATE----- $([Convert]::ToBase64String($Certificate.RawData, 'InsertLineBreaks')) -----END CERTIFICATE----- "@ > $Path } Log "Running PreConfig script". $shortLocation = $AbbreviatedRegionMap.Get_Item($Location.ToLower()) Log "Mapped long location name ${Location} to short name: ${shortLocation}" try { $isolatedKey = [RSA]::Create(2048) $isolatedCertificate = New-X509Certificate2 $isolatedKey "CN=AttestationIsolatedManagementCertificate" $EnvironmentVariables["isolatedSigningCertificate"] = $([Convert]::ToBase64String($isolatedCertificate.RawData, 'None')) $templateFileParameters.isolatedSigningCertificate = $([Convert]::ToBase64String($isolatedCertificate.RawData, 'None')) $EnvironmentVariables["isolatedSigningKey"] = $([Convert]::ToBase64String($isolatedKey.ExportPkcs8PrivateKey())) $EnvironmentVariables["serializedIsolatedSigningKey"] = $isolatedKey.ToXmlString($True) } finally { $isolatedKey.Dispose() } $EnvironmentVariables["locationShortName"] = $shortLocation $templateFileParameters.locationShortName = $shortLocation Log 'Creating 3 X509 certificates which can be used to sign policies.' $wrappingFiles = foreach ($i in 0..2) { try { $certificateKey = [RSA]::Create(2048) $certificate = New-X509Certificate2 $certificateKey "CN=AttestationCertificate$i" $EnvironmentVariables["policySigningCertificate$i"] = $([Convert]::ToBase64String($certificate.RawData)) $EnvironmentVariables["policySigningKey$i"] = $([Convert]::ToBase64String($certificateKey.ExportPkcs8PrivateKey())) $EnvironmentVariables["serializedPolicySigningKey$i"] = $certificateKey.ToXmlString($True) $baseName = "$PSScriptRoot\attestation-certificate$i" Export-X509Certificate2 "$baseName.pfx" $certificate } finally { $certificateKey.Dispose() } }
{ "content_hash": "9d62c51b7c8a5d3e1a660d3cc7e2d0b9", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 123, "avg_line_length": 33, "alnum_prop": 0.6638780442461424, "repo_name": "AsrOneSdk/azure-sdk-for-net", "id": "e9b5afa8cd1d8fb3b9e0d96252b2e77cf2b1eef3", "size": "5643", "binary": false, "copies": "6", "ref": "refs/heads/psSdkJson6Current", "path": "sdk/attestation/test-resources-pre.ps1", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "15473" }, { "name": "Bicep", "bytes": "13438" }, { "name": "C#", "bytes": "72203239" }, { "name": "CSS", "bytes": "6089" }, { "name": "Dockerfile", "bytes": "5652" }, { "name": "HTML", "bytes": "6169271" }, { "name": "JavaScript", "bytes": "16012" }, { "name": "PowerShell", "bytes": "649218" }, { "name": "Shell", "bytes": "31287" }, { "name": "Smarty", "bytes": "11135" } ], "symlink_target": "" }
#include <stdint.h> #include <sys/queue.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <assert.h> #include <errno.h> #include <signal.h> #include <stdarg.h> #include <inttypes.h> #include <getopt.h> #include <rte_common.h> #include <rte_log.h> #include <rte_memory.h> #include <rte_memcpy.h> #include <rte_memzone.h> #include <rte_eal.h> #include <rte_per_lcore.h> #include <rte_launch.h> #include <rte_atomic.h> #include <rte_cycles.h> #include <rte_prefetch.h> #include <rte_lcore.h> #include <rte_per_lcore.h> #include <rte_branch_prediction.h> #include <rte_interrupts.h> #include <rte_pci.h> #include <rte_random.h> #include <rte_debug.h> #include <rte_ether.h> #include <rte_ethdev.h> #include <rte_ring.h> #include <rte_log.h> #include <rte_mempool.h> #include <rte_mbuf.h> #include <rte_memcpy.h> /* basic constants used in application */ #define NUM_QUEUES 128 #define NUM_MBUFS 64*1024 #define MBUF_CACHE_SIZE 64 #define INVALID_PORT_ID 0xFF /* mask of enabled ports */ static uint32_t enabled_port_mask = 0; /* number of pools (if user does not specify any, 16 by default */ static enum rte_eth_nb_pools num_pools = ETH_16_POOLS; /* empty vmdq+dcb configuration structure. Filled in programatically */ static const struct rte_eth_conf vmdq_dcb_conf_default = { .rxmode = { .mq_mode = ETH_MQ_RX_VMDQ_DCB, .split_hdr_size = 0, .header_split = 0, /**< Header Split disabled */ .hw_ip_checksum = 0, /**< IP checksum offload disabled */ .hw_vlan_filter = 0, /**< VLAN filtering disabled */ .jumbo_frame = 0, /**< Jumbo Frame Support disabled */ }, .txmode = { .mq_mode = ETH_MQ_TX_NONE, }, .rx_adv_conf = { /* * should be overridden separately in code with * appropriate values */ .vmdq_dcb_conf = { .nb_queue_pools = ETH_16_POOLS, .enable_default_pool = 0, .default_pool = 0, .nb_pool_maps = 0, .pool_map = {{0, 0},}, .dcb_queue = {0}, }, }, }; static uint8_t ports[RTE_MAX_ETHPORTS]; static unsigned num_ports = 0; /* array used for printing out statistics */ volatile unsigned long rxPackets[ NUM_QUEUES ] = {0}; const uint16_t vlan_tags[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 }; /* Builds up the correct configuration for vmdq+dcb based on the vlan tags array * given above, and the number of traffic classes available for use. */ static inline int get_eth_conf(struct rte_eth_conf *eth_conf, enum rte_eth_nb_pools num_pools) { struct rte_eth_vmdq_dcb_conf conf; unsigned i; if (num_pools != ETH_16_POOLS && num_pools != ETH_32_POOLS ) return -1; conf.nb_queue_pools = num_pools; conf.enable_default_pool = 0; conf.default_pool = 0; /* set explicit value, even if not used */ conf.nb_pool_maps = sizeof( vlan_tags )/sizeof( vlan_tags[ 0 ]); for (i = 0; i < conf.nb_pool_maps; i++){ conf.pool_map[i].vlan_id = vlan_tags[ i ]; conf.pool_map[i].pools = 1 << (i % num_pools); } for (i = 0; i < ETH_DCB_NUM_USER_PRIORITIES; i++){ conf.dcb_queue[i] = (uint8_t)(i % (NUM_QUEUES/num_pools)); } (void)(rte_memcpy(eth_conf, &vmdq_dcb_conf_default, sizeof(*eth_conf))); (void)(rte_memcpy(&eth_conf->rx_adv_conf.vmdq_dcb_conf, &conf, sizeof(eth_conf->rx_adv_conf.vmdq_dcb_conf))); return 0; } /* * Initialises a given port using global settings and with the rx buffers * coming from the mbuf_pool passed as parameter */ static inline int port_init(uint8_t port, struct rte_mempool *mbuf_pool) { struct rte_eth_conf port_conf; const uint16_t rxRings = ETH_VMDQ_DCB_NUM_QUEUES, txRings = (uint16_t)rte_lcore_count(); const uint16_t rxRingSize = 128, txRingSize = 512; int retval; uint16_t q; retval = get_eth_conf(&port_conf, num_pools); if (retval < 0) return retval; if (port >= rte_eth_dev_count()) return -1; retval = rte_eth_dev_configure(port, rxRings, txRings, &port_conf); if (retval != 0) return retval; for (q = 0; q < rxRings; q ++) { retval = rte_eth_rx_queue_setup(port, q, rxRingSize, rte_eth_dev_socket_id(port), NULL, mbuf_pool); if (retval < 0) return retval; } for (q = 0; q < txRings; q ++) { retval = rte_eth_tx_queue_setup(port, q, txRingSize, rte_eth_dev_socket_id(port), NULL); if (retval < 0) return retval; } retval = rte_eth_dev_start(port); if (retval < 0) return retval; struct ether_addr addr; rte_eth_macaddr_get(port, &addr); printf("Port %u MAC: %02"PRIx8" %02"PRIx8" %02"PRIx8 " %02"PRIx8" %02"PRIx8" %02"PRIx8"\n", (unsigned)port, addr.addr_bytes[0], addr.addr_bytes[1], addr.addr_bytes[2], addr.addr_bytes[3], addr.addr_bytes[4], addr.addr_bytes[5]); return 0; } /* Check num_pools parameter and set it if OK*/ static int vmdq_parse_num_pools(const char *q_arg) { char *end = NULL; int n; /* parse number string */ n = strtol(q_arg, &end, 10); if ((q_arg[0] == '\0') || (end == NULL) || (*end != '\0')) return -1; if (n != 16 && n != 32) return -1; if (n == 16) num_pools = ETH_16_POOLS; else num_pools = ETH_32_POOLS; return 0; } static int parse_portmask(const char *portmask) { char *end = NULL; unsigned long pm; /* parse hexadecimal string */ pm = strtoul(portmask, &end, 16); if ((portmask[0] == '\0') || (end == NULL) || (*end != '\0')) return -1; if (pm == 0) return -1; return pm; } /* Display usage */ static void vmdq_usage(const char *prgname) { printf("%s [EAL options] -- -p PORTMASK]\n" " --nb-pools NP: number of pools (16 default, 32)\n", prgname); } /* Parse the argument (num_pools) given in the command line of the application */ static int vmdq_parse_args(int argc, char **argv) { int opt; int option_index; unsigned i; const char *prgname = argv[0]; static struct option long_option[] = { {"nb-pools", required_argument, NULL, 0}, {NULL, 0, 0, 0} }; /* Parse command line */ while ((opt = getopt_long(argc, argv, "p:",long_option,&option_index)) != EOF) { switch (opt) { /* portmask */ case 'p': enabled_port_mask = parse_portmask(optarg); if (enabled_port_mask == 0) { printf("invalid portmask\n"); vmdq_usage(prgname); return -1; } break; case 0: if (vmdq_parse_num_pools(optarg) == -1){ printf("invalid number of pools\n"); vmdq_usage(prgname); return -1; } break; default: vmdq_usage(prgname); return -1; } } for(i = 0; i < RTE_MAX_ETHPORTS; i++) { if (enabled_port_mask & (1 << i)) ports[num_ports++] = (uint8_t)i; } if (num_ports < 2 || num_ports % 2) { printf("Current enabled port number is %u," "but it should be even and at least 2\n",num_ports); return -1; } return 0; } /* When we receive a HUP signal, print out our stats */ static void sighup_handler(int signum) { unsigned q; for (q = 0; q < NUM_QUEUES; q ++) { if (q % (NUM_QUEUES/num_pools) == 0) printf("\nPool %u: ", q/(NUM_QUEUES/num_pools)); printf("%lu ", rxPackets[ q ]); } printf("\nFinished handling signal %d\n", signum); } /* * Main thread that does the work, reading from INPUT_PORT * and writing to OUTPUT_PORT */ static __attribute__((noreturn)) int lcore_main(void *arg) { const uintptr_t core_num = (uintptr_t)arg; const unsigned num_cores = rte_lcore_count(); uint16_t startQueue = (uint16_t)(core_num * (NUM_QUEUES/num_cores)); uint16_t endQueue = (uint16_t)(startQueue + (NUM_QUEUES/num_cores)); uint16_t q, i, p; printf("Core %u(lcore %u) reading queues %i-%i\n", (unsigned)core_num, rte_lcore_id(), startQueue, endQueue - 1); for (;;) { struct rte_mbuf *buf[32]; const uint16_t buf_size = sizeof(buf) / sizeof(buf[0]); for (p = 0; p < num_ports; p++) { const uint8_t src = ports[p]; const uint8_t dst = ports[p ^ 1]; /* 0 <-> 1, 2 <-> 3 etc */ if ((src == INVALID_PORT_ID) || (dst == INVALID_PORT_ID)) continue; for (q = startQueue; q < endQueue; q++) { const uint16_t rxCount = rte_eth_rx_burst(src, q, buf, buf_size); if (rxCount == 0) continue; rxPackets[q] += rxCount; const uint16_t txCount = rte_eth_tx_burst(dst, (uint16_t)core_num, buf, rxCount); if (txCount != rxCount) { for (i = txCount; i < rxCount; i++) rte_pktmbuf_free(buf[i]); } } } } } /* * Update the global var NUM_PORTS and array PORTS according to system ports number * and return valid ports number */ static unsigned check_ports_num(unsigned nb_ports) { unsigned valid_num_ports = num_ports; unsigned portid; if (num_ports > nb_ports) { printf("\nSpecified port number(%u) exceeds total system port number(%u)\n", num_ports, nb_ports); num_ports = nb_ports; } for (portid = 0; portid < num_ports; portid ++) { if (ports[portid] >= nb_ports) { printf("\nSpecified port ID(%u) exceeds max system port ID(%u)\n", ports[portid], (nb_ports - 1)); ports[portid] = INVALID_PORT_ID; valid_num_ports --; } } return valid_num_ports; } /* Main function, does initialisation and calls the per-lcore functions */ int main(int argc, char *argv[]) { unsigned cores; struct rte_mempool *mbuf_pool; unsigned lcore_id; uintptr_t i; int ret; unsigned nb_ports, valid_num_ports; uint8_t portid; signal(SIGHUP, sighup_handler); /* init EAL */ ret = rte_eal_init(argc, argv); if (ret < 0) rte_exit(EXIT_FAILURE, "Error with EAL initialization\n"); argc -= ret; argv += ret; /* parse app arguments */ ret = vmdq_parse_args(argc, argv); if (ret < 0) rte_exit(EXIT_FAILURE, "Invalid VMDQ argument\n"); cores = rte_lcore_count(); if ((cores & (cores - 1)) != 0 || cores > 128) { rte_exit(EXIT_FAILURE,"This program can only run on an even" "number of cores(1-128)\n\n"); } nb_ports = rte_eth_dev_count(); if (nb_ports > RTE_MAX_ETHPORTS) nb_ports = RTE_MAX_ETHPORTS; /* * Update the global var NUM_PORTS and global array PORTS * and get value of var VALID_NUM_PORTS according to system ports number */ valid_num_ports = check_ports_num(nb_ports); if (valid_num_ports < 2 || valid_num_ports % 2) { printf("Current valid ports number is %u\n", valid_num_ports); rte_exit(EXIT_FAILURE, "Error with valid ports number is not even or less than 2\n"); } mbuf_pool = rte_pktmbuf_pool_create("MBUF_POOL", NUM_MBUFS * nb_ports, MBUF_CACHE_SIZE, 0, RTE_MBUF_DEFAULT_BUF_SIZE, rte_socket_id()); if (mbuf_pool == NULL) rte_exit(EXIT_FAILURE, "Cannot create mbuf pool\n"); /* initialize all ports */ for (portid = 0; portid < nb_ports; portid++) { /* skip ports that are not enabled */ if ((enabled_port_mask & (1 << portid)) == 0) { printf("\nSkipping disabled port %d\n", portid); continue; } if (port_init(portid, mbuf_pool) != 0) rte_exit(EXIT_FAILURE, "Cannot initialize network ports\n"); } /* call lcore_main() on every slave lcore */ i = 0; RTE_LCORE_FOREACH_SLAVE(lcore_id) { rte_eal_remote_launch(lcore_main, (void*)i++, lcore_id); } /* call on master too */ (void) lcore_main((void*)i); return 0; }
{ "content_hash": "662df85245fce1947fa403bf27c896a4", "timestamp": "", "source": "github", "line_count": 437, "max_line_length": 87, "avg_line_length": 25.208237986270024, "alnum_prop": 0.6333514887436456, "repo_name": "shakuniji/mtcp", "id": "c31c2ce68ac70922036580b40a035807141ea7c5", "size": "12708", "binary": false, "copies": "19", "ref": "refs/heads/master", "path": "dpdk-2.1.0/examples/vmdq_dcb/main.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Awk", "bytes": "48304" }, { "name": "Batchfile", "bytes": "2464779" }, { "name": "C", "bytes": "54629782" }, { "name": "C++", "bytes": "168091" }, { "name": "CSS", "bytes": "1118" }, { "name": "Groff", "bytes": "1875" }, { "name": "HTML", "bytes": "34052" }, { "name": "Inno Setup", "bytes": "3960" }, { "name": "Makefile", "bytes": "764357" }, { "name": "Objective-C", "bytes": "5641" }, { "name": "PHP", "bytes": "967" }, { "name": "Perl", "bytes": "197335" }, { "name": "Perl6", "bytes": "11115" }, { "name": "Prolog", "bytes": "2103" }, { "name": "Python", "bytes": "118769" }, { "name": "Shell", "bytes": "1265378" }, { "name": "SourcePawn", "bytes": "15259" }, { "name": "Yacc", "bytes": "17232" } ], "symlink_target": "" }
<?php namespace Murky\BiblioBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class TagControllerTest extends WebTestCase { /* public function testCompleteScenario() { // Create a new client to browse the application $client = static::createClient(); // Create a new entry in the database $crawler = $client->request('GET', '/tag/'); $this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for GET /tag/"); $crawler = $client->click($crawler->selectLink('Create a new entry')->link()); // Fill in the form and submit it $form = $crawler->selectButton('Create')->form(array( 'murky_bibliobundle_tagtype[field_name]' => 'Test', // ... other fields to fill )); $client->submit($form); $crawler = $client->followRedirect(); // Check data in the show view $this->assertGreaterThan(0, $crawler->filter('td:contains("Test")')->count(), 'Missing element td:contains("Test")'); // Edit the entity $crawler = $client->click($crawler->selectLink('Edit')->link()); $form = $crawler->selectButton('Edit')->form(array( 'murky_bibliobundle_tagtype[field_name]' => 'Foo', // ... other fields to fill )); $client->submit($form); $crawler = $client->followRedirect(); // Check the element contains an attribute with value equals "Foo" $this->assertGreaterThan(0, $crawler->filter('[value="Foo"]')->count(), 'Missing element [value="Foo"]'); // Delete the entity $client->submit($crawler->selectButton('Delete')->form()); $crawler = $client->followRedirect(); // Check the entity has been delete on the list $this->assertNotRegExp('/Foo/', $client->getResponse()->getContent()); } */ }
{ "content_hash": "fb18d0a1597751dcddee4d4c7de8f5ad", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 125, "avg_line_length": 35.018181818181816, "alnum_prop": 0.6007268951194185, "repo_name": "rlbaltha/biblio", "id": "ffea98374645c95fc6d465319ea2ae3ccb23b7ef", "size": "1926", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Murky/BiblioBundle/Tests/Controller/TagControllerTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "518759" }, { "name": "JavaScript", "bytes": "1096730" }, { "name": "PHP", "bytes": "138887" } ], "symlink_target": "" }
#include "rpcconsole.h" #include "ui_rpcconsole.h" #include "clientmodel.h" #include "bitcoinrpc.h" #include "guiutil.h" #include <QTime> #include <QThread> #include <QKeyEvent> #if QT_VERSION < 0x050000 #include <QUrl> #endif #include <QScrollBar> #include <openssl/crypto.h> // TODO: add a scrollback limit, as there is currently none // TODO: make it possible to filter out categories (esp debug messages when implemented) // TODO: receive errors and debug messages through ClientModel const int CONSOLE_HISTORY = 50; const QSize ICON_SIZE(24, 24); const struct { const char *url; const char *source; } ICON_MAPPING[] = { {"cmd-request", ":/icons/tx_input"}, {"cmd-reply", ":/icons/tx_output"}, {"cmd-error", ":/icons/tx_output"}, {"misc", ":/icons/tx_inout"}, {NULL, NULL} }; /* Object for executing console RPC commands in a separate thread. */ class RPCExecutor : public QObject { Q_OBJECT public slots: void request(const QString &command); signals: void reply(int category, const QString &command); }; #include "rpcconsole.moc" /** * Split shell command line into a list of arguments. Aims to emulate \c bash and friends. * * - Arguments are delimited with whitespace * - Extra whitespace at the beginning and end and between arguments will be ignored * - Text can be "double" or 'single' quoted * - The backslash \c \ is used as escape character * - Outside quotes, any character can be escaped * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash * - Within single quotes, no escaping is possible and no special interpretation takes place * * @param[out] args Parsed arguments will be appended to this list * @param[in] strCommand Command line to split */ bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand) { enum CmdParseState { STATE_EATING_SPACES, STATE_ARGUMENT, STATE_SINGLEQUOTED, STATE_DOUBLEQUOTED, STATE_ESCAPE_OUTER, STATE_ESCAPE_DOUBLEQUOTED } state = STATE_EATING_SPACES; std::string curarg; foreach(char ch, strCommand) { switch(state) { case STATE_ARGUMENT: // In or after argument case STATE_EATING_SPACES: // Handle runs of whitespace switch(ch) { case '"': state = STATE_DOUBLEQUOTED; break; case '\'': state = STATE_SINGLEQUOTED; break; case '\\': state = STATE_ESCAPE_OUTER; break; case ' ': case '\n': case '\t': if(state == STATE_ARGUMENT) // Space ends argument { args.push_back(curarg); curarg.clear(); } state = STATE_EATING_SPACES; break; default: curarg += ch; state = STATE_ARGUMENT; } break; case STATE_SINGLEQUOTED: // Single-quoted string switch(ch) { case '\'': state = STATE_ARGUMENT; break; default: curarg += ch; } break; case STATE_DOUBLEQUOTED: // Double-quoted string switch(ch) { case '"': state = STATE_ARGUMENT; break; case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break; default: curarg += ch; } break; case STATE_ESCAPE_OUTER: // '\' outside quotes curarg += ch; state = STATE_ARGUMENT; break; case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself curarg += ch; state = STATE_DOUBLEQUOTED; break; } } switch(state) // final state { case STATE_EATING_SPACES: return true; case STATE_ARGUMENT: args.push_back(curarg); return true; default: // ERROR to end in one of the other states return false; } } void RPCExecutor::request(const QString &command) { std::vector<std::string> args; if(!parseCommandLine(args, command.toStdString())) { emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \"")); return; } if(args.empty()) return; // Nothing to do try { std::string strPrint; // Convert argument list to JSON objects in method-dependent way, // and pass it along with the method name to the dispatcher. json_spirit::Value result = tableRPC.execute( args[0], RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end()))); // Format result reply if (result.type() == json_spirit::null_type) strPrint = ""; else if (result.type() == json_spirit::str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint)); } catch (json_spirit::Object& objError) { try // Nice formatting for standard-format error { int code = find_value(objError, "code").get_int(); std::string message = find_value(objError, "message").get_str(); emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")"); } catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message { // Show raw JSON object emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false))); } } catch (std::exception& e) { emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what())); } } RPCConsole::RPCConsole(QWidget *parent) : QDialog(parent), ui(new Ui::RPCConsole), clientModel(0), historyPtr(0) { ui->setupUi(this); #ifndef Q_OS_MAC ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export")); ui->showCLOptionsButton->setIcon(QIcon(":/icons/options")); #endif // Install event filter for up and down arrow ui->lineEdit->installEventFilter(this); ui->messagesWidget->installEventFilter(this); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // set OpenSSL version label ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION)); startExecutor(); clear(); } RPCConsole::~RPCConsole() { emit stopExecutor(); delete ui; } bool RPCConsole::eventFilter(QObject* obj, QEvent *event) { if(event->type() == QEvent::KeyPress) // Special key handling { QKeyEvent *keyevt = static_cast<QKeyEvent*>(event); int key = keyevt->key(); Qt::KeyboardModifiers mod = keyevt->modifiers(); switch(key) { case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break; case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break; case Qt::Key_PageUp: /* pass paging keys to messages widget */ case Qt::Key_PageDown: if(obj == ui->lineEdit) { QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt)); return true; } break; default: // Typing in messages widget brings focus to line edit, and redirects key there // Exclude most combinations and keys that emit no text, except paste shortcuts if(obj == ui->messagesWidget && ( (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) || ((mod & Qt::ControlModifier) && key == Qt::Key_V) || ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert))) { ui->lineEdit->setFocus(); QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt)); return true; } } } return QDialog::eventFilter(obj, event); } void RPCConsole::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { // Keep up to date with client setNumConnections(model->getNumConnections()); connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); setNumBlocks(model->getNumBlocks(), model->getNumBlocksOfPeers()); connect(model, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int))); // Provide initial values ui->clientVersion->setText(model->formatFullVersion()); ui->clientName->setText(model->clientName()); ui->buildDate->setText(model->formatBuildDate()); ui->startupTime->setText(model->formatClientStartupTime()); ui->isTestNet->setChecked(model->isTestNet()); } } static QString categoryClass(int category) { switch(category) { case RPCConsole::CMD_REQUEST: return "cmd-request"; break; case RPCConsole::CMD_REPLY: return "cmd-reply"; break; case RPCConsole::CMD_ERROR: return "cmd-error"; break; default: return "misc"; } } void RPCConsole::clear() { ui->messagesWidget->clear(); history.clear(); historyPtr = 0; ui->lineEdit->clear(); ui->lineEdit->setFocus(); // Add smoothly scaled icon images. // (when using width/height on an img, Qt uses nearest instead of linear interpolation) for(int i=0; ICON_MAPPING[i].url; ++i) { ui->messagesWidget->document()->addResource( QTextDocument::ImageResource, QUrl(ICON_MAPPING[i].url), QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); } // Set default style sheet ui->messagesWidget->document()->setDefaultStyleSheet( "table { }" "td.time { color: #808080; padding-top: 3px; } " "td.message { font-family: Monospace; font-size: 12px; } " "td.cmd-request { color: #006060; } " "td.cmd-error { color: red; } " "b { color: #006060; } " ); message(CMD_REPLY, (tr("Welcome to the Joulecoin RPC console.") + "<br>" + tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" + tr("Type <b>help</b> for an overview of available commands.")), true); } void RPCConsole::message(int category, const QString &message, bool html) { QTime time = QTime::currentTime(); QString timeString = time.toString(); QString out; out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>"; out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>"; out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">"; if(html) out += message; else out += GUIUtil::HtmlEscape(message, true); out += "</td></tr></table>"; ui->messagesWidget->append(out); } void RPCConsole::setNumConnections(int count) { ui->numberOfConnections->setText(QString::number(count)); } void RPCConsole::setNumBlocks(int count, int countOfPeers) { ui->numberOfBlocks->setText(QString::number(count)); // If there is no current countOfPeers available display N/A instead of 0, which can't ever be true ui->totalBlocks->setText(countOfPeers == 0 ? tr("N/A") : QString::number(countOfPeers)); if(clientModel) ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString()); } void RPCConsole::on_lineEdit_returnPressed() { QString cmd = ui->lineEdit->text(); ui->lineEdit->clear(); if(!cmd.isEmpty()) { message(CMD_REQUEST, cmd); emit cmdRequest(cmd); // Truncate history from current position history.erase(history.begin() + historyPtr, history.end()); // Append command to history history.append(cmd); // Enforce maximum history size while(history.size() > CONSOLE_HISTORY) history.removeFirst(); // Set pointer to end of history historyPtr = history.size(); // Scroll console view to end scrollToEnd(); } } void RPCConsole::browseHistory(int offset) { historyPtr += offset; if(historyPtr < 0) historyPtr = 0; if(historyPtr > history.size()) historyPtr = history.size(); QString cmd; if(historyPtr < history.size()) cmd = history.at(historyPtr); ui->lineEdit->setText(cmd); } void RPCConsole::startExecutor() { QThread *thread = new QThread; RPCExecutor *executor = new RPCExecutor(); executor->moveToThread(thread); // Replies from executor object must go to this object connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString))); // Requests from this object must go to executor connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString))); // On stopExecutor signal // - queue executor for deletion (in execution thread) // - quit the Qt event loop in the execution thread connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit())); // Queue the thread for deletion (in this thread) when it is finished connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); // Default implementation of QThread::run() simply spins up an event loop in the thread, // which is what we want. thread->start(); } void RPCConsole::on_tabWidget_currentChanged(int index) { if(ui->tabWidget->widget(index) == ui->tab_console) { ui->lineEdit->setFocus(); } } void RPCConsole::on_openDebugLogfileButton_clicked() { GUIUtil::openDebugLogfile(); } void RPCConsole::scrollToEnd() { QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar(); scrollbar->setValue(scrollbar->maximum()); } void RPCConsole::on_showCLOptionsButton_clicked() { GUIUtil::HelpMessageBox help; help.exec(); }
{ "content_hash": "0e8a5b38aa695857741c99024e2e7b72", "timestamp": "", "source": "github", "line_count": 431, "max_line_length": 121, "avg_line_length": 33.06264501160093, "alnum_prop": 0.604701754385965, "repo_name": "CCPorg/XJO-JouleCoin-Ver-89906-Copy", "id": "15a5b53bf8aab3607f606100718cdb8d37d16418", "size": "14250", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qt/rpcconsole.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "89912" }, { "name": "C++", "bytes": "2494753" }, { "name": "CSS", "bytes": "1127" }, { "name": "Objective-C", "bytes": "5711" }, { "name": "Prolog", "bytes": "14184" }, { "name": "Python", "bytes": "69704" }, { "name": "Shell", "bytes": "14580" }, { "name": "TypeScript", "bytes": "5241724" } ], "symlink_target": "" }
package com.navercorp.pinpoint.profiler.context; import com.navercorp.pinpoint.bootstrap.context.AsyncContext; import com.navercorp.pinpoint.bootstrap.context.AsyncState; import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor; import com.navercorp.pinpoint.common.util.Assert; import com.navercorp.pinpoint.profiler.context.id.AsyncIdGenerator; import com.navercorp.pinpoint.profiler.context.id.TraceRoot; import com.navercorp.pinpoint.profiler.context.method.PredefinedMethodDescriptorRegistry; /** * @author Woonduk Kang(emeroad) */ public class DefaultAsyncContextFactory implements AsyncContextFactory { private final AsyncTraceContext asyncTraceContext; private final AsyncIdGenerator asyncIdGenerator; private final PredefinedMethodDescriptorRegistry predefinedMethodDescriptorRegistry; private final int asyncMethodApiId; public DefaultAsyncContextFactory(AsyncTraceContext asyncTraceContext, AsyncIdGenerator asyncIdGenerator, PredefinedMethodDescriptorRegistry predefinedMethodDescriptorRegistry) { this.asyncTraceContext = Assert.requireNonNull(asyncTraceContext, "traceFactoryProvider"); this.asyncIdGenerator = Assert.requireNonNull(asyncIdGenerator, "asyncIdGenerator"); this.predefinedMethodDescriptorRegistry = Assert.requireNonNull(predefinedMethodDescriptorRegistry, "predefinedMethodDescriptorRegistry"); this.asyncMethodApiId = getAsyncMethodApiId(predefinedMethodDescriptorRegistry); } private int getAsyncMethodApiId(PredefinedMethodDescriptorRegistry predefinedMethodDescriptorRegistry) { final MethodDescriptor asyncMethodDescriptor = predefinedMethodDescriptorRegistry.getAsyncMethodDescriptor(); return asyncMethodDescriptor.getApiId(); } @Override public AsyncId newAsyncId() { return asyncIdGenerator.newAsyncId(); } @Override public AsyncContext newAsyncContext(TraceRoot traceRoot, AsyncId asyncId) { Assert.requireNonNull(traceRoot, "traceRoot"); Assert.requireNonNull(asyncId, "asyncId"); return new DefaultAsyncContext(asyncTraceContext, traceRoot, asyncId, this.asyncMethodApiId); } @Override public AsyncContext newAsyncContext(TraceRoot traceRoot, AsyncId asyncId, AsyncState asyncState) { Assert.requireNonNull(traceRoot, "traceRoot"); Assert.requireNonNull(asyncId, "asyncId"); Assert.requireNonNull(asyncState, "asyncState"); return new StatefulAsyncContext(asyncTraceContext, traceRoot, asyncId, asyncMethodApiId, asyncState); } }
{ "content_hash": "9f6069c8f1c38d5f7895ddd78a77c82f", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 182, "avg_line_length": 42.96666666666667, "alnum_prop": 0.7990690457719162, "repo_name": "Xylus/pinpoint", "id": "53eeb3deb252e9356aed4bc5f00f811988805180", "size": "3168", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "profiler/src/main/java/com/navercorp/pinpoint/profiler/context/DefaultAsyncContextFactory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "23110" }, { "name": "CSS", "bytes": "534643" }, { "name": "CoffeeScript", "bytes": "10124" }, { "name": "Groovy", "bytes": "1423" }, { "name": "HTML", "bytes": "783457" }, { "name": "Java", "bytes": "16266462" }, { "name": "JavaScript", "bytes": "4821525" }, { "name": "Makefile", "bytes": "5246" }, { "name": "PLSQL", "bytes": "4156" }, { "name": "Python", "bytes": "3523" }, { "name": "Ruby", "bytes": "943" }, { "name": "Shell", "bytes": "31351" }, { "name": "TSQL", "bytes": "4316" }, { "name": "Thrift", "bytes": "15284" }, { "name": "TypeScript", "bytes": "1385542" } ], "symlink_target": "" }
from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from msrestazure.azure_operation import AzureOperationPoller import uuid from .. import models class StorageAccountsOperations(object): """StorageAccountsOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An objec model deserializer. """ def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.config = config def check_name_availability( self, account_name, custom_headers=None, raw=False, **operation_config): """ Checks that account name is valid and is not in use. :param account_name: The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. :type account_name: :class:`StorageAccountCheckNameAvailabilityParameters <fixtures.acceptancetestsstoragemanagementclient.models.StorageAccountCheckNameAvailabilityParameters>` :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: :class:`CheckNameAvailabilityResult <fixtures.acceptancetestsstoragemanagementclient.models.CheckNameAvailabilityResult>` :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true """ # Construct URL url = '/subscriptions/{subscriptionId}/providers/Microsoft.Storage/checkNameAvailability' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(account_name, 'StorageAccountCheckNameAvailabilityParameters') # Construct and send request request = self._client.post(url, query_parameters) response = self._client.send( request, header_parameters, body_content, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('CheckNameAvailabilityResult', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def create( self, resource_group_name, account_name, parameters, custom_headers=None, raw=False, **operation_config): """ Asynchronously creates a new storage account with the specified parameters. Existing accounts cannot be updated with this API and should instead use the Update Storage Account API. If an account is already created and subsequent PUT request is issued with exact same set of properties, then HTTP 200 would be returned. :param resource_group_name: The name of the resource group within the user’s subscription. :type resource_group_name: str :param account_name: The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. :type account_name: str :param parameters: The parameters to provide for the created account. :type parameters: :class:`StorageAccountCreateParameters <fixtures.acceptancetestsstoragemanagementclient.models.StorageAccountCreateParameters>` :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :rtype: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` instance that returns :class:`StorageAccount <fixtures.acceptancetestsstoragemanagementclient.models.StorageAccount>` :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'accountName': self._serialize.url("account_name", account_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(parameters, 'StorageAccountCreateParameters') # Construct and send request def long_running_send(): request = self._client.put(url, query_parameters) return self._client.send( request, header_parameters, body_content, **operation_config) def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) return self._client.send( request, header_parameters, **operation_config) def get_long_running_output(response): if response.status_code not in [200, 202]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('StorageAccount', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized if raw: response = long_running_send() return get_long_running_output(response) long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def delete( self, resource_group_name, account_name, custom_headers=None, raw=False, **operation_config): """ Deletes a storage account in Microsoft Azure. :param resource_group_name: The name of the resource group within the user’s subscription. :type resource_group_name: str :param account_name: The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. :type account_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: None :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'accountName': self._serialize.url("account_name", account_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.delete(url, query_parameters) response = self._client.send(request, header_parameters, **operation_config) if response.status_code not in [200, 204]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response def get_properties( self, resource_group_name, account_name, custom_headers=None, raw=False, **operation_config): """ Returns the properties for the specified storage account including but not limited to name, account type, location, and account status. The ListKeys operation should be used to retrieve storage keys. :param resource_group_name: The name of the resource group within the user’s subscription. :type resource_group_name: str :param account_name: The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. :type account_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: :class:`StorageAccount <fixtures.acceptancetestsstoragemanagementclient.models.StorageAccount>` :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'accountName': self._serialize.url("account_name", account_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send(request, header_parameters, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('StorageAccount', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def update( self, resource_group_name, account_name, parameters, custom_headers=None, raw=False, **operation_config): """ Updates the account type or tags for a storage account. It can also be used to add a custom domain (note that custom domains cannot be added via the Create operation). Only one custom domain is supported per storage account. This API can only be used to update one of tags, accountType, or customDomain per call. To update multiple of these properties, call the API multiple times with one change per call. This call does not change the storage keys for the account. If you want to change storage account keys, use the RegenerateKey operation. The location and name of the storage account cannot be changed after creation. :param resource_group_name: The name of the resource group within the user’s subscription. :type resource_group_name: str :param account_name: The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. :type account_name: str :param parameters: The parameters to update on the account. Note that only one property can be changed at a time using this API. :type parameters: :class:`StorageAccountUpdateParameters <fixtures.acceptancetestsstoragemanagementclient.models.StorageAccountUpdateParameters>` :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: :class:`StorageAccount <fixtures.acceptancetestsstoragemanagementclient.models.StorageAccount>` :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'accountName': self._serialize.url("account_name", account_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(parameters, 'StorageAccountUpdateParameters') # Construct and send request request = self._client.patch(url, query_parameters) response = self._client.send( request, header_parameters, body_content, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('StorageAccount', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def list_keys( self, resource_group_name, account_name, custom_headers=None, raw=False, **operation_config): """ Lists the access keys for the specified storage account. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param account_name: The name of the storage account. :type account_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: :class:`StorageAccountKeys <fixtures.acceptancetestsstoragemanagementclient.models.StorageAccountKeys>` :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/listKeys' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'accountName': self._serialize.url("account_name", account_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.post(url, query_parameters) response = self._client.send(request, header_parameters, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('StorageAccountKeys', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def list( self, custom_headers=None, raw=False, **operation_config): """ Lists all the storage accounts available under the subscription. Note that storage keys are not returned; use the ListKeys operation for this. :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: :class:`StorageAccountPaged <fixtures.acceptancetestsstoragemanagementclient.models.StorageAccountPaged>` """ def internal_paging(next_link=None, raw=False): if not next_link: # Construct URL url = '/subscriptions/{subscriptionId}/providers/Microsoft.Storage/storageAccounts' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send( request, header_parameters, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response # Deserialize response deserialized = models.StorageAccountPaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.StorageAccountPaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized def list_by_resource_group( self, resource_group_name, custom_headers=None, raw=False, **operation_config): """ Lists all the storage accounts available under the given resource group. Note that storage keys are not returned; use the ListKeys operation for this. :param resource_group_name: The name of the resource group within the user’s subscription. :type resource_group_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: :class:`StorageAccountPaged <fixtures.acceptancetestsstoragemanagementclient.models.StorageAccountPaged>` """ def internal_paging(next_link=None, raw=False): if not next_link: # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send( request, header_parameters, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response # Deserialize response deserialized = models.StorageAccountPaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.StorageAccountPaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized def regenerate_key( self, resource_group_name, account_name, key_name=None, custom_headers=None, raw=False, **operation_config): """ Regenerates the access keys for the specified storage account. :param resource_group_name: The name of the resource group within the user’s subscription. :type resource_group_name: str :param account_name: The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. :type account_name: str :param key_name: Possible values include: 'key1', 'key2' :type key_name: str or :class:`KeyName <storagemanagementclient.models.KeyName>` :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: :class:`StorageAccountKeys <fixtures.acceptancetestsstoragemanagementclient.models.StorageAccountKeys>` :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true """ regenerate_key = models.StorageAccountRegenerateKeyParameters(key_name=key_name) # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/regenerateKey' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'accountName': self._serialize.url("account_name", account_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(regenerate_key, 'StorageAccountRegenerateKeyParameters') # Construct and send request request = self._client.post(url, query_parameters) response = self._client.send( request, header_parameters, body_content, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('StorageAccountKeys', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
{ "content_hash": "26e5a681d1ea18101c751b61aec336c8", "timestamp": "", "source": "github", "line_count": 671, "max_line_length": 154, "avg_line_length": 46.666169895678095, "alnum_prop": 0.6528278989557053, "repo_name": "sharadagarwal/autorest", "id": "d2583af6ef3d7e11bd00adead7d7ba9dae0d0fe4", "size": "31799", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/operations/storage_accounts_operations.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "12942" }, { "name": "C#", "bytes": "11450022" }, { "name": "CSS", "bytes": "110" }, { "name": "HTML", "bytes": "274" }, { "name": "Java", "bytes": "4693719" }, { "name": "JavaScript", "bytes": "4685941" }, { "name": "PowerShell", "bytes": "29614" }, { "name": "Python", "bytes": "2274436" }, { "name": "Ruby", "bytes": "232193" }, { "name": "Shell", "bytes": "423" }, { "name": "TypeScript", "bytes": "179577" } ], "symlink_target": "" }
package com.sudoku.data.manager; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import com.sudoku.data.model.Grid; import com.sudoku.data.model.PlayedGrid; import com.sudoku.data.model.User; public class GridManager { private List<Grid> availableGrids; private List<PlayedGrid> playedGrids; private GridManager instance; public GridManager(){ this.availableGrids = new ArrayList<Grid>(); this.playedGrids = new ArrayList<PlayedGrid>(); instance=this; } public GridManager getInstance(){ return instance; } public boolean addGrid(Grid grid){ return availableGrids.add(grid); } public PlayedGrid addPlayedGrid(Grid grid, User player){ return new PlayedGrid(grid, player); } public boolean addPlayedGrid(PlayedGrid pgrid){ return playedGrids.add(pgrid); } public boolean removeGrid(Grid grid){ return availableGrids.remove(grid); } public List<Grid> searchGrid(List<String> keywords){ //J'imagine qu'on recherche dans la description et pas dans les tags List<Grid> result = new ArrayList<Grid>(); for(String str:keywords){ for(Grid grid:availableGrids){ if(grid.getDescription().contains(str)) result.add(grid); } } return result; } public boolean updateGridList(List<String> keywords){ // BESOIN D'EXPLICATIONS POUR CETTE FONCTION. Je n'ai pas trouv // son existence dans le diag de squence return false; } public Grid getLatestPlayedGrid(){ Grid g=availableGrids.get(0); for(Grid grid:availableGrids){ if (grid.getUpdateDate().after(g.getUpdateDate())){ g=grid; } } return g; } public List<PlayedGrid> getFinishedGrid(){ List<PlayedGrid> result = new ArrayList<PlayedGrid>(); for(PlayedGrid grid:playedGrids){ if(grid.isComplete()) result.add(grid); } return result; } public List<PlayedGrid> getIncompleteGrid(){ List<PlayedGrid> result = new ArrayList<PlayedGrid>(); for(PlayedGrid grid:playedGrids){ if(!grid.isComplete()) result.add(grid); } return result; } public List<Grid> getAvailableGrids(){ return availableGrids; } }
{ "content_hash": "fce30396ae246f4ccfb0cc94800fc862", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 70, "avg_line_length": 24.186813186813186, "alnum_prop": 0.692412539754657, "repo_name": "CelineTo/new-repo", "id": "c379aa6ade46e3b31c1addda83c439021dffbe40", "size": "2201", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/sudoku/data/manager/GridManager.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "96959" } ], "symlink_target": "" }
import { Component } from 'angular2/core'; import {RouteData} from 'angular2/router'; @Component({ selector: 'home', template: "<h1>Dynamic</h1> <p>I'm data passed from route : {{foo}}</p>" }) export class DynamicPageComponent { foo: string; constructor(data: RouteData) { console.log('constructor with data', arguments); this.foo = data.get('foo'); console.log('foo ', this.foo); } }
{ "content_hash": "0c4f0513a74bc545762433d6d519ec8d", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 74, "avg_line_length": 19.80952380952381, "alnum_prop": 0.6466346153846154, "repo_name": "mattimatti/Angular2Exercises", "id": "7605580ddbc64d2c05cd61220992ad03ad2318ef", "size": "416", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/components/pages/DynamicPageComponent.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "785" }, { "name": "HTML", "bytes": "5620" }, { "name": "JavaScript", "bytes": "27310" }, { "name": "Smarty", "bytes": "25" }, { "name": "TypeScript", "bytes": "27004" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.cdn.generated; import com.azure.core.util.Context; import com.azure.resourcemanager.cdn.models.DeliveryRuleResponseHeaderAction; import com.azure.resourcemanager.cdn.models.HeaderAction; import com.azure.resourcemanager.cdn.models.HeaderActionParameters; import com.azure.resourcemanager.cdn.models.RuleUpdateParameters; import java.util.Arrays; /** Samples for Rules Update. */ public final class RulesUpdateSamples { /* * x-ms-original-file: specification/cdn/resource-manager/Microsoft.Cdn/stable/2021-06-01/examples/Rules_Update.json */ /** * Sample code: Rules_Update. * * @param azure The entry point for accessing resource management APIs in Azure. */ public static void rulesUpdate(com.azure.resourcemanager.AzureResourceManager azure) { azure .cdnProfiles() .manager() .serviceClient() .getRules() .update( "RG", "profile1", "ruleSet1", "rule1", new RuleUpdateParameters() .withOrder(1) .withActions( Arrays .asList( new DeliveryRuleResponseHeaderAction() .withParameters( new HeaderActionParameters() .withHeaderAction(HeaderAction.OVERWRITE) .withHeaderName("X-CDN") .withValue("MSFT")))), Context.NONE); } }
{ "content_hash": "6a8c58c0e0b62bd90abafa9927a48327", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 120, "avg_line_length": 38.645833333333336, "alnum_prop": 0.5606469002695418, "repo_name": "Azure/azure-sdk-for-java", "id": "70f3963614c83f35d8cc70265e9ff94391126b53", "size": "1855", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/cdn/generated/RulesUpdateSamples.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "8762" }, { "name": "Bicep", "bytes": "15055" }, { "name": "CSS", "bytes": "7676" }, { "name": "Dockerfile", "bytes": "2028" }, { "name": "Groovy", "bytes": "3237482" }, { "name": "HTML", "bytes": "42090" }, { "name": "Java", "bytes": "432409546" }, { "name": "JavaScript", "bytes": "36557" }, { "name": "Jupyter Notebook", "bytes": "95868" }, { "name": "PowerShell", "bytes": "737517" }, { "name": "Python", "bytes": "240542" }, { "name": "Scala", "bytes": "1143898" }, { "name": "Shell", "bytes": "18488" }, { "name": "XSLT", "bytes": "755" } ], "symlink_target": "" }
export interface RefreshTokenConfig { clientId: string; clientSecret: string; refreshToken: string; } export interface AccessTokenConfig { clientId: string; clientSecret: string; accessToken: string; }
{ "content_hash": "eb87aa0ecfffaa415ce677d919987773", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 37, "avg_line_length": 17.615384615384617, "alnum_prop": 0.7161572052401747, "repo_name": "alexa/alexa-skills-kit-sdk-for-nodejs", "id": "e009ee2fb40d9eeeff2e1359119f92a05f062a18", "size": "817", "binary": false, "copies": "1", "ref": "refs/heads/2.0.x", "path": "ask-smapi-sdk/lib/smapiClientBuilder/authMethods/AuthMethods.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "7044" }, { "name": "TypeScript", "bytes": "571480" } ], "symlink_target": "" }
package ClassesBasicas; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.OneToOne; @Entity public class Time { public Time(int id, String nome, String estado, int pontos, Tecnico tecnico) { this.id = id; this.nome = nome; this.estado = estado; this.pontos = pontos; this.tecnico = tecnico; } public Time() { // TODO Auto-generated constructor stub } @Id @Column(name = "time_id") private int id; private String nome; private String estado; private int pontos; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } public int getPontos() { return pontos; } public void setPontos(int pontos) { this.pontos = pontos; } public List<Jogador> getJogadores() { return jogadores; } public void setJogadores(List<Jogador> jogadores) { this.jogadores = jogadores; } public Tecnico getTecnico() { return tecnico; } public void setTecnico(Tecnico tecnico) { this.tecnico = tecnico; } @OneToMany(mappedBy = "time", targetEntity = Jogador.class, fetch = FetchType.LAZY, cascade = CascadeType.ALL) private List<Jogador> jogadores; @OneToOne @JoinColumn(name = "tecnico_id") private Tecnico tecnico; @OneToOne(fetch = FetchType.LAZY, mappedBy = "timecasa", optional = true) private Jogo jogo; @OneToOne(fetch = FetchType.LAZY, mappedBy = "timevisitante", optional = true) private Jogo j; }
{ "content_hash": "f019745074cbcf5a94473fe8c596a9a5", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 111, "avg_line_length": 20.38888888888889, "alnum_prop": 0.7204359673024523, "repo_name": "vinytufi/Java", "id": "ca7078d3961d8722190df0dafe7b6463e9891dc1", "size": "1835", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Futebol JPA(Vinícius Marinho)/src/ClassesBasicas/Time.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "67200" } ], "symlink_target": "" }
package cn.xlvip.ffmpeg.library.opengl; import android.opengl.EGL14; import android.opengl.EGLExt; import android.opengl.EGLConfig; import android.opengl.EGLContext; import android.opengl.EGLDisplay; import android.opengl.EGLSurface; import android.util.Log; import android.view.Surface; /** * Created by chenwenfeng on 2017/5/26. */ class InputSurface { private static final String TAG = "InputSurface"; private static final boolean VERBOSE = false; private static final int EGL_RECORDABLE_ANDROID = 0x3142; private static final int EGL_OPENGL_ES2_BIT = 4; private EGLDisplay mEGLDisplay; private EGLContext mEGLContext; private EGLSurface mEGLSurface; private Surface mSurface; /** * Creates an InputSurface from a Surface. */ public InputSurface(Surface surface) { if (surface == null) { throw new NullPointerException(); } mSurface = surface; eglSetup(); } /** * Prepares EGL. We want a GLES 2.0 context and a surface that supports recording. */ private void eglSetup() { mEGLDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY); if (mEGLDisplay == EGL14.EGL_NO_DISPLAY) { throw new RuntimeException("unable to get EGL14 display"); } int[] version = new int[2]; if (!EGL14.eglInitialize(mEGLDisplay, version, 0, version, 1)) { mEGLDisplay = null; throw new RuntimeException("unable to initialize EGL14"); } // Configure EGL for pbuffer and OpenGL ES 2.0. We want enough RGB bits // to be able to tell if the frame is reasonable. int[] attribList = { EGL14.EGL_RED_SIZE, 8, EGL14.EGL_GREEN_SIZE, 8, EGL14.EGL_BLUE_SIZE, 8, EGL14.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_RECORDABLE_ANDROID, 1, EGL14.EGL_NONE }; EGLConfig[] configs = new EGLConfig[1]; int[] numConfigs = new int[1]; if (!EGL14.eglChooseConfig(mEGLDisplay, attribList, 0, configs, 0, configs.length, numConfigs, 0)) { throw new RuntimeException("unable to find RGB888+recordable ES2 EGL config"); } // Configure context for OpenGL ES 2.0. int[] attrib_list = { EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, EGL14.EGL_NONE }; mEGLContext = EGL14.eglCreateContext(mEGLDisplay, configs[0], EGL14.EGL_NO_CONTEXT, attrib_list, 0); checkEglError("eglCreateContext"); if (mEGLContext == null) { throw new RuntimeException("null context"); } // Create a window surface, and attach it to the Surface we received. int[] surfaceAttribs = { EGL14.EGL_NONE }; mEGLSurface = EGL14.eglCreateWindowSurface(mEGLDisplay, configs[0], mSurface, surfaceAttribs, 0); checkEglError("eglCreateWindowSurface"); if (mEGLSurface == null) { throw new RuntimeException("surface was null"); } } /** * Discard all resources held by this class, notably the EGL context. Also releases the * Surface that was passed to our constructor. */ public void release() { if (EGL14.eglGetCurrentContext().equals(mEGLContext)) { // Clear the current context and surface to ensure they are discarded immediately. EGL14.eglMakeCurrent(mEGLDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT); } EGL14.eglDestroySurface(mEGLDisplay, mEGLSurface); EGL14.eglDestroyContext(mEGLDisplay, mEGLContext); //EGL14.eglTerminate(mEGLDisplay); mSurface.release(); // null everything out so future attempts to use this object will cause an NPE mEGLDisplay = null; mEGLContext = null; mEGLSurface = null; mSurface = null; } /** * Makes our EGL context and surface current. */ public void makeCurrent() { if (!EGL14.eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext)) { throw new RuntimeException("eglMakeCurrent failed"); } } /** * Calls eglSwapBuffers. Use this to "publish" the current frame. */ public boolean swapBuffers() { return EGL14.eglSwapBuffers(mEGLDisplay, mEGLSurface); } /** * Returns the Surface that the MediaCodec receives buffers from. */ public Surface getSurface() { return mSurface; } /** * Sends the presentation time stamp to EGL. Time is expressed in nanoseconds. */ public void setPresentationTime(long nsecs) { EGLExt.eglPresentationTimeANDROID(mEGLDisplay, mEGLSurface, nsecs); } /** * Checks for EGL errors. */ private void checkEglError(String msg) { boolean failed = false; int error; while ((error = EGL14.eglGetError()) != EGL14.EGL_SUCCESS) { Log.e(TAG, msg + ": EGL error: 0x" + Integer.toHexString(error)); failed = true; } if (failed) { throw new RuntimeException("EGL error encountered (see log)"); } } }
{ "content_hash": "b08ce7e580e848f617c5a6bfab002ca6", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 94, "avg_line_length": 36.37671232876713, "alnum_prop": 0.6125023536057239, "repo_name": "aopi1125/code_clean_templet", "id": "4a1313abb6c34926d57164cda228aea1a037e790", "size": "5311", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "library/src/main/java/cn/xlvip/ffmpeg/library/opengl/InputSurface.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "314" }, { "name": "C", "bytes": "851" }, { "name": "GLSL", "bytes": "99482" }, { "name": "Java", "bytes": "501886" }, { "name": "Makefile", "bytes": "350" } ], "symlink_target": "" }
package prefuse.data.expression; import java.util.Iterator; import prefuse.data.Tuple; /** * Predicate representing an "or" clause of sub-predicates. * * @author <a href="http://jheer.org">jeffrey heer</a> */ public class OrPredicate extends CompositePredicate { /** * Create an empty OrPredicate. Empty OrPredicates return false * by default. */ public OrPredicate() { } /** * Create a new OrPredicate. * @param p1 the sole clause of this predicate */ public OrPredicate(Predicate p1) { add(p1); } /** * Create a new OrPredicate. * @param p1 the first clause of this predicate * @param p2 the second clause of this predicate */ public OrPredicate(Predicate p1, Predicate p2) { super(p1, p2); } /** * @see prefuse.data.expression.Expression#getBoolean(prefuse.data.Tuple) */ public boolean getBoolean(Tuple t) { if ( m_clauses.size() == 0 ) return false; Iterator iter = m_clauses.iterator(); while ( iter.hasNext() ) { Predicate p = (Predicate)iter.next(); if ( p.getBoolean(t) ) { return true; } } return false; } /** * @see java.lang.Object#toString() */ public String toString() { return ( size() == 0 ? "FALSE" : toString("OR") ); } } // end of class OrPredicate
{ "content_hash": "ff8df50147919ef065c2529c87cb7efc", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 77, "avg_line_length": 23.612903225806452, "alnum_prop": 0.5614754098360656, "repo_name": "ezegarra/microbrowser", "id": "58d39c25fda492f33ed00700246bffa3197f1804", "size": "1464", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/prefuse/data/expression/OrPredicate.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1387" }, { "name": "HTML", "bytes": "17064" }, { "name": "Java", "bytes": "3210397" }, { "name": "PLSQL", "bytes": "982379" }, { "name": "PLpgSQL", "bytes": "3792" }, { "name": "Python", "bytes": "20754" }, { "name": "R", "bytes": "3202" }, { "name": "Shell", "bytes": "587" } ], "symlink_target": "" }
import { NgRedux, select } from '@angular-redux/store'; import { Component, isDevMode, OnInit, ViewChild } from '@angular/core'; import * as L from 'leaflet'; import { Spinkit } from 'ng-http-loader'; import { CarouselConfig, ModalDirective } from 'ngx-bootstrap'; import { Observable, Subject } from 'rxjs'; import { debounceTime, distinctUntilChanged } from 'rxjs/operators'; import { AuthService } from '../../services/auth.service'; import { DbService } from '../../services/db.service'; import { EditService } from '../../services/edit.service'; import { GeocodeService } from '../../services/geocode.service'; import { MapService } from '../../services/map.service'; import { OverpassService } from '../../services/overpass.service'; import { ProcessService } from '../../services/process.service'; import { AppActions } from '../../store/app/actions'; import { IAppState } from '../../store/model'; import { AuthComponent } from '../auth/auth.component'; import { ToolbarComponent } from '../toolbar/toolbar.component'; @Component({ providers: [{ provide: CarouselConfig, useValue: { noPause: false } }], selector: 'app', styleUrls: [ './app.component.less', ], templateUrl: './app.component.html', }) export class AppComponent implements OnInit { spinkit = Spinkit; advancedMode: boolean = Boolean(localStorage.getItem('advancedMode')); @ViewChild(ToolbarComponent) toolbarComponent: ToolbarComponent; @ViewChild(AuthComponent) authComponent: AuthComponent; @ViewChild('helpModal') helpModal: ModalDirective; @select(['app', 'editing']) readonly editing$: Observable<boolean>; @select(['app', 'advancedExpMode']) readonly advancedExpMode$: Observable<boolean>; @select(['app', 'tutorialMode']) readonly tutorialMode$: Observable<boolean>; private startEventProcessing = new Subject<L.LeafletEvent>(); constructor( public appActions: AppActions, private ngRedux: NgRedux<IAppState>, private dbSrv: DbService, private editSrv: EditService, private geocodeSrv: GeocodeService, private mapSrv: MapService, private overpassSrv: OverpassService, private processSrv: ProcessService, private authSrv: AuthService, ) { if (isDevMode()) { console.log('WARNING: Ang. development mode is ', isDevMode()); } } ngOnInit(): any { this.dbSrv.deleteExpiredDataIDB(); this.dbSrv.deleteExpiredPTDataIDB().then(() => { console.log('LOG (app component) Successfully checked and deleted old items from IDB'); }).catch((err) => { console.log('LOG (app component) Error in deleting old items from IDB'); console.log(err); }); this.dbSrv.getCompletelyDownloadedElementsId(); this.dbSrv.getIdsQueriedRoutesForMaster(); const map = L.map('map', { center: L.latLng(49.686, 18.351), layers: [this.mapSrv.baseMaps.CartoDB_light], maxZoom: 22, minZoom: 4, zoom: 14, zoomAnimation: false, zoomControl: false, }); L.control.zoom({ position: 'topright' }).addTo(map); L.control.layers(this.mapSrv.baseMaps).addTo(map); L.control.scale().addTo(map); this.mapSrv.map = map; this.mapSrv.map.on('zoomend moveend', (event: L.LeafletEvent) => { this.startEventProcessing.next(event); }); this.startEventProcessing.pipe( debounceTime(500), distinctUntilChanged() ) .subscribe((event: L.LeafletEvent) => { this.processSrv.addPositionToUrlHash(); this.overpassSrv.initDownloader(this.mapSrv.map); this.processSrv.filterDataInBounds(); }); if ( window.location.hash !== '' && this.processSrv.hashIsValidPosition() ) { this.mapSrv.zoomToHashedPosition(); } else { this.geocodeSrv.getCurrentLocation(); } } hideHelpModal(): void { this.helpModal.hide(); } private showHelpModal(): void { this.helpModal.show(); } startTutorials(): void { this.appActions.actToggleTutorialMode(true); } isAuthenticated(): void { return this.authSrv.oauth.authenticated(); } }
{ "content_hash": "31fc197e7cffedc9cd103ad44eb83684", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 93, "avg_line_length": 34.23529411764706, "alnum_prop": 0.6782032400589102, "repo_name": "dkocich/osm-pt-ngx-leaflet", "id": "1800d8a394a27311d674d3fcd4667045360f0fd9", "size": "4074", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/components/app/app.component.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "80" }, { "name": "Dockerfile", "bytes": "473" }, { "name": "HTML", "bytes": "84204" }, { "name": "JavaScript", "bytes": "57440" }, { "name": "Less", "bytes": "4863" }, { "name": "Procfile", "bytes": "56" }, { "name": "TypeScript", "bytes": "421689" } ], "symlink_target": "" }
import material from 'vue-material/material' import MdDivider from './MdDivider' export default Vue => { material(Vue) Vue.component(MdDivider.name, MdDivider) }
{ "content_hash": "cb9ad705761250f0a1700829c2fae443", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 44, "avg_line_length": 23.857142857142858, "alnum_prop": 0.7544910179640718, "repo_name": "marcosmoura/vue-material", "id": "804b484fa859cbd5ea9c8be5b5564044ea9b5aa9", "size": "167", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/components/MdDivider/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "87031" }, { "name": "JavaScript", "bytes": "47434" }, { "name": "Shell", "bytes": "1374" }, { "name": "Vue", "bytes": "112894" } ], "symlink_target": "" }
from django.conf.urls.defaults import * from registration.views import activate from registration.views import register urlpatterns = patterns('', url(r'^register/$', register, {'backend': 'userprofile.backends.simple.SimpleBackend'}, name='registration_register'), )
{ "content_hash": "0b7943a76a2c2a0c31f63feca60aebc2", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 61, "avg_line_length": 23.916666666666668, "alnum_prop": 0.7317073170731707, "repo_name": "praekelt/django-userprofile", "id": "5bc6865f379e0cab17ae13ca8df88fc37ec147cb", "size": "287", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "userprofile/backends/simple/urls.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "258" }, { "name": "Python", "bytes": "17725" } ], "symlink_target": "" }
/* Copyright 2011 Dean Camera (dean [at] fourwalledcubicle [dot] com) Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name of the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. The author disclaim all warranties with regard to this software, including all implied warranties of merchantability and fitness. In no event shall the author be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software. */ /** \file * * V2Protocol parameter handler, to process V2 Protocol device parameters. */ #define INCLUDE_FROM_V2PROTOCOL_PARAMS_C #include "V2ProtocolParams.h" /* Non-Volatile Parameter Values for EEPROM storage */ static uint8_t EEMEM EEPROM_Rest_Polarity = 0x00; /* Volatile Parameter Values for RAM storage */ static ParameterItem_t ParameterTable[] = { { .ParamID = PARAM_BUILD_NUMBER_LOW, .ParamPrivileges = PARAM_PRIV_READ, .ParamValue = 0 }, { .ParamID = PARAM_BUILD_NUMBER_HIGH, .ParamPrivileges = PARAM_PRIV_READ, .ParamValue = 0 }, { .ParamID = PARAM_HW_VER, .ParamPrivileges = PARAM_PRIV_READ, .ParamValue = 0x00 }, { .ParamID = PARAM_SW_MAJOR, .ParamPrivileges = PARAM_PRIV_READ, .ParamValue = 0x01 }, { .ParamID = PARAM_SW_MINOR, .ParamPrivileges = PARAM_PRIV_READ, .ParamValue = 0x0D }, { .ParamID = PARAM_VTARGET, .ParamPrivileges = PARAM_PRIV_READ, .ParamValue = 0x32 }, { .ParamID = PARAM_SCK_DURATION, .ParamPrivileges = PARAM_PRIV_READ | PARAM_PRIV_WRITE, .ParamValue = 6 }, { .ParamID = PARAM_RESET_POLARITY, .ParamPrivileges = PARAM_PRIV_WRITE, .ParamValue = 0x01 }, { .ParamID = PARAM_STATUS_TGT_CONN, .ParamPrivileges = PARAM_PRIV_READ, .ParamValue = STATUS_ISP_READY }, { .ParamID = PARAM_DISCHARGEDELAY, .ParamPrivileges = PARAM_PRIV_WRITE, .ParamValue = 0x00 }, }; /** Loads saved non-volatile parameter values from the EEPROM into the parameter table, as needed. */ void V2Params_LoadNonVolatileParamValues(void) { /* Target RESET line polarity is a non-volatile value, retrieve current parameter value from EEPROM */ V2Params_GetParamFromTable(PARAM_RESET_POLARITY)->ParamValue = eeprom_read_byte(&EEPROM_Rest_Polarity); } /** Updates any parameter values that are sourced from hardware rather than explicitly set by the host, such as * VTARGET levels from the ADC on supported AVR models. */ void V2Params_UpdateParamValues(void) { #if (defined(ADC) && !defined(NO_VTARGET_DETECT)) /* Update VTARGET parameter with the latest ADC conversion of VTARGET on supported AVR models */ V2Params_GetParamFromTable(PARAM_VTARGET)->ParamValue = (((uint16_t)(VTARGET_REF_VOLTS * 10 * VTARGET_SCALE_FACTOR) * ADC_GetResult()) / 1024); #endif } /** Retrieves the host PC read/write privileges for a given parameter in the parameter table. This should * be called before calls to \ref V2Params_GetParameterValue() or \ref V2Params_SetParameterValue() when * getting or setting parameter values in response to requests from the host. * * \param[in] ParamID Parameter ID whose privileges are to be retrieved from the table * * \return Privileges for the requested parameter, as a mask of PARAM_PRIV_* masks */ uint8_t V2Params_GetParameterPrivileges(const uint8_t ParamID) { ParameterItem_t* ParamInfo = V2Params_GetParamFromTable(ParamID); if (ParamInfo == NULL) return 0; return ParamInfo->ParamPrivileges; } /** Retrieves the current value for a given parameter in the parameter table. * * \note This function does not first check for read privileges - if the value is being sent to the host via a * GET PARAM command, \ref V2Params_GetParameterPrivileges() should be called first to ensure that the * parameter is host-readable. * * \param[in] ParamID Parameter ID whose value is to be retrieved from the table * * \return Current value of the parameter in the table, or 0 if not found */ uint8_t V2Params_GetParameterValue(const uint8_t ParamID) { ParameterItem_t* ParamInfo = V2Params_GetParamFromTable(ParamID); if (ParamInfo == NULL) return 0; return ParamInfo->ParamValue; } /** Sets the value for a given parameter in the parameter table. * * \note This function does not first check for write privileges - if the value is being sourced from the host * via a SET PARAM command, \ref V2Params_GetParameterPrivileges() should be called first to ensure that the * parameter is host-writable. * * \param[in] ParamID Parameter ID whose value is to be set in the table * \param[in] Value New value to set the parameter to * * \return Pointer to the associated parameter information from the parameter table if found, NULL otherwise */ void V2Params_SetParameterValue(const uint8_t ParamID, const uint8_t Value) { ParameterItem_t* ParamInfo = V2Params_GetParamFromTable(ParamID); if (ParamInfo == NULL) return; ParamInfo->ParamValue = Value; /* The target RESET line polarity is a non-volatile parameter, save to EEPROM when changed */ if (ParamID == PARAM_RESET_POLARITY) eeprom_update_byte(&EEPROM_Rest_Polarity, Value); } /** Retrieves a parameter entry (including ID, value and privileges) from the parameter table that matches the given * parameter ID. * * \param[in] ParamID Parameter ID to find in the table * * \return Pointer to the associated parameter information from the parameter table if found, NULL otherwise */ static ParameterItem_t* V2Params_GetParamFromTable(const uint8_t ParamID) { ParameterItem_t* CurrTableItem = ParameterTable; /* Find the parameter in the parameter table if present */ for (uint8_t TableIndex = 0; TableIndex < TABLE_PARAM_COUNT; TableIndex++) { if (ParamID == CurrTableItem->ParamID) return CurrTableItem; CurrTableItem++; } return NULL; }
{ "content_hash": "8bd60caf8aefe79e17ecdd175b0ffe23", "timestamp": "", "source": "github", "line_count": 185, "max_line_length": 144, "avg_line_length": 38.25405405405405, "alnum_prop": 0.6641232160519994, "repo_name": "eiannone/CANBus-Triple", "id": "4f53fc6ccf02770516b4f81a6735773ea48fb01f", "size": "7221", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "avr/bootloaders/caterina/LUFA-111009/Projects/AVRISP-MKII/Lib/V2ProtocolParams.c", "mode": "33261", "license": "mit", "language": [ { "name": "Arduino", "bytes": "10900" }, { "name": "Assembly", "bytes": "9179" }, { "name": "C", "bytes": "4652610" }, { "name": "C#", "bytes": "20856" }, { "name": "C++", "bytes": "1136516" }, { "name": "HTML", "bytes": "482" }, { "name": "Makefile", "bytes": "1795341" }, { "name": "Objective-C", "bytes": "13760" } ], "symlink_target": "" }