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
|
|---|---|---|---|---|---|---|---|
PHP
|
UTF-8
| 1,927
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\Repo;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
class ApiController extends Controller
{
/**
* @Route("/get-top-php-repos", name="get_top_php_repos")
*/
public function getTopPhpReposAction(Request $request)
{
//init api wrapper
$client = new \Github\Client();
//init EntityManager
$em = $this->getDoctrine()->getManager();
//https://github.com/KnpLabs/php-github-api
$repo_response = $client->api('search')->repositories('language:php', 'stars', 'desc');
//count used to limit our foreach loop - 30 is the default limit
$count = 0;
$import_limit = 30;
foreach($repo_response['items'] as $repo_row){
$count++;
if( $count <= $import_limit){
//get repository
$repository = $this->getDoctrine()->getRepository('AppBundle:Repo');
$existing_repo = $repository->findOneBy(array('github_id'=>$repo_row['id']));
if($existing_repo){
//hydrate existing repo
$existing_repo->hydrateFromDataRow($repo_row);
} else{
//instantiate a new repo
$repo = new Repo();
//move all setters / date logic to hydrate
$repo->hydrateFromDataRow($repo_row);
$em->persist($repo);
}
} else{
break;
}
}
$em->flush();
return new RedirectResponse($this->generateUrl('frontend'));
}
}
|
JavaScript
|
UTF-8
| 5,431
| 2.671875
| 3
|
[] |
no_license
|
/*
* GameObject class. All displayed items use this.
*/
// Some trixie hacky setup of enums
var AnimationState = {
'list': ['IDLE', 'WALKING', 'SHOT', 'PODDING']
};
for (var as in AnimationState.list)
{
AnimationState[AnimationState.list[as]] = 0x1 << as;
// This one needs to go back and forth
AnimationState[0x1 << as] = AnimationState.list[as];
}
delete AnimationState.list;
var GameObjectState = {
'list': ['IDLE', 'MOVING', 'FLEEING', 'ATTACKING', 'DEAD', 'PODDED'],
'NONE': 0x00
};
for (var i in GameObjectState.list)
{
GameObjectState[GameObjectState.list[i]] = 0x01 << i;
};
delete GameObjectState.list;
var Tag = {
'list': ['PLAYER', 'POLICE', 'TERRAIN', 'CIVILIAN'],
'NONE': 'NONE',
'IGNORE': 0xFF
};
delete Tag.list;
for (var p in Tag.list)
{
Tag[Tag.list[p]] = 0x01 << p;
}
var Direction = {
'list': ['NORTH', 'EAST', 'SOUTH', 'WEST']
};
for (var d in Direction.list)
{
Direction[Direction.list[d]] = 0x01 << d;
// This one needs to go back and forth too
Direction[0x01 << d] = Direction.list[d];
}
var DirVec = {
'NORTH': Vec(0, -1),
'EAST': Vec(1, 0),
'SOUTH': Vec(0, 1),
'WEST': Vec(-1, 0)
};
var MOVE_STOP_THRESHOLD = 1;
function GameObject()
{
this.spriteTint = 0xFFFFFF;
this.animationSpeed = 0.125 - Math.random() * 0.125;
this.animationState = AnimationState.IDLE;
this.tag = Tag.NONE;
this.pos = Vec(0, 0);
this.gPos = Vec(0, 0);
this.size = Vec(3, 3);
this.spriteContainer = new PIXI.Container();
this.setSprite(this.buildSprite());
this.state = GameObjectState.IDLE;
this.moveSpeed = 2 * 32; // 1/2 a second per grid
this.deltaMovement = null;
this.facingDirection = Direction.SOUTH;
// Take that, entropy!
this.animationName = sprintf('%f%f%f', Math.random(), Math.random(), Math.random());
this.animations = {};
}
GameObject.prototype.buildSprite = function()
{
var sprite = new PIXI.Sprite(PIXI.Texture.fromImage('assets/default.png'));
sprite.anchor.x = sprite.anchor.y = 0.5;
sprite.name = 'default';
return sprite;
};
GameObject.prototype.buildMovieClip = function(anim_name, mc_frames)
{
var mc = PIXI.extras.MovieClip.fromFrames(mc_frames);
mc.name = anim_name;
mc.anchor.x = mc.anchor.y = 0.5;
mc.animationSpeed = 0.125;
return mc;
};
GameObject.prototype.setSprite = function(sprite)
{
if (this.animationName == sprite.animationName)
{
return;
}
// Clean up current
var currSprite = this.sprite;
if (currSprite instanceof PIXI.extras.MovieClip)
{
currSprite.stop();
}
// Do some testing?
this.spriteContainer.removeChild(currSprite);
this.sprite = sprite;
if (sprite instanceof PIXI.extras.MovieClip)
{
this.sprite = sprite;
this.sprite.animationSpeed = this.animationSpeed;
this.spriteContainer.position.x = this.pos.x;
this.spriteContainer.position.y = this.pos.y;
this.sprite.gotoAndPlay(0);
}
this.sprite.tint = this.spriteTint;
this.spriteContainer.addChild(this.sprite);
};
GameObject.prototype.update = function(delta)
{
switch (this.state)
{
case GameObjectState.IDLE:
this.tickIdle(delta);
this.tickUpdatePosition(delta);
break;
case GameObjectState.MOVING:
this.tickUpdatePosition(delta);
break;
case GameObjectState.DEAD:
break
}
};
GameObject.prototype.tickIdle = function(delta)
{
// Should be implemented by child
};
GameObject.prototype.tickUpdatePosition = function(delta)
{
var dest = Vec(grid.gridToWorld('x', this.gPos.x), grid.gridToWorld('y', this.gPos.y));
var dX = dest.x - this.pos.x;
var dY = dest.y - this.pos.y;
if (Math.abs(dX) > MOVE_STOP_THRESHOLD || Math.abs(dY) > MOVE_STOP_THRESHOLD)
{
this.deltaMovement = Vec(dX, dY);
var dir = Vec(dX, dY).normalize();
this.pos.add(dir.mult(this.moveSpeed * delta));
}
else
{
this.pos = dest;
this.deltaMovement = null;
}
this.spriteContainer.position.x = this.pos.x;
this.spriteContainer.position.y = this.pos.y;
};
GameObject.prototype.setTint = function(tint)
{
this.spriteTint = tint;
this.sprite.tint = tint;
};
GameObject.prototype.setAnimSpeed = function(speed)
{
this.animationSpeed = speed;
if (this.sprite instanceof PIXI.extras.MovieClip)
{
this.sprite.animationSpeed = this.animationSpeed;
}
};
GameObject.prototype.getPodded = function()
{
this.state = GameObjectState.PODDED;
this.animationState = AnimationState.PODDING;
// this.setSprite(this.animations[''])
// For now just tint the damn thing
this.setTint(0x00FF00);
this.setAnimSpeed(0.01);
if (pod_targets.indexOf(this) != -1)
{
pod_targets.splice(pod_targets.indexOf(this), 1)
}
checkVictory();
};
GameObject.prototype.updateAnimation = function()
{
var dirStr = Direction[this.facingDirection].toLowerCase();
var animStr = AnimationState[this.animationState].toLowerCase();
this.animationName = sprintf('%s_%s', animStr, dirStr);
this.setSprite(this.animations[this.animationName]);
};
|
Java
|
UTF-8
| 550
| 1.570313
| 2
|
[
"CDDL-1.0",
"BSD-3-Clause",
"LGPL-2.1-or-later",
"MIT-0",
"LicenseRef-scancode-warranty-disclaimer",
"SAX-PD",
"Apache-2.0",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-mx4j"
] |
permissive
|
package org.javalite.activeweb;
import app.services.RedirectorModule;
import com.google.inject.Guice;
import org.javalite.activejdbc.DBException;
import org.junit.Before;
import org.junit.Test;
/**
* @author Igor Polevoy: 3/5/12 11:19 AM
*/
public class Issue88Spec extends AppIntegrationSpec {
@Before
public void before() {
setInjector(Guice.createInjector(new RedirectorModule()));
}
@Test(expected = DBException.class)
public void shouldNotWrapDBException() {
controller("db_exception").get("index");
}
}
|
Markdown
|
UTF-8
| 8,870
| 2.53125
| 3
|
[] |
no_license
|
---
description: "Easiest Way to Prepare Award-winning Spicy chorizo &amp; longaniza shrimp soup"
title: "Easiest Way to Prepare Award-winning Spicy chorizo &amp; longaniza shrimp soup"
slug: 1032-easiest-way-to-prepare-award-winning-spicy-chorizo-and-amp-longaniza-shrimp-soup
date: 2020-11-19T01:24:55.964Z
image: https://img-global.cpcdn.com/recipes/6366674064244736/751x532cq70/spicy-chorizo-longaniza-shrimp-soup-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/6366674064244736/751x532cq70/spicy-chorizo-longaniza-shrimp-soup-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/6366674064244736/751x532cq70/spicy-chorizo-longaniza-shrimp-soup-recipe-main-photo.jpg
author: Erik Gill
ratingvalue: 4.9
reviewcount: 37425
recipeingredient:
- "2 lb shrimp"
- "2 carrots"
- "4 celery sticks"
- "4 chiote mexican squash"
- "1/2 onion"
- "1 pinch paprika"
- "1 tomatoe"
- "1/2 tbsp garlic"
- "1 cup cilantro"
- "1/2 packages beef chorizo"
- "1 cup fresh loganiza"
- "1 box low sodium chicken stock"
- "1 tbsp chicken bullion"
- "1 tsp salt"
- "1 tsp oregano"
- "1/2 tsp cumin"
recipeinstructions:
- "start by cleaning and pilling shrimp use skins boil in seperate pot for stock for soup"
- "dice your veggies into bite size pieces"
- "cook your beef chorizo & loganiza in the pot your going to cook your shrimp in. once cooked about 7 minutes or so remove from pan to a separate bowl. now add 2 tspn olive oil cook onions n tomatoes down till tender. add your veggies in except cilantro cook for about 10-12 minutes on medium heat adding your spices."
- "now add your chicken stock, strain your shrimp stock into pot & 2 cup of water bring to a simmer cook down veggies till tender."
- "once your veggies are tender add your shrimp cook till they turn pink about 3-4 minutes turn off add cilantro."
- "serve with limes."
categories:
- Recipe
tags:
- spicy
- chorizo
-
katakunci: spicy chorizo
nutrition: 188 calories
recipecuisine: American
preptime: "PT18M"
cooktime: "PT41M"
recipeyield: "3"
recipecategory: Lunch
---

Hello everybody, I hope you're having an incredible day today. Today, I'm gonna show you how to make a distinctive dish, spicy chorizo & longaniza shrimp soup. It is one of my favorites food recipes. This time, I am going to make it a bit tasty. This will be really delicious.
Spicy chorizo & longaniza shrimp soup is one of the most well liked of recent trending meals in the world. It is enjoyed by millions every day. It is simple, it's quick, it tastes yummy. They're fine and they look fantastic. Spicy chorizo & longaniza shrimp soup is something that I have loved my whole life.
Find Spanish Sausages Including Chorizo, Morcilla, Butifarra, & More At Tienda.com! Find Deals on Spicy Chorizo in Meats on Amazon. Mexican chorizo is typically seasoned with vinegar and chile peppers, while Spanish chorizo is made with garlic and pimentรณn (Spanish smoked paprika, either sweet or hot), which gives it its deep. Place the pork, Aleppo pepper, chili powder, garlic, salt, black pepper, oregano, cumin, cloves, and coriander into a bowl, and lightly toss the pork with the seasonings until thoroughly blended.
To get started with this particular recipe, we have to first prepare a few components. You can have spicy chorizo & longaniza shrimp soup using 16 ingredients and 6 steps. Here is how you cook that.
<!--inarticleads1-->
##### The ingredients needed to make Spicy chorizo & longaniza shrimp soup:
1. Prepare 2 lb shrimp
1. Take 2 carrots
1. Prepare 4 celery sticks
1. Take 4 chiote "mexican squash"
1. Make ready 1/2 onion
1. Take 1 pinch paprika
1. Prepare 1 tomatoe
1. Take 1/2 tbsp garlic
1. Make ready 1 cup cilantro
1. Take 1/2 packages beef chorizo
1. Make ready 1 cup fresh loganiza
1. Make ready 1 box low sodium chicken stock
1. Get 1 tbsp chicken bullion
1. Prepare 1 tsp salt
1. Get 1 tsp oregano
1. Make ready 1/2 tsp cumin
This year, add a little kick to your Thanksgiving turkey with this spicy cornbread dressing. Flavored with jalapenos, chorizo, and cilantro, it will be a welcome change of pace from your usual recipe. Spicy Chorizo Soup is developed to embrace the spiciness of the chorizo and to use that spiciness to balance the dish. Using a different type of ground sausage, will prevent you from getting the full experience of how the recipe is meant to taste.
<!--inarticleads2-->
##### Steps to make Spicy chorizo & longaniza shrimp soup:
1. start by cleaning and pilling shrimp use skins boil in seperate pot for stock for soup
1. dice your veggies into bite size pieces
1. cook your beef chorizo & loganiza in the pot your going to cook your shrimp in. once cooked about 7 minutes or so remove from pan to a separate bowl. now add 2 tspn olive oil cook onions n tomatoes down till tender. add your veggies in except cilantro cook for about 10-12 minutes on medium heat adding your spices.
1. now add your chicken stock, strain your shrimp stock into pot & 2 cup of water bring to a simmer cook down veggies till tender.
1. once your veggies are tender add your shrimp cook till they turn pink about 3-4 minutes turn off add cilantro.
1. serve with limes.
Spicy Chorizo Soup is developed to embrace the spiciness of the chorizo and to use that spiciness to balance the dish. Using a different type of ground sausage, will prevent you from getting the full experience of how the recipe is meant to taste. Spicy Chorizo Kennels produces high quality prey drive, old school, American Pit Bull Terriers. Chorizo is a heavily spiced sausage commonly used in Mexican dishes. It's crumbled and fried up with whatever other ingredients the dish calls for.
Turn to Food to Improve Your Mood
Many of us think that comfort foods are terrible for us and that we must keep away from them. Sometimes, if your comfort food is basically candy or other junk foods, this is true. Otherwise, comfort foods may be super nourishing and good for you. Several foods actually do elevate your mood when you eat them. When you are feeling a little down and are in need of an emotional pick-me-up, test out a couple of these.
Eggs, believe it or not, are wonderful for helping you battle depression. Just be sure that you do not throw out the egg yolk. Every time you want to cheer yourself up, the egg yolk is the most important part of the egg. Eggs, the yolks particularly, are high in B vitamins. The B vitamin family can be terrific for lifting up your mood. This is because these vitamins improve the function of your brain's neural transmitters (the parts of the brain that dictate how you feel). Try to eat an egg and feel a lot happier!
Make several trail mix of nuts or seeds. Your mood can be raised by consuming peanuts, almonds, cashews, sunflower seeds, pumpkin seeds, and so on. This is because these foods are high in magnesium, which helps to increase serotonin production. Serotonin is known as the "feel good" chemical substance and it tells your brain how you should be feeling day in and day out. The more serotonin you have, the more pleasant you will feel. Nuts, in addition to bettering your mood, can be a super protein source.
Cold water fish are great if you are wanting to be in a better mood. Cold water fish including tuna, trout and wild salmon are chock full of DHA and omega-3s. Omega-3 fatty acids and DHA are two things that actually help the grey matter in your brain function a lot better. It's the truth: consuming tuna fish sandwiches can really help you fight your depression.
It's not hard to drive away your bad mood when you consume grains. Millet, quinoa, barley, etc are great at helping you feel happier. They help you feel full as well which can actually help to make your mood better. It's easy to feel depressed when you are starving! The reason these grains are so great for your mood is that they are not difficult for your body to digest and process. These foods are easier to digest than others which helps jumpstart a rise in your glucose levels which in turn takes your mood to a happier place.
Green tea is truly excellent for your mood. You were just waiting to read that, weren't you? Green tea has a lot of an amino acid referred to as L-theanine. Studies have shown that this amino acid actually induces brain waves. This helps sharpen your mental energy while simultaneously calming your body. You probably already knew it is not hard to get healthy when you consume green tea. Now you know that green tea helps you to elevate your moods as well!
So you see, you don't have to turn to junk food or foods that are bad for you so you can feel better! Try some of these instead!
|
Ruby
|
UTF-8
| 976
| 2.828125
| 3
|
[] |
no_license
|
require_relative './character_flyweight_factory'
require_relative './font_flyweight_factory'
require 'singleton'
class CharacterAndFontFlyweightFactory
include Singleton
attr_accessor :font_and_characters
attr_reader :character_flyweight_factory, :font_flyweight_factory
def initialize
@font_and_characters = {}
@character_flyweight_factory = CharacterFlyweightFactory.instance
@font_flyweight_factory = FontFlyweightFactory.instance
end
def get_object_for(font, unicode)
key = { character: unicode, font: font }
if font_and_characters.key?(key)
character_and_font_pair = font_and_characters[key]
else
character_and_font_pair = {
character: character_flyweight_factory.get_character_for(unicode),
font: font_flyweight_factory.get_font_for(font[:font_name], font[:font_size], font[:font_style])
}
font_and_characters[key] = character_and_font_pair
end
character_and_font_pair
end
end
|
Ruby
|
UTF-8
| 2,138
| 3.421875
| 3
|
[] |
no_license
|
require './lib/pieces/knight.rb'
require './lib/board.rb'
RSpec.describe Knight do
context "when the Knight is the only piece" do
describe "#possible_moves" do
it "returns a list of all possible moves for a Knight at the border" do
board = double("Board")
square = double("Square")
allow(board).to receive(:[]) do |col, row|
if col < 0 or col > 7
nil
elsif row < 0 or row > 7
nil
else
square
end
end
# set all the squares in the board as empty squares
allow(square).to receive(:occupied?).and_return(false)
knight = Knight.new(position: [6, 0], color: "w")
moves = knight.possible_moves(board)
expect(moves).to match_array([
[7, 2], [5, 2], [4, 1]
])
end
it "returns a list of all possible moves for a knight in the middle" do
board = double("Board")
square = double("Square")
allow(board).to receive(:[]).and_return(square)
# set all the squares in the board as empty squares
allow(square).to receive(:occupied?).and_return(false)
knight = Knight.new(position: [4, 4], color: "b")
moves = knight.possible_moves(board)
expect(moves).to match_array([
[5, 6], [6, 5], [6, 3], [5, 2], [3, 2], [2, 3], [2, 5], [3, 6]
])
end
end
end
context "when the Knight is not the only piece" do
describe "#possible_moves" do
it "returns a list of possible moves" do
board = Board.new
board.place_piece([2, 3], piece: :Knight, color: "w")
board.place_piece([3, 2], piece: :Bishop, color: "w")
board.place_piece([4, 5], piece: :Rook, color: "b")
board.place_piece([5, 5], piece: :Rook, color: "w")
board.place_piece([5, 6], piece: :Rook, color: "b")
board.place_piece([4, 4], piece: :Knight, color: "w")
moves = board[4, 4].piece.possible_moves(board)
expect(moves).to match_array([
[5, 6], [6, 5], [6, 3], [5, 2], [2, 5], [3, 6]
])
end
end
end
end
|
Python
|
UTF-8
| 3,241
| 3.15625
| 3
|
[] |
no_license
|
import pygame
from threading import Thread
from time import clock
from core.bullet import Bullet
from core.player import Player
from color.chord import Note
class Game:
def __init__(self, width=500, height=500):
pygame.init()
self.window = pygame.display.set_mode((width, height))
self.graphics_loop_running = False
self.game_running = False
self.bullets = []
self.player = Player(250, 250, 0, 0)
def quit(self):
while self.graphics_loop_running:
pass
pygame.quit()
def play(self):
gu_thread = Thread(target=self.graphics_update_loop)
self.game_running = True
gu_thread.start()
while self.game_running:
event = pygame.event.wait()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
self.shoot(event.pos)
elif event.type == pygame.KEYDOWN:
if event.key == 119: # W
self.player.w_down = True
elif event.key == 97: # A
self.player.a_down = True
elif event.key == 115: # S
self.player.s_down = True
elif event.key == 100: # D
self.player.d_down = True
else:
print(event)
elif event.type == pygame.KEYUP:
if event.key == 119: # W
self.player.w_down = False
elif event.key == 97: # A
self.player.a_down = False
elif event.key == 115: # S
self.player.s_down = False
elif event.key == 100: # D
self.player.d_down = False
else:
print(event)
elif event.type == pygame.QUIT:
self.game_running = False
#else:
#print(event)
self.quit()
def shoot(self, pos):
self.bullets.append(Bullet(self.player, pos[0], pos[1], 1, 360))
def tick(self):
cleanup = []
for bullet in self.bullets:
bullet.tick()
if bullet.needs_cleanup:
cleanup.append(bullet)
self.player.tick()
for bullet in cleanup:
self.bullets.remove(bullet)
def graphics_update_loop(self):
seconds_per_frame = 1/30
next_update = clock() + seconds_per_frame
self.graphics_loop_running = True
while self.game_running:
while clock() < next_update:
pass
self.tick()
self.update()
next_update += seconds_per_frame
self.graphics_loop_running = False
def update(self):
self.window.fill((0,0,0))
baseLight = Note(1) * 500000
for bullet in self.bullets:
dist = self.player.distance(bullet)
if dist == 0:
light = 255
else:
light = min(255, (baseLight / (dist ** 2)).notes[1])
pygame.draw.circle(self.window, (light,light,light), bullet.position, 0, 0)
pygame.draw.circle(self.window, (255,0,0), self.player.position, 3, 0)
pygame.display.flip()
|
C
|
UTF-8
| 420
| 2.515625
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char data[12][12];
void swap (int n)
{
srand(time(NULL));
do
{
int times=88;
int i,j,i1,j1;
char t;
while (times--)
{
i=rand()%n+1;
j=rand()%n+1;
i1=rand()%n+1;
j1=rand()%n+1;
t=data[i][j];
data[i][j]=data[i1][j1];
data[i1][j1]=t;
}
}while(noclear(n));
}
|
Java
|
UTF-8
| 1,285
| 2.703125
| 3
|
[] |
no_license
|
package cn.maycope.util;
/**
* @Author Maycope
* @Date 2020/8/21
* @Version 1.0
*/
public enum ResultCode {
SUCCESS(2000,"ๆๅ"),
FAIL(5001,"ๅคฑ่ดฅ"),
RESULE_DATA_NONE(5002, "ๆฐๆฎๆชๆพๅฐ"),
ID_IS_ERROR(5003,"idๆ่ฏฏ"),
ARTICLE_IS_ERROR(5004,"ๆ็ซ ไธๅญๅจ"),
NAME_OR_TITLED_D(5005,"ๆ็ซ ๅ็งฐๆๅ
ๅฎนไธๅญๅจ"),
ARTICLE_IS_TRUE(5006,"ๆ็ซ ๅทฒ็ปๅญๅจ๏ผ่ฏทๅฟ้ๅคๆไบค"),
INSERT_SUCCESS(2001,"ๆ็ซ ๆๅ
ฅๆๅ"),
UPDATE_SUCCESS(2002,"ๆ็ซ ไฟฎๆนๆๅ");
private Integer code;
private String message;
ResultCode(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer code() {
return this.code;
}
public String message() {
return this.message;
}
public static String getMessage(String name) {
for (ResultCode item : ResultCode.values()) {
if (item.name().equals(name)) {
return item.message;
}
}
return name;
}
public static Integer getCode(String name) {
for (ResultCode item : ResultCode.values()) {
if (item.name().equals(name)) {
return item.code;
}
}
return null;
}
}
|
C++
|
UTF-8
| 11,450
| 3.25
| 3
|
[] |
no_license
|
#include "test.hpp"
void test_set(){
std::set<std::string> m;
ft::set<std::string> ft_m;
std::cout << "*Check empty (empty)*\n";
if (m.empty() == ft_m.empty())
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
std::cout << m.empty() << "!=" << ft_m.empty() << RESET << std::endl;
}
std::cout << "*Check max_size*\n";
if (m.max_size() == ft_m.max_size())
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
std::cout << m.max_size() << "!=" << ft_m.max_size() << RESET << std::endl;
}
std::pair<std::set<std::string>::iterator, bool> p = m.insert("abc");
std::pair<ft::set<std::string>::iterator, bool> ft_p = ft_m.insert("abc");
std::cout << "*Check insert return value (success)*\n";
if (*(p.first) == *(ft_p.first))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
std::cout << GREEN << "value: " << *(p.first) << "\t" << "bool: " << std::boolalpha << p.second << std::endl;
std::cout << RED << "value: " << *(ft_p.first) << "\t" << "bool: " << std::boolalpha << ft_p.second << std::endl;
}
p = m.insert("abc");
ft_p = ft_m.insert("abc");
std::cout << "*Check insert return value (fail)*\n";
if (*(p.first) == *(ft_p.first))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
std::cout << GREEN << "value: " << *(p.first) << "\t" << "bool: " << std::boolalpha << p.second << std::endl;
std::cout << RED << "value: " << *(ft_p.first) << "\t" << "bool: " << std::boolalpha << ft_p.second << std::endl;
}
p = m.insert("foo");
p = m.insert("def");
p = m.insert("xyz");
p = m.insert("chebubu");
p = m.insert("bar");
ft_p = ft_m.insert("foo");
ft_p = ft_m.insert("def");
ft_p = ft_m.insert("xyz");
ft_p = ft_m.insert("chebubu");
ft_p = ft_m.insert("bar");
std::cout << "*Check size*\n";
if (m.size() == ft_m.size())
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
std::cout << m.size() << "!=" << ft_m.size() << RESET << std::endl;
}
std::cout << "*Check empty (not empty)*\n";
if (m.empty() == ft_m.empty())
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
std::cout << m.empty() << "!=" << ft_m.empty() << RESET << std::endl;
}
std::cout << "*Check insert (single)*\n";
std::set<std::string>::iterator it = m.begin();
ft::set<std::string>::iterator ft_it = ft_m.begin();
for (; it != m.end(); it++, ft_it++){
if (*it != *ft_it)
std::cout << RED << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
else
std::cout << GREEN << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
}
std::cout << "*Check reverse iterator*\n";
std::set<std::string>::reverse_iterator rit = m.rbegin();
ft::set<std::string>::reverse_iterator ft_rit = ft_m.rbegin();
for (; rit != m.rend(); rit++, ft_rit++){
if (*rit != *ft_rit)
std::cout << RED << "value: " << std::setw(10) << *rit << std::setw(10) << "value: " << *ft_rit << RESET << std::endl;
else
std::cout << GREEN << "value: " << std::setw(10) << *rit << std::setw(10) << "value: " << *ft_rit << RESET << std::endl;
}
std::cout << "*Check from tail to head*\n";
it = m.end();
ft_it = ft_m.end();
it--;
ft_it--;
for (; it != m.begin(); it--, ft_it--){
if (*it != *ft_it)
std::cout << RED << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
else
std::cout << GREEN << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
}
std::cout << "*Check erase(iterator)*\n";
m.erase(((--(--((m.end()))))));
ft_m.erase(((--(--((ft_m.end()))))));
it = m.begin();
ft_it = ft_m.begin();
for (; ft_it != ft_m.end(); it++, ft_it++){
if (*it != *ft_it)
std::cout << RED << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
else
std::cout << GREEN << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
}
std::cout << "*Check erase(value)*\n";
m.erase("chebubu");
ft_m.erase("chebubu");
it = m.begin();
ft_it = ft_m.begin();
for (; ft_it != ft_m.end(); it++, ft_it++){
if (*it != *ft_it)
std::cout << RED << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
else
std::cout << GREEN << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
}
std::cout << "*Check erase(value not found)*\n";
m.erase("chebubu");
ft_m.erase("chebubu");
it = m.begin();
ft_it = ft_m.begin();
for (; ft_it != ft_m.end(); it++, ft_it++){
if (*it != *ft_it)
std::cout << RED << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
else
std::cout << GREEN << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
}
std::cout << "*Check erase(range)*\n";
m.erase(--(--(--m.end())), --m.end());
ft_m.erase(--(--(--ft_m.end())), --ft_m.end());
it = m.begin();
ft_it = ft_m.begin();
for (; it != m.end(); it++, ft_it++){
if (*it != *ft_it)
std::cout << RED << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
else
std::cout << GREEN << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
}
std::cout << "*Check swap*\n";
std::set<std::string> s;
ft::set<std::string> ft_s;
s.insert("kuku");
s.insert("nya");
s.insert("meow");
ft_s.insert("kuku");
ft_s.insert("nya");
ft_s.insert("meow");
std::swap(m, s);
ft::swap(ft_m, ft_s);
it = m.begin();
ft_it = ft_m.begin();
for (; it != m.end(); it++, ft_it++){
if (*it != *ft_it)
std::cout << RED << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
else
std::cout << GREEN << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
}
std::cout << "*Check swap (second container)*\n";
it = s.begin();
ft_it = ft_s.begin();
for (; it != s.end(); it++, ft_it++){
if (*it != *ft_it)
std::cout << RED << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
else
std::cout << GREEN << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
}
std::cout << "*Check copy contructor*\n";
std::set<std::string> c(m);
ft::set<std::string> ft_c(ft_m);
it = c.begin();
ft_it = ft_c.begin();
for (; it != c.end(); it++, ft_it++){
if (*it != *ft_it)
std::cout << RED << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
else
std::cout << GREEN << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
}
std::cout << "*Check insert with hint*\n";
c.insert(c.begin(), "allo");
ft_c.insert(ft_c.begin(), "allo");
it = c.begin();
ft_it = ft_c.begin();
for (; it != c.end(); it++, ft_it++){
if (*it != *ft_it)
std::cout << RED << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
else
std::cout << GREEN << "value: " << std::setw(10) << *it << std::setw(10) << "value: " << *ft_it << RESET << std::endl;
}
std::cout << "*Check find*\n";
if (*(c.find("allo")) == *(ft_c.find("allo")))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
std::cout << GREEN << *(c.find("allo")) << '\t' << RED << *(ft_c.find("allo")) << RESET << std::endl;
}
std::cout << "*Check count*\n";
if (c.count("allo") == ft_c.count("allo"))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
std::cout << GREEN << c.count("allo") << "\t" << RED << ft_c.count("allo") << RESET << std::endl;
}
if (c.count("allah") == ft_c.count("allah"))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
std::cout << GREEN << c.count("allah") << "\t" << RED << ft_c.count("allah") << RESET << std::endl;
}
std::cout << "*Check lower bound*\n";
if (*(c.lower_bound("kuku")) == *(ft_c.lower_bound("kuku")))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
std::cout << GREEN << *(c.lower_bound("allo")) << "\t" << RED << *(ft_c.lower_bound("allo")) << RESET << std::endl;
}
std::cout << "*Check upper bound*\n";
if (*(c.upper_bound("meow")) == *(ft_c.upper_bound("meow")))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
std::cout << GREEN << *(c.upper_bound("meow")) << "\t" << RED << *(ft_c.upper_bound("meow")) << RESET << std::endl;
}
std::cout << "*Check equal range*\n";
if (*(c.equal_range("meow").first) == *(ft_c.equal_range("meow").first) && *(c.equal_range("meow").second) == *(ft_c.equal_range("meow").second))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
std::cout << GREEN << *(c.equal_range("meow").first) << "\t" << RED << *(ft_c.equal_range("meow").first) << RESET << std::endl;
std::cout << GREEN << *(c.equal_range("meow").second) << "\t" << RED << *(ft_c.equal_range("meow").second) << RESET << std::endl;
}
if ((s == m) == (ft_s == ft_m))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
}
if ((s == c) == (ft_s == ft_c))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
}
std::cout << "*Check operator!=*\n";
if ((s != m) == (ft_s != ft_m))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
}
if ((s != c) == (ft_s != ft_c))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
}
std::cout << "*Check operator<*\n";
if ((s < m) == (ft_s < ft_m))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
}
if ((s < c) == (ft_s < ft_c))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
}
std::cout << "*Check operator>*\n";
if ((s > m) == (ft_s > ft_m))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
}
if ((s > c) == (ft_s > ft_c))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
}
std::cout << "*Check operator>=*\n";
if ((s >= m) == (ft_s >= ft_m))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
}
if ((s >= c) == (ft_s >= ft_c))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
}
std::cout << "*Check operator<=*\n";
if ((s <= m) == (ft_s <= ft_m))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
}
if ((s <= c) == (ft_s <= ft_c))
std::cout << GREEN << "OK" << RESET << std::endl;
else
{
std::cout << RED << "KO" << std::endl;
}
}
|
JavaScript
|
UTF-8
| 671
| 2.578125
| 3
|
[] |
no_license
|
import React, { createContext } from 'react';
const Context = createContext({
city: 'Kharkiv',
updateCity: () => {},
coord: [],
updateCoord: () => {},
});
export class UserProvider extends React.Component {
updateCity = newCity => {
this.setState({ city: newCity });
};
updateCoord = newCoord => {
this.setState({coord: newCoord});
};
state = {
city: 'Kharkiv',
updateCity: this.updateCity,
coord: [],
updateCoord: this.updateCoord
};
render() {
return (
<Context.Provider value={this.state}>
{this.props.children}
</Context.Provider>
);
}
}
export const UserConsumer = Context.Consumer;
|
Markdown
|
UTF-8
| 2,272
| 3.21875
| 3
|
[] |
no_license
|
๏ปฟ---
title: vue่ทฏ็ฑ็ๅฎ็ฐๅ็
date: '4/1/2019 11:15:15 AM '
tag: ['js', 'vue-router', 'vue']
meta:
-
name: description
content: null
-
name: keywords
content: null
---
## vue่ทฏ็ฑ็ๅฎ็ฐๅ็
> ๅจvueไธญ่ทฏ็ฑไธป่ฆๆ hashไธHistory interfaceไธค็งๆนๅผๅฎ็ฐๅ็ซฏ่ทฏ็ฑ๏ผๅ้กต่ทฏ็ฑ็็น็นๅฐฑๆฏ้็จๅ็ซฏ่ทฏ็ฑ็ณป็ป๏ผ้่ฟๆนๅURL๏ผๅจไธ้ๆฐ่ฏทๆฑ้กต้ข็ๆ
ๅตไธ๏ผๆดๆฐ้กต้ข่งๅพใ็ฎๅๅจๆต่งๅจ็ฏๅขไธญ่ฟไธๅ่ฝ็ๅฎ็ฐไธป่ฆๆไธค็งๆนๅผ
### hash
> ๅจๆต่งๅจ็urlไธญhash๏ผโ#โ๏ผ็ฌฆๅท็ๆฌๆฅไฝ็จๆฏๅ ๅจURLไธญๆ็คบ็ฝ้กตไธญ็ไฝ็ฝฎ๏ผ#็ฌฆๅทๆฌ่บซไปฅๅๅฎๅ้ข็ๅญ็ฌฆ็งฐไนไธบhash๏ผๅฏ้่ฟwindow.location.hashๅฑๆง่ฏปๅใ
#### ็น็น๏ผ
> hash่ฝ็ถๅบ็ฐๅจURLไธญ๏ผไฝไธไผ่ขซๅ
ๆฌๅจHTTP่ฏทๆฑไธญใๅฎๆฏ็จๆฅๆๅฏผๆต่งๅจๅจไฝ็๏ผๅฏนๆๅกๅจ็ซฏๅฎๅ
จๆ ็จ๏ผๅ ๆญค๏ผๆนๅhashไธไผ้ๆฐๅ ่ฝฝ้กต้ข๏ผๅนถไธๅฏไปฅไธบhash็ๆนๅๆทปๅ hashchange็ๅฌไบไปถ๏ผๅจไธไธชๅฐฑๆฏๆฏไธๆฌกๆนๅhash๏ผwindow.location.hash๏ผ๏ผ้ฝไผๅจๆต่งๅจ็่ฎฟ้ฎๅๅฒไธญๅขๅ ไธไธช่ฎฐๅฝ๏ผๆๅฐฑๅฏไปฅ้่ฟไป็่ฟๅ ไธช็น็นๅฎ็ฐไธไธชhashๆจกๅผ็ๅ้กต่ทฏ็ฑ๏ผ้่ฟๅฏนlocation.hash็ไฟฎๆนๅฎ็ฐpushๆนๆณ๏ผ่ทณ่ฝฌ้กต้ข๏ผ๏ผ้่ฟๅฏนlocation.href็ไฟฎๆนๅฎ็ฐreplace()ๆนๆณ๏ผ้่ฟๅฏนhashchangeไบไปถ็็ๅฌๅฎ็ฐ้กต้ข่ทณ่ฝฌๅ็ๆฐๆฎๆดๆฐ
### History
> Historyๆจกๅผๅๆฏๅฎๅ
จ้็จไบh5็ๆฐ็นๆง๏ผไปHTML5ๅผๅง๏ผHistory interfaceๆไพไบไธคไธชๆฐ็ๆนๆณ๏ผpushState(), replaceState()ไฝฟๅพๆไปฌๅฏไปฅๅฏนๆต่งๅจๅๅฒ่ฎฐๅฝๆ ่ฟ่กไฟฎๆน๏ผไปฅๅpopStateไบไปถๅฏไปฅ็ๅฌๅฐ็ถๆ็ๅๆด
**ไธ่ฟhistoryๆจกๅผๆไธไธช้ฎ้ขๅฐฑๆฏ**
> ๅฏนไบๅ้กตๅบ็จๆฅ่ฎฒ๏ผ็ๆณ็ไฝฟ็จๅบๆฏๆฏไป
ๅจ่ฟๅ
ฅๅบ็จๆถๅ ่ฝฝindex.html๏ผๅ็ปญๅจ็็ฝ็ปๆไฝ้่ฟAjaxๅฎๆ๏ผไธไผๆ นๆฎURL้ๆฐ่ฏทๆฑ้กต้ข๏ผไฝๆฏๅฆๆ็จๆท็ดๆฅๅจๅฐๅๆ ไธญ่พๅ
ฅๅนถๅ่ฝฆ๏ผๆต่งๅจ้ๅฏ้ๆฐๅ ่ฝฝ็ๆถๅhistoryๆจกๅผๅไผๅฐURLไฟฎๆนๅพๅฐฑๅๆญฃๅธธ่ฏทๆฑๅ็ซฏ็URLไธๆ ท๏ผๅจๆญคๆ
ๅตไธ้ๆฐๅๅ็ซฏๅ้่ฏทๆฑ๏ผๅฆๅ็ซฏๆฒกๆ้
็ฝฎๅฏนๅบ ็่ทฏ็ฑๅค็๏ผๅไผ่ฟๅ404้่ฏฏใ่ฟ็ง้ฎ้ข็่งฃๅณ๏ผไธ่ฌๆ
ๅตไธๆไปฌ้ฝๆฏๅจๅ็ซฏ่ฟ่ก้
็ฝฎ๏ผๅฐๆๆ็่ทฏ็ฑ่ฏทๆฑ้ฝๆๅindex.htmlๆไปถ
|
C++
|
UTF-8
| 927
| 3.0625
| 3
|
[] |
no_license
|
#pragma once
#include<vector>
#include<array>
#include<sstream>
#include<glm/glm.hpp>
class Mesh
{
typedef std::array<int, 3> face;
std::vector<glm::vec3> vtxs_;
std::vector<face> faces_;
std::vector<glm::vec4> planes_;
std::vector<glm::vec3> vtx_normals_;
void compute_planes();
void compute_vtx_normals();
public:
Mesh(std::vector<glm::vec3> vtxs, std::vector<face> faces);
~Mesh() = default;
Mesh normalize();
std::string as_obj();
static Mesh from_stream(std::istream& is);
std::array<glm::vec3, 3> get_vertices_for_face(face face) const;
//Operators
Mesh(const Mesh& other) = default;
Mesh(Mesh&& other) noexcept;
Mesh& operator=(const Mesh& other);
Mesh& operator=(Mesh&& other) noexcept;
//Getters
const std::vector<glm::vec3>& vtxs() const;
const std::vector<face>& faces() const;
const std::vector<glm::vec3>& vtx_normals() const;
const std::vector<glm::vec4>& planes() const;
};
|
Java
|
UTF-8
| 290
| 1.617188
| 2
|
[] |
no_license
|
package tam.rentalcars.repository.mongo;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import tam.rentalcars.model.Color;
@Repository
public interface ColorRepositoryMongo extends MongoRepository<Color, String> {
}
|
PHP
|
UTF-8
| 1,406
| 3.328125
| 3
|
[] |
no_license
|
<!DOCTYPE html>
<html>
<body>
<!-- using POST
-->
<?php
$nameErr = $phoneErr= $commentErr = "";
$name = $phone = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
}
else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "only letters and white space allowed";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "a number is required";
}
else {
$phone = test_input($_POST["phone"]);
if (!preg_match("/^[0-9]*$/",$phone)) {
$phoneErr = "only numbers allowed";
}
}
if (empty($_POST["comment"])) {
$comment = "";
}
else {
$comment = test_input($_POST["name"]);
}
}
?>
<form action ="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method ="post">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?> </span> <br>
<br>
Phone #: <input type="text" name="phone">
<span class="error">* <?php echo $phoneErr;?> </span> <br>
<br>
Comment: <input type="textbox" name="comment">
<span class="error">* <?php echo $commentErr;?> </span> <br>
<br>
<input type="submit">
<br>
</form>
<?php
echo $_POST["name"];
echo $_POST["phone"];
echo $_POST["comment"];
?>
<?php
function test_input($data) {
$data = trim($data);
$data = stripcslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</body>
</html>
|
C#
|
UTF-8
| 12,866
| 3.171875
| 3
|
[
"Apache-2.0"
] |
permissive
|
๏ปฟusing Neko.Utility.Core.IO.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
namespace Neko.Utility.Core.Data
{
/// <summary>
/// ๅญ็ฌฆไธฒๅธฎๅฉ็ฑป
/// <para>ๅฏไปฅๅฏนๅญ็ฌฆไธฒ่ฟ่กไธไบๅฟซ้ๆไฝ</para>
/// </summary>
public sealed class StringUtil
{
/// <summary>
/// ๅคๆญไธไธชๅฏน่ฑกๆฏๅฆไธบ็ฉบ
/// </summary>
/// <param name="value">่ฆๅคๆญ็ๅฏน่ฑก</param>
/// <returns></returns>
public static bool IsNullOrEmpty(object value)
{
return value == null || string.IsNullOrEmpty(value.ToString()) || string.IsNullOrWhiteSpace(value.ToString());
}
/// <summary>
/// ๅฏนๆฏไธคไธช็ฑปๅ
/// </summary>
/// <param name="fromType">่ฆๅฏนๆฏ็็ฑปๅ1</param>
/// <param name="typeName">่ฆๅฏนๆฏ็็ฑปๅ2็็ฑปๅๅ็งฐ<see cref="Type.FullName"/></param>
/// <returns></returns>
public static bool CompareType(Type fromType, string typeName)
{
if (fromType == null)
{
return false;
}
else if (fromType.ToString() == typeName || fromType.Name == typeName)
{
return true;
}
else if (fromType.ToString() == "System.Object" || fromType.Name == "Object")
{
return false;
}
else
{
return CompareType(fromType.BaseType, typeName);
}
}
/// <summary>
/// ๅฏนๆฏไธคไธช็ฑปๅ
/// </summary>
/// <param name="fromType">่ฆๅฏนๆฏ็็ฑปๅ1</param>
/// <param name="toType">่ฆๅฏนๆฏ็็ฑปๅ2</param>
/// <returns></returns>
public static bool CompareType(Type fromType, Type toType)
{
return CompareType(fromType, toType.ToString());
}
/// <summary>
/// ๆฏ่พไธคไธชๅฏน่ฑกๆฏๅฆ็ธ็ญ
/// </summary>
/// <param name="fromValue">่ฆๆฏ่พ็ๅฏน่ฑก1</param>
/// <param name="toValue">่ฆๆฏ่พ็ๅฏน่ฑก2</param>
/// <returns></returns>
public static bool SafeCompare(object fromValue, object toValue)
{
return SafeCompare(fromValue, toValue, false);
}
/// <summary>
/// ๆฏ่พไธคไธชๅญ็ฌฆไธฒๆฏๅฆ็ธ็ญ
/// </summary>
/// <param name="fromValue">่ฆๆฏ่พ็ๅญ็ฌฆไธฒ1</param>
/// <param name="toValue">่ฆๆฏ่พ็ๅญ็ฌฆไธฒ2</param>
/// <returns></returns>
public static bool SafeCompare(string fromValue, string toValue)
{
return SafeCompare(fromValue, toValue, false);
}
/// <summary>
/// ๆฏ่พไธคไธชๅฏน่ฑกๆฏๅฆ็ธ็ญ
/// <para>ๅฐไผๆไธคไธชๅฏน่ฑก่ฝฌๆขไธบๅญ็ฌฆไธฒ<see cref="Object.ToString()"/>ๆฅ่ฟ่กๆฏ่พ</para>
/// </summary>
/// <param name="fromValue">่ฆๆฏ่พ็ๅฏน่ฑก1</param>
/// <param name="toValue">่ฆๆฏ่พ็ๅฏน่ฑก2</param>
/// <param name="ignoreCase">ๆฏๅฆๅฟฝ็ฅๅคงๅฐๅ</param>
/// <returns></returns>
public static bool SafeCompare(object fromValue, object toValue, bool ignoreCase)
{
string fromStr = string.Empty, toStr = string.Empty;
if (fromValue != null)
{
fromStr = fromValue.ToString();
}
if (toValue != null)
{
toStr = toValue.ToString();
}
return SafeCompare(fromStr, toStr, ignoreCase);
}
/// <summary>
/// ๆฏ่พไธคไธชๅญ็ฌฆไธฒๆฏๅฆ็ธ็ญ
/// </summary>
/// <param name="fromValue">่ฆๆฏ่พ็ๅญ็ฌฆไธฒ1</param>
/// <param name="toValue">่ฆๆฏ่พ็ๅญ็ฌฆไธฒ2</param>
/// <param name="ignoreCase">ๆฏๅฆๅฟฝ็ฅๅคงๅฐๅ</param>
/// <returns></returns>
public static bool SafeCompare(string fromValue, string toValue, bool ignoreCase)
{
return !IsNullOrEmpty(fromValue) && !IsNullOrEmpty(toValue) && fromValue.Length == toValue.Length && (string.Compare(fromValue, toValue, ignoreCase, System.Globalization.CultureInfo.InvariantCulture) == 0);
}
/// <summary>
/// ่ทๅๅฝๅUTCๆถ้ด็ๅไธไฝ็Unixๆถ้ดๆณ
/// </summary>
/// <returns></returns>
public static string GetTimeStamp()
{
return GetTimeStamp(DateTime.UtcNow);
}
/// <summary>
/// ่ทๅๆๅฎๆถ้ด็ๅไธไฝ็Unixๆถ้ดๆณ
/// </summary>
/// <param name="time">่ฆ่ทๅๆถ้ดๆณ็ๆถ้ด</param>
/// <returns></returns>
public static string GetTimeStamp(DateTime time)
{
TimeSpan span = time - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(span.TotalSeconds * 1000).ToString();
}
/// <summary>
/// ๅฐๅไธไฝ็Unixๆถ้ดๆณ่ฝฌๆขไธบๆฅๆๆถ้ด
/// </summary>
/// <param name="timeStamp">่ฆ่ฝฌๆข็Unixๆถ้ดๆณ</param>
/// <returns></returns>
public static DateTime GetTimeStamp(string timeStamp)
{
DateTime result = DateTime.MinValue;
try
{
long unixDate = Convert.ToInt64(timeStamp);
DateTime utcStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
result = utcStart.AddMilliseconds(unixDate).ToLocalTime();
}
catch (Exception ex)
{
throw ex;
}
return result;
}
/// <summary>
/// ๅฐๅฏน่ฑก่ฝฌๆขไธบ็นๅฎ็ฑปๅ็ๆ ผๅผ
/// <list type="bullet">
/// <item>่ฝฌๆขๅคฑ่ดฅๅฐ่ฟๅ็ฑปๅ็้ป่ฎคๅผ</item>
/// <item>ๆ ๆณ่ฝฌๆขๅฐ่ฟๅๅฏน่ฑกๆฌ่บซ</item>
/// </list>
/// </summary>
/// <param name="targetType">ๆๅฎ็็ฑปๅ</param>
/// <param name="value">่ฆ่ฝฌๆข็ๅฏน่ฑก</param>
/// <returns></returns>
public static object Get(Type targetType, object value)
{
return InternalGet(targetType, value);
}
/// <summary>
/// ๅฐๅฏน่ฑก่ฝฌๆขไธบ็นๅฎ็ฑปๅ็ๆ ผๅผ
/// <list type="bullet">
/// <item>่ฝฌๆขๅคฑ่ดฅๅฐ่ฟๅ็ฑปๅ็้ป่ฎคๅผ</item>
/// <item>ๆ ๆณ่ฝฌๆขๅฐ่ฟๅๅฏน่ฑกๆฌ่บซ</item>
/// </list>
/// </summary>
/// <typeparam name="TObject">ๆๅฎ็็ฑปๅ</typeparam>
/// <param name="value">่ฆ่ฝฌๆข็ๅฏน่ฑก</param>
/// <returns></returns>
public static TObject Get<TObject>(object value)
{
return (TObject)Get(typeof(TObject), value);
}
/// <summary>
/// ๅฐๅฏน่ฑก่ฝฌๆขไธบ<see cref="string"/>็ฑปๅ
/// </summary>
/// <param name="value">่ฆ่ฝฌๆข็ๅฏน่ฑก</param>
/// <returns></returns>
public static string GetString(object value)
{
value = ObjectUtil.Get(value);
return value == null ? string.Empty : value.ToString();
}
/// <summary>
/// ๅฐๅฏน่ฑก่ฝฌๆขไธบ<see cref="bool"/>็ฑปๅ
/// </summary>
/// <param name="value">่ฆ่ฝฌๆข็ๅฏน่ฑก</param>
/// <returns></returns>
public static bool GetBoolean(object value)
{
return GetBoolean(value, false);
}
/// <summary>
/// ๅฐๅฏน่ฑก่ฝฌๆขไธบ<see cref="bool"/>็ฑปๅ
/// </summary>
/// <param name="value">่ฆ่ฝฌๆข็ๅฏน่ฑก</param>
/// <param name="defaultValue">่ฝฌๆขๅคฑ่ดฅๆถ่ฟๅ็้ป่ฎคๅผ</param>
/// <returns></returns>
public static bool GetBoolean(object value, bool defaultValue)
{
bool result = defaultValue;
try
{
if (!IsNullOrEmpty(value))
{
result = !SafeCompare(value, "0", true) && !SafeCompare(value, "false", true) && !SafeCompare(value, "f", true) && !SafeCompare(value, "no", true) && !SafeCompare(value, "n", true) && !SafeCompare(value, "ๅฆ", true) && !SafeCompare(value, "้", true) && !SafeCompare(value, "้่ฏฏ", true) && !SafeCompare(value, "ไธ", true) && !SafeCompare(value, "ไธๆฏ", true) && !IsNullOrEmpty(value);
}
}
catch (Exception ex)
{
throw ex;
}
return result;
}
/// <summary>
/// ๅฐๅฏน่ฑก่ฝฌๆขไธบ<see cref="int"/>็ฑปๅ
/// </summary>
/// <param name="value">่ฆ่ฝฌๆข็ๅฏน่ฑก</param>
/// <returns></returns>
public static int GetInt(object value)
{
return InternalGet<int>(value);
}
/// <summary>
/// ๅฐๅฏน่ฑก่ฝฌๆขไธบ<see cref="DateTime"/>็ฑปๅ
/// </summary>
/// <param name="value">่ฆ่ฝฌๆข็ๅฏน่ฑก</param>
/// <returns></returns>
public static DateTime? GetDateTime(object value)
{
DateTime? result = null;
if (IsNullOrEmpty(value))
{
return result;
}
if(value is DateTime || value is DateTime?)
{
result = (DateTime)value;
}
if(result == null)
{
string valueString = GetString(value);
if (!IsNullOrEmpty(valueString))
{
if(DateTime.TryParse(valueString,out DateTime parseResult))
{
result = parseResult;
}
}
}
return result;
}
/// <summary>
/// ๅฐๅฏน่ฑก่ฝฌๆขไธบ<see cref="double"/>็ฑปๅ
/// </summary>
/// <param name="value">่ฆ่ฝฌๆข็ๅฏน่ฑก</param>
/// <returns></returns>
public static double GetDouble(object value)
{
return InternalGet<double>(value);
}
/// <summary>
/// ๅฐๅฏน่ฑก่ฝฌๆขไธบ<see cref="decimal"/>็ฑปๅ
/// </summary>
/// <param name="value">่ฆ่ฝฌๆข็ๅฏน่ฑก</param>
/// <returns></returns>
public static decimal GetDecimal(object value)
{
return InternalGet<decimal>(value);
}
internal static Tvalue InternalGet<Tvalue>(object value)
{
Tvalue result = default(Tvalue);
try
{
if (!IsNullOrEmpty(value))
{
if (value.GetType().GetInterface(nameof(IConvertible)) != null)
{
result = (Tvalue)Convert.ChangeType(value, typeof(Tvalue));
}
else
{
result = (Tvalue)value;
}
}
}
catch (Exception ex)
{
throw ex;
}
return result;
}
internal static object InternalGet(Type targetType, object value)
{
object result = null;
//ๆ นๆฎ็ฑปๅ่ฐ็จๅฏนๅบ็ๆนๆณ่ฝฌๆขๆฐๆฎ
if (targetType.IsEnum)
{
string valueStr = GetString(value);
result = EnumUtil.Convert(targetType, valueStr);
}
else if (CompareType(targetType, typeof(string)))
{
result = GetString(value);
}
else if (CompareType(targetType, typeof(bool)))
{
string valueStr = GetString(value);
result = GetBoolean(valueStr);
}
else if (CompareType(targetType, typeof(int)))
{
result = GetInt(value);
}
else if (CompareType(targetType, typeof(double)))
{
result = GetDouble(value);
}
else if (CompareType(targetType, typeof(decimal)))
{
result = GetDecimal(value);
}
else if (CompareType(targetType, typeof(DateTime)) || CompareType(targetType, typeof(DateTime?)))
{
result = GetDateTime(value);
}
else if (targetType.IsClass && value is JObject) //ๅฆๆ่ฝฌๆข็็ฑปๅๆฏClassๅนถไธๆฏJObject็ฑปๅ,ๅ
ๅฐๆฅๆบๅฏน่ฑกๅบๅๅไธบJsonๅญ็ฌฆไธฒ๏ผ็ถๅๅๅๅบๅๅไธบ่ฆ่ฝฌๆข็็ฑปๅ
{
result = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(value), targetType);
}
else //ๅฆๆ้ฝไธๆฏไธ้ข็็ฑปๅ๏ผๅ่ฟๅๅฏน่ฑกๆฌ่บซ
{
result = value;
}
return result;
}
}
}
|
Python
|
UTF-8
| 6,063
| 2.828125
| 3
|
[] |
no_license
|
from produtos.classes.Produtos import Pepsi
from produtos.classes.Produtos import CocaCola
from produtos.classes.Produtos import Dolly
from produtos.classes.Produtos import GuaranaAntartica
from produtos.classes.Caracteristicas import Caracteristicas
from produtos.classes.Caracteristicas import Tamanho600ml
from produtos.classes.Caracteristicas import Tamanho1litro
from produtos.classes.Caracteristicas import Tamanho2litros
from produtos.classes.Caracteristicas import Tamanho3litros
import pytest
class TestCaracteristicas:
def test_Pepsi_600ml(self):
msg = 'Pepsi tamanho: 600ml.'
caracteristica = Tamanho600ml()
objeto = Pepsi(caracteristica)
assert isinstance(caracteristica, Caracteristicas)
assert isinstance(caracteristica, Tamanho600ml)
assert objeto.operation() == msg
def test_Pepsi_1_litro(self):
msg = 'Pepsi tamanho: 1 litro.'
caracteristica = Tamanho1litro()
objeto = Pepsi(caracteristica)
assert isinstance(caracteristica, Caracteristicas)
assert isinstance(caracteristica, Tamanho1litro)
assert objeto.operation() == msg
def test_Pepsi_2_litros(self):
msg = 'Pepsi tamanho: 2 litros.'
caracteristica = Tamanho2litros()
objeto = Pepsi(caracteristica)
assert isinstance(caracteristica, Caracteristicas)
assert isinstance(caracteristica, Tamanho2litros)
assert objeto.operation() == msg
def test_Pepsi_3_litros(self):
msg = 'Pepsi tamanho: 3 litros.'
caracteristica = Tamanho3litros()
objeto = Pepsi(caracteristica)
assert isinstance(caracteristica, Caracteristicas)
assert isinstance(caracteristica, Tamanho3litros)
assert objeto.operation() == msg
def test_CocaCola_600ml(self):
msg = 'CocaCola tamanho: 600ml.'
caracteristicas = Tamanho600ml()
objeto = CocaCola(caracteristicas)
assert isinstance(caracteristicas, Caracteristicas)
assert isinstance(caracteristicas, Tamanho600ml)
assert objeto.operation() == msg
def test_CocaCola_1_litro(self):
msg = 'CocaCola tamanho: 1 litro.'
caracteristicas = Tamanho1litro()
objeto = CocaCola(caracteristicas)
assert isinstance(caracteristicas, Caracteristicas)
assert isinstance(caracteristicas, Tamanho1litro)
assert objeto.operation() == msg
def test_CocaCola_2_litros(self):
msg = 'CocaCola tamanho: 2 litros.'
caracteristicas = Tamanho2litros()
objeto = CocaCola(caracteristicas)
assert isinstance(caracteristicas, Caracteristicas)
assert isinstance(caracteristicas, Tamanho2litros)
assert objeto.operation() == msg
def test_CocaCola_3_litros(self):
msg = 'CocaCola tamanho: 3 litros.'
caracteristicas = Tamanho3litros()
objeto = CocaCola(caracteristicas)
assert isinstance(caracteristicas, Caracteristicas)
assert isinstance(caracteristicas, Tamanho3litros)
assert objeto.operation() == msg
def test_Dolly_600ml(self):
msg = 'Dolly tamanho: 600ml.'
caracteristicas = Tamanho600ml()
objeto = Dolly(caracteristicas)
assert isinstance(caracteristicas, Caracteristicas)
assert isinstance(caracteristicas, Tamanho600ml)
assert objeto.operation() == msg
def test_Dolly_1_litro(self):
msg = 'Dolly tamanho: 1 litro.'
caracteristicas = Tamanho1litro()
objeto = Dolly(caracteristicas)
assert isinstance(caracteristicas, Caracteristicas)
assert isinstance(caracteristicas, Tamanho1litro)
assert objeto.operation() == msg
def test_Dolly_2_litros(self):
msg = 'Dolly tamanho: 2 litros.'
caracteristicas = Tamanho2litros()
objeto = Dolly(caracteristicas)
assert isinstance(caracteristicas, Caracteristicas)
assert isinstance(caracteristicas, Tamanho2litros)
assert objeto.operation() == msg
def test_Dolly_3_litros(self):
msg = 'Dolly tamanho: 3 litros.'
caracteristicas = Tamanho3litros()
objeto = Dolly(caracteristicas)
assert isinstance(caracteristicas, Caracteristicas)
assert isinstance(caracteristicas, Tamanho3litros)
assert objeto.operation() == msg
def test_GuaranaAntartica_600ml(self):
msg = 'Guarana Antartica tamanho: 600ml.'
caracteristicas = Tamanho600ml()
objeto = GuaranaAntartica(caracteristicas)
assert isinstance(caracteristicas, Caracteristicas)
assert isinstance(caracteristicas, Tamanho600ml)
assert objeto.operation() == msg
def test_GuaranaAntartica_1_litro(self):
msg = 'Guarana Antartica tamanho: 1 litro.'
caracteristicas = Tamanho1litro()
objeto = GuaranaAntartica(caracteristicas)
assert isinstance(caracteristicas, Caracteristicas)
assert isinstance(caracteristicas, Tamanho1litro)
assert objeto.operation() == msg
def test_GuaranaAntartica_2_litros(self):
msg = 'Guarana Antartica tamanho: 2 litros.'
caracteristicas = Tamanho2litros()
objeto = GuaranaAntartica(caracteristicas)
assert isinstance(caracteristicas, Caracteristicas)
assert isinstance(caracteristicas, Tamanho2litros)
assert objeto.operation() == msg
def test_GuaranaAntartica_3_litros(self):
msg = 'Guarana Antartica tamanho: 3 litros.'
caracteristicas = Tamanho3litros()
objeto = GuaranaAntartica(caracteristicas)
assert isinstance(caracteristicas, Caracteristicas)
assert isinstance(caracteristicas, Tamanho3litros)
assert objeto.operation() == msg
def test_class_abstractClass(self):
msg_erro = "Can't instantiate abstract class Caracteristicas "
msg_erro = msg_erro + "with abstract methods operation_implementation"
with pytest.raises(TypeError) as error:
Caracteristicas()
assert str(error.value) == msg_erro
|
Java
|
UTF-8
| 3,133
| 2.59375
| 3
|
[] |
no_license
|
package mum.edu.util;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import mum.edu.models.Artist;
import mum.edu.models.Characters;
import mum.edu.models.Comment;
import mum.edu.models.Director;
import mum.edu.models.Genre;
import mum.edu.models.Movie;
public class DataPopulate {
@SuppressWarnings("unused")
public static void populate() throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
EntityManager em = EntityManagerUtil.getInstance().createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
// adding movies
byte[] poster1 = imageUpload("mov1.jpg");
Date releaseDate1 = formatter.parse("12-Jun-2013");
Movie mov1 = new Movie("mov 1", poster1, releaseDate1,9, Genre.ACTION, "mov 1 summary", null);
byte[] poster2 = imageUpload("mov1.jpg");
Date releaseDate2 = formatter.parse("7-Feb-2016");
Movie mov2 = new Movie("mov 2", poster2, releaseDate2,8, Genre.ACTION, "mov 2 summary", null);
em.persist(mov1);
em.persist(mov2);
// Adding artirts
Date dob = formatter.parse("23-May-1982");
byte[] picture = imageUpload("arlando.jpg");
List<Movie> playedMov = Arrays.asList(mov1,mov2);
Artist Orlando = new Characters("Orlando Boom", dob, "Califonia", "Awarded with grammy 4 time", picture, playedMov, "supporting Actor");
Date dob2 = formatter.parse("23-May-1982");
byte[] picture2 = imageUpload("leonardo-dicaprio.jpg");
List<Movie> playedMov1 = Arrays.asList(mov2);
Artist leonardo = new Characters("leonardo-dicaprio", dob2, "Califonia", "Best actor of all time", picture2, playedMov1, "Lead Actor");
Date dob3 = formatter.parse("23-May-1982");
byte[] picture3 = imageUpload("arlando.jpg");
List<Movie> directedMov = Arrays.asList(mov1);
Artist Jackson = new Director("Peater Jackson", dob3, "Califonia", "Best Director.", picture3, directedMov);
em.persist(Orlando);
em.persist(leonardo);
em.persist(Jackson);
List<Artist> mov1Artists = Arrays.asList(Orlando,leonardo);
List<Artist> mov2Artists = Arrays.asList(Orlando,Jackson);
mov1.setArtists(mov1Artists);
mov2.setArtists(mov2Artists);
Comment com1 = new Comment("This movie is awesome", mov1);
Comment com2 = new Comment("I dont like ending of this movies", mov1);
Comment com3 = new Comment("over all good. ", mov1);
Comment com4 = new Comment("Unbelievalbe movie. Epic movie of century.", mov2);
em.persist(com1);
em.persist(com2);
em.persist(com3);
em.persist(com4);
tx.commit();
em.close();
}
private static byte[] imageUpload(String name) {
byte[] fileData = null;
try {
Path p = FileSystems.getDefault().getPath("",
System.getProperty("user.dir") + "/src/main/resources/" + name);
fileData = Files.readAllBytes(p);
} catch (Exception ex) {
ex.printStackTrace();
}
return fileData;
}
}
|
Markdown
|
UTF-8
| 11,294
| 3.359375
| 3
|
[] |
no_license
|
---
title: TypeScript
date: 2022-04-01 11:56:13
categories:
- Fullstack
tags:
- Typescript
---
## Why TypeScript
### Types
Types are applied to:
- variables
- function parameters
- function returns
- object values.
### JavaScript is Weakly-Typed.
This means that types are assigned by the interpreter based on the data and makes an educated guess when the code's intention is ambiguous. This can lead to unintended results.
**Example:**
```undefined
2 + '2' = '22'
```
### TypeScript Adds Typing to JavaScript
In short, TypeScript is a static and strong typed superset of JavaScript. When we're done with our TypeScript code, it compiles to JavaScript.
## Configure TypeScript
### Install TypeScript
```bash
npm init -y
```
```bash
$ npm i typescript // save to dependencies
$ npm i typescript --save-dev // save to devDependencies
```
Add `typescript`, `ts-node` and `@types/node` definitions to dev dependencies.
```bash
npm i --save-dev typescript
npm i --save-dev ts-node
npm i --save-dev @types/node
```
### Creating your package.json Script
To use TypeScript, you need to add a script to your package.json file to compile TypeScript to JavaScript. This is generally called your "build" script but could be named anything.
```javascript
"scripts": {
"build": "npx tsc"
},
```
To execute your `"build"` script use the following:
```bash
$ npm run build
```
Run the completed index file.
```bash
$ node build/.
```
`tsconfig.json` can also be named `jsconfig.json`.
To install the config file, run
```bash
$ npx tsc --init
```
### Helpful configurations to note:
```javascript
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"lib": ["ES2018", "DOM"],
"outDir": "./build",
"strict": true,
"noImplicitAny": true,
},
"exclude": ["node_modules", "tests"]
}
```
You will see many more options available than what is above. Your application may require additional settings to be configured, but these are typically the main settings to start with.
- `target` - sets what version of JS TypeScript will be transpiled to.
- `module` - sets what module system will be used when transpiling. Node.js uses the common.js module system by default
- `lib` - is used to say what libraries your code is using. In this case, ES2018 and the DOM API
- `outDir` - where you want your src code to output to. Often named build, prod, or server (when using it serverside)
- `strict` - enable strict typing
- `noImplicitAny` - disallow the `"any"` type (covered in TypeScript Basics)
- `exclude` - directories to exclude in compiling
## ES6 Modules
Now that we are using TypeScript for our application, we can also easily utilize the ES6 module system instead of the CommonJS module system. Destructuring should only be used when you are exporting the functions individually. If choosing to use export default, you must import the entire default as a module.
### Import
For importing modules, use the following syntax
```javascript
// Rename the module
import 'name' from 'module';
// Use destructuring to pull in specific functions when they are exported individually
import {function, function} from 'module';
```
### Export
```javascript
// Export an individual function or other type of object in code
export const myFunction = () => {};
// Export a single item at the end
export default object;
// Export a list of objects
export default {object1, object2};
```
## TypeScript Basics
### Implicit Typing and Explicit Typing
#### Implicit Typing
TypeScript will automatically assume types of objects if the object is not typed. It is best practice to allow TypeScript to type immutable variables and simple functions implicitly.
```javascript
const myNum = 3; // TypeScript implicitly types myNum as a number based on the variable
```
Implicit Typing is a best practice when the app is self-contained (meaning that it does not depend on other applications or APIs) or variables are immutable.

