content
stringlengths
10
4.9M
def packet_in_handler(self, ev): msg = ev.msg datapath = msg.datapath ofproto = msg.datapath.ofproto parser = msg.datapath.ofproto_parser dpid = msg.datapath.id pkt = packet.Packet(msg.data) in_port = msg.match['in_port'] data = msg.data if msg.buffer_id == ofproto.OFP_NO_BUFFER else None actions = [datapath.ofproto_parser.OFPActionOutput(ofproto.OFPP_FLOOD)] out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id, in_port=in_port, actions=actions, data=data) self.logger.info("Sending packet out") datapath.send_msg(out) return
<reponame>piskunovdenis/MemSpy<filename>MemSpy/MemSpy/Sources/Path.hpp #pragma once #include <string> namespace memspy { class Path { static const wchar_t kPathSeparator = L'\\'; public: static std::wstring GetFileName(const std::wstring& fileName); }; }
. Erythropsia or red vision (from the Greek erythros = red, and opsis = sight) is a temporary distortion of colour vision. This phenomenon is a chromatopsia or impaired vision. It consists of seeing all objects with a uniform reddish tint. This vision symptom usually alarms the patient. It is a Little known process and is usually transient. It may be due to benign processes such as post-operative cataracts and drug toxicity or to be a consequence of more serious processes such as vitreous haemorrhage.
/** * An expression condition that evaluates to true if the expression is a call to one of a set of operators. */ static class OperatorExprCondition implements ExprCondition { private final Set<Operator> operatorSet; /** * Creates an OperatorExprCondition. * * @param operatorSet Set of operators */ OperatorExprCondition( Iterable<? extends Operator> operatorSet ) { this.operatorSet = ImmutableSet.copyOf( operatorSet ); } @Override public boolean test( RexNode expr ) { return expr instanceof RexCall && operatorSet.contains( ((RexCall) expr).getOperator() ); } }
Square Wallet. Google Wallet. PayPal. For many years, these mobile payment apps have been heralded as the successors to our overstuffed wallets and purses. Adoption of these services, however, have been slow. It’s driven one startup to launch a crowdfunding campaign for Coin, a physical card that replaces everything in your billfold. It looks just like any other credit card and can be processed by the vast majority of credit card terminals. The low-key device has a small display and a button for cycling through all of your stored cards. Select the one you need for that given moment and then swipe your Coin through the terminal to make a payment. Much of its appeal stems from the comfort and familiarity associated with physical cards. With mobile payment apps, there is still a moment of doubt where I wonder if the store will accept the app I’m using, or even know what it is. The effort associated with explaining the service, or dealing with the embarassement when the clerk says they don’t accept it, usually puts me off using it altogether. Even if the person you’re dealing with raises an eyebrow at Coin, they’ll know what to do with it. Just swipe it across the terminal and punch in the amount that needs to be deducted from the card. Furthermore, it doesn’t require any special hardware or software. Coin comes with a small card reader that attaches to the bottom of your smartphone. Using the Coin app for iOS or Android, you can swipe each card in your possession and then take a picture of the information on the front. The card is then stored on the app using 128-bit encryption and synced with your Coin using a Bluetooth Low Energy connection. Once you’re set up though, you won’t need to access the app or your smartphone in order to continue using Coin. This pairing is only required when you need to manage, add or delete cards. Similar to Bikn, Linquet Mini and Button TrackR, Coin also comes with some useful security features. If you leave it behind in a store, bar or restaurant, you’ll be alerted through the companion app. In the event that you lose your Coin, it will also disable itself automatically. To make this device a reality, the team behind Coin is launching a crowdfunding campaign to the tune of $50,000. Each Coin will retail for $100, but you can reserve one for half that price if you get in early. In addition, there’s a $5 discount for every friend you refer. The first units are expected to ship in the summer of next year. In short, this is a card to replace all of your cards. Until mobile payment apps are truly commonplace across the world, Coin seems like the best alternative. It’s similar to the Wallaby Card, although Coin gives you greater control over which credit, debit, or gift card you’re using at any given moment. If it means we can finally leave our wallet or purse at home, we’re certainly interested. ➤ Coin
<gh_stars>0 /* eslint-disable import/first */ /* eslint-disable no-multi-str */ import * as mailer from '../../src/auth-server/mailer' import { InvitationType } from '../../src/persistance/invitation/types' import { RegistrationType } from '../../src/persistance/registration/types' jest.mock('../../src/utils/logger') jest.mock('nodemailer', () => ({ createTransport: jest.fn().mockReturnValue({ sendMail: jest.fn().mockReturnValue((mailoptions:any, callback:any) => {}) }) })) describe('Mailer', () => { it('recoverPassword', async () => { const spy = jest.spyOn(mailer, 'recoverPassword') await mailer.recoverPassword('username', 'token') expect(spy).toHaveBeenCalledTimes(1) }) it('verificationMail', async () => { const spy = jest.spyOn(mailer, 'verificationMail') await mailer.verificationMail('username', 'token', RegistrationType.COMPANY) await mailer.verificationMail('username', 'token', RegistrationType.USER) expect(spy).toHaveBeenCalledTimes(2) }) it('notifyDevOpsOfNewRegistration', async () => { const spy = jest.spyOn(mailer, 'notifyDevOpsOfNewRegistration') await mailer.notifyDevOpsOfNewRegistration('username', 'company') expect(spy).toHaveBeenCalledTimes(1) }) it('rejectRegistration', async () => { const spy = jest.spyOn(mailer, 'rejectRegistration') await mailer.rejectRegistration('username', 'company') expect(spy).toHaveBeenCalledTimes(1) }) it('invitationMail', async () => { const spy = jest.spyOn(mailer, 'invitationMail') await mailer.invitationMail('username', 'id', InvitationType.USER) await mailer.invitationMail('username', 'id', InvitationType.COMPANY) expect(spy).toHaveBeenCalledTimes(2) }) it('passwordlessLogin', async () => { const spy = jest.spyOn(mailer, 'passwordlessLogin') await mailer.passwordlessLogin('username', 'token') expect(spy).toHaveBeenCalledTimes(1) }) })
package se.danielkonsult.fsm4j_turnstile; /** * Acts as context for the turnstile state machine, keeping tracking of * how many times it has been opened, and how many forced attempts * (trying to pass without paying) that have been made. */ public class TurnstileData { private int passages = 0; private int forcedAttempts = 0; public void addPassage() { passages++; } public void addForcedAttempt() { forcedAttempts++; } public int getPassages() { return passages; } public int getForcedAttempts() { return forcedAttempts; } }
#[allow(unused_imports)] use proconio::input; #[allow(unused_imports)] use proconio::marker::Chars; #[allow(unused_imports)] use std::cmp::{max, min}; #[allow(unused)] const ALPHA_SMALL: [char; 26] = [ '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', ]; #[allow(unused)] const ALPHA: [char; 26] = [ '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', ]; #[allow(unused)] fn read<T: std::str::FromStr>() -> T { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } #[allow(unused)] fn read_vec<T: std::str::FromStr>() -> Vec<T> { read::<String>() .split_whitespace() .map(|e| e.parse().ok().unwrap()) .collect() } #[allow(unused)] fn read_touple<T: std::str::FromStr + Copy>() -> (T, T) { let v: Vec<T> = read_vec(); assert_eq!(v.len(), 2); (v[0], v[1]) } fn main() { input!(N: usize); input!(A: [i64; N]); let mut ans: i64 = 1_000_000_000_000_000_000; for i in 0..2 { let mut st = SegmentTree::<i64>::new(&A); // i % 2 == 0 ==> 偶数番目が正 // i % 2 == 1 ==> 偶数番目が負 let mut tot: i64 = 0; for j in 0..N { let mut diff = 0; let now = st.get(0, j + 1); if i % 2 == 0 { if j % 2 == 0 && now <= 0 { // 1にする diff = 1 - now; } else if j % 2 == 1 && now >= 0 { // -1にする diff = -1 - now; } } else { if j % 2 == 0 && now >= 0 { // -1にする diff = -1 - now; } else if j % 2 == 1 && now <= 0 { // 1にする diff = 1 - now; } } //println!("j = {}, now = {}, diff = {}", j, now, diff); tot += diff.abs(); st.update(j, A[j] + diff); } ans = min(ans, tot); } println!("{}", ans); } impl Monoid for i64 { const E: i64 = 0; fn calc(&self, rhs: &i64) -> Self { self + rhs } } #[allow(clippy::declare_interior_mutable_const)] trait Monoid<Rhs = Self> { const E: Rhs; fn calc(&self, other: &Rhs) -> Self; } #[derive(Debug, PartialEq, Clone)] struct SegmentTree<T: Clone + Monoid> { n: usize, //元の配列に一番近い2の冪乗を格納する tree: Vec<T>, } // 区間の最小の値を求めるセグメント木 impl<T: Clone + Monoid> SegmentTree<T> { // 元の配列をセグメント木で表現 // 2^nが元の配列のサイズ以上になる最小のnをNとする // O(N) fn new(v: &[T]) -> SegmentTree<T> { let mut n: usize = 1; // セグメント木の葉の要素数 while n < v.len() { n *= 2; } // セグメント木を表現するベクター let mut tree = vec![T::E; 2 * n - 1]; // 区間における最小値を求めるセグメント木に注意 // 葉から順に値を格納していく // まず最下段に値を格納する for (i, e) in v.iter().enumerate() { tree[i + n - 1] = e.clone(); } // 最下段の次の下段から値を書くのしていく for i in (0..(n - 1)).rev() { tree[i] = T::calc(&tree[2 * i + 1], &tree[2 * i + 2]); // 区間における最小値を求めるセグメント木に注意 } SegmentTree { n, tree } } // 元の配列のi番目の値が変更された時にセグメント木を更新 // O(logN) Nは元の配列の長さを超える最小の2の冪乗 fn update(&mut self, i: usize, val: T) { // 最下段の葉を更新 let mut m = i + self.n - 1; self.tree[m] = val; while m > 0 { m = (m - 1) / 2; self.tree[m] = T::calc(&self.tree[2 * m + 1], &self.tree[2 * m + 2]); // 区間における最小値を求めるセグメント木に注意 } } // 指定された区間の値を求める // 区間は半開区間[i, j)での値を求める // O(logN) fn get(&self, i: usize, j: usize) -> T { fn get_sub<U: Clone + Monoid>( t: &SegmentTree<U>, a: usize, b: usize, k: usize, l: usize, r: usize, ) -> U { // 求めたい区間が今いるノードの対応する区間と交差していない if r <= a || b <= l { return U::E; } // 区間における最小値を求めるセグメント木に注意 // 求めたい区間が今いるノードの対応する区間を被覆してる if a <= l && r <= b { return t.tree[k].clone(); } // 求めたい区間と今いるノードと対応している区間が交差してるとき // 子を探索する // 左の子の値 let vl = get_sub(t, a, b, 2 * k + 1, l, (l + r) / 2); // 右のこの値 let vr = get_sub(t, a, b, 2 * k + 2, (l + r) / 2, r); U::calc(&vl, &vr) } get_sub(&self, i, j, 0, 0, self.n) } }
import { DomNode, el } from "@hanul/skynode"; import msg from "msg.js"; import { View, ViewParams } from "skyrouter"; import Alert from "../../component/dialogue/Alert"; import MetaversesContract from "../../contracts/MetaversesContract"; import Layout from "../Layout"; import ViewUtil from "../ViewUtil"; export default class AddMetaverse implements View { private container: DomNode; private bannerPreview: DomNode; private bannerInput: DomNode<HTMLInputElement>; private iconPreview: DomNode; private iconInput: DomNode<HTMLInputElement>; private nameInput: DomNode<HTMLInputElement>; private descriptionTextarea: DomNode<HTMLInputElement>; private twitterInput: DomNode<HTMLInputElement>; private kakaotalkInput: DomNode<HTMLInputElement>; private kakaotalkInput2: DomNode<HTMLInputElement>; private kakaotalkInput3: DomNode<HTMLInputElement>; private linktreeInput: DomNode<HTMLInputElement>; private homepageInput: DomNode<HTMLInputElement>; private discordInput: DomNode<HTMLInputElement>; private telegramInput: DomNode<HTMLInputElement>; constructor() { Layout.current.title = msg("ADD_METAVERSE_TITLE"); Layout.current.content.append( (this.container = el(".add-metaverse-view", el("header", el("h1", msg("ADD_METAVERSE_TITLE")), el("p", msg("ADD_METAVERSE_DESCRIPTION")), ), el("main", el(".form", el("label", el("h3", msg("BANNER_IMAGE_ADDRESS_INPUT")), this.bannerPreview = el("img.banner-preview"), this.bannerInput = el("input", { type: "url", placeholder: msg("BANNER_IMAGE_ADDRESS_INPUT"), change: () => { (this.bannerPreview as DomNode<HTMLImageElement>).domElement.src = this.bannerInput.domElement.value; }, }), ), el("label", el("h3", msg("BANNER_UPLOAD_INPUT")), el("input", { type: "file", change: (event) => { const file = event.target.files[0]; const reader = new FileReader(); reader.addEventListener("load", async () => { const result = await fetch(`https://api.klu.bs/pfp/uploadbanner`, { method: "POST", body: reader.result as string, }); this.bannerInput.domElement.value = await result.text(); this.bannerInput.fireDomEvent("change"); }, false); if (file) { reader.readAsDataURL(file); } }, }), ), el("label", el("h3", msg("ICON_IMAGE_ADDRESS_INPUT")), this.iconPreview = el("img.icon-preview"), this.iconInput = el("input", { type: "url", placeholder: msg("ICON_IMAGE_ADDRESS_INPUT"), change: () => { (this.iconPreview as DomNode<HTMLImageElement>).domElement.src = this.iconInput.domElement.value; }, }), ), el("label", el("h3", msg("ICON_UPLOAD_INPUT")), el("input", { type: "file", change: (event) => { const file = event.target.files[0]; const reader = new FileReader(); reader.addEventListener("load", async () => { const result = await fetch(`https://api.klu.bs/pfp/uploadicon`, { method: "POST", body: reader.result as string, }); this.iconInput.domElement.value = await result.text(); this.iconInput.fireDomEvent("change"); }, false); if (file) { reader.readAsDataURL(file); } }, }), ), el("label", el("h3", msg("NAME_INPUT")), this.nameInput = el("input", { type: "text", placeholder: msg("NAME_INPUT") }), ), el("label", el("h3", msg("INTRODUCTION_INPUT")), el("p", el("span", msg("INTRODUCTION_MARKDOWN_DESCRIPTION")), el("a", msg("INTRODUCTION_MARKDOWN_BUTTON"), { href: "https://www.markdownguide.org/cheat-sheet/", target: "_blank" }), ), this.descriptionTextarea = el("textarea", { placeholder: msg("INTRODUCTION_INPUT") }), ), el("label", el("h3", msg("OPEN_KAKAO_INPUT")), this.kakaotalkInput = el("input", { type: "url", placeholder: msg("OPEN_KAKAO_INPUT") }), ), el("label", el("h3", msg("OPEN_KAKAO2_INPUT")), this.kakaotalkInput2 = el("input", { type: "url", placeholder: msg("OPEN_KAKAO2_INPUT") }), ), el("label", el("h3", msg("OPEN_KAKAO3_INPUT")), this.kakaotalkInput3 = el("input", { type: "url", placeholder: msg("OPEN_KAKAO3_INPUT") }), ), el("label", el("h3", msg("TWITTER_INPUT")), this.twitterInput = el("input", { type: "url", placeholder: msg("TWITTER_INPUT") }), ), el("label", el("h3", msg("LINKTREE_INPUT")), this.linktreeInput = el("input", { type: "url", placeholder: msg("LINKTREE_INPUT") }), ), el("label", el("h3", msg("HOMEPAGE_INPUT")), this.homepageInput = el("input", { type: "url", placeholder: msg("HOMEPAGE_INPUT") }), ), el("label", el("h3", msg("DISCORD_INPUT")), this.discordInput = el("input", { type: "url", placeholder: msg("DISCORD_INPUT") }), ), el("label", el("h3", msg("TELEGRAM_INPUT")), this.telegramInput = el("input", { type: "url", placeholder: msg("TELEGRAM_INPUT") }), ), el("button", msg("REGISTER_BUTTON"), { click: async () => { const extra = { banner: this.bannerInput.domElement.value, icon: this.iconInput.domElement.value, name: this.nameInput.domElement.value, description: this.descriptionTextarea.domElement.value, kakaotalk: this.kakaotalkInput.domElement.value, kakaotalk2: this.kakaotalkInput2.domElement.value, kakaotalk3: this.kakaotalkInput3.domElement.value, linktree: this.linktreeInput.domElement.value, homepage: this.homepageInput.domElement.value, discord: this.discordInput.domElement.value, telegram: this.telegramInput.domElement.value, twitter: this.twitterInput.domElement.value, }; await MetaversesContract.addMetaverse(JSON.stringify(extra)); setTimeout(async () => { new Alert(msg("SUCCESS_ADD_METAVERSE_TITLE"), msg("SUCCESS_ADD_METAVERSE_DESCRIPTION")); ViewUtil.go(`/metaverse/${(await MetaversesContract.getMetaverseCount()).toNumber() - 1}`); }, 2000); }, }), ), ), )), ); } public changeParams(params: ViewParams, uri: string): void { } public close(): void { this.container.delete(); } }
<reponame>RyaxTech/singularity-cri // Copyright (c) 2018-2019 Sylabs, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package image import ( "context" "encoding/json" "fmt" "io" "os" "os/exec" "path/filepath" "strconv" "strings" "sync" "time" "github.com/golang/glog" "github.com/sylabs/singularity-cri/pkg/fs" "github.com/sylabs/singularity-cri/pkg/image" "github.com/sylabs/singularity-cri/pkg/index" "github.com/sylabs/singularity-cri/pkg/singularity" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" k8s "k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2" ) const registryInfoFile = "registry.json" // SingularityRegistry implements k8s ImageService interface. type SingularityRegistry struct { storage string // path to image storage without trailing slash images *index.ImageIndex m sync.Mutex infoFile *os.File } // NewSingularityRegistry initializes and returns SingularityRuntime. // Singularity must be installed on the host otherwise it will return an error. func NewSingularityRegistry(storePath string, index *index.ImageIndex) (*SingularityRegistry, error) { _, err := exec.LookPath(singularity.RuntimeName) if err != nil { return nil, fmt.Errorf("could not find %s on this machine: %v", singularity.RuntimeName, err) } storePath, err = filepath.Abs(storePath) if err != nil { return nil, fmt.Errorf("could not get absolute storage directory path: %v", err) } registry := SingularityRegistry{ storage: storePath, images: index, } if err := os.MkdirAll(storePath, 0755); err != nil { return nil, fmt.Errorf("could not create storage directory: %v", err) } registry.infoFile, err = os.OpenFile(filepath.Join(storePath, registryInfoFile), os.O_CREATE|os.O_RDWR, 0644) if err != nil { return nil, fmt.Errorf("could not open registry backup file: %v", err) } err = registry.loadInfo() if err != nil { return nil, err } return &registry, nil } // Shutdown should be called whenever SingularityRegistry is no longer // used to make sure allocated resources are freed. func (s *SingularityRegistry) Shutdown() error { s.m.Lock() defer s.m.Unlock() if err := s.infoFile.Close(); err != nil { return fmt.Errorf("could not close infoFile: %v", err) } return nil } // PullImage pulls an image with authentication config. func (s *SingularityRegistry) PullImage(ctx context.Context, req *k8s.PullImageRequest) (*k8s.PullImageResponse, error) { ref, err := image.ParseRef(req.Image.Image) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "could not parse image reference: %v", err) } info, err := image.LibraryInfo(ctx, ref, req.GetAuth()) if err == image.ErrNotFound { return nil, status.Errorf(codes.NotFound, "image %s is not found", ref) } if err != nil && err != image.ErrNotLibrary { return nil, status.Errorf(codes.Internal, "could not get %s image metadata: %v", ref, err) } if info != nil { _, err := s.images.Find(info.Sha256) if err == nil { glog.V(2).Infof("Image %s is already present with the same checksum, skipping pull", ref) return &k8s.PullImageResponse{ ImageRef: info.ID, }, nil } } info, err = image.Pull(ctx, s.storage, ref, req.GetAuth()) if err != nil { return nil, status.Errorf(codes.Internal, "could not pull image: %v", err) } if err := info.Verify(); err != nil { info.Remove() return nil, status.Errorf(codes.InvalidArgument, "could not verify image: %v", err) } if err = s.images.Add(info); err != nil { info.Remove() return nil, status.Errorf(codes.Internal, "could not index image: %v", err) } if err = s.dumpInfo(); err != nil { glog.Errorf("Could not dump registry info: %v", err) } return &k8s.PullImageResponse{ ImageRef: info.ID, }, nil } // RemoveImage removes the image. // This call is idempotent, and does not return an error if the image has already been removed. func (s *SingularityRegistry) RemoveImage(ctx context.Context, req *k8s.RemoveImageRequest) (*k8s.RemoveImageResponse, error) { info, err := s.images.Find(req.Image.Image) if err == index.ErrNotFound { return &k8s.RemoveImageResponse{}, nil } if err != nil { return nil, status.Errorf(codes.InvalidArgument, "could not find image: %v", err) } err = info.Remove() if err == image.ErrIsUsed { return nil, status.Errorf(codes.FailedPrecondition, "unable to remove image: %v", err) } if err != nil { return nil, status.Errorf(codes.Internal, "could not remove image: %v", err) } if err := s.images.Remove(info.ID); err != nil { return nil, status.Errorf(codes.Internal, "could not remove image from index: %v", err) } if err = s.dumpInfo(); err != nil { glog.Errorf("Could not dump registry info: %v", err) } return &k8s.RemoveImageResponse{}, nil } // ImageStatus returns the status of the image. If the image is not // present, returns a response with ImageStatusResponse.Image set to nil. func (s *SingularityRegistry) ImageStatus(ctx context.Context, req *k8s.ImageStatusRequest) (*k8s.ImageStatusResponse, error) { info, err := s.images.Find(req.Image.Image) if err == index.ErrNotFound { return &k8s.ImageStatusResponse{}, nil } if err != nil { return nil, status.Errorf(codes.InvalidArgument, "could not find image: %v", err) } var verboseInfo map[string]string if req.Verbose { verboseInfo = map[string]string{ "usedBy": fmt.Sprintf("%v", info.UsedBy()), } } var uid *k8s.Int64Value var username string if info.OciConfig != nil && info.OciConfig.User != "" { // If conf.User is not empty, possible options are: // * "user" // * "uid" // * "user:group" // * "uid:gid // * "user:gid" // * "uid:group" user := strings.Split(info.OciConfig.User, ":")[0] userID, err := strconv.ParseInt(user, 10, 32) if err != nil { username = user } else { uid = &k8s.Int64Value{ Value: userID, } } } return &k8s.ImageStatusResponse{ Image: &k8s.Image{ Id: info.ID, RepoTags: info.Ref.Tags(), RepoDigests: info.Ref.Digests(), Size_: info.Size, Uid: uid, Username: username, }, Info: verboseInfo, }, nil } // ListImages lists existing images. func (s *SingularityRegistry) ListImages(ctx context.Context, req *k8s.ListImagesRequest) (*k8s.ListImagesResponse, error) { var imgs []*k8s.Image appendToResult := func(info *image.Info) { if info.Matches(req.Filter) { imgs = append(imgs, &k8s.Image{ Id: info.ID, RepoTags: info.Ref.Tags(), RepoDigests: info.Ref.Digests(), Size_: info.Size, }) } } s.images.Iterate(appendToResult) return &k8s.ListImagesResponse{ Images: imgs, }, nil } // ImageFsInfo returns information of the filesystem that is used to store images. // Note that local SIF images that were not pulled by CRI are not counted in this stat. func (s *SingularityRegistry) ImageFsInfo(context.Context, *k8s.ImageFsInfoRequest) (*k8s.ImageFsInfoResponse, error) { fsInfo, err := fs.Usage(s.storage) if err != nil { return nil, status.Errorf(codes.Internal, "could not get fs usage: %v", err) } fsUsage := &k8s.FilesystemUsage{ Timestamp: time.Now().UnixNano(), FsId: &k8s.FilesystemIdentifier{ Mountpoint: fsInfo.MountPoint, }, UsedBytes: &k8s.UInt64Value{ Value: uint64(fsInfo.Bytes), }, InodesUsed: &k8s.UInt64Value{ Value: uint64(fsInfo.Inodes), }, } return &k8s.ImageFsInfoResponse{ ImageFilesystems: []*k8s.FilesystemUsage{fsUsage}, }, nil } // loadInfo reads backup file and restores registry according to it. func (s *SingularityRegistry) loadInfo() error { s.m.Lock() defer s.m.Unlock() _, err := s.infoFile.Seek(0, io.SeekStart) if err != nil { return fmt.Errorf("could not seek registry info file: %v", err) } dec := json.NewDecoder(s.infoFile) // while the array contains values for dec.More() { var info *image.Info // decode an array value (Message) err := dec.Decode(&info) if err != nil { return fmt.Errorf("could not decode image: %v", err) } err = s.images.Add(info) if err != nil { return fmt.Errorf("could not add decoded image to index: %v", err) } } return nil } // dumpInfo dumps registry into backup file. func (s *SingularityRegistry) dumpInfo() error { s.m.Lock() defer s.m.Unlock() _, err := s.infoFile.Seek(0, io.SeekStart) if err != nil { return fmt.Errorf("could not seek registry info file: %v", err) } err = s.infoFile.Truncate(0) if err != nil { return fmt.Errorf("could not reset file: %v", err) } enc := json.NewEncoder(s.infoFile) encodeToFile := func(info *image.Info) { if info.Ref.URI() == singularity.LocalFileDomain { return } _ = enc.Encode(info) } s.images.Iterate(encodeToFile) return nil }
#pragma once #include "il2cpp.h" uint8_t Dpr_NetworkUtils_NetDataRecodeTradeData__get_GetDataID (Dpr_NetworkUtils_NetDataRecodeTradeData_o* __this, const MethodInfo* method_info); uint8_t Dpr_NetworkUtils_NetDataRecodeTradeData__get_DataID (const MethodInfo* method_info); void Dpr_NetworkUtils_NetDataRecodeTradeData___ctor (Dpr_NetworkUtils_NetDataRecodeTradeData_o* __this, const MethodInfo* method_info);
<reponame>sk177y/sexy<filename>src/Mutation.cpp<gh_stars>1-10 #include "Mutation.h" Mutation::Mutation() { } Mutation::~Mutation() { } void Mutation::mutate(Individual* individual) { } void Mutation::mutateRange(Individual* individual, double mutation) { }
def profile_pic_url(self) -> str: if self._context.is_logged_in: try: return self._iphone_struct['hd_profile_pic_url_info']['url'] except (InstaloaderException, KeyError) as err: self._context.error('{} Unable to fetch high quality profile pic.'.format(err)) return self._metadata("profile_pic_url_hd") else: return self._metadata("profile_pic_url_hd")
#ifndef MALLOC_FAIL_H #define MALLOC_FAIL_H /* https://stackoverflow.com/questions/1711170/unit-testing-for-failed-malloc I saw a cool solution to this problem which was presented to me by S. Paavolainen. The idea is to override the standard malloc(), which you can do just in the linker, by a custom allocator which 1. reads the current execution stack of the thread calling malloc() 2. checks if the stack exists in a database that is stored on hard disk 1. if the stack does not exist, adds the stack to the database and returns NULL 2. if the stack did exist already, allocates memory normally and returns Then you just run your unit test many times---this system automatically enumerates through different control paths to malloc() failure and is much more efficient and reliable than e.g. random testing. */ int should_malloc_fail(void); #endif
# import sys input=sys.stdin.readline def main(): S=input().strip("\n") Q=int(input()) sign=True head=[] tail=[] for i in range(Q): q=tuple(input().split()) if q[0]=="1": sign^=True else: if (q[1]=="1" and sign==True) or (q[1]=="2" and sign==False): head.append(q[2]) else: tail.append(q[2]) if sign==True: print("".join(head[::-1])+S+"".join(tail)) else: print("".join(tail[::-1])+S[::-1]+"".join(head)) if __name__=="__main__": main()
/** * Adds listener to width property such that if it is below a certain px, it will change to 2-grid mode. * <900px (2 grid); >=900 (3 grid) * * @param scene the scene which listener is added to. */ private void addDynamicGridPaneChange(Scene scene) { scene.widthProperty().addListener((obs, oldWidth, newWidth) -> { System.out.println("Width changed! old=" + oldWidth + "; new=" + newWidth); if (newWidth.doubleValue() < 900.0 && oldWidth.doubleValue() >= 900.0) { this.gPaneRight.setPercentWidth(0); this.gPaneCentre.setPercentWidth(75); } else if (newWidth.doubleValue() >= 900.0 && oldWidth.doubleValue() < 900) { this.gPaneCentre.setPercentWidth(60); this.gPaneRight.setPercentWidth(15); } }); }
/** Returns true if the hailstone sequence that starts with n is considered long * and false otherwise, as described in part (b). * Precondition: n > 0 */ public static boolean isLongSeq(int n){ /* to be implemented in part (b) */ if ((hailstoneLength(n))>n) return true; return false; }
//! Error types. use std::{error::Error, fmt::Display}; /// Returned when trying to reserve an key on a /// full [`Arena`](super::Arena). #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct ArenaFull; impl Display for ArenaFull { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("Cannot reserve an key because the arena is full") } } impl Error for ArenaFull {} #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] /// An error that can occur when inserting an item /// into an [`Arena`](super::Arena) with an existing /// [`Key`](super::Key). pub enum InsertWithKeyError { /// Cannot insert with this key because it is not reserved. KeyNotReserved, /// Cannot insert with this key because the slot index /// or generation is invalid for this arena. InvalidKey, } impl Display for InsertWithKeyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { InsertWithKeyError::KeyNotReserved => f.write_str("Cannot insert with this key because it is not reserved"), InsertWithKeyError::InvalidKey => f.write_str("Cannot insert with this key because the slot index or generation is invalid for this arena."), } } } impl Error for InsertWithKeyError {}
// ParseMenuItem parses a single item, returning the new menu. func (m MenuParser) ParseMenuItem(ctx context.Context, item *plugins.Item) *menu.MenuItem { displayText := item.DisplayText() itemAction := item.Action() menuItem := menu.Text(displayText, nil, func(_ *menu.CallbackData) { if itemAction == nil { return } itemAction(ctx) }) if item.Text != displayText { menuItem.Tooltip = item.Text } if item.Params.Key != "" { acc, err := keys.Parse(item.Params.Key) if err != nil { menuItem.Label = fmt.Sprintf("error: %s", err) } menuItem.Accelerator = acc } menuItem.Image = item.Params.Image menuItem.FontName = item.Params.Font menuItem.FontSize = item.Params.Size menuItem.RGBA = item.Params.Color if item.Params.TemplateImage != "" { menuItem.Image = item.Params.TemplateImage menuItem.MacTemplateImage = true } menuItem.MacAlternate = item.Params.Alternate if item.Params.Dropdown == false { menuItem.Hidden = true } if len(item.Items) > 0 { menuItem.SubMenu = m.ParseItems(ctx, item.Items) } if itemAction == nil && menuItem.SubMenu == nil { menuItem.Disabled = true } if item.Params.Disabled { menuItem.Disabled = true } return menuItem }
/** * @brief Registers a property changed handler function for a d-bus interface. * This refers to the standard-defined org.freedesktop.DBus.Properties.PropertiesChanged * signal. * * @param dbus The dbus control object. * @param interface The dbus interface to monitor for property changes. * @param userdata User data that will be passed to the property change handler. * @param handler The function that will be invoked upon property changes. * @param handle A handle referencing the installed property handler. * @return int The result of the operation. 0 if successful, in which case * '*handle' will be populated with a value that refers to the monitor. A * negative error value is returned otherwise. */ int ztp_dbus_register_properties_changed_handler( struct ztp_dbus_client *dbus, const char *interface, void *userdata, ztp_dbus_properties_changed_handler handler, struct ztp_dbus_properties_changed_handle **phandle) { if (strchr(interface, '\'') != NULL) return -EINVAL; struct ztp_dbus_properties_changed_handle *handle = calloc(1, sizeof *handle); if (!handle) return -ENOMEM; handle->userdata = userdata; handle->handler = handler; char match[256]; snprintf(match, sizeof match, "type='signal'," "interface='org.freedesktop.DBus.Properties'," "member='PropertiesChanged'," "arg0='%s'", interface); int ret = sd_bus_add_match(dbus->bus, &handle->slot, match, ztpd_dbus_on_properties_changed, handle); if (ret < 0) { zlog_error("failed to add match for PropertiesChanged handler (%d)", ret); goto fail; } list_add(&handle->list, &dbus->property_changed_handles); *phandle = handle; ret = 0; out: return ret; fail: ztp_dbus_unregister_properties_changed_handler(handle); goto out; }
Booking a summer camping trip can be stressful. The best campsites will sell out just minutes after the online reservation system opens for bookings, which can leave you scrambling to find an alternative. Last year, some friends and I wanted to go camping over the August long weekend. We started planning a trip to Golden Ears Provincial Park – about 90 minutes from Vancouver. Three nights was $63 all in and even when we added in gas, food, and drinks and firewood it was still a good deal. There are always ways to make a camping trip even cheaper. Here are a few tips to help you save money on your next camping adventure. Camp for free There are many beautiful places across Canada where you can camp for free. I’m fortunate to be from British Columbia, where there are an abundance of forestry sites that offer free camping. These sites offer little to no amenities - which means you won’t find any showers. Some have outhouses, picnic tables, fire pits, and if you’re lucky, you might find a shelter hut where you can keep dry and cook your food if the weather turns bad. But don’t be surprised if you find nothing more but a few flat surfaces for pitching tents. The website FreeCampsites.net is a good place to start. You will be able to find free and cheap camping sites across Canada and the USA. You are also allowed to camp and hike on Crown Land for free, and there are plenty of beautiful trails, forests, and mountains to explore. However, there are some rules, which will vary depending on the province. For example, in BC you are only allowed to camp on crown land for 14 consecutive days, and in Ontario, the maximum is 21 days. Related: How to save money on a road trip Discount camping If you camp often, it might be worth it to join a campground chain’s discount program. For example, KOA has campsites across Canada and the United States, and for $24/year, offers a 10 per cent discount to its loyalty cardholders. Camping at KOA sites are usually a bit more expensive $25-30/night, but offers many amenities, including water, WIFI, electricity, swimming pools, showers, and more. For an annual fee of $44, Passport America offers a 50 per cent discount on over 1,800 campgrounds across North America. Some campgrounds might charge a small fee for having more than one tent, but most places allow it for free, and the more people you have, the cheaper the camping is. Prepare meals ahead of time Save money, hassle, and space in your cooler by prepping your meals before you pack and head out into the wilderness. Marinate meat, cut some vegetables, and prepare skewers at home. You can bring a few potatoes wrapped in tinfoil for the fire, as well as eggs, pancake batter, and condiments in small containers. Used gear If you only camp during the summer months, there’s no reason to spend hundreds of dollars on a lightweight all-weather tent, down-filled sleeping bag, and all the expensive accessories. Check out discount stores, garage sales, Craigslist, or borrow items from friends and family. Be creative - there are plenty of things you can use around your house for making camping cheaper: laundry lint makes good tinder, dipping matches in wax makes them waterproof, and an old shower curtain can make a great tarp. Entertainment Entertaining yourself while camping is easy. Just bring cards, board games, a good book, walking shoes, and bicycles – if you can fit them in your car. Save on firewood by bringing some of your own wood from home, or buy wood from your local store. It will almost always be cheaper than paying $3 to $6 per bundle for wood that they sell at campsites. Related: Should you go on vacation if you’re in debt? What tips do you have for a frugal camping experience? Krystal Yee lives in Vancouver and blogs at Give Me Back My Five Bucks. You can reach her on Twitter (@krystalatwork), or by e-mail at [email protected].
/** * {@link Descriptor} for {@link Database} * * @author Kohsuke Kawaguchi */ public abstract class DatabaseDescriptor extends Descriptor<Database> { protected DatabaseDescriptor() { } protected DatabaseDescriptor(Class<? extends Database> clazz) { super(clazz); } public static DescriptorExtensionList<Database,DatabaseDescriptor> all() { return Jenkins.getInstance().getDescriptorList(Database.class); } }
<filename>src/mongomanager.py from pymongo import MongoClient import logging import inspect import json class MongoManager: #what all the scripts will use to connect to the dbs, so now its not in every single script, this can also auto add the indxes, do the updates, return things, etc. def __init__(self,dbname,host='localhost',port=27017,username=None,password=None): client = MongoClient(host, port) db=client[dbname] self.client=client if username is not None and password is not None: db.authenticate(username, password, mechanism='SCRAM-SHA-1') elif username is None and password is None: pass else: logging.error('no username and password specified') exit() self.db=db return def reindex_collections(self,collections=None): if collections is None: collections=self.db.collection_names() for collection in collections: logging.info("reindexing:"+collection) self.db[collection].reindex() logging.info('done reindexing:'+collection) return def backup_db(self,destinationfolder='.',collections=None): if collections is None: collections=self.db.collection_names() #backup the db to your local harddrive for collection in collections: logging.info('backing up collection: '+collection) file=open(destinationfolder+'/'+collection+'.json','w') items=self.db[collection].find().batch_size(100) for item in items: try: jsonitem=json.dumps(item) file.write(jsonitem) file.write('\n') except Exception as e: logging.error(e) logging.error(item) continue file.close() return def create_collections(self,collections): for collection in collections: if collection not in self.get_collections(): self.create_collection(collection) logging.info('collection created: '+collection) else: logging.info('collection already exists: '+collection) return def drop_collections(self,collections): for collection in collections: if collection in self.get_collections(): self.db.drop_collection(collection) return def create_collection(self,collection): if collection not in self.get_collections(): self.db.create_collection(collection) return def get_collections(self): return self.db.collection_names() def index_information(self,collection): return self.db[collection].index_information() def create_index(self,collection,index,name=None,unique=False,background=True): currentindexes=self.index_information(collection) if name==None: name=index if name not in currentindexes: self.db[collection].create_index(index,name=name,unique=unique,background=background) logging.info('new index created: '+index) else: pass #logging.info('index already exists: '+index) return def drop_indexes(self,collection,indexname=None): if indexname is None: todrop=self.index_information(collection) else: todrop=[indexname] for index in todrop: self.db[collection].drop_index(index) return def get_keys(self,collection): keys=set() for item in self.db[collection].find(): keys=keys.union(set(item.keys())) return list(keys) if __name__ == '__main__': logging.basicConfig(filename=inspect.stack()[0][1].replace('py','log'),level=logging.INFO,format='%(asctime)s:%(levelname)s:%(message)s') # m=MongoManager(host='financedevel') # x=m.index_information('companies')
// New creates a gRPC client and server connected to eachother. func New() (*Fake, func() error) { f := &Fake{} opts := []grpc.ServerOption{ grpc.UnaryInterceptor(UnaryLoggerInterceptor), grpc.StreamInterceptor(StreamLoggerInterceptor), } f.Server = grpc.NewServer(opts...) port := ":0" var err error f.Listener, err = net.Listen("tcp", port) if err != nil { glog.Fatalf("net.Listen(\"tcp\", %v) failed: %v", port, err) } addr := f.Listener.Addr().String() f.Client, err = grpc.Dial(addr, grpc.WithInsecure()) if err != nil { glog.Fatalf("grpc.Dial(%v, _) failed: %v", addr, err) } return f, f.Client.Close }
<filename>src/main/java/com/ambrosoft/exercises/SearchSparseSorted.java package com.ambrosoft.exercises; import java.util.Arrays; /** * Created by jacek on 1/2/17. */ public class SearchSparseSorted { /* sorted String array except from any number of empty Strings which break simple binary search suggests a modified binary search with some linear scans for nonempty strings worst case: all empty Strings we may ensure that an interval we search starts and ends with non-empty string binary search trouble: when midpoint hits empty, we have no idea if elt can be on the left or right Alternative: divide array in halves from middle (inclusive) scan left in search of non-empty if found and greater than elt, work with remaining part of left if smaller than elt, abandon and work with right half scanning from left to right we should have several FAIL values: one to mean continue on other side, and one to mean global fail */ static int goLeft(final String[] data, int from, final int to) { while (from > to) { if (data[from].isEmpty()) { --from; } else { return from; } } return -1; } static int goRight(final String[] data, int from, final int to) { while (from < to) { if (data[from].isEmpty()) { ++from; } else { return from; } } return -1; } // searches for non-empty value left and right of start, within bounds [lo, hi] static int pendulum(String[] data, int start, int lo, int hi) { if (data[start].isEmpty()) { int lft = start - 1; int rgt = start + 1; while (lft >= lo && rgt <= hi) { if (data[lft].isEmpty()) { --lft; } else { return lft; } if (data[rgt].isEmpty()) { ++rgt; } else { return rgt; } } while (lft >= lo) { if (data[lft].isEmpty()) { --lft; } else { return lft; } } while (rgt <= hi) { if (data[rgt].isEmpty()) { ++rgt; } else { return rgt; } } return -1; } else { return start; } } // contract: if el in data, it must be within [lo, hi] static int searchAux(String[] data, String el, int lo, int hi) { if (lo < hi) { final int middle = (lo + hi) / 2; if (data[middle].isEmpty()) { // we need to look left and right for some non-empty element int lft = goLeft(data, middle - 1, lo); return 0; } else { int cmp = el.compareTo(data[middle]); if (cmp == 0) { return middle; } else if (cmp < 0) { return searchAux(data, el, lo, middle - 1); } else { return searchAux(data, el, middle + 1, hi); } } } else { return -1; } } static int search(String[] data, String el) { final int lo = goRight(data, 0, data.length); if (lo < 0) { return -1; } else { final int cmpl = el.compareTo(data[lo]); if (cmpl == 0) { return lo; } else if (cmpl < 0) { return -1; } else { final int hi = goLeft(data, data.length - 1, lo); if (hi < 0) { return -1; } else { final int cmpr = el.compareTo(data[hi]); if (cmpr == 0) { return hi; } else if (cmpr > 0) { return -1; } else { return searchAux(data, el, lo + 1, hi - 1); } } } } } static int searchSimple(String[] data, String el) { return searchSimpleHelper(data, el, 0, data.length - 1); } static int searchSimpleHelper(String[] data, String el, int lo, int hi) { if (lo < hi) { final int nonEmpty = pendulum(data, (lo + hi) / 2, lo, hi); if (nonEmpty < 0) { return -1; } else { final int cmp = el.compareTo(data[nonEmpty]); if (cmp == 0) { return nonEmpty; } else if (cmp < 0) { return searchSimpleHelper(data, el, lo, nonEmpty - 1); } else { return searchSimpleHelper(data, el, nonEmpty + 1, hi); } } } else { return -1; } } static void test(String[] data, String el) { System.out.println(Arrays.toString(data)); System.out.println(String.format("%s -> %d", el, searchSimple(data, el))); } public static void main(String[] args) { String[] strings = new String[]{"", "", "a", "", "", "b", "", "", "", "c", "", "", "e", "", "f", "", "", "i", "", "", "", ""}; // test(new String[]{"", "", "b", "", "c", "", "", "d", "", "f", "",}, "c"); test(new String[]{"a", "", "", "", "", "", "", "", "", "", "b",}, "b"); // test(new String[]{"", "", "", "a", "", "", "", "", "", "", "",}, "a"); } }
<reponame>catphish/flex-floppy struct USBBufTable { struct USBBufDesc { uint16_t txBufferAddr ; uint16_t txBufferCount ; uint16_t rxBufferAddr ; uint16_t rxBufferCount ; } ep_desc[8]; }; #define USBBUFTABLE ((volatile struct USBBufTable *)0x40006C00) #define USBBUFRAW ((volatile uint8_t *)0x40006C00) #define USB_EPR(n) (*(volatile uint16_t *)(USB_BASE + 4 * n)) void usb_init(); void usb_main_loop(); uint8_t usb_rx_ready(uint8_t ep); uint8_t usb_tx_ready(uint8_t ep); void usb_read(uint8_t ep, volatile char * buffer); void usb_write(uint8_t ep, volatile char * buffer, uint32_t len); void usb_read_dbl(uint8_t ep, volatile char * buffer); void usb_write_dbl(uint8_t ep, volatile char * buffer, uint32_t len);
Writing in the National Post, Macdonald-Laurier Institute Senior Fellow Ken Coates argues that the problems facing Aboriginals in Canada run deeper than racism. Coates, who was responding to a sensational recent Maclean’s magazine cover story about the extent of racism towards Aboriginals in Winnipeg, says the solution instead lies with making Aboriginals powerful actors in their own renaissance. And, while the city faces serious issues, there are plenty of examples of this in Winnipeg. By Ken Coates, Jan. 28, 2015 With its current edition, Maclean’s magazine has sparked a national debate about the nature and extent of Canadian racism. Through the simple device of calling Winnipeg the “most racist” city in Canada, it has shone a light on one of the greatest “wicked problems” (a complex problem for which there is no simple solution) in Canadian public life. But it moves us no closer to a resolution. Racism is clearly part of the picture. But attaching it to the situation facing First Nations suggests that the solution lies in tackling the racists and changing their attitudes. That’s putting the cart before the horse. Picking on Winnipeg also blames the city for demographic and social accidents beyond its control. The challenges facing indigenous peoples are particularly acute in cities with large aboriginal populations, both in percentage and absolute terms. In these cities — Winnipeg, Regina, Saskatoon, Edmonton and Calgary — the size of the First Nations population makes the issue a collective challenge and responsibility. There are serious issues in the Manitoban capital. The migration of First Nations people from northern Manitoba, which has one of the lowest per-capita incomes in the country and many communities in serious crisis, exacerbates the existing problems in the city. For northern First Nations people, Winnipeg is an “arrival city,” a place that at least holds the promise of a better life and an escape from hardship. There is thus little reason for Canadians in other cities to look down their noses at those on the frontlines trying to deal with the legacy of Canada’s failed aboriginal policies. The point to bear in mind is that — strident racists aside — there is an overwhelming consensus in this country about the need to end that legacy and improve opportunities for aboriginal people. The constructive and positive developments in recent years, from constitutional and legal recognition of rights to surging aboriginal business development and large-scale indigenous enrolment in colleges and universities, have set the country on a much different course. That problems persist is widely recognized. First Nations want — and deserve — full recognition and acceptance of their aboriginal and treaty rights. First Nations also generally want greater autonomy, less interference from the federal government, and the resources needed to secure the same level of services that other Canadians take for granted. Many aboriginal Canadians — but no longer most — stay in their traditional territories and communities, but all want and expect a fair return from the development of resources on their lands. More than anything, they want, expect and deserve to be accepted as full members of the broader Canadian community. Wicked problems defy easy solutions, and this case is no different. But Canada has enough successful First Nations communities, from Whitecap in Saskatchewan, to Old Crow in the Yukon and Membertou in Nova Scotia, to prove that the problems are not as intractable as many Canadians believe. That is the narrative that holds out hope for something better for aboriginal people, because it makes them powerful actors in their own renaissance. But there is an alternative narrative, one that focuses on racism and victimization, social isolation and poverty. This narrative claims that despicable attitudes on the part of a minority of Canadians are the problem, and therefore implies that progress is only possible if we defeat those attitudes. This transfers the power to effect change to those elements of society least likely to change, and most hostile to the progress of aboriginal people. The response of Winnipegers — aboriginal and non-Aboriginal alike — to the Maclean’sarticle is a classic example of the first, empowering, narrative. The community doesn’t just resent its portrayal as a bastion of racism; it more importantly resents the neglect of the real collective action being undertaken to set things right, even in the face of the racism that undeniably exists there and elsewhere in Canada. Canada needs to think about the most effective strategy for redefining its relationship with First Nations peoples. If our understanding of the current situation and the opportunities of the future is limited to hurling accusations at one another, we will find it harder to change the reality of Aboriginal people on the ground. Many First Nations people understand that they have real options, based on aboriginal title, indigenous rights, and First Nations cultural strength, in defining their own future. Many non-aboriginal people already stand alongside their aboriginal friends and neighbours, determined to build a more equitable future. Winnipeg, irony of ironies, is at the forefront of this cooperative, aboriginally-driven, inter-racial problem-solving effort that is the real hope for indigenous peoples. By choosing the narrative of change, and of successful collaboration between aboriginal and non-aboriginal Canadians, we can continue to see First Nations businesses, aboriginal communities, and accomplished Indigenous Canadians flourish. In so doing we may not eliminate every vestige of racism, but can and will render the racists amongst us irrelevant. Ken S. Coates is a senior fellow with the Macdonald-Laurier Institute and Canada Research Chair in regional innovation in the Johnson-Shoyama Graduate School of Public Policy.
from task_custom import Task import asyncio async def coro(name): print(f">> Start {name}") await asyncio.sleep(1) print(f">> Working.. {name}") await asyncio.sleep(1) print(f">> End {name}") async def main(): task1 = Task(coro("coro1"), name="task1") task2 = Task(coro("coro2"), name="task2") await task1 await task2 # print(task1, task2) asyncio.run(main()) """ Task task1 __init__ Task task1 _step >> Start coro1 Task task1 _wakeup Task task1 _step >> Working.. coro1 Task task1 _wakeup Task task1 _step >> End coro1 """
// ReadFrom reads a packet from the connection. func (c *SecurePacketConn) ReadFrom(b []byte) (n int, src net.Addr, err error) { n, src, err = c.PacketConn.ReadFrom(c.readBuf) if err != nil { return } nn, err := c.Unpack(b, c.readBuf[:n]) return nn, src, err }
package com.mzj.action; import com.github.pagehelper.PageInfo; import com.mzj.commons.Const; import com.mzj.commons.ResponseCode; import com.mzj.commons.ServerResponse; import com.mzj.dao.pojo.Product; import com.mzj.dao.pojo.User; import com.mzj.dao.vo.*; import com.mzj.service.iservice.IProductService; import com.mzj.service.iservice.ProductService; import com.mzj.utils.FTPUtil; import org.apache.commons.fileupload.disk.DiskFileItem; import org.apache.commons.io.FileUtils; import org.apache.ibatis.annotations.Param; import org.csource.fastdfs.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2017/11/29. */ @Controller @RequestMapping("/manage/product") public class ProductManagerAction { @Autowired @Qualifier("productSer") private IProductService productService; /** * 后台: 商品上下架 * * @param productId * @param status * @return */ @RequestMapping(value = "set_sale_status.do", method = RequestMethod.GET) @ResponseBody public ServerResponse<String> updateProductStatus(Integer productId, Integer status) { ServerResponse<String> data = productService.updateProductStatus(productId, status); return data; } /** * 后台: 根据商品id查询商品 * * @param productId * @param session * @return */ @RequestMapping(value = "detail.do", method = RequestMethod.GET) @ResponseBody public ServerResponse<ProductDetailVo> selectByProductId(Integer productId, HttpSession session) { session.setAttribute("productId", productId); return productService.selectByProductId(productId); } /** * 后台:根据关键词查询商品(分页) * * @param productName * @param productId * @return */ @RequestMapping(value = "search.do", method = RequestMethod.POST) @ResponseBody public ServerResponse<PageInfo<ProductSearchVo>> searchProduct(String productName, Integer productId, Integer pageNum, Integer pageSize, HttpSession session) { User user = (User) session.getAttribute(Const.CURRENT_USER); if (user != null) { return productService.searchProduct(productName, productId, pageNum, pageSize); } return ServerResponse.error("用户未登录,请登录"); } /** * 后台:更新或插入产品 * * @param product * @return */ @RequestMapping(value = "save.do", method = RequestMethod.POST) @ResponseBody public ServerResponse<Product> saveOrUpdateProduct(Product product) { ServerResponse<Product> data = productService.saveOrUpdateProduct(product); return data; } /** * 后台:查询全部商品 * * @param pageNum * @param pageSize * @return */ @RequestMapping(value = "list.do", method = RequestMethod.POST) @ResponseBody public ServerResponse<PageInfo<ProductListVo>> findAllProduct(Integer pageNum, Integer pageSize, HttpSession session) { User user = (User) session.getAttribute(Const.CURRENT_USER); if (user != null) { return productService.findAllProduct(pageNum, pageSize); } return ServerResponse.error("用户未登录,请登录"); } //实现文件上传功能 @RequestMapping(value = "upload.do", method = RequestMethod.POST) @ResponseBody public ServerResponse<ProductUploadVo> doFlieUpload(@RequestParam("upload_file") MultipartFile sourceFile, HttpSession session) throws Exception { Integer productId = (Integer) session.getAttribute("productId"); String fileUri = ""; if (!sourceFile.isEmpty()) { try { ClientGlobal.init("C:\\Users\\瑞冰\\Desktop\\mmall\\src\\main\\resources\\client.conf"); // 3、创建一个TrackerClient对象。 TrackerClient trackerClient = new TrackerClient(); // 4、创建一个TrackerServer对象。 TrackerServer trackerServer = trackerClient.getConnection(); // 5、声明一个StorageServer对象,null。 StorageServer storageServer = null; // 6、获得StorageClient对象。 StorageClient storageClient = new StorageClient(trackerServer, storageServer); // 7、直接调用StorageClient对象方法上传文件即可。 String[] strings = storageClient.upload_file(sourceFile.getBytes(), "jpg", null); String url = ""; for (String str : strings) { url += str + "/"; } fileUri = "http://192.168.47.128/" + url.substring(0, url.lastIndexOf("/")); System.out.println(fileUri); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return productService.updateImage(productId, fileUri); } //实现富文本上传图片 @RequestMapping(value="richtext_img_upload.do",method=RequestMethod.POST) @ResponseBody public ProductRichTextVo doRichFlieUpload(@RequestParam("upload_file")MultipartFile sourceFile, HttpSession session) throws Exception{ ProductRichTextVo productRichTextVo = new ProductRichTextVo(); if(!sourceFile.isEmpty()){ File targetFile = new File("D:/richtemp", System.currentTimeMillis()+sourceFile.getOriginalFilename()); FileUtils.copyInputStreamToFile(sourceFile.getInputStream(),targetFile ); productRichTextVo.setFile_path("http://img.emall.com/"+targetFile.getName()); productRichTextVo.setMsg("上传成功"); productRichTextVo.setSuccess("true"); if(productRichTextVo != null){ return productRichTextVo; }else{ productRichTextVo.setFile_path("http://img.emall.com/"+targetFile.getName()); productRichTextVo.setMsg("error message"); productRichTextVo.setSuccess("false"); } } return productRichTextVo; } }
Looking for news you can trust? Subscribe to our free newsletters. The debate over the Keystone XL pipeline has moved from the White House to a farm in Texas. Third-generation farmer Julia Trigg Crawford is engaged in a court battle over whether TransCanada, the company that wants to build the massive pipeline from Canada to Texas, has a right to declare eminent domain on a portion of her family’s farm. Earlier this week, TransCanada announced that it intends to move forward with the portion of the Keystone XL pipeline that extends from Oklahoma down to Texas. This 485-mile-long portion of the pipeline doesn’t cross international borders, which means it won’t need approval from the State Department or President Obama. But it does cross right through Red’Arc Farm, which Crawford and her family own. The farm is in Direct, Texas, a small town about 20 miles northwest of Paris (city notable for it’s own 65-foot-tall replica of the Eiffel Tower, complete with a cowboy hat on top). Along with her father, sister, and brother, Crawford, 53, tends to her soybeans, wheat, corn, orchards, and cattle on this 600-acre property where the Red River and Bois d’Arc Creek meet. Her grandfather bought the land in 1948, and Crawford currently lives in the farmhouse. Back in 2008, the family got notice that TransCanada was interested in running a pipeline through a 30-acre pasture area. Crawford says they were first offered $7,000 for use of the land, though the figure later increased to $20,000. The Crawfords weren’t entirely opposed to having a pipeline run through the farm since there are several others running through the county. “Pipelines are not foreign here,” Crawford says. But then an initial archeological assessment of the property conducted by a firm the company hired found that the portion of the pasture the company was first interested in was full of artifacts left by the Caddo, a local American Indian tribe. That was not a big surprise to Crawford. “I pick up pieces of pottery all the time when I walk the dogs,” she says. She keeps the bits of pottery and arrowheads she finds in a large jar. So the company proposed an alternate route through another corner of the same pasture, hoping to avoid the archeological site. But according to the next inspection the archeological firm undertook, there were no artifacts in this new corner. That the second dig turned up nothing made Crawford suspicious, and she decided to get an independent survey of the site—which again turned up quite a few artifacts. She hoped that the reports would force TransCanada to pick a new route, but she says the company insisted on going right through the pasture. “They said if you don’t sign the easement we have the right to condemn the land and take it through eminent domain,” she said. She had other concerns about the pipeline, like the repercussions of a spill or the impact building the line might have on her ability to use the pasture. She says she tried to talk to the local contact person for the company and asked for concessions like thicker pipe metal, deeper burial, and assurance that her family would be compensated if the pipeline spilled into the creek they use for irrigation. The company didn’t offer any concessions, she says, and instead took the Crawfords to court last fall to claim eminent domain on the property. (The company has taken a similar tack with landowners in Nebraska as well.) That tipped off a legal battle that’s still ongoing. For one, Crawford believes that she and her family were never offered a fair price for their land. And for another, she thinks that the archaeological and historical value of the land outweighs the desire of a private company to dig through it. But the main reason she’s fighting eminent domain on her land is that she doesn’t think TransCanada has a right to declare it. Under Texas law, pipeline regulation is handled by the Railroad Commission. But the commission “does not have the authority to regulate any pipelines with respect to the exercise of their eminent domain powers,” it states on its website. So if a company is building an oil or gas pipeline in Texas, it’s generally able to declare eminent domain on any route it wants. But Crawford argues that there should be some kind of demonstrated public good before a private company can seize her land—or at least a state agency that has some oversight power. She’s hoping to challenge TransCanada’s claim that it can take the property when they go to court in April—particularly since the company doesn’t yet have all the permits necessary to start construction. “A foreign-owned, for-profit, nonpermitted company has been allowed by loopholes to condemn my land,” she says. “It’s about landowner rights.” Her story gotten quite a bit of press coverage in the last week, and she’s launched an internet petition that has drawn more than 15,000 signatures of support. TransCanada has vowed that it won’t let Crawford stand in the way of the pipeline. “We are not going to have one landowner hold up a multibillion-dollar project that is going to be for the benefit of the public,” the company’s lawyer told the court in their Feb. 17 hearing, according to Reuters. “They’re entitled to their day in court, but they’re not going to be able to stop the pipeline project under (Texas law).” Last week, a judge waived the restraining order that Crawford had requested against TransCanada, so now she worries that the company might start laying the groundwork for the pipeline at any moment. “We’re all looking out the window every hour.” For now, though, she’s waiting for their next round in court.
import virxrlu from util.utils import (Vector, backsolve, cap, defaultPD, defaultThrottle, shot_valid, side, sign) max_speed = 2300 throttle_accel = 100 * (2/3) brake_accel = Vector(x=-3500) boost_per_second = 33 + (1/3) min_boost_time = 1/30 jump_max_duration = 0.2 jump_speed = 291 + (2/3) jump_acc = 1458 + (1/3) class atba: def __init__(self, exit_distance=500, exit_flip=True): self.exit_distance = exit_distance self.exit_flip = exit_flip def run(self, agent): target = agent.ball.location car_to_target = target - agent.me.location distance_remaining = car_to_target.flatten().magnitude() angle_to_target = abs(Vector(x=1).angle2D(agent.me.local_location(target))) direction = 1 if angle_to_target < 2.2 else -1 local_target = agent.me.local_location(target) # Some adjustment to the final target to ensure it's inside the field and we don't try to drive through any goalposts to reach it if abs(agent.me.location.y) > 5120 - (agent.me.hitbox.width / 2): local_target.x = cap(local_target.x, -750, 750) angles = defaultPD(agent, local_target) defaultThrottle(agent, 1400) agent.controller.handbrake = angle_to_target > 1.54 velocity = agent.me.local_velocity().x if distance_remaining < self.exit_distance: agent.pop() if self.exit_flip: agent.push(flip(local_target)) elif angle_to_target < 0.05 and velocity > 600 and velocity < 1400 and distance_remaining / velocity > 3: agent.push(flip(local_target)) elif angle_to_target >= 2 and distance_remaining > 1000 and velocity < 200 and distance_remaining / abs(velocity) > 2: agent.push(flip(local_target, True)) elif agent.me.airborne: agent.push(recovery(local_target)) class wave_dash: def __init__(self, target=None): self.step = -1 # 0 = forward, 1 = right, 2 = backwards, 3 = left self.direction = 0 self.recovery = recovery() if target is not None: largest_direction = max(abs(target.x), abs(target.y)) dir_switch = { abs(target.x): 0, abs(target.y): 1 } self.direction = dir_switch[largest_direction] if (self.direction == 0 and target.x < 0) or (self.direction and target.y < 0): self.direction += 2 def run(self, agent): self.step += 1 target_switch = { 0: agent.me.forward.flatten()*100 + Vector(z=50), 1: agent.me.forward.flatten()*100, 2: agent.me.forward.flatten()*100 - Vector(z=50), 3: agent.me.forward.flatten()*100 } target_up = { 0: agent.me.local(Vector(z=1)), 1: agent.me.local(Vector(y=-50, z=1)), 2: agent.me.local(Vector(z=1)), 3: agent.me.local(Vector(y=50, z=1)) } defaultPD(agent, agent.me.local(target_switch[self.direction]), up=target_up[self.direction]) if self.direction == 0: agent.controller.throttle = 1 elif self.direction == 2: agent.controller.throttle = -1 else: agent.controller.handbrake = True if self.step < 1: agent.controller.jump = True elif self.step < 4: pass elif not agent.me.airborne: agent.pop() elif agent.me.location.z + (agent.me.velocity.z * 0.2) < 5: agent.controller.jump = True agent.controller.yaw = 0 if self.direction in {0, 2}: agent.controller.roll = 0 agent.controller.pitch = -1 if self.direction is 0 else 1 else: agent.controller.roll = -1 if self.direction is 1 else 1 agent.controller.pitch = 0 class double_jump: def __init__(self, intercept_time, shot_vector): self.intercept_time = intercept_time self.shot_vector = shot_vector self.ball_location = None # braking self.brake = brake() # Flags for what part of the routine we are in self.jumping = False self.dodged = False self.jump_time = -1 self.counter = 0 def update(self, shot): self.intercept_time = shot.intercept_time self.shot_vector = shot.shot_vector def run(self, agent): # This routine is the same as jump_shot, but it's designed to hit the ball above 250uus (and below 551uus or so) without any boost if not agent.shooting: agent.shooting = True T = self.intercept_time - agent.time # Capping T above 0 to prevent division problems time_remaining = cap(T, 0.000001, 6) slice_n = round(T * 60) agent.dbg_2d(f"Shot slice #: {slice_n}") if T > 0.3 or self.ball_location is None: ball = agent.ball_prediction_struct.slices[slice_n].physics.location self.ball_location = Vector(ball.x, ball.y, ball.z) self.dodge_point = self.ball_location - (self.shot_vector * agent.best_shot_value) if self.dodge_point.z > 490 or self.dodge_point.z < 380: agent.pop() return car_to_ball = self.ball_location - agent.me.location # whether we should go forwards or backwards angle_to_target = abs(Vector(x=1).angle2D(agent.me.local_location(self.dodge_point))) # whether we are to the left or right of the shot vector side_of_shot = sign(self.shot_vector.cross(Vector(z=1)).dot(car_to_ball)) final_target = self.dodge_point.copy() # Some adjustment to the final target to ensure it's inside the field and we don't try to drive through any goalposts to reach it if abs(agent.me.location.y) > 5120 - (agent.me.hitbox.length / 2): final_target.x = cap(final_target.x, -750, 750) car_to_dodge_point = final_target - agent.me.location car_to_dodge_perp = car_to_dodge_point.cross(Vector(z=side_of_shot)) # perpendicular distance_remaining = car_to_dodge_point.flatten().magnitude() acceleration_required = backsolve(self.dodge_point, agent.me, time_remaining, Vector() if not self.jumping else agent.gravity) local_acceleration_required = agent.me.local_velocity(acceleration_required) # The adjustment causes the car to circle around the dodge point in an effort to line up with the shot vector # The adjustment slowly decreases to 0 as the bot nears the time to jump adjustment = car_to_dodge_point.angle2D(self.shot_vector) * distance_remaining / 2 # size of adjustment # controls how soon car will jump based on acceleration required # we set this based on the time remaining # bigger = later, which allows more time to align with shot vector # smaller = sooner jump_threshold = cap(T * 200, 250, 584) # factoring in how close to jump we are adjustment *= (cap(jump_threshold - (acceleration_required.z), 0, jump_threshold) / jump_threshold) # we don't adjust the final target if we are already jumping final_target += ((car_to_dodge_perp.normalize() * adjustment) if not self.jumping else 0) + Vector(z=50) distance_remaining = (final_target - agent.me.location).flatten().magnitude() local_final_target = agent.me.local_location(final_target) # drawing debug lines to show the dodge point and final target (which differs due to the adjustment) agent.line(agent.me.location, self.dodge_point, agent.renderer.white()) agent.line(self.dodge_point-Vector(z=100), self.dodge_point+Vector(z=100), agent.renderer.green()) vf = agent.me.velocity + agent.gravity * T distance = agent.me.local_location(self.dodge_point).x if agent.me.airborne else distance_remaining speed_required = 2300 if distance_remaining > 2560 else distance / time_remaining agent.dbg_2d(f"Speed required: {speed_required}") if not self.jumping: velocity = agent.me.local_velocity().x local_dodge_point = agent.me.local_location(self.dodge_point.flatten()) local_vf = agent.me.local(vf.flatten()) if T <= 0 or not virxrlcu.double_jump_shot_is_viable(T + 0.3, agent.boost_accel, agent.me.location.dist(self.ball_location), self.shot_vector.tuple(), agent.me.forward.tuple(), agent.me.boost if agent.boost_amount != 'unlimited' else 100000, velocity): # If we're out of time or the ball was hit away or we just can't get enough speed, pop agent.pop() agent.shooting = False agent.shot_weight = -1 agent.shot_time = -1 if agent.me.airborne: agent.push(ball_recovery()) elif abs(local_dodge_point.y) < 92 and local_vf.x >= local_dodge_point.x: # Switch into the jump when the upward acceleration required reaches our threshold, and our lateral acceleration is negligible, and we're close enough to the point in time where the ball will be at the given location self.jumping = True elif agent.boost_amount != 'unlimited' and angle_to_target < 0.03 and velocity > 600 and velocity < speed_required - 500 and distance_remaining / velocity > 3: if agent.gravity.z < -450: agent.push(wave_dash()) else: agent.push(flip(local_final_target)) elif agent.boost_amount != 'unlimited' and angle_to_target >= 2 and distance_remaining > 1000 and velocity < 200: agent.push(flip(local_final_target, True)) elif agent.me.airborne: agent.push(recovery(local_final_target)) else: defaultPD(agent, local_final_target) defaultThrottle(agent, speed_required) agent.controller.handbrake = angle_to_target > 1.54 else: # Mark the time we started jumping so we know when to dodge if self.jump_time == -1: self.jump_time = agent.time jump_elapsed = agent.time - self.jump_time tau = jump_max_duration - jump_elapsed xf = agent.me.location + agent.me.velocity * T + 0.5 * agent.gravity * T * T if jump_elapsed == 0: vf += agent.me.up * jump_speed xf += agent.me.up * jump_speed * T vf += agent.me.up * jump_acc * tau xf += agent.me.up * jump_acc * tau * (T - 0.5 * tau) vf += agent.me.up * jump_speed xf += agent.me.up * jump_speed * (T - tau) delta_x = self.dodge_point - xf direction = delta_x.normalize() if abs(agent.me.forward.dot(direction)) > 0.5: delta_v = delta_x.dot(agent.me.forward) / T if agent.me.boost > 0 and delta_v >= agent.boost_accel * min_boost_time: agent.controller.boost = True else: agent.controller.throttle = cap(delta_v / (throttle_accel * min_boost_time), -1, 1) if T <= -0.4 or (not agent.me.airborne and self.counter > 0): agent.pop() agent.shooting = False agent.shot_weight = -1 agent.shot_time = -1 agent.push(ball_recovery()) elif jump_elapsed < jump_max_duration and vf.z <= self.dodge_point.z: agent.controller.jump = True elif self.counter < 4: self.counter += 1 if self.counter == 3: agent.controller.jump = True elif self.counter == 4: defaultPD(agent, agent.me.local_location(self.dodge_point), upside_down=True) if self.counter < 3: defaultPD(agent, agent.me.local((self.dodge_point - agent.me.location).flatten())) l_vf = vf + agent.me.location agent.line(l_vf-Vector(z=100), l_vf+Vector(z=100), agent.renderer.red()) class Aerial: def __init__(self, intercept_time, shot_vector, fast_aerial=True): self.intercept_time = intercept_time self.shot_vector = shot_vector self.fast_aerial = fast_aerial self.target = None self.jumping = False self.dodging = False self.ceiling = False self.time = -1 self.jump_time = -1 self.counter = 0 def update(self, shot): self.intercept_time = shot.intercept_time self.shot_vector = shot.shot_vector self.fast_aerial = shot.fast_aerial def run(self, agent): if not agent.shooting: agent.shooting = True if self.time == -1: self.time = agent.time elapsed = agent.time - self.time T = self.intercept_time - agent.time xf = agent.me.location + agent.me.velocity * T + 0.5 * agent.gravity * T * T vf = agent.me.velocity + agent.gravity * T slice_n = math.ceil(T * 60) agent.dbg_2d(f"Shot slice #: {slice_n}") if T > 0.1 or self.target is None: ball = agent.ball_prediction_struct.slices[slice_n].physics.location self.ball = Vector(ball.x, ball.y, ball.z) self.target = self.ball - (self.shot_vector * agent.best_shot_value * 0.8) if agent.me.location.z > 2044 - agent.me.hitbox.height * 1.1: self.ceiling = True self.target -= Vector(z=92) if not self.ceiling and (self.jumping or not agent.me.airborne): agent.dbg_2d("Jumping") if not self.jumping or not agent.me.airborne: self.jumping = True self.jump_time = agent.time self.counter = 0 jump_elapsed = agent.time - self.jump_time tau = jump_max_duration - jump_elapsed if jump_elapsed == 0: vf += agent.me.up * jump_speed xf += agent.me.up * jump_speed * T vf += agent.me.up * jump_acc * tau xf += agent.me.up * jump_acc * tau * (T - 0.5 * tau) if self.fast_aerial: vf += agent.me.up * jump_speed xf += agent.me.up * jump_speed * (T - tau) if jump_elapsed < jump_max_duration: agent.controller.jump = True elif self.counter < 6: self.counter += 1 if self.counter == 3: agent.controller.jump = True self.dodging = True elif self.counter == 6: self.dodging = self.jumping = False elif jump_elapsed < jump_max_duration: agent.controller.jump = True else: self.jumping = False if self.ceiling: agent.dbg_2d(f"Ceiling shot") delta_x = self.target - xf direction = delta_x.normalize() agent.line(agent.me.location, self.target, agent.renderer.white()) c_vf = vf + agent.me.location agent.line(c_vf - Vector(z=100), c_vf + Vector(z=100), agent.renderer.blue()) agent.line(xf - Vector(z=100), xf + Vector(z=100), agent.renderer.red()) agent.line(self.target - Vector(z=100), self.target + Vector(z=100), agent.renderer.green()) if not self.dodging: target = delta_x if delta_x.magnitude() > 50 else (self.target - agent.me.location) if self.jumping: target = target.flatten() target = agent.me.local(target) if abs(Vector(x=1).angle(target)) > 0.005: defaultPD(agent, target, upside_down=self.shot_vector.z < 0 and not self.jumping) if abs(agent.me.forward.dot(direction)) > 0.5: delta_v = delta_x.dot(agent.me.forward) / T if agent.me.boost > 0 and delta_v >= agent.boost_accel * min_boost_time: agent.controller.boost = True else: agent.controller.throttle = cap(delta_v / (throttle_accel * min_boost_time), -1, 1) if T <= 0 or (not self.jumping and not agent.me.airborne) or (not self.jumping and T > 2 and self.fast_aerial and not virxrlcu.aerial_shot_is_viable(T + 0.3, 144, agent.boost_accel, agent.gravity.tuple(), agent.me.location.tuple(), agent.me.velocity.tuple(), agent.me.up.tuple(), agent.me.forward.tuple(), 1 if agent.me.airborne else -1, agent.me.boost if agent.boost_amount != 'unlimited' else 100000, self.ball.tuple())): agent.pop() agent.shooting = False agent.shot_weight = -1 agent.shot_time = -1 agent.push(ball_recovery()) elif (self.ceiling and self.target.dist(agent.me.location) < 92 + agent.me.hitbox.length and not agent.me.doublejumped and agent.me.location.z < agent.ball.location.z + 92 and self.target.y * side(agent.team) > -4240) or (not self.ceiling and not self.fast_aerial and self.target.dist(agent.me.location) < 92 + agent.me.hitbox.length and not agent.me.doublejumped): agent.dbg_2d("Flipping") agent.controller.jump = True local_target = agent.me.local_location(self.target) agent.controller.pitch = abs(local_target.x) * -sign(local_target.x) agent.controller.yaw = abs(local_target.y) * sign(local_target.y) class flip: # Flip takes a vector in local coordinates and flips/dodges in that direction # cancel causes the flip to cancel halfway through, which can be used to half-flip def __init__(self, vector, cancel=False): self.vector = vector.normalize() self.pitch = abs(self.vector.x) * -sign(self.vector.x) self.yaw = abs(self.vector.y) * sign(self.vector.y) self.cancel = cancel # the time the jump began self.time = -1 # keeps track of the frames the jump button has been released self.counter = 0 def run(self, agent, manual=False): if agent.gravity.z >= 3250: agent.pop() if self.time == -1: elapsed = 0 self.time = agent.time else: elapsed = agent.time - self.time if elapsed < 0.15: agent.controller.jump = True elif elapsed >= 0.15 and self.counter < 3: agent.controller.jump = False self.counter += 1 elif elapsed < 0.3 or (not self.cancel and elapsed < 0.9): agent.controller.jump = True agent.controller.pitch = self.pitch agent.controller.yaw = self.yaw elif manual: return True else: agent.pop() agent.push(recovery()) class brake: @staticmethod def run(agent, manual=False): # current forward velocity speed = agent.me.local_velocity().x if abs(speed) > 10: # apply our throttle in the opposite direction # Once we're below a velocity of 50uu's, start to ease the throttle agent.controller.throttle = cap(speed / -50, -1, 1) elif not manual: agent.pop() class goto: # Drives towards a designated (stationary) target # Optional vector controls where the car should be pointing upon reaching the target def __init__(self, target, vector=None, brake=False): self.target = target self.vector = vector self.brake = brake self.rule1_timer = -1 def run(self, agent, manual=False): car_to_target = self.target - agent.me.location distance_remaining = car_to_target.flatten().magnitude() angle_to_target = abs(Vector(x=1).angle2D(agent.me.local(car_to_target))) direction = 1 if angle_to_target <= 2 or (agent.gravity.z > -450 and distance_remaining >= 1000) else -1 agent.dbg_2d(f"Angle to target: {angle_to_target}") agent.dbg_2d(f"Distance to target: {distance_remaining}") agent.line(self.target - Vector(z=500), self.target + Vector(z=500), (255, 0, 255)) if (not self.brake and distance_remaining < 350) or (self.brake and distance_remaining * 0.95 < (agent.me.local_velocity().x ** 2 * -1) / (2 * brake_accel.x)): if not manual: agent.pop() if self.brake: agent.push(brake()) return final_target = self.target.copy() # Some adjustment to the final target to ensure it's inside the field and we don't try to drive through any goalposts to reach it if abs(agent.me.location.y) > 5120 - (agent.me.hitbox.length / 2): final_target.x = cap(final_target.x, -750, 750) if self.vector is not None: # See comments for adjustment in jump_shot for explanation side_of_vector = sign(self.vector.cross(Vector(z=1)).dot(car_to_target)) car_to_target_perp = car_to_target.cross(Vector(z=side_of_vector)).normalize() adjustment = car_to_target.angle2D(self.vector) * distance_remaining / 3.14 final_target += car_to_target_perp * adjustment local_target = agent.me.local_location(final_target) defaultPD(agent, local_target) target_speed = 2300 if distance_remaining > 640 else 1400 defaultThrottle(agent, target_speed * direction) # this is to break rule 1's with TM8'S ONLY # 251 is the distance between center of the 2 longest cars in the game, with a bit extra if len(agent.friends) > 0 and agent.me.local_velocity().x < 50 and agent.controller.throttle == 1 and min(agent.me.location.flat_dist(car.location) for car in agent.friends) < 251: if self.rule1_timer == -1: self.rule1_timer = agent.time elif agent.time - self.rule1_timer > 1.5: agent.push(flip(Vector(y=250))) return elif self.rule1_timer != -1: self.rule1_timer = -1 if distance_remaining < 320: agent.controller.boost = False agent.controller.handbrake = angle_to_target > 1.54 if direction == 1 else angle_to_target < 2.2 velocity = agent.me.local_velocity().x if agent.boost_amount != 'unlimited' and angle_to_target < 0.03 and distance_remaining > 1920 and velocity > 600 and velocity < 2150 and distance_remaining / velocity > 2: if agent.gravity.z < -450: agent.push(wave_dash()) else: agent.push(flip(local_target)) elif direction == -1 and distance_remaining > 1000 and velocity < 200: agent.push(flip(local_target, True)) elif agent.me.airborne: agent.push(recovery(self.target)) class shadow: def __init__(self): self.goto = goto(Vector(), brake=True) def run(self, agent): ball_slice = agent.ball_prediction_struct.slices[agent.future_ball_location_slice].physics.location ball_loc = Vector(ball_slice.x, ball_slice.y) agent.line(ball_loc, ball_loc + Vector(z=185), agent.renderer.white()) ball_loc.y *= side(agent.team) if ball_loc.y < -2560 or (ball_loc.y < agent.ball.location.y * side(agent.team)): ball_loc = Vector(agent.ball.location.x, agent.ball.location.y * side(agent.team) + 640) distance = 1280 target = Vector(y=(ball_loc.y + distance) * side(agent.team)) agent.line(target, target + Vector(z=642), (255, 0, 255)) target.x = (abs(ball_loc.x) + (250 if target.y < -1280 else -(1024 if abs(ball_loc.x) > 1024 else ball_loc.x))) * sign(ball_loc.x) self_to_target = agent.me.location.dist(target) if self_to_target < 250 and ball_loc.y < -640 and agent.me.velocity.magnitude() < 100 and abs(Vector(x=1).angle2D(agent.me.local_location(agent.ball.location))) > 0.1: agent.push(face_target(ball=True)) else: self.goto.target = target self.goto.vector = agent.ball.location self.goto.run(agent, manual=True) if self_to_target < 500: agent.controller.boost = False class retreat: def __init__(self): self.goto = goto(Vector()) self.brake = brake() def run(self, agent): ball_slice = agent.ball_prediction_struct.slices[agent.future_ball_location_slice].physics.location ball = Vector(ball_slice.x, cap(ball_slice.y, -5100, 5100)) agent.line(ball, ball + Vector(z=185), agent.renderer.white()) ball.y *= side(agent.team) if ball.y < agent.ball.location.y * side(agent.team): ball = Vector(agent.ball.location.x, agent.ball.location.y * side(agent.team) + 640) target = self.get_target(agent) agent.line(target, target + Vector(z=642), (255, 0, 255)) if target.flat_dist(agent.me.location) < 350: if agent.me.velocity.magnitude() > 100: self.brake.run(agent, manual=True) elif abs(Vector(x=1).angle2D(agent.me.local_location(ball))) > 0.5: agent.pop() agent.push(face_target(ball=True)) else: agent.pop() else: self.goto.target = target self.goto.run(agent, manual=True) def get_target(self, agent): target = None ball_slice = agent.ball_prediction_struct.slices[agent.future_ball_location_slice].physics.location ball = Vector(ball_slice.x, ball_slice.y, ball_slice.z) ball_y = ball.y * side(agent.team) team_to_ball = [car.location.flat_dist(ball) for car in agent.friends if car.location.y * side(agent.team) >= ball_y - 50 and abs(car.location.x) < abs(ball.x)] self_to_ball = agent.me.location.flat_dist(ball) team_to_ball.append(self_to_ball) team_to_ball.sort() if agent.me.location.y * side(agent.team) >= ball_y - 50 and abs(agent.me.location.x) < abs(ball.x): if len(agent.friends) == 0 or abs(ball.x) < 900 or team_to_ball[-1] is self_to_ball: target = agent.friend_goal.location elif team_to_ball[0] is self_to_ball: target = agent.friend_goal.right_post if abs(ball.x) > 10 else agent.friend_goal.left_post if target is None: if len(agent.friends) <= 1: target = agent.friend_goal.location else: target = agent.friend_goal.left_post if abs(ball.x) > 10 else agent.friend_goal.right_post target = target.copy() target.y += 250 * side(agent.team) if len(agent.friends) == 0 or abs(ball.x) < 900 or team_to_ball[-1] is self_to_ball else -245 * side(agent.team) return target.flatten() class face_target: def __init__(self, target=None, ball=False): self.target = target self.ball = ball self.start_loc = None self.counter = 0 def run(self, agent): if self.ball: target = (agent.ball.location - agent.me.location).flatten() else: target = agent.me.velocity.flatten() if self.target is None else (self.target - agent.me.location).flatten() if agent.gravity.z < -550 and agent.gravity.z > -750: if self.counter == 0 and abs(Vector(x=1).angle(target)) <= 0.05: agent.pop() return if self.counter < 3: self.counter += 1 target = agent.me.local(target) if self.counter < 3: agent.controller.jump = True elif agent.me.airborne and abs(Vector(x=1).angle(target)) > 0.05: defaultPD(agent, target) else: agent.pop() else: target = agent.me.local(target) angle_to_target = abs(Vector(x=1).angle2D(target)) if angle_to_target > 0.1: if self.start_loc is None: self.start_loc = agent.me.location direction = -1 if angle_to_target < 1.57 else 1 agent.controller.steer = cap(target.y / 100, -1, 1) * direction agent.controller.throttle = 0.5 * direction agent.controller.handbrake = True else: agent.pop() if self.start_loc is not None: agent.push(goto(self.start_loc, target, True)) class goto_boost: # very similar to goto() but designed for grabbing boost def __init__(self, boost): self.boost = boost self.goto = goto(self.boost.location) def run(self, agent): if not self.boost.large: self.goto.vector = agent.ball.location if not self.boost.active: agent.pop() else: self.goto.run(agent, manual=True) class jump_shot: # Hits a target point at a target time towards a target direction # Target must be no higher than 300uu unless you're feeling lucky def __init__(self, intercept_time, shot_vector): self.intercept_time = intercept_time self.shot_vector = shot_vector self.ball_location = None # Flags for what part of the routine we are in self.jumping = False self.dodging = False self.counter = 0 self.jump_time = -1 def update(self, shot): self.intercept_time = shot.intercept_time self.shot_vector = shot.shot_vector def run(self, agent): if not agent.shooting: agent.shooting = True T = self.intercept_time - agent.time # Capping T above 0 to prevent division problems time_remaining = cap(T, 0.000001, 6) slice_n = round(T * 60) agent.dbg_2d(f"Shot slice #: {slice_n}") if T > 0.3 or self.ball_location is None: ball = agent.ball_prediction_struct.slices[slice_n].physics.location self.ball_location = Vector(ball.x, ball.y, ball.z) self.dodge_point = self.ball_location - (self.shot_vector * agent.best_shot_value) if self.dodge_point.z > 300: agent.pop() return car_to_ball = self.ball_location - agent.me.location # whether we should go forwards or backwards angle_to_target = abs(Vector(x=1).angle2D(agent.me.local(car_to_ball))) # whether we are to the left or right of the shot vector side_of_shot = sign(self.shot_vector.cross(Vector(z=1)).dot(car_to_ball)) final_target = self.dodge_point.copy() # Some adjustment to the final target to ensure it's inside the field and we don't try to drive through any goalposts to reach it if abs(agent.me.location.y) > 5120 - (agent.me.hitbox.length / 2): final_target.x = cap(final_target.x, -750, 750) car_to_dodge_point = final_target - agent.me.location car_to_dodge_perp = car_to_dodge_point.cross(Vector(z=side_of_shot)) # perpendicular acceleration_required = backsolve(self.dodge_point, agent.me, time_remaining, Vector() if not self.jumping else agent.gravity) local_acceleration_required = agent.me.local(acceleration_required) distance_remaining = car_to_dodge_point.flatten().magnitude() # The adjustment causes the car to circle around the dodge point in an effort to line up with the shot vector # The adjustment slowly decreases to 0 as the bot nears the time to jump adjustment = car_to_dodge_point.angle2D(self.shot_vector) * distance_remaining / 2 # size of adjustment # controls how soon car will jump based on acceleration required # we set this based on the time remaining # bigger = later, which allows more time to align with shot vector # smaller = sooner jump_threshold = cap(T * 200, 250, 584) # factoring in how close to jump we are adjustment *= (cap(jump_threshold - (acceleration_required.z), 0, jump_threshold) / jump_threshold) # we don't adjust the final target if we are already jumping final_target += ((car_to_dodge_perp.normalize() * adjustment) if not self.jumping else 0) + Vector(z=50) distance_remaining = (final_target - agent.me.location).flatten().magnitude() direction = 1 if angle_to_target < 2.1 or (agent.gravity.z > -450 and distance_remaining >= 1000) else -1 local_final_target = agent.me.local_location(final_target) # drawing debug lines to show the dodge point and final target (which differs due to the adjustment) agent.line(agent.me.location, self.dodge_point, agent.renderer.white()) agent.line(self.dodge_point-Vector(z=100), self.dodge_point+Vector(z=100), agent.renderer.green()) agent.line(final_target-Vector(z=100), final_target+Vector(z=100), agent.renderer.blue()) vf = agent.me.velocity + agent.gravity * T xf = agent.me.location + agent.me.velocity * T + 0.5 * agent.gravity * T * T ball_l = agent.me.local_location(agent.ball.location) speed_required = 2300 if (self.ball_location.z < 92 + agent.me.hitbox.height / 2 and abs(ball_l.y) < 46 and ball_l.x > agent.me.hitbox.length) or distance_remaining > 2560 else distance_remaining * 0.975 / time_remaining agent.dbg_2d(f"Speed required: {speed_required}") if not self.jumping: defaultPD(agent, local_final_target) defaultThrottle(agent, speed_required * direction) agent.controller.handbrake = angle_to_target > 1.54 if direction == 1 else angle_to_target < 2.2 local_dodge_point = agent.me.local_location(self.dodge_point.flatten()) # use algebra to get the required jump time min_jump_time = self.dodge_point - agent.me.location min_jump_time -= agent.me.velocity * T min_jump_time -= 0.5 * agent.gravity * T * T min_jump_time -= agent.me.up * jump_speed * T min_jump_time /= jump_acc # This leaves us with xf = dT - 0.5d^2, so we use the quadratic formula to solve it min_jump_time = max(quadratic(-0.5, T, sum(min_jump_time) / 3)) min_jump_time += 0.05 f_vf = vf + (agent.me.up * (jump_speed + jump_acc * min_jump_time)) local_vf = agent.me.local(f_vf.flatten()) velocity = agent.me.local_velocity().x if T <= 0 or not virxrlcu.jump_shot_is_viable(T + 0.3, agent.boost_accel, agent.me.location.dist(self.ball_location), self.shot_vector.tuple(), agent.me.forward.tuple(), agent.me.boost if agent.boost_amount != 'unlimited' else 100000, velocity): # If we're out of time or not fast enough to be within 45 units of target at the intercept time, we pop agent.pop() agent.shooting = False agent.shot_weight = -1 agent.shot_time = -1 if agent.me.airborne: agent.push(recovery()) elif self.dodge_point.z > 92 + agent.me.hitbox.height / 2 and ((T <= min_jump_time and self.dodge_point.z >= 175) or (T <= 0.3 and self.dodge_point.z < 175)) and abs(local_dodge_point.y) < (92 if find_slope(self.shot_vector, car_to_ball) > 2 or self.dodge_point.z <= 92 + agent.me.hitbox.height / 2 else math.ceil(92 + agent.me.hitbox.width / 2)) and local_vf.x >= local_dodge_point.x: # Switch into the jump when the upward acceleration required reaches our threshold, and our lateral acceleration is negligible self.jumping = True elif agent.boost_amount != 'unlimited' and angle_to_target < 0.03 and velocity > 600 and velocity < speed_required - 150 and distance_remaining / velocity > 3: if agent.gravity.z < -450: agent.push(wave_dash()) else: agent.push(flip(local_final_target)) elif direction == -1 and velocity < 200 and distance_remaining / abs(velocity) > 2: agent.push(flip(local_final_target, True)) elif agent.me.airborne: agent.push(recovery(local_final_target)) else: if self.jump_time == -1: self.jump_time = agent.time jump_elapsed = agent.time - self.jump_time tau = jump_max_duration - jump_elapsed if jump_elapsed == 0: vf += agent.me.up * jump_speed xf += agent.me.up * jump_speed * T vf += agent.me.up * jump_acc * tau xf += agent.me.up * jump_acc * tau * (T - 0.5 * tau) delta_x = self.dodge_point - xf d_direction = delta_x.normalize() if abs(agent.me.forward.dot(d_direction)) > 0.5 and self.counter < 3: delta_v = delta_x.dot(agent.me.forward) / T if agent.me.boost > 0 and delta_v >= agent.boost_accel * min_boost_time: agent.controller.boost = True else: agent.controller.throttle = cap(delta_v / (throttle_accel * min_boost_time), -1, 1) if T <= -0.4 or (not agent.me.airborne and self.counter >= 3): agent.pop() agent.shooting = False agent.shot_weight = -1 agent.shot_time = -1 agent.push(recovery()) return else: if self.counter == 3 and agent.me.location.dist(self.dodge_point) < (92.75 + agent.me.hitbox.length) * 1.05: # Get the required pitch and yaw to flip correctly vector = agent.me.local(self.shot_vector) self.p = abs(vector.x) * -sign(vector.x) self.y = abs(vector.y) * sign(vector.y) * direction # simulating a deadzone so that the dodge is more natural self.p = cap(self.p, -1, 1) if abs(self.p) > 0.1 else 0 self.y = cap(self.y, -1, 1) if abs(self.y) > 0.1 else 0 agent.controller.pitch = self.p agent.controller.yaw = self.y # Wait 1 more frame before dodging self.counter += 1 elif self.counter == 4: # Dodge agent.controller.jump = True agent.controller.pitch = self.p agent.controller.yaw = self.y else: # Face the direction we're heading in, with the z of our target target = agent.me.local(agent.me.velocity.flatten()) target.z = agent.me.local_location(self.dodge_point).z defaultPD(agent, target) if jump_elapsed < jump_max_duration and vf.z < self.dodge_point.z: # Initial jump to get airborne + we hold the jump button for extra power as required agent.controller.jump = True elif self.counter < 3: # Make sure we aren't jumping for at least 3 frames self.counter += 1 l_vf = vf + agent.me.location agent.line(l_vf-Vector(z=100), l_vf+Vector(z=100), agent.renderer.red()) class generic_kickoff: def __init__(self): self.start_time = -1 self.flip = False def run(self, agent): if self.start_time == -1: self.start_time = agent.time if self.flip or agent.time - self.start_time > 3: agent.kickoff_done = True agent.pop() return target = agent.ball.location + Vector(y=(200 if agent.gravity.z < -600 and agent.gravity.z > -700 else 50)*side(agent.team)) local_target = agent.me.local_location(target) defaultPD(agent, local_target) agent.controller.throttle = 1 agent.controller.boost = True distance = local_target.magnitude() if distance < 550: self.flip = True agent.push(flip(agent.me.local_location(agent.foe_goal.location))) class recovery: # Point towards our velocity vector and land upright, unless we aren't moving very fast # A vector can be provided to control where the car points when it lands def __init__(self, target=None): self.target = target def run(self, agent): local_target = agent.me.local(agent.me.velocity.flatten()) if self.target is None else agent.me.local((self.target - agent.me.location).flatten()) agent.dbg_2d(f"Recovering towards {self.target}") recover_on_ceiling = agent.me.velocity.z > 0 and agent.me.location.z > 1500 if recover_on_ceiling: agent.dbg_2d(f"Recovering on the ceiling") defaultPD(agent, local_target, upside_down=recover_on_ceiling) agent.controller.throttle = 1 if not agent.me.airborne: agent.pop() class ball_recovery: def __init__(self): self.recovery = recovery() def run(self, agent): self.recovery.target = agent.ball.location self.recovery.target.y = cap(self.recovery.target.y, -5100, 5100) self.recovery.run(agent) class short_shot: # This routine drives towards the ball and attempts to hit it towards a given target # It does not require ball prediction and kinda guesses at where the ball will be on its own def __init__(self, target): self.target = target self.start_time = None def run(self, agent): if not agent.shooting: agent.shooting = True if self.start_time is None: self.start_time = agent.time car_to_ball, distance = (agent.ball.location - agent.me.location).normalize(True) ball_to_target = (self.target - agent.ball.location).normalize() angle_to_target = abs(Vector(x=1).angle2D(agent.me.local(car_to_ball))) relative_velocity = car_to_ball.dot(agent.me.velocity-agent.ball.velocity) eta = cap(distance / cap(relative_velocity, 400, 1400), 0, 1.5) if relative_velocity != 0 else 1.5 # If we are approaching the ball from the wrong side the car will try to only hit the very edge of the ball left_vector = car_to_ball.cross(Vector(z=1)) right_vector = car_to_ball.cross(Vector(z=-1)) target_vector = -ball_to_target.clamp2D(left_vector, right_vector) final_target = agent.ball.location + (target_vector*(distance/2)) # Some adjustment to the final target to ensure we don't try to drive through any goalposts to reach it if abs(agent.me.location.y) > 5130: final_target.x = cap(final_target.x, -750, 750) agent.line(final_target-Vector(z=100), final_target + Vector(z=100), (255, 255, 255)) angles = defaultPD(agent, agent.me.local_location(final_target)) defaultThrottle(agent, 1400) agent.controller.handbrake = angle_to_target > 1.54 if abs(angles[1]) < 0.05 and (eta < 0.45 or distance < 150): agent.pop() agent.shooting = False agent.push(flip(agent.me.local(car_to_ball))) elif agent.time - self.start_time > 0.24: # This will run for 3 ticks, then pop agent.pop() agent.shooting = False class boost_down: def __init__(self): self.face = ball_recovery() def run(self, agent): if agent.me.boost == 0: agent.pop() agent.push(self.face) target = agent.me.local(agent.me.forward.flatten()*100 - Vector(z=100)) defaultPD(agent, target) if not agent.me.airborne: agent.pop() elif abs(Vector(x=1).angle(target)) < 0.5: agent.controller.boost = True
// { Driver Code Starts #include <bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution{ public: int countSubArrayProductLessThanK(const vector<int>& a, int n, long long k) { long prod=1; int j=0,ans=0; for(int i=0;i<n;i++){ prod*=a[i]; while(j<n&&prod>=k){ prod/=a[j]; j++; } ans+=(i-j+1); } return ans; } }; // { Driver Code Starts. int main() { int t; cin >> t; while (t--) { int n, i; long long int k; cin >> n >> k; vector<int> arr(n); for (i = 0; i < n; i++) cin >> arr[i]; Solution obj; cout << obj.countSubArrayProductLessThanK(arr, n, k) << endl; } return 0; } // } Driver Code Ends
def ensure_service_directory(self, relative_name): path = _service_directory(self._local_state_file, relative_name) makedirs_ok_if_exists(path) return path
/** * Creates a Table from given collection of objects with a given row type. * * <p>The difference between this method and {@link #fromValues(Object...)} is that the schema * can be manually adjusted. It might be helpful for assigning more generic types like * e.g. DECIMAL or naming the columns. * * <p>Examples: * <pre>{@code * tEnv.fromValues( * DataTypes.ROW( * DataTypes.FIELD("id", DataTypes.DECIMAL(10, 2)), * DataTypes.FIELD("name", DataTypes.STRING()) * ), * row(1, "ABC"), * row(2L, "ABCDE") * ) * }</pre> * will produce a Table with a schema as follows: * <pre>{@code * root * |-- id: DECIMAL(10, 2) * |-- name: STRING * }</pre> * * <p>For more examples see {@link #fromValues(Object...)}. * * @param rowType Expected row type for the values. * @param values Expressions for constructing rows of the VALUES table. * @see #fromValues(Object...) */ default Table fromValues(AbstractDataType<?> rowType, Object... values) { return fromValues(rowType, Arrays.asList(values)); }
// word list need it so we may need it in the future. public static void markAsUsed(final Context context, final String clientId, final String wordlistId, final int version, final int status, final boolean allowDownloadOnMeteredData) { final WordListMetadata wordListMetaData = MetadataHandler.getCurrentMetadataForWordList( context, clientId, wordlistId, version); if (null == wordListMetaData) return; final ActionBatch actions = new ActionBatch(); if (MetadataDbHelper.STATUS_DISABLED == status || MetadataDbHelper.STATUS_DELETING == status) { actions.add(new ActionBatch.EnableAction(clientId, wordListMetaData)); } else if (MetadataDbHelper.STATUS_AVAILABLE == status) { actions.add(new ActionBatch.StartDownloadAction(clientId, wordListMetaData)); } else { Log.e(TAG, "Unexpected state of the word list for markAsUsed : " + status); } actions.execute(context, new LogProblemReporter(TAG)); signalNewDictionaryState(context); }
Evaluation of the Patterns of Non-Adherence to Anti-Platelet Regimens in Stented Patients Bleeding Score for Predicting the Long-term Out-of-hospital Bleeding Risk in Chinese Patients after Percutaneous Coronary Intervention Background: The Patterns of Non-Adherence to Anti-Platelet Regimens in Stented Patients (PARIS) bleeding score is a novel score for predicting the out-of-hospital bleeding risk after percutaneous coronary intervention (PCI). However, whether this score has the same value in non-European and American populations is unclear. This study aimed to assess the PARIS bleeding score's predictive value of bleeding in patients after PCI in the Chinese population. Methods: We performed a prospective, observational study of 10,724 patients who underwent PCI from January to December 2013, in Fuwai Hospital, China. We defined the primary end point as major bleeding (MB) according to Bleeding Academic Research Consortium definition criteria including Type 2, 3, or 5. The predictive value of the PARIS bleeding score was assessed with the area under the receiver operating characteristic (AUROC) curve. Results: Of 9782 patients, 245 (2.50%) MB events occurred during the 2 years of follow-up. The PARIS bleeding score was significantly higher in the MB group than that of non-MB group (4.00 vs. 3.00 , Z = 3.71, P < 0.001). According to risk stratification of the PARIS bleeding score, the bleeding risk in the intermediate- and high-risk groups was 1.50 times (hazard ratio : 1.50; 95% confidence interval : 1.160–1.950; P = 0.002) and 2.27 times higher (HR: 2.27; 95% CI: 1.320–3.900; P = 0.003) than that in the low-risk group. The PARIS bleeding score showed a moderate predictive value for MB in the overall population (AUROC: 0.568, 95% CI: 0.532–0.605; P < 0.001) and acute coronary syndrome (ACS) subgroup (AUROC: 0.578, 95% CI: 0.530–0.626; P = 0.001) and tended to be predictive in the non-ACS subgroup (AUROC: 0.556, 95% CI: 0.501–0.611; P = 0.054). Conclusion: The PARIS bleeding score shows good clinical value for risk stratification and has a significant, but relatively limited, prognostic value for out-of-hospital bleeding in the Chinese population after PCI. increases the risk for adverse cardiovascular and even death events. Therefore, identifying patients at a high risk of bleeding is important in clinical work. The novel Patterns of Non-Adherence to Anti-Platelet Regimen in Stented Patients (PARIS) bleeding score was derived from European and American people to predict the out-of-hospital risk for stent thrombosis and the risk of bleeding after PCI. However, whether this score has the same predictive value in the Asian population is unclear. Validation of the risk score in different geographical and ethnic populations is important. An example of this importance is that a previous study showed that Framingham functions overestimated the risk of coronary heart disease in the Chinese population. Therefore, this study aimed to assess the PARIS bleeding score after PCI in a large sample of the Chinese population in patients with drug-eluting stents. Ethical approval The study was conducted in accordance with the Declaration of Helsinki and was by the hospital's Research Ethics Committee (No. 2013-449). The Institutional Review Board approved the study protocol and all of the patients provided written informed consent. Study design Data from all consecutive patients from a single center (Fuwai Hospital, China) who underwent PCI were prospectively collected. Between January and December 2013, a total of 10,724 consecutive patients were enrolled. We excluded patients who were not prescribed DAPT on discharge and those who did not successfully receive drug-eluting stents in at least one native coronary artery and those with in-hospital events including major bleeding (MB), stent thrombosis, myocardial infarction, and death. Finally, a total of 9782 patients were included in the final analysis. Aspirin was prescribed at a dose of 100 mg daily indefinitely. Clopidogrel 75 mg daily or ticagrelor 90 mg twice daily was advised for at least 1 year after PCI. End points and definitions The PARIS bleeding score in this study was based on the bleeding risk score of PARIS. The PARIS bleeding score consisted of six factors including age, body mass index, current smoking, anemia, creatinine clearance (CrCl) <60 ml/min, and triple therapy on discharge. Bleeding was quantified according to Bleeding Academic Research Consortium (BARC) definition criteria. MB was defined as Type 2, 3, or 5 from the BARC criteria. According to the PARIS study definitions, anemia was classified as hemoglobin levels <120 g/L in men and <110 g/L in women. CrCl was calculated using the Cockcroft-Gault formula. Follow-up All of the patients were evaluated by a clinical visit or by phone at 30 days and at 6, 12, and 24 months. Patients were advised to return for coronary angiography if clinically indicated by symptoms or documentation of myocardial ischemia. All adverse events were observed and adjudicated centrally by two independent cardiologists, and disagreement was resolved by consensus. Statistical analysis Categorical variables are expressed as frequency (percentage) and continuous variables are expressed as mean ± standard deviation (SD) or median (P25, P75). Mean values of continuous variables with normal distribution were compared by the Student's t-test, median values of continuous variables with nonnormal distribution were compared using nonparametric test (Wilcoxon), and the Pearson's Chi-square test or Fisher's exact test was used to compare categorical variables. Risk stratification was performed according to the original PARIS bleeding score as three risk strata (low risk, 0-3; moderate risk, 4-7; and high risk, ≥8). The predictive value of the PARIS bleeding score was assessed with the area under the receiver operating characteristic (AUROC) curve. All tests were two-sided, and a value of P < 0.05 was considered statistically significant. Statistical analysis was performed with SAS 9.2 software (SAS Institute, Cary, NC, USA). Patients' characteristics Among 10,724 patients undergoing PCI, we excluded those who failed to satisfy the enrollment requirements according to the original PARIS study . A total of 9782 patients were involved in the final analysis, with a mean age of 58.2 ± 10.2 years, 22.90% of patients were women, and 60.00% had acute coronary syndrome (ACS). Only 13 (0.13%) patients received ticagrelor and the rest of the patients took clopidogrel (99.87%). Only 17 (0.17%) patients received triple therapy with aspirin, a P2Y12 receptor inhibitor, and an oral anticoagulant drug. No patients received bivalirudin or prasugrel. A high proportion (91.20%) of patients with the transradial approach (TRA) of PCI was observed in this study. Patterns of Non-Adherence to Anti-Platelet Regimens in Stented Patients score in the major bleeding and non-major bleeding groups The bleeding risk score of PARIS was significantly higher in the MB group than that in the non-MB group (4.00 vs. 3.00 , Z = 3.71, P < 0.001; Table 1). Bleeding risk stratifications of Patterns of Non-Adherence to Anti-Platelet Regimens in Stented Patients According to the bleeding risk stratification of PARIS, low risk (0-3), intermediate risk (4-7), and high risk (≥8), the Predictive value of bleeding events using the Patterns of Non-Adherence to Anti-Platelet Regimens in Stented Patients bleeding score The PARIS bleeding score appeared to have predictive value for MB in the overall population (AUROC: 0.568; 95% CI: 0.532-0.605; P < 0.001). This score was further assessed in the ACS and non-ACS subgroups. The PARIS bleeding score appeared to have predictive value for MB in the ACS population, with an AUROC of 0.578 (95% CI: 0.530-0.626; P = 0.001). In the non-ACS population, the AUROC from the PARIS bleeding score was 0.556 (95% CI: 0.501-0.611; P = 0.054), but this only tended to have predictive value . dIscussIon At present, some bleeding scores are used clinically, and different bleeding scores are used for different patients. The Hypertension, Abnormal renal/liver function, Stroke, Bleeding history or predisposition, Labile international normalized ratio, Elderly (>65 years), Drugs/alcohol concomitantly (HAS-BLED) score for bleeding risk assessment is used in patients with atrial fibrillation, and the CRUSADE and ACUITY bleeding scores for in-hospital bleeding risk assessment are used in patients with acute myocardial infarction. The PARIS bleeding score is a newly reported score system for assessing out-of-hospital bleeding and thrombosis in patients with DAPT after PCI. Due to possible ethnic variations, we assessed the PARIS bleeding score according to BARC Type 2, 3, or 5 as a clinical end point in a large-scale, single-center, Chinese population in the real world. We found that the PARIS bleeding score showed the good clinical value of risk stratification in the Chinese population. In patients who experienced out-of-hospital MB after PCI, the PARIS bleeding score was significantly raised. Based on the risk stratification of the PARIS bleeding score, the score in the high-risk group was 2.27 times higher than that in the low-risk group, and that in the intermediate-risk group was 1.50 times higher than that in the low-risk group. These findings indicated that risk stratification of the PARIS bleeding score had satisfactory discrimination for a low, intermediate, and high risk of bleeding in patients with DAPT after PCI. Clinicians may find that identifying patients at high risk of bleeding and adopting corresponding treatments for populations at different bleeding risks are useful strategies. For patients at a high risk of bleeding, to reduce the risk of bleeding, enhancing monitoring and preventing bleeding, selecting appropriate types of antiplatelet and antithrombotic therapy, deploying new-generation drug-eluting stents, and choosing a relatively short DAPT duration are important. The present study is the first to evaluate the PARIS bleeding score according to BARC Type 2, 3, or 5 as end points in a large, real-world, Chinese population. The AROUC (0.568) in this study was relatively lower than the original PARIS bleeding score according to BARC Type 3 or 5 as a clinical end point (AUROC of 0.72 in the original PARIS study and 0.64 in a validation study ). This difference among studies might be related to the following reasons: (1) there were different definitions for MB between this study and the PARIS study. MB under the definition of the PARIS study refers to BARC Type 3 or 5, whereas MB in the current study refers to BARC Type 2, 3, or 5. Different MB definitions might affect the results. (2) There was a relatively low incidence of bleeding events in the study. The bleeding incidence in this study was 2.50%, which is lower than that in the PARIS study (3.17%). The study had a relatively low-risk bleeding rate compared with the PARIS study. Previous studies reported a large difference in the incidence of bleeding after PCI, ranging from 0.20% to 8.80%. These differences were mainly associated with different definitions of bleeding, ethnic variations, various study populations, different frequencies of using anticoagulant drugs, and various follow-up durations among the studies. Ratib et al. showed that the incidence of bleeding in 30 days after PCI through TRA was only 0.20%. Mehran et al. showed that the out-of-hospital incidence of bleeding in a 2-year follow-up after PCI was 1.4%. In addition, in the CREDO study, the incidence of bleeding at 1 year was as high as 8.80%. This study had some characteristics that might have affected the bleeding rate as follows: (1) there was a high proportion of patients with TRA-PCI in the present study (91.20%); (2) a low percentage of the population received oral triple therapy comprising anticoagulants, aspirin, and a P2Y12 receptor inhibitor (n = 17, 0.17%); (3) none of the maintenance doses of aspirin were higher than 100 mg; and (4) there was a low rate of using ticagrelor in 2013 in China (only 0.13% in this study). Previous studies showed that the use of the TRA and a low maintenance dose of aspirin may decrease the incidence of bleeding, triple therapy, and the use of strong P2Y12 receptor inhibitors may increase the bleeding risk. All of the above factors might affect the PARIS bleeding score's predictive value in this study. Therefore, the present study suggested that the clinical value of the PARIS bleeding score was limited in the Chinese population according to BARC Type 2, 3, or 5 as the clinical end point. The clinical value of the PARIS bleeding score for predicting bleeding in the ACS and non-ACS subgroups after drug-eluting stents has not been previously reported. Therefore, we further assessed the PARIS bleeding score in the ACS and non-ACS subgroups. We found that the PARIS bleeding score showed a significant predictive value of bleeding in the ACS population. However, in the non-ACS population, this score only showed a tendency to predict bleeding. Therefore, we concluded that the predictive value of the PARIS bleeding score was better in patients with ACS than that in those with non-ACS. Further studies and validation are required for determining the clinical predictive value of the PARIS bleeding score in the non-ACS population. In this study, the PARIS bleeding score showed a significant, but relatively limited, prognostic value for out-of-hospital bleeding after stent implantation in the Chinese population. Therefore, further evaluation is required to determine whether adding more plasma markers and platelet function testing could improve the prognostic value. In addition, a new bleeding risk score that is more suitable for the Chinese population might need to be established. The present study provided the reliable clinical data on the PARIS bleeding score in a Chinese population and provided an important reference for clinical practice. There are some limitations to this study. First, this study was a single-center, observational study, which might have affected the generalizability. Second, most patients in this study received clopidogrel, and the number of patients who received ticagrelor or triple therapy was relatively small. Therefore, the clinical value of using new types of oral antiplatelet drugs, including ticagrelor and prasugrel, and triple therapy requires further assessment using a large-scale clinical study. Finally, more studies should be conducted to evaluate the prognostic value of PARIS according to BARC Type 3 or 5 as end point. This large-population, real-world study shows that the PARIS bleeding score has good clinical value for risk stratification. In addition, the PARIS bleeding score shows a significant, but relatively limited, prognostic value of out-of-hospital bleeding according to BARC Type 2, 3, or 5 in the Chinese PCI population. The PARIS bleeding score also has predictive value for bleeding in the ACS subgroup. Conflicts of interest There are no conflicts of interest.
/* Both Source-Active and Source-Active Response have the same format * with one exception. Encapsulated multicast data is not allowed in * SA Response. */ static void dissect_msdp_sa(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int *offset, int length, proto_item *length_item) { guint32 entries; if (length < 1) { expert_add_info_format(pinfo, length_item, &ei_msdp_tlv_len_too_short, "TLV length for IPv4 Source-Active or Source-Active Response < 5"); return; } proto_tree_add_item_ret_uint(tree, hf_msdp_sa_entry_count, tvb, *offset, 1, ENC_BIG_ENDIAN, &entries); *offset += 1; length -= 1; if (length < 4) { expert_add_info_format(pinfo, length_item, &ei_msdp_tlv_len_too_short, "TLV length for IPv4 Source-Active or Source-Active Response < 5"); *offset += length; return; } proto_tree_add_item(tree, hf_msdp_sa_rp_addr, tvb, *offset, 4, ENC_BIG_ENDIAN); *offset += 4; length -= 4; while (entries-- > 0) { proto_tree *entry_tree; if (length < 12) { expert_add_info_format(pinfo, length_item, &ei_msdp_tlv_len_too_short, "TLV length for IPv4 Source-Active or Source-Active Response too short"); *offset += length; return; } entry_tree = proto_tree_add_subtree_format(tree, tvb, *offset, 12, ett_msdp_sa_entry, NULL, "(S,G) block: %s/%u -> %s", tvb_ip_to_str(tvb, *offset + 8), tvb_get_guint8(tvb, *offset + 3), tvb_ip_to_str(tvb, *offset + 4)); proto_tree_add_item(entry_tree, hf_msdp_sa_reserved, tvb, *offset, 3, ENC_BIG_ENDIAN); *offset += 3; length -= 3; proto_tree_add_item(entry_tree, hf_msdp_sa_sprefix_len, tvb, *offset, 1, ENC_BIG_ENDIAN); *offset += 1; length -= 1; proto_tree_add_item(entry_tree, hf_msdp_sa_group_addr, tvb, *offset, 4, ENC_BIG_ENDIAN); *offset += 4; length -= 4; proto_tree_add_item(entry_tree, hf_msdp_sa_src_addr, tvb, *offset, 4, ENC_BIG_ENDIAN); *offset += 4; length -= 4; } if (length > 0) { proto_tree *enc_tree; gint reported_length; tvbuff_t *next_tvb; enc_tree = proto_tree_add_subtree_format(tree, tvb, *offset, length, ett_msdp_sa_enc_data, NULL, "Encapsulated IPv4 packet: %u bytes", length); reported_length = tvb_reported_length_remaining(tvb, *offset); DISSECTOR_ASSERT(reported_length >= 0); if (reported_length > length) reported_length = length; next_tvb = tvb_new_subset_length(tvb, *offset, reported_length); col_set_writable(pinfo->cinfo, COL_PROTOCOL, FALSE); col_set_writable(pinfo->cinfo, COL_INFO, FALSE); call_dissector(ip_handle, next_tvb, pinfo, enc_tree); } *offset += length; return; }
def empty_slot_values(): return { "type": {"value": {}}, "size": {"value": {}}, "crust": {"value": {}}, "count": {"value": {}}, }
/******************************************************************************* The content of this file includes portions of the AUDIOKINETIC Wwise Technology released in source code form as part of the SDK installer package. Commercial License Usage Licensees holding valid commercial licenses to the AUDIOKINETIC Wwise Technology may use this file in accordance with the end user license agreement provided with the software or, alternatively, in accordance with the terms contained in a written agreement between you and Audiokinetic Inc. Version: v2017.2.6 Build: 6636 Copyright (c) 2006-2018 Audiokinetic Inc. *******************************************************************************/ ////////////////////////////////////////////////////////////////////// // // AkFXSrcAudioInput.cpp // // Sample capture of audio input to be used as a source. // ////////////////////////////////////////////////////////////////////// #include "AkFXSrcAudioInput.h" #include <AK/Tools/Common/AkAssert.h> #include <math.h> #include <AK/AkWwiseSDKVersion.h> // Holds audio input information struct AudioInputStream { AkReal32 * m_pData; AkUInt32 m_uDataSize; AkUInt32 m_uSampleRate; AudioInputStream() : m_pData(NULL), m_uDataSize(0), m_uSampleRate(0) {} }; AkAudioInputPluginExecuteCallbackFunc CAkFXSrcAudioInput::m_pfnExecCallback = NULL; AkAudioInputPluginGetFormatCallbackFunc CAkFXSrcAudioInput::m_pfnGetFormatCallback = NULL; AkAudioInputPluginGetGainCallbackFunc CAkFXSrcAudioInput::m_pfnGetGainCallback = NULL; // Useful definitions static const AkReal32 RAMPMAXTIME = 0.1f; // 100 ms ramps, worst-case // Plugin mechanism. FX create function and register its address to the FX manager. AK::IAkPlugin* CreateAudioInputSource( AK::IAkPluginMemAlloc * in_pAllocator ) { return AK_PLUGIN_NEW( in_pAllocator, CAkFXSrcAudioInput() ); } // Plugin mechanism. Parameter node create function to be registered to the FX manager. AK::IAkPluginParam * CreateAudioInputSourceParams(AK::IAkPluginMemAlloc * in_pAllocator) { return AK_PLUGIN_NEW(in_pAllocator, CAkFxSrcAudioInputParams()); } AK::PluginRegistration AkAudioInputSourceRegistration(AkPluginTypeSource, AKCOMPANYID_AUDIOKINETIC, 200, CreateAudioInputSource, CreateAudioInputSourceParams); // Constructor. CAkFXSrcAudioInput::CAkFXSrcAudioInput() : m_pSharedParams( NULL ) , m_pSourceFXContext( NULL ) { } // Destructor. CAkFXSrcAudioInput::~CAkFXSrcAudioInput() { } // Initialization. AKRESULT CAkFXSrcAudioInput::Init( AK::IAkPluginMemAlloc * in_pAllocator, // Memory allocator interface. AK::IAkSourcePluginContext * in_pSourceFXContext, // Source FX context AK::IAkPluginParam * in_pParams, // Effect parameters. AkAudioFormat & io_rFormat // Output audio format. ) { // Keep source FX context (looping info etc.) m_pSourceFXContext = in_pSourceFXContext; // Set parameters access m_pSharedParams = reinterpret_cast<CAkFxSrcAudioInputParams*>(in_pParams); if( m_pfnGetFormatCallback ) { m_pfnGetFormatCallback( in_pSourceFXContext->GetVoiceInfo()->GetPlayingID(), io_rFormat ); } m_Format = io_rFormat; // keeping track of the audio format for future use on Execute(). // Gain ramp initialization AkReal32 fGainIncrement = 1.f/(RAMPMAXTIME*io_rFormat.uSampleRate); m_GainRamp.RampSetup( fGainIncrement, GetGain() ); return AK_Success; } // Term: The effect must destroy itself herein AKRESULT CAkFXSrcAudioInput::Term( AK::IAkPluginMemAlloc * in_pAllocator ) { AK_PLUGIN_DELETE( in_pAllocator, this ); return AK_Success; } // Reset. Reinitialize processing state. AKRESULT CAkFXSrcAudioInput::Reset( ) { return AK_Success; } // Effect info query. AKRESULT CAkFXSrcAudioInput::GetPluginInfo( AkPluginInfo & out_rPluginInfo ) { out_rPluginInfo.eType = AkPluginTypeSource; out_rPluginInfo.bIsInPlace = true; out_rPluginInfo.uBuildVersion = AK_WWISESDK_VERSION_COMBINED; return AK_Success; } AkReal32 CAkFXSrcAudioInput::GetGain() { AkReal32 gain = 1.0; if( m_pSharedParams ) gain = m_pSharedParams->GetGain(); if( m_pfnGetGainCallback ) gain *= m_pfnGetGainCallback( m_pSourceFXContext->GetVoiceInfo()->GetPlayingID() ); return gain; } template <class T> void ProcessGainInt(AkUInt32 in_uNumFrames, AkUInt32 in_uNumChannels, AkAudioBuffer * io_pBufferOut, AK::CAkValueRamp& in_rRamp) { T * AK_RESTRICT pBufOut = (T*)(io_pBufferOut->GetChannel( 0 )); for( AkUInt32 i = 0; i < in_uNumFrames; ++i ) { // Tick gain interpolation ramp AkReal32 fCurGain = in_rRamp.Tick(); for( AkUInt32 j = 0; j < in_uNumChannels; ++j ) { *pBufOut = (T)(*pBufOut * fCurGain); pBufOut++; } } } template <class T> void ProcessGain(AkUInt32 in_uNumFrames, AkUInt32 in_uNumChannels, AkAudioBuffer * io_pBufferOut, AK::CAkValueRamp& in_rRamp) { // Each channel will have to process the ramp individually // Since channel are not interleaved, backup the Ramp and restore it at every iteration. AK::CAkValueRamp LocalBackup = in_rRamp; for ( AkUInt32 iChannel = 0; iChannel < in_uNumChannels; ++iChannel ) { if( iChannel != 0 ) in_rRamp = LocalBackup;//Restore the ramp for the new channel. T * AK_RESTRICT pBufOut = (T*)(io_pBufferOut->GetChannel( iChannel )); for( AkUInt32 i = 0; i < in_uNumFrames; ++i ) { // Tick gain interpolation ramp AkReal32 fCurGain = in_rRamp.Tick(); *pBufOut = (T)(*pBufOut * fCurGain); pBufOut++; } } } //Effect processing. void CAkFXSrcAudioInput::Execute( AkAudioBuffer * io_pBufferOut ) { if( !m_pfnExecCallback ) { io_pBufferOut->eState = AK_Fail; io_pBufferOut->uValidFrames = 0; return; } m_GainRamp.SetTarget( GetGain() ); m_pfnExecCallback( m_pSourceFXContext->GetVoiceInfo()->GetPlayingID(), io_pBufferOut); // Change target gain if necessary (RTPC value) AkUInt32 uNumFrames = io_pBufferOut->uValidFrames; AkUInt32 uNumChannels = io_pBufferOut->NumChannels(); if( m_Format.GetTypeID() == AK_FLOAT ) { ProcessGain<AkReal32>(uNumFrames, uNumChannels,io_pBufferOut, m_GainRamp); } else { AKASSERT( m_Format.GetTypeID() == AK_INT ); switch( m_Format.GetBlockAlign() / m_Format.GetNumChannels() ) { case 1: ProcessGainInt<AkInt8>(uNumFrames, uNumChannels, io_pBufferOut, m_GainRamp); break; case 2: ProcessGainInt<AkInt16>(uNumFrames, uNumChannels, io_pBufferOut, m_GainRamp); break; case 4: ProcessGainInt<AkInt32>(uNumFrames, uNumChannels, io_pBufferOut, m_GainRamp); break; default: AKASSERT( !"Unsupported format, no gain applied in AudioInput" ); break; } } } AKRESULT CAkFXSrcAudioInput::StopLooping() { // Since this plug-in is infinite playing, a stoplooping should result in stoping the sound. // returning AK_Fail will do it. return AK_Fail; } void CAkFXSrcAudioInput::SetAudioInputCallbacks( AkAudioInputPluginExecuteCallbackFunc in_pfnExecCallback, AkAudioInputPluginGetFormatCallbackFunc in_pfnGetFormatCallback, AkAudioInputPluginGetGainCallbackFunc in_pfnGetGainCallback ) { if( in_pfnExecCallback && in_pfnGetFormatCallback ) { m_pfnExecCallback = in_pfnExecCallback; m_pfnGetFormatCallback = in_pfnGetFormatCallback; m_pfnGetGainCallback = in_pfnGetGainCallback; } } void SetAudioInputCallbacks( AkAudioInputPluginExecuteCallbackFunc in_pfnExecCallback, AkAudioInputPluginGetFormatCallbackFunc in_pfnGetFormatCallback /*= NULL*/, // Optional AkAudioInputPluginGetGainCallbackFunc in_pfnGetGainCallback /*= NULL*/ // Optional ) { CAkFXSrcAudioInput::SetAudioInputCallbacks( in_pfnExecCallback, in_pfnGetFormatCallback, in_pfnGetGainCallback ); }
<filename>cache.go // Copyright 2018 GRAIL, Inc. All rights reserved. // Use of this source code is governed by the Apache 2.0 // license that can be found in the LICENSE file. package bigslice import ( "context" "reflect" "github.com/grailbio/bigslice/internal/slicecache" "github.com/grailbio/bigslice/sliceio" ) type cacheSlice struct { name Name Slice cache *slicecache.ShardCache } var _ slicecache.Cacheable = (*cacheSlice)(nil) func (c *cacheSlice) Name() Name { return c.name } func (c *cacheSlice) NumDep() int { return 1 } func (c *cacheSlice) Dep(i int) Dep { return Dep{c.Slice, false, false} } func (*cacheSlice) Combiner() *reflect.Value { return nil } func (c *cacheSlice) Reader(shard int, deps []sliceio.Reader) sliceio.Reader { return deps[0] } func (c *cacheSlice) Cache() *slicecache.ShardCache { return c.cache } // Cache caches the output of a slice to the given file prefix. // Cached data are stored as "prefix-nnnn-of-mmmm" for shards nnnn of // mmmm. When the slice is computed, each shard is encoded and // written to a separate file with this prefix. If all shards exist, // then Cache shortcuts computation and instead reads directly from // the previously computed output. The user must guarantee cache // consistency: if the cache is could be invalid (e.g., because of // code changes), the user is responsible for removing existing // cached files, or picking a different prefix that correctly // represents the operation to be cached. // // Cache uses GRAIL's file library, so prefix may refer to URLs to a // distributed object store such as S3. func Cache(ctx context.Context, slice Slice, prefix string) (Slice, error) { shardCache, err := slicecache.NewShardCache(ctx, prefix, slice.NumShard()) if err != nil { return nil, err } shardCache.RequireAllCached() return &cacheSlice{makeName("cache"), slice, shardCache}, nil } // CachePartial caches the output of the slice to the given file // prefix (it uses the same file naming scheme as Cache). However, unlike // Cache, if CachePartial finds incomplete cached results (from an // earlier failed or interrupted run), it will use them and recompute only // the missing data. // // WARNING: The user is responsible for ensuring slice's contents are // deterministic between bigslice runs. If keys are non-deterministic, for // example due to pseudorandom seeding based on time, or reading the state // of a modifiable file in S3, CachePartial produces corrupt results. // // As with Cache, the user must guarantee cache consistency. func CachePartial(ctx context.Context, slice Slice, prefix string) (Slice, error) { shardCache, err := slicecache.NewShardCache(ctx, prefix, slice.NumShard()) if err != nil { return nil, err } return &cacheSlice{makeName("cachepartial"), slice, shardCache}, nil }
Trap-Assisted DRAM Row Hammer Effect Through 3D TCAD simulations with single charge traps, we discovered a direct evidence to the mechanism of DRAM row hammer effect. It is governed by a charge pumping process, consisting of charge capture and emission under or around an aggressor wordline and subsequent carrier migration to a victim storage node. The process is highly sensitive to the location and energy level of acceptor-type traps; a single trap may enhance the row hammer effect by a factor of 60 in a 2y-nm node. Dependencies on bitline junction depth, temperature, and hammering waveform are analyzed, and the results are in good agreement with previously reported experiments. Feature size scaling is found to aggravate the row hammer effect.
def plot_dw_config(_data, ax=None, cmap='twilight', marker='cell', dx=2e-9): data = _data.sort_values('y') if ax is None: _, ax = plt.subplots() cmap = cm.get_cmap(cmap) colors = [cmap(np.arctan2(data.iloc[i]['my'], data.iloc[i]['mx'])/(2*np.pi) + 0.5) for i in range(len(data))] if marker == 'line': segments = [] for i in range(len(data)-1): segments.append(((data.iloc[i]['x'], data.iloc[i]['y']), (data.iloc[i+1]['x'], data.iloc[i+1]['y']))) collection = mplcollections.LineCollection(segments=segments, colors=colors[:-1], linewidths=6) collection.set_capstyle('round') ax.add_collection(collection) elif marker == 'cell': for i in range(len(data)-1): ax.add_patch(patches.Rectangle((data.iloc[i]['x'], data.iloc[i]['y']), dx, dx, edgecolor='none', facecolor=colors[i])) elif marker in ['o', '.']: ax.scatter(data['x'], data['y'], c=colors) ax.set_xlim(0.95*data['x'].min(), 1.05*data['x'].max()) ax.set_ylim(0, data['y'].max()) ax.set_aspect('equal') plt.draw() return
import * as koa from 'koa'; import * as logger from 'koa-logger-winston'; import * as winston from 'winston'; const app = new koa(); app.use(logger(new winston.Logger()));
<reponame>fenriz07/dd-trace-go<filename>contrib/gearbox/gearbox.go // Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2016 Datadog, Inc. // Package gearbox provides tracing functions for APM package gearbox import ( "context" "net/http" "gopkg.in/DataDog/dd-trace-go.v1/ddtrace" "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext" "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer" "github.com/gogearbox/gearbox" ) //Datadog this method should implement at a middleware layer func Datadog(ctx gearbox.Context) { method := string(ctx.Context().Method()) opts := []ddtrace.StartSpanOption{ tracer.SpanType(ext.SpanTypeWeb), tracer.Tag(ext.HTTPMethod, method), tracer.Tag(ext.HTTPURL, ctx.Context().URI().String()), tracer.Measured(), } headers := mapCtxToHTTPHeader(ctx) if spanctx, err := tracer.Extract(tracer.HTTPHeadersCarrier(headers)); err == nil { opts = append(opts, tracer.ChildOf(spanctx)) } span, ctxSpan := tracer.StartSpanFromContext(context.Background(), "http.request", opts...) ctx.SetLocal("ctxspan", ctxSpan) ctx.Next() span.SetTag(ext.ResourceName, string(ctx.Context().URI().Path())) status := ctx.Context().Response.StatusCode() span.SetTag(ext.HTTPCode, status) if status == gearbox.StatusInternalServerError || status == gearbox.StatusBadRequest { span.SetTag(ext.Error, string(ctx.Context().Response.Body()[:5000])) } span.Finish() } func mapCtxToHTTPHeader(ctx gearbox.Context) http.Header { headers := http.Header{} listHeadersDatadog := [3]string{ "X-Datadog-Trace-Id", "X-Datadog-Parent-Id", "X-Datadog-Sampling-Priority", } for _, headerDataDog := range listHeadersDatadog { valueHeader := ctx.Get(headerDataDog) if len(valueHeader) > 0 { headers.Add(headerDataDog, valueHeader) } } return headers }
Kristina Torres was so close. The 26-year-old was just six months away from being eligible to apply for permanent residency in Canada. Then she was fired. She still doesn’t know why. But she suspects that asking the mother of the autistic seven-year-old boy she looked after for better hours than the 16 a day she was working didn’t help. Torres was out of a job. But because the Filipina live-in caregiver was a temporary foreign worker, she was also out of a work permit. And until she could convince an employer to spend the time and money needed to get her a new one, she was out of luck. The trained nurse who’d travelled to the other side of the world to start a new life found herself living on cash her mother sent from the Philippines — a mortifying reversal of Canada’s customary remittance pattern. “To become a burden to people. … It’s brutal.” That was a year ago. Torres is still waiting for her paperwork to come through. So, for that matter, is Torres’s prospective employer, who’s desperate for a full-time caregiver for her husband so she can go back to work. “So both of us are stressed,” Torres said. Canada’s Temporary Foreign Worker program has drawn criticism from all sides of the political spectrum, and for all reasons — for being too broad, too restrictive, too lax, too inflexible. Some say they’re badly needed to fill labour sector-specific shortages in some parts of the country. Others argue those labour shortages would be easy to fill if employers paid enough to make the jobs attractive. Canada’s employers have relied on it increasingly over the past 15 years as a quick way to get labour with few long-term commitments. The total number of annual temporary foreign workers in Canada has more than tripled since 2006. By the late 2000s, the number of people brought in on fixed short-term work visas every year eclipsed the number of people arriving in Canada annually as permanent residents. CANADA’S NEWCOMER CONUNDRUM: Skills mismatch or labour market failure? The program has come under fire from labour unions who argue migrant workers steal Canadians’ jobs and workers’ rights advocates who argue the program creates a labour underclass of people who can’t leave bad jobs and who risk being fired and deported if they report abuse. The program came under much more serious scrutiny two years ago over a dispute involving Royal Bank of Canada and its labour outsourcing partner iGate, amid allegations the bank was firing Canadian workers and hiring cheaper, temporary replacements instead. READ MORE: Who hires temporary foreign workers? Afterward, then-Immigration Minister Jason Kenney vowed to reform the program. The federal Conservatives’ changes include making it harder to apply for the Labour Market Impact Assessment required to hire temporary foreign workers, limited the number of temporary foreign workers certain businesses in certain industries can hire and made it more difficult to keep temporary foreign workers for longer periods of time. But no one seems satisfied by the fixes. Many employers, and some labour-hungry provinces, argue there are too many restrictions, too many hoops to jump through. Temporary foreign workers and people advocating on their behalf argue the new rules just make a Byzantine system more confusing and actually penalize vulnerable workers more, making it even more difficult for them to build long-term lives in the country where they work for eight- or 12-month stretches. An estimated 70,000 people found themselves in limbo, scrambling for permanent residency or stopgap solutions, as their permits ran out April 1 of this year. Even if employers are paying temporary foreign workers above minimum wage, advocates say, if employees aren’t allowed to quit, employers have no incentive to give their workers reason to stay –depressing wages and working conditions for everyone. “Because Temporary Foreign Workers are dependent on the whims of their employers for their right to stay in Canada, they are at a disadvantage in terms of negotiating for fair wages, safe workplaces and respectful treatment,” argues the Alberta Federation of Labour, which has been a vocal critic of the program it calls a “two-tier labour market.” Now the pressure’s greater than ever to take a deceptively simple step: Remove the “temporary” part. “The only solution is for us to get proper status — permanent residency upon arrival,” Torres said. “Unless we get that, employers would still try to put you in a situation where you can’t really say no. … They can still abuse us and get away with whatever, ’cause they know were temporarily here and they know we have fear of being deported.” A hallmark of the program is that its workers are only here for a short time. They aren’t Canadians and there’s no plan for them to become Canadians. “That is the only basis on which to build a migration system that ensures security and decent work for everyone – people who are currently migrant workers and also local workers,” said constitutional lawyer Fay Faraday. Faraday has studied the often treacherous labour environment for Canada’s temporary foreign workers. “The way the labour migration system has been constructed right now, it brings workers into the country on terms that make them profoundly vulnerable to exploitation by employers,” she said. And if workers are brave enough to report abuse and the authorities validate it, Faraday said, the employer loses the ability to employ them, they’re out of a job and possibly deported. “Enforcing the rules actually makes the workers even more vulnerable,” Faraday said. “Employers’ ability to have a captive workforce that is unable to enforce its rights is something that drives down conditions for everyone.” A Statistics Canada study released last week found high-skilled temporary foreign workers — people working in management or in positions requiring at least some post-secondary education — who became permanent residents vastly out-earned their economy class immigrant counterparts, even years after both categories of newcomers had settled in Canada. “Landed immigrants with pre-landing Canadian skilled work experience had very large initial earnings advantage over immigrants who were selected directly from abroad,” co-author Aneta Bonikowska said in an email. “This gap narrowed over the first few years since landing because of higher earnings growth among the latter group, but did not disappear, even 15 years later.” This is likely due to a combination of employers selecting people they like to begin with, and people self-selecting for jobs or industries to which they’re better suited, the authors found. The report didn’t find the same earnings advantage for low-skilled temporary foreign workers, however. This includes everyone from fast-food restaurant workers to farm workers. These, advocates argue, are the people most vulnerable and who have the hardest time obtaining any kind of stable job environment in Canada, let alone permanent resident status. But, Bonikowska notes, a vanishingly small portion of low-skilled (or low-wage, as they’re now called by some federal departments) temporary workers gets the chance to remain in Canada. It remains extremely difficult to do so. Right now, the only class of so-called “low-skilled” or “low-wage” temporary foreign workers who can even apply for permanent resident status are live-in caregivers. And they can only do so after spending 24 months in precarious temp work, and after they find someone willing to pay for the paperwork required to sponsor them. A national Coalition for Migrant Workers Rights wants to change that by giving all Canadian workers the ability to become permanent residents and citizens, and by giving all of them the right to leave jobs they don’t like. The coalition called on the Trudeau government to reform the temporary foreign worker program by removing the “temporary” imperative. Ending “tied” work permits, says the coalition’s Syed Hussan, is “a pragmatic, easy, short-term change that will end bad employers ability to coerce workers, give worker the right everyone takes for granted – which is to change jobs and thereby immediately improve wages and working conditions for Canadian born and migrant workers.” In a way it’s surprising Torres is trying so hard to forge a life in Canada: She spent a year and a half as a live-in caregiver, working 16-hour days for two different families. She got weekends off but couldn’t stay at the families’ homes so paid to crash on someone’s couch. Working closely with germ-sharing young children gave her an incessant cold but she felt guilty taking sick days “because nobody’s going to take over.” But “I have not lost hope in Canada,” she says. “I learned a lot.” And she wants to learn more: to go back to school once she saves up enough money, and study nursing or speech pathology. “I have a million things that I want to do.” In the meantime, she waits. And volunteers at Toronto’s Caregivers Action Centre. “It helps a lot, knowing that youre not alone,” she said. “If I wasn’t involved with meeting other caregivers, I don’t know how I’d make it through.”
def from_items(cls, items: List[Item]) -> MailMessageItems: items = clean_items_relationships(items) stash_id = generate_item_id() for item in items: if not item.parent_id: item.parent_id = stash_id if not item.slot_id: item.slot_id = "main" item.location = None regenerate_items_ids(items) return cls( stash=stash_id, data=items, )
<gh_stars>0 package com.sparrowwallet.sparrow.io; import com.google.gson.*; import com.sparrowwallet.drongo.BitcoinUnit; import com.sparrowwallet.sparrow.Mode; import com.sparrowwallet.sparrow.Theme; import com.sparrowwallet.sparrow.net.*; import com.sparrowwallet.sparrow.wallet.FeeRatesSelection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.lang.reflect.Type; import java.nio.file.Files; import java.nio.file.attribute.PosixFilePermissions; import java.util.Arrays; import java.util.Currency; import java.util.List; import java.util.Random; import java.util.stream.Collectors; public class Config { private static final Logger log = LoggerFactory.getLogger(Config.class); public static final String CONFIG_FILENAME = "config"; private Mode mode; private BitcoinUnit bitcoinUnit; private FeeRatesSource feeRatesSource; private FeeRatesSelection feeRatesSelection; private Currency fiatCurrency; private ExchangeSource exchangeSource; private boolean loadRecentWallets = true; private boolean validateDerivationPaths = true; private boolean groupByAddress = true; private boolean includeMempoolOutputs = true; private boolean notifyNewTransactions = true; private boolean checkNewVersions = true; private Theme theme; private boolean openWalletsInNewWindows = false; private boolean hideEmptyUsedAddresses = false; private boolean showTransactionHex = true; private boolean showLoadingLog = false; private boolean showUtxosChart = true; private List<File> recentWalletFiles; private Integer keyDerivationPeriod; private File hwi; private Boolean hdCapture; private String webcamDevice; private ServerType serverType; private String publicElectrumServer; private String coreServer; private CoreAuthType coreAuthType; private File coreDataDir; private String coreAuth; private Boolean coreMultiWallet; private String coreWallet; private String electrumServer; private File electrumServerCert; private boolean useProxy; private String proxyServer; private static Config INSTANCE; private static Gson getGson() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(File.class, new FileSerializer()); gsonBuilder.registerTypeAdapter(File.class, new FileDeserializer()); return gsonBuilder.setPrettyPrinting().disableHtmlEscaping().create(); } private static File getConfigFile() { File sparrowDir = Storage.getSparrowDir(); return new File(sparrowDir, CONFIG_FILENAME); } private static Config load() { File configFile = getConfigFile(); if(configFile.exists()) { try { Reader reader = new FileReader(configFile); Config config = getGson().fromJson(reader, Config.class); reader.close(); if(config != null) { return config; } } catch(Exception e) { log.error("Error opening " + configFile.getAbsolutePath(), e); //Ignore and assume no config } } return new Config(); } public static synchronized Config get() { if(INSTANCE == null) { INSTANCE = load(); } return INSTANCE; } public Mode getMode() { return mode; } public void setMode(Mode mode) { this.mode = mode; flush(); } public BitcoinUnit getBitcoinUnit() { return bitcoinUnit; } public void setBitcoinUnit(BitcoinUnit bitcoinUnit) { this.bitcoinUnit = bitcoinUnit; flush(); } public FeeRatesSource getFeeRatesSource() { return feeRatesSource; } public void setFeeRatesSource(FeeRatesSource feeRatesSource) { this.feeRatesSource = feeRatesSource; flush(); } public FeeRatesSelection getFeeRatesSelection() { return feeRatesSelection; } public void setFeeRatesSelection(FeeRatesSelection feeRatesSelection) { this.feeRatesSelection = feeRatesSelection; flush(); } public Currency getFiatCurrency() { return fiatCurrency; } public void setFiatCurrency(Currency fiatCurrency) { this.fiatCurrency = fiatCurrency; flush(); } public boolean isFetchRates() { return getExchangeSource() != ExchangeSource.NONE; } public ExchangeSource getExchangeSource() { return exchangeSource; } public void setExchangeSource(ExchangeSource exchangeSource) { this.exchangeSource = exchangeSource; flush(); } public boolean isLoadRecentWallets() { return loadRecentWallets; } public void setLoadRecentWallets(boolean loadRecentWallets) { this.loadRecentWallets = loadRecentWallets; flush(); } public boolean isValidateDerivationPaths() { return validateDerivationPaths; } public void setValidateDerivationPaths(boolean validateDerivationPaths) { this.validateDerivationPaths = validateDerivationPaths; flush(); } public boolean isGroupByAddress() { return groupByAddress; } public void setGroupByAddress(boolean groupByAddress) { this.groupByAddress = groupByAddress; flush(); } public boolean isIncludeMempoolOutputs() { return includeMempoolOutputs; } public void setIncludeMempoolOutputs(boolean includeMempoolOutputs) { this.includeMempoolOutputs = includeMempoolOutputs; flush(); } public boolean isNotifyNewTransactions() { return notifyNewTransactions; } public void setNotifyNewTransactions(boolean notifyNewTransactions) { this.notifyNewTransactions = notifyNewTransactions; flush(); } public boolean isCheckNewVersions() { return checkNewVersions; } public void setCheckNewVersions(boolean checkNewVersions) { this.checkNewVersions = checkNewVersions; flush(); } public Theme getTheme() { return theme; } public void setTheme(Theme theme) { this.theme = theme; flush(); } public boolean isOpenWalletsInNewWindows() { return openWalletsInNewWindows; } public void setOpenWalletsInNewWindows(boolean openWalletsInNewWindows) { this.openWalletsInNewWindows = openWalletsInNewWindows; flush(); } public boolean isHideEmptyUsedAddresses() { return hideEmptyUsedAddresses; } public void setHideEmptyUsedAddresses(boolean hideEmptyUsedAddresses) { this.hideEmptyUsedAddresses = hideEmptyUsedAddresses; flush(); } public boolean isShowTransactionHex() { return showTransactionHex; } public void setShowTransactionHex(boolean showTransactionHex) { this.showTransactionHex = showTransactionHex; flush(); } public boolean isShowLoadingLog() { return showLoadingLog; } public void setShowLoadingLog(boolean showLoadingLog) { this.showLoadingLog = showLoadingLog; flush(); } public boolean isShowUtxosChart() { return showUtxosChart; } public void setShowUtxosChart(boolean showUtxosChart) { this.showUtxosChart = showUtxosChart; flush(); } public List<File> getRecentWalletFiles() { return recentWalletFiles; } public void setRecentWalletFiles(List<File> recentWalletFiles) { this.recentWalletFiles = recentWalletFiles; flush(); } public Integer getKeyDerivationPeriod() { return keyDerivationPeriod; } public void setKeyDerivationPeriod(Integer keyDerivationPeriod) { this.keyDerivationPeriod = keyDerivationPeriod; flush(); } public File getHwi() { return hwi; } public void setHwi(File hwi) { this.hwi = hwi; flush(); } public Boolean getHdCapture() { return hdCapture; } public Boolean isHdCapture() { return hdCapture != null && hdCapture; } public void setHdCapture(Boolean hdCapture) { this.hdCapture = hdCapture; flush(); } public String getWebcamDevice() { return webcamDevice; } public void setWebcamDevice(String webcamDevice) { this.webcamDevice = webcamDevice; flush(); } public ServerType getServerType() { return serverType; } public void setServerType(ServerType serverType) { this.serverType = serverType; flush(); } public boolean hasServerAddress() { return getServerAddress() != null && !getServerAddress().isEmpty(); } public String getServerAddress() { return getServerType() == ServerType.BITCOIN_CORE ? getCoreServer() : (getServerType() == ServerType.PUBLIC_ELECTRUM_SERVER ? getPublicElectrumServer() : getElectrumServer()); } public boolean requiresInternalTor() { if(isUseProxy()) { return false; } return requiresTor(); } public boolean requiresTor() { if(!hasServerAddress()) { return false; } Protocol protocol = Protocol.getProtocol(getServerAddress()); if(protocol == null) { return false; } return protocol.isOnionAddress(protocol.getServerHostAndPort(getServerAddress())); } public String getPublicElectrumServer() { return publicElectrumServer; } public void setPublicElectrumServer(String publicElectrumServer) { this.publicElectrumServer = publicElectrumServer; flush(); } public void changePublicServer() { List<String> otherServers = Arrays.stream(PublicElectrumServer.values()).map(PublicElectrumServer::getUrl).filter(url -> !url.equals(getPublicElectrumServer())).collect(Collectors.toList()); setPublicElectrumServer(otherServers.get(new Random().nextInt(otherServers.size()))); } public String getCoreServer() { return coreServer; } public void setCoreServer(String coreServer) { this.coreServer = coreServer; flush(); } public CoreAuthType getCoreAuthType() { return coreAuthType; } public void setCoreAuthType(CoreAuthType coreAuthType) { this.coreAuthType = coreAuthType; flush(); } public File getCoreDataDir() { return coreDataDir; } public void setCoreDataDir(File coreDataDir) { this.coreDataDir = coreDataDir; flush(); } public String getCoreAuth() { return coreAuth; } public void setCoreAuth(String coreAuth) { this.coreAuth = coreAuth; flush(); } public Boolean getCoreMultiWallet() { return coreMultiWallet; } public void setCoreMultiWallet(Boolean coreMultiWallet) { this.coreMultiWallet = coreMultiWallet; flush(); } public String getCoreWallet() { return coreWallet; } public void setCoreWallet(String coreWallet) { this.coreWallet = coreWallet; flush(); } public String getElectrumServer() { return electrumServer; } public void setElectrumServer(String electrumServer) { this.electrumServer = electrumServer; flush(); } public File getElectrumServerCert() { return electrumServerCert; } public void setElectrumServerCert(File electrumServerCert) { this.electrumServerCert = electrumServerCert; flush(); } public boolean isUseProxy() { return useProxy; } public void setUseProxy(boolean useProxy) { this.useProxy = useProxy; flush(); } public String getProxyServer() { return proxyServer; } public void setProxyServer(String proxyServer) { this.proxyServer = proxyServer; flush(); } private synchronized void flush() { Gson gson = getGson(); try { File configFile = getConfigFile(); if(!configFile.exists()) { Storage.createOwnerOnlyFile(configFile); } Writer writer = new FileWriter(configFile); gson.toJson(this, writer); writer.flush(); writer.close(); } catch (IOException e) { //Ignore } } private static class FileSerializer implements JsonSerializer<File> { @Override public JsonElement serialize(File src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.getAbsolutePath()); } } private static class FileDeserializer implements JsonDeserializer<File> { @Override public File deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new File(json.getAsJsonPrimitive().getAsString()); } } }
Examination of UTAUT model in an ERP postadoption environment: An empirical study This research presents an empirical study on UTAUT model in an ERP post-adoption environment, investigating the moderating effect of mid-level management support on the relationship between subjective norm, perceived behavior control and behavior intention. Using data gathered from ERP users in a large-scale enterprise, we showed that perceived usefulness, perceived ease of use, subjective norm, and perceived behavior control are critical cognitive beliefs influencing the behavior intention to use the ERP system. In addition, the hypothesis of moderating effect of mid-level management support has not been supported by strong empirical evidences. Theoretical implications and limitations are discussed.
/** * Trims a String to a specified length, if the String exceeds that length, * otherwise leaves it alone. If findWordBoundary is true, will work * backwards (or forwards, if searchBackForWordBoundary is false) from the * target length to a space character and truncate there (to avoid * truncating in the middle of a word). Puts the specified ellipsis text at * the end of the String if it is trimmed. */ public static String truncateEllipsis(String input, int targetLength, boolean findWordBoundary, boolean searchBackForWordBoundary, String ellipsis) { if (isEmpty(input)) { return ""; } String suffix = ellipsis == null ? "" : ellipsis; int length = targetLength; if (length > suffix.length()) { length = length - suffix.length(); } if (input.length() > length) { if (findWordBoundary) { int space = searchBackForWordBoundary ? input.lastIndexOf(' ', length) : input.indexOf(' ', length); if (space >= 1) { length = space; } } return input.substring(0, length) + suffix; } else { return input; } }
Utilization of and Adherence to Oral Contraceptive Pills and Associated Disparities in the United States This study investigated sociological factors that may influence women’s utilization of and adherence to oral contraceptive pills. This was a retrospective cross-sectional study using the 2010–2012 Medical Expenditure Panel Survey. Female adults aged 18–50 years were included. Logistic regression was performed to discern women’s decisions to use oral contraceptive pills or not. Ordinary least squares and Poisson regressions were conducted to examine the number of oral contraceptive pills received, refill frequency, and annual out-of-pocket expenditure on oral contraceptive pills. Covariates were based on the Andersen model of health care utilization. Among the study sample (weighted n = 207,007,531), 14.8% were oral contraceptive pill users. Factors positively related to oral contraceptive pill use included non-Hispanic white ethnicity, younger age, not currently married, having private insurance, residing in the Midwest, higher education level, and higher annual family income. Being non-Hispanic white and having a higher education level were positively related to oral contraceptive pill adherence. Our findings therefore demonstrate disparities in oral contraceptive pill utilization and adherence, especially according to women’s race/ethnicity and educational level. This study serves as a baseline assessment for the impact of the Affordable Care Act on oral contraceptive pill utilization and adherence for future studies.
<gh_stars>0 import { render } from '@testing-library/react'; import { StoreProvider } from 'easy-peasy'; import 'mutationobserver-shim'; import React from 'react'; import { BrowserRouter } from 'react-router-dom'; import { ToastContainer } from 'react-toastify'; import App from './App'; import { store } from './store'; import { FullScreenSuspense } from './util/suspense'; it('renders welcome message', async () => { const { findByText } = render( <StoreProvider store={store}> <FullScreenSuspense> <BrowserRouter> <App /> </BrowserRouter> </FullScreenSuspense> <ToastContainer /> </StoreProvider> ); const text = await findByText('Grab a slick name for your new app'); expect(text).toBeTruthy(); });
/*============================================================ Problem: Generate Parentheses ============================================================== Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" ============================================================*/ class Solution { vector<string> res; string tmp; private: void generate(int leftCount, int rightCount) { if (leftCount==0 && rightCount==0) res.push_back(tmp); if (leftCount>0) { // can generate left parentheses tmp += '('; generate(leftCount-1, rightCount); tmp = tmp.substr(0, tmp.size()-1); } if (rightCount>0 && leftCount<rightCount) { // can generate right parentheses tmp += ')'; generate(leftCount, rightCount-1); tmp = tmp.substr(0, tmp.size()-1); } } public: vector<string> generateParenthesis(int n) { res.clear(); generate(n, n); return res; } };
<reponame>ooliver1/upticheck import durationToHuman from "./duration"; export default async function handleUptime( request: Request, env: Env, path: string ): Promise<Response> { const uptime = await env.UPTIME.get(path); if (uptime === null) { return new Response('Service not found <img src="https://http.cat/404" />', { status: 404, headers: { "Content-Type": "text/html; charset=utf-8" }, }); } if (uptime === "down") { return new Response("Service is down", { status: 503 }); } else if (uptime === "waiting") { // dont want this to be 200 but i also dont want to break uptime counts return new Response("Waiting for service to reconnect", { status: 200 }); } const date = new Date(uptime); const diff = (new Date().getTime() - date.getTime()) / 1000; return new Response(`Service is up for ${durationToHuman(diff)}`, { status: 200 }); }
//--------------------------------------------------------------------------- //! //! This function does not provide fall back mechanics. This is intentional //! It should be used to compare two file locations exsactly bool IOManager::validate_file(const char* path, const char* embeded_path) const { if (embeded_path) { std::string embeded_hash = get_expected_sha1(embeded_path); std::string file_hash = calculate_sha1(path); return embeded_hash == file_hash; } else { if (does_embedded_file_exist(path)) { std::string embeded_hash = get_expected_sha1(path); std::string file_hash = calculate_sha1(path); return embeded_hash == file_hash; } return false; } }
/******************************************************************************* * Copyright (c) 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Zend Technologies *******************************************************************************/ package org.eclipse.php.internal.ui.preferences; import org.eclipse.osgi.util.NLS; public final class PreferencesMessages extends NLS { private static final String BUNDLE_NAME = "org.eclipse.php.internal.ui.preferences.PreferencesMessages"; //$NON-NLS-1$ private PreferencesMessages() { // Do not instantiate } public static String BuildPathDialog_error_title; public static String BuildPathDialog_error_message; public static String BuildPathsPropertyPage_error_message; public static String BuildPathsPropertyPage_error_title; public static String BuildPathsPropertyPage_job_title; public static String BuildPathsPropertyPage_no_java_project_message; public static String BuildPathsPropertyPage_closed_project_message; public static String BuildPathsPropertyPage_unsavedchanges_title; public static String BuildPathsPropertyPage_unsavedchanges_message; public static String BuildPathsPropertyPage_unsavedchanges_button_save; public static String BuildPathsPropertyPage_unsavedchanges_button_discard; public static String BuildPathsPropertyPage_unsavedchanges_button_ignore; public static String ClasspathVariablesPreferencePage_title; public static String ClasspathVariablesPreferencePage_description; public static String ClasspathVariablesPreferencePage_savechanges_title; public static String ClasspathVariablesPreferencePage_savechanges_message; public static String CleanUpPreferencePage_Description; public static String CleanUpPreferencePage_Title; public static String CodeAssistAdvancedConfigurationBlock_default_table_category_column_title; public static String CodeAssistAdvancedConfigurationBlock_default_table_description; public static String CodeAssistAdvancedConfigurationBlock_default_table_keybinding_column_title; public static String CodeAssistAdvancedConfigurationBlock_key_binding_hint; public static String CodeAssistAdvancedConfigurationBlock_page_description; public static String CodeAssistAdvancedConfigurationBlock_separate_table_category_column_title; public static String CodeAssistAdvancedConfigurationBlock_separate_table_description; public static String CodeAssistAdvancedConfigurationBlock_no_shortcut; public static String CodeAssistAdvancedConfigurationBlock_Up; public static String CodeAssistAdvancedConfigurationBlock_Down; public static String CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout; public static String CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout_ms; public static String CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout_emptyInput; public static String CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout_invalidInput; public static String CodeAssistAdvancedConfigurationBlock_parameterNameFromAttachedJavadoc_timeout_invalidRange; public static String CodeStylePreferencePage_0; public static String ImportOrganizeConfigurationBlock_emptylines_between_groups_label; public static String ImportOrganizeConfigurationBlock_error_invalidnumberofemptylines; public static String ImportOrganizePreferencePage_description; public static String ImportOrganizePreferencePage_title; public static String ImportOrganizeConfigurationBlock_order_label; public static String ImportOrganizeConfigurationBlock_other_static; public static String ImportOrganizeConfigurationBlock_other_static_label; public static String ImportOrganizeConfigurationBlock_other_normal; public static String ImportOrganizeConfigurationBlock_other_normal_label; public static String ImportOrganizeConfigurationBlock_order_add_button; public static String ImportOrganizeConfigurationBlock_order_edit_button; public static String ImportOrganizeConfigurationBlock_order_up_button; public static String ImportOrganizeConfigurationBlock_order_down_button; public static String ImportOrganizeConfigurationBlock_order_remove_button; public static String ImportOrganizeConfigurationBlock_order_add_static_button; public static String ImportOrganizeConfigurationBlock_order_load_button; public static String ImportOrganizeConfigurationBlock_order_save_button; public static String ImportOrganizeConfigurationBlock_other_description; public static String ImportOrganizeConfigurationBlock_ignoreLowerCase_label; public static String ImportOrganizeConfigurationBlock_threshold_label; public static String ImportOrganizeConfigurationBlock_error_invalidthreshold; public static String ImportOrganizeConfigurationBlock_loadDialog_title; public static String ImportOrganizeConfigurationBlock_loadDialog_error_title; public static String ImportOrganizeConfigurationBlock_loadDialog_error_message; public static String ImportOrganizeConfigurationBlock_saveDialog_title; public static String ImportOrganizeConfigurationBlock_saveDialog_error_title; public static String ImportOrganizeConfigurationBlock_staticthreshold_label; public static String ImportOrganizeConfigurationBlock_saveDialog_error_message; public static String ImportOrganizeInputDialog_title; public static String ImportOrganizeInputDialog_browse_packages_button; public static String ImportOrganizeInputDialog_browse_types_label; public static String ImportOrganizeInputDialog_title_static; public static String ImportOrganizeInputDialog_ChoosePackageDialog_title; public static String ImportOrganizeInputDialog_ChoosePackageDialog_description; public static String ImportOrganizeInputDialog_ChoosePackageDialog_empty; public static String ImportOrganizeInputDialog_ChooseTypeDialog_title; public static String ImportOrganizeInputDialog_ChooseTypeDialog_description; public static String ImportOrganizeInputDialog_ChooseTypeDialog_error_message; public static String ImportOrganizeInputDialog_error_enterName; public static String ImportOrganizeInputDialog_error_invalidName; public static String ImportOrganizeInputDialog_error_entryExists; public static String ImportOrganizeInputDialog_name_group_label; public static String ImportOrganizeInputDialog_name_group_static_label; public static String JavaBasePreferencePage_description; public static String JavaBasePreferencePage_doubleclick_action; public static String JavaBasePreferencePage_doubleclick_gointo; public static String JavaBasePreferencePage_doubleclick_expand; public static String JavaBasePreferencePage_refactoring_lightweight; public static String JavaBasePreferencePage_refactoring_title; public static String JavaBasePreferencePage_refactoring_auto_save; public static String JavaBasePreferencePage_search; public static String JavaBasePreferencePage_search_small_menu; public static String JavaBuildConfigurationBlock_build_recreate_modified; public static String JavadocConfigurationBlock_error_archive_not_found_in_workspace; public static String JavadocConfigurationBlock_external_radio; public static String JavadocConfigurationBlock_workspace_archive_selection_dialog_description; public static String JavadocConfigurationBlock_workspace_archive_selection_dialog_title; public static String JavadocConfigurationBlock_workspace_radio; public static String JavadocConfigurationPropertyPage_invalid_container; public static String JavadocConfigurationPropertyPage_not_supported; public static String JavadocConfigurationPropertyPage_read_only; public static String JavaEditorPropertyPage_SaveActionLink_Text; public static String NativeLibrariesPropertyPage_invalid_container; public static String NativeLibrariesPropertyPage_not_supported; public static String NativeLibrariesPropertyPage_read_only; public static String NewPHPProjectPreferencePage_title; public static String NewPHPProjectPreferencePage_description; public static String NewPHPProjectPreferencePage_sourcefolder_label; public static String NewPHPProjectPreferencePage_sourcefolder_project; public static String NewPHPProjectPreferencePage_sourcefolder_folder; public static String NewPHPProjectPreferencePage_folders_src; public static String NewPHPProjectPreferencePage_folders_public; public static String NewPHPProjectPreferencePage_folders_error_namesempty; public static String NewPHPProjectPreferencePage_folders_error_invalidsrcname; public static String NewPHPProjectPreferencePage_folders_error_invalidbinname; public static String NewPHPProjectPreferencePage_folders_error_invalidcp; public static String JavaEditorPreferencePage_showQuickFixables; public static String JavaEditorPreferencePage_analyseAnnotationsWhileTyping; public static String JavaEditorPreferencePage_multiLineComment; public static String JavaEditorPreferencePage_singleLineComment; public static String JavaEditorPreferencePage_returnKeyword; public static String JavaEditorPreferencePage_keywords; public static String JavaEditorPreferencePage_strings; public static String JavaEditorPreferencePage_others; public static String JavaEditorPreferencePage_operators; public static String JavaEditorPreferencePage_brackets; public static String JavaEditorPreferencePage_javaCommentTaskTags; public static String JavaEditorPreferencePage_javaDocKeywords; public static String JavaEditorPreferencePage_javaDocHtmlTags; public static String JavaEditorPreferencePage_javaDocLinks; public static String JavaEditorPreferencePage_javaDocOthers; public static String JavaEditorPreferencePage_backgroundColor; public static String JavaEditorPreferencePage_systemDefault; public static String JavaEditorPreferencePage_custom; public static String JavaEditorPreferencePage_semanticHighlighting_option; public static String JavaEditorPreferencePage_foreground; public static String JavaEditorPreferencePage_color; public static String JavaEditorPreferencePage_bold; public static String JavaEditorPreferencePage_italic; public static String JavaEditorPreferencePage_strikethrough; public static String JavaEditorPreferencePage_underline; public static String JavaEditorPreferencePage_enable; public static String JavaEditorPreferencePage_preview; public static String JavaEditorPreferencePage_displayedTabWidth; public static String JavaEditorPreferencePage_insertSpaceForTabs; public static String JavaEditorPreferencePage_showOverviewRuler; public static String JavaEditorPreferencePage_highlightMatchingBrackets; public static String JavaEditorPreferencePage_highlightCurrentLine; public static String JavaEditorPreferencePage_showPrintMargin; public static String JavaEditorPreferencePage_printMarginColumn; public static String JavaEditorPreferencePage_insertSingleProposalsAutomatically; public static String JavaEditorPreferencePage_showOnlyProposalsVisibleInTheInvocationContext; public static String JavaEditorPreferencePage_presentProposalsInAlphabeticalOrder; public static String JavaEditorPreferencePage_coloring_element; public static String JavaEditorPreferencePage_enableAutoActivation; public static String JavaEditorPreferencePage_automaticallyAddImportInsteadOfQualifiedName; public static String JavaEditorPreferencePage_suggestStaticImports; public static String JavaEditorPreferencePage_completionInserts; public static String JavaEditorPreferencePage_completionOverwrites; public static String JavaEditorPreferencePage_completionToggleHint; public static String JavaEditorPreferencePage_fillArgumentsOnMethodCompletion; public static String JavaEditorPreferencePage_fillParameterNamesOnMethodCompletion; public static String JavaEditorPreferencePage_fillBestGuessedArgumentsOnMethodCompletion; public static String JavaEditorPreferencePage_autoActivationDelay; public static String JavaEditorPreferencePage_autoActivationTriggersForJava; public static String JavaEditorPreferencePage_autoActivationTriggersForJavaDoc; public static String JavaEditorPreferencePage_completePrefixes; public static String JavaEditorPreferencePage_backgroundForMethodParameters; public static String JavaEditorPreferencePage_foregroundForMethodParameters; public static String JavaEditorPreferencePage_backgroundForCompletionReplacement; public static String JavaEditorPreferencePage_foregroundForCompletionReplacement; public static String JavaEditorPreferencePage_sourceHoverBackgroundColor; public static String JavaEditorPreferencePage_general; public static String JavaEditorPreferencePage_colors; public static String JavaEditorPreferencePage_empty_input; public static String JavaEditorPreferencePage_invalid_input; public static String JavaEditorPreferencePage_showLineNumbers; public static String JavaEditorPreferencePage_lineNumberForegroundColor; public static String JavaEditorPreferencePage_matchingBracketsHighlightColor2; public static String JavaEditorPreferencePage_currentLineHighlighColor; public static String JavaEditorPreferencePage_printMarginColor2; public static String JavaEditorPreferencePage_appearanceOptions; public static String JavaEditorPreferencePage_typing_tabTitle; public static String JavaEditorPreferencePage_typing_description; public static String JavaEditorPreferencePage_closeStrings; public static String JavaEditorPreferencePage_closeBrackets; public static String JavaEditorPreferencePage_closeBraces; public static String JavaEditorPreferencePage_closeJavaDocs; public static String JavaEditorPreferencePage_wrapStrings; public static String JavaEditorPreferencePage_escapeStrings; public static String JavaEditorPreferencePage_addJavaDocTags; public static String JavaEditorPreferencePage_smartPaste; public static String JavaEditorPreferencePage_link; public static String JavaEditorPreferencePage_link_tooltip; public static String JavaEditorPreferencePage_importsOnPaste; public static String JavaEditorPreferencePage_subWordNavigation; public static String JavaEditorPreferencePage_typing_smartSemicolon; public static String JavaEditorPreferencePage_typing_smartOpeningBrace; public static String JavaEditorPreferencePage_typing_smartTab; public static String JavaEditorPreferencePage_hoverTab_title; public static String JavaEditorPreferencePage_showEditorBreadcrumb; public static String JavaEditorColoringConfigurationBlock_link; public static String JavaBasePreferencePage_openTypeHierarchy; public static String JavaBasePreferencePage_inView; public static String JavaBasePreferencePage_inPerspective; public static String JavaEditorPreferencePage_quickassist_lightbulb; public static String JavaEditorPreferencePage_showJavaElementOnly; public static String JavaEditorPreferencePage_accessibility_disableCustomCarets; public static String JavaEditorPreferencePage_accessibility_wideCaret; public static String JavaEditorHoverConfigurationBlock_annotationRollover; public static String JavaEditorHoverConfigurationBlock_hoverPreferences; public static String JavaEditorHoverConfigurationBlock_enabled; public static String JavaEditorHoverConfigurationBlock_keyModifier; public static String JavaEditorHoverConfigurationBlock_description; public static String JavaEditorHoverConfigurationBlock_modifierIsNotValid; public static String JavaEditorHoverConfigurationBlock_modifierIsNotValidForHover; public static String JavaEditorHoverConfigurationBlock_duplicateModifier; public static String JavaEditorHoverConfigurationBlock_nameColumnTitle; public static String JavaEditorHoverConfigurationBlock_modifierColumnTitle; public static String JavaEditorHoverConfigurationBlock_delimiter; public static String JavaEditorHoverConfigurationBlock_insertDelimiterAndModifierAndDelimiter; public static String JavaEditorHoverConfigurationBlock_insertModifierAndDelimiter; public static String JavaEditorHoverConfigurationBlock_insertDelimiterAndModifier; public static String MarkOccurrencesConfigurationBlock_title; public static String MarkOccurrencesConfigurationBlock_link; public static String MarkOccurrencesConfigurationBlock_link_tooltip; public static String MarkOccurrencesConfigurationBlock_markOccurrences; public static String MarkOccurrencesConfigurationBlock_markTypeOccurrences; public static String MarkOccurrencesConfigurationBlock_markMethodOccurrences; public static String MarkOccurrencesConfigurationBlock_markConstantOccurrences; public static String MarkOccurrencesConfigurationBlock_markFieldOccurrences; public static String MarkOccurrencesConfigurationBlock_markLocalVariableOccurrences; public static String MarkOccurrencesConfigurationBlock_markExceptionOccurrences; public static String MarkOccurrencesConfigurationBlock_markMethodExitPoints; public static String MarkOccurrencesConfigurationBlock_markImplementors; public static String MarkOccurrencesConfigurationBlock_markBreakContinueTargets; public static String MarkOccurrencesConfigurationBlock_stickyOccurrences; public static String JavaElementInfoPage_binary; public static String JavaElementInfoPage_classpath_entry_kind; public static String JavaElementInfoPage_library; public static String JavaElementInfoPage_nameLabel; public static String JavaElementInfoPage_not_present; public static String JavaElementInfoPage_package; public static String JavaElementInfoPage_package_contents; public static String JavaElementInfoPage_project; public static String JavaElementInfoPage_resource_path; public static String JavaElementInfoPage_source; public static String JavaElementInfoPage_variable; public static String JavaElementInfoPage_variable_path; public static String JavaElementInfoPage_location; public static String JavadocConfigurationPropertyPage_IsPackageFragmentRoot_description; public static String JavadocConfigurationPropertyPage_IsIncorrectElement_description; public static String JavadocConfigurationPropertyPage_IsJavaProject_description; public static String JavadocConfigurationBlock_browse_folder_button; public static String JavadocConfigurationBlock_error_notafolder; public static String JavadocConfigurationBlock_javadocFolderDialog_label; public static String JavadocConfigurationBlock_javadocFolderDialog_message; public static String JavadocConfigurationBlock_MalformedURL_error; public static String JavadocConfigurationBlock_validate_button; public static String JavadocConfigurationBlock_InvalidLocation_message; public static String JavadocConfigurationBlock_ValidLocation_message; public static String JavadocConfigurationBlock_UnableToValidateLocation_message; public static String JavadocConfigurationBlock_MessageDialog_title; public static String JavadocConfigurationBlock_location_type_path_label; public static String JavadocConfigurationBlock_location_type_jar_label; public static String JavadocConfigurationBlock_location_path_label; public static String JavadocConfigurationBlock_location_jar_label; public static String JavadocConfigurationBlock_jar_path_label; public static String JavadocConfigurationBlock_zipImportSource_title; public static String JavadocConfigurationBlock_location_in_jarorzip_message; public static String JavadocConfigurationBlock_browse_jarorzip_path_title; public static String JavadocConfigurationBlock_error_notafile; public static String JavadocConfigurationBlock_error_invalidarchivepath; public static String JavadocConfigurationBlock_error_archivepathnotabsolute; public static String JavadocConfigurationBlock_error_dialog_title; public static String JavadocConfigurationBlock_browse_archive_button; public static String JavadocConfigurationBlock_browse_archive_path_button; public static String ProblemSeveritiesConfigurationBlock_ignore_documented_unused_exceptions; public static String ProblemSeveritiesConfigurationBlock_ignore_documented_unused_parameters; public static String ProblemSeveritiesConfigurationBlock_pb_redundant_null_check; public static String ProblemSeveritiesConfigurationBlock_pb_redundant_super_interface_label; public static String ProblemSeveritiesConfigurationBlock_treat_optional_as_fatal; public static String SourceAttachmentPropertyPage_error_title; public static String SourceAttachmentPropertyPage_error_message; public static String SourceAttachmentPropertyPage_invalid_container; public static String SourceAttachmentPropertyPage_noarchive_message; public static String SourceAttachmentPropertyPage_containerentry_message; public static String NativeLibrariesPropertyPage_invalidElementSelection_desription; public static String NativeLibrariesPropertyPage_errorAttaching_title; public static String NativeLibrariesPropertyPage_errorAttaching_message; public static String AppearancePreferencePage_description; public static String AppearancePreferencePage_methodreturntype_label; public static String AppearancePreferencePage_showCategory_label; public static String AppearancePreferencePage_methodtypeparams_label; public static String AppearancePreferencePage_pkgNamePatternEnable_label; public static String AppearancePreferencePage_pkgNamePattern_label; public static String AppearancePreferencePage_showMembersInPackagesView; public static String AppearancePreferencePage_stackViewsVerticallyInTheJavaBrowsingPerspective; public static String AppearancePreferencePage_note; public static String AppearancePreferencePage_preferenceOnlyEffectiveForNewPerspectives; public static String AppearancePreferencePage_packageNameCompressionPattern_error_isEmpty; public static String AppearancePreferencePage_foldEmptyPackages; public static String CodeFormatterPreferencePage_title; public static String CodeFormatterPreferencePage_description; public static String SourceAttachmentPropertyPage_not_supported; public static String SourceAttachmentPropertyPage_read_only; public static String TodoTaskPreferencePage_title; public static String TodoTaskPreferencePage_description; public static String TodoTaskConfigurationBlock_markers_tasks_high_priority; public static String TodoTaskConfigurationBlock_markers_tasks_normal_priority; public static String TodoTaskConfigurationBlock_markers_tasks_low_priority; public static String TodoTaskConfigurationBlock_markers_tasks_add_button; public static String TodoTaskConfigurationBlock_markers_tasks_remove_button; public static String TodoTaskConfigurationBlock_markers_tasks_edit_button; public static String TodoTaskConfigurationBlock_markers_tasks_name_column; public static String TodoTaskConfigurationBlock_markers_tasks_priority_column; public static String TodoTaskConfigurationBlock_markers_tasks_setdefault_button; public static String TodoTaskConfigurationBlock_casesensitive_label; public static String TodoTaskConfigurationBlock_needsbuild_title; public static String TodoTaskConfigurationBlock_tasks_default; public static String TodoTaskConfigurationBlock_needsfullbuild_message; public static String TodoTaskConfigurationBlock_needsprojectbuild_message; public static String TodoTaskInputDialog_new_title; public static String TodoTaskInputDialog_edit_title; public static String TodoTaskInputDialog_name_label; public static String TodoTaskInputDialog_priority_label; public static String TodoTaskInputDialog_priority_high; public static String TodoTaskInputDialog_priority_normal; public static String TodoTaskInputDialog_priority_low; public static String TodoTaskInputDialog_error_enterName; public static String TodoTaskInputDialog_error_comma; public static String TodoTaskInputDialog_error_entryExists; public static String TodoTaskInputDialog_error_noSpace; public static String PropertyAndPreferencePage_useworkspacesettings_change; public static String PropertyAndPreferencePage_showprojectspecificsettings_label; public static String PropertyAndPreferencePage_useprojectsettings_label; public static String JavaBuildPreferencePage_title; public static String JavaBuildPreferencePage_description; public static String JavaBuildConfigurationBlock_section_general; public static String JavaBuildConfigurationBlock_section_output_folder; public static String JavaBuildConfigurationBlock_section_access_rules; public static String JavaBuildConfigurationBlock_section_build_path_problems; public static String JavaBuildConfigurationBlock_error; public static String JavaBuildConfigurationBlock_warning; public static String JavaBuildConfigurationBlock_ignore; public static String JavaBuildConfigurationBlock_needsbuild_title; public static String JavaBuildConfigurationBlock_needsfullbuild_message; public static String JavaBuildConfigurationBlock_needsprojectbuild_message; public static String JavaBuildConfigurationBlock_resource_filter_description; public static String JavaBuildConfigurationBlock_resource_filter_label; public static String JavaBuildConfigurationBlock_build_invalid_classpath_label; public static String JavaBuildConfigurationBlock_build_clean_outputfolder_label; public static String JavaBuildConfigurationBlock_enable_exclusion_patterns_label; public static String JavaBuildConfigurationBlock_enable_multiple_outputlocations_label; public static String JavaBuildConfigurationBlock_pb_incomplete_build_path_label; public static String ProblemSeveritiesConfigurationBlock_pb_discourraged_reference_label; public static String JavaBuildConfigurationBlock_pb_build_path_cycles_label; public static String JavaBuildConfigurationBlock_pb_duplicate_resources_label; public static String ProblemSeveritiesConfigurationBlock_pb_forbidden_reference_label; public static String JavaBuildConfigurationBlock_pb_max_per_unit_label; public static String JavaBuildConfigurationBlock_pb_check_prereq_binary_level_label; public static String JavaBuildConfigurationBlock_empty_input; public static String JavaBuildConfigurationBlock_invalid_input; public static String JavaBuildConfigurationBlock_filter_invalidsegment_error; public static String ProblemSeveritiesPreferencePage_title; public static String ProblemSeveritiesConfigurationBlock_error; public static String ProblemSeveritiesConfigurationBlock_warning; public static String ProblemSeveritiesConfigurationBlock_ignore; public static String ProblemSeveritiesConfigurationBlock_section_potential_programming_problems; public static String ProblemSeveritiesConfigurationBlock_section_unnecessary_code; public static String ProblemSeveritiesConfigurationBlock_section_nls; public static String ProblemSeveritiesConfigurationBlock_section_code_style; public static String ProblemSeveritiesConfigurationBlock_section_deprecations; public static String ProblemSeveritiesConfigurationBlock_section_name_shadowing; public static String ProblemSeveritiesConfigurationBlock_section_annotations; public static String ProblemSeveritiesConfigurationBlock_needsbuild_title; public static String ProblemSeveritiesConfigurationBlock_needsfullbuild_message; public static String ProblemSeveritiesConfigurationBlock_needsprojectbuild_message; public static String ProblemSeveritiesConfigurationBlock_common_description; public static String ProblemSeveritiesConfigurationBlock_pb_unsafe_type_op_label; public static String ProblemSeveritiesConfigurationBlock_pb_raw_type_reference; public static String ProblemSeveritiesConfigurationBlock_pb_final_param_bound_label; public static String ProblemSeveritiesConfigurationBlock_pb_inexact_vararg_label; public static String ProblemSeveritiesConfigurationBlock_pb_accidential_assignement_label; public static String ProblemSeveritiesConfigurationBlock_pb_local_variable_hiding_label; public static String ProblemSeveritiesConfigurationBlock_pb_field_hiding_label; public static String ProblemSeveritiesConfigurationBlock_pb_special_param_hiding_label; public static String ProblemSeveritiesConfigurationBlock_pb_unqualified_field_access_label; public static String ProblemSeveritiesConfigurationBlock_pb_finally_block_not_completing_label; public static String ProblemSeveritiesConfigurationBlock_pb_undocumented_empty_block_label; public static String ProblemSeveritiesConfigurationBlock_pb_unused_throwing_exception_label; public static String ProblemSeveritiesConfigurationBlock_pb_unused_throwing_exception_when_overriding_label; public static String ProblemSeveritiesConfigurationBlock_pb_unused_throwing_exception_ignore_unchecked_label; public static String ProblemSeveritiesConfigurationBlock_pb_missing_serial_version_label; public static String ProblemSeveritiesConfigurationBlock_pb_overriding_pkg_dflt_label; public static String ProblemSeveritiesConfigurationBlock_pb_method_naming_label; public static String ProblemSeveritiesConfigurationBlock_pb_no_effect_assignment_label; public static String ProblemSeveritiesConfigurationBlock_pb_incompatible_interface_method_label; public static String ProblemSeveritiesConfigurationBlock_pb_indirect_access_to_static_label; public static String ProblemSeveritiesConfigurationBlock_pb_hidden_catchblock_label; public static String ProblemSeveritiesConfigurationBlock_pb_static_access_receiver_label; public static String ProblemSeveritiesConfigurationBlock_pb_unused_imports_label; public static String ProblemSeveritiesConfigurationBlock_pb_unused_local_label; public static String ProblemSeveritiesConfigurationBlock_pb_unused_parameter_label; public static String ProblemSeveritiesConfigurationBlock_pb_signal_param_in_overriding_label; public static String ProblemSeveritiesConfigurationBlock_pb_unused_private_label; public static String ProblemSeveritiesConfigurationBlock_pb_non_externalized_strings_label; public static String ProblemSeveritiesConfigurationBlock_pb_deprecation_label; public static String ProblemSeveritiesConfigurationBlock_pb_deprecation_in_deprecation_label; public static String ProblemSeveritiesConfigurationBlock_pb_deprecation_when_overriding_label; public static String ProblemSeveritiesConfigurationBlock_pb_empty_statement_label; public static String ProblemSeveritiesConfigurationBlock_pb_unnecessary_type_check_label; public static String ProblemSeveritiesConfigurationBlock_pb_incomplete_enum_switch_label; public static String ProblemSeveritiesConfigurationBlock_pb_unnecessary_else_label; public static String ProblemSeveritiesConfigurationBlock_pb_synth_access_emul_label; public static String ProblemSeveritiesConfigurationBlock_pb_autoboxing_problem_label; public static String ProblemSeveritiesConfigurationBlock_pb_char_array_in_concat_label; public static String ProblemSeveritiesConfigurationBlock_pb_missing_override_annotation_label; public static String ProblemSeveritiesConfigurationBlock_pb_missing_deprecated_annotation_label; public static String ProblemSeveritiesConfigurationBlock_pb_annotation_super_interface_label; public static String ProblemSeveritiesConfigurationBlock_pb_type_parameter_hiding_label; public static String ProblemSeveritiesConfigurationBlock_pb_unused_label_label; public static String JavadocProblemsPreferencePage_title; public static String JavadocProblemsConfigurationBlock_allStandardTags; public static String JavadocProblemsConfigurationBlock_public; public static String JavadocProblemsConfigurationBlock_protected; public static String JavadocProblemsConfigurationBlock_default; public static String JavadocProblemsConfigurationBlock_private; public static String JavadocProblemsConfigurationBlock_error; public static String JavadocProblemsConfigurationBlock_warning; public static String JavadocProblemsConfigurationBlock_ignore; public static String JavadocProblemsConfigurationBlock_needsbuild_title; public static String JavadocProblemsConfigurationBlock_needsfullbuild_message; public static String JavadocProblemsConfigurationBlock_needsprojectbuild_message; public static String JavadocProblemsConfigurationBlock_javadoc_description; public static String JavadocProblemsConfigurationBlock_pb_javadoc_support_label; public static String JavadocProblemsConfigurationBlock_pb_invalid_javadoc_label; public static String JavadocProblemsConfigurationBlock_pb_invalid_javadoc_tags_label; public static String JavadocProblemsConfigurationBlock_pb_invalid_javadoc_tags_visibility_label; public static String JavadocProblemsConfigurationBlock_pb_invalid_javadoc_tags_not_visible_ref_label; public static String JavadocProblemsConfigurationBlock_pb_invalid_javadoc_tags_deprecated_label; public static String JavadocProblemsConfigurationBlock_pb_missing_javadoc_label; public static String JavadocProblemsConfigurationBlock_pb_missing_javadoc_tags_visibility_label; public static String JavadocProblemsConfigurationBlock_pb_missing_javadoc_tags_overriding_label; public static String JavadocProblemsConfigurationBlock_pb_missing_comments_label; public static String JavadocProblemsConfigurationBlock_pb_missing_comments_visibility_label; public static String JavadocProblemsConfigurationBlock_pb_missing_comments_overriding_label; public static String JavadocProblemsConfigurationBlock_pb_missing_tag_description; public static String JavadocProblemsConfigurationBlock_returnTag; public static String CompliancePreferencePage_title; public static String CompliancePreferencePage_description; public static String ComplianceConfigurationBlock_error; public static String ComplianceConfigurationBlock_warning; public static String ComplianceConfigurationBlock_ignore; public static String ComplianceConfigurationBlock_version11; public static String ComplianceConfigurationBlock_version12; public static String ComplianceConfigurationBlock_version13; public static String ComplianceConfigurationBlock_version14; public static String ComplianceConfigurationBlock_version15; public static String ComplianceConfigurationBlock_needsbuild_title; public static String ComplianceConfigurationBlock_needsfullbuild_message; public static String ComplianceConfigurationBlock_needsprojectbuild_message; public static String ComplianceConfigurationBlock_variable_attr_label; public static String ComplianceConfigurationBlock_line_number_attr_label; public static String ComplianceConfigurationBlock_source_file_attr_label; public static String ComplianceConfigurationBlock_codegen_unused_local_label; public static String ComplianceConfigurationBlock_cldc11_requires_source13_compliance_se14; public static String ComplianceConfigurationBlock_codegen_inline_jsr_bytecode_label; public static String ComplianceConfigurationBlock_compiler_compliance_label; public static String ComplianceConfigurationBlock_default_settings_label; public static String ComplianceConfigurationBlock_source_compatibility_label; public static String ComplianceConfigurationBlock_codegen_targetplatform_label; public static String ComplianceConfigurationBlock_pb_assert_as_identifier_label; public static String ComplianceConfigurationBlock_pb_enum_as_identifier_label; public static String ComplianceConfigurationBlock_compliance_group_label; public static String ComplianceConfigurationBlock_classfiles_group_label; public static String OptionsConfigurationBlock_job_title; public static String OptionsConfigurationBlock_buildall_taskname; public static String OptionsConfigurationBlock_buildproject_taskname; public static String CodeStylePreferencePage_title; public static String CodeTemplatesPreferencePage_title; public static String JavaCategoryPropertyPage_text; public static String NameConventionConfigurationBlock_field_label; public static String NameConventionConfigurationBlock_static_label; public static String NameConventionConfigurationBlock_arg_label; public static String NameConventionConfigurationBlock_local_label; public static String NameConventionConfigurationBlock_keywordthis_label; public static String NameConventionConfigurationBlock_isforbooleangetters_label; public static String NameConventionConfigurationBlock_dialog_prefix; public static String NameConventionConfigurationBlock_dialog_suffix; public static String NameConventionConfigurationBlock_exceptionname_label; public static String NameConventionConfigurationBlock_error_emptyprefix; public static String NameConventionConfigurationBlock_error_emptysuffix; public static String NameConventionConfigurationBlock_error_invalidprefix; public static String NameConventionConfigurationBlock_error_invalidsuffix; public static String NameConventionConfigurationBlock_list_label; public static String NameConventionConfigurationBlock_list_edit_button; public static String NameConventionConfigurationBlock_list_name_column; public static String NameConventionConfigurationBlock_list_prefix_column; public static String NameConventionConfigurationBlock_list_suffix_column; public static String NameConventionConfigurationBlock_field_dialog_title; public static String NameConventionConfigurationBlock_field_dialog_message; public static String NameConventionConfigurationBlock_static_dialog_title; public static String NameConventionConfigurationBlock_static_dialog_message; public static String NameConventionConfigurationBlock_arg_dialog_title; public static String NameConventionConfigurationBlock_arg_dialog_message; public static String NameConventionConfigurationBlock_local_dialog_title; public static String NameConventionConfigurationBlock_local_dialog_message; public static String MembersOrderPreferencePage_category_button_up; public static String MembersOrderPreferencePage_category_button_down; public static String MembersOrderPreferencePage_visibility_button_up; public static String MembersOrderPreferencePage_visibility_button_down; public static String MembersOrderPreferencePage_label_description; public static String MembersOrderPreferencePage_fields_label; public static String MembersOrderPreferencePage_constructors_label; public static String MembersOrderPreferencePage_methods_label; public static String MembersOrderPreferencePage_staticfields_label; public static String MembersOrderPreferencePage_staticmethods_label; public static String MembersOrderPreferencePage_initialisers_label; public static String MembersOrderPreferencePage_staticinitialisers_label; public static String MembersOrderPreferencePage_types_label; public static String MembersOrderPreferencePage_public_label; public static String MembersOrderPreferencePage_private_label; public static String MembersOrderPreferencePage_protected_label; public static String MembersOrderPreferencePage_default_label; public static String MembersOrderPreferencePage_usevisibilitysort_label; public static String CodeTemplateBlock_link_tooltip; public static String CodeTemplateBlock_templates_comment_node; public static String CodeTemplateBlock_templates_code_node; public static String CodeTemplateBlock_catchblock_label; public static String CodeTemplateBlock_methodstub_label; public static String CodeTemplateBlock_constructorstub_label; public static String CodeTemplateBlock_newtype_label; public static String CodeTemplateBlock_classbody_label; public static String CodeTemplateBlock_interfacebody_label; public static String CodeTemplateBlock_enumbody_label; public static String CodeTemplateBlock_annotationbody_label; public static String CodeTemplateBlock_typecomment_label; public static String CodeTemplateBlock_fieldcomment_label; public static String CodeTemplateBlock_filecomment_label; public static String CodeTemplateBlock_methodcomment_label; public static String CodeTemplateBlock_overridecomment_label; public static String CodeTemplateBlock_delegatecomment_label; public static String CodeTemplateBlock_constructorcomment_label; public static String CodeTemplateBlock_gettercomment_label; public static String CodeTemplateBlock_settercomment_label; public static String CodeTemplateBlock_getterstub_label; public static String CodeTemplateBlock_setterstub_label; public static String CodeTemplateBlock_templates_edit_button; public static String CodeTemplateBlock_templates_import_button; public static String CodeTemplateBlock_templates_export_button; public static String CodeTemplateBlock_templates_exportall_button; public static String CodeTemplateBlock_createcomment_label; public static String CodeTemplateBlock_templates_label; public static String CodeTemplateBlock_preview; public static String CodeTemplateBlock_import_title; public static String CodeTemplateBlock_import_extension; public static String CodeTemplateBlock_export_title; public static String CodeTemplateBlock_export_filename; public static String CodeTemplateBlock_export_extension; public static String CodeTemplateBlock_export_exists_title; public static String CodeTemplateBlock_export_exists_message; public static String CodeTemplateBlock_error_read_title; public static String CodeTemplateBlock_error_read_message; public static String CodeTemplateBlock_error_parse_message; public static String CodeTemplateBlock_error_write_title; public static String CodeTemplateBlock_error_write_message; public static String CodeTemplateBlock_export_error_title; public static String CodeTemplateBlock_export_error_hidden; public static String CodeTemplateBlock_export_error_canNotWrite; public static String TypeFilterPreferencePage_description; public static String TypeFilterPreferencePage_list_label; public static String TypeFilterPreferencePage_add_button; public static String TypeFilterPreferencePage_addpackage_button; public static String TypeFilterPreferencePage_edit_button; public static String TypeFilterPreferencePage_remove_button; public static String TypeFilterPreferencePage_selectall_button; public static String TypeFilterPreferencePage_deselectall_button; public static String TypeFilterPreferencePage_choosepackage_label; public static String TypeFilterPreferencePage_choosepackage_description; public static String TypeFilterInputDialog_title; public static String TypeFilterInputDialog_message; public static String TypeFilterInputDialog_browse_button; public static String TypeFilterInputDialog_error_enterName; public static String TypeFilterInputDialog_error_invalidName; public static String TypeFilterInputDialog_error_entryExists; public static String TypeFilterInputDialog_choosepackage_label; public static String TypeFilterInputDialog_choosepackage_description; public static String JavaEditorPreferencePage_selectionBackgroundColor; public static String JavaEditorPreferencePage_selectionForegroundColor; public static String SpellingPreferencePage_empty_threshold; public static String SpellingPreferencePage_invalid_threshold; public static String SpellingPreferencePage_ignore_digits_label; public static String SpellingPreferencePage_ignore_mixed_label; public static String SpellingPreferencePage_ignore_sentence_label; public static String SpellingPreferencePage_ignore_upper_label; public static String SpellingPreferencePage_ignore_url_label; public static String SpellingPreferencePage_ignore_non_letters_label; public static String SpellingPreferencePage_ignore_single_letters_label; public static String SpellingPreferencePage_ignore_java_strings_label; public static String SpellingPreferencePage_ignore_ampersand_in_properties_label; public static String SpellingPreferencePage_proposals_threshold; public static String SpellingPreferencePage_problems_threshold; public static String SpellingPreferencePage_dictionary_label; public static String SpellingPreferencePage_encoding_label; public static String SpellingPreferencePage_workspace_dictionary_label; public static String SpellingPreferencePage_browse_label; public static String SpellingPreferencePage_dictionary_error; public static String SpellingPreferencePage_dictionary_none; public static String SpellingPreferencePage_locale_error; public static String SpellingPreferencePage_filedialog_title; public static String SpellingPreferencePage_filter_dictionary_extension; public static String SpellingPreferencePage_filter_all_extension; public static String SpellingPreferencePage_filter_dictionary_label; public static String SpellingPreferencePage_filter_all_label; public static String SpellingPreferencePage_enable_contentassist_label; public static String SpellingPreferencePage_group_user; public static String SpellingPreferencePage_group_dictionary; public static String SpellingPreferencePage_group_dictionaries; public static String SpellingPreferencePage_group_advanced; public static String SpellingPreferencePage_user_dictionary_description; public static String SpellingPreferencePage_variables; public static String BuildPathPreferencePage_title; public static String BuildPathPreferencePage_description; public static String UserLibraryPreferencePage_title; public static String UserLibraryPreferencePage_description; public static String UserLibraryPreferencePage_libraries_label; public static String UserLibraryPreferencePage_libraries_new_button; public static String UserLibraryPreferencePage_libraries_edit_button; public static String UserLibraryPreferencePage_libraries_addjar_button; public static String UserLibraryPreferencePage_libraries_remove_button; public static String UserLibraryPreferencePage_libraries_load_button; public static String UserLibraryPreferencePage_libraries_save_button; public static String UserLibraryPreferencePage_operation; public static String UserLibraryPreferencePage_operation_error; public static String UserLibraryPreferencePage_config_error_title; public static String UserLibraryPreferencePage_config_error_message; public static String UserLibraryPreferencePage_browsejar_new_title; public static String UserLibraryPreferencePage_browsejar_edit_title; public static String UserLibraryPreferencePage_LibraryNameDialog_new_title; public static String UserLibraryPreferencePage_LibraryNameDialog_edit_title; public static String UserLibraryPreferencePage_LibraryNameDialog_name_label; public static String UserLibraryPreferencePage_LibraryNameDialog_issystem_label; public static String UserLibraryPreferencePage_LibraryNameDialog_name_error_entername; public static String UserLibraryPreferencePage_LibraryNameDialog_name_error_exists; public static String UserLibraryPreferencePage_LoadSaveDialog_save_title; public static String UserLibraryPreferencePage_LoadSaveDialog_save_ok_title; public static String UserLibraryPreferencePage_LoadSaveDialog_load_title; public static String UserLibraryPreferencePage_LoadSaveDialog_location_label; public static String UserLibraryPreferencePage_LoadSaveDialog_location_button; public static String UserLibraryPreferencePage_LoadSaveDialog_list_selectall_button; public static String UserLibraryPreferencePage_LoadSaveDialog_load_replace_message; public static String UserLibraryPreferencePage_LoadSaveDialog_load_replace_multiple_message; public static String UserLibraryPreferencePage_LoadSaveDialog_list_deselectall_button; public static String UserLibraryPreferencePage_LoadSaveDialog_list_save_label; public static String UserLibraryPreferencePage_LoadSaveDialog_list_load_label; public static String UserLibraryPreferencePage_LoadSaveDialog_filedialog_save_title; public static String UserLibraryPreferencePage_LoadSaveDialog_filedialog_load_title; public static String UserLibraryPreferencePage_LoadSaveDialog_error_empty; public static String UserLibraryPreferencePage_LoadSaveDialog_error_invalidfile; public static String UserLibraryPreferencePage_LoadSaveDialog_overwrite_title; public static String UserLibraryPreferencePage_LoadSaveDialog_save_ok_message; public static String UserLibraryPreferencePage_LoadSaveDialog_overwrite_message; public static String UserLibraryPreferencePage_LoadSaveDialog_save_errordialog_title; public static String UserLibraryPreferencePage_LoadSaveDialog_save_errordialog_message; public static String UserLibraryPreferencePage_LoadSaveDialog_location_error_save_enterlocation; public static String UserLibraryPreferencePage_LoadSaveDialog_location_error_save_invalid; public static String UserLibraryPreferencePage_LoadSaveDialog_list_error_save_nothingselected; public static String UserLibraryPreferencePage_LoadSaveDialog_location_error_load_enterlocation; public static String UserLibraryPreferencePage_LoadSaveDialog_location_error_load_invalid; public static String UserLibraryPreferencePage_LoadSaveDialog_list_error_load_nothingselected; public static String UserLibraryPreferencePage_LoadSaveDialog_load_badformat; public static String UserLibraryPreferencePage_LoadSaveDialog_load_replace_title; public static String EditTemplateDialog_error_noname; public static String EditTemplateDialog_error_invalidName; public static String EditTemplateDialog_title_new; public static String EditTemplateDialog_title_edit; public static String EditTemplateDialog_name; public static String EditTemplateDialog_description; public static String EditTemplateDialog_context; public static String EditTemplateDialog_pattern; public static String EditTemplateDialog_insert_variable; public static String EditTemplateDialog_undo; public static String EditTemplateDialog_redo; public static String EditTemplateDialog_cut; public static String EditTemplateDialog_copy; public static String EditTemplateDialog_paste; public static String EditTemplateDialog_select_all; public static String EditTemplateDialog_content_assist; public static String JavaEditorPreferencePage_folding_title; public static String FoldingConfigurationBlock_enable; public static String FoldingConfigurationBlock_combo_caption; public static String FoldingConfigurationBlock_info_no_preferences; public static String FoldingConfigurationBlock_error_not_exist; public static String FoldingConfigurationBlock_warning_providerNotFound_resetToDefault; public static String PropertiesFileEditorPreferencePage_key; public static String PropertiesFileEditorPreferencePage_value; public static String PropertiesFileEditorPreferencePage_assignment; public static String PropertiesFileEditorPreferencePage_argument; public static String PropertiesFileEditorPreferencePage_comment; public static String PropertiesFileEditorPreferencePage_foreground; public static String PropertiesFileEditorPreferencePage_color; public static String PropertiesFileEditorPreferencePage_bold; public static String PropertiesFileEditorPreferencePage_italic; public static String PropertiesFileEditorPreferencePage_strikethrough; public static String PropertiesFileEditorPreferencePage_underline; public static String PropertiesFileEditorPreferencePage_enable; public static String PropertiesFileEditorPreferencePage_preview; public static String PropertiesFileEditorPreferencePage_link; public static String PropertiesFileEditorPreferencePage_link_tooltip; public static String SmartTypingConfigurationBlock_autoclose_title; public static String SmartTypingConfigurationBlock_automove_title; public static String SmartTypingConfigurationBlock_tabs_title; public static String SmartTypingConfigurationBlock_tabs_message_tab_text; public static String SmartTypingConfigurationBlock_tabs_message_others_text; public static String SmartTypingConfigurationBlock_tabs_message_tooltip; public static String SmartTypingConfigurationBlock_tabs_message_spaces; public static String SmartTypingConfigurationBlock_tabs_message_tabs; public static String SmartTypingConfigurationBlock_tabs_message_tabsAndSpaces; public static String SmartTypingConfigurationBlock_pasting_title; public static String SmartTypingConfigurationBlock_strings_title; public static String WorkingSetPropertyPage_ReadOnlyWizard_description; public static String WorkingSetPropertyPage_ReadOnlyWizard_title; public static String CodeAssistConfigurationBlock_typeFilters_link; public static String CodeAssistConfigurationBlock_sortingSection_title; public static String CodeAssistConfigurationBlock_autoactivationSection_title; public static String CodeAssistConfigurationBlock_insertionSection_title; public static String JavaEditorPreferencePage_coloring_category_java; public static String JavaEditorPreferencePage_coloring_category_javadoc; public static String JavaEditorPreferencePage_coloring_category_comments; public static String ProjectSelectionDialog_title; public static String ProjectSelectionDialog_desciption; public static String ProjectSelectionDialog_filter; static { NLS.initializeMessages(BUNDLE_NAME, PreferencesMessages.class); } public static String NameConventionConfigurationBlock_use_override_annotation_label; public static String ProblemSeveritiesConfigurationBlock_pb_unhandled_surpresswarning_tokens; public static String ProblemSeveritiesConfigurationBlock_pb_enable_surpresswarning_annotation; public static String SmartTypingConfigurationBlock_annotationReporting_link; public static String CodeAssistConfigurationBlock_restricted_link; public static String CodeAssistConfigurationBlock_hideDiscouraged_label; public static String CodeAssistConfigurationBlock_hideForbidden_label; public static String UserLibraryPreferencePage_UserLibraryPreferencePage_libraries_up_button; public static String UserLibraryPreferencePage_UserLibraryPreferencePage_libraries_down_button; public static String EditTemplateDialog_autoinsert; public static String ComplianceConfigurationBlock_jrecompliance_info; public static String ComplianceConfigurationBlock_jrecompliance_info_project; public static String ProblemSeveritiesConfigurationBlock_section_generics; public static String JavaBasePreferencePage_dialogs; public static String JavaBasePreferencePage_do_not_hide_description; public static String JavaBasePreferencePage_do_not_hide_button; public static String JavaBasePreferencePage_do_not_hide_dialog_title; public static String JavaBasePreferencePage_do_not_hide_dialog_message; public static String CodeAssistConfigurationBlock_matchCamelCase_label; public static String ComplianceConfigurationBlock_version16; public static String ComplianceConfigurationBlock_versionCLDC11; public static String ComplianceConfigurationBlock_src_greater_compliance; public static String ComplianceConfigurationBlock_classfile_greater_compliance; public static String ComplianceConfigurationBlock_classfile_greater_source; public static String ProblemSeveritiesConfigurationBlock_pb_parameter_assignment; public static String ProblemSeveritiesConfigurationBlock_pb_null_reference; public static String ProblemSeveritiesConfigurationBlock_pb_potential_null_reference; public static String ProblemSeveritiesConfigurationBlock_pb_fall_through_case; public static String ProblemSeveritiesConfigurationBlock_unused_suppresswarnings_token; public static String CodeAssistConfigurationBlock_hideDeprecated_label; public static String CodeAssistStaticMembersConfigurationBlock_description; public static String CodeAssistStaticMembersConfigurationBlock_newType_button; public static String CodeAssistStaticMembersConfigurationBlock_newMember_button; public static String CodeAssistStaticMembersConfigurationBlock_edit_button; public static String CodeAssistStaticMembersConfigurationBlock_remove_button; public static String FavoriteStaticMemberInputDialog_member_title; public static String FavoriteStaticMemberInputDialog_member_labelText; public static String FavoriteStaticMemberInputDialog_type_title; public static String FavoriteStaticMemberInputDialog_type_labelText; public static String FavoriteStaticMemberInputDialog_browse_button; public static String FavoriteStaticMemberInputDialog_ChooseTypeDialog_title; public static String FavoriteStaticMemberInputDialog_ChooseTypeDialog_description; public static String FavoriteStaticMemberInputDialog_ChooseTypeDialog_error_message; public static String FavoriteStaticMemberInputDialog_error_enterName; public static String FavoriteStaticMemberInputDialog_error_invalidMemberName; public static String FavoriteStaticMemberInputDialog_error_invalidTypeName; public static String FavoriteStaticMemberInputDialog_error_entryExists; public static String PHPCodeTemplateBlock_2; public static String PHPCoreOptionsConfigurationBlock_SettingVersionFailed_Title; }
/** * Creates the reisze pane with which the user can resize the model.grid * * @return the ScrollPane holding the link control panel */ private ScrollPane createGridResizePane() { Pane resizePanel = new Pane(); ToggleGroup radioGroup = new ToggleGroup(); myBuilder.addNewRadioButton(resizePanel, new ComponentProperties(20, 20) .text(myResources.getString("radioButton1Text")) .toggleGroup(radioGroup) .selected(true) .id(myResources.getString("radioButtonCSSId"))); RadioButton decrease = (RadioButton) myBuilder.addNewRadioButton(resizePanel, new ComponentProperties(20, 60) .text(myResources.getString("radioButton2Text")) .toggleGroup(radioGroup) .selected(false) .id(myResources.getString("radioButtonCSSId"))); myBuilder.addNewLabel(resizePanel, new ComponentProperties(20, 120) .text(myResources.getString("resizeInstructions1")) .color(Color.WHITE) .size(15)); @SuppressWarnings("unchecked") ComboBox<GridSizeDirection> directionComboBox = (ComboBox<GridSizeDirection>) myBuilder.addNewComboBox(resizePanel, new ComponentProperties<GridSizeDirection>(190, 125) .options(FXCollections.observableArrayList(GridSizeDirection.values()))); myBuilder.addNewLabel(resizePanel, new ComponentProperties(20, 200) .text(myResources.getString("resizeInstructions2")) .color(Color.WHITE) .size(15)); TextField sizeInput = (TextField) myBuilder.addNewTextField(resizePanel, new ComponentProperties(20, 230) .text(myResources.getString("sizeInputPrompt")) .width(200)); Button button = (Button) myBuilder.addNewButton(resizePanel, new ComponentProperties(20, 300) .text(myResources.getString("resizePrompt"))); directionComboBox.valueProperty().addListener(e -> button.setDisable(invalidValue(directionComboBox.getValue(), sizeInput.getText()))); sizeInput.textProperty().addListener(e -> button.setDisable(invalidValue(directionComboBox.getValue(), sizeInput.getText()))); sizeInput.textProperty().addListener(e -> button.setDisable(invalidValue(directionComboBox.getValue(), sizeInput.getText()))); button.setDisable(true); setResizeEventHandler(button, directionComboBox, sizeInput, radioGroup, decrease); return new ScrollPane(resizePanel); }
// purge continuously purges rows from a table. // This function is non-reentrant: there's only one instance of this function running at any given time. // A timer keeps calling this function, so if it bails out (e.g. on error) it will later resume work func (collector *TableGC) purge(ctx context.Context) (tableName string, err error) { if atomic.CompareAndSwapInt64(&purgeReentranceFlag, 0, 1) { defer atomic.StoreInt64(&purgeReentranceFlag, 0) } else { return "", nil } tableName, found := collector.nextTableToPurge() if !found { return "", nil } conn, err := dbconnpool.NewDBConnection(ctx, collector.env.Config().DB.DbaWithDB()) if err != nil { return tableName, err } defer conn.Close() if _, err := conn.ExecuteFetch("SET sql_log_bin = OFF", 0, false); err != nil { return tableName, err } defer func() { if !conn.IsClosed() { if _, err := conn.ExecuteFetch("SET sql_log_bin = ON", 0, false); err != nil { log.Errorf("TableGC: error setting sql_log_bin = ON: %+v", err) } } }() log.Infof("TableGC: purge begin for %s", tableName) for { if time.Since(collector.lastSuccessfulThrottleCheck) > throttleCheckDuration { checkResult := collector.lagThrottler.Check(ctx, throttlerAppName, "", throttleFlags) if checkResult.StatusCode != http.StatusOK { time.Sleep(throttleCheckDuration) continue } collector.lastSuccessfulThrottleCheck = time.Now() } parsed := sqlparser.BuildParsedQuery(sqlPurgeTable, tableName) res, err := conn.ExecuteFetch(parsed.Query, 1, true) if err != nil { return tableName, err } if res.RowsAffected == 0 { collector.submitTransitionRequest(ctx, schema.PurgeTableGCState, tableName) collector.removePurgingTable(tableName) log.Infof("TableGC: purge complete for %s", tableName) time.AfterFunc(time.Second, func() { collector.purgeRequestsChan <- true }) return tableName, nil } } }
# -*- coding: latin-1 -*- """ Funciones matematicas de todo tipo """ from math import asin, atan import cmath from numarray import * import numarray.linear_algebra as la import copy import logging import pylab ################################################################################ # UTILIDADES # ################################################################################ def escalon(a=0.0, b=1.0, A = 0.0, B=1.0): """ Devuelve una funcion escalon: B | ........ | . . A |.... ........ -------------------------------- a b Si b = None --> b = inf Si a = None --> a = inf Valores por defecto: a = A = 0.0 b = B = 1.0 """ if a == None: def r(t): if t<=b: return B else: return A elif b == None: def r(t): if t>=a: return B else: return A else: def r(t): if t>=a and t<=b: return B else: return A return r def sign(x): """ Devuelve el signo de x (0 se interpreta con signo positivo) x>=0 --> +1 x <0 --> -1 """ if x<0: return -1 elif x>=0: return +1 def cross(a, b): """ Calcula el producto vectorial de dos vectores. Los vectores pueden ser cualquier elemento iterable, pero el resultado es un array. """ return array([ a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0] ]) def mod(x): """ Devuelve el modulo del vector x """ s = 0 for c in x: s += c**2 return sqrt(s) def rlen(x): """ Alias para range(len(x)) """ return range(len(x)) def reverse(x): """ Ordena al reves una lista. """ y = [] for i in rlen(x): y.append(x[-1 - i]) return y def rad(x): """ Convierte de grados a radianes """ return x*pi/180. def deg(x): """ Convierte de radianes a grados """ return x*180./pi def localiza(x, L): """ Dado un contenedor L ordenado de menor a mayor , y un valor x, devuelve el indice del array tal que L[i]<=x<=L[i+1] mediante el metodo de la biseccion. Si el elemento no esta en la lista devuelve alguno de los extremos, de forma que el interpolador lineal se convierte automaticamente en un extrapolador. """ a=0 b=len(L)-1 while not ( (L[a+(b-a-1)/2]<=x) and (L[a+(b-a-1)/2+1]>=x) ): if x<L[a+(b-a-1)/2]: b=a+(b-a-1)/2 else: a=a+(b-a-1)/2+1 if a==len(L)-1: return len(L)-2 elif b==0: return 0 return a+(b-a-1)/2 def ang(x, y): """ Calcula el angulo que forma el punto (x,y). Util porque distingue porque vale para cualquier cuadrante y porque trata sin problemas los casos +-pi/2. """ if x == 0: if y>0: a = pi/2 elif y<0: a = -pi/2 else: a = 0.0 else: a = atan(y/x) if x<0: if y<0: a = a - pi else: a = a + pi if a>=pi: a -= 2*pi elif a<=-pi: a += 2*pi return a ################################################################################ # SUAVIZADO # ################################################################################ def smooth(x, cparada=None, cfijo=None): """ Suaviza los datos x, hasta que se cumpla una condicion de parada. cparada(n, x): devuelve verdadero cuando se cumpla la condicion de parada, para n pasadas y datos x cfijo(i) : devuelve verdadero si el dato en el indice i no es modificable """ if cfijo == None: def cfijo(i): if i<2 or i>len(x)-3: return True else: return False if cparada == None: def cparada(n, y): if n==1: return True else: return False # Arrays temporales y = x.copy() z = x.copy() # numero de pasadas n = 0 # kernel gaussiano para 4 vecinos p = 2 c = [0.1174, 0.1975, 0.2349, 0.1975, 0.1174] # Aplicamos sucesivas paradas mientras no se la condicion de parada while not cparada(n, y): for i in rlen(y): if not cfijo(i): z[i] = 0.0 for k in range(-p, p +1): z[i] += c[k]*y[i+k] y, z = z, y n += 1 return y ################################################################################ # CALCULO # ################################################################################ def solveNewton(h, ix, Nmax, eps): """ Resuelve por el metodo de Newton. En realidad aplica el metodo iterativo: Xn+1 = Xn + h(Xn) Mientras sea: |Xn+1 - Xn|>eps y n<Nmax Se supone que la funcion h(x) representa: h(x) = -f(x)/f'(x) para que el metodo calcule f(x)=0 """ n, error = 0, eps + 1 x0=ix while error>eps: x1=x0 + h(x0) error=abs(x1-x0) x0=x1 if n>Nmax: logging.error("Metodo de Newton no converge") break n += 1 return x1 def solveNewtonMulti(f, ix, Nmax, eps): """ Metodo de Newton para la ecuacion vectorial f(x) = 0. ix es el punto inicial Nmax maximo de iteraciones eps error numerico """ n, error, x0 = 0, eps + 1, ix s = len(ix) J = array(shape=(s,s), type='Float64') while error>eps: for i in range(s): J[i,:] = dpart_1(f, x0, i, eps) x1 = x0 - dot(la.inverse(J), f(x0)) error = mod(x1 - x0) x0 = x1 if n>Nmax: logging.error("Metodo de Newton(multi) no converge") break n += 1 return x1 def solveSecante(f, xa, xb, Nmax, eps): """ Resuelve f=0 mediante el metodo de la secante. xa y xb son los puntos iniciales para calcular la secante, de forma ideal deberia ser signo(f(xa))!=signo(f(xb)) y xa<xb """ error = eps + 1 n = 0 xa = float(xa) xb = float(xb) ya = f(xa) yb = f(xb) while error>eps: # Si tenemos la mala suerte de una horizontal # probamos con otro punto if yb == ya: xb = (xb + xa)/2. yb = f(xb) continue # Interseccion con cero de la recta que une A y B x = (xa*yb - ya*xb)/(yb - ya) y = f(x) # A lo mejor ha habido suerte if x == xa or x == xb: return x # Decidimos que punto se marcha, si A o B # Supongamos que se marcha B if y!=ya: x1 = (xa*y - ya*x)/(y-ya) else: # x1 es infinito x1 == None # Supongamos que se marcha A if y!=yb: x2 = (x*yb - y*xb)/(yb-y) else: # x2 es infinito x2 = None # Alguno de los 2 puntos no es posible if x1 == None: xa = x ya = y continue if x2 == None: xb = x yb = y continue # Hay que decidir entre dos puntos if sign(ya)!=sign(yb): # La solucion esta entre xa y xb, nos aseguramos # de que el nuevo punto caiga en este intervalo # si x1==None o x2==None fallan los test de intervalo # como debe ser if xa<x1 and x1<xb: # 1 cae dentro if xa<x2 and x2<xb: # Ambos caen dentro, nos quedamos con el mejor y1 = f(x1) y2 = f(x2) if abs(y1)<abs(y2): xb = x yb = y else: xa = x ya = y else: # 1 cae dentro, pero 2 fuera xb = x yb = y else: # 1 cae fuera, al menos uno tiene que caer dentro # por ser distinto signo ya, yb, luego 2 cae dentro xa = x ya = y else: # La solucion no tiene por que estar dentro del intervalo # Nos limitamos a coger el mejor y1 = f(x1) y2 = f(x2) if abs(y1)<abs(y2): xb = x yb = y else: xa = x ya = y if xa>xb: xa, xb = xb, xa ya, yb = yb, ya error = abs(y) n += 1 if n>Nmax: logging.error("Secante no converge") return None return x def deriv_1(f, x, h=0.001): """ Calcula la primera derivada de f en el punto x """ return (f(x+h) - f(x-h))/(2*h) def dpart_1(f, x, p, h=0.001): """ Calcula la derivada parcial de f en el punto x, en la coordenada p """ x1 = copy.deepcopy(x) x2 = copy.deepcopy(x) x1[p] -= h x2[p] += h return (f(x2) - f(x1))/(2*h) ################################################################################ # AJUSTE POR MINIMOS CUADRADOS # ################################################################################ def lsq_fit(x, y, f): """ Calcula un ajuste lineal del tipo: a0*f[0](x) + a1*f[1](x) + ... + aM-1*f[M-1](x) para los N datos "y" definidos en las N posiciones "x". Devuelve los coeficientes "a" y la desviacion estimadas en cada punto. """ M = len(f) b = array(shape=(M), type='Float64') c = array(shape=(M, M), type='Float64') for j in range(M): for k in range(M): c[k, j] = sum([dot(f[j](x[i]),f[k](x[i])) for i in rlen(x)]) b[j] = sum([dot(y[i], f[j](x[i])) for i in rlen(x)]) d = la.inverse(c) return dot(d, b), map(sqrt, diagonal(d)) def f_pol(n): """ Devuelve una funcion polinomica de grado n """ return (lambda x: x**n) def f_cos(n): """ Devuelve una funcion coseno de frecuencia n """ return (lambda x: cos(n*x)) def f_sin(n): """ Devuelve una funcion seno de frecuencia n """ return (lambda x: sin(n*x)) def f_lin(c, f): """ Devuelve la funcion c[i]*f[i] """ def r(x): return sum([c[i]*f[i](x) for i in rlen(f)]) return r ################################################################################ # INTERPOLADORES # ################################################################################ class InterpoladorLineal: """ Interpolador lineal para tablas multidimensionales """ def __init__(self, x, y): # nos aseguramos de que los tipos son correctos if not hasattr(x[0], '__getitem__'): self.x = [x] else: self.x = x self.y = array(y) # la dimension de cada punto de la tabla self.dim_x = len(self.x) def __call__(self, ix): """ Interpola el valor en el punto ix """ if not hasattr(ix, '__getitem__'): x = [ix] else: x = ix y0 = self.y for d in range(self.dim_x): i = localiza(x[d], self.x[d]) x0, x1, x2 = x[d], self.x[d][i], self.x[d][i+1] y1 = ((x2 - x0)*y0[i] + (x0 -x1)*y0[i+1])/(x2-x1) y0 = y1 return y1 class InterpoladorSpline: """ Interpola mediante splines cubicas datos unidimensionale. """ def __init__(self, x, y, tipo = 'Clamp', t0 = None, t1 = None): """ x: vector con las coordenadas x y: vector con las coordenadas y t0: tangente en x[0],y[0] t1: tangente en x[n],y[n] (len(x) == len(y) == n + 1) """ self.x = x self.y = y if t0 == None: t0 = (y[1] - y[0])/(x[1] - x[0]) if t1 == None: t1 = (y[-1] - y[-2])/(x[-1] - x[-2]) # Construimos el sistema de ecuaciones que nos determinan los # coeficientes de las splines n = len(x) - 1 C = zeros( shape = (n+1, n+1), type='Float64' ) b = array( shape =(n+1,), type='Float64') self.h = h = array( [x[i+1] - x[i] for i in range(n)], type='Float64') # Condiciones en los extremos if tipo == 'Clamp': C[0,:2] = [2, 1] b[0] = 6/(h[0]**2)*(y[1] - y[0] - t0*h[0]) C[n,-2:] = [1,2] b[n] = 6/(h[n-1]**2)*(y[n-1] - y[n] + t1*h[n-1]) else: C[0,0] = 1.0 b[0] = 0.0 C[n,n] = 1.0 b[n] = 0.0 # Grueso de la matriz for i in range(1,n): C[i][i-1:i+2] = [h[i-1], 2*(h[i-1] + h[i]), h[i]] b[i] = 6*((y[i+1] - y[i])/h[i] + (y[i-1] - y[i])/h[i-1]) # Salvamos los coeficientes self.a = la.solve_linear_equations(C, b) # Para poder consultarlo self.t0 = t0 self.t1 = t1 def __call__(self, ix): """ Calcula el valor interpolado en el punto ix. """ x, y = self.x, self.y i = localiza(ix, x) dx0, dx1 = ix - x[i], x[i+1] -ix a0, a1 = self.a[i], self.a[i+1] h = self.h[i] return ( (a0*dx1**3 + a1*dx0**3)/(6*h) + (y[i] - a0*h**2/6)*dx1/h + (y[i+1] - a1*h**2/6)*dx0/h ) ################################################################################ # QUATERNIOS # ################################################################################ def mul_quat(qA, qB): """ Multiplica dos cuaternios """ qAv = array(qA[1:]) qBv = array(qB[1:]) q0 = qA[0]*qB[0] - dot(qAv, qBv) q1, q2, q3 = qA[0]*qBv + qB[0]*qAv + cross(qAv, qBv) return q0, q1, q2, q3 class Quaternion: def __init__(self, q0=1., q1=0., q2=0., q3=0.): """ Inicializa el quaternio como (q0, (q1,q2,q3)) q0 es la parte escalar q1,q2,q3 la parte vectorial """ self.q0, self.q1, self.q2, self.q3 = q0, q1, q2, q3 def escalar(self): """ Devuelve la parte escalar del quaternio. """ return self.q0 def vector(self): """ Devuelve la parte vectorial del quaternio. """ return array([self.q1, self.q2, self.q3], type='Float64') @classmethod def rot(cls, ang, x, y, z): """ Devuelve un quaternio de la rotacion ang por el vector (x,y,z) """ q0 = cos(ang/2.) q1, q2, q3 = ( sin(ang/2.)*array([x, y, z], type='Float64')/ sqrt(x**2 + y**2 + z**2) ) return Quaternion(q0, q1, q2, q3) @classmethod def euler(cls, ch, th, fi): """ Devuelve el quaternio de rotacion equivalente a los angulos de euler dados """ return Quaternion.rotacion( [ (ch, 0, 0, 1), (th, 0, 1, 0), (fi, 1, 0, 0) ]) def conj(self): """ Devuelve el quaternio conjugado """ return Quaternion(self.q0, -self.q1, -self.q2, -self.q3) def toMatrix(self): """ Devuelve la matriz equivalente de rotacion """ q0, q1, q2, q3 = self.q0, self.q1, self.q2, self.q3 M = array(shape = (3, 3), type='Float64') return array([ [ 1. - 2.*(q2**2 + q3**2), 2.*(-q0*q3 + q1*q2), 2.*(q0*q2 + q1*q3) ], [ 2.*(q0*q3 + q1*q2), 1. - 2.*(q1**2 + q3**2), 2.*(-q0*q1 + q2*q3) ], [ 2.*(-q0*q2 + q1*q3), 2.*(q0*q1 + q2*q3), 1. - 2.*(q1**2 + q2**2) ]], type='Float64') def toEuler(self): """ Devuelve los angulos de euler en la tupla (ch, th, fi). """ q0, q1, q2, q3 = self.q0, self.q1, self.q2, self.q3 # normalizamos m = sqrt(q0**2 + q1**2 + q2**2 + q3**2) q0 /= m q1 /= m q2 /= m q3 /= m Sth = -2*(q1*q3 - q0*q2) # Como -pi/2<=th<=pi/2 podemos hacer esto tranquilos # Para th = +-pi/2 es posible que por error numerico se Sth>1 if Sth>1.0: Sth = 1.0 th = asin(Sth) # si no hay singularidad (th != +-pi/2) if abs(Sth) != 1.0: ch = ang(1 - 2*(q2**2 + q3**2), 2*(q1*q2 + q0*q3)) fi = ang(1 - 2*(q1**2 + q2**2), 2*(q0*q1 + q2*q3)) # si no damos un valor cualquiera a ch, ya que hay varias posibilidades # para ch y th que nos dan los mismos ejes else: ch = 0 fi = ang(q0*q2 + q1*q3, q1*q2 - q0*q3) return ch, th, fi def __add__(self, other): return Quaternion( self.q0 + other.q0, self.q1 + other.q1, self.q2 + other.q2, self.q3 + other.q3) def __mul__(self, other): if isinstance(other, Quaternion): q0 = self.q0*other.q0 - dot(self.vector(), other.vector()) q1, q2, q3 = ( self.q0*other.vector() + other.q0*self.vector() + cross(self.vector(), other.vector()) ) else: q0, q1, q2, q3 = ( other*self.q0, other*self.q1, other*self.q2, other*self.q3 ) return Quaternion(q0, q1, q2, q3) def __rmul__(self, other): return self*other def __sub__(self, other): return Quaternion( self.q0 - other.q0, self.q1 - other.q1, self.q2 - other.q2, self.q3 - other.q3 ) def __repr__(self): return "[%f, (%f, %f, %f)]" % (self.q0, self.q1, self.q2, self.q3) @classmethod def rotacion(cls, l_quat): """ Devuelve el quaternio resultante de aplicar sucesivamente las rotaciones contenidas en l_quat. Cada rotacion es una tupla de formato: (angulo, x, y, z) """ return reduce(lambda x,y: x*y, [Quaternion.rot(r[0], r[1], r[2], r[3]) for r in l_quat]) def __iter__(self): return [self.q0, self.q1, self.q2, self.q3].__iter__() ################################################################################ # POLINOMIOS # ################################################################################ def polyeval(p, x): """ Evalua el polinomio en x """ n = len(p) - 1 r = p[n] for i in range(n-1, -1, -1): r = p[i] + r*x return r def polydiv(p, a): """ Divide el polinomio p por el monomio x-a """ n = len(p) - 1 q = array(shape=(n,), type='Complex64') r = p[n] for i in range(n-1, -1, -1): s = p[i] q[i] = r r = s + a*r return q def psolve(p, eps = 0.001, x0 = 0., x1 = 1., x2 = 2., Nmax=100): """ Encuentra una raiz mediante el metodo de Muller """ P0 = polyeval(p, x0) P1 = polyeval(p, x1) P2 = polyeval(p, x2) error = eps + 1. n = 0 while error>eps: if n>Nmax: print "polysolve: n=%d>Nmax=%d" % (n, Nmax) return None q = (x0 - x1)/(x1 - x2) A = q*P0 - q*(1 + q)*P1 + q*q*P2 B = (2*q + 1)*P0 - (1+q)*(1+q)*P1 + q*q*P2 C = (1+q)*P0 # Si tenemos suerte es C = 0, en cuyo caso # interrumpimos YA, porque entonces es E = 0 # y dividiriamos por cero if C == 0: return x0 D = cmath.sqrt(B*B - 4*A*C) E1 = B - D E2 = B + D if abs(E1)>abs(E2): E = E1 else: E = E2 x = x0 - (x0 - x1)*2*C/E error = abs(x-x0) x0, x1, x2 = x, x0, x1 P0, P1, P2 = polyeval(p, x0), P0, P1 return x0 def polysolve(p, eps = 0.001, x0 = 0., x1 = 1., x2 = 2., Nmax=100): """ Encuentra todas las raices del polinomio, aplicando el metodo de Muller y dividiendo por la raiz resultante """ r = [] q = p while len(q)>1: s = psolve(q, eps, x0, x1, x2, Nmax) r.append(s) q = polydiv(q, s) return r def estabilidad(a, f, xa=-4, ya=-4, xb=0.5, yb=4, Nx=100, Ny=100): """ Dibuja la region de estabilidad. El polinomio de estabilidad tiene la forma: q(r) = sum( (a[j] - w*f[j](w))*r^(p-j), j, 0, p) donde p es el numero de pasos del esquema xa, ya, xb, yb forma el rectangulo donde se realiza el calculo. Nx, Ny son la resolucion que se utiliza para la malla. """ def pol(x, y): """ Calcula el polinomio característico en un punto generico x, y. """ # Si un coeficiente no esta presente, vale cero la = len(a) lf = len(f) # lt - 1 = numero de pasos-->lt coeficientes # generalmente lf>la lt = max(la, lf) def geta(i): if i>=la: return 0.0 else: return a[i] def getf(i): if i>=lf: return lambda x: 0.0 + 0.0j else: return f[i] # Punto del plano complejo w = x + y*1j # Lista con los coeficientes p = zeros(shape=(lt,), type='Complex64') # Finalmente construimos el polinomio for j in range(lt): p[lt - 1 - j] = geta(j) - w*getf(j)(w) return p Z = array(shape=(Nx, Ny), type='Float64') dx = float(xb - xa)/(Nx-1) dy = float(yb - ya)/(Ny-1) X = arange(xa, xb + dx, dx) Y = arange(ya, yb + dy, dy) mini = Nx - 1 maxi = 0 minj = Ny - 1 maxj = 0 for i in range(0, Nx): for j in range(0, Ny): p = pol(X[i], Y[j]) # Los ceros del polinomio z = polysolve(p) # Nos quedamos con la raiz de mayor modulo r = max(map(abs, z)) if r<=1: if i<mini: mini = i if i>maxi: maxi = i if j<minj: minj = j if j>maxj: maxj = j Z[j, i] = r # Damos un margen mini -= 3 maxi += 3 minj -= 3 maxj += 3 # Evitamos salirnos de limites if mini<0: mini = 0 if maxi>Nx - 1: maxi = Nx - 1 if minj<0: minj = 0 if maxj>Ny - 1: maxj = Ny - 1 # Por algun motivo solo funciona con copias X0 = X[mini:maxi].copy() Y0 = Y[minj:maxj].copy() Z0 = Z[minj:maxj, mini:maxi].copy() pylab.contour(X0, Y0, Z0, arange(0, 1.05, 0.05), colors='k') pylab.show() return X, Y, Z if __name__=="__main__": def f(x): A = array([1, 0, 0], type='Float64') B = array([ [1, 1, 1], [1, 1, 0], [1, 0, 0]], type='Float64') return A + dot(B, x) def g(x): a, b = x return array([a + b - 2, (a - 1)*(b + 2)], type='Float64') print solveNewtonMulti(f, [0, 0, 0], 100, 1e-5) print solveNewtonMulti(g, [0, 0], 100, 1e-5)
package strategies.divers; import cls.SimpleEnsemble; import com.yahoo.labs.samoa.instances.Instance; import utils.Trackable; import java.util.HashMap; import java.util.Random; public abstract class DiversityStrategy implements Trackable { abstract public void update(Instance instance, SimpleEnsemble ensemble, HashMap<String, Double> driftIndicators); abstract public void diversify(Instance instance, SimpleEnsemble ensemble); abstract public void reset(); protected Random random = new Random(); }
<reponame>CallistoHouseLtd/Raven /******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2003, 2016 <NAME> * * 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. * ****************************************************************************** * porcini/whisper would not be possible without the ideas, implementation, * brilliance and passion of the Squeak/Pharo communities and the cryptography * team, which are this software's foundation. * ****************************************************************************** * porcini/whisper would not be possible without the ideas, implementation, * brilliance and passion of the erights.org community, which is also this software's * foundation. In particular, I would like to thank the following individuals: * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> *******************************************************************************/ package club.callistohouse.raven.presentation.utils; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.List; import org.apache.log4j.BasicConfigurator; import org.junit.Before; import org.junit.Test; import com.google.zxing.common.reedsolomon.GaloisField; import com.google.zxing.common.reedsolomon.GenericGF; import com.google.zxing.common.reedsolomon.ReedSolomonDecoder; import com.google.zxing.common.reedsolomon.ReedSolomonEncoder; import com.google.zxing.common.reedsolomon.ReedSolomonException; import club.callistohouse.raven.core.RavenServer; import club.callistohouse.raven.core.RavenTerminal; import club.callistohouse.raven.remote.RavenInputStream; import club.callistohouse.raven.remote.RavenOutputStream; import club.callistohouse.raven.scope.Scope; import club.callistohouse.raven.tables.SwissTable; import club.callistohouse.session.parrotttalk.SessionIdentity; public class EncodingTests { @Before public void setup() { BasicConfigurator.configure(); } @Test @SuppressWarnings({ "unchecked", "resource" }) public void testArrayList() throws IOException, ClassNotFoundException, NoSuchAlgorithmException { List<String> list = new ArrayList<String>(); list.add("pauwau"); SwissTable table = new SwissTable(); Scope scope = new Scope(new RavenTerminal(new RavenServer(new SessionIdentity("mine", 10042), table)), table); ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); new ObjectOutputStream(baos1).writeObject(list); List<String> poppedList1 = (List<String>)new ObjectInputStream(new ByteArrayInputStream(baos1.toByteArray())).readObject(); ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); new RavenOutputStream(baos2, scope).writeObject(list); List<String> poppedList2 = (List<String>)new RavenInputStream(new ByteArrayInputStream(baos2.toByteArray()), scope).readObject(); assertEquals(list, poppedList1); assertEquals(list, poppedList2); } @SuppressWarnings("resource") @Test public void testArray() throws IOException, ClassNotFoundException { String[] array = new String[] { "robert" }; SwissTable table = new SwissTable(); Scope scope = new Scope(new RavenTerminal(new RavenServer(new SessionIdentity("mine", 10042), table)), table); ByteArrayOutputStream baos = new ByteArrayOutputStream(); new RavenOutputStream(baos, scope).writeObject(array); String[] poppedArray = (String[])new RavenInputStream(new ByteArrayInputStream(baos.toByteArray()), scope).readObject(); assertArrayEquals(array, poppedArray); } @SuppressWarnings("resource") @Test public void testString() throws IOException, ClassNotFoundException { String str = "Life can be so sweet, all it takes is faith and the right attitude"; SwissTable table = new SwissTable(); Scope scope = new Scope(new RavenTerminal(new RavenServer(new SessionIdentity("mine", 10042), table)), table); ByteArrayOutputStream baos = new ByteArrayOutputStream(); new RavenOutputStream(baos, scope).writeObject(str); System.out.println(baos.toString()); String poppedStr = (String)new RavenInputStream(new ByteArrayInputStream(baos.toByteArray()), scope).readObject(); assertEquals(str, poppedStr); } @Test public void testBaseParametersForRS_15_9() { GaloisField galoisField = new GaloisField(GenericGF.OW_CODE_FIELD_16, 15, 9, 4); assertEquals(15, galoisField.getNumberOfChunkCodeSymbols()); assertEquals(9, galoisField.getNumberOfChunkDataSymbols()); assertEquals(30, galoisField.getNumberOfBlockCodeBytes()); assertEquals(18, galoisField.getNumberOfBlockDataBytes()); assertEquals(60, galoisField.getNumberOfBlockCodeSymbols()); assertEquals(36, galoisField.getNumberOfBlockDataSymbols()); assertEquals(6, galoisField.getECSymbols()); assertEquals(4, galoisField.getSymbolSizeInBits()); } @Test public void testBaseParametersForRS_255_247() { GaloisField galoisField = new GaloisField(GenericGF.RS_256_A, 255, 247, 8); assertEquals(255, galoisField.getNumberOfChunkCodeSymbols()); assertEquals(247, galoisField.getNumberOfChunkDataSymbols()); assertEquals(1020, galoisField.getNumberOfBlockCodeBytes()); assertEquals(988, galoisField.getNumberOfBlockDataBytes()); assertEquals(1020, galoisField.getNumberOfBlockCodeSymbols()); assertEquals(988, galoisField.getNumberOfBlockDataSymbols()); assertEquals(8, galoisField.getECSymbols()); assertEquals(8, galoisField.getSymbolSizeInBits()); } @Test public void testBaseParametersForRS_255_223() { GaloisField galoisField = new GaloisField(GenericGF.RS_256_B, 255, 223, 8); assertEquals(255, galoisField.getNumberOfChunkCodeSymbols()); assertEquals(223, galoisField.getNumberOfChunkDataSymbols()); assertEquals(1020, galoisField.getNumberOfBlockCodeBytes()); assertEquals(892, galoisField.getNumberOfBlockDataBytes()); assertEquals(1020, galoisField.getNumberOfBlockCodeSymbols()); assertEquals(892, galoisField.getNumberOfBlockDataSymbols()); assertEquals(32, galoisField.getECSymbols()); assertEquals(8, galoisField.getSymbolSizeInBits()); } @Test public void testEncodeAndDecodeRS_15_9() throws ReedSolomonException { GaloisField galoisField = new GaloisField(GenericGF.OW_CODE_FIELD_16, 15, 9, 4); byte[] chunk = new byte[] { (byte) 0x0F, (byte) 0x0F, (byte) 0x0A, (byte) 0x0A, (byte) 0x0B, (byte) 0x0B, (byte) 0x09, (byte) 0x09, (byte) 0x0D}; byte[] encodedBytes = new ReedSolomonEncoder(galoisField).encodeBytes(chunk); byte[] decodedBytes = new ReedSolomonDecoder(galoisField).decodeBytes(encodedBytes); assertArrayEquals(chunk, decodedBytes); } @Test public void testEncodeAndDecodeRS_255_247() throws ReedSolomonException { GaloisField galoisField = new GaloisField(GenericGF.RS_256_A, 255, 247, 8); byte[] chunk = new byte[247]; byte[] test = new byte[] { (byte) 0x0F, (byte) 0x0E, (byte) 0x0D, (byte) 0x0B, (byte) 0x0A, (byte) 0x09, (byte) 0x08, (byte) 0x07, (byte) 0x06, (byte) 0x05}; for(int i = 0; i < 24; i++) { System.arraycopy(test, 0, chunk, i*10, test.length); } test = new byte[] { (byte) 0x0F, (byte) 0x0E, (byte) 0x0D, (byte) 0x0B, (byte) 0x0A, (byte) 0x09, (byte) 0x08 }; System.arraycopy(test, 0, chunk, 240, test.length); byte[] encodedBytes = new ReedSolomonEncoder(galoisField).encodeBytes(chunk); byte[] decodedBytes = new ReedSolomonDecoder(galoisField).decodeBytes(encodedBytes); assertArrayEquals(chunk, decodedBytes); } @Test public void testEncodeAndDecodeRS_255_223() throws ReedSolomonException { GaloisField galoisField = new GaloisField(GenericGF.RS_256_B, 255, 223, 8); byte[] chunk = new byte[223]; byte[] test = new byte[] { (byte) 0x0F, (byte) 0x0E, (byte) 0x0D, (byte) 0x0B, (byte) 0x0A, (byte) 0x09, (byte) 0x08, (byte) 0x07, (byte) 0x06, (byte) 0x05}; for(int i = 0; i < 22; i++) { System.arraycopy(test, 0, chunk, i*10, test.length); } test = new byte[] { (byte) 0x0F, (byte) 0x0E, (byte) 0x0D }; System.arraycopy(test, 0, chunk, 220, test.length); byte[] encodedBytes = new ReedSolomonEncoder(galoisField).encodeBytes(chunk); byte[] decodedBytes = new ReedSolomonDecoder(galoisField).decodeBytes(encodedBytes); assertArrayEquals(chunk, decodedBytes); } /* @Test public void testSmallDataEncoderDecoder() throws ReedSolomonException { byte[] testBytes = getSmallData(); byte[] encodedBytes = new FECBlockEncoder().encode(testBytes); assertArrayEquals(testBytes, decodedBytes); } @Test public void testLargeDataEncoderDecoder() throws ReedSolomonException { byte[] testBytes = getLargeData(); byte[] encodedBytes = new FECBlockEncoder().encode(testBytes); byte[] decodedBytes = new FECBlockDecoder().decode(encodedBytes); assertArrayEquals(testBytes, decodedBytes); }*/ protected byte[] getSmallData() { return "hello world".getBytes(); } protected byte[] getLargeData() { byte[] patternBytes = "helloworld".getBytes(); byte[] testBytes = new byte[3000000]; for(int i = 0; i < 300000; i++) { System.arraycopy(patternBytes, 0, testBytes, i*10, 10); } return testBytes; } /* @Test public void testEncodingDecoding() throws IOException, ClassNotFoundException { List<byte[]> byteList = getTestObject(); byte[] serializedBytes = serializeObject(byteList); byte[] encodedBytes = encodeTranny().encode(serializedBytes); byte[] decodedBytes = decodeTranny().decode(encodedBytes); assertArrayEquals(serializedBytes, decodedBytes); } @Test public void testByteArrays() throws IOException, ClassNotFoundException { byte[] bytes = "hello pauwau".getBytes(); byte[] encodedBytes = encodeTranny().encode(bytes); byte[] decodedBytes = decodeTranny().decode(encodedBytes); assertArrayEquals(bytes, decodedBytes); }*/ protected List<byte[]> getTestObject() { byte[] testBytes = new byte[1203]; new SecureRandom().nextBytes(testBytes); List<byte[]> byteList = new ArrayList<byte[]>(); byteList.add("hello pauwau".getBytes()); byteList.add(testBytes); return byteList; } protected byte[] serializeObject(Object obj) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(obj); return baos.toByteArray(); } protected Object deserializeObject(byte[] decodedBytes) throws IOException, ClassNotFoundException { ByteArrayInputStream bais = new ByteArrayInputStream(decodedBytes); ObjectInputStream in = new ObjectInputStream(bais); return in.readObject(); } /* @Test public void testEncoding() throws ReedSolomonException, IOException { String message = "Please don't serve a bad meal"; System.out.println(new String(encodeTranny().encode(message.getBytes()))); // System.out.println(encodeAndSerializeWithFECBlockEncoder(message)); } @Test public void testDeoding() throws ReedSolomonException, IOException, ClassNotFoundException { String message = "laedntsreabdmale a ve 'o seP"; System.out.println(new String(decodeTranny().decode(message.getBytes()))); // System.out.println(decodeAndDeserializeWithFECBlockEncoder(message)); } ScrambleByteTransformer encodeTranny() { return new ScrambleByteTransformer(); } ScrambleByteTransformer decodeTranny() { return new ScrambleByteTransformer(); }*/ }
Analog non-linear function synthesis Networks of resistors have been identified as interesting devices for analog computation. Since the analytical model of a network of constant resistors is a set of linear equations, such a circuit can be used to solve a large number of linear equations concurrently. Whenever such a resistive embodiment of a computational problem can be found, the resulting circuit is usually very simple, fast and dense compared to CPU-based hardware. Particular problems solved by such networks include simulation of electromagnetic f elds , linear image filtering , regularization for image processing , and D/A conversion . Netw orks of resistors are specially attractive for CMOS integrated circuits, since it has been shown that a circuit obtained by replacing every resistor by a single MOS transistor has exactly the same branch currents as its resistive counterpart . In the following, a resistive network combining constant and controlled resistors is described, as well as its implementation with MOS transistors. The purpose of this circuit is to synthesize non-linear functions of possibly several variables. The circuit can be considered as an implementation of fuzzy rules, since its constituents can be identified as membership functions, fuzzy logic gates and center-of-gravity "defuzzification" circuits. Alternatively, the circuit can also be considered as a look-up table with interpolation, since fuzzy rules and look-up table entries are actually about the same thing. With a single generic circuit structure, a number of different nonlinear functions can be synthesized by customizing geometrical parameters or connection patterns.
Production of lipid mediators in experimental keratitis of rabbit eye. The inhibitors of prostaglandin (PG) or leukotriene (LT) synthesis and antagonists of platelet-activating factor (PAF) or LTs are inhibitory in experimental keratitis and clinical symptoms of keratitis are reproduced by application of these lipid mediators. This suggests that PGE2, LTB4, LTD4, and PAF are involved in experimental immunogenic and toxic keratitis. The objective of the present study is the measurement of the concentrations of lipid mediators in the aqueous humour and their release by the cornea and iris during keratitis. In both inflammatory models the concentrations of PGE2, LTB4, LTD4, and PAF in the aqueous humour were significantly increased as compared to their controls. The release of PGE2, LTB4 and LTD4 from the cornea, and of PGE2, LTB4, and PAF from the iris was significantly increased compared to that from control tissues. The results are consistent with a role for these lipid mediators in the inflammatory models. Combined therapeutic use of synthesis inhibitors or antagonists of these mediators in eye inflammation seems possible and may serve as an alternative to topical corticosteroid therapy.
<gh_stars>0 /**TODO: Add copyright*/ #define BOOST_TEST_MODULE WeightInit test suite #include <boost/test/included/unit_test.hpp> #include <EvoNet/ml/WeightInit.h> #include <iostream> using namespace EvoNet; using namespace std; BOOST_AUTO_TEST_SUITE(weightInit) /** RandWeightInitOp Tests */ BOOST_AUTO_TEST_CASE(constructorRandWeightInitOp) { RandWeightInitOp<float>* ptrRandWeightInit = nullptr; RandWeightInitOp<float>* nullPointerRandWeightInit = nullptr; BOOST_CHECK_EQUAL(ptrRandWeightInit, nullPointerRandWeightInit); } BOOST_AUTO_TEST_CASE(destructorRandWeightInitOp) { RandWeightInitOp<float>* ptrRandWeightInit = nullptr; ptrRandWeightInit = new RandWeightInitOp<float>(); delete ptrRandWeightInit; } BOOST_AUTO_TEST_CASE(operationfunctionRandWeightInitOp) { RandWeightInitOp<float> operation(1.0, 2.0); operation = RandWeightInitOp<float>(0); BOOST_CHECK_NE(operation(), 0); operation = RandWeightInitOp<float>(1); BOOST_CHECK_NE(operation(), 1); operation = RandWeightInitOp<float>(10); BOOST_CHECK_NE(operation(), 10); operation = RandWeightInitOp<float>(100); BOOST_CHECK_NE(operation(), 100); } BOOST_AUTO_TEST_CASE(settersAndGettersRandWeightInitOp) { RandWeightInitOp<float> operation; BOOST_CHECK_EQUAL(operation.getName(), "RandWeightInitOp"); BOOST_CHECK_EQUAL(operation.getParamsAsStr(), "n:1.000000;f:1.000000"); } /** ConstWeightInitOp Tests */ BOOST_AUTO_TEST_CASE(constructorConstWeightInitOp) { ConstWeightInitOp<float>* ptrConstWeightInit = nullptr; ConstWeightInitOp<float>* nullPointerConstWeightInit = nullptr; BOOST_CHECK_EQUAL(ptrConstWeightInit, nullPointerConstWeightInit); } BOOST_AUTO_TEST_CASE(destructorConstWeightInitOp) { ConstWeightInitOp<float>* ptrConstWeightInit = nullptr; ptrConstWeightInit = new ConstWeightInitOp<float>(); delete ptrConstWeightInit; } BOOST_AUTO_TEST_CASE(operationfunctionConstWeightInitOp) { ConstWeightInitOp<float> operation(1); BOOST_CHECK_CLOSE(operation(), 1, 1e-6); } BOOST_AUTO_TEST_CASE(settersAndGettersConstWeightInitOp) { ConstWeightInitOp<float> operation; BOOST_CHECK_EQUAL(operation.getName(), "ConstWeightInitOp"); BOOST_CHECK_EQUAL(operation.getParamsAsStr(), "n:1.000000"); } /** RangeWeightInitOp Tests */ BOOST_AUTO_TEST_CASE(constructorRangeWeightInitOp) { RangeWeightInitOp<float>* ptrRangeWeightInit = nullptr; RangeWeightInitOp<float>* nullPointerRangeWeightInit = nullptr; BOOST_CHECK_EQUAL(ptrRangeWeightInit, nullPointerRangeWeightInit); } BOOST_AUTO_TEST_CASE(destructorRangeWeightInitOp) { RangeWeightInitOp<float>* ptrRangeWeightInit = nullptr; ptrRangeWeightInit = new RangeWeightInitOp<float>(); delete ptrRangeWeightInit; } BOOST_AUTO_TEST_CASE(operationfunctionRangeWeightInitOp) { RangeWeightInitOp<float> operation; operation = RangeWeightInitOp<float>(0, 0); BOOST_CHECK_EQUAL(operation(), 0); operation = RangeWeightInitOp<float>(0, 1); float value = operation(); BOOST_CHECK(value >= 0 && value <= 1); } BOOST_AUTO_TEST_CASE(settersAndGettersRangeWeightInitOp) { RangeWeightInitOp<float> operation(-1,1); BOOST_CHECK_EQUAL(operation.getName(), "RangeWeightInitOp"); BOOST_CHECK_EQUAL(operation.getParamsAsStr(), "lb:-1.000000;ub:1.000000"); } BOOST_AUTO_TEST_SUITE_END()
The Competitive Recap: We list what you might have missed (July 15th - July 21st) A lot is currently happening, and so it has become increasingly hard to keep track of everything that happened in a week. To help with that, we have compiled this Competitive Recap. Released every week we will try to congest every tournament and important news that has happened since the last recap. Whether you are interested in the bigger news, or want to stay updated on changes in teams, you can always tune in on Thursday to see if you missed anything. Important News: Valve issue cease and desist papers to twenty-three gambling websites After last week's statement by Valve clarifying their dislike of skin gambling, this week cease and desist papers surfaced showing just how active Valve will be in shutting down such surfaces. Valve is currently focusing on CSGO-based websites, but also included Dota2Lounge for example. Patch Notes: Ana arrives today, alongside major balance tweaks! The biggest Overwatch news this week was the arrival of Ana, and other tweaks from the same patch. Most people were expecting a PTR period of weeks, but Blizzard surprised all. Ana will be playable in our GosuGamers Weeklies this weekend because of it! Optical Broadcast charity tournament - Sign ups open Optical Broadcast is organizing a weekend of events aimed at helping the German cancer foundation “deutsche Krebshilfe e.V”. Due to the casual nature of especially the Saturday event, all players should feel comfortable signing up (with their friends). Registrations are handled on our website here. ANZ: The Zowie Gamestah Overwatch League is heating up​ The ANZ is lucky enough to have supporters like ZOWIE and Gamestah, who have been organizing consistent tournaments for Overwatch. Currently, the biggest tournament around is their Overwatch League, which will be going into Week 4 soon. [Community Spotlight] BlameTheController shows the probability of a Stealth Hero The discovery of specific voice lines in the game has started up some discussions. There are clear hints that the mechanic of stealth will get added to Overwatch. Stealth is one of those mechanics that people either hate or love, just like freezing effects. BlameTheController explains the situation in his video. Unique GosuGamers Content: Short Cuts #1: Volskaya Industries In this new video series, we compile useful shortcuts in the game as well as the ways to make use of them. Some heroes can easily move around the maps, like Pharah and Genji, but even Soldier: 76 and Junkrat can really get around with some trickery. The video format really highlights the actions required to get the most out of your hero. Overwatch as an esport - Part 1: The Beta period Overwatch has been out since May 24th, but has been playable since late October. Since then, the scene has grown a lot and many of the fans around now missed the formative beta scene. Luckily for those people, we decided to take a look back, and will do so in several more articles to come. How Pharah emerged as a premier pick in the previous metagame Pharah was one of the characters that gained a lot of value over time, due to certain hero nerfs and format changes. This lead to the rise of the Sky Queen. We highlighted this whole process, and identified her position in the last meta, in order to get insight into what is to come for her in the future. Tournament Recap: GosuGamers EU Weekly #16 - VODs The EU scene continues to be entertaining, in big part due to their highly competitive top division. Creation eSports did not play this weekend, which gave other top teams the opportunity to reach later rounds. GosuGamers NA Weekly #16 - VODs Due to the absence of teams like C9, LG and EnVyUs in our Weeklies over the last weeks, several other talented rosters have really have the chance to take the spotlight. nubris is still going strong, without a sponsor, and 1SHOT also surprised last weekend. Sea Algae (say it out loud and you might catch the joke) also continues to stick together and get results. That last team is also rumoured to get some sponsor backing soon. Beat Invitational - VODs: The BEAT Invitational finished this weekend, and provided great entertainment for all (but mostly the NA crowd). As we stated in our recap, this event included one pretty surprising finalist. That's all we will say, check out the VODs if you haven't already! iBUYPOWER Summer 2016 Overwatch Invitational: Where Beyond The Summit left off last week, iBUYPOWER picked up this weekend: Another NA invitational with all the best American teams. The big 3 (EnVyUs, Cloud9, Luminosity) played some great matches, but nubris NG Red and especially Code7 provided plenty of resistence as well. ESL Atlantic Showdown: Qualifiers for the ESL Atlantic Showdown continue these weeks, leading up to the grand GamesCom offline event. NA Qualifier #3 is still going on, and the important matches will be played today and tomorrow. Minor Transfers & Team News 1SHOT is recruiting a ladder grinder, and it could be you! 1SHOT, one of the mid tier with a lot of potential, is looking to reinforce their roster with a new DPS/flex player. The team has decided to open up applications to all players with an in-game skill rating of 76, and thus provide a great opportunity for ladder players wanting to turn pro. Sea Algae is looking for a Flex player Earlier today on Twitter, Sea Algae shared their desire to find a God Tier Flex player. Promising 'sponsorship coming very soon', the SA roster offers a mature and educative environment for players trying to go pro as well. We advise anyone interested in trying out Competitive Overwatch to apply for Sea Algae as well as 1SHOT. For more competitive OW news, follow @GosuOverwatch. QUICKPOLL Do you like the new section that highlights Features written over the week? Yes Thank you for voting! No Thank you for voting!
#include <bits/stdc++.h> using namespace std; typedef long long ll; int n, m; ll a[100000]; vector<vector<int> > conn(100000); int main() { cin >> n >> m; for(int i = 0; i < n; i++){ cin >> a[i]; } for(int i = 0; i < m; i++){ int y, x; cin >> y >> x; y -- , x--; conn[y].push_back(x); conn[x].push_back(y); } bool vis[n]; memset(vis, false, n); ll re = 0; for(int i = 0; i < n; i++){ if(vis[i])continue; vis[i] = true; queue<int> Q; Q.push(i); ll mi = a[i]; while(!Q.empty()){ int curr = Q.front(); Q.pop(); mi = min(a[curr], mi); for(int j = 0;j < conn[curr].size(); j++){ if(!vis[conn[curr][j]]){ Q.push(conn[curr][j]); vis[conn[curr][j]] = true; } } } re += mi; } cout << re << endl; return 0; }
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE BangPatterns #-} module Warden.Numeric ( combineFieldNumericState , combineMeanAcc , combineMeanDevAcc , combineNumericState , combineStdDevAcc , sampleMedian , summarizeFieldNumericState , summarizeNumericState , unsafeMedian , updateMinimum , updateMaximum , updateMeanDev , updateNumericState ) where import Control.Lens ((%~), (^.)) import qualified Data.Vector as V import qualified Data.Vector.Algorithms.Intro as Intro import Data.Vector.Unboxed ((!)) import qualified Data.Vector.Unboxed as VU import P import System.IO (IO) import Warden.Data import Warden.Sampling.Reservoir updateMinimum :: Minimum -> Double -> Minimum updateMinimum !acc x = {-# SCC updateMinimum #-} acc <> (Minimum x) {-# INLINE updateMinimum #-} updateMaximum :: Maximum -> Double -> Maximum updateMaximum !acc x = {-# SCC updateMaximum #-} acc <> (Maximum x) {-# INLINE updateMaximum #-} -- | Minimal-error mean and standard deviation with Welford's method. -- -- From Knuth (TAoCP v2, Seminumerical Algorithms, p232). -- -- \( \frac{1}{n} \sum_{x \in X} x \equiv M_1 = X_1, M_k = M_{k-1} + \frac{(X_k - M_{k-1})}{k} \) updateMeanDev :: MeanDevAcc -> Double -> MeanDevAcc updateMeanDev !macc x = {-# SCC updateMeanDev #-} case macc of MeanDevInitial -> let i = KAcc 1 m = MeanAcc 0 s = NoStdDevAcc in update' m s i x (MeanDevAcc m s i) -> update' m s i x where update' (MeanAcc m) s (KAcc i) v = let delta = v - m m' = MeanAcc $ m + delta / (fromIntegral i) i' = KAcc $ i + 1 s' = case s of NoStdDevAcc -> MStdDevAcc $ StdDevAcc 0 MStdDevAcc (StdDevAcc sda) -> MStdDevAcc . StdDevAcc $!! sda + (delta * (v - (unMeanAcc m'))) in MeanDevAcc m' s' i' {-# INLINE update' #-} {-# INLINE updateMeanDev #-} updateNumericState :: NumericState -> Double -> NumericState updateNumericState acc x = {-# SCC updateNumericState #-} (stateMinimum %~ (flip updateMinimum x)) . (stateMaximum %~ (flip updateMaximum x)) . (stateMeanDev %~ (flip updateMeanDev x)) $!! acc {-# INLINE updateNumericState #-} -- FIXME: this might commute error, requires further thought. combineMeanDevAcc :: MeanDevAcc -> MeanDevAcc -> MeanDevAcc combineMeanDevAcc MeanDevInitial MeanDevInitial = {-# SCC combineMeanDevAcc #-} MeanDevInitial combineMeanDevAcc MeanDevInitial md2 = {-# SCC combineMeanDevAcc #-} md2 combineMeanDevAcc md1 MeanDevInitial = {-# SCC combineMeanDevAcc #-} md1 combineMeanDevAcc (MeanDevAcc mu1 s1 c1) (MeanDevAcc mu2 s2 c2) = {-# SCC combineMeanDevAcc #-} let mu' = combineMeanAcc (mu1, c1) (mu2, c2) sda' = combineStdDevAcc mu' (mu1, s1, c1) (mu2, s2, c2) -- KAccs are off-by-one from the actual number of values seen, so -- subtract one from the sum to prevent it becoming off-by-two. c' = c1 + c2 - (KAcc 1) in MeanDevAcc mu' sda' c' {-# INLINE combineMeanDevAcc #-} -- | Combine stddev accumulators of two subsets by converting to variance -- (pretty cheap), combining the variances (less cheap), and converting back. -- -- There's almost certainly a better way to do this. combineStdDevAcc :: MeanAcc -- ^ Combined mean. -> (MeanAcc, MStdDevAcc, KAcc) -- ^ First subset. -> (MeanAcc, MStdDevAcc, KAcc) -- ^ Second subset. -> MStdDevAcc combineStdDevAcc _ (_, NoStdDevAcc, _) (_, NoStdDevAcc, _) = {-# SCC combineStdDevAcc #-} NoStdDevAcc combineStdDevAcc _ (_, MStdDevAcc (StdDevAcc s1), _) (_, NoStdDevAcc, _) = {-# SCC combineStdDevAcc #-} MStdDevAcc $ StdDevAcc s1 combineStdDevAcc _ (_, NoStdDevAcc, _) (_, MStdDevAcc (StdDevAcc s2), _) = {-# SCC combineStdDevAcc #-} MStdDevAcc $ StdDevAcc s2 combineStdDevAcc muHat (mu1, MStdDevAcc sda1, c1) (mu2, MStdDevAcc sda2, c2) = {-# SCC combineStdDevAcc #-} let var1 = varianceFromStdDevAcc c1 sda1 var2 = varianceFromStdDevAcc c2 sda2 in MStdDevAcc . stdDevAccFromVariance (c1 + c2 - (KAcc 1)) $ combineVariance muHat (mu1, var1, c1) (mu2, var2, c2) {-# INLINE combineStdDevAcc #-} -- | Combine variances of two subsets of a sample (that is, exact variance of -- datasets rather than estimate of variance of population). -- -- The derivation of this formula is in the Numerics section of the -- documentation. combineVariance :: MeanAcc -- ^ Combined mean. -> (MeanAcc, Variance, KAcc) -- ^ First subset. -> (MeanAcc, Variance, KAcc) -- ^ Second subset. -> Variance combineVariance (MeanAcc muHat) (MeanAcc mu1, Variance var1, KAcc c1) (MeanAcc mu2, Variance var2, KAcc c2) = {-# SCC combineVariance #-} let t1 = (c1' * var1) + (c1' * mu1 * mu1) t2 = (c2' * var2) + (c2' * mu2 * mu2) in Variance $ ((t1 + t2) * (1.0 / (c1' + c2'))) - (muHat * muHat) where c1' = fromIntegral $ c1 - 1 c2' = fromIntegral $ c2 - 1 {-# INLINE combineVariance #-} -- | Combine mean of two subsets, given subset means and size. combineMeanAcc :: (MeanAcc, KAcc) -> (MeanAcc, KAcc) -> MeanAcc combineMeanAcc (MeanAcc mu1, KAcc c1) (MeanAcc mu2, KAcc c2) = {-# SCC combineMeanAcc #-} let c1' = fromIntegral $ c1 - 1 c2' = fromIntegral $ c2 - 1 in MeanAcc $ ((mu1 * c1') + (mu2 * c2')) / (c1' + c2') {-# INLINE combineMeanAcc #-} -- FIXME: not associative combineNumericState :: NumericState -> NumericState -> NumericState combineNumericState ns1 ns2 = {-# SCC combineNumericState #-} (stateMinimum %~ (<> (ns1 ^. stateMinimum))) . (stateMaximum %~ (<> (ns1 ^. stateMaximum))) . (stateMeanDev %~ (combineMeanDevAcc (ns1 ^. stateMeanDev))) $!! ns2 {-# INLINE combineNumericState #-} combineFieldNumericState :: FieldNumericState -> FieldNumericState -> FieldNumericState combineFieldNumericState NoFieldNumericState NoFieldNumericState = {-# SCC combineFieldNumericState #-} NoFieldNumericState combineFieldNumericState NoFieldNumericState fns2 = {-# SCC combineFieldNumericState #-} fns2 combineFieldNumericState fns1 NoFieldNumericState = {-# SCC combineFieldNumericState #-} fns1 combineFieldNumericState (FieldNumericState ns1) (FieldNumericState ns2) = {-# SCC combineFieldNumericState #-} FieldNumericState $ V.zipWith combineNumericState ns1 ns2 {-# INLINE combineFieldNumericState #-} -- | Exact median of sample data. Unsafe, don't call this directly -- unless you know what you're doing. unsafeMedian :: VU.Vector Double -> Double unsafeMedian v = let n = VU.length v v' = VU.modify Intro.sort v in case n `mod` 2 of 0 -> let right = n `div` 2 left = right - 1 in ((v' ! left) + (v' ! right)) / 2 _ -> v' ! (n `div` 2) sampleMedian :: Sample -> Median sampleMedian NoSample = NoMedian sampleMedian (Sample v) = let n = VU.length v in if n < 2 then NoMedian else Median $ unsafeMedian v summarizeNumericState :: NumericState -> Sample -> NumericSummary summarizeNumericState st smpl = if st == initialNumericState -- We didn't see any numeric fields, so there's nothing to summarize. then NoNumericSummary else let (mn, stddev) = finalizeMeanDev $ st ^. stateMeanDev in NumericSummary (st ^. stateMinimum) (st ^. stateMaximum) mn stddev (sampleMedian smpl) smpl summarizeFieldNumericState :: FieldNumericState -> FieldReservoirAcc -> IO NumericFieldSummary summarizeFieldNumericState NoFieldNumericState _ = pure NoNumericFieldSummary summarizeFieldNumericState (FieldNumericState ss) NoFieldReservoirAcc = if V.null ss then pure NoNumericFieldSummary else pure . NumericFieldSummary $ V.zipWith summarizeNumericState ss (V.replicate (V.length ss) NoSample) summarizeFieldNumericState (FieldNumericState ss) (FieldReservoirAcc fra) = do samples <- V.mapM finalizeReservoirAcc fra if V.null ss then pure NoNumericFieldSummary else pure . NumericFieldSummary $ V.zipWith summarizeNumericState ss samples
/** * @brief Allocate an object clearing it. */ void *osPoolCAlloc(osPoolId pool_id) { void *object; object = chPoolAllocI((memory_pool_t *)pool_id); memset(object, 0, pool_id->object_size); return object; }
DETROIT — The United Automobile Workers union this year is renewing its effort to organize workers at plants that foreign automakers operate in the United States and will portray companies that resist as “human rights violators,” the union’s president said Wednesday. The president, Bob King, said the companies would be better off morally and financially if they allowed their workers to organize. The union, he said, has changed its philosophy and could help the companies become more competitive, not less. “We just have to convince them that we’re not the evil empire that they think we are,” Mr. King told reporters at an auto industry conference near the North American International Auto Show here. Last week, the U.A.W. released a list of 11 principles for “fair union elections” that it wants foreign-based manufacturers to adopt and said it had set aside $60 million from its strike fund to spend on organizing efforts within the plans of those companies. The principles are aimed at giving workers the chance to decide whether they want to unionize without intimidation, fear of repercussions from either side or misleading information. Advertisement Continue reading the main story Mr. King said Wednesday that union leaders were in preliminary talks with some of the companies it was focusing on, but he declined to identify them.
package clean_test import ( "errors" "strings" "testing" "github.com/spf13/afero" "github.com/staticdev/cleancontacts/clean" ) var ( Clean = clean.Clean{} FakeFS = afero.NewMemMapFs() ) func TestClean(t *testing.T) { testCases := []struct { name string contact string want string expectedErr error }{ { name: "happy-path", contact: `BEGIN:VCARD VERSION:3.0 FN:This Is A Full Name N:Name;This is A;Full;; item1.EMAIL;TYPE=INTERNET:<EMAIL> item1.X-ABLabel: TEL;TYPE=CELL:+40 547984080 item3.ADR:;;911 Omg Straat;;Hakooken - PR;;SW;911 Omg Straat\nHakooken - PR\nSW item3.X-ABLabel: NOTE:Some notes\n\nmore notes CATEGORIES:myContacts END:VCARD `, want: `BEGIN:VCARD VERSION:3.0 FN:This Is A Full Name N:Name;This is A;Full;; TEL:+40 547984080 END:VCARD `, }, { name: "skip-no-tel", contact: `BEGIN:VCARD VERSION:3.0 FN:This Is A Full Name N:Name;This is A;Full;; item1.EMAIL;TYPE=INTERNET:<EMAIL> item1.X-ABLabel: item3.ADR:;;911 Omg Straat;;Hakooken - PR;;SW;911 Omg Straat\nHakooken - PR\nSW item3.X-ABLabel: NOTE:Some notes\n\nmore notes CATEGORIES:myContacts END:VCARD `, want: ``, }, { name: "no-end-error", contact: `BEGIN:VCARD VERSION:3.0`, expectedErr: clean.CleanerError{Msg: "vcard: no END field found"}, }, } fileNameIn := "dirty-contacts.vcf" filePathOut := "./dirty-contact_cleaned.vcf" for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { afero.WriteFile(FakeFS, fileNameIn, []byte(tc.contact), 0o600) // nolint: errcheck err := Clean.ContactClean(FakeFS, fileNameIn, filePathOut) out, _ := afero.ReadFile(FakeFS, "dirty-contact_cleaned.vcf") outStr := strings.Replace(string(out), "\r\n", "\n", -1) if outStr != tc.want { t.Errorf("want (%q), got (%q)", tc.want, outStr) } if !errors.Is(err, tc.expectedErr) { t.Errorf("want (%v) got (%v)", tc.expectedErr, err) } }) } }
<reponame>jpwiddy/fsm-grid<filename>dist/fsm-grid.component.d.ts<gh_stars>0 import { OnChanges, OnInit } from '@angular/core'; export declare class FsmGridComponent implements OnInit, OnChanges { /** * Color of the header (in hex) * Values: * Default (blue) * Success (green) * Failure (red) */ headerClass: string; private appliedClass; private classOptions; constructor(); ngOnInit(): void; ngOnChanges(): void; private setheaderColor(); }
<filename>tests/components/directv/test_config_flow.py<gh_stars>1-10 """Test the DirecTV config flow.""" from typing import Any, Dict, Optional from asynctest import patch from requests.exceptions import RequestException from homeassistant.components.directv.const import DOMAIN from homeassistant.components.ssdp import ATTR_SSDP_LOCATION, ATTR_UPNP_SERIAL from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_SSDP, SOURCE_USER from homeassistant.const import CONF_HOST, CONF_NAME, CONF_SOURCE from homeassistant.data_entry_flow import ( RESULT_TYPE_ABORT, RESULT_TYPE_CREATE_ENTRY, RESULT_TYPE_FORM, ) from homeassistant.helpers.typing import HomeAssistantType from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry from tests.components.directv import ( HOST, RECEIVER_ID, SSDP_LOCATION, UPNP_SERIAL, MockDirectvClass, ) async def async_configure_flow( hass: HomeAssistantType, flow_id: str, user_input: Optional[Dict] = None ) -> Any: """Set up mock DirecTV integration flow.""" with patch( "homeassistant.components.directv.config_flow.DIRECTV", new=MockDirectvClass, ): return await hass.config_entries.flow.async_configure( flow_id=flow_id, user_input=user_input ) async def async_init_flow( hass: HomeAssistantType, handler: str = DOMAIN, context: Optional[Dict] = None, data: Any = None, ) -> Any: """Set up mock DirecTV integration flow.""" with patch( "homeassistant.components.directv.config_flow.DIRECTV", new=MockDirectvClass, ): return await hass.config_entries.flow.async_init( handler=handler, context=context, data=data ) async def test_duplicate_error(hass: HomeAssistantType) -> None: """Test that errors are shown when duplicates are added.""" MockConfigEntry( domain=DOMAIN, unique_id=RECEIVER_ID, data={CONF_HOST: HOST} ).add_to_hass(hass) result = await async_init_flow( hass, context={CONF_SOURCE: SOURCE_IMPORT}, data={CONF_HOST: HOST} ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "already_configured" result = await async_init_flow( hass, context={CONF_SOURCE: SOURCE_USER}, data={CONF_HOST: HOST} ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "already_configured" result = await async_init_flow( hass, context={CONF_SOURCE: SOURCE_SSDP}, data={ATTR_SSDP_LOCATION: SSDP_LOCATION, ATTR_UPNP_SERIAL: UPNP_SERIAL}, ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_form(hass: HomeAssistantType) -> None: """Test we get the form.""" await async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_USER} ) assert result["type"] == RESULT_TYPE_FORM assert result["errors"] == {} with patch( "homeassistant.components.directv.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.directv.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await async_configure_flow(hass, result["flow_id"], {CONF_HOST: HOST}) assert result["type"] == RESULT_TYPE_CREATE_ENTRY assert result["title"] == HOST assert result["data"] == {CONF_HOST: HOST} await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_form_cannot_connect(hass: HomeAssistantType) -> None: """Test we handle cannot connect error.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_USER} ) with patch( "tests.components.directv.test_config_flow.MockDirectvClass.get_version", side_effect=RequestException, ) as mock_validate_input: result = await async_configure_flow(hass, result["flow_id"], {CONF_HOST: HOST},) assert result["type"] == RESULT_TYPE_FORM assert result["errors"] == {"base": "cannot_connect"} await hass.async_block_till_done() assert len(mock_validate_input.mock_calls) == 1 async def test_form_unknown_error(hass: HomeAssistantType) -> None: """Test we handle unknown error.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_USER} ) with patch( "tests.components.directv.test_config_flow.MockDirectvClass.get_version", side_effect=Exception, ) as mock_validate_input: result = await async_configure_flow(hass, result["flow_id"], {CONF_HOST: HOST},) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "unknown" await hass.async_block_till_done() assert len(mock_validate_input.mock_calls) == 1 async def test_import(hass: HomeAssistantType) -> None: """Test the import step.""" with patch( "homeassistant.components.directv.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.directv.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await async_init_flow( hass, context={CONF_SOURCE: SOURCE_IMPORT}, data={CONF_HOST: HOST}, ) assert result["type"] == RESULT_TYPE_CREATE_ENTRY assert result["title"] == HOST assert result["data"] == {CONF_HOST: HOST} await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_ssdp_discovery(hass: HomeAssistantType) -> None: """Test the ssdp discovery step.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_SSDP}, data={ATTR_SSDP_LOCATION: SSDP_LOCATION, ATTR_UPNP_SERIAL: UPNP_SERIAL}, ) assert result["type"] == RESULT_TYPE_FORM assert result["step_id"] == "ssdp_confirm" assert result["description_placeholders"] == {CONF_NAME: HOST} with patch( "homeassistant.components.directv.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.directv.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await async_configure_flow(hass, result["flow_id"], {}) assert result["type"] == RESULT_TYPE_CREATE_ENTRY assert result["title"] == HOST assert result["data"] == {CONF_HOST: HOST} await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_ssdp_discovery_confirm_abort(hass: HomeAssistantType) -> None: """Test we handle SSDP confirm cannot connect error.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_SSDP}, data={ATTR_SSDP_LOCATION: SSDP_LOCATION, ATTR_UPNP_SERIAL: UPNP_SERIAL}, ) with patch( "tests.components.directv.test_config_flow.MockDirectvClass.get_version", side_effect=RequestException, ) as mock_validate_input: result = await async_configure_flow(hass, result["flow_id"], {}) assert result["type"] == RESULT_TYPE_ABORT await hass.async_block_till_done() assert len(mock_validate_input.mock_calls) == 1 async def test_ssdp_discovery_confirm_unknown_error(hass: HomeAssistantType) -> None: """Test we handle SSDP confirm unknown error.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_SSDP}, data={ATTR_SSDP_LOCATION: SSDP_LOCATION, ATTR_UPNP_SERIAL: UPNP_SERIAL}, ) with patch( "tests.components.directv.test_config_flow.MockDirectvClass.get_version", side_effect=Exception, ) as mock_validate_input: result = await async_configure_flow(hass, result["flow_id"], {}) assert result["type"] == RESULT_TYPE_ABORT await hass.async_block_till_done() assert len(mock_validate_input.mock_calls) == 1
#include <iostream> #include <sstream> using namespace std; int toNum(char a) { stringstream alfa; alfa<<a; int ret; alfa>>ret; return ret; } void print(int arr[]) { for(int j=0;j<4;j++) { cout<<arr[j]; } } int main() { int y; cin>>y; while(1) { y++; bool yes=0; int a[4]; int t=1; for(int b=3;b>-1;b--) { a[b]=(y%(t*10)-y%t)/t; t*=10; } for(int l=0;l<4;l++) { for(int m=0;m<4;m++) { if(a[l]==a[m]&&(l!=m)) yes=1; } } if(yes==0) { print(a); return 0; } } }
Gold nanocrystals: optical properties, fine-tuning of the shape, and biomedical applications Noble metal nanomaterials with special physical and chemical properties have attracted considerable attention in the past decades. In particular, Au nanocrystals (NCs), which possess high chemical inertness and unique surface plasmon resonance (SPR), have attracted extensive research interest. In this study, we review the properties and preparation of Au NCs with different morphologies as well as their important applications in biological detection. The preparation of Au NCs with different shapes by many methods such as seed-mediated growth method, seedless synthesis, polyol process, ultrasonic method, and hydrothermal treatment has already been introduced. In the seed-mediated growth method, the influence factors in determining the final shape of Au NCs are discussed. Au NCs, which show significant size-dependent color differences are proposed for preparing biological probes to detect biomacromolecules such as DNA and protein, while probe conjugate molecules serves as unique coupling agents with a target. Particularly, Au nanorods (NRs) have some unique advantages in the application of biological probes and photothermal cancer therapy compared to Au nanoparticles (NPs). Introduction Nobel metal nanoparticles (NPs) are widely applied in numerous elds. Among various noble metal nanomaterials, Au nanomaterials, which possess high chemical inertness and unique surface plasmon resonance (SPR) have gained extensive interest and research. Au nanocrystals (NCs) are studied comparatively early and have attracted increasing attention in medical and biological research because of their special physical and chemical properties and bio-affinity. 4 It has been proven that Au NCs can be prepared via a simple preparation procedure with good control over particle size, stable chemical properties, good biocompatibility, as well as easy to modify with biomolecules. Therefore, Au NCs have been proposed for applications in genomics, 5 biosensors, 6-8 clinical chemistry, 9 cancer cell photothermal therapy, optical imaging techniques, 15,16 targeted delivery of drugs, antigens, peptides, DNA, and so on. The interesting optical properties of Au NCs result from the excitation of free electron plasmons by the electromagnetic eld. 1, The plasmon modes of Au NCs are determined by shape, composition, size, and surrounding media. The resonance frequency is very sensitive to the shape of the NCs. In particular, Au nanorods (NRs) are promising systems for optical studies, as the spectrum is easily tunable by varying the aspect ratio. 2,23,24 As such, it is crucial to have tight control over the size and crystal structure of Au NCs. As a face-centered cubic (fcc) metal, Au NCs with different shapes have been synthesized successively. In realistic chemical synthesis, many critical parameters including thermodynamic and kinetic parameters are responsible for the nal shapes of Au NCs. Shape control synthesis provides one of the most powerful means to tailor the properties of Au NCs. 34,35 Due to extensive research and the importance of Au NCs, various reviews related to the preparation and applications of Au NCs have been published over the years. Most of them provided a specic introduction to various aspects of Au NCs, such as photosynthesis, modication, functionalization, toxicity of Au NCs, as well as the application of Au NCs in therapeutic applications, targeted drug delivery, and energy or environment. 43,44 A few publications are providing a generalized introduction to the synthesis, properties, and applications of Au NCs. 4,44,45 In particular, there is still a lack of detailed understanding of the synthesis mechanism or the precise controlling of the reaction parameters, which may prevent us from realizing the full potential of synthetic approaches and accurately controlling the growth of Au NCs. The specic physicochemical and optoelectrical characteristics of Au NCs are closely related to their size and morphology, which can be controlled by the selection of a synthetic approach. 38,46,47 The understanding of the reaction process and mechanism is promising to choose the appropriate synthesis route and reaction parameters such as time, temperature, and pH according to the required characteristics. Due to the frequently reported publications on Au NCs, this review may be incomplete and should be regarded as the starting point for understanding the basic principles behind the synthesis, properties, and biomedical applications of Au NCs. In this review, the properties and preparation of Au NCs with different morphologies as well as their important applications in biological detection are summarized. The preparation of Au NCs with different shapes by many methods such as seed-mediated growth method, seedless synthesis, the polyol process, ultrasonic method, and hydrothermal treatment is introduced. For the widely reported seedmediated growth method, the inuencing factors in determining the nal shape of Au NCs were studied. Some of the advantages and disadvantages of chemical synthesis methods are discussed, as well as the green synthesis methods are highlighted. The main objective of the present work is to provide a better basis for the synthesis, properties, and biomedical applications of Au NCs, which is benecial for the further development of Au NCs. Properties of Au NCs Seo et al. reported that surface energy has a strong inuence on the physical and chemical properties of the materials and there was a signicant negative correlation between the ratio of surface atoms versus total volume and surface energy. 25 It must be mentioned that bulk Au has distinct yellowish color, and the size dependence of the color of colloidal Au is simply the consequence of how light interacts with matter. NCs, typically in the size range of 1-100 nm, possess size and shapedependent properties, which differ from their bulk behavior. The color of the colloidal dispersions of Au NCs in a uid, typically water, varies from red to blue, depending upon the shape and size of the particles. For example, spherical colloidal Au NCs with a diameter of around 10 nm produce aqueous dispersions with a ruby red color, while increasing their size to nearly 100 nm or changing the morphology to rod-like (length 30 nm, diameter 10 nm) results in making the colloidal University. He has long been engaging in scientic research and engineering practice in the elds of environment pollution control and prevention, environment ecological planning and restoration, and has organized or presided over more than 100 major engineering in more than 20 countries. dispersion appear bluish. 48 Fig. 1(a) shows the photograph of Au NPs with sizes 3, 4, 6, 9, and 35 nm (from le to right). 49 The research interest in Au NCs over the past decades has been stemming from their remarkable optical properties related to SPR. SPR comes from the excitation of free electron plasmon by the electromagnetic eld. 1-3 When light impinges on Au NCs, free electrons of Au NCs interact with the incident light and produce resonance coupling. The oscillation leads to the charge separation between free electrons and the metal core, producing a coulomb force, such that the electrons oscillate around the surface of the particles. 50 Fig. 1(b) illustrates the localized surface plasmon. 50 SPR is produced when the vibration frequency of the incident light and free electrons are equal. SPR causes a strong absorption peak in UV-vis absorption spectroscopy. Optical absorption peaks of Au NCs appeared in the wavelength range of 510-550 nm, and the resonance frequency is very sensitive to the shape of NPs. Synthesis of Au NPs Au NCs, as a face-centered cubic (fcc) metal, are known to have enclosed by low-index {100}, {111}, and {110} facets. The relative surface energies are in the order of g{111} < g{100} < g{110}. 25 This phenomenon results from the rapid elimination of the high-index facets with the addition of atoms during the Au NC formation process. 26 The rate of crystal growth in the direction perpendicular to a high-index facet is generally much faster than that along the normal direction of a low-index facet, which results in the rapid elimination of the high-index facets with the addition of atoms during the formation of NCs. 26,51 As a result, in solution chemistry, fcc metal NCs enclosed by low-index {100}, {111} and {110} facets are more commonly observed because of their relatively low surface energy. 52 The physical and chemical properties were controlled by the shape of Au NCs. 25,27 Xia et al. mentioned that Au NCs, which possess high-index facets on their surface, such as trisoctahedral and concave cubic, showed better electro-catalytic activity in comparison to that possessing only low-index facets. 53 This phenomenon can be explained by the reason that the high-index facets of a single crystal possess a high density of lowcoordinated atoms such as steps, edges, and kinks, which can be served as highly active sites for adsorption and even catalysis. 27,54,55 As a symmetric fcc structure, it is not easy for Au to form single-crystal multi-armed NCs in isotropic aqueous solutions. Nevertheless, Chen et al. provided a systematic introduction to the preparation methods of monopod, bipod, tripod, and tetrapod Au NCs. 71 To date, Au NCs with different shapes as spheres, 28-30 rods, 73 cubes, 29,74 triangle, 53 polyhedron 25,59 and others 34,75 have been synthesized successively. Such as those in the TEM or SEM images of Au NCs with different morphologies shown in Fig. 2. The most typical method for preparing colloidal gold is the sodium citrate reduction method. Colloidal gold of different sizes can be prepared by changing the type and concentration of the reducing agent. 83 In general, parameters are responsible for the nal shapes of noble metal NCs. The synthetic method, reagents used in the growth process, the temperature of synthesis, reaction time, dimensions, and yield of Au NCs with different shapes are illustrated in Table 1. In solution-based chemical synthesis, thermodynamic and kinetic parameters controlled the growth of NCs. 26,84 Thermodynamic parameters include temperature and reduction potential, while kinetic parameters include reactant concentration, diffusion, solubility, and the reaction rate. By controlling these parameters, it is possible to tune the nucleation and growth stages of NCs and achieve crystallographic control. The seed-mediated growth method is the widely reported method in conventional chemical synthesis. 85,86 Since its inception and application, the seed-mediated growth method has made a revolutionary impact on the majority of the reported synthesis of shape-controlled Au NCs. It is typical that the seedmediated growth process comprises the preparation of small Au NCs and subsequent growth in reaction solutions. 87,88 Both, the crystallinity of seeds and the growth rates of different crystallographic facets play a vital role in determining the nal shape of the resultant nanostructure. 89 The shape of Au NCs could be controlled by tuning nucleation and growth stages in the seed-mediated growth method. 26,90,91 In the solution-phase synthesis of NCs, "nucleation" can be broadly dened as the formation of a small cluster from atoms in the solution. Small Au seed particles are generated under conditions of high chemical supersaturation. This leads to the fastest nucleation rate. Once the nuclei have grown past a critical size, they will have relatively stable crystallinity and well-dened crystallographic facets exposed on their surface, which can be termed "seeds". The shape of a seed is primarily determined by the minimization of the surface energy. 85 Aer the nucleation stage, each type of seed can still grow into an NC with several possible shapes. The reaction conditions are then altered and more Au ions and the reductant are added, together with some form of a shape-templating surfactant or molecule, and the seeds are grown into larger particles of particular morphologies or habits. The nal shape is controlled by the growth rates of different facets. 89 As the seed grows into a nanocrystal, the growth rates of different facets can be altered with capping agents to control the nal shape. Typically, the growth stage is much slower and proceeds under milder reducing conditions than those at the nucleation stage. 92 The shaping of these nanostructures can be analyzed by the deposition of metal atoms on the seed surface under reductive environments. 25 Grzelczak et al. proclaimed that in comparison to the nucleation stage, the growth stage was under a milder reducing process and the reaction rate was much slower. 92,93 Some chemical stabilizers such as poly(vinyl pyrrolidone) (PVP), poly(vinyl alcohol), and sodium dodecyl sulfate are added to reaction mixtures to control the growth of Au NCs. Polyhedral Au NCs with decahedral, icosahedral, and truncated tetrahedral shapes are synthesized by a simple one-pot polyol process in the presence of PVP. 97,98 A high PVP concentration of up to 360 equivalent of the Au precursor, HAuCl 4 , effectively stabilizes decahedral seeds to yield uniform decahedra with various edge sizes. Decreased PVP concentration subsequently leads to selective formation of icosahedral and truncated tetrahedral. 25,99 At relatively low PVP concentration, the internal surface energy of the crystals becomes more important than the interaction energy between surface atoms and PVP, and the particles prefer more rounded shapes to reduce the total surface area. The icosahedral structure is close to spherical and has stable {111} facets on the surface. The edge truncation of the icosahedron helps to diminish its structural strain energy. 25 Typical reducing agents such as citric acid, borohydride, tetrauoroborate, AA are used during the preparation of Au NCs. 94,100,101 AA is a commonly used reducing agent during the preparation of Au NCs. However, it has been reported that Au NCs can be obtained in large quantities by the aspartate reduction of Au ions. Suri et al. put forward amines as an attractive class of reducing agents because of their universal presence in biology and the environment. 102 Dong et al. described that amino acids can control the size and morphology of the Au NCs. They mentioned that amino acid moieties could form an organic matrix to have an inuence on the biomolecules and inorganic materials. 103 Conventional synthesis techniques involving the seedmediated growth method, seedless method, polyol process, hydrothermal method, and ultrasonic method have been developed for the synthesis of Au NCs with different sizes and shapes. Chemical methods can generate Au NCs at a low cost and provide repeatable results using various chemicals. Although the chemical synthesis methods described above are effective, many of them suffer from some drawbacks such as high temperature, harsh reaction conditions, long reaction times, the use of toxic and aggressive chemicals as reducing and/or capping agents to control the size and composition of Au NCs, resulting in the environmental pollution caused by the use of organic solvents. Besides, the toxic capping agents or chemicals used in the synthesis process tend to adsorb on the surface of Au NCs, which may cause severe threats to living cells while using Au NCs for drug delivery and diagnostic applications. Consideration of the environmental problems, Firdhouse et al. summarized the detailed advantages and disadvantages of conventional synthesis techniques for Au NPs synthesis. 113 In view of the environmental impact, eco-friendly green synthesis methods have currently become popular. Current strategies of ''green'' concern include the use of nontoxic chemicals, biodegradable polymers, and environmentally benign solvents. 121 In the green synthesis methods, the extracts from living organisms such as leaves, stems, roots, seeds, owers, fruit, whole plant, fungi, and algae are available as reducing and capping agents. 121,122 The synthesis of Au NCs via green routes has the advantages of simplicity, economical friendliness, low cost, moderate reaction conditions, and application of non-toxic chemicals. 114,123,124 This technique provides a wide range of applications for functional nanomaterials because ascorbic acid, terpenes, alkaloids, phenols, polyphenols, and avonoids are coated on the surface of NCs, resulting in Au NCs with lower toxicity than chemically synthesized counterparts. Not only that, Au NCs showed enhanced solubility and stability due to coating with biomolecules. 125 Nevertheless, the green synthesis methods are possibly related to some major operational obstacles, such as the need for a longer time, critical downstream processing to purify nanoparticles in high yields, and difficulty to optimize the process parameters and expand the scale. 126,127 Synthesis of Au NRs One-dimensional Au nanostructures have received considerable attention due to their size-dependent optical, catalytic, and electronic properties. 128,129 The research interest in Au NRs over the past decades has stemmed from their anisotropic conguration and unique optical properties. Since its inception and commercialization, Au NRs have made a revolutionary impact in the eld of bioanalysis and have become a powerful tool for bioanalytical chemistry. Shape control provides one of the most powerful tools to tailor the properties of noble metal nanostructures. In Fig. 4(a), L/D is the aspect ratio. Fig. 4(b) is the photograph of the colloidal solution of Au NRs. The color of the colloidal solution is related to the aspect ratios of Au NRs. There are distinct differences between the spherical Au NPs and Au NRs. The distinct difference from spherical NPs is that Au NRs possess two distinct surface plasmon resonances; a transverse SPR corresponding to the short axis of the rod, and a longitudinal SPR corresponding to the long axis ( Fig. 4(c)). The energy of the longitudinal SPR can be tuned from the middle of the visible region of the electromagnetic spectrum ($600 nm) to the infrared region ($1800 nm), simply by changing the aspect ratio of the Au NRs. 23,24 Au NRs have been prepared by conventional wet chemistry, photochemical and electrochemical methods. 130 Among the reported procedures, the seed-mediated growth has been by far the most efficient and popular approach. Au NRs are prepared by a seed-mediated growth approach, which uses $4 nm Au nanoclusters as seeds and subsequent reduction of a metal salt with a weak reducing agent in the presence of a directing surfactant to produce NRs. 128 Besides the seedmediated growth method, seedless synthesis is the other typical synthetic method to prepare Au NRs. The difference between the seed-mediated growth method and seedless synthesis is that the sizes of in situ seeds grown using NaBH 4 are about 1.5 nm, while the sizes of the seeds used in the seedmediated growth method are about 3.5 nm. The seedless method with a size of about 1.5 nm is in favor of the synthesis of anisotropic Au NCs. 1,131 The dimension of Au NRs prepared by the seedless synthesis method is about 25 Â 6 nm, while about 60 Â 15 nm by the seed-mediated growth method. 132 The size of Au NRs produced by seedless synthesis is much smaller than that prepared by the seed-mediated growth method. The seed-mediated growth method is discussed in detail in the following part. The seed-mediated growth method is a typical growth process that involves the preparation of Au NRs. Many factors affect the growth of Au NRs, such as the concentration of reagents, the pH of the growth solution, and the type of the directing surfactant. Table 2 lists the inuencing factors on the growth of Au NRs. In the solution-phase synthesis, impurities or capping agents can change the order of free energies of different facets through their interaction with a metal surface. As a result, the facet with a slower growth rate will be exposed more on the surface. 89 4.1 There are many factors affecting the growth of Au NRs 4.1.1 Directing surfactant. A surfactant such as CTAB plays a crucial role in the growth process of Au NRs. It seems that the growth of an NR takes place simultaneously in all directions. Once the seed grows to a critical size, the facets become large enough for signicant surfactant binding. The growth rate of different facets in the presence of the surfactant determines the nal shape of the nanoparticle. The slower growth in the width of the NR is an example of better protection of {110} facets by CTAB. The growth and the nal size of Au NRs depend on the Au supply and the surfactant concentration. In general, the surfactant is much higher in concentration; this process continues until the Au supply depletes. 23 The original idea was to use micelles formed by the cationic surfactant CTAB as a "so template" to direct NR formation. 20 Previous studies suggested that CTAB formed a bilayer on the surface of NR. 136,137 Compared to the ends, the assembly of CTAB bilayers along the long faces of Au NRs is preferred. Besides, CTAB assists in the ne-tuning of the shape because CTAB preferentially binds to the middle of the NRs. This property makes it possible to form Au NRs with a dog-bone shape. 128 It has been demonstrated that decreasing the concentration of CTAB yielded the NRs with shorter aspect ratios (1 to 6). 142 On the contrary, employing a surfactant with a longer aliphatic surfactant and smaller seed solution obtained longer NRs. 142 In 2005, citrate-capped Au NPs were chosen as seeds for Au NRs growth. 1 Then, Liu and Guyot-Sionnest observed differences between the crystalline structures of citrate and CTAB-stabilized seeds, conrming the multiply-twinned structure of citratecapped seeds. 1 A careful choice of the experimental conditions allows the growth of the seeds into NRs. Factors including temperature, 20 pH, 144,146,149,150 4.1.2 Seed. The amount added and the size of the seed impact the aspect ratio of Au NRs. The aspect ratio of Au NRs could be precisely controlled through the careful variation of the added amount of the seed into the growth solution. For a constant concentration of reagents, increasing the size of the seed decreased the aspect ratio of Au NRs. 131 4.1.3 Reducing agent. AA as a mild reducing agent has been widely used in the seed-mediated growth method. Vivek Sharma et al. 20 introduced that the reduction process of the Au ion by AA that can be described as: First reduction: Au 3+ / Au + CTA-AuBr 4 + C 6 H 8 O 6 / CTA-AuBr 2+ C 6 H 6 O 6 + 2H + + 2Br À Second reduction: The rst reduction is conned to the metal micelles. The second reduction starts only aer the addition of the seed solution. The study on the effect of the concentration of AA on the growth of Au NRs indicated that the reaction rate becomes faster with the increasing in the concentration of the reducing agent. The decrease in the reaction rate was in favor of the isotropic growth, thereby increasing the yield of NRs. The reduction rate affects the morphology of NRs. For example, an insufficient amount of AA yielded fatter Au NRs. 20 4.1.4 Temperature and pH. Apart from the reducing agent, both the temperature and pH are also able to change the morphology of Au NRs by controlling the reduction rate. The former report demonstrated that the aspect ratio of Au NRs increased with the decrease in the temperature. 20 It is worth noting that the increase in the aspect ratio is due to a decrease in the diameter of NRs. The decrease in the diameter resulted from the effective connement of the growth in the short axis at low temperature. 20 The pH value affects the reduction rate and reduces the power of the reducing agent. AA has a much weaker reducing power in a strongly acidic solution than in a weakly acidic solution. 87,143 Adding a small amount of the HCl solution to the growth solution could decrease the whole reduction rate and increase the aspect ratio. 153,154 The feasible formation of Au nanoprisms with an addition of a small amount of NaOH has been observed in a previous report by Mirkin et al. 155 This is because the reducing power of AA can be enhanced by eliminating the proton produced by the reduction. 145 Therefore, the formation of nanoprisms can be promoted at higher pH values. In other words, the chemical potential of AA is maintained at a higher state aer the addition of NaOH. 142 4.1.5 Au and Ag ions. Increasing the aspect ratio of Au NR with the increase in the Au atom content of the growth solution indicates that the higher the concentration of the Au former the longer the NRs. However, a further increase in the concentration of the Au ions caused the decrease in the length of the NRs because of the formation of Au-Br-surfactant. 23 The effect of the silver ion content does not always increase the aspect ratio of Au NRs. The negative effects of higher concentrations of silver ions may be due to their interaction with the bromide-resistant ions of the surfactant monomer. 23 Babak et al. explored the role of silver in the growth process of Au NRs and reported that Ag + could rst increase and then decrease the length of Au NRs, similar to the effect of Au ions. 23 Liu and Guyot-Sionnest proposed an elaborate explanation for the role of Ag + . 1 They suggested that the under-potential deposition (UPD) of metallic silver occurs on different crystal facets of Au NCs, leading to symmetry breaking and rod formation. UPD is an important process that occurs during the formation of metallic layers on metallic substrates. 156 It is widely observed that when a metal working electrode is slowly cathodically polarized, a second noble metal ion can be deposited on the substrate to form a thin lm. 157 Crucially, the initial deposition of metal monolayers with potentials much higher than the Nernst potential of the deposited metal is oen observed. This deposition of the rst and sometimes the second monolayer is called UPD. Ag + UPD does occur on Au {111} and the UPD process is inuenced by the presence of chloride ions. 92 In the presence of Cl À , the UPD offset becomes stronger. The above mechanism does not work in the growth of Au NRs using surfactant templates because the added silver ions are not reduced to atomic silver. Both silver ions and Au ions were contained in the growth solution, and AA as a reducing agent can only reduce the Au ions. Only under a basic pH, AA has the ability to reduce silver ions. 140 The deposition of silver on the surface of Au NRs only happens at pH $ 8 in the CTAB solution, with AA as the reducing agent. 158 Jana et al. reported that the preparation of Au NRs in the absence of silver ions can only obtain Au NPs. 139 This result conrmed that Ag + adsorbed on the surface of Au NPs in the form of AgBr restricts the growth and stabilizes the NR surface. The question that remains unresolved is why the addition of AgNO 3 during the growth of Au NRs leads to an increase in the yield and greatly improves the control of the aspect ratio of Au NRs. If the silver ion has catalytic activity and promotes the formation of NRs, the length should not be improved and only the number of NRs would increase. In fact, Ag + could combine with the headgroups of the capping material such as CTAB to form Ag-Br pairs. Ag + as a complexing agent between the monomers assists the template elongation. 141 Ag-Br pairs, which are formed between AgNO 3 and CTAB adsorbed in the facets of Au NPs cause restriction, limiting their growth, and obtaining Au NRs. 23 This combination decreases the charge density on the bromine ion, resulting in less repulsion between adjacent head groups on the gold surface. The repulsion between the neighboring headgroups results in CTAB template elongation. 4.1.6 Halide ions. Halide ions inuence the growth of Au NPs during the seed-mediated growth using CTAB as a cationic surfactant. The presence of distinct halide ions and their molar ratios resulted in the formation of diverse morphologies, such as spheroid, nanoplates, or NRs. 159 The dramatic change of the morphology is related to the adsorption of halide on different surfaces. 160 Chung et al. showed that a small amount of iodide ion resulted in the triangular nanoprisms in the presence of excessive bromide ion, in its absence, NRs were the main products. 142 The main effect of iodide ions is to decrease the overall rate of crystal growth, and iodide adsorption appears to inhibit crystal growth along the Au (111) direction, resulting in triangular nanoprisms. 142 In addition, a minuscule amount of iodide ion is crucial for the formation of a triangular disk instead of NRs. All halide ions are specically adsorbed on lowindex Au surfaces such as (111), (110), and (100). 142 Robert et al. demonstrated that Cl ions are important for shape controlling of Ag NPs. 161 4.1.7 Binary surfactant mixture. Using a binary surfactant mixture consisting of CTAB and benzyldimethylhexadecylammonium chloride (BDAC) in a seed-mediated method resulted in Au NRs with good uniformity, higher yield, and fewer by-products. 23,162,163 However, this effect was not observed in pure BDAC or large ratios of BDAC/CTAB mixture. 164 The growth solution only containing BDAC caused the formation of the nanosphere. This indicates that the CTAB monomer is necessary for the growth of NRs, and these monomers are more affected by silver ions. 23 This could be attributed to the smaller size and polarizability of chloride ions than bromine ions. Therefore, compared with Ag-Br, the bond in Ag-Cl is expected to be weak. As the contribution of BDAC increases, the average width of NR decreases. Biomedical applications Metal and semiconductor NCs show different characteristics, which are usually different from their corresponding bulk materials. NCs with a high surface area can enter cells and interact with intracellular substances. In recent years, metal and semiconductor NCs with new or improved optical, electrical and magnetic properties have attracted wide interest in basic research and biomedical applications. Semiconductor NPs consist of a few atoms up to several thousand atoms. The electronic energy level will be quantized when its size is small enough (typically less than 10 nm), in this case, they are also named quantum dots (QDs). 169 Yang et al. mentioned that QDs possess high photoluminescence efficiency and have unique applications in biological and light-emitting devices. 170 QDs have attracted signicant interest due to their small size and high uorescence quantum yield. 171 However, possible applications in biomedical elds are limited by their toxicity. Compared to toxic QDs, Au NCs have good biological applications in single cell research due to their good stability, cell permeability, and easy coupling with biological macromolecules. Besides, the diameter of Au NCs is in the range of 1-100 nm, and most biological molecules (such as proteins and nucleic acids) are in this size range. 167 Milkin et al. mentioned that nanomaterials are attractive probe candidates because of the following four reasons. First, they have a small size (1-100 nm) and a large specic surface area. Second, physical and chemical properties can be adjusted by controlling the size, composition, and shape of NCs. Then, they unusually target binding properties. Finally, they have overall structural robustness. 176 Based on the above properties, Au NCs can be used as probes to detect the physiological functions of biological molecules and reveal the life process at the molecular level. The typically biomedical applications of Au NCs in sensing, imaging, therapy, and immunology are presented in Fig. 5. Biomedical applications of Au NPs The electronic energy levels of Au NPs are split owing to their small size. The distance between the energy levels is related to the size of NPs. Specic wavelength light absorption occurs when the electron transition from a low band gap to a high band gap, resulting in the solution presenting different colors. 177 The color of colloidal Au is related to the size of Au NPs. 178,179 The color changes from pale orange-yellow, wine red, deep red, blue, and purple with the increase in the particle size. Its unique color change is the basis of biochemical applications. 177,180 The properties of colloidal Au mainly depend on the diameter and surface characteristics of Au NPs. They have controllable surface chemical properties for modication with various chemical and biologically active molecules. 181 It has been reported that the affinity of Au NPs with various sizes and shapes to thiols, disuldes, dithiocarbamates, and amines allows bioconjugation with many kinds of biological molecules. 182 The above characteristics provide the possibility for the detection of specic DNA and proteins. 183 Due to the good biocompatibility of Au, colloidal Au can be used for biological labels and the determination of protein concentration. The SPR of Au NPs is extremely sensitive to the environment, size and shape. 181,182 The aggregation degree, particle size range, and morphology of Au NPs can be determined by UV-visible absorption spectroscopy. The characteristic absorption peaks of Au NPs appeared at 510-550 nm. Under normal conditions, the surface of Au NPs is negatively charged, and the electrostatic repulsion between particles is greater than the van der Waals force. Therefore, a certain distance between the particles is maintained and the solution remains stable. When the external conditions change, such as lowering the temperature or adding the electrolyte solution, it would lead to aggregation between particles, resulting in the SPR absorption peak red shi. 180 For example, the color of colloidal Au changes, and the absorption spectrum red-shis while Au NPs are absorbed by biomacromolecules and the distances between the particles are smaller than their diameters. 16,48 These are the principles for the detection of DNA and proteins. 16 With the discovery of immune Au labelling, Au NPs began to be used in biomedical applications in the 1970s. 184 All the nano gold probes mentioned here were based on citrate-stabilized anionic Au NPs. Since the 1980s, Au NPs, which are connected with biomacro-molecules, have been used for various analytical methods. 16 In 1980, the sol particle immunoassay was proposed by Leuvering et al. 185 In 1996, Mirkin et al. proposed to use the assembled Au NPs with thiol-modied oligonucleotides as biological probes to detect DNA. Subsequently, a large number of reports using colorimetric assay methods to detect DNA, antigen and biological molecules, using Au nanoprobes decorated with oligonucleotides, antibodies, peptides have appeared. The colorimetric assay method has become an attractive choice for biological detection because it does not require the use of advanced equipment and is easy to operate in many applications. When particles aggregate to a certain extent, the color of the solution changes dramatically. Plasmon resonance absorption peak red-shis when the target molecule hybridizes with functional groups to cause the colorimetric response, indicating the presence of the target molecule. 16,186 Colorimetric methods have high selectivity and sensitivity for particle size, shape, and structure. 15,176 In the colorimetric assay method, the surface of Au NPs was functionalized. Glomm W. R. and Khlebtsov et al. referred to "functionalization" as dened as biomacromolecules attached to the surface of Au NPs. 189,190 Physical adsorption and coordination bond coupling are the two main methods to combine Au NPs with biological macromolecules, such as single-stranded oligonucleotides, antibodies, peptides, and carbohydrates. 16,184,186,191 Au NPs are used as optical markers, as well as probe-conjugated molecules for coupling with the target. Functionalization is the basis of biological applications. 16 In general, Au NPs were decorated with intermediate linkers so that they could be functionalized. The most commonly used intermediate linkers are thiol or thiolated derivatives, which are connected by the Au-S bond. In addition to alkylthiols, other ligands such as phosphine, amino, and carboxyl groups can also be used as linkers. 192,193 Genetic testing contains two contents including gene sequence identication and point mutation determination. Gene sequence identication may be used for genetic diagnosis. Point mutation determination is of great importance in the diagnosis of genetic diseases and drug resistance. 194 There are two strategies for detecting DNA using the colorimetric method: one is based on the conjugation of 10-30 nm Au NPs with thiol-modied single-stranded oligonucleotides (ssDNA), and the other uses the unmodied Au NPs as Au nanoprobes. 186, The main process of preparing Au NPs for DNA detection is as follows: rst, a thiol-modied oligonucleotide is synthesized. Then, oligonucleotides are added to the Au solution to form a solid connection with the surface of Au NPs through an Au-S covalent bond. Finally, buffer solution with an appropriate concentration should be added. Aer centrifugation, the nanogold probe is obtained. 182,195 The complex process is timeconsuming. It is unstable in the presence of a buffer solution because of the aggregating effect of salt ions, but Au NPs are readily stabilized by functionalization. 182 Rothberg et al. designed a gene detection method without the surface modication of Au NPs. 196,199 Colloidal Au remains stable due to electrostatic repulsion between particles. When a small amount of electrolyte solution, such as NaCl solution, is added, the electrostatic repulsion between nanoparticles is shielded by the electrolyte solution, resulting in particle aggregation and color change. There are some different propensities between ssDNA and double-stranded oligonucleotides (dsDNA). Due to van der Waals force, ssDNA can be adsorbed on the surface of Au NPs and remain stable at relatively high electrolyte concentrations. However, dsDNA presents a negatively charged phosphate skeleton, so dsDNA does not adsorb on the surface of negatively charged Au NPs. 200 Therefore, aer adding ssDNA or dsDNA and a certain concentration of salt solution to nano-gold solution, the color of adding ssDNA remained red, while the color changed from red to blue in the presence of dsDNA. 196,201 In addition, nano gold probes can be used to detect the mismatch of base pairs. 180,202 Taton et al. created a solid-phase detection mode based on the gold nanoprobe to identify target genes. 203 In colorimetric analysis, the solution color changed from red to blue when the growth solution contained the target gene. Aer the formation of the three-dimensional network structure, the system temperature gradually increased. When the temperature increases to a certain extent, the mismatched base pairs degenerated. As a result, the distance between particles returned to the distance before aggregation, and the color of the solution gradually returned to red. On the contrary, the completely complementary ssDNA remained stable, and the solution color did not change at this temperature. Therefore, this method can be used to detect point mutation. Nanogold probes can be used for the detection of proteins. 204,205 Au NPs were easily decorated using thiolate chemistry and their optical properties depend on the size. 206 Citrate-protected Au NPs, which are conjugated with proteins such as antibodies are used in biomolecular detection. 207 However, in a salt environment, citrate-protected Au NPs tend to aggregate. It is surprising that they are not easy to aggregate aer being connected with the protein layer. This method can be used to conrm the successful connection between Au NPs and proteins. 208 Au NPs have strong adsorption with proteins and other biological macromolecules. As a consequence, there is a good prospect in the immune analysis. Biomedical applications of Au NRs In addition to Au NPs, Au NRs also have been used in biological elds due to their strong light scattering efficiency, stable optical characteristics and are easy to process, and they are a good molecular probe because of the polarized light. Because of their anisotropic conguration and unique optical properties, Au NRs have great potential in chemical and biochemical sensing such as for metal ions, amino acids, antibodies, cancer cell imaging, and photothermal therapy. 130,166,195, In addition, Au NRs have the advantages of strong optical signals, high photostability and can be easily synthesized and engineered so that they can be used as single-molecule optical probes. More importantly, Au NRs whose light absorption and scattering are polarized are suitable for probe orientations. A typical Au nano-solution is hydrophobic and thermodynamically unstable, which requires surfactant stability. 190 Au NPs synthesized by reducing HAuCl 4 usually have negative charges on their surface. In contrast, Au NRs synthesized by the seed-mediated growth method are stabilized by CTAB, which is a widely used cationic surfactant and has a positive charge on its surface. In contrast to Au NPs, it is difficult for Au NRs to be functionalized due to the presence of CTAB surfactant molecules serving as stabilizers. Nevertheless, Dujardin et al. obtained a specic organization of short Au-NRs into anisotropic three-dimensional (3D) aggregates by DNA hybridization, but in this approach, it is needed to remove excess surfactant aer the synthesis of Au NRs. 215 Although CTAB bilayers hinder the formation of the Au-S bond between thiol-modied DNA and Au NRs, there exists electrostatic interaction between the positively charged ammonium of CTAB and the phosphate backbone of the DNA. 216 Since the Au NR surface has a positive charge, it can connect with the negatively charged un-modied ssDNA and dsDNA through electrostatic interactions. 217 This is the most fundamental difference between Au NPs and Au NRs. 218 There are mainly three methods to displace CTAB from the surfaces of Au NRs or harness the electrostatic interactions between CTAB and DNA. 216 One approach is to control the electrostatic interactions between DNA and positively charged surfaces. 16,195,219 The second approach is through packing the NRs with a thin lm of silica. The outer silica layers were modied with DNA functionalized by amine or thiol. The third approach is using the ligand exchange process to decorate Au NRs with ss-DNA. 216,220 CTAB-coated Au NRs were able to withstand high salt concentrations even without decorations and deposits. 221,222 He et al. described the use of un-modied CTAB-coated Au NRs for colorimetric assay. In this approach, it is not necessary to remove the excess CTAB from the solution by centrifugation. 195 It only needs the addition of target DNA to the mixture of the Au NRs without any modication and the label-free probe DNA in certain buffer salt solutions. The SPR absorption band will red-shi in a high ionic strength buffer aer mixing the NR probe and target ssDNA, indicating the aggregation of Au NRs. This phenomenon is ascribed to the formation of dsDNA from hybridization between the target DNA and probe DNA. In contrast, the addition of noncomplementary targets will not cause any spectral changes. 16,195 This protocol only experiences one step and is very simple for detecting hybridization. Moreover, it is easy to detect single-base-pair mismatches without temperature control, providing promising applications in the detection of single-nucleotide polymorphisms (SNPs) and disease diagnosis. 195,223,224 Although Au NRs have unique advantages in biological application, few studies applied Au NRs as orientation probes. The reason may come from the following reasons. First, there is a lack of good preparation and processing methods to obtain the desired size. Broader functionalities and applications can be achieved by tuning the longitudinal plasmon band of Au NRs. 225 Second, there is no suitable imaging technique to decipher its three dimensions. Au NRs have shown potential in photothermal cancer therapy and optoelectronic technology. 134,226,227 In 2004, O'Neill et al. demonstrated that Au NRs with SPR absorption in the near-infrared (NIR) region can target tumors in vivo. Aer excitation with a NIR laser, Au NRs released heat into the tumor environment, resulting in the rupture of the tumor cell membrane. 228 Aer that, Huang et al. reported that Au NRs with a low aspect ratio can be used as a simultaneous imaging and therapeutic agent to promote tumor cell recognition and photothermal removal in vitro due to their strong scattering and absorption properties in NIR spectroscopy. 229 The demonstration greatly increases the interest in the treatment and diagnosis of certain cancers using Au NRs. Compared with traditional chemotherapy, photothermal therapy may become an effective and specic cancer treatment option. Ideally, cell death can only be induced in the region where Au NRs are excited by laser with appropriate wavelengths. Photothermal therapy has attracted tremendous attention in killing cancer cells, making it a promising biomedical candidate for the treatment of cancer. In recent years, using assembled Au NRs for the photothermal killing of bacteria has also shown promising prospects. 232 6. Conclusions and outlook Conclusions In this study, we focused on the properties and preparation of Au NCs with different morphologies as well as their important applications in biological detection. The ability to carefully tailor the physical properties of Au NCs such as sizes, shapes, and composition is essential for their biomedical applications. As a face-centered cubic (fcc) metal, Au NCs can take a variety of geometrical shapes. In realistic chemical synthesis, particularly in the solution phase, many critical parameters, which can be divided into thermodynamic and kinetic parameters are responsible for the nal morphologies of Au NCs. The seedmediated growth method is the widely reported method, both the crystallinity of seeds and the growth rates of different crystallographic facets play a vital role in determining the nal shape of a resultant nanostructure. The colorimetric assay method has become an attractive choice for biological detection because it does not require the use of advanced equipment and is easy to operate in many applications. Nanogold probes including citrate-coated Au NPs and CTAB-coated Au NRs are being used for biological detection, such as oligonucleotides, proteins, and enzymes. Citrateprotected Au NPs can be easily decorated via thiolate chemistry and their optical properties depend on their size. In addition to Au NPs, Au NRs also have been used in biological elds. Since the Au NR surface has a positive charge, it can connect with the negatively charged un-modied ssDNA and dsDNA through electrostatic interactions. There are some disadvantages while using Au NCs in the colorimetric assay method. For example, it requires complex experimental procedures and cannot monitor the hybridization process real-time. In addition, it could not be achieved for absolute quantitative analysis. Therefore, it is important to nd a simple, real-time, and quantication system. Perspective and challenge The chemical method can generate Au NCs at a low cost and provide repeatable results using various chemicals. Gold NPs are considered an important research eld due to their unique and tunable SPR and their application in biomedical science, including drug delivery, tissue/tumor imaging, photothermal therapy, and immunochromatography identication of pathogens in clinical specimens. The synthesis of Au NCs with such extended medical applications should be free from toxic chemicals used during the synthesis process. It is promising to develop a green, effective, simple, air-stable, and cost-effective technique for the synthesis of Au NCs. The tendency of the presented approach is: (i) without the usage of a surfactant, capping agent, or template; (ii) the selection of an environmentally acceptable solvent with the use of eco-friendly reducing and stabilizing agents, for example, replacing toxic chemicals with extracts from living organisms for the synthesis of Au NCs; (iii) excellent yield of the products; (iv) simple maintenance and reuse of the Au NCs. For Au NCs synthesized using chemical methods, functionalizing the surface with more peculiar ligands to regulate and detoxify, which is caused by the toxic capping agents, is encouraged. These are the few future aspects for the generation of NCs via green synthesis and many more are yet to be explored by researchers. As for the application, gold nanoprobes are facing many challenges, such as selectivity and sensitivity decrease, reduction of the catalytic activity, and potential biohazard, in the practical application. To address these challenges, the existing detection technology should be further improved, and new functional nanoprobes should be developed on the basis of practical problems. In addition, more sensitive and easier methods of analysis should be designed. Along with further research, it is our ultimate goal to achieve automatic and intelligent sample testing. While using Au NRs as probes, developing a suitable imaging technique to decipher its three dimensions is expected. We hope that our research efforts in this review will contribute to a better understanding of the synthesis, optical properties, shape tuning, and applications of Au NCs. Author contributions Meng Li conceived the study and collected the literature. All authors were involved in writing and revising the manuscript. Conflicts of interest There are no conicts to declare.
def _makeservertoolbar(self, target): f = tk.Frame(target) self.serverChooser = OptionMenuFix(f, labelpos='w', menubutton_width=40, label_text = 'Connection ', label_font = self.FONT, menubutton_font = self.FONT, menu_font = self.FONT, command = self.chooseServer, menubutton_bd = 1, menubutton_highlightbackground = 'black', menubutton_borderwidth=1, menubutton_highlightcolor='black', menubutton_highlightthickness = 1, menubutton_height=1, ) self.serverChooser_NULL = '<no servers>' self.serverChooser.pack(expand=1, fill='x', anchor='center', side='left') b2 = tk.Button(f, image=self._ICON_sys, text='(S)', command=None) b2.pack(expand=0, fill='y', anchor='center', side='left', padx=1) b2.configure(command=self._openservermanager, **self.BORDER) b = tk.Button(f, text='Disconnect', command=self.closeconnection, image=self._ICON_disconnect, compound=None, **self.BORDER) b.pack(anchor='se', side='right',expand=0,fill='y') b = tk.Button(f, text='Refresh', command=self.refresh, image=self._ICON_refresh, compound=None, **self.BORDER) b.pack(anchor='se', side='right',expand=0,fill='y',padx=1) b = tk.Button(f, text='Prepare', command=self.racconizeServer, image=self._ICON_raccoon, compound=None, **self.BORDER) b.pack(anchor='se', side='right',expand=0,fill='y') f.pack(expand=0, fill='none', anchor='w',side='top', padx=3, pady=3) self._populateservertoolbar()
<reponame>gitlubtaotao/wblog package repositories import ( "github.com/gitlubtaotao/wblog/models" "github.com/gitlubtaotao/wblog/service" ) type ICommentRepository interface { MustListUnreadComment() ([]*models.Comment, error) CountComment() int ListCommentByPostID(postId uint) ([]*models.Comment, error) } type CommentRepository struct { service service.ICommentService } func (c *CommentRepository) ListCommentByPostID(postId uint) ([]*models.Comment, error) { return c.service.ListCommentByPostID(postId) } func NewCommentRepository() ICommentRepository { return &CommentRepository{service: service.NewCommentService()} } func (c *CommentRepository) MustListUnreadComment() ([]*models.Comment, error) { return c.service.ListUnreadComment() } func (c *CommentRepository) CountComment() int { return c.service.CountComment() }
<filename>retrofitcachelib/src/main/java/ren/yale/android/retrofitcachelib/intercept/CacheInterceptorOnNet.java package ren.yale.android.retrofitcachelib.intercept; import android.text.TextUtils; import java.io.IOException; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; import ren.yale.android.retrofitcachelib.CacheInterceptorListener; import ren.yale.android.retrofitcachelib.RetrofitCache; import ren.yale.android.retrofitcachelib.bean.CacheConfig; /** * Created by Yale on 2017/6/13. */ public class CacheInterceptorOnNet extends BaseInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response mockResponse = mockResponse(chain); if (mockResponse!=null){ return mockResponse; } String url = getOriginUrl(request.url().url().toString()); String mockPreUrl = request.header(KEY_HEADER_PRE_URL); if (!TextUtils.isEmpty(mockPreUrl)){ url = mockPreUrl; } CacheConfig cacheConfig = RetrofitCache.getInstance().getCacheTime(url); Long maxAge = cacheConfig.getTime(); Response response = chain.proceed(request); if (response.code()==301||response.code()==302){ String location = response.headers().get("Location"); RetrofitCache.getInstance().addUrlArgs(location,cacheConfig); } CacheInterceptorListener listener = RetrofitCache.getInstance().getCacheInterceptorListener(); if (listener!=null&&!listener.canCache(request,response)){ return response; } return response.newBuilder() .removeHeader("Cache-Control") .header("Cache-Control", "public,max-age="+maxAge) .removeHeader("Pragma") .build(); } }
// extractVolumesExtensions adds a k8s extension to each defined volume. // Every extension contains default k8s settings. func extractVolumesExtensions(c *ComposeProject, out *composeOverride) error { for _, v := range c.VolumeNames() { vol := c.Volumes[v] k8sVol, err := config.VolK8sConfigFromCompose(&vol) if err != nil { return nil } target := VolumeConfig{ Extensions: vol.Extensions, } if target.Extensions == nil { target.Extensions = make(map[string]interface{}) } m, err := k8sVol.Map() if err != nil { return err } target.Extensions[config.K8SExtensionKey] = m out.Volumes[v] = target } return nil }
<gh_stars>0 pkgname = "dinit-chimera" _commit = "<PASSWORD>" pkgver = "0.1" pkgrel = 0 build_style = "makefile" makedepends = ["linux-headers"] depends = ["dinit", "util-linux", "eudev"] pkgdesc = "Chimera core services suite" maintainer = "q66 <<EMAIL>>" license = "BSD-2-Clause" url = f"https://github.com/chimera-linux/dinit-chimera" source = f"https://github.com/chimera-linux/dinit-chimera/archive/{_commit}.tar.gz" sha256 = "6c19299c939a88e85eb0f09a54b1508a513c69b43bfadc6c5de6c18b7bbabf09" # no tests options = ["!check", "brokenlinks"] def post_install(self): self.install_file(self.files_path / "hostname", "etc") self.install_file(self.files_path / "os-release", "etc") self.install_file(self.files_path / "locale.conf", "etc") # init symlink self.install_link("dinit", "usr/bin/init")
Robust spectro-temporal features based on autoregressive models of Hilbert envelopes In this paper, we present a robust spectro-temporal feature extraction technique using autoregressive models (AR) of sub-band Hilbert envelopes. AR models of Hilbert envelopes are derived using frequency domain linear prediction (FDLP). From the sub-band Hilbert envelopes, spectral features are derived by integrating these envelopes in short-term frames and the temporal features are formed by converting these envelopes into modulation frequency components. The spectral and temporal feature streams are then combined at the phoneme posterior level and are used as the input features for a recognition system. For the proposed features, robustness is achieved by using novel techniques of noise compensation and gain normalization. Phoneme recognition experiments on telephone speech in the HTIMIT database show significant performance improvements for the proposed features when compared to other robust feature techniques (average relative reduction of 10.6 % in phoneme error rate). In addition to the overall phoneme recognition rates, the performance with broad phonetic classes is also reported.
<filename>notebooks/_solutions/case2_biodiversity_analysis6.py sum(survey_data_processed.duplicated())
<gh_stars>10-100 package com.bihe0832.android.lib.file.select; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; /** * @author hardyshi <EMAIL> Created on 4/8/21. */ class FileViewHolder { ImageView iv_icon; TextView tv_fileName; CheckBox cb_selected; }
import React from 'react' import { formatDate, LOCAL_TIME } from '../../util/format' import LocationDisplay from '../location/LocationDisplay' import { Card, makeStyles, CardContent, CardActionArea, Typography } from '@material-ui/core' import clsx from 'clsx' import { Link } from 'react-router-dom' import { grey } from '@material-ui/core/colors' import { Trip } from '../../util/types' import basicStyles from '../../styles/basicStyles' export interface TripProps { trip: Trip } const useStyles = makeStyles(theme => ({ trip: { cursor: 'pointer', }, enabledTrip: { color: theme.palette.primary.contrastText, backgroundColor: theme.palette.primary.main, }, disabledTrip: { background: grey[200], }, flexHorCenter: { display: 'flex', flexFlow: 'row wrap', alignItems: 'center' }, ...basicStyles(theme), })) function TripListItem (props: TripProps) { const classes = useStyles() return ( <Link to={`/trip/${props.trip.id}`} style={{ textDecoration: 'none', color: 'unset' }} > <Card className={clsx(classes.trip, classes.mb2, props.trip.enabled ? classes.enabledTrip : classes.disabledTrip)} > <CardActionArea> <CardContent> <Typography variant='h5' className={classes.mb2} > {props.trip.name} </Typography> <Typography component='span' variant='body1' > <div className={clsx(classes.flexHorCenter, classes.mb1)}> <div className={clsx('material-icons', classes.mr2)}> {props.trip.enabled ? 'notifications_active' : 'notifications_off'} </div> <div>{formatDate(props.trip.notify_at, LOCAL_TIME)}</div> </div> <div style={{ display: 'flex' }}> <div className={clsx('material-icons', classes.mr2)}>place</div> <div className={clsx(classes.flexHorCenter, classes.mb1)}> <LocationDisplay lat={props.trip.from_lat} lon={props.trip.from_lon} /> <div className={clsx('material-icons', classes.ml2, classes.mr2)}>arrow_right_alt</div> <LocationDisplay lat={props.trip.to_lat} lon={props.trip.to_lon} /> </div> </div> <div style={{ display: 'flex' }}> <div className={clsx('material-icons', classes.mr2)}>access_time</div> <div className={classes.flexHorCenter}> <div>{formatDate(props.trip.start, LOCAL_TIME)}</div> <div className={clsx('material-icons', classes.ml2, classes.mr2)}>arrow_right_alt</div> <div>{formatDate(props.trip.end, LOCAL_TIME)}</div> </div> </div> </Typography> </CardContent> </CardActionArea> </Card> </Link> ) } export default TripListItem
def _features(self, img, gt_label=None, cur_mode="puzzlemix", **kwargs): if cur_mode == "attentivemix": img = F.interpolate(img, scale_factor=kwargs.get("feat_size", 224) / img.size(2), mode="bilinear") features = self.backbone_k(img)[-1] elif cur_mode == "puzzlemix": input_var = Variable(img, requires_grad=True) self.backbone.eval() self.head_cls.eval() pred = self.neck_cls([self.backbone(input_var)[-1]]) pred = self.head_cls(pred) loss = self.head_cls.loss(pred, gt_label)["loss"] loss.backward(retain_graph=False) features = torch.sqrt(torch.mean(input_var.grad**2, dim=1)) self.backbone.zero_grad() self.head_cls.zero_grad() self.backbone.train() self.head_cls.train() return features
def _encode_component(value): int_bytes = bytearray() int_bytes.append(value & 0x7f) value >>= 7 while value: int_bytes.append(value & 0x7f | 0x80) value >>= 7 int_bytes.reverse() return int_bytes
/// Sort matched tracks by release dates fn sort_tracks(tracks: &mut Vec<(f64, &Track)>, config: &TaggerConfig) { match config.multiple_matches { MultipleMatchesSort::Default => {}, MultipleMatchesSort::Oldest => tracks.sort_by(|a, b| { if a.1.release_date.is_none() || b.1.release_date.is_none() { Ordering::Equal } else { a.1.release_date.as_ref().unwrap().cmp(b.1.release_date.as_ref().unwrap()) } }), MultipleMatchesSort::Newest => tracks.sort_by(|a, b| { if a.1.release_date.is_none() || b.1.release_date.is_none() { Ordering::Equal } else { b.1.release_date.as_ref().unwrap().cmp(a.1.release_date.as_ref().unwrap()) } }), } }
/** * * ADTF Demo Source. * * @file * Copyright &copy; Audi Electronics Venture GmbH. All rights reserved * * $Author: exthanlal $ * $Date: 2014-09-04 11:39:27 +0200 (Do, 04 Sep 2014) $ * $Revision: 25772 $ * * @remarks * */ #ifndef __STD_INCLUDES_HEADER #define __STD_INCLUDES_HEADER // ADTF header #include <adtf_platform_inc.h> #include <adtf_plugin_sdk.h> using namespace adtf; // AADC header #include "aadc.h" #endif // __STD_INCLUDES_HEADER
A recent issue of Handguns. handgunsmag.com Though print journalism largely remains in the financial doldrums, there’s at least one sector that’s maintaining its buoyancy in these days of political ferment and latent social unrest: gun magazines. AdWeek recently reported that four separate firearms publications saw significant circulation boosts over the first half of 2013. American Rifleman and America’s 1st Freedom, both published by the National Rifle Association, saw circulation increases of 14 percent and 8 percent, respectively, compared with the first half of 2012. Guns & Ammo and Handguns magazines, both issued by the publisher InterMedia Outdoors, saw respective jumps of 16 percent and 7 percent. These numbers are especially impressive when compared with those of other magazine sectors; fashion magazines and celebrity weeklies all reported reduced single-copy sales. What makes these magazines so popular? The obvious answer is that a lot of people like guns. (End of blog post—thanks for reading!) But is there anything else to it? I went to a bookstore and bought the latest issues of Handguns and Guns & Ammo to see what I could find. I also picked up a copy of Rifle Firepower, a newer magazine that is all about—you guessed it—rifles and the firepower they so ably provide. My main takeaway is that these are all essentially car magazines. They feature money shots of various guns, plenty of product reviews, and geeky, unbridled enthusiasm for their subject matter. They rarely stray into politics. If you don’t own a gun, there’s no real reason for you to read them. But, in the interest of science, I read them cover to cover all the same. Here are a few highlights. Handguns. The title isn’t a lie. Handguns is, indeed, all about handguns: how to get better at shooting them, how to properly conceal them, and which ones to buy. This single-minded focus will thrill handgun owners and scholars, but is likely to bore everyone else. The well of the October/November 2013 issue is filled with reviews of various handguns, like the Nighthawk Falcon Commander—“as nice (and expensive) a custom pistol as you’re likely to find”— and the Beretta Pico .380, which comes in pink. There are also a few other features, like a front-of-the-book column that explains that California is requiring that every new handgun sold in the state feature “microstamping” technology that imprints a unique identifier on each casing it fires. The author darkly opines that, far from being a tool that could help police officers solve crimes faster, the law is actually a sneaky back-door attempt at banning handguns entirely. A recent issue of Guns & Ammo. gunsandammo.com Guns & Ammo. Guns & Ammo is geared toward mature gun owners more interested in hunting and history than paramilitary fantasies. Its pages are loaded with photographs of middle-aged men: holding tiny handguns, holding slightly larger handguns, crouching triumphantly over some sort of dead hog. Give Guns & Ammo credit for knowing its target audience, I guess. It features a lot of gun reviews, as you might expect—Guns & Ammo also reviews the Beretta Pico .380—but the magazine’s spirit shines through elsewhere. Garry James’ “Gun Room” is an Antiques Roadshow-style column wherein the historical firearms expert answers readers’ questions about whether their old guns are valuable, or of historical interest. A long article by Layne Simpson tells you everything you’d ever want to know about triggers. Enough about the guns, what about the ammo, you ask? Not to worry: Editor-in-Chief Jim Bequette gets to the bottom of the “great ammo drought,” and finds that ammunition supplies are limited not because President Obama and his cronies are conspiring to take ammo off the market, but because gun sales are at an all-time high. A recent issue of Rifle Firepower. riflefirepower.com Rifle Firepower. This magazine’s November 2013 issue features seven exclamation points on its Table of Contents page. Rifle Firepower is an enthusiast’s magazine through and through, written for (and, apparently, by) people who want to get the most out of their rifles. There are lots of reviews, yes, but the nonreview content is useful and interesting, too. A helpful column titled “Flying with Guns & Ammo” offers a step-by-step guide on how to do just that (cheat sheet: make sure your guns are unloaded and packed in a locked, hard-sided container, and be sure to tell the airline that you’re flying with a gun). I liked F.W. Demara’s “Long Gun Legends” feature on pioneer John C. Garand, who designed the military-issue M1 semi-automatic rifle. And I was happy to see the magazine taking the time to check in with America’s favorite everyman, Joe the Plumber, in an interview at the very end of the book. The writer asked Joe what he would do if he weren’t a plumber. Answer: “I used to be a plumber, but now I run a website. I just want to get the truth out there.” There you have it! Crime is Slate’s crime blog. Like us on Facebook, and follow us on Twitter @slatecrime.
/** * <p>Invokes the add album dialog window and performs adding operation after that</p> */ public void addAlbom(PaEvent event) { if ( event.getEventType() != PaEventDispatcher.ALBUM_NEW_EVENT ) { return; } try { PaAlbumNewDialog dialog = new PaAlbumNewDialog(m_nodes,m_mainWindow, m_cont,0,getGuiStrs("newAlbomDialogCaptionName")); ArrayList<Integer> l = getSelectedAlbomsIds(); if(l.size() == 1) { if(l.get(0) == PaUtils.ALBUM_TOP_PARENT_ID) { dialog.setParentComboItem(PaUtils.getAlbomsRootName()); } else { dialog.setParentComboItem(m_cont.getAlbum(l.get(0)).getName()); } } else { dialog.setParentComboItem(PaUtils.getAlbomsRootName()); } dialog.setVisible(true); String newText = dialog.getAlbomName(); if (dialog.getClosedFlagValue() == 1) { Date date_alb = dialog.getDate(); boolean albomShouldBeLoaded = dialog.isAlbomShouldBeLoaded(); if ( date_alb == null ) { date_alb=new Date(); } PaAlbum al = new PaAlbum (newText, dialog.getCommentAlbum(), dialog.getRootPath(), date_alb, dialog.getFolderName()); al.setParentId(dialog.getParentAlbomId()); int id = m_cont.addAlbum(al); writeLogOnly("Album adding: An albom with id = " + id +" has been created" + NEXT_ROW+"folder name :" + al.getFolderName() + NEXT_ROW + "path : " + al.getFullStandardPath(), null); if ( id != -1) { try { PaEventDispatcher.get().fireCustomEvent( new PaEvent(PaEventDispatcher.ALBUM_REFRESH_EVENT) ); if(albomShouldBeLoaded) { PaUtils.get().getMainContainer().setCurrentLoadedContainer( PaUtils.get().getMainContainer().getContainer(id)); PaEventDispatcher.get().fireCustomEvent( new PaEvent(PaEventDispatcher.REFRESH_EVENT) ); PaUndoRedoDeque.get().clearAll(); } setSelected(id); PaActionsMngr.get().getAction("paactionsave").actionPerformed(null); writeLog(getMessagesStrs("newAlbomHasAdded")+ " : " + newText, null, true, true, true); writeLogOnly("Album adding: the operation is finished id = " + id, null); } catch (Exception e0) { writeLog("Exception : " + NEXT_ROW, e0, true, false, true); } } else { writeLog(getMessagesStrs("valueExists"), null, true, true, true); } } else { writeLogOnly("Album adding: the operation is canceled", null); } } finally { PaUtils.get().resetCursor(Cursor.DEFAULT_CURSOR); } }
// ListClusterStackNames gets all stack names matching regex func (c *StackCollection) ListClusterStackNames(ctx context.Context) ([]string, error) { var stacks []string re, err := regexp.Compile(clusterStackRegex) if err != nil { return nil, errors.Wrap(err, "cannot list stacks") } input := &cloudformation.ListStacksInput{ StackStatusFilter: defaultStackStatusFilter(), } paginator := cloudformation.NewListStacksPaginator(c.cloudformationAPI, input) for paginator.HasMorePages() { out, err := paginator.NextPage(ctx) if err != nil { return nil, err } for _, s := range out.StackSummaries { if re.MatchString(*s.StackName) { stacks = append(stacks, *s.StackName) } } } return stacks, nil }
/** * Lookup the value for the key. * * @param key * the key to be looked up, may be null * @return The value for the key. */ public String lookup(String key) { if (key.equals("filesdir")) { return AndroidLog4jHelper.getApplicationContext().getFilesDir().getAbsolutePath(); } if (key.equals("externalfilesdir")) { File f = AndroidLog4jHelper.getApplicationContext().getExternalFilesDir(null); if (f == null) { return null; } return f.getAbsolutePath(); } if (key.equals("logfilesdir")) { File f = AndroidLog4jHelper.getApplicationContext().getExternalFilesDir(null); if (f != null) { return new File(f, "logs").getAbsolutePath(); } return new File(AndroidLog4jHelper.getApplicationContext().getFilesDir(), "logs").getAbsolutePath(); } return null; }
import React from "react"; import { Sidebar } from "./sidebar"; import { Logger, LogEventName } from "../../lib/logger"; const kSidebarOffset = 100; export interface SidebarConfiguration { content: string | null; title: string | null; } interface IProps { sidebars: SidebarConfiguration[]; verticalOffset: number; } interface IState { showSidebarContent: boolean[]; } export class SidebarWrapper extends React.PureComponent<IProps, IState> { constructor(props: IProps) { super(props); this.state = { showSidebarContent: new Array(props.sidebars.length).fill(false) }; } render() { const { sidebars, verticalOffset } = this.props; return ( <React.Fragment> {sidebars.map((sidebar: SidebarConfiguration, index: number) => ( <Sidebar key={`sidebar-${index}`} content={sidebar.content} handleShowSidebar={this.setShowSidebarContent} index={index} show={this.state.showSidebarContent[index]} style={{ top: verticalOffset + kSidebarOffset * index}} title={sidebar.title} /> ))} </React.Fragment> ); } private setShowSidebarContent = (index: number, show: boolean) => { Logger.log({ event: LogEventName.toggle_sidebar, parameters: { show_sidebar: show } }); this.setState(state => { const updatedShowSidebarContent = new Array(state.showSidebarContent.length).fill(false); updatedShowSidebarContent[index] = show; return { showSidebarContent: updatedShowSidebarContent }; }); } }
Two Charts that Show the Challenge Facing Italy’s New Prime Minister Matteo Renzi is poised to take over as Italy’s youngest-ever prime minister. He has a clear mandate to get the Italian economy back on track, but everyone, including Renzi himself, knows that he faces a daunting task. Here are two charts that show just how far Italy’s growth and living standards have slipped and how hard it will be to reverse the trends. In terms of growth of real GDP, Italy has been at the bottom among the advanced economies of the OECD for a decade. In the following chart, Italy stands out not for having the slowest-growth in each given year, but rather, for the consistency of its slow growth. Before the global crisis, there were years when Japan or Germany grew more slowly than Italy, but both of those have recovered more strongly. After the crisis, Greece has grown even more slowly, and Spain almost as slowly, but both of those were coming off strong-pre-recession booms. Among OECD countries, only Portugal (not included in the chart) equaled Italy’s average growth rate since 2000 of just 0.3 percent. But, you might say, isn’t Italy wealthy enough to coast for a while and still maintain a high standard of living? That is true, to a degree. As the next chart shows, as recently as 2001, Italians had a per capita income, measured in terms of purchasing power, that was 119 percent of the EU average. That was higher than Germany or France. The problem is, since that time, Italy’s standard of living has slipped more than any other country. It was already slipping in the early 2000s, when Greece, Spain, and the UK were going strong. Those countries have faltered since, but over the whole period, Italy has lost more ground relative to its peers than any other EU member. Will Renzi be able to do anything to reverse the slide? Let’s hope so. As he takes office, the latest data show Italy’s economy growing by a tiny 0.1 percent in the fourth quarter of 2013, technically ending the country’s latest recession. His advisers are vetting all manner of reform proposals, ranging from easing the tax burden to freeing up a sclerotic labor market, to changes in the management of state corporations. The new prime minister has also proposed a bold electoral reform that he hopes will create the political space needed to put some of those reforms into effect without watering them down in endless negotiations with coalition partners. Matteo, we all wish you the best of luck!
import os import sys from yehua.main import HELP_TEXT, main, control_c_quit, get_yehua_file from six import StringIO from mock import patch from nose.tools import eq_, raises @patch("os.system") @patch("yehua.project.get_user_inputs") @patch("yehua.utils.mkdir") @patch("yehua.utils.save_file") @patch("yehua.utils.copy_file") def test_main(copy, save, mkdir, inputs, os_system): copy.return_value = 0 save.return_value = 0 mkdir.return_value = 0 inputs.return_value = dict(project_name="test-me") main() calls = mkdir.call_args_list calls = [str(call) for call in calls] expected = [ "call('test-me')", "call('test-me/test_me')", "call('test-me/tests')", "call('test-me/docs')", "call('test-me/docs/source')", "call('test-me/.moban.d')", "call('test-me/.moban.d/tests')", "call('test-me/.moban.d/docs')", "call('test-me/.moban.d/docs/source')", ] eq_(calls, expected) @raises(SystemExit) def test_main_help(): args = ["yehua", "help"] with patch("sys.stdout", new_callable=StringIO) as out: with patch.object(sys, "argv", args): main() eq_(out.getvalue(), HELP_TEXT) def test_yehua_file_passed_in_command_line(): args = ["yehua", "/tmp/yehua.yml"] with patch("yehua.main.Project") as mocked_project: with patch.object(sys, "argv", args): main() mocked_project.assert_called() def test_get_yehua_file_1(): file_name = "testme" os.environ["YEHUA_FILE"] = file_name yehua_file = get_yehua_file() eq_(file_name, yehua_file) os.environ.pop("YEHUA_FILE") def test_get_yehua_file_2(): with open("yehua.yml", "w") as f: f.write("test") yehua_file = get_yehua_file() eq_(os.path.abspath("yehua.yml"), yehua_file) os.unlink("yehua.yml") def test_get_yehua_file_3(): default_yehua_file = os.path.join("yehua", "resources", "yehua.yml") yehua_file = get_yehua_file() eq_(os.path.abspath(default_yehua_file), yehua_file) @raises(SystemExit) def test_contrl_c_quit(): control_c_quit("not", "used")
ES Football Newsletter Enter your email address Please enter an email address Email address is invalid Fill out this field Email address is invalid You already have an account. Please log in or register with your social account Australia’s women’s football team are ranked the fifth best side in world football. So how did they lose 7-0 to a collection of 15-year-old boys? It is the question gripping the Matildas, who will be targeting a medal at the Rio Olympics in August, after they were embarrassed by the Newcastle Jets under-16s side on Wednesday. Admittedly this was not the most fiercely competitive of friendly matches, with the women’s team employing a rotating team, but the Matildas, who often have no choice but to play boys teams such is the paucity of opponents in Australia, did have star names such as Katrina Gorry in their lineup. Assistant coach of the women’s side Gary van Egmond admitted his side, who were without their overseas-based players, had been taken by surprise. “To be honest we didn't expect that,” he told The Huffington Post. “But the Jets boys were very good. All credit to them. They moved the ball around very well and were excellent on the night. “At this stage in their preparation, obviously the Matildas are not in a position to play regular games so I'd suggest all and sundry were a little bit rusty. “We could have had an easier game, but we definitely want to keep testing the girls.” Van Egmond will presumably hope that their next opponents New Zealand don’t have any plans to sneak any children into their side.
<reponame>bellalMohamed/nativescript-windowed-modal import { GestureEventData } from "tns-core-modules/ui/gestures/gestures"; import { booleanConverter, CSSType, isIOS, layout, LayoutBase, View } from "tns-core-modules/ui/layouts/layout-base"; import { StackLayout } from "tns-core-modules/ui/layouts/stack-layout/stack-layout"; import { HorizontalAlignment, VerticalAlignment } from "tns-core-modules/ui/styling/style-properties"; @CSSType("ModalStack") export class ModalStack extends StackLayout { dismissEnabled: string = "true"; verticalPosition: VerticalAlignment = "middle"; horizontalPosition: HorizontalAlignment = "center"; constructor() { super(); } onLoaded(): void { super.onLoaded(); const modalView = this.getChildAt(0) as LayoutBase; this.set("height", "100%"); this.set("width", "100%"); this.horizontalAlignment = this.horizontalPosition; this.verticalAlignment = this.verticalPosition; this.on("tap", (evt) => this.outsideTap(evt as GestureEventData, modalView)); } private outsideTap(args: GestureEventData, modal: View): void { if (!booleanConverter(this.dismissEnabled)) { return; // Don't close the modal } if (isIOS) { const iosMotion = args.ios; const view = iosMotion.view; const tapPos = iosMotion.locationInView(view); const modalFrame = modal.ios.frame; const insideRect = CGRectContainsPoint(modalFrame, tapPos); if (insideRect) { // Touched inside, don't close. return; } } else { const androidMotion: android.view.MotionEvent = args.android; const x = androidMotion.getRawX() - layout.toDevicePixels(this.getLocationOnScreen().x); const y = androidMotion.getRawY() - layout.toDevicePixels(this.getLocationOnScreen().y); const rect = new android.graphics.Rect(); modal.android.getHitRect(rect); const insideRect = rect.contains(x, y); if (insideRect) { // Touched inside, don't close. return; } } modal.closeModal(); } }
2017 F1: 'Something changed' in McLaren-Honda divorce Posted by: Admin on Jul 09, 2017 - 06:14 AM 2017 F1: 'Something changed' in McLaren-Honda divorce After a tumultuous period in the McLaren-Honda marriage, the works collaboration now appears to be back on track. Recent reports hinted that a divorce announcement was imminent, but the rhetoric has suddenly changed in Austria, where Honda has duly delivered the more powerful 'spec 3' engine. It actually malfunctioned in Fernando Alonso's car, but the Spaniard sounded oddly satisfied with having to revert to the 'spec 2' unit from Baku. "From my grid position I can go into the points," he said. "We are constantly improving. The team is bringing aero parts all the time and Honda is bringing engine upgrades. We are moving in the right direction, we just lack reliability," Alonso added. Earlier in Austria, McLaren's Eric Boullier, Honda's Yusuke Hasegawa and Mercedes' Toto Wolff sat together in the FIA press conference, and together denied rumours McLaren would be Mercedes-powered next year. Now, Mercedes team chairman Niki Lauda insists: "If we intervened in an existing contract by offering an engine, Honda could sue us." And so it seems that McLaren and Honda may have patched up some of their differences. "The Japanese are being almost praised, even if another engine has broken," said Auto Motor und Sport correspondent Michael Schmidt. "You do not have to be a mind reader to realise that something has happened in the last two weeks." Still, there are some reports that a McLaren-imposed deadline for Honda to up its game even more is still in play. Marca sports newspaper quotes McLaren executive Zak Brown as saying: "In 2018 we must have a competitive engine. "Honda is working and progressing and we want to give them room to improve. We've seen a good reaction from them," he said. PaddockTalk Perspective
import scipy.io import os from PIL import Image, ImageDraw import numpy as np from data_utils.clean_data import clean_bboxes class mafa2kitti(): def __init__(self, annotation_file, mafa_base_dir, kitti_base_dir, kitti_resize_dims, category_limit, train): self.annotation_file = annotation_file self.data = scipy.io.loadmat(self.annotation_file) self.kitti_base_dir = kitti_base_dir self.mafa_base_dir = mafa_base_dir self.count_mask = category_limit[0] self.count_no_mask = category_limit[1] self.kitti_resize_dims = kitti_resize_dims self.train = train self.count_save_image = 0 if self.train: self.len_dataset = len(self.data["label_train"][0]) try: os.makedirs(self.kitti_base_dir+'/train/images',mode=0o777) except FileExistsError: print("Directory Already Exists") self.kitti_images = os.path.join(self.kitti_base_dir, 'train/images') try: os.makedirs(self.kitti_base_dir+ '/train/labels',mode=0o777) except FileExistsError: print("Directory Already Exists") self.kitti_labels = os.path.join(self.kitti_base_dir, 'train/labels') else: self.len_dataset = len(self.data["LabelTest"][0]) try: os.makedirs(self.kitti_base_dir+'/test/images',mode=0o777) except FileExistsError: print("Directory Already Exists") self.kitti_images = os.path.join(self.kitti_base_dir, 'test/images') try: os.makedirs(self.kitti_base_dir+'/test/labels',mode=0o777) except FileExistsError: print("Directory Already Exists") self.kitti_labels = os.path.join(self.kitti_base_dir, 'test/labels') def extract_labels(self, i, train_flag, _count_mask, _count_no_mask): if train_flag: train_image = self.data["label_train"][0][i] train_image_name = str(train_image[1]).strip("['']") # Test [0] categories = [] bboxes = [] for i in range(0, len(train_image[2])): _bbox_label = train_image[2][i] # Test[1][0] _category_id = _bbox_label[12] # Occ_Type: For Train: 13th, 10th in Test _occulution_degree = _bbox_label[13] bbox = [_bbox_label[0], _bbox_label[1], _bbox_label[0]+_bbox_label[2], _bbox_label[1]+_bbox_label[3]] if (_category_id != 3 and _occulution_degree > 2) and (_count_mask < self.count_mask): category_name = 'Mask' # Faces with Mask bbox = clean_bboxes(bbox) if bbox: _count_mask += 1 #count = 0 categories.append(category_name) bboxes.append(bbox) elif (_category_id==3 and _occulution_degree<2) and (_count_no_mask < self.count_no_mask): category_name = 'No-Mask' # Faces with Mask bbox = clean_bboxes(bbox) if bbox: _count_no_mask += 1 #count = 0 categories.append(category_name) bboxes.append(bbox) if bboxes: img = os.path.join(self.mafa_base_dir , train_image_name) #import pdb;pdb.set_trace() #print(train_image_name, bboxes) #self.save_images(img, train_image_name, bboxes) if not self.check_image_dims(image_name=train_image_name): self.make_labels(image_name=train_image_name, category_names=categories, bboxes=bboxes) else:#train_flag test_image = self.data["LabelTest"][0][i] test_image_name = str(test_image[0]).strip("['']") # Test [0] categories = [] bboxes = [] for i in range(0, len(test_image[1])): _bbox_label = test_image[1][i] # Test[1][0] # Occ_Type: For Train: 13th, 10th in Test # In test Data: refer to Face_type, 5th _face_type = _bbox_label[4] # Face Type _occ_type = _bbox_label[9] _occ_degree = _bbox_label[10] bbox = [_bbox_label[0], _bbox_label[1], _bbox_label[0] + _bbox_label[2], _bbox_label[1] + _bbox_label[3]] if (_face_type==1 and _occ_type!=3 and _occ_degree > 2) and _count_mask < self.count_mask: category_name = 'Mask' bboxes.append(bbox) categories.append(category_name) _count_mask+=1 elif (_face_type==2) and _count_mask < self.count_mask: category_name = 'No-Mask' bboxes.append(bbox) categories.append(category_name) _count_no_mask+1 if bboxes: if not self.check_image_dims(image_name=test_image_name): self.make_labels(image_name=test_image_name, category_names=categories, bboxes=bboxes) return _count_mask, _count_no_mask def check_image_dims(self, image_name): file_name=os.path.join(self.mafa_base_dir, image_name) img = Image.open(file_name).convert("RGB") img_w, img_h = img.size if img_w < img_h: return True return False def save_images(self, image_location, image_name, bboxes, debug=False): #draw rect on img image = Image.open(image_location).convert("RGB") img_bbox = ImageDraw.ImageDraw(image) if debug: import pdb;pdb.set_trace() print(image_name, bboxes) for i in range(0, len(bboxes)): x_min, y_min, x_max, y_max = bboxes[i] shape = [(x_min, y_min), (x_max, y_max)] img_bbox.rectangle(shape, fill=None, outline ="green", width=5) self.count_save_image += 1 image.save(os.path.join(self.kitti_images, image_name), 'JPEG') assert(self.count_save_image < 100) def make_labels(self, image_name, category_names, bboxes): # Process image file_image = os.path.splitext(image_name)[0] img = Image.open(os.path.join(self.mafa_base_dir, image_name)).convert("RGB") resize_img = img.resize(self.kitti_resize_dims) resize_img.save(os.path.join(self.kitti_images, file_image + '.jpg'), 'JPEG') # Process labels with open(os.path.join(self.kitti_labels, file_image + '.txt'), 'w') as label_file: for i in range(0, len(bboxes)): resized_bbox = self.resize_bbox(img=img, bbox=bboxes[i], dims=self.kitti_resize_dims) out_str = [category_names[i].replace(" ", "") + ' ' + ' '.join(['0'] * 1) + ' ' + ' '.join(['0'] * 2) + ' ' + ' '.join([b for b in resized_bbox]) + ' ' + ' '.join(['0'] * 7) + '\n'] label_file.write(out_str[0]) def resize_bbox(self, img, bbox, dims): img_w, img_h = img.size x_min, y_min, x_max, y_max = bbox ratio_w, ratio_h = dims[0] / img_w, dims[1]/img_h new_bbox = [str(int(np.round(x_min*ratio_w))), str(int(np.round(y_min*ratio_h))), str(int(np.round(x_max*ratio_w))), str(int(np.round(y_max *ratio_h)))] return new_bbox def mat2data(self): _count_mask, _count_no_mask = 0,0 for i in range(0, self.len_dataset): _count_mask, _count_no_mask = self.extract_labels(i=i, train_flag=self.train, _count_mask=_count_mask, _count_no_mask=_count_no_mask) print("MAFA Dataset: Total Mask faces: {} and No-Mask faces:{}".format(_count_mask, _count_no_mask)) return _count_mask, _count_no_mask def test_labels(self, file_name): img = Image.open(os.path.join(self.kitti_images, file_name + '.jpg')) text_file = open(os .path.join(self.kitti_labels, file_name + '.txt'), 'r') features = [] bbox = [] category = [] for line in text_file: features = line.split() bbox.append([float(features[4]), float(features[5]), float(features[6]), float(features[7])]) category.append(features[0]) print("Bounding Box", bbox) print("Category:", category) i = 0 for bb in bbox: cc = category[i] if cc == 'Mask': outline_box = 'red' elif cc == "No-Mask": outline_box = 'green' draw_img = ImageDraw.Draw(img) shape = ((bb[0], bb[1]), (bb[2], bb[3])) draw_img.rectangle(shape, fill=None, outline=outline_box) draw_img.text((bb[0], bb[1]), cc, (255,255,255)) i+=1 img.show() def main(): mafa_base_dir = r'C:\Users\ameykulkarni\Downloads\MAFA\MAFA' kitti_base_dir = r'C:\Users\ameykulkarni\Downloads\MAFA\KITTI_test' train = True if train: annotation_file = os.path.join(mafa_base_dir, 'MAFA-Label-Train/LabelTrainAll.mat') mafa_base_dir = os.path.join(mafa_base_dir, 'train-images\images') else: annotation_file = os.path.join(mafa_base_dir, 'MAFA-Label-Test/LabelTestAll.mat') mafa_base_dir = os.path.join(mafa_base_dir, 'test-images\images') category_limit = [25000, 25000] # Mask / No-Mask Limits kitti_resize_dims = (480, 272) # Look at TLT model requirements kitti_label = mafa2kitti(annotation_file=annotation_file, mafa_base_dir=mafa_base_dir, kitti_base_dir=kitti_base_dir, kitti_resize_dims=kitti_resize_dims, category_limit=category_limit, train=train) count_masks, count_no_masks = kitti_label.mat2data() kitti_label.test_labels(file_name='train_00006597') if __name__ == '__main__': main()
<gh_stars>0 import * as chai from 'chai'; import * as chaiAsPromised from 'chai-as-promised'; import Onexec from "../src/onexec"; chai.use(chaiAsPromised); var expect = chai.expect; describe('Onexec', function() { describe('single run', function() { it('should successfully run with value returned', function(done) { var onexec = new Onexec<string>((token) => token); expect(onexec.run('test')).eventually.equal('test').notify(done); }); it('should successfully run with promise returned', function(done) { var onexec = new Onexec<string>((token) => Promise.resolve(token)); expect(onexec.run('test')).eventually.equal('test').notify(done); }); it('should return a rejected promise', function(done) { var onexec = new Onexec<string>((token) => Promise.reject('rejected')); expect(onexec.run('test')).to.eventually.rejectedWith('rejected').notify(done); }); it('should return a rejected promise by throwing', function(done) { var onexec = new Onexec<string>((token) => { throw new Error('rejected') }); expect(onexec.run('test')).to.eventually.rejectedWith('rejected').notify(done); }); it('should have requestedOn and completedOn set', function(done) { var onexec = new Onexec<string>((token) => token); onexec.run('test') .then(() => { expect(onexec.completedOn.getTime()).to.gte(onexec.requestedOn.getTime()); done(); }) .catch(done); }); }); describe('multiple run', function() { it('should return the previous token', function(done) { var onexec = new Onexec<string>((token) => { return new Promise((resolve) => { setTimeout(() => { resolve(token) }, 10); }); }); onexec.run(1); expect(onexec.run(2)).to.eventually.equal(1).notify(done); }); it('should return the previous error', function(done) { var onexec = new Onexec<string>((token) => { return new Promise((resolve, reject) => { setTimeout(() => { reject(token) }, 10); }); }); onexec.run('1').catch(() => {}); expect(onexec.run('2')).to.eventually.rejectedWith('1').notify(done); }); }); describe('wait', function() { it('should wait on nothing', function(done) { var onexec = new Onexec<string>((token) => { return new Promise((resolve) => { setTimeout(() => { resolve(token) }, 10); }); }); expect(onexec.wait()).to.eventually.notify(done); }); it('should wait on fulfilled', function(done) { var onexec = new Onexec<string>((token) => { return new Promise((resolve) => { setTimeout(() => { resolve(token) }, 10); }); }); onexec.run(1); expect(onexec.wait()).to.eventually.notify(done); }); it('should wait on rejected', function(done) { var onexec = new Onexec<string>((token) => { return new Promise((resolve, reject) => { setTimeout(() => { reject(token) }, 10); }); }); onexec.run('1').catch(() => {}); expect(onexec.wait()).to.eventually.notify(done); }); }); });
First Gene Mapping in Hawaiian Drosophila Several electrophoretic gene markers have been located and three of these mapped in the genome of an endemic Hawaiian species, D. silvestris. This was accomplished by use of the multiple inversion polymorphisms of this species as chromosome markers. The initial localization of a few gene loci in D. silvestris provides a basis for further mapping of the entire picture-winged group of Hawaiian Drosophila, which comprises over 100 species. Detailed genetic analysis of the evolutionary events in this remarkable group of flies would then become feasible.