repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
weiyang13/main
src/test/java/seedu/ichifund/testutil/FundBookBuilder.java
package seedu.ichifund.testutil; import seedu.ichifund.model.FundBook; import seedu.ichifund.model.transaction.Transaction; /** * A utility class to help with building FundBook objects. * Example usage: <br> * {@code FundBook ab = new FundBookBuilder().withTransaction("John", "Doe").build();} */ public class FundBookBuilder { private FundBook fundBook; public FundBookBuilder() { fundBook = new FundBook(); } public FundBookBuilder(FundBook fundBook) { this.fundBook = fundBook; } /** * Adds a new {@code Transaction} to the {@code FundBook} that we are building. */ public FundBookBuilder withTransaction(Transaction transaction) { fundBook.addTransaction(transaction); return this; } public FundBook build() { return fundBook; } }
xiaomailong/prestudy
demo/electron-demo/demo1/Gruntfile.js
module.exports = function(grunt) { grunt.initConfig({ 'build-atom-shell': { tag: 'v0.19.5', nodeVersion: '0.18.0', buildDir: (process.env.TMPDIR || process.env.TEMP || '/tmp') + '/atom-shell', projectName: 'electrondemo', productName: 'ElectronDemo' } }); grunt.loadNpmTasks('grunt-build-atom-shell'); grunt.registerTask('default', ['build-atom-shell']); };
DFalque/mombo_landing_master
src/components/Header/MobileNav.js
<filename>src/components/Header/MobileNav.js<gh_stars>0 import React, { Component } from "react" import Nav from "./Nav" export class MobileNav extends Component { render() { return ( <div className="header__mobile"> <Nav /> </div> ) } } export default MobileNav
redecheck/redecheck
src/main/java/shef/reporting/inconsistencies/ViewportProtrusionFailure.java
<reponame>redecheck/redecheck<gh_stars>10-100 package shef.reporting.inconsistencies; import org.apache.commons.io.FileUtils; import org.openqa.selenium.WebDriver; import shef.layout.Element; import shef.layout.LayoutFactory; import shef.main.RLGExtractor; import shef.main.Utils; import shef.rlg.Node; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; /** * Created by thomaswalsh on 19/08/2016. */ public class ViewportProtrusionFailure extends ResponsiveLayoutFailure { Node node; int min, max; public Node getNode() { return node; } public int getMin() { return min; } public int getMax() { return max; } public ViewportProtrusionFailure(Node n, int i, int key) { node = n; min = i; max = key; } public String toString() { return node.getXpath() + " overflowed the viewport window between " + min + " and " + max; } @Override public void captureScreenshotExample(int errorID, String url, WebDriver webDriver, String fullUrl, String timeStamp) { try { int captureWidth = (min + max) / 2; HashMap<Integer, LayoutFactory> lfs = new HashMap<>(); BufferedImage img; img = RLGExtractor.getScreenshot(captureWidth, errorID, lfs, webDriver, fullUrl); LayoutFactory lf = lfs.get(captureWidth); Element e1 = lf.getElementMap().get(node.getXpath()); Element body = lf.getElementMap().get("/HTML/BODY"); Graphics2D g2d = img.createGraphics(); g2d.setColor(Color.RED); g2d.setStroke(new BasicStroke(3)); int[] coords = e1.getBoundingCoords(); // System.out.println(e1.getXpath()); // System.out.println(Arrays.toString(coords)); g2d.drawRect(coords[0], coords[1], coords[2] - coords[0], coords[3] - coords[1]); g2d.setColor(Color.GREEN); // g2d.setStroke(new BasicStroke(5, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{9}, 0)); int[] coords2 = body.getBoundingCoords(); // System.out.println(Arrays.toString(coords2)); g2d.drawRect(coords2[0], coords2[1], coords2[2] - coords2[0], coords2[3] - coords2[1]); g2d.dispose(); File output = Utils.getOutputFilePath(url, timeStamp, errorID); FileUtils.forceMkdir(output); ImageIO.write(img, "png", new File(output+ "/viewportOverflowWidth" + captureWidth + ".png")); } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException npe) { System.out.println("Could not find one of the offending elements in screenshot."); } } @Override public HashSet<Node> getNodes() { HashSet<Node> nodes = new HashSet<>(); nodes.add(node); return nodes; } @Override public int[] getBounds() { return new int[] {min, max}; } }
farkasmate/pdk
lib/pdk/cli.rb
require 'cri' require 'pdk/cli/errors' require 'pdk/cli/util' require 'pdk/cli/util/command_redirector' require 'pdk/cli/util/option_normalizer' require 'pdk/cli/util/option_validator' require 'pdk/cli/exec_group' require 'pdk/generators/module' require 'pdk/i18n' require 'pdk/logger' require 'pdk/report' require 'pdk/util/version' module PDK::CLI def self.run(args) @base_cmd.run(args) rescue PDK::CLI::ExitWithError => e PDK.logger.error(e.message) exit e.exit_code rescue PDK::CLI::FatalError => e PDK.logger.fatal(e.message) if e.message # If FatalError was raised as the result of another exception, send the # details of that exception to the debug log. If there was no cause # (FatalError raised on its own outside a rescue block), send the details # of the FatalError exception to the debug log. cause = e.cause if cause.nil? e.backtrace.each { |line| PDK.logger.debug(line) } else PDK.logger.debug("#{cause.class}: #{cause.message}") cause.backtrace.each { |line| PDK.logger.debug(line) } end exit e.exit_code end def self.template_url_option(dsl) dsl.option nil, 'template-url', _('Specifies the URL to the template to use when creating new modules or classes.'), argument: :required, default: PDK::Generate::Module.default_template_url end def self.skip_interview_option(dsl) dsl.option nil, 'skip-interview', _('When specified, skips interactive querying of metadata.') end @base_cmd = Cri::Command.define do name 'pdk' usage _('pdk command [options]') summary _('Puppet Development Kit') description _('The shortest path to better modules.') default_subcommand 'help' flag nil, :version, _('Show version of pdk.') do |_, _| puts PDK::Util::Version.version_string exit 0 end flag :h, :help, _('Show help for this command.') do |_, c| puts c.help exit 0 end format_desc = _( "Specify desired output format. Valid formats are '%{available_formats}'. " \ 'You may also specify a file to which the formatted output is sent, ' \ "for example: '--format=junit:report.xml'. This option may be specified " \ 'multiple times if each option specifies a distinct target file.', ) % { available_formats: PDK::Report.formats.join("', '") } option :f, :format, format_desc, argument: :required, multiple: true do |values| PDK::CLI::Util::OptionNormalizer.report_formats(values.compact) end flag :d, :debug, _('Enable debug output.') do |_, _| PDK.logger.enable_debug_output end option nil, 'answer-file', _('Path to an answer file.'), argument: :required, hidden: true do |value| PDK.answer_file = value end end require 'pdk/cli/bundle' require 'pdk/cli/new' require 'pdk/cli/test' require 'pdk/cli/validate' require 'pdk/cli/module' @base_cmd.add_command Cri::Command.new_basic_help end
cuongquay/led-matrix-display
AdsLedMatrixCMS/v3.0.1/Tools/NewProperty.cpp
<filename>AdsLedMatrixCMS/v3.0.1/Tools/NewProperty.cpp // NewProperty.cpp : implementation file // #include "stdafx.h" // CNewPropertyPage dialog IMPLEMENT_DYNAMIC(CNewPropertyPage, CPropertyPage) CNewPropertyPage::CNewPropertyPage() { } CNewPropertyPage::~CNewPropertyPage() { } CNewPropertyPage::CNewPropertyPage(UINT nIDTemplate, UINT nIDCaption, DWORD dwSize) { free(m_pPSP); m_pPSP=NULL; ASSERT(nIDTemplate != 0); AllocPSP(dwSize); CommonConstruct(MAKEINTRESOURCE(nIDTemplate), nIDCaption); } CNewPropertyPage::CNewPropertyPage(LPCTSTR lpszTemplateName, UINT nIDCaption , DWORD dwSize) { free(m_pPSP); m_pPSP=NULL; ASSERT(AfxIsValidString(lpszTemplateName)); AllocPSP(dwSize); CommonConstruct(lpszTemplateName, nIDCaption); } // extended construction CNewPropertyPage::CNewPropertyPage(UINT nIDTemplate, UINT nIDCaption,UINT nIDHeaderTitle, UINT nIDHeaderSubTitle, DWORD dwSize) { free(m_pPSP); m_pPSP=NULL; ASSERT(nIDTemplate != 0); AllocPSP(dwSize); CommonConstruct(MAKEINTRESOURCE(nIDTemplate), nIDCaption, nIDHeaderTitle, nIDHeaderSubTitle); } CNewPropertyPage::CNewPropertyPage(LPCTSTR lpszTemplateName, UINT nIDCaption, UINT nIDHeaderTitle, UINT nIDHeaderSubTitle, DWORD dwSize) { free(m_pPSP); m_pPSP=NULL; ASSERT(AfxIsValidString(lpszTemplateName)); AllocPSP(dwSize); CommonConstruct(lpszTemplateName, nIDCaption, nIDHeaderTitle, nIDHeaderSubTitle); } BEGIN_MESSAGE_MAP(CNewPropertyPage, CNewFrame<CPropertyPage>) END_MESSAGE_MAP() // CNewPropertyPage dialog IMPLEMENT_DYNAMIC(CNewPropertySheet, CPropertySheet) CNewPropertySheet::CNewPropertySheet() { } CNewPropertySheet::~CNewPropertySheet() { } CNewPropertySheet::CNewPropertySheet(UINT nIDCaption, CWnd* pParentWnd, UINT iSelectPage) { ASSERT(nIDCaption != 0); VERIFY(m_strCaption.LoadString(nIDCaption)); CommonConstruct(pParentWnd, iSelectPage); } CNewPropertySheet::CNewPropertySheet(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage) { ASSERT(pszCaption != NULL); m_strCaption = pszCaption; CommonConstruct(pParentWnd, iSelectPage); } // extended construction CNewPropertySheet::CNewPropertySheet(UINT nIDCaption, CWnd* pParentWnd, UINT iSelectPage, HBITMAP hbmWatermark, HPALETTE hpalWatermark, HBITMAP hbmHeader) { ASSERT(nIDCaption != 0); VERIFY(m_strCaption.LoadString(nIDCaption)); CommonConstruct(pParentWnd, iSelectPage); } CNewPropertySheet::CNewPropertySheet(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage, HBITMAP hbmWatermark, HPALETTE hpalWatermark , HBITMAP hbmHeader) { ASSERT(pszCaption != NULL); m_strCaption = pszCaption; CommonConstruct(pParentWnd, iSelectPage); } BEGIN_MESSAGE_MAP(CNewPropertySheet, CNewFrame<CPropertySheet>) END_MESSAGE_MAP() // CNewPropertyPage message handlers
christophersiem/MoodBoos
frontend/src/components/dialogs/UserDeleteDialog.js
<reponame>christophersiem/MoodBoos import React, { useContext, useState } from 'react'; import Button from '@material-ui/core/Button'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogTitle from '@material-ui/core/DialogTitle'; import { makeStyles } from '@material-ui/core/styles'; import { deleteUser } from '../../utils/auth-utils'; import { removeJWTToken } from '../../utils/jwt-utils'; import { LOGIN_FAILED } from '../../context/user/UserContextProvider'; import { UserDispatchContext, UserStateContext, } from '../../context/user/UserContext'; import Grid from '@material-ui/core/Grid'; const useStyles = makeStyles((theme) => ({ delete: { color: '#951010', margin: '15px 0px', }, delButton: { color: '#951010', alignSelf: 'center', marginTop: '20px', }, text: { fontFamily: theme.typography.subtitle2.fontFamily, }, })); export default function UserDeleteDialog() { const classes = useStyles(); const [open, setOpen] = useState(false); const dispatch = useContext(UserDispatchContext); const { userData } = useContext(UserStateContext); const handleClickOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; function handleClickDelete() { console.log(userData.userName); deleteUser(userData.userName) .then(removeJWTToken()) .catch((e) => console.error(e)); dispatch({ type: LOGIN_FAILED }); } return ( <> <Button className={classes.delButton} onClick={handleClickOpen}> Delete Your Account </Button> <Dialog open={open} onClose={handleClose} aria-labelledby="caution" aria-describedby="alert-dialog-description" > <DialogTitle id="caution">{'Caution'}</DialogTitle> <DialogContent> <DialogContentText id="alert-dialog-description" className={classes.text} > Are you sure you want to delete your Account? This cannot be undone </DialogContentText> </DialogContent> <DialogActions> <Grid container justify="space-around" alignItems="center"> <Grid item> <Button className={classes.delete} onClick={() => { handleClickDelete(); }} href="/" > Delete </Button> </Grid> <Button onClick={handleClose} style={{ color: '#47392d' }} autoFocus > Cancel </Button> </Grid> </DialogActions> </Dialog> </> ); }
Qualicen/Specmate
ui-tests/src/test/java/com/specmate/uitests/TestBase.java
<filename>ui-tests/src/test/java/com/specmate/uitests/TestBase.java package com.specmate.uitests; import java.net.URL; import java.util.LinkedList; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Rule; import org.junit.rules.TestName; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import com.saucelabs.common.SauceOnDemandAuthentication; import com.saucelabs.common.SauceOnDemandSessionIdProvider; import com.saucelabs.junit.SauceOnDemandTestWatcher; import com.specmate.uitests.pagemodel.LoginElements; import com.specmate.uitests.pagemodel.UITestUtil; @Ignore @RunWith(Parameterized.class) public class TestBase implements SauceOnDemandSessionIdProvider { public static String username = System.getenv("SAUCE_USERNAME"); public static String accesskey = System.getenv("SAUCE_ACCESS_KEY"); public static String seleniumURI; public static String buildTag; public static final String tunnelidentifier = System.getenv("TRAVIS_JOB_NUMBER"); public SauceOnDemandAuthentication authentication = new SauceOnDemandAuthentication(); /** Mark the Sauce Job as passed/failed when the test succeeds or fails */ @Rule public SauceOnDemandTestWatcher resultReportingTestWatcher = new SauceOnDemandTestWatcher(this, authentication); @Rule public TestName name = new TestName() { public String getMethodName() { return String.format("%s", super.getMethodName()); } }; protected String browser; protected String os; protected String version; protected String deviceName; protected String deviceOrientation; protected String sessionId; protected WebDriver driver; /** Constructor for test instances */ public TestBase(String os, String version, String browser, String deviceName, String deviceOrientation) { super(); this.os = os; this.version = version; this.browser = browser; this.deviceName = deviceName; this.deviceOrientation = deviceOrientation; } /** Browser configurations */ @Parameters public static LinkedList<String[]> browsersStrings() { LinkedList<String[]> browsers = new LinkedList<String[]>(); browsers.add(new String[] { "Windows 10", "93.0", "Chrome", null, null }); // browsers.add(new String[]{"Windows 10", "18.17763", "MicrosoftEdge", null, // null}); // browsers.add(new String[]{"Windows 10", "73.0", "firefox", null, null}); return browsers; } @Before public void setUp() throws Exception { // TODO change this to true for local test execution. The path to the chromedriver must be adapted boolean isLocalTest = false; DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(CapabilityType.BROWSER_NAME, browser); capabilities.setCapability(CapabilityType.VERSION, version); capabilities.setCapability("deviceName", deviceName); capabilities.setCapability("device-orientation", deviceOrientation); capabilities.setCapability("platform", os); capabilities.setCapability("tunnel-identifier", "github-action-tunnel-" + System.getenv("GITHUB_RUN_NUMBER")); String methodName = name.getMethodName(); capabilities.setCapability("name", methodName); if (buildTag != null) { capabilities.setCapability("build", buildTag); } if (!isLocalTest) { this.driver = new RemoteWebDriver( new URL("https://" + username + ":" + accesskey + seleniumURI + "/wd/hub"), capabilities); } else { // TODO Adapt the path // The version of the driver must be the same as the browser, download here: https://chromedriver.chromium.org/downloads System.setProperty("webdriver.chrome.driver", "Q:\\chromedriver.exe"); driver = new ChromeDriver(); } driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS); if (!isLocalTest) { this.sessionId = (((RemoteWebDriver) driver).getSessionId()).toString(); } } @After public void tearDown() throws Exception { driver.quit(); } public String getSessionId() { return sessionId; } @BeforeClass public static void setupClass() { // Get the uri to send the commands to seleniumURI = "@ondemand.saucelabs.com:443"; // Set the buildTag to the Github Action number buildTag = "#" + System.getenv("GITHUB_RUN_NUMBER"); if (buildTag == null) { buildTag = System.getenv("SAUCE_BUILD_NAME"); } } public void performLogin(LoginElements login) { UITestUtil.waitForProjectsToLoad(driver); login.username("username"); login.password("password"); login.changeToEnglish(); login.changeToGerman(); login.changeToProject("test-data"); login.login(); } }
icemanblues/advent-of-code
2015/day11/day11.go
package main import ( "fmt" ) const ( dayNum = "11" dayTitle = "Corporate Policy" ) const input = "hepxcrrq" var badRunes map[rune]struct{} = map[rune]struct{}{ 'i': {}, 'o': {}, 'l': {}, } var base26 []rune = []rune{ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', } var map26 map[rune]int = make(map[rune]int) func init() { for i, r := range base26 { map26[r] = i } } func validPassword(s string) bool { runes := []rune(s) // one increasing straight for i := 0; i < len(runes)-2; i++ { r := runes[i] rr := runes[i+1] rrr := runes[i+2] } // cannot contain i, o, l containsIOL := false for _, r := range s { if _, ok := badRunes[r]; ok { containsIOL = true break } } // two different, non-overlapping pairs pairs := make(map[rune]struct{}) for i := 0; i < len(runes)-1; i++ { if runes[i] == runes[i+1] { pairs[runes[i]] = struct{}{} } } hasTwoPairs := len(pairs) >= 2 return hasTwoPairs && !containsIOL } func part1() { fmt.Println("Part 1") fmt.Printf("%v\n", len(map26)) } func part2() { fmt.Println("Part 2") } func main() { fmt.Printf("Day %v: %v\n", dayNum, dayTitle) part1() part2() }
JohnnyTh/pytorch_multiproject
pytorch_multiproject/projects/CycleGAN/test.py
<gh_stars>1-10 import sys import os ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname('__file__')))) sys.path.insert(0, ROOT_DIR) import logging import torch import torch.nn as nn import torchvision.transforms as transforms from torch import optim from torch.utils.data import DataLoader from models.cycle_GAN import CycleGAN, GanGenerator, GanDiscriminator, GanOptimizer, GanLrScheduler from data.cycle_gan_dataset import CycleGanDataset from trainers.cycle_gan_trainer import CycleGanTrainer from logger.logger import main_run, default_log_config # default configuration file with hyperparameters DEFAULT_CONFIG = 'train.json' def main(config, args): # create an instance of logger logger = logging.getLogger(os.path.basename(__file__)) resources_dir = os.path.join(ROOT_DIR, 'resources', 'horse2zebra') test_sources = os.path.join(resources_dir, 'testA') test_targets = os.path.join(resources_dir, 'testB') trans_non_aug = transforms.Compose([transforms.ToPILImage(), transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) # get datasets test_dataset = CycleGanDataset(root=resources_dir, data_paths=[test_sources, test_targets], extensions=(('.jpg'),)*2, random_pairs=False, transform=trans_non_aug) # create dataloaders test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False, num_workers=0) # define generator generator = GanGenerator() # define discriminator discriminator = GanDiscriminator() # define criteria for losses gan_loss = nn.MSELoss() cycle_loss = nn.L1Loss() identity_loss = nn.L1Loss() model_hyperparams = {'lambda_identity': 0.5, 'lambda_a': 10.0, 'lambda_b': 10.0} model = CycleGAN(generator, discriminator, gan_loss, cycle_loss, identity_loss, model_hyperparams) # create optimizers for generators and discriminators optim_gen, optim_disc = model.get_optims(lr=config.get('lr', 0.0002)) # enable parallel forward pass computation if possible if torch.cuda.device_count() > 1: model = nn.DataParallel(model) optimizer = GanOptimizer(optim_gen, optim_disc) trainer = CycleGanTrainer(dataloaders=test_loader, root=ROOT_DIR, model=model, criterion=None, optimizer=optimizer, scheduler=None, metrics=None, epochs=1, save_dir=args.save_dir, checkpoint=args.checkpoint) trainer.test() if __name__ == '__main__': default_log_config() main_run(main, DEFAULT_CONFIG)
amiranmanesh/go-smart-api-maker
utils/validation/validation.go
package validation import ( "encoding/json" "github.com/go-playground/validator/v10" "regexp" ) func EmailValidate(email string) bool { //regular expression for email re := regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") return re.MatchString(email) } func GetValidationErrors(err error) []map[string]string { validatorErrors := make([]map[string]string, 0) switch err.(type) { case validator.ValidationErrors: { for _, fieldErr := range err.(validator.ValidationErrors) { item := map[string]string{} item[fieldErr.Field()] = fieldErr.Tag() validatorErrors = append(validatorErrors, item) } } case *json.UnmarshalTypeError: { item := map[string]string{} item["json_bind_error"] = err.Error() validatorErrors = append(validatorErrors, item) } default: { item := map[string]string{} item["unknown_error"] = err.Error() validatorErrors = append(validatorErrors, item) } } return validatorErrors } var phoneValidaion validator.Func = func(fl validator.FieldLevel) bool { value := fl.Field().String() return PhoneRegex(value) } func PhoneRegex(phone string) bool { matched, err := regexp.MatchString(`^09\d{9}$`, phone) if err != nil { return false } return matched }
garroshh/gloo-mesh
pkg/api/networking.enterprise.mesh.gloo.solo.io/v1beta1/controller/event_handlers.go
<filename>pkg/api/networking.enterprise.mesh.gloo.solo.io/v1beta1/controller/event_handlers.go // Code generated by skv2. DO NOT EDIT. //go:generate mockgen -source ./event_handlers.go -destination mocks/event_handlers.go // Definitions for the Kubernetes Controllers package controller import ( "context" networking_enterprise_mesh_gloo_solo_io_v1beta1 "github.com/solo-io/gloo-mesh/pkg/api/networking.enterprise.mesh.gloo.solo.io/v1beta1" "github.com/pkg/errors" "github.com/solo-io/skv2/pkg/events" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/predicate" ) // Handle events for the WasmDeployment Resource // DEPRECATED: Prefer reconciler pattern. type WasmDeploymentEventHandler interface { CreateWasmDeployment(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.WasmDeployment) error UpdateWasmDeployment(old, new *networking_enterprise_mesh_gloo_solo_io_v1beta1.WasmDeployment) error DeleteWasmDeployment(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.WasmDeployment) error GenericWasmDeployment(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.WasmDeployment) error } type WasmDeploymentEventHandlerFuncs struct { OnCreate func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.WasmDeployment) error OnUpdate func(old, new *networking_enterprise_mesh_gloo_solo_io_v1beta1.WasmDeployment) error OnDelete func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.WasmDeployment) error OnGeneric func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.WasmDeployment) error } func (f *WasmDeploymentEventHandlerFuncs) CreateWasmDeployment(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.WasmDeployment) error { if f.OnCreate == nil { return nil } return f.OnCreate(obj) } func (f *WasmDeploymentEventHandlerFuncs) DeleteWasmDeployment(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.WasmDeployment) error { if f.OnDelete == nil { return nil } return f.OnDelete(obj) } func (f *WasmDeploymentEventHandlerFuncs) UpdateWasmDeployment(objOld, objNew *networking_enterprise_mesh_gloo_solo_io_v1beta1.WasmDeployment) error { if f.OnUpdate == nil { return nil } return f.OnUpdate(objOld, objNew) } func (f *WasmDeploymentEventHandlerFuncs) GenericWasmDeployment(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.WasmDeployment) error { if f.OnGeneric == nil { return nil } return f.OnGeneric(obj) } type WasmDeploymentEventWatcher interface { AddEventHandler(ctx context.Context, h WasmDeploymentEventHandler, predicates ...predicate.Predicate) error } type wasmDeploymentEventWatcher struct { watcher events.EventWatcher } func NewWasmDeploymentEventWatcher(name string, mgr manager.Manager) WasmDeploymentEventWatcher { return &wasmDeploymentEventWatcher{ watcher: events.NewWatcher(name, mgr, &networking_enterprise_mesh_gloo_solo_io_v1beta1.WasmDeployment{}), } } func (c *wasmDeploymentEventWatcher) AddEventHandler(ctx context.Context, h WasmDeploymentEventHandler, predicates ...predicate.Predicate) error { handler := genericWasmDeploymentHandler{handler: h} if err := c.watcher.Watch(ctx, handler, predicates...); err != nil { return err } return nil } // genericWasmDeploymentHandler implements a generic events.EventHandler type genericWasmDeploymentHandler struct { handler WasmDeploymentEventHandler } func (h genericWasmDeploymentHandler) Create(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.WasmDeployment) if !ok { return errors.Errorf("internal error: WasmDeployment handler received event for %T", object) } return h.handler.CreateWasmDeployment(obj) } func (h genericWasmDeploymentHandler) Delete(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.WasmDeployment) if !ok { return errors.Errorf("internal error: WasmDeployment handler received event for %T", object) } return h.handler.DeleteWasmDeployment(obj) } func (h genericWasmDeploymentHandler) Update(old, new client.Object) error { objOld, ok := old.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.WasmDeployment) if !ok { return errors.Errorf("internal error: WasmDeployment handler received event for %T", old) } objNew, ok := new.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.WasmDeployment) if !ok { return errors.Errorf("internal error: WasmDeployment handler received event for %T", new) } return h.handler.UpdateWasmDeployment(objOld, objNew) } func (h genericWasmDeploymentHandler) Generic(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.WasmDeployment) if !ok { return errors.Errorf("internal error: WasmDeployment handler received event for %T", object) } return h.handler.GenericWasmDeployment(obj) } // Handle events for the RateLimiterServerConfig Resource // DEPRECATED: Prefer reconciler pattern. type RateLimiterServerConfigEventHandler interface { CreateRateLimiterServerConfig(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.RateLimiterServerConfig) error UpdateRateLimiterServerConfig(old, new *networking_enterprise_mesh_gloo_solo_io_v1beta1.RateLimiterServerConfig) error DeleteRateLimiterServerConfig(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.RateLimiterServerConfig) error GenericRateLimiterServerConfig(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.RateLimiterServerConfig) error } type RateLimiterServerConfigEventHandlerFuncs struct { OnCreate func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.RateLimiterServerConfig) error OnUpdate func(old, new *networking_enterprise_mesh_gloo_solo_io_v1beta1.RateLimiterServerConfig) error OnDelete func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.RateLimiterServerConfig) error OnGeneric func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.RateLimiterServerConfig) error } func (f *RateLimiterServerConfigEventHandlerFuncs) CreateRateLimiterServerConfig(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.RateLimiterServerConfig) error { if f.OnCreate == nil { return nil } return f.OnCreate(obj) } func (f *RateLimiterServerConfigEventHandlerFuncs) DeleteRateLimiterServerConfig(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.RateLimiterServerConfig) error { if f.OnDelete == nil { return nil } return f.OnDelete(obj) } func (f *RateLimiterServerConfigEventHandlerFuncs) UpdateRateLimiterServerConfig(objOld, objNew *networking_enterprise_mesh_gloo_solo_io_v1beta1.RateLimiterServerConfig) error { if f.OnUpdate == nil { return nil } return f.OnUpdate(objOld, objNew) } func (f *RateLimiterServerConfigEventHandlerFuncs) GenericRateLimiterServerConfig(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.RateLimiterServerConfig) error { if f.OnGeneric == nil { return nil } return f.OnGeneric(obj) } type RateLimiterServerConfigEventWatcher interface { AddEventHandler(ctx context.Context, h RateLimiterServerConfigEventHandler, predicates ...predicate.Predicate) error } type rateLimiterServerConfigEventWatcher struct { watcher events.EventWatcher } func NewRateLimiterServerConfigEventWatcher(name string, mgr manager.Manager) RateLimiterServerConfigEventWatcher { return &rateLimiterServerConfigEventWatcher{ watcher: events.NewWatcher(name, mgr, &networking_enterprise_mesh_gloo_solo_io_v1beta1.RateLimiterServerConfig{}), } } func (c *rateLimiterServerConfigEventWatcher) AddEventHandler(ctx context.Context, h RateLimiterServerConfigEventHandler, predicates ...predicate.Predicate) error { handler := genericRateLimiterServerConfigHandler{handler: h} if err := c.watcher.Watch(ctx, handler, predicates...); err != nil { return err } return nil } // genericRateLimiterServerConfigHandler implements a generic events.EventHandler type genericRateLimiterServerConfigHandler struct { handler RateLimiterServerConfigEventHandler } func (h genericRateLimiterServerConfigHandler) Create(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.RateLimiterServerConfig) if !ok { return errors.Errorf("internal error: RateLimiterServerConfig handler received event for %T", object) } return h.handler.CreateRateLimiterServerConfig(obj) } func (h genericRateLimiterServerConfigHandler) Delete(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.RateLimiterServerConfig) if !ok { return errors.Errorf("internal error: RateLimiterServerConfig handler received event for %T", object) } return h.handler.DeleteRateLimiterServerConfig(obj) } func (h genericRateLimiterServerConfigHandler) Update(old, new client.Object) error { objOld, ok := old.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.RateLimiterServerConfig) if !ok { return errors.Errorf("internal error: RateLimiterServerConfig handler received event for %T", old) } objNew, ok := new.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.RateLimiterServerConfig) if !ok { return errors.Errorf("internal error: RateLimiterServerConfig handler received event for %T", new) } return h.handler.UpdateRateLimiterServerConfig(objOld, objNew) } func (h genericRateLimiterServerConfigHandler) Generic(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.RateLimiterServerConfig) if !ok { return errors.Errorf("internal error: RateLimiterServerConfig handler received event for %T", object) } return h.handler.GenericRateLimiterServerConfig(obj) } // Handle events for the VirtualDestination Resource // DEPRECATED: Prefer reconciler pattern. type VirtualDestinationEventHandler interface { CreateVirtualDestination(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualDestination) error UpdateVirtualDestination(old, new *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualDestination) error DeleteVirtualDestination(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualDestination) error GenericVirtualDestination(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualDestination) error } type VirtualDestinationEventHandlerFuncs struct { OnCreate func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualDestination) error OnUpdate func(old, new *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualDestination) error OnDelete func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualDestination) error OnGeneric func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualDestination) error } func (f *VirtualDestinationEventHandlerFuncs) CreateVirtualDestination(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualDestination) error { if f.OnCreate == nil { return nil } return f.OnCreate(obj) } func (f *VirtualDestinationEventHandlerFuncs) DeleteVirtualDestination(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualDestination) error { if f.OnDelete == nil { return nil } return f.OnDelete(obj) } func (f *VirtualDestinationEventHandlerFuncs) UpdateVirtualDestination(objOld, objNew *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualDestination) error { if f.OnUpdate == nil { return nil } return f.OnUpdate(objOld, objNew) } func (f *VirtualDestinationEventHandlerFuncs) GenericVirtualDestination(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualDestination) error { if f.OnGeneric == nil { return nil } return f.OnGeneric(obj) } type VirtualDestinationEventWatcher interface { AddEventHandler(ctx context.Context, h VirtualDestinationEventHandler, predicates ...predicate.Predicate) error } type virtualDestinationEventWatcher struct { watcher events.EventWatcher } func NewVirtualDestinationEventWatcher(name string, mgr manager.Manager) VirtualDestinationEventWatcher { return &virtualDestinationEventWatcher{ watcher: events.NewWatcher(name, mgr, &networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualDestination{}), } } func (c *virtualDestinationEventWatcher) AddEventHandler(ctx context.Context, h VirtualDestinationEventHandler, predicates ...predicate.Predicate) error { handler := genericVirtualDestinationHandler{handler: h} if err := c.watcher.Watch(ctx, handler, predicates...); err != nil { return err } return nil } // genericVirtualDestinationHandler implements a generic events.EventHandler type genericVirtualDestinationHandler struct { handler VirtualDestinationEventHandler } func (h genericVirtualDestinationHandler) Create(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualDestination) if !ok { return errors.Errorf("internal error: VirtualDestination handler received event for %T", object) } return h.handler.CreateVirtualDestination(obj) } func (h genericVirtualDestinationHandler) Delete(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualDestination) if !ok { return errors.Errorf("internal error: VirtualDestination handler received event for %T", object) } return h.handler.DeleteVirtualDestination(obj) } func (h genericVirtualDestinationHandler) Update(old, new client.Object) error { objOld, ok := old.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualDestination) if !ok { return errors.Errorf("internal error: VirtualDestination handler received event for %T", old) } objNew, ok := new.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualDestination) if !ok { return errors.Errorf("internal error: VirtualDestination handler received event for %T", new) } return h.handler.UpdateVirtualDestination(objOld, objNew) } func (h genericVirtualDestinationHandler) Generic(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualDestination) if !ok { return errors.Errorf("internal error: VirtualDestination handler received event for %T", object) } return h.handler.GenericVirtualDestination(obj) } // Handle events for the VirtualGateway Resource // DEPRECATED: Prefer reconciler pattern. type VirtualGatewayEventHandler interface { CreateVirtualGateway(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualGateway) error UpdateVirtualGateway(old, new *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualGateway) error DeleteVirtualGateway(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualGateway) error GenericVirtualGateway(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualGateway) error } type VirtualGatewayEventHandlerFuncs struct { OnCreate func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualGateway) error OnUpdate func(old, new *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualGateway) error OnDelete func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualGateway) error OnGeneric func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualGateway) error } func (f *VirtualGatewayEventHandlerFuncs) CreateVirtualGateway(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualGateway) error { if f.OnCreate == nil { return nil } return f.OnCreate(obj) } func (f *VirtualGatewayEventHandlerFuncs) DeleteVirtualGateway(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualGateway) error { if f.OnDelete == nil { return nil } return f.OnDelete(obj) } func (f *VirtualGatewayEventHandlerFuncs) UpdateVirtualGateway(objOld, objNew *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualGateway) error { if f.OnUpdate == nil { return nil } return f.OnUpdate(objOld, objNew) } func (f *VirtualGatewayEventHandlerFuncs) GenericVirtualGateway(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualGateway) error { if f.OnGeneric == nil { return nil } return f.OnGeneric(obj) } type VirtualGatewayEventWatcher interface { AddEventHandler(ctx context.Context, h VirtualGatewayEventHandler, predicates ...predicate.Predicate) error } type virtualGatewayEventWatcher struct { watcher events.EventWatcher } func NewVirtualGatewayEventWatcher(name string, mgr manager.Manager) VirtualGatewayEventWatcher { return &virtualGatewayEventWatcher{ watcher: events.NewWatcher(name, mgr, &networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualGateway{}), } } func (c *virtualGatewayEventWatcher) AddEventHandler(ctx context.Context, h VirtualGatewayEventHandler, predicates ...predicate.Predicate) error { handler := genericVirtualGatewayHandler{handler: h} if err := c.watcher.Watch(ctx, handler, predicates...); err != nil { return err } return nil } // genericVirtualGatewayHandler implements a generic events.EventHandler type genericVirtualGatewayHandler struct { handler VirtualGatewayEventHandler } func (h genericVirtualGatewayHandler) Create(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualGateway) if !ok { return errors.Errorf("internal error: VirtualGateway handler received event for %T", object) } return h.handler.CreateVirtualGateway(obj) } func (h genericVirtualGatewayHandler) Delete(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualGateway) if !ok { return errors.Errorf("internal error: VirtualGateway handler received event for %T", object) } return h.handler.DeleteVirtualGateway(obj) } func (h genericVirtualGatewayHandler) Update(old, new client.Object) error { objOld, ok := old.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualGateway) if !ok { return errors.Errorf("internal error: VirtualGateway handler received event for %T", old) } objNew, ok := new.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualGateway) if !ok { return errors.Errorf("internal error: VirtualGateway handler received event for %T", new) } return h.handler.UpdateVirtualGateway(objOld, objNew) } func (h genericVirtualGatewayHandler) Generic(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualGateway) if !ok { return errors.Errorf("internal error: VirtualGateway handler received event for %T", object) } return h.handler.GenericVirtualGateway(obj) } // Handle events for the VirtualHost Resource // DEPRECATED: Prefer reconciler pattern. type VirtualHostEventHandler interface { CreateVirtualHost(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualHost) error UpdateVirtualHost(old, new *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualHost) error DeleteVirtualHost(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualHost) error GenericVirtualHost(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualHost) error } type VirtualHostEventHandlerFuncs struct { OnCreate func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualHost) error OnUpdate func(old, new *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualHost) error OnDelete func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualHost) error OnGeneric func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualHost) error } func (f *VirtualHostEventHandlerFuncs) CreateVirtualHost(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualHost) error { if f.OnCreate == nil { return nil } return f.OnCreate(obj) } func (f *VirtualHostEventHandlerFuncs) DeleteVirtualHost(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualHost) error { if f.OnDelete == nil { return nil } return f.OnDelete(obj) } func (f *VirtualHostEventHandlerFuncs) UpdateVirtualHost(objOld, objNew *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualHost) error { if f.OnUpdate == nil { return nil } return f.OnUpdate(objOld, objNew) } func (f *VirtualHostEventHandlerFuncs) GenericVirtualHost(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualHost) error { if f.OnGeneric == nil { return nil } return f.OnGeneric(obj) } type VirtualHostEventWatcher interface { AddEventHandler(ctx context.Context, h VirtualHostEventHandler, predicates ...predicate.Predicate) error } type virtualHostEventWatcher struct { watcher events.EventWatcher } func NewVirtualHostEventWatcher(name string, mgr manager.Manager) VirtualHostEventWatcher { return &virtualHostEventWatcher{ watcher: events.NewWatcher(name, mgr, &networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualHost{}), } } func (c *virtualHostEventWatcher) AddEventHandler(ctx context.Context, h VirtualHostEventHandler, predicates ...predicate.Predicate) error { handler := genericVirtualHostHandler{handler: h} if err := c.watcher.Watch(ctx, handler, predicates...); err != nil { return err } return nil } // genericVirtualHostHandler implements a generic events.EventHandler type genericVirtualHostHandler struct { handler VirtualHostEventHandler } func (h genericVirtualHostHandler) Create(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualHost) if !ok { return errors.Errorf("internal error: VirtualHost handler received event for %T", object) } return h.handler.CreateVirtualHost(obj) } func (h genericVirtualHostHandler) Delete(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualHost) if !ok { return errors.Errorf("internal error: VirtualHost handler received event for %T", object) } return h.handler.DeleteVirtualHost(obj) } func (h genericVirtualHostHandler) Update(old, new client.Object) error { objOld, ok := old.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualHost) if !ok { return errors.Errorf("internal error: VirtualHost handler received event for %T", old) } objNew, ok := new.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualHost) if !ok { return errors.Errorf("internal error: VirtualHost handler received event for %T", new) } return h.handler.UpdateVirtualHost(objOld, objNew) } func (h genericVirtualHostHandler) Generic(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.VirtualHost) if !ok { return errors.Errorf("internal error: VirtualHost handler received event for %T", object) } return h.handler.GenericVirtualHost(obj) } // Handle events for the RouteTable Resource // DEPRECATED: Prefer reconciler pattern. type RouteTableEventHandler interface { CreateRouteTable(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.RouteTable) error UpdateRouteTable(old, new *networking_enterprise_mesh_gloo_solo_io_v1beta1.RouteTable) error DeleteRouteTable(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.RouteTable) error GenericRouteTable(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.RouteTable) error } type RouteTableEventHandlerFuncs struct { OnCreate func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.RouteTable) error OnUpdate func(old, new *networking_enterprise_mesh_gloo_solo_io_v1beta1.RouteTable) error OnDelete func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.RouteTable) error OnGeneric func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.RouteTable) error } func (f *RouteTableEventHandlerFuncs) CreateRouteTable(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.RouteTable) error { if f.OnCreate == nil { return nil } return f.OnCreate(obj) } func (f *RouteTableEventHandlerFuncs) DeleteRouteTable(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.RouteTable) error { if f.OnDelete == nil { return nil } return f.OnDelete(obj) } func (f *RouteTableEventHandlerFuncs) UpdateRouteTable(objOld, objNew *networking_enterprise_mesh_gloo_solo_io_v1beta1.RouteTable) error { if f.OnUpdate == nil { return nil } return f.OnUpdate(objOld, objNew) } func (f *RouteTableEventHandlerFuncs) GenericRouteTable(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.RouteTable) error { if f.OnGeneric == nil { return nil } return f.OnGeneric(obj) } type RouteTableEventWatcher interface { AddEventHandler(ctx context.Context, h RouteTableEventHandler, predicates ...predicate.Predicate) error } type routeTableEventWatcher struct { watcher events.EventWatcher } func NewRouteTableEventWatcher(name string, mgr manager.Manager) RouteTableEventWatcher { return &routeTableEventWatcher{ watcher: events.NewWatcher(name, mgr, &networking_enterprise_mesh_gloo_solo_io_v1beta1.RouteTable{}), } } func (c *routeTableEventWatcher) AddEventHandler(ctx context.Context, h RouteTableEventHandler, predicates ...predicate.Predicate) error { handler := genericRouteTableHandler{handler: h} if err := c.watcher.Watch(ctx, handler, predicates...); err != nil { return err } return nil } // genericRouteTableHandler implements a generic events.EventHandler type genericRouteTableHandler struct { handler RouteTableEventHandler } func (h genericRouteTableHandler) Create(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.RouteTable) if !ok { return errors.Errorf("internal error: RouteTable handler received event for %T", object) } return h.handler.CreateRouteTable(obj) } func (h genericRouteTableHandler) Delete(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.RouteTable) if !ok { return errors.Errorf("internal error: RouteTable handler received event for %T", object) } return h.handler.DeleteRouteTable(obj) } func (h genericRouteTableHandler) Update(old, new client.Object) error { objOld, ok := old.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.RouteTable) if !ok { return errors.Errorf("internal error: RouteTable handler received event for %T", old) } objNew, ok := new.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.RouteTable) if !ok { return errors.Errorf("internal error: RouteTable handler received event for %T", new) } return h.handler.UpdateRouteTable(objOld, objNew) } func (h genericRouteTableHandler) Generic(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.RouteTable) if !ok { return errors.Errorf("internal error: RouteTable handler received event for %T", object) } return h.handler.GenericRouteTable(obj) } // Handle events for the ServiceDependency Resource // DEPRECATED: Prefer reconciler pattern. type ServiceDependencyEventHandler interface { CreateServiceDependency(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.ServiceDependency) error UpdateServiceDependency(old, new *networking_enterprise_mesh_gloo_solo_io_v1beta1.ServiceDependency) error DeleteServiceDependency(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.ServiceDependency) error GenericServiceDependency(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.ServiceDependency) error } type ServiceDependencyEventHandlerFuncs struct { OnCreate func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.ServiceDependency) error OnUpdate func(old, new *networking_enterprise_mesh_gloo_solo_io_v1beta1.ServiceDependency) error OnDelete func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.ServiceDependency) error OnGeneric func(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.ServiceDependency) error } func (f *ServiceDependencyEventHandlerFuncs) CreateServiceDependency(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.ServiceDependency) error { if f.OnCreate == nil { return nil } return f.OnCreate(obj) } func (f *ServiceDependencyEventHandlerFuncs) DeleteServiceDependency(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.ServiceDependency) error { if f.OnDelete == nil { return nil } return f.OnDelete(obj) } func (f *ServiceDependencyEventHandlerFuncs) UpdateServiceDependency(objOld, objNew *networking_enterprise_mesh_gloo_solo_io_v1beta1.ServiceDependency) error { if f.OnUpdate == nil { return nil } return f.OnUpdate(objOld, objNew) } func (f *ServiceDependencyEventHandlerFuncs) GenericServiceDependency(obj *networking_enterprise_mesh_gloo_solo_io_v1beta1.ServiceDependency) error { if f.OnGeneric == nil { return nil } return f.OnGeneric(obj) } type ServiceDependencyEventWatcher interface { AddEventHandler(ctx context.Context, h ServiceDependencyEventHandler, predicates ...predicate.Predicate) error } type serviceDependencyEventWatcher struct { watcher events.EventWatcher } func NewServiceDependencyEventWatcher(name string, mgr manager.Manager) ServiceDependencyEventWatcher { return &serviceDependencyEventWatcher{ watcher: events.NewWatcher(name, mgr, &networking_enterprise_mesh_gloo_solo_io_v1beta1.ServiceDependency{}), } } func (c *serviceDependencyEventWatcher) AddEventHandler(ctx context.Context, h ServiceDependencyEventHandler, predicates ...predicate.Predicate) error { handler := genericServiceDependencyHandler{handler: h} if err := c.watcher.Watch(ctx, handler, predicates...); err != nil { return err } return nil } // genericServiceDependencyHandler implements a generic events.EventHandler type genericServiceDependencyHandler struct { handler ServiceDependencyEventHandler } func (h genericServiceDependencyHandler) Create(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.ServiceDependency) if !ok { return errors.Errorf("internal error: ServiceDependency handler received event for %T", object) } return h.handler.CreateServiceDependency(obj) } func (h genericServiceDependencyHandler) Delete(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.ServiceDependency) if !ok { return errors.Errorf("internal error: ServiceDependency handler received event for %T", object) } return h.handler.DeleteServiceDependency(obj) } func (h genericServiceDependencyHandler) Update(old, new client.Object) error { objOld, ok := old.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.ServiceDependency) if !ok { return errors.Errorf("internal error: ServiceDependency handler received event for %T", old) } objNew, ok := new.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.ServiceDependency) if !ok { return errors.Errorf("internal error: ServiceDependency handler received event for %T", new) } return h.handler.UpdateServiceDependency(objOld, objNew) } func (h genericServiceDependencyHandler) Generic(object client.Object) error { obj, ok := object.(*networking_enterprise_mesh_gloo_solo_io_v1beta1.ServiceDependency) if !ok { return errors.Errorf("internal error: ServiceDependency handler received event for %T", object) } return h.handler.GenericServiceDependency(obj) }
gaponenko/art
art/Framework/Core/detail/Analyzer.h
#ifndef art_Framework_Core_detail_Analyzer_h #define art_Framework_Core_detail_Analyzer_h // vim: set sw=2 expandtab : // // The base class for all analyzer modules. // #include "art/Framework/Core/Observer.h" #include "art/Framework/Core/ProcessingFrame.h" #include "art/Framework/Core/detail/ImplicitConfigs.h" #include "art/Framework/Core/fwd.h" #include "art/Framework/Principal/fwd.h" #include "art/Persistency/Provenance/fwd.h" #include "art/Utilities/ScheduleID.h" #include "cetlib/exempt_ptr.h" #include "fhiclcpp/types/ConfigurationTable.h" #include "fhiclcpp/types/KeysToIgnore.h" #include "fhiclcpp/types/OptionalTable.h" #include "fhiclcpp/types/Table.h" #include "fhiclcpp/types/TableFragment.h" #include <atomic> #include <cstddef> #include <ostream> #include <string> namespace art { class SharedResources; } namespace art::detail { class Analyzer : public Observer { public: template <typename UserConfig, typename UserKeysToIgnore = void> class Table : public fhicl::ConfigurationTable { template <typename T> struct FullConfig { fhicl::Atom<std::string> module_type{ detail::ModuleConfig::plugin_type()}; fhicl::TableFragment<Observer::EOConfig> eoConfig; fhicl::TableFragment<T> user; }; using KeysToIgnore_t = std::conditional_t<std::is_void<UserKeysToIgnore>::value, detail::ModuleConfig::IgnoreKeys, fhicl::KeysToIgnore<detail::ModuleConfig::IgnoreKeys, UserKeysToIgnore>>; public: explicit Table(fhicl::Name&& name) : fullConfig_{std::move(name)} {} Table(fhicl::ParameterSet const& pset) : fullConfig_{pset} {} auto const& operator()() const { return fullConfig_().user(); } auto const& eoFragment() const { return fullConfig_().eoConfig(); } auto const& get_PSet() const { return fullConfig_.get_PSet(); } void print_allowed_configuration(std::ostream& os, std::string const& prefix) const { fullConfig_.print_allowed_configuration(os, prefix); } private: cet::exempt_ptr<fhicl::detail::ParameterBase const> get_parameter_base() const override { return &fullConfig_; } fhicl::Table<FullConfig<UserConfig>, KeysToIgnore_t> fullConfig_; }; public: virtual ~Analyzer() noexcept; explicit Analyzer(fhicl::ParameterSet const& pset); template <typename Config> explicit Analyzer(Table<Config> const& config) : Observer{config.eoFragment().selectEvents(), config.get_PSet()} {} void doBeginJob(SharedResources const& resources); void doEndJob(); void doRespondToOpenInputFile(FileBlock const& fb); void doRespondToCloseInputFile(FileBlock const& fb); void doRespondToOpenOutputFiles(FileBlock const& fb); void doRespondToCloseOutputFiles(FileBlock const& fb); bool doBeginRun(RunPrincipal& rp, ModuleContext const& mc); bool doEndRun(RunPrincipal& rp, ModuleContext const& mc); bool doBeginSubRun(SubRunPrincipal& srp, ModuleContext const& mc); bool doEndSubRun(SubRunPrincipal& srp, ModuleContext const& mc); bool doEvent(EventPrincipal& ep, ModuleContext const& mc, std::atomic<std::size_t>& counts_run, std::atomic<std::size_t>& counts_passed, std::atomic<std::size_t>& counts_failed); private: virtual void setupQueues(SharedResources const&) = 0; virtual void analyzeWithFrame(Event const&, ProcessingFrame const&) = 0; virtual void beginJobWithFrame(ProcessingFrame const&) = 0; virtual void endJobWithFrame(ProcessingFrame const&) = 0; virtual void respondToOpenInputFileWithFrame(FileBlock const&, ProcessingFrame const&) = 0; virtual void respondToCloseInputFileWithFrame(FileBlock const&, ProcessingFrame const&) = 0; virtual void respondToOpenOutputFilesWithFrame(FileBlock const&, ProcessingFrame const&) = 0; virtual void respondToCloseOutputFilesWithFrame(FileBlock const&, ProcessingFrame const&) = 0; virtual void beginRunWithFrame(Run const&, ProcessingFrame const&) = 0; virtual void endRunWithFrame(Run const&, ProcessingFrame const&) = 0; virtual void beginSubRunWithFrame(SubRun const&, ProcessingFrame const&) = 0; virtual void endSubRunWithFrame(SubRun const&, ProcessingFrame const&) = 0; }; template <typename T> inline std::ostream& operator<<(std::ostream& os, Analyzer::Table<T> const& t) { std::ostringstream config; t.print_allowed_configuration(config, std::string(3, ' ')); return os << config.str(); } } // namespace art::detail #endif /* art_Framework_Core_detail_Analyzer_h */ // Local Variables: // mode: c++ // End:
huanjka/AutoCADPlugin-HeatSource
ObjectARX 2016/samples/database/ARXDBG/Prompt/ArxDbgUiPrBase.cpp
<gh_stars>1-10 // ////////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk license // agreement provided at the time of installation or download, or which // otherwise accompanies this software in either electronic or hard copy form. // ////////////////////////////////////////////////////////////////////////////// // #include "StdAfx.h" #if defined(_DEBUG) && !defined(AC_FULL_DEBUG) #error _DEBUG should not be defined except in internal Adesk debug builds #endif #include "ArxDbgUiPrBase.h" /**************************************************************************** ** ** ArxDbgUiPrBase::ArxDbgUiPrBase ** ** **jma ** *************************************/ ArxDbgUiPrBase::ArxDbgUiPrBase(LPCTSTR msg, LPCTSTR keyWordList) : m_keyWords(keyWordList), m_message(msg) { ASSERT(msg != NULL); } /**************************************************************************** ** ** ArxDbgUiPrBase::~ArxDbgUiPrBase ** ** **jma ** *************************************/ ArxDbgUiPrBase::~ArxDbgUiPrBase() { } /**************************************************************************** ** ** ArxDbgUiPrBase::keyWords ** ** **jma ** *************************************/ LPCTSTR ArxDbgUiPrBase::keyWords() const { return m_keyWords; } /**************************************************************************** ** ** ArxDbgUiPrBase::setKeyWords ** ** **jma ** *************************************/ Acad::ErrorStatus ArxDbgUiPrBase::setKeyWords(LPCTSTR keyWordList) { ASSERT(keyWordList != NULL); m_keyWords = keyWordList; return Acad::eOk; } /**************************************************************************** ** ** ArxDbgUiPrBase::message ** ** **jma ** *************************************/ LPCTSTR ArxDbgUiPrBase::message() const { return m_message; } /**************************************************************************** ** ** ArxDbgUiPrBase::setMessage ** ** **jma ** *************************************/ Acad::ErrorStatus ArxDbgUiPrBase::setMessage(LPCTSTR msg) { m_message = msg; return Acad::eOk; } /**************************************************************************** ** ** ArxDbgUiPrBase::keyWordPicked ** ** **jma ** *************************************/ LPCTSTR ArxDbgUiPrBase::keyWordPicked() const { ASSERT(m_keyWordPicked.IsEmpty() == false); return m_keyWordPicked; } /**************************************************************************** ** ** ArxDbgUiPrBase::isKeyWordPicked ** ** **jma ** *************************************/ bool ArxDbgUiPrBase::isKeyWordPicked(LPCTSTR keyWordMatch) { ASSERT(m_keyWordPicked.IsEmpty() == false); ASSERT(keyWordMatch != NULL); if (m_keyWordPicked == keyWordMatch) return true; else return false; }
tcarnoldussen/Menge
src/Menge/MengeCore/data_set_selector.h
<gh_stars>100-1000 #pragma once #include <cassert> #include <vector> #include "MengeCore/BFSM/fsmCommon.h" #include "MengeCore/Math/RandGenerator.h" #include "MengeCore/Runtime/ReadersWriterLock.h" namespace Menge { /*! @brief The underlying definition of a set-based selector. The set-based selector contains a unique collection of `Data` elements. Data instances can be drawn from the set based on index, uniform random selection, or weighted random selection. */ template <typename Data> class SetSelector { public: /*! @brief Reports the number of data elements in the set. *Not* thread safe. */ size_t size() const { return _data.size(); } /*! @brief Reports the number of data elements in the set. Thread safe version. */ size_t size_concurrent() const; /*! @brief Adds a data element to the set (with an implied unit weight of 1.0). This is thread safe. @param data The data element to add to the set. The data element must live longer than this set. */ void addData(Data* data) { addData(data, 1.f); } /*! @brief Adds a data element to the set with the given weight. This is thread safe. @param data The data element to add to the set. The data element must live longer than this set. @param weight The weight for this element. */ void addData(Data* data, float weight) { _lock.lockWrite(); _data.emplace_back(data, weight); _total_weight += weight; _lock.releaseWrite(); } /*! @brief Returns the ith element in the set (where i = `index`). The ordering is defined by the order in which they were added to the set through calls to addData(). *Not* thread safe. @param index The index of the desired data element. */ Data* getByIndex(size_t index) { assert(index < _data.size()); return _data[index].data; } /*! @brief Returns the ith element in the set (where i = `index`). The ordering is defined by the order in which they were added to the set through calls to addData(). The thread safe version. @param index The index of the desired data element. */ Data* getByIndexConcurrent(size_t index) { _lock.lockRead(); Data* data = getByIndex(index); _lock.releaseRead(); return data; } /*! @brief Select one of the elements where all elements have equal probability. */ Data* getRandom() const { const size_t DATA_COUNT = _data.size(); if (DATA_COUNT) { size_t index = static_cast<size_t>(DATA_COUNT * _random_value.getValue()); // A hacky way to handle a random value of 1.0. index = index < DATA_COUNT ? index : DATA_COUNT - 1; return _data[index].data; } return nullptr; } /*! @brief Select on of the elements with probabilities proportional to their relative weights. */ Data* getWeighted() const { Data* result = nullptr; if (_data.size() > 0) { const float TGT_WEIGHT = _total_weight * _random_value.getValue(); float accum_weight = 0.f; for (auto& item : _data) { accum_weight += item.weight; if (accum_weight > TGT_WEIGHT) return item.data; } } return result; } private: // Internal structure for storing data and weight. struct WeightedData { WeightedData(Data* data_in, float weight_in) : data(data_in), weight(weight_in) {} Data* data; float weight; }; // The members of the set. std::vector<WeightedData> _data; // Bookkeeping -- the total accumulated weight. float _total_weight{0.f}; // Built-in random-number generator. mutable Math::UniformFloatGenerator _random_value{0.f, 1.f}; // The lock to maintain readers-writer access to the structure which controls the data. mutable ReadersWriterLock _lock; }; } // namespace Menge
Anirban166/tstl
deprecated/obsolete/src/ldominion2.py
<reponame>Anirban166/tstl import random DEBUG = True MAX_PLAYERS = 4 MAX_DECK = 10 MAX_HAND = 10 MAX_CARDS = 27 Curse = 0 Estate = 1 Duchy = 2 Province = 3 Copper = 4 Silver = 5 Gold = 6 Adventurer = 7 Ambassador = 8 Baron = 9 Council_Room = 10 Cutpurse = 11 Embargo = 12 Feast = 13 Gardens = 14 Great_Hall = 15 Mine = 16 Minion = 17 Outpost = 18 Remodel = 19 Salvager = 20 Sea_Hag = 21 Smithy = 22 Steward = 23 Treasure_Map = 24 Tribute = 25 Village = 26 class Game(): numPlayers =2 supplyCount = [0] * MAX_CARDS embargoTokens = [0] * MAX_CARDS outpostPlayed = 0 outpostTurn = 0 whoseTurn = 0 phase = 0 bonus = 0 numActions = 0 coins = 0 numBuys = 0 kingdomCards = [] deck = {} deckCount = [0] * MAX_PLAYERS discard = {} discardCount = [0] * MAX_PLAYERS hand = {} handCount = [0] * MAX_PLAYERS playedCards = [] playedCardCount = 0 def initializeGame(numPlayers, kingdomCards, randomSeed): game = Game() game.numPlayers = numPlayers if numPlayers > MAX_PLAYERS or numPlayers < 2: return -1 random.seed(randomSeed) game.kingdomCards = kingdomCards if len(kingdomCards) > 10 or len(kingdomCards) < 10: return -1 for i in range(10): if kingdomCards[i] not in [Adventurer, Ambassador, Baron ,Council_Room ,Cutpurse ,Embargo ,Feast ,Gardens ,Great_Hall ,Mine ,Minion ,Outpost ,Remodel ,Salvager ,Sea_Hag ,Smithy ,Steward ,Treasure_Map, Tribute, Village]: return -1; for i in range(10): for j in range(10): if j != i and kingdomCards[i] == kingdomCards[j]: return -1 if (numPlayers == 2): game.supplyCount[Curse] = 10 elif (numPlayers == 3): game.supplyCount[Curse] = 20 else: game.supplyCount[Curse] = 30 if (numPlayers == 2): game.supplyCount[Estate] = 8 game.supplyCount[Duchy] = 8 game.supplyCount[Province] = 8 else: game.supplyCount[Estate] = 12 game.supplyCount[Duchy] = 12 game.supplyCount[Province] = 12 game.supplyCount[Copper] = 60 - (7 * numPlayers) game.supplyCount[Silver] = 40 game.supplyCount[Gold] = 30 for i in range(Adventurer,MAX_CARDS): for j in range(10): if (kingdomCards[j] == i): if (kingdomCards[j] == Great_Hall or kingdomCards[j] == Gardens): if (numPlayers == 2): game.supplyCount[i] = 8 else: game.supplyCount[i] = 12 else: game.supplyCount[i] = 10 break else: game.supplyCount[i] = -1 for i in range(numPlayers): game.deckCount[i] = 0 game.deck[i] = [] game.hand[i] = [] game.discard[i] = [] for j in range(3): game.deck[i].append(Estate) game.deckCount[i] += 1 for j in range(3, 10): game.deck[i].append(Copper) game.deckCount[i] += 1 for i in range(numPlayers): shuffle(i, game) for i in range(numPlayers): game.handCount[i] = 0 game.discardCount[i] = 0 for i in range(Village): game.embargoTokens[i] = 0 game.outpostPlayed = 0 game.phase = 0 game.numActions = 1 game.numBuys = 1 game.playedCardCount = 0 game.whoseTurn = 0 game.handCount[game.whoseTurn] = 0 for it in range(5): drawCard(game.whoseTurn, game) updateCoins(game.whoseTurn, game, 0) return game def shuffle(player, g): if (g.deckCount[player] < 1): return -1 g.deck[player].sort() random.shuffle(g.deck[player]) return 0 def drawCard(player, g): if (g.deckCount[player] <= 0): g.deck[player] = g.discard[player] g.discard[player] = [] g.deckCount[player] = g.discardCount[player] g.discardCount[player] = 0 shuffle(player, g) g.discardCount[player] = 0 count = g.handCount[player] deckCounter = g.deckCount[player] if (deckCounter == 0): return -1 g.hand[player].append(g.deck[player][deckCounter - 1]) g.deck[player].pop(deckCount[player]-1) g.deckCount[player] -= 1 g.handCount[player] += 1 else: count = g.handCount[player] deckCounter = g.deckCount[player] g.hand[player].append(g.deck[player][deckCounter - 1]) g.deck[player].pop(g.deckCount[player]-1) g.deckCount[player] -= 1 g.handCount[player] += 1 return 0 def updateCoins(player, g, bonus): g.coins = 0 g.bonus+= bonus for card in g.hand[player]: if (card == Copper): g.coins += 1 elif (card == Silver): g.coins += 2 elif (card == Gold): g.coins += 3 g.coins += bonus return 0 def gainCard(supplyPos, g, toFlag, player): if g.supplyCount[supplyPos] < 1 : return -1 if (toFlag == 1): g.deck[player].append(supplyPos) g.deckCount[player]+=1 g.supplyCount[supplyPos]-=1 elif (toFlag == 2): g.hand[ player ].append(supplyPos) g.handCount[player]+=1 g.supplyCount[supplyPos]-=1 else: g.discard[player].append(supplyPos) g.discardCount[player]+=1 g.supplyCount[supplyPos]-=1 return 0 def discardCard(handPos, currentPlayer, g, trashFlag): if handPos not in g.hand[currentPlayer]: return -1 else: if (trashFlag == 0): g.playedCards.append(handPos) g.playedCardCount+=1 elif (trashFlag == 2): g.discard[currentPlayer].append(handPos) g.discardCount[currentPlayer]+=1 g.hand[currentPlayer].remove(handPos) return 0 ##fixCardHole(handPos, currentPlayer, g) def buyCard(supplyPos, g): if (g.numBuys < 1): return -1 elif (g.supplyCount[supplyPos] <1): return -1 elif (g.coins < getCost(supplyPos)): return -1 else: g.phase=1 gainCard(supplyPos,g, 0, g.whoseTurn) g.coins = (g.coins) - (getCost(supplyPos)) g.numBuys-=1 for i in range(g.embargoTokens[supplyPos]): gainCard('Curse',g,0,g.whoseTurn) return 0 def getCost(cardNumber): if cardNumber == Curse: return 0 if cardNumber == Estate: return 2 if cardNumber == Duchy: return 5 if cardNumber == Province: return 8 if cardNumber == Copper: return 0 if cardNumber == Silver: return 3 if cardNumber == Gold: return 6 if cardNumber == Adventurer: return 6 if cardNumber == Ambassador: return 3 if cardNumber == Baron: return 4 if cardNumber == Council_Room: return 5 if cardNumber == Cutpurse: return 4 if cardNumber == Embargo: return 2 if cardNumber == Feast: return 4 if cardNumber == Gardens: return 4 if cardNumber == Great_Hall: return 3 if cardNumber == Mine: return 5 if cardNumber == Minion: return 5 if cardNumber == Outpost: return 5 if cardNumber == Remodel: return 4 if cardNumber == Salvager: return 4 if cardNumber == Sea_Hag: return 4 if cardNumber == Smithy: return 4 if cardNumber == Steward: return 3 if cardNumber == Treasure_Map: return 4 if cardNumber == Tribute: return 5 if cardNumber == Village: return 3 else: return -1 def endTurn(g): currentPlayer = g.whoseTurn g.discard[currentPlayer].extend(g.hand[currentPlayer]) g.discardCount[currentPlayer]+=1 g.hand[currentPlayer] = [] g.handCount[currentPlayer] = 0 if currentPlayer < (g.numPlayers - 1): g.whoseTurn = currentPlayer + 1 else: g.whoseTurn = 0 g.outpostPlayed = 0 g.phase = 0 g.numActions = 1 g.coins = 0 g.numBuys = 1 g.playedCards = [] g.bonus = 0 g.playedCardCount = 0 g.handCount[g.whoseTurn] = 0 for k in range(5): drawCard(g.whoseTurn, g) updateCoins(g.whoseTurn, g , 0) return 0 def playCard(handPos, choice1, choice2, choice3, g): card = g.hand[g.whoseTurn][handPos] if (g.phase != 0): return -1 if (g.numActions < 1 ): return -1 if card not in g.kingdomCards: return -1 if card not in g.hand[g.whoseTurn]: return -1 if ( cardEffect(card, choice1, choice2, choice3, g, handPos, g.bonus) < 0 ): return -1 g.numActions-=1 discardCard(card,g.whoseTurn,g,0) updateCoins(g.whoseTurn, g, g.bonus) return 0 def cardEffect(card, choice1, choice2, choice3, g, handPos, bonus): currentPlayer = g.whoseTurn nextPlayer = (g.whoseTurn+1)%g.numPlayers tributeRevealedCards = [-1, -1] temphand = [] drawntreasure = 0 if card == Adventurer: while(drawntreasure<2): if (g.deckCount[currentPlayer] <1): shuffle(currentPlayer, g) drawCard(currentPlayer, g) cardDrawn = g.hand[currentPlayer][g.handCount[currentPlayer]-1] if (cardDrawn == Copper or cardDrawn == Silver or cardDrawn == Gold): drawntreasure+=1 else: temphand.append(g.hand[currentPlayer].pop(g.handCount[currentPlayer]-1)) discardCard(handPos, currentPlayer, g, 0) return 0 elif card == Ambassador: if g.hand[currentPlayer][choice1] not in g.hand[currentPlayer]: return -1 for i in range(2): if g.hand[currentPlayer][choice1] in g.hand[currentPlayer]: g.hand[currentPlayer].remove(g.hand[currentPlayer][choice1]) g.supplyCount[g.hand[currentPlayer][choice1]]+=1 discardCard(handPos, currentPlayer, g, 0) return 0 elif card == Baron: g.numBuys+=1 if (g.hand[currentPlayer][choice1] == Estate) and (g.hand[currentPlayer][choice1] in g.hand[currentPlayer]): discardCard(g.hand[currentPlayer][choice1],currentPlayer,g,2) updateCoins(currentPlayer,g,4) else: gainCard(Estate,g,0,currentPlayer) discardCard(handPos, currentPlayer, g, 0) return 0 elif card == Council_Room: for i in range(4): drawCard(currentPlayer, g) g.numBuys+=1 for i in range(g.numPlayers): if ( i != currentPlayer ): drawCard(i, g) discardCard(handPos, currentPlayer, g, 0) return 0 elif card == Cutpurse: updateCoins(currentPlayer, g, 2) for i in range(g.numPlayers): if (i != currentPlayer): if (Copper in g.hand[i]): discardCard(Copper, i, g, 0) discardCard(handPos, currentPlayer, g, 0) return 0 elif card == Embargo: updateCoins(currentPlayer,g,2) if ( g.supplyCount[choice1] == -1 ): return -1 g.embargoTokens[choice1]+=1 discardCard(handPos, currentPlayer, g, 1) return 0 elif card == Feast: if (g.supplyCount[choice1] <= 0): return -1 elif (getCost(choice1) > 5): return -1 elif (getCost(choice1) < 6): gainCard(choice1, g, 0, currentPlayer) discardCard(handPos, currentPlayer, g, 1) return 0 elif card == Gardens: return -1 elif card == Great_Hall: drawCard(currentPlayer,g); g.numActions+=1 discardCard(handPos, currentPlayer, g, 0) return 0 elif card == Mine: if (g.hand[currentPlayer][choice1] not in g.hand[currentPlayer]): return -1 elif (g.hand[currentPlayer][choice1] < Copper or g.hand[currentPlayer][choice1] > Gold): return -1 if (g.hand[currentPlayer][choice1] == Copper and choice2 == Silver): discardCard(Copper,currentPlayer,g,1) gainCard(Silver,g,2,currentPlayer) return 0 elif (g.hand[currentPlayer][choice1] == Copper and choice2 == Gold): discardCard(Copper,currentPlayer,g,1) gainCard(Gold,g,2,currentPlayer) return 0 elif (g.hand[currentPlayer][choice1] == Copper and choice2 == Copper): discardCard(Copper,currentPlayer,g,1) gainCard(Copper,g,2,currentPlayer) return 0 elif (choice2 > Gold or choice2 < Copper): return -1 elif( (getCost(g.hand[currentPlayer][choice1]) + 3) > getCost(choice2) ): return -1 else: return -1 discardCard(handPos, currentPlayer, g, 0) return 0 elif card == Minion: g.numActions+=1 discardCard(handPos, currentPlayer,g, 0) if (choice1): updateCoins(currentPlayer,g,2) elif (choice2): while(g.handcount[currentPlayer] > 0): discardCard(handPos, currentPlayer, g, 0) for i in range(4): drawCard(currentPlayer, g) for i in range(g.numPlayers): if (i != currentPlayer): if ( g.handCount[i] > 4 ): while( g.handCount[i] > 0 ): discardCard(handPos, i, g, 0) for j in range(4): drawCard(i, g) discardCard(handPos, currentPlayer, g, 0) return 0 elif card == Outpost: g.outpostPlayed+=1 discardCard(handPos, currentPlayer, g, 0) return 0 elif card == Remodel: j = g.hand[currentPlayer][choice1] if ( (getCost(g.hand[currentPlayer][choice1]) + 2) < getCost(choice2) ): return -1 else: gainCard(choice2, g, 0, currentPlayer) discardCard(handPos, currentPlayer, g, 1) discardCard(handPos, currentPlayer, g, 0) return 0 elif card == Salvager: g.numBuys+=1 if (choice1): g.coins = g.coins + getCost( g.hand[currentPlayer][handPos] ) discardCard(choice1, currentPlayer, g, 1) discardCard(handPos, currentPlayer, g, 0) return 0 elif card == Sea_Hag: for i in range(g.numPlayers): if (i != currentPlayer): drawCard(i,g) discardCard(g.hand[i][handCount[i]-1],i,g,2) gainCard(Curse,g,1,i) discardCard(handPos, currentPlayer, g, 0) return 0 elif card == Smithy: for i in range(3): drawCard(currentPlayer,g) discardCard(handPos,currentPlayer,g, 0) return 0 elif card == Steward: if (choice1 == 1): drawCard(currentPlayer, g) drawCard(currentPlayer, g) elif (choice1 == 2): g.coins = g.coins + 2 else: discardCard(choice2, currentPlayer, g, 1) discardCard(choice3, currentPlayer, g, 1) discardCard(handPos, currentPlayer, g, 0) return 0 elif card == Treasure_Map: index = -1 for i in range(handCount[currentPlayer]): if (g.hand[currentPlayer][i] == Treasure_Map and i != handPos): index = i break if (index > -1): discardCard(handPos, currentPlayer, g, 1) discardCard(index, currentPlayer, g, 1) for i in range(4): gainCard(Gold, g, 1, currentPlayer) discardCard(handPos, currentPlayer, g, 0) return 0 elif card == Village: drawCard(currentPlayer, g) g.numActions = g.numActions + 2 discardCard(handPos, currentPlayer, g, 0) return 0 def isGameOver(g): j=0 if (g.supplyCount[Province] == 0): return 1 for i in range(MAX_CARDS): if (g.supplyCount[i] == 0): j+=1 if ( j >= 3): return 1 return 0 def scoreFor (player, g): score = 0 fullDeck = g.deck[player]+g.hand[player]+g.discard[player] for card in fullDeck: if card == Estate: score+=1 if card == Duchy: score+=3 if card == Province: score+=6 if card == Great_Hall: score+=2 if card == Curse: score-=1 if card == Gardens: score = (len(fullDeck)%10) return score def getWinners(g): players =[0] * MAX_PLAYERS for i in range(MAX_PLAYERS): if (i >= g.numPlayers): players[i] = -9999 else: players[i] = scoreFor (i, g) j = 0 for i in range(MAX_PLAYERS): if (players[i] > players[j]): j = i highScore = players[j] currentPlayer = g.whoseTurn for i in range(MAX_PLAYERS): if ( players[i] == highScore and i > currentPlayer ): players[i]+=1 j = 0 for i in range(MAX_PLAYERS): if ( players[i] > players[j] ): j = i highScore = players[j] for i in range(MAX_PLAYERS): if ( players[i] == highScore ): players[i] = 1 else: players[i] = 0 return players
vkaltyrin/exchanger
Exchanger/Services/ExchangeMoneyService/ExchangeMoneyService.h
<filename>Exchanger/Services/ExchangeMoneyService/ExchangeMoneyService.h #import <Foundation/Foundation.h> #import "Wallet.h" #import "Currency.h" #import "User.h" #import "ExchangeMoneyData.h" @protocol ExchangeMoneyService <NSObject> - (void)exchangeWithUser:(User *)user moneyAmount:(NSNumber *)moneyAmount sourceCurrency:(Currency *)sourceCurrency targetCurrency:(Currency *)targetCurrency onResult:(void(^)(ExchangeMoneyData *))onResult; - (void)exchangeWallet:(Wallet *)wallet targetCurrency:(Currency *)currency onResult:(void(^)(Wallet *wallet))onResult; - (void)convertedCurrencyWithSourceCurrency:(Currency *)sourceCurrency targetCurrency:(Currency *)targetCurrency onConvert:(void(^)(Currency *))onConvert; @end
peter-empen/tessella
jvm/src/vision/id/tessella/OptionUtils.scala
package vision.id.tessella trait OptionUtils { final implicit class Opt[T](o: Option[T]) { def safeGet(msg: String = "cannot get, none"): T = o match { case Some(t) => t case None => throw new IllegalArgumentException(msg) } } }
Houkime/echo
engine/core/render/vulkan/vk_mapping.cpp
<gh_stars>0 #include "vk_mapping.h" namespace Echo { VkPrimitiveTopology VKMapping::MapPrimitiveTopology(Mesh::TopologyType type) { switch (type) { case Mesh::TT_POINTLIST: return VK_PRIMITIVE_TOPOLOGY_POINT_LIST; case Mesh::TT_LINELIST: return VK_PRIMITIVE_TOPOLOGY_LINE_LIST; case Mesh::TT_LINESTRIP: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP; case Mesh::TT_TRIANGLELIST: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; case Mesh::TT_TRIANGLESTRIP: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; } } String VKMapping::MapVertexSemanticString(VertexSemantic semantic) { switch (semantic) { case VS_POSITION: return "a_Position"; case VS_BLENDINDICES: return "a_Joint"; case VS_BLENDWEIGHTS: return "a_Weight"; case VS_COLOR: return "a_Color"; case VS_NORMAL: return "a_Normal"; case VS_TEXCOORD0: return "a_UV"; case VS_TEXCOORD1: return "a_UV1"; case VS_TANGENT: return "a_Tangent"; case VS_BINORMAL: return "a_Binormal"; default: return ""; } } VkBufferUsageFlags VKMapping::MapGpuBufferUsageFlags(GPUBuffer::GPUBufferType type) { switch (type) { case GPUBuffer::GBT_INDEX: return VK_BUFFER_USAGE_INDEX_BUFFER_BIT; case GPUBuffer::GBT_VERTEX: return VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; case GPUBuffer::GBT_UNIFORM: return VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; default: { EchoLogError("Unknown GPUBufferType.") return VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; } } } VkFormat VKMapping::MapVertexFormat(PixelFormat pixelFormat) { switch (pixelFormat) { case PF_RG32_FLOAT: return VK_FORMAT_R32G32_SFLOAT; case PF_RGBA8_UNORM: return VK_FORMAT_R8G8B8A8_UNORM; case PF_RGBA8_SNORM: return VK_FORMAT_R8G8B8A8_SNORM; case PF_RGB32_FLOAT: return VK_FORMAT_R32G32B32_SFLOAT; case PF_RGBA32_FLOAT: return VK_FORMAT_R32G32B32A32_SFLOAT; default: EchoLogError("MapingVertexFormat failed"); return VK_FORMAT_UNDEFINED; } } ShaderParamType VKMapping::MapUniformType(const spirv_cross::SPIRType& spirType) { switch (spirType.basetype) { case spirv_cross::SPIRType::BaseType::Int: return SPT_INT; case spirv_cross::SPIRType::BaseType::Float: { if (spirType.columns == 1) { if (spirType.vecsize == 1) return SPT_FLOAT; else if (spirType.vecsize == 2) return SPT_VEC2; else if (spirType.vecsize == 3) return SPT_VEC3; else if (spirType.vecsize == 4) return SPT_VEC4; } else if (spirType.columns == 4) { if (spirType.vecsize == 4) return SPT_MAT4; } EchoLogError("vulkan MapUniformType failed"); return SPT_UNKNOWN; } case spirv_cross::SPIRType::Image: return SPT_TEXTURE; case spirv_cross::SPIRType::Sampler: return SPT_TEXTURE; default: EchoLogError("vulkan MapUniformType failed"); return SPT_UNKNOWN; } } }
mikeludemann/helperFunctions_Python
src/DateTime/dayOfMonth.py
<filename>src/DateTime/dayOfMonth.py import time import datetime def dayOfMonth(): return datetime.date.today().strftime("%d")
1byte2bytes/cpython
Mac/Lib/test/aete.py
<gh_stars>1-10 # Look for scriptable applications -- that is, applications with an 'aete' resource # Also contains (partially) reverse engineered 'aete' resource decoding import MacOS import os import string import sys import types import StringIO from Res import * def main(): filename = "" redirect(filename, realmain) def redirect(filename, func, *args): f = filename and open(filename, 'w') save_stdout = sys.stdout try: if f: sys.stdout = f return apply(func, args) finally: sys.stdout = save_stdout if f: f.close() def realmain(): #list('C:System Folder:Extensions:AppleScript\252') #list('C:Tao AppleScript:Finder Liaison:Finder Liaison 1.0') list('C:Tao AppleScript:Scriptable Text Editor') #list('C:Internet:Eudora 1.4.2:Eudora1.4.2') #list('E:Excel 4.0:Microsoft Excel') #list('C:Internet:Netscape 1.0N:Netscape 1.0N') #find('C:') #find('D:') #find('E:') #find('F:') def find(dir, maxlevel = 5): hits = [] cur = CurResFile() names = os.listdir(dir) tuples = map(lambda x: (os.path.normcase(x), x), names) tuples.sort() names = map(lambda (x, y): y, tuples) for name in names: if name in (os.curdir, os.pardir): continue fullname = os.path.join(dir, name) if os.path.islink(fullname): pass if os.path.isdir(fullname): if maxlevel > 0: sys.stderr.write(" %s\n" % `fullname`) hits = hits + find(fullname, maxlevel-1) else: ctor, type = MacOS.GetCreatorAndType(fullname) if type in ('APPL', 'FNDR', 'zsys', 'INIT', 'scri', 'cdev'): sys.stderr.write(" %s\n" % `fullname`) try: rf = OpenRFPerm(fullname, 0, '\1') except MacOS.Error, msg: print "Error:", fullname, msg continue UseResFile(rf) n = Count1Resources('aete') if rf <> cur: CloseResFile(rf) UseResFile(cur) if n > 1: hits.append(fullname) sys.stderr.write("YES! %d in %s\n" % (n, `fullname`)) list(fullname) return hits def list(fullname): cur = CurResFile() rf = OpenRFPerm(fullname, 0, '\1') try: UseResFile(rf) resources = [] for i in range(Count1Resources('aete')): res = Get1IndResource('aete', 1+i) resources.append(res) for i in range(Count1Resources('aeut')): res = Get1IndResource('aeut', 1+i) resources.append(res) print "\nLISTING aete+aeut RESOURCES IN", `fullname` for res in resources: print "decoding", res.GetResInfo(), "..." data = res.data try: aete = decode(data) showaete(aete) print "Checking putaete..." f = StringIO.StringIO() putaete(f, aete) newdata = f.getvalue() if len(newdata) == len(data): if newdata == data: print "putaete created identical data" else: newaete = decode(newdata) if newaete == aete: print "putaete created equivalent data" else: print "putaete failed the test:" showaete(newaete) else: print "putaete created different data:" print `newdata` except: import traceback traceback.print_exc() sys.stdout.flush() finally: if rf <> cur: CloseResFile(rf) UseResFile(cur) def decode(data): f = StringIO.StringIO(data) aete = generic(getaete, f) aete = simplify(aete) processed = f.tell() unprocessed = len(f.read()) total = f.tell() if unprocessed: sys.stderr.write("%d processed + %d unprocessed = %d total\n" % (processed, unprocessed, total)) return aete def simplify(item): if type(item) is types.ListType: return map(simplify, item) elif type(item) == types.TupleType and len(item) == 2: return simplify(item[1]) else: return item # Here follows the aete resource decoder. # It is presented bottom-up instead of top-down because there are direct # references to the lower-level part-decoders from the high-level part-decoders. def getbyte(f, *args): c = f.read(1) if not c: raise EOFError, 'in getbyte' + str(args) return ord(c) def getword(f, *args): getalign(f) s = f.read(2) if len(s) < 2: raise EOFError, 'in getword' + str(args) return (ord(s[0])<<8) | ord(s[1]) def getlong(f, *args): getalign(f) s = f.read(4) if len(s) < 4: raise EOFError, 'in getlong' + str(args) return (ord(s[0])<<24) | (ord(s[1])<<16) | (ord(s[2])<<8) | ord(s[3]) def getostype(f, *args): getalign(f) s = f.read(4) if len(s) < 4: raise EOFError, 'in getostype' + str(args) return s def getpstr(f, *args): c = f.read(1) if len(c) < 1: raise EOFError, 'in getpstr[1]' + str(args) nbytes = ord(c) if nbytes == 0: return '' s = f.read(nbytes) if len(s) < nbytes: raise EOFError, 'in getpstr[2]' + str(args) return s def getalign(f): if f.tell() & 1: c = f.read(1) ##if c <> '\0': ## print 'align:', `c` def getlist(f, description, getitem): count = getword(f) list = [] for i in range(count): list.append(generic(getitem, f)) getalign(f) return list def alt_generic(what, f, *args): print "generic", `what`, args res = vageneric(what, f, args) print '->', `res` return res def generic(what, f, *args): if type(what) == types.FunctionType: return apply(what, (f,) + args) if type(what) == types.ListType: record = [] for thing in what: item = apply(generic, thing[:1] + (f,) + thing[1:]) record.append((thing[1], item)) return record return "BAD GENERIC ARGS: %s" % `what` getdata = [ (getostype, "type"), (getpstr, "description"), (getword, "flags") ] getargument = [ (getpstr, "name"), (getostype, "keyword"), (getdata, "what") ] getevent = [ (getpstr, "name"), (getpstr, "description"), (getostype, "suite code"), (getostype, "event code"), (getdata, "returns"), (getdata, "accepts"), (getlist, "optional arguments", getargument) ] getproperty = [ (getpstr, "name"), (getostype, "code"), (getdata, "what") ] getelement = [ (getostype, "type"), (getlist, "keyform", getostype) ] getclass = [ (getpstr, "name"), (getostype, "class code"), (getpstr, "description"), (getlist, "properties", getproperty), (getlist, "elements", getelement) ] getcomparison = [ (getpstr, "operator name"), (getostype, "operator ID"), (getpstr, "operator comment"), ] getenumerator = [ (getpstr, "enumerator name"), (getostype, "enumerator ID"), (getpstr, "enumerator comment") ] getenumeration = [ (getostype, "enumeration ID"), (getlist, "enumerator", getenumerator) ] getsuite = [ (getpstr, "suite name"), (getpstr, "suite description"), (getostype, "suite ID"), (getword, "suite level"), (getword, "suite version"), (getlist, "events", getevent), (getlist, "classes", getclass), (getlist, "comparisons", getcomparison), (getlist, "enumerations", getenumeration) ] getaete = [ (getword, "major/minor version in BCD"), (getword, "language code"), (getword, "script code"), (getlist, "suites", getsuite) ] # Display 'aete' resources in a friendly manner. # This one's done top-down again... def showaete(aete): [version, language, script, suites] = aete major, minor = divmod(version, 256) print "\nVersion %d/%d, language %d, script %d" % \ (major, minor, language, script) for suite in suites: showsuite(suite) def showsuite(suite): [name, desc, code, level, version, events, classes, comps, enums] = suite print "\nSuite %s -- %s (%s)" % (`name`, `desc`, `code`) print "Level %d, version %d" % (level, version) for event in events: showevent(event) for cls in classes: showclass(cls) for comp in comps: showcomparison(comp) for enum in enums: showenumeration(enum) def showevent(event): [name, desc, code, subcode, returns, accepts, arguments] = event print "\n Command %s -- %s (%s, %s)" % (`name`, `desc`, `code`, `subcode`) print " returns", showdata(returns) print " accepts", showdata(accepts) for arg in arguments: showargument(arg) def showargument(arg): [name, keyword, what] = arg print " %s (%s)" % (name, `keyword`), showdata(what) def showclass(cls): [name, code, desc, properties, elements] = cls print "\n Class %s (%s) -- %s" % (`name`, `code`, `desc`) for prop in properties: showproperty(prop) for elem in elements: showelement(elem) def showproperty(prop): [name, code, what] = prop print " property %s (%s)" % (`name`, `code`), showdata(what) def showelement(elem): [code, keyform] = elem print " element %s" % `code`, "as", keyform def showcomparison(comp): [name, code, comment] = comp print " comparison %s (%s) -- %s" % (`name`, `code`, comment) def showenumeration(enum): [code, items] = enum print "\n Enum %s" % `code` for item in items: showenumerator(item) def showenumerator(item): [name, code, desc] = item print " %s (%s) -- %s" % (`name`, `code`, `desc`) def showdata(data): [type, description, flags] = data return "%s -- %s %s" % (`type`, `description`, showdataflags(flags)) dataflagdict = {15: "optional", 14: "list", 13: "enum", 12: "mutable"} def showdataflags(flags): bits = [] for i in range(16): if flags & (1<<i): if i in dataflagdict.keys(): bits.append(dataflagdict[i]) else: bits.append(`i`) return '[%s]' % string.join(bits) # Write an 'aete' resource. # Closedly modelled after showaete()... def putaete(f, aete): [version, language, script, suites] = aete putword(f, version) putword(f, language) putword(f, script) putlist(f, suites, putsuite) def putsuite(f, suite): [name, desc, code, level, version, events, classes, comps, enums] = suite putpstr(f, name) putpstr(f, desc) putostype(f, code) putword(f, level) putword(f, version) putlist(f, events, putevent) putlist(f, classes, putclass) putlist(f, comps, putcomparison) putlist(f, enums, putenumeration) def putevent(f, event): [name, desc, eventclass, eventid, returns, accepts, arguments] = event putpstr(f, name) putpstr(f, desc) putostype(f, eventclass) putostype(f, eventid) putdata(f, returns) putdata(f, accepts) putlist(f, arguments, putargument) def putargument(f, arg): [name, keyword, what] = arg putpstr(f, name) putostype(f, keyword) putdata(f, what) def putclass(f, cls): [name, code, desc, properties, elements] = cls putpstr(f, name) putostype(f, code) putpstr(f, desc) putlist(f, properties, putproperty) putlist(f, elements, putelement) putproperty = putargument def putelement(f, elem): [code, parts] = elem putostype(f, code) putlist(f, parts, putostype) def putcomparison(f, comp): [name, id, comment] = comp putpstr(f, name) putostype(f, id) putpstr(f, comment) def putenumeration(f, enum): [code, items] = enum putostype(f, code) putlist(f, items, putenumerator) def putenumerator(f, item): [name, code, desc] = item putpstr(f, name) putostype(f, code) putpstr(f, desc) def putdata(f, data): [type, description, flags] = data putostype(f, type) putpstr(f, description) putword(f, flags) def putlist(f, list, putitem): putword(f, len(list)) for item in list: putitem(f, item) putalign(f) def putalign(f): if f.tell() & 1: f.write('\0') def putbyte(f, value): f.write(chr(value)) def putword(f, value): putalign(f) f.write(chr((value>>8)&0xff)) f.write(chr(value&0xff)) def putostype(f, value): putalign(f) if type(value) != types.StringType or len(value) != 4: raise TypeError, "ostype must be 4-char string" f.write(value) def putpstr(f, value): if type(value) != types.StringType or len(value) > 255: raise TypeError, "pstr must be string <= 255 chars" f.write(chr(len(value)) + value) # Call the main program if __name__ == '__main__': main() else: realmain()
PopCap/GameIdea
Engine/Source/Runtime/Engine/Private/Components/PointLightComponent.cpp
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. /*============================================================================= PointLightComponent.cpp: PointLightComponent implementation. =============================================================================*/ #include "EnginePrivate.h" #include "PointLightSceneProxy.h" static int32 GAllowPointLightCubemapShadows = 1; static FAutoConsoleVariableRef CVarAllowPointLightCubemapShadows( TEXT("r.AllowPointLightCubemapShadows"), GAllowPointLightCubemapShadows, TEXT("When 0, will prevent point light cube map shadows from being used and the light will be unshadowed.") ); /** * The point light policy for TMeshLightingDrawingPolicy. */ class FPointLightPolicy { public: typedef TPointLightSceneProxy<FPointLightPolicy> SceneInfoType; }; void FPointLightSceneProxyBase::UpdateRadius_GameThread(UPointLightComponent* Component) { ENQUEUE_UNIQUE_RENDER_COMMAND_TWOPARAMETER( UpdateRadius, FPointLightSceneProxyBase*,LightSceneInfo,this, float,ComponentRadius,Component->AttenuationRadius, { LightSceneInfo->UpdateRadius(ComponentRadius); }); } class FPointLightSceneProxy : public TPointLightSceneProxy<FPointLightPolicy> { public: /** Accesses parameters needed for rendering the light. */ virtual void GetParameters(FVector4& LightPositionAndInvRadius, FVector4& LightColorAndFalloffExponent, FVector& NormalizedLightDirection, FVector2D& SpotAngles, float& LightSourceRadius, float& LightSourceLength, float& LightMinRoughness) const { LightPositionAndInvRadius = FVector4( GetOrigin(), InvRadius); LightColorAndFalloffExponent = FVector4( GetColor().R, GetColor().G, GetColor().B, FalloffExponent); NormalizedLightDirection = -GetDirection(); SpotAngles = FVector2D( -2.0f, 1.0f ); LightSourceRadius = SourceRadius; LightSourceLength = SourceLength; LightMinRoughness = MinRoughness; } virtual FSphere GetBoundingSphere() const { return FSphere(GetPosition(), GetRadius()); } /** * Sets up a projected shadow initializer for shadows from the entire scene. * @return True if the whole-scene projected shadow should be used. */ virtual bool GetWholeSceneProjectedShadowInitializer(const FSceneViewFamily& ViewFamily, TArray<FWholeSceneProjectedShadowInitializer, TInlineAllocator<6> >& OutInitializers) const { if (ViewFamily.GetFeatureLevel() >= ERHIFeatureLevel::SM4 && GAllowPointLightCubemapShadows != 0) { FWholeSceneProjectedShadowInitializer& OutInitializer = *new(OutInitializers) FWholeSceneProjectedShadowInitializer; OutInitializer.PreShadowTranslation = -GetLightToWorld().GetOrigin(); OutInitializer.WorldToLight = GetWorldToLight().RemoveTranslation(); OutInitializer.Scales = FVector(1, 1, 1); OutInitializer.FaceDirection = FVector(0,0,1); OutInitializer.SubjectBounds = FBoxSphereBounds(FVector(0, 0, 0),FVector(Radius,Radius,Radius),Radius); OutInitializer.WAxis = FVector4(0,0,1,0); OutInitializer.MinLightW = 0.1f; OutInitializer.MaxDistanceToCastInLightW = Radius; OutInitializer.CascadeSettings.bOnePassPointLightShadow = true; OutInitializer.CascadeSettings.bRayTracedDistanceField = UseRayTracedDistanceFieldShadows() && DoesPlatformSupportDistanceFieldShadowing(ViewFamily.GetShaderPlatform()); return true; } return false; } FPointLightSceneProxy(const UPointLightComponent* Component) : TPointLightSceneProxy<FPointLightPolicy>(Component) {} }; UPointLightComponent::UPointLightComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { #if WITH_EDITORONLY_DATA if (!IsRunningCommandlet()) { static ConstructorHelpers::FObjectFinder<UTexture2D> StaticTexture(TEXT("/Engine/EditorResources/LightIcons/S_LightPoint")); static ConstructorHelpers::FObjectFinder<UTexture2D> DynamicTexture(TEXT("/Engine/EditorResources/LightIcons/S_LightPointMove")); StaticEditorTexture = StaticTexture.Object; StaticEditorTextureScale = 0.5f; DynamicEditorTexture = DynamicTexture.Object; DynamicEditorTextureScale = 0.5f; } #endif Intensity = 5000; Radius_DEPRECATED = 1024.0f; AttenuationRadius = 1000; LightFalloffExponent = 8.0f; SourceRadius = 0.0f; SourceLength = 0.0f; bUseInverseSquaredFalloff = true; } FLightSceneProxy* UPointLightComponent::CreateSceneProxy() const { return new FPointLightSceneProxy(this); } void UPointLightComponent::SetAttenuationRadius(float NewRadius) { // Only movable lights can change their radius at runtime if (AreDynamicDataChangesAllowed(false) && NewRadius != AttenuationRadius) { AttenuationRadius = NewRadius; PushRadiusToRenderThread(); } } void UPointLightComponent::SetLightFalloffExponent(float NewLightFalloffExponent) { if (AreDynamicDataChangesAllowed() && NewLightFalloffExponent != LightFalloffExponent) { LightFalloffExponent = NewLightFalloffExponent; MarkRenderStateDirty(); } } void UPointLightComponent::SetSourceRadius(float NewValue) { if (AreDynamicDataChangesAllowed() && SourceRadius != NewValue) { SourceRadius = NewValue; MarkRenderStateDirty(); } } void UPointLightComponent::SetSourceLength(float NewValue) { if (AreDynamicDataChangesAllowed() && SourceLength != NewValue) { SourceLength = NewValue; MarkRenderStateDirty(); } } bool UPointLightComponent::AffectsBounds(const FBoxSphereBounds& Bounds) const { if((Bounds.Origin - ComponentToWorld.GetLocation()).SizeSquared() > FMath::Square(AttenuationRadius + Bounds.SphereRadius)) { return false; } if(!Super::AffectsBounds(Bounds)) { return false; } return true; } void UPointLightComponent::SendRenderTransform_Concurrent() { // Update the scene info's cached radius-dependent data. if(SceneProxy) { ((FPointLightSceneProxyBase*)SceneProxy)->UpdateRadius_GameThread(this); } Super::SendRenderTransform_Concurrent(); } // FVector4 UPointLightComponent::GetLightPosition() const { return FVector4(ComponentToWorld.GetLocation(),1); } /** * @return ELightComponentType for the light component class */ ELightComponentType UPointLightComponent::GetLightType() const { return LightType_Point; } float UPointLightComponent::GetUniformPenumbraSize() const { if (LightmassSettings.bUseAreaShadowsForStationaryLight) { // Interpret distance as shadow factor directly return 1.0f; } else { // Heuristic to derive uniform penumbra size from light source radius return FMath::Clamp(SourceRadius == 0 ? .05f : SourceRadius * .005f, .0001f, 1.0f); } } // FBox UPointLightComponent::GetBoundingBox() const { return FBox(GetComponentLocation() - FVector(AttenuationRadius,AttenuationRadius,AttenuationRadius),GetComponentLocation() + FVector(AttenuationRadius,AttenuationRadius,AttenuationRadius)); } FSphere UPointLightComponent::GetBoundingSphere() const { return FSphere(ComponentToWorld.GetLocation(), AttenuationRadius); } void UPointLightComponent::Serialize(FArchive& Ar) { Super::Serialize(Ar); if (Ar.UE4Ver() < VER_UE4_INVERSE_SQUARED_LIGHTS_DEFAULT) { bUseInverseSquaredFalloff = InverseSquaredFalloff_DEPRECATED; AttenuationRadius = Radius_DEPRECATED; } } void UPointLightComponent::PostLoad() { Super::PostLoad(); if (GetLinkerUE4Version() < VER_UE4_POINT_LIGHT_SOURCE_RADIUS) { SourceRadius = SourceRadius_DEPRECATED; } } #if WITH_EDITOR bool UPointLightComponent::CanEditChange(const UProperty* InProperty) const { if (InProperty) { FString PropertyName = InProperty->GetName(); if (PropertyName == GET_MEMBER_NAME_STRING_CHECKED(ULightComponent, bCastShadowsFromCinematicObjectsOnly) && bUseRayTracedDistanceFieldShadows) { return false; } if (FCString::Strcmp(*PropertyName, TEXT("LightFalloffExponent")) == 0) { return !bUseInverseSquaredFalloff; } } return Super::CanEditChange(InProperty); } /** * Called after property has changed via e.g. property window or set command. * * @param PropertyThatChanged UProperty that has been changed, NULL if unknown */ void UPointLightComponent::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) { // Make sure exponent is > 0. LightFalloffExponent = FMath::Max( (float) KINDA_SMALL_NUMBER, LightFalloffExponent ); SourceRadius = FMath::Max(0.0f, SourceRadius); SourceLength = FMath::Max(0.0f, SourceLength); Intensity = FMath::Max(0.0f, Intensity); LightmassSettings.IndirectLightingSaturation = FMath::Max(LightmassSettings.IndirectLightingSaturation, 0.0f); LightmassSettings.ShadowExponent = FMath::Clamp(LightmassSettings.ShadowExponent, .5f, 8.0f); Super::PostEditChangeProperty(PropertyChangedEvent); } #endif // WITH_EDITOR void UPointLightComponent::PostInterpChange(UProperty* PropertyThatChanged) { static FName RadiusName(TEXT("Radius")); static FName AttenuationRadiusName(TEXT("AttenuationRadius")); static FName LightFalloffExponentName(TEXT("LightFalloffExponent")); FName PropertyName = PropertyThatChanged->GetFName(); if (PropertyName == RadiusName || PropertyName == AttenuationRadiusName) { // Old radius tracks will animate the deprecated value if (PropertyName == RadiusName) { AttenuationRadius = Radius_DEPRECATED; } PushRadiusToRenderThread(); } else if (PropertyName == LightFalloffExponentName) { MarkRenderStateDirty(); } else { Super::PostInterpChange(PropertyThatChanged); } } void UPointLightComponent::PushRadiusToRenderThread() { if (CastShadows) { // Shadow casting lights need to recompute light interactions // to determine which primitives to draw in shadow depth passes. MarkRenderStateDirty(); } else { if (SceneProxy) { ((FPointLightSceneProxyBase*)SceneProxy)->UpdateRadius_GameThread(this); } } }
teozfrank/DuelMe
Plugin/src/main/java/com/github/teozfrank/duelme/util/Util.java
package com.github.teozfrank.duelme.util; /** The MIT License (MIT) Copyright (c) 2014 teozfrank 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. */ import com.github.teozfrank.duelme.main.DuelMe; import com.google.common.collect.Lists; import org.bukkit.*; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.material.Wool; import java.util.*; public class Util { /** * duelme plugin */ private DuelMe plugin; /** * random class */ Random rand; public static String UNKNOWN_CMD = ChatColor.RED + "Unknown Command!"; public static String NO_PERMS = ChatColor.RED + "You do not have permission!"; public static String NO_ARENAS = ChatColor.RED + "There are no arenas to start the duel! Please notify a member of staff!"; public static final String LINE_BREAK = ChatColor.LIGHT_PURPLE + "-----------------------------------------------------"; public Util(DuelMe plugin) { this.plugin = plugin; this.rand = new Random(); } /** * Method to broadcast a plugin message to all online players * @param message message to send to all players */ public static void broadcastMessage(String message) { for (Player p : Util.getOnlinePlayers()) { Util.sendEmptyMsg(p,DuelMe.getPrefix() + " " + message); } } public static List<Player> getOnlinePlayers() { List<Player> list = Lists.newArrayList(); for (World world : Bukkit.getWorlds()) { list.addAll(world.getPlayers()); } return Collections.unmodifiableList(list); } /** * sends a message to the recipient with the plugin prefix * @param sender the recipient to send the message to * @param message the message to send the sender */ public static void sendMsg(CommandSender sender, String message) { if (sender == null) { return; } Player p = null; if (sender instanceof Player) { p = (Player) sender; } if (p == null) { Bukkit.getLogger().info(DuelMe.getPrefix() + " " + ChatColor.stripColor(message)); } else { p.sendMessage(DuelMe.getPrefix() + " " + message); } } /** * sends plugin credits to sender of command * @param sender the command sender */ public static void sendCredits(CommandSender sender){ sendEmptyMsg(sender,ChatColor.GOLD + " V"+DuelMe.getVersion()); } /** * send a plugin message to a player * @param player the player to send the message to * @param message the message to send the player */ public static void sendMsg(Player player, String message){ player.sendMessage(DuelMe.getPrefix() + " " + message); } /** * send a plugin message to a player * @param playerUUID the uuid of the player * @param message the message to send the player */ public static void sendMsg(UUID playerUUID, String message) { Player player = Bukkit.getPlayer(playerUUID); if(player != null) { sendMsg(player, message); } } /** * send the same message to two players * @param sender the duel sender * @param target the duel acceptor * @param message the message to send to the two players */ public static void sendMsg(Player sender, Player target, String message){ sender.sendMessage(DuelMe.getPrefix() + " " + message); target.sendMessage(DuelMe.getPrefix() + " " + message); } /** * sends a empty message to the recipient with the plugin prefix * @param sender the recipient to send the message to * @param message the message to send the sender */ public static void sendEmptyMsg(CommandSender sender, String message) { if (sender == null) { return; } Player p = null; if (sender instanceof Player) { p = (Player) sender; } if (p == null) { Bukkit.getLogger().info(ChatColor.stripColor(message)); } else { p.sendMessage(message); } } /** * check to see if a given location with within a given region * @param playerLoc player or entity location * @param loc1 position 1 of the region * @param loc2 position 2 of the region * @return return true if the location is within the region, false if not */ public static boolean isInRegion(Location playerLoc, Location loc1, Location loc2) { double[] dim = new double[2]; dim[0] = loc1.getX(); dim[1] = loc2.getX(); Arrays.sort(dim); if(playerLoc.getX() > dim[1] || playerLoc.getX() < dim[0]){ return false; } dim[0] = loc1.getZ(); dim[1] = loc2.getZ(); Arrays.sort(dim); if(playerLoc.getZ() > dim[1] || playerLoc.getZ() < dim[0]){ return false; } return true; } /** * set the time for countdown by setting the players level * @param player the player to set the level (time) to * @param time the time in seconds */ public static void setTime(Player player, int time) { player.setLevel(time); } /** * create menu item with a certain wool color * @param color the color of the wool * @param name the name of the item * @param lore the lore of the item * @return the item stack */ public static ItemStack createMenuItem(DyeColor color, String name,String lore){ ItemStack wool = new Wool(color).toItemStack(1); ItemMeta woolIm = wool.getItemMeta(); woolIm.setDisplayName(name); woolIm.setLore(Arrays.asList(lore)); wool.setItemMeta(woolIm); return wool; } /** * create menu item with a certain wool color * @param color the color of the wool * @param name the name of the item * @param lore the lore of the item * @return the item stack */ public static ItemStack createMenuItem(DyeColor color, String name,List<String> lore){ ItemStack wool = new Wool(color).toItemStack(1); ItemMeta woolIm = wool.getItemMeta(); woolIm.setDisplayName(name); woolIm.setLore(lore); wool.setItemMeta(woolIm); return wool; } /** * send a action bar message to a player * @param player the player to send the message to * @param message the message to send the player */ /*public static void sendActionBarMessage(Player player, String message) { IChatBaseComponent icbc = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + message + "\"}"); PacketPlayOutChat bar = new PacketPlayOutChat(icbc, (byte)2); ((CraftPlayer) player).getHandle().playerConnection.sendPacket(bar); }*/ /** * Check to see if a teleport is truly successful * by checking if the player has reached the destination * @param player the player * @param location the location the player is being teleported to * @return true if successful false if not */ public static boolean isTeleportSuccessful(Player player, Location location) { Location playerLocation = player.getLocation(); int playerLocX = playerLocation.getBlockX(); int playerLocZ = playerLocation.getBlockZ(); int teleportLocX = location.getBlockX(); int teleportLocZ = location.getBlockZ(); if(playerLocX == teleportLocX && playerLocZ == teleportLocZ) { return true; } return false; } }
im-ando/javafx-breakout
src/jp/imagemagic/breakout/View.java
package jp.imagemagic.breakout; import java.util.List; final record View(List<Drawable> objects) { }
thlws/payment-thl
src/main/java/org/thlws/payment/wechat/entity/response/mp/MpSendDataResponse.java
<filename>src/main/java/org/thlws/payment/wechat/entity/response/mp/MpSendDataResponse.java<gh_stars>10-100 package org.thlws.payment.wechat.entity.response.mp; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.thlws.utils.JsonUtil; /** * * @author HanleyTang *2016/11/18 */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class MpSendDataResponse { //{"errcode":0,"errmsg":"ok","msgid":414569352} private long errcode; private String errmsg; private String msgid; private String desc; @Override public String toString() { return JsonUtil.format(this); } public boolean isSuccess(){ return errcode == 0 ? true : false; } }
RikusW/avdecc-lib
controller/lib/include/stream_input_descriptor_response.h
/* * Licensed under the MIT License (MIT) * * Copyright (c) 2014 AudioScience Inc. * * 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. */ /** * stream_input_descriptor_response.h * * Public STREAM INPUT descriptor interface * The STREAM INPUT descriptor describes a sourced or sinked stream. */ #pragma once #include <stdint.h> #include "avdecc-lib_build.h" #include "descriptor_response_base.h" namespace avdecc_lib { class stream_input_descriptor_response : public virtual descriptor_response_base { public: virtual ~stream_input_descriptor_response(){}; /// /// \return The localized string reference pointing to the localized descriptor name. /// AVDECC_CONTROLLER_LIB32_API virtual uint16_t STDCALL localized_description() = 0; /// /// \return The descriptor index of the CLOCK DOMAIN descriptor providing the media clock for the stream. /// AVDECC_CONTROLLER_LIB32_API virtual uint16_t STDCALL clock_domain_index() = 0; /// /// \return The flags describing the capabilities or features of the stream. /// AVDECC_CONTROLLER_LIB32_API virtual uint16_t STDCALL stream_flags() = 0; /// /// \return True if the stream can be used as a clock synchronization source. /// AVDECC_CONTROLLER_LIB32_API virtual bool STDCALL stream_flags_clock_sync_source() = 0; /// /// \return True if the stream supports streaming at Class A. /// AVDECC_CONTROLLER_LIB32_API virtual bool STDCALL stream_flags_class_a() = 0; /// /// \return True if the stream supports streaming at Class B. /// AVDECC_CONTROLLER_LIB32_API virtual bool STDCALL stream_flags_class_b() = 0; /// /// \return True if the stream supports streaming with encrypted PDUs. /// AVDECC_CONTROLLER_LIB32_API virtual bool STDCALL stream_flags_supports_encrypted() = 0; /// /// \return True if the primary backup AVDECC Talker's Entity ID and primary backup AVDECC Talker's Unique ID are supported. /// AVDECC_CONTROLLER_LIB32_API virtual bool STDCALL stream_flags_primary_backup_supported() = 0; /// /// \return True if the primary backup AVDECC Talker's Entity ID and primary backup AVDECC Talker's Unique ID are valid. /// AVDECC_CONTROLLER_LIB32_API virtual bool STDCALL stream_flags_primary_backup_valid() = 0; /// /// \return True if the secondary backup AVDECC Talker's Entity ID and secondary backup AVDECC Talker's Unique ID are supported. /// AVDECC_CONTROLLER_LIB32_API virtual bool STDCALL stream_flags_secondary_backup_supported() = 0; /// /// \return True if the secondary backup AVDECC Talker's Entity ID and secondary backup AVDECC Talker's Unique ID are valid. /// AVDECC_CONTROLLER_LIB32_API virtual bool STDCALL stream_flags_secondary_backup_valid() = 0; /// /// \return True if the tertiary backup AVDECC Talker's Entity ID and tertiary backup AVDECC Talker's Unique ID are supported. /// AVDECC_CONTROLLER_LIB32_API virtual bool STDCALL stream_flags_tertiary_backup_supported() = 0; /// /// \return True if the tertiary backup AVDECC Talker's Entity ID and tertiary backup AVDECC Talker's Unique ID are valid. /// AVDECC_CONTROLLER_LIB32_API virtual bool STDCALL stream_flags_tertiary_backup_valid() = 0; /// /// \return The current format name of the stream. /// AVDECC_CONTROLLER_LIB32_API virtual const char * STDCALL current_format_name() = 0; /// /// \return The current format value of the stream. /// AVDECC_CONTROLLER_LIB32_API virtual uint64_t STDCALL current_format_value() = 0; /// /// \return The number of formats supported by this audio stream. The maximum value /// for this field is 47 for this version of AEM. /// AVDECC_CONTROLLER_LIB32_API virtual uint16_t STDCALL number_of_formats() = 0; /// /// \return The primary backup AVDECC Talker's Entity ID. /// AVDECC_CONTROLLER_LIB32_API virtual uint64_t STDCALL backup_talker_entity_id_0() = 0; /// /// \return The primary backup AVDECC Talker's Unique ID. /// AVDECC_CONTROLLER_LIB32_API virtual uint16_t STDCALL backup_talker_unique_0() = 0; /// /// \return The secondary backup AVDECC Talker's Entity ID. /// AVDECC_CONTROLLER_LIB32_API virtual uint64_t STDCALL backup_talker_entity_id_1() = 0; /// /// \return The secondary backup AVDECC Talker's Unique ID. /// AVDECC_CONTROLLER_LIB32_API virtual uint16_t STDCALL backup_talker_unique_1() = 0; /// /// \return The tertiary backup AVDECC Talker's Entity ID. /// AVDECC_CONTROLLER_LIB32_API virtual uint64_t STDCALL backup_talker_entity_id_2() = 0; /// /// \return The tertiary backup AVDECC Talker's Unique ID. /// AVDECC_CONTROLLER_LIB32_API virtual uint16_t STDCALL backup_talker_unique_2() = 0; /// /// \return The Entity ID of the AVDECC Talker that this stream is backing up. /// AVDECC_CONTROLLER_LIB32_API virtual uint64_t STDCALL backedup_talker_entity_id() = 0; /// /// \return The Unique ID of the AVDECC Talker that this stream is backing up. /// AVDECC_CONTROLLER_LIB32_API virtual uint16_t STDCALL backedup_talker_unique() = 0; /// /// \return The descriptor index of the AVB INTERFACE descriptor from which this stream /// is sourced or to which it is sinked. /// AVDECC_CONTROLLER_LIB32_API virtual uint16_t STDCALL avb_interface_index() = 0; /// /// \return The length in nanoseconds of the MAC's ingress buffer size. /// AVDECC_CONTROLLER_LIB32_API virtual uint32_t STDCALL buffer_length() = 0; /// /// \return The supported stream format by index. /// AVDECC_CONTROLLER_LIB32_API virtual uint64_t STDCALL get_supported_stream_fmt_by_index(size_t stream_fmt_index) = 0; }; }
SoftwareVerde/java-db
src/main/java/com/softwareverde/database/properties/MutableDatabaseProperties.java
<reponame>SoftwareVerde/java-db package com.softwareverde.database.properties; public class MutableDatabaseProperties implements DatabaseProperties { protected String _rootPassword; protected String _hostname; protected String _username; protected String _password; protected String _schema; protected Integer _port; public MutableDatabaseProperties() { } public MutableDatabaseProperties(final DatabaseProperties databaseProperties) { _rootPassword = databaseProperties.getRootPassword(); _hostname = databaseProperties.getHostname(); _username = databaseProperties.getUsername(); _password = databaseProperties.getPassword(); _schema = databaseProperties.getSchema(); _port = databaseProperties.getPort(); } @Override public String getRootPassword() { return _rootPassword; } @Override public String getHostname() { return _hostname; } @Override public String getUsername() { return _username; } @Override public String getPassword() { return _password; } @Override public String getSchema() { return _schema; } @Override public Integer getPort() { return _port; } @Override public DatabaseCredentials getRootCredentials() { return new DatabaseCredentials("root", _rootPassword); } @Override public DatabaseCredentials getCredentials() { return new DatabaseCredentials(_username, _password); } public void setRootPassword(final String rootPassword) { _rootPassword = <PASSWORD>; } public void setHostname(final String hostname) { _hostname = hostname; } public void setUsername(final String username) { _username = username; } public void setPassword(final String password) { _password = password; } public void setSchema(final String schema) { _schema = schema; } public void setPort(final Integer port) { _port = port; } }
SjoerdJakobs/OOFramework-java
lib/fxgraphics2d-1.5/src/com/orsoncharts/demo/StackedBarChart3D3.java
<reponame>SjoerdJakobs/OOFramework-java<gh_stars>0 /* =================== * Orson Charts - Demo * =================== * * Copyright (c) 2013-2016, Object Refinery Limited. * All rights reserved. * * http://www.object-refinery.com/orsoncharts/index.html * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the Object Refinery Limited 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 OBJECT REFINERY LIMITED 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. * * Note that the above terms apply to the demo source only, and not the * Orson Charts library. * */ package com.orsoncharts.demo; import com.orsoncharts.Chart3D; import com.orsoncharts.Chart3DFactory; import com.orsoncharts.Colors; import com.orsoncharts.axis.LabelOrientation; import com.orsoncharts.axis.StandardCategoryAxis3D; import com.orsoncharts.data.category.CategoryDataset3D; import com.orsoncharts.data.category.StandardCategoryDataset3D; import com.orsoncharts.label.StandardCategoryItemLabelGenerator; import com.orsoncharts.label.StandardCategoryLabelGenerator; import com.orsoncharts.plot.CategoryPlot3D; import com.orsoncharts.renderer.category.StackedBarRenderer3D; import com.orsoncharts.table.RectanglePainter; import com.orsoncharts.table.StandardRectanglePainter; import com.orsoncharts.util.Fit2D; import java.awt.Color; import java.net.URL; import javax.swing.ImageIcon; /** * 3D stacked bar chart configuration for demo applications. */ public class StackedBarChart3D3 { /** * Creates a stacked bar chart based on the supplied dataset. * * @param dataset the dataset. * * @return A stacked bar chart. */ public static Chart3D createChart(CategoryDataset3D dataset) { Chart3D chart = Chart3DFactory.createStackedBarChart( "The Sinking of the Titanic", "Survival data for 2,201 passengers", dataset, null, "Class", "Passengers"); URL imageURL = StackedBarChart3D3.class.getResource( "iStock_000003105870Small.jpg"); ImageIcon icon = new ImageIcon(imageURL); RectanglePainter background = new StandardRectanglePainter(Color.WHITE, icon.getImage(), Fit2D.SCALE_TO_FIT_TARGET); chart.setBackground(background); chart.setChartBoxColor(new Color(255, 255, 255, 155)); CategoryPlot3D plot = (CategoryPlot3D) chart.getPlot(); plot.setLegendLabelGenerator(new StandardCategoryLabelGenerator( StandardCategoryLabelGenerator.TOTAL_TEMPLATE)); plot.setToolTipGenerator(new StandardCategoryItemLabelGenerator( "%s, %s, %s = %4$.0f")); StandardCategoryAxis3D rowAxis = (StandardCategoryAxis3D) plot.getRowAxis(); rowAxis.setTickLabelGenerator(new StandardCategoryLabelGenerator( StandardCategoryLabelGenerator.TOTAL_TEMPLATE)); StandardCategoryAxis3D columnAxis = (StandardCategoryAxis3D) plot.getColumnAxis(); columnAxis.setTickLabelGenerator(new StandardCategoryLabelGenerator( StandardCategoryLabelGenerator.TOTAL_TEMPLATE)); columnAxis.setTickLabelOrientation(LabelOrientation.PARALLEL); columnAxis.setMaxTickLabelLevels(2); StackedBarRenderer3D renderer = (StackedBarRenderer3D) plot.getRenderer(); renderer.setColors(Colors.createIceCubeColors()); return chart; } /** * Creates a sample dataset (hard-coded for the purpose of keeping the * demo self-contained - in practice you would normally read your data * from a file, database or other source). * * @return A sample dataset. */ public static CategoryDataset3D createDataset() { StandardCategoryDataset3D dataset = new StandardCategoryDataset3D(); dataset.addValue(146, "Survivors", "Women/Children", "1st"); dataset.addValue(104, "Survivors", "Women/Children", "2nd"); dataset.addValue(103, "Survivors", "Women/Children", "3rd"); dataset.addValue(20, "Survivors", "Women/Children", "Crew"); dataset.addValue(57, "Survivors", "Men", "1st"); dataset.addValue(14, "Survivors", "Men", "2nd"); dataset.addValue(75, "Survivors", "Men", "3rd"); dataset.addValue(192, "Survivors", "Men", "Crew"); dataset.addValue(4, "Victims", "Women/Children", "1st"); dataset.addValue(13, "Victims", "Women/Children", "2nd"); dataset.addValue(141, "Victims", "Women/Children", "3rd"); dataset.addValue(3, "Victims", "Women/Children", "Crew"); dataset.addValue(118, "Victims", "Men", "1st"); dataset.addValue(154, "Victims", "Men", "2nd"); dataset.addValue(387, "Victims", "Men", "3rd"); dataset.addValue(670, "Victims", "Men", "Crew"); return dataset; } }
psamatt/OrderFulfilmentCQRSDemo
src/main/java/co/uk/acme/fulfillment/DeliveryDateNotChosenForDispatch.java
package co.uk.acme.fulfillment; /** * @author psamatt */ final public class DeliveryDateNotChosenForDispatch extends RuntimeException { public DeliveryDateNotChosenForDispatch() { super("Delivery Date not chosen for order to be dispatched"); } }
gift-surg/GiftCloudServerBuilder
plugin-resources/webapp/xnat/scripts/prearchive/PrearchiveDetails_delete.js
<reponame>gift-surg/GiftCloudServerBuilder<filename>plugin-resources/webapp/xnat/scripts/prearchive/PrearchiveDetails_delete.js /* * D:/Development/XNAT/1.6/xnat_builder_1_6dev/plugin-resources/webapp/xnat/scripts/prearchive/PrearchiveDetails_delete.js * XNAT http://www.xnat.org * Copyright (c) 2014, Washington University School of Medicine * All Rights Reserved * * Released under the Simplified BSD. * * Last modified 1/6/14 3:48 PM */ XNAT.app.scanDeleter={ requestDelete:function(scan_id){ this.lastScan=scan_id; xModalConfirm({ content: "Are you sure you want to delete scan "+scan_id+ "?", okAction: function(){ XNAT.app.scanDeleter.doDelete(); }, cancelAction: function(){ } }); }, doDelete:function(){ this.delCallback={ success:this.handleSuccess, failure:this.handleFailure, cache:false, // Turn off caching for IE scope:this }; if(this.lastScan!=undefined && this.lastScan!=null){ openModalPanel("delete_scan","Deleting scan " + this.lastScan); this.tempURL=serverRoot+"/REST" + this.url +"/scans/" + this.lastScan; YAHOO.util.Connect.asyncRequest('DELETE',this.tempURL+"?XNAT_CSRF=" + csrfToken,this.delCallback,null,this); } }, handleSuccess:function(o){ closeModalPanel("delete_scan"); $('#scanTR'+this.lastScan).remove(); XNAT.app.validator.validate(); XNAT.app.prearchiveActions.loadLogs(); }, handleFailure:function(o){ closeModalPanel("delete_scan"); showMessage("page_body", "Error", "Failed to delete scan. ("+ e.message + ")"); } };
guimeixen/Engine
Editor/imgui/imconfig.cpp
<gh_stars>0 #include "imconfig.h" #include "imgui_internal.h" bool ImGui::Combo(const char *label, int *currIndex, std::vector<std::string> &values) { if (values.empty()) return false; return Combo(label, currIndex, vector_getter, static_cast<void*>(&values), values.size()); } bool ImGui::ListBox(const char *label, int *currIndex, std::vector<std::string> &values) { if (values.empty()) return false; return ListBox(label, currIndex, vector_getter, static_cast<void*>(&values), values.size()); }
Jiaming-Yang-20/-CSC207-Book-Exchange-System
src/client/guiandpresenter/userscreen/usertrade/usertrademenuscreen/UserTradeMenuPresenter.java
<gh_stars>0 package client.guiandpresenter.userscreen.usertrade.usertrademenuscreen; import client.guiandpresenter.SystemPresenter; import java.util.List; /** * Presenter for the User Trade Menu. */ class UserTradeMenuPresenter extends SystemPresenter { /** * @param items a list of items * @return the three recent trade item of a user */ String getThreeRecentTradeItemMsg(List<String> items) { if (items.isEmpty()) return "You haven't had a trade yet. "; StringBuilder sb = new StringBuilder("<html>There are some of your most recent traded items(at most 3):<br>"); for (String str : items) { sb.append("<br>").append(str).append("<br>"); } return sb.toString(); } String cannotRequestTradeMsg() { return "<html> You cannot request trade " + "because <br> your account's on-vacation status is: on"; } /** * @param users a list of users * @return the top three trade partner of a user */ String getTopThreeTradePartnerMsg(List<String> users) { if (users.isEmpty()) return "You haven't had a trade yet. "; StringBuilder sb = new StringBuilder("<html>There are some of your most recent traded partners(at most 3):"); for (String str : users) { sb.append("<br>[").append(str).append("]<br>"); } return sb.toString(); } /** * @param thresholds an arraylist of threshold values * @return a string representation of threshold categories and their values */ String getTradeThresholds(int[] thresholds) { return "<html> The trade thresholds are: " + "<br>" + "Max incomplete trade count: " + thresholds[0] + "<br>" + "Min Lend borrow difference: " + thresholds[1] + "<br>" + "Max weekly transaction count: " + thresholds[2]; } /** * Get the title of this presenter. * * @return the title of this presenter. */ @Override public String getTitle() { return "User Trade Menu"; } /** * @return string indicating "View your trades" button */ String viewTradeBtn() { return "View Your Trades"; } /** * @return string indicating "Request a new trade" button */ String requestTradeBtn() { return "Request New Trade"; } /** * @return string indicating <code>threeRecentTradePartnersBtn</code> button */ String threeRecentTradePartnersBtn() { return "<html> Three Most Recent <br> Trading Partners"; } /** * @return string indicating <code>threeRecentTradeItemsBtn</code> button */ String threeRecentTradeItemsBtn() { return "<html> Three Most Recent <br> Traded Items"; } /** * @return string indicating <code>tradeThresholdsBtn</code> button */ String tradeThresholdsBtn() { return "<html> View Trade Threshold <br> Values"; } }
OrBin/redalert-android
app/src/main/java/com/red/alert/services/sound/StopSoundService.java
package com.red.alert.services.sound; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; public class StopSoundService extends Service { public static void stopSoundService(final Context context) { // Bind to the sound service context.bindService(new Intent(context, PlaySoundService.class), new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder binder) { // Convert binder to LocalBinder PlaySoundService.LocalBinder localBinder = (PlaySoundService.LocalBinder) binder; // Get service instance PlaySoundService service = localBinder.getService(); // Stop sound service.resetMediaPlayer(); // Unbind fom service context.unbindService(this); } @Override public void onServiceDisconnected(ComponentName componentName) { // Do nothing } }, context.BIND_AUTO_CREATE); } @Override public int onStartCommand(Intent Intent, int Flags, int StartId) { // Stop currently playing sounds stopSoundService(this); // Don't restart this service return START_NOT_STICKY; } @Override public IBinder onBind(Intent arg0) { // Provide service binder return null; } }
petrandreev/nosql-unit
nosqlunit-couchbase/src/main/java/com/lordofthejars/nosqlunit/couchbase/RemoteCouchbaseConfigurationBuilder.java
<filename>nosqlunit-couchbase/src/main/java/com/lordofthejars/nosqlunit/couchbase/RemoteCouchbaseConfigurationBuilder.java<gh_stars>100-1000 package com.lordofthejars.nosqlunit.couchbase; import java.net.URI; import java.util.ArrayList; import java.util.List; public class RemoteCouchbaseConfigurationBuilder { public static class Builder { private String name; private String password = ""; private String clusterUsername; private String clusterPassword; private List<URI> uris; private boolean createBucket = false; private Builder() { uris = new ArrayList<URI>(); } public static Builder start() { return new Builder(); } public Builder bucketName(final String name) { this.name = name; return this; } public Builder bucketPassword(final String pass) { password = pass; return this; } public Builder serverHost(final String url) { uris.add(URI.create(url)); return this; } public Builder createBucket(boolean createBucket) { this.createBucket = createBucket; return this; } public Builder clusterAuth(String clusterUsername, String clusterPassword) { this.clusterUsername = clusterUsername; this.clusterPassword = clusterPassword; return this; } public CouchbaseConfiguration build() { if (uris.isEmpty()) { uris.add(URI.create("localhost")); } final CouchbaseConfiguration couchbaseConfiguration = new CouchbaseConfiguration(uris, password, name, createBucket ); couchbaseConfiguration.setClusterUsername(clusterUsername); couchbaseConfiguration.setClusterPassword(clusterPassword); return couchbaseConfiguration; } } }
18600130137/leetcode
LeetCodeCPP/50. Pow(x, n)/main.cpp
// // main.cpp // 50. Pow(x, n) // // Created by admin on 2019/3/20. // Copyright © 2019年 liu. All rights reserved. // #include <iostream> using namespace std; class Solution { public: double myPow(double x, int n) { if(n==0){ return 1; } double tmp=myPow(x,n/2); if(n%2==0){ return tmp*tmp; }else if(n>0){ return tmp*tmp*x; }else{ return tmp*tmp/x; } } }; int main(int argc, const char * argv[]) { Solution so=Solution(); double ret=so.myPow(2, 10); cout<<"The ret is:"<<ret<<endl; return 0; }
nielshulstaert/pride-asa-pipeline
pride-asa-pipeline-core/src/main/java/com/compomics/pride_asa_pipeline/core/gui/view/ModificationConfigDialog.java
<reponame>nielshulstaert/pride-asa-pipeline package com.compomics.pride_asa_pipeline.core.gui.view; import java.awt.Color; import javax.swing.*; /** * The modification configuration dialog. * * @author <NAME> */ public class ModificationConfigDialog extends javax.swing.JDialog { private JFileChooser fileChooser; /** * Creates a new ModificationConfigDialog. * * @param parent * @param modal */ public ModificationConfigDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); this.getContentPane().setBackground(Color.WHITE); fileChooser = new JFileChooser(); modificationsTableScrollPane.getViewport().setOpaque(false); modifcationsTable.getTableHeader().setReorderingAllowed(false); modifcationsTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); setLocationRelativeTo(parent); } public JTable getModifcationsTable() { return modifcationsTable; } public JTextField getModAccessionTextField() { return modAccessionTextField; } public JComboBox getModLocationComboBox() { return modLocationComboBox; } public JTextField getModAverageMassShiftTextField() { return modAverageMassShiftTextField; } public JTextField getModMonoIsotopicMassShiftTextField() { return modMonoIsotopicMassShiftTextField; } public JTextField getModNameTextField() { return modNameTextField; } public JList getAffectedAminoAcidsList() { return affectedAminoAcidsList; } public JButton getAddAminoAcidButton() { return addAminoAcidButton; } public JList getAminoAcidsList() { return aminoAcidsList; } public JButton getRemoveAminoAcidButton() { return removeAminoAcidButton; } public JButton getAddModificationButton() { return addModificationButton; } public JButton getRemoveModificationButton() { return removeModificationButton; } public JLabel getBindingLoggingLabel() { return bindingLoggingLabel; } public JTextField getModAccessionValueTextField() { return modAccessionValueTextField; } public JButton getSaveButton() { return saveButton; } public JButton getImportButton() { return importButton; } public JFileChooser getFileChooser() { return fileChooser; } public JComboBox getModTypeComboBox() { return modTypeComboBox; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { modificationsTablePanel = new javax.swing.JPanel(); modificationsTableScrollPane = new javax.swing.JScrollPane(); modifcationsTable = new javax.swing.JTable(); saveButton = new javax.swing.JButton(); importButton = new javax.swing.JButton(); addModificationButton = new javax.swing.JButton(); removeModificationButton = new javax.swing.JButton(); editModificationPanel = new javax.swing.JPanel(); modNameLabel = new javax.swing.JLabel(); modNameTextField = new javax.swing.JTextField(); modAccessionLabel = new javax.swing.JLabel(); modAccessionTextField = new javax.swing.JTextField(); modMonoIsotopicMassShiftLabel = new javax.swing.JLabel(); modMonoIsotopicMassShiftTextField = new javax.swing.JTextField(); modLocationLabel = new javax.swing.JLabel(); modLocationComboBox = new javax.swing.JComboBox(); modAverageMassShiftLabel = new javax.swing.JLabel(); modAverageMassShiftTextField = new javax.swing.JTextField(); affectedAminoAcidsLabel = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); aminoAcidsList = new javax.swing.JList(); jScrollPane2 = new javax.swing.JScrollPane(); affectedAminoAcidsList = new javax.swing.JList(); addAminoAcidButton = new javax.swing.JButton(); removeAminoAcidButton = new javax.swing.JButton(); modAccessionValueLabel = new javax.swing.JLabel(); modAccessionValueTextField = new javax.swing.JTextField(); bindingLoggingLabel = new javax.swing.JLabel(); modTypeComboBox = new javax.swing.JComboBox(); modTypeLabel = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Modifications Configuration"); setMinimumSize(new java.awt.Dimension(500, 700)); modificationsTablePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Modifications")); modificationsTablePanel.setOpaque(false); modificationsTableScrollPane.setOpaque(false); modificationsTableScrollPane.setPreferredSize(new java.awt.Dimension(25, 25)); modifcationsTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); modifcationsTable.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); modifcationsTable.setOpaque(false); modificationsTableScrollPane.setViewportView(modifcationsTable); saveButton.setText("Save"); saveButton.setToolTipText("Click to save the modifications to the modifications file."); saveButton.setMaximumSize(new java.awt.Dimension(80, 25)); saveButton.setMinimumSize(new java.awt.Dimension(80, 25)); saveButton.setPreferredSize(new java.awt.Dimension(80, 25)); importButton.setText("Import"); importButton.setToolTipText("Click to import a modification file."); importButton.setMaximumSize(new java.awt.Dimension(80, 25)); importButton.setMinimumSize(new java.awt.Dimension(80, 25)); importButton.setPreferredSize(new java.awt.Dimension(80, 25)); addModificationButton.setText("Add"); addModificationButton.setToolTipText("Click to add a modification."); addModificationButton.setMaximumSize(new java.awt.Dimension(80, 25)); addModificationButton.setMinimumSize(new java.awt.Dimension(80, 25)); addModificationButton.setPreferredSize(new java.awt.Dimension(80, 25)); removeModificationButton.setText("Remove"); removeModificationButton.setToolTipText("Click to delete the selected modification"); removeModificationButton.setMaximumSize(new java.awt.Dimension(80, 25)); removeModificationButton.setMinimumSize(new java.awt.Dimension(80, 25)); removeModificationButton.setPreferredSize(new java.awt.Dimension(80, 25)); javax.swing.GroupLayout modificationsTablePanelLayout = new javax.swing.GroupLayout(modificationsTablePanel); modificationsTablePanel.setLayout(modificationsTablePanelLayout); modificationsTablePanelLayout.setHorizontalGroup( modificationsTablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, modificationsTablePanelLayout.createSequentialGroup() .addContainerGap() .addGroup(modificationsTablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(modificationsTableScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(modificationsTablePanelLayout.createSequentialGroup() .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(importButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(addModificationButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(removeModificationButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); modificationsTablePanelLayout.setVerticalGroup( modificationsTablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(modificationsTablePanelLayout.createSequentialGroup() .addContainerGap() .addComponent(modificationsTableScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(modificationsTablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(addModificationButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(removeModificationButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(importButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); editModificationPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Modification Details")); editModificationPanel.setMinimumSize(new java.awt.Dimension(100, 100)); editModificationPanel.setOpaque(false); editModificationPanel.setPreferredSize(new java.awt.Dimension(300, 300)); modNameLabel.setText("Name"); modNameTextField.setMinimumSize(new java.awt.Dimension(80, 20)); modNameTextField.setPreferredSize(new java.awt.Dimension(300, 30)); modAccessionLabel.setText("Accession"); modAccessionTextField.setMinimumSize(new java.awt.Dimension(80, 20)); modAccessionTextField.setPreferredSize(new java.awt.Dimension(300, 30)); modMonoIsotopicMassShiftLabel.setText("Monoisotopic Mass Shift"); modMonoIsotopicMassShiftTextField.setMinimumSize(new java.awt.Dimension(80, 20)); modMonoIsotopicMassShiftTextField.setPreferredSize(new java.awt.Dimension(300, 30)); modLocationLabel.setText("Location"); modLocationComboBox.setMinimumSize(new java.awt.Dimension(80, 20)); modLocationComboBox.setPreferredSize(new java.awt.Dimension(300, 30)); modAverageMassShiftLabel.setText("Average Mass Shift"); modAverageMassShiftTextField.setMinimumSize(new java.awt.Dimension(80, 20)); modAverageMassShiftTextField.setPreferredSize(new java.awt.Dimension(300, 30)); affectedAminoAcidsLabel.setText("Affected Amino Acids"); jScrollPane3.setMaximumSize(new java.awt.Dimension(0, 0)); jScrollPane3.setMinimumSize(new java.awt.Dimension(20, 20)); jScrollPane3.setPreferredSize(new java.awt.Dimension(20, 20)); jScrollPane3.setViewportView(aminoAcidsList); jScrollPane2.setMaximumSize(new java.awt.Dimension(0, 0)); jScrollPane2.setMinimumSize(new java.awt.Dimension(20, 20)); jScrollPane2.setPreferredSize(new java.awt.Dimension(20, 20)); jScrollPane2.setViewportView(affectedAminoAcidsList); addAminoAcidButton.setText(">>"); addAminoAcidButton.setMaximumSize(new java.awt.Dimension(80, 25)); addAminoAcidButton.setMinimumSize(new java.awt.Dimension(80, 25)); addAminoAcidButton.setPreferredSize(new java.awt.Dimension(80, 25)); removeAminoAcidButton.setText("<<"); removeAminoAcidButton.setMaximumSize(new java.awt.Dimension(80, 25)); removeAminoAcidButton.setMinimumSize(new java.awt.Dimension(80, 25)); removeAminoAcidButton.setPreferredSize(new java.awt.Dimension(80, 25)); modAccessionValueLabel.setText("Accession Value"); modAccessionValueTextField.setMinimumSize(new java.awt.Dimension(80, 20)); modAccessionValueTextField.setPreferredSize(new java.awt.Dimension(300, 30)); bindingLoggingLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N bindingLoggingLabel.setForeground(new java.awt.Color(255, 0, 0)); bindingLoggingLabel.setMinimumSize(new java.awt.Dimension(80, 25)); bindingLoggingLabel.setPreferredSize(new java.awt.Dimension(80, 25)); modTypeComboBox.setMinimumSize(new java.awt.Dimension(80, 20)); modTypeComboBox.setPreferredSize(new java.awt.Dimension(300, 30)); modTypeLabel.setText("Type"); javax.swing.GroupLayout editModificationPanelLayout = new javax.swing.GroupLayout(editModificationPanel); editModificationPanel.setLayout(editModificationPanelLayout); editModificationPanelLayout.setHorizontalGroup( editModificationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(editModificationPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(editModificationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(modAccessionLabel) .addComponent(modAccessionValueLabel) .addComponent(modAverageMassShiftLabel) .addComponent(modLocationLabel) .addComponent(affectedAminoAcidsLabel) .addComponent(modNameLabel) .addComponent(modMonoIsotopicMassShiftLabel) .addComponent(modTypeLabel)) .addGap(26, 26, 26) .addGroup(editModificationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, editModificationPanelLayout.createSequentialGroup() .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(editModificationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(addAminoAcidButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(removeAminoAcidButton, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(modAccessionTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 582, Short.MAX_VALUE) .addComponent(modNameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 582, Short.MAX_VALUE) .addComponent(bindingLoggingLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(editModificationPanelLayout.createSequentialGroup() .addGap(1, 1, 1) .addGroup(editModificationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(modTypeComboBox, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(modAccessionValueTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 581, Short.MAX_VALUE) .addComponent(modMonoIsotopicMassShiftTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 581, Short.MAX_VALUE) .addComponent(modAverageMassShiftTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 581, Short.MAX_VALUE) .addComponent(modLocationComboBox, 0, 581, Short.MAX_VALUE)))) .addContainerGap()) ); editModificationPanelLayout.setVerticalGroup( editModificationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(editModificationPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(bindingLoggingLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(editModificationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(modNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(modNameLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(editModificationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(modAccessionTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(modAccessionLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(editModificationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(modAccessionValueTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(modAccessionValueLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(editModificationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(modMonoIsotopicMassShiftTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(modMonoIsotopicMassShiftLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(editModificationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(modAverageMassShiftTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(modAverageMassShiftLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(editModificationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(modLocationLabel) .addComponent(modLocationComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(editModificationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(editModificationPanelLayout.createSequentialGroup() .addGap(77, 77, 77) .addComponent(addAminoAcidButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(removeAminoAcidButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(editModificationPanelLayout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(editModificationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(modTypeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(modTypeLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(editModificationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, editModificationPanelLayout.createSequentialGroup() .addComponent(affectedAminoAcidsLabel) .addGap(60, 60, 60)))))) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(modificationsTablePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(editModificationPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 754, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(modificationsTablePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(editModificationPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 440, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addAminoAcidButton; private javax.swing.JButton addModificationButton; private javax.swing.JLabel affectedAminoAcidsLabel; private javax.swing.JList affectedAminoAcidsList; private javax.swing.JList aminoAcidsList; private javax.swing.JLabel bindingLoggingLabel; private javax.swing.JPanel editModificationPanel; private javax.swing.JButton importButton; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JLabel modAccessionLabel; private javax.swing.JTextField modAccessionTextField; private javax.swing.JLabel modAccessionValueLabel; private javax.swing.JTextField modAccessionValueTextField; private javax.swing.JLabel modAverageMassShiftLabel; private javax.swing.JTextField modAverageMassShiftTextField; private javax.swing.JComboBox modLocationComboBox; private javax.swing.JLabel modLocationLabel; private javax.swing.JLabel modMonoIsotopicMassShiftLabel; private javax.swing.JTextField modMonoIsotopicMassShiftTextField; private javax.swing.JLabel modNameLabel; private javax.swing.JTextField modNameTextField; private javax.swing.JComboBox modTypeComboBox; private javax.swing.JLabel modTypeLabel; private javax.swing.JTable modifcationsTable; private javax.swing.JPanel modificationsTablePanel; private javax.swing.JScrollPane modificationsTableScrollPane; private javax.swing.JButton removeAminoAcidButton; private javax.swing.JButton removeModificationButton; private javax.swing.JButton saveButton; // End of variables declaration//GEN-END:variables }
addthis/basis
basis-core/src/main/java/com/addthis/basis/util/Dict.java
/* * 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.addthis.basis.util; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; /** * String-String map wrapper, useful for url and kv primitive applications * <p/> * TODO finish url class cutover * TODO multi-value params, put(key, val ...) method */ public class Dict { private Map<String, String> map; /** * create a new Dict backed by a LinkedHashMap */ public Dict() { map = new LinkedHashMap<>(); } /** * create a new Dict backed by the specified map * * @param map */ public Dict(Map<String, String> map) { assert (map != null); this.map = map; } /** * create a new Dict and read parameters from the given url query string * * @param query */ public Dict(String query) { map = DictUtil.parse(query); } /** * create a new Dict, initialized with the given key and value * * @param key * @param value */ public Dict(String key, String value) { this(); put(key, value); } public String put(String key, String value) { return map.put(key, value); } public String put(String key, int value) { return map.put(key, String.valueOf(value)); } public String put(String key, long value) { return map.put(key, String.valueOf(value)); } public String put(String key, double value) { return map.put(key, String.valueOf(value)); } public String put(String key, float value) { return map.put(key, String.valueOf(value)); } public String put(String key, boolean value) { return map.put(key, String.valueOf(value)); } public <T extends Enum<T>> String put(String key, T value) { return map.put(key, String.valueOf(value)); } public <T extends Enum<T>> String put(T value) { return value == null ? null : map.put(value.getClass().getSimpleName().toLowerCase(), String.valueOf(value)); } public boolean has(String key) { return map.containsKey(key); } public String get(String key) { return map.get(key); } public String get(String key, String dflt) { return has(key) ? map.get(key) : dflt; } public int getInt(String key, int dflt) { try { return has(key) ? Integer.parseInt(map.get(key)) : dflt; } catch (NumberFormatException e) { return dflt; } } public long getLong(String key, long dflt) { try { return has(key) ? Long.parseLong(map.get(key)) : dflt; } catch (NumberFormatException e) { return dflt; } } public float getFloat(String key, float dflt) { try { return has(key) ? Float.parseFloat(map.get(key)) : dflt; } catch (NumberFormatException e) { return dflt; } } public double getDouble(String key, double dflt) { try { return has(key) ? Double.parseDouble(map.get(key)) : dflt; } catch (NumberFormatException e) { return dflt; } } public boolean getBoolean(String key, boolean dflt) { try { return has(key) ? Boolean.parseBoolean(map.get(key)) : dflt; } catch (NumberFormatException e) { return dflt; } } /** * serialize to url query format key1=value1&key2=value2 */ public String toString() { return DictUtil.toString(map); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Dict)) { return false; } Dict that = (Dict) obj; return map.equals(that.map); } public int hashCode() { return map.hashCode(); } /** * @return number of keys stored in this dict */ public int size() { return map.size(); } /** * return the set of keys stored in this collection * * @return */ public Set<String> keySet() { return map.keySet(); } /** * Return this Multidict as a Dict. * * @return */ public Multidict asMultidict() { return DictUtil.asMultidict(this); } }
z-yin/Leetcode-learning
Leetcode/0001_to_0050/0028_implement_strStr()/cc/implement_strStr().cc
<gh_stars>1-10 #include <string> using namespace std; // 4 ms, 9.1 MB. Two pointers. class Solution { public: int strStr(string haystack, string needle) { int len_hay = haystack.size(); int len_nee = needle.size(); if (len_nee == 0) { return 0; } int i = 0; int end = len_hay - len_nee; while (i <= end) { if (haystack[i] == needle[0]) { int j = i + 1; while (j - i < len_nee && haystack[j] == needle[j - i]) { ++j; } if (j - i == len_nee) { return i; } } ++i; } return -1; } };
1432961067/LFKit
LFKit/LFKit/Component/LFBubbleView/LFBubbleView.h
// // LFBubbleView.h // LFBubbleViewDemo // // Created by 张林峰 on 16/6/29. // Copyright © 2016年 张林峰. All rights reserved. // #import <UIKit/UIKit.h> typedef NS_ENUM(NSInteger, LFTriangleDirection) { LFTriangleDirection_Down, LFTriangleDirection_Left, LFTriangleDirection_Right, LFTriangleDirection_Up }; /** 气泡提示框 */ @interface LFBubbleView : UIView @property (nonatomic, strong) UIColor *color;//背景色,默认红色半透明 @property (nonatomic, strong) UIColor *textColor;//字体颜色,默认白色 @property (nonatomic, strong) UIFont *font;//字体,默认12 @property (nonatomic, strong) UIColor *borderColor;//边框色,默认无 @property (nonatomic, assign) CGFloat borderWidth;//默认无 @property (nonatomic, assign) CGFloat cornerRadius;//圆角,默认5 @property (nonatomic, assign) CGFloat triangleH;//三角形高.默认7 @property (nonatomic, assign) CGFloat triangleW;//三角形底边长默认7 @property (nonatomic) UIEdgeInsets edgeInsets;//label四周边距,默认(5,5,5,5) @property (nonatomic, strong) UIView *contentView;//容器,可放自定义视图,默认装文字 @property (nonatomic, strong) UILabel *lbTitle;//提示文字 @property (nonatomic) LFTriangleDirection direction;//三角方向,默认朝下 @property (nonatomic, assign) CGFloat dismissAfterSecond;//hideAfterSecond秒后自动消失,不设置或0则不自动消失 @property (nonatomic, strong) NSString *showOnceKey;//如果设置了Key,该气泡只显示一次(比如某个新功能只需要提示用户一次) //优先使用triangleXY。如果triangleXY和triangleXYScale都不设置,则三角在中间 @property (nonatomic, assign) CGFloat triangleXY;//三角中心的x或y(三角朝上下代表x,三角朝左右代表y) @property (nonatomic, assign) CGFloat triangleXYScale;//三角的中心x或y位置占边长的比例,如0.5代表在中间 /** * 显示 * * @param point 三角顶端位置 */ - (void)showInPoint:(CGPoint)point; /**来回平移动画*/ - (void)doTranslationAnimate; /**弹跳动画*/ - (void)doSpringAnimate; @end
neilrjones/DevOps-Python-tools
impala_schemas_csv.py
#!/usr/bin/env python # vim:ts=4:sts=4:sw=4:et # # Author: <NAME> # Date: 2019-11-07 14:52:38 +0000 (Thu, 07 Nov 2019) # # https://github.com/harisekhon/devops-python-tools # # License: see accompanying Hari Sekhon LICENSE file # # If you're using my code you're welcome to connect with me on LinkedIn # and optionally send me feedback to help steer this or other code I publish # # https://www.linkedin.com/in/harisekhon # """ Connect to an Impala daemon and dump all the schemas, tables and columns out in CSV format to stdout In practice Hive is much more reliable than Impala for dumping masses of schema (see adjacent hive_schemas_csv.py) Impala appears faster initially but then slows down more than Hive and hits things query handle errors under sustained load of extracting large amounts of schema information There is also a risk that Impala's metadata may be out of date, so Hive is strongly preferred for this CSV format: database,table,column,type I recommend generating quoted csv because you may encounter Hive data types such as decimal(15,2) which would cause incorrect field splitting, you can disable by setting --quotechar='' to blank but if escaping is needed then you will be forced to specify an --escapechar otherwise the csv writer will raise a traceback to tell you to set one (eg. --escapechar='\\') Tested on Impala 2.7.0, 2.12.0 on CDH 5.10, 5.16 with Kerberos and SSL Due to a thrift / impyla bug this needs exactly thrift==0.9.3, see https://github.com/cloudera/impyla/issues/286 If you get an error like this: ERROR:impala.hiveserver2:Failed to open transport (tries_left=1) ... TTransportException: TSocket read 0 bytes then check your --kerberos and --ssl settings match the cluster's settings (Thrift and Kerberos have the worst error messages ever) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function #from __future__ import unicode_literals from hive_schemas_csv import HiveSchemasCSV __author__ = '<NAME>' __version__ = '0.5.0' class ImpalaSchemasCSV(HiveSchemasCSV): def __init__(self): # Python 2.x super(ImpalaSchemasCSV, self).__init__() # Python 3.x # super().__init__() # these are auto-set checking sys.argv[0] in HiveImpalaCLI class self.name = 'Impala' #self.default_port = 21050 #self.default_service_name = 'impala' if __name__ == '__main__': ImpalaSchemasCSV().main()
knmcguire/gap_sdk
tools/pulp_tools/pulp-debug-bridge/include/bridge-commands.hpp
/* * Copyright (C) 2018 ETH Zurich, University of Bologna and GreenWaves Technologies SA * * 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. */ /* * Authors: <NAME>, GWT (<EMAIL>) */ #ifndef __BRIDGE_COMMANDS_H #define __BRIDGE_COMMANDS_H #include <memory> #include <queue> #include <stack> #include <chrono> #include <exception> #include <list> #include "events/emitter.hpp" #include "events/events.hpp" #include "reqloop.hpp" #include "bridge-state.hpp" class BridgeCommandsException : public std::exception { }; class BridgeUnmatchedLoopException : public BridgeCommandsException { public: const char* what() const throw() { return "Unmatched startloop or endloop command"; } }; SMART_EMITTER(BridgeCommandsExit, exit) class BridgeCommands : public std::enable_shared_from_this<BridgeCommands>, public BridgeCommandsExitEmitter<> { public: using bridge_func_t = std::function<int(void *)>; using bridge_cont_complete_func_t = std::function<void(int)>; using bridge_cont_func_t = std::function<void(void *, bridge_cont_complete_func_t)>; using SpBridgeCommands = std::shared_ptr<BridgeCommands>; class BridgeCommand : public std::enable_shared_from_this<BridgeCommand> { public: virtual ~BridgeCommand() { }; virtual int64_t execute(SpBridgeCommands bc) = 0; }; class BridgeCommandExecute : public BridgeCommand { public: ~BridgeCommandExecute() {} BridgeCommandExecute(const bridge_func_t& cb) : m_cb(std::move(cb)) {} int64_t execute(SpBridgeCommands bc); private: bridge_func_t m_cb; }; class BridgeCommandExecuteAsync : public BridgeCommand { public: ~BridgeCommandExecuteAsync() {} BridgeCommandExecuteAsync(const bridge_cont_func_t& cb, const bridge_cont_complete_func_t& cb_complete) : m_cb(std::move(cb)), m_cb_complete(std::move(cb_complete)) {} int64_t execute(SpBridgeCommands bc); private: bridge_cont_func_t m_cb; bridge_cont_complete_func_t m_cb_complete; }; class BridgeCommandDelay : public BridgeCommand { public: ~BridgeCommandDelay() {} BridgeCommandDelay(std::chrono::microseconds duration) : m_duration(duration) {} int64_t execute(SpBridgeCommands UNUSED(bc)) { return m_duration.count(); }; private: std::chrono::microseconds m_duration; }; class BridgeCommandCollection : public BridgeCommand { public: ~BridgeCommandCollection() { while (!m_command_queue.empty()) m_command_queue.pop(); } BridgeCommandCollection() {} BridgeCommandCollection(const std::queue<std::shared_ptr<BridgeCommand>> &command_queue) : m_command_queue(std::move(command_queue)) {} virtual int64_t execute(SpBridgeCommands bc); void add_command(const std::shared_ptr<BridgeCommand> &command) { m_command_queue.emplace(command); } protected: std::queue<std::shared_ptr<BridgeCommand>> m_command_queue; bool m_started = false; }; class BridgeCommandRepeat : public BridgeCommandCollection { public: ~BridgeCommandRepeat() {} BridgeCommandRepeat(std::chrono::microseconds delay, int repeat_times) : m_delay(delay), m_repeat_times(repeat_times) {} int64_t execute(SpBridgeCommands bc); private: std::chrono::microseconds m_delay; int m_repeat_times; }; class BridgeCommandWaitExit : public BridgeCommand { public: ~BridgeCommandWaitExit() { } BridgeCommandWaitExit(SpBridgeCommands bc); int64_t execute(SpBridgeCommands bc); private: bool m_waiting = false; std::weak_ptr<BridgeCommands> m_bc; }; BridgeCommands(BridgeState * state) : m_state(state) { m_command_stack.push(std::make_shared<BridgeCommandCollection>()); } ~BridgeCommands() { clearall_exit(); while(!m_command_stack.empty()) m_command_stack.pop(); } int start_bridge(); void stop_bridge(); void queue_next_command(); void add_execute(const bridge_func_t& cb); void add_execute(const bridge_cont_func_t& cb); void add_repeat_start(std::chrono::microseconds delay, int count); void add_repeat_end(); void add_delay(std::chrono::microseconds delay); void add_wait_exit(); void trigger_exit() { emit_exit(); } EventLoop::SpEventLoop get_loop() { return m_state->m_event_loop; } std::shared_ptr<ReqLoop> get_req_loop() { return m_state->m_req_loop; } private: BridgeState * m_state; std::stack<std::shared_ptr<BridgeCommandCollection>> m_command_stack; int m_return_value; }; #endif
doveylovey/alipay-sdk-java
src/main/java/com/alipay/api/domain/AlipayTradePaygrowthPayabilityQueryModel.java
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 查询用户支付宝账户支付能力 * * @author auto create * @since 1.0, 2018-10-22 14:09:50 */ public class AlipayTradePaygrowthPayabilityQueryModel extends AlipayObject { private static final long serialVersionUID = 1227837699431816383L; /** * 业务标识,用于支付场景,需要根据具体的支付类型传值。 */ @ApiField("biz_identity") private String bizIdentity; /** * 实际支付金额,单位为元,精确到小数点后两位,取值范围[0.01,100000000] */ @ApiField("real_pay_amount") private String realPayAmount; /** * 请求来源,必传,新的场景取值需要根据业务定义。 */ @ApiField("request_from") private String requestFrom; /** * 支付宝userId,不能为空 */ @ApiField("user_id") private String userId; public String getBizIdentity() { return this.bizIdentity; } public void setBizIdentity(String bizIdentity) { this.bizIdentity = bizIdentity; } public String getRealPayAmount() { return this.realPayAmount; } public void setRealPayAmount(String realPayAmount) { this.realPayAmount = realPayAmount; } public String getRequestFrom() { return this.requestFrom; } public void setRequestFrom(String requestFrom) { this.requestFrom = requestFrom; } public String getUserId() { return this.userId; } public void setUserId(String userId) { this.userId = userId; } }
PhilAndrew/choco3gwt
choco-solver/src/main/java/org/chocosolver/solver/variables/events/SetEventType.java
/** * Copyright (c) 2014, * <NAME> (TASC, INRIA Rennes, LINA CNRS UMR 6241), * <NAME> (COSLING S.A.S.). * 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 the <organization> 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 <COPYRIGHT HOLDER> 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. */ package org.chocosolver.solver.variables.events; /** * An enum defining the set variable event types: * <ul> * <li><code>ADD_TO_KER</code>: value enforcing event,</li> * <li><code>REMOVE_FROM_ENVELOPE</code>: value removal event,</li> * </ul> * <p/> * * @author <NAME>, <NAME> */ public enum SetEventType implements IEventType { VOID(0), ADD_TO_KER(1), REMOVE_FROM_ENVELOPE(2); private final int mask; private final int strengthened_mask; private SetEventType(int mask) { this.mask = mask; this.strengthened_mask = mask; } @Override public int getMask() { return mask; } @Override public int getStrengthenedMask() { return strengthened_mask; } //****************************************************************************************************************** //****************************************************************************************************************** public static int all() { return ADD_TO_KER.mask+REMOVE_FROM_ENVELOPE.mask; } public static boolean isKerAddition(int mask) { return (mask & ADD_TO_KER.mask) != 0; } public static boolean isEnvRemoval(int mask) { return (mask & REMOVE_FROM_ENVELOPE.mask) != 0; } }
D0ggy/wk-os
arch/arm/include/asm_config.h
<filename>arch/arm/include/asm_config.h /* * Copyright (C) 2018 胡启航<<NAME>> * * Author: wkcs * * Email: <EMAIL>, <EMAIL> */ #ifndef __ARM_ASM_CONFIG_H__ #define __ARM_ASM_CONFIG_H__ #include <board_config.h> #define MM_ALIGN 4u #define MM_BLOCK_SIZE (MM_ALIGN * 32) #endif
Ttanasart-pt/Create
src/main/java/com/simibubi/create/content/contraptions/relays/belt/transport/BeltTunnelInteractionHandler.java
<gh_stars>1-10 package com.simibubi.create.content.contraptions.relays.belt.transport; import com.simibubi.create.AllBlocks; import com.simibubi.create.content.contraptions.relays.belt.BeltBlock; import com.simibubi.create.content.contraptions.relays.belt.BeltHelper; import com.simibubi.create.content.contraptions.relays.belt.BeltSlope; import com.simibubi.create.content.contraptions.relays.belt.BeltTileEntity; import com.simibubi.create.content.logistics.block.belts.tunnel.BeltTunnelBlock; import com.simibubi.create.content.logistics.block.belts.tunnel.BeltTunnelTileEntity; import com.simibubi.create.content.logistics.block.belts.tunnel.BrassTunnelBlock; import com.simibubi.create.content.logistics.block.belts.tunnel.BrassTunnelTileEntity; import com.simibubi.create.foundation.tileEntity.TileEntityBehaviour; import com.simibubi.create.foundation.tileEntity.behaviour.belt.DirectBeltInputBehaviour; import com.simibubi.create.foundation.utility.Iterate; import net.minecraft.block.BlockState; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Direction; import net.minecraft.util.Direction.Axis; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.items.ItemHandlerHelper; public class BeltTunnelInteractionHandler { public static boolean flapTunnelsAndCheckIfStuck(BeltInventory beltInventory, TransportedItemStack current, float nextOffset) { int currentSegment = (int) current.beltPosition; int upcomingSegment = (int) nextOffset; Direction movementFacing = beltInventory.belt.getMovementFacing(); if (!beltInventory.beltMovementPositive && nextOffset == 0) upcomingSegment = -1; if (currentSegment == upcomingSegment) return false; if (stuckAtTunnel(beltInventory, upcomingSegment, current.stack, movementFacing)) { current.beltPosition = currentSegment + (beltInventory.beltMovementPositive ? .99f : .01f); return true; } World world = beltInventory.belt.getWorld(); boolean onServer = !world.isRemote; boolean removed = false; BeltTunnelTileEntity nextTunnel = getTunnelOnSegement(beltInventory, upcomingSegment); if (nextTunnel instanceof BrassTunnelTileEntity) { BrassTunnelTileEntity brassTunnel = (BrassTunnelTileEntity) nextTunnel; if (brassTunnel.hasDistributionBehaviour()) { if (!brassTunnel.canTakeItems()) return true; if (onServer) { brassTunnel.setStackToDistribute(current.stack); current.stack = ItemStack.EMPTY; beltInventory.belt.sendData(); beltInventory.belt.markDirty(); } removed = true; } } else if (nextTunnel != null) { BlockState blockState = nextTunnel.getBlockState(); if (current.stack.getCount() > 1 && AllBlocks.ANDESITE_TUNNEL.has(blockState) && BeltTunnelBlock.isJunction(blockState) && movementFacing.getAxis() == blockState.get(BeltTunnelBlock.HORIZONTAL_AXIS)) { for (Direction d : Iterate.horizontalDirections) { if (d.getAxis() == blockState.get(BeltTunnelBlock.HORIZONTAL_AXIS)) continue; if (!nextTunnel.flaps.containsKey(d)) continue; BlockPos outpos = nextTunnel.getPos() .down() .offset(d); if (!world.isBlockPresent(outpos)) return true; DirectBeltInputBehaviour behaviour = TileEntityBehaviour.get(world, outpos, DirectBeltInputBehaviour.TYPE); if (behaviour == null) continue; if (!behaviour.canInsertFromSide(d)) continue; ItemStack toinsert = ItemHandlerHelper.copyStackWithSize(current.stack, 1); if (!behaviour.handleInsertion(toinsert, d, false).isEmpty()) return true; if (onServer) flapTunnel(beltInventory, upcomingSegment, d, false); current.stack.shrink(1); beltInventory.belt.sendData(); if (current.stack.getCount() <= 1) break; } } } if (onServer) { flapTunnel(beltInventory, currentSegment, movementFacing, false); flapTunnel(beltInventory, upcomingSegment, movementFacing.getOpposite(), true); } if (removed) return true; return false; } public static boolean stuckAtTunnel(BeltInventory beltInventory, int offset, ItemStack stack, Direction movementDirection) { BeltTileEntity belt = beltInventory.belt; BlockPos pos = BeltHelper.getPositionForOffset(belt, offset) .up(); if (!(belt.getWorld() .getBlockState(pos) .getBlock() instanceof BrassTunnelBlock)) return false; TileEntity te = belt.getWorld() .getTileEntity(pos); if (te == null || !(te instanceof BrassTunnelTileEntity)) return false; BrassTunnelTileEntity tunnel = (BrassTunnelTileEntity) te; return !tunnel.canInsert(movementDirection.getOpposite(), stack); } public static void flapTunnel(BeltInventory beltInventory, int offset, Direction side, boolean inward) { BeltTunnelTileEntity te = getTunnelOnSegement(beltInventory, offset); if (te == null) return; te.flap(side, inward ^ side.getAxis() == Axis.Z); } protected static BeltTunnelTileEntity getTunnelOnSegement(BeltInventory beltInventory, int offset) { BeltTileEntity belt = beltInventory.belt; if (belt.getBlockState() .get(BeltBlock.SLOPE) != BeltSlope.HORIZONTAL) return null; BlockPos pos = BeltHelper.getPositionForOffset(belt, offset) .up(); if (!(belt.getWorld() .getBlockState(pos) .getBlock() instanceof BeltTunnelBlock)) return null; TileEntity te = belt.getWorld() .getTileEntity(pos); if (te == null || !(te instanceof BeltTunnelTileEntity)) return null; return ((BeltTunnelTileEntity) te); } }
IC-hub/redbase
src/ql.h
// // ql.h // Query Language Component Interface // // This file only gives the stub for the QL component #ifndef QL_H #define QL_H #include <stdlib.h> #include <string.h> #include "redbase.h" #include "parser.h" #include "ql_error.h" #include "rm.h" #include "ix.h" #include "sm.h" #include "iterator.h" // // QL_Manager: query language (DML) // class QL_Manager { public: QL_Manager (SM_Manager &smm, IX_Manager &ixm, RM_Manager &rmm); ~QL_Manager(); // Destructor RC Select (int nSelAttrs, // # attrs in select clause // const RelAttr selAttrs[], // attrs in select clause const AggRelAttr selAttrs[], // attrs in select clause int nRelations, // # relations in from clause const char * const relations[], // relations in from clause int nConditions, // # conditions in where clause const Condition conditions[], // conditions in where clause int order, // order from order by clause RelAttr orderAttr, // the single attr ordered by bool group, RelAttr groupAttr); RC Insert (const char *relName, // relation to insert into int nValues, // # values const Value values[]); // values to insert RC Delete (const char *relName, // relation to delete from int nConditions, // # conditions in where clause const Condition conditions[]); // conditions in where clause RC Update (const char *relName, // relation to update const RelAttr &updAttr, // attribute to update const int bIsValue, // 1 if RHS is a value, 0 if attr const RelAttr &rhsRelAttr, // attr on RHS to set LHS eq to const Value &rhsValue, // or value to set attr eq to int nConditions, // # conditions in where clause const Condition conditions[]); // conditions in where clause public: RC IsValid() const; // Choose between filescan and indexscan for first operation - leaf level of // operator tree // to see if NLIJ is possible, join condition is passed down Iterator* GetLeafIterator(const char *relName, int nConditions, const Condition conditions[], int nJoinConditions = 0, const Condition jconditions[] = NULL, int order = 0, RelAttr* porderAttr = NULL); RC MakeRootIterator(Iterator*& newit, int nSelAttrs, const AggRelAttr selAttrs[], int nRelations, const char * const relations[], int order, RelAttr orderAttr, bool group, RelAttr groupAttr) const; RC PrintIterator(Iterator* it) const; void GetCondsForSingleRelation(int nConditions, Condition conditions[], char* relName, int& retCount, Condition*& retConds) const; // get conditions that involve both relations. intermediate relations are // possible from previous joins done so far - hence relsSoFar. void GetCondsForTwoRelations(int nConditions, Condition conditions[], int nRelsSoFar, char* relations[], char* relName2, int& retCount, Condition*& retConds) const; private: RM_Manager& rmm; IX_Manager& ixm; SM_Manager& smm; }; #endif // QL_H
yyh12345685/libnbf
src/event/event_data.cpp
<filename>src/event/event_data.cpp #include <string.h> #include "event/event_data.h" namespace bdf { static int incr_fd2data = 4096; static int init_fd2data = 40960; LOGGER_CLASS_IMPL(logger_, EventData); bool EventData::InitEventData(){ fd2data_ = (FdEvent **)malloc((init_fd2data + 1) * sizeof(*fd2data_)); if (nullptr == fd2data_){ WARN(logger_, "Malloc error."); } else{ TRACE(logger_, "Malloc ok."); memset(fd2data_, 0, sizeof(*fd2data_) *(init_fd2data + 1)); fd2data_size_ = init_fd2data; } closed_ = nullptr; closed_size_ = closed_count_ = 0; return true; } bool EventData::ReInitEventData(int& fd){ INFO(logger_, "before FdEvent realloc, fd2data_size_:" << fd2data_size_); int data_size_tmp = fd2data_size_ + incr_fd2data; while (data_size_tmp < fd) data_size_tmp += incr_fd2data; FdEvent **tmp = (FdEvent **)realloc(fd2data_, (data_size_tmp + 1) * sizeof(*tmp)); if (!tmp){ WARN(logger_, "EventData::Add realloc error."); return false; } fd2data_ = tmp; memset(fd2data_ + fd2data_size_ + 1, 0, sizeof(*fd2data_) * (data_size_tmp - fd2data_size_)); fd2data_size_ = data_size_tmp; INFO(logger_, "after FdEvent realloc, fd2data_size_:" << fd2data_size_); return true; } bool EventData::ReInitClosed(int& fd){ lock_.Lock(); if (closed_count_ >= closed_size_){ FdEvent **tmp = (FdEvent **)realloc(closed_, (closed_size_ + 1) * sizeof(*tmp)); if (!tmp){ lock_.UnLock(); WARN(logger_, "realloc failed, closed_size_:" << closed_size_); return false; } closed_ = tmp; closed_size_++; } if (nullptr != fd2data_[fd]){ closed_[closed_count_++] = fd2data_[fd]; fd2data_[fd]->closed_ = true; } lock_.UnLock(); return true; } void EventData::RemoveClosed(){ lock_.Lock(); for (int i = 0; i < closed_count_; ++i){ if (closed_[i]->closed_){ delete closed_[i]; closed_[i] = nullptr; } } closed_count_ = 0; lock_.UnLock(); } EventData::~EventData(){ lock_.Lock(); if (nullptr != fd2data_){ for (int fd = 0; fd <= fd2data_size_; ++fd){ if (nullptr != fd2data_[fd]){ delete fd2data_[fd]; fd2data_[fd] = nullptr; } } free(fd2data_); fd2data_ = nullptr; } for (int i = 0; i < closed_count_; ++i){ if (nullptr != closed_[i]){ delete closed_[i]; closed_[i] = nullptr; } } free(closed_); closed_ = nullptr; closed_count_ = closed_size_ = 0; lock_.UnLock(); } }
prodypanda/mail-check
src/react/ukncsc-mail-check-app/src/page/routes/PageRoutes.js
<reponame>prodypanda/mail-check import React from 'react'; import AdminRoutes from 'admin/routes'; import AntiSpoofingRoutes from 'anti-spoofing/routes'; import CommonRoutes from 'common/routes'; import DomainSecurityRoutes from 'domain-security/routes'; import MetricsRoutes from 'metrics/routes'; import MyDomainsRoutes from 'my-domains/routes'; import WelcomeRoutes from 'welcome/routes'; export default () => ( <React.Fragment> <AdminRoutes /> <AntiSpoofingRoutes /> <CommonRoutes /> <DomainSecurityRoutes /> <MetricsRoutes /> <MyDomainsRoutes /> <WelcomeRoutes /> </React.Fragment> );
kjthegod/chromium
extensions/shell/browser/api/shell_gcd/shell_gcd_api.cc
<filename>extensions/shell/browser/api/shell_gcd/shell_gcd_api.cc<gh_stars>1-10 // Copyright 2014 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 "extensions/shell/browser/api/shell_gcd/shell_gcd_api.h" #include "base/values.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/privet_daemon_client.h" #include "extensions/shell/common/api/shell_gcd.h" namespace gcd = extensions::shell::api::shell_gcd; namespace extensions { ShellGcdGetSetupStatusFunction::ShellGcdGetSetupStatusFunction() { } ShellGcdGetSetupStatusFunction::~ShellGcdGetSetupStatusFunction() { } ExtensionFunction::ResponseAction ShellGcdGetSetupStatusFunction::Run() { // |this| is refcounted so we don't need the usual DBus callback WeakPtr. chromeos::DBusThreadManager::Get()->GetPrivetDaemonClient()->GetSetupStatus( base::Bind(&ShellGcdGetSetupStatusFunction::OnSetupStatus, this)); return RespondLater(); } void ShellGcdGetSetupStatusFunction::OnSetupStatus( const std::string& status_string) { gcd::SetupStatus status = gcd::ParseSetupStatus(status_string); Respond(ArgumentList(gcd::GetSetupStatus::Results::Create(status))); } } // namespace extensions
prsdcse/react-bootstrap-table2
packages/react-bootstrap-table2-toolkit/src/csv/button.js
import React from 'react'; import PropTypes from 'prop-types'; const ExportCSVButton = (props) => { const { onExport, children, className, ...rest } = props; return ( <button type="button" className={ `react-bs-table-csv-btn btn btn-default ${className}` } onClick={ () => onExport() } { ...rest } > { children } </button> ); }; ExportCSVButton.propTypes = { children: PropTypes.node.isRequired, onExport: PropTypes.func.isRequired, className: PropTypes.string, style: PropTypes.object }; ExportCSVButton.defaultProps = { className: '', style: {} }; export default ExportCSVButton;
starpeak/cloudmodel
spec/workers/cloud_model/base_worker_spec.rb
require 'spec_helper' describe CloudModel::BaseWorker do let(:host) { Factory :host } subject { CloudModel::BaseWorker.new host } context 'render' do it 'should call render on a new instance of ActionView::Base and pass return value' do action_view = double(ActionView::Base) ActionView::Base.stub(:new).and_return action_view action_view.should_receive(:view_paths=).with ActionController::Base.view_paths action_view.should_receive(:render).with(template: 'my_template', locals: {a:1, b:2}).and_return 'rendered template' expect(subject.render 'my_template', a: 1, b: 2).to eq 'rendered template' end end context 'build_tar' do it 'should execute tar on host' do host.should_receive(:exec!).with("tar cf /inst/image.tar.bz2 /mnt/root", "Failed to build tar /inst/image.tar.bz2").and_return 'ok' subject.build_tar '/mnt/root', '/inst/image.tar.bz2' end it 'should parse boolean parameter' do host.should_receive(:exec!).with("tar cf /inst/image.tar.bz2 --option /mnt/root", "Failed to build tar /inst/image.tar.bz2").and_return 'ok' subject.build_tar '/mnt/root', '/inst/image.tar.bz2', option: true end it 'should parse valued parameter' do host.should_receive(:exec!).with("tar cf /inst/image.tar.bz2 --option test /mnt/root", "Failed to build tar /inst/image.tar.bz2").and_return 'ok' subject.build_tar '/mnt/root', '/inst/image.tar.bz2', option: 'test' end it 'should parse multiplevalued parameter' do host.should_receive(:exec!).with("tar cf /inst/image.tar.bz2 --option test --option test2 /mnt/root", "Failed to build tar /inst/image.tar.bz2").and_return 'ok' subject.build_tar '/mnt/root', '/inst/image.tar.bz2', option: ['test', 'test2'] end it 'should only put one - in front of single character options' do host.should_receive(:exec!).with("tar cf /inst/image.tar.bz2 -j -C test /mnt/root", "Failed to build tar /inst/image.tar.bz2").and_return 'ok' subject.build_tar '/mnt/root', '/inst/image.tar.bz2', j: true, C: 'test' end it 'should escape values' do host.should_receive(:exec!).with("tar cf /inst/image.tar.bz2\\;\\ mkfs.ext2\\ /dev/sda --option\\;\\ echo\\ /dev/random\\ /etc/passwd\\; test\\;\\ rsync\\ /\\ bad_host:/pirate\\; /mnt/root\\;\\ rm\\ -rf\\ /\\;", "Failed to build tar /inst/image.tar.bz2; mkfs.ext2 /dev/sda").and_return 'ok' subject.build_tar '/mnt/root; rm -rf /;', '/inst/image.tar.bz2; mkfs.ext2 /dev/sda', 'option; echo /dev/random /etc/passwd;' => 'test; rsync / bad_host:/pirate;' end end end
kukuhBaiquni/eltrion
src/Library/Redux/actions/_f_EditNonMemberInformation.js
<reponame>kukuhBaiquni/eltrion import { put, call, takeEvery } from 'redux-saga/effects'; import request from 'superagent'; import { SERVER_URL } from '../../../Configuration'; export const _editNonMemberInformation = (data) => { return { type: 'EDIT_NON_MEMBER_INFORMATION', data } }; const _editNonMemberInformation_X = () => { return { type: 'EDIT_NON_MEMBER_INFORMATION_FAILED' } }; const _editNonMemberInformation_V = (data) => { return { type: 'EDIT_NON_MEMBER_INFORMATION_SUCCESS', data } }; export const _resetEditNonMemberInformation = () => { return { type: 'RESET_EDIT_NON_MEMBER_INFORMATION_STATE' } }; export function* o_editNonMemberInformation(data) { yield takeEvery('EDIT_NON_MEMBER_INFORMATION', k_editNonMemberInformation) }; function* k_editNonMemberInformation(form) { try{ var response = yield call(() => { return request .post(`${SERVER_URL}admin/crud-user/edit`) .set('Authorization', `${form.data.token}`) .send({data: form.data}) .then((res) => { return res; }) }); yield put(_editNonMemberInformation_V(response.body.data)); }catch (error) { yield put(_editNonMemberInformation_X('Error when loading data!')); }; }
hyller/GladiatorLibrary
D4D/eGUI/D4D/graphic_objects/d4d_menu.h
<reponame>hyller/GladiatorLibrary /************************************************************************** * * Copyright 2014 by <NAME>. eGUI Community. * Copyright 2009-2013 by <NAME>. Freescale Semiconductor, Inc. * *************************************************************************** * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License Version 3 * or later (the "LGPL"). * * As a special exception, the copyright holders of the eGUI project give you * permission to link the eGUI sources with independent modules to produce an * executable, regardless of the license terms of these independent modules, * and to copy and distribute the resulting executable under terms of your * choice, provided that you also meet, for each linked independent module, * the terms and conditions of the license of that module. * An independent module is a module which is not derived from or based * on this library. * If you modify the eGUI sources, you may extend this exception * to your version of the eGUI sources, but you are not obligated * to do so. If you do not wish to do so, delete this * exception statement from your 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. * * You should have received a copy of the GNU General Public License * and the GNU Lesser General Public License along with this program. * If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************//*! * * @file d4d_menu.h * * @author <NAME> * * @version 0.0.47.0 * * @date Jan-14-2014 * * @brief D4D Driver menu object header file * *******************************************************************************/ #ifndef __D4D_MENU_H #define __D4D_MENU_H extern const D4D_OBJECT_SYS_FUNCTION d4d_menuSysFunc; void D4D_MenuScrollBarsFeedBack(D4D_OBJECT* pThis, D4D_INDEX old_position, D4D_INDEX new_position); /****************************************************************************** * D4D MENU setting constants * *//*! @addtogroup doxd4d_menu_const * @{ *******************************************************************************/ //********************* Menu flags for button specific flags ***************** /*! @defgroup doxd4d_menu_const_flags D4D MENU Defines masks of menu specific behaviour flags This section specifies masks of menu behaviour flags. @ingroup doxd4d_menu_const */ /** * @addtogroup doxd4d_menu_const_flags * @{ */ #define D4D_MENU_F_INDEX (0x01 << D4D_OBJECT_F_OBJECT_SHIFT) ///< Enable show of index of items in header #define D4D_MENU_F_SIDEBAR (0x02 << D4D_OBJECT_F_OBJECT_SHIFT) ///< Forca always show of side bar scroll bar /**@}*/ /*! @brief This is menu init flags. If not defined, it sets to (\ref D4D_OBJECT_F_VISIBLE | \ref D4D_OBJECT_F_ENABLED | \ref D4D_OBJECT_F_TABSTOP | \ref D4D_OBJECT_F_TOUCHENABLE | \ref D4D_OBJECT_F_MOUSE_NORMAL | \ref D4D_OBJECT_F_BEVEL_RAISED | \ref D4D_MENU_F_INDEX | \ref D4D_MENU_F_SIDEBAR) as a default.*/ #ifndef D4D_MENU_F_DEFAULT #define D4D_MENU_F_DEFAULT (D4D_OBJECT_F_VISIBLE | D4D_OBJECT_F_ENABLED | D4D_OBJECT_F_TABSTOP | D4D_OBJECT_F_TOUCHENABLE | D4D_OBJECT_F_MOUSE_NORMAL | D4D_OBJECT_F_BEVEL_RAISED | D4D_MENU_F_INDEX | D4D_MENU_F_SIDEBAR) #endif /*! @brief This is menu embedded scroll bar init flags. If not defined, it sets to (\ref D4D_OBJECT_F_ENABLED | \ref D4D_OBJECT_F_TOUCHENABLE | \ref D4D_OBJECT_F_FASTTOUCH | \ref D4D_OBJECT_F_MOUSE_NORMAL) as a default.*/ #ifndef D4D_MENU_F_SCRLBRS_DEFAULT #define D4D_MENU_F_SCRLBRS_DEFAULT (D4D_OBJECT_F_ENABLED | D4D_OBJECT_F_TOUCHENABLE | D4D_OBJECT_F_FASTTOUCH | D4D_OBJECT_F_MOUSE_NORMAL) #endif /*! @brief This is menu embedded scroll bar width If not defined, it sets to 20 pixels as a default.*/ #ifndef D4D_MENU_SCRLBR_WIDTH #define D4D_MENU_SCRLBR_WIDTH ( 20 ) #endif /*! @brief This is menu embedded scroll bar change step If not defined, it sets to 1 step as a default.*/ #ifndef D4D_MENU_SCRLBR_STEP #define D4D_MENU_SCRLBR_STEP ( 1 ) #endif /*! @brief This is menu init title text properties. If not defined, it sets to (\ref D4D_ALIGN_H_CENTER_MASK | \ref D4D_ALIGN_V_CENTER_MASK) as a default.*/ #ifndef D4D_MENU_TXT_PRTY_DEFAULT #define D4D_MENU_TXT_PRTY_DEFAULT (D4D_ALIGN_H_CENTER_MASK | D4D_ALIGN_V_CENTER_MASK) #endif /*! @brief This is menu init title font properties. If not defined, it sets to ( 0 ) as a default.*/ #ifndef D4D_MENU_FNT_PRTY_DEFAULT #define D4D_MENU_FNT_PRTY_DEFAULT ( 0 ) #endif /*! @brief This is menu init index font properties. If not defined, it sets to ( 0 ) as a default.*/ #ifndef D4D_MENU_IX_FNT_PRTY_DEFAULT #define D4D_MENU_IX_FNT_PRTY_DEFAULT ( 0 ) #endif /*! @brief This is menu init index text properties. If not defined, it sets to (\ref D4D_ALIGN_H_CENTER_MASK | \ref D4D_ALIGN_V_CENTER_MASK) as a default.*/ #ifndef D4D_MENU_IX_TXT_PRTY_DEFAULT #define D4D_MENU_IX_TXT_PRTY_DEFAULT ( D4D_ALIGN_H_CENTER_MASK | D4D_ALIGN_V_CENTER_MASK ) #endif /*! @brief This is menu init items font properties. If not defined, it sets to ( 0 ) as a default.*/ #ifndef D4D_MENU_ITEM_FNT_PRTY_DEFAULT #define D4D_MENU_ITEM_FNT_PRTY_DEFAULT ( 0 ) #endif /*! @brief This is menu init items text properties. If not defined, it sets to (\ref D4D_ALIGN_H_LEFT_MASK | \ref D4D_ALIGN_V_CENTER_MASK) as a default.*/ #ifndef D4D_MENU_ITEM_TXT_PRTY_DEFAULT #define D4D_MENU_ITEM_TXT_PRTY_DEFAULT ( D4D_ALIGN_V_CENTER_MASK | D4D_ALIGN_H_LEFT_MASK ) #endif /*! @} End of doxd4d_menu_const */ /****************************************************************************** * D4D MENU setting public types * *//*! @addtogroup doxd4d_menu_type * @{ *******************************************************************************/ /*! @brief This is menu item index variable type.*/ typedef sByte D4D_MENU_INDEX; /**************************************************************************/ /*! * @brief Type definition of menu on click callback function * @param pThis - pointer to menu instance that call the function * @param ix - index of item that has been clicked * @return none * @note This is menu call back function used to notify user application about on click event on handled index of item. *******************************************************************************/ typedef void (*D4D_MENU_ON_CLICK)(D4D_OBJECT* pThis, D4D_MENU_INDEX ix); /*! @} End of doxd4d_list_box_type */ /****************************************************************************** * Private Types ******************************************************************************/ // Menu configuration (goes to ROM by default) typedef struct { D4D_STRING text; const D4D_BMP* pIcon; // Item Icon void* pUser; }D4D_MENU_ITEM; typedef struct { D4D_MENU_INDEX ix; D4D_MENU_INDEX page_ix; } D4D_MENU_DATA; typedef struct { D4D_STRING title_text; // menu title text D4D_FONT indexFontId; D4D_FONT itemsFontId; D4D_MENU_INDEX posCnt; // Number of visiable position D4D_COOR textOff; // text offset between individual item on screen const D4D_BMP* pIcon; // Title Icon D4D_MENU_DATA* pData; // Menu volatile data struct const D4D_MENU_ITEM* pItems; D4D_MENU_ON_CLICK OnClicked; } D4D_MENU; /****************************************************************************** * Macros ******************************************************************************/ #define D4D_MENU_CHILD_SCROLL_BAR_VER_IX 1 // getting the MENU structure from general OBJECT #define D4D_GET_MENU(pObj) ((D4D_MENU*)((pObj)->pParam)) #define D4D_GET_MENU_SCROLL_BAR_HOR(pObj) ((D4D_OBJECT*)((pObj)->pRelations[D4D_MENU_CHILD_SCROLL_BAR_VER_IX])) /****************************************************************************** * D4D MENU setting public macros * *//*! @addtogroup doxd4d_menu_macro * @{ *******************************************************************************/ /**************************************************************************/ /*! * @brief Macro that create the Menu object structure in memory including all substructures * @param type - type of object <D4D_CONST; D4D_NO_CONST> * @param name - name of menu object * @param title_text - title text * @param title_font - title text font id * @param x - coordination of menu in X axis * @param y - coordination of menu in Y axis * @param cx - size of menu in X axis (width) * @param cy - size of menu in Y axis (height) (with hidden list box) * @param radius - radius of corners * @param pMargin - pointer to margin structure (*D4D_MARGIN)(Could be NULL) * @param pParent - pointer to parent object (Could be NULL) * @param flags - bitmask that specifies initial \ref doxd4d_object_const_flags and \ref doxd4d_menu_const_flags * @param pScheme - pointer to color scheme. In case that this parameter is NULL, the default scheme color will be used for draw menu * @param indexFontId - identification number of the used index text font * @param itemsFontId - identification number of the used item text font * @param posCnt - count of visible positions * @param menuItemsOff - offset between the individual items in pixels * @param pIcon - pointer to \ref D4D_BMP structure to title * @param pUser - user data of menu * @param pOnClick - Pointer to an on-click user callback function \ref D4D_MENU_ON_CLICK * @param pOnUsrMsg -Pointer to an on user message callback function \ref D4D_ON_USR_MSG. This callback is called before this * message event is sent to the object itself. The message can be skipped by the \ref D4D_MSG_SKIP * return value, in a normal case the return value must be \ref D4D_MSG_NOSKIP * @note This macro create complete D4D_MENU structure, including the object data sub structure. Is used to define all properties of menu. * It must be followed by \ref D4D_DECLARE_MENU_ITEM or \ref D4D_DECLARE_MENU_ITEM_FULL or at least \ref D4D_DECLARE_MENU_END. *******************************************************************************/ #define _D4D_DECLARE_MENU_BEGIN(type, name, title_text, title_font, x, y, cx, cy, radius, pMargin, pParent, flags, pScheme,\ indexFontId, itemsFontId, posCnt, menuItemsOff, pIcon, pUser, pOnClick, pOnUsrMsg) \ extern type D4D_MENU_ITEM name##_items[];\ extern D4D_OBJECT name##_scrollBarVer;\ static const D4D_OBJECT * name##_relations[] = {pParent, &name##_scrollBarVer, NULL};\ static D4D_MENU_DATA name##_data = { 0, 0};\ static D4D_STR_PROPERTIES name##_strPrties = { D4D_MENU_FNT_PRTY_DEFAULT , D4D_MENU_TXT_PRTY_DEFAULT }; \ static type D4D_MENU name##_params = \ { \ { title_text, D4D_TEXT_LEN(title_text), title_font, &name##_strPrties, D4D_OBJECT_MAX_TEXT_LEN(title_text), 0}, \ indexFontId, \ itemsFontId, \ posCnt, \ menuItemsOff, \ pIcon, \ &(name##_data), \ (const D4D_MENU_ITEM*)&(name##_items[0]),\ pOnClick, \ }; \ \ D4D_DECLARE_OBJECT(type, name, x, y, cx, cy, radius, pMargin, name##_relations, pOnUsrMsg, &d4d_menuSysFunc, &(name##_params), flags, pUser, pScheme)\ \ static const D4D_OBJECT* const name##_scrollBarRelations[] = {&name, NULL};\ \ _D4D_DECLARE_SCROLL_BAR(D4D_NO_CONST, name##_scrollBarVer, 20, 100, 100, 20, radius, NULL, name##_scrollBarRelations, D4D_MENU_F_SCRLBRS_DEFAULT, pScheme, NULL, D4D_MenuScrollBarsFeedBack, NULL) \ \ type D4D_MENU_ITEM name##_items[] = { /**************************************************************************/ /*! * @brief Macro that is used to add item to menu definition * @param pText - text of item * @param pIcon - pointer to item icon bitmap * @note This macro is used after the menu declaration to add new item * Here is an example demonstrating how to used it. * @code * D4D_DECLARE_STD_RMENU_AUTOSIZE_BEGIN(my_menu, D4D_DEFSTR("My Menu"), MU_BIG_FONT, 10, 10, 100, 120, 6, MY_SMALL_FONT, MY_FONT, &my_icon, NULL) * D4D_DECLARE_MENU_ITEM(D4D_DEFSTR("My Item1"), &myIcon1) * D4D_DECLARE_MENU_ITEM(D4D_DEFSTR("My Item2"), &myIcon2) * D4D_DECLARE_MENU_END(my_menu) * @endcode *******************************************************************************/ #define D4D_DECLARE_MENU_ITEM(pText, pIcon) { {(pText), D4D_TEXT_LEN(pText), 0, NULL, D4D_OBJECT_MAX_TEXT_LEN(pText), 0}, pIcon, NULL}, /**************************************************************************/ /*! * @brief Macro that is used to add item with user data menu definition * @param pText - text of item * @param pIcon - pointer to item icon bitmap * @param pUser - pointer to user data * @note This macro is used after the menu declaration to add new item with user data * Here is an example demonstrating how to used it. * @code * D4D_DECLARE_STD_RMENU_AUTOSIZE_BEGIN(my_menu, D4D_DEFSTR("My Menu"), MU_BIG_FONT, 10, 10, 100, 120, 6, MY_SMALL_FONT, MY_FONT, &my_icon, NULL) * D4D_DECLARE_MENU_ITEM(D4D_DEFSTR("My Item1"), &myIcon1, 0) * D4D_DECLARE_MENU_ITEM(D4D_DEFSTR("My Item2"), &myIcon2, 1) * D4D_DECLARE_MENU_END(my_menu) * @endcode *******************************************************************************/ #define D4D_DECLARE_MENU_ITEM_FULL(pText, pIcon, pUser) { {(pText), D4D_TEXT_LEN(pText), 0, NULL, D4D_OBJECT_MAX_TEXT_LEN(pText), 0}, pIcon, (void*)pUser}, /**************************************************************************/ /*! * @brief Macro that is used to close the item list for menu definition * @note This macro is used after the menu items declaration to close the list of items * Here is an example demonstrating how to used it. * @code * D4D_DECLARE_STD_RMENU_AUTOSIZE_BEGIN(my_menu, D4D_DEFSTR("My Menu"), MU_BIG_FONT, 10, 10, 100, 120, 6, MY_SMALL_FONT, MY_FONT, &my_icon, NULL) * D4D_DECLARE_MENU_ITEM(D4D_DEFSTR("My Item1"), &myIcon1, 0) * D4D_DECLARE_MENU_ITEM(D4D_DEFSTR("My Item2"), &myIcon2, 1) * _D4D_DECLARE_MENU_END() * @endcode *******************************************************************************/ #define _D4D_DECLARE_MENU_END() { {NULL, 0, 0, NULL}, NULL, NULL} }; /**************************************************************************/ /*! * @brief Macro that is used to close the item list for menu definition * @note This macro is used after the menu items declaration to close the list of items * Here is an example demonstrating how to used it. * This is obsolete macro, the parameter is not needed. It can be used \ref _D4D_DECLARE_MENU_END() instead of. * @code * D4D_DECLARE_STD_RMENU_AUTOSIZE_BEGIN(my_menu, D4D_DEFSTR("My Menu"), MU_BIG_FONT, 10, 10, 100, 120, 6, MY_SMALL_FONT, MY_FONT, &my_icon, NULL) * D4D_DECLARE_MENU_ITEM(D4D_DEFSTR("My Item1"), &myIcon1, 0) * D4D_DECLARE_MENU_ITEM(D4D_DEFSTR("My Item2"), &myIcon2, 1) * _D4D_DECLARE_MENU_END() * @endcode *******************************************************************************/ #define D4D_DECLARE_MENU_END(name) _D4D_DECLARE_MENU_END() /**************************************************************************/ /*! * @brief Macro that create the Menu object structure in memory including all substructures with restricted count of parameters to simplify definition * @param name - name of menu object * @param title_text - title text * @param title_font - title text font id * @param x - coordination of menu in X axis * @param y - coordination of menu in Y axis * @param cx - size of menu in X axis (width) * @param cy - size of menu in Y axis (height) (with hidden list box) * @param flags - bitmask that specifies initial \ref doxd4d_object_const_flags and \ref doxd4d_menu_const_flags * @param pScheme - pointer to color scheme. In case that this parameter is NULL, the default scheme color will be used for draw menu * @param indexFontId - identification number of the used index text font * @param itemsFontId - identification number of the used item text font * @param posCnt - count of visible positions * @param menuItemsOff - offset between the individual items in pixels * @param pIcon - pointer to \ref D4D_BMP structure to title * @param pUser - user data of menu * @param pOnClick - Pointer to an on-click user callback function \ref D4D_MENU_ON_CLICK * @param pOnUsrMsg -Pointer to an on user message callback function \ref D4D_ON_USR_MSG. This callback is called before this * message event is sent to the object itself. The message can be skipped by the \ref D4D_MSG_SKIP * return value, in a normal case the return value must be \ref D4D_MSG_NOSKIP * @note This macro create complete D4D_MENU structure, including the object data sub structure. Is used to define all properties of menu. If * there is missing parameter that is needed by user application used the full macro \ref _D4D_DECLARE_MENU_BEGIN instead of this one. * It must be followed by \ref D4D_DECLARE_MENU_ITEM or \ref D4D_DECLARE_MENU_ITEM_FULL or at least \ref D4D_DECLARE_MENU_END. *******************************************************************************/ #define D4D_DECLARE_MENU_BEGIN(name, title_text, title_font, x, y, cx, cy, flags, pScheme,\ indexFontId, itemsFontId, posCnt, menuItemsOff, pIcon, pUser, pOnClick, pOnUsrMsg) \ _D4D_DECLARE_MENU_BEGIN(D4D_CONST, name, title_text, title_font, x, y, cx, cy, 0, NULL, NULL, flags, pScheme,\ indexFontId, itemsFontId, posCnt, menuItemsOff, pIcon, pUser, pOnClick, pOnUsrMsg) /**************************************************************************/ /*! * @brief Macro that create the Menu object structure in memory including all substructures with restricted count of parameters to simplify definition * The missing parameters are replaced by default values. * @param name - name of menu object * @param title_text - title text * @param title_font - title text font id * @param x - coordination of menu in X axis * @param y - coordination of menu in Y axis * @param cx - size of menu in X axis (width) * @param cy - size of menu in Y axis (height) (with hidden list box) * @param indexFontId - identification number of the used index text font * @param itemsFontId - identification number of the used item text font * @param pIcon - pointer to \ref D4D_BMP structure to title * @param pOnClick - Pointer to an on-click user callback function \ref D4D_MENU_ON_CLICK * @note This macro create complete D4D_MENU structure, including the object data sub structure. Is used to define all properties of menu. If * there is missing parameter that is needed by user application used the full macro \ref _D4D_DECLARE_MENU_BEGIN instead of this one. * The main advantage is less parameters of this macro against the full version. * It must be followed by \ref D4D_DECLARE_MENU_ITEM or \ref D4D_DECLARE_MENU_ITEM_FULL or at least \ref D4D_DECLARE_MENU_END. *******************************************************************************/ #define D4D_DECLARE_STD_MENU_BEGIN(name, title_text, title_font, x, y, cx, cy, indexFontId, itemsFontId, pIcon, pOnClick) \ D4D_DECLARE_MENU_BEGIN(name, title_text, title_font, x, y, cx, cy, (D4D_MENU_F_DEFAULT), NULL,\ IndexFontId, ItemsFontId, 0, 0, pIcon, NULL, pOnClick, NULL) // Rounded menu definition /**************************************************************************/ /*! * @brief Macro that create the rounded Menu object structure in memory including all substructures with restricted count of parameters to simplify definition * @param name - name of menu object * @param title_text - title text * @param title_font - title text font id * @param x - coordination of menu in X axis * @param y - coordination of menu in Y axis * @param cx - size of menu in X axis (width) * @param cy - size of menu in Y axis (height) (with hidden list box) * @param radius - radius of corners * @param flags - bitmask that specifies initial \ref doxd4d_object_const_flags and \ref doxd4d_menu_const_flags * @param pScheme - pointer to color scheme. In case that this parameter is NULL, the default scheme color will be used for draw menu * @param indexFontId - identification number of the used index text font * @param itemsFontId - identification number of the used item text font * @param posCnt - count of visible positions * @param menuItemsOff - offset between the individual items in pixels * @param pIcon - pointer to \ref D4D_BMP structure to title * @param pUser - user data of menu * @param pOnClick - Pointer to an on-click user callback function \ref D4D_MENU_ON_CLICK * @param pOnUsrMsg -Pointer to an on user message callback function \ref D4D_ON_USR_MSG. This callback is called before this * message event is sent to the object itself. The message can be skipped by the \ref D4D_MSG_SKIP * return value, in a normal case the return value must be \ref D4D_MSG_NOSKIP * @note This macro create complete D4D_MENU structure, including the object data sub structure. Is used to define all properties of menu. If * there is missing parameter that is needed by user application used the full macro \ref _D4D_DECLARE_MENU_BEGIN instead of this one. * It must be followed by \ref D4D_DECLARE_MENU_ITEM or \ref D4D_DECLARE_MENU_ITEM_FULL or at least \ref D4D_DECLARE_MENU_END. *******************************************************************************/ #define D4D_DECLARE_RMENU_BEGIN(name, title_text, title_font, x, y, cx, cy, radius, flags, pScheme,\ indexFontId, itemsFontId, posCnt, menuItemsOff, pIcon, pUser, pOnClick, pOnUsrMsg) \ _D4D_DECLARE_MENU_BEGIN(D4D_CONST, name, title_text, title_font, x, y, cx, cy, radius, NULL, NULL, flags, pScheme,\ indexFontId, itemsFontId, posCnt, menuItemsOff, pIcon, pUser, pOnClick, pOnUsrMsg) /**************************************************************************/ /*! * @brief Macro that create the rounded Menu object structure in memory including all substructures with restricted count of parameters to simplify definition * The missing parameters are replaced by default values. * @param name - name of menu object * @param title_text - title text * @param title_font - title text font id * @param x - coordination of menu in X axis * @param y - coordination of menu in Y axis * @param cx - size of menu in X axis (width) * @param cy - size of menu in Y axis (height) (with hidden list box) * @param radius - radius of corners * @param indexFontId - identification number of the used index text font * @param itemsFontId - identification number of the used item text font * @param pIcon - pointer to \ref D4D_BMP structure to title * @param pOnClick - Pointer to an on-click user callback function \ref D4D_MENU_ON_CLICK * @note This macro create complete D4D_MENU structure, including the object data sub structure. Is used to define all properties of menu. If * there is missing parameter that is needed by user application used the full macro \ref _D4D_DECLARE_MENU_BEGIN instead of this one. * The main advantage is less parameters of this macro against the full version. * It must be followed by \ref D4D_DECLARE_MENU_ITEM or \ref D4D_DECLARE_MENU_ITEM_FULL or at least \ref D4D_DECLARE_MENU_END. *******************************************************************************/ #define D4D_DECLARE_STD_RMENU_BEGIN(name, title_text, title_font, x, y, cx, cy, radius, indexFontId, itemsFontId, pIcon, pOnClick) \ D4D_DECLARE_RMENU_BEGIN(name, title_text, title_font, x, y, cx, cy, radius, (D4D_MENU_F_DEFAULT), NULL,\ indexFontId, itemsFontId, 0, 0, pIcon, NULL, pOnClick, NULL) //IN RAM instantions macros /**************************************************************************/ /*! * @brief Same as \ref D4D_DECLARE_MENU_BEGIN, but is created in RAM instead of the ROM memory *******************************************************************************/ #define D4D_DECLARE_MENU_BEGIN_INRAM(name, title_text, title_font, x, y, cx, cy, flags, pScheme,\ indexFontId, itemsFontId, posCnt, menuItemsOff, pIcon, pUser, pOnClick, pOnUsrMsg) \ _D4D_DECLARE_MENU_BEGIN(D4D_NO_CONST, name, title_text, title_font, x, y, cx, cy, 0, NULL, NULL, flags, pScheme,\ indexFontId, itemsFontId, posCnt, menuItemsOff, pIcon, pUser, pOnClick, pOnUsrMsg) /**************************************************************************/ /*! * @brief Same as \ref D4D_DECLARE_STD_MENU_BEGIN, but is created in RAM instead of the ROM memory *******************************************************************************/ #define D4D_DECLARE_STD_MENU_BEGIN_INRAM(name, title_text, title_font, x, y, cx, cy, IndexFontId, ItemsFontId, pIcon, pOnClick) \ D4D_DECLARE_MENU_BEGIN_INRAM(name, title_text, title_font, x, y, cx, cy, (D4D_MENU_F_DEFAULT), NULL,\ IndexFontId, ItemsFontId, 0, 0, pIcon, NULL, pOnClick, NULL) // Rounded menu definition /**************************************************************************/ /*! * @brief Same as \ref D4D_DECLARE_RMENU_BEGIN, but is created in RAM instead of the ROM memory *******************************************************************************/ #define D4D_DECLARE_RMENU_BEGIN_INRAM(name, title_text, title_font, x, y, cx, cy, radius, flags, pScheme,\ indexFontId, itemsFontId, posCnt, menuItemsOff, pIcon, pUser, pOnClick, pOnUsrMsg) \ _D4D_DECLARE_MENU_BEGIN(D4D_NO_CONST, name, title_text, title_font, x, y, cx, cy, radius, NULL, NULL, flags, pScheme,\ indexFontId, itemsFontId, posCnt, menuItemsOff, pIcon, pUser, pOnClick, pOnUsrMsg) /**************************************************************************/ /*! * @brief Same as \ref D4D_DECLARE_STD_RMENU_BEGIN, but is created in RAM instead of the ROM memory *******************************************************************************/ #define D4D_DECLARE_STD_RMENU_BEGIN_INRAM(name, title_text, title_font, x, y, cx, cy, radius, IndexFontId, ItemsFontId, pIcon, pOnClick) \ D4D_DECLARE_RMENU_BEGIN_INRAM(name, title_text, title_font, x, y, cx, cy, radius, (D4D_MENU_F_DEFAULT), NULL,\ IndexFontId, ItemsFontId, 0, 0, pIcon, NULL, pOnClick, NULL) /*! @} End of doxd4d_menu_macro */ /* Obsolete macros */ #define D4D_DECLARE_RMENU_END(name) D4D_DECLARE_MENU_END(name) #define D4D_DECLARE_MENU_END_INRAM(name) _D4D_DECLARE_MENU_END() #define D4D_DECLARE_RMENU_END_INRAM(name) D4D_DECLARE_MENU_END_INRAM(name) /****************************************************************************** * Global functions ******************************************************************************/ D4D_MENU_INDEX D4D_MenuGetIndex(D4D_OBJECT* pThis); void D4D_MenuSetIndex(D4D_OBJECT* pThis, D4D_MENU_INDEX ix); D4D_MENU_INDEX D4D_MenuGetItemCount(D4D_OBJECT_PTR pThis); D4D_MENU_INDEX D4D_MenuFindUserDataItem(D4D_OBJECT_PTR pThis, void* pUser); void* D4D_MenuGetItemUserData(D4D_OBJECT_PTR pThis); D4D_STRING* D4D_MenuGetItemText(D4D_OBJECT_PTR pThis); #endif /* __D4D_MENU_H */
programmer-666/Codes
Python/FromUniversity/modules/np3.py
import numpy as np numss = np.array([[1,2,3],[4,5,6]]) print(numss[1,2], numss[:,1]) a2 = numss.copy() print(a2)
ylksty/gulimall
mall-member/src/main/java/com/ylkget/gmall/member/exception/PhoneExsitException.java
<filename>mall-member/src/main/java/com/ylkget/gmall/member/exception/PhoneExsitException.java package com.ylkget.gmall.member.exception; /** * <p> * * </p> * * @author joe 2021/2/23 17:02 */ public class PhoneExsitException extends Exception { public PhoneExsitException() { super("手机号存在"); } }
oremj/zamboni
mkt/reviewers/helpers.py
import jinja2 import waffle from django.utils.encoding import smart_str from jingo import register from tower import ugettext as _, ugettext_lazy as _lazy from access import acl from amo.helpers import impala_breadcrumbs from amo.urlresolvers import reverse from mkt.developers.helpers import mkt_page_title from mkt.reviewers.utils import clean_sort_param, create_sort_link @register.function @jinja2.contextfunction def reviewers_breadcrumbs(context, queue=None, items=None): """ Wrapper function for ``breadcrumbs``. Prepends 'Editor Tools' breadcrumbs. **queue** Explicit queue type to set. **items** list of [(url, label)] to be inserted after Add-on. """ crumbs = [(reverse('reviewers.home'), _('Reviewer Tools'))] if queue: queues = {'pending': _('Apps'), 'rereview': _('Re-reviews'), 'updates': _('Updates'), 'escalated': _('Escalations'), 'moderated': _('Moderated Reviews'), 'themes': _('Themes')} if items: url = reverse('reviewers.apps.queue_%s' % queue) else: # The Addon is the end of the trail. url = None crumbs.append((url, queues[queue])) if items: crumbs.extend(items) return impala_breadcrumbs(context, crumbs, add_default=True) @register.function @jinja2.contextfunction def reviewers_page_title(context, title=None, addon=None): if addon: title = u'%s | %s' % (title, addon.name) else: section = _lazy('Reviewer Tools') title = u'%s | %s' % (title, section) if title else section return mkt_page_title(context, title) @register.function @jinja2.contextfunction def queue_tabnav(context): """ Returns tuple of tab navigation for the queue pages. Each tuple contains four elements: (url namespace prefix, tab_code, page_url, tab_text) """ counts = context['queue_counts'] # Apps. if acl.action_allowed(context['request'], 'Apps', 'Review'): rv = [ ('apps', 'pending', 'queue_pending', _('Apps ({0})', counts['pending']).format(counts['pending'])), ('apps', 'rereview', 'queue_rereview', _('Re-reviews ({0})', counts['rereview']) .format(counts['rereview'])), ('apps', 'updates', 'queue_updates', _('Updates ({0})', counts['updates']).format(counts['updates'])), ] if acl.action_allowed(context['request'], 'Apps', 'ReviewEscalated'): rv.append( ('apps', 'escalated', 'queue_escalated', _('Escalations ({0})', counts['escalated']).format(counts['escalated'])) ) rv.append( ('apps', 'moderated', 'queue_moderated', _('Moderated Reviews ({0})', counts['moderated']).format(counts['moderated'])), ) else: rv = [] # Themes. if (acl.action_allowed(context['request'], 'Personas', 'Review') and waffle.switch_is_active('mkt-themes')): rv.append( ('themes', 'themes', 'queue_themes', _('Themes ({0})', counts['themes']).format(counts['themes'])), ) return rv @register.function @jinja2.contextfunction def logs_tabnav(context): """ Returns tuple of tab navigation for the log pages. Each tuple contains two elements: (page_url, tab_text) """ rv = [] # Apps. if acl.action_allowed(context['request'], 'Apps', 'Review'): rv.append(('reviewers.apps.logs', _('Apps'))) # Themes. if (acl.action_allowed(context['request'], 'Personas', 'Review') and waffle.switch_is_active('mkt-themes')): rv.append(('reviewers.themes.logs', _('Themes'))) return rv @register.function @jinja2.contextfunction def sort_link(context, pretty_name, sort_field): """Get table header sort links. pretty_name -- name displayed on table header sort_field -- name of get parameter, referenced to in views """ request = context['request'] sort, order = clean_sort_param(request) # Copy search/filter GET parameters. get_params = [(k, smart_str(v)) for k, v in request.GET.items() if k not in ('sort', 'order')] return create_sort_link(pretty_name, sort_field, get_params, sort, order)
seakers/daphne-brain
EDL/migrations/0004_edlcontextscorecards_current_corr_mat_status.py
# Generated by Django 2.1.12 on 2019-10-21 19:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('EDL', '0003_edlcontextscorecards_current_corr_mat_df'), ] operations = [ migrations.AddField( model_name='edlcontextscorecards', name='current_corr_mat_status', field=models.CharField(default='', max_length=255), ), ]
oyarzun/incubator-netbeans
java/java.disco/src/org/netbeans/modules/java/disco/AdvancedPanel.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.netbeans.modules.java.disco; import eu.hansolo.jdktools.Latest; import eu.hansolo.jdktools.PackageType; import eu.hansolo.jdktools.TermOfSupport; import io.foojay.api.discoclient.pkg.Distribution; import io.foojay.api.discoclient.pkg.Pkg; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.table.TableModel; import org.checkerframework.checker.guieffect.qual.UIEffect; import org.checkerframework.checker.nullness.qual.Nullable; public abstract class AdvancedPanel extends javax.swing.JPanel { protected BundleTableModel tableModel; private final DefaultComboBoxModel<Distribution> distrosModel; public AdvancedPanel() { distrosModel = new DefaultComboBoxModel<>(); initComponents(); distributionComboBox.setRenderer(new DistributionListCellRenderer()); versionComboBox.setRenderer(new VersionListCellRenderer()); packageTypeComboBox.setRenderer(new PackageTypeListCellRenderer()); } @UIEffect public @Nullable Pkg getSelectedPackage() { int index = table.getSelectedRow(); if (index < 0) { return null; } int modelIndex = table.convertRowIndexToModel(index); Pkg bundle = tableModel.getBundles().get(modelIndex); return bundle; } private TableModel createTableModel() { if (tableModel == null) { tableModel = new BundleTableModel(new ArrayList<>()); } return tableModel; } @UIEffect protected abstract void updateData(Distribution distribution, Integer featureVersion, Latest latest, PackageType bundleType); protected void updateDistributions(List<Distribution> distros) { distrosModel.removeAllElements(); distros.stream() .sorted((o1, o2) -> o1.getUiString().compareTo(o2.getUiString())) .forEachOrdered(distrosModel::addElement); Client.getInstance().getDistribution( DiscoPlatformInstall.defaultDistribution()) .filter(distros::contains) .ifPresent(distrosModel::setSelectedItem); } protected void setVersions(List<Integer> versions, Map<Integer, TermOfSupport> lts) { List<Integer> reversedVersions = new ArrayList<>(versions); Collections.sort(reversedVersions, Collections.reverseOrder()); ((VersionListCellRenderer) versionComboBox.getRenderer()).setLTS(lts); DefaultComboBoxModel versionModel = (DefaultComboBoxModel<Integer>) versionComboBox.getModel(); reversedVersions.forEach(v -> versionModel.addElement(v)); versionModel.setSelectedItem(LTSes.latest(lts)); } private ComboBoxModel<Integer> createVersionComboboxModel() { return new DefaultComboBoxModel<>(); } private ComboBoxModel<Distribution> createDistributionComboboxModel() { return distrosModel; } private ComboBoxModel<PackageType> createPackageTypeComboboxModel() { PackageType[] bundleTypes = Arrays.stream(PackageType.values()).filter(bundleType -> PackageType.NONE != bundleType).filter(bundleType -> PackageType.NOT_FOUND != bundleType).toArray(PackageType[]::new); return new DefaultComboBoxModel<>(bundleTypes); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { javax.swing.JPanel jPanel1 = new javax.swing.JPanel(); javax.swing.JPanel jPanel4 = new javax.swing.JPanel(); javax.swing.JLabel jLabel1 = new javax.swing.JLabel(); distributionComboBox = new javax.swing.JComboBox<>(); javax.swing.JPanel jPanel5 = new javax.swing.JPanel(); javax.swing.JLabel jLabel2 = new javax.swing.JLabel(); versionComboBox = new javax.swing.JComboBox<>(); javax.swing.JPanel jPanel3 = new javax.swing.JPanel(); javax.swing.JLabel jLabel3 = new javax.swing.JLabel(); packageTypeComboBox = new javax.swing.JComboBox<>(); javax.swing.JPanel jPanel2 = new javax.swing.JPanel(); javax.swing.JLabel jLabel4 = new javax.swing.JLabel(); latestCheckBox = new javax.swing.JCheckBox(); jScrollPane1 = new javax.swing.JScrollPane(); table = new javax.swing.JTable(); setLayout(new java.awt.BorderLayout()); jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.LINE_AXIS)); jPanel4.setLayout(new javax.swing.BoxLayout(jPanel4, javax.swing.BoxLayout.Y_AXIS)); org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(AdvancedPanel.class, "AdvancedPanel.jLabel1.text")); // NOI18N jPanel4.add(jLabel1); distributionComboBox.setModel(createDistributionComboboxModel()); distributionComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { distributionComboBoxActionPerformed(evt); } }); jPanel4.add(distributionComboBox); jPanel1.add(jPanel4); jPanel5.setLayout(new javax.swing.BoxLayout(jPanel5, javax.swing.BoxLayout.Y_AXIS)); org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(AdvancedPanel.class, "AdvancedPanel.jLabel2.text")); // NOI18N jPanel5.add(jLabel2); versionComboBox.setModel(createVersionComboboxModel()); versionComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { versionComboBoxActionPerformed(evt); } }); jPanel5.add(versionComboBox); jPanel1.add(jPanel5); jPanel3.setLayout(new javax.swing.BoxLayout(jPanel3, javax.swing.BoxLayout.Y_AXIS)); org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(AdvancedPanel.class, "AdvancedPanel.jLabel3.text")); // NOI18N jPanel3.add(jLabel3); packageTypeComboBox.setModel(createPackageTypeComboboxModel()); packageTypeComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { packageTypeComboBoxActionPerformed(evt); } }); jPanel3.add(packageTypeComboBox); jPanel1.add(jPanel3); jPanel2.setLayout(new javax.swing.BoxLayout(jPanel2, javax.swing.BoxLayout.Y_AXIS)); org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(AdvancedPanel.class, "AdvancedPanel.jLabel4.text")); // NOI18N jPanel2.add(jLabel4); latestCheckBox.setSelected(true); org.openide.awt.Mnemonics.setLocalizedText(latestCheckBox, org.openide.util.NbBundle.getMessage(AdvancedPanel.class, "AdvancedPanel.latestCheckBox.text")); // NOI18N latestCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { latestCheckBoxActionPerformed(evt); } }); jPanel2.add(latestCheckBox); jPanel1.add(jPanel2); add(jPanel1, java.awt.BorderLayout.CENTER); table.setAutoCreateRowSorter(true); table.setModel(createTableModel()); table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane1.setViewportView(table); add(jScrollPane1, java.awt.BorderLayout.PAGE_END); }// </editor-fold>//GEN-END:initComponents private void latestCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_latestCheckBoxActionPerformed updateData((Distribution) distributionComboBox.getSelectedItem(), (Integer) versionComboBox.getSelectedItem(), latestCheckBox.isSelected() ? Latest.OVERALL : Latest.NONE, (PackageType) packageTypeComboBox.getSelectedItem()); }//GEN-LAST:event_latestCheckBoxActionPerformed private void distributionComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_distributionComboBoxActionPerformed updateData((Distribution) distributionComboBox.getSelectedItem(), (Integer) versionComboBox.getSelectedItem(), latestCheckBox.isSelected() ? Latest.OVERALL : Latest.NONE, (PackageType) packageTypeComboBox.getSelectedItem()); }//GEN-LAST:event_distributionComboBoxActionPerformed private void versionComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_versionComboBoxActionPerformed updateData((Distribution) distributionComboBox.getSelectedItem(), (Integer) versionComboBox.getSelectedItem(), latestCheckBox.isSelected() ? Latest.OVERALL : Latest.NONE, (PackageType) packageTypeComboBox.getSelectedItem()); }//GEN-LAST:event_versionComboBoxActionPerformed private void packageTypeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_packageTypeComboBoxActionPerformed updateData((Distribution) distributionComboBox.getSelectedItem(), (Integer) versionComboBox.getSelectedItem(), latestCheckBox.isSelected() ? Latest.OVERALL : Latest.NONE, (PackageType) packageTypeComboBox.getSelectedItem()); }//GEN-LAST:event_packageTypeComboBoxActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox<Distribution> distributionComboBox; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JCheckBox latestCheckBox; private javax.swing.JComboBox<PackageType> packageTypeComboBox; protected javax.swing.JTable table; private javax.swing.JComboBox<Integer> versionComboBox; // End of variables declaration//GEN-END:variables }
alexmadeira/mark-ix
src/store/modules/rootSaga.js
import { all } from 'redux-saga/effects'; import banner from './banner/sagas'; import project from './project/sagas'; import projects from './projects/sagas'; export default function* rootSaga() { yield all([banner, projects, project]); }
scala-steward/ReactiveMongo
driver/src/main/scala/core/protocol/RequestMaker.scala
package reactivemongo.core.protocol import reactivemongo.io.netty.channel.ChannelId import reactivemongo.core.netty.BufferSequence import reactivemongo.api.ReadPreference import reactivemongo.api.commands.CommandKind /** * A helper to build requests. * * @param kind the kind of command to be requested * @param op the write operation * @param documents body of this request * @param channelIdHint a hint for sending this request on a particular channel */ private[reactivemongo] final class RequestMaker( kind: CommandKind, val op: RequestOp, val documents: BufferSequence, val readPreference: ReadPreference, val channelIdHint: Option[ChannelId], parentSTE: Seq[StackTraceElement]) { private val callerSTE: Seq[StackTraceElement] = { val current = Seq.newBuilder[StackTraceElement] current ++= reactivemongo.util.Trace. currentTraceElements.drop(3).dropRight(6) if (parentSTE.nonEmpty) { current += new StackTraceElement("---", "---", "---", -1) current ++= parentSTE } current.result() } @inline def apply(requestID: Int): Request = Request(kind, requestID, 0, op, documents, readPreference, channelIdHint, callerSTE) } private[reactivemongo] object RequestMaker { def apply( kind: CommandKind, op: RequestOp, documents: BufferSequence = BufferSequence.empty, readPreference: ReadPreference = ReadPreference.primary, channelIdHint: Option[ChannelId] = None, callerSTE: Seq[StackTraceElement] = Seq.empty): RequestMaker = new RequestMaker( kind, op, documents, readPreference, channelIdHint, callerSTE) def unapply(maker: RequestMaker): Option[(RequestOp, BufferSequence, ReadPreference, Option[ChannelId])] = Some((maker.op, maker.documents, maker.readPreference, maker.channelIdHint)) }
AskRajeshRaccha/tessera
tessera-partyinfo/src/test/java/com/quorum/tessera/discovery/internal/NetworkStoreProviderTest.java
package com.quorum.tessera.discovery.internal; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; public class NetworkStoreProviderTest { @Test public void defaultConstructorForCoverage() { assertThat(new NetworkStoreProvider()).isNotNull(); } @Test public void provider() { assertThat(NetworkStoreProvider.provider()) .isNotNull() .isExactlyInstanceOf(DefaultNetworkStore.class); } }
jefftc/changlab
Betsy/Betsy/modules/backfill_vcf_folder.py
<reponame>jefftc/changlab from Module import AbstractModule class Module(AbstractModule): def __init__(self): AbstractModule.__init__(self) def run( self, network, antecedents, out_attributes, user_options, num_cores, out_path): import os from genomicode import filelib from genomicode import parselib from genomicode import parallel from Betsy import module_utils as mlib in_vcf_node, bf_vcf_node = antecedents in_vcf_filenames = filelib.list_files_in_path( in_vcf_node.identifier, endswith=".vcf", toplevel_only=True) bf_vcf_filenames = filelib.list_files_in_path( bf_vcf_node.identifier, endswith=".vcf", toplevel_only=True) filelib.safe_mkdir(out_path) metadata = {} common_only = mlib.get_user_option( user_options, "backfill_common_only", allowed_values=["no", "yes"], not_empty=True) in_vcf_samples = [mlib.splitpath(x)[1] for x in in_vcf_filenames] bf_vcf_samples = [mlib.splitpath(x)[1] for x in bf_vcf_filenames] # Make sure there are no duplicate sample names. x1 = {}.fromkeys(in_vcf_samples).keys() x2 = {}.fromkeys(bf_vcf_samples).keys() assert len(in_vcf_samples) == len(x1), "Duplicate samples" assert len(bf_vcf_samples) == len(x2), "Duplicate samples" # Find the samples. common = [x for x in in_vcf_samples if x in bf_vcf_samples] in_only = [x for x in in_vcf_samples if x not in common] bf_only = [x for x in bf_vcf_samples if x not in common] assert common, "No common samples." pretty_in = parselib.pretty_list(in_only, max_items=5) pretty_bf = parselib.pretty_list(bf_only, max_items=5) if common_only == "no": assert not (in_only and bf_only), \ "Extra samples in both sets:\n%s\n%s" % ( pretty_in, pretty_bf) assert not in_only, "Target VCF file has extra samples: %s" % \ pretty_in assert not bf_only, "Source VCF file has extra samples: %s." % \ pretty_bf SAMPLES = common # list of sample, in_vcf_filename, bf_vcf_filename, out_filename jobs = [] for sample in SAMPLES: assert sample in in_vcf_samples assert sample in bf_vcf_samples i = in_vcf_samples.index(sample) j = bf_vcf_samples.index(sample) in_filename = in_vcf_filenames[i] bf_filename = bf_vcf_filenames[j] out_filename = os.path.join(out_path, "%s.vcf" % sample) x = sample, in_filename, bf_filename, out_filename jobs.append(x) jobs2 = [] for x in jobs: sample, in_filename, bf_filename, out_filename = x fn = backfill_vcf args = in_filename, bf_filename, out_filename keywds = {} jobs2.append((fn, args, keywds)) #num_cores = 1 parallel.pyfun(jobs2, num_procs=num_cores) metadata["num_cores"] = num_cores return metadata def name_outfile(self, antecedents, user_options): return "backfilled.vcf" def backfill_vcf(in_file, bf_file, out_file): import copy from genomicode import vcflib #print in_mvcf_node.identifier #print back_mvcf_node.identifier in_vcf = vcflib.read(in_file) bf_vcf = vcflib.read(bf_file) # May have multiple samples, e.g. germline and tumor. #assert len(in_vcf.samples) == 1, "Too many samples: %s" % in_vcf.samples x = [x for x in in_vcf.samples if x in bf_vcf.samples] SAMPLES = x # Parse out the read counts from the backfill vcf. bf_variants = {} # (sample, chrom, pos) -> ref, alt, Variant, Call for i in range(bf_vcf.num_variants()): var = vcflib.get_variant(bf_vcf, i) for sample in SAMPLES: call = vcflib.get_call(var, sample) if call.num_ref is None and call.num_alt is None and \ call.total_reads is None and call.vaf is None: continue x = sample, var.chrom, var.pos assert x not in bf_variants, "Duplicate: %s %s %s" % x bf_variants[x] = var.ref, var.alt, var, call # Find the variants that can be backfilled. # List of (chrom, pos, in_var_num, sample, in_call, bf_var, bf_call) matches = [] for i in range(in_vcf.num_variants()): in_var = vcflib.get_variant(in_vcf, i) for sample in SAMPLES: # Skip if there is no backfill information. key = sample, in_var.chrom, in_var.pos if key not in bf_variants: continue bf_ref, bf_alt, bf_var, bf_call = bf_variants[key] # Don't worry if the variants match. Just want a # rough estimate of the coverage at this location. ## Make sure the variants match. ##if not is_same_variants(ref, alt, bf_ref, bf_alt): ## continue in_call = vcflib.get_call(in_var, sample) x = in_var.chrom, in_var.pos, i, sample, in_call, bf_var, bf_call matches.append(x) # Update the read counts from annotated VCF file. out_vcf = copy.deepcopy(in_vcf) add_backfill_genotypes(out_vcf) seen = {} for x in matches: chrom, pos, var_num, sample, in_call, bf_var, bf_call = x seen[(sample, chrom, pos)] = 1 var = vcflib.get_variant(out_vcf, var_num) GD = var.sample2genodict[sample] mapping = [ ("BFILL_REF", "num_ref"), ("BFILL_ALT", "num_alt"), ("BFILL_COV", "total_reads"), ("BFILL_VAF", "vaf"), ] changed = False for gt_key, call_attr in mapping: x = getattr(bf_call, call_attr) if x is None: continue if type(x) is type([]): # arbitrarily use max x = max(x) GD[gt_key] = vcflib._format_vcf_value(x) changed = True if changed: vcflib.set_variant(out_vcf, var_num, var) # Add the variants that are in bf_file, but not in in_file. for x in bf_variants: # sample, chrom, pos = x if x in seen: continue bf_ref, bf_alt, bf_var, bf_call = bf_variants[x] # VarScan sets the filter_ to "PASS" for everything. Get rid # of this. bf_var.filter_ = ["BACKFILL"] vcflib.add_variant(out_vcf, bf_var) vcflib.write(out_file, out_vcf) def add_backfill_genotypes(vcf): # Will add genotype columns for backfill in place. from genomicode import vcflib # FORMAT GT:GQ:SDP:DP:RD:AD:FREQ:PVAL:RBQ:ABQ:RDF:RDR:ADF:ADR # <genotype> 0/1:12:28:28:24:4:14.29%:5.5746E-2:37:36:14:10:3:1 # Columns to add. COLUMNS = ["BFILL_REF", "BFILL_ALT", "BFILL_COV", "BFILL_VAF"] for i in range(vcf.num_variants()): var = vcflib.get_variant(vcf, i) changed = False for col in COLUMNS: if col not in var.genotype_names: var.genotype_names.append(col) changed = True for genodict in var.sample2genodict.itervalues(): if col in genodict: continue genodict[col] = "." changed = True if changed: vcflib.set_variant(vcf, i, var) def is_same_variants(ref1, alt1, ref2, alt2): alphabet = "ACGT" # One of them is mutation, the other is deletion. # SEQ1 A G # SEQ2 A . if ref1 == ref2 and alt1 in alphabet and alt2 == ".": return False if ref1 == ref2 and alt2 in alphabet and alt1 == ".": return False # One of them has more alleles than the other. # SEQ1 A G # SEQ2 A G,T alts1 = sorted(alt1.split(",")) alts2 = sorted(alt2.split(",")) num_alts_1 = len(alts1) num_alts_2 = len(alts2) if ref1 == ref2 and num_alts_1 != num_alts_2: return False # One of them has different alt alleles than the other. # SEQ1 C G,A # SEQ2 C G,T if ref1 == ref2 and alts1 != alts2: return False # Something weird going on. # SEQ1 GC G # SEQ2 G . if ref1 != ref2 and alt1 != alt2: return False return True
425868130/Spring-Cloud-Demo
auth-center/src/main/java/com/example/authcenter/dao/SysAuthProfileDao.java
<gh_stars>0 package com.example.authcenter.dao; import com.example.authcenter.entity.SysAuthProfile; public interface SysAuthProfileDao { int deleteByPrimaryKey(String uid); int insert(SysAuthProfile record); int insertSelective(SysAuthProfile record); SysAuthProfile selectByPrimaryKey(String uid); int updateByPrimaryKeySelective(SysAuthProfile record); int updateByPrimaryKey(SysAuthProfile record); }
huifer/Happy-Java
happy-common/happy-common-entity/src/main/java/com/huifer/happy/common/entity/bo/FileMetaBO.java
<reponame>huifer/Happy-Java package com.huifer.happy.common.entity.bo; import lombok.Data; import java.util.List; @Data public class FileMetaBO { private String groupName; private String remoteFilename; private String storageServersCount; private List<String> ipPorts; private String url; }
huchao-github/CCKit
CCKit/CCTextActionLabel.h
<gh_stars>0 // // CCTextActionLabel.h // CCKit // // Created by 胡超 on 2018/6/28. // Copyright © 2018年 胡超., ltd. All rights reserved. // #import <UIKit/UIKit.h> @interface CCTextActionLabel : UIView @property(nonatomic,strong) UIFont * font; @property(nonatomic,assign) NSTextAlignment textAlignment; /** 添加普通文字*/ @property (nonatomic,readonly) void (^appendNormalText)(NSString *text, UIColor *textColor); /** 添加点击文字*/ @property (nonatomic,readonly) void (^appendActionText)(NSString *text, UIColor *textColor, void(^tapAction)(void)); @end
jpisaac/phoenix
phoenix-core/src/main/java/org/apache/phoenix/expression/function/RegexpReplaceFunction.java
<filename>phoenix-core/src/main/java/org/apache/phoenix/expression/function/RegexpReplaceFunction.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.phoenix.expression.function; import java.io.DataInput; import java.io.IOException; import java.util.List; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.phoenix.expression.Determinism; import org.apache.phoenix.expression.Expression; import org.apache.phoenix.expression.util.regex.AbstractBasePattern; import org.apache.phoenix.parse.FunctionParseNode; import org.apache.phoenix.parse.FunctionParseNode.Argument; import org.apache.phoenix.parse.FunctionParseNode.BuiltInFunction; import org.apache.phoenix.parse.RegexpReplaceParseNode; import org.apache.phoenix.schema.SortOrder; import org.apache.phoenix.schema.tuple.Tuple; import org.apache.phoenix.schema.types.PDataType; import org.apache.phoenix.schema.types.PVarchar; /** * * Function similar to the regexp_replace function in Postgres, which is used to pattern * match a segment of the string. Usage: * {@code REGEXP_REPLACE(<source_char>,<pattern>,<replace_string>) } * source_char is the string in which we want to perform string replacement. pattern is a * Java compatible regular expression string, and we replace all the matching part with * replace_string. The first 2 arguments are required and are {@link org.apache.phoenix.schema.types.PVarchar}, * the replace_string is default to empty string. * * The function returns a {@link org.apache.phoenix.schema.types.PVarchar} * * * @since 0.1 */ @BuiltInFunction(name=RegexpReplaceFunction.NAME, nodeClass = RegexpReplaceParseNode.class, args= { @Argument(allowedTypes={PVarchar.class}), @Argument(allowedTypes={PVarchar.class}), @Argument(allowedTypes={PVarchar.class},defaultValue="null")}, classType = FunctionParseNode.FunctionClassType.ABSTRACT, derivedFunctions = {ByteBasedRegexpReplaceFunction.class, StringBasedRegexpReplaceFunction.class}) public abstract class RegexpReplaceFunction extends ScalarFunction { public static final String NAME = "REGEXP_REPLACE"; private static final PVarchar TYPE = PVarchar.INSTANCE; private byte [] rStrBytes; private int rStrOffset, rStrLen; private AbstractBasePattern pattern; public RegexpReplaceFunction() { } // Expect 1 arguments, the pattern. public RegexpReplaceFunction(List<Expression> children) { super(children); init(); } protected abstract AbstractBasePattern compilePatternSpec(String value); private void init() { ImmutableBytesWritable tmpPtr = new ImmutableBytesWritable(); Expression e = getPatternStrExpression(); if (e.isStateless() && e.getDeterminism() == Determinism.ALWAYS && e.evaluate(null, tmpPtr)) { String patternStr = (String) TYPE.toObject(tmpPtr, e.getDataType(), e.getSortOrder()); if (patternStr != null) pattern = compilePatternSpec(patternStr); } e = getReplaceStrExpression(); if (e.isStateless() && e.getDeterminism() == Determinism.ALWAYS && e.evaluate(null, tmpPtr)) { TYPE.coerceBytes(tmpPtr, TYPE, e.getSortOrder(), SortOrder.ASC); rStrBytes = tmpPtr.get(); rStrOffset = tmpPtr.getOffset(); rStrLen = tmpPtr.getLength(); } else { rStrBytes = null; } } @Override public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { AbstractBasePattern pattern = this.pattern; if (pattern == null) { Expression e = getPatternStrExpression(); if (!e.evaluate(tuple, ptr)) { return false; } if (ptr.getLength()==0) { return true; } String patternStr = (String) TYPE.toObject(ptr, e.getDataType(), e.getSortOrder()); if (patternStr == null) { return false; } else { pattern = compilePatternSpec(patternStr); } } byte[] rStrBytes = this.rStrBytes; int rStrOffset = this.rStrOffset, rStrLen = this.rStrLen; if (rStrBytes == null) { Expression replaceStrExpression = getReplaceStrExpression(); if (!replaceStrExpression.evaluate(tuple, ptr)) { return false; } if (ptr.getLength()==0) { return true; } TYPE.coerceBytes(ptr, TYPE, replaceStrExpression.getSortOrder(), SortOrder.ASC); rStrBytes = ptr.get(); rStrOffset = ptr.getOffset(); rStrLen = ptr.getLength(); } Expression sourceStrExpression = getSourceStrExpression(); if (!sourceStrExpression.evaluate(tuple, ptr)) { return false; } if (ptr.getLength()==0) { return true; } TYPE.coerceBytes(ptr, TYPE, sourceStrExpression.getSortOrder(), SortOrder.ASC); pattern.replaceAll(ptr, rStrBytes, rStrOffset, rStrLen); return true; } private Expression getSourceStrExpression() { return children.get(0); } private Expression getPatternStrExpression() { return children.get(1); } private Expression getReplaceStrExpression() { return children.get(2); } @Override public PDataType getDataType() { return PVarchar.INSTANCE; } @Override public void readFields(DataInput input) throws IOException { super.readFields(input); init(); } @Override public String getName() { return NAME; } }
282951387/KFrame
KFPlugin/KFIpAddress/KFIpAddressInterface.h
#ifndef __KF_IP_ADDRESS_INTERFACE_H__ #define __KF_IP_ADDRESS_INTERFACE_H__ #include "KFrame.h" namespace KFrame { ///////////////////////////////////////////////////////////////////////////////////////////// class KFIpAddressInterface : public KFModule { public: ///////////////////////////////////////////////////////////////////////// // 获得本机局域网ip virtual const std::string& GetLocalIp() = 0; // 获得本机外网ip virtual const std::string& GetInteranetIp() = 0; // 计算监听端口 virtual uint32 CalcListenPort( uint32 type, uint32 port, uint64 appid ) = 0; ///////////////////////////////////////////////////////////////////////// // 获得log地址 virtual const std::string& GetLogUrl() = 0; // 获得auth地址 virtual const std::string& GetAuthUrl() = 0; // 获得dir地址 virtual const std::string& GetDirUrl() = 0; // 获得pay地址 virtual const std::string& GetPayUrl() = 0; // 获得master ip virtual const KFIpAddress* GetMasterIp( const std::string& appname, uint32 zoneid ) = 0; // 查询master列表 virtual const std::list< KFIpAddress >& GetMasterList( const std::string& appname, uint32 zoneid ) = 0; }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////// __KF_INTERFACE__( _kf_ip_address, KFIpAddressInterface ); //////////////////////////////////////////////////////////////////////////////////////////////////////////////// } #endif
ScalablyTyped/SlinkyTyped
r/react-bootstrap-table/src/main/scala/typingsSlinky/reactBootstrapTable/mod/SizePerPageDropDownProps.scala
package typingsSlinky.reactBootstrapTable.mod import typingsSlinky.reactBootstrapTable.anon.Text import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait SizePerPageDropDownProps extends StObject { /** * Bootstrap css style class for the button, e.g. 'btn-warning' */ var btnContextual: js.UndefOr[String] = js.native /** * Custom class name to use for the component. */ var className: js.UndefOr[String] = js.native /** * Current size per page */ var currSizePerPage: js.UndefOr[String] = js.native /** * Flag to indicate that the dropdown is currently hidden */ var hidden: js.UndefOr[Boolean] = js.native /** * Callback function that should be triggered when the user clicks on the dropdown button. */ var onClick: js.UndefOr[js.Function1[/* toggleDropDown */ js.Function0[Unit], Unit]] = js.native /** * Flag to indicate that the dropdown is open */ var open: js.UndefOr[Boolean] = js.native /** * Size Per Page options list */ var options: js.UndefOr[js.Array[Double | Text]] = js.native /** * Whether the button menu should 'dropup' or 'dropdown'. */ var variation: js.UndefOr[DropDirection] = js.native } object SizePerPageDropDownProps { @scala.inline def apply(): SizePerPageDropDownProps = { val __obj = js.Dynamic.literal() __obj.asInstanceOf[SizePerPageDropDownProps] } @scala.inline implicit class SizePerPageDropDownPropsMutableBuilder[Self <: SizePerPageDropDownProps] (val x: Self) extends AnyVal { @scala.inline def setBtnContextual(value: String): Self = StObject.set(x, "btnContextual", value.asInstanceOf[js.Any]) @scala.inline def setBtnContextualUndefined: Self = StObject.set(x, "btnContextual", js.undefined) @scala.inline def setClassName(value: String): Self = StObject.set(x, "className", value.asInstanceOf[js.Any]) @scala.inline def setClassNameUndefined: Self = StObject.set(x, "className", js.undefined) @scala.inline def setCurrSizePerPage(value: String): Self = StObject.set(x, "currSizePerPage", value.asInstanceOf[js.Any]) @scala.inline def setCurrSizePerPageUndefined: Self = StObject.set(x, "currSizePerPage", js.undefined) @scala.inline def setHidden(value: Boolean): Self = StObject.set(x, "hidden", value.asInstanceOf[js.Any]) @scala.inline def setHiddenUndefined: Self = StObject.set(x, "hidden", js.undefined) @scala.inline def setOnClick(value: /* toggleDropDown */ js.Function0[Unit] => Unit): Self = StObject.set(x, "onClick", js.Any.fromFunction1(value)) @scala.inline def setOnClickUndefined: Self = StObject.set(x, "onClick", js.undefined) @scala.inline def setOpen(value: Boolean): Self = StObject.set(x, "open", value.asInstanceOf[js.Any]) @scala.inline def setOpenUndefined: Self = StObject.set(x, "open", js.undefined) @scala.inline def setOptions(value: js.Array[Double | Text]): Self = StObject.set(x, "options", value.asInstanceOf[js.Any]) @scala.inline def setOptionsUndefined: Self = StObject.set(x, "options", js.undefined) @scala.inline def setOptionsVarargs(value: (Double | Text)*): Self = StObject.set(x, "options", js.Array(value :_*)) @scala.inline def setVariation(value: DropDirection): Self = StObject.set(x, "variation", value.asInstanceOf[js.Any]) @scala.inline def setVariationUndefined: Self = StObject.set(x, "variation", js.undefined) } }
JonasAraujoP/Python
desafios/desafio20.py
<filename>desafios/desafio20.py #CÓDIGO SORTEIA UM ALUNO APENAS from random import shuffle a = str(input('1° aluno: ')).upper().strip() b = str(input('2° alino: ')).upper().strip() c = str(input('3° aluno: ')).upper().strip() d = str(input('4° aluno: ')).upper().strip() lista = [a,b,c,d] shuffle(lista) print(lista)
turesnake/leetPractice
src/_leetcode/leet_980.cpp
<reponame>turesnake/leetPractice /* * ====================== leet_980.cpp ========================== * -- tpr -- * CREATE -- 2020.06.09 * MODIFY -- * ---------------------------------------------------------- * 980. 不同路径 III */ #include "innLeet.h" #include "TreeNode1.h" #include "ListNode.h" namespace leet_980 {//~ // dfs 回溯 77%, 100% class S{ std::vector<std::vector<int>> *gridp {}; int H {}; int W {}; int roadNum {0}; int targetDeep {}; const std::vector<std::pair<int,int>> nearOffs { {-1,0},{1,0},{0,-1},{0,1} }; // dfs // [h][w] 可能是无效的,要检测 void walk( int h, int w, int deep ){ int mapVal = gridp->at(h).at(w); if( mapVal == 2 ){ // 只有彻底遍历的,才被统计 if( deep==targetDeep ){ roadNum++; } return; } gridp->at(h).at(w) = -2;//表示 本格 已经走过了 for( const auto &[offW,offH] : nearOffs ){ int newW = w + offW; int newH = h + offH; if( newW<0 || newW>=W || newH<0 || newH>=H ){ continue; } if( gridp->at(newH).at(newW)<0 ){ continue; }// 直接不走无效路 walk( newH, newW, deep+1 ); } gridp->at(h).at(w) = 0; } public: // 1 <= len * [0].len <= 20 // == 1 起点 // == 2 终点 // == 0 可行走 // == -1 法定障碍 // == -2 自设障碍 int uniquePathsIII( std::vector<std::vector<int>>& grid ){ H = static_cast<int>(grid.size()); W = static_cast<int>(grid.at(0).size()); if( H==1 && W==1 ){ return 0; } gridp = &grid; // 找到 起点 int begW = 0; int begH = 0; int negNum = 0; // -1 个数 bool isFind = false; for( int h=0; h<H; h++ ){ for( int w=0; w<W; w++ ){ int v = grid.at(h).at(w); if( v==1 ){ isFind = true; begW = w; begH = h; }else if( v==-1 ){ negNum++; } } } if( !isFind ){ return false; } targetDeep = W*H - negNum; //cout<<"begW:"<<begW<<" begH:"<<begH<<endl; walk( begH, begW, 1 ); return roadNum; } }; //=========================================================// void main_(){ std::vector<std::vector<int>> v { {1,0,0,0}, {0,0,0,0}, {0,0,0,2} }; cout<<"ret:"<<S{}.uniquePathsIII(v)<<endl; debug::log( "\n~~~~ leet: 980 :end ~~~~\n" ); } }//~
BBN-E/LearnIt
neolearnit/src/main/java/com/bbn/akbc/neolearnit/observations/feature/AbstractRelationFeature.java
<filename>neolearnit/src/main/java/com/bbn/akbc/neolearnit/observations/feature/AbstractRelationFeature.java package com.bbn.akbc.neolearnit.observations.feature; import com.bbn.akbc.neolearnit.observations.LearnItObservation; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * Created by bmin on 6/6/15. */ @JsonIgnoreProperties(ignoreUnknown=true) public abstract class AbstractRelationFeature extends LearnItObservation { @Override public abstract String toPrettyString(); public abstract String toIDString(); }
pearpai/TensorFlow-action
action/demo1/get_captcha.py
<filename>action/demo1/get_captcha.py<gh_stars>1-10 import urllib2 url = 'http://localhost:8080/getVerifyImage' request = urllib2.Request(url) html = urllib2.urlopen(request).read() count = 0 while count < 10000: print 'The count is:', count request = urllib2.Request(url) _html = urllib2.urlopen(request).read() count += 1
TwoFistedJustice/square-pie
tests/utility_shazam_type_checkers.test.js
<gh_stars>0 "use strict"; const { shazam_is_integer, shazam_is_boolean, shazam_is_array, } = require("../src/lib/utilities"); /* --------------------------------------------------------* * * * shazam_is_integer * * * ------------------------------------------------------- */ describe("shazam_is_integer integer verification utility", () => { test("should throw on a non-integer string", () => { expect(() => { shazam_is_integer("95.5", "utilities test suite", "should throw"); }).toThrow(); expect(() => { shazam_is_integer(95.5, "utilities test suite", "should throw"); }).toThrow(); }); test("should throw correct error message on a number that is not an integer", () => { let expected = "describe.test expects an integer or a string that can be coerced to an integer. Received: 95.5"; expect(() => { shazam_is_integer("95.5", "describe", "test"); }).toThrowError(new TypeError(expected)); expect(() => { shazam_is_integer(95.5, "describe", "test"); }).toThrowError(new TypeError(expected)); }); test("should throw correct error message on a string that does not coercible to a number", () => { let expected = "describe.test expects an integer or a string that can be coerced to an integer. Received: ABC"; expect(() => { shazam_is_integer("ABC", "describe", "test"); }).toThrowError(new TypeError(expected)); }); test("error should throw with correct defaults when name and caller not provided ", () => { let expected = "unspecified_class.unspecified_setter expects an integer or a string that can be coerced to an integer. Received: ABC"; expect(() => { shazam_is_integer("ABC"); }).toThrowError(new TypeError(expected)); }); test("should accept an integer string", () => { expect(() => { shazam_is_integer("42", "utilities test suite", "should NOT throw"); }).not.toThrow(); expect( shazam_is_integer("42", "utilities test suite", "should return true") ).toEqual(true); }); test("should accept an integer number", () => { let num = 42; expect(() => { shazam_is_integer(num, "utilities test suite", "should NOT throw"); }).not.toThrow(); expect( shazam_is_integer(num, "utilities test suite", "should return true") ).toEqual(true); }); }); /* --------------------------------------------------------* * * * shazam_is_boolean * * * ------------------------------------------------------- */ describe("shazam_is_boolean boolean verification utility", () => { test("should throw when fed a non-boolean", () => { expect(() => { shazam_is_boolean("true", "utilities test suite", "should throw"); }).toThrow(); }); test("should throw when fed a 1 or a 0", () => { expect(() => { shazam_is_boolean(1, "utilities test suite", "should throw"); }).toThrow(); expect(() => { shazam_is_boolean(0, "utilities test suite", "should throw"); }).toThrow(); }); test("should throw when the correct message a non-boolean", () => { let expected = `describe.test expects a boolean. Received: true\nMake sure you didn't pass a string that looks like a boolean.`; expect(() => { shazam_is_boolean("true", "describe", "test"); }).toThrowError(expected); }); test("should NOT throw when fed a boolean", () => { expect(() => { shazam_is_boolean(true, "utilities test suite", "should NOT throw"); }).not.toThrow(); }); test("should return true when fed a boolean", () => { expect( shazam_is_boolean(false, "utilities test suite", "should return true") ).toEqual(true); }); }); /* --------------------------------------------------------* * * * shazam_is_array * * * ------------------------------------------------------- */ describe("shazam_is_array", () => { let emptyArray = []; let goodArray = [1, 2, 3]; let notAnArray = "1,2,3"; test("shazam_is_array to return true when given an array with at least one member", () => { expect(shazam_is_array(goodArray)).toEqual(true); }); test("should throw error message when given an empty array", () => { let expected = "class.method expects an array with at least 1 member but received: empty array : "; expect(() => { shazam_is_array(emptyArray, "class", "method"); }).toThrowError(expected); }); test("should throw correct error message on a non-array", () => { let expected = "unspecified class.unspecified method expects an array with at least 1 member but received: string : 1,2,3"; expect(() => { shazam_is_array(notAnArray); }).toThrowError(expected); }); test("should throw correct error message on a empty-array", () => { let expected = "unspecified class.unspecified method expects an array with at least 1 member but received: empty array"; expect(() => { shazam_is_array([]); }).toThrowError(expected); }); });
karensmolermiller/incubator-geode
gemfire-core/src/main/java/com/gemstone/gemfire/internal/cache/partitioned/DumpB2NRegion.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 com.gemstone.gemfire.internal.cache.partitioned; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.apache.logging.log4j.Logger; import com.gemstone.gemfire.CancelException; import com.gemstone.gemfire.DataSerializer; import com.gemstone.gemfire.cache.CacheException; import com.gemstone.gemfire.cache.RegionDestroyedException; import com.gemstone.gemfire.cache.TimeoutException; import com.gemstone.gemfire.distributed.internal.DM; import com.gemstone.gemfire.distributed.internal.DistributionManager; import com.gemstone.gemfire.distributed.internal.DistributionMessage; import com.gemstone.gemfire.distributed.internal.DistributionStats; import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem; import com.gemstone.gemfire.distributed.internal.ReplyException; import com.gemstone.gemfire.distributed.internal.ReplyMessage; import com.gemstone.gemfire.distributed.internal.ReplyProcessor21; import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember; import com.gemstone.gemfire.internal.Assert; import com.gemstone.gemfire.internal.cache.ForceReattemptException; import com.gemstone.gemfire.internal.cache.PartitionedRegion; import com.gemstone.gemfire.internal.i18n.LocalizedStrings; import com.gemstone.gemfire.internal.logging.LogService; import com.gemstone.gemfire.internal.logging.log4j.LogMarker; /** * A message used for debugging purposes. For example if a test fails it can * call * {@link com.gemstone.gemfire.internal.cache.PartitionedRegion#sendDumpB2NRegionForBucket(int)} * which sends this message to all VMs that have that PartitionedRegion defined. * * @see com.gemstone.gemfire.internal.cache.PartitionedRegion#sendDumpB2NRegionForBucket(int) * @author rreja */ public final class DumpB2NRegion extends PartitionMessage { private static final Logger logger = LogService.getLogger(); private int bucketId; private boolean onlyReturnPrimaryInfo; public DumpB2NRegion() { } private DumpB2NRegion(Set recipients, int regionId, ReplyProcessor21 processor, int bId, boolean justPrimaryInfo) { super(recipients, regionId, processor); this.bucketId = bId; this.onlyReturnPrimaryInfo = justPrimaryInfo; } public static DumpB2NResponse send(Set recipients, PartitionedRegion r, int bId, boolean justPrimaryInfo) { DumpB2NResponse p = new DumpB2NResponse(r.getSystem(), recipients); DumpB2NRegion m = new DumpB2NRegion(recipients, r.getPRId(), p, bId, justPrimaryInfo); r.getDistributionManager().putOutgoing(m); return p; } @Override public void process(final DistributionManager dm) { PartitionedRegion pr = null; // Get the region, or die trying... final long finish = System.currentTimeMillis() + 10 * 1000; try { for (;;) { dm.getCancelCriterion().checkCancelInProgress(null); // pr = null; (redundant assignment) pr = PartitionedRegion.getPRFromId(this.regionId); if (pr != null) { break; } if (System.currentTimeMillis() > finish) { ReplyException rex = new ReplyException( new TimeoutException("Waited too long for region to initialize")); sendReply(getSender(), this.processorId, dm, rex, null, 0); return; } // wait a little boolean interrupted = Thread.interrupted(); try { Thread.sleep(2000); } catch (InterruptedException e) { interrupted = true; pr.checkReadiness(); } finally { if (interrupted) Thread.currentThread().interrupt(); } } // Now, wait for the PR to finish initializing pr.waitForData(); // OK, now it's safe to process this. super.process(dm); } catch (CancelException e) { sendReply(this.sender,this.processorId , dm, new ReplyException(e), pr, 0); } catch (PRLocallyDestroyedException e) { sendReply(this.sender,this.processorId , dm, new ReplyException(e), pr, 0); return; } catch (RegionDestroyedException rde) { sendReply(this.sender,this.processorId , dm, new ReplyException(rde), pr, 0); return; } } @Override protected boolean operateOnPartitionedRegion(DistributionManager dm, PartitionedRegion pr, long startTime) throws CacheException { PrimaryInfo pinfo = null; if (this.onlyReturnPrimaryInfo) { pinfo = new PrimaryInfo(pr.getRegionAdvisor().getBucket(this.bucketId).isHosting(), pr.getRegionAdvisor().isPrimaryForBucket(this.bucketId), ""); } else { pr.dumpB2NForBucket(this.bucketId); } DumpB2NReplyMessage.send(getSender(), getProcessorId(), dm, pinfo); return false; } public int getDSFID() { return PR_DUMP_B2N_REGION_MSG; } @Override public void fromData(DataInput in) throws IOException, ClassNotFoundException { super.fromData(in); this.bucketId = in.readInt(); this.onlyReturnPrimaryInfo = in.readBoolean(); } @Override public void toData(DataOutput out) throws IOException { super.toData(out); out.writeInt(this.bucketId); out.writeBoolean(this.onlyReturnPrimaryInfo); } public static final class DumpB2NReplyMessage extends ReplyMessage { private PrimaryInfo primaryInfo; public DumpB2NReplyMessage() {} private DumpB2NReplyMessage(int procid, PrimaryInfo pinfo) { super(); setProcessorId(procid); this.primaryInfo = pinfo; } public static void send(InternalDistributedMember recipient, int processorId, DM dm, PrimaryInfo pinfo) { DumpB2NReplyMessage m = new DumpB2NReplyMessage(processorId, pinfo); m.setRecipient(recipient); dm.putOutgoing(m); } @Override public void process(final DM dm, final ReplyProcessor21 processor) { final long startTime = getTimestamp(); if (logger.isTraceEnabled(LogMarker.DM)) { logger.trace(LogMarker.DM, "DumpB2NReplyMessage process invoking reply processor with processorId: {}", this.processorId); } if (processor == null) { if (logger.isTraceEnabled(LogMarker.DM)) { logger.trace(LogMarker.DM, "DumpB2NReplyMessage processor not found"); } return; } processor.process(this); if (logger.isTraceEnabled(LogMarker.DM)) { logger.trace(LogMarker.DM, "{} processed {}", processor, this); } dm.getStats().incReplyMessageTime(DistributionStats.getStatTime() - startTime); } public PrimaryInfo getPrimaryInfo() { return this.primaryInfo; } @Override public int getDSFID() { return PR_DUMP_B2N_REPLY_MESSAGE; } @Override public void fromData(DataInput in) throws IOException, ClassNotFoundException { super.fromData(in); this.primaryInfo = (PrimaryInfo) DataSerializer.readObject(in); } @Override public void toData(DataOutput out) throws IOException { super.toData(out); DataSerializer.writeObject(this.primaryInfo, out); } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("DumpB2NReplyMessage "); sb.append(this.processorId); sb.append(" from "); sb.append(this.getSender()); ReplyException ex = this.getException(); if (ex != null) { sb.append(" with exception "); sb.append(ex); } return sb.toString(); } } public static class DumpB2NResponse extends PartitionResponse { public final ArrayList primaryInfos = new ArrayList(); public DumpB2NResponse(InternalDistributedSystem dm, Set initMembers) { super(dm, initMembers); } @Override public void process(DistributionMessage msg) { if (msg instanceof DumpB2NReplyMessage) { DumpB2NReplyMessage reply = (DumpB2NReplyMessage)msg; if (reply.getPrimaryInfo() != null && reply.getPrimaryInfo().isHosting) { Object[] newBucketHost = new Object[] {reply.getSender(), Boolean.valueOf(reply.getPrimaryInfo().isPrimary), reply.getPrimaryInfo().hostToken}; synchronized(this.primaryInfos) { this.primaryInfos.add(newBucketHost); } } if (logger.isTraceEnabled(LogMarker.DM)) { logger.trace(LogMarker.DM, "DumpB2NResponse got a primaryInfo {} from {}", reply.getPrimaryInfo(), reply.getSender()); } } super.process(msg); } public List waitForPrimaryInfos() throws ForceReattemptException { try { waitForCacheException(); } catch (ForceReattemptException e) { logger.debug("B2NResponse got ForceReattemptException; rethrowing {}", e.getMessage(), e); throw e; } catch (CacheException e) { logger.debug("B2NResponse got remote CacheException, throwing ForceReattemptException. {}", e.getMessage(), e); throw new ForceReattemptException(LocalizedStrings.DumpB2NRegion_B2NRESPONSE_GOT_REMOTE_CACHEEXCEPTION_THROWING_FORCEREATTEMPTEXCEPTION.toLocalizedString(), e); } synchronized (this.primaryInfos) { return this.primaryInfos; } } } private static class PrimaryInfo implements Serializable { private static final long serialVersionUID = 6334695270795306178L; public final boolean isHosting, isPrimary; public final String hostToken; PrimaryInfo(boolean isHosting, boolean isPrimary, String hToken) { this.isHosting = isHosting; this.isPrimary = isPrimary; this.hostToken = hToken; if (this.isPrimary) { Assert.assertTrue(this.isHosting); } } } /* (non-Javadoc) * @see com.gemstone.gemfire.internal.cache.partitioned.PartitionMessage#appendFields(java.lang.StringBuffer) */ @Override protected void appendFields(StringBuffer buff) { super.appendFields(buff); buff.append(" bucketId=").append(this.bucketId) .append(" primaryInfoOnly=").append(this.onlyReturnPrimaryInfo); } /* (non-Javadoc) * @see java.lang.Object#clone() */ @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub return super.clone(); } }
dongyang1993/springboot-learning-example
springboot-security/springboot-security-learn05/src/main/java/org.springboot/security/repository/UserRepository.java
package org.springboot.security.repository; import org.springboot.security.entity.MineUser; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository<MineUser, Long> { MineUser findByUsername(String name); }
ColaMachine/MyBlock
src/main/java/cola/machine/game/myblocks/skill/SkillEntity.java
package cola.machine.game.myblocks.skill; /** * Created by luying on 16/9/25. */ public class SkillEntity { }
r-barnes/sw_comparison
implementations/ugene/src/plugins/GUITestBase/src/tests/regression_scenarios/GTTestsRegressionScenarios_3001_4000.cpp
<filename>implementations/ugene/src/plugins/GUITestBase/src/tests/regression_scenarios/GTTestsRegressionScenarios_3001_4000.cpp /** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2020 UniPro <<EMAIL>> * http://ugene.net * * 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 <GTGlobals.h> #include <api/GTUtils.h> #include <base_dialogs/DefaultDialogFiller.h> #include <base_dialogs/GTFileDialog.h> #include <base_dialogs/MessageBoxFiller.h> #include <drivers/GTKeyboardDriver.h> #include <drivers/GTMouseDriver.h> #include <primitives/GTAction.h> #include <primitives/GTCheckBox.h> #include <primitives/GTComboBox.h> #include <primitives/GTLineEdit.h> #include <primitives/GTListWidget.h> #include <primitives/GTMenu.h> #include <primitives/GTPlainTextEdit.h> #include <primitives/GTRadioButton.h> #include <primitives/GTSlider.h> #include <primitives/GTSpinBox.h> #include <primitives/GTSplitter.h> #include <primitives/GTTabWidget.h> #include <primitives/GTTableView.h> #include <primitives/GTToolbar.h> #include <primitives/GTTreeWidget.h> #include <primitives/GTWidget.h> #include <primitives/PopupChooser.h> #include <system/GTClipboard.h> #include <system/GTFile.h> #include <utils/GTKeyboardUtils.h> #include <utils/GTThread.h> #include <utils/GTUtilsDialog.h> #include <utils/GTUtilsToolTip.h> #include <QDialogButtonBox> #include <QFileDialog> #include <QHeaderView> #include <QListWidget> #include <QMainWindow> #include <QMenu> #include <QPlainTextEdit> #include <QProgressBar> #include <QPushButton> #include <QTableWidget> #include <QTextStream> #include <QThreadPool> #include <QWizard> #include <U2Core/AppContext.h> #include <U2Core/ExternalToolRegistry.h> #include <U2Core/U2ObjectDbi.h> #include <U2Core/U2SafePoints.h> #include <U2Gui/ProjectViewModel.h> #include <U2Gui/ToolsMenu.h> #include <U2View/ADVConstants.h> #include <U2View/ADVSingleSequenceWidget.h> #include <U2View/AnnotatedDNAViewFactory.h> #include <U2View/AnnotationsTreeView.h> #include <U2View/AssemblyNavigationWidget.h> #include <U2View/DetView.h> #include <U2View/MSAEditor.h> #include <U2View/MaEditorNameList.h> #include "../../workflow_designer/src/WorkflowViewItems.h" #include "GTDatabaseConfig.h" #include "GTTestsRegressionScenarios_3001_4000.h" #include "GTUtilsAnnotationsHighlightingTreeView.h" #include "GTUtilsAnnotationsTreeView.h" #include "GTUtilsAssemblyBrowser.h" #include "GTUtilsBookmarksTreeView.h" #include "GTUtilsCircularView.h" #include "GTUtilsDashboard.h" #include "GTUtilsEscClicker.h" #include "GTUtilsExternalTools.h" #include "GTUtilsLog.h" #include "GTUtilsMdi.h" #include "GTUtilsMsaEditor.h" #include "GTUtilsMsaEditorSequenceArea.h" #include "GTUtilsNotifications.h" #include "GTUtilsOptionPanelMSA.h" #include "GTUtilsOptionPanelSequenceView.h" #include "GTUtilsOptionsPanel.h" #include "GTUtilsPhyTree.h" #include "GTUtilsProject.h" #include "GTUtilsProjectTreeView.h" #include "GTUtilsSequenceView.h" #include "GTUtilsSharedDatabaseDocument.h" #include "GTUtilsTask.h" #include "GTUtilsTaskTreeView.h" #include "GTUtilsWizard.h" #include "GTUtilsWorkflowDesigner.h" #include "api/GTSequenceReadingModeDialog.h" #include "api/GTSequenceReadingModeDialogUtils.h" #include "runnables/qt/EscapeClicker.h" #include "runnables/ugene/corelibs/U2Gui/AlignShortReadsDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/AppSettingsDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/BuildIndexDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/ConvertAssemblyToSAMDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/CreateAnnotationWidgetFiller.h" #include "runnables/ugene/corelibs/U2Gui/CreateDocumentFromTextDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/CreateObjectRelationDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/DownloadRemoteFileDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/EditAnnotationDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/EditConnectionDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/EditQualifierDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/EditSequenceDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/ExportDocumentDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/ExportImageDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/FindQualifierDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/FindRepeatsDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/FindTandemsDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/ImportACEFileDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/ImportBAMFileDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/PositionSelectorFiller.h" #include "runnables/ugene/corelibs/U2Gui/PredictSecondaryStructureDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/ProjectTreeItemSelectorDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/RangeSelectionDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/RemovePartFromSequenceDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/ReplaceSubsequenceDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/SharedConnectionsDialogFiller.h" #include "runnables/ugene/corelibs/U2Gui/util/RenameSequenceFiller.h" #include "runnables/ugene/corelibs/U2View/ov_assembly/ExportReadsDialogFiller.h" #include "runnables/ugene/corelibs/U2View/ov_msa/BuildTreeDialogFiller.h" #include "runnables/ugene/corelibs/U2View/ov_msa/DeleteGapsDialogFiller.h" #include "runnables/ugene/corelibs/U2View/ov_msa/DistanceMatrixDialogFiller.h" #include "runnables/ugene/corelibs/U2View/ov_msa/ExportHighlightedDialogFiller.h" #include "runnables/ugene/corelibs/U2View/ov_msa/ExtractSelectedAsMSADialogFiller.h" #include "runnables/ugene/corelibs/U2View/ov_msa/LicenseAgreementDialogFiller.h" #include "runnables/ugene/corelibs/U2View/utils_smith_waterman/SmithWatermanDialogBaseFiller.h" #include "runnables/ugene/plugins/annotator/FindAnnotationCollocationsDialogFiller.h" #include "runnables/ugene/plugins/biostruct3d_view/StructuralAlignmentDialogFiller.h" #include "runnables/ugene/plugins/cap3/CAP3SupportDialogFiller.h" #include "runnables/ugene/plugins/dna_export/ExportAnnotationsDialogFiller.h" #include "runnables/ugene/plugins/dna_export/ExportMSA2MSADialogFiller.h" #include "runnables/ugene/plugins/dna_export/ExportMSA2SequencesDialogFiller.h" #include "runnables/ugene/plugins/dna_export/ExportSelectedSequenceFromAlignmentDialogFiller.h" #include "runnables/ugene/plugins/dna_export/ExportSequences2MSADialogFiller.h" #include "runnables/ugene/plugins/dna_export/ExportSequencesDialogFiller.h" #include "runnables/ugene/plugins/dna_export/ImportAnnotationsToCsvFiller.h" #include "runnables/ugene/plugins/dotplot/BuildDotPlotDialogFiller.h" #include "runnables/ugene/plugins/dotplot/DotPlotDialogFiller.h" #include "runnables/ugene/plugins/enzymes/ConstructMoleculeDialogFiller.h" #include "runnables/ugene/plugins/enzymes/DigestSequenceDialogFiller.h" #include "runnables/ugene/plugins/enzymes/FindEnzymesDialogFiller.h" #include "runnables/ugene/plugins/external_tools/BlastAllSupportDialogFiller.h" #include "runnables/ugene/plugins/external_tools/ClustalOSupportRunDialogFiller.h" #include "runnables/ugene/plugins/external_tools/FormatDBDialogFiller.h" #include "runnables/ugene/plugins/external_tools/RemoteBLASTDialogFiller.h" #include "runnables/ugene/plugins/external_tools/SnpEffDatabaseDialogFiller.h" #include "runnables/ugene/plugins/external_tools/SpadesGenomeAssemblyDialogFiller.h" #include "runnables/ugene/plugins/external_tools/TCoffeeDailogFiller.h" #include "runnables/ugene/plugins/weight_matrix/PwmBuildDialogFiller.h" #include "runnables/ugene/plugins/workflow_designer/AliasesDialogFiller.h" #include "runnables/ugene/plugins/workflow_designer/ConfigurationWizardFiller.h" #include "runnables/ugene/plugins/workflow_designer/CreateElementWithCommandLineToolFiller.h" #include "runnables/ugene/plugins/workflow_designer/CreateElementWithScriptDialogFiller.h" #include "runnables/ugene/plugins/workflow_designer/StartupDialogFiller.h" #include "runnables/ugene/plugins/workflow_designer/WizardFiller.h" #include "runnables/ugene/plugins/workflow_designer/WorkflowMetadialogFiller.h" #include "runnables/ugene/plugins_3rdparty/MAFFT/MAFFTSupportRunDialogFiller.h" #include "runnables/ugene/plugins_3rdparty/clustalw/ClustalWDialogFiller.h" #include "runnables/ugene/plugins_3rdparty/hmm3/UHMM3PhmmerDialogFiller.h" #include "runnables/ugene/plugins_3rdparty/kalign/KalignDialogFiller.h" #include "runnables/ugene/plugins_3rdparty/primer3/Primer3DialogFiller.h" #include "runnables/ugene/plugins_3rdparty/umuscle/MuscleDialogFiller.h" #include "runnables/ugene/ugeneui/ConvertAceToSqliteDialogFiller.h" #include "runnables/ugene/ugeneui/CreateNewProjectWidgetFiller.h" #include "runnables/ugene/ugeneui/DocumentFormatSelectorDialogFiller.h" #include "runnables/ugene/ugeneui/DocumentProviderSelectorDialogFiller.h" #include "runnables/ugene/ugeneui/NCBISearchDialogFiller.h" #include "runnables/ugene/ugeneui/SaveProjectDialogFiller.h" #include "runnables/ugene/ugeneui/SelectDocumentFormatDialogFiller.h" #include "runnables/ugene/ugeneui/SequenceReadingModeSelectorDialogFiller.h" namespace U2 { namespace GUITest_regression_scenarios { GUI_TEST_CLASS_DEFINITION(test_3014) { //1. Open the _common_data/scenarios/_regression/3014/pdb2q41.ent.gz GTLogTracer l; GTFileDialog::openFile(os, testDir + "_common_data/scenarios/_regression/3014/", "pdb2q41.ent.gz"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(10000); // 2. In context menu go to 'Molecular surface'->'SES' GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Molecular Surface" << "SES")); QWidget *widget3d = GTWidget::findWidget(os, "1-2Q41"); GTWidget::click(os, widget3d, Qt::RightButton); GTGlobals::sleep(10000); // Expected state: Moleculaar surface calculated and showed. Program not crached. GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3017) { //1. Open 'HIV-1.aln'; //2. Select few columns; //3. Run ClastulW, ClustalO, Mafft or T-Coffee alignment task; //4. Try to change an alignment while the task is running: move region, delete region etc.; //Current state: there is no results of your actions because msa is blocked, overview is not recalculated. GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW/", "ty3.aln.gz"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDialog::waitForDialog(os, new MuscleDialogFiller(os, MuscleDialogFiller::Refine)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << MSAE_MENU_ALIGN << "Align with muscle")); GTWidget::click(os, GTUtilsMdi::activeWindow(os), Qt::RightButton); GTGlobals::sleep(3000); GTUtilsMSAEditorSequenceArea::click(os, QPoint(13, 8)); GTKeyboardDriver::keyClick(Qt::Key_Delete); GTKeyboardDriver::keyClick(Qt::Key_Space); GTKeyboardDriver::keyClick('c', Qt::ControlModifier); GTGlobals::sleep(); QString clipboardText = GTClipboard::text(os); CHECK_SET_ERR("S" == clipboardText, "Alignment is not locked" + clipboardText); } GUI_TEST_CLASS_DEFINITION(test_3031) { // Open "data/samples/CLUSTALW/COI.aln". GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); // Open "Statistics" options panel tab. GTWidget::click(os, GTWidget::findWidget(os, "OP_SEQ_STATISTICS_WIDGET")); // Set "Montatna_montana" reference sequence. GTUtilsMSAEditorSequenceArea::click(os, QPoint(-4, 4)); GTWidget::click(os, GTWidget::findWidget(os, "addSeq")); // Delete "Montana_montana" sequence GTUtilsMSAEditorSequenceArea::click(os, QPoint(-4, 4)); GTKeyboardDriver::keyClick(Qt::Key_Delete); // 5. Right click on any sequence name // Expected state: action "Set this sequence as reference" is visible, "Unset reference sequence" is invisible } GUI_TEST_CLASS_DEFINITION(test_3034) { // 1. Open "samples/FASTA/human_T1.fa". // 2. Right click on the document -> Add -> Add object to document. // Expected: the dialog will appear. There are no human_T1 objects. GTLogTracer l; GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDialog::waitForDialog(os, new ProjectTreeItemSelectorDialogFiller(os, QMap<QString, QStringList>(), QSet<GObjectType>(), ProjectTreeItemSelectorDialogFiller::Separate, 0)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ACTION_PROJECT__ADD_MENU << ACTION_PROJECT__ADD_OBJECT)); QPoint docCenter = GTUtilsProjectTreeView::getItemCenter(os, "human_T1.fa"); GTMouseDriver::moveTo(docCenter); GTMouseDriver::click(Qt::RightButton); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3035) { //check read only user QString conName = "test_3035_db"; GTDatabaseConfig::initTestConnectionInfo(conName, GTDatabaseConfig::database(), true, true); { QList<SharedConnectionsDialogFiller::Action> actions; actions << SharedConnectionsDialogFiller::Action(SharedConnectionsDialogFiller::Action::CLICK, conName); actions << SharedConnectionsDialogFiller::Action(SharedConnectionsDialogFiller::Action::CONNECT, conName); GTUtilsDialog::waitForDialog(os, new SharedConnectionsDialogFiller(os, actions)); } GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Connect to UGENE shared database..."); // import, remove, drag'n'drop, empty recycle bin, restore from recycle bin. is prohibited GTUtilsProjectTreeView::click(os, "Recycle bin", Qt::RightButton); CHECK_SET_ERR(QApplication::activePopupWidget() == NULL, "popup menu unexpectidly presents on recyble bin"); GTUtilsProjectTreeView::click(os, "export_tests", Qt::RightButton); CHECK_SET_ERR(QApplication::activePopupWidget() == NULL, "popup menu unexpectidly presents on export_tests"); QModelIndex parent = GTUtilsProjectTreeView::findIndex(os, "export_tests"); QModelIndex index = GTUtilsProjectTreeView::findIndex(os, "et0001_sequence", parent); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, index)); GTUtilsDialog::waitForDialog(os, new PopupChecker(os, QStringList() << "action_project__edit_menu", PopupChecker::NotExists)); GTMouseDriver::click(Qt::RightButton); GTUtilsDialog::waitForDialog(os, new PopupChecker(os, QStringList() << "action_project__remove_selected_action", PopupChecker::NotExists)); GTMouseDriver::click(Qt::RightButton); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Open View" << "action_open_view")); GTMouseDriver::click(Qt::RightButton); GTGlobals::sleep(); QString name = GTUtilsMdi::activeWindowTitle(os); CHECK_SET_ERR(name == " [s] et0001_sequence", QString("unexpected window title:%1").arg(name)); GTUtilsDialog::waitForDialog(os, new ExportSelectedRegionFiller(os, sandBoxDir, "test_3035.fa")); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "action_project__export_import_menu_action" << "export sequences")); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, index)); GTMouseDriver::click(Qt::RightButton); GTGlobals::sleep(500); GTUtilsDialog::waitForDialog(os, new ExportSequenceAsAlignmentFiller(os, sandBoxDir, "test_3035_1.aln", ExportSequenceAsAlignmentFiller::Clustalw)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "action_project__export_import_menu_action" << "export sequences as alignment")); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, index)); GTMouseDriver::click(Qt::RightButton); GTGlobals::sleep(); } GUI_TEST_CLASS_DEFINITION(test_3052) { // 1. Open "_common_data/bam/chrM.sorted.bam". // Expected state: an "Import BAM file" dialog appears. // 2. Import the assembly somewhere to the "1.ugenedb" file. // Expected state: the assembly is imported, a view opens. // 3. Close the view. // 4. Open "_common_data/bam/scerevisiae.bam". // Expected state: an "Import BAM file" dialog appears. // 5. Select the same file as for "chrM.sorted.bam". Try to start import. // Expected state: a message box appears, it allows to replace the file, to append appent to the file or to cancel operation. // 6. Select the "Append" option. // Expected state: the assembly is imported, a view opens. // 7. Remove the the first assembly object from the document in the project view. // Expected state: the object is removed, there is no errors in the log. // 8. Remove the document from the project view (or just unload it - test_3052_1). Open it again. // Expected state: there is one assembly object in it. GTLogTracer l; QString ugenedbFileName = testDir + "_common_data/scenarios/sandbox/test_3052.ugenedb"; QString docName = "test_3052.ugenedb"; GTUtilsDialog::waitForDialog(os, new ImportBAMFileFiller(os, ugenedbFileName)); GTFileDialog::openFile(os, testDir + "_common_data/bam", "chrM.sorted.bam"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsMdi::closeWindow(os, "test_3052 [as] chrM"); GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, "Append")); GTUtilsDialog::waitForDialog(os, new ImportBAMFileFiller(os, ugenedbFileName)); GTFileDialog::openFile(os, testDir + "_common_data/bam", "scerevisiae.bam"); GTUtilsTaskTreeView::waitTaskFinished(os); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "chrM")); GTMouseDriver::click(); GTKeyboardDriver::keyPress(Qt::Key_Delete); GTGlobals::sleep(); GTUtilsDocument::removeDocument(os, docName); GTFileDialog::openFile(os, testDir + "_common_data/scenarios/sandbox", "test_3052.ugenedb"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3052_1) { GTLogTracer l; QString ugenedbFileName = testDir + "_common_data/scenarios/sandbox/test_3052.ugenedb"; QString docName = "test_3052.ugenedb"; GTUtilsDialog::waitForDialog(os, new ImportBAMFileFiller(os, ugenedbFileName)); GTFileDialog::openFile(os, testDir + "_common_data/bam", "chrM.sorted.bam"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsMdi::closeWindow(os, "test_3052 [as] chrM"); GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, "Append")); GTUtilsDialog::waitForDialog(os, new ImportBAMFileFiller(os, ugenedbFileName)); GTFileDialog::openFile(os, testDir + "_common_data/bam", "scerevisiae.bam"); GTUtilsTaskTreeView::waitTaskFinished(os); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "chrM")); GTMouseDriver::click(); GTKeyboardDriver::keyClick(Qt::Key_Delete); GTUtilsDocument::unloadDocument(os, docName, false); GTGlobals::sleep(); GTUtilsDocument::loadDocument(os, docName); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3072) { GTLogTracer l; // 1. Connect to shared database(eg.ugene_gui_test_win); Document *dbDoc = GTUtilsSharedDatabaseDocument::connectToTestDatabase(os); // 2. Add folder; GTUtilsSharedDatabaseDocument::createFolder(os, dbDoc, "/", "regression_test_3072"); CHECK_SET_ERR(!l.hasErrors(), "Errors in log: " + l.getJoinedErrorString()); } GUI_TEST_CLASS_DEFINITION(test_3073) { // 1. Open "human_T1.fa"; // 2. Create few annotations (new file MyDocument_n.gb appeared); // 3. Save the project with these files and relaunch UGENE; // 4. Open the project and open either sequence or annotation file; // Expected state: both files are loaded; GTLogTracer l; GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDialog::waitForDialog(os, new CreateAnnotationWidgetFiller(os, true, "group", "annotation_1", "10..20", sandBoxDir + "test_3073.gb")); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ADV_MENU_ADD << "create_annotation_action")); GTMenu::showContextMenu(os, GTWidget::findWidget(os, "render_area_human_T1 (UCSC April 2002 chr7:115977709-117855134)")); GTUtilsDialog::waitForDialog(os, new CreateAnnotationWidgetFiller(os, false, "group", "annotation_2", "10000..100000")); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ADV_MENU_ADD << "create_annotation_action")); GTMenu::showContextMenu(os, GTWidget::findWidget(os, "render_area_human_T1 (UCSC April 2002 chr7:115977709-117855134)")); GTUtilsDialog::waitForDialog(os, new CreateAnnotationWidgetFiller(os, false, "group", "annotation_3", "120000..180000")); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ADV_MENU_ADD << "create_annotation_action")); GTMenu::showContextMenu(os, GTWidget::findWidget(os, "render_area_human_T1 (UCSC April 2002 chr7:115977709-117855134)")); GTUtilsDocument::saveDocument(os, "test_3073.gb"); GTUtilsDialog::waitForDialog(os, new SaveProjectAsDialogFiller(os, "proj_test_3073", sandBoxDir + "/proj_test_3073")); GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Save project as...", GTGlobals::UseMouse); GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Close project", GTGlobals::UseMouse); GTGlobals::sleep(); GTFileDialog::openFile(os, sandBoxDir, "proj_test_3073.uprj"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(); GTUtilsDocument::loadDocument(os, "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(); CHECK_SET_ERR(GTUtilsDocument::isDocumentLoaded(os, "test_3073.gb"), "Annotation file is not loaded!"); GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Close project", GTGlobals::UseMouse); GTGlobals::sleep(); GTFileDialog::openFile(os, sandBoxDir, "proj_test_3073.uprj"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(); GTUtilsDocument::loadDocument(os, "test_3073.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(200); CHECK_SET_ERR(GTUtilsDocument::isDocumentLoaded(os, "human_T1.fa"), "Sequence file is not loaded!"); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3074) { // Disconnect from the shared database with opened msa from this database // 1. Connect to the "ugene_gui_test" database. // 2. Double click the object "/view_test_0002/[m] COI". // Expected: the msa is opened in the MSA Editor. // 3. Remove the database document from the project tree view. // Expected state: the MSA Editor is closed, UGENE doesn't crash. GTLogTracer logTracer; Document *databaseDoc = GTUtilsSharedDatabaseDocument::connectToTestDatabase(os); GTUtilsSharedDatabaseDocument::openView(os, databaseDoc, "/view_test_0002/COI"); QWidget *msaView = GTWidget::findWidget(os, " [m] COI"); CHECK_SET_ERR(NULL != msaView, "View wasn't opened"); GTUtilsSharedDatabaseDocument::disconnectDatabase(os, databaseDoc); GTUtilsLog::check(os, logTracer); } GUI_TEST_CLASS_DEFINITION(test_3079) { GTUtilsSharedDatabaseDocument::connectToTestDatabase(os); // 1. Remove any folder to the recycle bin QModelIndex fol = GTUtilsProjectTreeView::findIndex(os, "test_3079_inner"); QModelIndex bin = GTUtilsProjectTreeView::findIndex(os, "Recycle bin"); GTUtilsProjectTreeView::dragAndDrop(os, fol, bin); // 2. Try to remove any folder or sequence from the database to the folder from the first step fol = GTUtilsProjectTreeView::findIndex(os, "test_3079_inner"); QModelIndex seq = GTUtilsProjectTreeView::findIndex(os, "test_3079.fa"); GTUtilsProjectTreeView::dragAndDrop(os, seq, fol); // Current state: UGENE crashes } GUI_TEST_CLASS_DEFINITION(test_3085_1) { QFile(testDir + "_common_data/regression/3085/murine.gb").copy(sandBoxDir + "murine_3085_1.gb"); //1. Open samples/genbank/murine.gb. GTFileDialog::openFile(os, sandBoxDir + "murine_3085_1.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); QWidget *sv = GTUtilsMdi::activeWindow(os); //2. Change the sequence outside UGENE. //Expected state: dialog about file modification appeared. //3. Click Yes. GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::Yes)); QByteArray data = GTFile::readAll(os, sandBoxDir + "murine_3085_1.gb"); GTGlobals::sleep(1000); // wait at least 1 second: UGENE does not detect file changes within 1 second interval. QFile file(sandBoxDir + "murine_3085_1.gb"); file.open(QIODevice::WriteOnly); file.write(data); file.close(); //QFile(sandBoxDir + "murine_3085_1.gb").rename(sandBoxDir + "murine_3085_1_1.gb"); //QFile(testDir + "_common_data/regression/3085/murine_1.gb").copy(sandBoxDir + "murine_3085_1.gb"); GTGlobals::sleep(6000); //Expected state: file was updated, the sequence view with annotations is opened and updated. QWidget *reloaded1Sv = GTUtilsMdi::activeWindow(os); CHECK_SET_ERR(sv != reloaded1Sv, "File is not reloaded 1"); //4. Change the annotations file outside UGENE (e.g. change annotation region). //Expected state:: dialog about file modification appeared. //5. Click Yes. GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::Yes)); data = GTFile::readAll(os, testDir + "_common_data/regression/3085/murine_2.gb"); GTGlobals::sleep(1000); // wait at least 1 second: UGENE does not detect file changes within 1 second interval. QFile file1(sandBoxDir + "murine_3085_1.gb"); file1.open(QIODevice::WriteOnly); file1.write(data); file1.close(); GTGlobals::sleep(6000); //Expected state:: file was updated, the sequence view with annotations is opened and updated. QWidget *reloaded2Sv = GTUtilsMdi::activeWindow(os); CHECK_SET_ERR(reloaded1Sv != reloaded2Sv, "File is not reloaded 2"); } GUI_TEST_CLASS_DEFINITION(test_3085_2) { QFile(testDir + "_common_data/regression/3085/test.gb").copy(sandBoxDir + "murine_3085_2.gb"); GTLogTracer l; //1. Open "_common_data/regression/test.gb". GTFileDialog::openFile(os, sandBoxDir + "murine_3085_2.gb"); GTUtilsProjectTreeView::checkProjectViewIsOpened(os); //2. Append another sequence to the file outside of UGENE. //3. Click "Yes" in the appeared dialog in UGENE. GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::Yes)); QByteArray data = GTFile::readAll(os, testDir + "_common_data/regression/3085/test_1.gb"); GTGlobals::sleep(1000); // wait at least 1 second: UGENE does not detect file changes within 1 second interval. QFile file(sandBoxDir + "murine_3085_2.gb"); file.open(QIODevice::WriteOnly); file.write(data); file.close(); GTUtilsDialog::waitAllFinished(os); //Expected state: document reloaded without errors/warnings. CHECK_SET_ERR(!l.hasErrors(), "Errors in log: " + l.getJoinedErrorString()); } GUI_TEST_CLASS_DEFINITION(test_3086) { GTUtilsDialog::waitForDialog(os, new ImportBAMFileFiller(os, sandBoxDir + "test_3086/test_3086.ugenedb")); GTFileDialog::openFile(os, testDir + "_common_data/scenarios/_regression/3086/", "UGENE-3086.bam"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsTaskTreeView::waitTaskFinished(os); } GUI_TEST_CLASS_DEFINITION(test_3092) { // 1. Open "data/samples/FASTA/human_T1.fa". // 2. Do {Actions -> Analyze -> Query with BLAST+...} in the main menu. // Expected state: a dialog "Request to Local BLAST Database" appears, UGENE doesn't crash. GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDialog::waitForDialog(os, new BlastAllSupportDialogFiller(BlastAllSupportDialogFiller::Parameters(), os)); GTMenu::clickMainMenuItem(os, QStringList() << "Actions" << "Analyze" << "Query with local BLAST+...", GTGlobals::UseMouse); } GUI_TEST_CLASS_DEFINITION(test_3101) { //1. Open "_common_data\scenarios\_regression\3101\enzymes" //Expected state : "Document format selection" dialog appeared GTUtilsDialog::waitForDialog(os, new DocumentFormatSelectorDialogFiller(os, "Newick Standard")); GTUtilsProject::openFile(os, testDir + "_common_data/scenarios/_regression/3101/enzymes"); GTUtilsTaskTreeView::waitTaskFinished(os); //2. Select "Newick" format //Expected state : Task finished with error, but without assert call GTGlobals::sleep(); } GUI_TEST_CLASS_DEFINITION(test_3102) { //1. Go to 'File->Connect to UGENE shared database...' // Expected state: Showed dialog 'Shared Databases Connections' // In list of connections showed 'UGENE public database' GTLogTracer logTracer; Document *databaseDoc = GTUtilsSharedDatabaseDocument::connectToUgenePublicDatabase(os); CHECK_SET_ERR(NULL != databaseDoc, "UGENE public databased connection error"); } GUI_TEST_CLASS_DEFINITION(test_3103) { //1. Go to 'File->Connect to UGENE shared database...' //Expected state: Showed dialog 'Shared Databases Connections' //2. Click on 'Add' button //Expected state: Showed dailog 'Connection Settings' and 'Port' field filled with port 3306 { QList<SharedConnectionsDialogFiller::Action> actions; actions << SharedConnectionsDialogFiller::Action(SharedConnectionsDialogFiller::Action::ADD); actions << SharedConnectionsDialogFiller::Action(SharedConnectionsDialogFiller::Action::CLOSE); GTUtilsDialog::waitForDialog(os, new SharedConnectionsDialogFiller(os, actions)); } { EditConnectionDialogFiller::Parameters params; params.checkDefaults = true; params.accept = false; GTUtilsDialog::waitForDialog(os, new EditConnectionDialogFiller(os, params, EditConnectionDialogFiller::FROM_SETTINGS)); } GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Connect to UGENE shared database..."); } GUI_TEST_CLASS_DEFINITION(test_3112) { // 1. Open big alignment, e.g. "_common_data/clustal/big.aln" GTFileDialog::openFile(os, testDir + "_common_data/clustal/", "big.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); QToolButton *button = qobject_cast<QToolButton *>(GTAction::button(os, "Show overview")); CHECK_SET_ERR(button->isChecked(), "Overview button is not pressed"); // 2. Modify the alignment // Expected state: the task starts GTUtilsMsaEditor::removeColumn(os, 5); GTGlobals::sleep(500); CHECK_SET_ERR(0 != GTUtilsTaskTreeView::getTopLevelTasksCount(os), "1: There are no active tasks "); // 3. Click the "Overview" button on the main toolbar // Expected state: the task is canceled, the overview is hidden GTWidget::click(os, button); GTGlobals::sleep(500); // wait for task to be canceled CHECK_SET_ERR(0 == GTUtilsTaskTreeView::getTopLevelTasksCount(os), "2: There are unfinished tasks"); // 4. Click the "Overview" button again and wait till overview calculation and rendering ends GTWidget::click(os, button); CHECK_SET_ERR(0 != GTUtilsTaskTreeView::getTopLevelTasksCount(os), "3: There are no active tasks"); GTUtilsTaskTreeView::waitTaskFinished(os); // 5. Hide the overview // 6. Open the overview // Expected state: no task starts because nothing have been changed GTWidget::click(os, button); GTWidget::click(os, button); CHECK_SET_ERR(0 == GTUtilsTaskTreeView::getTopLevelTasksCount(os), "4: There are unfinished tasks"); // 7. Hide the overview GTWidget::click(os, button); // 8. Edit the alignment GTUtilsMsaEditor::removeColumn(os, 5); // 9. Open the overview // Expected state: overview calculation task starts GTWidget::click(os, button); GTGlobals::sleep(500); CHECK_SET_ERR(0 != GTUtilsTaskTreeView::getTopLevelTasksCount(os), "5: There are no active tasks"); } GUI_TEST_CLASS_DEFINITION(test_3124) { // 1. Connect to a shared database. // 2. Right click on the document->Add->Import to the database. // 3. Click "Add files". // 4. Choose "data/samples/Genbank/PBR322.gb". // 5. Click "Import". // Expected state : the file is imported, there are no errors in the log. GTLogTracer logTracer; Document *databaseDoc = GTUtilsSharedDatabaseDocument::connectToTestDatabase(os); CHECK_OP(os, ); GTUtilsSharedDatabaseDocument::importFiles(os, databaseDoc, "/test", QStringList() << dataDir + "samples/Genbank/PBR322.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsLog::check(os, logTracer); } GUI_TEST_CLASS_DEFINITION(test_3125) { //1. Connect to a shared database. //2. Find a msa in the database (or import a new one). //3. Find menu items: {Actions -> Export -> Save subalignment} //and {Actions -> Export -> Save sequence} //Expected state: actions are enabled, you can export a subalignment and a sequence. //Current state: actions are disabled. GTLogTracer logTracer; Document *databaseDoc = GTUtilsSharedDatabaseDocument::connectToTestDatabase(os); CHECK_OP(os, ); GTUtilsSharedDatabaseDocument::openView(os, databaseDoc, "/view_test_0002/COI"); QWidget *msaView = GTWidget::findWidget(os, " [m] COI"); CHECK_SET_ERR(NULL != msaView, "View wasn't opened"); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << MSAE_MENU_EXPORT << "Save subalignment")); GTUtilsDialog::waitForDialog(os, new ExtractSelectedAsMSADialogFiller(os, testDir + "_common_data/scenarios/sandbox/3125.aln", QStringList() << "Phaneroptera_falcata", 6, 600)); GTMenu::showContextMenu(os, GTWidget::findWidget(os, "msa_editor_sequence_area")); GTUtilsSharedDatabaseDocument::disconnectDatabase(os, databaseDoc); GTUtilsLog::check(os, logTracer); } GUI_TEST_CLASS_DEFINITION(test_3126) { // 1. Open "test/_common_data/ace/ace_test_1.ace". // 2. Click "OK" in the import dialog. // Expected: the file is imported, UGENE does not crash. GTLogTracer l; GTUtilsDialog::waitForDialog(os, new ImportACEFileFiller(os, false, sandBoxDir + "test_3126")); GTUtilsProject::openFile(os, testDir + "_common_data/ace/ace_test_1.ace"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3128) { // 1. Open file test/_common_data/cmdline/read-write/read_db_write_gen.uws" GTUtilsDialog::waitForDialog(os, new StartupDialogFiller(os)); GTLogTracer l; GTFileDialog::openFile(os, testDir + "_common_data/cmdline/read-write/", "read_db_write_gen.uws"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Set parameters: db="NCBI protein sequence database", id="AAA59172.1" GTUtilsWorkflowDesigner::click(os, "Read from remote database", QPoint(-20, -20)); GTUtilsWorkflowDesigner::setParameter(os, "Database", 2, GTUtilsWorkflowDesigner::comboValue); GTUtilsWorkflowDesigner::setParameter(os, "Resource ID(s)", "AAA59172.1", GTUtilsWorkflowDesigner::textValue); // 3. Launch scheme. GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::Ok)); GTWidget::click(os, GTAction::button(os, "Validate workflow")); GTGlobals::sleep(); // Expected state: no errors in the log. GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3128_1) { // 1. Open any genbank file with a COMMENT section GTFileDialog::openFile(os, dataDir + "samples/Genbank", "murine.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Find the "comment" annotation, click it. QTreeWidgetItem *item2 = GTUtilsAnnotationsTreeView::findItem(os, "comment"); QPoint p2 = GTTreeWidget::getItemCenter(os, item2); GTMouseDriver::moveTo(p2); GTMouseDriver::click(); //Expected state: UGENE does not crash. } GUI_TEST_CLASS_DEFINITION(test_3130) { // 1. Create an invalid connection to a shared database (e.g. wring login/password). // 2. Connect. // Expected: the error message is shown. // 3. Connect again. // Expected: the error message is shown, UGENE does not crash. GTDatabaseConfig::initTestConnectionInfo("test_3133"); EditConnectionDialogFiller::Parameters parameters; parameters.connectionName = "test_3133"; parameters.host = GTDatabaseConfig::host(); parameters.port = QString::number(GTDatabaseConfig::port()); parameters.database = GTDatabaseConfig::database(); parameters.login = GTDatabaseConfig::login() + "_test_3130"; parameters.password = GTDatabaseConfig::password(); GTUtilsDialog::waitForDialog(os, new EditConnectionDialogFiller(os, parameters, EditConnectionDialogFiller::MANUAL)); QList<SharedConnectionsDialogFiller::Action> actions; actions << SharedConnectionsDialogFiller::Action(SharedConnectionsDialogFiller::Action::CLICK, "test_3133"); actions << SharedConnectionsDialogFiller::Action(SharedConnectionsDialogFiller::Action::EDIT, "test_3133"); SharedConnectionsDialogFiller::Action connectAction(SharedConnectionsDialogFiller::Action::CONNECT, "test_3133"); connectAction.expectedResult = SharedConnectionsDialogFiller::Action::WRONG_DATA; actions << connectAction; actions << connectAction; actions << SharedConnectionsDialogFiller::Action(SharedConnectionsDialogFiller::Action::CLOSE); GTUtilsDialog::waitForDialog(os, new SharedConnectionsDialogFiller(os, actions)); GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Connect to UGENE shared database..."); GTGlobals::sleep(); } GUI_TEST_CLASS_DEFINITION(test_3133) { //1. Connect to a shared database (e.g. ugene_gui_test). Document *dbDoc = GTUtilsSharedDatabaseDocument::connectToTestDatabase(os); QString dbName = dbDoc->getName(); GTUtilsProjectTreeView::findIndex(os, dbName); CHECK_OP(os, ); //2. Save the project. GTUtilsDialog::waitForDialog(os, new SaveProjectAsDialogFiller(os, "test_3133", testDir + "_common_data/scenarios/sandbox/test_3133")); GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Save project as..."); //3. Close the project. GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Close project"); //4. Open the saved project. GTFileDialog::openFile(os, testDir + "_common_data/scenarios/sandbox/", "test_3133.uprj"); GTUtilsTaskTreeView::waitTaskFinished(os); //Expected state: project view is present, there are no documents presented. QModelIndex idx = GTUtilsProjectTreeView::findIndex(os, dbName, GTGlobals::FindOptions(false)); CHECK_SET_ERR(!idx.isValid(), "The database document is in the project"); } GUI_TEST_CLASS_DEFINITION(test_3137) { GTLogTracer l; // 1. Connect to shared database(eg.ugene_gui_test_win); Document *dbDoc = GTUtilsSharedDatabaseDocument::connectToTestDatabase(os); // 2. Add folder; GTUtilsSharedDatabaseDocument::createFolder(os, dbDoc, "/", "regression_test_3137"); // 3. Import some file to this folder(eg.COI.aln); GTUtilsSharedDatabaseDocument::importFiles(os, dbDoc, "/regression_test_3137", QStringList() << dataDir + "samples/CLUSTALW/COI.aln"); // 4. Delete folder; GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "regression_test_3137")); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ACTION_PROJECT__REMOVE_SELECTED)); GTMouseDriver::click(Qt::RightButton); // 5. Wait for several seconds; GTGlobals::sleep(10000); // Expected state : folder does not appear. GTGlobals::FindOptions findOptions(false); findOptions.depth = 1; const QModelIndex innerFolderNotFoundIndex = GTUtilsProjectTreeView::findIndex(os, "regression_test_3137", findOptions); CHECK_SET_ERR(!innerFolderNotFoundIndex.isValid(), "The 'regression_test_3137' folder was found in the database but expected to disappear"); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3138) { // 1. Open "_common_data/fasta/abcd.fa" // 2. Open Find Pattern on the Option Panel // 3. Set algorithm to "Regular expression" // 4. Find 'A*' pattern // Expected state: founded regions are valid. GTUtilsDialog::waitForDialog(os, new SequenceReadingModeSelectorDialogFiller(os, SequenceReadingModeSelectorDialogFiller::Merge)); GTUtilsProject::openFile(os, testDir + "_common_data/fasta/abcd.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTKeyboardDriver::keyClick('f', Qt::ControlModifier); GTGlobals::sleep(200); GTWidget::click(os, GTWidget::findWidget(os, "ArrowHeader_Search algorithm")); QComboBox *algorithmBox = qobject_cast<QComboBox *>(GTWidget::findWidget(os, "boxAlgorithm")); CHECK_SET_ERR(algorithmBox != NULL, "Cannot find boxAlgorithm widget!"); GTComboBox::setIndexWithText(os, algorithmBox, "Regular expression"); GTWidget::click(os, GTWidget::findWidget(os, "textPattern")); GTGlobals::sleep(200); GTKeyboardDriver::keySequence("A*"); GTGlobals::sleep(500); GTWidget::click(os, GTWidget::findWidget(os, "getAnnotationsPushButton")); GTGlobals::sleep(500); QList<U2Region> regions = GTUtilsAnnotationsTreeView::getAnnotatedRegions(os); foreach (const U2Region &r, regions) { CHECK_SET_ERR(r.length > 0, "Invalid annotated region!"); } } GUI_TEST_CLASS_DEFINITION(test_3139) { //1. Do {File -> Open as...} in the main menu. //2. Open "data/samples/FASTA/human_T1.fa" as msa. // Expected state: a MSA Editor is opened. // Current state: a Sequence View is opened. GTFileDialogUtils *ob = new GTFileDialogUtils(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsDialog::waitForDialog(os, ob); GTUtilsDialog::waitForDialog(os, new DocumentFormatSelectorDialogFiller(os, "FASTA")); GTUtilsDialog::waitForDialog(os, new SequenceReadingModeSelectorDialogFiller(os, SequenceReadingModeSelectorDialogFiller::Join)); GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Open as..."); GTUtilsTaskTreeView::waitTaskFinished(os); QWidget *seqArea = GTWidget::findWidget(os, "msa_editor_sequence_area"); CHECK_SET_ERR(NULL != seqArea, "MSA Editor isn't opened.!"); } GUI_TEST_CLASS_DEFINITION(test_3140) { // 1. Open "_common_data/clustal/big.aln". GTUtilsTaskTreeView::openView(os); GTFileDialog::openFile(os, testDir + "_common_data/clustal", "big.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Select the first symbol of the first line. GTUtilsMSAEditorSequenceArea::selectArea(os, QPoint(0, 0), QPoint(0, 0)); // 3. Press the Space button and do not unpress it. // Expected: the alignment changes on every button press. UGENE does not crash. // 4. Unpress the button. // Expected: the overview rendereing task is finished. The overview is shown. for (int i = 0; i < 100; i++) { GTKeyboardDriver::keyClick(Qt::Key_Space); GTGlobals::sleep(50); } GTGlobals::sleep(500); int renderTasksCount = GTUtilsTaskTreeView::getTopLevelTasksCount(os); CHECK_SET_ERR(1 == renderTasksCount, QString("An unexpected overview render tasks count: expect %1, got %2").arg(1).arg(renderTasksCount)); GTUtilsTaskTreeView::waitTaskFinished(os); const QColor currentColor = GTUtilsMsaEditor::getGraphOverviewPixelColor(os, QPoint(1, 1)); const QColor expectedColor = QColor("white"); const QString currentColorString = QString("(%1, %2, %3)").arg(currentColor.red()).arg(currentColor.green()).arg(currentColor.blue()); const QString expectedColorString = QString("(%1, %2, %3)").arg(expectedColor.red()).arg(expectedColor.green()).arg(expectedColor.blue()); CHECK_SET_ERR(expectedColor == currentColor, QString("An unexpected color, maybe overview was not rendered: expected %1, got %2").arg(expectedColorString).arg(currentColorString)); } GUI_TEST_CLASS_DEFINITION(test_3142) { // 1. Open "data/samples/CLUSTALW/COI.aln" // 2. On the options panel press the "Open tree" button // Expected state: the "Select files to open..." dialog has opened // 3. Choose the file "data/samples/Newick/COI.nwk" // Expected state: a tree view has appeared along with MSA view GTLogTracer l; GTFileDialog::openFile(os, dataDir + "/samples/CLUSTALW/", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(); GTWidget::click(os, GTWidget::findWidget(os, "OP_MSA_ADD_TREE_WIDGET")); GTGlobals::sleep(); GTUtilsDialog::waitForDialog(os, new GTFileDialogUtils(os, dataDir + "samples/Newick/COI.nwk")); GTWidget::click(os, GTWidget::findWidget(os, "OpenTreeButton")); QWidget *msaWidget = GTWidget::findWidget(os, "msa_editor_sequence_area"); CHECK_SET_ERR(msaWidget != NULL, "MSASequenceArea not found"); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3143) { // 1. Open file data/samples/Assembly/chrM.sorted.bam; GTUtilsDialog::waitForDialog(os, new ImportBAMFileFiller(os, sandBoxDir + "chrM.sorted.bam.ugenedb")); GTFileDialog::openFile(os, dataDir + "samples/Assembly", "chrM.sorted.bam"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(); // Expected state: Showed Import BAM File dialog. // 2. Click Import; // Expected state: Imported file opened in Assembly Viewer. GTWidget::findWidget(os, "assembly_browser_chrM.sorted.bam [as] chrM"); // 3. Remove this file from project and try to open it again; GTUtilsProjectTreeView::click(os, "chrM.sorted.bam.ugenedb"); GTKeyboardDriver::keyClick(Qt::Key_Delete); GTGlobals::sleep(); // Expected state: Showed Import BAM File dialog. GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, "Replace")); GTUtilsDialog::waitForDialog(os, new ImportBAMFileFiller(os, sandBoxDir + "chrM.sorted.bam.ugenedb")); GTFileDialog::openFile(os, dataDir + "samples/Assembly", "chrM.sorted.bam"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(); // 4. Click Import; // Expected state: Showed message box with question about overwriting of existing file.. // 5. Click Replace; GTWidget::findWidget(os, "assembly_browser_chrM.sorted.bam [as] chrM"); // Expected state: Imported file opened in Assembly Viewer without errors. } GUI_TEST_CLASS_DEFINITION(test_3144) { GTLogTracer l; // 1.Connect to a shared database. Document *dbDoc = GTUtilsSharedDatabaseDocument::connectToTestDatabase(os); QString folder1Name = GTUtils::genUniqueString("regression_test_3144_1"); QString folder2Name = GTUtils::genUniqueString("regression_test_3144_2"); // 2. Create a folder "regression_test_3144_1" in the root folder. GTUtilsSharedDatabaseDocument::createFolder(os, dbDoc, "/", folder1Name); // 3. Create a folder "regression_test_3144_2" in the folder "regression_test_3144_1". GTUtilsSharedDatabaseDocument::createFolder(os, dbDoc, "/" + folder1Name, folder2Name); // 4. Remove the folder "regression_test_3144_2". GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, folder2Name)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ACTION_PROJECT__REMOVE_SELECTED)); GTMouseDriver::click(Qt::RightButton); // Expected state : the folder "regression_test_3144_2" is moved to the "Recycle bin". QModelIndex rbIndex = GTUtilsProjectTreeView::findIndex(os, "Recycle bin"); GTUtilsProjectTreeView::checkItem(os, folder2Name, rbIndex); // 5. Remove the folder "regression_test_3144_1". GTGlobals::sleep(); GTGlobals::sleep(); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, folder1Name)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ACTION_PROJECT__REMOVE_SELECTED)); GTMouseDriver::click(Qt::RightButton); // Expected state : folders "regression_test_3144_1" is shown in the "Recycle bin", folder "regression_test_3144_2" disappears. rbIndex = GTUtilsProjectTreeView::findIndex(os, "Recycle bin"); GTUtilsProjectTreeView::checkItem(os, folder1Name, rbIndex); GTUtilsProjectTreeView::checkItem(os, folder2Name, rbIndex); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3155) { // 1. Open "humam_T1" // Expected state: "Circular search" checkbox does not exist GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(200); // 2. Press "Find ORFs" tool button class CancelClicker : public Filler { public: CancelClicker(HI::GUITestOpStatus &_os) : Filler(_os, "ORFDialogBase") { } virtual void run() { QWidget *w = QApplication::activeWindow(); CHECK(NULL != w, ); QDialogButtonBox *buttonBox = w->findChild<QDialogButtonBox *>(QString::fromUtf8("buttonBox")); CHECK(NULL != buttonBox, ); QPushButton *button = buttonBox->button(QDialogButtonBox::Cancel); CHECK(NULL != button, ); QCheckBox *check = qobject_cast<QCheckBox *>(GTWidget::findWidget(os, "ckCircularSearch", NULL, GTGlobals::FindOptions(false))); CHECK(NULL == check, ); GTWidget::click(os, button); } }; GTUtilsDialog::waitForDialog(os, new CancelClicker(os)); GTWidget::click(os, GTAction::button(os, "Find ORFs")); } GUI_TEST_CLASS_DEFINITION(test_3156) { // 1. Connect to a shared database //QString conName = "ugene_gui_test"; Document *databaseDoc = GTUtilsSharedDatabaseDocument::connectToTestDatabase(os); GTUtilsProjectTreeView::expandProjectView(os); GTUtilsSharedDatabaseDocument::createFolder(os, databaseDoc, "/", "test_3156"); // 2. Open file "data/samples/Genbank/murine.gb" GTFile::copy(os, dataDir + "samples/Genbank/murine.gb", sandBoxDir + "test_3156_murine.gb"); GTFileDialog::openFile(os, sandBoxDir, "test_3156_murine.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); // 3. Drag the document item onto the DB item in project view QModelIndex from = GTUtilsProjectTreeView::findIndex(os, "test_3156_murine.gb"); QModelIndex to = GTUtilsProjectTreeView::findIndex(os, "test_3156"); GTUtilsProjectTreeView::dragAndDrop(os, from, to); GTGlobals::sleep(10000); // Expected state: a new folder has appeared in the DB, objects from the document have been imported into it. to = GTUtilsProjectTreeView::findIndex(os, "test_3156"); GTUtilsProjectTreeView::checkItem(os, "murine.gb", to); } class test_3165_messageBoxDialogFiller : public MessageBoxDialogFiller { public: test_3165_messageBoxDialogFiller(HI::GUITestOpStatus &os, QMessageBox::StandardButton _b) : MessageBoxDialogFiller(os, _b) { } virtual void run() override { QWidget *activeModal = QApplication::activeModalWidget(); QMessageBox *messageBox = qobject_cast<QMessageBox *>(activeModal); CHECK_SET_ERR(messageBox != NULL, "messageBox is NULL"); QAbstractButton *button = messageBox->button(b); CHECK_SET_ERR(button != NULL, "There is no such button in messagebox"); GTWidget::click(os, button); GTGlobals::sleep(500); GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::Save, "", "permissionBox")); } }; GUI_TEST_CLASS_DEFINITION(test_3165) { // 1. Set file read-only: "test/_common_data/scenarios/msa/ma.aln". GTFile::copy(os, testDir + "_common_data/scenarios/msa/ma.aln", sandBoxDir + "ma.aln"); GTFile::setReadOnly(os, sandBoxDir + "ma.aln"); // 2. Open it with UGENE. GTFileDialog::openFile(os, sandBoxDir, "ma.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(500); // 3. Change the alignment (e.g. insert a gap). GTUtilsMSAEditorSequenceArea::click(os, QPoint(1, 1)); GTKeyboardDriver::keyClick(Qt::Key_Space); // 4. Close the project. GTUtilsDialog::waitForDialog(os, new SaveProjectDialogFiller(os, QDialogButtonBox::No)); GTUtilsDialog::waitForDialog(os, new test_3165_messageBoxDialogFiller(os, QMessageBox::Yes)); GTUtilsDialog::waitForDialog(os, new GTFileDialogUtils(os, sandBoxDir, "test_3165_out.aln", GTFileDialogUtils::Save)); GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Close project"); GTGlobals::sleep(); //GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::Save)); // Expected state: you are offered to save the project. // 5. Do not save the project. // Expected state: you are offered to save the file. // 6. Accept the offering. // Expected state: UGENE notices that it can't rewrite the file, it offers you to save the file to another location. // 7. Save file anywhere. // Expected state: the project closes, the file is successfully saved, UGENE doesn't crash. //TODO: add this check after UGENE-3200 fix //GTUtilsProject::checkProject(os, GTUtilsProject::NotExists); CHECK_SET_ERR(GTFile::check(os, sandBoxDir + "test_3165_out.aln"), "file not saved"); GTGlobals::sleep(); // Current state: file is successfully saved, then UGENE crashes. } GUI_TEST_CLASS_DEFINITION(test_3170) { // 1. Open human_T1.fa. GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // Click "Hide zoom view" QWidget *toolbar = GTWidget::findWidget(os, "views_tool_bar_human_T1 (UCSC April 2002 chr7:115977709-117855134)"); CHECK_SET_ERR(toolbar != nullptr, "Cannot find views_tool_bar_human_T1(UCSC April 2002 chr7:115977709-117855134)"); GTWidget::click(os, GTWidget::findWidget(os, "show_hide_zoom_view", toolbar)); // 2. Select the region [301..350]. GTUtilsDialog::waitForDialog(os, new SelectSequenceRegionDialogFiller(os, 51, 102)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Select" << "Sequence region")); GTMenu::showContextMenu(os, GTWidget::findWidget(os, "ADV_single_sequence_widget_0")); // 3. Context menu -> Analyze -> Query with BLAST+. // 5. Select the database. // 6. Run. BlastAllSupportDialogFiller::Parameters blastParams; blastParams.runBlast = true; blastParams.dbPath = testDir + "_common_data/cmdline/external-tool-support/blastplus/human_T1/human_T1.nhr"; GTUtilsDialog::waitForDialog(os, new BlastAllSupportDialogFiller(blastParams, os)); GTMenu::clickMainMenuItem(os, QStringList() << "Actions" << "Analyze" << "Query with local BLAST+...", GTGlobals::UseMouse); GTUtilsTaskTreeView::waitTaskFinished(os); // Expected: the found annotations don't start from the position 1. bool found1 = GTUtilsAnnotationsTreeView::findRegion(os, "blast result", U2Region(51, 51)); CHECK_OP(os, ); CHECK_SET_ERR(found1, "Can not find the blast result"); bool found2 = GTUtilsAnnotationsTreeView::findRegion(os, "blast result", U2Region(1, 52)); CHECK_OP(os, ); CHECK_SET_ERR(!found2, "Wrong blast result"); } GUI_TEST_CLASS_DEFINITION(test_3175) { // 1. Open "_common_data/scenarios/msa/ma.aln". GTFileDialog::openFile(os, testDir + "_common_data/scenarios/msa/ma.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); // Expected: the first sequence is "TAAGACTTCTAA". const QString firstSequence = GTUtilsMSAEditorSequenceArea::getSequenceData(os, 0); CHECK_SET_ERR("TAAGACTTCTAA" == firstSequence, "MSA changing is failed"); } GUI_TEST_CLASS_DEFINITION(test_3180) { //1. Open "samples/FASTA/human_T1.fa". //2. Click the "Find restriction sites" button on the main toolbar. //3. Accept the dialog. //Expected: the task becomes cancelled. GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Restriction Sites")); GTWidget::click(os, GTWidget::findWidget(os, "AutoAnnotationUpdateAction")); GTGlobals::systemSleep(); foreach (Task *task, AppContext::getTaskScheduler()->getTopLevelTasks()) { if (task->getTaskName() != "Auto-annotations update task") { continue; } GTGlobals::systemSleep(); task->cancel(); } GTGlobals::sleep(); CHECK_SET_ERR(AppContext::getTaskScheduler()->getTopLevelTasks().isEmpty(), "Task is not cancelled"); } GUI_TEST_CLASS_DEFINITION(test_3209_1) { // BLAST+ from file BlastAllSupportDialogFiller::Parameters blastParams; blastParams.runBlast = true; blastParams.programNameText = "blastn"; blastParams.dbPath = testDir + "_common_data/cmdline/external-tool-support/blastplus/human_T1/human_T1.nhr"; blastParams.withInputFile = true; blastParams.inputPath = dataDir + "samples/FASTA/human_T1.fa"; GTUtilsDialog::waitForDialog(os, new BlastAllSupportDialogFiller(blastParams, os)); GTMenu::clickMainMenuItem(os, QStringList() << "Tools" << "BLAST" << "BLAST+ search..."); GTUtilsTaskTreeView::waitTaskFinished(os); bool found = GTUtilsAnnotationsTreeView::findRegion(os, "blast result", U2Region(5061, 291)); CHECK_OP(os, ); CHECK_SET_ERR(found, "Can not find the blast result"); } GUI_TEST_CLASS_DEFINITION(test_3214) { GTUtilsWorkflowDesigner::openWorkflowDesigner(os); GTUtilsWorkflowDesigner::addAlgorithm(os, "Extract Consensus from Alignment as Sequence"); GTMouseDriver::moveTo(GTUtilsWorkflowDesigner::getItemCenter(os, "Extract Consensus from Alignment as Sequence")); GTMouseDriver::click(); GTUtilsWorkflowDesigner::setParameter(os, "Threshold", 49, GTUtilsWorkflowDesigner::spinValue); GTUtilsWorkflowDesigner::setParameter(os, "Algorithm", 0, GTUtilsWorkflowDesigner::comboValue); CHECK_SET_ERR(GTUtilsWorkflowDesigner::getParameter(os, "Threshold") == "50", "Wrong parameter"); GTUtilsWorkflowDesigner::addAlgorithm(os, "Extract Consensus from Alignment as Text"); GTMouseDriver::moveTo(GTUtilsWorkflowDesigner::getItemCenter(os, "Extract Consensus from Alignment as Text")); GTMouseDriver::click(); GTUtilsWorkflowDesigner::setParameter(os, "Algorithm", 0, GTUtilsWorkflowDesigner::comboValue); CHECK_SET_ERR(GTUtilsWorkflowDesigner::getAllParameters(os).size() == 1, "Too many parameters"); } GUI_TEST_CLASS_DEFINITION(test_3216_1) { // 1. Open "test/_common_data/genbank/1anot_1seq.gen" file. QDir().mkpath(sandBoxDir + "test_3216"); GTFile::copy(os, testDir + "_common_data/genbank/1anot_1seq.gen", sandBoxDir + "test_3216/test_3216_1.gen"); GTFileDialog::openFile(os, sandBoxDir + "test_3216", "test_3216_1.gen"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Add a qualifier with the value "012345678901234567890123456789012345678901234567890123456789". const QString expectedValue = "012345678901234567890123456789012345678901234567890123456789"; GTUtilsAnnotationsTreeView::createQualifier(os, "test_3216_1", expectedValue, "CDS"); // 3. Save the file, reopen the file. // Expected state: the qualifier value is the same. GTUtilsDocument::saveDocument(os, "test_3216_1.gen"); GTUtilsMdi::click(os, GTGlobals::Close); GTUtilsDocument::removeDocument(os, "test_3216_1.gen"); GTFileDialog::openFile(os, sandBoxDir + "test_3216", "test_3216_1.gen"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsAnnotationsTreeView::selectItems(os, QStringList() << "CDS"); const QString actualValue = GTUtilsAnnotationsTreeView::getQualifierValue(os, "test_3216_1", "CDS"); CHECK_SET_ERR(expectedValue == actualValue, QString("The qualifier value is incorrect: expect '%1', got '%2'").arg(expectedValue).arg(actualValue)); } GUI_TEST_CLASS_DEFINITION(test_3216_2) { // 1. Open "test/_common_data/genbank/1anot_1seq.gen" file. QDir().mkpath(sandBoxDir + "test_3216"); GTFile::copy(os, testDir + "_common_data/genbank/1anot_1seq.gen", sandBoxDir + "test_3216/test_3216_2.gen"); GTFileDialog::openFile(os, sandBoxDir + "test_3216", "test_3216_2.gen"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Add a qualifier with the value "012345678901234567890123456789 012345678901234567890123456789". const QString expectedValue = "012345678901234567890123456789 012345678901234567890123456789"; GTUtilsAnnotationsTreeView::createQualifier(os, "test_3216_2", expectedValue, "CDS"); // 3. Save the file, reopen the file. // Expected state: the qualifier value is the same. GTUtilsDocument::saveDocument(os, "test_3216_2.gen"); GTUtilsMdi::click(os, GTGlobals::Close); GTUtilsDocument::removeDocument(os, "test_3216_2.gen"); GTFileDialog::openFile(os, sandBoxDir + "test_3216", "test_3216_2.gen"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsAnnotationsTreeView::selectItems(os, QStringList() << "CDS"); const QString actualValue = GTUtilsAnnotationsTreeView::getQualifierValue(os, "test_3216_2", "CDS"); CHECK_SET_ERR(expectedValue == actualValue, QString("The qualifier value is incorrect: expect '%1', got '%2'").arg(expectedValue).arg(actualValue)); } GUI_TEST_CLASS_DEFINITION(test_3216_3) { // 1. Open "test/_common_data/genbank/1anot_1seq.gen" file. QDir().mkpath(sandBoxDir + "test_3216"); GTFile::copy(os, testDir + "_common_data/genbank/1anot_1seq.gen", sandBoxDir + "test_3216/test_3216_3.gen"); GTFileDialog::openFile(os, sandBoxDir + "test_3216", "test_3216_3.gen"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Add a qualifier with the value "012345678901234567890123456789 0 1 2345678901234567890123456789". const QString expectedValue = "012345678901234567890123456789 0 1 2345678901234567890123456789"; GTUtilsAnnotationsTreeView::createQualifier(os, "test_3216_3", expectedValue, "CDS"); // 3. Save the file, reopen the file. // Expected state: the qualifier value is the same. GTUtilsDocument::saveDocument(os, "test_3216_3.gen"); GTUtilsMdi::click(os, GTGlobals::Close); GTUtilsDocument::removeDocument(os, "test_3216_3.gen"); GTFileDialog::openFile(os, sandBoxDir + "test_3216", "test_3216_3.gen"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsAnnotationsTreeView::selectItems(os, QStringList() << "CDS"); const QString actualValue = GTUtilsAnnotationsTreeView::getQualifierValue(os, "test_3216_3", "CDS"); CHECK_SET_ERR(expectedValue == actualValue, QString("The qualifier value is incorrect: expect '%1', got '%2'").arg(expectedValue).arg(actualValue)); } GUI_TEST_CLASS_DEFINITION(test_3218) { // 1. Open "test/_common_data/genbank/big_feature_region.gb". GTLogTracer l; GTFileDialog::openFile(os, testDir + "_common_data/genbank/", "big_feature_region.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); // Expected state : file is opened, there are no errors in the log GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3220) { //1. Open human_T1.fa // GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsSequenceView::checkSequenceViewWindowIsActive(os); //2. Add an annotation GTUtilsDialog::waitForDialog(os, new CreateAnnotationWidgetFiller(os, true, "DDD", "D", "10..16")); GTMenu::clickMainMenuItem(os, QStringList() << "Actions" << "Add" << "New annotation..."); //2. Add qualifier with quotes GTUtilsDialog::waitForDialog(os, new EditQualifierFiller(os, "newqualifier", "val\"", GTGlobals::UseMouse, false)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ADV_MENU_ADD << "add_qualifier_action")); GTMouseDriver::moveTo(GTUtilsAnnotationsTreeView::getItemCenter(os, "D")); GTMouseDriver::click(Qt::RightButton); //3. Add another qualifier to the same annotation GTUtilsDialog::waitForDialog(os, new EditQualifierFiller(os, "newqualifier2", "val\"2", GTGlobals::UseMouse, false)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ADV_MENU_ADD << "add_qualifier_action")); GTMouseDriver::moveTo(GTUtilsAnnotationsTreeView::getItemCenter(os, "D")); GTMouseDriver::click(Qt::RightButton); GTUtilsDialog::waitAllFinished(os); //4. Save the file and reload it GTUtilsDocument::unloadDocument(os, "human_T1.fa", true); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDocument::loadDocument(os, "human_T1.fa"); GTUtilsSequenceView::checkSequenceViewWindowIsActive(os); GTMouseDriver::moveTo(GTUtilsAnnotationsTreeView::getItemCenter(os, "D")); GTMouseDriver::click(Qt::LeftButton); QTreeWidgetItem *generalItem = GTUtilsAnnotationsTreeView::findItem(os, "D"); AVAnnotationItem *annotation = dynamic_cast<AVAnnotationItem *>(generalItem); CHECK_SET_ERR(annotation != nullptr, "Annotation is not found"); CHECK_SET_ERR(annotation->annotation->findFirstQualifierValue("newqualifier") == "val\"", "Qualifier is not found"); CHECK_SET_ERR(annotation->annotation->findFirstQualifierValue("newqualifier2") == "val\"2", "Qualifier 2 is not found"); } GUI_TEST_CLASS_DEFINITION(test_3221) { // 1. Open "data/samples/FASTA/human_T1.fa". // 2. Open "Find pattern" options panel tab. // 3. Enter pattern with long annotation name(>15 characters). // 4. Check "Use pattern name" check box // 5. Press "Create annotations" button // Expected state: annotations created without errors. GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(200); GTUtilsOptionPanelSequenceView::openTab(os, GTUtilsOptionPanelSequenceView::Search); GTUtilsOptionPanelSequenceView::enterPattern(os, ">long_annotation_name"); GTKeyboardDriver::keyClick(Qt::Key_Enter, Qt::ControlModifier); GTKeyboardDriver::keySequence("ACGTAAA"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsOptionPanelSequenceView::openAnnotationParametersShowHideWidget(os, true); GTCheckBox::setChecked(os, GTWidget::findExactWidget<QCheckBox *>(os, "chbUsePatternNames"), true); GTUtilsOptionPanelSequenceView::clickGetAnnotation(os); GTUtilsTaskTreeView::waitTaskFinished(os); QTreeWidgetItem *annotationGroup = GTUtilsAnnotationsTreeView::findItem(os, "long_annotation_name (0, 10)"); CHECK_SET_ERR(NULL != annotationGroup, "Annotations have not been found"); } GUI_TEST_CLASS_DEFINITION(test_3223) { GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsOptionPanelSequenceView::openTab(os, GTUtilsOptionPanelSequenceView::Search); QString pattern = ">zzz\n" "ACCTGAA\n" ">yyy\n" "ATTGACA\n"; GTUtilsOptionPanelSequenceView::enterPattern(os, pattern, true); GTWidget::click(os, GTWidget::findWidget(os, "ArrowHeader_Annotation parameters")); QCheckBox *chbUsePatternNames = GTWidget::findExactWidget<QCheckBox *>(os, "chbUsePatternNames"); GTCheckBox::setChecked(os, chbUsePatternNames, true); GTWidget::click(os, GTWidget::findWidget(os, "getAnnotationsPushButton")); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsAnnotationsTreeView::findItem(os, "yyy (0, 32)"); GTUtilsAnnotationsTreeView::findItem(os, "zzz (0, 34)"); } GUI_TEST_CLASS_DEFINITION(test_3226) { //1. Create a workflow with a 'Read File URL(s)' element. GTUtilsWorkflowDesigner::openWorkflowDesigner(os); GTUtilsWorkflowDesigner::addAlgorithm(os, "Read File URL(s)"); //2. Setup alias 'in' for input path. QMap<QPoint *, QString> map; QPoint p(1, 0); map[&p] = "in"; GTUtilsDialog::waitForDialog(os, new AliasesDialogFiller(os, map)); GTWidget::click(os, GTAction::button(os, "Set parameter aliases")); //3. Copy and paste the 'Read File URL(s)' element. GTUtilsWorkflowDesigner::click(os, "Read File URL(s)"); GTKeyboardUtils::copy(os); //GTWidget::click(os, GTAction::button(os, "Copy action")); GTKeyboardUtils::paste(os); //4. Save the workflow. QString path = sandBoxDir + "test_3226_workflow.uwl"; GTUtilsDialog::waitForDialog(os, new WorkflowMetaDialogFiller(os, path, "")); GTWidget::click(os, GTAction::button(os, "Save workflow action")); //5. Close current workflow. GTWidget::click(os, GTAction::button(os, "New workflow action")); //7. Open the saved workflow. GTLogTracer l; GTUtilsWorkflowDesigner::loadWorkflow(os, path); //Expected state: the saved workflow is opened, there are no errors in the log, the alias it set only for the one element. GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3229) { // 1. Create the "read sequence -> write sequence" workflow. GTUtilsWorkflowDesigner::openWorkflowDesigner(os); WorkflowProcessItem *read = GTUtilsWorkflowDesigner::addElement(os, "Read Sequence", true); WorkflowProcessItem *write = GTUtilsWorkflowDesigner::addElement(os, "Write Sequence", true); GTUtilsWorkflowDesigner::connect(os, read, write); // 2. Set input a single file human_T1 GTUtilsWorkflowDesigner::click(os, read); GTUtilsWorkflowDesigner::setDatasetInputFile(os, dataDir + "samples/FASTA/human_T1.fa"); // 3. Set the output path: ../test.fa or ./test.fa Output file GTUtilsWorkflowDesigner::click(os, write); GTUtilsWorkflowDesigner::setParameter(os, "Output file", "./test.fa", GTUtilsWorkflowDesigner::textValue); // 4. Run the workflow. GTUtilsWorkflowDesigner::runWorkflow(os); GTUtilsTaskTreeView::waitTaskFinished(os); // Expected state: there is a single result file on the WD dashboard. const QStringList outputFiles = GTUtilsDashboard::getOutputFiles(os); const int expectedFilesCount = 1; CHECK_SET_ERR(expectedFilesCount == outputFiles.size(), QString("An unexpected count of output files: expected %1, got %2") .arg(expectedFilesCount) .arg(outputFiles.size())); const QString expectedFileName = "test.fa"; CHECK_SET_ERR(expectedFileName == outputFiles.first(), QString("An unexpected result file name: expected '%1', got '%2'") .arg(expectedFileName) .arg(outputFiles.first())); } GUI_TEST_CLASS_DEFINITION(test_3245) { // 1. Open "data/samples/CLUSTALW/COI.aln". GTFileDialog::openFile(os, dataDir + "/samples/CLUSTALW/", "COI.aln"); GTUtilsMsaEditor::checkMsaEditorWindowIsActive(os); // 2. Ensure that there is a single menu item (Create new color scheme) in the {Colors -> Custom schemes} // submenu of the context menu. Click it. GTUtilsOptionPanelMsa::openTab(os, GTUtilsOptionPanelMsa::Highlighting); GTUtilsOptionPanelMsa::checkTabIsOpened(os, GTUtilsOptionPanelMsa::Highlighting); QComboBox *combo = qobject_cast<QComboBox *>(GTWidget::findWidget(os, "colorScheme")); const int initialItemsNumber = combo->count(); // 3. Create a new color scheme, accept the preferences dialog. const QString colorSchemeName = "test scheme"; GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << MSAE_MENU_APPEARANCE << "Colors" << "Custom schemes" << "Create new color scheme")); GTUtilsDialog::waitForDialog(os, new NewColorSchemeCreator(os, colorSchemeName, NewColorSchemeCreator::nucl)); QWidget *area = GTUtilsMSAEditorSequenceArea::getSequenceArea(os); GTWidget::click(os, area, Qt::RightButton); // 4. Ensure that the new scheme is added to the context menu. Call the preferences dialog again. // 5. Remove the custom scheme and cancel the preferences dialog. GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << MSAE_MENU_APPEARANCE << "Colors" << "Custom schemes" << colorSchemeName)); QWidget *area1 = GTUtilsMSAEditorSequenceArea::getSequenceArea(os); GTWidget::click(os, area1, Qt::RightButton); combo = qobject_cast<QComboBox *>(GTWidget::findWidget(os, "colorScheme")); CHECK_SET_ERR(combo->count() - 1 == initialItemsNumber, "color scheme hasn't been added to the Options Panel"); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << MSAE_MENU_APPEARANCE << "Colors" << "Custom schemes" << "Create new color scheme")); GTUtilsDialog::waitForDialog(os, new NewColorSchemeCreator(os, colorSchemeName, NewColorSchemeCreator::nucl, NewColorSchemeCreator::Delete, true)); QWidget *area2 = GTUtilsMSAEditorSequenceArea::getSequenceArea(os); GTWidget::click(os, area2, Qt::RightButton); // Expected state: the scheme presents in the context menu, it is shown in the preferences dialog. GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << MSAE_MENU_APPEARANCE << "Colors" << "Custom schemes" << colorSchemeName)); QWidget *area3 = GTUtilsMSAEditorSequenceArea::getSequenceArea(os); GTWidget::click(os, area3, Qt::RightButton); combo = qobject_cast<QComboBox *>(GTWidget::findWidget(os, "colorScheme")); CHECK_SET_ERR(combo->count() - 1 == initialItemsNumber, "color scheme hasn't been added to the Options Panel"); } GUI_TEST_CLASS_DEFINITION(test_3250) { //1. Connect to a shared database. //2. Right click on the document in the project view. //Expected: there are no the "Export/Import" menu for the database connection. GTUtilsSharedDatabaseDocument::connectToTestDatabase(os); QPoint p = GTUtilsProjectTreeView::getItemCenter(os, "ugene_gui_test"); GTMouseDriver::moveTo(p); GTUtilsDialog::waitForDialog(os, new PopupChecker(os, QStringList() << "Export/Import", PopupChecker::NotExists)); GTMouseDriver::click(Qt::RightButton); GTGlobals::sleep(); } GUI_TEST_CLASS_DEFINITION(test_3253) { /* 1. Open "data/samples/ABIF/A01.abi". * 2. Minimaze annotation tree view * Expected state: Chromatagram view resized */ GTFileDialog::openFile(os, dataDir + "/samples/ABIF/", "A01.abi"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(); QSplitterHandle *splitterHandle = qobject_cast<QSplitterHandle *>(GTWidget::findWidget(os, "qt_splithandle_", GTUtilsMdi::activeWindow(os))); CHECK_SET_ERR(NULL != splitterHandle, "splitterHandle is not present"); QWidget *chromaView = GTWidget::findWidget(os, "chromatogram_view_A1#berezikov"); CHECK_SET_ERR(NULL != chromaView, "chromaView is NULL"); QWidget *annotationTreeWidget = GTWidget::findWidget(os, "annotations_tree_widget"); CHECK_SET_ERR(NULL != annotationTreeWidget, "annotationTreeWidget is NULL"); QSize startSize = chromaView->size(); GTMouseDriver::moveTo(QPoint(annotationTreeWidget->mapToGlobal(annotationTreeWidget->pos()).x() + 100, annotationTreeWidget->mapToGlobal(annotationTreeWidget->pos()).y())); GTMouseDriver::press(); GTMouseDriver::moveTo(QPoint(annotationTreeWidget->mapToGlobal(annotationTreeWidget->pos()).x() + 100, annotationTreeWidget->mapToGlobal(annotationTreeWidget->pos()).y() + annotationTreeWidget->size().height())); GTMouseDriver::release(); GTGlobals::sleep(); QSize endSize = chromaView->size(); CHECK_SET_ERR(startSize != endSize, "chromatogram_view is not resized"); } GUI_TEST_CLASS_DEFINITION(test_3253_1) { /* 1. Open "data/samples/ABIF/A01.abi". * 2. Toggle Show Detail View * 3. Resize annotation tree view * Expected state: Detail View view resized */ GTFileDialog::openFile(os, dataDir + "/samples/ABIF/", "A01.abi"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(); QWidget *annotationTreeWidget = GTWidget::findWidget(os, "annotations_tree_widget"); QWidget *toolbar = GTWidget::findWidget(os, "views_tool_bar_A1#berezikov"); CHECK_SET_ERR(toolbar != NULL, "Cannot find views_tool_bar_A1#berezikov"); QToolButton *showDetView = qobject_cast<QToolButton *>(GTWidget::findWidget(os, "show_hide_details_view", toolbar)); CHECK_SET_ERR(showDetView != NULL, "Cannot find show_hide_details_view widget or cast it to QToolButton"); if (!showDetView->isChecked()) { GTWidget::click(os, showDetView); } GTWidget::click(os, GTWidget::findWidget(os, "show_hide_overview", toolbar)); GTGlobals::sleep(); GTWidget::click(os, GTWidget::findWidget(os, "show_hide_zoom_view", toolbar)); GTGlobals::sleep(); GTWidget::click(os, GTWidget::findWidget(os, "CHROMA_ACTION", toolbar)); GTGlobals::sleep(); QSplitterHandle *splitterHandle = qobject_cast<QSplitterHandle *>(GTWidget::findWidget(os, "qt_splithandle_det_view_A1#berezikov")); CHECK_SET_ERR(NULL != splitterHandle, "splitterHandle is not present"); QWidget *detView = GTWidget::findWidget(os, "render_area_A1#berezikov"); QSize startSize = detView->size(); GTMouseDriver::moveTo(QPoint(annotationTreeWidget->mapToGlobal(annotationTreeWidget->pos()).x() + 100, annotationTreeWidget->mapToGlobal(annotationTreeWidget->pos()).y())); GTMouseDriver::press(); GTMouseDriver::moveTo(QPoint(annotationTreeWidget->mapToGlobal(annotationTreeWidget->pos()).x() + 100, annotationTreeWidget->mapToGlobal(annotationTreeWidget->pos()).y() - detView->size().height())); GTMouseDriver::release(); GTThread::waitForMainThread(); GTGlobals::sleep(5000); QSize endSize = detView->size(); CHECK_SET_ERR(startSize != endSize, "detView is not resized"); } GUI_TEST_CLASS_DEFINITION(test_3253_2) { /* 1. Open "data/samples/ABIF/A01.abi". * 2. Open GC Content (%) graph * 3. Close the chomatogram view * Expected state: GC Content (%) graph view resized. */ GTFileDialog::openFile(os, dataDir + "/samples/ABIF/", "A01.abi"); GTUtilsSequenceView::checkSequenceViewWindowIsActive(os); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "GC Content (%)")); GTWidget::click(os, GTWidget::findWidget(os, "GraphMenuAction", GTUtilsSequenceView::getSeqWidgetByNumber(os, 0))); GTUtilsDialog::waitAllFinished(os); GTUtilsTaskTreeView::waitTaskFinished(os); QWidget *graphView = GTWidget::findWidget(os, "GSequenceGraphViewRenderArea"); QSize startSize = graphView->size(); // Hide the chromatogram. GTWidget::click(os, GTWidget::findWidget(os, "CHROMA_ACTION")); QSplitter *splitter = qobject_cast<QSplitter *>(GTWidget::findWidget(os, "single_sequence_view_splitter")); CHECK_SET_ERR(splitter != nullptr, "Splitter was not found"); GTSplitter::moveHandle(os, splitter, graphView->height() / 2, 2); GTThread::waitForMainThread(); QSize endSize = graphView->size(); CHECK_SET_ERR(startSize != endSize, "graphView is not resized, size: " + QString::number(endSize.width()) + "x" + QString::number(endSize.height())); } GUI_TEST_CLASS_DEFINITION(test_3255) { // 1. Open "data/samples/Assembly/chrM.sam.bam". // Expected state: an import dialog appears. // 2. Set any valid output path (or use default), check the "Import unmapped reads" option and click the "Import" button. // Expected state: the task finished without errors. GTLogTracer l; GTUtilsDialog::waitForDialog(os, new ImportBAMFileFiller(os, sandBoxDir + "test_3255/test_3255.ugenedb", "", "", true)); GTFileDialog::openFile(os, testDir + "_common_data/bam/", "1.bam"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3263) { // 1. Open "_common_data/alphabets/standard_dna_rna_amino_1000.fa" GTUtilsDialog::waitForDialog(os, new SequenceReadingModeSelectorDialogFiller(os)); GTUtilsProject::openFile(os, testDir + "_common_data/alphabets/standard_dna_rna_amino_1000.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Open CV for the first sequence QWidget *cvButton1 = GTWidget::findWidget(os, "CircularViewAction", GTWidget::findWidget(os, "ADV_single_sequence_widget_0")); QWidget *cvButton2 = GTWidget::findWidget(os, "CircularViewAction", GTWidget::findWidget(os, "ADV_single_sequence_widget_1")); GTWidget::click(os, cvButton2); // 3. Open CV for the second sequence GTWidget::click(os, cvButton1); // 4. Click CV button for the first sequence (turn it off and on again) few times QWidget *CV_ADV_single_sequence_widget_1 = GTWidget::findWidget(os, "CV_ADV_single_sequence_widget_1"); QRect geometry = CV_ADV_single_sequence_widget_1->geometry(); for (int i = 0; i < 5; i++) { GTWidget::click(os, cvButton1); GTGlobals::sleep(1000); GTWidget::click(os, cvButton1); GTGlobals::sleep(1000); CHECK_SET_ERR(geometry == CV_ADV_single_sequence_widget_1->geometry(), "geometry changed"); } // See the result on the attached screenshot. } GUI_TEST_CLASS_DEFINITION(test_3266) { //1. Connect to a shared database. Document *doc = GTUtilsSharedDatabaseDocument::connectToTestDatabase(os); //2. Create a folder "1" somewhere. GTUtilsSharedDatabaseDocument::createFolder(os, doc, "/", "regression_3266_1"); //3. Create a folder "2" in the folder "1". GTUtilsSharedDatabaseDocument::createFolder(os, doc, "/regression_3266_1", "regression_3266_2"); //4. Remove the folder "2". GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "regression_3266_2")); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ACTION_PROJECT__REMOVE_SELECTED)); GTMouseDriver::click(Qt::RightButton); //Expected state: the folder "2" is in the Recycle bin. GTUtilsSharedDatabaseDocument::checkItemExists(os, doc, "/Recycle bin/regression_3266_2"); //5. Create another folder "2" in the folder "1". GTUtilsSharedDatabaseDocument::createFolder(os, doc, "/regression_3266_1", "regression_3266_2"); //6. Remove the folder "1". GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "regression_3266_1")); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ACTION_PROJECT__REMOVE_SELECTED)); GTMouseDriver::click(Qt::RightButton); //Expected state: folders "1" and "2" both are in the Recycle bin. GTUtilsSharedDatabaseDocument::checkItemExists(os, doc, "/Recycle bin/regression_3266_1"); GTUtilsSharedDatabaseDocument::checkItemExists(os, doc, "/Recycle bin/regression_3266_2"); } GUI_TEST_CLASS_DEFINITION(test_3270) { // 1. Open "data/samples/FASTA/human_T1.fa". GTFileDialog::openFile(os, dataDir + "samples/FASTA/human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Open "Search in Sequence" options panel tab. GTUtilsOptionPanelSequenceView::openTab(os, GTUtilsOptionPanelSequenceView::Search); // 3. Open "Annotation parameters" group and check "Use pattern name" option. GTUtilsOptionPanelSequenceView::openAnnotationParametersShowHideWidget(os); GTUtilsOptionPanelSequenceView::setUsePatternName(os); // 4. Set next patterns: // > pattern1 // TGGGGGCCAATA // > pattern2 // GGCAGAAACC QString pattern = "> pattern1" "\n" "TGGGGGCCAATA" "\n\n" "> pattern2" "\n" "GGCAGAAACC"; GTUtilsOptionPanelSequenceView::enterPattern(os, pattern, true); // Expected state: there is a warning: "annotation names are invalid...". QString warning = GTUtilsOptionPanelSequenceView::getHintText(os); CHECK_SET_ERR(warning.contains("annotation names are invalid"), QString("An incorrect warning: '%1'").arg(warning)); // 5. Click "Create annotations" button. GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsOptionPanelSequenceView::clickGetAnnotation(os); // Expected state: there are two annotations with names "pattern1" and "pattern2". GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsAnnotationsTreeView::findItem(os, "pattern1"); GTUtilsAnnotationsTreeView::findItem(os, "pattern2"); // 6. Set next pattern: // >gi|92133205|dbj|BD295338.1| A method for providing and controling the rice fertility, and discerning the presence of the rice restorer gene by using the rice restorer gene to the rice BT type cytoplasmic male sterility // TGGGGATTCT pattern = ">gi|92133205|dbj|BD295338.1| A method for providing and controling the rice fertility, and discerning the presence of the rice restorer gene by using the rice restorer gene to the rice BT type cytoplasmic male sterility" "\n" "TGGGGATTCT"; GTUtilsOptionPanelSequenceView::enterPattern(os, pattern, true); // Expected state: there are no warnings. warning = GTUtilsOptionPanelSequenceView::getHintText(os); CHECK_SET_ERR(!warning.contains("Warning"), QString("An unexpected warning: '%1'").arg(warning)); // 6. Click "Create annotations" button. GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsOptionPanelSequenceView::clickGetAnnotation(os); // Expected state: there is an additional annotation with name "gi|92133205|dbj|BD295338.1| A method for providing and controling the rice fertility, and discerning the presence of the rice restorer gene by using the rice restorer gene to the rice BT type cytoplasmic male sterility". GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsAnnotationsTreeView::findItem(os, "gi|92133205|dbj|BD295338.1| A method for providing and controling the rice fertility, and discerning the presence of the rice restorer gene by using the rice restorer gene to the rice BT type cytoplasmic male sterility"); } GUI_TEST_CLASS_DEFINITION(test_3274) { QStringList expectedNames; QList<ADVSingleSequenceWidget *> seqWidgets; expectedNames << "seq1" << "seq3" << "seq5"; seqWidgets = GTUtilsProject::openFileExpectSequences(os, testDir + "_common_data/alphabets/", "standard_dna_rna_amino_1000.fa", expectedNames); CHECK_OP_SET_ERR(os, "Failed to open sequences!"); ADVSingleSequenceWidget *seq1Widget = seqWidgets.at(0); ADVSingleSequenceWidget *seq3Widget = seqWidgets.at(1); GTUtilsCv::cvBtn::click(os, seq3Widget); GTUtilsCv::cvBtn::click(os, seq1Widget); QWidget *circularView = GTWidget::findWidget(os, "CV_ADV_single_sequence_widget_0"); CHECK_OP_SET_ERR(os, "Failed to open circular view!"); GTUtilsDialog::waitForDialog(os, new CircularViewExportImage(os, testDir + "_common_data/scenarios/sandbox/image.jpg", "", "seq3")); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ADV_MENU_EXPORT << "Save circular view as image")); GTWidget::click(os, circularView, Qt::RightButton); } GUI_TEST_CLASS_DEFINITION(test_3276) { // 1. Open "data/samples/CLUSTALW/COI.aln". GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW/", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Build a phylogenetic tree synchronized with the alignment. QDir().mkdir(QFileInfo(sandBoxDir + "test_3276/COI.nwk").dir().absolutePath()); GTUtilsDialog::waitForDialog(os, new BuildTreeDialogFiller(os, sandBoxDir + "test_3276/COI.wnk", 0, 0, true)); GTWidget::click(os, GTToolbar::getWidgetForActionName(os, GTToolbar::getToolbar(os, MWTOOLBAR_ACTIVEMDI), "Build Tree")); GTUtilsTaskTreeView::waitTaskFinished(os); // 3. Rename the first and the second sequences to "1". GTUtilsMSAEditorSequenceArea::renameSequence(os, "Isophya_altaica_EF540820", "1"); GTUtilsMSAEditorSequenceArea::renameSequence(os, "Bicolorana_bicolor_EF540830", "1"); // 4. Remove the first sequence. GTUtilsMSAEditorSequenceArea::removeSequence(os, "1"); // 5. Ensure that the "Sort alignment by tree" button on the tree view toolbar is disabled. QAction *sortAction = GTAction::findAction(os, "Sort Alignment"); CHECK_SET_ERR(NULL != sortAction, "'Sort alignment by tree' was not found"); CHECK_SET_ERR(!sortAction->isEnabled(), "'Sort alignment by tree' is unexpectedly enabled"); } GUI_TEST_CLASS_DEFINITION(test_3277) { // Open "data/samples/CLUSTALW/COI.aln". GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); QWidget *seqArea = GTWidget::findWidget(os, "msa_editor_sequence_area"); QColor before = GTWidget::getColor(os, seqArea, QPoint(1, 1)); QString bName = before.name(); // Open the "Highlighting" options panel tab. GTWidget::click(os, GTWidget::findWidget(os, "OP_MSA_HIGHLIGHTING")); // Set any reference sequence. GTUtilsMSAEditorSequenceArea::click(os, QPoint(-5, 5)); GTWidget::click(os, GTWidget::findWidget(os, "addSeq")); // Select different highlighting schemes. QComboBox *highlightingScheme = qobject_cast<QComboBox *>(GTWidget::findWidget(os, "highlightingScheme")); GTComboBox::setIndexWithText(os, highlightingScheme, "Gaps"); // Current state: the highlighting doesn't work for all sequences except the reference sequence. QColor after = GTWidget::getColor(os, seqArea, QPoint(1, 1)); QString aName = after.name(); CHECK_SET_ERR(before != after, "colors not changed"); } GUI_TEST_CLASS_DEFINITION(test_3279) { // Open "data/samples/CLUSTALW/COI.aln". GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); // Open "Statistics" options panel tab. GTWidget::click(os, GTWidget::findWidget(os, "OP_SEQ_STATISTICS_WIDGET")); // Set any reference sequence. GTUtilsMSAEditorSequenceArea::click(os, QPoint(-5, 5)); GTWidget::click(os, GTWidget::findWidget(os, "addSeq")); // Set "Show distances column" option. QCheckBox *showDistancesColumnCheck = qobject_cast<QCheckBox *>(GTWidget::findWidget(os, "showDistancesColumnCheck")); GTCheckBox::setChecked(os, showDistancesColumnCheck, true); // Expected state: the addition column is shown, it contains distances to the reference sequence. QString num1 = GTUtilsMSAEditorSequenceArea::getSimilarityValue(os, 1); QString num3 = GTUtilsMSAEditorSequenceArea::getSimilarityValue(os, 3); CHECK_SET_ERR(num1 == "19%", "unexpected sumilarity value an line 1: " + num1); CHECK_SET_ERR(num3 == "12%", "unexpected sumilarity value an line 3: " + num3); // Current state: the addition column is shown, it contains sequence names. } GUI_TEST_CLASS_DEFINITION(test_3283) { // 1. Open "data/Samples/MMDB/1CRN.prt". GTFileDialog::openFile(os, dataDir + "samples/MMDB", "1CRN.prt"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Click to any annotation on the panoramic view. GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "1CRN chain 1 annotation")); QTreeWidgetItem *item = GTUtilsAnnotationsTreeView::findItem(os, "sec_struct (0, 5)"); GTMouseDriver::moveTo(GTTreeWidget::getItemCenter(os, item)); GTMouseDriver::click(); } GUI_TEST_CLASS_DEFINITION(test_3287) { GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW/", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); CHECK_OP(os, ); ImageExportFormFiller::Parameters params; params.fileName = testDir + "_common_data/scenarios/sandbox/test_3287.bmp"; params.format = "BMP"; GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Export as image")); GTUtilsDialog::waitForDialog(os, new ImageExportFormFiller(os, params)); QWidget *overview = GTWidget::findWidget(os, "msa_overview_area_graph"); CHECK_OP(os, ); GTWidget::click(os, overview, Qt::RightButton); GTUtilsTaskTreeView::waitTaskFinished(os); QImage image(params.fileName); CHECK_SET_ERR(70 == image.height(), "Wrong image height"); } GUI_TEST_CLASS_DEFINITION(test_3288) { //1. Open "data/samples/CLUSTALW/HIV-1.aln". GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW/", "HIV-1.aln"); GTUtilsMsaEditor::checkMsaEditorWindowIsActive(os); //2. Click the "Build tree" button on the main toolbar. GTUtilsDialog::waitForDialog(os, new BuildTreeDialogFillerPhyML(os, true)); GTWidget::click(os, GTAction::button(os, "Build Tree")); //3. Select the "PhyML" tool, set "Equilibrium frequencies" option to "opti,ized", build the tree QProgressBar *taskProgressBar = GTWidget::findExactWidget<QProgressBar *>(os, "taskProgressBar"); int percent = 0; for (int time = 0; time < GT_OP_WAIT_MILLIS && percent == 0; time += GT_OP_CHECK_MILLIS) { GTGlobals::sleep(time > 0 ? GT_OP_CHECK_MILLIS : 0); percent = taskProgressBar->text().replace("%", "").toInt(); CHECK_SET_ERR(percent >= 0 && percent <= 100, "Percent must be within 0 and 100%"); } GTUtilsTaskTreeView::cancelTask(os, "Calculating Phylogenetic Tree"); GTUtilsTaskTreeView::waitTaskFinished(os); //Expected state: the task progress is correct. } GUI_TEST_CLASS_DEFINITION(test_3305) { GTLogTracer logTracer; // 1. Open "data/samples/FASTA/human_T1.fa". GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Create an annotation. QDir().mkpath(sandBoxDir + "test_3305"); GTUtilsDialog::waitForDialog(os, new CreateAnnotationWidgetFiller(os, true, "<auto>", "misc_feature", "1..5", sandBoxDir + "test_3305/test_3305.gb")); GTWidget::click(os, GTToolbar::getWidgetForActionName(os, GTToolbar::getToolbar(os, MWTOOLBAR_ACTIVEMDI), "create_annotation_action")); // 3. Call context menu on the annotations document, select the {Export/Import -> Export annotations...} menu item. // 4. Fill the dialog: // Export to file: any acceptable path; // File format: bed // and accept it. GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ACTION_PROJECT__EXPORT_IMPORT_MENU_ACTION << "ep_exportAnnotations2CSV")); GTUtilsDialog::waitForDialog(os, new ExportAnnotationsFiller(sandBoxDir + "test_3305/test_3305.bed", ExportAnnotationsFiller::bed, os)); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "test_3305.gb")); GTMouseDriver::click(Qt::RightButton); GTUtilsTaskTreeView::waitTaskFinished(os); // Expected state: the annotation is successfully exported, result file exists, there are no errors in the log. const QFile bedFile(sandBoxDir + "test_3305/test_3305.bed"); CHECK_SET_ERR(bedFile.exists() && bedFile.size() != 0, "The result file is empty or does not exist!"); GTUtilsLog::check(os, logTracer); } GUI_TEST_CLASS_DEFINITION(test_3306) { GTFileDialog::openFile(os, dataDir + "samples/Genbank", "sars.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsAnnotationsTreeView::getItemCenter(os, "CDS (0, 14)"); GTUtilsAnnotationsTreeView::getItemCenter(os, "gene (0, 13)"); GTUtilsAnnotationsTreeView::getItemCenter(os, "mat_peptide (0, 16)"); GTUtilsAnnotationsTreeView::getItemCenter(os, "misc_feature (0, 16)"); QTreeWidget *annotTreeWidget = GTUtilsAnnotationsTreeView::getTreeWidget(os); QScrollBar *scrollBar = annotTreeWidget->verticalScrollBar(); const int initialPos = scrollBar->value(); for (int i = 0; i < 15; ++i) { GTKeyboardDriver::keyClick(Qt::Key_Down); GTGlobals::sleep(200); } CHECK_SET_ERR(initialPos != scrollBar->value(), "ScrollBar hasn't moved"); } GUI_TEST_CLASS_DEFINITION(test_3307) { //1. Connect to shared database const QString folderName = "view_test_0001"; const QString folderPath = U2ObjectDbi::PATH_SEP + folderName; const QString sequenceVisibleName = "NC_001363"; const QString sequenceVisibleWidgetName = " [s] NC_001363"; const QString databaseSequenceObjectPath = folderPath + U2ObjectDbi::PATH_SEP + sequenceVisibleName; Document *databaseDoc = GTUtilsSharedDatabaseDocument::connectToTestDatabase(os); //2. Open any sequence from database GTUtilsSharedDatabaseDocument::openView(os, databaseDoc, databaseSequenceObjectPath); QWidget *seqView = GTWidget::findWidget(os, sequenceVisibleWidgetName); CHECK_SET_ERR(NULL != seqView, "View wasn't opened"); //3. Use context menu on sequence area. Choose "new annotation" GTUtilsDialog::waitForDialog(os, new CreateAnnotationWidgetFiller(os, true, "<auto>", "ann1", "1.. 20")); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "create_annotation_action")); GTMenu::showContextMenu(os, seqView); GTGlobals::sleep(500); GTUtilsTaskTreeView::waitTaskFinished(os, 60000); GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::No)); QList<QString> keys = GTUtilsProjectTreeView::getDocuments(os).keys(); QString name; foreach (const QString &key, keys) { if (key.startsWith("MyDocument")) { name = key; break; } } GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, name)); GTMouseDriver::click(); GTKeyboardDriver::keyClick(Qt::Key_Delete); GTGlobals::sleep(500); } GUI_TEST_CLASS_DEFINITION(test_3308) { // 1. Open "data/samples/PDB/1CF7.PDB". GTFileDialog::openFile(os, dataDir + "samples/PDB", "1CF7.PDB"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Call context menu on the 3dview, select {Structural Alignment -> Align With...} menu item. // 3. Accept the dialog. // Expected state: UGENE doesn't crash. GTUtilsDialog::waitForDialog(os, new StructuralAlignmentDialogFiller(os)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Structural Alignment" << "align_with")); QWidget *widget3d = GTWidget::findWidget(os, "1-1CF7"); CHECK_SET_ERR(NULL != widget3d, "3D widget was not found"); GTWidget::click(os, widget3d, Qt::RightButton); } GUI_TEST_CLASS_DEFINITION(test_3312) { GTLogTracer logTracer; //1. Connect to a shared database. Document *databaseDoc = GTUtilsSharedDatabaseDocument::connectToTestDatabase(os); //2. Get any msa object in it. GTUtilsSharedDatabaseDocument::openView(os, databaseDoc, "/test_3312/COI_3312"); QWidget *msaView = GTWidget::findWidget(os, " [m] COI_3312"); CHECK_SET_ERR(NULL != msaView, "View wasn't opened"); //3. Rename the object. //Expected state: object is successfully renamed, there are no errors in the log. GTUtilsProjectTreeView::rename(os, "COI_3312", "COI_3312_renamed"); GTGlobals::sleep(3000); GTUtilsProjectTreeView::rename(os, "COI_3312_renamed", "COI_3312"); GTGlobals::sleep(2000); GTUtilsSharedDatabaseDocument::disconnectDatabase(os, databaseDoc); GTUtilsLog::check(os, logTracer); } GUI_TEST_CLASS_DEFINITION(test_3313) { //1. Open "data/samples/CLUSTALW/ty3.aln". GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW", "ty3.aln.gz"); GTUtilsTaskTreeView::waitTaskFinished(os); //2. Open "Statistics" options panel tab. GTUtilsTaskTreeView::waitTaskFinished(os); GTWidget::click(os, GTWidget::findWidget(os, "OP_SEQ_STATISTICS_WIDGET")); //3. Set any reference sequence. GTUtilsMSAEditorSequenceArea::click(os, QPoint(-5, 5)); GTWidget::click(os, GTWidget::findWidget(os, "addSeq")); //4. Check the "Show distances column" option. QCheckBox *showDistancesColumnCheck = qobject_cast<QCheckBox *>(GTWidget::findWidget(os, "showDistancesColumnCheck")); GTCheckBox::setChecked(os, showDistancesColumnCheck, true); //5. Edit the msa fast enough, e.g. insert several gaps somewhere. GTUtilsMSAEditorSequenceArea::click(os, QPoint(10, 10)); GTGlobals::sleep(200); for (int i = 0; i < 10; i++) { GTKeyboardDriver::keyClick(Qt::Key_Space); GTGlobals::sleep(200); } GTGlobals::sleep(); CHECK_SET_ERR(2 >= GTUtilsTaskTreeView::getTopLevelTasksCount(os), "There are several \"Generate distance matrix\" tasks"); } GUI_TEST_CLASS_DEFINITION(test_3318) { // 1. Open human_T1.fa GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); CHECK_OP(os, ); // 2. Open COI.aln GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW/", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); CHECK_OP(os, ); // 3. Drag the sequence to the alignment GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << MSAE_MENU_LOAD << "Sequence from current project")); GTUtilsDialog::waitForDialog(os, new ProjectTreeItemSelectorDialogFiller(os, "human_T1.fa", "human_T1 (UCSC April 2002 chr7:115977709-117855134)")); GTMenu::showContextMenu(os, GTUtilsMdi::activeWindow(os)); GTGlobals::sleep(); // 4. Make the sequence reference GTUtilsMSAEditorSequenceArea::moveTo(os, QPoint(-5, 18)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "set_seq_as_reference")); GTMouseDriver::click(Qt::RightButton); // 5. Change the highlighting mode to "Disagreements" GTUtilsOptionPanelMsa::openTab(os, GTUtilsOptionPanelMsa::Highlighting); QComboBox *highlightingSchemeCombo = qobject_cast<QComboBox *>(GTWidget::findWidget(os, "highlightingScheme")); GTComboBox::setIndexWithText(os, highlightingSchemeCombo, "Disagreements"); // 6. Use the dots QCheckBox *useDotsCheckBox = qobject_cast<QCheckBox *>(GTWidget::findWidget(os, "useDots")); GTCheckBox::setChecked(os, useDotsCheckBox); // 7. Drag the reference sequence in the list of sequences const QPoint mouseDragPosition(-5, 18); GTUtilsMSAEditorSequenceArea::moveTo(os, mouseDragPosition); // GTMouseDriver::click(); // GTGlobals::sleep(); //GTMouseDriver::dragAndDrop(GTMouseDriver::getMousePosition(), GTMouseDriver::getMousePosition() + QPoint(0, -200)); GTMouseDriver::click(); GTGlobals::sleep(1000); GTMouseDriver::press(); for (int i = 0; i < 50; i++) { GTMouseDriver::moveTo(GTMouseDriver::getMousePosition() + QPoint(0, -5)); } GTGlobals::sleep(200); //GTUtilsMSAEditorSequenceArea::moveTo(os, mouseDragPosition + QPoint(0, -10)); GTMouseDriver::release(); GTThread::waitForMainThread(); GTGlobals::sleep(200); // Expected result: the highlighting mode is the same, human_T1 is still the reference. CHECK_SET_ERR(highlightingSchemeCombo->currentText() == "Disagreements", "Invalid highlighting scheme"); CHECK_SET_ERR(GTUtilsMSAEditorSequenceArea::isSequenceHightighted(os, "human_T1 (UCSC April 2002 chr7:115977709-117855134)"), "Unexpected reference sequence"); } GUI_TEST_CLASS_DEFINITION(test_3319) { // 1. Open "data/samples/FASTA/human_T1.fa". GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); //2. Reverse complement sequence GTKeyboardDriver::keyClick('r', Qt::ControlModifier | Qt::ShiftModifier); GTGlobals::sleep(500); GTUtilsDialog::waitForDialog(os, new SelectSequenceRegionDialogFiller(os, 51, 102)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Select" << "Sequence region")); GTMenu::showContextMenu(os, GTUtilsMdi::activeWindow(os)); GTGlobals::sleep(500); GTKeyboardDriver::keyClick('c', Qt::ControlModifier); GTGlobals::sleep(400); const QString clipboardText = GTClipboard::text(os); CHECK_SET_ERR(clipboardText == "TTTAAACCACAGGTCATGACCCAGTAGATGAGGAAATTGGTTTAGTGGTTTA", "unexpected text in clipboard: " + clipboardText); GTGlobals::sleep(500); } GUI_TEST_CLASS_DEFINITION(test_3321) { // Open sequence GTFileDialog::openFile(os, dataDir + "samples/Genbank/murine.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); // Open Circular View QWidget *parent = GTWidget::findWidget(os, "ADV_single_sequence_widget_0"); QWidget *CircularViewAction = GTWidget::findWidget(os, "CircularViewAction", parent); GTWidget::click(os, CircularViewAction); // Select region that contains zero position GTUtilsDialog::waitForDialog(os, new SelectSequenceRegionDialogFiller(os, "1..10,5823..5833")); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Select" << "Sequence region")); GTWidget::click(os, GTWidget::findWidget(os, "CV_ADV_single_sequence_widget_0"), Qt::RightButton); GTGlobals::sleep(); // Press "Ctrl+C" GTKeyboardDriver::keyClick('c', Qt::ControlModifier); // Make sure that buffer contains right region QString clipboardText = GTClipboard::text(os); CHECK_SET_ERR(clipboardText == "AAATGAAAGAGGTCTTTCATT", "unecpected text in clipboard: " + clipboardText); GTGlobals::sleep(500); } GUI_TEST_CLASS_DEFINITION(test_3328) { // 1. Open "test/_common_data/fasta/human_T1_cutted.fa". GTFileDialog::openFile(os, dataDir + "samples/Genbank/murine.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Click the "Find restriction sites" button on the main toolbar. // 3. Select a single enzyme: "AbaBGI". Start the search. class Scenario : public CustomScenario { public: void run(HI::GUITestOpStatus &os) { //3. Press "Select by length" //4. Input "7" and press "Ok" GTUtilsDialog::waitForDialog(os, new InputIntFiller(os, 8)); GTWidget::click(os, GTWidget::findWidget(os, "selectByLengthButton")); GTWidget::click(os, GTToolbar::getWidgetForActionTooltip(os, GTToolbar::getToolbar(os, MWTOOLBAR_ACTIVEMDI), "Find restriction sites...")); GTGlobals::sleep(2000); // 4. Close the sequence view until task has finished. GTUtilsMdi::click(os, GTGlobals::Close); // Expected state: the task is canceled. CHECK_SET_ERR(0 == GTUtilsTaskTreeView::getTopLevelTasksCount(os), "There are unfinished tasks"); } }; QThreadPool threadPool(this); QEventLoop waiter(this); if (GTUtilsTaskTreeView::getTopLevelTasksCount(os) != 0) { QString s = GTUtilsTaskTreeView::getTaskStatus(os, "Auto-annotations update task"); // Expected state: the task is canceled. CHECK_SET_ERR(s == "Canceling...", "Unexpected task status: " + s); } } GUI_TEST_CLASS_DEFINITION(test_3332) { //1. Open "data/sample/CLUSTALW/COI.aln". GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW/", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); //2. Select {Edit -> Remove columns of gaps...} menu item from the context menu. GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << MSAE_MENU_EDIT << "remove_columns_of_gaps")); //3. Select the "all-gaps columns" option and accept the dialog. GTUtilsDialog::waitForDialog(os, new DeleteGapsDialogFiller(os, 1)); GTMenu::showContextMenu(os, GTUtilsMSAEditorSequenceArea::getSequenceArea(os)); //Expected state: nothing happens. CHECK_SET_ERR(GTUtilsMSAEditorSequenceArea::getLength(os) == 604, "Wrong msa length"); } GUI_TEST_CLASS_DEFINITION(test_3333) { // 1. Connect to the UGENE public database. // 2. Drag and drop the object "/genomes/Arabidopsis thaliana (TAIR 10)/INFO" to the "/genomes/Arabidopsis thaliana (TAIR 10)" folder. // Expected state: nothing happens, there are no errors in the log. Document *connection = GTUtilsSharedDatabaseDocument::connectToUgenePublicDatabase(os); GTUtilsTaskTreeView::waitTaskFinished(os); GTLogTracer logTracer; const QModelIndex object = GTUtilsSharedDatabaseDocument::getItemIndex(os, connection, "/genomes/Arabidopsis thaliana (TAIR 10)/INFO"); const QModelIndex folder = GTUtilsSharedDatabaseDocument::getItemIndex(os, connection, "/genomes/Arabidopsis thaliana (TAIR 10)"); GTUtilsProjectTreeView::dragAndDrop(os, object, folder); GTUtilsLog::check(os, logTracer); GTGlobals::FindOptions options; options.depth = 1; int objectsCount = GTUtilsProjectTreeView::findIndeciesInProjectViewNoWait(os, "", GTUtilsSharedDatabaseDocument::getItemIndex(os, connection, "/genomes/Arabidopsis thaliana (TAIR 10)"), 0, options).size(); CHECK_SET_ERR(8 == objectsCount, QString("An unexpected objects count in the folder: expect %1, got %2").arg(8).arg(objectsCount)); } GUI_TEST_CLASS_DEFINITION(test_3335) { GTLogTracer lt; // 1. Open "data/samples/FASTA/human_T1.fa". GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Create an annotation. GTUtilsDialog::waitForDialog(os, new CreateAnnotationWidgetFiller(os, true, "test_3335", "misc_feature", "50..100", sandBoxDir + "test_3335/annotationTable.gb")); GTMenu::clickMainMenuItem(os, QStringList() << "Actions" << "Add" << "New annotation..."); // Expected state: an annotation table object appears in a new document. GTUtilsDocument::checkDocument(os, "annotationTable.gb"); // 3. Rename the sequence object. GTUtilsProjectTreeView::rename(os, "human_T1 (UCSC April 2002 chr7:115977709-117855134)", "renamed sequence"); // Expected state: the sequence object is renamed, object relations are correct, there are no errors in the log. const QModelIndex sequenceObjectIndex = GTUtilsProjectTreeView::findIndex(os, "renamed sequence"); CHECK_SET_ERR(sequenceObjectIndex.isValid(), "Can't find the renamed sequence object"); GTUtilsMdi::click(os, GTGlobals::Close); GTUtilsProjectTreeView::doubleClickItem(os, "Annotations"); GTGlobals::sleep(5000); QWidget *relatedSequenceView = GTUtilsMdi::findWindow(os, "human_T1 [s] renamed sequence"); CHECK_SET_ERR(NULL != relatedSequenceView, "A view for the related sequence was not opened"); GTUtilsLog::check(os, lt); } GUI_TEST_CLASS_DEFINITION(test_3342) { // 1. Open "human_T1.fa" // 2. Press "Build dotlpot" toolbar button // Expected state: "DotPlot" dialog appeared // 3. Press "Ok" button in the dialog // Expected state: Dotplot view has appeared // 4. Close dotplot view // Expected state: "Save dot-plot" dialog has appeared // 5. Press "Yes" button // Expected state: the view has been closed // Current state: the view can't be closed GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); const GTGlobals::FindOptions fo(false); QWidget *dotplotWgt = GTWidget::findWidget(os, "dotplot widget", NULL, fo); CHECK_SET_ERR(dotplotWgt == NULL, "There should be NO dotpot widget"); GTUtilsDialog::waitForDialog(os, new DotPlotFiller(os)); GTWidget::click(os, GTWidget::findWidget(os, "build_dotplot_action_widget")); GTGlobals::sleep(); dotplotWgt = GTWidget::findWidget(os, "dotplot widget"); CHECK_SET_ERR(dotplotWgt != NULL, "No dotpot widget"); GTUtilsDialog::waitForDialog(os, new MessageBoxNoToAllOrNo(os)); GTWidget::click(os, GTWidget::findWidget(os, "exitButton")); GTGlobals::sleep(); dotplotWgt = GTWidget::findWidget(os, "dotplot widget", NULL, fo); CHECK_SET_ERR(dotplotWgt == NULL, "There should be NO dotpot widget"); } GUI_TEST_CLASS_DEFINITION(test_3344) { // Steps to reproduce: // 1. Open "human_T1" // 2. Press "Find repeats" tool button // 3. Choose following settings in the dialog: region="whole sequence", min repeat length=10bp // 4. Press "start" // 5. Wait until repeats finding complete // Expected state: repeats finding completed and create annotations task started // 6. Delete "repeat_unit" annotations group // Current state: UGENE hangs GTLogTracer l; GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); Runnable *tDialog = new FindRepeatsDialogFiller(os, testDir + "_common_data/scenarios/sandbox/test_3344.gb", false, 10); GTUtilsDialog::waitForDialog(os, tDialog); GTMenu::clickMainMenuItem(os, QStringList() << "Actions" << "Analyze" << "Find repeats...", GTGlobals::UseMouse); GTGlobals::sleep(); GTUtilsTaskTreeView::waitTaskFinished(os); GTMouseDriver::moveTo(GTUtilsAnnotationsTreeView::getItemCenter(os, "Annotations [test_3344.gb] *")); GTMouseDriver::moveTo(GTUtilsAnnotationsTreeView::getItemCenter(os, "repeat_unit (0, 3486)")); GTKeyboardDriver::keyPress(Qt::Key_Delete); GTGlobals::sleep(); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3346) { GTLogTracer lt; QFile originalFile(dataDir + "samples/Genbank/murine.gb"); QString dstPath = sandBoxDir + "murine.gb"; originalFile.copy(dstPath); QFile copiedFile(dstPath); CHECK_SET_ERR(copiedFile.exists(), "Unable to copy file"); GTFileDialog::openFile(os, sandBoxDir, "murine.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); if (!copiedFile.open(QIODevice::ReadOnly | QIODevice::Text)) { os.setError("Unable to open file"); return; } QString fileData = copiedFile.readAll(); copiedFile.close(); fileData.replace("\"gag polyprotein\"", "\"gag polyprotein"); if (!copiedFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) { os.setError("Unable to open file"); return; } GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::Yes)); GTGlobals::sleep(1000); // wait at least 1 second: UGENE does not detect file changes within 1 second interval. QTextStream out(&copiedFile); out << fileData; copiedFile.close(); GTUtilsDialog::waitAllFinished(os); GTUtilsTaskTreeView::waitTaskFinished(os); CHECK_SET_ERR(lt.hasErrors(), "Expected to have errors in the log, but no errors found"); } GUI_TEST_CLASS_DEFINITION(test_3348) { GTFileDialog::openFile(os, testDir + "_common_data/cmdline/", "DNA.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDocument::checkDocument(os, "DNA.fa"); Runnable *findDialog = new FindRepeatsDialogFiller(os, testDir + "_common_data/scenarios/sandbox/", true, 10, 75, 100); GTUtilsDialog::waitForDialog(os, findDialog); GTMenu::clickMainMenuItem(os, QStringList() << "Actions" << "Analyze" << "Find repeats...", GTGlobals::UseMouse); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsAnnotationsTreeView::getTreeWidget(os); QTreeWidgetItem *annotationGroup = GTUtilsAnnotationsTreeView::findItem(os, "repeat_unit (0, 39)"); QTreeWidgetItem *generalItem = annotationGroup->child(36); CHECK_SET_ERR(generalItem != NULL, "Invalid annotation tree item"); AVAnnotationItem *annotation = dynamic_cast<AVAnnotationItem *>(generalItem); CHECK_SET_ERR(NULL != annotation, "Annotation tree item not found"); CHECK_SET_ERR("76" == annotation->annotation->findFirstQualifierValue("repeat_identity"), "Annotation qualifier not found"); GTUtilsMdi::click(os, GTGlobals::Close); GTMouseDriver::click(); } GUI_TEST_CLASS_DEFINITION(test_3357) { /* 1. Open file _common_data\alphabets\standard_dna_rna_amino_1000.fa 2. Click the CV button on seq3 widget 3. Select document in project view. Press delete key Expected state: UGENE doesn't crash. */ GTUtilsDialog::waitForDialog(os, new SequenceReadingModeSelectorDialogFiller(os)); GTUtilsProject::openFile(os, testDir + "_common_data/alphabets/standard_dna_rna_amino_1000.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(1000); QWidget *w = GTWidget::findWidget(os, "ADV_single_sequence_widget_1"); GTWidget::click(os, GTWidget::findWidget(os, "CircularViewAction", w)); GTGlobals::sleep(500); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "standard_dna_rna_amino_1000.fa")); GTMouseDriver::click(); GTKeyboardDriver::keyClick(Qt::Key_Delete); GTGlobals::sleep(500); } GUI_TEST_CLASS_DEFINITION(test_3373) { // 1. Launch WD // 2. Create the following workflow: "Read Sequence" -> "Reverse Complement" -> "Write Sequence" // 3. Set output format "GenBank" (to prevent warnings about annotation support) and the "result.gb" output file name // 4. Set input file "test/_common_data/fasta/seq1.fa" // 5. Run the workflow // Expected state: workflow is successfully finished. "result.gb" contains reverse complement sequence for "seq1.fa" GTLogTracer l; GTUtilsWorkflowDesigner::openWorkflowDesigner(os); GTUtilsWorkflowDesigner::addAlgorithm(os, "Read Sequence", true); GTUtilsWorkflowDesigner::addAlgorithm(os, "Reverse Complement"); GTUtilsWorkflowDesigner::addAlgorithm(os, "Write Sequence", true); WorkflowProcessItem *seqReader = GTUtilsWorkflowDesigner::getWorker(os, "Read Sequence"); WorkflowProcessItem *revComplement = GTUtilsWorkflowDesigner::getWorker(os, "Reverse Complement"); WorkflowProcessItem *seqWriter = GTUtilsWorkflowDesigner::getWorker(os, "Write Sequence"); GTUtilsWorkflowDesigner::connect(os, seqReader, revComplement); GTUtilsWorkflowDesigner::connect(os, revComplement, seqWriter); GTMouseDriver::moveTo(GTUtilsWorkflowDesigner::getItemCenter(os, "Write Sequence")); GTMouseDriver::click(); GTUtilsWorkflowDesigner::setParameter(os, "Document format", "GenBank", GTUtilsWorkflowDesigner::comboValue); GTUtilsWorkflowDesigner::setParameter(os, "Output file", "result.gb", GTUtilsWorkflowDesigner::textValue); GTWidget::click(os, GTUtilsMdi::activeWindow(os)); GTMouseDriver::moveTo(GTUtilsWorkflowDesigner::getItemCenter(os, "Read Sequence")); GTMouseDriver::click(); GTUtilsWorkflowDesigner::setDatasetInputFile(os, testDir + "_common_data/fasta/seq1.fa"); GTWidget::click(os, GTAction::button(os, "Run workflow")); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3379) { //1. Open "_common_data/fasta/abds.fa" as separate sequences QStringList expectedNames; QList<ADVSingleSequenceWidget *> seqWidgets; expectedNames << "seq1" << "seq3" << "seq5"; seqWidgets = GTUtilsProject::openFileExpectSequences(os, testDir + "_common_data/alphabets/", "standard_dna_rna_amino_1000.fa", expectedNames); CHECK_OP_SET_ERR(os, "Failed to open sequences!"); //2. Open a few CV ADVSingleSequenceWidget *seq1Widget = seqWidgets.at(0); ADVSingleSequenceWidget *seq3Widget = seqWidgets.at(1); GTUtilsCv::cvBtn::click(os, seq3Widget); GTUtilsCv::cvBtn::click(os, seq1Widget); QWidget *circularView = GTWidget::findWidget(os, "CV_ADV_single_sequence_widget_0"); CHECK_OP_SET_ERR(os, "Failed to open circular view!"); //3.Add more files to the project and open a few more views GTFileDialog::openFile(os, testDir + "_common_data/cmdline/", "DNA.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(1000); //4. Return to 'abcd.fa' view GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "seq1")); GTMouseDriver::doubleClick(); //5. Try to launch Export dialog using context menu GTUtilsDialog::waitForDialog(os, new CircularViewExportImage(os, testDir + "_common_data/scenarios/sandbox/image.jpg")); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ADV_MENU_EXPORT << "Save circular view as image", GTGlobals::UseMouse)); GTWidget::click(os, circularView, Qt::RightButton); } GUI_TEST_CLASS_DEFINITION(test_3384) { GTLogTracer l; // Open sequence data/samples/Genbank/murine.gb GTFileDialog::openFile(os, dataDir + "samples/Genbank", "murine.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); // Open CV GTWidget::click(os, GTWidget::findWidget(os, "CircularViewAction")); // Insert at least one symbol to the sequence GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "ADV_MENU_EDIT" << "action_edit_insert_sub_sequences")); GTUtilsDialog::waitForDialog(os, new InsertSequenceFiller(os, "A")); GTMenu::showContextMenu(os, GTUtilsSequenceView::getDetViewByNumber(os)); // Select an area on CV that contains zero position QWidget *cv = GTWidget::findWidget(os, "CV_ADV_single_sequence_widget_0"); GTWidget::click(os, cv); GTMouseDriver::moveTo(GTMouseDriver::getMousePosition() + QPoint(20, -20)); GTMouseDriver::press(); GTMouseDriver::moveTo(GTMouseDriver::getMousePosition() + QPoint(0, 40)); GTMouseDriver::release(); GTThread::waitForMainThread(); // Current state: SAFE_POINT triggers and selection is "beautiful" (see the attachment) GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3396) { //Open WD GTUtilsWorkflowDesigner::openWorkflowDesigner(os); //Add macs worker GTUtilsWorkflowDesigner::addAlgorithm(os, "Find Peaks with MACS"); //set paremeter wiggle output to false GTUtilsWorkflowDesigner::click(os, "Find Peaks with MACS"); GTUtilsWorkflowDesigner::setParameter(os, "Wiggle output", 0, GTUtilsWorkflowDesigner::comboValue); GTUtilsWorkflowDesigner::click(os, "Find Peaks with MACS"); GTGlobals::sleep(500); //Expected state: parrameter wiggle space is hidden QStringList parameters = GTUtilsWorkflowDesigner::getAllParameters(os); CHECK_SET_ERR(!parameters.contains("Wiggle space"), "Wiggle space parameter is shown"); } GUI_TEST_CLASS_DEFINITION(test_3398_1) { // 1. Open "_common_data/fasta/broken/data_in_the_name_line.fa". // 2. Select "As separate sequences" mode. GTUtilsDialog::waitForDialog(os, new SequenceReadingModeSelectorDialogFiller(os)); GTUtilsProject::openFile(os, testDir + "_common_data/fasta/broken/data_in_the_name_line.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // Expected state: an unloaded document appears, there are no objects within. GTUtilsTaskTreeView::waitTaskFinished(os); Document *doc = GTUtilsDocument::getDocument(os, "data_in_the_name_line.fa"); CHECK_SET_ERR(NULL != doc, "Document is NULL"); CHECK_SET_ERR(!doc->isLoaded(), "Document is unexpectedly loaded"); // 3. Call context menu on the document. // Expected state: UGENE doesn't crash, a context menu is shown. GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "action_load_selected_documents")); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "data_in_the_name_line.fa")); GTMouseDriver::click(Qt::RightButton); } GUI_TEST_CLASS_DEFINITION(test_3398_2) { // 1. Open "_common_data/fasta/broken/data_in_the_name_line.fa". // 2. Select "As separate sequences" mode. GTUtilsDialog::waitForDialog(os, new SequenceReadingModeSelectorDialogFiller(os, SequenceReadingModeSelectorDialogFiller::Merge, 10)); GTUtilsProject::openFile(os, testDir + "_common_data/fasta/broken/data_in_the_name_line.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // Expected state: an unloaded document appears, there are no objects within. GTUtilsTaskTreeView::waitTaskFinished(os); Document *doc = GTUtilsDocument::getDocument(os, "data_in_the_name_line.fa"); CHECK_SET_ERR(NULL != doc, "Document is NULL"); CHECK_SET_ERR(!doc->isLoaded(), "Document is unexpectedly loaded"); // 3. Call context menu on the document. // Expected state: UGENE doesn't crash, a context menu is shown. GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "action_load_selected_documents")); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "data_in_the_name_line.fa")); GTMouseDriver::click(Qt::RightButton); } GUI_TEST_CLASS_DEFINITION(test_3398_3) { // 1. Open "_common_data/fasta/broken/data_in_the_name_line.fa". // 2. Select "Merge into one sequence" mode, set 10 'unknown' symbols. GTUtilsDialog::waitForDialog(os, new SequenceReadingModeSelectorDialogFiller(os, SequenceReadingModeSelectorDialogFiller::Merge, 0)); GTUtilsProject::openFile(os, testDir + "_common_data/fasta/broken/data_in_the_name_line.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // Expected state: an unloaded document appears, there are no objects within. GTUtilsTaskTreeView::waitTaskFinished(os); Document *doc = GTUtilsDocument::getDocument(os, "data_in_the_name_line.fa"); CHECK_SET_ERR(NULL != doc, "Document is NULL"); CHECK_SET_ERR(!doc->isLoaded(), "Document is unexpectedly loaded"); // 3. Call context menu on the document. // Expected state: UGENE doesn't crash, a context menu is shown. GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "action_load_selected_documents")); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "data_in_the_name_line.fa")); GTMouseDriver::click(Qt::RightButton); } GUI_TEST_CLASS_DEFINITION(test_3398_4) { // 1. Open "_common_data/fasta/broken/data_in_the_name_line.fa". // 2. Select "As separate sequences" mode. GTUtilsDialog::waitForDialog(os, new SequenceReadingModeSelectorDialogFiller(os, SequenceReadingModeSelectorDialogFiller::Join)); GTUtilsProject::openFile(os, testDir + "_common_data/fasta/broken/data_in_the_name_line.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // Expected state: an unloaded document appears, there are no objects within. GTUtilsTaskTreeView::waitTaskFinished(os); Document *doc = GTUtilsDocument::getDocument(os, "data_in_the_name_line.fa"); CHECK_SET_ERR(NULL != doc, "Document is NULL"); CHECK_SET_ERR(!doc->isLoaded(), "Document is unexpectedly loaded"); // 3. Call context menu on the document. // Expected state: UGENE doesn't crash, a context menu is shown. GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "action_load_selected_documents")); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "data_in_the_name_line.fa")); GTMouseDriver::click(Qt::RightButton); } GUI_TEST_CLASS_DEFINITION(test_3437) { // 1. Open file test/_common_data/fasta/empty.fa GTFileDialog::openFile(os, testDir + "_common_data/fasta", "empty.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // Expected: file opened in msa editor QWidget *w = GTWidget::findWidget(os, "msa_editor_sequence_area"); CHECK_SET_ERR(w != NULL, "msa editor not opened"); } GUI_TEST_CLASS_DEFINITION(test_3402) { // Open "test/_common_data/clustal/100_sequences.aln". GTFileDialog::openFile(os, testDir + "_common_data/clustal", "3000_sequences.aln"); // Call context menu on the "100_sequences" object. GTUtilsMsaEditor::checkMsaEditorWindowIsActive(os); GTUtilsProjectTreeView::checkProjectViewIsOpened(os); GTUtilsDialog::waitForDialog(os, new ExportToSequenceFormatFiller(os, sandBoxDir, "test_3402.fa", ExportToSequenceFormatFiller::FASTA, true, true)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "action_project__export_import_menu_action" << "action_project__export_as_sequence_action")); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "3000_sequences.aln")); GTMouseDriver::click(Qt::RightButton); //GTUtilsTaskTreeView::waitTaskFinished(os); // Select {Export/Import -> Export alignmnet to sequence format...} // menu item. // Export somewhere as fasta, sure that "Add document to the project" checkbox is checked. // Wait until open view task will start. TaskScheduler *scheduller = AppContext::getTaskScheduler(); bool end = false; while (!end) { QList<Task *> tList = scheduller->getTopLevelTasks(); if (tList.isEmpty()) { continue; } QList<Task *> innertList; foreach (Task *t, tList) { innertList.append(t->getPureSubtasks()); } foreach (Task *t, innertList) { if (t->getTaskName().contains("Opening view")) { end = true; break; } } GTGlobals::sleep(10); } // Expected state: the fasta document is present in the project, open view task is in progress. GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "test_3402.fa")); // Delete the fasta document from the project. GTMouseDriver::click(); GTKeyboardDriver::keyClick(Qt::Key_Delete); GTGlobals::sleep(500); // Current state: UGENE not crashes. } GUI_TEST_CLASS_DEFINITION(test_3414) { /* check time on dashboard * 1. Open WD * 2. Select "Remote BLASTing" sample * 3. Set input file samples/FASTA/human_T1.fa * 4. Execute workflow * 5. Check elapsed time * */ GTUtilsWorkflowDesigner::openWorkflowDesigner(os); GTUtilsWorkflowDesigner::addSample(os, "Remote BLASTing"); GTKeyboardDriver::keyClick(Qt::Key_Escape); GTUtilsWorkflowDesigner::click(os, "Read Sequence(s)"); GTUtilsWorkflowDesigner::setDatasetInputFile(os, dataDir + "samples/FASTA/human_T1.fa"); GTUtilsWorkflowDesigner::runWorkflow(os); GTGlobals::sleep(1000); HIWebElement initEl = GTUtilsDashboard::findElement(os, "00:00:0", "SPAN"); QString s = initEl.toPlainText(); GTGlobals::sleep(5000); HIWebElement finalEl = GTUtilsDashboard::findElement(os, "00:00:0", "SPAN"); QString s1 = finalEl.toPlainText(); CHECK_SET_ERR(s != s1, "timer not changed"); GTUtilsTask::cancelTask(os, "Execute workflow"); } GUI_TEST_CLASS_DEFINITION(test_3428) { // 1. Add element with unset parameter to the scene GTUtilsWorkflowDesigner::openWorkflowDesigner(os); GTUtilsWorkflowDesigner::addAlgorithm(os, "Read Annotations"); //QRect r = GTUtilsWorkflowDesigner::getItemRect(os, "Read Annotations"); GTUtilsWorkflowDesigner::clickLink(os, "Read Annotations"); // 2. Click on the "unset" parameter of the element. // UGENE not crashes } GUI_TEST_CLASS_DEFINITION(test_3430) { //1. Open "_common_data/alphabets/standard_dna_rna_amino_1000.fa" as separate sequences QStringList expectedNames; QList<ADVSingleSequenceWidget *> seqWidgets; expectedNames << "seq1" << "seq3" << "seq5"; seqWidgets = GTUtilsProject::openFileExpectSequences(os, testDir + "_common_data/alphabets/", "standard_dna_rna_amino_1000.fa", expectedNames); CHECK_OP_SET_ERR(os, "Failed to open sequences!"); //2. Open one circular view ADVSingleSequenceWidget *seq1Widget = seqWidgets.at(0); GTUtilsCv::cvBtn::click(os, seq1Widget); QWidget *circularView1 = GTWidget::findWidget(os, "CV_ADV_single_sequence_widget_0"); CHECK_OP_SET_ERR(os, "Failed to open circular view!"); QWidget *circularView2 = GTWidget::findWidget(os, "CV_ADV_single_sequence_widget_1", NULL, GTGlobals::FindOptions(false)); CHECK_SET_ERR(NULL == circularView2, "Unexpected circular view is opened!"); //3. Press "Toggle circular views" button GTWidget::click(os, GTWidget::findWidget(os, "globalToggleViewAction_widget")); circularView1 = GTWidget::findWidget(os, "CV_ADV_single_sequence_widget_0", NULL, GTGlobals::FindOptions(false)); CHECK_SET_ERR(NULL == circularView1, "Unexpected circular view is opened!"); circularView2 = GTWidget::findWidget(os, "CV_ADV_single_sequence_widget_1", NULL, GTGlobals::FindOptions(false)); CHECK_SET_ERR(NULL == circularView2, "Unexpected circular view is opened!"); //4. Press "Toggle circular views" again GTWidget::click(os, GTWidget::findWidget(os, "globalToggleViewAction_widget")); GTWidget::findWidget(os, "CV_ADV_single_sequence_widget_0"); CHECK_OP_SET_ERR(os, "Failed to open circular view!"); GTWidget::findWidget(os, "CV_ADV_single_sequence_widget_1"); CHECK_OP_SET_ERR(os, "Failed to open circular view!"); } GUI_TEST_CLASS_DEFINITION(test_3439) { //Open WD GTUtilsWorkflowDesigner::openWorkflowDesigner(os); //Add macs worker GTUtilsWorkflowDesigner::addAlgorithm(os, "Write Alignment"); //Validate workflow GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::Ok)); GTWidget::click(os, GTAction::button(os, "Validate workflow")); GTGlobals::sleep(); //there is should be 2 errors CHECK_SET_ERR(GTUtilsWorkflowDesigner::checkErrorList(os, "Write Alignment") == 1, "Errors count dont match, should be 2 validation errors"); //set parameter "Data storage" to "Shared UGENE database" GTUtilsWorkflowDesigner::click(os, "Write Alignment", QPoint(-30, -30)); GTGlobals::sleep(); GTUtilsWorkflowDesigner::setParameter(os, "Data storage", 1, GTUtilsWorkflowDesigner::comboValue); //Validate workflow GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::Ok)); GTWidget::click(os, GTAction::button(os, "Validate workflow")); GTGlobals::sleep(); //there is should be 3 errors CHECK_SET_ERR(GTUtilsWorkflowDesigner::checkErrorList(os, "Write Alignment") == 3, "Errors count dont match, should be 2 validation errors"); } GUI_TEST_CLASS_DEFINITION(test_3441) { // Open file test_common_data\fasta\empty.fa GTFileDialog::openFile(os, testDir + "_common_data/fasta/", "empty.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // Open "Statistics" options panel tab. GTWidget::click(os, GTWidget::findWidget(os, "OP_MSA_GENERAL")); //Sequence count is 0 QLabel *seqCount = GTWidget::findExactWidget<QLabel *>(os, "alignmentHeight"); CHECK_SET_ERR(seqCount->text() == "0", "Sequence count don't match"); } GUI_TEST_CLASS_DEFINITION(test_3443) { GTKeyboardDriver::keyClick('3', Qt::AltModifier); GTGlobals::sleep(); QWidget *logViewWidget = GTWidget::findWidget(os, "dock_log_view"); CHECK_SET_ERR(logViewWidget->isVisible(), "Log view is expected to be visible"); GTKeyboardDriver::keyClick('3', Qt::AltModifier); GTGlobals::sleep(); CHECK_SET_ERR(!logViewWidget->isVisible(), "Log view is expected to be visible"); GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(500); QWidget *projectViewWidget = GTWidget::findWidget(os, "project_view"); GTKeyboardDriver::keyClick('1', Qt::AltModifier); GTGlobals::sleep(); CHECK_SET_ERR(!projectViewWidget->isVisible(), "Project view is expected to be invisible"); GTKeyboardDriver::keyClick('1', Qt::AltModifier); GTGlobals::sleep(); CHECK_SET_ERR(projectViewWidget->isVisible(), "Project view is expected to be visible"); GTKeyboardDriver::keyClick('2', Qt::AltModifier); GTGlobals::sleep(); QWidget *taskViewWidget = GTWidget::findWidget(os, "dock_task_view"); CHECK_SET_ERR(taskViewWidget->isVisible(), "Task view is expected to be visible"); GTKeyboardDriver::keyClick('2', Qt::AltModifier); GTGlobals::sleep(); CHECK_SET_ERR(!taskViewWidget->isVisible(), "Task view is expected to be invisible"); GTKeyboardDriver::keyClick('b', Qt::ControlModifier); GTGlobals::sleep(); QWidget *codonTableWidget = GTWidget::findWidget(os, "Codon table widget"); CHECK_SET_ERR(codonTableWidget->isVisible(), "Codon table is expected to be visible"); GTKeyboardDriver::keyClick('b', Qt::ControlModifier); GTGlobals::sleep(); CHECK_SET_ERR(!codonTableWidget->isVisible(), "Codon table is expected to be invisible"); } GUI_TEST_CLASS_DEFINITION(test_3450) { // 1. Open file "COI.aln" // 2. Open "Highlighting" options panel tab // 3. Set reference sequence // 4. Set highlighting scheme // 5. Press "Export" button in the tab // Expected state: "Export highlighted to file" dialog appeared, there is default file in "Export to file" // 6. Delete the file path and press "Export" button // Expected state: message box appeared // 6. Set the result file and press "Export" button // Current state: file is empty, but error is not appeared GTFileDialog::openFile(os, dataDir + "/samples/CLUSTALW/", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTWidget::click(os, GTWidget::findWidget(os, "OP_MSA_HIGHLIGHTING")); GTWidget::click(os, GTWidget::findWidget(os, "sequenceLineEdit")); GTKeyboardDriver::keySequence("Montana_montana"); GTKeyboardDriver::keyClick(Qt::Key_Enter); GTGlobals::sleep(300); QComboBox *combo = qobject_cast<QComboBox *>(GTWidget::findWidget(os, "highlightingScheme")); CHECK_SET_ERR(combo != NULL, "highlightingScheme not found!"); GTComboBox::setIndexWithText(os, combo, "Agreements"); QWidget *exportButton = GTWidget::findWidget(os, "exportHighlightning"); CHECK_SET_ERR(exportButton != NULL, "exportButton not found"); class ExportHighlightedDialogFiller : public Filler { public: ExportHighlightedDialogFiller(HI::GUITestOpStatus &os) : Filler(os, "ExportHighlightedDialog") { } virtual void run() { QWidget *dialog = QApplication::activeModalWidget(); CHECK_SET_ERR(dialog, "activeModalWidget is NULL"); QLineEdit *filePath = dialog->findChild<QLineEdit *>("fileNameEdit"); CHECK_SET_ERR(filePath != NULL, "fileNameEdit is NULL"); CHECK_SET_ERR(!GTLineEdit::copyText(os, filePath).isEmpty(), "Default file path is empty"); GTLineEdit::setText(os, filePath, ""); QPushButton *exportButton = dialog->findChild<QPushButton *>(); CHECK_SET_ERR(exportButton != NULL, "ExportButton is NULL"); GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, "Ok")); GTWidget::click(os, exportButton); GTLineEdit::setText(os, filePath, sandBoxDir + "test_3450_export_hl.txt"); GTWidget::click(os, exportButton); } }; GTUtilsDialog::waitForDialog(os, new ExportHighlightedDialogFiller(os)); GTWidget::click(os, exportButton); GTGlobals::sleep(); CHECK_SET_ERR(GTFile::getSize(os, sandBoxDir + "test_3450_export_hl.txt") != 0, "Exported file is empty!"); } GUI_TEST_CLASS_DEFINITION(test_3451) { // 1. Open file "COI.aln" // 2. Open "Highlighting" options panel tab // 3. Set reference sequence // 4. Set highlighting scheme // 5. Press "Export" button in the tab // Expected state: "Export highlighted to file" dialog appeared, there is default file in "Export to file" // 6. Set the "from" as 5, "to" as 6 // 7. Set the "to" as 5 // Expected state: "from" is 4 GTFileDialog::openFile(os, dataDir + "/samples/CLUSTALW/", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTWidget::click(os, GTWidget::findWidget(os, "OP_MSA_HIGHLIGHTING")); GTWidget::click(os, GTWidget::findWidget(os, "sequenceLineEdit")); GTKeyboardDriver::keySequence("Montana_montana"); GTKeyboardDriver::keyClick(Qt::Key_Enter); GTGlobals::sleep(300); QComboBox *combo = qobject_cast<QComboBox *>(GTWidget::findWidget(os, "highlightingScheme")); CHECK_SET_ERR(combo != NULL, "highlightingScheme not found!"); GTComboBox::setIndexWithText(os, combo, "Agreements"); QWidget *exportButton = GTWidget::findWidget(os, "exportHighlightning"); CHECK_SET_ERR(exportButton != NULL, "exportButton not found"); class CancelExportHighlightedDialogFiller : public Filler { public: CancelExportHighlightedDialogFiller(HI::GUITestOpStatus &os) : Filler(os, "ExportHighlightedDialog") { } virtual void run() { QWidget *dialog = QApplication::activeModalWidget(); CHECK_SET_ERR(dialog, "activeModalWidget is NULL"); QSpinBox *startPos = dialog->findChild<QSpinBox *>("startLineEdit"); CHECK_SET_ERR(startPos != NULL, "startLineEdit is NULL"); QSpinBox *endPos = dialog->findChild<QSpinBox *>("endLineEdit"); CHECK_SET_ERR(endPos != NULL, "endLineEdit is NULL"); GTSpinBox::checkLimits(os, startPos, 1, 604); GTSpinBox::checkLimits(os, endPos, 1, 604); //GTGlobals::sleep(); QDialogButtonBox *box = qobject_cast<QDialogButtonBox *>(GTWidget::findWidget(os, "buttonBox", dialog)); CHECK_SET_ERR(box != NULL, "buttonBox is NULL"); QPushButton *button = box->button(QDialogButtonBox::Cancel); CHECK_SET_ERR(button != NULL, "Cancel button is NULL"); GTWidget::click(os, button); } }; GTUtilsDialog::waitForDialog(os, new CancelExportHighlightedDialogFiller(os)); GTWidget::click(os, exportButton); GTGlobals::sleep(); } GUI_TEST_CLASS_DEFINITION(test_3452) { //1. Open "samples/Genbank/murine.gb". GTFileDialog::openFile(os, dataDir + "samples/Genbank", "murine.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); //2. Find the annotation: NC_001363 -> CDS (0, 4) -> CDS. //Expected state: qualifiers of CDS are shown. QTreeWidgetItem *item1 = GTUtilsAnnotationsTreeView::findItem(os, "CDS"); QTreeWidgetItem *item2 = GTUtilsAnnotationsTreeView::findItem(os, "comment"); QPoint p1 = GTTreeWidget::getItemCenter(os, item1); QPoint pQual(p1.x(), p1.y() + 80); QPoint p2 = GTTreeWidget::getItemCenter(os, item2); //3. Select the annotaions and its several qualifiers. GTMouseDriver::moveTo(p1); GTMouseDriver::click(); GTMouseDriver::moveTo(pQual); GTGlobals::sleep(500); GTKeyboardDriver::keyPress(Qt::Key_Shift); GTMouseDriver::click(); GTKeyboardDriver::keyRelease(Qt::Key_Shift); GTGlobals::sleep(500); //4. Try to drag selected annotaions. GTMouseDriver::dragAndDrop(p1, p2); //Expected state: UGENE does not crash. } GUI_TEST_CLASS_DEFINITION(test_3455) { //1. Open WD. GTUtilsWorkflowDesigner::openWorkflowDesigner(os); //2. Activate samples. GTUtilsWorkflowDesigner::setCurrentTab(os, GTUtilsWorkflowDesigner::samples); //3. Choose a sample (but not open it). QTreeWidgetItem *sample = GTUtilsWorkflowDesigner::findTreeItem(os, "call variants", GTUtilsWorkflowDesigner::samples); sample->parent()->setExpanded(true); GTMouseDriver::moveTo(GTTreeWidget::getItemCenter(os, sample)); GTMouseDriver::click(); CHECK_OP(os, ); //4. Load any workflow. QString schemaPath = testDir + "_common_data/scenarios/workflow designer/222.uwl"; GTUtilsWorkflowDesigner::loadWorkflow(os, schemaPath); CHECK_OP(os, ); //Expected: the elements tab is active. GTUtilsWorkflowDesigner::tab current = GTUtilsWorkflowDesigner::currentTab(os); CHECK_SET_ERR(GTUtilsWorkflowDesigner::algorithms == current, "Samples tab is active"); } GUI_TEST_CLASS_DEFINITION(test_3471) { // 1. Open "_common_data\bam\1.bam" // Expected state: "Import BAM file dialog" appeared // 2. Press "Import" button in the dialog // Expected state: assembly is empty, there is text "Assembly has no mapped reads. Nothing to visualize." GTUtilsDialog::waitForDialog(os, new ImportBAMFileFiller(os, sandBoxDir + "test_3471/test_3471.ugenedb")); GTFileDialog::openFile(os, testDir + "_common_data/bam/", "1.bam"); GTUtilsTaskTreeView::waitTaskFinished(os); // 3. Add bookmark // Expected state: UGENE doesn't crash GTUtilsBookmarksTreeView::addBookmark(os, GTUtilsMdi::activeWindow(os)->windowTitle(), "test_3471"); } GUI_TEST_CLASS_DEFINITION(test_3472) { GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW/", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsOptionPanelMsa::openTab(os, GTUtilsOptionPanelMsa::PairwiseAlignment); GTUtilsOptionPanelMsa::addFirstSeqToPA(os, "Conocephalus_discolor"); GTUtilsOptionPanelMsa::addSecondSeqToPA(os, "Conocephalus_sp."); GTWidget::click(os, GTWidget::findWidget(os, "ArrowHeader_Output settings")); QLineEdit *outputFilePathEdit = qobject_cast<QLineEdit *>(GTWidget::findWidget(os, "outputFileLineEdit")); CHECK_SET_ERR(NULL != outputFilePathEdit, "Invalid output file path edit field"); GTWidget::setFocus(os, outputFilePathEdit); #ifndef Q_OS_MAC GTKeyboardDriver::keyClick(Qt::Key_Home); #else GTKeyboardDriver::keyClick(Qt::LeftArrow, Qt::ControlModifier); #endif GTGlobals::sleep(); GTKeyboardDriver::keySequence("///123/123/123"); GTGlobals::sleep(); int deleteCounter = 100; while (0 < --deleteCounter) { GTKeyboardDriver::keyClick(Qt::Key_Delete); GTGlobals::sleep(100); } GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::Ok)); GTWidget::click(os, GTWidget::findWidget(os, "alignButton")); GTGlobals::sleep(5000); //needed for windows GTWidget::setFocus(os, outputFilePathEdit); #ifndef Q_OS_MAC GTKeyboardDriver::keyClick(Qt::Key_Home); #else GTKeyboardDriver::keyClick(Qt::LeftArrow, Qt::ControlModifier); #endif GTGlobals::sleep(); GTKeyboardDriver::keySequence(sandBoxDir + "123/123/123/1.aln"); GTGlobals::sleep(); deleteCounter = 15; while (0 < --deleteCounter) { GTKeyboardDriver::keyClick(Qt::Key_Delete); GTGlobals::sleep(100); } GTWidget::click(os, GTWidget::findWidget(os, "alignButton")); GTGlobals::sleep(); QString expected = "TTAGCTTATTAATT\n" "TTAGCTTATTAATT"; GTUtilsMSAEditorSequenceArea::checkSelection(os, QPoint(0, 0), QPoint(13, 1), expected); } GUI_TEST_CLASS_DEFINITION(test_3473) { /* 1. Open "human_T1" 2. Press "Show circular view" tool button Expected state: circular view appeared and button's hint change to "Remove circular view" 3. Press the button again Expected state: the hint is "Show circular view" */ GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(1000); QToolButton *a = qobject_cast<QToolButton *>(GTWidget::findWidget(os, "CircularViewAction")); CHECK_SET_ERR(a->toolTip() == "Show circular view", QString("Unexpected tooltip: %1, must be %2").arg(a->toolTip()).arg("Show circular view")); GTWidget::click(os, GTWidget::findWidget(os, "CircularViewAction")); GTGlobals::sleep(500); CHECK_SET_ERR(a->toolTip() == "Remove circular view", QString("Unexpected tooltip: %1, must be %2").arg(a->toolTip()).arg("Remove circular view")); GTGlobals::sleep(500); } GUI_TEST_CLASS_DEFINITION(test_3477) { // 1. Open "data/samples/human_T1.fa". GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Press "Find restriction sites" tool button. // Expected state: "Find restriction sites" dialog appeared. // 3. Select enzyme "T(1, 105) -> TaaI" and accept the dialog. GTUtilsDialog::waitForDialog(os, new FindEnzymesDialogFiller(os, QStringList() << "TaaI")); GTWidget::click(os, GTToolbar::getWidgetForActionName(os, GTToolbar::getToolbar(os, MWTOOLBAR_ACTIVEMDI), "Find restriction sites")); GTUtilsTaskTreeView::waitTaskFinished(os); // 4. Select {Tools -> Cloning -> Digest into Fragments...} menu item in the main menu. // Expected state: "Digest sequence into fragments" dialog appeared. // 5. Add "TaaI" to selected enzymes and accept the dialog. GTUtilsDialog::waitForDialog(os, new DigestSequenceDialogFiller(os)); GTMenu::clickMainMenuItem(os, QStringList() << "Tools" << "Cloning" << "Digest into fragments..."); GTUtilsTaskTreeView::waitTaskFinished(os); // 6. Select {Tools -> Cloning -> Construct molecule} menu item in the main menu. // Expected state: "Construct molecule" dialog appeared. // 7. Press "Add all" button. // 9.Press several times to checkbox "Inverted" for any fragment. // Expected state: checkbox's state updates on every click, UGENE doesn't crash. QList<ConstructMoleculeDialogFiller::Action> actions; actions << ConstructMoleculeDialogFiller::Action(ConstructMoleculeDialogFiller::AddAllFragments, ""); actions << ConstructMoleculeDialogFiller::Action(ConstructMoleculeDialogFiller::InvertAddedFragment, "Fragment 1"); actions << ConstructMoleculeDialogFiller::Action(ConstructMoleculeDialogFiller::InvertAddedFragment, "Fragment 1"); actions << ConstructMoleculeDialogFiller::Action(ConstructMoleculeDialogFiller::InvertAddedFragment, "Fragment 1"); actions << ConstructMoleculeDialogFiller::Action(ConstructMoleculeDialogFiller::InvertAddedFragment, "Fragment 1"); actions << ConstructMoleculeDialogFiller::Action(ConstructMoleculeDialogFiller::InvertAddedFragment, "Fragment 1"); actions << ConstructMoleculeDialogFiller::Action(ConstructMoleculeDialogFiller::InvertAddedFragment, "Fragment 1"); actions << ConstructMoleculeDialogFiller::Action(ConstructMoleculeDialogFiller::InvertAddedFragment, "Fragment 1"); actions << ConstructMoleculeDialogFiller::Action(ConstructMoleculeDialogFiller::InvertAddedFragment, "Fragment 1"); actions << ConstructMoleculeDialogFiller::Action(ConstructMoleculeDialogFiller::InvertAddedFragment, "Fragment 1"); actions << ConstructMoleculeDialogFiller::Action(ConstructMoleculeDialogFiller::InvertAddedFragment, "Fragment 1"); actions << ConstructMoleculeDialogFiller::Action(ConstructMoleculeDialogFiller::ClickCancel, ""); GTUtilsDialog::waitForDialog(os, new ConstructMoleculeDialogFiller(os, actions)); GTMenu::clickMainMenuItem(os, QStringList() << "Tools" << "Cloning" << "Construct molecule..."); GTGlobals::sleep(); } GUI_TEST_CLASS_DEFINITION(test_3480) { GTLogTracer l; GTUtilsDialog::waitForDialogWhichMayRunOrNot(os, new StartupDialogFiller(os)); GTFileDialog::openFile(os, testDir + "_common_data/bwa/workflow/", "bwa-mem.uwl"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(); GTUtilsWorkflowDesigner::click(os, "Align reads with BWA MEM"); GTUtilsWorkflowDesigner::setParameter(os, "Library", 0, GTUtilsWorkflowDesigner::comboValue); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3484) { // 1. Open an alignment // 2. Build the tree // 3. Unload both documents (alignment and tree) // 4. Delete the tree document from project // 5. Load alignment // Expected state: only alignment is opened. GTFile::copy(os, dataDir + "samples/CLUSTALW/COI.aln", testDir + "_common_data/scenarios/sandbox/COI_3484.aln"); GTFileDialog::openFile(os, testDir + "_common_data/scenarios/sandbox/", "COI_3484.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDialog::waitForDialog(os, new BuildTreeDialogFiller(os, testDir + "_common_data/scenarios/sandbox/COI_3484.nwk", 0, 0, true)); GTWidget::click(os, GTAction::button(os, "Build Tree")); GTUtilsTaskTreeView::waitTaskFinished(os); QGraphicsView *treeView = qobject_cast<QGraphicsView *>(GTWidget::findWidget(os, "treeView")); CHECK_SET_ERR(treeView != NULL, "TreeView not found"); GTUtilsDocument::unloadDocument(os, "COI_3484.nwk", false); GTGlobals::sleep(500); GTUtilsDocument::saveDocument(os, "COI_3484.aln"); GTUtilsDocument::unloadDocument(os, "COI_3484.aln", true); GTGlobals::sleep(); GTUtilsDocument::removeDocument(os, "COI_3484.nwk"); GTUtilsDocument::loadDocument(os, "COI_3484.aln"); CHECK_SET_ERR(GTUtilsProjectTreeView::checkItem(os, "COI_3484 .nwk") == false, "Unauthorized tree opening!"); } GUI_TEST_CLASS_DEFINITION(test_3484_1) { // 1. Open alignment // 2. Build the tree // Current state: tree and alignment are both in the project, loaded and visualized. // 3. Save the file and the project, relaunch UGENE (or close and reload project) // 4. Open project, open alignment // Current state: tree and alignment are both in the project, loaded and visualized. // 5. Delete the tree document from the project // 6. Save the alignment // 7. Save the project // 8. Relaunch UGENE and open the project // 9. Load the alignment // Current state: tree document is added to the project, both documents are loaded. // Expected state: only alignment is loaded. GTFile::copy(os, dataDir + "samples/CLUSTALW/COI.aln", testDir + "_common_data/scenarios/sandbox/COI_3484_1.aln"); GTFileDialog::openFile(os, testDir + "_common_data/scenarios/sandbox/", "COI_3484_1.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDialog::waitForDialog(os, new BuildTreeDialogFiller(os, testDir + "_common_data/scenarios/sandbox/COI_3484_1.nwk", 0, 0, true)); QAbstractButton *tree = GTAction::button(os, "Build Tree"); GTWidget::click(os, tree); GTUtilsTaskTreeView::waitTaskFinished(os); QGraphicsView *treeView = qobject_cast<QGraphicsView *>(GTWidget::findWidget(os, "treeView")); CHECK_SET_ERR(treeView != NULL, "TreeView not found"); GTUtilsDialog::waitForDialog(os, new SaveProjectAsDialogFiller(os, "proj_3484_1", testDir + "_common_data/scenarios/sandbox/proj_3484_1")); GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Save project as..."); GTGlobals::sleep(); GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Close project"); GTUtilsDialog::waitForDialog(os, new GTFileDialogUtils(os, testDir + "_common_data/scenarios/sandbox/", "proj_3484_1.uprj")); //GTWidget::clickWindowTitle(os, AppContext::getMainWindow()->getQMainWindow()); GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Open..."); GTGlobals::sleep(); GTUtilsDocument::loadDocument(os, "COI_3484_1.aln"); QGraphicsView *treeView1 = qobject_cast<QGraphicsView *>(GTWidget::findWidget(os, "treeView")); CHECK_SET_ERR(treeView1 != NULL, "TreeView not found"); GTUtilsDocument::removeDocument(os, "COI_3484_1.nwk"); GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Save all"); //GTWidget::clickWindowTitle(os, AppContext::getMainWindow()->getQMainWindow()); GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Close project"); GTUtilsDialog::waitForDialog(os, new GTFileDialogUtils(os, testDir + "_common_data/scenarios/sandbox/", "proj_3484_1.uprj")); GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Open..."); GTGlobals::sleep(); GTUtilsDocument::loadDocument(os, "COI_3484_1.aln"); CHECK_SET_ERR(GTUtilsProjectTreeView::checkItem(os, "COI_3484_1.nwk") == false, "Unauthorized tree opening!"); } GUI_TEST_CLASS_DEFINITION(test_3504) { // 1. Open COI.aln // 2. Build the tree and open it with the alignment. // Expected state: Tree view has horizontal scroll bar // 3. Change tree layout to unrooted. // 4. Change layout back to rectangular // Bug state: tree view has no horizontal scroll bar. // Expected state: horizontal scroll bar is present GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW/", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDialog::waitForDialog(os, new BuildTreeDialogFiller(os, sandBoxDir + "COI_3504.nwk", 0, 0, true)); QAbstractButton *tree = GTAction::button(os, "Build Tree"); GTWidget::click(os, tree); GTUtilsTaskTreeView::waitTaskFinished(os); QGraphicsView *treeView = qobject_cast<QGraphicsView *>(GTWidget::findWidget(os, "treeView")); CHECK_SET_ERR(treeView != NULL, "TreeView not found"); QScrollBar *scroll = treeView->horizontalScrollBar(); CHECK_SET_ERR(scroll != NULL, "TreeView does not have a horisontal scroll bar"); CHECK_SET_ERR(scroll->isVisible(), "Horisontal scroll bar is hidden"); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Unrooted")); GTWidget::click(os, GTWidget::findWidget(os, "Layout")); GTGlobals::sleep(); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Rectangular")); GTWidget::click(os, GTWidget::findWidget(os, "Layout")); scroll = treeView->horizontalScrollBar(); CHECK_SET_ERR(scroll != NULL, "TreeView does not have a horisontal scroll bar"); CHECK_SET_ERR(scroll->isVisible(), "Horisontal scroll bar is hidden"); } GUI_TEST_CLASS_DEFINITION(test_3518) { // 1. Select {Tools -> Weight matrix -> Build Weight Matrix} menu item in the main menu. // 2. Set file "data/samples/GFF/5prime_utr_intron_A20.gff" as input. // Expected state: the dialog process the file and notify user if the file is inappropriate, UGENE doesn't crash. QList<PwmBuildDialogFiller::Action> actions; actions << PwmBuildDialogFiller::Action(PwmBuildDialogFiller::ExpectInvalidFile, ""); actions << PwmBuildDialogFiller::Action(PwmBuildDialogFiller::SelectInput, dataDir + "samples/GFF/5prime_utr_intron_A20.gff"); actions << PwmBuildDialogFiller::Action(PwmBuildDialogFiller::ClickCancel, ""); GTUtilsDialog::waitForDialog(os, new PwmBuildDialogFiller(os, actions)); GTMenu::clickMainMenuItem(os, QStringList() << "Tools" << "Search for TFBS" << "Build weight matrix..."); GTGlobals::sleep(); } GUI_TEST_CLASS_DEFINITION(test_3519_1) { // 1. Open "data/samples/FASTA/human_T1.fa". // 2. Open a "SITECON Search" dialog, fill it and start the search. // Expected state: the dialog is opened, there are search results. // 3. Click the "Save as annotations" button and then click the "Search" button again before all annotations are drawn. // 4. Try to close the dialog. // Expected state: the dialog is closed, the search task is canceled. // Current state: GUI waits until all annotations are drawn, then react on the button click. GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); class SiteconCustomFiller : public Filler { public: SiteconCustomFiller(HI::GUITestOpStatus &os) : Filler(os, "SiteconSearchDialog") { } virtual void run() { QWidget *dialog = QApplication::activeModalWidget(); CHECK_SET_ERR(NULL != dialog, "activeModalWidget is NULL"); GTUtilsDialog::waitForDialog(os, new GTFileDialogUtils(os, dataDir + "/sitecon_models/eukaryotic", "CLOCK.sitecon.gz")); QWidget *modelButton = GTWidget::findWidget(os, "pbSelectModelFile", dialog); GTWidget::click(os, modelButton); GTUtilsDialog::clickButtonBox(os, dialog, QDialogButtonBox::Ok); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDialog::waitForDialog(os, new CreateAnnotationWidgetFiller(os, true, "<auto>", "sitecon_ann", "")); QWidget *saveButton = GTWidget::findWidget(os, "pbSaveAnnotations", dialog); GTWidget::click(os, saveButton); GTUtilsDialog::clickButtonBox(os, dialog, QDialogButtonBox::Ok); GTUtilsDialog::clickButtonBox(os, dialog, QDialogButtonBox::Cancel); } }; GTUtilsDialog::waitForDialog(os, new SiteconCustomFiller(os)); GTMenu::clickMainMenuItem(os, QStringList() << "Actions" << "Analyze" << "Find TFBS with SITECON...", GTGlobals::UseMouse); CHECK_SET_ERR(GTUtilsTaskTreeView::getTopLevelTasksCount(os) == 0, "Some task is still running"); } GUI_TEST_CLASS_DEFINITION(test_3519_2) { // 1. Open "data/samples/FASTA/human_T1.fa". // 2. Run "Auto-annotations update" task, e.g. find tandems with default parameters. // 3. Open a "SITECON Search" dialog before "auto-annotations update" task finish, fill it and start the search. // Current state: a deadlock occurs: "auto-annotations update" task wait until the dialog close, // dialog can't be closed until the search task finish, // the search task waits until the "auto-annotation update" task finish. GTFileDialog::openFile(os, testDir + "_common_data/fasta/", "Mycobacterium.fna"); GTUtilsTaskTreeView::waitTaskFinished(os); class SiteconCustomFiller : public Filler { public: SiteconCustomFiller(HI::GUITestOpStatus &os) : Filler(os, "SiteconSearchDialog") { } virtual void run() { QWidget *dialog = QApplication::activeModalWidget(); CHECK_SET_ERR(NULL != dialog, "activeModalWidget is NULL"); GTUtilsDialog::waitForDialog(os, new GTFileDialogUtils(os, dataDir + "/sitecon_models/eukaryotic", "CLOCK.sitecon.gz")); QWidget *modelButton = GTWidget::findWidget(os, "pbSelectModelFile", dialog); GTWidget::click(os, modelButton); GTGlobals::sleep(); GTUtilsDialog::clickButtonBox(os, dialog, QDialogButtonBox::Ok); GTGlobals::sleep(); CHECK_SET_ERR(GTUtilsTaskTreeView::getTopLevelTasksCount(os) == 2, QString("Incorrect top-level task counts: %1").arg(GTUtilsTaskTreeView::getTopLevelTasksCount(os))); GTGlobals::sleep(500); GTUtilsDialog::clickButtonBox(os, dialog, QDialogButtonBox::Cancel); } }; class AllEnzymesSearchScenario : public CustomScenario { public: void run(HI::GUITestOpStatus &os) { QWidget *dialog = QApplication::activeModalWidget(); CHECK_SET_ERR(NULL != dialog, "activeModalWidget is NULL"); QWidget *selectAllButton = GTWidget::findWidget(os, "selectAllButton", dialog); GTWidget::click(os, selectAllButton); GTUtilsDialog::clickButtonBox(os, dialog, QDialogButtonBox::Ok); } }; GTUtilsDialog::waitForDialog(os, new FindEnzymesDialogFiller(os, QStringList(), new AllEnzymesSearchScenario())); GTWidget::click(os, GTWidget::findWidget(os, "Find restriction sites_widget")); GTThread::waitForMainThread(); GTGlobals::sleep(1000); GTUtilsTaskTreeView::openView(os); GTUtilsDialog::waitForDialog(os, new SiteconCustomFiller(os)); GTMenu::clickMainMenuItem(os, QStringList() << "Actions" << "Analyze" << "Find TFBS with SITECON..."); GTGlobals::sleep(); CHECK_SET_ERR(GTUtilsTaskTreeView::checkTask(os, "SITECON search") == false, "SITECON task is still running"); GTUtilsTaskTreeView::cancelTask(os, "Auto-annotations update task"); GTUtilsTaskTreeView::waitTaskFinished(os, 60000); } GUI_TEST_CLASS_DEFINITION(test_3545) { // 1. Open "_common_data\scenarios\msa\big.aln" GTFile::copy(os, testDir + "_common_data/scenarios/msa/big.aln", sandBoxDir + "big.aln"); GTFileDialog::openFile(os, sandBoxDir, "big.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Use context menu GTUtilsDialog::waitForDialog(os, new GTFileDialogUtils(os, testDir + "_common_data/fasta", "NC_008253.fna")); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "MSAE_MENU_LOAD_SEQ" << "Sequence from file")); GTMenu::showContextMenu(os, GTWidget::findWidget(os, "msa_editor_sequence_area")); GTGlobals::sleep(); // {Add->Sequence from file} // Expected state: "Open file with sequence" dialog appeared // 3. Select sequence "_common_data\fasta\NC_008253.fna" and press "Open" // 4. Close MSAEditor GTUtilsMdi::click(os, GTGlobals::Close); // 5. Save document "big.aln" GTUtilsDialog::waitForDialog(os, new SaveProjectDialogFiller(os, QDialogButtonBox::No)); GTKeyboardDriver::keyClick('s', Qt::ControlModifier); GTGlobals::sleep(5000); //close project if (AppContext::getProject() != NULL) { GTGlobals::sleep(); GTWidget::click(os, GTUtilsProjectTreeView::getTreeView(os)); GTKeyboardDriver::keyClick('a', Qt::ControlModifier); GTGlobals::sleep(100); //GTUtilsDialog::waitForDialogWhichMayRunOrNot(os, new SaveProjectDialogFiller(os, QDialogButtonBox::No)); //GTUtilsDialog::waitForDialogWhichMayRunOrNot(os, new AppCloseMessageBoxDialogFiller(os)); GTKeyboardDriver::keyClick(Qt::Key_Delete); GTGlobals::sleep(500); #ifdef Q_OS_MAC GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Close project"); #else GTKeyboardDriver::keyClick('q', Qt::ControlModifier); GTGlobals::sleep(100); #endif GTGlobals::sleep(500); } GTGlobals::sleep(20000); // Current state: UGENE crashes } GUI_TEST_CLASS_DEFINITION(test_3552) { //1. Open "_common_data\clustal\fungal - all.aln" GTFileDialog::openFile(os, testDir + "_common_data/clustal", "10000_sequences.aln", GTFileDialog::Open, GTGlobals::UseMouse); QLabel *taskInfoLabel = GTWidget::findExactWidget<QLabel *>(os, "taskInfoLabel"); while (!taskInfoLabel->text().contains("Render")) { uiLog.trace("actual text: " + taskInfoLabel->text()); GTGlobals::sleep(100); } GTGlobals::sleep(500); QProgressBar *taskProgressBar = GTWidget::findExactWidget<QProgressBar *>(os, "taskProgressBar"); QString text = taskProgressBar->text(); CHECK_SET_ERR(text.contains("%"), "unexpected text: " + text); GTUtilsTaskTreeView::waitTaskFinished(os); // GTWidget::click(os, GTWidget::findWidget(os, "doc_lable_dock_task_view")); // GTGlobals::sleep(300); // GTWidget::click(os, GTWidget::findWidget(os, "doc_lable_dock_task_view")); //Expected state: render view task started, progress is correct } GUI_TEST_CLASS_DEFINITION(test_3553) { //1. Open "_common_data/clustal/big.aln". GTFileDialog::openFile(os, testDir + "_common_data/clustal", "big.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); //2. Select both sequences. GTUtilsMSAEditorSequenceArea::selectArea(os, QPoint(1, 0), QPoint(1, 1)); //3. Open the "Pairwise Alignment" OP tab. GTWidget::click(os, GTWidget::findWidget(os, "OP_PAIRALIGN")); //4. Press the "Align" button several times(~5). for (int i = 0; i < 5; i++) { GTWidget::click(os, GTWidget::findWidget(os, "alignButton")); GTGlobals::sleep(500); } //Expected: UGENE does not crash. } GUI_TEST_CLASS_DEFINITION(test_3555) { // 1. Open "_common_data\muscul4\prefab_1_ref.aln" // 2. Press "Switch on/off collapsing" tool button // 3. Scroll down sequences // Expected state: scrolling will continue until the last sequence becomes visible // Current state: see the attachment // 4. Click on the empty space below "1a0cA" sequence // Current state: SAFE_POINT in debug mode and incorrect selection in release(see the attachment) GTLogTracer l; GTFileDialog::openFile(os, testDir + "_common_data/muscul4/", "prefab_1_ref.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTWidget::click(os, GTToolbar::getWidgetForActionName(os, GTToolbar::getToolbar(os, "mwtoolbar_activemdi"), "Enable collapsing")); GTUtilsMSAEditorSequenceArea::scrollToBottom(os); QMainWindow *mw = AppContext::getMainWindow()->getQMainWindow(); MSAEditor *editor = mw->findChild<MSAEditor *>(); CHECK_SET_ERR(editor != NULL, "MsaEditor not found"); MaEditorNameList *nameList = editor->getUI()->getEditorNameList(); CHECK_SET_ERR(nameList != NULL, "MSANameList is empty"); GTWidget::click(os, nameList, Qt::LeftButton, QPoint(10, nameList->height() - 1)); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3556) { //1. Open "_common_data/muscul4/prefab_1_ref.aln". //2. Press the "Switch on/off collapsing" tool button. //3. Select the sequence "1a0cA". //4. Context menu: {Set with sequence as reference}. //Expected state: the sequence became reference. GTFileDialog::openFile(os, testDir + "_common_data/muscul4/", "prefab_1_ref.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTWidget::click(os, GTAction::button(os, "Enable collapsing")); GTUtilsMSAEditorSequenceArea::selectSequence(os, "1a0dA"); GTKeyboardDriver::keyClick(Qt::Key_End, Qt::ControlModifier); GTGlobals::sleep(); //GTUtilsMSAEditorSequenceArea::scrollToBottom(os); GTUtilsMSAEditorSequenceArea::selectSequence(os, "1a0cA"); const QPoint pos = GTMouseDriver::getMousePosition(); GTMouseDriver::moveTo(QPoint(pos.x(), pos.y() - 10)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "set_seq_as_reference")); GTMouseDriver::click(Qt::RightButton); GTWidget::click(os, GTWidget::findWidget(os, "OP_MSA_GENERAL")); QLineEdit *refEdit = qobject_cast<QLineEdit *>(GTWidget::findWidget(os, "sequenceLineEdit")); CHECK_SET_ERR(refEdit->text() == "1a0cA", "Wrong reference sequence"); } GUI_TEST_CLASS_DEFINITION(test_3557) { //1. Open "_common_data/muscul4/prefab_1_ref.aln". GTFileDialog::openFile(os, testDir + "_common_data/muscul4/", "prefab_1_ref.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); //2. Press the "Switch on/off collapsing" tool button. GTToolbar::clickButtonByTooltipOnToolbar(os, MWTOOLBAR_ACTIVEMDI, "Switch on/off collapsing"); //3. Select the "2|1a0cA|gi|32470780" and "1a0cA" sequences. //GTUtilsMSAEditorSequenceArea::scrollToBottom(os); GTUtilsMSAEditorSequenceArea::selectSequence(os, "1a0dA"); GTGlobals::sleep(); GTKeyboardDriver::keyClick(Qt::Key_End, Qt::ControlModifier); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(); // const int rowsCount = GTUtilsMsaEditor::getSequencesCount(os); GTUtilsMSAEditorSequenceArea::selectSequence(os, "2|1a0cA|gi|32470780"); GTGlobals::sleep(); GTKeyboardDriver::keyPress(Qt::Key_Shift); GTUtilsMSAEditorSequenceArea::selectSequence(os, "1a0cA"); GTKeyboardDriver::keyRelease(Qt::Key_Shift); //4. Open the "Pairwise Alignment" OP tab. GTUtilsOptionPanelMsa::openTab(os, GTUtilsOptionPanelMsa::PairwiseAlignment); //Expected: "2|1a0cA|gi|32470780" and "1a0cA" are in the OP. const QString firstRowName = GTUtilsOptionPanelMsa::getSeqFromPAlineEdit(os, 1); const QString secondRowName = GTUtilsOptionPanelMsa::getSeqFromPAlineEdit(os, 2); const QString expectedFirstRowName = "2|1a0cA|gi|32470780"; const QString expectedSecondRowName = "1a0cA"; CHECK_SET_ERR(firstRowName == expectedFirstRowName, QString("Wrong first sequence: expected '%1', got '%2'").arg(expectedFirstRowName).arg(firstRowName)); CHECK_SET_ERR(secondRowName == expectedSecondRowName, QString("Wrong second sequence: expected '%1', got '%2'").arg(expectedSecondRowName).arg(secondRowName)); } GUI_TEST_CLASS_DEFINITION(test_3563_1) { // 1. Open an alignment // 2. Build the tree // 3. Unload both documents (alignment and tree) // 4. Load alignment // Expected state: no errors in the log GTLogTracer l; GTFile::copy(os, testDir + "_common_data/clustal/dna.fasta.aln", testDir + "_common_data/scenarios/sandbox/test_3563_1.aln"); GTFileDialog::openFile(os, testDir + "_common_data/scenarios/sandbox/", "test_3563_1.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDialog::waitForDialog(os, new BuildTreeDialogFiller(os, testDir + "_common_data/scenarios/sandbox/test_3563_1.nwk", 0, 0, true)); QAbstractButton *tree = GTAction::button(os, "Build Tree"); GTWidget::click(os, tree); GTGlobals::sleep(); GTUtilsDocument::saveDocument(os, "test_3563_1.aln"); GTUtilsDocument::unloadDocument(os, "test_3563_1.nwk", false); GTGlobals::sleep(); GTUtilsDocument::unloadDocument(os, "test_3563_1.aln", true); GTGlobals::sleep(); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3563_2) { // 1. Open "human_T1.fa" // 2. Open "GFF/5prime_utr_intron_A21.gff" // 3. Drag and drop "Ca21 chr5 features" to "human_T1" // 4. Unload both documents // 5. Load "human_T1.fa" document // 6. Load "GFF/5prime_utr_intron_A21.gff" document // Expected state: no errors in the log GTLogTracer l; GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTFileDialog::openFile(os, dataDir + "samples/GFF/", "5prime_utr_intron_A21.gff"); GTUtilsTaskTreeView::waitTaskFinished(os); QModelIndex idxGff = GTUtilsProjectTreeView::findIndex(os, "Ca21chr5 features"); CHECK_SET_ERR(idxGff.isValid(), "Can not find 'Ca21 chr5 features' object"); QWidget *seqArea = GTWidget::findWidget(os, "render_area_human_T1 (UCSC April 2002 chr7:115977709-117855134)"); CHECK_SET_ERR(seqArea != NULL, "No sequence view opened"); GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, "Yes")); GTUtilsDialog::waitForDialog(os, new CreateObjectRelationDialogFiller(os)); GTUtilsProjectTreeView::dragAndDrop(os, idxGff, seqArea); GTUtilsDocument::unloadDocument(os, "human_T1.fa"); GTUtilsDocument::unloadDocument(os, "5prime_utr_intron_A21.gff", false); GTGlobals::sleep(); GTUtilsDocument::loadDocument(os, "human_T1.fa"); CHECK_SET_ERR(GTUtilsDocument::isDocumentLoaded(os, "5prime_utr_intron_A21.gff"), "Connection between documents was lost"); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3571_1) { // 1. Open file "test/_common_data/fasta/numbers_in_the_middle.fa" in sequence view class Custom : public CustomScenario { public: void run(HI::GUITestOpStatus &os) { QWidget *dialog = QApplication::activeModalWidget(); CHECK_SET_ERR(NULL != dialog, "activeModalWidget is NULL"); QRadioButton *separateRB = dialog->findChild<QRadioButton *>(QString::fromUtf8("separateRB")); CHECK_SET_ERR(separateRB != NULL, "radio button not found"); GTRadioButton::click(os, separateRB); GTUtilsDialog::clickButtonBox(os, dialog, QDialogButtonBox::Ok); GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::Ok)); } }; GTUtilsDialog::waitForDialog(os, new SequenceReadingModeSelectorDialogFiller(os, new Custom())); GTUtilsProject::openFile(os, testDir + "_common_data/fasta/numbers_in_the_middle.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Select first sequence ADVSingleSequenceWidget *firstSeqWidget = GTUtilsSequenceView::getSeqWidgetByNumber(os, 0); GTWidget::click(os, firstSeqWidget); // 3. Open statistics option panel tab. GTUtilsOptionPanelSequenceView::openTab(os, GTUtilsOptionPanelSequenceView::Statistics); // Expected state : only length info appears GTWidget::findWidget(os, "ArrowHeader_Common Statistics"); GTGlobals::FindOptions widgetFindSafeOptions(false); QWidget *charOccurWidget = GTWidget::findWidget(os, "ArrowHeader_Characters Occurrence", NULL, widgetFindSafeOptions); CHECK_SET_ERR(!charOccurWidget->isVisible(), "Character Occurrence section is unexpectedly visible"); // 4. Select second sequence ADVSingleSequenceWidget *secondSeqWidget = GTUtilsSequenceView::getSeqWidgetByNumber(os, 1); GTWidget::click(os, secondSeqWidget); // Expected state : length and characters occurrence info appears GTWidget::findWidget(os, "ArrowHeader_Common Statistics"); charOccurWidget = GTWidget::findWidget(os, "ArrowHeader_Characters Occurrence"); } GUI_TEST_CLASS_DEFINITION(test_3571_2) { // 1. Open file test/_common_data/fasta/numbers_in_the_middle.fa in sequence view class Custom : public CustomScenario { public: void run(HI::GUITestOpStatus &os) { QWidget *dialog = QApplication::activeModalWidget(); CHECK_SET_ERR(NULL != dialog, "activeModalWidget is NULL"); QRadioButton *separateRB = dialog->findChild<QRadioButton *>(QString::fromUtf8("separateRB")); CHECK_SET_ERR(separateRB != NULL, "radio button not found"); GTRadioButton::click(os, separateRB); GTUtilsDialog::clickButtonBox(os, dialog, QDialogButtonBox::Ok); GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::Ok)); } }; GTUtilsDialog::waitForDialog(os, new SequenceReadingModeSelectorDialogFiller(os, new Custom())); GTUtilsProject::openFile(os, testDir + "_common_data/fasta/numbers_in_the_middle.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Select second sequence ADVSingleSequenceWidget *secondSeqWidget = GTUtilsSequenceView::getSeqWidgetByNumber(os, 1); GTWidget::click(os, secondSeqWidget); // 3. Open statistics option panel tab. GTUtilsOptionPanelSequenceView::openTab(os, GTUtilsOptionPanelSequenceView::Statistics); // Expected state : length and characters occurrence info appears GTWidget::findWidget(os, "ArrowHeader_Common Statistics"); QWidget *charOccurWidget = GTWidget::findWidget(os, "ArrowHeader_Characters Occurrence"); // 4. Select first sequence ADVSingleSequenceWidget *firstSeqWidget = GTUtilsSequenceView::getSeqWidgetByNumber(os, 0); GTWidget::click(os, firstSeqWidget); // Expected state : only length info appears GTWidget::findWidget(os, "ArrowHeader_Common Statistics"); GTGlobals::FindOptions widgetFindSafeOptions(false); charOccurWidget = GTWidget::findWidget(os, "ArrowHeader_Characters Occurrence", NULL, widgetFindSafeOptions); CHECK_SET_ERR(!charOccurWidget->isVisible(), "Character Occurrence section is unexpectedly visible"); } GUI_TEST_CLASS_DEFINITION(test_3589) { // 0. Copy "data/samples/Assembly/chrM.sam" to a new folder to avoid UGENE conversion cache. // 1. Create a workflow: Read assembly. // 2. Set an input file: that copied chrM.sam. // 3. Run the workflow. // Expected state: there are warnings about header in log and dashboard. QString dirName = "test_3589_" + QDateTime::currentDateTime().toString("yyyy.MM.dd_HH.mm.ss"); QString dirPath = sandBoxDir + dirName + "/"; QDir().mkpath(dirPath); GTFile::copy(os, dataDir + "samples/Assembly/chrM.sam", dirPath + "chrM.sam"); GTLogTracer l; GTUtilsWorkflowDesigner::openWorkflowDesigner(os); WorkflowProcessItem *read = GTUtilsWorkflowDesigner::addElement(os, "Read NGS Reads Assembly"); CHECK_SET_ERR(read != NULL, "Added workflow element is NULL"); GTGlobals::sleep(); GTUtilsWorkflowDesigner::setDatasetInputFile(os, dirPath + "chrM.sam"); GTUtilsWorkflowDesigner::runWorkflow(os); GTUtilsTaskTreeView::waitTaskFinished(os); CHECK_SET_ERR(l.getJoinedErrorString().contains("There is no header in the SAM file"), "No warnings about header"); CHECK_SET_ERR(2 == GTUtilsLog::getErrors(os, l).size(), "Too many errors"); // initial warning and dashboard problem } GUI_TEST_CLASS_DEFINITION(test_3603) { // 1. Open "data/samples/FASTA/human_T1.fa". // 2. Open "Find Pattern" options panel tab. // 3. Set "Selected" region type. // 4. Call context menu on the sequence view, and select "Select sequence regions...". // 5. Accept the dialog with default values (a single region, from min to max). // Expected state: the region selector widget contains "Selected" region type, region is (1..199950). // Current state: the region selector widget contains "Selected" region type, region is (1..199951). GTLogTracer l; GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTWidget::click(os, GTWidget::findWidget(os, "OP_FIND_PATTERN")); QComboBox *regionComboBox = qobject_cast<QComboBox *>(GTWidget::findWidget(os, "boxRegion")); CHECK_SET_ERR(regionComboBox != NULL, "Region comboBox is NULL"); if (!regionComboBox->isVisible()) { GTWidget::click(os, GTWidget::findWidget(os, "ArrowHeader_Search in")); } GTComboBox::setIndexWithText(os, regionComboBox, "Selected region"); QWidget *renderArea = GTUtilsSequenceView::getSeqWidgetByNumber(os); CHECK_SET_ERR(renderArea != NULL, "Render area is NULL"); GTWidget::click(os, renderArea); GTUtilsDialog::waitForDialog(os, new SelectSequenceRegionDialogFiller(os)); GTKeyboardDriver::keyClick('a', Qt::ControlModifier); QLineEdit *start = qobject_cast<QLineEdit *>(GTWidget::findWidget(os, "editStart")); CHECK_SET_ERR(start != NULL, "Region start lineEdit is NULL"); QLineEdit *end = qobject_cast<QLineEdit *>(GTWidget::findWidget(os, "editEnd")); CHECK_SET_ERR(end != NULL, "Region end lineEdit is NULL"); CHECK_SET_ERR(start->text() == "1" && end->text() == "199950", "Selection is wrong!"); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3609_1) { // 1. Open "data/samples/FASTA/human_T1.fa". // 2. Call context menu on the sequence view, select {Edit sequence -> Remove subsequence...} menu item. // 3. Remove region (5000..199950). // 4. Enter position 50000 to the "goto" widget on the tool bar, click the "Go" button. // Expected state: you can't enter this position. // Current state: you can enter this position, an error message appears in the log after button click (safe point triggers in the debug mode). GTLogTracer l; GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // Click "Hide zoom view" QWidget *toolbar = GTWidget::findWidget(os, "views_tool_bar_human_T1 (UCSC April 2002 chr7:115977709-117855134)"); CHECK_SET_ERR(toolbar != nullptr, "Cannot find views_tool_bar_human_T1(UCSC April 2002 chr7:115977709-117855134)"); GTWidget::click(os, GTWidget::findWidget(os, "show_hide_zoom_view", toolbar)); QWidget *seqWidget = GTUtilsSequenceView::getSeqWidgetByNumber(os); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ADV_MENU_EDIT << ACTION_EDIT_REMOVE_SUBSEQUENCE)); GTUtilsDialog::waitForDialog(os, new RemovePartFromSequenceDialogFiller(os, "5000..199950")); GTWidget::click(os, seqWidget, Qt::RightButton); QLineEdit *goToPosLineEdit = qobject_cast<QLineEdit *>(GTWidget::findWidget(os, "go_to_pos_line_edit")); CHECK_SET_ERR(goToPosLineEdit != NULL, "GoTo lineEdit is NULL"); bool inputResult = GTLineEdit::tryToSetText(os, goToPosLineEdit, "50000"); CHECK_SET_ERR(inputResult == false, "Invalid goToPosition is accepted"); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3609_2) { // 1. Open "data/samples/FASTA/human_T1.fa". // 2. Call context menu on the sequence view, select {Edit sequence -> Insert subsequence...} menu item. // 3. Insert any subsequence long enough. // 4. Enter position 199960 to the "goto" widget on the tool bar, click the "Go" button. // Expected state: you can enter this position, view shows the position. // Current state: you can't enter this position. GTLogTracer l; GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // Click "Hide zoom view" QWidget *toolbar = GTWidget::findWidget(os, "views_tool_bar_human_T1 (UCSC April 2002 chr7:115977709-117855134)"); CHECK_SET_ERR(toolbar != nullptr, "Cannot find views_tool_bar_human_T1(UCSC April 2002 chr7:115977709-117855134)"); GTWidget::click(os, GTWidget::findWidget(os, "show_hide_zoom_view", toolbar)); QWidget *seqWidget = GTUtilsSequenceView::getSeqWidgetByNumber(os); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ADV_MENU_EDIT << ACTION_EDIT_INSERT_SUBSEQUENCE)); GTUtilsDialog::waitForDialog(os, new InsertSequenceFiller(os, "AAACCCTTTGGGAAA")); GTWidget::click(os, seqWidget, Qt::RightButton); QLineEdit *goToPosLineEdit = qobject_cast<QLineEdit *>(GTWidget::findWidget(os, "go_to_pos_line_edit")); CHECK_SET_ERR(goToPosLineEdit != NULL, "GoTo lineEdit is NULL"); GTLineEdit::setText(os, goToPosLineEdit, "199960"); QWidget *goBtn = GTWidget::findWidget(os, "Go!"); CHECK_SET_ERR(goBtn != NULL, "Go! button is NULL"); GTWidget::click(os, goBtn); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3609_3) { // 1. Open "data/samples/FASTA/human_T1.fa". // 2. Call context menu on the sequence view, select {Edit sequence -> Insert subsequence...} menu item. // 3. Insert any subsequence long enough. // 4. Call context menu, select {Go to position...} menu item. // 5. Enter position 199960 and accept the dialog. // Expected state: view shows the position, there are no errors in the log. // Current state: view shows the position, there is an error in the log (safe point triggers in the debug mode). GTLogTracer l; GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // Click "Hide zoom view" QWidget *toolbar = GTWidget::findWidget(os, "views_tool_bar_human_T1 (UCSC April 2002 chr7:115977709-117855134)"); CHECK_SET_ERR(toolbar != nullptr, "Cannot find views_tool_bar_human_T1(UCSC April 2002 chr7:115977709-117855134)"); GTWidget::click(os, GTWidget::findWidget(os, "show_hide_zoom_view", toolbar)); QWidget *seqWidget = GTUtilsSequenceView::getSeqWidgetByNumber(os); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ADV_MENU_EDIT << ACTION_EDIT_INSERT_SUBSEQUENCE)); GTUtilsDialog::waitForDialog(os, new InsertSequenceFiller(os, "AAACCCTTTGGGAAA")); GTWidget::click(os, seqWidget, Qt::RightButton); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ADV_GOTO_ACTION)); GTUtilsDialog::waitForDialog(os, new GoToDialogFiller(os, 199960)); GTWidget::click(os, seqWidget, Qt::RightButton); GTGlobals::sleep(5000); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3610) { // Open "data/samples/FASTA/human_T1.fa". // Select whole sequence. // Call context menu, select {Edit sequence -> Replace subsequence...}menu item. // Replace whole sequence with any inappropriate symbol, e.g. '='. Accept the dialog, agree with message box. // Expected state: UGENE doesn't crash. GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // Click "Hide zoom view" QWidget *toolbar = GTWidget::findWidget(os, "views_tool_bar_human_T1 (UCSC April 2002 chr7:115977709-117855134)"); CHECK_SET_ERR(toolbar != nullptr, "Cannot find views_tool_bar_human_T1(UCSC April 2002 chr7:115977709-117855134)"); GTWidget::click(os, GTWidget::findWidget(os, "show_hide_zoom_view", toolbar)); GTUtilsDialog::waitForDialog(os, new SelectSequenceRegionDialogFiller(os, 1, 199950)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Select" << "Sequence region")); GTMouseDriver::click(Qt::RightButton); GTGlobals::sleep(1000); class Scenario : public CustomScenario { void run(HI::GUITestOpStatus &os) { QWidget *dialog = QApplication::activeModalWidget(); CHECK_SET_ERR(NULL != dialog, "Active modal widget is NULL"); QPlainTextEdit *plainText = dialog->findChild<QPlainTextEdit *>("sequenceEdit"); CHECK_SET_ERR(plainText != NULL, "plain text not found"); GTWidget::click(os, plainText); GTKeyboardDriver::keyClick('A', Qt::ControlModifier); GTKeyboardDriver::keyClick('='); GTUtilsDialog::clickButtonBox(os, dialog, QDialogButtonBox::Ok); GTGlobals::sleep(); GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, "Ok")); GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, "Ok")); GTGlobals::sleep(); GTKeyboardDriver::keyClick(Qt::Key_Escape); } }; Runnable *filler = new ReplaceSubsequenceDialogFiller(os, new Scenario); GTUtilsDialog::waitForDialog(os, filler); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ADV_MENU_EDIT << ACTION_EDIT_REPLACE_SUBSEQUENCE)); GTUtilsSequenceView::openPopupMenuOnSequenceViewArea(os); } GUI_TEST_CLASS_DEFINITION(test_3612) { // 1. Open "_common_data/scenarios/msa/ma.aln". GTFileDialog::openFile(os, testDir + "_common_data/scenarios/msa", "ma.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Turn on the collapsing mode. GTUtilsMsaEditor::toggleCollapsingMode(os); // 3. Expand "Conocephalus_discolor" group. GTUtilsMSAEditorSequenceArea::clickCollapseTriangle(os, "Conocephalus_discolor"); // 4. Open "Pairwise alignment" options panel tab. GTUtilsOptionPanelMsa::openTab(os, GTUtilsOptionPanelMsa::PairwiseAlignment); // 5. Set parameters: // First sequence: Tettigonia_viridissima // Second sequence: Conocephalus_discolor // Algorithm: Smith-Waterman // Gap open penalty: 1 // In new window: unchecked // and start the align task. // Expected state: these two sequences are aligned, the same changes are applied to whole collapsing group. GTUtilsOptionPanelMsa::addFirstSeqToPA(os, "Tettigonia_viridissima"); GTUtilsOptionPanelMsa::addSecondSeqToPA(os, "Conocephalus_discolor"); GTWidget::click(os, GTWidget::findWidget(os, "ArrowHeader_Algorithm settings")); GTWidget::click(os, GTWidget::findWidget(os, "ArrowHeader_Output settings")); GTComboBox::setIndexWithText(os, GTWidget::findExactWidget<QComboBox *>(os, "algorithmListComboBox"), "Smith-Waterman"); GTSpinBox::setValue(os, GTWidget::findExactWidget<QSpinBox *>(os, "gapOpen"), 1); GTCheckBox::setChecked(os, GTWidget::findExactWidget<QCheckBox *>(os, "inNewWindowCheckBox"), false); GTWidget::click(os, GTWidget::findWidget(os, "alignButton")); GTUtilsTaskTreeView::waitTaskFinished(os); const QString firstSequence = GTUtilsMSAEditorSequenceArea::getSequenceData(os, "Conocephalus_discolor"); const QString secondSequence = GTUtilsMSAEditorSequenceArea::getSequenceData(os, "Conocephalus_sp."); CHECK_SET_ERR(firstSequence == "TT-AGCT-TATTAA", "Unexpected selection. Expected: TT-AGCT-TATTAA"); CHECK_SET_ERR(secondSequence == "TTAGCTTATTAA--", "Unexpected selection. Expected: TTAGCTTATTAA--"); } GUI_TEST_CLASS_DEFINITION(test_3613) { // 1. Open any assembly. // 2. Call a context menu on any read, select {Export -> Current Read} menu item. // 3, Set any appropriate destination and apply the dialog. // Expected state: a new document is added to the project, a view opens (MSA Editor or Sequence view, it should be clarified, see the documentation). // Current state: a new unloaded document is added to the project. If you force it to open it will load but "open view" task will fail with an error: "Multiple alignment object not found". GTLogTracer l; GTUtilsDialog::waitForDialog(os, new ImportBAMFileFiller(os, sandBoxDir + "test_3613.bam.ugenedb")); GTFileDialog::openFile(os, testDir + "_common_data/scenarios/assembly/", "example-alignment.bam"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(); GTUtilsAssemblyBrowser::zoomToMax(os); GTUtilsDialog::waitForDialog(os, new PopupChooserByText(os, QStringList() << "Export" << "Current read")); GTUtilsDialog::waitForDialog(os, new ExportReadsDialogFiller(os, sandBoxDir + "test_3613.fa")); QWidget *readsArea = GTWidget::findWidget(os, "assembly_reads_area"); CHECK_SET_ERR(readsArea != NULL, "Assembly reads area not found"); GTWidget::click(os, readsArea, Qt::RightButton); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3619) { GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsOptionPanelSequenceView::openTab(os, GTUtilsOptionPanelSequenceView::Search); QWidget *progressLabel = GTWidget::findWidget(os, "progressLabel"); QWidget *resultLabel = GTWidget::findWidget(os, "resultLabel"); GTUtilsOptionPanelSequenceView::setAlgorithm(os, "Regular expression"); GTUtilsOptionPanelSequenceView::enterPattern(os, "."); GTUtilsTaskTreeView::waitTaskFinished(os); CHECK_SET_ERR(progressLabel->isHidden() && resultLabel->isVisible(), "Wrong hide, show conditions 2"); } GUI_TEST_CLASS_DEFINITION(test_3622) { // 1. Open "data/samples/FASTA/human_T1.fa". // 2. Open "Find pattern" options panel tab. // 3. Enter any valid pattern. // Expected state: a new search task is launched. // 4. Set "InsDel" algorithm. // Expected state: a new search task is launched. // 5. Set any another match value. // Expected state: a new search task is launched. // 6. Set "Substitute" algorithm. // Expected state: a new search task is launched. // 7. Set any another match value. // Expected state: a new search task is launched. // 8. Turn on "Search with ambiguous bases" option. // Expected state: a new search task is launched. // 9. Select any sequence region. // 10. Set "Selected region" region type. // Expected state: a new search task is launched, the region type is set to "Custom region", the region is the same as the selected one. // 11. Change the region. // Expected state: a new search task is launched. GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsOptionPanelSequenceView::openTab(os, GTUtilsOptionPanelSequenceView::Search); SchedulerListener listener; GTUtilsOptionPanelSequenceView::enterPattern(os, "ACGT"); CHECK_SET_ERR(0 < listener.getRegisteredTaskCount(), "The search task wasn't registered"); listener.reset(); GTGlobals::sleep(200); GTUtilsOptionPanelSequenceView::setAlgorithm(os, "InsDel"); CHECK_SET_ERR(0 < listener.getRegisteredTaskCount(), "The search task wasn't registered"); listener.reset(); GTGlobals::sleep(200); GTUtilsOptionPanelSequenceView::setMatchPercentage(os, 80); CHECK_SET_ERR(0 < listener.getRegisteredTaskCount(), "The search task wasn't registered"); listener.reset(); GTGlobals::sleep(200); GTUtilsOptionPanelSequenceView::setAlgorithm(os, "Substitute"); CHECK_SET_ERR(0 < listener.getRegisteredTaskCount(), "The search task wasn't registered"); listener.reset(); GTGlobals::sleep(200); GTUtilsOptionPanelSequenceView::setMatchPercentage(os, 90); CHECK_SET_ERR(0 < listener.getRegisteredTaskCount(), "The search task wasn't registered"); listener.reset(); GTGlobals::sleep(200); GTUtilsOptionPanelSequenceView::setSearchWithAmbiguousBases(os); CHECK_SET_ERR(0 < listener.getRegisteredTaskCount(), "The search task wasn't registered"); listener.reset(); GTGlobals::sleep(200); GTUtilsSequenceView::selectSequenceRegion(os, 100, 200); GTUtilsOptionPanelSequenceView::setRegionType(os, "Selected region"); CHECK_SET_ERR(0 < listener.getRegisteredTaskCount(), "The search task wasn't registered"); listener.reset(); GTGlobals::sleep(200); const QString currentRegionType = GTUtilsOptionPanelSequenceView::getRegionType(os); CHECK_SET_ERR("Custom region" == currentRegionType, QString("An unexpected region type: expect '%1', got '%2'").arg("Custom region").arg(currentRegionType)); const QPair<int, int> currentRegion = GTUtilsOptionPanelSequenceView::getRegion(os); CHECK_SET_ERR(qMakePair(100, 200) == currentRegion, QString("An unexpected region: expect [%1, %2], got [%3, %4]").arg(100).arg(200).arg(currentRegion.first).arg(currentRegion.second)); GTUtilsOptionPanelSequenceView::setRegion(os, 500, 1000); CHECK_SET_ERR(0 < listener.getRegisteredTaskCount(), "The search task wasn't registered"); } GUI_TEST_CLASS_DEFINITION(test_3623) { GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsOptionPanelSequenceView::openTab(os, GTUtilsOptionPanelSequenceView::Search); GTUtilsOptionPanelSequenceView::enterPattern(os, "AAAAAAAAAAAAAAAAAAAAAAAAAAA"); GTUtilsOptionPanelSequenceView::toggleSaveAnnotationsTo(os); GTUtilsOptionPanelSequenceView::enterFilepathForSavingAnnotations(os, sandBoxDir + "op_seqview_test_0001.gb"); GTUtilsOptionPanelSequenceView::clickGetAnnotation(os); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(); CHECK_SET_ERR(GTUtilsOptionPanelSequenceView::isPrevNextEnabled(os), "Next and prev buttons are disabled"); } GUI_TEST_CLASS_DEFINITION(test_3625) { GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsOptionPanelSequenceView::openTab(os, GTUtilsOptionPanelSequenceView::Search); GTUtilsOptionPanelSequenceView::enterPattern(os, "ACACACACACACACACACACACACACAC", true); CHECK_SET_ERR(GTUtilsOptionPanelSequenceView::checkResultsText(os, "Results: 1/33"), "Results string not match. Expected 33."); GTWidget::click(os, GTWidget::findWidget(os, "ArrowHeader_Other settings")); QCheckBox *removeOverlapsBox = GTWidget::findExactWidget<QCheckBox *>(os, "removeOverlapsBox"); GTWidget::click(os, removeOverlapsBox); CHECK_SET_ERR(GTUtilsOptionPanelSequenceView::checkResultsText(os, "Results: 1/7"), "Results string not match. Expected 7."); GTWidget::click(os, removeOverlapsBox); GTUtilsOptionPanelSequenceView::setAlgorithm(os, "Regular expression"); GTUtilsOptionPanelSequenceView::enterPattern(os, "(AAAAAAAAAAAAAAAAAAAAA)+", true); CHECK_SET_ERR(GTUtilsOptionPanelSequenceView::checkResultsText(os, "Results: 1/28"), "Results string not match. Expected 28."); GTWidget::click(os, removeOverlapsBox); CHECK_SET_ERR(GTUtilsOptionPanelSequenceView::checkResultsText(os, "Results: 1/11"), "Results string not match. Expected 11."); } GUI_TEST_CLASS_DEFINITION(test_3629) { // 1. Open "data/samples/FASTA/human_T1.fa". GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Select {Add->New annotation...} menu item in the context menu. // Expected state: "Create Annotation" dialog appeared, "create new table" option is selected. // 3. Set any location and press "Create". // Expected state: new annotation object was created. QDir().mkpath(sandBoxDir + "test_3629"); GTUtilsDialog::waitForDialog(os, new CreateAnnotationWidgetFiller(os, true, "<auto>", "misc_feature", "1..5", sandBoxDir + "test_3629/test_3629.gb")); GTWidget::click(os, GTToolbar::getWidgetForActionTooltip(os, GTToolbar::getToolbar(os, MWTOOLBAR_ACTIVEMDI), "New annotation")); GTUtilsProjectTreeView::checkItem(os, "test_3629.gb"); // 4. Open "data/samples/Genbank/sars.gb". GTFileDialog::openFile(os, dataDir + "samples/Genbank", "sars.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); // 5. Add the annotation object to "sars" sequence. GTUtilsDialog::waitForDialog(os, new CreateObjectRelationDialogFiller(os)); GTUtilsProjectTreeView::dragAndDrop(os, GTUtilsProjectTreeView::findIndex(os, "Annotations"), GTUtilsAnnotationsTreeView::getTreeWidget(os)); // 6. Switch view to "human_T1". // Expected state: there are no attached annotations. GTUtilsProjectTreeView::doubleClickItem(os, "human_T1.fa"); GTThread::waitForMainThread(); QList<QTreeWidgetItem *> list = GTUtilsAnnotationsTreeView::findItems(os, "misc_feature", GTGlobals::FindOptions(false)); CHECK_SET_ERR(list.isEmpty(), QString("%1 annotation(s) unexpectidly found").arg(list.count())); } GUI_TEST_CLASS_DEFINITION(test_3645) { //checking results with diffirent algorithms GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsSequenceView::checkSequenceViewWindowIsActive(os); GTUtilsOptionPanelSequenceView::openTab(os, GTUtilsOptionPanelSequenceView::Search); GTUtilsOptionPanelSequenceView::isTabOpened(os, GTUtilsOptionPanelSequenceView::Search); GTUtilsOptionPanelSequenceView::toggleInputFromFilePattern(os); GTUtilsOptionPanelSequenceView::enterPatternFromFile(os, testDir + "_common_data/FindAlgorithm/", "find_pattern_op_2.fa"); GTUtilsOptionPanelSequenceView::clickNext(os); GTUtilsOptionPanelSequenceView::clickNext(os); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ADV_MENU_COPY << "Copy sequence", GTGlobals::UseMouse)); GTUtilsSequenceView::openPopupMenuOnSequenceViewArea(os); QString clipStr = GTClipboard::text(os); CHECK_SET_ERR(clipStr == "GGGGG", "Found sequence don't match"); } GUI_TEST_CLASS_DEFINITION(test_3634) { //1. File -> Open as -> "_common_data/gtf/invalid/AB375112_annotations.gtf". //Expected: the "Select correct document format" dialog appears. //2. Choose "GTF" in the combobox. //3. Click OK. // Expected: the file is not opened. GTLogTracer l; GTUtilsDialog::waitForDialog(os, new GTFileDialogUtils(os, testDir + "_common_data/gtf/invalid", "AB375112_annotations.gtf")); GTUtilsDialog::waitForDialog(os, new DocumentFormatSelectorDialogFiller(os, "GTF")); GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Open as..."); GTGlobals::sleep(); CHECK_SET_ERR(l.hasErrors(), "Expected to have errors in the log, but no errors found"); } GUI_TEST_CLASS_DEFINITION(test_3639) { GTLogTracer logTracer; //2. Open "human_T1.fa". GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); //1. Connect to any shared database with write permissions. GTUtilsSharedDatabaseDocument::connectToTestDatabase(os); //3. Select "human_T1.fa" document and a 'Recycle bin" folder in the project view. GTGlobals::FindOptions options; options.depth = 1; QModelIndex humanT1Doc = GTUtilsProjectTreeView::findIndex(os, "human_T1.fa", options); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, humanT1Doc)); GTMouseDriver::click(); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "Recycle bin")); GTKeyboardDriver::keyPress(Qt::Key_Control); GTMouseDriver::click(); GTKeyboardDriver::keyRelease(Qt::Key_Control); //4. Remove items with "del" key. GTKeyboardDriver::keyClick(Qt::Key_Delete); //Expected state: the document is removed, the folder is not removed, no message boxes appear. CHECK_SET_ERR(!logTracer.hasErrors(), "Errors in log: " + logTracer.getJoinedErrorString()); GTUtilsProjectTreeView::getItemCenter(os, "Recycle bin"); options.failIfNotFound = false; humanT1Doc = GTUtilsProjectTreeView::findIndex(os, "human_T1.fa", options); CHECK_SET_ERR(!humanT1Doc.isValid(), "The document is not removed"); } GUI_TEST_CLASS_DEFINITION(test_3640) { GTLogTracer logTracer; //2. Open any document. GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsSequenceView::checkSequenceViewWindowIsActive(os); //1. Connect to a read-only shared database (e.g. to the UGENE public database). GTUtilsSharedDatabaseDocument::connectToUgenePublicDatabase(os); //3. Select the document and any folder in the database in the project view. GTGlobals::FindOptions options; options.depth = 1; QModelIndex humanT1Doc = GTUtilsProjectTreeView::findIndex(os, "human_T1.fa", options); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, humanT1Doc)); GTMouseDriver::click(); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "genomes")); GTKeyboardDriver::keyPress(Qt::Key_Control); GTMouseDriver::click(); GTKeyboardDriver::keyRelease(Qt::Key_Control); //4. Remove selected items via "del" key. GTKeyboardDriver::keyClick(Qt::Key_Delete); //Expected state: the document is removed, the folder is not removed. CHECK_SET_ERR(!logTracer.hasErrors(), "Errors in log: " + logTracer.getJoinedErrorString()); GTUtilsProjectTreeView::findIndex(os, "genomes"); options.failIfNotFound = false; humanT1Doc = GTUtilsProjectTreeView::findIndex(os, "human_T1.fa", options); CHECK_SET_ERR(!humanT1Doc.isValid(), "The document is not removed"); } GUI_TEST_CLASS_DEFINITION(test_3649) { //1. Open "_common_data/smith-waterman2/simple/05/search.txt". GTFileDialog::openFile(os, testDir + "_common_data/smith_waterman2/simple/05", "search.txt"); GTUtilsTaskTreeView::waitTaskFinished(os); //2. Export the sequence object as alignment. GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ACTION_PROJECT__EXPORT_IMPORT_MENU_ACTION << ACTION_EXPORT_SEQUENCE_AS_ALIGNMENT)); GTUtilsDialog::waitForDialog(os, new ExportSequenceAsAlignmentFiller(os, testDir + "_common_data/scenarios/sandbox", "test_3649.aln", ExportSequenceAsAlignmentFiller::Clustalw, true)); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "S")); GTMouseDriver::click(Qt::RightButton); GTGlobals::sleep(); //3. Add a sequence from the file "_common_data/smith-waterman2/simple/05/query.txt" in the alignment. GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << MSAE_MENU_LOAD << "Sequence from file")); GTUtilsDialog::waitForDialog(os, new GTFileDialogUtils(os, testDir + "_common_data/smith_waterman2/simple/05", "query.txt")); GTWidget::click(os, GTUtilsMdi::activeWindow(os), Qt::RightButton); GTUtilsTaskTreeView::waitTaskFinished(os); //4. Select both sequences. GTUtilsMSAEditorSequenceArea::selectArea(os, QPoint(0, 0), QPoint(1, 1)); //5. Open pairwise alignment option panel tab. GTWidget::click(os, GTWidget::findWidget(os, "OP_PAIRALIGN")); //6. Align using the Smith-Waterman algorithm. GTUtilsOptionPanelMsa::setPairwiseAlignmentAlgorithm(os, "Smith-Waterman"); GTWidget::click(os, GTUtilsOptionPanelMsa::getAlignButton(os)); //Expected: UGENE does not crash. } GUI_TEST_CLASS_DEFINITION(test_3656) { // 1. Connect to the public database // 2. Go to /genomes/Human (hg 19) // 3. Right click on "chr2", then choose { Export/Import -> Export Sequences... } // Expected state: the "Export Sequences" dialog has appeared. // 4. Press "OK" // Expected state: Export task has launched and successfully finished. // Current state: UGENE hangs for a half of minute, then Export task is launched. GTLogTracer lt; GTUtilsSharedDatabaseDocument::connectToUgenePublicDatabase(os); CHECK_OP(os, ); GTUtilsTaskTreeView::waitTaskFinished(os); GTThread::waitForMainThread(); QTreeView *treeView = GTUtilsProjectTreeView::getTreeView(os); CHECK_SET_ERR(treeView != NULL, "Invalid project tree view"); QModelIndex prnt = GTUtilsProjectTreeView::findIndex(os, "Human (hg19)"); QModelIndex idx = GTUtilsProjectTreeView::findIndex(os, "chr2", prnt); GTThread::waitForMainThread(); GTUtils::checkExportServiceIsEnabled(os); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, idx)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ACTION_PROJECT__EXPORT_IMPORT_MENU_ACTION << ACTION_EXPORT_SEQUENCE)); GTUtilsDialog::waitForDialog(os, new ExportSelectedRegionFiller(os, testDir + "_common_data/scenarios/sandbox/", "test_3656.fa")); GTMouseDriver::click(Qt::RightButton); CHECK_SET_ERR(GTUtilsTaskTreeView::checkTask(os, "Export sequence to document"), "Task is not running!"); GTUtilsTaskTreeView::cancelTask(os, "Export sequence to document"); } GUI_TEST_CLASS_DEFINITION(test_3658) { // 1. Open the WD GTUtilsWorkflowDesigner::openWorkflowDesigner(os); // 2. Add "Call Varinats with Samtools" workflow element GTUtilsWorkflowDesigner::addAlgorithm(os, "Write Annotations"); // 3. Press on the toolbar // {Scripting mode->Show scripting options} GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Show scripting options")); GTWidget::click(os, GTAction::button(os, GTAction::findActionByText(os, "Scripting mode"))); // 4. Click on the workflow element GTUtilsWorkflowDesigner::click(os, "Write Annotations"); // Expected state: property editor appeared // 5. Press on the toolbar // {Scripting mode->Hide scripting options} GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Hide scripting options")); GTWidget::click(os, GTAction::button(os, GTAction::findActionByText(os, "Scripting mode"))); // Expected state: scripting column is hidden QTableView *table = qobject_cast<QTableView *>(GTWidget::findWidget(os, "table")); int count = table->model()->columnCount(); CHECK_SET_ERR(count == 2, QString("wrong columns number. expected 2, actual: %1").arg(count)); } GUI_TEST_CLASS_DEFINITION(test_3675) { /* 1. Open file COI.aln 2. Press "build tree" button on main toolbar 3. In build tree dialog set path like this: some_existing_folder/some_not_existing_folder/COI.nwk 4. Press build. Expected state: new folder created, COI.nwk writter there Actual state: error messagebox appeares: "you don't have permission to write to this folder" */ GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDialog::waitForDialog(os, new BuildTreeDialogFiller(os, sandBoxDir + "some_not_existing_folder/COI.nwk", 0, 0, true)); GTWidget::click(os, GTAction::button(os, GTAction::findAction(os, "Build Tree"))); GTUtilsTaskTreeView::waitTaskFinished(os); CHECK_SET_ERR(QFile::exists(sandBoxDir + "some_not_existing_folder/COI.nwk"), "File sandBoxDir/some_not_existing_folder/COI.nwk does not exist"); } GUI_TEST_CLASS_DEFINITION(test_3676) { //1. Open human_T1.fa //2. Context menu {Analyze --> Primer3} //Expected state: 'Primer Designer' dialog appeared //3. Go to Result Settings tab //4. Set group name and annotation name //5. Pick primers //Current state: a group name is correct, but annotations name is 'primer' //Expected state: all items have corresponding values from the dialog. GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); Primer3DialogFiller::Primer3Settings settings; settings.primersName = "testPrimer"; GTUtilsDialog::waitForDialog(os, new Primer3DialogFiller(os, settings)); GTWidget::click(os, GTWidget::findWidget(os, "primer3_action_widget")); GTUtilsTaskTreeView::waitTaskFinished(os); QTreeWidgetItem *testPrimer = GTUtilsAnnotationsTreeView::findItem(os, "testPrimer"); CHECK_SET_ERR(testPrimer != NULL, "Can not find item with name \"testPrimer\""); } GUI_TEST_CLASS_DEFINITION(test_3687_1) { //1. Open file "_common_data/NGS_tutorials/RNA-Seq_Analysis/Prepare_Raw_Data/lymph.fastq". //Expected state: "Sequence Reading Options" dialog appeared. //2. Select "As separate sequences in sequence viewer" in the dialog. //3. Press "Ok". //Expected: the finishes with error about sequences amount. qputenv("UGENE_MAX_OBJECTS_PER_DOCUMENT", "100"); GTUtilsDialog::waitForDialog(os, new SequenceReadingModeSelectorDialogFiller(os, SequenceReadingModeSelectorDialogFiller::Separate)); GTUtilsNotifications::waitForNotification(os, true, "contains too many sequences to be displayed"); GTUtilsProject::openFile(os, testDir + "_common_data/fastq/lymph_min.fastq"); GTUtilsTaskTreeView::waitTaskFinished(os); } GUI_TEST_CLASS_DEFINITION(test_3687_2) { //1. Open file "_common_data/NGS_tutorials/RNA-Seq_Analysis/Prepare_Raw_Data/lymph.fastq". //Expected state: "Sequence Reading Options" dialog appeared. //2. Select "Join sequences into alignment" in the dialog. //3. Press "Ok". //Expected: the finishes with error about sequences amount. qputenv("UGENE_MAX_OBJECTS_PER_DOCUMENT", "100"); GTUtilsDialog::waitForDialog(os, new SequenceReadingModeSelectorDialogFiller(os, SequenceReadingModeSelectorDialogFiller::Join)); GTUtilsNotifications::waitForNotification(os, true, "contains too many sequences to be displayed"); GTUtilsProject::openFile(os, testDir + "_common_data/fastq/lymph_min.fastq"); GTUtilsTaskTreeView::waitTaskFinished(os); } GUI_TEST_CLASS_DEFINITION(test_3690) { // 1. Open human_T1.fa // Expected state: there are two opened windows - start page and human_T1 // 2. Use short cut - Ctrl+Tab // Expected state: current active MDI window is changed to start page // 3. Use short cut - Ctrl+Shift+Tab // Expected state: current active MDI window is changed back to human_T1 GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); QWidget *wgt = GTUtilsMdi::activeWindow(os); CHECK_SET_ERR(wgt != NULL, "ActiveWindow is NULL"); CHECK_SET_ERR(wgt->windowTitle() == "human_T1 [s] human_T1 (UCSC April 2002 chr7:115977709-117855134)", "human_T1.fa should be opened!"); GTKeyboardDriver::keyClick(Qt::Key_Tab, Qt::ControlModifier); GTGlobals::sleep(); wgt = GTUtilsMdi::activeWindow(os); CHECK_SET_ERR(wgt != NULL, "ActiveWindow is NULL"); CHECK_SET_ERR(wgt->windowTitle() == "Start Page", "Start Page should be opened!"); GTKeyboardDriver::keyPress(Qt::Key_Shift); GTKeyboardDriver::keyClick(Qt::Key_Tab, Qt::ControlModifier); GTKeyboardDriver::keyRelease(Qt::Key_Shift); GTGlobals::sleep(); wgt = GTUtilsMdi::activeWindow(os); CHECK_SET_ERR(wgt != NULL, "ActiveWindow is NULL"); CHECK_SET_ERR(wgt->windowTitle() == "human_T1 [s] human_T1 (UCSC April 2002 chr7:115977709-117855134)", "human_T1.fa should be opened!"); } GUI_TEST_CLASS_DEFINITION(test_3697) { // 1. Create a connection to some shared database // 2. Create the second connection with the same parameters except connection name // Current state: the second connection is not created, after acceptance of the 'Connection settings' dialog nothing had happened - no connection, no message. // Extected state: message is shown // Additional scenario: // 1. Open WD // 2. Add Read Sequence element and // 3. Deselect Read Sequence element (click on empty space) and select it again // Current state: Connection Duplicate Detected dialog appeared. // Expected state: no message GTLogTracer l; QString conName1 = "test_3697: ugene_gui_test I"; { QList<SharedConnectionsDialogFiller::Action> actions; actions << SharedConnectionsDialogFiller::Action(SharedConnectionsDialogFiller::Action::ADD); actions << SharedConnectionsDialogFiller::Action(SharedConnectionsDialogFiller::Action::CLOSE); GTUtilsDialog::waitForDialog(os, new SharedConnectionsDialogFiller(os, actions)); } EditConnectionDialogFiller::Parameters params1; params1.connectionName = conName1; params1.host = GTDatabaseConfig::host(); params1.port = QString::number(GTDatabaseConfig::port()); params1.database = GTDatabaseConfig::database(); params1.login = "login"; params1.password = "password"; GTUtilsDialog::waitForDialog(os, new EditConnectionDialogFiller(os, params1, EditConnectionDialogFiller::MANUAL)); GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Connect to UGENE shared database..."); GTGlobals::sleep(); QString conName2 = "test_3697: ugene_gui_test II"; { QList<SharedConnectionsDialogFiller::Action> actions; actions << SharedConnectionsDialogFiller::Action(SharedConnectionsDialogFiller::Action::ADD); actions << SharedConnectionsDialogFiller::Action(SharedConnectionsDialogFiller::Action::CLOSE); GTUtilsDialog::waitForDialog(os, new SharedConnectionsDialogFiller(os, actions)); } GTGlobals::sleep(); GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, "Ok")); EditConnectionDialogFiller::Parameters params2 = params1; params2.connectionName = conName2; GTUtilsDialog::waitForDialog(os, new EditConnectionDialogFiller(os, params2, EditConnectionDialogFiller::MANUAL)); GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Connect to UGENE shared database..."); GTUtilsDialog::waitForDialogWhichMustNotBeRun(os, new MessageBoxDialogFiller(os, "Ok")); GTUtilsWorkflowDesigner::openWorkflowDesigner(os); GTUtilsWorkflowDesigner::addElement(os, "Read Alignment"); GTUtilsWorkflowDesigner::addElement(os, "Read Sequence", true); GTUtilsWorkflowDesigner::click(os, "Read Alignment"); GTUtilsWorkflowDesigner::click(os, "Read Sequence"); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3702) { // 1. Open human_T1.fa // 2. Drag'n' drop it from the project to welcome screen // Expected state: sequence view is opened GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsSequenceView::checkSequenceViewWindowIsActive(os); GTUtilsMdi::closeWindow(os, "human_T1 [s] human_T1 (UCSC April 2002 chr7:115977709-117855134)"); GTUtilsSequenceView::checkNoSequenceViewWindowIsOpened(os); GTUtilsMdi::checkWindowIsActive(os, "Start Page"); QPoint centerOfWelcomePage = AppContext::getMainWindow()->getQMainWindow()->geometry().center(); GTMouseDriver::dragAndDrop(GTUtilsProjectTreeView::getItemCenter(os, "human_T1.fa"), centerOfWelcomePage); QWidget *window = GTUtilsSequenceView::getActiveSequenceViewWindow(os); CHECK_SET_ERR(window->windowTitle() == "human_T1 [s] human_T1 (UCSC April 2002 chr7:115977709-117855134)", "human_T1.fa should be opened!"); } GUI_TEST_CLASS_DEFINITION(test_3710) { // 1. Open "_common_data/scenarios/msa/ma2_gapped.aln". GTFileDialog::openFile(os, testDir + "_common_data/scenarios/msa/ma2_gapped.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Open the Highlighting option panel tab. GTUtilsOptionPanelMsa::openTab(os, GTUtilsOptionPanelMsa::Highlighting); // 3. Select "Phaneroptera_falcata" as the reference sequence. GTUtilsOptionPanelMsa::addReference(os, "Phaneroptera_falcata"); // 4. Click the Export button. GTUtilsNotifications::waitForNotification(os, false, "Report for task: 'Export highlighting'"); GTUtilsDialog::waitForDialog(os, new ExportHighlightedDialogFiller(os, sandBoxDir + "export_test_3710")); QComboBox *highlightingScheme = GTWidget::findExactWidget<QComboBox *>(os, "highlightingScheme"); GTComboBox::setIndexWithText(os, highlightingScheme, "Agreements"); GTWidget::click(os, GTWidget::findWidget(os, "exportHighlightning")); GTGlobals::sleep(); // 5. Export. CHECK_SET_ERR(GTFile::getSize(os, sandBoxDir + "export_test_3710") != 0, "Exported file is empty!"); } GUI_TEST_CLASS_DEFINITION(test_3715) { //1. Open WD. GTUtilsWorkflowDesigner::openWorkflowDesigner(os); //2. Activate samples. GTUtilsWorkflowDesigner::setCurrentTab(os, GTUtilsWorkflowDesigner::samples); //3. Choose a sample GTUtilsWorkflowDesigner::addSample(os, "call variants"); GTKeyboardDriver::keyClick(Qt::Key_Escape); GTUtilsWorkflowDesigner::click(os, "Read Assembly (BAM/SAM)"); GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::Ok)); GTKeyboardDriver::keyClick('r', Qt::ControlModifier); GTGlobals::sleep(); CHECK_SET_ERR(GTUtilsWorkflowDesigner::checkErrorList(os, "Read Assembly") != 0, "Workflow errors list cant be empty"); } GUI_TEST_CLASS_DEFINITION(test_3717) { // 1. Open "data/samples/CLUSTALW/COI.aln". GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Click the last sequence in the name list area. GTUtilsMSAEditorSequenceArea::click(os, QPoint(-5, 17)); // 3. Press Shift and click the second sequence in the name list area. GTKeyboardDriver::keyPress(Qt::Key_Shift); GTUtilsMSAEditorSequenceArea::click(os, QPoint(-5, 1)); // Expected: sequences [2; last] are selected, the selection frame in the name list is shown. GTUtilsMSAEditorSequenceArea::checkSelectedRect(os, QRect(QPoint(0, 1), QPoint(603, 17))); // 3. Press Shift and click the first sequence in the name list area. GTUtilsMSAEditorSequenceArea::click(os, QPoint(-5, 0)); // Expected: the selection frame in the name list area is still shown and bound all sequences. GTUtilsMSAEditorSequenceArea::checkSelectedRect(os, QRect(QPoint(0, 0), QPoint(603, 17))); GTKeyboardDriver::keyRelease(Qt::Key_Shift); } GUI_TEST_CLASS_DEFINITION(test_3723) { // 1. Open simultaneously two files: "_common_data/fasta/fa1.fa.gz" and "_common_data/fasta/fa3.fa.gz". // Expected state: "Multiple Sequence Reading Mode" dialog appears. // 2. Open them with "Merge" option. // Expected state: sequences are merged and opened, there are no errors in the log. GTLogTracer logTracer; GTSequenceReadingModeDialog::mode = GTSequenceReadingModeDialog::Merge; GTUtilsDialog::waitForDialog(os, new GTSequenceReadingModeDialogUtils(os)); GTFileDialog::openFileList(os, testDir + "_common_data/fasta", QStringList() << "fa1.fa.gz" << "fa3.fa.gz"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDocument::checkDocument(os, "merged_document.gb"); GTUtilsDocument::isDocumentLoaded(os, "merged_document.gb"); GTUtilsLog::check(os, logTracer); } GUI_TEST_CLASS_DEFINITION(test_3724) { // 1. Open "data/samples/CLUSTALW/COI.aln". GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Use sequence area context menu: // { Statistics -> Generate distance matrix } // Expected state: the "Generate Distance Matrix" dialog has appeared. // 3. Click "Generate". // Expected state: the "Multiple Sequence Alignment Distance Matrix" view has appeared. GTUtilsDialog::waitForDialog(os, new PopupChooserByText(os, QStringList() << "Statistics" << "Generate distance matrix...")); GTUtilsDialog::waitForDialog(os, new DistanceMatrixDialogFiller(os)); GTUtilsMSAEditorSequenceArea::callContextMenu(os); } GUI_TEST_CLASS_DEFINITION(test_3728) { // 1. Connect to UGENE public database. GTUtilsSharedDatabaseDocument::connectToUgenePublicDatabase(os); GTUtilsTaskTreeView::waitTaskFinished(os); // Expected state: objects appear in alphabetic order in folders QModelIndex parent = GTUtilsProjectTreeView::findIndex(os, GTUtilsProjectTreeView::getTreeView(os), "genomes"); QStringList strList; QString prev = ""; for (int i = 0; i < 5; i++) { QString s = parent.child(i, 0).data(Qt::DisplayRole).toString(); int res = QString::compare(prev, s); CHECK_SET_ERR(res < 0, "order is not alphabet " + prev + s); prev = s; } // Current state: object order is nearly random and is not the same in successive UGENE launches } GUI_TEST_CLASS_DEFINITION(test_3730) { // 1. Open "data/samples/CLUSTALW/COI.aln". GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW", "COI.aln"); GTUtilsMsaEditor::checkMsaEditorWindowIsActive(os); // 2. Create new custom nucleotide color scheme. GTUtilsMSAEditorSequenceArea::createColorScheme(os, "test_3730_scheme_1", NewColorSchemeCreator::nucl); // 3. Go to Highlighting Options Panel tab and select this new color scheme. GTUtilsOptionPanelMsa::setColorScheme(os, "test_3730_scheme_1"); // 4. Go to Preferences again and create new amino color scheme. // 5. Accept Application Settings dialog. // Expected state: UGENE doesn't crash, color scheme is not changed. GTUtilsMSAEditorSequenceArea::createColorScheme(os, "test_3730_scheme_2", NewColorSchemeCreator::amino); QString colorScheme = GTUtilsOptionPanelMsa::getColorScheme(os); CHECK_SET_ERR(colorScheme == "test_3730_scheme_1", "The color scheme was unexpectedly changed"); } GUI_TEST_CLASS_DEFINITION(test_3731) { //1. Open /data/sample/PDB/1CRN.pdb //Expected state: Sequence is opened //2. Do context menu "Analyze - Predict Secondary Structure" //Expected state: Predict Secondary Structure dialog is appeared //3. Set "Range Start" 20, "Range End": 46, set any prediction algorithm //4. Press "Start prediction" button //Expected state: you get annotation(s) in range 20..46 //Current state for GOR IV: you get annotations with ranges 11..15 and 24..25 GTFileDialog::openFile(os, dataDir + "samples/MMDB", "1CRN.prt"); GTUtilsTaskTreeView::waitTaskFinished(os); QPoint itemCenter = GTUtilsAnnotationsTreeView::getItemCenter(os, "1CRN chain 1 annotation [1CRN.prt]"); itemCenter.setX(itemCenter.x() + 10); GTMouseDriver::moveTo(itemCenter); GTMouseDriver::click(); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ADV_MENU_REMOVE << "Selected objects with annotations from view")); GTMouseDriver::click(Qt::RightButton); GTGlobals::sleep(); GTUtilsDialog::waitForDialog(os, new PredictSecondaryStructureDialogFiller(os, 20, 46)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ADV_MENU_ANALYSE << "Predict secondary structure")); GTWidget::click(os, GTWidget::findWidget(os, "ADV_single_sequence_widget_0"), Qt::RightButton); GTGlobals::sleep(); QList<U2Region> annotatedRegions = GTUtilsAnnotationsTreeView::getAnnotatedRegions(os); foreach (U2Region curRegion, annotatedRegions) { CHECK_SET_ERR(curRegion.startPos >= 20, "Incorrect annotated region"); } } GUI_TEST_CLASS_DEFINITION(test_3732) { // 1. Open UGENE preferences, open "Resources" tab, set UGENE memory limit to 200Mb. class MemoryLimitSetScenario : public CustomScenario { void run(HI::GUITestOpStatus &os) { QWidget *dialog = QApplication::activeModalWidget(); CHECK_SET_ERR(NULL != dialog, "Active modal widget is NULL"); AppSettingsDialogFiller::openTab(os, AppSettingsDialogFiller::Resourses); GTLineEdit::setText(os, GTWidget::findExactWidget<QLineEdit *>(os, "memBox", dialog), "200"); GTUtilsDialog::clickButtonBox(os, dialog, QDialogButtonBox::Ok); } }; GTUtilsDialog::waitForDialog(os, new AppSettingsDialogFiller(os, new MemoryLimitSetScenario)); // 2. Open file "_common_data/scenarios/_regression/1688/sr100.000.fa" as separate sequences. // Expected state: there is an error in the log: "MemoryLocker - Not enough memory error, 41 megabytes are required". GTLogTracer logTracer; GTUtilsProject::openMultiSequenceFileAsMalignment(os, testDir + "_common_data/scenarios/_regression/1688", "sr100.000.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); CHECK_SET_ERR(logTracer.checkMessage("MemoryLocker - Not enough memory error, 41 megabytes are required"), "An expected error message not found"); } GUI_TEST_CLASS_DEFINITION(test_3736) { GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsOptionPanelSequenceView::openTab(os, GTUtilsOptionPanelSequenceView::Search); GTUtilsOptionPanelSequenceView::setAlgorithm(os, "Regular expression"); GTUtilsOptionPanelSequenceView::enterPattern(os, "A{5,6}", true); CHECK_SET_ERR(GTUtilsOptionPanelSequenceView::checkResultsText(os, "Results: 1/3973"), "Results string not match"); } GUI_TEST_CLASS_DEFINITION(test_3738) { // Select {DNA Assembly -> Contig assembly with CAP3} GTLogTracer l; GTUtilsDialog::waitForDialog(os, new ImportACEFileFiller(os, false, sandBoxDir + "test_3738.ugenedb")); GTUtilsDialog::waitForDialog(os, new CAP3SupportDialogFiller(os, QStringList() << testDir + "_common_data/scf/Sequence A.scf" << testDir + "_common_data/scf/Sequence B.scf", sandBoxDir + "test_3738.ace")); GTMenu::clickMainMenuItem(os, QStringList() << "Tools" << "Sanger data analysis" << "Reads de novo assembly (with CAP3)..."); // menu item in the main menu. // Set sequences "_common_data/scf/Sequence A.scf" and "_common_data/scf/Sequence B.scf" as input, set any valid output path and run the task. // Expected state: user is asked to select the view. // Select "Open in Assembly Browser with ACE importer format" and import the assembly anywhere. // Expected state: the assembly is successfully imported. GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsLog::check(os, l); // Current state: the assembly is not imported, there is an error in the log: Task {CAP3 run and open result task} } GUI_TEST_CLASS_DEFINITION(test_3744) { // 1. Open "data/samples/FASTA/human_T1.fa" // 2. Open the Find Pattern options panel tab // 3. Set the "Regular expression" search algorithm // 4. Paste to the pattern field the following string: "ACT.G" // Expected state: some results have been found // 5. Select the pattern by mouse or pressing "Shift + Home" // 6. Delete the pattern by pressing a backspace // Expected state: "Previous" and "Next" buttons are disabled GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTWidget::click(os, GTWidget::findWidget(os, "OP_FIND_PATTERN")); GTGlobals::sleep(500); GTUtilsOptionPanelSequenceView::setAlgorithm(os, "Regular expression"); GTUtilsOptionPanelSequenceView::enterPattern(os, "ACG.T", true); GTGlobals::sleep(200); QWidget *createButton = GTWidget::findWidget(os, "getAnnotationsPushButton"); GTUtilsOptionPanelSequenceView::enterPattern(os, "", true); CHECK_SET_ERR(!createButton->isEnabled(), "prevPushButton is unexpectidly enabled") } GUI_TEST_CLASS_DEFINITION(test_3749) { // 1. Open "data/samples/CLUSTALW/COI.aln". GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW/", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Select any base. GTUtilsMSAEditorSequenceArea::moveTo(os, QPoint(10, 10)); GTMouseDriver::click(Qt::LeftButton); class Scenario : public CustomScenario { void run(HI::GUITestOpStatus &os) { //GTMouseDriver::moveTo(GTMouseDriver::getMousePosition() - QPoint(5, 0)); GTUtilsMSAEditorSequenceArea::moveTo(os, QPoint(1, 10)); GTMouseDriver::click(); QWidget *contextMenu = QApplication::activePopupWidget(); CHECK_SET_ERR(NULL == contextMenu, "There is an unexpected context menu"); } }; // 3. Move the mouse to another base and click the right button. // Expected state: a context menu appears, a single base from the previous step is selected. GTUtilsDialog::waitForDialog(os, new PopupChecker(os, new Scenario)); GTUtilsMSAEditorSequenceArea::moveTo(os, QPoint(10, 9)); GTMouseDriver::click(Qt::RightButton); // 4. Move the mouse to the any third base and click the left button. // Expected state: the context menu closes, the first selected base is the only selected base. // Current state: the context menu closes, there is a selection from the base from the second step to the base from the last step. GTMouseDriver::click(Qt::LeftButton); GTUtilsMSAEditorSequenceArea::checkSelectedRect(os, QRect(QPoint(1, 10), QPoint(1, 10))); } GUI_TEST_CLASS_DEFINITION(test_3753) { //1. Export any document from the public database //2. Rename an object from the exported document // Expected state: object renamed // Current state: UGENE hangs GTLogTracer lt; GTUtilsSharedDatabaseDocument::connectToTestDatabase(os); CHECK_OP(os, ); QTreeView *treeView = GTUtilsProjectTreeView::getTreeView(os); CHECK_SET_ERR(NULL != treeView, "Invalid project tree view"); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "et0001_sequence")); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ACTION_PROJECT__EXPORT_IMPORT_MENU_ACTION << ACTION_EXPORT_SEQUENCE)); GTUtilsDialog::waitForDialog(os, new ExportSelectedRegionFiller(os, testDir + "_common_data/scenarios/sandbox/", "et0001_export.fasta", false, "sequence_test_3753")); GTMouseDriver::click(Qt::RightButton); GTGlobals::sleep(3000); GTUtilsProjectTreeView::rename(os, "sequence_test_3753", "test3753_renamed"); } GUI_TEST_CLASS_DEFINITION(test_3755) { GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW", "HIV-1.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); QWidget *seqArea = GTWidget::findWidget(os, "msa_editor_sequence_area"); QColor before = GTWidget::getColor(os, seqArea, QPoint(2, 1)); // Open the "Highlighting" options panel tab. GTWidget::click(os, GTWidget::findWidget(os, "OP_MSA_HIGHLIGHTING")); // Select different highlighting schemes. QComboBox *highlightingScheme = qobject_cast<QComboBox *>(GTWidget::findWidget(os, "highlightingScheme")); GTComboBox::setIndexWithText(os, highlightingScheme, "Conservation level"); QWidget *w = GTWidget::findWidget(os, "thresholdSlider"); QSlider *slider = qobject_cast<QSlider *>(w); GTSlider::setValue(os, slider, 80); QColor after = GTWidget::getColor(os, seqArea, QPoint(2, 1)); //check color change CHECK_SET_ERR(before != after, "colors not changed"); } GUI_TEST_CLASS_DEFINITION(test_3757) { // Open some specific PDB file and ensure that UGENE doesn't crash GTLogTracer l; GTFileDialog::openFile(os, testDir + "_common_data/pdb/", "water.pdb"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsProjectTreeView::findIndex(os, "water.pdb", QModelIndex()); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3760) { GTLogTracer l; GTFileDialog::openFile(os, testDir + "_common_data/phylip/", "Three Kingdoms.phy"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsProjectTreeView::findIndex(os, "Three Kingdoms.phy", QModelIndex()); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3768) { //1. Open "data/samples/FASTA/human_T1.fa". //2. Click "Find ORFs" button on the main toolbar. //3. Uncheck "Must start with init codon" option and accept the dialog. //4. Call context menu, select {Edit sequence -> Remove subsequence...} //5. Fill the dialog: //Region to remove: 2..199950; //Annotation region resolving mode: Crop corresponding annotation //and accept the dialog. //Current state: UGENE crashes. GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); class OkClicker : public Filler { public: OkClicker(HI::GUITestOpStatus &_os) : Filler(_os, "ORFDialogBase") { } virtual void run() { QWidget *w = QApplication::activeWindow(); CHECK(NULL != w, ); QDialogButtonBox *buttonBox = w->findChild<QDialogButtonBox *>(QString::fromUtf8("buttonBox")); CHECK(NULL != buttonBox, ); QCheckBox *ckInit = GTWidget::findExactWidget<QCheckBox *>(os, "ckInit", w); CHECK(NULL != ckInit, ); GTCheckBox::setChecked(os, ckInit, false); QPushButton *button = buttonBox->button(QDialogButtonBox::Ok); CHECK(NULL != button, ); GTWidget::click(os, button); } }; GTUtilsDialog::waitForDialog(os, new OkClicker(os)); GTWidget::click(os, GTAction::button(os, "Find ORFs")); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDialog::waitForDialog(os, new PopupChooserByText(os, QStringList() << "Edit" << "Remove subsequence...")); GTUtilsDialog::waitForDialog(os, new RemovePartFromSequenceDialogFiller(os, "2..199950")); GTUtilsSequenceView::openPopupMenuOnSequenceViewArea(os); } GUI_TEST_CLASS_DEFINITION(test_3770) { // 1. Select {File -> Access remote database...} menu item in the main menu. // 2. Fill the dialog: // Resource ID: NW_003943623; // Database: NCBI GenBank (DNA sequence); // Force download the appropriate sequence: checked // and accept the dialog. // 3. Try to cancel the task. // Expected state: the task cancels within a half of a minute. // Current state: the task doesn't cancel. GTUtilsDialog::waitForDialog(os, new RemoteDBDialogFillerDeprecated(os, "NW_003943623", 0, true, true, false, sandBoxDir)); GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Access remote database...", GTGlobals::UseKey); GTUtilsTaskTreeView::cancelTask(os, "Download remote documents"); GTGlobals::sleep(); CHECK_SET_ERR(GTUtilsTaskTreeView::countTasks(os, "Download remote documents") == 0, "Task was not canceled"); } GUI_TEST_CLASS_DEFINITION(test_3772) { //1. Open "samples/FASTA/human_T1.fa". GTFileDialog::openFile(os, dataDir + "samples/FASTA/human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); //2. Ctrl + F. GTUtilsOptionPanelSequenceView::openTab(os, GTUtilsOptionPanelSequenceView::Search); //3. Type "X". GTUtilsOptionPanelSequenceView::enterPattern(os, "X"); //Expected: //a) The alphabets warning appears. //b) The pattern text area is red. QLabel *label = dynamic_cast<QLabel *>(GTWidget::findWidget(os, "lblErrorMessage")); CHECK_SET_ERR(label->isVisible(), "Warning is not shown 1"); CHECK_SET_ERR(label->text().contains("Warning"), "Warning is not shown 2"); //4. Remove the character. GTUtilsOptionPanelSequenceView::enterPattern(os, ""); //Expected: //a) The alphabets warning disappears. //b) The pattern text area is white. if (label->isVisible()) { CHECK_SET_ERR(!label->text().contains("Warning"), "Warning is shown"); } } GUI_TEST_CLASS_DEFINITION(test_3773) { /* An easier way to reproduce an error: * 1. Open HMM profile * 2. Remove it from the project * Expected state: Log not have errors */ GTLogTracer logTracer; GTUtilsDialog::waitForDialog(os, new DocumentFormatSelectorDialogFiller(os, "Plain text")); GTUtilsProject::openFile(os, dataDir + "samples/HMM/aligment15900.hmm"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(200); GTUtilsProjectTreeView::click(os, "aligment15900.hmm"); GTKeyboardDriver::keyClick(Qt::Key_Delete); GTGlobals::sleep(200); GTUtilsLog::check(os, logTracer); } GUI_TEST_CLASS_DEFINITION(test_3773_1) { class OkClicker : public Filler { public: OkClicker(HI::GUITestOpStatus &_os) : Filler(_os, "HmmerBuildDialog") { } virtual void run() { QWidget *dialog = QApplication::activeModalWidget(); CHECK(dialog, ); QLineEdit *outHmmfileEdit = qobject_cast<QLineEdit *>(GTWidget::findWidget(os, "outHmmfileEdit", dialog)); CHECK(outHmmfileEdit, ); GTLineEdit::setText(os, outHmmfileEdit, "37773_1_out.hmm"); //GTWidget::click(os, GTWidget::findWidget(os, "outHmmfileToolButton")); QWidget *w = QApplication::activeWindow(); CHECK(NULL != w, ); QDialogButtonBox *buttonBox = w->findChild<QDialogButtonBox *>(QString::fromUtf8("buttonBox")); CHECK(NULL != buttonBox, ); QPushButton *button = buttonBox->button(QDialogButtonBox::Ok); CHECK(NULL != button, ); GTWidget::click(os, button); } }; GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW/", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTLogTracer logTracer; //QMenu* menu = GTMenu::showContextMenu(os, GTWidget::findWidget(os, "msa_editor_sequence_area")); //GTMenu::clickMenuItemByName(os, menu, QStringList() << "Build HMMER3 profile"); GTUtilsDialog::waitForDialog(os, new PopupChooserByText(os, QStringList() << "Advanced" << "Build HMMER3 profile")); GTUtilsDialog::waitForDialog(os, new OkClicker(os)); GTUtilsMSAEditorSequenceArea::callContextMenu(os, QPoint(5, 5)); GTUtilsLog::check(os, logTracer); } GUI_TEST_CLASS_DEFINITION(test_3778) { //1. Open "data/samples/FASTA/human_T1.fa". GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsSequenceView::checkSequenceViewWindowIsActive(os); //2. Open Circular View. QWidget *button = GTWidget::findWidget(os, "globalToggleViewAction_widget"); GTWidget::click(os, button); //3. Context menu -> Export -> Save circular view as image. //Expected state: the "Export Image" dialog appears. //4. Press "Export". //Expected state: the message about file name appears, the dialog is not closed (the export task does not start). class Scenario : public CustomScenario { public: void run(HI::GUITestOpStatus &os) { QWidget *dialog = QApplication::activeModalWidget(); CHECK_SET_ERR(NULL != dialog, "dialog is NULL"); QLineEdit *fileNameEdit = GTWidget::findExactWidget<QLineEdit *>(os, "fileNameEdit", dialog); GTLineEdit::setText(os, fileNameEdit, sandBoxDir + "circular_human_T1 (UCSC April 2002 chr7:115977709-117855134).png"); GTUtilsDialog::clickButtonBox(os, dialog, QDialogButtonBox::Ok); } }; GTUtilsDialog::waitForDialog(os, new CircularViewExportImage(os, new Scenario())); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ADV_MENU_EXPORT << "Save circular view as image", GTGlobals::UseMouse)); GTUtilsSequenceView::openPopupMenuOnSequenceViewArea(os); GTUtilsTaskTreeView::waitTaskFinished(os); GTFile::check(os, sandBoxDir + "circular_human_T1 (UCSC April 2002 chr7:115977709-117855134).png"); } GUI_TEST_CLASS_DEFINITION(test_3779) { GTUtilsDialog::waitForDialog(os, new ImportACEFileFiller(os, false, sandBoxDir + "regression_test_3779.ugenedb")); GTUtilsProject::openFile(os, testDir + "_common_data/ace/ace_test_4.ace"); GTUtilsTaskTreeView::waitTaskFinished(os); bool assemblyOverviewFound = !AppContext::getMainWindow()->getQMainWindow()->findChildren<CoveredRegionsLabel *>().isEmpty(); CHECK_SET_ERR(assemblyOverviewFound, "Assembly overview not found"); GTUtilsAssemblyBrowser::zoomToMax(os); GTUtilsAssemblyBrowser::zoomToMin(os); assemblyOverviewFound = !AppContext::getMainWindow()->getQMainWindow()->findChildren<CoveredRegionsLabel *>().isEmpty(); CHECK_SET_ERR(assemblyOverviewFound, "Assembly overview not found"); } GUI_TEST_CLASS_DEFINITION(test_3785_1) { //1. Open "_common_data/clustal/fungal - all.aln". GTFileDialog::openFile(os, testDir + "_common_data/clustal/fungal - all.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(3000); //2. Align with ClustalW. GTUtilsDialog::waitForDialog(os, new ClustalWDialogFiller(os)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << MSAE_MENU_ALIGN << "Align with ClustalW")); GTWidget::click(os, GTUtilsMSAEditorSequenceArea::getSequenceArea(os), Qt::RightButton); GTGlobals::sleep(1000); //Expected: task started. CHECK_SET_ERR(1 == GTUtilsTaskTreeView::getTopLevelTasksCount(os), "Task did not started"); //3. Close the alignment view. GTUtilsMdi::closeWindow(os, GTUtilsMdi::activeWindow(os)->objectName()); //Expected: task is still running. CHECK_SET_ERR(1 == GTUtilsTaskTreeView::getTopLevelTasksCount(os), "Task is cancelled"); //4. Delete the document from the project. GTUtilsProjectTreeView::click(os, "fungal - all.aln"); GTKeyboardDriver::keyClick(Qt::Key_Delete); GTGlobals::sleep(3000); //Expected: task is cancelled. CHECK_SET_ERR(0 == GTUtilsTaskTreeView::getTopLevelTasksCount(os), "Task is not cancelled"); } GUI_TEST_CLASS_DEFINITION(test_3785_2) { //1. Open "_common_data/clustal/fungal - all.aln". GTFileDialog::openFile(os, testDir + "_common_data/clustal/fungal - all.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(3000); //2. Align with ClustalW. GTUtilsDialog::waitForDialog(os, new ClustalWDialogFiller(os)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << MSAE_MENU_ALIGN << "Align with ClustalW")); GTWidget::click(os, GTUtilsMSAEditorSequenceArea::getSequenceArea(os), Qt::RightButton); GTGlobals::sleep(1000); //Expected: task started. CHECK_SET_ERR(1 == GTUtilsTaskTreeView::getTopLevelTasksCount(os), "Task did not started"); //3. Close the alignment view. GTUtilsMdi::closeWindow(os, GTUtilsMdi::activeWindow(os)->objectName()); //Expected: task is still running. CHECK_SET_ERR(1 == GTUtilsTaskTreeView::getTopLevelTasksCount(os), "Task is cancelled"); //4. Delete the object from the document. GTUtilsProjectTreeView::click(os, "fungal - all"); GTKeyboardDriver::keyClick(Qt::Key_Delete); GTGlobals::sleep(3000); //Expected: task is cancelled. CHECK_SET_ERR(0 == GTUtilsTaskTreeView::getTopLevelTasksCount(os), "Task is not cancelled"); } GUI_TEST_CLASS_DEFINITION(test_3788) { GTLogTracer logTracer; // 1. Open "data/samples/FASTA/human_T1.fa". GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Create an annotation on region 199950..199950. GTUtilsAnnotationsTreeView::createAnnotation(os, "<auto>", "misc_feature", "199950..199950"); // 3. Call context menu, select {Edit sequence -> Remove subsequence...} menu item. // 4. Remove region 2..199950, corresponding annotations should be cropped. // Expected result: sequence has length 1, there are no annotations. GTUtilsDialog::waitForDialog(os, new PopupChooserByText(os, QStringList() << "Edit" << "Remove subsequence...")); GTUtilsDialog::waitForDialog(os, new RemovePartFromSequenceDialogFiller(os, "2..199950")); GTUtilsSequenceView::openPopupMenuOnSequenceViewArea(os); GTUtilsTaskTreeView::waitTaskFinished(os); const QList<U2Region> annotatedRegions = GTUtilsAnnotationsTreeView::getAnnotatedRegions(os); CHECK_SET_ERR(0 == annotatedRegions.size(), "There are annotations unexpectedly"); GTUtilsLog::check(os, logTracer); } GUI_TEST_CLASS_DEFINITION(test_3797) { // Open "data/samples/CLUSTALW/COI.aln". // Toggle the collapsing mode. // Select some sequence in the name area. // Click the "end" or "page down" key. GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW/", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTWidget::click(os, GTToolbar::getWidgetForActionName(os, GTToolbar::getToolbar(os, "mwtoolbar_activemdi"), "Enable collapsing")); GTUtilsMSAEditorSequenceArea::selectSequence(os, QString("Mecopoda_sp.__Malaysia_")); GTKeyboardDriver::keyClick(Qt::Key_PageDown); GTGlobals::sleep(5000); } GUI_TEST_CLASS_DEFINITION(test_3805) { // 1. Open "data/samples/FASTA/human_T1.fa". GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Save the initial content GTUtilsDialog::waitForDialog(os, new SelectSequenceRegionDialogFiller(os, 51, 102)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Select" << "Sequence region")); GTMenu::showContextMenu(os, GTUtilsMdi::activeWindow(os)); GTKeyboardDriver::keyClick('c', Qt::ControlModifier); GTGlobals::sleep(500); const QString initialContent = GTClipboard::text(os); //3. Reverse sequence GTMenu::clickMainMenuItem(os, QStringList() << "Actions" << "Edit" << "Replace the whole sequence by" << "Reverse (3'-5') sequence", GTGlobals::UseKey); //4. Complement sequence GTMenu::clickMainMenuItem(os, QStringList() << "Actions" << "Edit" << "Replace the whole sequence by" << "Complementary (3'-5') sequence", GTGlobals::UseKey); //5. Reverse complement sequence GTMenu::clickMainMenuItem(os, QStringList() << "Actions" << "Edit" << "Replace the whole sequence by" << "Complementary (5'-3') sequence", GTGlobals::UseKey); GTUtilsDialog::waitForDialog(os, new SelectSequenceRegionDialogFiller(os, 51, 102)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Select" << "Sequence region")); GTMenu::showContextMenu(os, GTUtilsMdi::activeWindow(os)); GTGlobals::sleep(500); GTKeyboardDriver::keyClick('c', Qt::ControlModifier); GTGlobals::sleep(400); const QString newContent = GTClipboard::text(os); CHECK_SET_ERR(initialContent == newContent, "Result of actions is incorrect. Expected: " + initialContent + ", found: " + newContent); } GUI_TEST_CLASS_DEFINITION(test_3809) { GTFileDialog::openFile(os, testDir + "_common_data/regression/3809/zF849G6-6a01.p1k.scf.ab1"); GTUtilsTaskTreeView::waitTaskFinished(os); } GUI_TEST_CLASS_DEFINITION(test_3813) { //1. Open "samples/Genbank/murine.gb" GTFileDialog::openFile(os, dataDir + "/samples/Genbank/murine.gb"); GTUtilsSequenceView::checkSequenceViewWindowIsActive(os); //2. Press "Find restriction sites" toolbutton class Scenario : public CustomScenario { public: void run(HI::GUITestOpStatus &os) { //3. Press "Select by length" //4. Input "7" and press "Ok" GTUtilsDialog::waitForDialog(os, new InputIntFiller(os, 6)); GTWidget::click(os, GTWidget::findWidget(os, "selectByLengthButton")); //5. Run search GTUtilsDialog::clickButtonBox(os, QApplication::activeModalWidget(), QDialogButtonBox::Ok); } }; GTUtilsDialog::waitForDialog(os, new FindEnzymesDialogFiller(os, QStringList(), new Scenario())); GTWidget::click(os, GTWidget::findWidget(os, "Find restriction sites_widget")); GTUtilsTaskTreeView::waitTaskFinished(os); //6. Press toolbutton "Global automatic annotation updating" //7. Select all types of annotating QWidget *toolbarExtButton = GTWidget::findWidget(os, "qt_toolbar_ext_button", GTWidget::findWidget(os, "mwtoolbar_activemdi"), GTGlobals::FindOptions(false)); if (toolbarExtButton != NULL && toolbarExtButton->isVisible()) { GTWidget::click(os, toolbarExtButton); } GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "ORFs")); GTWidget::click(os, GTWidget::findWidget(os, "toggleAutoAnnotationsButton")); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Plasmid features")); GTWidget::click(os, GTWidget::findWidget(os, "toggleAutoAnnotationsButton")); GTUtilsTaskTreeView::waitTaskFinished(os); //8. Unload "murine.gb" GTUtilsDocument::unloadDocument(os, "murine.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsSequenceView::checkNoSequenceViewWindowIsOpened(os); //9. Load "murine.gb" //Expected state: auto-annotating task started GTUtilsDocument::loadDocument(os, "murine.gb"); GTUtilsSequenceView::checkSequenceViewWindowIsActive(os); //10. Unload the document, while the auto-annotating task is performing GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::Ok, "Failed to unload document", "UnloadWarning")); GTUtilsDocument::unloadDocument(os, "murine.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); } GUI_TEST_CLASS_DEFINITION(test_3815) { GTLogTracer l; //1. Open "_common_data/fasta/cant_translate.fa". GTFileDialog::openFile(os, testDir + "_common_data/fasta", "cant_translate.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); //2. Context menu of the document -> Export/Import -> Export sequences. //Expected state: the "Export Selected Sequences" dialog appears. //3. Check "Translate to amino alphabet" and press "Export". GTUtilsDialog::waitForDialog(os, new ExportSelectedRegionFiller(os, testDir + "_common_data/scenarios/sandbox/", "test_3815.fa", true)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ACTION_PROJECT__EXPORT_IMPORT_MENU_ACTION << ACTION_EXPORT_SEQUENCE)); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "cant_translate.fa")); GTMouseDriver::click(Qt::RightButton); GTUtilsTaskTreeView::waitTaskFinished(os); //Expected state: task has finished with error, no output file has been produced. CHECK_SET_ERR(l.checkMessage("No sequences have been produced"), "No error"); } GUI_TEST_CLASS_DEFINITION(test_3816) { // Open some specific file with a tree and ensure that UGENE doesn't crash GTLogTracer l; GTFileDialog::openFile(os, testDir + "_common_data/newick/", "arb-silva.nwk"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsProjectTreeView::findIndex(os, "arb-silva.nwk", QModelIndex()); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3817) { GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTKeyboardDriver::keyClick('f', Qt::ControlModifier); GTGlobals::sleep(1000); GTKeyboardDriver::keySequence("ACTGCT"); GTUtilsOptionPanelSequenceView::openSearchInShowHideWidget(os); QComboBox *boxRegion = qobject_cast<QComboBox *>(GTWidget::findWidget(os, "boxRegion")); GTComboBox::setIndexWithText(os, boxRegion, "Custom region"); QLineEdit *editStart = qobject_cast<QLineEdit *>(GTWidget::findWidget(os, "editStart")); QLineEdit *editEnd = qobject_cast<QLineEdit *>(GTWidget::findWidget(os, "editEnd")); GTLineEdit::setText(os, editStart, "123"); GTLineEdit::setText(os, editEnd, "1000"); GTComboBox::setIndexWithText(os, boxRegion, "Whole sequence"); CHECK_SET_ERR(!editStart->isVisible() && !editEnd->isVisible(), "Region boundary fields are unexpectedly visible"); GTComboBox::setIndexWithText(os, boxRegion, "Custom region"); CHECK_SET_ERR(editStart->isVisible() && editEnd->isVisible(), "Region boundary fields are unexpectedly invisible"); GTComboBox::setIndexWithText(os, boxRegion, "Selected region", false); CHECK_SET_ERR(boxRegion->currentText() == "Custom region", QString("Region type value is unexpected: %1. Expected: Custom region").arg(boxRegion->currentText())); } GUI_TEST_CLASS_DEFINITION(test_3821) { // 1. Open any genbank file with a COMMENT section GTFileDialog::openFile(os, dataDir + "samples/Genbank", "murine.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDialog::waitForDialog(os, new SelectSequenceRegionDialogFiller(os, 1, 2)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Select" << "Sequence region")); GTWidget::click(os, GTUtilsSequenceView::getSeqWidgetByNumber(os)->getDetView(), Qt::RightButton); GTGlobals::sleep(1000); Primer3DialogFiller::Primer3Settings settings; settings.shortRegion = true; GTUtilsDialog::waitForDialog(os, new Primer3DialogFiller(os, settings)); GTWidget::click(os, GTWidget::findWidget(os, "primer3_action_widget")); GTUtilsTaskTreeView::waitTaskFinished(os); } GUI_TEST_CLASS_DEFINITION(test_3829) { // Open "data/samples/FASTA/human_T1.fa". GTFileDialog::openFile(os, dataDir + "samples/FASTA/human_T1.fa"); GTUtilsSequenceView::checkSequenceViewWindowIsActive(os); // Open "data/samples/GFF/5prime_utr_intron_A20.gff". GTFileDialog::openFile(os, dataDir + "samples/GFF/5prime_utr_intron_A20.gff"); GTUtilsTaskTreeView::waitTaskFinished(os); // Attach the first annotation object to the sequence. QModelIndex index = GTUtilsProjectTreeView::findIndex(os, "Ca20Chr1 features"); // Expected state: UGENE warning about annotation is out of range. class scenario : public CustomScenario { void run(HI::GUITestOpStatus &os) { QWidget *dialog = GTWidget::getActiveModalWidget(os); QDialogButtonBox *buttonBox = qobject_cast<QDialogButtonBox *>(GTWidget::findWidget(os, "buttonBox", dialog)); CHECK_SET_ERR(buttonBox != NULL, "buttonBox is NULL"); QAbstractButton *okButton = buttonBox->button(QDialogButtonBox::Ok); CHECK_SET_ERR(okButton != NULL, "okButton is NULL"); // Agree with warning. GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::Yes)); GTWidget::click(os, okButton); } }; GTUtilsDialog::waitForDialog(os, new CreateObjectRelationDialogFiller(os, new scenario())); GTUtilsProjectTreeView::dragAndDrop(os, index, GTUtilsSequenceView::getPanOrDetView(os)); GTUtilsTaskTreeView::waitTaskFinished(os); // Expected state: there is a sequence with attached annotation table object, there is an annotation that is located beyond the sequence. GTMouseDriver::moveTo(GTUtilsAnnotationsTreeView::getItemCenter(os, "5_prime_UTR_intron")); GTMouseDriver::click(); // Select the annotation in the tree view. Open "Statistics" options panel tab or try to find something in the selected region. GTWidget::click(os, GTWidget::findWidget(os, "OP_SEQ_INFO")); GTUtilsOptionPanelSequenceView::checkTabIsOpened(os, GTUtilsOptionPanelSequenceView::Statistics); // Expected state: you can't set region that is not inside the sequence. // Current state: an incorrect selected region is set, crashes and safe points are possible with the region. } GUI_TEST_CLASS_DEFINITION(test_3819) { // 1. Connect to a shared database, that contains an assembly. // 2. Open the assembly. // Expected state: an Assembly Browser opens, there are some reads in the reads area after zooming. GTLogTracer logTracer; const QString folderName = "view_test_0003"; const QString folderPath = U2ObjectDbi::PATH_SEP + folderName; const QString assemblyVisibleName = "chrM"; const QString assemblyVisibleNameWidget = " [as] chrM"; const QString databaseAssemblyObjectPath = folderPath + U2ObjectDbi::PATH_SEP + assemblyVisibleName; Document *databaseDoc = GTUtilsSharedDatabaseDocument::connectToTestDatabase(os); QModelIndexList list = GTUtilsProjectTreeView::findIndeciesInProjectViewNoWait(os, assemblyVisibleName, GTUtilsProjectTreeView::findIndex(os, folderName)); foreach (QModelIndex index, list) { if (index.data() == "[as] chrM") { GTUtilsSharedDatabaseDocument::openView(os, databaseDoc, index); } } GTGlobals::sleep(5000); QWidget *assemblyView = GTWidget::findWidget(os, assemblyVisibleNameWidget); CHECK_SET_ERR(NULL != assemblyView, "View wasn't opened"); GTUtilsAssemblyBrowser::zoomToMax(os); GTUtilsAssemblyBrowser::goToPosition(os, 1); GTGlobals::sleep(); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "copy_read_information", GTGlobals::UseMouse)); GTMenu::showContextMenu(os, GTWidget::findWidget(os, "assembly_reads_area")); GTUtilsSharedDatabaseDocument::disconnectDatabase(os, databaseDoc); GTUtilsLog::check(os, logTracer); } GUI_TEST_CLASS_DEFINITION(test_3843) { // 1. Open file "_common_data/scenarios/msa/ma.aln". GTFileDialog::openFile(os, testDir + "_common_data/scenarios/msa/", "ma.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Turn the collapsing mode on. GTWidget::click(os, GTToolbar::getWidgetForActionName(os, GTToolbar::getToolbar(os, "mwtoolbar_activemdi"), "Enable collapsing")); // 3. Expand one of the collapsed sequences. GTUtilsMSAEditorSequenceArea::clickCollapseTriangle(os, "Conocephalus_discolor"); // 4. Select some region within a sequence from the chosen collapsed group. // 5. Click "Ctrl+C" // Expected state : clipboard contains a selected string GTUtilsMSAEditorSequenceArea::checkSelection(os, QPoint(4, 11), QPoint(10, 11), "CTTATTA"); } GUI_TEST_CLASS_DEFINITION(test_3850) { GTLogTracer l; //1. Open "data/samples/FASTA/human_T1.fa". GTFileDialog::openFile(os, dataDir + "samples/FASTA/human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); //2. Open "Search in Sequence" options panel tab. GTUtilsOptionPanelSequenceView::openTab(os, GTUtilsOptionPanelSequenceView::Search); //5. Check "Use pattern name" checkbox. GTUtilsOptionPanelSequenceView::openAnnotationParametersShowHideWidget(os, true); GTCheckBox::setChecked(os, GTWidget::findExactWidget<QCheckBox *>(os, "chbUsePatternNames"), true); //3. Check "Load patterns from file" checkbox. GTUtilsOptionPanelSequenceView::toggleInputFromFilePattern(os); //4. Set "_common_data/fasta/shuffled.fa" as input file. GTUtilsOptionPanelSequenceView::enterPatternFromFile(os, testDir + "_common_data/fasta", "shuffled.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); //Expected state: there are 1802 results found. CHECK_SET_ERR(GTUtilsOptionPanelSequenceView::checkResultsText(os, "Results: 1/1802"), "Results string not match"); //6. Click "Create annotations" button. GTUtilsOptionPanelSequenceView::clickGetAnnotation(os); GTUtilsTaskTreeView::waitTaskFinished(os); //Expected state: 1802 annotations are created, each has the same name as the pattern has. GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3862) { //1. Open any sequence GTFileDialog::openFile(os, dataDir + "samples/Genbank/CVU55762.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); //2. Switch on auto-annotations GTLogTracer l; GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Restriction Sites")); GTWidget::click(os, GTWidget::findWidget(os, "toggleAutoAnnotationsButton")); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Restriction Sites")); GTWidget::click(os, GTWidget::findWidget(os, "toggleAutoAnnotationsButton")); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3868) { //1. Open "VectorNTI_CAN_READ.gb" GTFileDialog::openFile(os, testDir + "_common_data/genbank/", "VectorNTI_CAN_READ.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsTaskTreeView::waitTaskFinished(os); //2. Open the "Annotation highlighting" OP widget. GTWidget::click(os, GTWidget::findWidget(os, "OP_ANNOT_HIGHLIGHT")); //Expected state: labels from genbank features are shown in annotations widgets GTMouseDriver::moveTo(GTUtilsAnnotHighlightingTreeView::getItemCenter(os, "rep_origin")); GTMouseDriver::click(); GTGlobals::sleep(); QLineEdit *qualifiersEdit = qobject_cast<QLineEdit *>(GTWidget::findWidget(os, "editQualifiers")); CHECK_SET_ERR(qualifiersEdit->text().contains("label"), "Label must be shown in annotation widget"); } GUI_TEST_CLASS_DEFINITION(test_3869) { //check comments for vector-nti format GTFileDialog::openFile(os, testDir + "_common_data/vector_nti_sequence/unrefined.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsAnnotationsTreeView::selectItems(os, QStringList() << "comment"); QString name = GTUtilsAnnotationsTreeView::getQualifierValue(os, "Author name", "comment"); CHECK_SET_ERR(name == "Demo User", "unexpected qualifier value: " + name) } GUI_TEST_CLASS_DEFINITION(test_3870) { //1. Open file "data/samples/CLUSTALW/COI.aln" GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW/", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsTaskTreeView::waitTaskFinished(os); int length = GTUtilsMSAEditorSequenceArea::getLength(os); //2. Insert gaps int columnsNumber = GTUtilsMSAEditorSequenceArea::getNumVisibleBases(os); GTUtilsMSAEditorSequenceArea::selectArea(os, QPoint(columnsNumber - 10, 0), QPoint(columnsNumber, 10), GTGlobals::UseMouse); GTGlobals::sleep(1000); GTKeyboardDriver::keyClick(Qt::Key_Space); //3. Export sequences with terminal gaps to FASTA //Expected state: terminal gaps are not cut off length = GTUtilsMSAEditorSequenceArea::getLength(os); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << MSAE_MENU_EXPORT << "Save subalignment")); GTUtilsDialog::waitForDialog(os, new ExtractSelectedAsMSADialogFiller(os, testDir + "_common_data/scenarios/sandbox/3870.fa", GTUtilsMSAEditorSequenceArea::getNameList(os), length - 60, length - 1, true, false, false, false, true, "FASTA")); GTMenu::showContextMenu(os, GTWidget::findWidget(os, "msa_editor_sequence_area")); // QFile resFile(testDir + "_common_data/scenarios/sandbox/3870.fa"); // QFile templateFile(testDir + "_common_data/scenarios/_regression/3870/3870.fa"); // CHECK_SET_ERR(resFile.size() == templateFile.size(), "Result file is incorrect"); } GUI_TEST_CLASS_DEFINITION(test_3886) { //1. Open WD. GTUtilsWorkflowDesigner::openWorkflowDesigner(os); //2. Open 'Extract consensus as sequence' sample. GTUtilsWorkflowDesigner::addSample(os, "Extract consensus as sequence"); GTUtilsTaskTreeView::waitTaskFinished(os); //3. Show wizard. class TestWizardFiller : public Filler { public: TestWizardFiller(HI::GUITestOpStatus &os) : Filler(os, "Extract Alignment Consensus as Sequence") { } void run() { //4. Click Next. //Expected: UGENE does not crash. GTWidget::click(os, GTWidget::findWidget(os, "__qt__passive_wizardbutton1")); GTGlobals::sleep(); GTUtilsWizard::clickButton(os, GTUtilsWizard::Cancel); } }; GTUtilsDialog::waitForDialog(os, new TestWizardFiller(os)); GTWidget::click(os, GTAction::button(os, "Show wizard")); GTGlobals::sleep(); } GUI_TEST_CLASS_DEFINITION(test_3895) { //1. Open '_common_data/genbank/pBR322.gb' (file contains circular marker) GTGlobals::sleep(); GTFileDialog::openFile(os, testDir + "_common_data/genbank", "pBR322.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsTaskTreeView::waitTaskFinished(os); //2. Export document to genbank format //Current state: there are two circular markers in the first line GTUtilsDialog::waitForDialog(os, new ExportDocumentDialogFiller(os, sandBoxDir, "test_3895.gb", ExportDocumentDialogFiller::Genbank, false, false)); GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << "Export document")); GTMouseDriver::moveTo(GTUtilsProjectTreeView::getItemCenter(os, "pBR322.gb")); GTMouseDriver::click(Qt::RightButton); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(); QFile exportedDoc(sandBoxDir + "test_3895.gb"); bool isOpened = exportedDoc.open(QFile::ReadOnly); CHECK_SET_ERR(isOpened, QString("Can not open file: \"%1\"").arg(exportedDoc.fileName())); QTextStream fileReader(&exportedDoc); QString firstLine = fileReader.readLine(); int firstIndex = firstLine.indexOf("circular", Qt::CaseInsensitive); int lastIndex = firstLine.indexOf("circular", firstIndex + 1, Qt::CaseInsensitive); CHECK_SET_ERR(lastIndex < 0, "There are several circular markers"); } GUI_TEST_CLASS_DEFINITION(test_3901) { //1. Open "_common_data/fasta/human_T1_cutted.fa". GTFileDialog::openFile(os, testDir + "_common_data/fasta/human_T1_cutted.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); //2. Toggle circular view. GTWidget::click(os, GTWidget::findWidget(os, "CircularViewAction")); QAction *wrapMode = GTAction::findActionByText(os, "Wrap sequence"); CHECK_SET_ERR(wrapMode != NULL, "Cannot find Wrap sequence action"); GTWidget::click(os, GTAction::button(os, wrapMode)); //3. Create an annotation with region: join(50..60,20..30,80..90). GTUtilsDialog::waitForDialog(os, new CreateAnnotationWidgetFiller(os, true, "group", "feature", "join(50..60,20..30,80..90)")); GTMenu::clickMainMenuItem(os, QStringList() << "Actions" << "Add" << "New annotation..."); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(); //4. Click to the arrow (80..90). GTUtilsSequenceView::clickAnnotationDet(os, "feature", 80, 0, true); GTGlobals::sleep(200); //Expected state: the arrow's region is selected. ADVSingleSequenceWidget *w = (ADVSingleSequenceWidget *)GTWidget::findWidget(os, "ADV_single_sequence_widget_0"); QVector<U2Region> selection = w->getSequenceSelection()->getSelectedRegions(); CHECK_SET_ERR(selection.size() == 1, "No selected region"); CHECK_SET_ERR(selection.first() == U2Region(79, 11), "Wrong selected region"); } GUI_TEST_CLASS_DEFINITION(test_3902) { // Open "data/samples/Genbank/murine.gb" and // "data/samples/Genbank/sars.gb" as separate sequences (in different views). // Select these two documents in the project view and unload them. Agree to close views. // Expected state: both documents are unloaded, there are no errors in the log. GTLogTracer l; GTFileDialog::openFile(os, dataDir + "samples/Genbank/", "murine.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(500); GTFileDialog::openFile(os, dataDir + "samples/Genbank/", "sars.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(500); GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::Yes)); GTUtilsDocument::unloadDocument(os, "murine.gb", false); GTGlobals::sleep(500); GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::Yes)); GTUtilsDocument::unloadDocument(os, "sars.gb", false); GTGlobals::sleep(500); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3903) { /* 1. Open any sequence 2. Open and close Find Pattern tab 3. Remove sub-sequence 4. Press Ctrl+F 5. Input e.g. 'A' Expected state: Log shouldn't contain errors Current state: SAFE_POINT is triggered or Current state: the warning appeared "there is no pattern to search" (The problem is in 'Region to search' parameter) */ GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // Click "Hide zoom view" QWidget *toolbar = GTWidget::findWidget(os, "views_tool_bar_human_T1 (UCSC April 2002 chr7:115977709-117855134)"); CHECK_SET_ERR(toolbar != nullptr, "Cannot find views_tool_bar_human_T1(UCSC April 2002 chr7:115977709-117855134)"); GTWidget::click(os, GTWidget::findWidget(os, "show_hide_zoom_view", toolbar)); GTGlobals::sleep(500); GTWidget::click(os, GTWidget::findWidget(os, "OP_FIND_PATTERN")); GTGlobals::sleep(500); GTWidget::click(os, GTWidget::findWidget(os, "OP_FIND_PATTERN")); GTGlobals::sleep(500); GTUtilsDialog::waitForDialog(os, new PopupChooserByText(os, QStringList() << "Edit" << "Remove subsequence...")); GTUtilsDialog::waitForDialog(os, new RemovePartFromSequenceDialogFiller(os, "100..199950")); GTUtilsSequenceView::openPopupMenuOnSequenceViewArea(os); GTUtilsTaskTreeView::waitTaskFinished(os); GTLogTracer lt; GTKeyboardDriver::keyClick('f', Qt::ControlModifier); GTGlobals::sleep(200); GTKeyboardDriver::keySequence("A"); GTGlobals::sleep(1000); CHECK_SET_ERR(!lt.hasErrors(), "Errors in log: " + lt.getJoinedErrorString()); } GUI_TEST_CLASS_DEFINITION(test_3904) { //1. Open file "data/samples/CLUSTALW/COI.aln" GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW/", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(5000); GTUtilsMSAEditorSequenceArea::click(os, QPoint(0, 0)); GTKeyboardDriver::keyClick(Qt::Key_Space); GTUtilsMSAEditorSequenceArea::selectSequence(os, "Phaneroptera_falcata"); GTLogTracer lt; GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << MSAE_MENU_EDIT << "remove_columns_of_gaps")); GTUtilsDialog::waitForDialog(os, new RemoveGapColsDialogFiller(os, RemoveGapColsDialogFiller::Percent, 10)); GTMenu::showContextMenu(os, GTUtilsMSAEditorSequenceArea::getSequenceArea(os)); GTGlobals::sleep(); CHECK_SET_ERR(!lt.hasErrors(), "Errors in log: " + lt.getJoinedErrorString()); } GUI_TEST_CLASS_DEFINITION(test_3905) { // 1. Open "data/samples/CLUSTALW/COI.aln". GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Remove the first sequence. GTUtilsMSAEditorSequenceArea::removeSequence(os, "Phaneroptera_falcata"); // 3. Undo removing. GTUtilsMsaEditor::undo(os); // 4. Set the first sequence as reference. GTUtilsMsaEditor::setReference(os, "Phaneroptera_falcata"); // 5. Redo removing. // Expected state: the reference sequence is unset. GTUtilsMsaEditor::redo(os); const QString &referenceName = GTUtilsMsaEditor::getReferenceSequenceName(os); CHECK_SET_ERR(referenceName.isEmpty(), "A reference sequence was not reset"); } GUI_TEST_CLASS_DEFINITION(test_3920) { // 1. Open "data/samples/FASTA/human_T1.fa". // 2. Click "find ORFs" button on the toolbar. // Set custom region that differs from the whole sequence region and accept the dialog. // Expected state: ORFs are found in the set region. // Current state: ORFs on the whole sequence are found. GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); class ORFDialogFiller : public Filler { public: ORFDialogFiller(HI::GUITestOpStatus &_os) : Filler(_os, "ORFDialogBase") { } virtual void run() { QWidget *w = QApplication::activeWindow(); CHECK(NULL != w, ); QLineEdit *start = w->findChild<QLineEdit *>("start_edit_line"); CHECK_SET_ERR(start != NULL, "start_edit_line not found"); GTLineEdit::setText(os, start, "1000"); QLineEdit *end = w->findChild<QLineEdit *>("end_edit_line"); CHECK_SET_ERR(end != NULL, "end_edit_line not found"); GTLineEdit::setText(os, end, "4000"); QDialogButtonBox *buttonBox = w->findChild<QDialogButtonBox *>(QString::fromUtf8("buttonBox")); CHECK(NULL != buttonBox, ); QPushButton *button = buttonBox->button(QDialogButtonBox::Ok); CHECK(NULL != button, ); GTWidget::click(os, button); } }; GTUtilsDialog::waitForDialog(os, new ORFDialogFiller(os)); GTWidget::click(os, GTAction::button(os, "Find ORFs")); GTUtilsTaskTreeView::waitTaskFinished(os); QList<U2Region> regions = GTUtilsAnnotationsTreeView::getAnnotatedRegions(os); foreach (const U2Region &r, regions) { CHECK_SET_ERR((r.startPos >= 1000 && r.startPos <= 4000 && r.endPos() >= 1000 && r.endPos() <= 4000), "Invalid annotated region!"); } } GUI_TEST_CLASS_DEFINITION(test_3924) { //check comments for vector-nti format GTFileDialog::openFile(os, testDir + "_common_data/vector_nti_sequence/unrefined.gb"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsAnnotationsTreeView::selectItems(os, QStringList() << "CDS"); QString name = GTUtilsAnnotationsTreeView::getQualifierValue(os, "vntifkey", "CDS"); CHECK_SET_ERR(name == "4", "unexpected qualifier value: " + name) } GUI_TEST_CLASS_DEFINITION(test_3927) { // 1. Open "_common_data/scenarios/msa/ma.aln". GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW/", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Enable collapsing mode. GTWidget::click(os, GTToolbar::getWidgetForActionName(os, GTToolbar::getToolbar(os, "mwtoolbar_activemdi"), "Enable collapsing")); // 3. Remove the first sequence. x3 GTUtilsMSAEditorSequenceArea::removeSequence(os, "Phaneroptera_falcata"); GTUtilsMSAEditorSequenceArea::removeSequence(os, "Isophya_altaica_EF540820"); GTUtilsMSAEditorSequenceArea::removeSequence(os, "Bicolorana_bicolor_EF540830"); //Expected state safe point didn't triggered } GUI_TEST_CLASS_DEFINITION(test_3928) { // 1. Open file "data/samples/CLUSTALW/COI.aln" // 2. Set any sequence as a reference via a context menu // 3. Open the "Statistics" tab in the Options panel // Expected state: reference sequence is shown in the "Reference sequence" section // 4. Close the Options panel // 5. Set any other sequence as a reference via a context menu // 6. Open the "Statistics" tab in the Options panel // Expected state: new reference sequence is shown in the "Reference sequence" section GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW", "COI.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDialog::waitForDialog(os, new PopupChooserByText(os, QStringList() << "Set this sequence as reference")); GTUtilsMSAEditorSequenceArea::callContextMenu(os, QPoint(5, 5)); QString currentReference = GTUtilsMsaEditor::getReferenceSequenceName(os); CHECK_SET_ERR("Metrioptera_japonica_EF540831" == currentReference, QString("An unexpected reference sequence is set: expect '%1', got '%2'").arg("Metrioptera_japonica_EF540831").arg(currentReference)); GTUtilsDialog::waitForDialog(os, new PopupChecker(os, QStringList() << "unset_reference")); GTUtilsMSAEditorSequenceArea::callContextMenu(os, QPoint(6, 6)); GTUtilsDialog::waitForDialog(os, new PopupChecker(os, QStringList() << "set_seq_as_reference")); GTUtilsMSAEditorSequenceArea::callContextMenu(os, QPoint(6, 6)); GTUtilsDialog::waitForDialog(os, new PopupChooserByText(os, QStringList() << "Set this sequence as reference")); GTUtilsMSAEditorSequenceArea::callContextMenu(os, QPoint(6, 6)); currentReference = GTUtilsMsaEditor::getReferenceSequenceName(os); CHECK_SET_ERR("Gampsocleis_sedakovii_EF540828" == currentReference, QString("An unexpected reference sequence is set: expect '%1', got '%2'").arg("Gampsocleis_sedakovii_EF540828").arg(currentReference)); } GUI_TEST_CLASS_DEFINITION(test_3938) { GTLogTracer lt; GTUtilsWorkflowDesigner::openWorkflowDesigner(os); GTUtilsWorkflowDesigner::addSample(os, "Variation annotation with SnpEff"); GTKeyboardDriver::keyClick(Qt::Key_Escape); GTUtilsWorkflowDesigner::addInputFile(os, "Input Variations File", testDir + "_common_data/vcf/valid.vcf"); GTUtilsWorkflowDesigner::click(os, "Annotate and Predict Effects with SnpEff"); GTUtilsDialog::waitForDialog(os, new SnpEffDatabaseDialogFiller(os, "ebola_zaire")); GTUtilsWorkflowDesigner::setParameter(os, "Genome", QVariant(), GTUtilsWorkflowDesigner::customDialogSelector); GTUtilsWorkflowDesigner::runWorkflow(os); GTUtilsTaskTreeView::waitTaskFinished(os); QString error = lt.getJoinedErrorString(); CHECK_SET_ERR(!error.contains("finished with error", Qt::CaseInsensitive), "Unexpected error message in the log: " + error); } GUI_TEST_CLASS_DEFINITION(test_3950) { // 1. Build BWA MEM index for "_common_data/bwa/NC_000021.gbk.fa // 2. Open "_common_data/bwa/workflow/bwa-mem.uwl" // 3. Set NC_000021.gbk.fa as reference // 4. Reads: nrsf-chr21.fastq, control-chr21.fastq // 5. Run workflow // Expected state: no error (code 1) GTLogTracer l; GTFile::copy(os, testDir + "_common_data/bwa/NC_000021.gbk.min.fa", sandBoxDir + "test_3950.fa"); GTUtilsDialog::waitForDialog(os, new BuildIndexDialogFiller(os, sandBoxDir, "test_3950.fa", "BWA MEM")); GTMenu::clickMainMenuItem(os, QStringList() << "Tools" << "NGS data analysis" << "Build index for reads mapping..."); GTUtilsDialog::waitAllFinished(os); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDialog::waitForDialogWhichMayRunOrNot(os, new StartupDialogFiller(os)); GTUtilsProject::openFile(os, testDir + "_common_data/bwa/workflow/bwa-mem.uwl"); GTUtilsWorkflowDesigner::checkWorkflowDesignerWindowIsActive(os); GTUtilsWorkflowDesigner::click(os, "File List"); GTUtilsWorkflowDesigner::setDatasetInputFile(os, testDir + "_common_data/bwa/nrsf-chr21.fastq"); GTUtilsWorkflowDesigner::createDataset(os); GTUtilsWorkflowDesigner::setDatasetInputFile(os, testDir + "_common_data/bwa/control-chr21.fastq"); GTUtilsWorkflowDesigner::click(os, "Align reads with BWA MEM"); GTUtilsWorkflowDesigner::setParameter(os, "Reference genome", sandBoxDir + "test_3950.fa", GTUtilsWorkflowDesigner::textValue); GTUtilsWorkflowDesigner::setParameter(os, "Output folder", QDir(sandBoxDir).absolutePath(), GTUtilsWorkflowDesigner::textValue); GTUtilsWorkflowDesigner::runWorkflow(os); GTUtilsTaskTreeView::waitTaskFinished(os, 40000); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3953) { /* 1. Open "human_T1.fa" 2. Open "find pattern" tab 3. Insert "TTGTCAGATTCACCA" into find pattern field 4. Put cursor to the beginning of find pattern field 5. Pres "delete" key, until all symbols are deleted Expected state: "create annotation" button is disabled Actual: "create annotation" button is enabled */ QString pattern("TTGTCAGATTCACCA"); GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(500); GTWidget::click(os, GTWidget::findWidget(os, "OP_FIND_PATTERN")); GTGlobals::sleep(500); GTKeyboardDriver::keySequence(pattern); GTGlobals::sleep(1000); GTKeyboardDriver::keyClick(Qt::Key_Home); GTGlobals::sleep(1000); QPushButton *getAnnotations = qobject_cast<QPushButton *>(GTWidget::findWidget(os, "getAnnotationsPushButton")); CHECK_SET_ERR(getAnnotations != NULL, "getAnnotationsPushButton is NULL"); CHECK_SET_ERR(getAnnotations->isEnabled() == true, QString("getAnnotationsPushButton is not active")); for (int i = 0; i <= pattern.length(); i++) { GTKeyboardDriver::keyClick(Qt::Key_Delete); GTGlobals::sleep(200); } CHECK_SET_ERR(getAnnotations->isEnabled() == false, QString("getAnnotationsPushButton is active")); } GUI_TEST_CLASS_DEFINITION(test_3959) { // 1. { File -> New document from text... } // Expected state: the "Create document" dialog has appeared // 2. Set sequence "AAAA", set some valid document path and click "Create". // Expected state: the Sequence view has opened, the "Zoom out" button is disabled. // 3. Call context menu { Edit sequence -> Insert subsequence... } // Expected state: the "Insert Sequence" dialog has appeared // 4. Set sequence "AAAA", position to insert - 5 and click "OK". // Expected state: the same sequence region is displayed, scrollbar has shrunk, "Zoom out" has enabled. Runnable *filler = new CreateDocumentFiller(os, "AAAA", false, CreateDocumentFiller::StandardRNA, true, false, "", testDir + "_common_data/scenarios/sandbox/result", CreateDocumentFiller::FASTA, "result", true); GTGlobals::sleep(); GTUtilsDialog::waitForDialog(os, filler); GTGlobals::sleep(); GTGlobals::sleep(); GTMenu::clickMainMenuItem(os, QStringList() << "File" << "New document from text...", GTGlobals::UseKey); GTUtilsTaskTreeView::waitTaskFinished(os); //QToolBar* mwtoolbar_activemdi = GTToolbar::getToolbar(os, MWTOOLBAR_MAIN); //QWidget* zoomOutButton = GTToolbar::getWidgetForActionTooltip(os, mwtoolbar_activemdi, "Zoom Out"); //CHECK_SET_ERR(!zoomOutButton->isEnabled(), "zoomOutButton button on toolbar is not disabled"); GTGlobals::sleep(); Runnable *filler1 = new InsertSequenceFiller(os, "AAAA"); GTUtilsDialog::waitForDialog(os, filler1); GTMenu::clickMainMenuItem(os, QStringList() << "Actions" << "Edit" << "Insert subsequence...", GTGlobals::UseKey); GTGlobals::sleep(); } GUI_TEST_CLASS_DEFINITION(test_3960) { /* 1. Open _common_data/scenarios/_regression/3960/all.gb * Expected state: No error messages in log */ GTLogTracer logTracer; GTUtilsDialog::waitForDialog(os, new GTFileDialogUtils(os, testDir + "_common_data/scenarios/_regression/3960", "all.gb")); GTUtilsDialog::waitForDialog(os, new DocumentFormatSelectorDialogFiller(os, "GenBank")); GTUtilsDialog::waitForDialog(os, new SequenceReadingModeSelectorDialogFiller(os, SequenceReadingModeSelectorDialogFiller::Merge)); GTMenu::clickMainMenuItem(os, QStringList() << "File" << "Open as..."); GTUtilsTaskTreeView::waitTaskFinished(os); CHECK_SET_ERR(!logTracer.hasErrors(), "Errors in log: " + logTracer.getJoinedErrorString()); } GUI_TEST_CLASS_DEFINITION(test_3975) { // 1. Open _common_data/gff/noheader.gff // 2. Connect it with some sequence to observe annotations // 3. Open the file in some text editor // Current state: there is annotation "chromosome" GTFileDialog::openFile(os, dataDir + "samples/FASTA/", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); GTFileDialog::openFile(os, testDir + "_common_data/gff/", "noheader.gff"); GTUtilsTaskTreeView::waitTaskFinished(os); QModelIndex idxGff = GTUtilsProjectTreeView::findIndex(os, "scaffold_1 features"); CHECK_SET_ERR(idxGff.isValid(), "Can not find 'scaffold_1 features' object"); QWidget *seqArea = GTWidget::findWidget(os, "render_area_human_T1 (UCSC April 2002 chr7:115977709-117855134)"); CHECK_SET_ERR(seqArea != NULL, "No sequence view opened"); GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, "Yes")); GTUtilsDialog::waitForDialog(os, new CreateObjectRelationDialogFiller(os)); GTUtilsProjectTreeView::dragAndDrop(os, idxGff, seqArea); QTreeWidgetItem *annotationGroup = GTUtilsAnnotationsTreeView::findItem(os, "chromosome (0, 1)"); CHECK_SET_ERR(NULL != annotationGroup, "Annotations have not been found"); } GUI_TEST_CLASS_DEFINITION(test_3983) { // 1. Open file "_common_data\fasta\amino_multy.aln" // 2. Open "Pairwise Alignment" OP tab // 3. Select first two sequences in the tab // 4. Run alignment // Current state: UGENE crashes GTLogTracer l; GTFileDialog::openFile(os, testDir + "_common_data/fasta", "amino_multy.aln"); GTUtilsMsaEditor::checkMsaEditorWindowIsActive(os); GTUtilsOptionPanelMsa::openTab(os, GTUtilsOptionPanelMsa::PairwiseAlignment); GTUtilsOptionPanelMsa::checkTabIsOpened(os, GTUtilsOptionPanelMsa::PairwiseAlignment); GTUtilsOptionPanelMsa::addFirstSeqToPA(os, "chr1_gl000191_random_Amino_translation_"); GTKeyboardDriver::keyClick(Qt::Key_Enter); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsMSAEditorSequenceArea::clickToPosition(os, QPoint(1, 1)); GTWidget::click(os, GTUtilsOptionPanelMsa::getAddButton(os, 2)); GTKeyboardDriver::keyClick(Qt::Key_Down); GTKeyboardDriver::keyClick(Qt::Key_Enter); GTWidget::click(os, GTUtilsOptionPanelMsa::getAlignButton(os)); GTUtilsTaskTreeView::waitTaskFinished(os); CHECK_SET_ERR(l.hasErrors(), "Expected to have errors in the log, but no errors found"); } GUI_TEST_CLASS_DEFINITION(test_3988) { // 1. Open "_common_data/zero". // Expected state: a message box appear, it contains a message: "File is empty: ...", the log contains the same message. GTLogTracer logTracer; GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::Ok, "File is empty:")); GTUtilsProject::openFileExpectNoProject(os, testDir + "_common_data/zero"); GTUtilsTaskTreeView::waitTaskFinished(os); GTGlobals::sleep(); GTUtilsLog::checkContainsError(os, logTracer, "File is empty:"); GTGlobals::sleep(); } GUI_TEST_CLASS_DEFINITION(test_3994) { GTFileDialog::openFile(os, dataDir + "samples/CLUSTALW", "HIV-1.aln"); GTUtilsTaskTreeView::waitTaskFinished(os); GTWidget::findWidget(os, "msa_editor_sequence_area"); QColor before = GTUtilsMSAEditorSequenceArea::getColor(os, QPoint(1, 0)); // Open the "Highlighting" options panel tab. GTWidget::click(os, GTWidget::findWidget(os, "OP_MSA_HIGHLIGHTING")); // Select different highlighting schemes. QComboBox *highlightingScheme = qobject_cast<QComboBox *>(GTWidget::findWidget(os, "highlightingScheme")); GTComboBox::setIndexWithText(os, highlightingScheme, "Conservation level"); QWidget *w = GTWidget::findWidget(os, "thresholdLessRb"); GTRadioButton::click(os, qobject_cast<QRadioButton *>(w)); GTGlobals::sleep(); QColor after = GTUtilsMSAEditorSequenceArea::getColor(os, QPoint(1, 0)); //check color change CHECK_SET_ERR(before != after, "colors not changed"); } GUI_TEST_CLASS_DEFINITION(test_3995) { GTLogTracer logTracer; // 1. Open "human_T1.fa" GTFileDialog::openFile(os, dataDir + "samples/FASTA", "human_T1.fa"); GTUtilsTaskTreeView::waitTaskFinished(os); // 2. Open circular view GTWidget::click(os, GTWidget::findWidget(os, "CircularViewAction")); // 3. Use context menu for exporting view as image GTUtilsDialog::waitForDialog(os, new PopupChooser(os, QStringList() << ADV_MENU_EXPORT << "Save circular view as image")); GTUtilsDialog::waitForDialog(os, new DefaultDialogFiller(os, "ImageExportForm")); GTWidget::click(os, GTWidget::findWidget(os, "CV_ADV_single_sequence_widget_0"), Qt::RightButton); // Expected state: "Export Image" dialog appeared // 4. Press "Export" button GTUtilsTaskTreeView::waitTaskFinished(os); // Bug state: Error message appears: "File path contains illegal characters or too long" GTUtilsLog::check(os, logTracer); } GUI_TEST_CLASS_DEFINITION(test_3996) { GTLogTracer l; //1. Open "samples/ABIF/A01.abi" GTFileDialog::openFile(os, dataDir + "/samples/ABIF/", "A01.abi"); GTUtilsTaskTreeView::waitTaskFinished(os); //2. Zoom In GTWidget::click(os, GTAction::button(os, "action_zoom_in_A1#berezikov")); //3. Click on the chrom.view QWidget *chromaView = GTWidget::findWidget(os, "chromatogram_view_A1#berezikov"); const QRect chromaViewRect = chromaView->rect(); GTMouseDriver::moveTo(chromaView->mapToGlobal(chromaViewRect.center() - QPoint(20, 0))); GTMouseDriver::press(); GTMouseDriver::moveTo(chromaView->mapToGlobal(chromaViewRect.center() + QPoint(20, 0))); GTMouseDriver::release(); GTThread::waitForMainThread(); GTUtilsLog::check(os, l); } GUI_TEST_CLASS_DEFINITION(test_3997) { GTFileDialog::openFile(os, testDir + "_common_data/clustal", "3000_sequences.nwk"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsDocument::removeDocument(os, "3000_sequences.nwk"); } GUI_TEST_CLASS_DEFINITION(test_3998) { // 1. Open attached sequence GTLogTracer l; // 2. a) Use menu // {Edit sequence->Reverse complement sequence} GTFileDialog::openFile(os, testDir + "_common_data/regression/3998/sequence.fasta"); GTUtilsTaskTreeView::waitTaskFinished(os); GTMenu::clickMainMenuItem(os, QStringList() << "Actions" << "Edit" << "Replace the whole sequence by" << "Complementary (5'-3') sequence"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsProjectTreeView::click(os, "sequence.fasta"); GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::No)); GTKeyboardDriver::keyClick(Qt::Key_Delete); GTGlobals::sleep(); // Current state: UGENE crashes // b) Use menu // {Edit sequence->Reverse sequence} GTFileDialog::openFile(os, testDir + "_common_data/regression/3998/sequence.fasta"); GTUtilsTaskTreeView::waitTaskFinished(os); GTMenu::clickMainMenuItem(os, QStringList() << "Actions" << "Edit" << "Replace the whole sequence by" << "Reverse (3'-5') sequence"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsProjectTreeView::click(os, "sequence.fasta"); GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::No)); GTKeyboardDriver::keyClick(Qt::Key_Delete); GTGlobals::sleep(); // Current state: UGENE crashes // c) Use menu // {Edit sequence->Complement sequence} GTFileDialog::openFile(os, testDir + "_common_data/regression/3998/sequence.fasta"); GTUtilsTaskTreeView::waitTaskFinished(os); GTMenu::clickMainMenuItem(os, QStringList() << "Actions" << "Edit" << "Replace the whole sequence by" << "Complementary (5'-3') sequence"); GTUtilsTaskTreeView::waitTaskFinished(os); GTUtilsProjectTreeView::click(os, "sequence.fasta"); GTUtilsDialog::waitForDialog(os, new MessageBoxDialogFiller(os, QMessageBox::No)); GTKeyboardDriver::keyClick(Qt::Key_Delete); GTGlobals::sleep(); // Current state: error occurred, sequence disappeared from the display GTUtilsLog::check(os, l); } } // namespace GUITest_regression_scenarios } // namespace U2
clemble/object-generator
src/test/java/com/stresstest/random/permutations/external/ExternalPublicEnum.java
<reponame>clemble/object-generator package com.stresstest.random.permutations.external; public enum ExternalPublicEnum { PUBLIC_ONE, PUBLIC_TWO, PUBLIC_THREE, PUBLIC_FOUR, PUBLIC_FIVE, PUBLIC_SIX, PUBLIC_SEVEN, PUBLIC_EIGHT, PUBLIC_NINE; }
Chromico/bk-base
src/dataflow/unified-computing/python/bkbase/dataflow/batch/topo/batch_topology.py
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: -------------------------------------------------------------------- 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. """ from bkbase.dataflow.batch.utils import batch_utils from bkbase.dataflow.batch.utils.custom_type import TimeUnit, WindowType from bkbase.dataflow.core.types.node import SinkNode, SourceNode from bkbase.dataflow.core.types.topology import Topology class BatchTopology(Topology): def __init__(self, batch_topo_builder): super().__init__(batch_topo_builder) self.batch_topo_builder = batch_topo_builder self.job_id = self.batch_topo_builder.schedule_id self.schedule_time = batch_utils.time_round_to_hour(int(batch_topo_builder.schedule_info["schedule_time"])) self.exec_id = self.batch_topo_builder.schedule_info["exec_id"] self.geog_area_code = self.batch_topo_builder.geog_area_code self.is_accumulate = self.batch_topo_builder.is_accumulate self.user_pkg_path = self.batch_topo_builder.user_pkg_path self.map_nodes(batch_topo_builder.type_tables) def __str__(self): return ( "job_id: %s, source_nodes: {%s}, sink_nodes: {%s}, " "schedule_time: %s, exec_id: %s, geog_area_code: %s, " "user_main_class: %s, user_main_module: %s, user_pkg_path: %s, user_args: %s" % ( self.job_id, str(self.__generate_source_str()), str(self.__generate_sink_str()), self.schedule_time, self.exec_id, self.geog_area_code, self.user_main_class, self.user_main_module, self.user_pkg_path, self.user_args, ) ) def map_nodes(self, type_tables): for node_type in type_tables: if node_type == "source": self.source_nodes = self.map_source_node(type_tables[node_type]) elif node_type == "sink": self.sink_nodes = self.map_sink_node(type_tables[node_type]) def map_source_node(self, nodes): node_dict = {} for node in nodes: if nodes[node]["input"]["type"] != "ignite": batch_source_node = BatchSourceNode() batch_source_node.node_id = node batch_source_node.map(nodes[node]) node_dict[node] = batch_source_node else: raise NotImplementedError("Only HDFS input is supported") return node_dict def map_sink_node(self, nodes): node_dict = {} for node in nodes: batch_sink_node = BatchSinkNode() batch_sink_node.node_id = node batch_sink_node.map(nodes[node]) node_dict[node] = batch_sink_node return node_dict def __generate_source_str(self): source_str = "" for source_node in self.source_nodes: source_str += str(self.source_nodes[source_node]) + " " return source_str def __generate_sink_str(self): sink_str = "" for sink_node in self.sink_nodes: sink_str += str(self.sink_nodes[sink_node]) + " " return sink_str class BatchSourceNode(SourceNode): def __init__(self): super().__init__() self.window = None self.storage_params = None self.self_dependency_mode = "" def map(self, node): self.window = self.__build_window(node["window"]) self.input = node["input"]["input_paths"] self.self_dependency_mode = node["self_dependency_mode"] self.storage_params = node["input"]["conf"] self.fields = node["fields"] def __build_window(self, window_params): is_accumulate = window_params["is_accumulate"] batch_window_offset = int(window_params["batch_window_offset"]) start = int(window_params["segment"]["start"]) end = int(window_params["segment"]["end"]) if str(window_params["segment"]["unit"]) == "day": unit = TimeUnit.DAY else: unit = TimeUnit.HOUR if is_accumulate: window_type = WindowType.ACCUMULATION else: window_type = WindowType.TUMBLING return BatchWindow(batch_window_offset, start, end, unit, window_type) def __str__(self): return "{}, window: {}, storage_params: {}, self_dependency_mode: {}".format( super().__str__(), self.window, self.storage_params, self.self_dependency_mode, ) class BatchSinkNode(SinkNode): def __init__(self): super().__init__() self.storages = None self.extra_storage = False def __str__(self): return "{}, storages: {}, extra_storage {}".format(super().__str__(), self.storages, self.extra_storage) def map(self, node): self.output = node["output"]["output_paths"] self.event_time = node["output"]["event_time"] self.storages = node["output"]["conf"] self.extra_storage = node["output"]["extra_storage"] class BatchWindow(object): def __init__(self, batch_window_offset, start, end, unit, window_type): self.batch_window_offset = batch_window_offset self.start = start self.end = end self.unit = unit self.window_type = window_type def get_start_in_hour(self): if self.unit == TimeUnit.DAY: return self.start * 24 return self.start def get_end_in_hour(self): if self.unit == TimeUnit.DAY: return self.end * 24 return self.end def get_batch_window_offset(self): return self.batch_window_offset def __str__(self): return "batch_window_offset: {}, start: {}, end: {}, unit: {}, window_type: {}".format( self.batch_window_offset, self.start, self.end, self.unit, self.window_type, )
shrutimantri/airflow
tests/models/test_timestamp.py
<filename>tests/models/test_timestamp.py # 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. import pendulum import pytest from freezegun import freeze_time from airflow.models import DAG, Log, TaskInstance from airflow.operators.dummy_operator import DummyOperator from airflow.utils import timezone from airflow.utils.db import provide_session from airflow.utils.state import State @pytest.yield_fixture(name="clear_db_fixture") @provide_session def clear_db(session=None): session.query(Log).delete() session.query(TaskInstance).delete() yield session session.query(Log).delete() session.query(TaskInstance).delete() session.commit() def add_log(execdate, session, timezone_override=None): dag = DAG(dag_id='logging', default_args={'start_date': execdate}) task = DummyOperator(task_id='dummy', dag=dag, owner='airflow') task_instance = TaskInstance(task=task, execution_date=execdate, state='success') session.merge(task_instance) log = Log(State.RUNNING, task_instance) if timezone_override: log.dttm = log.dttm.astimezone(timezone_override) session.add(log) session.commit() return log def test_timestamp_behaviour(clear_db_fixture): for session in clear_db_fixture: execdate = timezone.utcnow() with freeze_time(execdate): current_time = timezone.utcnow() old_log = add_log(execdate, session) session.expunge(old_log) log_time = session.query(Log).one().dttm assert log_time == current_time assert log_time.tzinfo.name == 'UTC' def test_timestamp_behaviour_with_timezone(clear_db_fixture): for session in clear_db_fixture: execdate = timezone.utcnow() with freeze_time(execdate): current_time = timezone.utcnow() old_log = add_log(execdate, session, timezone_override=pendulum.timezone('Europe/Warsaw')) session.expunge(old_log) # No matter what timezone we set - we should always get back UTC log_time = session.query(Log).one().dttm assert log_time == current_time assert old_log.dttm.tzinfo.name != 'UTC' assert log_time.tzinfo.name == 'UTC' assert old_log.dttm.astimezone(pendulum.timezone('UTC')) == log_time
npocmaka/Windows-Server-2003
printscan/faxsrv/print/faxprint/prnwzrd/coverpg.h
/*++ Copyright (c) 1996 Microsoft Corporation Module Name: coverpg.h Abstract: Functions for working with cover pages Environment: Windows XP fax driver user interface Revision History: 02/05/96 -davidx- Created it. dd-mm-yy -author- description --*/ #ifndef _COVERPAGE_H_ #define _COVERPAGE_H_ // // Cover page filename extension // #define MAX_FILENAME_EXT 4 // // Data structure for representing a list of cover pages: // the first nServerDirs paths refer to the server cover page directory // remaining paths contain user cover page directories // #define MAX_COVERPAGE_DIRS 8 typedef struct { INT nDirs; INT nServerDirs; LPTSTR pDirPath[MAX_COVERPAGE_DIRS]; } CPDATA, *PCPDATA; // // Flag bits attached to each cover page in a listbox // #define CPFLAG_DIRINDEX 0x00FF #define CPFLAG_SERVERCP 0x0100 #define CPFLAG_SELECTED 0x0400 #define CPFLAG_SUFFIX 0x0800 // // Generate a list of available cover pages (both server and user) // VOID InitCoverPageList( PCPDATA pCPInfo, HWND hwndList, LPTSTR pSelectedCoverPage ); // // Retrieve the currently selected cover page name // INT GetSelectedCoverPage( PCPDATA pCPInfo, IN HWND hwndList, OUT LPTSTR lptstrFullPath, IN UINT cchstrFullPath, OUT LPTSTR lptstrFileName, IN UINT cchstrFileName, OUT BOOL * pbIsServerPage ); // // Allocate memory to hold cover page information // PCPDATA AllocCoverPageInfo( LPTSTR lptstrServerName, LPTSTR lptstrPrinterName, BOOL ServerCpOnly ); // // must clients use server coverpages? // BOOL UseServerCp( LPTSTR lptstrServerName ); // // Free up memory used for cover page information // VOID FreeCoverPageInfo( PCPDATA pCPInfo ); #endif // !_COVERPAGE_H_
06needhamt/intellij-community
plugins/lombok/src/main/java/de/plushnikov/intellij/plugin/lombokconfig/ConfigDiscovery.java
package de.plushnikov.intellij.plugin.lombokconfig; import com.google.common.annotations.VisibleForTesting; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiFile; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.GlobalSearchScopes; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.util.containers.ConcurrentFactoryMap; import com.intellij.util.indexing.FileBasedIndex; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; public class ConfigDiscovery { @NotNull public static ConfigDiscovery getInstance() { return ApplicationManager.getApplication().getService(ConfigDiscovery.class); } public @NotNull Collection<String> getMultipleValueLombokConfigProperty(@NotNull ConfigKey configKey, @NotNull PsiClass psiClass) { return getConfigProperty(configKey, psiClass); } @NotNull public String getStringLombokConfigProperty(@NotNull ConfigKey configKey, @NotNull PsiClass psiClass) { Collection<String> result = getConfigProperty(configKey, psiClass); if (!result.isEmpty()) { return result.iterator().next(); } return configKey.getConfigDefaultValue(); } public boolean getBooleanLombokConfigProperty(@NotNull ConfigKey configKey, @NotNull PsiClass psiClass) { final String configProperty = getStringLombokConfigProperty(configKey, psiClass); return Boolean.parseBoolean(configProperty); } @NotNull private Collection<String> getConfigProperty(@NotNull ConfigKey configKey, @NotNull PsiClass psiClass) { @Nullable PsiFile psiFile = calculatePsiFile(psiClass); if (psiFile != null) { return discoverPropertyWithCache(configKey, psiFile); } return Collections.singletonList(configKey.getConfigDefaultValue()); } @Nullable private static PsiFile calculatePsiFile(@NotNull PsiClass psiClass) { PsiFile psiFile = psiClass.getContainingFile(); if (psiFile != null) { psiFile = psiFile.getOriginalFile(); } return psiFile; } @NotNull protected Collection<String> discoverPropertyWithCache(@NotNull ConfigKey configKey, @NotNull PsiFile psiFile) { return CachedValuesManager.getCachedValue(psiFile, () -> { Map<ConfigKey, Collection<String>> result = ConcurrentFactoryMap.createMap(configKeyInner -> discoverProperty(configKeyInner, psiFile)); return CachedValueProvider.Result.create(result, LombokConfigChangeListener.CONFIG_CHANGE_TRACKER); }).get(configKey); } @NotNull protected Collection<String> discoverProperty(@NotNull ConfigKey configKey, @NotNull PsiFile psiFile) { if (configKey.isConfigScalarValue()) { return discoverScalarProperty(configKey, psiFile); } return discoverCollectionProperty(configKey, psiFile); } @NotNull private Collection<String> discoverScalarProperty(@NotNull ConfigKey configKey, @NotNull PsiFile psiFile) { @Nullable VirtualFile currentFile = psiFile.getVirtualFile(); while (currentFile != null) { ConfigValue configValue = readProperty(configKey, psiFile.getProject(), currentFile); if (null != configValue) { if (null == configValue.getValue()) { if (configValue.isStopBubbling()) { break; } } else { return Collections.singletonList(configValue.getValue()); } } currentFile = currentFile.getParent(); } return Collections.singletonList(configKey.getConfigDefaultValue()); } @VisibleForTesting protected FileBasedIndex getFileBasedIndex() { return FileBasedIndex.getInstance(); } @Nullable private ConfigValue readProperty(@NotNull ConfigKey configKey, @NotNull Project project, @NotNull VirtualFile directory) { GlobalSearchScope directoryScope = GlobalSearchScopes.directoryScope(project, directory, false); List<ConfigValue> values = getFileBasedIndex().getValues(LombokConfigIndex.NAME, configKey, directoryScope); if (!values.isEmpty()) { return values.iterator().next(); } return null; } @NotNull private Collection<String> discoverCollectionProperty(@NotNull ConfigKey configKey, @NotNull PsiFile file) { List<String> properties = new ArrayList<>(); @Nullable VirtualFile currentFile = file.getVirtualFile(); while (currentFile != null) { final ConfigValue configValue = readProperty(configKey, file.getProject(), currentFile); if (null != configValue) { if (null == configValue.getValue()) { if (configValue.isStopBubbling()) { break; } } else { properties.add(configValue.getValue()); } } currentFile = currentFile.getParent(); } Collections.reverse(properties); Set<String> result = new HashSet<>(); for (String configProperty : properties) { if (StringUtil.isNotEmpty(configProperty)) { final String[] values = configProperty.split(";"); for (String value : values) { if (value.startsWith("+")) { result.add(value.substring(1)); } else if (value.startsWith("-")) { result.remove(value.substring(1)); } } } } return result; } }
clairechingching/ScaffCC
clang/test/SemaTemplate/instantiate-sizeof.cpp
<filename>clang/test/SemaTemplate/instantiate-sizeof.cpp // RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s // Make sure we handle contexts correctly with sizeof template<typename T> void f(T n) { int buffer[n]; [] { int x = sizeof(sizeof(buffer)); }(); } int main() { f<int>(1); }
amahussein/hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/auth/delegation/MiniKerberizedHadoopCluster.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.hadoop.fs.s3a.auth.delegation; import java.io.File; import java.io.IOException; import java.util.Properties; import org.apache.hadoop.thirdparty.com.google.common.base.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeys; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.HdfsConfiguration; import org.apache.hadoop.http.HttpConfig; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapreduce.MRJobConfig; import org.apache.hadoop.mapreduce.v2.jobhistory.JHAdminConfig; import org.apache.hadoop.minikdc.MiniKdc; import org.apache.hadoop.security.KDiag; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.ssl.KeyStoreTestUtil; import org.apache.hadoop.service.CompositeService; import org.apache.hadoop.test.GenericTestUtils; import org.apache.hadoop.yarn.conf.YarnConfiguration; import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION; import static org.apache.hadoop.hdfs.DFSConfigKeys.*; import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_DATA_TRANSFER_PROTECTION_KEY; import static org.apache.hadoop.mapreduce.v2.jobhistory.JHAdminConfig.DEFAULT_MR_HISTORY_PORT; import static org.apache.hadoop.security.UserGroupInformation.loginUserFromKeytabAndReturnUGI; import static org.apache.hadoop.yarn.conf.YarnConfiguration.*; import static org.junit.Assert.assertTrue; /** * This is intended to support setting up an mini-secure Hadoop + YARN + MR * cluster. * It does not do this, yet, for the following reason: things don't work. * It is designed to be started/stopped at the class level. * however, users should be logged in in test cases, so that their local state * (credentials etc) are reset in every test. */ public class MiniKerberizedHadoopCluster extends CompositeService { private static final Logger LOG = LoggerFactory.getLogger(MiniKerberizedHadoopCluster.class); public static final String ALICE = "alice"; public static final String BOB = "bob"; public static final String HTTP_LOCALHOST = "HTTP/localhost@$LOCALHOST"; /** * The hostname is dynamically determined based on OS, either * "localhost" (non-windows) or 127.0.0.1 (windows). */ public static final String LOCALHOST_NAME = Path.WINDOWS ? "127.0.0.1" : "localhost"; private MiniKdc kdc; private File keytab; private File workDir; private String krbInstance; private String loginUsername; private String loginPrincipal; private String sslConfDir; private String clientSSLConfigFileName; private String serverSSLConfigFileName; private String alicePrincipal; private String bobPrincipal; /** * Create the cluster. * If this class's log is at DEBUG level, this also turns * Kerberos diagnostics on in the JVM. */ public MiniKerberizedHadoopCluster() { super("MiniKerberizedHadoopCluster"); // load all the configs to force in the -default.xml files new HdfsConfiguration(); new YarnConfiguration(); new JobConf(); if (LOG.isDebugEnabled()) { // turn on kerberos logging @ debug. System.setProperty(KDiag.SUN_SECURITY_KRB5_DEBUG, "true"); System.setProperty(KDiag.SUN_SECURITY_SPNEGO_DEBUG, "true"); } } public MiniKdc getKdc() { return kdc; } public File getKeytab() { return keytab; } public String getKeytabPath() { return keytab.getAbsolutePath(); } public UserGroupInformation createBobUser() throws IOException { return loginUserFromKeytabAndReturnUGI(bobPrincipal, keytab.getAbsolutePath()); } public UserGroupInformation createAliceUser() throws IOException { return loginUserFromKeytabAndReturnUGI(alicePrincipal, keytab.getAbsolutePath()); } public File getWorkDir() { return workDir; } public String getKrbInstance() { return krbInstance; } public String getLoginUsername() { return loginUsername; } public String getLoginPrincipal() { return loginPrincipal; } public String withRealm(String user) { return user + "@EXAMPLE.COM"; } /** * Service init creates the KDC. * @param conf configuration */ @Override protected void serviceInit(final Configuration conf) throws Exception { patchConfigAtInit(conf); super.serviceInit(conf); Properties kdcConf = MiniKdc.createConf(); workDir = GenericTestUtils.getTestDir("kerberos"); workDir.mkdirs(); kdc = new MiniKdc(kdcConf, workDir); krbInstance = LOCALHOST_NAME; } /** * Start the KDC, create the keytab and the alice and bob users, * and UGI instances of them logged in from the keytab. */ @Override protected void serviceStart() throws Exception { super.serviceStart(); kdc.start(); keytab = new File(workDir, "keytab.bin"); loginUsername = UserGroupInformation.getLoginUser().getShortUserName(); loginPrincipal = loginUsername + "/" + krbInstance; alicePrincipal = ALICE + "/" + krbInstance; bobPrincipal = BOB + "/" + krbInstance; kdc.createPrincipal(keytab, alicePrincipal, bobPrincipal, "HTTP/" + krbInstance, HTTP_LOCALHOST, loginPrincipal); final File keystoresDir = new File(workDir, "ssl"); keystoresDir.mkdirs(); sslConfDir = KeyStoreTestUtil.getClasspathDir( this.getClass()); KeyStoreTestUtil.setupSSLConfig(keystoresDir.getAbsolutePath(), sslConfDir, getConfig(), false); clientSSLConfigFileName = KeyStoreTestUtil.getClientSSLConfigFileName(); serverSSLConfigFileName = KeyStoreTestUtil.getServerSSLConfigFileName(); } @Override protected void serviceStop() throws Exception { super.serviceStop(); // this can throw an exception, but it will get caught by the superclass. kdc.stop(); } protected void patchConfigAtInit(final Configuration conf) { // turn off some noise during debugging int timeout = 60 * 60_1000; conf.setInt("jvm.pause.info-threshold.ms", timeout); conf.setInt("jvm.pause.warn-threshold.ms", timeout); } /** * Set up HDFS to run securely. * In secure mode, HDFS goes out of its way to refuse to start if it * doesn't consider the configuration safe. * This is good in production, and it stops an HDFS cluster coming * up where things can't reliably talk to each other. * But it does complicate test setup. * Look at {@code org.apache.hadoop.hdfs.TestDFSInotifyEventInputStreamKerberized} * and {@code org.apache.hadoop.hdfs.qjournal.TestSecureNNWithQJM} * for the details on what options to set here. * @param conf configuration to patch. */ protected void patchConfigWithHDFSBindings(final Configuration conf) { Preconditions.checkState(isInState(STATE.STARTED)); enableKerberos(conf); String path = getKeytabPath(); String spnegoPrincipal = "*"; String localhost = LOCALHOST_NAME; String instance = getKrbInstance(); String hdfsPrincipal = getLoginPrincipal(); patchConfigAtInit(conf); conf.setLong(CommonConfigurationKeys.FS_DU_INTERVAL_KEY, Long.MAX_VALUE); conf.set(DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY, hdfsPrincipal); conf.set(DFS_NAMENODE_KEYTAB_FILE_KEY, path); conf.set(DFS_DATANODE_KERBEROS_PRINCIPAL_KEY, hdfsPrincipal); conf.set(DFS_DATANODE_KEYTAB_FILE_KEY, path); conf.set(DFS_WEB_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY, spnegoPrincipal); conf.set(DFS_JOURNALNODE_KEYTAB_FILE_KEY, path); conf.set(DFS_JOURNALNODE_KERBEROS_PRINCIPAL_KEY, hdfsPrincipal); conf.set(DFS_JOURNALNODE_KERBEROS_INTERNAL_SPNEGO_PRINCIPAL_KEY, spnegoPrincipal); conf.setBoolean(DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY, true); conf.set(DFS_DATA_TRANSFER_PROTECTION_KEY, "authentication"); conf.set(DFS_HTTP_POLICY_KEY, HttpConfig.Policy.HTTPS_ONLY.name()); conf.set(DFS_NAMENODE_HTTPS_ADDRESS_KEY, "localhost:0"); conf.set(DFS_DATANODE_HTTPS_ADDRESS_KEY, "localhost:0"); conf.set(DFS_HTTP_POLICY_KEY, HttpConfig.Policy.HTTPS_ONLY.name()); conf.set(DFS_CLIENT_HTTPS_KEYSTORE_RESOURCE_KEY, KeyStoreTestUtil.getClientSSLConfigFileName()); conf.set(DFS_SERVER_HTTPS_KEYSTORE_RESOURCE_KEY, KeyStoreTestUtil.getServerSSLConfigFileName()); } /** * Patch the YARN settings. * Note how the yarn principal has to include the realm. * @param conf configuration to patch. */ protected void patchConfigWithYARNBindings(final Configuration conf) { Preconditions.checkState(isInState(STATE.STARTED)); enableKerberos(conf); patchConfigAtInit(conf); String path = getKeytabPath(); String localhost = LOCALHOST_NAME; String yarnPrincipal = withRealm(getLoginPrincipal()); conf.set(RM_PRINCIPAL, yarnPrincipal); conf.set(RM_KEYTAB, path); conf.set(RM_HOSTNAME, localhost); conf.set(RM_BIND_HOST, localhost); conf.set(RM_ADDRESS, localhost + ":" + DEFAULT_RM_PORT); conf.set(NM_PRINCIPAL, yarnPrincipal); conf.set(NM_KEYTAB, path); conf.set(NM_ADDRESS, localhost + ":" + DEFAULT_NM_PORT); conf.setBoolean(TIMELINE_SERVICE_ENABLED, false); conf.setBoolean(MRJobConfig.MAPREDUCE_JOB_EMIT_TIMELINE_DATA, false); conf.set(JHAdminConfig.MR_HISTORY_KEYTAB, path); conf.set(JHAdminConfig.MR_HISTORY_PRINCIPAL, yarnPrincipal); conf.set(JHAdminConfig.MR_HISTORY_ADDRESS, localhost + ":" + DEFAULT_MR_HISTORY_PORT); conf.setBoolean(JHAdminConfig.MR_HISTORY_CLEANER_ENABLE, false); conf.setInt(RM_AM_MAX_ATTEMPTS, 1); conf.setInt(YarnConfiguration.RESOURCEMANAGER_CONNECT_MAX_WAIT_MS, 100); conf.setInt(YarnConfiguration.RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_MS, 10_000); } public void resetUGI() { UserGroupInformation.reset(); } /** * Given a shortname, built a long name with the krb instance and realm info. * @param shortname short name of the user * @return a long name */ private String userOnHost(final String shortname) { return shortname + "/" + krbInstance + "@" + getRealm(); } public String getRealm() { return kdc.getRealm(); } /** * Log in a user to UGI.currentUser. * @param user user to log in from * @throws IOException failure */ public void loginUser(final String user) throws IOException { UserGroupInformation.loginUserFromKeytab(user, getKeytabPath()); } /** * Log in the login principal as the current user. * @throws IOException failure */ public void loginPrincipal() throws IOException { loginUser(getLoginPrincipal()); } /** * General assertion that security is turred on for a cluster. */ public static void assertSecurityEnabled() { assertTrue("Security is needed for this test", UserGroupInformation.isSecurityEnabled()); } /** * Close filesystems for a user, downgrading a null user to a no-op. * @param ugi user * @throws IOException if a close operation raised one. */ public static void closeUserFileSystems(UserGroupInformation ugi) throws IOException { if (ugi != null) { FileSystem.closeAllForUGI(ugi); } } /** * Modify a configuration to use Kerberos as the auth method. * @param conf configuration to patch. */ public static void enableKerberos(Configuration conf) { conf.set(HADOOP_SECURITY_AUTHENTICATION, UserGroupInformation.AuthenticationMethod.KERBEROS.name()); } }
0lru/p3ui
cpp/p3/source/p3/widgets/InputText.h
#pragma once #include <string> #include <functional> #include <p3/Node.h> struct ImGuiInputTextCallbackData; namespace p3 { class InputText : public Node { public: using OnChange = std::function<void()>; InputText(std::size_t size=1024, std::optional<std::string> label=std::optional<std::string>()); StyleStrategy& style_strategy() const override; void render_impl(Context&, float width, float height) override; void set_hint(std::optional<std::string>); std::optional<std::string> const& hint(std::string) const; void set_on_change(OnChange); OnChange on_change() const; void update_content() override; void set_value(std::string); std::string const& value() const; protected: void dispose() override; private: std::string _value; std::size_t _size; std::optional<std::string> _hint; OnChange _on_change; static int Callback(ImGuiInputTextCallbackData* data); }; }
h1psterx/core
packages/crypto/__tests__/crypto/crypto.test.js
<reponame>h1psterx/core const crypto = require('../../lib/crypto/crypto') const configManager = require('../../lib/managers/config') const { TRANSACTION_TYPES, CONFIGURATIONS } = require('../../lib/constants') beforeEach(() => configManager.setConfig(CONFIGURATIONS.ARK.DEVNET)) describe('crypto.js', () => { describe('getBytes', () => { let bytes = null it('should be a function', () => { expect(crypto.getBytes).toBeFunction() }) // it('should return Buffer of simply transaction and buffer must be 292 length', () => { // const transaction = { // type: 0, // amount: 1000, // fee: 2000, // recipientId: 'AJWRd23HNEhPLkK1ymMnwnDBX2a7QBZqff', // timestamp: 141738, // asset: {}, // senderPublicKey: '<KEY>', // signature: '618a54975212ead93df8c881655c625544bce8ed7ccdfe6f08a42eecfb1adebd051307be5014bb051617baf7815d50f62129e70918190361e5d4dd4796541b0a' // eslint-disable-line max-len // } // bytes = crypto.getBytes(transaction) // expect(bytes).toBeObject() // expect(bytes.toString('hex') + transaction.signature).toHaveLength(292) // }) it('should return Buffer of simply transaction and buffer must be 202 length', () => { const transaction = { type: 0, amount: 1000, fee: 2000, recipientId: 'AJWRd23HNEhPLkK1ymMnwnDBX2a7QBZqff', timestamp: 141738, asset: {}, senderPublicKey: '<KEY>', signature: '618a54975212ead93df8c881655c625544bce8ed7ccdfe6f08a42eecfb1adebd051307be5014bb051617baf7815d50f62129e70918190361e5d4dd4796541b0a', // eslint-disable-line max-len id: '13987348420913138422' } bytes = crypto.getBytes(transaction) expect(bytes).toBeObject() expect(bytes.length).toBe(202) expect(bytes.toString('hex')).toBe('00aa2902005d036a858ce89f844491762eb89e2bfbd50a4a0a0da658e4b2628b25b117ae09171dfc69b54c7fe901e91d5a9ab78388645e2427ea00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e803000000000000d007000000000000618a54975212ead93df8c881655c625544bce8ed7ccdfe6f08a42eecfb1adebd051307be5014bb051617baf7815d50f62129e70918190361e5d4dd4796541b0a') }) // it('should return Buffer of transaction with second signature and buffer must be 420 length', () => { // const transaction = { // type: 0, // amount: 1000, // fee: 2000, // recipientId: 'AJWRd23HNEhPLkK1ymMnwnDBX2a7QBZqff', // timestamp: 141738, // asset: {}, // senderPublicKey: '<KEY>', // signature: '618a54975212ead93df8c881655c625544bce8ed7ccdfe6f08a42eecfb1adebd051307be5014bb051617baf7815d50f62129e70918190361e5d4dd4796541b0a', // eslint-disable-line max-len // signSignature: '618a54975212ead93df8c881655c625544bce8ed7ccdfe6f08a42eecfb1adebd051307be5014bb051617baf7815d50f62129e70918190361e5d4dd4796541b0a' // eslint-disable-line max-len // } // bytes = crypto.getBytes(transaction) // expect(bytes).toBeObject() // expect(bytes.toString('hex') + transaction.signature + transaction.signSignature).toHaveLength(420) // }) it('should return Buffer of transaction with second signature and buffer must be 266 length', () => { const transaction = { version: 1, type: 0, amount: 1000, fee: 2000, recipientId: 'AJWRd23HNEhPLkK1ymMnwnDBX2a7QBZqff', timestamp: 141738, asset: {}, senderPublicKey: '<KEY>', signature: '618a54975212ead93df8c881655c625544bce8ed7ccdfe6f08a42eecfb1adebd051307be5014bb051617baf7815d50f62129e70918190361e5d4dd4796541b0a', // eslint-disable-line max-len signSignature: '618a54975212ead93df8c881655c625544bce8ed7ccdfe6f08a42eecfb1adebd051307be5014bb051617baf7815d50f62129e70918190361e5d4dd4796541b0a', // eslint-disable-line max-len id: '13987348420913138422' } bytes = crypto.getBytes(transaction) expect(bytes).toBeObject() expect(bytes.length).toBe(266) expect(bytes.toString('hex')).toBe('00aa2902005d036a858ce89f844491762eb89e2bfbd50a4a0a0da658e4b2628b25b117ae09171dfc69b54c7fe901e91d5a9ab78388645e2427ea00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e803000000000000d007000000000000618a54975212ead93df8c881655c625544bce8ed7ccdfe6f08a42eecfb1adebd051307be5014bb051617baf7815d50f62129e70918190361e5d4dd4796541b0a618a54975212ead93df8c881655c625544bce8ed7ccdfe6f08a42eecfb1adebd051307be5014bb051617baf7815d50f62129e70918190361e5d4dd4796541b0a'); }) }) describe('getHash', () => { it('should be a function', () => { expect(crypto.getHash).toBeFunction() }) it('should return Buffer and Buffer most be 32 bytes length', () => { const transaction = { version: 1, type: 0, amount: 1000, fee: 2000, recipientId: 'AJWRd23HNEhPLkK1ymMnwnDBX2a7QBZqff', timestamp: 141738, asset: {}, senderPublicKey: '<KEY>', signature: '618a54975212ead93df8c881655c625544bce8ed7ccdfe6f08a42eecfb1adebd051307be5014bb051617baf7815d50f62129e70918190361e5d4dd4796541b0a' // eslint-disable-line max-len } const result = crypto.getHash(transaction) expect(result).toBeObject() expect(result).toHaveLength(32) expect(result.toString('hex')).toBe('952e33b66c35a3805015657c008e73a0dee1efefd9af8c41adb59fe79745ccea') }) }) describe('getId', () => { it('should be a function', () => { expect(crypto.getId).toBeFunction() }) it('should return string id and be equal to 952e33b66c35a3805015657c008e73a0dee1efefd9af8c41adb59fe79745ccea', () => { const transaction = { type: 0, amount: 1000, fee: 2000, recipientId: 'AJWRd23HNEhPLkK1ymMnwnDBX2a7QBZqff', timestamp: 141738, asset: {}, senderPublicKey: '<KEY>', signature: '618a54975212ead93df8c881655c625544bce8ed7ccdfe6f08a42eecfb1adebd051307be5014bb051617baf7815d50f62129e70918190361e5d4dd4796541b0a' // eslint-disable-line max-len } const id = crypto.getId(transaction) // old id expect(id).toBeString() expect(id).toBe('952e33b66c35a3805015657c008e73a0dee1efefd9af8c41adb59fe79745ccea') }) }) describe('getFee', () => { it('should be a function', () => { expect(crypto.getFee).toBeFunction() }) it('should return 10000000', () => { const fee = crypto.getFee({ type: TRANSACTION_TYPES.TRANSFER }) expect(fee).toBeNumber() expect(fee).toBe(10000000) }) }) describe('sign', () => { it('should be a function', () => { expect(crypto.sign).toBeFunction() }) it('should return a valid signature', () => { const keys = crypto.getKeys('secret') const transaction = { type: 0, amount: 1000, fee: 2000, recipientId: 'AJWRd23HNEhPLkK1ymMnwnDBX2a7QBZqff', timestamp: 141738, asset: {}, senderPublicKey: keys.publicKey } const signature = crypto.sign(transaction, keys) expect(signature.toString('hex')).toBe('3045022100f5c4ec7b3f9a2cb2e785166c7ae185abbff0aa741cbdfe322cf03b914002efee02206261cd419ea9074b5d4a007f1e2fffe17a38338358f2ac5fcc65d810dbe773fe') }) }) describe('secondSign', () => { it('should be a function', () => { expect(crypto.secondSign).toBeFunction() }) }) describe('getKeys', () => { it('should be a function', () => { expect(crypto.getKeys).toBeFunction() }) it('should return two keys in hex', () => { const keys = crypto.getKeys('secret') expect(keys).toBeObject() expect(keys).toHaveProperty('publicKey') expect(keys).toHaveProperty('privateKey') expect(keys.publicKey).toBeString() expect(keys.publicKey).toMatch(Buffer.from(keys.publicKey, 'hex').toString('hex')) expect(keys.privateKey).toBeString() expect(keys.privateKey).toMatch(Buffer.from(keys.privateKey, 'hex').toString('hex')) }) it('should return address', () => { const keys = crypto.getKeys('SDgGxWHHQHnpm5sth7MBUoeSw7V7nbimJ1RBU587xkryTh4qe9ov') const address = crypto.getAddress(keys.publicKey.toString('hex')) expect(address).toBe('DUMjDrT8mgqGLWZtkCqzvy7yxWr55mBEub') }) }) describe('getKeysFromWIF', () => { it('should be a function', () => { expect(crypto.getKeysFromWIF).toBeFunction() }) it('should return two keys in hex', () => { const keys = crypto.getKeysFromWIF('<KEY>') expect(keys).toBeObject() expect(keys).toHaveProperty('publicKey') expect(keys).toHaveProperty('privateKey') expect(keys.publicKey).toBeString() expect(keys.publicKey).toMatch(Buffer.from(keys.publicKey, 'hex').toString('hex')) expect(keys.privateKey).toBeString() expect(keys.privateKey).toMatch(Buffer.from(keys.privateKey, 'hex').toString('hex')) }) it('should return address', () => { const keys = crypto.getKeysFromWIF('<KEY>') const address = crypto.getAddress(keys.publicKey.toString('hex')) expect(address).toBe('DCAaPzPAhhsMkHfQs7fZvXFW2EskDi92m8') }) it('should get keys from compressed WIF', () => { const keys = crypto.getKeysFromWIF('<KEY>') expect(keys).toBeObject() expect(keys).toHaveProperty('publicKey') expect(keys).toHaveProperty('privateKey') expect(keys).toHaveProperty('compressed', true) }) it('should get keys from uncompressed WIF', () => { const keys = crypto.getKeysFromWIF('<KEY>') expect(keys).toBeObject() expect(keys).toHaveProperty('publicKey') expect(keys).toHaveProperty('privateKey') expect(keys).toHaveProperty('compressed', false) }) }) describe('keysToWIF', () => { it('should be a function', () => { expect(crypto.keysToWIF).toBeFunction() }) it('should get keys from WIF', () => { const wifKey = '<KEY>' const keys = crypto.getKeysFromWIF(wifKey) const actual = crypto.keysToWIF(keys) expect(keys.compressed).toBeTruthy() expect(actual).toBe(wifKey) }) it('should get address from compressed WIF (mainnet)', () => { const keys = crypto.getKeysFromWIF('<KEY>', CONFIGURATIONS.ARK.MAINNET) const address = crypto.getAddress(keys.publicKey, CONFIGURATIONS.ARK.MAINNET.pubKeyHash) expect(keys.compressed).toBeTruthy() expect(address).toBe('APnrtb2JGa6WjrRik9W3Hjt6h71mD6Zgez') }) it('should get address from compressed WIF (devnet)', () => { const keys = crypto.getKeysFromWIF('<KEY>', CONFIGURATIONS.ARK.DEVNET) const address = crypto.getAddress(keys.publicKey, CONFIGURATIONS.ARK.DEVNET.pubKeyHash) expect(keys.compressed).toBeTruthy() expect(address).toBe('DDA5nM7KEqLeTtQKv5qGgcnc6dpNBKJNTS') }) }) describe('getAddress', () => { it('should be a function', () => { expect(crypto.getAddress).toBeFunction() }) it('should generate address by publicKey', () => { const keys = crypto.getKeys('secret') const address = crypto.getAddress(keys.publicKey) expect(address).toBeString() expect(address).toBe('D7seWn8JLVwX4nHd9hh2Lf7gvZNiRJ7qLk') }) it('should generate address by publicKey - second test', () => { const keys = crypto.getKeys('secret second test to be sure it works correctly') const address = crypto.getAddress(keys.publicKey) expect(address).toBeString() expect(address).toBe('DDp4SYpnuzFPuN4W79PYY762d7FtW3DFFN') }) it('should not throw an error if the publicKey is valid', () => { try { const validKeys = ['<KEY>', 'a'.repeat(66)] for (const validKey of validKeys) { crypto.getAddress(validKey) } } catch (error) { expect().fail('Should not have failed to call getAddress with a valid publicKey') } }) it('should throw an error if the publicKey is invalid', () => { const invalidKeys = ['invalid', 'a'.repeat(65), 'a'.repeat(67), 'z'.repeat(66)] for (const invalidKey of invalidKeys) { expect(() => crypto.getAddress(invalidKey)).toThrowError(new Error(`publicKey '${invalidKey}' is invalid`)) } }) }) describe('verify', () => { it('should be a function', () => { expect(crypto.verify).toBeFunction() }) }) describe('verifySecondSignature', () => { it('should be a function', () => { expect(crypto.verifySecondSignature).toBeFunction() }) }) describe('validate address on different networks', () => { it('should validate MAINNET addresses', () => { configManager.setConfig(CONFIGURATIONS.ARK.MAINNET) expect(crypto.validateAddress('AdVSe37niA3uFUPgCgMUH2tMsHF4LpLoiX')).toBeTrue() }) it('should validate DEVNET addresses', () => { configManager.setConfig(CONFIGURATIONS.ARK.DEVNET) expect(crypto.validateAddress('DARiJqhogp2Lu6bxufUFQQMuMyZbxjCydN')).toBeTrue() }) }) })
goodow/realtime-channel
src/main/java/com/google/gwt/core/client/js/JsType.java
<reponame>goodow/realtime-channel /* * Copyright 2013 Google 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. */ package com.google.gwt.core.client.js; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * JsType is used to describe the interface of a Javascript object, either one that already * exists from the external Javascript environment, or one that will be accessible to the * external Javascript environment. Calls to methods on interfaces marked with this annotation * are treated specially by the GWT compiler for interoperability purposes. Such methods need * not be backed by an Overlay type implementation, the GWT compiler will assume that a JS method on * the prototype of the underlying reference will match the name of the method on this interface. * <p> * Furthermore, if the JsType is marked with a prototype reference, then concrete * implementations of the class emitted by the GWT compiler will use the specified prototype as * opposed the the ordinary one (e.g. java.lang.Object). * <p> * JsTypes act like JavaScriptObject in terms of castability, except when a prototype is * specified, in which case, cast checks and instanceof checks will be delegated to the native * JS instanceof operator. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented public @interface JsType { String prototype() default ""; boolean isNative() default false; }
kbens/rundeck
core/src/main/java/com/dtolabs/rundeck/plugins/scm/JobRenamed.java
package com.dtolabs.rundeck.plugins.scm; /** * Get source and UUID form a renamed Job */ public interface JobRenamed { /** * get the job the UUID * * @return uuid */ String getUuid(); /** * get the job the SourceID * * @return sourceID */ String getSourceId(); /** * get the job the renamed path * * @return renamedPath */ String getRenamedPath(); }
BerkeleyLibrary/geodata_pre_ingest
pre_ingestion/v_tool_2_1_get_ISO191390.py
<gh_stars>0 #!/usr/bin/python import os import sys from csv_iso_collection import CsvIsoCollection from csv_tranform import CsvTransform from validate_csv import ValidateCSV from geo_helper import GeoHelper # 1. Source: updated csv files - modified metadata # 2. output to two places: a) ISO19139 directory, b) source data directory def main(): try: process_path = sys.argv[1] valid_updated_csv = ValidateCSV(process_path) if valid_updated_csv.updated_csv_files_existed(): if valid_updated_csv.updated_csv_files_valid(): updated_csv_files = GeoHelper.dest_csv_files_updated(process_path) csv_collection = CsvIsoCollection(updated_csv_files).csv_collection() csvtransform = CsvTransform(csv_collection,process_path) csvtransform.transform_iso19139() output_iso19139_dir = GeoHelper.iso19139_path(process_path) arcpy.RefreshCatalog(output_iso19139_dir) except Exception, e: txt = "Code exception: {0} ; {1}".format(__file__,str(e)) GeoHelper.arcgis_message(txt) if __name__ == '__main__': main()
c0debrain/flat
app/src/views/containers/SignIn/StartScreen/index.js
<filename>app/src/views/containers/SignIn/StartScreen/index.js import React, { Component } from "react"; import Dimensions from 'Dimensions'; import Platform from 'Platform'; import { connect } from 'react-redux'; import { ImageBackground, View, StatusBar } from "react-native"; import { Container, Button, H3, Text } from "native-base"; import { l10n } from "../../../../lib/lang" import BaseComponent from "../../BaseContainer"; const deviceHeight = Dimensions.get("window").height; const styles = { imageContainer: { flex: 1, width: null, height: null }, logoContainer: { flex: 1, marginTop: deviceHeight / 8, alignItems: 'center' }, logo: { width: 280, height: 124 }, text: { color: "#fff", bottom: 6, marginTop: 5 } }; const launchscreenBg = require("../../../images/bg.png"); const launchscreenLogo = require("../../../images/logo.png"); class Home extends BaseComponent { render() { return ( <Container> <StatusBar barStyle="light-content" /> <ImageBackground source={launchscreenBg} style={styles.imageContainer}> <View style={styles.logoContainer}> <ImageBackground source={launchscreenLogo} style={styles.logo} /> </View> <View style={{ alignItems: "center", marginBottom: 50, backgroundColor: "transparent" }} > <H3 style={styles.text}>{l10n("Welcome to Flat Messenger")}</H3> <View style={{ marginTop: 8 }} /> <H3 style={styles.text}>{l10n("Tap the button to signup")}</H3> <View style={{ marginTop: 8 }} /> </View> <View style={{ marginBottom: 80 }}> <Button style={{ backgroundColor: "#444", alignSelf: "center" }} onPress={() => this.props.navigation.navigate("SendNumber")} > <Text>{l10n("Lets Go!")}</Text> </Button> </View> </ImageBackground> </Container> ); } } const mapStateToProps = state => ({ ...BaseComponent.defaltProps(state) }) const mapDispatchToProps = (dispatch) => ({ }) export default connect(mapStateToProps, mapDispatchToProps)(Home)
feesa/easyrec-parent
easyrec-web/src/main/java/org/easyrec/store/dao/web/impl/BackTrackingDAOMysqlImpl.java
<filename>easyrec-web/src/main/java/org/easyrec/store/dao/web/impl/BackTrackingDAOMysqlImpl.java package org.easyrec.store.dao.web.impl; import org.easyrec.store.dao.web.BackTrackingDAO; import org.springframework.jdbc.core.PreparedStatementCreatorFactory; import org.springframework.jdbc.core.support.JdbcDaoSupport; import javax.sql.DataSource; import java.sql.Types; /** * The Class implements the BacktrackingDAO * <p/> * <p> * <b>Company:&nbsp;</b> SAT, Research Studios Austria * </p> * <p/> * <p> * <b>Copyright:&nbsp;</b> (c) 2007 * <p/> * <b>last modified:</b><br/> $Author: phlavac $<br/> $Date: 2008-07-17 * 20:00:46 +0200 (Do, 17 Jul 2008) $<br/> $Revision: 15249 $ * </p> * * @author phlavac */ public class BackTrackingDAOMysqlImpl extends JdbcDaoSupport implements BackTrackingDAO { private static final String SQL_ADD_ITEM; private static final String SQL_COUNT_ITEM; private static final int[] ARGTYPES_ADD_ITEM; private static final PreparedStatementCreatorFactory PS_ADD_ITEM; static { SQL_ADD_ITEM = new StringBuilder().append(" INSERT INTO backtracking ") .append("(userId, tenantId, itemFromId, itemFromTypeId, itemToId, itemToTypeId, recType) VALUES ") .append("(?,?,?,?,?,?,?) ").toString(); SQL_COUNT_ITEM = new StringBuilder().append(" SELECT count(1) FROM backtracking WHERE") .append(" tenantId = ? AND itemFromId = ? AND itemFromTypeId = ? AND recType = ? AND itemToId = ? and itemToTypeId = ?").toString(); ARGTYPES_ADD_ITEM = new int[]{Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER}; PS_ADD_ITEM = new PreparedStatementCreatorFactory(SQL_ADD_ITEM, ARGTYPES_ADD_ITEM); PS_ADD_ITEM.setReturnGeneratedKeys(true); } public BackTrackingDAOMysqlImpl() {} public BackTrackingDAOMysqlImpl(DataSource dataSource) { setDataSource(dataSource); } /* * (non-Javadoc) * * @see at.researchstudio.sat.recommender.remote.store.dao.ItemDAO#saveItem(java.lang.String, * java.lang.String, int, java.lang.String) */ @Override public void track(Integer userId, Integer tenantId, Integer itemFromId, Integer itemFromType, Integer itemToId, Integer itemToType, Integer recType) { Object[] args = {userId, tenantId, itemFromId, itemFromType, itemToId, itemToType, recType}; try { getJdbcTemplate().update(PS_ADD_ITEM.newPreparedStatementCreator(args)); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug(e); } } } /* * (non-Javadoc) * * @see at.researchstudio.sat.recommender.remote.store.dao.ItemDAO#saveItem(java.lang.String, * java.lang.String, int, java.lang.String) */ @Override public Integer getItemCount(Integer tenantId, Integer itemFromId, Integer itemFromTypeId, Integer itemToId, Integer itemToTypeId, Integer recType) { try { return getJdbcTemplate() .queryForInt(SQL_COUNT_ITEM, new Object[]{tenantId, itemFromId, itemFromTypeId, recType, itemToId, itemToTypeId}, new int[]{Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER}); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug(e); } } return null; } /** * Clear tenant specific backtracking data. * * @param tenantId */ @Override public void clear(Integer tenantId) { try { getJdbcTemplate().update("DELETE FROM backtracking WHERE tenantId = ?", new Object[]{tenantId}); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug(e); } } } }
diCagri/content
Packs/PaloAltoNetworks_IoT/Scripts/iot_get_raci/iot_get_raci.py
<gh_stars>100-1000 import json import re import demistomock as demisto from CommonServerPython import * # noqa: E402 lgtm [py/polluting-import] from CommonServerUserPython import * # noqa: E402 lgtm [py/polluting-import] def get_iot_config(iot_config_list_name="IOT_CONFIG"): iot_config = demisto.executeCommand("getList", {"listName": iot_config_list_name}) if is_error(iot_config): return None iot_config_content = iot_config[0]['Contents'] try: return json.loads(iot_config_content) except Exception as e: return_error(f'Failed to parse the IOT_CONFIG. Error: {str(e)}') def get_raci(args): alert_name = args.get('alert_name', '') alert_type = args.get('raw_type') category = args.get('category', '') profile = args.get('profile', '') vendor = args.get('vendor', '') model = args.get('model', '') device_id = f'{category}|{profile}|{vendor}|{model}' iot_config_list_name = args.get('iot_config_list_name', 'IOT_CONFIG') config = get_iot_config(iot_config_list_name) if config is None: return None result = {} # determine owner owner = None for d in config.get('devices', []): if 'device_id' in d and 'owner' in d and re.match(d['device_id'], device_id): owner = d['owner'] result['owner'] = owner # determine raci raci = None for a in config.get('alerts', []): if 'iot_raw_type' in a and 'raci' in a and alert_type == a['iot_raw_type']: match_name = 'name_regex' not in a if not match_name: for n in a['name_regex']: if re.match(n, alert_name): match_name = True break if match_name: raci = a['raci'] if raci: r = raci['r'] if r == "IOT_OWNER": result['r'] = owner if owner is None: result['r_email'] = None result['r_snow'] = None else: e = config.get('groups', {}).get(owner, {}).get('email', None) if e is None: default_email = config.get('groups', {}).get('DEFAULT', {}).get('email', None) if default_email is not None: result['r_email'] = default_email else: result['r_email'] = None else: result['r_email'] = e result['r_snow'] = config.get('groups', {}).get(owner, {}).get('snow', None) elif r is not None: result['r'] = r e = config.get('groups', {}).get(r, {}).get('email', None) if e is None: default_email = config.get('groups', {}).get('DEFAULT', {}).get('email', None) if default_email is not None: result['r_email'] = default_email else: result['r_email'] = None else: result['r_email'] = e result['r_snow'] = config.get('groups', {}).get(r, {}).get('snow', None) else: result['r_email'] = None result['r_snow'] = None r_snow = result.get('r_snow', {}) if r_snow: fields = r_snow.get('fields', {}) if fields: r_snow['fields'] = ';'.join([f'{k}={v}' for k, v in fields.items()]) cfields = r_snow.get('custom_fields', {}) if cfields: r_snow['custom_fields'] = ';'.join([f'{k}={v}' for k, v in cfields.items()]) i = [] for inform in raci['i']: if inform == "IOT_OWNER": if owner is not None: i.append(owner) else: i.append(inform) result['i'] = ', '.join(i) if i else None if i: i_email = [] for entry in i: e = config.get('groups', {}).get(entry, {}).get('email', None) if e is None: default_email = config.get('groups', {}).get('DEFAULT', {}).get('email', None) if default_email is not None: i_email.append(default_email) else: i_email.append(e) if len(i_email) > 0: result['i_email'] = ', '.join(i_email) else: result['i_email'] = None else: result['r'] = None result['r_email'] = None result['r_snow'] = None result['i'] = None result['i_email'] = None return CommandResults( outputs_prefix='PaloAltoNetworksIoT.RACI', outputs_key_field="", outputs=result ) def main(): try: return_results(get_raci(demisto.args())) except Exception as ex: return_error(f'Failed to execute iot-security-get-raci. Error: {str(ex)}') if __name__ in ('__main__', '__builtin__', 'builtins'): main()
Fogolan/MongoDB-Stitch
containers/Notes.js
/** * Copyright 2015-present, Lights in the Sky (3273741 NS Ltd.) * All rights reserved. * * This source code is licensed under the license found in the * LICENSE file in the root directory of this source tree. * * @providesModule Notes */ import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link, browserHistory } from 'react-router'; import LineChart from '../components/charts/LineChart'; import { selectApp, logout } from '../actions'; import moment from 'moment'; import ReduxOutlet from '../outlets/ReduxOutlet'; import LocalReduxOutlet from '../outlets/LocalReduxOutlet'; import ModalFactory from '../components/modals/factory'; import AddNote from '../components/modals/AddNote'; import {Row, Col, Page} from '../components/ui/Layout'; let Factory = ModalFactory.modalFromFactory; let noteActions = LocalReduxOutlet('note', '576a87c1e0b944000054d234').actions; var shallowCompare = require('react-addons-shallow-compare'); class Notes extends Component { componentDidMount() { const { dispatch, app, apps, token } = this.props; dispatch(noteActions.fetch(token, {})); } shouldComponentUpdate(nextProps, nextState) { return shallowCompare(this, nextProps, nextState); } handleNewNote(name,description) { let {dispatch, app, user, token} = this.props; dispatch(noteActions.create(token, { _id: '4m4km34k3m43k4m3', name: name, description: description, app: '343k34jk34j34k3j43k4', dateCreated : Date.now(), dateUpdated : Date.now(), excerpt : 'New Note', author : {_id : user._id, name:user.name, avatar:user.avatar} })); ModalFactory.hide('addnoteModal'); } newNoteClick(e) { e.preventDefault(); ModalFactory.show('addnoteModal'); } deleteItem(id) { let {token, user, dispatch, params} = this.props; dispatch(noteActions.delete(token, {_id:id})); } render() { const { dispatch, notes } = this.props; let i = 0; return ( <Page height={900}> <Factory modalref="addnoteModal" title="Add Note" factory={AddNote} onCreate={(name,desc) => this.handleNewNote(name,desc)} /> <Row> <div className="pull-right w50 text-right m-r-lg"> <button className="btn btn-dark" onClick={(e)=>this.newNoteClick(e)}> <i className="fa fa-plus-square"></i> <span className="btn-text">New Note</span> </button> </div> </Row> <Row> {notes.list.map(note => { return <NoteItem key={i} index={i++} onDelete={(id)=>this.deleteItem(id)} onSelect={(index) => this.selectItem(index)} note={note} /> })} </Row> </Page> ); } } class NoteItem extends Component { onDelete(e) { let {note} = this.props; e.preventDefault(); this.props.onDelete(note._id); } render() { let {note, index} = this.props; return ( <div className="col-md-4 col-sm-6"> <section className="panel panel-default m-b-lg"> <header className="panel-heading text-uc">{note.name}<strong> {note.description}</strong> <button onClick={(e)=>this.onDelete(e)} style={{top: 9,right: 27, position: 'absolute'}} type="button" className="text-muted close">×</button> <hr /> </header> <Link to={`/apps/notes/${note._id}`}> <section className="panel-body" style={{paddingLeft:10}}>{note.excerpt}</section> </Link> <footer className="panel-footer"> <span className="thumb-sm avatar pull-left m-r-xs"> <img src={note.author.avatar ? note.author.avatar : ''} /> </span> <strong className="d-b">{note.author.name}</strong> <span className="text-muted text-xs">{moment(note.dateCreated).fromNow()}</span> </footer> </section> </div> ); } } function mapStateToProps(state) { return { token: state.app.token, user: state.user, app:state.app, notes: state.notes }; } export default connect(mapStateToProps)(Notes);
stardot/ncc
mip/inline.c
/* * inline.c: inline function expansion * Copyright (C) Advanced Risc Machines Ltd., 1993 * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ /* Nasties to tidy up: ** (1) the use of h0_(Binder) ** (2) lab_xname_()/lab_name_(). Use small ints everywhere for labelnumbers? */ #include <string.h> #include <stddef.h> /* offsetof */ #include "globals.h" #include "store.h" #include "flowgraf.h" #include "codebuf.h" #include "regalloc.h" #include "aeops.h" #include "aetree.h" #include "bind.h" #include "jopcode.h" #include "inline.h" #include "cg.h" #include "regsets.h" #include "simplify.h" #include "errors.h" #include "builtin.h" #include "sem.h" #include "dump.h" #include "mcdep.h" typedef struct SavedFnList SavedFnList; typedef union { RegSort rs; VRegnum r; } Inline_VRegIndex; typedef struct { Inline_ArgBinderList abl; int flags; uint8 accesssize, /* a MEM_xx value or MEM_NONE */ accessmap; int32 mink, maxk; Inline_ArgSubstList *argsubst; } Inline_ArgDesc; #define argdesc_(p) (*(Inline_ArgDesc **)&(p)->fn.args) #define adcdr_(p) (*(Inline_ArgDesc **)&cdr_(&(p)->abl)) #define IA_Updated 1 #define IA_OddAccess 2 #define IA_AccessSet 4 #define IA_UpdatedOutsideCore 8 #define IA_OddUseForPlusInCore 16 typedef uint8 BlockMap; typedef enum { IS_Ord, IS_Ctor, IS_Dtor } Inline_Sort; struct SavedFnList { SavedFnList *cdr; Inline_SavedFn fn; int32 maxlabel; VRegnum maxreg; Inline_VRegIndex *vregtypetab; Inline_Sort sort; union { BlockMap *ctor; BlockHead *dtor; } a; uint8 outoflineflags; }; #define ol_used 1 #define ol_emitted 2 typedef struct BindListIndex BindListIndex; struct BindListIndex { BindListIndex *cdr; BindList *orig; BindList *copy; }; typedef struct SymTrans SymTrans; struct SymTrans { SymTrans *cdr; Symstr *oldsym; Symstr *newsym; }; typedef struct { SynBindList *copied; BindListIndex *sharedbindlists; Inline_VRegIndex *vregindex; BindList *nullenv; SymTrans *symtrans; } SaveFnState; static SavedFnList *saved_fns; Inline_SavedFn *Inline_FindFn(Binder *b) { SavedFnList *fn = (SavedFnList *)bindinline_(b); if (fn != NULL) return &fn->fn; return NULL; } void Inline_RealUse(Binder *b) { SavedFnList *fn = (SavedFnList *)bindinline_(b); attributes_(b) |= A_REALUSE; if (fn != NULL) fn->outoflineflags |= ol_used; } static BindList *GlobalSharedBindListCopy(SaveFnState *st, BindList *bl); static Binder *GlobalBinderCopy(SaveFnState *st, Binder *b) { if (h0_(b) != s_binder) return (Binder *)(IPtr)h0_(b); { Symstr *sym = bindsym_(b); Binder *bnew; size_t n; if (bindstg_(b) & (bitofstg_(s_virtual)|b_globalregvar|bitofstg_(s_auto))) n = sizeof(Binder); else { if (attributes_(b) & A_GLOBALSTORE) return b; n = SIZEOF_NONAUTO_BINDER; } if (isgensym(sym)) { SymTrans *p = st->symtrans; for (; p != NULL; p = cdr_(p)) if (p->oldsym == sym) break; if (p == NULL) { p = NewSyn(SymTrans); cdr_(p) = st->symtrans; st->symtrans = p; p->oldsym = sym; p->newsym = gensymvalwithname(YES, symname_(sym)); } sym = p->newsym; } bnew = global_mk_binder(NULL, sym, bindstg_(b), bindtype_(b)); memcpy(bnew, b, n); bindsym_(bnew) = sym; h0_(b) = (AEop)(IPtr)bnew; st->copied = mkSynBindList(st->copied, b); if (bindstg_(b) & b_bindaddrlist) bindbl_(bnew) = GlobalSharedBindListCopy(st, bindbl_(b)); return bnew; } } static BindList *GlobalBindListCopy(SaveFnState *st, BindList *bl) { BindList *bl_new = NULL; BindList *bp, **bpp = &bl_new; Binder *prevb = NULL; for (; bl != NULL; bl = bl->bindlistcdr, bpp = &bp->bindlistcdr) { Binder *b = GlobalBinderCopy(st, bl->bindlistcar); if (prevb) bindcdr_(prevb) = b; prevb = b; bp = (BindList *)global_cons2(SU_Inline, NULL, b); *bpp = bp; } return bl_new; } static BindList *GlobalSharedBindListCopy(SaveFnState *st, BindList *bl) { BindListIndex *p = st->sharedbindlists; if (bl == NULL) return NULL; for (; p != NULL; p = cdr_(p)) if (bl == p->orig) return p->copy; { BindList *bl_new = (BindList *)global_cons2(SU_Inline, GlobalSharedBindListCopy(st, bl->bindlistcdr), GlobalBinderCopy(st, bl->bindlistcar)); st->sharedbindlists = (BindListIndex *)syn_list3(st->sharedbindlists, bl, bl_new); return bl_new; } } static Inline_ArgDesc *ArgDesc_Find(Binder *b, Inline_ArgDesc *ad) { for (; ad != NULL; ad = adcdr_(ad)) if (ad->abl.narrowtype != NULL) { if (b == ad->abl.globnarrowarg) break; } else if (b == ad->abl.globarg) break; return ad; } static bool IsSTRWExpansion(Icode *ic, int32 *offset) { /* Already checked that ic->op is STRBK */ Icode *ic2 = ic+1, *ic3 = ic+2; if ((ic2->op & J_TABLE_BITS) == J_SHRK && ic2->r3.i == 8 && ic->r1.r == ic2->r2.r && (ic3->op & J_TABLE_BITS) == J_STRBK && ic3->r2.r == ic->r2.r && ic3->r1.r == ic2->r1.r && (target_lsbytefirst ? ic3->r3.i == ic->r3.i+1 : ic3->r3.i+1 == ic->r3.i)) { *offset = target_lsbytefirst ? ic->r3.i : ic->r3.i-1; return YES; } return NO; } #define MapSize(n) ((size_t)(((n) + 7) / 8)) static BlockMap *NewTempMap(unsigned32 n) { size_t size = MapSize(n); BlockMap *map = NewSynN(BlockMap, size); memset(map, 0, size); return map; } static BlockMap *NewBlockMap(unsigned32 n) { size_t size = MapSize(n); BlockMap *map = NewGlobN(BlockMap, SU_Inline, size); memset(map, 0, size); return map; } static bool MapBitSet(BlockMap *map, unsigned32 n) { BlockMap *p = &map[n / 8]; unsigned bit = 1 << (n % 8); return ((*p & bit) != 0); } static bool SetMapBit(BlockMap *map, unsigned32 n) { BlockMap *p = &map[n / 8]; unsigned bit = 1 << (n % 8); if ((*p & bit) == 0) { *p |= bit; return YES; } else return NO; } static void ClearMapBit(BlockMap *map, unsigned32 n) { BlockMap *p = &map[n / 8]; unsigned bit = 1 << (n % 8); *p &= ~bit; } static void AddToMap(BlockMap *map, LabelNumber *lab) { if (!is_exit_label(lab)) { BlockHead *b = lab->block; if (SetMapBit(map, lab_name_(lab))) { if (blkflags_(b) & BLKSWITCH) { int32 n = blktabsize_(b); LabelNumber **table = blktable_(b); while (--n >= 0) AddToMap(map, table[n]); } else { if (blkflags_(b) & BLK2EXIT) AddToMap(map, blknext1_(b)); AddToMap(map, blknext_(b)); } } } } /* The compiler prepends code to call new() to constructors, and postpends * code to call delete() to destructors. When called for objects which don't * need allocation/deallocation, this gives rise to dead code which latter * phases of compilation are capable of removing, but at a cost (the increased * number of basic blocks slows down both cse and regalloc). Also, the code * to call new() assigns to __this, preventing it from being substituted when * the constructor is inlined, and therefore (perhaps spuriously) leaving the * constructed object marked as address-taken. */ static void FindStructorCore(SavedFnList *p) { BlockHead *b = blkdown_(top_block); BindList *argbl = currentfunction.argbindlist; Binder *arg1 = argbl == NULL ? NULL : argbl->bindlistcar; p->sort = IS_Ord; if ((blkflags_(b) & BLK2EXIT) && blklength_(b) == 2) { Icode *ic1 = blkcode_(b), *ic2 = ic1 + 1; if (ic1->op == J_LDRV+J_ALIGN4 && ic1->r3.b == arg1 && (ic2->op & ~Q_MASK) == J_CMPK && Q_issame((ic2->op & Q_MASK), Q_NE) && ic2->r3.i == 0 && ic2->r2.r == ic1->r1.r) { BlockMap *map = NewBlockMap(p->maxlabel); SetMapBit(map, lab_name_(blklab_(top_block))); AddToMap(map, blknext1_(b)); p->a.ctor = map; p->sort = IS_Ctor; } } else { BlockHead *b2 = blkup_(bottom_block); BlockHead *b1 = blkup_(b2); if (b1 != NULL && !(blkflags_(b2) & (BLK2EXIT+BLKSWITCH)) && blknext_(b2) == blklab_(bottom_block) && (blkflags_(b1) & BLK2EXIT) && Q_issame(blkflags_(b1) & Q_MASK, Q_EQ) && blknext_(b1) == blklab_(b2) && blknext1_(b1) == blklab_(bottom_block) && argbl != NULL && argbl->bindlistcdr != NULL) { Binder *arg2 = argbl->bindlistcdr->bindlistcar; int32 n = blklength_(b1); if (2 <= n) { Icode const *ic = &blkcode_(b1)[n-2]; if ((ic[1].op & ~Q_MASK) == J_CMPK && ic[1].r3.i == 0 && ic[1].r2.r == ic[0].r1.r) { if (3 <= n && ic[-1].op == J_LDRV+J_ALIGN4 && ic[-1].r3.b == arg2 && ic[0].op == J_ANDK && ic[0].r3.i == 1 && ic[0].r2.r == ic[-1].r1.r) { p->a.dtor = b1; p->sort = IS_Dtor; /* this is tentative: we need to know that arg2 isn't assigned to */ /* before we're certain */ } else if (ic[0].op == J_LDRV+J_ALIGN4 && ic[0].r3.b == arg2) { p->a.dtor = b1; p->sort = IS_Dtor; /* this is tentative: we need to know that arg2 isn't assigned to */ /* before we're certain */ } } } } } } typedef struct ABLList ABLList; struct ABLList { ABLList *cdr; Inline_ArgDesc *arg; }; static Inline_ArgDesc *ABL_Find(ABLList *p, Binder *b) { for (; p != NULL; p = cdr_(p)) if (bindsym_(b) == bindsym_(p->arg->abl.globarg)) return p->arg; return NULL; } static LabelNumber *LabelNo_NoteRef(LabelNumber *l, uint8 *justoneref, uint8 *anyref) { IPtr lno; uint32 mapbit; if (is_exit_label(l)) { lno = (IPtr)l; mapbit = 0; } else { lno = (IPtr)lab_name_(l); mapbit = lno; } if (SetMapBit(anyref, mapbit)) SetMapBit(justoneref, mapbit); else ClearMapBit(justoneref, mapbit); return (LabelNumber *)(IPtr)lno; } bool Inline_Save(Binder *b, BindList *local_binders, BindList *regvar_binders) { SavedFnList *p = NewGlob(SavedFnList, SU_Inline); SaveFnState st; bindinline_(b) = p; p->outoflineflags = (attributes_(b) & A_REALUSE) ? ol_used : 0; st.copied = NULL; st.sharedbindlists = NULL; st.symtrans = NULL; p->fn.fndetails = currentfunction; if (p->fn.fndetails.structresult != NULL) p->fn.fndetails.structresult = GlobalBinderCopy(&st, p->fn.fndetails.structresult); if (p->fn.fndetails.xrflags & xr_defext) Inline_RealUse(b); p->fn.fndetails.argbindlist = GlobalBindListCopy(&st, p->fn.fndetails.argbindlist); p->fn.var_binders = GlobalBindListCopy(&st, local_binders); p->fn.reg_binders = GlobalBindListCopy(&st, regvar_binders); p->fn.top_block = p->fn.bottom_block = NULL; p->fn.firstblockignoresize = 0; p->fn.firstblockignore = NULL; p->fn.ix_narrowspenv = -1; p->maxreg = vregister(INTREG); p->maxlabel = lab_name_(nextlabel()); FindStructorCore(p); { VRegnum n = p->maxreg; Inline_VRegIndex *vt = NewGlobN(Inline_VRegIndex, SU_Inline, p->maxreg); while (--n > NMAGICREGS) vt[n].rs = vregsort(n); p->vregtypetab = vt; } { BindList *bl = p->fn.fndetails.argbindlist; Inline_ArgDesc **adp = &argdesc_(p); FormTypeList *ft = typefnargs_(bindtype_(b)); ABLList *narrowargs = NULL; p->fn.args = NULL; for (; bl != NULL; bl = bl->bindlistcdr) { Inline_ArgDesc *ad = NewGlob(Inline_ArgDesc, SU_Inline); Binder *b = bl->bindlistcar; adcdr_(ad) = NULL; ad->abl.globarg = b; ad->flags = 0; ad->accessmap = 0; *adp = ad; adp = &adcdr_(ad); ad->abl.globnarrowarg = ad->abl.instantiatednarrowarg = NULL; ad->abl.narrowtype = NULL; ad->mink = MaxMemOffset(J_LDRK+J_ALIGN4); ad->maxk = MinMemOffset(J_LDRK+J_ALIGN4); /* ft reflects the declared argument types of the function, bl the types * of arguments actually passed (they will differ in the type of narrow * arguments, and also only bl has an entry for the extra pointer-to-result * argument of structure-returning functions). */ if (!(bl == p->fn.fndetails.argbindlist && p->fn.fndetails.structresult != NULL)) { if (widen_formaltype(ft->fttype) != ft->fttype) { ad->abl.narrowtype = ft->fttype; narrowargs = (ABLList *)syn_list2(narrowargs, ad); } ft = ft->ftcdr; } } if (narrowargs != NULL) { BlockHead *b = blkdown_(top_block); int32 n, len = blklength_(b); Icode *ic = blkcode_(b); uint8 *map = NewBlockMap(2*len); p->fn.firstblockignoresize = 2*len; p->fn.firstblockignore = map; p->fn.ix_max = len; for (n = 0; n < len; ic++, n++) { J_OPCODE op = ic->op & J_TABLE_BITS; if (op == J_SETSPENV && p->fn.ix_narrowspenv == -1) { p->fn.ix_narrowspenv = n; SetMapBit(map, n); } else if (op == J_STRV || op == J_STRDV) { Binder *mb = GlobalBinderCopy(&st, ic->r3.b); Inline_ArgDesc *ad = ABL_Find(narrowargs, mb); if (ad != NULL && ad->abl.globnarrowarg == NULL) { ad->abl.globnarrowarg = mb; SetMapBit(map, len+n); } } else if (op == J_INIT || op == J_INITD) { Binder *mb = GlobalBinderCopy(&st, ic->r3.b); Inline_ArgDesc *ad = ABL_Find(narrowargs, mb); if (ad != NULL && ad->abl.globnarrowarg == NULL) SetMapBit(map, n); } } } } { BlockHead *b = top_block; BlockHead *blast = NULL, *bnew; uint8 *justoneref = NewTempMap(p->maxlabel), *anyref = NewTempMap(p->maxlabel); /* to help determine {first,last}blockmergeable */ for (b = top_block; b != NULL; b = blkdown_(b), blast = bnew) { bnew = NewGlob(BlockHead, SU_Inline); *bnew = *b; blkup_(bnew) = blast; if (blast == NULL) p->fn.top_block = bnew; else blkdown_(blast) = bnew; if (blkflags_(b) & BLKSWITCH) { int32 n = blktabsize_(b); LabelNumber **sw_old = blktable_(b); LabelNumber **sw_new = NewGlobN(LabelNumber *, SU_Inline, n); while (--n >= 0) sw_new[n] = LabelNo_NoteRef(sw_old[n], justoneref, anyref); blktable_(bnew) = sw_new; } else { blknext_(bnew) = LabelNo_NoteRef(blknext_(b), justoneref, anyref); if (blkflags_(b) & BLK2EXIT) blknext1_(bnew) = LabelNo_NoteRef(blknext1_(b), justoneref, anyref); } blklab_(bnew) = (LabelNumber *)(IPtr)lab_name_(blklab_(b)); blkstack_(bnew) = GlobalSharedBindListCopy(&st, blkstack_(b)); { int32 n = blklength_(b), len = n; Icode *code_old = blkcode_(b); Icode *code_new = n == 0 ? (Icode *)DUFF_ADDR : NewGlobN(Icode, SU_Inline, n); bool inctorcore = YES; if (p->sort == IS_Ctor) inctorcore = MapBitSet(p->a.ctor, lab_name_(blklab_(b))); else if (p->sort == IS_Dtor && b == p->a.dtor) p->a.dtor = bnew; blkcode_(bnew) = code_new; while (--n >= 0) { Icode *ic_old = &code_old[n]; Icode *ic_new = &code_new[n]; J_OPCODE op = ic_old->op & J_TABLE_BITS; *ic_new = *ic_old; if (op == J_SETSPENV) { ic_new->r3.bl = GlobalSharedBindListCopy(&st, ic_new->r3.bl); ic_new->r2.bl = GlobalSharedBindListCopy(&st, ic_new->r2.bl); } else if (op == J_SETSPGOTO) { ic_new->r2.bl = GlobalSharedBindListCopy(&st, ic_new->r2.bl); ic_new->r3.l = (LabelNumber *)(IPtr)lab_xname_(ic_new->r3.l); } else if (uses_stack(op) || op == J_CALLK || op==J_ADCON || op == J_INIT || op == J_INITF || op == J_INITD) { Binder *bnew = ic_new->r3.b = GlobalBinderCopy(&st, ic_new->r3.b); Inline_ArgDesc *ad = ArgDesc_Find(bnew, argdesc_(p)); if (ad != NULL) { if (stores_r1(op)) { if (ad->abl.narrowtype == NULL || b != blkdown_(top_block) || !MapBitSet(p->fn.firstblockignore, len+n)) { if (inctorcore) ad->flags |= IA_Updated; else ad->flags |= IA_UpdatedOutsideCore; } } else if (op == J_LDRV) { Icode *next1 = ic_new + 1; if (n+1 < len) { J_OPCODE nextop = next1->op & J_TABLE_BITS; if (j_is_ldr_or_str(nextop) && reads_r2(nextop) && !reads_r3(nextop) && next1->r2.r == ic_new->r1.r) { int32 accesssize; #ifdef TARGET_LACKS_HALFWORD_STORE int32 k; if (nextop == J_STRBK && n+3 < len && IsSTRWExpansion(next1, &k) && k == 0) accesssize = MEM_W; else #endif if (next1->r3.i == 0) { accesssize = j_memsize(nextop); } else accesssize = MEM_NONE; if ((ad->flags & IA_AccessSet) && ad->accesssize != accesssize) accesssize = MEM_NONE; ad->accesssize = accesssize; ad->flags |= IA_AccessSet; ad->accessmap |= (1 << j_memsize(nextop)); if (next1->r3.i < ad->mink) ad->mink = next1->r3.i; if (next1->r3.i > ad->maxk) ad->maxk = next1->r3.i; continue; } else if (nextop == J_MOVR) continue; } if (inctorcore) ad->flags |= IA_OddUseForPlusInCore; } else if (op != J_INIT && op != J_INITF && op != J_INITD) ad->flags |= IA_OddAccess; } } else if (op==J_STRING) ic_new->r3.s = globalize_strseg(ic_new->r3.s); } } } blkdown_(blast) = NULL; p->fn.bottom_block = blast; p->fn.lastblockmergeable = MapBitSet(justoneref, 0) && !(blkflags_(blast) & (BLK2EXIT+BLKSWITCH)) && is_exit_label(blknext_(blast)); p->fn.firstblockmergeable = MapBitSet(justoneref, (IPtr)blklab_(blkdown_(p->fn.top_block))); } { SynBindList *bl = st.copied; for (; bl != NULL; bl = bl->bindlistcdr) h0_(bl->bindlistcar) = s_binder; } if (p->sort == IS_Dtor) { /* retract if the second argument isn't read-only */ Inline_ArgDesc *ad = adcdr_(argdesc_(p)); if (ad->flags & (IA_OddAccess + IA_Updated + IA_UpdatedOutsideCore)) p->sort = IS_Ord; } if (debugging(DEBUG_CG)) { cc_msg("Inline_Save %s", symname_(p->fn.fndetails.symstr)); if (p->sort == IS_Dtor) { cc_msg(": Dtor: %ld\n", (int32)blklab_(p->a.dtor)); } else if (p->sort == IS_Ctor) { int32 i; BlockMap *map = p->a.ctor; int c = '{'; cc_msg(": Ctor: "); for (i = 0; i < p->maxlabel; i++) if (MapBitSet(map, i)) { cc_msg("%c%ld", c, (long)i); c = ' '; } cc_msg("}\n"); } else cc_msg("\n"); } cdr_(p) = saved_fns; saved_fns = p; return YES; } static BindList *FromGlobalSharedBindListCopy(SaveFnState *st, BindList *bl); static Binder *FromGlobalBinderCopy(SaveFnState *st, Binder *b) { if (h0_(b) != s_binder) return (Binder *)(IPtr)h0_(b); { Binder *bnew; size_t n; if (bindstg_(b) & (bitofstg_(s_virtual)|b_globalregvar|bitofstg_(s_auto))) n = sizeof(Binder); else { if (attributes_(b) & A_GLOBALSTORE) return b; n = SIZEOF_NONAUTO_BINDER; } bnew = mk_binder(bindsym_(b), bindstg_(b), bindtype_(b)); memcpy(bnew, b, n); h0_(b) = (AEop)(IPtr)bnew; st->copied = mkSynBindList(st->copied, b); if (bindstg_(b) & bitofstg_(s_auto)) { if (bindstg_(b) & b_bindaddrlist) bindbl_(bnew) = FromGlobalSharedBindListCopy(st, bindbl_(b)); if (bindxx_(b) != GAP) bindxx_(bnew) = st->vregindex[bindxx_(b)].r; } return bnew; } } static BindList *FromGlobalBindListCopy(SaveFnState *st, BindList *bl) { BindList *bl_new = NULL; BindList *bp, **bpp = &bl_new; for (; bl != NULL; bl = bl->bindlistcdr, bpp = &bp->bindlistcdr) { Binder *b = FromGlobalBinderCopy(st, bl->bindlistcar); bp = (BindList *)binder_cons2(NULL, b); *bpp = bp; } return bl_new; } static BindList *FromGlobalSharedBindListCopy(SaveFnState *st, BindList *bl) { BindListIndex *p = st->sharedbindlists; if (bl == NULL) return st->nullenv; for (; p != NULL; p = cdr_(p)) if (bl == p->orig) return p->copy; { BindList *bl_new = (BindList *)binder_cons2( FromGlobalSharedBindListCopy(st, bl->bindlistcdr), FromGlobalBinderCopy(st, bl->bindlistcar)); st->sharedbindlists = (BindListIndex *)syn_list3(st->sharedbindlists, bl, bl_new); return bl_new; } } static LabelNumber *FromGlobalLabel( LabelNumber **index, Inline_RestoreControl *rc, LabelNumber *old) { /* (LabelNumber *) values like 'old' here only hold small ints. */ return !is_exit_label(old) ? index[(IPtr)old] : rc != NULL && rc->exitlabel != NULL ? rc->exitlabel : old; } static BindList *BindListCopy(BindList *bl) { BindList *bl_new = NULL; BindList *bp, **bpp = &bl_new; for (; bl != NULL; bl = bl->bindlistcdr, bpp = &bp->bindlistcdr) { bp = (BindList *)binder_cons2(NULL, bl->bindlistcar); *bpp = bp; } return bl_new; } static SavedFnList *FindSavedFn(Inline_SavedFn *fn) { SavedFnList *p; for (p = saved_fns; p != NULL; p = cdr_(p)) if (fn->fndetails.symstr == p->fn.fndetails.symstr) return p; return NULL; } static bool OverlargeOffset(Inline_ArgDesc const *ad, Expr *ex) { uint8 map = ad->accessmap; int32 k = intval_(arg2_(ex)); int32 mink = k + ad->mink, maxk = k + ad->maxk; int32 align = J_ALIGN4; /* WD: temp hack - will become parameter!! */ if ((map & (1 << MEM_B)) && (mink < MinMemOffset(J_LDRBK+align) || maxk > MaxMemOffset(J_LDRBK+align))) return YES; if ((map & (1 << MEM_W)) && (mink < MinMemOffset(J_LDRWK+align) || maxk > MaxMemOffset(J_LDRWK+align))) return YES; if ((map & (1 << MEM_I)) && (mink < MinMemOffset(J_LDRK+align) || maxk > MaxMemOffset(J_LDRK+align))) return YES; if ((map & (1 << MEM_F)) && (mink < MinMemOffset(J_LDRFK+align) || maxk > MaxMemOffset(J_LDRFK+align))) return YES; if ((map & (1 << MEM_D)) && (mink < MinMemOffset(J_LDRDK+align) || maxk > MaxMemOffset(J_LDRDK+align))) return YES; if ((map & (1 << MEM_LL)) && (mink < MinMemOffset(J_LDRLK+align) || maxk > MaxMemOffset(J_LDRLK+align))) return YES; return NO; } static void ResultRename_fixdef(VRegnum r, Inline_RestoreControl *rc, int32 *mask) /* Renames a fixed (non-renamable) result register in the newresultregs */ { int i; for (i = 0; i < rc->nresults; i++) if (((1 << i) & *mask) && rc->resultregs[i] == r) { rc->newresultregs[i] = r; *mask &= ~(1 << i); } } static void ResultRename_def(VRegnum *r, Inline_RestoreControl *rc, int32 *mask) /* Renames a result register to newresultregs */ { int i; for (i = 0; i < rc->nresults; i++) if (((1 << i) & *mask) && rc->resultregs[i] == *r) { if (rc->newresultregs[i] != GAP) *r = rc->newresultregs[i]; *mask &= ~(1 << i); } } void Inline_Restore(Inline_SavedFn *fn, Inline_RestoreControl *rc) { SaveFnState st; SavedFnList *p = FindSavedFn(fn); Inline_VRegIndex *vt = p->vregtypetab; int32 n = p->maxreg; BindList *argb_orig = fn->fndetails.argbindlist; Inline_ArgDesc *ad; BlockMap *map = NULL; BlockHead *dtorlast = NULL; BlockHead *bottom = p->fn.bottom_block; bool skipblock2 = NO; while (--n >= 0) vt[n].r = n <= NMAGICREGS ? n : vregister(vt[n].rs); st.copied = NULL; st.sharedbindlists = NULL; st.vregindex = p->vregtypetab; if (fn->fndetails.structresult != NULL) fn->fndetails.structresult = FromGlobalBinderCopy(&st, fn->fndetails.structresult); fn->fndetails.argbindlist = FromGlobalBindListCopy(&st, argb_orig); for (ad = argdesc_(p); ad != NULL; ad = adcdr_(ad)) ad->argsubst = NULL; if (rc != NULL) { Inline_ArgSubstList *as = rc->argreplace; BindList **blp = &fn->fndetails.argbindlist; int ia_cantsubst = IA_Updated + IA_OddAccess + IA_UpdatedOutsideCore; for (ad = argdesc_(p); ad != NULL; ad = adcdr_(ad)) { /* Prune from the argument bindlist those arguments which we know can */ /* be substituted for */ BindList *bl = *blp; if (as == NULL) break; if (as->arg == ad->abl.globarg || as->arg == ad->abl.globnarrowarg) { Inline_ArgSubstList *thisas = as; bool subst = YES; as = cdr_(as); if (ad->abl.narrowtype != NULL && ((thisas->sort != T_Int && thisas->sort != T_Binder) || ad->abl.globnarrowarg == NULL)) subst = NO; else if (ad == argdesc_(p) && p->sort == IS_Ctor && !(ad->flags & (IA_Updated + IA_OddAccess))) { if (thisas->notnull) { if (thisas->sort == T_Plus && (OverlargeOffset(ad, thisas->replacement.ex) || (ad->flags & IA_OddUseForPlusInCore))) subst = NO; map = p->a.ctor; ia_cantsubst = IA_Updated + IA_OddAccess; } else { if (thisas->sort == T_Int && intval_(thisas->replacement.ex) == 0) skipblock2 = YES; if (ad->flags & IA_UpdatedOutsideCore) subst = NO; } } else if (p->sort == IS_Dtor && ad == adcdr_(argdesc_(p)) && !(ad->flags & ia_cantsubst) && thisas->sort == T_Int && intval_(thisas->replacement.ex) == 0) dtorlast = p->a.dtor; else if ((thisas->sort == T_Plus && (OverlargeOffset(ad, thisas->replacement.ex) || (ad->flags & IA_OddUseForPlusInCore))) || ad->flags & ia_cantsubst) subst = NO; if (subst) { *blp = bl->bindlistcdr; ad->argsubst = thisas; if (debugging(DEBUG_CG)) { cc_msg("Substitution for %s$b: ", thisas->sort==T_AdconV ? "*" : "", thisas->arg); pr_expr_nl(thisas->replacement.ex); } continue; } thisas->refsleft = YES; } blp = &bl->bindlistcdr; } } if (rc != NULL) { BindList *bl = BindListCopy(fn->fndetails.argbindlist); BindList *argbl = bl; n = length((List *)bl); rc->env = st.nullenv = (BindList *)nconc((List *)bl, (List *)rc->env); for (; --n >= 0; argbl = argbl->bindlistcdr) { Binder *b = argbl->bindlistcar; bindbl_(b) = argbl; bindstg_(b) |= b_bindaddrlist; } } else st.nullenv = NULL; fn->var_binders = FromGlobalBindListCopy(&st, fn->var_binders); fn->reg_binders = FromGlobalBindListCopy(&st, fn->reg_binders); { LabelNumber **labelindex = NewSynN(LabelNumber *, p->maxlabel); BlockHead *b = fn->top_block; BlockHead *globtop = b; BlockHead *blast = NULL, *bnew = NULL; Inline_ArgSubstList *sl; for (n = 1; n < p->maxlabel; n++) labelindex[n] = nextlabel(); fn->top_block = fn->bottom_block = NULL; for (; b != NULL; b = blkdown_(b), blast = bnew) if ( skipblock2 ? b != blkdown_(globtop) : map != NULL ? MapBitSet(map, (IPtr)blklab_(b)) : YES) { int32 restoload = 0; bool resvoided = YES; bnew = NewBind(BlockHead); *bnew = *b; blkup_(bnew) = blast; if (blast == NULL) fn->top_block = bnew; else blkdown_(blast) = bnew; if (blkflags_(b) & BLKSWITCH) { int32 n = blktabsize_(b); LabelNumber **sw_old = blktable_(b); LabelNumber **sw_new = NewBindN(LabelNumber *, n); while (--n >= 0) sw_new[n] = FromGlobalLabel(labelindex, rc, sw_old[n]); blktable_(bnew) = sw_new; } else { BlockHead *b1 = b; if (b == dtorlast) { b1 = bottom; blkflags_(bnew) &= ~BLK2EXIT; } else { if (skipblock2 && blast == NULL) b1 = blkdown_(b); if (blkflags_(b) & BLK2EXIT) blknext1_(bnew) = FromGlobalLabel(labelindex, rc, blknext1_(b)); } if (is_exit_label(blknext_(b1)) && rc != NULL) { restoload = (1L << rc->nresults) - 1; if (rc->nresults > 0 && rc->newresultregs[0] != GAP) resvoided = NO; } blknext_(bnew) = FromGlobalLabel(labelindex, rc, blknext_(b1)); } { LabelNumber *lab = FromGlobalLabel(labelindex, rc, blklab_(b)); blklab_(bnew) = lab; lab->block = bnew; } blkstack_(bnew) = FromGlobalSharedBindListCopy(&st, blkstack_(b)); { int32 n_in = blklength_(b), n_out = n_in, n; Icode *code_old = blkcode_(b); Icode *code_new; bool copied = NO; VRegnum discardload = GAP; int32 noopcount = 0; Inline_ArgDesc *ad; for (n = n_in; --n >= 0; ) { J_OPCODE op = code_old[n].op & J_TABLE_BITS; if (op == J_ADCON) { Binder *b = code_old[n].r3.b; if ((bindstg_(b) & bitofstg_(s_extern)) && !(bindstg_(b) & (b_undef|b_fnconst)) && !(binduses_(b) & (u_bss|u_constdata)) && b != datasegment && bindaddr_(b) != 0) { n_out++; } } } if (b == dtorlast) { n_out = n_out - 2 + blklength_(bottom); n_in = blklength_(bottom); code_old = blkcode_(bottom); } code_new = n_out == 0 ? (Icode *)DUFF_ADDR : NewBindN(Icode, n_out); blkcode_(bnew) = code_new; blklength_(bnew) = n_out; for (n = n_out; --n, --n_in >= 0; ) { J_OPCODE op = code_old[n_in].op; uint32 flags = code_old[n_in].flags; VRegInt r1 = code_old[n_in].r1, r2 = code_old[n_in].r2, r3 = code_old[n_in].r3, r4 = code_old[n_in].r4; J_OPCODE opx = op & J_TABLE_BITS; if (uses_r1(op)) r1.r = vt[r1.r].r; if (uses_r2(op)) r2.r = vt[r2.r].r; if (uses_r3(op)) r3.r = vt[r3.r].r; if (uses_r4(op)) r4.r = vt[r4.r].r; if (opx == J_SETSPENV) { if (r3.bl == r2.bl && !copied && rc != NULL) { /* m = r2 only when both are empty, just before function exits (deliberately not optimised out to give somewhere for CSE-introduced binders to be popped). */ n_out--; goto maybeswitchblock; } r3.bl = FromGlobalSharedBindListCopy(&st, r3.bl); r2.bl = FromGlobalSharedBindListCopy(&st, r2.bl); } else if (opx == J_SETSPGOTO) { r2.bl = FromGlobalSharedBindListCopy(&st, r2.bl); r3.l = FromGlobalLabel(labelindex, rc, r3.l); } else if (opx == J_STRV && (ad = ArgDesc_Find(r3.b, argdesc_(p))) != NULL && (sl = ad->argsubst) != NULL && sl->sort == T_Int) { op = J_MOVK; r3.i = intval_(sl->replacement.ex); } else if (opx == J_STRV && (ad = ArgDesc_Find(r3.b, argdesc_(p))) != NULL && (sl = ad->argsubst) != NULL && sl->sort == T_Binder && ad->abl.narrowtype != NULL) { r3.b = sl->replacement.b; } else if (opx == J_LDRV && (ad = ArgDesc_Find(r3.b, argdesc_(p))) != NULL && (sl = ad->argsubst) != NULL) { switch (sl->sort) { default: syserr("Inline_Restore"); break; case T_Binder: r3.b = sl->replacement.b; break; case T_Adcon: r3.b = sl->replacement.b; op = J_ADCON; break; case T_Int: op = J_MOVK, r3.i = intval_(sl->replacement.ex); break; case T_Plus: { Binder *b = exb_(arg1_(sl->replacement.ex)); int32 k = intval_(arg2_(sl->replacement.ex)); Icode *next1 = &code_new[n+1]; J_OPCODE nextop = next1->op & J_TABLE_BITS; if (n+1 < n_out) { if (j_is_ldr_or_str(nextop) && reads_r2(nextop) && !reads_r3(nextop) && next1->r2.r == r1.r) { #ifdef TARGET_LACKS_HALFWORD_STORE int32 k1; if (nextop == J_STRBK && n+3 < n_out && IsSTRWExpansion(next1, &k1)) { code_new[n+3].r3.i += k; } #endif r3.b = b; next1->r3.i += k; break; } else if (nextop == J_MOVR && next1->r3.r == r1.r) { r3.b = b; next1->op = J_ADDK; next1->r2.r = r1.r; next1->r3.i = k; break; } } if (loads_r1(op) && r1.r == discardload) { op = J_NOOP; noopcount++; discardload = GAP; } else r3.b = FromGlobalBinderCopy(&st, r3.b); break; } case T_AdconV: /* Substituting an ADCONV: try to combine it with subsequent */ /* loads and stores (turning them into VK variants) so that */ /* the variable isn't falsely seen to be address-taken. */ { int32 i = n; bool used = NO; r3.b = sl->replacement.b; while (++i < n_out) { Icode *next = &code_new[i]; J_OPCODE nextop = next->op & J_TABLE_BITS; if (j_is_ldr_or_str(nextop) && reads_r2(nextop) && !reads_r3(nextop) && next->r2.r == r1.r) { if (sl->size == MEM_NONE || sl->size != ad->accesssize) { #ifdef TARGET_LACKS_HALFWORD_STORE int32 k; if (nextop == J_STRBK && i+2 < n_out && IsSTRWExpansion(next, &k)) { Icode *next3 = &code_new[i+2]; next3->op = J_addvk(next3->op); next3->r2.i = next3->r3.i; next3->r3.b = r3.b; } #endif next->op = J_addvk(next->op); next->r2.i = next->r3.i; next->r3.b = r3.b; } else { #ifdef TARGET_LACKS_HALFWORD_STORE int32 k; if (nextop == J_STRBK && i+2 < n_out && IsSTRWExpansion(next, &k) && k == 0) { (next+1)->op = J_NOOP; (next+2)->op = J_NOOP; noopcount += 2; next->op = J_STRV+J_ALIGN4; next->r2.r = GAP; next->r3.b = r3.b; } else #endif if (nextop == J_LDRBK || nextop == J_LDRWK) { next->op = J_LDRV+J_ALIGN4; next->r2.r = GAP; next->r3.b = r3.b; } else if (nextop == J_STRWK || nextop == J_STRBK) { next->op = J_STRV+J_ALIGN4; next->r2.r = GAP; next->r3.b = r3.b; } else { next->op = J_addvk(next->op); next->r2.i = next->r3.i; next->r3.b = r3.b; } } } else if (reads_r1(nextop) && next->r1.r == r1.r || reads_r2(nextop) && next->r2.r == r1.r || reads_r3(nextop) && next->r3.r == r1.r || reads_r4(nextop) && next->r4.r == r1.r) used = YES; } if (used) op = J_ADCONV; else { op = J_NOOP; noopcount++; } } break; } } else if (opx == J_ADCON) { r3.b = FromGlobalBinderCopy(&st, r3.b); if ((bindstg_(r3.b) & bitofstg_(s_extern)) && !(bindstg_(r3.b) & (b_undef|b_fnconst)) && !(binduses_(r3.b) & (u_bss|u_constdata)) && r3.b != datasegment) { if (bindaddr_(r3.b) != 0) { INIT_IC(code_new[n], J_ADDK); code_new[n].r1 = r1; code_new[n].r2 = r1; code_new[n].r3.i = bindaddr_(r3.b); code_new[n].r4.r = GAP; n--; } r3.b = datasegment; } } else if (uses_stack(op) || opx == J_CALLK || opx == J_INIT || opx == J_INITF || opx == J_INITD) r3.b = FromGlobalBinderCopy(&st, r3.b); if (loads_r1(op)) { if (restoload != 0) { int i; if (isproccall_(op)) { restoload = 0; for (i = 0; i < rc->nresults; i++) rc->newresultregs[i] = rc->resultregs[i]; } else for (i = 0; i < rc->nresults; i++) if (r1.r == rc->resultregs[i]) { restoload &= ~regbit(i); if (!resvoided) { r1.r = rc->newresultregs[i]; blkflags_(b) |= BLKREXPORTED; } else { if (op == J_MOVR) discardload = r3.r; op = J_NOOP; noopcount++; } break; } } else if (r1.r == discardload) { if (!isproccall_(op)) { op = J_NOOP; noopcount++; } discardload = GAP; } } else if (uses_r1(op) && r1.r == discardload) discardload = GAP; copied = YES; INIT_IC(code_new[n], op); code_new[n].flags = flags; code_new[n].r1 = r1; code_new[n].r2 = r2; code_new[n].r3 = r3; code_new[n].r4 = r4; /* WD: quick HACK for the above code - broken for inline assembler */ /* does not discard moves (discardload), or voids results (resvoided) there doesn't seem to be any point in doing that anyway... */ if (rc != NULL) { RealRegUse use; int i; if (!isproccall_(op)) { if (updates_r1(op)) ResultRename_fixdef(code_new[n].r1.r, rc, &restoload); else if (loads_r1(op)) ResultRename_def(&code_new[n].r1.r, rc, &restoload); if (updates_r2(op)) ResultRename_fixdef(code_new[n].r2.r, rc, &restoload); else if (loads_r2(op)) ResultRename_def(&code_new[n].r2.r, rc, &restoload); } RealRegisterUse(&code_new[n], &use); for (i = 0; i < NMAGICREGS; i++) { if (member_RealRegSet(&use.def, i)) ResultRename_fixdef(i, rc, &restoload); /* TODO: need to report a syserr if one of the result registers will be corrupted! */ } blkflags_(b) |= BLKREXPORTED; } /* TODO: a real implementation would need 2 passes to renumber the registers, because * it needs to rename USES too. BROKEN for inline assembler anyway! */ maybeswitchblock : if (n_in == 0 && b == dtorlast) { n_in = blklength_(dtorlast) - 2; code_old = blkcode_(dtorlast); b = bottom; } } if (noopcount > 0) { int32 n = 0, n_in = 0; for (; n_in < n_out; n_in++) if (code_new[n_in].op != J_NOOP) { if (n != n_in) code_new[n] = code_new[n_in]; n++; } n_out = n; } blklength_(bnew) = n_out; } } blkdown_(blast) = NULL; fn->bottom_block = blast; } { Inline_ArgDesc *ad = (Inline_ArgDesc *)(fn->args); for (; ad != NULL; ad = adcdr_(ad)) if (ad->abl.globnarrowarg != NULL) ad->abl.instantiatednarrowarg = FromGlobalBinderCopy(&st, ad->abl.globnarrowarg); } { SynBindList *bl = st.copied; for (; bl != NULL; bl = bl->bindlistcdr) h0_(bl->bindlistcar) = s_binder; } { VRegnum n = p->maxreg; Inline_VRegIndex *vt = p->vregtypetab; while (!isany_realreg_(--n)) vt[n].rs = vregsort(vt[n].r); } } void Inline_Init() { saved_fns = NULL; } static void Inline_CompileOutOfLineCopy(Inline_SavedFn *fn) { char v[128]; cg_sub_reinit(); Inline_Restore(fn, NULL); currentfunction = fn->fndetails; top_block = fn->top_block; bottom_block = fn->bottom_block; if (debugging(DEBUG_CG)) { sprintf(v, "Out-of-line %s", symname_(fn->fndetails.symstr)); flowgraf_print(v, NO); } cg_topdecl2(fn->var_binders, fn->reg_binders); } void Inline_Tidy() { SavedFnList *p; for (;;) { bool emitted = NO; for (p = saved_fns; p != NULL; p = cdr_(p)) if ((p->outoflineflags & ol_used) && !(p->outoflineflags & ol_emitted)) { { char v[128+5]; #ifdef TARGET_IS_THUMB /* This must be redone in a more sensible way later */ strcpy(v, "x$t$"); #else strcpy(v, "x$i$"); #endif strcpy(v+4, symname_(p->fn.fndetails.symstr)); obj_setcommoncode(); codebuf_reinit1(v); } emitted = YES; p->outoflineflags |= ol_emitted; Inline_CompileOutOfLineCopy(&p->fn); } if (!emitted) break; } } void Inline_LoadState(FILE *f) { uint32 w[5]; int32 nfn; fread(w, sizeof(uint32), 1, f); nfn = w[0]; while (--nfn >= 0) { SavedFnList *sf = NewGlob(SavedFnList, SU_Inline); fread(sf, sizeof(SavedFnList), 1, f); cdr_(sf) = saved_fns; saved_fns = sf; sf->fn.fndetails.symstr = Dump_LoadedSym((IPtr)sf->fn.fndetails.symstr); { Binder *b = bind_global_(sf->fn.fndetails.symstr); if (b != NULL) bindinline_(b) = sf; } sf->fn.fndetails.structresult = Dump_LoadedBinder((IPtr)sf->fn.fndetails.structresult); sf->fn.fndetails.argbindlist = Dump_LoadBindList(f); sf->fn.var_binders = Dump_LoadBindList(f); sf->fn.reg_binders = Dump_LoadBindList(f); { Inline_ArgDesc **adp = &argdesc_(sf); int32 n; fread(w, sizeof(uint32), 1, f); for (n = w[0]; --n >= 0; ) { Inline_ArgDesc *p = NewGlob(Inline_ArgDesc, SU_Inline); *adp = p; adp = &adcdr_(p); fread(w, sizeof(uint32), 3, f); p->flags = w[0]; p->abl.globarg = Dump_LoadedBinder(w[1]); p->abl.globnarrowarg = Dump_LoadedBinder(w[2]); p->abl.narrowtype = Dump_LoadType(f); } *adp = NULL; } sf->vregtypetab = NewGlobN(Inline_VRegIndex, SU_Inline, sf->maxreg); fread(sf->vregtypetab, sizeof(Inline_VRegIndex), (size_t)sf->maxreg, f); if (sf->fn.firstblockignoresize > 0) { sf->fn.firstblockignore = NewGlobN(uint8, SU_Inline, sf->fn.firstblockignoresize); fread(sf->fn.firstblockignore, sizeof(uint8), MapSize(sf->fn.firstblockignoresize), f); } else sf->fn.firstblockignore = NULL; if (sf->sort == IS_Ctor) { sf->a.ctor = NewGlobN(uint8, SU_Inline, sf->maxlabel); fread(sf->a.ctor, sizeof(uint8), MapSize(sf->maxlabel), f); } else if (sf->sort == IS_Dtor) fread(&sf->a.dtor, sizeof(LabelNumber *), 1, f); fread(w, sizeof(uint32), 1, f); { int32 nb = w[0]; BlockHead *b, *prev = NULL; for (; --nb >= 0; prev = b) { Icode *p; int32 n; int32 nstring; StringSegList **stringindex; b = NewGlob(BlockHead, SU_Inline); blkup_(b) = prev; if (prev == NULL) sf->fn.top_block = b; else blkdown_(prev) = b; fread(w, sizeof(uint32), 5, f); blklength_(b) = w[0]; blkflags_(b) = w[1]; blknext1_(b) = (LabelNumber *)(IPtr)w[2]; blklab_(b) = (LabelNumber *)(IPtr)w[3]; blkstack_(b) = Dump_LoadedSharedBindList(w[4]); blkusedfrom_(b) = NULL; blkuse_(b) = 0; blknest_(b) = 0; if (blkflags_(b) & BLKSWITCH) { blktable_(b) = NewGlobN(LabelNumber *, SU_Inline, blktabsize_(b)); fread(blktable_(b), sizeof(LabelNumber *), (size_t)blktabsize_(b), f); } else fread(&blknext_(b), sizeof(LabelNumber *), 1, f); if (sf->sort == IS_Dtor && (LabelNumber *)sf->a.dtor == blklab_(b)) sf->a.dtor = b; fread(&nstring, sizeof(uint32), 1, f); stringindex = NewSynN(StringSegList *, nstring); for (n = 0; n < nstring; n++) stringindex[n] = Dump_LoadStrSeg(f); if (blklength_(b) == 0) blkcode_(b) = (Icode *)DUFF_ADDR; else { blkcode_(b) = NewGlobN(Icode, SU_Inline, blklength_(b)); fread(blkcode_(b), sizeof(Icode), (size_t)blklength_(b), f); for (n = blklength_(b), p = blkcode_(b); --n >= 0; p++) { J_OPCODE op = p->op & J_TABLE_BITS; if (op == J_SETSPENV) { p->r3.bl = Dump_LoadedSharedBindList(p->r3.i); p->r2.bl = Dump_LoadedSharedBindList(p->r2.i); } else if (op == J_SETSPGOTO) { p->r2.bl = Dump_LoadedSharedBindList(p->r2.i); } else if (uses_stack(op) || op == J_CALLK || op==J_ADCON || op == J_INIT || op == J_INITF || op == J_INITD) { p->r3.b = Dump_LoadedBinder(p->r3.i); } else if (op == J_STRING) { p->r3.s = stringindex[p->r3.i]; } } } } blkdown_(prev) = NULL; sf->fn.bottom_block = prev; } } saved_fns = (SavedFnList *)dreverse((List *)saved_fns); } #ifndef NO_DUMP_STATE void Inline_DumpState(FILE *f) { SavedFnList *p = saved_fns; uint32 w[5]; w[0] = length((List *)p); fwrite(w, sizeof(uint32), 1, f); for (; p != NULL; p = cdr_(p)) { SavedFnList sf = *p; BlockHead *b; sf.fn.fndetails.symstr = (Symstr *)(IPtr)Dump_SymRef(sf.fn.fndetails.symstr); sf.fn.fndetails.structresult = (Binder *)(IPtr)Dump_BinderRef(sf.fn.fndetails.structresult); fwrite(&sf, sizeof(SavedFnList), 1, f); Dump_BindList(sf.fn.fndetails.argbindlist, f); Dump_BindList(sf.fn.var_binders, f); Dump_BindList(sf.fn.reg_binders, f); { Inline_ArgDesc *ad = argdesc_(&sf); w[0] = length((List *)&ad->abl); fwrite(w, sizeof(uint32), 1, f); for (; ad != NULL; ad = adcdr_(ad)) { w[0] = ad->flags; w[1] = Dump_BinderRef(ad->abl.globarg); w[2] = Dump_BinderRef(ad->abl.globnarrowarg); fwrite(w, sizeof(uint32), 3, f); Dump_Type(ad->abl.narrowtype, f); } } fwrite(sf.vregtypetab, sizeof(Inline_VRegIndex), (size_t)sf.maxreg, f); if (sf.fn.firstblockignoresize > 0) { fwrite(sf.fn.firstblockignore, sizeof(uint8), MapSize(sf.fn.firstblockignoresize), f); } if (sf.sort == IS_Ctor) fwrite(sf.a.ctor, sizeof(uint8), MapSize(sf.maxlabel), f); else if (sf.sort == IS_Dtor) fwrite(&blklab_(sf.a.dtor), sizeof(LabelNumber *), 1, f); w[0] = 0; for (b = sf.fn.top_block; b != NULL; b = blkdown_(b)) w[0]++; fwrite(w, sizeof(uint32), 1, f); for (b = sf.fn.top_block; b != NULL; b = blkdown_(b)) { Icode *p; int32 n; uint32 nstring; w[0] = blklength_(b); w[1] = blkflags_(b); w[2] = (uint32)(IPtr)blknext1_(b); w[3] = (uint32)(IPtr)blklab_(b); w[4] = Dump_NoteSharedBindList(blkstack_(b)); fwrite(w, sizeof(uint32), 5, f); if (blkflags_(b) & BLKSWITCH) fwrite(blktable_(b), sizeof(LabelNumber *), (size_t)blktabsize_(b), f); else fwrite(&blknext_(b), sizeof(LabelNumber *), 1, f); for (nstring = 0, n = blklength_(b), p = blkcode_(b); --n >= 0; p++) if ((p->op & J_TABLE_BITS) == J_STRING) nstring++; fwrite(&nstring, sizeof(uint32), 1, f); for (nstring = 0, n = blklength_(b), p = blkcode_(b); --n >= 0; p++) if ((p->op & J_TABLE_BITS) == J_STRING) { Dump_StrSeg(p->r3.s, f); p->r3.i = nstring++; } for (n = blklength_(b), p = blkcode_(b); --n >= 0; p++) { J_OPCODE op = p->op & J_TABLE_BITS; Icode c = *p; if (op == J_SETSPENV) { c.r3.i = Dump_NoteSharedBindList(p->r3.bl); c.r2.i = Dump_NoteSharedBindList(p->r2.bl); } else if (op == J_SETSPGOTO) { c.r2.i = Dump_NoteSharedBindList(p->r2.bl); } else if (uses_stack(op) || op == J_CALLK || op==J_ADCON || op == J_INIT || op == J_INITF || op == J_INITD) { c.r3.i = Dump_BinderRef(p->r3.b); } fwrite(&c, sizeof(Icode), 1, f); } } } } #endif /* NO_DUMP_STATE */
kirill-strizhak-zz/online-chess
src/main/java/ks3/oc/conn/handlers/HandshakeHandler.java
<filename>src/main/java/ks3/oc/conn/handlers/HandshakeHandler.java package ks3.oc.conn.handlers; import ks3.oc.Protocol; import ks3.oc.chat.ChatDisplay; import ks3.oc.main.MainWindow; import java.io.BufferedReader; import java.io.IOException; abstract class HandshakeHandler implements MessageHandler { protected final MainWindow main; protected final ChatDisplay chat; protected final BufferedReader reader; HandshakeHandler(BufferedReader reader, ChatDisplay chat, MainWindow main) { this.reader = reader; this.chat = chat; this.main = main; } void readName() throws IOException { String name = reader.readLine(); main.setOpponentName(name); chat.addChatLine("* " + name + " connected", Protocol.SYSTEM); } }
safetydank/resinlib
src/resin/materials/ShaderMaterial.cpp
<reponame>safetydank/resinlib #include "resin/materials/ShaderMaterial.h" namespace RESIN { ShaderMaterialRef ShaderMaterial::create() { return ShaderMaterialRef(new ShaderMaterial); } ShaderMaterial::ShaderMaterial() : Material(kShaderMaterial) { fragmentShader("void main() {}"); vertexShader("void main() {}"); // uniforms = {}; // defines = {}; // attributes = null; // shading = THREE.SmoothShading; linewidth(1.0f); wireframe(false); wireframeLinewidth(1.0f); fog(false); // set to use scene fog lights(false); // set to use scene lights // vertexColors = THREE.NoColors; // set to use "color" attribute stream skinning(false); // set to use skinning attribute streams morphTargets(false); // set to use morph targets morphNormals(false); // set to use morph normals // When rendered geometry doesn't include these attributes but the material does, // use these default values in WebGL. This avoids errors when buffer data is missing. defaultAttributeValues = { { "color", newAttribute<'c'>(1) }, // { "uv" : [ 0, 0 ] }, // { "uv2" : [ 0, 0 ] } }; // Color().setRGB(1.0f, 1.0f, 1.0f); } }
avigad/boole
boole/core/expr.py
# -*- coding: utf-8 -*- ############################################################################# # # expr.py # # description: types and expressions in Boole, all constructors inherit from # the Expr class, except Tele, which inherits from BaseExpr # # # Authors: # <NAME> # <NAME> # # ############################################################################## from expr_base import * import vargen ############################################################################## # # Expressions and types: these implement the term language of a dependent, # extensional, impredicative and classical type theory, With subtyping. # # # The datatype is represented by: # # Expr := Type | Kind | Bool | Const(string,Expr) | DB(int) | # Pi(name,Expr,Expr) | App(Expr,Expr,Expr) | # Abst(name,Expr,Expr) | Sig(name,Expr,Expr) | # Pair(Expr,Expr,Type) | Fst(Expr) | Snd(Expr) | # Ev(Tele) | # Forall(name,Expr,Expr) | Exists(name,Expr,Expr) | # Sub(Expr,Expr) | Box(Expr,Expr,Expr) # # Tele := Tele([name,...,name],[Expr,...,Expr]) # ############################################################################### class Const(Expr): """A constant declaration. Variables and constants are identified. """ def __init__(self, name, type, value=None, **kwargs): """ Arguments: - `name`: A name representing the constant - `type`: an expression representing its type - `value`: possibly a semantic value, making this an interpreted constant """ Expr.__init__(self) self.name = name self.type = type self.value = value for k in kwargs: self.info[k] = kwargs[k] self._hash = hash(('Const', self.name, self.type)) def accept(self, visitor, *args, **kwargs): """The accept method allows the definition of recursive functions over objects of type expr. Arguments: - `visitor`: an object of class ExprVisitor - `*args`: arguments to the visitor instance - `**kwargs`: named arguments to the visitor instance """ return visitor.visit_const(self, *args, **kwargs) def to_string(self): return self.name def is_const(self): return True def eq(self, expr): """Structural equality. Simply compares names. Arguments: - `expr`: an expression """ if expr.is_const(): return self.name == expr.name else: return False class DB(Expr): """A bound index represented by a De Bruijn variable. a De Bruijn variable generally does not to be initialized as it is incremented while moving through a term """ def __init__(self, index): """ """ Expr.__init__(self) self.index = index self._hash = hash(("DB", self.index)) def incr(self, inc): """Increment the index Arguments: - `inc`: integer specifying the increment. """ self.index += inc def decr(self): """Decrement the index by 1 """ if self.index == 0: raise ExprError("Cannot decrement a DB\ variable with index 0", self) else: self.index -= 1 def accept(self, visitor, *args, **kwargs): """The accept method allows the definition of recursive functions over objects of type expr. Arguments: - `visitor`: an object of class ExprVisitor - `*args`: arguments to the visitor instance - `**kwargs`: named arguments to the visitor instance """ return visitor.visit_db(self, *args, **kwargs) def to_string(self): return "DB({0!s})".format(self.index) def is_db(self): return True def eq(self, expr): """Structural equality. Arguments: - `expr`: an expression """ if expr.is_db(): return self.index == expr.index else: return False class Type(Expr): """The type of all small types """ def __init__(self): """ """ Expr.__init__(self) self.name = 'Type' self._hash = hash('Type') def accept(self, visitor, *args, **kwargs): """The accept method allows the definition of recursive functions over objects of type expr. Arguments: - `visitor`: an object of class ExprVisitor - `*args`: arguments to the visitor instance - `**kwargs`: named arguments to the visitor instance """ return visitor.visit_type(self, *args, **kwargs) def to_string(self): return "Type()" def is_type(self): return True def eq(self, expr): """Structural equality. Arguments: - `expr`: an expression """ return expr.is_type() class Kind(Expr): """The type of all large types """ def __init__(self): """ """ Expr.__init__(self) self._hash = hash('Kind') def accept(self, visitor, *args, **kwargs): """The accept method allows the definition of recursive functions over objects of type expr. Arguments: - `visitor`: an object of class ExprVisitor - `*args`: arguments to the visitor instance - `**kwargs`: named arguments to the visitor instance """ return visitor.visit_kind(self, *args, **kwargs) def to_string(self): return "Kind()" def is_kind(self): return True def eq(self, expr): """Structural equality. Arguments: - `expr`: an expression """ return expr.is_kind() class Bool(Expr): """The type of all propositions. """ def __init__(self): """ """ Expr.__init__(self) self.name = 'Bool' self._hash = hash('Bool') def accept(self, visitor, *args, **kwargs): """The accept method allows the definition of recursive functions over objects of type expr. Arguments: - `visitor`: an object of class ExprVisitor - `*args`: arguments to the visitor instance - `**kwargs`: named arguments to the visitor instance """ return visitor.visit_bool(self, *args, **kwargs) def to_string(self): return "Bool()" def is_bool(self): return True def eq(self, expr): """Structural equality. Arguments: - `expr`: an expression """ return expr.is_bool() class Bound(Expr): """An expression consisting of a binder, a domain, and a term which binds a variable of that domain. """ def __init__(self, binder, dom, body): """ Arguments: - `binder`: an element of the Binder class - `dom`: an expression denoting the domain of the variable - `body`: an expression with a bound variable. """ Expr.__init__(self) self.binder = binder self.dom = dom self.body = body self._hash = hash(("Bound", self.binder, self.dom, self.body)) def accept(self, visitor, *args, **kwargs): """The accept method allows the definition of recursive functions over objects of type expr. Arguments: - `visitor`: an object of class ExprVisitor - `*args`: arguments to the visitor instance - `**kwargs`: named arguments to the visitor instance """ return visitor.visit_bound(self, *args, **kwargs) def to_string(self): # Printing a bound expression involves # substituting the DB index by a constant # with the appropriate name. var = self.binder.var open_self = open_expr(var, self.dom, self.body, None) return "{0!s}({1!s}, {2!s})".format(\ self.binder.name, self.binder.var, open_self) def to_string_raw(self): return "{0!s}({1!s}, {2!s}, {3!s})".format(\ self.binder.name, self.binder.var, self.dom, self.body) def is_bound(self): return True def eq(self, expr): """Structural equality. Arguments: - `expr`: an expression """ if expr.is_bound() and (self.binder.name == expr.binder.name): return self.dom.equals(expr.dom) and self.body.equals(expr.body) else: return False class App(Expr): """Applications. Carries the proof of well-formedness """ def __init__(self, conv, fun, arg): """ Arguments: - `conv`: A term representing evidence that the application is well-typed. - `fun`: The functional part of the application. - `arg`: The argument part of the application. """ Expr.__init__(self) self.conv = conv self.fun = fun self.arg = arg self._hash = hash(("App", self.fun, self.arg)) def accept(self, visitor, *args, **kwargs): """The accept method allows the definition of recursive functions over objects of type expr. Arguments: - `visitor`: an object of class ExprVisitor - `*args`: arguments to the visitor instance - `**kwargs`: named arguments to the visitor instance """ return visitor.visit_app(self, *args, **kwargs) def to_string(self): """ Arguments: - `self`: """ return "App({0!s},{1!s},{2!s})".format(self.conv, self.fun, self.arg) def is_app(self): return True def eq(self, expr): """Structural equality. Arguments: - `expr`: an expression """ if expr.is_app(): return self.fun.equals(expr.fun) and self.arg.equals(expr.arg) else: return False class Pair(Expr): """Elements of Sigma types. They need to carry around their type, for type-checking to be decidable. """ def __init__(self, fst, snd, type): """ Arguments: - `fst`: an expression denoting the first component - `snd`: an expression denoting the second component - `type`: an expression """ Expr.__init__(self) self.fst = fst self.snd = snd self.type = type self._hash = hash(("Pair", self.type, self.fst, self.snd)) def accept(self, visitor, *args, **kwargs): """The accept method allows the definition of recursive functions over objects of type expr. Arguments: - `visitor`: an object of class ExprVisitor - `*args`: arguments to the visitor instance - `**kwargs`: named arguments to the visitor instance """ return visitor.visit_pair(self, *args, **kwargs) def to_string(self): return "Pair({0!s},{1!s},{2!s})".\ format(self.fst, self.snd, self.type) def is_pair(self): return True def eq(self, expr): """Structural equality. Arguments: - `expr`: an expression """ if expr.is_pair(): return self.fst.equals(expr.fst) and \ self.snd.equals(expr.snd) and \ self.type.equals(expr.type) else: return False class Fst(Expr): """First projection for Sigma types """ def __init__(self, expr): """ Arguments: - `expr`: the expression to which is applied the projection. """ Expr.__init__(self) self.expr = expr self._hash = hash(("Fst", self.expr)) def accept(self, visitor, *args, **kwargs): """The accept method allows the definition of recursive functions over objects of type expr. Arguments: - `visitor`: an object of class ExprVisitor - `*args`: arguments to the visitor instance - `**kwargs`: named arguments to the visitor instance """ return visitor.visit_fst(self, *args, **kwargs) def to_string(self): """ Arguments: - `self`: """ return "Fst({0!s})".format(self.expr) def is_fst(self): return True def equals(self, expr): """Structural equality. Arguments: - `expr`: an expression """ if expr.is_fst(): return self.expr.equals(expr.expr) else: return False class Snd(Expr): """Second projection for Sigma types """ def __init__(self, expr): """ Arguments: - `expr`: the expression to which is applied the projection. """ Expr.__init__(self) self.expr = expr self._hash = hash(("Snd", self.expr)) def accept(self, visitor, *args, **kwargs): """The accept method allows the definition of recursive functions over objects of type expr. Arguments: - `visitor`: an object of class ExprVisitor - `*args`: arguments to the visitor instance - `**kwargs`: named arguments to the visitor instance """ return visitor.visit_snd(self, *args, **kwargs) def to_string(self): """ Arguments: - `self`: """ return "Snd({0!s})".format(self.expr) def is_snd(self): return True def eq(self, expr): """Structural equality. Arguments: - `expr`: an expression """ if expr.is_snd(): return self.expr.equals(expr.expr) else: return False class Ev(Expr): """Evidence type: provides evidence for a proposition (of type Bool) """ def __init__(self, tele): """ Arguments: - `tele`: a telescope of evidence for a proposition - `goals`: None, or a pointer to a set of goals, which may be solved by tactic applications. """ Expr.__init__(self) self.tele = tele self.goals = None self._hash = hash("Ev") def accept(self, visitor, *args, **kwargs): """The accept method allows the definition of recursive functions over objects of type expr. Arguments: - `visitor`: an object of class ExprVisitor - `*args`: arguments to the visitor instance - `**kwargs`: named arguments to the visitor instance """ return visitor.visit_ev(self, *args, **kwargs) def to_string(self): return "Ev({0!s})".format(self.tele) def is_ev(self): return True def eq(self, expr): """Structural equality. Does not compare telescopes! Arguments: - `expr`: an expression """ if expr.is_ev(): return True else: return False def show_proof(self): """Show the proof of the goal set containing the goal generated by self, if there is one. """ if self.goals is None: print "No proof!" print prf = map(lambda x: str(x[1]), self.goals.history) print ", ".join(prf) print class Sub(Expr): """The subtype relation. Makes sense regardless of the type of the expressions. """ def __init__(self, lhs, rhs): """ Arguments: - `lhs`: an expression - `rhs`: an expression """ Expr.__init__(self) self.lhs = lhs self.rhs = rhs self._hash = hash(("Sub", self.lhs, self.rhs)) def accept(self, visitor, *args, **kwargs): """The accept method allows the definition of recursive functions over objects of type expr. Arguments: - `visitor`: an object of class ExprVisitor - `*args`: arguments to the visitor instance - `**kwargs`: named arguments to the visitor instance """ return visitor.visit_sub(self, *args, **kwargs) def to_string(self): """ Arguments: - `self`: """ return "Sub({0!s}, {1!s})".format(self.lhs, self.rhs) def is_sub(self): return True def eq(self, expr): """Structural equality. Arguments: - `expr`: an expression """ if expr.is_sub(): return (self.lhs.equals(expr.lhs)) and (self.rhs.equals(expr.rhs)) else: return False class Box(Expr): """Boxed epressions: a boxed expression carries a an expression, a type and a witness that the type of the expression is a subtype of the given type. """ def __init__(self, conv, expr, type): """ Arguments: - `conv`: A witness to the equality between the type of expr and type - `expr`: The expression denoted by the box - `type`: The type assigned to expr """ Expr.__init__(self) self.conv = conv self.expr = expr self.type = type self._hash = hash(("Box", self.expr)) def accept(self, visitor, *args, **kwargs): """The accept method allows the definition of recursive functions over objects of type expr. Arguments: - `visitor`: an object of class ExprVisitor - `*args`: arguments to the visitor instance - `**kwargs`: named arguments to the visitor instance """ return visitor.visit_box(self, *args, **kwargs) def to_string(self): return "Box({0!s},{1!s},{2!s})".format(self.conv, self.expr, self.type) def is_box(self): return True def eq(self, expr): """Structural equality. Arguments: - `expr`: an expression """ if expr.is_box(): return self.expr.equals(expr.expr) else: return False ############################################################################## # # The class of variable binders: this includes Pi, Abst, forall/exists # and Sig # ############################################################################### class Binder(object): """The class of Expression binders. """ def __init__(self, var): """ Arguments: - `var`: a variable name """ self.var = var self._hash = None def is_pi(self): return False def is_abst(self): return False def is_forall(self): return False def is_exists(self): return False def is_sig(self): return False def __hash__(self, ): return self._hash class Pi(Binder): """Dependent product """ def __init__(self, var): Binder.__init__(self, var) self.name = "pi" self._hash = hash("Pi") def is_pi(self): return True class Sig(Binder): """Dependent sum """ def __init__(self, var): Binder.__init__(self, var) self.name = "sig" self._hash = hash("Sig") def is_sig(self): return True class Abst(Binder): """Abstraction """ def __init__(self, var): Binder.__init__(self, var) self.name = "abst" self._hash = hash("Abst") def is_abst(self): return True class Forall(Binder): """Universal quantification """ def __init__(self, var): Binder.__init__(self, var) self.name = "forall" self._hash = hash("Forall") def is_forall(self): return True class Exists(Binder): """Existential quantification """ def __init__(self, var): Binder.__init__(self, var) self.name = "exists" self._hash = hash("Exists") def is_exists(self): return True ############################################################################### # # The Tele class represents a telescope. # ############################################################################### class Tele(Expr): """A telescope is a (possible) list of names and expressions, each expression may depend on the previous ones. """ def __init__(self, vars, types): """ Arguments: - `vars`: the names of the variable associated to each expression. - `types`: a list of types. Each type binds a variable of the previous type. """ Expr.__init__(self) self.info = info.DefaultInfo() self.vars = vars self.types = types self.len = len(self.types) assert(len(self.vars) == self.len) self._hash = hash(("Tuple", tuple(self.types))) def accept(self, visitor, *args, **kwargs): """The accept method allows the definition of recursive functions over objects of type expr. Arguments: - `visitor`: an object of class ExprVisitor - `*args`: arguments to the visitor instance - `**kwargs`: named arguments to the visitor instance """ return visitor.visit_tele(self, *args, **kwargs) def to_string(self): """ Arguments: - `self`: """ var_str = ', '.join(self.vars) ty_str = ', '.join(map(str, self.types)) return "Tele([{0!s}], [{1!s}])".format(var_str, ty_str) def eq(self, tele): """Structural equality. Arguments: - `expr`: an expression """ if self.len == tele.len: eq_info = [t1.equals(t2)\ for (t1, t2) in zip(self.types, tele.types)] return reduce(lambda x, y: x and y, eq_info, True) else: return False def __str__(self): """Call the printer implemented in info """ try: return self.info['__str__'](self) except KeyError: raise AttributeError('__str__') def __len__(self): return self.len def append(self, var, ty): """Add a variable and a type to the telescope. Side-effect free: returns a telescope Arguments: - `var`: a variable - `ty`: an expression """ return Tele(self.vars + [var], self.types + [ty]) def concat(self, tele): """Same as above, but for concatenation Arguments: - `tele`: """ return Tele(self.vars + tele.vars, self.types + tele.types) def pop(self, i=None): """Pop the i-th (last by default) argument of a telescope return the pair (name, type) Arguments: - `i`: an integer """ if i is None: return (self.vars.pop(), self.types.pop()) else: return (self.vars.pop(i), self.types.pop(i)) def open_tele(tele, vars, checked=False): """Takes a telescope and returns a list of pairs (constant, type) where the subsequent types may depend on the constant. Arguments: - `tele`: a telescope """ opened_ty = tele.types consts = [] for i in range(0, tele.len): opened_ty[i] = subst_expr(consts, opened_ty[i], is_open=True) x = Const(vars[i], opened_ty[i], checked=checked) consts.append(x) return (consts, opened_ty) def open_tele_default(tele): """Open a telescope with the default variables provided by the telescope definition. Arguments: - `tele`: a telescope """ return open_tele(tele, tele.vars) def open_tele_fresh(tele, checked=False): """Open a telescope with fresh variables Arguments: - `tele`: a telescope """ fr_vars = [fresh_name.get_name(v) for v in tele.vars] return open_tele(tele, fr_vars, checked=checked) ############################################################################## # # We add a new constructor to the Expr class: it represents meta-variables # which can be given a value when determined to be equal to an expression # by unification. # ############################################################################## class Mvar(Expr): """Unification variables for implicit arguments """ def __init__(self, name, type): """ Same definition as for Const, without info fields and the additional information for: - potential value, - the conext in which it was created (to be used when finding a value) - the pending abstractions to be applied to the final value when found. """ Expr.__init__(self) self.name = name self.type = type self._value = None self.tele = nullctxt() self.pending = [] self._hash = hash(("Mvar", self.name, self.type)) def accept(self, visitor, *args, **kwargs): return visitor.visit_mvar(self, *args, **kwargs) def set_val(self, val): """Give a value to the meta-variable Arguments: - `val`: an expression """ #update the info field to correspond to that #of the value: this makes mvar substitution #behave correctly with respect to info self.info = val.info self._value = val def to_string(self): return "?{0!s}".format(self.name) def is_mvar(self): """Tests whether the expression is an instance of Mvar """ return True def eq(self, expr): #There should only be one instance of #each meta-variable, so we use pointer equality return self is expr def has_value(self): """Returns True if the expression has a value """ return not (self._value is None) def clear(self): """Clear the value and the information of the meta-variable. """ self.info = info.DefaultInfo() self._value = None ############################################################################## # # The type of Pending substitution and abstraction operations. # These are performed as the meta-variable is instantiated to a value # ############################################################################## class Pending(object): pass class PendAbs(Pending): """A pending abstraction """ def __init__(self, names, depth): """ Arguments: - `names`: """ Pending.__init__(self) self.names = names self.depth = depth def now(self, expr): """Evaluate the abstraction Arguments: - `expr`: """ return AbstractExpr(self.names).visit(expr, self.depth) def __str__(self): return "PendAbs({0!s}, {1!s})".format(self.names, self.depth) class PendSub(Pending): """A pending Substitution """ def __init__(self, exprs, depth): """ Arguments: - `names`: """ Pending.__init__(self) self.exprs = exprs self.depth = depth def now(self, expr): """Evaluate the substitution Arguments: - `expr`: """ return SubstExpr(self.exprs).visit(expr, self.depth) def __str__(self): return "PendSub({0!s}, {1!s})".format(self.exprs, self.depth) ############################################################################### # # The visitor class for Expr and Tele # ############################################################################### class ExprVisitor(object): """The visitor class for Expr and Tele """ def __init__(self): """Do nothing by default. """ pass def visit_const(self, expr, *args, **kwargs): raise NotImplementedError() def visit_db(self, expr, *args, **kwargs): raise NotImplementedError() def visit_type(self, expr, *args, **kwargs): raise NotImplementedError() def visit_kind(self, expr, *args, **kwargs): raise NotImplementedError() def visit_bool(self, expr, *args, **kwargs): raise NotImplementedError() def visit_bound(self, expr, *args, **kwargs): raise NotImplementedError() def visit_app(self, expr, *args, **kwargs): raise NotImplementedError() def visit_pair(self, expr, *args, **kwargs): raise NotImplementedError() def visit_fst(self, expr, *args, **kwargs): raise NotImplementedError() def visit_snd(self, expr, *args, **kwargs): raise NotImplementedError() def visit_ev(self, expr, *args, **kwargs): raise NotImplementedError() def visit_sub(self, expr, *args, **kwargs): raise NotImplementedError() def visit_box(self, expr, *args, **kwargs): raise NotImplementedError() def visit_tele(self, expr, *args, **kwargs): raise NotImplementedError() def visit_mvar(self, expr, *args, **kwargs): raise NotImplementedError() def visit(self, expr, *args, **kwargs): """Call the appropriate method of self on expr depending on its form. Arguments: - `expr`: an expression """ return expr.accept(self, *args, **kwargs) ############################################################################### # # Locally nameless representation utility functions: # binding and freeing variables. # ############################################################################### class AbstractExpr(ExprVisitor): """Abstract an expression over a list of names, in the locally nameless approach. Return the updated expression. The names should be distinct. """ def __init__(self, names): """ Arguments: - `names`: a list of strings """ ExprVisitor.__init__(self) self.names = names def visit_const(self, expr, depth): """ Arguments: - `expr`: an expression. - `depth`: the number of binders crossed. """ if expr.name in self.names: index = depth + self.names.index(expr.name) return DB(index) else: return expr def visit_db(self, expr, *args, **kwargs): return DB(expr.index) def visit_type(self, expr, *args, **kwargs): return Type() def visit_kind(self, expr, *args, **kwargs): return Kind() def visit_bool(self, expr, *args, **kwargs): return Bool() def visit_bound(self, expr, depth): """ Arguments: - `expr`: an expression. - `depth`: the number of binders crossed. """ dom = self.visit(expr.dom, depth) b_body = self.visit(expr.body, depth + 1) return Bound(expr.binder, dom, b_body) def visit_app(self, expr, *args, **kwargs): conv = self.visit(expr.conv, *args, **kwargs) fun = self.visit(expr.fun, *args, **kwargs) arg = self.visit(expr.arg, *args, **kwargs) return App(conv, fun, arg) def visit_pair(self, expr, *args, **kwargs): type = self.visit(expr.type, *args, **kwargs) fst = self.visit(expr.fst, *args, **kwargs) snd = self.visit(expr.snd, *args, **kwargs) return Pair(fst, snd, type) def visit_fst(self, expr, *args, **kwargs): sub_expr = self.visit(expr.expr, *args, **kwargs) return Fst(sub_expr) def visit_snd(self, expr, *args, **kwargs): sub_expr = self.visit(expr.expr, *args, **kwargs) return Snd(sub_expr) def visit_ev(self, expr, *args, **kwargs): tele = self.visit(expr.tele, *args, **kwargs) return Ev(tele) def visit_sub(self, expr, *args, **kwargs): lhs = self.visit(expr.lhs, *args, **kwargs) rhs = self.visit(expr.rhs, *args, **kwargs) return Sub(lhs, rhs) def visit_box(self, expr, *args, **kwargs): conv = self.visit(expr.conv, *args, **kwargs) expr_cast = self.visit(expr.expr, *args, **kwargs) type = self.visit(expr.type, *args, **kwargs) return Box(conv, expr_cast, type) def visit_mvar(self, expr, depth): expr.tele = self.visit(expr.tele, depth) #This code should not be needed # print "Abstracting over", self.names[0] # expr.pending.append(e.PendAbs(self.names, depth)) # return the actual object here, as we want the value to # be propagated at each instance of the meta-variable return expr def visit_tele(self, expr, depth): types = [] for i, e in enumerate(expr.types): abs_e = self.visit(e, depth + i) types.append(abs_e) return Tele(expr.vars, types) @info.same_info def visit(self, expr, *args, **kwargs): return expr.accept(self, *args, **kwargs) def abstract_expr(vars, expr): """Abstract a list of variables in an expression. Arguments: - `var_list`: a list of variable names - `expr`: an expression """ abstractor = AbstractExpr(vars) return abstractor.visit(expr, 0) class SubstExpr(ExprVisitor): """Given a list of expressions e0,...,en instantiate the DB indices 0,...,n with those terms. """ def __init__(self, exprs, is_open=None): """ Arguments: - `exprs`: the expressions to instantiate. """ ExprVisitor.__init__(self) self.exprs = exprs self.len = len(self.exprs) self.is_open = is_open def visit_const(self, expr, *args, **kwargs): if self.is_open: return expr else: ty = self.visit(expr.type, *args, **kwargs) return Const(expr.name, ty) def visit_db(self, expr, depth): if expr.index < depth: return DB(expr.index) elif expr.index < depth + self.len: return self.exprs[expr.index - depth] else: return DB(expr.index) # raise ExprError("Unbound DB variable", expr) def visit_type(self, expr, *args, **kwargs): return Type() def visit_kind(self, expr, *args, **kwargs): return Kind() def visit_bool(self, expr, *args, **kwargs): return Bool() def visit_bound(self, expr, depth): dom = self.visit(expr.dom, depth) b_expr = self.visit(expr.body, depth + 1) return Bound(expr.binder, dom, b_expr) def visit_app(self, expr, *args, **kwargs): conv = self.visit(expr.conv, *args, **kwargs) fun = self.visit(expr.fun, *args, **kwargs) arg = self.visit(expr.arg, *args, **kwargs) return App(conv, fun, arg) def visit_pair(self, expr, *args, **kwargs): type = self.visit(expr.type, *args, **kwargs) fst = self.visit(expr.fst, *args, **kwargs) snd = self.visit(expr.snd, *args, **kwargs) return Pair(fst, snd, type) def visit_fst(self, expr, *args, **kwargs): sub_expr = self.visit(expr.expr, *args, **kwargs) return Fst(sub_expr) def visit_snd(self, expr, *args, **kwargs): sub_expr = self.visit(expr.expr, *args, **kwargs) return Snd(sub_expr) def visit_ev(self, expr, *args, **kwargs): tele = self.visit(expr.tele, *args, **kwargs) return Ev(tele) def visit_sub(self, expr, *args, **kwargs): lhs = self.visit(expr.lhs, *args, **kwargs) rhs = self.visit(expr.rhs, *args, **kwargs) return Sub(lhs, rhs) def visit_box(self, expr, *args, **kwargs): conv = self.visit(expr.conv, *args, **kwargs) expr_cast = self.visit(expr.expr, *args, **kwargs) type = self.visit(expr.type, *args, **kwargs) return Box(conv, expr_cast, type) def visit_mvar(self, expr, depth): expr.tele = self.visit(expr.tele, depth) #We record the opens performed on an Mvar, and apply #them in reverse as it is substituted by its value if self.is_open: names = [exp.name for exp in self.exprs] expr.pending.append(PendAbs(names, depth)) # expr.pending.append(PendSub(self.exprs, depth)) return expr def visit_tele(self, expr, depth): types = [] for i, e in enumerate(expr.types): abs_e = self.visit(e, depth + i) types.append(abs_e) return Tele(expr.vars, types) @info.same_info def visit(self, expr, *args, **kwargs): return expr.accept(self, *args, **kwargs) def subst_expr(exprs, expr, is_open=None): """Instantiate DB indices in expr according to expr_list Arguments: - `expr_list`: a list of expressions - `expr`: an expression """ if is_open != None: subster = SubstExpr(exprs, is_open=is_open) else: subster = SubstExpr(exprs) return subster.visit(expr, 0) def sub_in(exprs, vars, expr): """Replace constants with names given by vars by exprs in expr. Arguments: - `exprs`: a list of expressions - `vars`: a list of variable names - `expr`: an expression """ return subst_expr(exprs, abstract_expr(vars, expr)) def open_expr(var, typ, expr, checked): """Return the opened version of an expression with a bound variable, by substituting the bound name with a constant of type typ. Arguments: - `var`: a variable name - `typ`: a type - `expr`: an expression with a bound variable - `checked`: marks weather typ has been checked for well-typedness """ if checked == None: const = Const(var, typ, checked=True) else: const = Const(var, typ, checked=checked) return subst_expr([const], expr, is_open=True) def open_bound_fresh(expr, checked=None): """Return the opened body of a bound expression using the variable from the binder to generate a fresh name, along with the variable name. The constant is marked as type-checked by default. Arguments: - `expr`: an instance of Bound """ assert(expr.is_bound()) var = fresh_name.get_name(expr.binder.var, free_vars(expr.body)) return (var, open_expr(var, expr.dom, expr.body, checked)) def open_bound_fresh_const(expr): """Returns the pair (v, b) where v is a variable, b is an expression, and expr is the result of binding v in b expr.binder. """ assert(expr.is_bound()) var = fresh_name.get_name(expr.binder.var, free_vars(expr.body)) return (Const(var, expr.dom), open_expr(var, expr.dom, expr.body, None)) def open_bound_fresh_consts(expr): """Returns the pair (vlist, b) where vlist is a list of variables, b is an expression, and expr is the result of iteratively binding the variables in vlist in b, using the same binder. """ assert(expr.is_bound()) b = expr vlist = [] while b.is_bound() and b.binder.name == expr.binder.name\ and str(b.info) == str(expr.info): v, b = open_bound_fresh_const(b) vlist.append(v) return (vlist, b) ############################################################################### # # Various utility functions. # ############################################################################### def nullctxt(): """The empty telescope """ return Tele([], []) def root_app(expr): """Returns the pair (r, args) such that expr = r(*args) Arguments: - `expr`: an expression """ root = expr args = [] while root.is_app(): args.append(root.arg) root = root.fun #The arguments were collected in reverse order args.reverse() return (root, args) def root_pi(expr): """Returns the pair (r, [an,..,a0]) such that expr = Pi(a0, Pi(.. Pi(an, r)..) Arguments: - `expr`: an expression """ root = expr args = [] while root.is_pi(): args.append(root.dom) _, root = open_bound_fresh(root) return (root, args) def arg_i(expr, i): """Takes an expresion of the form f(a0,..., an) and returns ai, fails if the argument is not of the correct form. Arguments: - `expr`: an expression - `i`: an integer """ _, args = root_app(expr) return args[i] def is_eq(expr): """Returns True if the expression is of the form eq(e1, e2), False otherwise. Arguments: - `expr`: """ root, args = root_app(expr) #There is an implicit type argument return root.is_const() and (root.name == '==') and (len(args) == 3) def is_impl(expr): """Returns True if the expression is of the form implies(e1, e2), False otherwise. Arguments: - `expr`: """ root, args = root_app(expr) # TODO: hardcoding the name of implication here is inelegant return root.is_const() and root.name == 'implies' and \ len(args) == 2 def root_clause(expr): """Returns r such that expr is of the form forall(x1,...,forall(xn, p1 >= (p2 >= ... (pm >= r)))) replacing xi with fresh variables Arguments: - `expr`: an expression """ root = expr while root.is_forall(): _, root = open_bound_fresh(root) while is_impl(root): root = arg_i(root, 1) return root def sig_to_tele(expr, open_bound): """Takes a sigma type S = Sig(x1:A1,Sig(x2:A2,...,An+1)..) and returns the telescope: [x1:A1,...,xn:An,h:An+1] Arguments: - `expr`: an expression - `open_bound`: a function which opens binders """ sig_ty = expr tele = Tele([], []) while sig_ty.is_sig(): v, new_ty = open_bound(sig_ty) tele = tele.append(v, sig_ty.dom) sig_ty = new_ty hyp = fresh_name.get_name('hyp') return tele.append(hyp, sig_ty) def unpack_sig(expr, names): """Takes a sigma type S = Sig(x1:A1,Sig(x2:A2,...,An)..) and returns the dependent tuple (x1, (x2,(...,h)..) with xi : Ai and h : An Arguments: - `expr`: an expression -`names`: either None, or a list of names to give to the projections. """ sig_ty = expr tup = [] if names is None: proj_names = [] else: proj_names = names[:] proj_names.reverse() while sig_ty.is_sig(): v, new_ty = open_bound_fresh(sig_ty) try: #FIXME: possible name capture n = proj_names.pop() except IndexError: n = v c = Const(n, sig_ty.dom) tup.append((c, sig_ty)) sig_ty = new_ty try: n = proj_names.pop() except IndexError: n = fresh_name.get_name('h') c = Const(n, sig_ty) if len(tup) == 0: return c else: ret = c while len(tup) != 0: fst, ty = tup.pop() ret = Pair(fst, ret, ty) return ret class FreeVars(ExprVisitor): """Returns the list of free variables of an expression. """ def __init__(self): ExprVisitor.__init__(self) def visit_const(self, expr, *args, **kwargs): return self.visit(expr.type, *args, **kwargs) + \ [expr] def visit_db(self, expr, *args, **kwargs): return [] def visit_type(self, expr, *args, **kwargs): return [] def visit_kind(self, expr, *args, **kwargs): return [] def visit_bool(self, expr, *args, **kwargs): return [] def visit_bound(self, expr, *args, **kwargs): return self.visit(expr.dom, *args, **kwargs) + \ self.visit(expr.body, *args, **kwargs) def visit_app(self, expr, *args, **kwargs): return self.visit(expr.conv, *args, **kwargs) + \ self.visit(expr.fun, *args, **kwargs) + \ self.visit(expr.arg, *args, **kwargs) def visit_pair(self, expr, *args, **kwargs): return self.visit(expr.fst, *args, **kwargs) + \ self.visit(expr.snd, *args, **kwargs) + \ self.visit(expr.type, *args, **kwargs) def visit_fst(self, expr, *args, **kwargs): return self.visit(expr.expr, *args, **kwargs) def visit_snd(self, expr, *args, **kwargs): return self.visit(expr.expr, *args, **kwargs) def visit_ev(self, expr, *args, **kwargs): return self.visit(expr.tele, *args, **kwargs) def visit_sub(self, expr, *args, **kwargs): return self.visit(expr.lhs, *args, **kwargs) + \ self.visit(expr.rhs, *args, **kwargs) def visit_box(self, expr, *args, **kwargs): return self.visit(expr.conv, *args, **kwargs) + \ self.visit(expr.expr, *args, **kwargs) + \ self.visit(expr.type, *args, **kwargs) def visit_mvar(self, expr, *args, **kwargs): return self.visit(expr.tele, *args, **kwargs) def visit_tele(self, expr, *args, **kwargs): tele_vars = [v for ty in expr.types\ for v in self.visit(ty, *args, **kwargs)] return tele_vars def free_vars(expr): """returns the list of free variables of an expression Arguments: - `expr`: """ l = FreeVars().visit(expr) return [e.name for e in l] ############################################################################## # # Global fresh variable generator for expressions # ############################################################################## fresh_name = vargen.VarGen()
MadBomber/synvert-snippets
spec/rails/add_application_job_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Add ApplicationMailer' do let(:rewriter_name) { 'rails/add_application_mailer' } context 'add application_mailer' do let(:fake_file_path) { 'app/mailers/application_mailer.rb' } let(:test_content) { nil } let(:test_rewritten_content) { <<~EOS } class ApplicationMailer < ActionMailer::Base end EOS include_examples 'convertable' end context 'rename ActionMailer::Base' do let(:fake_file_path) { 'app/mailers/user_mailer.rb' } let(:test_content) { <<~EOS } class UserMailer < ActionMailer::Base end EOS let(:test_rewritten_content) { <<~EOS } class UserMailer < ApplicationMailer end EOS include_examples 'convertable' end end
ernestojimenezruiz/logmap-conservativity
src/main/java/scc/gui/OntoLoaderTask.java
<reponame>ernestojimenezruiz/logmap-conservativity<gh_stars>0 /******************************************************************************* * Copyright 2016 by the Department of Computer Science (University of Genova and University of Oxford) * * This file is part of LogMapC an extension of LogMap matcher for conservativity principle. * * LogMapC is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * LogMapC 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with LogMapC. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package scc.gui; import scc.exception.ClassificationTimeoutException; import scc.graphDataStructure.LightAdjacencyList; import java.util.concurrent.ExecutionException; import javax.swing.SwingWorker; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import util.OntoUtil; import util.Params; public class OntoLoaderTask extends SwingWorker<Void, Void> { private VisualDebugger vd; public OntoLoaderTask(VisualDebugger vd){ this.vd = vd; } @Override public Void doInBackground() throws OWLOntologyCreationException, ClassificationTimeoutException { LightAdjacencyList adj = null; try { OntoUtil.unloadAllOntologies(); vd.setAdjancencyList( adj = new LightAdjacencyList( vd.srcOnto,vd.trgOnto,null,true,true,true)); } catch (OWLOntologyCreationException e1) { e1.printStackTrace(); throw new Error("Error while processing selected ontologies."); } adj.loadMappings(vd.mapping, null, Params.fullDetection); adj.computeGlobalSCCsAndProblematicMappings(vd.problematicSCCs, null); return null; } /* * Executed in event dispatch thread */ public void done() { try { get(); } catch (InterruptedException | ExecutionException e1) { e1.printStackTrace(); System.exit(1); } vd.resetListAndPanel(); vd.showSCCs(vd.problematicSCCs); vd.setComputingStatus(false); vd.statusLabel.setText("Analysis completed"); vd.jLabelFilesSelected.setText(" - " + vd.problematicSCCs.size() + " SCCs detected" + vd.jLabelFilesSelected.getText()); vd.jButtonSaveMapping.setEnabled(true); vd.setSCCButtons(false); vd.clearDiagnosesFilters(); } }
torchOnVideo/torchOnVideo
torchOnVideo/frame_interpolation/cain/cain.py
from ..frame_interpolation import FrameInterpolation class CAIN(FrameInterpolation): def __init__(self): super(CAIN, self).__init__()