language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
1,957
2.640625
3
[]
no_license
package com.tercen.model.base; import com.tercen.base.*; import com.tercen.model.impl.*; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Collection; public class PropertyBase extends BaseObject { public String name; public String description; public PropertyBase() { super(); this.name = ""; this.description = ""; } public PropertyBase(LinkedHashMap m) { super(m); this.subKind = m.get(Vocabulary.SUBKIND) != null ? (String) m.get(Vocabulary.SUBKIND) : (String) (m.get(Vocabulary.KIND) != Vocabulary.Property_CLASS ? m.get(Vocabulary.KIND) : null); this.name = (String) m.get(Vocabulary.name_DP); this.description = (String) m.get(Vocabulary.description_DP); } public static Property createFromJson(LinkedHashMap m) { return PropertyBase.fromJson(m); } public static Property fromJson(LinkedHashMap m) { String kind = (String) m.get(Vocabulary.KIND); switch (kind) { case Vocabulary.Property_CLASS: return new Property(m); case Vocabulary.EnumeratedProperty_CLASS: return new EnumeratedProperty(m); case Vocabulary.FactorsProperty_CLASS: return new FactorsProperty(m); case Vocabulary.FormulaProperty_CLASS: return new FormulaProperty(m); case Vocabulary.DoubleProperty_CLASS: return new DoubleProperty(m); case Vocabulary.StringProperty_CLASS: return new StringProperty(m); case Vocabulary.BooleanProperty_CLASS: return new BooleanProperty(m); default: throw new IllegalArgumentException("bad kind : " + kind + " for class Property in fromJson constructor"); } } public LinkedHashMap toJson() { LinkedHashMap m = super.toJson(); m.put(Vocabulary.KIND, Vocabulary.Property_CLASS); if (this.subKind != null && this.subKind != Vocabulary.Property_CLASS) m.put(Vocabulary.SUBKIND, this.subKind); else m.remove(Vocabulary.SUBKIND); m.put(Vocabulary.name_DP, name); m.put(Vocabulary.description_DP, description); return m; } }
Python
UTF-8
4,714
3.484375
3
[]
no_license
import numpy as np from random import * import pandas as pd import pygame from pygame.locals import * class Labyrinth: """Géneration aléatoire de ligne pour construire chaque ligne d'un tableau'.""" ##lign = [0] ##for i in range(14): ##i = lign.append(randint(0,1)) """0 définit un sol et 1 définit un mur. Modification accessibilité chemin à la main, en remplaçant certains murs par des sols. Départ supposé en bas à gauche et arrivée en haut à droite""" tab = [ [0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0], [0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1], [0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1], [0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0], [0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0], [0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], ] def show_lab(self): # chargement des images floor = pygame.image.load("floor.png") wall = pygame.image.load("wall.png") # # On parcourt la liste du niveau num_lign = 0 for lign in self.tab: # On parcourt les listes de lignes num_case = 0 for sprite in lign: # On calcule la position réelle en pixels x = num_case * 25 y = num_lign * 25 if sprite == 1: # 1 = wall fenetre.blit(wall, (x, y)) elif sprite == 0: # 0 = floor fenetre.blit(floor, (x, y)) num_case += 1 num_lign += 1 class MacGyver: def show_mac (self): """Methode permettant d'initialiser le personnage""" # Sprites du personnage self = pygame.image.load("MacGyver.png") # Position du personnage fenetre.blit(self, (0, 350)) class Guardian: def show_guard (self): """Methode permettant d'initialiser le gardien""" # Sprites du personnage self = pygame.image.load("Guardian.png") # Position du personnage fenetre.blit(self, (350, 0)) class Items: def location (self, list): # # On parcourt la liste du labyrinthe num_lign = 0 for lign in list: # On parcourt les listes de lignes num_case = 0 for sprite in lign: if sprite == 1: # 1 = wall pass elif sprite == 0: # 0 = floor p = randint(0,2000) # p = possibilité d'avoir un objet sur la case if p == 1: # On calcule la position réelle en pixels des objets x = num_case * 25 y = num_lign * 25 if not (x == 0 and y == 350) and (x == 350 and y == 0): return [x, y] num_case += 1 num_lign += 1 return None def show_item (self, list): """Méthode permettant d'initialiser les objets""" # Coordonnées des objets sur tab for i in range(0,3): tab_loc = self.location(list) while tab_loc == None: tab_loc = self.location(list) x = tab_loc[0] y = tab_loc[1] # Sprites des objets en fonction de l'itération if i == 0: fenetre.blit(pygame.image.load("needle.png"), (x, y)) elif i == 1: fenetre.blit(pygame.image.load("syringe.png"), (x, y)) else: fenetre.blit(pygame.image.load("tube.png"), (x, y)) ##random.sample if __name__ == "__main__": pygame.init() fenetre = pygame.display.set_mode((375, 375)) lab = Labyrinth() lab.show_lab() mac = MacGyver() mac.show_mac() guard = Guardian() guard.show_guard() item = Items() item.show_item(lab.tab) # Rafraîchissement de l'écran pygame.display.flip() continuer = 1 # Boucle infinie while continuer: for event in pygame.event.get(): # On parcours la liste de tous les événements reçus if event.type == QUIT: # Si un de ces événements est de type QUIT continuer = 0
Go
UTF-8
997
2.703125
3
[]
no_license
package main import ( "github.com/elisescu/dryred" "os" "os/signal" "flag" "log" "sync" "time" ) func install_signal(fn func ()) { signal_channel := make (chan os.Signal, 1) signal.Notify(signal_channel, os.Interrupt) signal.Notify(signal_channel, os.Kill) go func() { <- signal_channel fn() }() } func main() { client := dryred.DRBackClientNew() // TODO: Fix this way of exiting the main loop should_stop := false var wg sync.WaitGroup wg.Add(1) install_signal(func () { log.Printf("Caught Ctrl+C.") should_stop = true client.Close() wg.Done() }) server_hostname := flag.String("server", "localhost", "Server hostname to connect to") server_port := flag.Int("port", 1234, "Server port to connect to") flag.Parse() log.Printf("Connecting to %s:%d", *server_hostname, *server_port); go func() { for !should_stop { log.Printf("Launching client..") client.Launch(*server_hostname, *server_port) time.Sleep(time.Second * 1) } } () wg.Wait() }
Python
UTF-8
299
3.1875
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class ListMetaclass(type): def __new__(cls,name,bases,attrs): attrs['add'] = lambda self,value:self.append(value) return type.__new__(cls,name,bases,attrs) class MyList(list, metaclass=ListMetaclass): pass c=MyList() print(c(1))
TypeScript
UTF-8
2,037
2.84375
3
[ "MIT" ]
permissive
/// <reference path="../../../Scripts/endgate.d.ts" /> // Wrap in module to keep code out of global scope module Camera { export class World { constructor(scene: eg.Rendering.Scene2d) { var camSize: eg.Size2d = scene.Camera.Size; // Add shapes and text to the Scene to represent the game world scene.Add(new eg.Graphics.Circle(350, 600, 25, eg.Graphics.Color.Green)); scene.Add(new eg.Graphics.Rectangle(camSize.Width, camSize.Height + 125, 125, 125, new eg.Graphics.Color("red"))); scene.Add(new eg.Graphics.Circle(400, 200, 25, eg.Graphics.Color.Orange)); scene.Add(this.CreateRotatedRect(0, 0, 200, 150, eg.Graphics.Color.Gray, Math.PI / 4)); scene.Add(this.CreateRotatedRect(0, 800, 400, 125, eg.Graphics.Color.Yellow, Math.PI * 1.75)); scene.Add(this.CreateRotatedText(camSize.Width, -30, "Hello!", 0)); scene.Add(this.CreateRotatedText(camSize.HalfWidth, 0, "TOP SIDE", 0)); scene.Add(this.CreateRotatedText(0, camSize.HalfHeight, "LEFT SIDE", -Math.PI / 2)); scene.Add(this.CreateRotatedText(camSize.Width, camSize.HalfHeight, "RIGHT SIDE", Math.PI / 2)); scene.Add(this.CreateRotatedText(camSize.HalfWidth, camSize.Height, "BOTTOM SIDE", Math.PI)); } // These two functions are just helper functions to make the above code look nicer private CreateRotatedRect(x: number, y: number, width: number, height: number, color: eg.Graphics.Color, rotation: number): eg.Graphics.Rectangle { var rect = new eg.Graphics.Rectangle(x, y, width, height, color); rect.Rotation = rotation; return rect; } private CreateRotatedText(x: number, y: number, text: string, rotation: number): eg.Graphics.Text2d { var t: eg.Graphics.Text2d = new eg.Graphics.Text2d(x, y, text); t.FontSettings.FontSize = 16 + "pt"; t.Rotation = rotation; return t; } } }
Java
UTF-8
507
2.4375
2
[]
no_license
package etc.etc.demonstrate.examples.super_sibling; import etc.java.lang.Object.*; import etc.demonstrate.examples.*; abstract class _SuperSiblingDelegate extends ObjectDelegate { private SuperSibling superSibling_; public _SuperSiblingDelegate(SuperSibling superSibling_) { super(superSibling_); this.superSibling_ = superSibling_; } public SuperSibling unEtc() { return (SuperSibling) super.unEtc(); } public String superSiblingMethod() { return superSibling_.superSiblingMethod(); } }
Java
UTF-8
3,421
2.265625
2
[]
no_license
package TesteVendas.Vendas.controller; import java.util.List; import java.util.Optional; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import TesteVendas.Vendas.dto.ProdutoDto; import TesteVendas.Vendas.model.Produto; import TesteVendas.Vendas.repository.ProdutoRepository; import TesteVendas.Vendas.services.ProdutoServices; @RestController @RequestMapping("/v1/Produto/") public class ProdutoController { private @Autowired ProdutoRepository reposutoryProduto; private @Autowired ProdutoServices serviceProduto; @GetMapping("PegarTodos") public ResponseEntity<List<Produto>> PegarTodos() { List<Produto> produto = reposutoryProduto.findAll(); if (produto.isEmpty()) { return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); } else { return ResponseEntity.status(200).body(produto); } } @GetMapping("BuscarPeloNome") public ResponseEntity<List<Produto>> PegarPeloNome(@RequestParam(defaultValue = "") String nome) { return ResponseEntity.status(200).body(reposutoryProduto.findAllByNomeContaining(nome)); } @GetMapping("BuscarPelaDescricao") public ResponseEntity<List<Produto>> PegarPelaDescricao(@RequestParam(defaultValue = "") String descricao) { return ResponseEntity.status(200).body(reposutoryProduto.findAllByDescricaoContaining(descricao)); } @GetMapping("BuscarPeloPreco") public ResponseEntity<List<Produto>> PegarPeloPreco(@RequestParam(defaultValue = "") double preco) { return ResponseEntity.status(200).body(reposutoryProduto.findAllByPrecoContaining(preco)); } @GetMapping("{idProduto}/BuscarPeloId") public ResponseEntity<Produto> PegarPeloId(@PathVariable long idProduto) { return reposutoryProduto.findById(idProduto).map(achou -> ResponseEntity.ok(achou)) .orElse(ResponseEntity.notFound().build()); } @DeleteMapping("{idProduto}/DeletarProduto") public void Deletar(@PathVariable long idProduto) { reposutoryProduto.deleteById(idProduto); } @PostMapping("CadastarProduto") public ResponseEntity<Object> CadastrarProduto(@RequestBody @Valid Produto novoProduto) { Optional<Object> produto = serviceProduto.CadastrarProduto(novoProduto); if (produto.isEmpty()) { return ResponseEntity.status(200).body("Produto Existente"); } else { return ResponseEntity.status(201).body("Produto Cadastrado"); } } @PutMapping("{idProduto}/AlterarProduto") public ResponseEntity<Produto> AlterarProduto(@PathVariable @Valid long idProduto, @Valid @RequestBody ProdutoDto novoProduto) { return serviceProduto.AlterarProduto(idProduto, novoProduto) .map(ProdutoAlterado -> ResponseEntity.status(201).body(reposutoryProduto.save(ProdutoAlterado))) .orElseGet(() -> { return ResponseEntity.badRequest().build(); }); } }
Python
UTF-8
2,580
2.515625
3
[]
no_license
from rest_framework import serializers from .models import Location, Subscriber class LocationSerializer(serializers.Serializer): city = serializers.CharField(required=True, max_length=256) state = serializers.CharField(required=True, max_length=64) class Meta: fields = ['city', 'state'] class SubscriberSerializer(serializers.Serializer): id = serializers.IntegerField(required=False) created = serializers.DateTimeField(required=False) first_name = serializers.CharField(required=True, max_length=64) last_name = serializers.CharField(required=True, max_length=64) email = serializers.CharField() gender = serializers.CharField(required=True, max_length=8) location = LocationSerializer(required=True) class Meta: fields = ['first_name', 'last_name', 'email', 'gender', 'location'] read_only_fields = ['id', 'created'] def create(self, validated_data): # remove location from serialized data and add model object location = validated_data.pop('location') city = location.get('city', None) state = location.get('state', None) if not city and not state: raise serializers.ValidationError('No location input found') # call get or create to reuse location objects location_obj = Location.objects.get_or_create(city=city, state=state)[0] # add location back to validated data validated_data.update({'location': location_obj}) # unpack validated_data to create a new Subscriber object return Subscriber.objects.create(**validated_data) class BulkSubscriberSerializer(serializers.Serializer): subscribers = SubscriberSerializer(many=True) class Meta: fields = ['subscribers'] def create(self, validated_data): # store the Subscriber objects to be created in bulk create_objects_list = [] # iterate over the validated_data and add Subscriber objects to a list to be created for data in validated_data: # notice the same functionality from the regular serializer location = data.pop('location') city = location.get('city', None) state = location.get('state', None) location_obj = Location.objects.get_or_create(city=city, state=state)[0] # combine data and {'location': location_obj} and unpack to the Subscriber model create_objects_list.append(Subscriber(**{**data, **{'location': location_obj}})) return Subscriber.objects.bulk_create(create_objects_list)
C#
UTF-8
979
2.828125
3
[]
no_license
using Facebook; using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Net; using System.Web; namespace Trabalho.Utility { public class FacebookConnection { /// <summary> /// Retorna os dados do usuario no Facebook /// </summary> /// <param name="facebook_token">Token do Facebook</param> /// <returns></returns> public string GetFacebookParameters(string facebook_token) { try { FacebookClient facebookClient = new FacebookClient(facebook_token); facebookClient.AppId = "614756975370105"; facebookClient.AppSecret = "5aaaaeb5b72b7c09772ce268a0d30a14"; return facebookClient.Get("me?fields=email,name").ToString(); } catch (FacebookOAuthException) { throw new Exception("Token de acesso já está expirado."); } } } }
Java
UTF-8
1,388
2.453125
2
[]
no_license
package com.csye6225.fall2019.courseservice.resources; import com.csye6225.fall2019.courseservice.datamodel.Course; import com.csye6225.fall2019.courseservice.datamodel.Lecture; import com.csye6225.fall2019.courseservice.service.CoursesService; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.List; @Path("courses") public class CoursesResource { CoursesService cseService = new CoursesService(); @GET @Produces(MediaType.APPLICATION_JSON) public List<Course> getCourse() { return cseService.getAllCourse(); } @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Course addCourse(Course cse) { return cseService.addCourse(cse.getName(), cse.getLectures(), cse.getBoard(), cse.getRoster(), cse.getEnrolledStd(), cse.getProfessor(), cse.getTeachAssist()); } @PUT @Path("/{courseId}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Course updateCourse(@PathParam("courseId") long cseId, Course cse) { return cseService.updateCourse(String.valueOf(cseId), cse); } @DELETE @Path("/{courseId}") @Produces(MediaType.APPLICATION_JSON) public Course deleteCourse(@PathParam("courseId") long cseId) { return cseService.deleteCourse(cseId); } }
Python
UTF-8
11,046
3.046875
3
[]
no_license
import math import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F class Attention(nn.Module): """ Applies attention mechanism on the `context` using the `query`. **Thank you** to IBM for their initial implementation of :class:`Attention`. Here is their `License <https://github.com/IBM/pytorch-seq2seq/blob/master/LICENSE>`__. Args: dimensions (int): Dimensionality of the query and context. attention_type (str, optional): How to compute the attention score: * dot: :math:`score(H_j,q) = H_j^T q` * general: :math:`score(H_j, q) = H_j^T W_a q` Example: >>> attention = Attention(256) >>> query = torch.randn(5, 1, 256) [batch size, output length, dimensions] >>> context = torch.randn(5, 5, 256) [batch size, query length, dimensions] >>> output, weights = attention(query, context) >>> output.size() torch.Size([5, 1, 256]) [batch size, output length, dimensions] >>> weights.size() torch.Size([5, 1, 5]) [batch size, output length, query length] """ def __init__(self, dimensions, attention_type='general'): super(Attention, self).__init__() if attention_type not in ['dot', 'general']: raise ValueError('Invalid attention type selected.') self.attention_type = attention_type if self.attention_type == 'general': self.linear_in = nn.Linear(dimensions, dimensions, bias=False) self.linear_out = nn.Linear(dimensions * 2, dimensions, bias=False) self.softmax = nn.Softmax(dim=-1) self.tanh = nn.Tanh() def forward(self, query, context): """ Args: query (:class:`torch.FloatTensor` [batch size, output length, dimensions]): Sequence of queries to query the context. tensor containing the output features from the decoder. context (:class:`torch.FloatTensor` [batch size, query length, dimensions]): Data overwhich to apply the attention mechanism. tensor containing features of the encoded input sequence. Returns: :class:`tuple` with `output` and `weights`: * **output** (:class:`torch.LongTensor` [batch size, output length, dimensions]): Tensor containing the attended features. * **weights** (:class:`torch.FloatTensor` [batch size, output length, query length]): Tensor containing attention weights. """ batch_size, output_len, dimensions = query.size() query_len = context.size(1) if self.attention_type == "general": query = query.reshape(batch_size * output_len, dimensions) query = self.linear_in(query) query = query.reshape(batch_size, output_len, dimensions) # TODO: Include mask on PADDING_INDEX? # (batch_size, output_len, dimensions) * (batch_size, query_len, dimensions) -> # (batch_size, output_len, query_len) attention_scores = torch.bmm( query, context.transpose(1, 2).contiguous()) # Compute weights across every context sequence attention_scores = attention_scores.reshape( batch_size * output_len, query_len) attention_weights = self.softmax(attention_scores) attention_weights = attention_weights.reshape( batch_size, output_len, query_len) # (batch_size, output_len, query_len) * (batch_size, query_len, dimensions) -> # (batch_size, output_len, dimensions) mix = torch.bmm(attention_weights, context) # concat -> (batch_size * output_len, 2*dimensions) combined = torch.cat((mix, query), dim=2) combined = combined.reshape(batch_size * output_len, 2 * dimensions) # Apply linear_out on every 2nd dimension of concat # output -> (batch_size, output_len, dimensions) output = self.linear_out(combined).reshape( batch_size, output_len, dimensions) output = self.tanh(output) return output, attention_weights class IBMAttention(nn.Module): r""" Applies an attention mechanism on the output features from the decoder. .. math:: \begin{array}{ll} x = context*output \\ attn = exp(x_i) / sum_j exp(x_j) \\ output = \tanh(w * (attn * context) + b * output) \end{array} Args: dim(int): The number of expected features in the output Inputs: output, context - **output** (batch, output_len, dimensions): tensor containing the output features from the decoder. - **context** (batch, input_len, dimensions): tensor containing features of the encoded input sequence. Outputs: output, attn - **output** (batch, output_len, dimensions): tensor containing the attended output features from the decoder. - **attn** (batch, output_len, input_len): tensor containing attention weights. Attributes: linear_out (torch.nn.Linear): applies a linear transformation to the incoming data: :math:`y = Ax + b`. mask (torch.Tensor, optional): applies a :math:`-inf` to the indices specified in the `Tensor`. Examples:: >>> attention = seq2seq.models.Attention(256) >>> context = Variable(torch.randn(5, 3, 256)) >>> output = Variable(torch.randn(5, 5, 256)) >>> output, attn = attention(output, context) """ def __init__(self, dim): super(IBMAttention, self).__init__() self.linear_out = nn.Linear(dim*2, dim) self.mask = None def set_mask(self, mask): """ Sets indices to be masked Args: mask (torch.Tensor): tensor containing indices to be masked """ self.mask = mask def forward(self, output, context): batch_size = output.size(0) hidden_size = output.size(2) input_size = context.size(1) # (batch, output_len, dim) * (batch, input_len, dim) -> (batch, output_len, input_len) attn = torch.bmm(output, context.transpose(1, 2)) if self.mask is not None: attn.data.masked_fill_(self.mask, -float('inf')) attn = F.softmax(attn.view(-1, input_size), dim=1).view(batch_size, -1, input_size) # (batch, output_len, input_len) * (batch, input_len, dim) -> (batch, output_len, dim) mix = torch.bmm(attn, context) # concat -> (batch, output_len, 2*dim) combined = torch.cat((mix, output), dim=2) # output -> (batch, output_len, dim) output = F.tanh(self.linear_out(combined.view(-1, 2 * hidden_size))).view(batch_size, -1, hidden_size) return output, attn class RNNAttention(nn.Module): def __init__(self, query_dim): # assume: query_dim = key/value_dim super(RNNAttention, self).__init__() self.scale = 1. / math.sqrt(query_dim) def forward(self, query, key, value): # query == hidden: (batch_size, hidden_dim) # key/value == gru_output: (batch_size, sentence_length, hidden_dim) query = query.unsqueeze(1) # (batch_size, 1, hidden_dim) key = key.permute(0, 2, 1) # (batch_size, hidden_dim, sentence_length) # bmm: batch matrix-matrix multiplication # (batch_size, 1, sentence_length) attention_weight = torch.bmm(query, key) # normalize sentence_length's dimension attention_weight = F.softmax(attention_weight.mul_(self.scale), dim=2) # (batch_size, 1, hidden_dim) attention_output = torch.bmm(attention_weight, value) # (batch_size, hidden_dim) attention_output = attention_output.squeeze(1) return attention_output, attention_weight.squeeze(1) class RNN_Attention(nn.Module): """ Attention Network. """ def __init__(self, dim): """ :param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network """ super(RNN_Attention, self).__init__() # linear layer to transform encoded image encoder_dim = decoder_dim = attention_dim = dim self.encoder_att = nn.Linear(encoder_dim, attention_dim) # linear layer to transform decoder's output self.decoder_att = nn.Linear(decoder_dim, attention_dim) # linear layer to calculate values to be softmax-ed self.full_att = nn.Linear(attention_dim, 1) self.relu = nn.ReLU() self.softmax = nn.Softmax(dim=1) # softmax layer to calculate weights def forward(self, encoder_out, decoder_hidden): """ Forward propagation. :param encoder_out: encoded images, a tensor of dimension (batch_size, num_pixels, encoder_dim) :param decoder_hidden: previous decoder output, a tensor of dimension (batch_size, decoder_dim) :return: attention weighted encoding, weights """ # (batch_size, num_pixels, attention_dim) att1 = self.encoder_att(encoder_out) # (batch_size, attention_dim) att2 = self.decoder_att(decoder_hidden) # (batch_size, num_pixels) att = self.full_att(self.relu(att1 + att2.unsqueeze(1))).squeeze(2) # (batch_size, num_pixels) alpha = self.softmax(att) # (batch_size, encoder_dim) attention_weighted_encoding = (encoder_out * alpha.unsqueeze(2)).sum(dim=1) return attention_weighted_encoding, alpha class SingleAttention(nn.Module): '''Transformerは本当はマルチヘッドAttentionですが、 分かりやすさを優先しシングルAttentionで実装します''' def __init__(self, d_model): super().__init__() # SAGANでは1dConvを使用したが、今回は全結合層で特徴量を変換する self.q_linear = nn.Linear(d_model, d_model) self.v_linear = nn.Linear(d_model, d_model) self.k_linear = nn.Linear(d_model, d_model) # 出力時に使用する全結合層 self.out = nn.Linear(d_model, d_model) # Attentionの大きさ調整の変数 self.d_k = d_model def forward(self, q, k, v, mask): # 全結合層で特徴量を変換 k = self.k_linear(k) q = self.q_linear(q) v = self.v_linear(v) # Attentionの値を計算する # 各値を足し算すると大きくなりすぎるので、root(d_k)で割って調整 weights = torch.matmul(q, k.transpose(1, 2)) / math.sqrt(self.d_k) # ここでmaskを計算 mask = mask.unsqueeze(1) weights = weights.masked_fill(mask == 0, -1e9) # softmaxで規格化をする normlized_weights = F.softmax(weights, dim=-1) # AttentionをValueとかけ算 output = torch.matmul(normlized_weights, v) # 全結合層で特徴量を変換 output = self.out(output) return output, normlized_weights
Python
UTF-8
19,016
2.9375
3
[]
no_license
from types import SimpleNamespace import augmentation.datasets.utils from augmentation.datasets.custom.mnist import MNIST_CORRUPTED_VARIANTS import tensorflow as tf # TODO multihead should be specified as an option to the dataset instead of a separate one def load_mnist_correlation_yz_multihead(dataset_name, dataset_version, data_dir, validation_frac): """ Dataset of the form 'mnist_correlation_yz_multihead/zigzag/{a}/{b}/{size}/{test_size}/[z]' This loads a training set with Y=a and Z=b, of total size {size}, where Y is the existence of the spurious feature and Z is the digit parity If the last option "z" is included, dataset is labeled by z instead of y """ params = dataset_name.split("/") assert params[0] == 'mnist_correlation_yz_multihead', f'Dataset name is {dataset_name}, ' \ f'should be mnist_correlation_yz_multihead/<variant>/<y_class>/<z_class>/<size>/<test_size>/<label>.' variant = params[1] y = int(params[2]) z = int(params[3]) size = int(params[4]) test_size = int(params[5]) label_var = params[6] if len(params) > 6 else 'y' assert variant in MNIST_CORRUPTED_VARIANTS, f'Dataset variant {variant} is not available.' assert y in [0, 1] and z in [0, 1], f'Classes Y={y} and Z={z} must be in {0, 1}.' assert label_var == 'y' or label_var == 'z' if z == 0: # Load up the standard MNIST dataset mnists_dataset_payload = augmentation.datasets.utils.load_dataset(dataset_name='mnist', dataset_version='3.*.*', data_dir=data_dir, validation_frac=validation_frac) else: # Load up the corrupted MNIST dataset mnists_dataset_payload = augmentation.datasets.utils.load_dataset(dataset_name=f'mnist_corrupted/{variant}', dataset_version='1.*.*', data_dir=data_dir, validation_frac=validation_frac) mnists_train = mnists_dataset_payload.train_dataset. \ filter(lambda image, label: label % 2 == y) mnists_val = mnists_dataset_payload.val_dataset. \ filter(lambda image, label: label % 2 == y) mnists_test = mnists_dataset_payload.test_dataset. \ filter(lambda image, label: label % 2 == y) train_sz_ = augmentation.datasets.utils.dataset_len(mnists_train) val_sz_ = augmentation.datasets.utils.dataset_len(mnists_val) test_sz_ = augmentation.datasets.utils.dataset_len(mnists_test) size = train_sz_ if size == -1 else size test_size = test_sz_ if test_size == -1 else min(test_size, test_sz_) assert size <= train_sz_ + val_sz_, f'Dataset size {size} for {dataset_name} should be at most {train_sz_ + val_sz_}.' val_size = int(size * validation_frac) if z == 0: mnists_train = mnists_train.take(size - val_size) mnists_val = mnists_val.take(val_size) mnists_test = mnists_test.take(test_size) else: mnists_train = mnists_train.skip(train_sz_ - (size - val_size)) mnists_val = mnists_val.skip(val_sz_ - val_size) mnists_test = mnists_test.skip(test_sz_ - test_size) # relabel labels to 0/1 if label_var == 'y': mnists_train = mnists_train.map(lambda image, label: (image, y)) mnists_val = mnists_val.map(lambda image, label: (image, y)) mnists_test = mnists_test.map(lambda image, label: (image, y)) if label_var == 'z': mnists_train = mnists_train.map(lambda image, label: (image, z)) mnists_val = mnists_val.map(lambda image, label: (image, z)) mnists_test = mnists_test.map(lambda image, label: (image, z)) print( f'{dataset_name} splits: {augmentation.datasets.utils.dataset_len(mnists_train)}, ' f'{augmentation.datasets.utils.dataset_len(mnists_val)}, {augmentation.datasets.utils.dataset_len(mnists_test)}') # Make a dataset info namespace to ensure downstream compatibility # num_classes = mnists_dataset_payload.dataset_info.features['label'].num_classes num_classes = 2 shape = mnists_dataset_payload.dataset_info.features['image'].shape num_examples = size # Change to multihead binary classification num_classes = 1 mnists_train = mnists_train.map(lambda x, y: (x, tf.convert_to_tensor(y)[..., None])) mnists_val = mnists_val.map(lambda x, y: (x, tf.convert_to_tensor(y)[..., None])) mnists_test = mnists_test.map(lambda x, y: (x, tf.convert_to_tensor(y)[..., None])) dataset_info = SimpleNamespace(features={'label': SimpleNamespace(num_classes=num_classes), 'image': SimpleNamespace(shape=shape)}, splits={'train': SimpleNamespace(num_examples=num_examples)}) if label_var == 'y': dataset_info.classes = ['parity'] else: dataset_info.classes = ['corruption'] return SimpleNamespace(dataset_info=dataset_info, train_dataset=mnists_train, val_dataset=mnists_val, test_dataset=mnists_test) def load_mnist_correlation_yz(dataset_name, dataset_version, data_dir, validation_frac): """ Dataset of the form 'mnist_correlation_yz/zigzag/{a}/{b}/{size}/{test_size}/[z]' This loads a training set with Y=a and Z=b, of total size {size}, where Y is the existence of the spurious feature and Z is the digit parity If the last option "z" is included, dataset is labeled by z instead of y """ params = dataset_name.split("/") assert params[0] == 'mnist_correlation_yz', f'Dataset name is {dataset_name}, ' \ f'should be mnist_correlation_yz/<variant>/<y_class>/<z_class>/<size>/<test_size>/<label>.' variant = params[1] y = int(params[2]) z = int(params[3]) size = int(params[4]) test_size = int(params[5]) label_var = params[6] if len(params) > 6 else 'y' assert variant in MNIST_CORRUPTED_VARIANTS, f'Dataset variant {variant} is not available.' assert y in [0, 1] and z in [0, 1], f'Classes Y={y} and Z={z} must be in {0, 1}.' assert label_var == 'y' or label_var == 'z' if z == 0: # Load up the standard MNIST dataset mnists_dataset_payload = augmentation.datasets.utils.load_dataset(dataset_name='mnist', dataset_version='3.*.*', data_dir=data_dir, validation_frac=validation_frac) else: # Load up the corrupted MNIST dataset mnists_dataset_payload = augmentation.datasets.utils.load_dataset(dataset_name=f'mnist_corrupted/{variant}', dataset_version='1.*.*', data_dir=data_dir, validation_frac=validation_frac) mnists_train = mnists_dataset_payload.train_dataset. \ filter(lambda image, label: label % 2 == y). \ cache() mnists_val = mnists_dataset_payload.val_dataset. \ filter(lambda image, label: label % 2 == y). \ cache() mnists_test = mnists_dataset_payload.test_dataset. \ filter(lambda image, label: label % 2 == y). \ cache() train_sz_ = augmentation.datasets.utils.dataset_len(mnists_train) val_sz_ = augmentation.datasets.utils.dataset_len(mnists_val) test_sz_ = augmentation.datasets.utils.dataset_len(mnists_test) size = train_sz_ if size == -1 else size test_size = test_sz_ if test_size == -1 else min(test_size, test_sz_) assert size <= train_sz_ + val_sz_, f'Dataset size {size} for {dataset_name} should be at most {train_sz_ + val_sz_}.' val_size = int(size * validation_frac) if z == 0: mnists_train = mnists_train.take(size - val_size) mnists_val = mnists_val.take(val_size) mnists_test = mnists_test.take(test_size) else: mnists_train = mnists_train.skip(train_sz_ - (size - val_size)) mnists_val = mnists_val.skip(val_sz_ - val_size) mnists_test = mnists_test.skip(test_sz_ - test_size) # relabel labels to 0/1 if label_var == 'y': mnists_train = mnists_train.map(lambda image, label: (image, y)) mnists_val = mnists_val.map(lambda image, label: (image, y)) mnists_test = mnists_test.map(lambda image, label: (image, y)) if label_var == 'z': mnists_train = mnists_train.map(lambda image, label: (image, z)) mnists_val = mnists_val.map(lambda image, label: (image, z)) mnists_test = mnists_test.map(lambda image, label: (image, z)) print( f'{dataset_name} splits: {augmentation.datasets.utils.dataset_len(mnists_train)}, ' f'{augmentation.datasets.utils.dataset_len(mnists_val)}, {augmentation.datasets.utils.dataset_len(mnists_test)}') # Make a dataset info namespace to ensure downstream compatibility num_classes = 2 shape = mnists_dataset_payload.dataset_info.features['image'].shape num_examples = size dataset_info = SimpleNamespace(features={'label': SimpleNamespace(num_classes=num_classes), 'image': SimpleNamespace(shape=shape)}, splits={'train': SimpleNamespace(num_examples=num_examples)}) return SimpleNamespace(dataset_info=dataset_info, train_dataset=mnists_train, val_dataset=mnists_val, test_dataset=mnists_test) def load_mnist_correlation_y(dataset_name, dataset_version, data_dir, validation_frac): """ Dataset of the form 'mnist_correlation_y/zigzag/{a}/{p}/{size}/[z]' This loads a training set with Y=a and p(Z=a) = p, of total size {size}, where Y is the existence of the spurious feature and Z is the digit parity """ params = dataset_name.split("/") assert params[0] == 'mnist_correlation_y', f'Dataset name is {dataset_name}, ' \ f'should be mnist_correlation_y/<variant>/<y_class>/<z_prob>/<size>/<label>.' variant = params[1] y = int(params[2]) p_z = float(params[3]) size = int(params[4]) label_var = params[5] if len(params) > 5 else 'y' if size == -1: size = 30000 # TODO FIX THIS - WHY ISN'T MNIST CLASS BALANCED assert variant in MNIST_CORRUPTED_VARIANTS, f'Dataset variant {variant} is not available.' assert y in [0, 1], f'Class Y={y} must be in {0, 1}.' assert 0. <= p_z <= 1., f'Probability p(Z=y)={p_z} should be in [0.0, 1.0].' assert size <= 30000, f'Dataset size {size} should be at most 30000.' assert label_var == 'y' or label_var == 'z' size_z = int(size * p_z) test_size_z = int(5000 * p_z) dataset_z = load_mnist_correlation_yz( f'mnist_correlation_yz/{variant}/{y}/{y}/{size_z}/{test_size_z}/{label_var}', dataset_version, data_dir, validation_frac) dataset_z_ = load_mnist_correlation_yz( f'mnist_correlation_yz/{variant}/{y}/{1 - y}/{size - size_z}/{5000 - test_size_z}/{label_var}', dataset_version, data_dir, validation_frac) dataset_z.train_dataset = dataset_z.train_dataset.concatenate(dataset_z_.train_dataset) dataset_z.val_dataset = dataset_z.val_dataset.concatenate(dataset_z_.val_dataset) dataset_z.test_dataset = dataset_z.test_dataset.concatenate(dataset_z_.test_dataset) dataset_z.dataset_info.splits['train'].num_examples += dataset_z_.dataset_info.splits['train'].num_examples return dataset_z def load_mnist_correlation_partial(dataset_name, dataset_version, data_dir, validation_frac): """ Dataset of the form 'mnist_correlation_partial/{variant}/{z}/{size}/[label_var]'. Creates a balanced dataset with Pr(Y = 1) = Pr(Y = 0) = 1/2 and Pr(Z = z) = 1. Use this for training CycleGANs: E.g. for 'mnist_correlation/zigzag/p/size/y' as your main dataset you can create source and target datasets using 'mnist_correlation_partial/zigzag/0/some_size/y' and 'mnist_correlation_partial/zigzag/1/some_size/y' """ params = dataset_name.split("/") assert params[0] == 'mnist_correlation_partial', \ f'Dataset name is {dataset_name}, should be mnist_correlation_partial/<variant>/<z_class>/<size>/<label>.' variant = params[1] z = int(params[2]) size = int(params[3]) label_var = params[4] if len(params) > 4 else 'y' size = 30000 if size == -1 else size assert variant in MNIST_CORRUPTED_VARIANTS, f'Dataset variant {variant} is not available.' assert z == 1 or z == 0, f'Clean should be 0 or 1 not {z}.' assert size <= 30000, f'Dataset size {size} should be at most 30000.' assert size % 2 == 0, f"C'mon why would you use an odd dataset size..." assert label_var == 'y' or label_var == 'z' dataset_evens = load_mnist_correlation_yz( f'mnist_correlation_yz/{variant}/{0}/{z}/{size // 2}/{5000}/{label_var}', dataset_version, data_dir, validation_frac) dataset_odds = load_mnist_correlation_yz( f'mnist_correlation_yz/{variant}/{1}/{z}/{size // 2}/{5000}/{label_var}', dataset_version, data_dir, validation_frac) dataset_evens.train_dataset = dataset_evens.train_dataset.concatenate(dataset_odds.train_dataset) dataset_evens.val_dataset = dataset_evens.val_dataset.concatenate(dataset_odds.val_dataset) dataset_evens.test_dataset = dataset_evens.test_dataset.concatenate(dataset_odds.test_dataset) dataset_evens.dataset_info.splits['train'].num_examples += dataset_odds.dataset_info.splits['train'].num_examples return dataset_evens def load_mnist_correlation(dataset_name, dataset_version, data_dir, validation_frac): """ Dataset of the form 'mnist_correlation/{variant}/{p}/{size}/[label_var]' This loads a training+val set of total size ~{size}, where the spurious feature {variant} and digit parity are correlated More precisely: - Y=parity and Z=variant are marginally balanced [p(Y=0) = p(Y=1) = P(Z=0) = P(Z=1) = 1/2] - P(Y=a | Z=a) = P(Z=a | Y=a) = p - Alternatively, Y and Z are correlated with strength (2p-1) """ params = dataset_name.split("/") assert params[0] == 'mnist_correlation', \ f'Dataset name is {dataset_name}, should be mnist_correlation/<variant>/<prob>/<size>/<label>.' variant = params[1] p = float(params[2]) size = int(params[3]) label_var = params[4] if len(params) > 4 else 'y' size = 60000 if size == -1 else size assert variant in MNIST_CORRUPTED_VARIANTS, f'Dataset variant {variant} is not available.' assert 0. <= p <= 1., f'Probability p(Z=y)={p} should be in [0.0, 1.0].' assert size <= 60000, f'Dataset size {size} should be at most 30000.' assert size % 2 == 0, f"C'mon why would you use an odd dataset size..." assert label_var == 'y' or label_var == 'z' dataset_evens = load_mnist_correlation_y( f'mnist_correlation_y/{variant}/{0}/{p}/{size // 2}/{label_var}', dataset_version, data_dir, validation_frac) dataset_odds = load_mnist_correlation_y( f'mnist_correlation_y/{variant}/{1}/{p}/{size // 2}/{label_var}', dataset_version, data_dir, validation_frac) dataset_evens.train_dataset = dataset_evens.train_dataset.concatenate(dataset_odds.train_dataset) dataset_evens.val_dataset = dataset_evens.val_dataset.concatenate(dataset_odds.val_dataset) dataset_evens.test_dataset = dataset_evens.test_dataset.concatenate(dataset_odds.test_dataset) dataset_evens.dataset_info.splits['train'].num_examples += dataset_odds.dataset_info.splits['train'].num_examples return dataset_evens def load_mnist_correlation_multihead(dataset_name, dataset_version, data_dir, validation_frac): """ Dataset of the form 'mnist_correlation_multihead/{variant}/{p}/{size}/[label_var]' This loads a training+val set of total size ~{size}, where the spurious feature {variant} and digit parity are correlated More precisely: - Y=parity and Z=variant are marginally balanced [p(Y=0) = p(Y=1) = P(Z=0) = P(Z=1) = 1/2] - P(Y=a | Z=a) = P(Z=a | Y=a) = p - Alternatively, Y and Z are correlated with strength (2p-1) """ params = dataset_name.split("/") assert params[0] == 'mnist_correlation_multihead', \ f'Dataset name is {dataset_name}, should be mnist_correlation_multihead/<variant>/<prob>/<size>/<label>.' variant = params[1] p = float(params[2]) size = int(params[3]) label_var = params[4] if len(params) > 4 else 'y' size = 60000 if size == -1 else size assert variant in MNIST_CORRUPTED_VARIANTS, f'Dataset variant {variant} is not available.' assert 0. <= p <= 1., f'Probability p(Z=y)={p} should be in [0.0, 1.0].' assert size <= 60000, f'Dataset size {size} should be at most 30000.' assert size % 2 == 0, f"C'mon why would you use an odd dataset size..." assert label_var == 'y' or label_var == 'z' dataset_evens = load_mnist_correlation_y( f'mnist_correlation_y/{variant}/{0}/{p}/{size // 2}/{label_var}', dataset_version, data_dir, validation_frac) dataset_odds = load_mnist_correlation_y( f'mnist_correlation_y/{variant}/{1}/{p}/{size // 2}/{label_var}', dataset_version, data_dir, validation_frac) dataset_evens.train_dataset = dataset_evens.train_dataset.concatenate(dataset_odds.train_dataset) dataset_evens.val_dataset = dataset_evens.val_dataset.concatenate(dataset_odds.val_dataset) dataset_evens.test_dataset = dataset_evens.test_dataset.concatenate(dataset_odds.test_dataset) dataset_evens.dataset_info.splits['train'].num_examples += dataset_odds.dataset_info.splits['train'].num_examples # To turn this into a "multihead" method: pretend there is 1 binary head dataset_evens.dataset_info.num_classes = 1 if label_var == 'y': dataset_evens.dataset_info.classes = ['parity'] else: dataset_evens.dataset_info.classes = ['corruption'] dataset_evens.train_dataset = dataset_evens.train_dataset.map(lambda x, y: (x, tf.convert_to_tensor(y)[..., None])) dataset_evens.val_dataset = dataset_evens.val_dataset.map(lambda x, y: (x, tf.convert_to_tensor(y)[..., None])) dataset_evens.test_dataset = dataset_evens.test_dataset.map(lambda x, y: (x, tf.convert_to_tensor(y)[..., None])) return dataset_evens
Python
UTF-8
3,007
3
3
[]
no_license
import numpy as np from sklearn.cluster import KMeans from math import log import random class FTL_online: def __init__(self, k, d): self.current = FTL(np.array([[0] * d for i in range(k)]), k, d) self.next = self.current self.X = [] self.k = d self.d = d def choose(self): self.current = self.next def observeOutcome(self, x_t): self.X.append(x_t) self.next = FTL(np.array(self.X), self.k, self.d) def loss(self, x_t): return self.current.loss(x_t) def get_prophet_loss_so_far(self): return self.next.kmeans.inertia_ /self.d class FTL: def __init__(self, X, k, d): if (X.shape[0] < k): self.kmeans = KMeans(n_clusters=k).fit(np.array([[0]*d for i in range(k)]).reshape(-1, d)) else: self.kmeans = KMeans(n_clusters=k).fit(X.reshape(-1, d)) self.d = d def loss(self, x_t): return -self.kmeans.score(x_t.reshape(-1, self.d))/self.d # MWUA: the multiplicative weights update algorithm class MWUA_FTL: def __init__(self, T, k, d): self.FTLs = [] self.learning_rate = T ** (-1 / 2) * log(T) self.X = [] self.weights = [] self.chosen_expert = None self.k = k self.d = d def choose(self): if self.chosen_expert is None: self.chosen_expert = FTL(np.array([[0] * self.d for i in range(self.k)]), self.k, self.d) else: self.chosen_expert = self.FTLs[self.draw()] def observeOutcome(self, x_t): new_leader = FTL(np.array(self.X + [x_t]), self.k, self.d) self.FTLs.append(new_leader) self.weights.append(1) for x in self.X: single_loss = new_leader.loss(x) self.weights[-1] *= (1 - self.learning_rate * single_loss) for i, obj in enumerate(self.FTLs): self.weights[i] *= (1 - self.learning_rate * obj.loss(x_t)) self.X.append(x_t) def loss(self, x_t): if (self.chosen_expert is None): return 1 return self.chosen_expert.loss(x_t) def get_prophet_loss_so_far(self): return self.FTLs[-1].kmeans.inertia_ /self.d def draw(self): choice = random.uniform(0, sum(self.weights)) choiceIndex = 0 for weight in self.weights: choice -= weight if choice <= 0: return choiceIndex choiceIndex += 1 def run(alg, T, gen_data): online_loss = 0 regret = [] X = [] for t in range(T): if (t%50==0): print ('iter',t) alg.choose() x_t = gen_data() alg.observeOutcome(x_t) l_t = alg.loss(x_t) online_loss += l_t X.append(x_t) prophet = alg.get_prophet_loss_so_far() regret.append(online_loss-prophet) print('final regret', regret[-1]) print('online', online_loss, 'prophet',prophet) return (regret, online_loss, prophet, alg)
Python
UTF-8
87,989
2.78125
3
[]
no_license
""" .. module:: merlin This is the main module containing the core objects in the system as well as some bootstrap and helper functions. .. moduleauthor:: Sam Win-Mason <sam@lemonadelabs.io> """ import itertools import logging import warnings import uuid import json import importlib from datetime import datetime from enum import Enum from json.decoder import JSONDecodeError from typing import (Iterable, Set, Mapping, Any, List, MutableSequence, Dict, # @UnusedImports Union, MutableSet, MutableMapping) # @UnusedImports class SimObject: """ Basic properties of all sim objects. """ def __init__(self, name: str=''): self.id = int(uuid.uuid4()) # type: int """auto-generated UUID""" self.name = name or str(self.id) """name or self.id (default)""" self._telemetry = dict() # type: MutableMapping[str, Iterable[Any]] """ Stores a series of properties and time series of values for that property """ def reset_telemetry(self) -> None: self._telemetry = dict() def set_telemetry_value(self, prop: str, value: Any) -> None: if prop not in self._telemetry: self._telemetry[prop] = list() self._telemetry[prop].append(value) def get_telemetry_data(self) -> Mapping[str, Iterable[Any]]: return self._telemetry class Simulation(SimObject): """ A representation of a network with its associated entities, ruleset, scenarios and outputs. Any new :py:class:`.Entity` needs to be added to the simulation with the :py:meth:`.add_entities` methods. """ def __init__(self, ruleset=None, config=None, outputs=None, name=''): super(Simulation, self).__init__(name) self._entities = set() # type: MutableSet[Entity] self._messages = list() # type: List[MerlinMessage] self.ruleset = ruleset # type: Ruleset self.initial_state = config or [] self.source_entities = set() # type: MutableSet[Entity] self.outputs = outputs or set() # type: MutableSet[Output] self.num_steps = 1 # type: int self.current_step = 1 # type: int self.run_errors = list() # type: List[MerlinException] self.verbose = True # type: bool def _run_senario_events(self, scenarios: List['Scenario']) -> None: for s in scenarios: for e in s.events: if (e.time + s.start_offset) == self.current_step: for a in e.actions: a.execute(self) def _get_object_telemetry(self, so: SimObject) -> Mapping[str, Any]: return { 'type': so.__class__.__name__, 'id': so.id, 'name': so.name, 'data': so.get_telemetry_data()} def find_sim_object( self, so_id: Union[str, int], so_type: str): """ Depending on the type of so_id, will attempt a name or an id find. If so_id is an int, an id lookup is performed. If so_id is a str then the name search is performed. :param so_id: the int id or str name of the object to find :param so_type: the type of the object to find :return: the SimObject or None if it could not be found """ search_dict = None if type(so_id) is int: id_search = { 'Entity': lambda s_id: [self.get_entity_by_id(s_id)], 'Output': lambda s_id: [ o for o in self.outputs if o.id == s_id], 'Process': lambda s_id: [self.get_process_by_id(s_id)], 'ProcessProperty': lambda s_id: [ pp for pp in itertools.chain.from_iterable( [p.get_properties() for p in self.get_processes()]) if pp.id == s_id], 'OutputConnector': lambda s_id: [ o for o in itertools.chain.from_iterable( [e.outputs for e in self._entities]) if o.id == s_id], 'InputConnector': lambda s_id: [ i for i in itertools.chain.from_iterable( [e.inputs for e in self._entities]) if i.id == s_id], 'Endpoint': lambda s_id: [ ep for ep in itertools.chain.from_iterable( [o.get_endpoint_objects() for o in itertools.chain.from_iterable( [e.outputs for e in self._entities])]) if ep.id == s_id] } search_dict = id_search elif type(so_id) is str: name_search = { 'Entity': lambda s_name: [self.get_entity_by_name(s_name)], 'Output': lambda s_name: [ o for o in self.outputs if o.name == s_name ], 'Process': lambda s_name: [self.get_process_by_name(s_name)], 'ProcessProperty': lambda s_name: [ pp for pp in itertools.chain.from_iterable( [p.get_properties() for p in self.get_processes()]) if pp.name == s_name], 'OutputConnector': lambda s_name: [ o for o in itertools.chain.from_iterable( [e.outputs for e in self._entities]) if o.name == s_name], 'InputConnector': lambda s_name: [ i for i in itertools.chain.from_iterable( [e.inputs for e in self._entities]) if i.name == s_name], 'Endpoint': lambda s_name: [ ep for ep in itertools.chain.from_iterable( [o.get_endpoint_objects() for o in itertools.chain.from_iterable( [e.outputs for e in self._entities])]) if ep.name == s_name] } search_dict = name_search if search_dict: # Combined connector search if so_type == 'Connector': result = search_dict.get( 'InputConnector', lambda s: [])(so_id) + \ search_dict.get( 'OutputConnector', lambda s: [])(so_id) else: result = search_dict.get(so_type, lambda s: [])(so_id) if len(result) == 0 or result[0] is None: return None else: return result[0] else: return None def parent_entity( self, parent_entity: 'Entity', child_entity: 'Entity') -> None: child_entity.parent = parent_entity parent_entity.add_child(child_entity) def disconnect_entities( self, from_entity: 'Entity', to_entity: 'Entity', unit_type: str) -> None: """ Disconnects the connector of unit_type between from_entity and to_entity :param Entity from_entity: :param Entity to_entity: :param str unit_type: """ i_con = to_entity.get_input_by_type(unit_type) o_con = from_entity.get_output_by_type(unit_type) if i_con and o_con: o_con.remove_input(i_con) to_entity.inputs.remove(i_con) def connect_entities( self, from_entity, to_entity, unit_type, input_additive_write=False, apportioning=None): """ :param Entity from_entity: :param Entity to_entity: :param str unit_type: the exact InputConnector and OutputConnector are identified by their ``type`` attribute. :param bool input_additive_write: sets ``additive write`` for the :py:class:`InputConnector` (only if not already exists!) :param ApportioningRules apportioning: sets apportioning rule for :py:class:`.OutputConnector` (only if not already exists!) """ o_con = from_entity.get_output_by_type(unit_type) i_con = to_entity.get_input_by_type(unit_type) if not o_con: o_con = OutputConnector( unit_type, from_entity, name='{0}_output'.format(unit_type), apportioning=apportioning) if not i_con: i_con = InputConnector( unit_type, to_entity, name='{0}_input'.format(unit_type), additive_write=input_additive_write) i_con.source = o_con o_con.add_input(i_con) from_entity.add_output(o_con) to_entity.add_input(i_con) def connect_output( self, entity, output, input_additive_write=False, apportioning=None): """ :param Entity entity: :param Output output: :param bool input_additive_write: sets ``additive write`` for the :py:class:`InputConnector` (only if not already exists!) :param ApportioningRules apportioning: sets apportioning rule for :py:class:`.OutputConnector` (only if not already exists!) """ if output not in self.outputs: return o_con = entity.get_output_by_type(output.type) if not o_con: o_con = OutputConnector( output.type, entity, name='{0}_output'.format(output.type), apportioning=apportioning) i_con = InputConnector( output.type, output, name='{0}_input_from_{1}'.format(output.type, entity.id), additive_write=input_additive_write) i_con.source = o_con o_con.add_input(i_con) entity.add_output(o_con) if i_con not in output.inputs: output.inputs.add(i_con) def set_time_span(self, num_months): """ :param int num_months: number of months, acts as default stop value for :py:meth:`pymerlin.merlin.Simulation.run`. So, without parameters ``run`` will run from ``1`` to ``num_months`` (inclusive). """ self.num_steps = num_months def add_attributes(self, ats): """ :param iterable with str ats: iterable with string identifiers the attributes identify the entities as assets, resources, branch, ... used in the parameter for instantiating :py:class:`pymerlin.merlin.Entity`. """ warnings.warn("Simulation.add_attributes to be phased out", DeprecationWarning) def get_attributes(self): """ :returns: a set of all attributes in this model :rtype: set(strings) return attributes as a set of strings (not iterator). """ atts = set() # get an iterator of all changes atts |= {a for e in self.get_entities() for a in e.attributes} atts |= {a for e in self.outputs for a in e.attributes} return atts def add_unit_types(self, uts): """ :param iterable with str uts: iterable with string identifiers for units used for instantiating :py:class:`pymerlin.merlin.ProcessOutput`, :py:class:`pymerlin.merlin.ProcessInput` and by :py:meth:`pymerlin.merlin.Simulation.connect_entities` """ warnings.warn("Simulation.add_unit_types to be phased out", DeprecationWarning) def get_unit_types(self): """ :returns: a set of all units in this model :rtype: set(strings) return attributes as a set of strings (not iterator). """ units = set() units |= {o.type for o in self.outputs} # get units/unit_types/types from output and input connectors for e in self.get_entities(): units |= {o.type for o in e.outputs} units |= {i.type for i in e.inputs} for p in e.get_processes(): units |= {o.type for o in p.outputs.values()} units |= {i.type for i in p.inputs.values()} return units def is_attribute(self, a): return a in self.get_attributes() def is_unit_type(self, ut): return ut in self.get_unit_types() def set_source_entities(self, entities): """ these entities are set as source entities, i.e. started first """ for e in entities: if e in self._entities and e not in self.source_entities: self.source_entities.add(e) def get_entities(self): return self._entities def add_entities(self, es): """ adds entities ``es`` to the simulation, but does not nest them into any :py:class:`.Entity`s """ for e in es: self.add_entity(e) def add_output(self, o): if o not in self.outputs: self.outputs.add(o) o.sim = self def add_entity(self, e, is_source_entity=False, parent=None): """ :param Entity e: The entity to add :param bool is_source_entity: a process containing entity, which has no inputs, so it is "naturally" a start of processing. :param .Entity parent: the parent entity, None if contained in simulation if not, the parent is the entity containing ``e`` and ``parent.add_child(e)`` needs to be called as well. """ if e not in self._entities: self._entities.add(e) e.parent = parent e.sim = self if is_source_entity: self.source_entities.add(e) def remove_entity(self, e): """ :param .Entity e: entity to be removed removes an entity if existing """ if e in self._entities: self._entities.remove(e) def get_entity_by_name(self, name) -> 'Entity': for e in self._entities: if e.name == name: return e return None def get_entity_by_id(self, e_id): for e in self._entities: if e.id == e_id: return e return None def get_processes(self) -> List['Process']: return itertools.chain.from_iterable( [e.get_processes() for e in self._entities]) def get_process_by_name(self, name): for e in self._entities: p = e.get_process_by_name(name) if p: return p return None def get_process_by_id(self, pid): for e in self._entities: p = e.get_process_by_id(pid) if p: return p return None def init_state(self): for action in self.initial_state: action.execute(self) def get_last_run_errors(self): return list(self.run_errors) def validate(self): # TODO: Write basic validation function for sim return True def log_message( self, message_type: 'MerlinMessage.MessageType', sender: SimObject, msg_id: str="", msg: str="", context: List[SimObject]=list()): m = MerlinMessage( message_type, self.current_step, sender, msg_id, msg, context) self._messages.append(m) def get_run_messages(self) -> List[Dict[str, Any]]: return [m.serialize() for m in self._messages] def get_sim_telemetry(self) -> List[Dict[str, Any]]: output = list() for o in self.outputs: output.append(self._get_object_telemetry(o)) for e in self.get_entities(): connector_to_pinput = dict() for p in e.get_processes(): for pprop in p.get_properties(): output.append(self._get_object_telemetry(pprop)) for pinput in p.inputs.values(): if pinput.connector.id not in connector_to_pinput: connector_to_pinput[pinput.connector.id] = list() connector_to_pinput[pinput.connector.id].append(pinput) for i in e.inputs: # coalese all consumers of this import # into a single time series if i.id in connector_to_pinput: master_consume = list() master_consume += [0.0] * (self.num_steps - len(master_consume)) pinputs = connector_to_pinput[i.id] for pi in pinputs: if 'consume' in pi.get_telemetry_data(): td = pi.get_telemetry_data()['consume'] for x in range(0, len(td)): master_consume[x] += td[x] for x in master_consume: i.set_telemetry_value('consume', x) # logging.info("id: {0}, name: {1}".format(i.id, i.name)) output.append(self._get_object_telemetry(i)) for o in e.outputs: output.append(self._get_object_telemetry(o)) # Append run messages ms = dict() ms['messages'] = self.get_run_messages() output.append(ms) return output def run( self, start: int=1, end: int=-1, scenarios: List['Scenario']=list()) -> None: """ :param int start: :param int end: :param List[Scenario] scenarios: runs the simulation in end-start+1 steps, where the end defaults to and is limited to ``self.num_steps``. Start is 1 or higher. """ start_time = datetime.now() logging.info("Merlin simulation {0} started".format(self.name)) self.run_errors.clear() self._messages.clear() if end > self.num_steps: self.num_steps = end sim_start = start if start > 1 else 1 sim_end = end if (0 < end < self.num_steps) else self.num_steps # clear data from the last run for o in self.outputs: o.reset() # call reset on all processes for e in self._entities: e.reset() # run all the steps in the sim for t in range(sim_start, sim_end+1): logging.info('Simulation step {0}'.format(t)) self.current_step = t self._run_senario_events(scenarios) # get sim outputs for se in self.source_entities: try: se.tick(t) except InputRequirementException as e: self.run_errors.append(e) logging.info( "pymerlin simulation {0} finished in {1}".format( self.name, datetime.now() - start_time)) class Output(SimObject): """ A network flow sink. """ def __init__(self, unit_type, name=''): """ :param str unit_type: the string identifying the unit of the output value :param str name: the name string for the base class. This collects the outputs for a branch or department from the different entities containing :py:class:`pymerlin.merlin.Process`. ``unit_type`` needs to be added to the simulation with :py:meth:`pymerlin.merlin.add_unit_types`. :attr:`minimum` sets a minimum expectation to the output value, which needs to be met or a warning will be flagged. """ super(Output, self).__init__(name) self.inputs = set() # type: Set[InputConnector] self.current_time = None # type: int self.type = unit_type self.result = list() # type: MutableSequence[float] self.sim = None # type: Union[Simulation, None] self.minimum = None self.attributes = set() # type: Set[str] self.updated = False def reset(self): self.result.clear() self.current_time = None self.reset_telemetry() self.updated = False for i in self.inputs: i.reset_telemetry() def tick(self, time): if self.current_time and time < self.current_time: return if (self.current_time is None) or (time > self.current_time): self.current_time = time self.updated = False if time == self.current_time: # need to check if we have all inputs updated before processing up_to_date = True for i in self.inputs: up_to_date = up_to_date and (i.time == self.current_time) if up_to_date and not self.updated: self.updated = True o = 0.0 for i in self.inputs: o += i.value self.result.append(o) if self.minimum and o < self.minimum: self.sim.log_message( MerlinMessage.MessageType.warn, self, "{0}_output_below_min".format(self.id), ("Output value {0} of type {1} has fallen " + "below the minimum of {2}").format( o, self.type, self.minimum) ) self.set_telemetry_value('value', o) class Entity(SimObject): """ A node in the network. Commonly used to represent a business capability, a resource or an asset. Entities can contain processes that modify data arriving at the entity's input connectors or generate new data that gets written to the entity's output connectors. """ def __init__( self, simulation: Simulation=None, name: str='', attributes: Set[str]=set()): super(Entity, self).__init__(name) self._processes = dict() # type: Dict[int, Set['Process']] self.sim = simulation # type: Simulation self.attributes = set(attributes) # shallow copy self.inputs = set() # type: Set[InputConnector] self.outputs = set() # type: Set[OutputConnector] self.parent = None # type: Union[None, Entity] self._children = set() # type: MutableSet[Entity] self.current_time = None # type: int self.processed = False # type: bool def __str__(self): return """ <Entity: {7}> name: {0}, attributes: {1}, inputs: {2}, outputs: {3}, parent: {4}, children: {5}, processes: {6} """.format( self.name, self.attributes, self.inputs, [(id(o), o.type) for o in self.outputs], "None" if self.parent is None else ( id(self.parent), self.parent.name), [(id(c), c.name) for c in self._children], self._processes, id(self)) def create_process( self, process_class: type, params: Dict[str, Any], priority: int=100) -> 'Process': """ Creates a new process inside the entity and wires up the appropriate inputs and outputs afterward. This is the proper way to create processes going forward. :param process_class: the type of the process to create :param params: the keyword arguments to the constructor of the process :param priority: the priority of the process, lower = higher priority :return: The newly created Process """ new_proc = process_class(**params) # type: Process new_proc.default_params = params new_proc.priority = priority self._add_process(new_proc) return new_proc def add_child(self, entity): if entity not in self._children: self._children.add(entity) entity.parent = self entity.sim = self.sim def remove_child(self, entity_id): child_to_remove = None for c in self._children: if c.id == entity_id: child_to_remove = c if child_to_remove: child_to_remove.parent = None self._children.remove(child_to_remove) def get_children(self): return self._children def get_child_by_id(self, entity_id): for c in self.get_children(): if c.id == entity_id: return c return None def get_child_by_name(self, entity_name): for c in self.get_children(): if c.name == entity_name: return c return None def add_input(self, input_con): if input_con not in self.inputs: input_con.parent = self self.inputs.add(input_con) def add_output(self, output_con): if output_con not in self.outputs: output_con.parent = self self.outputs.add(output_con) def reset(self): """ resets all processes in this entity to prepare for a new simulation run, (i.e. executing the ``tick`` method several times in sequence governed by the connector network. """ self.current_time = None self.processed = False for i in self.inputs: i.reset_telemetry() for o in self.outputs: o.reset_telemetry() self.reset_telemetry() procs = self._processes.values() for ps in procs: for p in ps: p.reset_telemetry() p.reset() for p_inputs in p.inputs.values(): p_inputs.reset_telemetry() for p_output in p.outputs.values(): p_output.reset_telemetry() for pprop in p.get_properties(): pprop.reset_telemetry() pprop.reset() def remove_process(self, proc_id): proc = self.get_process_by_id(proc_id) if proc: proc.parent = None for po in proc.outputs.values(): po.connector = None for pi in proc.outputs.values(): pi.connector = None self._processes[proc.priority].remove(proc) def get_processes(self) -> List['Process']: procs = self._processes.values() output = [] for ps in procs: output += ps return output def get_process_by_name(self, proc_name) -> 'Process': procs = self._processes.values() for ps in procs: for p in ps: if p.name == proc_name: return p return None def get_process_by_id(self, proc_id): procs = self._processes.values() for ps in procs: for p in ps: if p.id == proc_id: return p return None def get_connector_by_id(self, cid): connectors = self.inputs.union(self.outputs) print(connectors) for c in connectors: if c.id == cid: return c return None def get_output_by_type(self, unit_type) -> 'OutputConnector': for o in self.outputs: if o.type == unit_type: return o return None def get_input_by_type(self, unit_type) -> 'InputConnector': for o in self.inputs: if o.type == unit_type: return o return None def tick(self, time): """ :param int time: tick integer Executes all processes within an entity if all inputs are updated. Once all processes are executed with :py:meth:`.Process.compute`, the control flow goes depth-first to :py:meth:`.Output.tick`. """ logging.debug('Entity {0} received tick {1}'.format(self.name, time)) if self.current_time and time < self.current_time: return if (self.current_time is None) or (time > self.current_time): logging.debug("Entity {0} time updated".format(self.name)) self.processed = False self.current_time = time if time == self.current_time and not self.processed: # need to check if we have all inputs updated before processing up_to_date = True for i in self.inputs: # logging.debug(i) up_to_date = up_to_date and (i.time == self.current_time) if up_to_date: logging.debug( "Entity {0} inputs are all refreshed, processing..".format( self.name)) self._process() self._update_process_telemetry() def _add_process(self, proc): """ adds a :py:class:`pymerlin.merlin.Process` to an entity. If the Entity is already connected to other entities and the process inputs/outputs are matching, they are connected accordingly. This matching is done by ``type``! """ # first check to see if the proc has already been added. if proc.id in [p.id for p in self.get_processes()]: return if proc.priority in self._processes.keys(): self._processes[proc.priority].add(proc) else: self._processes[proc.priority] = {proc} proc.parent = self # Connect process outputs to entity outputs. # Create entity outputs if they don't exist. for po in proc.outputs.values(): o_con = self.get_output_by_type(po.type) if not o_con: o_con = OutputConnector( po.type, self, name='{0}_output'.format(po.type)) self.add_output(o_con) po.connector = o_con # Connect process inputs to entity inputs # Create entity inputs if they don't exist for pi in proc.inputs.values(): i_con = self.get_input_by_type(pi.type) if not i_con: i_con = InputConnector( pi.type, self, name='{0}_input'.format(pi.type)) self.add_input(i_con) pi.connector = i_con def _update_process_telemetry(self): if self._processes.keys(): for i in self._processes.keys(): for proc in self._processes[i]: for pprop in proc.get_properties(): pprop.set_telemetry_value('value', pprop.get_value()) def _process(self): self.processed = True if self._processes.keys(): for i in sorted(self._processes.keys()): for proc in self._processes[i]: logging.debug( "Computing level {0} process {1}".format(i, proc.name)) proc.compute(self.current_time) for pp in proc.get_properties(): pp.changed = False for o in self.outputs: o.tick() class Process(SimObject): """ A generator, processor and/or consumer of units Makes up the core of the graph processing and is considered abstract. Must be sub-classed to create specific processes. Things to override in the subclass: * :py:attr:`inputs`: dictionary with ``{name: ProcessInput}`` * :py:attr:`outputs`: dictionary with ``{name: ProcessOutput}`` * :py:attr:`props`: process_properties dictionary with ``{name: ProcessProperty}`` * :py:attr:`compute` and * :py:attr:`reset` if this process has internal states. The process object is added to an :py:class:`pymerlin.merlin.Entity` using the :py:meth:`pymerlin.merlin.Enitity.add_process` method *AFTER* the entities are connected to each other. """ def __init__(self, name: str=''): super(Process, self).__init__(name) self.parent = None # type: Entity self.priority = 1000 """ This number influences the execution order of the compute methods. The lower the number the earlier the compute method of this process will be executed. Processes with the same priority will be executed in an arbitrary order. To easily assign higher or lower priorities than the standard, the default is set to 1000. The priority needs to be an integer between 0 and +32767 incl. (this restriction comes from django's model implementation). """ self.inputs = dict() # type: Dict[str, 'ProcessInput'] self.outputs = dict() # type: Dict[str, 'ProcessOutput'] self.props = dict() # type: Dict[str, 'ProcessProperty'] self.default_params = dict() # type: Dict[str, Any] def get_prop(self, name) -> 'ProcessProperty': """ :return: the property with this name, None otherwise :rtype: :py:class:`pymerlin.merlin.ProcessProperty` """ if name in self.props: return self.props[name] else: # check SimObject name prop for pp in self.get_properties(): if pp.name == name: return pp return None def get_prop_value(self, name): """ :return: the current (?) value of the property with this name, None otherwise :rtype: the type as indicated by :py:attr:`pymerlin.merlin.ProcessProperty.type`. """ p = self.get_prop(name) if p: return p.get_value() else: return None def get_properties(self) -> List['ProcessProperty']: """ :returns: an iterable of all :py:class:`.ProcessProperty` objects """ return self.props.values() # create interface to self.inputs and self outputs to hide the # implementation details of the connectors def add_input(self, name, unit, connector=None): """ :param str name: to identify within :py:class:`.Process` :param InputConnector connector: An optional input connector to bind to :param str unit: unit of this output, used for connecting the :py:class:`.ProcessInput` with the :py:class:`.Entity`s connectors. """ inp = ProcessInput(name, unit, connector) self.inputs[name] = inp def add_output(self, name, unit): """ :param str name: to identify within :py:class:`.Process` :param str unit: unit of this output, used for connecting the :py:class:`.ProcessInput` with the :py:class:`.Entity`s connectors. """ out = ProcessOutput(name, unit) self.outputs[name] = out def add_property(self, display_name, name, property_type, default_value, read_only=False): """ :param :param str display_name: will be exposed to front-end and is more expressive than name :param str name: to identify within :py:class:`.Process` :param PropertyType property_type: the representation of the value :param float default_value: the default value :param bool read_only: Specifies if the created pp is read_only """ if name in self.props: raise KeyError("property %s already exists" % (name,)) prop = ProcessProperty( display_name, property_type=property_type, default=default_value, parent=self, readonly=read_only) self.props[name] = prop def remove_property(self, name): self.props[name].parent = None del self.props[name] def write_zero_to_all(self): """ Writes zero to all outputs """ for k in self.outputs.keys(): self.outputs[k].connector.write(0.0) def consume_all_inputs(self, absValue=float("inf"), relValue=1.0): """ :param float absValue: optional absolute value :param float relValue: optional relative value :returns: None by default this method consumes all available input. consumes everything available from all inputs """ for k in self.inputs: self.consume_input(k, min(absValue, relValue*self.get_input_available(k))) def provide_output(self, name, value): """ :param str name: name of output :param float value: the value made available/produced at the actual tick :returns: None """ self.outputs[name].connector.write(value) def get_input_available(self, name): """ :param str name: the name of the input :returns: the value provided/apportioned for the recent tick """ return self.inputs[name].connector.value def consume_input(self, name, value): """ :param str name: name of input :param float value: the value consumed at the actual tick :returns: None """ assert self.get_input_available(name) >= value, \ "consuming more input than available" self.inputs[name].consume(value) def notify_insufficient_input(self, name, available, required): assert name in self.inputs self.parent.sim.log_message( MerlinMessage.MessageType.warn, self, "{0}_{1}_insufficent_input".format(self.name, name), ("There is not enough {{{{{0}}}}} provided as an input. " + "We needed {1} but got {2}").format( self.inputs[name].type, required, available), context=list([self.inputs[name].connector]) ) def compute(self, tick): """ :param int tick: the actual tick from :py:meth:`pymerlin.merlin.Simulation.run` :return: None, see below for handling of compute results Called on each process every simulation step. override with your custom process function. Use the method :py:meth:`pymerlin.merlin.ProcessOutput.write` to provide the output value. The output write function allows the dependent processes to be executed, so even if nothing is produced, a ``write(0)`` is expected. .. code-block:: python3 self.outputs["licensesPrinted"].connector.write(licenseNo) Use the :py:class:`pymerlin.merlin.InputConnector` to access the inputs available: .. code-block:: python3 available = self.inputs['$'].connector.value self.inputs['$'].connector.consume(utilized) If a processes input requirement isn't met, raise an :py:exc:`pymerlin.merlin.InputRequirementException`. To allow the processes "downstream" to be executed, use a ``write(0)`` before raising the exception .. note:: It is safe to assume that :py:meth:`reset`, is called before this method. """ print("This process does absolutely nothing") def reset(self): """ Called at the start of a simulation run on each process so the process can initialize itself if necessary. override with your custom reset code. This method is called for all entities by :py:meth:`pymerlin.merlin.Simulation.run`. """ pass class ProcessInput(SimObject): """ :param str name: name for :py:attr:`pymerlin.merlin.SimObject.name` :param str unit_type: string identifying the unit of the output value :param object connector: saved, but not used right now The outputs and inputs are connected via the entities using :py:meth:`pymerlin.merlin.Simulation.connect_entites` matching up the unit types. The name on the front-end is the :py:attr:`.InputConnector.name`. """ def __init__(self, name, unit_type, connector=None): super(ProcessInput, self).__init__(name) self.type = unit_type # type: str self.connector = connector # type: InputConnector def __str__(self): return """ <ProcessInput {2}> type: {0} connector: {1}""".format(self.type, self.connector, id(self)) def consume(self, value): self.set_telemetry_value('consume', value) self.connector.value -= value class ProcessOutput(SimObject): def __init__(self, name, unit_type, connector=None): """ :param str name: name for :py:attr:`pymerlin.merlin.SimObject.name` :param str unit_type: string identifying the unit of the output value :param object connector: saved, but not used right now Used to define the outputs of a :py:class:`pymerlin.merlin.Process`. The outputs and inputs are connected via the entities using :py:meth:`pymerlin.merlin.Simulation.connect_entites` matching up the unit types. The unit needs to be registered with :py:meth:`pymerlin.Simuation.add_unit_types` The name on the front-end is the :py:attr:`.OutputConnector.name`. """ super(ProcessOutput, self).__init__(name) self.type = unit_type self.connector = connector def __str__(self): return """ <Process Output {0}> type: {1} connector: {2} """.format(id(self), self.type, self.connector) class ProcessProperty(SimObject): """ allows for parameterization of a process, e.g. productivity or cost per piece. the :attr:`.name` appears in the front-end graphics. """ class PropertyType(Enum): bool_type = 1 number_type = 2 int_type = 3 date_type = 4 def __init__( self, name, property_type=PropertyType.number_type, default=0.0, parent=None, readonly=False): """ :param str name: a name for easy identification :param Enum property_type: the type of the property, choose from :py:class:`PropertyType` :param object default: a default value for this property :param Process parent: the process using this property :param readonly: denotes if the field can be changed externally """ super(ProcessProperty, self).__init__(name) self.type = property_type self.max_val = None self.min_val = None self.default = default self.parent = parent self._value = self.default self.readonly = readonly self.changed = False def set_value(self, value): self._value = value self.changed = True def get_value(self) -> float: return self._value def reset(self): self._value = self.default class Connector(SimObject): """ abstract base class for input and output connectors. """ def __init__( self, unit_type, parent, name=''): super(Connector, self).__init__(name) self.type = unit_type self.parent = parent self.time = None class OutputConnector(Connector): """ Represents an outgoing entity connection. Stores the connected :py:class:`.InputConnector`s as :py:class:`.Endpoint`. """ def __init__( self, unit_type, parent, name='', apportioning=None, endpoints=None): """ is created by :py:meth:`.Simulation.connect_entities` or :py:meth:`.Simulation.connect_output`. :param str unit_type: the unit of the value put into this output :param Entity parent: the Entity featuring this output connector. :param .ApportioningRules apportioning: the rule how an output value is split on the inputs, the default is ``weighted``. :param iterable of .InputConnector endpoints: or None to create an empty set. """ super(OutputConnector, self).__init__(unit_type, parent, name) self.apportioning = (self.ApportioningRules.weighted if apportioning is None else apportioning) self._endpoints = endpoints or set() def __str__(self): return """ <OutputConnector> name: {0}, unit_type: {1}, parent: {2}, time: {3}, apportioning: {4}, endpoints: {5} """.format( self.name, self.type, self.parent, self.time, self.apportioning, self.get_endpoints()) class Endpoint(SimObject): """ This class is used to organize the :py:class:`.InputConnector`s which are connected to an :py:class:`.OutputConnector`. The :py:attr:`.bias` allows for a weighted distribution of the values written to the :py:class:`.OutputConnector` instance. On connecting or removing end-points, the biases are recalculated to equal weight. """ def __init__(self, connector=None, bias=0.0): super(OutputConnector.Endpoint, self).__init__(name='Endpoint') self.connector = connector self.bias = bias def __str__(self): return """ <Endpoint> connector: {0}, bias: {1} """.format(self.connector, self.bias) class ApportioningRules(Enum): copy_write = 1 weighted = 2 absolute = 3 def tick(self): """ propagates the control flow along the end-points if they are ready for it, which is decided by the time stamps """ if self.time == self.parent.current_time: for ep in self._endpoints: if ep.connector.time == self.time: ep.connector.parent.tick(self.time) def write(self, value): """ distribute or copy value to the :py:attr:`.Endpoint.connector`. The distribution is governed by :py:class:`.ApportioningRules`, using the values of :py:attr:`.Endpoint.connector.bias`. This method hands over the control flow to what is behind each end-point, resulting in a depth first like iteration. The apportioning rules are: ``copy_write`` The value written is copied to all end-points. ``weighted`` The bias values are used to apportion the value according to the weights. If all weights are 0, the value is split up in even parts over the end-points. ``absolute`` The bias values are used as absolute values, i.e. in the simple case, these values are written to the outputs if their sum is not larger than the value parameter. In more general terms: The end-points are apportioned in to order of decreasing bias. Each endpoint gets the value of bias, if the sum of the values already apportioned is allowing for it. Otherwise it gets the remainder value or 0. """ self.set_telemetry_value('value', value) logging.debug( "WRITING to Output {1} value: {0} ***".format(value, self)) self.time = self.parent.current_time # pre-calculate the values to be written # and provide them in ep_output if self.apportioning is self.ApportioningRules.copy_write: # very simple rule, just copy ep_output = [(ep, value) for ep in self._endpoints] elif self.apportioning is self.ApportioningRules.weighted: # get an ordered version of the end-points eps = list(self._endpoints) biases = [ep.bias for ep in eps] assert all(b >= 0 for b in biases), "biases must not be negative" bias_sum = sum(biases) if bias_sum == 0: # handle no biases set (default case) biases = [1.0]*len(eps) bias_sum = sum(biases) ep_output = zip(eps, (b/bias_sum*value for b in biases)) elif self.apportioning is self.ApportioningRules.absolute: # get sorted list of end-points, start with biggest one! eps = list(sorted(self._endpoints, key=lambda ep: ep.bias, reverse=True)) value_remaining = value+0.0 ep_output = [] for ep in eps: out_val = min(value_remaining, max(ep.bias, 0.0)) ep_output.append((ep, out_val)) value_remaining -= out_val else: assert False, ("unexpected apportioning rule value " "{}".format(self.apportioning)) # now do the output writing for ep, dist_value in ep_output: logging.debug("dist_value: {0}".format(dist_value)) ep.connector.write(dist_value) ep.connector.time = self.time def _get_endpoint(self, input_connector): result = None for ep in self._endpoints: if ep.connector == input_connector: result = ep return result def get_endpoints(self) -> 'List[tuple(InputConnector, float)]': """ Get the :py:class:`.InputConnector`s and their biases connected to this :py:class:`.OutputConnector`. :rtype: list :returns: list of (:py:class:`.InputConnector`, bias) """ return [(e.connector, e.bias) for e in self._endpoints] def get_endpoint_objects(self) -> List['OutputConnector.Endpoint']: return list(self._endpoints) def _ballance_bias(self): val = 1.0 / float(len(self._endpoints)) for ep in self._endpoints: ep.bias = val def add_input(self, input_connector): if not self._get_endpoint(input_connector): ep = self.Endpoint(input_connector, 0.0) self._endpoints.add(ep) self._ballance_bias() def remove_input(self, input_connector): ep = self._get_endpoint(input_connector) if ep: self._endpoints.remove(ep) if self._endpoints: self._ballance_bias() else: self.parent.outputs.remove(self) def set_endpoint_bias(self, input_connector, bias): ep = self._get_endpoint(input_connector) if ep: old_bias = ep.bias ep.bias = bias bias_diff = old_bias - bias # redistribute difference amongst other inputs for e in self._endpoints: if e != ep: e.bias = e.bias + bias_diff def set_endpoint_biases(self, biases): """ biases are in the form [(connector, bias)...n] where n is len(self._endpoints) """ if len(biases) != len(self._endpoints): raise MerlinException( "Biases parity must match number of endpoints") else: for b in biases: ep = self._get_endpoint(b[0]) if ep: ep.bias = b[1] else: raise SimReferenceNotFoundException( "endpoint does not exist") class InputConnector(Connector): """ Represents an incoming entity connection. """ def __init__( self, unit_type, parent, name='', source=None, additive_write=False): super(InputConnector, self).__init__(unit_type, parent, name) self.source = source self.additive_write = additive_write self.value = 0.0 def __str__(self): return """ <InputConnector> name: {0}, unit_type: {1}, parent: {2}, time: {3}, additive_write: {4}, source: {5} """.format( self.name, self.type, self.parent, self.time, self.additive_write, self.source) def write(self, value): self.value = (self.value + value) if self.additive_write else value self.set_telemetry_value('value', self.value) class Action(SimObject): """ Represents a creation or modification act for a :class:`.Simulation` Action is considered and abstract class and should be sub-classed to create a specific Action. """ def convert_to_id(self, prop: str): try: prop_id = int(prop) return prop_id except ValueError: return None @classmethod def create_from_dict(cls, actions: List[Dict[str, Any]]) -> 'List[Action]': output = list() for a in actions: output.append(Action._generate_action(a)) return output @classmethod def create(cls, script: str) -> 'List[Action]': """ Parses a MerlinScript string and returns a newly created list of action objects for the supplied merlin simulation. """ output = list() script = script.strip() lines = script.splitlines() # break into tokens for l in lines: l = l.strip() tokens = Action._lex_tokens(l) # print("lexer result = {0}".format(tokens)) output.append( Action._generate_action( Action._parse_action(tokens))) return output @classmethod def create_from_json(cls, json_string: str) -> 'List[Action]': """ Parses a list of actions from a json serilaised string :param str json_string: """ output = list() j = json.loads(json_string) for a in j: output.append(Action._generate_action(a)) return output @classmethod def _lex_tokens(cls, line: str) -> List[str]: """ The lexer function for the script. :param line: :return: a list of tokens """ # Find operator and split operators = [':=', '+', '-', '^', '/', '>'] parts = None for o in operators: parts = line.partition(o) if parts[0] != line: break if parts[0] == line: raise MerlinScriptException( "Parse error. Operator not found in line: {0}".format(line)) if not parts[0] and parts[1] and parts[2]: # print("param part: {0}".format(parts[2])) operand_1_tokens = Action._lex_operand(parts[2]) # print("lex result: {0}".format(operand_1_tokens)) return [parts[1]] + operand_1_tokens else: operand_1_tokens = Action._lex_operand(parts[0]) operand_2_tokens = Action._lex_operand(parts[2]) return operand_1_tokens + [parts[1]] + operand_2_tokens @classmethod def _lex_operand(cls, op_string: str) -> List[str]: output = list() if not op_string: return output op_string = op_string.strip() output.append(op_string.partition(' ')[0]) arguments = op_string.partition(' ')[2] if arguments == op_string: raise MerlinScriptException( "Parse error. Expected type in operand: {0}".format(op_string) ) output += [s.strip() for s in arguments.split(',')] return output @classmethod def _generate_action(cls, a: Dict[str, Any]) -> 'Action': # work out type of action based on ast # Unary expressions if a['operand_2'] is None: if len(a['operand_1']['params']) == 0: raise MerlinScriptException( "Invalid parameter size") if a['op'] == '+': if a['operand_1']['type'] == 'Attribute': try: return AddAttributesAction( [str(p) for p in a['operand_1']['params']]) except Exception: raise MerlinScriptException( "Invalid parameters for AddAttributeAction") elif a['operand_1']['type'] == 'Entity': try: return AddEntityAction( a['operand_1']['params'][0], attributes=a['operand_1']['params'][1:]) except Exception: raise MerlinScriptException( "Invalid parameters for AddEntityAction") elif a['operand_1']['type'] == 'UnitType': try: return UnitTypeAction( [str(p) for p in a['operand_1']['params']]) except Exception: raise MerlinScriptException( "Invalid parameters for AddUnitTypeAction") elif a['op'] == '-': if a['operand_1']['type'] == 'Attribute': raise MerlinScriptException( "Operation RemoveAttribute not supported") elif a['operand_1']['type'] == 'Entity': try: return RemoveEntityAction(a['operand_1']['params'][0]) except Exception: raise MerlinScriptException( "Invalid parameters for RemoveEntityAction") elif a['operand_1']['type'] == 'UnitType': raise MerlinScriptException( "Operation RemoveUnitType not supported") elif a['op'] == ':=': if a['operand_1']['type'] == 'Output': return ModifyOutputMinimumAction( a['operand_1']['params'][0], **(a['operand_1']['props'])) else: raise MerlinScriptException( "Invalid type for unary assignment operator" ) else: raise MerlinScriptException( ("Invalid operator for unary expression, " + "must be +, :=, or -")) else: if len(a['operand_1']['params']) == 0 \ or len(a['operand_2']['params']) == 0: raise MerlinScriptException( "Invalid parameter size") if a['op'] == '+': # Add process action return AddProcessAction( *(a['operand_1']['params'] + a['operand_2']['params']), **{'process_params': a['operand_2']['props']}) if a['op'] == '-': return RemoveProcessAction( *(a['operand_1']['params'] + a['operand_2']['params'])) if a['op'] == ':=': if a['operand_2']['type'] == 'Endpoint': # modify endpoint bias return ModifyEndpointBiasAction( *(a['operand_1']['params'] + a['operand_2']['params']), **a['operand_2']['props']) else: # modify process property if a['operand_2']['props'] is not None: return ModifyProcessPropertyAction( *(a['operand_1']['params'] + a['operand_2']['params']), **a['operand_2']['props']) else: return ModifyProcessPropertyAction( *(a['operand_1']['params'] + a['operand_2']['params'])) if a['op'] == '/': # Disconnect operator return RemoveConnectionAction( *(a['operand_1']['params'] + a['operand_2']['params'])) if a['op'] == '^': # Parent operator return ParentEntityAction( *(a['operand_1']['params'] + a['operand_2']['params'])) if a['op'] == '>': # Connect operator return AddConnectionAction( *(a['operand_1']['params'] + a['operand_2']['params'])) raise MerlinScriptException("No Process match!") @classmethod def _parse_action(cls, tokens) -> Dict[str, Any]: op = Action._parse_op(tokens[0]) if op: # this is a single operand command tokens = tokens[1:] # now look for a type type1 = Action._parse_type(tokens[0]) if type1: # parse type 1 params tokens = tokens[1:] type1_params = Action._parse_params(tokens) tokens = tokens[len(type1_params):] print(tokens) type1_props = Action._parse_props(tokens) return { 'op': op, 'operand_1': { 'type': type1, 'params': type1_params, 'props': type1_props }, 'operand_2': None} else: raise MerlinScriptException( "Syntax Error: {0} is not a valid type".format(tokens[0])) else: type1 = Action._parse_type(tokens[0]) if type1: tokens = tokens[1:] type1_params = Action._parse_params(tokens) tokens = tokens[len(type1_params):] type1_props = Action._parse_props(tokens) tokens = tokens[len(type1_props):] op = Action._parse_op(tokens[0]) if op: tokens = tokens[1:] type2 = Action._parse_type(tokens[0]) if type2: tokens = tokens[1:] type2_params = Action._parse_params(tokens) tokens = tokens[len(type2_params):] type2_props = Action._parse_props(tokens) return \ { 'op': op, 'operand_1': { 'type': type1, 'params': type1_params, 'props': type1_props }, 'operand_2': { 'type': type2, 'params': type2_params, 'props': type2_props } } else: raise MerlinScriptException( "Syntax Error: {0} is not a valid type".format( tokens[0])) else: raise MerlinScriptException( "Syntax Error: Expected an operator, got {0}".format( tokens[0])) else: raise MerlinScriptException( "Syntax Error: {0} is not a valid type".format( tokens[0])) @classmethod def _parse_params(cls, tokens: List[str]) -> List[str]: params = list() for t in tokens: if not t: raise MerlinScriptException( "Invalid param {0}".format(t)) tt = Action._parse_type(t) to = Action._parse_op(t) if ('=' in t) and (':' in t): return params if tt or to: return params else: params.append(t) return params @classmethod def _parse_props(cls, tokens: List[str]) -> Dict[str, Any]: if not tokens: return None props = dict() for t in tokens: tt = Action._parse_type(t) to = Action._parse_op(t) if tt or to: return props else: type_p = t.partition(':') if type_p[0] == t: # print("type partition error {0}".format(t)) return None else: label = type_p[0].strip() value_p = type_p[2].partition('=') if value_p[0] == type_p[2]: print("equality partiton error") return None else: val_type = value_p[0].strip() val = None if val_type == 'bool': val = (value_p[2].strip() == 'True') elif val_type == 'float': val = float(value_p[2].strip()) elif val_type == 'str': val = value_p[2].strip() if not val: raise MerlinScriptException( "invalid type {0}".format(val_type)) props[label] = val return props @classmethod def _parse_type(cls, token): if token in [ 'Entity', 'Attribute', 'UnitType', 'Process', 'Property', 'Output', 'Endpoint' ]: return token else: return None @classmethod def _parse_op(cls, token): if token in ['+', '-', '>', '/', ':=', '^']: return token else: return None def __init__(self): super(Action, self).__init__(name='') def execute(self, simulation: Simulation): pass def serialize(self) -> Dict[str, Any]: return dict() class Event(SimObject): """ An event is a pairing of a time and a list of actions to be executed at that time. A collection of events make up a :class:`pymerlin.Simulation` scenario. """ def __init__( self, actions: List[Action], time: int, name: str='') -> None: super(Event, self).__init__(name) self.actions = actions # type: List[Action] self.time = time # type: int @classmethod def create(cls, time: int, script: str) -> 'Event': try: json.loads(script) instance = cls( Action.create_from_json(script), time) except JSONDecodeError: instance = cls( Action.create(script), time) return instance @classmethod def create_from_dict( cls, time: int, data: List[Dict[str, Any]]) -> 'Event': return cls(Action.create_from_dict(data), time) def get_serialized_event_actions(self) -> List[Dict[str, Any]]: output = list() for a in self.actions: output.append(a.serialize()) return output class Scenario(SimObject): def __init__( self, events: Set[Event], sim: Simulation= None, start_offset: int= None, name: str=''): super(Scenario, self).__init__(name) self.events = events # type: Set[Event] self.sim = sim # type: Simulation self.start_offset = start_offset or 0 # type: int class MerlinMessage: class MessageType(Enum): info = 0 hint = 1 warn = 2 error = 3 def __init__( self, message_type: MessageType, # @UndefinedVariable time: int, sender: SimObject, message_id: str="", message: str="", context: List[SimObject]=list()): self.message_type = message_type # type: MerlinMessage.MessageType self.time = time # type: int self.sender = sender # type: SimObject self.message_id = message_id # type: str self.message = message # type: str context_data = list() for so in context: d = dict() d['id'] = so.id d['type'] = so.__class__.__name__ context_data.append(d) self.context = context_data # type: List[Dict[str, Any] def __str__(self): return self.serialize() def serialize(self) -> Dict[str, Any]: output = dict() output['type'] = self.message_type.value output['time'] = self.time output['sender'] = \ { 'id': self.sender.id, 'type': self.sender.__class__.__name__ } output['message_id'] = self.message_id output['message'] = self.message output['context'] = self.context return output class Ruleset: """ A validation class that checks the integrity of a particular :class:`pymerlin.Simulation` This is an abstract class that must be overridden by a specific ruleset for your simulation. In other words, each simulation will have it's own sub-class of Ruleset. In a future version of pymerlin, it would be desirable to have the rulset be desribed by a configuration file that could be generated from another product or application or written by hand. """ pass # Core package exceptions class MerlinException(Exception): """ Base exception class for Merlin """ def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class InputRequirementException(MerlinException): """ Should be thrown by a process if an input quantity produces a zero output by the compute function. Is used to indicate what input was deficient to make debugging the model easier. """ def __init__(self, process, process_input, input_value, required_input): """ :param Process process: the :py:class:`pymerlin.merlin.Process`, typically the ``self`` of the ``compute`` method. :param ProcessInput process_input: the input, which was found insufficient :param number input_value: the value found insufficient :param number required_input: the (minimum) value expected often used in :py:meth:`pymerlin.merlin.Process.compute`, the simulation does not stop, but the exceptions are caught and collected for reporting/introspection purposes. todo: what if two inputs are insufficient? """ super(InputRequirementException, self).__init__(required_input) self.process = process self.process_input = process_input self.input_value = input_value logging.exception(( "InputRequirementException in process {0} with " + "process input: {1} input value = {2} / required value = " + "{3}").format( self.process.name, self.process_input.name, self.input_value, self.value)) class SimReferenceNotFoundException(MerlinException): def __init__(self, value): super(SimReferenceNotFoundException, self).__init__(value) class EntityNotFoundException(MerlinException): def __init__(self, value): super(EntityNotFoundException, self).__init__(value) class MerlinScriptException(MerlinException): def __init__(self, value): super(MerlinException, self).__init__(value) class AddAttributesAction(Action): """ Adds global attributes to the sim """ def __init__(self, attributes): super(AddAttributesAction, self).__init__() self.attributes = attributes def execute(self, simulation): simulation.add_attributes(self.attributes) def serialize(self) -> Dict[str, Any]: return { 'op': '+', 'operand_1': { 'type': 'Attribute', 'params': self.attributes, 'props': None }, 'operand_2': None } class UnitTypeAction(Action): """ Adds global unittypes to the sim """ def __init__(self, unit_types): super(UnitTypeAction, self).__init__() self.unit_types = unit_types def execute(self, simulation): simulation.add_unit_types(self.unit_types) def serialize(self) -> Dict[str, Any]: return { 'op': '+', 'operand_1': { 'type': 'UnitType', 'params': self.unit_types, 'props': None }, 'operand_2': None } # Entity Actions class RemoveEntityAction(Action): """ Removes an enity from the simulation""" def __init__(self, entity_id): super(RemoveEntityAction, self).__init__() self.entity_id = self.convert_to_id(entity_id) or entity_id def execute(self, simulation): entity_to_remove = simulation.find_sim_object(self.entity_id, 'Entity') if entity_to_remove: self._remove_entity(entity_to_remove) def _remove_entity(self, ent): # remove output connections for o in ent.outputs: eps = o.get_endpoints() for e in eps: e[0].parent.inputs.remove(e[0]) # remove input connections for i in ent.inputs: i.source.remove_input(i) if ent.parent is None: ent.sim.remove_entity(ent) else: ent.parent.remove_child(ent.id) for child in ent.get_children(): self._remove_entity(child) ent.sim.remove_entity(ent) def serialize(self) -> Dict[str, Any]: return { 'op': '-', 'operand_1': { 'type': 'Entity', 'params': [self.entity_id], 'props': None }, 'operand_2': None } class AddEntityAction(Action): """Adds an entity to the Simulation""" def __init__( self, entity_name, attributes=list(), parent=None): super(AddEntityAction, self).__init__() self.attributes = attributes self.entity_name = entity_name self.parent = parent def execute(self, simulation): e = Entity(simulation, self.entity_name, set(self.attributes)) if self.parent == simulation or self.parent is None: simulation.add_entity(e) else: self.parent.add_child(e) def serialize(self) -> Dict[str, Any]: return { 'op': '+', 'operand_1': { 'type': 'Entity', 'params': [self.entity_name], 'props': None }, 'operand_2': None } # Connection Actions class RemoveConnectionAction(Action): """ removes a connecton from an entity """ def __init__( self, from_entity_id, to_entity_id, unit_type): super(RemoveConnectionAction, self).__init__() self.from_entity_id = self.convert_to_id(from_entity_id) or from_entity_id self.to_entity_id = self.convert_to_id(to_entity_id) or to_entity_id self.unit_type = self.convert_to_id(unit_type) or unit_type def execute(self, simulation: Simulation): from_entity = simulation.find_sim_object(self.from_entity_id, 'Entity') to_entity = simulation.find_sim_object(self.to_entity_id, 'Entity') if from_entity and to_entity: simulation.disconnect_entities( from_entity, to_entity, self.unit_type) def serialize(self) -> Dict[str, Any]: return { 'op': '/', 'operand_1': { 'type': 'Entity', 'params': [self.from_entity_id], 'props': None }, 'operand_2': { 'type': 'Entity', 'params': [self.to_entity_id, self.unit_type], 'props': None } } class AddConnectionAction(Action): """ Adds a connection from an entity output to entity input(s). """ def __init__( self, output_entity_id, input_entity_id, unit_type, apportioning=2, additive_write=False): super(AddConnectionAction, self).__init__() self.unit_type = unit_type self.output_entity_id = self.convert_to_id(output_entity_id) or output_entity_id self.input_entity_id = self.convert_to_id(input_entity_id) or input_entity_id self.apportioning = \ OutputConnector.ApportioningRules(int(apportioning)) self.additive_write = bool(additive_write) def execute(self, simulation: Simulation): from_entity = simulation.find_sim_object( self.output_entity_id, 'Entity') to_entity = simulation.find_sim_object( self.input_entity_id, 'Entity') simulation.connect_entities( from_entity, to_entity, self.unit_type, input_additive_write=self.additive_write, apportioning=self.apportioning) def serialize(self) -> Dict[str, Any]: return { 'op': '>', 'operand_1': { 'type': 'Entity', 'params': [self.output_entity_id, self.apportioning], 'props': None }, 'operand_2': { 'type': 'Entity', 'params': [ self.input_entity_id, self.unit_type, self.additive_write], 'props': None } } # Process Actions class RemoveProcessAction(Action): """ Removes a process from an entity """ def __init__(self, entity_id, process_id): super(RemoveProcessAction, self).__init__() self.process_id = self.convert_to_id(process_id) or process_id self.entity_id = self.convert_to_id(entity_id) or entity_id def execute(self, simulation: Simulation): e = simulation.find_sim_object(self.entity_id, 'Entity') p = simulation.find_sim_object(self.process_id, 'Process') e.remove_process(p.id) def serialize(self) -> Dict[str, Any]: return { 'op': '-', 'operand_1': { 'type': 'Entity', 'params': [self.entity_id], 'props': None }, 'operand_2': { 'type': 'Process', 'params': [self.process_id], 'props': None } } class AddProcessAction(Action): """ Adds a process to an entity """ def __init__( self, entity_id, process_class, priority, process_params=None): super(AddProcessAction, self).__init__() self.entity_id = self.convert_to_id(entity_id) or entity_id self.process_class = \ self.get_process_class_from_fullname(process_class) self.process_params = process_params if priority: self.priority = int(priority) else: self.priority = 100 def get_process_class_from_fullname(self, the_name: str) -> type: """ :param str the_name: name used to import the module and find the pymerlin.merlin.Process subclass :returns: the class (not the object!) This is the inverse of the :py:func:`.get_process_class_from_fullname`. """ # split name into parts mod_path = the_name.split(".")[:-1] if len(mod_path): try: namespace = importlib.import_module( ".".join(mod_path)).__dict__ except ImportError: raise ValueError( """module containing process class {0} could not be imported""".format(the_name)) else: # don't like this! namespace = globals() class_def = the_name.split(".")[-1] if class_def not in namespace: raise ValueError('process class %s not found' % the_name) # execute this function return namespace[class_def] def _get_fullname_from_process_class(self, the_class: type) -> str: if not issubclass(the_class, Process): raise TypeError("expecting sub class of pymerlin.merlin.Process") proc_classname = the_class.__name__ proc_module = the_class.__module__ return "{0}.{1}".format(proc_module, proc_classname) def execute(self, simulation): entity = simulation.find_sim_object(self.entity_id, 'Entity') if entity: entity.create_process( self.process_class, self.process_params, priority=self.priority) else: raise EntityNotFoundException(self.entity_id) def serialize(self) -> Dict[str, Any]: return { 'op': '+', 'operand_1': { 'type': 'Entity', 'params': [self.entity_id], 'props': None }, 'operand_2': { 'type': 'Process', 'params': [ self._get_fullname_from_process_class( self.process_class), self.priority ], 'props': self.process_params } } class ModifyProcessPropertyAction(Action): def __init__( self, entity_id, property_id, value, additive=False): super(ModifyProcessPropertyAction, self).__init__() self.entity_id = self.convert_to_id(entity_id) or entity_id self.property_id = self.convert_to_id(property_id) or property_id self.value = float(value) self.additive = additive def execute(self, simulation: Simulation): e = simulation.find_sim_object(self.entity_id, 'Entity') found_prop = simulation.find_sim_object( self.property_id, 'ProcessProperty') for p in e.get_processes(): for prop in p.get_properties(): if prop.id == found_prop.id: if self.additive: prop.set_value(prop.get_value() + self.value) else: prop.set_value(self.value) def serialize(self) -> Dict[str, Any]: return { 'op': ':=', 'operand_1': { 'type': 'Entity', 'params': [self.entity_id], 'props': None }, 'operand_2': { 'type': 'Property', 'params': [self.property_id, self.value], 'props': { 'additive': self.additive } } } class ParentEntityAction(Action): def __init__( self, child_entity_id, parent_entity_id ): super(ParentEntityAction, self).__init__() self.parent_entity_id = self.convert_to_id(parent_entity_id) or parent_entity_id self.child_entity_id = self.convert_to_id(child_entity_id) or child_entity_id def serialize(self) -> Dict[str, Any]: return { 'op': '^', 'operand_1': { 'type': 'Entity', 'params': [self.child_entity_id], 'props': None }, 'operand_2': { 'type': 'Entity', 'params': [self.parent_entity_id], 'props': None } } def execute(self, simulation: Simulation): parent_entity = simulation.find_sim_object( self.parent_entity_id, 'Entity') child_entity = simulation.find_sim_object( self.child_entity_id, 'Entity') if parent_entity and child_entity: simulation.parent_entity(parent_entity, child_entity) class ModifyOutputMinimumAction(Action): def __init__( self, output_id, minimum=None, additive=False ): super(ModifyOutputMinimumAction, self).__init__() self.output_id = self.convert_to_id(output_id) or output_id self.minimum = float(minimum) self.additive = additive def serialize(self) -> Dict[str, Any]: return { 'op': ":=", 'operand_1': { 'type': "Output", 'params': [self.output_id], "props": { 'minimum': self.minimum, 'additive': self.additive } }, 'operand_2': None } def execute(self, simulation: Simulation): output = simulation.find_sim_object(self.output_id, 'Output') if output: if self.additive: output.minimum += self.minimum else: output.minimum = self.minimum class ModifyEndpointBiasAction(Action): def __init__(self, entity_id, endpoint_id, bias=0.0, additive=False): super(ModifyEndpointBiasAction, self).__init__() self.entity_id = self.convert_to_id(entity_id) or entity_id self.endpoint_id = self.convert_to_id(endpoint_id) or endpoint_id self.bias = bias self.additive = additive def serialize(self): return { 'op': ':=', 'operand_1': { 'type': 'Entity', 'params': [self.entity_id], 'props': None }, 'operand_2': { 'type': 'Endpoint', 'params': [self.endpoint_id], 'props': { 'bias': self.bias, 'additive': self.additive } } } def execute(self, simulation: Simulation): e = simulation.find_sim_object(self.entity_id, 'Entity') found_ep = simulation.find_sim_object(self.endpoint_id, 'Endpoint') for o in e.outputs: for ep in o.get_endpoint_objects(): if ep.id == found_ep.id: if self.additive: ep.bias += self.bias else: ep.bias = self.bias break
Java
UTF-8
4,633
2.40625
2
[]
no_license
package com.example.congressapi; import android.content.Context; import android.support.annotation.NonNull; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class BillItemAdapter extends ArrayAdapter<Bill> { public static final String TAG = "BillItemAdapter"; public static List<Bill> billsList; LayoutInflater layoutInflater; public static Context adapterContext; public BillItemAdapter(Context context, List<Bill> objects) { super(context, R.layout.list_item_bill, objects); billsList = objects; layoutInflater = LayoutInflater.from(context); adapterContext = context; } @NonNull @Override // position - position of current item in dataset // convertView - reference to layout (may or may not be null) // // getView() is run for every item in the list view public View getView(int position, View convertView, ViewGroup parent) { // Since convertView may or may not be null because it can be new or resused from a previous item, // we first check here if it is null. if (convertView == null) { convertView = layoutInflater.inflate(R.layout.list_item_bill, parent, false); } // Based on the position of this view, get the associated bill from the billsList created in the // BillsFragment Bill bill = billsList.get(position); // Get handles to the TextViews in the list item layout TextView ID = (TextView) convertView.findViewById(R.id.textView_bill_id); TextView title = (TextView) convertView.findViewById(R.id.textView_bill_title); TextView introduced = (TextView) convertView.findViewById(R.id.textView_bill_introduced); // Set the text in the list item layout ID.setText(bill.getBill_id()); title.setText(bill.getTitle()); introduced.setText(bill.getIntroduced_on_formatted()); // Set the background to our gradient before returning the view. convertView.setBackgroundResource(R.drawable.list_item_bg); return convertView; } // Overrides needed to prevent IndexOutOfBoundsException // when using ArrayAdapter with Filter @Override public int getCount() { return billsList.size(); } @Override public Bill getItem(int pos) { return billsList.get(pos); } @Override public Filter getFilter() { return new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults filteredResults = new FilterResults(); // When we don't define a filter for our adapter, just return the views as-is if(constraint == null || constraint.length() == 0) { filteredResults.values = billsList; filteredResults.count = billsList.size(); } // Otherwise, filter the views based on the constraint // For bills, we are always filtering based on its "active" attribute else { List<Bill> filteredList = new ArrayList<>(); for(Bill b : billsList) { if(constraint.toString().equalsIgnoreCase(b.getActive())) { filteredList.add(b); } } // Set the filtered result values and size filteredResults.values = filteredList; filteredResults.count = filteredList.size(); } return filteredResults; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { // To know how to publish the list view, we need to check to see if we have any results from the filter // or not (count is 0 when filter was not used, so filterResults has no items) if(results.count == 0) { notifyDataSetInvalidated(); } else { billsList = (List<Bill>) results.values; notifyDataSetChanged(); } } }; } }
PHP
UTF-8
23,949
2.8125
3
[ "GPL-2.0-or-later", "GPL-1.0-or-later", "GPL-2.0-only", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
<?php if ( ! defined( 'ABSPATH' ) ) { die( 'You are not allowed to call this page directly.' ); } class FrmProStatisticsController { /** * Returns stats requested through the [frm-stats] shortcode * * @param array $atts * @return string */ public static function stats_shortcode( $atts ) { self::convert_old_atts_to_new_atts( $atts ); self::combine_defaults_and_user_defined_attributes( $atts ); self::format_atts( $atts ); if ( ! isset( $atts['id'] ) || ! $atts['id'] ) { return __( 'You must include a valid field id or key in your stats shortcode.', 'formidable-pro' ); } return self::get_field_stats( $atts['id'], $atts ); } /** * Get the entry IDs for a field, operator, and value combination * * @param array $args * @return array */ public static function get_field_matches( $args ) { $filter_args = self::get_filter_args( $args ); if ( ! $filter_args['field'] ) { return $filter_args['entry_ids']; } else if ( $filter_args['after_where'] && ! $filter_args['entry_ids'] ) { return array(); } return self::get_entry_ids_for_field_filter( $filter_args ); } /** * Flatten multi-dimensional arrays for stats and graphs * * @since 2.02.06 * @param object $field * @param bool $save_other_key * @param array $field_values */ public static function flatten_multi_dimensional_arrays_for_stats( $field, $save_other_key, &$field_values ) { $cleaned_values = array(); foreach ( $field_values as $k => $i ) { FrmProAppHelper::unserialize_or_decode( $i ); if ( ! is_array( $i ) ) { $cleaned_values[] = $i; continue; } if ( $field->type == 'address' || $field->type == 'credit_card' ) { $cleaned_values[] = implode( ' ', $i ); } else { foreach ( $i as $i_key => $item_value ) { if ( $save_other_key && strpos( $i_key, 'other' ) !== false ) { // If this is an "other" option, keep key $cleaned_values[] = $i_key; } else { $cleaned_values[] = $item_value; } } } } $field_values = $cleaned_values; } /** * Remove and convert deprecated attributes * * @since 2.02.06 * @param array $atts */ private static function convert_old_atts_to_new_atts( &$atts ) { if ( isset( $atts['entry_id'] ) ) { $atts['entry'] = $atts['entry_id']; unset( $atts['entry_id'] ); } if ( isset( $atts['round'] ) ) { $atts['decimal'] = $atts['round']; unset( $atts['round'] ); } if ( isset( $atts['value'] ) ) { if ( isset( $atts['id'] ) ) { $field_id = $atts['id']; $atts[ $field_id ] = $atts['value']; } unset( $atts['value'] ); } } /** * Combine the default attributes with the user-defined attributes * * @since 2.02.06 * @param array $atts */ private static function combine_defaults_and_user_defined_attributes( &$atts ) { $defaults = self::get_stats_defaults(); $combined_atts = array(); foreach ( $defaults as $k => $value ) { if ( isset( $atts[ $k ] ) ) { $combined_atts[ $k ] = $atts[ $k ]; unset( $atts[ $k ] ); } else if ( $value !== false ) { $combined_atts[ $k ] = $value; } } $combined_atts['filters'] = $atts; $atts = $combined_atts; } /** * Get the default attributes for stats * * @since 2.02.06 * @return array */ private static function get_stats_defaults() { $defaults = array( 'id' => false, //the ID of the field to show stats for 'type' => 'total', //total, count, average, median, deviation, star, minimum, maximum, unique 'user_id' => false, //limit the stat to a specific user id or "current" 'limit' => false, //limit the number of entries used in this calculation 'drafts' => 0, //don't include drafts by default 'entry' => false, 'thousands_sep' => false, 'decimal' => 2, //how many decimals to include 'dec_point' => false, //any other field ID in the form => the value it should be equal to ); return $defaults; } /** * Format the attributes for stats * * @since 2.02.06 * @param array $atts */ private static function format_atts( &$atts ) { if ( ! isset( $atts['id'] ) || ! $atts['id'] ) { return; } else { $atts['id'] = self::maybe_convert_field_key_to_id( $atts['id'] ); } if ( isset( $atts['user_id'] ) ) { $atts['user_id'] = FrmAppHelper::get_user_id_param( $atts['user_id'] ); } if ( isset( $atts['entry'] ) ) { $atts['entry_ids'] = self::maybe_convert_entry_keys_to_ids( $atts['entry'] ); } } /** * Convert entry keys to IDs * * @since 2.02.06 * @param string $entry_keys * @return array */ private static function maybe_convert_entry_keys_to_ids( $entry_keys ) { $entry_keys = explode( ',', $entry_keys ); $entry_ids = array(); foreach ( $entry_keys as $key ) { $entry_id = self::maybe_convert_entry_key_to_id( $key ); if ( $entry_id ) { $entry_ids[] = $entry_id; } } return $entry_ids; } /** * Returns an entry id unchanged or converts an entry key to an entry id. * * @param $key * * @return int -- entry id */ private static function maybe_convert_entry_key_to_id( $key ) { if ( is_numeric( $key ) ) { return $key; } return FrmEntry::get_id_by_key( $key ); } /** * Convert a field key to an ID * * @since 2.02.06 * @param string $key * @return int|string */ private static function maybe_convert_field_key_to_id( $key ) { if ( ! is_numeric( $key ) ) { $id = FrmField::get_id_by_key( $key ); } else { $id = $key; } return $id; } /** * Get field statistic * * @since 2.02.06 * @param int $id * @param array $atts * @return int|string|float */ private static function get_field_stats( $id, $atts ) { $field = FrmField::getOne( $id ); if ( ! $field ) { return 0; } $meta_values = self::get_meta_values_for_single_field( $field, $atts ); if ( empty( $meta_values ) ) { $statistic = 0; } else { $statistic = self::get_stats_from_meta_values( $atts, $meta_values ); } if ( 'star' === $atts['type'] ) { $statistic = self::get_stars( $field, $statistic ); } return $statistic; } /** * Get the meta values for a single stats field * * @since 2.02.06 * @param object $field * @param array $atts * @return array */ private static function get_meta_values_for_single_field( $field, $atts ) { $atts['form_id'] = $field->form_id; $atts['form_posts'] = self::get_form_posts_for_statistics( $atts ); self::check_field_filters( $atts ); // If there are field filters and entry IDs is empty, stop now if ( ! empty( $atts['filters'] ) && empty( $atts['entry_ids'] ) ) { return array(); } $meta_args = self::package_filtering_arguments_for_query( $atts ); $field_values = FrmProEntryMeta::get_all_metas_for_field( $field, $meta_args ); self::format_field_values( $field, $atts, $field_values ); return $field_values; } /** * Get the stars for a given statistic * * @since 2.02.06 * @param object $field * @param int $stat * @return string */ private static function get_stars( $field, $value ) { $atts = array( 'html' => true ); // force star field type to get stats $field->type = 'star'; return FrmFieldsHelper::get_unfiltered_display_value( compact( 'value', 'field', 'atts' ) ); } /** * Calculate a count, total, etc from a field's meta values * * @since 2.02.06 * @param array $atts * @param array $meta_values * @return int */ private static function get_stats_from_meta_values( $atts, $meta_values ) { $count = count( $meta_values ); if ( $atts['type'] != 'count' ) { $total = array_sum( $meta_values ); } else { $total = 0; } switch ( $atts['type'] ) { case 'average': case 'mean': case 'star': $stat = ( $total / $count ); break; case 'median': $stat = self::calculate_median( $meta_values ); break; case 'deviation': $mean = ( $total / $count ); $stat = 0.0; foreach ( $meta_values as $i ) { $stat += pow( $i - $mean, 2 ); } if ( $count > 1 ) { $stat /= ( $count - 1 ); $stat = sqrt( $stat ); } else { $stat = 0; } break; case 'minimum': $stat = min( $meta_values ); break; case 'maximum': $stat = max( $meta_values ); break; case 'count': $stat = $count; break; case 'unique': $stat = array_unique( $meta_values ); $stat = count( $stat ); break; case 'total': default: $stat = $total; } return self::get_formatted_statistic( $atts, $stat ); } /** * Calculate the median from an array of values * * @since 2.03.08 * * @param array $meta_values * * @return float */ public static function calculate_median( $meta_values ) { $count = count( $meta_values ); rsort( $meta_values ); $middle_index = (int) floor( $count / 2 ); if ( $count % 2 > 0 ) { // Odd number of values $median = (float) $meta_values[ $middle_index ]; } else { // Even number of values, calculate avg of 2 medians $low_middle = $meta_values[ $middle_index - 1 ]; $high_middle = $meta_values[ $middle_index ]; $median = (float) ( $low_middle + $high_middle ) / 2; } return $median; } /** * Get the formatted statistic value * * @since 2.02.06 * @param array $atts * @param float $stat * @return float|string */ private static function get_formatted_statistic( $atts, $stat ) { if ( isset( $atts['thousands_sep'] ) || isset( $atts['dec_point'] ) ) { $dec_point = isset( $atts['dec_point'] ) ? $atts['dec_point'] : '.'; $thousands_sep = isset( $atts['thousands_sep'] ) ? $atts['thousands_sep'] : ','; $statistic = number_format( $stat, $atts['decimal'], $dec_point, $thousands_sep ); } else { $statistic = round( $stat, $atts['decimal'] ); } return $statistic; } /** * Get form posts * * @since 2.02.06 * @param array $atts * @return mixed */ private static function get_form_posts_for_statistics( $atts ) { $where_post = array( 'form_id' => $atts['form_id'], 'post_id >' => 1 ); if ( $atts['drafts'] != 'both' ) { $where_post['is_draft'] = $atts['drafts']; } if ( isset( $atts['user_id'] ) ) { $where_post['user_id'] = $atts['user_id']; } return FrmDb::get_results( 'frm_items', $where_post, 'id,post_id' ); } /** * Package the filtering arguments for a field meta query * * @since 2.02.06 * @param array $atts * @return array */ private static function package_filtering_arguments_for_query( $atts ) { $pass_args = array( 'entry_ids' => 'entry_ids', 'user_id' => 'user_id', 'created_at_greater_than' => 'start_date', 'created_at_less_than' => 'end_date', 'drafts' => 'is_draft', 'form_id' => 'form_id', 'limit' => 'limit', ); $meta_args = array(); foreach ( $pass_args as $atts_key => $arg_key ) { if ( isset( $atts[ $atts_key ] ) ) { $meta_args[ $arg_key ] = $atts[ $atts_key ]; } } $meta_args['order_by'] = 'e.created_at DESC'; return $meta_args; } /** * Check field filters in the stats shortcode * * @since 2.02.06 * TODO: update this so old filters are converted to new filters * @param array $atts */ private static function check_field_filters( &$atts ) { if ( ! empty( $atts['filters'] ) ) { if ( ! isset( $atts['entry_ids'] ) ) { $atts['entry_ids'] = array(); $after_where = false; } else { $after_where = true; } foreach ( $atts['filters'] as $orig_f => $val ) { // Replace HTML entities with less than/greater than symbols $val = str_replace( array( '&gt;', '&lt;' ), array( '>', '<' ), $val ); // If first character is a quote, but the last character is not a quote if ( ( strpos( $val, '"' ) === 0 && substr( $val, -1 ) != '"' ) || ( strpos( $val, "'" ) === 0 && substr( $val, -1 ) != "'" ) ) { //parse atts back together if they were broken at spaces $next_val = array( 'char' => substr( $val, 0, 1 ), 'val' => $val ); continue; // If we don't have a previous value that needs to be parsed back together } else if ( ! isset( $next_val ) ) { $temp = FrmAppHelper::replace_quotes( $val ); foreach ( array( '"', "'" ) as $q ) { // Check if <" or >" exists in string and string does not end with ". if ( substr( $temp, -1 ) != $q && ( strpos( $temp, '<' . $q ) || strpos( $temp, '>' . $q ) ) ) { $next_val = array( 'char' => $q, 'val' => $val ); $cont = true; } unset( $q ); } unset( $temp ); if ( isset( $cont ) ) { unset( $cont ); continue; } } // If we have a previous value saved that needs to be parsed back together (due to WordPress pullling it apart) if ( isset( $next_val ) ) { if ( substr( FrmAppHelper::replace_quotes( $val ), -1 ) == $next_val['char'] ) { $val = $next_val['val'] . ' ' . $val; unset( $next_val ); } else { $next_val['val'] .= ' ' . $val; continue; } } $pass_args = array( 'orig_f' => $orig_f, 'val' => $val, 'entry_ids' => $atts['entry_ids'], 'form_id' => $atts['form_id'], 'form_posts' => $atts['form_posts'], 'after_where' => $after_where, 'drafts' => $atts['drafts'], ); $atts['entry_ids'] = self::get_field_matches( $pass_args ); $after_where = true; if ( ! $atts['entry_ids'] ) { return; } } } } /** * Package the arguments needed for a field filter * * @since 2.02.05 * @param array $args * @return array */ private static function get_filter_args( $args ) { $filter_args = array( 'field' => '', 'operator' => '=', 'value' => $args['val'], 'form_id' => $args['form_id'], 'entry_ids' => $args['entry_ids'], 'after_where' => $args['after_where'], 'drafts' => $args['drafts'], 'form_posts' => $args['form_posts'], ); $f = $args['orig_f']; if ( strpos( $f, '_not_equal' ) !== false ) { self::get_not_equal_filter_args( $f, $filter_args ); } else if ( strpos( $f, '_less_than_or_equal_to' ) !== false ) { self::get_less_than_or_equal_to_filter_args( $f, $filter_args ); } else if ( strpos( $f, '_less_than' ) !== false ) { self::get_less_than_filter_args( $f, $filter_args ); } else if ( strpos( $f, '_greater_than_or_equal_to' ) !== false ) { self::get_greater_than_or_equal_to_filter_args( $f, $filter_args ); } else if ( strpos( $f, '_greater_than' ) !== false ) { self::get_greater_than_filter_args( $f, $filter_args ); } else if ( strpos( $f, '_contains' ) !== false ) { self::get_contains_filter_args( $f, $filter_args ); } else if ( strpos( $f, '_does_not_contain' ) !== false ) { self::get_does_not_contain_filter_args( $f, $filter_args ); } else if ( is_numeric( $f ) && $f <= 10 ) { // If using <, >, <=, >=, !=. $f will count up for certain atts self::get_filter_args_for_deprecated_field_filters( $filter_args ); } else { // $f is field ID, key, updated_at, or created_at self::get_equal_to_filter_args( $f, $filter_args ); } self::convert_filter_field_key_to_id( $filter_args ); self::prepare_filter_value( $filter_args ); return $filter_args; } /** * Get the filter arguments for a not_equal filter * * @since 2.02.05 * @param string $f * @param array $filter_args */ private static function get_not_equal_filter_args( $f, &$filter_args ) { $filter_args['field'] = str_replace( '_not_equal', '', $f ); $filter_args['operator'] = '!='; self::maybe_get_all_entry_ids_for_form( $filter_args ); } /** * Get the filter arguments for a less_than_or_equal_to filter * * @since 2.02.11 * @param string $f * @param array $filter_args */ private static function get_less_than_or_equal_to_filter_args( $f, &$filter_args ) { $filter_args['field'] = str_replace( '_less_than_or_equal_to', '', $f ); $filter_args['operator'] = '<='; } /** * Get the filter arguments for a less_than filter * * @since 2.02.05 * @param string $f * @param array $filter_args */ private static function get_less_than_filter_args( $f, &$filter_args ) { $filter_args['field'] = str_replace( '_less_than', '', $f ); $filter_args['operator'] = '<'; } /** * Get the filter arguments for a greater_than_or_equal_to filter * * @since 2.02.11 * @param string $f * @param array $filter_args */ private static function get_greater_than_or_equal_to_filter_args( $f, &$filter_args ) { $filter_args['field'] = str_replace( '_greater_than_or_equal_to', '', $f ); $filter_args['operator'] = '>='; } /** * Get the filter arguments for a greater_than filter * * @since 2.02.05 * @param string $f * @param array $filter_args */ private static function get_greater_than_filter_args( $f, &$filter_args ) { $filter_args['field'] = str_replace( '_greater_than', '', $f ); $filter_args['operator'] = '>'; } /** * Get the filter arguments for a like filter * * @since 2.02.05 * @param string $f * @param array $filter_args */ private static function get_contains_filter_args( $f, &$filter_args ) { $filter_args['field'] = str_replace( '_contains', '', $f ); $filter_args['operator'] = 'LIKE'; } /** * Get the filter arguments for a like filter * * @since 2.02.13 * @param string $f * @param array $filter_args */ private static function get_does_not_contain_filter_args( $f, &$filter_args ) { $filter_args['field'] = str_replace( '_does_not_contain', '', $f ); $filter_args['operator'] = 'NOT LIKE'; self::maybe_get_all_entry_ids_for_form( $filter_args ); } /** * Get the filter arguments for an x=value filter * * @since 2.02.05 * @param string $f * @param array $filter_args */ private static function get_equal_to_filter_args( $f, &$filter_args ) { $filter_args['field'] = self::maybe_convert_field_name( $f ); if ( $filter_args['value'] === '' ) { self::maybe_get_all_entry_ids_for_form( $filter_args ); } } /** * Convert param name to a field name usable in a SQL query * * @param $field_name * * @return string -- converted field name */ private static function maybe_convert_field_name( $field_name ) { if ( 'parent_id' === $field_name ) { return 'parent_item_id'; } return $field_name; } /** * Convert a filter field key to an ID * * @since 2.02.05 * @param array $filter_args */ private static function convert_filter_field_key_to_id( &$filter_args ) { if ( ! is_numeric( $filter_args['field'] ) && ! in_array( $filter_args['field'], array( 'created_at', 'updated_at', 'parent_item_id' ) ) ) { $filter_args['field'] = FrmField::get_id_by_key( $filter_args['field'] ); } } /** * Prepare a filter value * * @since 2.02.05 * @param array $filter_args */ private static function prepare_filter_value( &$filter_args ) { $filter_args['value'] = FrmAppHelper::replace_quotes( $filter_args['value'] ); if ( in_array( $filter_args['field'], array( 'created_at', 'updated_at' ) ) ) { $filter_args['value'] = str_replace( array( '"', "'" ), '', $filter_args['value'] ); $filter_args['value'] = gmdate( 'Y-m-d H:i:s', strtotime( $filter_args['value'] ) ); $filter_args['value'] = get_gmt_from_date( $filter_args['value'] ); } else { $filter_args['value'] = trim( trim( $filter_args['value'], "'" ), '"' ); } } /** * Get the filter arguments for deprecated stats parameters * * @since 2.02.05 * @param array $filter_args */ private static function get_filter_args_for_deprecated_field_filters( &$filter_args ) { $lpos = strpos( $filter_args['value'], '<' ); $gpos = strpos( $filter_args['value'], '>' ); $not_pos = strpos( $filter_args['value'], '!=' ); $dash_pos = strpos( $filter_args['value'], '-' ); if ( $not_pos !== false || $filter_args['value'] === '' ) { self::maybe_get_all_entry_ids_for_form( $filter_args ); } if ( $not_pos !== false ) { // Not equal $filter_args['operator'] = '!='; $str = explode( $filter_args['operator'], $filter_args['value'] ); $filter_args['field'] = $str[0]; $filter_args['value'] = $str[1]; } else if ( $lpos !== false || $gpos !== false ) { // Greater than or less than $filter_args['operator'] = ( ( $gpos !== false && $lpos !== false && $lpos > $gpos ) || $lpos === false ) ? '>' : '<'; $str = explode( $filter_args['operator'], $filter_args['value'] ); if ( count( $str ) == 2 ) { $filter_args['field'] = $str[0]; $filter_args['value'] = $str[1]; } else if ( count( $str ) == 3 ) { //3 parts assumes a structure like '-1 month'<255<'1 month' $pass_args = $filter_args; $pass_args['orig_f'] = 0; $pass_args['val'] = str_replace( $str[0] . $filter_args['operator'], '', $filter_args['value'] ); $filter_args['entry_ids'] = self::get_field_matches( $pass_args ); $filter_args['after_where'] = true; $filter_args['field'] = $str[1]; $filter_args['value'] = $str[0]; $filter_args['operator'] = ( $filter_args['operator'] == '<' ) ? '>' : '<'; } if ( strpos( $filter_args['value'], '=' ) === 0 ) { $filter_args['operator'] .= '='; $filter_args['value'] = substr( $filter_args['value'], 1 ); } } else if ( $dash_pos !== false && strpos( $filter_args['value'], '=' ) !== false ) { // Field key contains dash // If field key contains a dash, then it won't be put in as $f automatically (WordPress quirk maybe?) $str = explode( '=', $filter_args['value'] ); $filter_args['field'] = $str[0]; $filter_args['value'] = $str[1]; } } /** * Get all the entry IDs for a form if entry IDs is empty and after_where is false * * @since 2.02.05 * @param array $args */ private static function maybe_get_all_entry_ids_for_form( &$args ) { if ( empty( $args['entry_ids'] ) && $args['after_where'] == 0 ) { $query = array( 'form_id' => $args['form_id'] ); if ( $args['drafts'] != 'both' ) { $query['is_draft'] = $args['drafts']; } $args['entry_ids'] = FrmDb::get_col( 'frm_items', $query ); } } /** * Get the entry IDs for a field/column filter * * @since 2.02.05 * @param array $filter_args * @return array */ private static function get_entry_ids_for_field_filter( $filter_args ) { if ( in_array( $filter_args['field'], array( 'created_at', 'updated_at', 'parent_item_id' ) ) ) { if ( 'parent_item_id' === $filter_args['field'] ) { $filter_args['value'] = self::maybe_convert_entry_key_to_id( $filter_args['value'] ); } $where = array( 'form_id' => $filter_args['form_id'], $filter_args['field'] . FrmDb::append_where_is( $filter_args['operator'] ) => $filter_args['value'], ); if ( $filter_args['entry_ids'] ) { $where['id'] = $filter_args['entry_ids']; } $entry_ids = FrmDb::get_col( 'frm_items', $where ); } else { $where_atts = apply_filters( 'frm_stats_where', array( 'where_is' => $filter_args['operator'], 'where_val' => $filter_args['value'] ), $filter_args ); $pass_args = array( 'where_opt' => $filter_args['field'], 'where_is' => $where_atts['where_is'], 'where_val' => $where_atts['where_val'], 'form_id' => $filter_args['form_id'], 'form_posts' => $filter_args['form_posts'], 'after_where' => $filter_args['after_where'], 'drafts' => $filter_args['drafts'], ); $entry_ids = FrmProAppHelper::filter_where( $filter_args['entry_ids'], $pass_args ); } return $entry_ids; } /** * Format the retrieved meta values for a field * * @since 2.02.06 * @param object $field * @param array $atts * @param array $field_values */ private static function format_field_values( $field, $atts, &$field_values ) { if ( ! $field_values ) { return; } // Flatten multi-dimensional array if ( $atts['type'] != 'count' && FrmField::is_field_with_multiple_values( $field ) ) { self::flatten_multi_dimensional_arrays_for_stats( $field, false, $field_values ); } $field_values = wp_unslash( $field_values ); } }
C
UTF-8
1,142
3.71875
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> void printstruct(int **store_winner, int size){ for(int r = 0; r < size; r++){ printf("%d\n", **store_winner); printf("(%d,%d)", *(*(store_winner + r) + 0),store_winner[r][1]); // printf("(%d,%d)", store_winner[r][0],store_winner[r][1]); } printf("\n"); } int main(int argc, char *argv[]) { int size = 3; int **store_winner1 = malloc(sizeof(int*)*size); int **store_winner2 = malloc(sizeof(int*)*size); if(store_winner1 == NULL || store_winner2 == NULL ){ printf("Memory allocation failed for storing winners\n"); } //Allocate each row with "size" number of ints for(int i = 0; i < size; i++){ *(store_winner1 + i) = malloc(sizeof(int)*2); *(store_winner2 + i) = malloc(sizeof(int)*2); // malloc check if(*store_winner1 + i == NULL){ printf("Memory allocation failed"); } } for(int r = 0; r < size; r++){ store_winner1[r][0] = -100; // set row to -1 store_winner1[r][1] = -1; // set row to -1 store_winner2[r][0] = -1; // set col to -1 store_winner2[r][1] = -1; // set col to -1 } printstruct(store_winner1, size); return 0; }
Shell
UTF-8
203
2.53125
3
[ "MIT" ]
permissive
#!/bin/bash # The logic to stop your application should be put in this script. set -e cat $OPENSHIFT_LOG_DIR/$OPENSHIFT_APP_NAME.log || : xargs -r kill <$OPENSHIFT_RUN_DIR/$OPENSHIFT_APP_NAME.pid || :
Java
UTF-8
19,615
1.765625
2
[ "MIT" ]
permissive
package libs.trustconnector.scdp.smartcard.application.edep; import libs.trustconnector.scdp.*; import org.jdom2.filter.*; import org.jdom2.*; import org.jdom2.xpath.*; import java.util.*; import libs.trustconnector.scdp.smartcard.application.*; import libs.trustconnector.scdp.util.*; import libs.trustconnector.scdp.smartcard.*; import libs.trustconnector.scdp.smartcard.checkrule.*; import libs.trustconnector.scdp.smartcard.application.edep.checker.*; import libs.trustconnector.scdp.crypto.*; import libs.trustconnector.scdp.SCDP; import libs.trustconnector.scdp.crypto.DES; import libs.trustconnector.scdp.smartcard.AID; import libs.trustconnector.scdp.smartcard.APDUChecker; import libs.trustconnector.scdp.smartcard.SmartCardReader; import libs.trustconnector.scdp.smartcard.application.Application; import libs.trustconnector.scdp.smartcard.application.Key; import libs.trustconnector.scdp.smartcard.application.KeySet; import libs.trustconnector.scdp.smartcard.application.edep.checker.DebetForCashWithdrawResponseChecker; import libs.trustconnector.scdp.smartcard.application.edep.checker.DebetForLoadResponseChecker; import libs.trustconnector.scdp.smartcard.application.edep.checker.DebitForPurchaseResponseChecker; import libs.trustconnector.scdp.smartcard.application.edep.checker.InitForLoadResponseChecker; import libs.trustconnector.scdp.smartcard.application.edep.checker.InitForPurchaseResponseChecker; import libs.trustconnector.scdp.smartcard.checkrule.APDURuleChecker; import libs.trustconnector.scdp.smartcard.checkrule.ResponseCheckRuleInt; import libs.trustconnector.scdp.util.ByteArray; import libs.trustconnector.scdp.util.Util; public class EDEP extends Application { public boolean bShowSessionDetail; public String tradeDateTime; static final String KEYSETS_ITEM_NAME = "keysets"; static final String KEYSET_ITEM_NAME = "keyset"; static final String KEY_ITEM_NAME = "key"; static final String KEY_ITEM_ATTR_TYPE = "type"; static final String KEY_ITEM_ATTR_ID = "id"; static final String KEY_ITEM_ATTR_VALUE = "value"; public static final int APP_TYPE_ED = 1; public static final int APP_TYPE_EP = 2; public static final int TRADE_TYPE_ED_LOAD = 1; public static final int TRADE_TYPE_EP_LOAD = 2; public static final int TRADE_TYPE_UNLOAD = 3; public static final int TRADE_TYPE_ED_WITHDRAW = 4; public static final int TRADE_TYPE_ED_PURCHASE = 5; public static final int TRADE_TYPE_EP_PURCHASE = 6; public static final int TRADE_TYPE_ED_UPDATE = 7; public static final int TRADE_TYPE_CREDIT_PURCHASE = 8; public EDEP(final SmartCardReader reader, final AID aid) { super(reader, aid); this.bShowSessionDetail = false; this.loadKeyset(); } protected void loadKeyset() { final Element root = SCDP.getCfgSubNode("keysets"); if (root == null) { System.out.println("app keysets config root node not found:" + this.aid); return; } Element keysetNode = null; try { final String exp = "./keyset[@appaid='" + this.aid + "']"; final XPathExpression<Element> xpath = (XPathExpression<Element>)XPathFactory.instance().compile(exp, Filters.element()); keysetNode = (Element)xpath.evaluateFirst((Object)root); } catch (Exception e) { System.out.println("app keyset config root node not found:" + this.aid); return; } if (keysetNode == null) { System.out.println("app keyset config node not found:" + this.aid); return; } final List<Element> keyList = (List<Element>)keysetNode.getChildren("key"); for (final Element keyNode : keyList) { final Key newKey = new EDEPKey(keyNode); KeySet keyset = this.keySets.findKeySet(new Integer(newKey.getType())); if (keyset == null) { keyset = new KeySet(new Integer(newKey.getType())); this.keySets.addKeySet(keyset); } keyset.addKey(newKey); } } public void updateKey(final int keyType, final int index, final byte[] keyValue) { final Key newKey = new EDEPKey(keyType, index, keyValue); KeySet keyset = this.keySets.findKeySet(new Integer(newKey.getType())); if (keyset == null) { keyset = new KeySet(new Integer(newKey.getType())); this.keySets.addKeySet(keyset); } keyset.addKey(newKey); } public byte[] getKeyValue(final int keyType, final int index) { final KeySet keyset = this.keySets.findKeySet(new Integer(keyType)); if (keyset != null) { final Key key = keyset.getKey(new Integer(index)); if (key != null && key instanceof EDEPKey) { final EDEPKey t = (EDEPKey)key; return t.getValue(); } } return null; } public byte[] getKeyValue(final int keyType) { return this.getKeyValue(keyType, 0); } public boolean purchase(final int appType, final int keyIndex, final int amount, final String terminalNo, final String terminalExNo) { String groupName = ""; int tradeType = 0; if (appType == 1) { groupName += "ED"; tradeType = 5; } else { if (appType != 2) { return false; } groupName += "EP"; tradeType = 6; } groupName += "\u6d88\u8d39"; groupName += ":"; groupName += String.format("%08X", amount); final int cookie = SCDP.beginGroup(groupName); this.initForPurchase(appType, keyIndex, amount, terminalNo); final ByteArray rsp = new ByteArray(this.apdu.getRData()); final ByteArray sessionKeyData = new ByteArray(); sessionKeyData.append(rsp.toBytes(11, 4)); sessionKeyData.append(rsp.toBytes(4, 2)); final ByteArray teminalExNoD = new ByteArray(terminalExNo); sessionKeyData.append(teminalExNoD.right(2)); this.showSessionDetail("sessionKey Data", sessionKeyData.toBytes()); final byte[] sessionKey = this.genSessionKey(tradeType, keyIndex, sessionKeyData.toBytes()); this.showSessionDetail("sessionKey", sessionKey); final String dateTime = this.getDateTime(); final ByteArray mac1Data = new ByteArray(); mac1Data.append(amount, 4); mac1Data.append((byte)tradeType); mac1Data.append(ByteArray.convert(terminalNo)); mac1Data.append(ByteArray.convert(dateTime)); this.showSessionDetail("MAC1 data", mac1Data.toBytes()); final byte[] mac1 = this.calcTMAC(sessionKey, mac1Data.toBytes()); this.showSessionDetail("MAC1", mac1); final ByteArray tacData = new ByteArray(); tacData.append(amount, 4); tacData.append((byte)tradeType); tacData.append(ByteArray.convert(terminalNo)); tacData.append(ByteArray.convert(terminalExNo)); tacData.append(ByteArray.convert(dateTime)); this.showSessionDetail("TAC Data", tacData.toBytes()); final byte[] tacKey = this.getKeyValue(7); this.showSessionDetail("TAC Key", tacKey); final byte[] tagSessionKey = this.genTACSessionKey(tacKey); this.showSessionDetail("TAC Session Key", tagSessionKey); final byte[] TAC = this.calcTMAC(tagSessionKey, tacData.toBytes()); this.showSessionDetail("TAC", TAC); final byte[] amountB = Util.intToBytes(amount, 4); this.showSessionDetail("MAC2 Data", amountB); final byte[] MAC2 = this.calcTMAC(sessionKey, amountB); this.showSessionDetail("MAC2", MAC2); final DebitForPurchaseResponseChecker debetForPurchase = new DebitForPurchaseResponseChecker(); debetForPurchase.TAC.setMatch(TAC); debetForPurchase.MAC2.setMatch(MAC2); this.debitForPurchase(terminalExNo, dateTime, mac1, debetForPurchase); final byte[] oldB = rsp.toBytes(0, 4); final int oldBalance = Util.bytesToInt(oldB); final int newBalance = oldBalance - amount; final APDURuleChecker c = new APDURuleChecker(); c.setCheckSW(36864); final ResponseCheckRuleInt br = new ResponseCheckRuleInt("\u4f59\u989d", 0); br.setMatch(newBalance); c.addCheckRule(br); this.getBalance(appType, c); SCDP.endGroup(cookie); return true; } public boolean load(final int appType, final int keyIndex, final int amount, final String terminalNo) { String groupName = ""; int tradeType = 0; if (appType == 1) { groupName += "ED"; tradeType = 1; } else { if (appType != 2) { return false; } groupName += "EP"; tradeType = 2; } groupName += "\u5708\u5b58"; groupName += ":"; groupName += String.format("%08X", amount); final int cookie = SCDP.beginGroup(groupName); this.initForLoad(appType, keyIndex, amount, terminalNo); final ByteArray rsp = new ByteArray(this.apdu.getRData()); final byte[] balance = rsp.toBytes(0, 4); final byte[] onlineSN = rsp.toBytes(4, 2); final byte[] random = rsp.toBytes(8, 4); final byte[] mac1 = rsp.toBytes(12, 4); final ByteArray sessionKeyData = new ByteArray(); sessionKeyData.append(random); sessionKeyData.append(onlineSN); final byte[] a = { -128, 0 }; sessionKeyData.append(a); this.showSessionDetail("sessionKey Data", sessionKeyData.toBytes()); final byte[] sessionKey = this.genSessionKey(tradeType, keyIndex, sessionKeyData.toBytes()); this.showSessionDetail("sessionKey", sessionKey); final ByteArray mac1Data = new ByteArray(); mac1Data.append(balance); final byte[] amountByte = Util.intToBytes(amount, 4); mac1Data.append(amountByte); mac1Data.append((byte)tradeType); mac1Data.append(ByteArray.convert(terminalNo)); this.showSessionDetail("MAC1 Data", mac1Data.toBytes()); final byte[] mac1Exp = this.calcTMAC(sessionKey, mac1Data.toBytes()); this.showSessionDetail("MAC1", mac1Exp); if (!Util.arrayCompare(mac1Exp, 0, mac1, 0, 4)) { SCDP.reportAPDUExpErr("\u68c0\u9a8cMAC\u5931\u8d25,\u671f\u5f85:" + ByteArray.convert(mac1Exp) + ",\u5b9e\u9645\u8fd4\u56de:" + ByteArray.convert(mac1)); SCDP.endGroup(cookie); return false; } final String dateTime = this.getDateTime(); mac1Data.reinit(); mac1Data.append(amountByte); mac1Data.append((byte)tradeType); mac1Data.append(ByteArray.convert(terminalNo)); mac1Data.append(ByteArray.convert(dateTime)); this.showSessionDetail("MAC2 Data", mac1Data.toBytes()); final byte[] mac2 = this.calcTMAC(sessionKey, mac1Data.toBytes()); this.showSessionDetail("MAC2", mac2); mac1Data.reinit(); final int ob = Util.bytesToInt(balance); mac1Data.append(Util.intToBytes(ob + amount, 4)); mac1Data.append(onlineSN); mac1Data.append(amountByte); mac1Data.append((byte)tradeType); mac1Data.append(ByteArray.convert(terminalNo)); mac1Data.append(ByteArray.convert(dateTime)); this.showSessionDetail("TAC Data", mac1Data.toBytes()); final byte[] tacKey = this.getKeyValue(7); this.showSessionDetail("TAC Key", tacKey); final byte[] tagSessionKey = this.genTACSessionKey(tacKey); this.showSessionDetail("TAC Session Key", tagSessionKey); final byte[] TAC = this.calcTMAC(tagSessionKey, mac1Data.toBytes()); this.showSessionDetail("TAC", TAC); final DebetForLoadResponseChecker debetLoad = new DebetForLoadResponseChecker(); debetLoad.TAC1.setMatch(TAC); this.debetForLoad(dateTime, mac2, debetLoad); final int newBalance = ob + amount; final APDURuleChecker c = new APDURuleChecker(); c.setCheckSW(36864); final ResponseCheckRuleInt br = new ResponseCheckRuleInt("\u4f59\u989d", 0); br.setMatch(newBalance); c.addCheckRule(br); this.getBalance(appType, c); SCDP.endGroup(cookie); return true; } public void verifyPIN() { this.verifyPIN(this.getKeyValue(12)); } public void initForPurchase(final int appType, final int keyIndex, final int amount, final String terminalNo, final APDUChecker checker) { this.apdu.setCAPDU("Init For Purchase", "805001020B0100000001112233445566"); this.apdu.setP2(appType); final ByteArray br = new ByteArray(); br.append((byte)keyIndex); br.append(amount, 4); br.append(ByteArray.convert(terminalNo)); this.apdu.setCData(br.toBytes()); this.apdu.setRAPDUChecker(checker); this.transmit(); } public void initForPurchase(final int appType, final int keyIndex, final int amount, final String terminalNo) { this.initForPurchase(appType, keyIndex, amount, terminalNo, new InitForPurchaseResponseChecker()); } public void initForLoad(final int appType, final int keyIndex, final int amount, final String terminalNo, final APDUChecker checker) { this.apdu.setCAPDU("Init For Load", "805000020B0100000001112233445566"); this.apdu.setP2(appType); final ByteArray br = new ByteArray(); br.append((byte)keyIndex); br.append(amount, 4); br.append(ByteArray.convert(terminalNo)); this.apdu.setCData(br.toBytes()); this.apdu.setRAPDUChecker(checker); this.transmit(); } public void initForLoad(final int appType, final int keyIndex, final int amount, final String terminalNo) { this.initForLoad(appType, keyIndex, amount, terminalNo, new InitForLoadResponseChecker()); } public void debetForLoad(final String dateTime, final byte[] mac2, final APDUChecker checker) { this.apdu.setCAPDU("Debit For Load", "805200000B20151020114000000000"); final ByteArray br = new ByteArray(); br.append(ByteArray.convert(dateTime)); br.append(mac2); this.apdu.setCData(br.toBytes()); this.apdu.setRAPDUChecker(checker); this.transmit(); } public void debetForLoad(final String dateTime, final byte[] mac2) { this.debetForLoad(dateTime, mac2, new DebetForLoadResponseChecker()); } public void debitForPurchase(final String terminalExNo, final String dateTime, final byte[] mac1, final APDUChecker checker) { this.apdu.setCAPDU("Debit For Purchase", "805401000F0000002015102011400000112233"); final ByteArray br = new ByteArray(); br.append(ByteArray.convert(terminalExNo)); br.append(ByteArray.convert(dateTime)); br.append(mac1); this.apdu.setCData(br.toBytes()); this.apdu.setRAPDUChecker(checker); this.transmit(); } public void debitForPurchase(final String terminalExNo, final String dateTime, final byte[] mac1) { this.debitForPurchase(terminalExNo, dateTime, mac1, new DebitForPurchaseResponseChecker()); } public void debitForCashWithdraw(final String terminalExNo, final String dateTime, final byte[] mac1, final APDUChecker checker) { this.apdu.setCAPDU("Debit For Cash Withdraw", "805401000F0000002015102011400000112233"); final ByteArray br = new ByteArray(); br.append(ByteArray.convert(terminalExNo)); br.append(ByteArray.convert(dateTime)); br.append(mac1); this.apdu.setCData(br.toBytes()); this.apdu.setRAPDUChecker(checker); this.transmit(); } public void debitForCashWithdraw(final String terminalExNo, final String dateTime, final byte[] mac1) { this.debitForCashWithdraw(terminalExNo, dateTime, mac1, new DebetForCashWithdrawResponseChecker()); } public void getBalance(final int tradeType) { final APDURuleChecker c = new APDURuleChecker(); c.setCheckSW(36864); this.getBalance(tradeType, c); } public void getBalance(final int tradeType, final APDUChecker checker) { this.apdu.setCAPDU("Get Balance", "805C000004"); this.apdu.setP2(tradeType); this.apdu.setRAPDUChecker(checker); this.transmit(); } public void verifyPIN(final byte[] pin) { this.apdu.setCAPDU("Verify PIN", "0020000000"); this.apdu.setCData(pin); this.transmit(); } public void selectFile(final AID aid) { this.apdu.setCAPDU("Select File", "00A4000000"); this.apdu.setCData(aid.toBytes()); this.transmit(); } public void readBinary(final int sfi, final int offset, final int length) { this.apdu.setCAPDU("Read Binary", "00B0000000"); this.apdu.setP1((sfi & 0x1F) | 0x80); this.apdu.setP2(offset); this.apdu.setP3(length); this.transmit(); } public void updateBinary() { } public void readRecord() { } public void updateRecord() { } public void unblockPIN() { } public void applicationBlock() { } public void applicationUnblock() { } public void internalAuth() { } public void externalAuth(final byte[] extAuthData) { this.apdu.setCAPDU("External Auth", "0082000000"); this.apdu.setCData(extAuthData); this.transmit(); } public void getChallenge() { this.apdu.setCAPDU("Get Challenge", "0084000004"); this.transmit(); } private byte[] genSessionKey(final int tradeType, final int keyIndex, final byte[] data) { int keyType = 0; switch (tradeType) { case 1: case 2: { keyType = 5; break; } case 3: { keyType = 6; break; } case 4: case 5: case 6: case 8: { keyType = 4; break; } case 7: { keyType = 8; break; } } final byte[] keyValue = this.getKeyValue(keyType, keyIndex); return DES.doCrypto(data, keyValue, 273); } byte[] genTACSessionKey(final byte[] keyDTK) { final byte[] sk = new byte[8]; ByteArray.xor(keyDTK, 0, keyDTK, 8, sk, 0, 8); return sk; } byte[] calcTMAC(final byte[] sessionKey, final byte[] data) { return DES.calcMAC(data, 4, sessionKey, null, 13089); } public void enableShowSessionDetail() { this.bShowSessionDetail = true; } public void disableShowSessionDetail() { this.bShowSessionDetail = false; } void showSessionDetail(final String msg, final byte[] data) { if (this.bShowSessionDetail) { final String log = msg + ":" + ByteArray.convert(data); SCDP.addLog(log); } } public void setTradeDateTime(final String tradeDateTime) { this.tradeDateTime = tradeDateTime; } public String getDateTime() { if (this.tradeDateTime == null) { return Util.getCurrentDateTime(); } return this.tradeDateTime; } }
Python
UTF-8
785
3.671875
4
[]
no_license
from collections import deque class TreeNode: def __init__(self, data): self.data = data self.left = None self.right = None def insert(root, data): q = deque() q.append(root) while q: temp = q.popleft() if temp.left: q.append(temp.left) else: temp.left = TreeNode(data) return if temp.right: q.append(temp.right) else: temp.right = TreeNode(data) return def inorder(root): if not root: return inorder(root.left) print(root.data) inorder(root.right) if __name__ == "__main__": root = TreeNode(10) insert(root, 17) insert(root, 11) insert(root, 12) insert(root, 15) inorder(root)
Java
UTF-8
4,076
2.21875
2
[]
no_license
package softgroup.backend.controller; import org.springframework.web.bind.annotation.*; import softgroup.backend.entity.*; import softgroup.backend.service.CourseService; import softgroup.backend.service.Course_studentService; import softgroup.backend.service.VideoService; import softgroup.backend.service.Video_studentService; import javax.annotation.Resource; import java.util.List; import java.util.Map; @RestController public class WatchtimeController { @Resource Video_studentService video_studentService; @Resource VideoService videoService; @Resource Course_studentService course_studentService; @Resource CourseService courseService; @CrossOrigin @PostMapping(value = "/api/updatetime") @ResponseBody public Result updatetime(@RequestBody Map<String, String> params){ Video_student video_student = video_studentService.getByVideoandUser(Integer.valueOf(params.get("videoid")), params.get("userid")); Video video = videoService.getById(Integer.valueOf(params.get("videoid"))); Course course = video.getCourse(); Integer courseid = course.getCourseid(); Integer coursetime = course.getCoursetime(); Course_student course_student = course_studentService.getByCourseidAndUserid(params.get("userid"), courseid); course_student.setSumtime(coursetime); Integer sumtime = videoService.getById(Integer.valueOf(params.get("videoid"))).getVideotime(); if(video_student == null) { video_studentService.update(new Video_student(Integer.valueOf(params.get("videoid")), params.get("userid"),Integer.valueOf(params.get("time")), sumtime)); course_student.setWatchtime(Integer.valueOf(params.get("time"))); course_studentService.save(course_student); return new Result(200, "花q"); } Integer time = Integer.valueOf(params.get("time")); //fuck //Video video = videoService.getById(Integer.valueOf(params.get("videoid"))); time += video_student.getWatchtime(); Integer temp_time = course_student.getWatchtime(); temp_time -= video_student.getWatchtime(); if(time.compareTo(video_student.getSumtime())>=0){ video_student.setWatchtime(video_student.getSumtime()); temp_time += video_student.getSumtime(); } else{ temp_time += time; video_student.setWatchtime(time); } //course_student.setWatchtime(temp_time); video_studentService.update(video_student); course_studentService.save(course_student); return new Result(200, "更新成功"); } //返回课程学习进度 @CrossOrigin @PostMapping(value = "/api/getcoursewatchtime") @ResponseBody public Result getcoursewatchtime(@RequestBody Map<String, String> params){ Course_student course_student = course_studentService.getByCourseidAndUserid(params.get("userid"),Integer.valueOf(params.get("courseid"))); Course course = courseService.getById(Integer.valueOf(params.get("courseid"))); List<Video> videos = videoService.getByCourse(course); Integer sumtime = 0; for(int i = 0; i<videos.size(); i++){ if(video_studentService.getByVideoandUser(videos.get(i).getVideoId(), params.get("userid")) == null) continue; Video_student video_student = video_studentService.getByVideoandUser(videos.get(i).getVideoId(), params.get("userid")); Integer watch = video_student.getWatchtime(); Integer sum = video_student.getSumtime(); if(sum - watch <= 3000){ video_student.setWatchtime(sum); video_studentService.update(video_student); } sumtime += video_studentService.getByVideoandUser(videos.get(i).getVideoId(), params.get("userid")).getWatchtime(); } course_student.setWatchtime(sumtime); return new Result(200,"返回成功",course_student); } }
C++
UTF-8
868
3.015625
3
[]
no_license
#include <iostream> #include <cstdio> #include <cmath> #include <algorithm> using namespace std; int arr[10]; int _max = -999; void r_rotate(int _arr[], int s, int t) { int temp = _arr[t]; for (int i = t; i > s; i--) { _arr[i] = _arr[i - 1]; } _arr[s] = temp; } void l_rotate(int _arr[], int s, int t) { int temp = _arr[s]; for (int i = s; i < t; i++) { _arr[i] = _arr[i + 1]; } _arr[t] = temp; } void perm(int set[], int size,int N, int K) { if (K == 0) { int sum = 0; for (int i = 0; i < N-1; i++) { sum += abs(arr[i] - arr[i + 1]); } _max = max(sum, _max); return; } for (int i = size; i < N; i++) { r_rotate(set, size,i); perm(set, size + 1, N, K - 1); l_rotate(set, size, i); } } int main() { int N; scanf("%d", &N); for (int i = 0; i < N; i++) { scanf("%d", &arr[i]); } perm(arr, 0, N, N); printf("%d\n", _max); }
Java
UTF-8
1,593
2.984375
3
[]
no_license
package com.botijasoftware.utils.collision; import com.botijasoftware.utils.Vector3; public class CollisionHollowSphere extends CollisionVolume { private Sphere outsphere; private Sphere insphere; private float holeangle; private float halfholeangle; private float angle; public CollisionHollowSphere(Vector3 center, float outradius, float inradius, float holeangle) { outsphere = new Sphere(center, outradius); insphere = new Sphere(center, inradius); this.holeangle = holeangle; this.halfholeangle = this.holeangle/2; } private boolean inHole(Vector3 v) { float a = (float)Math.atan2(-(v.Y-outsphere.Y), v.X-outsphere.X); return (a < angle+halfholeangle) && (a > angle-halfholeangle); } public boolean collides(CollisionVolume c) { return (c.collides(outsphere) && (!c.collides(insphere)) && !inHole(c.getPosition())); } public boolean collides(Sphere s) { return (outsphere.collides(s) && (!insphere.collides(s) && !inHole(s.getCenter()))) ; } public boolean collides(Vector3 v) { return (outsphere.collides(v) && (!insphere.collides(v) && !inHole(v))); } public Vector3 getPosition() { return insphere.getCenter(); } public void setPosition(Vector3 v) { outsphere.setCenter(v); insphere.setCenter(v); } public void setOutRadius(float r) { outsphere.setRadius(r); } public void setInRadius(float r) { insphere.setRadius(r); } public float getOutRadius() { return outsphere.radius; } public float getInRadius() { return insphere.radius; } public void rotate(float angle) { this.angle = angle; } }
Python
UTF-8
447
3.5625
4
[]
no_license
#Name: ...Lowai Dobie... #Email: ...lowai.dobie76@myhunter.cuny.edu... #Date: October 21, 2020 #This program prints: Daily Attendence import matplotlib.pyplot as plt import pandas as pd fil=input("Enter name of input file: ") out=input("Enter name of output file: ") df=pd.read_csv(fil) df["Date"] = pd.to_datetime(df["Date"].apply(str)) df['% Attending']= (df['Present']/df['Enrolled'])*100 df.plot(x='Date',y='% Attending') fig = plt.gcf() fig.savefig(out)
Java
UTF-8
1,988
3.515625
4
[]
no_license
package theory; public interface Scale { public default String name() { return "<anonymous scale> " + intervals(); } /** * Should not include the root note. For example, the major scale would be: * <p> * [2, 2, 1, 2, 2, 2, 1] * <p> * to indicate the following scale degrees: * <p> * (do) [re, mi, fa, sol, la, ti, (do)] * * @return an int array indicating half steps for each interval */ public int[] intervals(); /** * Includes the root note but not the start of the scale above. For example, the major intervals are: * <p> * [0, 2, 4, 5, 7, 9, 11] * <p> * to indicate the following scale degrees: * <p> * [do, re, mi, fa, sol, la, ti] (do) * * @return the distance in half steps that each scale degree is above the root */ public default int[] intervalsFromRoot() { int[] intervals = intervals(); int length = intervals.length; int[] retval = new int[length]; retval[0] = 0; for (int i=0; i<length-1; i++) { int sum = 0; for (int j=0; j<=i; j++) { sum += intervals[j]; } retval[i+1] = sum; } return retval; } /** @return octave size in half steps */ public default int getWidth() { int width = 0; for (int interval : intervals()) width += interval; return width; } /** @return what it says on the tin; go read up on music theory! */ public default boolean isDiatonic() { int[] intervals = intervals(); int length = intervals.length; if (length != 7) return false; int firstHalfStep = -1; int secondHalfStep = -1; for (int i=0; i<length; i++) { if (intervals[i] == 1) { if (firstHalfStep == -1) { firstHalfStep = 1; continue; } if (secondHalfStep == -1) { secondHalfStep = i; continue; } } if (intervals[i] != 2) return false; // found an interval other than a half or whole step } if (firstHalfStep == -1 || secondHalfStep == -1) return false; // found fewer than two half steps return true; } }
Shell
UTF-8
298
3.125
3
[]
no_license
#!/bin/bash sudo echo # install yarn if !(command -v yarn >/dev/null 2>&1); then sudo npm install yarn -g fi root=$(pwd) modules=(api home blog) # init modules. yarn for m in ${modules[@]} do echo "===== init" ${m} "======" cd $root/$m && yarn done cd $root/types && sudo npm link
Markdown
UTF-8
7,328
3.046875
3
[ "MIT" ]
permissive
# ethereum-blocks [![Build Status](https://secure.travis-ci.org/hiddentao/ethereum-blocks.png?branch=master)](http://travis-ci.org/hiddentao/ethereum-blocks) [![NPM module](https://badge.fury.io/js/ethereum-blocks.png)](https://badge.fury.io/js/ethereum-blocks) [![Twitter URL](https://img.shields.io/twitter/url/http/shields.io.svg?style=social&label=Follow&maxAge=2592000)](https://twitter.com/hiddentao) Process blocks from an Ethereum [web3](https://github.com/ethereum/web3.js/) instance robustly. This library uses [web3.eth.filter](https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethfilter) to listen for the latest blocks on a chain. When a block is received all registered handlers are invoked to perform any required processing on the block data. Features: * Can *catch up* on all missed blocks when restarted * Detects if connection has dropped and waits until re-established * Processing handlers can be asynchronous * Errors are gracefully handled * Customizable logging, can be turned on/off at runtime * Works with any [web3](https://github.com/ethereum/web3.js/) instance * No dependencies - works in Node, Electron apps and browsers * Automated [tests](https://travis-ci.org/hiddentao/ethereum-blocks) ## Installation ```shell $ npm install ethereum-blocks ``` ## Usage ```js import Web3 from 'web3'; import EthereumBlocks from 'ethereum-blocks'; const web3 = new Web3(/* connect to running Geth node */); // create a new instance const blocks = new EthereumBlocks({ web3: web3 }); // register a handler called "myHandler" blocks.registerHandler('myHandler', (eventType, blockId, data) => { switch (eventType) { case 'block': /* data = result of web3.eth.getBlock(blockId) */ console.log('Block id', blockId); console.log('Block nonce', data.nonce); break; case 'error': /* data = Error instance */ console.error(data); break; } }); // start the block processor blocks.start().catch(console.error); ``` ### Starting and stopping The `start()` and `stop()` methods are used for starting and stopping the block processor. Both are asynchronous and return `Promise` objects which resolve to a boolean indicating whether there was a change of state. Starting it: ```js blocks.start() .then((started) => { console.log( started ? 'Started' : 'Already running'); console.log( blocks.isRunning ); /* true */ }) .catch((err) => { /* error */ console.log( blocks.isRunning ); /* false */ }) ``` Stopping it: ```js blocks.stop() .then((stopped) => { console.log( stopped ? 'Stopped' : 'Was not running'); console.log( blocks.isRunning ); /* false */ }) .catch((err) => { /* error */ }) ``` As shown above, the `isRunning` property can be used to check the current status of the processor at any point in time. ### Catching up with missed blocks If you are re-starting the block processor after having previously stopped it (e.g. if your app restarted) then it is useful to be able to *catch up* on any blocks you may have missed in the intervening period. To do this you first need the id/number of the last block which got processed. This can be obtained at any time using the `lastBlock` property. You could store this value in storage for use later on: ```js window.localStorage.set('lastBlock', blocks.lastBlock); ``` Then next time your app starts up you can retrieve this value and tell the block processor to process all blocks which came after this one up until the current block, before then watching for new blocks: ```js const lastBlockProcessed = window.localStorage.get('lastBlock'); blocks.start({ catchupFrom: lastBlockProcessed ? Number(lastBlockProcessed) : null, }); ``` New incoming blocks will be added to the processing queue AFTER all the blocks from the `catchupFrom` block until the current one. ### Handlers Handlers are functions which get passed the block data in order to do any actual processing needed. To add and remove them: * `registerHandler(id: String, fn: Function)` - an `id` is required just so that the handler can be referred to in log messages. The `fn` handler function should have the signature `(eventType, blockId, data)`: * `eventType` - {String} The event type (either "block" or "error") * `blockId` - {String} Id of block. * `data` - {Object} Block data or error object. * `deregisterHandler(id: String)` - the `id` must be the same one that you passed in to the registration call. *Note: If you call `registerHandler` with the same `id` more than once then the handler function sent in the latest call will be the one which gets invoked.* If a handler function returns a `Promise` then it is treated as an asynchronous function. You can register both synchronous and asynchronous handlers with the same block processor. Processing on a given block is only considered complete when all handlers have finished executing (asynchronous or otherwise). *Note: If a handler throws an error it will be caught and logged, but the other registered handlers will still get executed.* ### Logger By default internal logging is silent. But you can turn on logging at any time by setting the `logger` property: ```js blocks.logger = console; /* log everything to console */ ``` The supplied logger object must have 3 methods: `info`, `warn` and `error`. If any one of these methods isn't provided then the built-in method (i.e. silent method) get used. For example: ```js // let's output only the error messages blocks.logger = { error: console.error.bind(console) } ``` ### Handling node connection failures If the web3 connection to the client node fails (e.g. because the node crashes) then the block processor is intelligent enough to detect this and wait for the connection to be re-established before resuming processing. To check to see if the connection is active use the `isConnected` property. For example, let's say we called `start()` and the connection to the node then went down we would have: ```js console.log( blocks.isRunning ); /* true */ console.log( blocks.isConnected ); /* false */ ``` The processor will check every `connectionCheckInterval` milliseconds to see if the connection has been established. You can get or set this property at runtime to check more or less often: ```js console.log( blocks.connectionCheckInterval ); /* 5000 */ blocks.connectionCheckInterval = 100; /* change it to check every 100ms */ ``` ### Processing loop interval You can change set how often the processing loop should run using the `loopInterval` property. This is measured in milliseconds and is 5000 by default (i.e. 5 seconds): ```js console.log( blocks.loopInterval ); /* 5000 */ blocks.loopInterval = 100; /* run the processing loop every 100ms */ ``` ### Browser usage If you are not using a packaging manager and are instead importing [ethereumBlocks.js](dist/ethereumBlocks.js) directly then the class is exposed on the global object as `EthereumBlocks`. Thus, in the browser window context you would use it like this: ```js const blocks = new window.EthereumBlocks({ web3: web3 }); ``` ## Development To build and run the tests: ```shell $ npm install $ npm test ``` ## Contributions Contributions welcome - see [CONTRIBUTING.md](CONTRIBUTING.md) ## License MIT - see [LICENSE.md](LICENSE.md)
C#
UTF-8
1,656
2.84375
3
[]
no_license
using ExamCleanCode.Core.Services.Data.interfaces; using ExamCleanCode.Core.Services.interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExamCleanCode.Core.Services.implementations { public class BorrowBookService : IBorrowBook { private readonly IUserAccess _accessService; private readonly IRepositoryLoad<Book> _bookLoadRepository; private readonly IRepositoryWrite<Book> _bookWriteRepository; public BorrowBookService(IUserAccess accessService, IRepositoryLoad<Book> bookLoadRepository, IRepositoryWrite<Book> bookWriteRepository) { _accessService = accessService; _bookLoadRepository = bookLoadRepository; _bookWriteRepository = bookWriteRepository; } public void BorrowBook(User currentUser, string title) { if (!(_accessService.CanPerformAction(currentUser, Role.Member))) { throw new Exception("You can't perform this action"); } var books = _bookLoadRepository.GetAll(); var book = books.First(a => a.Title == title); if(book == null) throw new Exception("This book doesn't exist"); if(book.Borrower != null) throw new Exception("This book is already borrowed"); book.Borrower = currentUser.Login; book.BorrowDate = DateTime.Now; _bookWriteRepository.AddAll(books); } } }
Java
UTF-8
885
2.484375
2
[]
no_license
package br.imd.ufrn.sistema.telegrambot.command; import java.util.HashMap; import java.util.Map; import java.util.Optional; public class CommandFactory { static Map<String, Command> commandMap = new HashMap<>(); static { commandMap.put("/create", new CreateCommand()); commandMap.put("/show", new ShowCommand()); commandMap.put("/find", new FindCommand()); commandMap.put("/delete", new DeleteCommand()); commandMap.put("/help", new HelpCommand()); commandMap.put("/start", new HelpCommand()); commandMap.put("/c", new CreateCommand()); commandMap.put("/s", new ShowCommand()); commandMap.put("/f", new FindCommand()); commandMap.put("/d", new DeleteCommand()); commandMap.put("/h", new HelpCommand()); } public static Optional<Command> getCommand(String command) { return Optional.ofNullable(commandMap.get(command)); } }
C++
UTF-8
13,343
2.8125
3
[]
no_license
#include "Descriptors.h" #include "Image.h" #include "Utilities.h" #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #include <stdexcept> void Descriptors::createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory, VkDevice& logicalDevice, VkPhysicalDevice& physicalDevice) { // Create buffer VkBufferCreateInfo bufferInfo = {}; bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferInfo.size = size; bufferInfo.usage = usage; bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; if (vkCreateBuffer(logicalDevice, &bufferInfo, nullptr, &buffer) != VK_SUCCESS) { throw std::runtime_error("Failed to create vertex buffer"); } // Query buffer's memory requirements VkMemoryRequirements memRequirements; vkGetBufferMemoryRequirements(logicalDevice, buffer, &memRequirements); // Allocate memory in device VkMemoryAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memRequirements.size; allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties, physicalDevice); if (vkAllocateMemory(logicalDevice, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate vertex buffer"); } // Associate allocated memory with vertex buffer vkBindBufferMemory(logicalDevice, buffer, bufferMemory, 0); } void Descriptors::copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size, VkCommandPool& commandPool, VkDevice& logicalDevice, VkQueue& graphicsQueue) { // Create a temporary command buffer for the transfer operation VkCommandBuffer commandBuffer = beginSingleTimeCommands(commandPool, logicalDevice); VkBufferCopy copyRegion = {}; copyRegion.size = size; vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, &copyRegion); endSingleTimeCommands(commandPool, commandBuffer, graphicsQueue, logicalDevice); } void Descriptors::createVertexBuffer(std::vector<Vertex>& vertices, VkBuffer& vertexBuffer, VkDeviceMemory& vertexBufferMemory, VkDevice& logicalDevice, VkPhysicalDevice& physicalDevice, VkCommandPool& commandPool, VkQueue& graphicsQueue) { // Create the staging buffer VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; VkDeviceSize bufferSize = sizeof(vertices[0]) * vertices.size(); VkBufferUsageFlags stagingUsage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; VkMemoryPropertyFlags stagingProperties = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; createBuffer(bufferSize, stagingUsage, stagingProperties, stagingBuffer, stagingBufferMemory, logicalDevice, physicalDevice); // Fill the staging buffer void *data; vkMapMemory(logicalDevice, stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, vertices.data(), (size_t)bufferSize); vkUnmapMemory(logicalDevice, stagingBufferMemory); // Create the vertex buffer VkBufferUsageFlags vertexUsage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; VkMemoryPropertyFlags vertexFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; createBuffer(bufferSize, vertexUsage, vertexFlags, vertexBuffer, vertexBufferMemory, logicalDevice, physicalDevice); // Copy data from staging to vertex buffer copyBuffer(stagingBuffer, vertexBuffer, bufferSize, commandPool, logicalDevice, graphicsQueue); // No need for the staging buffer anymore vkDestroyBuffer(logicalDevice, stagingBuffer, nullptr); vkFreeMemory(logicalDevice, stagingBufferMemory, nullptr); } void Descriptors::createIndexBuffer(std::vector<uint32_t>& indices, VkBuffer& indexBuffer, VkDeviceMemory& indexBufferMemory, VkDevice& logicalDevice, VkPhysicalDevice& physicalDevice, VkCommandPool& commandPool, VkQueue& graphicsQueue) { // Create the staging buffer VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; VkDeviceSize bufferSize = sizeof(indices[0]) * indices.size(); VkBufferUsageFlags stagingUsage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; VkMemoryPropertyFlags stagingProperties = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; createBuffer(bufferSize, stagingUsage, stagingProperties, stagingBuffer, stagingBufferMemory, logicalDevice, physicalDevice); // Fill the staging buffer void *data; vkMapMemory(logicalDevice, stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, indices.data(), (size_t)bufferSize); vkUnmapMemory(logicalDevice, stagingBufferMemory); // Create the vertex buffer VkBufferUsageFlags indexUsage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT; VkMemoryPropertyFlags indexFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; createBuffer(bufferSize, indexUsage, indexFlags, indexBuffer, indexBufferMemory, logicalDevice, physicalDevice); // Copy data from staging to vertex buffer copyBuffer(stagingBuffer, indexBuffer, bufferSize, commandPool, logicalDevice, graphicsQueue); // No need for the staging buffer anymore vkDestroyBuffer(logicalDevice, stagingBuffer, nullptr); vkFreeMemory(logicalDevice, stagingBufferMemory, nullptr); } void Descriptors::createBladesBuffer(Blades* blades, VkDevice& logicalDevice, VkPhysicalDevice& physicalDevice, VkCommandPool& commandPool, VkQueue& computeQueue) { // Create the staging buffer VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; VkDeviceSize bufferSize = NUM_BLADES * sizeof(Blade); VkBufferUsageFlags stagingUsage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; VkMemoryPropertyFlags stagingProperties = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; createBuffer(bufferSize, stagingUsage, stagingProperties, stagingBuffer, stagingBufferMemory, logicalDevice, physicalDevice); // Fill the staging buffer void *data; vkMapMemory(logicalDevice, stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, blades->data(), (size_t)bufferSize); vkUnmapMemory(logicalDevice, stagingBufferMemory); // Create the storage buffer VkBufferUsageFlags storageUsage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; VkMemoryPropertyFlags storageFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; createBuffer(bufferSize, storageUsage, storageFlags, bladesBuffer, bladesBufferMemory, logicalDevice, physicalDevice); // Copy data from staging to storage buffer copyBuffer(stagingBuffer, bladesBuffer, bufferSize, commandPool, logicalDevice, computeQueue); // No need for the staging buffer anymore vkDestroyBuffer(logicalDevice, stagingBuffer, nullptr); vkFreeMemory(logicalDevice, stagingBufferMemory, nullptr); } void Descriptors::createCulledBladesBuffer(VkDevice& logicalDevice, VkPhysicalDevice& physicalDevice, VkCommandPool& commandPool, VkQueue& computeQueue) { // Create the storage buffer VkBufferUsageFlags storageUsage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; VkMemoryPropertyFlags storageFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; VkDeviceSize bufferSize = NUM_BLADES * sizeof(Blade); createBuffer(bufferSize, storageUsage, storageFlags, culledBladesBuffer, culledBladesBufferMemory, logicalDevice, physicalDevice); } void Descriptors::createUniformBuffer(VkDeviceSize bufferSize, VkBuffer& buffer, VkDeviceMemory& bufferMemory, VkDevice& logicalDevice, VkPhysicalDevice& physicalDevice) { // Create uniform buffer VkBufferUsageFlags usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; VkMemoryPropertyFlags properties = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; createBuffer(bufferSize, usage, properties, buffer, bufferMemory, logicalDevice, physicalDevice); } void Descriptors::createMvpBuffer(VkDeviceSize bufferSize, VkDevice& logicalDevice, VkPhysicalDevice& physicalDevice) { createUniformBuffer(bufferSize, mvpBuffer, mvpBufferMemory, logicalDevice, physicalDevice); } void Descriptors::createTimeBuffer(VkDeviceSize bufferSize, VkDevice& logicalDevice, VkPhysicalDevice& physicalDevice) { createUniformBuffer(bufferSize, timeBuffer, timeBufferMemory, logicalDevice, physicalDevice); } void Descriptors::createNumBladesBuffer(VkDeviceSize bufferSize, VkDevice& logicalDevice, VkPhysicalDevice& physicalDevice) { VkBufferUsageFlags storageUsage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; VkMemoryPropertyFlags storageFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; createBuffer(bufferSize, storageUsage, storageFlags, numBladesBuffer, numBladesBufferMemory, logicalDevice, physicalDevice); } void Descriptors::copyBufferToImage(VkDevice& logicalDevice, VkCommandPool& commandPool, VkQueue& graphicsQueue, VkBuffer& buffer, VkImage& image, uint32_t width, uint32_t height) { VkCommandBuffer commandBuffer = beginSingleTimeCommands(commandPool, logicalDevice); // Specify which part of the buffer is going to be copied to which part of the image VkBufferImageCopy region = {}; region.bufferOffset = 0; region.bufferRowLength = 0; region.bufferImageHeight = 0; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.mipLevel = 0; region.imageSubresource.baseArrayLayer = 0; region.imageSubresource.layerCount = 1; region.imageOffset = { 0, 0, 0 }; region.imageExtent = { width, height, 1 }; vkCmdCopyBufferToImage(commandBuffer, buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region); endSingleTimeCommands(commandPool, commandBuffer, graphicsQueue, logicalDevice); } void Descriptors::createTextureImage(VkDevice& logicalDevice, VkPhysicalDevice& physicalDevice, VkCommandPool& commandPool, VkQueue& graphicsQueue) { // Load the image int texWidth, texHeight, texChannels; stbi_uc* pixels = stbi_load("Textures/grass.jpg", &texWidth, &texHeight, &texChannels, STBI_rgb_alpha); VkDeviceSize imageSize = texWidth * texHeight * 4; if (!pixels) { throw std::runtime_error("Failed to load texture image"); } // Create staging buffer VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; VkBufferUsageFlags stagingUsage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; VkMemoryPropertyFlags stagingProperties = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; createBuffer(imageSize, stagingUsage, stagingProperties, stagingBuffer, stagingBufferMemory, logicalDevice, physicalDevice); // Copy pixel values to the buffer void* data; vkMapMemory(logicalDevice, stagingBufferMemory, 0, imageSize, 0, &data); memcpy(data, pixels, static_cast<size_t>(imageSize)); vkUnmapMemory(logicalDevice, stagingBufferMemory); // Free pixel array stbi_image_free(pixels); // Create Vulkan image VkFormat format = VK_FORMAT_R8G8B8A8_UNORM; VkImageTiling tiling = VK_IMAGE_TILING_OPTIMAL; VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; VkMemoryPropertyFlags properties = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; Image::createImage(logicalDevice, physicalDevice, texWidth, texHeight, format, tiling, usage, properties, textureImage, textureImageMemory); // Copy the staging buffer to the texture image // --> First need to transition the texture image to VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL Image::transitionImageLayout(logicalDevice, commandPool, graphicsQueue, textureImage, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); copyBufferToImage(logicalDevice, commandPool, graphicsQueue, stagingBuffer, textureImage, static_cast<uint32_t>(texWidth), static_cast<uint32_t>(texHeight)); // Transition texture image for shader access Image::transitionImageLayout(logicalDevice, commandPool, graphicsQueue, textureImage, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); // No need for stagin buffer anymore vkDestroyBuffer(logicalDevice, stagingBuffer, nullptr); vkFreeMemory(logicalDevice, stagingBufferMemory, nullptr); } void Descriptors::createTextureImageView(VkDevice& logicalDevice) { textureImageView = Image::createImageView(logicalDevice, textureImage, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT); } void Descriptors::createTextureSampler(VkDevice& logicalDevice) { // --- Specify all filters and transformations --- VkSamplerCreateInfo samplerInfo = {}; samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; // Interpolation of texels that are magnified or minified samplerInfo.magFilter = VK_FILTER_LINEAR; samplerInfo.minFilter = VK_FILTER_LINEAR; // Addressing mode samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; // Anisotropic filtering samplerInfo.anisotropyEnable = VK_TRUE; samplerInfo.maxAnisotropy = 16; // Border color samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK; // Choose coordinate system for addressing texels --> [0, 1) here samplerInfo.unnormalizedCoordinates = VK_FALSE; // Comparison function used for filtering operations samplerInfo.compareEnable = VK_FALSE; samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS; // Mipmapping samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; samplerInfo.mipLodBias = 0.0f; samplerInfo.minLod = 0.0f; samplerInfo.maxLod = 0.0f; if (vkCreateSampler(logicalDevice, &samplerInfo, nullptr, &textureSampler) != VK_SUCCESS) { throw std::runtime_error("Failed to create texture sampler"); } }
Python
UTF-8
104
3.34375
3
[]
no_license
def saberiDo(x): if (x == 1): return 1 return x + saberiDo(x - 1) print(saberiDo(10))
PHP
UTF-8
1,223
3.078125
3
[]
no_license
<?php /** * Een groep invoervelden die achter elkaar ge-renderd worden. * Zet geen html voor, tussen of na de velden. * * @package Forms */ namespace SledgeHammer; class Fields extends Object implements View, Import, \ArrayAccess { protected $fields; function __construct($fields = array()) { $this->fields = $fields; } function initial($values) { foreach($this->fields as $key => $null) { if (isset($values[$key])) { $this->fields[$key]->initial($values[$key]); } } } function import(&$error_messages, $source = array()) { $values = array(); foreach($this->fields as $key => $Field) { $error_message = false; $values[$key] = $this->fields[$key]->import($error_message, $source); if ($error_message) { $error_messages[$key] = $error_message; } } return $values; } function render() { foreach ($this->fields as $field) { $field->render(); } } // ArrayAccess implementatie function offsetExists($key) { return array_key_exists($key, $this->fields); } function offsetGet($key) { return $this->fields[$key]; } function offsetSet($key, $value) { $this->fields[$key] = $value; } function offsetUnset($key) { unset($this->fields[$key]); } } ?>
Java
UTF-8
1,115
2.671875
3
[]
no_license
package cn.donald.expr; import org.junit.Assert; import org.junit.Test; import java.util.List; public class InfixToPostfixTest { @Test public void test() { { List<Token> tokens = InfixToPostfix.convert("2+3"); Assert.assertEquals("[2, 3, +]", tokens.toString()); } { List<Token> tokens = InfixToPostfix.convert("2+3*4"); Assert.assertEquals("[2, 3, 4, *, +]", tokens.toString()); } { List<Token> tokens = InfixToPostfix.convert("2-3*4+5"); Assert.assertEquals("[2, 3, 4, *, -, 5, +]", tokens.toString()); } { List<Token> tokens = InfixToPostfix.convert("10-2*3+50"); Assert.assertEquals("[10, 2, 3, *, -, 50, +]", tokens.toString()); } { List<Token> tokens = InfixToPostfix.convert("5-2+8*10"); Assert.assertEquals("[5, 2, -, 8, 10, *, +]", tokens.toString()); } { List<Token> tokens = InfixToPostfix.convert("(2+3)*10"); Assert.assertEquals("[2, 3, +, 10, *]", tokens.toString()); } { List<Token> tokens = InfixToPostfix.convert("1*3+5*(10-1)"); Assert.assertEquals("[1, 3, *, 5, 10, 1, -, *, +]", tokens.toString()); } } }
Markdown
UTF-8
5,442
3.453125
3
[ "MIT" ]
permissive
# Benchmark: Faster way to count unique objects Counting unique elements is a common task in many programs. Until recently the most straightforward way to do so was something along these lines: ``` js function getUniqueElements(array) { var counter = {}; for (var i = 0; i < array.length; ++i) { var key = array[i]; counter[key] = 1; } return Object.keys(counter); } var unique = getUniqueElements(['cat', 'dog', 'cat']); // unique is: ['cat', 'dog'] ``` *SIDE NOTE*: This program has a subtle bug. ~~Open issue if you found it and I'll give you credit.~~ Kudos to @lukaszsamson, @erykpiast, @elclanrs, @Slayer95 and @bchelli for [bringing answers](https://github.com/anvaka/set-vs-object/issues)! With introduction of [Set object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) things have changed. The program can be rewritten as: ``` js function getUniqueSet(array) { return new Set(array); } var uniqueSet = getUniqueSet(['cat', 'dog', 'cat']); // uniqueSet now has only two elements 'cat' and 'dog'. ``` `Set` is [supported by all major browsers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#Browser_compatibility) but is it really faster than plain old `Object`? TL;DR **Set is almost two times faster than Object**. **In the context of `getUniqueElement`, it depends on the input data. Set is faster than Object when duplication ratio is less than 0.3. Otherwise, plain object is faster.** ## Benchmark: Jaccard Similarity [Jaccard similarity](https://en.wikipedia.org/wiki/Jaccard_index) is a simple function which takes two sets and returns their "similarity" index: ``` function similarity(A, B) { intersection = (number of shared elements between A and B) union = (number of unique elements in A and B) return intersection/union } ``` For example, similarity between set `cat, dog, bird` and set `cat` is `1/3`. There is one shared element (`cat`), and there are three unique elements. Now we have to implement this function two times: using `Set` and using `Object`: ``` js function similarityObject(objA, objB) { var aKeys = Object.keys(objA); var intersect = 0; aKeys.forEach(function(key) { if (objB[key]) intersect += 1; }); var objBSize = Object.keys(setB).length var objASize = aKeys.length; var similarity = intersect/(objASize + objBSize - intersect); return similarity; } function similaritySet(setA, setB) { var intersect = 0; setA.forEach(function(key) { if (setB.has(key)) intersect += 1; }); var similarity = intersect/(setA.size + setB.size - intersect); return similarity; } ``` To have statistically reliable answers we run these functions over and over again on the same data set and count how many times we were able to compute similarity index. [Benchmark](https://www.npmjs.com/package/benchmark) module is extremely good for this. Here are the results: ``` > node index.js Compute jaccard similarity with Set x 1,232 ops/sec ±1.45% (87 runs sampled) Compute jaccard similarity with Map x 1,193 ops/sec ±1.33% (88 runs sampled) Compute jaccard similarity with objects (Object.keys()) x 616 ops/sec ±1.32% (85 runs sampled) Compute jaccard similarity with objects (for in) x 600 ops/sec ±1.46% (82 runs sampled) ``` Set objects are almost two times faster than our old plain Object. The tests were executed using v8 engine `4.6.85.31`. ## Benchmark: Emulating Set Creation ``` > node creation.js Huge collision Obj (size: 1000) x 20,350 ops/sec ±1.00% (91 runs sampled) Huge collision Set (size: 1000) x 12,017 ops/sec ±1.00% (90 runs sampled) High collision Obj (size: 1000) x 19,266 ops/sec ±1.19% (91 runs sampled) High collision Set (size: 1000) x 11,005 ops/sec ±0.94% (92 runs sampled) Fare collision Obj (size: 1000) x 7,669 ops/sec ±0.97% (90 runs sampled) Fare collision Set (size: 1000) x 10,974 ops/sec ±0.96% (93 runs sampled) Rare collision Obj (size: 1000) x 2,689 ops/sec ±1.00% (93 runs sampled) Rare collision Set (size: 1000) x 10,444 ops/sec ±1.42% (93 runs sampled) Huge collision: 57.8% duplication High collision: 36.8% duplication Fare collision: 15% duplication Rare collision: 4.8% duplication ``` Set objects are faster than old plain Object when a small fraction of duplicated elements are expected. When getting unique elements from an array with a high percentage of duplicates, old plain object is still faster. The tests were executed using node.js v8.4.0. ## Memory consideration I compared RAM consumption by building 10,000,000 string keys and stored them both as object keys and as set elements. There was no significant difference between two approaches: Set used ~913MB, while Object was ~942MB. You can find code in [testMemory.sh](https://github.com/anvaka/set-vs-object/blob/master/testMemory.sh) # Conclusion Sets are awesome and we should use them more often. They are fast, and supported by Chrome, Firefox, Microsoft Edge, and node.js. You can explore [index.js](https://github.com/anvaka/set-vs-object/blob/master/index.js) file to see the actual benchmark code. ## Bonus If you haven't seen it yet, watch this video about performance and benchmarking from Vyacheslav Egorov: https://www.youtube.com/watch?v=65-RbBwZQdU . He doesn't talk about Sets or Jaccard similarity. His view on benchmarking changed how I perceive them now, and I hope you will love it too!
Python
UTF-8
5,106
2.578125
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # # Project World Bank # # By Mostafa Jubayer Khan # # # In[1]: #Importing the Pandas & NumPy Libraries import pandas as pd import numpy as np import pandas_gbq as gbq # ### Reading the all the CSV Files # In[2]: df_1 = pd.read_csv('/Users/mostafajubayerkhan/Desktop/Education/Nandish_IT/Data/API_EN.ATM.PM25.MC.ZS_DS2_en_csv_v2_1217689.csv', sep=',', header=0, skiprows=3, nrows=267) df_1.columns df_2 = pd.read_csv('/Users/mostafajubayerkhan/Desktop/Education/Nandish_IT/Data/API_NY.GDP.MKTP.CD_DS2_en_csv_v2_1217511.csv', sep=',', header=0, skiprows=3, nrows=267) df_2.columns df_3 = pd.read_csv('/Users/mostafajubayerkhan/Desktop/Education/Nandish_IT/Data/API_NY.GDP.MKTP.KD.ZG_DS2_en_csv_v2_1217525.csv', sep=',', header=0, skiprows=3, nrows=267) df_3.columns df_4 = pd.read_csv('/Users/mostafajubayerkhan/Desktop/Education/Nandish_IT/Data/API_SE.PRM.CMPT.ZS_DS2_en_csv_v2_1217813.csv', sep=',', header=0, skiprows=3, nrows=267) df_4.columns df_5 = pd.read_csv('/Users/mostafajubayerkhan/Desktop/Education/Nandish_IT/Data/API_SI.POV.DDAY_DS2_en_csv_v2_1217581.csv', sep=',', header=0, skiprows=3, nrows=267) df_5.columns df_6 = pd.read_csv('/Users/mostafajubayerkhan/Desktop/Education/Nandish_IT/Data/API_SP.POP.1564.TO.ZS_DS2_en_csv_v2_1217810.csv', sep=',', header=0, skiprows=3, nrows=267) df_6.columns df_7 = pd.read_csv('/Users/mostafajubayerkhan/Desktop/Education/Nandish_IT/Data/API_SP.POP.TOTL_DS2_en_csv_v2_1217749.csv', sep=',', header=0, skiprows=3, nrows=267) df_7.columns # In[3]: # Removing the last, unwanted "Unamed : 64" Column from all the DataFrame. df_1=df_1.drop('Unnamed: 64' , 1) df_1.columns df_2=df_2.drop('Unnamed: 64' , 1) df_2.columns df_3=df_3.drop('Unnamed: 64' , 1) df_3.columns df_4=df_4.drop('Unnamed: 64' , 1) df_4.columns df_5=df_5.drop('Unnamed: 64' , 1) df_5.columns df_6=df_6.drop('Unnamed: 64' , 1) df_6.columns df_7=df_7.drop('Unnamed: 64' , 1) df_7.columns # In[4]: df_1= df_1.melt(id_vars = ['Country Name', 'Country Code', 'Indicator Name', 'Indicator Code'], var_name = "year") df_2= df_2.melt(id_vars = ['Country Name', 'Country Code', 'Indicator Name', 'Indicator Code'], var_name = "year") df_3= df_3.melt(id_vars = ['Country Name', 'Country Code', 'Indicator Name', 'Indicator Code'], var_name = "year") df_4= df_4.melt(id_vars = ['Country Name', 'Country Code', 'Indicator Name', 'Indicator Code'], var_name = "year") df_5= df_5.melt(id_vars = ['Country Name', 'Country Code', 'Indicator Name', 'Indicator Code'], var_name = "year") df_6= df_6.melt(id_vars = ['Country Name', 'Country Code', 'Indicator Name', 'Indicator Code'], var_name = "year") df_7= df_7.melt(id_vars = ['Country Name', 'Country Code', 'Indicator Name', 'Indicator Code'], var_name = "year") # In[5]: # Renaming to Columns of the respective dataframes for removing extra space within the columns for uploading into the GoogLe Big Query df_1=df_1.rename(columns={'Country Name':'Country_Name','Country Code':'Country_Code','Indicator Name':'Indicator_Name','Indicator Code': 'Indicator_Code'}) df_2=df_2.rename(columns={'Country Name':'Country_Name','Country Code':'Country_Code','Indicator Name':'Indicator_Name','Indicator Code': 'Indicator_Code'}) df_3=df_3.rename(columns={'Country Name':'Country_Name','Country Code':'Country_Code','Indicator Name':'Indicator_Name','Indicator Code': 'Indicator_Code'}) df_4=df_4.rename(columns={'Country Name':'Country_Name','Country Code':'Country_Code','Indicator Name':'Indicator_Name','Indicator Code': 'Indicator_Code'}) df_5=df_5.rename(columns={'Country Name':'Country_Name','Country Code':'Country_Code','Indicator Name':'Indicator_Name','Indicator Code': 'Indicator_Code'}) df_6=df_6.rename(columns={'Country Name':'Country_Name','Country Code':'Country_Code','Indicator Name':'Indicator_Name','Indicator Code': 'Indicator_Code'}) df_7=df_7.rename(columns={'Country Name':'Country_Name','Country Code':'Country_Code','Indicator Name':'Indicator_Name','Indicator Code': 'Indicator_Code'}) # ### Uploading all the dataframes (df_1 to df_7) into the Google BigQuery # In[6]: # Uploading all the 7 dataframes in to the Google Big Query a = gbq.to_gbq(df_1, destination_table='BigQuery.df_1', project_id='commanding-air-282216', if_exists='replace') b = gbq.to_gbq(df_2, destination_table='BigQuery.df_2', project_id='commanding-air-282216', if_exists='replace') c = gbq.to_gbq(df_3, destination_table='BigQuery.df_3', project_id='commanding-air-282216', if_exists='replace') d = gbq.to_gbq(df_4, destination_table='BigQuery.df_4', project_id='commanding-air-282216', if_exists='replace') e = gbq.to_gbq(df_5, destination_table='BigQuery.df_5', project_id='commanding-air-282216', if_exists='replace') f = gbq.to_gbq(df_6, destination_table='BigQuery.df_6', project_id='commanding-air-282216', if_exists='replace') g = gbq.to_gbq(df_7, destination_table='BigQuery.df_7', project_id='commanding-air-282216', if_exists='replace') df =[a,b,c,d,e,f,g] for i in df : # i += 1 pass print('Done Uploading into gbq') print('Done Uploading into gbq') # In[ ]:
TypeScript
UTF-8
732
2.65625
3
[ "MIT" ]
permissive
import * as vscode from 'vscode' import * as paths from './paths' export function isMarkdown(doc: vscode.TextDocument): boolean { return doc.fileName.split('.').pop() === 'md' } export function getTitle(doc: vscode.TextDocument): string | undefined { if (!isMarkdown(doc)) { return } const line = doc.lineAt(0) const match = line.text.match(/#\s(\S.*)/) if (match) { return match[1] } } interface LinkMarkupArg { alt: string fromFile: string toFile: string } export function localLinkMarkup(arg: LinkMarkupArg) { const relPath = paths.getRelPath(arg.fromFile, arg.toFile) return `[+${arg.alt}](${relPath})` } export function linkMarkup(alt: string, uri: string) { return `[${alt}](${uri})` }
Markdown
UTF-8
1,590
2.65625
3
[]
no_license
# Introduction This project started with some self reflection and a simple observation. I often unwind with an episode of the british panel comedy show [Would I Lie To You?](https://en.wikipedia.org/wiki/List_of_Would_I_Lie_to_You%3F_episodes) In one particualr episode, it seemed like the female guests had their suggestions ignored by the team leaders. It got me thinking that it might be a great dataset to dig a little further into. It's essentially a convergence of 3 things I love: * Skepticism - I wonder if that's really how it is, or just confirmation bias? * Quantitive analysis - Nothing better than bringing some numbers to a slippery problem * Offbeat british humour - This seems as harmless as it can be. Does bias dwell even here? I'm certain there's no overt ill will within the show, and I'm sure they actively go out of their way to make their guests as welcome and respected as possible. In some ways that makes this all the more interesting. Does bias emerge even in such a welcoming and respectful enviroment? ## Data sources For now, I'm planning on pulling the episode and team lists from the wikipedia page linked above. I haven't found any other fansite resources where individual round results have been compiled, so that side is going ot require some good old fashioned screen time. No complaints here. ## Manual updates If you make manual edits to the json data file, the atom plugin 'Pretty JSON' is a reliable way to reformat the file so its layout stays consistent with the scraper script. This helps to avoid whiespace churn in the diffs on this file.
Python
UTF-8
1,507
4.09375
4
[]
no_license
""" Given an array of positive integers target and an array initial of same size with all zeros. Return the minimum number of operations to form a target array from initial if you are allowed to do the following operation: Choose any subarray from initial and increment each value by one. Input: target = [1,2,3,2,1] Output: 3 Explanation: We need at least 3 operations to form the target array from the initial array. [0,0,0,0,0] increment 1 from index 0 to 4 (inclusive). [1,1,1,1,1] increment 1 from index 1 to 3 (inclusive). [1,2,2,2,1] increment 1 at index 2. [1,2,3,2,1] target array is formed. Approach: target = [1,2,3,2,1] dp = [1, 0, 0, 0, 0] for i in range(1, 5): 1. i = 1 target[1] = 2 > target[0] = 1 ---> Go to else dp[1] = dp[0] + (2 - 1) = 1 + 1 = 2 dp =[1,2,0,0,0] 2. i = 2 target[2] = 3 > target[1] = 2 ---> Go to else dp[2] = dp[1] + (3 - 2) = 2 + 1 = 3 dp = [1,2,3,0,0] 3. i = 3 target[3] = 2 <= target[2] = 3 ---> enter if dp[3] = dp[2] = 3 dp = [1, 2, 3, 3, 0] 4. i = 4 target[4] = 1 <= target[3] = 2 --> enter if dp[4] = dp[3] = 3 dp = [1,2,3,3,3] Return 3 """ from typing import List def minNumberOperations(target: List[int]) -> int: n = len(target) dp = [0] * n dp[0] = target[0] for i in range(1, n): if target[i] <= target[i-1]: dp[i] = dp[i-1] else: dp[i] = dp[i-1] + (target[i] - target[i-1]) return dp[n-1]
C#
UTF-8
1,826
2.796875
3
[]
no_license
using Microsoft.Extensions.Logging; using System; using System.Diagnostics; using System.Threading.Tasks; using systeminfo.Core.Entities; namespace systeminfo.Core.Services.Unix { public class UnixDiskMetricsProvider : IDiskMetricsProvider { private readonly ILogger<UnixDiskMetricsProvider> _logger; public UnixDiskMetricsProvider(ILogger<UnixDiskMetricsProvider> logger) { _logger = logger; } public async Task<DiskMetrics> GetDiskMetrics(string fs) { var output = ""; var cmd = string.Format("df | grep '{0}' | xargs", fs); var info = new ProcessStartInfo(cmd); info.FileName = "/bin/bash"; info.Arguments = $"-c \"{cmd}\""; info.RedirectStandardOutput = true; _logger.LogInformation($"Executing cmd {cmd}"); using (var process = Process.Start(info)) { output = await process.StandardOutput.ReadToEndAsync(); _logger.LogInformation($"Obtained external proccess output"); _logger.LogInformation(output); } var data = output.Split(' ', StringSplitOptions.RemoveEmptyEntries); _logger.LogInformation($"Final values {string.Join(", ", data)}"); var filesystem = data[0]; var size = int.Parse(data[1]); var used = int.Parse(data[2]); var avail = int.Parse(data[3]); var use = int.Parse(data[4].TrimEnd('%')); var metrics = new DiskMetrics( new Percentage(use), size, used, avail, filesystem); _logger.LogInformation($"Disk metrics {metrics}"); return metrics; } } }
Java
UTF-8
888
3.40625
3
[]
no_license
package co.edu.uptc.logica.modelo; /** * clase que define a la entidad Producto * @author Marcos Esteban Vargas Avella * */ public class Producto { private String name; private double price; /** * Constructor de clase vacio */ public Producto() { } /** * Constructor de la clase para instanciar * @param name parametro que representa el nombre del producto, des de tipo String * @param price Parametro de tipo double que representa el valor del producto */ public Producto(String name,double price) { this.name = name; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Producto [nombre=" + name + ", precio=" + price + "]"; } }
Python
UTF-8
381
2.796875
3
[]
no_license
import time from twisted.internet import reactor, threads, defer # To be executed in thread, not coroutine. def do_long_calculation(): time.sleep(3) return 3 @defer.inlineCallbacks def print_result(): # Await thread temination x = yield threads.deferToThread(do_long_calculation) print(x) print_result().addCallback(lambda ign: reactor.stop()) reactor.run()
Markdown
UTF-8
3,668
3
3
[]
no_license
_model:blog-post --- title1:雜學校 創新教育博覽會 --- title2:——你的選擇,你的有敢擇學 --- date:2017/11/04 --- info:今天的行程是考試,上課,讀書;明天的行程是考試,上課,讀書。後天也是、大後天也是,到了明年依然是。有一說法是,我們的現行教育體制......(繼續閱讀) --- content: <p> 今天的行程是考試,上課,讀書;明天的行程是考試,上課,讀書。<br>後天也是、大後天也是,到了明年依然是。 </p> <p> 有一說法是,我們的現行教育體制是源自工業革命時期,為滿足更多生產需求而生,也因此制定出統一的上課時段、課程內容、整齊的劃位以方便管理,並規定上課要安靜、講話要舉手。與一世紀前相仿的模式,套用於現今更加資本化的社會,高等教育的低學費、高資源以及制式的成績衡量方式,某方面造成了更多人追求更好的成績、上更好的學校,隨著時間加成,多人競爭的少量資源(可能是學校或排名)被賦予了光環,升學主義就此緊扣國民教育,形成了一套扭曲而堅固的教育體制。 </p> <p> 本就機械化而制式、不太允許學生自我創意思考的教育模式,加上升學主義高漲,學生一方面無法在教育裡受到啟蒙開始為自我反思,一方面也沒有時間。<br>因為,明天還要考試,上課,讀書。 </p> <p> 然而我們選擇了這個體制(體制外學校另當別論),彼此也就相互依存。我們深知未來需要這套體制中的獲利(好的學歷),以作為進入社會的助力。然而身處體制內,我們害怕選擇離開體制後,失去學歷優勢,又無奈於在體制內,追逐優勢的過程。 </p> <p> 「人生的原廠設定:超勇敢」這是雜學校的宣傳語之一。<br>勇敢是種選擇,選擇需要勇敢。或許我們也就正需要這樣的勇敢。追求自我的心之所向需要勇敢、放下體制追尋夢想需要勇敢、突破體制需要勇敢。因為如此,我們勢必得放下失去,失去原本體制內的優勢。<br>雜學校,亞洲教育創新博覽會,集結了近乎所有台灣能遇見的體制外教育機構或組織,與轉型中的體制內學校。我們看到了在各種不同的領域、各種不同的面向,用相同程度的熱情,滿懷理想正在努力勇敢改變的一群人。 </p> <p> 然而現況是,我們依然依存於體制內。<br>如果真的勇敢放手一搏,是否我們的未來就成了一場豪賭?倘若失敗,今天的勇氣不過匹夫之勇,我們成了教育轉型中自願的犧牲者,或者說,投資不利的失敗者。如果我們在大勇敢之前沒有資本(像是突出的天份與智商,能夠完全跳脫體制),那就給自己一些小小的勇敢吧。 </p> <p> 當然,這所謂的小小勇敢就是,勢必得放棄掉一點點追求頂尖分數的時間。 </p> <br> <p><a href="https://letsnews.thisistap.com/2547/%E5%8D%87%E5%AD%B8%E4%B8%BB%E7%BE%A9%E7%9A%84%E5%B9%95%E5%BE%8C%E7%9C%9F%E5%85%87%E2%94%80%E2%94%80%E5%BE%9E%E5%A4%A7%E5%AD%B8%E5%AD%B8%E8%B2%BB%E7%9C%8B%E3%80%8C%E5%88%86%E6%95%B8%E8%BF%B7%E6%80%9D/">參考文章:升學主義的幕後真兇──從大學學費看「分數迷思」的由來(文/黃化臻 編輯/傅觀)</a></p> <p><a href="http://zashare.org/">雜學校網站</a></p>
PHP
UTF-8
17,009
2.546875
3
[ "MIT" ]
permissive
<?php /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Tokenizer; use PhpCsFixer\Tests\TestCase; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @covers \PhpCsFixer\Tokenizer\Token */ final class TokenTest extends TestCase { /** * @param mixed $input * * @dataProvider provideConstructorValidationCases */ public function testConstructorValidation($input) { $this->expectException(\InvalidArgumentException::class); new Token($input); } public function provideConstructorValidationCases() { return [ [null], [123], [new \stdClass()], [['asd', 'asd']], [[null, 'asd']], [[new \stdClass(), 'asd']], [[T_WHITESPACE, null]], [[T_WHITESPACE, 123]], [[T_WHITESPACE, '']], [[T_WHITESPACE, new \stdClass()]], ]; } /** * @group legacy * @expectedDeprecation PhpCsFixer\Tokenizer\Token::clear is deprecated and will be removed in 3.0. */ public function testClear() { $token = $this->getForeachToken(); $token->clear(); Tokens::setLegacyMode(false); static::assertSame('', $token->getContent()); static::assertNull($token->getId()); static::assertFalse($token->isArray()); } public function testGetPrototype() { static::assertSame($this->getBraceTokenPrototype(), $this->getBraceToken()->getPrototype()); static::assertSame($this->getForeachTokenPrototype(), $this->getForeachToken()->getPrototype()); } public function testIsArray() { static::assertFalse($this->getBraceToken()->isArray()); static::assertTrue($this->getForeachToken()->isArray()); } /** * @param bool $isCast * * @dataProvider provideIsCastCases */ public function testIsCast(Token $token, $isCast) { static::assertSame($isCast, $token->isCast()); } public function provideIsCastCases() { return [ [$this->getBraceToken(), false], [$this->getForeachToken(), false], [new Token([T_ARRAY_CAST, '(array)', 1]), true], [new Token([T_BOOL_CAST, '(bool)', 1]), true], [new Token([T_DOUBLE_CAST, '(double)', 1]), true], [new Token([T_INT_CAST, '(int)', 1]), true], [new Token([T_OBJECT_CAST, '(object)', 1]), true], [new Token([T_STRING_CAST, '(string)', 1]), true], [new Token([T_UNSET_CAST, '(unset)', 1]), true], ]; } /** * @param bool $isClassy * * @dataProvider provideIsClassyCases */ public function testIsClassy(Token $token, $isClassy) { static::assertSame($isClassy, $token->isClassy()); } public function provideIsClassyCases() { return [ [$this->getBraceToken(), false], [$this->getForeachToken(), false], [new Token([T_CLASS, 'class', 1]), true], [new Token([T_INTERFACE, 'interface', 1]), true], [new Token([T_TRAIT, 'trait', 1]), true], ]; } /** * @param bool $isComment * * @dataProvider provideIsCommentCases */ public function testIsComment(Token $token, $isComment) { static::assertSame($isComment, $token->isComment()); } public function provideIsCommentCases() { return [ [$this->getBraceToken(), false], [$this->getForeachToken(), false], [new Token([T_COMMENT, '/* comment */', 1]), true], [new Token([T_DOC_COMMENT, '/** docs */', 1]), true], ]; } /** * @group legacy * @expectedDeprecation PhpCsFixer\Tokenizer\Token::isEmpty is deprecated and will be removed in 3.0. */ public function testIsEmpty() { $braceToken = $this->getBraceToken(); static::assertFalse($braceToken->isEmpty()); $emptyToken = new Token(''); static::assertTrue($emptyToken->isEmpty()); $whitespaceToken = new Token([T_WHITESPACE, ' ']); static::assertFalse($whitespaceToken->isEmpty()); } public function testIsGivenKind() { $braceToken = $this->getBraceToken(); $foreachToken = $this->getForeachToken(); static::assertFalse($braceToken->isGivenKind(T_FOR)); static::assertFalse($braceToken->isGivenKind(T_FOREACH)); static::assertFalse($braceToken->isGivenKind([T_FOR])); static::assertFalse($braceToken->isGivenKind([T_FOREACH])); static::assertFalse($braceToken->isGivenKind([T_FOR, T_FOREACH])); static::assertFalse($foreachToken->isGivenKind(T_FOR)); static::assertTrue($foreachToken->isGivenKind(T_FOREACH)); static::assertFalse($foreachToken->isGivenKind([T_FOR])); static::assertTrue($foreachToken->isGivenKind([T_FOREACH])); static::assertTrue($foreachToken->isGivenKind([T_FOR, T_FOREACH])); } public function testIsKeywords() { static::assertTrue($this->getForeachToken()->isKeyword()); static::assertFalse($this->getBraceToken()->isKeyword()); } /** * @param ?int $tokenId * @param string $content * @param bool $isConstant * * @dataProvider provideMagicConstantCases */ public function testIsMagicConstant($tokenId, $content, $isConstant = true) { $token = new Token( null === $tokenId ? $content : [$tokenId, $content] ); static::assertSame($isConstant, $token->isMagicConstant()); } public function provideMagicConstantCases() { $cases = [ [T_CLASS_C, '__CLASS__'], [T_DIR, '__DIR__'], [T_FILE, '__FILE__'], [T_FUNC_C, '__FUNCTION__'], [T_LINE, '__LINE__'], [T_METHOD_C, '__METHOD__'], [T_NS_C, '__NAMESPACE__'], [T_TRAIT_C, '__TRAIT__'], ]; foreach ($cases as $case) { $cases[] = [$case[0], strtolower($case[1])]; } foreach ([$this->getForeachToken(), $this->getBraceToken()] as $token) { $cases[] = [$token->getId(), $token->getContent(), false]; $cases[] = [$token->getId(), strtolower($token->getContent()), false]; } return $cases; } /** * @param bool $isNativeConstant * * @dataProvider provideIsNativeConstantCases */ public function testIsNativeConstant(Token $token, $isNativeConstant) { static::assertSame($isNativeConstant, $token->isNativeConstant()); } public function provideIsNativeConstantCases() { return [ [$this->getBraceToken(), false], [$this->getForeachToken(), false], [new Token([T_STRING, 'null', 1]), true], [new Token([T_STRING, 'false', 1]), true], [new Token([T_STRING, 'true', 1]), true], [new Token([T_STRING, 'tRuE', 1]), true], [new Token([T_STRING, 'TRUE', 1]), true], ]; } /** * @param bool $isWhitespace * @param null|string $whitespaces * * @dataProvider provideIsWhitespaceCases */ public function testIsWhitespace(Token $token, $isWhitespace, $whitespaces = null) { if (null !== $whitespaces) { static::assertSame($isWhitespace, $token->isWhitespace($whitespaces)); } else { static::assertSame($isWhitespace, $token->isWhitespace(null)); static::assertSame($isWhitespace, $token->isWhitespace()); } } public function provideIsWhitespaceCases() { return [ [$this->getBraceToken(), false], [$this->getForeachToken(), false], [new Token(' '), true], [new Token("\t "), true], [new Token("\t "), false, ' '], [new Token([T_WHITESPACE, "\r", 1]), true], [new Token([T_WHITESPACE, "\0", 1]), true], [new Token([T_WHITESPACE, "\x0B", 1]), true], [new Token([T_WHITESPACE, "\n", 1]), true], [new Token([T_WHITESPACE, "\n", 1]), false, " \t"], ]; } /** * @param mixed $prototype * @param null|int $expectedId * @param null|string $expectedContent * @param null|bool $expectedIsArray * @param null|string $expectedExceptionClass * * @dataProvider provideCreatingTokenCases */ public function testCreatingToken($prototype, $expectedId, $expectedContent, $expectedIsArray, $expectedExceptionClass = null) { if ($expectedExceptionClass) { $this->expectException($expectedExceptionClass); } $token = new Token($prototype); static::assertSame($expectedId, $token->getId()); static::assertSame($expectedContent, $token->getContent()); static::assertSame($expectedIsArray, $token->isArray()); } public function provideCreatingTokenCases() { return [ [[T_FOREACH, 'foreach'], T_FOREACH, 'foreach', true], ['(', null, '(', false], [123, null, null, null, \InvalidArgumentException::class], [false, null, null, null, \InvalidArgumentException::class], [null, null, null, null, \InvalidArgumentException::class], ]; } public function testEqualsDefaultIsCaseSensitive() { $token = new Token([T_FUNCTION, 'function', 1]); static::assertTrue($token->equals([T_FUNCTION, 'function'])); static::assertFalse($token->equals([T_FUNCTION, 'Function'])); } /** * @param bool $equals * @param array|string|Token $other * @param bool $caseSensitive * * @dataProvider provideEqualsCases */ public function testEquals(Token $token, $equals, $other, $caseSensitive = true) { static::assertSame($equals, $token->equals($other, $caseSensitive)); } public function provideEqualsCases() { $brace = $this->getBraceToken(); $function = new Token([T_FUNCTION, 'function', 1]); return [ [$brace, false, '!'], [$brace, false, '!', false], [$brace, true, '('], [$brace, true, '(', false], [$function, false, '('], [$function, false, '(', false], [$function, false, [T_NAMESPACE]], [$function, false, [T_NAMESPACE], false], [$function, false, [T_VARIABLE, 'function']], [$function, false, [T_VARIABLE, 'function'], false], [$function, false, [T_VARIABLE, 'Function']], [$function, false, [T_VARIABLE, 'Function'], false], [$function, true, [T_FUNCTION]], [$function, true, [T_FUNCTION], false], [$function, true, [T_FUNCTION, 'function']], [$function, true, [T_FUNCTION, 'function'], false], [$function, false, [T_FUNCTION, 'Function']], [$function, true, [T_FUNCTION, 'Function'], false], [$function, false, [T_FUNCTION, 'junction'], false], [$function, true, new Token([T_FUNCTION, 'function'])], [$function, false, new Token([T_FUNCTION, 'Function'])], [$function, true, new Token([T_FUNCTION, 'Function']), false], // if it is an array any additional field is checked too [$function, false, [T_FUNCTION, 'function', 'unexpected']], ]; } public function testEqualsAnyDefaultIsCaseSensitive() { $token = new Token([T_FUNCTION, 'function', 1]); static::assertTrue($token->equalsAny([[T_FUNCTION, 'function']])); static::assertFalse($token->equalsAny([[T_FUNCTION, 'Function']])); } /** * @param bool $equalsAny * @param bool $caseSensitive * * @dataProvider provideEqualsAnyCases */ public function testEqualsAny($equalsAny, array $other, $caseSensitive = true) { $token = new Token([T_FUNCTION, 'function', 1]); static::assertSame($equalsAny, $token->equalsAny($other, $caseSensitive)); } public function provideEqualsAnyCases() { $brace = $this->getBraceToken(); $foreach = $this->getForeachToken(); return [ [false, []], [false, [$brace]], [false, [$brace, $foreach]], [true, [$brace, $foreach, [T_FUNCTION]]], [true, [$brace, $foreach, [T_FUNCTION, 'function']]], [false, [$brace, $foreach, [T_FUNCTION, 'Function']]], [true, [$brace, $foreach, [T_FUNCTION, 'Function']], false], [false, [[T_VARIABLE, 'junction'], [T_FUNCTION, 'junction']], false], ]; } /** * @param bool $isKeyCaseSensitive * @param array|bool $caseSensitive * @param int $key * * @dataProvider provideIsKeyCaseSensitiveCases */ public function testIsKeyCaseSensitive($isKeyCaseSensitive, $caseSensitive, $key) { static::assertSame($isKeyCaseSensitive, Token::isKeyCaseSensitive($caseSensitive, $key)); } public function provideIsKeyCaseSensitiveCases() { return [ [true, true, 0], [true, true, 1], [true, [], 0], [true, [true], 0], [true, [false, true], 1], [true, [false, true, false], 1], [true, [false], 10], [false, false, 10], [false, [false], 0], [false, [true, false], 1], [false, [true, false, true], 1], [false, [1 => false], 1], ]; } /** * @group legacy * @expectedDeprecation PhpCsFixer\Tokenizer\Token::isChanged is deprecated and will be removed in 3.0. */ public function testIsChanged() { $token = new Token([T_WHITESPACE, ' ']); static::assertFalse($token->isChanged()); } /** * @param null|string $expected * @param int $id * * @dataProvider provideTokenGetNameCases */ public function testTokenGetNameForId($expected, $id) { static::assertSame($expected, Token::getNameForId($id)); } public function provideTokenGetNameCases() { return [ [ null, -1, ], [ 'T_CLASS', T_CLASS, ], [ 'CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE', CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE, ], ]; } /** * @param null|string $expected * * @dataProvider provideGetNameCases */ public function testGetName(Token $token, $expected = null) { static::assertSame($expected, $token->getName()); } public function provideGetNameCases() { yield [ new Token([T_FUNCTION, 'function', 1]), 'T_FUNCTION', ]; yield [ new Token(')'), null, ]; yield [ new Token(''), null, ]; } /** * @dataProvider provideToArrayCases */ public function testToArray(Token $token, array $expected) { static::assertSame($expected, $token->toArray()); } public function provideToArrayCases() { yield [ new Token([T_FUNCTION, 'function', 1]), [ 'id' => T_FUNCTION, 'name' => 'T_FUNCTION', 'content' => 'function', 'isArray' => true, 'changed' => false, ], ]; yield [ new Token(')'), [ 'id' => null, 'name' => null, 'content' => ')', 'isArray' => false, 'changed' => false, ], ]; yield [ new Token(''), [ 'id' => null, 'name' => null, 'content' => '', 'isArray' => false, 'changed' => false, ], ]; } private function getBraceToken() { return new Token($this->getBraceTokenPrototype()); } private function getBraceTokenPrototype() { return '('; } private function getForeachToken() { return new Token($this->getForeachTokenPrototype()); } private function getForeachTokenPrototype() { static $prototype = [T_FOREACH, 'foreach']; return $prototype; } }
JavaScript
UTF-8
8,271
3.984375
4
[]
no_license
// 1. Оголосіть змінні str, num, flag и txt зі значеннями «Привіт», 123, true, «true». // За допомогою typeof переконайтесь, що значення змінних належать типам: string, number и boolean. let str5 = 'Привіт'; console.log(typeof str5); let num = 123; console.log(typeof num); let flag = true; console.log(flag); let txt = "true"; console.log(txt); // 2. Оголосіть змінні a1, a2, a3, a4, a5.За домогою 3х математичних оператцій, отримайте числа: 34, 12, 66, 90, 87. // Старайтесь використовувати різні оператори.Example: // 88 = (16 / 2) * 11 let a1 = 10 * 2 - 5 + 10 / 2 + 10 + 4; console.log(a1); let a2 = 6 + 8 / 2 + 2 console.log(a2); let a3 = (40 - 10 + 3) * 2 console.log(a3); let a4 = 10 * 11 - 20 console.log(a4); let a5 = 2 * 40 + 7 console.log(a5); // 3. Створіть змінні a6, a7, a8, a9, a10. Запишіть в них результати виразів: // 5 % 3, // 3 % 5, // 5 + '3', // '5' - 3, // 75 + 'кг' let a6 = 5 % 3; console.log(a6); let a7 = 3 % 5; console.log(a7); let a8 = 5 + '3'; console.log(a8); let a9 = '5' - 3; console.log(a9); let a10 = 75 + 'кг'; console.log(a10); // 4. Напишіть код, який вираховує площу прямокутника висотою 23см. (змінна height) та шириною 10см (змінна width). // Значееня площі зберігати в змінній s. let height = 23; let width = 10; let s = height*width; console.log(s); // 5. Напиши код, который находит объем цилиндра высотой 10м (переменная heightC) и диаметром основания 4м (dC), // результат поместите в переменную v. let dC = +prompt('введіть число'); let rC1 = dC/2; let rC2 = +prompt('введіть степінь'); let rC = Math.pow(rC1,rC2); const PI = 3.14; let heightC = +prompt('введіть число'); let v = heightC*rC*PI; console.log(v); // 6. У прямоугольного треугольника две стороны n (со значением 3) и m (со значением 4). // Найдите гипотенузу k по теореме Пифагора (нужно использовать функцию Math.pow(число, степень) или оператор возведения в степень ** ). let n = 3; let m = 4; let k = Math.sqrt(Math.pow(n, 2) + Math.pow(m, 2)); console.log(k); // 8. Вывести в окно браузера при помощи метода alert() следующие данные: Ваше ФИО, возраст, хобби (каждой на новой строки спомощью \n). let name = 'Данилюк Оксана Олександрівна'; let age = 29; let hobby = 'редизайн меблів'; alert(`ПІП: ${name}\nВік: ${age}\nХоббі: ${hobby}`); // 9. Создать 4 переменные с использованием ключевого слова let с именами str1, str2, str3, concatenation. // Переменной str1 присвоить фразу ‘Кто ‘, str2 – ‘ты ‘, str3 – ‘такой?’ // Локальной переменной concatenation присвоить результат конкатенации 3-х строк: str1, str2, str3. // Вывести в документ содержимое переменной concatenation спомощью document.write let str1 = 'Хто'; let str2 = 'ти'; let str3 = 'такий?'; let concatenation = (`<p>${str1} ${str2} ${str3}</p>`); document.write(concatenation); // 10. Подумайте Какие значения выведет в окно браузера следующий фрагмент кода? и почему? let str = "20"; let a = 5; document.write(str + a + "<br/>"); // 205 document.write(str - a + "<br/>"); // 15 document.write(str * "2" + "<br/>");// 40 document.write(str / 2 + "<br/>");// 10 // 13. С помощью окна ввода, вызываемого методом prompt, сделать сложение двух чисел, а вывод результата при помощи метода alert let num1 = +prompt('введіть число №1'); let num2 = +prompt('введіть число №2'); let summ = num1 + num2; alert(summ); // 14. С помощью окна ввода, вызываемого методом prompt, пользователь последовательно выводит имя, фамилию и возраст, а вам не обходимо вывести строку такого вида // Доброго вечера Иван Иванов, мои поздравления что вам 32 , а вывод результата при помощи метода alert let firstName = prompt('Введіть Ваше ім"я'); let lastName = prompt('Введіть Ваше прізвище'); let yourAge = +prompt('Введіть Ваш вік'); alert(`Доброго вечора ${firstName} ${lastName}, мої вітання, що Вам ${yourAge}!`); // --------------------------ДОДАТКОВО----------------------------- // 1. Три різних числа вводяться через prompt(). // За допомоги if else вивести іх в порядку зростання. (відсортувати по зростанню) let n1 = +prompt('Введіть число №1'); let n2 = +prompt('Введіть число №2'); let n3 = +prompt('Введіть число №3'); if (n1 > n2 && n1 > n3 && n2 > n3) { alert(`${n3}, ${n2}, ${n1}`); } // 2. // Все параматры получаем с клавиатуры!!!! // Имитируем поведение пешехода на перекстке. // Если светофор зеленый - вывести "иди". // Если светофор желтый - вывести "подожди". // Если светофор красный - вывести "стой". // Если светофор в аварийном режиме вывести "делай что хочешь"! let color = prompt('введіть колір'); if (color === 'green') { alert('йди'); } else if (color === 'yellow') { alert('почекай'); } else if (color === 'red') { alert('стій'); } else { alert('роби що хочеш') } // 3 // Все параметры получаем с клавиатуры!!!!(prompt , confirm) // Создать переменную isRoadClear которая характеризирует наличие на дороге машин. // Улучшаем предыдущее задание. // Если светофор зеленый и машин нет - вывести "иди". // Если светофор зеленый и машины есть - вывести подожди пока нарушители проедут". // Если светофор желтый и машины есть - вывести "жди". // Если светофор желтый и машин нет - вывести "все рано жди". // Если светофор красный и машин нет- вывести "стой все рано". // Если светофор красный - и машины есть вывести "стой и жди". // Если светофор в аварийном режиме вывести "делай что хочешь"! let color1 = prompt('введіть колір'); let isRoadClear = confirm('дорога чиста?'); if (color1 === 'green') { if (isRoadClear) { alert('йди'); } else { alert('почекай, поки проїдуть, потім йди'); } } else if (color1 === 'yellow') { if (isRoadClear) { alert('почекай'); } else { alert('всеодно почекай'); } } else if (color1 === 'red') { if (isRoadClear) { alert('стій всеодно'); } else { alert('стій і чекай'); } } else { alert('роби що хочеш') }
Java
UTF-8
302
1.820313
2
[]
no_license
package com.test.application.designPatten.behavioralPattern.commandPattern; import com.test.application.designPatten.behavioralPattern.commandPattern.editor.Editor; public class Demo { public static void main(String[] args) { Editor editor = new Editor(); editor.init(); } }
Python
UTF-8
1,773
2.671875
3
[ "MIT" ]
permissive
""" Noise wrapper. Created on Thu Feb 28 15:07:21 2019 @author: molano """ # !/usr/bin/env python3 # -*- coding: utf-8 -*- import gym class ReactionTime(gym.Wrapper): # TODO: Make this a trial wrapper instead? """Allow reaction time response. Modifies a given environment by allowing the network to act at any time after the fixation period. """ metadata = { 'description': 'Modifies a given environment by allowing the network' + ' to act at any time after the fixation period.', 'paper_link': None, 'paper_name': None, } def __init__(self, env, urgency=0.0): super().__init__(env) self.env = env self.urgency = urgency self.tr_dur = 0 def reset(self, step_fn=None): if step_fn is None: step_fn = self.step return self.env.reset(step_fn=step_fn) def step(self, action): dec = 'decision' stim = 'stimulus' assert stim in self.env.start_t.keys(),\ 'Reaction time wrapper requires a stimulus period' assert dec in self.env.start_t.keys(),\ 'Reaction time wrapper requires a decision period' if self.env.t_ind == 0: # set start of decision period self.env.start_t[dec] = self.env.start_t[stim]+self.env.dt # change ground truth accordingly self.env.gt[self.start_ind[stim]+1: self.env.end_ind[stim]] =\ self.env.gt[self.start_ind[dec]] obs, reward, done, info = self.env.step(action) if info['new_trial']: info['tr_dur'] = self.tr_dur obs *= 0 else: self.tr_dur = self.env.t_ind reward += self.urgency return obs, reward, done, info
Python
UTF-8
2,000
3.65625
4
[]
no_license
import math DEFAULT_RADIUS = 4 DEFAULT_LIFE = 200 DEFAULT_SP_LIFE = 150 HALF_TURN = 45 class Torpedo: """ the class representing the torpedoes in the game asteroids, they each have speed and location on x and on the y axis and direction. """ def __init__(self, x_location=0, x_speed=0, y_location=0, y_speed=0, direction=0, special=False): self.__x_location = x_location self.__x_speed = x_speed self.__y_location = y_location self.__y_speed = y_speed self.__direction = direction self.__radius = DEFAULT_RADIUS self.__special = special if special: self.__torpedo_life = DEFAULT_SP_LIFE else: self.__torpedo_life = DEFAULT_LIFE def hurt_torpedo(self): """ decrease torpedo life by one. :return: if it is dead (0 life) return False else return True. """ if self.__torpedo_life <= 0: return False self.__torpedo_life -= 1 return True # Getters def get_x_location(self): return self.__x_location def get_y_location(self): return self.__y_location def get_x_speed(self): return self.__x_speed def get_y_speed(self): return self.__y_speed def get_direction(self): return self.__direction def get_radius(self): return self.__radius def get_life(self): return self.__torpedo_life def get_special(self): return self.__special # Setters def set_x_location(self, new_x): self.__x_location = new_x def set_y_location(self, new_y): self.__y_location = new_y def set_x_speed(self, new_speed): self.__x_speed = new_speed def set_y_speed(self, new_speed): self.__y_speed = new_speed def set_direction(self, new_direction): self.__direction = new_direction def set_life(self, new_life): self.__torpedo_life = new_life
Swift
UTF-8
560
2.609375
3
[]
no_license
/// MARK: - UIImage+DAView extension UIImage { /// MARK: - class method /** * create UIImage from UIView * @param view UIView * @return UIImage **/ class func imageFromView(view: UIView) -> UIImage { let scale = UIScreen.mainScreen().scale UIGraphicsBeginImageContextWithOptions(view.frame.size, false, scale) view.layer.renderInContext(UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext(); return image } }
JavaScript
UTF-8
3,843
2.78125
3
[ "MIT" ]
permissive
import { get, INTERCEPT_GET } from 'ember-metal/property_get'; import { set, INTERCEPT_SET, UNHANDLED_SET } from 'ember-metal/property_set'; QUnit.module('set'); QUnit.test('should set arbitrary properties on an object', function() { var obj = { string: 'string', number: 23, boolTrue: true, boolFalse: false, nullValue: null, undefinedValue: undefined }; var newObj = { undefinedValue: 'emberjs' }; for (var key in obj) { if (!obj.hasOwnProperty(key)) { continue; } equal(set(newObj, key, obj[key]), obj[key], 'should return value'); equal(get(newObj, key), obj[key], 'should set value'); } }); QUnit.test('should call INTERCEPT_SET and support UNHANDLED_SET if INTERCEPT_SET is defined', function() { var obj = { string: 'string', number: 23, boolTrue: true, boolFalse: false, nullValue: null, undefinedValue: undefined }; var newObj = { undefinedValue: 'emberjs' }; let calledWith; newObj[INTERCEPT_SET] = function(obj, key, value) { calledWith = [key, value]; return UNHANDLED_SET; }; for (var key in obj) { if (!obj.hasOwnProperty(key)) { continue; } calledWith = undefined; equal(set(newObj, key, obj[key]), obj[key], 'should return value'); equal(calledWith[0], key, 'INTERCEPT_SET called with the key'); equal(calledWith[1], obj[key], 'INTERCEPT_SET called with the key'); equal(get(newObj, key), obj[key], 'should set value since UNHANDLED_SET was returned'); } }); QUnit.test('should call INTERCEPT_SET and support handling the set if it is defined', function() { var obj = { string: 'string', number: 23, boolTrue: true, boolFalse: false, nullValue: null, undefinedValue: undefined }; var newObj = { bucket: {} }; let calledWith; newObj[INTERCEPT_SET] = function(obj, key, value) { set(obj.bucket, key, value); return value; }; for (var key in obj) { if (!obj.hasOwnProperty(key)) { continue; } calledWith = undefined; equal(set(newObj, key, obj[key]), obj[key], 'should return value'); equal(get(newObj.bucket, key), obj[key], 'should have moved the value to `bucket`'); ok(newObj.bucket.hasOwnProperty(key), 'the key is defined in bucket'); ok(!newObj.hasOwnProperty(key), 'the key is not defined on the raw object'); } }); QUnit.test('should call INTERCEPT_GET and INTERCEPT_SET', function() { var obj = { string: 'string', number: 23, boolTrue: true, boolFalse: false, nullValue: null, undefinedValue: undefined }; var newObj = { string: null, number: null, boolTrue: null, boolFalse: null, nullValue: null, undefinedValue: null, bucket: {} }; newObj[INTERCEPT_SET] = function(obj, key, value) { set(obj.bucket, key, value); return value; }; newObj[INTERCEPT_GET] = function(obj, key) { return get(obj.bucket, key); }; for (var key in obj) { if (!obj.hasOwnProperty(key)) { continue; } equal(set(newObj, key, obj[key]), obj[key], 'should return value'); equal(get(newObj.bucket, key), obj[key], 'should have moved the value to `bucket`'); equal(get(newObj, key), obj[key], 'INTERCEPT_GET was called'); } }); QUnit.test('should call setUnknownProperty if defined and value is undefined', function() { var obj = { count: 0, unknownProperty(key, value) { ok(false, 'should not invoke unknownProperty if setUnknownProperty is defined'); }, setUnknownProperty(key, value) { equal(key, 'foo', 'should pass key'); equal(value, 'BAR', 'should pass key'); this.count++; return 'FOO'; } }; equal(set(obj, 'foo', 'BAR'), 'BAR', 'should return set value'); equal(obj.count, 1, 'should have invoked'); });
Python
UTF-8
281
3.28125
3
[]
no_license
# def reverse(text): # return text[::-1] # def reverse(text): # reversed_string = [] # for i in range(len(text) -1, -1, -1): # reversed_string += text[i] # return ''.join(reversed_string) def reverse(text): return ''.join([i for i in reversed(text)])
C#
UTF-8
1,170
2.84375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using NUnit.Framework.Internal; using TestNinja.Fundamentals; namespace TestNinja.UnitTests { [TestFixture] public class DemeritPointsCalculatorTests { private DemeritPointsCalculator _calculator; [SetUp] public void SetUp() { _calculator = new DemeritPointsCalculator(); } [Test] [TestCase(0, 0)] [TestCase(60, 0)] [TestCase(69, 0)] [TestCase(75, 2)] public void CalculateDemeritPoints_WhenCalled_ShouldReturnCorrectValue(int speed, int expectedResult) { var result = _calculator.CalculateDemeritPoints(speed); Assert.That(result, Is.EqualTo(expectedResult)); } [Test] [TestCase(-1)] [TestCase(350)] public void CalculateDemeritPoints_WithBadArguments_ShouldReturnException(int speed) { Assert.That(() => _calculator.CalculateDemeritPoints(speed), Throws.TypeOf<ArgumentOutOfRangeException>()); } } }
C++
UTF-8
2,260
2.53125
3
[]
no_license
//============================================================================= #ifndef TRIANGLE_BSP_H #define TRIANGLE_BSP_H //== INCLUDES ================================================================= #include <graphene/surface_mesh/data_structure/Surface_mesh.h> #include <graphene/geometry/Plane.h> #include <vector> //== NAMESPACES =============================================================== namespace graphene { namespace surface_mesh { /// \addtogroup surface_mesh /// @{ //== CLASS DEFINITION ========================================================= /// Triangle BSP class Triangle_BSP { public: /// construct with mesh Triangle_BSP(Surface_mesh& mesh); /// destructur ~Triangle_BSP() { delete root_; } /// construct BSP, returns depth of the tree unsigned int build(unsigned int max_faces=10, unsigned int max_depth=100); /// nearest neighbor information struct Nearest_neighbor { Scalar dist; Surface_mesh::Face face; Point nearest; int tests; }; /// Return handle of the nearest neighbor Nearest_neighbor nearest(const Point& p) const; private: typedef graphene::geometry::Plane Plane; // Node of the tree: contains parent, children and splitting plane struct Node { Node(Node* _parent); ~Node(); Node *parent_, *left_child_, *right_child_; std::vector<Surface_mesh::Face> faces_; Plane plane_; }; private: // Recursive part of build() unsigned int _build(Node* node, unsigned int max_handles, unsigned int depth); // Recursive part of nearest() void _nearest(Node* node, const Point& point, Nearest_neighbor& data) const; private: Surface_mesh& mesh_; Node* root_; Surface_mesh::Vertex_property<Point> points_; }; /// @} //============================================================================= } // namespace surface_mesh } // namespace graphene //============================================================================= #endif //=============================================================================
Markdown
UTF-8
657
2.609375
3
[]
no_license
Starting an "etch a sketch" project where each grid space can be changed into a different color. Fun side project, most difficult part by far is the where I had to try to make the grid size stay the same, while there are more or less squares. Meaning the sizes of the squares had to scale with how many there are, relative to the grid size. Really nice to see it in this state. 9/20 edit -Fixed part where the color wheel would not update the initial color when changing on the color picker. 2/21/21 -Pushed update where grid would reset whenever the user chooses a new color You may view the project below: https://albertoe22.github.io/Etch-a-Sketch/
Java
UTF-8
2,798
2.28125
2
[]
no_license
package com.example.barbara.skytonight.presentation.core; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.barbara.skytonight.R; import com.example.barbara.skytonight.entity.NewsHeadline; import com.example.barbara.skytonight.presentation.core.NewsFragment.OnListFragmentInteractionListener; import java.text.SimpleDateFormat; import java.util.List; import java.util.Locale; public class NewsRecyclerViewAdapter extends RecyclerView.Adapter<NewsRecyclerViewAdapter.ViewHolder> { private final List<NewsHeadline> mValues; private final OnListFragmentInteractionListener mListener; private Context context; public NewsRecyclerViewAdapter(List<NewsHeadline> items, OnListFragmentInteractionListener listener) { mValues = items; mListener = listener; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { context = parent.getContext(); View view = LayoutInflater.from(context).inflate(R.layout.fragment_news_list_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull final ViewHolder holder, int position) { final NewsHeadline newsObject = mValues.get(position); holder.mItem = newsObject; holder.mTitleView.setText(newsObject.getTitle()); final SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy HH:mm", Locale.getDefault()); holder.mDateView.setText(sdf.format(newsObject.getPubDate().getTime())); holder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(newsObject.getUrl())); context.startActivity(intent); } }); } @Override public int getItemCount() { return mValues.size(); } public class ViewHolder extends RecyclerView.ViewHolder { final View mView; final TextView mTitleView; final TextView mDateView; public NewsHeadline mItem; public ViewHolder(View view) { super(view); mView = view; mTitleView = view.findViewById(R.id.newsTitleTextView); mDateView = view.findViewById(R.id.newsPubDateTextView); } @Override public String toString() { return super.toString() + " '" + mDateView.getText() + "'"; } } }
C#
UTF-8
27,073
2.53125
3
[ "CC-BY-3.0-US", "MIT", "CC-BY-3.0" ]
permissive
//--------------------------------------------------------------------- // <copyright file="CombinatorialStrategy.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; namespace Microsoft.SqlServer.Test.TestShell.Core.InputSpaceModeling { /// <summary> /// Attempted to set exploration strategy for a dimension that is not in the target matrix. /// </summary> [Serializable] public class DimensionNotInMatrixException : Exception { /// <summary> /// Initializes a new instance of the <see cref="DimensionNotInMatrixException"/> class. /// </summary> public DimensionNotInMatrixException() { } /// <summary> /// Initializes a new instance of the <see cref="DimensionNotInMatrixException"/> class. /// </summary> /// <param name="message">The message.</param> public DimensionNotInMatrixException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="DimensionNotInMatrixException"/> class. /// </summary> /// <param name="missingDimension">The missing dimension.</param> public DimensionNotInMatrixException(Dimension missingDimension) : base(string.Format(CultureInfo.InvariantCulture, "Dimension: {0} is not in the test matrix", missingDimension)) { } /// <summary> /// Initializes a new instance of the <see cref="DimensionNotInMatrixException"/> class. /// </summary> /// <param name="message">The message.</param> /// <param name="inner">The inner.</param> public DimensionNotInMatrixException(string message, Exception inner) : base(message, inner) { } /// <summary> /// Initializes a new instance of the <see cref="DimensionNotInMatrixException"/> class. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0). </exception> protected DimensionNotInMatrixException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } /// <summary> /// Attempted to explore a combinatorial strategy without setting exploration strategies for all the dimensions. /// </summary> [Serializable] public class DimensionStrategyNotSetException : Exception { /// <summary> /// Initializes a new instance of the <see cref="DimensionStrategyNotSetException"/> class. /// </summary> public DimensionStrategyNotSetException() { } /// <summary> /// Initializes a new instance of the <see cref="DimensionStrategyNotSetException"/> class. /// </summary> /// <param name="message">The message.</param> public DimensionStrategyNotSetException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="DimensionStrategyNotSetException"/> class. /// </summary> /// <param name="missingDimension">The missing dimension.</param> public DimensionStrategyNotSetException(Dimension missingDimension) : base(string.Format(CultureInfo.InvariantCulture, "Dimension: {0} doesn't have a corresponding exploration strategy", missingDimension)) { } /// <summary> /// Initializes a new instance of the <see cref="DimensionStrategyNotSetException"/> class. /// </summary> /// <param name="message">The message.</param> /// <param name="inner">The inner.</param> public DimensionStrategyNotSetException(string message, Exception inner) : base(message, inner) { } /// <summary> /// Initializes a new instance of the <see cref="DimensionStrategyNotSetException"/> class. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0). </exception> protected DimensionStrategyNotSetException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } /// <summary> /// An exploration strategy over a test matrix that independently chooses values from each dimension, /// then proceeds to choose a set of combinations of these values. /// </summary> public abstract class CombinatorialStrategy : ExplorationStrategy<Vector> { private Matrix _targetMatrix; private List<IConstraint> _constraints; private Dictionary<QualifiedDimension, IExplorationStrategy> _explorationStrategies = new Dictionary<QualifiedDimension, IExplorationStrategy>(); /// <summary> /// Initializes a new instance of the <see cref="CombinatorialStrategy"/> class. /// </summary> /// <param name="targetMatrix">The target matrix.</param> /// <param name="constraints">The constraints.</param> /// <exception cref="ArgumentNullException">Any of the parameters is null.</exception> protected CombinatorialStrategy(Matrix targetMatrix, IEnumerable<IConstraint> constraints) { if (targetMatrix == null) throw new ArgumentNullException("targetMatrix"); if (constraints == null) throw new ArgumentNullException("constraints"); _targetMatrix = targetMatrix; _constraints = new List<IConstraint>(constraints); foreach (IConstraint c in _constraints) { if (c == null) throw new ArgumentNullException("constraints", "One of the constraints is null"); } SetDefaultStrategies(Enumerable.Empty<Matrix>(), _targetMatrix); } private void SetDefaultStrategies(IEnumerable<Matrix> path, Matrix targetMatrix) { foreach (Dimension dim in targetMatrix.Dimensions) { Matrix asMatrix; Type underlyingType = Nullable.GetUnderlyingType(dim.Domain) ?? dim.Domain; if (underlyingType.IsEnum()) { _explorationStrategies.Add(QualifiedDimension.Create(dim, path), (IExplorationStrategy)typeof(ExhaustiveEnumStrategy<>).MakeGenericType(dim.Domain).GetInstanceConstructor(true, new Type[0]).Invoke(null)); } else if (typeof(bool).Equals(dim.Domain)) { _explorationStrategies.Add(QualifiedDimension.Create(dim, path), new ExhaustiveIEnumerableStrategy<bool>(true, false)); } else if (typeof(bool?).Equals(dim.Domain)) { _explorationStrategies.Add(QualifiedDimension.Create(dim, path), new ExhaustiveIEnumerableStrategy<bool?>(true, false, null)); } else if ((asMatrix = dim as Matrix) != null) { SetDefaultStrategies(path.Concat(Enumerable.Repeat(asMatrix, 1)), asMatrix); } } } /// <summary> /// Initializes a new instance of the <see cref="CombinatorialStrategy"/> class as a copy of the given strategy. /// </summary> /// <param name="sourceStrategy">The source strategy.</param> /// <exception cref="ArgumentNullException"><paramref name="sourceStrategy"/> is null.</exception> protected CombinatorialStrategy(CombinatorialStrategy sourceStrategy) { if (sourceStrategy == null) throw new ArgumentNullException("sourceStrategy"); _targetMatrix = sourceStrategy._targetMatrix; _constraints = new List<IConstraint>(sourceStrategy._constraints); ImportDimensionStrategies(sourceStrategy); } /// <summary> /// Gets the target matrix. /// </summary> /// <value>The target matrix.</value> public Matrix TargetMatrix { get { return _targetMatrix; } } /// <summary> /// The constraints that should be respected when exploring the matrix. /// </summary> /// <value>The constraints.</value> public Collection<IConstraint> Constraints { get { return new Collection<IConstraint>(_constraints); } } /// <summary> /// Sets the exploration strategy for the given dimension. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dimension">The dimension.</param> /// <param name="strategy">The strategy. Can be null which will clear out the strategy for <paramref name="dimension"/>.</param> /// <remarks> /// Strategies should be set for all the dimensions in the test matrix; /// except for enum and bool dimensions, which are exhaustive by default. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="dimension"/> is null.</exception> /// <exception cref="DimensionNotInMatrixException"><paramref name="dimension"/> is not in the target matrix.</exception> public void SetDimensionStrategy<T>(Dimension<T> dimension, ExplorationStrategy<T> strategy) { if (dimension == null) throw new ArgumentNullException("dimension"); if (!_targetMatrix.Dimensions.Contains(dimension)) throw new DimensionNotInMatrixException(dimension); SetDimensionStrategy((QualifiedDimension<T>)dimension, strategy); } /// <summary> /// Sets the exploration strategy for the given dimension. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dimension">The dimension.</param> /// <param name="strategy">The strategy. Can be null which will clear out the strategy for <paramref name="dimension"/>.</param> /// <remarks> /// Strategies should be set for all the dimensions in the test matrix; /// except for enum and bool dimensions, which are exhaustive by default. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="dimension"/> is null.</exception> /// <exception cref="DimensionNotInMatrixException"><paramref name="dimension"/> is not in the target matrix.</exception> [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "I use the generic version for type safety")] public void SetDimensionStrategy<T>(QualifiedDimension<T> dimension, ExplorationStrategy<T> strategy) { if (dimension == null) throw new ArgumentNullException("dimension"); SetDimensionStrategyBase(dimension, strategy); } /// <summary> /// Sets the exploration strategy for the given dimension. /// </summary> /// <param name="dimension">The dimension.</param> /// <param name="strategy">The strategy. Can be null which will clear out the strategy for <paramref name="dimension"/>.</param> /// <remarks> /// Strategies should be set for all the dimensions in the test matrix; /// except for enum and bool dimensions, which are exhaustive by default. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="dimension"/> is null.</exception> /// <exception cref="DimensionNotInMatrixException"><paramref name="dimension"/> is not in the target matrix.</exception> public void SetDimensionStrategy(Dimension dimension, IExplorationStrategy strategy) { if (dimension == null) throw new ArgumentNullException("dimension"); if (!_targetMatrix.Dimensions.Contains(dimension)) throw new DimensionNotInMatrixException(dimension); SetDimensionStrategyBase((QualifiedDimension)dimension, strategy); } private void SetDimensionStrategyBase(QualifiedDimension dimension, IExplorationStrategy strategy) { Matrix currentMatrix = _targetMatrix; List<Matrix> innerPath = new List<Matrix>(); foreach (Matrix innerMatrix in dimension.Path) { if (!currentMatrix.Dimensions.Contains(innerMatrix)) { throw new DimensionNotInMatrixException(innerMatrix); } if (strategy != null) { _explorationStrategies.Remove(QualifiedDimension.Create(innerMatrix, innerPath)); } currentMatrix = innerMatrix; innerPath.Add(innerMatrix); } if (strategy == null) _explorationStrategies.Remove(dimension); else if (_explorationStrategies.ContainsKey(dimension)) _explorationStrategies[dimension] = strategy; else _explorationStrategies.Add(dimension, strategy); } /// <summary> /// Sets the exploration strategy for the given dimension to a categorical strategy with the given categories defined. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dimension"></param> /// <param name="allCategories"></param> /// <exception cref="ArgumentNullException">Any of the parameters is null.</exception> /// <exception cref="DimensionNotInMatrixException"><paramref name="dimension"/> is not in the target matrix.</exception> /// <example><code><![CDATA[ /// _fullStrategy.PartitionDimension(_dataTypeDimension, /// new PointCategory<PimodType>("String", PimodType.VarChar(20), PimodType.NVarChar(10), PimodType.Char(5), PimodType.NChar(50)), /// new PointCategory<PimodType>("Integer", PimodType.TinyInt(), PimodType.SmallInt(), PimodType.Int(), PimodType.BigInt())); ///_fullStrategy.PartitionDimension(_tableSizeDimension, /// new PointCategory<int>("OneRow", 1), /// new IntegerRangeCategory("Small", 10, 20), /// new IntegerRangeCategory("Large", 10000, 15000)); /// ]]></code></example> public void PartitionDimension<T>(Dimension<T> dimension, params Category<T>[] allCategories) { SetDimensionStrategy(dimension, new CategoricalStrategy<T>(allCategories)); } /// <summary> /// Sets the exploration strategy for the given dimension to a categorical strategy with the given categories defined. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dimension"></param> /// <param name="allCategories"></param> /// <exception cref="ArgumentNullException">Any of the parameters is null.</exception> /// <exception cref="DimensionNotInMatrixException"><paramref name="dimension"/> is not in the target matrix.</exception> /// <example><code><![CDATA[ /// _fullStrategy.PartitionDimension(_dataTypeDimension, /// new PointCategory<PimodType>("String", PimodType.VarChar(20), PimodType.NVarChar(10), PimodType.Char(5), PimodType.NChar(50)), /// new PointCategory<PimodType>("Integer", PimodType.TinyInt(), PimodType.SmallInt(), PimodType.Int(), PimodType.BigInt())); ///_fullStrategy.PartitionDimension(_tableSizeDimension, /// new PointCategory<int>("OneRow", 1), /// new IntegerRangeCategory("Small", 10, 20), /// new IntegerRangeCategory("Large", 10000, 15000)); /// ]]></code></example> public void PartitionDimension<T>(QualifiedDimension<T> dimension, params Category<T>[] allCategories) { SetDimensionStrategy(dimension, new CategoricalStrategy<T>(allCategories)); } /// <summary> /// Gets the current exploration strategy for the given dimension. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dimension">The dimension.</param> /// <returns> /// The strategy set for the dimension, or null if none found. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="dimension"/> is null.</exception> [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "I use the generic version for type safety")] public ExplorationStrategy<T> GetDimensionStrategy<T>(QualifiedDimension<T> dimension) { return (ExplorationStrategy<T>)(GetBaseDimensionStrategy(dimension)); } /// <summary> /// Gets the current exploration strategy for the given dimension. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dimension">The dimension.</param> /// <returns> /// The strategy set for the dimension, or null if none found. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="dimension"/> is null.</exception> [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "I use the generic version for type safety")] public ExplorationStrategy<T> GetDimensionStrategy<T>(Dimension<T> dimension) { return (ExplorationStrategy<T>)(GetBaseDimensionStrategy(dimension)); } /// <summary> /// (Internal usage) Gets the current exploration strategy for the given dimension. /// </summary> /// <param name="dimension">The dimension.</param> /// <returns> /// The strategy set for the dimension, or null if none found. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="dimension"/> is null.</exception> public IExplorationStrategy GetBaseDimensionStrategy(Dimension dimension) { if (dimension == null) throw new ArgumentNullException("dimension"); return GetBaseDimensionStrategy(QualifiedDimension.Create(dimension)); } /// <summary> /// (Internal usage) Gets the current exploration strategy for the given dimension. /// </summary> /// <param name="dimension">The dimension.</param> /// <returns> /// The strategy set for the dimension, or null if none found. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="dimension"/> is null.</exception> public IExplorationStrategy GetBaseDimensionStrategy(QualifiedDimension dimension) { if (dimension == null) throw new ArgumentNullException("dimension"); IExplorationStrategy ret; if (_explorationStrategies.TryGetValue(dimension, out ret)) return ret; else return null; } /// <summary> /// Imports the dimension exploration strategies from any common dimensions found with the given source combinatorial strategy. /// </summary> /// <remarks> /// If sourceStrategy has a test matrix with dimensions {A,B,C,D}, and it has known strategies for dimensions {A,B,C}, /// and this strategy has dimensions {B,C,D,E}, then this method will import the strategies for dimensions {B,C}. /// </remarks> /// <param name="sourceStrategy"></param> /// <returns>The number of strategies imported.</returns> /// <exception cref="ArgumentNullException"><paramref name="sourceStrategy"/> is null.</exception> public int ImportDimensionStrategies(CombinatorialStrategy sourceStrategy) { if (sourceStrategy == null) throw new ArgumentNullException("sourceStrategy"); int ret = 0; foreach (KeyValuePair<QualifiedDimension, IExplorationStrategy> dimStrategy in sourceStrategy._explorationStrategies) { if (_explorationStrategies.ContainsKey(dimStrategy.Key)) { _explorationStrategies[dimStrategy.Key] = dimStrategy.Value; ret++; } else if (_targetMatrix.Dimensions.Contains(dimStrategy.Key.FullPath.First())) { _explorationStrategies.Add(dimStrategy.Key, dimStrategy.Value); ret++; } } return ret; } /// <summary> /// Imports the dimension exploration strategies for the given innner matrix found with the given source combinatorial strategy. /// </summary> /// <param name="innerMatrix">The inner matrix.</param> /// <param name="sourceStrategy">The source strategy.</param> /// <remarks> /// This is useful for exploring dimensions from a sub-matrix in the same strategy, which is useful e.g. for doing pairwise coverage /// across sub-matrix boundaries. /// </remarks> /// <returns>The number of strategies imported.</returns> /// <exception cref="ArgumentNullException">Any of the parameters is null.</exception> public int ImportSubMatrixStrategies(Matrix innerMatrix, CombinatorialStrategy sourceStrategy) { if (innerMatrix == null) { throw new ArgumentNullException("innerMatrix"); } return ImportSubMatrixStrategies(new Matrix[] { innerMatrix }, sourceStrategy); } /// <summary> /// Imports the dimension exploration strategies for the given innner matrix found with the given source combinatorial strategy. /// </summary> /// <param name="innerMatrixPath">The inner matrix path.</param> /// <param name="sourceStrategy">The source strategy.</param> /// <remarks> /// This is useful for exploring dimensions from a sub-matrix in the same strategy, which is useful e.g. for doing pairwise coverage /// across sub-matrix boundaries. /// </remarks> /// <returns>The number of strategies imported.</returns> /// <exception cref="ArgumentNullException"><paramref name="sourceStrategy"/> is null.</exception> public int ImportSubMatrixStrategies(IEnumerable<Matrix> innerMatrixPath, CombinatorialStrategy sourceStrategy) { if (sourceStrategy == null) { throw new ArgumentNullException("sourceStrategy"); } if (innerMatrixPath == null || innerMatrixPath.Any(m => m == null)) { throw new ArgumentNullException("innerMatrixPath"); } int ret = 0; foreach (KeyValuePair<QualifiedDimension, IExplorationStrategy> dimStrategy in sourceStrategy._explorationStrategies) { SetDimensionStrategyBase(QualifiedDimension.Create(dimStrategy.Key.BaseDimension, innerMatrixPath.Concat(dimStrategy.Key.Path)), dimStrategy.Value); ret++; } _constraints.AddRange(sourceStrategy._constraints.Select<IConstraint, IConstraint>(c => new InnerSubMatrixWrapperConstraint(c, innerMatrixPath))); return ret; } /// <summary> /// Checks that all dimensions have exploration strategies. /// </summary> /// <exception cref="DimensionStrategyNotSetException">Any dimension found with no corresponding strategy.</exception> protected void CheckAllDimensionsHaveExplorationStrategies() { CheckAllDimensionsHaveExplorationStrategies(Enumerable.Empty<Matrix>(), _targetMatrix); } /// <summary> /// Checks that all dimensions have exploration strategies. /// </summary> /// <param name="path">The path.</param> /// <param name="targetMatrix">The target matrix.</param> /// <exception cref="DimensionStrategyNotSetException">Any dimension found with no corresponding strategy.</exception> private void CheckAllDimensionsHaveExplorationStrategies(IEnumerable<Matrix> path, Matrix targetMatrix) { foreach (Dimension dimension in targetMatrix.Dimensions) { if (!_explorationStrategies.ContainsKey(QualifiedDimension.Create(dimension, path))) { Matrix asMatrix; if ((asMatrix = dimension as Matrix) != null) { CheckAllDimensionsHaveExplorationStrategies(path.Concat(Enumerable.Repeat(asMatrix, 1)), asMatrix); } else { throw new DimensionStrategyNotSetException(dimension); } } } } private IEnumerable<ValueFactoryWithOptionalConcreteValue> GetValues(IExplorationStrategy strategy) { foreach (IValueFactory value in strategy.BaseExplore()) yield return new ValueFactoryWithOptionalConcreteValue(value); } /// <summary> /// Gets all individual dimension values. /// </summary> /// <returns></returns> /// <exception cref="DimensionStrategyNotSetException">Any dimension found with no corresponding strategy.</exception> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Every invocation could yield different results.")] protected ReadOnlyCollection<DimensionWithValues> GetAllDimensionValues() { return GetAllDimensionValues(Enumerable.Empty<Matrix>(), _targetMatrix); } /// <summary> /// Gets all individual dimension values. /// </summary> /// <param name="path">The path.</param> /// <param name="targetMatrix">The target matrix.</param> /// <returns></returns> /// <exception cref="DimensionStrategyNotSetException">Any dimension found with no corresponding strategy.</exception> private ReadOnlyCollection<DimensionWithValues> GetAllDimensionValues(IEnumerable<Matrix> path, Matrix targetMatrix) { CheckAllDimensionsHaveExplorationStrategies(); List<DimensionWithValues> ret = new List<DimensionWithValues>(targetMatrix.Dimensions.Count); foreach (Dimension dimension in targetMatrix.Dimensions) { QualifiedDimension QualifiedDimension = QualifiedDimension.Create(dimension, path); if (_explorationStrategies.ContainsKey(QualifiedDimension)) { ret.Add(new DimensionWithValues(QualifiedDimension, GetValues(GetBaseDimensionStrategy(QualifiedDimension)))); } else { Matrix asMatrix = (Matrix)dimension; ret.AddRange(GetAllDimensionValues(path.Concat(Enumerable.Repeat(asMatrix, 1)), asMatrix)); } } return ret.AsReadOnly(); } private class InnerSubMatrixWrapperConstraint : IConstraint { private readonly IConstraint _innerConstraint; private readonly ReadOnlyCollection<Matrix> _path; public InnerSubMatrixWrapperConstraint(IConstraint innerConstraint, IEnumerable<Matrix> path) { _path = new List<Matrix>(path).AsReadOnly(); _innerConstraint = innerConstraint; } #region IConstraint Members public bool IsValid(Vector target) { Vector innerVector = target.GetValue(QualifiedDimension.Create(_path.Last(), _path.Take(_path.Count - 1))); return _innerConstraint.IsValid(innerVector); } public ReadOnlyCollection<QualifiedDimension> RequiredDimensions { get { return new List<QualifiedDimension>(_innerConstraint.RequiredDimensions .Select(d => QualifiedDimension.Create(d.BaseDimension, _path.Concat(d.Path))) ).AsReadOnly(); } } #endregion } /// <summary> /// Determines whether the specified target is valid according to the constraints. /// </summary> /// <param name="target">The target.</param> /// <returns> /// <c>true</c> if the specified target is valid; otherwise, <c>false</c>. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="target"/> is null.</exception> protected bool IsValidVector(Vector target) { if (target == null) { throw new ArgumentNullException("target"); } return _constraints.All(c => c.IsValid(target)); } } }
Java
UTF-8
781
2.484375
2
[]
no_license
package util; import com.alibaba.fastjson.JSON; import entry.test.User; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.util.ArrayList; import java.util.List; public class UtillTool { public static void main(String[] asd){ List<User> users = new ArrayList<>(); users.add(new User("yu",10)); users.add(new User("shuai",11)); users.add(new User("shi",12)); System.out.println(JSON.toJSONString(users)); } /** * 获取当前进程ID */ private static String getCurrentThreadID() { RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); String name = runtime.getName(); return name.substring(0, name.indexOf("@")); } }
Java
UTF-8
7,881
2.03125
2
[]
no_license
package com.blowthem.app; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.ActivityInfo; import android.graphics.Point; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.view.Display; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.ArrayList; /** * Created by walter on 24.08.14. */ public class RegistrationActivity extends Activity { private EditText nameField, passwordField, mailField; private TextView nicknameText, passwordText, mailText; private ImageView activitiesMainLabel; private Intent mainActivityIntent, serviceIntent; private Button registrationButton; private Handler clientHandler = new Handler(); private Runnable clientRunnable = new Runnable() { @Override public void run() { startService(serviceIntent); } }; private String key; //private UpdateReceiver updateReceiver = new UpdateReceiver(); private boolean mIsBound= false; //private UpdateReceiver updateReceiver = new UpdateReceiver(); private MusicService musicService; private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder binder) { musicService = ((MusicService.ServiceBinder) binder).getService(); } @Override public void onServiceDisconnected(ComponentName name) { musicService = null; } }; public void doBindService(){ bindService(new Intent(this, MusicService.class), serviceConnection, Context.BIND_AUTO_CREATE); mIsBound = true; } public void doUnbindService(){ if(mIsBound){ unbindService(serviceConnection); mIsBound = false; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); doBindService(); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); getActionBar().hide(); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); setContentView(R.layout.activity_registration); this.mainActivityIntent = new Intent(this, MainSettingsActivity.class); this.serviceIntent = new Intent(this, SocketService.class); this.nameField = (EditText)findViewById(R.id.nameText); this.passwordField = (EditText)findViewById(R.id.passwordText); this.mailField = (EditText)findViewById(R.id.mailText); this.registrationButton = (Button)findViewById(R.id.registration_button); this.nicknameText = (TextView) findViewById(R.id.nickname_label); this.passwordText = (TextView) findViewById(R.id.password_label); this.mailText = (TextView) findViewById(R.id.mail_label); this.activitiesMainLabel = (ImageView) findViewById(R.id.text_logo); Display currentDisplay = getWindowManager().getDefaultDisplay(); Point size = new Point(); currentDisplay.getSize(size); ViewGroup.LayoutParams params = nameField.getLayoutParams(); params.height = size.y / 10; params.width = size.x / 3; nameField.setLayoutParams(params); params = passwordField.getLayoutParams(); params.height = size.y / 10; params.width = size.x / 3; passwordField.setLayoutParams(params); params = mailField.getLayoutParams(); params.height = size.y / 10; params.width = size.x / 3; mailField.setLayoutParams(params); params = registrationButton.getLayoutParams(); params.height = size.y / 10; params.width = size.x / 3; registrationButton.setLayoutParams(params); params = nicknameText.getLayoutParams(); params.height = size.y / 10; params.width = size.x / 3; nicknameText.setLayoutParams(params); params = passwordText.getLayoutParams(); params.height = size.y / 10; params.width = size.x / 3; passwordText.setLayoutParams(params); params = mailText.getLayoutParams(); params.height = size.y / 10; params.width = size.x / 3; mailText.setLayoutParams(params); RelativeLayout.LayoutParams marginParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); marginParams.setMargins(size.x / 10, size.y / 10, 0, 0); marginParams.height = size.y / 5; marginParams.width = size.x / 2; activitiesMainLabel.setLayoutParams(marginParams); registrationButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clientHandler.removeCallbacks(clientRunnable); ArrayList<String> list = new ArrayList<String>(); list.add("$registration$"); list.add(nameField.getText().toString()); list.add(passwordField.getText().toString()); list.add(mailField.getText().toString()); serviceIntent.putStringArrayListExtra("registration", list); clientHandler.post(clientRunnable); } }); clientHandler.post(startMainActivity); final Button musicButton = (Button) findViewById(R.id.music); params = musicButton.getLayoutParams(); params.width = size.x / 20; params.height = size.x / 20; musicButton.setLayoutParams(params); musicButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(musicButton.getBackground().getConstantState().equals(getResources().getDrawable(R.drawable.music).getConstantState())) { musicButton.setBackgroundResource(R.drawable.none_music); musicService.pauseMusic(); } else if(musicButton.getBackground().getConstantState().equals(getResources().getDrawable(R.drawable.none_music).getConstantState())){ musicButton.setBackgroundResource(R.drawable.music); musicService.resumeMusic(); } } }); new Handler().post(new Runnable() { @Override public void run() { if(musicService.mediaPlayer.isPlaying()){ musicButton.setBackgroundResource(R.drawable.music); } else { musicButton.setBackgroundResource(R.drawable.none_music); } } }); AlphaAnimation alpha = new AlphaAnimation(0.0f, 1.0f); alpha.setDuration(1000); alpha.setFillAfter(true); activitiesMainLabel.setAnimation(alpha); } private Runnable startMainActivity = new Runnable() { @Override public void run() { if(LoginBridge.registration != null && LoginBridge.registration.equals("$registration_success$")){ LoginBridge.registration = null; startActivity(mainActivityIntent); //startMainActivity.interrupt(); } else { clientHandler.post(this); } } }; @Override protected void onDestroy() { super.onDestroy(); doUnbindService(); } }
Java
UTF-8
965
3.546875
4
[]
no_license
/** * Demo that static methods and variables in parent classes can be invoked through child classtypes and object references * * * * @author Alan Cowap * @version 1.0 Initial code * @version 1.1 Demo static call to Parent class method thrgugh a casted child class object reference, thx to Kevin Phair for the suggestion * @dependencies None * */ package com.alancowap.ocja.questions.sample; public class StaticMethods { public static void main(String[] args) { Top.runMe(); Middle.runMe(); Bottom.runMe(); Bottom.num = 6; new Bottom().runMe(); Bottom b = new Bottom(); b.runMe(); b.num = 8; ((Top)b).runMe(); //This will execute runMe() in Top, even if there was another in Bottom } } class Top{ static int num = 10; static void runMe(){System.out.println("Top");} } class Middle extends Top{} class Bottom extends Middle{ static void runMe(){System.out.println("Bottom");} }
Markdown
UTF-8
849
2.984375
3
[]
no_license
--- title: 创建 Github 项目 --- 创建一个新的 Github 项目,本地保存一个本项目的 clone 。学会 push/pull 同步项目。 ### 项目简介 项目名叫 sleep-write ,是一个写文章的平台。 ### 具体 Github 操作 到首页,点 New Repository 按钮,创建一个新的仓库。 ### 本地创建项目 ``` mkdir sleep-write cd sleep-write atom . # 添加一个 README.md git init git add -A git commit -m"first commit" ``` ### 添加目标仓库位置 ``` git remote add origin git@github.com:happypeter/sleep-write.git git push -u origin master ``` 这样 REAME.md 就被推送到 github.com 之上了。 ### 添加项目文件夹 ``` mkdir client mkdir server ``` 项目采用前后端分离的架构,前台 react 代码都放到 client 文件夹,后台 express 代码都放到 server 文件夹。
Java
UTF-8
1,404
1.71875
2
[]
no_license
package com.gamsestop.pages; import java.util.List; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class EletronicsPage { public WebDriver driver; public EletronicsPage(WebDriver driver) { PageFactory.initElements(driver, this); } @FindBy(xpath="//ul[@class='nav navbar-nav level-1']/li/a[@data-name='Electronics']") public WebElement electronicLink; @FindBy(xpath="//div[@class='dropdown-menu block-layout show']//img[contains(@class,'icon expand-arrow')]") public WebElement viewMore; @FindBy(xpath="//div[@class='dropdown-menu block-layout show']//img[contains(@class,'icon expand-arrow')]") public List<WebElement> viewMores; @FindBy(xpath="//div[@class='dropdown-menu block-layout show']//ul/li/a") public List<WebElement> allEletronics; @FindBy(xpath="//h1[contains(text(),'Electronics')]//ancestor::div//following-sibling::div//div[@class='slick-list draggable']//div[@role='tabpanel']//a") public List<WebElement> carousals; @FindBy(xpath="//div[@class='collection-tabs4 content-width']") public WebElement homegrid; @FindBy(xpath="//div[@class='collection-tabs4 content-width']") public List<WebElement> homegrids; @FindBy(xpath="//div[@class='collection-tabs4 content-width']//a") public List<WebElement> listOfGids; }
Java
UTF-8
572
3.359375
3
[]
no_license
package Lab3.visitor; public class DurationVisitor implements Visitor { private int totalDuration = 0; @Override public void visit(Book book) { totalDuration += book.getNumberOfPages() * 5; } public void visit (Video video) { totalDuration += video.getTime() + video.getTime()/30 *5; } public void visit(Audio audio) { totalDuration += audio.getTime() + audio.numberOfSongs * 0.3; } public String toString() { return "The visited elemnts have a total duration of " + totalDuration + " min"; } }
Ruby
UTF-8
1,943
2.796875
3
[ "MIT" ]
permissive
class Seed def self.genres(genres) beer_genres = JSON.parse(genres) beer_genres.each do |genre| BeerGenre.create(genre) end end def self.flavors(flavors) food_flavors = JSON.parse(flavors) food_flavors.each do |flavor| FoodFlavor.create(flavor) end end def self.matches(matches) all_matches = JSON.parse(matches) all_matches.each do |match| Match.create(beer_genre: BeerGenre.find_by_name(match["beer_genre"]), food_flavor: FoodFlavor.find_by_name(match["food_flavor"]), intensity: match["intensity"]) end end def self.beers for i in 1..583 results = get_beer_data(i) beer_info_array = parse_beer_data(results) create_beer_objects(beer_info_array) end end def self.get_beer_data(page_number) HTTParty.get("http://api.brewerydb.com/v2/beers/?key=#{CONFIG['brewerydb']['key']}&p=#{page_number}&status=verified&format=json").to_json end def self.parse_beer_data(data) JSON.parse(data)["data"] end def self.create_beer_objects(beers) beers.each do |beer| beer["status"] == "verified" ? new_beer = Beer.new : next new_beer.name = beer["name"] new_beer.description = beer["description"] new_beer.abv = beer["abv"] new_beer.available = beer["available"]["name"] if beer["available"] new_beer.label_url = beer["labels"]["medium"] if beer["labels"] new_beer.style = beer["style"]["name"] if beer["style"] new_beer = set_beer_category(new_beer, beer["style"]["category"]["name"]) if new_beer.style new_beer.save end end def self.set_beer_category(beer, default_category) style_list = JSON.parse(File.read("#{Rails.root}/db/categories_and_styles.json")) beer.category = default_category style_list.each do |category, styles| beer.category = category if styles.include?(beer.style) end beer end end
Java
UTF-8
925
2.09375
2
[]
no_license
package com.re.paas.internal.clustering.classes; import java.io.Serializable; public class NodeJoinResult implements Serializable { private static final long serialVersionUID = 1L; private boolean isSuccess; private String message; private String nodeId; private String masterNodeId; public boolean isSuccess() { return isSuccess; } public NodeJoinResult setSuccess(boolean isSuccess) { this.isSuccess = isSuccess; return this; } public String getMessage() { return message; } public NodeJoinResult setMessage(String message) { this.message = message; return this; } public String getNodeId() { return nodeId; } public NodeJoinResult setNodeId(String nodeId) { this.nodeId = nodeId; return this; } public String getMasterNodeId() { return masterNodeId; } public NodeJoinResult setMasterNodeId(String masterNodeId) { this.masterNodeId = masterNodeId; return this; } }
Java
UTF-8
685
3.28125
3
[]
no_license
/**/ package collections; import java.util.*; public class MyLinkedList { public static void main(String[] args) { List <Integer> ll = new LinkedList<>(); List <Integer> al = new ArrayList<>(); getTimeDiff(al); getTimeDiff(ll); } static void getTimeDiff(List<Integer> list) { long start = System.currentTimeMillis(); for(int i = 0; i<100000; i++) { list.add(0, i); } long end = System.currentTimeMillis(); System.out.println(list.getClass().getName() //here list is the object of some class so by using getClass() we generated class and by using get name we finally obtained name of that class + " " + (end - start)); } }
Swift
UTF-8
260
2.8125
3
[]
no_license
import Foundation extension URLResponse { func isHttpResponseValid() -> Bool { guard let httpResponse = self as? HTTPURLResponse ,(200...299).contains(httpResponse.statusCode) else { return false } return true } }
Python
UTF-8
200
3.1875
3
[]
no_license
class Gate: def __init__(self, x, y): self.x = x self.y = y def match(self, x, y): if self.x == x and self.y == y: self.text = "* " return True
SQL
UTF-8
922
3.78125
4
[]
no_license
--Views CREATE VIEW [label].[vOptionGroupRepresentative] AS SELECT o.SortOrder, vo.DisplayName OptionName, ma.DisplayName MakeName, mo.DisplayName ModelName, t.YearId, t.TrimName FROM ( SELECT vo.SortOrder, MIN(vo.KbbVehicleId) KbbVehicleId FROM VehicleOption vo JOIN VehicleCategory vc ON vc.KBBVehicleId = vo.KBBVehicleId WHERE vc.CategoryId=36 AND vo.OptionTypeId <> 4 AND vo.OptionTypeId <> 7 GROUP BY vo.SortOrder ) AS o JOIN KBBVehicle v ON v.KBBVehicleId = o.KbbVehicleId JOIN Trim t ON v.TrimId = t.TrimId JOIN Model mo ON t.ModelId = mo.ModelId JOIN Make ma ON mo.MakeId = ma.MakeId OUTER APPLY ( SELECT MIN(vo.DisplayName) DisplayName FROM VehicleOption vo WHERE o.SortOrder = vo.SortOrder AND o.KbbVehicleId = vo.KBBVehicleId GROUP BY vo.SortOrder ) vo
C++
UTF-8
19,648
2.734375
3
[]
no_license
#include <sstream> #include <ctime> #include <Windows.h> #include "Snake.h" #include "Utility.h" #include <conio.h> #include <SDL.h> #include <SDL_image.h> #include <SDL_mixer.h> #include <SDL_ttf.h> #include <string> #define LEFT VK_LEFT #define RIGHT VK_RIGHT #define UP VK_UP #define DOWN VK_DOWN #define ESC VK_ESCAPE #define SCREEN_WIDTH MAX_X #define SCREEN_HEIGHT MAX_Y #define SCREEN_HEIGHTPLUS SCREEN_HEIGHT + FACTOR*4 const int TOTAL_BUTTONS = 3; Snake snake; Apple apple; bool endGame = false; int ranX; int ranY; //Điều kiện xuất hiện của Táo (khác tường, khác rắn) bool conditionApple(int x, int y){ if((x >= (MAX_X/FACTOR)/4 && x <= ((MAX_X/FACTOR) - (MAX_X/FACTOR)/4) && y == (MAX_Y/FACTOR)/4) || (y >= (MAX_Y/FACTOR)/4 && y <= ((MAX_Y/FACTOR)-(MAX_Y/FACTOR)/4) && x == (MAX_X/FACTOR)/2) || x == 0 || x == (MAX_X/FACTOR)-1 || y == 0 || y == (MAX_Y/FACTOR)-1) return true; for(int i = 0; i < snake.getLengthSnake(); i++) if(x == snake.getSnakeX()[i] && y == snake.getSnakeY()[i]) return true; return false; } //chọn random vị trí Táo tiếp theo void randomApple(){ while(1){ srand(time(NULL)); ranX = rand() % (MAX_X/FACTOR-1) + 1; ranY = rand() % (MAX_Y/FACTOR-1) + 1; if(!conditionApple(ranX, ranY)) break; } apple.setAppleX(ranX); apple.setAppleY(ranY); } //Texture wrapper class - Class Load các đối tượng Texture SDL (hình ảnh, font chữ) class LTexture { public: //Initializes variables LTexture(); //Deallocates memory ~LTexture(); //Loads image at specified path bool loadFromFile( std::string path ); //Creates image from font string bool loadFromRenderedText( std::string textureText, SDL_Color textColor ); //Deallocates texture void free(); //Renders texture at given point void render( int x, int y); //Renders picture texture void renderPicture( int x, int y); //Gets image dimensions int getWidth(); int getHeight(); void setWidth(int w); void setHeight(int y); private: //The actual hardware texture SDL_Texture* mTexture; //Image dimensions int mWidth; int mHeight; }; //Starts up SDL and creates window bool init(); //Loads media bool loadMedia(); //Frees media and shuts down SDL void close(); //Loads individual image as texture SDL_Texture* loadTexture( std::string path ); //The window we'll be rendering to SDL_Window* gWindow = NULL; //The window renderer SDL_Renderer* gRenderer = NULL; //Scene textures - các texture lưu hình ảnh LTexture gSnake; LTexture gHeadSnake_right; LTexture gHeadSnake_left; LTexture gHeadSnake_down; LTexture gHeadSnake_up; LTexture gBodySnake_ver; LTexture gBodySnake_hor; LTexture gTailSnake_right; LTexture gTailSnake_left; LTexture gTailSnake_down; LTexture gTailSnake_up; LTexture gMidSnake_leftup; LTexture gMidSnake_rightup; LTexture gMidSnake_upleft; LTexture gMidSnake_upright; LTexture gApple; LTexture gBackGround; LTexture gSelect; LTexture gFlame[2]; LTexture gEnter; LTexture gTextureButton[TOTAL_BUTTONS]; LTexture gBbutton; LTexture gBlock; LTexture gBackground[2]; //biến lưu file âm thanh //The music that will be played Mix_Music *gMusic = NULL; Mix_Music *gMusicMenu = NULL; //The sound effects that will be used Mix_Chunk *gScratch = NULL; Mix_Chunk *gHigh = NULL; //Globally used font - font chữ TTF_Font *gFont = NULL; //Scene textures - Điểm số LTexture gScore; LTexture::LTexture() { //Initialize mTexture = NULL; mWidth = FACTOR; mHeight = FACTOR; } LTexture::~LTexture() { //Deallocate free(); } //load hình ảnh bool LTexture::loadFromFile( std::string path ) { //Get rid of preexisting texture free(); //The final texture SDL_Texture* newTexture = NULL; //Load image at specified path SDL_Surface* loadedSurface = IMG_Load( path.c_str() ); if( loadedSurface == NULL ) { printf( "Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError() ); } else { //Color key image SDL_SetColorKey( loadedSurface, SDL_TRUE, SDL_MapRGB( loadedSurface->format, 0xFF, 0xFF, 0xFF ) ); //Create texture from surface pixels newTexture = SDL_CreateTextureFromSurface( gRenderer, loadedSurface ); if( newTexture == NULL ) { printf( "Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError() ); } else { //Get image dimensions mWidth = FACTOR; mHeight = FACTOR; } //Get rid of old loaded surface SDL_FreeSurface( loadedSurface ); } //Return success mTexture = newTexture; return mTexture != NULL; } //load font chữ bool LTexture::loadFromRenderedText( std::string textureText, SDL_Color textColor ) { //Get rid of preexisting texture free(); //Render text surface SDL_Surface* textSurface = TTF_RenderText_Solid( gFont, textureText.c_str(), textColor ); if( textSurface != NULL ) { //Create texture from surface pixels mTexture = SDL_CreateTextureFromSurface( gRenderer, textSurface ); if( mTexture == NULL ) { printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() ); } else { //Get image dimensions mWidth = textSurface->w; mHeight = textSurface->h; } //Get rid of old surface SDL_FreeSurface( textSurface ); } else { printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() ); } //Return success return mTexture != NULL; } void LTexture::free() { //Free texture if it exists if( mTexture != NULL ) { SDL_DestroyTexture( mTexture ); mTexture = NULL; mWidth = 0; mHeight = 0; } } // dựng hình texture ra cửa sổ void LTexture::render( int x, int y ) { //Set rendering space and render to screen SDL_Rect renderQuad = { x, y, mWidth, mHeight }; SDL_SetRenderDrawColor( gRenderer, 199, 149, 122, 0xFF ); SDL_RenderFillRect( gRenderer, &renderQuad); SDL_RenderCopy( gRenderer, mTexture, NULL, &renderQuad ); } void LTexture::renderPicture(int x, int y) { SDL_Rect renderQuad = { x, y, mWidth, mHeight }; SDL_RenderCopy( gRenderer, mTexture, NULL, &renderQuad ); } // lấy giá trị chiều ngang texture int LTexture::getWidth() { return mWidth; } // lấy chiều dọc int LTexture::getHeight() { return mHeight; } // cài đặt giá trị chiều ngang void LTexture::setWidth(int w){ this->mWidth = w; } // cài đặt giá trị chiều dọc void LTexture::setHeight(int h){ this->mHeight = h; } // khởi tạo SDL bool init() { //Initialization flag bool success = true; //Initialize SDL if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Set texture filtering to linear if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) ) { printf( "Warning: Linear texture filtering not enabled!" ); } //Create window gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHTPLUS, SDL_WINDOW_SHOWN ); if( gWindow == NULL ) { printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Create renderer for window gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED ); if( gRenderer == NULL ) { printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Initialize renderer color SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); //Initialize PNG loading int imgFlags = IMG_INIT_PNG; if( !( IMG_Init( imgFlags ) & imgFlags ) ) { printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() ); success = false; } //Initialize SDL_mixer if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 ) { printf( "SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError() ); success = false; } //Initialize SDL_ttf if( TTF_Init() == -1 ) { printf( "SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError() ); success = false; } } } } return success; } //load dữ liệu bool loadMedia() { //Loading success flag bool success = true; if( !gBackground[0].loadFromFile( "picture/snake_background.png" )){ printf( "Failed to load snake_background' texture image!\n" ); success = false; } if( !gBackground[1].loadFromFile( "picture/background1.png" )){ printf( "Failed to load background1' texture image!\n" ); success = false; } if( !gBlock.loadFromFile( "picture/Gold_Block.png" )){ printf( "Failed to load gBlock' texture image!\n" ); success = false; } //load gBbutton if( !gBbutton.loadFromFile( "picture/button.png" )){ printf( "Failed to load gBbutton' texture image!\n" ); success = false; } //Load Apple' texture if( !gApple.loadFromFile( "picture/apple.png" )){ printf( "Failed to load Apple' texture image!\n" ); success = false; } //Load HeadSnake texture if( !gSnake.loadFromFile( "picture/snake.png" )){ printf( "Failed to load Snake' texture image!\n" ); success = false; } if( !gHeadSnake_right.loadFromFile( "picture/headSnake_right.png" )){ printf( "Failed to load HeadSnake' texture image!\n" ); success = false; } if( !gHeadSnake_left.loadFromFile( "picture/headSnake_left.png" )){ printf( "Failed to load HeadSnake' texture image!\n" ); success = false; } if( !gHeadSnake_down.loadFromFile( "picture/headSnake_down.png" )){ printf( "Failed to load HeadSnake' texture image!\n" ); success = false; } if( !gHeadSnake_up.loadFromFile( "picture/headSnake_up.png" )){ printf( "Failed to load HeadSnake' texture image!\n" ); success = false; } //Load BodySnake texture if( !gBodySnake_ver.loadFromFile( "picture/bodySnake_ver.png" )){ printf( "Failed to load BodySnake' texture image!\n" ); success = false; } if( !gBodySnake_hor.loadFromFile( "picture/bodySnake_hor.png" )){ printf( "Failed to load BodySnake' texture image!\n" ); success = false; } //Load TailSnake texture if( !gTailSnake_right.loadFromFile( "picture/tailSnake_right.png" )){ printf( "Failed to load TailSnake' texture image!\n" ); success = false; } if( !gTailSnake_left.loadFromFile( "picture/tailSnake_left.png" )){ printf( "Failed to load TailSnake' texture image!\n" ); success = false; } if( !gTailSnake_down.loadFromFile( "picture/tailSnake_down.png" )){ printf( "Failed to load TailSnake' texture image!\n" ); success = false; } if( !gTailSnake_up.loadFromFile( "picture/tailSnake_up.png" )){ printf( "Failed to load TailSnake' texture image!\n" ); success = false; } //Load midSnake texture if( !gMidSnake_leftup.loadFromFile( "picture/mid_leftup_downright.png" )){ printf( "Failed to load MidSnake' texture image!\n" ); success = false; } if( !gMidSnake_rightup.loadFromFile( "picture/mid_rightup_downleft.png" )){ printf( "Failed to load MidSnake' texture image!\n" ); success = false; } if( !gMidSnake_upleft.loadFromFile( "picture/mid_upleft_rightdown.png" )){ printf( "Failed to load MidSnake' texture image!\n" ); success = false; } if( !gMidSnake_upright.loadFromFile( "picture/mid_upright_leftdown.png" )){ printf( "Failed to load MidSnake' texture image!\n" ); success = false; } if(!gEnter.loadFromFile("picture/EnterPlay.png")){ printf( "Failed to load Enter' texture image!\n" ); success = false; } if(!gTextureButton[0].loadFromFile("picture/button_start.png")){ printf( "Failed to load ButtonStart' texture image!\n" ); success = false; } //Buttons if(!gTextureButton[1].loadFromFile("picture/button_score.png")){ printf( "Failed to load ButtonScore' texture image!\n" ); success = false; } if(!gTextureButton[2].loadFromFile("picture/button_exit.png")){ printf( "Failed to load ButtonExit' texture image!\n" ); success = false; } if(!gSelect.loadFromFile("picture/button_select.png")){ printf( "Failed to load Select' texture image!\n" ); success = false; } //Flame if(!gFlame[0].loadFromFile("picture/flame.png")){ printf( "Failed to load Flame' texture image!\n" ); success = false; } if(!gFlame[1].loadFromFile("picture/flame1.png")){ printf( "Failed to load Flame1' texture image!\n" ); success = false; } //back ground menu if(!gBackGround.loadFromFile("picture/backGroundMenu.png")){ printf( "Failed to load BackGround' texture image!\n" ); success = false; } //Load sound effects gScratch = Mix_LoadWAV( "sound/scratch.wav" ); if( gScratch == NULL ) { printf( "Failed to load scratch sound effect! SDL_mixer Error: %s\n", Mix_GetError() ); success = false; } gHigh = Mix_LoadWAV( "sound/high.wav" ); if( gHigh == NULL ) { printf( "Failed to load high sound effect! SDL_mixer Error: %s\n", Mix_GetError() ); success = false; } //Load music gMusic = Mix_LoadMUS( "sound/03ptalit.mid" ); if( gMusic == NULL ) { printf( "Failed to load beat music! SDL_mixer Error: %s\n", Mix_GetError() ); success = false; } gMusicMenu = Mix_LoadMUS( "sound/1_rosann.mid" ); if( gMusic == NULL ) { printf( "Failed to load beat music! SDL_mixer Error: %s\n", Mix_GetError() ); success = false; } gFont = TTF_OpenFont( "font/comic.ttf", 100 ); if( gFont == NULL ) { printf( "Failed to load lazy font! SDL_ttf Error: %s\n", TTF_GetError() ); success = false; } //Nothing to load return success; } //kết thúc SDL void close() { gBackground[0].free(); gBackground[1].free(); gBlock.free(); gBbutton.free(); //Free loaded Apple images gApple.free(); //Free loaded Snake images gHeadSnake_right.free(); gHeadSnake_left.free(); gHeadSnake_up.free(); gHeadSnake_down.free(); gBodySnake_ver.free(); gBodySnake_hor.free(); gTailSnake_right.free(); gTailSnake_left.free(); gTailSnake_up.free(); gTailSnake_down.free(); gMidSnake_leftup.free(); gMidSnake_rightup.free(); gMidSnake_upleft.free(); gMidSnake_upright.free(); for(int i=0; i < TOTAL_BUTTONS; i++) gTextureButton[i].free(); gFlame[0].free(); gFlame[1].free(); gBackGround.free(); gSelect.free(); //Free the sound effects Mix_FreeChunk( gScratch ); Mix_FreeChunk( gHigh ); gScratch = NULL; gHigh = NULL; //Free the music Mix_FreeMusic( gMusic ); gMusic = NULL; Mix_FreeMusic( gMusicMenu ); gMusicMenu = NULL; //Destroy window SDL_DestroyRenderer( gRenderer ); SDL_DestroyWindow( gWindow ); gWindow = NULL; gRenderer = NULL; //Quit SDL subsystems IMG_Quit(); SDL_Quit(); } // vẽ map void DrawMap(int num){ SDL_SetRenderDrawColor( gRenderer, 0x97, 0xFF, 0xFF, 0xFF ); SDL_RenderClear(gRenderer); for(int x = 0; x < SCREEN_WIDTH; x += FACTOR){ gBlock.renderPicture(x, 0); gBlock.renderPicture(x, SCREEN_HEIGHT - FACTOR); } for(int y = 0; y < SCREEN_HEIGHT; y += FACTOR){ gBlock.renderPicture(0, y); gBlock.renderPicture(SCREEN_WIDTH - FACTOR, y); } SDL_Rect wallAround = { FACTOR, FACTOR, SCREEN_WIDTH-FACTOR*2, SCREEN_HEIGHT-FACTOR*2 }; SDL_SetRenderDrawColor( gRenderer, 199, 149, 122, 0xFF ); SDL_RenderFillRect( gRenderer, &wallAround); gBackground[1].setWidth(SCREEN_WIDTH); gBackground[1].setHeight(SCREEN_HEIGHTPLUS - SCREEN_HEIGHT); gBackground[1].render(0, SCREEN_HEIGHT); gBackground[0].setWidth(SCREEN_WIDTH/2); gBackground[0].setHeight(SCREEN_HEIGHTPLUS - SCREEN_HEIGHT); gBackground[0].renderPicture(SCREEN_WIDTH/4, SCREEN_HEIGHT); for(int x = SCREEN_WIDTH/4; x <= SCREEN_WIDTH-(SCREEN_WIDTH/4); x += FACTOR) gFlame[num].render(x, SCREEN_HEIGHT/4); for(int y = SCREEN_HEIGHT/4; y <= SCREEN_HEIGHT-(SCREEN_HEIGHT/4); y += FACTOR) gFlame[num].render( SCREEN_WIDTH/2, y); } // vẽ rắn void DrawSnake(){ //Draw snake for(int i = 0; i < snake.getLengthSnake(); i++){ if((i != snake.getLengthSnake() - 1) && (snake.getSnakeX()[i-1] != snake.getSnakeX()[i+1]) && (snake.getSnakeY()[i-1] != snake.getSnakeY()[i+1]) && ((snake.getDirectionSnake()[i-1] == dright && snake.getDirectionSnake()[i] == dup) || (snake.getDirectionSnake()[i-1] == ddown && snake.getDirectionSnake()[i] == dleft))){ gMidSnake_leftup.render(snake.getSnakeX()[i] * FACTOR, snake.getSnakeY()[i] * FACTOR); } else if((i != snake.getLengthSnake() - 1) && (snake.getSnakeX()[i-1] != snake.getSnakeX()[i+1]) && (snake.getSnakeY()[i-1] != snake.getSnakeY()[i+1]) && ((snake.getDirectionSnake()[i-1] == ddown && snake.getDirectionSnake()[i] == dright) || (snake.getDirectionSnake()[i-1] == dleft && snake.getDirectionSnake()[i] == dup))){ gMidSnake_rightup.render(snake.getSnakeX()[i] * FACTOR, snake.getSnakeY()[i] * FACTOR); } else if((i != snake.getLengthSnake() - 1) && (snake.getSnakeX()[i-1] != snake.getSnakeX()[i+1]) && (snake.getSnakeY()[i-1] != snake.getSnakeY()[i+1]) && ((snake.getDirectionSnake()[i-1] == dright && snake.getDirectionSnake()[i] == ddown) || (snake.getDirectionSnake()[i-1] == dup && snake.getDirectionSnake()[i] == dleft))){ gMidSnake_upleft.render(snake.getSnakeX()[i] * FACTOR, snake.getSnakeY()[i] * FACTOR); } else if((i != snake.getLengthSnake() - 1) && (snake.getSnakeX()[i-1] != snake.getSnakeX()[i+1]) && (snake.getSnakeY()[i-1] != snake.getSnakeY()[i+1]) && ((snake.getDirectionSnake()[i-1] == dup && snake.getDirectionSnake()[i] == dright) || (snake.getDirectionSnake()[i-1] == dleft && snake.getDirectionSnake()[i] == ddown))){ gMidSnake_upright.render(snake.getSnakeX()[i] * FACTOR, snake.getSnakeY()[i] * FACTOR); } else if(snake.getDirectionSnake()[i] == dright){ if(i == 0){ gTailSnake_right.render(snake.getSnakeX()[i] * FACTOR, snake.getSnakeY()[i] * FACTOR); } else if( i == snake.getLengthSnake() - 1){ gHeadSnake_right.render(snake.getSnakeX()[i] * FACTOR, snake.getSnakeY()[i] * FACTOR); } else{ gBodySnake_hor.render(snake.getSnakeX()[i] * FACTOR, snake.getSnakeY()[i] * FACTOR); } } else if(snake.getDirectionSnake()[i] == dleft){ if(i == 0){ gTailSnake_left.render(snake.getSnakeX()[i] * FACTOR, snake.getSnakeY()[i] * FACTOR); } else if( i == snake.getLengthSnake() - 1){ gHeadSnake_left.render(snake.getSnakeX()[i] * FACTOR, snake.getSnakeY()[i] * FACTOR); } else{ gBodySnake_hor.render(snake.getSnakeX()[i] * FACTOR, snake.getSnakeY()[i] * FACTOR); } } else if(snake.getDirectionSnake()[i] == dup){ if(i == 0){ gTailSnake_up.render(snake.getSnakeX()[i] * FACTOR, snake.getSnakeY()[i] * FACTOR); } else if( i == snake.getLengthSnake() - 1){ gHeadSnake_up.render(snake.getSnakeX()[i] * FACTOR, snake.getSnakeY()[i] * FACTOR); } else{ gBodySnake_ver.render(snake.getSnakeX()[i] * FACTOR, snake.getSnakeY()[i] * FACTOR); } } else if(snake.getDirectionSnake()[i] == ddown){ if(i == 0){ gTailSnake_down.render(snake.getSnakeX()[i] * FACTOR, snake.getSnakeY()[i] * FACTOR); } else if( i == snake.getLengthSnake() - 1){ gHeadSnake_down.render(snake.getSnakeX()[i] * FACTOR, snake.getSnakeY()[i] * FACTOR); } else{ gBodySnake_ver.render(snake.getSnakeX()[i] * FACTOR, snake.getSnakeY()[i] * FACTOR); } } } //delete old tail SDL_Rect Snake; if(snake.getSnakeXo()[0] != 0 && snake.getSnakeY()[0] != 0){ Snake.x = snake.getSnakeXo()[0]*FACTOR; Snake.y = snake.getSnakeYo()[0]*FACTOR; Snake.w = FACTOR; Snake.h = FACTOR; SDL_SetRenderDrawColor( gRenderer, 199, 149, 122, 0xFF ); SDL_RenderFillRect( gRenderer, &Snake); } } // vẽ táo void DrawApple(){ SDL_Rect Apple; Apple.x = apple.getAppleX()*FACTOR; Apple.y = apple.getAppleY()*FACTOR; Apple.w = FACTOR; Apple.h = FACTOR; SDL_SetRenderDrawColor( gRenderer, 0x00, 0xFF, 0x00, 0xFF ); SDL_RenderFillRect( gRenderer, &Apple); }
C++
UTF-8
452
2.953125
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; class B { int N, ans; double A, T, H; public: void solve() { cin >> N >> T >> A; double minDiff{ 999999 }; double tmpDiff; for (int i{ 1 }; i <= N; i++) { cin >> H; tmpDiff = abs((A - (T - 0.006 * H))); if (tmpDiff < minDiff) { ans = i; minDiff = tmpDiff; } } cout << ans << endl; } }; int main() { B solution; solution.solve(); return 0; }
C#
UTF-8
2,991
2.703125
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Flick_nishiwaki : MonoBehaviour { bool turikawa; public bool Turikawa { get { return turikawa; } set { turikawa = value; } } private Vector3 touchStartPos; // タッチ開始座標 private Vector3 touchEndPos; // タッチ終了座標 //public GameObject gameObject; // Use this for initialization void Start() { } // Update is called once per frame void Update() { Flick(); } // タッチした位置、離した位置を取得 void Flick() { if (Input.GetKeyDown(KeyCode.Mouse0)) { touchStartPos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Input.mousePosition.z); } if (Input.GetKeyUp(KeyCode.Mouse0)) { touchEndPos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Input.mousePosition.z); GetDirection(); } } void GetDirection() { float directionX = touchEndPos.x - touchStartPos.x; float directionY = touchEndPos.y - touchStartPos.y; string Direction = "touch"; if (Mathf.Abs(directionY) < Mathf.Abs(directionX)) { if (30 < directionX) { //右向きにフリック Direction = "right"; Debug.Log("右フリック"); } else if (-30 > directionX) { //左向きにフリック Direction = "left"; Debug.Log("左フリック"); } } else if (Mathf.Abs(directionX) < Mathf.Abs(directionY)) { if (30 < directionY) { //上向きにフリック Direction = "up"; } //else if (-30 > directionY) //{ // //下向きのフリック // Direction = "down"; //} else { Direction = "touch"; Debug.Log("タッチ"); } switch (Direction) { case "right": Debug.Log("右フリック");//右フリックされた時の処理 turikawa = true; break; case "left": Debug.Log("左フリック");//左フリックされた時の処理 break; case "up": Debug.Log("上フリック");//上フリックされた時の処理 break; //case "down": // Debug.Log("下フリック");//下フリックされた時の処理 // break; case "touch": Debug.Log("タッチ");//タッチした時の処理 break; } } } }
C#
UTF-8
3,686
3.203125
3
[]
no_license
// This exercise will show how to create WCF service. // How to host it using IMPERATIVE end point creation > Start visual studio . Create new project . Select WCF library. > Rename default service interface. Add operation in it. > Build this service. It will generate dll file. > Add new console project for hosting this WCF library > Add reference of System.serviceModel and WCF library project > Use imperative code to create service end points and declaring binding and behavior. > Run this console application > Create another console project for writing client application for WCF service > Right click project and add service reference. Give Address at which service is hosted. > Now create instance of proxy class and call service methods. // --------------------- // 1. Interface // --------------------- using System.ServiceModel; namespace GirishLibrary { [ServiceContract] public interface IAjit { [OperationContract] int AddNumber(int x, int y); } } using System.ServiceModel; namespace GirishLibrary { [ServiceContract] public interface IGirish { [OperationContract] string GetData(int value); } } // --------------------- // 2. service Class // --------------------- using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace GirishLibrary { public class Girish : IGirish { public string GetData(int value) { return string.Format("You entered: {0}", value); } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GirishLibrary { public class Ajit : IAjit { public int AddNumber(int x, int y) { Console.WriteLine("Ajit::AddNumber() is called "); return x + y; } } } // --------------------- // 3. Host // --------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GirishLibrary; using System.ServiceModel; using System.ServiceModel.Description; namespace GirishHost { class Program { static void Main(string[] args) { // Service 1 Uri httpBaseAddress = new Uri("http://localhost:6790"); var Sh = new ServiceHost(typeof(Ajit), new Uri[] { httpBaseAddress }); Sh.AddServiceEndpoint(typeof(IAjit), new BasicHttpBinding(), httpBaseAddress); var smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; Sh.Description.Behaviors.Add(smb); Sh.Open(); Console.WriteLine("Started....."); foreach (var item in Sh.Description.Endpoints) { Console.WriteLine("Address: " + item.Address.ToString()); Console.WriteLine("Binding: " + item.Binding.Name.ToString()); Console.WriteLine("Contract: " + item.Contract.Name.ToString()); } Console.ReadLine(); } } } // --------------------- // 4. Client // --------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GirishClient.ServiceReference1; namespace GirishClient { class Program { static void Main(string[] args) { AjitClient client = new AjitClient(); var output = client.AddNumber(10, 20); Console.WriteLine("Service Output:" + output ); } } }
Java
UTF-8
620
2.125
2
[ "MIT" ]
permissive
package ca.nexapp.starterkit.infrastructure.persistence.json.users; import ca.nexapp.starterkit.domain.users.UserFactory; import ca.nexapp.starterkit.domain.users.UserFactoryTest; import ca.nexapp.starterkit.infrastructure.persistence.inmemory.users.UserInMemory; public class UserJsonFactoryTest extends UserFactoryTest<UserInMemory> { @Override protected UserFactory createFactory() { return new UserJsonFactory(); } @Override protected Class<UserInMemory> instanceOf() { return UserInMemory.class; // no need to create a class UserJson, the InMemory fits pretty great } }
C#
UTF-8
3,682
3.578125
4
[]
no_license
/* Para resolver os problemas do array, podemos trabalhar com uma classe do C# chamada List . Para utilizarmos uma lista dentro do código precisamos informar qual é o tipo de elemento que a lista armazenará. ex : // cria uma lista que armazena o tipo Produto List<Produto> lista = new List<Produto>(); Da mesma forma que criamos a lista de Produto, também poderíamos criar uma lista de números inteiros ou de qualquer outro tipo do C#. Essa lista do C# armazena seus elementos dentro de um array. funções : Add() adiciona elemento Remove() // remove pelo elemento RemoveAt() // remove pelo índice Se quisermos saber quantos elementos existem em nosso List , podemos simplesmente ler a propriedade Count, Size(), GetTotal(). Também podemos descobrir se um elemento está dentro de uma lista: ex: lista.Contains(c1); // true ou false */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Globalization; namespace Listas { public abstract class Produto : IComparable<Produto> // classe abstrata Produto não pode ser instanciada, somente suas classes filhas não abstratas. { private protected string _nome; // Modificador de acesso private protected permite que a propria classe e suas subclasses(no mesmo projeto) acessem o atributo public static int ControleDeTiposProdutos { get; private set; } public decimal Preco { get; private protected set; } public int QtdEstoque { get; private protected set; } public Produto() //Construtor padrão { QtdEstoque = 0; ControleDeTiposProdutos++; } public Produto(decimal preco) : this() { //_preco = preco; if(preco > 0) { Preco = preco; } else { throw new ArgumentException("Preço invalido !"); //Console.WriteLine("Preço invalido ! \n"); } } public Produto(decimal preco, int qtdEstoque) : this(preco) { if(qtdEstoque >= 0) { QtdEstoque = qtdEstoque; } else { Console.WriteLine(" QtdEstoque com valor invalido ! "); } } // Properties customizada public String Nome { get { return _nome; } set { if(value != null && value.Length > 1) { _nome = value; } else { Console.WriteLine(" Nome invalido !"); } } } public abstract decimal PrecoProdutoComTaxa(); public virtual decimal ValorTotalEmEstoque() { return Preco * QtdEstoque; } public void AdicionarProdutos(int quantidade) { QtdEstoque += quantidade; } public void RemoverProdutos(int quantidade) { if (quantidade <= QtdEstoque) { QtdEstoque -= quantidade; } else { Console.WriteLine(" Quantidade no estoque menor que a solicitada ! \n"); } } //ordenando a lista pelo nome public int CompareTo(Produto produto) { return Nome.CompareTo(produto.Nome); } } }
JavaScript
UTF-8
910
2.671875
3
[]
no_license
const imgMe = document.querySelector("#imgMe") const imgMeBack = document.querySelector("#imgMeBack") const svg1 = document.querySelector("#svg1") const svg2 = document.querySelector("#svg2") const descMe = document.querySelector("#descMe pre") document.addEventListener("mousemove", (e) => { imgMe.style = `bottom : calc(-10vh + (${e.clientY}px - 350px)/100); left : calc(100vw - 1650px + 60px + (${-e.clientX}px - 350px)/40);` imgMeBack.style = `bottom : calc(-20vh + (${e.clientY}px - 350px)/30); left : calc(100vw - 1650px - 60px + (${-e.clientX}px - 350px)/15)` svg1.style = `bottom : calc(5vh + (${e.clientY}px - 350px)/60); left : calc(100vw - 1650px + 50px + (${-e.clientX}px - 350px)/25)` svg2.style = `bottom : calc(35vh + (${e.clientY}px - 350px)/15); left : calc(100vw - 1650px + 500px + (${-e.clientX}px - 350px)/10)` }) setTimeout(()=>{ descMe.innerHTML=dataUser.bio },1000)
C++
UTF-8
2,704
2.734375
3
[]
no_license
#include "Shared/Items/Item.hpp" using namespace std; constexpr int Item::DefaultArmor; constexpr int Item::DefaultSpell; constexpr int Item::DefaultWeapon; namespace { const string invalid = "~~INVALID~~"; const vector<string> categories = { "All", "Armor", "Weapons", "Potions", "Food", "Spell Tombs", "Keys", "Miscellaneous" }; const vector<string> categoriesSingle = { "All", "Armor", "Weapon", "Potion", "Food", "Spell Tomb", "Key", "Miscellaneous" }; } const string& Item::getCategoryString(Category cat) { if (cat == All) return categories[0]; unsigned int i = cat; if (i<categories.size()) return categories[i+1]; return invalid; } const string& Item::getCategorySingular(Category cat) { if (cat == All) return categoriesSingle[0]; unsigned int i = cat;; if (i<categoriesSingle.size()) return categoriesSingle[i+1]; return invalid; } Item::Category Item::getCategoryFromName(const string& name) { for (unsigned int i = 0; i<categories.size(); ++i) { if (categories[i] == name || categoriesSingle[i] == name) return Category(signed(i)-1); } return All; } const vector<string>& Item::getAllCategories() { return categories; } Item::Item(int i, Category cat, const string& nm, const string& desc, const ItemEffect::List& eft, int v, const string& mp, const string& mn) { id = i; category = cat; name = nm; description = desc; effects = eft; value = v; mapGfx = mp; menuImg = mn; } int Item::getId() const { return id; } Item::Category Item::getCategory() const { return category; } const string& Item::getName() const { return name; } const string& Item::getDescription() const { return description; } const ItemEffect::List& Item::getEffects() const { return effects; } int Item::getValue() const { return value; } const string& Item::getMapGfxFile() const { return mapGfx; } const string& Item::getMenuImageFile() const { return menuImg; } void Item::save(File& file) const { file.write<uint16_t>(getId()); file.write<uint8_t>(getCategory()); file.writeString(getName()); file.write<uint8_t>(getEffects().size()); for (auto j = getEffects().begin(); j != getEffects().end(); ++j) { file.write<uint16_t>(j->asInt()); file.write<uint32_t>(j->getIntensity()); file.write<uint32_t>(j->getDurationMs()); file.write<uint16_t>(j->getOdds() * 1000); } file.write<uint32_t>(getValue()); file.writeString(getDescription()); file.writeString(getMapGfxFile()); file.writeString(getMenuImageFile()); p_save(file); }
PHP
UTF-8
3,244
2.921875
3
[]
no_license
<?php require_once "db_engine/db_engine_admin.php"; class AdminEngine { // Properties // Constructor // Methods public function findMissingAudioEntriesInDatabase() { $dbEngine = new dbEngine(); $missingGridAudio = $dbEngine->getMissingGridAudio(); $missingInventoryGainAudio = $dbEngine->getMissingInventoryAudio("gain"); $missingInventoryUseAudio = $dbEngine->getMissingInventoryAudio("use"); $missingInventoryNotFoundAudio = $dbEngine->getMissingInventoryAudio("notfound"); $missingAudio = array_merge($missingGridAudio,$missingInventoryGainAudio,$missingInventoryUseAudio,$missingInventoryNotFoundAudio); return $missingAudio; } public function findMissingInventoryItems() { $dbEngine = new dbEngine(); $missingInventoryGainItems = $dbEngine->getMissingInventory("gain"); $missingInventoryNeedItems = $dbEngine->getMissingInventory("need"); $missingInventory = array_merge($missingInventoryGainItems,$missingInventoryNeedItems); return $missingInventory; } public function findMissingAudioFiles() { $dbEngine = new dbEngine(); $allAudioFiles = $dbEngine->getAllAudioFilenames(); $missingAudioFiles = array(); foreach ($allAudioFiles as $audio) { if (!file_exists("audio/".$audio["filename"])) { $missingAudioFiles[] = $audio; } } return $missingAudioFiles; } public function getLeaderboard() { $output = "<table class=\"table table-striped\"><tr>". "<th>Telephone</th>". "<th>Last Played</th>". "<th>Seconds Played</th>". "<th>Moves Made</th>". "</tr>\n"; $dbEngine = new dbEngine(); $leaderboard = $dbEngine->getLeaderboard(); foreach ($leaderboard as $entry) { $output .= "<tr>". "<td>". $entry["telNumber"] ."</td>\n". "<td>". $entry["lastUpdated"] ."</td>\n". "<td>". $entry["totalSecondsPlay"] ."</td>\n". "<td>". $entry["totalMovesMade"] ."</td>\n". "</tr>"; } $output .= "</table>"; return $output; } public function getPlayersInPlay() { $output = "<table class=\"table table-striped\"><tr>". "<th>Telephone</th>". "<th>Last Grid</th>". "<th>Last Played</th>". "<th>Seconds Played</th>". "<th>Moves Made</th>". "</tr>\n"; $dbEngine = new dbEngine(); $leaderboard = $dbEngine->getAllUncompletedPlayers(); foreach ($leaderboard as $entry) { $output .= "<tr>". "<td>". $entry["telNumber"] ."</td>\n". "<td>". $entry["gridID"] ."</td>\n". "<td>". $entry["lastUpdated"] ."</td>\n". "<td>". $entry["totalSecondsPlay"] ."</td>\n". "<td>". $entry["totalMovesMade"] ."</td>\n". "</tr>"; } $output .= "</table>"; return $output; } }
JavaScript
UTF-8
815
2.625
3
[]
no_license
import React, { createContext, useContext, useState, useEffect } from "react"; export const AuthContext = createContext({}); export const useAuth = () => useContext(AuthContext); export const AuthProvider = ({ children }) => { const [token, setToken] = useState(""); useEffect(() => { if (token) { salvaToken(token); } }, [token]); useEffect(() => { chiamaToken(); }, []); const salvaToken = (token) => { localStorage.setItem("token", `${token}`); }; const chiamaToken = () => { const itemToken = localStorage.getItem("token"); if (itemToken !== "") { setToken(itemToken); } else { console.log("token non trovato"); } }; return ( <AuthContext.Provider value={{ token, setToken }}> {children} </AuthContext.Provider> ); };
Markdown
UTF-8
899
2.859375
3
[]
no_license
<h1>Projeto dt money</h1> Aplicação prática e simples para gerenciamento das despesas pessoais. Desenvolvido no programa Ignite da rocketseat. ## 🚀 Tecnologias Esse projeto foi desenvolvido com as seguintes tecnologias: - [React] - [MirageJs] ## 💻 Projeto <h4>Features:</h4> <ul> <li>Dashboard de apresentação das entradas e saídas e o balanço total (entradas - saídas)</li> <li>Para criação de uma nova transação o usuário clica no botão Nova transação, a qual abre um modal para a inserção da nova transação</li> </ul> ## 🔖 Layout <table> <tr> <td><strong>Dashboard</strong></td> <td><strong>Modal</strong></td> <tr> <tr> <td><img src="screens/dash.png"></td> <td><img src="screens/modal.png"></td> <tr> </table> ## Licença Esse projeto está sob a licença MIT. Execute yarn install ou npm install para instalação.
Java
UTF-8
13,924
2.21875
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. test * cosas por poner: - Identificador de msg para poder usar varios thread sin ningun problema -Verificar paquete si es para el mouse o el texto - long press button para back y hacer delete mas seguidos. - hacer el hilo de la conexion por wifi para que no este recibiendo datos siempre */ package javaapplication15; import com.sun.awt.AWTUtilities; import java.awt.Color; import java.awt.Dimension; import java.awt.MouseInfo; import java.awt.Shape; import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.awt.geom.RoundRectangle2D; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.TimerTask; import java.util.logging.Level; import java.util.logging.Logger; import javax.microedition.io.StreamConnection; import javax.microedition.io.StreamConnectionNotifier; import javax.swing.JFrame; /** * * @author Itic */ public class MainHome extends JFrame{ static String administrador=""; DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); public MainHome() { initComponents(); // this.setBackground(new Color(0,0,0,0)); // cordenadas iconos --* primer icono (70,200), luego se incrementara 100 al x -> (170,200) , (270, 200) this.setAlwaysOnTop(true); jTextField1.setFocusable(true); /*jLabel6.setLocation(70, 200); jLabel7.setLocation(170, 200);*/ Shape forma = new RoundRectangle2D.Double(40,0, this.getBounds().width-80, this.getBounds().height,104,104); AWTUtilities.setWindowShape(this, forma); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jCheckBoxMenuItem1 = new javax.swing.JCheckBoxMenuItem(); jMenuItem4 = new javax.swing.JMenuItem(); jPanel2 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jTextField1 = new javax.swing.JTextField(); jCheckBoxMenuItem1.setSelected(true); jCheckBoxMenuItem1.setText("jCheckBoxMenuItem1"); jMenuItem4.setText("jMenuItem4"); setAutoRequestFocus(false); setBackground(new java.awt.Color(255, 255, 255)); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); setFocusCycleRoot(false); setFocusTraversalPolicyProvider(true); setMinimumSize(new java.awt.Dimension(438, 630)); setUndecorated(true); addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { formMouseEntered(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { formMousePressed(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { formMouseReleased(evt); } }); addWindowFocusListener(new java.awt.event.WindowFocusListener() { public void windowGainedFocus(java.awt.event.WindowEvent evt) { formWindowGainedFocus(evt); } public void windowLostFocus(java.awt.event.WindowEvent evt) { formWindowLostFocus(evt); } }); addWindowListener(new java.awt.event.WindowAdapter() { public void windowActivated(java.awt.event.WindowEvent evt) { formWindowActivated(evt); } }); getContentPane().setLayout(null); jPanel2.setBackground(new java.awt.Color(255, 255, 255)); jLabel2.setBackground(new java.awt.Color(255, 255, 255)); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/javaapplication15/logolector.png"))); // NOI18N jLabel2.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { jLabel2MousePressed(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { jLabel2MouseReleased(evt); } }); jPanel2.add(jLabel2); getContentPane().add(jPanel2); jPanel2.setBounds(-20, 0, 480, 520); jPanel1.setBackground(new java.awt.Color(102, 204, 255)); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); jTextField1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextField1KeyPressed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(150, 150, 150) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(154, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(25, 25, 25) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(54, Short.MAX_VALUE)) ); getContentPane().add(jPanel1); jPanel1.setBounds(0, 520, 440, 110); pack(); }// </editor-fold>//GEN-END:initComponents private void formMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMousePressed // TODO add your handling code here: }//GEN-LAST:event_formMousePressed private void formMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseReleased // TODO add your handling code here: }//GEN-LAST:event_formMouseReleased private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus // TODO add your handling code here: }//GEN-LAST:event_formWindowGainedFocus private void formMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseEntered // TODO add your handling code here: }//GEN-LAST:event_formMouseEntered private void formWindowLostFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowLostFocus // TODO add your handling code here: }//GEN-LAST:event_formWindowLostFocus private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated // TODO add your handling code here: }//GEN-LAST:event_formWindowActivated private void jLabel2MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel2MouseReleased // TODO add your handling code here: /* mouseX = MouseInfo.getPointerInfo().getLocation().x; mouseY= MouseInfo.getPointerInfo().getLocation().y; this.setLocation(mouseX,mouseY);*/ }//GEN-LAST:event_jLabel2MouseReleased private void jLabel2MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel2MousePressed // TODO add your handling code here: }//GEN-LAST:event_jLabel2MousePressed private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed // TODO add your handling code here: String usuario = ""; // variable para guardar la matricula del usuario para posteriormente comparar String tipo=""; // determinamos si es alumno o administrador Statement s = null; // se al macena la conexion if(evt.getKeyCode() == KeyEvent.VK_ENTER) // si se presiona enter { try { Connection conn = null; //se establece la conexion del sql try { conn = DriverManager.getConnection("jdbc:ucanaccess://C:/Users/Miguel/Documents/NetBeansProjects/Finger/src/javaapplication15/lector.mdb"); // aqui se tiene que cambiar la ruta de la base de datos } catch (SQLException ex) { Logger.getLogger(UserLogin.class.getName()).log(Level.SEVERE, null, ex); } s = conn.createStatement(); // se hace la conexion para pposteriormente hacer un statement , el statement sirve para poder hacer querys ResultSet rs = s.executeQuery("SELECT * from Alumnos Where Matricula='"+jTextField1.getText()+"'"); // aqui se hace un select a la tabla papra ver si el alumno existe if (rs.next()) { // se jala los datos si es que hubo una coincidencia con la base de datos y la matricula ingresada usuario=rs.getString("Matricula"); tipo= rs.getString("tipo"); } } catch (SQLException ex) { Logger.getLogger(MainHome.class.getName()).log(Level.SEVERE, null, ex); } // aqui se decide si se deja entrar a la persona o no ;) if(jTextField1.getText().equals(usuario)){ System.out.println(tipo); if(tipo.equals("Administrador")){ this.dispose(); Registro reg= new Registro(); reg.setVisible(true); reg.setLocation(200, 10); }else{ try { s.executeUpdate("INSERT INTO RegistrodeActividad (Matricula,Registro) VALUES('"+jTextField1.getText()+"', '"+dateFormat.format(date)+"')"); } catch (SQLException ex) { Logger.getLogger(MainHome.class.getName()).log(Level.SEVERE, null, ex); } } } jTextField1.setText(""); }// tecla enter fin }//GEN-LAST:event_jTextField1KeyPressed /** * @param args the command line arguments */ public static void main(String args[]) throws IOException { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { MainHome main= new MainHome(); main.setVisible(true); // main.setLocationRelativeTo(null); main.setLocation(200, 10); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem1; private javax.swing.JLabel jLabel2; private javax.swing.JMenuItem jMenuItem4; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables }
Markdown
UTF-8
1,705
3.109375
3
[]
no_license
# Tools to help with creating a CoreML model file This project contains the following: 1. download-images - NodeJS script that, given a URL on ImageNet, downloads all of the images, strips them of any irrelevant EXIF data and then puts them in the correct training data folder 2. train-model - Python script that trains a machine learning model with TuriCreate and outputs the results as a CoreML file ## download-images To run this, go into the directory, then... ``` npm install ``` Once the node modules have installed, run the following command to download the images... ``` node download-imagenet-files.js http://www.image-net.org/api/text/imagenet.synset.geturls?wnid=n07697537 hotdog ``` The first parameter should be the URL to the imagenet synset list of URLs. The second parameter is the classification you want to give these images, e.g. hotdog. The script will take a few moments to run, and after it has, it will dump the images in the training_data folder. ## train-model This folder contains a Python script that trains the model with turicreate. Before running the script, make sure that you have followed the installation instructions on the TuriCreate github - https://github.com/apple/turicreate. Note: there seems to be an issue exporting to CoreML if you have installed Python with homebrew. Therefore, I would thoroughly recommend following the steps for installing with Anaconda on the link above. Once you've got your training_data downloaded, you can run the script like so: ``` python train-model.py ``` This will take quite a while (10mins-ish), but once it has completed, a file will be created called Classifier.mlmodel. You can import this into your XCode projects.
Markdown
UTF-8
2,733
2.71875
3
[ "MIT" ]
permissive
--- title: REST API Lists pageTitle: REST API Lists description: "Learn all about GraphQL and why it is an API technology that's superior to REST. It is not only for React & Javascript developers but can be used for any API." question: Which of these statements is true? answers: ["GraphQL is a database technology", "GraphQL can only be used together with SQL", "GraphQL was invented by Facebook", "GraphQL was developed by Netflix and Coursera"] correctAnswer: 2 videoId: oCT4HOJsUZQ duration: 5 --- ## In Wekan code wekan/models/lists.js at bottom: ``` JsonRoutes.add('GET', '/api/boards/:boardId/lists', function (req, res) { try { const paramBoardId = req.params.boardId; Authentication.checkBoardAccess( req.userId, paramBoardId); JsonRoutes.sendResult(res, { code: 200, data: Lists.find({ boardId: paramBoardId, archived: false }).map(function (doc) { return { _id: doc._id, title: doc.title, }; }), }); } catch (error) { JsonRoutes.sendResult(res, { code: 200, data: error, }); } }); JsonRoutes.add('GET', '/api/boards/:boardId/lists/:listId', function (req, res) { try { const paramBoardId = req.params.boardId; const paramListId = req.params.listId; Authentication.checkBoardAccess( req.userId, paramBoardId); JsonRoutes.sendResult(res, { code: 200, data: Lists.findOne({ _id: paramListId, boardId: paramBoardId, archived: false }), }); } catch (error) { JsonRoutes.sendResult(res, { code: 200, data: error, }); } }); JsonRoutes.add('POST', '/api/boards/:boardId/lists', function (req, res) { try { Authentication.checkUserId( req.userId); const paramBoardId = req.params.boardId; const id = Lists.insert({ title: req.body.title, boardId: paramBoardId, }); JsonRoutes.sendResult(res, { code: 200, data: { _id: id, }, }); } catch (error) { JsonRoutes.sendResult(res, { code: 200, data: error, }); } }); JsonRoutes.add('DELETE', '/api/boards/:boardId/lists/:listId', function (req, res) { try { Authentication.checkUserId( req.userId); const paramBoardId = req.params.boardId; const paramListId = req.params.listId; Lists.remove({ _id: paramListId, boardId: paramBoardId }); JsonRoutes.sendResult(res, { code: 200, data: { _id: paramListId, }, }); } catch (error) { JsonRoutes.sendResult(res, { code: 200, data: error, }); } }); ```
C#
UTF-8
448
3.296875
3
[]
no_license
using System; namespace Coche_Solid.Algoritmos { public class MissingNumber { public int GetMissingNumber(int[] numbers, int totalCount) { int expectedSum = totalCount * ((totalCount + 1) / 2); int actualSum = 0; foreach (var i in numbers) { actualSum += i; } return expectedSum - actualSum; } } }
JavaScript
UTF-8
2,484
2.75
3
[]
no_license
let klikDodajPlus=function(dogodek){ let t=dogodek.target.parentElement.getElementsByTagName("p")[0]; t.innerText=Number(t.innerText)<9 ? Number(t.innerText)+1 : 9; } let klikDodajMinus=function(dogodek){ let t=dogodek.target.parentElement.getElementsByTagName("p")[0]; t.innerText=Number(t.innerText)>0 ? Number(t.innerText)-1 : 0; } let clearStorage=function(){ let sessionStorage=window.sessionStorage; sessionStorage.removeItem("ura"); sessionStorage.removeItem("stOseb"); sessionStorage.removeItem("datum"); } let klikRezerviraj=function(dogodek){ let jedi=[].slice.call(document.getElementsByClassName("foodCounter")).reduce((res,x)=>{ if(x.innerText!=0){ res.push({"meni_item":x.id,"kolicina":Number(x.innerText)}) } return res; },[]); let sessionStorage=window.sessionStorage; let ura=sessionStorage.getItem("ura"); let stOseb=Number(sessionStorage.getItem("stOseb")); let datum=sessionStorage.getItem("datum"); let datum_in_ura=new Date(datum); datum_in_ura.setHours(ura.split(":")[0],ura.split(":")[1]); const credentials = JSON.parse(localStorage.getItem("credentials")); let payload={ "datum_in_ura":datum_in_ura.toJSON(), "stOseb":stOseb, "jedi":jedi, "uporabnik_id":credentials.uporabnik_id }; let xhttp=new XMLHttpRequest(); xhttp.open("POST","/api/rezervacija"); xhttp.onload=()=>{ if(xhttp.status==200){ window.alert("Rezervacija uspešno oddana"); window.location.replace("/"); }else{ window.alert("Prišlo je do napake: "+JSON.parse(xhttp.responseText).sporocilo); window.location.replace("/"); } } xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhttp.send(JSON.stringify(payload)); } let preveriStorage=function(){ let sessionStorage=window.sessionStorage; if(sessionStorage.getItem("ura")==null || sessionStorage.getItem("stOseb")==null || sessionStorage.getItem("datum")==null){ window.location.replace("/"); } } preveriStorage(); for(let but of document.getElementsByClassName("fa-plus")){ but.addEventListener("click",klikDodajPlus); } for(let but of document.getElementsByClassName("fa-minus")){ but.addEventListener("click",klikDodajMinus); } document.getElementById("klikRezerviraj").addEventListener("click",klikRezerviraj); window.onunload=clearStorage;
Python
UTF-8
4,188
3.125
3
[]
no_license
import wda import matplotlib.pyplot as plt from PIL import Image, ImageFilter import time import pytesseract # 计算战斗结算区域中的固定方框位置中的灰色面积 # 获取图片像素值的二维数组 # 战利品第一格坐标如下: ''' (572,265)------(705,265) | | | | | | (572,395)------(705,395) ''' # 计算目标区域里的灰色像素占比,小于1/5即出魔卡 # 灰色像素RGB范围如下: # R:120~140 # G:120~140 # B:130~160 # 战斗页面判断:截取战利品栏,判断是否存在白框 # 白色RGB值:R==G==B def pull_screenshot(): c.screenshot('auto.png') fig = plt.figure() # 战利品位置,非洲人暂时取4个掉落 # 多取几个位置... items = [(572, 265, 705, 395), (572, 455, 705, 585), (572, 645, 705, 775), (572, 835, 705, 965), (400, 365, 533, 495), (400, 555, 533, 685), ] # 战利品框 item_field = (400, 220, 550, 370) # 体力框 power_field = (1140, 1725, 1200, 1790) # 获取截图 c = wda.Client() s = c.session() # 按目标区域截取图片 def crop_photo(item): # 读取图片并模糊化,减少计算量 img = Image.open('auto.png') img2 = img.filter(ImageFilter.BLUR).crop(item).resize((64, 64)) img2.save('1.png') # plt.imshow(img2) # plt.show() # 确认战利品是否包含魔卡 def check_item(index=1): count = 0 img = Image.open('1.png') size = img.size[0] * img.size[1] list = img.getcolors(size) # 通过判断灰色值范围 for i in list: r, g, b = i[1] # 排除掉落数不满4个,截取到白色框的情况,直接退出循环 if r == g == b: count += i[0] if r > 120 and r < 140 and g > 120 and g < 140 and b > 130 and b < 155: count += i[0] if count * 100 // size == 100: return False elif count * 100 // size > 20: print('材料掉落..') return False elif index == 0: print('截取到特效小星星') return 'BUG' else: print("魔卡掉落!!") return True # 确认战斗状态 def check_status(): pull_screenshot() crop_photo(item_field) count = 0 img = Image.open('1.png') size = img.size[0] * img.size[1] list = img.getcolors(size) # print(len(list)) for i in list: r, g, b = i[1] if r == b == g: count += i[0] # count记录所有符合条件的像素点,白色比例大如50%判定为战斗结算框 if count * 100 // size > 50: print("当前位于战斗结算页面...") return True else: print("当前位于战斗页面...") return False # 遍历战利品 def check_a_lot_of_items(): pull_screenshot() for item in items: crop_photo(item) result = check_item(items.index(item)) # 如果截图bug,递归重新获取截图判定 if result == 'BUG': time.sleep(1) return check_a_lot_of_items() if result: return True return False # 体力值检查,文字太小,识别准确率不够,暂不用 def power_check(): img = Image.open('auto.png') img2 = img.crop(power_field).rotate(90) img2.save('1.png') text = pytesseract.image_to_string(img2, lang='chi_sim') if (int(text) < 8): return False else: return True # 模拟点击开始 def start(): s.double_tap(1, 1) # 点击'进入战斗' s.tap(330, 1910) print("'进入战斗'") time.sleep(0.5) # 点击'开始战斗' s.tap(765, 1800) print("'开始战斗'") time.sleep(5) # 自动重复刷本直到魔卡掉落 def auto_card(): count = 1 print('正在肝第%d次' % count) start() while (True): if check_status(): if check_a_lot_of_items(): break else: s.tap(765, 1800) count += 1 start() print('正在肝第%d次' % count) else: time.sleep(5) if __name__ == '__main__': auto_card()
Java
UTF-8
2,409
3.71875
4
[]
no_license
package lib; import java.util.ArrayList; import java.util.Stack; public class FourFiveValidateBST { public FourFiveValidateBST() { // TODO Auto-generated constructor stub } public static boolean validateBST(TreeNode root) { // In order traverse, the result should be sorted... if(root == null) { return false; } ArrayList<Integer> a_tester = new ArrayList<>(); Stack<TreeNode> s = new Stack<>(); s.add(root); TreeNode currNode = root; while(!s.empty()) { if(currNode != null) { s.add(currNode.left); currNode = currNode.left; } else { currNode = s.pop(); if(currNode != null) { a_tester.add(currNode.data); currNode = currNode.right; } } } int i; for (i = 0; i < a_tester.size() - 1 && a_tester.get(i) < a_tester.get(i+1); i++) {} return i == a_tester.size() - 1; } /* Create a tree that may or may not be a BST */ public static TreeNode createTestTree() { /* Create a random BST */ TreeNode head = AssortedMethods.randomBST(10, -10, 10); /* Insert an element into the BST and potentially ruin the BST property */ TreeNode node = head; do { int n = AssortedMethods.randomIntInRange(-10, 10); int rand = AssortedMethods.randomIntInRange(0, 5); if (rand == 0) { node.data = n; } else if (rand == 1) { node = node.left; } else if (rand == 2) { node = node.right; } else if (rand == 3 || rand == 4) { break; } } while (node != null); return head; } public static void main(String[] args) { /* Simple test -- create one */ int[] array = {Integer.MIN_VALUE, 3, 5, 6, 10, 13, 15, Integer.MAX_VALUE}; TreeNode node = TreeNode.createMinimalBST(array); //node.left.data = 6; // "ruin" the BST property by changing one of the elements node.print(); boolean isBst = validateBST(node); System.out.println(isBst); /* More elaborate test -- creates 100 trees (some BST, some not) and compares the outputs of various methods. */ /*for (int i = 0; i < 100; i++) { TreeNode head = createTestTree(); // Compare results boolean isBst1 = checkBST(head); boolean isBst2 = checkBSTAlternate(head); if (isBst1 != isBst2) { System.out.println("*********************** ERROR *******************"); head.print(); break; } else { System.out.println(isBst1 + " | " + isBst2); head.print(); } }*/ } }
JavaScript
UTF-8
2,270
2.6875
3
[ "MIT" ]
permissive
// Simple constraints object, for more advanced features see https://addpipe.com/blog/audio-constraints-getusermedia/ var constraints = { audio: true, video: false } /* We're using the standard promise based getUserMedia() https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia */ navigator.mediaDevices.getUserMedia(constraints).then( function(stream) { __log("getUserMedia() success, stream created, initializing WebAudioRecorder..."); //assign to gumStream for later use gumStream = stream; /* use the stream */ input = audioContext.createMediaStreamSource(stream); //stop the input from playing back through the speakers input.connect(audioContext.destination) //get the encoding encodingType = encodingTypeSelect.options[encodingTypeSelect.selectedIndex].value; //disable the encoding selector encodingTypeSelect.disabled = true; recorder = new WebAudioRecorder(input, { workerDir: "js/", encoding: encodingType, onEncoderLoading: function(recorder, encoding) { // show "loading encoder..." display __log("Loading " + encoding + " encoder..."); }, onEncoderLoaded: function(recorder, encoding) { // hide "loading encoder..." display __log(encoding + " encoder loaded"); } }); recorder.onComplete = function(recorder, blob) { __log("Encoding complete"); createDownloadLink(blob, recorder.encoding); encodingTypeSelect.disabled = false; } recorder.setOptions({ timeLimit: 120, encodeAfterRecord: encodeAfterRecord, ogg: { quality: 0.5 }, mp3: { bitRate: 160 } }); //start the recording process recorder.startRecording(); __log("Recording started"); }).catch(function(err) { //enable the record button if getUSerMedia() fails recordButton.disabled = false; stopButton.disabled = true; }); //disable the record button recordButton.disabled = true; stopButton.disabled = false;
PHP
UTF-8
351
3.859375
4
[]
no_license
<?php class ObjectIteration { public $a=10; public $b=20; public $name="Result"; private $private="Private"; public function method() { foreach($this as $key => $value) { print "$key => $value"."\n"; } } } $class = new ObjectIteration(); foreach($class as $key => $value) { print "$key => $value"."\n"; } $class-> method(); ?>
Java
UTF-8
1,722
3.84375
4
[]
no_license
package array; import java.util.Deque; import java.util.LinkedList; import java.util.Stack; /** * Given an array and an integer k, find the maximum for each and every contiguous subarray of size k. Examples : Input : arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6} k = 3 Output : 3 3 4 5 5 5 6 */ public class SlidingWindow { public static void main(String[] args) { int[] arr = {1, 3, 2, 1, 0, 5, 2, 3, 6}; SlidingWindow sw = new SlidingWindow(); int k = 3; Integer[] result = sw.findMaxElements(arr,k); for(int element: result) { System.out.println(element); } } Integer[] findMaxElements(int[] arr, int k) { Deque<Integer> slidingMaxElementsSlide = new LinkedList<>(); Integer[] resultArray = new Integer[arr.length-k-1]; int j =0; int i = 0; int resultInd = 0; while(i<arr.length){ if(j==k) { int max = slidingMaxElementsSlide.peekFirst(); resultArray[resultInd] = arr[max]; resultInd++; if(slidingMaxElementsSlide.peekFirst()<=i-k){ slidingMaxElementsSlide.removeFirst(); } j=k-1; } while(!slidingMaxElementsSlide.isEmpty() && arr[slidingMaxElementsSlide.peek()]< arr[i]) { slidingMaxElementsSlide.removeLast(); } slidingMaxElementsSlide.addLast(i); i++; j++; } if(j==k) { int max = slidingMaxElementsSlide.peekFirst(); resultArray[resultInd] = arr[max]; resultInd++; } return resultArray; } }
Java
UTF-8
230
1.757813
2
[]
no_license
package com.tientham.androidsample.ui; import android.content.Context; /** * Created by tientham (tien.tominh@gmail.com) on 2019-05-26. */ public interface BaseView { void showLoading(); void hideLoading(); Context context(); }
TypeScript
UTF-8
1,230
2.53125
3
[]
no_license
import { Component, OnInit } from '@angular/core'; import { Burger } from '../models/Burguer'; import { JsonPipe } from '@angular/common'; import { Ingredient } from '../models/Ingredient'; const localkey = "burger;" @Component({ selector: 'burger-builder', templateUrl: './burger-builder.component.html', styleUrls: ['./burger-builder.component.css'] }) export class BurgerBuilderComponent implements OnInit { burger: Burger = new Burger(); constructor() { } ngOnInit() { console.log('started main'); this.LoadBurgerFromLocalStorage(); } AddIngredient(ingredient: Ingredient) { this.burger.AddIngredient(ingredient); this.SaveBurgerToLocalStorage(); } RemoveIngredient(ingredient: Ingredient) { this.burger.RemoveIngredient(ingredient); this.SaveBurgerToLocalStorage(); } private SaveBurgerToLocalStorage() { const burgerJson = JSON.stringify(this.burger); localStorage.setItem(localkey, burgerJson); } private LoadBurgerFromLocalStorage() { const storeJson = localStorage.getItem(localkey); if(storeJson) { const storeData = JSON.parse(storeJson); if(storeData._ingredients) this.burger = new Burger(storeData._ingredients); } } }
Java
UTF-8
3,041
1.875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.client.endpoint; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Collections; import org.springframework.core.convert.converter.Converter; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.RequestEntity; import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.core.ClientAuthenticationMethod; /** * Utility methods used by the {@link Converter}'s that convert from an implementation of * an {@link AbstractOAuth2AuthorizationGrantRequest} to a {@link RequestEntity} * representation of an OAuth 2.0 Access Token Request for the specific Authorization * Grant. * * @author Joe Grandja * @since 5.1 * @see OAuth2AuthorizationCodeGrantRequestEntityConverter * @see OAuth2ClientCredentialsGrantRequestEntityConverter */ final class OAuth2AuthorizationGrantRequestEntityUtils { private static HttpHeaders DEFAULT_TOKEN_REQUEST_HEADERS = getDefaultTokenRequestHeaders(); private OAuth2AuthorizationGrantRequestEntityUtils() { } static HttpHeaders getTokenRequestHeaders(ClientRegistration clientRegistration) { HttpHeaders headers = new HttpHeaders(); headers.addAll(DEFAULT_TOKEN_REQUEST_HEADERS); if (ClientAuthenticationMethod.CLIENT_SECRET_BASIC.equals(clientRegistration.getClientAuthenticationMethod())) { String clientId = encodeClientCredential(clientRegistration.getClientId()); String clientSecret = encodeClientCredential(clientRegistration.getClientSecret()); headers.setBasicAuth(clientId, clientSecret); } return headers; } private static String encodeClientCredential(String clientCredential) { try { return URLEncoder.encode(clientCredential, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException ex) { // Will not happen since UTF-8 is a standard charset throw new IllegalArgumentException(ex); } } private static HttpHeaders getDefaultTokenRequestHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8)); final MediaType contentType = MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"); headers.setContentType(contentType); return headers; } }
JavaScript
UTF-8
4,527
2.6875
3
[]
no_license
import React, { useState, useEffect } from 'react' import Blog from './components/Blog' import blogService from './services/blogs' import Notification from './components/Notification' import loginService from './services/login' import BlogForm from './components/BlogForm' import Togglable from './components/Togglable' const App = () => { const [blogs, setBlogs] = useState([]) const [notification, setNotification] = useState({ text: null, cName: null }) const [username, setUsername] = useState('') const [password, setPassword] = useState('') const [user, setUser] = useState(null) useEffect(() => { blogService.getAll().then(blogs => setBlogs(blogs) ) }, []) useEffect(() => { const loggedUserJSON = window.localStorage.getItem('loggedBlogAppUser') if (loggedUserJSON) { const user = JSON.parse(loggedUserJSON) setUser(user) blogService.setToken(user.token) } }, []) const handleLogin = async (event) => { event.preventDefault() try { const user = await loginService.login( { username, password, }) window.localStorage.setItem('loggedBlogAppUser', JSON.stringify(user)) blogService.setToken(user.token) setUser(user) setUsername('') setPassword('') setMessage(`Welcome ${user.name}`, 'success') } catch (exception) { setMessage('wrong username or password', 'error') } } const setMessage = ((text, cName) => { setNotification({ text: text, cName: cName }) setTimeout(() => { setNotification({ text: null, cName: null }) }, 5000) }) const handleLogout = () => { window.localStorage.clear() setUser(null) setMessage('You have safely logged out', 'success') } const addBlog = (newBlog) => { blogFormRef.current.toggleVisibility() blogService .create(newBlog) .then(returnedBlog => { setBlogs(blogs.concat(returnedBlog)) setMessage(`a new blog ${returnedBlog.title} by ${returnedBlog.author} added`, 'success') }) .catch(() => { setMessage('Could not add blog, sorry', 'error') }) } const updateBlog = (blog) => { const likedBlog = blogs.find(b => b.id === blog.id) const updatedBlog = { ...likedBlog, likes: likedBlog.likes + 1 } blogService .update(blog.id, updatedBlog) .then(returnedBlog => { setBlogs(blogs.map(b => b.id !== blog.id ? b : returnedBlog)) setMessage('Thanks for liking!', 'success') }) .catch(error => { setMessage(`Blog ${updatedBlog.title} was already removed from the server`, error) }) } const blogFormRef = React.createRef() const blogForm = () => ( <Togglable buttonLabel='create new blog' ref={blogFormRef}> <BlogForm createBlog={addBlog} /> </Togglable> ) const deleteBlog = (blog) => { const confirm = window.confirm(`Remove blog ${blog.title} by ${blog.author}?`) if (confirm) { blogService .remove(blog.id) .then(setBlogs(blogs.filter(b => b.id !== blog.id))) setMessage(`Blog ${blog.title} by ${blog.author} removed!`, 'success') } } if (user === null) { return ( <div> <Notification message={notification} /> <h2>Please login to application</h2> <form onSubmit={handleLogin}> <div> username <input id="username" type="text" value={username} name="Username" onChange={({ target }) => setUsername(target.value)} /> </div> <div> password <input id="password" type="text" value={password} name="Password" onChange={({ target }) => setPassword(target.value)} /> </div> <button type="submit">login</button> </form> </div> ) } return ( <div> <Notification message={notification} /> <h1>Blogs</h1> <p>{user.name} logged in <button type="submit" id='logOutButton' onClick={handleLogout}>log out</button> </p> {blogForm()} <ul> {blogs .sort(({ likes: previousLikes }, { likes: currentLikes }) => currentLikes - previousLikes) .map(blog => <Blog key={blog.id} blog={blog} user={user} updateBlog={updateBlog} removeBlog={deleteBlog} /> )} </ul> </div> ) } export default App
Shell
UTF-8
429
3.75
4
[]
no_license
#!/bin/bash set -euo pipefail readonly BASE_DIR="$(dirname $(realpath $BASH_SOURCE))" source "$BASE_DIR/config/current.sh" function main() { local name="$1" cd "$REPOSITORIES_DIR/$name.git" local newrev="$(git rev-parse ${2-HEAD})" local oldrev="$(git rev-parse $newrev~)" echo "$oldrev $newrev main" | hooks/post-receive } if [[ $# -lt 1 ]] then echo "$0 name [revision]" exit 1 fi main "$@"
Python
UTF-8
581
3.078125
3
[]
no_license
import sys def vauvau(lines): a,b,c,d = [int(x) for x in lines[0].split()] f_t = a+b s_t = c+d p,m,g = [int(x) for x in lines[1].split()] for p in [p,m,g]: p_t_1 = p % f_t p_t_2 = p % s_t # print(p, p_t_1, p_t_2) if p_t_1 != 0 and p_t_1 <= a and p_t_2 != 0 and p_t_2 <= c: print("both") elif (p_t_1 != 0 and p_t_1 <= a) or (p_t_2 != 0 and p_t_2 <= c): print("one") else: print("none") def main(): lines = [line.strip() for line in sys.stdin] vauvau(lines) main()
Shell
UTF-8
438
2.65625
3
[]
no_license
#!/bin/bash -e rails new $1 cd $1 git init git add . git commit -m "initial commit; 'rails new $1'" heroku create $1 #TODO convert to heredoc echo >> Gemfile echo "# Heroku dependencies" >> Gemfile echo "group :production do" >> Gemfile echo " gem 'pg'" >> Gemfile echo " gem 'thin'" >> Gemfile echo "end" >> Gemfile bundle install --without production git add Gemfile* git commit -m "add Heroku dependencies" git push heroku HEAD
Markdown
UTF-8
2,148
2.609375
3
[ "MIT" ]
permissive
# Ruby on Rails Patterns: Service Objects and Interactors ![logo](https://res.cloudinary.com/practicaldev/image/fetch/s--jvDLhx0b--/c_imagga_scale,f_auto,fl_progressive,h_420,q_auto,w_1000/https://dev-to-uploads.s3.amazonaws.com/i/cpcr5w0kgl6j94tss7n9.png) ## About The Project This is a Ruby on Rails demo application that shows how to organise a fat controller intro service objects. And then goes further into adding `interactor` gem and showing how to better organise this concept of service objects with interactors. ## How To Run This is a Ruby on Rails API only application. Since we only need API to demonstrate the patterns. Let's create the app with ```bash rails new rails-service \ --skip-action-text \ --skip-active-storage \ --skip-javascript \ --skip-spring -T \ --skip-turbolinks \ --skip-sprockets \ --skip-test \ --api ``` We will skip some of the parts that we know are not necessary for this demonstration. The migration and seed are already in. So let's run ```bash rails db:migrate db:seed ``` The controllers are versioned into `v1`, `v2`, `v3`. Each controller shows how to tackle the problem with user registration. This controller handles user creation, subscription creation for user, adding a dedicated support person for the user, sending welcome email and update time series based metrics table for revenue calculation. You can hit the api with ```bash curl -XPOST -H "Content-type: application/json" -d '{ "name": "Blake Dawson", "email": "blake@dawson.com", "pass": "OnePass", "product_name": "Business" }' 'localhost:3000/api/v1/user/create' ``` Replace `v1` with `v2` or `v3` to hit different versions of same controller ## Contribution Want to contribute? Great! To fix a bug or enhance an existing code, follow these steps: - Fork the repo - Create a new branch (`git checkout -b improve-feature`) - Make the appropriate changes in the files - Add changes to reflect the changes made - Commit your changes (`git commit -am 'Improve feature'`) - Push to the branch (`git push origin improve-feature`) - Create a Pull Request ## License MIT © [MD Ahad Hasan](https://github.com/joker666)
Java
UTF-8
616
1.875
2
[ "Apache-2.0" ]
permissive
package org.javamaster.b2c.classloader; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; /** * @author yudong * @date 2019/6/24 */ @SpringBootApplication @ComponentScan(basePackages = "org.javamaster.b2c") public class ClassLoaderApplication { public static void main(String[] args) { // 关闭devtools重启功能 // System.setProperty("spring.devtools.restart.enabled", "false"); SpringApplication.run(ClassLoaderApplication.class, args); } }
Java
UTF-8
596
2.484375
2
[]
no_license
package br.com.bandtec.Continuada01; public class App { public static void main(String[] args) { PersonagemController pe = new PersonagemController(); Personagem p = new Sayajin("Terra", "Goku", "Kamehameha", 1500.00, 2); Personagem p2 = new Sayajin("Vegeta", "Vegeta", "Final Flash", 5000.00, 3); Personagem p3 = new Namekuseijin("Namek", "Piccolo", "Makankosappo", 3000.00, 3); pe.addPoder(p); pe.addPoder(p2); pe.addPoder(p3); pe.mostraPersonagens(); pe.exibePoderMaiorQue8000Mil(); } }
TypeScript
UTF-8
2,253
3.09375
3
[ "Apache-2.0" ]
permissive
import _get from 'lodash.get'; import { Observable } from 'rxjs'; import { concat } from 'rxjs/internal/observable/concat'; import { debounceTime, map, switchMap } from 'rxjs/operators'; // Flattens an array of arrays: [1, [a, b], [c], d] = [1, a, b, c, d] export const flatten = (arrays: Array<string>) => [].concat.apply([], arrays); // A wrapper for the _get function. export const pick = (fieldName, fallback?) => (entity) => _get(entity, fieldName, fallback); // Picks particular fields from a collection (collection = array of objects). export const pluck = (fieldName, fallback) => (array) => array.map(pick(fieldName, fallback)); // A wrapper for a filter function. export const filterBy = (filterFn) => (array) => array.filter(filterFn); // To be used in filter function. Assumes there is no other item with the same value to the left of the inspected item. export const isMostLeft = (value, index, self) => self.indexOf(value) === index; export const includes = (substr) => (value) => value.includes(substr); // Filters out repetitions from an array. export const makeDistinct = filterBy(isMostLeft); /** * Used to stitch together autocomplete suggestions source and autocomplete input field to filter results relevant * to user input. * * @method filterSource * @param {Observable<string[]>} [autocompleteSource$] Array of all suggestions. * @param {Observable<string>} [formInputValue$] String used to filter suggestions. * @return {Observable<string[]>} All suggestions including the formInputValue$ string. * * ### Example * ```javascript * * const claimDefinitions$: Observable<string[]> = this.suggestionService.get() * this.suggestions$ = filterSource(claimDefinitions$, formGroup.get('claimName').valueChanges); * ``` * */ export function filterSource(autocompleteSource$: Observable<string[]>, formInputValue$: Observable<string>): Observable<string[]> { const filteredSource$ = (autocompleteInputValue) => autocompleteSource$.pipe( map(filterBy(includes(autocompleteInputValue))) ); // Concat is used to return all suggestions on the first click. return concat(autocompleteSource$, formInputValue$.pipe( debounceTime(300), switchMap(filteredSource$) )); }
Java
UTF-8
691
3.046875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package creational.builder; /** * * Clase ProjectException que permite tirar una excepcion personalizada * cuando se introduzca un dato erroneo al querer crear un Project. * Importante para interrumpir el proceso de creacion de un objeto y evitar * uso de memoria inecesario. * * @author Miguel Angel Egoavil Mathison Carne: B92695 * @author Jose Pablo Vásquez Araya Carne: B98315 */ class ProjectException extends Exception { public ProjectException(String msg) { super("No se puede crear el proyecto debido a: " + msg); } }