#### Explicit Typing
```javascript
let myVar: number = 3; // myVar has been explicitly typed as a number
```

### Basic Types
`string` - used for string types, textual data
```javascript
let studentName:string;
studentName = 'Dae Lee'
```
------
`number` - used for number types including integers and decimals
```javascript
let studentAge: number;
studentAge = 10;
```
------
`boolean` - used for `true`/`false` types
```javascript
let studentEnriched: boolean;
studentEnriched = true;
```
------
`Union Types` - used when more than one type can be used
```javascript
let studentPhone: (number | string);
studentPhone = '(555) 555 - 5555';
studentPhone = 5555555555;
```
------
`null` - used when an object or variable is intentionally `null`, typically only functionally found in union types
```javascript
const getCapitals = (str:string):string[] | null => {
const capitals = str.match(/[A-Z]/);
return capitals;
}
console.log(getCapitals('something'));
// returns null
console.log(getCapitals('Something'));
// returns ['S']
```
------
`undefined` - used when a variable has yet to be defined
```javascript
const myFunc = (student: string | undefined) => {
if ( student === undefined ){
// do something
}
};
```
---
`void` - used as a return type when the function returns nothing
```javascript
const myFunc = (student: string): void {
console.log(student);
};
```
------
`never` - used as a return type when the function will never return anything, such as with functions that throw errors or infinite loops
```javascript
const myError = (err: string): never {
throw new Error(err);
}
```
------
`any` - *should be avoided*. Used when the type of the item being typed can be anything
```javascript
const myFunc = (student: any): any => {
// do something
};
```
------
`unknown` - used when the type of the thing being typed is unknown. Used heavily for type assertion
```javascript
const myFunc = (student: unknown): string => {
// do something
}
```
### Type Assertions
Type Assertions are used to tell TypeScript that even though TypeScript thinks it should be one type, it is actually a different type. Common to see when a type is `unknown`
```javascript
const myFunc = (student: unknown): string => {
newStudent = student as string;
return newStudent;
}
```
### Object-like types
**Array** - to type as an array, use the type, followed by square brackets. Union types can be used to allow for multiple types in an array.
```tsx
let arr: string[]; // only accepts strings
let arr2: (string | number)[]; // accepts strings or numbers
```
------
**Tuple** - tuples are not native to JavaScript. When you know exactly what data will be in the array, and you will not be adding to the array or modifying the type for any value, you can use a tuple.
```typescript
let arr: [string, number, string]; // ['cat', 7, 'dog']
```
------
`enum` - enums are not native to JavaScript but are similar to enumeration used in other languages like C++ and Java. You use an enum when you have a constant set of values that will not be changed. By default, the values in an enum are also given a numeric value starting at 0. However, the numeric value can manually be set to any number explicitly or by calculation. Uses PascalCase to name the type.
```typescript
enum Weekend {
Friday,
Saturday,
Sunday
}
```
### Objects and Interfaces
Objects are easily created in JavaScript due to JavaScript's weak typing. With TypeScript, they take a bit more work. It is possible to create an object in TypeScript, but TypeScript offers better tools for doing so.
**Object** - creating an object requires defining the object before setting values. Once you have defined the object, additional properties cannot be added to the type definition, making it unhelpful when you need to add more properties after creation.
```ts
let student:{ name: string, age: number, enrolled: boolean} = {name: 'Maria', age: 10, enrolled: true};
```
------
`interface` - Interfaces are a concept not native to javascript, but similar concepts exist in other languages like Java, C++, and Python, where you create an abstract class as an interface for creating classes. With TypeScript, interfaces are simply used as the blueprint for the shape of something. Interfaces can be used to create functions but are most commonly seen to create objects.
```tsx
interface Student {
name: string,
age: number,
enrolled: boolean
};
let newStudent:Student = {name: 'Maria', age: 10, enrolled: true};
```
```tsx
interface Undergrad extends Student {
major: string;
}
```
#### Duck Typing
Duck Typing is a programming concept that tests if an object meets the duck test: "If it walks like a duck and it quacks like a duck, then it must be a duck."
TypeScript uses duck typing for interfaces, meaning that even though you may say a function takes in an argument of interface A, if interface B has the same properties of A, it will also accept B. Interface A is the duck, and Interface B walks and quacks like a duck, so we'll accept it as a duck too.
#### Optional and Readonly Properties
**Optional** - use when an object may or may not have a specific property by adding a `?` at the end of the property name.
```tsx
interface Student {
name: string,
age: number,
enrolled: boolean,
phone?: number // phone becomes optional
};
```
------
`readonly` - use when a property should not be able to be modified after the object has been created.
```ts
interface Student {
name: string,
age: number,
enrolled: boolean,
readonly id: number // id is readonly
};
```
### Type Aliases
#### With primitive types for documentation
```tsx
type Name = string;
```
#### Workes with unions and tuples
```tsx
type Input = string | number;
type Coord = [number, number];
```
Type Aliases can also be used as object. It is similar as interface.
### Classes
TypeScript classes look and behave very much like the classes introduced in ES6. The biggest addition to TypeScript classes is the addition of access modifiers.
```tsx
class Student {
protected studentGrade: number;
private studentId: number;
public constructor(grade: number, id: number) {
this.studentGrade = grade;
this.studentId = id;
}
id(){
return this.studentId;
}
}
```
### Factory Functions
```tsx
interface Student {
name: string;
age: number
greet(): void;
}
const studentFactory = (name: string, age: number): Student =>{
const greet = ():void => console.log('hello');
return { name, age, greet };
}
const myStudent = studentFactory('Hana', 16);
```
## Generics and Asynchronous TypeScript
### Generics
We can combine the following function using generics.
```tsx
const getItem = (arr: number[]):number => {
return arr[1];
}
const getItem = (arr: string[]):string => {
return arr[1];
}
```
```tsx
// Generic Function
const getItem = <T>(arr: T[]):T => {
return arr[1];
};
```
|
Rust
|
UTF-8
| 9,800
| 2.984375
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
use std::{
fmt::{self, Debug, Formatter},
pin::Pin,
rc::Rc,
};
use futures_lite::{Future, Stream, StreamExt};
use crate::{
channels::channel_mesh::{FullMesh, Senders},
task::JoinHandle,
GlommioError, ResourceType, Result,
};
/// Alias for return type of `Handler`
pub type HandlerResult = Pin<Box<dyn Future<Output = ()>>>;
/// Trait for handling sharded messages
pub trait Handler<T>: Clone {
/// Handle a message either received from an external stream or forwarded
/// from another peer.
/// * `msg` - The message to handle.
/// * `src_shard` - ID of the shard where the msg is from.
/// * `cur_shard` - ID of the local shard.
fn handle(&self, msg: T, src_shard: usize, cur_shard: usize) -> HandlerResult;
}
/// The public interface for sharding
pub struct Sharded<T: Send, H> {
shard: Rc<Shard<T, H>>,
consumers: Vec<JoinHandle<()>>,
forward_tasks: Vec<JoinHandle<()>>,
closed: bool,
}
impl<T: Send, H> Debug for Sharded<T, H> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "Sharded")
}
}
/// Alias for sharding function
pub type ShardFn<T> = fn(&T, usize) -> usize;
impl<T: Send + 'static, H: Handler<T> + 'static> Sharded<T, H> {
/// Join a full mesh for sharding
pub async fn new(mesh: FullMesh<T>, shard_fn: ShardFn<T>, handler: H) -> Result<Self, ()> {
let nr_shards = mesh.nr_peers();
let (senders, mut receivers) = mesh.join().await?;
let shard = Rc::new(Shard {
nr_shards,
shard_id: senders.peer_id(),
shard_fn,
senders,
handler: handler.clone(),
});
let mut forward_tasks = Vec::with_capacity(nr_shards);
for (src_shard, stream) in receivers.streams() {
let handler = handler.clone();
let cur_shard = shard.shard_id;
let consumer = crate::spawn_local(async move {
while let Some(msg) = stream.recv().await {
handler.handle(msg, src_shard, cur_shard).await;
}
});
forward_tasks.push(consumer.detach());
}
Ok(Self {
shard,
consumers: Vec::new(),
forward_tasks,
closed: false,
})
}
/// Returns the total number of shards
pub fn nr_shards(&self) -> usize {
self.shard.nr_shards
}
/// Returns the shard_id associated with ourselves
pub fn shard_id(&self) -> usize {
self.shard.shard_id
}
/// Consume messages from a stream. It will return a
/// [`GlommioError::Closed`] if this [`Sharded`] is closed. Otherwise,
/// the function will return immediately after spawning a background
/// task draining messages from the stream.
///
/// [`GlommioError::Closed`]: crate::GlommioError::Closed
pub fn handle<S: Stream<Item = T> + Unpin + 'static>(&mut self, messages: S) -> Result<(), S> {
if self.closed {
Err(GlommioError::Closed(ResourceType::Channel(messages)))
} else {
let shard = self.shard.clone();
let consumer = crate::spawn_local(async move { shard.handle(messages).await }).detach();
self.consumers.push(consumer);
Ok(())
}
}
/// Sends an individual message to a given shard.
///
/// This function returns [`GlommioError::Closed`] if this [`Sharded`] is
/// closed, or [`InvalidInput`] if the destination id is invalid.
///
/// This function ignores the sharding function.
///
/// [`GlommioError::Closed`]: crate::GlommioError::Closed
/// [`InvalidInput`]: std::io::ErrorKind::InvalidInput
pub async fn send_to(&self, dst_shard: usize, message: T) -> Result<(), T> {
self.shard.send_to(dst_shard, message).await
}
/// Sends an individual message to the correct shard.
///
/// The correct shard is calculated using the sharding function in this
/// `Sharded` object.
///
/// This function returns [`GlommioError::Closed`] if this [`Sharded`] is
/// closed.
///
/// [`GlommioError::Closed`]: crate::GlommioError::Closed
pub async fn send(&self, message: T) -> Result<(), T> {
self.shard.send(message).await
}
/// Close this [`Sharded`] and wait for all existing background tasks to
/// finish. No more consuming task will be spawned, but incoming
/// messages from the streams consumed by existing background tasks
/// will not be rejected. So it would be important to truncate the streams
/// from upstream before calling this method to prevent it from hanging.
pub async fn close(&mut self) {
while let Some(consumer) = self.consumers.pop() {
consumer.await;
}
self.shard.close();
while let Some(task) = self.forward_tasks.pop() {
task.await;
}
}
}
struct Shard<T: Send, H> {
nr_shards: usize,
shard_id: usize,
shard_fn: ShardFn<T>,
senders: Senders<T>,
handler: H,
}
impl<T: Send + 'static, H: Handler<T> + 'static> Shard<T, H> {
async fn handle<S: Stream<Item = T> + Unpin>(&self, mut messages: S) {
while let Some(msg) = messages.next().await {
self.send(msg).await.unwrap();
}
}
async fn send_to(&self, dst_shard: usize, msg: T) -> Result<(), T> {
if dst_shard == self.shard_id {
self.handler.handle(msg, self.shard_id, self.shard_id).await;
} else {
self.senders.send_to(dst_shard, msg).await?;
}
Ok(())
}
async fn send(&self, msg: T) -> Result<(), T> {
let dst_shard = (self.shard_fn)(&msg, self.nr_shards);
self.send_to(dst_shard, msg).await
}
fn close(&self) {
self.senders.close();
}
}
#[cfg(test)]
mod tests {
use futures_lite::{future::ready, stream::repeat_with, FutureExt, StreamExt};
use crate::{
channels::{
channel_mesh::MeshBuilder,
sharding::{Handler, HandlerResult, Sharded},
},
enclose,
prelude::*,
};
#[test]
fn test_send() {
type Msg = usize;
let nr_shards = 10;
fn shard_fn(msg: &Msg, nr_shards: usize) -> usize {
*msg % nr_shards
}
#[derive(Clone)]
struct RequestHandler {
_nr_shards: usize,
}
impl Handler<Msg> for RequestHandler {
fn handle(&self, msg: Msg, _src_shard: usize, cur_shard: usize) -> HandlerResult {
assert_eq!(msg, cur_shard);
ready(()).boxed_local()
}
}
let mesh = MeshBuilder::full(nr_shards, 1024);
let shards = (0..nr_shards).map(|_| {
LocalExecutorBuilder::default().spawn(enclose!((mesh) move || async move {
let handler = RequestHandler { _nr_shards: nr_shards };
let mut sharded = Sharded::new(mesh, shard_fn, handler).await.unwrap();
for i in 0..nr_shards {
sharded.send(i).await.unwrap();
}
sharded.close().await;
}))
});
for s in shards.collect::<Vec<_>>() {
s.unwrap().join().unwrap();
}
}
#[test]
fn test_send_to() {
type Msg = usize;
let nr_shards = 10;
fn shard_fn(_msg: &Msg, _nr_shards: usize) -> usize {
panic!("Should not be called")
}
#[derive(Clone)]
struct RequestHandler {
_nr_shards: usize,
}
impl Handler<Msg> for RequestHandler {
fn handle(&self, msg: Msg, _src_shard: usize, cur_shard: usize) -> HandlerResult {
assert_eq!(msg, cur_shard);
ready(()).boxed_local()
}
}
let mesh = MeshBuilder::full(nr_shards, 1024);
let shards = (0..nr_shards).map(|_| {
LocalExecutorBuilder::default().spawn(enclose!((mesh) move || async move {
let handler = RequestHandler { _nr_shards: nr_shards };
let mut sharded = Sharded::new(mesh, shard_fn, handler).await.unwrap();
for i in 0..nr_shards {
sharded.send_to(i, i).await.unwrap();
}
sharded.send_to(nr_shards + 1 , nr_shards + 1).await.unwrap_err();
sharded.close().await;
}))
});
for s in shards.collect::<Vec<_>>() {
s.unwrap().join().unwrap();
}
}
#[test]
fn test() {
type Msg = i32;
let nr_shards = 10;
fn shard_fn(msg: &Msg, nr_shards: usize) -> usize {
*msg as usize % nr_shards
}
#[derive(Clone)]
struct RequestHandler {
nr_shards: usize,
}
impl Handler<i32> for RequestHandler {
fn handle(&self, msg: Msg, _src_shard: usize, cur_shard: usize) -> HandlerResult {
assert_eq!(shard_fn(&msg, self.nr_shards), cur_shard);
ready(()).boxed_local()
}
}
let mesh = MeshBuilder::full(nr_shards, 1024);
let shards = (0..nr_shards).map(|_| {
LocalExecutorBuilder::default().spawn(enclose!((mesh) move || async move {
let handler = RequestHandler { nr_shards };
let mut sharded = Sharded::new(mesh, shard_fn, handler).await.unwrap();
let messages = repeat_with(|| fastrand::i32(0..100)).take(1000);
sharded.handle(messages).unwrap();
sharded.close().await;
}))
});
for s in shards.collect::<Vec<_>>() {
s.unwrap().join().unwrap();
}
}
}
|
Python
|
UTF-8
| 708
| 3.453125
| 3
|
[] |
no_license
|
import turtle
from turtle import Turtle , Screen
import random
turtle.colormode(255)
color_list = [(239, 236, 238), (238, 237, 236), (237, 237, 241), (26, 108, 164), (194, 38, 81), (237, 161, 50), (234, 215, 86), (226, 237, 229)]
tom = Turtle()
color = random.choice(color_list)
number_of_dots = 100
tom.penup()
tom.setheading(225)
tom.forward(250)
tom.setheading(0)
for dot_count in range(1, number_of_dots + 1):
tom.penup()
tom.dot(20, random.choice(color_list))
tom.forward(30)
if dot_count % 10 == 0:
tom.setheading(90)
tom.forward(30)
tom.setheading(180)
tom.forward(300)
tom.setheading(0)
tom.hideturtle()
screen = Screen()
screen.exitonclick()
|
Markdown
|
UTF-8
| 2,692
| 3.203125
| 3
|
[
"MIT"
] |
permissive
|
# Inscribe Note Taker
 <br>
