language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 2,181 | 2.15625 | 2 |
[] |
no_license
|
package com.sudoajay.whatsappstatus.BottomFragments.Local;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
import com.sudoajay.whatsappstatus.MainActivity;
import com.sudoajay.whatsappstatus.R;
/**
* A simple {@link Fragment} subclass.
*/
public class LocalFragment extends Fragment {
private MainActivity main_Activity;
private View view;
private TabLayout tabLayout;
private ViewPager viewPager;
public LocalFragment() {
// Required empty public constructor
}
public LocalFragment createInstance(MainActivity main_Activity) {
this.main_Activity = main_Activity;
return this;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_local, container, false);
Reference();
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final MyAdapter adapter = new MyAdapter(main_Activity.getApplicationContext()
, getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return view;
}
private void Reference() {
tabLayout = view.findViewById(R.id.localTab);
viewPager = view.findViewById(R.id.viewPager_Local);
}
}
|
Markdown
|
UTF-8
| 2,081 | 4.21875 | 4 |
[] |
no_license
|
### 5.5.2 使用cin.get(char)进行补救
通常,逐个字符读取输入的程序需要检查每个字符,包括空格、制表符和换行符。cin所属的istream类(在iostream中定义)中包含一个能够满足这种要求的成员函数。具体地说,成员函数cin.get(ch)读取输入中的下一个字符(即使它是空格),并将其赋给变量ch。使用这个函数调用替换cin>>ch,可以修补程序清单5.16的问题。程序清单5.17列出了修改后的代码。
程序清单5.17 textin2.cpp
```css
// textin2.cpp -- using cin.get(char)
#include <iostream>
int main()
{
using namespace std;
char ch;
int count = 0;
cout << "Enter characters; enter # to quit:\n";
cin.get(ch); // use the cin.get(ch) function
while (ch != ‘#’)
{
cout << ch;
++count;
cin.get(ch); // use it again
}
cout << endl << count << " characters read\n";
return 0;
}
```
下面是该程序的运行情况:
```css
Enter characters; enter # to quit:
Did you use a #2 pencil?
Did you use a
14 characters read
```
现在,该程序回显了每个字符,并将全部字符计算在内,其中包括空格。输入仍被缓冲,因此输入的字符个数仍可能比最终到达程序的要多。
如果熟悉C语言,可能以为这个程序存在严重的错误!cin.get(ch)调用将一个值放在ch变量中,这意味着将修改该变量的值。在C语言中,要修改变量的值,必须将变量的地址传递给函数。但程序清单5.17调用cin.get()时,传递的是ch,而不是&ch。在C语言中,这样的代码无效,但在C++中有效,只要函数将参数声明为引用即可。引用是C++在C语言的基础上新增的一种类型。头文件iostream将cin.get(ch)的参数声明为引用类型,因此该函数可以修改其参数的值。我们将在第8章中详细介绍。同时,C语言行家可以松一口气了——通常,在C++中传递的参数的工作方式与在C语言中相同。然而,cin.get(ch)不是这样。
|
Java
|
UTF-8
| 791 | 3.53125 | 4 |
[] |
no_license
|
package unit13;
import java.util.Arrays;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import static java.lang.System.*;
public class NumberSort
{
//instance variables and other methods not shown
private static int getNumDigits(int number)
{
int count = 0;
int keeper = number;
while (keeper > 0){
keeper = keeper/10;
count += 1;
}
return count;
}
@SuppressWarnings("null")
public static int[] getSortedDigitArray(int number)
{
int[] sorted = new int[getNumDigits(number)];
int digit = 0;
int keeper = number;
for (int i = 0; i < getNumDigits(number); i++){
digit = keeper%10;
sorted[i] = digit;
keeper = keeper/10;
}
Arrays.sort(sorted);
return sorted;
}
}
|
Python
|
UTF-8
| 8,726 | 4.03125 | 4 |
[] |
no_license
|
import pygame #Import pygame
import time
import random
pygame.init() #After importing we need to initiate pygame.
display_width = 900 #Setting up the total display weidth and height of the game display.
display_height = 650
#Defining the colors.
black = (0, 0, 0) #Black means absence of any color and white means all colos
white = (255, 255, 255) #Colors are written here in (R,G,B) format. ie. (Red,Green,Blue) Maximum 256 choices starting from 0
red = (255, 0, 0) #Maximum 256 choices starting from 0.
green = (0, 255, 0)
blue = (0, 0, 255)
block_color = (25, 100, 130) #Defining the color of the block
car_width = 74 #Defining the height and with of our object of the game.
car_height = 82 # Object means the image we will import..
game_display = pygame.display.set_mode((display_width, display_height)) #Setting up the display enviournment.
pygame.display.set_caption("CAR CRASH 2D") #Giving a name to the enviournment.
clock = pygame.time.Clock() #Defining the clock of the game.
car_image = pygame.image.load('car_paint_transparent.png') #Importing the image and assigning it to a variable called car_image.
def dodged_things(count) : #Here we want to enter a counter that says how many blocks we have dodged.
font= pygame.font.SysFont(None,25)
text= font.render(("Dodged: " + str(count)),True, black)
game_display.blit(text,(0,0))
def things(thingx,thingy,thingw,thingh,color): #Defining things as those will come up and we have to go away from it.
pygame.draw.rect(game_display,block_color,[thingx,thingy,thingw,thingh]) #Drawing rectangles.
def car(x, y): #Defing a function for the image i.e. the car at coordinates (x,y).
game_display.blit(car_image, (int(x), int(y)))
def text_objects(text,font): #We want to show some text if something happens in the game.
text_surface = font.render(text, True, black) #Thus we define a function text_objects() which takes the text and font as inputs
return text_surface, text_surface.get_rect() #and returns the text confined in a rectangle->get_rect()
def message_display(text): #Defining a function for displaying the message.
largeText= pygame.font.Font('freesansbold.ttf', 80) #Stating the font and size of the text.
text_surface, text_rectangle = text_objects(text, largeText)
text_rectangle.center = (int((display_width/2)), int((display_height/2))) #Stating where the text will be. Here at the middle of the screen of the game.
game_display.blit(text_surface, text_rectangle) #This is the code for text to generate. Without this thext would not generate.
pygame.display.update() #This is the code for the text to pop up at the front after generating.
time.sleep(2) #Stating the time (i.e. 2 sec) after which the text will pop up.
game_loop() #After the text is shown, the game will restart.
def crash(): #Defining a function called crash which will actually show the text.
message_display("You Crashed") #This is the message we want to display.
def game_loop(): #Here the main code for the game starts.
x = (display_width * 0.45) # Initializing the position of the object.
y = (display_height * 0.75)
x_change = 0 #Initializing the change in position as 0 initially.
thing_startx= random.randrange(0,display_width)
thing_starty= -600
thing_speed= 7
thing_width= 50
thing_height= 50
dodged=0
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT: #This is the code for if we click on the cross button on the game screen,
pygame.quit() #the game will close. Otherwise the game will close automatically.
quit()
if event.type == pygame.KEYDOWN: #From here we defined if we press right-aroow/left-arrow/up/down keys
if event.key == pygame.K_LEFT: #The x_change and the y_change variables
x_change = -7 #will be upgraded as we wish.
if event.key == pygame.K_RIGHT:
x_change = +7
if event.type == pygame.KEYUP: #Codes here states that if we don't press the keys
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: #or stop pressing the keys,
x_change = 0 #the object will stop moving,#That means x_change will be 0.
x += x_change #Upgrading the coordinates of the object by x_change and y_change
game_display.fill(white) #Game display is stated as white
things(thing_startx,thing_starty,thing_width,thing_height,block_color)
thing_starty += thing_speed #This means the initial y coordinate of the block is equal to its initial speed.
car(x, y)
dodged_things(dodged)
if x > display_width - car_width or x < 0: #Here we state a boundary for the car i.e the edges of the game display.
crash() # We further state that if the car goes to the boundary,the message is poped up i.e "You Crushed".
if thing_starty > display_height:
thing_starty=0-thing_height
thing_startx= random.randrange(0,display_width) #This generates the blocks randomly.
dodged += 1 #This increases the number of counts of the dodged blocks.
thing_speed += 1 #This increases the speed of the block over time.
if y< thing_starty+thing_height: #Code for the conditions of the car to crash.
if x> thing_startx and x< thing_startx + thing_width or x+car_width>thing_startx and x+car_width< thing_startx+thing_width:
crash()
pygame.display.update() #This is again to update the display. Otherwise we would not see anything.
clock.tick(100) #This is to specify how fast I want to change the dispaly frame.
#Here it is 100 frames/sec.
game_loop() #This code actually runs the game. The prev one was just defining it. :)
pygame.quit() #To quit pygame.
quit() #To quit python.
|
Java
|
UTF-8
| 3,898 | 3.1875 | 3 |
[] |
no_license
|
package pl.edu.knbit.bitjava;
import pl.edu.knbit.bitjava.model.Course;
import pl.edu.knbit.bitjava.model.Student;
import pl.edu.knbit.bitjava.model.dto.CourseDTO;
import pl.edu.knbit.bitjava.services.CourseService;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Created by surja on 31.10.2020
*/
public class Main {
public static void main(String[] args) {
int[] ints = {1, 2, 3, 66, 1, 41, 2, 4, 14, 4, 6, 12, 6, 88, 4};
CourseService courseService = new CourseService();
// courseService.getCourses().forEach(course -> System.out.println(course));
// courseService.getCourses().forEach(System.out::println);
// Arrays.stream(ints).boxed().forEach(integer -> System.out.println(integer));
//
// Arrays.stream(ints).boxed().filter(integer -> integer > 50).forEach(integer -> System.out.println(integer));
// //COUNT
// long count = Arrays.stream(ints).boxed().filter(integer -> integer > 50).count();
// System.out.println(count);
// //SORTED
// Arrays.stream(ints).boxed().filter(integer -> integer < 50).sorted(Collections.reverseOrder()).forEach(System.out::println);
//
// //ANY_MATCH
// boolean b = Arrays.stream(ints).boxed().anyMatch(integer -> integer == 1);
// System.out.println(b);
// //ALL_MATCH
// boolean b1 = Arrays.stream(ints).boxed().allMatch(integer -> integer == 1);
// System.out.println(b1);
// //takeWhile, dropWhile, distinct
// Arrays.stream(ints).boxed().takeWhile(integer -> integer < 50).forEach(System.out::println);
// Arrays.stream(ints).boxed().distinct().forEach(System.out::println);
// Arrays.stream(ints).boxed().dropWhile(integer -> integer<50).forEach(System.out::println);
// Arrays.stream(ints).boxed().skip(2).forEach(System.out::println);
// int sum = Arrays.stream(ints).boxed().skip(2).mapToInt(Integer::intValue).sum();
// System.out.println(sum);
// Stream<Course> courseStream = courseService.getCourses().stream();
//
// //COLLECT
// List<CourseDTO> collect = courseStream.map(CourseDTO::fromCourse).collect(Collectors.toList());
//
// //flatMap-ile mamy wszystkich studentow
// int sum = courseStream.map(course -> course.getStudents().size()).mapToInt(Integer::intValue).sum();//???? czy to dziala?
// System.out.println(sum);
//
// //FLAT_MAP
// //Stream<Course> -> Stream<List<Student>>
// //Stream<Course> -> Stream<Student>
// //flatMap [[1,2],[4,5]] -> [1,2,4,5]
// long count = courseStream.flatMap(course -> course.getStudents().stream()).distinct().count();
// System.out.println(count);
//
// List<Student> studentList = courseStream.flatMap(course -> course.getStudents().stream()).distinct().collect(Collectors.toList());
//
// //suma wieku wszystkich studentow REDUCE
// int i = courseStream.flatMap(course -> course.getStudents().stream()).distinct().map(student -> student.age).mapToInt(Integer::intValue).sum();
// System.out.println(i);
//
// int i = courseStream.flatMap(course -> course.getStudents().stream()).distinct().reduce(0, (i1, i2) -> i1 + i2.age, (a ,b) -> a+b);
// System.out.println(i);
//
// //groupBy
// Map<Integer, List<Student>> collect = courseStream.flatMap(course -> course.getStudents().stream()).collect(Collectors.groupingBy(student -> student.age));
// collect.get(21).forEach(System.out::println);
//
// Map<String, Double> collect = courseStream.collect(Collectors.groupingBy(course -> course.name, Collectors.averagingDouble(c -> c.students.size())));
// collect.forEach((s, aDouble) -> System.out.println(aDouble));
}
}
|
C++
|
UTF-8
| 974 | 3 | 3 |
[] |
no_license
|
#include "gameState.h"
#include <iostream>
void GameState::init()
{
zombies[0].init("Sally", "Librarian");
zombies[1].init("Milly", "Butcher");
zombies[2].init("Sam", "Tailor");
zombies[3].init("Spot", "T-Rex");
zombies[4].init("Fred", "Giant Spider");
}
void GameState::start()
{
printf("The contestants are:\n");
drawStatus();
printf("\nLet the battle Begin! Who will emerge victorious!\n");
}
void GameState::drawStatus() const
{
for (int i = 0; i < Z_count; ++i)
zombies[i].draw(false);
}
void GameState::drawRound() const
{
printf("\nCombat Round: \n");
for (int i = 0; i < Z_count; ++i)
zombies[i].draw(false);
}
void GameState::update()
{
for (int i = 0; i < Z_count; ++i)
if (zombies[i].isAlive())
zombies[rand() % Z_count].takeDamage(zombies[i].rollAttack());
}
bool GameState::isGameOver() const
{
int livingZombies = 0;
for (int i = 0; i < Z_count; ++i)
if (zombies[i].isAlive())
livingZombies++;
return livingZombies == 1;
}
|
Java
|
UTF-8
| 369 | 2.171875 | 2 |
[] |
no_license
|
package com.Game;
import com.Audio.Audio;
import com.FileIO.FileIO;
import com.Graphic.Graphic;
import com.KeyEvent.Input;
public interface Game {
public Input getInput();
public FileIO getFileIO();
public Graphic getGraphics();
public Audio getAudio();
public void setScreen(Screen screen);
public Screen getCurrentScreen();
public Screen getStartScreen();
}
|
Python
|
UTF-8
| 364 | 3.0625 | 3 |
[
"Apache-2.0"
] |
permissive
|
# v['a'] = 1.0
# b = b - (b*v)*v >>> setitem(v, 'a', 1.0)
# print(b) >>> b = add(b, neg(scalar_mul(v, dot(b,v))))
class Vec:
# Operator overloading
def __init__(self, labels, function):
self.D = labels
self.f = function
def add(u, v):
'''Returns the sum of the two vectors'''
assert u.D == v.D
pass
|
Java
|
UTF-8
| 2,077 | 3.515625 | 4 |
[] |
no_license
|
package _07_If_IfElse;
import java.util.Scanner;
public class Advance_1_Alisveris {
public static void main(String[] args) {
/*
* SORU 4
*
* Kullanicidan aldigi urunun adedini ve liste fiyatini alin,
* kullaniciya musteri karti olup olmadigini sorun
*
* Musteri karti varsa 10 urunden fazla alirsa %20, yoksa %15 indirim yapin
* Musteri karti yoksa 10 urunden fazla alirsa %15, yoksa %10 indirim yapin
*
*/
Scanner scan = new Scanner(System.in);
System.out.println("Urun miktarini giriniz");
int miktar = scan.nextInt();
System.out.println("Urun liste fiyatini giriniz");
double price = scan.nextDouble();
System.out.println("Musteri kartiniz var mi 1:Evet 2:Hayir");
int kart=scan.nextInt();
//1.yol
/*
if(kart==1 && miktar>10) {
System.out.println("%20 Indirimli toplam fiyat = " + miktar*price*.80 );
} else if (kart==1 && miktar<10) {
System.out.println("%15 Indirimli toplam fiyat = " + miktar*price*.85 );
} else if (kart==2 && miktar>10) {
System.out.println("%15 Indirimli toplam fiyat = " + miktar*price*.85 );
} else if (kart==2 && miktar<10) {
System.out.println("%15 Indirimli toplam fiyat = " + miktar*price*.90 );
} else System.out.println("Lutfen size soylenen seceneklerden birini giriniz");
*/
// 2.yol
if(kart==1) {
if(miktar>10) {
System.out.println("%20 Indirimli toplam fiyat = " + miktar*price*.80 );
} else {
System.out.println("%15 Indirimli toplam fiyat = " + miktar*price*.85 );
}
} else if(kart==2) {
if(miktar>10 ) {
System.out.println("%15 Indirimli toplam fiyat = " + miktar*price*.85 );
}else {
System.out.println("%15 Indirimli toplam fiyat = " + miktar*price*.90 );
}
} else System.out.println("Lutfen size soylenen seceneklerden birini giriniz");
scan.close();
}
}
|
SQL
|
UTF-8
| 545 | 3.34375 | 3 |
[] |
no_license
|
CREATE DATABASE chat;
USE chat;
DROP TABLE IF EXISTS users;
CREATE TABLE users (
user_id INT AUTO_INCREMENT,
user_name VARCHAR(25),
PRIMARY KEY (user_id)
);
DROP TABLE IF EXISTS messages;
CREATE TABLE messages (
id INT AUTO_INCREMENT,
text VARCHAR(300),
user_id INT NOT NULL,
room_name varchar(25) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES users (user_id)
);
/* Execute this file from the command line by typing:
* mysql -u root < server/schema.sql
* to create the database and the tables.*/
|
Java
|
UTF-8
| 1,471 | 2.21875 | 2 |
[] |
no_license
|
package model;
public class Penjualanmodel {
private int id;
private String nama;
private String status;
private String alamat;
private String jumlah;
private String tanggal;
public Penjualanmodel( String nama, String status, String alamat, String jumlah, String tanggal) {
this.nama = nama;
this.status = status;
this.alamat = alamat;
this.jumlah = jumlah;
this.tanggal = tanggal;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getAlamat() {
return alamat;
}
public void setAlamat(String alamat) {
this.alamat = alamat;
}
public String getJumlah() {
return jumlah;
}
public void setJumlah(String jumlah) {
this.jumlah = jumlah;
}
public String getTanggal() {
return tanggal;
}
public void setTanggal(String tanggal) {
this.tanggal = tanggal;
}
public String getPangkalan() {
return pangkalan;
}
public void setPangkalan(String pangkalan) {
this.pangkalan = pangkalan;
}
private String pangkalan;
}
|
PHP
|
UTF-8
| 2,129 | 3.21875 | 3 |
[] |
no_license
|
<?php declare(strict_types=1);
namespace Ajthenewguy\Php8ApiServer\Traits;
use Ajthenewguy\Php8ApiServer\Exceptions\SystemInterfaceException;
trait SystemInterface
{
public static int $return_status = 0;
/**
* Execute an external program.
* Capture result to an array and return it.
*
* @param string
* @return array
*/
public static function exec(): array
{
$output = [];
$command = implode(' ', func_get_args());
if (false === exec($command, $output, static::$return_status)) {
throw new SystemInterfaceException(sprintf('%s: failure', $command));
}
return $output;
}
/**
* Execute an external program and display raw output.
* Returns the return status.
*
* @std
*
* @param string
* @return int
*/
public static function passthru(): int
{
$command = implode(' ', func_get_args());
passthru($command, static::$return_status);
return static::$return_status;
}
/**
* Execute command via shell and return the complete output as a string.
* A string containing the output from the executed command
*
* @param string
* @return string|null
*/
public static function shell_exec(): ?string
{
$command = implode(' ', func_get_args());
$return = shell_exec($command);
if ($return === false) {
throw new SystemInterfaceException(sprintf('%s: pipe coule not be established', $command));
}
return $return;
}
/**
* Execute an external program and display the output.
* Returns the last line of the command output on success, and false on failure.
*
* @std
*
* @param string
* @return string
*/
public static function system(): string
{
$command = implode(' ', func_get_args());
if (false === ($return = system($command, static::$return_status))) {
throw new SystemInterfaceException(sprintf('%s: failure', $command));
}
return $return;
}
}
|
Java
|
UTF-8
| 8,671 | 1.515625 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*******************************************************************************
* Copyright (c) 2023 Tremolo Security, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.tremolosecurity.util;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.ArrayList;
import org.apache.xml.security.utils.Base64;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import com.tremolosecurity.certs.CertManager;
import com.tremolosecurity.config.xml.ApplicationType;
import com.tremolosecurity.config.xml.ParamType;
import com.tremolosecurity.config.xml.TremoloType;
import com.tremolosecurity.config.xml.TrustType;
import com.tremolosecurity.proxy.util.OpenSAMLUtils;
import org.apache.commons.codec.binary.Hex;
import org.opensaml.core.config.InitializationService;
import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport;
import org.opensaml.core.xml.io.Marshaller;
import org.opensaml.core.xml.io.MarshallingException;
import org.opensaml.saml.saml2.metadata.EntityDescriptor;
import org.opensaml.saml.saml2.metadata.IDPSSODescriptor;
import org.opensaml.saml.saml2.metadata.KeyDescriptor;
import org.opensaml.saml.saml2.metadata.NameIDFormat;
import org.opensaml.saml.saml2.metadata.SingleSignOnService;
import org.opensaml.saml.saml2.metadata.impl.EntityDescriptorBuilder;
import org.opensaml.saml.saml2.metadata.impl.EntityDescriptorMarshaller;
import org.opensaml.saml.saml2.metadata.impl.IDPSSODescriptorBuilder;
import org.opensaml.saml.saml2.metadata.impl.KeyDescriptorBuilder;
import org.opensaml.saml.saml2.metadata.impl.NameIDFormatBuilder;
import org.opensaml.saml.saml2.metadata.impl.SingleSignOnServiceBuilder;
import org.opensaml.security.credential.UsageType;
import org.opensaml.security.x509.BasicX509Credential;
import org.opensaml.xmlsec.signature.KeyInfo;
import org.opensaml.xmlsec.signature.Signature;
import org.opensaml.xmlsec.signature.X509Data;
import org.opensaml.xmlsec.signature.impl.KeyInfoBuilder;
import org.opensaml.xmlsec.signature.impl.X509CertificateBuilder;
import org.opensaml.xmlsec.signature.impl.X509DataBuilder;
import org.opensaml.xmlsec.signature.support.SignatureConstants;
import org.opensaml.xmlsec.signature.support.Signer;
import org.w3c.dom.Element;
/**
* Saml2Metadata
*/
public class Saml2Metadata {
public static String generateIdPMetaData(String baseURL,String idpName,TremoloType tt,KeyStore ks,boolean excludens) throws Exception {
InitializationService.initialize();
ApplicationType idp = null;
for (ApplicationType app : tt.getApplications().getApplication()) {
if (app.getName().equalsIgnoreCase(idpName)) {
idp = app;
}
}
if (idp == null) {
throw new Exception("IdP '" + idpName + "' not found");
}
String url = baseURL + idp.getUrls().getUrl().get(0).getUri();
SecureRandom random = new SecureRandom();
byte[] idBytes = new byte[20];
random.nextBytes(idBytes);
StringBuffer b = new StringBuffer();
b.append('f').append(Hex.encodeHexString(idBytes));
String id = b.toString();
EntityDescriptorBuilder edb = new EntityDescriptorBuilder();
EntityDescriptor ed = edb.buildObject();
ed.setID(id);
ed.setEntityID(url);
IDPSSODescriptorBuilder idpssdb = new IDPSSODescriptorBuilder();
IDPSSODescriptor sd = idpssdb.buildObject();//ed.getSPSSODescriptor("urn:oasis:names:tc:SAML:2.0:protocol");
sd.addSupportedProtocol("urn:oasis:names:tc:SAML:2.0:protocol");
ed.getRoleDescriptors().add(sd);
HashMap<String,List<String>> params = new HashMap<String,List<String>>();
for (ParamType pt : idp.getUrls().getUrl().get(0).getIdp().getParams()) {
List<String> vals = params.get(pt.getName());
if (vals == null) {
vals = new ArrayList<String>();
params.put(pt.getName(), vals);
}
vals.add(pt.getValue());
}
sd.setWantAuthnRequestsSigned(params.containsKey("requireSignedAuthn") && params.get("requireSignedAuthn").get(0).equalsIgnoreCase("true"));
KeyDescriptorBuilder kdb = new KeyDescriptorBuilder();
if (params.get("encKey") != null && ! params.get("encKey").isEmpty() && (ks.getCertificate(params.get("encKey").get(0)) != null)) {
KeyDescriptor kd = kdb.buildObject();
kd.setUse(UsageType.ENCRYPTION);
KeyInfoBuilder kib = new KeyInfoBuilder();
KeyInfo ki = kib.buildObject();
X509DataBuilder x509b = new X509DataBuilder();
X509Data x509 = x509b.buildObject();
X509CertificateBuilder certb = new X509CertificateBuilder();
org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
cert.setValue(Base64.encode(ks.getCertificate(params.get("encKey").get(0)).getEncoded()));
x509.getX509Certificates().add(cert);
ki.getX509Datas().add(x509);
kd.setKeyInfo(ki);
sd.getKeyDescriptors().add(kd);
}
if (params.get("sigKey") != null && ! params.get("sigKey").isEmpty() && (ks.getCertificate(params.get("sigKey").get(0)) != null)) {
KeyDescriptor kd = kdb.buildObject();
kd.setUse(UsageType.SIGNING);
KeyInfoBuilder kib = new KeyInfoBuilder();
KeyInfo ki = kib.buildObject();
X509DataBuilder x509b = new X509DataBuilder();
X509Data x509 = x509b.buildObject();
X509CertificateBuilder certb = new X509CertificateBuilder();
org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
cert.setValue(Base64.encode(ks.getCertificate(params.get("sigKey").get(0)).getEncoded()));
x509.getX509Certificates().add(cert);
ki.getX509Datas().add(x509);
kd.setKeyInfo(ki);
sd.getKeyDescriptors().add(kd);
}
HashSet<String> nameids = new HashSet<String>();
for (TrustType trustType : idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust()) {
for (ParamType pt : trustType.getParam()) {
if (pt.getName().equalsIgnoreCase("nameIdMap")) {
String val = pt.getValue().substring(0,pt.getValue().indexOf('='));
if (! nameids.contains(val)) {
nameids.add(val);
}
}
}
}
NameIDFormatBuilder nifb = new NameIDFormatBuilder();
for (String nidf : nameids) {
NameIDFormat nif = nifb.buildObject();
//nif.setFormat(nidf);
nif.setURI(nidf);
sd.getNameIDFormats().add(nif);
}
SingleSignOnServiceBuilder ssosb = new SingleSignOnServiceBuilder();
SingleSignOnService sso = ssosb.buildObject();
sso.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
sso.setLocation(url + "/httpPost");
sd.getSingleSignOnServices().add(sso);
sso = ssosb.buildObject();
sso.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
sso.setLocation(url + "/httpRedirect");
sd.getSingleSignOnServices().add(sso);
/*
String signingKey = loadOptional(cmd,"signMetadataWithKey",options);
if (signingKey != null && ks.getCertificate(signingKey) != null) {
BasicX509Credential signingCredential = new BasicX509Credential((X509Certificate) ks.getCertificate(signingKey), (PrivateKey) ks.getKey(signingKey,tt.getKeyStorePassword().toCharArray()));
Signature signature = OpenSAMLUtils.buildSAMLObject(Signature.class);
signature.setSigningCredential(signingCredential);
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
ed.setSignature(signature);
try {
XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(ed).marshall(ed);
} catch (MarshallingException e) {
throw new RuntimeException(e);
}
Signer.signObject(signature);
}*/
// Get the Subject marshaller
EntityDescriptorMarshaller marshaller = new EntityDescriptorMarshaller();
// Marshall the Subject
Element assertionElement = marshaller.marshall(ed);
String metadata = net.shibboleth.utilities.java.support.xml.SerializeSupport.nodeToString(assertionElement);
if (excludens) {
metadata = metadata.replaceAll("md:", "").replaceAll("ds:", "");
}
return metadata;
}
}
|
C#
|
UTF-8
| 3,093 | 3.359375 | 3 |
[] |
no_license
|
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
namespace LeetCode
{
public class Solution2 {
private static Dictionary<string,bool> charMapMain = new Dictionary<string,bool>();
public int LengthOfLongestSubstring(string s)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
var len = s.Length;
var maxString = string.Empty;
for(int i=0;i<len;i++)
{
//stopWatch.Start();
for(int j=1;j<=len-i;j++)
{
//Console.WriteLine(j);
var str = s.Substring(i,j);
//Console.WriteLine(str+"s");
if(isUnique(str))
{
if(str.Length>maxString.Length)
maxString = str;
}
}
//charMap.Clear();
//stopWatch.Stop();
//Console.WriteLine($"time taken for {i} :"+stopWatch.ElapsedMilliseconds);
}
stopWatch.Stop();
Console.WriteLine("time taken "+stopWatch.ElapsedMilliseconds);
Console.WriteLine(maxString);
return maxString.Length;
}
public bool isUnique(string s)
{
if(s.Length>2)
if(charMapMain.ContainsKey(s.Substring(0, s.Length-2)))
{
Console.WriteLine(s.Substring(s.Length-2,1));
var s1= Convert.ToChar(s.Substring(s.Length-2,1));
return !s.Contains(s1);
}
var charMap = new Dictionary<char,int>();
//Stopwatch sw = new Stopwatch();
//sw.Start();
foreach(char c in s)
{
if(charMap.ContainsKey(c))
{
charMap[c]++;
break;
}
else
charMap.Add(c,1);
}
//sw.Stop();
//Console.WriteLine("time in isunique "+ DateTime.Now);
var count = charMap.Values.Count(x=> x!=1);
var result =false;
if(count==0)
result= true;
else
result=false;
charMapMain.Add(s, result);
return result;
}
}
}/*
sliding windows
public int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet<>();
int ans = 0, i = 0, j = 0;
while (i < n && j < n) {
// try to extend the range [i, j]
if (!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
ans = Math.max(ans, j - i);
}
else {
set.remove(s.charAt(i++));
}
}
//sliding windows optimized
return ans;
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length(), ans = 0;
Map<Character, Integer> map = new HashMap<>(); // current index of character
// try to extend the range [i, j]
for (int j = 0, i = 0; j < n; j++) {
if (map.containsKey(s.charAt(j))) {
i = Math.max(map.get(s.charAt(j)), i);
}
ans = Math.max(ans, j - i + 1);
map.put(s.charAt(j), j + 1);
}
return ans;
}
}
*/
|
Markdown
|
UTF-8
| 3,477 | 3.234375 | 3 |
[
"CC-BY-4.0"
] |
permissive
|
---
layout: post
title: "Enforcing Mandatory Comments in C#"
date: 2015-07-10 00:47:07
tags: vs-studio project comments conventions
---
Making C# documentation mandatory for all public members is easy. Builds will
stop any code without standard comments dead in their tracks. Too much code
to update everything at once? You can selectively disable this option for code
you cannot fix yet. In an earlier [post][enforce] I mentioned you can make
comments mandatory and in this post I will show you how.
Why?
===============================================================================
Documentation is a great tool for helping people understand and navigate code.
The exterminator team I was a part of team has been really big on adding documentation lately. Anytime the team
encounters code new undocumented code or learns something new after debugging a
challenging problem they try to improve the documentation.
I don't like to think about coding standards. Mandatory comments are really easy to
enforce using the C# compiler. Let the tools do the work for you, so you can
focus on solving problems.
Enable the Project Setting
===============================================================================
The bottom of the build tab within your Visual Studio project settings has
everything you will need to enforce comments for all public members and types.
In order to enforce the setting do the following:
1. Enable XML documentation
2. Enable **Treat All Warnings As Errors** or **Specific Warnings with [1591][cs1591]**
3. Run a build to find missing comments
The screenshot below shows specifying the documentation warning to fail the build
and a failed build due to missing documentation:
<img src="/images/EnforcedComments.png" />
Updating the code
===============================================================================
If you are like me and are updating an existing codebase you probably have your
work cut out for you.
When I needed to do this I skipped updating documentation for some code I didn't know.
After updating hundreds of classes and methods I started to wear down. Rather
than write dumb boilerplate comments which did not help the code, I decided to leave it until the next time
we were working on that code.
You can use ``#pragma warning disable 1591`` and ``#pragma warning restore 1591``
to ignore missing comments and restore enforce missing comments, respectively.
If you want to ignore missing comments for an entire file place the
``#pragma warning disable 1591`` at the very top. The example below shows
ignoring and restoring the missing comment warnings.
{% highlight csharp tabsize=4 %}
using System;
namespace Example {
/// <summary>This sample program greets friendly users!</summary>
public static class Program {
// Start ignoring methods which don't have comments
#pragma warning disable 1591
public static void Main() {
Console.WriteLine( Message );
}
// Any additional lines past this point would have comments enforced
#pragma warning restore 1591
/// <summary>A common greeting among computers</summary>
public const string Message = "Hello World";
}
}
{% endhighlight %}
Enjoy
===============================================================================
So there you have it, enforcing comments for fun and profit. Enjoy!
[enforce]: /posts/exterminator-10-caught-by-conventions/#ext-10-note-1-reverse
[cs1591]: https://msdn.microsoft.com/en-us/library/zk18c1w9.aspx
|
Java
|
UTF-8
| 421 | 3.796875 | 4 |
[] |
no_license
|
/*
* Pertemuan 02b: Aritmatika dengan OOP
*/
class AritmatikaOOP{
int a;
int b;
public int kali(int a, int b){
int c = a*b;
return c;
}
public int bagi(int a, int b){
int c = a/b;
return c;
}
public int tambah(int a, int b){
int c = a+b;
return c;
}
public int kurang(int a,int b){
int c = a-b;
return c;
}
}
|
Markdown
|
UTF-8
| 557 | 2.546875 | 3 |
[] |
no_license
|
Build the image from the Dockerfile
```docker build -t grafana:{version} .```
If you do not have image modifications than just pull the official Grafana image
docker pull grafana:{version}
Set the right tag to push to the repository
```docker tag {repo}/grafana:{version} {aws_account_id}.dkr.ecr.{region}.amazonaws.com/{repo}/grafana:{version}```
Push the newly created image to the AWS repository
```docker push {aws_account_id}.dkr.ecr.{region}.amazonaws.com/{repo}/grafana:{version}```
Please repeate these steps with the influxdb image too
|
Java
|
UTF-8
| 317 | 1.710938 | 2 |
[] |
no_license
|
package com.hrpasquati.cursomc.cursomc.repositoyOuDAO;
import com.hrpasquati.cursomc.cursomc.domain.Endereco;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EnderecoRepository extends JpaRepository<Endereco, Integer> {
}
|
TypeScript
|
UTF-8
| 467 | 3.234375 | 3 |
[] |
no_license
|
interface ParseResult<T> {
success: boolean;
data: T;
}
export const parser = (contents: string): ParseResult<string[]> => {
const lines = contents.split('\n');
const parsableLines = lines.filter(line => !line.startsWith('#'));
const words: string[] = parsableLines.map(line => {
return line.replace(/[^a-zA-Z]/g, '').toUpperCase();
});
const data = words.filter(word => word.length >= 3 && word.length <= 15);
return { success: true, data };
};
|
SQL
|
UTF-8
| 8,225 | 2.953125 | 3 |
[] |
no_license
|
-- Generated by Oracle SQL Developer Data Modeler 20.2.0.167.1538
-- at: 2020-10-09 14:55:56 MESZ
-- site: Oracle Database 12cR2
-- type: Oracle Database 12cR2
-- predefined type, no DDL - MDSYS.SDO_GEOMETRY
-- predefined type, no DDL - XMLTYPE
CREATE TABLE animals (
animal_id INTEGER,
animal_name VARCHAR2
-- ERROR: VARCHAR2 size not specified
,
villeger_id INTEGER,
domesticated RAW(2000),
age INTEGER,
competence_bonus FLOAT,
meat_content FLOAT,
villegar_villegar_id NUMBER NOT NULL
);
CREATE TABLE disease (
disease_id INTEGER,
disease_name VARCHAR2
-- ERROR: VARCHAR2 size not specified
,
duration_in_days INTEGER,
risk_of_death FLOAT,
competence_malus FLOAT,
villegar_villegar_id NUMBER NOT NULL
);
CREATE TABLE family (
family_id INTEGER,
last_name VARCHAR2
-- ERROR: VARCHAR2 size not specified
,
villagar_id INTEGER,
housing_id INTEGER,
family_happiness FLOAT,
family_id1 NUMBER NOT NULL,
village_village_id1 NUMBER NOT NULL
);
ALTER TABLE family ADD CONSTRAINT family_pk PRIMARY KEY ( family_id1 );
CREATE TABLE housing (
house_id INTEGER,
family_id INTEGER,
size_in_m2 INTEGER,
condition FLOAT,
age INTEGER,
family_family_id1 NUMBER NOT NULL
);
CREATE UNIQUE INDEX housing__idx ON
housing (
family_family_id1
ASC );
CREATE TABLE job (
job_id INTEGER,
job_name VARCHAR2
-- ERROR: VARCHAR2 size not specified
,
required_competence FLOAT,
wage FLOAT,
risk_factor FLOAT,
job_id1 NUMBER NOT NULL,
villegar_villegar_id NUMBER NOT NULL
);
CREATE UNIQUE INDEX job__idx ON
job (
villegar_villegar_id
ASC );
ALTER TABLE job ADD CONSTRAINT job_pk PRIMARY KEY ( job_id1 );
CREATE TABLE location (
location_id INTEGER,
location_name VARCHAR2
-- ERROR: VARCHAR2 size not specified
,
job_id INTEGER,
condition FLOAT,
max_number_of_villegars INTEGER,
food_content FLOAT,
max_number_of_animals INTEGER,
location_id1 NUMBER NOT NULL,
job_job_id1 NUMBER NOT NULL
);
CREATE UNIQUE INDEX location__idx ON
location (
job_job_id1
ASC );
ALTER TABLE location ADD CONSTRAINT location_pk PRIMARY KEY ( location_id1 );
CREATE TABLE village (
village_id INTEGER,
village_name VARCHAR2
-- ERROR: VARCHAR2 size not specified
,
family_id INTEGER,
location_id INTEGER,
popularity FLOAT,
village_id1 NUMBER NOT NULL,
location_location_id1 NUMBER NOT NULL
);
CREATE UNIQUE INDEX village__idx ON
village (
location_location_id1
ASC );
ALTER TABLE village ADD CONSTRAINT village_pk PRIMARY KEY ( village_id1 );
CREATE TABLE villegar (
villager_id INTEGER,
first_name VARCHAR2
-- ERROR: VARCHAR2 size not specified
,
last_name VARCHAR2
-- ERROR: VARCHAR2 size not specified
,
sex RAW(2000),
age INTEGER,
job_id INTEGER,
disease_id INTEGER,
competence FLOAT,
happiness FLOAT,
animal_id INTEGER,
villegar_id NUMBER NOT NULL,
family_family_id1 NUMBER NOT NULL
);
ALTER TABLE villegar ADD CONSTRAINT villegar_pk PRIMARY KEY ( villegar_id );
ALTER TABLE animals
ADD CONSTRAINT animals_villegar_fk FOREIGN KEY ( villegar_villegar_id )
REFERENCES villegar ( villegar_id );
ALTER TABLE disease
ADD CONSTRAINT disease_villegar_fk FOREIGN KEY ( villegar_villegar_id )
REFERENCES villegar ( villegar_id );
ALTER TABLE family
ADD CONSTRAINT family_village_fk FOREIGN KEY ( village_village_id1 )
REFERENCES village ( village_id1 );
ALTER TABLE housing
ADD CONSTRAINT housing_family_fk FOREIGN KEY ( family_family_id1 )
REFERENCES family ( family_id1 );
ALTER TABLE job
ADD CONSTRAINT job_villegar_fk FOREIGN KEY ( villegar_villegar_id )
REFERENCES villegar ( villegar_id );
ALTER TABLE location
ADD CONSTRAINT location_job_fk FOREIGN KEY ( job_job_id1 )
REFERENCES job ( job_id1 );
ALTER TABLE village
ADD CONSTRAINT village_location_fk FOREIGN KEY ( location_location_id1 )
REFERENCES location ( location_id1 );
ALTER TABLE villegar
ADD CONSTRAINT villegar_family_fk FOREIGN KEY ( family_family_id1 )
REFERENCES family ( family_id1 );
CREATE SEQUENCE family_family_id1_seq START WITH 1 NOCACHE ORDER;
CREATE OR REPLACE TRIGGER family_family_id1_trg BEFORE
INSERT ON family
FOR EACH ROW
WHEN ( new.family_id1 IS NULL )
BEGIN
:new.family_id1 := family_family_id1_seq.nextval;
END;
/
CREATE SEQUENCE job_job_id1_seq START WITH 1 NOCACHE ORDER;
CREATE OR REPLACE TRIGGER job_job_id1_trg BEFORE
INSERT ON job
FOR EACH ROW
WHEN ( new.job_id1 IS NULL )
BEGIN
:new.job_id1 := job_job_id1_seq.nextval;
END;
/
CREATE SEQUENCE location_location_id1_seq START WITH 1 NOCACHE ORDER;
CREATE OR REPLACE TRIGGER location_location_id1_trg BEFORE
INSERT ON location
FOR EACH ROW
WHEN ( new.location_id1 IS NULL )
BEGIN
:new.location_id1 := location_location_id1_seq.nextval;
END;
/
CREATE SEQUENCE village_village_id1_seq START WITH 1 NOCACHE ORDER;
CREATE OR REPLACE TRIGGER village_village_id1_trg BEFORE
INSERT ON village
FOR EACH ROW
WHEN ( new.village_id1 IS NULL )
BEGIN
:new.village_id1 := village_village_id1_seq.nextval;
END;
/
CREATE SEQUENCE villegar_villegar_id_seq START WITH 1 NOCACHE ORDER;
CREATE OR REPLACE TRIGGER villegar_villegar_id_trg BEFORE
INSERT ON villegar
FOR EACH ROW
WHEN ( new.villegar_id IS NULL )
BEGIN
:new.villegar_id := villegar_villegar_id_seq.nextval;
END;
/
-- Oracle SQL Developer Data Modeler Summary Report:
--
-- CREATE TABLE 8
-- CREATE INDEX 4
-- ALTER TABLE 13
-- CREATE VIEW 0
-- ALTER VIEW 0
-- CREATE PACKAGE 0
-- CREATE PACKAGE BODY 0
-- CREATE PROCEDURE 0
-- CREATE FUNCTION 0
-- CREATE TRIGGER 5
-- ALTER TRIGGER 0
-- CREATE COLLECTION TYPE 0
-- CREATE STRUCTURED TYPE 0
-- CREATE STRUCTURED TYPE BODY 0
-- CREATE CLUSTER 0
-- CREATE CONTEXT 0
-- CREATE DATABASE 0
-- CREATE DIMENSION 0
-- CREATE DIRECTORY 0
-- CREATE DISK GROUP 0
-- CREATE ROLE 0
-- CREATE ROLLBACK SEGMENT 0
-- CREATE SEQUENCE 5
-- CREATE MATERIALIZED VIEW 0
-- CREATE MATERIALIZED VIEW LOG 0
-- CREATE SYNONYM 0
-- CREATE TABLESPACE 0
-- CREATE USER 0
--
-- DROP TABLESPACE 0
-- DROP DATABASE 0
--
-- REDACTION POLICY 0
--
-- ORDS DROP SCHEMA 0
-- ORDS ENABLE SCHEMA 0
-- ORDS ENABLE OBJECT 0
--
-- ERRORS 8
-- WARNINGS 0
|
Java
|
UTF-8
| 1,000 | 2.46875 | 2 |
[] |
no_license
|
package forum;
public class Message {
private int id;
private int s_id;
private int r_id;
private String title;
private String message;
private int s_status;
private int r_status;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getS_id() {
return s_id;
}
public void setS_id(int s_id) {
this.s_id = s_id;
}
public int getR_id() {
return r_id;
}
public void setR_id(int r_id) {
this.r_id = r_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getS_status() {
return s_status;
}
public void setS_status(int s_status) {
this.s_status = s_status;
}
public int getR_status() {
return r_status;
}
public void setR_status(int r_status) {
this.r_status = r_status;
}
public String toString() {
return "m";
}
}
|
Java
|
UTF-8
| 1,433 | 3.484375 | 3 |
[] |
no_license
|
/**
* Description
*
* Classe répertoriant les méthodes de test de mouvement
*/
/**
* @author Maxime Caron
*
*/
public final class Move {
/**
*Vérifie si un mouvement est horizontal
*
* @param p1
* @param p2
* @return true si le mouvement est horizontal, false sinon
*/
static boolean horizontal(Position p1, Position p2){
return (p1.getRow() == p2.getRow());
}
/**
* Calcul la longueur d'un déplacement horizontal
*
* @param p1
* @param p2
* @return distance horizotal entre p1 et p2
*/
static int longueurHorizontal(Position p1, Position p2){
return (p1.getRow()-p1.getRow());
}
/**
*Vérifie si un mouvement est vertical
*
* @param p1
* @param p2
* @return true si le mouvement est vertical, false sinon
*/
static boolean vertical(Position p1, Position p2){
return (p1.getCol() == p2.getCol());
}
/**
* Calcul la longueur d'un déplacement vertical
*
* @param p1
* @param p2
* @return distance vertical entre p1 et p2
*/
static int longueurVertical(Position p1, Position p2){
return (p2.getCol()-p1.getCol());
}
/**
*Vérifie si un mouvement est diagonal
*
* @param p1
* @param p2
* @return true si le mouvement est diagonal, false sinon
*/
static boolean diagonal(Position p1, Position p2){
return (longueurVertical(p1,p2) == longueurHorizontal(p1,p2));
}
}
|
Python
|
UTF-8
| 1,220 | 2.859375 | 3 |
[] |
no_license
|
import numpy as np
import os
from scipy.io import loadmat
import pandas as pd
import time
start_time = time.time()
pressure_mat_path = "E:/PycharmProjects/wide_scope/sensor_pressure.mat"
raw_data = loadmat(pressure_mat_path)
# loadmat() 之后得到的是一个dict
# dict_keys(['__header__', '__version__', '__globals__', 'sensor_pressure'])
print(raw_data.keys())
sensor_pressure = raw_data['sensor_pressure']
# 取出来之后是个ndarray
# 497320, 10
print(sensor_pressure.shape)
pressure_data = pd.DataFrame(sensor_pressure)
print(pressure_data)
new_index = np.arange(126100, 424300, 10)
# 29820
print(new_index.__len__())
pressure_data = pd.DataFrame(pressure_data, index=new_index)
# [29820 rows x 10 columns]
print(pressure_data)
if not os.path.exists("E:/PycharmProjects/wide_scope/pressure_data.csv"):
pressure_data.to_csv("E:/PycharmProjects/wide_scope/pressure_data.csv",
index=False, header=False)
else:
os.remove("E:/PycharmProjects/wide_scope/pressure_data.csv")
pressure_data.to_csv("E:/PycharmProjects/wide_scope/pressure_data.csv",
index=False, header=False)
end_time = time.time()
print("End! During time is %.2f minutes" % ((end_time - start_time)/60))
|
Java
|
UTF-8
| 2,590 | 2.21875 | 2 |
[] |
no_license
|
package com.saimadhu.mychatapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.Toolbar;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class LoginActivity extends AppCompatActivity {
EditText email,password;
Button button_login;
FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// //accessing the toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setActionBar(toolbar);
getActionBar().setTitle("Login");
getActionBar().setDisplayHomeAsUpEnabled(true);
email = (EditText)findViewById(R.id.login_email);
password = (EditText)findViewById(R.id.login_password);
button_login = (Button)findViewById(R.id.button_login);
button_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAuth = FirebaseAuth.getInstance();
String txt_email = email.getText().toString();
String txt_password = password.getText().toString();
Toast.makeText(LoginActivity.this, txt_email, Toast.LENGTH_SHORT).show();
mAuth.signInWithEmailAndPassword(txt_email,txt_password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
} else{
Toast.makeText(LoginActivity.this, "Authentication Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}
|
Java
|
UTF-8
| 475 | 2.4375 | 2 |
[
"MIT"
] |
permissive
|
package com.algolia.search.exceptions;
/**
* Exception thrown when an error occurs during the retry strategy. For example: All hosts are
* unreachable.
*/
public class AlgoliaRetryException extends AlgoliaRuntimeException {
public AlgoliaRetryException(String message, Throwable cause) {
super(message, cause);
}
public AlgoliaRetryException(String message) {
super(message);
}
public AlgoliaRetryException(Throwable cause) {
super(cause);
}
}
|
C#
|
UTF-8
| 1,186 | 3.484375 | 3 |
[] |
no_license
|
using System;
namespace TechReturners.Exercises
{
public interface ICat
{
bool IsAsleep { get; set; }
string Setting { get; set; }
string Eat { get; set; }
int AverageHeight { get; set; }
void GoToSleep();
void WakeUp();
}
public abstract class TypeCat : ICat
{
public bool IsAsleep { get; set; }
public string Setting { get; set; }
public string Eat { get; set; }
public int AverageHeight { get; set; }
public void GoToSleep()
{
IsAsleep = true;
}
public void WakeUp()
{
IsAsleep = false;
}
}
public class DomesticCat : TypeCat
{
public DomesticCat()
{
IsAsleep = false;
Setting = "domestic";
AverageHeight = 23;
Eat = "Purrrrrrr";
}
}
public class LionCat : TypeCat
{
public LionCat()
{
AverageHeight = 1100;
Eat = "Roar!!!!";
}
}
public class CheetahCat : TypeCat
{
public CheetahCat()
{
Eat = "Zzzzzzz";
}
}
}
|
Java
|
UTF-8
| 3,834 | 2.015625 | 2 |
[] |
no_license
|
package com.ogc.standard.ao.impl;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ogc.standard.ao.IShareRecordAO;
import com.ogc.standard.bo.IAccountBO;
import com.ogc.standard.bo.ISYSConfigBO;
import com.ogc.standard.bo.IShareRecordBO;
import com.ogc.standard.bo.IUserBO;
import com.ogc.standard.bo.base.Paginable;
import com.ogc.standard.common.AmountUtil;
import com.ogc.standard.common.SysConstants;
import com.ogc.standard.domain.Account;
import com.ogc.standard.domain.ShareRecord;
import com.ogc.standard.domain.User;
import com.ogc.standard.enums.ECurrency;
import com.ogc.standard.enums.EJourBizTypePlat;
import com.ogc.standard.enums.EJourBizTypeUser;
import com.ogc.standard.enums.ESysConfigType;
import com.ogc.standard.enums.ESystemAccount;
@Service
public class ShareRecordAOImpl implements IShareRecordAO {
@Autowired
private IShareRecordBO shareRecordBO;
@Autowired
private IAccountBO accountBO;
@Autowired
private ISYSConfigBO sysConfigBO;
@Autowired
private IUserBO userBO;
@Override
@Transactional
public String addShareRecord(String userId, String channel,
String content) {
String code = shareRecordBO.saveShareRecord(userId, channel, content);
// 添加碳泡泡
Map<String, String> configMap = sysConfigBO
.getConfigsMap(ESysConfigType.TPP_RULE.getCode());
BigDecimal quantity = new BigDecimal(configMap.get(SysConstants.SHARE));
quantity = AmountUtil.mul(quantity, 1000L);
Account userTppAccount = accountBO.getAccountByUser(userId,
ECurrency.TPP.getCode());
Account sysTppAccount = accountBO
.getAccount(ESystemAccount.SYS_ACOUNT_TPP_POOL.getCode());
// if (quantity.compareTo(sysTppAccount.getAmount()) == 1) {
// quantity = sysTppAccount.getAmount();
// }
accountBO.transAmount(sysTppAccount, userTppAccount, quantity,
EJourBizTypeUser.SHARE.getCode(), EJourBizTypePlat.SHARE.getCode(),
EJourBizTypeUser.SHARE.getValue(),
EJourBizTypePlat.SHARE.getValue(), userId);
return code;
}
@Override
public Paginable<ShareRecord> queryShareRecordPage(int start, int limit,
ShareRecord condition) {
Paginable<ShareRecord> page = shareRecordBO.getPaginable(start, limit,
condition);
if (null != page && CollectionUtils.isNotEmpty(page.getList())) {
for (ShareRecord shareRecord : page.getList()) {
init(shareRecord);
}
}
return page;
}
@Override
public List<ShareRecord> queryShareRecordList(ShareRecord condition) {
List<ShareRecord> list = shareRecordBO.queryShareRecordList(condition);
if (CollectionUtils.isNotEmpty(list)) {
for (ShareRecord shareRecord : list) {
init(shareRecord);
}
}
return list;
}
@Override
public ShareRecord getShareRecord(String code) {
ShareRecord shareRecord = shareRecordBO.getShareRecord(code);
init(shareRecord);
return shareRecord;
}
private void init(ShareRecord shareRecord) {
String userName = null;
User user = userBO.getUserUnCheck(shareRecord.getUserId());
if (null != user) {
userName = user.getMobile();
if (null != user.getRealName()) {
userName = user.getRealName() + userName;
}
shareRecord.setUserName(userName);
}
}
}
|
JavaScript
|
UTF-8
| 930 | 2.90625 | 3 |
[] |
no_license
|
import React, { Component } from 'react';
import './App.css';
import ValidationComponent from './ValidationComponent/ValidationComponent'
class App extends Component {
state = {
text: 'test',
textLengthStatus: 'Too short!'
}
textChangeHandler = ( event ) => {
this.setState( {text: event.target.value} );
if( this.state.text.length < 5 ) {
this.setState( {textLengthStatus: 'Too short!'} );
}
else if( this.state.text.length > 5 ) {
this.setState( {textLengthStatus: 'Too long!'} );
}
else {
this.setState( {textLengthStatus: 'Just right!'} );
}
}
render() {
return (
<div className="App">
<input type="text" onChange={this.textChangeHandler}/>
<ValidationComponent
text={this.state.text}
textLengthStatus={this.state.textLengthStatus}>
</ValidationComponent>
</div>
);
}
}
export default App;
|
Ruby
|
UTF-8
| 1,079 | 2.53125 | 3 |
[] |
no_license
|
require "http"
require_relative "../../models/serializers"
module TvShowQueries
@@API_KEY = 'da4c6ba6f06724d02816bdcefb12c87b'
def tv_show_by_id(id:)
url = "https://api.themoviedb.org/3/tv/#{id}?api_key=#@@API_KEY&language=en-US"
response = HTTP.get(url)
return Serializers.serialize_json_object_to_type(response, TvShow)
end
def popular_tv_shows()
url = "https://api.themoviedb.org/3/tv/popular?api_key=#@@API_KEY&language=en-US"
response = HTTP.get(url)
return Serializers.serialize_json_array_to_type(response, TvShow, "results")
end
def top_rated_tv_shows()
url = "https://api.themoviedb.org/3/tv/top_rated?api_key=#@@API_KEY&language=en-US"
response = HTTP.get(url)
return Serializers.serialize_json_array_to_type(response, TvShow, "results")
end
def on_air_tv_shows()
url = "https://api.themoviedb.org/3/tv/on_the_air?api_key=#@@API_KEY&language=en-US"
response = HTTP.get(url)
return Serializers.serialize_json_array_to_type(response, TvShow, "results")
end
end
|
C#
|
UTF-8
| 1,111 | 3.421875 | 3 |
[
"MIT"
] |
permissive
|
namespace P01.MarketStore.Core
{
using System;
public class PayDesk
{
public static void PrintPurchaseValue(decimal purchaseValue)
{
string message = $"Purchase value: ${purchaseValue}";
Console.WriteLine(message);
}
public static void PrintDiscountRate(decimal discountRate)
{
string message = $"Discount rate: {discountRate:F1}%";
Console.WriteLine(message);
}
public static void PrintDiscount(decimal discountRate, decimal purchaseValue)
{
decimal discountSum = (discountRate / 100m) * purchaseValue;
string message = $"Discount: ${discountSum:F2}";
Console.WriteLine(message);
}
public static void PrintTotalPurchase(decimal discountRate, decimal purchaseValue)
{
decimal discountSum = (discountRate / 100m) * purchaseValue;
decimal totalSum = purchaseValue - discountSum;
string message = $"Total: ${totalSum:F2}";
Console.WriteLine(message);
}
}
}
|
Java
|
UTF-8
| 828 | 2.015625 | 2 |
[] |
no_license
|
package com.dkswjdals89.krakensearch.domain.history;
import com.dkswjdals89.krakensearch.constant.SearchType;
import com.dkswjdals89.krakensearch.domain.BaseTimeEntity;
import com.dkswjdals89.krakensearch.domain.account.Account;
import lombok.*;
import javax.persistence.*;
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Getter
@ToString
@Entity(name = "tlb_search_history")
public class SearchHistory extends BaseTimeEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(targetEntity = Account.class)
@JoinColumn
private Account account;
@Enumerated(EnumType.STRING)
@Column(columnDefinition = "TEXT", nullable = false)
private SearchType searchType;
@Column(columnDefinition = "TEXT", nullable = false)
private String searchKeyword;
}
|
Python
|
UTF-8
| 1,965 | 3.234375 | 3 |
[] |
no_license
|
import unittest
from User import User
from hashlib import md5
class UserTestCase(unittest.TestCase):
def test_basic(self):
u = User('user1', 'ashgdhsfv', email='user1@gmail.com')
self.assertEqual(u.username, 'user1')
self.assertEqual(u.email, 'user1@gmail.com')
self.assertNotEqual(u.password, 'ashgdhsfv')
# check that it uses by folder>python -m unittest
# self.assertEqual(1,2)
def test_skip_optional(self):
u = User('user2', 'ashgdhsfv', email='user1@gmail.com', fax='+380671412')
self.assertFalse(hasattr(u, 'fax'))
# check that it uses by folder>python -m unittest
# self.assertEqual(1 in {3, 2}, False)
def test_create_with_pswd(self):
user = User('user1', password='QAZWSX!@')
self.assertTrue(hasattr(user, 'pass_hash'))
self.assertEqual(user.pass_hash, md5(b'QAZWSX!@').hexdigest())
# print(md5('QAZWSX!@'.encode()))
# print(md5(b'QAZWSX!@'))
# self.assertIn(1, {3, 2}) # better error descr
# self.assertEqual(1 in {3, 2}, False)
def test_set_password(self):
user = User('user1', password='QAZWSX!@')
user.password ='QAZWSX!@'
self.assertTrue(hasattr(user, 'pass_hash'))
self.assertTrue(hasattr(user, 'password'))
def test_set_attr(self):
user = User('user1', password='QAZWSX!@')
# useful when we expect the exception to be raised
# with self.assertRaises(AttributeError):
# user.password = 'QWERTY'
if __name__ == '__main__':
unittest.main()
# The same with simple assers
# u = User('user1', 'ashgdhsfv', email='user1@gmail.com')
# assert u.username == 'user1'
# assert u.pass_hash == 'ashgdhsfv'
# assert u.email == 'user1@gmail.com'
# u2 = User(
# 'user2', 'ashgdhsfv', email='user1@gmail.com', fax='+380677931412'
# )
# assert not hasattr(u2, 'fax'), 'No such attribute'
# assert u.username == u2.username, (u.username, u2.username)
|
Python
|
UTF-8
| 722 | 3.75 | 4 |
[] |
no_license
|
#import the pandas library and aliasing as pd
import pandas as pd
import numpy as np
data = {'x' : 10., 'y' : 11., 'z' : 12.}
s = pd.Series(data)
print s
data = {'a1' : 10, 'a2' : 11, 'a3' : 12}
s = pd.Series(data)
print s["a1":"a2"]
data = {'a' : 0., 'b' : 1., 'c' : 2.}
s = pd.Series(data,index=['b','c','d','a'])
print s
"""Index order is persisted and the missing element is filled with NaN (Not a Number)."""
s = pd.Series(5, index=[0, 1, 2, 3])
print s
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
print s
#retrieve the first element
print s[0]
print s[:3]
#retrieve the last three element
print s[-3:]
#retrieve multiple elements
print s[['a','c','d']]
#retrieve non exist elements
#print s['f']
|
Java
|
UTF-8
| 717 | 2.125 | 2 |
[
"MIT"
] |
permissive
|
package app.projectma.WsConfig;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component
public class WebSocketEventListener {
private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketEventListener.class);
@EventListener
public void handleWebsocketConnectListener(final SessionConnectedEvent event) {
LOGGER.info("new connection!");
}
@EventListener
public void handleWebsocketDisconnectListener(final SessionConnectedEvent event) {
LOGGER.info("disconnected!");
}
}
|
Java
|
UTF-8
| 1,098 | 2.5 | 2 |
[] |
no_license
|
package com.chowhound.chowhound.models;
import com.chowhound.chowhound.ChowhoundApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ChowhoundApplication.class)
public class CuisineTests {
@Test
public void testCuisineGettersAndSetters() {
Cuisine testCuisine = new Cuisine();
int id = 1;
String description = "test cuisine";
List<Truck> trucksWithTestCuisine = new ArrayList<>();
testCuisine.setId(id);
testCuisine.setCategory(description);
testCuisine.setIsPrimary(true);
testCuisine.setTrucks(trucksWithTestCuisine);
assertEquals(id,testCuisine.getId());
assertEquals(description, testCuisine.getCategory());
assertTrue(testCuisine.isIsPrimary());
assertEquals(0, testCuisine.getTrucks().size());
}
}
|
Python
|
UTF-8
| 1,385 | 3.703125 | 4 |
[] |
no_license
|
# pay attention on infinity 'inf' +infinity = float('inf'), -infinity = float('-inf')
# In Java, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY
def peak_finding(alist):
""" a brute force method """
i = 0
length = len(alist)
while i < length:
if i ==0 and alist[i]>alist[i+1]:
print 'find a peak', alist[i]
return alist[i]
elif i==length-1 and alist[i]>alist[i-2]:
print 'find a peak', alist[i]
return alist[i]
else:
if alist[i]>=alist[i-1] and alist[i]>=alist[i+1]:
print 'find peak', alist[i]
return alist[i]
else:
print 'keep moving forward'
i += 1
def peak_finding2(alist):
""" divide and conquer method """
# first reconstruct this list
blist = []
blist.append(float('-inf'))
blist = [x for x in alist]
import random
length = len(alist)
pivot = random.randint(0, length-1)
print 'pivot', pivot
if pivot == 0 and alist[pivot] > alist[pivot+1]:
return alist[pivot]
elif pivot = length-1 and alist[pivot]>
alistt = [12,23,1,8,9,11,32,45,0,7,6,4,31]
peak_finding(alistt)
|
Markdown
|
UTF-8
| 2,055 | 2.921875 | 3 |
[] |
no_license
|
---
layout: mechanics
title: Sprint Review
order: 90
---
The Sprint Review is an inspect-adapt point at the end of the Sprint. During the Sprint Review, customers and stakeholders examine what the teams built during the Sprint and discuss changes and new ideas. Together the Teams, Product Owner and users/customers/stakeholders decide the direction of the product.
# Overview of the Sprint Review
The Sprint Review is the occasion for all of the teams to review the *one* potentially shippable Product Increment together. The focus is on the [whole product](../principles/whole-product-focus.html).
<figure>
<img src="/img/framework/sprint-review-retrospective.png" alt="sprint-review-retrospective.png">
</figure>
## Inspect-Adapt and *not* Inspect-Accept
The most common mistake in a Sprint Review is to focus on the Product Owner accepting items from the teams. This is a misunderstanding of the purpose of the Sprint Review and moves it away from [empirical process control](../principles/empirical_process_control.html) towards finding blame. The Sprint Review is an opportunity for everyone to collaborate about the product.
## Sprint Review Bazaar
The Sprint Review is best conducted using a diverge-converge meeting pattern. During the diverge periods, use a bazaar. This is analogous to a science fair: A large room has multiple areas, each staffed by team representatives, where the items developed by a team are shown and discussed. Stakeholders visit areas of interest.
During the converge periods, stakeholders summarize their opinions from the bazaar. A subset of items may be inspected on a common computer projector during this time, also.
There may be multiple diverge-converge cycles.
## Recommended Reading
* Inspect and Adapt chapter of [Practices for Scaling Agile & Lean Development](http://www.amazon.com/Practices-Scaling-Lean-Agile-Development/dp/0321636406)
This 40-page chapter covers adoption and also review retrospective. It is also [available online](http://www.informit.com/articles/article.aspx?p=1564482).
|
PHP
|
UTF-8
| 416 | 2.765625 | 3 |
[] |
no_license
|
<?php
namespace Interfaces;
/**
* Interface EntityInterface
* @package Interfaces
*/
interface EntityInterface
{
/**
* @param $contentTypeId
* @param $entry
* @return mixed
*/
public function renderTemplate();
/**
* @return mixed
*/
public function toArray();
/**
* @param $entry
* @return mixed
*/
public function setProprieties($entry);
}
|
Java
|
UTF-8
| 876 | 2.421875 | 2 |
[] |
no_license
|
package alt.flex.server.internal;
import io.netty.channel.Channel;
import java.util.Iterator;
import java.util.TimerTask;
import alt.flex.protocol.FlexProtocol.Response;
import alt.flex.protocol.FlexProtocol.ResponseType;
/**
*
* @author Albert Shift
*
*/
public final class HeartBreathSender extends TimerTask {
private final static Response HEART_BREATH_RESPONSE = Response.newBuilder().setResponseType(ResponseType.HEART_BREATH).build();
private final ClientManager clientManager;
public HeartBreathSender(ClientManager clientManager) {
this.clientManager = clientManager;
}
@Override
public void run() {
Iterator<Channel> iterator = clientManager.getConnectedClients();
while(iterator.hasNext()) {
Channel channel = iterator.next();
if (channel.isActive()) {
channel.writeAndFlush(HEART_BREATH_RESPONSE);
}
}
}
}
|
TypeScript
|
UTF-8
| 1,552 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
import { Request, Response } from 'express';
import { getRepository } from 'typeorm';
import * as Yup from 'yup';
import User from '../models/User';
import CreateUserService from '../services/CreateUserService';
export default class UsersController {
// eslint-disable-next-line class-methods-use-this
public async create(request: Request, response: Response): Promise<Response> {
const schema = Yup.object().shape({
name: Yup.string().required(),
email: Yup.string().email().required(),
password: Yup.string().required().min(6),
});
await schema.validate(request.body, {
abortEarly: false,
});
const { name, email, password } = request.body;
const createUser = new CreateUserService();
const user = await createUser.execute({
name,
email,
password,
});
return response.json(user);
}
// eslint-disable-next-line class-methods-use-this
public async index(request: Request, response: Response): Promise<Response> {
const userRepository = getRepository(User);
const users = await userRepository.find();
users.map(user => {
return delete user.password;
});
return response.json(users);
}
// eslint-disable-next-line class-methods-use-this
public async show(request: Request, response: Response): Promise<Response> {
const { id } = request.params;
const userRepository = getRepository(User);
const user = await userRepository.findOneOrFail(id);
delete user.password;
return response.json(user);
}
}
|
Java
|
UTF-8
| 958 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
package com.example.twitter.service.tweet;
import java.util.List;
import com.example.twitter.dto.TweetDTO;
/**
* Service to manage operations over Tweets.
* Allows to save, get and validate Tweets
* @author alvaro
*
*/
public interface TweetService {
/**
* Returns the Tweet (if exists) given an ID
* @param tweetId
* @return
*/
TweetDTO getTweetById(String tweetId);
/**
* Persist the tweet on the database
* @param tweet
* @return
*/
TweetDTO saveTweet(TweetDTO tweet);
/**
* Updates the field 'validated' to the given value
* @param tweetId
*/
void updateValidated(String tweetId, boolean validated);
/**
* Returns a paginated list of tweets
* 'validated' its optional
* If no value is passed on validated field, it will returns tweets with both values
*
* @param page
* @param size
* @param validated
* @return
*/
List<TweetDTO> getTweets(Integer page, Integer size, Boolean validated);
}
|
Java
|
UTF-8
| 1,285 | 3.234375 | 3 |
[] |
no_license
|
package demo;
/**
*
*/
/**
* @author Phan Toan
*
*/
public class OperatorsDemo {
/**
* Demo operators
*/
public static void main(String[] args) {
int num1 = 37;
int num2 = -9;
int num3 = 12;
int num4 = 6;
boolean b = true;
System.out.printf("a:%d a++:%d a:%d\n", num1, num1++, num1);
System.out.printf("num2:%d --num2:%d num2:%d\n", num2, --num2, num2);
System.out.printf("num2:%d -num2:%d num2:%d\n", num2, -num2, num2);
System.out.printf("num2:%d ~num2:%d num2:%d\n", num2, ~num2, num2);
System.out.printf("num2:%d num2<<1:%d num2:%d\n", num2, num2<<1, num2);
System.out.printf("num2:%d num2>>=:%d num2:%d\n", num2, num2>>=2, num2);
System.out.printf("num2:%d num2>>>1:%d num2:%d\n", num2, num2>>>1, num2);
System.out.printf("b:%b !b:%b b:%b\n", b, !b, b);
System.out.printf("num3:%d num3&num4:%d num4:%d\n", num3, num3&num4, num4);
System.out.printf("num3:%d num3^num4:%d num4:%d\n", num3, num3^num4, num4);
System.out.printf("num3:%d num3|num4:%d num4:%d\n", num3, num3|num4, num4);
System.out.printf("num3:%d num4:%d num3+=num4:%d num3:%d\n", num3, num4, num3+=num4, num3);
System.out.printf("num3:%d [num3 > 10 ? num2 : num4]:%d\n", num3, num3 > 10 ? num2 : num4 );
}
}
|
Java
|
UTF-8
| 1,510 | 1.921875 | 2 |
[] |
no_license
|
package com.youyisi.admin.application.invitefriendactivity.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.youyisi.admin.application.invitefriendactivity.InviteFriendActivityService;
import com.youyisi.admin.domain.invitefriendactivity.InviteFriendActivity;
import com.youyisi.admin.domain.invitefriendactivity.InviteFriendActivityRepository;
import com.youyisi.lang.Page;
/**
* @author shuye
* @time 2016-08-11
*/
@Service
public class InviteFriendActivityServiceImpl implements InviteFriendActivityService {
@Autowired
private InviteFriendActivityRepository repository;
@Override
public InviteFriendActivity get(Long id) {
return repository.get(id);
}
@Override
public InviteFriendActivity save(InviteFriendActivity entity) {
return repository.save(entity);
}
@Override
public Integer delete(InviteFriendActivity entity) {
return repository.delete(entity);
}
@Override
public Integer update(InviteFriendActivity entity) {
return repository.update(entity);
}
@Override
public Page<InviteFriendActivity> queryPage(Page<InviteFriendActivity> page) {
return repository.queryPage(page);
}
@Override
public Integer delByActivityId(Long activityId) {
return repository.delByActivityId(activityId);
}
@Override
public InviteFriendActivity getByActivityId(Long activityId) {
return repository.getByActivityId(activityId);
}
}
|
Java
|
UTF-8
| 3,524 | 1.789063 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.jfrog.hudson.pipeline.common.types.builds;
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
import org.jfrog.hudson.pipeline.common.types.buildInfo.BuildInfo;
import org.jfrog.hudson.pipeline.common.types.deployers.CommonDeployer;
import org.jfrog.hudson.pipeline.common.types.resolvers.CommonResolver;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.jfrog.hudson.pipeline.common.Utils.appendBuildInfo;
/**
* Created by Yahav Itzhak on 26 Dec 2018.
*/
public class NpmBuild extends PackageManagerBuild {
public static final String NPM_BUILD = "npmBuild";
public static final String JAVA_ARGS = "javaArgs";
public static final String DEPLOY_ARTIFACTS = "deployArtifacts";
public NpmBuild() {
deployer = new CommonDeployer();
resolver = new CommonResolver();
}
@Whitelisted
public void install(Map<String, Object> args) {
Map<String, Object> stepVariables = prepareNpmStep(args, Arrays.asList(PATH, JAVA_ARGS, ARGS, BUILD_INFO, MODULE));
stepVariables.put(ARGS, args.get(ARGS));
// Throws CpsCallableInvocation - Must be the last line in this method
cpsScript.invokeMethod("artifactoryNpmInstall", stepVariables);
}
@Whitelisted
public void ci(Map<String, Object> args) {
Map<String, Object> stepVariables = prepareNpmStep(args, Arrays.asList(PATH, JAVA_ARGS, ARGS, BUILD_INFO, MODULE));
stepVariables.put(ARGS, args.get(ARGS));
// Throws CpsCallableInvocation - Must be the last line in this method
cpsScript.invokeMethod("artifactoryNpmCi", stepVariables);
}
@Whitelisted
public void publish(Map<String, Object> args) {
Map<String, Object> stepVariables = prepareNpmStep(args, Arrays.asList(PATH, JAVA_ARGS, BUILD_INFO, MODULE));
// Throws CpsCallableInvocation - Must be the last line in this method
cpsScript.invokeMethod("artifactoryNpmPublish", stepVariables);
}
private Map<String, Object> prepareNpmStep(Map<String, Object> args, List<String> keysAsList) {
Set<String> npmArgumentsSet = args.keySet();
if (!keysAsList.containsAll(npmArgumentsSet)) {
throw new IllegalArgumentException("Only the following arguments are allowed: " + keysAsList.toString());
}
deployer.setCpsScript(cpsScript);
Map<String, Object> stepVariables = getRunArguments((String) args.get(PATH), (BuildInfo) args.get(BUILD_INFO));
appendBuildInfo(cpsScript, stepVariables);
stepVariables.put(MODULE, args.get(MODULE));
// Added to allow java remote debugging
stepVariables.put(JAVA_ARGS, args.get(JAVA_ARGS));
return stepVariables;
}
@Whitelisted
public void resolver(Map<String, Object> resolverArguments) throws Exception {
setResolver(resolverArguments, Arrays.asList(REPO, SERVER));
}
@Whitelisted
public void deployer(Map<String, Object> deployerArguments) throws Exception {
setDeployer(deployerArguments, Arrays.asList(REPO, SERVER, DEPLOY_ARTIFACTS, INCLUDE_ENV_VARS));
}
private Map<String, Object> getRunArguments(String path, BuildInfo buildInfo) {
Map<String, Object> stepVariables = new LinkedHashMap<>();
stepVariables.put(NPM_BUILD, this);
stepVariables.put(PATH, path);
stepVariables.put(BUILD_INFO, buildInfo);
return stepVariables;
}
}
|
Python
|
UTF-8
| 6,600 | 2.734375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
from nltk import FreqDist, ConditionalFreqDist, ConditionalProbDist, \
DictionaryProbDist, DictionaryConditionalProbDist, LidstoneProbDist, \
MutableProbDist, MLEProbDist, UniformProbDist, HiddenMarkovModelTagger
from nltk.tag.hmm import _log_add
from hadooplib.mapper import MapperBase
from hadooplib.util import *
from numpy import *
# _NINF = float('-inf') # won't work on Windows
_NINF = float('-1e300')
_TEXT = 0 # index of text in a tuple
_TAG = 1 # index of tag in a tuple
class EM_Mapper(MapperBase):
"""
compute the local hmm parameters from one the input sequences
"""
def pd(self, values, samples):
"""
helper methods to get DictionaryProbDist from
a list of values
"""
d = {}
for value, item in zip(values, samples):
d[item] = value
return DictionaryProbDist(d)
def cpd(self, array, conditions, samples):
"""
helper methods to get DictionaryConditionalProbDist from
a two dimension array
"""
d = {}
for values, condition in zip(array, conditions):
d[condition] = self.pd(values, samples)
return DictionaryConditionalProbDist(d)
def read_params(self):
"""
read parameter file, initialize the hmm model
"""
params = open("hmm_parameter", 'r')
d = {}
A = {}
B = {}
for line in params:
words = line.strip().split()
# ignore blank lines and comment lines
if len(words) == 0 or line.strip()[0] == "#":
continue
if words[0] == "Pi":
d[words[1]] = float(words[2])
elif words[0] == "A":
A[(words[1], words[2])] = float(words[3])
elif words[0] == "B":
B[(words[1], words[2])] = float(words[3])
params.close()
# get initial state probability p (state)
Pi = DictionaryProbDist(d)
A_keys = A.keys()
B_keys = B.keys()
states = set()
symbols = set()
for e in A_keys:
states.add(e[0])
states.add(e[1])
for e in B_keys:
states.add(e[0])
symbols.add(e[1])
states = list(states)
states.sort()
symbols = list(symbols)
symbols.sort()
# get transition probability p(state | state)
prob_matrix = []
for condition in states:
li = []
for state in states:
li.append(A.get((condition, state), 0))
prob_matrix.append(li)
A = self.cpd(array(prob_matrix, float64), states, states)
# get emit probability p(symbol | state)
prob_matrix = []
for state in states:
li = []
for symbol in symbols:
li.append(B.get((state, symbol), 0))
prob_matrix.append(li)
B = self.cpd(array(prob_matrix, float64), states, symbols)
return symbols, states, A, B, Pi
def map(self, key, value):
"""
establish the hmm model and estimate the local
hmm parameters from the input sequences
@param key: None
@param value: input sequence
"""
symbols, states, A, B, pi = self.read_params()
N = len(states)
M = len(symbols)
symbol_dict = dict((symbols[i], i) for i in range(M))
model = HiddenMarkovModelTagger(symbols=symbols, states=states, \
transitions=A, outputs=B, priors=pi)
logprob = 0
sequence = list(value)
if not sequence:
return
# compute forward and backward probabilities
alpha = model._forward_probability(sequence)
beta = model._backward_probability(sequence)
# find the log probability of the sequence
T = len(sequence)
lpk = _log_add(*alpha[T-1, :])
logprob += lpk
# now update A and B (transition and output probabilities)
# using the alpha and beta values. Please refer to Rabiner's
# paper for details, it's too hard to explain in comments
local_A_numer = ones((N, N), float64) * _NINF
local_B_numer = ones((N, M), float64) * _NINF
local_A_denom = ones(N, float64) * _NINF
local_B_denom = ones(N, float64) * _NINF
# for each position, accumulate sums for A and B
for t in range(T):
x = sequence[t][_TEXT] #not found? FIXME
if t < T - 1:
xnext = sequence[t+1][_TEXT] #not found? FIXME
xi = symbol_dict[x]
for i in range(N):
si = states[i]
if t < T - 1:
for j in range(N):
sj = states[j]
local_A_numer[i, j] = \
_log_add(local_A_numer[i, j],
alpha[t, i] +
model._transitions[si].logprob(sj) +
model._outputs[sj].logprob(xnext) +
beta[t+1, j])
local_A_denom[i] = _log_add(local_A_denom[i],
alpha[t, i] + beta[t, i])
else:
local_B_denom[i] = _log_add(local_A_denom[i],
alpha[t, i] + beta[t, i])
local_B_numer[i, xi] = _log_add(local_B_numer[i, xi],
alpha[t, i] + beta[t, i])
for i in range(N):
self.outputcollector.collect("parameters", \
tuple2str(("Pi", states[i], pi.prob(states[i]))))
self.collect_matrix('A', local_A_numer, lpk, N, N)
self.collect_matrix('B', local_B_numer, lpk, N, M)
self.collect_matrix('A_denom', [local_A_denom], lpk, 1, N)
self.collect_matrix('B_denom', [local_B_denom], lpk, 1, N)
self.outputcollector.collect("parameters", "states " + \
tuple2str(tuple(states)))
self.outputcollector.collect("parameters", "symbols " + \
tuple2str(tuple(symbols)))
def collect_matrix(self, name, matrix, lpk, row, col):
"""
a utility function to collect the content in matrix
"""
for i in range(row):
for j in range(col):
self.outputcollector.collect("parameters", \
tuple2str((name, i, j, matrix[i][j], lpk, row, col)))
if __name__ == "__main__":
EM_Mapper().call_map()
|
C#
|
UTF-8
| 11,234 | 2.8125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace amongus.Model
{
class AmongUsModel
{
private AmongUsTable _table;
private Int32 _gameTime;
public Int32 GameTime { get { return _gameTime; } }
public AmongUsTable Table { get { return _table; } }
public Boolean IsGameOver { get { return false; } }
public event EventHandler<AmongUsModelEventArgs> GameAdvanced;
/// <summary>
/// Játék végének eseménye.
/// </summary>
public event EventHandler<AmongUsModelEventArgs> GameOver;
/// <summary>
/// Játék létrehozásának eseménye.
/// </summary>
public event EventHandler<AmongUsModelEventArgs> GameCreated;
public AmongUsModel()
{
_table = new AmongUsTable();
}
public void NewGame()
{
_table = new AmongUsTable();
_gameTime = 0;
GenerateFields();
OnGameCreated();
}
public void AdvanceTime()
{
if (IsGameOver) // ha már vége, nem folytathatjuk
return;
_gameTime++;
Step();
OnGameAdvanced();
if (_gameTime == 99) // ha lejárt az idő, jelezzük, hogy vége a játéknak
OnGameOver(false);
}
private void ImpostorWithAnotherCrewmate()
{
for (int i = 5; i < _table.positions.Count - 1; i++)
{
if (_table.positions[i].Key == _table.positions[_table.positions.Count - 1].Key && _table.positions[i].Value == _table.positions[_table.positions.Count - 1].Value)
{
_table.SetValue(_table.positions[i].Key, _table.positions[i].Value, 0);
_table.positions.RemoveAt(i);
Debug.Write("toroltem\n");
}
}
}
public void Step()
{
if (IsGameOver) // ha már vége a játéknak, nem játszhatunk
return;
Random rand = new Random();
double random = rand.NextDouble();
ImpostorWithAnotherCrewmate();
//Debug.Write(_table.positions.Count + " " + _table.positionsCompletedTasks.Count + " \n");
if (_table.positions.Count == 6 || _table.positionsCompletedTasks.Count == 5)
{
OnGameOver(true);
}
for(int i = 5; i < _table.positions.Count; i++) //key = x, value = y
{
Boolean isGoodPos = false;
while(!isGoodPos)
{
if(random <= 0.25) //bal
{
if (_table.positions[i].Value - 1 >= 0)
{
if (_table.positions.Contains(new KeyValuePair<int, int>(_table.positions[i].Key, _table.positions[i].Value - 1)) &&
_table.GetValue(_table.positions[i].Key, _table.positions[i].Value - 1) == 1 &&
_table.GetValue(_table.positions[i].Key, _table.positions[i].Value) == 3)
{
_table.positionsCompletedTasks.Add(new KeyValuePair<int, int>(_table.positions[i].Key, _table.positions[i].Value - 1));
_table.completedTasksIndex++;
}
_table.SetValue(_table.positions[i].Key, _table.positions[i].Value, 0);
_table.positions[i] = new KeyValuePair<int, int>(_table.positions[i].Key, _table.positions[i].Value - 1);
}
isGoodPos = true;
random = rand.NextDouble();
}
else if(random <= 0.5) //jobb
{
if (_table.positions[i].Value + 1 < _table.Size)
{
if (_table.positions.Contains(new KeyValuePair<int, int>(_table.positions[i].Key, _table.positions[i].Value + 1)) &&
_table.GetValue(_table.positions[i].Key, _table.positions[i].Value + 1) == 1 &&
_table.GetValue(_table.positions[i].Key, _table.positions[i].Value) == 3)
{
_table.positionsCompletedTasks.Add(new KeyValuePair<int, int>(_table.positions[i].Key, _table.positions[i].Value + 1));
_table.completedTasksIndex++;
}
_table.SetValue(_table.positions[i].Key, _table.positions[i].Value, 0);
_table.positions[i] = new KeyValuePair<int, int>(_table.positions[i].Key, _table.positions[i].Value + 1);
isGoodPos = true;
}
random = rand.NextDouble();
}
else if (random <= 0.75) // le
{
if (_table.positions[i].Key - 1 >= 0)
{
if (_table.positions.Contains(new KeyValuePair<int, int>(_table.positions[i].Key - 1, _table.positions[i].Value )) &&
_table.GetValue(_table.positions[i].Key - 1, _table.positions[i].Value) == 1 &&
_table.GetValue(_table.positions[i].Key, _table.positions[i].Value) == 3)
{
_table.positionsCompletedTasks.Add( new KeyValuePair<int, int>(_table.positions[i].Key - 1, _table.positions[i].Value));
_table.completedTasksIndex++;
}
_table.SetValue(_table.positions[i].Key, _table.positions[i].Value, 0);
_table.positions[i] = new KeyValuePair<int, int>(_table.positions[i].Key - 1, _table.positions[i].Value);
isGoodPos = true;
}
random = rand.NextDouble();
}
else // fel
{
if (_table.positions[i].Key + 1 < _table.Size)
{
if (_table.positions.Contains(new KeyValuePair<int, int>(_table.positions[i].Key + 1, _table.positions[i].Value)) &&
_table.GetValue(_table.positions[i].Key + 1, _table.positions[i].Value) == 1 &&
_table.GetValue(_table.positions[i].Key, _table.positions[i].Value) == 3)
{
_table.positionsCompletedTasks.Add( new KeyValuePair<int, int>(_table.positions[i].Key + 1, _table.positions[i].Value ));
_table.completedTasksIndex++;
}
_table.SetValue(_table.positions[i].Key, _table.positions[i].Value, 0);
_table.positions[i] = new KeyValuePair<int, int>(_table.positions[i].Key + 1, _table.positions[i].Value);
isGoodPos = true;
}
random = rand.NextDouble();
}
}
}
for (int i = 0; i < _table.positions.Count; i++)
{
if (i < 5)
{
_table.SetValue(_table.positions[i].Key, _table.positions[i].Value, 1);
}
else
{
_table.SetValue(_table.positions[i].Key, _table.positions[i].Value, 3);
}
}
for(int i = 0; i < _table.positionsCompletedTasks.Count; i++)
{
_table.SetValue(_table.positionsCompletedTasks[i].Key, _table.positionsCompletedTasks[i].Value, 2);
}
// for (int i = 0; i < _table.Size; i++)
// {
// for (int j = 0; j < _table.Size; j++)
// ezzel állítom majd be a pályán az értékeket
OnGameAdvanced();
//if (_table.IsFilled) // ha vége a játéknak, jelezzük, hogy győztünk
//{
// OnGameOver(true);
//}
}
//csak itt állítgathatok értékeket
private void GenerateFields() // itt jon a bigbrain time, mindig kell majd egy set value, 9. indexen lévő ember az impostor, 5-9 kikérem majd mindig az indexeket és odarakom aztán majd a positionoknál fogom váltogatni az értékeket nem a pályán
{
for(int i = 0; i < _table.Size; i++)
{
for(int j = 0; j < _table.Size; j++)
{
_table.SetValue(i, j, 0);
}
}
for(int i = 0; i < 5; i++) // belerakom a pozi helyekre megnézem van e benne már ugyan az az érték ha igen ujra generálom
{
Random rand = new Random();
int k = rand.Next(0, _table.Size);
int j = rand.Next(0, _table.Size);
while(_table.GetValue(k,j) != 0)
{
k = rand.Next(0, _table.Size);
j = rand.Next(0, _table.Size);
}
_table.SetValue(k, j, 1);
_table.positions.Add(new KeyValuePair<int, int>(k, j));
}
for (int i = 0; i < 5; i++)
{
Random rand = new Random();
int k = rand.Next(0, _table.Size);
int j = rand.Next(0, _table.Size);
while (_table.GetValue(k, j) != 0)
{
k = rand.Next(0, _table.Size);
j = rand.Next(0, _table.Size);
}
_table.SetValue(k, j, 3);
_table.positions.Add(new KeyValuePair<int, int>(k, j));
}
}
private void OnGameAdvanced()
{
if (GameAdvanced != null)
GameAdvanced(this, new AmongUsModelEventArgs(false,_gameTime));
}
/// <summary>
/// Játék vége eseményének kiváltása.
/// </summary>
/// <param name="isWon">Győztünk-e a játékban.</param>
private void OnGameOver(Boolean isWon)
{
if (GameOver != null)
GameOver(this, new AmongUsModelEventArgs(isWon, _gameTime));
}
/// <summary>
/// Játék létrehozás eseményének kiváltása.
/// </summary>
private void OnGameCreated()
{
if (GameCreated != null)
GameCreated(this, new AmongUsModelEventArgs(false, _gameTime));
}
}
}
|
C#
|
UTF-8
| 5,162 | 2.953125 | 3 |
[] |
no_license
|
using Mythigine;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using static AnimalsOutput.Enums;
namespace AnimalsOutput
{
class Program
{
private static GenePool dna;
private static List<Animal> animals;
private static DNAController dnacontroller = DNAController.GetSingleton();
static void Main(string[] args)
{
animals = new List<Animal>();
Gene _g;
Animal _a;
Races _r;
_r = Races.Human;
dna = new GenePool();
switch (_r)
{
case Races.Human:
_g = new Gene(typeof(HairColor), HairColor.Blonde, HairColor.Blonde);
dna.Add(_g);
_g = new Gene(typeof(SkinColor), SkinColor.Caucasian, SkinColor.Caucasian);
dna.Add(_g);
_g = new Gene(typeof(EyeColor), EyeColor.Green, EyeColor.Green);
dna.Add(_g);
break;
case Races.Dog:
/*_g = new Gene(typeof(Enums.Dog.HairColor), Enums.Dog.HairColor.Blonde.ToString(), Enums.Dog.HairColor.Blonde.ToString());
dna.Add(_g);
_g = new Gene(typeof(Enums.Dog.SkinColor), Enums.Dog.SkinColor.Axil.ToString(), Enums.Dog.SkinColor.Axil.ToString());
dna.Add(_g);
_g = new Gene(typeof(Enums.Dog.EyeColor), Enums.Dog.EyeColor.Axil.ToString(), Enums.Dog.EyeColor.Axil.ToString());
dna.Add(_g);*/
break;
}
_a = new Animal(1, _r, dna);
animals.Add(_a);
dna = new GenePool();
switch (_r)
{
case Races.Human:
_g = new Gene(typeof(HairColor), HairColor.Black, HairColor.Black);
dna.Add(_g);
_g = new Gene(typeof(SkinColor), SkinColor.Asian, SkinColor.Asian);
dna.Add(_g);
_g = new Gene(typeof(EyeColor), EyeColor.Brown, EyeColor.Brown);
dna.Add(_g);
break;
case Races.Dog:
/*_g = new Gene(typeof(Enums.Dog.HairColor), Enums.Dog.HairColor.Brunette, Enums.Dog.HairColor.Brunette);
dna.Add(_g);
_g = new Gene(typeof(Enums.Dog.SkinColor), Enums.Dog.SkinColor.Terminal.ToString(), Enums.Dog.SkinColor.Terminal.ToString());
dna.Add(_g);
_g = new Gene(typeof(Enums.Dog.EyeColor), Enums.Dog.EyeColor.Terminal.ToString(), Enums.Dog.EyeColor.Terminal.ToString());
dna.Add(_g);*/
break;
}
_a = new Animal(2, _r, dna);
animals.Add(_a);
animals.Add(new Animal(3, animals[0].Race, animals[0], animals[1]));
#region Table info
GenePool father = animals[0].GetGenes;
GenePool mother = animals[1].GetGenes;
GenePool child = animals[2].GetGenes;
Console.WriteLine(String.Format("\n|{0,5}\t\t|{1,5}\t|{2,5}\t|{3,5}\n", "Trait", animals[0].Race.ToString() + " 1", animals[1].Race.ToString() + " 2", animals[2].Race.ToString() + " Child"));
foreach (Type trait in Trait.AllTraits)
{
bool raceFound = false;
foreach (RaceAttribute r in Enums.GetAttributes<RaceAttribute>(trait))
{
if (r.Race.Equals(animals[0].Race))
{
raceFound = true;
break;
}
}
if (raceFound)
{
Gene gf = father.FindByTrait(trait);
Gene gm = mother.FindByTrait(trait);
Gene gc = child.FindByTrait(trait);
string traitAsString = Enums.GetAttribute<DescriptionAttribute>(trait).Description;
if (gf.Dominant.ToString().Length <= 6)
Console.WriteLine(String.Format("|{0,5}\t|{1,5}\t\t|{2,5}\t\t|{3,5}", traitAsString, gf.Dominant.ToString(), gm.Dominant.ToString(), gc.Dominant.ToString()));
else
Console.WriteLine(String.Format("|{0,5}\t|{1,5}\t|{2,5}\t\t|{3,5}", traitAsString, gf.Dominant.ToString(), gm.Dominant.ToString(), gc.Dominant.ToString()));
if (gf.Dominant.ToString().Length <= 6)
Console.WriteLine(String.Format("|{0,5}\t|{1,5}\t\t|{2,5}\t\t|{3,5}", traitAsString, gf.Recessive.ToString(), gm.Recessive.ToString(), gc.Recessive.ToString()));
else
Console.WriteLine(String.Format("|{0,5}\t|{1,5}\t|{2,5}\t\t|{3,5}", traitAsString, gf.Recessive.ToString(), gm.Recessive.ToString(), gc.Recessive.ToString()));
}
}
#endregion
Console.WriteLine("Press enter key to continue . . .");
Console.ReadLine();
}
}
}
|
PHP
|
UTF-8
| 1,551 | 2.546875 | 3 |
[] |
no_license
|
<?php
/**
*
* @author Complete with your name <andyouremail@debserverp4.com.ar>
*/
class Financial_Model_AccountType extends ZFModel_ParentModel {
public function __construct(array $options=null) {
parent::__construct($options);
$this->setDbTable('Financial_Model_DbTable_AccountType');
}
/**
* @var NO $id
*/
protected $id;
/**
* Set id
*/
public function setId($id) {
$this->id=$id;
return $this;
}
/**
* Get id
*/
public function getId() {
return $this->id;
}
/**
* @var NO $dateCreated
*/
protected $dateCreated;
/**
* Set dateCreated
*/
public function setDateCreated($dateCreated) {
$this->dateCreated=$dateCreated;
return $this;
}
/**
* Get dateCreated
*/
public function getDateCreated() {
return $this->dateCreated;
}
/**
* @var YES $dateUpdated
*/
protected $dateUpdated;
/**
* Set dateUpdated
*/
public function setDateUpdated($dateUpdated) {
$this->dateUpdated=$dateUpdated;
return $this;
}
/**
* Get dateUpdated
*/
public function getDateUpdated() {
return $this->dateUpdated;
}
/**
* @var NO $name
*/
protected $name;
/**
* Set name
*/
public function setName($name) {
$this->name=$name;
return $this;
}
/**
* Get name
*/
public function getName() {
return $this->name;
}
}
|
JavaScript
|
UTF-8
| 693 | 2.5625 | 3 |
[] |
no_license
|
// Contains test data
var randomNaughtyString = require('naughty-string-validator');
exports.email = (faker.internet.email()).toLowerCase();
exports.password = faker.internet.password();
exports.url = faker.internet.url();
exports.invalidPassword = faker.internet.password(4);
exports.randomNumber = faker.random.number({ min: 0, max: 99999999999999 });
exports.unicodeCharacters = '👾 🙇 💁 🙅 🙆 🙋 🙎 🙍';
exports.getNaughtyString = randomNaughtyString;
exports.name = faker.name.findName;
exports.fName = faker.name.firstName;
exports.lName = faker.name.lastName;
exports.powers = ["strength", "agility"];
exports.killerFalse = 'False';
exports.age = faker.random.number(100);
|
Java
|
UTF-8
| 3,637 | 2.046875 | 2 |
[] |
no_license
|
package com.quickblox.sample.videochat.java.activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.quickblox.sample.videochat.java.R;
import com.quickblox.sample.videochat.java.data.LocalSharePrefData;
import com.quickblox.sample.videochat.java.fragments.AppRTCIndicatorFragment1;
import com.quickblox.sample.videochat.java.fragments.AppRTCIndicatorFragment2;
import com.quickblox.sample.videochat.java.fragments.AppRTCIndicatorFragment3;
import com.quickblox.sample.videochat.java.fragments.AppRTCIndicatorFragment4;
import com.quickblox.sample.videochat.java.fragments.AppRTCIndicatorFragment5;
import com.quickblox.sample.videochat.java.fragments.AppRTCIndicatorFragment6;
import com.quickblox.sample.videochat.java.util.IOnBackPressed;
public class RAppLauncherActivity extends AppCompatActivity {
ViewPager viewPager;
private LocalSharePrefData mLocalSharedPrefData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rapp_launcher);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
viewPager=(ViewPager)findViewById(R.id.view_pager);
mLocalSharedPrefData=new LocalSharePrefData();
loadAdapter();
}
private void loadAdapter() {
if (mLocalSharedPrefData.getIsUserRegistered(RAppLauncherActivity.this)){
viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int pos) {
switch (pos) {
case 0:
return AppRTCIndicatorFragment1.newInstance(getString(R.string.title_indicator_one),getString(R.string.title_indicator_onep2));
case 1:
return AppRTCIndicatorFragment2.newInstance(getString(R.string.title_indicator_two),getString(R.string.title_indicator_twop2));
case 2:
return AppRTCIndicatorFragment3.newInstance(getString(R.string.title_indicator_three),getString(R.string.title_indicator_threep2));
case 3:
return AppRTCIndicatorFragment4.newInstance(getString(R.string.title_indicator_four),getString(R.string.title_indicator_fourp2));
case 4:
return AppRTCIndicatorFragment5.newInstance(getString(R.string.title_indicator_five),getString(R.string.title_indicator_fivep2));
case 5:
return AppRTCIndicatorFragment6.newInstance(getString(R.string.title_indicator_six),getString(R.string.title_indicator_six2));
default:
return AppRTCIndicatorFragment1.newInstance(getString(R.string.title_indicator_default),getString(R.string.title_indicator_defaultp2));
}
}
@Override
public int getCount() {
return 6;
}
}
@Override
public void onBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.main_container);
if (!(fragment instanceof IOnBackPressed) || !((IOnBackPressed) fragment).onBackPressed()) {
}
}
}
|
Python
|
UTF-8
| 1,776 | 2.75 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
from pprint import pprint
import time
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import AgglomerativeClustering
from sklearn.neighbors import kneighbors_graph
# ====================================================
# data
# ====================================================
n_samples = 1500
np.random.seed(0)
t = 1.5 * np.pi * (1 + 3 * np.random.rand(1, n_samples))
x = t * np.cos(t)
y = t * np.sin(t)
X = np.concatenate((x, y))
X += 0.7 * np.random.randn(2, n_samples)
X = X.T
plt.scatter(X[:, 0], X[:, 1])
plt.show()
knn_graph = kneighbors_graph(X, 30, include_self = False)
for connectivity in (None, knn_graph):
for n_clusters in (30, 3):
plt.figure(figsize = (10, 4))
for index, linkage in enumerate(("average", "complete", "ward", "single")):
plt.subplot(1, 4, index + 1)
# --------------------------------------------------------
# clustering
# --------------------------------------------------------
model = AgglomerativeClustering(linkage = linkage,
connectivity = connectivity,
n_clusters = n_clusters)
t0 = time.time()
model.fit(X)
elapsed_time = time.time() - t0
# --------------------------------------------------------
# plot the clustering
# --------------------------------------------------------
plt.scatter(X[:, 0], X[:, 1], c = model.labels_, cmap = plt.cm.nipy_spectral)
plt.title("linkage=%s\n(time %.2fs)" % (linkage, elapsed_time),
fontdict = dict(verticalalignment = "top"))
# plt.axis("euqal")
plt.axis("off")
plt.subplots_adjust(bottom = 0, top = 0.89, wspace = 0, left = 0, right = 1)
plt.suptitle("n_cluster=%i, connectivity=%r" % (n_clusters, connectivity is not None), size = 17)
plt.show()
|
Java
|
UTF-8
| 3,466 | 2.421875 | 2 |
[] |
no_license
|
package com.example.triary_app;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class DeleteDetailAction extends ListActivity {
/** Items entered by the user is stored in this ArrayList variable */
/** Declaring an ArrayAdapter to set items to ListView */
ArrayAdapter adapter;
private setTableDetaillsOfBook setTable;
private Cursor cursor;
private List list;
private String id_book;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().hide();
/** Setting a custom layout for the list activity */
setContentView(R.layout.activity_deletedetail);
setTable = new setTableDetaillsOfBook(this);
readAllBook();
getActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
// hide();
int actionBarTitleId = Resources.getSystem().getIdentifier(
"action_bar_title", "id", "android");
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/Book_Akhanake.ttf");
if (actionBarTitleId > 0) {
TextView title = (TextView) findViewById(actionBarTitleId);
if (title != null) {
title.setTypeface(tf);
}
}
/** Reference to the delete button of the layout main.xml */
Button btnDel = (Button) findViewById(R.id.btnDel);
/** Defining the ArrayAdapter to set items to ListView */
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, list);
/** Defining a click event listener for the button "Delete" */
OnClickListener listenerDel = new OnClickListener() {
@Override
public void onClick(View v) {
/** Getting the checked items from the listview */
SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
int itemCount = getListView().getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
setTable.deleteDetail(list.get(i).toString());
adapter.remove(list.get(i));
}
}
checkedItemPositions.clear();
adapter.notifyDataSetChanged();
}
};
/** Setting the event listener for the delete button */
btnDel.setOnClickListener(listenerDel);
/** Setting the adapter to the ListView */
setListAdapter(adapter);
}
public void readAllBook() {
id_book = getIntent().getStringExtra("id");
list = new ArrayList();
cursor = setTable.readDetail(id_book);
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(3));
} while (cursor.moveToNext());
}
}
}
|
Markdown
|
UTF-8
| 2,453 | 2.75 | 3 |
[] |
no_license
|
Secdrop
=======
A secure, easy-to-use, iOS-compatible drop box that makes use of both symmetric (first stage is AES-256, encrypted in-browser) and asymmetric encryption (GPG public-key for second stage, performed on server side).
As first-stage encryption is performed within the browser via CryptoJS (256-bit AES), an SSL server isn't required. However, it is _highly_ recommended.
Requirements
============
* `client/`
* CryptoJS <http://code.google.com/p/crypto-js/>
* jQuery >= 1.9.1 <http://jquery.com>
* Bootstrap <http://twitter.github.com/bootstrap/>
* `server/` and `dec/`
* GPG (or PGP) <http://www.gnupg.org>
* `dec/`
* OpenSSL (command-line tool) <http://www.openssl.org>
Recommended
===========
* An HTTPS server
Source hierarchy
================
* `client/` - The client-side implementation of the UI, first-stage encryption and file-send functionality
* `server/` - Server-side scripts for accepting uploads and performing second-stage asymmetric encryption.
* `dec/` - The tools used to decrypt dropped files. *__Never__* use this on the server-side unless you *__fully__* trust your server!
Installation & Use
====================
* `client/`
* Put these files in your __DocumentRoot__ or somewhere publicly-viewable for your HTTPS server.
* Install client requirements (noted above) into the *js/* directory.
* `server/`
* Ensure GPG is available at */usr/bin/gpg* or set the proper path via the sec.cgi config (.sec.cgi.conf, key __GPGCLIPath__).
* Configure the output path for dropped files via config key __OutputDirectory__. Default is */tmp/secdrop.output*. __This path must be writable for the user executing your CGI process__.
* Configure the recipient GPG public key via config key __GPGRecipient__. This keypair must be available to the recipient using *dec/secdl.pl*.
* __Be certain__ that you've configured your chosen web server to disallow access to the config file as well as the path used for __OutputDirectory__.
* `dec/`
* __Only use these scripts for decryption on a trusted machine.__
* `dec/secdl.pl arg1 arg2` decrypts files in *arg1* into directory *arg2*. (Presumably the files are sourced from __OutputDirectory__ in the server config. I simply use *scp* to retrieve files.)
* You will be prompted for the password the original sender used to encrypt via the web UI.
* Second-stage decryption will be done with the GPG keypair for the recipient specified in the server config.
|
C++
|
UTF-8
| 893 | 2.890625 | 3 |
[] |
no_license
|
#ifndef ALGORITHM_PRIORITY_QUEUE_TEST_H
#define ALGORITHM_PRIORITY_QUEUE_TEST_H
#include <iostream>
//#include "../../algorithm/queue/priority_queue_based_on_heap.h"
#include "../../algorithm/queue/priority_queue_based_on_vector.h"
namespace myalgorithm {
using std::cout;
using std::endl;
void testPriorityQueue()
{
PriorityQueue<int> pq;
cout << "Initial pq size: " << pq.size() << endl;
cout << endl;
pq.push(3);
pq.push(10);
cout << "pq size: " << pq.size() << endl;
cout << endl;
pq.push(15);
cout << "pq top: " << pq.top() << endl;
cout << endl;
while (!pq.empty()) {
cout << "pq pop: " << pq.top() << endl;
pq.pop();
}
cout << endl;
cout << "pq size: " << pq.size() << endl;
}
}
#endif // ALGORITHM_PRIORITY_QUEUE_TEST_H
|
Go
|
UTF-8
| 553 | 3.203125 | 3 |
[] |
no_license
|
package main
import "fmt"
func paincRoutine() {
fmt.Println("-> start paincRoutine")
error := fmt.Errorf("custom")
// panic will break a application, is like throw Error in other lang
panic(error)
}
func rescueRoutine() {
fmt.Println("-> start rescueRoutine")
rescued := recover()
if rescued != nil {
fmt.Println("rescued", rescued)
}
fmt.Println("-> end rescueRoutine")
}
func main() {
// defer schedule functin to run after caller
defer rescueRoutine()
fmt.Println("-> start main")
paincRoutine()
fmt.Println("-> end main")
}
|
Java
|
UTF-8
| 9,595 | 1.953125 | 2 |
[] |
no_license
|
package com.google.firebase.messaging;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import com.google.android.gms.common.internal.Preconditions;
import com.google.android.gms.internal.firebase_messaging.zzk;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import java.io.Closeable;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.Executor;
final class h
implements Closeable
{
private final URL a;
private Task<Bitmap> b;
private volatile InputStream c;
private h(URL paramURL)
{
this.a = paramURL;
}
public static h a(String paramString)
{
if (TextUtils.isEmpty(paramString))
return null;
String str1;
try
{
h localh = new h(new URL(paramString));
return localh;
}
catch (MalformedURLException localMalformedURLException)
{
str1 = String.valueOf(paramString);
if (str1.length() == 0);
}
for (String str2 = "Not downloading image, bad URL: ".concat(str1); ; str2 = new String("Not downloading image, bad URL: "))
{
Log.w("FirebaseMessaging", str2);
return null;
}
}
public final Task<Bitmap> a()
{
return (Task)Preconditions.checkNotNull(this.b);
}
public final void a(Executor paramExecutor)
{
this.b = Tasks.call(paramExecutor, new g(this));
}
// ERROR //
public final Bitmap b()
throws java.io.IOException
{
// Byte code:
// 0: aload_0
// 1: getfield 20 com/google/firebase/messaging/h:a Ljava/net/URL;
// 4: invokestatic 42 java/lang/String:valueOf (Ljava/lang/Object;)Ljava/lang/String;
// 7: astore_1
// 8: ldc 54
// 10: new 103 java/lang/StringBuilder
// 13: dup
// 14: bipush 22
// 16: aload_1
// 17: invokestatic 42 java/lang/String:valueOf (Ljava/lang/Object;)Ljava/lang/String;
// 20: invokevirtual 46 java/lang/String:length ()I
// 23: iadd
// 24: invokespecial 106 java/lang/StringBuilder:<init> (I)V
// 27: ldc 108
// 29: invokevirtual 112 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 32: aload_1
// 33: invokevirtual 112 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 36: invokevirtual 116 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 39: invokestatic 119 android/util/Log:i (Ljava/lang/String;Ljava/lang/String;)I
// 42: pop
// 43: aload_0
// 44: getfield 20 com/google/firebase/messaging/h:a Ljava/net/URL;
// 47: invokevirtual 123 java/net/URL:openConnection ()Ljava/net/URLConnection;
// 50: invokevirtual 129 java/net/URLConnection:getInputStream ()Ljava/io/InputStream;
// 53: astore 6
// 55: aload 6
// 57: ldc2_w 130
// 60: invokestatic 136 com/google/android/gms/internal/firebase_messaging/zzj:zza (Ljava/io/InputStream;J)Ljava/io/InputStream;
// 63: astore 11
// 65: aload_0
// 66: aload 6
// 68: putfield 138 com/google/firebase/messaging/h:c Ljava/io/InputStream;
// 71: aload 11
// 73: invokestatic 144 android/graphics/BitmapFactory:decodeStream (Ljava/io/InputStream;)Landroid/graphics/Bitmap;
// 76: astore 16
// 78: aload 16
// 80: ifnonnull +167 -> 247
// 83: aload_0
// 84: getfield 20 com/google/firebase/messaging/h:a Ljava/net/URL;
// 87: invokestatic 42 java/lang/String:valueOf (Ljava/lang/Object;)Ljava/lang/String;
// 90: astore 17
// 92: new 103 java/lang/StringBuilder
// 95: dup
// 96: bipush 24
// 98: aload 17
// 100: invokestatic 42 java/lang/String:valueOf (Ljava/lang/Object;)Ljava/lang/String;
// 103: invokevirtual 46 java/lang/String:length ()I
// 106: iadd
// 107: invokespecial 106 java/lang/StringBuilder:<init> (I)V
// 110: ldc 146
// 112: invokevirtual 112 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 115: aload 17
// 117: invokevirtual 112 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 120: invokevirtual 116 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 123: astore 18
// 125: ldc 54
// 127: aload 18
// 129: invokestatic 60 android/util/Log:w (Ljava/lang/String;Ljava/lang/String;)I
// 132: pop
// 133: new 101 java/io/IOException
// 136: dup
// 137: aload 18
// 139: invokespecial 147 java/io/IOException:<init> (Ljava/lang/String;)V
// 142: athrow
// 143: astore 14
// 145: aload 14
// 147: athrow
// 148: astore 15
// 150: aload 14
// 152: astore 13
// 154: aload 15
// 156: astore 12
// 158: aload 13
// 160: aload 11
// 162: invokestatic 149 com/google/firebase/messaging/h:a (Ljava/lang/Throwable;Ljava/io/InputStream;)V
// 165: aload 12
// 167: athrow
// 168: astore 9
// 170: aload 9
// 172: athrow
// 173: astore 10
// 175: aload 9
// 177: astore 8
// 179: aload 10
// 181: astore 7
// 183: aload 6
// 185: ifnull +10 -> 195
// 188: aload 8
// 190: aload 6
// 192: invokestatic 149 com/google/firebase/messaging/h:a (Ljava/lang/Throwable;Ljava/io/InputStream;)V
// 195: aload 7
// 197: athrow
// 198: astore_3
// 199: aload_0
// 200: getfield 20 com/google/firebase/messaging/h:a Ljava/net/URL;
// 203: invokestatic 42 java/lang/String:valueOf (Ljava/lang/Object;)Ljava/lang/String;
// 206: astore 4
// 208: ldc 54
// 210: new 103 java/lang/StringBuilder
// 213: dup
// 214: bipush 26
// 216: aload 4
// 218: invokestatic 42 java/lang/String:valueOf (Ljava/lang/Object;)Ljava/lang/String;
// 221: invokevirtual 46 java/lang/String:length ()I
// 224: iadd
// 225: invokespecial 106 java/lang/StringBuilder:<init> (I)V
// 228: ldc 151
// 230: invokevirtual 112 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 233: aload 4
// 235: invokevirtual 112 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 238: invokevirtual 116 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 241: invokestatic 60 android/util/Log:w (Ljava/lang/String;Ljava/lang/String;)I
// 244: pop
// 245: aload_3
// 246: athrow
// 247: ldc 54
// 249: iconst_3
// 250: invokestatic 155 android/util/Log:isLoggable (Ljava/lang/String;I)Z
// 253: ifeq +49 -> 302
// 256: aload_0
// 257: getfield 20 com/google/firebase/messaging/h:a Ljava/net/URL;
// 260: invokestatic 42 java/lang/String:valueOf (Ljava/lang/Object;)Ljava/lang/String;
// 263: astore 20
// 265: ldc 54
// 267: new 103 java/lang/StringBuilder
// 270: dup
// 271: bipush 31
// 273: aload 20
// 275: invokestatic 42 java/lang/String:valueOf (Ljava/lang/Object;)Ljava/lang/String;
// 278: invokevirtual 46 java/lang/String:length ()I
// 281: iadd
// 282: invokespecial 106 java/lang/StringBuilder:<init> (I)V
// 285: ldc 157
// 287: invokevirtual 112 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 290: aload 20
// 292: invokevirtual 112 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 295: invokevirtual 116 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 298: invokestatic 160 android/util/Log:d (Ljava/lang/String;Ljava/lang/String;)I
// 301: pop
// 302: aconst_null
// 303: aload 11
// 305: invokestatic 149 com/google/firebase/messaging/h:a (Ljava/lang/Throwable;Ljava/io/InputStream;)V
// 308: aload 6
// 310: ifnull +9 -> 319
// 313: aconst_null
// 314: aload 6
// 316: invokestatic 149 com/google/firebase/messaging/h:a (Ljava/lang/Throwable;Ljava/io/InputStream;)V
// 319: aload 16
// 321: areturn
// 322: astore 7
// 324: aconst_null
// 325: astore 8
// 327: goto -144 -> 183
// 330: astore 12
// 332: aconst_null
// 333: astore 13
// 335: goto -177 -> 158
//
// Exception table:
// from to target type
// 65 78 143 java/lang/Throwable
// 83 143 143 java/lang/Throwable
// 247 302 143 java/lang/Throwable
// 145 148 148 finally
// 55 65 168 java/lang/Throwable
// 158 168 168 java/lang/Throwable
// 302 308 168 java/lang/Throwable
// 170 173 173 finally
// 43 55 198 java/io/IOException
// 188 195 198 java/io/IOException
// 195 198 198 java/io/IOException
// 313 319 198 java/io/IOException
// 55 65 322 finally
// 158 168 322 finally
// 302 308 322 finally
// 65 78 330 finally
// 83 143 330 finally
// 247 302 330 finally
}
public final void close()
{
zzk.zza(this.c);
}
}
/* Location: E:\Study\Tools\apktool2_2\dex2jar-0.0.9.15\classes_viber_2_dex2jar.jar
* Qualified Name: com.google.firebase.messaging.h
* JD-Core Version: 0.6.2
*/
|
JavaScript
|
UTF-8
| 12,888 | 2.953125 | 3 |
[] |
no_license
|
//GLOBAL VARIABLES-----------------------------------------
//Require modules and constants
//Discord.js client module and instance.
const Discord = require('discord.js');
//Fs required for managing decoupled files.
const fs = require('fs');
//Requiring the module to manipulate arrays more easily.
const arrayMove = require('array-move');
//Token and API configurations.
const { API_KEY, AUTH_TOKEN } = require('./config');
//Axios instance and configurating the external API's endpoint.
const axios = require('axios');
//Youtube Downloader.
const ytdl = require('ytdl-core');
//Instance of the discord client module.
const beatBot = new Discord.Client();
//Utilities module.
const beatBotUtils = require('./commands/utils');
//Song queue.
const queue = new Map();
beatBot.prefix = "&";
const commandFiles = fs.readdirSync('./commands');
const commands = [];
//End Require modules and constants.
//Global vars when checking certain statuses.
var isRepeating = false;
var currentYouTubeVideoList = [];
//End global vars.
for (let i = 0; i < commandFiles.length; i++) {
commands.push(require(`./commands/${commandFiles[i]}`));
}
beatBot.login(AUTH_TOKEN);
commands.forEach((command) => {
beatBot.on('message', (msg) => {
if(msg.content.startsWith(`${beatBot.prefix}${command.name}`) && !msg.author.bot) {
switch (command.name) {
case "help":
command.execute(msg, commands, beatBot.prefix);
break;
default:
command.execute(msg, beatBot, queue);
break;
}
}
});
});
//---------------------------------------------------------------
/* Voice channel and video play commands will stay in the same bot.js file
because they need a global variable context for the Map queue to work properly. */
beatBot.on('message', msg => {
if (!msg.content.startsWith(`${beatBot.prefix}`)) return;
msg.content.trim();
let startsWith = msg.content.split(' ')[0];
const serverQueue = queue.get(msg.guild.id);
switch (startsWith) {
case `${beatBot.prefix}play`:
const args = msg.content.split(' ');
if (!args[1]) return msg.reply('you must specify a link or search for me to play a video!');
executePlay(msg, serverQueue);
break;
case `${beatBot.prefix}skip`:
skip(msg, serverQueue);
break;
case `${beatBot.prefix}pause`:
pause(msg, serverQueue);
break;
case `${beatBot.prefix}resume`:
resume(msg, serverQueue);
break;
case `${beatBot.prefix}stop`:
stop(msg, serverQueue);
break;
case `${beatBot.prefix}nowplaying`:
nowPlaying(msg, serverQueue);
break;
case `${beatBot.prefix}queue`:
checkCurrentQueue(msg, serverQueue);
break;
case `${beatBot.prefix}repeat`:
repeatCurrentSong(msg, serverQueue);
break;
case `${beatBot.prefix}next`:
moveItemToFirstInQueue(msg, serverQueue);
break;
default:
break;
}
});
async function executePlay(msg, serverQueue) {
const args = msg.content.split(' ');
var songInfo = {};
const voiceChannel = msg.member.voiceChannel;
if (!voiceChannel) return msg.reply('you need to be in a voice channel to play a video.');
const permissions = voiceChannel.permissionsFor(msg.client.user);
if (!permissions.has('CONNECT') || !permissions.has('SPEAK')) {
return msg.reply('I do not have the permission to speak or join the current voice channel.');
}
try {
if (args[1].includes('https://'))
songInfo = await ytdl.getInfo(args[1]);
else {
let embedSearchResultsList = new Discord.RichEmbed()
.setColor('#10B631')
.setTitle('These are the videos I found!')
.setDescription("Take a look at the videos I found and choose one by typing it's index number!");
args.shift();
//The YouTube API only accepts the space characters as '+' on it's query parameters
//and the promise receives two functions in case something goes wrong on the API call.
await searchForYoutubeVideo(msg, args.join('+')).then((response) => { response }, (error) => { console.log(beatBotUtils.treatErrorMessage(error)) });
currentYouTubeVideoList.forEach((item) => {
embedSearchResultsList.addField(`${currentYouTubeVideoList.indexOf(item) + 1} - ${item.snippet.title}`, "----------------");
});
await msg.channel.send(embedSearchResultsList).then(async () => {
await msg.channel.awaitMessages(message => message.author.id === msg.author.id, { time: 10000 }).then(async collected => {
let videoLink = currentYouTubeVideoList[collected.first().content - 1].id.videoId;
songInfo = await ytdl.getInfo(`https://youtube.com/watch?v=${videoLink}`);
})
.catch((promiseRejection) => {
msg.channel.send(`Couldn't find the requested video on the list because I bumped into the following error: **${beatBotUtils.treatErrorMessage(promiseRejection)}**`);
return;
});
});
}
} catch (error) {
console.error(beatBotUtils.treatErrorMessage(error));
msg.channel.send(`The requested video cannot be played because I bumped into the following error: "${beatBotUtils.treatErrorMessage(error)}"`);
return;
}
if (songInfo.title && songInfo.video_url) {
const song = {
title: songInfo.title,
url: songInfo.video_url,
};
//It checks if serverQueue doesn't have an undefined or null value and checks if it has songs in its queue.
if (!serverQueue || serverQueue.songs.length === 0) {
const queueConstruct = {
textChannel: msg.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 5,
playing: true
};
queue.set(msg.guild.id, queueConstruct);
queueConstruct.songs.push(song);
try {
var connection = await voiceChannel.join();
queueConstruct.connection = connection;
msg.channel.send(`Now playing: **${song.title}**`);
if (queueConstruct.songs.length > 0) {
play(msg.guild, queueConstruct.songs[0]);
} else {
await msg.guild.voiceConnection.channel.leave();
msg.reply('Leaving channel!');
}
} catch (err) {
queue.delete(msg.guild.id);
console.log(beatBotUtils.treatErrorMessage(err));
}
} else {
await msg.channel.send(`The following video has been added to the queue: **${song.title}**`);
serverQueue.songs.push(song);
}
}
}
async function skip(msg, serverQueue) {
if (!msg.member.voiceChannel) return msg.reply('you have to be in a voice channel to stop the queue!');
if (!serverQueue) return msg.reply('there is no video I can skip.');
try {
isRepeating = false;
await serverQueue.connection.dispatcher.end();
await msg.reply(`video skipped!`);
} catch (e) {
console.error(beatBotUtils.treatErrorMessage(error));
serverQueue.songs.shift();
}
}
async function pause(msg, serverQueue) {
if (!msg.member.voiceChannel) return msg.reply('you have to be in a voice channel.');
if (!serverQueue) return msg.reply('there is no video for me to pause.');
await serverQueue.connection.dispatcher.pause();
msg.reply('video paused.');
}
async function resume(msg, serverQueue) {
if (!msg.member.voiceChannel) return msg.reply('you have to be in a voice channel.');
if (!serverQueue) return msg.reply('there is no video for me to resume.');
await serverQueue.connection.dispatcher.resume();
msg.reply('video resumed.');
}
async function stop(msg, serverQueue) {
if (!serverQueue || (serverQueue && serverQueue.songs.length === 0)) return msg.reply("there are no songs in queue for me to clean and stop it.");
if (!msg.member.voiceChannel) return msg.reply('you have to be in a voice channel to stop the queue!');
serverQueue.songs = [];
await serverQueue.connection.dispatcher.end();
msg.reply('queue stopped and cleaned.');
}
async function nowPlaying(msg, serverQueue) {
if (serverQueue && serverQueue.songs.length > 0) {
await msg.channel.send(`Now playing: **${serverQueue.songs[0].title}**`);
} else {
await msg.channel.send("There is nothing playing right now.");
}
}
async function checkCurrentQueue(msg, serverQueue) {
try {
if (!serverQueue || serverQueue.songs.length === 0) {
return msg.reply('the queue is currently empty!');
}
let embedMessage = new Discord.RichEmbed()
.setTitle('Songs in queue!')
.setColor('#10B631')
.setDescription('The current video queue!');
let count = 1;
await serverQueue.songs.forEach((item) => {
embedMessage.addField(`${count} - **${item.title}**`, "----------------");
count++;
});
msg.channel.send(embedMessage);
}
catch (e) {
console.log(beatBotUtils.treatErrorMessage(e));
}
}
async function repeatCurrentSong(msg, serverQueue) {
if (serverQueue && serverQueue.songs.length > 0) {
if (!isRepeating) {
isRepeating = true;
await msg.reply("repeating the current song.");
} else {
isRepeating = false;
await msg.reply("returned to the normal queue.");
}
} else {
await msg.reply("there is no song playing for me to repeat.");
}
}
async function searchForYoutubeVideo(msg, search) {
await axios.default.get('https://www.googleapis.com/youtube/v3/search', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
params: {
key: API_KEY,
part: 'snippet',
type: 'video',
maxResults: 10,
q: search
}
}).then(async (res) => {
currentYouTubeVideoList = await res.data.items;
}).catch((e) => {
console.log(beatBotUtils.treatErrorMessage(e));
return beatBotUtils.treatErrorMessage(e);
});
}
async function moveItemToFirstInQueue(msg, serverQueue) {
let embedMessage = new Discord.RichEmbed()
.setTitle('Songs in queue!')
.setColor('#10B631')
.setDescription('The current video queue. Choose a song for me to prioritize!');
if (!serverQueue || serverQueue.songs.length < 2) {
return msg.reply("I can't move the video you requested because the queue is empty, has only one song to the played or the requested video does not exist in the queue.");
}
let count = 1;
await serverQueue.songs.forEach((item) => {
embedMessage.addField(`${count} - **${item.title}**`, "----------------");
count++;
});
await msg.channel.send(embedMessage).then(async () => {
await msg.channel.awaitMessages(message => message.author.id === msg.author.id, { time: 10000 }).then(async collected => {
arrayMove.mutate(serverQueue.songs, collected.first().content - 1, 1);
msg.reply('the requested video has been moved to the top of the list and is going to be played next!');
})
.catch((error) => {
msg.channel.send(`Couldn't find the requested video on the list because I bumped into the following error: **${beatBotUtils.treatErrorMessage(error)}**`);
});
});
}
async function play(guild, song) {
const serverQueue = await queue.get(guild.id);
if (!song) {
serverQueue.voiceChannel.leave();
queue.delete(guild.id);
return;
}
const dispatcher = await serverQueue.voiceChannel.connection.playStream(ytdl(song.url, { highWaterMark: 1<<25, quality: 'highestaudio' }))
.on('end', () => {
if (!isRepeating)
serverQueue.songs.shift();
if (serverQueue.songs.length > 0) {
play(guild, serverQueue.songs[0]);
} else {
guild.voiceConnection.channel.leave();
}
})
.on('error', error => {
console.log(beatBotUtils.treatErrorMessage(error));
});
dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
}
|
Go
|
UTF-8
| 1,181 | 3.34375 | 3 |
[] |
no_license
|
package day05
import (
"fmt"
"sort"
"github.com/nktori/AdventOfCode2020/utils"
)
func Solve() {
utils.PrintDay(5, "Binary Boarding")
input := utils.ParseStrings("/inputs/day05/day05.txt")
fmt.Println("Problem 1:", problem1(input))
fmt.Println("Problem 2:", problem2(input))
}
func problem1(input []string) int {
max := 0
for _, b := range input {
max = utils.MaxInt(max, getBoardingId(b))
}
return max
}
func problem2(input []string) int {
ids := make([]int, len(input))
for i, b := range input {
ids[i] = getBoardingId(b)
}
sort.Ints(ids)
for i := 0; i < len(ids)-1; i++ {
if ids[i+1]-ids[i] == 2 {
return ids[i] + 1
}
}
panic("Couldn't find boarding pass")
}
func getBoardingId(pattern string) int {
minRow, maxRow := 0, 127
minCol, maxCol := 0, 7
for _, rune := range pattern {
switch rune {
case 'F':
maxRow = minRow + ((maxRow - minRow) / 2)
case 'B':
minRow = maxRow - ((maxRow - minRow) / 2)
case 'L':
maxCol = minCol + ((maxCol - minCol) / 2)
case 'R':
minCol = maxCol - ((maxCol - minCol) / 2)
}
}
if minCol == maxCol && minRow == maxRow {
return (minRow * 8) + minCol
}
panic("Boarding pass invalid")
}
|
JavaScript
|
UTF-8
| 9,160 | 2.84375 | 3 |
[] |
no_license
|
"use strict";
// This shows the first time a user signs in
// It steps through the sign up process
// to get user's profile info
import React from 'react';
import {View, ScrollView, Text, Image, Linking} from 'react-native';
// import {
// Step,
// Stepper,
// StepLabel,
// } from 'material-ui/Stepper';
// import RaisedButton from 'material-ui/RaisedButton';
// import FlatButton from 'material-ui/FlatButton';
// import MyTheme from '../theme/theme.js';
// import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
// import getMuiTheme from 'material-ui/styles/getMuiTheme';
// import TextField from 'material-ui/TextField';
import { findUser, updateUser } from '../services/userServices';
// import { hashHistory } from 'react-router';
// const rValidImage = /^((https?|ftp):)?\/\/.*(jpeg|jpg|png|gif|bmp)$/i
// const isValidImage = function(url) {
// return url.match(rValidImage)
// };
// Validation function for each step of signup process
// Values param is the form name currently being validated
// Step 0 is user profile, step 1 is dog profile
const validate = (values, step) => {
const errors = {};
var requiredFields = [];
const fields = [ 'firstname', 'lastname', 'loc', 'dogname', 'dogBreed', 'dogAge', 'picLink' ];
if (step === 0) {
requiredFields = fields.slice(0, 3);
requiredFields.forEach(field => {
if (!values[field].value) {
errors[field] = 'Required'
}
})
} else {
requiredFields = fields.slice(3);
requiredFields.forEach(field => {
if (!values[field].value) {
errors[field] = 'Required';
}
})
if (isNaN(parseInt(values.dogAge.value))) {
errors.dogAge = 'Please enter a number'
}
// if (!isValidImage(values.picLink.value)) {
// errors.picLink = 'Invalid Url'
// }
}
return errors
}
class ProfileCreation extends React.Component {
// Keeps all user info in state
constructor(props) {
super(props)
this.state = {
finished: false,
stepIndex: 0,
firstname: "",
lastname: "",
loc: "",
dogname: "",
dogBreed: "",
dogAge: "",
picLink:"",
errorText: {}
}
this.handleNext = this.handleNext.bind(this);
this.handlePrev = this.handlePrev.bind(this);
}
// Waits until new user info is saved to DataBase, then pulls
// available info to pre-populate sign up form
// Currently only first and last name are available
// On every sign up
componentDidMount() {
setTimeout(() => {
// User services function, searches by user ID
console.log('finduser: ',findUser(this.props.profile.userId));
findUser(this.props.profile.userId)
.then(user => console.log(user))
.then((user) => {
this.setState({"firstname": user.firstname});
this.setState({"lastname": user.lastname})
this.setState({"loc": user.loc || ""});
this.setState({"dogname": user.dogname || ""});
this.setState({"dogBreed": user.dogBreed || ""});
this.setState({"dogAge": user.dogAge || ""});
this.setState({"picLink": user.picLink || ""});
})
}, 1000)
}
// Updates State to match user input
handleChange(prop, event) {
let change = {};
change[prop] = event.target.value
this.setState(change);
}
// Does error checking on form iput, and either displays error message,
// or updates user in DB and redirects to users page after step 1 is complete
handleSubmit() {
var errors = {};
if (this.state.stepIndex === 1) {
errors = validate(dogProfile, 1);
} else {
errors = validate(ownerProfile, 0);
}
if (Object.keys(errors).length === 0) {
this.handleNext();
if (this.state.stepIndex === 1) {
updateUser(this.state)
.then(function (user) {
hashHistory.push('/users')
});
}
}
this.setState({"errorText": errors});
console.log(this.state);
}
// Steps to next part of sign up form
handleNext() {
var self = this;
this.setState({
stepIndex: self.state.stepIndex + 1,
finished: self.state.stepIndex >= 1,
});
}
// Goes backwards on sign up form
handlePrev(){
var self = this;
if (this.state.stepIndex > 0) {
this.setState({stepIndex: self.state.stepIndex - 1});
}
}
// Material ui - info for step form with 2 steps (user info and dog info)
getStepContent(stepIndex) {
switch (stepIndex) {
case 0:
return (
<form name="ownerProfile">
<TextField
hintText="First Name"
floatingLabelText="First Name"
value = {this.state.firstname}
onChange = {this.handleChange.bind(this, 'firstname')}
name = "firstname"
errorText = {this.state.errorText.firstname}
/><br />
<TextField
hintText="Last Name"
floatingLabelText="Last Name"
value = {this.state.lastname}
onChange = {this.handleChange.bind(this, 'lastname')}
name = "lastname"
errorText = {this.state.errorText.lastname}
/><br />
<TextField
hintText="Location"
floatingLabelText="Location"
value = {this.state.loc}
onChange = {this.handleChange.bind(this, 'loc')}
name = "loc"
errorText = {this.state.errorText.loc}
/><br />
</form>
)
case 1:
return (
<form name="dogProfile">
<TextField
hintText="Dog Name"
floatingLabelText="Dog Name"
value = {this.state.dogname}
onChange = {this.handleChange.bind(this, 'dogname')}
name = "dogname"
errorText = {this.state.errorText.dogname}
/><br />
<TextField
hintText="Dog Breed"
floatingLabelText="Dog Breed"
value = {this.state.dogBreed}
onChange = {this.handleChange.bind(this, 'dogBreed')}
name = "dogBreed"
errorText = {this.state.errorText.dogBreed}
/><br />
<TextField
hintText="Dog Age"
floatingLabelText="Dog Age"
value = {this.state.dogAge}
onChange = {this.handleChange.bind(this, 'dogAge')}
name = "dogAge"
errorText = {this.state.errorText.dogAge}
/><br />
<TextField
hintText="Dog Profile Pic"
floatingLabelText="Dog Profile Pic"
value = {this.state.picLink}
onChange = {this.handleChange.bind(this, 'picLink')}
name = "picLink"
errorText = {this.state.errorText.picLink}
/><br />
</form>
)
default:
return '';
}
}
// Renders current step of form, or blank if form is complete
// and user is being redirected
// <MuiThemeProvider muiTheme={getMuiTheme(MyTheme)}>
//GOES INSIDE THE FIRST VIEW
// <Stepper activeStep={stepIndex}>
// <Step>
// <StepLabel>Tell us more about you</StepLabel>
// </Step>
// <Step>
// <StepLabel>Tell us more about your best friend</StepLabel>
// </Step>
// </Stepper>
// {finished ? ("") : (
// <FlatButton
// label="Back"
// disabled={stepIndex === 0}
// onTouchTap={this.handlePrev}
// style={{marginRight: 12}}
// />
// <RaisedButton
// label={stepIndex === 2 ? 'Finish' : 'Next'}
// secondary={true}
// onTouchTap={()=>{
// this.handleSubmit();
// }}
// />
// )}
// </MuiThemeProvider>
render() {
console.log('the profile creation page');
const {finished, stepIndex} = this.state;
// const contentStyle = {margin: '0 16px'};
return (
<View>
<View>
<View>
<View>
<Text>this is a test view of profile creation</Text>
<Text>this is a test view of profile creation</Text>
<Text>this is a test view of profile creation</Text>
<Text>this is a test view of profile creation</Text>
<Text>this is a test view of profile creation</Text>
<Text>this is a test view of profile creation</Text>
<Text>this is a test view of profile creation</Text>
<Text>this is a test view of profile creation</Text>
<Text>this is a test view of profile creation</Text>
<Text>this is a test view of profile creation</Text>
<Text>this is a test view of profile creation</Text>
<Text>this is a test view of profile creation</Text>
<Text>this is a test view of profile creation</Text>
</View>
<View>
</View>
</View>
</View>
</View>
);
}
}
module.exports = ProfileCreation
|
Python
|
UTF-8
| 3,151 | 2.59375 | 3 |
[] |
no_license
|
from result_module import ResultModule
import unittest
import time
list_lengths_map = [{'au': 1, 'bi': 2, 'ceu': 2, 'cký': 3, 'dem': 3, 'do': 2, 'fa': 2, 'gi': 2, 'je': 2, 'jo': 2,
'lo': 2, 'ma': 2, 'mí': 2, 'na': 2, 'ne': 2, 'o': 1, 'po': 2, 'pou': 2, 'rma': 3, 'sex': 4,
'sm': 2, 'sro': 3, 'ti': 2, 'to': 2, 'tý': 2, 'u': 1, 'ur': 2, 'vl': 2, 'vě': 3, 'ze': 2,
'či': 2, 'zpa': 3, 'žil': 3},
{'wro': 3, 'bl': 2, 'sněh': 3},
{'у': 1, 'кра': 3, 'їн': 3, 'сько': 3, 'гож': 3},
{'rž': 2},
{'ma': 2, 'ria': 3}]
list_frequency_map = [{'au': 1, 'bi': 1, 'ceu': 1, 'cký': 2, 'dem': 1, 'do': 1, 'fa': 1, 'gi': 1, 'je': 1, 'jo': 1,
'lo': 1, 'ma': 1, 'mí': 1, 'na': 1, 'ne': 1, 'o': 1, 'po': 1, 'pou': 1, 'rma': 1, 'sex': 1,
'sm': 1, 'sro': 1, 'ti': 2, 'to': 1, 'tý': 1, 'u': 1, 'ur': 1, 'vl': 1, 'vě': 1, 'ze': 1,
'či': 1, 'zpa': 1, 'žil': 1},
{'wro': 1, 'bl': 1, 'sněh': 1},
{'у': 1, 'кра': 1, 'їн': 1, 'сько': 1, 'гож': 1},
{'rž': 1},
{'ma': 1, 'ria': 1}]
list_map_with_rep = [{1: 3, 2: 23, 3: 8, 4: 1},
{3: 2, 2: 1},
{1: 1, 3: 4},
{2: 1},
{2: 1, 3: 1}]
list_map_wout_rep = [{1: 3, 2: 22, 3: 7, 4: 1},
{3: 2, 2: 1},
{1: 1, 3: 4},
{2: 1},
{2: 1, 3: 1}]
class TestStringMethods(unittest.TestCase):
def test_1(self):
module = ResultModule(list_lengths_map[0], list_frequency_map[0], "blabla/")
module.run()
time.sleep(1)
self.assertEqual(module.map_with_rep, list_map_with_rep[0])
self.assertEqual(module.map_wout_rep, list_map_wout_rep[0])
def test_2(self):
module = ResultModule(list_lengths_map[1], list_frequency_map[1], "blabla")
module.run()
time.sleep(1)
self.assertEqual(module.map_with_rep, list_map_with_rep[1])
self.assertEqual(module.map_wout_rep, list_map_wout_rep[1])
def test_3(self):
module = ResultModule(list_lengths_map[2], list_frequency_map[2], "blabla")
module.run()
time.sleep(1)
self.assertEqual(module.map_with_rep, list_map_with_rep[2])
self.assertEqual(module.map_wout_rep, list_map_wout_rep[2])
def test_4(self):
module = ResultModule(list_lengths_map[3], list_frequency_map[3], "blabla")
module.run()
time.sleep(1)
self.assertEqual(module.map_with_rep, list_map_with_rep[3])
self.assertEqual(module.map_wout_rep, list_map_wout_rep[3])
def test_5(self):
module = ResultModule(list_lengths_map[4], list_frequency_map[4], "blabla")
module.run()
time.sleep(1)
self.assertEqual(module.map_with_rep, list_map_with_rep[4])
self.assertEqual(module.map_wout_rep, list_map_wout_rep[4])
if __name__ == '__main__':
unittest.main()
|
PHP
|
UTF-8
| 5,484 | 3.140625 | 3 |
[] |
no_license
|
<?php
/**
* Implementation:
* $object->addEventListener('delete', $this);
* or
* SERIA_EventDispatcher::addClassEventListener("classname", "eventname", "classEventListener");
*/
// EXPERIMENTAL
abstract class SERIA_EventDispatcher implements SERIA_NamedObject
{
private static $eventHooks = array();
/**
* Adds an event listener to this object. Whenever this object throws an
* event using $this->throwEvent, all listeners listening to the specified
* event name will be instantiated and the catchEvent method will be called
* with event name and a reference to $this object.
*/
public function addEventListener($eventName, SERIA_EventListener $listener)
{
$targetId = serialize($listener->getObjectId());
$sourceId = serialize($this->getObjectId());
$id = SERIA_Base::guid('eventlistener');
try
{
SERIA_Base::db()->exec('INSERT INTO '.SERIA_PREFIX.'_event_listeners (id, source, target, eventName) VALUES (
'.SERIA_Base::db()->quote($id).',
'.SERIA_Base::db()->quote($sourceId).',
'.SERIA_Base::db()->quote($targetId).',
'.SERIA_Base::db()->quote($eventName).'
)');
}
catch (SERIA_Exception $e)
{
throw new SERIA_Exception('Can\'t listen to the same event multiple times. This execption should be avoided, not catched - for scalability.');
}
}
/**
* Add a callback function to receive events thrown from various classes.
*/
public static function addClassEventHook($className, $eventName, $callback)
{
if(!isset(self::$eventHooks[$className]))
self::$eventHooks[$className] = array();
if(!isset(self::$eventHooks[$className][$eventName]))
self::$eventHooks[$className][$eventName] = array();
self::$eventHooks[$className][$eventName][] = $callback;
}
/**
* Adds a class event listener that will receive all events thrown in the system. This is persistant.
*/
public static function addClassEventListener($className, $eventName, SERIA_EventListener $listener)
{
if(!class_exists($className))
throw new SERIA_Exception("No such class '$className'.");
if(!is_subclass_of($className, 'SERIA_EventDispatcher'))
throw new SERIA_Exception("Can't listen to classes that does not extend SERIA_EventDispatcher.");
$targetId = serialize($listener->getObjectId());
$id = SERIA_Base::guid('eventlistener');
try
{
SERIA_Base::db()->exec('INSERT INTO '.SERIA_PREFIX.'_event_listeners (id, source, target, eventName) VALUES (
'.SERIA_Base::db()->quote($id).',
'.SERIA_Base::db()->quote($className).',
'.SERIA_Base::db()->quote($targetId).',
'.SERIA_Base::db()->quote($eventName).'
)');
}
catch (SERIA_Exception $e)
{
throw new SERIA_Exception('Can\'t listen to the same event multiple times. This execption should be avoided, not catched - for scalability.');
}
}
/**
* Throw an event to all listening objects. Return values are added to a result array.
*
* @param $eventName The name of the event being fired, for example 'delete' or 'update'.
*/
public function throwEvent()
{
$args = func_get_args();
$eventName = $args[0];
unset($args[0]);
$results = array();
$listeners = $this->getEventListeners($eventName);
$args = array_merge(array($this, $eventName), $args);
$classNames = array($className = get_class($this));
while($className = get_parent_class($className))
$classNames[] = $className;
foreach($classNames as $className)
{
if(isset(self::$eventHooks[$className]) && isset(self::$eventHooks[$className][$eventName]))
{
foreach(self::$eventHooks[$className][$eventName] as $callback)
{
if(!is_callable($callback))
{
throw new SERIA_Exception('Invalid callback \''.$callback.'\' added as event hook.');
}
$results[] = call_user_func_array($callback, $args);
}
}
}
foreach($listeners as $listener) {
$function = array($listener, "catchEvent");
$results[] = call_user_func_array($function, $args);
}
return $results;
}
/**
* Get an array of all eventlisteners listening to this object, this class or any of this class's parent classes
* @param $eventName The name of the event type that we want listeners for
*/
public function getEventListeners($eventName=false)
{
$db = SERIA_Base::db();
$classNameParts = array('source='.$db->quote($className = get_class($this)));
while($className = get_parent_class($className))
$classNameParts[] = 'source='.$db->quote($className);
$classNameParts[] = 'source='.$db->quote(serialize($this->getObjectId()));
$classNamePartsSQL = '('.implode(' OR ', $classNameParts).')';
$query = 'SELECT target FROM '.SERIA_PREFIX.'_event_listeners WHERE '.$classNamePartsSQL.($eventName!==false?' AND eventName='.SERIA_Base::db()->quote($eventName):'');
$listeners = SERIA_Base::db()->query($query)->fetchAll(PDO::FETCH_COLUMN, 0);
$listeners = array_flip($listeners);
foreach($listeners as $objectId => $object)
{
try
{
$listeners[$objectId] = SERIA_NamedObjects::getInstanceOf($objectId);
if (!$listeners[$objectId])
unset($listeners[$objectId]);
}
catch (SERIA_Exception $e)
{
unset($listeners[$objectId]);
}
}
return $listeners;
}
}
|
Java
|
UTF-8
| 4,055 | 2.0625 | 2 |
[] |
no_license
|
package um.edu.uy.interfaz.administrador;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.ResourceBundle;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import um.edu.uy.interfaz.cliente.ControladorInicio;
@Component
public class AdminControladorPagosPendientes implements ApplicationContextAware {
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private Button btnVerPagosPendientes;
@FXML
private TextField txtAnioFin;
@FXML
private TextField txtAnioInicio;
@FXML
private TextField txtDiaFin;
@FXML
private TextField txtDiaInicio;
@FXML
private TextField txtMesFin;
@FXML
private TextField txtMesInicio;
ApplicationContext applicationContext;
private LocalDate fechaInicio;
private LocalDate fechaFin;
@FXML
void verPagosPendientes(ActionEvent event) throws IOException {
Stage stage;
Parent root = null;
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setControllerFactory(applicationContext::getBean);
stage = new Stage();
if (event.getSource() == btnVerPagosPendientes) {
try {
fechaInicio = LocalDate.of(Integer.parseInt(txtAnioInicio.getText()), Integer.parseInt(txtMesInicio.getText()), Integer.parseInt(txtDiaInicio.getText()));
fechaFin = LocalDate.of(Integer.parseInt(txtAnioFin.getText()), Integer.parseInt(txtMesFin.getText()), Integer.parseInt(txtDiaFin.getText()));
} catch (NumberFormatException e) {
showAlert("Lo sentimos, ", "Ingrese una fecha de inicio y de finalizacion.");
}
stage = (Stage) btnVerPagosPendientes.getScene().getWindow();
root = fxmlLoader.load(AdminControladorRegistro.class.getResourceAsStream("verPagosPendientes.fxml"));
}
Scene scene = new Scene(root);
scene.getStylesheets().add(ControladorInicio.class.getResource("style.css").toExternalForm());
stage.setScene(scene);
stage.show();
}
@FXML
void initialize() {
assert btnVerPagosPendientes != null : "fx:id=\"btnVerPagosPendientes\" was not injected: check your FXML file 'verPagosPendientes.fxml'.";
assert txtAnioFin != null : "fx:id=\"txtAnioFin\" was not injected: check your FXML file 'recibirFechasParaPagosPendientes.fxml'.";
assert txtAnioInicio != null : "fx:id=\"txtAnioInicio\" was not injected: check your FXML file 'recibirFechasParaPagosPendientes.fxml'.";
assert txtDiaFin != null : "fx:id=\"txtDiaFin\" was not injected: check your FXML file 'recibirFechasParaPagosPendientes.fxml'.";
assert txtDiaInicio != null : "fx:id=\"txtDiaInicio\" was not injected: check your FXML file 'recibirFechasParaPagosPendientes.fxml'.";
assert txtMesFin != null : "fx:id=\"txtMesFin\" was not injected: check your FXML file 'recibirFechasParaPagosPendientes.fxml'.";
assert txtMesInicio != null : "fx:id=\"txtMesInicio\" was not injected: check your FXML file 'recibirFechasParaPagosPendientes.fxml'.";
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public static void showAlert(String title, String contextText) {
javafx.scene.control.Alert alert = new javafx.scene.control.Alert(
javafx.scene.control.Alert.AlertType.INFORMATION);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(contextText);
alert.showAndWait();
}
public LocalDate getFechaInicio() {
return fechaInicio;
}
public LocalDate getFechaFin() {
return fechaFin;
}
}
|
Java
|
UTF-8
| 1,017 | 3.515625 | 4 |
[] |
no_license
|
package shashank;
import java.util.Scanner;
public class WeekDay_Q5Feb03 {
void dayOfWeek(int day)
{
if (day%7==0 && day!=0)
day=7;
else
day=day%7;
switch(day)
{
case 1:
System.out.println("The day is Sunday");
break;
case 2:
System.out.println("The day is Monday");
break;
case 3:
System.out.println("The day is Tuesday");
break;
case 4:
System.out.println("The day is Wednesday");
break;
case 5:
System.out.println("The day is Thursday");
break;
case 6:
System.out.println("The day is Friday");
break;
case 7:
System.out.println("The day is Saturday");
break;
default:
System.out.println("Invalid input");
}
}
public static void main(String[] args)
{
System.out.println("Please enter number between 1 to 7, to know underlying day");
Scanner sc = new Scanner(System.in);
WeekDay_Q5Feb03 wd = new WeekDay_Q5Feb03();
wd.dayOfWeek(sc.nextInt());
}
}
|
Java
|
UTF-8
| 8,151 | 2.140625 | 2 |
[] |
no_license
|
package reverblabs.apps.aura.ui.adapters.playlist;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import reverblabs.apps.aura.R;
import reverblabs.apps.aura.interfaces.AdapterToFragmentCallbacks;
import reverblabs.apps.aura.ui.fragments.playlist.PlaylistsFragment;
import reverblabs.apps.aura.model.Playlist;
import reverblabs.apps.aura.model.Song;
import reverblabs.apps.aura.utils.Constants;
import static reverblabs.apps.aura.R.drawable.playlist;
public class AdapterForPlaylists extends RecyclerView.Adapter<AdapterForPlaylists.ViewHolder> {
private ArrayList<Playlist> playlistDataset = new ArrayList<>();
private Context context;
private Cursor cursor;
private AdapterToFragmentCallbacks fragmentCallbacks;
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, PopupMenu.OnMenuItemClickListener {
TextView name;
TextView count;
ImageView imageView;
ImageView overflow;
ViewHolder(View v) {
super(v);
name = v.findViewById(R.id.playlist_name);
count = v.findViewById(R.id.playlist_count);
imageView = v.findViewById(R.id.image_playlists);
overflow = v.findViewById(R.id.overflow_playlists);
overflow.setOnClickListener(this);
v.setOnClickListener(this);
}
@Override
public void onClick(View view){
if(view==overflow){
if(!(playlistDataset.get(getAdapterPosition()).name).equals(context.getString(R.string.recently_added))
&& !(playlistDataset.get(getAdapterPosition()).name).equals(context.getString(R.string.recently_played))
&& !(playlistDataset.get(getAdapterPosition()).name).equals(context.getString(R.string.favourites))) {
PopupMenu popupMenu = new PopupMenu(context, view);
MenuInflater inflater = popupMenu.getMenuInflater();
inflater.inflate(R.menu.menu_playlist, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(this);
popupMenu.show();
}
}
else {
if(playlistDataset.get(getAdapterPosition()).name != null) {
String clickedPlaylist = playlistDataset.get(getAdapterPosition()).name;
long id = playlistDataset.get(getAdapterPosition()).playlistId;
Bundle bundle = new Bundle();
bundle.putString(Constants.PLAYLIST_NAME, clickedPlaylist);
bundle.putLong(Constants.PLAYLIST_ID, id);
fragmentCallbacks.createPlaylistDetailFragment(bundle);
}
}
}
@Override
public boolean onMenuItemClick(MenuItem item){
int posOfItemDeleted;
Playlist playlist = playlistDataset.get(getAdapterPosition());
posOfItemDeleted = playlistDataset.indexOf(playlist);
switch (item.getItemId()){
case R.id.add_to_queue_playlist:
ArrayList<Song> temp = playlist.getAllSongsOfPlaylist(context.getContentResolver(), playlist.getId());
fragmentCallbacks.addToQueue(temp);
return true;
case R.id.delete_playlist:
Log.i(Constants.TAG, Long.toString(playlist.getId()));
playlist.deletePlaylist(context.getContentResolver(), playlist.getId());
notifyItemRemoved(posOfItemDeleted);
default:
return false;
}
}
}
public AdapterForPlaylists( Context cx, Cursor dataCusrsor, PlaylistsFragment fragment ){
context = cx;
cursor = dataCusrsor;
fragmentCallbacks = fragment;
}
public Cursor swapCursor(Cursor mCursor){
if(cursor == mCursor){
return null;
}
Cursor oldCursor = cursor;
this.cursor = mCursor;
try{
cursor.moveToFirst();
}
catch (NullPointerException e){
}
if(cursor!=null){
int idcolumn = cursor.getColumnIndex(MediaStore.Audio.Playlists._ID);
int namecolumn = cursor.getColumnIndex(MediaStore.Audio.Playlists.NAME);
playlistDataset.clear();
Playlist recentlyAdded = new Playlist(-1, context.getString(R.string.recently_added), Playlist.getNoOfSongsInRecentlyAdded(context.getContentResolver()));
playlistDataset.add(recentlyAdded);
Playlist recentlyPlayed = new Playlist(-2, context.getString(R.string.recently_played), Playlist.getSongsInRecentlyPlayed(context));
playlistDataset.add(recentlyPlayed);
Playlist favourites = new Playlist(-3,context.getString(R.string.favourites), Playlist.getSongsInFavourites(context));
playlistDataset.add(favourites);
if (cursor.getCount() > 0) {
do {
int count = Playlist.getNoOfSongsInPlaylist(context.getContentResolver(), cursor.getLong(0));
Playlist playlist = new Playlist(cursor.getLong(idcolumn),
cursor.getString(namecolumn), count);
playlistDataset.add(playlist);
} while (cursor.moveToNext());
}
this.notifyDataSetChanged();
}
return oldCursor;
}
@Override
public AdapterForPlaylists.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_for_playlists, parent, false);
return new AdapterForPlaylists.ViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull AdapterForPlaylists.ViewHolder holder, int position) {
if(playlistDataset.get(position).name != null) {
holder.name.setText(playlistDataset.get(position).name);
int noOfSongs = playlistDataset.get(position).noOfSongs;
if (noOfSongs == 1) {
holder.count.setText(Integer.toString(noOfSongs) + " " + context.getString(R.string.song));
} else {
holder.count.setText(Integer.toString(noOfSongs) + " " + context.getString(R.string.songs));
}
Log.i(Constants.TAG, "Playlist in bindView holder" + playlistDataset.get(position).name);
holder.imageView.setImageResource(playlist);
if ((playlistDataset.get(position).name).equals(context.getString(R.string.recently_added))
|| (playlistDataset.get(position).name).equals(context.getString(R.string.recently_played))
|| (playlistDataset.get(position).name).equals(context.getString(R.string.favourites))) {
holder.overflow.setVisibility(View.GONE);
} else {
holder.overflow.setImageResource(R.drawable.overflow);
}
}
}
public void notifyNewPlaylistCreated(long id, String name){
Playlist playlist = new Playlist(id, name, 0);
playlistDataset.add(playlist);
notifyItemRangeInserted(playlistDataset.size() - 1, 1);
}
@Override
public int getItemCount() {
if (playlistDataset != null) {
return playlistDataset.size();
}else {
return 0;
}
}
}
|
Markdown
|
UTF-8
| 733 | 2.65625 | 3 |
[] |
no_license
|
My name is Arman Kaliakyn id: 190103486. I am a 2nd year student at Sdu.
Lab5
My project has 4 pages.First page home,about,portfolio and contact.In my project I used extends and a controller.




