max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,602
#ifdef HAVE_CONFIG_H # include "config.h" /* for _GNU_SOURCE */ #endif #include <assert.h> #include <stdio.h> #include <qthread/qthread.h> #ifndef SERIAL_FORKING # include <qthread/qloop.h> #endif #include <qthread/qtimer.h> #include "argparsing.h" static aligned_t null_task(void *args_) { return 42; } static void par_null_task(size_t start, size_t stop, void *args_) {} int main(int argc, char *argv[]) { uint64_t count = 0; int par_fork = 0; qtimer_t timer; double total_time = 0.0; CHECK_VERBOSE(); NUMARG(count, "MT_COUNT"); NUMARG(par_fork, "MT_PAR_FORK"); assert(0 != count); assert(qthread_initialize() == 0); syncvar_t *rets = NULL; for (uint64_t i = 0; i < count; i++) rets[i] = SYNCVAR_EMPTY_INITIALIZER; timer = qtimer_create(); if (par_fork) { qtimer_start(timer); qt_loop_sv(0, count, par_null_task, NULL); qtimer_stop(timer); } else { rets = calloc(count, sizeof(syncvar_t)); qtimer_start(timer); for (uint64_t i = 0; i < count; i++) { qthread_fork_syncvar(null_task, NULL, &rets[i]); } for (uint64_t i = 0; i < count; i++) { qthread_syncvar_readFF(NULL, &rets[i]); } qtimer_stop(timer); } total_time = qtimer_secs(timer); qtimer_destroy(timer); printf("%lu %lu %f\n", (unsigned long)qthread_num_workers(), (unsigned long)count, total_time); return 0; } /* vim:set expandtab */
808
1,056
/* * AddSemicolon.java * * Created on March 12, 2005, 8:07 PM */ package org.netbeans.test.java.hints; /** * * @author lahvac */ public class AddSemicolon { /** Creates a new instance of AddSemicolon */ public AddSemicolon() { int test } }
119
1,109
<reponame>qiquanzhijia/gryphon<gh_stars>1000+ import os from sqlalchemy import UnicodeText, TypeDecorator from gryphon.lib.encrypt import * try: DB_ENCRYPT_KEY = os.environ['DB_ENCRYPT_KEY'] except: raise Exception("""Requires environment variables: DB_ENCRYPT_KEY""") class EncryptedUnicodeText(TypeDecorator): impl = UnicodeText def process_bind_param(self, value, dialect): secret_key = DB_ENCRYPT_KEY if value: return encrypt(value, secret_key) else: return value def process_result_value(self, value, dialect): secret_key = DB_ENCRYPT_KEY if value: return decrypt(value, secret_key) else: return value
318
1,056
<reponame>timfel/netbeans /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.javascript.nodejs.ui; import java.awt.Image; import java.awt.event.ActionEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Objects; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.event.ChangeListener; import org.netbeans.api.annotations.common.StaticResource; import org.netbeans.api.project.Project; import org.netbeans.modules.javascript.nodejs.file.PackageJson; import org.netbeans.modules.javascript.nodejs.ui.libraries.LibraryCustomizer; import org.netbeans.spi.project.ui.CustomizerProvider2; import org.netbeans.spi.project.ui.support.NodeFactory; import org.netbeans.spi.project.ui.support.NodeList; import org.openide.filesystems.FileUtil; import org.openide.loaders.DataFolder; import org.openide.nodes.AbstractNode; import org.openide.nodes.Children; import org.openide.nodes.Node; import org.openide.util.ChangeSupport; import org.openide.util.ImageUtilities; import org.openide.util.NbBundle; import org.openide.util.WeakListeners; public final class NpmLibraries { private NpmLibraries() { } @NodeFactory.Registration(projectType = "org-netbeans-modules-web-clientproject", position = 600) public static NodeFactory forHtml5Project() { return new NpmLibrariesNodeFactory(); } @NodeFactory.Registration(projectType = "org-netbeans-modules-php-project", position = 400) public static NodeFactory forPhpProject() { return new NpmLibrariesNodeFactory(); } @NodeFactory.Registration(projectType = "org-netbeans-modules-web-project", position = 310) public static NodeFactory forWebProject() { return new NpmLibrariesNodeFactory(); } @NodeFactory.Registration(projectType = "org-netbeans-modules-maven", position = 610) public static NodeFactory forMavenProject() { return new NpmLibrariesNodeFactory(); } //~ Inner classes private static final class NpmLibrariesNodeFactory implements NodeFactory { @Override public NodeList<?> createNodes(Project project) { assert project != null; return new NpmLibrariesNodeList(project); } } private static final class NpmLibrariesNodeList implements NodeList<Node>, PropertyChangeListener { private final Project project; private final PackageJson packageJson; private final NpmLibrariesChildren npmLibrariesChildren; private final ChangeSupport changeSupport = new ChangeSupport(this); // @GuardedBy("thread") private Node npmLibrariesNode; NpmLibrariesNodeList(Project project) { assert project != null; this.project = project; packageJson = new PackageJson(project.getProjectDirectory()); npmLibrariesChildren = new NpmLibrariesChildren(packageJson); } @Override public List<Node> keys() { if (!npmLibrariesChildren.hasDependencies()) { return Collections.<Node>emptyList(); } if (npmLibrariesNode == null) { npmLibrariesNode = new NpmLibrariesNode(project, npmLibrariesChildren); } return Collections.<Node>singletonList(npmLibrariesNode); } @Override public void addChangeListener(ChangeListener listener) { changeSupport.addChangeListener(listener); } @Override public void removeChangeListener(ChangeListener listener) { changeSupport.removeChangeListener(listener); } @Override public Node node(Node key) { return key; } @Override public void addNotify() { packageJson.addPropertyChangeListener(WeakListeners.propertyChange(this, packageJson)); } @Override public void removeNotify() { } @Override public void propertyChange(PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if (PackageJson.PROP_DEPENDENCIES.equals(propertyName) || PackageJson.PROP_DEV_DEPENDENCIES.equals(propertyName) || PackageJson.PROP_PEER_DEPENDENCIES.equals(propertyName) || PackageJson.PROP_OPTIONAL_DEPENDENCIES.equals(propertyName)) { fireChange(); } } private void fireChange() { npmLibrariesChildren.refreshDependencies(); changeSupport.fireChange(); } } private static final class NpmLibrariesNode extends AbstractNode { @StaticResource private static final String LIBRARIES_BADGE = "org/netbeans/modules/javascript/nodejs/ui/resources/libraries-badge.png"; // NOI18N private final Project project; private final Node iconDelegate; NpmLibrariesNode(Project project, NpmLibrariesChildren npmLibrariesChildren) { super(npmLibrariesChildren); assert project != null; this.project = project; iconDelegate = DataFolder.findFolder(FileUtil.getConfigRoot()).getNodeDelegate(); } @NbBundle.Messages("NpmLibrariesNode.name=npm Libraries") @Override public String getDisplayName() { return Bundle.NpmLibrariesNode_name(); } @Override public Image getIcon(int type) { return ImageUtilities.mergeImages(iconDelegate.getIcon(type), ImageUtilities.loadImage(LIBRARIES_BADGE), 7, 7); } @Override public Image getOpenedIcon(int type) { return getIcon(type); } @Override public Action[] getActions(boolean context) { return new Action[] { new CustomizeLibrariesAction(project), }; } } private static final class NpmLibrariesChildren extends Children.Keys<NpmLibraryInfo> { @StaticResource private static final String LIBRARIES_ICON = "org/netbeans/modules/javascript/nodejs/ui/resources/libraries.gif"; // NOI18N @StaticResource private static final String DEV_BADGE = "org/netbeans/modules/javascript/nodejs/ui/resources/libraries-dev-badge.gif"; // NOI18N @StaticResource private static final String PEER_BADGE = "org/netbeans/modules/javascript/nodejs/ui/resources/libraries-peer-badge.png"; // NOI18N @StaticResource private static final String OPTIONAL_BADGE = "org/netbeans/modules/javascript/nodejs/ui/resources/libraries-optional-badge.png"; // NOI18N private final PackageJson packageJson; private final java.util.Map<String, Image> icons = new HashMap<>(); public NpmLibrariesChildren(PackageJson packageJson) { super(true); assert packageJson != null; this.packageJson = packageJson; } public boolean hasDependencies() { return !packageJson.getDependencies().isEmpty(); } public void refreshDependencies() { setKeys(); } @Override protected Node[] createNodes(NpmLibraryInfo key) { return new Node[] {new NpmLibraryNode(key)}; } @NbBundle.Messages({ "NpmLibrariesChildren.library.dev=dev", "NpmLibrariesChildren.library.optional=optional", "NpmLibrariesChildren.library.peer=peer", }) @Override protected void addNotify() { setKeys(); } @Override protected void removeNotify() { setKeys(Collections.<NpmLibraryInfo>emptyList()); } private void setKeys() { PackageJson.NpmDependencies dependencies = packageJson.getDependencies(); if (dependencies.isEmpty()) { setKeys(Collections.<NpmLibraryInfo>emptyList()); return; } List<NpmLibraryInfo> keys = new ArrayList<>(dependencies.getCount()); keys.addAll(getKeys(dependencies.dependencies, null, null)); keys.addAll(getKeys(dependencies.devDependencies, DEV_BADGE, Bundle.NpmLibrariesChildren_library_dev())); keys.addAll(getKeys(dependencies.optionalDependencies, OPTIONAL_BADGE, Bundle.NpmLibrariesChildren_library_optional())); keys.addAll(getKeys(dependencies.peerDependencies, PEER_BADGE, Bundle.NpmLibrariesChildren_library_peer())); setKeys(keys); } @NbBundle.Messages({ "# {0} - library name", "# {1} - library version", "NpmLibrariesChildren.description.short={0}: {1}", "# {0} - library name", "# {1} - library version", "# {2} - library type", "NpmLibrariesChildren.description.long={0}: {1} ({2})", }) private List<NpmLibraryInfo> getKeys(java.util.Map<String, String> dependencies, String badge, String libraryType) { if (dependencies.isEmpty()) { return Collections.emptyList(); } List<NpmLibraryInfo> keys = new ArrayList<>(dependencies.size()); for (java.util.Map.Entry<String, String> entry : dependencies.entrySet()) { String description; if (libraryType != null) { description = Bundle.NpmLibrariesChildren_description_long(entry.getKey(), entry.getValue(), libraryType); } else { description = Bundle.NpmLibrariesChildren_description_short(entry.getKey(), entry.getValue()); } keys.add(new NpmLibraryInfo(geIcon(badge), entry.getKey(), description)); } Collections.sort(keys); return keys; } private Image geIcon(String badge) { Image icon = icons.get(badge); if (icon == null) { icon = ImageUtilities.loadImage(LIBRARIES_ICON); if (badge != null) { icon = ImageUtilities.mergeImages(icon, ImageUtilities.loadImage(badge), 8, 8); } icons.put(badge, icon); } return icon; } } private static final class NpmLibraryNode extends AbstractNode { private final NpmLibraryInfo libraryInfo; NpmLibraryNode(NpmLibraryInfo libraryInfo) { super(Children.LEAF); this.libraryInfo = libraryInfo; } @Override public String getName() { return libraryInfo.name; } @Override public String getShortDescription() { return libraryInfo.description; } @Override public Image getIcon(int type) { return libraryInfo.icon; } @Override public Image getOpenedIcon(int type) { return libraryInfo.icon; } @Override public Action[] getActions(boolean context) { return new Action[0]; } } private static final class NpmLibraryInfo implements Comparable<NpmLibraryInfo> { final Image icon; final String name; final String description; NpmLibraryInfo(Image icon, String name, String descrition) { assert icon != null; assert name != null; assert descrition != null; this.icon = icon; this.name = name; this.description = descrition; } @Override public int compareTo(NpmLibraryInfo other) { return name.compareToIgnoreCase(other.name); } @Override public int hashCode() { int hash = 5; hash = 13 * hash + Objects.hashCode(this.name); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final NpmLibraryInfo other = (NpmLibraryInfo) obj; return name.equalsIgnoreCase(other.name); } } private static final class CustomizeLibrariesAction extends AbstractAction { private final Project project; @NbBundle.Messages("CustomizeLibrariesAction.name=Properties") CustomizeLibrariesAction(Project project) { assert project != null; this.project = project; String name = Bundle.CustomizeLibrariesAction_name(); putValue(NAME, name); putValue(SHORT_DESCRIPTION, name); } @Override public void actionPerformed(ActionEvent e) { project.getLookup().lookup(CustomizerProvider2.class).showCustomizer(LibraryCustomizer.CATEGORY_NAME, null); } } }
5,789
3,921
/* * Created by LuaView. * Copyright (c) 2017, Alibaba Group. All rights reserved. * * This source code is licensed under the MIT. * For the full copyright and license information,please view the LICENSE file in the root directory of this source tree. */ package com.taobao.luaview.util; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; /** * Alert * @author song */ public class AlertUtil { /** * show an system default alert dialog with given title, msg, ok, cancel, listeners * * @param context * @param title * @param msg * @param ok * @param cancel * @param lOk * @param lCancel */ public static void showAlert(Context context, int title, int msg, int ok, int cancel, DialogInterface.OnClickListener lOk, DialogInterface.OnClickListener lCancel) { AlertDialog dialog = buildAlert(context, title, msg, ok, cancel, lOk, lCancel); if (dialog != null) { dialog.show(); } } /** * show an system default alert dialog with given title, msg, ok, cancal, listeners * * @param context * @param title * @param msg * @param ok * @param cancel * @param lOk * @param lCancel */ public static void showAlert(Context context, CharSequence title, CharSequence msg, CharSequence ok, CharSequence cancel, DialogInterface.OnClickListener lOk, DialogInterface.OnClickListener lCancel) { AlertDialog dialog = buildAlert(context, title, msg, ok, cancel, lOk, lCancel); if (dialog != null) { dialog.show(); } } /** * show an system default alert dialog with given title, msg, ok, cancal, listeners * * @param context * @param title * @param msg * @param ok * @param lOk */ public static void showAlert(Context context, CharSequence title, CharSequence msg, CharSequence ok, DialogInterface.OnClickListener lOk) { AlertDialog dialog = buildAlert(context, title, msg, ok, null, lOk, null); if (dialog != null) { dialog.show(); } } /** * build a alert dialog * * @param context * @param title * @param msg * @param ok * @param cancel * @param lOk * @param lCancel * @return */ public static AlertDialog buildAlert(Context context, Integer title, Integer msg, Integer ok, Integer cancel, DialogInterface.OnClickListener lOk, DialogInterface.OnClickListener lCancel) { AlertDialog.Builder builder = new AlertDialog.Builder(context); if (title != null) builder.setTitle(title); if (msg != null) builder.setMessage(msg); if (ok != null) builder.setPositiveButton(ok, lOk); if (cancel != null) builder.setNegativeButton(cancel, lCancel); return builder.create(); } /** * build a alert dialog * * @param context * @param title * @param msg * @param ok * @param cancel * @param lOk * @param lCancel * @return */ public static AlertDialog buildAlert(Context context, CharSequence title, CharSequence msg, CharSequence ok, CharSequence cancel, DialogInterface.OnClickListener lOk, DialogInterface.OnClickListener lCancel) { AlertDialog.Builder builder = new AlertDialog.Builder(context); if (title != null) builder.setTitle(title); if (msg != null) builder.setMessage(msg); if (ok != null) builder.setPositiveButton(ok, lOk); if (cancel != null) builder.setNegativeButton(cancel, lCancel); return builder.create(); } }
1,382
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.resourcehealth.models; import com.azure.core.util.ExpandableStringEnum; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** Defines values for StageValues. */ public final class StageValues extends ExpandableStringEnum<StageValues> { /** Static value Active for StageValues. */ public static final StageValues ACTIVE = fromString("Active"); /** Static value Resolve for StageValues. */ public static final StageValues RESOLVE = fromString("Resolve"); /** Static value Archived for StageValues. */ public static final StageValues ARCHIVED = fromString("Archived"); /** * Creates or finds a StageValues from its string representation. * * @param name a name to look for. * @return the corresponding StageValues. */ @JsonCreator public static StageValues fromString(String name) { return fromString(name, StageValues.class); } /** @return known StageValues values. */ public static Collection<StageValues> values() { return values(StageValues.class); } }
383
307
<reponame>haducloc/appslandia-common // The MIT License (MIT) // Copyright © 2015 AppsLandia. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package com.appslandia.common.base; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import com.appslandia.common.utils.AssertUtils; /** * * @author <a href="mailto:<EMAIL>"><NAME></a> * */ public abstract class ThreadSafeTester extends InitializeObject { private int tasks = 100; private int threads = 8; private CountDownLatch countDownLatch; private ExecutorService executorService; @Override protected void init() throws Exception { AssertUtils.assertTrue(this.tasks > 0); AssertUtils.assertTrue(this.threads > 0); this.executorService = Executors.newFixedThreadPool(this.threads); this.countDownLatch = new CountDownLatch(this.tasks); } public ThreadSafeTester tasks(int tasks) { assertNotInitialized(); this.tasks = tasks; return this; } public ThreadSafeTester threads(int threads) { assertNotInitialized(); this.threads = threads; return this; } protected abstract Runnable newTask(); public ThreadSafeTester executeThenAwait() { return executeThenAwait(0, null); } public ThreadSafeTester executeThenAwait(long timeout, TimeUnit unit) { initialize(); for (int i = 0; i < this.tasks; i++) { this.executorService.execute(newTask()); } try { if (timeout == 0) { this.countDownLatch.await(); } else { this.countDownLatch.await(timeout, unit); } } catch (InterruptedException ex) { throw new UncheckedException(ex); } this.executorService.shutdown(); return this; } protected void countDown() { this.countDownLatch.countDown(); } }
882
335
<filename>H/Huddle_verb.json { "word": "Huddle", "definitions": [ "Crowd together; nestle closely.", "Curl one's body into a small space.", "Heap together in a disorderly manner.", "Have a private discussion; confer." ], "parts-of-speech": "Verb" }
124
2,146
<filename>examples/zip/boo.cpp #include <zip/zip.h> int main() { struct zip_t *zip = zip_open("dummy", ZIP_DEFAULT_COMPRESSION_LEVEL, 'w'); zip_close(zip); return 0; }
75
1,350
<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.security.keyvault.administration.models; /** * A class that represents the result of a SelectiveKeyRestore operation. */ public final class KeyVaultSelectiveKeyRestoreResult { }
85
879
package org.zstack.sdk; public enum TagPatternType { simple, withToken, }
29
713
<gh_stars>100-1000 package org.infinispan.persistence.spi; /** * An exception thrown by the {@link org.infinispan.persistence.manager.PersistenceManager} if one or more * stores are unavailable when a cache operation is attempted. * * @author <NAME> * @since 9.3 */ public class StoreUnavailableException extends PersistenceException { public StoreUnavailableException() { } public StoreUnavailableException(String message) { super(message); } public StoreUnavailableException(String message, Throwable cause) { super(message, cause); } public StoreUnavailableException(Throwable cause) { super(cause); } }
201
416
// // ILClassificationUIExtensionContext.h // IdentityLookup // // Copyright © 2018 Apple. All rights reserved. // #import <Foundation/Foundation.h> #import <IdentityLookup/IdentityLookup.h> NS_ASSUME_NONNULL_BEGIN @class ILClassificationResponse; /// Represents a Classification UI extension request's context. IL_EXTERN API_AVAILABLE(ios(12.0), macCatalyst(13.0)) API_UNAVAILABLE( macos, tvos, watchos) @interface ILClassificationUIExtensionContext : NSExtensionContext @property (nonatomic, getter=isReadyForClassificationResponse) BOOL readyForClassificationResponse; @end NS_ASSUME_NONNULL_END
203
2,003
// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "util/testharness.h" #include "db/db_impl.h" namespace leveldb { class EnvForVeriyDbInGetPropertyCase1 : public EnvWrapper { public: EnvForVeriyDbInGetPropertyCase1() : EnvWrapper(Env::Default()) {} virtual Status GetChildren(const std::string& dir, std::vector<std::string>* r) { return Status::OK(); } virtual Status GetFileSize(const std::string& f, uint64_t* s) { *s = 789; return Status::OK(); } void SetDBImpl(DBImpl* impl) { impl_ = impl; } public: DBImpl* impl_; }; class EnvForVeriyDbInGetPropertyCase2 : public EnvWrapper { public: EnvForVeriyDbInGetPropertyCase2() : EnvWrapper(Env::Default()) {} virtual Status GetChildren(const std::string& dir, std::vector<std::string>* r) { r->push_back("456.sst"); impl_->shutting_down_.Release_Store(impl_); return Status::OK(); } virtual Status GetFileSize(const std::string& f, uint64_t* s) { *s = 789; return Status::OK(); } void SetDBImpl(DBImpl* impl) { impl_ = impl; } public: DBImpl* impl_; }; class EnvForVeriyDbInGetPropertyCase3 : public EnvWrapper { public: EnvForVeriyDbInGetPropertyCase3() : EnvWrapper(Env::Default()) {} virtual Status GetChildren(const std::string& dir, std::vector<std::string>* r) { r->push_back("456.sst"); return Status::OK(); } virtual Status GetFileSize(const std::string& f, uint64_t* s) { *s = 789; return Status::TimeOut("timeout"); } void SetDBImpl(DBImpl* impl) { impl_ = impl; } public: DBImpl* impl_; }; class DBImplTest { public: void init(DBImpl* impl) { Version* v = new Version(impl->versions_); FileMetaData* f = new FileMetaData; f->refs++; f->number = (1UL << 63 | 123UL << 32 | 456); f->file_size = 789; f->smallest = InternalKey("", 0, kTypeValue); f->largest = InternalKey("", 0, kTypeValue); (v->files_[0]).push_back(f); impl->versions_->AppendVersion(v); } DBImplTest() {} ~DBImplTest() {} }; TEST(DBImplTest, VeriyDbInGetPropertyWhenShuttingDownCase1) { Options opt; EnvForVeriyDbInGetPropertyCase1* env = new EnvForVeriyDbInGetPropertyCase1; opt.env = env; DBImpl* impl = new DBImpl(opt, "test_table/tablet000123/1"); env->SetDBImpl(impl); init(impl); std::string db_property_key = "leveldb.verify-db-integrity"; std::string db_property_val; impl->shutting_down_.Release_Store(impl); ASSERT_EQ(impl->GetProperty(db_property_key, &db_property_val), false); delete opt.env; delete impl; } TEST(DBImplTest, VeriyDbInGetPropertyWhenShuttingDownCase2) { Options opt; EnvForVeriyDbInGetPropertyCase2* env = new EnvForVeriyDbInGetPropertyCase2; opt.env = env; DBImpl* impl = new DBImpl(opt, "test_table/tablet000123/1"); env->SetDBImpl(impl); init(impl); std::string db_property_key = "leveldb.verify-db-integrity"; std::string db_property_val; ASSERT_EQ(impl->GetProperty(db_property_key, &db_property_val), false); delete opt.env; delete impl; } TEST(DBImplTest, VeriyDbInGetPropertyWhenShuttingDownCase3) { Options opt; EnvForVeriyDbInGetPropertyCase3* env = new EnvForVeriyDbInGetPropertyCase3; opt.env = env; DBImpl* impl = new DBImpl(opt, "test_table/tablet000123/1"); env->SetDBImpl(impl); init(impl); std::string db_property_key = "leveldb.verify-db-integrity"; std::string db_property_val; ASSERT_EQ(impl->GetProperty(db_property_key, &db_property_val), false); delete opt.env; delete impl; } } // namespace leveldb int main(int argc, char** argv) { return leveldb::test::RunAllTests(); }
1,523
625
package com.jtransc.annotation; import java.lang.annotation.*; @Retention(RetentionPolicy.CLASS) @Target({ElementType.METHOD, ElementType.CONSTRUCTOR}) @Repeatable(value = JTranscCallSiteBodyList.class) public @interface JTranscCallSiteBody { String target(); String[] value(); }
90
643
package com.hellokoding.account.service; import com.hellokoding.account.model.User; import com.hellokoding.account.model.VerificationToken; import com.hellokoding.account.repository.UserRepository; import com.hellokoding.account.repository.VerificationTokenRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.List; @Service public class VerificationTokenService { private UserRepository userRepository; private VerificationTokenRepository verificationTokenRepository; private SendingMailService sendingMailService; @Autowired public VerificationTokenService(UserRepository userRepository, VerificationTokenRepository verificationTokenRepository, SendingMailService sendingMailService){ this.userRepository = userRepository; this.verificationTokenRepository = verificationTokenRepository; this.sendingMailService = sendingMailService; } public void createVerification(String email){ List<User> users = userRepository.findByEmail(email); User user; if (users.isEmpty()) { user = new User(); user.setEmail(email); userRepository.save(user); } else { user = users.get(0); } List<VerificationToken> verificationTokens = verificationTokenRepository.findByUserEmail(email); VerificationToken verificationToken; if (verificationTokens.isEmpty()) { verificationToken = new VerificationToken(); verificationToken.setUser(user); verificationTokenRepository.save(verificationToken); } else { verificationToken = verificationTokens.get(0); } sendingMailService.sendVerificationMail(email, verificationToken.getToken()); } public ResponseEntity<String> verifyEmail(String token){ List<VerificationToken> verificationTokens = verificationTokenRepository.findByToken(token); if (verificationTokens.isEmpty()) { return ResponseEntity.badRequest().body("Invalid token."); } VerificationToken verificationToken = verificationTokens.get(0); if (verificationToken.getExpiredDateTime().isBefore(LocalDateTime.now())) { return ResponseEntity.unprocessableEntity().body("Expired token."); } verificationToken.setConfirmedDateTime(LocalDateTime.now()); verificationToken.setStatus(VerificationToken.STATUS_VERIFIED); verificationToken.getUser().setIsActive(true); verificationTokenRepository.save(verificationToken); return ResponseEntity.ok("You have successfully verified your email address."); } }
957
1,345
<filename>napari/utils/context/_tests/test_expressions.py<gh_stars>1000+ import ast import pytest from napari.utils.context._expressions import ( _OPS, Constant, Expr, Name, _iter_names, parse_expression, ) def test_names(): assert Name("n").eval({'n': 5}) == 5 # currently, evaludating with a missing name is an error. with pytest.raises(NameError): Name("n").eval() assert repr(Name('n')) == "Name(id='n', ctx=Load())" def test_constants(): assert Constant(1).eval() == 1 assert Constant(3.14).eval() == 3.14 assert Constant('asdf').eval() == 'asdf' assert str(Constant('asdf')) == "'asdf'" assert str(Constant(r'asdf')) == "'asdf'" assert Constant(b'byte').eval() == b'byte' assert str(Constant(b'byte')) == "b'byte'" assert Constant(True).eval() is True assert Constant(False).eval() is False assert Constant(None).eval() is None assert repr(Constant(1)) == 'Constant(value=1)' # only {None, str, bytes, bool, int, float} allowed with pytest.raises(TypeError): Constant((1, 2)) # type: ignore def test_bool_ops(): n1 = Name[bool]("n1") true = Constant(True) false = Constant(False) assert (n1 & true).eval({'n1': True}) is True assert (n1 & false).eval({'n1': True}) is False assert (n1 & false).eval({'n1': False}) is False assert (n1 | true).eval({'n1': True}) is True assert (n1 | false).eval({'n1': True}) is True assert (n1 | false).eval({'n1': False}) is False # real constants assert (n1 & True).eval({'n1': True}) is True assert (n1 & False).eval({'n1': True}) is False assert (n1 & False).eval({'n1': False}) is False assert (n1 | True).eval({'n1': True}) is True assert (n1 | False).eval({'n1': True}) is True assert (n1 | False).eval({'n1': False}) is False # when working with Expr objects: # the binary "op" & refers to the boolean op "and" assert str(Constant(1) & 1) == '1 and 1' # note: using "and" does NOT work to combine expressions # (in this case, it would just return the second value "1") assert not isinstance(Constant(1) and 1, Expr) def test_bin_ops(): one = Constant(1) assert (one + 1).eval() == 2 assert (one - 1).eval() == 0 assert (one * 4).eval() == 4 assert (one / 4).eval() == 0.25 assert (one // 4).eval() == 0 assert (one % 2).eval() == 1 assert (one % 1).eval() == 0 assert (Constant(2) ** 2).eval() == 4 assert (one ^ 2).eval() == 3 def test_unary_ops(): assert Constant(1).eval() == 1 assert (+Constant(1)).eval() == 1 assert (-Constant(1)).eval() == -1 assert Constant(True).eval() is True assert (~Constant(True)).eval() is False def test_comparison(): n = Name[int]("n") n2 = Name[int]("n2") one = Constant(1) assert (n == n2).eval({'n': 2, 'n2': 2}) assert not (n == n2).eval({'n': 2, 'n2': 1}) assert (n != n2).eval({'n': 2, 'n2': 1}) assert not (n != n2).eval({'n': 2, 'n2': 2}) # real constant assert (n != 1).eval({'n': 2}) assert not (n != 2).eval({'n': 2}) assert (n < one).eval({'n': -1}) assert not (n < one).eval({'n': 2}) assert (n <= one).eval({'n': 0}) assert (n <= one).eval({'n': 1}) assert not (n <= one).eval({'n': 2}) # with real constant assert (n < 1).eval({'n': -1}) assert not (n < 1).eval({'n': 2}) assert (n <= 1).eval({'n': 0}) assert (n <= 1).eval({'n': 1}) assert not (n <= 1).eval({'n': 2}) assert (n > one).eval({'n': 2}) assert not (n > one).eval({'n': 1}) assert (n >= one).eval({'n': 2}) assert (n >= one).eval({'n': 1}) assert not (n >= one).eval({'n': 0}) # real constant assert (n > 1).eval({'n': 2}) assert not (n > 1).eval({'n': 1}) assert (n >= 1).eval({'n': 2}) assert (n >= 1).eval({'n': 1}) assert not (n >= 1).eval({'n': 0}) assert Expr.in_(Constant('a'), Constant('abcd')).eval() is True assert Constant('a').in_(Constant('abcd')).eval() is True assert Expr.not_in(Constant('a'), Constant('abcd')).eval() is False assert Constant('a').not_in(Constant('abcd')).eval() is False def test_iter_names(): expr = 'a if b in c else d > e' a = parse_expression(expr) b = Expr.parse(expr) # alias assert sorted(_iter_names(a)) == ['a', 'b', 'c', 'd', 'e'] assert sorted(_iter_names(b)) == ['a', 'b', 'c', 'd', 'e'] with pytest.raises(RuntimeError): # don't directly instantiate Expr() GOOD_EXPRESSIONS = [ 'a and b', 'a == 1', 'a if b == 7 else False', # valid constants: '1', '3.14', 'True', 'False', 'None', 'hieee', "b'bytes'", ] for k, v in _OPS.items(): if issubclass(k, ast.unaryop): GOOD_EXPRESSIONS.append(f"{v} 1" if v == 'not' else f"{v}1") else: GOOD_EXPRESSIONS.append(f"1 {v} 2") # these are not supported BAD_EXPRESSIONS = [ 'a orr b', # typo 'a b', # invalid syntax 'a = b', # Assign 'my.attribute', # Attribute '__import__(something)', # Call 'print("hi")', '(1,)', # tuples not yet supported '{"key": "val"}', # dicts not yet supported '{"hi"}', # set constant '[]', # lists constant 'mylist[0]', # Index 'mylist[0:1]', # Slice 'f"a"', # JoinedStr 'a := 1', # NamedExpr r'f"{a}"', # FormattedValue '[v for v in val]', # ListComp '{v for v in val}', # SetComp r'{k:v for k, v in val}', # DictComp '(v for v in val)', # GeneratorExp ] @pytest.mark.parametrize('expr', GOOD_EXPRESSIONS) def test_serdes(expr): assert str(parse_expression(expr)) == expr @pytest.mark.parametrize('expr', BAD_EXPRESSIONS) def test_bad_serdes(expr): with pytest.raises(SyntaxError): parse_expression(expr)
2,493
389
<filename>fast_soft_sort/numpy_ops.py # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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. """Numpy operators for soft sorting and ranking. Fast Differentiable Sorting and Ranking <NAME>, <NAME>, <NAME>, <NAME> https://arxiv.org/abs/2002.08871 This implementation follows the notation of the paper whenever possible. """ from .third_party import isotonic import numpy as np from scipy import special def isotonic_l2(input_s, input_w=None): """Solves an isotonic regression problem using PAV. Formally, it solves argmin_{v_1 >= ... >= v_n} 0.5 ||v - (s-w)||^2. Args: input_s: input to isotonic regression, a 1d-array. input_w: input to isotonic regression, a 1d-array. Returns: solution to the optimization problem. """ if input_w is None: input_w = np.arange(len(input_s))[::-1] + 1 input_w = input_w.astype(input_s.dtype) solution = np.zeros_like(input_s) isotonic.isotonic_l2(input_s - input_w, solution) return solution def isotonic_kl(input_s, input_w=None): """Solves isotonic optimization with KL divergence using PAV. Formally, it solves argmin_{v_1 >= ... >= v_n} <e^{s-v}, 1> + <e^w, v>. Args: input_s: input to isotonic optimization, a 1d-array. input_w: input to isotonic optimization, a 1d-array. Returns: solution to the optimization problem (same dtype as input_s). """ if input_w is None: input_w = np.arange(len(input_s))[::-1] + 1 input_w = input_w.astype(input_s.dtype) solution = np.zeros(len(input_s)).astype(input_s.dtype) isotonic.isotonic_kl(input_s, input_w.astype(input_s.dtype), solution) return solution def _partition(solution, eps=1e-9): """Returns partition corresponding to solution.""" # pylint: disable=g-explicit-length-test if len(solution) == 0: return [] sizes = [1] for i in range(1, len(solution)): if abs(solution[i] - solution[i - 1]) > eps: sizes.append(0) sizes[-1] += 1 return sizes def _check_regularization(regularization): if regularization not in ("l2", "kl"): raise ValueError("'regularization' should be either 'l2' or 'kl' " "but got %s." % str(regularization)) class _Differentiable(object): """Base class for differentiable operators.""" def jacobian(self): """Computes Jacobian.""" identity = np.eye(self.size) return np.array([self.jvp(identity[i]) for i in range(len(identity))]).T @property def size(self): raise NotImplementedError def compute(self): """Computes the desired quantity.""" raise NotImplementedError def jvp(self, vector): """Computes Jacobian vector product.""" raise NotImplementedError def vjp(self, vector): """Computes vector Jacobian product.""" raise NotImplementedError class Isotonic(_Differentiable): """Isotonic optimization.""" def __init__(self, input_s, input_w, regularization="l2"): self.input_s = input_s self.input_w = input_w _check_regularization(regularization) self.regularization = regularization self.solution_ = None @property def size(self): return len(self.input_s) def compute(self): if self.regularization == "l2": self.solution_ = isotonic_l2(self.input_s, self.input_w) else: self.solution_ = isotonic_kl(self.input_s, self.input_w) return self.solution_ def _check_computed(self): if self.solution_ is None: raise RuntimeError("Need to run compute() first.") def jvp(self, vector): self._check_computed() start = 0 return_value = np.zeros_like(self.solution_) for size in _partition(self.solution_): end = start + size if self.regularization == "l2": val = np.mean(vector[start:end]) else: val = np.dot(special.softmax(self.input_s[start:end]), vector[start:end]) return_value[start:end] = val start = end return return_value def vjp(self, vector): start = 0 return_value = np.zeros_like(self.solution_) for size in _partition(self.solution_): end = start + size if self.regularization == "l2": val = 1. / size else: val = special.softmax(self.input_s[start:end]) return_value[start:end] = val * np.sum(vector[start:end]) start = end return return_value def _inv_permutation(permutation): """Returns inverse permutation of 'permutation'.""" inv_permutation = np.zeros(len(permutation), dtype=np.int) inv_permutation[permutation] = np.arange(len(permutation)) return inv_permutation class Projection(_Differentiable): """Computes projection onto the permutahedron P(w).""" def __init__(self, input_theta, input_w=None, regularization="l2"): if input_w is None: input_w = np.arange(len(input_theta))[::-1] + 1 self.input_theta = np.asarray(input_theta) self.input_w = np.asarray(input_w) _check_regularization(regularization) self.regularization = regularization self.isotonic = None def _check_computed(self): if self.isotonic_ is None: raise ValueError("Need to run compute() first.") @property def size(self): return len(self.input_theta) def compute(self): self.permutation = np.argsort(self.input_theta)[::-1] input_s = self.input_theta[self.permutation] self.isotonic_ = Isotonic(input_s, self.input_w, self.regularization) dual_sol = self.isotonic_.compute() primal_sol = input_s - dual_sol self.inv_permutation = _inv_permutation(self.permutation) return primal_sol[self.inv_permutation] def jvp(self, vector): self._check_computed() ret = vector.copy() ret -= self.isotonic_.jvp(vector[self.permutation])[self.inv_permutation] return ret def vjp(self, vector): self._check_computed() ret = vector.copy() ret -= self.isotonic_.vjp(vector[self.permutation])[self.inv_permutation] return ret def _check_direction(direction): if direction not in ("ASCENDING", "DESCENDING"): raise ValueError("direction should be either 'ASCENDING' or 'DESCENDING'") class SoftRank(_Differentiable): """Soft ranking.""" def __init__(self, values, direction="ASCENDING", regularization_strength=1.0, regularization="l2"): self.values = np.asarray(values) self.input_w = np.arange(len(values))[::-1] + 1 _check_direction(direction) sign = 1 if direction == "ASCENDING" else -1 self.scale = sign / regularization_strength _check_regularization(regularization) self.regularization = regularization self.projection_ = None @property def size(self): return len(self.values) def _check_computed(self): if self.projection_ is None: raise ValueError("Need to run compute() first.") def compute(self): if self.regularization == "kl": self.projection_ = Projection( self.values * self.scale, np.log(self.input_w), regularization=self.regularization) self.factor = np.exp(self.projection_.compute()) return self.factor else: self.projection_ = Projection( self.values * self.scale, self.input_w, regularization=self.regularization) self.factor = 1.0 return self.projection_.compute() def jvp(self, vector): self._check_computed() return self.factor * self.projection_.jvp(vector) * self.scale def vjp(self, vector): self._check_computed() return self.projection_.vjp(self.factor * vector) * self.scale class SoftSort(_Differentiable): """Soft sorting.""" def __init__(self, values, direction="ASCENDING", regularization_strength=1.0, regularization="l2"): self.values = np.asarray(values) _check_direction(direction) self.sign = 1 if direction == "DESCENDING" else -1 self.regularization_strength = regularization_strength _check_regularization(regularization) self.regularization = regularization self.isotonic_ = None @property def size(self): return len(self.values) def _check_computed(self): if self.isotonic_ is None: raise ValueError("Need to run compute() first.") def compute(self): size = len(self.values) input_w = np.arange(1, size + 1)[::-1] / self.regularization_strength values = self.sign * self.values self.permutation_ = np.argsort(values)[::-1] s = values[self.permutation_] self.isotonic_ = Isotonic(input_w, s, regularization=self.regularization) res = self.isotonic_.compute() # We set s as the first argument as we want the derivatives w.r.t. s. self.isotonic_.s = s return self.sign * (input_w - res) def jvp(self, vector): self._check_computed() return self.isotonic_.jvp(vector[self.permutation_]) def vjp(self, vector): self._check_computed() inv_permutation = _inv_permutation(self.permutation_) return self.isotonic_.vjp(vector)[inv_permutation] class Sort(_Differentiable): """Hard sorting.""" def __init__(self, values, direction="ASCENDING"): _check_direction(direction) self.values = np.asarray(values) self.sign = 1 if direction == "DESCENDING" else -1 self.permutation_ = None @property def size(self): return len(self.values) def _check_computed(self): if self.permutation_ is None: raise ValueError("Need to run compute() first.") def compute(self): self.permutation_ = np.argsort(self.sign * self.values)[::-1] return self.values[self.permutation_] def jvp(self, vector): self._check_computed() return vector[self.permutation_] def vjp(self, vector): self._check_computed() inv_permutation = _inv_permutation(self.permutation_) return vector[inv_permutation] # Small utility functions for the case when we just want the forward # computation. def soft_rank(values, direction="ASCENDING", regularization_strength=1.0, regularization="l2"): r"""Soft rank the given values. The regularization strength determines how close are the returned values to the actual ranks. Args: values: A 1d-array holding the numbers to be ranked. direction: Either 'ASCENDING' or 'DESCENDING'. regularization_strength: The regularization strength to be used. The smaller this number, the closer the values to the true ranks. regularization: Which regularization method to use. It must be set to one of ("l2", "kl", "log_kl"). Returns: A 1d-array, soft-ranked. """ return SoftRank(values, regularization_strength=regularization_strength, direction=direction, regularization=regularization).compute() def soft_sort(values, direction="ASCENDING", regularization_strength=1.0, regularization="l2"): r"""Soft sort the given values. Args: values: A 1d-array holding the numbers to be sorted. direction: Either 'ASCENDING' or 'DESCENDING'. regularization_strength: The regularization strength to be used. The smaller this number, the closer the values to the true sorted values. regularization: Which regularization method to use. It must be set to one of ("l2", "log_kl"). Returns: A 1d-array, soft-sorted. """ return SoftSort(values, regularization_strength=regularization_strength, direction=direction, regularization=regularization).compute() def sort(values, direction="ASCENDING"): r"""Sort the given values. Args: values: A 1d-array holding the numbers to be sorted. direction: Either 'ASCENDING' or 'DESCENDING'. Returns: A 1d-array, sorted. """ return Sort(values, direction=direction).compute() def rank(values, direction="ASCENDING"): r"""Rank the given values. Args: values: A 1d-array holding the numbers to be ranked. direction: Either 'ASCENDING' or 'DESCENDING'. Returns: A 1d-array, ranked. """ permutation = np.argsort(values) if direction == "DESCENDING": permutation = permutation[::-1] return _inv_permutation(permutation) + 1 # We use 1-based indexing.
4,580
1,742
<reponame>UCD4IDS/sage<gh_stars>1000+ r""" Constructions of generator matrices using the GUAVA package for GAP This module only contains Guava wrappers (GUAVA is an optional GAP package). AUTHORS: - <NAME> (2005-11-22, 2006-12-03): initial version - <NAME> (2006-12-10): factor GUAVA code to guava.py - <NAME> (2007-05): removed Golay codes, toric and trivial codes and placed them in code_constructions; renamed RandomLinearCode to RandomLinearCodeGuava - <NAME>er (2008-03): removed QR, XQR, cyclic and ReedSolomon codes - <NAME>er (2009-05): added "optional package" comments, fixed some docstrings to be sphinx compatible - <NAME> (2019-11): port to libgap """ #***************************************************************************** # Copyright (C) 2007 <NAME> <<EMAIL>> # 2006 <NAME> <<EMAIL>> # 2019 <NAME> <<EMAIL>> # # Distributed under the terms of the GNU General Public License (GPL) # # http://www.gnu.org/licenses/ #***************************************************************************** from sage.libs.gap.libgap import libgap from sage.misc.randstate import current_randstate from sage.matrix.matrix_space import MatrixSpace from sage.rings.finite_rings.finite_field_constructor import FiniteField as GF from .linear_code import LinearCode from sage.features.gap import GapPackage def QuasiQuadraticResidueCode(p): r""" A (binary) quasi-quadratic residue code (or QQR code). Follows the definition of Proposition 2.2 in [BM2003]_. The code has a generator matrix in the block form `G=(Q,N)`. Here `Q` is a `p \times p` circulant matrix whose top row is `(0,x_1,...,x_{p-1})`, where `x_i=1` if and only if `i` is a quadratic residue `\mod p`, and `N` is a `p \times p` circulant matrix whose top row is `(0,y_1,...,y_{p-1})`, where `x_i+y_i=1` for all `i`. INPUT: - ``p`` -- a prime `>2`. OUTPUT: Returns a QQR code of length `2p`. EXAMPLES:: sage: C = codes.QuasiQuadraticResidueCode(11); C # optional - gap_packages (Guava package) [22, 11] linear code over GF(2) These are self-orthogonal in general and self-dual when $p \\equiv 3 \\pmod 4$. AUTHOR: <NAME> (11-2005) """ GapPackage("guava", spkg="gap_packages").require() libgap.load_package("guava") C=libgap.QQRCode(p) G=C.GeneratorMat() MS = MatrixSpace(GF(2), len(G), len(G[0])) return LinearCode(MS(G)) def RandomLinearCodeGuava(n, k, F): r""" The method used is to first construct a `k \times n` matrix of the block form `(I,A)`, where `I` is a `k \times k` identity matrix and `A` is a `k \times (n-k)` matrix constructed using random elements of `F`. Then the columns are permuted using a randomly selected element of the symmetric group `S_n`. INPUT: - ``n,k`` -- integers with `n>k>1`. OUTPUT: Returns a "random" linear code with length `n`, dimension `k` over field `F`. EXAMPLES:: sage: C = codes.RandomLinearCodeGuava(30,15,GF(2)); C # optional - gap_packages (Guava package) [30, 15] linear code over GF(2) sage: C = codes.RandomLinearCodeGuava(10,5,GF(4,'a')); C # optional - gap_packages (Guava package) [10, 5] linear code over GF(4) AUTHOR: <NAME> (11-2005) """ current_randstate().set_seed_gap() GapPackage("guava", spkg="gap_packages").require() libgap.load_package("guava") C=libgap.RandomLinearCode(n,k,F) G=C.GeneratorMat() MS = MatrixSpace(F, len(G), len(G[0])) return LinearCode(MS(G))
1,398
1,545
<filename>bookkeeper-server/src/main/java/org/apache/bookkeeper/bookie/storage/ldb/LongWrapper.java /** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.bookkeeper.bookie.storage.ldb; import io.netty.util.Recycler; import io.netty.util.Recycler.Handle; /** * Wrapper for a long serialized into a byte array. */ class LongWrapper { final byte[] array = new byte[8]; public void set(long value) { ArrayUtil.setLong(array, 0, value); } public long getValue() { return ArrayUtil.getLong(array, 0); } public static LongWrapper get() { return RECYCLER.get(); } public static LongWrapper get(long value) { LongWrapper lp = RECYCLER.get(); ArrayUtil.setLong(lp.array, 0, value); return lp; } public void recycle() { handle.recycle(this); } private static final Recycler<LongWrapper> RECYCLER = new Recycler<LongWrapper>() { @Override protected LongWrapper newObject(Handle<LongWrapper> handle) { return new LongWrapper(handle); } }; private final Handle<LongWrapper> handle; private LongWrapper(Handle<LongWrapper> handle) { this.handle = handle; } }
682
11,356
// Copyright <NAME> 2002-2004. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_CONFIG_FILE_VP_2003_01_02 #define BOOST_CONFIG_FILE_VP_2003_01_02 #include <iosfwd> #include <string> #include <set> #include <boost/noncopyable.hpp> #include <boost/program_options/config.hpp> #include <boost/program_options/option.hpp> #include <boost/program_options/eof_iterator.hpp> #include <boost/detail/workaround.hpp> #include <boost/program_options/detail/convert.hpp> #if BOOST_WORKAROUND(__DECCXX_VER, BOOST_TESTED_AT(60590042)) #include <istream> // std::getline #endif #include <boost/static_assert.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/shared_ptr.hpp> #ifdef BOOST_MSVC # pragma warning(push) # pragma warning(disable: 4251) // class XYZ needs to have dll-interface to be used by clients of class XYZ #endif namespace boost { namespace program_options { namespace detail { /** Standalone parser for config files in ini-line format. The parser is a model of single-pass lvalue iterator, and default constructor creates past-the-end-iterator. The typical usage is: config_file_iterator i(is, ... set of options ...), e; for(; i !=e; ++i) { *i; } Syntax conventions: - config file can not contain positional options - '#' is comment character: it is ignored together with the rest of the line. - variable assignments are in the form name '=' value. spaces around '=' are trimmed. - Section names are given in brackets. The actual option name is constructed by combining current section name and specified option name, with dot between. If section_name already contains dot at the end, new dot is not inserted. For example: @verbatim [gui.accessibility] visual_bell=yes @endverbatim will result in option "gui.accessibility.visual_bell" with value "yes" been returned. TODO: maybe, we should just accept a pointer to options_description class. */ class BOOST_PROGRAM_OPTIONS_DECL common_config_file_iterator : public eof_iterator<common_config_file_iterator, option> { public: common_config_file_iterator() { found_eof(); } common_config_file_iterator( const std::set<std::string>& allowed_options, bool allow_unregistered = false); virtual ~common_config_file_iterator() {} public: // Method required by eof_iterator void get(); #if BOOST_WORKAROUND(_MSC_VER, <= 1900) void decrement() {} void advance(difference_type) {} #endif protected: // Stubs for derived classes // Obtains next line from the config file // Note: really, this design is a bit ugly // The most clean thing would be to pass 'line_iterator' to // constructor of this class, but to avoid templating this class // we'd need polymorphic iterator, which does not exist yet. virtual bool getline(std::string&) { return false; } private: /** Adds another allowed option. If the 'name' ends with '*', then all options with the same prefix are allowed. For example, if 'name' is 'foo*', then 'foo1' and 'foo_bar' are allowed. */ void add_option(const char* name); // Returns true if 's' is a registered option name. bool allowed_option(const std::string& s) const; // That's probably too much data for iterator, since // it will be copied, but let's not bother for now. std::set<std::string> allowed_options; // Invariant: no element is prefix of other element. std::set<std::string> allowed_prefixes; std::string m_prefix; bool m_allow_unregistered; }; template<class charT> class basic_config_file_iterator : public common_config_file_iterator { public: basic_config_file_iterator() { found_eof(); } /** Creates a config file parser for the specified stream. */ basic_config_file_iterator(std::basic_istream<charT>& is, const std::set<std::string>& allowed_options, bool allow_unregistered = false); private: // base overrides bool getline(std::string&); private: // internal data shared_ptr<std::basic_istream<charT> > is; }; typedef basic_config_file_iterator<char> config_file_iterator; typedef basic_config_file_iterator<wchar_t> wconfig_file_iterator; struct null_deleter { void operator()(void const *) const {} }; template<class charT> basic_config_file_iterator<charT>:: basic_config_file_iterator(std::basic_istream<charT>& is, const std::set<std::string>& allowed_options, bool allow_unregistered) : common_config_file_iterator(allowed_options, allow_unregistered) { this->is.reset(&is, null_deleter()); get(); } // Specializing this function for wchar_t causes problems on // borland and vc7, as well as on metrowerks. On the first two // I don't know a workaround, so make use of 'to_internal' to // avoid specialization. template<class charT> bool basic_config_file_iterator<charT>::getline(std::string& s) { std::basic_string<charT> in; if (std::getline(*is, in)) { s = to_internal(in); return true; } else { return false; } } // Specialization is needed to workaround getline bug on Comeau. #if BOOST_WORKAROUND(__COMO_VERSION__, BOOST_TESTED_AT(4303)) || \ (defined(__sgi) && BOOST_WORKAROUND(_COMPILER_VERSION, BOOST_TESTED_AT(741))) template<> bool basic_config_file_iterator<wchar_t>::getline(std::string& s); #endif }}} #ifdef BOOST_MSVC # pragma warning(pop) #endif #endif
2,517
380
# oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. # Copyright (c) 2016, Gluu # # Author: <NAME> # import java import sys from javax.ws.rs.core import Response from javax.ws.rs import WebApplicationException from org.jboss.resteasy.client.exception import ResteasyClientException from org.gluu.model.custom.script.type.auth import PersonAuthenticationType from org.gluu.oxauth.client.fido.u2f import FidoU2fClientFactory from org.gluu.oxauth.model.config import Constants from org.gluu.oxauth.security import Identity from org.gluu.oxauth.service import AuthenticationService, SessionIdService from org.gluu.oxauth.service.common import UserService from org.gluu.oxauth.service.fido.u2f import DeviceRegistrationService from org.gluu.oxauth.util import ServerUtil from org.gluu.service.cdi.util import CdiUtil from org.gluu.util import StringHelper class PersonAuthentication(PersonAuthenticationType): def __init__(self, currentTimeMillis): self.currentTimeMillis = currentTimeMillis def init(self, customScript, configurationAttributes): print "U2F. Initialization" print "U2F. Initialization. Downloading U2F metadata" u2f_server_uri = configurationAttributes.get("u2f_server_uri").getValue2() u2f_server_metadata_uri = u2f_server_uri + "/.well-known/fido-u2f-configuration" metaDataConfigurationService = FidoU2fClientFactory.instance().createMetaDataConfigurationService(u2f_server_metadata_uri) max_attempts = 20 for attempt in range(1, max_attempts + 1): try: self.metaDataConfiguration = metaDataConfigurationService.getMetadataConfiguration() break except WebApplicationException, ex: # Detect if last try or we still get Service Unavailable HTTP error if (attempt == max_attempts) or (ex.getResponse().getStatus() != Response.Status.SERVICE_UNAVAILABLE.getStatusCode()): raise ex java.lang.Thread.sleep(3000) print "Attempting to load metadata: %d" % attempt print "U2F. Initialized successfully" return True def destroy(self, configurationAttributes): print "U2F. Destroy" print "U2F. Destroyed successfully" return True def getApiVersion(self): return 11 def getAuthenticationMethodClaims(self, requestParameters): return None def isValidAuthenticationMethod(self, usageType, configurationAttributes): return True def getAlternativeAuthenticationMethod(self, usageType, configurationAttributes): return None def authenticate(self, configurationAttributes, requestParameters, step): authenticationService = CdiUtil.bean(AuthenticationService) identity = CdiUtil.bean(Identity) credentials = identity.getCredentials() user_name = credentials.getUsername() if (step == 1): print "U2F. Authenticate for step 1" user_password = <PASSWORD>() logged_in = False if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)): userService = CdiUtil.bean(UserService) logged_in = authenticationService.authenticate(user_name, user_password) if (not logged_in): return False return True elif (step == 2): print "U2F. Authenticate for step 2" token_response = ServerUtil.getFirstValue(requestParameters, "tokenResponse") if token_response == None: print "U2F. Authenticate for step 2. tokenResponse is empty" return False auth_method = ServerUtil.getFirstValue(requestParameters, "authMethod") if auth_method == None: print "U2F. Authenticate for step 2. authMethod is empty" return False authenticationService = CdiUtil.bean(AuthenticationService) user = authenticationService.getAuthenticatedUser() if (user == None): print "U2F. Prepare for step 2. Failed to determine user name" return False if (auth_method == 'authenticate'): print "U2F. Prepare for step 2. Call FIDO U2F in order to finish authentication workflow" authenticationRequestService = FidoU2fClientFactory.instance().createAuthenticationRequestService(self.metaDataConfiguration) authenticationStatus = authenticationRequestService.finishAuthentication(user.getUserId(), token_response) if (authenticationStatus.getStatus() != Constants.RESULT_SUCCESS): print "U2F. Authenticate for step 2. Get invalid authentication status from FIDO U2F server" return False return True elif (auth_method == 'enroll'): print "U2F. Prepare for step 2. Call FIDO U2F in order to finish registration workflow" registrationRequestService = FidoU2fClientFactory.instance().createRegistrationRequestService(self.metaDataConfiguration) registrationStatus = registrationRequestService.finishRegistration(user.getUserId(), token_response) if (registrationStatus.getStatus() != Constants.RESULT_SUCCESS): print "U2F. Authenticate for step 2. Get invalid registration status from FIDO U2F server" return False return True else: print "U2F. Prepare for step 2. Authenticatiod method is invalid" return False return False else: return False def prepareForStep(self, configurationAttributes, requestParameters, step): identity = CdiUtil.bean(Identity) if (step == 1): return True elif (step == 2): print "U2F. Prepare for step 2" session = CdiUtil.bean(SessionIdService).getSessionId() if session == None: print "U2F. Prepare for step 2. Failed to determine session_id" return False authenticationService = CdiUtil.bean(AuthenticationService) user = authenticationService.getAuthenticatedUser() if (user == None): print "U2F. Prepare for step 2. Failed to determine user name" return False u2f_application_id = configurationAttributes.get("u2f_application_id").getValue2() # Check if user have registered devices deviceRegistrationService = CdiUtil.bean(DeviceRegistrationService) userInum = user.getAttribute("inum") registrationRequest = None authenticationRequest = None deviceRegistrations = deviceRegistrationService.findUserDeviceRegistrations(userInum, u2f_application_id) if (deviceRegistrations.size() > 0): print "U2F. Prepare for step 2. Call FIDO U2F in order to start authentication workflow" try: authenticationRequestService = FidoU2fClientFactory.instance().createAuthenticationRequestService(self.metaDataConfiguration) authenticationRequest = authenticationRequestService.startAuthentication(user.getUserId(), None, u2f_application_id, session.getId()) except ClientResponseFailure, ex: if (ex.getResponse().getResponseStatus() != Response.Status.NOT_FOUND): print "U2F. Prepare for step 2. Failed to start authentication workflow. Exception:", sys.exc_info()[1] return False else: print "U2F. Prepare for step 2. Call FIDO U2F in order to start registration workflow" registrationRequestService = FidoU2fClientFactory.instance().createRegistrationRequestService(self.metaDataConfiguration) registrationRequest = registrationRequestService.startRegistration(user.getUserId(), u2f_application_id, session.getId()) identity.setWorkingParameter("fido_u2f_authentication_request", ServerUtil.asJson(authenticationRequest)) identity.setWorkingParameter("fido_u2f_registration_request", ServerUtil.asJson(registrationRequest)) return True elif (step == 3): print "U2F. Prepare for step 3" return True else: return False def getExtraParametersForStep(self, configurationAttributes, step): return None def getCountAuthenticationSteps(self, configurationAttributes): return 2 def getPageForStep(self, configurationAttributes, step): if (step == 2): return "/auth/u2f/login.xhtml" return "" def getNextStep(self, configurationAttributes, requestParameters, step): return -1 def getLogoutExternalUrl(self, configurationAttributes, requestParameters): print "Get external logout URL call" return None def logout(self, configurationAttributes, requestParameters): return True
3,948
1,401
<reponame>FunnyYish/jvmgo-book package com.github.jvmgo.instructions.comparisons;
33
703
<reponame>Tekh-ops/ezEngine #include <ProcGenPlugin/ProcGenPluginPCH.h> #include <ProcGenPlugin/Declarations.h> #include <ProcGenPlugin/VM/ExpressionByteCode.h> // clang-format off EZ_BEGIN_STATIC_REFLECTED_ENUM(ezProcGenBlendMode, 1) EZ_ENUM_CONSTANTS(ezProcGenBlendMode::Add, ezProcGenBlendMode::Subtract, ezProcGenBlendMode::Multiply, ezProcGenBlendMode::Divide) EZ_ENUM_CONSTANTS(ezProcGenBlendMode::Max, ezProcGenBlendMode::Min) EZ_ENUM_CONSTANTS(ezProcGenBlendMode::Set) EZ_END_STATIC_REFLECTED_ENUM; EZ_BEGIN_STATIC_REFLECTED_ENUM(ezProcVertexColorChannelMapping, 1) EZ_ENUM_CONSTANTS(ezProcVertexColorChannelMapping::R, ezProcVertexColorChannelMapping::G, ezProcVertexColorChannelMapping::B, ezProcVertexColorChannelMapping::A) EZ_ENUM_CONSTANTS(ezProcVertexColorChannelMapping::Black, ezProcVertexColorChannelMapping::White) EZ_END_STATIC_REFLECTED_ENUM; EZ_BEGIN_STATIC_REFLECTED_TYPE(ezProcVertexColorMapping, ezNoBase, 1, ezRTTIDefaultAllocator<ezProcVertexColorMapping>) { EZ_BEGIN_PROPERTIES { EZ_ENUM_MEMBER_PROPERTY("R", ezProcVertexColorChannelMapping, m_R)->AddAttributes(new ezDefaultValueAttribute(ezProcVertexColorChannelMapping::R)), EZ_ENUM_MEMBER_PROPERTY("G", ezProcVertexColorChannelMapping, m_G)->AddAttributes(new ezDefaultValueAttribute(ezProcVertexColorChannelMapping::G)), EZ_ENUM_MEMBER_PROPERTY("B", ezProcVertexColorChannelMapping, m_B)->AddAttributes(new ezDefaultValueAttribute(ezProcVertexColorChannelMapping::B)), EZ_ENUM_MEMBER_PROPERTY("A", ezProcVertexColorChannelMapping, m_A)->AddAttributes(new ezDefaultValueAttribute(ezProcVertexColorChannelMapping::A)), } EZ_END_PROPERTIES; } EZ_END_STATIC_REFLECTED_TYPE; EZ_BEGIN_STATIC_REFLECTED_ENUM(ezProcPlacementMode, 1) EZ_ENUM_CONSTANTS(ezProcPlacementMode::Raycast, ezProcPlacementMode::Fixed) EZ_END_STATIC_REFLECTED_ENUM; EZ_BEGIN_STATIC_REFLECTED_ENUM(ezProcVolumeImageMode, 1) EZ_ENUM_CONSTANTS(ezProcVolumeImageMode::ReferenceColor, ezProcVolumeImageMode::ChannelR, ezProcVolumeImageMode::ChannelG, ezProcVolumeImageMode::ChannelB, ezProcVolumeImageMode::ChannelA) EZ_END_STATIC_REFLECTED_ENUM; // clang-format on static ezTypeVersion s_ProcVertexColorMappingVersion = 1; ezResult ezProcVertexColorMapping::Serialize(ezStreamWriter& stream) const { stream.WriteVersion(s_ProcVertexColorMappingVersion); stream << m_R; stream << m_G; stream << m_B; stream << m_A; return EZ_SUCCESS; } ezResult ezProcVertexColorMapping::Deserialize(ezStreamReader& stream) { /*ezTypeVersion version =*/stream.ReadVersion(s_ProcVertexColorMappingVersion); stream >> m_R; stream >> m_G; stream >> m_B; stream >> m_A; return EZ_SUCCESS; } namespace ezProcGenInternal { GraphSharedDataBase::~GraphSharedDataBase() = default; Output::~Output() = default; ezHashedString ExpressionInputs::s_sPositionX = ezMakeHashedString("PositionX"); ezHashedString ExpressionInputs::s_sPositionY = ezMakeHashedString("PositionY"); ezHashedString ExpressionInputs::s_sPositionZ = ezMakeHashedString("PositionZ"); ezHashedString ExpressionInputs::s_sNormalX = ezMakeHashedString("NormalX"); ezHashedString ExpressionInputs::s_sNormalY = ezMakeHashedString("NormalY"); ezHashedString ExpressionInputs::s_sNormalZ = ezMakeHashedString("NormalZ"); ezHashedString ExpressionInputs::s_sColorR = ezMakeHashedString("ColorR"); ezHashedString ExpressionInputs::s_sColorG = ezMakeHashedString("ColorG"); ezHashedString ExpressionInputs::s_sColorB = ezMakeHashedString("ColorB"); ezHashedString ExpressionInputs::s_sColorA = ezMakeHashedString("ColorA"); ezHashedString ExpressionInputs::s_sPointIndex = ezMakeHashedString("PointIndex"); ezHashedString ExpressionOutputs::s_sDensity = ezMakeHashedString("Density"); ezHashedString ExpressionOutputs::s_sScale = ezMakeHashedString("Scale"); ezHashedString ExpressionOutputs::s_sColorIndex = ezMakeHashedString("ColorIndex"); ezHashedString ExpressionOutputs::s_sObjectIndex = ezMakeHashedString("ObjectIndex"); ezHashedString ExpressionOutputs::s_sR = ezMakeHashedString("R"); ezHashedString ExpressionOutputs::s_sG = ezMakeHashedString("G"); ezHashedString ExpressionOutputs::s_sB = ezMakeHashedString("B"); ezHashedString ExpressionOutputs::s_sA = ezMakeHashedString("A"); } // namespace ezProcGenInternal
1,660
1,093
/* * Copyright 2002-2019 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.integration.jpa.outbound; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import javax.sql.DataSource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.integration.jpa.test.JpaTestUtils; import org.springframework.integration.jpa.test.entity.StudentDomain; import org.springframework.integration.support.MessageBuilder; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; /** * * @author <NAME> * @author <NAME> * * @since 2.2 * */ @RunWith(SpringRunner.class) @DirtiesContext public class JpaOutboundChannelAdapterTransactionalTests { @Autowired @Qualifier("input") private MessageChannel channel; @Autowired DataSource dataSource; @Test public void saveEntityWithTransaction() { List<?> results1 = new JdbcTemplate(this.dataSource) .queryForList("Select * from Student"); assertThat(results1).isNotNull(); assertThat(results1.size()).isEqualTo(3); StudentDomain testStudent = JpaTestUtils.getTestStudent(); Message<StudentDomain> message = MessageBuilder.withPayload(testStudent).build(); this.channel.send(message); List<?> results2 = new JdbcTemplate(this.dataSource) .queryForList("Select * from Student"); assertThat(results2).isNotNull(); assertThat(results2.size()).isEqualTo(4); assertThat(testStudent.getRollNumber()).isNull(); } }
744
567
<reponame>intelkevinputnam/lpot-docs # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import os from maskrcnn_benchmark.utils.imports import import_file def setup_environment(): """Perform environment setup work. The default setup is a no-op, but this function allows the user to specify a Python source file that performs custom setup work that may be necessary to their computing environment. """ custom_module_path = os.environ.get("TORCH_DETECTRON_ENV_MODULE") if custom_module_path: setup_custom_environment(custom_module_path) else: # The default setup is a no-op pass def setup_custom_environment(custom_module_path): """Load custom environment setup from a Python source file and run the setup function. """ module = import_file("maskrcnn_benchmark.utils.env.custom_module", custom_module_path) assert hasattr(module, "setup_environment") and callable( module.setup_environment ), ( "Custom environment module defined in {} does not have the " "required callable attribute 'setup_environment'." ).format( custom_module_path ) module.setup_environment() # Force environment setup when this module is imported setup_environment()
577
14,668
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/apps/app_service/webapk/webapk_test_server.h" #include "base/bind.h" #include "base/command_line.h" #include "chrome/common/chrome_switches.h" namespace { constexpr char kServerPath[] = "/webapk"; constexpr char kToken[] = "<PASSWORD>"; std::unique_ptr<net::test_server::HttpResponse> BuildValidWebApkResponse( std::string package_name) { auto webapk_response = std::make_unique<webapk::WebApkResponse>(); webapk_response->set_package_name(std::move(package_name)); webapk_response->set_version("1"); webapk_response->set_token(kToken); std::string response_content; webapk_response->SerializeToString(&response_content); auto response = std::make_unique<net::test_server::BasicHttpResponse>(); response->set_code(net::HTTP_OK); response->set_content(response_content); return response; } std::unique_ptr<net::test_server::HttpResponse> BuildFailedResponse() { auto response = std::make_unique<net::test_server::BasicHttpResponse>(); response->set_code(net::HTTP_BAD_REQUEST); return response; } } // namespace namespace apps { WebApkTestServer::WebApkTestServer() = default; WebApkTestServer::~WebApkTestServer() = default; bool WebApkTestServer::SetUpAndStartServer( net::test_server::EmbeddedTestServer* server) { server->RegisterRequestHandler(base::BindRepeating( &WebApkTestServer::HandleWebApkRequest, base::Unretained(this))); bool result = server->Start(); if (result) { GURL server_url = server->GetURL(kServerPath); base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kWebApkServerUrl, server_url.spec()); } return result; } void WebApkTestServer::RespondWithSuccess(const std::string& package_name) { webapk_response_builder_ = base::BindRepeating(&BuildValidWebApkResponse, package_name); } void WebApkTestServer::RespondWithError() { webapk_response_builder_ = base::BindRepeating(&BuildFailedResponse); } std::unique_ptr<net::test_server::HttpResponse> WebApkTestServer::HandleWebApkRequest( const net::test_server::HttpRequest& request) { if (request.relative_url == kServerPath) { last_webapk_request_ = std::make_unique<webapk::WebApk>(); last_webapk_request_->ParseFromString(request.content); return webapk_response_builder_.Run(); } return nullptr; } } // namespace apps
856
809
/** * @file * @brief * * @author <NAME> * @date 21.08.2013 */ extern int __mulsi3(int op1, int op2); int __mulhi3(int op1, int op2) { return __mulsi3(op1, op2); }
89
369
from __future__ import (absolute_import, division, print_function, unicode_literals) from collections import defaultdict, namedtuple from logging import getLogger from transip import TransIP from transip.exceptions import TransIPHTTPError from transip.v6.objects import DnsEntry from . import ProviderException from ..record import Record from .base import BaseProvider DNSEntry = namedtuple('DNSEntry', ('name', 'expire', 'type', 'content')) class TransipException(ProviderException): pass class TransipConfigException(TransipException): pass class TransipNewZoneException(TransipException): pass class TransipProvider(BaseProvider): ''' Transip DNS provider transip: class: octodns.provider.transip.TransipProvider # Your Transip account name (required) account: yourname # Path to a private key file (required if key is not used) key_file: /path/to/file # The api key as string (required if key_file is not used) key: | \''' -----BEGIN PRIVATE KEY----- ... -----END PRIVATE KEY----- \''' # if both `key_file` and `key` are presented `key_file` is used ''' SUPPORTS_GEO = False SUPPORTS_DYNAMIC = False SUPPORTS = set(('A', 'AAAA', 'CNAME', 'MX', 'NS', 'SRV', 'SPF', 'TXT', 'SSHFP', 'CAA')) # unsupported by OctoDNS: 'TLSA' MIN_TTL = 120 TIMEOUT = 15 ROOT_RECORD = '@' def __init__(self, id, account, key=None, key_file=None, *args, **kwargs): self.log = getLogger('TransipProvider[{}]'.format(id)) self.log.debug('__init__: id=%s, account=%s, token=***', id, account) super(TransipProvider, self).__init__(id, *args, **kwargs) if key_file is not None: self._client = TransIP(login=account, private_key_file=key_file) elif key is not None: self._client = TransIP(login=account, private_key=key) else: raise TransipConfigException( 'Missing `key` or `key_file` parameter in config' ) def populate(self, zone, target=False, lenient=False): ''' Populate the zone with records in-place. ''' self.log.debug('populate: name=%s, target=%s, lenient=%s', zone.name, target, lenient) before = len(zone.records) try: domain = self._client.domains.get(zone.name.strip('.')) records = domain.dns.list() except TransIPHTTPError as e: if e.response_code == 404 and target is False: # Zone not found in account, and not a target so just # leave an empty zone. return False elif e.response_code == 404 and target is True: self.log.warning('populate: Transip can\'t create new zones') raise TransipNewZoneException( ('populate: ({}) Transip used ' + 'as target for non-existing zone: {}').format( e.response_code, zone.name)) else: self.log.error( 'populate: (%s) %s ', e.response_code, e.message ) raise TransipException( 'Unhandled error: ({}) {}'.format( e.response_code, e.message ) ) self.log.debug( 'populate: found %s records for zone %s', len(records), zone.name ) if records: values = defaultdict(lambda: defaultdict(list)) for record in records: name = zone.hostname_from_fqdn(record.name) if name == self.ROOT_RECORD: name = '' if record.type in self.SUPPORTS: values[name][record.type].append(record) for name, types in values.items(): for _type, records in types.items(): record = Record.new( zone, name, _data_for(_type, records, zone), source=self, lenient=lenient, ) zone.add_record(record, lenient=lenient) self.log.info('populate: found %s records', len(zone.records) - before) return True def _apply(self, plan): desired = plan.desired changes = plan.changes self.log.debug('apply: zone=%s, changes=%d', desired.name, len(changes)) try: domain = self._client.domains.get(plan.desired.name[:-1]) except TransIPHTTPError as e: self.log.exception('_apply: getting the domain failed') raise TransipException( 'Unhandled error: ({}) {}'.format(e.response_code, e.message) ) records = [] for record in plan.desired.records: if record._type in self.SUPPORTS: # Root records have '@' as name name = record.name if name == '': name = self.ROOT_RECORD records.extend(_entries_for(name, record)) # Transform DNSEntry namedtuples into transip.v6.objects.DnsEntry # objects, which is a bit ugly because it's quite a magical object. api_records = [DnsEntry(domain.dns, r._asdict()) for r in records] try: domain.dns.replace(api_records) except TransIPHTTPError as e: self.log.warning( '_apply: Set DNS returned one or more errors: {}'.format(e) ) raise TransipException( 'Unhandled error: ({}) {}'.format(e.response_code, e.message) ) def _data_for(type_, records, current_zone): if type_ == 'CNAME': return { 'type': type_, 'ttl': records[0].expire, 'value': _parse_to_fqdn(records[0].content, current_zone), } def format_mx(record): preference, exchange = record.content.split(' ', 1) return { 'preference': preference, 'exchange': _parse_to_fqdn(exchange, current_zone), } def format_srv(record): priority, weight, port, target = record.content.split(' ', 3) return { 'port': port, 'priority': priority, 'target': _parse_to_fqdn(target, current_zone), 'weight': weight, } def format_sshfp(record): algorithm, fp_type, fingerprint = record.content.split(' ', 2) return { 'algorithm': algorithm, 'fingerprint': fingerprint.lower(), 'fingerprint_type': fp_type, } def format_caa(record): flags, tag, value = record.content.split(' ', 2) return {'flags': flags, 'tag': tag, 'value': value} def format_txt(record): return record.content.replace(';', '\\;') value_formatter = { 'MX': format_mx, 'SRV': format_srv, 'SSHFP': format_sshfp, 'CAA': format_caa, 'TXT': format_txt, }.get(type_, lambda r: r.content) return { 'type': type_, 'ttl': _get_lowest_ttl(records), 'values': [value_formatter(r) for r in records], } def _parse_to_fqdn(value, current_zone): # TransIP allows '@' as value to alias the root record. # this provider won't set an '@' value, but can be an existing record if value == TransipProvider.ROOT_RECORD: value = current_zone.name if value[-1] != '.': value = '{}.{}'.format(value, current_zone.name) return value def _get_lowest_ttl(records): return min([r.expire for r in records] + [100000]) def _entries_for(name, record): values = record.values if hasattr(record, 'values') else [record.value] formatter = { 'MX': lambda v: f'{v.preference} {v.exchange}', 'SRV': lambda v: f'{v.priority} {v.weight} {v.port} {v.target}', 'SSHFP': lambda v: ( f'{v.algorithm} {v.fingerprint_type} {v.fingerprint}' ), 'CAA': lambda v: f'{v.flags} {v.tag} {v.value}', 'TXT': lambda v: v.replace('\\;', ';'), }.get(record._type, lambda r: r) return [ DNSEntry(name, record.ttl, record._type, formatter(value)) for value in values ]
4,151
412
# -*- coding: UTF-8 -*- from __future__ import unicode_literals from collections import OrderedDict from string import ascii_uppercase from .. import Provider as AddressProvider class Provider(AddressProvider): """ Provider for addresses for en_PH locale Like many things in the Philippines, even addresses are more complicated than necessary. This provider is already a gross oversimplification, and it is still a lot more complicated VS providers from other locales despite taking shortcuts. Below are some tidbits of information that, as a whole, shaped the design decisions of this provider. - There are many levels of geopolitical division, thus many levels of local government: * There are three major island groups - Luzon, Visayas, Mindanao * Those major groups are divided into 17 different regions. * Each region is divided into provinces with the exception of the National Capital Region aka Metro Manila. * Each province is composed of multiple cities/municipalities. * Metro Manila, like a province, is composed of multiple cities/municipalities, but it is a region. * Each city/municipality is composed of multiple smaller local government units called barangays. * In some places, some barangays are divided further, and as of 2019, there are 42,045 barangays on record. - Metro Manila is part of Luzon geographically, but it is almost always treated as a separate entity politically, economically, statistically, and so on, since it is home to around 13% of the population despite being only around 0.2% of the country's total land area. - Names of cities, municipalities, and barangays vary a lot. Furthermore, if a place has a non-English name, there will almost always be no English translation and vice-versa. It is essentially impossible to generate fake city, municipality, and barangay names in a similar manner used in the other "en" locales while being locale specific. - Subdivisions and other higher density housing (like high-rise condominiums) are popular in real estate. - The 13th floor is omitted in buildings like in many parts of the world. - The floor number distribution is partly based on the tallest buildings in the Philippines and partly anecdotal, but the general idea is that the higher the floor number is, the lower probability of it appearing. Furthermore, as the floor number approaches the highest floors of the tallest buildings, the probability plummets further. - The address distribution is based on the official 2015 population census. - Addresses should include a barangay, but it has been dropped to keep things sane, all things considered. - In addition to numbered floors, buildings have ground floors and may have lower ground, upper ground, mezzanine, and basement floors. Buildings may also have units on any of those floors, but the naming scheme varies, so they have been dropped, again to keep things sane. Sources: - https://en.wikipedia.org/wiki/Provinces_of_the_Philippines - https://en.wikipedia.org/wiki/List_of_cities_and_municipalities_in_the_Philippines - https://en.wikipedia.org/wiki/Barangay - https://en.wikipedia.org/wiki/Postal_addresses_in_the_Philippines - https://en.wikipedia.org/wiki/List_of_ZIP_codes_in_the_Philippines - https://www.phlpost.gov.ph/ - http://en.wikipedia.org/wiki/List_of_tallest_buildings_in_the_Philippines - https://psa.gov.ph/sites/default/files/attachments/hsd/pressrelease/2015%20population%20counts%20Summary_0.xlsx """ metro_manila_postcodes = tuple(x for x in range(400, 1849)) luzon_province_postcodes = ( tuple(x for x in range(1850, 5000)) + tuple(x for x in range(5100, 5600)) ) visayas_province_postcodes = ( tuple(x for x in range(5000, 5100)) + tuple(x for x in range(5600, 5800)) + tuple(x for x in range(6000, 6900)) ) mindanao_province_postcodes = ( tuple(x for x in range(7000, 7600)) + tuple(x for x in range(8000, 8900)) + tuple(x for x in range(9000, 9900)) ) postcodes = ( metro_manila_postcodes + luzon_province_postcodes + visayas_province_postcodes + mindanao_province_postcodes ) metro_manila_lgus = ( 'Caloocan', 'Las Piñas', 'Makati', 'Malabon', 'Mandaluyong', 'Manila', 'Marikina', 'Muntinlupa', 'Navotas', 'Parañaque', 'Pasay', 'Pasig', 'Pateros', 'Quezon City', 'San Juan', 'Taguig', 'Valenzuela', ) province_lgus = ( 'Aborlan', 'Abra de Ilog', 'Abucay', 'Abulug', 'Abuyog', 'Adams', 'Agdangan', 'Aglipay', 'Agno', 'Agoncillo', 'Agoo', 'Aguilar', 'Aguinaldo', 'Agutaya', 'Ajuy', 'Akbar', 'Al-Barka', 'Alabat', 'Alabel', 'Alamada', 'Alaminos', 'Alangalang', 'Albuera', 'Alburquerque', 'Alcala', 'Alcantara', 'Alcoy', 'Alegria', 'Aleosan', 'Alfonso Castañeda', 'Alfonso Lista', 'Alfonso', 'Aliaga', 'Alicia', 'Alilem', 'Alimodian', 'Alitagtag', 'Allacapan', 'Allen', 'Almagro', 'Almeria', 'Aloguinsan', 'Aloran', 'Altavas', 'Alubijid', 'Amadeo', 'Amai Manabilang', 'Ambaguio', 'Amlan', 'Ampatuan', 'Amulung', 'Anahawan', 'Anao', 'Anda', 'Angadanan', 'Angat', 'Angeles', 'Angono', 'Anilao', 'Anini-y', 'Antequera', 'Antipas', 'Antipolo', 'Apalit', 'Aparri', 'Araceli', 'Arakan', 'Arayat', 'Argao', 'Aringay', 'Aritao', 'Aroroy', 'Arteche', 'Asingan', 'Asipulo', 'Asturias', 'Asuncion', 'Atimonan', 'Atok', 'Aurora', 'Ayungon', 'Baao', 'Babatngon', 'Bacacay', 'Bacarra', 'Baclayon', 'Bacnotan', 'Baco', 'Bacolod-Kalawi', 'Bacolod', 'Bacolor', 'Bacong', 'Bacoor', 'Bacuag', 'Badian', 'Badiangan', 'Badoc', 'Bagabag', 'Bagac', 'Bagamanoc', 'Baganga', 'Baggao', 'Bago', 'Baguio', 'Bagulin', 'Bagumbayan', 'Bais', 'Bakun', 'Balabac', 'Balabagan', 'Balagtas', 'Balamban', 'Balanga', 'Balangiga', 'Balangkayan', 'Balaoan', 'Balasan', 'Balatan', 'Balayan', 'Balbalan', 'Baleno', 'Baler', 'Balete', 'Baliangao', 'Baliguian', 'Balilihan', 'Balindong', 'Balingasag', 'Balingoan', 'Baliuag', 'Ballesteros', 'Baloi', 'Balud', 'Balungao', 'Bamban', 'Bambang', 'Banate', 'Banaue', 'Banaybanay', 'Banayoyo', 'Banga', 'Bangar', 'Bangued', 'Bangui', 'Banguingui', 'Bani', 'Banisilan', 'Banna', 'Bansalan', 'Bansud', 'Bantay', 'Bantayan', 'Banton', 'Baras', 'Barbaza', 'Barcelona', 'Barili', 'Barira', 'Barlig', 'Barobo', 'Barotac Nuevo', 'Barotac Viejo', 'Baroy', 'Barugo', 'Basay', 'Basco', 'Basey', 'Basilisa', 'Basista', 'Basud', 'Batac', 'Batad', 'Batan', 'Batangas City', 'Bataraza', 'Bato', 'Batuan', 'Bauan', 'Bauang', 'Bauko', 'Baungon', 'Bautista', 'Bay', 'Bayabas', 'Bayambang', 'Bayang', 'Bayawan', 'Baybay', 'Bayog', 'Bayombong', 'Bayugan', 'Belison', 'Benito Soliven', 'Besao', 'Bien Unido', 'Bilar', 'Biliran', 'Binalbagan', 'Binalonan', 'Biñan', 'Binangonan', 'Bindoy', 'Bingawan', 'Binidayan', 'Binmaley', 'Binuangan', 'Biri', 'Bislig', 'Boac', 'Bobon', 'Bocaue', 'Bogo', 'Bokod', 'Bolinao', 'Boliney', 'Boljoon', 'Bombon', 'Bongabon', 'Bongabong', 'Bongao', 'Bonifacio', 'Bontoc', 'Borbon', 'Borongan', 'Boston', 'Botolan', 'Braulio E. Dujali', "Brooke's Point", 'Buadiposo-Buntong', 'Bubong', 'Bucay', 'Bucloc', 'Buenavista', 'Bugallon', 'Bugasong', 'Buguey', 'Buguias', 'Buhi', 'Bula', 'Bulakan', 'Bulalacao', 'Bulan', 'Buldon', 'Buluan', 'Bulusan', 'Bunawan', 'Burauen', 'Burdeos', 'Burgos', 'Buruanga', 'Bustos', 'Busuanga', 'Butig', 'Butuan', 'Buug', 'Caba', 'Cabadbaran', 'Cabagan', 'Cabanatuan', 'Cabangan', 'Cabanglasan', 'Cabarroguis', 'Cabatuan', 'Cabiao', 'Cabucgayan', 'Cabugao', 'Cabusao', 'Cabuyao', 'Cadiz', 'Cagayan de Oro', 'Cagayancillo', 'Cagdianao', 'Cagwait', 'Caibiran', 'Cainta', 'Cajidiocan', 'Calabanga', 'Calaca', 'Calamba', 'Calanasan', 'Calanogas', 'Calapan', 'Calape', 'Calasiao', 'Calatagan', 'Calatrava', 'Calauag', 'Calauan', 'Calayan', 'Calbayog', 'Calbiga', 'Calinog', 'Calintaan', 'Calubian', 'Calumpit', 'Caluya', 'Camalaniugan', 'Camalig', 'Camaligan', 'Camiling', 'Can-avid', 'Canaman', 'Candaba', 'Candelaria', 'Candijay', 'Candon', 'Candoni', 'Canlaon', 'Cantilan', 'Caoayan', 'Capalonga', 'Capas', 'Capoocan', 'Capul', 'Caraga', 'Caramoan', 'Caramoran', 'Carasi', 'Carcar', 'Cardona', 'Carigara', 'Carles', 'Carmen', 'Carmona', 'Carranglan', 'Carrascal', 'Casiguran', 'Castilla', 'Castillejos', 'Cataingan', 'Catanauan', 'Catarman', 'Catbalogan', 'Cateel', 'Catigbian', 'Catmon', 'Catubig', 'Cauayan', 'Cavinti', 'Cavite City', 'Cawayan', 'Cebu City', 'Cervantes', 'Clarin', 'Claver', 'Claveria', 'Columbio', 'Compostela', 'Concepcion', 'Conner', 'Consolacion', 'Corcuera', 'Cordon', 'Cordova', 'Corella', 'Coron', 'Cortes', 'Cotabato City', 'Cuartero', 'Cuenca', 'Culaba', 'Culasi', 'Culion', 'Currimao', 'Cuyapo', 'Cuyo', 'Daanbantayan', 'Daet', 'Dagami', 'Dagohoy', 'Daguioman', 'Dagupan', 'Dalaguete', 'Damulog', 'Danao', 'Dangcagan', 'Danglas', 'Dao', 'Dapa', 'Dapitan', 'Daraga', 'Daram', 'Dasmariñas', 'Dasol', 'Datu Abdullah Sangki', 'Datu Anggal Midtimbang', 'Datu Blah T. Sinsuat', 'Datu Hoffer Ampatuan', 'Datu Montawal', 'Datu Odin Sinsuat', 'Datu Paglas', 'Datu Piang', 'Datu Salibo', 'Datu Saudi-Ampatuan', 'Datu Unsay', 'Dauin', 'Dauis', 'Davao City', 'Del Carmen', 'Del Gallego', 'Delfin Albano', 'Diadi', 'Diffun', 'Digos', 'Dilasag', 'Dimasalang', 'Dimataling', 'Dimiao', 'Dinagat', 'Dinalungan', 'Dinalupihan', 'Dinapigue', 'Dinas', 'Dingalan', 'Dingle', 'Dingras', 'Dipaculao', 'Diplahan', 'Dipolog', 'Ditsaan-Ramain', 'Divilacan', 'Dolores', '<NAME>', '<NAME>', '<NAME>', 'Doña Remedios Trinidad', 'Donsol', 'Dueñas', 'Duero', 'Dulag', 'Dumaguete', 'Dumalag', 'Dumalinao', 'Dumalneg', 'Dumangas', 'Dumanjug', 'Dumaran', 'Dumarao', 'Dumingag', 'Dupax del Norte', 'Dupax del Sur', 'Echague', 'El Nido', 'El Salvador', 'Enrile', '<NAME>', '<NAME>', 'Escalante', 'Esperanza', 'Estancia', 'Famy', 'Ferrol', 'Flora', 'Floridablanca', 'Gabaldon', 'Gainza', 'Galimuyod', 'Gamay', 'Gamu', 'Ganassi', 'Gandara', 'Gapan', 'Garchitorena', '<NAME>', 'Gasan', 'Gattaran', 'General Emilio Aguinaldo', 'General Luna', 'General MacArthur', 'General Mamerto Natividad', 'General Mariano Alvarez', 'General Nakar', 'General Salipada K. Pendatun', 'General Santos', 'General Tinio', 'General Trias', 'Gerona', 'Getafe', 'Gigaquit', 'Gigmoto', 'Ginatilan', 'Gingoog', 'Giporlos', 'Gitagum', 'Glan', 'Gloria', 'Goa', 'Godod', 'Gonzaga', 'Governor Generoso', 'Gregorio del Pilar', 'Guagua', 'Gubat', 'Guiguinto', 'Guihulngan', 'Guimba', 'Guimbal', 'Guinayangan', 'Guindulman', 'Guindulungan', 'Guinobatan', 'Guinsiliban', 'Guipos', 'Guiuan', 'Gumaca', 'Gutalac', '<NAME>', '<NAME>', 'Hadji Pang<NAME>ahil', 'Hagonoy', 'Hamtic', 'Hermosa', 'Hernani', 'Hilongos', 'Himamaylan', 'Hinabangan', 'Hinatuan', 'Hindang', 'Hingyon', 'Hinigaran', 'Hinoba-an', 'Hinunangan', 'Hinundayan', 'Hungduan', 'Iba', 'Ibaan', 'Ibajay', 'Igbaras', 'Iguig', 'Ilagan', 'Iligan', 'Ilog', 'Iloilo City', 'Imelda', 'Impasugong', 'Imus', 'Inabanga', 'Indanan', 'Indang', 'Infanta', 'Initao', 'Inopacan', 'Ipil', 'Iriga', 'Irosin', 'Isabel', 'Isabela City', 'Isabela', 'Isulan', 'Itbayat', 'Itogon', 'Ivana', 'Ivisan', 'Jabonga', 'Jaen', 'Jagna', 'Jalajala', 'Jamindan', 'Janiuay', 'Jaro', 'Jasaan', 'Javier', 'Jiabong', 'Jimalalud', 'Jimenez', 'Jipapad', 'Jolo', 'Jomalig', 'Jones', 'Jordan', '<NAME>', '<NAME>', '<NAME>', 'Josefina', 'Jovellar', 'Juban', 'Julita', 'Kabacan', 'Kabankalan', 'Kabasalan', 'Kabayan', 'Kabugao', 'Kabuntalan', 'Kadingilan', 'Kalamansig', 'Kalawit', 'Kalayaan', 'Kalibo', 'Kalilangan', 'Kalingalan Caluang', 'Kananga', 'Kapai', 'Kapalong', 'Kapangan', 'Kapatagan', 'Kasibu', 'Katipunan', 'Kauswagan', 'Kawayan', 'Kawit', 'Kayapa', 'Kiamba', 'Kiangan', 'Kibawe', 'Kiblawan', 'Kibungan', 'Kidapawan', 'Kinoguitan', 'Kitaotao', 'Kitcharao', 'Kolambugan', 'Koronadal', 'Kumalarang', 'La Carlota', 'La Castellana', 'La Libertad', 'La Paz', 'La Trinidad', 'Laak', 'Labangan', 'Labason', 'Labo', 'Labrador', 'Lacub', 'Lagangilang', 'Lagawe', 'Lagayan', 'Lagonglong', 'Lagonoy', 'Laguindingan', 'Lake Sebu', 'Lakewood', 'Lal-lo', 'Lala', 'Lambayong', 'Lambunao', 'Lamitan', 'Lamut', 'Langiden', 'Languyan', 'Lantapan', 'Lantawan', 'Lanuza', 'Laoac', 'Laoag', 'Laoang', 'Lapinig', 'Lapu-Lapu', 'Lapuyan', 'Larena', 'Las Navas', 'Las Nieves', 'Lasam', 'Laua-an', 'Laur', 'Laurel', 'Lavezares', 'Lawaan', 'Lazi', 'Lebak', 'Leganes', 'Legazpi', 'Lemery', 'Le<NAME>', 'Leon', 'Leyte', 'Lezo', 'Lian', 'Lianga', 'Libacao', 'Libagon', 'Libertad', 'Libjo', 'Libmanan', 'Libon', 'Libona', 'Libungan', 'Licab', 'Licuan-Baay', 'Lidlidda', 'Ligao', 'Lila', 'Liliw', 'Liloan', 'Liloy', 'Limasawa', 'Limay', 'Linamon', 'Linapacan', 'Lingayen', 'Lingig', 'Lipa', 'Llanera', 'Llorente', 'Loay', 'Lobo', 'Loboc', 'Looc', 'Loon', 'Lope de Vega', 'Lo<NAME>', 'Lopez', 'Loreto', 'Los Baños', 'Luba', 'Lubang', 'Lubao', 'Lubuagan', 'Lucban', 'Lucena', 'Lugait', 'Lugus', 'Luisiana', 'Lumba-Bayabao', 'Lumbaca-Unayan', 'Lumban', 'Lumbatan', 'Lumbayanague', 'Luna', 'Lupao', 'Lupi', 'Lupon', 'Lutayan', 'Luuk', "M'lang", 'Maasim', 'Maasin', 'Maayon', 'Mabalacat', 'Mabinay', 'Mabini', 'Mabitac', 'Mabuhay', 'Macabebe', 'Macalelon', 'MacArthur', 'Maco', 'Maconacon', 'Macrohon', 'Madalag', 'Madalum', 'Madamba', 'Maddela', 'Madrid', 'Madridejos', 'Magalang', 'Magallanes', 'Magarao', 'Magdalena', 'Magdiwang', 'Magpet', 'Magsaysay', 'Magsingal', 'Maguing', 'Mahaplag', 'Mahatao', 'Mahayag', 'Mahinog', 'Maigo', 'Maimbung', 'Mainit', 'Maitum', 'Majayjay', 'Makato', 'Makilala', 'Malabang', 'Malabuyoc', 'Malalag', 'Malangas', 'Malapatan', 'Malasiqui', 'Malay', 'Malaybalay', 'Malibcong', 'Malilipot', 'Malimono', 'Malinao', 'Malita', 'Malitbog', 'Mallig', 'Malolos', 'Malungon', 'Maluso', 'Malvar', 'Mamasapano', 'Mambajao', 'Mamburao', 'Mambusao', 'Manabo', 'Manaoag', 'Manapla', 'Manay', 'Mandaon', 'Mandaue', 'Mangaldan', 'Mangatarem', 'Mangudadatu', 'Manito', 'Manjuyod', 'Mankayan', 'Manolo Fortich', 'Mansalay', 'Manticao', 'Manukan', 'Mapanas', 'Mapandan', 'Mapun', 'Marabut', 'Maragondon', 'Maragusan', 'Maramag', 'Marantao', 'Marawi', 'Marcos', 'Margosatubig', '<NAME>', 'Maria', 'Maribojoc', 'Marihatag', 'Marilao', 'Maripipi', 'Mariveles', 'Marogong', 'Masantol', 'Masbate City', 'Masinloc', 'Masiu', 'Maslog', 'Mataasnakahoy', 'Matag-ob', 'Matalam', 'Matalom', 'Matanao', 'Matanog', 'Mati', 'Matnog', 'Matuguinao', 'Matungao', 'Mauban', 'Mawab', 'Mayantoc', 'Maydolong', 'Mayorga', 'Mayoyao', 'Medellin', 'Medina', 'Mendez', 'Mercedes', 'Merida', 'Mexico', 'Meycauayan', 'Miagao', 'Midsalip', 'Midsayap', 'Milagros', 'Milaor', 'Mina', 'Minalabac', 'Minalin', 'Minglanilla', 'Moalboal', 'Mobo', 'Mogpog', 'Moises Padilla', 'Molave', 'Moncada', 'Mondragon', 'Monkayo', 'Monreal', 'Montevista', 'Morong', 'Motiong', 'Mulanay', 'Mulondo', 'Munai', 'Muñoz', 'Murcia', 'Mutia', 'Naawan', 'Nabas', 'Nabua', 'Nabunturan', 'Naga', 'Nagbukel', 'Nagcarlan', 'Nagtipunan', 'Naguilian', 'Naic', 'Nampicuan', 'Narra', 'Narvacan', 'Nasipit', 'Nasugbu', 'Natividad', 'Natonin', 'Naujan', 'Naval', 'New Bataan', 'New Corella', 'New Lucena', 'New Washington', 'Norala', 'Northern Kabuntalan', 'Norzagaray', 'Noveleta', 'Nueva Era', 'Nueva Valencia', 'Numancia', 'Nunungan', 'Oas', 'Obando', 'Ocampo', 'Odiongan', 'Old Panamao', 'Olongapo', 'Olutanga', 'Omar', 'Opol', 'Orani', 'Oras', 'Orion', 'Ormoc', 'Oroquieta', 'Oslob', 'Oton', 'Ozamiz', 'Padada', 'Padre Burgos', 'Padre Garcia', 'Paete', 'Pagadian', 'Pagalungan', 'Pagayawan', 'Pagbilao', 'Paglat', 'Pagsanghan', 'Pagsanjan', 'Pagudpud', 'Pakil', 'Palanan', 'Palanas', 'Palapag', 'Palauig', 'Palayan', 'Palimbang', 'Palo', 'Palompon', 'Paluan', 'Pambujan', 'Pamplona', 'Panabo', 'Panaon', 'Panay', 'Pandag', 'Pandami', 'Pandan', 'Pandi', 'Panganiban', 'Pangantucan', 'Pangil', 'Panglao', 'Panglima Estino', 'Panglima Sugala', 'Pangutaran', 'Paniqui', 'Panitan', 'Pantabangan', 'Pantao Ragat', 'Pantar', 'Pantukan', 'Panukulan', 'Paoay', 'Paombong', 'Paracale', 'Paracelis', 'Paranas', 'Parang', 'Pasacao', 'Pasil', 'Passi', 'Pastrana', 'Pasuquin', 'Pata', 'Patikul', 'Patnanungan', 'Patnongon', 'Pavia', 'Payao', 'Peñablanca', 'Peñaranda', 'Peñarrubia', 'Perez', 'Piagapo', 'Piat', 'Picong', 'Piddig', 'Pidigan', 'Pigcawayan', 'Pikit', 'Pila', 'Pilar', 'Pili', 'Pililla', 'Pinabacdao', 'Pinamalayan', 'Pinamungajan', 'Piñan', 'Pinili', 'Pintuyan', 'Pinukpuk', '<NAME>', '<NAME>', 'Pitogo', 'Placer', 'Plaridel', 'Pola', 'Polanco', 'Polangui', 'Polillo', 'Polomolok', 'Pontevedra', 'Poona Bayabao', 'Poona Piagapo', 'Porac', 'Poro', 'Pototan', 'Pozorrubio', 'Presentacion', 'President <NAME>', 'President <NAME>', 'President Quirino', 'President Roxas', '<NAME>', 'Prosperidad', 'Pualas', 'Pudtol', 'Puerto Galera', 'Puerto Princesa', 'Pugo', 'Pulilan', 'Pulupandan', 'Pura', 'Quezon', 'Quinapondan', 'Quirino', 'Ragay', '<NAME>', '<NAME>', 'Ramon', 'Ramos', 'Rapu-Rapu', 'Real', '<NAME>', '<NAME>', 'Rizal', 'Rodriguez', 'Romblon', 'Ronda', 'Rosales', 'Rosario', '<NAME>', 'Roxas City', 'Roxas', 'Sabangan', 'Sablan', 'Sablayan', 'Sabtang', 'Sadanga', 'Sagada', 'Sagay', 'Sagbayan', 'Sagñay', 'Saguday', 'Saguiaran', '<NAME>', 'Salay', 'Salcedo', 'Sallapadan', 'Salug', 'Salvador Benedicto', 'Salvador', 'Samal', 'Samboan', 'Sampaloc', 'San Agustin', 'San Andres', 'San Antonio', 'San Benito', 'San Carlos', 'San Clemente', 'San Dionisio', 'San Emilio', 'San Enrique', 'San Esteban', 'San Fabian', 'San Felipe', 'San Fernando', 'San Francisco', 'San Gabriel', 'San Guillermo', 'San Ildefonso', 'San Isidro', 'San Jacinto', 'San Joaquin', 'San Jorge', 'San Jose de Buan', 'San Jose de Buenavista', 'San Jose del Monte', 'San Jose', 'San Juan', 'San Julian', 'San Leonardo', 'San Lorenzo Ruiz', 'San Lorenzo', 'San Luis', 'San Manuel', 'San Marcelino', 'San Mariano', 'San Mateo', 'San Miguel', 'San Narciso', 'San Nicolas', 'San Pablo', 'San Pascual', 'San Pedro', 'San Policarpo', 'San Quintin', 'San Rafael', 'San Remigio', 'San Ricardo', 'San Roque', 'San Sebastian', 'San Simon', 'San Teodoro', 'San Vicente', 'Sanchez-Mira', 'Santa Ana', 'Santa Barbara', 'Santa Catalina', 'Santa Cruz', 'Santa Elena', 'Santa Fe', 'Santa Ignacia', 'Santa Josefa', 'Santa Lucia', 'Santa Magdalena', 'Santa Marcela', 'Santa Margarita', 'Santa Maria', 'Santa Monica', 'Santa Praxedes', 'Santa Rita', 'Santa Rosa', 'Santa Teresita', 'Santa', 'Santander', 'Santiago', 'Santo Domingo', 'Santo Niño', 'Santo Tomas', 'Santol', 'Sapa-Sapa', 'Sapad', 'Sapang Dalaga', 'Sapian', 'Sara', 'Sarangani', 'Sariaya', 'Sarrat', 'Sasmuan', 'Sebaste', 'Senator Ninoy Aquino', 'Ser<NAME> Sr.', 'Sevilla', '<NAME>', '<NAME>', 'Siasi', 'Siaton', 'Siay', 'Siayan', 'Sibagat', 'Sibalom', 'Sibonga', 'Sibuco', 'Sibulan', 'Sibunag', 'Sibutad', 'Sibutu', 'Sierra Bullones', 'Sigay', 'Sigma', 'Sikatuna', 'Silago', 'Silang', 'Silay', 'Silvino Lobos', 'Simunul', 'Sinacaban', 'Sinait', 'Sindangan', 'Siniloan', 'Siocon', 'Sipalay', 'Sipocot', 'Siquijor', 'Sirawai', 'Siruma', 'Sison', 'Sitangkai', 'Socorro', 'Sofronio Española', 'Sogod', 'Solana', 'Solano', 'Solsona', 'Sominot', 'Sorsogon City', 'South Ubian', 'South Upi', 'Sual', 'Subic', 'Sudipen', 'Sugbongcogon', 'Sugpon', 'Sulat', 'Sulop', 'Sultan Dumalondong', 'Sultan Kudarat', 'Sultan Mastura', 'Sultan Naga Dimaporo', 'Sultan sa Barongis', 'Sultan Sumagka', 'Sumilao', 'Sumisip', 'Surallah', 'Surigao City', 'Suyo', "T'Boli", 'Taal', 'Tabaco', 'Tabango', 'Tabina', 'Tabogon', 'Tabontabon', 'Tabuan-Lasa', 'Tabuelan', 'Tabuk', 'Tacloban', 'Tacurong', 'Tadian', 'Taft', 'Tagana-an', 'Tagapul-an', 'Tagaytay', 'Tagbilaran', 'Tagbina', 'Tagkawayan', 'Tago', 'Tagoloan II', 'Tagoloan', 'Tagudin', 'Tagum', 'Talacogon', 'Talaingod', 'Talakag', 'Talalora', 'Talavera', 'Talayan', 'Talibon', 'Talipao', 'Talisay', 'Talisayan', 'Talugtug', 'Talusan', 'Tambulig', 'Tampakan', 'Tamparan', 'Tampilisan', 'Tanauan', 'Tanay', 'Tandag', 'Tandubas', 'Tangalan', 'Tangcal', 'Tangub', 'Tanjay', 'Tantangan', 'Tanudan', 'Tanza', 'Tapaz', 'Tapul', 'Taraka', 'Tarangnan', 'Tarlac City', 'Tarragona', 'Tayabas', 'Tayasan', 'Taysan', 'Taytay', 'Tayug', 'Tayum', 'Teresa', 'Ternate', 'Tiaong', 'Tibiao', 'Tigaon', 'Tigbao', 'Tigbauan', 'Tinambac', 'Tineg', 'Tinglayan', 'Tingloy', 'Tinoc', 'Tipo-Tipo', 'Titay', 'Tiwi', '<NAME>', 'Toboso', 'Toledo', 'Tolosa', '<NAME>', 'Torrijos', '<NAME>', 'Trento', 'Trinidad', 'Tuao', 'Tuba', 'Tubajon', 'Tubao', 'Tubaran', 'Tubay', 'Tubigon', 'Tublay', 'Tubo', 'Tubod', 'Tubungan', 'Tuburan', 'Tudela', 'Tugaya', 'Tuguegarao', 'Tukuran', 'Tulunan', 'Tumauini', 'Tunga', 'Tungawan', 'Tupi', 'Turtle Islands', 'Tuy', 'Ubay', 'Umingan', 'Ungkaya Pukan', 'Unisan', 'Upi', 'Urbiztondo', 'Urdaneta', 'Uson', 'Uyugan', 'Valderrama', 'Valencia', 'Valladolid', 'Vallehermoso', 'Veruela', 'Victoria', 'Victorias', 'Viga', 'Vigan', 'Villaba', 'Villanueva', 'Villareal', 'Villasis', 'Villaverde', 'Villaviciosa', '<NAME>', 'Vintar', 'Vinzons', 'Virac', 'Wao', 'Zamboanga City', 'Zamboanguita', 'Zaragoza', 'Zarraga', 'Zumarraga', ) luzon_provinces = ( 'Abra', 'Albay', 'Apayao', 'Aurora', 'Bataan', 'Batanes', 'Batangas', 'Benguet', 'Bulacan', 'Cagayan', 'Camarines Norte', 'Camarines Sur', 'Catanduanes', 'Cavite', 'Ifugao', 'Ilocos Norte', 'Ilocos Sur', 'Isabela', 'Kalinga', 'La Union', 'Laguna', 'Marinduque', 'Masbate', 'Mountain Province', 'Nueva Ecija', 'Nueva Vizcaya', 'Occidental Mindoro', 'Oriental Mindoro', 'Palawan', 'Pampanga', 'Pangasinan', 'Quezon', 'Quirino', 'Rizal', 'Romblon', 'Sorsogon', 'Tarlac', 'Zambales', ) visayas_provinces = ( 'Aklan', 'Antique', 'Biliran', 'Bohol', 'Capiz', 'Cebu', 'Eastern Samar', 'Guimaras', 'Iloilo', 'Leyte', 'Negros Occidental', 'Negros Oriental', 'Northern Samar', 'Samar', 'Siquijor', 'Southern Leyte', ) mindanao_provinces = ( 'Agusan del Norte', 'Agusan del Sur', 'Basilan', 'Bukidnon', 'Camiguin', 'Compostela Valley', 'Cotabato', 'Davao del Norte', 'Davao del Sur', 'Davao Occidental', 'Davao Oriental', 'Dinagat Islands', 'Lanao del Norte', 'Lanao del Sur', 'Maguindanao', 'Misamis Occidental', 'Misamis Oriental', 'Sarangani', 'South Cotabato', 'Sultan Kudarat', 'Sulu', 'Surigao del Norte', 'Surigao del Sur', 'Tawi-Tawi', 'Zamboanga del Norte', 'Zamboanga del Sur', 'Zamboanga Sibugay', ) provinces = luzon_provinces + visayas_provinces + mindanao_provinces partitioned_building_number_formats = ( '{{standalone_building_number}}?', '{{standalone_building_number}} ?', '{{standalone_building_number}}-?', '{{standalone_building_number}} Unit ?', ) building_unit_number_formats = ( 'Unit {{floor_unit_number}}', 'Room {{floor_unit_number}}', '{{floor_number}}F', '{{ordinal_floor_number}} Floor', ) building_name_formats = ( '{{last_name}} {{building_name_suffix}}', '{{random_object_name}} {{building_name_suffix}}', ) building_name_suffixes = ( 'Apartment', 'Apartments', 'Building', 'Building %', 'Building Tower %', 'Condominiums', 'Condominiums %', 'Condominiums Tower %', 'Place', 'Place %', 'Place Tower %', 'Residences', 'Residences %', 'Residences Tower %', 'Suites', 'Suites %', 'Suites Tower %', 'Tower', 'Towers', 'Towers %', ) subdivision_unit_number_formats = ( 'B{{subdivision_block_number}} L{{subdivision_lot_number}}', 'Block {{subdivision_block_number}} Lot {{subdivision_lot_number}}', ) subdivision_name_formats = ( '{{last_name}} {{subdivision_name_suffix}}', '{{random_object_name}} {{subdivision_name_suffix}}', ) subdivision_name_suffixes = ( 'Cove', 'Cove %', 'Cove Phase %', 'Estates', 'Estates %', 'Estates Phase %', 'Grove', 'Grove %', 'Grove Phase %', 'Homes', 'Homes %', 'Homes Phase %', 'Subdivision', 'Subdivision %', 'Subdivision Phase %', 'Village', 'Village %', 'Village Phase %', ) floor_numbers = OrderedDict([ (str(x), 0.08) for x in range(2, 5) # Floors 2 to 4, 24% of the time ] + [ (str(x), 0.32356832089420257 / x) for x in range(5, 13) # Floors 5 to 12, 33% of the time ] + [ (str(x), 0.30341265418486174 / (x - 1)) for x in range(14, 30) # Floors 14 to 29, 25% of the time ] + [ (str(x), 0.30096338222652870 / (x - 1)) for x in range(30, 50) # Floors 30 to 49, 16% of the time ] + [ (str(x), 0.04570476167856688 / (x - 1)) for x in range(50, 75) # Floors 50 to 74, 1.9% of the time ] + [ (str(x), 0.003415677066138734 / (x - 1)) for x in range(75, 100) # Floors 75 to 99, 0.1% of the time ]) street_suffixes = OrderedDict([ ('Avenue', 0.12), ('Avenue Extension', 0.01), ('Boulevard', 0.05), ('Boulevard Extension', 0.008), ('Circle', 0.002), ('Drive', 0.15), ('Drive Extension', 0.03), ('Expressway', 0.01), ('Extension', 0.05), ('Highway', 0.02), ('Road', 0.2), ('Road Extension', 0.04), ('Service Road', 0.01), ('Street', 0.3), ]) street_name_formats = ( '{{last_name}} {{street_suffix}}', '{{ordinal_street_number}} {{street_suffix}}', '{{gemstone_name}} {{street_suffix}}', '{{mountain_name}} {{street_suffix}}', '{{plant_name}} {{street_suffix}}', '{{space_object_name}} {{street_suffix}}', ) street_address_formats = ( '{{standalone_building_number}} {{street_name}}', '{{partitioned_building_number}} {{street_name}}', '{{subdivision_unit_number}} {{subdivision_name}}, {{street_name}}', '{{subdivision_unit_number}} {{street_name}}, {{subdivision_name}}', '{{standalone_building_number}} {{street_name}}, {{subdivision_name}}', '{{building_unit_number}} {{building_name}}, {{standalone_building_number}} {{street_name}}', ) metro_manila_address_formats = ( '{{street_address}}, {{metro_manila_lgu}}, {{metro_manila_postcode}} Metro Manila', ) luzon_province_address_formats = ( '{{street_address}}, {{province_lgu}}, {{luzon_province_postcode}} {{luzon_province}}', ) visayas_province_address_formats = ( '{{street_address}}, {{province_lgu}}, {{visayas_province_postcode}} {{visayas_province}}', ) mindanao_province_address_formats = ( '{{street_address}}, {{province_lgu}}, {{mindanao_province_postcode}} {{mindanao_province}}', ) address_formats = OrderedDict([ (metro_manila_address_formats, 0.127524), (luzon_province_address_formats, 0.485317), (visayas_province_address_formats, 0.148142), (mindanao_province_address_formats, 0.239017), ]) def _ordinal_string(self, num): if isinstance(num, str): num = int(num) suffix = ['th', 'st', 'nd', 'rd', 'th'][min(num % 10, 4)] if 11 <= num % 100 <= 13: suffix = 'th' return str(num) + suffix def _create_postcode(self, postcodes): return '{postcode:04d}'.format(postcode=self.random_element(postcodes)) def _create_address(self, address_formats): return self.generator.parse(self.random_element(address_formats)) def metro_manila_postcode(self): return self._create_postcode(self.metro_manila_postcodes) def luzon_province_postcode(self): return self._create_postcode(self.luzon_province_postcodes) def visayas_province_postcode(self): return self._create_postcode(self.visayas_province_postcodes) def mindanao_province_postcode(self): return self._create_postcode(self.mindanao_province_postcodes) def postcode(self): return self._create_postcode(self.postcodes) def luzon_province(self): return self.random_element(self.luzon_provinces) def visayas_province(self): return self.random_element(self.visayas_provinces) def mindanao_province(self): return self.random_element(self.mindanao_provinces) def province(self): return self.random_element(self.provinces) def standalone_building_number(self): return str(self.random_int(min=1)) def partitioned_building_number(self): pattern = self.lexify( self.random_element(self.partitioned_building_number_formats), letters=ascii_uppercase[:10], ) return self.generator.parse(pattern) def building_number(self): if self.random_int() % 2 == 0: return self.standalone_building_number() else: return self.partitioned_building_number() def ordinal_street_number(self): return self._ordinal_string(self.random_int(1, 99)) def floor_number(self): return self.random_element(self.floor_numbers) def ordinal_floor_number(self): return self._ordinal_string(self.floor_number()) def floor_unit_number(self): return '{floor_number}{unit_number:02d}'.format( floor_number=self.floor_number(), unit_number=self.random_int(1, 40), ) def building_unit_number(self): return self.generator.parse(self.random_element(self.building_unit_number_formats)) def building_name(self): return self.generator.parse(self.random_element(self.building_name_formats)) def building_name_suffix(self): return self.numerify(self.random_element(self.building_name_suffixes)) def subdivision_block_number(self): return '{block_number:02d}'.format(block_number=self.random_int(1, 25)) def subdivision_lot_number(self): return '{lot_number:02d}'.format(lot_number=self.random_int(1, 99)) def subdivision_unit_number(self): return self.generator.parse(self.random_element(self.subdivision_unit_number_formats)) def subdivision_name(self): return self.generator.parse(self.random_element(self.subdivision_name_formats)) def subdivision_name_suffix(self): return self.numerify(self.random_element(self.subdivision_name_suffixes)) def metro_manila_lgu(self): return self.random_element(self.metro_manila_lgus) def province_lgu(self): return self.random_element(self.province_lgus) def metro_manila_address(self): return self._create_address(self.metro_manila_address_formats) def luzon_province_address(self): return self._create_address(self.luzon_province_address_formats) def visayas_province_address(self): return self._create_address(self.visayas_province_address_formats) def mindanao_province_address(self): return self._create_address(self.mindanao_province_address_formats) def address(self): return self._create_address(self.random_element(self.address_formats))
14,196
1,431
<filename>src/scratchpad/src/org/apache/poi/hwmf/draw/HwmfROP3Composite.java /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.hwmf.draw; import java.awt.Color; import java.awt.Composite; import java.awt.CompositeContext; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.util.ArrayDeque; import java.util.Deque; import org.apache.poi.hwmf.record.HwmfTernaryRasterOp; /** * HWMFs Raster Operation for Ternary arguments (Source / Destination / Pattern) */ public class HwmfROP3Composite implements Composite { private final HwmfTernaryRasterOp rop3; private final byte[] mask; private final int mask_width; private final int mask_height; private final int foreground; private final int background; private final Point2D startPnt; private final boolean hasPattern; public HwmfROP3Composite(AffineTransform at, Shape shape, HwmfTernaryRasterOp rop3, BufferedImage bitmap, Color background, Color foreground) { this.rop3 = rop3; if (bitmap == null) { mask_width = 1; mask_height = 1; mask = new byte[]{1}; } else { mask_width = bitmap.getWidth(); mask_height = bitmap.getHeight(); mask = new byte[mask_width * mask_height]; bitmap.getRaster().getDataElements(0, 0, mask_width, mask_height, mask); } this.background = background.getRGB(); this.foreground = foreground.getRGB(); Rectangle2D bnds = at.createTransformedShape(shape.getBounds2D()).getBounds2D(); startPnt = new Point2D.Double(bnds.getMinX(),bnds.getMinY()); hasPattern = rop3.calcCmd().contains("P"); } @Override public CompositeContext createContext(ColorModel srcColorModel, ColorModel dstColorModel, RenderingHints hints) { return new Rop3Context(); } private class Rop3Context implements CompositeContext { private final Deque<int[]> stack = new ArrayDeque<>(); // private Integer origOffsetX, origOffsetY; @Override public void compose(Raster src, Raster dstIn, WritableRaster dstOut) { int w = Math.min(src.getWidth(), dstIn.getWidth()); int h = Math.min(src.getHeight(), dstIn.getHeight()); int startX = (int)startPnt.getX(); int startY = (int)startPnt.getY(); int offsetY = dstIn.getSampleModelTranslateY(); int offsetX = dstIn.getSampleModelTranslateX(); final int[] srcPixels = new int[w]; final int[] dstPixels = new int[w]; final int[] patPixels = hasPattern ? new int[w] : null; for (int y = 0; y < h; y++) { dstIn.getDataElements(0, y, w, 1, dstPixels); src.getDataElements(0, y, w, 1, srcPixels); fillPattern(patPixels, y, startX, startY, offsetX, offsetY); rop3.process(stack, dstPixels, srcPixels, patPixels); assert(stack.size() == 1); int[] dstOutPixels = stack.pop(); dstOut.setDataElements(0, y, w, 1, dstOutPixels); } } private void fillPattern(int[] patPixels, int y, int startX, int startY, int offsetX, int offsetY) { if (patPixels != null) { int offY2 = (startY+y+offsetY) % mask_height; offY2 = (offY2 < 0) ? mask_height + offY2 : offY2; int maskBase = offY2 * mask_width; for (int i=0; i<patPixels.length; i++) { int offX2 = (startX+i+offsetX) % mask_width; offX2 = (offX2 < 0) ? mask_width + offX2 : offX2; patPixels[i] = mask[maskBase + offX2] == 0 ? background : foreground; } } } @Override public void dispose() { } } }
2,060
537
<filename>cpp/turbodbc/Library/turbodbc/type_code.h #pragma once namespace turbodbc { /** * This enumeration assigns integer values to certain database types */ enum class type_code : int { boolean = 0, ///< boolean type integer = 10, ///< integer types floating_point = 20, ///< floating point types string = 30, ///< string types unicode = 31, ///< unicode types timestamp = 40, ///< timestamp types date = 41 ///< date type }; }
212
852
import FWCore.ParameterSet.Config as cms # This version is intended for unpacking standard production data castorDigis = cms.EDProducer("CastorRawToDigi", # Optional filter to remove any digi with "data valid" off, "error" on, # or capids not rotating FilterDataQuality = cms.bool(True), # Number of the first CASTOR FED. If this is not specified, the # default from FEDNumbering is used. CastorFirstFED = cms.int32(690), ZDCFirstFED = cms.int32(693), # FED numbers to unpack. If this is not specified, all FEDs from # FEDNumbering will be unpacked. FEDs = cms.untracked.vint32( 690, 691, 692, 693, 722), # Do not complain about missing FEDs ExceptionEmptyData = cms.untracked.bool(False), # Do not complain about missing FEDs ComplainEmptyData = cms.untracked.bool(False), # At most ten samples can be put into a digi, if there are more # than ten, firstSample and lastSample select which samples # will be copied to the digi firstSample = cms.int32(0), lastSample = cms.int32(9), # castor technical trigger processor UnpackTTP = cms.bool(True), # report errors silent = cms.untracked.bool(False), # InputLabel = cms.InputTag("rawDataCollector"), CastorCtdc = cms.bool(False), UseNominalOrbitMessageTime = cms.bool(True), ExpectedOrbitMessageTime = cms.int32(-1), UnpackZDC = cms.bool(True), )
558
372
<reponame>kbore/pbis-open<filename>lwio/include/lwio/srvshareapi.h /* * Copyright © BeyondTrust Software 2004 - 2019 * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS * WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH * BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT * SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE, * NOTWITHSTANDING THE ABOVE NOTICE. IF YOU HAVE QUESTIONS, OR WISH TO REQUEST * A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT * BEYONDTRUST AT beyondtrust.com/contact */ /* * Copyright (C) BeyondTrust Software. All rights reserved. * * Module Name: * * srvshareapi.h * * Abstract: * * Client API around SRV share IOCTLs * * Authors: <NAME> (<EMAIL>) */ #ifndef __LWIO_SRVSHAREAPI_H__ #define __LWIO_SRVSHAREAPI_H__ #include <lwio/io-types.h> #include <lwio/lwshareinfo.h> /** * @brief Add share * * Adds a new share with the specified share info. * * @param[in] pServer the server name * @param[in] Level the share info level * @param[in] pInfo the share info * @retval LW_STATUS_SUCCESS success * @retval LW_STATUS_INVALID_LEVEL invalid info level */ LW_NTSTATUS LwIoSrvShareAdd( LW_IN LW_PCWSTR pServer, LW_IN LW_ULONG Level, LW_IN LW_PVOID pInfo ); /** * @brief Delete a share * * Deletes the share with the specified name. * * @param[in] pServer the server name * @param[in] pNetname the share name * @retval LW_STATUS_SUCCESS success * @retval LW_STATUS_NOT_FOUND the specified share was not found */ LW_NTSTATUS LwIoSrvShareDel( LW_IN LW_PCWSTR pServer, LW_IN LW_PCWSTR pNetname ); /** * @brief Enumerate shares * * Enumerates all shares at the specified info level. * The results can be freed with #LwIoSrvShareFreeInfo(). * * @param[in] pServer the server name * @param[in] Level the share info level to return * @param[out] ppInfo set to the returned share info array * @param[out] pCount set to the number of shares returned * @retval LW_STATUS_SUCCESS success * @retval LW_STATUS_INVALID_LEVEL invalid info level */ LW_NTSTATUS LwIoSrvShareEnum( LW_IN LW_PCWSTR pServer, LW_IN LW_ULONG Level, LW_OUT LW_PVOID* ppInfo, LW_OUT LW_PULONG pCount ); /** * @brief Get share info * * Gets info about the specified share at the given info level. * Use #LwIoSrvShareFreeInfo() with a Count of 1 to free the result. * * @param[in] pServer the server name * @param[in] pNetname the share name * @param[in] Level the share info level to return * @param[out] ppInfo set to the returned share info * @retval LW_STATUS_SUCCESS success * @retval LW_STATUS_INVALID_LEVEL invalid info level * @retval LW_STATUS_NOT_FOUND the specified share was not found */ LW_NTSTATUS LwIoSrvShareGetInfo( LW_IN LW_PCWSTR pServer, LW_IN LW_PCWSTR pNetname, LW_IN LW_ULONG Level, LW_OUT LW_PVOID* ppInfo ); /** * @brief Set share info * * Sets info about the specified share at the given info level. * * @param[in] pServer the server name * @param[in] pNetname the share name * @param[in] Level the share info level * @param[in] pInfo the share info to set * @retval LW_STATUS_SUCCESS success * @retval LW_STATUS_INVALID_LEVEL invalid info level * @retval LW_STATUS_NOT_FOUND the specified share was not found */ LW_NTSTATUS LwIoSrvShareSetInfo( LW_IN LW_PCWSTR pServer, LW_IN LW_PCWSTR pNetname, LW_IN LW_ULONG Level, LW_IN LW_PVOID pInfo ); /** * @brief Free share info * * Frees a share info structure or share info structure array. * * @param[in] Level the share info level * @param[in] Count the number of info structure to free * @param[in,out] pInfo the share info to free */ LW_VOID LwIoSrvShareFreeInfo( LW_ULONG Level, LW_ULONG Count, LW_PVOID pInfo ); /** * @brief Reload shares configuration * * Allows reloading shares configuration in cases the sharedb * content was changed. */ LW_NTSTATUS LwIoSrvShareReloadConfiguration( LW_VOID ); #endif
1,685
3,242
<reponame>MankinChung/cockroach<gh_stars>1000+ package com.wanjian.demo; import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; /** * Created by wanjian on 2018/1/22. */ public class SecondAct extends Activity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview); setAdapter(recyclerView); } private void setAdapter(final RecyclerView recyclerView) { recyclerView.setLayoutManager(new LinearLayoutManager(this)); DividerItemDecoration decoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL); decoration.setDrawable(getResources().getDrawable(R.drawable.divider)); recyclerView.addItemDecoration(decoration); recyclerView.setAdapter(new RecyclerView.Adapter() { @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item, recyclerView, false); view.setTag(R.id.txt, view.findViewById(R.id.txt)); return new RecyclerView.ViewHolder(view) { }; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { ((TextView) holder.itemView.getTag(R.id.txt)).setText(String.valueOf(position)); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(SecondAct.this, "POSITION " + position, Toast.LENGTH_SHORT).show(); } }); if (position == 20) { throw new RuntimeException("RecyclerView 设置数据出错 POSITION: " + position); } } @Override public int getItemCount() { return 100; } }); } }
1,099
1,768
<filename>tlatools/org.lamport.tlatools/src/tla2sany/utilities/Vector.java // Copyright (c) 2003 Compaq Corporation. All rights reserved. package tla2sany.utilities; import java.util.Enumeration; public class Vector<E> { static int defaultSize = 10; protected Object info[]; protected int size = 0; protected int capacity; protected int increment; public Vector() { info = new Object[ defaultSize ]; capacity = defaultSize; increment = defaultSize; } public Vector(int initialSize ) { info = new Object[ initialSize ]; capacity = initialSize; increment = initialSize; } public final int size() { return size; } /* Method replaced below public final String toString() { String ret=""; for (int i = 0; i < size; i++) { ret = ret + info[i].toString(); } return ret; } */ public final void addElement( E obj ) { if (size == capacity) { Object next[] = new Object[ capacity + increment ]; System.arraycopy( info, 0, next, 0, capacity ); capacity+= increment; info = next; } info[ size ] = obj; size++; } @SuppressWarnings("unchecked") public final E firstElement() { return (E)info[0]; } @SuppressWarnings("unchecked") public final E lastElement() { return (E)info[ size-1 ]; } @SuppressWarnings("unchecked") public final E elementAt(int i) { if (i < 0 || i >= size ) throw new ArrayIndexOutOfBoundsException(); else return (E)info[ i ]; } public final void removeAllElements() { for (int lvi = 0; lvi < size; lvi++ ) { info[lvi] = null; } size = 0; } public final void removeElementAt( int i ) { if (i < 0 || i >= size ) throw new ArrayIndexOutOfBoundsException(); else { for (int lvi = i+1; lvi < size; lvi++ ) info[ lvi-1 ] = info [lvi]; size--; info[ size ] = null; } } public final void insertElementAt( E obj, int i ) { if (i < 0 || i >= size ) throw new ArrayIndexOutOfBoundsException(); else if (size == capacity) { Object next[] = new Object[ capacity + increment ]; System.arraycopy( info, 0, next, 0, i ); next[i] = obj; System.arraycopy( info, i, next, i+1, capacity - i ); capacity+= increment; info = next; } else { for ( int lvi = size; lvi > i; lvi-- ) info[ lvi ] = info[lvi-1]; info[ i ] = obj; } size++; } public final void setElementAt( E obj, int i ) { if (i < 0 || i >= size ) throw new ArrayIndexOutOfBoundsException(); else info[ i ] = obj; } public final boolean contains (E obj) { for (int i = 0; i < size; i++) { if ( info[ i ] == obj ) return true; } return false; } public final Enumeration<E> elements() { return new VectorEnumeration<E>( info, size ); } public final void append( Vector<E> v ) { if ( v.size + size > capacity ) { Object neo[] = new Object[ capacity + v.capacity ]; capacity += v.capacity; System.arraycopy( info, 0, neo, 0, size ); info = neo; } System.arraycopy( v.info, 0, info, size, v.size ); size += v.size; } // Like the append method above, but elements of v will not be added to THIS Vector // if they are already present at least once; repeated elements already in // THIS Vector, however, will not be removed. public final void appendNoRepeats(Vector<E> v) { for (int i = 0; i < v.size(); i++) { if ( ! this.contains(v.elementAt(i)) ) this.addElement(v.elementAt(i)); } } @Override public final String toString() { String ret; ret = "[ "; if (this.size() > 0) ret += this.elementAt(0).toString(); for (int i = 1; i<this.size(); i++) { ret += ", " + this.elementAt(i).toString(); } return ret + " ]"; } // end toString() }
1,515
1,474
""" @author: <NAME> @contact: <EMAIL> """ from .basedataset import BaseImageDataset from typing import Callable from PIL import Image import os import os.path as osp import glob import re from common.vision.datasets._util import download class DukeMTMC(BaseImageDataset): """DukeMTMC-reID dataset from `Performance Measures and a Data Set for Multi-Target, Multi-Camera Tracking (ECCV 2016) <https://arxiv.org/pdf/1609.01775v2.pdf>`_. Dataset statistics: - identities: 1404 (train + query) - images:16522 (train) + 2228 (query) + 17661 (gallery) - cameras: 8 Args: root (str): Root directory of dataset verbose (bool, optional): If true, print dataset statistics after loading the dataset. Default: True """ dataset_dir = '.' archive_name = 'DukeMTMC-reID.tgz' dataset_url = 'https://cloud.tsinghua.edu.cn/f/89f1edaf0f83434f8070/?dl=1' def __init__(self, root, verbose=True): super(DukeMTMC, self).__init__() download(root, self.dataset_dir, self.archive_name, self.dataset_url) self.relative_dataset_dir = self.dataset_dir self.dataset_dir = osp.join(root, self.dataset_dir) self.train_dir = osp.join(self.dataset_dir, 'DukeMTMC-reID/bounding_box_train') self.query_dir = osp.join(self.dataset_dir, 'DukeMTMC-reID/query') self.gallery_dir = osp.join(self.dataset_dir, 'DukeMTMC-reID/bounding_box_test') required_files = [self.dataset_dir, self.train_dir, self.query_dir, self.gallery_dir] self.check_before_run(required_files) train = self.process_dir(self.train_dir, relabel=True) query = self.process_dir(self.query_dir, relabel=False) gallery = self.process_dir(self.gallery_dir, relabel=False) if verbose: print("=> DukeMTMC-reID loaded") self.print_dataset_statistics(train, query, gallery) self.train = train self.query = query self.gallery = gallery self.num_train_pids, self.num_train_imgs, self.num_train_cams = self.get_imagedata_info(self.train) self.num_query_pids, self.num_query_imgs, self.num_query_cams = self.get_imagedata_info(self.query) self.num_gallery_pids, self.num_gallery_imgs, self.num_gallery_cams = self.get_imagedata_info(self.gallery) def process_dir(self, dir_path, relabel=False): img_paths = glob.glob(osp.join(dir_path, '*.jpg')) pattern = re.compile(r'([-\d]+)_c(\d)') pid_container = set() for img_path in img_paths: pid, _ = map(int, pattern.search(img_path).groups()) pid_container.add(pid) pid2label = {pid: label for label, pid in enumerate(pid_container)} dataset = [] for img_path in img_paths: pid, cid = map(int, pattern.search(img_path).groups()) assert 1 <= cid <= 8 cid -= 1 # index starts from 0 if relabel: pid = pid2label[pid] dataset.append((img_path, pid, cid)) return dataset def translate(self, transform: Callable, target_root: str): """ Translate an image and save it into a specified directory Args: transform (callable): a transform function that maps images from one domain to another domain target_root (str): the root directory to save images """ os.makedirs(target_root, exist_ok=True) translated_dataset_dir = osp.join(target_root, self.relative_dataset_dir) translated_train_dir = osp.join(translated_dataset_dir, 'DukeMTMC-reID/bounding_box_train') translated_query_dir = osp.join(translated_dataset_dir, 'DukeMTMC-reID/query') translated_gallery_dir = osp.join(translated_dataset_dir, 'DukeMTMC-reID/bounding_box_test') print("Translating dataset with image to image transform...") self.translate_dir(transform, self.train_dir, translated_train_dir) self.translate_dir(None, self.query_dir, translated_query_dir) self.translate_dir(None, self.gallery_dir, translated_gallery_dir) print("Translation process is done, save dataset to {}".format(translated_dataset_dir)) def translate_dir(self, transform, origin_dir: str, target_dir: str): image_list = os.listdir(origin_dir) for image_name in image_list: if not image_name.endswith(".jpg"): continue image_path = osp.join(origin_dir, image_name) image = Image.open(image_path) translated_image_path = osp.join(target_dir, image_name) translated_image = image if transform: translated_image = transform(image) os.makedirs(os.path.dirname(translated_image_path), exist_ok=True) translated_image.save(translated_image_path)
2,098
1,270
<reponame>leisurehound/PinpointKit // // PinpointKit.h // PinpointKit // // Created by <NAME> on 1/22/16. // Copyright © 2016 Lickability. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for PinpointKit. FOUNDATION_EXPORT double PinpointKitVersionNumber; //! Project version string for PinpointKit. FOUNDATION_EXPORT const unsigned char PinpointKitVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <PinpointKit/PublicHeader.h> #import <PinpointKit/ASLLogger.h>
178
923
<filename>chainerrl/initializers/__init__.py<gh_stars>100-1000 from chainerrl.initializers.constant import VarianceScalingConstant # NOQA from chainerrl.initializers.orthogonal import Orthogonal # NOQA # LeCunNormal was merged into Chainer v3, thus removed from ChainerRL. # For backward compatibility, it is still imported in this namespace. from chainer.initializers import LeCunNormal # NOQA
122
379
/** * Copyright 2016-2017 Sixt GmbH & Co. Autovermietung KG * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.sixt.service.framework.servicetest.injection; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.sixt.service.framework.MethodHandlerDictionary; import com.sixt.service.framework.ServiceProperties; import com.sixt.service.framework.servicetest.mockservice.ImpersonatedPortDictionary; import org.eclipse.jetty.client.HttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public abstract class TestInjectionModule extends AbstractModule { private static final Logger logger = LoggerFactory.getLogger(TestInjectionModule.class); protected final ServiceProperties serviceProperties; protected final MethodHandlerDictionary methodHandlerDictionary = new MethodHandlerDictionary(); protected final ImpersonatedPortDictionary portDictionary = ImpersonatedPortDictionary.getInstance(); public TestInjectionModule(String serviceName, ServiceProperties props) { this.serviceProperties = props; serviceProperties.setServiceName(serviceName); if (props.getProperty("registry") == null) { serviceProperties.addProperty("registry", "consul"); } if (props.getProperty("registryServer") == null) { serviceProperties.addProperty("registryServer", "localhost:8500"); } if (props.getProperty("kafkaServer") == null) { serviceProperties.addProperty("kafkaServer", "localhost:9092"); } } @Provides public MethodHandlerDictionary getMethodHandlers() { return methodHandlerDictionary; } @Provides public HttpClient getHttpClient() { HttpClient client = new HttpClient(); client.setFollowRedirects(false); client.setMaxConnectionsPerDestination(32); client.setConnectTimeout(100); client.setAddressResolutionTimeout(100); //You can set more restrictive timeouts per request, but not less, so // we set the maximum timeout of 1 hour here. client.setIdleTimeout(60 * 60 * 1000); try { client.start(); } catch (Exception e) { logger.error("Error building http client", e); } return client; } @Provides public ExecutorService getExecutorService() { return Executors.newCachedThreadPool(); } public ServiceProperties getServiceProperties() { return serviceProperties; } }
927
308
<reponame>vsrvraghavan-swanspeed/edx-app-android<filename>OpenEdXMobile/src/main/java/org/edx/mobile/view/adapters/DiscussionReportViewHolder.java package org.edx.mobile.view.adapters; import android.graphics.PorterDuff; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.appcompat.widget.AppCompatImageView; import androidx.core.content.ContextCompat; import org.edx.mobile.R; public class DiscussionReportViewHolder { ViewGroup reportLayout; private AppCompatImageView reportIconImageView; private TextView reportTextView; public DiscussionReportViewHolder(View itemView) { reportLayout = (ViewGroup) itemView. findViewById(R.id.discussion_responses_action_bar_report_container); reportIconImageView = (AppCompatImageView) itemView. findViewById(R.id.discussion_responses_action_bar_report_icon_view); reportTextView = (TextView) itemView. findViewById(R.id.discussion_responses_action_bar_report_text_view); } public void setReported(boolean isReported) { reportLayout.setSelected(isReported); int reportStringResId = isReported ? R.string.discussion_responses_reported_label : R.string.discussion_responses_report_label; reportTextView.setText(reportTextView.getResources().getString(reportStringResId)); reportIconImageView.setColorFilter(ContextCompat.getColor(reportIconImageView.getContext(), R.color.infoBase), PorterDuff.Mode.SRC_IN); } public boolean toggleReported() { setReported(!reportLayout.isSelected()); return reportLayout.isSelected(); } }
628
12,278
<reponame>ikrima/immer // // immer: immutable data structures for C++ // Copyright (C) 2016, 2017, 2018 <NAME> // // This software is distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt // #include "iter.hpp" #ifndef GENERATOR_T #error "you must define a GENERATOR_T" #endif using generator__ = GENERATOR_T; using t__ = typename decltype(generator__{}(0))::value_type; NONIUS_BENCHMARK("iter/std::set", benchmark_access_std_iter<generator__, std::set<t__>>()) NONIUS_BENCHMARK("iter/std::unordered_set", benchmark_access_std_iter<generator__, std::unordered_set<t__>>()) NONIUS_BENCHMARK("iter/boost::flat_set", benchmark_access_std_iter<generator__, boost::container::flat_set<t__>>()) NONIUS_BENCHMARK("iter/hamt::hash_trie", benchmark_access_std_iter<generator__, hamt::hash_trie<t__>>()) NONIUS_BENCHMARK("iter/immer::set/5B", benchmark_access_iter<generator__, immer::set<t__, std::hash<t__>,std::equal_to<t__>,def_memory,5>>()) NONIUS_BENCHMARK("iter/immer::set/4B", benchmark_access_iter<generator__, immer::set<t__, std::hash<t__>,std::equal_to<t__>,def_memory,4>>()) NONIUS_BENCHMARK("reduce/immer::set/5B", benchmark_access_reduce<generator__, immer::set<t__, std::hash<t__>,std::equal_to<t__>,def_memory,5>>()) NONIUS_BENCHMARK("reduce/immer::set/4B", benchmark_access_reduce<generator__, immer::set<t__, std::hash<t__>,std::equal_to<t__>,def_memory,4>>())
583
644
/* Copyright 2015 OpenMarket Ltd 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 "MXKViewControllerHandling.h" #import "MXKActivityHandlingViewController.h" /** MXKViewController extends UIViewController to handle requirements for any matrixKit view controllers (see MXKViewControllerHandling protocol). This class provides some methods to ease keyboard handling. */ @interface MXKViewController : MXKActivityHandlingViewController <MXKViewControllerHandling> #pragma mark - Keyboard handling /** Call when keyboard display animation is complete. Override this method to set the actual keyboard view in 'keyboardView' property. The 'MXKViewController' instance will then observe the keyboard frame changes, and update 'keyboardHeight' property. */ - (void)onKeyboardShowAnimationComplete; /** The current keyboard view (This field is nil when keyboard is dismissed). This property should be set when keyboard display animation is complete to track keyboard frame changes. */ @property (nonatomic) UIView *keyboardView; /** The current keyboard height (This field is 0 when keyboard is dismissed). */ @property CGFloat keyboardHeight; @end
410
309
<filename>piou/formatter/rich_formatter.py import sys from dataclasses import dataclass, field from typing import Optional, Union from rich.console import Console, RenderableType from rich.markdown import Markdown from rich.padding import Padding from rich.table import Table from .base import Formatter, Titles from ..command import Command, CommandOption, ParentArgs, CommandGroup def pad(s: RenderableType, padding_left: int = 1): return Padding(s, (0, padding_left)) def fmt_option(option: CommandOption, show_full: bool = False, color: str = 'white') -> str: if option.is_positional_arg: return f'[{color}]<{option.name}>[/{color}]' elif show_full: first_arg, *other_args = option.keyword_args required = f'[{color}]*[/{color}]' if option.is_required else '' if other_args: other_args = ', '.join(other_args) return f'[{color}]{first_arg}[/{color}] ({other_args}){required}' else: return f'[{color}]{first_arg}[/{color}]{required}' else: return '[' + sorted(option.keyword_args)[-1] + ']' def fmt_cmd_options(options: list[CommandOption]) -> str: return (' '.join([fmt_option(x) for x in options]) if options else '' # '[<arg1>] ... [<argN>]' ) def fmt_help(option: CommandOption, show_default: bool): if show_default and option.default is not None and not option.is_required: default_str = option.default if not option.is_password else '******' default_str = f'[bold](default: {default_str})[/bold]' return option.help + f' {default_str}' if option.help else default_str else: return option.help def get_usage(global_options: list[CommandOption], command: Optional[str] = None, command_options: Optional[list[CommandOption]] = None, parent_args: Optional[ParentArgs] = None): parent_args = parent_args or [] _global_options = ' '.join(['[' + sorted(x.keyword_args)[-1] + ']' for x in global_options]) command = f'[underline]{command}[/underline]' if command else '<command>' cmds = [sys.argv[0].split('/')[-1]] + [x.cmd for x in parent_args] cmds = ' '.join(f'[underline]{x}[/underline]' for x in cmds) usage = cmds if _global_options: usage = f'{usage} {_global_options}' usage = f'{usage} {command}' if command_options: usage = f'{usage} {fmt_cmd_options(command_options)}' return usage @dataclass(frozen=True) class RichTitles(Titles): GLOBAL_OPTIONS = f'[bold]{Titles.GLOBAL_OPTIONS}[/bold]' AVAILABLE_CMDS = f'[bold]{Titles.AVAILABLE_CMDS}[/bold]' COMMANDS = f'[bold]{Titles.COMMANDS}[/bold]' USAGE = f'[bold]{Titles.USAGE}[/bold]' DESCRIPTION = f'[bold]{Titles.DESCRIPTION}[/bold]' ARGUMENTS = f'[bold]{Titles.ARGUMENTS}[/bold]' OPTIONS = f'[bold]{Titles.OPTIONS}[/bold]' MIN_MARKDOWN_SIZE: int = 75 @dataclass class RichFormatter(Formatter): _console: Console = field(init=False, default_factory=lambda: Console(markup=True, highlight=False)) cmd_color: str = 'cyan' option_color: str = 'cyan' show_default: bool = True use_markdown: bool = True """Use Markdown object for the description, otherwise use default str """ # Only if use_markdown is True code_theme: str = 'solarized-dark' """See https://pygments.org/styles/ for a list of styles """ def _color_cmd(self, cmd: str): return f'[{self.cmd_color}]{cmd}[/{self.cmd_color}]' def __post_init__(self): self.print_fn = self._console.print def _print_description(self, item: Union[CommandGroup, Command]): description = item.description or item.help if description: self.print_fn() self.print_fn(RichTitles.DESCRIPTION) if self.use_markdown: _max_width = max(len(x) for x in description.split('\n')) self.print_fn(pad(Markdown(' \n'.join(description.split('\n')), code_theme=self.code_theme)), width=max(_max_width, MIN_MARKDOWN_SIZE)) else: self.print_fn(pad(description)) def _print_options(self, options: list[CommandOption]): self.print_rows([(fmt_option(opt, show_full=True, color=self.option_color), fmt_help(opt, show_default=self.show_default)) for opt in options]) def print_rows(self, rows: list[tuple[str, Optional[str]]]): table = Table(show_header=False, box=None, padding=(0, self.col_space)) table.add_column(width=self.col_size) table.add_column() for row in rows: table.add_row(*row) self.print_fn(table) def print_cli_help(self, group: CommandGroup): self.print_fn(RichTitles.USAGE) self.print_fn(pad(get_usage(group.options))) self.print_fn() if group.options: self.print_fn(RichTitles.GLOBAL_OPTIONS) self._print_options(group.options) self.print_fn() self.print_fn(RichTitles.AVAILABLE_CMDS) self.print_rows([(f' {self._color_cmd(_command.name or "")}', _command.help) for _command in group.commands.values()]) self._print_description(group) def print_cmd_help(self, command: Command, options: list[CommandOption], parent_args: Optional[ParentArgs] = None): usage = get_usage( global_options=options, command=command.name, command_options=command.options_sorted, parent_args=parent_args ) self.print_fn(RichTitles.USAGE) self.print_fn(pad(usage)) self.print_fn() if command.positional_args: self.print_fn(RichTitles.ARGUMENTS) self.print_rows( [(fmt_option(option, color=self.option_color), fmt_help(option, show_default=self.show_default)) for option in command.positional_args]) if command.keyword_args: self.print_fn('\n' + RichTitles.OPTIONS) self._print_options(command.keyword_args) global_options = options + [parent_option for parent_arg in (parent_args or []) for parent_option in parent_arg.options] if global_options: self.print_fn('\n' + RichTitles.GLOBAL_OPTIONS) self._print_options(global_options) self._print_description(command) def print_cmd_group_help(self, group: CommandGroup, parent_args: ParentArgs): parent_commands = [sys.argv[0].split('/')[-1]] + [x.cmd for x in parent_args] commands_str = [] for i, (cmd_name, cmd) in enumerate(group.commands.items()): _cmds = [] for cmd_lvl, x in enumerate(parent_commands + [cmd_name]): _cmds.append(f'[underline]{x}[/underline]') if group.options and cmd_lvl == len(parent_commands) - 1: _cmds.append(fmt_cmd_options(group.options)) _cmds_str = ' '.join(_cmds) _line = f'{"" if i == 0 else "or: ":>5}{_cmds_str} {fmt_cmd_options(cmd.options_sorted)}'.rstrip() commands_str.append(_line) commands_str = '\n'.join(commands_str) self.print_fn(RichTitles.USAGE) self.print_fn(commands_str) self.print_fn() self.print_fn(RichTitles.COMMANDS) for cmd_name, cmd in group.commands.items(): self.print_fn(pad(f'[underline]{cmd_name}[/underline]', padding_left=2)) if cmd.help: self.print_fn(pad(cmd.help, padding_left=4)) self.print_fn() if cmd.options: self.print_rows([(fmt_option(opt, show_full=True, color=self.option_color), fmt_help(opt, show_default=self.show_default)) for opt in cmd.options_sorted]) self.print_fn() if group.options: self.print_fn(RichTitles.OPTIONS) self._print_options(group.options) self.print_fn() global_options = [parent_option for parent_arg in (parent_args or []) for parent_option in parent_arg.options] if global_options: self.print_fn(RichTitles.GLOBAL_OPTIONS) self._print_options(global_options) self._print_description(group) def print_cmd_error(self, available_commands: list[str]): _available_cmds = ', '.join(available_commands) self.print_fn(f'[red]Unknown command given. Possible commands are "[bold]{_available_cmds}[/bold]"[/red]') def print_keyword_param_error(self, cmd: str, param: str) -> None: self.print_fn( f'[red]Could not find keyword parameter [bold]{param!r}[/bold] for command [bold]{cmd!r}[/bold][/red]') def print_param_error(self, key: str, cmd: str) -> None: self.print_fn(f"[red]Could not find value for [bold]{key!r}[/bold] in [bold]{cmd}[/bold][/red]") def print_count_error(self, expected_count: int, count: int, cmd: str): self.print_fn( f'[red]Expected {expected_count} positional arguments but got {count} for command [bold]{cmd}[/bold][/red]')
4,534
3,444
<reponame>huihui7987/blade package com.hellokaton.blade.kit; import com.hellokaton.blade.mvc.http.Request; import lombok.experimental.UtilityClass; /** * Web kit * * @author biezhi * 2017/6/2 */ @UtilityClass public class WebKit { public static final String UNKNOWN_MAGIC = "unknown"; /** * Get the client IP address by request * * @param request Request instance * @return return ip address */ public static String ipAddress(Request request) { String ipAddress = request.header("x-forwarded-for"); if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) { ipAddress = request.header("Proxy-Client-IP"); } if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) { ipAddress = request.header("WL-Proxy-Client-IP"); } if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) { ipAddress = request.header("X-Real-IP"); } if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) { ipAddress = request.header("HTTP_CLIENT_IP"); } if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) { ipAddress = request.header("HTTP_X_FORWARDED_FOR"); } return ipAddress; } }
582
558
// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2013, <NAME>, FU Berlin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Knut Reinert or the FU Berlin nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // ========================================================================== // Author: <NAME> <<EMAIL>> // ========================================================================== #ifndef CORE_INCLUDE_SEQAN_BAM_IO_CIGAR_H_ #define CORE_INCLUDE_SEQAN_BAM_IO_CIGAR_H_ namespace seqan { // ============================================================================ // Forwards // ============================================================================ // ============================================================================ // Tags, Classes, Enums // ============================================================================ // ---------------------------------------------------------------------------- // struct CigarElement // ---------------------------------------------------------------------------- /** .Class.CigarElement ..cat:Fragment Store ..summary:One entry of a CIGAR string. ..signature:CigarElement<TOperation, TCount> ..param.TOperation:Type to use for storing operations. ...default:nolink:$char$ ..param.TCount:Type to use for storing counts. ...default:nolink:$unsigned$ ..include:seqan/store.h .Memfunc.CigarElement#CigarElement ..class:Class.CigarElement ..summary:Constructor ..signature:CigarElement() ..signature:CigarElement(operation, count) ..param.operation:The operation to use. ...type:nolink:$TOperation$, typically $char$. ..param.count:The operation count. ...type:nolink:$Count$, typically $unsigned$. ..remarks:The default constructor initialized both @Memvar.CigarElement#operation@ and @Memvar.CigarElement#count@ with $0$. .Memvar.CigarElement#operation ..class:Class.CigarElement ..summary:The described operation. ..type:nolink:$TOperation$ .Memvar.CigarElement#count ..class:Class.CigarElement ..summary:The number of operations. ..type:nolink:$TCount$ */ template <typename TOperation_ = char, typename TCount_ = unsigned> struct CigarElement { typedef TOperation_ TOperation; typedef TCount_ TCount; TOperation operation; TCount count; CigarElement() : operation(0), count(0) {} CigarElement(TOperation o, TCount c): operation(o), count(c) {} }; // ============================================================================ // Metafunctions // ============================================================================ // ============================================================================ // Functions // ============================================================================ template <typename TOperation, typename TCount> inline bool operator>(CigarElement<TOperation, TCount> const & lhs, CigarElement<TOperation, TCount> const & rhs) { return lhs.operation > rhs.operation || (lhs.operation == rhs.operation && lhs.count > rhs.count); } template <typename TOperation, typename TCount> inline bool operator<(CigarElement<TOperation, TCount> const & lhs, CigarElement<TOperation, TCount> const & rhs) { return lhs.operation < rhs.operation || (lhs.operation == rhs.operation && lhs.count < rhs.count); } template <typename TOperation, typename TCount> inline bool operator==(CigarElement<TOperation, TCount> const & lhs, CigarElement<TOperation, TCount> const & rhs) { return lhs.operation == rhs.operation && lhs.count == rhs.count; } // ---------------------------------------------------------------------------- // toBamCigarElement() // ---------------------------------------------------------------------------- template <typename TOperation, typename TCount> __uint32 toBamCigarElement(CigarElement<TOperation, TCount> const & cigarElement) { char operation = 0; switch (cigarElement.operation) { case 'X': operation += 1; case '=': operation += 1; case 'P': operation += 1; case 'H': operation += 1; case 'S': operation += 1; case 'N': operation += 1; case 'D': operation += 1; case 'I': operation += 1; case 'M': break; } return (cigarElement.count << 4) | operation; } // ---------------------------------------------------------------------------- // getMDString() // ---------------------------------------------------------------------------- template < typename TMDString, typename TGaps1, typename TGaps2> inline void getMDString( TMDString &md, TGaps1 &gaps1, TGaps2 &gaps2) { typedef typename Value<TMDString>::Type TMDChar; typename Iterator<TGaps1>::Type it1 = begin(gaps1); typename Iterator<TGaps2>::Type it2 = begin(gaps2); char op, lastOp = ' '; unsigned numOps = 0; clear(md); for (; !atEnd(it1) && !atEnd(it2); goNext(it1), goNext(it2)) { if (isGap(it1)) continue; if (isGap(it2)) { op = 'D'; } else op = (*it1 == *it2)? 'M': 'R'; // append match run if (lastOp != op) { if (lastOp == 'M') { std::stringstream num; num << numOps; append(md, num.str()); } numOps = 0; lastOp = op; } // append deleted/replaced reference character if (op != 'M') { // add ^ from non-deletion to deletion if (op == 'D' && lastOp != 'D') appendValue(md, '^'); // add 0 from deletion to replacement if (op == 'R' && lastOp == 'D') appendValue(md, '0'); appendValue(md, convert<TMDChar>(*it1)); } ++numOps; } SEQAN_ASSERT_EQ(atEnd(it1), atEnd(it2)); if (lastOp == 'M') { std::stringstream num; num << numOps; append(md, num.str()); } } // ---------------------------------------------------------------------------- // getCigarString() // ---------------------------------------------------------------------------- template < typename TCigar, typename TGaps1, typename TGaps2, typename TThresh> inline void getCigarString( TCigar &cigar, TGaps1 &gaps1, TGaps2 &gaps2, TThresh splicedGapThresh) { typename Iterator<TGaps1>::Type it1 = begin(gaps1); typename Iterator<TGaps2>::Type it2 = begin(gaps2); clear(cigar); char op, lastOp = ' '; unsigned numOps = 0; // std::cout << "gaps1\t" << gaps1 << std::endl; // std::cout << "gaps2\t" << gaps2 << "\t" << clippedBeginPosition(gaps2) << std::endl; for (; !atEnd(it1) && !atEnd(it2); goNext(it1), goNext(it2)) { if (isGap(it1)) { if (isGap(it2)) op = 'P'; else if (isClipped(it2)) op = '?'; else op = 'I'; } else if (isClipped(it1)) { op = '?'; } else { if (isGap(it2)) op = 'D'; else if (isClipped(it2)) op = 'S'; else op = 'M'; } // append CIGAR operation if (lastOp != op) { if (lastOp == 'D' && numOps >= (unsigned)splicedGapThresh) lastOp = 'N'; if (numOps > 0) { std::stringstream num; num << numOps; append(cigar, num.str()); appendValue(cigar, lastOp); } numOps = 0; lastOp = op; } ++numOps; } // if (atEnd(it1) != atEnd(it2)) // std::cerr << "Invalid pairwise alignment:" << std::endl << gaps1 << std::endl << gaps2 << std::endl; SEQAN_CHECK(atEnd(it1) == atEnd(it2), "Cannot get CIGAR from invalid pairwise alignment!"); if (lastOp == 'D' && numOps >= (unsigned)splicedGapThresh) lastOp = 'N'; if (numOps > 0) { std::stringstream num; num << numOps; append(cigar, num.str()); appendValue(cigar, lastOp); } } template < typename TCigar, typename TGaps1, typename TGaps2> inline void getCigarString( TCigar &cigar, TGaps1 &gaps1, TGaps2 &gaps2) { return getCigarString(cigar, gaps1, gaps2, 20); } template < typename TOperation, typename TCount, typename TSpec, typename TGaps1, typename TGaps2, typename TThresh> inline void getCigarString( String<CigarElement<TOperation, TCount>, TSpec> &cigar, TGaps1 &gaps1, TGaps2 &gaps2, TThresh splicedGapThresh) { typename Iterator<TGaps1>::Type it1 = begin(gaps1); typename Iterator<TGaps2>::Type it2 = begin(gaps2); clear(cigar); char op = '?', lastOp = ' '; unsigned numOps = 0; // std::cout << gaps1 << std::endl; // std::cout << gaps2 << std::endl; for (; !atEnd(it1) && !atEnd(it2); goNext(it1), goNext(it2)) { if (isGap(it1)) { if (isGap(it2)) op = 'P'; else if (isClipped(it2)) op = '?'; else op = 'I'; } else if (isClipped(it1)) { op = '?'; } else { if (isGap(it2)) op = 'D'; else if (isClipped(it2)) op = 'S'; else op = 'M'; } if (lastOp != op) { if (lastOp == 'D' && numOps >= (unsigned)splicedGapThresh) lastOp = 'N'; if (numOps > 0) appendValue(cigar, CigarElement<>(lastOp, numOps)); numOps = 0; lastOp = op; } ++numOps; } SEQAN_ASSERT_EQ(atEnd(it1), atEnd(it2)); if (lastOp == 'D' && numOps >= (unsigned)splicedGapThresh) lastOp = 'N'; if (numOps > 0) appendValue(cigar, CigarElement<>(op, numOps)); } // ---------------------------------------------------------------------------- // alignAndGetCigarString() // ---------------------------------------------------------------------------- template < typename TCigar, typename TMDString, typename TContig, typename TReadSeq, typename TAlignedRead, typename TErrors, typename TAlignFunctor> inline void alignAndGetCigarString( TCigar &cigar, TMDString &md, TContig &contig, TReadSeq &readSeq, TAlignedRead &alignedRead, TErrors &errors, TAlignFunctor const & functor) { typedef Align<TReadSeq, ArrayGaps> TAlign; TAlign align; resize(rows(align), 2); if (alignedRead.beginPos <= alignedRead.endPos) assignSource(row(align, 0), infix(contig.seq, alignedRead.beginPos, alignedRead.endPos)); else assignSource(row(align, 0), infix(contig.seq, alignedRead.endPos, alignedRead.beginPos)); assignSource(row(align, 1), readSeq); if (!(errors == 0 || (errors == 1 && length(readSeq) == length(source(row(align, 0)))))) errors = functor.align(align); getCigarString(cigar, row(align, 0), row(align, 1)); getMDString(md, row(align, 0), row(align, 1)); } template <typename TCigar, typename TMDString, typename TContig, typename TReadSeq, typename TErrors, typename TAlignedRead> inline void alignAndGetCigarString(TCigar &cigar, TMDString &md, TContig &contig, TReadSeq &readSeq, TAlignedRead &alignedRead, TErrors &, Nothing const &) { typedef typename TContig::TContigSeq TContigSeq; typedef Gaps<TContigSeq, AnchorGaps<typename TContig::TGapAnchors> > TContigGaps; typedef Gaps<TReadSeq, AnchorGaps<typename TAlignedRead::TGapAnchors> > TReadGaps; TContigGaps contigGaps(contig.seq, contig.gaps); if (alignedRead.beginPos <= alignedRead.endPos) { setClippedBeginPosition(contigGaps, alignedRead.beginPos); setClippedEndPosition(contigGaps, alignedRead.endPos); } else { setClippedBeginPosition(contigGaps, alignedRead.endPos); setClippedEndPosition(contigGaps, alignedRead.beginPos); } TReadGaps readGaps(readSeq, alignedRead.gaps); // TContigGaps contigGaps2(contig.seq, contig.gaps); // if (i == 4) // printf("It's it!\n"); // std::cerr << "read gaps: " << readGaps << std::endl; // std::cerr << "contig gaps:" << contigGaps << std::endl; getCigarString(cigar, contigGaps, readGaps); getMDString(md, contigGaps, readGaps); } // ---------------------------------------------------------------------------- // _getClippedLength() // ---------------------------------------------------------------------------- template <typename TCigarString, typename TNum> inline void _getClippedLength(TCigarString const & cigar, TNum & sum) { typedef typename Iterator<TCigarString, Standard>::Type TCigarIter; TCigarIter it = begin(cigar, Standard()); TCigarIter itEnd = end(cigar, Standard()); sum = 0; for (; it != itEnd; ++it) if (getValue(it).operation != 'S' && getValue(it).operation != 'H') sum += getValue(it).count; } // ---------------------------------------------------------------------------- // _getLengthInRef() // ---------------------------------------------------------------------------- template <typename TCigarString, typename TNum> inline void _getLengthInRef(TCigarString const & cigar, TNum & sum) { typedef typename Iterator<TCigarString const, Standard>::Type TCigarIter; TCigarIter it = begin(cigar, Standard()); TCigarIter itEnd = end(cigar, Standard()); sum = 0; for (; it != itEnd; ++it) if (getValue(it).operation != 'S' && getValue(it).operation != 'H' && getValue(it).operation != 'I') sum += getValue(it).count; } // ---------------------------------------------------------------------------- // cigarToGapAnchorRead() // ---------------------------------------------------------------------------- template<typename TCigarString, typename TGaps> inline unsigned cigarToGapAnchorRead(TCigarString const & cigar, TGaps & gaps) { typename Iterator<TGaps>::Type it = begin(gaps); bool atBegin = true; unsigned beginGaps = 0; for (unsigned i = 0; i < length(cigar); ++i) { switch (cigar[i].operation) { case 'D': case 'N': case 'P': if (atBegin) beginGaps += cigar[i].count; insertGaps(it, cigar[i].count); case 'I': case 'M': case 'S': it += cigar[i].count; atBegin = false; } } return beginGaps; } // ---------------------------------------------------------------------------- // cigarToGapAnchorContig() // ---------------------------------------------------------------------------- template<typename TCigarString, typename TGaps> inline unsigned cigarToGapAnchorContig(TCigarString const & cigar, TGaps & gaps) { typename Iterator<TGaps>::Type it = begin(gaps); bool atBegin = true; unsigned beginGaps = 0; for (unsigned i = 0; i < length(cigar); ++i) { switch (cigar[i].operation) { case 'I': case 'P': if (atBegin) beginGaps += cigar[i].count; insertGaps(it, cigar[i].count); case 'D': case 'M': case 'N': case 'S': it += cigar[i].count; atBegin = false; } } return beginGaps; } } // namespace seqan #endif // #ifndef CORE_INCLUDE_SEQAN_BAM_IO_CIGAR_H_
6,936
1,444
package mage.cards.r; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.Effect; import mage.abilities.effects.common.DontUntapInControllersUntapStepAllEffect; import mage.abilities.effects.common.TapTargetEffect; import mage.abilities.effects.common.counter.AddCountersTargetEffect; import mage.abilities.keyword.FlyingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.*; import mage.counters.CounterType; import mage.filter.common.FilterCreaturePermanent; import mage.target.common.TargetCreaturePermanent; import java.util.UUID; /** * * @author JRHerlehy */ public final class RimescaleDragon extends CardImpl { private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("creatures with ice counters"); static { filter.add(CounterType.ICE.getPredicate()); } public RimescaleDragon(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{5}{R}{R}"); this.addSuperType(SuperType.SNOW); this.subtype.add(SubType.DRAGON); this.power = new MageInt(5); this.toughness = new MageInt(5); // Flying this.addAbility(FlyingAbility.getInstance()); // {2}{snow}: Tap target creature and put an ice counter on it. Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new TapTargetEffect("tap target creature"), new ManaCostsImpl("{2}{S}") ); Effect effect = new AddCountersTargetEffect(CounterType.ICE.createInstance()); effect.setText("and put an ice counter on it"); ability.addEffect(effect); ability.addTarget(new TargetCreaturePermanent(1)); this.addAbility(ability); // Creatures with ice counters on them don't untap during their controllers' untap steps. effect = new DontUntapInControllersUntapStepAllEffect(Duration.WhileOnBattlefield, TargetController.ANY, filter); effect.setText("Creatures with ice counters on them don't untap during their controllers' untap steps"); this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, effect)); } private RimescaleDragon(final RimescaleDragon card) { super(card); } @Override public RimescaleDragon copy() { return new RimescaleDragon(this); } }
897
6,304
/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkClusterator_DEFINED #define SkClusterator_DEFINED #include <vector> #include <cstdint> class SkGlyphRun; /** Given the m-to-n glyph-to-character mapping data (as returned by harfbuzz), iterate over the clusters. */ class SkClusterator { public: SkClusterator(const SkGlyphRun& run); uint32_t glyphCount() const { return fGlyphCount; } bool reversedChars() const { return fReversedChars; } struct Cluster { const char* fUtf8Text; uint32_t fTextByteLength; uint32_t fGlyphIndex; uint32_t fGlyphCount; explicit operator bool() const { return fGlyphCount != 0; } bool operator==(const SkClusterator::Cluster& o) { return fUtf8Text == o.fUtf8Text && fTextByteLength == o.fTextByteLength && fGlyphIndex == o.fGlyphIndex && fGlyphCount == o.fGlyphCount; } }; Cluster next(); private: uint32_t const * const fClusters; char const * const fUtf8Text; uint32_t const fGlyphCount; uint32_t const fTextByteLength; bool const fReversedChars; uint32_t fCurrentGlyphIndex = 0; }; #endif // SkClusterator_DEFINED
577
1,103
<reponame>noyarth/eggs<filename>database/redis/redis-6/egg-redis-6.json { "_comment": "DO NOT EDIT: FILE GENERATED AUTOMATICALLY BY PTERODACTYL PANEL - PTERODACTYL.IO", "meta": { "version": "PTDL_v1" }, "exported_at": "2020-09-28T21:07:40-04:00", "name": "Redis-6", "author": "<EMAIL>", "description": "Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams.", "image": "quay.io\/parkervcp\/pterodactyl-images:db_redis-6", "startup": "\/usr\/local\/bin\/redis-server \/home\/container\/redis.conf --save 60 1 --dir \/home\/container\/ --bind 0.0.0.0 --port {{SERVER_PORT}} --requirepass {{SERVER_PASSWORD}} --maxmemory {{SERVER_MEMORY}}mb --daemonize yes && redis-cli -p {{SERVER_PORT}} -a {{SERVER_PASSWORD}}; redis-cli -p {{SERVER_PORT}} -a {{SERVER_PASSWORD}} shutdown save", "config": { "files": "{}", "startup": "{\r\n \"done\": \"Configuration loaded\"\r\n}", "logs": "{}", "stop": "^C" }, "scripts": { "installation": { "script": "#!\/bin\/ash\r\n# Redis Installation Script\r\n#\r\n# Server Files: \/mnt\/server\r\n\r\napk add --no-cache curl\r\n\r\nif [ ! -d \/mnt\/server ]; then\r\n mkdir \/mnt\/server\/\r\nfi\r\n\r\ncd \/mnt\/server\/\r\n\r\nif [ ! -d \/mnt\/server\/redis.conf ]; then\r\n curl https:\/\/raw.githubusercontent.com\/parkervcp\/eggs\/master\/database\/redis\/redis-6\/redis.conf -o redis.conf\r\nfi\r\n\r\nsleep 5\r\necho -e \"Install complete. Made this to not have issues.\"", "container": "alpine:3.10", "entrypoint": "ash" } }, "variables": [ { "name": "Redis Password", "description": "The password redis should use to secure the server.", "env_variable": "SERVER_PASSWORD", "default_value": "<PASSWORD>", "user_viewable": 1, "user_editable": 1, "rules": "required|string" } ] }
985
426
<filename>IfcPlusPlus/src/ifcpp/IFC4/lib/IfcPolyLoop.cpp /* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include "ifcpp/model/AttributeObject.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/model/BuildingGuid.h" #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/IFC4/include/IfcCartesianPoint.h" #include "ifcpp/IFC4/include/IfcPolyLoop.h" #include "ifcpp/IFC4/include/IfcPresentationLayerAssignment.h" #include "ifcpp/IFC4/include/IfcStyledItem.h" // ENTITY IfcPolyLoop IfcPolyLoop::IfcPolyLoop( int id ) { m_entity_id = id; } shared_ptr<BuildingObject> IfcPolyLoop::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcPolyLoop> copy_self( new IfcPolyLoop() ); for( size_t ii=0; ii<m_Polygon.size(); ++ii ) { auto item_ii = m_Polygon[ii]; if( item_ii ) { copy_self->m_Polygon.emplace_back( dynamic_pointer_cast<IfcCartesianPoint>(item_ii->getDeepCopy(options) ) ); } } return copy_self; } void IfcPolyLoop::getStepLine( std::stringstream& stream ) const { stream << "#" << m_entity_id << "= IFCPOLYLOOP" << "("; writeEntityList( stream, m_Polygon ); stream << ");"; } void IfcPolyLoop::getStepParameter( std::stringstream& stream, bool /*is_select_type*/ ) const { stream << "#" << m_entity_id; } const std::wstring IfcPolyLoop::toString() const { return L"IfcPolyLoop"; } void IfcPolyLoop::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map ) { const size_t num_args = args.size(); if( num_args != 1 ){ std::stringstream err; err << "Wrong parameter count for entity IfcPolyLoop, expecting 1, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); } readEntityReferenceList( args[0], m_Polygon, map ); } void IfcPolyLoop::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const { IfcLoop::getAttributes( vec_attributes ); if( !m_Polygon.empty() ) { shared_ptr<AttributeObjectVector> Polygon_vec_object( new AttributeObjectVector() ); std::copy( m_Polygon.begin(), m_Polygon.end(), std::back_inserter( Polygon_vec_object->m_vec ) ); vec_attributes.emplace_back( std::make_pair( "Polygon", Polygon_vec_object ) ); } } void IfcPolyLoop::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) const { IfcLoop::getAttributesInverse( vec_attributes_inverse ); } void IfcPolyLoop::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity ) { IfcLoop::setInverseCounterparts( ptr_self_entity ); } void IfcPolyLoop::unlinkFromInverseCounterparts() { IfcLoop::unlinkFromInverseCounterparts(); }
1,081
32,544
package com.baeldung.web.reactive; import com.fasterxml.jackson.annotation.JsonProperty; public class Task { private final String name; private final int id; public Task(@JsonProperty("name") String name, @JsonProperty("id") int id) { this.name = name; this.id = id; } public String getName() { return this.name; } public int getId() { return this.id; } @Override public String toString() { return "Task{" + "name='" + name + '\'' + ", id=" + id + '}'; } }
230
427
<gh_stars>100-1000 # # RUN: rm -rf %t.dir # RUN: mkdir -p %t.dir # RUN: touch %t.dir/hello.swift # RUN: echo 'print("hello")' > %t.dir/hello.swift # RUN: %{swiftc} %t.dir/hello.swift -o %t.dir/hello # Check the file exists # # RUN: ls %t.dir/ > %t.listing # RUN: %{FileCheck} --check-prefix CHECK-FILE --input-file %t.listing %s # # CHECK-FILE: hello # Check the file runs # # RUN: %t.dir/hello > %t.output # RUN: %{FileCheck} --check-prefix CHECK-OUT --input-file %t.output %s # # CHECK-OUT: hello
220
851
import os from pathlib import Path import sys from typing import Optional, Text import toml version_file_path = Path("questionary/version.py") pyproject_file_path = Path("pyproject.toml") def get_pyproject_version(): """Return the project version specified in the poetry build configuration.""" data = toml.load(pyproject_file_path) return data["tool"]["poetry"]["version"] def get_current_version() -> Text: """Return the current library version as specified in the code.""" if not version_file_path.is_file(): raise FileNotFoundError( f"Failed to find version file at {version_file_path().absolute()}" ) # context in which we evaluate the version py - # to be able to access the defined version, it already needs to live in the # context passed to exec _globals = {"__version__": ""} with open(version_file_path) as f: exec(f.read(), _globals) return _globals["__version__"] def get_tagged_version() -> Optional[Text]: """Return the version specified in a tagged git commit.""" return os.environ.get("TRAVIS_TAG") if __name__ == "__main__": if get_pyproject_version() != get_current_version(): print( f"Version in {pyproject_file_path} does not correspond " f"to the version in {version_file_path}! The version needs to be " f"set to the same value in both places." ) sys.exit(1) elif get_tagged_version() and get_tagged_version() != get_current_version(): print( f"Tagged version does not correspond to the version " f"in {version_file_path}!" ) sys.exit(1) elif get_tagged_version() and get_tagged_version() != get_pyproject_version(): print( f"Tagged version does not correspond to the version " f"in {pyproject_file_path}!" ) sys.exit(1) else: print("Versions look good!")
764
407
<gh_stars>100-1000 package com.alibaba.sreworks.clustermanage.server.params; import com.alibaba.fastjson.JSONObject; import com.alibaba.sreworks.domain.DO.Cluster; import lombok.Data; /** * @author jinghua.yjh */ @Data public class ClusterDeployClientParam { private JSONObject envMap; }
109
1,655
<filename>src/editor/ShapePainter.hpp #ifndef SHAPEPAINTER_HPP_ #define SHAPEPAINTER_HPP_ #include "AbstractPainter.hpp" #include "opengl/OpenGL.hpp" #include <vector> namespace Tungsten { class Mat4f; namespace GL { class VertexBuffer; class Shader; } class ShapePainter: public AbstractPainter { static CONSTEXPR uint32 MaxVertices = 1 << 16; static GL::VertexBuffer *_vbo; static GL::Shader *_defaultShader; static bool _initialized; static void initialize(); struct VboVertex { Vec3f pos; Vec4c color; }; DrawMode _mode; Vec4f _color; std::vector<VboVertex> _verts; GLint toGlMode(); void flush(); void addVertexRaw(Vec3f x); void addVertexRaw(Vec2f x); public: ShapePainter(DrawMode mode = MODE_LINES); ShapePainter(const Mat4f &proj, DrawMode mode = MODE_LINES); ~ShapePainter(); void labelShape(int /*id*/) final override { } void addVertex(Vec2f x) final override; void begin(DrawMode mode) final override; void drawRect(Vec2f pos, Vec2f size, bool filled = true, float width = 1.0f) final override; void drawRectStipple(Vec2f pos, Vec2f size, float period, float width = 1.0f) final override; void drawEllipseRect(Vec2f pos, Vec2f size, bool filled = true, float width = 1.0f) final override; void drawEllipse(Vec2f center, Vec2f radii, bool filled = true, float width = 1.0f) final override; void drawArc(Vec2f center, Vec2f radii, float aStart, float aEnd, bool filled = true, float width = 1.0f) final override; void drawLine(Vec2f x0, Vec2f x1, float width = 1.0f) final override; void drawLineStipple(Vec2f x0, Vec2f x1, float period, float width = 1.0f) final override; void drawLine(Vec3f x0, Vec3f x1); void setColor(const Vec3f &c) final override { _color = Vec4f(c.x(), c.y(), c.z(), 1.0f); } void setColor(const Vec4f &c) final override { _color = c; } void setAlpha(float a) final override { _color.w() = a; } }; } #endif /* SHAPEPAINTER_HPP_ */
865
640
<reponame>ahjelm/z88dk<filename>libsrc/target/zx-common/fcntl/esxdos/open.c #include <fcntl.h> /* Or is it unistd.h, who knows! */ int open(char *name, int flags, mode_t mode) __naked { #asm EXTERN asm_esxdos_f_open push ix ld hl,6 ;flags add hl,sp ld a,(hl) ; esxdos flags are +1 on C flags inc a and 3 inc hl ld c,0 ; esx_mode_open_exist bit 2,(hl) ;O_CREAT jr z,not_o_creat ld c,8 ; esx_mode_open_crea bit 1,(hl) ;O_TRUNC jr z,not_o_trunc ld c,$0c ; esx_mode_creat_trunc not_o_creat: not_o_trunc: or c ; add in open mode ld b,a inc hl ld e,(hl) ;filename inc hl ld d,(hl) ex de,hl ld a,$2a ;* call asm_esxdos_f_open jr c,end ld h,0 end: pop ix ret #endasm }
581
575
<filename>chrome/services/util_win/util_win_impl.cc // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/services/util_win/util_win_impl.h" #include <objbase.h> #include <shldisp.h> #include <wrl/client.h> #include <string> #include <utility> #include "base/bind.h" #include "base/files/file_enumerator.h" #include "base/files/file_path.h" #include "base/path_service.h" #include "base/scoped_native_library.h" #include "base/strings/utf_string_conversions.h" #include "base/win/scoped_bstr.h" #include "base/win/scoped_com_initializer.h" #include "base/win/scoped_variant.h" #include "base/win/shortcut.h" #include "base/win/win_util.h" #include "chrome/browser/win/conflicts/module_info_util.h" #include "chrome/installer/util/install_util.h" #include "chrome/services/util_win/av_products.h" #include "chrome/services/util_win/processor_metrics.h" #include "third_party/metrics_proto/system_profile.pb.h" #include "ui/shell_dialogs/execute_select_file_win.h" namespace { // This class checks if the current executable is pinned to the taskbar. It also // keeps track of the errors that occurs that prevents it from getting a result. class IsPinnedToTaskbarHelper { public: IsPinnedToTaskbarHelper() = default; // Returns true if the current executable is pinned to the taskbar. If // [check_verbs] is true we check that the unpin from taskbar verb exists for // the shortcut. bool GetResult(bool check_verbs); bool error_occured() { return error_occured_; } private: // Returns the shell resource string identified by |resource_id|, or an empty // string on error. std::wstring LoadShellResourceString(uint32_t resource_id); // Returns true if the "Unpin from taskbar" verb is available for |shortcut|, // which means that the shortcut is pinned to the taskbar. bool ShortcutHasUnpinToTaskbarVerb(const base::FilePath& shortcut); // Returns true if the target parameter of the |shortcut| evaluates to // |program_compare|. bool IsShortcutForProgram(const base::FilePath& shortcut, const InstallUtil::ProgramCompare& program_compare); // Returns true if one of the shortcut inside the given |directory| evaluates // to |program_compare| and is pinned to the taskbar. If [check_verbs] is // true we check that the unpin from taskbar verb exists for the shortcut. bool DirectoryContainsPinnedShortcutForProgram( const base::FilePath& directory, const InstallUtil::ProgramCompare& program_compare, bool check_verbs); bool error_occured_ = false; base::win::ScopedCOMInitializer scoped_com_initializer_; DISALLOW_COPY_AND_ASSIGN(IsPinnedToTaskbarHelper); }; std::wstring IsPinnedToTaskbarHelper::LoadShellResourceString( uint32_t resource_id) { base::ScopedNativeLibrary scoped_native_library(::LoadLibraryEx( FILE_PATH_LITERAL("shell32.dll"), nullptr, LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE)); if (!scoped_native_library.is_valid()) return std::wstring(); const wchar_t* resource_ptr = nullptr; int length = ::LoadStringW(scoped_native_library.get(), resource_id, reinterpret_cast<wchar_t*>(&resource_ptr), 0); if (!length || !resource_ptr) return std::wstring(); return std::wstring(resource_ptr, length); } bool IsPinnedToTaskbarHelper::ShortcutHasUnpinToTaskbarVerb( const base::FilePath& shortcut) { // Found inside shell32.dll's resources. constexpr uint32_t kUnpinFromTaskbarID = 5387; std::wstring verb_name(LoadShellResourceString(kUnpinFromTaskbarID)); if (verb_name.empty()) { error_occured_ = true; return false; } Microsoft::WRL::ComPtr<IShellDispatch> shell_dispatch; HRESULT hresult = ::CoCreateInstance(CLSID_Shell, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shell_dispatch)); if (FAILED(hresult) || !shell_dispatch) { error_occured_ = true; return false; } Microsoft::WRL::ComPtr<Folder> folder; hresult = shell_dispatch->NameSpace( base::win::ScopedVariant(shortcut.DirName().value().c_str()), &folder); if (FAILED(hresult) || !folder) { error_occured_ = true; return false; } Microsoft::WRL::ComPtr<FolderItem> item; hresult = folder->ParseName( base::win::ScopedBstr(shortcut.BaseName().value()).Get(), &item); if (FAILED(hresult) || !item) { error_occured_ = true; return false; } Microsoft::WRL::ComPtr<FolderItemVerbs> verbs; hresult = item->Verbs(&verbs); if (FAILED(hresult) || !verbs) { error_occured_ = true; return false; } long verb_count = 0; hresult = verbs->get_Count(&verb_count); if (FAILED(hresult)) { error_occured_ = true; return false; } long error_count = 0; for (long i = 0; i < verb_count; ++i) { Microsoft::WRL::ComPtr<FolderItemVerb> verb; hresult = verbs->Item(base::win::ScopedVariant(i, VT_I4), &verb); if (FAILED(hresult) || !verb) { error_count++; continue; } base::win::ScopedBstr name; hresult = verb->get_Name(name.Receive()); if (FAILED(hresult)) { error_count++; continue; } if (base::WStringPiece(name.Get(), name.Length()) == verb_name) return true; } if (error_count == verb_count) error_occured_ = true; return false; } bool IsPinnedToTaskbarHelper::IsShortcutForProgram( const base::FilePath& shortcut, const InstallUtil::ProgramCompare& program_compare) { base::win::ShortcutProperties shortcut_properties; if (!ResolveShortcutProperties( shortcut, base::win::ShortcutProperties::PROPERTIES_TARGET, &shortcut_properties)) { return false; } return program_compare.EvaluatePath(shortcut_properties.target); } bool IsPinnedToTaskbarHelper::DirectoryContainsPinnedShortcutForProgram( const base::FilePath& directory, const InstallUtil::ProgramCompare& program_compare, bool check_verbs) { base::FileEnumerator shortcut_enum(directory, false, base::FileEnumerator::FILES); for (base::FilePath shortcut = shortcut_enum.Next(); !shortcut.empty(); shortcut = shortcut_enum.Next()) { if (IsShortcutForProgram(shortcut, program_compare)) { if (check_verbs) { if (ShortcutHasUnpinToTaskbarVerb(shortcut)) { return true; } } else { return true; } } } return false; } bool IsPinnedToTaskbarHelper::GetResult(bool check_verbs) { base::FilePath current_exe; if (!base::PathService::Get(base::FILE_EXE, &current_exe)) return false; InstallUtil::ProgramCompare current_exe_compare(current_exe); // Look into the "Quick Launch\User Pinned\TaskBar" folder. base::FilePath taskbar_pins_dir; if (base::PathService::Get(base::DIR_TASKBAR_PINS, &taskbar_pins_dir) && DirectoryContainsPinnedShortcutForProgram( taskbar_pins_dir, current_exe_compare, check_verbs)) { return true; } // Check all folders in ImplicitAppShortcuts. base::FilePath implicit_app_shortcuts_dir; if (!base::PathService::Get(base::DIR_IMPLICIT_APP_SHORTCUTS, &implicit_app_shortcuts_dir)) { return false; } base::FileEnumerator directory_enum(implicit_app_shortcuts_dir, false, base::FileEnumerator::DIRECTORIES); for (base::FilePath directory = directory_enum.Next(); !directory.empty(); directory = directory_enum.Next()) { current_exe.value(); if (DirectoryContainsPinnedShortcutForProgram( directory, current_exe_compare, check_verbs)) { return true; } } return false; } } // namespace UtilWinImpl::UtilWinImpl(mojo::PendingReceiver<chrome::mojom::UtilWin> receiver) : receiver_(this, std::move(receiver)) {} UtilWinImpl::~UtilWinImpl() = default; void UtilWinImpl::IsPinnedToTaskbar(IsPinnedToTaskbarCallback callback) { IsPinnedToTaskbarHelper helper; bool is_pinned_to_taskbar = helper.GetResult(false); bool is_pinned_to_taskbar_verb_check = helper.GetResult(true); std::move(callback).Run(!helper.error_occured(), is_pinned_to_taskbar, is_pinned_to_taskbar_verb_check); } void UtilWinImpl::CallExecuteSelectFile( ui::SelectFileDialog::Type type, uint32_t owner, const std::u16string& title, const base::FilePath& default_path, const std::vector<ui::FileFilterSpec>& filter, int32_t file_type_index, const std::u16string& default_extension, CallExecuteSelectFileCallback callback) { base::win::ScopedCOMInitializer scoped_com_initializer; base::win::EnableHighDPISupport(); ui::ExecuteSelectFile( type, title, default_path, filter, file_type_index, base::UTF16ToWide(default_extension), reinterpret_cast<HWND>(base::win::Uint32ToHandle(owner)), base::BindOnce(std::move(callback))); } void UtilWinImpl::InspectModule(const base::FilePath& module_path, InspectModuleCallback callback) { std::move(callback).Run(::InspectModule(module_path)); } void UtilWinImpl::GetAntiVirusProducts(bool report_full_names, GetAntiVirusProductsCallback callback) { base::win::ScopedCOMInitializer scoped_com_initializer; std::move(callback).Run(::GetAntiVirusProducts(report_full_names)); } void UtilWinImpl::RecordProcessorMetrics( RecordProcessorMetricsCallback callback) { // TODO(sebmarchand): Check if we should move the ScopedCOMInitializer to the // UtilWinImpl class. base::win::ScopedCOMInitializer scoped_com_initializer; ::RecordProcessorMetrics(); std::move(callback).Run(); }
3,696
4,339
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.sqltests; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.junit.Test; /** * Includes all base sql test plus tests that make sense in replicated mode with a non-default number of partitions. */ public class ReplicatedSqlCustomPartitionsTest extends ReplicatedSqlTest { /** Test partitions count. */ private static final int NUM_OF_PARTITIONS = 509; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { return super.getConfiguration(igniteInstanceName) .setCacheConfiguration( new CacheConfiguration("partitioned" + NUM_OF_PARTITIONS + "*") .setAffinity(new RendezvousAffinityFunction(false, NUM_OF_PARTITIONS)), new CacheConfiguration("replicated" + NUM_OF_PARTITIONS + "*") .setCacheMode(CacheMode.REPLICATED) .setAffinity(new RendezvousAffinityFunction(false, NUM_OF_PARTITIONS)) ); } /** * Create and fill common tables in replicated mode. * Also create additional department table in partitioned mode to * test mixed partitioned/replicated scenarios. */ @Override protected void setupData() { createTables("template=replicated" + NUM_OF_PARTITIONS); fillCommonData(); createDepartmentTable(DEP_PART_TAB, "template=partitioned" + NUM_OF_PARTITIONS); fillDepartmentTable(DEP_PART_TAB); } /** * Check LEFT JOIN with collocated data of replicated and partitioned tables. * This test relies on having the same number of partitions in replicated and partitioned caches */ @Test public void testLeftJoinReplicatedPartitioned() { checkLeftJoinEmployeeDepartment(DEP_PART_TAB); } /** * Check RIGHT JOIN with collocated data of partitioned and replicated tables. */ @Test public void testRightJoinPartitionedReplicated() { checkRightJoinDepartmentEmployee(DEP_PART_TAB); } }
990
1,388
// // Copyright 2015 <NAME> // // 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. // // TLB flags #define TLB_PRESENT 1 #define TLB_WRITABLE (1 << 1) #define TLB_EXECUTABLE (1 << 2) #define TLB_SUPERVISOR (1 << 3) #define TLB_GLOBAL (1 << 4) // Control register indices #define CR_CURRENT_THREAD 0 #define CR_TRAP_HANDLER 1 #define CR_TRAP_PC 2 #define CR_TRAP_CAUSE 3 #define CR_FLAGS 4 #define CR_TRAP_ADDRESS 5 #define CR_CYCLE_COUNT 6 #define CR_TLB_MISS_HANDLER 7 #define CR_SAVED_FLAGS 8 #define CR_CURRENT_ASID 9 #define CR_SCRATCHPAD0 11 #define CR_SCRATCHPAD1 12 #define CR_SUBCYCLE 13 #define CR_INTERRUPT_ENABLE 14 #define CR_INTERRUPT_ACK 15 #define CR_INTERRUPT_PENDING 16 #define CR_INTERRUPT_TRIGGER 17 #define CR_JTAG_DATA 18 #define CR_SYSCALL_INDEX 19 #define CR_SUSPEND_THREAD 20 #define CR_RESUME_THREAD 21 #define CR_PERF_EVENT_SELECT0 22 #define CR_PERF_EVENT_SELECT1 23 #define CR_PERF_EVENT_COUNT0_L 24 #define CR_PERF_EVENT_COUNT0_H 25 #define CR_PERF_EVENT_COUNT1_L 26 #define CR_PERF_EVENT_COUNT1_H 27 // Trap types #define TT_RESET 0 #define TT_ILLEGAL_INSTRUCTION 1 #define TT_PRIVILEGED_OP 2 #define TT_INTERRUPT 3 #define TT_SYSCALL 4 #define TT_UNALIGNED_ACCESS 5 #define TT_PAGE_FAULT 6 #define TT_TLB_MISS 7 #define TT_ILLEGAL_STORE 8 #define TT_SUPERVISOR_ACCESS 9 #define TT_NOT_EXECUTABLE 10 #define TT_BREAKPOINT 11 #define TRAP_CAUSE_STORE 0x10 #define TRAP_CAUSE_DCACHE 0x20 // Flag register bits #define FLAG_INTERRUPT_EN (1 << 0) #define FLAG_MMU_EN (1 << 1) #define FLAG_SUPERVISOR_EN (1 << 2) // Device registers #define REG_HOST_INTERRUPT 0xffff0018 #define REG_SERIAL_WRITE 0xffff0048 #define REG_TIMER_COUNT 0xffff0240 .macro start_all_threads li s0, 0xffffffff setcr s0, CR_RESUME_THREAD .endm .macro halt_current_thread getcr s0, CR_CURRENT_THREAD move s1, 1 shl s1, s1, s0 setcr s1, CR_SUSPEND_THREAD 1: b 1b .endm .macro halt_all_threads li s0, 0xffffffff setcr s0, CR_SUSPEND_THREAD 1: b 1b .endm // Print a null terminated string pointer to by s0 to the serial // port. Clobbers s0-s3. .align 4, 0xff .macro print_string li s1, 0xffff0040 // Load address of serial registers 1: load_u8 s2, (s0) // Read a character bz s2, 3f // If delimiter, exit 2: load_32 s3, (s1) // Read STATUS and s3, s3, 1 // Check write available bit bz s3, 2b // If this is clear, busy wait store_32 s2, 8(s1) // Write space available, send char add_i s0, s0, 1 // Increment pointer b 1b // Loop for next char 3: .endm // Print a character in s0. Clobbers s1, s2 .macro print_char li s1, 0xffff0040 // Load address of serial registers 1: load_32 s2, (s1) // Read STATUS and s2, s2, 1 // Check write available bit bz s2, 1b // If this is clear, busy wait store_32 s0, 8(s1) // Write space available, send char .endm // If register is not equal to testval, print failure message. // Otherwise continue. Clobbers s25 .macro assert_reg reg, testval li s25, \testval cmpeq_i s25, s25, \reg bnz s25, 1f call fail_test 1: .endm .macro flush_pipeline b 1f 1: .endm .macro should_not_get_here call fail_test .endm // Print failure message and halt. It will print \x04 (^D) at the end, which // will cause the serial_loader console mode to exit on FPGA, triggering the // end of the test. .align 4, 0xff fail_test: lea s0, failstr print_string halt_all_threads failstr: .ascii "FAIL" .byte 4, 0 // Print success message and halt .align 4, 0xff pass_test: lea s0, passstr print_string halt_all_threads passstr: .ascii "PASS" .byte 4, 0 .align 4, 0xff
2,326
348
<filename>docs/data/t2/064/64389.json<gh_stars>100-1000 {"nom":"Monassut-Audiracq","dpt":"Pyrénées-Atlantiques","inscrits":290,"abs":48,"votants":242,"blancs":24,"nuls":5,"exp":213,"res":[{"panneau":"1","voix":134},{"panneau":"2","voix":79}]}
105
335
"""Tests for structures.""" import unittest from grow.common import structures from operator import itemgetter class AttributeDictTestCase(unittest.TestCase): """Test the attribute dict structure.""" def test_attributes(self): """Keys are accessible as attributes.""" obj = structures.AttributeDict({ 'key': 'value', }) self.assertEqual('value', obj['key']) self.assertEqual('value', obj.key) class DeepReferenceDictTestCase(unittest.TestCase): """Test the deep reference dict structure.""" def test_deep_reference(self): """Delimited keys are accessible.""" obj = structures.DeepReferenceDict({ 'key': { 'sub_key': { 'value': 'foo', } }, }) self.assertEqual('foo', obj['key']['sub_key']['value']) self.assertEqual('foo', obj['key.sub_key.value']) def test_deep_reference_error(self): """Missing keys raise error.""" obj = structures.DeepReferenceDict({ 'key': {}, }) with self.assertRaises(KeyError): _ = obj['key.sub_key.value'] class SortedCollectionTestCase(unittest.TestCase): """Test the sorted collection structure.""" def setUp(self): self.key = itemgetter(2) self.coll = structures.SortedCollection(key=self.key) for record in [ ('roger', 'young', 30), ('angela', 'jones', 28), ('bill', 'smith', 22), ('david', 'thomas', 32)]: self.coll.insert(record) def test_clear(self): """Clears the collection.""" self.assertEqual(4, len(self.coll)) self.coll.clear() self.assertEqual(0, len(self.coll)) def test_contains(self): """Contains matches.""" self.assertTrue(('roger', 'young', 30) in self.coll) self.assertFalse(('bob', 'young', 30) in self.coll) def test_copy(self): """Copies the collection.""" coll_copy = self.coll.copy() self.assertEqual(4, len(self.coll)) self.assertEqual(4, len(coll_copy)) self.coll.insert(('roger', 'young', 30)) self.assertEqual(5, len(self.coll)) self.assertEqual(4, len(coll_copy)) def test_count(self): """Counts matches.""" self.assertEqual(1, self.coll.count(('roger', 'young', 30))) self.coll.insert(('roger', 'young', 30)) self.assertEqual(2, self.coll.count(('roger', 'young', 30))) def test_find(self): """Find first match.""" self.assertEqual(('angela', 'jones', 28), self.coll.find(28)) with self.assertRaises(ValueError): self.coll.find(39) def test_get_item(self): """Greater than equal.""" self.assertEqual(('bill', 'smith', 22), self.coll[0]) def test_ge(self): """Greater than equal.""" self.assertEqual(('angela', 'jones', 28), self.coll.find_ge(28)) with self.assertRaises(ValueError): self.coll.find_ge(40) def test_gt(self): """Greater than.""" self.assertEqual(('roger', 'young', 30), self.coll.find_gt(28)) with self.assertRaises(ValueError): self.coll.find_gt(40) def test_index(self): """Index from item.""" match = self.coll.find_gt(28) self.assertEqual(2, self.coll.index(match)) def test_insert_right(self): """Index from item.""" self.assertEqual(1, self.coll.count(('roger', 'young', 30))) self.coll.insert_right(('roger', 'young', 30)) self.assertEqual(2, self.coll.count(('roger', 'young', 30))) def test_key(self): """Index from item.""" self.assertEqual(self.key, self.coll.key) self.coll.key = itemgetter(0) # now sort by first name self.assertEqual([('angela', 'jones', 28), ('bill', 'smith', 22), ('david', 'thomas', 32), ('roger', 'young', 30)], list(self.coll)) def test_le(self): """Less than equal.""" self.assertEqual(('angela', 'jones', 28), self.coll.find_le(28)) with self.assertRaises(ValueError): self.coll.find_le(10) def test_lt(self): """Less than.""" self.assertEqual(('bill', 'smith', 22), self.coll.find_lt(28)) with self.assertRaises(ValueError): self.coll.find_lt(10) def test_remove(self): """Removes matches.""" item = ('roger', 'young', 30) self.assertTrue(item in self.coll) self.coll.remove(item) self.assertFalse(item in self.coll) def test_repr(self): """Output of repr.""" actual = repr(self.coll) self.assertIn('SortedCollection(', actual) self.assertIn("('bill', 'smith', 22)", actual) self.assertIn("('angela', 'jones', 28)", actual) self.assertIn("('roger', 'young', 30)", actual) self.assertIn("('david', 'thomas', 32)", actual) def test_sorting(self): """Collection is sorted.""" self.assertEqual([('bill', 'smith', 22), ('angela', 'jones', 28), ('roger', 'young', 30), ('david', 'thomas', 32)], list(self.coll)) def test_sorting_default(self): """Collection is sorted using a default for the value.""" self.key = itemgetter(2) self.coll = structures.SortedCollection(key=self.key, default=100) for record in [ ('roger', 'young', None), ('angela', 'jones', 28), ('bill', 'smith', 22), ('david', 'thomas', 32)]: self.coll.insert(record) self.assertEqual( [ ('bill', 'smith', 22), ('angela', 'jones', 28), ('david', 'thomas', 32), ('roger', 'young', None), ], list(self.coll))
2,884
412
<reponame>jimgrundy/cbmc /*******************************************************************\ Module: Symbolic Execution Author: <NAME>, <EMAIL> \*******************************************************************/ /// \file /// Symbolic Execution #include "goto_symex.h" #include <util/arith_tools.h> #include <util/byte_operators.h> #include <util/c_types.h> #include <util/pointer_offset_size.h> #include <util/std_code.h> void goto_symext::havoc_rec( statet &state, const guardt &guard, const exprt &dest) { if(dest.id()==ID_symbol) { exprt lhs; if(guard.is_true()) lhs=dest; else lhs=if_exprt( guard.as_expr(), dest, exprt(ID_null_object, dest.type())); auto rhs = side_effect_expr_nondett(dest.type(), state.source.pc->source_location()); symex_assign(state, lhs, rhs); } else if(dest.id()==ID_byte_extract_little_endian || dest.id()==ID_byte_extract_big_endian) { havoc_rec(state, guard, to_byte_extract_expr(dest).op()); } else if(dest.id()==ID_if) { const if_exprt &if_expr=to_if_expr(dest); guardt guard_t=state.guard; guard_t.add(if_expr.cond()); havoc_rec(state, guard_t, if_expr.true_case()); guardt guard_f=state.guard; guard_f.add(not_exprt(if_expr.cond())); havoc_rec(state, guard_f, if_expr.false_case()); } else if(dest.id()==ID_typecast) { havoc_rec(state, guard, to_typecast_expr(dest).op()); } else if(dest.id()==ID_index) { havoc_rec(state, guard, to_index_expr(dest).array()); } else if(dest.id()==ID_member) { havoc_rec(state, guard, to_member_expr(dest).struct_op()); } else { // consider printing a warning } } void goto_symext::symex_other( statet &state) { const goto_programt::instructiont &instruction=*state.source.pc; const codet &code = instruction.get_other(); const irep_idt &statement=code.get_statement(); if(statement==ID_expression) { // ignore } else if(statement==ID_cpp_delete || statement=="cpp_delete[]") { const codet clean_code = to_code(clean_expr(code, state, false)); symex_cpp_delete(state, clean_code); } else if(statement==ID_printf) { const codet clean_code = to_code(clean_expr(code, state, false)); symex_printf(state, clean_code); } else if(can_cast_expr<code_inputt>(code)) { const codet clean_code = to_code(clean_expr(code, state, false)); symex_input(state, clean_code); } else if(can_cast_expr<code_outputt>(code)) { const codet clean_code = to_code(clean_expr(code, state, false)); symex_output(state, clean_code); } else if(statement==ID_decl) { UNREACHABLE; // see symex_decl.cpp } else if(statement==ID_nondet) { // like skip } else if(statement==ID_asm) { // we ignore this for now } else if(statement==ID_array_copy || statement==ID_array_replace) { // array_copy and array_replace take two pointers (to arrays); we need to: // 1. remove any dereference expressions (via clean_expr) // 2. find the actual array objects/candidates for objects (via // process_array_expr) // 3. build an assignment where the type on lhs and rhs is: // - array_copy: the type of the first array (even if the second is smaller) // - array_replace: the type of the second array (even if it is smaller) DATA_INVARIANT( code.operands().size() == 2, "expected array_copy/array_replace statement to have two operands"); // we need to add dereferencing for both operands exprt dest_array = clean_expr(code.op0(), state, false); exprt src_array = clean_expr(code.op1(), state, false); // obtain the actual arrays process_array_expr(state, dest_array); process_array_expr(state, src_array); // check for size (or type) mismatch and adjust if(dest_array.type() != src_array.type()) { if(statement==ID_array_copy) { src_array = make_byte_extract( src_array, from_integer(0, index_type()), dest_array.type()); do_simplify(src_array); } else { // ID_array_replace dest_array = make_byte_extract( dest_array, from_integer(0, index_type()), src_array.type()); do_simplify(dest_array); } } symex_assign(state, dest_array, src_array); } else if(statement==ID_array_set) { // array_set takes a pointer (to an array) and a value that each element // should be set to; we need to: // 1. remove any dereference expressions (via clean_expr) // 2. find the actual array object/candidates for objects (via // process_array_expr) // 3. use the type of the resulting array to construct an array_of // expression DATA_INVARIANT( code.operands().size() == 2, "expected array_set statement to have two operands"); // we need to add dereferencing for the first operand exprt array_expr = clean_expr(code.op0(), state, false); // obtain the actual array(s) process_array_expr(state, array_expr); // prepare to build the array_of exprt value = clean_expr(code.op1(), state, false); // we might have a memset-style update of a non-array type - convert to a // byte array if(array_expr.type().id() != ID_array) { auto array_size = size_of_expr(array_expr.type(), ns); CHECK_RETURN(array_size.has_value()); do_simplify(array_size.value()); array_expr = make_byte_extract( array_expr, from_integer(0, index_type()), array_typet(char_type(), array_size.value())); } const array_typet &array_type = to_array_type(array_expr.type()); if(array_type.subtype() != value.type()) value = typecast_exprt(value, array_type.subtype()); symex_assign(state, array_expr, array_of_exprt(value, array_type)); } else if(statement==ID_array_equal) { // array_equal takes two pointers (to arrays) and the symbol that the result // should get assigned to; we need to: // 1. remove any dereference expressions (via clean_expr) // 2. find the actual array objects/candidates for objects (via // process_array_expr) // 3. build an assignment where the lhs is the previous third argument, and // the right-hand side is an equality over the arrays, if their types match; // if the types don't match the result trivially is false DATA_INVARIANT( code.operands().size() == 3, "expected array_equal statement to have three operands"); // we need to add dereferencing for the first two exprt array1 = clean_expr(code.op0(), state, false); exprt array2 = clean_expr(code.op1(), state, false); // obtain the actual arrays process_array_expr(state, array1); process_array_expr(state, array2); exprt rhs = equal_exprt(array1, array2); // check for size (or type) mismatch if(array1.type() != array2.type()) rhs = false_exprt(); symex_assign(state, code.op2(), rhs); } else if(statement==ID_user_specified_predicate || statement==ID_user_specified_parameter_predicates || statement==ID_user_specified_return_predicates) { // like skip } else if(statement==ID_fence) { target.memory_barrier(state.guard.as_expr(), state.source); } else if(statement==ID_havoc_object) { DATA_INVARIANT( code.operands().size() == 1, "expected havoc_object statement to have one operand"); exprt object = clean_expr(code.op0(), state, false); process_array_expr(state, object); havoc_rec(state, guardt(true_exprt(), guard_manager), object); } else UNREACHABLE; }
2,970
406
<filename>src/test/java/org/broad/igv/feature/tribble/TribbleIndexTest.java<gh_stars>100-1000 /* * The MIT License (MIT) * * Copyright (c) 2007-2015 Broad Institute * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.broad.igv.feature.tribble; import org.broad.igv.AbstractHeadlessTest; import org.broad.igv.feature.BasicFeature; import org.broad.igv.tools.IgvTools; import org.broad.igv.util.TestUtils; import htsjdk.tribble.AbstractFeatureReader; import htsjdk.variant.vcf.VCFCodec; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertEquals; /** * @author jrobinso * @date Aug 9, 2010 */ public class TribbleIndexTest extends AbstractHeadlessTest { /** * chr2 1 200000000 LONG_FEATURE * ... * chr2 179098961 179380395 Hs.134602 * chr2 179209546 179287210 Hs.620337 * chr2 179266309 179266748 Hs.609465 * chr2 179296428 179300012 Hs.623987 * chr2 179302952 179303488 Hs.594545 */ @Test public void testLinearIndex() throws Exception { String bedFile = TestUtils.DATA_DIR + "bed/Unigene.sample.bed"; String chr = "chr2"; int start = 179266309 - 1; int end = 179303488 + 1; int expectedCount = 6; Set<String> expectedNames = new HashSet<String>(Arrays.asList("Hs.134602", "Hs.620337", "Hs.609465", "Hs.623987", "Hs.594545", "LONG_FEATURE")); // Interval index TestUtils.createIndex(bedFile, IgvTools.LINEAR_INDEX, 500); AbstractFeatureReader bfr = AbstractFeatureReader.getFeatureReader(bedFile, new IGVBEDCodec()); Iterator<BasicFeature> iter = bfr.query(chr, start, end); int countInterval = 0; while (iter.hasNext()) { BasicFeature feature = iter.next(); Assert.assertTrue(feature.getEnd() >= start && feature.getStart() <= end); Assert.assertTrue(expectedNames.contains(feature.getName())); countInterval++; } assertEquals(expectedCount, countInterval); } @Test /** * Test interval tree index * chr2 179098961 179380395 Hs.134602 * chr2 179209546 179287210 Hs.620337 * chr2 179266309 179266748 Hs.609465 * chr2 179296428 179300012 Hs.623987 * chr2 179302952 179303488 Hs.594545 * */ public void testIntervalTree() throws Exception { //chr2:179,222,066-179,262,059<- CONTAINS TTN String bedFile = TestUtils.DATA_DIR + "bed/Unigene.sample.bed"; String chr = "chr2"; int start = 179266309 - 1; int end = 179303488 + 1; int expectedCount = 6; Set<String> expectedNames = new HashSet<String>(Arrays.asList("Hs.134602", "Hs.620337", "Hs.609465", "Hs.623987", "Hs.594545", "LONG_FEATURE")); // Interval index TestUtils.createIndex(bedFile, IgvTools.INTERVAL_INDEX, 1); AbstractFeatureReader bfr = AbstractFeatureReader.getFeatureReader(bedFile, new IGVBEDCodec()); Iterator<BasicFeature> iter = bfr.query(chr, start, end); int countInterval = 0; while (iter.hasNext()) { BasicFeature feature = iter.next(); Assert.assertTrue(feature.getEnd() >= start && feature.getStart() <= end); Assert.assertTrue(expectedNames.contains(feature.getName())); countInterval++; } assertEquals(expectedCount, countInterval); } @Test public void testReadSingleVCF() throws Exception { String file = TestUtils.DATA_DIR + "vcf/indel_variants_onerow.vcf"; String chr = "chr9"; // Linear index TestUtils.createIndex(file); // First test query AbstractFeatureReader bfr = AbstractFeatureReader.getFeatureReader(file, new VCFCodec()); Iterator<htsjdk.variant.variantcontext.VariantContext> iter = bfr.query(chr, 5073767 - 5, 5073767 + 5); int count = 0; while (iter.hasNext()) { htsjdk.variant.variantcontext.VariantContext feat = iter.next(); assertEquals("chr9", feat.getChr()); assertEquals(feat.getStart(), 5073767); assertTrue(feat.hasAttribute("MapQs")); count++; } assertEquals(1, count); // Test non-indexed access (iterator) iter = bfr.iterator(); count = 0; while (iter.hasNext()) { htsjdk.variant.variantcontext.VariantContext feat = iter.next(); assertEquals("chr9", feat.getChr()); assertEquals(feat.getStart(), 5073767); assertTrue(feat.hasAttribute("MapQs")); count++; } assertEquals(1, count); //Do similar as above, but have a different test file file = TestUtils.DATA_DIR + "vcf/outputPileup.flt1.vcf"; chr = "1"; // Linear index TestUtils.createIndex(file); bfr = AbstractFeatureReader.getFeatureReader(file, new VCFCodec()); iter = bfr.query(chr, 984163 - 5, 984163 + 5); count = 0; while (iter.hasNext()) { htsjdk.variant.variantcontext.VariantContext feat = iter.next(); assertEquals(chr, feat.getChr()); if (count == 0) { assertEquals(984163, feat.getStart()); } count++; } assertEquals(1, count); } }
2,782
342
/* * Copyright 2008,2016 BitMover, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "resource.h" #include "system.h" #include "bk_shellx_version.h" #include <atlhost.h> class CVersionDialog: public CAxDialogImpl<CVersionDialog> { public: enum {IDD = IDD_VERSIONDIALOG}; CVersionDialog() {} ~CVersionDialog() {} BEGIN_MSG_MAP(CVersionDialog) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) MESSAGE_HANDLER(WM_CLOSE, OnCloseDialog) COMMAND_HANDLER(IDOK, BN_CLICKED, OnClickedOK) CHAIN_MSG_MAP(CAxDialogImpl<CVersionDialog>) END_MSG_MAP() LRESULT OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { char *out1, *out2, *out3; CAxDialogImpl<CVersionDialog>::OnInitDialog(uMsg, wParam, lParam, bHandled); bHandled = TRUE; out1 = cmd2buf(bkexe, "version"); out2 = aprintf("%s\n\n%s", BK_SHELLX_VERSION_STR, out1); out3 = dosify(out2); SetDlgItemText(IDC_BK_VERSION, _T(out3)); free(out1); free(out2); free(out3); return (1); } LRESULT OnCloseDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { EndDialog(IDD_VERSIONDIALOG); return (0); } LRESULT OnClickedOK(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) { EndDialog(wID); return (0); } };
711
892
{ "schema_version": "1.2.0", "id": "GHSA-c8jg-8x69-pcr4", "modified": "2022-05-13T01:01:26Z", "published": "2022-05-13T01:01:26Z", "aliases": [ "CVE-2017-2791" ], "details": "JustSystems Ichitaro 2016 Trial contains a vulnerability that exists when trying to open a specially crafted PowerPoint file. Due to the application incorrectly handling the error case for a function's result, the application will use this result in a pointer calculation for reading file data into. Due to this, the application will read data from the file into an invalid address thus corrupting memory. Under the right conditions, this can lead to code execution under the context of the application.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2017-2791" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/96440" }, { "type": "WEB", "url": "http://www.talosintelligence.com/reports/TALOS-2016-0199/" } ], "database_specific": { "cwe_ids": [ "CWE-119" ], "severity": "HIGH", "github_reviewed": false } }
525
7,407
<reponame>xuyanbo03/lab<filename>deepmind/level_generation/text_level/translate_text_level_test.cc // Copyright (C) 2016 Google Inc. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // //////////////////////////////////////////////////////////////////////////////// #include "deepmind/level_generation/text_level/translate_text_level.h" #include <fstream> #include <iterator> #include <string> #include "deepmind/support/logging.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/flags/flag.h" #include "deepmind/level_generation/text_level/text_level_settings.h" #include "deepmind/support/test_srcdir.h" ABSL_FLAG( std::string, map_outfile, "", "If this argument is provided, write the .map output of the test map to " "the specified file. Useful for testing other parts of the pipeline."); namespace deepmind { namespace lab { namespace { using ::testing::AnyOf; using ::testing::Eq; constexpr char kEntities[] = " ******\n" " *** *********\n" " * x I *\n" " ** P ***H****H**\n" " * * * *\n" " ***************\n"; constexpr char kVariations[] = ".........\n" "....AAAAAAAAAAAAAA\n" ".\n" ".CCCCCCCCCCCCCCCCCCCCCCCCCC\n" ".CCCCCCCCCCCCCCCCCCCCCCC\n" "$%^&*()\n" ".............\n"; bool NoOp(std::size_t, std::size_t, char, const MapSnippetEmitter&, std::vector<std::string>*) { return false; } TEST(TranslateTextLevel, Simple) { std::mt19937_64 rng(123); TextLevelSettings settings; std::string actual = TranslateTextLevel(kEntities, kVariations, &rng, NoOp, &settings); ASSERT_THAT(actual, testing::HasSubstr("\"classname\" \"info_player_start\"")); ASSERT_THAT(actual, testing::HasSubstr("\"classname\" \"worldspawn\"")); ASSERT_THAT(actual, testing::HasSubstr("\"classname\" \"light\"")); ASSERT_THAT(actual, testing::HasSubstr("\"classname\" \"func_door\"")); ASSERT_THAT(actual, testing::HasSubstr("\"classname\" \"trigger_multiple\"")); if (FLAGS_map_outfile.IsSpecifiedOnCommandLine()) { std::string filename = absl::GetFlag(FLAGS_map_outfile); if (std::ofstream(filename) << actual) { LOG(INFO) << "Test map written to '" << filename << "'."; } else { LOG(ERROR) << "Failed to write map file to '" << filename << "'."; } } } // The utility of this test is somewhat limited: The output depends on the // specific implementation of various random algorithms, and thus it is // really only reliable on a fixed platform. When moving platforms, you will // most likely need to generate a new golden output file. TEST(TranslateTextLevel, CompareWithGolden) { std::mt19937_64 rng(123); TextLevelSettings settings; std::string actual = TranslateTextLevel(kEntities, kVariations, &rng, NoOp, &settings); std::ifstream golden_libcxx( TestSrcDir() + "/deepmind/level_generation/text_level/" "translate_text_level_test_libc++.golden_output"); QCHECK(golden_libcxx) << "Failed to open golden libc data file."; std::ifstream golden_libstdcxx( TestSrcDir() + "/deepmind/level_generation/text_level/" "translate_text_level_test_libstdc++.golden_output"); QCHECK(golden_libstdcxx) << "Failed to open golden libstdc data file."; std::string expected_libc(std::istreambuf_iterator<char>(golden_libcxx), {}); std::string expected_libstdc(std::istreambuf_iterator<char>(golden_libstdcxx), {}); EXPECT_THAT(actual, AnyOf(Eq(expected_libc), Eq(expected_libstdc))); } TEST(TranslateTextLevel, Custom) { auto callback = [](std::size_t i, std::size_t j, char ent, const MapSnippetEmitter& em, std::vector<std::string>* out) { if (ent != 'x') return false; out->push_back( em.AddEntity(i, j, 0, "XyzzyEntity", {{"a", "1"}, {"b", "2"}})); return true; }; std::mt19937_64 rng(123); TextLevelSettings settings; std::string actual = TranslateTextLevel( kEntities, kVariations, &rng, callback, &settings); EXPECT_THAT(actual, testing::HasSubstr( "{\n" " \"classname\" \"XyzzyEntity\"\n" " \"a\" \"1\"\n" " \"b\" \"2\"\n" " \"origin\" \"650 350 30\"\n" "}")); } TEST(TranslateTextLevel, SkyBox) { std::mt19937_64 rng(123); TextLevelSettings exporter_settings; exporter_settings.skybox_texture_name = "map/lab_games/sky/lg_sky_01"; std::string actual = TranslateTextLevel(kEntities, kVariations, &rng, NoOp, &exporter_settings); // Test skybox brushes EXPECT_THAT(actual, testing::HasSubstr( " {\n" " ( -626 0 0 ) ( -626 32 0 ) ( -626 0 32 ) " "map/lab_games/sky/lg_sky_01_up 378 0 0 -0.375 0.03125 0 0 0\n" " ( -242 0 0 ) ( -242 0 32 ) ( -242 32 0 ) " "map/lab_games/sky/lg_sky_01_up 378 0 0 -0.375 0.03125 0 0 0\n" " ( 0 -626 0 ) ( 0 -626 32 ) ( 32 -626 0 ) " "map/lab_games/sky/lg_sky_01_up 378 0 0 -0.375 0.03125 0 0 0\n" " ( 0 -242 0 ) ( 32 -242 0 ) ( 0 -242 32 ) " "map/lab_games/sky/lg_sky_01_up 378 0 0 -0.375 0.03125 0 0 0\n" " ( 0 0 192 ) ( 32 0 192 ) ( 0 32 192 ) " "map/lab_games/sky/lg_sky_01_up 378 378 0 -0.375 0.375 0 0 0\n" " ( 0 0 224 ) ( 0 32 224 ) ( 32 0 224 ) " "map/lab_games/sky/lg_sky_01_up 378 378 0 -0.375 0.375 0 0 0\n" " }\n" " {\n" " ( -626 0 0 ) ( -626 32 0 ) ( -626 0 32 ) " "map/lab_games/sky/lg_sky_01_dn 378 0 0 -0.375 0.03125 0 0 0\n" " ( -242 0 0 ) ( -242 0 32 ) ( -242 32 0 ) " "map/lab_games/sky/lg_sky_01_dn 378 0 0 -0.375 0.03125 0 0 0\n" " ( 0 -626 0 ) ( 0 -626 32 ) ( 32 -626 0 ) " "map/lab_games/sky/lg_sky_01_dn 378 0 0 -0.375 0.03125 0 0 0\n" " ( 0 -242 0 ) ( 32 -242 0 ) ( 0 -242 32 ) " "map/lab_games/sky/lg_sky_01_dn 378 0 0 -0.375 0.03125 0 0 0\n" " ( 0 0 -224 ) ( 32 0 -224 ) ( 0 32 -224 ) " "map/lab_games/sky/lg_sky_01_dn 378 378 0 -0.375 0.375 0 0 0\n" " ( 0 0 -192 ) ( 0 32 -192 ) ( 32 0 -192 ) " "map/lab_games/sky/lg_sky_01_dn 378 378 0 -0.375 0.375 0 0 0\n" " }\n" " {\n" " ( -658 0 0 ) ( -658 32 0 ) ( -658 0 32 ) " "map/lab_games/sky/lg_sky_01_lf 378 512 0 -0.375 0.375 0 0 0\n" " ( -626 0 0 ) ( -626 0 32 ) ( -626 32 0 ) " "map/lab_games/sky/lg_sky_01_lf 378 512 0 -0.375 0.375 0 0 0\n" " ( 0 -626 0 ) ( 0 -626 32 ) ( 32 -626 0 ) " "map/lab_games/sky/lg_sky_01_lf 448 512 0 -0.03125 0.375 0 0 0\n" " ( 0 -242 0 ) ( 32 -242 0 ) ( 0 -242 32 ) " "map/lab_games/sky/lg_sky_01_lf 448 512 0 -0.03125 0.375 0 0 0\n" " ( 0 0 -192 ) ( 32 0 -192 ) ( 0 32 -192 ) " "map/lab_games/sky/lg_sky_01_lf 448 378 0 -0.03125 0.375 0 0 0\n" " ( 0 0 192 ) ( 0 32 192 ) ( 32 0 192 ) " "map/lab_games/sky/lg_sky_01_lf 448 378 0 -0.03125 0.375 0 0 0\n" " }\n" " {\n" " ( -242 0 0 ) ( -242 32 0 ) ( -242 0 32 ) " "map/lab_games/sky/lg_sky_01_rt 378 512 0 -0.375 0.375 0 0 0\n" " ( -210 0 0 ) ( -210 0 32 ) ( -210 32 0 ) " "map/lab_games/sky/lg_sky_01_rt 378 512 0 -0.375 0.375 0 0 0\n" " ( 0 -626 0 ) ( 0 -626 32 ) ( 32 -626 0 ) " "map/lab_games/sky/lg_sky_01_rt 448 512 0 -0.03125 0.375 0 0 0\n" " ( 0 -242 0 ) ( 32 -242 0 ) ( 0 -242 32 ) " "map/lab_games/sky/lg_sky_01_rt 448 512 0 -0.03125 0.375 0 0 0\n" " ( 0 0 -192 ) ( 32 0 -192 ) ( 0 32 -192 ) " "map/lab_games/sky/lg_sky_01_rt 448 378 0 -0.03125 0.375 0 0 0\n" " ( 0 0 192 ) ( 0 32 192 ) ( 32 0 192 ) " "map/lab_games/sky/lg_sky_01_rt 448 378 0 -0.03125 0.375 0 0 0\n" " }\n" " {\n" " ( -626 0 0 ) ( -626 32 0 ) ( -626 0 32 ) " "map/lab_games/sky/lg_sky_01_ft 448 512 0 -0.03125 0.375 0 0 0\n" " ( -242 0 0 ) ( -242 0 32 ) ( -242 32 0 ) " "map/lab_games/sky/lg_sky_01_ft 448 512 0 -0.03125 0.375 0 0 0\n" " ( 0 -658 0 ) ( 0 -658 32 ) ( 32 -658 0 ) " "map/lab_games/sky/lg_sky_01_ft 378 512 0 -0.375 0.375 0 0 0\n" " ( 0 -626 0 ) ( 32 -626 0 ) ( 0 -626 32 ) " "map/lab_games/sky/lg_sky_01_ft 378 512 0 -0.375 0.375 0 0 0\n" " ( 0 0 -192 ) ( 32 0 -192 ) ( 0 32 -192 ) " "map/lab_games/sky/lg_sky_01_ft 378 448 0 -0.375 0.03125 0 0 0\n" " ( 0 0 192 ) ( 0 32 192 ) ( 32 0 192 ) " "map/lab_games/sky/lg_sky_01_ft 378 448 0 -0.375 0.03125 0 0 0\n" " }\n" " {\n" " ( -626 0 0 ) ( -626 32 0 ) ( -626 0 32 ) " "map/lab_games/sky/lg_sky_01_bk 448 512 0 -0.03125 0.375 0 0 0\n" " ( -242 0 0 ) ( -242 0 32 ) ( -242 32 0 ) " "map/lab_games/sky/lg_sky_01_bk 448 512 0 -0.03125 0.375 0 0 0\n" " ( 0 -242 0 ) ( 0 -242 32 ) ( 32 -242 0 ) " "map/lab_games/sky/lg_sky_01_bk 378 512 0 -0.375 0.375 0 0 0\n" " ( 0 -210 0 ) ( 32 -210 0 ) ( 0 -210 32 ) " "map/lab_games/sky/lg_sky_01_bk 378 512 0 -0.375 0.375 0 0 0\n" " ( 0 0 -192 ) ( 32 0 -192 ) ( 0 32 -192 ) " "map/lab_games/sky/lg_sky_01_bk 378 448 0 -0.375 0.03125 0 0 0\n" " ( 0 0 192 ) ( 0 32 192 ) ( 32 0 192 ) " "map/lab_games/sky/lg_sky_01_bk 378 448 0 -0.375 0.03125 0 0 0\n }")); // Test skybox entity EXPECT_THAT(actual, testing::HasSubstr( "{\n" " \"classname\" \"_skybox\"\n" " \"origin\" \"-434 -434 0\"\n" "}")); } TEST(TranslateTextLevel, MakeFenceDoor) { auto callback = [](std::size_t i, std::size_t j, char ent, const MapSnippetEmitter& em, std::vector<std::string>* out) { if (ent == 'I' || ent == 'H') { out->push_back(em.AddFenceDoor(i, j, ent)); return true; } return false; }; std::mt19937_64 rng(123); TextLevelSettings settings; std::string actual = TranslateTextLevel( kEntities, kVariations, &rng, callback, &settings); // Test the first vertical fence door. EXPECT_THAT(actual, testing::HasSubstr( "\"angle\" \"90\"\n \"targetname\" \"door_11_3\"\n")); EXPECT_THAT(actual, testing::HasSubstr( "( 1146 0 0 ) ( 1146 32 0 ) ( 1146 0 32 ) door_placeholder:door_11_3")); // Test the first horizontal fence door. EXPECT_THAT(actual, testing::HasSubstr( "\"angle\" \"0\"\n \"targetname\" \"door_9_2\"\n")); EXPECT_THAT(actual, testing::HasSubstr( "( 901 0 0 ) ( 901 32 0 ) ( 901 0 32 ) door_placeholder:door_9_2")); } } // namespace } // namespace lab } // namespace deepmind
5,269
5,169
<reponame>Gantios/Specs { "name": "HQJD_P_aySDK", "version": "2.27.1", "summary": "JDPay", "homepage": "https://github.com/TianQiLi/HQJD_P_aySDK", "license": { "type": "Copyright", "text": " Copyright 2020 tql " }, "authors": { "litianqi": "<EMAIL>" }, "description": "WKwebview", "source": { "git": "https://github.com/TianQiLi/HQJD_P_aySDK.git", "tag": "2.27.1" }, "platforms": { "ios": "8.0" }, "requires_arc": true, "vendored_frameworks": "JDPay.framework", "frameworks": [ "UIKit", "Foundation", "CoreGraphics", "WebKit", "CoreLocation", "SystemConfiguration" ], "resources": "JDPay.framework/Res/*bundle" }
323
488
/* * ===================================================================================== * * Filename: stringprintf.cpp * * Description: * * Version: 1.0 * Created: 08/14/2019 11:09:23 AM * Revision: none * Compiler: gcc * * Author: YOUR NAME (), * Organization: * * ===================================================================================== */ #include <cstdarg> #include <cstdio> #include <string> namespace android { namespace base { void StringAppendV(std::string* dst, const char* format, va_list ap) { // First try with a small fixed size buffer char space[1024]; // It's possible for methods that use a va_list to invalidate // the data in it upon use. The fix is to make a copy // of the structure before using it and use that copy instead. va_list backup_ap; va_copy(backup_ap, ap); int result = vsnprintf(space, sizeof(space), format, backup_ap); va_end(backup_ap); if (result < static_cast<int>(sizeof(space))) { if (result >= 0) { // Normal case -- everything fit. dst->append(space, result); return; } if (result < 0) { // Just an error. return; } } // Increase the buffer size to the size requested by vsnprintf, // plus one for the closing \0. int length = result + 1; char* buf = new char[length]; // Restore the va_list before we use it again va_copy(backup_ap, ap); result = vsnprintf(buf, length, format, backup_ap); va_end(backup_ap); if (result >= 0 && result < length) { // It fit dst->append(buf, result); } delete[] buf; } std::string StringPrintf(const char* fmt, ...) { va_list ap; va_start(ap, fmt); std::string result; StringAppendV(&result, fmt, ap); va_end(ap); return result; } void StringAppendF(std::string* dst, const char* format, ...) { va_list ap; va_start(ap, format); StringAppendV(dst, format, ap); va_end(ap); } } // namespace base } // namespace android
715
338
<reponame>xemio/ANTsPy<filename>ants/utils/mni2tal.py __all__ = ['mni2tal'] def mni2tal(xin): """ mni2tal for converting from ch2/mni space to tal - very approximate. This is a standard approach but it's not very accurate. ANTsR function: `mni2tal` Arguments --------- xin : tuple point in mni152 space. Returns ------- tuple Example ------- >>> import ants >>> ants.mni2tal( (10,12,14) ) References ---------- http://bioimagesuite.yale.edu/mni2tal/501_95733_More\%20Accurate\%20Talairach\%20Coordinates\%20SLIDES.pdf http://imaging.mrc-cbu.cam.ac.uk/imaging/MniTalairach """ if (not isinstance(xin, (tuple,list))) or (len(xin) != 3): raise ValueError('xin must be tuple/list with 3 coordinates') x = list(xin) # The input image is in RAS coordinates but we use ITK which returns LPS # coordinates. So we need to flip the coordinates such that L => R and P => A to # get RAS (MNI) coordinates x[0] = x[0] * (-1) # flip X x[1] = x[1] * (-1) # flip Y xout = x if (x[2] >= 0): xout[0] = x[0] * 0.99 xout[1] = x[1] * 0.9688 + 0.046 * x[2] xout[2] = x[1] * (-0.0485) + 0.9189 * x[2] if (x[2] < 0): xout[0] = x[0] * 0.99 xout[1] = x[1] * 0.9688 + 0.042 * x[2] xout[2] = x[1] * (-0.0485) + 0.839 * x[2] return(xout)
702
17,085
<reponame>OuyangChao/Paddle<gh_stars>1000+ // Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) #include "paddle/fluid/platform/cuda_resource_pool.h" #include "paddle/fluid/platform/gpu_info.h" namespace paddle { namespace platform { CudaStreamResourcePool::CudaStreamResourcePool() { int dev_cnt = platform::GetCUDADeviceCount(); pool_.reserve(dev_cnt); for (int dev_idx = 0; dev_idx < dev_cnt; ++dev_idx) { auto creator = [dev_idx] { platform::SetDeviceId(dev_idx); gpuStream_t stream; #ifdef PADDLE_WITH_HIP PADDLE_ENFORCE_CUDA_SUCCESS( hipStreamCreateWithFlags(&stream, hipStreamNonBlocking)); #else PADDLE_ENFORCE_CUDA_SUCCESS( cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking)); #endif return stream; }; auto deleter = [dev_idx](gpuStream_t stream) { platform::SetDeviceId(dev_idx); #ifdef PADDLE_WITH_HIP PADDLE_ENFORCE_CUDA_SUCCESS(hipStreamDestroy(stream)); #else PADDLE_ENFORCE_CUDA_SUCCESS(cudaStreamDestroy(stream)); #endif }; pool_.emplace_back( ResourcePool<CudaStreamObject>::Create(creator, deleter)); } } CudaStreamResourcePool& CudaStreamResourcePool::Instance() { static CudaStreamResourcePool pool; return pool; } std::shared_ptr<CudaStreamObject> CudaStreamResourcePool::New(int dev_idx) { PADDLE_ENFORCE_GE( dev_idx, 0, platform::errors::InvalidArgument( "The dev_idx should be not less than 0, but got %d.", dev_idx)); PADDLE_ENFORCE_LT( dev_idx, pool_.size(), platform::errors::OutOfRange( "The dev_idx should be less than device count %d, but got %d.", pool_.size(), dev_idx)); return pool_[dev_idx]->New(); } CudaEventResourcePool::CudaEventResourcePool() { int dev_cnt = platform::GetCUDADeviceCount(); pool_.reserve(dev_cnt); for (int dev_idx = 0; dev_idx < dev_cnt; ++dev_idx) { auto creator = [dev_idx] { platform::SetDeviceId(dev_idx); gpuEvent_t event; #ifdef PADDLE_WITH_HIP PADDLE_ENFORCE_CUDA_SUCCESS( hipEventCreateWithFlags(&event, hipEventDisableTiming)); #else PADDLE_ENFORCE_CUDA_SUCCESS( cudaEventCreateWithFlags(&event, cudaEventDisableTiming)); #endif return event; }; auto deleter = [dev_idx](gpuEvent_t event) { platform::SetDeviceId(dev_idx); #ifdef PADDLE_WITH_HIP PADDLE_ENFORCE_CUDA_SUCCESS(hipEventDestroy(event)); #else PADDLE_ENFORCE_CUDA_SUCCESS(cudaEventDestroy(event)); #endif }; pool_.emplace_back(ResourcePool<CudaEventObject>::Create(creator, deleter)); } } CudaEventResourcePool& CudaEventResourcePool::Instance() { static CudaEventResourcePool pool; return pool; } std::shared_ptr<CudaEventObject> CudaEventResourcePool::New(int dev_idx) { PADDLE_ENFORCE_GE( dev_idx, 0, platform::errors::InvalidArgument( "The dev_idx should be not less than 0, but got %d.", dev_idx)); PADDLE_ENFORCE_LT( dev_idx, pool_.size(), platform::errors::OutOfRange( "The dev_idx should be less than device count %d, but got %d.", pool_.size(), dev_idx)); return pool_[dev_idx]->New(); } } // namespace platform } // namespace paddle #endif
1,548
1,144
<gh_stars>1000+ /* * #%L * de.metas.handlingunits.base * %% * Copyright (C) 2020 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package de.metas.handlingunits.allocation.impl; import java.math.BigDecimal; import java.math.RoundingMode; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.adempiere.util.lang.IMutable; import org.adempiere.util.lang.IPair; import org.adempiere.util.lang.ImmutablePair; import org.compiere.SpringContextHolder; import org.compiere.model.I_C_UOM; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import de.metas.handlingunits.HUIteratorListenerAdapter; import de.metas.handlingunits.HuId; import de.metas.handlingunits.IHUContext; import de.metas.handlingunits.IHandlingUnitsBL; import de.metas.handlingunits.IHandlingUnitsDAO; import de.metas.handlingunits.allocation.IAllocationDestination; import de.metas.handlingunits.allocation.IAllocationRequest; import de.metas.handlingunits.allocation.IAllocationResult; import de.metas.handlingunits.allocation.IAllocationSource; import de.metas.handlingunits.allocation.IAllocationStrategy; import de.metas.handlingunits.allocation.spi.impl.AggregateHUTrxListener; import de.metas.handlingunits.allocation.strategy.AllocationStrategyFactory; import de.metas.handlingunits.allocation.strategy.AllocationStrategyType; import de.metas.handlingunits.impl.HUIterator; import de.metas.handlingunits.model.I_M_HU; import de.metas.handlingunits.model.I_M_HU_Item; import de.metas.handlingunits.snapshot.IHUSnapshotDAO; import de.metas.handlingunits.storage.IHUItemStorage; import de.metas.handlingunits.storage.IHUStorage; import de.metas.handlingunits.storage.IProductStorage; import de.metas.util.Check; import de.metas.util.Services; import lombok.NonNull; import javax.annotation.Nullable; /** * An Allocation Source/Destination which has a list of HUs in behind. Usually used to load from HUs. * * @author tsa * */ public class HUListAllocationSourceDestination implements IAllocationSource, IAllocationDestination { /** @return single HU allocation source/destination */ public static HUListAllocationSourceDestination of(@NonNull final I_M_HU hu) { return new HUListAllocationSourceDestination(ImmutableList.of(hu), AllocationStrategyType.DEFAULT); } public static HUListAllocationSourceDestination of( @NonNull final I_M_HU hu, @NonNull final AllocationStrategyType allocationStrategyType) { return new HUListAllocationSourceDestination(ImmutableList.of(hu), allocationStrategyType); } public static HUListAllocationSourceDestination ofHUId(@NonNull final HuId huId) { final IHandlingUnitsBL handlingUnitsRepo = Services.get(IHandlingUnitsBL.class); final I_M_HU hu = handlingUnitsRepo.getById(huId); return new HUListAllocationSourceDestination(ImmutableList.of(hu), AllocationStrategyType.DEFAULT); } /** @return multi-HUs allocation source/destination */ public static HUListAllocationSourceDestination of(final Collection<I_M_HU> sourceHUs) { return new HUListAllocationSourceDestination(ImmutableList.copyOf(sourceHUs), AllocationStrategyType.DEFAULT); } // Services private final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); private final AllocationStrategyFactory allocationStrategyFactory = SpringContextHolder.instance.getBean(AllocationStrategyFactory.class); private final ImmutableList<I_M_HU> sourceHUs; private final int lastIndex; private int currentIndex = -1; private final AllocationStrategyType allocationStrategyType; private I_M_HU currentHU = null; private boolean destroyEmptyHUs = false; private boolean createHUSnapshots = false; // by default, don't create private String snapshotId = null; /** see {@link #setStoreCUQtyBeforeProcessing(boolean)} */ private boolean storeCUQtyBeforeProcessing = true; private HUListAllocationSourceDestination( @NonNull final ImmutableList<I_M_HU> sourceHUs, @NonNull final AllocationStrategyType allocationStrategyType) { this.sourceHUs = sourceHUs; lastIndex = sourceHUs.size() - 1; this.allocationStrategyType = allocationStrategyType; this.storeCUQtyBeforeProcessing = computeStoreCUQtyBeforeProcessing(allocationStrategyType); } private static boolean computeStoreCUQtyBeforeProcessing(@NonNull final AllocationStrategyType allocationStrategyType) { if (AllocationStrategyType.UNIFORM.equals(allocationStrategyType)) { return false; } else { return true; } } public boolean isDestroyEmptyHUs() { return destroyEmptyHUs; } /** * Shall we destroy HUs which are empty after {@link #unloadAll(IHUContext)}. * * @param destroyEmptyHUs true if HUs shall be destroyed if they are empty * @return */ public HUListAllocationSourceDestination setDestroyEmptyHUs(final boolean destroyEmptyHUs) { this.destroyEmptyHUs = destroyEmptyHUs; return this; } /** * Shall we create snapshots of all {@link I_M_HU}s (recursivelly), before touching them. * * In case it's activated, a full snapshots will be taken before touching any of the underlying HUs. * The snapshot ID will be accessible by {@link #getSnapshotId()}. * * @param createHUSnapshots * @return */ public HUListAllocationSourceDestination setCreateHUSnapshots(final boolean createHUSnapshots) { this.createHUSnapshots = createHUSnapshots; return this; } /** * For this instance's HUs their included HUs (if any), this setter specifies whether this instance will make sure that for every aggregate HU, the current CU-per-TU quantity is stored in the given {@code request}'s {@link IHUContext}. * <p> * This information (if stored by this instance) can later be used by {@link AggregateHUTrxListener} to adjust the {@code HA} item's {@code Qty} or split off a partial TU. * If you don't want this behavior (e.g. gh #943: because we are adjusting the HU's storage from the net weight), then just call this method with {@code false}. If you don't use this setter, the default will be {@code true}. * * @param storeCUQtyBeforeProcessing * @return */ public HUListAllocationSourceDestination setStoreCUQtyBeforeProcessing(final boolean storeCUQtyBeforeProcessing) { this.storeCUQtyBeforeProcessing = storeCUQtyBeforeProcessing; return this; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("HUs Count", sourceHUs.size()) .add("Current HU index", currentIndex) .add("HUs", sourceHUs) .toString(); } @Override public IAllocationResult load(final IAllocationRequest request) { return processRequest(request, AllocationDirection.INBOUND_ALLOCATION); } @Override public IAllocationResult unload(final IAllocationRequest request) { return processRequest(request, AllocationDirection.OUTBOUND_DEALLOCATION); } private IAllocationResult processRequest( @NonNull final IAllocationRequest request, @NonNull final AllocationDirection direction) { if (storeCUQtyBeforeProcessing) { // store the CU qtys in memory, so at the end of the load we can check if they changed. sourceHUs.forEach(hu -> { storeAggregateItemCuQty(request, hu); }); } createHUSnapshotsIfRequired(request.getHUContext()); final IMutableAllocationResult result = AllocationUtils.createMutableAllocationResult(request.getQty()); while (!result.isCompleted()) { if (currentHU == null) { currentHU = nextHU(); if (currentHU == null) { // we reached the last HU break; } } final IAllocationRequest currentRequest = AllocationUtils.createQtyRequestForRemaining(request, result); final IAllocationStrategy allocationStrategy = allocationStrategyFactory.createAllocationStrategy(direction, allocationStrategyType); final IAllocationResult currentResult = allocationStrategy.execute(currentHU, currentRequest); AllocationUtils.mergeAllocationResult(result, currentResult); // It seems that current HU is empty but we still have more qty to deallocate, we need to move forward to the next one if (currentResult.getQtyToAllocate().signum() != 0) { currentHU = null; } } return result; } /** * See {@link #setStoreCUQtyBeforeProcessing(boolean)}. * * @param request * @param hu */ private void storeAggregateItemCuQty(final IAllocationRequest request, final I_M_HU hu) { if (handlingUnitsBL.isAggregateHU(hu)) { final BigDecimal cuQty; final I_M_HU_Item haItem = hu.getM_HU_Item_Parent(); final BigDecimal aggregateHUQty = haItem.getQty(); if (aggregateHUQty.signum() <= 0) { cuQty = BigDecimal.ZERO; } else { final IHUStorage storage = request.getHUContext().getHUStorageFactory().getStorage(hu); final BigDecimal storageQty = storage == null ? BigDecimal.ZERO : storage.getQtyForProductStorages(request.getC_UOM()).toBigDecimal(); // gh #1237: cuQty does *not* have to be a an "integer" number. // If the overall HU's storage is not always integer and given that the aggregate's TU qty is always an integer, cuQty can't be an integer at any times either final I_C_UOM storageUOM = storage.getC_UOMOrNull(); Check.errorIf(storageUOM == null, "The storage of M_HU_ID={} (an aggregate HU) has a null UOM (i.e. contains substorages with incompatible UOMs)", hu.getM_HU_ID()); // can't be null, because in aggregate-HU country, storages are uniform and therefore all have the same UOM final int scale = storageUOM.getStdPrecision(); cuQty = storageQty.divide(aggregateHUQty, scale, RoundingMode.FLOOR); } request.getHUContext().setProperty(AggregateHUTrxListener.mkItemCuQtyPropertyKey(haItem), cuQty); } else { final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class); handlingUnitsDAO.retrieveIncludedHUs(hu).forEach(includedHU -> storeAggregateItemCuQty(request, includedHU)); } } @Nullable private I_M_HU nextHU() { currentIndex++; if (currentIndex > lastIndex) { return null; } return sourceHUs.get(currentIndex); } @Override public List<IPair<IAllocationRequest, IAllocationResult>> unloadAll(final IHUContext huContext) { createHUSnapshotsIfRequired(huContext); final List<IPair<IAllocationRequest, IAllocationResult>> result = new ArrayList<>(); while (true) { if (currentHU == null) { currentHU = nextHU(); if (currentHU == null) { // we reached the last HU break; } } final List<IPair<IAllocationRequest, IAllocationResult>> huResult = unloadAll(huContext, currentHU); result.addAll(huResult); currentHU = null; } return result; } private List<IPair<IAllocationRequest, IAllocationResult>> unloadAll(final IHUContext huContext, final I_M_HU hu) { final List<IPair<IAllocationRequest, IAllocationResult>> result = new ArrayList<>(); final HUIteratorListenerAdapter huIteratorListener = new HUIteratorListenerAdapter() { /** * Create an allocation request which will empty the given product storage. * * @param productStorage * @return allocation request */ private IAllocationRequest createAllocationRequest(final IProductStorage productStorage) { final IAllocationRequest request = AllocationUtils.createQtyRequest(huContext, productStorage.getProductId(), productStorage.getQty(), getHUIterator().getDate() // date ); return request; } @Override public Result beforeHUItemStorage(final IMutable<IHUItemStorage> itemStorage) { // don't go downstream because we don't care what's there return Result.SKIP_DOWNSTREAM; } @Override public Result afterHUItemStorage(final IHUItemStorage itemStorage) { final ZonedDateTime date = getHUIterator().getDate(); final I_M_HU_Item huItem = itemStorage.getM_HU_Item(); final I_M_HU_Item referenceModel = huItem; for (final IProductStorage productStorage : itemStorage.getProductStorages(date)) { final IAllocationRequest productStorageRequest = createAllocationRequest(productStorage); final IAllocationSource productStorageAsSource = new GenericAllocationSourceDestination( productStorage, huItem, referenceModel); final IAllocationResult productStorageResult = productStorageAsSource.unload(productStorageRequest); result.add(ImmutablePair.of(productStorageRequest, productStorageResult)); } return Result.CONTINUE; } }; final HUIterator iterator = new HUIterator(); iterator.setDate(huContext.getDate()); iterator.setStorageFactory(huContext.getHUStorageFactory()); iterator.setListener(huIteratorListener); iterator.iterate(hu); return result; } @Override public void unloadComplete(final IHUContext huContext) { performDestroyEmptyHUsIfNeeded(huContext); } private void performDestroyEmptyHUsIfNeeded(final IHUContext huContext) { if (!destroyEmptyHUs) { return; } for (final I_M_HU hu : sourceHUs) { // Skip it if already destroyed if (handlingUnitsBL.isDestroyed(hu)) { continue; } handlingUnitsBL.destroyIfEmptyStorage(huContext, hu); } } /** * Gets the snapshot ID in case {@link #setCreateHUSnapshots(boolean)} was activated. * * @return * <ul> * <li>Snapshot ID * <li><code>null</code> if snapshots were not activated or there was NO need to take a snapshot (i.e. nobody asked this object to change the underlying HUs) * </ul> */ public String getSnapshotId() { return snapshotId; } private final void createHUSnapshotsIfRequired(final IHUContext huContext) { if (!createHUSnapshots) { return; } // Make sure no snapshots was already created // shall not happen if (snapshotId != null) { throw new IllegalStateException("Snapshot was already created: " + snapshotId); } snapshotId = Services.get(IHUSnapshotDAO.class) .createSnapshot() .setContext(huContext) .addModels(sourceHUs) .createSnapshots() .getSnapshotId(); } }
5,165
5,169
{ "name": "JRPodPrivate", "version": "0.1.0", "summary": "JRPodPrivate is First Commit", "description": "TODO: JRPodPrivate is First Commit and Test.", "homepage": "https://gitee.com/jerrisoft2", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "wni": "<EMAIL>" }, "source": { "git": "https://gitee.com/jerrisoft2/JRPodPrivate.git", "tag": "0.1.0" }, "platforms": { "ios": "8.0" }, "source_files": "JRPodPrivate/Classes/**/*" }
224
1,567
/* * Tencent is pleased to support the open source community by making PaxosStore available. * Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * https://opensource.org/licenses/BSD-3-Clause * 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. */ #include <vector> #include "gtest/gtest.h" #include "core/pins_wrapper.h" #include "core/plog_helper.h" #include "cutils/id_utils.h" #include "test_helper.h" using namespace paxos; using namespace test; namespace { Message SimpleReqMsg() { Message msg; msg.set_index(test_index); set_key(msg, test_logid); msg.set_from(2); msg.set_to(selfid); msg.set_proposed_num( cutils::prop_num_compose(2, 10)); set_test_accepted_value(msg); return msg; } } // namespace TEST(PInsAliveStateTest, SimpleConstruct) { PInsAliveState pins_state( paxos::to_paxos_key(test_logid), test_index, cutils::prop_num_compose(selfid, 1)); assert(false == pins_state.IsChosen()); } TEST(PInsAliveStateTest, BeginProp) { Message begin_prop_msg; begin_prop_msg.set_type(MessageType::BEGIN_PROP); set_test_accepted_value(begin_prop_msg); int ret = 0; bool write = false; MessageType rsp_msg_type = MessageType::NOOP; // case 1 { auto pins_state = EmptyPInsState(1); auto pins_impl = EmptyPIns(1); begin_prop_msg.set_key(pins_state->GetKey()); begin_prop_msg.set_index(pins_state->GetIndex()); std::tie(write, rsp_msg_type) = pins_state->Step(begin_prop_msg, pins_impl); assert(true == write); assert(MessageType::PROP == rsp_msg_type); assert(0 < pins_impl.proposed_num()); assert(pins_impl.has_promised_num()); assert(pins_impl.proposed_num() == pins_impl.promised_num()); assert(false == pins_impl.has_accepted_num()); assert(false == pins_impl.has_accepted_value()); assert(false == pins_state->IsChosen()); auto proposing_value = pins_state->TestProposingValue(); assert(nullptr != proposing_value); assert(proposing_value->reqid() == begin_prop_msg.accepted_value().reqid()); assert(proposing_value->data() == begin_prop_msg.accepted_value().data()); assert(pins_state->TestProposedNum() == pins_impl.proposed_num()); auto& rsp_votes = pins_state->TestRspVotes(); assert(true == rsp_votes.empty()); } // case 2 { auto pins_state = EmptyPInsState(1); auto pins_impl = EmptyPIns(1); pins_impl.set_promised_num(cutils::prop_num_compose(2, 0)); std::tie(write, rsp_msg_type) = pins_state->Step(begin_prop_msg, pins_impl); assert(false == write); assert(MessageType::NOOP == rsp_msg_type); assert(0 == pins_impl.proposed_num()); assert(cutils::prop_num_compose(2, 0) == pins_impl.promised_num()); assert(false == pins_impl.has_accepted_num()); assert(false == pins_impl.has_accepted_value()); assert(false == pins_state->IsChosen()); assert(nullptr == pins_state->TestProposingValue()); } } TEST(PInsAliveStateTest, BeginFastProp) { Message bfast_prop_msg; bfast_prop_msg.set_type(MessageType::BEGIN_FAST_PROP); set_test_accepted_value(bfast_prop_msg); int ret = 0; bool write = false; MessageType rsp_msg_type = MessageType::NOOP; // case 1 { auto pins_state = EmptyPInsState(1); auto pins_impl = EmptyPIns(1); bfast_prop_msg.set_key(pins_state->GetKey()); bfast_prop_msg.set_index(pins_state->GetIndex()); std::tie(write, rsp_msg_type) = pins_state->Step(bfast_prop_msg, pins_impl); assert(true == write); assert(MessageType::FAST_ACCPT == rsp_msg_type); assert(0 < pins_impl.proposed_num()); assert(pins_impl.has_promised_num()); assert(pins_impl.proposed_num() == pins_impl.promised_num()); assert(pins_impl.has_accepted_num()); assert(pins_impl.proposed_num() == pins_impl.accepted_num()); assert(pins_impl.has_accepted_value()); check_entry_equal( pins_impl.accepted_value(), bfast_prop_msg.accepted_value()); assert(false == pins_state->IsChosen()); auto proposing_value = pins_state->TestProposingValue(); assert(nullptr != proposing_value); check_entry_equal(*proposing_value, bfast_prop_msg.accepted_value()); assert(pins_state->TestProposedNum() == pins_impl.proposed_num()); auto& rsp_votes = pins_state->TestRspVotes(); assert(true == rsp_votes.empty()); } // case 2 { auto pins_state = EmptyPInsState(1); auto pins_impl = EmptyPIns(1); pins_impl.set_promised_num(cutils::prop_num_compose(2, 0)); std::tie(write, rsp_msg_type) = pins_state->Step(bfast_prop_msg, pins_impl); assert(false == write); assert(MessageType::NOOP == rsp_msg_type); assert(0 == pins_impl.proposed_num()); assert(cutils::prop_num_compose(2, 0) == pins_impl.promised_num()); assert(false == pins_impl.has_accepted_num()); assert(false == pins_impl.has_accepted_value()); assert(false == pins_state->IsChosen()); assert(nullptr == pins_state->TestProposingValue()); } } TEST(PInsAliveStateTest, TryProp) { Message try_prop_msg; try_prop_msg.set_type(MessageType::TRY_PROP); set_test_accepted_value(try_prop_msg); try_prop_msg.mutable_accepted_value()->set_reqid(0); // indicate try prop int ret = 0; bool write = false; auto rsp_msg_type = MessageType::NOOP; // case 1 { auto pins_state = EmptyPInsState(test_index); auto pins_impl = EmptyPIns(test_index); try_prop_msg.set_key(pins_state->GetKey()); try_prop_msg.set_index(pins_state->GetIndex()); assert(PropState::NIL == pins_state->TestPropState()); std::tie(write, rsp_msg_type) = pins_state->Step(try_prop_msg, pins_impl); assert(PropState::WAIT_PREPARE == pins_state->TestPropState()); assert(true == write); assert(MessageType::PROP == rsp_msg_type); assert(pins_impl.has_promised_num()); assert(pins_impl.proposed_num() == pins_impl.promised_num()); assert(nullptr != pins_state->TestProposingValue()); uint64_t proposed_num = pins_impl.proposed_num(); Message prop_rsp_msg; prop_rsp_msg.set_type(MessageType::PROP_RSP); prop_rsp_msg.set_key(pins_state->GetKey()); prop_rsp_msg.set_index(pins_state->GetIndex()); prop_rsp_msg.set_from(2); prop_rsp_msg.set_proposed_num(proposed_num); prop_rsp_msg.set_promised_num(proposed_num); std::tie(write, rsp_msg_type) = pins_state->Step(prop_rsp_msg, pins_impl); assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); assert(true == write); assert(MessageType::ACCPT == rsp_msg_type); assert(pins_impl.has_accepted_num()); assert(pins_impl.accepted_num() == proposed_num); assert(pins_impl.has_accepted_value()); assert(0 == pins_impl.accepted_value().reqid()); assert(test_value == pins_impl.accepted_value().data()); } // case 2 TryProp in WAIT_PREPARE state { std::unique_ptr<paxos::PInsAliveState> pins_state; PaxosInstance pins_impl; std::tie(pins_state, pins_impl) = WaitPropRsp(); // reject uint64_t proposed_num = pins_impl.proposed_num(); Message prop_rsp_msg; prop_rsp_msg.set_type(MessageType::PROP_RSP); prop_rsp_msg.set_key(pins_state->GetKey()); prop_rsp_msg.set_index(pins_state->GetIndex()); prop_rsp_msg.set_from(2); prop_rsp_msg.set_proposed_num(proposed_num); prop_rsp_msg.set_promised_num( cutils::PropNumGen(2, 0).Next(proposed_num)); assert(prop_rsp_msg.promised_num() > prop_rsp_msg.proposed_num()); std::tie(write, rsp_msg_type) = pins_state->Step(prop_rsp_msg, pins_impl); assert(PropState::WAIT_PREPARE == pins_state->TestPropState()); assert(size_t{1} == pins_state->TestRspVotes().size()); std::tie(write, rsp_msg_type) = pins_state->Step(try_prop_msg, pins_impl); assert(PropState::WAIT_PREPARE == pins_state->TestPropState()); assert(true == write); assert(MessageType::PROP == rsp_msg_type); assert(proposed_num < pins_impl.proposed_num()); assert(pins_state->TestRspVotes().empty()); assert(nullptr != pins_state->TestProposingValue()); } // case 3 TryProp in WAIT_ACCPT state (normal accpt) { std::unique_ptr<paxos::PInsAliveState> pins_state; PaxosInstance pins_impl; std::tie(pins_state, pins_impl) = WaitAccptRsp(1); // reject uint64_t proposed_num = pins_impl.proposed_num(); Message accpt_rsp_msg; accpt_rsp_msg.set_type(MessageType::ACCPT_RSP); accpt_rsp_msg.set_key(pins_state->GetKey()); accpt_rsp_msg.set_index(pins_state->GetIndex()); accpt_rsp_msg.set_from(2); accpt_rsp_msg.set_proposed_num(proposed_num); accpt_rsp_msg.set_accepted_num( cutils::PropNumGen(2, 0).Next(proposed_num)); assert(accpt_rsp_msg.accepted_num() > accpt_rsp_msg.proposed_num()); std::tie(write, rsp_msg_type) = pins_state->Step(accpt_rsp_msg, pins_impl); assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); assert(size_t{1} == pins_state->TestRspVotes().size()); std::tie(write, rsp_msg_type) = pins_state->Step(try_prop_msg, pins_impl); assert(PropState::WAIT_PREPARE == pins_state->TestPropState()); assert(true == write); assert(MessageType::PROP == rsp_msg_type); assert(proposed_num < pins_impl.proposed_num()); assert(accpt_rsp_msg.accepted_num() < pins_impl.proposed_num()); assert(pins_state->TestRspVotes().empty()); assert(nullptr != pins_state->TestProposingValue()); } // case 4 TryPropo in WAIT_ACCPT state (fast accpt) { std::unique_ptr<paxos::PInsAliveState> pins_state; PaxosInstance pins_impl; std::tie(pins_state, pins_impl) = WaitFastAccptRsp(); // reject uint64_t proposed_num = pins_impl.proposed_num(); Message faccpt_rsp_msg; faccpt_rsp_msg.set_type(MessageType::FAST_ACCPT_RSP); faccpt_rsp_msg.set_key(pins_state->GetKey()); faccpt_rsp_msg.set_index(pins_state->GetIndex()); faccpt_rsp_msg.set_from(2); faccpt_rsp_msg.set_proposed_num(proposed_num); faccpt_rsp_msg.set_accepted_num( cutils::PropNumGen(2, 0).Next(proposed_num)); assert(faccpt_rsp_msg.accepted_num() > proposed_num); std::tie(write, rsp_msg_type) = pins_state->Step(faccpt_rsp_msg, pins_impl); assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); assert(size_t{1} == pins_state->TestRspVotes().size()); std::tie(write, rsp_msg_type) = pins_state->Step(try_prop_msg, pins_impl); assert(PropState::WAIT_PREPARE == pins_state->TestPropState()); assert(true == write); assert(MessageType::PROP == rsp_msg_type); assert(proposed_num < pins_impl.proposed_num()); } } TEST(PInsAliveStateTest, FastAccptRsp) { int ret = 0; bool write = false; auto rsp_msg_type = MessageType::NOOP; // case 1 { std::unique_ptr<paxos::PInsAliveState> pins_state; PaxosInstance pins_impl; std::tie(pins_state, pins_impl) = WaitFastAccptRsp(); uint64_t proposed_num = pins_impl.proposed_num(); Message faccpt_rsp_msg; faccpt_rsp_msg.set_type(MessageType::FAST_ACCPT_RSP); faccpt_rsp_msg.set_key(pins_state->GetKey()); faccpt_rsp_msg.set_index(pins_state->GetIndex()); faccpt_rsp_msg.set_from(2); faccpt_rsp_msg.set_proposed_num(proposed_num); faccpt_rsp_msg.set_accepted_num(proposed_num); // accepted assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); std::tie( write, rsp_msg_type) = pins_state->Step(faccpt_rsp_msg, pins_impl); assert(PropState::CHOSEN == pins_state->TestPropState()); assert(false == write); assert(MessageType::CHOSEN == rsp_msg_type); assert(pins_state->IsChosen()); assert(nullptr == pins_state->TestProposingValue()); assert(pins_state->TestRspVotes().empty()); assert(test_reqid == pins_impl.accepted_value().reqid()); assert(test_value == pins_impl.accepted_value().data()); } // case 2 ignore { std::unique_ptr<paxos::PInsAliveState> pins_state; PaxosInstance pins_impl; std::tie(pins_state, pins_impl) = WaitFastAccptRsp(); Message faccpt_rsp_msg; faccpt_rsp_msg.set_type(MessageType::FAST_ACCPT_RSP); faccpt_rsp_msg.set_key(pins_state->GetKey()); faccpt_rsp_msg.set_index(pins_state->GetIndex()); faccpt_rsp_msg.set_from(2); faccpt_rsp_msg.set_proposed_num( cutils::prop_num_compose(2, 0)); std::tie( write, rsp_msg_type) = pins_state->Step(faccpt_rsp_msg, pins_impl); assert(false == write); assert(MessageType::NOOP == rsp_msg_type); assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); assert(pins_state->TestRspVotes().empty()); } // case 3 reject { std::unique_ptr<paxos::PInsAliveState> pins_state; PaxosInstance pins_impl; std::tie(pins_state, pins_impl) = WaitFastAccptRsp(); uint64_t proposed_num = pins_impl.proposed_num(); Message faccpt_rsp_msg; faccpt_rsp_msg.set_type(MessageType::FAST_ACCPT_RSP); faccpt_rsp_msg.set_key(pins_state->GetKey()); faccpt_rsp_msg.set_index(pins_state->GetIndex()); faccpt_rsp_msg.set_from(2); faccpt_rsp_msg.set_proposed_num(proposed_num); faccpt_rsp_msg.set_accepted_num( cutils::PropNumGen(2, 0).Next(proposed_num)); assert(faccpt_rsp_msg.accepted_num() > proposed_num); // reject std::tie( write, rsp_msg_type) = pins_state->Step(faccpt_rsp_msg, pins_impl); assert(false == write); assert(MessageType::NOOP == rsp_msg_type); assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); assert(size_t{1} == pins_state->TestRspVotes().size()); auto pins_state_bak = pins_state->TestClone(); auto pins_impl_bak = pins_impl; auto faccpt_rsp_msg_bak = faccpt_rsp_msg; { // reject faccpt_rsp_msg.set_from(3); assert(faccpt_rsp_msg.accepted_num() > faccpt_rsp_msg.proposed_num()); assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); std::tie( write, rsp_msg_type) = pins_state->Step(faccpt_rsp_msg, pins_impl); assert(PropState::WAIT_PREPARE == pins_state->TestPropState()); assert(true == write); assert(MessageType::PROP == rsp_msg_type); assert(pins_state->TestRspVotes().empty()); } pins_state = std::move(pins_state_bak); pins_impl = pins_impl_bak; faccpt_rsp_msg = faccpt_rsp_msg_bak; // redundance reject msg assert(faccpt_rsp_msg.accepted_num() > faccpt_rsp_msg.proposed_num()); assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); assert(size_t{1} == pins_state->TestRspVotes().size()); std::tie( write, rsp_msg_type) = pins_state->Step(faccpt_rsp_msg, pins_impl); assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); assert(false == write); assert(MessageType::NOOP == rsp_msg_type); assert(size_t{1} == pins_state->TestRspVotes().size()); { // accpt faccpt_rsp_msg.set_from(3); faccpt_rsp_msg.set_accepted_num(faccpt_rsp_msg.proposed_num()); assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); std::tie( write, rsp_msg_type) = pins_state->Step(faccpt_rsp_msg, pins_impl); assert(PropState::CHOSEN == pins_state->TestPropState()); assert(false == write); assert(MessageType::CHOSEN == rsp_msg_type); assert(pins_state->IsChosen()); assert(nullptr == pins_state->TestProposingValue()); } } // case 4 reject with accepted_num == 0 <=> promoised_num > proposed_num { std::unique_ptr<paxos::PInsAliveState> pins_state; PaxosInstance pins_impl; std::tie(pins_state, pins_impl) = WaitAccptRsp(1); uint64_t proposed_num = pins_impl.proposed_num(); Message faccpt_rsp_msg; faccpt_rsp_msg.set_type(MessageType::FAST_ACCPT_RSP); faccpt_rsp_msg.set_key(pins_state->GetKey()); faccpt_rsp_msg.set_index(pins_state->GetIndex()); faccpt_rsp_msg.set_from(2); faccpt_rsp_msg.set_proposed_num(proposed_num); // 0 accepted_num faccpt_rsp_msg.set_accepted_num(0); faccpt_rsp_msg.set_promised_num( cutils::PropNumGen(3, 0).Next(proposed_num)); // reject std::tie( write, rsp_msg_type) = pins_state->Step(faccpt_rsp_msg, pins_impl); assert(false == write); assert(MessageType::NOOP == rsp_msg_type); assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); assert(size_t{1} == pins_state->TestRspVotes().size()); assert(faccpt_rsp_msg.promised_num() == pins_state->TestMaxHintNum()); } } TEST(PInsAliveStateTest, AccptRsp) { int ret = 0; bool write = false; auto rsp_msg_type = MessageType::NOOP; // case 1 { std::unique_ptr<paxos::PInsAliveState> pins_state; PaxosInstance pins_impl; std::tie(pins_state, pins_impl) = WaitAccptRsp(1); uint64_t proposed_num = pins_impl.proposed_num(); Message accpt_rsp_msg; accpt_rsp_msg.set_type(MessageType::ACCPT_RSP); accpt_rsp_msg.set_key(pins_state->GetKey()); accpt_rsp_msg.set_index(pins_state->GetIndex()); accpt_rsp_msg.set_from(2); accpt_rsp_msg.set_proposed_num(proposed_num); accpt_rsp_msg.set_accepted_num(proposed_num); // accepted assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); std::tie( write, rsp_msg_type) = pins_state->Step(accpt_rsp_msg, pins_impl); assert(PropState::CHOSEN == pins_state->TestPropState()); assert(false == write); assert(MessageType::CHOSEN == rsp_msg_type); assert(pins_state->IsChosen()); assert(nullptr == pins_state->TestProposingValue()); assert(pins_state->TestRspVotes().empty()); assert(test_reqid == pins_impl.accepted_value().reqid()); assert(test_value == pins_impl.accepted_value().data()); // pins_state mark as chosen, nomore msg!! } // case 2 { std::unique_ptr<paxos::PInsAliveState> pins_state; PaxosInstance pins_impl; std::tie(pins_state, pins_impl) = WaitAccptRsp(1); Message accpt_rsp_msg; accpt_rsp_msg.set_type(MessageType::ACCPT_RSP); accpt_rsp_msg.set_key(pins_state->GetKey()); accpt_rsp_msg.set_index(pins_state->GetIndex()); accpt_rsp_msg.set_from(2); accpt_rsp_msg.set_proposed_num( cutils::prop_num_compose(2, 0)); accpt_rsp_msg.set_accepted_num(accpt_rsp_msg.proposed_num()); assert(accpt_rsp_msg.proposed_num() != pins_impl.proposed_num()); // ingore std::tie( write, rsp_msg_type) = pins_state->Step(accpt_rsp_msg, pins_impl); assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); assert(false == write); assert(MessageType::NOOP == rsp_msg_type); assert(false == pins_state->IsChosen()); assert(pins_state->TestRspVotes().empty()); } // case 3 reject { std::unique_ptr<paxos::PInsAliveState> pins_state; PaxosInstance pins_impl; std::tie(pins_state, pins_impl) = WaitAccptRsp(1); uint64_t proposed_num = pins_impl.proposed_num(); Message accpt_rsp_msg; accpt_rsp_msg.set_type(MessageType::ACCPT_RSP); accpt_rsp_msg.set_key(pins_state->GetKey()); accpt_rsp_msg.set_index(pins_state->GetIndex()); accpt_rsp_msg.set_from(2); accpt_rsp_msg.set_proposed_num(proposed_num); accpt_rsp_msg.set_accepted_num( cutils::PropNumGen(2, 0).Next(proposed_num)); assert(accpt_rsp_msg.accepted_num() > proposed_num); // reject std::tie( write, rsp_msg_type) = pins_state->Step(accpt_rsp_msg, pins_impl); assert(false == write); assert(MessageType::NOOP == rsp_msg_type); assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); assert(size_t{1} == pins_state->TestRspVotes().size()); auto pins_state_bak = pins_state->TestClone(); auto pins_impl_bak = pins_impl; auto accpt_rsp_msg_bak = accpt_rsp_msg; { // reject accpt_rsp_msg.set_from(3); assert(accpt_rsp_msg.accepted_num() > accpt_rsp_msg.proposed_num()); assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); std::tie( write, rsp_msg_type) = pins_state->Step(accpt_rsp_msg, pins_impl); assert(PropState::WAIT_PREPARE == pins_state->TestPropState()); assert(true == write); assert(MessageType::PROP == rsp_msg_type); assert(pins_state->TestRspVotes().empty()); } pins_state = std::move(pins_state_bak); pins_impl = pins_impl_bak; accpt_rsp_msg = accpt_rsp_msg_bak; { // accpt accpt_rsp_msg.set_from(3); accpt_rsp_msg.set_accepted_num(accpt_rsp_msg.proposed_num()); assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); std::tie( write, rsp_msg_type) = pins_state->Step(accpt_rsp_msg, pins_impl); assert(PropState::CHOSEN == pins_state->TestPropState()); assert(false == write); assert(MessageType::CHOSEN == rsp_msg_type); assert(pins_state->IsChosen()); assert(nullptr == pins_state->TestProposingValue()); assert(pins_state->TestRspVotes().empty()); assert(test_reqid == pins_impl.accepted_value().reqid()); assert(test_value == pins_impl.accepted_value().data()); } } // case 4 reject with accepted_num == 0 <=> promised_num { std::unique_ptr<paxos::PInsAliveState> pins_state; PaxosInstance pins_impl; std::tie(pins_state, pins_impl) = WaitAccptRsp(1); uint64_t proposed_num = pins_impl.proposed_num(); Message accpt_rsp_msg; accpt_rsp_msg.set_type(MessageType::ACCPT_RSP); accpt_rsp_msg.set_key(pins_state->GetKey()); accpt_rsp_msg.set_index(pins_state->GetIndex()); accpt_rsp_msg.set_from(2); accpt_rsp_msg.set_proposed_num(proposed_num); // 0 = > indicate a reject accpt_rsp_msg.set_accepted_num(0); // => reject by promised_num accpt_rsp_msg.set_promised_num( cutils::PropNumGen(3, 0).Next(proposed_num)); assert(accpt_rsp_msg.promised_num() > accpt_rsp_msg.proposed_num()); // reject std::tie( write, rsp_msg_type) = pins_state->Step(accpt_rsp_msg, pins_impl); assert(false == write); assert(MessageType::NOOP == rsp_msg_type); assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); assert(size_t{1} == pins_state->TestRspVotes().size()); assert(accpt_rsp_msg.promised_num() == pins_state->TestMaxHintNum()); } } TEST(PInsAliveStateTest, PropRsp) { int ret = 0; bool write = false; auto rsp_msg_type = MessageType::NOOP; // case 1 { std::unique_ptr<paxos::PInsAliveState> pins_state; PaxosInstance pins_impl; std::tie(pins_state, pins_impl) = WaitPropRsp(); uint64_t proposed_num = pins_impl.proposed_num(); Message prop_rsp_msg; prop_rsp_msg.set_type(MessageType::PROP_RSP); prop_rsp_msg.set_key(pins_state->GetKey()); prop_rsp_msg.set_index(pins_state->GetIndex()); prop_rsp_msg.set_from(2); prop_rsp_msg.set_proposed_num(proposed_num); // promised prop_rsp_msg.set_promised_num(proposed_num); assert(false == prop_rsp_msg.has_accepted_num()); assert(PropState::WAIT_PREPARE == pins_state->TestPropState()); assert(false == pins_impl.has_accepted_num()); std::tie( write, rsp_msg_type) = pins_state->Step(prop_rsp_msg, pins_impl); assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); assert(true == write); assert(MessageType::ACCPT == rsp_msg_type); assert(pins_impl.has_accepted_num()); assert(pins_impl.has_accepted_value()); check_entry_equal(*(pins_state->TestProposingValue()), pins_impl.accepted_value()); // reject will be ignore prop_rsp_msg.set_from(3); prop_rsp_msg.set_promised_num( cutils::prop_num_compose(2, 1)); std::tie( write, rsp_msg_type) = pins_state->Step(prop_rsp_msg, pins_impl); assert(false == write); assert(MessageType::NOOP == rsp_msg_type); assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); assert(pins_state->TestRspVotes().empty()); //assert(pins_state->GetStrictPropFlag()); } // case 2 ignore { std::unique_ptr<paxos::PInsAliveState> pins_state; PaxosInstance pins_impl; std::tie(pins_state, pins_impl) = WaitPropRsp(); uint64_t proposed_num = cutils::prop_num_compose(1, 10); assert(proposed_num != pins_impl.proposed_num()); Message prop_rsp_msg; prop_rsp_msg.set_type(MessageType::PROP_RSP); prop_rsp_msg.set_key(pins_state->GetKey()); prop_rsp_msg.set_index(pins_state->GetIndex()); prop_rsp_msg.set_from(2); prop_rsp_msg.set_proposed_num(proposed_num); prop_rsp_msg.set_promised_num(proposed_num); std::tie( write, rsp_msg_type) = pins_state->Step(prop_rsp_msg, pins_impl); assert(false == write); assert(MessageType::NOOP == rsp_msg_type); assert(false == pins_impl.has_accepted_num()); assert(PropState::WAIT_PREPARE == pins_state->TestPropState()); assert(true == pins_state->TestRspVotes().empty()); // assert(pins_state->GetStrictPropFlag()); } // case 3 reject { // auto pins_state = EmptyPInsState(); std::unique_ptr<paxos::PInsAliveState> pins_state; PaxosInstance pins_impl; std::tie(pins_state, pins_impl) = WaitPropRsp(); uint64_t proposed_num = pins_impl.proposed_num(); Message prop_rsp_msg; prop_rsp_msg.set_type(MessageType::PROP_RSP); prop_rsp_msg.set_key(pins_state->GetKey()); prop_rsp_msg.set_index(pins_state->GetIndex()); prop_rsp_msg.set_from(2); prop_rsp_msg.set_proposed_num(proposed_num); prop_rsp_msg.set_promised_num( cutils::prop_num_compose(2, 10)); assert(false == prop_rsp_msg.has_accepted_num()); assert(prop_rsp_msg.promised_num() > proposed_num); assert(PropState::WAIT_PREPARE == pins_state->TestPropState()); std::tie( write, rsp_msg_type) = pins_state->Step(prop_rsp_msg, pins_impl); assert(PropState::WAIT_PREPARE == pins_state->TestPropState()); assert(false == write); assert(MessageType::NOOP == rsp_msg_type); assert(false == pins_impl.has_accepted_num()); assert(size_t{1} == pins_state->TestRspVotes().size()); // case 3.1 auto pins_state_bak = pins_state->TestClone(); auto pins_impl_bak = pins_impl; auto prop_rsp_msg_bak = prop_rsp_msg; { prop_rsp_msg.set_from(3); assert(prop_rsp_msg.promised_num() > pins_impl.proposed_num()); // reject assert(PropState::WAIT_PREPARE == pins_state->TestPropState()); std::tie( write, rsp_msg_type) = pins_state->Step(prop_rsp_msg, pins_impl); assert(true == write); assert(MessageType::PROP == rsp_msg_type); assert(PropState::WAIT_PREPARE == pins_state->TestPropState()); assert(true == pins_state->TestRspVotes().empty()); // assert(pins_state->GetStrictPropFlag());; } // case 3.2 pins_state = std::move(pins_state_bak); pins_impl = pins_impl_bak; prop_rsp_msg = prop_rsp_msg_bak; { prop_rsp_msg.set_from(3); prop_rsp_msg.set_promised_num(prop_rsp_msg.proposed_num()); // promised assert(PropState::WAIT_PREPARE == pins_state->TestPropState()); std::tie( write, rsp_msg_type) = pins_state->Step(prop_rsp_msg, pins_impl); assert(true == write); assert(MessageType::ACCPT == rsp_msg_type); assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); assert(true == pins_state->TestRspVotes().empty()); assert(pins_impl.has_accepted_num()); assert(pins_impl.has_accepted_value()); //assert(pins_state->GetStrictPropFlag()); } } // case 4 promised with accepted value { std::unique_ptr<paxos::PInsAliveState> pins_state; PaxosInstance pins_impl; std::tie(pins_state, pins_impl) = WaitPropRsp(); // assert(pins_state->GetStrictPropFlag()); uint64_t proposed_num = pins_impl.proposed_num(); Message prop_rsp_msg; prop_rsp_msg.set_type(MessageType::PROP_RSP); prop_rsp_msg.set_key(pins_state->GetKey()); prop_rsp_msg.set_index(pins_state->GetIndex()); prop_rsp_msg.set_from(2); prop_rsp_msg.set_proposed_num(proposed_num); prop_rsp_msg.set_promised_num(proposed_num); prop_rsp_msg.set_accepted_num( cutils::prop_num_compose(2, 0)); assert(prop_rsp_msg.accepted_num() < proposed_num); set_diff_test_accepted_value(prop_rsp_msg); assert(PropState::WAIT_PREPARE == pins_state->TestPropState()); assert(false == pins_impl.has_accepted_num()); std::tie( write, rsp_msg_type) = pins_state->Step(prop_rsp_msg, pins_impl); assert(PropState::WAIT_ACCEPT == pins_state->TestPropState()); assert(true == write); assert(MessageType::ACCPT == rsp_msg_type); assert(pins_impl.has_accepted_num()); assert(proposed_num == pins_impl.accepted_num()); assert(pins_impl.has_accepted_value()); check_entry_equal(pins_impl.accepted_value(), prop_rsp_msg.accepted_value()); assert(nullptr != pins_state->TestProposingValue()); assert(test_reqid != pins_state->TestProposingValue()->reqid()); assert(prop_rsp_msg.accepted_num() == pins_state->TestMaxAcceptedHintNum()); // assert(false == pins_state->GetStrictPropFlag()); } } namespace { PaxosInstance FullPIns(bool chosen=true) { PaxosInstance pins_impl; pins_impl.set_index(test_index); auto proposed_num = cutils::prop_num_compose(1, 0); pins_impl.set_proposed_num(proposed_num); pins_impl.set_promised_num(proposed_num); pins_impl.set_accepted_num(proposed_num); { auto entry = pins_impl.mutable_accepted_value(); assert(nullptr != entry); entry->set_reqid(test_reqid); entry->set_data(test_value); } pins_impl.set_chosen(chosen); return pins_impl; } } // namespace TEST(PInsWrapperTest, SimpleConstruct) { // not chosen { PaxosInstance pins_impl; PInsWrapper pins_wrapper(nullptr, pins_impl); assert(false == pins_wrapper.IsChosen()); } // chosen { PaxosInstance pins_impl; set_test_accepted_value(pins_impl); pins_impl.set_chosen(true); PInsWrapper pins_wrapper(nullptr, pins_impl); assert(true == pins_wrapper.IsChosen()); } } TEST(PInsWrapperTest, ChosenStepMsg) { PaxosInstance pins_impl = FullPIns(); PInsWrapper pins_wrapper(nullptr, pins_impl); assert(true == pins_wrapper.IsChosen()); int ret = 0; bool write = false; std::unique_ptr<Message> rsp_msg = nullptr; // case 1 { Message req_msg; req_msg.set_type(MessageType::CHOSEN); req_msg.set_index(pins_impl.index()); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(req_msg); assert(false == write); assert(nullptr == rsp_msg); } // case 2 { std::vector<MessageType> vec_msg_type = { //MessageType::PROP_RSP, //MessageType::ACCPT_RSP, //MessageType::FAST_ACCPT_RSP, MessageType::GET_CHOSEN, MessageType::PROP, MessageType::ACCPT, MessageType::FAST_ACCPT, }; assert(false == vec_msg_type.empty()); for (auto msg_type : vec_msg_type) { Message req_msg; req_msg.set_type(msg_type); req_msg.set_index(pins_impl.index()); set_key(req_msg, test_logid); req_msg.set_from(2); req_msg.set_to(selfid); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(req_msg); assert(false == write); assert(nullptr != rsp_msg); assert(MessageType::CHOSEN == rsp_msg->type()); assert(rsp_msg->index() == pins_impl.index()); assert(rsp_msg->to() == 2); assert(rsp_msg->from() == selfid); assert(rsp_msg->has_promised_num()); assert(rsp_msg->has_accepted_num()); assert(rsp_msg->has_accepted_value()); check_entry_equal( rsp_msg->accepted_value(), pins_impl.accepted_value()); } } } TEST(PInsWrapperTest, NotChosenStepChosenMsg) { PaxosInstance pins_impl = FullPIns(false); int ret = 0; bool write = false; std::unique_ptr<Message> rsp_msg = nullptr; Message chosen_msg; chosen_msg.set_type(MessageType::CHOSEN); chosen_msg.set_index(pins_impl.index()); chosen_msg.set_proposed_num(pins_impl.accepted_num()); set_accepted_value(pins_impl.accepted_value(), chosen_msg); Message nmchosen_msg; nmchosen_msg.set_type(MessageType::CHOSEN); nmchosen_msg.set_index(pins_impl.index()); nmchosen_msg.set_proposed_num( cutils::prop_num_compose(2, 0)); set_diff_test_accepted_value(nmchosen_msg); // case 1 nullptr == pins_state { // case 1.1 accepted_num match { PInsWrapper pins_wrapper(nullptr, pins_impl); assert(false == pins_wrapper.IsChosen()); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(chosen_msg); assert(false == write); assert(nullptr == rsp_msg); assert(pins_wrapper.IsChosen()); } // case 1.2 accepted_num don't match { pins_impl = FullPIns(false); PInsWrapper pins_wrapper(nullptr, pins_impl); assert(false == pins_wrapper.IsChosen()); auto old_proposed_num = pins_impl.proposed_num(); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(nmchosen_msg); assert(true == write); assert(nullptr == rsp_msg); assert(pins_wrapper.IsChosen()); check_entry_equal( nmchosen_msg.accepted_value(), pins_impl.accepted_value()); assert(nmchosen_msg.accepted_num() <= pins_impl.proposed_num()); assert(old_proposed_num < pins_impl.proposed_num()); assert(pins_impl.proposed_num() == pins_impl.promised_num()); assert(pins_impl.proposed_num() == pins_impl.accepted_num()); } } // case 2 nullptr != pins_state { // case 2.1 { pins_impl = FullPIns(false); // reset auto pins_state = EmptyPInsState(pins_impl.index()); PInsWrapper pins_wrapper(pins_state.get(), pins_impl); assert(false == pins_wrapper.IsChosen()); assert(false == pins_state->IsChosen()); auto old_proposed_num = pins_impl.proposed_num(); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(chosen_msg); assert(false == write); assert(nullptr == rsp_msg); assert(pins_wrapper.IsChosen()); assert(pins_state->IsChosen()); assert(old_proposed_num == pins_impl.proposed_num()); } // case 2.2 { pins_impl = FullPIns(false); auto pins_state = EmptyPInsState(pins_impl.index()); PInsWrapper pins_wrapper(pins_state.get(), pins_impl); auto old_proposed_num = pins_impl.proposed_num(); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(nmchosen_msg); assert(true == write); assert(nullptr == rsp_msg); assert(pins_wrapper.IsChosen()); check_entry_equal( nmchosen_msg.accepted_value(), pins_impl.accepted_value()); assert(nmchosen_msg.accepted_num() <= pins_impl.proposed_num()); assert(old_proposed_num < pins_impl.proposed_num()); assert(pins_impl.proposed_num() == pins_impl.promised_num()); assert(pins_impl.proposed_num() == pins_impl.accepted_num()); } } } TEST(PInsWrapperTest, NotChosenStepPropMsg) { int ret = 0; bool write = false; std::unique_ptr<Message> rsp_msg = nullptr; Message prop_msg; prop_msg.set_type(MessageType::PROP); prop_msg.set_index(test_index); prop_msg.set_proposed_num( cutils::prop_num_compose(2, 10)); set_key(prop_msg, test_logid); prop_msg.set_from(2); prop_msg.set_to(selfid); // case 1 promised => empty stat { auto pins_impl = EmptyPIns(test_index); PInsWrapper pins_wrapper(nullptr, pins_impl); assert(false == pins_impl.has_promised_num()); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(prop_msg); assert(true == write); assert(nullptr != rsp_msg); assert(pins_impl.has_promised_num()); assert(pins_impl.promised_num() == prop_msg.proposed_num()); assert(MessageType::PROP_RSP == rsp_msg->type()); assert(prop_msg.proposed_num() == rsp_msg->proposed_num()); // indicate => promised assert(prop_msg.proposed_num() == rsp_msg->promised_num()); assert(prop_msg.index() == rsp_msg->index()); assert(prop_msg.key() == rsp_msg->key()); assert(prop_msg.to() == rsp_msg->from()); assert(prop_msg.from() == rsp_msg->to()); } // case 2 promised => not empty stat { auto pins_impl = EmptyPIns(test_index); pins_impl.set_promised_num( cutils::prop_num_compose(3, 1)); assert(pins_impl.promised_num() < prop_msg.proposed_num()); PInsWrapper pins_wrapper(nullptr, pins_impl); uint64_t prev_promised_num = pins_impl.promised_num(); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(prop_msg); assert(true == write); assert(nullptr != rsp_msg); assert(prev_promised_num < pins_impl.promised_num()); assert(pins_impl.promised_num() == prop_msg.proposed_num()); assert(MessageType::PROP_RSP == rsp_msg->type()); assert(prop_msg.proposed_num() == rsp_msg->proposed_num()); // indicate => promised assert(prop_msg.proposed_num() == rsp_msg->promised_num()); } // case 3 reject { auto pins_impl = EmptyPIns(test_index); pins_impl.set_promised_num( cutils::PropNumGen(3, 0).Next(prop_msg.proposed_num())); assert(pins_impl.promised_num() > prop_msg.proposed_num()); PInsWrapper pins_wrapper(nullptr, pins_impl); uint64_t prev_promised_num = pins_impl.promised_num(); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(prop_msg); assert(false == write); assert(nullptr != rsp_msg); assert(prev_promised_num == pins_impl.promised_num()); assert(MessageType::PROP_RSP == rsp_msg->type()); assert(prop_msg.proposed_num() == rsp_msg->proposed_num()); assert(prev_promised_num == rsp_msg->promised_num()); } } TEST(PInsWrapperTest, NotChosenStepAccptMsg) { int ret = 0; bool write = false; std::unique_ptr<Message> rsp_msg = nullptr; Message accpt_msg = SimpleReqMsg(); accpt_msg.set_type(MessageType::ACCPT); // case 1 accepted => empty stat { auto pins_impl = EmptyPIns(test_index); PInsWrapper pins_wrapper(nullptr, pins_impl); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(accpt_msg); assert(true == write); assert(nullptr != rsp_msg); assert(pins_impl.has_promised_num()); assert(pins_impl.promised_num() == accpt_msg.proposed_num()); assert(pins_impl.has_accepted_num()); assert(pins_impl.accepted_num() == accpt_msg.proposed_num()); assert(pins_impl.has_accepted_value()); check_entry_equal( pins_impl.accepted_value(), accpt_msg.accepted_value()); assert(MessageType::ACCPT_RSP == rsp_msg->type()); assert(accpt_msg.proposed_num() == rsp_msg->proposed_num()); assert(accpt_msg.proposed_num() == rsp_msg->accepted_num()); assert(false == rsp_msg->has_promised_num()); assert(accpt_msg.index() == rsp_msg->index()); assert(accpt_msg.key() == rsp_msg->key()); assert(accpt_msg.to() == rsp_msg->from()); assert(accpt_msg.from() == rsp_msg->to()); } // case 2: accepted => not empty stat { auto pins_impl = EmptyPIns(test_index); uint64_t old_proposed_num = cutils::prop_num_compose(3, 1); assert(old_proposed_num < accpt_msg.proposed_num()); pins_impl.set_promised_num(old_proposed_num); pins_impl.set_accepted_num(old_proposed_num); { auto entry = pins_impl.mutable_accepted_value(); assert(nullptr != entry); entry->set_reqid(test_reqid + test_reqid); entry->set_data(test_value + test_value); } assert(pins_impl.accepted_value().reqid() != accpt_msg.accepted_value().reqid()); PInsWrapper pins_wrapper(nullptr, pins_impl); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(accpt_msg); assert(true == write); assert(nullptr != rsp_msg); assert(old_proposed_num < pins_impl.promised_num()); assert(accpt_msg.proposed_num() == pins_impl.promised_num()); assert(accpt_msg.proposed_num() == pins_impl.accepted_num()); check_entry_equal(accpt_msg.accepted_value(), pins_impl.accepted_value()); } // case 3. reject { auto pins_impl = EmptyPIns(test_index); uint64_t old_proposed_num = cutils::PropNumGen(3, 0).Next(accpt_msg.proposed_num()); assert(old_proposed_num > accpt_msg.proposed_num()); pins_impl.set_promised_num(old_proposed_num); assert(false == pins_impl.has_accepted_num()); PInsWrapper pins_wrapper(nullptr, pins_impl); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(accpt_msg); assert(false == write); assert(nullptr != rsp_msg); assert(MessageType::ACCPT_RSP == rsp_msg->type()); assert(old_proposed_num == pins_impl.promised_num()); assert(false == pins_impl.has_accepted_num()); assert(false == pins_impl.has_accepted_value()); // not equal accepted_num => reject assert(rsp_msg->proposed_num() != rsp_msg->accepted_num()); assert(0 == rsp_msg->accepted_num()); assert(rsp_msg->has_promised_num()); } // case 4. reject { auto pins_impl = EmptyPIns(test_index); uint64_t old_proposed_num = cutils::PropNumGen(3, 0).Next(accpt_msg.proposed_num()); assert(old_proposed_num > accpt_msg.proposed_num()); pins_impl.set_promised_num(old_proposed_num); pins_impl.set_accepted_num(old_proposed_num); { auto entry = pins_impl.mutable_accepted_value(); assert(nullptr != entry); entry->set_reqid(test_reqid + test_reqid); entry->set_data(test_value + test_value); } PInsWrapper pins_wrapper(nullptr, pins_impl); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(accpt_msg); assert(false == write); assert(nullptr != rsp_msg); assert(MessageType::ACCPT_RSP == rsp_msg->type()); assert(old_proposed_num == pins_impl.accepted_num()); assert(rsp_msg->proposed_num() < rsp_msg->accepted_num()); assert(false == rsp_msg->has_promised_num()); } } TEST(PInsWrapperTest, NotChosenStepFastAccptMsg) { int ret = 0; bool write = false; std::unique_ptr<Message> rsp_msg = nullptr; auto faccpt_msg = SimpleReqMsg(); faccpt_msg.set_type(MessageType::FAST_ACCPT); // case 1: fast accpt => empty stat { auto pins_impl = EmptyPIns(test_index); PInsWrapper pins_wrapper(nullptr, pins_impl); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(faccpt_msg); assert(true == write); assert(nullptr != rsp_msg); assert(pins_impl.has_promised_num()); assert(pins_impl.promised_num() == faccpt_msg.proposed_num()); assert(pins_impl.has_accepted_num()); assert(pins_impl.accepted_num() == faccpt_msg.proposed_num()); assert(pins_impl.has_accepted_value()); check_entry_equal( pins_impl.accepted_value(), faccpt_msg.accepted_value()); assert(MessageType::FAST_ACCPT_RSP == rsp_msg->type()); assert(faccpt_msg.proposed_num() == rsp_msg->proposed_num()); assert(faccpt_msg.proposed_num() == rsp_msg->accepted_num()); assert(false == rsp_msg->has_promised_num()); } // case 2: fast accpt => not empty stat : only promised { auto pins_impl = EmptyPIns(test_index); uint64_t old_proposed_num = cutils::prop_num_compose(3, 0); assert(old_proposed_num < faccpt_msg.proposed_num()); pins_impl.set_promised_num(old_proposed_num); PInsWrapper pins_wrapper(nullptr, pins_impl); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(faccpt_msg); assert(true == write); assert(nullptr != rsp_msg); assert(old_proposed_num < pins_impl.promised_num()); assert(pins_impl.has_accepted_num()); assert(old_proposed_num < pins_impl.accepted_num()); } // case 3: fast accpt => reject because local accepted before { auto pins_impl = EmptyPIns(test_index); uint64_t old_proposed_num = cutils::prop_num_compose(3, 0); assert(old_proposed_num < faccpt_msg.proposed_num()); pins_impl.set_promised_num(old_proposed_num); pins_impl.set_accepted_num(old_proposed_num); { auto entry = pins_impl.mutable_accepted_value(); assert(nullptr != entry); entry->set_reqid(test_reqid + test_reqid); entry->set_data(test_value + test_value); } PInsWrapper pins_wrapper(nullptr, pins_impl); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(faccpt_msg); assert(false == write); assert(nullptr != rsp_msg); assert(MessageType::FAST_ACCPT_RSP == rsp_msg->type()); assert(pins_impl.accepted_num() == rsp_msg->accepted_num()); assert(false == rsp_msg->has_promised_num()); assert(faccpt_msg.proposed_num() != rsp_msg->accepted_num()); } // case 4: reject => not accepted, but promised high proposed_num { auto pins_impl = EmptyPIns(test_index); uint64_t old_proposed_num = cutils::PropNumGen(3, 0).Next(faccpt_msg.proposed_num()); assert(old_proposed_num > faccpt_msg.proposed_num()); pins_impl.set_promised_num(old_proposed_num); assert(false == pins_impl.has_accepted_num()); PInsWrapper pins_wrapper(nullptr, pins_impl); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(faccpt_msg); assert(false == write); assert(nullptr != rsp_msg); assert(MessageType::FAST_ACCPT_RSP == rsp_msg->type()); assert(0 == rsp_msg->accepted_num()); assert(rsp_msg->has_promised_num()); assert(old_proposed_num == rsp_msg->promised_num()); } // case 5: reject => accepted large propsed num { auto pins_impl = EmptyPIns(test_index); uint64_t old_proposed_num = cutils::PropNumGen(3, 0).Next(faccpt_msg.proposed_num()); assert(old_proposed_num > faccpt_msg.proposed_num()); pins_impl.set_promised_num(old_proposed_num); pins_impl.set_accepted_num(old_proposed_num); { auto entry = pins_impl.mutable_accepted_value(); assert(nullptr != entry); entry->set_reqid(test_reqid + test_reqid); entry->set_data(test_value + test_value); } PInsWrapper pins_wrapper(nullptr, pins_impl); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(faccpt_msg); assert(false == write); assert(nullptr != rsp_msg); assert(MessageType::FAST_ACCPT_RSP == rsp_msg->type()); assert(false == rsp_msg->has_promised_num()); assert(old_proposed_num == rsp_msg->accepted_num()); } } TEST(PInsWrapperTest, NotChosenStepBeginPropMsg) { int ret = 0; bool write = false; std::unique_ptr<Message> rsp_msg = nullptr; Message begin_prop_msg; begin_prop_msg.set_type(MessageType::BEGIN_PROP); set_key(begin_prop_msg, test_logid); begin_prop_msg.set_index(test_index); begin_prop_msg.set_to(selfid); set_test_accepted_value(begin_prop_msg); auto pins_impl = EmptyPIns(test_index); auto pins_state = EmptyPInsState(pins_impl.index()); PInsWrapper pins_wrapper(pins_state.get(), pins_impl); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(begin_prop_msg); assert(true == write); assert(nullptr != rsp_msg); assert(0 < pins_impl.proposed_num()); assert(pins_impl.has_promised_num()); assert(pins_impl.promised_num() == pins_impl.proposed_num()); assert(MessageType::PROP == rsp_msg->type()); assert(test_index == rsp_msg->index()); assert(0 == rsp_msg->to()); // broad-cast assert(rsp_msg->proposed_num() == pins_impl.proposed_num()); } TEST(PInsWrapperTest, NotChosenStepBeginFastPropMsg) { int ret = 0; bool write = false; std::unique_ptr<Message> rsp_msg = nullptr; Message fbegin_prop_msg; fbegin_prop_msg.set_type(MessageType::BEGIN_FAST_PROP); set_key(fbegin_prop_msg, test_logid); fbegin_prop_msg.set_index(test_index); fbegin_prop_msg.set_to(selfid); set_test_accepted_value(fbegin_prop_msg); auto pins_impl = EmptyPIns(test_index); auto pins_state = EmptyPInsState(pins_impl.index()); PInsWrapper pins_wrapper(pins_state.get(), pins_impl); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(fbegin_prop_msg); assert(true == write); assert(nullptr != rsp_msg); assert(0 < pins_impl.proposed_num()); assert(pins_impl.has_promised_num()); assert(pins_impl.has_accepted_num()); check_entry_equal( fbegin_prop_msg.accepted_value(), pins_impl.accepted_value()); assert(MessageType::FAST_ACCPT == rsp_msg->type()); assert(test_index == rsp_msg->index()); assert(0 == rsp_msg->to()); assert(rsp_msg->proposed_num() == pins_impl.proposed_num()); assert(rsp_msg->has_accepted_value()); check_entry_equal( fbegin_prop_msg.accepted_value(), rsp_msg->accepted_value()); } TEST(PInsWrapperTest, NotChosenStepTryPropMsg) { int ret = 0; bool write = false; std::unique_ptr<Message> rsp_msg = nullptr; Message try_prop_msg; try_prop_msg.set_type(MessageType::TRY_PROP); set_key(try_prop_msg, test_logid); try_prop_msg.set_index(test_index); try_prop_msg.set_to(selfid); set_test_accepted_value(try_prop_msg); try_prop_msg.mutable_accepted_value()->set_reqid(0); assert(0 == try_prop_msg.accepted_value().reqid()); auto pins_impl = EmptyPIns(test_index); auto pins_state = EmptyPInsState(pins_impl.index()); PInsWrapper pins_wrapper(pins_state.get(), pins_impl); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(try_prop_msg); assert(true == write); assert(nullptr != rsp_msg); assert(0 < pins_impl.proposed_num()); assert(pins_impl.has_promised_num()); assert(false == pins_impl.has_accepted_num()); assert(MessageType::PROP == rsp_msg->type()); assert(test_index == rsp_msg->index()); assert(0 == rsp_msg->to()); assert(rsp_msg->proposed_num() == pins_impl.proposed_num()); } TEST(PInsWrapperTest, NotChosenStepPropRspMsg) { int ret = 0; bool write = false; std::unique_ptr<Message> rsp_msg = nullptr; std::unique_ptr<paxos::PInsAliveState> pins_state; PaxosInstance pins_impl; std::tie(pins_state, pins_impl) = WaitPropRsp(); PInsWrapper pins_wrapper(pins_state.get(), pins_impl); Message prop_rsp_msg; prop_rsp_msg.set_type(MessageType::PROP_RSP); set_key(prop_rsp_msg, test_logid); prop_rsp_msg.set_index(test_index); prop_rsp_msg.set_from(2); prop_rsp_msg.set_to(selfid); prop_rsp_msg.set_proposed_num(pins_impl.proposed_num()); // case 1 prop_rsp_msg.set_promised_num( cutils::PropNumGen(3, 0).Next(pins_impl.proposed_num())); assert(prop_rsp_msg.promised_num() > pins_impl.proposed_num()); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(prop_rsp_msg); assert(false == write); assert(nullptr == rsp_msg); // case 2 prop_rsp_msg.set_from(3); prop_rsp_msg.set_promised_num(prop_rsp_msg.proposed_num()); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(prop_rsp_msg); assert(true == write); assert(nullptr != rsp_msg); assert(MessageType::ACCPT == rsp_msg->type()); assert(test_index == rsp_msg->index()); assert(selfid == rsp_msg->from()); assert(0 == rsp_msg->to()); assert(pins_impl.proposed_num() == rsp_msg->proposed_num()); assert(pins_impl.has_accepted_value()); } TEST(PInsWrapperTest, NotChosenStepAccptRspMsg) { int ret = 0; bool write = false; std::unique_ptr<Message> rsp_msg = nullptr; std::unique_ptr<paxos::PInsAliveState> pins_state; PaxosInstance pins_impl; std::tie(pins_state, pins_impl) = WaitAccptRsp(1); PInsWrapper pins_wrapper(pins_state.get(), pins_impl); Message accpt_rsp_msg; accpt_rsp_msg.set_type(MessageType::ACCPT_RSP); set_key(accpt_rsp_msg, test_logid); accpt_rsp_msg.set_index(test_index); accpt_rsp_msg.set_from(2); accpt_rsp_msg.set_to(selfid); accpt_rsp_msg.set_proposed_num(pins_impl.proposed_num()); // case 1 accpt_rsp_msg.set_accepted_num(0); accpt_rsp_msg.set_promised_num( cutils::PropNumGen(3, 0).Next(pins_impl.proposed_num())); assert(accpt_rsp_msg.promised_num() > pins_impl.proposed_num()); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(accpt_rsp_msg); assert(false == write); assert(nullptr == rsp_msg); // case 2 accpt_rsp_msg.set_from(3); accpt_rsp_msg.clear_promised_num(); accpt_rsp_msg.set_accepted_num(accpt_rsp_msg.proposed_num()); assert(accpt_rsp_msg.proposed_num() == pins_impl.proposed_num()); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(accpt_rsp_msg); assert(false == write); // mark chosen, but not need write disk assert(nullptr != rsp_msg); assert(MessageType::CHOSEN == rsp_msg->type()); assert(pins_wrapper.IsChosen()); assert(pins_state->IsChosen()); assert(test_index == rsp_msg->index()); assert(selfid == rsp_msg->from()); assert(0 == rsp_msg->to()); assert(rsp_msg->has_accepted_value()); } TEST(PInsWrapperTest, NotChosenStepFastAccptRspMsg) { int ret = 0; bool write = false; std::unique_ptr<Message> rsp_msg = nullptr; std::unique_ptr<paxos::PInsAliveState> pins_state; PaxosInstance pins_impl; std::tie(pins_state, pins_impl) = WaitFastAccptRsp(); PInsWrapper pins_wrapper(pins_state.get(), pins_impl); Message faccpt_rsp_msg; faccpt_rsp_msg.set_type(MessageType::FAST_ACCPT_RSP); set_key(faccpt_rsp_msg, test_logid); faccpt_rsp_msg.set_index(test_index); faccpt_rsp_msg.set_from(2); faccpt_rsp_msg.set_to(selfid); faccpt_rsp_msg.set_proposed_num(pins_impl.proposed_num()); // case 1 faccpt_rsp_msg.set_accepted_num(0); faccpt_rsp_msg.set_promised_num( cutils::PropNumGen(3, 0).Next(pins_impl.proposed_num())); assert(faccpt_rsp_msg.promised_num() > pins_impl.proposed_num()); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(faccpt_rsp_msg); assert(false == write); assert(nullptr == rsp_msg); // case 2 faccpt_rsp_msg.set_from(3); faccpt_rsp_msg.clear_promised_num(); faccpt_rsp_msg.set_accepted_num(faccpt_rsp_msg.proposed_num()); assert(faccpt_rsp_msg.proposed_num() == pins_impl.proposed_num()); std::tie(ret, write, rsp_msg) = pins_wrapper.Step(faccpt_rsp_msg); assert(false == write); assert(nullptr != rsp_msg); assert(MessageType::CHOSEN == rsp_msg->type()); assert(pins_wrapper.IsChosen()); assert(pins_state->IsChosen()); assert(test_index == rsp_msg->index()); assert(selfid == rsp_msg->from()); assert(0 == rsp_msg->to()); assert(rsp_msg->has_accepted_value()); }
27,797
2,023
<reponame>tdiprima/code import lxml.etree as et def data2xml(d, name='data'): r = et.Element(name) return et.tostring(buildxml(r, d)) def buildxml(r, d): if isinstance(d, dict): for k, v in d.iteritems(): s = et.SubElement(r, k) buildxml(s, v) elif isinstance(d, tuple) or isinstance(d, list): for v in d: s = et.SubElement(r, 'i') buildxml(s, v) elif isinstance(d, basestring): r.text = d else: r.text = str(d) return r print data2xml({'a':[1,2,('c',{'d':'e'})],'f':'g'}) # <data><a><i>1</i><i>2</i><i><i>c</i><i><d>e</d></i></i></a><f>g</f></data>
363
4,012
<gh_stars>1000+ /* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/io/text/data_chunk_source_factories.hpp> #include <cudf/io/text/multibyte_split.hpp> #include <cudf/strings/strings_column_view.hpp> using namespace cudf; using namespace test; // 😀 | F0 9F 98 80 | 11110000 10011111 10011000 10000000 // 😎 | F0 9F 98 8E | 11110000 10011111 10011000 10001110 struct MultibyteSplitTest : public BaseFixture { }; TEST_F(MultibyteSplitTest, NondeterministicMatching) { auto delimiter = std::string("abac"); auto host_input = std::string("ababacabacab"); auto expected = strings_column_wrapper{"ababac", "abac", "ab"}; auto source = cudf::io::text::make_source(host_input); auto out = cudf::io::text::multibyte_split(*source, delimiter); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *out); } TEST_F(MultibyteSplitTest, DelimiterAtEnd) { auto delimiter = std::string(":"); auto host_input = std::string("abcdefg:"); auto expected = strings_column_wrapper{"abcdefg:", ""}; auto source = cudf::io::text::make_source(host_input); auto out = cudf::io::text::multibyte_split(*source, delimiter); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *out); } TEST_F(MultibyteSplitTest, LargeInput) { auto host_input = std::string(); auto host_expected = std::vector<std::string>(); for (auto i = 0; i < (2 * 32 * 128 * 1024); i++) { host_input += "...:|"; host_expected.emplace_back(std::string("...:|")); } host_expected.emplace_back(std::string("")); auto expected = strings_column_wrapper{host_expected.begin(), host_expected.end()}; auto delimiter = std::string("...:|"); auto source = cudf::io::text::make_source(host_input); auto out = cudf::io::text::multibyte_split(*source, delimiter); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *out); } TEST_F(MultibyteSplitTest, OverlappingMatchErasure) { auto delimiter = "::"; auto host_input = std::string( ":::::" ":::::"); auto expected = strings_column_wrapper{":::::", ":::::"}; auto source = cudf::io::text::make_source(host_input); auto out = cudf::io::text::multibyte_split(*source, delimiter); // CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *out); // this use case it not yet supported. } TEST_F(MultibyteSplitTest, HandpickedInput) { auto delimiters = "::|"; auto host_input = std::string( "aaa::|" "bbb::|" "ccc::|" "ddd::|" "eee::|" "fff::|" "ggg::|" "hhh::|" "___::|" "here::|" "is::|" "another::|" "simple::|" "text::|" "seperated::|" "by::|" "emojis::|" "which::|" "are::|" "multiple::|" "bytes::|" "and::|" "used::|" "as::|" "delimiters.::|" "::|" "::|" "::|"); auto expected = strings_column_wrapper{ "aaa::|", "bbb::|", "ccc::|", "ddd::|", "eee::|", "fff::|", "ggg::|", "hhh::|", "___::|", "here::|", "is::|", "another::|", "simple::|", "text::|", "seperated::|", "by::|", "emojis::|", "which::|", "are::|", "multiple::|", "bytes::|", "and::|", "used::|", "as::|", "delimiters.::|", "::|", "::|", "::|", ""}; auto source = cudf::io::text::make_source(host_input); auto out = cudf::io::text::multibyte_split(*source, delimiters); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *out, debug_output_level::ALL_ERRORS); }
1,790
14,668
#!/usr/bin/env vpython3 # Copyright 2021 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import unittest import six if six.PY3: import unittest.mock as mock from pyfakefs import fake_filesystem_unittest from blinkpy.web_tests.stale_expectation_removal import constants from blinkpy.web_tests.stale_expectation_removal import expectations def CreateFile(fs, *args, **kwargs): # TODO(crbug.com/1156806): Remove this and just use fs.create_file() when # Catapult is updated to a newer version of pyfakefs that is compatible # with Chromium's version. if hasattr(fs, 'create_file'): fs.create_file(*args, **kwargs) else: fs.CreateFile(*args, **kwargs) @unittest.skipIf(six.PY2, 'Script and unittest are Python 3-only') class GetExpectationFilepathsUnittest(fake_filesystem_unittest.TestCase): def setUp(self): self.setUpPyfakefs() self.instance = expectations.WebTestExpectations() CreateFile( self.fs, os.path.join(constants.WEB_TEST_ROOT_DIR, 'FlagExpectations', 'README.txt')) def testRealFilesCanBeFound(self): """Tests that real files are returned.""" with fake_filesystem_unittest.Pause(self): filepaths = self.instance.GetExpectationFilepaths() self.assertTrue(len(filepaths) > 0) for f in filepaths: self.assertTrue(os.path.exists(f)) def testTopLevelFiles(self): """Tests that top-level expectation files are properly returned.""" with mock.patch.object(self.instance, '_GetTopLevelExpectationFiles', return_value=['/foo']): filepaths = self.instance.GetExpectationFilepaths() self.assertEqual(filepaths, ['/foo']) def testFlagSpecificFiles(self): """Tests that flag-specific files are properly returned.""" flag_filepath = os.path.join(constants.WEB_TEST_ROOT_DIR, 'FlagExpectations', 'foo-flag') CreateFile(self.fs, flag_filepath) with mock.patch.object(self.instance, '_GetTopLevelExpectationFiles', return_value=[]): filepaths = self.instance.GetExpectationFilepaths() self.assertEqual(filepaths, [flag_filepath]) def testAllExpectationFiles(self): """Tests that both top level and flag-specific files are returned.""" flag_filepath = os.path.join(constants.WEB_TEST_ROOT_DIR, 'FlagExpectations', 'foo-flag') CreateFile(self.fs, flag_filepath) with mock.patch.object(self.instance, '_GetTopLevelExpectationFiles', return_value=['/foo']): filepaths = self.instance.GetExpectationFilepaths() self.assertEqual(filepaths, ['/foo', flag_filepath]) @unittest.skipIf(six.PY2, 'Script and unittest are Python 3-only') class GetExpectationFileTagHeaderUnittest(fake_filesystem_unittest.TestCase): def setUp(self): self.setUpPyfakefs() self.instance = expectations.WebTestExpectations() def testRealContentsCanBeLoaded(self): """Tests that some sort of valid content can be read from the file.""" with fake_filesystem_unittest.Pause(self): header = self.instance._GetExpectationFileTagHeader( expectations.MAIN_EXPECTATION_FILE) self.assertIn('tags', header) self.assertIn('results', header) def testContentLoading(self): """Tests that the header is properly loaded.""" header_contents = """\ # foo # bar # baz not a comment """ CreateFile(self.fs, expectations.MAIN_EXPECTATION_FILE) with open(expectations.MAIN_EXPECTATION_FILE, 'w') as f: f.write(header_contents) header = self.instance._GetExpectationFileTagHeader( expectations.MAIN_EXPECTATION_FILE) expected_header = """\ # foo # bar # baz """ self.assertEqual(header, expected_header) if __name__ == '__main__': unittest.main(verbosity=2)
1,905
3,799
#!/usr/bin/python3 # # Copyright (C) 2020 The Android Open Source Project # # 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. # from ReleaseNoteMarkdown import * from GitClient import CommitType, getTitleFromCommitType, getChangeIdAOSPLink, getBuganizerLink class CommitMarkdownList: """Generates the markdown list of commits with sections defined by enum [CommitType], in the format: **New Features** - <[Commit.summary]> <[getChangeIdAOSPLink]> <[getBuganizerLink] 1> <[getBuganizerLink] 2>... **API Changes** - <[Commit.summary]> <[getChangeIdAOSPLink]> <[getBuganizerLink] 1> <[getBuganizerLink] 2>... **Bug Fixes** - <[Commit.summary]> <[getChangeIdAOSPLink]> <[getBuganizerLink] 1> <[getBuganizerLink] 2>... **External Contribution** - <[Commit.summary]> <[getChangeIdAOSPLink]> <[getBuganizerLink] 1> <[getBuganizerLink] 2>... """ def __init__(self, commits=[], forceIncludeAllCommits=False): self.forceIncludeAllCommits = forceIncludeAllCommits self.commits = commits def add(self, commit): self.commits.append(commit) def getListItemStr(self): return "- " def formatReleaseNoteString(self, commit): if commit.releaseNote != "": releaseNoteString = commit.releaseNote else: releaseNoteString = self.getListItemStr() + commit.summary newLineCharCount = releaseNoteString.count("\n") if releaseNoteString[-1] == "\n": newLineCharCount = newLineCharCount - 1 releaseNoteString = releaseNoteString.replace("\n", "\n ", newLineCharCount) releaseNoteString += " (" + str(getChangeIdAOSPLink(commit.changeId)) for bug in commit.bugs: releaseNoteString += ", " + str(getBuganizerLink(bug)) releaseNoteString += ")" return self.getListItemStr() + releaseNoteString def makeReleaseNotesSection(self, sectionCommitType): sectionHeader = MarkdownBoldText(getTitleFromCommitType(sectionCommitType)) markdownStringSection = "" for commit in self.commits: if commit.changeType != sectionCommitType: continue commitString = self.formatReleaseNoteString(commit) if self.forceIncludeAllCommits or commit.releaseNote != "": markdownStringSection = markdownStringSection + commitString if markdownStringSection[-1] != '\n': markdownStringSection += '\n' markdownStringSection = "\n%s\n\n%s" % (sectionHeader, markdownStringSection) return markdownStringSection def __str__(self): markdownString = "" for commitType in CommitType: markdownString += self.makeReleaseNotesSection(commitType) return markdownString class GitilesDiffLogLink(MarkdownLink): def __str__(self): return "[%s](%s)" % (self.linkText, self.linkUrl) def getGitilesDiffLogLink(version, startSHA, endSHA, projectDir): """ @param startSHA the SHA at which to start the diff log (exclusive) @param endSHA the last SHA to include in the diff log (inclusive) @param projectDir the local directory of the project, in relation to frameworks/support @return A [MarkdownLink] to the public Gitiles diff log """ baseGitilesUrl = "https://android.googlesource.com/platform/frameworks/support/+log/" # The root project directory is already existent in the url path, so the directory here # should be relative to frameworks/support/. if ("frameworks/support" in projectDir): print_e("Gitiles directory should be relative to frameworks/support; received incorrect directory: $projectDir") exit(1) if startSHA != "": return GitilesDiffLogLink("Version %s contains these commits." % version, "%s%s..%s/%s" % (baseGitilesUrl, startSHA, endSHA, projectDir)) else: return GitilesDiffLogLink("Version %s contains these commits." % version, "%s%s/%s" % (baseGitilesUrl, endSHA, projectDir)) class LibraryHeader(MarkdownHeader): """ Markdown class for a Library Header in the format: ### Version <version> {:#<artifactIdTag-version>} An artifactId tag is required because artifactIds may be can be grouped by version, in which case the tag is not obvious """ def __init__(self, groupId="", version="", artifactIdTag=""): self.markdownType = HeaderType.H3 self.text = "%s Version %s {:#%s%s}" % (groupId, version, artifactIdTag, version) class ChannelSummaryItem: """Generates the summary list item in the channel.md pages, which take the format: * [<Title> Version <version>](/jetpack/androidx/releases/<groupid>#<version>) where <header> is usually the GroupId. """ def __init__(self, formattedTitle, groupId, version, artifactIdTag=""): self.text = "* [%s Version %s](/jetpack/androidx/releases/%s#%s%s)\n" % (formattedTitle, version, groupId.lower(), artifactIdTag, version) def __str__(self): return self.text class LibraryReleaseNotes: """ Structured release notes class, that connects all parts of the release notes. Creates release notes in the format: <pre> <[LibraryHeader]> <Date> `androidx.<groupId>:<artifactId>:<version>` is released. The commits included in this version can be found <[MarkdownLink]>. <[CommitMarkdownList]> </pre> """ def __init__(self, groupId, artifactIds, version, releaseDate, fromSHA, untilSHA, projectDir, requiresSameVersion, commitList=[], forceIncludeAllCommits=False): """ @property groupId Library GroupId. @property artifactIds List of ArtifactIds included in these release notes. @property version Version of the library, assuming all artifactIds have the same version. @property releaseDate Date the release will go live. Defaults to the current date. @property fromSHA The oldest SHA to which to query for release notes. It will be excluded from release notes, but the next newer SHA will be included. @property untilSHA The newest SHA to be included in the release notes. @property projectDir The filepath relative to the parent directory of the .git directory. @property requiresSameVersion True if the groupId of this module requires the same version for all artifactIds in the groupId. When true, uses the GroupId for the release notes header. When false, uses the list of artifactIds for the header. @property commitList The initial list of Commits to include in these release notes. Defaults to an empty list. Users can always add more commits with [LibraryReleaseNotes.addCommit] @param forceIncludeAllCommits Set to true to include all commits, both with and without a release note field in the commit message. Defaults to false, which means only commits with a release note field are included in the release notes. """ self.groupId = groupId self.artifactIds = artifactIds self.version = version self.releaseDate = MarkdownDate(releaseDate) self.fromSHA = fromSHA self.untilSHA = untilSHA self.projectDir = projectDir self.commitList = commitList self.requiresSameVersion = requiresSameVersion self.forceIncludeAllCommits = forceIncludeAllCommits self.diffLogLink = MarkdownLink() self.commits = commitList self.commitMarkdownList = CommitMarkdownList(commitList, forceIncludeAllCommits) self.summary = "" self.bugsFixed = [] self.channelSummary = None if version == "" or groupId == "": raise RuntimeError("Tried to create Library Release Notes Header without setting " + "the groupId or version!") if requiresSameVersion: formattedGroupId = groupId.replace("androidx.", "") formattedGroupId = self.capitalizeTitle(formattedGroupId) self.header = LibraryHeader(formattedGroupId, version) self.channelSummary = ChannelSummaryItem(formattedGroupId, formattedGroupId, version) else: artifactIdTag = artifactIds[0] + "-" if len(artifactIds) == 1 else "" formattedArtifactIds = (" ".join(artifactIds)) if len(artifactIds) > 3: formattedArtifactIds = groupId.replace("androidx.", "") formattedArtifactIds = self.capitalizeTitle(formattedArtifactIds) self.header = LibraryHeader(formattedArtifactIds, version, artifactIdTag) formattedGroupId = groupId.replace("androidx.", "") self.channelSummary = ChannelSummaryItem(formattedArtifactIds, formattedGroupId, version, artifactIdTag) self.diffLogLink = getGitilesDiffLogLink(version, fromSHA, untilSHA, projectDir) def getFormattedReleaseSummary(self): numberArtifacts = len(self.artifactIds) for i in range(0, numberArtifacts): currentArtifactId = self.artifactIds[i] if numberArtifacts == 1: self.summary = "`%s:%s:%s` is released. " % (self.groupId, currentArtifactId, self.version) elif numberArtifacts == 2: if i == 0: self.summary = "`%s:%s:%s` and " % (self.groupId, currentArtifactId, self.version) if i == 1: self.summary += "`%s:%s:%s` are released. " % (self.groupId, currentArtifactId, self.version) elif numberArtifacts == 3: if (i < numberArtifacts - 1): self.summary += "`%s:%s:%s`, " % (self.groupId, currentArtifactId, self.version) else: self.summary += "and `%s:%s:%s` are released. " % (self.groupId, currentArtifactId, self.version) else: commonArtifactIdSubstring = self.artifactIds[0].split('-')[0] self.summary = "`%s:%s-*:%s` is released. " % ( self.groupId, commonArtifactIdSubstring, self.version ) self.summary += "%s\n" % self.diffLogLink return self.summary def capitalizeTitle(self, artifactWord): artifactWord = artifactWord.title() keywords = ["Animated", "Animation", "Callback", "Compat", "Drawable", "File", "Layout", "Pager", "Pane", "Parcelable", "Provider", "Refresh", "SQL", "State", "TV", "Target", "View", "Inflater"] for keyword in keywords: artifactWord = artifactWord.replace(keyword.lower(), keyword) return artifactWord def addCommit(self, newCommit): for bug in newCommit.bugs: bugsFixed.append(bug) commits.append(newCommit) commitMarkdownList.add(newCommit) def __str__(self): return "%s\n%s\n\n%s%s" % (self.header, self.releaseDate, self.getFormattedReleaseSummary(), self.commitMarkdownList)
3,409
619
/* * Authors: <NAME> <<EMAIL>> * Copyright (c) 2016 Intel Corporation. * * This program and the accompanying materials are made available under the * terms of the The MIT License which is available at * https://opensource.org/licenses/MIT. * * SPDX-License-Identifier: MIT */ #ifndef UPM_PRESSURE_H_ #define UPM_PRESSURE_H_ #ifdef __cplusplus extern "C" { #endif // Pressure function table typedef struct _upm_pressure_ft { upm_result_t (*upm_pressure_set_scale) (void* dev, float scale); upm_result_t (*upm_pressure_set_offset) (void* dev, float offset); upm_result_t (*upm_pressure_get_value) (void* dev, float* value); } upm_pressure_ft; #ifdef __cplusplus } #endif #endif /* UPM_PRESSURE_H_ */
263
511
/* * Interaction with the T20 driver * Copyright (c) 2016, Samsung Electronics Co., Ltd. */ #include "includes.h" #include "driver.h" #ifdef CONFIG_SCSC_WLAN extern void *slsi_t20_init(void *ctx, const char *ifname, void *global_priv); extern void slsi_t20_deinit(void *priv); extern const u8 *slsi_get_mac_addr(void *priv); extern int slsi_t20_get_capa(void *priv, struct wpa_driver_capa *capa); extern int slsi_hw_scan(void *priv, struct wpa_driver_scan_params *params); extern struct wpa_scan_results *slsi_get_scan_results(void *priv); extern int slsi_connect(void *priv, struct wpa_driver_associate_params *params); extern int slsi_disconnect(void *priv, const u8 *addr, int reason_code); extern int slsi_start_ap(void *priv, struct wpa_driver_ap_params *settings); extern int slsi_stop_ap(void *priv); extern int slsi_del_station(void *priv, const u8 *addr, int reason); extern ssize_t slsi_set_country(void *priv, const char *country_code); extern ssize_t slsi_get_country(void *priv, char *country_code); extern int slsi_set_rts(void *priv, int rts); extern int slsi_get_signal_poll(void *priv, struct wpa_signal_info *si); extern int slsi_set_frag_threshold(void *priv, int frag_threshold); extern int slsi_get_ap_bssid(void *priv, u8 *bssid); extern struct hostapd_hw_modes *slsi_get_hw_feature_data(void *priv, u16 *num_modes, u16 *flags); extern int slsi_mlme_send_ap_eapol(void *priv, const u8 *addr, const u8 *data, size_t data_len, int encrypt, const u8 *own_addr, u32 flags); extern int slsi_get_key(const char *ifname, void *priv, const u8 *addr, int idx, u8 *seq); extern int slsi_set_tx_power(void *priv, int dbm); extern int slsi_get_tx_power(void *priv); extern int slsi_set_panic(void *priv); //extern struct wireless_dev *slsi_add_virtual_intf(struct wiphy *wiphy, const char *name, enum nl80211_iftype type, u32 *flags, struct vif_params *params); extern int slsi_add_key(const char *ifname, void *priv, enum wpa_alg alg, const u8 *mac_addr, int key_idx, int set_tx, const u8 *seq, size_t seq_len, const u8 *key, size_t key_len); extern int slsi_get_ssid(void *priv, u8 *ssid); int slsi_sta_remove(void *priv, const u8 *addr) { return slsi_del_station(priv, addr, 0); } int slsi_sta_deauth(void *priv, const u8 *own_addr, const u8 *addr, int reason) { return slsi_del_station(priv, addr, reason); } const struct wpa_driver_ops wpa_driver_t20_ops = { .name = "slsi_t20", .desc = "SLSI T20 Driver", .init2 = slsi_t20_init, .deinit = slsi_t20_deinit, .get_mac_addr = slsi_get_mac_addr, .get_capa = slsi_t20_get_capa, .scan2 = slsi_hw_scan, .get_scan_results2 = slsi_get_scan_results, .associate = slsi_connect, .deauthenticate = slsi_disconnect, .set_ap = slsi_start_ap, .stop_ap = slsi_stop_ap, .sta_remove = slsi_sta_remove, .sta_deauth = slsi_sta_deauth, .set_frag = slsi_set_frag_threshold, .set_rts = slsi_set_rts, .signal_poll = slsi_get_signal_poll, .get_country = slsi_get_country, .set_country = slsi_set_country, .get_bssid = slsi_get_ap_bssid, .get_hw_feature_data = slsi_get_hw_feature_data, .set_key = slsi_add_key, .get_ssid = slsi_get_ssid, .hapd_send_eapol = slsi_mlme_send_ap_eapol, .get_seqnum = slsi_get_key, .set_tx_power = slsi_set_tx_power, .get_tx_power = slsi_get_tx_power, .set_panic = slsi_set_panic, // .if_add = slsi_add_virtual_intf }; #else int slsi_sta_remove(void *priv, const u8 *addr) { return 0; } int slsi_sta_deauth(void *priv, const u8 *own_addr, const u8 *addr, int reason) { return 0; } const struct wpa_driver_ops wpa_driver_t20_ops = { .name = "slsi_t20", .desc = "SLSI T20 Driver", }; #endif
1,513
881
<gh_stars>100-1000 /* * RESTinio */ /*! * @file * @brief Utilities for suppressing exceptions from some code block. * * @since v.0.6.0 */ #pragma once #include <restinio/impl/include_fmtlib.hpp> #include <restinio/null_logger.hpp> #include <exception> namespace restinio { namespace utils { // // Wrappers for logging with suppressing of exceptions. // template< typename Logger, typename Message_Builder > void log_trace_noexcept( Logger && logger, Message_Builder && builder ) noexcept { try { logger.trace( std::forward<Message_Builder>(builder) ); } catch( ... ) {} } template< typename Message_Builder > void log_trace_noexcept( null_logger_t &, Message_Builder && ) noexcept {} template< typename Logger, typename Message_Builder > void log_info_noexcept( Logger && logger, Message_Builder && builder ) noexcept { try { logger.info( std::forward<Message_Builder>(builder) ); } catch( ... ) {} } template< typename Message_Builder > void log_info_noexcept( null_logger_t &, Message_Builder && ) noexcept {} template< typename Logger, typename Message_Builder > void log_warn_noexcept( Logger && logger, Message_Builder && builder ) noexcept { try { logger.warn( std::forward<Message_Builder>(builder) ); } catch( ... ) {} } template< typename Message_Builder > void log_warn_noexcept( null_logger_t &, Message_Builder && ) noexcept {} template< typename Logger, typename Message_Builder > void log_error_noexcept( Logger && logger, Message_Builder && builder ) noexcept { try { logger.error( std::forward<Message_Builder>(builder) ); } catch( ... ) {} } template< typename Message_Builder > void log_error_noexcept( null_logger_t &, Message_Builder && ) noexcept {} /*! * @brief Helper function for execution a block of code with * suppression of any exceptions raised inside that block. * * Exceptions caught are logged via \a logger. Exceptions thrown during * this logging are suppressed. * * @since v.0.6.0 */ template< typename Logger, typename Lambda > void suppress_exceptions( //! Logger to be used. Logger && logger, //! Description of the block of code. //! Will be used for logging about exceptions caught. const char * block_description, //! Block of code for execution. Lambda && lambda ) noexcept { try { lambda(); } catch( const std::exception & x ) { log_error_noexcept( logger, [&] { return fmt::format( "an exception in '{}': {}", block_description, x.what() ); } ); } catch( ... ) { log_error_noexcept( logger, [&] { return fmt::format( "an unknown exception in '{}'", block_description ); } ); } } /*! * @brief Helper function for execution a block of code with * suppression of any exceptions raised inside that block. * * All exceptions are simply intercepted. Nothing is logged in the * case of an exception thrown. * * @since v.0.6.0 */ template< typename Lambda > void suppress_exceptions_quietly( Lambda && lambda ) noexcept { try { lambda(); } catch( ... ) {} } } /* namespace utils */ } /* namespace restinio */
1,026
837
<filename>app/src/main/java/me/saket/dank/ui/submission/adapter/package-info.java @ParametersAreNonnullByDefault package me.saket.dank.ui.submission.adapter; import javax.annotation.ParametersAreNonnullByDefault;
78
521
<gh_stars>100-1000 /* @(#)e_atan2.c 5.1 93/09/24 */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ #include <LibConfig.h> #include <sys/EfiCdefs.h> #if defined(LIBM_SCCS) && !defined(lint) __RCSID("$NetBSD: e_atan2.c,v 1.12 2002/05/26 22:01:48 wiz Exp $"); #endif #if defined(_MSC_VER) /* Handle Microsoft VC++ compiler specifics. */ // unary minus operator applied to unsigned type, result still unsigned #pragma warning ( disable : 4146 ) #endif /* __ieee754_atan2(y,x) * Method : * 1. Reduce y to positive by atan2(y,x)=-atan2(-y,x). * 2. Reduce x to positive by (if x and y are unexceptional): * ARG (x+iy) = arctan(y/x) ... if x > 0, * ARG (x+iy) = pi - arctan[y/(-x)] ... if x < 0, * * Special cases: * * ATAN2((anything), NaN ) is NaN; * ATAN2(NAN , (anything) ) is NaN; * ATAN2(+-0, +(anything but NaN)) is +-0 ; * ATAN2(+-0, -(anything but NaN)) is +-pi ; * ATAN2(+-(anything but 0 and NaN), 0) is +-pi/2; * ATAN2(+-(anything but INF and NaN), +INF) is +-0 ; * ATAN2(+-(anything but INF and NaN), -INF) is +-pi; * ATAN2(+-INF,+INF ) is +-pi/4 ; * ATAN2(+-INF,-INF ) is +-3pi/4; * ATAN2(+-INF, (anything but,0,NaN, and INF)) is +-pi/2; * * Constants: * The hexadecimal values are the intended ones for the following * constants. The decimal values may be used, provided that the * compiler will convert from decimal to binary accurately enough * to produce the hexadecimal values shown. */ #include "math.h" #include "math_private.h" static const double tiny = 1.0e-300, zero = 0.0, pi_o_4 = 7.8539816339744827900E-01, /* 0x3FE921FB, 0x54442D18 */ pi_o_2 = 1.5707963267948965580E+00, /* 0x3FF921FB, 0x54442D18 */ pi = 3.1415926535897931160E+00, /* 0x400921FB, 0x54442D18 */ pi_lo = 1.2246467991473531772E-16; /* 0x3CA1A626, 0x33145C07 */ double __ieee754_atan2(double y, double x) { double z; int32_t k,m,hx,hy,ix,iy; u_int32_t lx,ly; EXTRACT_WORDS(hx,lx,x); ix = hx&0x7fffffff; EXTRACT_WORDS(hy,ly,y); iy = hy&0x7fffffff; if(((ix|((lx|-lx)>>31))>0x7ff00000)|| ((iy|((ly|-ly)>>31))>0x7ff00000)) /* x or y is NaN */ return x+y; if(((hx-0x3ff00000)|lx)==0) return atan(y); /* x=1.0 */ m = ((hy>>31)&1)|((hx>>30)&2); /* 2*sign(x)+sign(y) */ /* when y = 0 */ if((iy|ly)==0) { switch(m) { case 0: case 1: return y; /* atan(+-0,+anything)=+-0 */ case 2: return pi+tiny;/* atan(+0,-anything) = pi */ case 3: return -pi-tiny;/* atan(-0,-anything) =-pi */ } } /* when x = 0 */ if((ix|lx)==0) return (hy<0)? -pi_o_2-tiny: pi_o_2+tiny; /* when x is INF */ if(ix==0x7ff00000) { if(iy==0x7ff00000) { switch(m) { case 0: return pi_o_4+tiny;/* atan(+INF,+INF) */ case 1: return -pi_o_4-tiny;/* atan(-INF,+INF) */ case 2: return 3.0*pi_o_4+tiny;/*atan(+INF,-INF)*/ case 3: return -3.0*pi_o_4-tiny;/*atan(-INF,-INF)*/ } } else { switch(m) { case 0: return zero ; /* atan(+...,+INF) */ case 1: return -zero ; /* atan(-...,+INF) */ case 2: return pi+tiny ; /* atan(+...,-INF) */ case 3: return -pi-tiny ; /* atan(-...,-INF) */ } } } /* when y is INF */ if(iy==0x7ff00000) return (hy<0)? -pi_o_2-tiny: pi_o_2+tiny; /* compute y/x */ k = (iy-ix)>>20; if(k > 60) z=pi_o_2+0.5*pi_lo; /* |y/x| > 2**60 */ else if(hx<0&&k<-60) z=0.0; /* |y|/x < -2**60 */ else z=atan(fabs(y/x)); /* safe to do y/x */ switch (m) { case 0: return z ; /* atan(+,+) */ case 1: { u_int32_t zh; GET_HIGH_WORD(zh,z); SET_HIGH_WORD(z,zh ^ 0x80000000); } return z ; /* atan(-,+) */ case 2: return pi-(z-pi_lo);/* atan(+,-) */ default: /* case 3 */ return (z-pi_lo)-pi;/* atan(-,-) */ } }
2,036
3,097
<filename>Wuxianda/Classes/Src/Home/Sub/recommend/Sub/Models/YPReplyRealContentModel.h // // YPReplyRealContentModel.h // Wuxianda // // Created by 胡云鹏 on 16/6/18. // Copyright © 2016年 michaelhuyp. All rights reserved. // #import <Foundation/Foundation.h> @interface YPReplyRealContentModel : NSObject /** members数组 */ @property (nonatomic, copy) NSArray *members; /** 评论内容 */ @property (nonatomic, copy) NSString *message; @property (nonatomic, copy) NSString *plat; @property (nonatomic, copy) NSString *device; @end /** { "message":"op之前,字幕组翻译的童谣解释,很像所谓的游戏规则,加上“光宗”多次提到的自相残杀,感觉很像狼人游戏。其中有七只鬼,八成是三十几个人中的七人,也可能有村庄的村民,不过那样角色就太多了。童谣说,吃过一次人后便忘不了,从第一次吃人开始,会在短期内连续吃人。鬼会每天工作结束后说想要吃人,显然鬼具有正常人类身份的时间段,就类似于狼人游戏中的“天亮天黑”,可能鬼会在天黑前这个时间段露出破绽,最美味的人是孩童,“孩童”就暂时认定为这些主人公吧,毕竟是“人生重来”,重生不应当从婴儿开始?“孩童”美味,而睡着了的孩童面目可憎,所谓面目可憎,应该不仅仅是丑陋,而是本能上的厌恶,也就应该是夜晚睡着的孩子不会被吃。童谣里说,鬼会把人吃的干干净净,但是会留下眼球,这里眼球应当是用来明示有一人被吃,而鬼可以选择承担可能死亡的风险,吞掉眼球来暂时隐瞒人的死亡。也不排除眼球还有其他未揭示的作用。拧断手脚便能使孩童不能动弹,鬼可以通过此手段限制孩童的行为,不过鬼理应在面对单独的孩童时占压倒性的优势,所以这条规则很可能是用于孩童使用的,即自相残杀中的自相残杀,孩童为求自保拧断其他孩童的手脚。女主角“真咲”(有几个记住她名字的╮(╯▽╰)╭)很显然就是狼人游戏中的“先知”,这样就不能排除其他人中拥有适用于游戏规则的特殊能力。因为是孩童被吃干净了,而且是现实中,可以拧断孩童的手脚,即不禁止孩童间互相伤害,所以类似“女巫”救人或毒死人的能力应当不会出现。在人物介绍中出现了情侣以及渴求伴侣的人,所以“情侣”这身份可能会出现,并拥有特殊规则,当然也可能仅仅是为复杂人物关系、情感。 以上皆是呓语,表打我_(:3」∠)_", "plat":2, "device":"", "members":Array[0] } */
1,673
1,371
<gh_stars>1000+ /* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * * */ package software.amazon.smithy.aws.go.codegen.customization; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import software.amazon.smithy.go.codegen.GoSettings; import software.amazon.smithy.go.codegen.integration.GoIntegration; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.IntegerShape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.traits.BoxTrait; import software.amazon.smithy.utils.MapUtils; import software.amazon.smithy.utils.SetUtils; /** * Integration that back fills the `boxed` traits to API shapes that were not decorated with the trait in the model. */ public class BackfillBoxTrait implements GoIntegration { private static final Logger LOGGER = Logger.getLogger(BackfillBoxTrait.class.getName()); /** * Map of service shape to Set of operation shapes that need to have this * presigned url auto fill customization. */ public static final Map<ShapeId, Set<ShapeId>> SERVICE_TO_MEMBER_MAP = MapUtils.of( ShapeId.from("com.amazonaws.s3control#AWSS3ControlServiceV20180820"), SetUtils.of( ShapeId.from("com.amazonaws.s3control#S3ExpirationInDays") )); /** * /** * Updates the API model to add additional members to the operation input shape that are needed for presign url * customization. * * @param model API model * @param settings Go codegen settings * @return updated API model */ @Override public Model preprocessModel(Model model, GoSettings settings) { ShapeId serviceId = settings.getService(); if (!SERVICE_TO_MEMBER_MAP.containsKey(serviceId)) { return model; } Model.Builder builder = model.toBuilder(); Set<ShapeId> shapeIds = SERVICE_TO_MEMBER_MAP.get(serviceId); for (ShapeId shapeId : shapeIds) { IntegerShape shape = model.expectShape(shapeId, IntegerShape.class); if (shape.getTrait(BoxTrait.class).isPresent()) { LOGGER.warning("BoxTrait is present in model and does not require backfill"); continue; } builder.addShape(shape.toBuilder() .addTrait(new BoxTrait()) .build()); } return builder.build(); } }
1,078
3,052
<reponame>yuyangdexue/iOS-InterviewQuestion-collection // // CommandManager.h // DesignPatten // // Created by yangyang38 on 2018/3/17. // Copyright © 2018年 yangyang. All rights reserved. // #import <Foundation/Foundation.h> #import "Command.h" @interface CommandManager : NSObject // 命令管理容器 @property (nonatomic, strong) NSMutableArray <Command*> *arrayCommands; // 命令管理者以单例方式呈现 + (instancetype)sharedInstance; // 执行命令 + (void)executeCommand:(Command *)cmd completion:(CommandCompletionCallBack)completion; // 取消命令 + (void)cancelCommand:(Command *)cmd; @end
243
348
<gh_stars>100-1000 {"nom":"Rotalier","circ":"1ère circonscription","dpt":"Jura","inscrits":145,"abs":61,"votants":84,"blancs":6,"nuls":1,"exp":77,"res":[{"nuance":"REM","nom":"<NAME>","voix":41},{"nuance":"LR","nom":"<NAME>","voix":36}]}
96
1,014
<reponame>electroniceel/Glasgow # Ref: https://static.docs.arm.com/ihi0031/c/IHI0031C_debug_interface_as.pdf # Document Number: IHI0031C # Accession: G00027 import logging import argparse from ....support.aobject import * from ....arch.jtag import * from ....arch.arm.jtag import * from ....arch.arm.dap.dp import * from ...interface.jtag_probe import JTAGProbeApplet from . import * class ARMJTAGDPInterface(ARMDPInterface, aobject): # Mask with all data link independent fields in the CTRL/STAT DP register. _DP_CTRL_STAT_mask = DP_CTRL_STAT( TRNMODE=0b11, TRNCNT=0xFFF, MASKLANE=0b1111, CDBGRSTREQ=0b1, CDBGRSTACK=0b1, CDBGPWRUPREQ=0b1, CDBGPWRUPACK=0b1, CSYSPWRUPREQ=0b1, CSYSPWRUPACK=0b1).to_int() async def __init__(self, interface, logger): self.lower = interface self._logger = logger self._level = logging.DEBUG if self._logger.name == __name__ else logging.TRACE self._select = DP_SELECT() await self.reset() def _log(self, message, *args): self._logger.log(self._level, "JTAG-DP: " + message, *args) # Low-level xPACC operations async def _write_dpacc(self, addr, value): await self.lower.write_ir(IR_DPACC) dr_update = DR_xPACC_update(RnW=0, A=(addr & 0xf) >> 2, DATAIN=value) # TODO: use JTAG masked compare when implemented dr_capture = DR_xPACC_capture.from_bits(await self.lower.exchange_dr(dr_update.to_bits())) assert dr_capture.ACK == DR_xPACC_ACK.OK_FAULT async def _read_dpacc(self, addr): await self.lower.write_ir(IR_DPACC) dr_update = DR_xPACC_update(RnW=1, A=(addr & 0xf) >> 2) # TODO: use JTAG masked compare when implemented dr_capture = DR_xPACC_capture.from_bits(await self.lower.exchange_dr(dr_update.to_bits())) assert dr_capture.ACK == DR_xPACC_ACK.OK_FAULT # TODO: pick a better nop than repeated read? dr_capture = DR_xPACC_capture.from_bits(await self.lower.exchange_dr(dr_update.to_bits())) assert dr_capture.ACK == DR_xPACC_ACK.OK_FAULT return dr_capture.ReadResult async def _poll_apacc(self): await self.lower.write_ir(IR_DPACC) dp_update_bits = DR_xPACC_update(RnW=1, A=DP_CTRL_STAT_addr >> 2).to_bits() while True: ap_capture = DR_xPACC_capture.from_bits(await self.lower.exchange_dr(dp_update_bits)) if ap_capture.ACK != DR_xPACC_ACK.WAIT: break self._log("ap wait") assert ap_capture.ACK == DR_xPACC_ACK.OK_FAULT dp_capture = DR_xPACC_capture.from_bits(await self.lower.exchange_dr(dp_update_bits)) assert dp_capture.ACK == DR_xPACC_ACK.OK_FAULT dp_ctrl_stat = DP_CTRL_STAT.from_int(dp_capture.ReadResult) assert not dp_ctrl_stat.STICKYORUN, "AP transaction overrun" if dp_ctrl_stat.STICKYERR: dp_update_bits = DR_xPACC_update( RnW=0, A=DP_CTRL_STAT_addr >> 2, DATAIN=dp_ctrl_stat.to_int()).to_bits() dp_capture = DR_xPACC_capture.from_bits(await self.lower.exchange_dr(dp_update_bits)) assert dp_capture.ACK == DR_xPACC_ACK.OK_FAULT raise ARMAPTransactionError("AP transaction error") else: return ap_capture.ReadResult async def _write_apacc(self, addr, value): await self.lower.write_ir(IR_APACC) dr_update = DR_xPACC_update(RnW=0, A=(addr & 0xf) >> 2, DATAIN=value) # TODO: use JTAG masked compare when implemented dr_capture = DR_xPACC_capture.from_bits(await self.lower.exchange_dr(dr_update.to_bits())) assert dr_capture.ACK == DR_xPACC_ACK.OK_FAULT await self._poll_apacc() async def _read_apacc(self, addr): await self.lower.write_ir(IR_APACC) dr_update = DR_xPACC_update(RnW=1, A=(addr & 0xf) >> 2) # TODO: use JTAG masked compare when implemented dr_capture = DR_xPACC_capture.from_bits(await self.lower.exchange_dr(dr_update.to_bits())) assert dr_capture.ACK == DR_xPACC_ACK.OK_FAULT return await self._poll_apacc() # High-level DP and AP register operations async def reset(self): self._log("reset") await self.lower.test_reset() # DP registers are not reset by Debug-Logic-Reset (or anything else except power-on reset); # make sure our cached state matches DP's actual state. await self._write_dpacc(DP_SELECT_addr, self._select.to_int()) async def _prepare_dp_reg(self, addr): assert addr in range(0x00, 0x100, 4) if addr & 0xf != 0x4: pass # DP accessible from any bank elif self._select.DPBANKSEL == addr >> 4: self._log("dp select (elided)") pass # DP bank matches cached SELECT register else: self._log("dp select bank=%#3x", addr >> 4) self._select.DPBANKSEL = addr >> 4 await self._write_dpacc(DP_SELECT_addr, self._select.to_int()) async def _write_dp_reg(self, addr, value): await self._prepare_dp_reg(addr) self._log("dp write addr=%#04x data=%#010x", addr, value) await self._write_dpacc(addr, value) async def _read_dp_reg(self, addr): await self._prepare_dp_reg(addr) self._log("dp read addr=%#04x", addr) value = await self._read_dpacc(addr) self._log("dp read data=%#010x", value) return value async def write_dp_reg(self, addr, value): assert addr in (DP_CTRL_STAT_addr,) assert value & ~self._DP_CTRL_STAT_mask == 0, \ "Data link defined DP register bits may not be set" await self._write_dp_reg(addr, value) async def read_dp_reg(self, addr): assert addr in (DP_CTRL_STAT_addr, DP_DPIDR_addr, DP_TARGETID_addr, DP_EVENTSTAT_addr) return await self._read_dp_reg(addr) async def _prepare_ap_reg(self, id, addr): assert id in range(256) and addr in range(0x00, 0x100, 4) if self._select.APSEL == id and self._select.APBANKSEL == addr >> 4: self._log("ap select (elided)") pass # AP ID/bank matches cached SELECT register else: self._log("ap select id=%d bank=%#3x", id, addr >> 4) self._select.APSEL = id self._select.APBANKSEL = addr >> 4 await self._write_dpacc(DP_SELECT_addr, self._select.to_int()) async def write_ap_reg(self, index, addr, value): await self._prepare_ap_reg(index, addr) self._log("ap write id=%d addr=%#04x data=%#010x", index, addr, value) await self._write_apacc(addr, value) async def read_ap_reg(self, index, addr): await self._prepare_ap_reg(index, addr) self._log("ap read id=%d addr=%#04x", index, addr) value = await self._read_apacc(addr) self._log("ap read data=%#010x", value) return value class DebugARMJTAGApplet(DebugARMAppletMixin, JTAGProbeApplet, name="debug-arm-jtag"): preview = True logger = logging.getLogger(__name__) help = "debug ARM processors via JTAG" description = """ Debug ARM processors with CoreSight support via the JTAG interface. """ @classmethod def add_run_arguments(cls, parser, access): super().add_run_arguments(parser, access) super().add_run_tap_arguments(parser) async def run(self, device, args): tap_iface = await self.run_tap(DebugARMJTAGApplet, device, args) return await ARMJTAGDPInterface(tap_iface, self.logger)
3,400
303
<filename>include/tvm/tvm_preprocessor.h #ifndef TVM_PREPROCESSOR_H_ #define TVM_PREPROCESSOR_H_ #include "tvm_htab.h" int tvm_preprocess(char *src, int *src_len, tvm_htab_t *defines); #endif
93
310
/* * Copyright [2019] [恒宇少年 - 于起宇] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.minbox.framework.api.boot.sample.mybatis.enhance; import com.alibaba.fastjson.JSON; import com.gitee.hengboy.mybatis.enhance.dsl.factory.EnhanceDslFactory; import com.gitee.hengboy.mybatis.pageable.Page; import com.gitee.hengboy.mybatis.pageable.request.PageableRequest; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.minbox.framework.api.boot.sample.mybatis.enhance.dsl.DSystemUser; import org.minbox.framework.api.boot.sample.mybatis.enhance.dto.SystemUserDTO; import org.minbox.framework.api.boot.sample.mybatis.enhance.entity.SystemUser; import org.minbox.framework.api.boot.sample.mybatis.enhance.mapper.SystemUserMapper; import org.minbox.framework.api.boot.sample.mybatis.enhance.service.SystemUserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.ObjectUtils; import java.util.List; /** * @author:恒宇少年 - 于起宇 * <p> * DateTime:2019-07-09 22:16 * Blog:http://blog.yuqiyu.com * WebSite:http://www.jianshu.com/u/092df3f77bca * Gitee:https://gitee.com/hengboy * GitHub:https://github.com/hengboy */ @RunWith(SpringRunner.class) @SpringBootTest(classes = ApiBootMybatisEnhanceApplication.class) public class ApiBootEnhanceSampleTest { /** * logger instance */ static Logger logger = LoggerFactory.getLogger(ApiBootEnhanceSampleTest.class); @Autowired private SystemUserService systemUserService; @Autowired private EnhanceDslFactory dslFactory; @Autowired private SystemUserMapper systemUserMapper; @Test public void manyTableJoin() throws Exception { List<SystemUser> users = systemUserService.manyTableJoin(); if (!ObjectUtils.isEmpty(users)) { users.stream().forEach(user -> { logger.info("用户名:{},昵称:{}", user.getUserName(), user.getNickName()); }); } } @Test public void diyResultType() { List<SystemUserDTO> users = systemUserService.diyResultType(); if (!ObjectUtils.isEmpty(users)) { users.stream().forEach(user -> { logger.info("用户名:{},昵称:{}", user.getUserName(), user.getNickName()); }); } } @Test public void assembleQuery() { List<SystemUser> users = systemUserService.assembleQuery(false); if (!ObjectUtils.isEmpty(users)) { users.stream().forEach(user -> { logger.info("用户名:{},昵称:{}", user.getUserName(), user.getNickName()); }); } } @Test public void count() { Long count = systemUserService.count(); logger.info("统计结果:{}", count); } @Test public void avg() { Integer avg = systemUserService.avg(); logger.info("年龄平均值:{}", avg); } @Test public void sum() { Long sum = systemUserService.sum(); logger.info("年龄总和:{}", sum); } @Test public void min() { Integer min = systemUserService.min(); logger.info("最小的年龄:{}", min); } @Test public void max() { Integer max = systemUserService.max(); logger.info("最大的年龄:{}", max); } @Test public void dslUpdate() { systemUserService.dslUpdate(); } @Test public void dslDelete() { systemUserService.dslDelete(); } @Test public void dslOrder() { List<SystemUser> users = systemUserService.order(); if (!ObjectUtils.isEmpty(users)) { users.stream().forEach(user -> { logger.info("用户名:{},昵称:{}", user.getUserName(), user.getNickName()); }); } } @Test public void page() { List<SystemUser> users = systemUserService.page(); if (!ObjectUtils.isEmpty(users)) { users.stream().forEach(user -> { logger.info("用户名:{},昵称:{}", user.getUserName(), user.getNickName()); }); } } @Test public void group() { List<SystemUser> users = systemUserService.group(); if (!ObjectUtils.isEmpty(users)) { users.stream().forEach(user -> { logger.info("用户名:{},昵称:{}", user.getUserName(), user.getNickName()); }); } } @Test public void methodNamed() { SystemUser user1 = systemUserMapper.findByUserName("admin"); logger.info("用户名查询:{}", user1.getUserName()); SystemUser user2 = systemUserMapper.findByUserNameAndStatus("admin", 1); logger.info("用户名 and 状态查询:{}", user2.getUserName()); List<SystemUser> users = systemUserMapper.findByStatus(1); if (!ObjectUtils.isEmpty(users)) { users.stream().forEach(user -> { logger.info("用户名:{},昵称:{}", user.getUserName(), user.getNickName()); }); } } @Test public void countNamed() { Long count = systemUserMapper.countByStatus(1); logger.info("统计数据:{}", count); count = systemUserMapper.countByUserNameAndStatus("admin", 1); logger.info("统计数据:{}", count); } @Test public void removeNamed() { systemUserMapper.removeByStatus(0); systemUserMapper.removeByUserNameAndStatus("admin", 0); } @Test public void selectUsers() { Page<SystemUser> userPage = PageableRequest.of(1, 1).request(() -> { DSystemUser dSystemUser = DSystemUser.DSL(); dslFactory.createSearchable() .selectFrom(dSystemUser) .where(dSystemUser.userName.eq("admin")) .resultType(SystemUser.class) .fetch(); }); System.out.println(userPage.getTotalElements()); List<SystemUser> users = userPage.getData(); Assert.assertNotNull(users); System.out.println(JSON.toJSONString(users)); } }
3,074
529
<filename>DeviceCode/pal/OpenSSL/OpenSSL_1_0_0/Include/openssl/des.h #include "../../crypto/des/des.h"
46
1,233
package com.github.mustachejava.util; import java.util.LinkedHashMap; public class Node extends LinkedHashMap<String, NodeValue> { }
43
1,088
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <boost/date_time/local_time/local_time_types.hpp> #include <limits> #include "bistro/bistro/cron/CrontabItem.h" #include "bistro/bistro/cron/CrontabSelector.h" // Add stateful Cron support for more robustness, see README for a design. namespace folly { class dynamic; } namespace facebook { namespace bistro { namespace detail_cron { class EpochCrontabItem : public CrontabItem { public: EpochCrontabItem(const folly::dynamic&, boost::local_time::time_zone_ptr); folly::Optional<time_t> findFirstMatch(time_t time_since_utc_epoch) const final; bool isTimezoneDependent() override { return false; } private: CrontabSelector epoch_sel_; }; }}}
298
1,647
#ifndef PYTHONIC_NUMPY_ARRAYSTR_HPP #define PYTHONIC_NUMPY_ARRAYSTR_HPP #include "pythonic/include/numpy/array_str.hpp" #include "pythonic/numpy/array2string.hpp" #endif
81
310
<reponame>dreeves/usesthis { "name": "iPad mini", "description": "A 7.9 inch tablet device.", "url": "https://www.apple.com/ipad-mini/" }
59
852
<reponame>ckamtsikis/cmssw import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDHarvester import DQMEDHarvester cscDigiHarvesting = DQMEDHarvester("MuonCSCDigisHarvestor") MuonCSCDigisPostProcessors = cms.Sequence(cscDigiHarvesting)
102
809
<filename>src/arch/mips/include/asm/mipsregs.h /** * @file * * @brief * * @date 04.07.2012 * @author <NAME> */ #ifndef MIPSREGS_H_ #define MIPSREGS_H_ #include <stdint.h> /* * Configure language */ #ifdef __ASSEMBLY__ #define _ULCAST_ #define _U64CAST_ #else #define _ULCAST_ (unsigned long) #define _U64CAST_ (u64) #endif /* * Coprocessor 0 registers. */ #define CP0_CONTEXT 4 /* The Pointer to an entry in (PTE) array */ #define CP0_BADVADDR 8 /* Virtual address of last exception */ #define CP0_COUNT 9 /* Processor cycle count */ #define CP0_COMPARE 11 /* Comparator value to generate timer IRQ7 */ #define CP0_STATUS 12 /* select 0 Processor status and control */ #define CP0_INTCTL 12 /* select 1 Interrupt control */ #define CP0_CAUSE 13 /* Cause of last exception */ #define CP0_EPC 14 /* Program counter at last exception */ #define CP0_PRID 15 /* Processor identification (read only) */ #define CP0_EBASE 15 /* select 1 exception base */ #define CP0_CONFIG 16 /* select 0 Configuration */ #define CP0_CONFIG1 16 /* select 1 configuration */ #define CP0_CONFIG2 16 /* select 2 Configuration */ #define CP0_CONFIG3 16 /* select 3 configuration */ #define CP0_CONFIG4 16 /* select 4 configuration */ #define CP0_CONFIG5 16 /* select 5 Configuration */ #define CP0_CONFIG6 16 /* select 6 configuration */ #define CP0_CONFIG7 16 /* select 7 configuration */ #define CP0_DEBUG 23 /* Debug control and status */ #define CP0_DEPC 24 /* Program counter at last debug exception */ #define CP0_ERROREPC 30 /* Program counter at last error */ #define CP0_DESAVE 31 /* Debug handler scratchpad register */ #define MIPS_IRQN_TIMER 7 /* timer interrupt number */ #define ST0_IRQ_MASK_OFFSET 0x8 /* interrupt mask offset in status and cause registers */ #define ST0_SOFTIRQ_NUM 0x2 #define ST0_IM 0x0000ff00 #define ST0_IP0 (1 << (ST0_IRQ_MASK_OFFSET + 0)) /* soft interrupt 0 */ #define ST0_IP1 (1 << (ST0_IRQ_MASK_OFFSET + 1)) /* soft interrupt 1 */ #define ST0_IP2 (1 << (ST0_IRQ_MASK_OFFSET + 2)) /* UART1 interrupt flag */ #define ST0_IP3 (1 << (ST0_IRQ_MASK_OFFSET + 3)) /* UART2 interrupt flag */ #define ST0_IP6 (1 << (ST0_IRQ_MASK_OFFSET + 6)) /* RTC interrupt flag */ #define ST0_IP7 (0x1 << (ST0_IRQ_MASK_OFFSET + MIPS_IRQN_TIMER)) /* timer interrupt flag */ #define ST0_IE 0x00000001 /* interrupts enable mask */ #define ST0_EXL 0x00000002 /* exception level mask */ #define ST0_ERL 0x00000004 /* error level mask */ #define ST0_BEV (1 << 22) /* Boot exception vectors */ #define CAUSE_IV (1 << 23) /* vectored interrupt table */ #define CAUSE_PCI (1 << 26) /* performance counter interrupt */ #define CAUSE_DC (1 << 27) /* stop counter */ #define CAUSE_TI (1 << 30) /* timer interrupt */ #define CAUSE_BD (1 << 31) /* branch delay */ #define CAUSE_IM 0x0000ff00 /* interrupts mask */ #define INTCTL_VS 0x000003E0 //#define CONFIG3_VEXIC (1 << 6) /* Support for an external interrupt controller. */ //#define CONFIG3_VINT (1 << 5) /* Vectored interrupts implemented. */ /* * Bits in the coprocessor 0 config register. */ /* Generic bits. */ #define CONF_CM_CACHABLE_NO_WA 0 #define CONF_CM_CACHABLE_WA 1 #define CONF_CM_UNCACHED 2 #define CONF_CM_CACHABLE_NONCOHERENT 3 #define CONF_CM_CACHABLE_CE 4 #define CONF_CM_CACHABLE_COW 5 #define CONF_CM_CACHABLE_CUW 6 #define CONF_CM_CACHABLE_ACCELERATED 7 #define CONF_CM_CMASK 7 #define CONF_BE (_ULCAST_(1) << 15) /* Bits specific to the MIPS32/64 PRA. */ #define MIPS_CONF_VI (_ULCAST_(1) << 3) #define MIPS_CONF_MT (_ULCAST_(7) << 7) #define MIPS_CONF_MT_TLB (_ULCAST_(1) << 7) #define MIPS_CONF_MT_FTLB (_ULCAST_(4) << 7) #define MIPS_CONF_AR (_ULCAST_(7) << 10) #define MIPS_CONF_AT (_ULCAST_(3) << 13) #define MIPS_CONF_IMPL (_ULCAST_(0x1ff) << 16) #define MIPS_CONF_M (_ULCAST_(1) << 31) /* * Bits in the MIPS32/64 PRA coprocessor 0 config registers 1 and above. */ #define MIPS_CONF1_FP (_ULCAST_(1) << 0) #define MIPS_CONF1_EP (_ULCAST_(1) << 1) #define MIPS_CONF1_CA (_ULCAST_(1) << 2) #define MIPS_CONF1_WR (_ULCAST_(1) << 3) #define MIPS_CONF1_PC (_ULCAST_(1) << 4) #define MIPS_CONF1_MD (_ULCAST_(1) << 5) #define MIPS_CONF1_C2 (_ULCAST_(1) << 6) #define MIPS_CONF1_DA_SHF 7 #define MIPS_CONF1_DA_SZ 3 #define MIPS_CONF1_DA (_ULCAST_(7) << 7) #define MIPS_CONF1_DL_SHF 10 #define MIPS_CONF1_DL_SZ 3 #define MIPS_CONF1_DL (_ULCAST_(7) << 10) #define MIPS_CONF1_DS_SHF 13 #define MIPS_CONF1_DS_SZ 3 #define MIPS_CONF1_DS (_ULCAST_(7) << 13) #define MIPS_CONF1_IA_SHF 16 #define MIPS_CONF1_IA_SZ 3 #define MIPS_CONF1_IA (_ULCAST_(7) << 16) #define MIPS_CONF1_IL_SHF 19 #define MIPS_CONF1_IL_SZ 3 #define MIPS_CONF1_IL (_ULCAST_(7) << 19) #define MIPS_CONF1_IS_SHF 22 #define MIPS_CONF1_IS_SZ 3 #define MIPS_CONF1_IS (_ULCAST_(7) << 22) #define MIPS_CONF1_TLBS_SHIFT (25) #define MIPS_CONF1_TLBS_SIZE (6) #define MIPS_CONF1_TLBS (_ULCAST_(63) << MIPS_CONF1_TLBS_SHIFT) #define MIPS_CONF2_SA_SHF 0 #define MIPS_CONF2_SA (_ULCAST_(15) << 0) #define MIPS_CONF2_SL_SHF 4 #define MIPS_CONF2_SL (_ULCAST_(15) << 4) #define MIPS_CONF2_SS_SHF 8 #define MIPS_CONF2_SS (_ULCAST_(15) << 8) #define MIPS_CONF2_L2B (_ULCAST_(1) << 12) #define MIPS_CONF2_SU (_ULCAST_(15) << 12) #define MIPS_CONF2_TA (_ULCAST_(15) << 16) #define MIPS_CONF2_TL (_ULCAST_(15) << 20) #define MIPS_CONF2_TS (_ULCAST_(15) << 24) #define MIPS_CONF2_TU (_ULCAST_(7) << 28) #define MIPS_CONF3_TL (_ULCAST_(1) << 0) #define MIPS_CONF3_SM (_ULCAST_(1) << 1) #define MIPS_CONF3_MT (_ULCAST_(1) << 2) #define MIPS_CONF3_CDMM (_ULCAST_(1) << 3) #define MIPS_CONF3_SP (_ULCAST_(1) << 4) #define MIPS_CONF3_VINT (_ULCAST_(1) << 5) #define MIPS_CONF3_VEIC (_ULCAST_(1) << 6) #define MIPS_CONF3_LPA (_ULCAST_(1) << 7) #define MIPS_CONF3_ITL (_ULCAST_(1) << 8) #define MIPS_CONF3_CTXTC (_ULCAST_(1) << 9) #define MIPS_CONF3_DSP (_ULCAST_(1) << 10) #define MIPS_CONF3_DSP2P (_ULCAST_(1) << 11) #define MIPS_CONF3_RXI (_ULCAST_(1) << 12) #define MIPS_CONF3_ULRI (_ULCAST_(1) << 13) #define MIPS_CONF3_ISA (_ULCAST_(3) << 14) #define MIPS_CONF3_ISA_OE (_ULCAST_(1) << 16) #define MIPS_CONF3_MCU (_ULCAST_(1) << 17) #define MIPS_CONF3_MMAR (_ULCAST_(7) << 18) #define MIPS_CONF3_IPLW (_ULCAST_(3) << 21) #define MIPS_CONF3_VZ (_ULCAST_(1) << 23) #define MIPS_CONF3_PW (_ULCAST_(1) << 24) #define MIPS_CONF3_SC (_ULCAST_(1) << 25) #define MIPS_CONF3_BI (_ULCAST_(1) << 26) #define MIPS_CONF3_BP (_ULCAST_(1) << 27) #define MIPS_CONF3_MSA (_ULCAST_(1) << 28) #define MIPS_CONF3_CMGCR (_ULCAST_(1) << 29) #define MIPS_CONF3_BPG (_ULCAST_(1) << 30) #define MIPS_CONF4_MMUSIZEEXT_SHIFT (0) #define MIPS_CONF4_MMUSIZEEXT (_ULCAST_(255) << 0) #define MIPS_CONF4_FTLBSETS_SHIFT (0) #define MIPS_CONF4_FTLBSETS (_ULCAST_(15) << MIPS_CONF4_FTLBSETS_SHIFT) #define MIPS_CONF4_FTLBWAYS_SHIFT (4) #define MIPS_CONF4_FTLBWAYS (_ULCAST_(15) << MIPS_CONF4_FTLBWAYS_SHIFT) #define MIPS_CONF4_FTLBPAGESIZE_SHIFT (8) #define MIPS_CONF4_FTLBPAGESIZE (_ULCAST_(7) << MIPS_CONF4_FTLBPAGESIZE_SHIFT) #define MIPS_CONF4_VFTLBPAGESIZE (_ULCAST_(31) << MIPS_CONF4_FTLBPAGESIZE_SHIFT) #define MIPS_CONF4_MMUEXTDEF (_ULCAST_(3) << 14) #define MIPS_CONF4_MMUEXTDEF_MMUSIZEEXT (_ULCAST_(1) << 14) #define MIPS_CONF4_MMUEXTDEF_FTLBSIZEEXT (_ULCAST_(2) << 14) #define MIPS_CONF4_MMUEXTDEF_VTLBSIZEEXT (_ULCAST_(3) << 14) #define MIPS_CONF4_KSCREXIST_SHIFT (16) #define MIPS_CONF4_KSCREXIST (_ULCAST_(255) << MIPS_CONF4_KSCREXIST_SHIFT) #define MIPS_CONF4_VTLBSIZEEXT_SHIFT (24) #define MIPS_CONF4_VTLBSIZEEXT (_ULCAST_(15) << MIPS_CONF4_VTLBSIZEEXT_SHIFT) #define MIPS_CONF4_AE (_ULCAST_(1) << 28) #define MIPS_CONF4_IE (_ULCAST_(3) << 29) #define MIPS_CONF4_TLBINV (_ULCAST_(2) << 29) #define MIPS_CONF5_NF (_ULCAST_(1) << 0) #define MIPS_CONF5_UFR (_ULCAST_(1) << 2) #define MIPS_CONF5_MRP (_ULCAST_(1) << 3) #define MIPS_CONF5_LLB (_ULCAST_(1) << 4) #define MIPS_CONF5_MVH (_ULCAST_(1) << 5) #define MIPS_CONF5_VP (_ULCAST_(1) << 7) #define MIPS_CONF5_SBRI (_ULCAST_(1) << 6) #define MIPS_CONF5_FRE (_ULCAST_(1) << 8) #define MIPS_CONF5_UFE (_ULCAST_(1) << 9) #define MIPS_CONF5_L2C (_ULCAST_(1) << 10) #define MIPS_CONF5_CA2 (_ULCAST_(1) << 14) #define MIPS_CONF5_MI (_ULCAST_(1) << 17) #define MIPS_CONF5_CRCP (_ULCAST_(1) << 18) #define MIPS_CONF5_MSAEN (_ULCAST_(1) << 27) #define MIPS_CONF5_EVA (_ULCAST_(1) << 28) #define MIPS_CONF5_CV (_ULCAST_(1) << 29) #define MIPS_CONF5_K (_ULCAST_(1) << 3 /* helpers for access to MIPS co-processor 0 registers */ #define __read_32bit_c0_register(source, sel) \ ({ int __res; \ if (sel == 0) \ __asm__ __volatile__( \ "mfc0\t%0, " #source "\n\t ehb" \ : "=r" (__res)); \ else \ __asm__ __volatile__( \ ".set\tmips32\n\t" \ "mfc0\t%0, " #source ", " #sel "\n\t" \ ".set\tmips0\n\t" \ : "=r" (__res)); \ __res; \ }) #define __write_32bit_c0_register(register, sel, value) \ do { \ if (sel == 0) \ __asm__ __volatile__( \ "mtc0\t%z0, " #register "\n\t ehb" \ : : "Jr" ((unsigned int)(value))); \ else \ __asm__ __volatile__( \ ".set\tmips32\n\t" \ "mtc0\t%z0, " #register ", " #sel "\n\t" \ ".set\tmips0" \ : : "Jr" ((unsigned int)(value))); \ } while (0) /* read/write mips status register */ #define mips_read_c0_status() __read_32bit_c0_register($12, 0) #define mips_write_c0_status(val) __write_32bit_c0_register($12, 0, val) /* read/write mips cause register */ #define mips_read_c0_cause() __read_32bit_c0_register($13, 0) #define mips_write_c0_cause(val) __write_32bit_c0_register($13, 0, val) /* read/write mips compare register */ #define mips_read_c0_compare() __read_32bit_c0_register($11, 0) #define mips_write_c0_compare(val) __write_32bit_c0_register($11, 0, val) /* read/write mips count register */ #define mips_read_c0_count() __read_32bit_c0_register($9, 0) #define mips_write_c0_count(val) __write_32bit_c0_register($9, 0, val) /* read/write mips interrupt control register */ #define mips_read_c0_intctl() __read_32bit_c0_register($12, 1) #define mips_write_c0_intctl(val) __write_32bit_c0_register($12, 1, val) /* read/write mips exception base register */ #define mips_read_c0_ebase() __read_32bit_c0_register($15, 1) #define mips_write_c0_ebase(val) __write_32bit_c0_register($15, 1, val) /* read/write mips config register */ #define mips_read_c0_config() __read_32bit_c0_register($16, 0) #define mips_write_c0_config(val) __write_32bit_c0_register($16, 0, val) /* read/write mips config1 register */ #define mips_read_c0_config1() __read_32bit_c0_register($16, 1) #define mips_write_c0_config1(val) __write_32bit_c0_register($16, 1, val) /* read/write mips config2 register */ #define mips_read_c0_config2() __read_32bit_c0_register($16, 2) #define mips_write_c0_config2(val) __write_32bit_c0_register($16, 2, val) /* read/write mips config3 register */ #define mips_read_c0_config3() __read_32bit_c0_register($16, 3) #define mips_write_c0_config3(val) __write_32bit_c0_register($16, 3, val) /* read/write mips config4 register */ #define mips_read_c0_config4() __read_32bit_c0_register($16, 4) #define mips_write_c0_config4(val) __write_32bit_c0_register($16, 4, val) /* read/write mips config5 register */ #define mips_read_c0_config5() __read_32bit_c0_register($16, 5) #define mips_write_c0_config5(val) __write_32bit_c0_register($16, 5, val) /* read/write mips config6 register */ #define mips_read_c0_config6() __read_32bit_c0_register($16, 6) #define mips_write_c0_config6(val) __write_32bit_c0_register($16, 6, val) /* read/write mips config7 register */ #define mips_read_c0_config7() __read_32bit_c0_register($16, 7) #define mips_write_c0_config7(val) __write_32bit_c0_register($16, 7, val) #ifndef __ASSEMBLER__ static inline unsigned int mips_change_c0_config(unsigned int change, unsigned int val) { unsigned int res, new_val; res = mips_read_c0_config(); new_val = res & ~change; new_val |= (val & change); mips_write_c0_config(new_val); return res; } #endif /* __ASSEMBLY__ */ #endif /* MIPSREGS_H_ */
6,621
897
/* Sieve of Eratosthenes : Sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the first prime number, 2. The multiples of a given prime are generated as a sequence of numbers starting from that prime, with constant difference between them that is equal to that prime. */ import java.util.Scanner; public class SieveOfEratosthenes { public static void sieve(int n) { boolean prime[]=new boolean[n+1]; for(int i=0;i<=n;i++) { prime[i]=true; } prime[0]=prime[1]=false; for(int i=2;i*i<=n;i++) { // If a number is prime : if(prime[i]==true) { // Marking all multiples of that number as false for(int j=i*i;j<=n;j+=i) { prime[j]=false; } } } // Printing all prime number less than n : for(int i=0;i<=n;i++) { if(prime[i]==true) { System.out.print(i+" "); } } } public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.print("Enter a number : "); int n=sc.nextInt(); System.out.println("Prime number less than or equal to "+n+" are : "); sieve(n); } /* Sample Input : Enter a number : 100 Sample Output : Prime number less than or equal to 100 are : 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 */ }
580
21,382
#include "barrier_helper.h" #include <algorithm> #include "util/streaming_logging.h" #include "util/streaming_util.h" namespace ray { namespace streaming { StreamingStatus StreamingBarrierHelper::GetMsgIdByBarrierId(const ObjectID &q_id, uint64_t barrier_id, uint64_t &msg_id) { std::lock_guard<std::mutex> lock(global_barrier_mutex_); auto queue_map = global_barrier_map_.find(barrier_id); if (queue_map == global_barrier_map_.end()) { return StreamingStatus::NoSuchItem; } auto msg_id_map = queue_map->second.find(q_id); if (msg_id_map == queue_map->second.end()) { return StreamingStatus::QueueIdNotFound; } msg_id = msg_id_map->second; return StreamingStatus::OK; } void StreamingBarrierHelper::SetMsgIdByBarrierId(const ObjectID &q_id, uint64_t barrier_id, uint64_t msg_id) { std::lock_guard<std::mutex> lock(global_barrier_mutex_); global_barrier_map_[barrier_id][q_id] = msg_id; } void StreamingBarrierHelper::ReleaseBarrierMapById(uint64_t barrier_id) { std::lock_guard<std::mutex> lock(global_barrier_mutex_); global_barrier_map_.erase(barrier_id); } void StreamingBarrierHelper::ReleaseAllBarrierMap() { std::lock_guard<std::mutex> lock(global_barrier_mutex_); global_barrier_map_.clear(); } void StreamingBarrierHelper::MapBarrierToCheckpoint(uint64_t barrier_id, uint64_t checkpoint) { std::lock_guard<std::mutex> lock(barrier_map_checkpoint_mutex_); barrier_checkpoint_map_[barrier_id] = checkpoint; } StreamingStatus StreamingBarrierHelper::GetCheckpointIdByBarrierId( uint64_t barrier_id, uint64_t &checkpoint_id) { std::lock_guard<std::mutex> lock(barrier_map_checkpoint_mutex_); auto checkpoint_item = barrier_checkpoint_map_.find(barrier_id); if (checkpoint_item == barrier_checkpoint_map_.end()) { return StreamingStatus::NoSuchItem; } checkpoint_id = checkpoint_item->second; return StreamingStatus::OK; } void StreamingBarrierHelper::ReleaseBarrierMapCheckpointByBarrierId( const uint64_t barrier_id) { std::lock_guard<std::mutex> lock(barrier_map_checkpoint_mutex_); auto it = barrier_checkpoint_map_.begin(); while (it != barrier_checkpoint_map_.end()) { if (it->first <= barrier_id) { it = barrier_checkpoint_map_.erase(it); } else { it++; } } } StreamingStatus StreamingBarrierHelper::GetBarrierIdByLastMessageId(const ObjectID &q_id, uint64_t message_id, uint64_t &barrier_id, bool is_pop) { std::lock_guard<std::mutex> lock(message_id_map_barrier_mutex_); auto message_item = global_reversed_barrier_map_.find(message_id); if (message_item == global_reversed_barrier_map_.end()) { return StreamingStatus::NoSuchItem; } auto message_queue_item = message_item->second.find(q_id); if (message_queue_item == message_item->second.end()) { return StreamingStatus::QueueIdNotFound; } if (message_queue_item->second->empty()) { STREAMING_LOG(WARNING) << "[Barrier] q id => " << q_id.Hex() << ", str num => " << Util::Hexqid2str(q_id.Hex()) << ", message id " << message_id; return StreamingStatus::NoSuchItem; } else { barrier_id = message_queue_item->second->front(); if (is_pop) { message_queue_item->second->pop(); } } return StreamingStatus::OK; } void StreamingBarrierHelper::SetBarrierIdByLastMessageId(const ObjectID &q_id, uint64_t message_id, uint64_t barrier_id) { std::lock_guard<std::mutex> lock(message_id_map_barrier_mutex_); auto max_message_id_barrier = max_message_id_map_.find(q_id); // remove finished barrier in different last message id if (max_message_id_barrier != max_message_id_map_.end() && max_message_id_barrier->second != message_id) { if (global_reversed_barrier_map_.find(max_message_id_barrier->second) != global_reversed_barrier_map_.end()) { global_reversed_barrier_map_.erase(max_message_id_barrier->second); } } max_message_id_map_[q_id] = message_id; auto message_item = global_reversed_barrier_map_.find(message_id); if (message_item == global_reversed_barrier_map_.end()) { BarrierIdQueue temp_queue = std::make_shared<std::queue<uint64_t>>(); temp_queue->push(barrier_id); global_reversed_barrier_map_[message_id][q_id] = temp_queue; return; } auto message_queue_item = message_item->second.find(q_id); if (message_queue_item != message_item->second.end()) { message_queue_item->second->push(barrier_id); } else { BarrierIdQueue temp_queue = std::make_shared<std::queue<uint64_t>>(); temp_queue->push(barrier_id); global_reversed_barrier_map_[message_id][q_id] = temp_queue; } } void StreamingBarrierHelper::GetAllBarrier(std::vector<uint64_t> &barrier_id_vec) { std::transform( global_barrier_map_.begin(), global_barrier_map_.end(), std::back_inserter(barrier_id_vec), [](std::unordered_map<uint64_t, std::unordered_map<ObjectID, uint64_t>>::value_type pair) { return pair.first; }); } bool StreamingBarrierHelper::Contains(uint64_t barrier_id) { return global_barrier_map_.find(barrier_id) != global_barrier_map_.end(); } uint32_t StreamingBarrierHelper::GetBarrierMapSize() { return global_barrier_map_.size(); } void StreamingBarrierHelper::GetCurrentMaxCheckpointIdInQueue( const ObjectID &q_id, uint64_t &checkpoint_id) const { auto item = current_max_checkpoint_id_map_.find(q_id); if (item != current_max_checkpoint_id_map_.end()) { checkpoint_id = item->second; } else { checkpoint_id = 0; } } void StreamingBarrierHelper::SetCurrentMaxCheckpointIdInQueue( const ObjectID &q_id, const uint64_t checkpoint_id) { current_max_checkpoint_id_map_[q_id] = checkpoint_id; } } // namespace streaming } // namespace ray
2,737
825
<reponame>jiangkang/Hummer package com.didi.hummer.demo; import android.content.Context; import android.view.View; import com.didi.hummer.annotation.Component; import com.didi.hummer.annotation.JsAttribute; import com.didi.hummer.annotation.JsMethod; import com.didi.hummer.annotation.JsProperty; import com.didi.hummer.context.HummerContext; import com.didi.hummer.core.engine.JSValue; import com.didi.hummer.render.component.view.HMBase; import com.didi.hummer.render.style.HummerStyleUtils; /** * 视图组件导出组件 * * Created by XiaoFeng on 2021/4/21. */ @Component("TestView") public class TestView extends HMBase<View> { public TestView(HummerContext context, JSValue jsValue, String viewID) { super(context, jsValue, viewID); } @Override protected View createViewInstance(Context context) { return new View(context); } @JsProperty("text") private String text; public void setText(String text) { this.text = text; } @JsAttribute("color") public void setColor(int color) { } @JsMethod("layout") public void layout() { getView().requestLayout(); } @Override public boolean setStyle(String key, Object value) { switch (key) { case HummerStyleUtils.Hummer.COLOR: setColor((int) value); break; default: return false; } return true; } }
602
2,151
<reponame>zipated/src // Copyright 2018 The Feed Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.libraries.feed.testing.conformance.storage; import static com.google.common.truth.Truth.assertThat; import com.google.android.libraries.feed.common.Result; import com.google.android.libraries.feed.common.functional.Consumer; import com.google.android.libraries.feed.common.testing.RequiredConsumer; import com.google.android.libraries.feed.host.storage.CommitResult; import com.google.android.libraries.feed.host.storage.ContentMutation; import com.google.android.libraries.feed.host.storage.ContentStorage; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Collections; import java.util.Map; import org.junit.Test; /** * Conformance test for {@link ContentStorage}. Hosts who wish to test against this should extend * this class and set {@code storage} to the Host implementation. */ public abstract class ContentStorageConformanceTest { private static final String KEY = "key"; private static final String KEY_0 = KEY + " 0"; private static final String KEY_1 = KEY + " 1"; private static final String OTHER_KEY = "other"; private static final byte[] DATA_0 = "data 0".getBytes(Charset.forName("UTF-8")); private static final byte[] DATA_1 = "data 1".getBytes(Charset.forName("UTF-8")); private static final byte[] OTHER_DATA = "other data".getBytes(Charset.forName("UTF-8")); // Helper consumers to make tests cleaner private final Consumer<Result<Map<String, byte[]>>> isKey0Data0 = input -> { assertThat(input.isSuccessful()).isTrue(); Map<String, byte[]> valueMap = input.getValue(); assertThat(valueMap.get(KEY_0)).isEqualTo(DATA_0); }; private final Consumer<Result<Map<String, byte[]>>> isKey0EmptyData = input -> { assertThat(input.isSuccessful()).isTrue(); Map<String, byte[]> valueMap = input.getValue(); assertThat(valueMap.get(KEY_0)).isNull(); }; private final Consumer<Result<Map<String, byte[]>>> isKey0Data1 = input -> { assertThat(input.isSuccessful()).isTrue(); Map<String, byte[]> valueMap = input.getValue(); assertThat(valueMap.get(KEY_0)).isEqualTo(DATA_1); }; private final Consumer<Result<Map<String, byte[]>>> isKey0Data0Key1Data1 = result -> { assertThat(result.isSuccessful()).isTrue(); Map<String, byte[]> input = result.getValue(); assertThat(input.get(KEY_0)).isEqualTo(DATA_0); assertThat(input.get(KEY_1)).isEqualTo(DATA_1); }; private final Consumer<Result<Map<String, byte[]>>> isKey0EmptyDataKey1EmptyData = input -> { assertThat(input.isSuccessful()).isTrue(); Map<String, byte[]> valueMap = input.getValue(); assertThat(valueMap.get(KEY_0)).isNull(); assertThat(valueMap.get(KEY_1)).isNull(); }; private final Consumer<Result<Map<String, byte[]>>> isKey0Data0Key1Data1OtherKeyOtherData = result -> { assertThat(result.isSuccessful()).isTrue(); Map<String, byte[]> input = result.getValue(); assertThat(input.get(KEY_0)).isEqualTo(DATA_0); assertThat(input.get(KEY_1)).isEqualTo(DATA_1); assertThat(input.get(OTHER_KEY)).isEqualTo(OTHER_DATA); }; private final Consumer<Result<Map<String, byte[]>>> isKey0EmptyDataKey1EmptyDataOtherKeyOtherData = result -> { assertThat(result.isSuccessful()).isTrue(); Map<String, byte[]> input = result.getValue(); assertThat(input.get(KEY_0)).isNull(); assertThat(input.get(KEY_1)).isNull(); assertThat(input.get(OTHER_KEY)).isEqualTo(OTHER_DATA); }; private final Consumer<CommitResult> isSuccess = input -> assertThat(input).isEqualTo(CommitResult.SUCCESS); protected ContentStorage storage; @Test public void missingKey() throws Exception { RequiredConsumer<Result<Map<String, byte[]>>> consumer = new RequiredConsumer<>(isKey0EmptyData); storage.get(Collections.singletonList(KEY_0), consumer); assertThat(consumer.isCalled()).isTrue(); } @Test public void missingKey_multipleKeys() throws Exception { RequiredConsumer<Result<Map<String, byte[]>>> consumer = new RequiredConsumer<>(isKey0EmptyDataKey1EmptyData); storage.get(Arrays.asList(KEY_0, KEY_1), consumer); assertThat(consumer.isCalled()).isTrue(); } @Test public void storeAndRetrieve() throws Exception { RequiredConsumer<CommitResult> consumer = new RequiredConsumer<>( input -> { assertThat(input).isEqualTo(CommitResult.SUCCESS); RequiredConsumer<Result<Map<String, byte[]>>> byteConsumer = new RequiredConsumer<>(isKey0Data0); storage.get(Collections.singletonList(KEY_0), byteConsumer); assertThat(byteConsumer.isCalled()).isTrue(); }); storage.commit(new ContentMutation.Builder().upsert(KEY_0, DATA_0).build(), consumer); assertThat(consumer.isCalled()).isTrue(); } @Test public void storeAndRetrieve_multipleKeys() throws Exception { RequiredConsumer<CommitResult> consumer = new RequiredConsumer<>( input -> { assertThat(input).isEqualTo(CommitResult.SUCCESS); RequiredConsumer<Result<Map<String, byte[]>>> byteConsumer = new RequiredConsumer<>(isKey0Data0Key1Data1); storage.get(Arrays.asList(KEY_0, KEY_1), byteConsumer); assertThat(byteConsumer.isCalled()).isTrue(); }); storage.commit( new ContentMutation.Builder().upsert(KEY_0, DATA_0).upsert(KEY_1, DATA_1).build(), consumer); assertThat(consumer.isCalled()).isTrue(); } @Test public void storeAndOverwrite_chained() throws Exception { RequiredConsumer<CommitResult> consumer = new RequiredConsumer<>( input -> { assertThat(input).isEqualTo(CommitResult.SUCCESS); RequiredConsumer<Result<Map<String, byte[]>>> byteConsumer = new RequiredConsumer<>(isKey0Data1); storage.get(Collections.singletonList(KEY_0), byteConsumer); assertThat(byteConsumer.isCalled()).isTrue(); }); storage.commit( new ContentMutation.Builder().upsert(KEY_0, DATA_0).upsert(KEY_0, DATA_1).build(), consumer); assertThat(consumer.isCalled()).isTrue(); } @Test public void storeAndOverwrite_separate() throws Exception { RequiredConsumer<CommitResult> consumer = new RequiredConsumer<>( input -> { assertThat(input).isEqualTo(CommitResult.SUCCESS); RequiredConsumer<Result<Map<String, byte[]>>> byteConsumer = new RequiredConsumer<>(isKey0Data0); storage.get(Collections.singletonList(KEY_0), byteConsumer); assertThat(byteConsumer.isCalled()).isTrue(); // Second consumer required to be nested to ensure that it executes in sequence RequiredConsumer<CommitResult> consumer2 = new RequiredConsumer<>( input1 -> { assertThat(input1).isEqualTo(CommitResult.SUCCESS); RequiredConsumer<Result<Map<String, byte[]>>> byteConsumer2 = new RequiredConsumer<>(isKey0Data1); storage.get(Collections.singletonList(KEY_0), byteConsumer2); assertThat(byteConsumer2.isCalled()).isTrue(); }); storage.commit( new ContentMutation.Builder().upsert(KEY_0, DATA_1).build(), consumer2); assertThat(consumer2.isCalled()).isTrue(); }); storage.commit(new ContentMutation.Builder().upsert(KEY_0, DATA_0).build(), consumer); assertThat(consumer.isCalled()).isTrue(); } @Test public void storeAndDelete() throws Exception { RequiredConsumer<CommitResult> consumer = new RequiredConsumer<>( input -> { assertThat(input).isEqualTo(CommitResult.SUCCESS); // Confirm Key 0 and 1 are present RequiredConsumer<Result<Map<String, byte[]>>> byteConsumer = new RequiredConsumer<>(isKey0Data0Key1Data1); storage.get(Arrays.asList(KEY_0, KEY_1), byteConsumer); assertThat(byteConsumer.isCalled()).isTrue(); // Delete Key 0 RequiredConsumer<CommitResult> deleteConsumer = new RequiredConsumer<>(isSuccess); storage.commit(new ContentMutation.Builder().delete(KEY_0).build(), deleteConsumer); assertThat(deleteConsumer.isCalled()).isTrue(); // Confirm that Key 0 is deleted and Key 1 is present byteConsumer = new RequiredConsumer<>(isKey0EmptyData); storage.get(Arrays.asList(KEY_0, KEY_1), byteConsumer); assertThat(byteConsumer.isCalled()).isTrue(); }); storage.commit( new ContentMutation.Builder().upsert(KEY_0, DATA_0).upsert(KEY_1, DATA_1).build(), consumer); assertThat(consumer.isCalled()).isTrue(); } @Test public void storeAndDeleteByPrefix() throws Exception { RequiredConsumer<CommitResult> consumer = new RequiredConsumer<>( input -> { assertThat(input).isEqualTo(CommitResult.SUCCESS); // Confirm Key 0, Key 1, and Other are present RequiredConsumer<Result<Map<String, byte[]>>> byteConsumer = new RequiredConsumer<>(isKey0Data0Key1Data1OtherKeyOtherData); storage.get(Arrays.asList(KEY_0, KEY_1, OTHER_KEY), byteConsumer); assertThat(byteConsumer.isCalled()).isTrue(); // Delete by prefix Key RequiredConsumer<CommitResult> deleteConsumer = new RequiredConsumer<>(isSuccess); storage.commit( new ContentMutation.Builder().deleteByPrefix(KEY).build(), deleteConsumer); // Confirm Key 0 and Key 1 are deleted, and Other is present byteConsumer = new RequiredConsumer<>(isKey0EmptyDataKey1EmptyDataOtherKeyOtherData); storage.get(Arrays.asList(KEY_0, KEY_1, OTHER_KEY), byteConsumer); assertThat(byteConsumer.isCalled()).isTrue(); }); storage.commit( new ContentMutation.Builder() .upsert(KEY_0, DATA_0) .upsert(KEY_1, DATA_1) .upsert(OTHER_KEY, OTHER_DATA) .build(), consumer); assertThat(consumer.isCalled()).isTrue(); } @Test public void multipleValues_getAll() throws Exception { RequiredConsumer<CommitResult> commitResultConsumer = new RequiredConsumer<>( input -> { assertThat(input).isEqualTo(CommitResult.SUCCESS); RequiredConsumer<Result<Map<String, byte[]>>> mapConsumer = new RequiredConsumer<>(isKey0Data0Key1Data1); storage.getAll(KEY, mapConsumer); assertThat(mapConsumer.isCalled()).isTrue(); }); storage.commit( new ContentMutation.Builder().upsert(KEY_0, DATA_0).upsert(KEY_1, DATA_1).build(), commitResultConsumer); assertThat(commitResultConsumer.isCalled()).isTrue(); } }
4,843