With the Inscribe Note Taker, users are able to save, retrieve, and delete persistent notes at their convenience. This is made possible by Node.js, Express, and server-side functionality.
<a href="https://inscribe-notes.herokuapp.com/" target="_blank">Demo the deployed app here</a>
## User Story
AS A user, I want to be able to write and save notes <br>
I WANT to be able to delete notes I've written before <br>
SO THAT I can organize my thoughts and keep track of tasks I need to complete
## Table of Contents
* [Installation](#installation)
* [Usage](#usage)
* [Resources](#resources)
* [Contributions](#contributions)
* [Testing](#testing)
* [Questions](#questions)
* [License](#license)
## Installation
If you want to use the application on your local server:
1. Clone the repo.
2. Install required dependencies by running command ```npm i```.
3. Run command ```node server``` to start the server on your local machine.
Otherwise, feel free to demo the deployed application <a href="https://inscribe-notes.herokuapp.com/" target="_blank">here</a>.
## Usage
To use Inscribe, simply click in the text area labeled "Enter note title here..." and insert the title of your note. Repeat the same process for the note text. After the note text is inserted, a save button will appear in the top right corner. Click the button to save the note to your list of notes in the sidebar. To retrieve the note, simply click on the note in the sidebar. To delete the note, click on the trash can icon next to the note in the sidebar. When viewing a note, click the "add" icon in the top right corner to begin writing a new note.
<img src = "Develop/images/root.png" alt="screenshot of inscribe">
<img src = "Develop/images/note.png" alt="screenshot of inscribe">
<img src = "Develop/images/view-note.png" alt="screenshot of inscribe">
<img src = "Develop/images/save.png" alt="screenshot of inscribe">
## Resources
**jQuery** <br>
**Node.js** <br>
**Express** <br>
**Bootstrap** <br>
**UUID** <br>
**Heroku** <br>
**Font Awesome**
## Contributions
All contributions to this project are welcome! Clone the repo down to your local machine, commit changes, push to GitHub, and open a pull request!
## Testing
No tests are set up for Inscribe at this time. Feel free to write tests or search the application for bugs.
## Questions
If you have any further questions, feel free to reach out to me! <br>
<a href='https://www.github.com/twkirkpatrick' target="_blank">Github</a> <br>
<a href='mailto:twk4491@gmail.com' target="_blank">twk4491@gmail.com</a>
## License
Usage is provided under the MIT license.
|
Python
|
UTF-8
| 1,717
| 3.921875
| 4
|
[
"BSD-3-Clause"
] |
permissive
|
"""
Filename: ecdf.py
Authors: Thomas Sargent, John Stachurski
Implements the empirical cumulative distribution function given an array
of observations.
"""
import numpy as np
import matplotlib.pyplot as plt
class ECDF(object):
"""
One-dimensional empirical distribution function given a vector of
observations.
Parameters
----------
observations : array_like
An array of observations
Attributes
----------
observations : array_like
An array of observations
"""
def __init__(self, observations):
self.observations = np.asarray(observations)
def __call__(self, x):
"""
Evaluates the ecdf at x
Parameters
----------
x : scalar(float)
The x at which the ecdf is evaluated
Returns
-------
scalar(float)
Fraction of the sample less than x
"""
return np.mean(self.observations <= x)
def plot(self, a=None, b=None):
"""
Plot the ecdf on the interval [a, b].
Parameters
----------
a : scalar(float), optional(default=None)
Lower end point of the plot interval
b : scalar(float), optional(default=None)
Upper end point of the plot interval
"""
# === choose reasonable interval if [a, b] not specified === #
if a is None:
a = self.observations.min() - self.observations.std()
if b is None:
b = self.observations.max() + self.observations.std()
# === generate plot === #
x_vals = np.linspace(a, b, num=100)
f = np.vectorize(self.__call__)
plt.plot(x_vals, f(x_vals))
plt.show()
|
Shell
|
UTF-8
| 106
| 2.546875
| 3
|
[] |
no_license
|
#!/bin/bash
echo -n "Enter a Password: "
read -s pass_value
echo ""
echo "Password Entered: $pass_value"
|
C
|
UTF-8
| 883
| 2.84375
| 3
|
[
"CC0-1.0"
] |
permissive
|
#ifndef __DEBUGUTIL_H__
#define __DEBUGUTIL_H__
#include "CDebugLogger.h"
/*
Christopher De Pasquale
Created: 20th of April, 2018
Last Edit: 24th of April, 2018
Usage:
DbgAssert(pPtr != NULL);
DbgAssertMsg(pPtr != NULL, "The pointer is null!!!");
*/
#ifdef NDEBUG
#define DbgAssertMsg(ignore, _ignore) ((void)0)
#define DbgAssert(ignore) ((void)0)
#else
#define DbgAssertMsg(expr, msg) \
if (!expr == false) { \
CDebugLogger::LogFatalFile("ASSERT_LOG.txt", "ASSERT FAILED - %s\n\tSource: %s AT LINE %i\n\tEXPRESSION: %s != 1\n", msg, __FILE__, __LINE__, #expr); \
exit(EXIT_FAILURE); \
}
#define DbgAssert(expr) \
if (expr == false) { \
CDebugLogger::LogFatalFile("ASSERT_LOG.txt", "ASSERT FAILED!!\n\tSource: %s AT LINE %i\n\tEXPRESSION: %s != 1\n", __FILE__, __LINE__, #expr); \
exit(EXIT_FAILURE); \
}
#endif
#endif
|
Java
|
UTF-8
| 1,376
| 2.21875
| 2
|
[] |
no_license
|
package report;
import dbmodel.SourceChapterSummary;
public class SourceChapterReport extends SourceChapterSummary {
private Integer problemDoneCount;
private Integer problemWrongCount;
private Integer problemBlankCount;
public SourceChapterReport(SourceChapterSummary sourceChapterSummary) {
setChapternotecount(sourceChapterSummary.getChapternotecount());
setChapterproblemcount(sourceChapterSummary.getChapterproblemcount());
setIdsourcechapter(sourceChapterSummary.getIdsourcechapter());
setSourcechapterindex(sourceChapterSummary.getSourcechapterindex());
setSourcechaptername(sourceChapterSummary.getSourcechaptername());
setSourceid(sourceChapterSummary.getSourceid());
}
public Integer getProblemDoneCount() {
return problemDoneCount;
}
public void setProblemDoneCount(Integer problemDoneCount) {
this.problemDoneCount = problemDoneCount;
}
public Integer getProblemWrongCount() {
return problemWrongCount;
}
public void setProblemWrongCount(Integer problemWrongCount) {
this.problemWrongCount = problemWrongCount;
}
public Integer getProblemBlankCount() {
return problemBlankCount;
}
public void setProblemBlankCount(Integer problemBlankCount) {
this.problemBlankCount = problemBlankCount;
}
}
|
JavaScript
|
UTF-8
| 342
| 3.5625
| 4
|
[] |
no_license
|
/**
* @param {string} S
* @return {string}
*/
var reorganizeString = function(S) {
const arr = S.split('')
console.log('arr: ', arr);
let item = 0;
};
/*
็คบไพ 1:
่พๅ
ฅ: S = "aab"
่พๅบ: "aba"
็คบไพ 2:
่พๅ
ฅ: S = "aaab"
่พๅบ: ""
*/
var S = "aab"
var S = "aaab"
var val = reorganizeString(S);
console.log('val: ', val);
|
Markdown
|
UTF-8
| 8,307
| 2.734375
| 3
|
[] |
no_license
|
---
title: "GPU passthrough - my switch to Linux"
excerpt_separator: "<!--more-->"
categories:
- Blog
tags:
- Other
- Linux
---
A few weeks ago I decided to ditch my Windows workstation and move to Linux. While Microsoft is (in my opinion) going in the right direction (WSL 2, Terminal, Package Manager) they are still very intrusive in terms of how one should use his computer (do some updates will ya?!) and privacy / telemtry data. One example for the second point that I noticed recently is, that you **have** to use a Micorosoft (online) account during installation. Only way around this is to cut your internet connection...
I was already using a lot of Linux at work (servers) and in my Homelab, so I am not unfamiliar with it. Only thing that hold me back to switch were games that are only running on Windows. (cause there is no better way to ruin your day than a few rounds of League w/ some friend ;) )
The most elegant way to solve the gaming problem on Linux is to use a VM and passing through your graphics card. Here I want to shortly sum up what I did to get my setup working. The resource I used the most is [this](https://wiki.archlinux.org/index.php/PCI_passthrough_via_OVMF) Arch Linux wiki entry.
##Prerequisites I - General
To pass through PCI devices there are a few hardware prerequisites. These are:
1. CPU must support hardware virtualaization and IOMMU (on Intel this is VT-x & VT-d)
2. Mainboard must support IOMMU
3. GPU (ROM) must support UEFI
If you want help looking for hardware for a GPU passthrough setup you should look at [passthroughpo.st](https://passthroughpo.st/vfio-increments/).
I use a Intel i7-9700k as CPU, a ASRock z390 Pro4 as Mainboard and a NVIDIA GeForce GTX 660 as GPU. (I am aware that my GPU is really old and crappy, but it is mine and it works!) Y
<figure>
<a href="/assets/images/gpu_passthrough_system_info.png"><img src="/assets/images/gpu_passthrough_system_info.png"></a>
</figure>
<figure>
<a href="/assets/images/gpu_passthrough_kernel_info.png"><img src="/assets/images/gpu_passthrough_kernel_info.png"></a>
</figure>
It is not really important what Linux distro you use. It should have recent software versions (e.g. QEMU & KVM). Thats why some people prefer Arch or Manajaro and have problems with Debian or Ubuntu. At the end of the day you should use the distro you like the most, because you can make the passthrough work (theoretically) on any distro. I am using Fedora 32.
##Prerquisites II - Flashing GPU
Unfortunately my hardware didn't fulfill the prerequisites, because my GPU didn't support UEFI. (Keep in mind this baby is quite old and was released [in 2012](https://en.wikipedia.org/wiki/GeForce_600_series#GeForce_600_(6xx)_series). To keep using this GPU I would need to update its VBIOS to enable it for UEFI.
irst find the exact version of your card. You can use a tool like [gpu-z](https://www.techpowerup.com/gpuz/) to find it (and verify if your GPU supports UEFI in the first place). In my case the model is *Asus GTX660-DC2-2GD5*.
I did find an official [vendor](https://www.asus.com/us/Graphics-Cards/GTX660DC22GD5/HelpDesk_BIOS/) (Asus) tool to update the VBIOS, but it didn't work on my machine. The next way is to try to manually flash the ROM. (*this can brick your GPU*)
You can get the most up to date VBIOS for your card at techpowerup. For my graphic card, [this](https://www.techpowerup.com/vgabios/147770/asus-gtx660-2048-130628-1) link is the right one. For flashing I used [NVFlash](https://www.techpowerup.com/download/nvidia-nvflash/).
After verifying the hash of the new ROM, backing up my running ROM via GPU-Z and disabling the GPU (e.g. in Device Manager on Windows), I used following commands:
{% highlight javascript linenos %}
#list index
nvflash --list
#disable EEPROM write protection
nvflash64 --protectoff
#Flash new ROM to device at index
nvflash64 --index=*your_index* *new_ROM*
nvflash64 --protecton
{% endhighlight %}
After flashing I rebooted and then verified that the GPU now supports UEFI (via GPU-Z).
After fulfilling all requirements and installing Linux as host OS, the actual work on the passthrough can begin.
##Activate IOMMU & Isolate GPU
As already specified at the beginning, my main source for all coming steps of this setup was the [Arch Linux Wiki](https://wiki.archlinux.org/index.php/PCI_passthrough_via_OVMF). My config will be specific to my hardware and to the Fedora host OS I chose.
Before being able to pass thorugh a PCI device to a VM, we have to enable IOMMU. The IOMMU will allow our hypervisor to directly address the device memory without corrupting it and without the need for the hypervisor to tranlsate it (which would be slow). A short description of IOMMU and its uses in virtualization can be found on [this](https://en.wikipedia.org/wiki/Input%E2%80%93output_memory_management_unit#Virtualization) Wikipedia site.
First the CPU feature must be activated in your BIOS settings. After that we need to edit the kernel parameter *GRUB_CMDLINE_LINUX_DEFAULT* and add *intel_iommu=on* to it. This should be done in */etc/default/grub*, so we have to create a new GRUB config file with the command *grub2-mkconfig* and then reboot. After reboot check if enabling IOMMU worked with the command and script specified [here](https://wiki.archlinux.org/index.php/PCI_passthrough_via_OVMF#Enabling_IOMMU). We need to note the device ids of the GPU and the attached sound device. These two should also be in one IOMMU Group. It should look something like this:
<figure>
<a href="/assets/images/gpu_passthrough_check_iommu.png"><img src="/assets/images/gpu_passthrough_check_iommu.png"></a>
</figure>
With IOMMU enabled we can isolate the GPU, so our host system won't block it at startup. We will do this by binding the vfio-pci stub driver to the device. We shall create the file */etc/modprobe.d/vfio.conf* with the content *options vfio-pci ids=10de:11c0,10de:0e0b* where the ids resonate to the device ids we noted earlier. Next create */etc/dracut.conf.d/vfio.conf* with the content *add_drivers+="vfio vfio_iommu_type1 vfio_pci vfio_virqfd"*. This specifies the drivers to attach. We should also add *rd.driver.pre=vfio-pci* to our kernel parameters, to make sure the driver is loaded early in the boot process. At last, recreate the GRUB config and your initramfs (w/ *dracut --force --kver your_kernel_version*) and reboot. You can check if the driver is succesfully bound to your GPU like this:
<figure>
<a href="/assets/images/gpu_passthrough_vfio_pci_driver.png"><img src="/assets/images/gpu_passthrough_vfio_pci_driver.png"></a>
</figure>
If this is the case, you are ready for setting up your Windows VM.
##VM Setup & Problems
The VM setup with QEMU/KVM and virt-manager is really straightforward. The only change in your config before installing the VM should be to set the CPU mode to *host-passthrough*. After that install your Windows via the standard Spice channel and then shutdown the VM. Remove all the virtual I/O devices (Spice etc) and attach your GPU as PCI device. If you are using a NVIDIA GPU you will have to solve the [Error 43](https://wiki.archlinux.org/index.php/PCI_passthrough_via_OVMF#%22Error_43:_Driver_failed_to_load%22_on_Nvidia_GPUs_passed_to_Windows_VMs) that will disable your GPU.
In my case I also got bluescreens (VIDEO TDR Failure) at every boot of the Windows VM. The libvirt logs showed the error: *vfio_region_write device or resource busy*. I found the solution to this problem [here](https://www.linuxquestions.org/questions/linux-kernel-70/kernel-fails-to-assign-memory-to-pcie-device-4175487043/) and wrote a [script](https://github.com/twenska/pci-passthrough/blob/master/start_vm.sh) to reset my PCI root port before every VM start.
You can find my complete virtual machine config file on [my Github Repo](https://github.com/twenska/pci-passthrough).
For passing sound from the VM to the host I use PulseAudio. To pass my peripherals I use a simple USB switch and pass a PCI-USB card to the VM. The setup works really good for playing simple Windows games (like League of Legends) on a Linux host. There is still a lot of optimization possible (new GPU, Huge MemPages, CPU Core Isolation) if I would need more performance, but for the moment I am happy with my setup :)
|
Go
|
UTF-8
| 2,716
| 2.515625
| 3
|
[] |
no_license
|
package main
import (
"b2/backend"
"b2/components/analysis"
"b2/components/changes"
"b2/components/exrecords"
"b2/components/managed/accounts"
"b2/components/managed/assets"
"b2/components/managed/classifications"
"b2/components/managed/docexmappings"
"b2/components/managed/documents"
"b2/components/managed/expenses"
"b2/components/managed/series"
"b2/components/suggestions"
"b2/manager"
"encoding/json"
"log"
"net/http"
"os"
)
// Config is to hold the data loaded at runtime from the config file
type Config struct {
Host string
ServerCert string
ServerKey string
DB string
SwUser uint64
SwToken string
DocsLocation string
}
func loadConfig() *Config {
config := new(Config)
file, err := os.Open("config")
if err != nil {
panic(err)
}
decoder := json.NewDecoder(file)
err = decoder.Decode(&config)
if err != nil {
panic(err)
}
return config
}
type handler interface {
Handle(w http.ResponseWriter, req *http.Request)
Path() string
LongPath() string
}
func addHandler(h handler) {
http.HandleFunc(h.Path(), h.Handle)
http.HandleFunc(h.LongPath(), h.Handle)
}
func main() {
config := loadConfig()
backend := backend.Instance(config.DB)
backend.Accounts = accounts.Instance(backend)
backend.Assets = assets.Instance(backend)
backend.Classifications = classifications.Instance(backend)
backend.Documents = documents.Instance(backend)
backend.Expenses = expenses.Instance(backend)
backend.Mappings = docexmappings.Instance(backend)
backend.Series = series.Instance(backend)
backend.Splitwise.BearerToken = config.SwToken
backend.Splitwise.User = config.SwUser
backend.DocsLocation = config.DocsLocation
backend.Start()
addHandler(analysis.Instance("/analysis", backend))
addHandler(manager.WebhandlerInstance("/assets", backend.Assets))
addHandler(manager.WebhandlerInstance("/assets/series", backend.Series))
addHandler(manager.WebhandlerInstance("/documents", backend.Documents))
addHandler(manager.WebhandlerInstance("/expenses", backend.Expenses))
addHandler(manager.WebhandlerInstance("/expenses/accounts", backend.Accounts))
addHandler(manager.WebhandlerInstance("/expenses/classifications", backend.Classifications))
addHandler(exrecords.Instance("/expenses/externalrecords", backend))
addHandler(suggestions.Instance("/expenses/suggestions", backend))
addHandler(manager.WebhandlerInstance("/mappings", backend.Mappings))
http.HandleFunc("/processor", backend.Process)
c := changes.Instance("/changes/", backend)
http.HandleFunc(c.Path, c.Handle)
//log.Fatal(http.ListenAndServe("localhost:8000", nil))
log.Fatal(http.ListenAndServeTLS(config.Host, config.ServerCert, config.ServerKey, nil))
}
|
Markdown
|
UTF-8
| 550
| 2.640625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
---
permalink: /
title: "About Me"
excerpt: "About me"
author_profile: true
redirect_from:
- /about/
- /about.html
---
My name is Zonghao Huang. I am currently a Ph.D. student at [Department of Computer Science, Duke University](https://www.cs.duke.edu/), where I am fortunately advised by Prof. [Michael Reiter](https://reitermk.github.io/). Previously, I did my undergraduate study at Amoy University (Xiamen University).
Generally, I am interested in the intersection of optimization, deep neural networks, cryptography, and computer security & privacy.
|
C#
|
UTF-8
| 3,023
| 2.828125
| 3
|
[] |
no_license
|
๏ปฟusing System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace BJCBCPOS.Services.Helpers {
public static class XmlHelper {
/// <summary>
/// Deserialize XML File the object T
/// </summary>
/// <param name="xmlFile">Full Path and file name</param>
/// <returns>Object T</returns>
public static T DeserializeFromFile<T>(this T toDeserialize,string xmlFile) {
XmlSerializer res = new XmlSerializer(toDeserialize.GetType());
using(StreamReader file = new StreamReader(xmlFile)) {
return (T)res.Deserialize(file);
}
}
/// <summary>
/// Deserialize XML Content String to the object T
/// </summary>
/// <param name="xmlString">xml content</param>
/// <returns>Object T</returns>
public static T DeserializeFromString<T>(this string xmlString, T toDeserialize) {
XmlSerializer res = new XmlSerializer(toDeserialize.GetType());
using(TextReader reader = new StringReader(xmlString)) {
return (T)res.Deserialize(reader);
}
}
/// <summary>
/// Serialize Object to xml content without namespaces
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="toSerialize"></param>
/// <returns>Xml String</returns>
public static string SerializeObject<T>(this T toSerialize) {
XmlWriterSettings settings = new XmlWriterSettings {/*Indent = true,*/ OmitXmlDeclaration = true };
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
using(var stream = new StringWriter())
using(var writer = XmlWriter.Create(stream,settings)) {
var serializer = new XmlSerializer(typeof(T));
serializer.Serialize(writer,toSerialize,namespaces);
return stream.ToString();
}
}
}
// How to Use
//public class BillPaymentService {
// private readonly string basePath = @"D:\Repository\Deftsoft\POS-Single\BJCBCPOS_Solution\BJCBCPOS\OtherServices\BillPayment";
// public BillPayment.ServiceType.ServiceTypeResp GetServiceType() {
// try {
// // request
// var request = new BillPayment.ServiceType.ServiceTypeReq();
// request = request.DeserializeFromFile(Path.Combine(basePath,"1. Bill Payment List Menu Request.xml"));
// var xlmparam = request.SerializeObject();
// // response
// var serviceType = new BillPayment.ServiceType.ServiceTypeResp();
// return serviceType.DeserializeFromFile(Path.Combine(basePath,"2. Bill Payment List Menu Response.xml"));
// } catch(Exception ex) {
// throw ex;
// }
// }
//}
}
|
Swift
|
UTF-8
| 10,681
| 2.671875
| 3
|
[] |
no_license
|
//
// FirstViewController.swift
// IoT_Respirator
//
// Created by Alexander Luisi on 29/05/2019.
// Copyright ยฉ 2019 Alexander Luisi. All rights reserved.
//
import UIKit
import NotificationCenter
import Charts
import CoreLocation
struct GlobalArrays
{
static var globalData: [ReadingPacket] = []
static var startTime: Date!
static var currentLocation: CLLocationCoordinate2D!
}
class FirstViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Load in the BLE manager on the first view to be shared across the other two
BluetoothManager.shared.setup()
// Request the current position of the user for backup
// (Probably should be in another place in the code, but it'll work
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
// Register a notification so that the data can be retrieved from the BLE methods
NotificationCenter.default.addObserver(self, selector: #selector(onUartReceived(_:)), name: .didReceiveUartString, object: nil)
GlobalArrays.startTime = Date() // TODO change this when the 'start' button is pressed
}
@IBOutlet weak var chartView: LineChartView!
@IBOutlet weak var vocChartView: LineChartView!
@IBOutlet weak var co2ChartView: LineChartView!
@IBOutlet weak var noxcoChartView: LineChartView!
@IBOutlet weak var rawVOCChartView: LineChartView!
@objc func onUartReceived(_ notification: Notification)
{
print("UART Recieved via notification \n")
guard let rxString = notification.userInfo?["uart"] as? String else { return }
//print(rxString)
// Deserialize the JSON here and add to the global array
//let data = rxString.data(using: .ascii)! // convert the JSON string to data in pure ASCII (unsigned char)
let trimmedString = rxString.replacingOccurrences(of: "\0", with: "")
let data = trimmedString.data(using: .ascii)!
//let tempString = String(data: data, encoding: .ascii)!
//print(tempString)
do {
if let jsonContainer = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
let addition = ReadingPacket(json: jsonContainer, jsonString: rxString)
GlobalArrays.globalData.append(addition!)
// Probably a better way to do this without Notifications to avoid resource contention, but I'm going with what I know
NotificationCenter.default.post(name: .didUpdateGlobalArray, object: nil, userInfo: nil) // Notify the other view data is available
self.updateParticulates()
self.updateTotalVOCs()
self.updateCO2()
self.updateRawCoNox()
self.updateRawVOC()
print("Estimated AQI Value: \(String(describing: addition?.airQualityEstimate))")
NotificationCenter.default.post(name: .didReceiveJSONString, object: nil, userInfo: ["json": trimmedString])
}
} catch let error {
print(error.localizedDescription)
}
//let jsonContainer = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
//let addition = ReadingPacket(json: jsonContainer, jsonString: rxString)
// Add the latest data to the array
//GlobalArrays.globalData.append(addition!)
//self.updateChart()
}
// Get the current location of the user for use if the GPS drops/fails
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let locationValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
GlobalArrays.currentLocation = locationValue
}
// Chart updates
private func updateParticulates(){
var pm25 = [ChartDataEntry]()
var pm10 = [ChartDataEntry]()
// Plot the pm2.5 and pm10 data in the chart
for i in 0..<GlobalArrays.globalData.count {
let value1 = ChartDataEntry(x: GlobalArrays.globalData[i].timeReceived, y: Double(GlobalArrays.globalData[i].particulateMatter2p5))
pm25.append(value1)
let value2 = ChartDataEntry(x: GlobalArrays.globalData[i].timeReceived, y: Double(GlobalArrays.globalData[i].particulateMatter10))
pm10.append(value2)
}
// Form the data into a data set
let pm25Line = LineChartDataSet(entries: pm25, label: "PM2.5 in ug/m^3")
let pm10Line = LineChartDataSet(entries: pm10, label: "PM10 in ug/m^3")
pm25Line.colors = [UIColor.blue]
pm10Line.colors = [UIColor.red]
// Disable the circles
pm25Line.drawCirclesEnabled = false
pm10Line.drawCirclesEnabled = false
let data = LineChartData()
data.addDataSet(pm25Line)
data.addDataSet(pm10Line)
data.setDrawValues(false)
chartView.data = data
chartView.xAxis.labelPosition = .bottom
chartView.rightAxis.enabled = false
chartView.chartDescription?.text = "Particulate Concentration"
}
private func updateTotalVOCs(){
var tvoc = [ChartDataEntry]()
// Plot the pm2.5 and pm10 data in the chart
for i in 0..<GlobalArrays.globalData.count {
let value1 = ChartDataEntry(x: GlobalArrays.globalData[i].timeReceived, y: Double(GlobalArrays.globalData[i].totalVOC))
tvoc.append(value1)
}
// Form the data into a data set
let tvocLine = LineChartDataSet(entries: tvoc, label: "Total VOC ppb")
tvocLine.colors = [UIColor.blue]
// Disable the circles
tvocLine.drawCirclesEnabled = false
let data = LineChartData()
data.addDataSet(tvocLine)
data.setDrawValues(false)
vocChartView.data = data
vocChartView.xAxis.labelPosition = .bottom
vocChartView.rightAxis.enabled = false
vocChartView.chartDescription?.text = "Total VOC Concentration"
}
private func updateCO2(){
var co2 = [ChartDataEntry]()
// Plot the pm2.5 and pm10 data in the chart
for i in 0..<GlobalArrays.globalData.count {
let value1 = ChartDataEntry(x: GlobalArrays.globalData[i].timeReceived, y: Double(GlobalArrays.globalData[i].carbonDioxideRelative))
co2.append(value1)
}
// Form the data into a data set
let co2Line = LineChartDataSet(entries: co2, label: "Total CO2 ppm")
co2Line.colors = [UIColor.blue]
// Disable the circles
co2Line.drawCirclesEnabled = false
let data = LineChartData()
data.addDataSet(co2Line)
data.setDrawValues(false)
co2ChartView.data = data
co2ChartView.xAxis.labelPosition = .bottom
co2ChartView.rightAxis.enabled = false
co2ChartView.chartDescription?.text = "Equivalent CO2 Concentration"
}
// Update CO/NOx here
private func updateRawVOC(){
var eth = [ChartDataEntry]()
var h2 = [ChartDataEntry]()
// Plot the pm2.5 and pm10 data in the chart
for i in 0..<GlobalArrays.globalData.count {
let value1 = ChartDataEntry(x: GlobalArrays.globalData[i].timeReceived, y: Double(GlobalArrays.globalData[i].ethanolRelative))
eth.append(value1)
let value2 = ChartDataEntry(x: GlobalArrays.globalData[i].timeReceived, y: Double(GlobalArrays.globalData[i].hydrogenRelative))
h2.append(value2)
}
// Form the data into a data set
let ethLine = LineChartDataSet(entries: eth, label: "Raw Ethanol Value")
let h2Line = LineChartDataSet(entries: h2, label: "Raw Hydrogen Value")
ethLine.colors = [UIColor.blue]
h2Line.colors = [UIColor.red]
// Disable the circles
ethLine.drawCirclesEnabled = false
h2Line.drawCirclesEnabled = false
let data = LineChartData()
data.addDataSet(ethLine)
data.addDataSet(h2Line)
data.setDrawValues(false)
rawVOCChartView.data = data
rawVOCChartView.xAxis.labelPosition = .bottom
rawVOCChartView.rightAxis.enabled = false
rawVOCChartView.chartDescription?.text = "Particulate Concentration"
}
private func updateRawCoNox(){
var co = [ChartDataEntry]()
var nox = [ChartDataEntry]()
// Plot the pm2.5 and pm10 data in the chart
for i in 0..<GlobalArrays.globalData.count {
let value1 = ChartDataEntry(x: GlobalArrays.globalData[i].timeReceived, y: Double(GlobalArrays.globalData[i].carbonMonoxideRelative))
co.append(value1)
let value2 = ChartDataEntry(x: GlobalArrays.globalData[i].timeReceived, y: Double(GlobalArrays.globalData[i].nitrogenOxidesRelative))
nox.append(value2)
}
// Form the data into a data set
let coLine = LineChartDataSet(entries: co, label: "Carbon Monoxide ADC Value")
let noxLine = LineChartDataSet(entries: nox, label: "Nitrogen Oxides ADC Value")
coLine.colors = [UIColor.blue]
noxLine.colors = [UIColor.red]
// Disable the circles
coLine.drawCirclesEnabled = false
noxLine.drawCirclesEnabled = false
let data = LineChartData()
data.addDataSet(coLine)
data.addDataSet(noxLine)
data.setDrawValues(false)
noxcoChartView.data = data
noxcoChartView.xAxis.labelPosition = .bottom
noxcoChartView.rightAxis.enabled = false
noxcoChartView.chartDescription?.text = "Raw Carbon Monoxide and Nitrogen Oxides"
}
}
extension Notification.Name
{
static let didReceiveUartString = Notification.Name("didReceiveUartString")
}
|
Python
|
UTF-8
| 267
| 2.984375
| 3
|
[] |
no_license
|
def main(steps = 3, iterations = 2017):
l = [0]
pos = 0
for i in range(0, iterations):
pos = (pos + steps) % len(l)
l.insert(pos + 1, i + 1)
pos += 1
print(l[l.index(2017) + 1])
if __name__ == '__main__':
main(steps = 303)
|
JavaScript
|
UTF-8
| 402
| 3.359375
| 3
|
[] |
no_license
|
//given an array of prices, return maximum profit from a single transaction
var maxProfit = function(prices) {
let buy, sell;
let maxProfit = 0;
for(let i = 0; i < prices.length; i++){
buy = prices[i];
for(let j = i + 1; j < prices.length; j++){
sell = prices[j];
maxProfit = Math.max(maxProfit, sell - buy);
}
}
return maxProfit;
};
|
Shell
|
UTF-8
| 470
| 2.640625
| 3
|
[] |
no_license
|
#!/bin/bash
notify-send 'Backup script' 'Start backing up /home' --icon=dialog-information
rsync -e "ssh" --progress --ignore-errors --delete-after --exclude-from=/home/nop-90/scripts/rsync-exclude.txt -rav /home/nop-90/{.*,*} rsync@node:/external2/home
if [ $? -eq 0 ]; then
notify-send 'Backup script' 'Backup finished with non-zero status' --icon=dialog-warning
else
notify-send 'Backup script' 'Backup finished with zero status' --icon=dialog-information
fi
|
JavaScript
|
UTF-8
| 2,645
| 3.109375
| 3
|
[] |
no_license
|
import { useState, Component } from "react";
import ExerciseArrayExtended from './ExerciseArrayExtended'
const mainContainerStyle =
{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
marginTop: 250
}
const tableContainerStyle =
{
flexDirection: 'row',
display: 'flex',
justifyContent: 'space-evenly',
alignItems: 'center',
flex: 1,
height: 300
}
function Exercise1Extended() {
const [testArrays, setTestArrays] = useState([["Bob", "Mark", "John", "Tony", "Tim", "Matt", "Margaret", "Moe", "George"], [], []]);
const [testArraysSelected, setTestArraysSelected] = useState([[], [], []])
const moveSelected = (arrayIndex) => {
let tmpTestArrays = [...testArrays]
let tmpTestArraysSelected = [...testArraysSelected]
//Loops through all arrays and moves selected objects to the selected array
tmpTestArraysSelected.forEach((array, index) => {
//Does not add items that are already in the array
if (index !== arrayIndex) {
array.forEach((selection, selectionIndex) => {
if (selection === true) {
tmpTestArrays[arrayIndex].push(tmpTestArrays[index][selectionIndex])
}
})
}
})
for (let j = 0; j < tmpTestArraysSelected.length; j++) {
for (let i = tmpTestArraysSelected[j].length - 1; i >= 0; i--) {
//Does not remove the selected items from the target array
if (j === arrayIndex) {
break
}
console.log(tmpTestArraysSelected[j][i])
if (tmpTestArraysSelected[j][i]) {
tmpTestArraysSelected[j].splice(i, 1)
tmpTestArrays[j].splice(i, 1)
}
}
}
setTestArrays(tmpTestArrays)
setTestArraysSelected(tmpTestArraysSelected)
}
const selectItem = (position, arrayNumber) => {
let tmpArray = [...testArraysSelected]
tmpArray[arrayNumber][position] = !tmpArray[arrayNumber][position]
setTestArraysSelected(tmpArray)
}
return (
<div style={mainContainerStyle} >
<div style={tableContainerStyle}>
{testArrays.map((arrayObject, i) =>
<ExerciseArrayExtended testArray={arrayObject} key={i} testArraySelected={testArraysSelected[i]} selectItem={selectItem} arrayNumber={i} moveSelected={moveSelected} />
)}
</div>
</div >
);
}
export default Exercise1Extended;
|
Markdown
|
UTF-8
| 390
| 2.625
| 3
|
[] |
no_license
|
# Image Similarity Computation Based on Euclidean Distance
# Introduction
Using the color moments of the images which are extracted, we can calculate the similarity between the images by Euclidean distance.
้่ฟๆๅๅพๅ็้ข่ฒ็ฉ๏ผๅฉ็จๆฌงๅผ่ท็ฆปๆฑ่งฃๅพๅ้ด็็ธไผผๅบฆใ
# Environment
Windows 10
Matlab 2016
# Demo
https://youtu.be/pqk3qZQdJeY
|
Python
|
UTF-8
| 300
| 2.859375
| 3
|
[] |
no_license
|
from scanner import scanner
from solver import sudoku
scan = scanner(
"/home/zoh/Programming_Data/Projects/Sudoku_Solver/Pics/Train_data/4.jpg")
scan.getDigits()
grid = scan.grid
slv = sudoku(grid)
ifSolved = slv.solve()
if ifSolved == True:
slv.show()
else:
print("Couldn't Solve")
|
Java
|
UTF-8
| 3,254
| 2.5
| 2
|
[] |
no_license
|
package com.ez.framework.core.pojo;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import com.ez.framework.core.util.PojoClassInfo;
public abstract class AbsPojo implements IPojo {
/**
* <code>m_id</code> - ID.
*/
protected String m_id;
/**
* Constructor.
*/
public AbsPojo() {
}
/**
* get UUID key.
*
* @return UUID key.
*/
protected String getUUIDKey() {
return java.util.UUID.randomUUID().toString();
}
public String getId() {
if (this.m_id == null || this.m_id.length() == 0) {
this.m_id = getUUIDKey();
}
return this.m_id;
}
public void setId(String id) {
this.m_id = id;
}
public Object getFieldValueByName(String fieldName) {
if (null != fieldName && fieldName.length() > 0) {
PojoClassInfo t_clazzInfo = PojoClassInfo.getInstance(this.getClass());
if (null != t_clazzInfo) {
Method t_method = t_clazzInfo.getGetter(fieldName);
if (null != t_method) {
try {
return t_method.invoke(this, new Object[] {});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
return null;
}
public void setFieldValueByName(String fieldName, Object[] value) {
if (null != fieldName && fieldName.length() > 0) {
PojoClassInfo t_clazzInfo = PojoClassInfo.getInstance(this.getClass());
if (null != t_clazzInfo) {
Method t_method = t_clazzInfo.getSetter(fieldName);
if (null != t_method) {
try {
t_method.invoke(this, value);
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
}
public String[] getFieldNames(int type) {
PojoClassInfo t_clazzInfo = PojoClassInfo.getInstance(this.getClass());
if (null != t_clazzInfo) {
if (type == IPojo.S_FIELDTYPE_WRITE) {
return t_clazzInfo.getWriteablePropertyNames();
} else if (type == IPojo.S_FIELDTYPE_READ) {
return t_clazzInfo.getReadablePropertyNames();
}
}
return null;
}
public int hashCode() {
return new HashCodeBuilder(-1137714557, 409667233).appendSuper(super.hashCode()).append(this.m_id).toHashCode();
}
public boolean equals(Object object) {
if (!(object instanceof AbsPojo)) {
return false;
}
AbsPojo rhs = (AbsPojo) object;
return new EqualsBuilder().appendSuper(super.equals(object)).append(this.m_id, rhs.m_id).isEquals();
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
public Object deepClone() throws IOException, ClassNotFoundException {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(this);
oo.flush();
oo.close();
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi = new ObjectInputStream(bi);
return oi.readObject();
}
}
|
Python
|
UTF-8
| 1,294
| 3.921875
| 4
|
[] |
no_license
|
import gc
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
if self.head is not None:
self.head.prev = new_node
self.head = new_node
def delete(self, position):
if self.head == None:
return
temp = self.head
if(position==0):
self.head = temp.next
temp.next.prev=None
return
for i in range(position-1):
temp = temp.next
if temp is None:
break
if temp is None:
return
if temp.next is None:
return
next = temp.next.next
temp.next = next
next.prev = temp
gc.collect()
def printlist(self):
temp = self.head
while(temp is not None):
print(temp.data)
temp = temp.next
dll=DoublyLinkedList()
dll.push(4)
dll.push(3)
dll.push(2)
dll.push(1)
print("created linked list is :")
dll.printlist()
dll.delete(2)
print("modified linked list is:")
dll.printlist()
|
C#
|
UTF-8
| 1,174
| 3.09375
| 3
|
[] |
no_license
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LearnCSharp
{
class OverrideExample
{
public static void CallMe()
{
//nothing to call or display as of now
}
class MyConceptBase
{
//public virtual int value; // can't virtual because not allowed on fields
public virtual int number { get; set; }
public int EmpNumber { get; set; }
}
class MyConceptDerived : MyConceptBase
{
//overriding property from base. can't override fields because not allowed to defined them as virtual in base
public override int number
{
get
{
return base.number;
}
set
{
base.number = value;
}
}
public new string EmpNumber { get; set; }// this is called shadowing , so difference bewtween shadowing and overriding is
//overiding does not override type like int but shadow does
}
}
}
|
Java
|
UTF-8
| 549
| 2.34375
| 2
|
[] |
no_license
|
package com.anthill.to_sql.type;
public class TypeArg {
private String name;
private String dataType;
public String getName() {
return name;
}
public void setName(String name) {
name = (name != null) ? name.trim() : null;
this.name = (name != null && name.length() == 0) ? null : name;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
dataType = (dataType != null) ? dataType.trim() : null;
this.dataType = (dataType != null && dataType.length() == 0) ? null : dataType;
}
}
|
Java
|
UTF-8
| 238
| 2.671875
| 3
|
[] |
no_license
|
package com.cn.thread.runnable;
public class RunnableImpl1 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("RunnableImpl1 : " + i );
}
}
}
|
JavaScript
|
UTF-8
| 2,362
| 2.765625
| 3
|
[] |
no_license
|
// Row of a single course, used in course-table
import React, {useState} from 'react'
import {Link} from "react-router-dom";
const CourseRow = (
{
course,
title,
lastModified,
owner,
updateCourse,
deleteCourse
}) => {
const day = new Date();
const options = {year: 'numeric', month: 'numeric', day: 'numeric' };
const editorPath = "/courses/table/edit/".concat(course._id)
// useState() returns state and function that updates it
const [editing, setEditing] = useState(false)
const [newTitle, setNewTitle] = useState(title)
const saveCourse = () => {
setEditing(false);
if (newTitle === course.title) {return};
const newCourse = {
...course,
title: newTitle,
lastModified: day.toLocaleDateString(undefined, options),
}
updateCourse(newCourse);
}
return (
<tr>
{/*Title column*/}
<td>
{ !editing &&
<Link to={editorPath}>
<i className="fas fa-file fa-lg fa-fw mr-1 text-primary"/>
<span className="text-dark">{title}</span>
</Link>
}
{ editing &&
<input onChange={(event) => setNewTitle(event.target.value)}
value={newTitle}
className="form-control"/>
}
</td>
<td className="d-none d-sm-table-cell">
<Link
to={`/courses/${course._id}/quizzes`}>
Quizzes
</Link>
</td>
<td className="d-none d-sm-table-cell">{owner}</td>
<td className="d-none d-md-table-cell">{lastModified}</td>
{/*Icons for row, delete and edit only show when editing is true*/}
<td className="text-right">
{!editing && <i onClick={() => setEditing(true)} className="fas fa-edit fa-lg mr-2 text-primary"/>}
{editing && <i onClick={saveCourse} className="fas fa-check fa-lg mr-2 text-success"/>}
{editing && <i onClick={() => deleteCourse(course._id)} className="fas fa-minus-circle fa-lg mx-2 text-danger"/>}
</td>
</tr>
)
}
export default CourseRow
|
Markdown
|
UTF-8
| 2,216
| 3.328125
| 3
|
[
"MIT",
"CC-BY-3.0"
] |
permissive
|
<a name="FontDescriptor"></a>
## FontDescriptor
An object that contains information on a system font.
**Kind**: global class
* [FontDescriptor](#FontDescriptor)
* [new FontDescriptor(family, size, weight, italic, stretch)](#new_FontDescriptor_new)
* [.getFamily()](#FontDescriptor+getFamily) โ <code>string</code>
* [.getSize()](#FontDescriptor+getSize) โ <code>number</code>
* [.getWeight()](#FontDescriptor+getWeight) โ <code>number</code>
* [.getItalic()](#FontDescriptor+getItalic) โ <code>number</code>
* [.getStretch()](#FontDescriptor+getStretch) โ <code>number</code>
<a name="new_FontDescriptor_new"></a>
### new FontDescriptor(family, size, weight, italic, stretch)
Create a new FontDescriptor object.
| Param | Type | Description |
| --- | --- | --- |
| family | <code>string</code> | the name of the font, e.g. "Helvetica" |
| size | <code>number</code> | size in point of the font |
| weight | <code>number</code> | weight of the font |
| italic | <code>number</code> | 1 if the font is italic, otherwise 0 |
| stretch | <code>number</code> | horizontal stretch value for the font |
<a name="FontDescriptor+getFamily"></a>
### fontDescriptor.getFamily() โ <code>string</code>
Return the name of the font, e.g. "Helvetica".
**Kind**: instance method of [<code>FontDescriptor</code>](#FontDescriptor)
<a name="FontDescriptor+getSize"></a>
### fontDescriptor.getSize() โ <code>number</code>
Return the size in point of the font.
**Kind**: instance method of [<code>FontDescriptor</code>](#FontDescriptor)
<a name="FontDescriptor+getWeight"></a>
### fontDescriptor.getWeight() โ <code>number</code>
Return weight of the font.
**Kind**: instance method of [<code>FontDescriptor</code>](#FontDescriptor)
<a name="FontDescriptor+getItalic"></a>
### fontDescriptor.getItalic() โ <code>number</code>
Return 1 if the font is italic, otherwise 0.
**Kind**: instance method of [<code>FontDescriptor</code>](#FontDescriptor)
<a name="FontDescriptor+getStretch"></a>
### fontDescriptor.getStretch() โ <code>number</code>
Return horizontal stretch value for the font.
**Kind**: instance method of [<code>FontDescriptor</code>](#FontDescriptor)
|
Java
|
UTF-8
| 1,665
| 2.359375
| 2
|
[] |
no_license
|
package model.dto;
public class UserIllnessDto {
private Integer idU;
private String cnp;
private String bloodGroup;
private String nameUser;
//private Integer idI;
private String nameIllness;
private String description;
public UserIllnessDto(Integer idU, String cnp, String bloodGroup, String nameUser, String nameIllness, String description) {
this.idU = idU;
this.cnp = cnp;
this.bloodGroup = bloodGroup;
this.nameUser = nameUser;
//this.idI = idI;
this.nameIllness = nameIllness;
this.description = description;
}
public Integer getIdU() {
return idU;
}
public void setIdU(Integer idU) {
this.idU = idU;
}
public String getCnp() {
return cnp;
}
public void setCnp(String cnp) {
this.cnp = cnp;
}
public String getBloodGroup() {
return bloodGroup;
}
public void setBloodGroup(String bloodGroup) {
this.bloodGroup = bloodGroup;
}
public String getNameUser() {
return nameUser;
}
public void setNameUser(String nameUser) {
this.nameUser = nameUser;
}
/*public Integer getIdI() {
return idI;
}
public void setIdI(Integer idI) {
this.idI = idI;
}*/
public String getNameIllness() {
return nameIllness;
}
public void setNameIllness(String nameIllness) {
this.nameIllness = nameIllness;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
Java
|
UTF-8
| 3,590
| 2.828125
| 3
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package apptransi;
import java.util.ArrayList;
/**
*
* @author pcsiecon
*/
public class Transi {
private ArrayList<Alumno> alumnos;
public Transi() {
alumnos = new ArrayList<Alumno>();
}
/**
* @return the alumnos
*/
public ArrayList<Alumno> getAlumnos() {
return alumnos;
}
public void registrarAlumno(String codigo, String nombre, String modalidad) {
this.alumnos.add(new Alumno(codigo, nombre, modalidad));
}
public Alumno buscarAlumno(String codigoAlumno) {
Alumno alumnoEncontrado = null;
for (Alumno alumno : alumnos) {
if (alumno.getCodigo().equals(codigoAlumno)) {
alumnoEncontrado = alumno;
break;
}
}
return alumnoEncontrado;
}
public void eliminarAlumno(String codigoAlumno) {
Alumno alumno = buscarAlumno(codigoAlumno);
alumnos.remove(alumno);
}
public double calcularPromedioFinalMayor() {
double promedioMayor = 0.0;
for (Alumno alumno : alumnos) {
double promedioAlumno = alumno.getCalificacion().calcularPromedioFinal();
if (promedioAlumno > promedioMayor) {
promedioMayor = promedioAlumno;
break;
}
}
return promedioMayor;
}
public double calcularPromedioFinalMenor() {
double promedioMenor = calcularPromedioFinalMayor();
for (Alumno alumno : alumnos) {
double promedioAlumno = alumno.getCalificacion().calcularPromedioFinal();
if (promedioAlumno < promedioMenor) {
promedioMenor = promedioAlumno;
break;
}
}
return promedioMenor;
}
public double calcularPromedioSalon() {
double promedioSalon = 0.0;
if (!alumnos.isEmpty()) {
for (Alumno alumno : alumnos) {
promedioSalon += alumno.getCalificacion().calcularPromedioFinal();
}
promedioSalon = promedioSalon / alumnos.size();
}
return promedioSalon;
}
public boolean registrarCalificacionTradicional(String codigoAlumno, double examenParcial, double examenFinal, double practica1, double practica2) {
Alumno alumno = buscarAlumno(codigoAlumno);
if (alumno != null) {
alumno.getCalificacion().setExamenParcial(examenParcial);
alumno.getCalificacion().setExamenFinal(examenFinal);
((CalificacionTradicional) alumno.getCalificacion()).setPractica1(practica1);
((CalificacionTradicional) alumno.getCalificacion()).setPractica2(practica2);
return true;
} else {
return false;
}
}
public boolean registrarCalificacionPractica(String codigoAlumno, double examenParcial, double examenFinal, double trabajo1, double trabajo2, double proyecto) {
Alumno alumno = buscarAlumno(codigoAlumno);
if (alumno != null) {
alumno.getCalificacion().setExamenParcial(examenParcial);
alumno.getCalificacion().setExamenFinal(examenFinal);
((CalificacionPractica) alumno.getCalificacion()).setTrabajo1(trabajo1);
((CalificacionPractica) alumno.getCalificacion()).setTrabajo2(trabajo2);
((CalificacionPractica) alumno.getCalificacion()).setProyecto(proyecto);
return true;
} else {
return false;
}
}
}
|
Python
|
UTF-8
| 2,307
| 3.171875
| 3
|
[] |
no_license
|
import sys
import traceback
class Screen():
'''ๅฑๅน็ฑป็จๆฅ็ฎก็็ปๅถๅฑๅนๅพๅ'''
def __init__(self, setting, pygame):
'''ๅๅงๅ'''
self.pygame = pygame
if setting.fullScreenDisplay:
# pygame.HWSURFACE #็กฌไปถๅ ้๏ผ#ไป
ๅ
จๅฑๆจกๅผ
# pygame.DOUBLEBUF #ๅ็ผๅฒ
# pygame.FULLSCREEN #ๅ
จๅฑๆพ็คบ
self.screen = pygame.display.set_mode(
(setting.screenWidth, setting.screenHeight), pygame.FULLSCREEN|pygame.HWSURFACE|pygame.DOUBLEBUF) # ๅๅปบๅฑๅน,่กจ็คบๅ
จๅฑ
else:
self.screen = pygame.display.set_mode((setting.screenWidth, setting.screenHeight),pygame.DOUBLEBUF)
self.rect = self.screen.get_rect()
self.elementList = [] # ่ฆ็ปๅถๅจๅฑๅนไธ็ๅ
็ด
self.tempElementList = [] # ่ฆไธดๆถ็ปๅถๅจๅฑๅนไธ็ๅ
็ด
self.scene = None # ๅบๆฏ
pygame.display.set_caption(setting.screenTitle) # ่ฎพ็ฝฎๅฑๅนๆ ้ข
def update(self, data):
'''ๆดๆฐๅฑๅนๅ
ๅฎน'''
elementList = [self.scene]
elementList.extend(self.elementList)
elementList.extend(self.tempElementList)
for element in elementList:
# try:
# if element == None:
# continue
element.update(data)
# except Exception as e:
# e.print_stack()
# print(e)
# print("ๆดๆฐๅคฑ่ดฅ๏ผ่ทณ่ฟ")
def draw(self):
# self.scene.draw() #็ปๅถๅบๆฏ
elementList = [self.scene]
elementList.extend(self.elementList)
elementList.extend(self.tempElementList)
for element in elementList:
# try:
# # print(element.rect)
if element == None:
continue
element.draw(self.screen,self.rect) #็ปๅถ
# # self.screen.blit(element.image, element.rect) # ็ปๅถ
# except Exception as e:
# traceback.print_stack()
# print(e)
# print("็ปๅถ้่ฏฏ๏ผ่ทณ่ฟ")
# self.pygame.display.flip() # ๆดๆฐๆพ็คบ
self.pygame.display.update() # ๆดๆฐๆพ็คบ
self.tempElementList = [] #ๆธ
็ฉบไธดๆถๅ
็ด ๅ่กจ
|
Java
|
UTF-8
| 2,788
| 2.96875
| 3
|
[] |
no_license
|
package com.niuan.common.ezyer.util.thread;
/**
* BackgroundTaskๆฏๅจๅๅฐ่ฟ่ก็ไปปๅก๏ผ่ฏฅไปปๅกไผๆ นๆฎexecutorId็ไธๅ่ขซๅฎๆๅจไธๅ็บฟ็จ๏ผ
* ็ธๅexecutorId็ไปปๅกไผ่ฟ่กๅจ็ธๅ็็บฟ็จ๏ผๅนถไธๆ นๆฎexecute่ฐ็จๆนๆณ็ๅ
ๅ้กบๅบ่่ฟ่กๆ้๏ผๅ
่ฐ็จ็ไผๅ
ๆง่ก
*
* @author carlosliu
*
*/
public abstract class BackgroundTask<PARAMS, PROGRESS, RESULT> {
private boolean mIsCanceled;
public static final int EXECUTOR_ID_DEFAULT = 1001;
public static final int EXECUTOR_ID_DAEMON = 1002;
private int mExecutorId = EXECUTOR_ID_DEFAULT;
public int getExecutorId() {
return mExecutorId;
}
public void setExecutorId(int executorId) {
this.mExecutorId = executorId;
mExecutor = TaskExecutor.getInstance(mExecutorId);
}
/**
* ่ฟๅๅฝๅไปปๅกๆๅจ็executor๏ผ้กปๅจ่ฐ็จ{@link #setExecutorId(int)}ๆ่
* {@link #execute(Object...)} ๆ่
{@link #executeNow(Object...)} ไนๅ
*
* @return the executor for current task, will be null if task not
* initialized
*/
public TaskExecutor getExecutor() {
return mExecutor;
}
private void ensureExecutor() {
if (mExecutor == null) {
mExecutor = TaskExecutor.getInstance(mExecutorId);
}
}
public boolean isCanceled() {
return mIsCanceled;
}
private TaskExecutor mExecutor;
public BackgroundTask() {
}
/**
* ไผ่ขซTaskExecutor่ฐ็จ๏ผ่ฟ่กไบๅๅฐ็บฟ็จ
*/
void callbackFromBackgroundThread() {
result = doInBackground(params);
}
/**
* ๅฝdoInBackground่ฐ็จๅฎๆฏๅ๏ผไผ่ฐ็จonPosExecuteๆนๆณๅๅฐUI็บฟ็จ
*/
void onPostExecute() {
onPostExecute(result);
}
/**
* return progress in ui thread
*
* @see #publishProgress(Object)
*
* @param progress
*/
protected void onProgressUpdate(PROGRESS progress) {
}
/**
* call this method in {@link #doInBackground(Object...)}
*
* @param progress
*/
protected void publishProgress(final PROGRESS progress) {
mExecutor.runOnUiThread(new Runnable() {
@Override
public void run() {
onProgressUpdate(progress);
}
});
}
protected void onPreExecute(boolean pending) {
}
protected abstract RESULT doInBackground(PARAMS... params);
protected void onPostExecute(RESULT result) {
};
private PARAMS[] params;
private RESULT result;
/**
* ๅฐไปปๅกๆทปๅ ๅฐ้ๅ๏ผๅฆๆ็บฟ็จๆๅ๏ผไผๅค้็บฟ็จ็ปง็ปญๆง่กไปปๅก
*
* @param params
*/
public void execute(PARAMS... params) {
this.params = params;
ensureExecutor();
mExecutor.execute(this);
}
/**
* ๅฐ่ฏฅไปปๅกๆๅจ้ๅๆๅ้ข๏ผๅฆๆ็บฟ็จๆๅ๏ผไผๅค้็บฟ็จ็ปง็ปญๆง่กไปปๅก
*
* @param params
*/
public void executeNow(PARAMS... params) {
this.params = params;
ensureExecutor();
mExecutor.executeNow(this);
}
}
|
Java
|
UTF-8
| 748
| 3.84375
| 4
|
[] |
no_license
|
package com.test.mvnmyExample;
import java.util.Random;
public class IntRand {
/**
* Initialises array & sums numbers uses static methods The array consists
* of randomly generated ints
*/
public static int[] popArray(int size) {
// initialising array
int[] myArray = new int[size];
// creating the random number generator
Random randGenerator = new Random(11);
for (int i = 0; i < size; i++) {
// will produce pseudo random ints
myArray[i] = randGenerator.nextInt();
}
return myArray;
}
public static int cumCount(int[] theArray) {
// Cumulative sum of numbers in array
int size = theArray.length;
int count = 0;
for (int i = 0; i < size; i++) {
count = count + theArray[i];
}
return count;
}
}
|
Java
|
UTF-8
| 2,929
| 2.171875
| 2
|
[] |
no_license
|
package com.cg.fds.service;
import java.util.Optional;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.function.Executable;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import com.cg.fds.entities.CartItem;
import com.cg.fds.entities.FoodCart;
import com.cg.fds.entities.Item;
import com.cg.fds.exception.InvalidCartException;
import com.cg.fds.repository.ICartItemRepository;
import com.cg.fds.repository.ICartRepository;
import com.cg.fds.repository.IItemRepository;
@ExtendWith(MockitoExtension.class)
public class CartServiceImpUnitTest {
@Mock
ICartRepository cartRepository;
@Mock
IItemRepository itemRepository;
@Mock
ICartItemRepository cartItemRepository;
@Spy
@InjectMocks
CartServiceImp cartService;
/**
* scenario when items exist in cart before , items list is not null
*/
@Test
void addItemToCartTest_1() {
FoodCart cart = Mockito.mock(FoodCart.class);
Item item = Mockito.mock(Item.class);
Mockito.doNothing().when(cartService).validateCart(cart);
Mockito.doReturn(cart).when(cartService).increaseQuantity(cart, item, 1);
FoodCart result = cartService.addItemToCart(cart, item);
Assertions.assertNotNull(result);
Assertions.assertEquals(cart, result);
Mockito.verify(cartService).increaseQuantity(cart, item, 1);
Mockito.verify(cartService).validateCart(cart);
}
/**
* scenario , cart is null
*/
@Test
void addItemToCartTest_2() {
FoodCart cart = Mockito.mock(FoodCart.class);
Mockito.doThrow(InvalidCartException.class).when(cartService).validateCart(cart);
Executable executable = () -> cartService.validateCart(cart);
Assertions.assertThrows(InvalidCartException.class, executable);
}
@Test
void removeTest_1() {
String cartItemId = "string";
FoodCart cart = Mockito.mock(FoodCart.class);
Mockito.doNothing().when(cartService).validateCart(cart);
// CartItem cartItem=Mockito.mock(CartItem.class);
Item item = Mockito.mock(Item.class);
Mockito.when(CartItem.id(cart, item)).thenReturn(cartItemId);
FoodCart result = cartService.removeItem(cart, item);
Assertions.assertNotNull(result);
Assertions.assertEquals(cart, result);
Mockito.verify(cartService).validateCart(cart);
}
@Test
void clearCartTest_1() {
FoodCart cart = Mockito.mock(FoodCart.class);
Mockito.doNothing().when(cartService).validateCart(cart);
FoodCart result = cartService.clearCart(cart);
Assertions.assertNotNull(result);
Assertions.assertEquals(cart, result);
Mockito.verify(cartService).validateCart(cart);
}
@Test
public void validateCartTest() {
FoodCart cart = null;
Executable executable = () -> cartService.validateCart(cart);
Assertions.assertThrows(InvalidCartException.class, executable);
}
}
|
Shell
|
UTF-8
| 644
| 3.0625
| 3
|
[] |
no_license
|
#!/bin/bash
cd "$(dirname "$0")"
# Start up Google Compute Engine instances
cd terraform
terraform apply
# Create ansible hosts file
cat <<EOS >../ansible/hosts
[master]
$(terraform output -json instance_ips | jq '.[0]' | tr -d '"')
[slave]
$(terraform output -json instance_ips | jq -r '.[1:] | join("\n")' | tr -d '"')
EOS
# Create MPI hosts file
cat <<EOS >../ansible/roles/master/files/hosts
# master
$(terraform output -json instance_names | jq '.[0]' | tr -d '"')
# slave
$(terraform output -json instance_names | jq -r '.[1:] | join("\n")' | tr -d '"')
EOS
# Configure MPI cluster
cd ../ansible
ansible-playbook site.yml -i hosts
|
JavaScript
|
UTF-8
| 757
| 3.09375
| 3
|
[] |
no_license
|
function validateFirstName(data){
var ans = "";
if(data.trim() == ""){
ans = "This is required!";
}
return ans;
}
function validateLastName(data){
var ans = "";
if(data.trim() == ""){
ans = "This is required!";
}
return ans;
}
function validateMobileNumber(data){
var ans = "";
if(isNaN(data)){
ans = "Invalid Cellphone Number!";
}
return ans;
}
function validateBirthday(data){
var ans = "";
if(data.trim() == ""){
ans = "This is required!";
}
return ans;
}
function validateAddress(data){
var ans = "";
if(data.trim() == ""){
ans = "This is required!";
}
return ans;
}
function validatePhysicianNumber(data){
var ans = "";
if(isNaN(data)){
ans = "Invalid Cellphone Number!";
}
return ans;
}
|
Markdown
|
UTF-8
| 1,293
| 3.421875
| 3
|
[] |
no_license
|
# Weather
These are examples from the [Exploring Data tutorial](https://vega.github.io/vega-lite/tutorials/getting_started.html).
---
Letโs use a tick mark to show the distribution of precipitation.
<div id='tick'></div>
To better see the distribution of precipitation data, we can create a histogram.
<div id='histogram'></div>
Letโs look at how precipitation in Seattle changes throughout the year.
<div id='month'></div>
Let's aggregate by year and month (yearmonth) rather than just month. This allows us to see seasonal trends but for each year separately.
<div id='yearmonth'></div>
Is maximum temperature increasing from year to year? Letโs create a chart that shows the mean of the maximum daily temperatures.
<div id='temp-by-year'></div>
What about the variability of the temperatures changes throughout the year?
<div id='variability'></div>
We might wish to know how different kinds of weather (e.g. sunny days or rainy days) are distributed throughout the year.
<div id='weather-types'></div>
We can further tune the chart by providing a color scale range that maps the values from the weather field to meaningful colors (e.g. sun should be yellow, not green). In addition, we can customize the axis and legend titles.
<div id='weather-types-color'></div>
|
C++
|
UTF-8
| 13,614
| 2.546875
| 3
|
[] |
no_license
|
#pragma once
// This has 2 classes
// A) MonoGeometry
// B) StereoGeometry
//opencv
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <string>
#include "camodocal/camera_models/Camera.h"
#include "camodocal/camera_models/CameraFactory.h"
#include "camodocal/camera_models/CataCamera.h"
#include "camodocal/camera_models/EquidistantCamera.h"
#include "MiscUtils.h"
#include "ElapsedTime.h"
#include "PoseManipUtils.h"
#include "TermColor.h"
// Threads and threadsafety
#include <thread>
#include <mutex>
#include <atomic>
class MonoGeometry {
public:
MonoGeometry() { }
MonoGeometry(camodocal::CameraPtr _camera );
// Set the new intrinsic matrix (optional). By default will use the same as
// the abstract camera. but the K matrix is essentially just scaling pixel sizes.
// this comes to play in stereopairs and/or motion stereo.
void set_K( Matrix3d K );
// this is just a call to cv::remap with the maps already computed.
void do_image_undistortion( const cv::Mat& im_raw, cv::Mat & im_undistorted );
private:
camodocal::CameraPtr camera;
Matrix3d K_new;
float new_fx, new_fy, new_cx, new_cy;
cv::Mat map_x, map_y;
std::mutex m;
};
// There are 3 types of images
// im*_raw
// im*_undistorted
// im*_stereo_rectified
class StereoGeometry {
public:
// right_T_left: extrinsic calibration for stereo pair. The position of left camera as viewed from right camera.
StereoGeometry( camodocal::CameraPtr _left_camera,
camodocal::CameraPtr _right_camera,
const Matrix4d& right_T_left
);
// intrinsic cam matrix for both cameras. Here it is important to set this
// else the block matching computation won't be valid. If this is not set
// we will use the matrix for left camera as K_new.
// Everytime a new K is set, we have to recompute the maps.
void set_K( Matrix3d K );
void set_K( float _fx, float _fy, float _cx, float _cy );
const Matrix3d& get_K();
// set extrinsic. THis is thread safe
// Everytime a new extrinsic is set, we have to recompute the maps.
void set_stereoextrinsic( Matrix4d __right_T_left );
void set_stereoextrinsic( Vector4d quat_xyzw, Vector3d tr_xyz );
const Matrix4d& get_stereoextrinsic();
void fundamentalmatrix_from_stereoextrinsic( Matrix3d& F );
//TODO write another function to return fundamental matrix of rectified stereo pair.
// Draw epipolar lines on both views. These images will be overwritten. You need
// to give me undistorted image-pairs. You can undistory image pair with
// StereoGeometry::do_image_undistortion()
void draw_epipolarlines( cv::Mat& imleft_undistorted, cv::Mat& imright_undistorted );
void draw_srectified_epipolarlines( cv::Mat& imleft_srectified, cv::Mat& imright_srectified );
void do_image_undistortion( const cv::Mat& imleft_raw, const cv::Mat& imright_raw,
cv::Mat& imleft_undistorted, cv::Mat& imright_undistorted
);
// given the undistorted images outputs the stereo-rectified pairs
// This is essentially just cv::remap using the stereo-rectification maps
void do_stereo_rectification_of_undistorted_images(
const cv::Mat& imleft_undistorted, const cv::Mat& imright_undistorted,
cv::Mat& imleft_srectified, cv::Mat& imright_srectified );
// Given raw image pair return stereo-rectified pair. This is a 2 step process
// raw --> undistorted --> stereo rectified
void do_stereo_rectification_of_raw_images(
const cv::Mat& imleft_raw, const cv::Mat& imright_raw,
cv::Mat& imleft_srectified, cv::Mat& imright_srectified );
// stereo rectified --> disparity. Uses the stereo-block matching algorithm,
// ie. cv::StereoBM
// if you use this function, besure to call `do_stereo_rectification_of_undistorted_images`
// or `do_stereo_rectification_of_raw_images` on your images before calling this function.
// returned disparity is CV_16SC1. Be cautioned.
void do_stereoblockmatching_of_srectified_images(
const cv::Mat& imleft_srectified, const cv::Mat& imright_srectified,
cv::Mat& disparity
);
// raw--> disparity
// internally does:
// step-1: raw-->undistorted
// step-2: undistorted--> srectify (stereo rectify)
// step-3: srectify --> disparity
void do_stereoblockmatching_of_raw_images(
const cv::Mat& imleft_raw, const cv::Mat& imright_raw,
cv::Mat& disparity
);
// undistorted --> disparity
// step-1: undistorted --> srectified
// step-2 : srectified --> disparity
void do_stereoblockmatching_of_undistorted_images(
const cv::Mat& imleft_undistorted, const cv::Mat& imright_undistorted,
cv::Mat& disparity
);
// # Inputs
// disparity_raw : The disparity image
// fill_eigen_matrix : _3dpts will be allocated and filled only if this flag is true. If this flag is false then eigen matrix is not filled in this function.
// make_homogeneous : true will result in Eigen matrix being 4xN else will be 3xN. fill_eigen_matrix need to be true for this to matter.
// # Outputs
// out3d : 3 channel image. X,Y,Z --> ch0, ch1, ch2. Will also contain invalid 3d points.
// _3dpts : 4xN matrix containing only valid points. N < disparity_raw.shape[0]*disparity_raw.shape[1].
void disparity_to_3DPoints(const cv::Mat& disparity_raw,
cv::Mat& out3D, MatrixXd& _3dpts,
bool fill_eigen_matrix=true, bool make_homogeneous=true );
// #Input
// imleft_raw, imright_raw : Raw images. As is from the camera.
// # Output
// _3dpts : 4xN
// 1. raw --> srectified
// 2. srectified --> disparity_raw
// 3. disparity_raw --> 3d points
void get3dpoints_from_raw_images( const cv::Mat& imleft_raw, const cv::Mat& imright_raw,
MatrixXd& _3dpts );
// #Input
// imleft_raw, imright_raw : Raw images. As is from the camera.
// # Output
// _3dpts : 4xN
// 1. raw --> srectified
// 2. srectified --> disparity_raw
// 3. disparity_raw --> 3d points
// _3dImage: 3d points as 3 channel image. 1st channel is X, 2nd channel is Y and 3rd channel is Z.
void get3dpoints_and_3dmap_from_raw_images( const cv::Mat& imleft_raw, const cv::Mat& imright_raw,
MatrixXd& _3dpts, cv::Mat& _3dImage );
// returns both 3dpoints and 3dimage along with srectified image pair
void get3dpoints_and_3dmap_from_raw_images( const cv::Mat& imleft_raw, const cv::Mat& imright_raw,
MatrixXd& _3dpts, cv::Mat& _3dImage,
cv::Mat& imleft_srectified, cv::Mat& imright_srectified );
// #Input
// imleft_raw, imright_raw : Raw images. As is from the camera.
// # Output
// _3dImage: 3d points as 3 channel image. 1st channel is X, 2nd channel is Y and 3rd channel is Z.
// Also note that these co-ordinates and imleft_raw co-ordinate do not correspond. They correspond to
// the srectified images. Incase you want to use the color info with these 3d points, this
// will lead to wrong. You should compute the srectified images for that.
// 1. raw --> srectified
// 2. srectified --> disparity_raw
// 3. disparity_raw --> 3d points
void get3dmap_from_raw_images( const cv::Mat& imleft_raw, const cv::Mat& imright_raw,
cv::Mat& _3dImage );
// #Input
// imleft_raw, imright_raw : Raw images. As is from the camera.
// # Output
// e_3dImageX, e_3dImageY, e_3dImageZ: cv::split( _3dImage ). same size as imleft_raw.shape.
// Also note that these co-ordinates and imleft_raw co-ordinate do not correspond. They correspond to
// the srectified images. Incase you want to use the color info with these 3d points, this
// will lead to wrong. You should compute the srectified images for that.
// 1. raw --> srectified
// 2. srectified --> disparity_raw
// 3. disparity_raw --> 3d points
void get3dmap_from_raw_images( const cv::Mat& imleft_raw, const cv::Mat& imright_raw,
MatrixXd& e_3dImageX, MatrixXd& e_3dImageY, MatrixXd& e_3dImageZ );
// Given raw image pair returns valid 3d points and disparity false color map.
// #Input
// imleft_raw, imright_raw : Raw images. As is from the camera.
// #Output
// _3dpts : 4xN matrix.
// disparity_for_visualization : false color mapped for visualization only. Don't do any processing with this one.
void get3dpoints_and_disparity_from_raw_images( const cv::Mat& imleft_raw, const cv::Mat& imright_raw,
MatrixXd& _3dpts, cv::Mat& disparity_for_visualization );
// Given raw image pair return a) stereo-rectified image pair b) valid 3d points c) disparity false color map
void get_srectifiedim_and_3dpoints_and_disparity_from_raw_images(
const cv::Mat& imleft_raw, const cv::Mat& imright_raw,
cv::Mat& imleft_srectified, cv::Mat& imright_srectified,
MatrixXd& _3dpts, cv::Mat& disparity_for_visualization );
void get_srectifiedim_and_3dpoints_and_3dmap_and_disparity_from_raw_images(
const cv::Mat& imleft_raw, const cv::Mat& imright_raw,
cv::Mat& imleft_srectified, cv::Mat& imright_srectified,
MatrixXd& _3dpts, cv::Mat& _3dImage, cv::Mat& disparity_for_visualization );
// colorize a disparity map
// #Input:
// disp_raw: The raw disparity, CV_16SC1. This is not strict, haven't tested other input data types
// #Output:
// disparity_for_visualization_gray: hot color mapping of the above, CV_8UC3
void disparity_to_falsecolormap( const cv::Mat& disp_raw, cv::Mat& disparity_for_visualization_gray );
// Given a disparity map, convert to depthmap.
// depth_ij = focal_length * baseline / disparity_ij
// #input:
// disp_raw: Disparity
// #Output:
// depth: CV_32FC1
void disparity_to_depth( const cv::Mat& disp_raw, cv::Mat& depth );
// Some semi private getters of internal variables
public:
const cv::Mat& get_Q() const { return rm_Q; }
// TODO: (if need be) also have getters from rm_R1, rm_R2, rm_P1, rm_P2, rm_shift, rm_fundamental_matrix.
const cv::Mat& get_rm_R1( ) const { return rm_R1; }
const cv::Mat& get_rm_R2( ) const { return rm_R2; }
const cv::Mat& get_rm_P1( ) const { return rm_P1; }
const cv::Mat& get_rm_P2( ) const { return rm_P2; }
void print_blockmatcher_algo_info();
private:
camodocal::CameraPtr camera_left, camera_right;
Matrix4d right_T_left; ///< extrinsic calibration of the stereopair.
Matrix3d K_new;
float new_fx, new_fy, new_cx, new_cy;
std::shared_ptr<MonoGeometry> left_geom, right_geom;
// stereo rectify maps
// theory : http://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/FUSIELLO/tutorial.html
mutable std::mutex m_extrinsics;
mutable std::mutex m_intrinsics;
// This function is called everytime you change the intrinsics and extrinsics for
// the stereo pair. This outputs the stereo-rectification maps, ie. map1_x, map1_y, map2_x, map2_y
// This is not intended to be a public call.
// TODO: thread safety
void make_stereo_rectification_maps();
cv::Mat rm_R1, rm_R2, rm_P1, rm_P2, rm_Q;
Vector3d rm_shift; // right_T_left
Matrix3d rm_fundamental_matrix; // fundamental matrix after rectification
cv::Mat map1_x, map1_y, map2_x, map2_y;
// Stereo Block Matching
cv::Ptr<cv::StereoBM> bm;
cv::Ptr<cv::StereoSGBM> sgbm;
};
class GeometryUtils {
public:
// Given the focal length make a K out of it
static void make_K( float new_fx, float new_fy, float new_cx, float new_cy, Matrix3d& K );
// For a camera gets a K
static void getK( camodocal::CameraPtr m_cam, Matrix3d& K );
// Ideal Projection:
// a) c_X = c_X / c_X.row(2). ==> Z divide
// b) perspective_proj = c_X.topRows(3)
// c) uv = K * c_X
// # Input
// K : Camera params. K_new
// c_X : 3D points expressed in frame of the camera.
// Note that if you have world 3d points you will need to transform
// it to camera co-ordinates before you pass it to this function.
// uv : image co-ordinates (xy)
static void idealProjection( const Matrix3d& K, const MatrixXd& c_X, MatrixXd& uv );
static void idealProjection( const Matrix3d& K, const vector<Vector3d>& c_X, MatrixXd& uv );
static void idealProjection( const Matrix3d& K, const Matrix4d& w_T_c, const vector<Vector3d>& c_X, MatrixXd& uv );
// given a point cloud as 3xN or 4xN matrix, gets colors for each based on the depth
// min==-1 then we will compute the min from data, else will use whatever was supplied
// max==-1 then we will compute the max from data, else will use whatever.
static void depthColors( const MatrixXd& ptcld, vector<cv::Scalar>& out_colors, double min=-1, double max=-1 );
static void depthColors( const MatrixXd& ptcld, MatrixXd& out_colors, double min=-1, double max=-1 ); // out_colors : 3xN rgb \in [0,1]
};
|
C#
|
UTF-8
| 1,172
| 3.5625
| 4
|
[] |
no_license
|
๏ปฟusing System;
namespace ClientApplicationFactoryDesignPattern
{
class Program
{
static void Main(string[] args)
{
//Console.WriteLine("Hello World!");
CardFactory factory = null;
Console.WriteLine("Enter the card type you would like to visit: ");
string car = Console.ReadLine();
switch (car.ToLower())
{
case "moneyback":
factory = new MoneyBackFactory(50000, 0);
break;
case "titanium":
factory = new TitaniumFactory(100000, 0);
break;
case "platinum":
factory = new PlatinumFactory(500000, 1000);
break;
default:
break;
}
CreditCard creditCard = factory.GetCreditCard();
Console.WriteLine("\nYour card details are below: \n");
Console.WriteLine($"Card Type: {creditCard.CardType}\nCredit Limit: {creditCard.CreditLimit}\nAnnual Charge: {creditCard.AnnualCharge}");
Console.ReadKey();
}
}
}
|
PHP
|
UTF-8
| 489
| 3.515625
| 4
|
[] |
no_license
|
<?php
class Deck
{
protected $cards = array(), $index;
protected $available_suits = array(
'hearts',
'spades',
'clubs',
'diamonds'
);
public function __construct()
{
foreach ($this->available_suits as $suit) {
for ($i = 1; $i <= 13; $i++) {
$this->cards[] = new Card($i, $suit);
}
}
$this->index = 0;
}
public function shuffle()
{
shuffle($this->cards);
$this->index = 0;
}
public function deal() {
return $this->cards[$this->index++];
}
}
|
Java
|
UTF-8
| 4,268
| 2.484375
| 2
|
[] |
no_license
|
package me.IcanR.CombatGui;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin implements Listener {
public Inventory inv;
@Override
public void onEnable() {
this.getServer().getPluginManager().registerEvents(this, this);
createInv();
}
@Override
public void onDisable( ) {
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (label.equalsIgnoreCase("combat")) {
if(!(sender instanceof Player)) {
sender.sendMessage(ChatColor.DARK_RED + "" + "Console join server to do this");
return true;
}
Player player = (Player) sender;
//GUI
player.openInventory(inv);
return true;
}
return false;
}
@EventHandler()
public void onClick(InventoryClickEvent event) {
if (!event.getInventory().equals(inv))
return;
if (event.getCurrentItem() == null) return;
if (event.getCurrentItem().getItemMeta() == null) return;
if (event.getCurrentItem().getItemMeta().getDisplayName() == null) return;
event.setCancelled(true);
Player player = (Player) event.getWhoClicked();
if (event.getSlot() == 0) {
//crossbow
player.performCommand("combatcrossbow");
player.sendMessage(ChatColor.GOLD + "This your item");
}
if (event.getSlot() == 1) {
//sword
player.performCommand("combatsword");
player.sendMessage(ChatColor.GOLD + "This your item");
}
if (event.getSlot() == 2) {
//shotgun
player.performCommand("shotgun");
player.sendMessage(ChatColor.GOLD + "This your item");
}
if (event.getSlot() == 8) {
player.closeInventory();
}
return;
}
public void createInv() {
inv = Bukkit.createInventory(null, 9,ChatColor.BLUE + "" + ChatColor.BOLD + "Combat List");
ItemStack item = new ItemStack(Material.CROSSBOW);
ItemMeta meta = item.getItemMeta();
//CrossBow
meta.setDisplayName(ChatColor.YELLOW + "COMBAT CROSSBOW");
List<String> lore = new ArrayList<String>();
lore.add(ChatColor.GRAY + "Click to select CrossBow");
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(0, item);
//Sword
item.setType(Material.DIAMOND_SWORD);
meta.setDisplayName(ChatColor.DARK_BLUE + "COMBAT SWORD");
item.setItemMeta(meta);
inv.setItem(1, item);
//ShotGun
item.setType(Material.GOLDEN_HORSE_ARMOR);
meta.setDisplayName(ChatColor.DARK_PURPLE + "COMBAT GUN");
item.setItemMeta(meta);
inv.setItem(2, item);
//ComingSoon
item.setType(Material.LIGHT_GRAY_STAINED_GLASS_PANE);
meta.setDisplayName(ChatColor.DARK_RED + "COOMING SOON");
item.setItemMeta(meta);
inv.setItem(3, item);
//ComingSOOn
item.setType(Material.LIGHT_GRAY_STAINED_GLASS_PANE);
meta.setDisplayName(ChatColor.DARK_RED + "COOMING SOON");
item.setItemMeta(meta);
inv.setItem(4, item);
//COmingSooN
item.setType(Material.LIGHT_GRAY_STAINED_GLASS_PANE);
meta.setDisplayName(ChatColor.DARK_RED + "COOMING SOON");
item.setItemMeta(meta);
inv.setItem(5, item);
//ComingsOOn
item.setType(Material.LIGHT_GRAY_STAINED_GLASS_PANE);
meta.setDisplayName(ChatColor.DARK_RED + "COOMING SOON");
item.setItemMeta(meta);
inv.setItem(6, item);
//CoMingsOOn
item.setType(Material.LIGHT_GRAY_STAINED_GLASS_PANE);
meta.setDisplayName(ChatColor.DARK_RED + "COOMING SOON");
item.setItemMeta(meta);
inv.setItem(8, item);
//close button
item.setType(Material.BARRIER);
meta.setDisplayName(ChatColor.RED + "" + ChatColor.BOLD + "Close Menu");
lore.clear();
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(8, item);
}
}
|
Java
|
UTF-8
| 667
| 2.15625
| 2
|
[
"MIT"
] |
permissive
|
package com.zjx.readlife.ireader.ui.adapter;
import android.content.Context;
import com.zjx.readlife.ireader.model.bean.CommentBean;
import com.zjx.readlife.ireader.ui.adapter.view.CommentHolder;
import com.zjx.readlife.ireader.ui.base.adapter.IViewHolder;
import com.zjx.readlife.ireader.widget.adapter.WholeAdapter;
/**
* Created by readlife on 17-4-29.
*/
public class CommentAdapter extends WholeAdapter<CommentBean> {
public CommentAdapter(Context context, Options options) {
super(context, options);
}
@Override
protected IViewHolder<CommentBean> createViewHolder(int viewType) {
return new CommentHolder(false);
}
}
|
Python
|
UTF-8
| 406
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
def display_table(t):
display(Markdown(
'<div class="datatable">' +
tabulate(t, headers='keys') +
"\n\n</div>"
))
def table_ds(ds, fdr, le_prop=0.0, nes=0.0):
df = ds.to_dataframe()
df.reset_index(level=0, inplace=True)
df = df.loc[(df['fdr'] < fdr) &
(df['le_prop'] > le_prop) &
(np.abs(df['nes']) > nes) ]
display_table(df)
|
Rust
|
UTF-8
| 2,058
| 2.96875
| 3
|
[] |
no_license
|
use async_std::net::{TcpListener, TcpStream};
use async_std::stream::StreamExt;
use async_std::task;
use std::env;
use std::io::{ErrorKind, Result};
mod noise;
fn main() {
let count = env::args().count();
if count < 3 {
usage();
}
let mode = env::args().nth(1).unwrap();
let port = env::args().nth(2).unwrap();
let address = format!("127.0.0.1:{}", port);
task::block_on(async move {
let result = match mode.as_ref() {
"server" => tcp_server(address).await,
"client" => tcp_client(address).await,
_ => panic!(usage()),
};
if let Err(e) = result {
eprintln!("error: {}", e);
}
});
}
fn usage() {
println!("usage: cargo run [client|server] [port]");
std::process::exit(1);
}
async fn tcp_server(address: String) -> Result<()> {
let listener = TcpListener::bind(&address).await?;
println!("Listening on {}", listener.local_addr()?);
let mut incoming = listener.incoming();
while let Some(stream) = incoming.next().await {
let stream = stream?;
let peer_addr = stream.peer_addr().unwrap();
eprintln!("new connection from {}", peer_addr);
task::spawn(async move {
match onconnection(stream, false).await {
Err(ref e) if e.kind() != ErrorKind::UnexpectedEof => {
eprintln!("connection closed from {} with error: {}", peer_addr, e);
}
Err(_) | Ok(()) => {
eprintln!("connection closed from {}", peer_addr);
}
}
});
}
Ok(())
}
async fn tcp_client(address: String) -> Result<()> {
let stream = TcpStream::connect(&address).await?;
onconnection(stream, true).await?;
Ok(())
}
async fn onconnection(stream: TcpStream, is_initiator: bool) -> Result<()> {
match noise::handshake(stream, is_initiator).await {
Ok(_) => eprintln!("done without errors"),
Err(e) => eprintln!("error {:?}", e),
};
Ok(())
}
|
C#
|
UTF-8
| 6,188
| 2.515625
| 3
|
[] |
no_license
|
๏ปฟusing System;
using System.Linq;
using System.Collections.Generic;
using Frontend2;
using Frontend2.Hardware;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace VendingMachineTester
{
[TestClass]
public class GoodWeirdOrdering
{
/// <summary>
/// UT01-GO
/// Checking values with no configuration
/// </summary
[TestMethod]
public void GoodValuesNoConfigure()
{
var vm = new VendingMachine(new int[] { 5, 10, 25, 100 }, 3, 10, 10, 10);
new VendingMachineLogic(vm);
var delivery = VMUtility.ExtractDelivery(vm);
var unload = VMUtility.Unload(vm);
Assert.AreEqual(0, delivery.Count);
Assert.AreEqual(0, VMUtility.CentsInCoinRacks(unload));
Assert.AreEqual(0, VMUtility.PopsInPopRacks(unload).Count);
Assert.AreEqual(0, unload.PaymentCoinsInStorageBin.Count);
}
/// <summary>
/// UT02-GO
/// Mixed coin denominations
/// </summary>
[TestMethod]
public void GoodMixedCoins()
{
var vm = new VendingMachine(new int[] { 100, 5, 25, 10 }, 3, 2, 10, 10);
new VendingMachineLogic(vm);
vm.Configure(new List<string>() { "Coke", "Water", "Juice" }, new List<int>() { 250, 250, 205 });
vm.LoadCoins(new int[] { 0, 1, 2, 1 });
vm.LoadPopCans(new int[] { 1, 1, 1 });
vm.SelectionButtons[0].Press();
var delivery = VMUtility.ExtractDelivery(vm);
Assert.AreEqual(0, delivery.Count);
vm.CoinSlot.AddCoin(new Coin(100));
vm.CoinSlot.AddCoin(new Coin(100));
vm.CoinSlot.AddCoin(new Coin(100));
vm.SelectionButtons[0].Press();
delivery = VMUtility.ExtractDelivery(vm);
Assert.IsTrue((VMUtility.Pops(new string[] { "Coke" })).SequenceEqual(VMUtility.PopsInDelivery(delivery)));
Assert.AreEqual(50, VMUtility.CentsInDelivery(delivery));
var unload = VMUtility.Unload(vm);
Assert.IsTrue((VMUtility.Pops(new string[] { "Water", "Juice" })).SequenceEqual(VMUtility.PopsInPopRacks(unload)));
Assert.AreEqual(215, VMUtility.CentsInCoinRacks(unload));
Assert.AreEqual(100, unload.PaymentCoinsInStorageBin.Sum(c => c.Value));
}
/// <summary>
/// UT03-GO
/// Extracting delivery before sale of drink
/// </summary>
[TestMethod]
public void GoodExtractBeforeSale()
{
var vm = new VendingMachine(new int[] { 100, 5, 25, 10 }, 3, 10, 10, 10);
new VendingMachineLogic(vm);
vm.Configure(new List<string>() { "Coke", "Water", "Juice" }, new List<int>() { 250, 250, 205 });
vm.LoadCoins(new int[] { 0, 1, 2, 1 });
vm.LoadPopCans(new int[] { 1, 1, 1 });
vm.SelectionButtons[0].Press();
var delivery = VMUtility.ExtractDelivery(vm);
Assert.AreEqual(0, delivery.Count);
vm.CoinSlot.AddCoin(new Coin(100));
vm.CoinSlot.AddCoin(new Coin(100));
vm.CoinSlot.AddCoin(new Coin(100));
delivery = VMUtility.ExtractDelivery(vm);
Assert.AreEqual(0, delivery.Count);
var unload = VMUtility.Unload(vm);
Assert.IsTrue((VMUtility.Pops(new string[] { "Coke", "Water", "Juice" })).SequenceEqual(VMUtility.PopsInPopRacks(unload)));
Assert.AreEqual(65, VMUtility.CentsInCoinRacks(unload));
Assert.AreEqual(0, unload.PaymentCoinsInStorageBin.Sum(c => c.Value));
}
/// <summary>
/// UT04-GO
/// Changing configuration throughout the tests
/// </summary>
[TestMethod]
public void GoodChangingConfiguration()
{
var vm = new VendingMachine(new int[] { 5, 10, 25, 100 }, 3, 10, 10, 10);
new VendingMachineLogic(vm);
vm.Configure(new List<string>() { "A", "B", "C" }, new List<int>() { 5, 10, 25 });
vm.LoadCoins(new int[] { 1, 1, 2, 0 });
vm.LoadPopCans(new int[] { 1, 1, 1 });
vm.Configure(new List<string>() { "Coke", "Water", "Juice" }, new List<int>() { 250, 250, 205 });
vm.SelectionButtons[0].Press();
var delivery = VMUtility.ExtractDelivery(vm);
Assert.AreEqual(0, delivery.Count);
vm.CoinSlot.AddCoin(new Coin(100));
vm.CoinSlot.AddCoin(new Coin(100));
vm.CoinSlot.AddCoin(new Coin(100));
vm.SelectionButtons[0].Press();
// Check values of original configuration
delivery = VMUtility.ExtractDelivery(vm);
Assert.AreEqual(50, VMUtility.CentsInDelivery(delivery));
Assert.IsTrue(VMUtility.Pops(new string[] { "A" }).SequenceEqual(VMUtility.PopsInDelivery(delivery)));
var unload = VMUtility.Unload(vm);
Assert.IsTrue((VMUtility.Pops(new string[] { "B", "C" })).SequenceEqual(VMUtility.PopsInPopRacks(unload)));
Assert.AreEqual(315, VMUtility.CentsInCoinRacks(unload));
Assert.AreEqual(0, unload.PaymentCoinsInStorageBin.Sum(c => c.Value));
// Check results of new configuration change
vm.LoadCoins(new int[] { 1, 1, 2, 0 });
vm.LoadPopCans(new int[] { 1, 1, 1 });
vm.CoinSlot.AddCoin(new Coin(100));
vm.CoinSlot.AddCoin(new Coin(100));
vm.CoinSlot.AddCoin(new Coin(100));
vm.SelectionButtons[0].Press();
delivery = VMUtility.ExtractDelivery(vm);
Assert.AreEqual(50, VMUtility.CentsInDelivery(delivery));
Assert.IsTrue(VMUtility.Pops(new string[] { "Coke" }).SequenceEqual(VMUtility.PopsInDelivery(delivery)));
unload = VMUtility.Unload(vm);
Assert.IsTrue((VMUtility.Pops(new string[] { "Water", "Juice" })).SequenceEqual(VMUtility.PopsInPopRacks(unload)));
Assert.AreEqual(315, VMUtility.CentsInCoinRacks(unload));
Assert.AreEqual(0, unload.PaymentCoinsInStorageBin.Sum(c => c.Value));
}
}
}
|
C#
|
UTF-8
| 1,926
| 2.59375
| 3
|
[] |
no_license
|
๏ปฟ/*
* Created by SharpDevelop.
* User: Eucliwood
* Date: 12-Oct-17
* Time: 23:51
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Text;
using System.Security.Cryptography;
namespace Sha
{
/// <summary>
/// Description of UserControl1.
/// </summary>
public partial class Sha : UserControl
{
public Sha()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
void setCipherbox(string cipher){
cipherbox.Text = cipher;
}
string getInput(){
return inputbox.Text;
}
public string getHashSha256(string text)
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
SHA256Managed hashstring = new SHA256Managed();
byte[] hash = hashstring.ComputeHash(bytes);
string hashString = string.Empty;
foreach (byte x in hash)
{
hashString += String.Format("{0:x2}", x);
}
return hashString;
}
public string getHashSha512(string text)
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
SHA512Managed hashstring = new SHA512Managed();
byte[] hash = hashstring.ComputeHash(bytes);
string hashString = string.Empty;
foreach (byte x in hash)
{
hashString += String.Format("{0:x2}", x);
}
return hashString;
}
void HashbuttonClick(object sender, EventArgs e)
{
string input = getInput();
string cipher;cipher = getHashSha256(input);
if(sha256ratio.Checked)
cipher = getHashSha256(input);
else
cipher = getHashSha512(input);
setCipherbox(cipher);
}
}
}
|
TypeScript
|
UTF-8
| 1,107
| 2.5625
| 3
|
[] |
no_license
|
import {
Body,
Controller,
Post,
ValidationPipe,
Headers,
Get,
} from '@nestjs/common';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';
import { AuthService } from './auth.service';
import { UserEntity } from './user.entity';
@Controller()
export class AuthController {
/**
*
* @param authService
*/
constructor(private authService: AuthService) {}
/**
*
* @param authCredentialsDto
*/
// @Post('/api/auth/register')
// register(
// @Body(ValidationPipe) authCredentialsDto: AuthCredentialsDto,
// ): Promise<UserEntity> {
// return this.authService.register(authCredentialsDto);
// }
/**
*
* @param authCredentialsDto
*/
@Post('/api/auth/login')
login(
@Body(ValidationPipe) authCredentialsDto: AuthCredentialsDto,
): Promise<{ accessToken: string }> {
return this.authService.login(authCredentialsDto);
}
/**
*
* @param accessToken
*/
@Get('/api/auth/logged-in')
isAuthenticated(@Headers('accesstoken') accessToken: string) {
return this.authService.isAuthenticated(accessToken);
}
}
|
TypeScript
|
UTF-8
| 1,037
| 3.3125
| 3
|
[] |
no_license
|
export interface TypedSchema<T> {
type: T
getSchema(): JSONSchema
}
export type JSONSchema = object
export type UnwrapTypedSchema<Schema> = Schema extends TypedSchema<
infer InnerType
>
? InnerType
: never
export type TypeOf<Schema extends TypedSchema<any>> = Schema['type']
export interface BaseSchemaDefinition {
/**
* Schema title
*/
title?: string
/**
* Schema description
*/
description?: string
/**
* A comment to be added to the schema
*/
$comment?: string
/**
* Default value to be assigned when no value is given in
* the document
*/
default?: any
/**
* A list of example values that match this schema
*/
examples?: any[]
}
export function defineType<
SchemaDefinition extends BaseSchemaDefinition,
ValueType
>(
type: string,
value: ValueType
): (schema?: SchemaDefinition) => TypedSchema<ValueType> {
return (schema: any = {}) => {
return {
getSchema: () => Object.assign({}, schema, { type }),
type: value as ValueType,
}
}
}
|
C#
|
UTF-8
| 550
| 2.828125
| 3
|
[] |
no_license
|
๏ปฟusing System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Update the in game text to display the speed of the train.
/// </summary>
public class DisplaySpeed : DisplayText {
/// <summary>
/// As long as the game isn't over (meaning not gamestate 6).
/// Show the current speed of the train.
/// </summary>
protected override void Update()
{
if (GameMaster.state != 6)
{
textObject.text = ("Speed: " + GameMaster.speed.ToString("F2"));
}
}
}
|
TypeScript
|
UTF-8
| 1,556
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
๏ปฟimport { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { User } from '../_models/index';
@Injectable()
export class UserService {
constructor(private http: Http) { }
/**
* Get all User
*/
getAll() {
return this.http.get('/users').map((response: Response) => response.json());
}
/**
* Get user by Id
* @param {string} _id [description]
*/
getById(_id: string) {
return this.http.get('/users/' + _id).map((response: Response) => response.json());
}
/**
* Create a user
* @param {User} user [description]
*/
create(user: User) {
return this.http.post('/users/register', user);
}
/**
* Update a user
* @param {User} user [description]
*/
update(user: User) {
return this.http.put('/users/' + user._id, user);
}
/**
* Delete a user
* @param {string} _id [description]
*/
delete(_id: string) {
return this.http.delete('/users/' + _id);
}
/**
* Forgot password, Sends an email
* @param {string} _id [description]
*/
forgotpassword(user: User) {
return this.http.post('/users/forgot-password', user).map((response: Response) => response.json());
}
/**
* Reset password
* @param {string} _id [description]
*/
resetpassword(user: User) {
return this.http.post('/users/reset-password', user).map((response: Response) => response.json());
}
}
|
Java
|
UTF-8
| 10,175
| 3.046875
| 3
|
[] |
no_license
|
package com.ivangorbachev;
import java.util.*;
import static java.lang.Math.*;
public class ConvexPolygonGame {
class Point {
long x, y;
Point(long x, long y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Point{" +
"x=" + x +
", y=" + y +
'}';
}
}
Point[] pts;
public String winner(int[] X, int[] Y) {
pts = new Point[X.length];
int minX = 1 << 30, maxX = -1 << 30, minY = 1 << 30, maxY = -1 << 30;
for (int i = 0; i < pts.length; ++i) {
minX = min(minX, X[i]);
maxX = max(maxX, X[i]);
minY = min(minY, Y[i]);
maxY = max(maxY, Y[i]);
pts[i] = new Point(X[i], Y[i]);
}
long area = 0;
for (int i = 0; i < pts.length; ++i) {
area += area(pts[i], pts[(i + 1) % pts.length]);
}
area = abs(area);
List<Point> inside = new ArrayList<Point>();
for (long x = minX; x <= maxX; ++x) {
for (long y = minY; y <= maxY; ++y) {
if (checkCorner(x, y))
continue;
if (abs(calcArea(x, y)) == area) {
calcArea(x, y);
inside.add(new Point(x, y));
if (can(inside)) {
return "Masha";
}
}
}
}
return "Petya";
}
boolean can(List<Point> inside) {
if (inside.size() < 3)
return false;
return abs(triangleArea(inside.get(0), inside.get(1), inside.get(inside.size() - 1))) > 0;
}
long triangleArea(Point p1, Point p2, Point p3) {
return area(p1, p2) + area(p2, p3) + area(p3, p1);
}
boolean checkCorner(long x, long y) {
for (Point p : pts)
if (p.x == x && p.y == y) return true;
return false;
}
long calcArea(long x, long y) {
Point p = new Point(x, y);
long ret = 0;
for (int i = 0; i < pts.length; ++i) {
Point p1 = pts[i];
Point p2 = pts[(i + 1) % pts.length];
ret += triangleArea(p, p1, p2);
}
return ret;
}
long area(Point p1, Point p2) {
return (p1.y + p2.y) * (p2.x - p1.x);
}
// BEGIN CUT HERE
static boolean DEBUG = false;
void dbg(Object... objs) {
if (!DEBUG) {
return;
}
for (Object o : objs) {
String printLine;
if (o.getClass().isArray()) {
printLine = arrayToString(o);
} else {
printLine = o.toString();
}
System.err.print(printLine + " ");
}
System.err.println();
}
String arrayToString(Object o) {
if (o instanceof long[])
return Arrays.toString((long[]) o);
if (o instanceof int[])
return Arrays.toString((int[]) o);
if (o instanceof short[])
return Arrays.toString((short[]) o);
if (o instanceof char[])
return Arrays.toString((char[]) o);
if (o instanceof byte[])
return Arrays.toString((byte[]) o);
if (o instanceof double[])
return Arrays.toString((double[]) o);
if (o instanceof float[])
return Arrays.toString((float[]) o);
if (o instanceof boolean[])
return Arrays.toString((boolean[]) o);
if (o instanceof Object[])
return Arrays.deepToString((Object[]) o);
throw new IllegalStateException();
}
public static void main(String[] args) {
try {
DEBUG = true;
// eq(0, (new ConvexPolygonGame()).winner(new int[]{0, 1, 0}, new int[]{0, 0, 1}), "Petya");
// eq(1, (new ConvexPolygonGame()).winner(new int[]{0, 4, 2}, new int[]{0, 0, 2}), "Masha");
// eq(2, (new ConvexPolygonGame()).winner(new int[]{0, 100, 100, 0}, new int[]{0, 0, 100, 100}), "Masha");
eq(3, (new ConvexPolygonGame()).winner(new int[]{0, 50, 100, 50}, new int[]{0, -1, 0, 1}), "Petya");
// eq(4, (new ConvexPolygonGame()).winner(new int[]{-100000, 100000, 100000, -100000}, new int[]{-1, -1, 1, 1}), "Masha");
} catch (Exception exx) {
System.err.println(exx);
exx.printStackTrace(System.err);
}
}
private static void eq(int n, int a, int b) {
if (a == b)
System.err.println("Case " + n + " passed.");
else
System.err.println("Case " + n + " failed: expected " + b + ", received " + a + ".");
}
private static void eq(int n, char a, char b) {
if (a == b)
System.err.println("Case " + n + " passed.");
else
System.err.println("Case " + n + " failed: expected '" + b + "', received '" + a + "'.");
}
private static void eq(int n, long a, long b) {
if (a == b)
System.err.println("Case " + n + " passed.");
else
System.err.println("Case " + n + " failed: expected \"" + b + "L, received " + a + "L.");
}
private static void eq(int n, boolean a, boolean b) {
if (a == b)
System.err.println("Case " + n + " passed.");
else
System.err.println("Case " + n + " failed: expected " + b + ", received " + a + ".");
}
private static void eq(int n, double a, double b) {
if (eq(a, b))
System.err.println("Case " + n + " passed.");
else
System.err.println("Case " + n + " failed: expected " + b + ", received " + a + ".");
}
private static void eq(int n, String a, String b) {
if (a != null && a.equals(b))
System.err.println("Case " + n + " passed.");
else
System.err.println("Case " + n + " failed: expected \"" + b + "\", received \"" + a + "\".");
}
private static void eq(int n, int[] a, int[] b) {
if (a.length != b.length) {
System.err.println("Case " + n + " failed: returned " + a.length + " elements; expected " + b.length + " elements.");
return;
}
for (int i = 0; i < a.length; i++)
if (a[i] != b[i]) {
System.err.println("Case " + n + " failed. Expected and returned array differ in position " + i);
print(b);
print(a);
return;
}
System.err.println("Case " + n + " passed.");
}
private static void eq(int n, long[] a, long[] b) {
if (a.length != b.length) {
System.err.println("Case " + n + " failed: returned " + a.length + " elements; expected " + b.length + " elements.");
return;
}
for (int i = 0; i < a.length; i++)
if (a[i] != b[i]) {
System.err.println("Case " + n + " failed. Expected and returned array differ in position " + i);
print(b);
print(a);
return;
}
System.err.println("Case " + n + " passed.");
}
private static void eq(int n, double[] a, double[] b) {
if (a.length != b.length) {
System.err.println("Case " + n + " failed: returned " + a.length + " elements; expected " + b.length + " elements.");
return;
}
for (int i = 0; i < a.length; i++)
if (!eq(a[i], b[i])) {
System.err.println("Case " + n + " failed. Expected and returned array differ in position " + i);
print(b);
print(a);
return;
}
System.err.println("Case " + n + " passed.");
}
private static void eq(int n, String[] a, String[] b) {
if (a.length != b.length) {
System.err.println("Case " + n + " failed: returned " + a.length + " elements; expected " + b.length + " elements.");
return;
}
for (int i = 0; i < a.length; i++)
if (!a[i].equals(b[i])) {
System.err.println("Case " + n + " failed. Expected and returned array differ in position " + i);
print(b);
print(a);
return;
}
System.err.println("Case " + n + " passed.");
}
private static void print(int a) {
System.err.print(a + " ");
}
private static void print(long a) {
System.err.print(a + "L ");
}
private static void print(String s) {
System.err.print("\"" + s + "\" ");
}
private static void print(int[] rs) {
if (rs == null) return;
System.err.print('{');
for (int i = 0; i < rs.length; i++) {
System.err.print(rs[i]);
if (i != rs.length - 1)
System.err.print(", ");
}
System.err.println('}');
}
private static void print(long[] rs) {
if (rs == null) return;
System.err.print('{');
for (int i = 0; i < rs.length; i++) {
System.err.print(rs[i]);
if (i != rs.length - 1)
System.err.print(", ");
}
System.err.println('}');
}
private static void print(double[] rs) {
if (rs == null) return;
System.err.print('{');
for (int i = 0; i < rs.length; i++) {
System.err.print(rs[i]);
if (i != rs.length - 1)
System.err.print(", ");
}
System.err.println('}');
}
private static void print(String[] rs) {
if (rs == null) return;
System.err.print('{');
for (int i = 0; i < rs.length; i++) {
System.err.print("\"" + rs[i] + "\"");
if (i != rs.length - 1)
System.err.print(", ");
}
System.err.println('}');
}
private static void nl() {
System.err.println();
}
private static double eps = 1e-9;
private static boolean eq(double a, double b) {
return abs(a - b) <= eps;
}
// END CUT HERE
}
|
PHP
|
UTF-8
| 572
| 2.515625
| 3
|
[] |
no_license
|
<?php
require("parser.php");
$parser = new Parser();
function getMenu(){
global $parser;
echo $parser->getMenu();
}
function stickies(){
global $parser;
return $parser->getStickies();
}
function getWelcomeTitle(){
global $parser;
echo $parser->getWelcome()->title;
}
function getWelcomeText(){
global $parser;
echo $parser->getWelcome()->text;
}
function faqs(){
global $parser;
return $parser->getFaqs();
}
?>
|
Java
|
UTF-8
| 1,963
| 2.1875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.apache.ofbiz.webapp.website;
import lombok.experimental.FieldNameConstants;
import java.io.Serializable;
import lombok.Getter;
import lombok.Setter;
import java.sql.Timestamp;
import org.apache.ofbiz.entity.GenericValue;
import java.util.List;
import java.util.ArrayList;
/**
* Web Page
*/
@FieldNameConstants
public class WebPage implements Serializable {
public static final long serialVersionUID = 4601365251141622784L;
public static final String NAME = "WebPage";
/**
* Web Page Id
*/
@Getter
@Setter
private String webPageId;
/**
* Page Name
*/
@Getter
@Setter
private String pageName;
/**
* Web Site Id
*/
@Getter
@Setter
private String webSiteId;
/**
* Last Updated Stamp
*/
@Getter
@Setter
private Timestamp lastUpdatedStamp;
/**
* Last Updated Tx Stamp
*/
@Getter
@Setter
private Timestamp lastUpdatedTxStamp;
/**
* Created Stamp
*/
@Getter
@Setter
private Timestamp createdStamp;
/**
* Created Tx Stamp
*/
@Getter
@Setter
private Timestamp createdTxStamp;
/**
* Content Id
*/
@Getter
@Setter
private String contentId;
public WebPage(GenericValue value) {
webPageId = (String) value.get(FIELD_WEB_PAGE_ID);
pageName = (String) value.get(FIELD_PAGE_NAME);
webSiteId = (String) value.get(FIELD_WEB_SITE_ID);
lastUpdatedStamp = (Timestamp) value.get(FIELD_LAST_UPDATED_STAMP);
lastUpdatedTxStamp = (Timestamp) value.get(FIELD_LAST_UPDATED_TX_STAMP);
createdStamp = (Timestamp) value.get(FIELD_CREATED_STAMP);
createdTxStamp = (Timestamp) value.get(FIELD_CREATED_TX_STAMP);
contentId = (String) value.get(FIELD_CONTENT_ID);
}
public static WebPage fromValue(org.apache.ofbiz.entity.GenericValue value) {
return new WebPage(value);
}
public static List<WebPage> fromValues(List<GenericValue> values) {
List<WebPage> entities = new ArrayList<>();
for (GenericValue value : values) {
entities.add(new WebPage(value));
}
return entities;
}
}
|
Java
|
UTF-8
| 15,893
| 3.078125
| 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 javaapplication5;
/**
*
* @author SUJITHA
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
//import javax.swing.JOptionPane;
/**
*
* @author Samsung
*/
import java.util.*;
//import java.io.*;
import javax.swing.JOptionPane;
/*public class TextEditor {
public static void main(String s[]) throws FileNotFoundException, IOException {
String filename;
filename = JOptionPane.showInputDialog("ENTER THE FILENAME");
DLL [] l= new DLL[100];
DLL g;//for creating new link
/*for(int i=0; i<2; i++){
l[i]=new DLL();
}
String input,input1;//used when two diff inputs are required
PrintWriter outputfile = new PrintWriter(filename);
JOptionPane.showMessageDialog(null,"enter line by line and enter save to exit ");
String choice;
StringTokenizer word;
int i=0;
String h;
do{
String w = JOptionPane.showInputDialog("ENTER THe line");
word=new StringTokenizer(w," ");
l[i]=new DLL();
while(word.hasMoreTokens()){
h=word.nextToken();
l[i].insertWordL(h);
} i++;
outputfile.println(w);
choice = JOptionPane.showInputDialog("enter y to continue else n ");
}while("y".equals(choice)||"Y".equals(choice)&&i<100);
for(int j=0; l[j]!=null&&j<i;j++){
l[j].display();
System.out.println();
}String k;
//do{
k = JOptionPane.showInputDialog("ENTER your choice whether word or line or exit ");
switch (k) {
case "word":
{
int line;
input=JOptionPane.showInputDialog("Enter line number to be edited");
line=Integer.parseInt(input);
do{
input = JOptionPane.showInputDialog("here's the list \n 1:insert word beginning\n 2: Insert at end\n 3: insert at any position\n4:replace at first\n 5:replace at end\n6:replace at any position\n7:Delete first\n8:Delete last\n9:Delete at any position ");
int d;
d=Integer.parseInt(input);
switch(d){
case 1:
input=JOptionPane.showInputDialog("Enter word");
l[line-1].insertWordB(input);
break;
case 2:
input=JOptionPane.showInputDialog("Enter word");
l[line-1].insertWordL(input);
break;
case 3:
input=JOptionPane.showInputDialog("Enter word ");
input1=JOptionPane.showInputDialog("Enter position");
l[line-1].insertWordAnyPos(input,Integer.parseInt(input1));
break;
case 4:
try {
input=JOptionPane.showInputDialog("Enter word ");
l[line-1].replaceWordB(input);
}
catch(EmptyDoublyLinkedList e){}
break;
case 5:
try {
input=JOptionPane.showInputDialog("Enter word ");
l[line-1].replaceWordL(input);
}
catch(EmptyDoublyLinkedList e){}
break;
case 6:
try {
input=JOptionPane.showInputDialog("Enter word ");
input1=JOptionPane.showInputDialog("Enter pos");
l[line-1].replaceWordatAnyPos(input, Integer.parseInt(input1));
}
catch(EmptyDoublyLinkedList e){}
break;
case 7:
try {
l[line-1].deleteWordB();
}
catch(EmptyDoublyLinkedList e){}
break;
case 8:
try {
l[line-1].deleteWordL();
}
catch(EmptyDoublyLinkedList e){}
break;
case 9:
try {
input1=JOptionPane.showInputDialog("Enter pos");
l[line-1].deleteWordatAnyPos(Integer.parseInt(input1));
}
catch(EmptyDoublyLinkedList e){}
break;
default:
break;
}
input=JOptionPane.showInputDialog("Continue: y or n");
}while(input.equals("y")||input.equals("Y"));
break;
}
case "line":
{
input = JOptionPane.showInputDialog("here's the list for lines \n 1:insert line beginning\n 2: Insert at end\n 3: insert at any position\n4:replace at first\n 5:replace at end\n6:replace at any position\n7:Delete first\n8:Delete last\n9:Delete at any position ");
int d;
d=Integer.parseInt(input);
switch(d){
case 1:
input=JOptionPane.showInputDialog("Enter line");
g=new DLL();
word=new StringTokenizer(input, " ");
while(word.hasMoreTokens()){
g.insertWordL(word.nextToken());
}
l[i]=new DLL();
for(int j=i-1; j>=0; j--){
l[j+1]=l[j];
}
i++;
l[0]=g;
break;
case 2:
input=JOptionPane.showInputDialog("Enter line");
g=new DLL();
word=new StringTokenizer(input, " ");
while(word.hasMoreTokens()){
g.insertWordL(word.nextToken());
}
l[i]=new DLL();
l[i]=g;
i++;
break;
case 3:
input=JOptionPane.showInputDialog("Enter line");
input1=JOptionPane.showInputDialog("Enter position");
g=new DLL();
word=new StringTokenizer(input, " ");
while(word.hasMoreTokens()){
g.insertWordL(word.nextToken());
}
l[i]=new DLL();
for(int j=i-1; j>=Integer.parseInt(input1)-1; j--){
l[j+1]=l[j];
}
i++;
l[Integer.parseInt(input1)-1]=g;
break;
case 4:
input=JOptionPane.showInputDialog("Enter line");
g=new DLL();
word=new StringTokenizer(input, " ");
while(word.hasMoreTokens()){
g.insertWordL(word.nextToken());
}
l[0]=g;
break;
case 5:
input=JOptionPane.showInputDialog("Enter line");
g=new DLL();
word=new StringTokenizer(input, " ");
while(word.hasMoreTokens()){
g.insertWordL(word.nextToken());
}
l[i-1]=g;
break;
case 6:
input=JOptionPane.showInputDialog("Enter line");
input1=JOptionPane.showInputDialog("Enter position");
g=new DLL();
word=new StringTokenizer(input, " ");
while(word.hasMoreTokens()){
g.insertWordL(word.nextToken());
}
l[Integer.parseInt(input1)-1]=g;
break;
case 7:
for(int j =0; j<i-1 ; j++){
l[j]=l[j+1];
}
l[i-1]=null;
i--;
break;
case 8:
l[i-1]=null;
i--;
break;
case 9:
input1=JOptionPane.showInputDialog("enter the position");
for(int j =Integer.parseInt(input1)-1; j<i ; j++){
l[j]=l[j+1];
}
l[i]=null;
i--;
break;
default :
break;
}
}
default:
break;
}
FileWriter fwriter=new FileWriter(filename,true);
try (PrintWriter outputfile1 = new PrintWriter(fwriter)) {
for(int j=0;j<i; j++){
Node p =l[j].header.next ;
while(p!=l[j].trailer){
outputfile1.print(p.getString()+" ");
p=p.getNext();
}
outputfile1.println();
l[j].display();
System.out.println();
}
}
}
}
*/
class Node{
public Node next;
public Node prev;
public String str;
public void setString(String s){
str = s;
}
public String getString(){
return str ;
}
public void setNext(Node n){
next = n;
}
public Node getNext(){
return next;
}
public void setPrev(Node n){
prev = n;
}
public Node getPrev(){
return prev;
}
}
public class DLL{
Node header , trailer;
DLL(){
header = new Node();
trailer = new Node();
//header=null;
//header=trailer;
//trailer=header;
header.setNext(trailer);
trailer.setPrev(header);
header.setPrev(null);
trailer.setNext(null);
}
public void insertWordB(String s ){
Node p = new Node();
p.setString(s);
if(header.getNext()==trailer){
p.setNext(trailer);
p.setPrev(header);
header.setNext(p);
trailer.setPrev(p);
}
else{
Node q;
q=header.getNext();
p.setNext(q);
p.setPrev(header);
header.setNext(p);
q.setPrev(p);
}
}
public void insertWordL(String s ){
Node p = new Node();
p.setString(s);
if(header.getNext()==trailer){
p.setNext(trailer);
p.setPrev(header);
header.setNext(p);
trailer.setPrev(p);
}
else{
Node q ;
q=trailer.getPrev();
p.setNext(trailer);
p.setPrev(q);
trailer.setPrev(p);
q.setNext(p);
}
}
public void insertWordAnyPos(String s ,int pos ){
Node p = new Node();
p.setString(s);
if(header.getNext()==trailer){
p.setNext(trailer);
p.setPrev(header);
header.setNext(p);
trailer.setPrev(p);
}
else{
Node q ;
q=header;
int i=0;
while(q!=trailer && i!=pos){
q=q.getNext();
i++;
}
p.setNext(q);
p.setPrev(q.getPrev());
q.getPrev().setNext(p);
q.setPrev(p);
}
}
public void deleteWordB() throws EmptyDoublyLinkedList{
if(header.getNext()==trailer) throw new EmptyDoublyLinkedList("its empty");
else{
Node q;
Node p;
q=header.getNext();
p=header.getNext().getNext();
p.setPrev(header);
header.setNext(p);
q=null;
}
}
void deleteWordL ( )throws EmptyDoublyLinkedList {
if(header.getNext()==trailer) throw new EmptyDoublyLinkedList ("its empty");
else{
Node q;
q=trailer.getPrev();
q.getPrev().setNext(trailer);
trailer.setPrev(q.getPrev());
//q=null;
}
}
void deleteWordatAnyPos( int pos)throws EmptyDoublyLinkedList{
if(header.getNext()==trailer) throw new EmptyDoublyLinkedList("its empty");
else{
Node q;
q=header;
int i =0;
while(q!=trailer && i!=pos){
q=q.getNext();
i++;
}
q.getPrev().setNext(q.getNext());
q.getNext().setPrev(q.getPrev());
//q=null;
}
}
void replaceWordB ( String s)throws EmptyDoublyLinkedList{
if(header.getNext()==trailer) throw new EmptyDoublyLinkedList("its empty");
else{
header.getNext().setString(s);
}
}
void replaceWordL ( String s)throws EmptyDoublyLinkedList{
if(header.getNext()==trailer) throw new EmptyDoublyLinkedList("its empty");
else{
trailer.getPrev().setString(s);
}
}
void replaceWordatAnyPos ( String s , int pos)throws EmptyDoublyLinkedList{
if(header.getNext()==trailer) throw new EmptyDoublyLinkedList("its empty");
else{
Node q ;
q=header;
int i=0 ;
while(q!=trailer && i!=pos){
q=q.getNext();
i++;
}
q.setString(s);
}
}
@Override
public String toString(){
String s = null;
Node current=header.getNext();
s=current.getString();
current=current.getNext();
while(current!=trailer){
s+=" "+current.getString()+" ";
current=current.getNext();
}
return s;
}
public void display (){
Node q=header.getNext();
while(q!=trailer){
System.out.print(q.getString()+" ") ;
q=q.getNext();
}
}
}
class EmptyDoublyLinkedList extends Exception{
EmptyDoublyLinkedList( String s){
System.out.println(" the text file is empty");
}
}
|
JavaScript
|
UTF-8
| 1,081
| 3.328125
| 3
|
[] |
no_license
|
console.log("Weight-Converter Using Javascript ๐")
let kilogram = document.querySelector("#Kilogram");
let converter = document.querySelector("#Convert");
let card = document.querySelector("#card");
// console.log(kilogram,converter)
converter.addEventListener("click",function(){
kg_value = kilogram.value;
if(kg_value===null || kg_value===""){
alert("Kilogram value is missing. ")
}else{
showConvertedWeights(kg_value)
}
kilogram.value=""
})
function showConvertedWeights(kg_units){
let createdDiv = document.querySelector("#box");
let html = ""
html += `<ul class="list-group list-group-flush">
<li class="list-group-item"><h4>Kilograms(Entered):${kg_units}(kg) </h4></li>
<li class="list-group-item"><h4>In Grams: ${kg_units * 1000}(g)</h4></li>
<li class="list-group-item"><h4>In Pounds: ${kg_units * 2.2046}(lb)</h4></li>
<li class="list-group-item"><h4>In Ounces: ${kg_units * 35.2739}(oz)</h4></li>
</ul>`;
createdDiv.innerHTML = html;
}
|
Java
|
UTF-8
| 250
| 2.921875
| 3
|
[] |
no_license
|
public class PostOrder {
public static void postOrder(TreeNode<Integer> root) {
if(root==null) {
return ;
}
for(int i=0;i<root.children.size();i++) {
postOrder(root.children.get(i));
}
System.out.print(root.data+" ");
}
}
|
C++
|
UTF-8
| 1,007
| 3.09375
| 3
|
[] |
no_license
|
#include <queue>
#include "solution.h"
using namespace std;
vector<int> Solution::findOrder(int numCourses, vector<vector<int>>& prerequisites)
{
vector<int> res;
vector<int> indegree(numCourses,0);
vector<vector<int>> adjacency(numCourses);
for (auto item : prerequisites)
{
indegree[item[0]]++;
adjacency[item[1]].push_back(item[0]);
}
queue<int> zeroDegree;
for (size_t i = 0; i < indegree.size(); i++)
{
if (indegree[i] == 0)
{
zeroDegree.push(i);
}
}
while (!zeroDegree.empty())
{
int course = zeroDegree.front();
zeroDegree.pop();
res.push_back(course);
for (auto item : adjacency[course])
{
indegree[item]--;
if (indegree[item] == 0)
{
zeroDegree.push(item);
}
}
}
if (res.size() == numCourses)
{
return res;
} else {
return {};
}
}
|
Java
|
UTF-8
| 2,329
| 1.9375
| 2
|
[] |
no_license
|
package com.allens.allenstools.activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.allens.allenstools.R;
import com.allens.lib_base.base.BaseActivity;
import com.example.lib_login_facebook.FaceBookLoginModel;
import com.example.lib_login_facebook.OnFacebookListener;
public class FaceBookAct extends BaseActivity {
private FaceBookLoginModel faceBookLoginModel;
private TextView textView;
private StringBuffer stringBuffer;
@Override
public int getContentViewId() {
return R.layout.activity_facebook;
}
@Override
protected void initView(Bundle savedInstanceState) {
}
@Override
protected void initListener() {
faceBookLoginModel = new FaceBookLoginModel();
textView = findViewById(R.id.face_tv);
stringBuffer = new StringBuffer();
}
@Override
public boolean setSkipStatusBar() {
return true;
}
public void click_login_facebook(View view) {
if (faceBookLoginModel != null)
faceBookLoginModel.login(this, new OnFacebookListener() {
@Override
public void onFaceBookLoginSuccess(String token) {
stringBuffer.append("็ปๅฝๆๅ ").append("token : ").append("\n").append(token).append("\n").append("\n");
textView.setText(stringBuffer.toString());
}
@Override
public void onFaceBookLoginCancel() {
stringBuffer.append("ๅๆถ็ปๅฝ ").append("\n");
textView.setText(stringBuffer.toString());
}
@Override
public void onFaceBookLoginFailed(Throwable throwable) {
stringBuffer.append("็ปๅฝๆฐ็พ ").append(throwable.getMessage()).append("\n");
textView.setText(stringBuffer.toString());
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (faceBookLoginModel != null)
faceBookLoginModel.onActivityResult(requestCode, resultCode, data);
}
}
|
Python
|
UTF-8
| 2,759
| 2.78125
| 3
|
[] |
no_license
|
import os
import shutil
from .sv_handler import SVHandler
from .xlsx_handler import XlsxHandler
def sv_dir_to_xlsx(dir_path,newpath,file_extenstion='.csv'):
""" A function to convert a directory of sv files to a directory of xlsx files.
:param dir_path: The path for where to directory is located
:type dir_path: str
:param newpath: The path for the new directory for where the xlsx files will be located
:type newpath: str
:param file_extenstion: The extension of the sv file that is being converted
:type file_extenstion: str
"""
os.makedirs(newpath)
for file_ in os.listdir(dir_path):
if os.path.splitext(file_)[-1].lower() == file_extenstion:
handler = sv_handler.SVHandler(os.path.join(dir_path, file_))
file_2 = xlsx_handler.XlsxHandler.dict_to_xlsx(handler.sv_to_dict(), os.path.join(newpath, os.path.splitext(file_)[0] + '.xlsx'))
def sv_dir_to_sv(dir_path,newpath,file_extenstion1='.csv',file_extenstion2='.psv', delimiter = '|'):
""" A function to convert a directory of sv files to a directory of a different sv files.
:param dir_path: The path for where to directory is located
:type dir_path: str
:param newpath: The path for the new directory for where the xlsx files will be located
:type newpath: str
:param file_extenstion: The extension of the sv file that is being converted
:type file_extenstion: str
:param file_extenstion2: The extension of the new sv files that will be created
:type file_extenstion2: str
:param delimiter: the delimiter that will be used for the new sv files
"""
os.makedirs(newpath)
for file_ in os.listdir(dir_path):
if os.path.splitext(file_)[-1].lower() == file_extenstion1:
handler = sv_handler.SVHandler(os.path.join(dir_path, file_))
file_2 = sv_handler.SVHandler.dict_to_sv(handler.sv_to_dict(), os.path.join(newpath, os.path.splitext(file_)[0] + file_extenstion2), delimiter=delimiter)
def xlsx_dir_to_sv(dir_path,newpath,file_extenstion='.csv', delimiter=','):
""" A function to convert a directory of xlsx files to a directory of a sv files.
:param dir_path: The path for where to directory is located
:type dir_path: str
:param newpath: The path for the new directory for where the xlsx files will be located
:type newpath: str
:param file_extenstion: The extension of the new sv files that will be created
:type file_extenstion: str
:param delimiter: the delimiter that will be used for the new sv files
"""
os.makedirs(newpath)
for file_ in os.listdir(dir_path):
if os.path.splitext(file_)[-1].lower() == '.xlsx':
handler = xlsx_handler.XlsxHandler(os.path.join(dir_path, file_))
file_2 = sv_handler.SVHandler.dict_to_sv(handler.xlsx_to_dict(), os.path.join(newpath, os.path.splitext(file_)[0] + file_extenstion),delimiter=delimiter)
|
Python
|
UTF-8
| 277
| 3.171875
| 3
|
[] |
no_license
|
import memes
print("Hello Hack Quarantine!")
def main():
print("This is the next step of the workshop!")
print(memes.get_random())
print(memes.get_meme())
print("This is the last step of the workshop!")
print(memes.cats())
print(memes.dogs())
print(memes.fish())
main()
|
Markdown
|
UTF-8
| 3,217
| 2.609375
| 3
|
[] |
no_license
|
---
layout: commandcall
category: CommandCall
title: "QUERY_NON_MOVABLE_MODEL_INCOMING_INTERREFS"
tags: 1.3 1.5
---
QUERY_NON_MOVABLE_MODEL_INCOMING_INTERREFS returns a list of non movable incoming interrefs from one model to another model.
# Syntax:
```adoscript
{% raw %}
QueryNonMovableIncomingInterrefs : QUERY_NON_MOVABLE_MODEL_INCOMING_INTERREFS frommodelid:intValue tomodelid:intValue .
#-->RESULT ecode:intValue reftext:strValue
{% endraw %}
```
{: .line-numbers}
# Parameters:
|`frommodelid`|intValue, the frommodelid, is the model ID of the source of the โto be movedโ interrefs.|
|`tomodelid`|intValue, the tomodelid, is the model ID of the target of the โto be movedโ interrefs.|
# Returns:
|`ecode`|intValue, Contains the error code or is 0 in case of success.|
|`reftext`|strValue|
# Remarks:
Both models need to be loaded for the command to work correctly.
An example of use for this command is in version control. Detailed references of a model A1 will need to be moved on to the successor of the model A2 when A1 is approved, and a new version A2 comes along. A1 is moved into the archives and A2 becomes the new approved version. Thus all interrefs of A1 must now be attached to A2. Before such an action (A2 is released and A1 is archived) all interrefs need to be checked to see if they can really be shifted from A1 to A2. If an object in A2 does not exist any longer and the user needs a warning, this message port is very useful as it returns a list of non movable interrefs.
If there are no non movable interrefs then the returned list will be empty.
If reftext is not empty, it contains 1 to n lines of the following code (each line describing one interref).
REF srcmodelid - intValue
srcdobjid - intValue
srcattrid - intValue
srcobjname - strValue
srcownerid - intValue
srcownerattrid - intValue
targettype - modifier
tmodeltype - strValue
tmodelname - strValue
tversion - strValue
tclassname - strValue
tobjname - strValue '\n'
targettype is either the modifier "model" or "object" depending on whether you have a reference to a model (model reference) or a reference to an object in a model (instance reference).
If srcobjid and srcownerid (and srcattrid and srcownerattrid) contain the same ID, then the reference comes from a modeling instance (with ID scrobjid in model srcmodelid).
If the reference originated from a recordrow, then srcobjid will be the ID of the record row and srcattrid will be the ID of the column within the record.
In this case the owner of the record row (the modeling instance) will be given by srcownerid, and scrownerattrid is the ID of the record attribute.
Note:
In both cases srcobjname will contain the name of the modeling instance!
The target of the reference is given by tmodeltype, tmodelname, tversion, tclassname, and tobjname.
If targettype is "model" you can ignore the variables tclassname and tobjname since they always contain an empty string ("").
# See Also:
Example 1:
```adoscript
{% raw %}
# call QUERY_NON_MOVABLE_MODEL_INCOMING_INTERREFS
CC "Core" QUERY_NON_MOVABLE_MODEL_INCOMING_INTERREFS frommodelid:(id1) tomodelid:(id2)
{% endraw %}
```
{: .line-numbers}
|
Python
|
UTF-8
| 545
| 3.78125
| 4
|
[] |
no_license
|
numbers = [3, 1, 4, 1, 5, 9, 2]
# numbers[0] = 3
# numbers[-1] = 9
# numbers[3] = 1
# numbers[:-1] = 3 1 4 1 5
# numbers[3:4] = 4
# 5 in numbers = [4]
# 7 in numbers = [6]
# "3" in numbers = [0]
# numbers + [6, 5, 3] = 3 1 4 1 5 9 2 6 5 3
print(numbers[0])
print(numbers[-1])
print(numbers[3])
print(numbers[:-1])
print(numbers[3:4])
print(numbers[4])
print(numbers[6])
print(numbers[0])
print(numbers + [6, 5, 3])
numbers[0] = str('ten')
print(numbers)
numbers[-1] = 1
print(numbers[2:])
if 9 in numbers:
print("9 is in list of numbers")
|
Java
|
UTF-8
| 1,114
| 3.5
| 4
|
[] |
no_license
|
//Scan all primitive data types
import java.util.ArrayList;
/**
* Created by: Michias Shiferaw
* Created on: Sept 2016
* Stack of items class.
*/
public class MrCoxallStackpp<S> {
private static final ArrayList<Integer> stackey = new ArrayList<Integer>();
/**
* Created by: Michias Shiferaw
* Created on: Sept 2016
* Stack of items class.
*/
public int peek() {
if (stackey.size() == 0) {
return -1;
} else {
return stackey.get(stackey.size() - 1);
}
}
public void clear() {
stackey.clear();
}
/**
* Created by: Michias Shiferaw
* Created on: Sept 2016
* Stack of items class.
*/
public int pop() {
//removes top value from stack
int delete = stackey.remove(stackey.size() - 1);
return delete;
}
// Adds integers onto stack
public void push(int numbero) {
stackey.add(numbero);
}
/**
* Created by: Michias Shiferaw
* Created on: Sept 2016
* Stack of items class.
*
*/
public String toString() {
String output = "";
for (Integer element : stackey) {
output += element + "\n";
}
return output.toString();
}
}
|
Java
|
UTF-8
| 544
| 1.890625
| 2
|
[] |
no_license
|
package com.sri.straylight.client.util;
import com.sri.straylight.fmuWrapper.voManaged.ScalarValueCollection;
import com.sri.straylight.fmuWrapper.voNative.ConfigStruct;
import com.sri.straylight.fmuWrapper.voNative.SimStateNative;
/**
* The Interface IFmuConnect.
*/
public abstract class FmuConnectionAbstract {
public abstract void setConfig(ConfigStruct configStruct);
public abstract void requestStateChange(SimStateNative newState);
public abstract void setScalarValueCollection(ScalarValueCollection collection);
}
|
SQL
|
UTF-8
| 15,557
| 2.8125
| 3
|
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 3.2.0.1
-- http://www.phpmyadmin.net
--
-- Servidor: localhost
-- Tiempo de generaciรณn: 16-05-2010 a las 14:10:32
-- Versiรณn del servidor: 5.1.36
-- Versiรณn de PHP: 5.3.0
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Base de datos: `sisae`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `asesoria`
--
CREATE TABLE IF NOT EXISTS `asesoria` (
`idAsesorMateria` int(11) NOT NULL AUTO_INCREMENT,
`idAsesor` varchar(50) NOT NULL,
`IdAlumno` varchar(50) NOT NULL,
`Materia` varchar(200) NOT NULL,
`status` varchar(50) NOT NULL,
`Dia` varchar(200) NOT NULL,
PRIMARY KEY (`idAsesorMateria`,`idAsesor`,`IdAlumno`,`status`),
KEY `status` (`status`),
KEY `idAsesor` (`idAsesor`),
KEY `IdAlumno` (`IdAlumno`),
KEY `Dia` (`Dia`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=34 ;
--
-- Volcar la base de datos para la tabla `asesoria`
--
INSERT INTO `asesoria` (`idAsesorMateria`, `idAsesor`, `IdAlumno`, `Materia`, `status`, `Dia`) VALUES
(6, 'Gato', 'marko', 'Quimica', 'ACTIVA', 'Lunes 13:00:00 14:00:00'),
(7, 'Lunita', 'marko', 'Geometria y Trigonometria', 'ACTIVA', 'Lunes 14:00:00 15:00:00'),
(8, 'Gina', 'marko', 'Dibujo Tecnico', 'ACTIVA', 'Miercoles 14:00:00 15:00:00'),
(9, 'Antonio', 'marko', 'Programacion', 'ACTIVA', 'Lunes 14:00:00 15:00:00'),
(10, 'Gato', 'marko', 'Programacion', 'ACTIVA', 'Lunes 15:00:00 16:00:00'),
(11, 'Antonio', 'marko', 'Programacion', 'ACTIVA', 'Lunes 14:00:00 15:00:00'),
(12, 'Gina', 'marko', 'Dibujo Tecnico', 'ACTIVA', 'Miercoles 14:00:00 15:00:00'),
(13, 'Isa', 'marko', 'Quimica', 'ACTIVA', 'Lunes 15:00:00 16:00:00'),
(14, 'Wero', 'marko', 'Quimica', 'ACTIVA', 'Martes 12:00:00 13:00:00'),
(15, 'Antonio', 'marko', 'Programacion', 'ACTIVA', 'Viernes 13:00:00 14:00:00'),
(16, 'Antonio', 'marko', 'Programacion', 'ACTIVA', 'Lunes 14:00:00 15:00:00'),
(17, 'Antonio', 'marko', 'Programacion', 'ACTIVA', 'Lunes 14:00:00 15:00:00'),
(18, 'Victor', 'marko', 'Geometria y Trigonometria', 'ACTIVA', 'Lunes 14:00:00 15:00:00'),
(19, 'Gina', 'marko', 'Dibujo Tecnico', 'ACTIVA', 'Jueves 09:00:00 10:00:00'),
(20, 'Gato', 'marko', 'Quimica', 'ACTIVA', 'Lunes 13:00:00 14:00:00'),
(21, 'Lunita', 'marko', 'Geometria y Trigonometria', 'ACTIVA', 'Lunes 14:00:00 15:00:00'),
(22, 'Antonio', 'marko', 'Programacion', 'ACTIVA', 'Lunes 14:00:00 15:00:00'),
(23, 'Isa', 'max', 'Quimica', 'ACTIVA', 'Lunes 15:00:00 16:00:00'),
(24, 'Lunita', 'max', 'Geometria y Trigonometria', 'ACTIVA', 'Lunes 14:00:00 15:00:00'),
(25, 'Wences', 'max', 'Ingles', 'ACTIVA', 'Lunes 14:00:00 15:00:00'),
(26, 'Gato', 'max', 'Programacion', 'ACTIVA', 'Lunes 15:00:00 16:00:00'),
(27, 'Antonio', 'max', 'Programacion', 'ACTIVA', 'Lunes 14:00:00 15:00:00'),
(28, 'Gato', 'max', 'Quimica', 'ACTIVA', 'Lunes 14:00:00 15:00:00'),
(29, 'Isa', 'maery', 'Quimica', 'ACTIVA', 'Lunes 15:00:00 16:00:00'),
(30, 'Wences', 'maery', 'Ingles', 'ACTIVA', 'Lunes 14:00:00 15:00:00'),
(31, 'Antonio', 'max', 'Programacion', 'ACTIVA', 'Lunes 14:00:00 15:00:00'),
(32, 'Wences', 'max', 'Ingles', 'ACTIVA', 'Lunes 14:00:00 15:00:00'),
(33, 'Antonio', 'max', 'Programacion', 'ACTIVA', 'Lunes 14:00:00 15:00:00');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `asesorusuario`
--
CREATE TABLE IF NOT EXISTS `asesorusuario` (
`idAsesor` varchar(50) NOT NULL,
`Nombres` varchar(50) NOT NULL,
`Paterno` varchar(50) DEFAULT NULL,
`Materno` varchar(50) DEFAULT NULL,
`Boleta` varchar(50) DEFAULT NULL,
`clave` varchar(200) NOT NULL,
`correo` varchar(50) DEFAULT NULL,
`status` varchar(50) NOT NULL,
PRIMARY KEY (`idAsesor`),
KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcar la base de datos para la tabla `asesorusuario`
--
INSERT INTO `asesorusuario` (`idAsesor`, `Nombres`, `Paterno`, `Materno`, `Boleta`, `clave`, `correo`, `status`) VALUES
('Abel', 'Abel', NULL, NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE'),
('Antonio', 'Antonio', NULL, NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE'),
('Darky', 'Giovanna', NULL, NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE'),
('Ely', 'Ely', NULL, NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE'),
('Gato', 'Omar', 'Rodriguez', 'Diaz', '2008081286', '490e3145c1cd9e4aa9b9ca2d6ec782c8', 'mago_1992j@hotmail.com', 'ACTIVE'),
('Gina', 'Gina', 'Rojas', 'Avila', '2008080989', '490e3145c1cd9e4aa9b9ca2d6ec782c8', 'x.cosa@hotmail.com', 'ACTIVE'),
('Isa', 'Isabel', 'Morales', NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE'),
('Ivan', 'Ivan', NULL, NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE'),
('Juan', 'Juan', NULL, NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE'),
('Lalo', 'Eduardo', NULL, NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE'),
('Lunita', 'Cynthia', NULL, NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE'),
('Mariana', 'Mariana', 'Vargas', 'Dominguez', '2008081146', '490e3145c1cd9e4aa9b9ca2d6ec782c8', 'pancakexx_@hotmail.com', 'ACTIVE'),
('mau', 'mau', 'm', 'm', '2', 'e3d0cd173a3342f1d2119cc5bce5d1d4', 'm', 'ACTIVE'),
('maun', 'n', 'n', 'n', 'n', '7b8b965ad4bca0e41ab51de7b31363a1', 'n', 'ACTIVE'),
('Miguel', 'Miguel', NULL, NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE'),
('Miriam', 'Miriam', NULL, NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE'),
('Nely', 'Nely', NULL, NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE'),
('Osvaldo', 'Osvaldo', NULL, NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE'),
('Paola', 'Paola', NULL, NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE'),
('Paty', 'Paty', NULL, NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE'),
('Pity', 'Gabriel', 'Solis', 'Velazquez', '2008081094', '490e3145c1cd9e4aa9b9ca2d6ec782c8', 'gabriel_gs20@hotmail.com', 'EXPULSADO'),
('pu', 'pu', 'p', 'p', 'p', '534b9a3588bdd87bf7c3b9d650e43e46', 'p', 'ACTIVE'),
('Rulo', 'Raul', NULL, NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE'),
('Vero', 'Veronica', NULL, NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE'),
('Victor', 'Victor', NULL, NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE'),
('Wences', 'Wences', NULL, NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE'),
('Wero', 'Ernesto', NULL, NULL, NULL, '490e3145c1cd9e4aa9b9ca2d6ec782c8', NULL, 'ACTIVE');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `asesor_materia`
--
CREATE TABLE IF NOT EXISTS `asesor_materia` (
`IdAsesor_Materia` int(11) NOT NULL AUTO_INCREMENT,
`IdAsesor` varchar(50) NOT NULL,
`IdMateria` int(11) NOT NULL,
PRIMARY KEY (`IdAsesor_Materia`),
KEY `IdAsesor` (`IdAsesor`),
KEY `IdMateria` (`IdMateria`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=48 ;
--
-- Volcar la base de datos para la tabla `asesor_materia`
--
INSERT INTO `asesor_materia` (`IdAsesor_Materia`, `IdAsesor`, `IdMateria`) VALUES
(1, 'Antonio', 1),
(2, 'Gato', 1),
(3, 'Gato', 2),
(4, 'Isa', 2),
(5, 'Wero', 2),
(6, 'Abel', 2),
(7, 'Miriam', 2),
(8, 'Vero', 2),
(9, 'Lalo', 2),
(10, 'Paola', 2),
(11, 'Victor', 2),
(12, 'Rulo', 2),
(13, 'Victor', 3),
(14, 'Lunita', 3),
(15, 'Wences', 3),
(16, 'Osvaldo', 3),
(17, 'Miguel', 3),
(18, 'Paty', 3),
(19, 'Rulo', 3),
(20, 'Pity', 3),
(21, 'Ivan', 3),
(22, 'Wero', 3),
(23, 'Gina', 4),
(24, 'Lunita', 4),
(25, 'Wences', 5),
(26, 'Darky', 5),
(27, 'Juan', 6),
(28, 'Ely', 6),
(29, 'Ivan', 6),
(30, 'Osvaldo', 6),
(31, 'Antonio', 6),
(32, 'Pity', 6),
(33, 'Ely', 7),
(34, 'Miguel', 7),
(35, 'Isa', 7),
(36, 'Miriam', 8),
(37, 'Isa', 8),
(38, 'Nely', 8),
(39, 'Paty', 8),
(40, 'Paola', 9),
(41, 'Nely', 9),
(42, 'Lalo', 9),
(43, 'Isa', 9),
(44, 'Pity', 9),
(45, 'Vero', 10),
(46, 'Juan', 10),
(47, 'Wero', 10);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `horarios`
--
CREATE TABLE IF NOT EXISTS `horarios` (
`idHorario` int(11) NOT NULL AUTO_INCREMENT,
`Dia` varchar(50) NOT NULL,
`Horainic` time NOT NULL,
`Horafin` time NOT NULL,
`IdAsesor` varchar(50) NOT NULL,
`IdMateria` int(11) DEFAULT NULL,
PRIMARY KEY (`idHorario`),
KEY `IdAsesor` (`IdAsesor`),
KEY `Dia` (`Dia`),
KEY `IdMateria` (`IdMateria`),
KEY `IdMateria_2` (`IdMateria`),
KEY `Dia_2` (`Dia`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=46 ;
--
-- Volcar la base de datos para la tabla `horarios`
--
INSERT INTO `horarios` (`idHorario`, `Dia`, `Horainic`, `Horafin`, `IdAsesor`, `IdMateria`) VALUES
(2, 'Lunes', '14:00:00', '15:00:00', 'Antonio', 1),
(3, 'Lunes', '15:00:00', '16:00:00', 'Gato', 1),
(4, 'Viernes', '13:00:00', '14:00:00', 'Antonio', 1),
(5, 'Lunes', '13:00:00', '14:00:00', 'Gato', 2),
(6, 'Lunes', '14:00:00', '15:00:00', 'Gato', 2),
(7, 'Lunes', '15:00:00', '16:00:00', 'Isa', 2),
(8, 'Martes', '12:00:00', '13:00:00', 'Wero', 2),
(9, 'Martes', '13:00:00', '14:00:00', 'Wero', 2),
(11, 'Martes', '14:00:00', '15:00:00', 'Isa', 2),
(12, 'Miercoles', '13:00:00', '14:00:00', 'Abel', 2),
(13, 'Miercoles', '14:00:00', '15:00:00', 'Abel', 2),
(14, 'Jueves', '14:00:00', '15:00:00', 'Miriam', 2),
(15, 'Jueves', '14:00:00', '15:00:00', 'Vero', 2),
(16, 'Jueves', '14:00:00', '15:00:00', 'Lalo', 2),
(17, 'Viernes', '11:00:00', '12:00:00', 'Paola', 2),
(18, 'Viernes', '13:00:00', '14:00:00', 'Victor', 2),
(19, 'Viernes', '14:00:00', '15:00:00', 'Rulo', 2),
(20, 'Lunes', '14:00:00', '15:00:00', 'Victor', 3),
(22, 'Lunes', '14:00:00', '15:00:00', 'Lunita', 3),
(23, 'Lunes', '15:00:00', '16:00:00', 'Wences', 3),
(24, 'Martes', '11:00:00', '12:00:00', 'Osvaldo', 3),
(25, 'Martes', '12:00:00', '13:00:00', 'Osvaldo', 3),
(26, 'Martes', '14:00:00', '15:00:00', 'Victor', 3),
(27, 'Martes', '14:00:00', '15:00:00', 'Lunita', 3),
(28, 'Miercoles', '13:00:00', '14:00:00', 'Miguel', 3),
(30, 'Miercoles', '13:00:00', '14:00:00', 'Paty', 3),
(31, 'Miercoles', '14:00:00', '15:00:00', 'Miguel', 3),
(32, 'Miercoles', '14:00:00', '15:00:00', 'Paty', 3),
(33, 'Jueves', '13:00:00', '14:00:00', 'Rulo', 3),
(34, 'Jueves', '14:00:00', '15:00:00', 'Pity', 3),
(35, 'Jueves', '14:00:00', '15:00:00', 'Rulo', 3),
(36, 'Viernes', '13:00:00', '14:00:00', 'Ivan', 3),
(37, 'Viernes', '13:00:00', '14:00:00', 'Wero', 3),
(38, 'Viernes', '14:00:00', '15:00:00', 'Wences', 3),
(39, 'Miercoles', '14:00:00', '15:00:00', 'Gina', 4),
(40, 'Miercoles', '14:00:00', '15:00:00', 'Lunita', 4),
(41, 'Jueves', '09:00:00', '10:00:00', 'Gina', 4),
(42, 'Lunes', '14:00:00', '15:00:00', 'Wences', 5),
(43, 'Martes', '14:00:00', '15:00:00', 'Darky', 5),
(44, 'Miercoles', '14:00:00', '15:00:00', 'Wences', 5),
(45, 'Viernes', '13:00:00', '14:00:00', 'Darky', 5);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `materias`
--
CREATE TABLE IF NOT EXISTS `materias` (
`idMateria` int(11) NOT NULL AUTO_INCREMENT,
`Materia` varchar(30) NOT NULL,
PRIMARY KEY (`idMateria`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
--
-- Volcar la base de datos para la tabla `materias`
--
INSERT INTO `materias` (`idMateria`, `Materia`) VALUES
(1, 'Programacion'),
(2, 'Quimica'),
(3, 'Geometria y Trigonometria'),
(4, 'Dibujo Tecnico'),
(5, 'Ingles'),
(6, 'Calculo Diferencial'),
(7, 'Filosofia'),
(8, 'Fisica'),
(9, 'Historia'),
(10, 'Biologia');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `status`
--
CREATE TABLE IF NOT EXISTS `status` (
`status` varchar(50) NOT NULL,
PRIMARY KEY (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcar la base de datos para la tabla `status`
--
INSERT INTO `status` (`status`) VALUES
('ACTIVE'),
('BLOQUEADO'),
('EXPULSADO'),
('INACTIVO'),
('SUSPENDIDO');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `status_asesoria`
--
CREATE TABLE IF NOT EXISTS `status_asesoria` (
`status_Asesoria` varchar(50) NOT NULL,
PRIMARY KEY (`status_Asesoria`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcar la base de datos para la tabla `status_asesoria`
--
INSERT INTO `status_asesoria` (`status_Asesoria`) VALUES
('ACTIVA'),
('FINALIZADA'),
('SUSPENDIDA');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `usuarioalumno`
--
CREATE TABLE IF NOT EXISTS `usuarioalumno` (
`IdAlumno` varchar(50) NOT NULL,
`Nombre` varchar(50) NOT NULL,
`Paterno` varchar(50) NOT NULL,
`Materno` varchar(50) NOT NULL,
`Boleta` varchar(20) NOT NULL,
`Clave` varchar(200) NOT NULL,
`Correo` varchar(50) NOT NULL,
`status` varchar(50) NOT NULL,
PRIMARY KEY (`IdAlumno`),
KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcar la base de datos para la tabla `usuarioalumno`
--
INSERT INTO `usuarioalumno` (`IdAlumno`, `Nombre`, `Paterno`, `Materno`, `Boleta`, `Clave`, `Correo`, `status`) VALUES
('maery', 'maritza', 'hernandez', 'hernandez', '55', 'e389cb43132a236f3c11e96d4557a28e', '55', 'ACTIVE'),
('marko', 'marko', 'mayen', 'hdz', '222', '37efe2e47d7691194b8b64b7301243d3', 'ppp', 'ACTIVE'),
('max', 'marko', 'mayen', 'hernandez', '2008080699', '37efe2e47d7691194b8b64b7301243d3', 'mmm', 'ACTIVE'),
('mental', 'mariano', 'sample', 'll', 'l', '37efe2e47d7691194b8b64b7301243d3', 'l', 'ACTIVE');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `usuarios`
--
CREATE TABLE IF NOT EXISTS `usuarios` (
`nombre` varchar(30) NOT NULL,
`clave` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcar la base de datos para la tabla `usuarios`
--
INSERT INTO `usuarios` (`nombre`, `clave`) VALUES
('sas', 'sas'),
('hdjkashdjkhas', 'jhdjkshfjksdfh'),
('gato', 'erika'),
('marko', 'yeisuli'),
('pity', 'isabel');
--
-- Filtros para las tablas descargadas (dump)
--
--
-- Filtros para la tabla `asesoria`
--
ALTER TABLE `asesoria`
ADD CONSTRAINT `asesoria_ibfk_10` FOREIGN KEY (`idAsesor`) REFERENCES `asesorusuario` (`idAsesor`),
ADD CONSTRAINT `asesoria_ibfk_11` FOREIGN KEY (`IdAlumno`) REFERENCES `usuarioalumno` (`IdAlumno`),
ADD CONSTRAINT `asesoria_ibfk_12` FOREIGN KEY (`status`) REFERENCES `status_asesoria` (`status_Asesoria`);
--
-- Filtros para la tabla `asesorusuario`
--
ALTER TABLE `asesorusuario`
ADD CONSTRAINT `asesorusuario_ibfk_1` FOREIGN KEY (`status`) REFERENCES `status` (`status`);
--
-- Filtros para la tabla `asesor_materia`
--
ALTER TABLE `asesor_materia`
ADD CONSTRAINT `asesor_materia_ibfk_2` FOREIGN KEY (`IdMateria`) REFERENCES `materias` (`idMateria`),
ADD CONSTRAINT `asesor_materia_ibfk_3` FOREIGN KEY (`IdAsesor`) REFERENCES `asesorusuario` (`idAsesor`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Filtros para la tabla `horarios`
--
ALTER TABLE `horarios`
ADD CONSTRAINT `horarios_ibfk_1` FOREIGN KEY (`IdAsesor`) REFERENCES `asesorusuario` (`idAsesor`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `horarios_ibfk_2` FOREIGN KEY (`IdMateria`) REFERENCES `materias` (`idMateria`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Filtros para la tabla `usuarioalumno`
--
ALTER TABLE `usuarioalumno`
ADD CONSTRAINT `usuarioalumno_ibfk_1` FOREIGN KEY (`status`) REFERENCES `status` (`status`);
|
JavaScript
|
UTF-8
| 1,879
| 3
| 3
|
[] |
no_license
|
/**
* Main rendering function for GET request
*/
function doGet() {
return HtmlService.createHtmlOutputFromFile('calc.html')
.addMetaTag('viewport', 'width=device-width, initial-scale=1')
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
var MAX_REWARD = 50 * 1e6;
/**
* Calculate the reward and type of hauler needed for a given value of goods
* to haul and volume.
*
* TODO: Consider evepraisal or inventory block result.
* Note, this has difficulty with packaged ship volumes. Evepraisal always
* returns the unpacked ship volume, and has no way to differentiate between a
* packaged or unpackaged ship. It's unclear how a copy and paste from the EVE
* inventory would deal with this.
*/
function calculateReward(value, volume) {
value = parseInt(value.replace(/,/g, ''));
volume = parseFloat(volume.replace(/,/g, ''));
// Returns the cheapest, fastest hauler that the cargo fits in
var fitsIn = function(value, volume) {
var hauler_limits = [ // Ordered by value and volume from least to greatest
{ type: 'Interceptor', value: 100 * 1e6, volume: 100 },
{ type: 'T1 Industrial', value: 100 * 1e6, volume: 30000 },
{ type: 'Blockade Runner', value: 500 * 1e6, volume: 9000 },
{ type: 'Deep Space Transport', value: 500 * 1e6, volume: 55000 },
{ type: 'Orca', value: 2000 * 1e6, volume: 90000 },
];
for (var i = 0; i < hauler_limits.length; i++) {
var hauler = hauler_limits[i];
if (value <= hauler.value && volume <= hauler.volume) {
return hauler.type;
}
}
return "Doesn't even fit in an Orca!";
};
// TODO error handling
return {
value: value,
hauler_type: fitsIn(value, volume),
reward: MAX_REWARD * Math.max(value / (500 * 1e6),
volume / 60000)
};
}
|
Python
|
UTF-8
| 15,898
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
import numpy as np
from abc import ABCMeta, abstractmethod
from ezclimate.damage_simulation import DamageSimulation
from ezclimate.forcing import Forcing
class Damage(object, metaclass=ABCMeta):
"""Abstract damage class for the EZ-Climate model.
Parameters
----------
tree : `TreeModel` object
provides the tree structure used
bau : `BusinessAsUsual` object
business-as-usual scenario of emissions
Attributes
----------
tree : `TreeModel` object
provides the tree structure used
bau : `BusinessAsUsual` object
business-as-usual scenario of emissions
"""
def __init__(self, tree, bau):
self.tree = tree
self.bau = bau
@abstractmethod
def average_mitigation(self):
"""The average_mitigation function should return a 1D array of the
average mitigation for every node in the period.
"""
pass
@abstractmethod
def damage_function(self):
"""The damage_function should return a 1D array of the damages for
every node in the period.
"""
pass
class DLWDamage(Damage):
"""Damage class for the EZ-Climate model. Provides the damages from emissions and mitigation outcomes.
Parameters
----------
tree : `TreeModel` object
provides the tree structure used
bau : `BusinessAsUsual` object
business-as-usual scenario of emissions
cons_growth : float
constant consumption growth rate
ghg_levels : ndarray or list
end GHG levels for each end scenario
Attributes
----------
tree : `TreeModel` object
provides the tree structure used
bau : `BusinessAsUsual` object
business-as-usual scenario of emissions
cons_growth : float
constant consumption growth rate
ghg_levels : ndarray or list
end GHG levels for each end scenario
dnum : int
number of simulated damage paths
d : ndarray
simulated damages
d_rcomb : ndarray
adjusted simulated damages for recombining tree
cum_forcings : ndarray
cumulative forcing interpolation coeffiecients, used to calculate forcing based mitigation
forcing : `Forcing` object
class for calculating cumulative forcing and GHG levels
damage_coefs : ndarray
interpolation coefficients used to calculate damages
"""
def __init__(self, tree, bau, cons_growth, ghg_levels, subinterval_len):
super(DLWDamage, self).__init__(tree, bau)
self.ghg_levels = ghg_levels
if isinstance(self.ghg_levels, list):
self.ghg_levels = np.array(self.ghg_levels)
self.cons_growth = cons_growth
self.dnum = len(ghg_levels)
self.subinterval_len = subinterval_len
self.cum_forcings = None
self.d = None
self.d_rcomb = None
self.emit_pct = None
self.damage_coefs = None
def _recombine_nodes(self):
"""Creating damage coefficients for recombining tree. The state reached by an up-down move is
separate from a down-up move because in general the two paths will lead to different degrees of
mitigation and therefore of GHG level. A 'recombining' tree is one in which the movement from
one state to the next through time is nonetheless such that an up move followed by a down move
leads to the same fragility.
"""
nperiods = self.tree.num_periods
sum_class = np.zeros(nperiods, dtype=int)
new_state = np.zeros([nperiods, self.tree.num_final_states], dtype=int)
temp_prob = self.tree.final_states_prob.copy()
self.d_rcomb = self.d.copy()
for old_state in range(self.tree.num_final_states):
temp = old_state
n = nperiods-2
d_class = 0
while n >= 0:
if temp >= 2**n:
temp -= 2**n
d_class += 1
n -= 1
sum_class[d_class] += 1
new_state[d_class, sum_class[d_class]-1] = old_state
sum_nodes = np.append(0, sum_class.cumsum())
prob_sum = np.array([self.tree.final_states_prob[sum_nodes[i]:sum_nodes[i+1]].sum() for i in range(len(sum_nodes)-1)])
for period in range(nperiods):
for k in range(self.dnum):
d_sum = np.zeros(nperiods)
old_state = 0
for d_class in range(nperiods):
d_sum[d_class] = (self.tree.final_states_prob[old_state:old_state+sum_class[d_class]] * self.d_rcomb[k, old_state:old_state+sum_class[d_class], period]).sum()
old_state += sum_class[d_class]
self.tree.final_states_prob[new_state[d_class, 0:sum_class[d_class]]] = temp_prob[0]
for d_class in range(nperiods):
self.d_rcomb[k, new_state[d_class, 0:sum_class[d_class]], period] = d_sum[d_class] / prob_sum[d_class]
self.tree.node_prob[-len(self.tree.final_states_prob):] = self.tree.final_states_prob
for p in range(1,nperiods-1):
nodes = self.tree.get_nodes_in_period(p)
for node in range(nodes[0], nodes[1]+1):
worst_end_state, best_end_state = self.tree.reachable_end_states(node, period=p)
self.tree.node_prob[node] = self.tree.final_states_prob[worst_end_state:best_end_state+1].sum()
def _damage_interpolation(self):
"""Create the interpolation coefficients used in `damage_function`."""
if self.d is None:
print("Importing stored damage simulation")
self.import_damages()
self._recombine_nodes()
if self.emit_pct is None:
bau_emission = self.bau.ghg_end - self.bau.ghg_start
self.emit_pct = 1.0 - (self.ghg_levels-self.bau.ghg_start) / bau_emission
self.damage_coefs = np.zeros((self.tree.num_final_states, self.tree.num_periods, self.dnum-1, self.dnum))
amat = np.ones((self.tree.num_periods, self.dnum, self.dnum))
bmat = np.ones((self.tree.num_periods, self.dnum))
self.damage_coefs[:, :, -1, -1] = self.d_rcomb[-1, :, :]
self.damage_coefs[:, :, -1, -2] = (self.d_rcomb[-2, :, :] - self.d_rcomb[-1, :, :]) / self.emit_pct[-2]
amat[:, 0, 0] = 2.0 * self.emit_pct[-2]
amat[:, 1:, 0] = self.emit_pct[:-1]**2
amat[:, 1:, 1] = self.emit_pct[:-1]
amat[:, 0, -1] = 0.0
for state in range(0, self.tree.num_final_states):
bmat[:, 0] = self.damage_coefs[state, :, -1, -2] * self.emit_pct[-2]
bmat[:, 1:] = self.d_rcomb[:-1, state, :].T
self.damage_coefs[state, :, 0] = np.linalg.solve(amat, bmat)
def import_damages(self, file_name="simulated_damages"):
"""Import saved simulated damages. File must be saved in 'data' directory
inside current working directory. Save imported values in `d`.
Parameters
----------
file_name : str, optional
name of file of saved simulated damages
Raises
------
IOError
If file does not exist.
"""
from ezclimate.tools import import_csv
try:
d = import_csv(file_name, ignore="#", header=False)
except IOError as e:
import sys
print(("Could not import simulated damages:\n\t{}".format(e)))
sys.exit(0)
n = self.tree.num_final_states
self.d = np.array([d[n*i:n*(i+1)] for i in range(0, self.dnum)])
self._damage_interpolation()
def damage_simulation(self, draws, peak_temp=9.0, disaster_tail=12.0, tip_on=True,
multi_tips=False, temp_map=1, temp_dist_params=None, maxh=100.0, save_simulation=True):
"""Initialization and simulation of damages, given by :mod:`ez_climate.DamageSimulation`.
Parameters
----------
draws : int
number of Monte Carlo draws
peak_temp : float, optional
tipping point parameter
disaster_tail : float, optional
curvature of tipping point
tip_on : bool, optional
flag that turns tipping points on or off
multi_tips : bool, optional
if to allow multiple tipping points in simulation
temp_map : int, optional
mapping from GHG to temperature
* 0: implies Pindyck displace gamma
* 1: implies Wagner-Weitzman normal
* 2: implies Roe-Baker
* 3: implies user-defined normal
* 4: implies user-defined gamma
temp_dist_params : ndarray or list, optional
if temp_map is either 3 or 4, user needs to define the distribution parameters
maxh : float, optional
time parameter from Pindyck which indicates the time it takes for temp to get half
way to its max value for a given level of ghg
cons_growth : float, optional
yearly growth in consumption
save_simulation : bool, optional
True if simulated values should be save, False otherwise
Returns
-------
ndarray
simulated damages
"""
ds = DamageSimulation(tree=self.tree, ghg_levels=self.ghg_levels, peak_temp=peak_temp,
disaster_tail=disaster_tail, tip_on=tip_on, temp_map=temp_map,
temp_dist_params=temp_dist_params, maxh=maxh, cons_growth=self.cons_growth)
self.ds = ds
print("Starting damage simulation..")
self.d = ds.simulate(draws, write_to_file=save_simulation, multiple_tipping_points=multi_tips)
print("Done!")
self._damage_interpolation()
return self.d
def _forcing_based_mitigation(self, forcing, period):
"""Calculation of mitigation based on forcing up to period. Interpolating between the forcing associated
with the constant degree of mitigation consistent with the damage simulation scenarios.
"""
p = period - 1
if forcing > self.cum_forcings[p][1]:
weight_on_sim2 = (self.cum_forcings[p][2] - forcing) / (self.cum_forcings[p][2] - self.cum_forcings[p][1])
weight_on_sim3 = 0
elif forcing > self.cum_forcings[p][0]:
weight_on_sim2 = (forcing - self.cum_forcings[p][0]) / (self.cum_forcings[p][1] - self.cum_forcings[p][0])
weight_on_sim3 = (self.cum_forcings[p][1] - forcing) / (self.cum_forcings[p][1] - self.cum_forcings[p][0])
else:
weight_on_sim2 = 0
weight_on_sim3 = 1.0 + (self.cum_forcings[p][0] - forcing) / self.cum_forcings[p][0]
return weight_on_sim2 * self.emit_pct[1] + weight_on_sim3*self.emit_pct[0]
def _forcing_init(self):
"""Initialize `Forcing` object and cum_forcings used in calculating the force mitigation up to a node."""
if self.emit_pct is None:
bau_emission = self.bau.ghg_end - self.bau.ghg_start
self.emit_pct = 1.0 - (self.ghg_levels-self.bau.ghg_start) / bau_emission
self.cum_forcings = np.zeros((self.tree.num_periods, self.dnum))
mitigation = np.ones((self.dnum, self.tree.num_decision_nodes)) * self.emit_pct[:, np.newaxis]
for i in range(0, self.dnum):
for n in range(1, self.tree.num_periods+1):
node = self.tree.get_node(n, 0)
self.cum_forcings[n-1, i] = Forcing.forcing_at_node(mitigation[i], node, self.tree,
self.bau, self.subinterval_len)
def average_mitigation_node(self, m, node, period=None):
"""Calculate the average mitigation until node.
Parameters
----------
m : ndarray or list
array of mitigation
node : int
node for which average mitigation is to be calculated for
period : int, optional
the period the node is in
Returns
-------
float
average mitigation
"""
if period == 0:
return 0
if period is None:
period = self.tree.get_period(node)
state = self.tree.get_state(node, period)
path = self.tree.get_path(node, period)
new_m = m[path[:-1]]
period_len = self.tree.decision_times[1:period+1] - self.tree.decision_times[:period]
bau_emissions = self.bau.emission_by_decisions[:period]
total_emission = np.dot(bau_emissions, period_len)
ave_mitigation = np.dot(new_m, bau_emissions*period_len)
return ave_mitigation / total_emission
def average_mitigation(self, m, period):
"""Calculate the average mitigation for all node in a period.
m : ndarray or list
array of mitigation
period : int
period to calculate average mitigation for
Returns
-------
ndarray
average mitigations
"""
nodes = self.tree.get_num_nodes_period(period)
ave_mitigation = np.zeros(nodes)
for i in range(nodes):
node = self.tree.get_node(period, i)
ave_mitigation[i] = self.average_mitigation_node(m, node, period)
return ave_mitigation
def _ghg_level_node(self, m, node):
return Forcing.ghg_level_at_node(m, node, self.tree, self.bau, self.subinterval_len)
def ghg_level_period(self, m, period=None, nodes=None):
"""Calculate the GHG levels corresponding to the given mitigation.
Need to provide either `period` or `nodes`.
Parameters
----------
m : ndarray or list
array of mitigation
period : int, optional
what period to calculate GHG levels for
nodes : ndarray or list, optional
the nodes to calculate GHG levels for
Returns
-------
ndarray
GHG levels
"""
if nodes is None and period is not None:
start_node, end_node = self.tree.get_nodes_in_period(period)
if period >= self.tree.num_periods:
add = end_node-start_node+1
start_node += add
end_node += add
nodes = np.array(list(range(start_node, end_node+1)))
if period is None and nodes is None:
raise ValueError("Need to give function either nodes or the period")
ghg_level = np.zeros(len(nodes))
for i in range(len(nodes)):
ghg_level[i] = self._ghg_level_node(m, nodes[i])
return ghg_level
def ghg_level(self, m, periods=None):
"""Calculate the GHG levels for more than one period.
Parameters
----------
m : ndarray or list
array of mitigation
periods : int, optional
number of periods to calculate GHG levels for
Returns
-------
ndarray
GHG levels
"""
if periods is None:
periods = self.tree.num_periods-1
if periods >= self.tree.num_periods:
ghg_level = np.zeros(self.tree.num_decision_nodes+self.tree.num_final_states)
else:
ghg_level = np.zeros(self.tree.num_decision_nodes)
for period in range(periods+1):
start_node, end_node = self.tree.get_nodes_in_period(period)
if period >= self.tree.num_periods:
add = end_node-start_node+1
start_node += add
end_node += add
nodes = np.array(list(range(start_node, end_node+1)))
ghg_level[nodes] = self.ghg_level_period(m, nodes=nodes)
return ghg_level
def _damage_function_node(self, m, node):
"""Calculate the damage at any given node, based on mitigation actions in `m`."""
if self.damage_coefs is None:
self._damage_interpolation()
if self.cum_forcings is None:
self._forcing_init()
if node == 0:
return 0.0
period = self.tree.get_period(node)
forcing, ghg_level = Forcing.forcing_and_ghg_at_node(m, node, self.tree, self.bau, self.subinterval_len, "both")
force_mitigation = self._forcing_based_mitigation(forcing, period)
ghg_extension = 1.0 / (1 + np.exp(0.05*(ghg_level-200)))
worst_end_state, best_end_state = self.tree.reachable_end_states(node, period=period)
probs = self.tree.final_states_prob[worst_end_state:best_end_state+1]
if force_mitigation < self.emit_pct[1]:
damage = (probs *(self.damage_coefs[worst_end_state:best_end_state+1, period-1, 1, 1] * force_mitigation \
+ self.damage_coefs[worst_end_state:best_end_state+1, period-1, 1, 2])).sum()
elif force_mitigation < self.emit_pct[0]:
damage = (probs * (self.damage_coefs[worst_end_state:best_end_state+1, period-1, 0, 0] * force_mitigation**2 \
+ self.damage_coefs[worst_end_state:best_end_state+1, period-1, 0, 1] * force_mitigation \
+ self.damage_coefs[worst_end_state:best_end_state+1, period-1, 0, 2])).sum()
else:
damage = 0.0
i = 0
for state in range(worst_end_state, best_end_state+1):
if self.d_rcomb[0, state, period-1] > 1e-5:
deriv = 2.0 * self.damage_coefs[state, period-1, 0, 0]*self.emit_pct[0] \
+ self.damage_coefs[state, period-1, 0, 1]
decay_scale = deriv / (self.d_rcomb[0, state, period-1]*np.log(0.5))
dist = force_mitigation - self.emit_pct[0] + np.log(self.d_rcomb[0, state, period-1]) \
/ (np.log(0.5) * decay_scale)
damage += probs[i] * (0.5**(decay_scale*dist) * np.exp(-np.square(force_mitigation-self.emit_pct[0])/60.0))
i += 1
return (damage / probs.sum()) + ghg_extension
def damage_function(self, m, period):
"""Calculate the damage for every node in a period, based on mitigation actions `m`.
Parameters
----------
m : ndarray or list
array of mitigation
period : int
period to calculate damages for
Returns
-------
ndarray
damages
"""
nodes = self.tree.get_num_nodes_period(period)
damages = np.zeros(nodes)
for i in range(nodes):
node = self.tree.get_node(period, i)
damages[i] = self._damage_function_node(m, node)
return damages
|
Java
|
UTF-8
| 4,350
| 2.4375
| 2
|
[] |
no_license
|
package com.crossover.trial.properties;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import com.amazonaws.regions.Region;
import com.crossover.trial.properties.util.Logger;
import com.crossover.trial.properties.util.ParametersMap;
import com.crossover.trial.properties.util.PropertiesTypeResolver;
import com.crossover.trial.properties.util.PropertiesUtil;
public class PropertyManager {
private static final Logger logger = new Logger();
private int nThreads = PropertiesUtil.NUM_OF_THREADS;
private final ExecutorService executor =
Executors.newFixedThreadPool(nThreads);
//private final ExecutorService executor = Executors
//.newSingleThreadExecutor();
private final Collection<Callable<Properties>> tasks = new ArrayList<Callable<Properties>>();
private volatile ParametersMap<Object, Object> finalMap = new ParametersMap<Object, Object>();
public void init(String[] args) {
for (int itr = 0; itr < args.length; itr++) {
if (args[itr] != null && args[itr].trim().length() > 10) {// 10 is
// just
// a
// sanity
// check
PropertyThrottle propertyThrottle = new PropertyThrottle(
args[itr]);
tasks.add(propertyThrottle);
}
}
if (tasks.size() > 0) {
List<Future<Properties>> results = null;
try {
results = executor.invokeAll(tasks, 80, TimeUnit.SECONDS);
tasks.clear();
} catch (InterruptedException ie) {
logger.writeErrorStackTrace(ie);
}
for (Future<Properties> f : results) {
try {
Properties properties = f.get();
if(properties != null) {
for(Entry<Object,Object> e: properties.entrySet()) {
finalMap.put(e.getKey(), PropertiesTypeResolver.getType(e.getValue().toString()));
}
}
logger.writeDebugLog("Outbound : " + properties);
} catch (InterruptedException e) {
logger.writeErrorStackTrace(e);
} catch (ExecutionException e) {
// TODO Auto-generated catch block
logger.writeErrorStackTrace(e);
}
}
results.clear();
shutDown();
prettyPrint(finalMap);
}
}
public String getStringProperty(Object paramObject) {
return finalMap.getString(paramObject);
}
public Long getLongProperty(Object paramObject) {
return finalMap.getLong(paramObject);
}
public Double getDoubleProperty(Object paramObject) {
return finalMap.getDouble(paramObject);
}
public Boolean getBooleanProperty(Object paramObject) {
return finalMap.getBoolean(paramObject);
}
public Region getRegionProperty(Object paramObject) {
return finalMap.getAWSRegions(paramObject);
}
public Object putInProperties(Object key, Object value) {
return finalMap.put(key, value);
}
public void prettyPrint(ParametersMap<Object, Object> map) {
StringBuffer sb = new StringBuffer(1024*8);
List<String> values = new ArrayList<String>();
for(Entry<Object,Object> e: map.entrySet()) {
values.add(e.getKey().toString());
}
Collections.sort(values, new Comparator<String>() {
public int compare(String a, String b) {
return a.compareTo(b);
}
});
for(int i = 0; i < values.size(); i++) {
String key = values.get(i);
sb.append(key.toLowerCase()).append(", ").append(map.get(key).getClass().getCanonicalName()).append(", ").append(map.get(key)).append("\r\n");
}
System.out.println(sb.toString());
}
private void shutDown() {
try {
logger.writeDebugLog("attempt to shutdown executor");
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.writeErrorLog("tasks interrupted");
} finally {
if (!executor.isTerminated()) {
logger.writeErrorLog("cancel non-finished tasks");
}
// (Re-)Cancel if current thread also interrupted
executor.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
logger.writeDebugLog("shutdown finished");
}
}
}
|
Java
|
UTF-8
| 9,659
| 1.929688
| 2
|
[] |
no_license
|
package com.example.pang.spacedelivery.Customer;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.example.pang.spacedelivery.MainActivity;
import com.example.pang.spacedelivery.R;
import com.example.pang.spacedelivery.food;
import com.example.pang.spacedelivery.interfaces.AddorRemoveCallbacks;
import com.example.pang.spacedelivery.ipConfig;
import com.google.gson.JsonObject;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import java.util.List;
import static android.content.Context.MODE_PRIVATE;
public class FoodInRestaurantAdapter extends RecyclerView.Adapter<FoodInRestaurantAdapter.ViewHolder> {
private List<food> mFoodList;
private Context mContext;
private RecyclerView mRecyclerV;
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView foodNameTxtV;
public TextView foodPriceTxtV;
public ImageView foodImageImgV;
public TextView foodDetailTxtV;
public TextView foodChooseTxtV;
public View layout;
public ViewHolder(View v) {
super(v);
layout = v;
foodNameTxtV = (TextView) v.findViewById(R.id.textViewName);
foodPriceTxtV = (TextView) v.findViewById(R.id.textViewPrice);
foodImageImgV = (ImageView) v.findViewById(R.id.imageViewDis);
foodDetailTxtV = (TextView) v.findViewById(R.id.textViewDetail);
foodChooseTxtV = (TextView) v.findViewById(R.id.textViewChoose);
}
}
public void add(int position, food food) {
mFoodList.add(position, food);
notifyItemInserted(position);
}
public void remove(int position) {
mFoodList.remove(position);
notifyItemRemoved(position);
}
public FoodInRestaurantAdapter(List<food> myDataset, Context context, RecyclerView recyclerView) {
mFoodList = myDataset;
mContext = context;
mRecyclerV = recyclerView;
}
@Override
public FoodInRestaurantAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
LayoutInflater inflater = LayoutInflater.from(
parent.getContext());
View v =
inflater.inflate(R.layout.activity_food_in_restaurant_adapter, parent, false);
FoodInRestaurantAdapter.ViewHolder vh = new FoodInRestaurantAdapter.ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(final FoodInRestaurantAdapter.ViewHolder holder, final int position) {
ipConfig ip = new ipConfig();
final String baseUrl = ip.getBaseUrlFood() ;
final food food = mFoodList.get(position);
holder.foodNameTxtV.setText("เนเธกเธเธน: " + food.getFoodName());
holder.foodPriceTxtV.setText("เธฃเธฒเธเธฒ: " + food.getFoodPrice()+" เธเธฒเธ");
Ion.with(mContext)
.load(baseUrl+"upload-img/"+food.getFoodImage())
.intoImageView(holder.foodImageImgV);
holder.foodDetailTxtV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
goToUpdateActivity(food.getFoodId(),food.getFoodName(),food.getFoodDetail(),food.getFoodImage(),food.getFoodPrice(),food.getFoodStamp());
}
});
if(food.getCheckChoose().equals("pass"))
{
if(mContext instanceof FoodInRestaurant)
{
mFoodList.get(position).setAddedTocart(true);
holder.foodChooseTxtV.setText("เธขเธเนเธฅเธดเธเนเธฅเธทเธญเธ");
}
}else
{
mFoodList.get(position).setAddedTocart(false);
holder.foodChooseTxtV.setText("เนเธฅเธทเธญเธ");
}
holder.foodChooseTxtV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!mFoodList.get(position).isAddedTocart())
{
if(mContext instanceof FoodInRestaurant)
{
ipConfig ip1 = new ipConfig();
final String baseUrl1 = ip1.getBaseUrlCart() ;
SharedPreferences sharedpreferences;
final String MyPREFERENCES = "MyPrefs" ;
final String User_id = "userKey";
sharedpreferences = mContext.getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
final String user_id1 = sharedpreferences.getString(User_id, "");
Ion.with(mContext)
.load(baseUrl1+"addToCart.php")
.setMultipartParameter("user_id",user_id1)
.setMultipartParameter("food_id", String.valueOf(food.getFoodId()))
.asString()
.setCallback(new FutureCallback<String>() {
@Override
public void onCompleted(Exception e, String result) {
if(result.equals("cannotAdd")){
System.out.println("TEST"+result);
new AlertDialog.Builder(mContext)
.setTitle("เนเธฅเธทเธญเธเธฃเธฒเธขเธเธฒเธฃเธญเธฒเธซเธฒเธฃ")
.setMessage("เนเธกเนเธชเธฒเธกเธฒเธฃเธเนเธฅเธทเธญเธเธฃเธฒเธขเธเธฒเธฃเธญเธฒเธซเธฒเธฃเธชเธฑเนเธเธซเธฅเธฒเธขเธฃเนเธฒเธเนเธเน เนเธฅเธทเธญเธเนเธเนเนเธเธเธฒเธฐเธฃเนเธฒเธเนเธเธตเธขเธงเนเธเนเธฒเธเธฑเนเธ")
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_menu_close_clear_cancel)
.show();
}else {
mFoodList.get(position).setAddedTocart(true);
holder.foodChooseTxtV.setText("เธขเธเนเธฅเธดเธเนเธฅเธทเธญเธ");
((AddorRemoveCallbacks)mContext).onAddProduct();
}
}
});
}
}else
{
mFoodList.get(position).setAddedTocart(false);
holder.foodChooseTxtV.setText("เนเธฅเธทเธญเธ");
((AddorRemoveCallbacks)mContext).onRemoveProduct();
removeFoodCart(food.getFoodId());
}
}
});
holder.layout.setOnClickListener(new View.OnClickListener() {
@SuppressLint("ResourceType")
@Override
public void onClick(View v) {
}
});
}
private void goToUpdateActivity(long foodId,String name,String detail,String img ,double price ,double stamp){
Intent goToUpdate = new Intent(mContext, FoodDetail.class);
goToUpdate.putExtra("ID", foodId);
goToUpdate.putExtra("name", name);
goToUpdate.putExtra("detail", detail);
goToUpdate.putExtra("img", img);
goToUpdate.putExtra("price", price);
goToUpdate.putExtra("stamp", stamp);
mContext.startActivity(goToUpdate);
}
private void removeFoodCart(long foodId){
ipConfig ip1 = new ipConfig();
final String baseUrl1 = ip1.getBaseUrlCart() ;
SharedPreferences sharedpreferences;
final String MyPREFERENCES = "MyPrefs" ;
final String User_id = "userKey";
sharedpreferences = this.mContext.getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
final String user_id1 = sharedpreferences.getString(User_id, "");
Ion.with(mContext)
.load(baseUrl1+"removeToCart.php")
.setMultipartParameter("user_id",user_id1)
.setMultipartParameter("food_id", String.valueOf(foodId))
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
@Override
public void onCompleted(Exception e, JsonObject result) {
}
});
}
@Override
public int getItemCount() {
return mFoodList.size();
}
}
|
Java
|
UTF-8
| 2,328
| 2.375
| 2
|
[] |
no_license
|
package com.redis.service;
import com.redis.model.Programmer;
import com.redis.repository.ProgrammerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Service
public class ProgrammerServiceImpl implements ProgrammerService {
private final ProgrammerRepository programmerRepository;
@Autowired
public ProgrammerServiceImpl(ProgrammerRepository programmerRepository) {
this.programmerRepository = programmerRepository;
}
@Override
public void setProgrammerAsString(String idKey, String programmer) {
programmerRepository.setProgrammerAsString(idKey, programmer);
}
@Override
public String getProgrammerAsString(String idKey) {
return programmerRepository.getProgrammerAsString(idKey);
}
@Override
public void addProgrammersAsList(Programmer programmer) {
programmerRepository.addProgrammersAsList(programmer);
}
@Override
public List<Programmer> getProgrammersListMembers() {
return programmerRepository.getProgrammersListMembers();
}
@Override
public Long getProgrammersListCount() {
return programmerRepository.getProgrammersListCount();
}
@Override
public void addProgrammersAsSet(Programmer... programmer) {
programmerRepository.addProgrammersAsSet(programmer);
}
@Override
public Set<Programmer> getProgrammersSetMembers() {
return programmerRepository.getProgrammersSetMembers();
}
@Override
public boolean isSetMember(Programmer programmer) {
return programmerRepository.isSetMember(programmer);
}
@Override
public void saveHash(Programmer programmer) {
programmerRepository.saveHash(programmer);
}
@Override
public void updateHash(Programmer programmer) {
programmerRepository.updateHash(programmer);
}
@Override
public Map<Integer, Programmer> findAllHash() {
return programmerRepository.findAllHash();
}
@Override
public Programmer findHash(int id) {
return programmerRepository.findHash(id);
}
@Override
public void deleteHash(int id) {
programmerRepository.deleteHash(id);
}
}
|
JavaScript
|
UTF-8
| 562
| 2.53125
| 3
|
[] |
no_license
|
var url = "week-15";
function updateUrl () {
var text = url;
$("#url").val(text);
var urlInput = $("#url");
}
function getUrl () {
return $("#url").val().trim();
}
$(function () {
$("#url").keyup(function(event){
url = getUrl();
if(url.charAt(0) == "-") url = url.substring(1);
setCookies();
var targetUrl = $('#target').attr("href");
if(targetUrl != null) {
$('#target').attr("href", "https://gits-15.sys.kth.se/INDA15/" + selectedStudent + "-" + url);
}
});
});
|
C++
|
UTF-8
| 1,694
| 3.375
| 3
|
[] |
no_license
|
#include <iostream>
#include <string>
#include <vector>
class Publisher ;
class Subscriber
{
std::vector<Publisher*> subscribed_to ;
public:
void subscribeTo(Publisher*);
virtual void getPublication(const Publisher*) = 0 ;
};
class Person : public Subscriber
{
std::string name ;
public:
Person(const std::string& s) : name(s) {}
void getPublication(const Publisher*);
friend std::ostream& operator<<(std::ostream& stream, const Person& p)
{
stream << p.name ;
return stream ;
}
};
class Publisher
{
std::vector<Subscriber*> subscribers ;
std::string name ;
std::vector<std::string> publications;
void publish() { for(auto& c : subscribers) c->getPublication(this); }
public:
Publisher(const std::string &n) : name(n) {}
void addSubscriber(Subscriber* s) { subscribers.push_back(s); }
std::string getName() const { return name; }
std::string getLatestPublication() const { return publications.back(); }
void addPublication(const std::string& ct) { publications.push_back(ct); publish(); }
};
void Subscriber::subscribeTo(Publisher* p)
{ subscribed_to.push_back(p); p->addSubscriber(this); }
void Person::getPublication(const Publisher* p)
{ std::cout << name << " got publication : " << p->getLatestPublication() << " from " << p->getName() << std::endl; }
int main() {
Publisher p1("mcgrawhill"), p2("pearson");
Person n1("Shaun"), n2("Nick");
n1.subscribeTo(&p1);
n2.subscribeTo(&p1);
n2.subscribeTo(&p2);
p1.addPublication("C++11 Reference");
p2.addPublication("C++14 Reference");
return 0;
}
|
Python
|
UTF-8
| 1,893
| 2.6875
| 3
|
[] |
no_license
|
import cv2
import numpy as np
def set_point_to_displace(height_queue, points_to_displace_queue):
cap = cv2.VideoCapture(0)
while True:
cam_constant = 557
if height_queue.empty():
print("empty queue")
pass
else:
cam_height = height_queue.get()
lower_colour = np.array([20, 45, 80])
upper_colour = np.array([46, 130, 220])
point_to_displace = np.zeros(2)
_, frame = cap.read()
height, width = frame.shape[:2]
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
blur = cv2.GaussianBlur(hsv, (15, 15), 0)
mask = cv2.inRange(blur, lower_colour, upper_colour)
_, contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if len(contours):
filter(lambda a: cv2.contourArea(a) > 500, contours)
c = sorted(contours, key=cv2.contourArea)[::-1]
for contour in c[0:1:]:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.circle(frame, ((2 * x + w) / 2, (2 * y + h) / 2), 2, (0, 0, 255), -1)
cv2.circle(frame, (width / 2, height / 2), 2, (0, 0, 255), -1)
x_displacement_in_pixels = ((2 * x + w) / 2) - (width / 2)
y_displacement_in_pixels = (height / 2) - ((2 * y + h) / 2)
point_to_displace = [(x_displacement_in_pixels * cam_height) / cam_constant,
(y_displacement_in_pixels * cam_height) / cam_constant]
print(points_to_displace_queue)
points_to_displace_queue.put(point_to_displace)
else:
pass
cv2.imshow("frame", frame)
|
Java
|
UTF-8
| 508
| 2.984375
| 3
|
[] |
no_license
|
package seo.dale.practice.java.util.queue;
import org.junit.Test;
import java.util.PriorityQueue;
import java.util.Queue;
public class PriorityQueueTest {
private Queue<String> queue;
@Test
public void test() {
queue = new PriorityQueue<>(3);
queue.add("A");
queue.add("B");
queue.add("C");
queue.add("D");
queue.add("E");
System.out.println("#queue: " + queue);
System.out.println("#queue.size(): " + queue.size());
}
}
|
C++
|
UTF-8
| 1,292
| 3.859375
| 4
|
[] |
no_license
|
#include<iostream>
#include<cstring>
using namespace std;
struct stringy
{
char * str;
int ct;
};
//prototypes for set(), show(), and show() go here
void set(stringy &string, char str[]) // I don't use a pointer here because the string isn't passed as a pointer-to-character.
{
int i = 0;
while(str[i] != '\0')
i++;
string.ct = i;
string.str = new char[i];
strcpy(string.str, str);
}
void show(const stringy &string, int times = 1)
{
for(int i = 0; i < times; i++)
cout << string.str << endl;
}
void show(const char * str, int times = 1)
{
for(int i = 0; i < times; i++)
cout << str << endl;
}
int main()
{
stringy beany;
char testing[] = "Reality is precisely what I want it to be. I've ensured it."; //Because this isn't initialized as a pointer, I can't refer to it as one when I pass it to set()
set(beany, testing); //first argument is a reference,
//allocates space to hold copy of testing,
// str member of beany to point to the new block,
//copies testing to new block, and sets ct member of beany
show(beany); //prints member string once
show(beany, 2); //prints member string twice
testing[0] = 'D';
testing[1] = 'u';
show(testing);
show(testing, 3); //Shows testing string thrice, previous does it just once.
show("Done!");
}
|
Python
|
UTF-8
| 3,494
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
from environments.blackjack import BlackJack
import pandas as pd
import rl_learning as rl
def learn_Q_function(all_observed_decision_states, reward, model):
"""
Episodic learning (mostly for lookup table method) - helper method
"""
if model.model_class == 'lookup_table':
model.fit(all_observed_decision_states, reward)
elif model.model_class == 'scikit' or model.model_class == 'vw' or model.model_class == 'vw_python':
for decision_state in all_observed_decision_states:
X_new, y_new = model.return_design_matrix(decision_state, reward)
model.X.append(X_new)
model.y.append(y_new)
if model.buffer == 1000:
model.fit(model.X, model.y)
# TODO Instead of killing entire buffer we can keep a few and kill only the subset
model.clean_buffer()
return model
def train_reinforcement_learning_strategy(num_sims=1, game_obs='blackjack', model_class='lookup_table'):
"""
Episodic learning (mostly for lookup table method)
"""
start_time = time.time()
# Initialize model
model = Model({'class': model_class, 'base_folder_name': game_obs.base_folder_name})
banditAlgorithm = BanditAlgorithm(params=0.1)
model.initialize()
model.all_possible_decisions = game_obs.action_space
for _ in xrange(num_sims):
model.buffer += 1
# Initialize game
game_obs.reset()
if game_obs.game_status != 'in process':
continue
all_observed_decision_states, reward = game_obs.complete_one_episode(banditAlgorithm, model)
model = learn_Q_function(all_observed_decision_states, reward, model)
model.finish()
elapsed_time = int(time.time() - start_time)
print ": took time:" + str(elapsed_time)
return banditAlgorithm.policy, model
# Test simple monte-carlo learning for blackjack
def test_training_monte_carlo_for_blackjack(model_class, epochs):
blackjack = BlackJack()
policy, model = train_reinforcement_learning_strategy(num_sims=epochs, game_obs=blackjack, model_class=model_class)
df = pd.DataFrame(policy).T
df.columns = ['player_value', 'dealer_value', 'decision', 'score']
policy_Q_table = df.pivot('player_value', 'dealer_value')['decision']
print policy_Q_table
policy_Q_score = df.pivot('player_value', 'dealer_value')['score']
print policy_Q_score
# Add ipython notebook 3D ghaph
# Test policy
rl.test_policy_with_random_play(blackjack, model)
return policy, model
# Test TD for blackjack
def test_training_TD_for_blackjack(model_class, epochs=5000):
blackjack = BlackJack()
policy, model = train_reinforcement_strategy_temporal_difference(epochs=epochs, game_obs=blackjack, model_class=model_class)
df = pd.DataFrame(policy).T
df.columns = ['player_value', 'dealer_value', 'decision', 'score']
policy_Q_table = df.pivot('player_value', 'dealer_value')['decision']
print policy_Q_table
policy_Q_score = df.pivot('player_value', 'dealer_value')['score']
print policy_Q_score
# Add ipython notebook 3D ghaph
# Test policy
rl.test_policy_with_random_play(blackjack)
return policy, model
#policy, model = test_training_monte_carlo_for_blackjack(model_class='lookup_table', epochs=5000)
#policy, model = test_training_monte_carlo_for_blackjack(model_class='vw_python', epochs=5000)
policy, model = test_training_TD_for_blackjack(model_class='vw_python', epochs=10000)
|
PHP
|
UTF-8
| 2,551
| 2.828125
| 3
|
[] |
no_license
|
<?php
namespace RoarProj\controllers\middlewares;
use Silex\Application;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\ConstraintViolationListInterface;
use RoarProj\exceptions\ValidationException;
class RequestValidator
{
const BODY_SCHEMA = 'body';
const PATH_SCHEMA = 'path';
const QUERY_SCHEMA = 'query';
public function __construct($options = [])
{
$this->pathSchema = isset($options[self::PATH_SCHEMA]) ?
$options[self::PATH_SCHEMA] : null;
$this->bodySchema = isset($options[self::BODY_SCHEMA]) ?
$options[self::BODY_SCHEMA] : null;
$this->querySchema = isset($options[self::QUERY_SCHEMA]) ?
$options[self::QUERY_SCHEMA] : null;
}
/**
* @param Request $request
* @param Application $app
* @throws ValidationException
*/
public function __invoke(Request $request, Application $app)
{
$validator = $app['validator'];
//URL Parameters validation
$this->performValidation(
$request->attributes,
$this->pathSchema,
'Invalid URL attributes.',
$validator
);
//Body validation
$this->performValidation(
$request->request,
$this->bodySchema,
'Invalid Request Body.',
$validator
);
//MetricQuery string validation
$this->performValidation(
$request->query,
$this->querySchema,
'Invalid URL query string.',
$validator
);
}
/**
* @param ParameterBag $parameterBag
* @param $schema
* @param $message
* @param $validator
* @throws ValidationException
*/
private function performValidation(
ParameterBag $parameterBag,
$schema,
$message,
$validator
) {
if ($schema !== null) {
$errors = $validator->validate($parameterBag->all(), $schema);
$this->throwIfErrors($errors, $message);
}
}
/**
* @param ConstraintViolationListInterface $errors
* @param $msg
* @throws ValidationException
*/
private function throwIfErrors(
ConstraintViolationListInterface $errors,
$msg
) {
if (count($errors) > 0) {
throw new ValidationException($msg, $errors);
}
}
private $pathSchema;
private $bodySchema;
private $querySchema;
}
|
Markdown
|
UTF-8
| 16,792
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
---
title: 'ํ์ด์ฌ์ ์ด์ฉํ ํด๋ฆฐ ์ฝ๋๋ฅผ ์ํ ํ
์คํธ ์ฃผ๋ ๊ฐ๋ฐ - 3์ฅ ๋จ์ ํ
์คํธ๋ฅผ ์ด์ฉํ ๊ฐ๋จํ ํํ์ด์ง ํ
์คํธ'
date: 2019-12-23 12:00:00
category: 'tdd'
---
## Intro
๋ณธ๊ฒฉ์ ์ธ To-Do ์น ์ํ๋ฆฌ์ผ์ด์
๊ฐ๋ฐ์ ์ํด ๋จ์ ํ
์คํธ๋ฅผ ๋ง๋ค์ด๋ณธ๋ค.
## ์ฒซ Django ์ ํ๋ฆฌ์ผ์ด์
๊ณผ ์ฒซ ๋จ์ ํ
์คํธ(์์ : [03-01](https://github.com/PilhwanKim/books/blob/master/test_driven_development_with_python/ch03/03-01))
- Django ๋ 1๊ฐ ํ๋ก์ ํธ์ n๊ฐ app์ผ๋ก ๊ตฌ์ฑ๋์ด ์๋ค.
- ์ด๊ฒ์ ๋ค๋ฅธ ํ๋ก์ ํธ์์๋ ๋์ผํ ์ฑ์ ์ฌ์ฉ๊ฐ๋ฅํ๋๋ก app ๋จ์๋ก ์ฌ์ฌ์ฉ์ ๊ฐ๋ฅํ๊ฒ ํ๊ธฐ ์ํ ๊ฒ์ด๋ค.
- ์ฑ์ ์ฝ๋๋ฅผ ๊ตฌ์กฐํํ๊ธฐ์ํ ์ข์ ์๋จ์ด๋ค.
### ์์
๋ชฉ๋ก ์ฑ์ ๋ง๋ค์ด ๋ณด์.
```sh
$ python manage.py startapp lists
```
์คํํ๋ฉด superlists/superlists ์ ๋์ผ ์์น์ spuerlists/lists ๋ผ๋ ํด๋๊ฐ ์์ฑ๋๋ค.

## ๋จ์ ํ
์คํธ๋ ๋ฌด์์ด๊ณ , ๊ธฐ๋ฅ ํ
์คํธ์ ์ด๋ค ์ฐจ์ด๊ฐ ์์๊น?
| ์ข
๋ฅ | ๋จ์ ํ
์คํธ | ๊ธฐ๋ฅ ํ
์คํธ |
| --- | :-------: | :-------: |
| ๊ด์ | ํ๋ก๊ทธ๋๋จธ ๊ด์ | ์ฌ์ฉ์ ๊ด์ |
| ๋ชฉํ | ์ ํ๋ฆฌ์ผ์ด์
๋ด๋ถ | ์ ํ๋ฆฌ์ผ์ด์
์ธ๋ถ |
| ๋ ์ด์ด | ํ์ ๋ ๋ฒจ | ์์ ๋ ๋ฒจ |
### ํ
์คํธ ์์
์์
1. ๊ธฐ๋ฅ ํ
์คํธ ์์ฑ : ์ฌ์ฉ์ ๊ด์ ์ ์๋ก์ด ๊ธฐ๋ฅ์ฑ ์ ์
2. ๊ธฐ๋ฅ ํ
์คํธ ์คํจ - ํ์๋จ์ ์ด๋ค ๊ธฐ๋ฅ์ ์์ฑํด์ผ ํต๊ณผํ ์ง ๊ณ ๋ฏผ/์ค๊ณ
2-1. ๋จ์ ํ
์คํธ ์์ฑ : ๊ธฐ๋ฅํ
์คํธ์์์ ๊ณ ๋ฏผ์ ํ
์คํธ๋ก ์์ฑ
2-2. ๋จ์ ํ
์คํธ ์คํจ : ํ
์คํธ๋ฅผ ํต๊ณผํ ์ ๋๋ก ์ต์ํ์ ์ฝ๋ ์์ฑ. ๊ณผ์ 2-1/2-2๋ฅผ ํ๋์ ๊ธฐ๋ฅ ํ
์คํธ ์์ฑ๋ ๋๊น์ง ๋ฐ๋ณต
3. ๊ธฐ๋ฅ ํ
์คํธ ์ฌ์คํํ์ฌ ํต๊ณผํ๋์ง ํ์ธ. ์คํจ์ ๊ณผ์ 2๋ก ๋์๊ฐ์ ๋ค์ ์์ฑ. ํต๊ณผ์ ํ๊ฐ์ง ๊ธฐ๋ฅ ์์ฑ
์ฆ ์์๋จ(๊ธฐ๋ฅํ
์คํธ) ๋ฅผ ๋จผ์ ์์ฑํ์ ๊ทธ ํ์๋จ(๋จ์ ํ
์คํธ)์ ์๊ฒ ์ชผ๊ฒ์ ํ
์คํธ ํจ์ ์์ ์๋ค.
๋ฒ๊ฑฐ๋ก์ ๋ณด์ผ ์ ์์ผ๋, ์ค์ง์ ์ธ ์ค๊ณ์ ์ดํ์ ๊ฒ์ฆํ ์ ์๋ ์๋ํ๋ ํด๊น์ง ๋ง๋ค์ด์ง๊ธฐ ๋๋ฌธ์ ํฉ๋ฆฌ์ ์ธ ํ๋ก์ธ์ค์ธ๊ฑฐ ๊ฐ๋ค.
## Django์์์ ๋จ์ ํ
์คํธ(์์ : [03-02](https://github.com/PilhwanKim/books/blob/master/test_driven_development_with_python/ch03/03-02))
### TDD ์ฃผ๊ธฐ
์ ์คํจ -> ํ
์คํธ๋ฅผ ํต๊ณผํ ์ฝ๋ ์์ฑ -> ํ ํต๊ณผ -> ์ ํ
์คํธ ์ฝ๋ ์์ฑ -> ์ ์คํจ..(๊ณ์ ๋ฐ๋ณต)
### django.test.TestCase ํด๋์ค
Django๋ ๊ธฐ๋ณธ TestCase class๋ฅผ ํ์ฅํ django.test.TestCase ํด๋์ค๋ฅผ ๊ธฐ๋ณธ ๋จ์ ํ
์คํธ๋ก ์ฌ์ฉํ๋๋ก ๊ถํ๊ณ ์๋ค.
django ํ๋ก์ ํธ์ ๋ง๋ ์ฌ๋ฌ ํ์ฅ ๊ธฐ๋ฅ๋ค์ด ์๋ค.
๊ทธ ์ค์ manage.py ์์ test ์ปค๋งจ๋๋ก ์ ์ฒด testcase๋ฅผ ์คํํ๋ ๊ธฐ๋ฅ์ด ํฌํจ๋์ด ์๋ค.
๊ณ ์์ ์ธ ์คํจ ํ
์คํธ๋ฅผ ์์ฑํ์ฌ ์ด๋ฅผ ํ์ธํด ๋ณด์.
[lists/tests.py](https://github.com/PilhwanKim/books/blob/master/test_driven_development_with_python/ch03/03-02/superlists/lists/tests.py)
```sh
$ python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
F
======================================================================
FAIL: test_bad_maths (lists.tests.SmokeTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "workspace/superlists/lists/tests.py", line 7, in test_bad_maths
self.assertEqual(1 + 1, 3)
AssertionError: 2 != 3
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
Destroying test database for alias 'default'...
```
## Django์ MVC, URL, ๋ทฐ ํจ์(์์ : [03-03](https://github.com/PilhwanKim/books/blob/master/test_driven_development_with_python/ch03/03-03))
Django๋ **๋์ฒด๋ก** MVC(Model-View-Cotroller) ํจํด์ ๋ฐ๋ฆ
์ด MVC ํจํด์ ์ฐจ์ฉํ์ฌ Django๋
| MVCํจํด | Django |
| ----------- | :------: |
| Model(Data) | Model |
| View | Template |
| Controller | View |
๋ผ๊ณ ํํํ์ฌ MTV(model-template-view)ํจํด์ด๋ผ๊ณ ๋ช
๋ช
ํจ
### HTTP ์์ฒญ Django ์ ์ฒ๋ฆฌ ํ๋ฆ

์ ๊ธฐ ์ค์ http client - view ์ฌ์ด์์ ์ผ์ด๋๋ ์ผ์ ์ข๋ ์์ธํ ์ค๋ช
ํ๋ฉด ์ด๋ ๋ค.
1. ํน์ URL์ ๋ํ HTTP ์์ฒญ ๋ฐ์
2. ํน์ ๊ท์น์ ์ด์ฉํด์ ํด๋น ์์ฒญ์ ์ด๋ค ๋ทฐ ํจ์๋ฅผ ์คํํ ์ง ๊ฒฐ์
3. ๋ทฐ ๊ธฐ๋ฅ ์์ฒญ์ ์ฒ๋ฆฌํ๊ณ HTTP ์๋ต์ ๋ฐํ
๋ฐ๋ผ์ ์ฐ๋ฆฌ๊ฐ ํ
์คํธ ํ 2๊ฐ์ง
1. URL์ ๋ฃจํธ("/")๋ฅผ ํด์ํด์ ํน์ ๋ทฐ ๊ธฐ๋ฅ์ ๋งค์นญ์ํฌ ์ ์๋๊ฐ?
2. ์ด ๋ทฐ ๊ธฐ๋ฅ์ด ํน์ HTML์ ๋ฐํํ๊ฒ ํด์ ๊ธฐ๋ฅ ํ
์คํธ๋ฅผ ํต๊ณผํ๋๊ฐ?
[์ฒซ ๋ฒ์งธ ํ
์คํธ ์ฝ๋](https://github.com/PilhwanKim/books/blob/master/test_driven_development_with_python/ch03/03-03/superlists/lists/tests.py)
```sh
$ python manage.py test
System check identified no issues (0 silenced).
E
======================================================================
ERROR: lists.tests (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: lists.tests
Traceback (most recent call last):
File "/Users/pilhwankim/.pyenv/versions/3.7.1/lib/python3.7/unittest/loader.py", line 434, in _find_test_path
module = self._get_module_from_name(name)
File "/Users/pilhwankim/.pyenv/versions/3.7.1/lib/python3.7/unittest/loader.py", line 375, in _get_module_from_name
__import__(name)
File "/Users/pilhwankim/Github/books/test_driven_development_with_python/ch03_Testing_a_Simple_Home_Page_with_Unit_Tests/03-03/superlists/lists/tests.py", line 3, in <module>
from lists.views import home_page
ImportError: cannot import name 'home_page' from 'lists.views' (/Users/pilhwankim/Github/books/test_driven_development_with_python/ch03_Testing_a_Simple_Home_Page_with_Unit_Tests/03-03/superlists/lists/views.py)
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
```
์์ํ๋ ๋๋ก ์๋ฌ๊ฐ ๋ฐ์ํ๋ค.
๋๋ต ์๋ฌ์ ๋ด์ฉ์ veiws ์ home_page ๋ผ๋ ์กด์ฌํ์ง ์๋ ๊ฒ์ ์ํฌํธ ํ๋ ค๊ณ ํ๊ธฐ ๋๋ฌธ์ ๋ฐ์ํ๋ค.
์์ธก๋ ์คํจ์ด๊ณ TDD ๊ด์ ์ผ๋ก๋ ๊ฑฐ์ณ๊ฐ์ผ ํ ์ฒซ ๊ณผ์ ์ด๋ค.
## ๋ง์นจ๋ด ์ค์ง์ ์ธ ์ ํ๋ฆฌ์ผ์ด์
์ ์์ฑํ๋ค(์์ : [03-04](https://github.com/PilhwanKim/books/blob/master/test_driven_development_with_python/ch03/03-04))
์คํจ ํ
์คํธ๋ฅผ ํด๊ฒฐํด ๋ณด์. ํ๋ฒ์ ํ๋์ฉ! ์ผ๋จ import ์๋ฌ๋ฅผ ํด๊ฒฐํ๋ค.
[view ๊ตฌํ ์ฝ๋](https://github.com/PilhwanKim/books/blob/master/test_driven_development_with_python/ch03/03-04/superlists/lists/views.py)
๋๋ฌด ๋จ์ํ๊ณ ํ๋ฌดํ ์ฝ๋์ด๊ธฐ ํ๋ฐ, ์ ์์ ์๋๋ ์ด๋ฐ๊ฑฐ ๊ฐ๋ค.
***ํ ๋ฒ์ ํ ๊ฐ์ง์ ๋น๋ฉดํ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํด๋ผ!***
๋ค์๊ณผ ๊ฐ์ด ๊ตฌํํ๊ณ ๋ค์ ํ
์คํธ๋ฅผ ๋๋ ค๋ณด๋ฉด ๋ค๋ฅธ ์๋ฌ๊ฐ ๋ฐ์ํ๋ค.
```sh
python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_root_url_resolves_to_home_page_view (lists.tests.HomePageTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/pilhwankim/Github/books/test_driven_development_with_python/ch03_Testing_a_Simple_Home_Page_with_Unit_Tests/03-04/superlists/lists/tests.py", line 8, in test_root_url_resolves_to_home_page_view
found = resolve('/')
File "/Users/pilhwankim/.pyenv/versions/tdd-with-python-env/lib/python3.7/site-packages/django/urls/base.py", line 24, in resolve
return get_resolver(urlconf).resolve(path)
File "/Users/pilhwankim/.pyenv/versions/tdd-with-python-env/lib/python3.7/site-packages/django/urls/resolvers.py", line 567, in resolve
raise Resolver404({'tried': tried, 'path': new_path})
django.urls.exceptions.Resolver404: {'tried': [[<URLResolver <URLPattern list> (admin:admin) 'admin/'>]], 'path': ''}
----------------------------------------------------------------------
Ran 1 test in 0.004s
FAILED (errors=1)
Destroying test database for alias 'default'...
```
## URL๊ณผ ๋ทฐ ํจ์ ๋งตํ(์์ : [03-05](https://github.com/PilhwanKim/books/blob/master/test_driven_development_with_python/ch03/03-05))
- Django ๋ urls.py ์์ URL๊ณผ view ๋ฅผ ๋งคํํ ์ง ์ ์
- superlists(project root)/superlists/urls.py - ์ ์ฒด ์ฌ์ดํธ ๋์์ผ๋ก ํ๋ ๋ฉ์ธ urls.py
์ฐธ๊ณ ์ฌํญ) 2ํ ๊ธฐ์ค ์ฑ
์ด django 1.7 ๊ธฐ์ค์ด๋ค. ๊ตณ์ด ์์ ๋ฒ์ ์ ์ธ ํ์๋ ์์ผ๋ฏ๋ก ์ต์ ์ 2.2 ๋ฒ์ ์ผ๋ก ์ต๋ํ ์์ ๋ฅผ ๋ฐ๋ผ ์งํํ๋ค.
ํฌ๊ฒ ๋ฐ๋ ๋ด์ฉ์ 3๊ฐ์ง ์ ๋ ์์ฝ๋จ
1. django.conf.urls.url ๋ก ๋งคํํ๋ ๋ด์ฉ์ด django.urls.path ๋ก ํ์ค์ ์ธ ์ค์ ์ด ๋ฐ๋(์ด์ ๊ฒ๋ ์ฌ์ฉ๊ฐ๋ฅํ๋. django ์์๋ path๋ฅผ ๊ธฐ๋ณธ์ผ๋ก ํจ)
2. ๋ฐ๋ผ์ url pattern ์
๋ ฅ์ด ์ ๊ท์ ํํ์์ path convert ๋ฐฉ์์ผ๋ก ๋ฐ๋
3. ๋ฌธ์์ด๋ก view ๊ฒฝ๋ก ์ค์ ๋ฐฉ์ ์ ์ธ. ์ง์ view ๋ฅผ import ํจ
์ฑ
์ ๋ด์ฉ๊ณผ ๋น์ทํ๊ฒ ์๋์ ๊ฐ์ด urls.py ๋ฅผ ๋ณ๊ฒฝํด ์งํํด๋ณด๋ฉด
```py
from django.contrib import admin
from django.urls import path
from lists import views as home_views
urlpatterns = [
# path('admin/', admin.site.urls),
path('', home_views.home_page, name='home'),
]
```
```sh
$ python manage.py test
Creating test database for alias 'default'...
Destroying test database for alias 'default'...
Traceback (most recent call last):
(...์๋ต...)
File "/test_driven_development_with_python/ch03_Testing_a_Simple_Home_Page_with_Unit_Tests/03-05/superlists/superlists/urls.py", line 22, in <module>
path('/', lists.views.home_page, name='home'),
File "~/.pyenv/versions/tdd-with-python-env/lib/python3.7/site-packages/django/urls/conf.py", line 73, in _path
raise TypeError('view must be a callable or a list/tuple in the case of include().')
TypeError: view must be a callable or a list/tuple in the case of include().
```
urls.py ์ view์ url ๋งคํ์ ํ์ผ๋,์์ง lists.views.home_page ๊ฐ None ๊ฐ์ผ๋ก ์์ง ๋ฏธ๊ตฌํ ๋์ด์ ๋ํ๋๋ ์๋ฌ์ด๋ค.
๋ค์ lists/views.py ๋ก ๋์๊ฐ์ ์ค์ view ๋ฅผ ํจ์๋ก ๊ตฌํํด๋ณด์.
[view ๊ตฌํ ์ฝ๋](https://github.com/PilhwanKim/books/blob/master/test_driven_development_with_python/ch03/03-05/superlists/lists/views.py)
ํ
์คํธ๋ฅผ ์คํํด๋ณด๋ฉด
```sh
python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
Destroying test database for alias 'default'...
```
์ฒซ ํ
์คํธ๊ฐ ์ฑ๊ณตํ๋ค! ์ฌ์ดํธ ๋ฃจํธ("/") ์์ฒญ์ django view ๊น์ง ์ฐ๊ฒฐํ๋ ๊ฒ์ด ์ฑ๊ณตํ๋ค๋ ์๋ฏธ์ด๋ค.
## ๋ทฐ๋ฅผ ์ํ ๋จ์ ํ
์คํธ(์์ : [03-06](https://github.com/PilhwanKim/books/blob/master/test_driven_development_with_python/ch03/03-06))
- ์ด์ ์ฌ์ดํธ ๋ฃจํธ ์์ฒญ์ ์ค์ HTML ์๋ต๊ฐ์ ๋ฐํํ๋ ๋ด์ฉ๋ ์ถ๊ฐํด์ผ ํจ
- ์์ ๋ด์ฉ์ ๊ฒ์ฆํ๋ ํ
์คํธ ์ฝ๋ ์ถ๊ฐ๊ฐ ๋จผ์
[tests ๊ตฌํ ์ฝ๋](https://github.com/PilhwanKim/books/blob/master/test_driven_development_with_python/ch03/03-06/superlists/lists/tests.py)
์ถ๊ฐ๋ ํ
์คํธ๋ ์์ฝํ๋ฉด response body ํ
์คํธ๊ฐ
```html
<html>
<title>To-Do lists</title>
</html>
```
๋ด์ฉ์ผ๋ก ์ค๋์ง ๊ฒ์ฆํ๋ ๋ด์ฉ์ด๋ค.
```sh
python manage.py test
======================================================================
ERROR: test_home_page_returns_correct_html (lists.tests.HomePageTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/pilhwankim/Github/books/test_driven_development_with_python/ch03_Testing_a_Simple_Home_Page_with_Unit_Tests/03-06/superlists/lists/tests.py", line 15, in test_home_page_returns_correct_html
response = home_page(request)
TypeError: home_page() takes 0 positional arguments but 1 was given
----------------------------------------------------------------------
Ran 2 tests in 0.001s
FAILED (errors=1)
```
์๋์ ์ผ๋ก ํ
์คํธ๋ฅผ ๋๋ ค๋ณด๋ฉด ์คํจํ๋ค. ์ด์ ๊ตฌํํด์ผ ํ๋ค.
### ๋จ์ ํ
์คํธ-์ฝ๋ ์ฃผ๊ธฐ
1. ํฐ๋ฏธ๋์์ ๋จ์ ํ
์คํธ๋ฅผ ์คํํ์ฌ ์ด๋ป๊ฒ ์คํจํ๋์ง ํ์ธํ๋ค.
2. ํธ์ง๊ธฐ ์์์ ํ์ฌ ์คํจ ํ
์คํธ๋ฅผ ์์ ํ๊ธฐ ์ํ **์ต์ํ์ ์ฝ๋**๋ฅผ ๋ณ๊ฒฝํ๋ค.
์ฝ๋ ํ์ง์ ๋์ด๊ณ ์ ํ๋ค๋ฉด ์ฝ๋ ๋ณ๊ฒฝ์ ์ต์ํ ํ๋ค. ์ฆ ์ด ์ผ์ด์ค์์๋
```sh
home_page() takes 0 positional arguments but 1 was given
```
๋ผ๊ณ ํ๊ธฐ ๋๋ฌธ์ home_page ํจ์์ argument๋ฅผ 1๊ฐ ์ถ๊ฐํ๋ **์ต์ํ์ ์ฝ๋**๋ฅผ ๋ณ๊ฒฝํ๊ณ ๋ค์ ํ
์คํธ ํด์ผํ๋ค.
1. ์ฝ๋ ๋ณ๊ฒฝ(request ์ถ๊ฐ)
```py
def home_page(request):
pass
```
2. ํ
์คํธ
```sh
======================================================================
ERROR: test_home_page_returns_correct_html (lists.tests.HomePageTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/superlists/lists/tests.py", line 16, in test_home_page_returns_correct_html
self.assertTrue(response.content.startswith(b'<html>'))
AttributeError: 'NoneType' object has no attribute 'content'
----------------------------------------------------------------------
```
home_page ์ ๋ฆฌํด๊ฐ ์์ด None ์ผ๋ก ์ค๊ธฐ ๋๋ฌธ์ด๋ค. ๊ทธ๋์ ์ฝ๋ ๋ณ๊ฒฝ์?
3. ์ฝ๋ ๋ณ๊ฒฝ(return ์ django.http.HttpResponse ์ฌ์ฉ)
```py
from django.http import HttpResponse
def home_page(request):
return HttpResponse()
```
4. ํ
์คํธ
```sh
======================================================================
FAIL: test_home_page_returns_correct_html (lists.tests.HomePageTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/superlists/lists/tests.py", line 16, in test_home_page_returns_correct_html
self.assertTrue(response.content.startswith(b'<html>'))
AssertionError: False is not true
----------------------------------------------------------------------
Ran 2 tests in 0.007s
```
๋ฆฌํด๊ฐ ๊ฐ์ฒด๋ ๋ง๊ฒ ์์ผ๋ contents ๊ฐ ์๊ธฐ ๋๋ฌธ์ด๋ค. contents๋ฅผ ์ฑ์ธ ์ฝ๋ ๋ณ๊ฒฝ์?
5. ์ฝ๋ ๋ณ๊ฒฝ(HttpResponse ์ html content ํ
์คํธ ๋ฃ๊ธฐ)
```python
from django.http import HttpResponse
def home_page(request):
return HttpResponse('<html><title>To-Do lists</title></html>')
```
6. ํ
์คํธ
```sh
python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
..
----------------------------------------------------------------------
Ran 2 tests in 0.002s
OK
Destroying test database for alias 'default'...
```
๋๋์ด ํ๋์ ๋จ์ ํ
์คํธ๊ฐ ์๊ฒฐ๋์๋ค!
์ด์ ์ ๊ฐ๋ฐํ์๋ ๊ธฐ๋ฅ ํ
์คํธ(functional_test.py)๋ฅผ ๋ค์ ์คํํด๋ณด์!
```sh
# shell์ 2๊ฐ ๋์ฐ๊ณ ํ์ชฝ์๋ django ์๋ฒ๋ฅผ ๋์
$ python manage.py runserver
# ๋ค๋ฅธ ํ์ชฝ์์ ๊ธฐ๋ฅ ํ
์คํธ ์คํ
$ python functional_test.py
F
======================================================================
FAIL: test_can_start_a_list_and_retrieve_it_later (__main__.NewVisitorTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "functional_test.py", line 21, in test_can_start_a_list_and_retrieve_it_later
self.fail('Finish the test!')
AssertionError: Finish the test!
----------------------------------------------------------------------
Ran 1 test in 2.256s
FAILED (failures=1)
```
unittest ๊ฒฐ๊ณผ๋ ์คํจ๋ก ๋์ค์ง๋ง self.fail()๊ฐ ์คํ๋์ด asserionError ๊ฐ ๋ ๊ฒ์ด๋ฏ๋ก ์ด์ test ๋ ํต๊ณผํ ๊ฒ์ด๋ค.
์ฒซ๋ฒ์งธ ๊ธฐ๋ฅ ํ
์คํธ๋ ์ฑ๊ณต์ด๋ค!
## ๋๋์
์ด ์ฅ์์ ์ ์๊ฐ ๋
์๋ค์ด ๊นจ๋ซ๊ธฐ ์ํ๋ ํต์ฌ์ ์ธ ๋ด์ฉ์ **๋จ์ ํ
์คํธ-์ฝ๋ ์ฃผ๊ธฐ** ์ **์ต์ํ์ ์ฝ๋ ๋ณ๊ฒฝ** ์ด ์๋๊ฐ ์ถ๋ค.
์ฌ์ค ๊ธฐ๋ฅ์ด๋ ์ฝ๋ ์์ผ๋ก ๋ฐ์ง๋ฉด ๋๊ฒ ์ ์ ์์ธ๋ฐ ์ ๋ ๊ฒ ๊น์ง ์์ฃผ ํ
์คํธ ํด์ผํ๋? ๋ผ๋ ์๊ฐ๋ ๋ ๋ค.
ํ์ง๋ง ์ฌ๊ธฐ์ ์ด๋ ๊ฒ ์ธ๋ฐํ ์คํ
์ ์ธ๊ธํ๋ ์ด์ ๋ ์๋ง๋ TDD๊ฐ ์ด๋ค ๊ฒ์ธ์ง ์ค์ ๊ฒฝํํด ๋ณด๊ธฐ ์ํจ์ด๋ผ๋ ์๊ฐ์ด ๋ ๋ค.
ํ๋ฒ์ ํ ๊ฐ์ง์ฉ! ํ๋ฒ์ ์์ฃผ ์์ ์คํ
์ ๋ฐ์๋๊ฐ๊ธฐ! ์ค์ TDD๋ฅผ ๊ฐ๋ฐํ๋ ๋ฐฉ๋ฒ์ด ์ด๋ ๋ค๋๊ฑธ ์ ๊นจ๋ซ๊ฒ ๋ ๊ณ๊ธฐ๊ฐ ๋ ๊ฒ ๊ฐ๋ค.
|
C
|
UTF-8
| 1,575
| 3.84375
| 4
|
[] |
no_license
|
#include<stdio.h>
#include<stdlib.h>
struct Stack {
int size;
int top ;
int *Starr ;
};
struct Queue{
struct Stack s1 ;
struct Stack s2 ; };
struct Stack* create (int size){
// struct Stack* st ;
struct Stack* st=(struct Stack*)malloc(sizeof(struct Stack));
st->top=-1 ;
st->size=size ;
st->Starr=(int*)malloc(sizeof(int)*size);
return st ;
}
int isEmpty(struct Stack* st){
if(st->top==-1){
return 1 ;
}
return 0 ;
}
struct Stack* push(int x , struct Stack* st){
if(st->top==st->size-1){
printf("Stack Overflow \n");
return ;
}
st->top++ ;
st->Starr[st->top]=x ;
// printf("Pushed : %d " , st->Starr[st->top]);
return st ;
}
void Display(struct Stack* st){
int i= 0 ;
for(i=0;i<st->size ; i++){
printf(" %d " , st->Starr[i]);
}
}
int Pop(struct Stack* st){
int x =st->Starr[st->top];
st->Starr[st->top]=0 ;
st->top-- ;
//printf("\n Popped number is %d \n " , x);
return x ;
}
void Peek(struct Stack* st){
printf("\n Peek: %d" , st->Starr[st->top]);
}
void enqueue(struct Stack* st1 ,struct Stack* st2 , int x){
// printf("%d" , x);
push(x,st1);
}
void dequeue(struct Stack* st1 ,struct Stack* st2 ){
int x;
while(!isEmpty(st1)){
x=Pop(st1);
push(x,st2);
}
printf("Dequeued element : %d" , Pop(st2));
}
int main(){
struct Stack* st2 ;
st2=create(5);
struct Stack* st1 ;
st1=create(5);
enqueue(st1 , st2 , 5);
enqueue(st1 , st2 , 4);
enqueue(st1 , st2 , 3);
dequeue(st1 , st2);
}
|
PHP
|
UTF-8
| 1,268
| 2.9375
| 3
|
[] |
no_license
|
<?php
function convert_to_impGallon($value, $from_unit) {
switch($from_unit) {
case 'bucket':
return $value * 4;
break;
case 'butt':
return $value * 108;
break;
case 'firkin':
return $value * 9;
break;
case 'hogshead':
return $value * 54;
break;
case 'pint':
return $value * 0.125;
break;
case 'impGallons':
return $value;
break;
default:
return "Unsupported unit.";
}
}
function convert_from_impGallon($value, $to_unit) {
switch($to_unit) {
case 'bucket':
return $value / 4;
break;
case 'butt':
return $value / 108;
break;
case 'firkin':
return $value / 9;
break;
case 'hogshead':
return $value / 54;
break;
case 'pint':
return $value / 0.125;
break;
case 'impGallons':
return $value;
default:
return "Unsupported unit.";
}
}
function convert_liquid($value, $from_unit, $to_unit) {
$impGallon_value = convert_to_impGallon($value, $from_unit);
$new_value = convert_from_impGallon($impGallon_value, $to_unit);
return $new_value;
}
?>
|
Java
|
UTF-8
| 813
| 3.203125
| 3
|
[] |
no_license
|
import java.io.PrintWriter;
import java.net.*;
import java.util.concurrent.*;
import java.util.*;
public class HelperClient extends Thread {
Socket sock;
PrintWriter out;
Scanner in;
int id;
public HelperClient (int id, Socket s ) {
this.id = id;
sock = s ;
}
public void run () {
try {
if ( sock.isConnected() ) {
System.out.println ( "client number " + id + " connected and started") ;
}
out = new PrintWriter ( sock.getOutputStream() ) ;
out.print( "whatever");
out.flush(); // dont forget this tiny little statement
// in = new Scanner ( sock.getInputStream() ) ;
// String mssg = in.nextLine() ;
// System.out.println( "message recieved from server : " + mssg );
}
catch ( Exception e ) {
}
}
}
|
Swift
|
UTF-8
| 2,709
| 3.15625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// DBPractice
//
// Created by ๊น๋ค์ on 2020/07/22.
// Copyright ยฉ 2020 ๊น๋ค์ . All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBAction func getData(_ sender: Any) {
self.textFieldTitle.text = UserDefaults.standard.object(forKey: "title") as? String
self.textFieldContents.text = UserDefaults.standard.object(forKey: "contents") as? String
self.textFieldTitle.isEnabled = false
self.textFieldContents.isEnabled = false
self.saveButton.isEnabled = false
}
@IBAction func insertData(_ sender: Any) {
self.textFieldTitle.text = ""
self.textFieldContents.text = ""
self.textFieldTitle.isEnabled = true
self.textFieldContents.isEnabled = true
self.saveButton.isEnabled = true
self.textFieldTitle.placeholder = "์ ๋ชฉ"
self.textFieldContents.placeholder = "๋ด์ฉ"
}
@IBAction func saveData(_ sender: Any) {
UserDefaults.standard.set(self.textFieldTitle.text, forKey: "title")
UserDefaults.standard.set(textFieldContents.text, forKey: "contents")
self.showToast(message: "์ ์ฅ๋์์ต๋๋ค.")
}
@IBOutlet weak var textFieldTitle: UITextField!
@IBOutlet weak var textFieldContents: UITextField!
@IBOutlet weak var saveButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.textFieldTitle.isEnabled = false
self.textFieldContents.isEnabled = false
self.saveButton.isEnabled = false
}
func showToast(message : String) {
let width_variable:CGFloat = 10
let toastLabel = UILabel(frame: CGRect(x: width_variable, y: self.view.frame.size.height-300, width: view.frame.size.width-2*width_variable, height: 35))
// ๋ทฐ๊ฐ ์์นํ ์์น๋ฅผ ์ง์ ํด์ค๋ค. ์ฌ๊ธฐ์๋ ์๋๋ก๋ถํฐ 100๋งํผ ๋จ์ด์ ธ์๊ณ , ๋๋น๋ ์์ชฝ์ 10๋งํผ ์ฌ๋ฐฑ์ ๊ฐ์ง๋ฉฐ, ๋์ด๋ 35๋ก
toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
toastLabel.textColor = UIColor.white
toastLabel.textAlignment = .center;
toastLabel.font = UIFont(name: "Montserrat-Light", size: 12.0)
toastLabel.text = message
toastLabel.alpha = 1.0
toastLabel.layer.cornerRadius = 10;
toastLabel.clipsToBounds = true
self.view.addSubview(toastLabel)
UIView.animate(withDuration: 4.0, delay: 0.1, options: .curveEaseOut, animations: {
toastLabel.alpha = 0.0
}, completion: {(isCompleted) in
toastLabel.removeFromSuperview()
})
}
}
|
Java
|
UTF-8
| 5,769
| 2.53125
| 3
|
[] |
no_license
|
package edu.school.api;
import edu.school.entities.Action;
import edu.school.entities.ActionTarget;
import edu.school.entities.Activity;
import edu.school.entities.ActivityTarget;
import edu.school.entities.ActivityType;
import edu.school.entities.Group;
import edu.school.entities.GroupMember;
import edu.school.entities.Process;
import edu.school.entities.ProcessAdmin;
import edu.school.entities.Request;
import edu.school.entities.RequestAction;
import edu.school.entities.RequestData;
import edu.school.entities.RequestStakeholder;
import edu.school.entities.State;
import edu.school.entities.Target;
import edu.school.entities.Transition;
import edu.school.entities.TransitionAction;
import edu.school.entities.User;
import java.util.Date;
public interface ControllerIntf {
/**
* Crea un objeto de tipo User y lo hace persistente en la BD
* @param firstName
* @param lastName
* @param birthdayDate
* @return
*/
public User createUser(String firstName, String lastName, Date birthdayDate);
/**
* Crea un objeto de tipo Process y lo hace persistente en la BD
* @param name
* @return
*/
public Process createProcess(String name);
/**
* Crea un objeto de tipo Request y lo hace persistente en la BD
* @param title
* @param dateRequested
* @param process
* @param currentState
* @param userId
* @return
*/
public Request createRequest(String title, Date dateRequested,
Process process, State currentState, User userId);
/**
* Asigna un Process a un User, creando un objeto ProcessAdmin
* y lo hace persistente en la BD
* @param process
* @param user
* @return
*/
public ProcessAdmin assignAdmin(Process process, User user);
/**
* Crea un objeto de tipo State y lo hace persistente en la BD
* @param stateType
* @param process
* @param name
* @param description
* @return
*/
public State createState(String stateType, Process process,
String name, String description);
/**
* Crea el objeto con la data correspondiente a un requerimiento
* @param requestId
* @param name
* @param value
* @return
*/
public RequestData createRequestData(String name, String value,
Request requestId);
/**
* Asigna un interesado (stakeholder) en conocer sobre el requerimiento
* @param requestId
* @param stakeholder
* @return
*/
public RequestStakeholder createRequestStackeholder(Request requestId,
User stakeholder);
/**
* Crea un objeto Transition cuando un Process cambia de un State (actual)
* a un nuevo State (siguiente)
* @param processId
* @param currentStateId
* @param nextStateId
* @return
*/
public Transition createTransition(Process processId, State currentStateId,
State nextStateId);
/**
* Crea un objeto Action y lo hace persistente en la base de datos.
* @param actionType
* @param processId
* @param name
* @param description
* @return
*/
public Action createAction(String actionType, Process processId, String name,
String description);
/**
* Crea un objeto TransitionAction y lo hace persistente en la base de datos
* @param transitionId
* @param actionId
* @return
*/
public TransitionAction createTransitionAction(Transition transitionId,
Action actionId);
/**
* Crea un objeto ActivityType y lo hace persistente en la base de datos
* @param name
* @return
*/
public ActivityType createActivityType(String name);
/**
* Crea un objeto Activity y lo hace persistente en la base de datos
* @param activityTypeId
* @param processId
* @param name
* @param description
* @return
*/
public Activity createActivity(ActivityType activityTypeId, Process processId,
String name, String description);
/**
* Crea un objeto Group y lo hace persistente en la base de datos
* @param processId
* @param name
* @return
*/
public Group createGroup(Process processId, String name);
/**
* Crea un objeto GroupMember y lo hace persistente en la base de datos
* @param groupId
* @param userId
* @return
*/
public GroupMember createGroupMember(Group groupId, User userId);
/**
* Crea un objeto Target y lo hace persistente en la base de datos
* @param name
* @param description
* @return
*/
public Target createTarget(String name, String description);
/**
* Crea un objeto ActionTarget y lo hace persistente en la base de datos
* @param actionId
* @param targetId
* @param groupId
* @return
*/
public ActionTarget createActionTarget(Action actionId, Target targetId,
Group groupId);
/**
* Crea un objeto ActivityTarget y lo hace persistente en la base de datos
*
* @param actionId
* @param targetId
* @param groupId
* @return
*/
public ActivityTarget createActionTarget(Activity activityId, Target targetId,
Group groupId);
/**
* Crea un objeto RequestAction y lo hace persistente en la base de datos
*
* @param requestId
* @param actionId
* @param transitionId
* @param isActive
* @param isComplete
* @return
*/
public RequestAction createRequestAction(Request requestId, Action actionId,
Transition transitionId, int isActive, int isComplete);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.