content
stringlengths
128
6.74k
<commit_msg>Switch underlying implementation to Set from List. <commit_before>package org.nwapw.abacus.lexing.pattern; import java.util.ArrayList; public class PatternNode<T> { protected ArrayList<PatternNode<T>> outputStates; public PatternNode(){ outputStates = new ArrayList<>(); } public boolean matches(char other){ return false; } public char range(){ return '\0'; } public void addInto(ArrayList<PatternNode<T>> into){ into.add(this); } } <commit_after>package org.nwapw.abacus.lexing.pattern; import java.util.ArrayList; import java.util.HashSet; public class PatternNode<T> { protected HashSet<PatternNode<T>> outputStates; public PatternNode(){ outputStates = new HashSet<>(); } public boolean matches(char other){ return false; } public char range(){ return '\0'; } public void addInto(ArrayList<PatternNode<T>> into){ into.add(this); } }
<commit_msg>Add dismissed courses to student entity to persist feedback <commit_before>package at.ac.tuwien.inso.entity; import static java.util.Arrays.asList; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.OneToMany; @Entity public class Student extends UisUser { @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) private List<StudyPlanRegistration> studyplans = new ArrayList<>(); protected Student() { } public Student(String identificationNumber, String name, String email) { this(identificationNumber, name, email, null); } public Student(String identificationNumber, String name, String email, UserAccount account) { super(identificationNumber, name, email, account); } @Override protected void adjustRole(UserAccount account) { account.setRole(Role.STUDENT); } public List<StudyPlanRegistration> getStudyplans() { return studyplans; } public Student addStudyplans(StudyPlanRegistration... studyplans) { this.studyplans.addAll(asList(studyplans)); return this; } } <commit_after>package at.ac.tuwien.inso.entity; import static java.util.Arrays.asList; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.OneToMany; @Entity public class Student extends UisUser { @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) private List<StudyPlanRegistration> studyplans = new ArrayList<>(); @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) private List<Course> dismissedCourses = new ArrayList<>(); protected Student() { } public Student(String identificationNumber, String name, String email) { this(identificationNumber, name, email, null); } public Student(String identificationNumber, String name, String email, UserAccount account) { super(identificationNumber, name, email, account); } @Override protected void adjustRole(UserAccount account) { account.setRole(Role.STUDENT); } public List<StudyPlanRegistration> getStudyplans() { return studyplans; } public Student addStudyplans(StudyPlanRegistration... studyplans) { this.studyplans.addAll(asList(studyplans)); return this; } public List<Course> getDismissedCourses() { return dismissedCourses; } public void setDismissedCourses(List<Course> dismissedCourses) { this.dismissedCourses = dismissedCourses; } public Student addDismissedCourse(Course... dismissedCourse) { this.dismissedCourses.addAll(asList(dismissedCourse)); return this; } }
<commit_msg>Use real network interface for gRPC acceptance testing <commit_before>// +build acceptance package app_test import ( stdnet "net" "time" "github.com/DATA-DOG/godog" "github.com/deshboard/boilerplate-grpc-service/test" "github.com/goph/stdlib/net" "google.golang.org/grpc" ) func init() { test.RegisterFeaturePath("../features") test.RegisterFeatureContext(FeatureContext) } func FeatureContext(s *godog.Suite) { addr := net.ResolveVirtualAddr("pipe", "pipe") listener, dialer := net.PipeListen(addr) server := grpc.NewServer() client, _ := grpc.Dial("", grpc.WithInsecure(), grpc.WithDialer(func(s string, t time.Duration) (stdnet.Conn, error) { return dialer.Dial() })) // Add steps here func(s *godog.Suite, server *grpc.Server, client *grpc.ClientConn) {}(s, server, client) go server.Serve(listener) } <commit_after>// +build acceptance package app_test import ( "net" "github.com/DATA-DOG/godog" "github.com/deshboard/boilerplate-grpc-service/test" "google.golang.org/grpc" ) func init() { test.RegisterFeaturePath("../features") test.RegisterFeatureContext(FeatureContext) } func FeatureContext(s *godog.Suite) { lis, err := net.Listen("tcp", ":0") if err != nil { panic(err) } client, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure()) if err != nil { panic(err) } server := grpc.NewServer() // Add steps here func(s *godog.Suite, server *grpc.Server, client *grpc.ClientConn) {}(s, server, client) go server.Serve(lis) }
<commit_msg>Include virtual in all methods. <commit_before> class GameObject { public: void load(int pX, int pY, int pWidth, int pHeight, std::string pTextureId); void draw(SDL_Renderer *renderer); void update(); void clean() { std::cout << "clean game object"; } protected: std::string textureId; int currentFrame; int currentRow; int x; int y; int width; int height; }; #endif <commit_after> class GameObject { public: virtual void load(int pX, int pY, int pWidth, int pHeight, std::string pTextureId); virtual void draw(SDL_Renderer *renderer); virtual void update(); virtual void clean() {}; protected: std::string textureId; int currentFrame; int currentRow; int x; int y; int width; int height; }; #endif
<commit_msg>Add method to get complete Authorization Header for adorsys <commit_before>package de.fau.amos.virtualledger.server.auth; import org.keycloak.KeycloakPrincipal; import org.keycloak.KeycloakSecurityContext; import org.keycloak.representations.AccessToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; @Component public class KeycloakUtilizer { /** * extracts the email adress from the keycloak context. * returns null if not successful. */ public String getEmail() { return getAccessToken().getEmail(); } /** * extracts the first name from the keycloak context. * returns null if not successful. */ public String getFirstName() { return getAccessToken().getGivenName(); } /** * extracts the last name from the keycloak context. * returns null if not successful. */ public String getLastName() { return getAccessToken().getFamilyName(); } private AccessToken getAccessToken() { return getKeycloakSecurityContext().getToken(); } public String getTokenString() { return getKeycloakSecurityContext().getTokenString(); } private KeycloakSecurityContext getKeycloakSecurityContext() { try { //noinspection unchecked return ((KeycloakPrincipal<KeycloakSecurityContext>) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getKeycloakSecurityContext(); } catch (final Exception e) { throw new KeycloakException("Failure at getting data about the user by the identity token!"); } } } <commit_after>package de.fau.amos.virtualledger.server.auth; import org.keycloak.KeycloakPrincipal; import org.keycloak.KeycloakSecurityContext; import org.keycloak.representations.AccessToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; @Component public class KeycloakUtilizer { /** * extracts the email adress from the keycloak context. * returns null if not successful. */ public String getEmail() { return getAccessToken().getEmail(); } /** * extracts the first name from the keycloak context. * returns null if not successful. */ public String getFirstName() { return getAccessToken().getGivenName(); } /** * extracts the last name from the keycloak context. * returns null if not successful. */ public String getLastName() { return getAccessToken().getFamilyName(); } private AccessToken getAccessToken() { return getKeycloakSecurityContext().getToken(); } public String getAuthorizationHeader() { return "Bearer: " + getTokenString(); } public String getTokenString() { return getKeycloakSecurityContext().getTokenString(); } private KeycloakSecurityContext getKeycloakSecurityContext() { try { //noinspection unchecked return ((KeycloakPrincipal<KeycloakSecurityContext>) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getKeycloakSecurityContext(); } catch (final Exception e) { throw new KeycloakException("Failure at getting data about the user by the identity token!"); } } }
<commit_msg>Disable resizing the indexing screen <commit_before>package org.madhatters.mediaplayer; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception{ Parent root = FXMLLoader.load(getClass().getResource("/fxml/indexing_screen.fxml")); primaryStage.setTitle("Mad Hatter Media Player"); primaryStage.setScene(new Scene(root)); primaryStage.show(); } public static void main(String[] args) { launch(args); } } <commit_after>package org.madhatters.mediaplayer; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception{ Parent root = FXMLLoader.load(getClass().getResource("/fxml/indexing_screen.fxml")); primaryStage.setResizable(false); primaryStage.setTitle("Mad Hatter Media Player"); primaryStage.setScene(new Scene(root)); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
<commit_msg>Change img srcset check messages and checked layouts <commit_before>import { Context } from "../index"; import { Rule } from "../rule"; const SVG_URL_PATTERN = /^[^?]+\.svg(\?.*)?$/i export class AmpImgUsesSrcSet extends Rule { async run(context: Context) { const $ = context.$; const incorrectImages = $("amp-img") .filter((_, e) => { const src = $(e).attr("src"); const layout = $(e).attr("layout"); const srcset = $(e).attr("srcset"); return ( !SVG_URL_PATTERN.exec(src) && layout && layout !== 'fixed' && layout != 'fixed-height' && !srcset ) }); if (incorrectImages.length > 0) { return this.warn( "Not all responsive <amp-img> define a srcset. Using AMP Optimizer might help." ); } return this.pass(); } meta() { return { url: "https://amp.dev/documentation/guides-and-tutorials/optimize-and-measure/amp-optimizer-guide/explainer/?format=websites#image-optimization", title: "Responsive <amp-img> uses srcset", info: "", }; } } <commit_after>import { Context } from "../index"; import { Rule } from "../rule"; const SVG_URL_PATTERN = /^[^?]+\.svg(\?.*)?$/i const CHECKED_IMG_LAYOUTS = ["fill", "flex-item", "intrinsic", "responsive"]; export class AmpImgUsesSrcSet extends Rule { async run(context: Context) { const $ = context.$; const incorrectImages = $("amp-img") .filter((_, e) => { const src = $(e).attr("src"); const layout = $(e).attr("layout"); const srcset = $(e).attr("srcset"); return ( !SVG_URL_PATTERN.exec(src) && layout && CHECKED_IMG_LAYOUTS.includes(layout) && !srcset ) }); if (incorrectImages.length > 0) { return this.warn( "Not all <amp-img> with non-fixed layout define a srcset. Using AMP Optimizer might help." ); } return this.pass(); } meta() { return { url: "https://amp.dev/documentation/guides-and-tutorials/optimize-and-measure/amp-optimizer-guide/explainer/?format=websites#image-optimization", title: "<amp-img> with non-fixed layout uses srcset", info: "", }; } }
<commit_msg>Clarify values used in tests.<commit_before>from unittest import TestCase from chipy8 import Memory class TestMemory(TestCase): def setUp(self): self.memory = Memory() def test_write(self): 'Write a byte to memory then read it.' address = 0x200 self.memory.write_byte(0x200, 0x01) self.assertEqual(0x01, self.memory.read_byte(0x200)) def test_load(self): 'Load a stream of bytes to memory starting on an address.' address = 0x200 self.memory.load(0x200, [0x01, 0x02, 0x03]) self.assertEqual(0x01, self.memory.read_byte(address)) self.assertEqual(0x02, self.memory.read_byte(address + 1)) self.assertEqual(0x03, self.memory.read_byte(address + 2)) <commit_after>from unittest import TestCase from chipy8 import Memory class TestMemory(TestCase): def setUp(self): self.memory = Memory() def test_write(self): 'Write a byte to memory then read it.' address = 0x200 self.memory.write_byte(address, 0x01) self.assertEqual(0x01, self.memory.read_byte(address)) def test_load(self): 'Load a stream of bytes to memory starting on an address.' address = 0x200 self.memory.load(address, [0x01, 0x02, 0x03]) self.assertEqual(0x01, self.memory.read_byte(address)) self.assertEqual(0x02, self.memory.read_byte(address + 1)) self.assertEqual(0x03, self.memory.read_byte(address + 2))
<commit_msg>Improve proper using of property decorator and logic <commit_before>from buffer.models.update import Update PATHS = { 'GET_PENDING': 'profiles/%s/updates/pending.json', } class Updates(list): def __init__(self, api, profile_id): self.api = api self.profile_id = profile_id @property def pending(self): url = PATHS['GET_PENDING'] % self.profile_id response = self.api.get(url=url) for update in response['updates']: self.append(Update(api=self.api, raw_response=update)) return self <commit_after>from buffer.models.update import Update PATHS = { 'GET_PENDING': 'profiles/%s/updates/pending.json', 'GET_SENT': 'profiles/%s/updates/sent.json', } class Updates(list): def __init__(self, api, profile_id): self.api = api self.profile_id = profile_id self.__pending = [] self.__sent = [] @property def pending(self): pending_updates = [] url = paths['get_pending'] % self.profile_id response = self.api.get(url=url) for update in response['updates']: pending_updates.append(update(api=self.api, raw_response=update)) self.__pending = pending_updates return self.__pending @property def sent(self): url = PATHS['GET_SENT'] % self.profile_id response = self.api.get(url=url) for update in response['updates']: self.append(Update(api=self.api, raw_response=update)) return self
<commit_msg>Add completed field to review <commit_before>from django.db import models from django.contrib.auth.models import User class Review(models.Model): user = models.ForeignKey(User, default=None) title = models.CharField(max_length=128) description = models.TextField() date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) query = models.TextField() abstract_pool_size = models.IntegerField() document_pool_size = models.IntegerField() final_pool_size = models.IntegerField() class Paper(models.Model): review = models.ForeignKey(Review) title = models.CharField(max_length=128) authors = models.CharField(max_length=128) abstract = models.TextField() publish_date = models.DateField() url = models.URLField() notes = models.TextField() ABSTRACT_POOL = 'A' DOCUMENT_POOL = 'D' FINAL_POOL = 'F' REJECTED = 'R' POOLS = ((ABSTRACT_POOL, 'Abstract pool'), (DOCUMENT_POOL, 'Document pool'), (FINAL_POOL, 'Final pool'), (REJECTED, 'Rejected')) pool = models.CharField(max_length=1, choices=POOLS, default=ABSTRACT_POOL) <commit_after>from django.db import models from django.contrib.auth.models import User class Review(models.Model): user = models.ForeignKey(User, default=None) title = models.CharField(max_length=128) description = models.TextField() date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) completed = models.BooleanField(default=False) query = models.TextField() abstract_pool_size = models.IntegerField() document_pool_size = models.IntegerField() final_pool_size = models.IntegerField() class Paper(models.Model): review = models.ForeignKey(Review) title = models.CharField(max_length=128) authors = models.CharField(max_length=128) abstract = models.TextField() publish_date = models.DateField() url = models.URLField() notes = models.TextField() ABSTRACT_POOL = 'A' DOCUMENT_POOL = 'D' FINAL_POOL = 'F' REJECTED = 'R' POOLS = ((ABSTRACT_POOL, 'Abstract pool'), (DOCUMENT_POOL, 'Document pool'), (FINAL_POOL, 'Final pool'), (REJECTED, 'Rejected')) pool = models.CharField(max_length=1, choices=POOLS, default=ABSTRACT_POOL)
<commit_msg>Correct path to parent dir <commit_before>import os import sys sys.path.insert(0, os.path.dirname(__file__)) from gravity import __version__ # noqa: E402 project = 'Gravity' copyright = '2022, The Galaxy Project' author = 'The Galaxy Project' release = '__version__' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration extensions = [] templates_path = ['_templates'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # -- Options for HTML output ------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output html_theme = 'alabaster' html_static_path = ['_static'] <commit_after>import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) from gravity import __version__ # noqa: E402 project = 'Gravity' copyright = '2022, The Galaxy Project' author = 'The Galaxy Project' release = '__version__' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration extensions = [] templates_path = ['_templates'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # -- Options for HTML output ------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output html_theme = 'alabaster' html_static_path = ['_static']
<commit_msg>Remove exception specifier from RandomNumberGenerator::randomize <commit_before>/************************************************* * RandomNumberGenerator Header File * * (C) 1999-2008 Jack Lloyd * *************************************************/ #ifndef BOTAN_RANDOM_NUMBER_GENERATOR__ #define BOTAN_RANDOM_NUMBER_GENERATOR__ #include <botan/exceptn.h> namespace Botan { /************************************************* * Entropy Source * *************************************************/ class BOTAN_DLL EntropySource { public: virtual u32bit slow_poll(byte[], u32bit) = 0; virtual u32bit fast_poll(byte[], u32bit); virtual ~EntropySource() {} }; /************************************************* * Random Number Generator * *************************************************/ class BOTAN_DLL RandomNumberGenerator { public: virtual void randomize(byte[], u32bit) throw(PRNG_Unseeded) = 0; virtual bool is_seeded() const = 0; virtual void clear() throw() {}; byte next_byte(); void add_entropy(const byte[], u32bit); u32bit add_entropy(EntropySource&, bool = true); virtual ~RandomNumberGenerator() {} private: virtual void add_randomness(const byte[], u32bit) = 0; }; } #endif <commit_after>/************************************************* * RandomNumberGenerator Header File * * (C) 1999-2008 Jack Lloyd * *************************************************/ #ifndef BOTAN_RANDOM_NUMBER_GENERATOR__ #define BOTAN_RANDOM_NUMBER_GENERATOR__ #include <botan/exceptn.h> namespace Botan { /************************************************* * Entropy Source * *************************************************/ class BOTAN_DLL EntropySource { public: virtual u32bit slow_poll(byte[], u32bit) = 0; virtual u32bit fast_poll(byte[], u32bit); virtual ~EntropySource() {} }; /************************************************* * Random Number Generator * *************************************************/ class BOTAN_DLL RandomNumberGenerator { public: virtual void randomize(byte[], u32bit) = 0; virtual bool is_seeded() const = 0; virtual void clear() throw() {}; byte next_byte(); void add_entropy(const byte[], u32bit); u32bit add_entropy(EntropySource&, bool = true); virtual ~RandomNumberGenerator() {} private: virtual void add_randomness(const byte[], u32bit) = 0; }; } #endif
<commit_msg>Add pombola.spinner to OPTIONAL_APPS in the new settings modules <commit_before>COUNTRY_APP = 'nigeria' OPTIONAL_APPS = [] TWITTER_USERNAME = 'NGShineyoureye' TWITTER_WIDGET_ID = '354909651910918144' BLOG_RSS_FEED = 'http://eienigeria.org/rss.xml' MAP_BOUNDING_BOX_NORTH = 14.1 MAP_BOUNDING_BOX_EAST = 14.7 MAP_BOUNDING_BOX_SOUTH = 4 MAP_BOUNDING_BOX_WEST = 2.5 MAPIT_COUNTRY = 'NG' <commit_after>COUNTRY_APP = 'nigeria' OPTIONAL_APPS = ['pombola.spinner'] TWITTER_USERNAME = 'NGShineyoureye' TWITTER_WIDGET_ID = '354909651910918144' BLOG_RSS_FEED = 'http://eienigeria.org/rss.xml' MAP_BOUNDING_BOX_NORTH = 14.1 MAP_BOUNDING_BOX_EAST = 14.7 MAP_BOUNDING_BOX_SOUTH = 4 MAP_BOUNDING_BOX_WEST = 2.5 MAPIT_COUNTRY = 'NG'
<commit_msg>Put terminal handlers under base_url <commit_before>import os from terminado import NamedTermManager from .handlers import TerminalHandler, NewTerminalHandler, TermSocket from . import api_handlers def initialize(webapp): shell = os.environ.get('SHELL', 'sh') webapp.terminal_manager = NamedTermManager(shell_command=[shell]) handlers = [ (r"/terminals/new", NewTerminalHandler), (r"/terminals/(\w+)", TerminalHandler), (r"/terminals/websocket/(\w+)", TermSocket, {'term_manager': webapp.terminal_manager}), (r"/api/terminals", api_handlers.TerminalRootHandler), (r"/api/terminals/(\w+)", api_handlers.TerminalHandler), ] webapp.add_handlers(".*$", handlers)<commit_after>import os from terminado import NamedTermManager from IPython.html.utils import url_path_join as ujoin from .handlers import TerminalHandler, NewTerminalHandler, TermSocket from . import api_handlers def initialize(webapp): shell = os.environ.get('SHELL', 'sh') webapp.terminal_manager = NamedTermManager(shell_command=[shell]) base_url = webapp.settings['base_url'] handlers = [ (ujoin(base_url, "/terminals/new"), NewTerminalHandler), (ujoin(base_url, r"/terminals/(\w+)"), TerminalHandler), (ujoin(base_url, r"/terminals/websocket/(\w+)"), TermSocket, {'term_manager': webapp.terminal_manager}), (ujoin(base_url, r"/api/terminals"), api_handlers.TerminalRootHandler), (ujoin(base_url, r"/api/terminals/(\w+)"), api_handlers.TerminalHandler), ] webapp.add_handlers(".*$", handlers)
<commit_msg>Apply Id if SavedEncounter is missing one <commit_before>import { CombatantState } from "../../common/CombatantState"; import { EncounterState } from "../../common/EncounterState"; import { probablyUniqueString } from "../../common/Toolbox"; function updateLegacySavedCreature(savedCreature: any) { if (!savedCreature.StatBlock) { savedCreature.StatBlock = savedCreature["Statblock"]; } if (!savedCreature.Id) { savedCreature.Id = probablyUniqueString(); } if (savedCreature.MaxHP) { savedCreature.StatBlock.HP.Value = savedCreature.MaxHP; } } export function UpdateLegacySavedEncounter( savedEncounter: any ): EncounterState<CombatantState> { savedEncounter.Combatants = savedEncounter.Combatants || savedEncounter.Creatures; savedEncounter.ActiveCombatantId = savedEncounter.ActiveCombatantId || savedEncounter.ActiveCreatureId; savedEncounter.Path = savedEncounter.Path || ""; savedEncounter.Combatants.forEach(updateLegacySavedCreature); const legacyCombatantIndex = savedEncounter.ActiveCreatureIndex; if (legacyCombatantIndex !== undefined && legacyCombatantIndex != -1) { savedEncounter.ActiveCombatantId = savedEncounter.Combatants[legacyCombatantIndex].Id; } return savedEncounter; } <commit_after>import { CombatantState } from "../../common/CombatantState"; import { EncounterState } from "../../common/EncounterState"; import { probablyUniqueString } from "../../common/Toolbox"; import { AccountClient } from "../Account/AccountClient"; function updateLegacySavedCreature(savedCreature: any) { if (!savedCreature.StatBlock) { savedCreature.StatBlock = savedCreature["Statblock"]; } if (!savedCreature.Id) { savedCreature.Id = probablyUniqueString(); } if (savedCreature.MaxHP) { savedCreature.StatBlock.HP.Value = savedCreature.MaxHP; } } export function UpdateLegacySavedEncounter( savedEncounter: any ): EncounterState<CombatantState> { savedEncounter.Combatants = savedEncounter.Combatants || savedEncounter.Creatures; savedEncounter.ActiveCombatantId = savedEncounter.ActiveCombatantId || savedEncounter.ActiveCreatureId; savedEncounter.Path = savedEncounter.Path || ""; savedEncounter.Id = savedEncounter.Id || AccountClient.MakeId(savedEncounter.Name || probablyUniqueString()); savedEncounter.Combatants.forEach(updateLegacySavedCreature); const legacyCombatantIndex = savedEncounter.ActiveCreatureIndex; if (legacyCombatantIndex !== undefined && legacyCombatantIndex != -1) { savedEncounter.ActiveCombatantId = savedEncounter.Combatants[legacyCombatantIndex].Id; } return savedEncounter; }
<commit_msg>Add new test case for newMultiplexer <commit_before>module BroadcastSpec (spec) where import Protolude import Control.Concurrent.STM.TChan import Control.Concurrent.STM.TQueue import Test.Hspec import PostgRESTWS.Broadcast spec :: Spec spec = describe "Broadcast" $ it "relays a single message from producer to 1 listener on 1 test channel" $ do output <- newTQueueIO :: IO (TQueue Message) multi <- liftIO $ newMultiplexer (\_ msgs-> atomically $ writeTQueue msgs (Message "test" "payload")) (\_ -> return ()) void $ onMessage multi "test" (\ch -> atomically $ do message <- readTChan ch writeTQueue output message) liftIO $ relayMessages multi outMsg <- atomically $ readTQueue output outMsg `shouldBe` Message "test" "payload" <commit_after>module BroadcastSpec (spec) where import Protolude import Control.Concurrent.STM.TChan import Control.Concurrent.STM.TQueue import Test.Hspec import PostgRESTWS.Broadcast spec :: Spec spec = do describe "newMultiplexer" $ it "opens a separate thread for a producer function" $ do output <- newTQueueIO :: IO (TQueue ThreadId) void $ liftIO $ newMultiplexer (\_ _-> do tid <- myThreadId atomically $ writeTQueue output tid ) (\_ -> return ()) outMsg <- atomically $ readTQueue output myThreadId `shouldNotReturn` outMsg describe "relayMessages" $ it "relays a single message from producer to 1 listener on 1 test channel" $ do output <- newTQueueIO :: IO (TQueue Message) multi <- liftIO $ newMultiplexer (\_ msgs-> atomically $ writeTQueue msgs (Message "test" "payload")) (\_ -> return ()) void $ onMessage multi "test" (\ch -> atomically $ do message <- readTChan ch writeTQueue output message) liftIO $ relayMessages multi outMsg <- atomically $ readTQueue output outMsg `shouldBe` Message "test" "payload"
<commit_msg>Make Type an instance of Show <commit_before>module Statsd ( StatsdClient, client, increment, decrement, count, gauge, timing, histogram, ) where type Stat = String data StatsdClient = StatsdClient { host :: String , port :: Int , namespace :: Stat , key :: Maybe String } client :: String -> Int -> Stat -> Maybe String -> StatsdClient client = StatsdClient increment :: StatsdClient -> Stat -> IO () increment client stat = count client stat 1 decrement :: StatsdClient -> Stat -> IO () decrement client stat = count client stat (-1) count :: StatsdClient -> Stat -> Int -> IO () count client stat value = send client stat value Count gauge :: StatsdClient -> Stat -> Int -> IO () gauge client stat value = send client stat value Guage -- duration in milliseconds timing :: StatsdClient -> Stat -> Int -> IO () timing client stat value = send client stat value Timing histogram :: StatsdClient -> Stat -> Int -> IO () histogram client stat value = send client stat value Histogram send :: StatsdClient -> Stat -> Int -> Type -> IO () send client stat value stat_type = undefined data Type = Count | Guage | Timing | Histogram show :: Type -> String show Count = "c" show Guage = "g" show Timing = "ms" show Histogram = "h"<commit_after>module Statsd ( StatsdClient, client, increment, decrement, count, gauge, timing, histogram, ) where type Stat = String data StatsdClient = StatsdClient { host :: String , port :: Int , namespace :: Stat , key :: Maybe String } client :: String -> Int -> Stat -> Maybe String -> StatsdClient client = StatsdClient increment :: StatsdClient -> Stat -> IO () increment client stat = count client stat 1 decrement :: StatsdClient -> Stat -> IO () decrement client stat = count client stat (-1) count :: StatsdClient -> Stat -> Int -> IO () count client stat value = send client stat value Count gauge :: StatsdClient -> Stat -> Int -> IO () gauge client stat value = send client stat value Guage -- duration in milliseconds timing :: StatsdClient -> Stat -> Int -> IO () timing client stat value = send client stat value Timing histogram :: StatsdClient -> Stat -> Int -> IO () histogram client stat value = send client stat value Histogram send :: StatsdClient -> Stat -> Int -> Type -> IO () send client stat value stat_type = undefined data Type = Count | Guage | Timing | Histogram instance Show Type where show Count = "c" show Guage = "g" show Timing = "ms" show Histogram = "h"
<commit_msg>Add other DaoImpl beans in rest-dispatcher-servlet.xml 4 <commit_before>package com.devcru.journowatch.api.services; import org.springframework.beans.factory.annotation.Autowired; import com.devcru.journowatch.api.daoimpl.VenueDaoImpl; import com.devcru.journowatch.api.objects.Venue; public class VenueService { @Autowired VenueDaoImpl vd; public boolean createVenue(Venue venue) { boolean isSuccess = vd.createVenue(venue); return isSuccess; } public Venue getVenue(Venue venue) { venue = vd.getVenue(venue); return venue; } public boolean updateVenue(Venue venue) { boolean isSuccess = vd.updateVenue(venue); return isSuccess; } public boolean deleteVenue(Venue venue) { boolean isSuccess = vd.deleteVenue(venue); return isSuccess; } } <commit_after>package com.devcru.journowatch.api.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.devcru.journowatch.api.daoimpl.VenueDaoImpl; import com.devcru.journowatch.api.objects.Venue; @Service public class VenueService { @Autowired private VenueDaoImpl vd; public boolean createVenue(Venue venue) { boolean isSuccess = vd.createVenue(venue); return isSuccess; } public Venue getVenue(Venue venue) { venue = vd.getVenue(venue); return venue; } public boolean updateVenue(Venue venue) { boolean isSuccess = vd.updateVenue(venue); return isSuccess; } public boolean deleteVenue(Venue venue) { boolean isSuccess = vd.deleteVenue(venue); return isSuccess; } }
<commit_msg>Remove absent extractor from entry points <commit_before>import sys from setuptools import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): # XXX sometimes TestCommand is not a newstyle class TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # XXX import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.test_args) sys.exit(errno) try: with open('README.rst') as readme: README = readme.read() except IOError: README = '' setup( name='rdio_dl', version='0.0.1dev', packages=['rdio_dl'], install_requires=['requests', 'youtube_dl'], dependency_links=[ 'git+https://github.com/ravishi/youtube-dl.git@f77da1fae6#egg=youtube_dl', ], author='Dirley Rodrigues', author_email='dirleyrls@gmail.com', long_description=README, entry_points={ 'youtube_dl.extractors': [ 'rdio = rdio_dl.extractor:RdioIE', 'rdio_playlist = rdio_dl.extractor:RdioPlaylistIE', ], }, test_suite='tests', tests_require=['pytest'], cmdclass={'test': PyTest}, ) <commit_after>import sys from setuptools import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): # XXX sometimes TestCommand is not a newstyle class TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # XXX import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.test_args) sys.exit(errno) try: with open('README.rst') as readme: README = readme.read() except IOError: README = '' setup( name='rdio_dl', version='0.0.1dev', packages=['rdio_dl'], install_requires=['requests', 'youtube_dl'], dependency_links=[ 'git+https://github.com/ravishi/youtube-dl.git@f77da1fae6#egg=youtube_dl', ], author='Dirley Rodrigues', author_email='dirleyrls@gmail.com', long_description=README, entry_points={ 'youtube_dl.extractors': [ 'rdio = rdio_dl.extractor:RdioIE', ], }, test_suite='tests', tests_require=['pytest'], cmdclass={'test': PyTest}, )
<commit_msg>Add comment about browsers not liking application/json. <commit_before>from fileupload.models import Picture from django.views.generic import CreateView, DeleteView from django.http import HttpResponse from django.utils import simplejson from django.core.urlresolvers import reverse from django.conf import settings class PictureCreateView(CreateView): model = Picture def form_valid(self, form): self.object = form.save() f = self.request.FILES.get('file') data = [{'name': f.name, 'url': settings.MEDIA_URL + "pictures/" + f.name, 'thumbnail_url': settings.MEDIA_URL + "pictures/" + f.name, 'delete_url': reverse('upload-delete', args=[f.name]), 'delete_type': "DELETE"}] return JSONResponse(data) class PictureDeleteView(DeleteView): model = Picture def delete(self, request, *args, **kwargs): self.object = self.get_object() self.object.delete() return JSONResponse(True) class JSONResponse(HttpResponse): """ JSON response class """ def __init__(self,obj='',json_opts={},mimetype="application/json",*args,**kwargs): content = simplejson.dumps(obj,**json_opts) super(JSONResponse,self).__init__(content,mimetype,*args,**kwargs) <commit_after>from fileupload.models import Picture from django.views.generic import CreateView, DeleteView from django.http import HttpResponse from django.utils import simplejson from django.core.urlresolvers import reverse from django.conf import settings class PictureCreateView(CreateView): model = Picture def form_valid(self, form): self.object = form.save() f = self.request.FILES.get('file') data = [{'name': f.name, 'url': settings.MEDIA_URL + "pictures/" + f.name, 'thumbnail_url': settings.MEDIA_URL + "pictures/" + f.name, 'delete_url': reverse('upload-delete', args=[f.name]), 'delete_type': "DELETE"}] return JSONResponse(data) class PictureDeleteView(DeleteView): model = Picture def delete(self, request, *args, **kwargs): self.object = self.get_object() self.object.delete() return JSONResponse(True) class JSONResponse(HttpResponse): """JSON response class. This does not help browsers not liking application/json.""" def __init__(self,obj='',json_opts={},mimetype="application/json",*args,**kwargs): content = simplejson.dumps(obj,**json_opts) super(JSONResponse,self).__init__(content,mimetype,*args,**kwargs)
<commit_msg>Fix issue with duplicated call <commit_before>import sys import os import shutil import composer import configuration import downloader def run(): project_dir = os.getcwd()+'/' execution_dir = os.path.split(os.path.dirname(os.path.realpath(__file__)))[0]+'/' if len(sys.argv) == 2: project_dir = sys.argv[1] os.chdir(execution_dir) print '>>> Execution dir: '+execution_dir print '>>> Project dir: '+project_dir build_dir = project_dir+'build/' configuration.load(project_dir) configuration.add('project-dir', project_dir) configuration.add('build-dir', build_dir) composer.initialization() downloader.initialization() def update(): php_bin = 'php' if len(sys.argv) == 2: php_bin = sys.argv[1] print '>>> PHP version is: '+php_bin configuration.add('php', php_bin) composer.initialization() composer.update() downloader.update() def prepare_dir(path): if os.path.isdir(path): shutil.rmtree(path) os.makedirs(path) <commit_after>import sys import os import shutil import composer import configuration import downloader def run(): try: project_dir = configuration.get_value('project-dir') except: project_dir = os.getcwd()+'/' execution_dir = os.path.split(os.path.dirname(os.path.realpath(__file__)))[0]+'/' if len(sys.argv) == 2: project_dir = sys.argv[1] os.chdir(execution_dir) print '>>> Execution dir: '+execution_dir print '>>> Project dir: '+project_dir build_dir = project_dir+'build/' configuration.load(project_dir) configuration.add('project-dir', project_dir) configuration.add('build-dir', build_dir) composer.initialization() downloader.initialization() def update(): php_bin = 'php' if len(sys.argv) == 2: php_bin = sys.argv[1] print '>>> PHP version is: '+php_bin configuration.add('php', php_bin) composer.initialization() composer.update() downloader.update() def prepare_dir(path): if os.path.isdir(path): shutil.rmtree(path) os.makedirs(path)
<commit_msg>Add configuration for pagaing related properties. <commit_before>package uk.ac.ebi.quickgo.ontology; import uk.ac.ebi.quickgo.ontology.coterms.CoTermConfig; import uk.ac.ebi.quickgo.ontology.service.ServiceConfig; import uk.ac.ebi.quickgo.rest.controller.SwaggerConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Import; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; /** * Runnable class to start an embedded server to host the defined RESTful components. * * Created 16/11/15 * @author Edd */ @SpringBootApplication(exclude = {SolrRepositoriesAutoConfiguration.class}) @ComponentScan({ "uk.ac.ebi.quickgo.ontology.controller", "uk.ac.ebi.quickgo.rest"}) @Import({ServiceConfig.class, SwaggerConfig.class, CoTermConfig.class}) public class OntologyREST { /** * Ensures that placeholders are replaced with property values */ @Bean static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } public static void main(String[] args) { SpringApplication.run(OntologyREST.class, args); } } <commit_after>package uk.ac.ebi.quickgo.ontology; import uk.ac.ebi.quickgo.ontology.coterms.CoTermConfig; import uk.ac.ebi.quickgo.ontology.service.ServiceConfig; import uk.ac.ebi.quickgo.rest.controller.SwaggerConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Import; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; /** * Runnable class to start an embedded server to host the defined RESTful components. * * Created 16/11/15 * @author Edd */ @SpringBootApplication(exclude = {SolrRepositoriesAutoConfiguration.class}) @ComponentScan({ "uk.ac.ebi.quickgo.ontology.controller", "uk.ac.ebi.quickgo.rest"}) @Import({ServiceConfig.class, SwaggerConfig.class, CoTermConfig.class, OntologyRestConfig.class}) public class OntologyREST { /** * Ensures that placeholders are replaced with property values */ @Bean static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } public static void main(String[] args) { SpringApplication.run(OntologyREST.class, args); } }
<commit_msg>Add new typedef for values sent to setsockopt(). <commit_before> // Under Windows, define stuff that we need #ifdef _MSC_VER #include <winsock.h> #define MAXHOSTNAMELEN 64 #define EWOULDBLOCK WSAEWOULDBLOCK #define EINPROGRESS WSAEINPROGRESS #define MSG_WAITALL 0 typedef SOCKET Socket; typedef int socklen_t; typedef char SocketOptionFlag; #else #include <unistd.h> #include <string.h> #include <netdb.h> #include <fcntl.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/param.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/tcp.h> typedef int Socket; typedef int SocketOptionFlag; #endif void initNetwork(); void cleanupNetwork(); Socket openSocket(int domain, int type, int protocol); void closeSocket(Socket socket); void setBlockingFlag(Socket socket, bool block); bool getBlockingFlag(Socket socket); #endif <commit_after> // Under Windows, define stuff that we need #ifdef _MSC_VER #include <winsock.h> #define MAXHOSTNAMELEN 64 #define EWOULDBLOCK WSAEWOULDBLOCK #define EINPROGRESS WSAEINPROGRESS #define MSG_WAITALL 0 typedef SOCKET Socket; typedef int socklen_t; typedef char SocketOptionFlag; typedef int SocketOptionValue; #else #include <unistd.h> #include <string.h> #include <netdb.h> #include <fcntl.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/param.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/tcp.h> typedef int Socket; typedef int SocketOptionFlag; typedef int SocketOptionValue; #endif void initNetwork(); void cleanupNetwork(); Socket openSocket(int domain, int type, int protocol); void closeSocket(Socket socket); void setBlockingFlag(Socket socket, bool block); bool getBlockingFlag(Socket socket); #endif
<commit_msg>Change visibility of storage interruption manager <commit_before>package com.orientechnologies.orient.core.storage.impl.local; import com.orientechnologies.common.concur.lock.OInterruptedException; import com.orientechnologies.common.log.OLogManager; public class OStorageInterruptionManager { private int depth = 0; private boolean interrupted = false; protected void interrupt(Thread thread) { synchronized (this) { if (depth <= 0) { interrupted = true; } else if (thread != null) { thread.interrupt(); } } } protected void enterCriticalPath() { synchronized (this) { if (Thread.currentThread().isInterrupted() || (interrupted && depth == 0)) { final Thread thread = Thread.currentThread(); // thread.interrupt(); OLogManager.instance().warnNoDb(this, "Execution of thread '%s' is interrupted", thread); throw new OInterruptedException("Command interrupted"); } this.depth++; } } protected void exitCriticalPath() { synchronized (this) { this.depth--; if (interrupted && depth == 0) { final Thread thread = Thread.currentThread(); // thread.interrupt(); OLogManager.instance().warnNoDb(this, "Execution of thread '%s' is interrupted", thread); throw new OInterruptedException("Command interrupted"); } } } } <commit_after>package com.orientechnologies.orient.core.storage.impl.local; import com.orientechnologies.common.concur.lock.OInterruptedException; import com.orientechnologies.common.log.OLogManager; public class OStorageInterruptionManager { private int depth = 0; private boolean interrupted = false; protected void interrupt(Thread thread) { synchronized (this) { if (depth <= 0) { interrupted = true; } else if (thread != null) { thread.interrupt(); } } } public void enterCriticalPath() { synchronized (this) { if (Thread.currentThread().isInterrupted() || (interrupted && depth == 0)) { final Thread thread = Thread.currentThread(); // thread.interrupt(); OLogManager.instance().warnNoDb(this, "Execution of thread '%s' is interrupted", thread); throw new OInterruptedException("Command interrupted"); } this.depth++; } } public void exitCriticalPath() { synchronized (this) { this.depth--; if (interrupted && depth == 0) { final Thread thread = Thread.currentThread(); // thread.interrupt(); OLogManager.instance().warnNoDb(this, "Execution of thread '%s' is interrupted", thread); throw new OInterruptedException("Command interrupted"); } } } }
<commit_msg>Set celery task results to expire in 1h <commit_before> """Celery configuration values.""" BROKER_URL = "redis://localhost" BROKER_POOL_LIMIT = 20 BROKER_TRANSPORT_OPTIONS = { "visibility_timeout": 60*60*6, "fanout_prefix": True, "fanout_patterns": True } # Use custom json encoder. CELERY_ACCEPT_CONTENT = ["kjson"] CELERY_RESULT_SERIALIZER = "kjson" CELERY_TASK_SERIALIZER = "kjson" CELERY_TIMEZONE = "UTC" CELERY_ENABLE_UTC = True CELERY_IGNORE_RESULT = True CELERY_DISABLE_RATE_LIMITS = True # Use a different DB than the redis default one. CELERY_RESULT_BACKEND = "redis://localhost/1" <commit_after> """Celery configuration values.""" BROKER_URL = "redis://localhost" BROKER_POOL_LIMIT = 20 BROKER_TRANSPORT_OPTIONS = { "visibility_timeout": 60*60*6, "fanout_prefix": True, "fanout_patterns": True } # Use custom json encoder. CELERY_ACCEPT_CONTENT = ["kjson"] CELERY_RESULT_SERIALIZER = "kjson" CELERY_TASK_SERIALIZER = "kjson" CELERY_TASK_RESULT_EXPIRES = 3600 CELERY_TIMEZONE = "UTC" CELERY_ENABLE_UTC = True CELERY_IGNORE_RESULT = True CELERY_DISABLE_RATE_LIMITS = True # Use a different DB than the redis default one. CELERY_RESULT_BACKEND = "redis://localhost/1"
<commit_msg>Solve problem 701 (my 600th problem :) <commit_before>package leetcode; /** * https://leetcode.com/problems/insert-into-a-binary-search-tree/ */ public class Problem701 { public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public TreeNode insertIntoBST(TreeNode root, int val) { // TODO return null; } public static void main(String[] args) { Problem701 prob = new Problem701(); } } <commit_after>package leetcode; /** * https://leetcode.com/problems/insert-into-a-binary-search-tree/ */ public class Problem701 { public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public TreeNode insertIntoBST(TreeNode root, int val) { if (root == null) { return new TreeNode(val); } if (root.val > val) { root.left = insertIntoBST(root.left, val); } else { root.right = insertIntoBST(root.right, val); } return root; } }
<commit_msg>FIX - write concerns not added to collection<commit_before>package com.mongodb.memphis.config; import org.bson.BsonDocument; import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class Collection { private String name; private WriteConcern writeConcern; private ReadConcern readConcern; private ReadPreference readPreference; public final String getName() { return name; } public final WriteConcern getWriteConcern() { return writeConcern; } public final ReadConcern getReadConcern() { return readConcern; } public final ReadPreference getReadPreference() { return readPreference; } public MongoCollection<BsonDocument> getMongoCollection(MongoDatabase mongoDatabase) { MongoCollection<BsonDocument> collection = mongoDatabase.getCollection(name, BsonDocument.class); if (writeConcern != null) { collection.withWriteConcern(writeConcern); } if (readConcern != null) { collection.withReadConcern(readConcern); } if (readPreference != null) { collection.withReadPreference(readPreference); } return collection; } } <commit_after>package com.mongodb.memphis.config; import org.bson.BsonDocument; import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class Collection { private String name; private WriteConcern writeConcern; private ReadConcern readConcern; private ReadPreference readPreference; public final String getName() { return name; } public final WriteConcern getWriteConcern() { return writeConcern; } public final ReadConcern getReadConcern() { return readConcern; } public final ReadPreference getReadPreference() { return readPreference; } public MongoCollection<BsonDocument> getMongoCollection(MongoDatabase mongoDatabase) { MongoCollection<BsonDocument> collection = mongoDatabase.getCollection(name, BsonDocument.class); if (writeConcern != null) { collection = collection.withWriteConcern(writeConcern); } if (readConcern != null) { collection = collection.withReadConcern(readConcern); } if (readPreference != null) { collection = collection.withReadPreference(readPreference); } return collection; } }
<commit_msg>Support setting alpha in colors <commit_before> """Provides convenience methods for styling text.""" BOLD = 1 UNDERLINE = 2 ITALIC = 4 def color_for_rgb_float(red, green, blue): if any(map(lambda x: x < 0 or x > 1, (red, green, blue))): raise ValueError("Values must be in the range 0..1 (inclusive)") red, green, blue = map(lambda c: int(0xFF * c), (red, green, blue)) return (0xFF << 24) | (red << 16) | (green << 8) | blue <commit_after> """Provides convenience methods for styling text.""" BOLD = 1 UNDERLINE = 2 ITALIC = 4 def color_for_rgba_float(red, green, blue, alpha=1): if any(map(lambda x: x < 0 or x > 1, (red, green, blue, alpha))): raise ValueError("Values must be in the range 0..1 (inclusive)") red, green, blue, alpha = map(lambda c: int(0xFF * c), (red, green, blue, alpha)) return (alpha << 24) | (red << 16) | (green << 8) | blue
<commit_msg>Check if you are using python 3.3+ <commit_before> from taiga_ncurses import __name__, __description__, __version__ from setuptools import setup, find_packages REQUIREMENTS = [ "requests==2.5.0", "urwid>=1.3.0", "x256==0.0.3" ] NAME = __name__ DESCRIPTION = __description__ VERSION = "{0}.{1}".format(*__version__) setup(name=NAME, version=VERSION, description=DESCRIPTION, packages=find_packages(), entry_points={ "console_scripts": ["taiga-ncurses = taiga_ncurses.cli:main"] }, classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Console :: Curses", "Intended Audience :: End Users/Desktop", "Operating System :: POSIX :: Linux", "Operating System :: MacOS", "Programming Language :: Python :: 3.3", ], install_requires=REQUIREMENTS,) <commit_after> from __future__ import print_function import sys if sys.version_info[0] < 3 or sys.version_info[1] < 3: print("Sorry, taiga-ncurses needs python >= 3.3", file=sys.stderr) sys.exit(-1) from taiga_ncurses import __name__, __description__, __version__ from setuptools import setup, find_packages REQUIREMENTS = [ "requests==2.5.0", "urwid>=1.3.0", "x256==0.0.3" ] NAME = __name__ DESCRIPTION = __description__ VERSION = "{0}.{1}".format(*__version__) setup(name=NAME, version=VERSION, description=DESCRIPTION, packages=find_packages(), entry_points={ "console_scripts": ["taiga-ncurses = taiga_ncurses.cli:main"] }, classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Console :: Curses", "Intended Audience :: End Users/Desktop", "Operating System :: POSIX :: Linux", "Operating System :: MacOS", "Programming Language :: Python :: 3.3", ], install_requires=REQUIREMENTS,)
<commit_msg>Change modelId to type Integer <commit_before>package xyz.igorgee.imagecreator3d; import java.io.File; public class Model { String name; File location; String modelID; public Model(String name, File location) { this.name = name; this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } public File getLocation() { return location; } public void setLocation(File location) { this.location = location; } public String getModelID() { return modelID; } public void setModelID(String modelID) { this.modelID = modelID; } } <commit_after>package xyz.igorgee.imagecreator3d; import java.io.File; public class Model { String name; File location; Integer modelID; public Model(String name, File location) { this.name = name; this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } public File getLocation() { return location; } public void setLocation(File location) { this.location = location; } public Integer getModelID() { return modelID; } public void setModelID(Integer modelID) { this.modelID = modelID; } }
<commit_msg>Fix enemy factory since world is now using vector2 <commit_before>package revert.Entities; import java.awt.Point; import revert.AI.EnemyAi; import revert.MainScene.World; public class EnemyFactory { Point[] spawnPoints; World world; public EnemyFactory(World world, Point... spawns) { this.spawnPoints = spawns; this.world = world; } /** * Create a data set array * @param size * @return */ public int[][] createWave(int size) { int[][] wave = new int[size][]; for (int i = 0; i < size; i++) { Point loc = spawnPoints[(int)(Math.random()*spawnPoints.length)]; int[] n = {loc.x, loc.y, (int)(Math.random()*3)}; wave[i] = n; } return wave; } public Enemy generateEnemy(int type) { Enemy e = new Enemy(world, world.getPlayer()); EnemyAi ai = null; if (type == 0) { //ai = new PassiveAi(); } else { System.out.println("No enemy type corresponds to value: " + type + ". Instantiating basic enemy"); } e.setAI(ai); return e; } } <commit_after>package revert.Entities; import java.awt.Point; import com.kgp.util.Vector2; import revert.AI.EnemyAi; import revert.MainScene.World; public class EnemyFactory { Vector2[] spawnPoints; World world; public EnemyFactory(World world, Vector2... spawns) { this.spawnPoints = spawns; this.world = world; } /** * Create a data set array * @param size * @return */ public int[][] createWave(int size) { int[][] wave = new int[size][]; for (int i = 0; i < size; i++) { Vector2 loc = spawnPoints[(int)(Math.random()*spawnPoints.length)]; int[] n = {(int)loc.x, (int)loc.y, (int)(Math.random()*3)}; wave[i] = n; } return wave; } public Enemy generateEnemy(int type) { Enemy e = new Enemy(world, world.getPlayer()); EnemyAi ai = null; if (type == 0) { //ai = new PassiveAi(); } else { System.out.println("No enemy type corresponds to value: " + type + ". Instantiating basic enemy"); } e.setAI(ai); return e; } }
<commit_msg>Use correct directory for file section AT. <commit_before>// Copyright (C) 2003-2009 by Object Mentor, Inc. All rights reserved. // Released under the terms of the CPL Common Public License version 1.0. package fitnesse.fixtures; import util.FileUtil; import java.io.File; public class FileSection { private static File fileSection; public FileSection(String type) throws Exception { if ("setup".equals(type.toLowerCase())) { new File(FitnesseFixtureContext.baseDir).mkdir(); File dir = new File(FitnesseFixtureContext.baseDir); dir.mkdir(); fileSection = new File(dir, "files"); fileSection.mkdir(); } else { FileUtil.deleteFileSystemDirectory(FitnesseFixtureContext.baseDir); fileSection = null; } } public static File getFileSection() { return fileSection; } } <commit_after>// Copyright (C) 2003-2009 by Object Mentor, Inc. All rights reserved. // Released under the terms of the CPL Common Public License version 1.0. package fitnesse.fixtures; import util.FileUtil; import java.io.File; public class FileSection { private static File fileSection; public FileSection(String type) throws Exception { if ("setup".equals(type.toLowerCase())) { File dir = new File(FitnesseFixtureContext.context.getRootPagePath()); dir.mkdir(); fileSection = new File(dir, "files"); fileSection.mkdir(); } else { FileUtil.deleteFileSystemDirectory(FitnesseFixtureContext.context.getRootPagePath()); fileSection = null; } } public static File getFileSection() { return fileSection; } }
<commit_msg>arch/x86: Print symbol names in backtrace This transforms: #0 [0x1018C7] #1 [0x101636] #2 [0x100231] into: #0 [0x1018C7] panic #1 [0x101636] k_main #2 [0x100231] start <commit_before> /* * Walk up the stack and print the locations of each stack frame base. */ void bt(void) { u32 *ebp, *eip; unsigned int sf = 0; /* Start form the current stack base */ asm volatile("mov %%ebp, %0" : "=r" (ebp)); /* Continue until you reach a zeroed stack base pointer. The initial ebp * value is zeroed at boot, but note that this could be corrupted in the * case of serious memory corruption. To protect against this, we keep * track of the frame number and break if it exceeds a reasonable * maximum value. */ while (ebp) { eip = ebp + 1; printf("#%d [0x%x]\n", sf, *eip); ebp = (u32*)*ebp; sf++; /* break if exceeded maximum */ if (sf > MAX_STACK_FRAME) break; } } <commit_after> /* * Walk up the stack and print the locations of each stack frame base. */ void bt(void) { u32 *ebp, *eip; unsigned int sf = 0; /* Start form the current stack base */ asm volatile("mov %%ebp, %0" : "=r" (ebp)); /* Continue until you reach a zeroed stack base pointer. The initial ebp * value is zeroed at boot, but note that this could be corrupted in the * case of serious memory corruption. To protect against this, we keep * track of the frame number and break if it exceeds a reasonable * maximum value. */ while (ebp) { eip = ebp + 1; printf("#%d [0x%x] %s\n", sf, *eip, symbol_from_elf(&kelf, *eip)); ebp = (u32*)*ebp; sf++; /* break if exceeded maximum */ if (sf > MAX_STACK_FRAME) break; } }
<commit_msg>Add newline and add missing enhance annotation. <commit_before>package net.bytebuddy.matcher; import net.bytebuddy.description.type.TypeDefinition; /** * Matches an enumeration type. * * @param <T> The type of the matched entity. */ public class ArrayTypeMatcher<T extends TypeDefinition> extends ElementMatcher.Junction.AbstractBase<T> { /** * {@inheritDoc} */ public boolean matches(T target) { return target.isArray(); } @Override public String toString() { return "isArray()"; } }<commit_after>package net.bytebuddy.matcher; import net.bytebuddy.build.HashCodeAndEqualsPlugin; import net.bytebuddy.description.type.TypeDefinition; /** * Matches an enumeration type. * * @param <T> The type of the matched entity. */ @HashCodeAndEqualsPlugin.Enhance public class ArrayTypeMatcher<T extends TypeDefinition> extends ElementMatcher.Junction.AbstractBase<T> { /** * {@inheritDoc} */ public boolean matches(T target) { return target.isArray(); } @Override public String toString() { return "isArray()"; } }
<commit_msg>Add test for enumeration editing Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me> <commit_before>from gi.repository import Gtk from gaphor import UML from gaphor.UML.classes import ClassItem from gaphor.UML.classes.classespropertypages import ClassAttributes class TestClassPropertyPages: def test_attribute_editing(self, case): class_item = case.create(ClassItem, UML.Class) model = ClassAttributes(class_item, (str, bool, object)) model.append([None, False, None]) path = Gtk.TreePath.new_first() iter = model.get_iter(path) model.update(iter, col=0, value="attr") assert model[iter][-1] is class_item.subject.ownedAttribute[0] <commit_after>from gi.repository import Gtk from gaphor import UML from gaphor.UML.classes import ClassItem, EnumerationItem from gaphor.UML.classes.classespropertypages import ( ClassAttributes, ClassEnumerationLiterals, ) def test_attribute_editing(case): class_item = case.create(ClassItem, UML.Class) model = ClassAttributes(class_item, (str, bool, object)) model.append([None, False, None]) path = Gtk.TreePath.new_first() iter = model.get_iter(path) model.update(iter, col=0, value="attr") assert model[iter][-1] is class_item.subject.ownedAttribute[0] def test_enumeration_editing(case): enum_item = case.create(EnumerationItem, UML.Enumeration) model = ClassEnumerationLiterals(enum_item, (str, object)) model.append([None, None]) path = Gtk.TreePath.new_first() iter = model.get_iter(path) model.update(iter, col=0, value="enum") assert model[iter][-1] is enum_item.subject.ownedLiteral[0]
<commit_msg>Update the s3 api example <commit_before>package aws import ( "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials/stscreds" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" ) func ListBuckets() { fmt.Println("List buckets") // Specify profile for config and region for requests sess := session.Must(session.NewSessionWithOptions(session.Options{ Config: aws.Config{Region: aws.String("us-west-2")}, Profile: "okta2aws", })) creds := stscreds.NewCredentials(sess, "arn:aws:iam::4xxxx9:role/SoeRolee") s3svc := s3.New(sess, &aws.Config{Credentials: creds}) result, err := s3svc.ListBuckets(nil) if err != nil { fmt.Println("Failed to list s3 buckets.", err) } for _, b := range result.Buckets { fmt.Printf("* %s created on %s \n ", aws.StringValue(b.Name), aws.TimeValue(b.CreationDate)) } } <commit_after>package aws import ( "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials/stscreds" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" ) func ListBuckets() { fmt.Println("List buckets") // Specify profile for config and region for requests sess := session.Must(session.NewSessionWithOptions(session.Options{ Config: aws.Config{Region: aws.String("us-west-2")}, Profile: "okta2aws", })) creds := stscreds.NewCredentials(sess, "arn:aws:iam::461168169469:role/SSOAdmin1Role") s3svc := s3.New(sess, &aws.Config{Credentials: creds}) result, err := s3svc.ListBuckets(nil) if err != nil { fmt.Println("Failed to list s3 buckets.", err) } for _, b := range result.Buckets { fmt.Printf("Bucket %s created on %s \n ", aws.StringValue(b.Name), aws.TimeValue(b.CreationDate)) bucketname := aws.String(*b.Name) // Get Bucket location. input := &s3.GetBucketLocationInput{ Bucket: bucketname, } result, err := s3svc.GetBucketLocation(input) if err != nil { fmt.Println(err.Error()) } fmt.Printf("Result: %s", aws.StringValue(result.LocationConstraint)) } }
<commit_msg>Print CPU time in splash screen <commit_before> string Logo = str("\n" " _.-.\n" " .-. `) | .-.\n" " _.'`. .~./ \\.~. .`'._\n" " .-' .'.'.'.-| |-.'.'.'. '-.\n" " `'`'`'`'` \\ / `'`'`'`'`\n" " /||\\\n" " //||\\\\\n" "\n" " The Kernel of Truth\n"); void kernel_main(void *multiboot_tables) { enum status status = init_log("log"); assert(status == Ok); log(Logo); logf("\tVersion %d.%d.%d\n\tCommit %s\n\t%s\n", kernel_major, kernel_minor, kernel_patch, vcs_version, project_website); init_interrupts(); init_physical_allocator(multiboot_tables); init_slab(); status = init_heap(); assert(status == Ok); halt(); } <commit_after> string Logo = str("\n" " _.-.\n" " .-. `) | .-.\n" " _.'`. .~./ \\.~. .`'._\n" " .-' .'.'.'.-| |-.'.'.'. '-.\n" " `'`'`'`'` \\ / `'`'`'`'`\n" " /||\\\n" " //||\\\\\n" "\n" " The Kernel of Truth\n"); void kernel_main(void *multiboot_tables) { enum status status = init_log("log"); assert(status == Ok); log(Logo); logf("\tVersion %d.%d.%d\n\tCommit %s\n\t%s\n\tCPU Time %ld\n", kernel_major, kernel_minor, kernel_patch, vcs_version, project_website, cpu_time()); init_interrupts(); init_physical_allocator(multiboot_tables); init_slab(); status = init_heap(); assert(status == Ok); halt(); }
<commit_msg>Add ssl_version to the list of attributes, required when vnc_api gets called via multiprocessing module. This will ensure ssl_version gets included when pickle calls __getstate__ and __setstate__. Courtesy: https://github.com/sigmavirus24/requests-toolbelt/commit/decadbd3512444889feb30cf1ff2f1448a3ecfca Closes-Bug:#1604247 Change-Id: Iee9e0348c005e88c535f4da33cf98149a8c1b19d <commit_before># -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # @author: Sanju Abraham, Juniper Networks, OpenContrail from requests.adapters import HTTPAdapter try: # This is required for RDO, which installs both python-requests # and python-urllib3, but symlinks python-request's internally packaged # urllib3 to the site installed one. from requests.packages.urllib3.poolmanager import PoolManager except ImportError: # Fallback to standard installation methods from urllib3.poolmanager import PoolManager class SSLAdapter(HTTPAdapter): '''An HTTPS Transport Adapter that can be configured with SSL/TLS version.''' def __init__(self, ssl_version=None, **kwargs): self.ssl_version = ssl_version self.poolmanager = None super(SSLAdapter, self).__init__(**kwargs) def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, ssl_version=self.ssl_version) <commit_after># -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # @author: Sanju Abraham, Juniper Networks, OpenContrail from requests.adapters import HTTPAdapter try: # This is required for RDO, which installs both python-requests # and python-urllib3, but symlinks python-request's internally packaged # urllib3 to the site installed one. from requests.packages.urllib3.poolmanager import PoolManager except ImportError: # Fallback to standard installation methods from urllib3.poolmanager import PoolManager class SSLAdapter(HTTPAdapter): '''An HTTPS Transport Adapter that can be configured with SSL/TLS version.''' HTTPAdapter.__attrs__.extend(['ssl_version']) def __init__(self, ssl_version=None, **kwargs): self.ssl_version = ssl_version self.poolmanager = None super(SSLAdapter, self).__init__(**kwargs) def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, ssl_version=self.ssl_version)
<commit_msg>Fix default code directory for non-root user. Fixing the default code directory for non-root users, which should be under `~/.puppetlabs/etc/code`. The bug was that there was a check to see if the global location existed, and if it did, to use that location even when non-root. The fix is to remove that check and only use the global location for root. This matches the behavior of Puppet. <commit_before> using namespace std; namespace fs = boost::filesystem; namespace sys = boost::system; namespace puppet { namespace compiler { string settings::default_code_directory() { auto home = getenv("HOME"); // For root or if the directory exists, use the global code directory sys::error_code ec; if (!home || geteuid() == 0 || fs::is_directory("/etc/puppetlabs/code", ec)) { return "/etc/puppetlabs/code"; } // Otherwise, use the local directory return (fs::path(home) / ".puppetlabs" / "etc" / "code").string(); } vector<string> settings::default_environment_directories() { vector<string> directories = { "$codedir/environments", }; return directories; } vector<string> settings::default_module_directories() { vector<string> directories = { "$codedir/modules", "/opt/puppetlabs/puppet/modules", }; return directories; } }} // namespace puppet::compiler<commit_after> using namespace std; namespace fs = boost::filesystem; namespace sys = boost::system; namespace puppet { namespace compiler { string settings::default_code_directory() { auto home = getenv("HOME"); // For root or users without a HOME directory, use the global location if (!home || geteuid() == 0) { return "/etc/puppetlabs/code"; } // Otherwise, use the local directory return (fs::path(home) / ".puppetlabs" / "etc" / "code").string(); } vector<string> settings::default_environment_directories() { vector<string> directories = { "$codedir/environments", }; return directories; } vector<string> settings::default_module_directories() { vector<string> directories = { "$codedir/modules", "/opt/puppetlabs/puppet/modules", }; return directories; } }} // namespace puppet::compiler
<commit_msg>Use integers instead of floats in for-loop While this adds a few more lines to the program, I think it makes it more explicit where the constants come from. It also faciliates easier modification of the example. It's also safer to use an integer instead of a float as a conditional in a for-loop. This is because floating point values are imprecise. As a result, you may end up with one more or one fewer iteration than you anticipated. Integers don't have this disadvantage. <commit_before> class SpiralLinesGLWidget : public GLWidget { public: SpiralLinesGLWidget(QWidget* parent = 0); protected: void initializeGL(); void render(); }; SpiralLinesGLWidget::SpiralLinesGLWidget(QWidget* parent) : GLWidget(parent) {} void SpiralLinesGLWidget::initializeGL() { GLWidget::initializeGL(); setXRotation(-45); setYRotation(15); setZRotation(45); } void SpiralLinesGLWidget::render() { // How many revolutions of the spiral are rendered. static const float REVOLUTIONS = 10; static const float PI = 3.14159; glBegin(GL_LINE_STRIP); for (float angle = 0; angle < 2*PI*REVOLUTIONS; angle += PI / (2 * REVOLUTIONS * 10)) { glVertex2f( angle * (float) sin(angle), angle * (float) cos(angle)); } glEnd(); } #endif // SPIRALLINESGLWIDGET_H <commit_after> class SpiralLinesGLWidget : public GLWidget { public: SpiralLinesGLWidget(QWidget* parent = 0); protected: void initializeGL(); void render(); }; SpiralLinesGLWidget::SpiralLinesGLWidget(QWidget* parent) : GLWidget(parent) {} void SpiralLinesGLWidget::initializeGL() { GLWidget::initializeGL(); setXRotation(-45); setYRotation(15); setZRotation(45); } void SpiralLinesGLWidget::render() { // How many revolutions of the spiral are rendered. static const float REVOLUTIONS = 10; static const float PI = 3.14159; // How many vertices per revolution. static const float SLICES = 10; glBegin(GL_LINE_STRIP); for (int i = 0; i <= REVOLUTIONS * SLICES; i++) { const float angle = i * 2 * PI / SLICES; glVertex2f( angle * (float) sin(angle), angle * (float) cos(angle)); } glEnd(); } #endif // SPIRALLINESGLWIDGET_H
<commit_msg>Add Second Shape Test for Layers Util <commit_before>"""Tests for spectral.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np import os import layers class LayersTest(tf.test.TestCase): def test_conv_transpose_shape(self): inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32) conv_transpose = layers.Conv1DTranspose( filters=2, kernel_size=1, strides=1 ) outputs = conv_transpose(inputs) self.assertShapeEqual(inputs, outputs) if __name__ == '__main__': os.environ["CUDA_VISIBLE_DEVICES"] = '' tf.test.main() <commit_after>"""Tests for spectral.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np import os import layers class LayersTest(tf.test.TestCase): def test_conv_transpose_shape(self): inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32) conv_transpose = layers.Conv1DTranspose( filters=2, kernel_size=1, strides=1 ) outputs = conv_transpose(inputs) self.assertShapeEqual(inputs, outputs) def test_conv_transpose_shape_upscale(self): inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32) conv_transpose = layers.Conv1DTranspose( filters=2, kernel_size=1, strides=2 ) outputs = conv_transpose(inputs) self.assertEqual((10, 10, 2), outputs.shape) if __name__ == '__main__': os.environ["CUDA_VISIBLE_DEVICES"] = '' tf.test.main()
<commit_msg>Add a timeout to the delta detector Make it so that the detector doesn't beep more than once per second. It would be even better if the beeping occurred in another thread... <commit_before>import numpy as N import gtk.gdk class DeltaDetector(object): def __init__(self, active=False, threshold=20.0): self._previous_frame = None self._frame = None self.active = active self.threshold = threshold def send_frame(self, frame): self._previous_frame = self._frame self._frame = N.array(frame, dtype=float) if not self.active: return if self._previous_frame is None: return if(self._previous_frame.shape != self._frame.shape): self._previous_frame = None return if N.max(N.abs(self._frame - self._previous_frame)) > self.threshold: gtk.gdk.beep() # Properties @property def active(self): return self._active @active.setter def active(self, value): self._active = bool(value) @property def threshold(self): return self._threshold @threshold.setter def threshold(self, value): self._threshold = float(value) @property def average(self): if self._frame is None or self._previous_frame is None: return 0.0 return N.mean(self._frame - self._previous_frame) <commit_after>import numpy as N import gobject import gtk.gdk class DeltaDetector(object): def __init__(self, active=False, threshold=20.0): self._previous_frame = None self._frame = None self.active = active self.threshold = threshold self._timed_out = False def send_frame(self, frame): self._previous_frame = self._frame self._frame = N.array(frame, dtype=float) if self._timed_out: return if not self.active: return if self._previous_frame is None: return if(self._previous_frame.shape != self._frame.shape): self._previous_frame = None return if N.max(N.abs(self._frame - self._previous_frame)) > self.threshold: gtk.gdk.beep() # Don't beep more than once per second self._timed_out = True gobject.timeout_add(1000, self._switch_on_timeout) def _switch_on_timeout(self): self._timed_out = False return False # Properties @property def active(self): return self._active @active.setter def active(self, value): self._active = bool(value) @property def threshold(self): return self._threshold @threshold.setter def threshold(self, value): self._threshold = float(value) @property def average(self): if self._frame is None or self._previous_frame is None: return 0.0 return N.mean(self._frame - self._previous_frame)
<commit_msg>Mark workspace app related properties as deprecated <commit_before>package com.github.seratch.jslack.api.methods.response.oauth; import com.github.seratch.jslack.api.methods.SlackApiResponse; import lombok.Data; import java.util.List; @Data public class OAuthAccessResponse implements SlackApiResponse { private boolean ok; private String warning; private String error; private String needed; private String provided; private String tokenType; private String accessToken; private String scope; private String enterpriseId; private String teamName; private String teamId; private String userId; private IncomingWebhook incomingWebhook; private Bot bot; private AuthorizingUser authorizingUser; private InstallerUser installerUser; @Deprecated // for workspace apps private Scopes scopes; @Data public static class IncomingWebhook { private String url; private String channel; private String channelId; private String configurationUrl; } @Data public static class Bot { private String botUserId; private String botAccessToken; } @Data public static class AuthorizingUser { private String userId; private String appHome; } @Data public static class InstallerUser { private String userId; private String appHome; } @Data public static class Scopes { private List<String> appHome; private List<String> team; private List<String> channel; private List<String> group; private List<String> mpim; private List<String> im; private List<String> user; } } <commit_after>package com.github.seratch.jslack.api.methods.response.oauth; import com.github.seratch.jslack.api.methods.SlackApiResponse; import lombok.Data; import java.util.List; @Data public class OAuthAccessResponse implements SlackApiResponse { private boolean ok; private String warning; private String error; private String needed; private String provided; private String tokenType; private String accessToken; private String scope; private String enterpriseId; private String teamName; private String teamId; private String userId; private IncomingWebhook incomingWebhook; private Bot bot; @Data public static class IncomingWebhook { private String url; private String channel; private String channelId; private String configurationUrl; } @Data public static class Bot { private String botUserId; private String botAccessToken; } @Deprecated // for workspace apps private AuthorizingUser authorizingUser; @Deprecated // for workspace apps private InstallerUser installerUser; @Deprecated // for workspace apps private Scopes scopes; @Deprecated @Data public static class AuthorizingUser { private String userId; private String appHome; } @Deprecated @Data public static class InstallerUser { private String userId; private String appHome; } @Deprecated @Data public static class Scopes { private List<String> appHome; private List<String> team; private List<String> channel; private List<String> group; private List<String> mpim; private List<String> im; private List<String> user; } }
<commit_msg>Exclude test_project from installation so it won't pollute site-packages.<commit_before>try: from setuptools import setup, find_packages except: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name = 'django-flatblocks', version = '0.3.5', description = 'django-flatblocks acts like django.contrib.flatpages but ' 'for parts of a page; like an editable help box you want ' 'show alongside the main content.', long_description = open('README.rst').read(), keywords = 'django apps', license = 'New BSD License', author = 'Horst Gutmann', author_email = 'zerok@zerokspot.com', url = 'http://github.com/zerok/django-flatblocks/', dependency_links = [], classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Plugins', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], packages = find_packages(exclude='ez_setup'), include_package_data = True, zip_safe = False, ) <commit_after>try: from setuptools import setup, find_packages except: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name = 'django-flatblocks', version = '0.3.5', description = 'django-flatblocks acts like django.contrib.flatpages but ' 'for parts of a page; like an editable help box you want ' 'show alongside the main content.', long_description = open('README.rst').read(), keywords = 'django apps', license = 'New BSD License', author = 'Horst Gutmann', author_email = 'zerok@zerokspot.com', url = 'http://github.com/zerok/django-flatblocks/', dependency_links = [], classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Plugins', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], packages = find_packages(exclude=['ez_setup', 'test_project']), include_package_data = True, zip_safe = False, )
<commit_msg>Add GetProcessHeaps(), HeapFree() of kernel32 <commit_before>import * as D from '../windef'; import * as GT from '../types'; export const fnDef: GT.Win32FnDef = { GetLastError: [D.DWORD, []], // err code: https://msdn.microsoft.com/zh-cn/library/windows/desktop/ms681381(v=vs.85).aspx GetModuleHandleW: [D.HMODULE, [D.LPCTSTR]], // retrive value from buf by ret.ref().readUInt32() GetModuleHandleExW: [D.BOOL, [D.DWORD, D.LPCTSTR, D.HMODULE]], // flags, optional LPCTSTR name, ref hModule }; export interface Win32Fn { GetLastError(): GT.DWORD; GetModuleHandleW(lpModuleName: GT.LPCTSTR): GT.HMODULE; GetModuleHandleExW(dwFlags: GT.DWORD, lpModuleName: GT.LPCTSTR | null, phModule: GT.HMODULE): GT.BOOL; } <commit_after>import * as D from '../windef'; import * as GT from '../types'; export const fnDef: GT.Win32FnDef = { GetLastError: [D.DWORD, []], // err code: https://msdn.microsoft.com/zh-cn/library/windows/desktop/ms681381(v=vs.85).aspx GetModuleHandleW: [D.HMODULE, [D.LPCTSTR]], // retrive value from buf by ret.ref().readUInt32() GetModuleHandleExW: [D.BOOL, [D.DWORD, D.LPCTSTR, D.HMODULE]], // flags, optional LPCTSTR name, ref hModule GetProcessHeaps: [D.DWORD, [D.DWORD, D.PHANDLE]], HeapFree: [D.BOOL, [D.HANDLE, D.DWORD, D.LPVOID]], }; export interface Win32Fn { GetLastError(): GT.DWORD; GetModuleHandleW(lpModuleName: GT.LPCTSTR): GT.HMODULE; GetModuleHandleExW(dwFlags: GT.DWORD, lpModuleName: GT.LPCTSTR | null, phModule: GT.HMODULE): GT.BOOL; GetProcessHeaps(NumberOfHeaps: GT.DWORD, ProcessHeaps: GT.PHANDLE): GT.DWORD; HeapFree( hHeap: GT.HANDLE, dwFlags: GT.DWORD, lpMem: GT.LPVOID | null): GT.BOOL; }
<commit_msg>Add \r at the end of Web socket <commit_before>import os import socket import websocket from . import IOHandler def resolve_hostname(hostname, port): # We do our own mDNS resolution # to enforce we only search for IPV4 address # and avoid a 5s timeout in the websocket on the ESP # See https://github.com/esp8266/Arduino/issues/2110 addrinfo = socket.getaddrinfo(hostname, port, socket.AF_INET, 0, socket.SOL_TCP) addr = addrinfo[0][4][0] return addr class Ws(IOHandler): @classmethod def is_host_compatible(cls, host): try: socket.inet_pton(socket.AF_INET, host) return True except socket.error: return host.endswith('.local') @classmethod def available_hosts(cls): hosts = ['pi-gate.local'] return [ ip for ip in hosts if os.system('ping -c 1 -W1 -t1 {} > /dev/null 2>&1'.format(ip)) == 0 ] def __init__(self, host, port=9342): host = resolve_hostname(host, port) url = 'ws://{}:{}'.format(host, port) self._ws = websocket.create_connection(url) def is_ready(self): return True def recv(self): return self._ws.recv() def write(self, data): self._ws.send(data) def close(self): self._ws.close() <commit_after>import os import socket import websocket from . import IOHandler def resolve_hostname(hostname, port): # We do our own mDNS resolution # to enforce we only search for IPV4 address # and avoid a 5s timeout in the websocket on the ESP # See https://github.com/esp8266/Arduino/issues/2110 addrinfo = socket.getaddrinfo(hostname, port, socket.AF_INET, 0, socket.SOL_TCP) addr = addrinfo[0][4][0] return addr class Ws(IOHandler): @classmethod def is_host_compatible(cls, host): try: socket.inet_pton(socket.AF_INET, host) return True except socket.error: return host.endswith('.local') @classmethod def available_hosts(cls): hosts = ['pi-gate.local'] return [ ip for ip in hosts if os.system('ping -c 1 -W1 -t1 {} > /dev/null 2>&1'.format(ip)) == 0 ] def __init__(self, host, port=9342): host = resolve_hostname(host, port) url = 'ws://{}:{}'.format(host, port) self._ws = websocket.create_connection(url) def is_ready(self): return True def recv(self): return self._ws.recv() def write(self, data): self._ws.send(data + '\r'.encode()) def close(self): self._ws.close()
<commit_msg>Add media to url, for development only <commit_before>from django.conf.urls import url from django.contrib.auth.decorators import login_required from django.contrib.auth import views from . import views app_name="listings" urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^accounts/register/$', views.register, name='register'), url(r'^accounts/register/complete/$', views.RegistrationCompleteView.as_view(), name='registration_complete'), url(r'^accounts/profile/$', login_required(views.ProfileView.as_view()), name='profile'), url(r'^listing/new/$', login_required(views.ListingCreate.as_view()), name='new'), url(r'^listing/(?P<listing_id>\d+)/$', views.ListingDetail.as_view(), name='detail'), url(r'^listing/(?P<listing_id>\d+)/edit/$', login_required(views.ListingEdit.as_view()), name='edit'), url(r'^listing/(?P<listing_id>\d+)/toggle/$', login_required(views.listing_status_toggle), name='toggle'), ] <commit_after>from django.conf.urls import url from django.contrib.auth.decorators import login_required from django.contrib.auth import views from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from . import views app_name="listings" urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^accounts/register/$', views.register, name='register'), url(r'^accounts/register/complete/$', views.RegistrationCompleteView.as_view(), name='registration_complete'), url(r'^accounts/profile/$', login_required(views.ProfileView.as_view()), name='profile'), url(r'^accounts/profile/preference$', login_required(views.PreferenceView.as_view()), name='preference'), url(r'^listing/new/$', login_required(views.ListingCreate.as_view()), name='new'), url(r'^listing/(?P<listing_id>\d+)/$', views.ListingDetail.as_view(), name='detail'), url(r'^listing/(?P<listing_id>\d+)/edit/$', login_required(views.ListingEdit.as_view()), name='edit'), url(r'^listing/(?P<listing_id>\d+)/toggle/$', login_required(views.listing_status_toggle), name='toggle'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) admin.site.site_header = 'Housing Admin'
<commit_msg>Change how StringIO is imported <commit_before>import contextlib import re import sys import mock from six.moves import cStringIO from random_object_id.random_object_id import \ gen_random_object_id, parse_args, main @contextlib.contextmanager def captured_output(): new_out = StringIO() old_out = sys.stdout try: sys.stdout = new_out yield sys.stdout finally: sys.stdout = old_out def test_gen_random_object_id(): assert re.match('[0-9a-f]{24}', gen_random_object_id()) def test_gen_random_object_id_time(): with mock.patch('time.time') as mock_time: mock_time.return_value = 1429506585.786924 object_id = gen_random_object_id() assert re.match('55348a19', object_id) def test_parse_args(): assert parse_args(['-l']).long_form def test_main(): with mock.patch('sys.argv', ['random_object_id']): with captured_output() as output: main() assert re.match('[0-9a-f]{24}\n', output.getvalue()) def test_main_l(): with mock.patch('sys.argv', ['random_object_id', '-l']): with captured_output() as output: main() assert re.match('ObjectId\("[0-9a-f]{24}"\)\n', output.getvalue()) <commit_after>import contextlib import re import sys import mock import six from random_object_id.random_object_id import \ gen_random_object_id, parse_args, main @contextlib.contextmanager def captured_output(): old_out = sys.stdout try: sys.stdout = six.StringIO() yield sys.stdout finally: sys.stdout = old_out def test_gen_random_object_id(): assert re.match('[0-9a-f]{24}', gen_random_object_id()) def test_gen_random_object_id_time(): with mock.patch('time.time') as mock_time: mock_time.return_value = 1429506585.786924 object_id = gen_random_object_id() assert re.match('55348a19', object_id) def test_parse_args(): assert parse_args(['-l']).long_form def test_main(): with mock.patch('sys.argv', ['random_object_id']): with captured_output() as output: main() assert re.match('[0-9a-f]{24}\n', output.getvalue()) def test_main_l(): with mock.patch('sys.argv', ['random_object_id', '-l']): with captured_output() as output: main() assert re.match('ObjectId\("[0-9a-f]{24}"\)\n', output.getvalue())
<commit_msg>Make an empty struct nonempty. In r23405 we added a component of the task private data to hold comm layer information. This is chpl_comm_taskPrvData_t, a struct typt. For comm=none we don't need any comm layer info, so we made the struct type empty. Unfortunately empty struct types aren't legal C (c99 standard, 6.2.5 (20)). The gcc compiler lets this pass, but the PGI and Cray compilers bark at it. To fix this, add a dummy element to the struct for the comm=none case. (I tried making it a 0-length array, but the PGI compiler barked at that, too.) git-svn-id: 88467cb1fb04b8a755be7e1ee1026be4190196ef@23411 3a8e244f-b0f2-452b-bcba-4c88e055c3ca <commit_before>// This is the last-resort version of this file. It will be used only // if the comm layer implementation does not supply one. #ifndef _chpl_comm_task_decls_h #define _chpl_comm_task_decls_h // Define the type of a n.b. communications handle. typedef void* chpl_comm_nb_handle_t; typedef struct { } chpl_comm_taskPrvData_t; #undef HAS_CHPL_CACHE_FNS #endif <commit_after>// This is the last-resort version of this file. It will be used only // if the comm layer implementation does not supply one. #ifndef _chpl_comm_task_decls_h #define _chpl_comm_task_decls_h // Define the type of a n.b. communications handle. typedef void* chpl_comm_nb_handle_t; typedef struct { int dummy; // structs must be nonempty } chpl_comm_taskPrvData_t; #undef HAS_CHPL_CACHE_FNS #endif
<commit_msg>Add some tests for the model <commit_before>import unittest from datetime import datetime from twofa import create_app, db from twofa.models import User class UserTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') db.create_all() def tearDown(self): db.session.remove() db.drop_all() def test_password_setter(self): pass<commit_after>import unittest from twofa import create_app, db from twofa.models import User from unittest.mock import patch class UserTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.user = User( 'example@example.com', 'fakepassword', 'Alice', 33, 600112233, 123 ) db.create_all() def tearDown(self): db.session.remove() db.drop_all() def test_has_authy_app(self): # Arrange # Act with patch('twofa.models.authy_user_has_app', return_value=True): has_authy_app = self.user.has_authy_app # Assert self.assertTrue(has_authy_app) def test_hasnt_authy_app(self): # Arrange # Act with patch('twofa.models.authy_user_has_app', return_value=False): has_authy_app = self.user.has_authy_app # Assert self.assertFalse(has_authy_app) def test_password_is_unreadable(self): # Arrange # Act / Assert with self.assertRaises(AttributeError): self.user.password def test_password_setter(self): # Arrange old_password_hash = self.user.password_hash password = 'superpassword' # Act self.user.password = password # Assert self.assertNotEqual(password, self.user.password_hash) self.assertNotEqual(old_password_hash, self.user.password_hash) def test_verify_password(self): # Arrange password = 'anothercoolpassword' unused_password = 'unusedpassword' self.user.password = password # Act ret_good_password = self.user.verify_password(password) ret_bad_password = self.user.verify_password(unused_password) # Assert self.assertTrue(ret_good_password) self.assertFalse(ret_bad_password) def test_send_one_touch_request(self): # Arrange # Act with patch('twofa.models.send_authy_one_touch_request') as fake_send: self.user.send_one_touch_request() # Assert fake_send.assert_called_with(self.user.authy_id, self.user.email)
<commit_msg>Replace my deferred with a mock <commit_before>from asyncio import Future, gather, new_event_loop, sleep from twisted.internet.defer import Deferred, ensureDeferred from pyee import EventEmitter def test_asyncio_emit(): """Test that event_emitters can handle wrapping coroutines as used with asyncio. """ loop = new_event_loop() ee = EventEmitter(loop=loop) should_call = Future(loop=loop) @ee.on('event') async def event_handler(): should_call.set_result(True) async def create_timeout(loop=loop): await sleep(0.1, loop=loop) if not should_call.done(): raise Exception('should_call timed out!') return should_call.cancel() timeout = create_timeout(loop=loop) @should_call.add_done_callback def _done(result): assert result ee.emit('event') loop.run_until_complete(gather(should_call, timeout, loop=loop)) loop.close() def test_twisted_emit(): """Test that event_emitters can handle wrapping coroutines when using twisted and ensureDeferred. """ ee = EventEmitter(scheduler=ensureDeferred) should_call = Deferred() @ee.on('event') async def event_handler(): should_call.callback(True) @should_call.addCallback def _done(result): assert result @should_call.addErrback def _err(exc): raise exc ee.emit('event') <commit_after>from asyncio import Future, gather, new_event_loop, sleep from mock import Mock from twisted.internet.defer import ensureDeferred from pyee import EventEmitter def test_asyncio_emit(): """Test that event_emitters can handle wrapping coroutines as used with asyncio. """ loop = new_event_loop() ee = EventEmitter(loop=loop) should_call = Future(loop=loop) @ee.on('event') async def event_handler(): should_call.set_result(True) async def create_timeout(loop=loop): await sleep(0.1, loop=loop) if not should_call.done(): raise Exception('should_call timed out!') return should_call.cancel() timeout = create_timeout(loop=loop) @should_call.add_done_callback def _done(result): assert result ee.emit('event') loop.run_until_complete(gather(should_call, timeout, loop=loop)) loop.close() def test_twisted_emit(): """Test that event_emitters can handle wrapping coroutines when using twisted and ensureDeferred. """ ee = EventEmitter(scheduler=ensureDeferred) should_call = Mock() @ee.on('event') async def event_handler(): should_call(True) ee.emit('event') should_call.assert_called_once()
<commit_msg>Add MongoDB + post route handling <commit_before>package main import ( "github.com/codegangsta/martini" "github.com/codegangsta/martini-contrib/render" ) func main() { m := martini.Classic() m.Use(render.Renderer()) m.Get("/", func() string { return "Merry Christmas!" }) m.Get("/wishes", func(r render.Render) { r.HTML(200, "list", nil) }) m.Run() } <commit_after>package main import ( "github.com/codegangsta/martini" "github.com/codegangsta/martini-contrib/binding" "github.com/codegangsta/martini-contrib/render" "gopkg.in/mgo.v2" ) type Wish struct { Name string `form:"name"` Description string `form:"name"` } // DB Returns a martini.Handler func DB() martini.Handler { session, err := mgo.Dial("mongodb://localhost") if err != nil { panic(err) } return func(c martini.Context) { s := session.Clone() c.Map(s.DB("advent")) defer s.Close() c.Next() } } // GetAll returns all Wishes in the database func GetAll(db *mgo.Database) []Wish { var wishlist []Wish db.C("wishes").Find(nil).All(&wishlist) return wishlist } func main() { m := martini.Classic() m.Use(render.Renderer()) m.Use(DB()) m.Get("/", func() string { return "Merry Christmas!" }) m.Get("/wishes", func(r render.Render) { r.HTML(200, "list", nil) }) m.Post("/wishes", binding.Form(Wish{}), func(wish Wish, r render.Render, db *mgo.Database) { db.C("wishes").Insert(wish) r.HTML(200, "list", GetAll(db)) }) m.Run() }
<commit_msg>Add test for git clone <commit_before>package main import ( "net/http" "net/http/httptest" "testing" ) func TestRootAccess(t *testing.T) { response := httptest.NewRecorder() n := setUpServer() req, err := http.NewRequest("GET", "http://localhost:8080/", nil) if err != nil { t.Error(err) } n.ServeHTTP(response, req) if response.Code != http.StatusOK { t.Errorf("Got error for GET ruquest to /") } body := string(response.Body.Bytes()) expectedBody := "{\"status\":\"ok\"}" if body != expectedBody { t.Errorf("Got empty body for GET request to /\n Got: %s, Expected: %s", body, expectedBody) } } <commit_after>package main import ( "net/http" "net/http/httptest" "testing" "github.com/wantedly/risu/schema" ) func TestGitClone(t *testing.T) { opts := schema.BuildCreateOpts{ SourceRepo: "wantedly/private-nginx-image-server", Name: "quay.io/wantedly/private-nginx-image-server:test", } build := schema.NewBuild(opts) err := gitClone(build) if err != nil { t.Error(err) } } func TestRootAccess(t *testing.T) { response := httptest.NewRecorder() n := setUpServer() req, err := http.NewRequest("GET", "http://localhost:8080/", nil) if err != nil { t.Error(err) } n.ServeHTTP(response, req) if response.Code != http.StatusOK { t.Errorf("Got error for GET ruquest to /") } body := string(response.Body.Bytes()) expectedBody := "{\"status\":\"ok\"}" if body != expectedBody { t.Errorf("Got empty body for GET request to /\n Got: %s, Expected: %s", body, expectedBody) } }
<commit_msg>Make close() idempotent and implement Closable rather than AutoClosable<commit_before>package org.purl.wf4ever.robundle; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import org.purl.wf4ever.robundle.fs.BundleFileSystem; public class Bundle implements AutoCloseable { private boolean deleteOnClose; private final Path root; public Bundle(Path root, boolean deleteOnClose) { this.root = root; this.setDeleteOnClose(deleteOnClose); } @Override public void close() throws IOException { close(isDeleteOnClose()); } protected void close(boolean deleteOnClose) throws IOException { getFileSystem().close(); if (deleteOnClose) { Files.deleteIfExists(getSource()); } } public FileSystem getFileSystem() { return getRoot().getFileSystem(); } public Path getRoot() { return root; } public Path getSource() { BundleFileSystem fs = (BundleFileSystem) getFileSystem(); return fs.getSource(); } public boolean isDeleteOnClose() { return deleteOnClose; } public void setDeleteOnClose(boolean deleteOnClose) { this.deleteOnClose = deleteOnClose; } } <commit_after>package org.purl.wf4ever.robundle; import java.io.Closeable; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import org.purl.wf4ever.robundle.fs.BundleFileSystem; public class Bundle implements Closeable { private boolean deleteOnClose; private final Path root; public Bundle(Path root, boolean deleteOnClose) { this.root = root; this.setDeleteOnClose(deleteOnClose); } @Override public void close() throws IOException { close(isDeleteOnClose()); } protected void close(boolean deleteOnClose) throws IOException { if (! getFileSystem().isOpen()) { return; } getFileSystem().close(); if (deleteOnClose) { Files.deleteIfExists(getSource()); } } public FileSystem getFileSystem() { return getRoot().getFileSystem(); } public Path getRoot() { return root; } public Path getSource() { BundleFileSystem fs = (BundleFileSystem) getFileSystem(); return fs.getSource(); } public boolean isDeleteOnClose() { return deleteOnClose; } public void setDeleteOnClose(boolean deleteOnClose) { this.deleteOnClose = deleteOnClose; } }
<commit_msg>Add "include_initial" kwarg to support tailing stack updates `get_events` will return all events that have occurred for a stack. This is useless if we're tailing an update to a stack. <commit_before>import time def _tail_print(e): print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id)) def get_events(conn, stackname): """Get the events in batches and return in chronological order""" next = None event_list = [] while 1: events = conn.describe_stack_events(stackname, next) event_list.append(events) if events.next_token is None: break next = events.next_token time.sleep(1) return reversed(sum(event_list, [])) def tail(conn, stack_name, log_func=_tail_print, sleep_time=5): """Show and then tail the event log""" # First dump the full list of events in chronological order and keep # track of the events we've seen already seen = set() initial_events = get_events(conn, stack_name) for e in initial_events: log_func(e) seen.add(e.event_id) # Now keep looping through and dump the new events while 1: events = get_events(conn, stack_name) for e in events: if e.event_id not in seen: log_func(e) seen.add(e.event_id) time.sleep(sleep_time) <commit_after>import time def _tail_print(e): print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id)) def get_events(conn, stackname): """Get the events in batches and return in chronological order""" next = None event_list = [] while 1: events = conn.describe_stack_events(stackname, next) event_list.append(events) if events.next_token is None: break next = events.next_token time.sleep(1) return reversed(sum(event_list, [])) def tail(conn, stack_name, log_func=_tail_print, sleep_time=5, include_initial=True): """Show and then tail the event log""" # First dump the full list of events in chronological order and keep # track of the events we've seen already seen = set() initial_events = get_events(conn, stack_name) for e in initial_events: if include_initial: log_func(e) seen.add(e.event_id) # Now keep looping through and dump the new events while 1: events = get_events(conn, stack_name) for e in events: if e.event_id not in seen: log_func(e) seen.add(e.event_id) time.sleep(sleep_time)
<commit_msg>Set the default device to native in Python binding <commit_before>from xchainer._core import * # NOQA _global_context = Context() _global_context.get_backend('native') set_global_default_context(_global_context) <commit_after>from xchainer._core import * # NOQA _global_context = Context() set_global_default_context(_global_context) set_default_device('native')
<commit_msg>Add virtualenv.create function to enable easy virtualenv creation <commit_before>from __future__ import absolute_import, division, print_function from virtualenv.__about__ import ( __author__, __copyright__, __email__, __license__, __summary__, __title__, __uri__, __version__ ) __all__ = [ "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", ] <commit_after>from __future__ import absolute_import, division, print_function from virtualenv.__about__ import ( __author__, __copyright__, __email__, __license__, __summary__, __title__, __uri__, __version__ ) from virtualenv.core import create __all__ = [ "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", "create", ]
<commit_msg>Define bool type together with true/false <commit_before> // Explicitly-sized versions of integer types typedef __signed char int8_t; typedef unsigned char uint8_t; typedef short int16_t; typedef unsigned short uint16_t; typedef int int32_t; typedef unsigned int uint32_t; typedef long long int64_t; typedef unsigned long long uint64_t; // size_t is used for memory object sizes. typedef uint32_t size_t; #endif /* TYPES_H */ <commit_after> // Explicitly-sized versions of integer types typedef __signed char int8_t; typedef unsigned char uint8_t; typedef short int16_t; typedef unsigned short uint16_t; typedef int int32_t; typedef unsigned int uint32_t; typedef long long int64_t; typedef unsigned long long uint64_t; typedef uint8_t bool; #define true 1; #define false 0; // size_t is used for memory object sizes. typedef uint32_t size_t; #endif /* TYPES_H */
<commit_msg>Add mezzo task, for copy project to mezzo <commit_before>from invoke import task import jschema @task def pip(ctx): ctx.run("rm -rf dist jschema.egg-info") ctx.run("./setup.py sdist") ctx.run("twine upload dist/jschema-{}.tar.gz".format(jschema.__version__)) @task def doc(ctx): ctx.run("./setup.py build_sphinx") ctx.run("./setup.py upload_sphinx") <commit_after>from invoke import task from invoke.util import cd import jschema @task def pip(ctx): ctx.run("rm -rf dist jschema.egg-info") ctx.run("./setup.py sdist") ctx.run("twine upload dist/jschema-{}.tar.gz".format(jschema.__version__)) @task def doc(ctx): ctx.run("./setup.py build_sphinx") ctx.run("./setup.py upload_sphinx") @task def mezzo(ctx): ctx.run("mkdir -p build/jschema") ctx.run("cp -R jschema setup.py build/jschema") with cd("build"): ctx.run("tar cf jschema.tar.gz jschema") ctx.run("mv jschema.tar.gz /opt/mezzo/dependencies") ctx.run("rm -rf jschema")
<commit_msg>Fix inability dynamically install Pipeline <commit_before>package jenkins.advancedqueue; import hudson.model.Job; import hudson.model.Queue; import jenkins.advancedqueue.sorter.ItemInfo; import jenkins.advancedqueue.sorter.QueueItemCache; import jenkins.model.Jenkins; import org.jenkinsci.plugins.workflow.support.steps.ExecutorStepExecution; class PriorityConfigurationPlaceholderTaskHelper { private static boolean placeholderTaskUsed = Jenkins.getInstance().getPlugin("workflow-durable-task-step") != null; boolean isPlaceholderTask(Queue.Task task) { return placeholderTaskUsed && task instanceof ExecutorStepExecution.PlaceholderTask; } PriorityConfigurationCallback getPriority(ExecutorStepExecution.PlaceholderTask task, PriorityConfigurationCallback priorityCallback) { Job<?, ?> job = (Job<?, ?>) task.getOwnerTask(); ItemInfo itemInfo = QueueItemCache.get().getItem(job.getName()); itemInfo.getPriority(); priorityCallback.setPrioritySelection(itemInfo.getPriority()); return priorityCallback; } static boolean isPlaceholderTaskUsed() { return placeholderTaskUsed; } } <commit_after>package jenkins.advancedqueue; import hudson.model.Job; import hudson.model.Queue; import jenkins.advancedqueue.sorter.ItemInfo; import jenkins.advancedqueue.sorter.QueueItemCache; import jenkins.model.Jenkins; import org.jenkinsci.plugins.workflow.support.steps.ExecutorStepExecution; class PriorityConfigurationPlaceholderTaskHelper { boolean isPlaceholderTask(Queue.Task task) { return isPlaceholderTaskUsed() && task instanceof ExecutorStepExecution.PlaceholderTask; } PriorityConfigurationCallback getPriority(ExecutorStepExecution.PlaceholderTask task, PriorityConfigurationCallback priorityCallback) { Job<?, ?> job = (Job<?, ?>) task.getOwnerTask(); ItemInfo itemInfo = QueueItemCache.get().getItem(job.getName()); itemInfo.getPriority(); priorityCallback.setPrioritySelection(itemInfo.getPriority()); return priorityCallback; } static boolean isPlaceholderTaskUsed() { return Jenkins.getInstance().getPlugin("workflow-durable-task-step") != null; } }
<commit_msg>engine: Modify excepted exception to match impl The patch modifies the expected exception to the correct package so test could pass successfully. Change-Id: I016ced1da2d86e27497149fac82fea832ce01a1e Signed-off-by: Moti Asayag <da1debb83a8e12b6e8822edf2c275f55cc51b720@redhat.com> <commit_before>package org.ovirt.engine.core.dao; import static org.mockito.Mockito.mock; import org.junit.Before; import org.junit.Test; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.NotImplementedException; /** * A sparse test case for {@link NetworkDAOHibernateImpl} * intended to fail once we start implementing actual methods */ public class NetworkDAOHibernateImplTest { /** The DAO to test */ private NetworkDAOHibernateImpl dao; @Before public void setUp() { dao = new NetworkDAOHibernateImpl(); } @Test(expected = NotImplementedException.class) public void testUnimplementedMethods() { dao.getAllForCluster(mock(Guid.class), mock(Guid.class), true); } } <commit_after>package org.ovirt.engine.core.dao; import static org.mockito.Mockito.mock; import org.apache.commons.lang.NotImplementedException; import org.junit.Before; import org.junit.Test; import org.ovirt.engine.core.compat.Guid; /** * A sparse test case for {@link NetworkDAOHibernateImpl} * intended to fail once we start implementing actual methods */ public class NetworkDAOHibernateImplTest { /** The DAO to test */ private NetworkDAOHibernateImpl dao; @Before public void setUp() { dao = new NetworkDAOHibernateImpl(); } @Test(expected = NotImplementedException.class) public void testUnimplementedMethods() { dao.getAllForCluster(mock(Guid.class), mock(Guid.class), true); } }
<commit_msg>Fix my fix for the BlockBreak event changes (reverted).<commit_before>package com.gmail.nossr50.events.fake; import java.util.ArrayList; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.inventory.ItemStack; public class FakeBlockBreakEvent extends BlockBreakEvent { public FakeBlockBreakEvent(Block theBlock, Player player) { super(theBlock, player, new ArrayList<ItemStack>(theBlock.getDrops())); } }<commit_after>package com.gmail.nossr50.events.fake; //import java.util.ArrayList; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.block.BlockBreakEvent; //import org.bukkit.inventory.ItemStack; public class FakeBlockBreakEvent extends BlockBreakEvent { public FakeBlockBreakEvent(Block theBlock, Player player) { super(theBlock, player); } // public FakeBlockBreakEvent(Block theBlock, Player player) { // super(theBlock, player, new ArrayList<ItemStack>(theBlock.getDrops())); // } }
<commit_msg>Test left and right method, almost identical to get test <commit_before>"""Test heap.""" data = [1, 2, 3, 4] def heap_init(): """Test heap init.""" from heap import Heap assert isinstance(Heap() == Heap) def test_push(): """Test push method.""" from heap import Heap high_low = Heap() high_low.push(data[0]) high_low.push(data[1]) assert high_low.high_low[1] == data[1] def test_get_parent(): """Test parent method.""" from heap import Heap high_low = Heap() high_low.high_low.append(data[0]) high_low.high_low.append(data[1]) high_low.high_low.append(data[2]) assert high_low.high_low[high_low.get_parent(1)] == data[0] assert high_low.high_low[high_low.get_parent(2)] == data[0] <commit_after>"""Test heap.""" data = [1, 2, 3, 4] def heap_init(): """Test heap init.""" from heap import Heap assert isinstance(Heap() == Heap) def test_push(): """Test push method.""" from heap import Heap high_low = Heap() high_low.push(data[0]) high_low.push(data[1]) assert high_low.high_low[1] == data[1] def test_get_parent(): """Test parent method.""" from heap import Heap high_low = Heap() high_low.high_low.append(data[0]) high_low.high_low.append(data[1]) high_low.high_low.append(data[2]) assert high_low.high_low[high_low.get_parent(1)] == data[0] assert high_low.high_low[high_low.get_parent(2)] == data[0] def test_get_left(): """Test left method.""" from heap import Heap high_low = Heap() high_low.push(data[0]) high_low.push(data[1]) high_low.push(data[2]) assert high_low.high_low[high_low.get_left(0)] == data[1] def test_get_right(): """Test left method.""" from heap import Heap high_low = Heap() high_low.push(data[0]) high_low.push(data[1]) high_low.push(data[2]) assert high_low.high_low[high_low.get_right(0)] == data[2]
<commit_msg>Use exception handling with decorator <commit_before>''' ''' import functools import operator from .. import monads def view(func, **constraints): '''Functions that decorates a view. This function can also checks the argument values ''' func.is_view = True @functools.wraps(func) def wrapper(*args, **kwargs): try: if not functools.reduce(operator.__and__, [constraints[arg](kwargs[arg]) for arg in constraints]): return monads.NoneMonad(ValueError( 'Wrong view argument value')) return monads.ValueMonad(func(*args, **kwargs)) except Exception as e: return monads.NoneMonad(e) return wrapper <commit_after>''' ''' import functools import operator from .. import monads def view(func, **constraints): '''Functions that decorates a view. This function can also checks the argument values ''' func.is_view = True @functools.wraps(func) @monads.handle_exception def wrapper(*args, **kwargs): if not functools.reduce(operator.__and__, [constraints[arg](kwargs[arg]) for arg in constraints]): return monads.NoneMonad(ValueError('Wrong view argument value')) return monads.ValueMonad(func(*args, **kwargs)) return wrapper
<commit_msg>Update the zebra launcher to use chpl_launch_using_exec() as implemented in r18010. git-svn-id: 88467cb1fb04b8a755be7e1ee1026be4190196ef@18032 3a8e244f-b0f2-452b-bcba-4c88e055c3ca <commit_before> static char* chpl_launch_create_command(int argc, char* argv[], int32_t numLocales) { int i; int size; char baseCommand[256]; char* command; chpl_compute_real_binary_name(argv[0]); sprintf(baseCommand, "zebra -fast -r %s", chpl_get_real_binary_name()); size = strlen(baseCommand) + 1; for (i=1; i<argc; i++) { size += strlen(argv[i]) + 3; } command = chpl_malloc(size, sizeof(char), CHPL_RT_MD_COMMAND_BUFFER, -1, ""); sprintf(command, "%s", baseCommand); for (i=1; i<argc; i++) { strcat(command, " '"); strcat(command, argv[i]); strcat(command, "'"); } if (strlen(command)+1 > size) { chpl_internal_error("buffer overflow"); } return command; } int chpl_launch(int argc, char* argv[], int32_t numLocales) { return chpl_launch_using_system(chpl_launch_create_command(argc, argv, numLocales), argv[0]); } int chpl_launch_handle_arg(int argc, char* argv[], int argNum, int32_t lineno, chpl_string filename) { return 0; } void chpl_launch_print_help(void) { } <commit_after> static char** chpl_launch_create_argv(int argc, char* argv[]) { const int largc = 3; char *largv[largc]; largv[0] = (char *) "zebra"; largv[1] = (char *) "-fast"; largv[2] = (char *) "-r"; return chpl_bundle_exec_args(argc, argv, largc, largv); } int chpl_launch(int argc, char* argv[], int32_t numLocales) { if (numLocales != 1) { // This error should be taken care of before we get to this point chpl_internal_error("The XMT launcher only supports numLocales==1"); } return chpl_launch_using_exec("zebra", chpl_launch_create_argv(argc, argv), argv[0]); } int chpl_launch_handle_arg(int argc, char* argv[], int argNum, int32_t lineno, chpl_string filename) { return 0; } void chpl_launch_print_help(void) { }
<commit_msg>Check possible exception with wrong key data <commit_before>import os from django.forms import Form from django.test import TestCase from snowpenguin.django.recaptcha2.fields import ReCaptchaField from snowpenguin.django.recaptcha2.widgets import ReCaptchaWidget class RecaptchaTestForm(Form): recaptcha = ReCaptchaField(widget=ReCaptchaWidget()) class TestRecaptchaForm(TestCase): def setUp(self): os.environ['RECAPTCHA_DISABLE'] = 'True' def test_dummy_validation(self): form = RecaptchaTestForm({}) self.assertTrue(form.is_valid()) def tearDown(self): del os.environ['RECAPTCHA_DISABLE'] <commit_after>import os from django.forms import Form from django.test import TestCase from snowpenguin.django.recaptcha2.fields import ReCaptchaField from snowpenguin.django.recaptcha2.widgets import ReCaptchaWidget class RecaptchaTestForm(Form): recaptcha = ReCaptchaField(widget=ReCaptchaWidget()) class TestRecaptchaForm(TestCase): def setUp(self): os.environ['RECAPTCHA_DISABLE'] = 'True' def test_dummy_validation(self): form = RecaptchaTestForm({}) self.assertTrue(form.is_valid()) def test_dummy_error(self): del os.environ['RECAPTCHA_DISABLE'] form = RecaptchaTestForm({}) self.assertFalse(form.is_valid()) def tearDown(self): del os.environ['RECAPTCHA_DISABLE']
<commit_msg>Adjust output when user enters 'ans' <commit_before> int main() { std::string input_line; double ans = 0; std::cout << "miniMAT: It's like MATLAB, but smaller." << std::endl; std::cout << "Copyright (C) 2014 Federico Menozzi" << std::endl; std::cout << std::endl; while (true) { std::cout << ">>> "; std::getline(std::cin, input_line); if (input_line == "quit" || input_line == "exit") break; else if (input_line == "ans") { std::cout << "ans = " << ans << std::endl; continue; } else if (input_line == "") continue; if (std::cin.eof()) { std::cout << std::endl; break; } auto reporter = std::make_shared<miniMAT::reporter::ErrorReporter>(); miniMAT::lexer::Lexer lexer(input_line, reporter); miniMAT::parser::Parser parser(lexer, reporter); auto ast = parser.Parse(); if (reporter->HasErrors()) reporter->ReportErrors(); else { ans = ast->VisitEvaluate(); std::cout << "ans = " << std::endl << std::endl; std::cout << " " << ans << std::endl << std::endl; } } return 0; } <commit_after> int main() { std::string input_line; double ans = 0; std::cout << "miniMAT: It's like MATLAB, but smaller." << std::endl; std::cout << "Copyright (C) 2014 Federico Menozzi" << std::endl; std::cout << std::endl; while (true) { std::cout << ">>> "; std::getline(std::cin, input_line); if (input_line == "quit" || input_line == "exit") break; else if (input_line == "ans") { std::cout << "ans = " << std::endl << std::endl; std::cout << " " << ans << std::endl << std::endl; continue; } else if (input_line == "") continue; if (std::cin.eof()) { std::cout << std::endl; break; } auto reporter = std::make_shared<miniMAT::reporter::ErrorReporter>(); miniMAT::lexer::Lexer lexer(input_line, reporter); miniMAT::parser::Parser parser(lexer, reporter); auto ast = parser.Parse(); if (reporter->HasErrors()) reporter->ReportErrors(); else { ans = ast->VisitEvaluate(); std::cout << "ans = " << std::endl << std::endl; std::cout << " " << ans << std::endl << std::endl; } } return 0; }
<commit_msg>Add alias to TelePythClient which will be deprecated in the future. <commit_before> from telepyth.client import TelePythClient from telepyth.utils import is_interactive if is_interactive(): from telepyth.magics import TelePythMagics <commit_after> from telepyth.client import TelePythClient from telepyth.utils import is_interactive TelepythClient = TelePythClient # make alias to origin definition if is_interactive(): from telepyth.magics import TelePythMagics
<commit_msg>Fix internal references to bad_style in test code. <commit_before>// Copyright 2014–2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![deny(nonstandard_style)] #![allow(dead_code)] fn CamelCase() {} //~ ERROR should have a snake #[allow(bad_style)] mod test { fn CamelCase() {} #[forbid(bad_style)] mod bad { fn CamelCase() {} //~ ERROR should have a snake static bad: isize = 1; //~ ERROR should have an upper } mod warn { #![warn(bad_style)] fn CamelCase() {} //~ WARN should have a snake struct snake_case; //~ WARN should have a camel } } fn main() {} <commit_after>// Copyright 2014–2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![deny(nonstandard_style)] #![allow(dead_code)] fn CamelCase() {} //~ ERROR should have a snake #[allow(nonstandard_style)] mod test { fn CamelCase() {} #[forbid(nonstandard_style)] mod bad { fn CamelCase() {} //~ ERROR should have a snake static bad: isize = 1; //~ ERROR should have an upper } mod warn { #![warn(nonstandard_style)] fn CamelCase() {} //~ WARN should have a snake struct snake_case; //~ WARN should have a camel } } fn main() {}
<commit_msg>Add console input approximation point <commit_before>package main; import approximation.Lagrange; /** * Main class * @author Pavel_Verkhovtsov */ public class Main { private static double[] y = {2.02, 1.98, 1.67, 1.65, 1.57, 1.42, 1.37, 1.07, 0.85, 0.48, 0.35, -0.30, -0.61, -1.2, -1.39, -1.76, -2.28, -2.81, -3.57, -4.06}; private static double[] x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; /** * Main method. * @param args console parameters */ public static void main(final String[] args){ Lagrange lagrange = new Lagrange(x, y); System.out.println(lagrange.approximazeFunction(2)); } } <commit_after>package main; import java.util.Scanner; import approximation.Lagrange; /** * Main class * @author Pavel_Verkhovtsov */ public class Main { private static double[] y = {2.02, 1.98, 1.67, 1.65, 1.57, 1.42, 1.37, 1.07, 0.85, 0.48, 0.35, -0.30, -0.61, -1.2, -1.39, -1.76, -2.28, -2.81, -3.57, -4.06}; private static double[] x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; /** * Main method. * @param args console parameters */ @SuppressWarnings("resource") public static void main(final String[] args){ Lagrange lagrange = new Lagrange(x, y); System.out.print("Input approximation point: "); double point = new Scanner(System.in).nextDouble(); System.out.println(lagrange.approximazeFunction(point)); } }
<commit_msg>Update cmd to allow args Change the cmd string so that the "args" argument can be used in linter settings. The way it was any args would be inserted between the '-file' and the filename which broke the '-file' argument. For this config, "cflint": { "@disable": false, "args": ['-configfile c:\cflintrc.xml'], "excludes": [] } The results are: old: cflint -q -text -file -configfile c:\cflintrc.xml index.cfm new: cflint -file index.cfm -q -text -configfile c:\cflintrc.xml<commit_before> """This module exports the CFLint plugin class.""" from SublimeLinter.lint import Linter, util class CFLint(Linter): """Provides an interface to CFLint.""" syntax = ('coldfusioncfc', 'html+cfml') cmd = 'cflint -q -text -file' version_args = '-version' version_re = r'\b(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.1.8' regex = r'''(?xi) # The severity ^\s*Severity:(?:(?P<warning>(INFO|WARNING))|(?P<error>ERROR))\s*$\r?\n # The file name ^.*$\r?\n # The Message Code ^.*$\r?\n # The Column number ^\s*Column:(?P<col>\d+)\s*$\r?\n # The Line number ^\s*Line:(?P<line>\d+)\s*$\r?\n # The Error Message ^\s*Message:(?P<message>.+)$\r?\n ''' multiline = True error_stream = util.STREAM_STDOUT word_re = r'^<?(#?[-\w]+)' tempfile_suffix = '-' <commit_after> """This module exports the CFLint plugin class.""" from SublimeLinter.lint import Linter, util class CFLint(Linter): """Provides an interface to CFLint.""" syntax = ('coldfusioncfc', 'html+cfml') cmd = 'cflint -file @ -q -text' version_args = '-version' version_re = r'\b(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.1.8' regex = r'''(?xi) # The severity ^\s*Severity:(?:(?P<warning>(INFO|WARNING))|(?P<error>ERROR))\s*$\r?\n # The file name ^.*$\r?\n # The Message Code ^.*$\r?\n # The Column number ^\s*Column:(?P<col>\d+)\s*$\r?\n # The Line number ^\s*Line:(?P<line>\d+)\s*$\r?\n # The Error Message ^\s*Message:(?P<message>.+)$\r?\n ''' multiline = True error_stream = util.STREAM_STDOUT word_re = r'^<?(#?[-\w]+)' tempfile_suffix = '-'
<commit_msg>Create class for the reflectors <commit_before>import string class Steckerbrett: def __init__(self): pass class Walzen: def __init__(self): pass class Enigma: def __init__(self): pass def cipher(self, message): pass<commit_after>import string class Steckerbrett: def __init__(self): pass class Umkehrwalze: def __init__(self, wiring): self.wiring = wiring def encode(self, letter): return self.wiring[string.ascii_uppercase.index(letter)] class Walzen: def __init__(self): pass class Enigma: def __init__(self): pass def cipher(self, message): pass
<commit_msg>Update runtime app model parsing <commit_before>import { RuntimeAppInstance } from './runtime-app-instance'; import { Page } from '../../shared/model'; /** * Runtime application model that corresponds to AppStatusResource from SCDF server. * * @author Ilayaperumal Gopinathan */ export class RuntimeApp { public deploymentId: string; public state: string; public instances: any; public appInstances: any; constructor(deploymentId: string, state: string, instances: any, appInstances: RuntimeAppInstance[]) { this.deploymentId = deploymentId; this.state = state; this.instances = instances; this.appInstances = appInstances; } public static fromJSON(input): RuntimeApp { let instances = []; if (input.instances._embedded.appInstanceStatusResourceList) { instances = input.instances._embedded.appInstanceStatusResourceList; } return new RuntimeApp(input.deploymentId, input.state, input.instances, instances); } public static pageFromJSON(input): Page<RuntimeApp> { const page = Page.fromJSON<RuntimeApp>(input); if (input && input._embedded && input._embedded.appStatusResourceList) { page.items = input._embedded.appStatusResourceList.map((item) => { if (!!item.instances._embedded && !!item.instances._embedded.appInstanceStatusResourceList) { item.appInstances = item.instances._embedded.appInstanceStatusResourceList; } else { item.appInstances = []; } return item; }); } return page; } } <commit_after>import { RuntimeAppInstance } from './runtime-app-instance'; import { Page } from '../../shared/model'; /** * Runtime application model that corresponds to AppStatusResource from SCDF server. * * @author Ilayaperumal Gopinathan */ export class RuntimeApp { public deploymentId: string; public state: string; public instances: any; public appInstances: any; constructor(deploymentId: string, state: string, instances: any, appInstances: RuntimeAppInstance[]) { this.deploymentId = deploymentId; this.state = state; this.instances = instances; this.appInstances = appInstances; } public static fromJSON(input): RuntimeApp { let instances = []; if (!!input.instances && !!input.instances._embedded && !!input.instances._embedded.appInstanceStatusResourceList) { instances = input.instances._embedded.appInstanceStatusResourceList; } return new RuntimeApp(input.deploymentId, input.state, input.instances, instances); } public static pageFromJSON(input): Page<RuntimeApp> { const page = Page.fromJSON<RuntimeApp>(input); if (input && input._embedded && input._embedded.appStatusResourceList) { page.items = input._embedded.appStatusResourceList.map((item) => { if (!!item.instances && !!item.instances._embedded && !!item.instances._embedded.appInstanceStatusResourceList) { item.appInstances = item.instances._embedded.appInstanceStatusResourceList; } else { item.appInstances = []; } return item; }); } return page; } }
<commit_msg>Add function for creating a datetime aware object <commit_before>from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone()) def datetime_midnight_date(date_obj): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return datetime_midnight(date_obj.year, date_obj.month, date_obj.day) def datetime_midnight_today(): """ Returns today at midnight as a timezone aware datetime object, using the current timezone. """ today = date.today() return datetime_midnight(today.year, today.month, today.day) <commit_after>from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone()) def datetime_midnight_date(date_obj): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return datetime_midnight(date_obj.year, date_obj.month, date_obj.day) def datetime_midnight_today(): """ Returns today at midnight as a timezone aware datetime object, using the current timezone. """ today = date.today() return datetime_midnight(today.year, today.month, today.day) def datetime_aware(year, month, day, hour, minute, second): """ Return a datetime aware object with current local timezone. """ _datetime = datetime(year, month, day, hour, minute, second) return timezone.make_aware(_datetime, timezone.get_current_timezone())
<commit_msg>utils: Implement functions to work with atoms <commit_before>module Utils ( listOfAtoms ) where import Logic listOfAtoms :: (Formula a)-> [a] listOfAtoms formula = overAtoms (\x y -> x:y) formula [] <commit_after>module Utils ( atoms , atomUnion ) where import Data.List import Logic -- Get list of atoms atoms formula = atomUnion (\atom -> [atom]) formula -- Collect atoms by some attribute set by function atomUnion function formula = overAtoms (\p q -> function p `union` q) formula []
<commit_msg>Update to the latest way to offer metadata <commit_before>from ._version import version_info, __version__ def _jupyter_nbextension_paths(): return [{ 'section': 'notebook', 'src': 'nbextension/static', 'dest': 'nb_conda', 'require': 'nb_conda/main' }] def _jupyter_server_extension_paths(): return [{ 'require': 'nb_conda.nbextension' }] <commit_after>from ._version import version_info, __version__ def _jupyter_nbextension_paths(): return [dict(section="notebook", src="nbextension/static", dest="nb_conda", require="nb_conda/main")] def _jupyter_server_extension_paths(): return [dict(module='nb_conda.nbextension')]
<commit_msg>Add descriptions of the CC's <commit_before>/* * registers.h */ #ifndef REGISTERS_H #define REGISTERS_H #define REGSIZE 8 /* number of registers */ /* Program Registers */ #define EAX 0x0 #define ECX 0x1 #define EDX 0x2 #define EBX 0x3 #define ESP 0x4 #define EBP 0x5 #define ESI 0x6 #define EDI 0x7 #define RNONE 0xf /* i.e. - no register needed */ /* Condition Codes (CC) */ #define ZF 0x2 /* zero flag - bit 2 of the CC */ #define SF 0x1 /* sign flag - bit 1 of the CC */ #define OF 0x0 /* overflow flag - bit 0 of the CC */ void clearCC(void); void clearRegisters(void); unsigned int getCC(unsigned int bitNumber); unsigned int getRegister(int regNum); void setCC(unsigned int bitNumber, unsigned int value); void setRegister(int regNum, unsigned int regValue); #endif /* REGISTERS_H */ <commit_after>/* * registers.h */ #ifndef REGISTERS_H #define REGISTERS_H #define REGSIZE 8 /* number of registers */ /* Program Registers */ #define EAX 0x0 #define ECX 0x1 #define EDX 0x2 #define EBX 0x3 #define ESP 0x4 #define EBP 0x5 #define ESI 0x6 #define EDI 0x7 #define RNONE 0xf /* i.e. - no register needed */ /* Condition Codes (CC) */ /* * Set with each arithmetic/logical operation (OPL). * ZF: was the result 0? * SF: was the result < 0? * OF: did the result overflow? (2's complement) */ #define ZF 0x2 /* zero flag - bit 2 of the CC */ #define SF 0x1 /* sign flag - bit 1 of the CC */ #define OF 0x0 /* overflow flag - bit 0 of the CC */ void clearCC(void); void clearRegisters(void); unsigned int getCC(unsigned int bitNumber); unsigned int getRegister(int regNum); void setCC(unsigned int bitNumber, unsigned int value); void setRegister(int regNum, unsigned int regValue); #endif /* REGISTERS_H */
<commit_msg>Add warning for skipped tests if pytest not available <commit_before>from __future__ import division import libtbx.load_env def discover_pytests(module): try: import os import pytest except ImportError: return [] if 'LIBTBX_SKIP_PYTEST' in os.environ: return [] test_list = [] dist_dir = libtbx.env.dist_path(module) class TestDiscoveryPlugin: def pytest_itemcollected(self, item): test_list.append([ "libtbx.python", "-m", "pytest", '--noconftest', os.path.join(dist_dir, item.nodeid) ]) print "Discovering pytest tests:" pytest.main(['-qq', '--collect-only', '--noconftest', dist_dir], plugins=[TestDiscoveryPlugin()]) return test_list if (__name__ == "__main__"): import unittest test_suite = unittest.defaultTestLoader.discover(libtbx.env.dist_path("i19"), pattern="tst_*.py") result = unittest.TextTestRunner().run(test_suite) import sys sys.exit(0 if result.wasSuccessful() else 1) tst_list = [ # "$D/tests/tst_legacy.py", ["$D/tests/tst_legacy_mult.py", "1"] # ["$D/tests/tst_legacy_mult.py", "2"] ] + discover_pytests("i19") <commit_after>from __future__ import division import libtbx.load_env def discover_pytests(module): try: import os import pytest except ImportError: def pytest_warning(): print "=" * 60 print "WARNING: Skipping some tests\n" print "To run all available tests you need to install pytest" print "eg. with libtbx.python -m pip install pytest" print "=" * 60 pytest_warning() import atexit atexit.register(pytest_warning) return [] if 'LIBTBX_SKIP_PYTEST' in os.environ: return [] test_list = [] dist_dir = libtbx.env.dist_path(module) class TestDiscoveryPlugin: def pytest_itemcollected(self, item): test_list.append([ "libtbx.python", "-m", "pytest", '--noconftest', os.path.join(dist_dir, item.nodeid) ]) print "Discovering pytest tests:" pytest.main(['-qq', '--collect-only', '--noconftest', dist_dir], plugins=[TestDiscoveryPlugin()]) return test_list if (__name__ == "__main__"): import unittest test_suite = unittest.defaultTestLoader.discover(libtbx.env.dist_path("i19"), pattern="tst_*.py") result = unittest.TextTestRunner().run(test_suite) import sys sys.exit(0 if result.wasSuccessful() else 1) tst_list = [ # "$D/tests/tst_legacy.py", ["$D/tests/tst_legacy_mult.py", "1"] # ["$D/tests/tst_legacy_mult.py", "2"] ] + discover_pytests("i19")
<commit_msg>Make isolated arg check example <commit_before>from __future__ import print_function @check.arg(0, check.int_value(min=0)) @check.arg(1, check.int_value(min=0)) def add_positive_integers(int1, int2): return int1 + int2 def main(): print(add_positive_integers(1, 5)) print(add_positive_integers(0, 5)) print(add_positive_integers(-1, 5)) if __name__ == '__main__': main() <commit_after>from __future__ import print_function from collections import defaultdict def check_arg(arg_id, *constraints): return ArgCheckAdder(arg_id, *constraints) def check_int_value(min=None, max=None): def constraint(arg_id, args, kwargs): assert isinstance(args[arg_id], int) assert args[arg_id] >= 0 return constraint class ArgCheckAdder(object): def __init__(self, arg_id, *constraints): self.arg_id = arg_id self.constraints = constraints def __call__(self, func): if hasattr(func, 'checks'): func.checks[self.arg_id].extend(self.constraints) return func else: return CheckedFunction(func, {self.arg_id: self.constraints}) class CheckedFunction(object): def __init__(self, func, checks): self.checks = defaultdict(list) self.checks.update(checks) self.func = func def __call__(self, *args, **kwargs): for arg_id, checks in self.checks.items(): for check in checks: check(arg_id, args, kwargs) self.func(*args, **kwargs) @check_arg(0, check_int_value(min=0)) @check_arg(1, check_int_value(min=0)) def add_positive_integers(int1, int2): return int1 + int2 def main(): print(add_positive_integers(1, 5)) print(add_positive_integers(0, 5)) print(add_positive_integers(-1, 5)) if __name__ == '__main__': main()
<commit_msg>Handle signals with default interface <commit_before>from .gobject import GObject from . import signals class Game(GObject): def __init__(self): self.maps = {} self.player = None def run(self): pass def handle_signals(self): signals.handle_signals(self) @staticmethod def reg_signal(*args): signals.reg_signal(*args) @staticmethod def have_signals(): return signals.have_signals() <commit_after>from .gobject import GObject from . import signals import time class Game(GObject): def __init__(self): self.maps = {} self.player = None def run(self): while True: self.handle_signals() time.sleep(0.3) def handle_signals(self): signals.handle_signals(self) @staticmethod def reg_signal(*args): signals.reg_signal(*args) @staticmethod def have_signals(): return signals.have_signals()
<commit_msg>Update test to reflect new method name. <commit_before>from context import slot_users_controller as uc class TestUsers: def test_validate_credentials_returns_true_for_valid_credentials(self): result = uc.return_user_if_valid_credentials('slot', 'test') assert result is True def test_validate_credentials_returns_false_for_invalid_credentials(self): result = uc.return_user_if_valid_credentials('bad_username', 'bad_password') assert result is False def test_convert_dict_to_user_instance_returns_valid_user_instance(self): result = uc.convert_dict_to_user_instance({}) assert result<commit_after>from context import slot_users_controller as uc class TestUsers: def test_validate_credentials_returns_true_for_valid_credentials(self): result = uc.return_user_if_valid_credentials('slot', 'test') assert result is True def test_validate_credentials_returns_false_for_invalid_credentials(self): result = uc.return_user_if_valid_credentials('bad_username', 'bad_password') assert result is False def test_convert_dict_to_user_instance_returns_valid_user_instance(self): result = uc.return_user_instance_or_anonymous({}) assert result
<commit_msg>Remove username and password from repository <commit_before>from django.db import models import mongoengine from mongoengine import Document, EmbeddedDocument from mongoengine.fields import * # Create your models here. class Greeting(models.Model): when = models.DateTimeField('date created', auto_now_add=True) MONGODB_URI = 'mongodb+srv://fikaadmin:ZJ6TtyTZMXA@fikanotedb.ltkpy.mongodb.net/fikanotedb?retryWrites=true&w=majority' mongoengine.connect('fikanotedb', host=MONGODB_URI) class Shownote(EmbeddedDocument): url = URLField() title = StringField() date = DateTimeField() class FikanoteDB(Document): title = StringField() number = IntField() person = ListField(StringField()) agenda = StringField() date = DateTimeField() shownotes = ListField(EmbeddedDocumentField(Shownote)) meta = {'collection': 'fikanotedb'} class AgendaDB(Document): url = URLField() title = StringField() date = DateTimeField() meta = {'collection': 'agendadb'} <commit_after>from django.db import models import mongoengine from mongoengine import Document, EmbeddedDocument from mongoengine.fields import * import os # Create your models here. class Greeting(models.Model): when = models.DateTimeField('date created', auto_now_add=True) USER = os.getenv('DATABASE_USER') PASWORD = os.getenv('DATABASE_PASSWORD') MONGODB_URI = "mongodb+srv://{}:{}@fikanotedb.ltkpy.mongodb.net/fikanotedb?retryWrites=true&w=majority".format(USER, PASWORD) mongoengine.connect('fikanotedb', host=MONGODB_URI) class Shownote(EmbeddedDocument): url = URLField() title = StringField() date = DateTimeField() class FikanoteDB(Document): title = StringField() number = IntField() person = ListField(StringField()) agenda = StringField() date = DateTimeField() shownotes = ListField(EmbeddedDocumentField(Shownote)) meta = {'collection': 'fikanotedb'} class AgendaDB(Document): url = URLField() title = StringField() date = DateTimeField() meta = {'collection': 'agendadb'}
<commit_msg>Add some mock types with monad transformer and reader for testing <commit_before>{-# LANGUAGE OverloadedStrings #-} module Ecumenical ( retrieve , put ) where import Prelude hiding (readFile, writeFile) import Data.ByteString.Char8 import Control.Exception import Control.Monad.Reader -- Get a value from the store by key, if it exists. retrieve :: ByteString -> IO (Maybe ByteString) retrieve key = do value <- fileContents $ dataPath key return value put :: ByteString -> ByteString -> IO () put key value = do writeFile (dataPath key) value return () fileContents :: FilePath -> IO (Maybe ByteString) fileContents path = do contents <- (try $ readFile path) :: IO (Either IOException ByteString) case contents of Left _ -> return Nothing Right text -> return $ Just text dataPath :: ByteString -> FilePath dataPath key = "data/" ++ (unpack key) <commit_after>{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Ecumenical ( retrieve , put ) where import Prelude hiding (readFile, writeFile) import Data.ByteString.Char8 import Control.Exception import Control.Monad.Reader import Control.Monad.Trans newtype MockDB m a = MockDB { db :: ReaderT (Maybe ByteString) m a } deriving (Applicative, Functor, Monad, MonadTrans) class Monad m => MonadDB m where get :: ByteString -> m (Maybe ByteString) instance MonadDB IO where get = retrieve instance Monad m => MonadDB (MockDB m) where get _ = return $ Just "foo" -- Get a value from the store by key, if it exists. retrieve :: ByteString -> IO (Maybe ByteString) retrieve key = do value <- fileContents $ dataPath key return value put :: ByteString -> ByteString -> IO () put key value = do writeFile (dataPath key) value return () fileContents :: FilePath -> IO (Maybe ByteString) fileContents path = do contents <- (try $ readFile path) :: IO (Either IOException ByteString) case contents of Left _ -> return Nothing Right text -> return $ Just text dataPath :: ByteString -> FilePath dataPath key = "data/" ++ (unpack key)
<commit_msg>Add support for NotoSans and Arimo.<commit_before> from os import path tachyfont_major_version = 1 tachyfont_minor_version = 0 BASE_DIR = path.dirname(__file__) def fontname_to_zipfile(fontname): family_dir = '' if fontname[0:10] == 'NotoSansJP': family_dir = 'NotoSansJP/' zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar' return zip_path <commit_after> from os import path tachyfont_major_version = 1 tachyfont_minor_version = 0 BASE_DIR = path.dirname(__file__) def fontname_to_zipfile(fontname): family_dir = '' if fontname[0:10] == 'NotoSansJP': family_dir = 'NotoSansJP/' elif fontname[0:8] == 'NotoSans': family_dir = 'NotoSans/' elif fontname[0:5] == 'Arimo': family_dir = 'Arimo/' zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar' return zip_path
<commit_msg>Update script file for the season <commit_before>from main import initiate_shame # Testing this initiate_shame(1141922, 2016) <commit_after>from main import initiate_shame initiate_shame(1141922, 2017) initiate_shame(144768, 2017)
<commit_msg>Add replace double quotation mark from configuration file parameters. <commit_before>import configparser from blo.BloArticle import BloArticle from blo.DBControl import DBControl class Blo: def __init__(self, config_file_path): config = configparser.ConfigParser() config.read(config_file_path) self._db_file_path = config['DB']['DB_PATH'] self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'] self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'] # create tables self._db_control = DBControl(self._db_file_path) self._db_control.create_tables() self._db_control.close_connect() def insert_article(self, file_path): self._db_control = DBControl(self._db_file_path) article = BloArticle(self._template_dir) article.load_from_file(file_path) self._db_control.insert_article(article, self._default_template_file) self._db_control.close_connect() <commit_after>import configparser from blo.BloArticle import BloArticle from blo.DBControl import DBControl class Blo: def __init__(self, config_file_path): config = configparser.ConfigParser() config.read(config_file_path) self._db_file_path = config['DB']['DB_PATH'].replace('"', '') self._template_dir = config['TEMPLATE']['TEMPLATE_DIR'].replace('"', '') self._default_template_file = config['TEMPLATE']['DEFAULT_TEMPLATE_FILE'].replace('"', '') # create tables self._db_control = DBControl(self._db_file_path) self._db_control.create_tables() self._db_control.close_connect() def insert_article(self, file_path): self._db_control = DBControl(self._db_file_path) article = BloArticle(self._template_dir) article.load_from_file(file_path) self._db_control.insert_article(article, self._default_template_file) self._db_control.close_connect()
<commit_msg>Remove (nonexistant) method getname on mode objects<commit_before>/******************************************************************************* * Copyright (c) 2014 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package com.codenvy.ide.editor.codemirror.client.jso; import com.google.gwt.core.client.JavaScriptObject; public class CMModeOverlay extends JavaScriptObject { protected CMModeOverlay() { } public final native String getName() /*-{ return this.name; }-*/; } <commit_after>/******************************************************************************* * Copyright (c) 2014 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package com.codenvy.ide.editor.codemirror.client.jso; import com.google.gwt.core.client.JavaScriptObject; public class CMModeOverlay extends JavaScriptObject { protected CMModeOverlay() { } }
<commit_msg>Comment out tests that fail intentionally (for testing purposes). <commit_before>package water.cookbook; import org.junit.*; import water.*; import water.fvec.*; import water.util.Log; import water.util.RemoveAllKeysTask; public class Cookbook extends TestUtil { @Before public void removeAllKeys() { Log.info("Removing all keys..."); RemoveAllKeysTask collector = new RemoveAllKeysTask(); collector.invokeOnAllNodes(); Log.info("Removed all keys."); } @Test public void testWillFail() { throw new RuntimeException("first test fails"); } // --- // Test flow-coding a filter & group-by computing e.g. mean @Test public void testBasic() { Key k = Key.make("cars.hex"); Frame fr = parseFrame(k, "smalldata/cars.csv"); //Frame fr = parseFrame(k, "../datasets/UCI/UCI-large/covtype/covtype.data"); // Call into another class so we do not need to weave anything in this class // when run as a JUnit Cookbook2.basicStatic(k, fr); } @Test public void testWillFail2() { throw new RuntimeException("3 test fails"); } } <commit_after>package water.cookbook; import org.junit.*; import water.*; import water.fvec.*; import water.util.Log; import water.util.RemoveAllKeysTask; public class Cookbook extends TestUtil { @Before public void removeAllKeys() { Log.info("Removing all keys..."); RemoveAllKeysTask collector = new RemoveAllKeysTask(); collector.invokeOnAllNodes(); Log.info("Removed all keys."); } // @Test // public void testWillFail() { // throw new RuntimeException("first test fails"); // } // --- // Test flow-coding a filter & group-by computing e.g. mean @Test public void testBasic() { Key k = Key.make("cars.hex"); Frame fr = parseFrame(k, "smalldata/cars.csv"); //Frame fr = parseFrame(k, "../datasets/UCI/UCI-large/covtype/covtype.data"); // Call into another class so we do not need to weave anything in this class // when run as a JUnit Cookbook2.basicStatic(k, fr); } // @Test // public void testWillFail2() { // throw new RuntimeException("3 test fails"); // } }
<commit_msg>Add Problem's command-line options tests <commit_before> using tcframe::BaseProblem; class MyProblem : public BaseProblem { protected: void Config() { setSlug("foo"); setTimeLimit(2); setMemoryLimit(256); } void InputFormat() { } void OutputFormat() { } }; TEST(ProblemTest, DefaultOptions) { BaseProblem* problem = new DefaultProblem(); EXPECT_EQ("problem", problem->getSlug()); EXPECT_EQ(0, problem->getTimeLimit()); EXPECT_EQ(0, problem->getMemoryLimit()); } TEST(ProblemTest, MyOptions) { BaseProblem* problem = new MyProblem(); problem->applyProblemConfiguration(); EXPECT_EQ("foo", problem->getSlug()); EXPECT_EQ(2, problem->getTimeLimit()); EXPECT_EQ(256, problem->getMemoryLimit()); } <commit_after> using tcframe::BaseProblem; class MyProblem : public BaseProblem { protected: void Config() { setSlug("foo"); setTimeLimit(2); setMemoryLimit(256); } void InputFormat() { } void OutputFormat() { } }; TEST(ProblemTest, DefaultOptions) { BaseProblem* problem = new DefaultProblem(); EXPECT_EQ("problem", problem->getSlug()); EXPECT_EQ(0, problem->getTimeLimit()); EXPECT_EQ(0, problem->getMemoryLimit()); } TEST(ProblemTest, MyOptions) { BaseProblem* problem = new MyProblem(); problem->applyProblemConfiguration(); EXPECT_EQ("foo", problem->getSlug()); EXPECT_EQ(2, problem->getTimeLimit()); EXPECT_EQ(256, problem->getMemoryLimit()); } TEST(ProblemTest, CommandLineOptions) { char* argv[] = {(char*) "<runner>", (char*)"--slug=bar", (char*)"--time-limit=3", (char*)"--memory-limit=64"}; BaseProblem* problem = new MyProblem(); problem->applyProblemConfiguration(); problem->applyProblemCommandLineOptions(4, argv); EXPECT_EQ("bar", problem->getSlug()); EXPECT_EQ(3, problem->getTimeLimit()); EXPECT_EQ(64, problem->getMemoryLimit()); } TEST(ProblemTest, CommandLineOptionsWithNos) { char* argv[] = {(char*) "<runner>", (char*)"--no-time-limit", (char*)"--no-memory-limit"}; BaseProblem* problem = new MyProblem(); problem->applyProblemConfiguration(); problem->applyProblemCommandLineOptions(3, argv); EXPECT_EQ("foo", problem->getSlug()); EXPECT_EQ(0, problem->getTimeLimit()); EXPECT_EQ(0, problem->getMemoryLimit()); }
<commit_msg>Test generating a 503 status<commit_before>package au.org.ands.vocabs.toolkit.restlet; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; /** Testing restlet. */ @Path("testing2") public class TestRestlet2 { /** getMessage. * @return the message. */ @Produces(MediaType.TEXT_PLAIN) @GET public final String getMessage() { return "Hello World! Again!"; } /** getMessage. * @return the message. */ @Produces(MediaType.APPLICATION_JSON) @GET public final String getMessageJson() { return "{\"hello\":\"Hello JSON!\"}"; } } <commit_after>package au.org.ands.vocabs.toolkit.restlet; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; /** Testing restlet. */ @Path("testing2") public class TestRestlet2 { /** getMessage. * @return the message. */ @Produces(MediaType.TEXT_PLAIN) @GET public final String getMessage() { return "Hello World! Again!"; } /** getMessage. * @return the message. */ @Produces(MediaType.APPLICATION_JSON) @GET public final String getMessageJson() { return "{\"hello\":\"Hello JSON!\"}"; } /** getException. * This shows how to return a status code 503 "service unavailable" * and also some content. * @return the message. */ @Path("except") @Produces(MediaType.TEXT_PLAIN) @GET public final Response getExcept() { return Response.status(Status.SERVICE_UNAVAILABLE). entity("Hi there").build(); } }
<commit_msg>Update clean project jobs command <commit_before>from django.core.management import BaseCommand from django.db import ProgrammingError from django.db.models import Q from projects.models import Project from runner.schedulers import notebook_scheduler, tensorboard_scheduler class Command(BaseCommand): @staticmethod def _clean(): for project in Project.objects.exclude(Q(tensorboard=None) | Q(notebook=None)): if project.has_notebook: notebook_scheduler.stop_notebook(project, update_status=False) if project.has_tensorboard: tensorboard_scheduler.stop_tensorboard(project, update_status=False) def handle(self, *args, **options): try: self._clean() except ProgrammingError: pass <commit_after>from django.core.management import BaseCommand from django.db import ProgrammingError from django.db.models import Q from projects.models import Project from runner.schedulers import notebook_scheduler, tensorboard_scheduler class Command(BaseCommand): @staticmethod def _clean(): filters = Q(tensorboard_jobs=None) | Q(notebook_jobs=None) for project in Project.objects.exclude(filters): if project.has_notebook: notebook_scheduler.stop_notebook(project, update_status=False) if project.has_tensorboard: tensorboard_scheduler.stop_tensorboard(project, update_status=False) def handle(self, *args, **options): try: self._clean() except ProgrammingError: pass
<commit_msg>Add double-quote delimiters to args.<commit_before>// Rel native launcher for Linux. #include <iostream> #include <cstdlib> #include <unistd.h> #include <libgen.h> #include <string> #include <fstream> #include <streambuf> int main(int argc, char **argv) { // Convert first argument of argv[0] (full pathspec to this executable) to path where executable is found char *dir = dirname(argv[0]); chdir(dir); // Read the ini file std::string iniFileName("lib/Rel.ini"); std::ifstream configfile(iniFileName); std::string cmd((std::istreambuf_iterator<char>(configfile)), std::istreambuf_iterator<char>()); // Empty or no ini file? if (cmd.length() == 0) { std::cerr << (std::string("Missing or Damaged .ini File: Unable to find ") + iniFileName).c_str() << std::endl; return 10; } // Include command-line args. std::string args(""); for (int i = 1; i < argc; i++) args += std::string(" ") + std::string(argv[i]); setenv("SWT_GTK3", "0", 1); return system((cmd + args).c_str()); } <commit_after>// Rel native launcher for Linux. #include <iostream> #include <cstdlib> #include <unistd.h> #include <libgen.h> #include <string> #include <fstream> #include <streambuf> int main(int argc, char **argv) { // Convert first argument of argv[0] (full pathspec to this executable) to path where executable is found char *dir = dirname(argv[0]); chdir(dir); // Read the ini file std::string iniFileName("lib/Rel.ini"); std::ifstream configfile(iniFileName); std::string cmd((std::istreambuf_iterator<char>(configfile)), std::istreambuf_iterator<char>()); // Empty or no ini file? if (cmd.length() == 0) { std::cerr << (std::string("Missing or Damaged .ini File: Unable to find ") + iniFileName).c_str() << std::endl; return 10; } // Include command-line args. std::string args(""); for (int i = 1; i < argc; i++) args += std::string(" \"") + std::string(argv[i]) + std::string("\""); setenv("SWT_GTK3", "0", 1); return system((cmd + args).c_str()); }
<commit_msg>Add officers index to contentmap <commit_before>from falmer.content.models.core import ClickThrough from .staff import StaffPage, StaffMemberSnippet from .section_content import SectionContentPage from .selection_grid import SelectionGridPage from .officer_overview import OfficerOverviewPage from .homepage import HomePage from .freshers import FreshersHomepage from .generic import KBRootPage, KBCategoryPage, AnswerPage, ReferencePage, DetailedGuidePage, DetailedGuideSectionPage from .basic import StubPage, BasicContentPage from .outlets import OutletIndexPage, OutletPage from .scheme import SchemeIndexPage, SchemePage all_pages = ( StaffPage, StaffMemberSnippet, SectionContentPage, SelectionGridPage, OfficerOverviewPage, HomePage, KBRootPage, KBCategoryPage, AnswerPage, ReferencePage, DetailedGuidePage, DetailedGuideSectionPage, StubPage, BasicContentPage, OutletIndexPage, OutletPage, SchemeIndexPage, SchemePage, FreshersHomepage, ClickThrough, ) name_to_class_map = {cls.__name__: cls for cls in all_pages} <commit_after>from falmer.content.models.core import ClickThrough from .staff import StaffPage, StaffMemberSnippet from .section_content import SectionContentPage from .selection_grid import SelectionGridPage from .officer_overview import OfficerOverviewPage, OfficersIndex from .homepage import HomePage from .freshers import FreshersHomepage from .generic import KBRootPage, KBCategoryPage, AnswerPage, ReferencePage, DetailedGuidePage, DetailedGuideSectionPage from .basic import StubPage, BasicContentPage from .outlets import OutletIndexPage, OutletPage from .scheme import SchemeIndexPage, SchemePage all_pages = ( StaffPage, StaffMemberSnippet, SectionContentPage, SelectionGridPage, OfficerOverviewPage, OfficersIndex, HomePage, KBRootPage, KBCategoryPage, AnswerPage, ReferencePage, DetailedGuidePage, DetailedGuideSectionPage, StubPage, BasicContentPage, OutletIndexPage, OutletPage, SchemeIndexPage, SchemePage, FreshersHomepage, ClickThrough, ) name_to_class_map = {cls.__name__: cls for cls in all_pages}
<commit_msg>Update warning message if numba import fails <commit_before> #-Numba-# numba_import_fail_message = "Numba import failed. Falling back to non-optimized routine."<commit_after> #-Numba-# numba_import_fail_message = ("Numba import failed. Falling back to non-optimized routines.\n" "This will reduce the overall performance of this package.\n" "To install please use the anaconda distribution.\n" "http://continuum.io/downloads")
<commit_msg>Add bold and italic helpers <commit_before> from __future__ import absolute_import from reportlab.platypus import ( Paragraph as BaseParagraph, Image as BaseImage, Spacer, ) from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet styles = getSampleStyleSheet() snormal = ParagraphStyle('normal') def Paragraph(text, style=snormal, **kw): if isinstance(style, basestring): style = styles[style] if kw: style = ParagraphStyle('style', parent=style, **kw) return BaseParagraph(text, style) def HSpacer(width): return Spacer(0, width) def Image(path, width=None, height=None, ratio=None): if width and ratio: height = width / ratio elif height and ratio: width = height * ratio return BaseImage(path, width, height) <commit_after> from __future__ import absolute_import from reportlab.platypus import ( Paragraph as BaseParagraph, Image as BaseImage, Spacer, ) from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet styles = getSampleStyleSheet() snormal = ParagraphStyle('normal') def Paragraph(text, style=snormal, **kw): if isinstance(style, basestring): style = styles[style] if kw: style = ParagraphStyle('style', parent=style, **kw) return BaseParagraph(text, style) def bold(string, *args, **kw): """ Return string as a :class:`Paragraph` in bold """ return Paragraph(u'<b>{}</b>'.format(string), *args, **kw) def italic(string, *args, **kw): """ Return string as a :class:`Paragraph` in italic """ return Paragraph(u'<i>{}</i>'.format(string), *args, **kw) def HSpacer(width): return Spacer(0, width) def Image(path, width=None, height=None, ratio=None): if width and ratio: height = width / ratio elif height and ratio: width = height * ratio return BaseImage(path, width, height)
<commit_msg>Revert "docs(demo): remove unnecessary window declaration" This reverts commit ba5e2a949b43020a58df08346834014d56d5f4b7. <commit_before>import Panzoom from '../src/panzoom' console.log('This is a demo version of Panzoom for testing.') console.log('It exposes a global (window.Panzoom) and should not be used in production.') window.Panzoom = Panzoom <commit_after>import Panzoom from '../src/panzoom' console.log('This is a demo version of Panzoom for testing.') console.log('It exposes a global (window.Panzoom) and should not be used in production.') declare global { interface Window { Panzoom: typeof Panzoom } } window.Panzoom = Panzoom
<commit_msg>Fix broken build (still v76) <commit_before>// @flow import { createApiActions, createEntityReducer, mergeEntity } from './_entity' import { crudAction, standardTypes } from './_lib' import { callApi } from 'utils/api.js' const CHARACTER = 'character' export default createEntityReducer(CHARACTER, { [crudAction(CHARACTER, 'CHANGE_TYPE').success.toString()]: mergeEntity, }) export const [ createCharacter, duplicateCharacter, fetchCharacter, fetchAllCharacters, updateCharacter, destroyCharacter, ] = createApiActions(CHARACTER) export function changeCharacterType(id: number, type: string) { const action = crudAction(CHARACTER, 'CHANGE_TYPE') return callApi({ body: JSON.stringify({ type }), endpoint: `/api/v1/characters/${id}/change_type`, types: standardTypes(CHARACTER, action), }) } <commit_after>import createCachedSelector from 're-reselect' import { ICharacter } from 'types' import { callApi } from 'utils/api.js' import { createApiActions, createEntityReducer, mergeEntity } from './_entity' import { crudAction, standardTypes } from './_lib' import { EntityState, WrappedEntityState } from './_types' const unwrapped = (state: WrappedEntityState): EntityState => state.entities.current const CHARACTER = 'character' export default createEntityReducer(CHARACTER, { [crudAction(CHARACTER, 'CHANGE_TYPE').success.toString()]: mergeEntity, }) export const [ createCharacter, duplicateCharacter, fetchCharacter, fetchAllCharacters, updateCharacter, destroyCharacter, ] = createApiActions(CHARACTER) export function changeCharacterType(id: number, type: string) { const action = crudAction(CHARACTER, 'CHANGE_TYPE') return callApi({ body: JSON.stringify({ type }), endpoint: `/api/v1/characters/${id}/change_type`, types: standardTypes(CHARACTER, action), }) } export const getSpecificCharacter = (state: WrappedEntityState, id: number) => unwrapped(state).characters[id] const getMerits = (state: WrappedEntityState) => unwrapped(state).merits export const getMeritsForCharacter = createCachedSelector( [getSpecificCharacter, getMerits], (character, merits) => character.merits.map(m => merits[m]) )((state, id) => id)
<commit_msg>Add url to user agent <commit_before>from __future__ import absolute_import __all__ = ['build_session', 'delete', 'get', 'post', 'put'] import freight import requests USER_AGENT = 'freight/{}'.format(freight.VERSION), def build_session(): session = requests.Session() session.headers.update({'User-Agent': USER_AGENT}) return session def delete(*args, **kwargs): session = build_session() return session.delete(*args, **kwargs) def get(*args, **kwargs): session = build_session() return session.get(*args, **kwargs) def post(*args, **kwargs): session = build_session() return session.post(*args, **kwargs) def put(*args, **kwargs): session = build_session() return session.put(*args, **kwargs) <commit_after>from __future__ import absolute_import __all__ = ['build_session', 'delete', 'get', 'post', 'put'] import freight import requests USER_AGENT = 'freight/{version} (https://github.com/getsentry/freight)'.format( version=freight.VERSION, ), def build_session(): session = requests.Session() session.headers.update({'User-Agent': USER_AGENT}) return session def delete(*args, **kwargs): session = build_session() return session.delete(*args, **kwargs) def get(*args, **kwargs): session = build_session() return session.get(*args, **kwargs) def post(*args, **kwargs): session = build_session() return session.post(*args, **kwargs) def put(*args, **kwargs): session = build_session() return session.put(*args, **kwargs)
<commit_msg>Add test for calling done with an argument <commit_before>/// <reference path="pg.d.ts" /> import * as pg from "pg"; var conString = "postgres://username:password@localhost/database"; // https://github.com/brianc/node-pg-types pg.types.setTypeParser(20, (val) => Number(val)); // Client pooling pg.connect(conString, (err, client, done) => { if (err) { return console.error("Error fetching client from pool", err); } client.query("SELECT $1::int AS number", ["1"], (err, result) => { done(); if (err) { return console.error("Error running query", err); } console.log(result.rows[0]["number"]); return null; }); return null; }); // Simple var client = new pg.Client(conString); client.connect((err) => { if (err) { return console.error("Could not connect to postgres", err); } client.query("SELECT NOW() AS 'theTime'", (err, result) => { if (err) { return console.error("Error running query", err); } console.log(result.rows[0]["theTime"]); client.end(); return null; }); return null; });<commit_after>/// <reference path="pg.d.ts" /> import * as pg from "pg"; var conString = "postgres://username:password@localhost/database"; // https://github.com/brianc/node-pg-types pg.types.setTypeParser(20, (val) => Number(val)); // Client pooling pg.connect(conString, (err, client, done) => { if (err) { return console.error("Error fetching client from pool", err); } client.query("SELECT $1::int AS number", ["1"], (err, result) => { if (err) { done(err); return console.error("Error running query", err); } else { done(); } console.log(result.rows[0]["number"]); return null; }); return null; }); // Simple var client = new pg.Client(conString); client.connect((err) => { if (err) { return console.error("Could not connect to postgres", err); } client.query("SELECT NOW() AS 'theTime'", (err, result) => { if (err) { return console.error("Error running query", err); } console.log(result.rows[0]["theTime"]); client.end(); return null; }); return null; });
<commit_msg>Use newer factory-boy Meta syntax for s3 <commit_before>"""Factories for the S3 addon.""" from factory import SubFactory, Sequence from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory from website.addons.s3.model import ( S3UserSettings, S3NodeSettings ) class S3AccountFactory(ExternalAccountFactory): provider = 's3' provider_id = Sequence(lambda n: 'id-{0}'.format(n)) oauth_key = Sequence(lambda n: 'key-{0}'.format(n)) oauth_secret = Sequence(lambda n:'secret-{0}'.format(n)) display_name = 'S3 Fake User' class S3UserSettingsFactory(ModularOdmFactory): FACTORY_FOR = S3UserSettings owner = SubFactory(UserFactory) class S3NodeSettingsFactory(ModularOdmFactory): FACTORY_FOR = S3NodeSettings owner = SubFactory(ProjectFactory) user_settings = SubFactory(S3UserSettingsFactory) bucket = 'mock_bucket' <commit_after>"""Factories for the S3 addon.""" from factory import SubFactory, Sequence from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory from website.addons.s3.model import ( S3UserSettings, S3NodeSettings ) class S3AccountFactory(ExternalAccountFactory): provider = 's3' provider_id = Sequence(lambda n: 'id-{0}'.format(n)) oauth_key = Sequence(lambda n: 'key-{0}'.format(n)) oauth_secret = Sequence(lambda n:'secret-{0}'.format(n)) display_name = 'S3 Fake User' class S3UserSettingsFactory(ModularOdmFactory): class Meta: model = S3UserSettings owner = SubFactory(UserFactory) class S3NodeSettingsFactory(ModularOdmFactory): class Meta: model = S3NodeSettings owner = SubFactory(ProjectFactory) user_settings = SubFactory(S3UserSettingsFactory) bucket = 'mock_bucket'