|
C++
|
UTF-8
| 479 | 2.9375 | 3 |
[] |
no_license
|
#include<cstdio>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
for(int i=1;i<=t;i++){
int h,m,s,hh,mm,ss;
scanf("%d %d %d",&h,&m,&s);
scanf("%d %d %d",&hh,&mm,&ss);
m+=s/60;s%=60;
mm+=ss/60;ss%=60;
h+=m/60;m%=60;
hh+=mm/60;mm%=60;
if(h==hh&&m==mm&&s==ss)
printf("Case %d: Yes\n",i);
else
printf("Case %d: No\n",i);
}
return 0;
}
|
Java
|
ISO-8859-1
| 1,329 | 2.40625 | 2 |
[] |
no_license
|
package Servlets;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/ServletDeconnexion")
public class ServletDeconnexion extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletDeconnexion() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/* Rcupration et destruction de la session en cours */
HttpSession session = request.getSession();
session.invalidate();
//supprssion des lements du context de l'application
ServletContext ss = getServletContext();
ss.removeAttribute("UserStudent");
ss.removeAttribute("UserMember");
/* Redirection vers la page d'acceuille ! */
this.getServletContext().getRequestDispatcher("/WEB-INF/VIEW/login.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
|
JavaScript
|
UTF-8
| 195 | 2.84375 | 3 |
[] |
no_license
|
/*
* 37. Default Parameters One Debug
*/
function isEqualTo(number = 10,compare){
console.log(number);
console.log(compare);
return number == compare;
}
console.log(isEqualTo(11));
|
Java
|
UTF-8
| 3,258 | 3.796875 | 4 |
[] |
no_license
|
package com.cardGame;
public class Card implements Comparable<Card>{
private Suite cardSuite;
private byte cardValue;
public Card(int cardSuite, int cardValue){
switch (cardSuite){
case 1:
this.cardSuite = Suite.CIRCLE;
break;
case 2:
this.cardSuite = Suite.TRIANGLE;
break;
case 3:
this.cardSuite = Suite.CROSS;
break;
case 4:
this.cardSuite = Suite.SQUARE;
break;
case 5:
this.cardSuite = Suite.STAR;
break;
case 6:
this.cardSuite = Suite.WHOT;
break;
}
this.setCardValue (cardValue);
}
public Suite getCardSuite() {
return cardSuite;
}
public short getCardValue() {
return cardValue;
}
public void setCardValue(int cardValue) {
this.cardValue = (byte) cardValue;
}
public void displayCard() {
System.out.println(getCardSuite() + " " + getCardValue());
}
/**
* Compares this object with the specified object for order. Returns a
* negative integer, zero, or a positive integer as this object is less
* than, equal to, or greater than the specified object.
*
* <p>The implementor must ensure <tt>sgn(x.compareTo(y)) ==
* -sgn(y.compareTo(x))</tt> for all <tt>x</tt> and <tt>y</tt>. (This
* implies that <tt>x.compareTo(y)</tt> must throw an exception iff
* <tt>y.compareTo(x)</tt> throws an exception.)
*
* <p>The implementor must also ensure that the relation is transitive:
* <tt>(x.compareTo(y)>0 && y.compareTo(z)>0)</tt> implies
* <tt>x.compareTo(z)>0</tt>.
*
* <p>Finally, the implementor must ensure that <tt>x.compareTo(y)==0</tt>
* implies that <tt>sgn(x.compareTo(z)) == sgn(y.compareTo(z))</tt>, for
* all <tt>z</tt>.
*
* <p>It is strongly recommended, but <i>not</i> strictly required that
* <tt>(x.compareTo(y)==0) == (x.equals(y))</tt>. Generally speaking, any
* class that implements the <tt>Comparable</tt> interface and violates
* this condition should clearly indicate this fact. The recommended
* language is "Note: this class has a natural ordering that is
* inconsistent with equals."
*
* <p>In the foregoing description, the notation
* <tt>sgn(</tt><i>expression</i><tt>)</tt> designates the mathematical
* <i>signum</i> function, which is defined to return one of <tt>-1</tt>,
* <tt>0</tt>, or <tt>1</tt> according to whether the value of
* <i>expression</i> is negative, zero or positive.
*
* @param card the object to be compared.
* @return a negative integer, zero, or a positive integer as this object
* is less than, equal to, or greater than the specified object.
*/
@Override
public int compareTo(Card card) {
if (this.getCardValue() == card.getCardValue() || this.getCardSuite()== card.getCardSuite()) return 0;
else if (this.getCardValue() > card.getCardValue()) return 1;
else return -1;
}
}
|
Python
|
UTF-8
| 572 | 3.671875 | 4 |
[] |
no_license
|
""" Selection Sort p. 157 """
array = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8]
# Swap 사용.ver
'''
for i in range(len(array)):
min_index = i
for j in range(i+1, len(array)):
if array[min_index] > array[j]:
min_index = j
array[min_index], array[i] = array[i], array[min_index] # swap
'''
# no swap.ver
for i in range(len(array)):
min_index = i
for j in range(i+1, len(array)):
if array[min_index] > array[j]:
min_index = j
temp = array[i]
array[i] = array[min_index]
array[min_index] = temp
print(array)
|
Java
|
UTF-8
| 1,303 | 2.625 | 3 |
[] |
no_license
|
package jp.co.kin.common.encode;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import org.springframework.stereotype.Component;
import jp.co.kin.common.log.Logger;
import jp.co.kin.common.log.LoggerFactory;
import jp.co.kin.common.type.Charset;
/**
* URLエンコード/デコードクラス
*
* @since 1.0.0
*/
@Component("urlEncodeAndDecoder")
public class UrlEncodeAndDecoder implements BaseEncodeAndDecoder {
private static final Logger LOG = LoggerFactory.getLogger(UrlEncodeAndDecoder.class);
@Override
public String encode(String str, Charset charset) {
try {
return URLEncoder.encode(str, charset.getValue());
} catch (UnsupportedEncodingException e) {
LOG.error("指定された文字コードが不正です charset=" + charset.getValue(), e);
return null;
}
}
@Override
public String decode(String str, Charset charset) {
try {
return URLDecoder.decode(str, charset.getValue());
} catch (UnsupportedEncodingException e) {
LOG.error("指定された文字コードが不正です charset=" + charset.getValue(), e);
return null;
}
}
}
|
JavaScript
|
UTF-8
| 856 | 2.796875 | 3 |
[] |
no_license
|
import React from 'react'
import Task from './Task'
//Using an Array before
// const tasks = [
// {id: 1,
// text: "Panera Bread Jam Session",
// day: "Today",
// remainder: true},
// {id: 2,
// text: "Burger Interview",
// day: "next monday",
// remainder: true},
// ]
//Now we use states and hooks
//Handles multiple tasks, component takes in a array of tasks and outputs it back to App.js
const Tasks = ({tasks,onDelete,onToggle}) => {
return (
<>
{/* Using a list with tasks.map, for each loop with each element in tasks, send it to Task.js to display */}
{tasks.map((task,index)=>(
<Task
key={index}
task={task}
onDelete={onDelete}
onToggle={onToggle}/>
))}
</>
)
}
export default Tasks
|
C#
|
UTF-8
| 448 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
namespace Newtonsoft.Json
{
/// <summary>
/// Specifies whether to ignore empty arrays
/// </summary>
public enum EmptyArrayHandling
{
/// <summary>
/// Ignore empty array when deserializing (use object current array).
/// </summary>
Ignore = 0,
/// <summary>
/// Set empty array (replace object's current array with an empty one)
/// </summary>
Set = 1
}
}
|
Markdown
|
UTF-8
| 4,847 | 2.65625 | 3 |
[] |
no_license
|
---
description: "Steps to Prepare Speedy Refried Beans - Quick Stovetop Recipe"
title: "Steps to Prepare Speedy Refried Beans - Quick Stovetop Recipe"
slug: 570-steps-to-prepare-speedy-refried-beans-quick-stovetop-recipe
date: 2020-12-21T14:25:47.590Z
image: https://img-global.cpcdn.com/recipes/45b3dfa02713a364/680x482cq70/refried-beans-quick-stovetop-recipe-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/45b3dfa02713a364/680x482cq70/refried-beans-quick-stovetop-recipe-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/45b3dfa02713a364/680x482cq70/refried-beans-quick-stovetop-recipe-recipe-main-photo.jpg
author: Lucy Morrison
ratingvalue: 4.8
reviewcount: 30058
recipeingredient:
- "2 tbsp. butter divided"
- "1/2 yellow onion diced"
- "1 jalapeno seeds removed and diced optional"
- "4 cloves garlic minced"
- "2 cans each 15 oz pinto beans drained and rinsed"
- "1/2 cup unsalted chicken or veggie broth"
- "1 tsp. chipotle chili powder"
- "1 tsp. ground cumin"
- "1/2 tsp. oregano"
- " Juice from 12 lime"
- "1/4 tsp. salt"
- "1/8 tsp. pepper"
recipeinstructions:
- "In a medium saucepan, melt 1 tbsp. of the butter over med-high heat. Once its melted, add the onion and jalapeno (if using). Cook, stirring often, until they're softened, about 5 minutes. Then stir in the garlic and cook until it's fragrant."
- "Stir in the beans, broth, chili powder, cumin and oregano and let this mixture come up to a simmer. Once it begins to bubble, let it simmer for about 5 or so minutes, then remove the pan from the heat. Either use a masher to roughly mash the beans, or use a food processor for a smoother consistency."
- "Once the beans are mashed, season with the lime juice, salt and pepper. Then stir in the additional tbsp. of butter until it's all melted and incorporated in. That's it! Serve it up with some yummy toppings."
categories:
- Recipe
tags:
- refried
- beans
-
katakunci: refried beans
nutrition: 100 calories
recipecuisine: American
preptime: "PT26M"
cooktime: "PT38M"
recipeyield: "1"
recipecategory: Lunch
---

