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
| 679
| 2.46875
| 2
|
[] |
no_license
|
package com.automation.Utils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class UsefulMethods {
public static void waitForVisibilityOfElement(WebDriver driver, WebElement element, int time) {
WebDriverWait wait = new WebDriverWait(driver, time);
wait.until(ExpectedConditions.visibilityOf(element));
}
public static void waitForInvisibilityOfElement(WebDriver driver, WebElement element, int time) {
WebDriverWait wait = new WebDriverWait(driver, time);
wait.until(ExpectedConditions.invisibilityOf(element));
}
}
|
Shell
|
UTF-8
| 286
| 2.546875
| 3
|
[] |
no_license
|
#!/bin/sh
if [ -d "work" ]; then
sudo rm -fr work
fi
echo "Create database volume..."
mkdir -p work/data
sudo chcon -Rt container_file_t work
podman unshare chown -R 27:27 work
# TODO Add podman run for mysql image here
sleep 9
# TODO Add podman run for todonodejs image here
|
Go
|
UTF-8
| 714
| 2.8125
| 3
|
[] |
no_license
|
package usecase
import (
"github.com/hikaru7719/receipt-rest-api/domain/model"
"testing"
)
func TestReceiptUsecase_GetReceipt(t *testing.T) {
usecaseTest := NewReceiptUsecase(&ReceiptRepositoryStub{})
actual, err := usecaseTest.GetReceipt(1)
if err != nil {
t.Error("error")
}
if actual.Name != "test" {
t.Error("error")
}
}
type ReceiptRepositoryStub struct{}
func (r *ReceiptRepositoryStub) FindOne(receiptID int) (*model.Receipt, error) {
receipt := &model.Receipt{Name: "test"}
return receipt, nil
}
func (r *ReceiptRepositoryStub) Create(receipt *model.Receipt) (*model.Receipt, error) {
return receipt, nil
}
func (r *ReceiptRepositoryStub) Delete(receiptID int) error {
return nil
}
|
Java
|
UTF-8
| 2,927
| 4.03125
| 4
|
[] |
no_license
|
/**
* Write a description of class Person here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Person
{
// instance variables - replace the example below with your own
private String firstName, secondName;
/**
* Constructor for objects of class Person
*/
public Person(String newFirstName, String newSecondName)
{
// Sets first and second name to the given arguments.
this.firstName = newFirstName;
this.secondName = newSecondName;
}
public Person(String newSecondName)
{
// Sets the second name to the given argument while leaving first name
// blank.
this("", newSecondName);
}
/**
* Setter and getter methods for obects of class Person.
*/
// gets the first and second inital.
public String getInitals()
{
String firstInital = "", secondInital = "";
if (!firstName.equals(""))
{
firstInital = this.firstName.substring(0,1);
}
if (!secondName.equals(""))
{
secondInital = this.secondName.substring(0,1);
}
return firstInital + secondInital;
}
// gets the first name and second name, with a space between them.
public String getName ()
{
String firstName = "", secondName = "";
// this gap will become a space if there is a first name.
String gap = "";
if (!this.firstName.equals(""))
{
firstName = this.firstName;
gap = " ";
}
if (!this.secondName.equals(""))
{
secondName = this.secondName;
}
return firstName + gap + secondName;
}
public void printReverse()
{
int lengthWord = 0;
String toReturn = "";
char[] reversed = new char[0];
// this creats a char array the length of the second name, and populates
// it in reverse order.
lengthWord = this.secondName.length();
reversed = new char[lengthWord];
for (int i =0; i < lengthWord; i++)
{
reversed[i] = this.secondName.charAt(lengthWord-i-1);
}
// this takes the array and converts it into a string.
toReturn = new String(reversed);
// this takes the array and resets it to the length of the first name, and
// populates it in reverse order.
lengthWord = this.firstName.length();
reversed = new char[lengthWord];
for (int i =0; i < lengthWord; i++)
{
reversed[i] = this.firstName.charAt(lengthWord-i-1);
}
// this takes the array and converts it to a string sticking it onto to
// the second name already reversed.
toReturn = toReturn + " " + new String(reversed) ;
System.out.println (toReturn);
}
}
|
C
|
UTF-8
| 841
| 3.5
| 4
|
[] |
no_license
|
#include <stdio.h>
typedef char BYTE;
// program name, original file, output file
int main(int argc, char *argv[])
{
int nOfSegments = 0;
int start = 0;
int end = 0;
BYTE temp;
FILE *inptr = fopen(argv[1], "r");
FILE *outptr = fopen(argv[2], "wb");
printf("How many segments?\n");
scanf("%i", &nOfSegments);
for (int i = 0; i < nOfSegments; i++)
{
printf("Start (inclusive) of segment %i? ", i + 1);
scanf("%i", &start);
printf("End (exclusive) of segment %i? ", i + 1);
scanf("%i", &end);
fseek(inptr, start, SEEK_SET);
for (int j = start; j < end; j++)
{
fread(&temp, sizeof(BYTE), 1, inptr);
fwrite(&temp, sizeof(BYTE), 1, outptr);
}
}
return 0;
}
|
Java
|
UTF-8
| 905
| 3.984375
| 4
|
[] |
no_license
|
package ex02;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MainEx02 {
public static void main(String[] args) {
List<Integer> lista = new ArrayList<>();
lista.add(1);
lista.add(5);
lista.add(5);
lista.add(6);
lista.add(7);
lista.add(8);
lista.add(8);
lista.add(8);
lista.forEach(System.out::println);
System.out.println("-----");
Set<Integer> lista2 = new HashSet<>();
lista2.add(1);
lista2.add(5);
lista2.add(5);
lista2.add(6);
lista2.add(7);
lista2.add(8);
lista2.add(8);
lista2.add(8);
lista2.forEach(System.out::println);
// Lista permite a repetição dos números. Já o método Set não permite, imprimindo apenas uma vez cada número.
}
}
|
C#
|
UTF-8
| 1,410
| 2.609375
| 3
|
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FindClosest : MonoBehaviour
{
private CursorPos cursor;
public BuildGround closestBuildGround;
public float x;
public float y;
private void Start()
{
cursor = GameObject.Find("Canvas").GetComponent<CursorPos>();
}
// Update is called once per frame
void Update()
{
FindClosestBuildGround();
}
public void FindClosestBuildGround()
{
float distanceToClosestBuildGround = Mathf.Infinity;
BuildGround closestBuildGround = null;
BuildGround[] allGrounds = FindObjectsOfType<BuildGround>();
foreach (BuildGround currentBuildGround in allGrounds)
{
float distanceToBuildGround = (currentBuildGround.transform.position - cursor.transform.position).magnitude;
if (distanceToBuildGround < distanceToClosestBuildGround)
{
distanceToClosestBuildGround = distanceToBuildGround;
closestBuildGround = currentBuildGround;
x = closestBuildGround.transform.position.x;
y = closestBuildGround.transform.position.y;
}
}
//Debug.Log(closestBuildGround.transform.position);
//Debug.DrawLine(cursor.transform.position, closestBuildGround.transform.position);
}
}
|
Java
|
UTF-8
| 1,144
| 2.90625
| 3
|
[] |
no_license
|
package com.danwink.simgame;
import java.util.ArrayList;
import java.util.HashMap;
public class SimElement
{
SimElement parent;
String name;
private String fullname;
HashMap<String, SimElement> children = new HashMap<String, SimElement>();
ArrayList<Action> ontick = new ArrayList<Action>();
public void tick()
{
for( String k : children.keySet() )
{
children.get( k ).tick();
}
for( Action a : ontick )
{
a.run();
}
}
public Stock getStock( String name )
{
Stock ret = null;
SimElement e = children.get( name );
if( this instanceof Stock && name.equals( this.name ) )
{
ret = (Stock)this;
}
else if( e != null && e instanceof Stock )
{
ret = (Stock)e;
}
else if( parent != null )
{
ret = parent.getStock( name );
}
return ret;
}
public String getFullName()
{
if( fullname != null ) return fullname;
if( parent != null )
{
String parentname = parent.getFullName();
if( !parentname.equals( "" ) )
{
fullname = parentname + "." + name;
}
else
{
fullname = name;
}
}
else
{
fullname = name;
}
return fullname;
}
}
|
Rust
|
UTF-8
| 839
| 3.953125
| 4
|
[] |
no_license
|
fn main() {
part1();
part2();
part3();
}
fn part1() {
let mut s = String::new();
s.push_str("create_string");
println!("{}", s);
let mut s2 = "initial contents".to_string();
s2.push_str(": test");
println!("{}", s2);
}
fn part2() {
{
let mut s = String::from("foo");
s.push_str("bar");
println!("{}", s);
}
{
let mut s1 = String::from("foo");
let s2 = "bar";
s1.push_str(s2);
println!("s1 is {}", s1);
println!("s2 is {}", s2);
}
{
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = String::from("") + &s1 + &s2;
println!("s3 is {}", s3);
}
}
fn part3() {
let hello = "Hello World";
let slice = &hello[0..3];
println!("slice is {}", slice);
}
|
Java
|
UTF-8
| 1,168
| 1.867188
| 2
|
[] |
no_license
|
package com.bin.easymobilecare.api;
import com.bin.easymobilecare.ApiPojo.BrandCategoryResponse;
import com.bin.easymobilecare.ApiPojo.Login.LoginRequest;
import com.bin.easymobilecare.ApiPojo.Login.LoginStatusResponse;
import com.bin.easymobilecare.ApiPojo.NotificationRequest;
import com.bin.easymobilecare.ApiPojo.NotificationResponse;
import com.bin.easymobilecare.ApiPojo.Signup.SignupRequest;
import com.bin.easymobilecare.ApiPojo.Signup.SignupResponseStatusResponse;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
/**
* Created by pranishshrestha on 5/2/17.
*/
public interface Api {
//@Path use to dend dynamic path
@POST("getNotification")
Call<NotificationResponse> getNotification(@Body NotificationRequest notificationRequest);
// @GET("Categories/discover")
@GET("productsGet")
Call<List<BrandCategoryResponse>> getBrand();
@POST("Account/login")
Call<LoginStatusResponse> getLoginData(@Body LoginRequest loginRequest);
@POST("mobSignUp")
Call<SignupResponseStatusResponse> getSignupData(@Body SignupRequest signupRequest);
}
|
Markdown
|
UTF-8
| 2,616
| 3.03125
| 3
|
[] |
no_license
|
# OGMeet
This project was generated with angular as front-end and spring-boot as back-end.
## Project Description
All students and Faculty can login into Dashboard but the functionality differs. OCMS is a management system for managing student attendance and also faculty attendance and is a means of communication between students and Faculty. They can simply login and attendance will be marked automatically. Ongoing sessions will be displayed. They can use the notes given by the Faculty. Faculty can submit notes, host meetings(optional). Students can view their total attendance. Their average scores and subjects. There’s ADMIN login where admin can login, add new faculty, add new students, add new subjects and vice-versa.
# A student can:
* login
* can view attendance
* can view the notes
* will get meeting update in dashboard
* view subjects
* view his averages
* can have teacher profile and can connect with faculty
* personal text with teacher
# A Teacher can:
* login
* create and remove students
* create and remove subject
* can view attendance
* can set the notes
* can host meeting in dashboard
* view subjects
* set student averages.
* can see all student profile and can connect with student
# ADMIN CAN:
* login
* create and remove students
* create and remove teacher
* create and remove subjects
* can see all students and teachers
## Technologies Used
* Java 8
* HibernateX
* Postgres - version 42.2.22
* Log4j - version 2.14.1
* HTML5
* Bootstrap 5
* Angular 12
* Rest
* SpringBoot
## Features
* Single Page Application
* BootStrap Grid System
* Modals
* Toasting
* Two way binding
## Getting Started
> Download the project from this repository [backend](https://github.com/Sri-va/Project2-backend.git) as well as from the current repository using git clone command in your convenient folder
> Open the Spring Boot project using any of the IDE's like Spring Tool Suite, Eclipse, etc.
> Run the project as SpringBoot App
> Open the Angular application using VS Code and go to the terminal and execute this command **ng serve -o**
> Observe the output on browsers like Microsoft Edge, Google Chrome, Mozilla Firefox, etc.
- Images of what it should look like
[index](https://github.com/Sri-va/Project-2/blob/main/index.jpeg)
## Usage
> You can login as an instructor/student.
> As an instructor, you can view and update your details,
> Host meeting,
> Upload notes if you want,
> If you are a student, it's almost same as above, except hosting the meeting and uploading notes, instead, you can download the notes and join the meeting hosted by the instructor.
|
Java
|
UTF-8
| 321
| 1.5625
| 2
|
[] |
no_license
|
package pl.pwn.reaktor.medoda;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MedodaShopApplication {
public static void main(String[] args) {
SpringApplication.run(MedodaShopApplication.class, args);
}
}
|
Java
|
UTF-8
| 1,417
| 2.03125
| 2
|
[] |
no_license
|
package com.vanilla.healthmanagement.controller;
import com.github.pagehelper.PageInfo;
import com.vanilla.healthmanagement.pojo.Member;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
/*家庭成员管理
* 19-1-2Vanilla
* */
@RestController
@RequestMapping("/member")
public class MemberController {
@Resource
com.vanilla.healthmanagement.service.MemberService MemberService;
@GetMapping("/list")
public PageInfo<Member> getMember(Member member){
List<Member> members =MemberService.getMembers(member);
PageInfo<Member> pageInfo = new PageInfo<>(members);
return pageInfo;
}
@GetMapping("/getAll")
public List<Member> getAll(Member member){
// Member.setActive(1);
return MemberService.getAll(member);
}
@PostMapping("/add")
public int add(Member member){
return MemberService.add(member);
}
@GetMapping("/del")
public int del(Member member){
return MemberService.update(member);
}
@PostMapping("/update")
public int update(@Valid Member member, BindingResult bindingResult){
return MemberService.update(member);
}
@GetMapping("/getOne")
public Member getOne(Integer id){
return MemberService.getMemberById(id);
}
}
|
Rust
|
UTF-8
| 364
| 3.5625
| 4
|
[
"MIT"
] |
permissive
|
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
assert_eq!(result, 20);
let a = [10, 20, 30, 40, 50];
for e in a.iter() {
println!("Value: {}", e);
}
for number in (1..4).rev() {
println!("{}!", number);
}
}
|
Swift
|
UTF-8
| 523
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
//
// MovieListViewModel.swift
// TheMovieApp
//
// Created by CİHAN ÖZTÜRK on 31.01.2021.
// Copyright © 2021 CİHAN ÖZTÜRK. All rights reserved.
//
import Foundation
import UIKit
struct MovieListViewModel {
var imageURL: String?
var title: String?
var isHiddenFavIcon: Bool = true
init(imageURL: String?, title: String?, isHiddenFavIcon: Bool) {
self.imageURL = "https://image.tmdb.org/t/p/w200" + (imageURL ?? "")
self.title = title
self.isHiddenFavIcon = isHiddenFavIcon
}
}
|
C
|
UTF-8
| 1,464
| 2.90625
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <math.h>
#define SAMPLE_RATE 44100 //Hz
#define TIME 10.0 //sec
#define PI 3.141592
float osc_sin(float t){
return sin(2.*PI * t);
}
float osc_sqr(float t){
t = fmod(t,1.0f);
return t < 0.5 ? -1 : 1;
}
float osc_saw(float t){
t = fmod(t,1.0f);
return 2.f * t - 1.;
}
float osc_inv_saw(float t){
t = fmod(t, 1.0f);
return 1. - 2.f * t;
}
float note(float n){
return 440.f * powf(2,(n-24)/12.);
}
float voice0(float t){
return 0.7 * osc_sin(t) + 0.3 * osc_sin(2.f * t);
}
float exp_curve(float t , float k){
if(t < 0.f) return 0.f;
return expf(-k*t);
}
float lin_change(float start, float end, float t){
if(t < 0.f || t > 1.f) return 0.f;
return start * (1.f - t) + end * t;
}
float ar(float rise, float fall, float t){
if(t < 0.f) return 0.f;
if(t < rise) return t/rise;
t -= rise;
return exp(-t*fall);
//if(t < fall) return 1.f - t/fall;
//return 0.f;
}
float temp0(float t){
int p = (int)(4.f*t);
t = fmod(t , .25);
p %= 4;
int n = 0;
if(p == 0) n = 15;
if(p == 1) n = 21;
if(p == 2) n = 19;
if(p == 3) n = 21;
return ar(0.07,20,t) * voice0(note(n)*t);
}
float sound(float t){
return temp0(t);
}
int main(){
int64_t nSamples = (uint64_t)(SAMPLE_RATE * TIME);
for(uint64_t i = 0;i < nSamples;i++){
int16_t sample = (int16_t)(sound(((float)i)/SAMPLE_RATE) * 32000);
write(1, &sample, sizeof(int16_t));
}
return 0;
}
|
Java
|
UTF-8
| 1,875
| 2.390625
| 2
|
[] |
no_license
|
package cn.zup.iot.timerdecision.service.settings;
/**
* 区域类型
* @author samson
*
*/
public enum WeatherType
{
/**
晴
*/
qing(0),
/**
多云
*/
duoyun(1),
/**
阴
*/
yin(2),
/**
阵雨
*/
zhenyu(3),
/**
雷阵雨
*/
leizhenyu(4),
/**
雷阵雨伴有冰雹
*/
leizhenyubanyoubingbao(5),
/**
雨夹雪
*/
yujiaxue(6),
/**
小雨
*/
xiaoyu(7),
/**
中雨
*/
zhongyu(8),
/**
大雨
*/
dayu(9),
/**
暴雨
*/
baoyu(10),
/**
大暴雨
*/
dabaoyu(11),
/**
特大暴雨
*/
tedabaoyu(12),
/**
阵雪
*/
zhenxue(13),
/**
小雪
*/
xiaoxue(14),
/**
中雪 */
zhongxue(15),
/**
大雪
*/
daxue(16),
/**
暴雪
*/
baoxue(17),
/**
雾
*/
wu(18),
/**
冻雨
*/
dongyu(19),
/**
沙尘暴
*/
shachenbao(20),
/**
小雨-中雨
*/
xiaoyuzhongyu(21),
/**
中雨-大雨
*/
zhongyudayu(22),
/**
大雨-暴雨
*/
dayubaoyu(23),
/**
暴雨-大暴雨
*/
baoyudabaoyu(24),
/**
大暴雨特大暴雨
*/
dabaoyutedabaoyu(25),
/**
小雪-中雪
*/
xiaoxuezhongxue(26),
/**
中雪-大雪
*/
zhongxuedaxue(27),
/**
大雪-暴雪
*/
daxuebaoxue(28),
/**
浮沉
*/
fuchen(29),
/**
扬沙
*/
yangsha(30),
/**
强沙尘暴
*/
qiangshachenbao(31),
/**
霾
*/
mai(53);
private int intValue;
private static java.util.HashMap<Integer, WeatherType> mappings;
private synchronized static java.util.HashMap<Integer, WeatherType> getMappings()
{
if (mappings == null)
{
mappings = new java.util.HashMap<Integer, WeatherType>();
}
return mappings;
}
private WeatherType(int value)
{
intValue = value;
WeatherType.getMappings().put(value, this);
}
public int getValue()
{
return intValue;
}
public static WeatherType forValue(int value)
{
return getMappings().get(value);
}
}
|
C#
|
UTF-8
| 1,918
| 2.671875
| 3
|
[
"Apache-2.0"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml.Xsl;
namespace CryptoJokerDecryptor
{
public partial class KeyValidationWindow : Form
{
const int PublicPrivateKeyLength = 2440;
public string PublicPrivateKey = string.Empty;
public KeyValidationWindow()
{
InitializeComponent();
}
private void SubmitDecryptionKeyBtn_Click(object sender, EventArgs e)
{
if (DecryptionKeyTxt.Text.Length == PublicPrivateKeyLength)
{
string decodedPublicPrivateKey = DecodeString(DecryptionKeyTxt.Text);
if (decodedPublicPrivateKey != null && decodedPublicPrivateKey.Contains("<RSAKeyValue>"))
{
PublicPrivateKey = decodedPublicPrivateKey;
this.Close();
}
else
{
MessageBox.Show("The decryption key has bad format.", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("The decryption key has bad format.", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private string DecodeString(string str)
{
try
{
return GetString(Convert.FromBase64String(str));
}
catch (Exception)
{
return null;
}
}
private string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
}
}
|
Python
|
UTF-8
| 1,534
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
"""
Main Function for wol(wiley online library, https://onlinelibrary.wiley.com/)
"""
from toc.toc_wol import WOLTOC
from paper.paper_wol import WOLPaper
from excel.excel import Excel
from openpyxl.styles import Font
def wol(toc_url,
base_url = "https://onlinelibrary.wiley.com",
save_excel = "results/wol.xlsx",
save_mode = 'o',
sheet_name = "wol_papers"):
excel_title = ["题目","作者","发表日期","发表刊物","全文链接","关键词","摘要"]
excel_col_width = {'A': 50, 'B':20, 'C':20, 'D':30, 'E':50, 'F':50, 'G':100}
excel_inst = Excel(save_excel)
toc_inst = WOLTOC(url=toc_url, base_url=base_url)
toc_inst.get_all()
excel_inst.write(sheet_name=sheet_name, data_array=excel_title, write_mode=save_mode)
papers_dict = toc_inst.papers
for key in papers_dict.keys():
print("[+] Info: Paper: {}".format(papers_dict[key]))
paper = WOLPaper(url=papers_dict[key])
paper.get_all()
data_term = [paper.title, paper.authors_to_string(), paper.publish_date, paper.journal_info, paper.url, paper.keywords_to_string(), paper.abstract]
excel_inst.write(sheet_name=sheet_name, data_array=data_term)
excel_inst.set_col_width(sheet_name=sheet_name, cols_width=excel_col_width)
excel_inst.set_row_auto_wraptext_center(sheet_name=sheet_name, all=True)
excel_inst.set_font(sheet_name=sheet_name, font_style=Font(name='Times New Roman'), all=True)
if __name__ == "__main__":
wol()
|
Python
|
UTF-8
| 849
| 2.9375
| 3
|
[
"Apache-2.0"
] |
permissive
|
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# https://github.com/joeyajames/Python/blob/master/Web%20Data%20Mining/Python%20Requests.ipynb
# https://www.youtube.com/watch?v=ChwSD5e0Qs0
import requests
payload = {'page': 2, 'count': 25 }
r = requests.get('https://httpbin.org/get', params=payload)
print('r.text =', r.text)
print('r.url =', r.url)
# post
payload = {'username': 'john', 'count': 'testing' } # se retrouve dans "form"
r = requests.post('https://httpbin.org/post', data=payload)
print('r.text =', r.text)
# auth
# http://httpbin.org/basic-auth/john/testing génère une page qui attend john/testing comme login/passwd
r = requests.get('http://httpbin.org/basic-auth/john/testing', auth=('john','testing'))
print('r.text =', r.text)
# timeout
r = requests.get('http://httpbin.org/delay/6', timeout=3)
print(r)
|
C++
|
UTF-8
| 4,570
| 2.921875
| 3
|
[] |
no_license
|
#ifndef GAMECONTROLLER_H
#define GAMECONTROLLER_H
#include "gamedatamodel.h"
#include <memory>
#include <QObject>
#include <QSizeF>
/** Значение по умолчанию радиуса "пузырей"
*/
const double defaultRadiusOfCircles = 50;
/** Значение по умолчанию времени жизни "пузыря"
*/
const int defaultLifeTimeOfCircles = 5 * 1000;
/** Значение по умолчанию времени роста "пузыря"
*/
const int defaultTimeOfCircleBurn = 500;
/** Значение по умолчанию количества летящих точек.
*/
const uint defaultNumberOfSpots = 10;
/** Значение по умолчанию скорости летящих точек.
*/
const double defaultSpeedOfSports = 60;
/** Как часто обновлять цсену игры.
*/
const int udateSceneInterval = 1000 / 25;
/** Начальное значение радиуса "пузыря". С нго он будет рости до своего нормального радиуса.
*/
const double baseRadiusOfCircle = 0;
/** Содержит логику игры.
*/
class GameController : public QObject {
Q_OBJECT
public:
/** Содержит логику игры.
*
* У всех "пузырей" радиус одинаковый.
* У всех летающих точек одинаковая скорость.
*
* @param gameDataModel Указаель на модель данных игры. Контроллер расчитывает, что экземпляр модели данных существуе, пока существует контроллер.
* @param mRadiusOfCircles Иницирует раздиусь"пузырей"
* @param mLifeTimeOfCircles Инициирует время жизни "пузырей"
* @param timeOfCircleBurn Инициирует время роста "пузырей"
* @param mNumberOfSpots Инициирует количество летающих точек.
* @param mSpeedOfSports Инициирует скорость летающих точек.
* @param parent Указатель на родителя в дереве Qt.
*/
explicit GameController(GameDataModel *gameDataModel, qreal mRadiusOfCircles, long mLifeTimeOfCircles, long timeOfCircleBurn, uint mNumberOfSpots, double mSpeedOfSports, QObject *parent = 0);
virtual ~GameController();
/** Инициировать игру
*
* Сбрасывает модель данных игры в начальные значения.
* У всех "пузырей" радиус одинаковый.
* У всех летающих точек одинаковая скорость.
*/
void initGame();
/** Пользователь создаёт "пузырь"
*
* "Пузырь" будет создан только впервый раз.
* В последующие разы контроллер проигнорирует вызов метода.
* @param position Координаты, в которых пытаемся создать пузырь.
*/
Q_INVOKABLE void createCircle(const QPointF &position);
/** Изменить размер области игры.
* @param width Новая ширина области игры.
* @param height Новая высота области игры.
*/
Q_INVOKABLE void setGameAreaSize(int width, int height);
/** Оставновить игру.
*/
Q_INVOKABLE void stopGame();
signals:
void gameStoped();
public slots:
/** Пересчитать данные игры согласно прошедьшему времени.
*/
void updateScene();
private:
GameDataModel* mGameDataModel;
qreal mRadiusOfCircles;
/** Время жизни круга в милисекундах.*/
long mLifeTimeOfCircles;
/** Время в течении которогокруг растёт. В милисекундах.*/
long mTimeOfCircleBurn;
uint mNumberOfSpots;
double mSpeedOfSports;
/** Скорость роста круга. Чтобы не пересчитывать многократно, сохраняю значение заранее.*/
double mSpeeOfCircleBurn;
/** Проверить, влетела ли точка в какой ни будь "пузырь".
*
* @param spotPosition Позиция точки.
* @return true, если точка влетела в какой ни будь "пузырь". Иначе false.
*/
bool spotIntersectCircle(const QPointF &spotPosition) const;
};
#endif // GAMECONTROLLER_H
|
C++
|
UTF-8
| 567
| 2.90625
| 3
|
[] |
no_license
|
/*
? ? ??????
?????20110102
? ?????
?????????????????
**/
void check(int *a);
int g_lenth;
int main()
{
char a[101];
int b[100];
cin.getline(a, 101);
g_lenth = strlen(a);
for(int i = 0; i < g_lenth; i++)
{
if(a[i] == a[0])
b[i] = 1;
else
b[i] = 2;
}
check(b);
return 0;
}
void check(int *a)
{
for(int i = 0; i < g_lenth; i++)
if(a[i] == 2)
for(int j = i - 1; j >= 0; j--)
if(a[j] == 1)
{
cout << j << ' ' << i << endl;
a[i] = 0;
a[j] = 0;
return check(a);
}
}
|
C++
|
UTF-8
| 2,580
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
#pragma once
#include <geneial/algorithm/diagnostics/Diagnostics.h>
#include <memory>
#include <algorithm>
#include <iomanip>
geneial_private_namespace(geneial)
{
geneial_private_namespace(algorithm)
{
geneial_export_namespace
{
template<typename FITNESS_TYPE>
Diagnostics<FITNESS_TYPE>::Diagnostics(const std::shared_ptr<BaseGeneticAlgorithm<FITNESS_TYPE>> &algorithm)
:_algorithm(algorithm)
{
instrumentAlgorithm();
}
template<typename FITNESS_TYPE>
void Diagnostics<FITNESS_TYPE>::instrumentAlgorithm()
{
//Have we already done something?
if (!_algorithm->hasBeenStarted())
{
//Inject Statistical Bookkeeper
//Prepare Algorithm for Diagnosis
if (!std::dynamic_pointer_cast<StatisticBookkeeper>(_algorithm->getBookkeeper()))
{
_algorithm->setBookkeeper(std::shared_ptr<StatisticBookkeeper>(new StatisticBookkeeper));
}
}
else
{
std::runtime_error("Algorithm has already started! Unable to inject diagnosis instrumentation!");
}
}
template<typename FITNESS_TYPE>
inline void Diagnostics<FITNESS_TYPE>::analyseAll(std::ostream& os)
{
analyseTimeSpent(os);
}
template<typename FITNESS_TYPE>
inline void Diagnostics<FITNESS_TYPE>::analyseTimeSpent(std::ostream& os)
{
auto statkeeper = std::dynamic_pointer_cast<StatisticBookkeeper>(_algorithm->getBookkeeper());
auto& events = statkeeper->getEvents();
// std::sort (events.begin(), events.end());
printTiming("TIME_ITERATION",events,os);
printTiming("TIME_AGING",events,os);
printTiming("TIME_SELECTION",events,os);
printTiming("TIME_OFFSPRING",events,os);
printTiming("TIME_MUTATION",events,os);
printTiming("TIME_REPLACEMENT",events,os);
printTiming("TIME_REPLENISHMENT",events,os);
printTiming("TIME_CRITERIA",events,os);
printTiming("TIME_OBSERVERS",events,os);
}
template<typename FITNESS_TYPE>
inline void Diagnostics<FITNESS_TYPE>::analyseEventsCoupling(std::ostream& os)
{
}
template<typename FITNESS_TYPE>
inline void Diagnostics<FITNESS_TYPE>::analyseEventsCrossover(std::ostream& os)
{
}
template<typename FITNESS_TYPE>
inline void Diagnostics<FITNESS_TYPE>::analyseEventsMutation(std::ostream& os)
{
}
template<typename FITNESS_TYPE>
inline void Diagnostics<FITNESS_TYPE>::analyseEventsReplacement(std::ostream& os)
{
}
template<typename FITNESS_TYPE>
inline void Diagnostics<FITNESS_TYPE>::anaylseEventsSelection(std::ostream& os)
{
}
template<typename FITNESS_TYPE>
inline void Diagnostics<FITNESS_TYPE>::anaylseConvergence(std::ostream& os)
{
}
}
}
}
|
Swift
|
UTF-8
| 4,895
| 3.015625
| 3
|
[] |
no_license
|
//
// ContactController.swift
// ContactList
//
// Created by Shak Feizi on 5/14/21.
//
import UIKit
import CloudKit
class ContactController {
// Shak notes: Properties
// sharedInstance
static let sharedInstance = ContactController()
// SOT
var contactsArray: [Contact] = []
// Database
let privateDB = CKContainer.default().privateCloudDatabase
// Shak notes: Functions
// Creat / Save
func creatAndSave(with name: String, phoneNumber: String, completion: @escaping (Result<String, NetworkError>) -> Void) {
let newContact = Contact(name: name, phoneNumber: phoneNumber)
let record = CKRecord(contact: newContact)
privateDB.save(record) { record, error in
// Handling error
if let error = error {
print("Error in \(#function) : \(error.localizedDescription) \n---\n \(error)")
return completion(.failure(.ckError(error)))
}
// Handling record
guard let record = record else { return completion(.failure(.couldNotUnwrap)) }
guard let saveContact = Contact(ckRecord: record) else { return completion(.failure(.couldNotUnwrap)) }
self.contactsArray.insert(saveContact, at: 0)
print(self.contactsArray.count)
completion(.success("Successfully created and save a Contact."))
}
}
// Update
func updateContact(contact: Contact, completion: @escaping (Result<Contact, NetworkError>) -> Void) {
let record = CKRecord(contact: contact)
let updateOperation = CKModifyRecordsOperation(recordsToSave: [record], recordIDsToDelete: nil)
updateOperation.savePolicy = .changedKeys
updateOperation.qualityOfService = .userInteractive
updateOperation.modifyRecordsCompletionBlock = { (records,_ , error) in
// Handling error
if let error = error {
print("Error in \(#function) : \(error.localizedDescription) \n---\n \(error)")
return completion(.failure(.ckError(error)))
}
guard let record = records?.first else { return completion(.failure(.couldNotUnwrap)) }
guard let updateContact = Contact(ckRecord: record) else { return completion(.failure(.couldNotUnwrap)) }
print("Update \(record.recordID) in CloudKit")
completion(.success(updateContact))
}
privateDB.add(updateOperation)
}
// Delete
func deleteContact(contact: Contact, completion: @escaping (Result<Bool, NetworkError>) -> Void) {
let deleteOperation = CKModifyRecordsOperation(recordsToSave: nil, recordIDsToDelete: [contact.recordID])
deleteOperation.savePolicy = .changedKeys
deleteOperation.qualityOfService = .userInteractive
deleteOperation.modifyRecordsCompletionBlock = { (records,_ , error) in
// Handling error
if let error = error {
print("Error in \(#function) : \(error.localizedDescription) \n---\n \(error)")
return completion(.failure(.ckError(error)))
}
if records?.count == 0 {
print("Delete record from CloudKit")
completion(.success(true))
} else {
return completion(.failure(.unexpectedRecordsFound))
}
}
privateDB.add(deleteOperation)
}
// Fetch
func fetchAllContacts(completion: @escaping (Result<[Contact], NetworkError>) -> Void) {
let fetchAllPredicates = NSPredicate(value: true)
let query = CKQuery(recordType: CloudKeys.recordTypeKey, predicate: fetchAllPredicates)
privateDB.perform(query, inZoneWith: nil) { records, error in
// Handling error
if let error = error {
print("Error in \(#function) : \(error.localizedDescription) \n---\n \(error)")
return completion(.failure(.ckError(error)))
}
guard let records = records else { return completion(.failure(.couldNotUnwrap)) }
print("Fetch Contact successfully.")
let contacts = records.compactMap ({ Contact(ckRecord: $0) })
self.contactsArray = contacts
completion(.success(contacts))
}
}
} //End of class
|
Java
|
UTF-8
| 431
| 3.46875
| 3
|
[] |
no_license
|
import java.util.*;
class User{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Name :");
String name = sc.next();
System.out.println("Roll No :");
int Roll = sc.nextInt();
System.out.println("Field of intrest :");
String Intrest = sc.next();
System.out.println("Hey,my name is "+name+" and my roll no is "+Roll+" My field of intrest are "+Intrest);
}
}
|
C#
|
UTF-8
| 3,385
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
// Copyright (c) True Goodwill. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace FFT.Oanda.Orders
{
using System;
using System.Collections.Immutable;
using System.Text.Json.Serialization;
/// <summary>
/// A StopLossOrder is an order that is linked to an open Trade and created
/// with a price threshold. The Order will be filled (closing the Trade) by
/// the first price that is equal to or worse than the threshold. A
/// StopLossOrder cannot be used to open a new Position.
/// </summary>
public sealed class StopLossOrder : Order
{
/// <summary>
/// Initializes a new instance of the <see cref="StopLossOrder"/> class.
/// </summary>
[JsonConstructor]
public StopLossOrder(
string id,
DateTime createTime,
OrderState state,
ClientExtensions? clientExtensions,
OrderType type,
string instrument,
TimeInForce timeInForce,
DateTime? gtdTime,
OrderPositionFill positionFill,
OrderTriggerCondition triggerCondition,
TakeProfitDetails? takeProfitOnFill,
StopLossDetails? stopLossOnFill,
GuaranteedStopLossDetails? guaranteedStopLossOnFill,
TrailingStopLossDetails? trailingStopLossOnFill,
ClientExtensions? tradeClientExtensions,
string? fillingTransactionID,
DateTime? filledTime,
string? tradeOpenedID,
string? tradeReducedID,
ImmutableList<string>? tradeClosedIDs,
string? cancellingTransactionID,
DateTime? cancelledTime,
string? replacesOrderID,
string? replacedByOrderID,
string tradeID,
string? clientTradeID,
decimal price,
decimal? distance)
: base(
id,
createTime,
state,
clientExtensions,
type,
instrument,
timeInForce,
gtdTime,
positionFill,
triggerCondition,
takeProfitOnFill,
stopLossOnFill,
guaranteedStopLossOnFill,
trailingStopLossOnFill,
tradeClientExtensions,
fillingTransactionID,
filledTime,
tradeOpenedID,
tradeReducedID,
tradeClosedIDs,
cancellingTransactionID,
cancelledTime,
replacesOrderID,
replacedByOrderID)
{
TradeID = tradeID;
ClientTradeID = clientTradeID;
Price = price;
Distance = distance;
}
/// <summary>
/// The ID of the Trade to close when the price threshold is breached.
/// </summary>
public string TradeID { get; }
/// <summary>
/// The client ID of the Trade to be closed when the price threshold is
/// breached.
/// </summary>
public string? ClientTradeID { get; }
/// <summary>
/// The price threshold specified for the Stop Loss Order. The associated
/// Trade will be closed by a market price that is equal to or worse than
/// this threshold.
/// </summary>
public decimal Price { get; }
/// <summary>
/// Specifies the distance (in price units) from the Account’s current price
/// to use as the Stop Loss Order price. If the Trade is short the
/// Instrument’s bid price is used, and for long Trades the ask is used.
/// </summary>
public decimal? Distance { get; }
}
}
|
Java
|
UTF-8
| 396
| 1.851563
| 2
|
[] |
no_license
|
package com.mshis.medicalSystem.dao.medicalrecord;
import com.mshis.medicalSystem.pojo.bean.CaseHistory;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* description:
* author: 沫凌
* create: 2019-07-18 10:07
*/
public interface DiseaseRecordDao extends JpaRepository<CaseHistory,Integer> {
CaseHistory findFirstByChNumAndChTimes(Integer chNum,Integer chTimes);
}
|
Java
|
UTF-8
| 1,195
| 2.5625
| 3
|
[] |
no_license
|
package xyz.elfanrodhian.myfamilylocator.models;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class TimelineItem {
private FamilyMember familyMember;
String date;
Long timestamp;
public TimelineItem() {
}
public TimelineItem(FamilyMember familyMember) {
this.familyMember = familyMember;
Calendar c = Calendar.getInstance();
// Apr 21, 2017 at 1:17pm
SimpleDateFormat df = new SimpleDateFormat("MMM dd,yyyy 'at' h:ma", Locale.getDefault());
date = df.format(c.getTime());
// negative to allow firebase to order i descending order
timestamp = -1 * System.currentTimeMillis();
}
public FamilyMember getFamilyMember() {
return familyMember;
}
public void setFamilyMember(FamilyMember familyMember) {
this.familyMember = familyMember;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
}
|
C#
|
UTF-8
| 2,099
| 2.765625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AerolineaFrba
{
public class Cliente
{
int id;
decimal dni;
string nombre;
string apellido;
string dir;
decimal telefono;
string mail;
DateTime fechaNacimiento;
public Cliente(int id, decimal dni,string nombre, string apellido,string dir,decimal telefono,string mail,DateTime fechaNacimiento)
{
// TODO: Complete member initialization
this.id = id;
this.dni = dni;
this.nombre=nombre;
this.apellido = apellido;
this.dir = dir;
this.telefono = telefono;
this.mail = mail;
this.fechaNacimiento = fechaNacimiento;
}
public Cliente(decimal dni, string nombre, string apellido, string dir, decimal telefono, string mail, DateTime fechaNacimiento)
{
// TODO: Complete member initialization
this.dni = dni;
this.nombre = nombre;
this.apellido = apellido;
this.dir = dir;
this.telefono = telefono;
this.mail = mail;
this.fechaNacimiento = fechaNacimiento;
}
public decimal getDni
{
get { return dni; }
}
public string getNombre
{
get { return nombre; }
}
public string getApellido
{
get { return apellido; }
}
public string getDir
{
get { return dir; }
}
public string getMail
{
get { return mail; }
}
public decimal getTelefono
{
get { return telefono; }
}
public DateTime getFechaNacimiento
{
get { return fechaNacimiento; }
}
internal void setDni(decimal p)
{
this.dni = p;
}
public int getId
{
get { return id; }
}
}
}
|
PHP
|
UTF-8
| 6,948
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
<?php
/**
*
* Query Service
* =============
*
* Have the different queries here to be
* used in other services
*/
namespace fishawack\triton\services;
use fishwack\triton\Triton;
use Craft;
use craft\elements\Entry;
use craft\elements\Category;
use craft\elements\GlobalSet;
use yii\base\Component;
class QueryService extends Component
{
public function queryAllGlobalSet()
{
}
/*
* Get one result from globalsets
*
* @param string $sectionHandle
*/
public function queryOneGlobalSet(string $sectionHandle)
{
$globalset = GlobalSet::find()
->handle($sectionHandle)
->one();
return $globalset;
}
/*
* @param string $sectionHandle
*/
public function queryAllEntries(string $sectionHandle, $status = "live")
{
$entries = Entry::find()
->section($sectionHandle)
->status($status)
->all();
for($i = 0; $i < count($entries); $i++)
{
$entries[$i]->title = trim($entries[$i]);
}
return $entries;
}
/*
* Get one entry from selected section
*
* @param string $sectionHandle
*/
public function queryOneEntry(string $sectionHandle)
{
$entries = Entry::find()
->section($sectionHandle)
->one();
return $entries;
}
/*
* Get one entry from selected section
*
* WIP / Don't use
* @param string $sectionHandle
*/
public function queryOneEntryByProducts(string $product)
{
$entries = Entry::find()
->section('publications')
->product($product)
->one();
return $entries;
}
/*
* Get one entry whether it's enabled or not
*
* @param string $entryId
*/
public function queryEntryById($entryId)
{
$query = Entry::find()
->status(null)
->id($entryId)
->one();
return $query;
}
/*
* Get one entry whether it's enabled or not
*
* @param string $entryId
*/
public function queryEntryByTitle($title)
{
$query = Entry::find()
->status(null)
->title($title)
->one();
return $query;
}
/*
* Get one entry by section and title
*
* @param string $entryId
*/
public function queryEntryBySectionAndTitle($title, $section)
{
$query = Entry::find()
->status(null)
->section($section)
->title($title)
->one();
return $query;
}
/*
* Get entry by slug!
* Better for JSC
*/
public function queryEntryBySlug($slug)
{
$query = Entry::find()
->anyStatus()
->slug($slug)
->one();
return $query;
}
/*
* Get entry by slug!
* Better for JSC
*/
public function queryEntryBySlugAndSection($slug, $sectionTitle = '')
{
$query = Entry::find()
->section($sectionTitle)
->anyStatus()
->slug($slug)
->one();
return $query;
}
/*
* Get one entry whether it's enabled or not by
* title ans section
*
* @param string $entryId
*/
public function queryEntryByCongressTitle($title)
{
$query = Entry::find()
->anyStatus()
->section('congresses')
->title($title)
->one();
return $query;
}
public function queryEntryByCongressSlug($slug)
{
$slug = str_replace(' ', '-', $slug);
$slug = preg_replace('/[^A-Za-z0-9\-]/', '-', $slug);
var_dump($slug);
$query = Entry::find()
->anyStatus()
->section('congresses')
->slug($slug)
->one();
return $query;
}
/*
* @param string $sectionHandle
*/
public function queryAllCategories()
{
$query = Category::find()
->all();
$results = $this->swapKeys($query);
return $results;
}
public function getAllEntriesUntouchedWithProduct(string $sectionTitle, $product = '')
{
$entries = Entry::find()
->section($sectionTitle)
->product($product)
->status(null)
->all();
return $entries;
}
public function getAllEntriesUntouched(string $sectionTitle)
{
$query = Entry::find()
->section($sectionTitle)
->status(null)
->all();
return $query;
}
public function getCategory(string $categoryTitle)
{
return Craft::$app->getCategories()->getGroupByHandle($categoryTitle);
}
public function getAllCategoriesUntouched(string $categoryTitle)
{
// Find the correct group id
$group = Craft::$app->getCategories()->getGroupByHandle($categoryTitle);
$query = Category::find()
->groupId($group->id)
->all();
return $query;
}
public function queryCategoriesByTitle(string $categoryTitle)
{
// Find the correct group id
$group = Craft::$app->getCategories()->getGroupByHandle($categoryTitle);
if(!$group)
{
return false;
}
$query = Category::find()
->groupId($group->id)
->all();
return $query;
}
public function queryCategoryById(int $categoryId)
{
// Find the correct group id
$query = Category::find()
->groupId($categoryId)
->all();
return $query;
}
/*
* @param string $sectionHandle
*/
public function queryOneCategory(string $categoryTitle)
{
// Find the correct group id
$group = Craft::$app->getCategories()->getGroupByHandle($categoryTitle);
$query = Category::find()
->groupId($group->id)
->one();
return $query;
}
/*
*
* @param string $entryTitle
*/
public function queryFindEntryCategory($category, string $entryTitle)
{
$query = Category::find()
->search($entryTitle)
->one();
return $query;
}
/*
* Swap keys so that we can sift
* through out array and do minupulation
*
* @param array $originalData
*/
public function swapKeys(array $originalData)
{
$dataCleaned = [];
foreach($originalData as $newData)
{
$dataCleaned[$newData->title] = $newData;
}
return $dataCleaned;
}
public function changeTitleToSlug($title) {
$title = str_replace(' ', '-', $title);
$slug = preg_replace('/[^A-Za-z0-9\-]/', '-', $title);
$slug = strtolower($slug);
return $slug;
}
}
|
C++
|
UTF-8
| 235
| 2.71875
| 3
|
[] |
no_license
|
#include<iostream>
using namespace std;
int main()
{
int a[]={16, 17, 4, 3, 5, 2};
int m=-1;
for(int j=5;j>=0;j--)
{
int t=a[j];
a[j]=m;
if(t>m)
m=t;
}
for(int i=0;i<6;i++)cout<<a[i]<<" ";
}
|
Java
|
UTF-8
| 9,890
| 2.28125
| 2
|
[] |
no_license
|
//*****************************************************************************
// Author: Rafael Geraldeli Rossi
// E-mail: rgr.rossi at gmail com
// Last-Modified: January 29, 2015
// Description:
//*****************************************************************************
package TCTInterfaces.Parameters;
import TCTParameters.Parameters_NumLabeledDocs;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.ListModel;
public class Interface_Parameters_NumberLabeledExamples extends javax.swing.JInternalFrame {
Parameters_NumLabeledDocs parametersNumLabeledInstancesPerClass;
public Interface_Parameters_NumberLabeledExamples(Parameters_NumLabeledDocs parametersNumLabeledInstancesPerClass) {
initComponents();
this.parametersNumLabeledInstancesPerClass = parametersNumLabeledInstancesPerClass;
DefaultListModel model = new DefaultListModel();
for (int j = 0; j < parametersNumLabeledInstancesPerClass.getNumLabeledInstancesPerClass().size(); j++) {
model.addElement(parametersNumLabeledInstancesPerClass.getNumLabeledInstancesPerClass(j));
}
lVizinhos.setModel(model);
this.setVisible(true);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
lVizinhos = new javax.swing.JList();
bIncluir = new javax.swing.JButton();
bRemover = new javax.swing.JButton();
bOK = new javax.swing.JButton();
bCancelar = new javax.swing.JButton();
setClosable(true);
setIconifiable(true);
setTitle("TCT - Labeled Examples");
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Nº of Labeled Examples"));
lVizinhos.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "1", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
lVizinhos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane1.setViewportView(lVizinhos);
bIncluir.setText("Add");
bIncluir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bIncluirActionPerformed(evt);
}
});
bRemover.setText("Remove");
bRemover.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bRemoverActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(bRemover, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(bIncluir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)
.addContainerGap())
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(bIncluir)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bRemover)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
bOK.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
bOK.setText("OK");
bOK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bOKActionPerformed(evt);
}
});
bCancelar.setText("Cancel");
bCancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bCancelarActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(bOK, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(bCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(bCancelar)
.addComponent(bOK))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void bIncluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bIncluirActionPerformed
JOptionPane ent = new JOptionPane();
try {
Integer item = Integer.parseInt(ent.showInputDialog(this, "Number of labeled examples for each class:", "TCT", ent.PLAIN_MESSAGE));
ListModel model = lVizinhos.getModel();
DefaultListModel model2 = new DefaultListModel();
for (int j = 0; j < model.getSize(); j++) {
model2.addElement(model.getElementAt(j));
}
model2.addElement(item);
lVizinhos.setModel(model2);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Incorrect value");
e.printStackTrace();
}
}//GEN-LAST:event_bIncluirActionPerformed
private void bRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bRemoverActionPerformed
int i = lVizinhos.getSelectedIndex();
if (i == -1) {
return;
}
ListModel model = lVizinhos.getModel();
DefaultListModel model2 = new DefaultListModel();
for (int j = 0; j < model.getSize(); j++) {
model2.addElement(model.getElementAt(j));
}
model2.removeElementAt(i);
lVizinhos.setModel(model2);
}//GEN-LAST:event_bRemoverActionPerformed
private void bOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bOKActionPerformed
ArrayList<Double> numInstPerClass = new ArrayList<Double>();
ListModel model = lVizinhos.getModel();
for (int item = 0; item < model.getSize(); item++) {
numInstPerClass.add(Double.parseDouble(model.getElementAt(item).toString()));
}
parametersNumLabeledInstancesPerClass.setNumLabeledInstancesPerClass(numInstPerClass);
this.dispose();
}//GEN-LAST:event_bOKActionPerformed
private void bCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCancelarActionPerformed
this.dispose();
}//GEN-LAST:event_bCancelarActionPerformed
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton bCancelar;
private javax.swing.JButton bIncluir;
private javax.swing.JButton bOK;
private javax.swing.JButton bRemover;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JList lVizinhos;
// End of variables declaration//GEN-END:variables
}
|
Markdown
|
UTF-8
| 4,353
| 2.640625
| 3
|
[] |
no_license
|
# Getting Started
<%= title("Installation") %>
Before installing make sure you have the required dependencies installed:
* [Go](https://golang.org) version `1.7` or greater.
* GCC, or equivalent C compiler for [mattn/go-sqlite3](https://github.com/mattn/go-sqlite3).
* [OPTIONAL] [node](https://github.com/nodejs/node) and [npm](https://github.com/npm/npm) for the [asset pipeline](/docs/assets) built upon [webpack](https://github.com/webpack/webpack).
### Basic Installation:
<%= code("text") { %>
$ go get -u -v github.com/gobuffalo/buffalo/buffalo
<% } %>
### SQLite3 Support:
Buffalo includes support for *go-sqlite3* which requires a C compiler to be built. Either install a compiler, for example GCC, from source/package manager or build Buffalo *without* support for SQLite3:
<%= code("text") { %>
$ go get -v -u -tags nosqlite github.com/gobuffalo/buffalo/buffalo
<% } %>
<%= title("Generating a New Project") %>
Buffalo aims to make building new web applications in Go as quick and simple as possible, and what could be more simple than a *new application* generator? Start by going to your `$GOPATH` and create your new application!
<%= code("text") { %>
$ cd $GOPATH/src/github.com/$USER/
$ # Make sure $GOPATH/bin is in your $PATH, then:
$ buffalo new <name>
<% } %>
That will generate a whole new Buffalo application that is ready to go. It'll even run `go get` for you to make sure you have all of the necessary dependencies needed to run your application.
<%= code("text") { %>
$ buffalo new coke
Buffalo version <%= version %>
--> .../coke/README.md
--> .../coke/actions/actions_test.go
--> .../coke/actions/app.go
--> .../coke/actions/home.go
--> .../coke/actions/home_test.go
--> .../coke/actions/render.go
--> .../coke/.codeclimate.yml
--> .../coke/.gitignore
--> .../coke/grifts/routes.go
--> .../coke/main.go
--> .../coke/templates/application.html
--> .../coke/templates/index.html
--> .../coke/.buffalo.dev.yml
--> go get github.com/markbates/refresh/...
--> go install github.com/markbates/refresh
--> go get github.com/markbates/grift/...
--> go install github.com/markbates/grift
--> go get github.com/motemen/gore
--> go install github.com/motemen/gore
--> .../coke/assets/images/logo.svg
--> .../coke/assets/css/application.scss
--> .../coke/assets/js/application.js
--> .../coke/public/assets/.gitignore
--> .../coke/webpack.config.js
--> npm init -y
--> .../coke/models/models.go
--> .../coke/models/models_test.go
--> go get github.com/markbates/pop/...
--> go install github.com/markbates/pop/soda
--> database.yml
--> go get -t ./...
--> goimports -w .
Congratulations! Your application, coke, has been successfully built!
You can find your new application at:
.../coke
Please read the README.md file in your new application for next steps on running your application.
<% } %>
To see a list of available flags for the `new` command, just check out its help.
<%= code("text") { %>
$ buffalo help new
<% } %>
Note: by default, Buffalo generates a database.yml targeted for postgres. If you wish to change this behavior, you can pass in a `--db-type` flag into the `new` command.
<%= code("text") { %>
$ buffalo new coke --db-type sqlite3
<% } %>
If your app doesn't need a database, or if you want to handle it by yourself, you can use the `--skip-pop` flag.
<%= code("text") { %>
$ buffalo new coke --skip-pop
<% } %>
<%= partial("docs/dev.md") %>
<%= title("Building Your Application", {name: "building"}) %>
Buffalo features a command, `build`, that will build a full binary of your application including, but not limited to; assets, migrations, templates, etc... If you buy into the "Buffalo Way" things just work. It's a wonderful experience. :)
<%= code("text") { %>
$ buffalo build
<% } %>
<%= code("text") { %>
Buffalo version <%= version %>
--> cleaning up target dir
--> running node_modules/.bin/webpack
--> packing .../coke/actions/actions-packr.go
--> running go build -v -o bin/gobuffalo -ldflags -X main.version=b5dffda -X main.buildTime="2017-03-20T11:05:23-04:00"
--> cleaning up build
----> cleaning up buffalo_build_main.go
----> cleaning up a
----> cleaning up a/a.go
----> cleaning up a/database.go
----> cleaning up buffalo_build_main.go
----> cleaning up ...coke/actions/actions-packr.go
<% } %>
See [Building](/docs/building) for more options on the `build` command.
|
Markdown
|
UTF-8
| 2,945
| 3.21875
| 3
|
[] |
no_license
|
# Super Resolution Using GAN
## Objective
- The main objective was recover or restore high resolution image from low resolution image.
- In this project low resolution images were converted to high resolutions images by applying Generative Adversarial Networks.
- GANs are class of AI algorithms used in Unsupervised Machine Learning. GANs are deep neural network architectures comprised of two networks (Generator and Discriminator) pitting one against the other (thus the “adversarial”) [1].
- 1000 images from the 2017 COCO dataset has been used. Higher number of images and more epochs can be in the training.

## Loss used
- Usually the focus is on minimizing the mean squared reconstruction error while generating super reolution images. The results have high peak signal-to-noise ratios(PSNR). This means we have good image quality results, but they are often lacking high-frequency details.
- Hence, perceptual loss[2] function which comprise of Content and Adversarial loss has been used.
- Adversarial loss: A discriminator network that is trained to differentiate between the super-resolved images and original photo-realistic images.
- Content Loss: The VGG loss is defined based on the ReLU activation layers of the pre-trained 19 layer VGG network. VGG loss is defined as the euclidean distance between the feature representations of a reconstructed image and the reference image.
- Refer to the original paper [2] for more details on perceptual loss.

## Network Architecture
- The network architecture as propoed in [3] has been used.
- Residual blocks: Since deeper networks are more difficult to train, residual layers have been used.
- PixelShuffler x2: This is feature map upscaling. 2 sub-pixel CNN are used in Generator. There are various ways to do that. In code keras inbuilt function has been used.
- PRelu(Parameterized Relu): PRelu in place of Relu or LeakyRelu has been used. It introduces learn-able parameter that makes it possible to adaptively learn the negative part coefficient.
- k3n64s1 this means kernel 3, channels 64 and strides 1.

## Note for training the network
- The GAN losses don't stabilize unless you first pretrain the generator.
- The network will still end up being able to improve image quality if you don't, but it will be only from the VGG loss and the GAN part will be basically useless.
- First the generator is pre-trained to minimize the MSE between the training inputs and the training targets with no GAN.
- Once this model is trained, removed we will continue training (using VGG perceptual loss + GAN loss and training the descriminator in the training loop) For more info (https://www.fast.ai/2019/05/03/decrappify/)


## References
[1] : https://arxiv.org/pdf/1609.04802.pdf
[2] : https://arxiv.org/pdf/1603.08155.pdf
[3] : https://arxiv.org/pdf/1609.04802.pdf
|
Java
|
UTF-8
| 2,558
| 2.234375
| 2
|
[] |
no_license
|
package com.yaoguang.greendao.entity.company.user;
/**
* 用户查询条件类
*
* @author ZhangDeQuan
* @time 2016年9月30日 上午11:07:49
*/
public class UserCondition {
// 当前登录用户ID
private String userId;
// 当前登录用户归属部门ID
private String userOfficeId;
// 归属公司ID
private String companyId;
// 归属部门ID
private String officeId;
// 登录名
private String loginName;
// 姓名
private String name;
// 公司名称
private String companyName;
// 用户类型(0:系统管理 1:普通用户)
private String userType;
// 是否web端登录
private Integer loginFlag = -1;
// (0:离职 1:可用 -1:全部)
private Integer usable = -1;
// 是否黄页官网显示(0-否,1-是)
private Integer isWebsiteShow = -1;
// 黄页功能是否过期(0-否,1-是,-1-全部)
private Integer isWebsiteOverdue = -1;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserOfficeId() {
return userOfficeId;
}
public void setUserOfficeId(String userOfficeId) {
this.userOfficeId = userOfficeId;
}
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
public String getOfficeId() {
return officeId;
}
public void setOfficeId(String officeId) {
this.officeId = officeId;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public Integer getLoginFlag() {
return loginFlag;
}
public void setLoginFlag(Integer loginFlag) {
this.loginFlag = loginFlag;
}
public Integer getUsable() {
return usable;
}
public void setUsable(Integer usable) {
this.usable = usable;
}
public Integer getIsWebsiteShow() {
return isWebsiteShow;
}
public void setIsWebsiteShow(Integer isWebsiteShow) {
this.isWebsiteShow = isWebsiteShow;
}
public Integer getIsWebsiteOverdue() {
return isWebsiteOverdue;
}
public void setIsWebsiteOverdue(Integer isWebsiteOverdue) {
this.isWebsiteOverdue = isWebsiteOverdue;
}
}
|
Swift
|
UTF-8
| 6,897
| 2.53125
| 3
|
[] |
no_license
|
import UIKit
import Network
var heroRes3 : [Hero] = []
var filtering = false
var filteredArray = [Hero]()
class apiTestViewController: UIViewController {
@IBOutlet weak var testingCollectionView: UICollectionView!
@IBOutlet weak var navBarItem: UINavigationItem!
var heroRes2 = [Hero]()
var searching = false
var searched = [Hero]()
let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
Appearance()
configureSearchController()
let _url = "https://rickandmortyapi.com/api/character/"
for x in 0..<30 {
var url2 = _url + String(x+1)
print("urlAPI: " + url2 + " ind: " + String(x))
getFromJson(url: URL(string: url2)!, index: x)
}
print("heroRes2: " + String(heroRes2.count))
testingCollectionView.dataSource = self
testingCollectionView.delegate = self
testingCollectionView.collectionViewLayout = UICollectionViewFlowLayout()
}
override func viewDidAppear(_ animated: Bool) {
// print("heroRes3: " + String(heroRes3.count))
testingCollectionView.reloadData()
}
func getFromJson(url: URL, index: Int) {
URLSession.shared.dataTask(with: url, completionHandler: {data, response, error in
guard let data = data, error == nil else {
print("something went wrong")
return
}
do { // if got data:
try self.heroRes2.append(JSONDecoder().decode(Hero.self, from: data))
if (self.heroRes2.count == index+1) {
print("appended")
}
print("indx: " + String(index) , String(decoding: data, as: UTF8.self))
} catch {
print(error.localizedDescription)
print("ERROR PARSING")
}
}).resume()
}
func Appearance() {
navigationController?.isNavigationBarHidden = false
navigationController?.navigationBar.isTranslucent = false
self.title = "Characters"
navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor(red: 188.0/255.0, green: 214.0/255.0, blue: 90.0/255.0, alpha: 1.0)]
if let layout = testingCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.sectionHeadersPinToVisibleBounds = true
layout.headerReferenceSize = CGSize(width: 100, height: 40)
}
}
func filterBttnTouched(sender: UIBarButtonItem) {
// performSegue(withIdentifier: "toFilter", sender: self)
DispatchQueue.main.asyncAfter(deadline: .now()) { [unowned self] in
performSegue(withIdentifier: "toFilter", sender: self)
}
}
func configureSearchController() {
searchController.loadViewIfNeeded()
searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.enablesReturnKeyAutomatically = false
searchController.searchBar.returnKeyType = UIReturnKeyType.done
self.navigationItem.searchController = searchController
self.navigationItem.hidesSearchBarWhenScrolling = false
definesPresentationContext = true
searchController.searchBar.placeholder = "Введите имя"
}
}
extension apiTestViewController: UICollectionViewDataSource , UICollectionViewDelegate, UISearchResultsUpdating, UISearchBarDelegate, UIPickerViewDelegate {
func updateSearchResults(for searchController: UISearchController) {
let searchText = searchController.searchBar.text!
if !searchText.isEmpty {
searching = true
searched.removeAll()
for x in heroRes2 {
if x.name.lowercased().contains(searchText.lowercased())
{
searched.append(x)
}
}
} else {
searching = false
searched.removeAll()
searched = heroRes3
}
testingCollectionView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searching = false
searched.removeAll()
testingCollectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if filtering {
return filteredArray.count
} else {
if searching {
return searched.count
}
else {
return 30
}
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "test1CollectionViewCell", for: indexPath) as! test1CollectionViewCell
heroRes3 = heroRes2
if filtering {
cell.setup(hero: filteredArray[indexPath.row])
//print("filtering true, filteredArray.count:" + String(filteredArray.count))
} else {
if searching {
//print("filtering false, searching true")
cell.setup(hero: self.searched[indexPath.row])
} else {
//print("filtering false, searching false")
cell.setup(hero: (heroRes3[indexPath.row]))
}
}
cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 0.5
cell.layer.cornerRadius = 20
cell.image.backgroundColor = .white
cell.image.contentMode = .scaleAspectFill
return cell
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
1
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let desVC = mainStoryboard.instantiateViewController(identifier: "DetailedViewController") as! DetailedViewController
desVC.img.downloaded(from: heroRes2[indexPath.row].image)
desVC.name_.text = heroRes2[indexPath.row].name
self.navigationController?.pushViewController(desVC, animated: true)
}
}
extension apiTestViewController : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 171, height: 217)
}
}
|
Java
|
UTF-8
| 6,547
| 1.9375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package timchat.ui;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.fanweilin.coordinatemap.R;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.imsdk.ext.sns.TIMFriendResult;
import com.tencent.qcloud.presentation.presenter.FriendshipManagerPresenter;
import com.tencent.qcloud.ui.NotifyDialog;
import java.util.ArrayList;
import java.util.List;
import timchat.adapters.GroupListAdapter;
import timchat.model.FriendshipInfo;
/**
* 好友分组管理
*/
public class ManageFriendGroupActivity extends FragmentActivity implements View.OnClickListener {
private final String TAG = ManageFriendGroupActivity.class.getSimpleName();
private ListView mMyGroupList;
private GroupListAdapter mGroupListAdapter;
private LinearLayout mAddGroup;
private List<String> groups = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manager_group);
mMyGroupList = findViewById(R.id.group_list);
mAddGroup = findViewById(R.id.add_group);
mAddGroup.setOnClickListener(this);
groups.addAll(FriendshipInfo.getInstance().getGroups());
mGroupListAdapter = new GroupListAdapter(this, groups, this);
mMyGroupList.setAdapter(mGroupListAdapter);
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.add_group) {
addDialog();
}
}
private Dialog addGroupDialog;
private void addDialog() {
addGroupDialog = new Dialog(this, R.style.dialog);
addGroupDialog.setContentView(R.layout.dialog_addgroup);
TextView btnYes = addGroupDialog.findViewById(R.id.confirm_btn);
TextView btnNo = addGroupDialog.findViewById(R.id.cancel_btn);
final EditText inputView = addGroupDialog.findViewById(R.id.input_group_name);
btnNo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addGroupDialog.dismiss();
}
});
btnYes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String groupname = inputView.getText().toString();
if (groupname.equals("")) {
Toast.makeText(ManageFriendGroupActivity.this, getString(R.string.add_dialog_null), Toast.LENGTH_SHORT).show();
} else {
FriendshipManagerPresenter.createFriendGroup(groupname, new TIMValueCallBack<List<TIMFriendResult>>() {
@Override
public void onError(int i, String s) {
Log.e(TAG, "onError code " + i + " msg " + s);
switch (i){
case 32218:
//分组名称已存在
Toast.makeText(ManageFriendGroupActivity.this, getString(R.string.add_group_error_existed), Toast.LENGTH_SHORT).show();
break;
case 32214:
//分组达到上限
Toast.makeText(ManageFriendGroupActivity.this, getString(R.string.add_group_error_limit), Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(ManageFriendGroupActivity.this, getString(R.string.add_group_error), Toast.LENGTH_SHORT).show();
break;
}
}
@Override
public void onSuccess(List<TIMFriendResult> timFriendResults) {
Toast.makeText(ManageFriendGroupActivity.this, getString(R.string.add_group_succ), Toast.LENGTH_SHORT).show();
// FriendshipEvent.getInstance().OnAddFriendGroups(null);
groups.add(groupname);
mGroupListAdapter.notifyDataSetChanged();
// FriendshipEvent.getInstance().OnAddFriendGroups(null);
}
});
}
addGroupDialog.dismiss();
}
});
Window window = addGroupDialog.getWindow();
window.setGravity(Gravity.TOP);
WindowManager.LayoutParams lp = window.getAttributes();
window.setAttributes(lp);
addGroupDialog.show();
}
public void deleteGroup(int position) {
deleteDialog(position);
}
private void deleteDialog(final int position) {
NotifyDialog dialog = new NotifyDialog();
dialog.show(getString(R.string.delete_dialog_subtitle)+groups.get(position)+getString(R.string.delete_dialog_subtitle_sur), ManageFriendGroupActivity.this.getSupportFragmentManager(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
FriendshipManagerPresenter.delFriendGroup(groups.get(position), new TIMCallBack() {
@Override
public void onError(int i, String s) {
Log.e(TAG, "onError code " + i + " msg " + s);
Toast.makeText(ManageFriendGroupActivity.this, getString(R.string.del_group_error), Toast.LENGTH_SHORT).show();
}
@Override
public void onSuccess() {
Toast.makeText(ManageFriendGroupActivity.this, getString(R.string.delete_group_succ), Toast.LENGTH_SHORT).show();
// FriendshipEvent.getInstance().OnDelFriendGroups(Collections.singletonList(groups.get(position)));
groups.remove(position);
mGroupListAdapter.notifyDataSetChanged();
}
});
}
});
}
}
|
Java
|
UTF-8
| 1,017
| 2.671875
| 3
|
[] |
no_license
|
package edu.buffalo.cse.ir.wikiindexer.tokenizer.rules;
import edu.buffalo.cse.ir.wikiindexer.tokenizer.TokenStream;
import edu.buffalo.cse.ir.wikiindexer.tokenizer.TokenizerException;
import edu.buffalo.cse.ir.wikiindexer.tokenizer.rules.TokenizerRule.RULENAMES;
@RuleClass(className = RULENAMES.SPECIALCHARS)
public class SpecialCharRule implements TokenizerRule {
public SpecialCharRule() {
super();
// TODO Auto-generated constructor stub
}
@Override
public void apply(TokenStream stream) throws TokenizerException {
if(stream!=null)
{ // TODO Auto-generated method stub
String str=null;
String token;
while(stream.hasNext())
{
token = stream.next();
if(token!=null){
str = token.replaceAll("(\\w+)(?![-.,'!?])\\p{Punct}(\\w+)", "$1 $2");
str = str.replaceAll("(?![.,'!?-])\\p{Punct}","");
str = str.trim();
str= str.replaceAll(" ( )", " ");
stream.previous();
stream.set(str);
stream.next();
}
}
//
}
stream.reset();
}
}
|
Python
|
UTF-8
| 2,820
| 2.5625
| 3
|
[] |
no_license
|
from ..models import Battle, King
from .serializers import BattleSerializer, StatsSerializer
from got.response import JSONResponse
from rest_framework.views import APIView
from ..stats import Stats
class BattleListView(APIView):
"""
API View for the /list endpoint
"""
permission_classes = ()
def get(self, request):
batlles = BattleSerializer(instance=Battle.objects.all(), many=True).data
return JSONResponse(batlles)
class BattleDetailView(APIView):
"""
API View for the detail view of the battles /battles/<pk>
"""
permission_classes = ()
def get(self, request, pk):
battle = BattleSerializer(instance=Battle.objects.get(id=pk)).data
return JSONResponse(battle)
class BattleCountView(APIView):
"""
API View for the count of all the records in the db /count
"""
permission_classes = ()
def get(self, request):
count = Battle.objects.count()
return JSONResponse(count)
class StatsView(APIView):
"""
API View for the stats of all the data in the db /stats
"""
permission_classes = ()
def get(self, request):
stat = StatsSerializer(instance=Stats()).data
return JSONResponse(stat)
class SearchView(APIView):
"""
API View for the search request using name, attacker_king, defender_king,
location, type of battle /search
"""
permission_classes = ()
def get(self, request):
name = request.query_params.get('name', None)
type = request.query_params.get('type', None)
location = request.query_params.get('location', None)
attacker_king = request.query_params.get('attacker_king', None)
defender_king = request.query_params.get('defender_king', None)
if name:
battle = BattleSerializer(instance=Battle.objects.get(name__iexact=name)).data
return JSONResponse(battle)
elif type:
battle = BattleSerializer(instance=Battle.objects.filter(battle_type__iexact=type), many=True).data
return JSONResponse(battle)
elif location:
battle = BattleSerializer(instance=Battle.objects.filter(location__iexact=location), many=True).data
return JSONResponse(battle)
elif attacker_king:
king_object = King.objects.get(name__iexact=attacker_king)
battle = BattleSerializer(instance=Battle.objects.filter(attacker_king=king_object), many=True).data
return JSONResponse(battle)
elif defender_king:
king_object = King.objects.get(name__iexact=defender_king)
battle = BattleSerializer(instance=Battle.objects.filter(defender_king=king_object), many=True).data
return JSONResponse(battle)
else:
return JSONResponse(name)
|
TypeScript
|
UTF-8
| 748
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
import { Issue } from './issue';
/** The result of a JQL search. */
export interface SearchResults {
/** Expand options that include additional search result details in the response. */
expand?: string;
/** The index of the first item returned on the page. */
startAt?: number;
/** The maximum number of results that could be on the page. */
maxResults?: number;
/** The number of results on the page. */
total?: number;
/** The list of issues found by the search. */
issues?: Issue[];
/** Any warnings related to the JQL query. */
warningMessages?: string[];
/** The ID and name of each field in the search results. */
names?: {};
/** The schema describing the field types in the search results. */
schema?: {};
}
|
Java
|
UTF-8
| 911
| 2.234375
| 2
|
[] |
no_license
|
package com.sqli.imputation.service.impl;
import com.sqli.imputation.domain.Activity;
import com.sqli.imputation.service.ActivityPopulatorService;
import com.sqli.imputation.service.ActivityService;
import com.sqli.imputation.service.dto.ActivityDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class DefaultActivityPopulatorService implements ActivityPopulatorService {
@Autowired
private ActivityService activityService;
@Override
public Activity populateDatabase(ActivityDTO activityDTO) {
Activity activity = clone(activityDTO);
activity = activityService.save(activity);
return activity;
}
private Activity clone(ActivityDTO activityDTO) {
Activity activity = new Activity();
activity.setName(activityDTO.getLibelle());
return activity;
}
}
|
JavaScript
|
UTF-8
| 685
| 2.984375
| 3
|
[] |
no_license
|
document.addEventListener('DOMContentLoaded', restore_options);
const body = document.querySelector('body');
body.addEventListener('click', ()=> txtDomainName.focus());
const btnSave = document.getElementById('btnSave');
btnSave.addEventListener('click', save_options);
const txtDomainName = document.getElementById('txtDomainName');
function save_options() {
const domain = txtDomainName.value.trim();
chrome.storage.sync.set({ domain }, () => console.log('Domain ' + domain));
}
function restore_options() {
const defaultDomain = '';
chrome.storage.sync.get({ domain: defaultDomain }, items =>
txtDomainName.value = items.domain
);
}
|
Markdown
|
UTF-8
| 3,685
| 2.828125
| 3
|
[] |
no_license
|
<h1 align="center">
<img src=".github/banner.png" alt="Time & Attendance">
</h1>
<p align="center">Registre e acompanhe seus pontos eletrônicos de maneira simples e fácil!</p>
<h4 align="center">Versão 1.0</h4>
<p align="center">
<a href="#-sobre">Sobre</a> |
<a href="#-tecnologias">Tecnologias</a> |
<a href="#-layout">Layout</a> |
<a href="#-to-do">To-Do</a> |
<a href="#information_source-instalação-e-uso">Instalação</a> |
<a href="#-licença">Licença</a>
</p>
<p align="center">
<img
alt="Github Top Language"
src="https://img.shields.io/github/languages/top/carlosmfreitas2409/time-and-attendance-web?message=TOPLanguage&color=5965E0"
>
<img
alt="Github Language Count"
src="https://img.shields.io/github/languages/count/carlosmfreitas2409/time-and-attendance-web?message=Languages&color=5965E0"
>
<a href="https://github.com/carlosmfreitas2409/time-and-attendance-web/commits/master">
<img alt="GitHub last commit" src="https://img.shields.io/github/last-commit/carlosmfreitas2409/time-and-attendance-web?message=Commit&color=5965E0">
</a>
<img
alt="Project License"
src="https://img.shields.io/github/license/carlosmfreitas2409/time-and-attendance-web?message=MIT&color=5965E0"
>
</p>
<p align="center">
<img src=".github/mockup.png" alt="Time & Attendance" width="100%">
</p>
----
## 💡 Sobre
O <b>Time & Attendance</b> é uma aplicação em que você pode registrar e acompanhar seus pontos eletrônicos de maneira simples e fácil!
Este projeto foi um desafio desenvolvido para uma avaliação técnica.
## 🛠️ Tecnologias
Esse projeto foi desenvolvido usando as seguintes tecnologias:
- [Next.js](https://nextjs.org/)
- [ReactJS](https://pt-br.reactjs.org)
- [Typescript](https://typescriptlang.org/)
- [Axios](https://github.com/axios/axios)
- [Chakra UI](https://chakra-ui.com)
- [Date-fns](https://date-fns.org/)
- [Yup](https://github.com/jquense/yup)
- [React Hook Form](https://react-hook-form.com)
- [React Input Mask](https://www.npmjs.com/package/react-input-mask)
## 🎨 Layout
Nos links abaixo você encontra o layout do projeto Web. Lembrando que você precisa ter uma conta no [Figma](https://figma.com) para acessá-lo.
- [Layout Web](https://www.figma.com/file/BLDK4nVufBNhcbLMfOqBgC/Time-&-Attendance)
## :information_source: Instalação e uso
Para clonar e executar esta aplicação, você precisará do [Git](https://git-scm.com/) e [Yarn](https://yarnpkg.com/). A partir de sua linha de comando:
```bash
# Clone este repositório
$ git clone https://github.com/carlosmfreitas2409/time-and-attendance-web
# Entre no repositório
$ cd time-and-attendance-web
# Instale as dependências
$ yarn
# Rode a aplicação
$ yarn dev
# Navegue para http://localhost:3000
# A aplicação será recarregada automaticamente se você alterar qualquer um dos arquivos.
# OBS: Você precisa estar com a API iniciada.
```
## ⚙️ Como contribuir
- Faça um fork desse repositório;
- Crie uma branch com a sua feature: `git checkout -b minha-feature`;
- Faça commit das suas alterações: `git commit -m 'feat: Minha nova feature'`;
- Faça push para a sua branch: `git push origin minha-feature`;
## 📝 Licença
Esse projeto está sob a licença MIT. Veja o arquivo [LICENSE](https://github.com/carlosmfreitas2409/time-and-attendance-web/blob/master/LICENSE) para mais detalhes.
---
Feito com 💜 por Carlos Eduardo 👋 [Confira meu LinkedIn](https://www.linkedin.com/in/carlosmeduardo/)
|
PHP
|
UTF-8
| 2,641
| 3.09375
| 3
|
[] |
no_license
|
<?php
/**
* @file
*
* @package \Bookpro\Database\DatabaseAbstract
*/
namespace Bookpro\Database;
/**
* Class DatabaseAbstract
*/
abstract class DatabaseAbstract
{
/**
* @var $database static; Should allow connection Mysql, same for all subclasses
*/
private static $database;
/**
* @var $table array, Array of tables for subclases
*/
private static $table = [];
/**
* Contructor
*/
public function __construct($database = false){
self::init($database);
}
/**
* @method initialize
*/
public static function init($database=false){if(!($database===false))self::$database=$database;}
/**
* @return $database
*/
public static function getdatabase() { return self::$database; }
/**
* @return $table
*/
public static function getTable($classname) { return self::$table[$classname]; }
/**
* Return requete type
*
* @param string , should contains a Statement request.
* @param class
*
* @return $object type
*/
public static function fetchFromdatabase($stmt, $table){
return static::getdatabase()->query($stmt)->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, $table);
}
/**
* Return array array assoc
*
* @param string , $stmt
*/
public static function queryAssoc($stmt){
return static::getdatabase()->query($stmt)->fetchAll(\PDO::FETCH_ASSOC);
}
/**
* Bind
*/
public function bind($param, $value, $type= null){
if(is_null($type)){
switch (true) {
case is_bool($value):
$type = \PDO::PARAM_BOOL;
break;
case is_int($value):
$type = \PDO::PARAM_INT;
break;
case is_null($value):
$type = \PDO::PARAM_NULL;
break;
default:
$type = \PDO::PARAM_STR;
}
}
static::getdatabase()->bindValue($parameter, $value, $type);
}
/**
* Begin Transaction
*/
public static function beginTransaction(){
static::getdatabase()->beginTransaction();
}
/**
* @return array
*/
public static function prepareBy($stmt, $value){
$q = static::getdatabase()->prepare($stmt);
$q->execute([$value]);
$row = $q->fetch(\PDO::FETCH_ASSOC);
return $row;
}
}
|
Python
|
UTF-8
| 153
| 3.375
| 3
|
[
"MIT"
] |
permissive
|
'''8. Write a Python program to check a dictionary is empty or not.'''
dict1 = {'a': 2, 'b': 3, 'c': 34}
dict2 = {}
print(any(dict1))
print(any(dict2))
|
Python
|
UTF-8
| 690
| 3.03125
| 3
|
[] |
no_license
|
from .angle import *
def plot_test():
"""Make sure that the red x is inside the halo of blue dots."""
import matplotlib.pyplot as plt
deviationfrompole=.1
fig,ax=plt.subplots(figsize=(10,4),ncols=2)
sxy=SphereCoordinate(pi+.5,pi-deviationfrompole)
xy=[sxy.random_shift(bds=((1+cos(.05))/2,(1+cos(.1))/2)) for i in range(1000)]
xy=vstack(xy)
ax[0].plot(xy[:,0],xy[:,1],'o')
ax[0].plot(sxy.phi,sxy.theta,'rx',mew=3)
sxy=SphereCoordinate(pi+.5,deviationfrompole)
xy=[sxy.random_shift(bds=((1+cos(.05))/2,(1+cos(.1))/2)) for i in range(1000)]
xy=vstack(xy)
ax[1].plot(xy[:,0],xy[:,1],'o')
ax[1].plot(sxy.phi,sxy.theta,'rx',mew=3)
|
Ruby
|
UTF-8
| 1,808
| 3.984375
| 4
|
[] |
no_license
|
require "byebug"
def two_sum_v1?(arr, target)
arr.each_with_index do |ele1, idx1| #o(n)
arr.each_with_index do |ele2, idx2| #o(n)
if idx1 < idx2
return true if ele1 + ele2 == target
end
end
end
false
end
arr = [0, 1, 5, 7]
def two_sum_v2?(arr,target) # linearithmic
sorted = quick_sort(arr) #o(nlogn)
sorted.each_with_index do |ele, idx| #o(n)
# debugger
search_value = target - ele
search_index = bsearch(sorted, search_value) # o(logn)
return true if (idx != search_index && search_index != nil)
end
false
end
def quick_sort(arr) # linearthmic
return arr if arr.length <= 1
pivot = arr.first
left_side = arr[1..-1].select {|num| num < pivot}
right_side = arr[1..-1].select {|num| num >= pivot}
quick_sort(left_side) + [pivot] + quick_sort(right_side)
end
def bsearch(arr, target) #logarithmic
mid = arr.length / 2
case target <=> arr[mid]
when -1
return bsearch(arr[0...mid],target)
when 0
return mid
when 1
answer = bsearch(arr[mid+1..-1], target)
# if answer.nil?
# return nil
# else
# return answer + 1 + mid
# end
return answer + mid + 1 unless answer.nil?
end
nil
end
# arr = [1,2,3,4,5,6,7,8,9]
# p bsearch(arr, 6)
# p two_sum_v2?(arr, 6) # => should be true
# p two_sum_v2?(arr, 11) # => should be false
def two_sum_v3?(arr, target)
hash = Hash.new
arr.each { |ele| hash[ele] = ele } #o(n)
arr.each do |ele| #o(n)
search_value = target - ele
return true if !hash[search_value].nil? && hash[search_value] != ele
end
false
end
p two_sum_v3?(arr, 6) # => should be true
p two_sum_v3?(arr, 10) # => should be false
|
Shell
|
UTF-8
| 266
| 3.28125
| 3
|
[
"MIT"
] |
permissive
|
#!/bin/bash
NODEID=`cat /etc/node_id`
if [ "$NODEID" == "1" ]; then
LOCALIP=`curl -s http://169.254.169.254/2011-05-01/meta-data/local-ipv4`
for i in $(seq 5 -1 1)
do echo "$LOCALIP mongo load complete, ready for transfer or resuming in $i"
sleep 60
done
fi
|
SQL
|
UTF-8
| 5,540
| 3.6875
| 4
|
[] |
no_license
|
create table tb_client(
client_id int primary key,
client_fname nvarchar(50),
client_lname nvarchar(50),
client_phone int,
client_email nvarchar(50),
client_address nvarchar(50)
);
create table tb_car(
car_id int primary key,
car_model nvarchar(50),
cal_color nvarchar(50),
rental_price int
);
create table tb_booking(
booking_id int primary key,
booking_date date,
booking_duration nvarchar(50),
total_price int,
client_id int foreign key references tb_client(client_id),
car_id int foreign key references tb_car(car_id)
);
insert into tb_client values(1,'magdy','fawzy',01127485678,'magdy@email.com','elray street 4');
insert into tb_client values(2,'Doha','Gamal',01227485678,'doha@email.com','elray street 5');
insert into tb_client values(3,'ahmed','ismail',01527485678,'ahmed@email.com','mandara street 7');
insert into tb_client values(4,'fares','mohamed',01129875678,'fares@email.com','manshia street 8');
insert into tb_client values(5,'ibrahim','elmnofy',01127485558,'ibrahim@email.com','qlen street 4');
insert into tb_client values(6,'youssef','loay',01123385678,'youssef@email.com','sidi gaber street 4');
insert into tb_client values(7,'abdo','yassen',01127485699,'abdo@email.com','smouha street 7');
insert into tb_client values(8,'abdallah','aboshoieka',01127481178,'abdalluh@email.com','negrig street 9');
select*from tb_client;
insert into tb_car values(10,'lada','white',200);
insert into tb_car values(11,'mercedes','black',300);
insert into tb_car values(12,'reno 2f','blue',400);
insert into tb_car values(13,'Audi','navy',500);
insert into tb_car values(14,'porsche','black',2000);
insert into tb_car values(15,'Opel','white',1000);
insert into tb_car values(16,'ladaJaguar','yellow',500);
insert into tb_car values(17,'Skoda','black',700);
select*from tb_car;
insert into tb_booking values(20,'11-9-2020','2 months',3000,1,10);
insert into tb_booking values(21,'2-9-2020','3 months',3500,2,11);
insert into tb_booking values(22,'9-9-2020','1 months',4000,3,12);
insert into tb_booking values(23,'10-9-2020','2 weeks',6000,4,13);
insert into tb_booking values(24,'11-7-2020','1 months',2000,5,14);
insert into tb_booking values(25,'12-11-2020','3 weeks',4000,6,15);
select*from tb_booking;
--1-what is the usage of ASCII function?
SELECT ASCII(client_fname) AS NumCodeOfFirstChar
FROM tb_client;
--2-how to use CHAR function?
SELECT CHAR(75) AS CodeToCharacter;
--3-how to use CHARINDEX function?
SELECT CHARINDEX('d', 'Abdalluh') AS MatchPosition;
--4-how to use CONCAT function?
SELECT CONCAT('fares', '.com');
--5-how to use DATALENGTH function?
SELECT DATALENGTH('Doha');
--6-how to know the difference between two words?
SELECT DIFFERENCE('skoda', 'lada');
--7-how to use LEFT function?
SELECT LEFT('ibrahim', 3) AS ExtractString;
--8-how to use LEN function?
SELECT LEN('mercedes');
--9-how to use LOWER function?
SELECT LOWER('Gamal');
--10-how to use NCHAR function?
SELECT NCHAR(65) AS NumberCodeToUnicode;
--11-how to use PATINDEX function?
SELECT PATINDEX('aly', 'Mohamed');
--12-how to use REPLACE function?
SELECT REPLACE('Opel', 'e', 'w');
--13-how to use REVERSE function?
SELECT REVERSE('Abo shoieka');
--14-how to use RIGHT function?
SELECT RIGHT('yassen', 3) AS ExtractString;
--15-how to use RTRIM function?
SELECT RTRIM('lada ') AS RightTrimmedString;
--16-how to use STR function?
SELECT STR(65);
--17-how to use SUBSTRING function?
SELECT SUBSTRING('Mohamed', 1, 3) AS ExtractString;
--18-how to use UNICODE function?
SELECT UNICODE('ismail');
--19-how to use UPPER function?
SELECT UPPER('mandara street 4');
--20-how to use SOUNDEX function?
SELECT SOUNDEX('moatasem'), SOUNDEX('nada');
--sub query
SELECT client_fname FROM tb_client WHERE client_id in (SELECT client_id FROM tb_car WHERE car_id >13)
SELECT car_model FROM tb_car WHERE car_id in (SELECT car_id FROM tb_client WHERE client_id >2)
SELECT client_address FROM tb_client WHERE client_id in (SELECT client_id FROM tb_car WHERE car_id >14)
--different join
SELECT car_model, client_lname
FROM tb_car
INNER JOIN tb_client
ON tb_car.car_id = tb_client.client_id;
SELECT client_email, car_id
FROM tb_client
LEFT JOIN tb_car
ON tb_client.client_id = tb_car.car_id;
SELECT client_phone, total_price
FROM tb_client
RIGHT JOIN tb_booking
ON tb_client.client_id = tb_booking.booking_id;
SELECT client_phone, booking_id
FROM tb_client
FULL JOIN tb_booking
ON tb_client.client_id = tb_booking.booking_id;
SELECT client_fname,booking_date
FROM tb_client,tb_booking
WHERE tb_client.client_id=tb_booking.booking_id
--count and group
--what the number of clients ?
SELECT COUNT(client_id)
FROM tb_client
--what is the number of cars ?
SELECT COUNT(car_id)
FROM tb_car
--Group
SELECT COUNT(client_id), client_email
FROM tb_client
GROUP BY client_email
--update
UPDATE tb_car
set car_model='skoda' where car_id=1
UPDATE tb_client
set client_fname='noha' where client_id=3
UPDATE tb_booking
set total_price=6000 where booking_id=24
UPDATE tb_client
set client_lname='nader' where client_id=5
UPDATE tb_car
set cal_color='green' where car_id=12
select*from tb_booking;
select*from tb_car;
select*from tb_client;
--delete
DELETE from tb_client where client_id=7
DELETE from tb_car where car_id=16
DELETE from tb_booking where booking_id =25
DELETE from tb_client where client_fname='ahmed'
DELETE from tb_car where car_id=8
select*from tb_booking;
select*from tb_car;
select*from tb_client;
|
JavaScript
|
UTF-8
| 2,086
| 2.78125
| 3
|
[] |
no_license
|
const passport = require('passport');
const UserModel = require('../models/user-model.js');
// it determines what gets saved into the session when you log in.
passport.serializeUser((userFromDb, done) => {
// tell passport we want to save the ID inside the session
done(null, userFromDb._id);
});
// it tells passport how to get the user's information
passport.deserializeUser((idFromBowl, done) => {
UserModel.findById(
idFromBowl,
(err, userFromDb) => {
// if there's a database error, inform passport.
if (err) {
done(err);
return;
}
// give passport the user document from the database
done(null, userFromDb);
}
);
});
// ---------------------------------------------------------------------
// STRATEGIES SETUP
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
// "passport.use()" sets up a new strategy
passport.use(
new LocalStrategy({
usernameField: 'userValue',
passwordField: 'password'
},
(userValue, passValue, done) => {
// find the user in the DB with that email
UserModel.findOne({
$or:[{ email: userValue},
{username: userValue}]
},
(err, userFromDb) => {
if (err) {
done(err);
return;
}
// "userFromDb" will be "null" if we didn't find anything
if (userFromDb === null) {
done(null, false, { message: 'Invalid email or password.' });
return;
}
// validates password
const isGoodPassword = bcrypt.compareSync(passValue, userFromDb.encryptedPassword);
if (isGoodPassword === false) {
done(null, false, { message: 'Invalid email or password.' });
return;
}
// If information is correct, sends passport the user document.
done(null, userFromDb);
});
}));
|
Python
|
UTF-8
| 7,238
| 3.40625
| 3
|
[] |
no_license
|
# neuralnet.py
# ---------------
# Licensing Information: You are free to use or extend this projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to the University of Illinois at Urbana-Champaign
#
# Created by Justin Lizama (jlizama2@illinois.edu) on 10/29/2019
"""
This is the main entry point for MP6. You should only modify code
within this file -- the unrevised staff files will be used for all other
files and classes when code is run, so be careful to not modify anything else.
"""
import numpy as np
import torch
#####
# Part 2 To-Do List:
# * Change activation function.
# * Use multiple activation functions (one between input to hidden, one between hidden and output)
# * Change number of hidden units
# * Add more hidden layers (with different number of hidden units). Makes more weights and biases.
# * Add more activation functions for these hidden layers
# * Implement L2 Regularization
# * Implement data standardization
#####
class NeuralNet(torch.nn.Module):
def __init__(self, lrate,loss_fn,in_size,out_size):
"""
Initialize the layers of your neural network
@param lrate: The learning rate for the model.
@param loss_fn: A loss function defined in the following way:
@param yhat - an (N,out_size) tensor
@param y - an (N,) tensor
@return l(x,y) an () tensor that is the mean loss
@param in_size: Dimension of input
@param out_size: Dimension of output
For Part 1 the network should have the following architecture (in terms of hidden units):
in_size -> 32 -> out_size
"""
super(NeuralNet, self).__init__()
self.loss_fn = loss_fn # loss function
self.input_size = in_size # input_size
self.output_size = out_size # output size
self.learning_rate = lrate # learning rate
self.tanh = torch.nn.Tanh() # Activation function
self.hiddenActivation = torch.nn.ReLU()
self.inputToHidden = torch.nn.Linear(in_size, 100) # weight.size = [32, 3072]. bias.size = [32]
self.hiddenToHidden = torch.nn.Linear(100, 50)
self.hiddenToOutput = torch.nn.Linear(50, out_size) # weight.size = [2, 32]. bias.size = [2]
self.inputToHiddenOpt = torch.optim.SGD([self.inputToHidden.weight, self.inputToHidden.bias], lr=lrate)
self.hiddenToOutputOpt = torch.optim.SGD([self.hiddenToOutput.weight, self.hiddenToOutput.bias], lr=lrate)
self.hiddenToHiddenOpt = torch.optim.SGD([self.hiddenToHidden.weight, self.hiddenToHidden.bias], lr=lrate)
def set_parameters(self, params):
""" Set the parameters of your network
@param params: a list of tensors containing all parameters of the network
"""
self.inputToHidden.weight = params[1]
self.inputToHidden.bias = params[2]
self.hiddenToOutput.weight = params[3]
self.hiddenToOutput.bias = params[4]
self.hiddenToHidden.weight = params[5]
self.hiddenToHidden.bias = params[6]
return
def get_parameters(self):
""" Get the parameters of your network
@return params: a list of tensors containing all parameters of the network
"""
return [self.inputToHidden.weight, self.inputToHidden.bias, self.hiddenToOutput.weight, self.hiddenToOutput.bias, self.hiddenToHidden.weight, self.hiddenToHidden.bias]
def forward(self, x):
""" A forward pass of your neural net (evaluates f(x)).
@param x: an (N, in_size) torch tensor
@return y: an (N, out_size) torch tensor of output from the network
"""
xNP = x.numpy()
xMean = np.mean(xNP)
xSTD = np.std(xNP)
xNP = (xNP - xMean) / xSTD
x = torch.from_numpy(xNP)
y = torch.ones(x.shape[0], 2)
for index, image in enumerate(x):
tanInput = torch.matmul(self.inputToHidden.weight, image) + self.inputToHidden.bias
tan = self.tanh(tanInput)
yVal = torch.matmul(self.hiddenToHidden.weight, tan) + self.hiddenToHidden.bias
activator = self.hiddenActivation(yVal)
finalVal = torch.matmul(self.hiddenToOutput.weight, activator) + self.hiddenToOutput.bias
y[index] = finalVal
return y
def step(self, x,y):
"""
Performs one gradient step through a batch of data x with labels y
@param x: an (N, in_size) torch tensor
@param y: an (N,) torch tensor
@return L: total empirical risk (mean of losses) at this time step as a float
"""
self.inputToHiddenOpt.zero_grad()
self.hiddenToHiddenOpt.zero_grad()
self.hiddenToOutputOpt.zero_grad()
yhats = self.forward(x)
loss = self.loss_fn(yhats, y)
loss.backward()
self.inputToHiddenOpt.step()
self.hiddenToHiddenOpt.step()
self.hiddenToOutputOpt.step()
return loss.item()
# loss=self.loss_fn(self.forward(x),y)
# self.optimizer.zero_grad()
# loss.backward()
# self.optimizer.step()
# return loss.item()
# Taken from https://towardsdatascience.com/understanding-pytorch-with-an-example-a-step-by-step-tutorial-81fc5f8c4e8e
class trainData(torch.utils.data.Dataset):
def __init__(self, x_tensor, y_tensor):
self.x = x_tensor
self.y = y_tensor
def __getitem__(self, index):
return (self.x[index], self.y[index])
def __len__(self):
return len(self.x)
def fit(train_set,train_labels,dev_set,n_iter,batch_size=100):
""" Make NeuralNet object 'net' and use net.step() to train a neural net
and net(x) to evaluate the neural net.
@param train_set: an (N, out_size) torch tensor
@param train_labels: an (N,) torch tensor
@param dev_set: an (M,) torch tensor
@param n_iter: int, the number of epochs of training
@param batch_size: The size of each batch to train on. (default 100)
# return all of these:
@return losses: Array of total loss at the beginning and after each iteration. Ensure len(losses) == n_iter
@return yhats: an (M,) NumPy array of approximations to labels for dev_set
@return net: A NeuralNet object
# NOTE: This must work for arbitrary M and N
"""
loss_fn = torch.nn.CrossEntropyLoss()
losses = []
net = NeuralNet(0.1, loss_fn, train_set.size()[1], 2) # The input size is the length of features (3072). Output size is different possible classes (2).
training_data = trainData(train_set, train_labels)
training_loader = torch.utils.data.DataLoader(dataset=training_data, batch_size=batch_size, shuffle=False)
for epoch in range(n_iter):
batch = next(iter(training_loader))
batchStep = net.step(batch[0], batch[1])
losses.append(batchStep)
predictions = net.forward(dev_set)
dev_labels = np.zeros(dev_set.size()[0])
for index, pred in enumerate(predictions):
dev_labels[index] = torch.argmax(pred).item()
torch.save(net, "net")
return losses, dev_labels, net
|
Java
|
UTF-8
| 247
| 3.0625
| 3
|
[] |
no_license
|
public class OffByOne implements CharacterComparator {
@Override
public boolean equalChars(char first, char second) {
int diff = first - second;
int gapNum = 1;
return (diff == gapNum) || (diff == -gapNum);
}
}
|
Markdown
|
UTF-8
| 6,668
| 3.65625
| 4
|
[] |
no_license
|
[TOC]
### JavaScript概述
- 简介:是基于对象和事件驱动的语言,应用于客户端;是基于对象的,它给我们提供了很多对象,可以直接拿过来使用。
- 事件驱动:html做网站的静态效果,javasript做出动态效果;
- 客户端:即浏览器;
- 特点:
- 交互性(信息的动态交互)
- 安全性(不可以直接访问本地硬盘)
- 跨平台性(只要是可以解析js的浏览器都可以执行,和平台无关)
- javascript的组成
- ECMAScript
- ECMA:欧洲计算机协会
- 由ECMA组织指定的js的语法,语句……
- BOM【broswer object model】:浏览器对象模型
- DOM【document object model】:文档对象模型
### java和javascript的区别
- java是sun公司开发;js是网景公司;
- java是面向对象;javascript是基于对象的;
- java是强类型的语言;js是弱类型的语言;
- java需要先编译成class文件才可以运行;而js只需要解析就可以运行;
### js和html的结合方式
- 方法一:使用一个标签< script type=“text/javascript” >js代码;< /script>
- 方法二: 使用script标签,引入一个外部的js文件
- 创建一个js文件,写js代码;
- < script type="text/javascript" src="1.js">< /script >
> 使用第二种方法的时候,不要再script标签里面写js代码了,因为它不会执行
### js的原始类型和声明变量
- java的基本类型:byte,short,int,long,float,double,char,boolean
- js的原始类型:
- string:字符串,如:var str=“abc”;
- number:数字类型,如:var m=10;
- boolean:true和false,如:var flag=true;
- null:获取对象的引用,null表示对象引用为空;
- undifined:定义一个变量,没有赋值,如var aa;
> js定义变量都使用关键字-var;名称可以自定义;
> typeof:查看当前变量的数据类型
### js的语句- 和java里面的差不多
- java里面的语句:if判断;switch语句;for循环,while循环,do-while循环
- js里面的这些语句
- if判断语句
- switch语句:js里面支持所有的类型
### js的运算符
和java的不同:
- js中不区分小数和整数,123/1000*1000在js中是123,但是在java中是0;
- Boolean类型可以进行运算,false就是0或者null,非0非空是true,默认用1显示;
```html
<script type="text/javascript">
alert(false);//false
alert(true);//true
alert(false+1);//1
alert(true+1);//2
</script>
```
- 字符串的相加和相减
- 相加做的是字符串的连接运算;
- 相减做的是数的减法运算,如果字符串不是数字而使用了相减,会出现Nan;
```html
<script type="text/javascript">
var i=123;
alert(i/1000*1000);//123
var i2="49";
alert(i2+1);//491
alert(i2-1);//48
var i3="a";
alert(i3+1);//a1
alert(i3-1);//Nan,表示不是一个数字
</script>
```
- 等号
- =:赋值;
- ==:比较的是值,即数字类型也可以和字符串进行比较;
- ===:比较的是值和类型,即只有类型相同才可以进行比较;
```html
<script type="text/javascript">
var i=10;
var x="20";
if(i==="10"){
alert(10);
}else{
alert(123);
}
</script>
```
补充:
- 直接向页面输出的语句,即可以向页面输出变量,固定值和html代码;
- document.write(“aaa”);
- document.write(“< br/ >”);
- document.write(“< hr/ >”);
> document.write里面是双引号,如果想要设置标签的属性,需要使用单引号;
>
> document.write可以输出变量,还可以输出html代码;
#### js的数组
定义方式
- 方式一:var arr=[1,3,5]; var arr=[1,3,”5”,true,3.14]
- 方式二:使用内置对象Array对象--先定义长度,在填充
- 方法三;使用内置对象Array--定义数组的同时填充内容
```html
<script type="text/javascript">
//方法一
var arr1=[1,3,5,true,"A"];
// alert(arr1);
//方法二
var arr2=new Array(3);
arr2[0]=1;
arr2[1]=2;
arr2[2]=3;
alert(arr2);
//方法三
var arr3=new Array(1,6,6,6,6);
alert(arr3);
alert(arr3.length);
</script>
```
> 数组长度:数组名.length
#### js的函数/方法
- 参数列表中不需要写var,可以直接写变量;
- 方法一:使用关键字function
- function 方法名(参数列表){方法体;返回值可有可无}
```html
<script type="text/javascript">
//定义一个三个数相乘的方法
function method(a,b,c){
var sum=a+b+c;
alert(sum);
}
//调用
method(2,3,5)
</script>
```
- 匿名方法;var 自定义名称=function(参数列表){方法体和返回值;}
```html
<script type="text/javascript">
//定义一个三个数相乘的方法
var method=function method(a,b,c){//
var sum=a+b+c;
alert(sum);
}
//调用
method(2,3,5)
</script>
```
- 方法三:【了解】:使用到js里面的一个内置对象Function
- var 自定义名称=new Function(“参数列表”,“方法体和返回值”)
#### js的全局变量和局部变量
- 全局变量:在script标签里面定义一个变量,这个变量在页面中js部分都可以使用
- 局部变量:在方法内部定义一个变量,只能在方法内部使用;
> ie自带了一个调试工具,ie8及其以上的版本,F12;
#### js标签的位置
- 理论上放到哪里都可以,即使是< /script >的结尾后面,但是建议吧script标签放到< /body > 后面;
- 如果你想要在js中获取input里面的值,但是script标签放的是head里面,此时我们无法取到里面的值;因为html是从上到下解析的,你把script标签放到head里面,而input是需要放到body里面的,这样当我们想要获取值的时候,页面还没有解析到input那一行,就无法取到;
|
Java
|
UTF-8
| 753
| 3.609375
| 4
|
[] |
no_license
|
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Введите размер массива: ");
int size = scanner.nextInt();
int[] mas = new int[size];
for (int i = 0; i < mas.length; i++) {
int a = 100;
int randomNumber = (int) (Math.random() * a);
mas[i] = randomNumber;
}
for (int i = 0; i < mas.length; i++) { //для проверки
System.out.print(mas[i] + " ");
}
System.out.println("");
for (int i = 1; i < mas.length; i += 2) {
int a = mas[i];
mas[i] = mas[i - 1];
mas[i - 1] = a;
}
for (int i = 0; i < mas.length; i++) {
System.out.print(mas[i] + " ");
}
}
}
|
PHP
|
UTF-8
| 1,896
| 2.8125
| 3
|
[] |
no_license
|
<?php
/*
* This file is part of sebastian/object-graph.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace SebastianBergmann\ObjectGraph;
use SebastianBergmann\ObjectEnumerator\Enumerator;
use SebastianBergmann\ObjectReflector\ObjectReflector;
final class Builder
{
public function build($objectGraph): NodeCollection
{
/** @var int[] $map */
$map = new \SplObjectStorage;
$enumerator = new Enumerator;
$id = 1;
$nodes = [];
foreach ($enumerator->enumerate($objectGraph) as $object) {
$map[$object] = $id++;
}
foreach ($enumerator->enumerate($objectGraph) as $object) {
$attributes = [];
$reflector = new ObjectReflector;
foreach ($reflector->getAttributes($object) as $name => $value) {
if (\is_array($value)) {
$value = $this->processArray($value, $map);
} elseif (\is_object($value)) {
$value = new NodeReference($map[$value]);
}
$attributes[$name] = $value;
}
$nodes[] = new Node($map[$object], \get_class($object), $attributes);
}
return new NodeCollection($nodes);
}
private function processArray(array $array, \SplObjectStorage $map): array
{
/** @var int[] $map */
$result = [];
foreach ($array as $key => $value) {
if (\is_array($value)) {
$value = $this->processArray($value, $map);
} elseif (\is_object($value)) {
$value = new NodeReference($map[$value]);
}
$result[$key] = $value;
}
return $result;
}
}
|
Java
|
UTF-8
| 920
| 2.984375
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.googlecode.dex2jar.ir.ts;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
public class UniqueQueue<T> extends LinkedList<T> {
private static final long serialVersionUID = 7578371020752763662L;
Set<T> set = new HashSet<>();
public UniqueQueue() {
}
@Override
public boolean addAll(Collection<? extends T> c) {
boolean result = false;
for (T t : c) {
if (add(t)) {
result = true;
}
}
return result;
}
@Override
public boolean add(T t) {
if (set.add(t)) {
super.add(t);
}
return true;
}
public T poll() {
T t = super.poll();
set.remove(t);
return t;
}
@Override
public T pop() {
T t = super.pop();
set.remove(t);
return t;
}
}
|
C#
|
UTF-8
| 5,263
| 3.59375
| 4
|
[] |
no_license
|
using System;
using System.Collections.Generic;
namespace BuilderDesignPatternExample
{
/// <summary>
/// The 'Product' class
/// </summary>
class Vehicle
{
VehicleType vehicleType;
Dictionary<PartType, string> parts = new Dictionary<PartType, string>();
// Constructor
public Vehicle(VehicleType vehicleType)
{
this.vehicleType = vehicleType;
}
public string this[PartType key]
{
get { return parts[key]; }
set { parts[key] = value; }
}
public void Show()
{
Console.WriteLine("\n---------------------------");
Console.WriteLine("Vehicle Type: {0}", vehicleType);
Console.WriteLine(" Frame : {0}",
this[PartType.Frame]);
Console.WriteLine(" Engine : {0}",
this[PartType.Engine]);
Console.WriteLine(" #Wheels: {0}",
this[PartType.Wheel]);
Console.WriteLine(" #Doors : {0}",
this[PartType.Door]);
}
}
/// <summary>
/// Part type enumeration
/// </summary>
public enum PartType
{
Frame,
Engine,
Wheel,
Door
}
/// <summary>
/// Vehicle type enumeration
/// </summary>
public enum VehicleType
{
Car,
Scooter,
MotorCycle
}
/// <summary>
/// The 'Builder' abstract class
/// </summary>
abstract class VehicleBuilder
{
public Vehicle Vehicle { get; private set; }
// Constructor
public VehicleBuilder(VehicleType vehicleType)
{
Vehicle = new Vehicle(vehicleType);
}
public abstract void BuildFrame();
public abstract void BuildEngine();
public abstract void BuildWheels();
public abstract void BuildDoors();
}
/// <summary>
/// The 'Director' class
/// </summary>
class Shop
{
VehicleBuilder vehicleBuilder;
// Builder uses a complex series of steps
public void Construct(VehicleBuilder vehicleBuilder)
{
this.vehicleBuilder = vehicleBuilder;
this.vehicleBuilder.BuildFrame();
this.vehicleBuilder.BuildEngine();
this.vehicleBuilder.BuildWheels();
this.vehicleBuilder.BuildDoors();
}
public void ShowVehicle()
{
vehicleBuilder.Vehicle.Show();
}
}
//-----------------------------------------------------------------------------
/// <summary>
/// 'ConcreteBuilder1' - Motor Cycle
/// </summary>
class MotorCycleBuilder : VehicleBuilder
{
// Invoke base class constructor
public MotorCycleBuilder()
: base(VehicleType.MotorCycle)
{
}
public override void BuildFrame()
{
Vehicle[PartType.Frame] = "MotorCycle Frame";
}
public override void BuildEngine()
{
Vehicle[PartType.Engine] = "500 cc";
}
public override void BuildWheels()
{
Vehicle[PartType.Wheel] = "2";
}
public override void BuildDoors()
{
Vehicle[PartType.Door] = "0";
}
}
/// <summary>
/// ConcreteBuilder2 - Car Builder
/// </summary>
class CarBuilder : VehicleBuilder
{
// Invoke base class constructor
public CarBuilder()
: base(VehicleType.Car)
{
}
public override void BuildFrame()
{
Vehicle[PartType.Frame] = "Car Frame";
}
public override void BuildEngine()
{
Vehicle[PartType.Engine] = "2500 cc";
}
public override void BuildWheels()
{
Vehicle[PartType.Wheel] = "4";
}
public override void BuildDoors()
{
Vehicle[PartType.Door] = "4";
}
}
/// <summary>
/// ConcreteBuilder3 - Scooter
/// </summary>
class ScooterBuilder : VehicleBuilder
{
// Invoke base class constructor
public ScooterBuilder() : base(VehicleType.Scooter)
{
}
public override void BuildFrame()
{
Vehicle[PartType.Frame] = "Scooter Frame";
}
public override void BuildEngine()
{
Vehicle[PartType.Engine] = "50 cc";
}
public override void BuildWheels()
{
Vehicle[PartType.Wheel] = "2";
}
public override void BuildDoors()
{
Vehicle[PartType.Door] = "0";
}
}
class Program
{
static void Main(string[] args)
{
//1. Director
var director = new Shop();
//2. Scooter Builder
director.Construct(new ScooterBuilder());
director.ShowVehicle();
//Car Builder
director.Construct(new CarBuilder());
director.ShowVehicle();
//MotorCycle Builder
director.Construct(new MotorCycleBuilder());
director.ShowVehicle();
Console.ReadKey();
}
}
}
|
Python
|
UTF-8
| 580
| 3.859375
| 4
|
[] |
no_license
|
# Assignment 3-1
def calculator (val1, val2, opt):
if opt == '+':
return val1 + val2
elif opt == '-':
return val1 - val2
elif opt == '*':
return val1 * val2
elif opt == '/':
return val1 / val2
elif opt == '//':
return val1 // val2
elif opt == '%':
return val1 % val2
elif opt == '**':
return val1 ** val2
else:
print("다시 입력해주세요.")
quit()
user_input = list(map(str, input().split(" ")))
print(calculator(int(user_input[0]), int(user_input[1]), user_input[2]))
|
Java
|
UTF-8
| 1,193
| 2.859375
| 3
|
[] |
no_license
|
package de.moritz.upperbuchstabe;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class QueueTest {
private Queue queue;
@Before
public void erzeugeQueue(){
queue = new Queue(3);
}
@Test(expected=IllegalArgumentException.class, timeout=1000)
public void queueTest() {
new Queue(0);
}
@Test(expected=IllegalStateException.class, timeout=1000)
public void dequeueTest() {
queue.dequeue();
}
@Test
public void enqueue_dequeueTest() {
int para1 =1,para2 =2,para3 =3;
queue.enqueue(para1);
queue.enqueue(para2);
queue.enqueue(para3);
assertEquals(para1, queue.dequeue());
assertEquals(para2, queue.dequeue());
assertEquals(para3, queue.dequeue());
}
@Test
public void enqueue_dequeue_ringTest() {
int para1 =1,para2 =2,para3 =3;
queue.enqueue(para1+10);
queue.enqueue(para2+10);
queue.enqueue(para3+10);
queue.enqueue(para1);
queue.enqueue(para2);
queue.enqueue(para3);
assertEquals(para1+10, queue.dequeue());
assertEquals(para2+10, queue.dequeue());
assertEquals(para3, queue.dequeue());
}
}
|
Java
|
UTF-8
| 489
| 1.984375
| 2
|
[] |
no_license
|
package com.acme.account.dto.request;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
@AllArgsConstructor
@Getter
@Builder(toBuilder = true)
@NoArgsConstructor
public class DecreaseRequestDto {
@NotNull
@Positive(message = "Decrease value must be greater than 0")
private float value;
@NotNull
private String token;
}
|
Java
|
UTF-8
| 411
| 2.046875
| 2
|
[] |
no_license
|
package com.skillindia.datajpa.course;
import javax.persistence.Column;
import javax.persistence.Id;
public class Course {
private static final long serialVersionUID = 1L;
@Id
@Column(unique=true)
private int courseId;
private String courseName;
private String courseDescription;
private int courseDuration;
@Column
private int establishmentId;
@Column
private String requestStatus;
}
|
Markdown
|
UTF-8
| 6,423
| 2.953125
| 3
|
[] |
no_license
|
### 陆抗国战解析
武将技能:
【恪守】
当你受到伤害后时,你可以弃置两张颜色相同的手牌,然后此伤害-1。同时若你已确定势力且没有与你势力相同的其他角色,则你进行一次判定,若结果为红色,你摸一张牌。
【筑围】
你的判定牌生效后,你可以获得之,然后你可令当前回合角色本回合使用杀的次数上限+1,手牌上限+1。
**历史背景**
【恪守】来源于陆抗做事严格遵守,绝不改变的态度。
【筑围】来源于“西陵破晋”,吴军日夜在西陵筑造围墙抵御羊祜。
**技能剖析**
【恪守】
①“当你受到伤害后时,你可以弃置两张颜色相同的手牌”,首先得是受到伤害时,可以弃置同颜色的手牌,没有说一回合一次,所以只要你牌够多,抗下所有伤害也不在话下。重点:
⑴可以,主动技可选择发动与否。
⑵同颜色,并非花色,♠️♣️或者♦️♥️二选一。
⑶手牌,也就是说不能丢装备牌。
②然后此伤害-1,类似羊徽瑜的【弘仪】判定。注意最多只能减少一点伤害,酒杀这种两点以上的伤害挡不住。
③“若你已确定势力………你摸一张牌”简单地讲就是不能有队友。然后此技能才能发动,而判定为红色则摸一张牌。这技能结算的前后顺序是同级的,实测为先判定后询问弃牌与否,也就是说先摸再弃(前提你判红)。此为被动发动不由你控制。【筑围】
①“你的判定牌生效后,你可以获得之”类似于郭嘉的【天妒】,属于配合一技能使用的副技能。
②“然后你可………手牌上限+1”需注意几点⑴可令当前回合角色本回合。主动技,发动权在自己手上,一般不对别人发动,因为都是敌人。除非组成了临时同盟,不然这技能顶多自己用一下。
模式适用性
在国战吴国里属于奇葩的那类,一般吴国都是靠打团过活,单体能力均没有蜀、魏、群强,不都是吴国是个绿皮小火车,全靠火车头带(吕范)。而陆抗很完美的给我们诠释了“你活着,影响我输出”这句话。技能不仅和自己冲突,更合队友格格不入,只要有一个队友在场,陆抗就是个小白板,在这点上与军八的界钟会一样“孤儿”。
**武将评级**∶B+
**玩法技巧**
定位:
不太能理解为什么陆抗这么帅的小哥哥不仅军八被削,在国战也得不到发挥(陆抗:“策划,和着我得罪你了呗?”至于这66的定价,有一大半包含在卡两个灯的价值,可玩性有,但不算高。
玩法技巧:
【恪守】
①陆抗作为一个“独王”适合做野心家,这样就不需要考虑拖后腿的队友啦,一技能与二技能产生联动,过牌量和防御都大大增强,【恪守】不是非得两个技能都使用的,弃牌那个选项是主动技,而后面的判定则为被动技,符合要求自动发动。建议一般只发动判定来过牌,而伤害-1不到万不得已不要用,或者你手牌溢出严重了可以浪一点。
②实测期间,还因未亮将的队友导致无法摸牌(变相坑队友哇),所以陆抗不适合早亮,因为亮了也是白板,还会暴露队友身份,亮的早还会被集火,百害无一利。
③回合外弃牌一般都是弃红色,因为红色牌偏防御,但我都已经是防御牌了,为什么非要弃牌来减伤呢?而且一定得是手牌,把装备牌也加上不好吗?所以这个技能一般不怎么发动。(还好是主动技)
【筑围】
①明面上看是辅助一技能的,实际上属于自相矛盾⑴如果有队友的情况下,一技能直接白板无法触发,就一个防御技。⑵一技能能用的时候应该是就剩你一个人的时候,此刻判定必须得为红色才能拿到两牌的牌差,不然也就一张牌。⑶令本回合武将多出一张杀和加一手牌上限,你会对敌人用这正面收益的技能吗?所以最后只可能是在自己回合开始时判个兵乐。(多出杀与乐中冲突,多手牌上限则与兵冲突)。
②二技能相当于是个限定技,一副牌里有多少兵乐?而这些都贴在你脸上的几率有多大呢?所以技能用出来的频率可想而知,趋于限定技。
③至于同时被兵被乐应该是可以叠加的,手牌上限+2,多出两张杀
④当陆抗只身一人时,【筑围】与【恪守】的契合点达到了最大值,可就算如此也不足以单打成功,所以得组成暂时同盟,把技能用其他阵营的“伙伴”用出来,蹭他aoe或者让他杀你这样你可以过牌,他还能多杀和加上限。最后在与他进入单挑局胜算会大很多。(怎么看这都是陆抗的正确玩法,但怎么跟二五仔一样?确定是咱东吴的人吗?哈哈哈)此刻的陆抗每轮必判定摸牌然后带上多出杀+多手牌上限,这样的单体能力属实不错,就不清楚能否力挽狂澜呢?
接下来看看和陆抗有配合的吴国武将们~虽然吴国没有一个判定将,但好在吴国还有补牌将。这对于陆抗来说可能是个好消息~
①和小乔的配合,在国战配合小乔的【天香】和自己的【恪守】双buff可立于不败之地~再加上小乔的【红颜】加大了判红的概率,增加了陆抗摸牌的几率。
②和吕蒙的配合,吕蒙屯牌,可为陆抗续航,只不过这有点太浪费牌了~
③和吕范的配合,陆抗【恪守】用牌,吕范【典财】补牌再加上【筑围】判定小过牌组合起来过牌量其实很可观的。
要多提一句,很好奇陆抗和他爹陆逊有没有“珠联璧合”的效果。因为技能上完全冲突,陆逊技能为团队服务,陆抗技能单打独斗,陆逊不能被乐,所以降低了陆抗【筑围】的发动几率。这爷俩在一起简直1+1<2~
然后想吐槽一下,东吴是不是喜欢技能上加手牌上限,前有孙邵回炉重造,后有陆抗挺进国战,要知道没有摸牌能力的武将你给他再多手牌上限都没用,还不如来个体力上限更有效。
就是国战的武将搭配由不得我们自己选,往往都不尽如人意,所以以上配合遇到了最好,没遇到的也不能强求噢。
|
C++
|
UTF-8
| 5,109
| 2.546875
| 3
|
[
"Apache-2.0"
] |
permissive
|
#include "halley/tools/make_font/font_face.h"
#include <ft2build.h>
#include FT_FREETYPE_H
#include <halley/text/halleystring.h>
#include <memory>
#include <halley/support/exception.h>
#include <halley/maths/vector2.h>
#include <halley/file_formats/image.h>
#include "halley/text/string_converter.h"
using namespace Halley;
namespace Halley {
class FontFacePimpl
{
public:
FT_Library library = nullptr;
FT_Face face = nullptr;
};
}
FontFace::FontFace(String filename)
: pimpl (std::make_unique<FontFacePimpl>())
{
int error = FT_Init_FreeType(&pimpl->library);
if (error) {
throw Exception("Unable to initialize FreeType", HalleyExceptions::Graphics);
}
error = FT_New_Face(pimpl->library, filename.c_str(), 0, &pimpl->face);
if (error) {
throw Exception("Unable to load font face", HalleyExceptions::Graphics);
}
}
FontFace::FontFace(gsl::span<const gsl::byte> data)
: pimpl (std::make_unique<FontFacePimpl>())
{
int error = FT_Init_FreeType(&pimpl->library);
if (error) {
throw Exception("Unable to initialize FreeType", HalleyExceptions::Graphics);
}
error = FT_New_Memory_Face(pimpl->library, reinterpret_cast<const FT_Byte*>(data.data()), FT_Long(data.size()), 0, &pimpl->face);
if (error) {
throw Exception("Unable to load font face", HalleyExceptions::Graphics);
}
}
FontFace::~FontFace()
{
if (pimpl->face) {
FT_Done_Face(pimpl->face);
}
if (pimpl->library) {
FT_Done_FreeType(pimpl->library);
}
}
void FontFace::setSize(float sz)
{
size = sz;
FT_Set_Char_Size(pimpl->face, 0, lround(size * 64), 72, 0);
}
String FontFace::getName() const
{
return pimpl->face->family_name + String(" ") + pimpl->face->style_name;
}
float FontFace::getSize() const
{
return size;
}
float FontFace::getHeight() const
{
if (pimpl->face->height > 0 && pimpl->face->units_per_EM > 0) {
return pimpl->face->height * size / pimpl->face->units_per_EM;
} else {
return pimpl->face->size->metrics.height / 64.0f;
}
}
float FontFace::getAscender() const
{
if (pimpl->face->units_per_EM > 0) {
return pimpl->face->ascender * size / pimpl->face->units_per_EM;
} else {
return pimpl->face->size->metrics.ascender / 64.0f;
}
}
Vector<int> FontFace::getCharCodes() const
{
Vector<int> result = {0};
FT_UInt index;
for (FT_ULong charcode = FT_Get_First_Char(pimpl->face, &index); index != 0; charcode = FT_Get_Next_Char(pimpl->face, charcode, &index)) {
if (charcode != 0) {
result.push_back(charcode);
}
}
return result;
}
Vector2i FontFace::getGlyphSize(int charCode) const
{
int index = charCode == 0 ? 0 : FT_Get_Char_Index(pimpl->face, charCode);
int error = FT_Load_Glyph(pimpl->face, index, FT_LOAD_DEFAULT);
if (error) {
throw Exception("Unable to load glyph " + toString(charCode), HalleyExceptions::Graphics);
}
auto metrics = pimpl->face->glyph->metrics;
return Vector2i(metrics.width, metrics.height) / 64;
}
void FontFace::drawGlyph(Image& image, int charcode, Vector2i pos) const
{
auto glyph = pimpl->face->glyph;
int index = charcode == 0 ? 0 : FT_Get_Char_Index(pimpl->face, charcode);
int error = FT_Load_Glyph(pimpl->face, index, FT_LOAD_DEFAULT);
if (error) {
throw Exception("Unable to load glyph " + toString(charcode), HalleyExceptions::Graphics);
}
error = FT_Render_Glyph(glyph, FT_RENDER_MODE_MONO);
if (error != 0) {
throw Exception("Unable to render glyph " + toString(charcode), HalleyExceptions::Graphics);
}
auto bmp = glyph->bitmap;
image.blitFrom(pos, gsl::span<unsigned char>(bmp.buffer, bmp.rows * bmp.pitch), bmp.width, bmp.rows, bmp.pitch, 1);
}
FontMetrics FontFace::getMetrics(int charcode, float scale) const
{
int index = FT_Get_Char_Index(pimpl->face, charcode);
int error = FT_Load_Glyph(pimpl->face, index, FT_LOAD_DEFAULT);
if (error) {
throw Exception("Unable to load glyph " + toString(charcode), HalleyExceptions::Graphics);
}
FontMetrics result;
float multiplier = scale / 64.0f;
auto& metrics = pimpl->face->glyph->metrics;
result.advance = Vector2f(Vector2i(metrics.horiAdvance, metrics.vertAdvance)) * multiplier;
result.bearingHorizontal = Vector2f(Vector2i(metrics.horiBearingX, metrics.horiBearingY)) * multiplier;
result.bearingVertical = Vector2f(Vector2i(metrics.vertBearingX, metrics.vertBearingY)) * multiplier;
return result;
}
Vector<KerningPair> FontFace::getKerning(const Vector<int>& codes) const
{
Vector<KerningPair> results;
if (!FT_HAS_KERNING(pimpl->face)) {
return results;
}
Vector<int> indices;
for (int code: codes) {
int index = FT_Get_Char_Index(pimpl->face, code);
if (code != 0) {
indices.push_back(index);
}
}
for (int left: indices) {
for (int right: indices) {
FT_Vector result;
FT_Get_Kerning(pimpl->face, left, right, FT_KERNING_UNFITTED, &result);
if (result.x != 0 || result.y != 0) {
results.emplace_back(KerningPair(left, right, Vector2f(result.x / 64.0f, result.y / 64.0f)));
}
}
}
return results;
}
void* FontFace::getFreeTypeLib() const
{
return pimpl ? pimpl->library : nullptr;
}
void* FontFace::getFreeTypeFace() const
{
return pimpl ? pimpl->face : nullptr;
}
|
Java
|
UTF-8
| 4,521
| 2.765625
| 3
|
[] |
no_license
|
/* CLASE ListarCompras
* RESPONSABILIDAD Listar los clientes de la galeria
* DESCRIPCION Aplicacion que lista las compras de un cliente
* COLABORACION Trabaja con las clases: MenuGaleria, EgaleriaDeArte, Cliente, MostrarComras, Listar
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ListarCompras extends JFrame {
Container contenedor;
Cliente cl;
EGaleriaDeArte gal=new EGaleriaDeArte();
Galeria galeria=new Galeria();
JComboBox Listar;/////////Cuadro combinado
Font fuente=new Font("Lucida Calligraphy",Font.BOLD,13);
Font fuente2=new Font("Segoe Print",Font.PLAIN,13);
Font fuente3=new Font("Segoe Script",Font.BOLD,20);
JLabel titulo, titulo2, titulo3, escoger;
// String vector[]={"a"};
public ListarCompras ()
{
super( "Listar compras del cliente" );
contenedor = getContentPane();
contenedor.setLayout(null);
//MENU INICIO
JMenu menuAyuda = new JMenu( "INICIO" );
JMenuItem acercade=new JMenuItem("Acerca de ....");
acercade.addActionListener(new ActionListener()
{
public void actionPerformed( ActionEvent evento )
{
JOptionPane.showMessageDialog( ListarCompras.this,
"Programa creado para organizacion y inventariado de una galeria de arte\n\n Creado por : \n JAIRO ANDRES LEYTON \n MARIA ALEJANDRA PABON \n VICTOR CAMILO JIMENEZ \n\n\n\nVersion 1.0 \n\n ",
"Acerca de", JOptionPane.PLAIN_MESSAGE );
}
}
);
JMenuItem ayuda = new JMenuItem( "Ayuda " );
ayuda.addActionListener(new ActionListener()
{
public void actionPerformed( ActionEvent evento )
{
Acercade obj=new Acercade();
}
}
);
menuAyuda.add( ayuda);
menuAyuda.add( acercade );
JMenuItem elementoSalir = new JMenuItem( "Salir Del programa" );
elementoSalir.setMnemonic( 'S' );
menuAyuda.add( elementoSalir );
elementoSalir.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent evento )
{
System.exit( 0 );
}
}
);
//creacion de barra
JMenuBar barra = new JMenuBar();
setJMenuBar( barra );
barra.add( menuAyuda );
//FIN MENU INICIO
ImageIcon icono=new ImageIcon("arte1.gif");
titulo= new JLabel("LISTAR COMPRAS DEL CLIENTE");
titulo.setToolTipText("Eliminar cliente picasa");
titulo.setForeground(Color.black);
titulo.setFont(fuente3);
titulo.setBounds(150,70,500,30);
contenedor.add(titulo);
titulo2= new JLabel("GALERIA",icono,SwingConstants.LEFT);
titulo2.setForeground(Color.black);
titulo2.setFont(fuente);
titulo2.setToolTipText("Menu Picasa");
titulo2.setBounds(20,20,500,20);
contenedor.add(titulo2);
titulo3=new JLabel("PICASA");
titulo3.setForeground(Color.black);
titulo3.setFont(fuente);
titulo3.setBounds(30,40,500,20);
contenedor.add(titulo3);
contenedor.setBackground(Color.white);
escoger = new JLabel("Escoja el cliente");
escoger.setBounds(50,120,200,20);
escoger.setFont(fuente2);
Listar = new JComboBox();
//Listar.setMaximumRowCount(5);
Listar.setBounds(50,150,150,20);
gal.listaNombres();
ComboBoxModel elemento = new DefaultComboBoxModel(gal.nombres);
Listar.setModel(elemento);
// JOptionPane.showMessageDialog(null,artistasvivos);
contenedor.add(escoger);
contenedor.add(Listar);
ManejadorBoton manejador=new ManejadorBoton();
Listar.addActionListener(manejador);
setSize(550,300);
setVisible(true);
}
private class ManejadorBoton extends EGaleriaDeArte implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e) {
for(int i=0;i<galeria.clientes.size();i++)
{ if(Listar.getSelectedIndex()==i)
{
Cliente cli= galeria.obtenerCliente(i);
new MostrarCompras(cli);
}}
}}
public static void main(String args[])
{
new ListarCompras();
}
}
|
Markdown
|
UTF-8
| 1,067
| 3.4375
| 3
|
[] |
no_license
|
# MyQueue Problem
Implement a MyQueue class which implements a queue using two stacks.
## Solution
This solution was tested on Ruby 2.4.3 but should run on earlier versions. The solution implements a `Stack`
class and its associated `StackNode` in `stack.rb`. Only the `Stack` class is used in the solution for the `MyQueue`
class. This class keeps track of two stacks: a `storage_stack` and a `helper_stack`. The storage stack maintains the
reversed contents of the queue such that when its `pop` or `peek` methods are called, they return the first item in the
queue. The helper stack is kept empty. It is only used when pushing to the queue to temporarily hold items from the
storage stack while a new item is added to the bottom of the storage stack.
## Running the Examples and Unit Tests
`run_example.rb` contains an example of the queue at work. You can run it with:
```bash
$ ruby run_example.rb
```
`test_binary_tree.rb` contains unit tests for both the queue and the stack. You can run them with:
```bash
$ ruby test_my_queue.rb
$ ruby test_stack.rb
```
|
C
|
UTF-8
| 406
| 3.609375
| 4
|
[] |
no_license
|
#include<stdio.h>
float potencia(float a, int b);
int main(){
int i, j;
for(i=2; i<=10; i++){
for(j=0; j<=10; j++){
printf("%.2f ", potencia(i, j));
}
printf("\n");
}
printf("\n\n");
return 0;
}
float potencia(float b, int e){
int i;
float resultado;
resultado = b;
if(e==0){
return 1;
}
else{
for(i=0; i<e-1; i++){
resultado *= b;
}
}
return resultado;
}
|
Python
|
UTF-8
| 2,845
| 2.78125
| 3
|
[] |
no_license
|
# coding=utf-8
# coding: utf-8
import random
from flask import *
import time
from Task import Task
from threading import Thread
class MyApp():
"""Small class for holding flask application
object Task()
list of all connected clients"""
def __init__(self):
self.fl = Flask(__name__)
self.task = Task()
self.ping_lst = []
self.st_time = time.time()
self.delta = 0
app = MyApp()
class Ping(Thread):
"""Thread for controlling response from client at regular time intervals"""
def __init__(self, client, time_ping):
Thread.__init__(self)
self.client = client
self.__begin_ping = time_ping
self.__end_ping = time_ping
self.start()
def ping(self, time_ping):
"""Set time of getting response"""
self.__end_ping = time_ping
def run(self):
"""Main function of thread in which at regular intervals checking response"""
while 1:
time.sleep(2)
if self.__end_ping - self.__begin_ping > 3:
break
else:
self.__begin_ping = self.__end_ping
self.__end_ping += 4
print "miss response"
if app.task.percent() != 100:
app.task.append_part(app.task.connected_clients[self.client])
else:
app.delta = time.time() - app.st_time
del app.task.connected_clients[self.client]
@app.fl.route('/')
def index():
"""Main page"""
return render_template("test.htm", var=random.randint(1,9999))
@app.fl.route('/task/<client_id>', methods=['GET'])
def part_task(client_id):
"""Sending task to worker"""
try:
app.task.connected_clients[client_id] = app.task.pop_part()
except IndexError:
return "null"
return {"truck": app.task.truck,
"shipment": app.task.connected_clients[client_id]}.__str__()
@app.fl.route('/ping/<client_id>', methods=['POST'])
def ping(client_id):
"""Get response from worker, that it's alive"""
tmp = filter(lambda x: x.client == client_id, app.ping_lst)
if tmp:
tmp[0].ping(time.time())
else:
print "init"
app.ping_lst.append(Ping(client_id, time.time()))
return "null"
@app.fl.route('/log')
def log():
""" Render log-page """
return render_template('log.html',
clients=app.task.connected_clients.__len__(),
percent=app.task.percent(),
n=app.task.result,
delta = app.delta)
@app.fl.route('/return-result/<client_id>', methods=['POST'])
def return_result(client_id):
"""Receive result from worker"""
app.task.result += int(request.form['result'])
return 'Null'
if __name__ == '__main__':
app.fl.run(host='0.0.0.0')
|
Markdown
|
UTF-8
| 2,050
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
# isthemunibusy-go
This was originally a project to predict how crowded the muni trains would be, but given the current circumstances with COVID-19, I have decided to pivot this project to be a feature test admin tool.
## Features
- Create a new feature test (DONE)
- Name
- Start date
- End date
- Variants[]
- Name
- Percentage
- Is control?
- Delete an existing feature test (DONE)
- Cascade to feature test variants
- Cascade to users with those test variants
- Update an existing feature test (DONE)
- Name
- End date
- Create a feature test variant (DONE)
- Name
- Percentage
- Is control?
- Update a feature test variant (DONE)
- Name
- Percentage
- Is control?
- Delete a feature test variant (DONE)
- Cascade to users with that test variant
- List user test variants (DONE)
- List feature tests (DONE)
- List feature test variants (DONE)
- Assign users to a test variant (create user test variant) (DONE)
- Change test variants for a user (update user test variant) (DONE)
- Delete user test variant (DONE)
- Only allow changes to feature test variant id for user feature test variant update (DONE)
- Better error messages for constraint violations (DONE)
DB:
- check constraint on test variant percentage sum <= 100 (DONE)
- check constraint on test variants for a test only having one row is_control = true
- insert (DONE)
- update (leaving alone for now)
## How to run locally
Navigate to the go repo directory (`go\src\github.com\hwangm\isthemunibusy-go`)
In a terminal window, run `go run .\main.go`.
To restart, Ctrl-C and re-run.
## Notes
- graphql DateTime field expects an input like "2020-05-05T00:00:00Z". It's pretty picky about the time formatting.
- 2/15/2021: added a websocket handler at "ws://localhost:8080/websocket" to test notification service. React app currently configured to auto-connect to this WS endpoint. Incoming messages will be printed in stdout, then sleep for 5 seconds and send a message to the client.
|
Shell
|
UTF-8
| 946
| 2.984375
| 3
|
[] |
no_license
|
#!/bin/bash
# example file. Put this into the project root folder and run.
SRC_ROOT=/nfs/masi/xuk9/singularity/thorax_combine/conda_base/src/thorax_pca
PYTHON_ENV=/home/local/VANDERBILT/xuk9/anaconda3/envs/python37/bin/python
CONFIG=${SRC_ROOT}/config/pca_conda_base.yaml
PROJ_ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
AFFINE_ROOT=${PROJ_ROOT}/output/affine
ANALYSIS_ROOT=${PROJ_ROOT}/analysis
DATA_LIST=${PROJ_ROOT}/data/file_list
AFFINE_INTERP_FOLDRE=${AFFINE_ROOT}/interp/ori
STD_ROI_MASK=${PROJ_ROOT}/reference/roi_mask.nii.gz
IMG_MASK_OVERLAY_PNG_FOLDER=${ANALYSIS_ROOT}/affine_img_mask_overlay_png
mkdir -p ${IMG_MASK_OVERLAY_PNG_FOLDER}
set -o xtrace
${PYTHON_ENV} ${SRC_ROOT}/src/plot_img_mask_overlay.py \
--config ${CONFIG} \
--in-folder ${AFFINE_INTERP_FOLDRE} \
--mask-img ${STD_ROI_MASK} \
--out-png-folder ${IMG_MASK_OVERLAY_PNG_FOLDER} \
--file-list-txt ${DATA_LIST}
set +o xtrace
|
Markdown
|
UTF-8
| 3,493
| 3.421875
| 3
|
[] |
no_license
|
---
title: <Python><PAT> 1138 Postorder Traversal
date: 2019-09-05 22:16:24
tags:
- PAT
- 题解
cover: http://pwb80dtf4.bkt.clouddn.com/PAT-cover.webp
categories: PAT
top_img: http://pwb80dtf4.bkt.clouddn.com/PAT-top.webp
description: 前序中序转后序
---
# 题目
Suppose that all the keys in a binary tree are distinct positive integers. Given the preorder and inorder traversal sequences, you are supposed to output the first number of the postorder traversal sequence of the corresponding binary tree.
### Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 50,000), the total number of nodes in the binary tree. The second line gives the preorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
### Output Specification:
For each test case, print in one line the first number of the postorder traversal sequence of the corresponding binary tree.
### Sample Input:
```in
7
1 2 3 4 5 6 7
2 3 1 5 4 7 6
```
### Sample Output:
```out
3
```
# 题解
## 思路
+ 题目给出了前序遍历和中序遍历
+ 求后序遍历的第一个数
+ 前序遍历是根左右
+ 中序遍历是左根右
+ 后序遍历是左右根
+ 我们可以这样画图来辅助理解,对于一棵树或子树,都符合下面的规律
+ ```
前序: 根[ 左 ][ 右 ]
中序: [ 左 ]根[ 右 ]
```
+ 而我们想要的是后序遍历的第一项
+ 从逻辑上来说
+ 就是一个节点如果有左子树的,就深入左子树,不管右子树。
+ 如果有右子树的,就深入右子树。
+ 都没有的,输出它。
+ 这样子剪枝,就可以大大减少复杂度,将递归优化成尾递归
## 数据结构
+ pre 是前序序列
+ in 是中序序列
+ judge 是递归函数
+ pre_left 是在前序中的树的左边界
+ in_left,in_right 是在中序中的树的左右边界
## 算法
+ 照着思路来走一遍就可以了
+ 难点是树的左右边界坐标的确立,但是参考我前面画的图,就问题不大了。
## 代码
+ 由于这道题测试数据格式有误,Python有一个点会非零返回。
### Python 3
```python
def judge(pre_left, in_left, in_right):
in_root = _in.index(pre[pre_left])
if in_left <= in_root - 1:
judge(pre_left + 1, in_left, in_root - 1)
elif in_root + 1 <= in_right:
judge(pre_left + (in_root - in_left) + 1, in_root + 1, in_right)
else:
print(_in[in_root])
n = int(input())
pre = list(map(int, input().split()))
_in = list(map(int, input().split()))
judge(0, 0, n - 1)
```
### C++
```c++
#include <iostream>
#include <vector>
#include <unordered_map>
#include <set>
using namespace std;
void judge(const int pre[],const int in[],int pre_left,int in_left,int in_right){
int in_root;
for (int i = in_left;i<=in_right;++i){
if (in[i] == pre[pre_left]){
in_root = i;
break;
}
}
if (in_left <= in_root - 1)
judge(pre,in,pre_left + 1, in_left, in_root - 1);
else if(in_root + 1 <= in_right)
judge(pre,in,pre_left + (in_root - in_left) + 1, in_root + 1, in_right);
else
cout<<in[in_root]<<endl;
}
int main() {
int n;
cin >> n;
int pre[n];
int in[n];
for (int i = 0; i < n; i++)
cin >> pre[i];
for (int i = 0; i < n; i++)
cin >> in[i];
judge(pre,in,0,0,n-1);
}
```
|
Java
|
UTF-8
| 950
| 2.203125
| 2
|
[] |
no_license
|
package com.engulf.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
public class LoginController {
@RequestMapping("/toLogin")
public String toLogin(String username, String password, HttpSession session){
return "login";
}
@RequestMapping("/toMain")
public String toLogin(){
return "main";
}
@RequestMapping("/login")
public String login(String username, String password, HttpSession session){
//把用户信息存在session中
session.setAttribute("userLoginInfo",username);
return "main";
}
@RequestMapping("/logout")
public String logout(HttpSession session){
//把用户信息存在session中
session.removeAttribute("userLoginInfo");
return "redirect:/toMain";
}
}
|
Markdown
|
UTF-8
| 14,371
| 3.171875
| 3
|
[
"MIT"
] |
permissive
|
# My People
## Introduction
One of my new favourite features in Windows is: My People. My People makes it easy to stay connected with contacts you often engage with. My People gives users the ability to pin their favourite contact to the task bar. Users can interact with their contact through voice, video, and text from the task bar. This makes it quick and easy to use without distracting your flow.

For responses requiring an emoticon, My People has shoulder tap, a simple notification above the contact.

I want to show you how you can use My People in your applications to drive better engagement.
## Phases of development
* Setup Protocol Activation for MyPeople experiences
* Create a Contact (optional)
* Annotate a contact
* Pin a Contact
* Shoulder Tap
* Sharing content as a share target
* Passing Contact Information
Here I have my UWP, it's nothing too glamourous since it's for demo purposes. I have a MainPage which has a welcome message, a create contact button and a should tap button.

When I click the Create Contact button, it will create a contact called [Joe Bloggs](https://en.wikipedia.org/wiki/Joe_Bloggs), he is a good looking guy :) and pin Joe to the task bar.
When I click the "Shoulder Tap" Button it plays an animation above Joe's head.
When I click on the contact, you'll see the My People app show in the tab and display a different UI that is suited to it's space. When I drag content to the contact, it shares that content.
Now you know what's possible, let's get into the code!
When you launch the My People app from the task bar, it loads a seperate instace of your application. I could use the Visual State Manager to change the look on the MainPage. In this case, I decided to create a seperate XAML file. When lauching the app from the task bar, we need to override the OnActivated method in the App.xaml.cs
### Setup Protocol Activation for MyPeople experiences
```csharp
override protected void OnActivated(IActivatedEventArgs e)
{
if (e.Kind == ActivationKind.ContactPanel)
{
var args = e as ContactPanelActivatedEventArgs;
// Change Contact Panel Header Color.
args.ContactPanel.HeaderColor = Colors.LightSlateGray;
// Create a Frame to act as the navigation context and navigate to the first page
var rootFrame = new Frame();
// Place the frame in the current Window
Window.Current.Content = rootFrame;
// Navigate to the page that shows the Contact UI.
rootFrame.Navigate(typeof(MyPeopleCanvas), args);
// Ensure the current window is active
Window.Current.Activate();
}
}
```
In this code you can see that when the activation is from the contact panel. I setup the root frame to navigate to the MyPeopleCanvas XAML. If you have done protocol activation before, this code should look familar. Optionally, you can change the header color to keep in line with your app brandning, so I've set mine to Light Slate Gray.
Now that I have the page and routing setup, it's time to integrate our experience with My People.
### Integrate with My People
In this demo, I am going to create a contact. This is optional if you already have a contact. I want to show you how to create a contact though as some application developers may have bots. This is a really nice way to show your bot some love and increase their user engagement.
First step is to add the extension for contact panel to the app. Open the Package.appxmanifest in the code editor and add these lines of XML. Note you'll need to also add a new namespace if you don't already have uap4 specified.
```xml
<uap4:Extension Category="windows.contactPanel">
<uap4:ContactPanel SupportsUnknownContacts="true" />
</uap4:Extension>
```
There are 4 main concepts that happen when I click the Create Contact button:
* Find a contact (in case it already exists)
* If the contact doesn't exist, create one
* Annotate the contact so My People knows what this contact can do.
* Programmatically pin the contact to the task bar
```csharp
private async void CreateContact_Click(object sender, RoutedEventArgs e)
{
var contact = await FindContact("joebloggs@contoso.com");
if (contact == null)
{
await CreateAContact();
contact = await FindContact("joebloggs@contoso.com");
}
await TagAContact(contact);
await PinAContact(contact);
}
```
Based on the steps above, let's start creating the methods.
I need to first find a contact. If the contact already exists then there is no point re-creating it. I use the ContactManager to request the Contact Store, basically all my contacts on the device. I then ask it to find a contact with an id (in this case Joe Bloggs email address). If it finds Joe, return him, otherwise return null.
```csharp
private async Task<Contact> FindContact(string id)
{
ContactStore contactStore = await ContactManager.RequestStoreAsync();
IReadOnlyList<Contact> contacts = null;
contacts = await contactStore.FindContactsAsync(id);
return contacts.FirstOrDefault();
}
```
I'm guessing most of you won't have Joe Bloggs on your machine already, so I'm going to create a contact, with an image, email and phone number. The remote id is a unique id for the contact. It syncs with the user across their devices. I use an email address for the remote id because they are generally pretty unique. Once I have created a contact, I need to add it to a Contact List. Contacts don't generally float around, they are part of a list. You can see the various lists you have in the Windows 10 People app (not to be confused with this app). Once I find or create a Contact List, I save the contact to it.
```csharp
private async Task CreateAContact()
{
var contact = new Contact
{
FirstName = "Joe",
LastName = "Bloggs",
SourceDisplayPicture = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/shen.png")),
RemoteId = "joebloggs@contoso.com"
};
var email = new ContactEmail
{
Address = "joebloggs@contoso.com",
Kind = ContactEmailKind.Other
};
contact.Emails.Add(email);
var phone = new ContactPhone
{
Number = "1234567890",
Kind = ContactPhoneKind.Mobile
};
contact.Phones.Add(phone);
var store = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AppContactsReadWrite);
ContactList contactList;
IReadOnlyList<ContactList> contactLists = await store.FindContactListsAsync();
if (!contactLists.Any())
{
contactList = await store.CreateContactListAsync("MyPeopleContactList");
}
else
{
contactList = contactLists.First();
}
await contactList.SaveContactAsync(contact);
}
```
A contact on it's own is no good though, what we need to do is annotate the contact so we can associate our app to it. We need to apply the supported operations our app can help with. To do this we create a ContactAnnotation.
### Annontate a contact
```csharp
private async Task TagAContact(Contact contact)
{
ContactAnnotationStore annotationStore = await ContactManager.RequestAnnotationStoreAsync(ContactAnnotationStoreAccessType.AppAnnotationsReadWrite);
ContactAnnotationList annotationList;
IReadOnlyList<ContactAnnotationList> annotationLists = await annotationStore.FindAnnotationListsAsync();
if (!annotationLists.Any())
{
annotationList = await annotationStore.CreateAnnotationListAsync();
}
else
{
annotationList = annotationLists.First();
}
var annotation = new ContactAnnotation
{
ContactId = contact.Id,
RemoteId = "joebloggs@contoso.com",
SupportedOperations =
ContactAnnotationOperations.AudioCall |
ContactAnnotationOperations.VideoCall |
ContactAnnotationOperations.ContactProfile |
ContactAnnotationOperations.Share | ContactAnnotationOperations.Message
};
string appId = "d2b5f9e1-1de2-4efb-863b-9eb5737d84b1_75cr2b68sm664!App";
annotation.ProviderProperties.Add("ContactPanelAppID", appId);
annotation.ProviderProperties.Add("ContactShareAppID", appId);
await annotationList.TrySaveAnnotationAsync(annotation);
}
```
The ContactAnnotation must share the same contact id and remote id of the contact. This helps join the annontation to the contact. I also register the contact annotation with the Contact Panel (task bar) and the share target. To register, I set the ProviderProperties with the AppId. You can get the app id from the Package.appxmanifest, navigate to the packaging tab. Copy the Package Family Name and append "!App" to it.

As I'm registering various operations, I need to also make sure I have access to them so I select them as Capabilities:

The final thing we want to do is programmatically pin the contact to the My People contact panel. This step is optional but I wanted to show you how easy it is to programmatically do this.
### Pin a Contact
```csharp
private async Task PinAContact(Contact contact)
{
PinnedContactManager pinnedContactManager = PinnedContactManager.GetDefault();
await pinnedContactManager.RequestPinContactAsync(contact, PinnedContactSurface.Taskbar);
}
```
Let's run the app up and see what happens.

WAHOO!! So we have the basics. Let's now add the optional extras.
Next is the shoulder tap. When someone taps the "Shoulder Tap" button I want ot play an animation above the contact. I'm a Game of Thrones fan, so I'm going to pick my favourite gif of [Daenerys Targaryen](https://en.wikipedia.org/wiki/Daenerys_Targaryen).
What's great about the shoulder tap is that it uses the Toast Nofication infrastruction. I pass the shoulder tap xml payload to ToastNotificationManager.
### Shoulder Tap
```csharp
private void ShoulderTap_Click(object sender, RoutedEventArgs e)
{
string xmlText = File.ReadAllText(@"Assets\toast.xml");
XmlDocument xmlContent = new XmlDocument();
xmlContent.LoadXml(xmlText);
var notification = new ToastNotification(xmlContent);
ToastNotificationManager.CreateToastNotifier().Show(notification);
}
```
How does the ToastNotificationManager know that this is a shoulder tap vs a generic toast? Well... In the payload we set the attribute experienceType="shoulderTap". If the user is not pinned, it will show a toast noification based on the first template ("Oh no, pin me!"). If the contact is pinned to the My People Contact Panel then it will pop a toast quietly using the first template and use the second template and do the shoulder tap.
```xml
<toast hint-people="remoteid:joebloggs@contoso.com">
<visual lang="en-US">
<binding template="ToastGeneric">
<text hint-style="body">Oh no, pin me!</text>
<text>MyPeople sent you a notification</text>
</binding>
<binding template="ToastGeneric" experienceType="shoulderTap">
<image src="ms-appx:///Assets/khalesi.gif"/>
</binding>
</visual>
</toast>
```
For my final My People feature I'm going to add a Share Target. This is great if you want to pass files to someone quickly. If it's a bot maybe dragging an image over the bot contact will perform an image search. The ideas are endless.
In the App.xaml.cs I override the OnShareTargetActivated method. If the share was performed against a contact I want to load the MyPeopleCanvas page, otherwise the MainPage.
### Sharing as a share target
```csharp
protected override void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
{
bool isPeopleShare = false;
if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 5))
{
// Make sure the current OS version includes the My People feature before
// accessing the ShareOperation.Contacts property
isPeopleShare = args.ShareOperation.Contacts.Any();
}
if (isPeopleShare)
{
var rootFrame = new Frame();
// Place the frame in the current Window
Window.Current.Content = rootFrame;
// Navigate to the page that shows the Contact UI.
rootFrame.Navigate(typeof(MyPeopleCanvas), args.ShareOperation);
// Ensure the current window is active
Window.Current.Activate();
}
else
{
// Show standard share UI for unpinned contacts
var rootFrame = new Frame();
rootFrame.Navigate(typeof(MainPage), args.ShareOperation);
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
}
```
In the MyPeopleCanvas page, I check the ShareOperation and extract the contact information and the data. In this case the name and image.
### Passing Contact Information
```csharp
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
if (e.Parameter is ShareOperation shareTarget)
{
WelcomeMessageTextBlock.Text = $"Welcome {shareTarget.Contacts.First().Name}, here is your image";
if (shareTarget.Data.Contains(StandardDataFormats.StorageItems))
{
var storageItems = await shareTarget.Data.GetStorageItemsAsync();
var storageItem = storageItems.Cast<StorageFile>().First();
var bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(await storageItem.OpenReadAsync());
MyImage.Source = bitmapImage;
}
}
}
```
I want to call out a new feature in C# which I love! Look at how I cast the e.Parameter. I check it's type using the 'is' keyword, and if the 'is' operation returns true, it will populate the variable shareTarget.
To make sure that only jpg and pngs are sent, I need to declare the Share Target in the Package.appxmanifest.

Now when I drag and image over the contact and drop it, look what happens!

I hope you have enjoyed reading this post. I know it's been a while since I've posted but I plan to blog more often this year! :)
You can find the source here:
https://www.github.com/shenchauhan/MyPeople
|
C
|
UTF-8
| 1,119
| 2.609375
| 3
|
[] |
no_license
|
/*------------------------------------------------------------------------------------------------------------------
-- HEADER FILE: translat.h - This file provides all related to the translation of an input buffer received from a
-- pipe in response to the input of special characters, defined in codes.h.
--
-- PROGRAM: translator
--
-- FUNCTIONS:
-- void translate_from_input(int *pipe, size_t buffer_size)
-- void print_translation_pipe(int *pipe, char *output_buffer, char *read_buffer)
--
-- DATE: Jan 18, 2020
--
-- REVISIONS: (N/A)
--
-- DESIGNER: Michael Yu
--
-- PROGRAMMER: Michael Yu
--
----------------------------------------------------------------------------------------------------------------------*/
#ifndef TRANSLATE_H
#define TRANSLATE_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "translator.h"
#include "output.h"
#include "codes.h"
void translate_from_input(int *pipe, size_t buffer_size);
void print_translation_pipe(int *pipe, char *output_buffer, char *read_buffer);
#endif
|
Markdown
|
UTF-8
| 465
| 2.84375
| 3
|
[] |
no_license
|
### svelte.parse
```js
ast: object = svelte.parse(
source: string,
options?: {
filename?: string,
customElement?: boolean
}
)
```
`parse` 函数用来解析一个组件并返回它的抽象语法树。
```js
const svelte = require('svelte/compiler');
const ast = svelte.parse(source, { filename: 'App.svelte' });
```
与编译用的 `generate: false` 选项不同的是,这个只会进行解析,不会做对这个组件做更多的验证或分析。
|
Java
|
UTF-8
| 3,190
| 2.46875
| 2
|
[] |
no_license
|
// RTEFX - Rich Text Editor for JavaFX
// Copyright (C) 2003, 2018 Robert Lichtenberger
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package org.rtefx;
import junit.framework.*;
import java.text.*;
/** Tests for REDCharacterIterator
* @author rli@chello.at
* @tier test
*/
public class RTestREDCharacterIterator extends TestCase {
public RTestREDCharacterIterator(String name) {
super(name);
}
public static Test suite() {
return new TestSuite(RTestREDCharacterIterator.class);
}
public void setUp() throws Exception {
fEditor = new REDEditor();
fEditor.replace("A Troll sat alone on his seat of stone.", 0, 0, null);
fIter = fEditor.createCharacterIterator();
super.setUp();
}
public void tearDown() throws Exception {
super.tearDown();
}
public void testIndex() {
assertEquals('T', fIter.setIndex(2));
assertEquals('A', fIter.setIndex(0));
assertEquals('.', fIter.setIndex(fEditor.length()-1));
assertEquals(CharacterIterator.DONE, fIter.setIndex(-1));
assertEquals(CharacterIterator.DONE, fIter.setIndex(-10));
assertEquals(0, fIter.getIndex());
assertEquals(' ', fIter.next());
assertEquals(CharacterIterator.DONE, fIter.setIndex(fEditor.length()));
assertEquals(CharacterIterator.DONE, fIter.setIndex(fEditor.length() + 3));
assertEquals(fEditor.length(), fIter.getIndex());
assertEquals('.', fIter.previous());
}
public void testClone() {
fIter.setIndex(5);
REDCharacterIterator iter2 = (REDCharacterIterator) fIter.clone();
assertEquals(fIter.getIndex(), iter2.getIndex());
assertEquals(fIter.next(), iter2.next());
}
public void testMisc() {
assertEquals('A', fIter.first());
assertEquals('.', fIter.last());
assertEquals('.', fIter.current());
assertEquals('e', fIter.previous());
assertEquals('e', fIter.current());
assertEquals(0, fIter.getBeginIndex());
assertEquals(fEditor.length(), fIter.getEndIndex());
}
public void testTraverse() {
StringBuffer buf = new StringBuffer();
for(char c = fIter.first(); c != CharacterIterator.DONE; c = fIter.next()) {
buf.append(c);
}
assertEquals("A Troll sat alone on his seat of stone.", "" + buf);
}
public void testTraverseReverse() {
StringBuffer buf = new StringBuffer();
for(char c = fIter.last(); c != CharacterIterator.DONE; c = fIter.previous()) {
buf.append(c);
}
assertEquals(".enots fo taes sih no enola tas llorT A", "" + buf);
}
REDEditor fEditor;
CharacterIterator fIter;
}
|
Markdown
|
UTF-8
| 784
| 2.65625
| 3
|
[] |
no_license
|
# Sentiment Analysis and Feature selection on a Large Movie Review Dataset.
* The source of the dataset is:[dataset_link] (http://ai.stanford.edu/~amaas/data/sentiment/)
* Both train and test dataset contains 25000 reviews respectively.
### The notebook covers the following topics:
* Read file from our path to local directory.
* Perform sentiment analysis using self implemented Naive Bayes and compared the accuracy with builtin multinomial naive bayes classification model.
* Improving the accuracy using Logistic Regression classification model.
* Perform dimensionaility reduction by doing feature selection using mutual info classifier and acheive the same accuracy as above while using reduced set of features.
* Plot the curve between number of features and F1-scores.
|
Markdown
|
UTF-8
| 834
| 3.140625
| 3
|
[] |
no_license
|
## 常用Date/Time函数
| 函数 | 描述 |
| ------------------------------------------------------------ | -------------------------------------------------- |
| [date_default_timezone_set()](https://www.w3school.com.cn/php/func_date_default_timezone_set.asp) | 设置由所有的 Date/Time 函数使用的默认时区。 |
| [strtotime()](https://www.w3school.com.cn/php/func_date_strtotime.asp) | 将任何英文文本的日期或时间描述解析为 Unix 时间戳。 |
| [date(format, timestamp)](https://www.w3school.com.cn/php/func_date_date.asp) | 格式化本地日期和时间。 |
## 参考
- [PHP Date / Time 函数](http://www.w3school.com.cn/php/php_ref_date.asp)
|
Java
|
UTF-8
| 1,711
| 2.84375
| 3
|
[] |
no_license
|
package com.example.nicolascarraggi.trgrd.rulesys;
/**
* Created by nicolascarraggi on 26/04/17.
*
* An event that occurs when an input action happens on a device.
*
*/
public class InputActionEvent extends Event {
private InputAction inputAction;
private String type;
// SKELETON constructor
public InputActionEvent(int id, String name, String type, int iconResource, Device device, EventType eventType, RuleEngine ruleEngine) {
super(id, name, iconResource, device, eventType, ruleEngine);
this.eventValueType = EventValueType.INPUTACTION;
this.type = type;
this.inputAction = null;
}
public InputActionEvent(int id, String name, String type, int iconResource, Device device, EventType eventType, InputAction inputAction, RuleEngine ruleEngine) {
this(id, name, type, iconResource, device, eventType, ruleEngine);
this.inputAction = inputAction;
this.inputAction.setInputActionEvent(this);
this.isSkeleton=false;
}
// copy constructor
public InputActionEvent(int id, InputActionEvent inputActionEvent, InputAction inputAction){
this(id, inputActionEvent.getName(), inputActionEvent.getInputActionType(), inputActionEvent.getIconResource(),inputActionEvent.getDevice(),inputActionEvent.getEventType(),inputAction, inputActionEvent.getRuleEngine());
}
public InputAction getInputAction() {
return inputAction;
}
public void setInputAction(InputAction inputAction) {
this.inputAction = inputAction;
}
public String getInputActionType() {
return type;
}
public void setInputActionType(String type) {
this.type = type;
}
}
|
C
|
UTF-8
| 539
| 2.671875
| 3
|
[] |
no_license
|
#define _CRT_SECURE_NO_DEPRECATE
#include "shared.h"
void InitializeTrace(){
int i = 0;
for (i = 0; i < TRACE_SIZE; i++){
trace[i].CDB = -1;
trace[i].execution = -1;
trace[i].issued = -1;
trace[i].valid = 0;
memset(trace[i].instruction, 0, 16);
}
}
void PrintTrace(){
int i = 0;
FILE *dest = FileOpen("trace.txt", "wt");
for (i = 0; i < TRACE_SIZE; i++){
if (trace[i].valid == TRUE){
fprintf(dest, "%s %d %d %d\n", trace[i].instruction, trace[i].issued, trace[i].execution, trace[i].CDB);
}
}
fclose(dest);
}
|
C#
|
UTF-8
| 2,857
| 2.84375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.UI.Popups;
using App1.Common;
using App1.Model;
using App1.View;
namespace App1.View_Model
{
class EventViewModel : NotifyChanged
{
// Saves the event that the user selects to this variable.
public Event _selectedEvent;
// Everytime the user switch pages this method handles the navigation
private readonly FrameNavigate _frameNavigate;
/* This is sort of a private eventlist, we have this, so we can set the
* Globat singleton to this list
*/
public ObservableCollection<Event> EventList { get; set; }
// The global variable
private EventCatalogSingleton _singleton = EventCatalogSingleton.GetInstance();
//--------------------------------------------------------------------
// Handles the navigation
public RelayCommand GoToCreateEventPage { get; set; }
public RelayCommand DeleteEvent { get; set; }
public Event SelectedEvent
{
get => _selectedEvent;
set
{
_selectedEvent = value;
OnPropertyChanged(nameof(SelectedEvent));
}
}
//-------------------------------------------------------------------
/* When the constructer is called we set the Evenlist to
* the Global singleton list and we bind the view to the Eventlist
* and that is why we can see all the data from the list in every page.
*/
public EventViewModel()
{
try
{
EventList = new ObservableCollection<Event>();
var events = _singleton.GetEventList();
EventList = events;
}
catch (Exception e)
{
var dialog = new MessageDialog(e.Message);
}
SelectedEvent = new Event();
GoToCreateEventPage = new RelayCommand(DoGoToCreatePage);
DeleteEvent = new RelayCommand(DoDeleteEvent);
_selectedEvent = new Event();
_frameNavigate = new FrameNavigate();
}
// RelayCommand Methods
public void DoGoToCreatePage()
{
Type type = typeof(CreateEventPage);
_frameNavigate.ActivateFrameNavigation(type);
}
public void DoDeleteEvent()
{
if (SelectedEvent == null)
{
var dialog = new MessageDialog("You have to pick an Event to delete");
}
else
{
_singleton.GetEventList().Remove(SelectedEvent);
}
}
}
}
|
Java
|
UTF-8
| 7,508
| 1.679688
| 2
|
[] |
no_license
|
package com.bw.movie.activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.bw.movie.R;
import com.bw.movie.bean.LoginBean;
import com.bw.movie.bean.LoginSubBean;
import com.bw.movie.bean.Result;
import com.bw.movie.core.ResultInfe;
import com.bw.movie.core.utils.EncryptUtil;
import com.bw.movie.greendao.DaoMaster;
import com.bw.movie.greendao.DaoSession;
import com.bw.movie.greendao.LoginSubBeanDao;
import com.bw.movie.presenter.LoginPresenter;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.jessyan.autosize.internal.CustomAdapt;
public class LoginActivity extends WDActivity implements CustomAdapt, ResultInfe {
boolean canSee = false;
@BindView(R.id.regis_btn)
TextView regis_btn;
@BindView(R.id.my_login_phone)
EditText my_login_phone;
@BindView(R.id.my_login_pwd)
EditText my_login_pwd;
@BindView(R.id.rem_check)
CheckBox rem_check;
private LoginPresenter loginPresenter;
private SharedPreferences sp;
private LoginSubBeanDao loginSubBeanDao;
private IWXAPI mWechatApi;
private SharedPreferences checked;
@Override
protected int getLayoutId() {
return R.layout.activity_login;
}
@Override
protected void initView() {
loginPresenter = new LoginPresenter(this);
sp = getSharedPreferences("login", MODE_PRIVATE);
checked = getSharedPreferences("Checked", MODE_PRIVATE);
DaoSession daoSession = DaoMaster.newDevSession(LoginActivity.this, LoginSubBeanDao.TABLENAME);
loginSubBeanDao = daoSession.getLoginSubBeanDao();
boolean checkeds = checked.getBoolean("checked", false);
if (checkeds) {
List<LoginSubBean> list = loginSubBeanDao.loadAll();
LoginSubBean loginSubBean = list.get(0);
my_login_phone.setText(loginSubBean.getPhone());
my_login_pwd.setText(loginSubBean.getPwd());
rem_check.setChecked(true);
}
//点击软键盘外部,收起软键盘
my_login_phone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus) {
InputMethodManager manager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
if (manager != null)
manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
});
//点击软键盘外部,收起软键盘
my_login_pwd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus) {
InputMethodManager manager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
if (manager != null)
manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
});
}
@Override
protected void destoryData() {
loginPresenter.unBind();
}
/**
* 点击微信登录
*/
@OnClick(R.id.mIv_WeChat)
public void mIv_WeChat() {
//初始化微信
mWechatApi = WXAPIFactory.createWXAPI(this, "wxb3852e6a6b7d9516", false);
mWechatApi.registerApp("wxb3852e6a6b7d9516");
final SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";
req.state = "wechat_sdk_demo";
mWechatApi.sendReq(req);
}
@OnClick(R.id.my_login_btn)
public void my_login_btn() {
String name = my_login_phone.getText().toString();
String pwd = my_login_pwd.getText().toString();
String pwds = EncryptUtil.encrypt(pwd);
loginPresenter.request(name, pwds);
}
/**
* 查看密码
*/
@OnClick(R.id.mIv_eye)
public void mIv_eye() {
if (canSee == false) {
//如果是不能看到密码的情况下,
my_login_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
canSee = true;
} else {
//如果是能看到密码的状态下
my_login_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
canSee = false;
}
}
/**
* 去注册
*/
@OnClick(R.id.regis_btn)
public void regis_btn() {
startActivity(new Intent(LoginActivity.this, RegisActivity.class));
}
@Override
public boolean isBaseOnWidth() {
return false;
}
@Override
public float getSizeInDp() {
return 720;
}
/**
* 登录返回接口
*
* @param data
*/
@Override
public void success(Object data) {
Result result = (Result) data;
if (!result.getStatus().equals("0000")) {
Toast.makeText(this, "" + result.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
LoginBean loginBean = (LoginBean) result.getResult();
SharedPreferences.Editor edit = sp.edit();
//添加Sp添加
LoginSubBean userInfo = loginBean.getUserInfo();
edit.putString("sessionId", loginBean.getSessionId());
edit.putInt("userId", loginBean.getUserId());
edit.commit();
SharedPreferences.Editor edit2 = checked.edit();
edit2.putBoolean("checked", rem_check.isChecked());
edit2.commit();
LoginSubBean loginSubBean = new LoginSubBean();
loginSubBean.setStatu(1);
loginSubBean.setPwd(my_login_pwd.getText().toString());
loginSubBean.setGid(0);
loginSubBean.setHeadPic(userInfo.getHeadPic());
loginSubBean.setBirthday(userInfo.getBirthday());
loginSubBean.setId(userInfo.getId());
loginSubBean.setLastLoginTime(userInfo.getLastLoginTime());
loginSubBean.setPhone(userInfo.getPhone());
loginSubBean.setSessionId(loginBean.getSessionId());
loginSubBean.setNickName(userInfo.getNickName());
loginSubBean.setSex(userInfo.getSex());
loginSubBean.setUserId(userInfo.getUserId());
loginSubBean.setMail(userInfo.getMail());
loginSubBeanDao.insertOrReplace(loginSubBean);
SharedPreferences userinfo = getSharedPreferences("userinfo", MODE_PRIVATE);
SharedPreferences.Editor edits = userinfo.edit();
edits.putBoolean("login", true);
edits.commit();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
@Override
public void errors(Throwable throwable) {
}
}
|
JavaScript
|
UTF-8
| 1,177
| 2.78125
| 3
|
[] |
no_license
|
var dateApp = {
init: function() {
console.log('init js date');
/********************************* AU CHARGEMENT DE LA PAGE *********************************/
// Transforme le format des dates
$(document).ready(function () {
// Transforme le format des dates de recherche
moment.locale('fr')
var singleDate = $('.js-search-departureDate')
$(singleDate).each(function() {
$(this).text(moment($(this).text()).format('ddd D MMM'))
})
var returnDate = $('.js-search-returnDate')
$(returnDate).each(function() {
$(this).text(moment($(this).text()).format('ddd D MMM'))
})
var fullDate = $('.js-full-date')
$(fullDate).each(function() {
$(this).text(moment($(this).text()).format('ddd D MMM LT'))
})
var reviewDate = $('.js-review-date')
$(reviewDate).each(function() {
$(this).text(moment($(this).text()).format('ll'))
})
});
},
};
// Chargement du DOM
$(dateApp.init);
|
Java
|
UTF-8
| 7,287
| 2.203125
| 2
|
[] |
no_license
|
package com.example.batchdataapp.config;
import com.example.batchdataapp.entity.Person;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.integration.launch.JobLaunchRequest;
import org.springframework.batch.integration.launch.JobLaunchingGateway;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.dsl.MessageChannels;
import org.springframework.integration.file.dsl.Files;
import org.springframework.integration.handler.GenericHandler;
import org.springframework.integration.transformer.GenericTransformer;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import java.io.File;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Configuration
public class IntegrationConfig {
//create channel
@Bean
MessageChannel files() {
return MessageChannels.direct().get();
}
@Bean
IntegrationFlow batchJobFlow(
Job job,
JdbcTemplate jdbcTemplate,
JobLauncher launcher,
MessageChannel files
) {
return IntegrationFlows.from(files)
.transform(
(GenericTransformer<File, JobLaunchRequest>) file -> {
JobParameters jp = new JobParametersBuilder()
.addString("file", file.getAbsolutePath())
.toJobParameters();
return new JobLaunchRequest(job, jp);
}
)
// .transform(
// new GenericTransformer<File, JobLaunchRequest>() {
// @Override
// public JobLaunchRequest transform(File file) {
// JobParameters jp = new JobParametersBuilder()
// .addString("file", file.getAbsolutePath())
// .toJobParameters();
// return new JobLaunchRequest(job, jp);
// }
// }
// )
.handle(new JobLaunchingGateway(launcher))
.handle(JobExecution.class, (filePayload, messageHeaders) -> {
System.out.println("Job Execution from Integration Config: "+filePayload.getExitStatus().toString());
List<Person> personList = jdbcTemplate.query("select * from PEOPLE", (rs, rowNum) -> new Person(rs.getString("first"),
rs.getString("last"),
rs.getString("email")
));
personList.forEach(System.out::println);
return null;
}
)
.get();
// .handle(File.class, (filePayload, messageHeaders) -> {
// System.out.println("We have seen "+filePayload.getAbsolutePath());
// return null;
// }).get();
// .handle(File.class, new GenericHandler<File>() {
// @Override
// public Object handle(File filePayload, MessageHeaders messageHeaders) {
// System.out.println("We have seen "+filePayload.getAbsolutePath());
// return null;
// }
// })
}
@Bean
IntegrationFlow incomingFiles(
//@Value("${HOME}/Desktop/in") File dir
@Value("/Users/G3/Desktop/in") File dir
) {
return IntegrationFlows.from(
Files.inboundAdapter(dir)
.preventDuplicates(true)
.autoCreateDirectory(true),
poller -> poller.poller(spec -> spec.fixedRate(1, TimeUnit.SECONDS)))
.channel(this.files())
.get();
}
/*
@Bean
IntegrationFlow incomingFiles(
@Value("/Users/G3/Desktop/in") File dir,
Job job,
JdbcTemplate jdbcTemplate,
JobLauncher launcher
) {
return IntegrationFlows.from(
Files.inboundAdapter(dir)
.preventDuplicates(true)
.autoCreateDirectory(true),
poller -> poller.poller(spec -> spec.fixedRate(1, TimeUnit.SECONDS)))
.transform(
(GenericTransformer<File, JobLaunchRequest>) file -> {
JobParameters jp = new JobParametersBuilder()
.addString("file", file.getAbsolutePath())
.toJobParameters();
return new JobLaunchRequest(job, jp);
}
)
// .transform(
// new GenericTransformer<File, JobLaunchRequest>() {
// @Override
// public JobLaunchRequest transform(File file) {
// JobParameters jp = new JobParametersBuilder()
// .addString("file", file.getAbsolutePath())
// .toJobParameters();
// return new JobLaunchRequest(job, jp);
// }
// }
// )
.handle(new JobLaunchingGateway(launcher))
.handle(JobExecution.class, (filePayload, messageHeaders) -> {
System.out.println("Job Execution from Integration Config: "+filePayload.getExitStatus().toString());
List<Person> personList = jdbcTemplate.query("select * from PEOPLE", (rs, rowNum) -> new Person(rs.getString("first"),
rs.getString("last"),
rs.getString("email")
));
personList.forEach(System.out::println);
return null;
}
)
.get();
// .handle(File.class, (filePayload, messageHeaders) -> {
// System.out.println("We have seen "+filePayload.getAbsolutePath());
// return null;
// }).get();
// .handle(File.class, new GenericHandler<File>() {
// @Override
// public Object handle(File filePayload, MessageHeaders messageHeaders) {
// System.out.println("We have seen "+filePayload.getAbsolutePath());
// return null;
// }
// })
}
*/
}
|
SQL
|
UTF-8
| 474
| 3.09375
| 3
|
[] |
no_license
|
/* Formatted on 12/2/2015 4:03:08 (QP5 v5.252.13127.32867) */
SELECT SUM (plan) plan,
SUM (fakt) / 1000 fakt,
SUM (plan_ng) plan_ng,
SUM (fakt_ng) / 1000 fakt_ng,
SUM (plan_coffee) plan_coffee,
SUM (fakt_coffee) / 1000 fakt_coffee
FROM networkplanfact npf
WHERE npf.YEAR = :y
AND npf.MONTH = :m
AND npf.id_net IN (SELECT sw_kod
FROM nets n
WHERE :net = n.id_net)
|
C#
|
UTF-8
| 5,012
| 2.671875
| 3
|
[
"MS-PL",
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] |
permissive
|
using System.Collections.Generic;
using System.Runtime.Versioning;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace Demo.WinForms.WindowsDX.Test;
[SupportedOSPlatform("windows7.0")]
public class Engine
{
private const int PaddleWidth = 50;
private const int PaddleHeight = 10;
private const int PaddleBottomMargin = 20;
private const int BallRadius = 5;
private readonly GraphicsDevice _graphicsDevice;
private readonly SpriteBatch _spriteBatch;
private float _paddleX;
private List<Ball> _balls;
private Texture2D _whiteTex;
public int BottomHitCount { get; private set; }
public Engine(IGraphicsDeviceService graphics)
{
_graphicsDevice = graphics.GraphicsDevice;
_spriteBatch = new SpriteBatch(_graphicsDevice);
}
public void Initialize()
{
_whiteTex = SolidColorTexture(_graphicsDevice, Color.White);
var ball1 = new Ball
{
Radius = BallRadius
};
ball1.Randomize(_graphicsDevice.Viewport.Bounds);
_balls = new List<Ball> { ball1 };
}
public void Update(GameTime gameTime)
{
UpdatePaddle(gameTime);
foreach (var ball in _balls)
{
UpdateBall(ball, gameTime);
}
}
public void Draw(GameTime gameTime)
{
_graphicsDevice.Clear(Color.Black);
Rectangle paddleRect = new Rectangle((int)_paddleX, _graphicsDevice.Viewport.Height - PaddleBottomMargin, PaddleWidth, PaddleHeight);
_spriteBatch.Begin();
_spriteBatch.Draw(_whiteTex, paddleRect, Color.White);
foreach (var ball in _balls)
{
_spriteBatch.Draw(_whiteTex, ball.Bounds, Color.White);
}
_spriteBatch.End();
}
public int BallCount => _balls.Count;
public void AddBall()
{
Ball ball = new Ball() { Radius = BallRadius };
ball.Randomize(_graphicsDevice.Viewport.Bounds);
_balls.Add(ball);
}
public void RemoveBall()
{
if (_balls.Count > 0)
{
_balls.RemoveAt(_balls.Count - 1);
}
}
private static Texture2D SolidColorTexture(GraphicsDevice device, Color color)
{
var tex = new Texture2D(device, 1, 1);
var data = new Color[1] { color };
tex.SetData(data);
return tex;
}
private void UpdatePaddle(GameTime gameTime)
{
var keyboard = InputManager.GetKeyboardState();
if (keyboard.IsKeyDown(Keys.Left) && _paddleX > 0)
{
_paddleX -= (float)(300 * gameTime.ElapsedGameTime.TotalSeconds);
}
else if (keyboard.IsKeyDown(Keys.Right) && _paddleX < (_graphicsDevice.Viewport.Width - PaddleWidth))
{
_paddleX += (float)(300 * gameTime.ElapsedGameTime.TotalSeconds);
}
}
private void UpdateBall(Ball ball, GameTime gameTime)
{
var newPosition = ball.Position + ball.Direction * (float)gameTime.ElapsedGameTime.TotalSeconds;
var newDirection = ball.Direction;
if (newPosition.X < _graphicsDevice.Viewport.X + ball.Radius)
{
newPosition = new Vector2(_graphicsDevice.Viewport.X + BallRadius, newPosition.Y);
newDirection = new Vector2(newDirection.X * -1, newDirection.Y);
}
if (newPosition.X >= _graphicsDevice.Viewport.X + _graphicsDevice.Viewport.Width - ball.Radius)
{
newPosition = new Vector2(_graphicsDevice.Viewport.X + _graphicsDevice.Viewport.Width - ball.Radius, newPosition.Y);
newDirection = new Vector2(newDirection.X * -1, newDirection.Y);
}
if (newPosition.Y < _graphicsDevice.Viewport.Y + ball.Radius)
{
newPosition = new Vector2(newPosition.X, _graphicsDevice.Viewport.Y + ball.Radius);
newDirection = new Vector2(newDirection.X, newDirection.Y * -1);
}
if (newPosition.Y >= _graphicsDevice.Viewport.Y + _graphicsDevice.Viewport.Height - ball.Radius)
{
newPosition = new Vector2(newPosition.X, _graphicsDevice.Viewport.Y + _graphicsDevice.Viewport.Height - ball.Radius);
newDirection = new Vector2(newDirection.X, newDirection.Y * -1);
BottomHitCount++;
}
ball.Position = newPosition;
ball.Direction = newDirection;
var paddleRect = new Rectangle((int)_paddleX, _graphicsDevice.Viewport.Height - PaddleBottomMargin, PaddleWidth, PaddleHeight);
if (paddleRect.Intersects(ball.Bounds))
{
Bounce(ball, gameTime);
}
}
private static void Bounce(Ball ball, GameTime gameTime)
{
var newPosition = ball.Position - ball.Direction * (float)gameTime.ElapsedGameTime.TotalSeconds;
var newDirection = new Vector2(ball.Direction.X, ball.Direction.Y * -1);
ball.Position = newPosition;
ball.Direction = newDirection;
}
}
|
Python
|
UTF-8
| 1,114
| 3.0625
| 3
|
[] |
no_license
|
import pandas as pd
class Model(object):
"""Abstract class for models. Every model should at least define:
- identifier: ID of the model, as string (eg.: xgboost)
- train: train the model and define self.model
- predict: predict tournament data and save it to file"""
def __init__(self, data, output_path):
self.training_data = pd.read_csv(data['training_data'], float_precision='high')
self.validation_data = pd.read_csv(data['validation_data'], float_precision='high')
if 'reduced_features' in data:
self.feature_cols = data['reduced_features']
else:
self.feature_cols = list(self.training_data.columns[:-1])
self.tournament_file = data['tournament_file']
self.output_path = output_path
self.model = None
def identifier(self):
raise NotImplementedError("Identifier method not implemented yet.")
def train(self):
raise NotImplementedError("Train method not implemented yet.")
def predict(self):
raise NotImplementedError("Predict method not implemented yet.")
|
Python
|
UTF-8
| 2,414
| 3.8125
| 4
|
[] |
no_license
|
#!/usr/bin/python
# coding:utf-8
"""
@author: yyhaker
@contact: 572176750@qq.com
@file: 买卖股票的最佳时机III(可以购两次).py
@time: 2019/8/16 21:44
"""
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
# 思路:双指针,维护两个指针i, j;i之前的买一次,i-j买一次
# 时间复杂度为 O(n^2), (超时没过)
max_res = 0
i, j = 0, 0
# 移动i
mini = float("inf")
while i < len(prices):
if prices[i] < mini:
mini = prices[i]
ans1 = prices[i] - mini
max_res = max(max_res, ans1)
i += 1
# 移动j
j = i
minj = float("inf")
while j < len(prices):
if prices[j] < minj:
minj = prices[j]
ans2 = prices[j] - minj
max_res = max(max_res, ans1 + ans2)
j += 1
return max_res
class Solution2(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
# 思路:遍历两次prices, 从左到右遍历,LM[i]表示i之前的最大收益;
# 从右到左遍历,RM[i]表示i之后的最大收益;
# 最后再遍历一遍,取LM[i] + RM[i+1]的最大值
# 时间复杂度为O(n), 空间复杂度为O(n)
LM = [0] * len(prices)
minval = float('inf')
cur_max = 0
for i in range(len(prices)):
if prices[i] < minval:
minval = prices[i]
cur_max = max(cur_max, prices[i] - minval)
LM[i] = cur_max
RM = [0] * len(prices)
max_val = -1
cur_max = 0
for i in range(len(prices) - 1, -1, -1):
if prices[i] > max_val:
max_val = prices[i]
cur_max = max(cur_max, max_val - prices[i])
RM[i] = cur_max
max_res = 0
for i in range(len(prices)):
if i + 1 < len(prices):
max_res = max(max_res, LM[i] + RM[i + 1])
else:
max_res = max(max_res, LM[i])
return max_res
nums = [0, 3, 7, 5, 9, 1, 100]
nums2 = [3, 3, 5, 0, 0, 3, 1, 4]
nums3 = [3, 2, 6, 5, 0, 3]
solution = Solution2()
res = solution.maxProfit(nums3)
print(res)
|
Markdown
|
UTF-8
| 2,684
| 3.3125
| 3
|
[] |
no_license
|
+++
title = "2020-11-16: English"
date = 2020-11-16T10:37:43+09:00
tags = ["English self-learning"]
+++
## Review 11/16 lesson: Discussion
[Mental Models and Making Decisions You Don’t Regret](https://dariusforoux.com/mental-models/)
### Notes
1. Answer compound questions respectively and concisely.
2. Use prepositions correctly and make sentences understandably.
### Vocabulary
#### hindsight
the ability to understand a situation only after it has happened
* With hindsight, I could have done something good unless I was lazy with many things.
* With hindsight, I had many things that I feel there had to be a better way to do them.
* With hindsight, I should have done things that made me improve.
#### romanticize
to talk or think about things in a way that makes them seem more romantic or attractive than they really are
* When we are in a tough situation, we tend to glorify or romanticize reality.
* I don't like to romanticize messy work.
* Don't romanticize reality, or you can't feel happy forever.
#### imminent
an event that is imminent, especially an unpleasant one, will happen very soon
* A combination of flu and coronavirus are imminent this winter.
* My step-father was about to be in imminent danger of dying three months ago.
* The presentation that I'm going to give on next Thursday is imminent.
#### pseudo-intellectuals
a person who wants to be thought of as having a lot of intelligence and knowledge but who is not really intelligent or knowledgeable
* Don't be pseudo-intellectual, you shouldn't mind how others look at you.
* I don't like a person who is pseudo-intellectual.
* I'm bothered and tired with people who are pseudo-intellectual.
- - -
## Speaking: 4-57
### Try.1
1. The cat is called Tama.
2. When he told us **about** the plan, it sounded impossible.
3. The woman named Nancy Brown came here today.
- A woman whose name was Nancy Brown came here today.
4. ~~Why did he draw the paint?~~
- Why did he paint this picture?
5. Did you watch the program again?
- Yes, I did.
6. The news will surprise them.
7. It will be cloudy in Paris **tomorrow**.
8. Bob must know her telephone number.
9. The teacher took the students to the museum.
10. The vegetables sold here are fresh.
### Try.2
1. Why did he paint ~~the~~ **this** picture?
2. The vegetables sold here are fresh.
3. The cat is called Tama.
4. The news will surprise them.
5. It will be cloudy in Paris tomorrow.
6. A woman whose name was Nancy Brown came here **today**.
7. Bob must know here phone number.
8. When he told us about the plan, it sounded impossible.
9. The teacher took the students to the museum.
10. Did you see the program again?
- Yes, I did.
|
Java
|
UTF-8
| 1,139
| 3.28125
| 3
|
[] |
no_license
|
package cn.itcast.multithread;
import java.util.Random;
/**
* Created by Admin on 8/31/2016.
* <p>
* 使用ThreadLocal来改写ThreadScopeSharedData
*/
public class ThreadLocalTest {
private static ThreadLocal<Integer> myThreadLocal = new ThreadLocal();
private static class A {
void printData() {
System.out.printf("A %s: %d%n", Thread.currentThread().getName(), myThreadLocal.get());
}
}
private static class B {
void printData() {
System.out.printf("B %s: %d%n", Thread.currentThread().getName(), myThreadLocal.get());
}
}
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
@Override
public void run() {
int data = new Random().nextInt();
System.out.printf("%s put data: %d%n", Thread.currentThread().getName(), data);
myThreadLocal.set(data);
new A().printData();
new B().printData();
}
}).start();
}
}
}
|
Java
|
UTF-8
| 7,550
| 2.515625
| 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 studentsSchoolOfArts;
import studentSchoolOfComputing.*;
import com.jfoenix.controls.JFXCheckBox;
import classes.DatabaseConnection;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import classes.textFileGetAdmno;
/**
* FXML Controller class
*
* @author George
*/
public class Units11Controller implements Initializable {
/**
* Initializes the controller class.
*/
@FXML
public JFXCheckBox ccs101;
public JFXCheckBox ccs102;
public JFXCheckBox ccs103;
public JFXCheckBox ccs104;
public JFXCheckBox ccs105;
public JFXCheckBox ccs106;
public JFXCheckBox ccs107;
public ImageView view;
public Label error;
public ArrayList <String> units = new ArrayList <> ();
public String sql;
ResultSet resultset;
DatabaseConnection connection = new DatabaseConnection();
// java.io.File file = new java.io.File("src/studentLogIn/java.txt");
textFileGetAdmno files = new textFileGetAdmno();
public String values = files.getText();
public void handleSubmit(ActionEvent e){
if(ccs101.isSelected()){
units.add(ccs101.getText());
}
if(ccs102.isSelected()){
units.add(ccs102.getText());
}
if(ccs103.isSelected()){
units.add(ccs103.getText());
}
if(ccs104.isSelected()){
units.add(ccs104.getText());
}
if(ccs105.isSelected()){
units.add(ccs105.getText());
}
if(ccs106.isSelected()){
units.add(ccs106.getText());
}
// System.out.println(units.size());
int length = units.size();
if(length <1){
System.out.println("NO UNITS SUBMITTED.");
// error.setText("NO UNITS SELECTED FOR SUBMISSION.");
error.setVisible(true);
}
else{
// WE NEED TO GET THE PARTICULAR ABOUT THE STUDENT AS FROM THE DATABASE.
String school = values.substring(0, 2);
System.out.println(school);
String schoolDataBaseName = "";
switch(school){
case "ci":
schoolDataBaseName = "schoolofcomputing";
System.out.println(schoolDataBaseName);
break;
case "sc":
schoolDataBaseName = "schoolofbioloicalandpysicalsciences";
System.out.println(schoolDataBaseName);
break;
case "mt":
schoolDataBaseName = " schoolofmaths";
System.out.println(schoolDataBaseName);
break;
case "ed":
schoolDataBaseName = "schoolofeducation";
System.out.println(schoolDataBaseName);
break;
case "at":
schoolDataBaseName ="schoolofarts";
System.out.println(schoolDataBaseName);
break;
default:
System.out.println("AN ERROR IS OCCURRINg PLEASE CHECK THE DATA GIVEN");
}
try {
// SELECTIN THE EXACT DATA.
String fname = "";
String lname = "";
Statement statement = connection.co.createStatement();
// String sql1 = "select fName,lName from '" + schoolDataBaseName + "' where admno = '"+values +"'";
String sql1 = "select fname , lName from " +schoolDataBaseName+" where admno = '"+(String)values+"'";
resultset = statement.executeQuery(sql1);
if( resultset.next()){
fname = resultset.getString("fName");
lname = resultset.getString("lName");
}
if(length == 1){
// INSERT THE ONE UNIT IN THE DATABASE.
System.out.println( " "+fname + " "+lname+ " "+ values);
//Statement statement2 = connection.co.createStatement();
String unit1 = units.get(0);
// unit1.replace("\\\\r || \\\\n ", " ");
// System.out.println(unit1);
// System.out.println(System.getProperty("line.separator"));
String sql2 = "INSERT INTO registerunits (fname,lname,admno,unit1) values('"+ fname + "','"+ lname + "','" +values+"','"+unit1+"')";
// String sql2 = "insert into registerunits (fname,lname,admno,unit1) values ('"+fname+"','karis','ca567','uuduud')";
statement.executeUpdate(sql2);
System.out.println("THE DATA IS UPDATED");
}
} catch (Exception ex) {
// Logger.getLogger(Units11Controller.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
}
}
}
@Override
public void initialize(URL url, ResourceBundle rb) {
connection.Connect();
try {
Statement statement = connection.co.createStatement();
String sql = "select password from studentverification where username = '"+values+"'";
// statement.executeQuery(sql);
// ResultSet resultset ;
resultset = statement.executeQuery(sql);
if(resultset.next()){
String number = resultset.getString(1);
System.out.println("THE PASSWORD IS :"+number);
}
} catch (SQLException ex) {
Logger.getLogger(Units11Controller.class.getName()).log(Level.SEVERE, null, ex);
}
// System.out.println("THE BI BREAKTHROUH :" + values);
try {
// TODO
ccs101.setFocusTraversable(false);
ccs102.setFocusTraversable(false);
ccs103.setFocusTraversable(false);
ccs104.setFocusTraversable(false);
ccs105.setFocusTraversable(false);
ccs106.setFocusTraversable(false);
//ADDING THE IMAGE IN THE IMAGEVIEW.
File f = new File("src/images/maseno.png");
Image image;
try {
image = new Image(f.toURI().toURL().toString());
view.setImage(image);
} catch (MalformedURLException ex) {
Logger.getLogger(Units11Controller.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch(Exception ex){
System.out.println(ex);
}
}
}
|
Markdown
|
UTF-8
| 2,760
| 2.890625
| 3
|
[] |
no_license
|
---
date: 2021-05-18 13:00
title: What’s Next? - May 2021
description:
---
You might just have finished reading our [progress report from the last three months](/posts/progress-update-may-2021/). Now it’s time to talk about what we’re planning for the next few months!
Like last time, this is a list of areas that we’ll focus on over the next few months, not a to-do list. Other features and bug fixes will crop up and might take priority, and that’s OK! It’s good to have a rough direction in mind, though.
## Author Information
We feel strongly that open-source package authors should be acknowledged for their work. The very first designs for the package index had author information right at the top of the package metadata, but it didn’t quite make it into our feature set at launch. We want to change that, adding author information prominently at the top of our package metadata section.
We’ll collect the author information via the `.spi.yml` file [we already use](/posts/the-swift-package-index-metadata-file-first-steps) for build configuration.
## Package Keywords
We’ve long debated whether packages should have categories that come from a pre-determined list or have freeform keywords. After giving it some thought we’re going to go with freeform keywords rather than categories. We’ll collect keyword metadata from [GitHub topics](https://github.blog/2017-01-31-introducing-topics/) and show the keywords on package pages.
## Dependency Information
We’d also like to start working towards displaying the dependencies that a package would bring into your project if you use it. For example, we might start by adding a simple count of top-level and total dependencies.
## Additional Package Metadata
We’d also love to pick up a few more data points about every package. Does a package have tests? Is source code available? Is it a fork of another package? All of these are good indicators when considering dependencies.
## Home Page Redesign
Using the author information and keyword information mentioned above, we’d love to work on a much more information-rich home page. The first part of this is to think about it properly and put together a design, which is why we’re not going to talk about _precisely_ what you can expect today. However, we’ll be working on this.
## Package Collections
Finally, we’d like to finish off our support for Package Collections and put it live to coincide with the release of Swift 5.5. Initially, we’ll support collections that show all packages authored by their repository owner. So, for example, a collection of [these packages from Apple](https://swiftpackageindex.com/apple), or [these packages from the Vapor project](https://swiftpackageindex.com/vapor).
|
Java
|
UTF-8
| 3,172
| 1.789063
| 2
|
[] |
no_license
|
package com.tencent.mm.plugin.ipcall.a.a;
import com.tencent.mm.bp.b;
import com.tencent.mm.protocal.c.azf;
import java.util.Iterator;
import java.util.LinkedList;
public final class c {
public String fHE;
public String fJt;
public String fqG;
public int jlI;
public LinkedList<azf> krz = new LinkedList();
public int lUc;
public String lUd;
public int nJA;
public b nJB;
public LinkedList<azf> nJC = new LinkedList();
public int nJD = 999;
public LinkedList<d> nJE = new LinkedList();
public String nJF;
public String nJG;
public String nJH;
public int nJI;
public boolean nJJ = false;
public int nJe;
public long nJf;
public long nJg;
public int nJh;
public int nJi;
public int nJj;
public int nJk;
public String nJl;
public int nJm;
public int nJn;
public int nJo;
public int nJp;
public boolean nJq = false;
public boolean nJr = false;
public boolean nJs = false;
public boolean nJt = true;
public int nJu = 0;
public int nJv;
public int nJw;
public int nJx;
public b nJy;
public int nJz;
public final int aUv() {
if (this.nJE == null || this.nJE.size() <= 0) {
return this.nJn;
}
return ((d) this.nJE.get(0)).nJn;
}
public final int aUw() {
if (this.nJE == null || this.nJE.size() <= 0) {
return this.jlI;
}
return ((d) this.nJE.get(0)).gRd;
}
public final String toString() {
StringBuilder stringBuilder = new StringBuilder("");
stringBuilder.append("IPCallInfo: ");
stringBuilder.append(String.format("[roomId: %d, roomKey: %d, callSeq: %d, inviteId: %d, roomMemberId: %d, syncKey: %d, syncInterval: %d, currentStatus: %d, ErrMsg: %s, ErrCode:%d, ErrLevel:%d]\n", new Object[]{Integer.valueOf(this.nJe), Long.valueOf(this.nJf), Long.valueOf(this.nJg), Integer.valueOf(this.nJh), Integer.valueOf(this.nJm), Integer.valueOf(this.nJn), Integer.valueOf(this.nJo), Integer.valueOf(this.jlI), this.lUd, Integer.valueOf(this.lUc), Integer.valueOf(this.nJk)}));
stringBuilder.append(String.format("[toUsername: %s, toPhoneNumber: %s]\n", new Object[]{this.fHE, this.nJG}));
stringBuilder.append("[addrList: ");
Iterator it = this.krz.iterator();
while (it.hasNext()) {
azf azf = (azf) it.next();
stringBuilder.append(String.format("{IP: %s, port: %d}", new Object[]{azf.wDa, Integer.valueOf(azf.wMQ)}));
}
stringBuilder.append("]");
stringBuilder.append("\n");
if (this.nJE == null || this.nJE.size() <= 0) {
stringBuilder.append("userInfoList is empty");
} else {
stringBuilder.append("[userInfoList: ");
it = this.nJE.iterator();
while (it.hasNext()) {
d dVar = (d) it.next();
stringBuilder.append("{");
stringBuilder.append(dVar.toString());
stringBuilder.append("}");
}
stringBuilder.append("]");
}
return stringBuilder.toString();
}
}
|
PHP
|
UTF-8
| 4,117
| 2.65625
| 3
|
[] |
no_license
|
<?php
abstract class Df_Core_Block_Element extends Df_Core_Block_Template {
/**
* @override
* @return string
*/
public function getArea() {return Df_Core_Const_Design_Area::FRONTEND;}
/** @return string */
public function getCssClassesAttributeAsString() {
if (!isset($this->{__METHOD__})) {
$this->{__METHOD__} =
!$this->getCssClasses()
? ''
: implode(
Df_Core_Const::T_ASSIGNMENT
,array(
self::HTML_ATTRIBUTE__CLASS
,$this->quoteAttributeValue(
implode(' ', $this->getCssClasses())
)
)
)
;
}
return $this->{__METHOD__};
}
/** @return string[] */
protected function getCssClasses() {return array();}
/**
* @override
* @return string
*/
protected function getDefaultTemplate() {return $this->calculateTemplatePath();}
/** @return string[] */
protected function getTemplatePathParts() {
if (!isset($this->{__METHOD__})) {
$this->{__METHOD__} =
$this->splitClassNameInMagentoFormatToPathParts(
$this->getCurrentClassNameInMagentoFormat()
)
;
}
return $this->{__METHOD__};
}
/**
* Потомки могу переопределить данный метод.
* Если данный метод вернёт true, то система не будет рисовать данный блок.
* @return bool
*/
protected function isBlockEmpty() {return false;}
/**
* @override
* @return bool
*/
protected function needCaching() {return false;}
/**
* @override
* @return bool
*/
protected function needToShow() {return parent::needToShow() && !$this->isBlockEmpty();}
/**
* @param string $classNameInMagentoFormat
* @return string[]
*/
protected function splitClassNameInMagentoFormatToPathParts($classNameInMagentoFormat) {
df_param_string($classNameInMagentoFormat, 0);
/** @var string[] $moduleNameAndPath */
$moduleNameAndPath =
explode(
Df_Core_Model_Reflection::MODULE_NAME_SEPARATOR
,$classNameInMagentoFormat
)
;
df_assert_array($moduleNameAndPath);
df_assert_eq(2, count($moduleNameAndPath));
/** @var string $moduleName */
$moduleName = df_a($moduleNameAndPath, 0);
df_assert_string($moduleName);
/** @var string[] $moduleNameParts */
$moduleNameParts =
explode(
Df_Core_Model_Reflection::PARTS_SEPARATOR
,$moduleName
)
;
df_assert_array($moduleNameParts);
/**
* Заменяем только первое вхождение.
* df_checkout_pro/frontend_field_company
* надо разбить как:
* df/checkout_pro/frontend/field/company
*/
$moduleNameParts = df_array_clean(
df_a($moduleNameParts, 0)
,implode(Df_Core_Model_Reflection::PARTS_SEPARATOR, rm_tail($moduleNameParts)
));
df_assert_between(count($moduleNameParts), 1, 2);
/** @var string[] $pathParts */
$pathParts =
explode(
Df_Core_Model_Reflection::PARTS_SEPARATOR
,df_a($moduleNameAndPath, 1)
)
;
return array_merge($moduleNameParts, $pathParts);
}
/** @return string */
private function calculateTemplatePath() {
if (!isset($this->{__METHOD__})) {
$this->{__METHOD__} =
implode(
'.'
,array(
df_concat_path($this->getTemplatePathParts())
,Df_Core_Const::FILE_EXTENSION__TEMPLATE
)
)
;
}
return $this->{__METHOD__};
}
/**
* @param string $html
* @return string
*/
private function escapeHtmlWithQuotesInUtf8Mode($html) {
df_param_string($html, 0);
/** @var string $result */
$result =
htmlspecialchars(
$html
,ENT_QUOTES
,Df_Core_Const::UTF_8
,false
)
;
df_result_string($result);
return $result;
}
/**
* @param string $attributeValue
* @param string $quoteSymbol[optional]
* @return string
*/
private function quoteAttributeValue(
$attributeValue, $quoteSymbol = Df_Core_Const::T_QUOTE_SINGLE
) {
df_param_string($attributeValue, 0);
df_param_string($quoteSymbol, 1);
return
df_concat(
$quoteSymbol
,$this->escapeHtmlWithQuotesInUtf8Mode($attributeValue)
,$quoteSymbol
)
;
}
const _CLASS = __CLASS__;
const HTML_ATTRIBUTE__CLASS = 'class';
}
|
Python
|
UTF-8
| 12,009
| 2.984375
| 3
|
[] |
no_license
|
import os
import re
from functools import reduce
DIRECTIONS = ['north', 'south', 'east', 'west']
OPPOSITES = {'north': 'south', 'south': 'north', 'east': 'west', 'west': 'east'}
class TileMosaic():
def __init__(self, tiles):
self.tiles = tiles
self.mosaic = None
def get_tile_by_id(self, id):
return [tile for tile in self.tiles if tile.id == id][0]
def create_mosaic(self, id):
mosaic_data = []
row_data = []
tile_at_left_corner = [tile for tile in self.tiles if sorted(tile.neighbours.keys()) == sorted(['south', 'east'])]
tile_at_left = tile_at_left_corner[0] if len(tile_at_left_corner) > 0 else None
while tile_at_left:
left_data = tile_at_left.data_without_borders()
tile_at_right = tile_at_left.neighbours.get('east', None)
while tile_at_right:
row_data = []
for left_row, right_row in zip(left_data, tile_at_right.data_without_borders()):
row_data.append(left_row + right_row)
left_data = row_data.copy()
tile_at_right = tile_at_right.neighbours.get('east', None)
tile_at_left = tile_at_left.neighbours.get('south', None)
mosaic_data.extend(row_data)
self.mosaic = ImageTile(id, mosaic_data)
def __str__(self):
result_str = ''
tile_at_left_corner = [tile for tile in self.tiles if sorted(tile.neighbours.keys()) == sorted(['south', 'east'])]
tile_at_left = tile_at_left_corner[0] if len(tile_at_left_corner) > 0 else None
while tile_at_left:
result_str += str(tile_at_left.id) + '|'
tile_at_right = tile_at_left.neighbours.get('east', None)
while tile_at_right:
result_str += str(tile_at_right.id)
tile_at_right = tile_at_right.neighbours.get('east', None)
if tile_at_right:
result_str += '|'
result_str += '\n'
tile_at_left = tile_at_left.neighbours.get('south', None)
return result_str
class ImageTile():
def __init__(self, id, data):
self.id = id
self.data = data
self.neighbours = {}
self.borders = {}
# Init tile borders
self.update_borders()
def rotate(self):
data = [list(row) for row in self.data]
self.data = [''.join(pixel) for pixel in zip(*data[::-1])]
self.update_borders()
def flip(self):
for i, row in enumerate(self.data):
self.data[i] = row[::-1]
self.update_borders()
def update_borders(self):
self.borders['north'] = self.data[0]
self.borders['east'] = ''.join([col for row in self.data for i, col in enumerate(row) if i == len(row) - 1])
self.borders['south'] = self.data[-1]
self.borders['west'] = ''.join([col for row in self.data for i, col in enumerate(row) if i == 0])
def data_without_borders(self):
return [row[1:-1] for row in self.data[1:-1]]
def borders_match(self, tile):
matching_directions = []
for direction in DIRECTIONS:
if self.borders[direction] == tile.borders[OPPOSITES[direction]]:
matching_directions.append(direction)
return matching_directions
def add_neighbour(self, tile):
match = None
# Check if new tile matches any borders and nothing is added yet
for direction in DIRECTIONS:
if not isinstance(self.borders[direction], ImageTile) \
and self.borders[direction] == tile.borders[OPPOSITES[direction]]:
if not isinstance(tile.borders[OPPOSITES[direction]], ImageTile):
match = direction
self.neighbours[direction] = tile
if not match:
return False
directions_to_check = ('north', 'south') if match in ('east', 'west') else ('east', 'west')
# Update neighbours
for direction in directions_to_check:
if direction in self.neighbours:
# Check if neighbour tile exist
neighbour_tile = self.neighbours[direction].neighbours.get(match, None)
if neighbour_tile:
# Check if tile border is the same with the neighbour
if neighbour_tile.borders[OPPOSITES[direction]] == tile.borders[direction]:
neighbour_tile.neighbours[OPPOSITES[direction]] = tile
tile.neighbours[direction] = neighbour_tile
else:
raise ValueError('Tile borders should have matched:',
neighbour_tile.borders[OPPOSITES[direction]],
tile.borders[direction])
# Go further if possible
if match in neighbour_tile.neighbours:
opposite_tile = neighbour_tile.neighbours[match].neighbours.get(OPPOSITES[direction], None)
if opposite_tile:
if opposite_tile.borders[OPPOSITES[match]] == tile.borders[match]:
opposite_tile.neighbours[OPPOSITES[match]] = tile
tile.neighbours[match] = opposite_tile
else:
raise ValueError('Tile borders should have matched:',
opposite_tile.borders[OPPOSITES[direction]],
tile.borders[match] )
return True
def __str__(self):
return str(self.id) + '\n' + '\n'.join(self.data) + '\n'
def find_matching_tiles(target_tile, tiles):
matching_tiles = {}
tiles_matched = []
for tile in [tile for tile in tiles if tile.id != target_tile.id]:
match_found = None
for flip in range(2):
num_rotations = 0
while num_rotations < 4:
match_found = target_tile.borders_match(tile)
if len(match_found) > 0:
for match in match_found:
if tile.id not in tiles_matched:
tiles_matched.append(tile.id)
matching_tiles[tile.id] = match
num_rotations = 4
else:
tile.rotate()
num_rotations += 1
if not match_found and flip == 0:
tile.flip()
return matching_tiles
def find_pattern(pattern, image):
pattern_index = []
for row in pattern:
pattern_index.append([match.start() for match in re.finditer('#', row)])
num_patterns_found = 0
for i in range(len(image.data) - 3):
for j in range(len(image.data[0]) - len(pattern[0])):
matches = 0
for pattern_row in [1,2,0]:
for index in pattern_index[pattern_row]:
if image.data[i+pattern_row][j+index] == '#':
matches += 1
else:
break
else:
continue
break
else:
if matches == ''.join(pattern).count('#') :
num_patterns_found += 1
return num_patterns_found
def split_list(input_list, separator):
sub_list = []
for item in input_list:
if item == separator:
yield sub_list
sub_list = []
else:
sub_list.append(item)
yield sub_list
def main():
with open('{0}/input.txt'.format(os.path.dirname(os.path.realpath(__file__)))) as f:
lines = f.read().splitlines()
# Parse input data
tile_data = [item for item in split_list(lines, '')]
tiles = []
for data in tile_data:
id = int(data[0].replace('Tile ','').replace(':',''))
tiles.append(ImageTile(id, data[1:]))
# Find possible neighbours for all tiles
neighbours = {}
for tile in tiles:
neighbours[tile.id] = find_matching_tiles(tile, tiles)
corner_tiles = [key for key in neighbours.keys() if len(neighbours[key]) == 2]
# Part 1
result = reduce((lambda x, y: x * y), corner_tiles)
print('Part 1 result:', result)
# 20899048083289
# Part 2
mosaic = TileMosaic(tiles.copy())
unoriented_tile_ids = [tile.id for tile in tiles]
# Start assembling from corner tile
target_tile_id = corner_tiles.pop(0)
target_tile = mosaic.get_tile_by_id(target_tile_id)
unoriented_tile_ids.remove(target_tile_id)
target_tiles = []
# Add neighbouring tiles to queue
queue = []
for tile_id in neighbours[target_tile.id].keys():
tile = mosaic.get_tile_by_id(tile_id)
queue.append(tile)
unoriented_tile_ids.remove(tile_id)
while target_tile:
# Check tiles in queue
while len(queue) > 0:
tile = queue.pop(0)
neighbour_found = False
for flip in range(2):
num_rotations = 0
while num_rotations < 4:
neighbour_found = target_tile.add_neighbour(tile)
if neighbour_found:
tile.add_neighbour(target_tile)
# Add found tile to targets for next round
if tile.id not in [tile.id for tile in target_tiles]:
target_tiles.append(tile)
num_rotations = 4
else:
tile.rotate()
num_rotations += 1
if neighbour_found:
pass
elif not neighbour_found and flip == 0:
tile.flip()
if not neighbour_found:
unoriented_tile_ids.append(tile.id)
# Choose next target tile
target_tile = None
min_neighbours = 5
for tile in target_tiles:
if len(tile.neighbours) != len(neighbours[tile.id]):
# Choose the next target based on number of possible neighbours: prefer corners and borders
if len(neighbours[tile.id]) < min_neighbours:
target_tile = tile
min_neighbours = len(neighbours[tile.id])
# If number of maximum neighbours is reached, remove tile from targets
else:
if tile.id in unoriented_tile_ids:
unoriented_tile_ids.remove(tile.id)
if target_tile:
target_tiles = [tile for tile in target_tiles if tile.id != target_tile.id]
# Add neighbours of the new target tile to queue
queue = []
for tile_id in neighbours[target_tile.id].keys():
tile = mosaic.get_tile_by_id(tile_id)
if tile_id in unoriented_tile_ids:
queue.append(tile)
# Mosaic tiles together
print(mosaic)
mosaic.create_mosaic(1)
print(mosaic.mosaic)
SEA_MONSTER = [
' # ',
'# ## ## ###',
' # # # # # # '
]
# Find pattern from mosaic
for flip in range(2):
num_rotations = 0
while num_rotations < 5:
num_monsters_found = find_pattern(SEA_MONSTER, mosaic.mosaic)
if num_monsters_found > 0:
num_rotations = 5
else:
mosaic.mosaic.rotate()
num_rotations += 1
if num_monsters_found > 0:
break
else:
mosaic.mosaic.flip()
print('Part 2 answer: ', ''.join(mosaic.mosaic.data).count('#') - num_monsters_found * ''.join(SEA_MONSTER).count('#'))
# 1559
if __name__ == '__main__':
main()
|
Markdown
|
UTF-8
| 3,854
| 2.734375
| 3
|
[] |
no_license
|
# Image/Video Grey-to-Color
# Introduction
In image colorization, goal is to produce a colored image given a grayscale input image. This
problem is challenging because it is multimodal -- a single grayscale image may correspond to
many plausible colored images. As a result, traditional models often relied on significant user
input alongside a grayscale image.
Recently, deep neural networks have shown remarkable success in automatic image colorization
going from grayscale to color with no additional human input. This success may in part be due to
their ability to capture and use semantic information (i.e. what the image actually is) in
colorization, although we are not yet sure what exactly makes these types of models perform so
well.
<img width="741" alt="Screen Shot 2020-03-01 at 12 54 20 AM" src="https://user-images.githubusercontent.com/41890348/75622625-5f74e480-5b57-11ea-90fc-75171697ffe5.png">
<img width="705" alt="Screen Shot 2020-03-01 at 12 54 31 AM" src="https://user-images.githubusercontent.com/41890348/75622626-600d7b00-5b57-11ea-9d45-efa57e8a4da4.png">
For the dataset, we are using publicly available series of 1000 photos from
open dataset and deep
learning net website. The link is shown as below: https://skymind.ai/wiki/open-datasets and http://deeplearning.net/datasets/.We are planning to split 70% in the training set and 30%
in thethe test set. Since we have not much of dataset, we might need to give up on validate set for now.
These photos are each 256*256 pixels and includes faces, photography, pa
inting, animals andobjects.To help with generalization, we also performed various transformations including zooms,
flips and shears to prevent overfitting.
<img width="696" alt="Screen Shot 2020-03-01 at 12 57 49 AM" src="https://user-images.githubusercontent.com/41890348/75622686-0bb6cb00-5b58-11ea-8014-d91ab629d11b.png">
<img width="920" alt="Screen Shot 2020-03-01 at 12 57 59 AM" src="https://user-images.githubusercontent.com/41890348/75622688-0e192500-5b58-11ea-98f2-35124b917147.png">
<img width="928" alt="Screen Shot 2020-03-01 at 12 58 18 AM" src="https://user-images.githubusercontent.com/41890348/75622689-0f4a5200-5b58-11ea-9fb9-8723e8b4a6fb.png">
<img width="1022" alt="Screen Shot 2020-03-01 at 12 59 21 AM" src="https://user-images.githubusercontent.com/41890348/75622691-11141580-5b58-11ea-9c1a-342272e85214.png">
<img width="865" alt="Screen Shot 2020-03-01 at 12 59 34 AM" src="https://user-images.githubusercontent.com/41890348/75622694-140f0600-5b58-11ea-8a86-929afeba06c0.png">
<img width="880" alt="Screen Shot 2020-03-01 at 12 59 44 AM" src="https://user-images.githubusercontent.com/41890348/75622696-16716000-5b58-11ea-8d00-c7ca5ed7a7c1.png">
<img width="997" alt="Screen Shot 2020-03-01 at 12 59 58 AM" src="https://user-images.githubusercontent.com/41890348/75622697-17a28d00-5b58-11ea-86e5-32a08e62ee52.png">
# References
1. S. Ioffe and C. Szegedy. Batch normalization: Accelerating deep network training by reducing
internal covariate shift.arXiv preprint arXiv:1502.03167, 2015.
2 .D. Kingma and J. Ba. Adam: A method for stochastic optimization. arXiv preprint
arXiv:1412.6980, 2014.
3. A. Krizhevsky, I. Sutskever, and G. E. Hinton. Imagenet classification with deep
convolutional neural networks. In Advances in neural information processing systems, pages
1097–1105, 2012.
4. A.OlivaandA.Torralba.Modeling the shape of the scene:Aholistic representation of the spatial
envelope. International journal of computer vision, 42(3):145–175, 2001.
5. A. Olmos et al. A biologically inspired algorithm for the recovery of shading and reflectance
images. Perception,33(12):1463–1473, 2004.
6. O. Russakovsky, J. Deng, H. Su, J. Krause, S. Satheesh,S. Ma, Z. Hua
ng, A. Ka
rpathy, A.
Khosla, M. Bernstein, et al. Imagenet large scale visual recognition challenge. International
Journal of Computer Vision, 115(3):211–252, 2015.
|
Python
|
UTF-8
| 2,522
| 3.015625
| 3
|
[
"Apache-2.0"
] |
permissive
|
# Copyright 2014, 2015 Rogier van Dalen.
# 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.
# This test should run under Python 2 and 3 without modification.
from python_range_example import *
def yield_empty():
if False:
yield 3
def yield_6_25_8_5():
yield 6.25
yield 8.5
class TestError (Exception):
pass
def yield_6_25_error():
yield 6.25
raise TestError()
def yield_5_hello():
yield 5
yield "hello"
check_empty ([])
check_empty (())
check_empty (yield_empty())
check_empty ([i for i in [3,4] if i == None])
check_empty (i for i in [3,4] if i == None)
check_empty_2 ([])
check_empty_2 (())
check_empty_2 (yield_empty())
check_empty_2 ([i for i in [3,4] if i == None])
check_empty_2 (i for i in [3,4] if i == None)
check_6_25_8_5 ([6.25, 8.5])
check_6_25_8_5 ((6.25, 8.5))
check_6_25_8_5 (i + 1 for i in [5.25, 7.5])
check_6_25_8_5 (yield_6_25_8_5())
check_6_25_8_5_chop ([6.25, 8.5])
check_6_25_8_5_chop ((6.25, 8.5))
check_6_25_8_5_chop (i + 1 for i in [5.25, 7.5])
check_6_25_8_5_chop (yield_6_25_8_5())
check_6_25_8_5_chop_in_place ([6.25, 8.5])
check_6_25_8_5_chop_in_place ((6.25, 8.5))
check_6_25_8_5_chop_in_place (i + 1 for i in [5.25, 7.5])
check_6_25_8_5_chop_in_place (yield_6_25_8_5())
check_5_hello_untyped ([5, 'hello'])
check_5_hello_untyped ((5, 'hello'))
check_5_hello_untyped (yield_5_hello())
check_5_hello_typed ([5, 'hello'])
check_5_hello_typed ((5, 'hello'))
check_5_hello_typed (yield_5_hello())
check_5_hello_overtyped ([5, 'hello'])
check_5_hello_overtyped ((5, 'hello'))
check_5_hello_overtyped (yield_5_hello())
check_hello_5_bye_27 ([
('hello', 5),
('bye', 27),
])
check_17_None_hi ([17, None, "hi"]);
# Break things.
# Check that iter(5) throws a TypeError.
try:
iter (5)
except TypeError:
pass
# This should throw the same.
try:
check_6_25_8_5 (5)
except TypeError:
pass
# Throw some random error.
try:
check_6_25_8_5 (yield_6_25_error())
except TestError:
pass
v = test_return_something()
assert (v == 1)
|
Python
|
UTF-8
| 5,120
| 3.21875
| 3
|
[
"MIT"
] |
permissive
|
import unittest
import pymatrices as pm
class testArray(object):
def __init__(self, value, result):
self.value = value
self.result = result
verticalVector = testArray([[1]
,[2]
,[3]
,[4]], [4, 1])
horizontalVector = testArray([[1, 2, 3, 4, 5]], [1, 5])
squareMatrix = testArray([[1 , 2]
, [3 , 4]], [2,2])
rectangularMatrix_1 = testArray([[1 , 2]
, [ 3 , 4]
, [ 5 , 6]], [3, 2])
rectangularMatrix_2 = testArray([ [1 , 2 , 3 , 0]
, [4 , 5 , 6 , 0]
, [7 , 8 , 9 , 0]], [3, 4])
matrix_1 = [[ 0, 0, 0],
[ 0, 0, 0]]
matrix_2 = [[ 1, 1],
[ 1, 1],
[ 1, 1]]
matrix_3 = [[ 3, 3, 3],
[ 3, 3, 3],
[ 3, 3, 3]]
variable = pm.Matrix(0, 2, 3)
class TestPM(unittest.TestCase):
def test_inputTypeAssert_CorrectInput(self):
self.assertEqual(
pm.inputTypeAssert(
[ [1234 , int]
, ["string", str]
, [0.2 , (int, float)]
, [ [] , list]
, [ [[]] , list]])
, None)
def test_inputTypeAssert_incorrectInput(self):
self.assertRaises(TypeError,
pm.inputTypeAssert,
[ [1234 , str]
, ["string", int]
, [None , str]
, [0.2 , float] ])
def test_arrayShapeAssert_notAList(self):
self.assertRaises(TypeError,
pm.arrayShapeAssert,
123)
def test_arrayShapeAssert_singleDimensionList(self):
self.assertRaises(TypeError,
pm.arrayShapeAssert,
[1,2])
def test_arrayShapeAssert_wrongList(self):
self.assertRaises(TypeError,
pm.arrayShapeAssert,
list("this is a string"))
def test_arrayShapeAssert_badElementType(self):
self.assertRaises(TypeError,
pm.arrayShapeAssert,
[ [1 , 2 , 1.2]
, [1 , "a" , 3 ] ])
def test_arrayShapeAssert_notConsistentDimensions(self):
self.assertRaises(IndexError,
pm.arrayShapeAssert,
[ [1 , 2 , 3]
, [2 , 3 , 4]
, [2 , 3 , 4, 5] ])
def test_arrayShapeAssert_correctReturn_1(self):
self.assertEqual(
pm.arrayShapeAssert(verticalVector.value)
, verticalVector.result)
def test_arrayShapeAssert_correctReturn_2(self):
self.assertEqual(
pm.arrayShapeAssert(horizontalVector.value)
, horizontalVector.result)
def test_arrayShapeAssert_correctReturn_3(self):
self.assertEqual(
pm.arrayShapeAssert(squareMatrix.value)
, squareMatrix.result)
def test_arrayShapeAssert_correctReturn_4(self):
self.assertEqual(
pm.arrayShapeAssert(rectangularMatrix_1.value)
, rectangularMatrix_1.result)
def test_arrayShapeAssert_correctReturn_5(self):
self.assertEqual(
pm.arrayShapeAssert(rectangularMatrix_2.value)
, rectangularMatrix_2.result)
def test_newMatrix_wrongFillerType(self):
self.assertRaises(TypeError,
pm.Matrix, 'a', 2, 3)
def test_newMatrix_Return_1(self):
variable.newMatrix(0, 2, 3)
self.assertEqual(variable.__grid__
, matrix_1)
def test_newMatrix_Return_2(self):
variable.newMatrix(1, 3, 2)
self.assertEqual(variable.__grid__
, matrix_2)
def test_newMatrix_Return_3(self):
variable.newMatrix(3, 3, 3)
self.assertEqual(variable.__grid__
, matrix_3)
def test_addFunction_incorrectDimensions_1(self):
variable.newMatrix(1, 2, 3)
self.assertRaises(IndexError, variable.__add__, [[3,2,1], [1,2,2], [2,2,2]])
def test_addFunction_incorrectDimensions_2(self):
variable.newMatrix(1, 2, 3)
self.assertRaises(IndexError, variable.__add__, [[3,2,1]])
def test_addFunction_incorrectType(self):
variable.newMatrix(1, 2, 3)
self.assertRaises(TypeError, variable.__add__, 'a')
def test_addFunction_Return_1(self):
variable.newMatrix(1, 3, 1)
self.assertEqual(variable + 2
, [[3], [3], [3]])
def test_addFunction_Return_2(self):
variable.newMatrix(1, 1, 3)
self.assertEqual(variable + 2
, [[3,3,3]])
def test_addFunction_Return_3(self):
variable.newMatrix(1, 2, 3)
self.assertEqual(variable + [[3, 2, 1],
[2, 2, 2]]
, [[4,3,2],[3,3,3]])
def test_addFunction_Return_4(self):
variable.newMatrix(1, 2, 3)
self.assertEqual(variable + 2
, [[3,3,3],[3,3,3]])
def test_addFunction_Return_5(self):
variable.newMatrix([[0,1,2],[3,4,5],[6,7,8]])
self.assertEqual(2 + variable
, [[2,3,4],[5,6,7],[8,9,10]])
if __name__ == "__main__":
unittest.main()
|
JavaScript
|
UTF-8
| 1,670
| 2.5625
| 3
|
[] |
no_license
|
const {
beforeAll,
afterAll,
describe,
test,
expect,
} = require('@jest/globals');
const { connect, close } = require('./db');
const { getLatest, add, remove } = require('../controller/best');
beforeAll(async () => {
await connect();
});
afterAll(async () => {
await close();
});
const getSamplePhoto = (id) => {
const timestamp = Math.round(new Date().getTime() / 10000);
return {
id,
message: '',
picture: 'https://www.example.com/image.jpg',
timestamp,
};
};
const getSamplePhotos = (no = 1) => {
const photos = [];
for (let i = 0; i < no; i += 1) {
photos.push(getSamplePhoto(i));
}
return photos;
};
describe('Photos route test', () => {
test('photos get', async (done) => {
const latest = await getLatest();
expect(latest).toStrictEqual({
ok: true,
});
done();
});
test('insert photo', async (done) => {
const photos = getSamplePhotos(1);
const result = await add(photos);
expect(result).toBeTruthy();
// verify the latest is same
const latest = await getLatest();
expect(latest.data.photos).toStrictEqual(photos);
// insert another
const photos2 = getSamplePhotos(2);
const result2 = await add(photos2);
expect(result2.data.photos).toStrictEqual(photos2);
// verify the latest is same
const latest2 = await getLatest();
expect(latest2.data.photos).toStrictEqual(photos2);
done();
});
test('delete photo', async () => {
const removed = await remove();
expect(removed).toStrictEqual({ ok: true });
// verify
const latest = await getLatest();
expect(latest).toStrictEqual({ ok: true });
});
});
|
Java
|
UTF-8
| 12,292
| 2.171875
| 2
|
[
"MIT"
] |
permissive
|
package org.ergvein;
import android.annotation.TargetApi;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.RouteInfo;
import android.os.Build;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import systems.obsidian.HaskellActivity;
/**
* DNS servers detector
*
* IMPORTANT: don't cache the result.
*
* Or if you want to cache the result make sure you invalidate the cache
* on any network change.
*
* It is always better to use a new instance of the detector when you need
* current DNS servers otherwise you may get into troubles because of invalid/changed
* DNS servers.
*
* This class combines various methods and solutions from:
* Dnsjava http://www.xbill.org/dnsjava/
* Minidns https://github.com/MiniDNS/minidns
*
* Unfortunately both libraries are not aware of Orero changes so new method was added to fix this.
*
* Created by Madalin Grigore-Enescu on 2/24/18.
*/
public class DnsDetector {
private static final String TAG = "DnsDetector";
/**
* Holds some default DNS servers used in case all DNS servers detection methods fail.
* Can be set to null if you want caller to fail in this situation.
*/
private static final String FACTORY_DNS_SERVERS = "1.1.1.1;8.8.8.8;8.8.4.4";
/**
* Properties delimiter used in exec method of DNS servers detection
*/
private static final String METHOD_EXEC_PROP_DELIM = "]: [";
//region - public //////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Returns android DNS servers used for current connected network
* @return Dns servers array
*/
private static String getServers(final HaskellActivity a) {
// Will hold the consecutive result
String[] result;
// METHOD 1: old deprecated system properties
result = getServersMethodSystemProperties();
if (result != null && result.length > 0) {
String res = String.join(";", result);
return res;
}
// METHOD 2 - use connectivity manager
result = getServersMethodConnectivityManager(a);
if (result != null && result.length > 0) {
String res = String.join(";", result);
return res;
}
// LAST METHOD: detect android DNS servers by executing getprop string command in a separate process
// This method fortunately works in Oreo too but many people may want to avoid exec
// so it's used only as a failsafe scenario
result = getServersMethodExec();
if (result != null && result.length > 0) {
String res = String.join(";", result);
return res;
}
// Fall back on factory DNS servers
return FACTORY_DNS_SERVERS;
}
//endregion
//region - private /////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Detect android DNS servers by using connectivity manager
*
* This method is working in android LOLLIPOP or later
*
* @return Dns servers array
*/
private static String [] getServersMethodConnectivityManager(final HaskellActivity a) {
Context context = a.getApplicationContext();
// This code only works on LOLLIPOP and higher
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
ArrayList<String> priorityServersArrayList = new ArrayList<>();
ArrayList<String> serversArrayList = new ArrayList<>();
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
// Iterate all networks
// Notice that android LOLLIPOP or higher allow iterating multiple connected networks of SAME type
for (Network network : connectivityManager.getAllNetworks()) {
NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
if (networkInfo.isConnected()) {
LinkProperties linkProperties = connectivityManager.getLinkProperties(network);
List<InetAddress> dnsServersList = linkProperties.getDnsServers();
// Prioritize the DNS servers for link which have a default route
if (linkPropertiesHasDefaultRoute(linkProperties)) {
for (InetAddress element: dnsServersList) {
String dnsHost = element.getHostAddress();
priorityServersArrayList.add(dnsHost);
}
} else {
for (InetAddress element: dnsServersList) {
String dnsHost = element.getHostAddress();
serversArrayList.add(dnsHost);
}
}
}
}
}
// Append secondary arrays only if priority is empty
if (priorityServersArrayList.isEmpty()) {
priorityServersArrayList.addAll(serversArrayList);
}
// Stop here if we have at least one DNS server
if (priorityServersArrayList.size() > 0) {
return priorityServersArrayList.toArray(new String[0]);
}
} catch (Exception ex) {
Log.d(TAG, "Exception detecting DNS servers using ConnectivityManager method", ex);
}
}
// Failure
return null;
}
/**
* Detect android DNS servers by using old deprecated system properties
*
* This method is NOT working anymore in Android 8.0
* Official Android documentation state this in the article Android 8.0 Behavior Changes.
* The system properties net.dns1, net.dns2, net.dns3, and net.dns4 are no longer available,
* a change that improves privacy on the platform.
*
* https://developer.android.com/about/versions/oreo/android-8.0-changes.html#o-pri
* @return Dns servers array
*/
private static String [] getServersMethodSystemProperties() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
// This originally looked for all lines containing .dns; but
// http://code.google.com/p/android/issues/detail?id=2207#c73
// indicates that net.dns* should always be the active nameservers, so
// we use those.
final String re1 = "^\\d+(\\.\\d+){3}$";
final String re2 = "^[0-9a-f]+(:[0-9a-f]*)+:[0-9a-f]+$";
ArrayList<String> serversArrayList = new ArrayList<>();
try {
Class SystemProperties = Class.forName("android.os.SystemProperties");
Method method = SystemProperties.getMethod("get", new Class[]{String.class});
final String[] netdns = new String[]{"net.dns1", "net.dns2", "net.dns3", "net.dns4"};
for (int i = 0; i < netdns.length; i++) {
Object[] args = new Object[]{netdns[i]};
String v = (String) method.invoke(null, args);
if (v != null && (v.matches(re1) || v.matches(re2)) && !serversArrayList.contains(v)) {
serversArrayList.add(v);
}
}
// Stop here if we have at least one DNS server
if (serversArrayList.size() > 0) {
return serversArrayList.toArray(new String[0]);
}
} catch (Exception ex) {
Log.d(TAG, "Exception detecting DNS servers using SystemProperties method", ex);
}
}
// Failed
return null;
}
/**
* Detect android DNS servers by executing getprop string command in a separate process
*
* Notice there is an android bug when Runtime.exec() hangs without providing a Process object.
* This problem is fixed in Jelly Bean (Android 4.1) but not in ICS (4.0.4) and probably it will never be fixed in ICS.
* https://stackoverflow.com/questions/8688382/runtime-exec-bug-hangs-without-providing-a-process-object/11362081
*
* @return Dns servers array
*/
private static String [] getServersMethodExec() {
// We are on the safe side and avoid any bug
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
try {
Process process = Runtime.getRuntime().exec("getprop");
InputStream inputStream = process.getInputStream();
LineNumberReader lineNumberReader = new LineNumberReader(new InputStreamReader(inputStream));
Set<String> serversSet = methodExecParseProps(lineNumberReader);
if (serversSet != null && serversSet.size() > 0) {
return serversSet.toArray(new String[0]);
}
} catch (Exception ex) {
Log.d(TAG, "Exception in getServersMethodExec", ex);
}
}
// Failed
return null;
}
/**
* Parse properties produced by executing getprop command
* @param lineNumberReader
* @return Set of parsed properties
* @throws Exception
*/
private static Set<String> methodExecParseProps(BufferedReader lineNumberReader) throws Exception {
String line;
Set<String> serversSet = new HashSet<String>(10);
while ((line = lineNumberReader.readLine()) != null) {
int split = line.indexOf(METHOD_EXEC_PROP_DELIM);
if (split == -1) {
continue;
}
String property = line.substring(1, split);
int valueStart = split + METHOD_EXEC_PROP_DELIM.length();
int valueEnd = line.length() - 1;
if (valueEnd < valueStart) {
// This can happen if a newline sneaks in as the first character of the property value. For example
// "[propName]: [\n…]".
Log.d(TAG, "Malformed property detected: \"" + line + '"');
continue;
}
String value = line.substring(valueStart, valueEnd);
if (value.isEmpty()) {
continue;
}
if (property.endsWith(".dns") || property.endsWith(".dns1") ||
property.endsWith(".dns2") || property.endsWith(".dns3") ||
property.endsWith(".dns4")) {
// normalize the address
InetAddress ip = InetAddress.getByName(value);
if (ip == null) continue;
value = ip.getHostAddress();
if (value == null) continue;
if (value.length() == 0) continue;
serversSet.add(value);
}
}
return serversSet;
}
/**
* Returns true if the specified link properties have any default route
* @param linkProperties
* @return true if the specified link properties have default route or false otherwise
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static boolean linkPropertiesHasDefaultRoute(LinkProperties linkProperties) {
for (RouteInfo route : linkProperties.getRoutes()) {
if (route.isDefaultRoute()) {
return true;
}
}
return false;
}
//endregion
}
|
JavaScript
|
UTF-8
| 268
| 3.21875
| 3
|
[
"MIT"
] |
permissive
|
// array include user
// get the name out of array by find and use the function
let arrOne = [
{id: 1, name:"pooya"},
{id: 2, name:"pari"},
{id: 3, name:"masih"},
{id: 4, name:"mohammad"}
];
let user = arrOne.find(item => item.id == 1);
alert(user.name)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.