content
stringlengths
10
4.9M
/** * Created by kdoherty on 7/8/15. */ public abstract class AbstractRequestSender { private String restAction; private String url; private boolean hasAddedParams = false; protected AbstractRequestSender(String restAction, String url) { this.restAction = restAction; this.url = url; } protected abstract Result send(); protected AbstractRequestSender addQueryParam(String key, Object value) { if (!hasAddedParams) { url += "?"; hasAddedParams = true; } else { url += "&"; } url += (key + "=" + value); return this; } protected Http.RequestBuilder getRequestBuilder() { return new Http.RequestBuilder().uri(url).method(restAction); } }
<reponame>camiladuartes/Rest-API-Nearest-Promotions<gh_stars>0 import { Injectable } from '@nestjs/common'; import { CreatePromotionDto } from './dto/create-promotion.dto'; import { Promotion, PromotionDocument } from './entities/promotion.entity'; import { Model } from 'mongoose'; import { InjectModel } from '@nestjs/mongoose'; import { UpdatePromotionDto } from './dto/update-promotion.dto'; import { latLongDistance } from 'src/utils/utility-functions'; // Provider; injectable as a dependency of another @Injectable() export class PromotionsService { constructor(@InjectModel(Promotion.name) private promotionModel: Model<PromotionDocument>) { } create(createPromotionDto: CreatePromotionDto) { // Instanciate a comment for object-relational mapping const promotion = new this.promotionModel(createPromotionDto); return promotion.save(); } findAll() { return this.promotionModel.find(); } findOne(id: string) { return this.promotionModel.findById(id); } // async findAllVotesByPromotion(promotionId: string) { // // const promotionVotes = await this.votesService.findAllByPromotion(promotionId); // // return promotionVotes; // return this.voteModel.find({idPromotion: promotionId}); // } update(id: string, promotion: UpdatePromotionDto) { return this.promotionModel.findByIdAndUpdate( { _id: id, }, { $set: promotion, }, { new: true, }, ).exec(); } remove(id: string) { return this.promotionModel.deleteOne({_id: id}).exec(); } computeVote(id: string, vote: number){ return this.promotionModel.findByIdAndUpdate( { _id: id, }, { votes: vote, }, { new: true, }, ).exec(); } findByPrice(min: number, max: number){ if(max != 0){ return this.promotionModel.find({ price: { $gte: min, $lte: max } }); } else { return this.promotionModel.find({ price: { $gte: min } }); } } async findByDistance(distance: number, lat: number, long: number){ let promotions = await this.findAll(); let rangePromotions = [] promotions.forEach(element => { console.log(element.id,latLongDistance(element.lat, element.long, lat, long)); if(latLongDistance(element.lat, element.long, lat, long) <= distance){ rangePromotions.push(element); } }); return rangePromotions; } async findByPattern(pattern: string){ return this.promotionModel.find({$or :[{"product": {'$regex': pattern}}, {"store": {'$regex': pattern}}, {"location": {'$regex': pattern}}]}); } }
167 SHARES Facebook Twitter Linkedin Reddit The Vive Tracker, a ‘puck’-like device designed to attach to objects to track them in VR via the SteamVR Tracking system, went on sale this week after 1,000 units went out to developers earlier this year. One developer aptly demonstrated the tracking performance by juggling a trio of Trackers in VR. We’ve seen people juggle virtual objects in VR, but what about real objects that are tracked using the SteamVR Tracking system? Thanks to the high-quality tracking performance of the HTC Vive tracker, that’s apparently now a possibility. Steve Bowler, co-founder of Cloud Gate Studio, shot a quick video of himself juggling three active Vive Trackers while wearing the Vive headset. Even as the devices are spinning through the air and being occasionally occluded by his hands, they appear to maintain robust tracking the entire time. For juggling of course, it isn’t just accuracy of the objects that’s important, but also the latency. How accurate are the @htcvive and the Trackers? This accurate. pic.twitter.com/DbiLGKiuvi — Steve Bowler (@gameism) March 28, 2017 Bowler must be quite confident in the Vive Tracker’s capability, as that’s $300 worth of equipment being juggled. And while some seasoned jugglers might be able to juggle spheres with their eyes closed or blindfolded, the irregular shape of the Vive Tracker and the way it spins through the air makes it all the more challenging. As we see in the video, it appears Bowler is relying quite heavily on the information he’s seeing through the headset (the location, direction, and speed of the Trackers through the air) to accomplish this task. For $99 each, the Vive Tracker became openly available for sale this week, though with the accessory ecosystem just getting underway, it’s still at this point recommended only for developers. Later this year HTC is expected to push the device more widely to businesses and consumers.
<gh_stars>0 package fi.evident.enlight.utils; import java.io.File; public final class PathUtils { public static String extensionFor(String path) { return extensionFor(new File(path)); } public static String extensionFor(File file) { String name = file.getName(); int index = name.lastIndexOf('.'); return index != -1 ? name.substring(index+1) : ""; } }
def register(self): self.establish_connection() self.add_listeners() self.subscribe_to_topics(Constants.PRE_REGISTRATION_TOPICS_TO_SUBSCRIBE) registration_request = self.registration_builder.build() logger.info("Sending registration request") logger.debug("Registration request is {0}".format(registration_request)) response = self.blocking_request(registration_request, Constants.REGISTRATION_ENDPOINT) logger.info("Registration response received") logger.debug("Registration response is {0}".format(response)) self.handle_registration_response(response) for endpoint, cache, listener in self.post_registration_requests: response = self.blocking_request({'hash': cache.hash}, endpoint) try: listener.on_event({}, response) except: logger.exception("Exception while handing response to request at {0}. {1}".format(endpoint, response)) raise self.subscribe_to_topics(Constants.POST_REGISTRATION_TOPICS_TO_SUBSCRIBE) self.file_cache.reset() self.initializer_module.is_registered = True self.initializer_module._connection = self.connection
package main import mgl "github.com/go-gl/mathgl/mgl64" // change this to mgl32 for 32 bit floats // epsilon is a "near zero" value. I'm not really using it mathematically correctly. const epsilon = 0.0001 // Below aliases are to make it easy to switch between 32 and 64 bit floats // V3 is a 3d vector. type V3 = mgl.Vec3 // M4 is a 4x4 matrix. type M4 = mgl.Mat4 // Float is a floating point number type Float = float64
module CharQq.Q where import CharQq.Prelude import qualified CharQq.Exp as Exp import qualified CharQq.Pat as Pat stringChar :: String -> Q Char stringChar = \ case [char] -> return char [] -> fail "Empty quotation" _ -> fail "More than one char in the quotation" stringCodepointExp :: String -> Q Exp stringCodepointExp = fmap Exp.codepoint . stringChar stringCodepointPat :: String -> Q Pat stringCodepointPat = fmap Pat.codepoint . stringChar stringCodepointsExp :: String -> Q Exp stringCodepointsExp = return . Exp.codepoints stringCodepointsPat :: String -> Q Pat stringCodepointsPat = return . Pat.codepoints codepointChar :: Int -> Q Char codepointChar codepoint = if codepoint <= ord maxBound then return (chr codepoint) else fail "Codepoint is out of the supported Unicode range" stringInt :: String -> Q Int stringInt string = case readMaybe string of Just int -> return int Nothing -> fail "String doesn't parse to integer" stringCodepointChar :: String -> Q Char stringCodepointChar = stringInt >=> codepointChar stringCodepointCharExp :: String -> Q Exp stringCodepointCharExp = fmap Exp.char . stringCodepointChar stringCodepointCharPat :: String -> Q Pat stringCodepointCharPat = fmap Pat.char . stringCodepointChar
<reponame>Licenser/event-listener<gh_stars>0 //! A simple mutex implementation. //! //! This mutex exposes both blocking and async methods for acquiring a lock. #![allow(dead_code)] use std::cell::UnsafeCell; use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{mpsc, Arc}; use std::thread; use std::time::{Duration, Instant}; use event_listener::Event; /// A simple mutex. struct Mutex<T> { /// Set to `true` when the mutex is locked. locked: AtomicBool, /// Blocked lock operations. lock_ops: Event, /// The inner protected data. data: UnsafeCell<T>, } unsafe impl<T: Send> Send for Mutex<T> {} unsafe impl<T: Send> Sync for Mutex<T> {} impl<T> Mutex<T> { /// Creates a mutex. fn new(t: T) -> Mutex<T> { Mutex { locked: AtomicBool::new(false), lock_ops: Event::new(), data: UnsafeCell::new(t), } } /// Attempts to acquire a lock. fn try_lock(&self) -> Option<MutexGuard<'_, T>> { if self.locked.swap(true, Ordering::Acquire) { Some(MutexGuard(self)) } else { None } } /// Blocks until a lock is acquired. fn lock(&self) -> MutexGuard<'_, T> { let mut listener = None; loop { // Attempt grabbing a lock. if let Some(guard) = self.try_lock() { return guard; } // Set up an event listener or wait for a notification. match listener.take() { None => { // Start listening and then try locking again. listener = Some(self.lock_ops.listen()); } Some(l) => { // Wait until a notification is received. l.wait(); } } } } /// Blocks until a lock is acquired or the timeout is reached. fn lock_timeout(&self, timeout: Duration) -> Option<MutexGuard<'_, T>> { let deadline = Instant::now() + timeout; let mut listener = None; loop { // Attempt grabbing a lock. if let Some(guard) = self.try_lock() { return Some(guard); } // Set up an event listener or wait for an event. match listener.take() { None => { // Start listening and then try locking again. listener = Some(self.lock_ops.listen()); } Some(l) => { // Wait until a notification is received. if !l.wait_deadline(deadline) { return None; } } } } } /// Acquires a lock asynchronously. async fn lock_async(&self) -> MutexGuard<'_, T> { let mut listener = None; loop { // Attempt grabbing a lock. if let Some(guard) = self.try_lock() { return guard; } // Set up an event listener or wait for an event. match listener.take() { None => { // Start listening and then try locking again. listener = Some(self.lock_ops.listen()); } Some(l) => { // Wait until a notification is received. l.await; } } } } } /// A guard holding a lock. struct MutexGuard<'a, T>(&'a Mutex<T>); unsafe impl<T: Send> Send for MutexGuard<'_, T> {} unsafe impl<T: Sync> Sync for MutexGuard<'_, T> {} impl<T> Deref for MutexGuard<'_, T> { type Target = T; fn deref(&self) -> &T { unsafe { &*self.0.data.get() } } } impl<T> DerefMut for MutexGuard<'_, T> { fn deref_mut(&mut self) -> &mut T { unsafe { &mut *self.0.data.get() } } } fn main() { const N: usize = 10; // A shared counter. let counter = Arc::new(Mutex::new(0)); // A channel that signals when all threads are done. let (tx, rx) = mpsc::channel(); // Spawn a bunch of threads incrementing the counter. for _ in 0..N { let counter = counter.clone(); let tx = tx.clone(); thread::spawn(move || { let mut counter = counter.lock(); *counter += 1; // If this is the last increment, signal that we're done. if *counter == N { tx.send(()).unwrap(); } }); } // Wait until the last thread increments the counter. rx.recv().unwrap(); // The counter must equal the number of threads. assert_eq!(*counter.lock(), N); println!("Done!"); }
import flattenedNavigationData from '../../autoGeneratedData/rootTopics.json' import isExternalLink from '../../src/utils/isExternalLink' /* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires */ chai.use(require('chai-string')) const ignore = [ 'mailto', // github responds with 429 too many requests because it thinks we are spamming them 'https://github.com', 'https://stream.launchdarkly.', 'https://events.launchdarkly.', 'https://app.launchdarkly.', 'https://console.aws.', 'https://mockbin.org', 'https://glitch.com', 'https://app.logdna.com', ] describe('Verify links', () => { flattenedNavigationData.forEach(({ label, allItems }) => { allItems.forEach(path => { it(`${label}: ${path}`, () => { if (isExternalLink(path)) { cy.request(path).then(resp => { expect(resp.status).to.eq(200) }) } else { cy.visit(path) cy.get('main a').each($a => { const href = $a.prop('href') const included = !ignore.find(prefix => href.startsWith(prefix)) if (included) { cy.request(`${href}`).then(resp => { expect(resp.status).to.eq(200) }) } }) } }) }) }) })
/** * We are grouping events after applying a window. * * <p>The triggers specified in the window will produce each a pane per group of events (those * sharing the same key). This class holds together the metadata about a pane and group, so it can * be examined easily in the output. */ @DefaultCoder(AvroCoder.class) public class PaneGroupMetadata { private int numberOfTriggers; // Number of triggers up to this point (to order the rows in the output) private String windowBoundaries; // Window boundaries (timestamps) as a string private Boolean isFirstPane; // Is this the first pane/trigger of this window? private Boolean isLastPane; // Is it the last one? private String timing; // EARLY, ON_TIME or LATE private int numEventsBeforeWindow; // Num. of events seen before applying the window private int numEventsAfterWindow; // Num. of events seen after the window (same if no dropped data) private int groupSize; // Number of elements in this group // This constructor is necessary to run tests with JUnit public PaneGroupMetadata() {} public PaneGroupMetadata( int numberOfTriggers, String windowBoundaries, Boolean isFirstPane, Boolean isLastPane, String timing, int numEventsBeforeWindow, int numEventsAfterWindow, int groupSize) { this.numberOfTriggers = numberOfTriggers; this.windowBoundaries = windowBoundaries; this.isFirstPane = isFirstPane; this.isLastPane = isLastPane; this.timing = timing; this.numEventsBeforeWindow = numEventsBeforeWindow; this.numEventsAfterWindow = numEventsAfterWindow; this.groupSize = groupSize; } public String toCSVLine() { String line = String.format( "%d,%s,%b,%b,%s,%d,%d,%d", numberOfTriggers, windowBoundaries, isFirstPane, isLastPane, timing, numEventsBeforeWindow, numEventsAfterWindow, groupSize); return line; } }
package me.alexisevelyn.crewmate.packethandler.packets.reliable; import me.alexisevelyn.crewmate.Main; import me.alexisevelyn.crewmate.Server; import me.alexisevelyn.crewmate.api.Game; import me.alexisevelyn.crewmate.api.GameCodeHelper; import me.alexisevelyn.crewmate.api.GameSettings; import me.alexisevelyn.crewmate.enums.GamePacketType; import me.alexisevelyn.crewmate.enums.hazel.SendOption; import me.alexisevelyn.crewmate.events.impl.HostGameEvent; import me.alexisevelyn.crewmate.exceptions.InvalidBytesException; import me.alexisevelyn.crewmate.exceptions.InvalidGameCodeException; import me.alexisevelyn.crewmate.handlers.GameManager; import me.alexisevelyn.crewmate.packethandler.PacketHelper; import me.alexisevelyn.crewmate.packethandler.packets.ClosePacket; import org.apiguardian.api.API; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.net.InetAddress; import java.net.URL; public class HostSettingsPacket { /** * Retrieves the game settings from the client on game join as host. * * <br><br> * Refer to NOT-IMPLEMENTED for the game settings that are set in the lobby. * * @param server Server Instance * @param clientAddress Client's IP Address * @param clientPort Client's Port * @param payloadBytes payload bytes * @return Joined Game Packet With List of Other Clients If Any Or Close Packet If Exception */ @API(status = API.Status.EXPERIMENTAL) @NotNull public static byte[] getNewGameSettings(@NotNull Server server, @NotNull InetAddress clientAddress, int clientPort, @NotNull byte... payloadBytes) { // 01 00 02 2b 00 00 2a 02 09 02 00 00 00 01 00 00 c0 3f 00 00 00 3f 00 00 80 3f 00 00 f0 41 02 02 03 01 00 00 00 03 00 0f 00 00 00 78 00 00 00 00 0f // RP NO NO PL PL RC // RP = Reliable Packet (1) // NO = Nonce (2) // PL = Packet Length (43) // RC = Reliable Packet Type (0x00 for Host Game) byte[] gameCodeBytes = getCodeFromList(); try { GameSettings gameSettings = new GameSettings(payloadBytes); HostGameEvent event = new HostGameEvent(GameCodeHelper.parseGameCode(gameCodeBytes), gameSettings.getMaxPlayers(), gameSettings.getImposterCount(), gameSettings.getMaps()[0], gameSettings.getLanguages()); event.call(server); byte[] newCode = GameCodeHelper.generateGameCodeBytes(event.getGameCode()); GameManager.addGame(new Game(newCode)); return useCustomCode(newCode); } catch (InvalidGameCodeException e) { // LogHelper.printLineErr(e.getMessage()); // e.printStackTrace(); return ClosePacket.closeWithMessage(Main.getTranslation("gamecode_invalid_code_exception")); } catch(InvalidBytesException exception) { return ClosePacket.closeWithMessage(Main.getTranslation("game_packet_invalid_size")); } } // For S->C @API(status = API.Status.EXPERIMENTAL) private static byte[] getRandomGameCode() { byte[] nonce = new byte[] {(byte) 0xbb, 0x01}; byte[] gameCode = getCodeFromList(); // Game Code byte[] gameCodeSize = PacketHelper.convertShortToLE((short) gameCode.length); byte hostGame = (byte) GamePacketType.HOST_SETTINGS.getReliablePacketType(); // The client will respond with a packet that triggers getNewGameSettings(...); return new byte[] {SendOption.RELIABLE.getByte(), nonce[0], nonce[1], gameCodeSize[0], gameCodeSize[1], hostGame, gameCode[0], gameCode[1], gameCode[2], gameCode[3]}; } // TODO: Rewrite @API(status = API.Status.EXPERIMENTAL) private static byte[] useCustomCode(byte... code) throws InvalidBytesException { if (code.length != 4) throw new InvalidBytesException(String.format(Main.getTranslation("invalid_number_of_bytes_exact"), 4)); byte[] header = new byte[] {SendOption.RELIABLE.getByte(), 0x00, 0x01, 0x04, 0x00, 0x00}; return PacketHelper.mergeBytes(header, code); } @Deprecated @API(status = API.Status.EXPERIMENTAL) private static byte[] getCodeFromList() { try { // This is a temporary test function // https://stackoverflow.com/a/53673751/6828099 // File To Pull Words From URL filePath = Main.class.getClassLoader().getResource("codes/words.txt"); // Create Temporary File File tempFile = File.createTempFile("words", ".tmp"); tempFile.deleteOnExit(); // Copy Word List to Temporary File FileOutputStream out = new FileOutputStream(tempFile); assert filePath != null : "Words List is Missing - Translate Me If Method Kept"; out.write(filePath.openStream().readAllBytes()); RandomAccessFile file = new RandomAccessFile(tempFile, "r"); // For Random Position long length = file.length() - 1; long position = (long) (Math.random() * length); // Skip Ahead file.seek(position); // Skip to End of Line // TODO: Fix so it can grab the first word on the list and // so it doesn't NPE for reading the line on the last word of the list file.readLine(); byte[] gameCodeBytes = GameCodeHelper.generateGameCodeBytes(file.readLine()); // Close File Reference file.close(); // Get Word return gameCodeBytes; } catch (IOException | NullPointerException | AssertionError exception) { exception.printStackTrace(); return ClosePacket.closeWithMessage(Main.getTranslation("server_side_exception")); } catch (InvalidGameCodeException exception) { return ClosePacket.closeWithMessage(Main.getTranslation("gamecode_invalid_code_exception")); } } }
use std::cmp::Ordering; use std::fmt; //GrailPair is a small struct which can be used for stability testing of the sort. #[allow(dead_code)] #[derive(Clone, Copy, Eq, Default)] pub(crate) struct GrailPair { pub key: isize, pub value: isize, } impl fmt::Debug for GrailPair { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.key) } } //Manual implementation of Partial and Total Ordering for the GrailPair struct assures that key is the value //compared between GrailPair objects, rather than the default implementation comparing every field. impl Ord for GrailPair { fn cmp(&self, other: &Self) -> Ordering { self.key.cmp(&other.key) } } impl PartialOrd for GrailPair { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.key.cmp(&other.key)) } } //Manual implementation of Partial Equality serves the same purpose as for Partial Ordering. impl PartialEq for GrailPair { fn eq(&self, other: &Self) -> bool { self.key == other.key } }
Despite hammering out the details late last year, Kodak still had to wait for the Bankruptcy court to greenlight its big patent sale. Today, that happened: Judge Allan Gropper has approved the $527 million deal between Kodak, Apple and Google -- giving the floundering photo company final permission to offload more than 1,000 imaging patents. Kodak originally valued its collection of IP at over $2 billion, which Gropper deemed a bit high. Despite hoping for a higher payout, Kodak's attorney admits the deal is probably the best it could have hoped for, explaining that the $525 million the company will collect in the agreement will give it some "patent peace." Apple and Google, once rivals for Kodak's intellectual property, struck a deal to bid on the patents together -- lowering their respective costs and keeping the bid war out of the courts. Less litigation sounds good to us, even if it's only for a little while. Check out Bloomberg's report at the adjacent source link for more info.
def is_ne(self, strategy_pair, support_pair): u = strategy_pair[1].reshape(strategy_pair[1].size, 1) row_payoffs = np.dot(self.payoff_matrices[0], u) v = strategy_pair[0].reshape(strategy_pair[0].size, 1) column_payoffs = np.dot(self.payoff_matrices[1].T, v) row_support_payoffs = row_payoffs[np.array(support_pair[0])] column_support_payoffs = column_payoffs[np.array(support_pair[1])] return (row_payoffs.max() == row_support_payoffs.max() and column_payoffs.max() == column_support_payoffs.max())
// for all the workers, gathering their voting results. // in the format of <task_id, which_object_is_preferred>. void generate_sim_votes_taskID_who( const int& n, const int& w, bool **GT, const vector<vector<vector<int>>> & matrice, vector<vector <td_wieghts::client_vote>> & v_client_votes ){ if (v_client_votes.size() < w){ v_client_votes.clear(); v_client_votes = vector<vector<client_vote>>(w, vector<client_vote>(0)); } for (int ww = 0; ww < w; ++ww){ int task_id = 0; int who = 0; for (int i = 0; i < n; ++i){ for (int j = 0; j < i; ++j){ if (GT[i][j] == true){ if (matrice[ww][i][j] > 0){ who = i; v_client_votes[ww].push_back(client_vote(task_id, who)); } else if (matrice[ww][j][i] > 0){ who = j; v_client_votes[ww].push_back(client_vote(task_id, who)); } else { } task_id++; } } } } }
Faith and Culture in the Time of Coronavirus The social experience of Covid-19 has already generated in many countries an impressive bibliography of multiple genres and in many fields. It is tempting to oppose this excess of analysis and reflection with the voice of Job. He rejected the words of his theological friends who came to comfort him by calling them “sap of the mallow,” unable to extinguish his lacerating pain. Or, we might be inclined to resound the harsh phrase of another biblical sage, Qoheleth, who warned: “All things are wearisome, more than words can say” (1:8). Yet all communities live through events that can generate new cultural, religious, social, and, more specifically, anthropological phenomena and models. But perhaps there is a lack of great intellectual figures capable of extracting a symbolic banner from lived reality. To make this observation more explicit it would be sufficient to refer to the memorable pages of Alessandro Manzoni’s The Betrothed (1827) where he re-elaborates the plague that struck Italy in the years 1629–31. Or we could resort to that dramatic masterpiece from Albert Camus, his famous novel The Plague (1947), especially for the problem of theodicy that it proposes following Dostoevsky’s Brothers Karamazov. Or we could even evoke the lesser known but suggestive Letters from a City in Mourning (1885) by the Swedish doctor and writer Axel Munthe, who journeyed to Naples in 1884 to cure the victims of a cholera epidemic. On a religious level, however, a high-level presence has been manifested: the images seen around the world of Pope Francis in an empty St. Peter’s Square, under the pouring rain with the emblem of the crucified Christ. The
def publish_images(targets_file=None, target=None): if target: targets = [target] else: targets = get_targets(targets_file) for target in targets: publish_target(target)
package withjava; import java.util.Optional; public class UsingJavaOptional { public static Optional<String> some = Optional.of("abc"); public static Optional<String> none = Optional.empty(); }
package session import ( "errors" "fmt" "github.com/grestful/utils" ) type ISession interface { Close() bool Destroy(sid string) bool Gc(maxLeftTime int64) bool Open(savePath string) bool Read(sid string) map[string]interface{} Write(sid string, data map[string]interface{}) bool Error(sid string) error SetPrefix(keyPrefix string) } type IUserSession interface { SetData(data *utils.MapReader) error GetData() (data *utils.MapReader, err error) GetUserId() int64 GetProperty(name string) interface{} GetAuthName() string SetSessionHandler(session ISession) error SetUserIdKey(idName string) } type UserSession struct { UserId int64 `json:"userId"` Property *utils.MapReader `json:"property"` Sid string `json:"sid"` flag uint8 //0 未读 1 已读 2 已写 idName string handler ISession } func GetNewUserSession(sid string, session ISession) IUserSession { return &UserSession{ UserId: 0, Property: utils.NewMapperReader(make(map[string]interface{})), Sid: sid, handler: session, } } func (s *UserSession) SetUserIdKey(idName string) { s.idName = idName } func (s *UserSession) getUserIdKey() string { if s.idName == "" { return "userId" } return s.idName } func (s *UserSession) SetData(data *utils.MapReader) error { s.UserId = data.ReadWithInt64(s.getUserIdKey(), 0) if s.UserId > 0 { s.Property = data s.flag = 2 s.handler.Write(s.Sid, s.Property.GetValue()) } return errors.New(fmt.Sprintf("no found id in data %v", data.GetValue())) } func (s *UserSession) GetData() (data *utils.MapReader, err error) { s.checkRead() return s.Property, nil } func (s *UserSession) GetUserId() int64 { s.checkRead() return s.UserId } func (s *UserSession) GetProperty(name string) interface{} { s.checkRead() return s.Property.ReadWithInterface(name, nil) } func (s *UserSession) GetAuthName() string { return "cookie" } func (s *UserSession) SetSessionHandler(session ISession) error { s.handler = session return nil } func (s *UserSession) checkRead() bool { if s.flag != 1 { if s.Sid == "" { return false } s.flag = 1 s.Property = utils.NewMapperReader(s.handler.Read(s.Sid)) } return true }
<reponame>shaneding/clx<gh_stars>100-1000 # Copyright (c) 2020, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest import cudf import clx from clx.analytics.asset_classification import AssetClassification import torch from os import path import random import pandas as pd column1 = [random.randint(1, 24) for _ in range(9000)] column2 = [random.randint(1, 4) for _ in range(9000)] column3 = [random.randint(1, 9) for _ in range(9000)] column4 = [random.randint(1, 26) for _ in range(9000)] column5 = [random.randint(1, 3) for _ in range(9000)] column6 = [random.randint(1, 9) for _ in range(9000)] column7 = [random.randint(1, 37) for _ in range(9000)] column8 = [random.randint(1, 8) for _ in range(9000)] column9 = [random.randint(1, 4) for _ in range(9000)] column10 = [random.randint(1, 11) for _ in range(9000)] label = [random.randint(0, 6) for _ in range(9000)] train_pd = pd.DataFrame(list(zip(column1, column2, column3, column4, column5, column6, column7, column8, column9, column10, label)), columns=["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "label"]) train_gdf = cudf.from_pandas(train_pd) batch_size = 6 epochs = 15 @pytest.mark.parametrize("train_gdf", [train_gdf]) def test_train_model_mixed_cat_cont(tmpdir, train_gdf): train_gdf = train_gdf.copy() cat_cols = ["1", "2", "3", "4", "5", "6", "7", "8"] cont_cols = ["9", "10"] train_gdf[cont_cols] = normalize_conts(train_gdf[cont_cols]) ac = AssetClassification() ac.train_model(train_gdf, cat_cols, cont_cols, "label", batch_size, epochs) if torch.cuda.is_available(): assert isinstance(ac._model, clx.analytics.model.tabular_model.TabularModel) @pytest.mark.parametrize("train_gdf", [train_gdf]) def test_train_model_all_cat(tmpdir, train_gdf): train_gdf = train_gdf.copy() cat_cols = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] cont_cols = [] ac = AssetClassification() ac.train_model(train_gdf, cat_cols, cont_cols, "label", batch_size, epochs) if torch.cuda.is_available(): assert isinstance(ac._model, clx.analytics.model.tabular_model.TabularModel) @pytest.mark.parametrize("train_gdf", [train_gdf]) def test_train_model_all_cont(tmpdir, train_gdf): train_gdf = train_gdf.copy() cont_cols = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] cat_cols = [] train_gdf[cont_cols] = normalize_conts(train_gdf[cont_cols]) ac = AssetClassification() ac.train_model(train_gdf, cat_cols, cont_cols, "label", batch_size, epochs) if torch.cuda.is_available(): assert isinstance(ac._model, clx.analytics.model.tabular_model.TabularModel) @pytest.mark.parametrize("train_gdf", [train_gdf]) def test_predict(tmpdir, train_gdf): if torch.cuda.is_available(): cat_cols = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] cont_cols = [] ac = AssetClassification() ac.train_model(train_gdf, cat_cols, cont_cols, "label", batch_size, epochs) # predict test_gdf = train_gdf.head() test_gdf.drop("label", axis=1) preds = ac.predict(test_gdf, cat_cols, cont_cols) assert isinstance(preds, cudf.core.series.Series) assert len(preds) == len(test_gdf) assert preds.dtype == int def test_save_model(tmpdir): if torch.cuda.is_available(): cat_cols = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] cont_cols = [] ac = AssetClassification() ac.train_model(train_gdf, cat_cols, cont_cols, "label", batch_size, epochs) # save model ac.save_model(str(tmpdir.join("clx_ac.mdl"))) assert path.exists(str(tmpdir.join("clx_ac.mdl"))) def test_load_model(tmpdir): if torch.cuda.is_available(): cat_cols = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] cont_cols = [] ac = AssetClassification() ac.train_model(train_gdf, cat_cols, cont_cols, "label", batch_size, epochs) # save model ac.save_model(str(tmpdir.join("clx_ac.mdl"))) assert path.exists(str(tmpdir.join("clx_ac.mdl"))) # load model ac2 = AssetClassification() ac2.load_model(str(tmpdir.join("clx_ac.mdl"))) assert isinstance(ac2._model, clx.analytics.model.tabular_model.TabularModel) def normalize_conts(gdf): means, stds = (gdf.mean(0), gdf.std(ddof=0)) gdf = (gdf - means) / stds return gdf
0 SHARES Facebook Twitter Google Whatsapp Pinterest Print Mail Flipboard Bernie Sanders put on a clinic and completely stonewalled ABC’s News Jon Karl when he tried to get the Democratic candidate to personally attack Hillary Clinton. Video: https://youtu.be/Al4sVp7Rs2E Transcript via ABC’s This Week: KARL: Hey, we are out of time. I want a yes or no answer to one quick question. Hillary Clinton’s poll suggest a lot of people don’t see her as honest and trustworthy. Do you think Hillary Clinton is honest and trustworthy? SANDERS: I have a lot of respect for Hillary Clinton. She is somebody I’ve known for 25 years. I’m not going to be engaging in personal attacks against her. KARL: So you won’t say whether or not she’s honest. SANDERS: I’m not going to be engaging in personal attacks against her. She and I disagree on many issues. The American people want a serious debate about serious issues, not personal attacks. KARL: All right, Senator Sanders, thank you very much for joining us. [[AD2]] Whether one supports Bernie Sanders or not, the Senator from Vermont deserves respect for the way that he has conducted his campaign. The media would love nothing more than for Sanders to personally attack Clinton. The corporate media in the United States has convinced themselves that the American people are too stupid to enjoy a debate about issues, so they spend their time trying to goad candidates into personally attacking each other. Sanders is the only candidate who has not taken the bait. He understands that personally attacking Hillary Clinton would take the focus off of the issues that matter. Plus, one of the reasons why Sen. Sanders has attracted such a dedicated following is that he is a different kind of candidate. There is a something dignified about a candidate who refuses to dwell in the sewer of modern American politics. The contrast between the Democratic and Republican primaries is striking. On the Republican side, RNC Chairman Reince Priebus is practically begging his candidates to stop attacking each other, but with Donald Trump sitting at the top of the polls, the Republican primary has become a mudslinging contest. While the Republicans are doing everything in their power to avoid discussing issues, Democrats are having an issue-driven debate among their candidates that is already sharpening up their vision of what the post-Obama Democratic agenda will look like. Bernie Sanders isn’t going to be bullied by the corporate media. He knows exactly what the press wants, and he is refusing to give it to them. Whether the media likes it or not, Democrats are going to have a spirited primary centered around the issues. Save the circus and childish behavior for the Republicans. Democrats are busy plotting a path to a prosperous future for the middle-class. If you’re ready to read more from the unbossed and unbought Politicus team, sign up for our newsletter here! Email address: Leave this field empty if you're human:
/** * Read the parameter in the specified shape. * * @param shape the shape to read (not null, unaffected) * @return the parameter value (&ge;0) or NaN if not applicable */ public float read(CollisionShape shape) { Validate.nonNull(shape, "shape"); if (shape instanceof CompoundCollisionShape) { switch (this) { case HalfExtentX: case HalfExtentY: case HalfExtentZ: case Height: case Radius: return Float.NaN; } } float result; switch (this) { case HalfExtentX: result = MyShape.halfExtents(shape, null).x; break; case HalfExtentY: result = MyShape.halfExtents(shape, null).y; break; case HalfExtentZ: result = MyShape.halfExtents(shape, null).z; break; case Height: result = MyShape.height(shape); break; case Margin: result = shape.getMargin(); break; case Radius: result = MyShape.radius(shape); break; case ScaleX: result = shape.getScale(null).x; break; case ScaleY: result = shape.getScale(null).y; break; case ScaleZ: result = shape.getScale(null).z; break; case ScaledVolume: result = MyShape.volume(shape); break; default: throw new IllegalArgumentException(toString()); } assert Float.isNaN(result) || result >= 0f : result; return result; }
"""Julynter module""" import sys from ._version import __version__ if sys.version_info < (3, 5): from .oldcmd import main else: from .handlers import setup_handlers from .cmd import main def _jupyter_server_extension_paths(): """Register julynter server extension""" return [{ "module": "julynter" }] def load_jupyter_server_extension(lab_app): """Registers the API handler to receive HTTP requests from the frontend extension. Parameters ---------- lab_app: jupyterlab.labapp.LabApp JupyterLab application instance """ setup_handlers(lab_app.web_app) lab_app.log.info("Registered Julynter extension at URL path /julynter") if __name__ == "__main__": main()
<reponame>ayinlaaji/pokedex<gh_stars>0 import React from "react"; import { Divider, List, Pagination } from "semantic-ui-react"; import PokemonItem from "@pokedex/components/molecules/PokemonItem"; import { Poke } from "@pokedex/typings/pokemon"; type Props = { totalPages: number; pokemons: Poke[]; handleItemClick: (id: string) => void; handleMoreClick: any; }; const PokemonList = ({ totalPages, pokemons, handleItemClick, handleMoreClick }: Props) => ( <div> <List divided> {pokemons.map(({ name, id }) => ( <PokemonItem key={id} name={name} handleClick={() => handleItemClick(id)} /> ))} </List> <Divider /> <Pagination boundaryRange={3} defaultActivePage={1} ellipsisItem={null} firstItem={null} lastItem={null} siblingRange={1} onPageChange={handleMoreClick} totalPages={totalPages} /> </div> ); export default PokemonList;
def from_networkx(cls, G, layout_function, nodes=None, **kwargs): positions = layout_function(G, **kwargs) edges = G.edges() if nodes: idx_dim = nodes.kdims[-1].name xs, ys = zip(*[v for k, v in sorted(positions.items())]) indices = list(nodes.dimension_values(idx_dim)) edges = [(src, tgt) for (src, tgt) in edges if src in indices and tgt in indices] nodes = nodes.select(**{idx_dim: [eid for e in edges for eid in e]}).sort() nodes = nodes.add_dimension('x', 0, xs) nodes = nodes.add_dimension('y', 1, ys).clone(new_type=Nodes) else: nodes = Nodes([tuple(pos)+(idx,) for idx, pos in sorted(positions.items())]) return cls((edges, nodes))
import random def riffleShuffle(va, flips): nl = va for n in range(flips): #cut the deck at the middle +/- 10%, remove the second line of the formula for perfect cutting cutPoint = len(nl)/2 + random.choice([-1, 1]) * random.randint(0, len(va)/10) # split the deck left = nl[0:cutPoint] right = nl[cutPoint:] del nl[:] while (len(left) > 0 and len(right) > 0): #allow for imperfect riffling so that more than one card can come form the same side in a row #biased towards the side with more cards #remove the if and else and brackets for perfect riffling if (random.uniform(0, 1) >= len(left) / len(right) / 2): nl.append(right.pop(0)) else: nl.append(left.pop(0)) if (len(left) > 0): nl = nl + left if (len(right) > 0): nl = nl + right return nl def overhandShuffle(va, passes): mainHand = va for n in range(passes): otherHand = [] while (len(mainHand) > 0): #cut at up to 20% of the way through the deck cutSize = random.randint(0, len(va) / 5) + 1 temp = [] #grab the next cut up to the end of the cards left in the main hand i=0 while (i<cutSize and len(mainHand) > 0): temp.append(mainHand.pop(0)) i = i + 1 #add them to the cards in the other hand, sometimes to the front sometimes to the back if (random.uniform(0, 1) >= 0.1): #front most of the time otherHand = temp + otherHand else: otherHand = otherHand + temp #move the cards back to the main hand mainHand = otherHand return mainHand print "Riffle shuffle" nums = [x+1 for x in range(21)] print nums print riffleShuffle(nums, 10) print print "Riffle shuffle" nums = [x+1 for x in range(21)] print nums print riffleShuffle(nums, 1) print print "Overhand shuffle" nums = [x+1 for x in range(21)] print nums print overhandShuffle(nums, 10) print print "Overhand shuffle" nums = [x+1 for x in range(21)] print nums print overhandShuffle(nums, 1) print print "Library shuffle" nums = [x+1 for x in range(21)] print nums random.shuffle(nums) print nums print
/** * @author Christopher Butler */ public class DefaultCloseAction extends ViewAction { public DefaultCloseAction() { } public void actionPerformed(View view, ActionEvent evt) { DockingManager.close(view); } }
<filename>packages/db/src/books.spec.ts import { books } from "./books"; describe("books", () => { describe("quotes", () => { it("should all have a uniq id", () => { const uniqIds = new Set(); const ids = books.flatMap((b) => b.quotes || []).map((q) => q.id); ids.forEach((id) => { if (uniqIds.has(id)) throw duplicatedId(id); uniqIds.add(id); }); function duplicatedId(id: string) { return new Error( `at least two quotes have the same id "${id}"` ); } }); }); });
def process_channel(processor: PostProcessor, start: datetime, stop: datetime, downloader=TimeSeriesDict.get) -> str: channel_file, filename = path2h5file(get_path(f'{processor.channel} {start}', 'hdf5')) logger.debug(f'Initiated hdf5 stream to {filename}') num_strides = (stop - start) // processor.stride_length strides = [[start + processor.stride_length * i, start + processor.stride_length * (i + 1)] for i in range(num_strides)] for stride_start, stride_stop in strides: if data_exists(processor.output_channels, to_gps(stride_stop).seconds, channel_file): continue logger.debug(f'Initiating data download for {processor.channel} ({stride_start} to {stride_stop})') segments = [[int(s.start), int(s.end)] for s in DataQualityFlag.query('L1:DMT-ANALYSIS_READY:1', to_gps(stride_start), to_gps(stride_stop)).active ] if processor.respect_segments else [[to_gps(stride_start).seconds, to_gps(stride_stop).seconds]] raw_segments = list() for seg_start, seg_stop in segments: try: raw_segments.append([downloader([processor.channel], start=seg_start, end=seg_stop + processor.extra_seconds), seg_start]) except RuntimeError: logger.warning(f'SKIPPING download for {processor.channel} ({stride_start} to {stride_stop}) !!') logger.info(f'Completed data download for {processor.channel} ({stride_start} to {stride_stop})') for raw, segment_start in raw_segments: finished_segment = processor.compute(raw[processor.channel]) logger.info(f'Generated {processor.__class__.__name__} for {processor.channel}') write_to_disk(finished_segment, segment_start, channel_file) logger.info(f'Completed stride {stride_start} to {stride_stop})') logger.debug(f'Completed channel at {filename}') return filename
#include "benchmark/benchmark.h" #include "binary-search-tree.h" void test_binary_tree_search (void) { int search_target = 8; std::string tree_elements = ""; BinarySearchTree *bst_tree = new BinarySearchTree(); BSTNode *head = bst_tree->create_node(1); BSTNode *node1 = bst_tree->create_node(2); BSTNode *node2 = bst_tree->create_node(3); BSTNode *node3 = bst_tree->create_node(4); BSTNode *node4 = bst_tree->create_node(5); BSTNode *node5 = bst_tree->create_node(6); BSTNode *node6 = bst_tree->create_node(7); BSTNode *node7 = bst_tree->create_node(8); bst_tree->insert_node(head, node1); bst_tree->insert_node(head, node2); bst_tree->insert_node(head, node3); bst_tree->insert_node(head, node4); bst_tree->insert_node(head, node5); bst_tree->insert_node(head, node6); bst_tree->insert_node(head, node7); bst_tree->inorder_print_tree (&tree_elements, head); tree_elements = ""; bst_tree->remove_node(head, 2); bst_tree->remove_node(head, 4); bst_tree->remove_node(head, 7); bst_tree->inorder_print_tree (&tree_elements, head); // test search BSTNode *test_search = bst_tree->search_node(head, search_target); bst_tree->destroy_tree(head); } static void BM_BinarySearchTree(benchmark::State& state) { // Perform setup here for (auto _ : state) { // This code gets timed test_binary_tree_search(); } } // Register the function as a benchmark BENCHMARK(BM_BinarySearchTree); // Run the benchmark BENCHMARK_MAIN();
#include <stdio.h> #include <stdlib.h> #include <string.h> int main (void){ char string[] = "test program for teii"; printf("%s\n", string); char *found = strstr(string,"dpii"); if (found){ printf("%s\n",found); found[0]='p'; found[1]='s'; found[2]='e'; found[3]='r'; } else printf("No match was found\n"); printf("%s\n",string); return 0; }
package com.fundynamic.d2tm.game.controls; import com.fundynamic.d2tm.game.entities.Entity; import com.fundynamic.d2tm.game.entities.EntityRepository; import com.fundynamic.d2tm.game.entities.Player; import com.fundynamic.d2tm.game.map.Cell; import com.fundynamic.d2tm.game.rendering.Viewport; import com.fundynamic.d2tm.graphics.ImageRepository; import com.fundynamic.d2tm.math.Vector2D; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import java.util.HashMap; import java.util.Map; public class Mouse { public enum MouseImages { NORMAL, HOVER_OVER_SELECTABLE_ENTITY, MOVE, ATTACK, CUSTOM } private final Player controllingPlayer; private final GameContainer gameContainer; private final EntityRepository entityRepository; private Viewport viewport; private MouseBehavior mouseBehavior; private Entity lastSelectedEntity; private Cell hoverCell; private MouseImages currentImage; private Map<MouseImages, Image> mouseImages = new HashMap<>(); Mouse(Player controllingPlayer, GameContainer gameContainer, EntityRepository entityRepository) { this.controllingPlayer = controllingPlayer; this.entityRepository = entityRepository; this.gameContainer = gameContainer; } public static Mouse create(Player player, GameContainer gameContainer, EntityRepository entityRepository, ImageRepository imageRepository) throws SlickException { Mouse mouse = new Mouse(player, gameContainer, entityRepository); mouse.addMouseImage(Mouse.MouseImages.NORMAL, imageRepository.loadAndCache("mouse/mouse_normal.png")); mouse.addMouseImage(Mouse.MouseImages.HOVER_OVER_SELECTABLE_ENTITY, imageRepository.loadAndCache("mouse/mouse_pick.png")); mouse.addMouseImage(Mouse.MouseImages.MOVE, imageRepository.loadAndCache("mouse/mouse_move.png")); mouse.addMouseImage(Mouse.MouseImages.ATTACK, imageRepository.loadAndCache("mouse/mouse_attack.png")); mouse.init(); return mouse; } public void init() { this.mouseBehavior = new NormalMouse(this); this.hoverCell = null; } // TODO make mouse implement Renderable interface? public void render(Graphics graphics) { mouseBehavior.render(graphics); } /** * When a left click (== press and release) has been detected, this method is called. */ public void leftClicked() { mouseBehavior.leftClicked(); } /** * When a right click (== press and release) has been detected, this method is called. */ public void rightClicked() { mouseBehavior.rightClicked(); } /** * This method is called to update the mouse (and its associated behavior) state. Notifying that * the mouse has been moved to the given cell. * @param cell */ public void mouseMovedToCell(Cell cell) { mouseBehavior.mouseMovedToCell(cell); } public void setMouseBehavior(MouseBehavior mouseBehavior) { if (mouseBehavior == null) throw new IllegalArgumentException("MouseBehavior argument may not be null!"); System.out.println("Mouse behavior changed into " + mouseBehavior); this.mouseBehavior = mouseBehavior; } public Entity getLastSelectedEntity() { return lastSelectedEntity; } public void setLastSelectedEntity(Entity lastSelectedEntity) { this.lastSelectedEntity = lastSelectedEntity; } public Cell getHoverCell() { return hoverCell; } public void setHoverCell(Cell hoverCell) { this.hoverCell = hoverCell; } public Player getControllingPlayer() { return controllingPlayer; } public void leftButtonReleased() { mouseBehavior.leftButtonReleased(); } public void draggedToCoordinates(int newX, int newY) { mouseBehavior.draggedToCoordinates(Vector2D.create(newX, newY)); } public void setMouseImage(Image image, int hotSpotX, int hotSpotY) { if (image == null) throw new IllegalArgumentException("Image to set for mouse cursor may not be null!"); if (!mouseImages.containsValue(image)) { this.currentImage = MouseImages.CUSTOM; } try { gameContainer.setMouseCursor(image, hotSpotX, hotSpotY); } catch (SlickException e) { throw new CannotSetMouseCursorException(e); } } public void setMouseImageHotSpotCentered(Image image) { if (image == null) throw new IllegalArgumentException("Image to set for mouse cursor may not be null!"); if (!mouseImages.containsValue(image)) { this.currentImage = MouseImages.CUSTOM; } try { gameContainer.setMouseCursor(image, image.getWidth() / 2, image.getHeight() / 2); } catch (SlickException e) { throw new CannotSetMouseCursorException(e); } } public void setMouseImage(MouseImages key, int hotSpotX, int hotSpotY) { if (key.equals(this.currentImage)) return; this.currentImage = key; setMouseImage(mouseImages.get(key), hotSpotX, hotSpotY); } public void addMouseImage(MouseImages key, Image image) { if (image == null) throw new IllegalArgumentException("Image for mouse images cannot be null!"); this.mouseImages.put(key, image); } public MouseBehavior getMouseBehavior() { return this.mouseBehavior; } public EntityRepository getEntityRepository() { return entityRepository; } public Viewport getViewport() { return viewport; } public void setViewport(Viewport viewport) { this.viewport = viewport; } public void movedTo(Vector2D position) { viewport.tellAboutNewMousePositions(position.getXAsInt(), position.getYAsInt()); com.fundynamic.d2tm.game.map.Map map = viewport.getMap(); Vector2D coordinates = viewport.translateScreenToAbsoluteMapPixels(position); mouseMovedToCell(map.getCellByAbsoluteMapCoordinates(coordinates)); } }
import { ObjectId } from "mongodb" /** * @description 음원의 도큐먼트 인터페이스 * @prop {ObjectId} audioId Document의 고유 아이디 * @prop {string} userId 유저 아이디 * @prop {string} url 음원 경로 * @prop {string} title 음원 제목 * @prop {string} filter 음원 필터 * @prop {number} views 음원 조회수 * @prop {number} duration 음원 길이 */ export interface AudioEntity { audioId: ObjectId userId: string url: string title: string filter: "Default" | "NightCore" | "Stereo" | "NoiseFilter" views: number duration: number } /** * @description 폴더의 도큐먼트 인터페이스 * @prop {ObjectId} folderId Document의 고유 아이디 * @prop {string} creator 폴더 생성자 아이디 * @prop {string} folderName 폴더 이름 * @prop {number} likes 좋아요 수 * @prop {Date} updatedAt 최근 업데이트 날짜 * @prop {Date} createdAt 생성 날짜 * @prop {boolean | undefined} likeStatus 좋아요 상태 * */ export interface FolderEntity { folderId: ObjectId creator: string folderName: string likes: number updatedAt: Date createdAt: Date likeStatus?: boolean } /** * @description 폴더내에 파일의 도큐먼트 인터페이스 * @prop {ObjectId} _id Document의 고유 아이디 * @prop {ObjectId} folderId 폴더 아이디 * @prop {ObjectId} audioId 음원 아이디 */ interface FileEntity { _id: ObjectId folderId: ObjectId audioId: ObjectId }
/** * A scriptable Diffusion subscriber. * <p> * Reads a list of actions from a configuration file and performs those actions at the user-specified times. * * @author adam */ public class Subscriber { // Do we want human or machine-readable statistics output? // Machine-readable is in the style of nmon, ultimately processed by a tool // such as Kabana. public enum OutputFormat { HUMAN, MACHINE } public static final Logger LOGGER = LoggerFactory.getLogger("subscriber"); public static final Random RANDOM = new Random(); public static final ConcurrentHashMap<SessionId, Session> ACTIVE_SESSIONS = new ConcurrentHashMap<>(); public static final ScheduledExecutorService DEFAULT_SCHEDULED_EXECUTOR = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors()); public static StatsCollector STATS_COLLECTOR; private final ExecutorService actionExecutorPool = Executors.newCachedThreadPool(); private String configFile; private OptionSet options; public Subscriber() { RANDOM.setSeed(System.currentTimeMillis()); } /** * Main entry point. * * @param args command-line arguments * @throws Exception */ public static void main(String[] args) throws Exception { final int rc; final Subscriber subscriber = new Subscriber(); subscriber.parseOptions(args); subscriber.start(); rc = subscriber.waitUntilDone(); Subscriber.STATS_COLLECTOR.stop(); Subscriber.STATS_COLLECTOR.printSummary(); Subscriber.STATS_COLLECTOR.terminate(); LOGGER.info("Subscriber has been stopped"); System.exit(rc); } /** * Load configuration and start the appropriate number of threads for reading and performing actions. */ private void start() { STATS_COLLECTOR.getStatistics().setStartTime(); // Load config file and get a list of Executors, one per Action. ConfigLoader cfgLoader = new ConfigLoader(configFile, options); List<ActionExecutor> actionExecutors = cfgLoader.loadActionExecutors(); LOGGER.info("Starting action executors"); // Start up all the action executors. actionExecutors.forEach(actionExecutorPool::execute); // Don't allow any more action executors to start. actionExecutorPool.shutdown(); } /** * Blocks until all action executors have terminated. * * @return 0 on controlled shutdown, -1 on unexpected shutdown. */ private int waitUntilDone() { try { do { } while (actionExecutorPool.awaitTermination(60, TimeUnit.SECONDS) == false); } catch (InterruptedException ex) { LOGGER.trace("Interrupted while waiting for action executors to terminate"); return -1; } return 0; } private void parseOptions(String args[]) throws IOException { OptionParser optionParser = new OptionParser(); optionParser.acceptsAll(Arrays.asList("f", "filename"), "Write stats to the named file. Implies -m unless overridden." + " A value of \"-\" writes to stdout." + " If no value is specified, a unique filename is automatically generated.") .withRequiredArg() .ofType(String.class); optionParser.acceptsAll(Arrays.asList("o", "url"), "Default URL of Diffusion server") .withRequiredArg() .ofType(String.class) .defaultsTo("ws://localhost:8080"); optionParser.acceptsAll(Arrays.asList("p", "principal"), "Default principal (username)") .withRequiredArg() .ofType(String.class); optionParser.acceptsAll(Arrays.asList("s", "password"), "Default credentials (password)") .withRequiredArg() .ofType(String.class); optionParser.acceptsAll(Arrays.asList("h", "human"), "Human-readable output"); optionParser.acceptsAll(Arrays.asList("m", "machine"), "Machine-readable output"); optionParser.acceptsAll(Arrays.asList("c", "config"), "Filename containing test configuration") .withRequiredArg() .ofType(String.class) .defaultsTo("script.json"); optionParser.acceptsAll(Arrays.asList("u", "updaterate"), "Rate at which the statistics are output, in milliseconds") .withRequiredArg() .ofType(Long.class) .defaultsTo(1000L); optionParser.acceptsAll(Arrays.asList("?", "help"), "Show help") .forHelp(); options = optionParser.parse(args); if (options.has("help") || args.length == 0) { optionParser.printHelpOn(System.out); System.exit(0); } OutputFormat outputFormat = OutputFormat.HUMAN; if (options.has("filename")) { outputFormat = OutputFormat.MACHINE; } if (options.has("human")) { outputFormat = OutputFormat.HUMAN; } else if (options.has("machine")) { outputFormat = OutputFormat.MACHINE; } configFile = (String) options.valueOf("config"); STATS_COLLECTOR = new StatsCollector((Long) options.valueOf("updaterate"), (String) options.valueOf("filename"), outputFormat); } }
/// Writing the hash move.toml to file fn store_manifest_checksum(ctx: &Context) -> Result<()> { let build_path = ctx.project_dir.join("build"); if !build_path.exists() { fs::create_dir_all(&build_path)?; } let path_version = build_path.join(HASH_FILE_NAME); if path_version.exists() { fs::remove_file(&path_version)?; } fs::write(&path_version, ctx.manifest_hash.to_string())?; Ok(()) }
Macular Sequelae Following Exudative Retinal Detachment After Laser Photocoagulation for Retinopathy of Prematurity. BACKGROUND AND OBJECTIVE To report a series of exudative retinal detachments (ERDs) following laser photocoagulation for retinopathy of prematurity (ROP). PATIENTS AND METHODS Retrospective case series. RESULTS Eleven eyes of seven infants were identified who developed ERD following laser. Median gestation age was 25 weeks (interquartile range : 24-27 weeks), and median birth weight was 662 grams (IQR: 538-850 grams). Median postmenstrual age at time of laser was 35 weeks (IQR: 33-39 weeks). ERD was diagnosed at a median of 7 days (IQR: 5-7 days) after laser and was managed with steroids. Bevacizumab was also used for certain cases. Time to resolution ranged from 1 to 5 weeks. Macular pigment changes, atrophy, window defect on fluorescein angiography, and photoreceptor loss on optical coherence tomography were noted in some cases following ERD resolution. Excluding one patient who expired at 3 months, median length of follow-up was 10 years (IQR: 9-13.5 years). Overall, only one patient, who presented with less severe ERD, had normal vision. CONCLUSIONS ERD is an uncommonly reported complication following laser for ROP. Macular changes following ERD resolution may have negative visual consequences. .
<reponame>phatblat/macOSPrivateFrameworks // // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSObject.h" @interface VCPGaborFilter : NSObject { struct Kernel **_filterBanks; int _numScales; int _numOrientations; int _num; } - (int)createGaborFilterKernel:(struct Kernel)arg1 sigmaX:(float)arg2 sigmaY:(float)arg3 lambda:(float)arg4 thetaInDegree:(float)arg5 phaseInDegree:(float)arg6; - (int)processWithFilterScaleIdx:(int)arg1 orientIdx:(int)arg2 srcImage:(const float *)arg3 outImage:(float *)arg4 width:(unsigned long long)arg5 height:(unsigned long long)arg6; - (void)dealloc; - (id)initWithNumberOfScales:(int)arg1 numOfOrientations:(int)arg2 width:(unsigned long long)arg3 height:(unsigned long long)arg4; @end
/// Return the the push shuffles in the execution plan, shuffle writer should be the root node fn find_push_shuffle(plan: &Arc<dyn ExecutionPlan>) -> Option<ShuffleWriterExec> { if let Some(shuffle_writer) = plan.as_any().downcast_ref::<ShuffleWriterExec>() { if shuffle_writer.is_push_shuffle() { Some(shuffle_writer.clone()) } else { None } } else { None } }
// WithConfig sets the OAuth configs on the Options struct func WithConfig(c config.OAuth) Option { return func(o *Options) { o.Config = c } }
<reponame>ogrisel/mahout /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.mahout.cf.taste.hadoop.similarity.item; import java.io.IOException; import org.apache.hadoop.mapreduce.Mapper; import org.apache.mahout.cf.taste.hadoop.similarity.CoRating; import org.apache.mahout.math.VarLongWritable; /** * map out each pair of items that appears in the same user-vector together with the multiplied vector lengths * of the associated item vectors */ public final class CopreferredItemsMapper extends Mapper<VarLongWritable,ItemPrefWithItemVectorWeightArrayWritable,ItemPairWritable,CoRating> { @Override protected void map(VarLongWritable user, ItemPrefWithItemVectorWeightArrayWritable itemPrefsArray, Context context) throws IOException, InterruptedException { ItemPrefWithItemVectorWeightWritable[] itemPrefs = itemPrefsArray.getItemPrefs(); for (int n = 0; n < itemPrefs.length; n++) { ItemPrefWithItemVectorWeightWritable itemN = itemPrefs[n]; long itemNID = itemN.getItemID(); double itemNWeight = itemN.getWeight(); float itemNValue = itemN.getPrefValue(); for (int m = n + 1; m < itemPrefs.length; m++) { ItemPrefWithItemVectorWeightWritable itemM = itemPrefs[m]; long itemAID = Math.min(itemNID, itemM.getItemID()); long itemBID = Math.max(itemNID, itemM.getItemID()); ItemPairWritable pair = new ItemPairWritable(itemAID, itemBID, itemNWeight, itemM.getWeight()); context.write(pair, new CoRating(itemNValue, itemM.getPrefValue())); } } } }
/* * lane_detach -- detaches the currently held lane from the current thread */ unsigned lane_detach(PMEMobjpool *pop) { struct lane_info *lane = get_lane_info_record(pop); lane->nest_count -= 1; ASSERTeq(lane->nest_count, 0); return (unsigned)lane->lane_idx; }
def pre_spawn_start(self, user, spawner): if not self.enable_auth_state: return auth_state = yield user.get_auth_state() gh_user = auth_state.get("github_user") gh_token = auth_state.get("access_token") if gh_user: gh_id = gh_user.get("id") gh_org = yield self._get_user_organizations(gh_token) gh_email = gh_user.get("email") if not gh_email: gh_email = yield self._get_user_email(gh_token) if gh_email: spawner.environment['GITHUB_EMAIL'] = gh_email gh_login = gh_user.get("login") gh_name = gh_user.get("name") or gh_login if gh_id: spawner.environment['EXTERNAL_UID'] = str(gh_id) if gh_org: orglstr = "" for k in gh_org: if orglstr: orglstr += "," orglstr += k + ":" + str(gh_org[k]) spawner.environment['EXTERNAL_GROUPS'] = orglstr if gh_name: spawner.environment['GITHUB_NAME'] = gh_name if gh_login: spawner.environment['GITHUB_LOGIN'] = gh_login if gh_token: spawner.environment['GITHUB_ACCESS_TOKEN'] = "[secret]" self.log.info("Spawned environment: %s", json.dumps( spawner.environment, sort_keys=True, indent=4)) spawner.environment['GITHUB_ACCESS_TOKEN'] = gh_token
/** * Creates instance of Round from string source * * @param line string with data * @return instance of Round */ public Round parseToRound(String line) { List<String> splitLine = Stream.of(line.split(";")).map(String::new) .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); int tmpYear = Integer.parseInt(splitLine.get(0)); int tmpWeek = Integer.parseInt(splitLine.get(1)); String tmpRound = splitLine.get(2); DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy.MM.dd."); LocalDate tmpDate = (splitLine.get(3).isEmpty()) ? null : LocalDate.parse(splitLine.get(3), pattern); List<Hit> tmpHitList = new ArrayList<>(); for (int i = 4, j = 14; i < 14; i += 2, j--) { tmpHitList.add(this.parseToHit(j, splitLine.get(i), splitLine.get(i + 1))); } List<Outcome> tmpGameResult = new ArrayList<>(); for (int i = 14; i < 28; i++) { tmpGameResult.add(Outcome.getOutcome(splitLine.get(i))); } return new Round(tmpYear, tmpWeek, tmpRound, tmpDate, tmpHitList, tmpGameResult); }
/** * Validate a war level override of the * java2ClassLoadingComplianceOverride flag to true with a * useJBossWebLoader = false * * @throws Exception */ public void testJava2ClassLoadingComplianceOverride() throws Exception { getLog().info("+++ Begin testJava2ClassLoadingComplianceOverride"); deploy("class-loading.war"); try { String baseURL = "http://" + getServerHost() + ":" + Integer.getInteger("web.port", 8080) + '/'; URL url = new URL(baseURL+"class-loading/ClasspathServlet2?class=org.apache.log4j.net.SocketAppender"); HttpMethodBase request = HttpUtils.accessURL(url, REALM, HttpURLConnection.HTTP_OK); Header cs = request.getResponseHeader("X-CodeSource"); log.info(cs); assertTrue("X-CodeSource("+cs+") does not contain war", cs.getValue().indexOf(".war") < 0 ); getLog().debug(url+" OK"); } finally { undeploy("class-loading.war"); getLog().info("+++ End testJava2ClassLoadingComplianceOverride"); } }
def int_arg(v): try: return int(v) except ValueError: raise ViewExceptionRest( 'Invalid argument format. %s must be an integer.' % (repr(v),), 400 )
<filename>src/main/java/arekkuusu/implom/common/block/BlockKondenzator.java /* * Arekkuusu / Improbable plot machine. 2018 * * This project is licensed under the MIT. * The source code is available on github: * https://github.com/ArekkuusuJerii/Improbable-plot-machine */ package arekkuusu.implom.common.block; import arekkuusu.implom.api.util.IPMMaterial; import arekkuusu.implom.client.util.ResourceLibrary; import arekkuusu.implom.client.util.baker.DummyModelRegistry; import arekkuusu.implom.client.util.baker.model.ModelRendered; import arekkuusu.implom.client.util.helper.ModelHelper; import arekkuusu.implom.common.block.base.BlockBaseFacing; import arekkuusu.implom.common.block.tile.TileKondenzator; import arekkuusu.implom.common.lib.LibNames; import com.google.common.collect.ImmutableMap; import net.katsstuff.teamnightclipse.mirror.client.baked.BakedPerspective; import net.katsstuff.teamnightclipse.mirror.data.Vector3; import net.minecraft.block.BlockDirectional; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.ItemCameraTransforms; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumBlockRenderType; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.model.TRSRTransformation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nullable; /* * Created by <Arekkuusu> on 8/9/2018. * It's distributed as part of Improbable plot machine. */ @SuppressWarnings("deprecation") public class BlockKondenzator extends BlockBaseFacing { private static final ImmutableMap<EnumFacing, AxisAlignedBB> BB_MAP = FacingAlignedBB.create( new Vector3(1, 12, 1), new Vector3(15, 15, 15), EnumFacing.UP ).build(); public BlockKondenzator() { super(LibNames.KONDENZATOR, IPMMaterial.MONOLITH); setDefaultState(getDefaultState().withProperty(BlockDirectional.FACING, EnumFacing.DOWN)); setHarvestLevel(Tool.PICK, ToolLevel.STONE); setHardness(1F); } @Override public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { return getTile(TileKondenzator.class, world, pos).map(t -> t.add(player.getHeldItem(hand))).orElse(false); } @Override public EnumBlockRenderType getRenderType(IBlockState state) { return EnumBlockRenderType.ENTITYBLOCK_ANIMATED; } @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { EnumFacing facing = state.getValue(BlockDirectional.FACING); return BB_MAP.getOrDefault(facing, FULL_BLOCK_AABB); } @Override public boolean isFullCube(IBlockState state) { return false; } @Override public boolean isOpaqueCube(IBlockState state) { return false; } @Override public boolean hasTileEntity(IBlockState state) { return true; } @Nullable @Override public TileEntity createTileEntity(World world, IBlockState state) { return new TileKondenzator(); } @Override @SideOnly(Side.CLIENT) public void registerModel() { DummyModelRegistry.register(this, new ModelRendered() .setTransforms(ImmutableMap.<ItemCameraTransforms.TransformType, TRSRTransformation>builder() .put(ItemCameraTransforms.TransformType.GUI, BakedPerspective.mkTransform(0F, -6F, 0F, 30F, 45F, 0F, 0.63F)) .put(ItemCameraTransforms.TransformType.THIRD_PERSON_RIGHT_HAND, BakedPerspective.mkTransform(0F, -2.5F, 0F, 75F, 45F, 0F, 0.38F)) .put(ItemCameraTransforms.TransformType.THIRD_PERSON_LEFT_HAND, BakedPerspective.mkTransform(0F, -2.5F, 0F, 75F, 45F, 0F, 0.38F)) .put(ItemCameraTransforms.TransformType.FIRST_PERSON_RIGHT_HAND, BakedPerspective.mkTransform(0F, -3F, 0F, 0F, 45F, 0F, 0.38F)) .put(ItemCameraTransforms.TransformType.FIRST_PERSON_LEFT_HAND, BakedPerspective.mkTransform(0F, -3F, 0F, 0F, 225F, 0F, 0.38F)) .put(ItemCameraTransforms.TransformType.GROUND, BakedPerspective.mkTransform(0F, -4.5F, 0F, 0F, 0F, 0F, 0.25F)) .put(ItemCameraTransforms.TransformType.FIXED, BakedPerspective.mkTransform(0F, 0, 4F, 90F, 0F, 0F, 0.5F)) .build() ).setParticle(ResourceLibrary.KONDENZATOR) ); ModelHelper.registerModel(this, 0, ""); } public static class ImbuingConstants { public static final int IMBUING_INCREASE_INTERVAL = 40; public static final int IMBUING_DECREASE_INTERVAL = 80; public static final int IMBUING_CAPACITY = 100; public static final int IMBUING_TIME = 100; } }
import React from 'react'; import type { Text as RNText } from 'react-native'; import Icon, { IconProps } from './Component'; import type { ThemeProps } from '../../../theme'; const ThemedIcon = React.forwardRef< RNText, IconProps & Partial<ThemeProps<IconProps>> >((props, ref) => { return <Icon {...props} ref={ref} />; }); ThemedIcon.displayName = 'Icon'; export default ThemedIcon;
/** * Used to be able to change the behaviour of the palette view pane * from being the content pane of a CoScrolledHorizontalFlowPanel to * be a ordinary panel in a srollpane. * This method should set m_palettePanel and return the CoPanel holding m_palettePanel * Creation date: (2001-10-30 10:52:12) * @return com.bluebrim.swing.client.CoPanel */ public JComponent createPalettePanel() { CoScrolledHorizontalFlowPanel sp = new CoScrolledHorizontalFlowPanel(); m_palettePanel = sp.getContentPane(); return sp; }
/** * @author Sri Harsha Chilakapati */ class DictionaryJSO extends JavaScriptObject { protected DictionaryJSO() { } public static native DictionaryJSO create() /*-{ return {}; }-*/; public final native void define(String name, String property) /*-{ this[name] = property; }-*/; public final native void define(String name, boolean property) /*-{ this[name] = property; }-*/; }
def begin_runs(self): self.keithley.write(":SOUR:VOLT:SWE:INIT") self.result = self.keithley.query(":READ?") self.yvalues = np.array(self.keithley.query_ascii_values(":FETC?")) self.curr = np.array(self.yvalues[0::2]) self.vso = np.array(self.yvalues[1::2])
def deepmac_proto_to_params(deepmac_config): loss = losses_pb2.Loss() loss.localization_loss.weighted_l2.CopyFrom( losses_pb2.WeightedL2LocalizationLoss()) loss.classification_loss.CopyFrom(deepmac_config.classification_loss) classification_loss, _, _, _, _, _, _ = (losses_builder.build(loss)) deepmac_field_class = ( center_net_pb2.CenterNet.DESCRIPTOR.nested_types_by_name[ 'DeepMACMaskEstimation']) params = {} for field in deepmac_field_class.fields: value = getattr(deepmac_config, field.name) if field.enum_type: params[field.name] = field.enum_type.values_by_number[value].name.lower() else: params[field.name] = value params['roi_jitter_mode'] = params.pop('jitter_mode') params['classification_loss'] = classification_loss return DeepMACParams(**params)
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleContexts #-} module UseHaskellAPITypes where import Data.Aeson import Data.Aeson.TH import Data.Bson.Generic import GHC.Generics -- | System data types. -- | Data type used to store user's credentials after login. data Details = Details { clientKey :: String , clientName :: String , clientSesh :: String , clientTicket :: String , clientExpiry :: String } deriving (Show, Eq, Generic, FromJSON, ToJSON, ToBSON, FromBSON) -- | Generic one element message data StrWrap = StrWrap { aVal :: String } deriving (Show, Eq, Generic, FromJSON, ToJSON, ToBSON, FromBSON) -- | Generic two element message. data Message = Message { name :: String , message :: String } deriving (Show, Eq, Generic, FromJSON, ToJSON, ToBSON, FromBSON) -- | Generic three element message. data Message3 = Message3 { one :: String , two :: String , three :: String } deriving (Show, Eq, Generic, FromJSON, ToJSON, ToBSON, FromBSON) -- | Generic four element message. data Message4 = Message4 { val1 :: String , val2 :: String , val3 :: String , val4 :: String } deriving (Show, Eq, Generic, FromJSON, ToJSON, ToBSON, FromBSON) -- | Type to identify transaction owner. data CurrentTrans = CurrentTrans { tOwner :: String , myTID :: String } deriving (Show, Generic, FromJSON, ToJSON, ToBSON, FromBSON) -- auth stuff data Login = Login { userName :: String , password :: String } deriving (Show, Generic, FromJSON, ToJSON, ToBSON, FromBSON) -- locking stuff data Lock = Lock { fPath :: String , state :: Bool , owner :: String }deriving (Show, Generic, ToJSON, FromJSON, ToBSON, FromBSON) deriving instance FromBSON Bool deriving instance ToBSON Bool -- directory stuff starts here data FileRef = FileRef { fp :: String , myd :: String , fid :: String , fts :: String }deriving (Show, Eq, Generic, ToJSON, FromJSON, ToBSON, FromBSON) -- transaction types for directory service data ShadowRef = ShadowRef { dTID :: String , references :: [FileRef] }deriving (Show, Eq, Generic, ToJSON, FromJSON, ToBSON, FromBSON) data ShadowDirs = ShadowDirs { dTransID :: String , tDirs :: [String] }deriving (Show, Eq, Generic, ToJSON, FromJSON, ToBSON, FromBSON) data SendFileRef = SendFileRef { filePath :: String , myDirectory :: String , fID :: String , fTimeStamp :: String , fServerIP :: String , fServerPort :: String }deriving (Show, Eq, Generic, ToJSON, FromJSON, ToBSON, FromBSON) -- file server data that directory server uses to manage replication process data FsAttributes = FsAttributes { ip :: String , port :: String }deriving (Show, Eq, Generic, ToJSON, FromJSON, ToBSON, FromBSON) data FsInfo = FsInfo { myName :: String , primaryServer :: Maybe FsAttributes , servers :: [FsAttributes] }deriving (Show, Generic, ToJSON, FromJSON, ToBSON, FromBSON) data FileID = FileID { directory :: String , idNum :: String }deriving (Show, Generic, ToJSON, FromJSON, ToBSON, FromBSON) data FsContents = FsContents { dirName :: String , fsFiles :: [String] }deriving (Show, Eq, Generic, ToJSON, FromJSON, ToBSON, FromBSON) -- directory stuff ends here -- transaction stuff starts here data Modification = Modification { fileRef :: SendFileRef , fileContents :: String }deriving (Show, Eq, Generic, ToJSON, FromJSON, ToBSON, FromBSON) -- this data type is upload variation for tServer data FileTransaction = FileTransaction { tID :: String , modification :: Modification , authTicket :: String }deriving (Show, Eq, Generic, ToJSON, FromJSON, ToBSON, FromBSON) -- this data type is stored on transaction server data Transaction = Transaction { transID :: String , modifications :: [Modification] , readyStates :: [String] }deriving (Show, Generic, ToJSON, FromJSON, ToBSON, FromBSON) data TransLocks = TransLocks { tLocksID :: String , tFilePaths :: [String] }deriving (Show, Eq, Generic, ToJSON, FromJSON, ToBSON, FromBSON) data Shadow = Shadow { fTID :: String , file :: Message }deriving (Show, Eq, Generic, ToJSON, FromJSON, ToBSON, FromBSON) data ShadowInfo = ShadowInfo { trID :: String , files :: [Message] }deriving (Show, Generic, ToJSON, FromJSON, ToBSON, FromBSON) -- transaction stuff ends here deriving instance FromBSON String deriving instance ToBSON String deriving instance FromBSON [Message] deriving instance ToBSON [Message] deriving instance FromBSON [String] deriving instance ToBSON [String] deriving instance FromBSON [Modification] deriving instance ToBSON [Modification] deriving instance FromBSON [FsAttributes] deriving instance ToBSON [FsAttributes] deriving instance FromBSON [FileRef] deriving instance ToBSON [FileRef] deriving instance FromBSON [FsContents] deriving instance ToBSON [FsContents] deriving instance FromBSON (Maybe FsAttributes) deriving instance ToBSON (Maybe FsAttributes) -- | We will also define a simple data type for returning data from a REST call. data ResponseData = ResponseData { response :: String } deriving (Generic, ToJSON, FromJSON,FromBSON, Show)
<reponame>emilybache/GildedRose-Approval-Kata-sample-solution package com.gildedrose; import java.io.FileNotFoundException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.ArrayList; import com.csvreader.CsvReader; /** * This test fixture allows you to test the method 'updateQuality' in the GildedRose class * using TextTest (see http://texttest.org) * * It expects to find a csv file in the current working directory called 'items.csv'. It parses this file * to populate a list of items. It then calls 'updateQuality' on the list and prints the result. * * You may also pass a command line argument, which should be an integer indicating how many times to call * 'updateQuality' if you want it to do it more than once, to simulate several days worth of updates. */ public class TexttestFixture { public static void main(String[] args) throws Exception { System.out.println("OMGHAI!"); List<Item> items = new ArrayList<>(); Path csvFile = Paths.get("items.csv"); if (Files.exists(csvFile)) { CsvReader itemsCsv = new CsvReader("items.csv"); itemsCsv.readHeaders(); while (itemsCsv.readRecord()) { String name = itemsCsv.get("Name"); int sellIn = Integer.parseInt(itemsCsv.get("sellIn")); int quality = Integer.parseInt(itemsCsv.get("quality")); items.add(new Item(name, sellIn, quality)); } } Item[] itemsArr = new Item[items.size()]; GildedRose app = new GildedRose(items.toArray(itemsArr)); int days = 1; if (args.length > 0) { days = Integer.parseInt(args[0]) + 1; } for (int i = 0; i < days; i++) { System.out.println("-------- day " + i + " --------"); System.out.println("name, sellIn, quality"); for (Item item : items) { System.out.println(item); } System.out.println(); app.updateQuality(); } } }
{-# LANGUAGE RecordWildCards, DeriveGeneric, OverloadedStrings, DuplicateRecordFields #-} module FixMigration where import Database.MySQL.Base import Util hiding(prod_conn); import Lib; import Model import qualified Data.List as DL import Text.Parsec; import Data.Text as DT hiding(filter, map, all, head, zipWith) import Data.Text.Format import qualified Data.Text.Lazy as DTL import Data.Text.Encoding as DE import qualified Data.Text.IO as TIO import Data.ByteString.Lazy (fromStrict, toStrict) import TextShow import Data.Maybe import Data.Monoid import Data.String import qualified Data.HashMap as HM import Control.Monad import Control.Exception import System.IO online_conn = connect defaultConnectInfo { ciHost = "10.9.119.247" , ciUser = "shiva" , ciPassword = "<PASSWORD>" , ciDatabase = encodeUtf8 "shiva_console" } -- prod_conn = new_conn prod_conn = online_conn all_table_relative :: IO [Integer] all_table_relative = do lists <- bracket online_conn close $ \c -> do rows <- query_rows c "SELECT DISTINCT RelativeID FROM TableVersionMeta" return $ Prelude.map (getInt . head) rows return lists fix_table_version :: Integer -> IO () fix_table_version rid = do lists <- bracket online_conn close $ \c -> do ps <- prepareStmt c "SELECT Version, Columns, Indices, LastColumnId, LastIndexId FROM TableVersionMeta WHERE RelativeID = ?" rows <- query_rows_stmt c ps [toMySQLValue rid] return $ Prelude.map decode_row rows let col_mp = DL.foldl setup_col_map HM.empty $ map (\(_, b, _, _, _) -> b) lists idx_mp = DL.foldl setup_idx_map HM.empty $ map (\(_, _, c, _, _) -> c) lists col_mp' = fix_id col_mp idx_mp' = fix_id idx_mp lists' = map (convert_version col_mp' idx_mp') lists forM_ lists' $ \(v, co, i, lcid, liid) -> do bracket online_conn close $ \c -> do let col = encode' co idx = encode' i ps <- prepareStmt c "UPDATE TableVersionMeta SET Columns = ?, Indices = ?, LastColumnId = ?, LastIndexId = ? WHERE RelativeID = ? AND Version = ?" executeStmt c ps [toMySQLValue col, toMySQLValue idx, toMySQLValue lcid, toMySQLValue liid, toMySQLValue rid, toMySQLValue v] -- putStrLn $ show $ DL.sortBy (\a b -> compare (snd a) (snd b)) $ HM.toList $ col_mp' file <- openFile "fix_table.txt" WriteMode forM_ lists' $ \(v, c, i, lcid, liid) -> do hPutStrLn file $ show v hPutStrLn file $ unpack $ encode' c hPutStrLn file $ unpack $ encode' i hPutStrLn file $ show lcid hPutStrLn file $ show liid return () where fix_id mp = let maxid = HM.fold max 0 mp id_map = HM.foldWithKey (\k v r -> if HM.member v r then r else HM.insert v k r) HM.empty mp (mid', mp') = HM.foldWithKey (\k v (mid, r) -> if id_map HM.! v == k then (mid, r) else (mid + 1, HM.insert k (mid + 1) r)) (maxid, mp) mp in mp' decode_row :: [MySQLValue] -> (Integer, [Col], [Index], Integer, Integer) decode_row [a, b, c, d, e] = (getInt a, cols, indices, getInt d,getInt e) where cols = either error Prelude.id $ decode' $ getText b indices = either error Prelude.id $ decode' $ getText c setup_col_map m cols = DL.foldl setup_one_col m cols setup_one_col m Col{..} = if HM.member name m then m else HM.insert name idNum m setup_idx_map m indices = DL.foldl setup_one_idx m indices setup_one_idx m Index{..} = if HM.member name m then m else HM.insert name idNum m convert_version col_mp idx_mp (version, cols, indices, _, _) = (version, cols', indices', lcid', liid') where col_id Col{..} = idNum cols' = DL.sortBy (\a b -> compare (col_id a) (col_id b)) $ map (convert_col col_mp) cols idx_id Index{..} = idNum indices' = DL.sortBy (\a b -> compare (idx_id a) (idx_id b)) $ map (convert_index idx_mp) indices lcid' = HM.fold max 0 col_mp liid' = HM.fold max 0 idx_mp convert_col m col@Col{..} = col { idNum = m HM.! name} :: Col convert_index m index@Index{..} = index { idNum = m HM.! name } :: Index add_miss_qa rid = do qa_structure <- readFile "./qa-version.sql" let structure = pack qa_structure prepend_table_version prod_conn rid structure incr_env_version prod_conn rid "DAILY" tid <- get_env_tid prod_conn rid "DAILY" prepend_version_track prod_conn tid Nothing return () prepend_version_meta rid = do struct <- readFile "./new-version.sql" prepend_table_version prod_conn rid $ pack struct incr_env_version prod_conn rid "DAILY" incr_env_version prod_conn rid "QA" dev_tid <- get_env_tid prod_conn rid "DAILY" putStrLn $ "dev tid -> " ++ show dev_tid shifts <- prepend_version_track prod_conn dev_tid Nothing putStrLn $ "shifts -> " ++ show shifts qa_tid <- get_env_tid prod_conn rid "QA" putStrLn $ "qa tid -> " ++ show dev_tid incr_table_versionTrack_version prod_conn qa_tid fixup_version_track_syncId prod_conn qa_tid shifts fix_table_nullAble_default = do all_tbs <- all_tables let need_fix_tbs = DL.filter need_fix all_tbs --forM_ need_fix_tbs do_fix_column_meta putStrLn $ show $ fmap (\(a, b, c) -> (a,b)) $ need_fix_tbs return () where need_fix :: (Integer, Integer, [Col]) -> Bool need_fix (rid, version, cols) = DL.any col_need_fix cols col_need_fix :: Col -> Bool col_need_fix Col{..} = not null && defaultValue == Just Nothing all_tables = do bracket online_conn close $ \c -> do rows <- query_rows c "SELECT RelativeID, Version, Columns FROM TableVersionMeta WHERE Columns is NOT NULL AND Columns != ''" return $ DL.map convert rows convert [a, b, c] = (getInt a, getInt b , eitherErrorS . decode' . getText $ c) do_fix_column_meta (rid, version, cols) = do let cols' = DL.map fix_col cols bracket online_conn close $ \c -> do ps <- prepareStmt c "UPDATE TableVersionMeta SET Columns = ? WHERE RelativeID = ? AND Version = ? " executeStmt c ps [toMySQLValue . encode' $ cols', toMySQLValue rid, toMySQLValue version] where fix_col c@Col{..} = c { defaultValue = Nothing } :: Col fix_nullAble = do all_tbs <- all_tables let need_fix_tbs = DL.filter need_fix all_tbs putStrLn $ show $ fmap (\(a,b,c,d) -> (a,b)) $ need_fix_tbs --forM_ need_fix_tbs test_prod_reference -- forM_ need_fix_tbs do_fix_nullAble where test_prod_reference (rid, version, _, _) = do bracket online_conn close $ \c -> do ps <- prepareStmt c "SELECT ID FROM TableMeta WHERE RelativeID = ? AND Version = ? AND Env = 'PROD'" rows <- query_rows_stmt c ps [toMySQLValue rid, toMySQLValue version] if DL.length rows /= 0 then do let tid = getInt . DL.head . DL.head $ rows putStrLn $ show (rid, version, tid) else return () do_fix_nullAble (rid, version, cols, colsOK) = do putStrLn $ show (rid, version) bracket online_conn close $ \c -> do ps <- prepareStmt c "UPDATE TableVersionMeta SET Columns = ? WHERE RelativeID = ? AND Version = ?" executeStmt c ps [toMySQLValue . encode' $ colsOK, toMySQLValue rid, toMySQLValue version] all_tables = do bracket online_conn close $ \c -> do rows <- query_rows c "SELECT RelativeID, Version, Columns, DDL FROM TableVersionMeta WHERE Columns is NOT NULL AND Columns != ''" return $ DL.map convert rows convert [a, b, c, d] = (getInt a, getInt b ,eitherErrorS . decode' . getText $ c , nCols) where dt = getText d (nCols, _) = either (\e -> error $ (DT.unpack dt) ++ "\n" ++ show e) Prelude.id $ parse_create_table dt need_fix :: (Integer, Integer, [Col], [Col]) -> Bool need_fix (a, b, cols', cols) = DL.any (col_need_fix cols') cols col_need_fix cols c = let c' = fromJust $ DL.find (\cc -> ((Model.name :: (Col -> String)) cc) == ((Model.name :: (Col -> String)) c)) cols in ((Model.null :: Col -> Bool) c') /= ((Model.null :: Col -> Bool) c) fix_table_columns_and_indices rid version = do (cols, indices, struct) <- get_table_version_info prod_conn rid version let (cols', indices') = eitherErrorS $ parse_create_table struct cols'' = DL.map (set_up_col_id cols) cols' indices'' = DL.map (set_up_idx_id indices) indices' update_column_indices prod_conn rid version (Util.encode' cols'') (Util.encode' indices'') return () where col_name :: Col -> String col_name Col{..} = name set_up_col_id cols col = let c' = fromMaybe (error "cannot found") $ DL.find (\c -> col_name c == col_name col) cols cid = ((idNum :: Col -> Int) c') in col { idNum = cid } :: Col set_up_idx_id indices idx = let i' = fromMaybe (error "cannot found") $ DL.find (\i -> idx_name i == idx_name i) indices iid = ((idNum :: Index -> Int) i') in idx { idNum = iid } :: Index update_column_indices conn rid version cols indices = do bracket conn close $ \c -> do ps <- prepareStmt c "UPDATE TableVersionMeta SET Columns = ?, Indices = ? WHERE RelativeID = ? AND Version = ?" executeStmt c ps [toMySQLValue cols, toMySQLValue indices, toMySQLValue rid, toMySQLValue version] get_table_version_info :: IO MySQLConn -> Integer -> Integer -> IO ([Col], [Index], Text) get_table_version_info conn rid version = do bracket conn close $ \c -> do ps <- prepareStmt c "SELECT Columns, Indices, DDL \ \ FROM TableVersionMeta WHERE RelativeID = ? AND Version = ?" row <- query_single_row_stmt c ps $ fmap toMySQLValue [rid, version] let [a, b, c] = row (cols, indices, struct) = (getText a, getText b, getText c) cols' = eitherError $ Util.decode' cols indices' = eitherError $ Util.decode' indices return (cols', indices', struct)
/* Copyright 2021 The GoPlus Authors (goplus.org) 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 gox import ( "go/ast" "go/token" "io" "log" "os" "syscall" "github.com/goplus/gox/internal/go/format" "github.com/goplus/gox/internal/go/printer" ) // ---------------------------------------------------------------------------- // ASTFile func func ASTFile(pkg *Package, testingFile bool) *ast.File { idx := getInTestingFile(testingFile) decls := pkg.files[idx].getDecls(pkg) return &ast.File{Name: ident(pkg.Types.Name()), Decls: decls, Imports: getImports(decls)} } func getImports(decls []ast.Decl) []*ast.ImportSpec { if len(decls) > 0 { if decl, ok := decls[0].(*ast.GenDecl); ok && decl.Tok == token.IMPORT { n := len(decl.Specs) ret := make([]*ast.ImportSpec, n) for i, spec := range decl.Specs { ret[i] = spec.(*ast.ImportSpec) } return ret } } return nil } // CommentedASTFile func func CommentedASTFile(pkg *Package, testingFile bool) *printer.CommentedNodes { return &printer.CommentedNodes{ Node: ASTFile(pkg, testingFile), CommentedStmts: pkg.commentedStmts, } } // WriteTo func func WriteTo(dst io.Writer, pkg *Package, testingFile bool) (err error) { fset := token.NewFileSet() return format.Node(dst, fset, CommentedASTFile(pkg, testingFile)) } // WriteFile func func WriteFile(file string, pkg *Package, testingFile bool) (err error) { if debugWriteFile { log.Println("WriteFile", file, "testing:", testingFile) } f, err := os.Create(file) if err != nil { return } err = syscall.EFAULT defer func() { f.Close() if err != nil { os.Remove(file) } }() return WriteTo(f, pkg, testingFile) } // ----------------------------------------------------------------------------
Beyond the random phase approximation: Improved description of short-range correlation by a renormalized adiabatic local density approximation We assess the performance of a recently proposed renormalized adiabatic local density approximation (rALDA) for \textit{ab initio} calculations of electronic correlation energies in solids and molecules. The method is an extension of the random phase approximation (RPA) derived from time-dependent density functional theory and the adiabatic connection fluctuation-dissipation theorem and contains no fitted parameters. The new kernel is shown to preserve the accurate description of dispersive interactions from RPA while significantly improving the description of short range correlation in molecules, insulators, and metals. For molecular atomization energies the rALDA is a factor of 7(4) better than RPA(PBE) when compared to experiments, and a factor of 3(1.5) better than RPA(PBE) for cohesive energies of solids. For transition metals the inclusion of full shell semi-core states is found to be crucial for both RPA and rALDA calculations and can improve the cohesive energies by up to 0.4 eV. Finally we discuss straightforward generalizations of the method, which might improve results even further.
#ifndef TERM_HTTPSERVER_H #define TERM_HTTPSERVER_H #include "list/list.h" #include <microhttpd.h> void termHttpServer(const char* state); void stopHttpServer(struct MHD_Daemon** d_ptr); #endif // TERM_HTTPSERVER_H
<gh_stars>0 import time import os import requests import json from datetime import datetime from flask_sqlalchemy import SQLAlchemy from intruo import Intruo, IntruoConfiguration, IntruoModules from flask import Flask, render_template, jsonify, request, send_file from nanoid import generate DEBUG_INTRUO = True template_folder = os.path.join(os.getcwd(), 'web', 'templates') static_folder = os.path.join(os.getcwd(), 'web', 'static') app = Flask( import_name='__name__', template_folder=template_folder, static_url_path='/static', static_folder=static_folder, ) app.config['SECRET_KEY'] = 'INTRUO_SECRET_KEY' app.config ['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///intruo.db' db = SQLAlchemy(app) class IntruoDB(db.Model): id = db.Column(db.Integer, primary_key = True) public_id = db.Column(db.Text()) domain = db.Column(db.Text()) time_init = db.Column(db.Text()) time_end = db.Column(db.Text()) result = db.Column(db.Text()) def __init__(self, public_id, domain, time_init, time_end, result): self.public_id = public_id self.domain = domain self.time_init = time_init self.time_end = time_end self.result = result db.create_all() # Routing Main @app.route('/', methods=['GET']) def main(): return render_template('main.html') # Routing Result @app.route('/resultado/<public_id>', methods=['GET']) def result(public_id): data = IntruoDB.query.filter_by(public_id=public_id).first() result = json.loads(data.result) return render_template('result.html', result=result) # Routing API @app.route('/api/check_configuration', methods=['GET']) def api_configuration_check(): configuration = IntruoConfiguration.check_configuration() for item in configuration: if configuration[item]['result'] == False: return jsonify(configuration), 400 return jsonify(configuration) @app.route('/api/configuration/install/driver', methods=['POST']) def api_configuration_install_driver(): data = request.files if not 'driver' in data: return jsonify({'error': 'No podemos instalar el driver. Intenta reinstalando INTRUO.'}), 400 driver = request.files['driver'] driver.save(os.path.join(os.getcwd(), 'utils', 'chromedriver.exe')) return jsonify(True) @app.route('/api/modules', methods=['GET']) def api_modules(): result = [] for module in IntruoModules: result.append(module.value.split('__')[1].replace('_', ' ')) return jsonify(result) @app.route('/api/module/page_online', methods=['POST']) def api_module_is_up(): data = request.json domain = data['domain'] try: r = requests.get(domain) except requests.exceptions.RequestException as e: print(e) return jsonify('La página no está disponbile.'), 400 return jsonify(True) @app.route('/api/modules/run', methods=['POST']) def api_module_run(): data = request.json domain = data['domain'] modules = data['modules'] intruo = Intruo(domain=domain, debug=DEBUG_INTRUO) intruo.module__https() for module in modules: module = module.replace(' ', '_') module = f'module__{module.lower()}' getattr(intruo, module)() save_result = intruo.action_generate_results() result = intruo.result intruo_record = IntruoDB( public_id=generate('1234567890abcdefghijkmnopqrstuvwxyz', 10), domain=domain, time_init=result['time_execution']['init'], time_end=result['time_execution']['end'], result=json.dumps(save_result) ) db.session.add(intruo_record) db.session.commit() return jsonify(intruo_record.public_id) @app.route('/api/module/screenshot', methods=['POST']) def api_module_screenshot(): data = request.json domain = data['domain'] intruo = Intruo(domain=domain, debug=DEBUG_INTRUO) filename = intruo.action_get_screenshoot() return jsonify(filename) @app.route('/api/download/json/<public_id>', methods=['GET']) def api_download_json_result(public_id): data = IntruoDB.query.filter_by(public_id=public_id).first() json_file = json.loads(data.result)['json'] return send_file(os.path.join(os.getcwd(), 'web', 'static', 'results', 'json', json_file), as_attachment=True, download_name=json_file) @app.route('/api/download/html/<public_id>', methods=['GET']) def api_download_html_result(public_id): data = IntruoDB.query.filter_by(public_id=public_id).first() html_file = json.loads(data.result)['html'] return send_file(os.path.join(os.getcwd(), 'web', 'static', 'results', 'html', html_file), as_attachment=True, download_name=html_file) @app.route('/api/scan/history', methods=['GET']) def api_scan_history(): history = IntruoDB.query.all() result = [] for row in history: result.append({ 'public_id': row.public_id, 'domain': row.domain, 'time_init': row.time_init, 'time_end': row.time_end, 'result': json.loads(row.result) }) return jsonify(result) @app.route('/api/scan/delete/<public_id>', methods=['DELETE']) def api_scan_delete(public_id): data = IntruoDB.query.filter_by(public_id=public_id).first() data_files = json.loads(data.result) files = { 'screenshot': os.path.join(os.getcwd(), 'web', 'static', 'results', 'screenshot', data_files['screenshot']), 'json': os.path.join(os.getcwd(), 'web', 'static', 'results', 'json', data_files['json']), 'js': os.path.join(os.getcwd(), 'web', 'static', 'results', 'js', data_files['js']), 'html': os.path.join(os.getcwd(), 'web', 'static', 'results', 'html', data_files['html']), } for f in files: if os.path.exists(files[f]): os.remove(files[f]) db.session.delete(data) db.session.commit() return jsonify(True) if __name__ == "__main__": # openedIntruo = False # if not openedIntruo: # Intruo.action_open_browser('http://127.0.0.1:5000/') # openedIntruo = True # app.run(debug=True, use_reloader=False) app.run(debug=True, use_reloader=True)
def to_edges(l): it = iter(l) last = next(it) for current in it: yield last, current last = current
/// Performs type analysis for the given AST node. This annotates the node with a concrete type. fn analyze(&mut self, mut ast: Ast, root_node: NodeId) -> Ast { self.push_defers(); let _ = self.annotate_node(&mut ast, root_node, NodeContext::Statement); self.pop_defers(&mut ast); ast }
/** * Various utility functions for zip-files used by classes in this package. * @author fwiers * */ public class ZipUtil { private ZipUtil() {} /** * Searches for a zip-entry and returns it as an input-stream (backed by a byte-array). * @param entryNameStart null/empty or the first part of the name of the zip-entry that should be opened. * @param entryNameEnd null/empty or the last part of the name of the zip-entry that should be opened. * @return An input-stream (that does not have to be closed, it is a {@link ByteArrayInputStream}. */ public static InputStream getInputStream(File zippedFile, String entryNameStart, String entryNameEnd) throws IOException { ZipFile zipFile = null; InputStream in = null; try { zipFile = new ZipFile(zippedFile); Enumeration<? extends ZipEntry> e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = (ZipEntry) e.nextElement(); String fname = entry.getName(); boolean foundEntry = BootUtil.isEmpty(entryNameStart) ? true : fname.startsWith(entryNameStart); if (foundEntry) { foundEntry = BootUtil.isEmpty(entryNameEnd) ? true : fname.endsWith(entryNameEnd); } if (foundEntry) { in = getInputStream(zipFile, entry); break; } } } catch (Exception ignored) { //ignored.printStackTrace(); ; } finally { // JRE 6: zip file is NOT a closeable // BootUtil.close(zipFile); try { zipFile.close(); } catch (Exception ignored) { ; } } return in; } /** * Returns the bytes form the zip-entry as input-stream. */ public static InputStream getInputStream(ZipFile zipFile, ZipEntry entry) throws IOException { return new ByteArrayInputStream(getBytes(zipFile, entry)); } /** * Returns the bytes form the zip-entry. */ public static byte[] getBytes(ZipFile zipFile, ZipEntry entry) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); // InputStream is closed when zipFile is closed. InputStream in = zipFile.getInputStream(entry); byte[] buf = new byte[8192]; int l = 0; while ((l = in.read(buf)) > 0) { bout.write(buf, 0, l); } return bout.toByteArray(); } }
<filename>src/app/models/User.ts<gh_stars>1-10 export enum UserRole { Unclear = "Unclear", User = "User", Admin = "Admin", } export class User { public username: string; public role: UserRole; public token: string; constructor(json) { Object.assign(this,json); this.role = json.role as UserRole; } }
def _BrowseForDirectory(self, evt): default_path = self.GetPath() if os.path.exists(default_path): default_path = os.path.join(default_path, '..') else: default_path = '' dirname = wx.DirSelector(message='Pick an existing App Engine App', defaultPath=default_path, style=wx.DD_DIR_MUST_EXIST) if dirname: self.SetPath(dirname)
#! /usr/bin/env python from __future__ import print_function import os import re import sys import subprocess #****************** template file ********************************** templateFile = open('templateForDropbox.txt', 'r') fileContents = templateFile.read(-1) print('--------------- TEMPLATE : -----------------') print(fileContents) p1 = re.compile(r'TAGNAME') p2 = re.compile(r'PRODNAME') #****************** definitions ********************************** jec_type = 'JetCorrectorParametersCollection' ERA = 'Jec11_V10' ALGO_LIST = [#'IC5Calo','IC5PF', 'AK5Calo','AK5PF','AK5PFchs','AK5JPT'#,#'AK5TRK', 'AK7Calo','AK7PF', 'KT4Calo','KT4PF', #'KT6Calo','KT6PF' ] #********************************************************************* files = [] ### L2+L3 Corrections for aa in ALGO_LIST: #loop for jet algorithms s1 = jec_type + '_' + ERA + '_' + aa s2 = jec_type + '_' + ERA + '_' + aa k1 = p1.sub( s1, fileContents ) k2 = p2.sub( s2, k1 ) k2outfile = s2 + '.txt' print('--------------------------------------') print('ORCOFF File for jet correction : ' + s2) print('Written to ' + k2outfile) FILE = open(k2outfile,"w") FILE.write(k2) files.append( k2outfile ) for ifile in files : s = "./dropBoxOffline_test.sh "+ERA+".db " + ifile print(s) subprocess.call( ["./dropBoxOffline_test.sh", ERA+".db", ifile])
from django.contrib import admin from .models import Pet admin.site.register(Pet)
/** * Copy the contents on another semisparse array into this one * * @param from the source array */ public synchronized void putAll(SemisparseByteArray from) { byte[] temp = new byte[4096]; for (Range<UnsignedLong> range : from.defined.asRanges()) { long length; long lower = range.lowerEndpoint().longValue(); if (range.upperBoundType() == BoundType.CLOSED) { assert range.upperEndpoint() == UnsignedLong.MAX_VALUE; length = -lower; } else { length = range.upperEndpoint().longValue() - lower; } for (long i = 0; Long.compareUnsigned(i, length) < 0;) { int l = MathUtilities.unsignedMin(temp.length, length - i); from.getData(lower + i, temp, 0, l); this.putData(lower + i, temp, 0, l); i += l; } } }
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import absolute_import, division, print_function import torch def decorate_batch(batch, device='cpu'): """Decorate the input batch with a proper device Parameters ---------- batch : {[torch.Tensor | list | dict]} The input batch, where the list or dict can contain non-tensor objects device: str, optional 'cpu' or 'cuda' Raises: ---------- Exception: Unsupported data type Return ---------- torch.Tensor | list | dict Maintain the same structure as the input batch, but with tensors moved to a proper device. """ if isinstance(batch, torch.Tensor): batch = batch.to(device) return batch elif isinstance(batch, dict): for key, value in batch.items(): if isinstance(value, torch.Tensor): batch[key] = value.to(device) elif isinstance(value, dict) or isinstance(value, list): batch[key] = decorate_batch(value, device) # retain other value types in the batch dict return batch elif isinstance(batch, list): new_batch = [] for value in batch: if isinstance(value, torch.Tensor): new_batch.append(value.to(device)) elif isinstance(value, dict) or isinstance(value, list): new_batch.append(decorate_batch(value, device)) else: # retain other value types in the batch list new_batch.append(value) return new_batch else: raise Exception('Unsupported batch type {}'.format(type(batch)))
Image copyright ITV Image caption ITV has made a new version of Thunderbirds titled Thunderbirds Are Go The government is giving broadcasters including Channel 4 and ITV an extra £60m to help them make more home-grown children's programmes. The money will be targeted at commercial channels to help them compete with BBC children's shows. Teletubbies creator Anne Wood welcomed the funding, saying programme-makers "desperately need more support". The £60m pot will be spent over three years and will come from the 2010 licence fee settlement. Culture Secretary Karen Bradley said it would give the children's TV sector "the boost it needs to create innovative content for a wider audience that would otherwise not be made". The money will be available for programmes shown by commercial public service broadcasters - including ITV, Channel 4 and Channel 5 - as well as other "free and widely available" channels and streaming services, and potentially other online platforms. Anne Wood, who leads the Save Kids' Content UK campaign, said she was "deeply grateful" for the move. 'Never had such difficult times' "It shows the government's awareness of the issue and the importance of children's television culture to children in this country," she told BBC News. "We in the children's production sector have never had such difficult times raising finance. We desperately need more support." The Department for Digital, Culture, Media and Sport said the fund could be used to pay for up to 50% of the production and distribution costs of original TV shows. Programmes from new and diverse backgrounds, and those made in the nations and regions, will be "a particular focus", it said. The government said the fund would "stimulate greater variety in a market where the BBC is often the dominant buyer and broadcaster" of children's shows. Image copyright Getty Images Image caption The Teletubbies are among Britain's most successful children's TV exports, underlining the BBC's dominance in the sector Spending on first-run home-grown children's programming by public service broadcasters fell by 26% to £84m between 2006-16. In 2016, CBBC and CBeebies accounted for 87% of all such children's programming. Although ITV no longer has the daily offering of children's TV shows that many children of the 1970s and 1980s will remember, it does screen a range of children's programmes on its channels, often to be seen on ITV early on weekend mornings. It recently announced a new show, Spy School - described as an entertainment game show challenging child contestants to solve puzzles and crack codes - that will be on air from 7 January. Its other popular shows include the animated adventures of Mr Bean, a new version of Thunderbirds titled Thunderbirds Are Go, the Saturday morning show Scrambled! and the comedy Bottom Knocker Street. The announcement of the extra funding comes after media watchdog Ofcom was given new powers to set quotas for children's shows on public service broadcasters. Follow us on Facebook, on Twitter @BBCNewsEnts, or on Instagram at bbcnewsents. If you have a story suggestion email [email protected].
// Log logs a message at any given level func Log(level string, message string, context Mapper) error { client, err := gotask.NewAutoClient() if err != nil { return err } payload := map[string]interface{}{ "level": level, "context": context.Map(), "message": message, } err = client.Call(phpLog, payload, nil) return err }
def disableOverride(self,alarmlist) : action = DisableAction(None) action.performAction(self.comments,alarmlist)
FREQUENTLY ASKED QUESTIONS What does the weekend look like? You and your fellow students will start a company over the course of three days. We rent work space, invite approximately 40 students with a wide range of backgrounds, and provide food, drinks, snacks, and coffee. But most importantly, we give you everything you need to go from selecting an idea on day 1 to presenting a minimum viable product on day 3. By the end of the program, you should have the skills, motivation, and network to move forward with your company –– now or ten years from now. If I participate, what do I get out of the weekend? The worst case scenario is that you will work with brilliant people from numerous disciplines toward the common goal of building real companies and products. Great connections happen at 3 Day Startup: cofounders meet, complimentary skill sets collide, and friends are made. The best case scenario is that you will be a cofounder of a wildly successful new startup. I’m a student majoring in X. Should I even consider applying? Yes! Our past participants span from first years to PhD candidates with backgrounds from English to engineering. Everyone is welcomed and everyone is valued. If you are passionate or curious about startups or technology, a 3DS program gives you just the push you need. And you’ll have a lot of fun along the way! What kind of ideas are allowed? All kinds of ideas are allowed. Companies in everything from chocolate, to stationary, to software have emerged from 3DS. Any idea can gain traction at a 3DS program and develop into an awesome startup. At the program, we will show you how to take your idea and make it both viable and scalable. What about food? Sleep? All meals, drinks, and in-between snacks are provided. Sleep is optional. What is your rate of success? First of all, You can check out some of the companies that have been started by 3 Day Startup Alumni here. Our primary success metrics are learning outcomes and companies launched. Per program, 3 Day Startup results in more successful startups than any other weekend entrepreneurship event. When we say startups, we mean the real thing: companies that are making money or taking investment. We have run 300+ programs in the US and internationally, and those have given rise to 90+ companies that have received over $85 million in funding. 34 companies from 3DS have been accepted to accelerators such as Y Combinator, Tech Stars, 500 Startups, Capital Factory, and Dreamit Ventures. On average, most 3 Day Startup programs –– in both mature and nascent university entrepreneurship ecosystems –– generate at least one successful startup.
package consensus import ( autocliv1 "cosmossdk.io/api/cosmos/autocli/v1" consensusv1 "cosmossdk.io/api/cosmos/consensus/v1" ) // AutoCLIOptions implements the autocli.HasAutoCLIConfig interface. func (am AppModule) AutoCLIOptions() *autocliv1.ModuleOptions { return &autocliv1.ModuleOptions{ Query: &autocliv1.ServiceCommandDescriptor{ Service: consensusv1.Query_ServiceDesc.ServiceName, RpcCommandOptions: []*autocliv1.RpcCommandOptions{ { RpcMethod: "Params", Use: "params", Short: "Query the current consensus parameters", }, }, }, // Tx is purposely left empty, as the only tx is MsgUpdateParams which is gov gated. } }
<filename>src/Unit5/Lesson27/Code27_2.hs module Unit5.Lesson27.Code27_2 where main27_2 :: IO () main27_2 = do print (incMaybe successfulRequest) print (incMaybe failedRequest) incMaybe :: Maybe Int -> Maybe Int incMaybe (Just n) = Just (n + 1) incMaybe Nothing = Nothing successfulRequest :: Maybe Int successfulRequest = Just 6 failedRequest :: Maybe Int failedRequest = Nothing
<reponame>DarshanSudhakar/BugVilla<gh_stars>100-1000 import React from 'react'; import styled from 'styled-components/macro'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { notify } from 'react-notify-toast'; const StyledToastText = styled.div` display: flex; justify-content: center; align-items: center; .notification__icon { margin-right: 10px; } .close-icon { margin-left: 20px; transition: 0.2s; cursor: pointer; &:hover { transform: scale(1.2); transition: 0.2s; } } `; export const Toast: React.FC<{ icon?: any; }> = ({ icon = 'exclamation-triangle', children }) => { return ( <StyledToastText> <FontAwesomeIcon className="notification__icon" icon={icon} /> {children} <FontAwesomeIcon onClick={notify.hide} className="close-icon" icon="times" /> </StyledToastText> ); }; export const toast = { error: (message: string) => { notify.show(<Toast icon="exclamation-circle">{message}</Toast>, 'error'); }, success: (message: string) => { notify.show(<Toast icon="check-circle">{message}</Toast>, 'success'); }, info: (message: string) => { notify.show(<Toast icon="info-circle">{message}</Toast>, 'info'); } }; export default Toast;
<filename>src/modules/auth/ro/auth.ro.ts import { ApiProperty } from '@nestjs/swagger' export class AuthRO { @ApiProperty() access_token: string }
import { Observable } from 'rxjs'; import { Movie } from '../models/movie'; export interface MediaServiceInterface { getMovies(): Observable<Movie[]>; getMovieByUuid(uuid: string): Observable<Movie>; }
A comparative evaluation of the effect of intravenous dexmedetomidine and clonidine on intraocular pressure after suxamethonium and intubation Background: In patients with penetrating eye injury and a full stomach, suxamethonium is still used for rapid sequence induction of anesthesia. But its use is associated with the rise in intraocular pressure (IOP) and this can result in permanent vision loss in these patients. Dexmedetomidine and clonidine are two alpha-2 adrenergic agonist drugs which prevent the rise in IOP. The aim of this study is to compare the efficacy of intravenous (i.v.) dexmedetomidine and clonidine in preventing an increase in IOP after administration of suxamethonium and tracheal intubation. Materials and Methods: Sixty patients undergoing elective nonophthalmic surgery under general anesthesia were included in this clinical study. Patients were randomly assigned into three groups to receive 0.5 mcg/kg dexmedetomidine (Group D), 2 mcg/kg clonidine (Group C) or normal saline (Group S) as premedication i.v. over a period of 10 min before induction. IOP, heart rate, and mean arterial pressure were recorded before and after premedication, after suxamethonium, after intubation and then after 5 min. Results: Following administration of dexmedetomidine and clonidine IOP decreased in both groups. After suxamethonium IOP increased in all three groups but it never crossed the baseline in Group D and C. After laryngoscopy and intubation IOP again increased in all three groups but in dexmedetomidine group it never crossed the baseline whereas in clonidine group it was significantly higher than the baseline. Conclusion: Single i.v. dose of dexmedetomidine premedication (0.5 mcg/kg) blunt the IOP and hemodynamic response to suxamethonium injection and tracheal intubation more effectively than single i.v. dose of clonidine premedication (2 mcg/kg). INTRODUCTION Increasing intraocular pressure (IOP) in ophthalmic surgery has always been problematic for the surgeon and it is necessary to prevent the elevation of IOP and control it before, during and after the surgery. and use of nitroglycerine. Dexmedetomidine and clonidine are two alpha-2 adrenergic agonist drugs which have the property of inhibiting rise in IOP following suxamethonium, laryngoscopy, and tracheal intubation. The aim of this study is to compare the effectiveness of single preinduction bolus of intravenous (i.v.) dexmedetomidine 0.5 mcg/kg and i.v. clonidine 2 mcg/ kg in attenuating the rise in IOP after suxamethonium and tracheal intubation. MATERIALS AND METHODS After obtaining the approval of institutional ethics committee and written informed consent, 60 adult patients of American Society of Anesthesiologists (ASA) 1 or 2, aged 18-60 years, who were scheduled for elective nonophthalmic surgeries under general anesthesia were included in the study. Exclusion criteria include patients suffering from hypertension, acute or chronic eye disease, any known allergies or contraindication of study drugs, predicted difficulty in intubation and pregnancy. Patients were also not included if they were receiving any drug known to alter IOP. The patients were randomly allocated into three groups of 20 patients each to receive 0.5 mcg/kg dexmedetomidine (Group D), 2 mcg/kg clonidine (Group C) or normal saline (Group S) i.v. as a premedication. No other sedative premedication was given to patients. On arrival in the operating room, multichannel monitor (Datex-ohmeda, cardiocap/5, GE healthcare, Helsinki, Finland) with the facility to measure pulse oximeter, noninvasive blood pressure, electrocardiogram, temperature and respiratory gas monitor were attached and patient's baseline heart rate (HR), mean arterial pressure (MAP), SpO 2 and respiratory rate were recorded after 5 min. Topical proparacaine hydrochloride 0.5% eye drop was applied to the cornea in each eye and IOP was measured with a, Schioetz tonometer (made in Germany) by an ophthalmologist who was unaware of the nature of the study (baseline value). Study solutions of dexmedetomidine, clonidine and normal saline in 20 ml syringes were prepared by anesthesiologist, who was not involved in data recording. Dexmedetomidine (Dextomid, Neon Laboratories) was prepared by diluting 50 mcg dexmedetomidine in 20 ml of normal saline to make a concentration of 2.5 mcg/ml. Clonidine (Cloneon, Neon Laboratories) was prepared by diluting 200 mcg clonidine in 20 ml normal saline to make a concentration of 10 mcg/ml. In all three groups, 0.2 ml/kg of study solution was administered as a single i.v. bolus over 10 min before induction of anesthesia using a syringe pump (SP102, Larsen and toubro Ltd). Patients in Group D received dexmedetomidine 0.5 mcg/kg, Group C received clonidine 2 mcg/kg, and Group S received same amount of normal saline. General anesthesia was standardized in all the groups. Anesthesia was induced with injection thiopental 5 mg/kg and injection suxamethonium was administered at a dose of 1.5 mg/kg to facilitate laryngoscopy and intubation. After cessation of fasciculation laryngoscopy was performed with a Macintosh laryngoscope andtrachea was intubated with appropriate number endotracheal tube. The patient was excluded from the study if the trachea could not be intubated at the first attempt. After intubation anesthesia was maintained with N 2 O in O 2 (60:40), isoflurane (1%), fentanyl (1 mcg/kg) and vecuronium bromide. All the patients were ventilated mechanically (by Anesthesia workstation: Datex-ohmeda 9100c, serial no-ME14010022, GE healthcare) to maintain the end-tidal carbon dioxide partial pressure between 32 and 35 mmHg. At the end of anesthesia, the neuromuscular blockade was antagonized with neostigmine and glycopyrrolate. Patients were extubated and observed in the postoperative room. Intraocular pressure, HR, MAP were measured and recorded before premedication (baseline), after 10 min infusion of study drug (after premedication), 30 s after injection of suxamethonium, immediately after intubation and 5 min after intubation. Statistical analysis The decision to include 20 patients in each group was based on a power analysis (α = 0.05, β = 0.2), which revealed that at least 20 patients should be included in each group. Difference between the groups in the demographic data and baseline values were analyzed using unpaired t-test. For comparison of different observations within and between the groups, data were analyzed by repeated measures analysis of variance. Analysis was performed using software IBM Corp (2011), IBM SPSS statistics for windows, version 20.0 (Armonk, NY). Data were presented as mean ± standard deviation A P < 0.05 was considered statistically significant. RESULTS There were no significant differences among the groups regarding age, weight, ASA physical status of the patients . Baseline HR, MAP, and IOP of the different groups were also comparable. Significant decrease in IOP was observed in Group D and C following infusion of study drug (P < 0.001) compared Saudi Journal of Anesthesia Vol. 9, Issue 2, April-June 2015 with baseline. Following suxamethonium IOP increased in all the three Groups (D, C, S), but it was below baseline in Group D and C and increased significantly from the baseline value (P < 0.001) in Group S. After intubation IOP increased in all groups but it was below baseline in Group D, unlike that in Group C and Group S (P < 0.001) where it was significantly higher than baseline. IOP was more than the baseline in the Group S even after 5 min following intubation (P = 0.002). After intubation IOP in Group, D was lower significantly from Group C and S (P < 0.001). In Group D IOP was not higher than the basal value at all the times . After premedication, decrease in HR and MAP was observed in Group D and C while significant increase in HR and MAP from baseline was recorded following intubation in Group C and S (P < 0.001). HR and MAP increased significantly after intubation in Group C and S when compared with Group D (HR and MAP: P < 0.001 for Group C and S) . DISCUSSION Suxamethonium is widely used drug in a rapid sequence induction of anesthesia. The use of suxamethonium is limited in the case of perforating eye injury because it increases IOP. There is an increase in IOP about 8 mm Hg from the basal value (10-21.7) after administration of suxamethonium. There is further increase in IOP due to laryngoscopy and intubation. During anesthesia, a rise in IOP can produce permanent visual loss. IOP becomes atmospheric once the eye cavity has been entered, and any sudden rise in pressure may lead to prolapse of the iris and lens, and loss of vitreous. Thus, proper control of IOP is critical. Many methods have been advocated to prevent the rise in IOP with limited success. Various studies have focused on the effects of alpha-2 adrenergic agonist in preventing IOP rise. The results obtained from these studies indicate a favorable effect of using alpha-2 agonists dexmedetomidine and clonidine to prevent the IOP increase following the injection of suxamethonium and tracheal intubation. Dexmedetomidine is a highly selective alpha-2 adrenergic agonist. After a single i.v. dose of dexmedetomidine (0.6 mcg/kg) there was a 34% reduction in IOP. Mowafi et al. have reported attenuation of the increase in the IOP, HR and arterial pressure by a bolus injection of 0.6 mcg/kg dexmedetomidine as a premedication over 10 min before Vol. 9, Issue 2, April-June 2015 Saudi Journal of Anesthesia induction of anesthesia. Pal et al. in a study on 66 patients showed that the dexmedetomidine (0.6 mcg/kg as well as 0.4 mcg/kg) effectively prevents rise of IOP following suxamethonium and intubation. But hemodynamic stability is better with a lower dose (0.4 mcg/kg). As with dexmedetomidine, pretreatment with clonidine attenuates responses to tracheal intubation, decreases IOP, and increases the likelihood of hypotension. Ghignone et al. studied the effect of oral clonidine and found that it effectively blunts the IOP and hemodynamic responses to laryngoscopy and intubation following injection of suxamethonium. Weigert et al. reported pronounced drop in IOP and MAP after administration of 0.2 mcg/kg/min clonidine i.v. over 10 min. Similar effects were reported by Lemes et al. by using i.v. clonidine (2.5 mcg/kg) during cataract surgery. None of the previous workers compared the effect of using i.v. dexmedetomidine and i.v. clonidine premedication over IOP during general anesthesia. There is a risk of hypotension and bradycardia when higher dose of clonidine and dexmedetomidine are used. So we preferred single -bolus low dose for both drugs in our study. In our study reduction in IOP was noticed following administration of dexmedetomidine and clonidine (Group D and C). IOP was increased after administration of suxamethonium in all three groups but in dexmedetomidine and clonidine groups this increase was up to the baseline value whereas in saline group IOP increase was significantly more than the baseline. Also, after laryngoscopy and intubation IOP was increased in all three groups but only in the dexmedetomidine group it still remained less than the baseline value whereas in clonidine and saline group it was significantly more than the baseline. We also observed significant attenuation of pressure response to laryngoscopy and intubation using dexmedetomidine (0.5 mcg/kg) whereas clonidine (2 mcg/kg) was shown to be ineffective in attenuation of pressure response at this dose. Thus, single i.v. dose of dexmedetomidine premedication (0.5 mcg/kg) blunt the IOP and hemodynamic response to suxamethonium injection and tracheal intubation. However, i.v. clonidine premedication, with the dose of 2 mcg/kg used in this study was shown to be effective in preventing rise of IOP after suxamethonium only but was ineffective in the attenuation of IOP and hemodynamic responses to laryngoscopy and tracheal intubation. We conclude that i.v. dexmedetomidine is more effective than i.v. clonidine in attenuating the IOP and hemodynamic response to laryngoscopy and tracheal intubation. Therefore, dexmedetomidine should be used as premedication before rapid sequence induction of anesthesia where raised IOP is dangerous for the patients. In order to further evaluate the effects of i.v. clonidine over IOP during general anesthesia, additional studies should be planned to assess the optimum dose, mode and delivery timing of this drug.
""" GRMIPose (Google PoseNet) for COCO Keypoint, implemented in TensorFlow (Lite). Original paper: 'Towards Accurate Multi-person Pose Estimation in the Wild,' https://arxiv.org/abs/1701.01779. """ __all__ = ['GRMIPoseLite', 'grmiposelite_mobilenet_w1_coco'] import math import numpy as np import tensorflow as tf class GRMIPoseLite(tf.keras.Model): """ GRMIPose (Google PoseNet) model from 'Towards Accurate Multi-person Pose Estimation in the Wild,' https://arxiv.org/abs/1701.01779. Parameters: ---------- interpreter : obj Instance of the TFLite model interpreter. in_channels : int, default 3 Number of input channels. in_size : tuple of two ints, default (257, 257) Spatial size of the expected input image. keypoints : int, default 17 Number of keypoints. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, interpreter, in_channels=3, in_size=(257, 257), keypoints=17, data_format="channels_last", **kwargs): super(GRMIPoseLite, self).__init__(**kwargs) assert (in_channels == 3) self.in_size = in_size self.keypoints = keypoints self.data_format = data_format self.interpreter = interpreter self.interpreter.allocate_tensors() input_details = self.interpreter.get_input_details() self.input_tensor_index = input_details[0]["index"] self.in_shape = tuple(input_details[0]["shape"]) assert (self.in_size == self.in_shape[1:3]) self.output_tensor_index_list = [i["index"] for i in self.interpreter.get_output_details()] def call(self, x, training=None): x_np = x.numpy() # import cv2 # cv2.imshow("x_np", x_np[0]) # cv2.waitKey(0) # cv2.destroyAllWindows() assert (x_np.shape == self.in_shape) self.interpreter.set_tensor(self.input_tensor_index, x_np) self.interpreter.invoke() heatmap = self.interpreter.get_tensor(self.output_tensor_index_list[0]) offsets = self.interpreter.get_tensor(self.output_tensor_index_list[1]) pts = np.zeros((self.keypoints, 3), np.float32) oh, ow = heatmap.shape[1:3] fh = self.in_size[0] / (oh - 1) fw = self.in_size[1] / (ow - 1) for k in range(self.keypoints): max_h = heatmap[0, 0, 0, 0] max_i = 0 max_j = 0 for i in range(oh): for j in range(ow): h = heatmap[0, i, j, k] if h > max_h: max_h = h max_i = i max_j = j pts[k, 0] = max_i * fh + offsets[0, max_i, max_j, k] pts[k, 1] = max_j * fw + offsets[0, max_i, max_j, k + self.keypoints] pts[k, 2] = self.sigmoid(max_h) pts1 = pts.copy() for k in range(self.keypoints): pts1[k, 0] = 0.25 * pts[k, 1] pts1[k, 1] = 0.25 * pts[k, 0] y = tf.convert_to_tensor(np.expand_dims(pts1, axis=0)) # import cv2 # canvas = x_np[0] # canvas = cv2.cvtColor(canvas, code=cv2.COLOR_BGR2RGB) # for k in range(self.keypoints): # cv2.circle( # canvas, # (pts[k, 1], pts[k, 0]), # 3, # (0, 0, 255), # -1) # scale_factor = 3 # cv2.imshow( # winname="canvas", # mat=cv2.resize( # src=canvas, # dsize=None, # fx=scale_factor, # fy=scale_factor, # interpolation=cv2.INTER_NEAREST)) # cv2.waitKey(0) # cv2.destroyAllWindows() return y @staticmethod def sigmoid(x): return 1.0 / (1.0 + math.exp(-x)) def get_grmiposelite(model_path, keypoints, model_name=None, data_format="channels_last", pretrained=False, **kwargs): """ Create GRMIPose (Google PoseNet) model with specific parameters. Parameters: ---------- model_path : str Path to pretrained model. keypoints : int Number of keypoints. model_name : str or None, default None Model name for loading pretrained model. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. """ assert (pretrained is not None) assert (model_name is not None) if (model_path is None) or (not model_path): raise ValueError("Parameter `model_path` should be properly initialized for loading pretrained model.") interpreter = tf.lite.Interpreter(model_path=model_path) net = GRMIPoseLite( interpreter=interpreter, keypoints=keypoints, data_format=data_format, **kwargs) return net def grmiposelite_mobilenet_w1_coco(model_path, keypoints=17, data_format="channels_last", pretrained=False, **kwargs): """ GRMIPose (Google PoseNet) model on the base of 1.0 MobileNet-224 for COCO Keypoint from 'Towards Accurate Multi-person Pose Estimation in the Wild,' https://arxiv.org/abs/1701.01779. Parameters: ---------- model_path : str Path to pretrained model. keypoints : int, default 17 Number of keypoints. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_grmiposelite(model_path=model_path, keypoints=keypoints, model_name="grmiposelite_mobilenet_w1_coco", data_format=data_format, pretrained=pretrained, **kwargs) def _test(): data_format = "channels_last" in_size = (257, 257) keypoints = 17 pretrained = False model_path = "" models = [ grmiposelite_mobilenet_w1_coco, ] for model in models: net = model(model_path=model_path, pretrained=pretrained, in_size=in_size, data_format=data_format) batch = 1 x = tf.random.normal((batch, in_size[0], in_size[1], 3)) y = net(x) assert (y.shape[0] == batch) assert ((y.shape[1] == keypoints) and (y.shape[2] == 3)) if __name__ == "__main__": _test()
An appellate court Thursday upheld a penalty against Oregon bakery owners who refused to make a cake for a same-sex wedding almost five years ago. The owners of the since-closed Gresham bakery - Aaron and Melissa Klein - argued that state Labor Commissioner Brad Avakian violated state and federal laws by forcing them to pay emotional-distress damages of $135,000 to the lesbian couple Rachel and Laurel Bowman-Cryer. Their lawyers said Avakian and the state Bureau of Labor and Industries violated the Kleins' rights as artists to free speech, their rights to religious freedom and their rights as defendants to a due process. In 2013 the Kleins refused to make a cake for Rachel and Laurel Bowman-Cryer when they discovered the wedding was for a same-sex couple (Melissa Klein, left, and Aaron Klein, right) Rachel and Laurel Bowman-Cryer (pictured) are protected by a 2007 Oregon law that prevents discrimination against gays, lesbians, bisexual and transgender peopl But the Oregon Court of Appeals sided with the state Thursday, saying the Kleins failed to show the state targeted them for their religious beliefs. The judges also found public statements made by Avakian before deciding the case did not establish a lack of impartiality. 'Today's ruling sends a strong signal that Oregon remains open to all,' Avakian said after the 62-page opinion was released Thursday. The decision comes weeks after the U.S. Supreme Court heard arguments in the high-profile case of a Colorado baker who refused to make a wedding cake for a same-sex couple. That baker, Jack Phillips, claims his First Amendment claims of artistic freedom were being violated - a similar issue raised by the Kleins. The Oregon court said the Kleins' argument that their cakes entail an artistic expression is 'entitled to be taken seriously,' but it's not enough for the couple to assert their cakes are pieces of art - they must show others perceive their creations like a sculpture or painting. An appellate court Thursday upheld a penalty against the bakery owners (pictured) who refused to make a cake for a same-sex wedding almost five years ago In this February 5, 2013, file photo, Melissa Klein, co-owner of Sweet Cakes by Melissa, in Gresham tells a customer that the bakery has sold out of baked goods for the day. The bakery has since closed 'Although we accept that the Kleins imbue each wedding cake with their own aesthetic choices, they have made no showing that other people will necessarily experience any wedding cake that the Kleins create predominantly as 'expression' rather than as food,' the opinion says. First Liberty Institute, the legal organization that represents the Kleins, disagreed with the ruling. 'The Oregon Court of Appeals decided that Aaron and Melissa Klein are not entitled to the Constitution's promises of religious liberty and free speech,' said Kelly Shackelford, the firm's president. 'In a diverse and pluralistic society, people of good will should be able to peacefully coexist with different beliefs.' The case began when Rachel Bowman-Cryer went to the suburban Portland bakery with her mother in January 2013. The bakery has since closed The state fined the bakers after determining they violated a 2007 Oregon law that protects the rights of gays, lesbians, bisexual and transgender people in employment, housing and public accommodations. The law provides an exemption for religious organizations but does not allow private businesses to discriminate based on sexual orientation. The case began when Rachel Bowman-Cryer went to the suburban Portland bakery with her mother in January 2013. They met with Aaron Klein, who asked for the date of the ceremony and the names of the bride and groom. When told there was no groom, Klein said he was sorry but the bakery did not make cakes for same-sex weddings. According to documents from the case, Rachel and her mother left the shop, but returned a short time later. As Rachel remained in the car, in tears, her mother went in to speak with Klein. The mother told Klein she had once thought like him, but her 'truth had changed' when she had two gay children. Klein responded by quoting Leviticus: 'You shall not lie with a male as one lies with a female; it is an abomination.' Rachel and Laurel Bowman-Cryer praised the ruling in a statement released through their attorney: 'It does not matter how you were born or who you love. All of us are equal under the law and should be treated equally. Oregon will not allow a 'Straight Couples Only' sign to be hung in bakeries or other stores.'
// (C) Copyright <NAME>, <NAME>, <NAME>, Howard // Hinnant & <NAME> 2000. // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). // // See http://www.boost.org/libs/type_traits for most recent version including documentation. #ifndef BOOST_TT_IS_MEMBER_FUNCTION_POINTER_CXX_11_HPP_INCLUDED #define BOOST_TT_IS_MEMBER_FUNCTION_POINTER_CXX_11_HPP_INCLUDED #include <boost/type_traits/integral_constant.hpp> namespace boost { #ifdef _MSC_VER #define BOOST_TT_DEF_CALL __thiscall #else #define BOOST_TT_DEF_CALL #endif template <class T> struct is_member_function_pointer : public false_type {}; template <class T> struct is_member_function_pointer<T const> : public is_member_function_pointer<T> {}; template <class T> struct is_member_function_pointer<T volatile> : public is_member_function_pointer<T> {}; template <class T> struct is_member_function_pointer<T const volatile> : public is_member_function_pointer<T> {}; #if defined(_MSVC_LANG) && (_MSVC_LANG >= 201703) // MSVC can't handle noexcept(b) as a deduced template parameter // so we will have to write everything out :( #define BOOST_TT_NOEXCEPT_PARAM #define BOOST_TT_NOEXCEPT_DECL #elif defined(__cpp_noexcept_function_type) #define BOOST_TT_NOEXCEPT_PARAM , bool NE #define BOOST_TT_NOEXCEPT_DECL noexcept(NE) #else #define BOOST_TT_NOEXCEPT_PARAM #define BOOST_TT_NOEXCEPT_DECL #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (BOOST_TT_DEF_CALL C::*)(Args...)BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (C::*)(Args..., ...)BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const qualified: template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (BOOST_TT_DEF_CALL C::*)(Args...)const BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)const BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // volatile: template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (BOOST_TT_DEF_CALL C::*)(Args...)volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const volatile template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (BOOST_TT_DEF_CALL C::*)(Args...)const volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)const volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // Reference qualified: template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (BOOST_TT_DEF_CALL C::*)(Args...)& BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)& BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const qualified: template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (BOOST_TT_DEF_CALL C::*)(Args...)const & BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)const & BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // volatile: template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (BOOST_TT_DEF_CALL C::*)(Args...)volatile & BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)volatile & BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const volatile template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (BOOST_TT_DEF_CALL C::*)(Args...)const volatile & BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)const volatile & BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // rvalue reference qualified: template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (BOOST_TT_DEF_CALL C::*)(Args...) && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...) && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const qualified: template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (BOOST_TT_DEF_CALL C::*)(Args...)const && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)const && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // volatile: template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (BOOST_TT_DEF_CALL C::*)(Args...)volatile && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)volatile && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const volatile template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (BOOST_TT_DEF_CALL C::*)(Args...)const volatile && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)const volatile && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #if defined(_MSC_VER) && (defined(_M_AMD64) || defined(_M_IX86)) #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__stdcall C::*)(Args...)BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__fastcall C::*)(Args...)BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__vectorcall C::*)(Args...)BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)const BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__stdcall C::*)(Args...)const BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__fastcall C::*)(Args...)const BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)const BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__vectorcall C::*)(Args...)const BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // volatile: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__stdcall C::*)(Args...)volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__fastcall C::*)(Args...)volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__vectorcall C::*)(Args...)volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const volatile: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)const volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__stdcall C::*)(Args...)const volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__fastcall C::*)(Args...)const volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)const volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__vectorcall C::*)(Args...)const volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // reference qualified: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__stdcall C::*)(Args...)&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__fastcall C::*)(Args...)&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__vectorcall C::*)(Args...)&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)const &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__stdcall C::*)(Args...)const &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__fastcall C::*)(Args...)const &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)const &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__vectorcall C::*)(Args...)const &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // volatile: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__stdcall C::*)(Args...)volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__fastcall C::*)(Args...)volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__vectorcall C::*)(Args...)volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const volatile: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)const volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__stdcall C::*)(Args...)const volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__fastcall C::*)(Args...)const volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)const volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__vectorcall C::*)(Args...)const volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // rvalue reference qualified: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...) && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__stdcall C::*)(Args...) && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__fastcall C::*)(Args...) && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...) && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__vectorcall C::*)(Args...) && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)const &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__stdcall C::*)(Args...)const &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__fastcall C::*)(Args...)const &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)const &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__vectorcall C::*)(Args...)const &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // volatile: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__stdcall C::*)(Args...)volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__fastcall C::*)(Args...)volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__vectorcall C::*)(Args...)volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const volatile: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)const volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__stdcall C::*)(Args...)const volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__fastcall C::*)(Args...)const volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)const volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret (__vectorcall C::*)(Args...)const volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #if defined(_MSVC_LANG) && (_MSVC_LANG >= 201703) #undef BOOST_TT_NOEXCEPT_DECL #define BOOST_TT_NOEXCEPT_DECL noexcept template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(BOOST_TT_DEF_CALL C::*)(Args...)BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const qualified: template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(BOOST_TT_DEF_CALL C::*)(Args...)const BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)const BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // volatile: template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(BOOST_TT_DEF_CALL C::*)(Args...)volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const volatile template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(BOOST_TT_DEF_CALL C::*)(Args...)const volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)const volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // Reference qualified: template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(BOOST_TT_DEF_CALL C::*)(Args...)& BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)& BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const qualified: template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(BOOST_TT_DEF_CALL C::*)(Args...)const & BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)const & BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // volatile: template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(BOOST_TT_DEF_CALL C::*)(Args...)volatile & BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)volatile & BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const volatile template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(BOOST_TT_DEF_CALL C::*)(Args...)const volatile & BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)const volatile & BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // rvalue reference qualified: template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(BOOST_TT_DEF_CALL C::*)(Args...) && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...) && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const qualified: template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(BOOST_TT_DEF_CALL C::*)(Args...)const && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)const && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // volatile: template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(BOOST_TT_DEF_CALL C::*)(Args...)volatile && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)volatile && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const volatile template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(BOOST_TT_DEF_CALL C::*)(Args...)const volatile && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class ...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(C::*)(Args..., ...)const volatile && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #if defined(_MSC_VER) && (defined(_M_AMD64) || defined(_M_IX86)) #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__stdcall C::*)(Args...)BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__fastcall C::*)(Args...)BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__vectorcall C::*)(Args...)BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)const BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__stdcall C::*)(Args...)const BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__fastcall C::*)(Args...)const BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)const BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__vectorcall C::*)(Args...)const BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // volatile: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__stdcall C::*)(Args...)volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__fastcall C::*)(Args...)volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__vectorcall C::*)(Args...)volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const volatile: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)const volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__stdcall C::*)(Args...)const volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__fastcall C::*)(Args...)const volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)const volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__vectorcall C::*)(Args...)const volatile BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // reference qualified: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__stdcall C::*)(Args...)&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__fastcall C::*)(Args...)&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__vectorcall C::*)(Args...)&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)const &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__stdcall C::*)(Args...)const &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__fastcall C::*)(Args...)const &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)const &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__vectorcall C::*)(Args...)const &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // volatile: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__stdcall C::*)(Args...)volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__fastcall C::*)(Args...)volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__vectorcall C::*)(Args...)volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const volatile: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)const volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__stdcall C::*)(Args...)const volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__fastcall C::*)(Args...)const volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)const volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__vectorcall C::*)(Args...)const volatile &BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // rvalue reference qualified: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...) && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__stdcall C::*)(Args...) && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__fastcall C::*)(Args...) && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...) && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__vectorcall C::*)(Args...) && BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)const &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__stdcall C::*)(Args...)const &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__fastcall C::*)(Args...)const &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)const &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__vectorcall C::*)(Args...)const &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // volatile: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__stdcall C::*)(Args...)volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__fastcall C::*)(Args...)volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__vectorcall C::*)(Args...)volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; // const volatile: #ifdef __CLR_VER template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret __clrcall(Args...)const volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #ifdef _M_IX86 template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__stdcall C::*)(Args...)const volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__fastcall C::*)(Args...)const volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__cdecl C::*)(Args...)const volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif template <class Ret, class C, class...Args BOOST_TT_NOEXCEPT_PARAM> struct is_member_function_pointer<Ret(__vectorcall C::*)(Args...)const volatile &&BOOST_TT_NOEXCEPT_DECL> : public true_type {}; #endif #endif #undef BOOST_TT_NOEXCEPT_DECL #undef BOOST_TT_NOEXCEPT_PARAM #undef BOOST_TT_DEF_CALL } #endif // BOOST_TT_IS_MEMBER_FUNCTION_POINTER_CXX_11_HPP_INCLUDED
/** * Recursively count <code>ordinal</code>, whose depth is <code>currentDepth</code>, * and all its descendants down to <code>maxDepth</code> (including), * descendants whose value in the count arrays, <code>arrays</code>, is != 0. * The count arrays only includes the current partition, from <code>offset</code>, to (exclusive) * <code>endOffset</code>. * It is assumed that <code>ordinal</code> < <code>endOffset</code>, * otherwise, not <code>ordinal</code>, and none of its descendants, reside in * the current partition. <code>ordinal</code> < <code>offset</code> is allowed, * as ordinal's descendants might be >= <code>offeset</code>. * * @param ordinal a facet ordinal. * @param youngestChild mapping a given ordinal to its youngest child in the taxonomy (of largest ordinal number), * or to -1 if has no children. * @param olderSibling mapping a given ordinal to its older sibling, or to -1 * @param arrays values for the ordinals in the given partition * @param offset the first (smallest) ordinal in the given partition * @param partitionSize number of ordinals in the given partition * @param endOffset one larger than the largest ordinal that belong to this partition * @param currentDepth the depth or ordinal in the TaxonomyTree (relative to rootnode of the facetRequest) * @param maxDepth maximal depth of descendants to be considered here (measured relative to rootnode of the * facetRequest). * * @return the number of nodes, from ordinal down its descendants, of depth <= maxDepth, * which reside in the current partition, and whose value != 0 */ private int countOnly(int ordinal, int[] youngestChild, int[] olderSibling, FacetArrays arrays, int partitionSize, int offset, int endOffset, int currentDepth, int maxDepth) { int ret = 0; if (offset <= ordinal) { if (0 != facetRequest.getValueOf(arrays, ordinal % partitionSize)) { ret++; } } if (currentDepth >= maxDepth) { return ret; } int yc = youngestChild[ordinal]; while (yc >= endOffset) { yc = olderSibling[yc]; } while (yc > TaxonomyReader.INVALID_ORDINAL) { ret += countOnly (yc, youngestChild, olderSibling, arrays, partitionSize, offset, endOffset, currentDepth+1, maxDepth); yc = olderSibling[yc]; } return ret; }
/** * Attempt to authenticate the user based upon their presented credentials. * This action uses the HTTP parameters of login_email, login_password, and * login_realm as credentials. * * <p>If the authentication attempt is successful then an HTTP redirect will be * sent to the browser redirecting them to their original location in the * system before authenticated or if none is supplied back to the DSpace * home page. The action will also return true, thus contents of the action will * be executed. * * <p>If the authentication attempt fails, the action returns false. * * <p>Example use: * * <pre> * {@code * <map:act name="Authenticate"> * <map:serialize type="xml"/> * </map:act> * <map:transform type="try-to-login-again-transformer"> * } * </pre> * * @author Scott Phillips */ public class OpenidAction extends AbstractAction { /** * Attempt to authenticate the user. * @param redirector redirector. * @param resolver source resolver. * @param objectModel object model. * @param source source * @param parameters sitemap parameters. * @return result of the action. * @throws java.lang.Exception on error. */ @Override public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters parameters) throws Exception { // First check if we are performing a new login Request request = ObjectModelHelper.getRequest(objectModel); final HttpServletResponse httpResponse = (HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT); final String AUTHORIZE = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("org.dspace.app.xmlui.aspect.eperson.openid.authorize"); final String RETURN_URL = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("org.dspace.app.xmlui.aspect.eperson.openid.return_url"); String return_redirect = (RETURN_URL != null) ? RETURN_URL.trim() : "https://biblioteca.digital.gob.cl/callback"; String redirect = URLEncoder.encode(return_redirect, "UTF-8"); final String CLIENT_ID = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("org.dspace.app.xmlui.aspect.eperson.openid.client_id"); final String RESPONSE_TYPE = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("org.dspace.app.xmlui.aspect.eperson.openid.response_type"); final String SCOPE = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("org.dspace.app.xmlui.aspect.eperson.openid.scope"); HttpSession session = request.getSession(); tokenGenerator tg = new tokenGenerator(); session.setAttribute("token", tg.generateHash()); String token = (String)session.getAttribute("token"); httpResponse.sendRedirect(AUTHORIZE +"?client_id="+CLIENT_ID +"&redirect_uri=" +redirect +"&response_type="+RESPONSE_TYPE+"&scope="+SCOPE+"&state=" +token); return null; } }
//Create a tracked object list // those stay constant for the entire length of the run TrackedObjectList::TrackedObjectList(const std::string &trackingBaseFrame) : detectCount_(0) , trackingBaseFrame_(trackingBaseFrame) { }
import { IDatePickerStrings } from './DatePicker.types'; import { defaultCalendarStrings } from '../../Calendar'; export const defaultDatePickerStrings: IDatePickerStrings = { ...defaultCalendarStrings, prevMonthAriaLabel: 'Go to previous month', nextMonthAriaLabel: 'Go to next month', prevYearAriaLabel: 'Go to previous year', nextYearAriaLabel: 'Go to next year', closeButtonAriaLabel: 'Close date picker', isRequiredErrorMessage: 'Field is required', invalidInputErrorMessage: 'Invalid date format', };
/* GetSize Return the number of entries in the selected phonebook object that are actually used (i.e. indexes that correspond to non-NULL entries). Possible errors: org.bluez.obex.Error.Forbidden org.bluez.obex.Error.Failed */ func (a *PhonebookAccess1) GetSize() (uint16, error) { var val0 uint16 err := a.client.Call("GetSize", 0, ).Store(&val0) return val0, err }
// Copyright (c) 2016 CNRS and LIRIS' Establishments (France). // All rights reserved. // // This file is part of CGAL (www.cgal.org) // // $URL$ // $Id$ // SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial // // Author(s) : <NAME> <<EMAIL>> // #ifndef GMAP_TEST_INSERTIONS_H #define GMAP_TEST_INSERTIONS_H #include <CGAL/Generalized_map_operations.h> template<typename GMAP> bool check_number_of_cells_3(GMAP& gmap, unsigned int nbv, unsigned int nbe, unsigned int nbf, unsigned int nbvol, unsigned int nbcc); template<typename GMAP> bool test_vertex_insertion(GMAP& gmap) { typename GMAP::Dart_handle d1, d2, d3; trace_test_begin(); d1 = gmap.create_dart(); gmap.insert_cell_0_in_cell_1(d1); if ( !check_number_of_cells_3(gmap, 2, 1, 1, 1, 1) ) return false; gmap.clear(); trace_test_begin(); d1 = gmap.create_dart(); gmap.template sew<1>(d1, d1); gmap.insert_cell_0_in_cell_1(d1); if ( !check_number_of_cells_3(gmap, 2, 1, 1, 1, 1) ) return false; gmap.clear(); trace_test_begin(); d1 = gmap.make_edge(); gmap.insert_cell_0_in_cell_1(d1); if ( !check_number_of_cells_3(gmap, 3, 2, 1, 1, 1) ) return false; gmap.clear(); trace_test_begin(); d1 = gmap.make_edge(); gmap.template sew<1>(d1, gmap.template alpha<0>(d1)); gmap.insert_cell_0_in_cell_1(d1); if ( !check_number_of_cells_3(gmap, 2, 2, 1, 1, 1) ) return false; gmap.clear(); trace_test_begin(); d1 = gmap.make_edge(); d2 = gmap.make_edge(); gmap.template sew<2>(d1, d2); gmap.insert_cell_0_in_cell_1(d1); if ( !check_number_of_cells_3(gmap, 3, 2, 2, 1, 1) ) return false; gmap.clear(); trace_test_begin(); d1 = gmap.make_edge(); d2 = gmap.make_edge(); gmap.template sew<2>(d1, d2); gmap.template sew<1>(d1, gmap.template alpha<0>(d1)); gmap.insert_cell_0_in_cell_1(d1); if ( !check_number_of_cells_3(gmap, 2, 2, 2, 1, 1) ) return false; gmap.clear(); trace_test_begin(); d1 = gmap.make_edge(); d2 = gmap.make_edge(); gmap.template sew<2>(d1, d2); gmap.template sew<1>(d1, gmap.template alpha<0>(d1)); gmap.template sew<1>(d2, gmap.template alpha<0>(d2)); gmap.insert_cell_0_in_cell_1(d1); if ( !check_number_of_cells_3(gmap, 2, 2, 2, 1, 1) ) return false; gmap.clear(); trace_test_begin(); d1 = gmap.make_combinatorial_polygon(3); d2 = gmap.template alpha<0,1>(d1); d3 = gmap.template alpha<1>(d1); gmap.insert_cell_0_in_cell_1(d1); gmap.insert_cell_0_in_cell_1(d2); gmap.insert_cell_0_in_cell_1(d3); if ( !check_number_of_cells_3(gmap, 6, 6, 1, 1, 1) ) return false; gmap.clear(); trace_test_begin(); d1 = gmap.make_combinatorial_polygon(3); d2 = gmap.make_combinatorial_polygon(3); gmap.template sew<3>(d1, d2); d2 = gmap.template alpha<0,1>(d1); d3 = gmap.template alpha<1>(d1); gmap.insert_cell_0_in_cell_1(d1); gmap.insert_cell_0_in_cell_1(d2); gmap.insert_cell_0_in_cell_1(d3); if ( !check_number_of_cells_3(gmap, 6, 6, 1, 2, 1) ) return false; gmap.clear(); trace_test_begin(); d1 = gmap.make_combinatorial_polygon(3); d2 = gmap.make_combinatorial_polygon(3); gmap.template sew<2>(d1, d2); gmap.insert_cell_0_in_cell_1(d1); if ( !check_number_of_cells_3(gmap, 5, 6, 2, 1, 1) ) return false; gmap.clear(); trace_test_begin(); d1 = gmap.make_combinatorial_polygon(3); d2 = gmap.make_combinatorial_polygon(3); gmap.template sew<2>(d1, d2); gmap.insert_cell_0_in_cell_1(gmap.template alpha<0,1>(d1)); gmap.insert_cell_0_in_cell_1(gmap.template alpha<1>(d1)); gmap.insert_cell_0_in_cell_1(d1); if ( !check_number_of_cells_3(gmap, 7, 8, 2, 1, 1) ) return false; gmap.clear(); trace_test_begin(); d1 = gmap.make_combinatorial_hexahedron(); d2 = gmap.make_combinatorial_hexahedron(); gmap.template sew<3>(d1, d2); gmap.insert_cell_0_in_cell_1(gmap.template alpha<0,1,0,1>(d1)); gmap.insert_cell_0_in_cell_1(gmap.template alpha<0,1>(d1)); gmap.insert_cell_0_in_cell_1(gmap.template alpha<1>(d1)); gmap.insert_cell_0_in_cell_1(d1); if ( !check_number_of_cells_3(gmap, 16, 24, 11, 2, 1) ) return false; gmap.clear(); return true; } template<typename GMAP> bool test_edge_insertion(GMAP& gmap) { typename GMAP::Dart_handle d1, d2, d3; trace_test_begin(); d1 = gmap.make_combinatorial_polygon(4); gmap.insert_cell_1_in_cell_2(d1, gmap.alpha(d1,0,1,0)); if ( !check_number_of_cells_3(gmap, 4, 5, 2, 1, 1) ) return false; gmap.clear(); trace_test_begin(); d1 = gmap.make_combinatorial_polygon(4); d2 = gmap.make_combinatorial_polygon(4); gmap.template sew<3>(d1, d2); gmap.insert_cell_1_in_cell_2(d1, gmap.alpha(d1,0,1,0)); if ( !check_number_of_cells_3(gmap, 4, 5, 2, 2, 1) ) return false; gmap.clear(); trace_test_begin(); d1 = gmap.make_combinatorial_polygon(4); d2 = gmap.make_combinatorial_polygon(4); gmap.template sew<2>(d1, d2); gmap.insert_cell_1_in_cell_2(d1, gmap.alpha(d1,0,1,0)); if ( !check_number_of_cells_3(gmap, 6, 8, 3, 1, 1) ) return false; gmap.clear(); trace_test_begin(); d1 = gmap.create_dart(); gmap.insert_dangling_cell_1_in_cell_2(d1); if ( !check_number_of_cells_3(gmap, 2, 2, 1, 1, 1) ) return false; gmap.clear(); trace_test_begin(); d1 = gmap.make_edge(); gmap.template sew<1>(d1, gmap.alpha(d1, 0)); gmap.insert_dangling_cell_1_in_cell_2(d1); if ( !check_number_of_cells_3(gmap, 2, 2, 1, 1, 1) ) return false; gmap.clear(); trace_test_begin(); d1 = gmap.make_edge(); d2 = gmap.make_edge(); gmap.template sew<3>(d1, d2); gmap.template sew<1>(d1, gmap.alpha(d1, 0)); gmap.insert_dangling_cell_1_in_cell_2(d1); if ( !check_number_of_cells_3(gmap, 2, 2, 1, 2, 1) ) return false; gmap.clear(); trace_test_begin(); d1 = gmap.make_combinatorial_polygon(4); gmap.insert_dangling_cell_1_in_cell_2(d1); if ( !check_number_of_cells_3(gmap, 5, 5, 1, 1, 1) ) return false; gmap.clear(); trace_test_begin(); d1 = gmap.make_combinatorial_polygon(4); d2 = gmap.make_combinatorial_polygon(4); gmap.template sew<3>(d1, d2); gmap.insert_dangling_cell_1_in_cell_2(d1); if ( !check_number_of_cells_3(gmap, 5, 5, 1, 2, 1) ) return false; gmap.clear(); trace_test_begin(); d1 = gmap.make_combinatorial_polygon(4); d2 = gmap.make_combinatorial_polygon(4); gmap.template sew<2>(d1, d2); gmap.insert_dangling_cell_1_in_cell_2(d1); if ( !check_number_of_cells_3(gmap, 7, 8, 2, 1, 1) ) return false; gmap.clear(); return true; } template<typename GMAP> bool test_face_insertion(GMAP& gmap) { typename GMAP::Dart_handle d1, d2, d3; std::vector<typename GMAP::Dart_handle> v; trace_test_begin(); d1 = gmap.make_combinatorial_polygon(4); v.push_back(d1); v.push_back(gmap.alpha(v[0],0,1)); v.push_back(gmap.alpha(v[1],0,1)); v.push_back(gmap.alpha(v[2],0,1)); gmap.insert_cell_2_in_cell_3(v.begin(),v.end()); if ( !check_number_of_cells_3(gmap, 4, 4, 2, 1, 1) ) return false; gmap.clear(); v.clear(); trace_test_begin(); d1 = gmap.make_combinatorial_polygon(3); d2 = gmap.make_combinatorial_polygon(3); gmap.template sew<2>(d1, d2); v.push_back(d1); v.push_back(gmap.alpha(v[0],0,1)); v.push_back(gmap.alpha(v[1],0,1)); gmap.insert_cell_2_in_cell_3(v.begin(),v.end()); if ( !check_number_of_cells_3(gmap, 4, 5, 3, 2, 1) ) return false; gmap.clear(); v.clear(); trace_test_begin(); d1 = gmap.make_combinatorial_hexahedron(); d2 = gmap.alpha(d1,2); v.push_back(d2); v.push_back(gmap.alpha(v[0],0,1,2,1)); v.push_back(gmap.alpha(v[1],0,1,2,1)); v.push_back(gmap.alpha(v[2],0,1,2,1)); gmap.insert_cell_2_in_cell_3(v.begin(),v.end()); if ( !check_number_of_cells_3(gmap, 8, 12, 7, 2, 1) ) return false; gmap.clear(); v.clear(); trace_test_begin(); d1 = gmap.make_combinatorial_hexahedron(); d2 = gmap.make_combinatorial_hexahedron(); gmap.template sew<3>(d1,d2); d3 = gmap.alpha(d1, 2); gmap.template remove_cell<2>(d1); v.push_back(d3); v.push_back(gmap.alpha(v[0],0,1,2,1)); v.push_back(gmap.alpha(v[1],0,1,2,1)); v.push_back(gmap.alpha(v[2],0,1,2,1)); gmap.insert_cell_2_in_cell_3(v.begin(),v.end()); if ( !check_number_of_cells_3(gmap, 12, 20, 11, 2, 1) ) return false; GMAP gmap2; d1 = gmap2.make_combinatorial_hexahedron(); d2 = gmap2.make_combinatorial_hexahedron(); gmap2.template sew<3>(d1,d2); if ( !gmap.is_isomorphic_to(gmap2, false, false, false) ) { std::cout<<"Error: gmap and gmap2 are not isomorphic (after insertion/removal).\n"; assert(false); return false; } if (CGAL::degree<GMAP, 0>(gmap2, d1)!=4) { std::cout<<"Error: 0-degree is wrong: "<<CGAL::degree<GMAP, 0>(gmap2, d1)<<" instead of 4."<<std::endl; assert(false); return false; } if (CGAL::degree<GMAP, 1>(gmap2, d1)!=3) { std::cout<<"Error: 1-degree is wrong: "<<CGAL::degree<GMAP, 1>(gmap2, d1)<<" instead of 3."<<std::endl; assert(false); return false; } if (CGAL::degree<GMAP, 2>(gmap2, d1)!=2) { std::cout<<"Error: 2-degree is wrong: "<<CGAL::degree<GMAP, 2>(gmap2, d1)<<" instead of 2."<<std::endl; assert(false); return false; } if (CGAL::codegree<GMAP, 1>(gmap2, d1)!=2) { std::cout<<"Error: 1-codegree is wrong: "<<CGAL::codegree<GMAP, 1>(gmap2, d1)<<" instead of 2."<<std::endl; assert(false); return false; } if (CGAL::codegree<GMAP, 2>(gmap2, d1)!=4) { std::cout<<"Error: 2-codegree is wrong: "<<CGAL::codegree<GMAP, 2>(gmap2, d1)<<" instead of 4."<<std::endl; assert(false); return false; } if (CGAL::codegree<GMAP, 3>(gmap2, d1)!=6) { std::cout<<"Error: 3-codegree is wrong: "<<CGAL::codegree<GMAP, 3>(gmap2, d1)<<" instead of 6."<<std::endl; assert(false); return false; } gmap.clear(); v.clear(); return true; } #endif // GMAP_TEST_INSERTIONS_H
/// <summary> /// If we determine that this till doesn't actually need a true escape continuation, then let's /// not spend CPU or memory at runtime creating or maintaining one! We do this by removing /// all of the NewTill/EndTill instructions that we generated, since there are no matching TillEsc /// instructions that require them. /// </summary> static void RemoveTillContinuation(CompiledBlock compiledBlock, IntermediateInstruction tillBlockInstr, CompileScope tillScope, SmileList flags) { SmileList temp; Int index; CompiledTillSymbol compiledTillSymbol; SmileSymbol smileSymbol; IntermediateInstruction instr; CompiledBlock endTillBlock; CompiledBlock_DetachInstruction(compiledBlock, tillBlockInstr); for (temp = flags, index = 0; SMILE_KIND(temp) == SMILE_KIND_LIST; temp = LIST_REST(temp), index++) { smileSymbol = (SmileSymbol)temp->a; compiledTillSymbol = (CompiledTillSymbol)CompileScope_FindSymbolHere(tillScope, smileSymbol->symbol); instr = compiledTillSymbol->whenLabel->next; endTillBlock = instr->p.childBlock; if (instr->opcode != Op_Block || endTillBlock == NULL || !((endTillBlock->numInstructions == 0 && endTillBlock->first == NULL) || (endTillBlock->numInstructions == 2 && endTillBlock->first->next->opcode == Op_EndTill))) Smile_Abort_FatalError("Compiler generated an invalid EndTill block."); CompiledBlock_Clear(endTillBlock); } }
<gh_stars>1-10 package vkutil type ObjectType string //go:generate stringer -type=ObjectType const ( OBJECT_USER ObjectType = "user" OBJECT_POST = "post" // — запись на стене пользователя или группы; OBJECT_COMMENT = "comment" // — комментарий к записи на стене; OBJECT_PHOTO = "photo" //— фотография; OBJECT_AUDIO = "audio" // — аудиозапись; OBJECT_VIDEO = "video" // — видеозапись; OBJECT_NOTE = "note" // — заметка; OBJECT_PHOTO_COMMENT = "photo_comment" // — комментарий к фотографии; OBJECT_VIDEO_COMMENT = "video_comment" // — комментарий к видеозаписи; OBJECT_TOPIC_COMMENT = "topic_comment" // — комментарий в обсуждении; OBJECT_GROUP = "group" OBJECT_APPLICATION = "application" OBJECT_PAGE = "page" ) func (o *ObjectType) UnmarshalJSON(in []byte) error { *o = ObjectType(string(in[1 : len(in)-1])) return nil }
def _search(self, key, node): i = 0 while i < len(node.keys) and key > node.keys[i]: i += 1 if i < len(node.keys) and key == node.keys[i]: return node, i elif node.leaf: return None, None else: return self._search(key, node.childs[i])
Ghostbusters Product FAQs The following are answers to the frequently asked questions for the GHOSTBUSTERS™ product line that we are currently developing. What items does ANOVOS intend to produce? Screen accurate full-size props in kit form (end user assembled and painted). Screen accurate full-size complete prop replicas, ready to wear/display. Screen accurate wearable uniforms/jumpsuits. Scaled prop replicas and collectibles for desktop/tabletop display. Will you produce items from the original films, cartoon series or 2016 film? At this time, we are licensed to produce items from Ghostbusters (1984) and Ghostbusters II (1989). What price range should we expect for these items? Pricing for products not yet released has not been determined and will obviously vary from piece to piece. Will you include electronics, lights or sound? We hope to offer some fully-built props with lights and sound. We also plan to offer kit versions with options for electronics. Make sure to subscribe to our newsletter for updates. Will you be making any "inspired by" or "off screen" items like jackets or women's dresses? This is still to be determined, but we are licensed to create derived jackets. Where will you be shipping to? We will be shipping to the following countries: United States Canada Australia Austria China Germany France Italy Ireland Japan New Zealand Spain Switzerland Taiwan United Kingdom PROTON PACK Will you be releasing a completed ready-to-wear version of the Proton Pack? Yes, but we are still working out the details as far as pricing and enhancements that will make it differ from the kit version. Will the thrower/Neutrino Wand have an extending barrel? Yes, but we are still determining if it will be spring-loaded or manual extension. Please subscribe to our newsletter for product updates. What is the motherboard made of? Although features are subject to change during development, this is currently planned to be made of plastic. How heavy is the pack? We will not have a good approximation of the final weight until production is completed. Please subscribe to our newsletter for product updates. Exactly how much assembly is required of the kit? (How many separate parts, trimming, gluing required, painting?) We are still in the process of engineering individual components and do not have a final piece count. Most of the assembly will use fasteners (screws) for solid connections. Almost all the pieces will require paint/finishing of some kind. We will be providing detailed downloadable assembly instructions to make it as easy as possible for novice builders. Can you easily add electronics after you’ve built the kit? Because most of the major assemblies are fastened together with machine screws, the disassembly is fairly straightforward and should only require reversing certain assembly steps to make modifications like the electronics upgrade. Is this a Ghostbusters 1 (1984) or Ghostbusters 2 (1989) style Proton Pack? Though the differences are very minor, this Proton Pack leans toward the Ghostbusters 2 style. Please contact [email protected] for other questions relating to the Ghostbusters line, and be sure you are subscribed to our newsletter. As long-time fans, we're excited to bring these items to life...and we're ready to believe you! Ghostbusters TM & ©2016 Columbia Pictures Industries, Inc. All Rights Reserved.
def parse_pr(pr_txt: str) -> Dict[str, Union[dt.date, int, Dict[str, Any]]]: new_cases, new_deaths = _get_new_cases_deaths(pr_txt) hd_cases_deaths = _parse_hd_cases_deaths(pr_txt) return { const.DATE: _parse_date(pr_txt), const.NEW_CASES: new_cases, const.NEW_DEATHS: new_deaths, const.HOSPITALIZATIONS: _parse_hospitalizations(pr_txt), const.CASES: hd_cases_deaths[const.CASES], const.DEATHS: hd_cases_deaths[const.DEATHS], const.CASES_BY_AGE: _parse_age_cases(pr_txt), const.CASES_BY_GENDER: _parse_gender(pr_txt), const.CASES_BY_RACE: _parse_race_cases(pr_txt), const.DEATHS_BY_RACE: _parse_race_deaths(pr_txt), const.AREA: _parse_csa(pr_txt) }
package com.cscot.basicnetherores.api; import com.cscot.basicnetherores.BasicNetherOres; import net.minecraft.item.BlockItem; import net.minecraft.item.Item; import net.minecraft.util.Identifier; import java.util.HashMap; import java.util.Map; public class ItemLists { //All Blocks are added to this list for registration public static final Map<Identifier, BlockItem> ITEMS = new HashMap<>(); public static final Map<Identifier, Item> INGOTS = new HashMap<>(); //Ingots List public static Item ALUMINUM_INGOT = addItem("aluminum_ingot", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); //public static Item COPPER_INGOT = addItem("copper_ingot", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); public static Item LEAD_INGOT = addItem("lead_ingot", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); public static Item NICKEL_INGOT = addItem("nickel_ingot", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); public static Item SILVER_INGOT = addItem("silver_ingot", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); public static Item TIN_INGOT = addItem("tin_ingot", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); public static Item OSMIUM_INGOT = addItem("osmium_ingot", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); public static Item URANIUM_INGOT = addItem("uranium_ingot", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); //Nugget List public static Item ALUMINUM_NUGGET = addItem("aluminum_nugget", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); public static Item COPPER_NUGGET = addItem("copper_nugget", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); public static Item LEAD_NUGGET = addItem("lead_nugget", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); public static Item NICKEL_NUGGET = addItem("nickel_nugget", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); public static Item SILVER_NUGGET = addItem("silver_nugget", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); public static Item OSMIUM_NUGGET = addItem("osmium_nugget", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); public static Item TIN_NUGGET = addItem("tin_nugget", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); //Raw Ore List public static Item RAW_ALUMINUM = addItem("raw_aluminum", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); public static Item RAW_LEAD = addItem("raw_lead", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); public static Item RAW_NICKEL = addItem("raw_nickel", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); public static Item RAW_SILVER = addItem("raw_silver", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); public static Item RAW_TIN = addItem("raw_tin", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); public static Item RAW_OSMIUM = addItem("raw_osmium", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); public static Item RAW_URANIUM = addItem("raw_uranium", new Item((new Item.Settings()).group(BasicNetherOres.ITEMGROUP))); public static <I extends BlockItem> I add(String name, I item) { item.appendBlocks(Item.BLOCK_ITEMS, item); ITEMS.put(new Identifier(BasicNetherOres.MOD_ID, name), item); return item; } public static <I extends Item> I addItem(String name, I item) { INGOTS.put(new Identifier(BasicNetherOres.MOD_ID, name), item); return item; } }
/** * Exchange a number of `unleveraged_assets` for their equivalent in leveraged * assets. Track this change in MINTSTATE. * * Assumes the position was already approved by `mint_man` */ pub fn create_leveraged_position( storage: &mut dyn Storage, sender: &Addr, mint_count: Uint128, unleveraged_assets: Uint128, ) -> Result<MinterPosition, ContractError> { let mut state = POOLSTATE.load(storage)?; let already_minted = match MINTSTATE.load(storage, &sender) { Ok(mint) => mint, _ => Uint128::zero(), }; let new_mint_count = already_minted + mint_count; MINTSTATE.save(storage, &sender, &new_mint_count)?; state.assets_in_reserve += unleveraged_assets; state.total_leveraged_pool_share += mint_count; state.total_leveraged_assets += mint_count; POOLSTATE.save(storage, &state)?; Ok(MinterPosition { leveraged_pool_partial_share: mint_count, leveraged_pool_total_share: state.total_leveraged_pool_share, }) }
/** * <p>Add a chain of trusted certificates to this X509Store.</p> * * <p>The first certificate in the chain must be self-signed, and all * certificates must be CA certificates. The list must be ordered with the * root certificate in the first position and the leaf certificate in the * last position.</p> * * @param chain the ordered chain of certificates. * @throws NoSuchAlgorithmException if the signature algorithm is * unsupported. * @throws InvalidKeyException if an certificate's public key is invalid. * @throws NoSuchProviderException if there is no signature provider. * @throws SignatureException if a certificate signature verification fails. * @throws CertificateExpiredException if the certificate is expired. * @throws CertificateNotYetValidException if the certificate is not yet * valid. * @throws CertificateException if a certificate is malformed or the first * certificate is not a self-signed certificate. */ public void addTrusted(final List<X509Certificate> chain) throws CertificateExpiredException, CertificateNotYetValidException, CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException { if (chain == null || chain.isEmpty()) return; X509Certificate issuer = chain.get(0); if(!isSelfSigned(issuer)) throw new CertificateException("First certificate is not self-signed: " + Base64.encode(issuer.getEncoded())); addTrusted(issuer); for (int i = 1; i < chain.size(); ++i) { final X509Certificate cert = chain.get(i); cert.verify(issuer.getPublicKey()); addTrusted(cert); issuer = cert; } }
Growth prediction methods: A review Growth prediction is an estimation of the amount of growth to be expected. In orthodontics the term refers to the estimation of amount and direction of growth of the bones of the craniofacial skeletal and overlying soft tissues. Successful prediction requires specifying both the amount and the direction of growth, in relation to the reference point. Estimation of dentofacial growth must consider the increments, vectors, area, duration and timing of growth accessions. All these are subjected to the changes in growth pattern the the unrestricted any medium, the original and source are credited. Introduction Growth prediction is an estimation of the amount of growth to be expected. In orthodontics the term refers to the estimation of amount and direction of growth of the bones of the craniofacial skeletal and overlying soft tissues. Successful prediction requires specifying both the amount and the direction of growth, in relation to the reference point. 1 Estimation of dentofacial growth must consider the increments, vectors, area, duration and timing of growth accessions. All these are subjected to the changes in growth pattern. The ability to predict the magnitude and direction of a patient's facial growth early in life would enable the clinician to identify those individual who requires interceptive growth modification and to ensure that the appropriate treatment can be rendered while growth is expected. Growth prediction helps the clinician to intercept and correct the malocclusion. It can be used as patient education aids. Growth prediction (VTO) is helpful in 'visualizing' the treatment objectives and prioritizes the objectives, keeping in mind the growth pattern of the patient. A tool for orthodontic treatment planning but without adolescents. 3. Even as it permits the observation of the changes in the sagittal jaw relations with growth change occurring in the vertical relations are to a large extent. For clinical purpose according to Bjork the analysis of the vertical development of the face may be improved by using natural reference structure in mandible by superimposing two radiographs taken at different ages and orienting them with references to this structures, growth pattern of the mandible can be estimated with fairly high degree of accuracy. 2 Metric method This aim at a prediction of the facial development on the basis of the facial morphology determined metrically from a single radiographic film. 3 However statistical studies of the possibility of the predicting the intensity of the directions of subsequent development from size and shape at childhood. Indicate that this method is not feasible at least from a clinical point of view no matter with system cephalometric analysis has been used. Structural method This is based on the information concerning of the remodelling process of the mandible during growth, gained from the implant studies by Bjork. 4 The principle is recognized specific structural features those results of the remodelling particular type of mandibular rotation. 5 A prediction of subsequent course is then made on the assumption that the trend will continue. It easier now to classify growth prediction methods into: 1. Cephalometric methods. 2. Non-cephalometric methods. Tweed stated that the faces of all children grow downward and forward in one of the three ways. Therefore, facial growth trends may be classified as type A, Type B and Type C, each having subdivision. 6 Type A growth trend Growth is approximately equal in both vertical and horizontal directions. According to Tweed, approximately 25% of patients present this type of growth trend. Type B growth trend In this type, the growth is downward and forward with the middle face growing forward more rapidly than the lower, as designed by the increase in ANB angle. If ANB is less than 4 • , prognosis is fair and reasonably acceptable facial changes and good occlusion can be attained with proper and determined treatment procedures. Type C growth trend In which type, the lower face is growing downward and forward more rapidly than the middle face, with a decrease in ANB reading. The prognosis is excellent for treatment of patient with Type C growth trend as far as facial esthetics is concerned. About 60% of the patients exhibit this type of growth trend, according to Tweed. (Ricketts, 1972) Robert M. Ricketts, in 1972, using trial and error procedure with longitudinal cephalometric records and computers has developed a method to determine the arc of growth of mandible. Considering arcial development as a basic explanation of mandibular growth is "A normal human mandible grows by superior anterior (vertical) apposition at the ramus or the curve or arc which is a segment formed from a circle. 7 The radius of this circle is determined by using the distance from mental protuberance (Pm) to a point at the forking of the stress lines at the terminus of the oblique ridge on the medial side of the ramus (point-eva)" Implication of growth principle have been summarized by Rickettsas 1. Symphysis rotates during growth from a horizontal to a more vertical inclination, and the genial tubercles and the lingual plate drop downward in the process. this explains the characteristics "chin -button development" in the cephalometric film. Implant studies show that greatest apposition takes place at the inferior margin of the symphysis (and perhaps the posterior side) in preschool years. The apposition may appear lateral to the midline on the symphysis as bulk is needed for bracing. 2. This phenomenon explains the observation of reversal lines at the pogonion and supragonion. 3. It explains why mandibular plane changes extensively in some individuals 4. It shows why ankylosed teeth affect occlusal plane development 5. It explains how the early ankylosis of the lower molar terminal with the tooth located at the lower border of the mandible, the mandibular arc continues to grow and this tooth becomes trooped within the cortical bone and the lower border resorbs up to it 6. It suggests why mandibular anchorage is risky in retrognathic faces, because less space is available for molar eruption due to a more vertical eruption in that type than prognathic types. 7. It explains why the lower arches of brachyfacial (tight arc cases) can be expanded and brought and will remains stable. 8. It explains why good dentures may become progressively more crowded in long, tapered faces and sometimes in normal faces. 9. It explains how the third molar impaction can occur by bone growth around the molar rather than its submergence into ramus (however, it appears that both the processes are involved). 10. It offers a possibility that impaction of the third molars can be prevented by simple enucleation (at age 6-8) of the bud which lies on the surface, not within the bone. 11. It suggests that abnormal growth of mandible can be understood as a function of relative contribution of the coronoid and condyloid processes. 12. It shows why positioning of the roots of the lower first molar to the buccal, or locking them under cortical bone, will prevent upward and, therefore, forward eruption of the whole lower dental arch thereby enhancing of lower teeth. Drawbacks of arcial growth prediction 1. It relies heavily on the operator's skill in tracing the cephalogram. Minor tracing errors could produce a grossly wrong prediction. 2. Ricketts uses patient's chronological age rather than skeletal age, since he requires no hand -wrist radiograph. Since average growth increments are added to the age, if the patient has completed growth or if he is in a growth spurt, or a lag phase, it will alter the results, particularly if the time interval is short and the patient is near maturity. Mitchell and Jordan, in their evaluation of arcial growth prediction method conclude that hand -wrist radiograph will improve the accuracy of the short range prediction of the amount of growth expected. 3. Since the growth increment constants are derived from western population, the applicability of the same to any other population (e.g. Indian population) must be verified. 4. The method does not take into account the growth of the condyle and ramus laterally in the third dimension. 5. Method fails to predict the mandibular growth in cases of true prognathism, or in cases of environment disturbance in growth. Tooth mineralization as an indicator of the pubertal growth spurt The commencement of adolescent peak growth velocity in body height and facial growth is closely related in timing to certain ossification events which occur in the hand and wrist. An investigation into calcification patterns of the teeth revealed a high degree of correlation between the stage of mineralization of the lower canine and these events. 8 The state of mineralization was related to degree of calcification of the hook of hamate, and the development of the epiphysis of the middle phalanx of third finger. He found that calcification stage G of the mandibular canine correlated the best with other maturational indicators. Frontal sinus as a predictor of mandibular growth Rossouw, Lombard, and Harris, in 1991, attempted to assess the correlation between the frontal sinus and the mandibular growth. The author concluded that although the frontal sinus is exposed to muscles attachment it and to influences from the external environment that play a part in the its size, "the frontal sinus as seen on a lateral cephalogram is a valuable indicator of excessive mandibular growth." Thus, patient having a large frontal sinus, according to the study, would most probably present an excessive mandibular growth. 9 Visualized treatment Objective It is a procedure based primarily on cephalometrics, the purpose of which is to establish a balanced profile and pleasing facial aesthetics and to evaluate the orthodontic correction necessary to achieve this goal. This is core of the few methods that emphasize the soft tissue profile balance of the patient's face. Guidelines are provided whereby the lips are graphically repositioned. 10 A template may be used to facilitate drawing the soft tissue of the lips. This is followed by location of the maxillary incisor teeth. Finally, the lower incisors are repositioned to be in harmony with the upper incisors. Following upon the repositioning of the mandibular incisor, the resultant arch length discrepancy may be calculated to determine whether or not teeth should be extracted prior to orthodontic correction. Should the computed information suggest that teeth be extracted, the V.T.O. will yield information based on anchorage requirements as to whether first or second bicuspids should be removed, or whether the proposed treatment plan is feasible or desirable. The V.T.O. accomplishes the following: 1. Predicts growth over an estimated treatment time, based on the individual morphogenetic pattern. 2. Analyzes the soft tissue facial profile. 3. Graphically plans the best soft tissue facial profile for the particular patient. 4. Determines favourable incisor repositioning, based on an "ideal" projected soft tissue facial profile. 5. Assists in determining total arch length discrepancy when taking into account "cephalometric correction". 6. Aids in determining between extraction and nonextraction treatment. 7. Aids in deciding which teeth to extract, if extractions are indicated. 8. Assists in planning treatment mechanics. 9. Assists in deciding which cases are more suited to surgical and/or surgical-orthodontic correction. 10. It provides a visual goal or objective for which to strive during treatment. The V.T.O. procedure described is based on concepts of growth prediction which relate facial skeletal structural changes to the base of the craniofacial complex. Hand wrist radiograph Fishman developed a system of hand-wrist skeletal maturation indicators (SMIs) using four stages of bone maturation at six anatomic sites on the hand and the wrist. 11 Also in 1982, Hagg and Tarangercreated a method using the hand-wrist radiograph to correlate certain maturity indicators to the pubertal growth spurt. Hand wrist radiograph is "the most standardized and studied method of skeletal age assessment", according to Smith in 1982, Fishman published a system for assessment of skeletal maturation on the basis of 11 discrete "skeletal maturity indicator" covering the entire period of adolescence development. The indicators provide identification of the progressive maturation events and are located on a six anatomic sites located on the thumb, third finger, fifth finger and radius. Skeletal Maturity Indicators (SMI) Width of epiphysis as wide as diaphysis 1. Third Finger-Proximal Phalanx Incisor positions The computer also proved to be inaccurate in measuring the anteroposterior changes in molar position. Both the maxillary and mandibular first molars were found to be more posterior (relative to the pterygovertical plane). Soft tissues The computer prediction of the soft-tissue profile was not very accurate Conclusion of computerised growth prediction: 1. The computer was accurate in its prediction of the amount of growth in the anterior cranial base and the upper anterior facial height. 2. The computer underestimated the amount of increase in posterior facial height and lower anterior facial height. 3. The computer was accurate in predicting the effects of growth and orthodontic treatment on mandibular length but underestimated the amount of backward mandibular rotation. 4. The computer was accurate in predicting the effects of growth and orthodontic treatment on the degree of maxillary rotation but overestimated the increase in anteroposterior maxillary length. 5. The computer was accurate in predicting the effects of growth and orthodontic treatment on mandibular incisor position but overestimated the amount of distal movement of the maxillary incisor. 6. The computer underestimated the amount of vertical eruption of the maxillary molars and overestimated the amount of vertical eruption of the mandibular molars. 7. The computer overestimated the amount of forward movement of the maxillary and mandibular Molars. 8. The computer was inaccurate in predicting the effects of growth and orthodontic treatment on the size of the nose and the relative anteroposterior positions of the upper lip, lower lip, and soft-tissue chin. Disadvantage Expensive and trained man power. Recent computer software systems for growth prediction 1. QUICK CEPH for Apple Mackintosh 2. Rocky Mountain data systems for IBM mainframe systems. 3. Facial print for IBM personal computer.
<gh_stars>0 import { PartialType } from '@nestjs/mapped-types'; import { ChoreDto } from './create-chore.dto'; export interface UpdateChoreDto extends ChoreDto {}
<filename>src/day9.rs //! Link: https://adventofcode.com/2019/day/9 //! Day 9: Sensor Boost //! //! You've just said goodbye to the rebooted rover and left Mars when you receive //! a faint distress signal coming from the asteroid belt. It must be the Ceres monitoring station! //! //! In order to lock on to the signal, you'll need to boost your sensors. //! The Elves send up the latest BOOST program - Basic Operation Of System Test. //! //! While BOOST (your puzzle input) is capable of boosting your sensors, //! for tenuous safety reasons, it refuses to do so until the computer it runs on //! passes some checks to demonstrate it is a complete Intcode computer. use failure::Error; use std::str::FromStr; use crate::common::intcode_old::IntcodeVM; #[aoc_generator(day9)] fn input_generator(input: &str) -> IntcodeVM { IntcodeVM::from_str(input).unwrap() } // Your existing Intcode computer is missing one key feature: // it needs support for parameters in relative mode. // // Parameters in mode 2, relative mode, behave very similarly to parameters in position mode: // the parameter is interpreted as a position. // Like position mode, parameters in relative mode can be read from or written to. // // The important difference is that relative mode parameters don't count from address 0. // Instead, they count from a value called the relative base. The relative base starts at 0. // // The address a relative mode parameter refers to is itself plus the current relative base. // When the relative base is 0, relative mode parameters and position mode parameters with // the same value refer to the same address. // // The relative base is modified with the relative base offset instruction: // - Opcode 9 adjusts the relative base by the value of its only parameter. // The relative base increases (or decreases, if the value is negative) by the value of the parameter. // // Your Intcode computer will also need a few other capabilities: // - The computer's available memory should be much larger than the initial program. // Memory beyond the initial program starts with the value 0 and // can be read or written like any other memory. // (It is invalid to try to access memory at a negative address, though.) // - The computer should have support for large numbers. // Some instructions near the beginning of the BOOST program will verify this capability. // // The BOOST program will ask for a single input; run it in test mode by providing it the value 1. // It will perform a series of checks on each opcode, // output any opcodes (and the associated parameter modes) that seem to be functioning incorrectly, // and finally output a BOOST keycode. // // Once your Intcode computer is fully functional, // the BOOST program should report no malfunctioning opcodes when run in test mode; // it should only output a single value, the BOOST keycode. // What BOOST keycode does it produce? // // Your puzzle answer was 2789104029. #[aoc(day9, part1, IntcodeVM)] fn solve_part1_intcode(vm: &IntcodeVM) -> Result<i64, Error> { let output = vm.clone().simple_input(vec![1]).execute_and_collect()?; Ok(*output.first().expect("expected output to contain at least one value")) } // You now have a complete Intcode computer. // // Finally, you can lock on to the Ceres distress signal! // You just need to boost your sensors using the BOOST program. // // The program runs in sensor boost mode by providing the input instruction the value 2. // Once run, it will boost the sensors automatically, // but it might take a few seconds to complete the operation on slower hardware. // In sensor boost mode, the program will output a single value: // the coordinates of the distress signal. // // Run the BOOST program in sensor boost mode. // What are the coordinates of the distress signal? // // Your puzzle answer was 32869. #[aoc(day9, part2, IntcodeVM)] fn solve_part2_intcode(vm: &IntcodeVM) -> Result<i64, Error> { let output = vm.clone().simple_input(vec![2]).execute_and_collect()?; Ok(*output.first().expect("expected output to contain at least one value")) }
/** * A {@link BoundLocation} holds location information for a bound of a type parameter of a class or * method: parameter index and bound index. It also handles type parameters themselves (not just the * bound part). It would be better named "TypeParameterLocation", or the two uses could be separated * out. */ public final class BoundLocation { /** * The index of the parameter to which the bound applies among all type parameters of the class or * method. */ public final int paramIndex; /** * The index of the bound among all bounds on the type parameter. -1 if for the type parameter * itself. */ public final int boundIndex; /** * Constructs a new {@link BoundLocation}; the arguments are assigned to the fields of the same * names. */ public BoundLocation(int paramIndex, int boundIndex) { this.paramIndex = paramIndex; this.boundIndex = boundIndex; } /** * Returns whether this {@link BoundLocation} equals <code>o</code>; a slightly faster variant of * {@link #equals(Object)} for when the argument is statically known to be another nonnull {@link * BoundLocation}. */ public boolean equals(BoundLocation l) { return paramIndex == l.paramIndex && boundIndex == l.boundIndex; } /** * This {@link BoundLocation} equals <code>o</code> if and only if <code>o</code> is another * nonnull {@link BoundLocation} and <code>this</code> and <code>o</code> have equal {@link * #paramIndex} and {@link #boundIndex}. */ @Override public boolean equals(Object o) { return o instanceof BoundLocation && equals((BoundLocation) o); } @Override public int hashCode() { return Objects.hash(paramIndex, boundIndex); } @Override public String toString() { return "BoundLocation(" + paramIndex + "," + boundIndex + ")"; } }
import { generateId } from "../helpers/generateId"; import { Book } from "./Book"; import { Borrower } from "./Borrower"; export class Borrow { private id: string; private borrower: Borrower; private returnDate: Date; private borrowDate: Date; private borrowedBook: Book; constructor(options: BorrowOptions) { this.id = `borrow-${generateId()}`; this.borrower = options.borrower; this.borrowedBook = options.borrowedBook; if (options.borrowDate) { if (options.returnDate.getTime() < options.borrowDate.getTime()) { this.returnDate = options.returnDate; this.borrowDate = options.borrowDate; } else { throw new Error("Return date must be always a head of borrow date."); } } else { this.borrowDate = new Date(); this.returnDate = options.returnDate; } } getId() { return this.id; } getBorrower() { return this.borrower; } getBorrowedBook() { return this.borrowedBook; } getReturnDate() { return this.returnDate; } getBorrowDate() { return this.borrowDate; } timeTillReturnBook(): Date { return new Date(this.returnDate.getTime() - this.borrowDate.getTime()); } } export interface BorrowOptions { returnDate: Date; borrowDate?: Date; borrowedBook: Book; borrower: Borrower; }
def parse_path_from_file(file_path): try: with codecs.open(file_path, encoding='utf-8', mode='r') as f: content = f.read() except IOError as e: log.warning('(Search Index) Unable to index file: %s, error: %s', file_path, e) return '' page_json = json.loads(content) path = page_json['url'] path = re.sub('/$', '/index', path) path = re.sub('\.html$', '', path) path = re.sub('^/', '', path) return path