Hey everyone, I hope you are having an amazing day today. Today, I will show you a way to prepare a distinctive dish, refried beans - quick stovetop recipe. One of my favorites food recipes. For mine, I will make it a little bit tasty. This is gonna smell and look delicious.
Refried Beans - Quick Stovetop Recipe is one of the most popular of current trending meals on earth. It is easy, it is fast, it tastes yummy. It is appreciated by millions every day. Refried Beans - Quick Stovetop Recipe is something which I've loved my whole life. They are nice and they look wonderful.
To get started with this recipe, we must first prepare a few components. You can cook refried beans - quick stovetop recipe using 12 ingredients and 3 steps. Here is how you cook that.
<!--inarticleads1-->
##### The ingredients needed to make Refried Beans - Quick Stovetop Recipe:
1. Prepare 2 tbsp. butter, divided
1. Get 1/2 yellow onion, diced
1. Prepare 1 jalapeno, seeds removed and diced (optional)
1. Make ready 4 cloves garlic, minced
1. Make ready 2 cans (each 15 oz.) pinto beans, drained and rinsed
1. Make ready 1/2 cup unsalted chicken or veggie broth
1. Get 1 tsp. chipotle chili powder
1. Prepare 1 tsp. ground cumin
1. Make ready 1/2 tsp. oregano
1. Take Juice from 1/2 lime
1. Take 1/4 tsp. salt
1. Take 1/8 tsp. pepper
<!--inarticleads2-->
##### Instructions to make Refried Beans - Quick Stovetop Recipe:
1. In a medium saucepan, melt 1 tbsp. of the butter over med-high heat. Once its melted, add the onion and jalapeno (if using). Cook, stirring often, until they're softened, about 5 minutes. Then stir in the garlic and cook until it's fragrant.
1. Stir in the beans, broth, chili powder, cumin and oregano and let this mixture come up to a simmer. Once it begins to bubble, let it simmer for about 5 or so minutes, then remove the pan from the heat. Either use a masher to roughly mash the beans, or use a food processor for a smoother consistency.
1. Once the beans are mashed, season with the lime juice, salt and pepper. Then stir in the additional tbsp. of butter until it's all melted and incorporated in. That's it! Serve it up with some yummy toppings.
So that's going to wrap this up with this exceptional food refried beans - quick stovetop recipe recipe. Thanks so much for reading. I am confident you will make this at home. There's gonna be more interesting food at home recipes coming up. Remember to bookmark this page in your browser, and share it to your loved ones, friends and colleague. Thank you for reading. Go on get cooking!
|
PHP
|
UTF-8
| 1,260 | 2.703125 | 3 |
[] |
no_license
|
<?php
namespace AppBundle\Entity;
use AppBundle\Custom\Entry\AbsEntry;
/**
* PioneerparkSetting
*/
class PioneerparkSetting extends AbsEntry
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $settingKey;
/**
* @var string
*/
private $settingValue;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set settingKey
*
* @param string $settingKey
*
* @return PioneerparkSetting
*/
public function setSettingKey($settingKey)
{
$this->settingKey = $settingKey;
return $this;
}
/**
* Get settingKey
*
* @return string
*/
public function getSettingKey()
{
return $this->settingKey;
}
/**
* Set settingValue
*
* @param string $settingValue
*
* @return PioneerparkSetting
*/
public function setSettingValue($settingValue)
{
$this->settingValue = $settingValue;
return $this;
}
/**
* Get settingValue
*
* @return string
*/
public function getSettingValue()
{
return $this->settingValue;
}
}
|
C
|
UTF-8
| 6,687 | 3.171875 | 3 |
[] |
no_license
|
// Author: Eric Kalosa-Kenyon
//
// This program times matrix multiplication using each loop ordering and reports
// timing results.
//
// Takes:
// n - command line input, size of matrices to multiply
// Returns:
// stdio - timing results
//
// Sources:
// 1. http://www.programmingsimplified.com/c-program-multiply-matrices
// 2. https://en.wikipedia.org/wiki/C_dynamic_memory_allocation
// 3. http://web.cs.ucdavis.edu/~fgygi/ecs230/homework/hw3/dotblas.c
// 4. http://web.cs.ucdavis.edu/~fgygi/ecs230/homework/hw2/timing1.c
// 5. http://www.cplusplus.com/forum/windows/192252/
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
#include "sys/time.h"
#include "math.h"
// BEGIN SUBROUTINES
volatile double gtod(void) {
/* Get time of day */
/* Directly from timing1.c on ~fgygi */
/* http://web.cs.ucdavis.edu/~fgygi/ecs230/homework/hw2/timing1.c */
static struct timeval tv;
static struct timezone tz;
gettimeofday(&tv,&tz);
return tv.tv_sec + 1.e-6*tv.tv_usec;
}
long long readTSC(void)
{
/* Read the time stamp counter on Intel x86 chips */
/* Directly from timing2.c on ~fgygi */
/* http://web.cs.ucdavis.edu/~fgygi/ecs230/homework/hw2/timing2.c */
union { long long complete; unsigned int part[2]; } ticks;
__asm__ ("rdtsc; mov %%eax,%0;mov %%edx,%1"
: "=mr" (ticks.part[0]), "=mr" (ticks.part[1])
: /* no inputs */
: "eax", "edx");
return ticks.complete;
}
// END SUBROUTINES
// BEGIN MAIN
int main(int argc, char** argv)
{
// initialize matrix size and indexing variables
int n = atoi(argv[1]); // size of mx from commandline
int r = atoi(argv[2]); // number of times to perform the multiplication
int i, j, k, s; // indicies for matrix arrays
double sum = 0.0;
// dynamic memory allocation for the matrices
double *A = (double*)malloc((n*n)* sizeof(double));
double *B = (double*)malloc((n*n)* sizeof(double));
double *C = (double*)malloc((n*n)* sizeof(double));
if ((A == NULL) || (B == NULL) || (C == NULL)) {
fprintf(stderr, "malloc failed\n");
return(-1);
}
// make arbitrary matrices A and B
for (j = 0; j < n; j++) {
for (i = 0; i < n; i++) {
A[i + n*j] = i/(j+1.0) + 1.0/(i + n*j + 1);
B[i + n*j] = j/(i+1.0) + 2.0/(i + n*j + 1);
}
}
// initialize timing elements
clock_t clk;
double tod, t_cpu, t_real;
long start, stop, time_elapsed;
long long delta_clock;
// perform AB r times
printf("clocks, time, loop_order\n");
for (s = 0; s < r; s++) {
// start timing
clk = clock();
start = readTSC();
tod = gtod();
// perform multiplication C = AB - using ordering 1 jik
for (j = 0; j < n; j++) {
for (i = 0; i < n; i++) {
for (k = 0; k < n; k++) {
sum = sum + A[i + n*k]*B[k + n*j];
}
C[i + n*j] = sum;
sum = 0.0;
}
}
// determine and display timing results
delta_clock = clock() - clk;
t_real = gtod() - tod;
stop = readTSC();
time_elapsed = stop - start;
printf("%ld, %f, %d\n", time_elapsed, t_real, 1 );
// start timing
clk = clock();
start = readTSC();
tod = gtod();
// perform multiplication C = AB - using ordering 2 jki
for (j = 0; j < n; j++) {
for (k = 0; k < n; k++) {
for (i = 0; i < n; i++) {
sum = sum + A[i + n*k]*B[k + n*j];
}
C[i + n*j] = sum;
sum = 0.0;
}
}
// determine and display timing results
delta_clock = clock() - clk;
t_real = gtod() - tod;
stop = readTSC();
time_elapsed = stop - start;
printf("%ld, %f, %d\n", time_elapsed, t_real, 2 );
// start timing
clk = clock();
start = readTSC();
tod = gtod();
// perform multiplication C = AB - using ordering 3 ijk
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
for (k = 0; k < n; k++) {
sum = sum + A[i + n*k]*B[k + n*j];
}
C[i + n*j] = sum;
sum = 0.0;
}
}
// determine and display timing results
delta_clock = clock() - clk;
t_real = gtod() - tod;
stop = readTSC();
time_elapsed = stop - start;
printf("%ld, %f, %d\n", time_elapsed, t_real, 3 );
// start timing
clk = clock();
start = readTSC();
tod = gtod();
// perform multiplication C = AB - using ordering 4 ikj
for (i = 0; i < n; i++) {
for (k = 0; k < n; k++) {
for (j = 0; j < n; j++) {
sum = sum + A[i + n*k]*B[k + n*j];
}
C[i + n*j] = sum;
sum = 0.0;
}
}
// determine and display timing results
delta_clock = clock() - clk;
t_real = gtod() - tod;
stop = readTSC();
time_elapsed = stop - start;
printf("%ld, %f, %d\n", time_elapsed, t_real, 4 );
// start timing
clk = clock();
start = readTSC();
tod = gtod();
// perform multiplication C = AB - using ordering 5 kji
for (k = 0; k < n; k++) {
for (j = 0; j < n; j++) {
for (i = 0; i < n; i++) {
sum = sum + A[i + n*k]*B[k + n*j];
}
C[i + n*j] = sum;
sum = 0.0;
}
}
// determine and display timing results
delta_clock = clock() - clk;
t_real = gtod() - tod;
stop = readTSC();
time_elapsed = stop - start;
printf("%ld, %f, %d\n", time_elapsed, t_real, 5 );
// start timing
clk = clock();
start = readTSC();
tod = gtod();
// perform multiplication C = AB - using ordering 6 kij
for (k = 0; k < n; k++) {
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
sum = sum + A[i + n*k]*B[k + n*j];
}
C[i + n*j] = sum;
sum = 0.0;
}
}
// determine and display timing results
delta_clock = clock() - clk;
t_real = gtod() - tod;
stop = readTSC();
time_elapsed = stop - start;
printf("%ld, %f, %d\n", time_elapsed, t_real, 6 );
} // END for loop over R (multiply AB multiple times)
// Remove the matrices from memory
free(A);
free(B);
free(C);
return 0;
/* // display A and B */
/* printf("Matrix A:\n"); */
/* for (i = 0; i < n; i++) { */
/* for (j = 0; j < n; j++) */
/* printf("%lf\t", A[i + n*j]); */
/* printf("\n"); */
/* } */
/* printf("Matrix B:\n"); */
/* for (i = 0; i < n; i++) { */
/* for (j = 0; j < n; j++) */
/* printf("%lf\t", B[i + n*j]); */
/* printf("\n"); */
/* } */
/* // display product C = AB */
/* printf("Product C of AB:\n"); */
/* for (i = 0; i < n; i++) { */
/* for (j = 0; j < n; j++) */
/* printf("%lf\t", C[i + n*j]); */
/* printf("\n"); */
/* } */
return 0;
}
// END MAIN
|
TypeScript
|
UTF-8
| 5,533 | 2.5625 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
import { Subscription } from 'rxjs';
import { IAppEventLoggerOptions } from './types';
import AppEventBus from './app-event-bus';
import {
AppEventTypes,
AppEventTypeAnimationFrame,
AppEventTypeWindowResize,
AppEventTypeRendererGeometryUpdate,
AppEventTypeKeyDown,
AppEventTypeKeyUp,
AppEventTypeMouseDown,
AppEventTypeMouseUp,
AppEventTypeMouseMove,
AppEventTypeCameraLook,
} from './app-event';
export default class AppEventLogger {
private eventBus?: AppEventBus | null = null;
private eventSubscriptions?: Array<Subscription | null> | null = null;
private options?: IAppEventLoggerOptions | null = null;
private isInitialized: boolean;
private isDestroyed: boolean;
constructor(eventBus: AppEventBus, options?: IAppEventLoggerOptions) {
this.eventBus = eventBus;
if (typeof options === 'undefined') {
options = {};
}
this.setupOptionsObject(options);
this.initEventSubscriptions();
this.isInitialized = true;
this.isDestroyed = false;
}
public destroy(): void {
if (this.isInitialized !== true || this.isDestroyed === true) {
return;
}
this.freeEventSubscriptions();
this.destroyProperties();
this.isDestroyed = true;
}
private setupOptionsObject(options: IAppEventLoggerOptions): void {
const availableOptions: string[] = [
'animationFrame',
'windowResize',
'geometryUpdate',
'keyDown',
'keyUp',
'mouseDown',
'mouseUp',
'mouseMove',
'cameraLook',
];
availableOptions.forEach((option: string) => {
if (typeof options[option] !== 'boolean') {
options[option] = true;
}
});
this.options = options;
}
private freeEventSubscriptions(): void {
if (!this.eventSubscriptions) {
return;
}
this.eventSubscriptions.forEach((subscription: Subscription | null, idx: number) => {
if (subscription) {
subscription.unsubscribe();
}
if (this.eventSubscriptions) {
delete this.eventSubscriptions[idx];
this.eventSubscriptions[idx] = null;
}
});
}
private destroyProperties(): void {
delete this.eventBus;
this.eventBus = null;
delete this.eventSubscriptions;
this.eventSubscriptions = null;
delete this.options;
this.options = null;
}
private initEventSubscriptions(): void {
if (!this.eventBus) {
throw new Error('can not run func initEventSubscriptions() : eventBus is not initialized');
}
this.eventSubscriptions = [];
const subscription: Subscription = this.eventBus.subscribe((event: AppEventTypes) => {
if (!this.options) {
throw new Error('can not run func initEventSubscriptions() : options is not initialized');
}
if (
this.options.animationFrame && event instanceof AppEventTypeAnimationFrame
) {
console.log('---------- -------- ----- ---- -- -');
console.log('event :: AppEventTypeAnimationFrame');
console.log('payload.delta = ', event.payload.delta);
} else if (
this.options.windowResize && event instanceof AppEventTypeWindowResize
) {
console.log('---------- -------- ----- ---- -- -');
console.log('event :: AppEventTypeWindowResize');
} else if (
this.options.geometryUpdate && event instanceof AppEventTypeRendererGeometryUpdate
) {
console.log('---------- -------- ----- ---- -- -');
console.log('event :: AppEventTypeRendererGeometryUpdate');
console.log('payload.appHeight = ', event.payload.appHeight);
console.log('payload.appWidth = ', event.payload.appWidth);
console.log('payload.offsetLeft = ', event.payload.offsetLeft);
console.log('payload.offsetTop = ', event.payload.offsetTop);
} else if (
this.options.keyDown && event instanceof AppEventTypeKeyDown
) {
console.log('---------- -------- ----- ---- -- -');
console.log('event :: AppEventTypeKeyDown');
console.log('payload.code = ', event.payload.code);
} else if (
this.options.keyDown && event instanceof AppEventTypeKeyUp
) {
console.log('---------- -------- ----- ---- -- -');
console.log('event :: AppEventTypeKeyUp');
console.log('payload.code = ', event.payload.code);
} else if (
this.options.mouseDown && event instanceof AppEventTypeMouseDown
) {
console.log('---------- -------- ----- ---- -- -');
console.log('event :: AppEventTypeMouseDown');
} else if (
this.options.mouseUp && event instanceof AppEventTypeMouseUp
) {
console.log('---------- -------- ----- ---- -- -');
console.log('event :: AppEventTypeMouseUp');
} else if (
this.options.mouseMove && event instanceof AppEventTypeMouseMove
) {
console.log('---------- -------- ----- ---- -- -');
console.log('event :: AppEventTypeMouseMove');
console.log('payload.mouseX = ', event.payload.mouseX);
console.log('payload.mouseY = ', event.payload.mouseY);
} else if (
this.options.cameraLook && event instanceof AppEventTypeCameraLook
) {
console.log('---------- -------- ----- ---- -- -');
console.log('event :: AppEventTypeCameraLook');
console.log('payload.xPos = ', event.payload.xPos);
console.log('payload.yPos = ', event.payload.yPos);
}
});
this.eventSubscriptions.push(subscription);
}
}
|
C++
|
UTF-8
| 1,730 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include "Engine/Core/EngineCommon.hpp"
#include <map>
namespace Profiler
{
struct Measurement;
}
class ProfilerReportEntry
{
private:
static constexpr int CHILD_STR_INDENT = 1;
public:
ProfilerReportEntry( const String& name );
~ProfilerReportEntry();
void PopulateTreeR( Profiler::Measurement *node );
void AccumulateData( Profiler::Measurement *node );
void FinalizeTimesR();
// Call after FinalizeTimesR for tree and after CollapesTreeToFlatR for flat
void FinalizePercentagesR( double frameTime );
// root Entry should be a clean entry without children
// call after FinalizeTimesR
void CollapesTreeToFlatR( ProfilerReportEntry *rootEntry );
void PopulateFlatR( Profiler::Measurement *node, ProfilerReportEntry *rootEntry );
ProfilerReportEntry* GetOrCreateChild( const String& id );
String GernerateStringR( int indent = 0 );
size_t GetTotalStringSizeR();
// this is done according to sorting order
void AppendToStringR( String& appendTo );
void SortChildrenR(
std::function<bool( ProfilerReportEntry*, ProfilerReportEntry* )> comparer );
void SortChildernTotalTimeR();
void SortChildernSelfTimeR();
public:
String m_name;
uint m_callCount;
double m_totalTime = 0; // inclusive time;
double m_selfTime = 0; // exclusive time
double m_totalPercentTime = 0;
double m_selfPercentTime = 0;
String m_reportString;
// if you care about new piece data - add time;
// mean
// median
// high water
// low water
ProfilerReportEntry *m_parent;
std::map<String, ProfilerReportEntry*> m_children;
std::vector <ProfilerReportEntry*> m_sortedChildren;
};
|
Java
|
UTF-8
| 504 | 2.625 | 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 solvedRight;
/**
*
* @author Irfan Assidiq
*/
public class SampleOne {
public static void main(String [] ar){
try{
int a = 5;
int b = a/0;
}catch(ArithmeticException e){
System.out.println(e);
}
System.out.println("Setelah eksepsi");
}
}
|
PHP
|
UTF-8
| 207 | 3.4375 | 3 |
[] |
no_license
|
<?php
namespace Generator;
class TriangularNumberGenerator
{
public static function gen($n)
{
for ($i = 0; $i <= $n; $i++)
{
yield ($i * ($i + 1)) / 2;
}
}
}
|
Markdown
|
UTF-8
| 11,182 | 2.6875 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
% Gravitation
% CEA Explorer et comprendre l'Univers
% 12 octobre 2020
---
theme: beige
transition: linear
---
## Pourquoi les planètes du système solaire bougent-elles sur des orbites elliptiques?
---
### Galilée
*(1564 — 1642)*
La gravité agit de la même façon sur tous les corps à la surface de la Terre.
---
<figure>
<a href="https://commons.wikimedia.org/wiki/File:Piazza_dei_Miracoli_-_The_Cathedral_and_the_Leaning_Tower_in_Pisa_(2).jpg">
<img src="../../images/tower_pisa.jpg"
alt="Tour de Pise d'où Galilée aurait soi disant-laissé tomber deux boulets de masses différentes."
style="
max-height: 500px;
max-width: 1000px;
">
</a>
<figcaption style="font-size: 0.4em; color: #666;">
(Dudva [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/deed.en))
</figcaption>
</figure>
---
<iframe
src="//commons.wikimedia.org/wiki/File:Apollo_15_feather_and_hammer_drop.ogv?embedplayer=yes"
width="654" height="480" frameborder="0" webkitAllowFullScreen
mozallowfullscreen allowFullScreen>
</iframe>
<figcaption style="font-size: 0.4em; color: #666;">
Dave Scott, Apollo 15 (NASA)
</figcaption>
---
<iframe width="560" height="315"
src="https://www.youtube.com/embed/E43-CfukEgs" frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen>
</iframe>
---
### Galilée (encore)
**Principe d'inertie** (v. 1.0)
*En l'absence de toute contrainte et de toute force, un objet en mouvement
continuera sur sa lancée horizontale pour toujours.*
Les planètes continuent a parcourir leur orbite pour toujours.
---
### René Descartes
*(1596 — 1650)*
<figure>
<a title="After Frans Hals (1582/1583–1666) [Public domain], via Wikimedia Commons"
href="https://commons.wikimedia.org/wiki/File%3AFrans_Hals_-_Portret_van_Ren%C3%A9_Descartes.jpg">
<img src="../../images/descartes.jpg"
alt="Portrait de René Descartes par Frans Hals."
style="
max-height: 450px;
max-width: 1000px;
">
</a>
</figure>
---
### René Descartes
**Principe d'inertie** (v. 2.0)
*Les objets se déplacent en ligne droite à vitesse constante tant et aussi
longtemps qu'aucune force n'agit sur eux.*
---
### Il doit donc y avoir une force qui tire les planètes vers le Soleil
---
### Isaac Newton
*(1642 — 1727)*
<figure>
<a title="Sir Godfrey Kneller [Public domain], via Wikimedia Commons"
href="https://commons.wikimedia.org/wiki/File%3AGodfreyKneller-IsaacNewton-1689.jpg">
<img src="../../images/newton.jpg"
alt="Portrait d'Isaac Newton par Godfrey Kneller."
style="
max-height: 450px;
max-width: 1000px;
">
</a>
</figure>
---
### Isaac Newton
#### Quelle est la force qui tire continuellement les planètes vers le Soleil et les maintient sur leur orbite?
---
### Première loi de la mécanique
**Principe d'inertie** (v. 2.0)
*Les objets se déplacent en ligne droite à vitesse constante tant et aussi
longtemps qu'aucune force n'agit sur eux.*
---
### Deuxième loi de la mécanique
L'accélération subit par un corps est proportionnelle à la force nette
appliquée à ce corps et inversement proportionnelle à la masse du corps.
---
### Troisième loi de la mécanique
Toute force exercée par un objet A sur un objet B est accompagnée d'une force
exercée par l'objet B sur l'objet A qui a la même grandeur et est dans la
direction opposée.
---
### La force qui maintient les planètes en orbite autour du Soleil est la même qui fait tomber les objets à la surface de la Terre
---
### Interlude : Newton et la pomme
<figure>
<a href="https://fr.wikipedia.org/wiki/Fichier:Newton%27s-apple.jpg">
<img src="../../images/Newton-apple.jpg"
alt="Newton et la pomme"
style="
max-height: 500px;
max-width: 1000px;
">
</a>
<figcaption style="font-size: 0.4em; color: #666;">
(Alexander Borek [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/deed.fr))
</figcaption>
</figure>
---
### Loi de la gravitation universelle de Newton
$$F = \frac{G m_1 m_2}{r^2}$$
---
<iframe width="800px" height="600px"
src="https://lab.loicseguin.com/schroeder/index.html">
</iframe>
---
### Isaac Newton
Publication de ses résultats dans les *Philosophiae Naturalis Principia
Mathematica*
---
### Succès de la théorie newtonienne
Permet d'expliquer tous les phénomènes célestes observés
Prédit de nouveaux phénomènes
---
### Prédiction de la trajectoire d'une comète par Edmund Halley
<a title="By NASA/W. Liller [Public domain], via Wikimedia Commons"
href="https://commons.wikimedia.org/wiki/File%3ALspn_comet_halley.jpg"><img
width="512" alt="Lspn comet halley"
src="//upload.wikimedia.org/wikipedia/commons/2/2a/Lspn_comet_halley.jpg"/></a>
---
### Étude des systèmes binaires par Caroline et William Herschel
<figure>
<a href="https://wellcomecollection.org/works/dmbmc538">
<img src="../../images/herschels.jpg"
alt="Caroline et William Herschel polissant un miroir"
style="
max-height: 450px;
max-width: 1000px;
">
</a>
<figcaption style="font-size: 0.4em; color: #666;">
Wellcome Collection ([CC BY 4.0](https://creativecommons.org/licenses/by/4.0/))
</figcaption>
</figure>
---
### Découverte de nouvelles planètes
>- Découverte d'Uranus en 1781 par William Herschel
>- L'orbite d'Uranus est bizarre...
>- J. C. Adams et Urbain Le Verrier prédisent l'existence d'une autre planète
>- Neptune découverte en 1846 par J. G. Galle à l'endroit prédit par Adams et Le Verrier
---
## Problème avec la théorie newtonienne
Perturbation dans l'orbite de Mercure qui ne s'explique d'aucune façon...
---
### Albert Einstein
*(1879 — 1955)*
<a title="By Lucien Chavan / ETH Zürich (ETH-Bibliothek Zürich, Bildarchiv)
[CC-BY-SA-3.0 (http://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia
Commons"
href="http://commons.wikimedia.org/wiki/File%3AAlbert_Einstein_ETH-Bib_Portr_05937.jpg"><img
width="256" alt="Albert Einstein ETH-Bib Portr 05937"
src="../../images/Albert_Einstein.jpg"/></a>
---
### Albert Einstein
- Essaie de réconcilier le principe de relativité galiléenne et
l'électrodynamisme
- Essaie d'expliquer pourquoi toutes les mesures de la vitesse de la lumière
donnent la même valeur
<br />
>- Il ne tente pas d'expliquer l'orbite de Mercure
---
### Relativité restreinte
*(1905)*
Deux postulats
- Le principe de relativité
- La constance de la vitesse de la lumière
---
### Relativité restreinte
- Espace et temps ne sont plus absolus
- Dilatation du temps et contraction des longueurs
- Facteur de ralentissement du temps
$$\gamma = \frac{1}{\sqrt{1 - \frac{v^2}{c^2}}}$$
---
### Relativité restreinte
- Dilatation du temps et contraction des longueurs deviennent plus importante
lorsqu'on s'approche de la vitesse de la lumière
- Les objets massifs ne peuvent jamais atteindre la vitesse de la lumière
---
### Relativité restreinte
Équivalence masse-énergie
$$E = \gamma m c^2$$
---
### Albert Einstein
La même année (1905), il publie 4 découvertes fondamentales :
- L'effet photoélectrique
- Le mouvement brownien
- La relativité restreinte
- L'équivalence masse-énergie
<br />
C'est l'*Annus Mirabilis*.
---
### Relativité générale
*(1916)*
- Extension de la relativité restreinte à des référentiels accélérés
- En plus des deux postulats de la relativité restreinte, Einstein ajoute le
**principe d'équivalence**
*Il n'y a pas de différence entre la gravité et un référentiel accéléré.*
---
### Principe d'équivalence
<figure>
<img src="../../images/principe_equivalence.png"
alt="Principe d'équivalence"
style="
padding: 10px;
max-height: 500px;
max-width: 1000px;
">
</figure>
---
### Relativité générale
- La masse déforme l'**espace-temps**
- Ces déformations sont la cause de la gravitation
---
### Relativité générale
- Près du Soleil, la courbure de l'espace est très importante
- Mercure est près du Soleil!
- Einstein prédit les perturbations de l'orbite de Mercure
---
## Autres succès de la relativité générale
---
### Lentilles gravitationnelles
<a href="https://hubblesite.org/contents/media/images/1990/20/22-Image.html?news=true">
<img alt="Croix d'Einstein G2237+0305"
src="../../images/g2237+0305.jpg"
style="
max-height: 500px;
max-width: 1000px;
"
/>
</a>
---
<figure>
<a href="https://apod.nasa.gov/apod/ap111221.html">
<img src="../../images/lensshoe_hubble_3235.jpg"
alt="Lentille gravitationnelle LRG 3-757 photographiée par Hubble"
style="
max-height: 600px;
max-width: 1000px;
">
</a>
<figcaption style="font-size: 0.4em; color: #666;">
LRG 3-757 photographiée par Hubble. (ESA/Hubble & NASA)
</figcaption>
</figure>
---
<figure>
<a href="https://www.spacetelescope.org/images/potw1506a/">
<img src="../../images/potw1506a.jpg"
alt="Amas de galaxies causant un effet de lentille gravitationnelle"
style="
max-height: 600px;
max-width: 1000px;
">
</a>
<figcaption style="font-size: 0.4em; color: #666;">
(NASA/ESA).
</figcaption>
</figure>
---
### Trous noirs
- La relativité générale ajoute un ralentissement du temps dû à la gravité.
- Ce ralentissement dépend de la vitesse de libération
- Si la vitesse de libération est celle de la lumière, ralentissement infini
---
### Trous noirs
Les objets pour lesquels la vitesse de libération est celle de la lumière sont
appelés des **trous noirs**.
---
### Trous noirs supermassifs
<a href="https://www.nasa.gov/multimedia/imagegallery/image_feature_2247.html">
<img alt="Active Black Hole Squashes Star Formation"
src="../../images/PIA15625.jpg"
style="
max-height: 500px;
max-width: 1000px;
">
</a>
<figcaption style="font-size: 0.4em; color: #666;">
NASA/JPL-Caltech
</figcaption>
---
<figure>
<a href="https://www.nasa.gov/feature/goddard/2019/nasa-visualization-shows-a-black-hole-s-warped-world">
<img src="../../images/bh_accretiondisk_sim_stationary_websize.gif"
alt="Simulation d'un trou noir avec disque d'acrétion"
style="
max-height: 500px;
max-width: 1000px;
">
</a>
<figcaption style="font-size: 0.4em; color: #666;">
NASA’s Goddard Space Flight Center/Jeremy Schnittman
</figcaption>
</figure>
---
<figure>
<a href="https://www.eso.org/public/images/eso1907a/">
<img src="../../images/eso1907a.jpg"
alt="Trou noir M87* au centre de la galaxie M87"
style="
max-height: 500px;
max-width: 1000px;
">
</a>
<figcaption style="font-size: 0.4em; color: #666;">
EHT Collaboration
</figcaption>
</figure>
---
## Le futur...
>- Pour expliquer la vitesse de rotation des galaxies, il manque de la masse!
C'est la **matière sombre** qui compose environ 27% de la masse dans
l'Univers.
>- L'expansion de l'Univers est trop rapide! Il faut de l'**énergie sombre**
pour l'expliquer. L'énergie sombre représente 68% de la masse dans
l'Univers.
---
## Le futur...
On ne sait pas de quoi est composé 95% de l'Univers...
Il reste beaucoup à faire!
|
Python
|
UTF-8
| 3,713 | 2.59375 | 3 |
[] |
no_license
|
import logging, time
class DexTrader:
def __init__(self,exchange,web3_providor):
self.client = exchange
self.w3 = web3_providor
self.account = self.client.account
def AmountSlippage(self,pair_contract,slippage):
first_token = self.w3.toChecksumAddress(pair_contract.functions.token0().call())
if first_token == self.client.currency:
reserves = pair_contract.functions.getReserves().call()
shitcoin = float(self.w3.fromWei(reserves[1], 'ether'))
limit = (0.01 * shitcoin) / (1 - (slippage/100))
return self.w3.toWei(limit, 'ether')
else:
reserves = pair_contract.functions.getReserves().call()
shitcoin = float(self.w3.fromWei(reserves[0], 'ether'))
limit = (0.01 * shitcoin) / (1 - (slippage/100))
return self.w3.toWei(limit, 'ether')
def getTokenBalance(self,token_contract):
balance = token_contract.functions.balanceOf(self.account).call()
return balance
def getPath(self,pair_contract, mode):
token0 = self.w3.toChecksumAddress(pair_contract.functions.token0().call())
token1 = self.w3.toChecksumAddress(pair_contract.functions.token1().call())
if mode == 'buy':
if token0 == self.client.currency:
path = [token0,token1]
else:
path = [token1,token0]
elif mode == 'sell':
if token0 == self.client.currency:
path = [token1,token0]
else:
path = [token0,token1]
return path
def getBalance(self):
balance = self.w3.eth.getBalance(self.account)
gas_money = self.w3.toWei(0.1,'ether')
return balance - gas_money
def getTradeAmount(self):
balance = self.getBalance()
lowest_amount_allowed = self.w3.toWei(2.5,'ether')
if balance >= lowest_amount_allowed:
return balance
else:
return None
def tx_isValid(self,tx_hash):
hex_hash = self.w3.toHex(tx_hash)
while True:
try:
receipt = self.w3.eth.getTransactionReceipt(hex_hash)
receipt_dict = dict(receipt)
status = receipt_dict.get('status')
break
except:
time.sleep(10)
if status == 1:
return True
else:
return False
def buy(self,pair_contract,price,time):
rsi_value = round(price)
logging.info('BUY: {} at {} RSI'.format(pair_contract,rsi_value))
buy_amount = self.getTradeAmount()
if buy_amount <= self.AmountSlippage(pair_contract,20) and buy_amount != None:
amount = buy_amount
else:
return False
amountl = int(amount/price)
amountmin = amountl - (int(amountl * 0.03))
path = self.getPath(pair_contract, 'buy')
tx_hash = self.client.swapExactETHForTokens(amount,amountmin,path)
time.sleep(10)
validity = tx_hash(self.tx_isValid(tx_hash))
if validity == True:
return True
else:
return False
return True
def sell(self,token_contract,price,time):
if self.client.isApproved(token_contract) == False:
self.client.approve(token_contract)
time.sleep(10)
amount = self.getTokenBalance(token_contract)
amount_min = int(price * (amount - (amount * 0.05)))
path = self.getPath(token_contract,'sell')
tx_hash = self.client.swapExactTokensForETH(amount,amount_min,path)
return tx_hash
def closePositions(self):
return
|
Markdown
|
UTF-8
| 20 | 2.546875 | 3 |
[] |
no_license
|
# github
tugas push
|
Java
|
UTF-8
| 264 | 1.78125 | 2 |
[] |
no_license
|
package cn.jokang.algorithms.leetcode.test;
import cn.jokang.algorithms.leetcode.ThreeSum;
import org.junit.Test;
public class ThreeSumTest {
@Test
public void test() {
ThreeSum s = new ThreeSum();
s.threeSum(new int[]{-1, 0, 1, 2, -1, -4});
}
}
|
PHP
|
UTF-8
| 1,133 | 2.609375 | 3 |
[] |
no_license
|
<?php
if (! function_exists('style')) {
/**
* 样式别名加载(支持批量加载,后期可拓展为自动多文件压缩合并)
* @return string
*/
function style()
{
$styleArray = array_map(function ($aliases) {
$cssUrl = asset_static($aliases);
return HTML::style($cssUrl);
}, func_get_args());
return implode('', array_filter($styleArray));
}
}
if (! function_exists('script')) {
/**
* 脚本别名加载(支持批量加载,后期可拓展为自动多文件压缩合并)
* @return string
*/
function script()
{
$scriptArray = array_map(function ($aliases) {
$jsUrl = asset_static($aliases);
return HTML::script($jsUrl);
}, func_get_args());
return implode('', array_filter($scriptArray));
}
}
if(!function_exists("is_pjax")){
/**
* 是否是pjax请求
*
*/
function is_pjax()
{
if(array_key_exists('HTTP_X_PJAX', $_SERVER) && $_SERVER['HTTP_X_PJAX'] === 'true')
return true;
return false;
}
}
|
JavaScript
|
UTF-8
| 849 | 3.984375 | 4 |
[] |
no_license
|
// Square that changes size when you scroll the page
// Wraz ze skrollowaniem strony zmniejsza się lub zwiększa wielkość czarnego kwadratu.
const square = document.createElement("div");
document.body.appendChild(square);
let grow = true; // flaga
let size = 100; // wielkość kwadratu
square.style.width = size + "px";
square.style.height = size + "px";
const changeTheSize = function () {
if (size >= window.innerWidth / 2) {
grow = !grow; // grow = false;
} else if (size <= 0) {
grow = !grow; // grow = true;
}
if (grow) {
size += 6;
square.style.width = size + "px";
square.style.height = size + "px";
} else {
size -= 6;
square.style.width = size + "px";
square.style.height = size + "px";
}
}
window.addEventListener("scroll", changeTheSize);
|
Swift
|
UTF-8
| 1,925 | 2.71875 | 3 |
[] |
no_license
|
import Foundation
extension Array where Element == Blocker.Rule {
var compress: Self {
self
.filter {
$0.trigger == .all || $0.trigger == .script
}
+ self
.filter {
$0.trigger != .all && $0.trigger != .script
}
.reduce(into: [URL.Allow : Set<String>]()) {
if case let .css(css) = $1.action,
case let .url(url) = $1.trigger {
$0[url, default: []].formUnion(css)
}
}
.map {
.init(trigger: .url($0.0), action: .css($0.1))
}
}
var content: String {
"[" + map {
"""
{
"action": {
\($0.action.content)
},
"trigger": {
\($0.trigger.content)
}
}
"""
}
.joined(separator: ",") + "]"
}
}
private extension Blocker.Rule.Action {
var content: String {
switch self {
case .cookies:
return """
"type": "block-cookies"
"""
case .http:
return """
"type": "make-https"
"""
case .block:
return """
"type": "block"
"""
case let .css(css):
return """
"type": "css-display-none",
"selector": "\(css.joined(separator: ", "))"
"""
}
}
}
private extension Blocker.Rule.Trigger {
var content: String {
switch self {
case .all:
return """
"url-filter": ".*"
"""
case .script:
return """
"url-filter": ".*",
"load-type": ["third-party"],
"resource-type": ["script"]
"""
case let .url(url):
return """
"url-filter": "^https?://+([^:/]+\\\\.)?\(url.rawValue)\\\\.\(url.tld)[:/]",
"url-filter-is-case-sensitive": true,
"if-domain": ["*\(url.rawValue).\(url.tld.rawValue)"],
"load-type": ["first-party"],
"resource-type": ["document"]
"""
}
}
}
|
C++
|
UTF-8
| 501 | 3.265625 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int n; //size of array
cin >> n;
int arr[n];
// taking input in arr
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int max = arr[0], min = arr[0];
for (int i = 1; i < n; i++) {
if (max < arr[i])
max = arr[i];
if (min > arr[i])
min = arr[i];
}
cout << "Maximum Value = " << max << "\n";
cout << "Minimum Value = " << min;
return 0;
}
|
Java
|
UTF-8
| 247 | 1.820313 | 2 |
[] |
no_license
|
package common;
public class Constants
{
public static String finalProfileDataTextFile = System.getProperty("user.dir")+"/src/Resources/FinalProfileData.txt";
public static String dataPropertiesFile = "src/Resources/data.properties" ;
}
|
Go
|
UTF-8
| 287 | 3.625 | 4 |
[] |
no_license
|
package main
import "fmt"
func main() {
i := 1
for i < 5 {
fmt.Println(i)
i++
}
for j := 1; j < 10; j++ {
fmt.Println(j)
}
for {
fmt.Println("loop")
i++
if i > 10 {
break
}
}
for k, v := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} {
fmt.Println(k, v)
}
}
|
Ruby
|
UTF-8
| 715 | 2.65625 | 3 |
[] |
no_license
|
require 'test_helper'
class CartTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
fixtures :products
def new_cart_with_one_product(product_name)
cart = Cart.create
cart.add_product(products(product_name).id)
cart
end
test "cart should create a new line item" do
cart = new_cart_with_one_product(:one)
puts '1 Line Items: '
puts cart.line_items
assert_equal 1, cart.line_items.size
cart.add_product(products(:ruby).id)
puts '2 Line Items: '
puts cart.line_items
assert_equal 2, cart.line_items.size
cart.add_product(products(:one).id)
puts '3 Line Items: '
puts cart.line_items
assert_equal 2, cart.line_items.size
end
end
|
C++
|
UTF-8
| 2,798 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
//
// Created by flipback on 11/16/19.
//
#include <string>
#include <stdexcept>
#include "EncapsPacket.h"
#include "utils/Buffer.h"
using eipScanner::utils::Buffer;
namespace eipScanner {
namespace eip {
EncapsPacket::EncapsPacket() : _command{EncapsCommands::NOP}
, _length{0}
, _sessionHandle{0}
, _statusCode{EncapsStatusCodes::SUCCESS}
, _context(8)
, _options{0}
, _data(0) {
}
EncapsPacket::~EncapsPacket() = default;
void EncapsPacket::expand(const std::vector<uint8_t> &data) {
if (data.size() < HEADER_SIZE) {
throw std::runtime_error("EncapsPacket header must be 24 bytes");
}
Buffer buffer(data);
buffer >> reinterpret_cast<cip::CipUint&>(_command)
>> _length
>> _sessionHandle
>> reinterpret_cast<cip::CipUdint&>(_statusCode)
>> _context
>> _options;
auto dataSize = data.size() - HEADER_SIZE;
if (dataSize != _length) {
throw std::runtime_error("EncapsPacket data must be " + std::to_string(_length)
+ " but we have only " + std::to_string(dataSize) + " bytes");
}
_data.resize(_length);
buffer >> _data;
}
std::vector<uint8_t> EncapsPacket::pack() const {
Buffer buffer;
buffer << static_cast<cip::CipUint>(_command)
<< _length
<< _sessionHandle
<< static_cast<cip::CipUdint>(_statusCode)
<< _context
<< _options
<< _data;
return buffer.data();
}
EncapsCommands EncapsPacket::getCommand() const {
return _command;
}
void EncapsPacket::setCommand(EncapsCommands command) {
_command = command;
}
cip::CipUint EncapsPacket::getLength() const {
return _length;
}
cip::CipUdint EncapsPacket::getSessionHandle() const {
return _sessionHandle;
}
void EncapsPacket::setSessionHandle(cip::CipUdint sessionHandle) {
_sessionHandle = sessionHandle;
}
EncapsStatusCodes EncapsPacket::getStatusCode() const {
return _statusCode;
}
void EncapsPacket::setStatusCode(EncapsStatusCodes statusCode) {
_statusCode = statusCode;
}
const std::vector<uint8_t> &EncapsPacket::getData() const {
return _data;
}
void EncapsPacket::setData(const std::vector<uint8_t> &data) {
_data = data;
_length = data.size();
}
size_t EncapsPacket::getLengthFromHeader(const std::vector<uint8_t>& data) {
std::vector<uint8_t> lengthVector(data.begin() + 2, data.begin() + 4);
Buffer buf(lengthVector);
cip::CipUint len;
buf >> len;
return len;
}
bool EncapsPacket::operator==(const EncapsPacket &rhs) const {
return _command == rhs._command &&
_length == rhs._length &&
_sessionHandle == rhs._sessionHandle &&
_statusCode == rhs._statusCode &&
_context == rhs._context &&
_options == rhs._options &&
_data == rhs._data;
}
bool EncapsPacket::operator!=(const EncapsPacket &rhs) const {
return !(rhs == *this);
}
}
}
|
Java
|
UTF-8
| 10,269 | 2.546875 | 3 |
[] |
no_license
|
package ru.berserk.client;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import static ru.berserk.client.Main.main;
// Created by StudenetskiyA on 29.01.2017.
public class UnitLabel extends JLabel {
static final int BorderOval=4;
static final Color NumberColor=Color.red;
static final Color NumberBackColor=Color.gray;
MyFunction.ClickImage tapClick;
public BufferedImage image;
Creature creature;
Color borderInactiveColor=Color.CYAN;
Color borderTappedColor = Color.gray;
Color borderActiveColor = Color.green;
Color borderAlreadyAttackColor = Color.blue;
void setAll(Creature _creature, int _width,int _height){
creature=_creature;
setSize(_width,_height);
try {
image = ImageIO.read(new File("cards/small/"+creature.image.substring(0,creature.image.length()-4)+".png"));
// image = ImageIO.read(new File("cards/small/Гном-легионер.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
UnitLabel(){
super();
}
static int plusSize(){
return BorderOval+4+BorderOval/2;
}
void drawAttackInitiator(Graphics g){
try {
BufferedImage tap = ImageIO.read(new File("icons/effects/attackinitiator.png"));
g.drawImage(tap, getCenterX()-getWidth()/4, getCenterY()-getWidth() / 2, getWidth() / 2, getWidth() / 2, null);
} catch (IOException e) {
e.printStackTrace();
}
}
void drawAttackTarget(Graphics g){
try {
BufferedImage tap = ImageIO.read(new File("icons/effects/attacktarget.png"));
g.drawImage(tap, getCenterX()-getWidth()/4, getCenterY()-getWidth() / 2, getWidth() / 2, getWidth() / 2, null);
} catch (IOException e) {
e.printStackTrace();
}
}
void drawImage(Graphics g){
if (isVisible()) {
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(image, getX(), getY(), getWidth()+1, getHeight()+1, null);
if (creature.getIsSummonedJust() && !creature.isTapped)
g2.setColor(borderInactiveColor);
else if (!creature.getIsSummonedJust() && !creature.isTapped && !creature.attackThisTurn) g2.setColor(borderActiveColor);
else if (!creature.getIsSummonedJust() && !creature.isTapped && creature.attackThisTurn) g2.setColor(borderAlreadyAttackColor);
else g2.setColor(borderTappedColor);
g2.setStroke(new BasicStroke(BorderOval));
g2.drawOval(getX()-BorderOval/2,getY()-BorderOval/2,getWidth()+BorderOval,getHeight()+BorderOval);
g2.setColor(Color.BLACK);
g2.setStroke(new BasicStroke(2));
g2.drawOval(getX()-BorderOval/2-2,getY()-BorderOval/2-2,getWidth()+BorderOval+4,getHeight()+BorderOval+4);
g2.drawOval(getX()-BorderOval/2+2,getY()-BorderOval/2+2,getWidth()+BorderOval-4,getHeight()+BorderOval-4);
int down=getCenterY()+getHeight()/2+BorderOval/2+1;
int up=getCenterY()-getHeight()/2-BorderOval/2-1;
g2.setColor(Color.BLACK);
g2.drawRect(getCenterX()-getWidth()/4-getWidth()/3-1,down-getWidth()/3-1,getWidth()/3+1,getWidth()/3+1);
g2.drawRect(getCenterX()+getWidth()/4-1,down-getWidth()/3-1,getWidth()/3+1,getWidth()/3+1);
g2.setColor(NumberBackColor);
g2.fillRect(getCenterX()-getWidth()/4-getWidth()/3,down-getWidth()/3,getWidth()/3,getWidth()/3);
g2.fillRect(getCenterX()+getWidth()/4,down-getWidth()/3,getWidth()/3,getWidth()/3);
//20 for 688 - for Serif
int fs=main.getWidth()*20/890;
Font font = new Font("Serif", Font.BOLD, fs);
Rectangle att = new Rectangle(getCenterX()-getWidth()/4-getWidth()/3,down-getWidth()/3,getWidth()/3,getWidth()/3);
setColorBonusOrMinus(g2,creature.getBonusOrMinusPower());
// System.out.println("BMpower="+creature.getBonusOrMinusPower());
drawCenteredString(g2,String.valueOf(creature.getPower()),att,font);
att = new Rectangle(getCenterX()+getWidth()/4,down-getWidth()/3,getWidth()/3,getWidth()/3);
setColorBonusOrMinus(g2,creature.getBonusOrMinusTougness());
drawCenteredString(g2,String.valueOf(creature.getTougness()-creature.damage),att,font);
if (creature.text.contains("ТАП")) {
g2.setColor(Color.BLACK);
g2.drawRect(getCenterX()+getWidth()/4-1,up,getWidth()/3+1,getWidth()/3+1);
g2.setColor(NumberBackColor);
g2.fillRect(getCenterX()+getWidth()/4,up,getWidth()/3,getWidth()/3);
try {
tapClick.image= ImageIO.read(new File("icons/effects/tap.png"));
tapClick.LSD(g2, getCenterX() + getWidth() / 4, up, getWidth() / 3, getWidth() / 3);
} catch (IOException e) {
e.printStackTrace();
}
}
//TODO Calculate effects count.
int effectsX=getCenterX()-getWidth()/6;
int effectsY=down-2*getWidth()/3;
int effectsFounded=0;
if (creature.effects.poison!=0) {
try {
BufferedImage tap = ImageIO.read(new File("icons/effects/poison"+creature.effects.poison+".png"));
g2.drawImage(tap, effectsX+effectsFounded*getWidth()/3, effectsY, getWidth() / 3, getWidth() / 3, null);
} catch (IOException e) {
e.printStackTrace();
}
effectsFounded++;
}
if (creature.effects.turnToDie<=2) {
try {
BufferedImage tap = ImageIO.read(new File("icons/effects/dienear.png"));
g2.drawImage(tap, effectsX+effectsFounded*getWidth()/3, effectsY, getWidth() / 3, getWidth() / 3, null);
} catch (IOException e) {
e.printStackTrace();
}
effectsFounded++;
}
if (creature.effects.getVulnerability()) {
try {
BufferedImage tap = ImageIO.read(new File("icons/effects/vulnerability.png"));
g2.drawImage(tap, effectsX+effectsFounded*getWidth()/3, effectsY, getWidth() / 3, getWidth() / 3, null);
} catch (IOException e) {
e.printStackTrace();
}
effectsFounded++;
}
if (creature.effects.bonusArmor!=0) {
try {
//TODO When we have more pictures, replace 3 for N.
BufferedImage tap = ImageIO.read(new File("icons/effects/bonusarmor3.png"));
g2.drawImage(tap, effectsX+effectsFounded*getWidth()/3, effectsY, getWidth() / 3, getWidth() / 3, null);
} catch (IOException e) {
e.printStackTrace();
}
effectsFounded++;
}
if (creature.effects.changeControl) {
try {
BufferedImage tap = ImageIO.read(new File("icons/effects/changecontrol.png"));
g2.drawImage(tap, effectsX+effectsFounded*getWidth()/3, effectsY, getWidth() / 3, getWidth() / 3, null);
} catch (IOException e) {
e.printStackTrace();
}
effectsFounded++;
}
if (creature.effects.getBonusToShoot()!=0) {
try {
BufferedImage tap = ImageIO.read(new File("icons/effects/bonustoshoot.png"));
g2.drawImage(tap, effectsX+effectsFounded*getWidth()/3, effectsY, getWidth() / 3, getWidth() / 3, null);
} catch (IOException e) {
e.printStackTrace();
}
effectsFounded++;
}
if (!creature.effects.additionalText.equals("")) {
if (creature.effects.additionalText.contains("Не может атаковать. Не может блокировать.")) {
try {
BufferedImage tap = ImageIO.read(new File("icons/effects/cantattactorblock.png"));
g2.drawImage(tap, effectsX+effectsFounded*getWidth()/3, effectsY, getWidth() / 3, getWidth() / 3, null);
} catch (IOException e) {
e.printStackTrace();
}
effectsFounded++;
}
//Unknowed additional text
else {
try {
BufferedImage tap = ImageIO.read(new File("icons/effects/additionaltext.png"));
g2.drawImage(tap, effectsX + effectsFounded * getWidth() / 3, effectsY, getWidth() / 3, getWidth() / 3, null);
} catch (IOException e) {
e.printStackTrace();
}
effectsFounded++;
}
}
//TODO if effects more than can be placed on card
}
}
public void drawCenteredString(Graphics g, String text, Rectangle rect, Font font) {
// Get the FontMetrics
FontMetrics metrics = g.getFontMetrics(font);
// Determine the X coordinate for the text
int x = (int)rect.getX()+(rect.width - metrics.stringWidth(text)) / 2;
// Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen)
int y = (int)rect.getY()+((rect.height - metrics.getHeight()) / 2) + metrics.getAscent();
// Set the font
g.setFont(font);
// Draw the String
g.drawString(text, x, y);
}
int getCenterX(){
return getX()+getWidth()/2;
}
int getCenterY(){
return getY()+getHeight()/2;
}
void setColorBonusOrMinus(Graphics g,int n){
if (n>0) g.setColor(Color.green);
else if (n<0) g.setColor(Color.RED);
else g.setColor(Color.white);
}
}
|
Swift
|
UTF-8
| 1,859 | 3.109375 | 3 |
[] |
no_license
|
//
// Bombe.swift
// Mnigma
//
// Created by Leo Mehlig on 2/19/15.
// Copyright (c) 2015 Leo Mehlig. All rights reserved.
//
import Foundation
class Bombe {
func decodeText(encodedText: String, guessedWords: [String]) -> (decodedText: String, usedEnigma: Enigma)? {
let unmatchingWords = unmatchingWordsDictFromText(encodedText, forWords: guessedWords)
return nil
}
//Unmacthing Words
func unmatchingWordsDictFromText(text: String, forWords wordAry: [String]) -> [String: [String]] {
var unmatchDict = [String: [String]]()
for word in wordAry {
let m = completUnmatchingPartsOfText(text, toWord: word)
if m.count > 0 {
unmatchDict[word] = m
}
}
return unmatchDict
}
func completUnmatchingPartsOfText(text: String, toWord word: String) -> [String] {
var matchingDecodedStrings = [String]()
let textStr = NSString(string: text)
textLoop: for idx in 0..<(count(text)-count(word)) {
let p = text[idx..<idx+count(word)]
for (i, c) in enumerate(p) {
if c == word[i]{
continue textLoop
}
}
matchingDecodedStrings.append(p)
}
return matchingDecodedStrings
}
}
extension String {
subscript (r: Range<Int>) -> String {
get {
let subStart = advance(self.startIndex, r.startIndex, self.endIndex)
let subEnd = advance(subStart, r.endIndex - r.startIndex, self.endIndex)
return self.substringWithRange(Range(start: subStart, end: subEnd))
}
}
subscript (idx: Int) -> Character {
get {
let s = self[idx..<idx+1]
for c in s { return c }
return "x"
}
}
}
|
C++
|
UTF-8
| 1,566 | 2.53125 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
#include "func_thread.h"
#include "info_router.h"
FuncThread::FuncThread(std::shared_ptr<InfoRouter>& router):
_func_router(router) {
}
FuncThread::~FuncThread() {
}
void FuncThread::Run() {
while (!_stop) {
auto t = Pop();
if (t) {
if (CallFunc(t->_func_name, t->_func_param_ret)){
_func_router->PushRet(t);
}
} else {
continue;
}
}
}
void FuncThread::Stop() {
_stop = true;
Push(nullptr);
}
bool FuncThread::RegisterFunc(const std::string& name, const CommonFunc& func) {
std::unique_lock<std::mutex> lock(_mutex);
if (_func_map.count(name)) {
return false;
}
_func_map[name] = func;
return true;
}
bool FuncThread::RemoveFunc(const std::string& name) {
std::unique_lock<std::mutex> lock(_mutex);
auto iter = _func_map.find(name);
if (iter != _func_map.end()) {
_func_map.erase(iter);
return true;
}
return false;
}
CommonFunc FuncThread::FindFunc(const std::string& name) {
std::unique_lock<std::mutex> lock(_mutex);
auto iter = _func_map.find(name);
if (iter != _func_map.end()) {
return iter->second;
}
return nullptr;
}
bool FuncThread::CallFunc(const std::string& name, std::vector<cppnet::Any>& param_ret) {
auto iter = _func_map.find(name);
if (iter == _func_map.end()) {
return false;
}
//client responsible for parameter verification
//so can direct call here
param_ret = iter->second(param_ret);
return true;
}
|
Java
|
UTF-8
| 1,882 | 2.28125 | 2 |
[] |
no_license
|
package fr.afpa.formation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import fr.afpa.formation.business.service.SpecieService;
import fr.afpa.formation.persistence.entity.Specie;
import fr.afpa.formation.persistence.repository.AnimalRepository;
import fr.afpa.formation.persistence.repository.PersonRepository;
import fr.afpa.formation.persistence.repository.SpecieRepository;
@SpringBootApplication
public class Application implements CommandLineRunner{
@Autowired
SpecieRepository specieRepository;
@Autowired
AnimalRepository animalRepository;
@Autowired
PersonRepository personRepository;
@Autowired
SpecieService specieService;
private Log log = LogFactory.getLog(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
log.info("Application Animal");
// long idSpecie = 1L;
// String commonName = "Saïd";
// String latinName = "Saïdus";
// log.info(specieRepository.findById(idSpecie).get().toString());
// Specie specie = new Specie(commonName,latinName);
// specieRepository.save(specie);
// log.info(animalRepository.findById(idSpecie).get().toString());
// log.info(personRepository.findById(5L).get().toString());
// Animal animal = animalRepository.findById(2L).get();
// Person person = new Person("Nathan", "Lepers", 23);
// person.getListAnimal().add(animal);
// personRepository.save(person);
// log.info(person.getId());
// personRepository.deleteById(person.getId());
specieService.create(new Specie("test","test"));
}
}
|
JavaScript
|
UTF-8
| 384 | 3.046875 | 3 |
[] |
no_license
|
function Grid() {
}
Grid.prototype.generate = function () {
var board = [];
for (var i = 0; i < 8; i++) {
board.push([]);
for (var j = 0; j < 8; j++) {
board[i].push(bombOrEmpty());
}
}
return board;
};
function bombOrEmpty() {
return Math.random() > 0.9 ? 'bomb' : 'empty';
}
var module = module || {};
module.exports = Grid;
|
TypeScript
|
UTF-8
| 449 | 2.765625 | 3 |
[] |
no_license
|
import express from "express"
import getCity from "../services/getCity"
import getWeatherCity from "../services/getWeatherCity"
const route = express.Router()
/**
* route that returns current weather by city
*/
route.get("/:city?", async(req, res) => {
try {
const city = await getCity(req.params.city)
const weather = await getWeatherCity(city)
res.send(weather)
} catch(error) {
res.send(error)
}
})
export default route
|
Python
|
UTF-8
| 438 | 2.859375 | 3 |
[] |
no_license
|
import bpy
def create_material(name, color, alpha):
"""Create material with color"""
material = bpy.data.materials.new(name)
material.diffuse_color = color
material.alpha = alpha
return material
def set_material(object, material):
"""Set material at object"""
obj_data = object.data
if obj_data.materials:
obj_data.materials[0] = material
else:
obj_data.materials.append(material)
|
C++
|
UTF-8
| 795 | 2.59375 | 3 |
[] |
no_license
|
/*
* File: engine.h
* Author: spink
*
* Created on 29 January 2015, 08:09
*/
#ifndef ENGINE_H
#define ENGINE_H
#include <define.h>
#include <map>
namespace captive {
namespace engine {
class Engine
{
public:
Engine(std::string libfile);
virtual ~Engine();
bool init();
bool install(uint8_t *base);
uint64_t entrypoint() const { return _entrypoint; }
inline bool lookup_symbol(std::string name, uint64_t& symbol) {
auto sym = symbols.find(name);
if (sym == symbols.end())
return false;
symbol = sym->second;
return true;
}
private:
bool load();
bool loaded;
std::string libfile;
uint8_t *lib;
size_t lib_size;
uint64_t _entrypoint;
std::map<std::string, uint64_t> symbols;
};
}
}
#endif /* ENGINE_H */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.