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
|
---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 4,171 | 2.890625 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Pre-work - CodePath TodoApp
**Listagram** is an android app that allows building a todo list and basic todo items management functionality including adding new items, editing and deleting an existing item.
Submitted by: **Rahul Doshi**
Time spent: **10** hour(s) spent in total
## User Stories
The following **required** functionality is completed:
* [x] User can **successfully add and remove items** from the todo list
* [x] User can **tap a todo item in the list and bring up an edit screen for the todo item** and then have any changes to the text reflected in the todo list.
* [x] User can **persist todo items** and retrieve them properly on app restart
The following **optional** features are implemented:
* [x] Persist the todo items [into SQLite](http://guides.codepath.com/android/Persisting-Data-to-the-Device#sqlite) instead of a text file
* [x] Improve style of the todo items in the list [using a custom adapter](http://guides.codepath.com/android/Using-an-ArrayAdapter-with-ListView)
* [x] Add support for completion due dates for todo items (and display within listview item)
* [x] Use a [DialogFragment](http://guides.codepath.com/android/Using-DialogFragment) instead of new Activity for editing items
* [x] Add support for selecting the priority of each todo item (and display in listview item)
* [x] Tweak the style improving the UI / UX, play with colors, images or backgrounds
The following **additional** features are implemented:
* [x] User can search for task items by keywords in the name
* [x] User can sort task items by due date, priority
* [x] Splash Screen while the app loads/configures itself (DBFlow) on slower devices
## Video Walkthrough
Here's a walkthrough of implemented user stories:
<img src='http://i.imgur.com/6MVJDDd.gif' title='Video Walkthrough' width='' alt='Video Walkthrough' />
GIF created with [LiceCap](http://www.cockos.com/licecap/).
## Notes
I planned on completing a whole number of other design ideas that I have but I had no time/ran short:
* Use material design's floating action button style to allow for creation of new task items (promoted action)
* Use an icon (eg. exclamation or bell) and colored vertical line to signify overdue task items
* Allow users to set optional reminders for task items in the list
* Human readable dates (ex. Today, Tomorrow, Yesterday, This Month, Next Month, x Days from Now, n Months from Now etc.)
* Tabbed activity view to separate/segragate items either by priority, due date or completed/incomplete/archived
* Tindr-like take on ToDos with a swipeable UX for done/not-done items (aka Listr)
* Connect to some simple backend server (like Firebase) to persist a user's todo tak items across multiple devices (with a unique ID such as a set of login credentials)
DBFlow was also slightly tricky to work with, especially when changing the type for a column the app needed to be recompiled before it would pick up the changes (for autocomplete) when writing out the syntax for SQL queries etc.
Given more time, I would have probably also restructured/refactored my app into a few different packages, and identified several places where I could have easily promoted code reusability using modern OOP concepts and design patterns like abstraction, data encapsulation and polymorphism.
Lastly, getting the right icons was a challenge, and layouts were not always easy to work with.
Finally, I would have also liked to include at least some rudimentary/basic testing. I spent a lot of time debugging my app and manually testing edge-cases and corner conditions.
## License
Copyright 2017 Rahul Doshi
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.
|
Java
|
UTF-8
| 13,036 | 2.25 | 2 |
[] |
no_license
|
package com.forthelight.controller;
import com.forthelight.biz.CollegeBiz;
import com.forthelight.biz.MajorBiz;
import com.forthelight.biz.StudentBiz;
import com.forthelight.biz.StudentCommentCourseBiz;
import com.forthelight.domain.College;
import com.forthelight.domain.Major;
import com.forthelight.domain.Student;
import com.forthelight.domain.StudentCommentCourse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
public class StudentController {
private StudentBiz studentBiz;
private MajorBiz majorBiz;
private CollegeBiz collegeBiz;
@Autowired
private StudentCommentCourseBiz studentCommentCourseBiz;
@Autowired
public void setStudentBiz(StudentBiz studentBiz) {
this.studentBiz = studentBiz;
}
@Autowired
public void setMajorBiz(MajorBiz majorBiz) {
this.majorBiz = majorBiz;
}
@Autowired
public void setCollegeBiz(CollegeBiz collegeBiz) {
this.collegeBiz = collegeBiz;
}
@RequestMapping(value = "/login", produces = "application/json;charset=UTF-8")
@ResponseBody
public String login(HttpServletRequest request, HttpServletResponse response) {
response.setCharacterEncoding("UTF-8");
response.setContentType("json");
Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
Map<String, Object> rsp = new HashMap<>();
String NickName = request.getParameter("NickName");
String password = request.getParameter("password");
Student student = studentBiz.loginValidate(NickName);
if (student != null && student.getPassword() != null){
if (student.getPassword().equals(password)){
rsp.put("success", true);
rsp.put("data", "登陆成功");
HttpSession session = request.getSession();
session.setAttribute("user",student);
} else {
rsp.put("success", false);
rsp.put("data", "密码错误");
}
} else {
rsp.put("success",false);
rsp.put("data","用户不存在");
}
return gson.toJson(rsp);
}
@RequestMapping(value = "/getsession", produces = "application/json;charset=UTF-8")
@ResponseBody
public String getsession(HttpServletRequest request, HttpServletResponse response){
response.setCharacterEncoding("UTF-8");
response.setContentType("json");
Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
Map<String, Object> rsp = new HashMap<>();
HttpSession session = request.getSession(false);
Student student = (Student)session.getAttribute("user");
if(student==null) {
rsp.put("success", false);
rsp.put("data","当前未登录");
}else{
rsp.put("success",true);
rsp.put("data",student);
}
return gson.toJson(rsp);
}
@RequestMapping(value = "/register", produces = "application/json;charset=UTF-8")
@ResponseBody
public String register(HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> rsp = new HashMap<>();
Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
String collegeName = request.getParameter("collegeName");
College college = collegeBiz.findByName(collegeName);
Major major = majorBiz.findByName(request.getParameter("majorName"));
// 验证学院和专业
if (college == null) {
rsp.put("success", false);
rsp.put("data", String.format("学院 %s 不存在", request.getParameter("collegeName")));
return gson.toJson(rsp);
} else {
if (major == null || !major.getCollege().getId().equals(college.getId())) {
rsp.put("success", false);
rsp.put("data", String.format("学院 %s 下没有专业 %s", request.getParameter("collegeName"),
request.getParameter("majorName")));
return gson.toJson(rsp);
}
}
// 验证学号重复
if (studentBiz.findByStudentNumber(request.getParameter("studentNumber")) != null) {
rsp.put("success", false);
rsp.put("data", "该学号已注册");
return gson.toJson(rsp);
}
// 验证姓名重复
if (studentBiz.findByName(request.getParameter("studentName")) != null) {
rsp.put("success", false);
rsp.put("data", "该姓名已注册");
return gson.toJson(rsp);
}
// 验证两次密码
if (!request.getParameter("password").equals(request.getParameter("re_password"))) {
rsp.put("success", false);
rsp.put("data", "两次密码不一致");
return gson.toJson(rsp);
}
// 创建用户
Student newStudent = new Student();
newStudent.setStudentName(request.getParameter("studentName"));
newStudent.setStudentNumber(request.getParameter("studentNumber"));
newStudent.setPassword(request.getParameter("password"));
newStudent.setNickName(request.getParameter("nickName"));
newStudent.setGender(request.getParameter("gender"));
newStudent.setGrade(Integer.parseInt(request.getParameter("grade")));
newStudent.setCollege(college);
newStudent.setMajor(major);
studentBiz.insert(newStudent);
rsp.put("success", true);
rsp.put("data", "注册成功");
return gson.toJson(rsp);
}
@RequestMapping(value = "/studentInfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE
+ ";charset=utf-8")
@ResponseBody
public String getStudentInfo(String studentIdStr, HttpServletResponse response) {
response.setContentType("text/json;charset:UTF-8");
response.setCharacterEncoding("UTF-8");
Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
int studentId = Integer.parseInt(studentIdStr);
boolean success = false;
if (studentIdStr != null) {
success = true;
}
// ------------------ 左边栏学生信息数据 ------------------
Student student = studentBiz.findById(studentId);
if (student == null) {
success = false;
}
Map<String, Object> studentInfo = new HashMap<>();
studentInfo.put("student", student);
studentInfo.put("college", student.getCollege());
studentInfo.put("major", student.getMajor());
studentInfo.put("courses", student.getCourses());
// ------------------ 第一个标签栏数据 ---------------------
List<StudentCommentCourse> studentCommentCourses = studentCommentCourseBiz.findByStudentId(studentId);
JsonArray comments = new JsonArray();
for (StudentCommentCourse studentCommentCourse : studentCommentCourses) {
JsonObject comment = new JsonObject();
// comment.addProperty("studentPortrait",
// studentCommentCourse.getStudent().getStudentPortrait());
int courseId = studentCommentCourse.getSelectId();
comment.addProperty("courseName", studentCommentCourse.getCourse().getCourseName());
String commentTime = studentCommentCourse.getCommentTime().toString();
comment.addProperty("commentTime", commentTime);
comment.addProperty("likeNumber", studentCommentCourse.getLikeNumber());
comment.addProperty("commentContent", studentCommentCourse.getComment());
comments.add(comment);
}
Map<String, Object> data = new HashMap<>();
data.put("studentInfo", studentInfo);
data.put("comments", comments);
Map<String, Object> res = new HashMap<>();
res.put("data", data);
res.put("success", success);
return gson.toJson(res);
}
@RequestMapping(value = "/editStudentInfo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE
+ ";charset=utf-8")
@ResponseBody
public String editStudentInfo(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/json;charset:UTF-8");
response.setCharacterEncoding("UTF-8");
Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
String studentIdStr = request.getParameter("studentIdStr");
String nickName = request.getParameter("nickName");
String gender = request.getParameter("gender");
String password = request.getParameter("password");
String college = request.getParameter("college");
String major = request.getParameter("major");
int genderNumber = Integer.parseInt(gender);
Student student = new Student();
int studentId = Integer.parseInt(studentIdStr);
student.setId(studentId);
student.setNickName(nickName);
student.setGender(gender);
student.setStudentPortrait(studentBiz.findById(studentId).getStudentPortrait());
student.setPassword(password);
student.setCollege(collegeBiz.findByName(college));
student.setMajor(majorBiz.findByName(major));
int result = studentBiz.update(student);
boolean success = false;
if (result > 0) {
success = true;
}
Map<String, Object> res = new HashMap<>();
res.put("success", success);
return gson.toJson(res);
}
@RequestMapping(value = "/searchStudent", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE
+ ";charset=utf-8")
@ResponseBody
public String searchStudentInfo(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/json;charset:UTF-8");
response.setCharacterEncoding("UTF-8");
Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
Map<String, Object> res = new HashMap<>();
String keyword = request.getParameter("keyword");
List<Student> students = new ArrayList<Student>();
if (keyword == "") {
students = studentBiz.findAll();
} else {
students = studentBiz.findByKeyword(keyword);
}
boolean success = false;
if (students.size() > 0) {
success = true;
}
JsonArray studentInfo = new JsonArray();
for (Student student : students) {
JsonObject studentInfoArray = new JsonObject();
studentInfoArray.addProperty("studentId", student.getId());
studentInfoArray.addProperty("studentName", student.getStudentName());
studentInfoArray.addProperty("nickName", student.getNickName());
studentInfoArray.addProperty("studentNumber", student.getStudentNumber());
studentInfoArray.addProperty("college", student.getCollege().getCollegeName());
studentInfoArray.addProperty("major", student.getMajor().getMajorName());
studentInfoArray.addProperty("selectNumber", student.getCourses().size());
studentInfoArray.addProperty("commentNumber",studentCommentCourseBiz.findByStudentId(student.getId()).size());
studentInfo.add(studentInfoArray);
}
Map<String, Object> data = new HashMap<>();
data.put("students", studentInfo);
res.put("data", data);
res.put("success", success);
return gson.toJson(res);
}
@RequestMapping(value = "/deleteStudent", method = RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
@ResponseBody
public String deleteStudent(String studentIdStr, HttpServletResponse response) {
response.setContentType("text/json;charset:UTF-8");
response.setCharacterEncoding("UTF-8");
Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
Map<String, Object> res = new HashMap<>();
boolean success = false;
int studentId = Integer.parseInt(studentIdStr);
int result = studentBiz.delete(studentId);
if(result > 0) {
success = true;
}
res.put("success", success);
return gson.toJson(res);
}
@RequestMapping(value = "/studentBasicInfo", method = RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
@ResponseBody
public String studentBasicInfo(String studentIdStr, HttpServletResponse response) {
response.setContentType("text/json;charset:UTF-8");
response.setCharacterEncoding("UTF-8");
Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
Map<String, Object> res = new HashMap<>();
int studentId = Integer.parseInt(studentIdStr);
boolean success = false;
if (studentIdStr != null) {
success = true;
}
Student studentInfo = studentBiz.findById(studentId);
if (studentInfo == null) {
success = false;
}
Map<String, Object> student = new HashMap<>();
student.put("student", studentInfo);
student.put("college", studentInfo.getCollege().getCollegeName());
student.put("major", studentInfo.getMajor().getMajorName());
if(studentInfo.getGrade() == 1){
student.put("grade","大一");
}
if(studentInfo.getGrade() == 2){
student.put("grade","大二");
}
if(studentInfo.getGrade() == 3){
student.put("grade","大三");
}
if(studentInfo.getGrade() == 4){
student.put("grade","大四");
}
Map<String, Object> data = new HashMap<>();
data.put("student",student);
res.put("data",data);
res.put("success",success);
return gson.toJson(res);
}
}
|
Markdown
|
UTF-8
| 469 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
# affirmeep
##### Express JS Demo API
Two endpoints available:
***/***
Returns Hello World
***/affirmations***
Gives you a random affirmation
## Quick Start
Install dependencies:
```bash
$ npm install
```
Start the server:
```bash
$ npm start
```
View the website at: http://localhost:3000
## Tests
To run the test suite, first install the dependencies, then run `npm test`:
```bash
$ npm install
$ npm test
```
## License
[MIT](LICENSE)
|
Python
|
UTF-8
| 2,149 | 2.640625 | 3 |
[] |
no_license
|
import numpy as np
from sklearn.ensemble import RandomForestClassifier
import threading
from joblib import Parallel, delayed
class BalancedRFClassifier(RandomForestClassifier):
def predict_proba(self, X):
"""Predict class probabilities for X.
The predicted class probabilities of an input sample are computed as
the mean predicted class probabilities of the trees in the forest. The
class probability of a single tree is the fraction of samples of the same
class in a leaf. This variant corrects for issues with weighting for
unbalanced classes.
Parameters
----------
X : array-like or sparse matrix of shape = [n_samples, n_features]
The input samples. Internally, its dtype will be converted to
``dtype=np.float32``. If a sparse matrix is provided, it will be
converted into a sparse ``csr_matrix``.
Returns
-------
p : array of shape = [n_samples, n_classes], or a list of n_outputs
such arrays if n_outputs > 1.
The class probabilities of the input samples. The order of the
classes corresponds to that in the attribute `classes_`.
"""
check_is_fitted(self, 'estimators_')
# Check data
X = self._validate_X_predict(X)
# Assign chunk of trees to jobs
n_jobs, _, _ = _partition_estimators(self.n_estimators, self.n_jobs)
# avoid storing the output of every estimator by summing them here
all_proba = [np.zeros((X.shape[0], j), dtype=np.float64)
for j in np.atleast_1d(self.n_classes_)]
lock = threading.Lock()
Parallel(n_jobs=n_jobs, verbose=self.verbose,
**_joblib_parallel_args(require="sharedmem"))(
delayed(_accumulate_prediction)(e.predict_proba, X, all_proba,
lock)
for e in self.estimators_)
for proba in all_proba:
proba /= len(self.estimators_)
if len(all_proba) == 1:
return all_proba[0]
else:
return all_proba
|
JavaScript
|
UTF-8
| 307 | 3.8125 | 4 |
[] |
no_license
|
//Assigment loop
let foods = ["tomato", "broccoli", "kale", "cabbage", "apple"]
//forLoop
function forLoop(arr){
for(let i = 0; i < foods.length; i++){
if(foods[i]!="apple"){
console.log(`${foods[i]} is a healthy food, it's definitely worth to eat.`)
}
}
}
//forEach
|
Markdown
|
UTF-8
| 278 | 2.53125 | 3 |
[] |
no_license
|
# PollApp
A platform which allows users to share their oppinions in various (more or less important) matters via short poll method. User can take part in as many polls as he or she wants. Users can also create their own questions and see what the world thinks about the issues.
|
Java
|
UTF-8
| 671 | 1.914063 | 2 |
[] |
no_license
|
package com.example.scholaedu;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
public class GrupFragment extends Fragment {
private TextView toolbarText_;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.grup_discussion, container, false);
toolbarText_ = root.findViewById(R.id.toolbar_text_group_discussion);
return root;
}
}
|
Java
|
UTF-8
| 309 | 2.203125 | 2 |
[
"Apache-2.0"
] |
permissive
|
package tamil.lang.api.expression;
import tamil.lang.exception.service.ServiceException;
/**
* Created by velsubra on 11/30/16.
*/
public interface BinaryOperator<T> {
public OperatorDefinition getOperator();
public Operand<T> perform(Operand<T> left, Operand<T> right) throws ServiceException;
}
|
Java
|
UTF-8
| 773 | 1.953125 | 2 |
[] |
no_license
|
package com.olxchallenge.pages.login;
import com.olxchallenge.framework.AbstractPage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class LoginPage extends AbstractPage{
public LoginPage(WebDriver driver) {
super(driver);
}
public void login(){
getElementById("login").sendKeys("qachallengept0512@gmail.com");
getElementById("password").sendKeys("inicial051217");
getElementByValueAndClassName("btn-default","Zaloguj").click();
}
public void accesLoginPage(){
accessUrl("https://www.otodom.pl/konto/?ref%5B0%5D%5Baction%5D=myaccount&ref%5B0%5D%5Bmethod%5D=index");
}
public void logout(){
getElementById("user_items").click();
getElementById("logout").click();
}
}
|
Python
|
UTF-8
| 444 | 3.953125 | 4 |
[] |
no_license
|
#!/usr/bin/env python
def Function(x, y, z=20):
return (x + y + z);
print "Sum: {}".format(Function(1, 5, 10))
print "Sum: {}".format(Function(x=1, y=5))
print "Sum: {}".format(Function(1, y=5, z=20))
print "Sum: {}".format(Function('I', ' am', ' Groot'))
print "Sum: {}".format(Function([1], [5], [100]))
list = [1, 3, 5]
print "Sum: {}".format(Function(*list))
dict = {'x': 1, 'y': 3, 'z': 5}
print "Sum: {}".format(Function(**dict))
|
C++
|
UTF-8
| 391 | 2.609375 | 3 |
[] |
no_license
|
#include "Startmenu.hpp"
// Starts te Start Menu.
void StartMenu::StartMenuLoop(){
hwlib::wait_ms(500);
displayText
<< "\f" << "Press Button "
<< "\n" << "to start " << hwlib::flush;
for(;;){
hwlib::wait_ms(20);
if(!continueButton.read()){
displayText
<< "\n" << "Button Pressed. "
<< "\n" << "Loading game. " << hwlib::flush;
hwlib::wait_ms(1000);
break;
}
}
}
|
Java
|
UTF-8
| 3,157 | 3.265625 | 3 |
[] |
no_license
|
package Patterns.week3.fileio;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
/*
Sinds versie 7 kent Java try-with-resources. De syntax hiervan is als volgt:
1. try (r = Resource):
2. doe je dingen met r
3. catch (Ex e):
4. doe dingen met e
5. finally:
6. dingen opruimen
Een checked Exception die door de Resource in regel 1 kan worden geworpen, vereist nog steeds
een catch or declare, maar in alle gevallen wordt de resource impliciet voor je afgesloten. De
scope van de Resource r is in dit voorbeeld alleen maar regel 2, dus je hebt daar geen beschikking
over binnen je catch- of je finally-blok; dit is een verandering ten opzichte van de klassieke
methode, waar je de variabelen declareert buiten de scope van de try, omdat je die in het finally-
blok wilt kunnen adresseren (om hem te sluiten bijvoorbeeld).
Om in een try-with-resource gebruikt te kunnen worden, moeten Resource de interface AutoClosable
implementeren:
https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html
Op die manier kun je dus ook je eigen Resources creëren (bijvoorbeeld wanneer je met een database-
connectie werkt).
Omdat we hier toch met 1.8 werken, heb ik ook het printen en dergelijke in een lambda gezet. Het is
van belang dat je deze syntax begrijpt en kunt lezen en toepassen.
*/
public class DemoTryWithResources implements FileDemo {
public void directoryListing() {
// try with resource
String path = "/Users/docent/Desktop/";
try (Stream<Path> stream = Files.list(Paths.get(path))) {
// lambda voor het uitprinten
stream.forEach(f -> System.out.println(f));
} catch (IOException e) {
System.out.println("Er ging iets mis met het lezen van de directory.");
e.printStackTrace();
}
}
public void listFileContents() {
String filename = "/Users/docent/Desktop/demo.txt";
Path path = Paths.get(filename);
try (BufferedReader reader = Files.newBufferedReader(path)) {
// lambda voor het uitprinten
reader.lines().forEach(l -> System.out.println(l));
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeToFile () {
String filename = "/Users/docent/Desktop/schrijven_java8.txt";
Path path = Paths.get(filename);
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
writer.write("A28 bij Leusden dicht nadat vrachtwagen viaduct ramt.\n");
writer.write("NAVO en EU uiten zorgen over zenuwgasaanval Russische spion.\n");
writer.write("Rusland zal direct reageren als VS Syrië bestookt met aanvallen.\n");
writer.write("Video Dronebeelden tonen hoe wolkenkrabber Kentucky wordt opgeblazen.\n");
} catch (IOException e) {
System.out.println("Er ging iets fout bij het wegschrijven");
e.printStackTrace();
}
}
}
|
Swift
|
UTF-8
| 1,385 | 2.703125 | 3 |
[] |
no_license
|
//
// WebService.swift
// FlickrApes
//
// Created by Shahin on 2018-05-27.
// Copyright © 2018 98%Chimp. All rights reserved.
//
import Foundation
import Alamofire
class WebService
{
typealias Keys = Constants.Web.Keys
typealias Paths = Constants.Web.Paths
static func searchPhotos(for tags: String, completion: @escaping (_ photos: [FlickrPhoto]) -> Void)
{
let params = [Keys.format: "json",
Keys.tags: tags]
Alamofire.request(Paths.publicPhotos, method: .get, parameters: params, encoding: URLEncoding.default, headers: nil).responseString { (response) in
var flickrPhotos = [FlickrPhoto]()
let jsonString = response.value
let cleanedUpJSONString = jsonString?.dropFirst(15).dropLast()
guard let data = cleanedUpJSONString?.data(using: .utf8),
let photosDictionary = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
let rawPhotos = photosDictionary?["items"] as? [[String: Any]]
else { return }
for photoDict in rawPhotos
{
let photo = FlickrPhoto().parse(with: photoDict)
flickrPhotos.append(photo)
}
completion(flickrPhotos)
}
}
}
|
Python
|
UTF-8
| 6,163 | 2.53125 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
"""
Defines the unit tests for the :mod:`colour.models.rgb.transfer_functions.\
fujifilm_flog` module.
"""
import numpy as np
import unittest
from colour.models.rgb.transfer_functions import (
log_encoding_FLog,
log_decoding_FLog,
)
from colour.utilities import domain_range_scale, ignore_numpy_errors
__author__ = "Colour Developers"
__copyright__ = "Copyright 2013 Colour Developers"
__license__ = "New BSD License - https://opensource.org/licenses/BSD-3-Clause"
__maintainer__ = "Colour Developers"
__email__ = "colour-developers@colour-science.org"
__status__ = "Production"
__all__ = [
"TestLogEncoding_FLog",
"TestLogDecoding_FLog",
]
class TestLogEncoding_FLog(unittest.TestCase):
"""
Define :func:`colour.models.rgb.transfer_functions.fujifilm_flog.\
log_encoding_FLog` definition unit tests methods.
"""
def test_log_encoding_FLog(self):
"""
Test :func:`colour.models.rgb.transfer_functions.fujifilm_flog.\
log_encoding_FLog` definition.
"""
self.assertAlmostEqual(
log_encoding_FLog(0.0), 0.092864000000000, places=7
)
self.assertAlmostEqual(
log_encoding_FLog(0.18), 0.459318458661621, places=7
)
self.assertAlmostEqual(
log_encoding_FLog(0.18, 12), 0.459318458661621, places=7
)
self.assertAlmostEqual(
log_encoding_FLog(0.18, 10, False), 0.463336510514656, places=7
)
self.assertAlmostEqual(
log_encoding_FLog(0.18, 10, False, False),
0.446590337236003,
places=7,
)
self.assertAlmostEqual(
log_encoding_FLog(1.0), 0.704996409216428, places=7
)
def test_n_dimensional_log_encoding_FLog(self):
"""
Test :func:`colour.models.rgb.transfer_functions.fujifilm_flog.\
log_encoding_FLog` definition n-dimensional arrays support.
"""
L_in = 0.18
V_out = log_encoding_FLog(L_in)
L_in = np.tile(L_in, 6)
V_out = np.tile(V_out, 6)
np.testing.assert_almost_equal(
log_encoding_FLog(L_in), V_out, decimal=7
)
L_in = np.reshape(L_in, (2, 3))
V_out = np.reshape(V_out, (2, 3))
np.testing.assert_almost_equal(
log_encoding_FLog(L_in), V_out, decimal=7
)
L_in = np.reshape(L_in, (2, 3, 1))
V_out = np.reshape(V_out, (2, 3, 1))
np.testing.assert_almost_equal(
log_encoding_FLog(L_in), V_out, decimal=7
)
def test_domain_range_scale_log_encoding_FLog(self):
"""
Test :func:`colour.models.rgb.transfer_functions.fujifilm_flog.\
log_encoding_FLog` definition domain and range scale support.
"""
L_in = 0.18
V_out = log_encoding_FLog(L_in)
d_r = (("reference", 1), ("1", 1), ("100", 100))
for scale, factor in d_r:
with domain_range_scale(scale):
np.testing.assert_almost_equal(
log_encoding_FLog(L_in * factor), V_out * factor, decimal=7
)
@ignore_numpy_errors
def test_nan_log_encoding_FLog(self):
"""
Test :func:`colour.models.rgb.transfer_functions.fujifilm_flog.\
log_encoding_FLog` definition nan support.
"""
log_encoding_FLog(np.array([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]))
class TestLogDecoding_FLog(unittest.TestCase):
"""
Define :func:`colour.models.rgb.transfer_functions.fujifilm_flog.\
log_decoding_FLog` definition unit tests methods.
"""
def test_log_decoding_FLog(self):
"""
Test :func:`colour.models.rgb.transfer_functions.fujifilm_flog.\
log_decoding_FLog` definition.
"""
self.assertAlmostEqual(
log_decoding_FLog(0.092864000000000), 0.0, places=7
)
self.assertAlmostEqual(
log_decoding_FLog(0.459318458661621), 0.18, places=7
)
self.assertAlmostEqual(
log_decoding_FLog(0.459318458661621, 12), 0.18, places=7
)
self.assertAlmostEqual(
log_decoding_FLog(0.463336510514656, 10, False), 0.18, places=7
)
self.assertAlmostEqual(
log_decoding_FLog(0.446590337236003, 10, False, False),
0.18,
places=7,
)
self.assertAlmostEqual(
log_decoding_FLog(0.704996409216428), 1.0, places=7
)
def test_n_dimensional_log_decoding_FLog(self):
"""
Test :func:`colour.models.rgb.transfer_functions.fujifilm_flog.\
log_decoding_FLog` definition n-dimensional arrays support.
"""
V_out = 0.459318458661621
L_in = log_decoding_FLog(V_out)
V_out = np.tile(V_out, 6)
L_in = np.tile(L_in, 6)
np.testing.assert_almost_equal(
log_decoding_FLog(V_out), L_in, decimal=7
)
V_out = np.reshape(V_out, (2, 3))
L_in = np.reshape(L_in, (2, 3))
np.testing.assert_almost_equal(
log_decoding_FLog(V_out), L_in, decimal=7
)
V_out = np.reshape(V_out, (2, 3, 1))
L_in = np.reshape(L_in, (2, 3, 1))
np.testing.assert_almost_equal(
log_decoding_FLog(V_out), L_in, decimal=7
)
def test_domain_range_scale_log_decoding_FLog(self):
"""
Test :func:`colour.models.rgb.transfer_functions.fujifilm_flog.\
log_decoding_FLog` definition domain and range scale support.
"""
V_out = 0.459318458661621
L_in = log_decoding_FLog(V_out)
d_r = (("reference", 1), ("1", 1), ("100", 100))
for scale, factor in d_r:
with domain_range_scale(scale):
np.testing.assert_almost_equal(
log_decoding_FLog(V_out * factor), L_in * factor, decimal=7
)
@ignore_numpy_errors
def test_nan_log_decoding_FLog(self):
"""
Test :func:`colour.models.rgb.transfer_functions.fujifilm_flog.\
log_decoding_FLog` definition nan support.
"""
log_decoding_FLog(np.array([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]))
if __name__ == "__main__":
unittest.main()
|
Java
|
UTF-8
| 1,154 | 2.046875 | 2 |
[] |
no_license
|
package com.silverpeas.mobile.server.services;
import org.silverpeas.core.date.Date;
import org.silverpeas.core.socialnetwork.model.SocialInformation;
import org.silverpeas.core.socialnetwork.model.SocialInformationType;
import org.silverpeas.core.socialnetwork.provider.ProviderSwitchInterface;
import org.silverpeas.core.util.ServiceProvider;
import org.silverpeas.core.util.logging.SilverLogger;
import java.util.ArrayList;
import java.util.List;
public class ProviderService {
private ProviderSwitchInterface switchInterface;
public ProviderService() {
switchInterface = ServiceProvider.getService(ProviderSwitchInterface.class);
}
public List<SocialInformation> getSocialInformationsListOfMyContact(SocialInformationType socialInformationType, String myId,
List<String> myContactIds, Date begin, Date end) {
try {
return switchInterface.getSocialInformationsListOfMyContacts(socialInformationType, myId, myContactIds, begin, end);
} catch (Exception ex) {
SilverLogger.getLogger("socialNetwork").error("ProviderService.getSocialInformationsListOfMyContact",ex);
}
return new ArrayList<>();
}
}
|
SQL
|
UTF-8
| 4,180 | 3.15625 | 3 |
[] |
no_license
|
-- --------------------------------------------------------
-- Host: 127.0.0.1
-- Server version: 8.0.17 - MySQL Community Server - GPL
-- Server OS: Win64
-- HeidiSQL Version: 10.2.0.5599
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- Dumping database structure for boot2
CREATE DATABASE IF NOT EXISTS `boot2` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci */ /*!80016 DEFAULT ENCRYPTION='N' */;
USE `boot2`;
-- Dumping structure for table boot2.course
CREATE TABLE IF NOT EXISTS `course` (
`id` int(11) NOT NULL,
`duration` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- Dumping data for table boot2.course: ~5 rows (approximately)
/*!40000 ALTER TABLE `course` DISABLE KEYS */;
REPLACE INTO `course` (`id`, `duration`, `name`) VALUES
(1, '6 months', 'Java'),
(3, '2 months', 'jpa'),
(4, '1 months', 'spring security'),
(8, '1 month', 'hibernate'),
(9, '2 months', 'hibernate');
/*!40000 ALTER TABLE `course` ENABLE KEYS */;
-- Dumping structure for table boot2.enquiry
CREATE TABLE IF NOT EXISTS `enquiry` (
`id` int(11) NOT NULL,
`enquirer_contact_number` int(11) NOT NULL,
`enquirer_email` varchar(255) DEFAULT NULL,
`enquirer_name` varchar(255) DEFAULT NULL,
`is_available` varchar(255) DEFAULT NULL,
`query` varchar(255) DEFAULT NULL,
`course_id` int(11) DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FKikwh71k4u3pn9w2n5tgh0miwb` (`course_id`),
CONSTRAINT `FKikwh71k4u3pn9w2n5tgh0miwb` FOREIGN KEY (`course_id`) REFERENCES `course` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- Dumping data for table boot2.enquiry: ~6 rows (approximately)
/*!40000 ALTER TABLE `enquiry` DISABLE KEYS */;
REPLACE INTO `enquiry` (`id`, `enquirer_contact_number`, `enquirer_email`, `enquirer_name`, `is_available`, `query`, `course_id`, `created_at`, `updated_at`) VALUES
(1, 983876, '27tarang@gmail.com', 'Tarang', NULL, 'We are 5 students to opt for this course, when can we expect to enroll in.', 3, '2019-08-21 02:51:06', '2019-08-21 02:51:17'),
(2, 983876, '27tarang@gmail.com', 'LMP', NULL, 'We are 5 students to opt for this course, when can we expect to enroll in.', 3, '2019-08-21 02:51:07', '2019-08-21 02:51:17'),
(7, 983876, '27tarang@gmail.com', 'PQR', NULL, 'We are 5 students to opt for this course, when can we expect to enroll in.', 3, '2019-08-21 02:51:08', '2019-08-21 02:51:16'),
(10, 983876, '27tarang@gmail.com', 'LMP', 'Yes', 'Reolved', 3, '2019-08-21 02:51:09', '2019-08-21 02:51:14'),
(11, 983876, '27tarang@gmail.com', 'quack', NULL, 'We are 5 students waiting for this course to start, when can we expect to enroll in this.', 3, '2019-08-21 02:51:09', '2019-08-21 02:51:12'),
(12, 983876, '27tarang@gmail.com', 'quack quack', NULL, 'We are 5 students waiting for this course to start, when can we expect to enroll in this.', 1, '2019-08-21 19:14:59', '2019-08-21 19:15:00');
/*!40000 ALTER TABLE `enquiry` ENABLE KEYS */;
-- Dumping structure for table boot2.hibernate_sequence
CREATE TABLE IF NOT EXISTS `hibernate_sequence` (
`next_val` bigint(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- Dumping data for table boot2.hibernate_sequence: ~2 rows (approximately)
/*!40000 ALTER TABLE `hibernate_sequence` DISABLE KEYS */;
REPLACE INTO `hibernate_sequence` (`next_val`) VALUES
(13),
(13);
/*!40000 ALTER TABLE `hibernate_sequence` ENABLE KEYS */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
|
Swift
|
UTF-8
| 993 | 3.921875 | 4 |
[
"MIT"
] |
permissive
|
//
// main.swift
// COWWrapper
//
// Created by Alexander Rubtsov on 21.06.2021.
// Реализовать COW reference type объекта в своей структуре
import Foundation
//Simple class
class Car {
enum Model {
case Porsche
case lamborghini
case Lada
}
var model: Model
init(model: Model) {
self.model = model
}
}
//Struct that handles COW around the simple class object
struct CarCopyOnWrite {
var car: Car
var model: Car.Model {
get { return car.model }
set {
if !isKnownUniquelyReferenced(&car) {
car = Car(model: newValue)
}
car.model = newValue
}
}
init(model: Car.Model) {
car = Car(model: model)
}
}
//MARK: - Test
var myCar = CarCopyOnWrite(model: .lamborghini)
var otherCar = myCar
otherCar.model = .Lada
print("My car is \(myCar.model) while other cars are just \(otherCar.model)")
|
PHP
|
UTF-8
| 497 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Database\Seeders;
use App\Models\Subject;
use Illuminate\Database\Seeder;
class SubjectSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Subject::create(['subject' => 'English']);
Subject::create(['subject' => 'Gujarati']);
Subject::create(['subject' => 'Hindi']);
Subject::create(['subject' => 'Sanskrit']);
Subject::create(['subject' => 'Maths']);
}
}
|
C#
|
UTF-8
| 1,456 | 2.53125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AjaxTentaTest.Models;
namespace AjaxTentaTest.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult Details()
{
Person person = new Person()
{
Id = 1,
Name = "Roger",
BirthDate = new DateTime(year: 1954, month: 03, day: 12)
};
return View(person);
}
public string HitMe()
{
return " Pow-Punch! ";
}
public string Hide()
{
return "";
}
public ActionResult GetCarCreate(int id)
{
return RedirectToAction(actionName: "_Create2",
controllerName: "Car",
routeValues: new { id });
//TODO Forsätt här...
/*
return RedirectToAction(actionName: "_Create",
controllerName: "Car",
routeValues: new { id });
*/
}
}
}
|
C#
|
UTF-8
| 7,675 | 3.125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RadioactiveBunnies
{
class Startup
{
static int[] playerPosition = new int[2];
static bool gameOverWon = false;
static bool gameOverDead = false;
static void Main(string[] args)
{
var input = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
int rowIndex = input[0];
int colIndex = input[1];
char[][] matrix = new char[rowIndex][];
for (int row = 0; row < matrix.Length; row++)
{
matrix[row] = Console.ReadLine().ToCharArray();
}
var commands = Console.ReadLine().ToCharArray();
for (int i = 0; i < commands.Length; i++)
{
if (commands[i] == 'U')
{
Move(matrix, 'U');
if (gameOverWon || gameOverDead)
{
break;
}
}
if (commands[i] == 'R')
{
Move(matrix, 'R');
if (gameOverWon || gameOverDead)
{
break;
}
}
if (commands[i] == 'L')
{
Move(matrix, 'L');
if (gameOverWon || gameOverDead)
{
break;
}
}
if (commands[i] == 'D')
{
Move(matrix, 'D');
if (gameOverWon || gameOverDead)
{
break;
}
}
}
if (gameOverWon)
{
for (int row = 0; row < matrix.Length; row++)
{
Console.WriteLine(string.Join("", matrix[row]));
}
Console.WriteLine($"won: {string.Join(" ", playerPosition)}");
}
if (gameOverDead)
{
for (int row = 0; row < matrix.Length; row++)
{
Console.WriteLine(string.Join("", matrix[row]));
}
Console.WriteLine($"dead: {string.Join(" ", playerPosition)}");
}
}
private static void Move(char[][] matrix, char direction)
{
for (int row = 0; row < matrix.Length; row++)
{
for (int col = 0; col < matrix[0].Length; col++)
{
if (matrix[row][col] == 'B')
{
for (int r = Math.Max(0, row - 1); r <= Math.Min(row + 1, matrix.Length - 1); r++)
{
for (int c = Math.Max(0, col - 1); c <= Math.Min(col + 1, matrix[0].Length - 1); c++)
{
double distanceToBunny = Math.Sqrt(Math.Pow(row - r, 2) + Math.Pow(col - c, 2));
if (distanceToBunny == 1)
{
if (matrix[r][c] == 'P')
{
gameOverDead = true;
playerPosition = new int[2] { r, c };
matrix[r][c] = 'b';
}
else if (matrix[r][c] == '.')
{
matrix[r][c] = 'b';
}
}
}
}
}
}
}
for (int row = 0; row < matrix.Length; row++)
for (int col = 0; col < matrix[0].Length; col++)
if (matrix[row][col] == 'b')
matrix[row][col] = 'B';
if (direction == 'U')
{
for (int row = 0; row < matrix.Length; row++)
{
for (int col = 0; col < matrix[row].Length; col++)
{
if (matrix[row][col] == 'P')
{
var playerIndex = row - 1;
if (playerIndex < 0)
{
gameOverWon = true;
//playerPosition = new int[2] { row, col };
break;
}
matrix[row][col] = '.';
matrix[playerIndex][col] = 'P';
break;
}
}
}
}
if (direction == 'R')
{
for (int row = 0; row < matrix.Length; row++)
{
for (int col = 0; col < matrix[row].Length; col++)
{
if (matrix[row][col] == 'P')
{
var playerIndex = col + 1;
if (playerIndex > matrix[row].Length)
{
gameOverWon = true;
//playerPosition = new int[2] { row, col };
break;
}
matrix[row][col] = '.';
matrix[playerIndex][col] = 'P';
break;
}
}
}
}
if (direction == 'L')
{
for (int row = 0; row < matrix.Length; row++)
{
for (int col = 0; col < matrix[row].Length; col++)
{
if (matrix[row][col] == 'P')
{
var playerIndex = col - 1;
if (playerIndex < 0)
{
gameOverWon = true;
//playerPosition = new int[2] { row, col };
break;
}
matrix[row][col] = '.';
matrix[playerIndex][col] = 'P';
break;
}
}
}
}
if (direction == 'D')
{
for (int row = 0; row < matrix.Length; row++)
{
for (int col = 0; col < matrix[row].Length; col++)
{
if (matrix[row][col] == 'P')
{
var playerIndex = row + 1;
if (playerIndex > matrix.Length)
{
gameOverWon = true;
//playerPosition = new int[2] { row, col };
break;
}
matrix[row][col] = '.';
matrix[playerIndex][col] = 'P';
break;
}
}
}
}
}
}
}
|
Python
|
UTF-8
| 4,535 | 2.875 | 3 |
[] |
no_license
|
from flask import request # receiving data from requests
from flask import jsonify # Make a response (like dict)
from flask import make_response # Make a response (like dict)
from flask_restful import Resource # modules for fast creation of apis
from flask_apispec import marshal_with, doc, use_kwargs
from flask_apispec.views import MethodResource
from marshmallow import Schema, fields, validate
from model.enum import StatusMsg, ErrorMsg
from functions import coords_from_address, is_in_mkad, get_distance
from pathlib import Path
from typeguard import check_type
from icecream import ic
class ResponseSchema(Schema):
"""
Define a format for API response
"""
class DistanceSchema(Schema):
"""
Define a format for distance response
"""
text = fields.Str(default='Nothing')
value = fields.Integer(default=0)
status = fields.Str(validate=validate.OneOf(
[StatusMsg.FAIL, StatusMsg.OK]), required=True) # String that always is returned
message = fields.Str(validate=validate.OneOf([
'address is needed', 'address not found', 'address is iside of MKAD',
'originis address is not measurable', 'distance meassured correclty',
'an error occurred'
]), required=True) # String that always is returned
error = fields.Str(optional=True, validate=validate.OneOf([
ErrorMsg.MISSING_VALUES, ErrorMsg.INVALID_VALUE, ErrorMsg.INVALID_VALUE,
ErrorMsg.TYPE_ERROR, ErrorMsg.UNKNOWN_ERROR
]))
# distance = fields.Dict()
distance = fields.Nested(DistanceSchema)
class RequestSchema(Schema):
"""
Define a format for apis request
"""
address = fields.Str()
class MeassureDistance(MethodResource, Resource):
@doc(
description='Get distance from <i>addres</i> to <b>MDAK</b> taken as parammeter some address making use of google maps api',
tags=['Distance']
) # Adding a brief description for endpoint
@marshal_with(ResponseSchema) # Adding response schema
@use_kwargs(RequestSchema) # Adding request schema
def get(self):
"""
Function: get
Summary: HTTP GET methdo to meassure distance between a address and MKAD
Examples: distance from Madrid, Spain to MKAD
Parameters:
address (str): Address of origin
Returns: Status,
"""
address = request.args.get('address') # Get address (it does not fail if address is not sent)
try:
if not address: # Check if addres is sent
return make_response(jsonify(
status=StatusMsg.FAIL, error=ErrorMsg.MISSING_VALUES, message='address is needed'), 400)
check_type('address', address, str) # Check for address type
response = coords_from_address(address) # Get coords and place_id from address
if not response: # If not response something was wrong with the address
return make_response(jsonify(
status=StatusMsg.FAIL, error=ErrorMsg.INVALID_VALUE, message='address not found'), 400)
coords, place_id = response
if is_in_mkad(coords): # Check if the coords are inside of MKAD
return jsonify(status=StatusMsg.OK, message='address is iside of MKAD', distance=dict(
text='', value=0))
# Get distance from input address to MKAD
distance = get_distance(place_id)
if not distance: # If no distance are returned, the distance are not measurable
return make_response(jsonify(
status=StatusMsg.FAIL, error=ErrorMsg.INVALID_VALUE, message='originis address is not measurable'), 400)
with open(Path.cwd()/'distances.log', 'a') as f:
f.write(f'{distance}\n') # Write distance into .log file
return jsonify(
status=StatusMsg.OK, message='distance meassured correclty', distance=distance)
# It is raised for unexpected types (Will never raised given that get's
# parameter are always formated as strings)
except TypeError as e:
return make_response(jsonify(
status=StatusMsg.FAIL, error=ErrorMsg.TYPE_ERROR, message='an error occurred', log=str(e)), 400)
except Exception as e: # Any other error
return make_response(jsonify(
status=StatusMsg.FAIL, error=ErrorMsg.UNKNOWN_ERROR, message='an error occurred', log=str(e)), 500)
|
Markdown
|
UTF-8
| 754 | 2.78125 | 3 |
[] |
no_license
|
## Lab01-NumbersGame
###Author: Meggan Triplett
####Description
This is a C# console application that will ask a user to enter several numbers and will then take those numbers to run different calculations.
####Getting Started
Clone this repository to your local machine.
$ git clone [https://github.com/Megga-Miister/Lab01-NumbersGame.git]
To run the program from Visual Studio:
Select File -> Open -> Project/Solution
Next navigate to the location you cloned the Repository.
Double click on the Lab01-NumbersGame directory.
Then select and open Lab01NumbersGame.sln
####Visuals
Application Run Through Examples

Change Log
1.1: Added Program.cs files containing working app - 20 March 2019
|
Python
|
UTF-8
| 557 | 4.15625 | 4 |
[] |
no_license
|
"""
Write a program to swap odd and even bits in an integer with as
few instructions as possible. (e.g., bit 0 and bit 1 are swapped, bit
2 and bit 3 are swapped, and so on.)
- extract even bits and shift to right by 1 bit, extract odd bits and
shift to left by 1 bit, then merge the above two.
"""
def swapbits(n):
# assume 32-bit integers
evenbits = n & 0x55555555
oddbits = n & 0xAAAAAAAA
return (evenbits << 1) | (oddbits >> 1)
def test_swapbits():
assert swapbits(0b1010) == 0b0101
assert swapbits(0b10101010) == 0b01010101
|
Java
|
UTF-8
| 687 | 2.90625 | 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 funcao_01;
/**
*
* @author Celio_pc
*/
public class Funcao_01 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// novo objeto f que tem os metodos
Fatorial f = new Fatorial();
f.setValor(5);
// formula
System.out.print(f.getString());
// calculamdo fatorial do numero informado
System.out.println(f.getFatorial());
}
}
|
Java
|
UTF-8
| 1,762 | 2.3125 | 2 |
[] |
no_license
|
package com.spring.data.domain;
import java.util.Date;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Min;
import javax.validation.constraints.Past;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
public class BaseDept {
@NumberFormat(pattern = "No:#,###")
@Min(value = 20, message = "{Min.deptNo}")
private Integer deptNo;
@Length(min = 2, max = 5)
private String deptCode;
@Pattern(regexp = "\\d+公司", message = "[message]公司名称的值具有不正确的格式")
private String deptName;
@DateTimeFormat(pattern = "yyyy-MM-dd kk:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd kk:mm:ss", locale = "zh", timezone = "GMT+8")
@Past
private Date modifyDate;
@AssertTrue
private Boolean isRun;
public BaseDept(Integer deptNo, String deptCode) {
super();
this.deptNo = deptNo;
this.deptCode = deptCode;
}
public BaseDept() {
super();
}
public Integer getDeptNo() {
return deptNo;
}
public void setDeptNo(Integer deptNo) {
this.deptNo = deptNo;
}
public String getDeptCode() {
return deptCode;
}
public void setDeptCode(String deptCode) {
this.deptCode = deptCode;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
public Boolean getIsRun() {
return isRun;
}
public void setIsRun(Boolean isRun) {
this.isRun = isRun;
}
}
|
Python
|
UTF-8
| 2,170 | 3.03125 | 3 |
[] |
no_license
|
'''
Helper functions for plotting/analyzing control systems
from scipython.com
'''
import numpy as np
import matplotlib.pyplot as plt
# vector field
def vec_field(F):
x = np.linspace(-10, 10, 30)
y = np.linspace(-10, 10, 30)
xv, yv = np.meshgrid(x, y)
xx, yy = np.meshgrid(x, y)
for i in range(len(x)):
for j in range(len(y)):
val = F(x[i], y[j])
xx[i][j] = val[1]
yy[i][j] = val[0]
plt.quiver(xv, yv, xx, yy, zorder=1)
ax = plt.gca()
ax.add_artist(plt.Circle((0, 0), 6, zorder=2, fill=False))
ax.add_artist(plt.Circle((0, 0), 4, zorder=2, fill=False))
plt.show()
# Bivariable Function
def F(x, y):
pd = 5
pos = np.array([x, y]).T
in_ = np.array([0, -1]).T
out_ = np.array([0, 1]).T
k = .1
vec = -k/ang(in_, pos)*pos + k/ang(out_, pos)*pos + np.dot(R(-(90 + (90/5)*(p(x, y) - pd))), pos)
t = np.arctan2(*np.flip(vec, 0))
return np.array([np.cos(t), np.sin(t)]).T
# magnitude
def p(x, y): return (x**2 + y**2)**.5
# set u_list for each unicycle object based on adjacency matrix
def set_u_list(A, list_of_u):
r, c = np.shape(A)
for i in range(r):
for j in range(c):
if A[i][j] == 1:
list_of_u[i].u_list.append(list_of_u[j])
# rotation matrix
def R(t):
c, s = np.cos(t), np.sin(t)
return np.array(((c, -s), (s, c)))
# norm
def n2(x): return np.dot(x, x)**.5
# angle between 2 vectors
def ang(x, y):
if n2(x) == 0 or n2(y) == 0:
return 0
else:
return np.arccos(np.dot(x, y)/n2(x)/n2(y))
# arccos with correct sign
def arccos2(px, py, p2):
if py >= 0:
return np.arccos(px/p2)
else:
return 2*np.pi - np.arccos(px/p2)
# draw vector field
def vec_field_system(sys_init):
for i in range(-10, 10):
for j in range(-10, 10):
sys = sys_init(i, j)
traj = sys.run(2)
plt.plot(traj[0].T, traj[1].T)
plt.plot(traj[0][0], traj[1][0], '.')
ax = plt.gca()
plt.show()
|
JavaScript
|
UTF-8
| 1,312 | 2.75 | 3 |
[
"MIT",
"CC-BY-3.0"
] |
permissive
|
function deleteOffre(_id) {
console.log("id_offre= " + _id);
var id_offre = _id;
var libelle_food = null;
var taux = null;
var obj;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4) {
obj = JSON.parse(xhttp.responseText);
var i;
for (i = 0; i < obj.length; i++) {
if (obj[i].id_offre == _id) {
libelle_food = obj[i].libelle_food;
taux = "- "+obj[i].taux+" %";
deleteItem(id_offre, libelle_food, taux);
}
}
}
};
xhttp.open("GET", "http://41.226.11.252:1180/espritfood/ProjetAndroidSim/ListeOffreAdmin.php");
xhttp.send();
}
function deleteItem(id_offre,libelle_food, taux) {
if (libelle_food !== null && taux !== null) {
var xhttp2 = new XMLHttpRequest();
xhttp2.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
window.location.reload();
}
};
xhttp2.open("POST", "http://41.226.11.252:1180/espritfood/ProjetAndroidSim/SupprimerOffre.php", true);
xhttp2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp2.send("id_offre=" + id_offre + "&taux=" + taux + "&libelle_food=" + libelle_food);
} else {
console.log("Erreur offre non trouvée !");
}
}
|
PHP
|
UTF-8
| 1,407 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
<?php declare(strict_types = 1);
// Configuration
$config = array_replace_recursive(
[
'secretBcrypt' => '',
'saveDirName' => '/data/',
'maxScreenshotSize' => 2 * 1048576,
'screenshotMimeType' => 'image/png'
],
file_exists('./config.php') ? include_once('./config.php') : []
);
$baseUri = 'https://' . $_SERVER['HTTP_HOST'] . $config['saveDirName'];
$saveDir = __DIR__ . $config['saveDirName'];
$screenshot = $_FILES['screenshot'];
if (!password_verify($_POST['secret'], $config['secretBcrypt'])) {
http_response_code(401);
exit();
}
if (
// Make sure it is a successful single file upload
!isset($screenshot['error']) ||
is_array($screenshot['error']) ||
$screenshot['error'] !== UPLOAD_ERR_OK ||
// Verify size and mime type
$screenshot['size'] > $config['maxScreenshotSize'] ||
mime_content_type($screenshot['tmp_name']) !== $config['screenshotMimeType']
) {
http_response_code(422);
exit();
}
// Generate screenshot path
do {} while (file_exists($filename = bin2hex(random_bytes(12)) . '.png'));
// Create save directory and move screenshot to it
if (
(is_writable($saveDir) || mkdir($saveDir, 0755, true)) &&
move_uploaded_file($screenshot['tmp_name'], $saveDir . $filename)
) {
// Print uploaded screenshot url
exit($baseUri . $filename);
} else {
http_response_code(500);
exit();
}
|
Python
|
UTF-8
| 679 | 3.671875 | 4 |
[] |
no_license
|
"""
Dynamic programming solution to 0/1 Knapsack.
"""
# (value, weight) of each item
I = [(10, 5), (40, 4), (30, 6), (50, 3)]
MAX = 10 # max weight
# (value, weight) of each item
I = [(1, 1), (4, 3), (3, 2)]
MAX = 4 # max weight
# Create a table of [0, 1, .., Ith] X [0, 1, ..., MAX]
V = {}
V[0] = [0] * (MAX+1)
for i in range(1, len(I) + 1):
V[i] = [0] * (MAX+1)
for w in range(MAX + 1):
vj, wj = I[i - 1]
if w >= wj:
V[i][w] = max(V[i-1][w-wj] + vj, V[i-1][w])
else:
V[i][w] = V[i-1][w]
for i in range(len(I)+1):
print str(i) + ' | ',
for w in range(MAX+1):
print str(V[i][w]) + '\t',
print ""
|
JavaScript
|
UTF-8
| 6,322 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
var NoFocusPinnedTab = false;
var PinnedTabURL = "";
var NextCreateTriggersKeep = false;
var JustFixedLegacySettings = false;
function startup() {
chrome.storage.sync.get(
[
KOPT_NoFocusTab,
KOPT_Page,
KOPT_CustomURL,
KOPT_LegacyKey // Old
],
function(items) {
// Deal with legacy settings // Old
if(!JustFixedLegacySettings)
if(haveLegacySettings(items)) {
fixLegacySettings(items);
return;
}
updateSettings(items);
updateAllWindows();
}
);
}
function haveLegacySettings(items) {
if(items[KOPT_LegacyKey])
return true;
return false;
}
function fixLegacySettings(items) {
chrome.storage.sync.set(
{
[KOPT_Page]: PinnedTabPage_Custom,
[KOPT_CustomURL]: items[KOPT_LegacyKey],
[KOPT_LegacyKey]: "" // Old style, clear it out when we save. Should have fixed it to new style in actual elements via loadOptions().
},
function() {
JustFixedLegacySettings = true; // Shouldn't be needed, but just in case.
startup(); // Start over with updated settings.
}
);
}
function updateSettings(items) {
PinnedTabURL = getPinnedURL(items);
NoFocusPinnedTab = items[KOPT_NoFocusTab];
}
function getPinnedURL(items) {
var pageToPin = items[KOPT_Page];
if(pageToPin == PinnedTabPage_Default)
return PinnedTabURL_Default;
if(pageToPin == PinnedTabPage_BlankLight)
return PinnedTabURL_BlankLight;
if(pageToPin == PinnedTabPage_BlankDark)
return PinnedTabURL_BlankDark;
if(pageToPin == PinnedTabPage_Custom)
return items[KOPT_CustomURL];
return PinnedTabURL_Default;
}
function updateAllWindows() {
chrome.windows.getAll(
{
"populate": true,
"windowTypes": ["normal"]
},
function(windows){
for(var i = 0; i < windows.length; i++)
keepSpecialTabs(windows[i].id);
}
);
}
function keepSpecialTabs(targetWindowId) {
if(!targetWindowId)
return;
chrome.windows.get(
targetWindowId,
{
"populate": true,
"windowTypes": ["normal"]
},
function(targetWindow) {
if(!keepPinnedTab(targetWindow)) // Only check for the additional tab if we didn't just create a pinned one.
keepAdditionalTab(targetWindow);
}
);
}
function keepPinnedTab(targetWindow) {
if(PinnedTabURL == "")
return false;
if(targetWindow.type != "normal")
return false;
if(needPinnedTab(targetWindow)) {
createPinnedTab(targetWindow);
return true; // Created a new pinned tab
}
return false;
}
function needPinnedTab(targetWindow) {
if(targetWindow == undefined)
return false;
if(isOurTab(targetWindow.tabs[0])) // Our desired tab already exists.
return false;
return true;
}
function isOurTab(tab, urlToCheck = PinnedTabURL) {
if(!tab)
return false;
if(!tab.pinned)
return false;
if((tab.url.indexOf(urlToCheck) === -1) && (tab.pendingUrl.indexOf(urlToCheck) === -1))
return false;
return true;
}
function createPinnedTab(targetWindow) {
chrome.tabs.create(
{
"windowId": targetWindow.id,
"url": PinnedTabURL,
"index": 0,
"pinned": true,
"active": false
},
catchTabCreateError
);
}
function catchTabCreateError(tab) {
if(!tab) // Most likely, the window doesn't exist anymore (because last tab was closed).
var lastError = chrome.runtime.lastError; // check lastError so Chrome doesn't output anything to the console.
}
function keepAdditionalTab(targetWindow) {
if(targetWindow.type != "normal")
return;
if(needAdditionalTab(targetWindow))
createAdditionalTab(targetWindow);
}
function needAdditionalTab(targetWindow) {
if(targetWindow.tabs.length > 1)
return false;
return true;
}
function createAdditionalTab(targetWindow) {
chrome.tabs.create(
{
"windowId": targetWindow.id,
"active": true
},
catchTabCreateError
);
}
function windowCreated(newWindow) {
NextCreateTriggersKeep = true;
}
function tabActivated(activeInfo) {
if(NoFocusPinnedTab)
chrome.windows.get(
activeInfo.windowId,
{
"populate": true,
"windowTypes": ["normal"]
},
function(targetWindow) {
if(ourTabIsFocused(targetWindow))
unfocusPinnedTab(targetWindow);
}
);
}
function ourTabIsFocused(targetWindow) {
var firstTab = targetWindow.tabs[0];
if(!targetWindow)
return false;
if(!isOurTab(firstTab))
return false;
if(!firstTab.active)
return false;
return true;
}
function unfocusPinnedTab(targetWindow) {
if(targetWindow.tabs.length < 2)
return;
chrome.tabs.update(
targetWindow.tabs[1].id,
{
active: true
}
);
}
function tabCreated(tab) {
if(NextCreateTriggersKeep) {
NextCreateTriggersKeep = false;
keepSpecialTabs(tab.windowId);
}
}
function tabDetached(tabId, detachInfo) {
chrome.windows.get(
detachInfo.oldWindowId,
{
"populate": true
},
closeWindowOnDetachLastRealTab
);
}
function closeWindowOnDetachLastRealTab(detachedWindow) {
if(!detachedWindow)
return;
if(detachedWindow.tabs.length != 1)
return;
if(!isOurTab(detachedWindow.tabs[0]))
return;
chrome.windows.remove(detachedWindow.id);
}
function tabRemoved(tabId, removeInfo) {
if(removeInfo.isWindowClosing)
return;
keepSpecialTabs(removeInfo.windowId);
}
function storageChanged() {
chrome.storage.sync.get(
[
KOPT_NoFocusTab,
KOPT_Page,
KOPT_CustomURL,
KOPT_LegacyKey // Old
],
function(items) {
var oldPinnedURL = PinnedTabURL;
updateSettings(items);
if(oldPinnedURL == PinnedTabURL)
return;
convertAllWindows(oldPinnedURL, PinnedTabURL);
}
);
}
function convertAllWindows(oldPinnedURL, newPinnedURL) {
chrome.windows.getAll(
{
"populate": true,
"windowTypes": ["normal"]
},
function(windows){
for(var i = 0; i < windows.length; i++) {
convertWindow(windows[i], oldPinnedURL, newPinnedURL);
}
}
);
}
function convertWindow(targetWindow, oldPinnedURL, newPinnedURL) {
var firstTab = targetWindow.tabs[0];
if(!isOurTab(firstTab, oldPinnedURL))
return;
chrome.tabs.update(
firstTab.id,
{
"url": newPinnedURL
}
);
}
startup();
chrome.windows.onCreated.addListener(windowCreated);
chrome.tabs.onActivated.addListener(tabActivated);
chrome.tabs.onCreated.addListener(tabCreated);
chrome.tabs.onDetached.addListener(tabDetached);
chrome.tabs.onRemoved.addListener(tabRemoved);
chrome.storage.onChanged.addListener(storageChanged);
|
Java
|
UTF-8
| 1,313 | 3 | 3 |
[] |
no_license
|
package music;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class SongTest {
Song song1;
String name = "Boats";
String artist = "Jacob";
int songLength = 237;
@BeforeEach
void runBefore() {
song1 = new Song(name, artist, songLength);
}
@Test
void testSong() {
String name = "Airplanes";
String artist = "Jessica";
int songLength = 152;
Song song2 = new Song(name, artist, songLength);
assertEquals(name, song2.getName());
assertEquals(artist, song2.getArtist());
assertEquals(songLength, song2.getSongLength());
}
@Test
void testSetName() {
String name = "Cars";
song1.setName(name);
assertEquals(name, song1.getName());
}
@Test
void testSetArtist() {
String artist = "James";
song1.setArtist(artist);
assertEquals(artist, song1.getArtist());
}
@Test
void testGetName() {
assertEquals(name, song1.getName());
}
@Test
void testGetArtist() {
assertEquals(artist, song1.getArtist());
}
@Test
void testGetSongLength() {
assertEquals(songLength, song1.getSongLength());
}
}
|
Java
|
UTF-8
| 32,324 | 2.34375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package sagex.api;
/**
* Unofficial SageTV Generated File - Never Edit
* Generated Date/Time: 5/27/22 7:59 AM
* See Official Sage Documentation at <a href='http://download.sage.tv/api/sage/api/ChannelAPI.html'>ChannelAPI</a>
* This Generated API is not Affiliated with SageTV. It is user contributed.
*/
import sagex.UIContext;
public class ChannelAPI {
/**
Gets the descriptive name for this Channel. This is the longer text string.
Parameters:
Channel- the Channel Object
Returns:
the longer descriptive name for the specified Channel
*/
public static java.lang.String GetChannelDescription (Object Channel) {
Object o = sagex.SageAPI.call("GetChannelDescription", new Object[] {Channel});
if (o!=null) return (java.lang.String) o;
return null;
}
/**
* UI Context Aware Call<br>
Gets the descriptive name for this Channel. This is the longer text string.
Parameters:
Channel- the Channel Object
Returns:
the longer descriptive name for the specified Channel
*/
public static java.lang.String GetChannelDescription (UIContext _uicontext,Object Channel) {
Object o = sagex.SageAPI.call(_uicontext, "GetChannelDescription", new Object[] {Channel});
if (o!=null) return (java.lang.String) o;
return null;
}
/**
Gets the name for this Channel. This is the Channel's call sign.
Parameters:
Channel- the Channel Object
Returns:
the name (call sign) for the specified Channel
*/
public static java.lang.String GetChannelName (Object Channel) {
Object o = sagex.SageAPI.call("GetChannelName", new Object[] {Channel});
if (o!=null) return (java.lang.String) o;
return null;
}
/**
* UI Context Aware Call<br>
Gets the name for this Channel. This is the Channel's call sign.
Parameters:
Channel- the Channel Object
Returns:
the name (call sign) for the specified Channel
*/
public static java.lang.String GetChannelName (UIContext _uicontext,Object Channel) {
Object o = sagex.SageAPI.call(_uicontext, "GetChannelName", new Object[] {Channel});
if (o!=null) return (java.lang.String) o;
return null;
}
/**
Gets the name of the associated network for this Channel. This is a way of grouping kinds of Channels together.
Parameters:
Channel- the Channel Object
Returns:
the network name for the specified Channel
*/
public static java.lang.String GetChannelNetwork (Object Channel) {
Object o = sagex.SageAPI.call("GetChannelNetwork", new Object[] {Channel});
if (o!=null) return (java.lang.String) o;
return null;
}
/**
* UI Context Aware Call<br>
Gets the name of the associated network for this Channel. This is a way of grouping kinds of Channels together.
Parameters:
Channel- the Channel Object
Returns:
the network name for the specified Channel
*/
public static java.lang.String GetChannelNetwork (UIContext _uicontext,Object Channel) {
Object o = sagex.SageAPI.call(_uicontext, "GetChannelNetwork", new Object[] {Channel});
if (o!=null) return (java.lang.String) o;
return null;
}
/**
Gets the channel number to tune to for this Channel. SageTV will return the first channel number it finds for this Channel since there may be multiple ones.
Parameters:
Channel- the Channel Object
Returns:
a channel number associated with this Channel
*/
public static java.lang.String GetChannelNumber (Object Channel) {
Object o = sagex.SageAPI.call("GetChannelNumber", new Object[] {Channel});
if (o!=null) return (java.lang.String) o;
return null;
}
/**
* UI Context Aware Call<br>
Gets the channel number to tune to for this Channel. SageTV will return the first channel number it finds for this Channel since there may be multiple ones.
Parameters:
Channel- the Channel Object
Returns:
a channel number associated with this Channel
*/
public static java.lang.String GetChannelNumber (UIContext _uicontext,Object Channel) {
Object o = sagex.SageAPI.call(_uicontext, "GetChannelNumber", new Object[] {Channel});
if (o!=null) return (java.lang.String) o;
return null;
}
/**
Gets the channel number to tune to for this Channel on the specified lineup.
SageTV will return the first channel number it finds for this Channel on the lineup since there may be multiple ones.
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
Returns:
the channel number for the specified Channel on the specified Lineup
*/
public static java.lang.String GetChannelNumberForLineup (Object Channel, java.lang.String Lineup) {
Object o = sagex.SageAPI.call("GetChannelNumberForLineup", new Object[] {Channel,Lineup});
if (o!=null) return (java.lang.String) o;
return null;
}
/**
* UI Context Aware Call<br>
Gets the channel number to tune to for this Channel on the specified lineup.
SageTV will return the first channel number it finds for this Channel on the lineup since there may be multiple ones.
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
Returns:
the channel number for the specified Channel on the specified Lineup
*/
public static java.lang.String GetChannelNumberForLineup (UIContext _uicontext,Object Channel, java.lang.String Lineup) {
Object o = sagex.SageAPI.call(_uicontext, "GetChannelNumberForLineup", new Object[] {Channel,Lineup});
if (o!=null) return (java.lang.String) o;
return null;
}
/**
Gets the physical channel number to tune to for this Channel on the specified lineup.
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
Returns:
the physical channel number for the specified Channel on the specified Lineup
Since:
5.1
*/
public static java.lang.String GetPhysicalChannelNumberForLineup (Object Channel, java.lang.String Lineup) {
Object o = sagex.SageAPI.call("GetPhysicalChannelNumberForLineup", new Object[] {Channel,Lineup});
if (o!=null) return (java.lang.String) o;
return null;
}
/**
* UI Context Aware Call<br>
Gets the physical channel number to tune to for this Channel on the specified lineup.
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
Returns:
the physical channel number for the specified Channel on the specified Lineup
Since:
5.1
*/
public static java.lang.String GetPhysicalChannelNumberForLineup (UIContext _uicontext,Object Channel, java.lang.String Lineup) {
Object o = sagex.SageAPI.call(_uicontext, "GetPhysicalChannelNumberForLineup", new Object[] {Channel,Lineup});
if (o!=null) return (java.lang.String) o;
return null;
}
/**
Returns true if there is a configured lineup for which this channel is viewable.
Parameters:
Channel- the Channel object
Returns:
true if there is a configured lineup for which this channel is viewable.
*/
public static boolean IsChannelViewable (Object Channel) {
Object o = sagex.SageAPI.call("IsChannelViewable", new Object[] {Channel});
if (o!=null) return (Boolean) o;
return false;
}
/**
* UI Context Aware Call<br>
Returns true if there is a configured lineup for which this channel is viewable.
Parameters:
Channel- the Channel object
Returns:
true if there is a configured lineup for which this channel is viewable.
*/
public static boolean IsChannelViewable (UIContext _uicontext,Object Channel) {
Object o = sagex.SageAPI.call(_uicontext, "IsChannelViewable", new Object[] {Channel});
if (o!=null) return (Boolean) o;
return false;
}
/**
Returns true if this Channel is viewable on the specified Lineup
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
Returns:
true if this Channel is viewable on the specified Lineup
*/
public static boolean IsChannelViewableOnLineup (Object Channel, java.lang.String Lineup) {
Object o = sagex.SageAPI.call("IsChannelViewableOnLineup", new Object[] {Channel,Lineup});
if (o!=null) return (Boolean) o;
return false;
}
/**
* UI Context Aware Call<br>
Returns true if this Channel is viewable on the specified Lineup
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
Returns:
true if this Channel is viewable on the specified Lineup
*/
public static boolean IsChannelViewableOnLineup (UIContext _uicontext,Object Channel, java.lang.String Lineup) {
Object o = sagex.SageAPI.call(_uicontext, "IsChannelViewableOnLineup", new Object[] {Channel,Lineup});
if (o!=null) return (Boolean) o;
return false;
}
/**
Returns true if this Channel is viewable on the specified Lineup on the specified channel number
Parameters:
Channel- the Channel object
ChannelNumber- the channel number to check
Lineup- the name of the Lineup
Returns:
true if this Channel is viewable on the specified Lineup on the specified channel number
*/
public static boolean IsChannelViewableOnNumberOnLineup (Object Channel, java.lang.String ChannelNumber, java.lang.String Lineup) {
Object o = sagex.SageAPI.call("IsChannelViewableOnNumberOnLineup", new Object[] {Channel,ChannelNumber,Lineup});
if (o!=null) return (Boolean) o;
return false;
}
/**
* UI Context Aware Call<br>
Returns true if this Channel is viewable on the specified Lineup on the specified channel number
Parameters:
Channel- the Channel object
ChannelNumber- the channel number to check
Lineup- the name of the Lineup
Returns:
true if this Channel is viewable on the specified Lineup on the specified channel number
*/
public static boolean IsChannelViewableOnNumberOnLineup (UIContext _uicontext,Object Channel, java.lang.String ChannelNumber, java.lang.String Lineup) {
Object o = sagex.SageAPI.call(_uicontext, "IsChannelViewableOnNumberOnLineup", new Object[] {Channel,ChannelNumber,Lineup});
if (o!=null) return (Boolean) o;
return false;
}
/**
Gets the channel numbers which can be used to tune this Channel on the specified lineup.
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
Returns:
the channel numbers for the specified Channel on the specified Lineup
*/
public static java.lang.String[] GetChannelNumbersForLineup (Object Channel, java.lang.String Lineup) {
return (java.lang.String[]) sagex.SageAPI.call("GetChannelNumbersForLineup", new Object[] {Channel,Lineup});
}
/**
* UI Context Aware Call<br>
Gets the channel numbers which can be used to tune this Channel on the specified lineup.
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
Returns:
the channel numbers for the specified Channel on the specified Lineup
*/
public static java.lang.String[] GetChannelNumbersForLineup (UIContext _uicontext,Object Channel, java.lang.String Lineup) {
return (java.lang.String[]) sagex.SageAPI.call(_uicontext, "GetChannelNumbersForLineup", new Object[] {Channel,Lineup});
}
/**
Clears any associated channel mappings that were created for this Channel on the specified Lineup
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
*/
public static void ClearChannelMappingOnLineup (Object Channel, java.lang.String Lineup) {
sagex.SageAPI.call("ClearChannelMappingOnLineup", new Object[] {Channel,Lineup});
}
/**
* UI Context Aware Call<br>
Clears any associated channel mappings that were created for this Channel on the specified Lineup
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
*/
public static void ClearChannelMappingOnLineup (UIContext _uicontext,Object Channel, java.lang.String Lineup) {
sagex.SageAPI.call(_uicontext, "ClearChannelMappingOnLineup", new Object[] {Channel,Lineup});
}
/**
Returns true if the user has remapped this Channel to a different number than it's default on the specified Lineup
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
Returns:
true if the user has remapped this Channel to a different number than it's default on the specified Lineup
*/
public static boolean IsChannelRemappedOnLineup (Object Channel, java.lang.String Lineup) {
Object o = sagex.SageAPI.call("IsChannelRemappedOnLineup", new Object[] {Channel,Lineup});
if (o!=null) return (Boolean) o;
return false;
}
/**
* UI Context Aware Call<br>
Returns true if the user has remapped this Channel to a different number than it's default on the specified Lineup
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
Returns:
true if the user has remapped this Channel to a different number than it's default on the specified Lineup
*/
public static boolean IsChannelRemappedOnLineup (UIContext _uicontext,Object Channel, java.lang.String Lineup) {
Object o = sagex.SageAPI.call(_uicontext, "IsChannelRemappedOnLineup", new Object[] {Channel,Lineup});
if (o!=null) return (Boolean) o;
return false;
}
/**
Maps a channel on a lineup to a new channel number.
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
NewNumber- the new channel number to use for this Channel
*/
public static void SetChannelMappingForLineup (Object Channel, java.lang.String Lineup, java.lang.String NewNumber) {
sagex.SageAPI.call("SetChannelMappingForLineup", new Object[] {Channel,Lineup,NewNumber});
}
/**
* UI Context Aware Call<br>
Maps a channel on a lineup to a new channel number.
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
NewNumber- the new channel number to use for this Channel
*/
public static void SetChannelMappingForLineup (UIContext _uicontext,Object Channel, java.lang.String Lineup, java.lang.String NewNumber) {
sagex.SageAPI.call(_uicontext, "SetChannelMappingForLineup", new Object[] {Channel,Lineup,NewNumber});
}
/**
Maps a channel on a lineup to a new channel number(s).
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
NewNumbers- the new channel numbers to use for this Channel
Since:
6.4.3
*/
public static void SetChannelMappingsForLineup (Object Channel, java.lang.String Lineup, java.lang.String[] NewNumbers) {
sagex.SageAPI.call("SetChannelMappingsForLineup", new Object[] {Channel,Lineup,NewNumbers});
}
/**
* UI Context Aware Call<br>
Maps a channel on a lineup to a new channel number(s).
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
NewNumbers- the new channel numbers to use for this Channel
Since:
6.4.3
*/
public static void SetChannelMappingsForLineup (UIContext _uicontext,Object Channel, java.lang.String Lineup, java.lang.String[] NewNumbers) {
sagex.SageAPI.call(_uicontext, "SetChannelMappingsForLineup", new Object[] {Channel,Lineup,NewNumbers});
}
/**
Clears any associated physical channel mappings that were created for this Channel on the specified Lineup
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
Since:
5.1
*/
public static void ClearPhysicalChannelMappingsOnLineup (Object Channel, java.lang.String Lineup) {
sagex.SageAPI.call("ClearPhysicalChannelMappingsOnLineup", new Object[] {Channel,Lineup});
}
/**
* UI Context Aware Call<br>
Clears any associated physical channel mappings that were created for this Channel on the specified Lineup
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
Since:
5.1
*/
public static void ClearPhysicalChannelMappingsOnLineup (UIContext _uicontext,Object Channel, java.lang.String Lineup) {
sagex.SageAPI.call(_uicontext, "ClearPhysicalChannelMappingsOnLineup", new Object[] {Channel,Lineup});
}
/**
Returns true if the user has remapped this physical Channel to a different physical number than it's default on the specified Lineup
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
Returns:
true if the user has remapped this physical Channel to a different number than it's default on the specified Lineup
Since:
5.1
*/
public static boolean IsPhysicalChannelRemappedOnLineup (Object Channel, java.lang.String Lineup) {
Object o = sagex.SageAPI.call("IsPhysicalChannelRemappedOnLineup", new Object[] {Channel,Lineup});
if (o!=null) return (Boolean) o;
return false;
}
/**
* UI Context Aware Call<br>
Returns true if the user has remapped this physical Channel to a different physical number than it's default on the specified Lineup
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
Returns:
true if the user has remapped this physical Channel to a different number than it's default on the specified Lineup
Since:
5.1
*/
public static boolean IsPhysicalChannelRemappedOnLineup (UIContext _uicontext,Object Channel, java.lang.String Lineup) {
Object o = sagex.SageAPI.call(_uicontext, "IsPhysicalChannelRemappedOnLineup", new Object[] {Channel,Lineup});
if (o!=null) return (Boolean) o;
return false;
}
/**
Maps a Channel on a lineup to a new physical channel number.
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
NewNumber- the new phyical channel number to use for this Channel
Since:
5.1
*/
public static void SetPhysicalChannelMappingForLineup (Object Channel, java.lang.String Lineup, java.lang.String NewNumber) {
sagex.SageAPI.call("SetPhysicalChannelMappingForLineup", new Object[] {Channel,Lineup,NewNumber});
}
/**
* UI Context Aware Call<br>
Maps a Channel on a lineup to a new physical channel number.
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
NewNumber- the new phyical channel number to use for this Channel
Since:
5.1
*/
public static void SetPhysicalChannelMappingForLineup (UIContext _uicontext,Object Channel, java.lang.String Lineup, java.lang.String NewNumber) {
sagex.SageAPI.call(_uicontext, "SetPhysicalChannelMappingForLineup", new Object[] {Channel,Lineup,NewNumber});
}
/**
Returns an ID which can be used withGetChannelForStationID()
for doing keyed lookups of Channel objects
Parameters:
Channel- the Channel object
Returns:
the station ID for the specified Channel
*/
public static int GetStationID (Object Channel) {
Object o = sagex.SageAPI.call("GetStationID", new Object[] {Channel});
if (o!=null) return (Integer) o;
return 0;
}
/**
* UI Context Aware Call<br>
Returns an ID which can be used withGetChannelForStationID()
for doing keyed lookups of Channel objects
Parameters:
Channel- the Channel object
Returns:
the station ID for the specified Channel
*/
public static int GetStationID (UIContext _uicontext,Object Channel) {
Object o = sagex.SageAPI.call(_uicontext, "GetStationID", new Object[] {Channel});
if (o!=null) return (Integer) o;
return 0;
}
/**
Gets the logo image for the specified Channel if one exists
Parameters:
Channel- the Channel object
Returns:
the logo image for the Channel
*/
public static Object GetChannelLogo (Object Channel) {
Object o = sagex.SageAPI.call("GetChannelLogo", new Object[] {Channel});
if (o!=null) return (Object) o;
return null;
}
/**
* UI Context Aware Call<br>
Gets the logo image for the specified Channel if one exists
Parameters:
Channel- the Channel object
Returns:
the logo image for the Channel
*/
public static Object GetChannelLogo (UIContext _uicontext,Object Channel) {
Object o = sagex.SageAPI.call(_uicontext, "GetChannelLogo", new Object[] {Channel});
if (o!=null) return (Object) o;
return null;
}
/**
Returns a Channel logo for the requested Channel if one exists. This can provide more detailed requests then the single argument GetChannelLogo call.
Parameters:
Channel- the Channel object
Type- the type of image, can be one of "Small", "Med" or "Large" (all logos have all sizes available, w/ the exception of user-supplied logos)
Index- the 0-based index of the image to retrieve when multiple images exist for a given Type (there are only ever 0, 1 or 2 logos for a channel)
Fallback- should be true if an alternate image is allowed (this enables checking user-supplied logos first, as well as falling back to the primary logo if a secondary one is requested but does not exist)
Returns:
a MetaImage corresponding to the requested image, or null if no image matching the requested parameters is found or an invalid Type is specified
Since:
7.1
*/
public static Object GetChannelLogo (Object Channel, java.lang.String Type, int Index, boolean Fallback) {
Object o = sagex.SageAPI.call("GetChannelLogo", new Object[] {Channel,Type,Index,Fallback});
if (o!=null) return (Object) o;
return null;
}
/**
* UI Context Aware Call<br>
Returns a Channel logo for the requested Channel if one exists. This can provide more detailed requests then the single argument GetChannelLogo call.
Parameters:
Channel- the Channel object
Type- the type of image, can be one of "Small", "Med" or "Large" (all logos have all sizes available, w/ the exception of user-supplied logos)
Index- the 0-based index of the image to retrieve when multiple images exist for a given Type (there are only ever 0, 1 or 2 logos for a channel)
Fallback- should be true if an alternate image is allowed (this enables checking user-supplied logos first, as well as falling back to the primary logo if a secondary one is requested but does not exist)
Returns:
a MetaImage corresponding to the requested image, or null if no image matching the requested parameters is found or an invalid Type is specified
Since:
7.1
*/
public static Object GetChannelLogo (UIContext _uicontext,Object Channel, java.lang.String Type, int Index, boolean Fallback) {
Object o = sagex.SageAPI.call(_uicontext, "GetChannelLogo", new Object[] {Channel,Type,Index,Fallback});
if (o!=null) return (Object) o;
return null;
}
/**
Returns true if the argument is a Channel object. Automatic type conversion is NOT done in this call.
Parameters:
Channel- the object to test
Returns:
true if the argument is a Channel object
*/
public static boolean IsChannelObject (Object Channel) {
Object o = sagex.SageAPI.call("IsChannelObject", new Object[] {Channel});
if (o!=null) return (Boolean) o;
return false;
}
/**
* UI Context Aware Call<br>
Returns true if the argument is a Channel object. Automatic type conversion is NOT done in this call.
Parameters:
Channel- the object to test
Returns:
true if the argument is a Channel object
*/
public static boolean IsChannelObject (UIContext _uicontext,Object Channel) {
Object o = sagex.SageAPI.call(_uicontext, "IsChannelObject", new Object[] {Channel});
if (o!=null) return (Boolean) o;
return false;
}
/**
Sets whether or not the specified Channel is viewable on the specified number on the specified Lineup
Parameters:
Channel- the Channel object
ChannelNumber- the channel number to set the viewability state for
Lineup- the name of the Lineup
Viewable- true if is viewable, false if it is not
*/
public static void SetChannelViewabilityForChannelNumberOnLineup (Object Channel, java.lang.String ChannelNumber, java.lang.String Lineup, boolean Viewable) {
sagex.SageAPI.call("SetChannelViewabilityForChannelNumberOnLineup", new Object[] {Channel,ChannelNumber,Lineup,Viewable});
}
/**
* UI Context Aware Call<br>
Sets whether or not the specified Channel is viewable on the specified number on the specified Lineup
Parameters:
Channel- the Channel object
ChannelNumber- the channel number to set the viewability state for
Lineup- the name of the Lineup
Viewable- true if is viewable, false if it is not
*/
public static void SetChannelViewabilityForChannelNumberOnLineup (UIContext _uicontext,Object Channel, java.lang.String ChannelNumber, java.lang.String Lineup, boolean Viewable) {
sagex.SageAPI.call(_uicontext, "SetChannelViewabilityForChannelNumberOnLineup", new Object[] {Channel,ChannelNumber,Lineup,Viewable});
}
/**
Sets whether or not the specified Channel is viewable on the specified Lineup. This affects all channel numbers it appears on.
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
Viewable- true if is viewable, false if it is not
*/
public static void SetChannelViewabilityForChannelOnLineup (Object Channel, java.lang.String Lineup, boolean Viewable) {
sagex.SageAPI.call("SetChannelViewabilityForChannelOnLineup", new Object[] {Channel,Lineup,Viewable});
}
/**
* UI Context Aware Call<br>
Sets whether or not the specified Channel is viewable on the specified Lineup. This affects all channel numbers it appears on.
Parameters:
Channel- the Channel object
Lineup- the name of the Lineup
Viewable- true if is viewable, false if it is not
*/
public static void SetChannelViewabilityForChannelOnLineup (UIContext _uicontext,Object Channel, java.lang.String Lineup, boolean Viewable) {
sagex.SageAPI.call(_uicontext, "SetChannelViewabilityForChannelOnLineup", new Object[] {Channel,Lineup,Viewable});
}
/**
Returns the Channel object that has the corresponding station ID. The station ID is retrieved usingGetStationID()
Parameters:
StationID- the station ID to look up
Returns:
the Channel with the specified station ID
*/
public static Object GetChannelForStationID (int StationID) {
Object o = sagex.SageAPI.call("GetChannelForStationID", new Object[] {StationID});
if (o!=null) return (Object) o;
return null;
}
/**
* UI Context Aware Call<br>
Returns the Channel object that has the corresponding station ID. The station ID is retrieved usingGetStationID()
Parameters:
StationID- the station ID to look up
Returns:
the Channel with the specified station ID
*/
public static Object GetChannelForStationID (UIContext _uicontext,int StationID) {
Object o = sagex.SageAPI.call(_uicontext, "GetChannelForStationID", new Object[] {StationID});
if (o!=null) return (Object) o;
return null;
}
/**
Adds a new Channel to the database. The CallSign should not match that of any other channel; but this rule is not enforced.
The StationID is what is used as the unique key to identify a station. Be sure that if you're creating new station IDs they do not conflict with existing ones.
The safest way to pick a station ID (if you need to at random) is to make it less than 10000 and ensure that no channel already exists with that station ID.
Parameters:
CallSign- the 'Name' to assign to the new Channel
Name- the 'Description' to assign to the new Channel
Network- the 'Network' that the Channel is part of (can be "")
StationID- the unique ID to give to this Channel
Returns:
the newly created Channel object, if the station ID is already in use it will return the existing Channel object, but updated with the passed in values
*/
public static Object AddChannel (java.lang.String CallSign, java.lang.String Name, java.lang.String Network, int StationID) {
Object o = sagex.SageAPI.call("AddChannel", new Object[] {CallSign,Name,Network,StationID});
if (o!=null) return (Object) o;
return null;
}
/**
* UI Context Aware Call<br>
Adds a new Channel to the database. The CallSign should not match that of any other channel; but this rule is not enforced.
The StationID is what is used as the unique key to identify a station. Be sure that if you're creating new station IDs they do not conflict with existing ones.
The safest way to pick a station ID (if you need to at random) is to make it less than 10000 and ensure that no channel already exists with that station ID.
Parameters:
CallSign- the 'Name' to assign to the new Channel
Name- the 'Description' to assign to the new Channel
Network- the 'Network' that the Channel is part of (can be "")
StationID- the unique ID to give to this Channel
Returns:
the newly created Channel object, if the station ID is already in use it will return the existing Channel object, but updated with the passed in values
*/
public static Object AddChannel (UIContext _uicontext,java.lang.String CallSign, java.lang.String Name, java.lang.String Network, int StationID) {
Object o = sagex.SageAPI.call(_uicontext, "AddChannel", new Object[] {CallSign,Name,Network,StationID});
if (o!=null) return (Object) o;
return null;
}
/**
Returns all of the Channels that are defined in the system
Returns:
all of the Channel objects that are defined in the system
*/
public static Object[] GetAllChannels () {
return (Object[]) sagex.SageAPI.call("GetAllChannels", (Object[])null);
}
/**
* UI Context Aware Call<br>
Returns all of the Channels that are defined in the system
Returns:
all of the Channel objects that are defined in the system
*/
public static Object[] GetAllChannels (UIContext _uicontext) {
return (Object[]) sagex.SageAPI.call(_uicontext, "GetAllChannels", (Object[])null);
}
/**
Returns a count of logos for this channel. This will either be 0, 1 or 2. This does NOT include user-supplied channel logos.
Since all channel logos have all types, this does not require a type argument.
Parameters:
Channel- the Channel object
Returns:
the number of logos for the specified Channel (does NOT include user-supplied logos)
Since:
7.1
*/
public static int GetChannelLogoCount (Object Channel) {
Object o = sagex.SageAPI.call("GetChannelLogoCount", new Object[] {Channel});
if (o!=null) return (Integer) o;
return 0;
}
/**
* UI Context Aware Call<br>
Returns a count of logos for this channel. This will either be 0, 1 or 2. This does NOT include user-supplied channel logos.
Since all channel logos have all types, this does not require a type argument.
Parameters:
Channel- the Channel object
Returns:
the number of logos for the specified Channel (does NOT include user-supplied logos)
Since:
7.1
*/
public static int GetChannelLogoCount (UIContext _uicontext,Object Channel) {
Object o = sagex.SageAPI.call(_uicontext, "GetChannelLogoCount", new Object[] {Channel});
if (o!=null) return (Integer) o;
return 0;
}
/**
Gets the URL of the logo image for the specified Channel if one exists
Parameters:
Channel- the Channel object
Returns:
the URL of the logo image for the Channel
Since:
8.0
*/
public static java.lang.String GetChannelLogoURL (Object Channel) {
Object o = sagex.SageAPI.call("GetChannelLogoURL", new Object[] {Channel});
if (o!=null) return (java.lang.String) o;
return null;
}
/**
* UI Context Aware Call<br>
Gets the URL of the logo image for the specified Channel if one exists
Parameters:
Channel- the Channel object
Returns:
the URL of the logo image for the Channel
Since:
8.0
*/
public static java.lang.String GetChannelLogoURL (UIContext _uicontext,Object Channel) {
Object o = sagex.SageAPI.call(_uicontext, "GetChannelLogoURL", new Object[] {Channel});
if (o!=null) return (java.lang.String) o;
return null;
}
/**
Returns a Channel logo URL for the requested Channel if one exists. This can provide more detailed requests then the single argument GetChannelLogoURL call.
Parameters:
Channel- the Channel object
Type- the type of image, can be one of "Small", "Med" or "Large" (all logos have all sizes available, w/ the exception of user-supplied logos)
Index- the 0-based index of the image to retrieve when multiple images exist for a given Type (there are only ever 0, 1 or 2 logos for a channel)
Fallback- should be true if an alternate image is allowed (this enables checking user-supplied logos first, as well as falling back to the primary logo if a secondary one is requested but does not exist)
Returns:
a URL corresponding to the requested image, or null if no image matching the requested parameters is found or an invalid Type is specified
Since:
8.0
*/
public static java.lang.String GetChannelLogoURL (Object Channel, java.lang.String Type, int Index, boolean Fallback) {
Object o = sagex.SageAPI.call("GetChannelLogoURL", new Object[] {Channel,Type,Index,Fallback});
if (o!=null) return (java.lang.String) o;
return null;
}
/**
* UI Context Aware Call<br>
Returns a Channel logo URL for the requested Channel if one exists. This can provide more detailed requests then the single argument GetChannelLogoURL call.
Parameters:
Channel- the Channel object
Type- the type of image, can be one of "Small", "Med" or "Large" (all logos have all sizes available, w/ the exception of user-supplied logos)
Index- the 0-based index of the image to retrieve when multiple images exist for a given Type (there are only ever 0, 1 or 2 logos for a channel)
Fallback- should be true if an alternate image is allowed (this enables checking user-supplied logos first, as well as falling back to the primary logo if a secondary one is requested but does not exist)
Returns:
a URL corresponding to the requested image, or null if no image matching the requested parameters is found or an invalid Type is specified
Since:
8.0
*/
public static java.lang.String GetChannelLogoURL (UIContext _uicontext,Object Channel, java.lang.String Type, int Index, boolean Fallback) {
Object o = sagex.SageAPI.call(_uicontext, "GetChannelLogoURL", new Object[] {Channel,Type,Index,Fallback});
if (o!=null) return (java.lang.String) o;
return null;
}
}
|
Markdown
|
UTF-8
| 11,350 | 3.765625 | 4 |
[] |
no_license
|
## 重学 React
[参考资料: Reac.js 小书 by 胡子大哈](http://huziketang.mangojuice.top/books/react/)
组件化可以帮助我们解决前端结构的复用性问题,整个页面可以由这样的不同的组件组合、嵌套构成。
### 01 使用 React
1. 下载 `react`, `react-dom`
2. 导入 `react`, `react-dom`
`react` 编写 React 组件需要,`react-dom` 将 React 组件渲染到页面上
#### JSX
类似 HTML 的语法,直接写在 React 组件中。包含 JavaScript 的对象树。
JSX 就是 JavaScript 对象。
#### render
React 中的一切皆是组件。组件一般都需要继承 Component,创建 render 方法,render 方法必须返回一个 JSX 对象。
render 方法返回的 JSX 只能有一个根元素。
**可以插入表达式**
可以使用 `{}` 包裹起来,表达式返回的结果就会渲染到页面上。可以是变量、表达式计算,函数执行,表达式可以插入在标签内部,也可以在标签的属性上使用
> Note
在 JavaScript 中,class 是一个保留字,所以无法在 React 中使用,要使用 className
**条件返回**
可以使用表达式,也就代表可以根据表达式的值,返回不同的内容。
如果在表达式中返回 null,那么什么内容都不会展示。
### 02 组件嵌套、组合与组件树
自定义的组件都需要用大写,普通的 HTML 标签都要用小写。
### 03 事件监听
给需要监听的组件添加属性,React 已经帮助我们封装好了 on* 的属性,也不用担心兼容问题。on* 的事件监听只能用于 HTML 标签上面,不能在组件标签上面使用。事件监听函数会传入一个 event 对象。
**事件中的 this**
事件中的 this 不指向实例本身,而是 undefined。如果需要指向组件,需要在调用时进行绑定
``` jsx
<img
onClick={this.handleClickOnImage.bind(this)}
src={logo}
className="App-logo"
alt="logo"
/>
```
### 组件中的 state 和 setState
一个组件的显示形态是可以由它数据状态和配置参数决定的。一个组件可以拥有自己的状态,状态可以是变化的。在 React 中称之为 state
setState 由 Component 提供,调用这个函数时,会更新组件的状态,并且重新调用 render 方法,然后把 render 方法渲染的最新内容显示在页面上。不能直接使用 `this.state = xx`,如果这样修改,React 就不会知道 state 进行了修改。setState 接收一个对象或者函数作为参数。
- 使用对象作为参数时,只需要传入需要更改的部分,不用传入整个对象
- 使用函数作为参数时,函数参数需要传入前一个 state,返回一个新的 state,一个操作中,多次调用 setState 更新,组件只会渲染一次,React 会把消息对象的 setState 进行合并,然后再渲染组件。不用担心 setState 带来的性能问题。
### 组件中的 props
props 是组件的属性,让组件可以配置,在其他的地方使用。每个组件都可以接受一个 props 参数,它是一个对象,包含了对这个组件的配置。
在组件的内部使用 `this.props.name` 来使用组件。在组件的外部,直接在标签上面设置属性名,所有的属性都会当作 props 对象的键值。
组件的 props 可以是任何类型的,字符串,数字,对象,数组,甚至是函数。
设置默认的 props 可以在组件内声明 defaultProps,也可以在使用组件的时候设置 props。一旦 props 传入进来,就不能修改。如果修改,可以通过设置函数 props,在函数 props 中修改组件的 state 或者通知父组件修改。
### state vs props
**State 的主要作用是用于组件保存、控制、修改自己的可变状态。在组件内部初始化,可以被组件自身修改,而外部不能访问也不能修改。State 是一个局部的,只能被自身控制的数据源。**
**Props 的作用是让组件的父组件传递参数进行配置。是外部传递进来的配置参数,组件内部无法修改,除非外部组件传入新的 props,否则组件的 props 不变。**
拥有 state 的组件称之为 stateful 组件,没有state 的组件称之为 stateless 组件。状态会带来管理的复杂性,所以要尽量多的使用无状态组件。
### 渲染列表数据
如果在 {} 中放入一个数组,React 会帮你把数组里面的元素一个个罗列出来。
所以可以使用 map 渲染数据列表。使用时需要添加一个 key,为元素的唯一标识符。
### 状态提升
将这种组件之间共享的状态交给组件最近的公共父节点保管,这种方式称为状态提升。
当某个状态被多个组件依赖或者影响的时候,就把该状态提升到这些组件的最近公共父组件中去管理,用 props 传递数据或者函数来管理这种依赖或着影响的行为。
使用 props 传递函数的例子:
App handleDelete(index)
List<Comment> onDeleteComment(index) handleDeleteComment
Comment onClick={this.handleClick.bind(this)} handleDelete
### 生命周期
React.js 将组件渲染,并且构造 DOM 元素然后塞入页面的过程称为组件的挂载
**React 挂载阶段的生命周期:**
-> constructor()
-> componentWillMount()
-> render()
// 然后构造 DOM 元素插入页面
-> componentDidMount()
// ...
// 即将从页面中删除
-> componentWillUnmount()
// 从页面中删除
state 的初始化工作放在 constructor 里面,在 componentWillMount 里面进行组件的启动工作,如发起网络请求,设置定时器,组件销毁的时候需要将定时器清理掉,在 componentWillUnmount 里面处理。
依赖于 DOM 的工作需要放在 componentDidMount 中里面进行。
**更新阶段的生命周期**
shouldComponentUpdate(nextProps, nextState) 如果返回 false 不更新
componentWillReceiveProps(nextProps) 组件从父组件接收到新的 props 前调用
componentWillUpdate():组件开始重新渲染之前调用。
componentDidUpdate():组件重新渲染并且把更改变更到真实的 DOM 以后调用。
### ref 和 React 中的 DOM 操作
在 React 中基本上不需要和 DOM 直接打交道,但又几种情况需要使用 DOM,如:进入页面后自动聚焦,需要使用 `input.focus()`,如果想动态获取 DOM 元素的尺寸
React 提供了 ref 属性来帮我们获取已挂载元素的 DOM 结点,可以给某个 jsx 元素加上 ref 属性。
ref 属性是一个函数,在函数中可以把 DOM 元素设置为组件实例的一个属性,之后就可以获取 DOM 元素。
组件也可以使用 ref,但不推荐这么做
```js
<input ref={(input) => this.input = input} />
this.input.focus()
```
### props.children 和容器类组件
使用自定义组件时,所有嵌套在组件中的 jsx 结构都可以通过组件的 props.children 属性获得。
### propTypes 和组件参数验证
在使用 React 构建大型应用时,推荐使用 propTypes 构建,可以给组件的配置添加上类型验证,如果传入的类型不对,浏览器会报错,使用 js 编写不会报错,如果使用 TypeScript 会报错。
### 命名建议
组件的私有方法使用 `_` 开头,所有的监听方法使用 `handle` 开头,把监听方法传递给组件的时候,属性名用 `on`。
组件的编写顺序:
- static 开头的类属性,如 defaultProps、propTypes。
- 构造函数,constructor。
- getter/setter(还不了解的同学可以暂时忽略)。
- 组件生命周期。
- _ 开头的私有方法。
- 事件监听方法,handle*。
- render*开头的方法,有时候 render() 方法里面的内容会分开到不同函数里面进行,这些函数都以 render* 开头。
- render() 方法。
### 高阶组件
高阶组件就是一个函数,传给它一个组件,它返回一个新的组件。高阶组件就是为了代码复用,组件可能存在着某些相同的逻辑,把这些逻辑抽离出来,放到高阶组件中复用,高阶组件内部的包装组件和被包装组件之间通过 props 传递数据。
就是设计模式中的装饰者模式,通过组合的方法达到很高的灵活程度。
### Context
Context 相当于组件树上的某颗子树的全局变量。context 至少能往下传递,不能往上传递。
使用 context 时,需要在组件中声明 `childContextTypes`,设置 context 的类型,然后使用 `getChildContext` 获取返回的对象。然后在组件中使用 `this.context.some` 使用
context 中的数据是可以随意修改的
### Redux 的原理
Redux 与 React-redux 并不是一个东西。Redux 是一种架构模式,不关注使用什么库,可以应用到 React Vue,甚至是 jQuery。
为什么需要 Redux?模块/组件之间需要共享数据,但是数据可能被任意修改导致不可预料的结果。
设置一条规则:模块组件之间可以共享数据,也可以更改数据,但是要提前月订,这个数据不能直接修改,只能执行某些允许的修改,而且必须显式的通知调用修改。
为此,Redux 中有 `dispatch` 负责数据的修改。
```js
function dispatch (action) {
switch (action.type) {
case 'UPDATE_TITLE_TEXT':
appState.title.text = action.text
break
case 'UPDATE_TITLE_COLOR':
appState.title.color = action.color
break
default:
break
}
}
```
所有的数据操作必须通过 dispatch 函数,接收一个参数 action,这个 action 是一个普通的 js 对象,里面必须包含一个 type 字段来声明目的,dispatch 在 switch 里面会识别这个 type 字段,能够识别出来的操作才能执行 state 的更改。action 中除了 type 字段是必须的之外,其他的字段都是可以自定义的。
store:
getState 获取 state
dispatch 发起更改 state 的通知调用,reducer 来更改 state
### Provider
使用高阶组件,将 context 与 pure component 连接起来, 在高阶组件中再将 context 与 redux 连接起来,然后使用一个 mapStateToProps 的方法,将 state 传递给 pure component,同时也可以使用 mapDispatchToProps 传递给 props 给 pure component.
Provider 是一个容器组件,将嵌套的内容原封不动的作为自己的子组件。将外界传递给它的 props.state 放到 context 中,这样子组件就可以使用。
### pure component vs container component
pure component 可预测性强,对 props 以外的数据零依赖,也不会产生副作用。尽量使用 pure component 提高组件的可复用性。
container component 专门做数据相关的应用逻辑,和各种数据打交道,然后把数据通过 props 传递给 pure component。
container componetn 组件可以包含 pure component 和 container component,但是 pure component 尽量不要依赖 container component
最好将组件放在两个目录中,所有的 pure component 放在 components 目录中,所有的 container component 组件放在 containers 目录中。
根据组件是否需要高度复用的,把组件分为 pure 和 container 组件两种类型
container 组件并不意味着完全不能复用,它的复用是依赖场景的,在特定的场景下是可以复用的。而 pure component 是可以跨应用场景复用的。
|
TypeScript
|
UTF-8
| 1,033 | 2.953125 | 3 |
[] |
no_license
|
import {State, Action } from './state'
export const setReposByUser = (repos:[]):Action => {
return {
type: "SET_REPOS_BY_USER",
payload: repos
};
};
export const setErrorMessage = (errorMessage:string):Action => {
return {
type: "SET_ERROR_MESSAGE",
payload: errorMessage
};
};
export const toggleEnabled = (enabled:boolean):Action => {
return {
type: "TOGGLE_ENABLED",
payload: enabled
};
};
export const reducer = ( state: State, action:Action): State => {
switch (action.type) {
case "SET_REPOS_BY_USER":
return {
...state,
reposByUser: action.payload
}
case "SET_ERROR_MESSAGE":
return {
...state,
errorMessage:action.payload
}
case "TOGGLE_ENABLED":
return {
...state,
enabled:action.payload
}
default:
return state;
}
}
|
Swift
|
UTF-8
| 10,980 | 2.703125 | 3 |
[] |
no_license
|
//
// Business.swift
// Open
//
// Created by Bryan Ryczek on 10/21/16.
// Copyright © 2016 Bryan Ryczek. All rights reserved.
//
import UIKit
import Foundation
import CoreLocation
import FirebaseDatabase
//property ideas
// business owner
// phone number
// hours
enum DayOfWeek : Int {
case sunday = 0
case monday = 1
case tuesday = 2
case wednesday = 3
case thursday = 4
case friday = 5
case saturday = 6
}
struct Business {
var opnPlaceID : String //Generated upon signup
let placeID : String //Google places ID for cross reference
let key: String
let ref: FIRDatabaseReference?
//Name
let businessName : String
let contactName : String
//Security
let password : String
//Tags
let businessTypeOne : String
let businessTypeTwo : String
let businessTypeThree : String
let businessTags : [String]
//Hours
let mondayOpen : String
let mondayClose : String
let tuesdayOpen : String
let tuesdayClose : String
let wednesdayOpen : String
let wednesdayClose : String
let thursdayOpen : String
let thursdayClose : String
let fridayOpen : String
let fridayClose : String
let saturdayOpen : String
let saturdayClose : String
let sundayOpen : String
let sundayClose : String
//Address
let addressLineOne : String
let addressLineTwo : String
let city : String
let state : String
let zip : String
//Hood
let neighborhood : String
//Contact Info
let phoneNumber : String
let website : String
let email : String
//etc.
let businessDescription : String
//lat - long
let latitude : Double
let longitude : Double
var isOpen: Bool {
get {
let dates = getOpenClose(self)
return isDateWithinInverval(dates[0], close: dates[1])
}
}
var nxtOpn : String {
get {
return nextOpen(self)
}
}
var opnTil : String {
get {
return openUntil(self)
}
}
var location : CLLocation {
get {
return CLLocation(latitude: latitude, longitude: longitude)
}
}
init(//Key
opnPlaceID : String,
placeID : String,
key: String = "",
//Name
businessName : String,
contactName : String,
//Security
password : String,
//Tags
businessTypeOne : String,
businessTypeTwo : String,
businessTypeThree : String,
businessTags : [String],
//Hours
mondayOpen : String,
mondayClose : String,
tuesdayOpen : String,
tuesdayClose : String,
wednesdayOpen : String,
wednesdayClose : String,
thursdayOpen : String,
thursdayClose : String,
fridayOpen : String,
fridayClose : String,
saturdayOpen : String,
saturdayClose : String,
sundayOpen : String,
sundayClose : String,
//Address
addressLineOne : String,
addressLineTwo : String,
city : String,
state : String,
zip : String,
//Hood
neighborhood : String,
//Contact Info
phoneNumber : String,
website : String,
email : String,
//etc.
businessDescription : String,
// lat - long
latitude : Double,
longitude : Double
) {
self.opnPlaceID = opnPlaceID
self.placeID = placeID
self.key = key
self.businessName = businessName
self.contactName = contactName
self.password = password
self.businessTypeOne = businessTypeOne
self.businessTypeTwo = businessTypeTwo
self.businessTypeThree = businessTypeThree
self.businessTags = businessTags
self.mondayOpen = mondayOpen
self.mondayClose = mondayClose
self.tuesdayOpen = tuesdayOpen
self.tuesdayClose = tuesdayClose
self.wednesdayOpen = wednesdayOpen
self.wednesdayClose = wednesdayClose
self.thursdayOpen = thursdayOpen
self.thursdayClose = thursdayClose
self.fridayOpen = fridayOpen
self.fridayClose = fridayClose
self.saturdayOpen = saturdayOpen
self.saturdayClose = saturdayClose
self.sundayOpen = sundayOpen
self.sundayClose = sundayClose
self.addressLineOne = addressLineOne
self.addressLineTwo = addressLineTwo
self.city = city
self.state = state
self.zip = zip
self.neighborhood = neighborhood
self.phoneNumber = phoneNumber
self.website = website
self.email = email
self.businessDescription = businessDescription
//lat - long
self.latitude = latitude
self.longitude = longitude
self.ref = nil
}
init(snapshot: FIRDataSnapshot) {
key = snapshot.key
let snapshotValue = snapshot.value as! [String: AnyObject]
opnPlaceID = snapshotValue["opnPlaceID"] as! String
placeID = snapshotValue["placeID"] as! String
businessName = snapshotValue["businessName"] as! String
contactName = snapshotValue["contactName"] as! String
password = snapshotValue["password"] as! String
businessTypeOne = snapshotValue["businessTypeOne"] as! String
businessTypeTwo = snapshotValue["businessTypeTwo"] as! String
businessTypeThree = snapshotValue["businessTypeThree"] as! String
businessTags = snapshotValue["businessTags"] as! [String]
mondayOpen = snapshotValue["mondayOpen"] as! String
mondayClose = snapshotValue["mondayClose"] as! String
tuesdayOpen = snapshotValue["tuesdayOpen"] as! String
tuesdayClose = snapshotValue["tuesdayClose"] as! String
wednesdayOpen = snapshotValue["wednesdayOpen"] as! String
wednesdayClose = snapshotValue["wednesdayClose"] as! String
thursdayOpen = snapshotValue["thursdayOpen"] as! String
thursdayClose = snapshotValue["thursdayClose"] as! String
fridayOpen = snapshotValue["fridayOpen"] as! String
fridayClose = snapshotValue["fridayClose"] as! String
saturdayOpen = snapshotValue["saturdayOpen"] as! String
saturdayClose = snapshotValue["saturdayClose"] as! String
sundayOpen = snapshotValue["sundayOpen"] as! String
sundayClose = snapshotValue["sundayClose"] as! String
addressLineOne = snapshotValue["addressLineOne"] as! String
addressLineTwo = snapshotValue["addressLineTwo"] as! String
city = snapshotValue["city"] as! String
state = snapshotValue["state"] as! String
zip = snapshotValue["zip"] as! String
neighborhood = snapshotValue["neighborhood"] as! String
phoneNumber = snapshotValue["phoneNumber"] as! String
website = snapshotValue["website"] as! String
email = snapshotValue["email"] as! String
businessDescription = snapshotValue["businessDescription"] as! String
latitude = snapshotValue["latitude"] as! Double
longitude = snapshotValue["longitude"] as! Double
ref = snapshot.ref
}
func toAnyObject() -> Any {
return [
//"isOpen" : isOpen,
"opnPlaceID" : opnPlaceID,
"placeID" : placeID,
"businessName": businessName,
"contactName" : contactName,
"password" : password,
"businessTypeOne" : businessTypeOne,
"businessTypeTwo" : businessTypeTwo,
"businessTypeThree" : businessTypeThree,
"businessTags" : businessTags,
"mondayOpen" : mondayOpen,
"mondayClose" : mondayClose,
"tuesdayOpen" : tuesdayOpen,
"tuesdayClose" : tuesdayClose,
"wednesdayOpen" : wednesdayOpen,
"wednesdayClose" : wednesdayClose,
"thursdayOpen" : thursdayOpen,
"thursdayClose" : thursdayClose,
"fridayOpen" : fridayOpen,
"fridayClose" : fridayClose,
"saturdayOpen" : saturdayOpen,
"saturdayClose" : saturdayClose,
"sundayOpen" : sundayOpen,
"sundayClose" : sundayClose,
"addressLineOne" : addressLineOne,
"addressLineTwo" : addressLineTwo,
"city" : city,
"state" : state,
"zip" : zip,
"neighborhood" : neighborhood,
"phoneNumber" : phoneNumber,
"website" : website,
"email" : email,
"businessDescription" : businessDescription,
"latitude" : latitude,
"longitude" : longitude,
]
}
}
extension Business {
mutating func generateOpnPlaceID() {
self.opnPlaceID = randomOpnKey(length: 18, business: self)
}
}
extension Business: Equatable {
static func ==(lhs: Business, rhs: Business) -> Bool {
let areEqual = lhs.opnPlaceID == rhs.opnPlaceID &&
lhs.placeID == rhs.placeID &&
lhs.businessName == rhs.businessName &&
lhs.contactName == rhs.contactName &&
lhs.password == rhs.password &&
lhs.businessTypeOne == rhs.businessTypeOne &&
lhs.businessTypeTwo == rhs.businessTypeTwo &&
lhs.businessTypeThree == rhs.businessTypeThree &&
lhs.businessTags == rhs.businessTags &&
lhs.mondayOpen == rhs.mondayOpen &&
lhs.mondayClose == rhs.mondayClose &&
lhs.tuesdayOpen == rhs.tuesdayOpen &&
lhs.tuesdayClose == rhs.tuesdayClose &&
lhs.wednesdayOpen == rhs.wednesdayOpen &&
lhs.wednesdayClose == rhs.wednesdayClose &&
lhs.thursdayOpen == rhs.thursdayOpen &&
lhs.thursdayClose == rhs.thursdayClose &&
lhs.fridayOpen == rhs.fridayOpen &&
lhs.fridayClose == rhs.fridayClose &&
lhs.saturdayOpen == rhs.saturdayOpen &&
lhs.saturdayClose == rhs.saturdayClose &&
lhs.sundayOpen == rhs.sundayOpen &&
lhs.sundayClose == rhs.sundayClose &&
lhs.addressLineOne == rhs.addressLineOne &&
lhs.addressLineTwo == rhs.addressLineTwo &&
lhs.city == rhs.city &&
lhs.state == rhs.state &&
lhs.zip == rhs.zip &&
lhs.neighborhood == rhs.neighborhood &&
lhs.phoneNumber == rhs.phoneNumber &&
lhs.website == rhs.website &&
lhs.email == rhs.email &&
lhs.businessDescription == rhs.businessDescription &&
lhs.latitude == rhs.latitude &&
lhs.longitude == rhs.longitude
return areEqual
}
}
|
Shell
|
UTF-8
| 496 | 2.984375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
#! /bin/sh
echo "Running $0"
. $GLOBUS_LOCATION/libexec/globus-sh-tools.sh
GPATH=$GPT_LOCATION
if [ "$GPATH" = "" ]; then
GPATH=$GLOBUS_LOCATION
fi
if [ "$GPATH" = "" ]; then
echo "GPT_LOCATION or GLOBUS_LOCATION needs to be set before running this script."
fi
$GLOBUS_SH_PERL -I${GPATH}/lib/perl -I${GLOBUS_LOCATION}/lib/perl \
${GLOBUS_LOCATION}/setup/globus/setup-gram-manager.pl \
-m "Cobalt" \
-p "globus_wsrf_gram_service_java_setup_cobalt" \
"$@"
|
C++
|
UHC
| 2,197 | 2.59375 | 3 |
[] |
no_license
|
#ifndef _BreadDataFactory_h_
#define _BreadDataFactory_h_
#include "BreadStdHeader.h"
#include "BreadInline.h"
namespace Bread
{
/*
@date 2011.01.21
@auth prodongi
@desc atlmap
@todo Ÿ
*/
template <class K, class V, class B, class S, class T>
class cDataFactory
{
protected:
typedef K KEY;
typedef V VALUE;
typedef B BUCKET;
typedef S SCHEDULER;
typedef T THREAD;
typedef typename T::LOADING_INFO LOADING_INFO;
public:
cDataFactory()
{
m_bucket = NULL;
m_scheduler = NULL;
m_loadingThread = NULL;
m_deletingThread = NULL;
}
virtual void initialize()
{
m_bucket = new BUCKET;
m_scheduler = new SCHEDULER;
createThread();
}
virtual void finalize()
{
safeDelete(m_loadingThread, true);
safeDelete(m_bucket);
safeDelete(m_scheduler);
safeDelete(m_deletingThread);
}
virtual void update(float /*elapsedtime*/) {}
bool is(KEY const& key) const
{
return m_bucket->is(key);
}
V* get(KEY const& key) const
{
return m_bucket->get(key);
}
bool insert(KEY const& key, V* value)
{
return m_bucket->insert(key, &value);
}
bool remove(KEY const& key)
{
return m_bucket->remove(key);
}
V* create(KEY const& key)
{
return m_bucket->create(key);
}
V* create()
{
return m_bucket->create();
}
template <class Fn> void forEach(Fn func)
{
m_bucket->forEach(func);
}
size_t getBucketSize() const
{
return m_bucket->getBucketSize();
}
size_t getCount() const
{
return m_bucket->getCount();
}
void addLoadingList(LOADING_INFO const& info)
{
m_loadingThread->addLoadingList(info);
}
void directLoading(LOADING_INFO const& info)
{
m_loadingThread->directLoading(info);
}
void mergeThread()
{
m_loadingThread->merge();
m_deletingThread->merge();
}
/// @brief m_loadingThread copy Ÿ mergeϱ ȣ
virtual void mergeCopyData(VALUE* /*copyData*/) {}
protected:
virtual ~cDataFactory() {}
virtual void createThread() = 0;
protected:
BUCKET* m_bucket;
SCHEDULER* m_scheduler;
THREAD* m_loadingThread;
THREAD* m_deletingThread;
};
}
#endif
|
Java
|
UTF-8
| 1,062 | 2.234375 | 2 |
[] |
no_license
|
package com.fury.game.system.files.logs;
import com.fury.cache.Revision;
import com.fury.core.model.node.entity.actor.figure.player.Player;
import com.fury.core.model.item.Item;
public class LoggedPlayerItem extends LoggedItem {
String username;
boolean received;
public LoggedPlayerItem(Item item, Player with, boolean received) {
super(item);
username = with == null ? null : with.getUsername();
this.received = received;
}
public LoggedPlayerItem(int id, long timestamp, int amount, Revision revision, String username, boolean received) {
super(id, timestamp, amount, revision);
this.username = username;
this.received = received;
}
public LoggedPlayerItem(int id, long timestamp, int amount, String username, boolean received) {
super(id, timestamp, amount);
this.username = username;
this.received = received;
}
public String getUsername() {
return username;
}
public boolean wasReceived() {
return received;
}
}
|
Java
|
UTF-8
| 279 | 1.648438 | 2 |
[] |
no_license
|
package com.yaoyao.order.service;
import com.yaoyao.common.pojo.ShopResult;
import com.yaoyao.order.pojo.OrderInfo;
public interface OrderService {
//生成订单,OrderInfo当中包含了表单提交的所有数据。
ShopResult createOrder(OrderInfo orderInfo);
}
|
Python
|
UTF-8
| 3,274 | 3.59375 | 4 |
[] |
no_license
|
"""
Odessa Elie
May 1, 2020
Naive Bayes Classifier
The purpose of this project is to implement the Naive Bayes Classifier on text data.
"""
#importing packages
import numpy as np
import pandas as pd
from sklearn import preprocessing
import operator
import nltk
#nltk.download()
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from nltk.stem import PorterStemmer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.metrics import confusion_matrix
#take the user's input of the dataset and label file and print some samples
filename = input("Enter filename: ")
labelfile = input("Enter label filename: ")
classifier1 = input("Enter the first classification label: ")
classifier2 = input("Enter the second classification label: ")
get_data = pd.read_table(filename,sep=',', header=0, names=['Category', 'Message'], encoding= 'unicode_escape')
# Printing the dataset details
print ("\nDataset Details (instances, attributes): ", get_data.shape)
# Printing the first 5 instances of the dataset
print ("\nDataset sample: \n",get_data.head())
#Training label
training_label = open(filename)
#Extract values from training labels
lines = training_label.readlines()
for longlines in open(filename,"r"):
longlines = longlines.strip()
lines = longlines.split(";")
#Get numlines number of lines
numlines = len(lines)
d = dict()
# Loop through each line of the file, remove the leading spaces and newline characters and split the line into words
for line in open(labelfile,"r"):
line = line.strip()
words = line.split(",")
# Iterate over each word in line to check if it is in the dictionary. If it is there increment and if it is not insert it with a count of 1
for word in words:
if word in d:
d[word] += 1
else:
d[word] = 1
#calculate the probability of the classification
for key in d:
d[key]/= numlines
print("\nProbability of each classification:")
print("\n".join("{}: {}".format(k, v) for k,v in d.items()))
#convert ham and spam to binary
get_data['Category'] = get_data.Category.map({classifier1: 0, classifier2: 1})
get_data['Message'] = get_data['Message'].apply(nltk.word_tokenize)
stemmer = PorterStemmer()
stemfunction = lambda x: [stemmer.stem(y) for y in x]
get_data['Message'] = get_data['Message'].apply(stemfunction)
# This converts the list of words into strings separated by spaces
get_data['Message'] = get_data['Message'].apply(lambda x: ' '.join(x))
vectorizer = CountVectorizer()
counts = vectorizer.fit_transform(get_data['Message'])
transformer = TfidfTransformer().fit(counts)
counts = transformer.transform(counts)
#split into training and testing (60-40 split)
X_train, X_test, y_train, y_test = train_test_split(counts, get_data['Category'], test_size = 0.4, random_state = 50)
NBmodel = MultinomialNB().fit(X_train, y_train)
prediction = NBmodel.predict(X_test)
print("\nAccuracy: ",np.mean(prediction == y_test)*100, "%")
print("\nConfusion Matrix: \n",confusion_matrix(y_test, prediction))
|
Markdown
|
UTF-8
| 1,782 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
# Go 1.14
Welcome to the Go 1.14 Release Party!
https://www.crowdcast.io/e/pdx-go-march-12-2020
## Loops
Go 1.14 comes with a change in how the runtime does preemption of Goroutines.
- Release notes are [here](https://golang.org/doc/go1.14#runtime)
- Code samples are [here](./preemption/main.go)
## Tests
Go 1.14 comes with two nice additions for testing. Previously, we had to implement this stuff ourselves and it was hard.
## Cleaning up
When we're writing tests, we often have to clean up after ourselves after we're done. For example, we might need to delete a database table or close a connection. Before 1.14, we had to come up with our own ways to reliably clean up. Now, Go has a native way to cleanup. The [`*testing.T`](https://golang.org/pkg/testing/#T.Cleanup) and [`*testing.B`](https://golang.org/pkg/testing/#B.Cleanup) types both have a `Cleanup(func())` method on them.
- Release notes are [here](https://golang.org/doc/go1.14#testing)
- Code samples are [here](./tests/cleanup_test.go)
- Run them with `go test -v cleanup_test.go`
## Log streaming
When we ran `go test -v`, Go waited until the end of the test to print all of the strings passed to `t.Log`.
Sometimes it's more helpful to have the output streamed as it happens. Now, if you run `go test -v`, each `t.Log` call gets flushed to `STDOUT` as it happens.
- Release notes are [here](https://golang.org/doc/go1.14#go-command) (see the "testing" header at the bottom of the section)
- Code samples are [here](./tests/stream_test.go)
- Run them with `go test -v stream_test.go`
## Overlapping interfaces
Before 1.14, you couldn't do this:
```go
type Interface1 {
Hello()
}
type Interface2 {
Hello()
}
type Interface3 {
Interface1
Interface2
}
```
But now you can!
|
Markdown
|
UTF-8
| 3,369 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
# Peregrin
A library for inspecting Zhooks, Ochooks and EPUB ebooks, and converting
between them.
Invented by [Inventive Labs](http://inventivelabs.com.au). Released under the
MIT license.
More info: http://ochook.org/peregrin
## Requirements
Ruby, at least 1.8.x.
You must have ImageMagick installed — specifically, you must have the 'convert'
utility provided by ImageMagick somewhere in your PATH.
Required Ruby gems:
* zipruby
* nokogiri
## Peregrin from the command-line
You can use Peregrin to inspect a Zhook, Ochook or EPUB file from the
command-line. It will perform very basic validation of the file and
output an analysis.
$ peregrin strunk.epub
[EPUB]
Components:
main0.xml
main1.xml
main2.xml
main3.xml
main4.xml
main5.xml
main6.xml
main7.xml
main8.xml
main9.xml
main10.xml
main11.xml
main12.xml
main13.xml
main14.xml
main15.xml
main16.xml
main17.xml
main18.xml
main19.xml
main20.xml
main21.xml
Media: 1
css/main.css
Cover: cover.png
Metadata:
title: The Elements of Style
creator: William Strunk Jr.
cover: cover
language: en
identifier: 8102537c96
Note that file type detection is quite naive — it just uses the path extension,
and if the extension is not .zhook or .epub, it assumes the path is an
Ochook directory.
You can also use Peregrin to convert from one format to another. Just provide
two paths to the utility; it will convert from the first to the second.
$ peregrin strunk.epub strunk.zhook
[Zhook]
Components:
index.html
Media: 2
css/main.css
cover.png
Cover: cover.png
Metadata:
title: The Elements of Style
creator: William Strunk Jr.
cover: cover
language: en
identifier: e4603149df00
## Library usage
The three formats are represented in the Peregrin::Epub, Peregrin::Zhook and
Peregrin::Ochook classes. Each format class responds to the following methods:
* validate(path)
* read(path) - creates an instance of the class from the path
* new(book) - creates an instance of the class from a Peregrin::Book
Each instance of a format class responds to the following methods:
* write(path)
* to_book(options) - returns a Peregrin:Book object
Here's what a conversion routine might look like:
zhook = Peregrin::Zhook.read('foo.zhook')
epub = Peregrin::Epub.new(zhook.to_book(:componentize => true))
epub.write('foo.epub')
## Peregrin::Book
Between the three supported formats, there is an abstracted concept of "book"
data, which holds the following information:
* components - an array of files that make up the linear content
* contents - an array of chapters (with titles, hrefs and children)
* metadata - a hash of key/value pairs
* media - an array of files contained in the ebook, other than components
* cover - the media file that should be used as the cover of the ebook
There will probably be some changes to the shape of this data over the
development of Peregrin, to ensure that the Book interchange object retains all
relevant information about an ebook without lossiness. But for the moment,
it's being kept as simple as possible.
## Peregrin?
All this rhyming on "ook" put me in mind of the Took family. There is no
deeper meaning.
|
JavaScript
|
UTF-8
| 519 | 2.6875 | 3 |
[] |
no_license
|
/* Metodo getRemito
Permite traer un remito con el idTransac como parametro
*/
const { Router } = require("express");
const router = Router();
const _ = require("underscore");
const docs = require("../sample.json");
//console.log(docs)
router.get('/:id', (req,res) => {
const { id } = req.params
console.log(id)
_.each(docs, (doc, i) => {
// console.log(doc.idTransac)
if( doc.idTransac == id ){
console.log("encontrado")
res.send(doc)
}
})
})
module.exports = router
|
Java
|
UTF-8
| 350 | 1.78125 | 2 |
[] |
no_license
|
package com.dml.puke.wanfa.dianshu.dianshuzu;
import com.dml.puke.pai.DianShu;
/**
* 连3张。 333444555、444555666777888
*
* @author Neo
*
*/
public class LiansanzhangDianShuZu extends LianXuDianShuZu {
public LiansanzhangDianShuZu() {
}
public LiansanzhangDianShuZu(DianShu[] lianXuDianShuArray) {
super(lianXuDianShuArray);
}
}
|
C++
|
UTF-8
| 2,323 | 2.578125 | 3 |
[] |
no_license
|
#include <ESP8266WiFi.h>
#include <SocketIOClient.h>
SocketIOClient client;
const char* ssid = "BANDOTT83"; // Tên mạng Wifi được chỉ định sẽ kết nối (SSID)
const char* password = "20180720"; // Password của mạng Wifi được chỉ định sẽ kết nối
const char* host = "192.168.100.18"; // Địa chỉ IP của máy khi truy cập cùng mạng WiFi
const int port = 3000; //Cổng dịch vụ socket server do chúng ta tạo!
extern String RID;
extern String Rfull;
unsigned long previousMillis = 0;
long interval = 2000;
void setup()
{
Serial.begin(115200);
delay(10);
Serial.print("Ket noi vao mang ")
Serial.println(ssid);
//Kết nối vào mạng Wif
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) { //Thoát ra khỏi vòng
delay(500);
Serial.print('.');
Serial.println();
Serial.println(F("Da ket noi WiFi"));
Serial.println(F("Di chi IP cua ESP8266 (Socket Client ESP8266): "));
Serial.println(WiFi.localIP());
if (!client.connect(host, port))
Serial.println(F("Ket noi den socket server that bai!"));
return;
//Khi đã kết nối thành côn
if (client.connected())
//Thì gửi sự kiện ("connection") đến Socket server ahihi
client.send("connection", "message", "Connected !!!!");
}
void loop()
{
//tạo một task cứ sau "interval" giây thì chạy lệnh
if (millis() - previousMillis > interval)
//lệnh
previousMillis = millis() {
//gửi sự kiện "atime" là một JSON chứa tham số message có nội dung là Time please
client.send("atime", "message", "Time please?");
//Khi bắt được bất kỳ sự kiện nào thì chúng ta có hai tham số
// +RID: Tên sự kiệ
// +RFull: Danh sách tham số được nén thành chuỗi JSON
if (client.monitor()) {
Serial.println(RID);
Serial.println(Rfull);
//Kết nối lại
if (!client.connected()) {
client.reconnect(host, port);
}
}
}
}
|
Markdown
|
UTF-8
| 1,607 | 3.1875 | 3 |
[] |
no_license
|
基金
========
## 定投的两种策略
一种根据大盘或者基金对应的指数,设定区间。比如沪指3000点上下500点,定时投1000。3500-4000投800每次。4000-4500投500每次。2000-2500,1500每次。具体选哪个,区间,价格差别是整数,还是百分比,需要你自己定。
一种是价值平均。就是保持市值。方法举例,第一周买1000,市值也是1000;第二周,不管花多少,让市值到2000;第n周,市值到n千。这样越跌,买的越多。涨就买的少,甚至提钱出来。需要你有个大体的估算,跌的时候用钱会多,涨会产生不少闲钱。投进去的收益率倒是会提高。
看你自己选择吧,定投就是设计好以后无脑执行就可以了,开始的设计可能会麻烦点
傻瓜投资策略:
1.定投策略:选好一个标的,按月投入固定金额,持有到牛市一次性赎回。
2.定投升级策略:比如说第一个月投入1000元,第二个月若涨了200,则投入800元,若跌了200,则投入1200元。以此类推。
3.50%平衡策略:选好一个标的,先建仓50%,持有50%的现金,若上涨了20%,则卖掉10%,若下跌20%,则买入10%,始终保持市值和现金各占50%,高抛低吸。
4.目标市值策略:比如说买入一个标的1000元,若涨了100,则卖出100元,若跌了100,则买入100元,始终保持1000元的市值。
5.网格策略:买入一个标一定的份额作为底仓,每上涨5%卖出一份,每下跌5%买入一份,如此循环操作。
以上策略根据估值选标的,胜率几乎是百分之百
|
Python
|
UTF-8
| 323 | 2.984375 | 3 |
[] |
no_license
|
function_names = []
with open("temp.py", 'rb') as f:
for line in f.readlines():
line = str(line).strip()
print(type(line))
print(line)
if str(line).startswith('def'):
function_name = line.split(' ')[1]
function_names.append(function_name)
print(function_names)
|
C
|
UTF-8
| 7,291 | 2.875 | 3 |
[] |
no_license
|
#include "game.h"
#include "raylib.h"
#include "utilities.h"
#include "player.h"
#include "computer.h"
#include <time.h>
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
int length = 30;
int radius = 8;
float pointDis = 65.0f;
float thickness = 6.0f;
int carry = -1; // If there is a segment currently carried by the mouse.
int nrSegments = 0;
static int nrSegmentsLeft = 0;
int gameState = 1; // 1 - player's turn, 0 - computer's turn
/* Functions regarding point spawning */
static int isValidPoint (int index, int x, int y)
{
if (!length)
return 1;
for (int i = 0; i < index; i++)
if (pointDistance(x, y, segment[i].point.x, segment[i].point.y) <= pointDis)
return 0;
return 1;
}
static void setRandomPoints (Rectangle bound)
{
const int lengthX = (int)(bound.x + bound.width);
const int lengthY = (int)(bound.y + bound.height);
srand(time(0));
for (int i = 0; i < length; ) {
int x = rand() % lengthX;
while (!(bound.x <= x && x <= bound.width))
x = rand() % lengthX;
int y = rand() % lengthY;
while (!(bound.y <= y && y <= bound.height))
y = rand() % lengthY;
if (isValidPoint(i, x, y)) {
segment[i].point.x = x;
segment[i].point.y = y;
segment[i].pair = -1;
segment[i].valid = 1;
i++;
}
}
}
// Graphical rendering and pre-rendering functions
static void DrawBackground(Rectangle backRect, Rectangle frontRect)
{
const float roundness = 0.2f;
const int segments = 0;
DrawRectangleRounded(backRect, roundness, segments, GRAY);
DrawRectangleRounded(frontRect, roundness, segments, WHITE);
}
static void DrawPoints()
{
for (int i = 0; i < length; i++)
DrawCircle(segment[i].point.x, segment[i].point.y, radius, BLACK);
}
static void DrawInfo(Texture2D ExitSTexture, Texture2D ExitHTexture)
{
int mouseX = GetMouseX();
int mouseY = GetMouseY();
int screenW = GetScreenWidth();
int screenH = GetScreenHeight();
// Exit button.
if (screenW - 50 <= mouseX && mouseX <= screenW && 0 <= mouseY && mouseY <= 50) {
DrawTexture(ExitHTexture, screenW - 50, 0, RAYWHITE);
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON))
CloseWindow();
}
else DrawTexture(ExitSTexture, screenW - 50, 0, RAYWHITE);
// Label with segment information.
char text[100] = "Segments Left: ";
char result[10];
sprintf(result, "%d", nrSegmentsLeft);
strcat(text, result);
int TextX = screenW / 2 - 150;
int TextY = (screenH - screenH / 4) + 50;
DrawText(text, TextX, TextY, 25, BLACK);
// Change Turn button.
if (gameState) {
int buttonX = TextX + 15;
int buttonY = TextY + 50;
int buttonW = 200;
int buttonH = 75;
if (buttonX <= mouseX && mouseX <= buttonX + buttonW &&
buttonY <= mouseY && mouseY <= buttonY + buttonH) {
DrawRectangle(buttonX, buttonY, buttonW, buttonH, GRAY);
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON))
gameState = 0;
}
else DrawRectangle(buttonX, buttonY, buttonW, buttonH, BLACK);
}
}
static void Render(Rectangle backRect, Rectangle frontRect)
{
ClearBackground(WHITE);
DrawFPS(0, 0);
DrawBackground(backRect, frontRect);
DrawPoints();
}
void SegmentsLeft()
{
// Returns the number of valid segments left.
if (!nrSegments) {
nrSegmentsLeft = (length * (length - 1) / 2);
return;
}
int count = 0;
for (int i = 0; i < length - 1; i++)
for (int j = i + 1; j < length; j++)
if (segment[i].pair == -1 && segment[j].pair == -1) {
int value = 1;
for (int k = 0; k < nrSegments; k++)
if (!isValidSegment(segment[i].point, segment[j].point, segment[pairedPoints[k]].point, segment[segment[pairedPoints[k]].pair].point)) {
value = 0;
break;
}
if (value)
count++;
}
nrSegmentsLeft = count;
}
static void PreRender(Rectangle backRect, Rectangle frontRect)
{
const float seconds = 0.20f;
for (int i = 0; i < length;) {
BeginDrawing();
ClearBackground(WHITE);
DrawBackground(backRect, frontRect);
for (int j = 0; j < i; j++)
DrawCircle(segment[j].point.x, segment[j].point.y, radius, BLACK);
EndDrawing();
DelayTime(seconds);
i++;
}
SegmentsLeft();
}
static int isMouseBounds(Rectangle bound)
{
int mouseX = GetMouseX();
int mouseY = GetMouseY();
if (!(bound.x <= mouseX && mouseX <= bound.width)) return 0;
if (!(bound.y <= mouseY && mouseY <= bound.height)) return 0;
return 1;
}
static void DrawSegment()
{
for (int i = 0; i < length; i++) {
Vector2 startPos = segment[i].point;
if (segment[i].pair > 0) {
Vector2 endPos = segment[segment[i].pair].point;
DrawLineEx(startPos, endPos, thickness, BLACK);
}
if (carry == i) {
Vector2 mousePos = GetMousePosition();
segment[i].valid = 1;
for (int j = 0; j < length && segment[i].valid; j++)
if (segment[j].pair > 0 && segment[j].pair > j)
segment[i].valid = isValidSegment(startPos, mousePos, segment[j].point, segment[segment[j].pair].point);
if (segment[i].valid)
DrawLineEx(startPos, mousePos, thickness, BLACK);
else
DrawLineEx(startPos, mousePos, thickness, RED);
}
}
}
void Turn()
{
if (gameState)
PlayerTurn();
else ComputerTurn();
SegmentsLeft();
}
void startGame()
{
/* Import necessary info */
// Exit button.
Image ExitS = LoadImage("Resources/ExitSimple.png");
ImageResize(&ExitS, 50, 50);
Texture2D ExitSTexture = LoadTextureFromImage(ExitS);
UnloadImage(ExitS);
Image ExitH = LoadImage("Resources/ExitHover.png");
ImageResize(&ExitH, 50, 50);
Texture2D ExitHTexture = LoadTextureFromImage(ExitH);
UnloadImage(ExitH);
// Background rectangle
Rectangle backRect = { 60, 50, GetScreenWidth() - 120, (GetScreenHeight() - GetScreenHeight() / 4) - 50};
Rectangle frontRect = { 70, 60, GetScreenWidth() - 140, (GetScreenHeight() - GetScreenHeight() / 4) - 70};
Rectangle bound = {frontRect.x + 50, frontRect.y + 100, frontRect.width - 50, frontRect.height - 50};
setRandomPoints(bound);
PreRender(backRect, frontRect);
while (!WindowShouldClose())
{
BeginDrawing();
Render(backRect, frontRect);
DrawInfo(ExitSTexture, ExitHTexture);
Turn();
DrawSegment();
EndDrawing();
}
UnloadTexture(ExitSTexture);
UnloadTexture(ExitHTexture);
CloseWindow();
}
|
C#
|
UTF-8
| 7,917 | 3.21875 | 3 |
[] |
no_license
|
/***************************************
* PatternRecognitionTest
* テストとサンプルコードを兼ねた静的クラス
*
* [履歴]
* 2012/6/20 作っただけ。まだ空です。
* 2012/6/23 昔造ったテストコードを移植してみたけど、フォルダ名とデータセットはどうしよう?
* *************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PatternRecognition;
using PatternRecognition.ArtificialNeuralNetwork;
namespace PatternRecognition
{
/// <summary>
/// パターン認識に関するテストとサンプルコードを兼ねた静的クラス
/// </summary>
static class PatternRecognitionTest
{
/// <summary>
/// NeuralNetTeacherクラスを使って、既に生成されている特徴ベクトルをまとめたファイルを読み込ませて学習を行う part1
/// </summary>
static public void Iris_learning()
{
var minPara = new MinParameter(15, 1, 0.1);
var NNteacher = new Teacher(minPara); // ニューラルネットの教師クラスのインスタンスを生成
NNteacher.Setup("教師データの例 Iris"); // 学習データの入ったフォルダ名を渡して初期化
int timeOfLearning = 10000; // 学習回数(厳密には一致しない)
for (int i = 1; i <= 2; i++) // 2回ループさせる
{
NNteacher.Learn(timeOfLearning);
Console.Write(NNteacher.SaveDecisionChart("decision chart " + (i * timeOfLearning).ToString() + ".csv", "\t")); // ファイルへ保存しつつコンソールへ出力する
}
NNteacher.SaveLearnigOutcome(); // 学習した結合係数などをファイルに保存
var discriminator = new Discriminator(); // 保存したファイルを使用して識別器を生成
discriminator.Setup(); // これ以降、学習成果を利用して識別を行うことができる。このサンプルでは省略。
return;
}
/// <summary>
/// NeuralNetTeacherクラスを使って、既に生成されている特徴ベクトルをまとめたファイルを読み込ませて学習を行う part2
/// </summary>
static public void Iris_learning2()
{
var minPara = new MinParameter(13, 1, 0.1);
var NNteacher = new Teacher(minPara); // ニューラルネットの教師クラスのインスタンスを生成
NNteacher.Setup("教師データの例 Iris");
int timeOfLearning = 10000;
for (int i = 1; i <= 2; i++) // 2回ループさせる
{
NNteacher.Learn(timeOfLearning);
NNteacher.SaveDecisionChart("decision chart " + (i * timeOfLearning).ToString() + ".csv");
}
NNteacher.SaveLearnigOutcome(); // 学習した結合係数などをファイルに保存
// これ以降は識別テスト
var feature = new Feature("5.4 3.4 1.7 0.2"); // セトナのデータ
// 学習済みのニューラルネットワーククラスオブジェクトを渡して学習器を構成
var discriminator = new Discriminator(NNteacher.GetNeuralNetwork(), NNteacher.ModelIDs);// これ以降、学習成果を利用して識別を行うことができる。
var test = discriminator.Discriminate(feature, 2); // 結果を降順で2つもらう
string outputstr = "";
for (int i = 0; i < test.Length; i++)
outputstr += test[i].ID + ", " + test[i].Likelihood.ToString("0.00") + "\n";
Console.WriteLine(outputstr, "識別テストその1の結果");
// ファイルから結合係数を読み込ませても同じ結果が出ることを確認する
var discriminator2 = new Discriminator();
discriminator2.Setup();
var test2 = discriminator.Discriminate(feature); // テストを実施し、表示する
Console.WriteLine("識別結果: " + test2.ID + ", " + test2.Likelihood.ToString("0.00"), "識別テストその2の結果");
return;
}
/// <summary>
/// XORの学習の例
/// <para>NeuralNetworkクラスを直接操作して論理演算を実行する例です。</para>
/// </summary>
static public void XOR_learning()
{
var para = new Parameter(2, 5, 1, 1, 0.1); // ニューラルネットのパラメータ設定(中間層が多いと、学習係数を小さくとる必要がある)7層が限界・・
var NNforXOR = new NeuralNetwork(); // ニューラルネットクラスのインスタンス生成
NNforXOR.Setup(para);
for (int i = 0; i < 100; i++) // 学習開始
{
var ans = new double[4];
Console.Write("now i: " + i.ToString() + "@ ");
for (int k = 0; k < 100; k++)
{
ans[0] = NNforXOR.Learn(new double[2] { 0.0, 0.0 }, 0.0); // 特徴ベクトルと教師ベクトルを渡す
ans[1] = NNforXOR.Learn(new double[2] { 0.0, 1.0 }, 1.0);
ans[2] = NNforXOR.Learn(new double[2] { 1.0, 0.0 }, 1.0);
ans[3] = NNforXOR.Learn(new double[2] { 1.0, 1.0 }, 0.0);
}
Console.WriteLine("ans = " + ans[0].ToString("0.000") + ", " + ans[1].ToString("0.000") + ", " + ans[2].ToString("0.000") + ", " + ans[3].ToString("0.000") +
", 最後の学習結果→Error variation," + NNforXOR.VariationOfError.ToString("0.000") + ", Total Error," + NNforXOR.TotalOutputError.ToString("0.000"));
}
NNforXOR.Save("NN.ini");
return;
}
/// <summary>
/// sin()関数の学習の例
/// <para>NeuralNetworkクラスを直接利用して関数近似を行わせるサンプルです。</para>
/// <para>
/// 2011/12/25現在、0~1までの出力しか得られない。
/// 出力関数と学習則を変更するか、関数近似時には値のマッピングが必要である。
/// 他の人はどうやってんだろう?</para>
/// </summary>
static public void sin_learnig()
{
var para = new Parameter(1, 13, 1, 3, 0.01); // ニューラルネットのパラメータ設定
var NNforSin = new NeuralNetwork(); // ニューラルネットクラスのインスタンス生成
NNforSin.Setup(para);
for (int i = 0; i < 500; i++) // 学習開始
{
Console.Write("\nnow i: " + i.ToString() + "@ ");
Console.Write("ans = ");
for (int k = 0; k < 15; k++)
{
double theta = (double)k / 15.0 * 2.0 * Math.PI;
double ans = 0.0;
for (int l = 0; l < 100; l++) ans = NNforSin.Learn(theta, Math.Sin(theta)); // 特徴ベクトルと教師ベクトルを渡す
Console.Write(", " + ans.ToString("0.000"));
}
}
NNforSin.Save("NN.ini");
return;
}
}
}
|
C#
|
UTF-8
| 2,597 | 3.390625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dijkstra
{
public class DijkstaAlgorithm
{
public static void GetShortestWay(int startNode, int finishNode)
{
Node last = NodeFlyweight.GetNode(finishNode);
Node current = NodeFlyweight.GetNode(startNode);
current.Visited = true;
current.TotalCost = 0;
while (last.Visited != true)
{
SetTotalCost(current.Id);
current = GetNext(current.Id);
}
ShowWay(startNode, finishNode);
Console.WriteLine("TotalCost: " + last.TotalCost);
}
private static void SetTotalCost(int current)
{
Node node = NodeFlyweight.GetNode(current);
foreach (var con in node.Connections)
{
if (node.TotalCost + con.Cost < con.Node.TotalCost && con.Node.Visited != true)
{
con.Node.TotalCost = node.TotalCost + con.Cost;
con.Node.PreviousNode = NodeFlyweight.GetNode(node.Id);
}
}
}
private static Node GetNext(int current)
{
int nextId = current;
double minCost = double.MaxValue;
foreach (var node in NodeFlyweight.GetNodesList())
{
if(node.TotalCost < minCost && node.Visited != true)
{
nextId = node.Id;
minCost = node.TotalCost;
}
}
Node next = NodeFlyweight.GetNode(nextId);
next.Visited = true;
return next;
}
private static void ShowWay(int startNode, int finishNode)
{
List<int> way = new List<int>();
Node node = NodeFlyweight.GetNode(finishNode);
do
{
way.Add(node.Id);
node = NodeFlyweight.GetNode(node.PreviousNode.Id);
}
while (node.Id != startNode);
way.Add(startNode);
way.Reverse();
Console.Write("Way: ");
foreach(var point in way)
{
Console.Write(point);
if(point != way[way.Count - 1])
{
Console.Write(" -> ");
}
}
Console.WriteLine();
}
}
}
|
Python
|
UTF-8
| 4,773 | 3.015625 | 3 |
[] |
no_license
|
# To add a new cell, type '#%%'
# To add a new markdown cell, type '#%% [markdown]'
#%% Change working directory from the workspace root to the ipynb file location. Turn this addition off with the DataScience.changeDirOnImportExport setting
# ms-python.python added
import os
try:
os.chdir(os.path.join(os.getcwd(), 'TweeterClassifier'))
print(os.getcwd())
except:
pass
#%% [markdown]
# ### Twitter Text Classifier
# #### Step 1.
# Import Libraries
# 1. Pandas: Used for structured data operations and manipulations.
# 2. Numpy:Stands for numerical python. It works on n-dimensional array.
# 3. nltk: nlp library for Lemmatization and Steming
# 4. sklearn:
#
#%%
import pandas as pd
import numpy as np
import re
from nltk.tokenize import word_tokenize
from nltk import pos_tag
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from sklearn.preprocessing import LabelEncoder
from collections import defaultdict
from nltk.corpus import wordnet as wn
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import model_selection, naive_bayes, svm
from sklearn.metrics import accuracy_score
from sklearn.model_selection import StratifiedShuffleSplit
np.random.seed(500)
def removeHttp(text):
return re.sub('http[s]?://\S+', '', text)
def dataCleaning(tweets):
for index, entry in enumerate(tweets['text']):
tweets.loc[index,'input_tweet'] = entry
# Step - a : Remove blank rows if any.
tweets['text'].dropna(inplace=True)
# Step - b : Change all the text to lower case. This is required as python interprets 'dog' and 'DOG' differently
tweets['text'] = [entry.lower() for entry in tweets['text']]
tweets['text'] = [removeHttp(entry) for entry in tweets['text']]
# Step - c : Tokenization : In this each entry in the corpus will be broken into set of words
tweets['text']= [word_tokenize(entry) for entry in tweets['text']]
# WordNetLemmatizer requires Pos tags to understand if the word is noun or verb or adjective etc. By default it is set to Noun
tag_map = defaultdict(lambda : wn.NOUN)
tag_map['J'] = wn.ADJ
tag_map['V'] = wn.VERB
tag_map['R'] = wn.ADV
for index,entry in enumerate(tweets['text']):
# Declaring Empty List to store the words that follow the rules for this step
Final_words = []
# Initializing WordNetLemmatizer()
word_Lemmatized = WordNetLemmatizer()
# pos_tag function below will provide the 'tag' i.e if the word is Noun(N) or Verb(V) or something else.
for word, tag in pos_tag(entry):
# Below condition is to check for Stop words and consider only alphabets
if word not in stopwords.words('english') and word.isalpha():
word_Final = word_Lemmatized.lemmatize(word)
Final_words.append(word_Final)
# The final processed set of words for each iteration will be stored in 'text_final'
tweets.loc[index,'text_final'] = str(Final_words)
return tweets
def getSplitRatio (numberOfClass, testsize):
return StratifiedShuffleSplit(n_splits=numberOfClass, test_size=testsize, random_state=0)
#%%
# readFile
#column = ["text_final","label","input_tweet"]
Corpus = pd.read_csv(r"Tweets_V3_5_5_balanced.csv",encoding='latin-1',sep=";")
# Data Lemmatizer and clean all tweets for Model
Corpus = dataCleaning(Corpus)
splitRatio = getSplitRatio(numberOfClass = 9, testsize = 0.3)
dataset = Corpus
from tweeter.dataset import dataframe
feature_vector = dataframe(dataset)
#input_X, input_Y, input_T = dataset['text_final'], dataset['label'], dataset['input_tweet']
#splitRatio.get_n_splits(input_X, input_Y)
splitRatio.get_n_splits(feature_vector.X, feature_vector.Y)
for train_idx, test_idx in splitRatio.split(feature_vector.X, feature_vector.Y):
train_index, test_index = train_idx, test_idx
# %%
from tweeter.dataset import dataset
trainingset = dataset(feature_vector,train_index)
testset = dataset(feature_vector, test_index)
#%%
Encoder = LabelEncoder()
trainingset.encode(Encoder)
testset.encode(Encoder)
#%%
Tfidf_vect = TfidfVectorizer(max_features=5000)
Tfidf_vect.fit(feature_vector.X)
trainingset.transform(Tfidf_vect)
testset.transform(Tfidf_vect)
#Train_X_Tfidf = Tfidf_vect.transform(trainingset.X)
#Test_X_Tfidf = Tfidf_vect.transform(testset.X)
#%%
# Classifier - Algorithm - SVM
# fit the training dataset on the classifier
SVM = svm.SVC(C=1.0, kernel='linear', degree=4, gamma='auto')
SVM.fit(trainingset.x_transform,trainingset.Y_encode)
# predict the labels on validation dataset
predictions_SVM = SVM.predict(testset.x_transform)
# Use accuracy_score function to get the accuracy
print("SVM Accuracy Score -> ",
accuracy_score(predictions_SVM, testset.Y_encode)*100)
# %%
|
Java
|
UTF-8
| 833 | 2.703125 | 3 |
[] |
no_license
|
package com.myTest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.myTest.VisualBoundaryDetector;
public class Main {
public static void main(String[] args) {
try {
long startTime = System.currentTimeMillis();
for (int i=0; i<36; i++) {
BufferedImage originalFile = ImageIO.read(new File("/Users/tinaht/Desktop/Lab/TextDetection/data/"+String.valueOf(i)+".jpg"));
VisualBoundaryDetector visualBoundaryDetector;
visualBoundaryDetector = new VisualBoundaryDetector(originalFile,i, 1080, 2244);
visualBoundaryDetector.detectTextBoundary();
}
long endTime = System.currentTimeMillis();
System.out.println("运行时间:" + (endTime - startTime) + "ms");
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
Java
|
UHC
| 259 | 2.609375 | 3 |
[] |
no_license
|
package ex01.Abstract;
public class MainEntry {
public static void main(String[] args) {
Circle c = new Circle();
Point pt = new Circle();
// ̷Ե ֵ
Rectangle rect = new Rectangle();
rect.disp();
c.disp();
pt.disp();
}
}
|
Markdown
|
UTF-8
| 634 | 2.5625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
# SwMapsLib
A .NET library for reading and writing SW Maps project files.
SW Maps is a free GIS and mobile mapping app for collecting, presenting and sharing geographic information, available for Android.
https://play.google.com/store/apps/details?id=np.com.softwel.swmaps
## Usage
SW Maps project files (SWMZ) can be read using the SwmzReader class. This creates an instance of the SwMapsProject class, which contains all the information read from the SWMZ file.
To create SW Maps projects, use the SwMapsProjectBuilder class. This creates an SwMapsProject, which can be written as a SW Maps V1 or V2 database, or an SWMZ file.
|
C++
|
UTF-8
| 362 | 2.75 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
vector<int> a(n);
for(auto& e : a) cin >> e;
int counter = -1;
bool isDividable = true;
while(isDividable){
for(auto& e : a){
if( e == 0 ) isDividable = false;
if( e%2 == 0 ) e /= 2;
else isDividable = false;
}
counter++;
}
cout << counter << endl;
return 0;
}
|
Markdown
|
UTF-8
| 899 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
# nl.liacs.watch_cli
## How to compile
First, fetch the required submodules:
```
git submodule update --init --recursive
```
Then, you can compile the software to a packed JAR using Gradle:
```
./gradlew shadowJar
```
This will create a jar in the `./build/libs/` folder.
## How to Run
You can run the software by simply running `java -jar <jar>` where `<jar>` is the JAR file as generated in the previous section.
For example, you'd run:
```
java -jar build/libs/nl.liacs.watch_cli-1.0-all.jar
```
## How to use
If watch_cli is running on the host computer, and the watch is connected with device manager,
an ID will be given to the watch when it is connected. This happens automatically.
Using ```devices```, it is possible to view the connection between the host and the watch.
Once the software is running, the help command can be used to get more information about the other commands
|
Python
|
UTF-8
| 6,396 | 3.5625 | 4 |
[] |
no_license
|
# Shane Weisz
# WSZSHA001
import sys
from random import randint
def FIFO(size, pages):
"""
Function that implements the FIFO page replacement algorithm and
returns the number of page faults that occur.
Parameters:
size (int): The number of available page frames - can vary from 1 to 7
pages (list): A page reference string e.g. [1, 2, 3, 5, 1, 2, 3, 5]
Returns:
int: The number of page faults that occured.
"""
queue = [] # queue, the page frames, is initially empty
page_faults = 0 # tracks the number of page faults
for page in pages: # loops through each page in the page ref str
if page not in queue: # check if the page is in memory already
page_faults += 1 # if not, a page fault has occurred
if len(queue) >= size: # check if there are no empty frames left
del queue[0] # if full, remove page at head of queue
queue.append(page) # append the new page at end of queue
return page_faults
def LRU(size, pages):
"""
Function that implements the LRU (Least Recently Used) page replacement
algorithm and returns the number of page faults that occur.
Parameters:
size (int): The number of available page frames - can vary from 1 to 7
pages (list): A page reference string e.g. [1, 2, 3, 5, 1, 2, 3, 5]
Returns:
int: The number of page faults that occured.
"""
stack = [] # stack, the page frames, is initially empty
page_faults = 0 # tracks the number of page faults
for page in pages: # loops through each page in the page ref str
if page not in stack: # check if the page is in memory already
page_faults += 1 # if not, a page fault has occurred
if len(stack) >= size: # check if there are no empty frames left
del stack[size-1] # remove the least recently used page
else: # page is in memory
stack.remove(page) # remove page from old place in stack
# put page on top of the stack because its the most recently used page.
stack.insert(0, page)
return page_faults
def OPT(size, pages):
"""
Function that implements the optimal page replacement algorithm (OPT)
and returns the number of page faults that occur.
Parameters:
size (int): The number of available page frames - can vary from 1 to 7
pages (list): A page reference string e.g. [1, 2, 3, 5, 1, 2, 3, 5]
Returns:
int: The number of page faults that occured.
"""
frames = [] # represent the frames in physical memory
page_faults = 0 # tracks the number of page faults
for (page_index, page) in enumerate(pages): # loop through page ref string
if page not in frames: # check if the page is in memory already
page_faults += 1 # if not, a page fault has occurred
if len(frames) < size: # check if there are any free frames
frames.append(page) # if so, place page in a free frame
else:
# the frames are full, so we must replace the frame
# that will not be used for the longest period of time
upcoming_pages = pages[page_index+1:]
frame_to_replace = find_victim_frame(frames, upcoming_pages)
# replace the victim frame with the new page
pos = frames.index(frame_to_replace)
frames.remove(frame_to_replace)
frames.insert(pos, page)
return page_faults
def find_victim_frame(frames, upcoming_pages):
"""
Helper function for the OPT algorithm to find the the victim frame (frame
to replace) i.e. the frame that will not be used for the longest time.
Parameters:
frames (list): A list of the frames in memory e.g [0, 3, 5]
pages (list): A page reference string e.g. [1, 2, 3, 5, 1, 2, 3, 5]
Returns:
int: The frame that will not be used for the longest time - hence,
the frame to replace in the OPT algorithm
"""
frame_to_replace = frames[0] # initialize to first frame
max_time_till_use = 0 # initialize to zero
# loop through frames in memory to find the frame to replace
for frame in frames:
# check if the frame is never referenced in the future
# if so, we can replace this frame
if frame not in upcoming_pages:
frame_to_replace = frame
break
# find the next usage and time until the frame is next used
for (i, upcoming_page) in enumerate(upcoming_pages, 1):
if frame == upcoming_page:
time_till_use = i
break
# check if this frame has the current longest time till use
if time_till_use > max_time_till_use:
max_time_till_use = time_till_use
frame_to_replace = frame
return frame_to_replace
def generate_page_reference_string(N):
"""
Generates a random page-reference string of length N
where page numbers range from 0 to 9
Parameters:
N (int): The desired length of the page reference string
Returns:
list: a list of page references e.g. [0,2,4,1,2,3]
"""
pages = [] # Stores the page-reference string
for i in range(N):
pages.append(randint(0, 9)) # Generates a random integer from 0-9
return pages
def main():
"""
A randomly generated page-reference string is applied to each of the FIFO,
LRU and optimal page replacement algorithms, and the number of page faults
incurred by each algorithm is recorded.
"""
N = int(input("Enter the length of the page reference string: "))
pages = generate_page_reference_string(N)
print "Page reference string: ", pages
size = int(sys.argv[1]) # number of frames in memory
print "FIFO", FIFO(size, pages), "page faults."
print "LRU", LRU(size, pages), "page faults."
print "OPT", OPT(size, pages), "page faults."
if __name__ == "__main__":
if len(sys.argv) != 2:
print "Usage: python paging.py [number of pages]"
else:
main()
|
Java
|
UTF-8
| 3,048 | 1.867188 | 2 |
[
"BSD-3-Clause",
"IJG",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-boost-original",
"LicenseRef-scancode-unknown-license-reference",
"libtiff",
"MIT",
"Apache-2.0"
] |
permissive
|
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2018 by PDFTron Systems Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------
package com.pdftron.pdf.tools;
import android.graphics.Color;
import android.support.annotation.Keep;
import android.support.annotation.NonNull;
import com.pdftron.common.PDFNetException;
import com.pdftron.pdf.Annot;
import com.pdftron.pdf.ColorPt;
import com.pdftron.pdf.ColorSpace;
import com.pdftron.pdf.Field;
import com.pdftron.pdf.Font;
import com.pdftron.pdf.PDFDoc;
import com.pdftron.pdf.PDFViewCtrl;
import com.pdftron.pdf.Rect;
import com.pdftron.pdf.annots.Widget;
import com.pdftron.pdf.tools.ToolManager.ToolMode;
import com.pdftron.pdf.utils.Utils;
import com.pdftron.sdf.Obj;
import java.util.UUID;
/**
* This class is for creating multiline text field
*/
@Keep
public class TextFieldCreate extends RectCreate {
private boolean mIsMultiline;
private int mJustification;
/**
* Class constructor
*/
public TextFieldCreate(PDFViewCtrl ctrl) {
this(ctrl, true, Field.e_left_justified);
}
/**
* Class constructor
*/
public TextFieldCreate(PDFViewCtrl ctrl, boolean isMultiline, int justification) {
super(ctrl);
mIsMultiline = isMultiline;
mJustification = justification;
}
/**
* The overload implementation of {@link Tool#getToolMode()}.
*/
@Override
public ToolManager.ToolModeBase getToolMode() {
return ToolMode.FORM_TEXT_FIELD_CREATE;
}
@Override
public int getCreateAnnotType() {
return Annot.e_Widget;
}
@Override
protected Annot createMarkup(@NonNull PDFDoc doc, Rect bbox) throws PDFNetException {
String fieldName = UUID.randomUUID().toString();
Field field = doc.fieldCreate(fieldName, Field.e_text);
Widget annot = Widget.create(doc, bbox,field);
ColorPt colorPt = Utils.color2ColorPt(Color.WHITE);
annot.setBackgroundColor(colorPt, ColorSpace.e_device_rgb);
field.setFlag(Field.e_multiline, mIsMultiline);
field.setJustification(mJustification);
annot.getSDFObj().putString(PDFTRON_ID, "");
// change font size
// https://groups.google.com/forum/#!msg/pdfnet-sdk/FWmdwfup8c8/cVWfN9AwDQAJ
Font font = Font.create(doc, Font.e_helvetica, false);
Obj acroForm = doc.getAcroForm();
if (null == acroForm) {
acroForm = doc.getRoot().putDict("AcroForm");
}
Obj dr = acroForm.findObj("DR");
if (null == dr) {
dr = acroForm.putDict("DR");
}
Obj fonts = dr.findObj("Font");
if (null == fonts) {
fonts = dr.putDict("Font");
}
fonts.put("Helv", font.GetSDFObj());
annot.getSDFObj().putString("DA", "/Helv 16 Tf 0 g");
return annot;
}
}
|
Markdown
|
UTF-8
| 1,190 | 2.90625 | 3 |
[] |
no_license
|
## Project Overview
A React based Covid-19 tracker to get information about the worldwide cases for different countries using an interactive map based interface and using <a href='https://disease.sh/docs/#/COVID-19%3A%20Worldometers'>disease.sh</a> apis
## Demo URL
https://covid-19-tracker-fcaff.web.app/
## Demo Images
<img src='./src/assets/darkMode.png'>
<img src='./src/assets/lightMode.png'>
<img src='./src/assets/recovered.png'>
<img src='./src/assets/deaths.png'>
## Steps to run
### Clone the repo
<code>git clone https://github.com/dineshnadimpalli/React-Covid-19-Tracker.git</code>
### Install the dependencies
<code>npm i</code>
### Start the project
<code>npm start</code>
## API References
All the APIs used in this project are taken from <a href='disease.sh'>disease.sh</a> which provides open-source APIs on disease information
1) <code>/v3/covid-19/all</code>
To get global COVID-19 totals for today, yesterday and two days ago
2) <code>/v3/covid-19/countries</code> To get COVID-19 totals for all countries
3) <code>/v3/covid-19/historical/all</code> To get global accumulated COVID-19 time series data
## Happy Coding ✌️👨🏻💻
|
Swift
|
UTF-8
| 5,682 | 2.703125 | 3 |
[] |
no_license
|
//
// MovieDetailViewController.swift
// movies_app
//
// Created by Uno qualunque on 03/10/21.
//
import UIKit
class MovieDetailViewController: UIViewController {
var movieTitleLabel: UILabel!
var movieOriginalTitleLabel: UILabel!
var movieImageView: UIImageView!
var movieOverviewTextView: UITextView!
var moviePopularityLabel: UILabel!
var movieOriginalLanguageLabel: UILabel!
var movieReleaseDateLabel: UILabel!
var movieTitle: String?
var movie: Movie?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.largeTitleDisplayMode = .never
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareTheFilm))
title = movie?.title
view.backgroundColor = .white
movieTitleLabel = UILabel()
movieOriginalTitleLabel = UILabel()
movieImageView = UIImageView()
movieOverviewTextView = UITextView()
moviePopularityLabel = UILabel()
movieOriginalLanguageLabel = UILabel()
movieReleaseDateLabel = UILabel()
movieTitleLabel.text = movie?.title
movieTitleLabel.translatesAutoresizingMaskIntoConstraints = false
movieOriginalTitleLabel.text = movie?.original_title
movieOriginalTitleLabel.font = UIFont.preferredFont(forTextStyle: .title1)
movieOriginalTitleLabel.numberOfLines = 0
if movie!.original_language == "en" {
movieOriginalTitleLabel.text = movie?.original_title
} else {
movieOriginalTitleLabel.text = "\(movie!.title) / \(movie!.original_title)"
}
movieOriginalTitleLabel.translatesAutoresizingMaskIntoConstraints = false
let url = URL(string: "https://image.tmdb.org/t/p/original\(movie!.backdrop_path)")!
let data = try? Data(contentsOf: url)
movieImageView.image = UIImage(data: data!)
movieImageView.translatesAutoresizingMaskIntoConstraints = false
movieOverviewTextView.text = movie!.overview
movieOverviewTextView.font = UIFont.systemFont(ofSize: 16)
movieOverviewTextView.isUserInteractionEnabled = false
movieOverviewTextView.isScrollEnabled = false
movieOverviewTextView.translatesAutoresizingMaskIntoConstraints = false
moviePopularityLabel.text = "Popularity: \(movie!.popularity)"
moviePopularityLabel.translatesAutoresizingMaskIntoConstraints = false
movieOriginalLanguageLabel.text = movie!.original_language.uppercased()
movieOriginalLanguageLabel.translatesAutoresizingMaskIntoConstraints = false
movieReleaseDateLabel.text = movie!.release_date.replacingOccurrences(of: "-", with: "/")
movieReleaseDateLabel.translatesAutoresizingMaskIntoConstraints = false
addSubViews()
addConstraints()
}
func addSubViews() {
view.addSubview(movieOriginalTitleLabel)
view.addSubview(movieImageView)
view.addSubview(movieOverviewTextView)
view.addSubview(moviePopularityLabel)
view.addSubview(movieOriginalLanguageLabel)
view.addSubview(movieReleaseDateLabel)
}
func addConstraints() {
let layout = view.layoutMarginsGuide
NSLayoutConstraint.activate([
movieImageView.topAnchor.constraint(equalTo: layout.topAnchor),
movieImageView.leftAnchor.constraint(equalTo: view.leftAnchor),
movieImageView.rightAnchor.constraint(equalTo: view.rightAnchor),
movieImageView.heightAnchor.constraint(equalToConstant: 270),
movieOriginalTitleLabel.topAnchor.constraint(equalTo: movieImageView.bottomAnchor, constant: 10),
movieOriginalTitleLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 13),
movieOriginalTitleLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -10),
movieOverviewTextView.topAnchor.constraint(equalTo: movieOriginalTitleLabel.bottomAnchor),
movieOverviewTextView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 10),
movieOverviewTextView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -10),
moviePopularityLabel.topAnchor.constraint(equalTo: movieOverviewTextView.bottomAnchor, constant: -4),
moviePopularityLabel.leftAnchor.constraint(equalTo: layout.leftAnchor, constant: -5),
movieOriginalLanguageLabel.bottomAnchor.constraint(equalTo: layout.bottomAnchor),
movieOriginalLanguageLabel.leftAnchor.constraint(equalTo: layout.leftAnchor),
movieReleaseDateLabel.bottomAnchor.constraint(equalTo: layout.bottomAnchor),
movieReleaseDateLabel.rightAnchor.constraint(equalTo: layout.rightAnchor)
])
}
@objc func shareTheFilm() {
let text = "I suggest you to watch this movie: \(movie!.title)"
let vc = UIActivityViewController(activityItems: [text], applicationActivities: nil)
vc.popoverPresentationController?.sourceView = self.view
self.present(vc, animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
Markdown
|
UTF-8
| 1,898 | 2.828125 | 3 |
[] |
no_license
|
# Sudoku Solver
This is the world-known **Sudoku game**. <br>
I did this project to learn about the **Backtracking Algorithm** and because I like Sudoku and found the project funny.
<br>
<br>
## Game Mechanics
The board it self is in the [working.py](https://github.com/henrique-efonseca/Portfolio/blob/master/Sudoku/working.py) file, so you just need to run the file and it will automatically solve the board. If you want you can change the board in the file.
```
python working.py
- - - - - - - - - - - - -
7 8 0 | 4 0 0 | 1 2 0
6 0 0 | 0 7 5 | 0 0 9
0 0 0 | 6 0 1 | 0 7 8
- - - - - - - - - - - - -
0 0 7 | 0 4 0 | 2 6 0
0 0 1 | 0 5 0 | 9 3 0
9 0 4 | 0 6 0 | 0 0 5
- - - - - - - - - - - - -
0 7 0 | 3 0 0 | 0 1 2
1 2 0 | 0 0 7 | 4 0 0
0 4 9 | 2 0 6 | 0 0 7
solving sudoku...
- - - - - - - - - - - - -
7 8 5 | 4 3 9 | 1 2 6
6 1 2 | 8 7 5 | 3 4 9
4 9 3 | 6 2 1 | 5 7 8
- - - - - - - - - - - - -
8 5 7 | 9 4 3 | 2 6 1
2 6 1 | 7 5 8 | 9 3 4
9 3 4 | 1 6 2 | 7 8 5
- - - - - - - - - - - - -
5 7 8 | 3 9 4 | 6 1 2
1 2 6 | 5 8 7 | 4 9 3
3 4 9 | 2 1 6 | 8 5 7
```
<br>
One good and simple addiction (and that I'll maybe add in the fucture) to this project would be to let the user add '.txt' files with boards and then the program would prompt for the file name of the file containing the board to be solved.
<br>
To use the GUI version (it doesn't have a solver built-in) you just need to run the [GUI.py](https://github.com/henrique-efonseca/Portfolio/blob/master/Sudoku/GUI.py) .
Note: You'll need to have pygame installed.
<br>
<br>

<br>
I did this project based on the Tutorial of [Tec With Tim](https://techwithtim.net/tutorials/python-programming/sudoku-solver-backtracking/).
<br>
<br>
---
© [Henrique Fonseca](https://github.com/henrique-efonseca)
|
Java
|
UTF-8
| 2,301 | 2.65625 | 3 |
[] |
no_license
|
package com.ejushang.steward.message;
import com.ejushang.steward.common.grabber.Message;
import com.ejushang.steward.common.grabber.MessageType;
import com.ejushang.steward.ordercenter.domain.OriginalOrder;
import com.ejushang.steward.ordercenter.domain.OriginalRefund;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* 源消息队列持有者,管理抓取与分析线程的交互
*
* User: liubin
* Date: 13-12-27
*/
@Component
public class MessageHolder {
private final Logger log = LoggerFactory.getLogger(MessageHolder.class);
public static final int MAX_MESSAGE_COUNTS = 10000;
private LinkedBlockingQueue<Message> queue = new LinkedBlockingQueue<Message>(MAX_MESSAGE_COUNTS);
/**
* 往队列放入原始订单信息
* @param originalOrders
* @return
*/
public boolean addOrders(List<OriginalOrder> originalOrders) {
return add(new Message(originalOrders, MessageType.ORDER));
}
/**
* 往队列放入原始订单主键
* @param originalOrderIds
* @return
*/
public boolean addOrderIds(List<Integer> originalOrderIds) {
return add(new Message(originalOrderIds, MessageType.ORDER_ID));
}
/**
* 往队列放入原始退款信息
* @param originalRefunds
* @return
*/
public boolean addRefunds(List<OriginalRefund> originalRefunds) {
return add(new Message(originalRefunds, MessageType.REFUND));
}
/**
* 往队列放入元素
* @param grabberMessage
* @return
*/
private boolean add(Message grabberMessage) {
try {
queue.offer(grabberMessage, 10, TimeUnit.SECONDS);
return true;
} catch (InterruptedException e) {
log.warn("往队列放消息的阻塞过程被中断,队列已满?", e);
}
return false;
}
/**
* 取出队列中的所有元素
* @return
*/
public List<Message> fetchAll() {
List<Message> allMessages = new ArrayList<Message>();
queue.drainTo(allMessages);
return allMessages;
}
}
|
Java
|
UTF-8
| 6,473 | 1.84375 | 2 |
[] |
no_license
|
package com.yxytech.parkingcloud.core.entity;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.FieldFill;
import com.yxytech.parkingcloud.core.enums.ApproveEnum;
import com.yxytech.parkingcloud.core.enums.OrgNatureEnum;
import com.yxytech.parkingcloud.core.utils.SuperModel;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
*
* </p>
*
* @author cj
* @since 2017-10-18
*/
@TableName("yxy_organzation")
public class Organization extends SuperModel<Organization> {
private static final long serialVersionUID = 1L;
@TableId
private Long id;
@TableField("org_nature")
private OrgNatureEnum orgNature;
@TableField("full_name")
private String fullName;
@TableField("short_name")
private String shortName;
@TableField("register_address")
private String registerAddress;
@TableField("legal_represent_ative")
private String legalRepresentAtive;
@TableField("taxpayer_number")
private String taxpayerNumber;
@TableField("phone_number")
private String phoneNumber;
private String email;
@TableField("org_number")
private String orgNumber;
@TableField("registration_number")
private String registrationNumber;
@TableField("approve_status")
private ApproveEnum approveStatus;
@TableField("is_property_org")
private Boolean isPropertyOrg;
@TableField("is_manage_org")
private Boolean isManageOrg;
@TableField("is_facility_org")
private Boolean isFacilityOrg;
@TableField("is_regulatory")
private Boolean isRegulatory;
@TableField(value = "created_by", fill=FieldFill.INSERT)
private Long createdBy;
@TableField(value = "created_at", fill=FieldFill.INSERT)
private Date createdAt;
@TableField(value = "updated_by", fill=FieldFill.INSERT_UPDATE)
private Long updatedBy;
@TableField(value = "updated_at", fill=FieldFill.INSERT_UPDATE)
private Date updatedAt;
@TableField("is_valid")
private Boolean isValid;
@TableField("area_id")
private Long areaId;
@TableField("org_number_certificate")
private String orgNumberCertificate;
private transient String areaName;
public Boolean getRegulatory() {
return isRegulatory;
}
public void setRegulatory(Boolean regulatory) {
isRegulatory = regulatory;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public OrgNatureEnum getOrgNature() {
return orgNature;
}
public void setOrgNature(OrgNatureEnum orgNature) {
this.orgNature = orgNature;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public String getRegisterAddress() {
return registerAddress;
}
public void setRegisterAddress(String registerAddress) {
this.registerAddress = registerAddress;
}
public String getLegalRepresentAtive() {
return legalRepresentAtive;
}
public void setLegalRepresentAtive(String legalRepresentAtive) {
this.legalRepresentAtive = legalRepresentAtive;
}
public String getTaxpayerNumber() {
return taxpayerNumber;
}
public void setTaxpayerNumber(String taxpayerNumber) {
this.taxpayerNumber = taxpayerNumber;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getOrgNumber() {
return orgNumber;
}
public void setOrgNumber(String orgNumber) {
this.orgNumber = orgNumber;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public void setRegistrationNumber(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public ApproveEnum getApproveStatus() {
return approveStatus;
}
public void setApproveStatus(ApproveEnum approveStatus) {
this.approveStatus = approveStatus;
}
public Boolean getPropertyOrg() {
return isPropertyOrg;
}
public void setPropertyOrg(Boolean propertyOrg) {
isPropertyOrg = propertyOrg;
}
public Boolean getManageOrg() {
return isManageOrg;
}
public void setManageOrg(Boolean manageOrg) {
isManageOrg = manageOrg;
}
public Boolean getFacilityOrg() {
return isFacilityOrg;
}
public void setFacilityOrg(Boolean facilityOrg) {
isFacilityOrg = facilityOrg;
}
public Long getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Long createdBy) {
this.createdBy = createdBy;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Long getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(Long updatedBy) {
this.updatedBy = updatedBy;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public Boolean getValid() {
return isValid;
}
public void setValid(Boolean valid) {
isValid = valid;
}
public Long getAreaId() {
return areaId;
}
public void setAreaId(Long areaId) {
this.areaId = areaId;
}
public String getOrgNumberCertificate() {
return orgNumberCertificate;
}
public void setOrgNumberCertificate(String orgNumberCertificate) {
this.orgNumberCertificate = orgNumberCertificate;
}
@Override
protected Serializable pkVal() {
return this.id;
}
@Override
public String toString() {
return "Organization{" +
"id=" + id +
", orgNature=" + orgNature +
", fullName=" + fullName +
", shortName=" + shortName +
", registerAddress=" + registerAddress +
", legalRepresentAtive=" + legalRepresentAtive +
", taxpayerNumber=" + taxpayerNumber +
", phoneNumber=" + phoneNumber +
", email=" + email +
", orgNumber=" + orgNumber +
", registrationNumber=" + registrationNumber +
", isPropertyOrg=" + isPropertyOrg +
", isManageOrg=" + isManageOrg +
", isFacilityOrg=" + isFacilityOrg +
", createdBy=" + createdBy +
", createdAt=" + createdAt +
", updatedBy=" + updatedBy +
", updatedAt=" + updatedAt +
", isValid=" + isValid +
", areaId=" + areaId +
"}";
}
}
|
C#
|
UTF-8
| 407 | 3.40625 | 3 |
[] |
no_license
|
using System.Text.RegularExpressions;
public class Program
{
public static string TextToNumberBinary(string str)
{
str = Regex.Replace(str, "zero", "0", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "one", "1", RegexOptions.IgnoreCase);
str = Regex.Replace(str, "[^01]", "");
int newLength = str.Length - (str.Length % 8);
return str.Substring(0, newLength);
}
}
|
Python
|
UTF-8
| 571 | 4.375 | 4 |
[] |
no_license
|
op = input(''' please try any math operator
+ for addition
- for substraction
/ for division
* for multiplication''')
print("enter your first number ")
n1 = int(input())
print("enter your second number")
n2 = int(input())
if (op=='+'):
print( "sum of these two numbers is", int(n1)+int(n2))
elif(op=='-'):
print("sum of these two numbers is", int(n1)-int(n2))
elif(op=='/'):
print("sum of these two numbers is", int(n1)/int(n2))
elif(op=='*'):
print("sum of these two numbers is", int(n1)*int(n2))
else:
print("you`ve not types a valid operator")
|
Swift
|
UTF-8
| 4,943 | 2.578125 | 3 |
[
"Apache-2.0"
] |
permissive
|
//
// captionViewController.swift
// Instagram
//
// Created by Wenn Huang on 3/12/17.
// Copyright © 2017 Wenn Huang. All rights reserved.
//
import UIKit
import Parse
class captionViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
@IBOutlet weak var createButton: UIButton!
@IBOutlet weak var postDescriptionTextField: UITextField!
@IBOutlet weak var submitPostButton: UIButton!
@IBOutlet weak var postImageView: UIImageView!
var picture : UIImage!
override func viewDidLoad() {
super.viewDidLoad()
clear()
// Do any additional setup after loading the view.
}
private func clear(){
postDescriptionTextField.text = ""
postDescriptionTextField.isEnabled = false
submitPostButton.isEnabled = false
postImageView.image = nil
createButton.isEnabled = true
createButton.alpha = 1
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func showAlert(title: String, message: String)
{
let alertView = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .cancel) {_ in /*Some Code to Execute*/}
alertView.addAction(action)
self.present(alertView, animated: true, completion: nil)
}
@IBAction func toAlbum(_ sender: UIButton) {
func showCamera(){
let cameraPicker = UIImagePickerController()
cameraPicker.delegate = self
cameraPicker.allowsEditing = true
cameraPicker.sourceType = .camera
self.present(cameraPicker, animated: true, completion: nil)
print("using camera")
}
func showAlbum(){
let cameraPicker = UIImagePickerController()
cameraPicker.delegate = self
cameraPicker.allowsEditing = true
cameraPicker.sourceType = .photoLibrary
self.present(cameraPicker, animated: true, completion: nil)
print ("using album")
}
let action = UIAlertController(title: "New Photo", message: nil, preferredStyle: .actionSheet)
action.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (UIAlertAction) in
showCamera()
}))
action.addAction(UIAlertAction(title: "Album", style: .default, handler: { (UIAlertAction) in
showAlbum()
}))
self.present(action, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
picture = image
postImageView.image = picture
postDescriptionTextField.isEnabled = true
submitPostButton.isEnabled = true
createButton.isEnabled = false
createButton.alpha = 0
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
@IBAction func onSaveButton(_ sender: Any) {
let resizedImage = self.resize(image: postImageView.image!, newSize: CGSize(width: 400, height: 400))
Post.postUserImage(image: resizedImage, withCaption: postDescriptionTextField.text) { (success, error) in
if success
{
self.showAlert(title: "Success", message: "Image Posted")
self.clear()
}
else
{
self.showAlert(title: "Error", message: (error?.localizedDescription)!)
}
}
}
private func resize(image: UIImage, newSize: CGSize) -> UIImage {
let resizeImageView = UIImageView(frame: CGRect(x:0,y:0,width:newSize.width,height:newSize.height))
resizeImageView.contentMode = UIViewContentMode.scaleAspectFill
resizeImageView.image = image
UIGraphicsBeginImageContext(resizeImageView.frame.size)
resizeImageView.layer.render(in: UIGraphicsGetCurrentContext()!)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
Java
|
UTF-8
| 960 | 2.203125 | 2 |
[] |
no_license
|
package com.example.engosama.newdiverapp.Utils;
import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.Window;
import android.view.WindowManager;
import com.example.engosama.newdiverapp.R;
public class Constants {
//This method fot change color of Status bar
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static void setStatusBarGradiant(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = activity.getWindow();
Drawable background = activity.getResources().getDrawable(R.drawable.bk_button_shape);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(activity.getResources().getColor(android.R.color.transparent));
window.setBackgroundDrawable(background);
}
}
}
|
C#
|
UTF-8
| 4,982 | 3.046875 | 3 |
[
"MIT"
] |
permissive
|
using System;
using NUnit.Framework;
using Xamarin.Forms.Maps;
namespace Xamarin.Forms.Core.UnitTests
{
[TestFixture]
public class DistanceTests : BaseTestFixture
{
[Test]
public void Constructor()
{
var distance = new Distance(25);
Assert.AreEqual(25, distance.Meters);
}
[Test]
public void ConstructFromKilometers()
{
const double EPSILON = 0.001;
Distance distance = Distance.FromKilometers(2);
Assert.True(Math.Abs(distance.Kilometers - 2) < EPSILON);
Assert.True(Math.Abs(distance.Meters - 2000) < EPSILON);
Assert.True(Math.Abs(distance.Miles - 1.24274) < EPSILON);
}
[Test]
public void ConstructFromMeters()
{
const double EPSILON = 0.001;
Distance distance = Distance.FromMeters(10560);
Assert.True(Math.Abs(distance.Meters - 10560) < EPSILON);
Assert.True(Math.Abs(distance.Miles - 6.5616798) < EPSILON);
Assert.True(Math.Abs(distance.Kilometers - 10.56) < EPSILON);
}
[Test]
public void ConstructFromMiles()
{
const double EPSILON = 0.001;
// Reached the limit of double precision using the number
// of miles of the earth's circumference
const double EPSILON_FOR_LARGE_MILES_TO_METERS = 16;
// Reached the limit of double precision
const double EPSILON_FOR_LARGE_MILES_TO_KM = 0.1;
Distance distance = Distance.FromMiles(3963.1676);
Assert.True(Math.Abs(distance.Miles - 3963.1676) < EPSILON);
Assert.True(Math.Abs(distance.Meters - 6378099.99805) < EPSILON_FOR_LARGE_MILES_TO_METERS);
Assert.True(Math.Abs(distance.Kilometers - 6378.09999805) < EPSILON_FOR_LARGE_MILES_TO_KM);
}
[Test]
public void ConstructFromPositions()
{
const double EPSILON = 0.001;
Position position1 = new Position(37.403992, -122.034988);
Position position2 = new Position(37.776691, -122.416534);
Distance distance = Distance.BetweenPositions(position1, position2);
Assert.True(Math.Abs(distance.Meters - 53363.08) < EPSILON);
Assert.True(Math.Abs(distance.Kilometers - 53.36308) < EPSILON);
Assert.True(Math.Abs(distance.Miles - 33.15828) < EPSILON);
}
[Test]
public void EqualityOp([Range(5, 9)] double x, [Range(5, 9)] double y)
{
bool result = Distance.FromMeters(x) == Distance.FromMeters(y);
if (x == y)
Assert.True(result);
else
Assert.False(result);
}
[Test]
public void Equals([Range(3, 7)] double x, [Range(3, 7)] double y)
{
bool result = Distance.FromMiles(x).Equals(Distance.FromMiles(y));
if (x == y)
Assert.True(result);
else
Assert.False(result);
}
[Test]
public void EqualsNull()
{
Assert.False(Distance.FromMeters(5).Equals(null));
}
[Test]
public void GettingAndSettingKilometers()
{
const double EPSILON = 0.001;
Distance distance = Distance.FromKilometers(1891);
Assert.True(Math.Abs(distance.Kilometers - 1891) < EPSILON);
}
[Test]
public void GettingAndSettingMeters()
{
const double EPSILON = 0.001;
Distance distance = Distance.FromMeters(123434);
Assert.True(Math.Abs(distance.Meters - 123434) < EPSILON);
}
[Test]
public void GettingAndSettingMiles()
{
const double EPSILON = 0.001;
Distance distance = Distance.FromMiles(515);
Assert.True(Math.Abs(distance.Miles - 515) < EPSILON);
}
[Test]
public void HashCode([Range(4, 5)] double x, [Range(4, 5)] double y)
{
Distance distance1 = Distance.FromMiles(x);
Distance distance2 = Distance.FromMiles(y);
bool result = distance1.GetHashCode() == distance2.GetHashCode();
if (x == y)
Assert.True(result);
else
Assert.False(result);
}
[Test]
public void InequalityOp([Range(5, 9)] double x, [Range(5, 9)] double y)
{
bool result = Distance.FromMeters(x) != Distance.FromMeters(y);
if (x != y)
Assert.True(result);
else
Assert.False(result);
}
[Test]
public void ObjectInitializerKilometers()
{
const double EPSILON = 0.001;
Distance distance = Distance.FromKilometers(10);
Assert.True(Math.Abs(distance.Meters - 10000) < EPSILON);
}
[Test]
public void ObjectInitializerMeters()
{
const double EPSILON = 0.001;
Distance distance = Distance.FromMeters(1057);
Assert.True(Math.Abs(distance.Kilometers - 1.057) < EPSILON);
}
[Test]
public void ObjectInitializerMiles()
{
const double EPSILON = 0.001;
Distance distance = Distance.FromMiles(100);
Assert.True(Math.Abs(distance.Meters - 160934.4) < EPSILON);
}
[Test]
public void ClampFromMeters()
{
var distance = Distance.FromMeters(-1);
Assert.AreEqual(0, distance.Meters);
}
[Test]
public void ClampFromMiles()
{
var distance = Distance.FromMiles(-1);
Assert.AreEqual(0, distance.Meters);
}
[Test]
public void ClampFromKilometers()
{
var distance = Distance.FromKilometers(-1);
Assert.AreEqual(0, distance.Meters);
}
[Test]
public void Equals()
{
Assert.True(Distance.FromMiles(2).Equals((object)Distance.FromMiles(2)));
}
}
}
|
C++
|
UTF-8
| 1,059 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
#ifndef PERLIN_NOISE_HPP
#define PERLIN_NOISE_HPP
#include <vector>
#include "random.hpp"
class PerlinNoise
{
public:
PerlinNoise();
explicit PerlinNoise(uint32_t seed);
virtual ~PerlinNoise();
PerlinNoise(const PerlinNoise& other);
PerlinNoise(PerlinNoise&& other);
PerlinNoise& operator= (const PerlinNoise& other);
PerlinNoise& operator= (PerlinNoise&& other);
void Seed(const uint32_t& seed);
uint32_t Seed() const;
double Noise(double x, double y, double z);
double OctaveNoise(double x, double y, double z, int total_octaves, double persistence);
private:
uint32_t m_seed;
std::vector<int> m_permutations;
double Fade(double t);
double Gradient(int hash, double x, double y, double z);
void GeneratePermutationVector();
//this functions is declared in the class to remove external dependencies
double Lerp(const double& start, const double& end, const double& t);
};
#endif//PERLIN_NOISE_HPP
|
JavaScript
|
UTF-8
| 132 | 3.015625 | 3 |
[] |
no_license
|
// Learned how to Create Decimal Numbers with JS
var ourDecimal = 5.7;
// Only change code below this line
var myDecimal = 5.7;
|
Markdown
|
UTF-8
| 2,785 | 2.71875 | 3 |
[
"Apache-2.0"
] |
permissive
|
# tsn_kinetics400
|模型名称|tsn_kinetics400|
| :--- | :---: |
|类别|视频-视频分类|
|网络|TSN|
|数据集|Kinetics-400|
|是否支持Fine-tuning|否|
|模型大小|95MB|
|最新更新日期|2021-02-26|
|数据指标|-|
## 一、模型基本信息
- ### 模型介绍
- TSN(Temporal Segment Network)是视频分类领域经典的基于2D-CNN的解决方案。该方法主要解决视频的长时间行为判断问题,通过稀疏采样视频帧的方式代替稠密采样,既能捕获视频全局信息,也能去除冗余,降低计算量。最终将每帧特征平均融合后得到视频的整体特征,并用于分类。TSN的训练数据采用由DeepMind公布的Kinetics-400动作识别数据集。该PaddleHub Module可支持预测。
- 具体网络结构可参考论文:[TSN](https://arxiv.org/abs/1608.00859)。
## 二、安装
- ### 1、环境依赖
- paddlepaddle >= 1.4.0
- paddlehub >= 1.0.0 | [如何安装PaddleHub](../../../../docs/docs_ch/get_start/installation.rst)
- ### 2、安装
- ```shell
$ hub install tsn_kinetics400
```
- 如您安装时遇到问题,可参考:[零基础windows安装](../../../../docs/docs_ch/get_start/windows_quickstart.md)
| [零基础Linux安装](../../../../docs/docs_ch/get_start/linux_quickstart.md) | [零基础MacOS安装](../../../../docs/docs_ch/get_start/mac_quickstart.md)
## 三、模型API预测
- ### 1、命令行预测
- ```shell
hub run tsn_kinetics400 --input_path "/PATH/TO/VIDEO"
```
或者
- ```shell
hub run tsn_kinetics400 --input_file test.txt
```
- Note: test.txt 存放待分类视频的存放路径
- 通过命令行方式实现文字识别模型的调用,更多请见 [PaddleHub命令行指令](../../../../docs/docs_ch/tutorial/cmd_usage.rst)
- ### 2、预测代码示例
- ```python
import paddlehub as hub
tsn = hub.Module(name="tsn_kinetics400")
test_video_path = "/PATH/TO/VIDEO"
# set input dict
input_dict = {"image": [test_video_path]}
# execute predict and print the result
results = tsn.video_classification(data=input_dict)
for result in results:
print(result)
```
- ### 3、API
- ```python
def video_classification(data)
```
- 用于视频分类预测
- **参数**
- data(dict): dict类型,key为image,str类型;value为待分类的视频路径,list类型。
- **返回**
- result(list\[dict\]): list类型,每个元素为对应输入视频的预测结果。预测结果为dict类型,key为label,value为该label对应的概率值。
## 五、更新历史
* 1.0.0
初始发布
- ```shell
$ hub install tsn_kinetics400==1.0.0
```
|
Java
|
UTF-8
| 778 | 3.84375 | 4 |
[] |
no_license
|
package myDay2;
public class ConstructorOverload {
int a;
double b;
String str;
public ConstructorOverload(int c,int d)
{
a=c+d;
}
public ConstructorOverload(double c,double d)
{
b=c*d;
}
public ConstructorOverload(String n)
{
str=n;
}
public static void main(String[] args)
{
ConstructorOverload res=new ConstructorOverload(2,3);
ConstructorOverload res1=new ConstructorOverload(2.0,3.0);
ConstructorOverload res2=new ConstructorOverload("Add and Mul");
System.out.println("Addition of 2 numbers is\t"+res.a);
System.out.println("Multiplication of 2 numbers is\t"+res1.b);
System.out.println(res2.str+" Are done successfully");
}
}
|
Python
|
UTF-8
| 1,539 | 2.890625 | 3 |
[
"Apache-2.0"
] |
permissive
|
"""
Implementation of the BaseAgent class.
"""
import numpy as np
from mesa import Agent
class BaseAgent(Agent):
"""
Extended base class for a MESA model agent.
Args:
unique_id (int): unique identifier of the agent.
pos (tuple): (x,y) coordinates of the agent in the 2D-grid.
model (CompassModel): CompassModel object.
params (Argparser): containing all parameter values.
"""
def __init__(self, unique_id, pos, model, params):
super().__init__(pos, model)
self.unique_id = unique_id
self.pos = pos
self.model = model
self.params = params
self.model.increment_agent_count()
def __repr__(self):
"""
Returns:
str: output string representing the unique identifier of the agent.
"""
return f"<BaseAgent object with unique_id: {self.unique_id}>"
def step(self, **kwargs):
"""
Perform an agent step.
Note:
Agents should have this method for the model to work.
"""
pass
def advance(self, **kwargs):
"""
Advance scheduled step.
Note:
Agents should have this method for the model to work.
"""
pass
def new_composition_array(self):
"""
Returns:
array: a new composition array with all values set to zero.
"""
n_attributes = len(self.params["group_types"][0])
composition = np.zeros(n_attributes)
return composition
|
C++
|
UTF-8
| 699 | 2.796875 | 3 |
[] |
no_license
|
#include "Globals.h"
#include <ctime>
//static member variables:
IrrlichtGfx* Globals::irrlichtGfx_ = 0;
User* Globals::user_ = 0;
Globals::Globals()
{
}
Globals::~Globals ()
{
}
void Globals::init ()
{
srand ((unsigned int)time(0) );
if(this->irrlichtGfx_ == 0)
{
this->irrlichtGfx_ = new IrrlichtGfx();
irrlichtGfx_->initIrrlicht ();
}
if(this->user_ == 0)
this->user_ = new User();
}
IrrlichtGfx* Globals::getIrrlichtGfx()
{
return Globals::irrlichtGfx_;
}
User* Globals::getUser ()
{
return Globals::user_;
}
void Globals::setIrrlichtGfx (IrrlichtGfx* irrlichtGfx)
{
irrlichtGfx_ = irrlichtGfx;
}
void Globals::setUser (User* user)
{
user_ = user;
}
|
C#
|
UTF-8
| 1,360 | 2.671875 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(characterStats))]
public class characterCombat : MonoBehaviour {
characterStats myStats;
public float attackDelay = .6f;
//public float attackSpeed = 1f;
private float attackCooldown = 0f;
private Animator anim;
// Call Back method to know when we are attacking
public event System.Action OnAttack;
void Start(){
anim = GetComponent<Animator> ();
myStats = GetComponent<characterStats> ();
}
void Update(){
attackCooldown -= Time.deltaTime;
}
public void Attack(characterStats targetStats){
if(attackCooldown <= 0f){
StartCoroutine (DoDamage (targetStats, attackDelay));
if (gameObject.tag != "Player") {
StartCoroutine (playSoundAfterSomeSec ());
}
if (OnAttack != null) {
OnAttack ();
}
attackCooldown = 1.2f;
}
}
// Add delay to allow the animation to play for example wiating the sword to fall on the enemy
// before actually do the damage
IEnumerator DoDamage (characterStats stats, float delay){
yield return new WaitForSeconds (delay);
anim.SetBool ("isAttacking", true);
stats.DamageTaken (myStats.damage.GetValue ());
}
IEnumerator playSoundAfterSomeSec (){
yield return new WaitForSeconds (1.5f);
FindObjectOfType<audioManager>().Play ("attackSword");
}
}
|
Shell
|
UTF-8
| 1,167 | 3.296875 | 3 |
[] |
no_license
|
#!/bin/sh
ls perl-tar/clam*gz perl-tar/Mail-Spam*gz
echo
echo -n 'ClamAV version number: '
read ClamVer
echo -n 'SpamAssassin version number: '
read SAVer
Filename=install-Clam-$ClamVer-SA-$SAVer.tar.gz
Pathname=/root/build/tar/$Filename
mkdir /tmp/clamsa.$$
BUILD=/tmp/clamsa.$$/install-Clam-$ClamVer-SA-$SAVer
mkdir $BUILD
chmod +x CheckModuleVersion install.sh
chmod -x functions.sh
cp CheckModuleVersion functions.sh install.sh $BUILD
cp -rp perl-tar $BUILD
rm -rf $BUILD/perl-tar/CVS
rm -rf $BUILD/perl-tar/*spec
cd $BUILD
cd ..
find . -type d -name .svn -exec rm -rf {} \;
tar czf $Pathname install-Clam-$ClamVer-SA-$SAVer
echo Result is in $Pathname
echo and should go in mailscanner/files/4/
echo
ls -l $Pathname
sleep 5
echo
echo Copying to server
echo -n 'Thump return to continue: '
read a
scp $Pathname admin@server.jules.fm:domains/mailscanner.info/public_html/files/4/
echo Making install-Clam-SA-latest.tar.gz link to install-Clam-$ClamVer-SA-$SAVer-tar.gz
ssh admin@server.jules.fm ln -nsf install-Clam-$ClamVer-SA-$SAVer.tar.gz domains/mailscanner.info/public_html/files/4/install-Clam-SA-latest.tar.gz
# Clean up
cd
rm -rf /tmp/clamsa.$$
|
Java
|
UTF-8
| 4,605 | 2.03125 | 2 |
[] |
no_license
|
package com.april.groupware.todo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.context.WebApplicationContext;
import com.april.groupware.cmn.SearchVO;
import com.april.groupware.todo.service.TodoVO;
import com.april.groupware.todo.service.imple.TodoDaoImpl;
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/root-context.xml",
"file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml"
})
public class TestTodoDao {
private final Logger LOG = LoggerFactory.getLogger(TestTodoDao.class);
@Autowired
WebApplicationContext webApplicationContext;
TodoVO board01;
TodoVO board02;
TodoVO board03;
TodoVO board04;
@Autowired
TodoDaoImpl dao;
@Test
@Ignore
public void doRetrieve() {
//1.전체 삭제
//2.추가:3건
//3.목록조회:3건
dao.doDeleteAll();
int flag = dao.doInsert(board01);
flag += dao.doInsert(board02);
flag += dao.doInsert(board03);
assertThat(flag, is(3));
SearchVO searchVO=new SearchVO(10,1,"10","_124");
List<TodoVO> list = (List<TodoVO>) dao.doRetrieve(searchVO);
assertThat(list.size(), is(3));
for(TodoVO vo: list) {
LOG.debug(vo.toString());
}
}
@Test
public void addAndGet() {
//1.전체 삭제
//2.추가
//3.단건조회
//4.수정
//5.비교
//1.전체 삭제
dao.doDeleteAll();
//2.추가:3건
int flag = dao.doInsert(board01);
flag += dao.doInsert(board02);
flag += dao.doInsert(board03);
assertThat(flag, is(3));
//3.단건조회:board01
TodoVO vsVO = (TodoVO) dao.doSelectOneTitle(board01);
//4.수정
vsVO.setDeptNm(vsVO.getDeptNm()+"_U");
vsVO.setpTitle(vsVO.getpTitle()+"_U");
vsVO.setpType(vsVO.getpType()+"_U");
vsVO.setCustomer(vsVO.getCustomer()+"_U");
vsVO.setTaskContents(vsVO.getTaskContents()+"_U");
vsVO.setArea(vsVO.getArea()+"_U");
vsVO.setWorkingForm(vsVO.getWorkingForm()+"_U");
vsVO.setModId(vsVO.getModId()+"_U");
//4.1 수정
flag = dao.doUpdate(vsVO);
assertThat(flag, is(1));
//4.2.단건조회
TodoVO orgVO = (TodoVO) dao.doSelectOne(vsVO);
}
@Test
@Ignore
public void doInsert() {
//1. 삭제
// dao.doDelete(board01);
// dao.doDelete(board02);
// dao.doDelete(board03);
// dao.doDeleteAll();
//2. 입력
int flag = dao.doInsert(board01);
flag += dao.doInsert(board02);
flag += dao.doInsert(board03);
LOG.debug("--------------");
LOG.debug("flag:"+flag);
LOG.debug("--------------");
assertThat(flag, is(3));
}
@Before
public void setUp() throws Exception {
LOG.debug("^^^^^^^^^^^");
LOG.debug("^WebApplicationContext^"+webApplicationContext);
LOG.debug("^^^^^^^^^^^");
board01=new TodoVO("1234_124","운영","PM작업","MAIN","무림","잘하고 있습니다","서울","외근","1234_124","1234_124","","");
board02=new TodoVO("5678_124","개발","PM작업","MAIN","무림","잘하고 있습니다","서울","외근","5678_124","5678_124","","");
board03=new TodoVO("9876_124","회계","PM작업","MAIN","무림","잘하고 있습니다","서울","외근","9876_124","9876_124","","");
board04=new TodoVO("1234_124","운영","PM작업","MAIN","무림","잘하고 있습니다","서울","외근","1234_124","1234_124","","");
}
@After
public void tearDown() throws Exception {
LOG.debug("^^^^^^^^^^^");
LOG.debug("^tearDown^");
LOG.debug("^^^^^^^^^^^");
}
@Test
@Ignore
public void test() {
LOG.debug("=====================");
LOG.debug("=test()=");
LOG.debug("=====================");
LOG.debug("=====================");
LOG.debug("=dao()="+dao);
LOG.debug("=====================");
assertNotNull(dao);
assertThat(1, is(1));
}
}
|
Java
|
UTF-8
| 2,454 | 2.1875 | 2 |
[] |
no_license
|
package com.xawl.car.exception;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import com.xawl.car.domain.err;
import com.xawl.car.util.DateUtil;
import com.xawl.car.util.JsonUtil;
import com.xawl.car.util.keyUtil;
/**
* 全局异常,跳转到404或者...
*
* @author kernel
*
*/
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
// 500错误
public class ExceptionResolver implements HandlerExceptionResolver {
private SqlSessionFactory sessionFactory;
@Autowired
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
this.sessionFactory = sqlSessionFactory;
}
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
err e1 = new err();
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
String msg=sw.toString();
e1.setJ_class(ex.getClass() + "");
e1.setMessage(msg);
e1.setDate(DateUtil.getSqlDate());
/* 使用response返回 */
SqlSession openSession = sessionFactory.openSession(true);
openSession.insert("com.xawl.car.dao.ErrorMapper.insert", e1);
response.setStatus(HttpStatus.OK.value()); // 设置状态码
response.setContentType(MediaType.APPLICATION_JSON_VALUE); // 设置ContentType
response.setCharacterEncoding("UTF-8"); // 避免乱码
response.setContentType("application/json;charset=UTF-8");
JSONObject jsonObjec = JsonUtil.createJson(keyUtil.SERVICE_ERROR);
jsonObjec.element("msg", "出现错误");
ex.printStackTrace();
response.setHeader("Cache-Control", "no-cache, must-revalidate");
try {
response.getWriter().print(jsonObjec.toString());
} catch (IOException e) {
openSession.close();
}
openSession.close();
return null;
}
}
|
Python
|
UTF-8
| 2,423 | 3.1875 | 3 |
[] |
no_license
|
import random
from AI.entity import Entity
class AI(Entity):
def __init__(self, name):
super().__init__(name)
self._stats_file_name = 'ai.stats'
self._wins = 0
self._loses = 0
self._attack_rate = 1.0
self._defend_rate = 1.0
self._read_stats()
def __del__(self):
self._write_stats()
def _read_stats(self):
with open(self._stats_file_name) as f:
for line in f:
status, value = line.split()
if status == 'wins':
self._wins = int(value)
elif status == 'loses':
self._loses = int(value)
elif status == 'attack_rate':
self._attack_rate = float(value)
elif status == 'defend_rate':
self._defend_rate = float(value)
def _write_stats(self):
with open('ai.stats', 'w') as f:
f.write(f'wins {self._wins}\n'
f'loses {self._loses}\n'
f'attack_rate {self._attack_rate}\n'
f'defend_rate {self._defend_rate}')
# Собственно псевдо разум нашего псевдо ИИ.
def update_stats(self, is_winner):
if is_winner:
self._wins += 1
if (self._wins - self._loses) < 5: # Если мы выиграли 5 раз подряд, то ничего не делаем
if self._attack_rate < self._defend_rate: # Если наши победы благодаря тому, что у нас высокий критерий защиты, то давайте его увеличим
self._defend_rate += 0.1
else: # Если же все это благодаря атаке, то нарастим ее.
self._attack_rate += 0.1
else:
self._loses += 1
if (self._wins - self._loses) < 5:
if self._defend_rate < self._attack_rate:
self._defend_rate += 0.1
else:
self._attack_rate += 0.1
def turn(self, enemy):
result = random.choices(['attack', 'defend'], [self._attack_rate, self._defend_rate])
result = result[0]
if result == 'attack':
self._attack(enemy)
else:
self._defend()
# ДЗ
# str rjust, ljust
|
Java
|
UTF-8
| 2,598 | 2.984375 | 3 |
[] |
no_license
|
package com.cookie.android.util;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.DecimalFormat;
/**
* FormatUtils
* Author: ZhangLingfei
* Date : 2018/12/15 0015
*/
public class FormatUtils {
/**
* 一亿
*/
private static final int YI_YI = 100000000;
/**
* 一万
*/
private static final int YI_WAN = 10000;
public static String formatBig(int number) {
return formatBig((long) number);
}
public static String formatBig(long number) {
DecimalFormat format;
String result;
if (number >= YI_YI) {
format = new DecimalFormat("0.0");
float temp = number / (float) YI_YI;
result = format.format(temp);
return result + "亿";
} else if (number >= YI_WAN) {
format = new DecimalFormat("0");
return format.format(number / YI_WAN) + "万";
}
return String.valueOf(number);
}
public static int limit(int min, int max, int value) {
if (value < min) {
value = min;
} else if (value > max) {
value = max;
}
return value;
}
public static String formatSmall(int number) {
if (number > 99) {
return "99+";
}
return String.valueOf(number);
}
public static int toInt(String s) {
return toInt(s, 0);
}
public static float toFloat(String s) {
try {
return Float.parseFloat(s);
} catch (NumberFormatException e) {
Logger.printException(e);
return 0;
}
}
public static int toInt(String s, int defValue) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
Logger.printException(e);
return defValue;
}
}
public static long toLong(String s) {
return toLong(s, 0);
}
public static short[] bytesToShort(byte[] bytes) {
if (bytes == null) {
return null;
}
short[] shorts = new short[bytes.length / 2];
ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts);
return shorts;
}
public static long toLong(String value, long defValue) {
try {
return Long.parseLong(value);
} catch (NumberFormatException e) {
Logger.printException(e);
return defValue;
}
}
}
|
Python
|
UTF-8
| 5,866 | 2.6875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import Optional, Union, Tuple, List, Dict
import pickle
import queue
import os
from pathlib import Path
from time import sleep
import vimeo_dl as vimeo
import requests
from bs4 import BeautifulSoup
from vimeodl import log
__all__ = ["VimeoDownloader"]
__http = requests.Session()
class VimeoLinkExtractor:
"""
Base class for parsing and extracting
links from vimeo website
"""
DOMAIN = "https://vimeo.com/"
def __init__(self, url):
self.videos = queue.Queue()
self.root_url = url.split(self.DOMAIN, maxsplit=1)[1]
self.waitTime = 1
def get_content(self, page_soup: BeautifulSoup):
contents = page_soup.find_all("div", attrs={"id": "browse_content"})
for content in contents:
lis = content.find_all("li")
for li in lis:
hrefs = li.find_all("a", href=True)
for href in hrefs:
if "/videos/page" not in href["href"]:
vid_uri = href["href"].split("/")[-1]
log.info("\tLink: {}{}".format(self.DOMAIN, vid_uri))
self.videos.put(self.DOMAIN + vid_uri)
@staticmethod
def has_next_page(soup: BeautifulSoup) -> bool:
n = soup.find_all("li", class_="pagination_next")
if len(n) is 0:
return False
if hasattr(n[0], n[0].a.text):
if n[0].a.text == "Next":
return True
return False
@staticmethod
def get_next_page(soup: BeautifulSoup) -> Optional[str]:
if VimeoLinkExtractor.has_next_page(soup):
n = soup.find_all("li", class_="pagination_next")
return n[0].a.get("href")
return None
def extract(self):
soup = fetch_page(self.DOMAIN + self.root_url)
if soup:
self.get_content(soup)
while True:
if self.has_next_page(soup):
next_url = self.DOMAIN + self.get_next_page(soup)
soup = fetch_page(next_url)
sleep(0.2)
self.get_content(soup)
if self.videos.qsize() % 100 == 0:
print("\n[Throttle for {} sec] \n".format(self.waitTime))
sleep(self.waitTime)
else:
break
return list(self.videos.queue)
class VimeoDownloader:
def __init__(self, url, out_dir, resume):
self.out_dir = out_dir
self.resume_file = Path(os.path.join(out_dir, "video_links.p"))
self.count = 0
self.total = None
self.vd = None
self.urls = list()
self.url = url
self.queue = queue.Queue()
# check if there's a file with links already
if resume and self.resume_file.is_file():
log.info("Loading urls from file\n")
with open(os.path.join(out_dir, "video_links.p"), "rb") as file:
self.urls = pickle.load(file)
else:
log.warning("Can't find resume file")
log.info("Extracting urls")
self.vd = VimeoLinkExtractor(self.url)
self.urls = self.vd.extract()
log.info("Resume file: " + out_dir + os.sep + "video_links.p")
with open(os.path.join(out_dir, "video_links.p"), "wb") as file:
pickle.dump(self.urls, file)
self.total = len(self.urls)
log.info("Found {} videos\n".format(self.total))
def download(self):
for url in self.urls: # put all links in a queue
self.queue.put(url)
while not self.queue.empty():
url = self.queue.get()
video = vimeo.new(url, size=True, basic=True)
print(
"Title: {} - Duration: {} \nUrl: {}".format(
video.title, video.duration, url
)
)
streams = video.streams
log.info("Available Downloads: ")
for s in streams: # check available video quality
log.info(f"{s._itag}/{s._resolution}/{s._extension}")
best_video = video.getbest() # select the best quality
log.info(
f"Selecting best quality: {best_video._itag}/{best_video._resolution}/{best_video._extension}"
)
videopath = Path(
os.path.join(self.out_dir, video.title + "." + s._extension)
)
# check if the video in the link is already downloaded
if videopath.exists():
log.info(f"Already downloaded : {url}")
self.count += 1
else:
self.count += 1
log.info(f"Downloading... {self.count}/{self.total} {videopath}")
best_video.download(filepath=self.out_dir, quiet=False)
self.urls.remove(url) # remove downloaded link from the list
# save the updated list to a file to resume if something happens
# from there
pickle.dump(self.urls, open(self.out_dir + os.sep + "video_links.p", "wb"))
log.info("Download finished [{}/{}]: ".format(self.count, self.total), end="")
if self.count == self.total:
log.info("All videos downloaded successfully ")
os.remove(self.datadir + os.sep + "video_links.p")
else:
log.warning("Some videos failed to download run again")
def fetch_page(url: str) -> BeautifulSoup:
"""
Return BeautifulSoup object after successfully fetched url
:param url: Url like string
:return: BeautifulSoup object of url
"""
response = __http.get(url)
if response.status_code != 200:
response.raise_for_status()
return BeautifulSoup(response.text, "html.parser")
|
Java
|
UTF-8
| 11,649 | 1.585938 | 2 |
[] |
no_license
|
/* **DO NOT EDIT THIS FILE** */
/*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* This software is the proprietary information of Sun Microsystems, Inc.
* Use is subject to license terms.
*
* This is a part of the Squawk JVM.
*/
package com.sun.squawk.vm;
/**
* This class defines the native bytecodes used in the Squawk system.
* It was automatically generated as a part of the build process
* and should not be edited by hand.
*
* @author Nik Shaylor
*/
public final class Native {
public final static int java_lang_VM$addToClassStateCache = 0;
public final static int java_lang_VM$allocate = 1;
public final static int java_lang_VM$allocateVirtualStack = 2;
public final static int java_lang_VM$asKlass = 3;
public final static int java_lang_VM$asThread = 4;
public final static int java_lang_VM$callStaticNoParm = 5;
public final static int java_lang_VM$callStaticOneParm = 6;
public final static int java_lang_VM$deadbeef = 7;
public final static int java_lang_VM$executeCIO = 8;
public final static int java_lang_VM$executeCOG = 9;
public final static int java_lang_VM$executeGC = 10;
public final static int java_lang_VM$fatalVMError = 11;
public final static int java_lang_VM$getBranchCount = 12;
public final static int java_lang_VM$getFP = 13;
public final static int java_lang_VM$getGlobalAddr = 14;
public final static int java_lang_VM$getGlobalAddrCount = 15;
public final static int java_lang_VM$getGlobalInt = 16;
public final static int java_lang_VM$getGlobalIntCount = 17;
public final static int java_lang_VM$getGlobalOop = 18;
public final static int java_lang_VM$getGlobalOopCount = 19;
public final static int java_lang_VM$getGlobalOopTable = 20;
public final static int java_lang_VM$getMP = 21;
public final static int java_lang_VM$getPreviousFP = 22;
public final static int java_lang_VM$getPreviousIP = 23;
public final static int java_lang_VM$hasVirtualMonitorObject = 24;
public final static int java_lang_VM$hashcode = 25;
public final static int java_lang_VM$invalidateClassStateCache = 26;
public final static int java_lang_VM$isBigEndian = 27;
public final static int java_lang_VM$removeVirtualMonitorObject = 28;
public final static int java_lang_VM$serviceResult = 29;
public final static int java_lang_VM$setGlobalAddr = 30;
public final static int java_lang_VM$setGlobalInt = 31;
public final static int java_lang_VM$setGlobalOop = 32;
public final static int java_lang_VM$setPreviousFP = 33;
public final static int java_lang_VM$setPreviousIP = 34;
public final static int java_lang_VM$threadSwitch = 35;
public final static int java_lang_VM$zeroWords = 36;
public final static int java_lang_Address$add = 37;
public final static int java_lang_Address$addOffset = 38;
public final static int java_lang_Address$and = 39;
public final static int java_lang_Address$diff = 40;
public final static int java_lang_Address$eq = 41;
public final static int java_lang_Address$fromObject = 42;
public final static int java_lang_Address$fromPrimitive = 43;
public final static int java_lang_Address$hi = 44;
public final static int java_lang_Address$hieq = 45;
public final static int java_lang_Address$isMax = 46;
public final static int java_lang_Address$isZero = 47;
public final static int java_lang_Address$lo = 48;
public final static int java_lang_Address$loeq = 49;
public final static int java_lang_Address$max = 50;
public final static int java_lang_Address$ne = 51;
public final static int java_lang_Address$or = 52;
public final static int java_lang_Address$roundDown = 53;
public final static int java_lang_Address$roundDownToWord = 54;
public final static int java_lang_Address$roundUp = 55;
public final static int java_lang_Address$roundUpToWord = 56;
public final static int java_lang_Address$sub = 57;
public final static int java_lang_Address$subOffset = 58;
public final static int java_lang_Address$toObject = 59;
public final static int java_lang_Address$toUWord = 60;
public final static int java_lang_Address$zero = 61;
public final static int java_lang_UWord$and = 62;
public final static int java_lang_UWord$eq = 63;
public final static int java_lang_UWord$fromPrimitive = 64;
public final static int java_lang_UWord$hi = 65;
public final static int java_lang_UWord$hieq = 66;
public final static int java_lang_UWord$isMax = 67;
public final static int java_lang_UWord$isZero = 68;
public final static int java_lang_UWord$lo = 69;
public final static int java_lang_UWord$loeq = 70;
public final static int java_lang_UWord$max = 71;
public final static int java_lang_UWord$ne = 72;
public final static int java_lang_UWord$or = 73;
public final static int java_lang_UWord$toInt = 74;
public final static int java_lang_UWord$toOffset = 75;
public final static int java_lang_UWord$toPrimitive = 76;
public final static int java_lang_UWord$zero = 77;
public final static int java_lang_Offset$add = 78;
public final static int java_lang_Offset$bytesToWords = 79;
public final static int java_lang_Offset$eq = 80;
public final static int java_lang_Offset$fromPrimitive = 81;
public final static int java_lang_Offset$ge = 82;
public final static int java_lang_Offset$gt = 83;
public final static int java_lang_Offset$isZero = 84;
public final static int java_lang_Offset$le = 85;
public final static int java_lang_Offset$lt = 86;
public final static int java_lang_Offset$ne = 87;
public final static int java_lang_Offset$sub = 88;
public final static int java_lang_Offset$toInt = 89;
public final static int java_lang_Offset$toPrimitive = 90;
public final static int java_lang_Offset$toUWord = 91;
public final static int java_lang_Offset$wordsToBytes = 92;
public final static int java_lang_Offset$zero = 93;
public final static int java_lang_Unsafe$charAt = 94;
public final static int java_lang_Unsafe$copyTypes = 95;
public final static int java_lang_Unsafe$getAsByte = 96;
public final static int java_lang_Unsafe$getAsUWord = 97;
public final static int java_lang_Unsafe$getByte = 98;
public final static int java_lang_Unsafe$getChar = 99;
public final static int java_lang_Unsafe$getInt = 100;
public final static int java_lang_Unsafe$getLong = 101;
public final static int java_lang_Unsafe$getLongAtWord = 102;
public final static int java_lang_Unsafe$getObject = 103;
public final static int java_lang_Unsafe$getShort = 104;
public final static int java_lang_Unsafe$getType = 105;
public final static int java_lang_Unsafe$getUWord = 106;
public final static int java_lang_Unsafe$setAddress = 107;
public final static int java_lang_Unsafe$setByte = 108;
public final static int java_lang_Unsafe$setChar = 109;
public final static int java_lang_Unsafe$setInt = 110;
public final static int java_lang_Unsafe$setLong = 111;
public final static int java_lang_Unsafe$setLongAtWord = 112;
public final static int java_lang_Unsafe$setObject = 113;
public final static int java_lang_Unsafe$setShort = 114;
public final static int java_lang_Unsafe$setType = 115;
public final static int java_lang_Unsafe$setUWord = 116;
public final static int java_lang_CheneyCollector$memoryProtect = 117;
public final static int java_lang_ServiceOperation$cioExecute = 118;
public final static int java_lang_Lisp2Bitmap$clearBitFor = 119;
public final static int java_lang_Lisp2Bitmap$clearBitsFor = 120;
public final static int java_lang_Lisp2Bitmap$getAddressForBitmapWord = 121;
public final static int java_lang_Lisp2Bitmap$getAddressOfBitmapWordFor = 122;
public final static int java_lang_Lisp2Bitmap$iterate = 123;
public final static int java_lang_Lisp2Bitmap$setBitFor = 124;
public final static int java_lang_Lisp2Bitmap$testAndSetBitFor = 125;
public final static int java_lang_Lisp2Bitmap$testBitFor = 126;
public final static int java_lang_VM$lcmp = 127;
/*if[FLOATS]*/
public final static int java_lang_VM$fcmpl = 128;
public final static int java_lang_VM$fcmpg = 129;
public final static int java_lang_VM$dcmpl = 130;
public final static int java_lang_VM$dcmpg = 131;
public final static int java_lang_VM$math = 132;
public final static int java_lang_VM$floatToIntBits = 133;
public final static int java_lang_VM$doubleToLongBits = 134;
public final static int java_lang_VM$intBitsToFloat = 135;
public final static int java_lang_VM$longBitsToDouble = 136;
/*end[FLOATS]*/
public final static int ENTRY_COUNT = /*VAL*/false/*FLOATS*/ ? 137 : 128;
}
|
JavaScript
|
UTF-8
| 3,159 | 3.203125 | 3 |
[] |
no_license
|
import React, { useState } from "react";
import "./styles.css";
var books = {
"Think Like A Monk": [
{
name:
"Remember, saying whatever we want, whenever we want, however we want, is not freedom. Real freedom is not feeling the need to say these things."
},
{ name: "Cancers of the Mind : Comparing, Complaining, Criticizing." },
{
name:
"The more we define ourselves in relation to the people around us, the more lost we are."
},
{
name:
"In 1902, the sociologist Charles Horton Cooley wrote: ''I am not what I think I am, and I am not what you think I am. I am what I think you think I am''."
},
{
name:
"The less time you fixate on everyone else, the more time you have to focus on yourself"
}
],
"Atomic Habits": [
{
name:
"''Every action you take is a vote for the type of person you wish to become. No single instance will transform your beliefs, but as the votes build up, so does the evidence of your new identity''."
},
{ name: "''Habit are the compound interest of self-improvement''." },
{
name:
"''Goals are good for setting a direction but systems are the best for making progress''."
},
{
name:
"''Success is the product of daily habit -- not once in a lifetime transformation''."
},
{
name:
"''We all deal with setback but in long run, the quality of our lives depends on the quality of our habits''."
}
],
"The Alchemist": [
{
name:
"''And, when you want something, all the universe consipre in helping you to achive it.''"
},
{
name:
"''It's the possibility of having a dream come true that makes life interesting.''"
},
{
name:
"''The simple things are also the most extraordinary things, and only the wise can see them.''"
},
{
name:
"''Why do we have to listen to our hearts?'' the boy asked. ''Because, wherever your heart is, that is where you will find your treasure.''"
},
{
name:
"''There is only one thing that makes a dream impossible to achieve: the fear of failure.''"
}
]
};
var arrayOfBooks = Object.keys(books); //Conversting Object to array so that we can use it in map function
export default function App() {
var [selectedbooks, setSelectedbooks] = useState("Think Like A Monk");
function booksClickHandler(booksNameReceived) {
selectedbooks = booksNameReceived;
setSelectedbooks(selectedbooks);
}
//View
return (
<div className="App">
<h1>Quotes App</h1>
<h4>5 Quotes From Different Books </h4>
<div>
{arrayOfBooks.map((booksName) => {
return (
<button
key={booksName}
onClick={() => booksClickHandler(booksName)}
>
{booksName}
</button>
);
})}
</div>
<div>
{books[selectedbooks].map((quotesList) => {
return (
<ul>
<li>{quotesList.name}</li>
</ul>
);
})}
</div>
</div>
);
}
|
Python
|
UTF-8
| 2,154 | 3.140625 | 3 |
[] |
no_license
|
import numpy as np
from CtrlSys import CtrlSys as cs
class Pod(object):
""" A pod looks like:
r_3 -- r_0
| \ / |
| CM |
| / \ |
r_2 __ r_1
With mass equally distributed over the square.
Attributes:
ctrlSys: a CtrlSys object that computes the thruster forces
note: This class is sort-of unnecessary right now, but if I
build alternative 'controllers', it will be useful to
have a wrapper that maintains the thruster location
and direction data... (?)
"""
def __init__(self, m, body_l):
"""Return a new Pod object"""
# relative and scalable thrust vectors & thruster positions
base_d = zip([1,1,-1,-1, 1, -1], [1,-1,-1,1, 0, 0], [0,0,0,0,0,0])
base_r = zip([1,1,-1,-1, 1, -1], [1,-1,-1,1, 1, 1], [0,0,0,0,0,0])
# r is a 6x3 matrix of the thruster positions
# relative to the pod's center (center of mass)
r = np.matrix(
[[body_l * x, body_l * y, body_l * z] for x,y,z in base_r]
)
# d is a 6x3 matrix of the directions of the
# force exerted by each thruster, relative
# to the pod's center
d = np.matrix(
[[x / np.sqrt(np.power(x,2) + np.power(y,2)),
y / np.sqrt(np.power(x,2) + np.power(y,2)), z] for x,y,z in base_d]
)
# J is the moment of inertia matrix (needed to be
# calculated out by hand)
J = np.identity(3) * m * np.power(body_l, 2) / 6
# M is the mass matrix
M = m * np.identity(3)
self.ctrlSys = cs(M, J, r, d)
def calcNewLocalVel(self, v, w, percent):
self.ctrlSys.calcF(v, w, percent)
return self.ctrlSys.predictDeltaV(v, w)
def getThrusterForces(self):
return self.ctrlSys.getF()
if __name__ == '__main__':
p = Pod(40, 10)
v = np.transpose(np.matrix([10,10,0]))
w = np.transpose(np.matrix([0,0,10]))
percent = .7
p.ctrlSys.calcF(v,w,percent)
print(p.ctrlSys.F)
|
PHP
|
UTF-8
| 758 | 2.859375 | 3 |
[] |
no_license
|
<?php
namespace VSamPlugin\Front;
/**
* The public-facing functionality of the plugin.
*
* Defines the plugin name, version, and two examples hooks for how to
* enqueue the public-facing stylesheet and JavaScript.
*
*/
class FrontModule{
private $plugin_name;
private $version;
public function __construct( $plugin_name, $version ) {
$this->plugin_name = $plugin_name;
$this->version = $version;
}
public function enqueue_styles() {
wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/public.css', array(), $this->version, 'all' );
}
public function enqueue_scripts() {
wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/public.js', array( 'jquery' ), $this->version, false );
}
}
|
Python
|
UTF-8
| 402 | 3.265625 | 3 |
[] |
no_license
|
def minimumNumber(a,n):
count = 0
if any(i.isdigit() for i in a) == False:
count += 1
if any(i.islower() for i in a) == False:
count += 1
if any(i.isupper() for i in a) == False:
count += 1
if any(i in "!@#$%^&*()-+" for i in a) == False:
count += 1
return max(count,6-n)
n = int(input())
password = input()
print(minimumNumber(password,n))
|
PHP
|
UTF-8
| 899 | 3.046875 | 3 |
[] |
no_license
|
<?php
class LogHandler extends Handler
{
// VARIABLES
/**
* @var LogHandler
*/
private static $INSTANCE;
/**
* @var LogDao
*/
private $logDao;
// /VARIABLES
// CONSTRUCTOR
public function __construct( LogDbDao $logDao )
{
$this->logDao = $logDao;
self::$INSTANCE = $this;
}
// /CONSTRUCTOR
// FUNCTIONS
/**
* @param LogModel $log
*/
public function handle( LogModel $log )
{
if ( $this->logDao )
$this->logDao->add( $log );
}
/**
* @param LogModel $log
*/
public static function doLog( LogModel $log )
{
if ( self::$INSTANCE )
{
$instance = self::$INSTANCE;
$instance->handle( $log );
}
}
// /FUNCTIONS
}
?>
|
Go
|
UTF-8
| 3,041 | 3.609375 | 4 |
[] |
no_license
|
package robot
import (
"errors"
"testing"
)
type input struct {
x int
y int
direction string
}
func TestPlace(t *testing.T) {
tests := []struct {
name string
in input
out *Robot
err error
}{
{
name: "Place OK",
in: input{0, 0, "NORTH"},
out: &Robot{0, 0, "NORTH"},
err: nil,
},
}
for _, test := range tests {
t.Logf("case: %s", test.name)
actual, _ := Place(test.in.x, test.in.y, test.in.direction)
expected := test.out
if actual.X != expected.X || actual.Y != expected.Y || actual.Direction != expected.Direction {
t.Errorf("got %v, want %v for output", actual, expected)
}
}
}
func TestPlace_WithInvalid(t *testing.T) {
tests := []struct {
name string
in input
out *Robot
err error
}{
{
name: "Place with invalid position",
in: input{0, 6, "NORTH"},
out: nil,
err: nil,
},
{
name: "Place with invalid direction",
in: input{0, 0, "NOWHERE"},
out: nil,
err: nil,
},
}
for _, test := range tests {
t.Logf("case: %s", test.name)
actual, _ := Place(test.in.x, test.in.y, test.in.direction)
expected := test.out
if actual != expected {
t.Errorf("got %v, want %v for output", actual, expected)
}
}
}
func TestMove(t *testing.T) {
tests := []struct {
name string
in *Robot
out *Robot
err error
}{
{
name: "Move North",
in: &Robot{0, 0, "NORTH"},
out: &Robot{0, 1, "NORTH"},
err: nil,
},
{
name: "Move South",
in: &Robot{0, 1, "SOUTH"},
out: &Robot{0, 0, "SOUTH"},
err: nil,
},
{
name: "Move EAST",
in: &Robot{0, 1, "EAST"},
out: &Robot{1, 1, "EAST"},
err: nil,
},
{
name: "Move WEST",
in: &Robot{4, 1, "WEST"},
out: &Robot{3, 1, "WEST"},
err: nil,
},
{
name: "Move Past Edge",
in: &Robot{0, 3, "WEST"},
out: &Robot{0, 3, "WEST"},
err: errors.New("Error: Robot trying to move out of bound."),
},
}
for _, test := range tests {
t.Logf("case: %s", test.name)
actual, _ := Move(test.in)
expected := test.out
// if err != nil {
// t.Errorf("Error %v", err)
// }
if actual.X != expected.X || actual.Y != expected.Y || actual.Direction != expected.Direction {
t.Errorf("got %v, want %v for output", actual, expected)
}
}
}
func TestReport(t *testing.T) {
expected := "Output: 4,4,SOUTH"
robot, err := Place(4, 4, "SOUTH")
if err != nil {
t.Errorf("Robot failed to place")
}
actual := ReportPosition(robot)
if actual != expected {
t.Errorf("Expected %v but got %v", expected, actual)
}
}
func TestLeft(t *testing.T) {
robot, err := Place(0, 0, "NORTH")
if err != nil {
t.Errorf("There should be no error")
}
robot = RotateLeft(robot)
if robot.Direction != "WEST" {
t.Errorf("Robot has not turned left")
}
}
func TestRight(t *testing.T) {
robot, err := Place(0, 0, "NORTH")
if err != nil {
t.Errorf("There should be no error")
}
robot = RotateRight(robot)
if robot.Direction != "EAST" {
t.Errorf("Robot has not turned right")
}
}
|
Java
|
UTF-8
| 2,649 | 2.78125 | 3 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package zrkc.group.new_ui.component;
import zrkc.group.javabean.ShowImg;
import zrkc.group.javabean.User;
import zrkc.group.new_ui.component.Listener.ClassImgMouseListener;
import javax.swing.*;
import java.awt.*;
//需要将ClassInfoFrame声明之后再声明
public class ClassImg extends JPanel {
private ShowImg showImg = null;
private User user = null;
private JLabel text = null;
private JLabel image = null;
private MainPanel mainPanel = null;
int x;
int y;
int w;
int h;
public ClassImg(int x, int y, int w, int h, int i_w, int i_h, ShowImg img, User user, MainPanel panel){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.setLayout(null);
this.setBounds(x, y, w, h + i_h);
this.showImg = img;
this.user = user;
this.mainPanel = panel;
addImage();
addText(i_w, i_h);
}
private void addImage(){
image = new JLabel();
if(showImg == null || showImg.getImg() == null)
System.out.println("no");
System.out.println("y");
ImageIcon icon = new ImageIcon(showImg.getImg());
icon.setImage(icon.getImage().getScaledInstance(w, h, Image.SCALE_DEFAULT));
image.setBounds(0,0, w, h);
image.setIcon(icon);
image.addMouseListener(new ClassImgMouseListener(mainPanel));
this.add(image);
}
private void addText(int i_w, int i_h){
String name = user.getName();
text = new JLabel();
text.setText(name);
Font font = new Font("黑体", Font.PLAIN, i_h);
text.setFont(font);
text.setForeground(Color.BLUE);
text.setBounds(get_x(i_h, name), h, i_w*name.length(),i_h);//位置需要居中
text.addMouseListener(new ClassImgMouseListener(mainPanel));
this.add(text);
}
private int get_x(int i_h, String name){
int length = w;
int middle = w / 2;
int len = 0;
char ch;
for(int i = 0; i < name.length(); i++){
ch = name.charAt(i);
if(isChinese(ch))
{
len += 2;
continue;
}
len += 1;
}
int word_len = len * i_h;
int x = middle - word_len / 4;
return x;
}
private boolean isChinese(char ch){
try{
return String.valueOf(ch).getBytes("UTF-8").length > 1;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
}
|
Markdown
|
UTF-8
| 1,415 | 3.625 | 4 |
[
"Apache-2.0"
] |
permissive
|
# hex
A simple tool to encode and decode hexadecimal data.
## Install
```sh
go install github.com/maraino/hex
```
## Usage
No brainer functionality, just three flags and four features.
```sh
$ hex --help
Usage: hex [<filename>]
-c encodes the input as hexadecimal followed by characters
-d decodes input
-p encoded using a prettier format aa:bb
```
### Encode
Encodes a file or the standard input to hexadecimal.
```sh
$ echo Hello World! > hello.txt
$ hex hello.txt
48656c6c6f20576f726c64210a
```
```sh
$ echo Hello World! | hex
48656c6c6f20576f726c64210a
```
Or encode to a prettier format:
```sh
$ echo Hello World! | hex -p
48:65:6c:6c:6f:20:57:6f:72:6c:64:21:0a
```
### Decode
Decodes an hexadecimal string:
```sh
$ echo 48656c6c6f20576f726c64210a | hex -d
Hello World!
```
You can also use a file or a different formatting, it will ignore any
non-hexadecimal character:
```sh
$ echo 48:65:6C:6C:6F:20:57:6F:72:6C:64:21:0A > hello.hex
$ hex -d hello.hex
Hello World!
```
### Hex dump
Returns an hex dump of the given data, like `hexdump -C`:
```sh
$ hex -c hello.txt
00000000 48 65 6c 6c 6f 20 57 6f 72 6c 64 21 0a |Hello World!.|
```
### Decode and dump
Combines `-d` and `-c` to first decode and then dump:
```sh
$ echo 48:65:6C:6C:6F:20:57:6F:72:6C:64:21:0A | hex -d -c
00000000 48 65 6c 6c 6f 20 57 6f 72 6c 64 21 0a |Hello World!.|
```
|
JavaScript
|
UTF-8
| 763 | 3.921875 | 4 |
[] |
no_license
|
/*
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101
Example 2:
Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.
Example 3:
Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.
Example 4:
Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.
*/
/**
* @param {number} n
* @return {boolean}
*/
var hasAlternatingBits = function(n) {
for(i = n % 2; n !== 0; i++) {
n >>= 1;
if (n % 2 === i % 2) {
return false;
}
}
return true;
};
console.log(hasAlternatingBits(10));
|
C#
|
UTF-8
| 2,205 | 3.203125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TopologicalSort
{
class Program
{
static void Main(string[] args)
{
int[,] adjMat = new int[,] { { 0, 1, 0, 1, 0, 0 },
{ 0, 0, 1, 1, 0, 0 },
{ 0, 0, 0, 1, 1, 1 },
{ 0, 0, 0, 0, 1, 1 },
{ 0, 0, 0, 0, 0, 1 },
{ 0, 0, 0, 0, 0, 0 }};
int[] arr = TopologicSortBFS(adjMat);
for (int i = 0; i < arr.Length; i++)
{
Console.Write(" " + arr[i] + ", ");
}
}
public static int[] TopologicSortBFS(int[,] adjMat)
{
int V = adjMat.GetLength(0);
int[] T = new int[V];
int[] visited = new int[V];
int[] in_degree = new int[V];
Queue<int> q = new Queue<int>();
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
if (adjMat[i, j] == 1)
in_degree[j]++;//degin of vertax j.
}
}
for (int i = 0; i < V; i++)
{
if (in_degree[i] == 0)
{
q.Enqueue(i);
visited[i] = 1;
}
}
int curVertax;
int current = 0;
while (q.Count != 0)
{
curVertax = q.Dequeue();
T[current++] = curVertax;
for (int i = 0; i < V; i++)
{
if (adjMat[curVertax, i] > 0 && visited[i] == 0)
{
in_degree[i] = in_degree[i] - 1;
if (in_degree[i] == 0)
{
q.Enqueue(i);
visited[i] = 1;
}
}
}
}
return T;
}
}
}
|
C++
|
UTF-8
| 31,336 | 2.546875 | 3 |
[] |
no_license
|
/*
* Ocean General Circulation Modell ( OGCM ) applied to laminar flow
* Program for the computation of geo-atmospherical circulating flows in a spherical shell
* Finite difference scheme for the solution of the 3D Navier-Stokes equations
* with 2 additional transport equations to describe the water vapour and co2 concentration
* 4. order Runge-Kutta scheme to solve 2. order differential equations
*
* class to write sequel, transfer and paraview files
*/
#include <iostream>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <Utils.h>
#include "PostProcess_Hyd.h"
using namespace std;
using namespace AtomUtils;
PostProcess_Hydrosphere::PostProcess_Hydrosphere(int im, int jm, int km,
const string &output_path){
this->im = im;
this->jm = jm;
this->km = km;
this->output_path = output_path;
}
PostProcess_Hydrosphere::~PostProcess_Hydrosphere() {}
void PostProcess_Hydrosphere::dump_array(const string &name, Array &a,
double multiplier, ofstream &f){
f << " <DataArray type=\"Float32\" Name=\"" << name << "\" format=\"ascii\">\n";
for (int k = 0; k < km; k++){
for (int j = 0; j < jm; j++){
for (int i = 0; i < im; i++){
f << (a.x[i][j][k] * multiplier) << endl;
}
f << "\n";
}
f << "\n";
}
f << "\n";
f << " </DataArray>\n";
}
void PostProcess_Hydrosphere::dump_radial(const string &desc, Array &a,
double multiplier, int i, ofstream &f){
f << "SCALARS " << desc << " float " << 1 << endl;
f << "LOOKUP_TABLE default" << endl;
for (int j = 0; j < jm; j++){
for (int k = 0; k < km; k++){
f << (a.x[i][j][k] * multiplier) << endl;
}
}
}
void PostProcess_Hydrosphere::dump_radial_2d(const string &desc, Array_2D &a,
double multiplier, ofstream &f){
f << "SCALARS " << desc << " float " << 1 << endl;
f << "LOOKUP_TABLE default" << endl;
for (int j = 0; j < jm; j++){
for (int k = 0; k < km; k++){
f << (a.y[j][k] * multiplier) << endl;
}
}
}
void PostProcess_Hydrosphere::dump_zonal(const string &desc, Array &a,
double multiplier, int k, ofstream &f){
f << "SCALARS " << desc << " float " << 1 << endl;
f << "LOOKUP_TABLE default" << endl;
for ( int i = 0; i < im; i++ ){
for ( int j = 0; j < jm; j++ ){
f << (a.x[ i ][ j ][ k ] * multiplier) << endl;
}
}
}
void PostProcess_Hydrosphere::dump_longal(const string &desc, Array &a,
double multiplier, int j, ofstream &f)
{
f << "SCALARS " << desc << " float " << 1 << endl;
f << "LOOKUP_TABLE default" << endl;
for (int i = 0; i < im; i++){
for (int k = 0; k < km; k++){
f << (a.x[i][j][k] * multiplier) << endl;
}
}
}
void PostProcess_Hydrosphere::paraview_vts ( const string &Name_Bathymetry_File,
int n, Array_1D &rad, Array_1D &the, Array_1D &phi,
Array &h, Array &t, Array &p, Array &u, Array &v,
Array &w, Array &c, Array &fup, Array &fvp,
Array &fwp, Array &fcp, Array &fpp, Array &ftp,
Array &aux_u, Array &aux_v, Array &aux_w,
Array &Salt_Finger, Array &Buoyancy_Force,
Array &Salt_Balance ){
double x, y, z, sinthe, sinphi, costhe, cosphi;
// file administration
string Hydrosphere_vts_File_Name = output_path + "/[" + Name_Bathymetry_File + "]_Hyd" + std::to_string(n) + ".vts";
// string Hydrosphere_vts_File_Name << "/[" << Name_Bathymetry_File << "]_Hyd_Kreide_" << n << ".vts";
ofstream Hydrosphere_vts_File;
Hydrosphere_vts_File.precision ( 4 );
Hydrosphere_vts_File.setf ( ios::fixed );
string path = output_path + Name_Bathymetry_File;
Hydrosphere_vts_File.open (path);
if (!Hydrosphere_vts_File.is_open()){
cerr << "ERROR: could not open paraview_vts file " << __FILE__ << " at line " << __LINE__ << "\n";
abort();
}
Hydrosphere_vts_File << "<?xml version=\"1.0\"?>\n" << endl;
Hydrosphere_vts_File << "<VTKFile type=\"StructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">\n" << endl;
Hydrosphere_vts_File << " <StructuredGrid WholeExtent=\"" << 1 << " "<< im << " "<< 1 << " " << jm << " "<< 1 << " " << km << "\">\n" << endl;
Hydrosphere_vts_File << " <Piece Extent=\"" << 1 << " "<< im << " "<< 1 << " " << jm << " "<< 1 << " " << km << "\">\n" << endl;
// Hydrosphere_vts_File << " <PointData Vectors=\"Velocity Rotation\" Scalars=\"Topography Temperature Pressure Salinity u-Component v-Component w-Component\">\n" << endl;
Hydrosphere_vts_File << " <PointData Vectors=\"Velocity\" Scalars=\"Topography Temperature Pressure Salinity\">\n" << endl;
// writing u, v und w velocity components in cartesian coordinates
Hydrosphere_vts_File << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" Name=\"Velocity\" format=\"ascii\">\n" << endl;
for ( int k = 0; k < km; k++ ){
sinphi = sin( phi.z[ k ] );
cosphi = cos( phi.z[ k ] );
for ( int j = 0; j < jm; j++ ){
sinthe = sin( the.z[ j ] );
costhe = cos( the.z[ j ] );
for ( int i = 0; i < im; i++ ){
// transformation from spherical to cartesian coordinates for presentation in ParaView
fup.x[ i ][ j ][ k ] = sinthe * cosphi * u.x[ i ][ j ][ k ] + costhe * cosphi *
v.x[ i ][ j ][ k ] - sinphi * w.x[ i ][ j ][ k ];
fvp.x[ i ][ j ][ k ] = sinthe * sinphi * u.x[ i ][ j ][ k ] + sinphi * costhe *
v.x[ i ][ j ][ k ] + cosphi * w.x[ i ][ j ][ k ];
fwp.x[ i ][ j ][ k ] = costhe * u.x[ i ][ j ][ k ] - sinthe * v.x[ i ][ j ][ k ];
Hydrosphere_vts_File << fup.x[ i ][ j ][ k ] << " " << fvp.x[ i ][ j ][ k ]
<< " " << fwp.x[ i ][ j ][ k ] << endl;
}
Hydrosphere_vts_File << "\n" << endl;
}
Hydrosphere_vts_File << "\n" << endl;
}
Hydrosphere_vts_File << "\n" << endl;
Hydrosphere_vts_File << " </DataArray>\n" << endl;
// writing of sea ground
Hydrosphere_vts_File << " <DataArray type=\"Float32\" Name=\"Topography\" format=\"ascii\">\n" << endl;
for ( int k = 0; k < km; k++ ){
for ( int j = 0; j < jm; j++ ){
for ( int i = 0; i < im; i++ ){
Hydrosphere_vts_File << h.x[ i ][ j ][ k ] << endl;
}
Hydrosphere_vts_File << "\n" << endl;
}
Hydrosphere_vts_File << "\n" << endl;
}
Hydrosphere_vts_File << "\n" << endl;
Hydrosphere_vts_File << " </DataArray>\n" << endl;
// writing of temperature
Hydrosphere_vts_File << " <DataArray type=\"Float32\" Name=\"Temperature\" format=\"ascii\">\n" << endl;
for ( int k = 0; k < km; k++ ){
for ( int j = 0; j < jm; j++ ){
for ( int i = 0; i < im; i++ ){
Hydrosphere_vts_File << t.x[ i ][ j ][ k ] << endl;
}
Hydrosphere_vts_File << "\n" << endl;
}
Hydrosphere_vts_File << "\n" << endl;
}
Hydrosphere_vts_File << "\n" << endl;
Hydrosphere_vts_File << " </DataArray>\n" << endl;
// writing temperature
Hydrosphere_vts_File << " <DataArray type=\"Float32\" Name=\"Pressure\" format=\"ascii\">\n" << endl;
for ( int k = 0; k < km; k++ ){
for ( int j = 0; j < jm; j++ ){
for ( int i = 0; i < im; i++ ){
Hydrosphere_vts_File << p.x[ i ][ j ][ k ] << endl;
}
Hydrosphere_vts_File << "\n" << endl;
}
Hydrosphere_vts_File << "\n" << endl;
}
Hydrosphere_vts_File << "\n" << endl;
Hydrosphere_vts_File << " </DataArray>\n" << endl;
// writing scalar function c
Hydrosphere_vts_File << " <DataArray type=\"Float32\" Name=\"Salinity\" format=\"ascii\">\n" << endl;
for ( int k = 0; k < km; k++ ){
for ( int j = 0; j < jm; j++ ){
for ( int i = 0; i < im; i++ ){
Hydrosphere_vts_File << c.x[ i ][ j ][ k ] << endl;
}
Hydrosphere_vts_File << "\n" << endl;
}
Hydrosphere_vts_File << "\n" << endl;
}
Hydrosphere_vts_File << "\n" << endl;
Hydrosphere_vts_File << " </DataArray>\n" << endl;
Hydrosphere_vts_File << " </PointData>\n" << endl;
Hydrosphere_vts_File << " <Points>\n" << endl;
Hydrosphere_vts_File << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n" << endl;
// transformation from spherical to cartesian coordinates
for ( int k = 0; k < km; k++ ){
for ( int j = 0; j < jm; j++ ){
for ( int i = 0; i < im; i++ ){
x = rad.z[ i ] * sin( the.z[ j ] ) * cos ( phi.z[ k ] );
y = rad.z[ i ] * sin( the.z[ j ] ) * sin ( phi.z[ k ] );
z = rad.z[ i ] * cos( the.z[ j ] );
Hydrosphere_vts_File << x << " " << y << " " << z << endl;
}
Hydrosphere_vts_File << "\n" << endl;
}
Hydrosphere_vts_File << "\n" << endl;
}
Hydrosphere_vts_File << " </DataArray>\n" << endl;
Hydrosphere_vts_File << " </Points>\n" << endl;
Hydrosphere_vts_File << " </Piece>\n" << endl;
Hydrosphere_vts_File << " </StructuredGrid>\n" << endl;
Hydrosphere_vts_File << "</VTKFile>\n" << endl;
Hydrosphere_vts_File.close();
}
void PostProcess_Hydrosphere::paraview_panorama_vts ( const string &Name_Bathymetry_File,
int n, double &u_0, double &r_0_water, Array &h,
Array &t, Array &p_dyn, Array &p_stat, Array &r_water,
Array &r_salt_water, Array &u, Array &v, Array &w,
Array &c, Array &aux_u, Array &aux_v, Array &aux_w,
Array &Salt_Finger, Array &Salt_Diffusion, Array &Buoyancy_Force,
Array &Salt_Balance ){
double x, y, z, dx, dy, dz;
string Atmosphere_panorama_vts_File_Name = output_path + "/[" + Name_Bathymetry_File + "]_Hyd_panorama_" + std::to_string(n) + ".vts";
ofstream Hydrosphere_panorama_vts_File;
Hydrosphere_panorama_vts_File.precision ( 4 );
Hydrosphere_panorama_vts_File.setf ( ios::fixed );
Hydrosphere_panorama_vts_File.open(Atmosphere_panorama_vts_File_Name);
if (!Hydrosphere_panorama_vts_File.is_open()){
cerr << "ERROR: could not open panorama_vts file " << __FILE__ << " at line " << __LINE__ << "\n";
abort();
}
Hydrosphere_panorama_vts_File << "<?xml version=\"1.0\"?>\n" << endl;
Hydrosphere_panorama_vts_File << "<VTKFile type=\"StructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">\n" << endl;
Hydrosphere_panorama_vts_File << " <StructuredGrid WholeExtent=\"" << 1 << " "<< im << " "<< 1 << " " << jm << " "<< 1 << " " << km << "\">\n" << endl;
Hydrosphere_panorama_vts_File << " <Piece Extent=\"" << 1 << " "<< im << " "<< 1 << " " << jm << " "<< 1 << " " << km << "\">\n" << endl;
// Hydrosphere_panorama_vts_File << " <PointData Vectors=\"Velocity\" Scalars=\"Topography Temperature Pressure Salinity SaltFinger BuoyancyForce SaltBalance\">\n" << endl;
Hydrosphere_panorama_vts_File << " <PointData Vectors=\"Velocity\" Scalars=\"Topography Temperature PressureDynamic PressureStatic Salinity\">\n" << endl;
// writing u, v und w velocity components in cartesian coordinates
Hydrosphere_panorama_vts_File << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" Name=\"Velocity\" format=\"ascii\">\n" << endl;
for ( int k = 0; k < km; k++ ){
for ( int j = 0; j < jm; j++ ){
for ( int i = 0; i < im; i++ ){
// transformtion from spherical to cartesian coordinates for representation in ParaView
Hydrosphere_panorama_vts_File << u.x[ i ][ j ][ k ] << " " << v.x[ i ][ j ][ k ] << " " << w.x[ i ][ j ][ k ] << endl;
}
Hydrosphere_panorama_vts_File << "\n" << endl;
}
Hydrosphere_panorama_vts_File << "\n" << endl;
}
Hydrosphere_panorama_vts_File << "\n" << endl;
Hydrosphere_panorama_vts_File << " </DataArray>\n" << endl;
dump_array("Topography", h, 1.0, Hydrosphere_panorama_vts_File);
dump_array("u-velocity", u, 1000.0, Hydrosphere_panorama_vts_File);
dump_array("v-velocity", v, 1.0, Hydrosphere_panorama_vts_File);
dump_array("w-velocity", w, 1.0, Hydrosphere_panorama_vts_File);
dump_array("Temperature", t, 1.0, Hydrosphere_panorama_vts_File);
dump_array("PressureDynamic", p_dyn, u_0 * u_0 * r_0_water * 1e-3, Hydrosphere_panorama_vts_File);
dump_array("PressureStatic", p_stat, 1.0, Hydrosphere_panorama_vts_File);
dump_array("Salinity", c, 1.0, Hydrosphere_panorama_vts_File);
dump_array("DensityWater", r_water, 1.0, Hydrosphere_panorama_vts_File);
dump_array("DensitySaltWater", r_salt_water, 1.0, Hydrosphere_panorama_vts_File);
dump_array("Salt_Finger", Salt_Finger, 1.0, Hydrosphere_panorama_vts_File);
dump_array("SaltDiffusion", Salt_Diffusion, 1.0, Hydrosphere_panorama_vts_File);
dump_array("SaltBalance", Salt_Balance, 1.0, Hydrosphere_panorama_vts_File);
dump_array("BuoyancyForce", Buoyancy_Force, 1.0, Hydrosphere_panorama_vts_File);
Hydrosphere_panorama_vts_File << " </PointData>\n" << endl;
Hydrosphere_panorama_vts_File << " <Points>\n" << endl;
Hydrosphere_panorama_vts_File << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n" << endl;
// writing cartesian coordinates
x = 0.;
y = 0.;
z = 0.;
dx = .025;
dy = .1;
dz = .1;
for ( int k = 0; k < km; k++ ){
for ( int j = 0; j < jm; j++ ){
for ( int i = 0; i < im; i++ ){
if ( k == 0 || j == 0 ) x = 0.;
else x = x + dx;
Hydrosphere_panorama_vts_File << x << " " << y << " " << z << endl;
}
x = 0;
y = y + dy;
Hydrosphere_panorama_vts_File << "\n" << endl;
}
y = 0;
z = z + dz;
Hydrosphere_panorama_vts_File << "\n" << endl;
}
Hydrosphere_panorama_vts_File << " </DataArray>\n" << endl;
Hydrosphere_panorama_vts_File << " </Points>\n" << endl;
Hydrosphere_panorama_vts_File << " </Piece>\n" << endl;
Hydrosphere_panorama_vts_File << " </StructuredGrid>\n" << endl;
Hydrosphere_panorama_vts_File << "</VTKFile>\n" << endl;
Hydrosphere_panorama_vts_File.close();
}
void PostProcess_Hydrosphere::paraview_vtk_longal ( const string &Name_Bathymetry_File,
int j_longal, int n, double &u_0, double &r_0_water,
Array &h, Array &p_dyn, Array &p_stat, Array &r_water,
Array &r_salt_water, Array &t, Array &u, Array &v, Array &w,
Array &c, Array &aux_u, Array &aux_v, Array &Salt_Finger,
Array &Salt_Diffusion, Array &Buoyancy_Force,
Array &Salt_Balance ){
double x, y, z, dx, dz;
i_max = im;
k_max = km;
string Hydrosphere_longal_File_Name = output_path + "/[" + Name_Bathymetry_File + "]_Hyd_longal_" + std::to_string(j_longal) + "_" + std::to_string(n) + ".vtk";
ofstream Hydrosphere_vtk_longal_File;
Hydrosphere_vtk_longal_File.precision ( 4 );
Hydrosphere_vtk_longal_File.setf ( ios::fixed );
Hydrosphere_vtk_longal_File.open(Hydrosphere_longal_File_Name);
if (!Hydrosphere_vtk_longal_File.is_open()){
cerr << "ERROR: could not open vtk_longal file " << __FILE__ << " at line " << __LINE__ << "\n";
abort();
}
Hydrosphere_vtk_longal_File << "# vtk DataFile Version 3.0" << endl;
Hydrosphere_vtk_longal_File << "Longitudinal_Data_Hydrosphere_Circulation\n";
Hydrosphere_vtk_longal_File << "ASCII" << endl;
Hydrosphere_vtk_longal_File << "DATASET STRUCTURED_GRID" << endl;
Hydrosphere_vtk_longal_File << "DIMENSIONS " << k_max << " "<< i_max << " " << 1 << endl;
Hydrosphere_vtk_longal_File << "POINTS " << i_max * k_max << " float" << endl;
// transformation from spherical to cartesian coordinates
x = 0.;
y = 0.;
z = 0.;
dx = .1;
dz = .025;
for ( int i = 0; i < im; i++ ){
for ( int k = 0; k < km; k++ ){
if ( k == 0 ) z = 0.;
else z = z + dz;
Hydrosphere_vtk_longal_File << x << " " << y << " "<< z << endl;
}
z = 0.;
x = x + dx;
}
Hydrosphere_vtk_longal_File << "POINT_DATA " << i_max * k_max << endl;
dump_longal("Topography", h, 1., j_longal, Hydrosphere_vtk_longal_File);
dump_longal("u-Component", u, 1000., j_longal, Hydrosphere_vtk_longal_File);
dump_longal("v-Component", v, 1., j_longal, Hydrosphere_vtk_longal_File);
dump_longal("w-Component", w, 1., j_longal, Hydrosphere_vtk_longal_File);
dump_longal("Temperature", t, 1., j_longal, Hydrosphere_vtk_longal_File);
dump_longal("PressureDynamic", p_dyn, u_0 * u_0 * r_0_water * 1e-3, j_longal, Hydrosphere_vtk_longal_File);
dump_longal("PressureStatic", p_stat, 1., j_longal, Hydrosphere_vtk_longal_File);
dump_longal("Salinity", c, 1., j_longal, Hydrosphere_vtk_longal_File);
dump_longal("DensityWater", r_water, 1., j_longal, Hydrosphere_vtk_longal_File);
dump_longal("DensitySaltWater", r_salt_water, 1., j_longal, Hydrosphere_vtk_longal_File);
dump_longal("SaltFinger", Salt_Finger, 1., j_longal, Hydrosphere_vtk_longal_File);
dump_longal("SaltDiffusion", Salt_Diffusion, 1., j_longal, Hydrosphere_vtk_longal_File);
dump_longal("SaltBalance", Salt_Balance, 1., j_longal, Hydrosphere_vtk_longal_File);
dump_longal("BuoyancyForce", Buoyancy_Force, 1., j_longal, Hydrosphere_vtk_longal_File);
// writing longitudinal u-w-cell structure
Hydrosphere_vtk_longal_File << "VECTORS u-w-Cell float" << endl;
for ( int i = 0; i < im; i++ ){
for ( int k = 0; k < km; k++ ){
Hydrosphere_vtk_longal_File << u.x[ i ][ j_longal ][ k ] << " " << y << " " << w.x[ i ][ j_longal ][ k ] << endl;
}
}
Hydrosphere_vtk_longal_File.close();
}
void PostProcess_Hydrosphere::paraview_vtk_radial ( const string &Name_Bathymetry_File,
int i_radial, int n, double &u_0, double &t_0, double &r_0_water,
Array &h, Array &p_dyn, Array &p_stat, Array &r_water,
Array &r_salt_water, Array &t, Array &u, Array &v, Array &w,
Array &c, Array &aux_u, Array &aux_v, Array &Salt_Finger,
Array &Salt_Diffusion, Array &Buoyancy_Force,
Array &Salt_Balance, Array_2D &Upwelling, Array_2D &Downwelling,
Array_2D &SaltFinger, Array_2D &SaltDiffusion,
Array_2D &BuoyancyForce, Array_2D &BottomWater,
Array_2D &Evaporation_Dalton, Array_2D &Precipitation,
Array_2D &Bathymetry ){
double x, y, z, dx, dy;
j_max = jm;
k_max = km;
string Hydrosphere_radial_File_Name = output_path + "/[" + Name_Bathymetry_File + "]_Hyd_radial_" + std::to_string(i_radial) + "_" + std::to_string(n) + ".vtk";
ofstream Hydrosphere_vtk_radial_File;
Hydrosphere_vtk_radial_File.precision ( 4 );
Hydrosphere_vtk_radial_File.setf ( ios::fixed );
Hydrosphere_vtk_radial_File.open(Hydrosphere_radial_File_Name);
if (!Hydrosphere_vtk_radial_File.is_open()){
cerr << "ERROR: could not open paraview_vtk file " << __FILE__ << " at line " << __LINE__ << "\n";
abort();
}
Hydrosphere_vtk_radial_File << "# vtk DataFile Version 3.0" << endl;
Hydrosphere_vtk_radial_File << "Radial_Data_Hydrosphere_Circulation\n";
Hydrosphere_vtk_radial_File << "ASCII" << endl;
Hydrosphere_vtk_radial_File << "DATASET STRUCTURED_GRID" << endl;
Hydrosphere_vtk_radial_File << "DIMENSIONS " << k_max << " "<< j_max << " " << 1 << endl;
Hydrosphere_vtk_radial_File << "POINTS " << j_max * k_max << " float" << endl;
// transformation from spherical to cartesian coordinates
x = 0.;
y = 0.;
z = 0.;
dx = .1;
dy = .1;
for ( int j = 0; j < jm; j++ ){
for ( int k = 0; k < km; k++ ){
if ( k == 0 ) y = 0.;
else y = y + dy;
Hydrosphere_vtk_radial_File << x << " " << y << " "<< z << endl;
}
y = 0.;
x = x + dx;
}
Hydrosphere_vtk_radial_File << "POINT_DATA " << j_max * k_max << endl;
// writing temperature
Hydrosphere_vtk_radial_File << "SCALARS Temperature float " << 1 << endl;
Hydrosphere_vtk_radial_File << "LOOKUP_TABLE default" <<endl;
for ( int j = 0; j < jm; j++ ){
for ( int k = 0; k < km; k++ ){
Hydrosphere_vtk_radial_File << t.x[ i_radial ][ j ][ k ] * t_0 - t_0 << endl;
aux_v.x[ i_radial ][ j ][ k ] = Evaporation_Dalton.y[ j ][ k ] - Precipitation.y[ j ][ k ];
if ( is_land( h, 0, j, k ) ) aux_v.x[ i_radial ][ j ][ k ] = 0.;
}
}
dump_radial("Topography", h, 1., i_radial, Hydrosphere_vtk_radial_File);
dump_radial_2d("Bathymetry_m", Bathymetry, 1., Hydrosphere_vtk_radial_File);
dump_radial("u-Component", u, 1000., i_radial, Hydrosphere_vtk_radial_File);
dump_radial("v-Component", v, 1., i_radial, Hydrosphere_vtk_radial_File);
dump_radial("w-Component", w, 1., i_radial, Hydrosphere_vtk_radial_File);
dump_radial("PressureDynamic", p_dyn, u_0 * u_0 * r_0_water * 1e-3, i_radial, Hydrosphere_vtk_radial_File);
dump_radial("PressureStatic", p_stat, 1., i_radial, Hydrosphere_vtk_radial_File);
dump_radial("Salinity", c, 1., i_radial, Hydrosphere_vtk_radial_File);
dump_radial("DensityWater", r_water, 1., i_radial, Hydrosphere_vtk_radial_File);
dump_radial("DensitySaltWater", r_salt_water, 1., i_radial, Hydrosphere_vtk_radial_File);
dump_radial("SaltFinger", Salt_Finger, 1., i_radial, Hydrosphere_vtk_radial_File);
dump_radial("SaltDiffusion", Salt_Diffusion, 1., i_radial, Hydrosphere_vtk_radial_File);
dump_radial("SaltBalance", Salt_Balance, 1., i_radial, Hydrosphere_vtk_radial_File);
dump_radial("BuoyancyForce", Buoyancy_Force, 1., i_radial, Hydrosphere_vtk_radial_File);
dump_radial_2d("Upwelling", Upwelling, 1., Hydrosphere_vtk_radial_File);
dump_radial_2d("Downwelling", Downwelling, 1., Hydrosphere_vtk_radial_File);
dump_radial_2d("BottomWater", BottomWater, 1., Hydrosphere_vtk_radial_File);
dump_radial_2d("Evaporation_Dalton", Evaporation_Dalton, 1., Hydrosphere_vtk_radial_File);
dump_radial_2d("Precipitation", Precipitation, 1., Hydrosphere_vtk_radial_File);
dump_radial("Evap-Precip", aux_v, 1., i_radial, Hydrosphere_vtk_radial_File);
Hydrosphere_vtk_radial_File << "VECTORS v-w-Cell float" << endl;
for ( int j = 0; j < jm; j++ ){
for ( int k = 0; k < km; k++ ){
Hydrosphere_vtk_radial_File << v.x[ i_radial ][ j ][ k ] << " " << w.x[ i_radial ][ j ][ k ] << " " << z << endl;
}
}
Hydrosphere_vtk_radial_File.close();
}
void PostProcess_Hydrosphere::paraview_vtk_zonal ( const string &Name_Bathymetry_File,
int k_zonal, int n, double &u_0, double &r_0_water,
Array &h, Array &p_dyn, Array &p_stat, Array &r_water,
Array &r_salt_water, Array &t, Array &u, Array &v,
Array &w, Array &c, Array &Salt_Finger, Array &Salt_Diffusion,
Array &Buoyancy_Force, Array &Salt_Balance ){
double x, y, z, dx, dy;
i_max = im;
j_max = jm;
streampos anfangpos, endpos;
string Hydrosphere_zongal_File_Name = output_path + "/[" + Name_Bathymetry_File + "]_Hyd_zonal_" + std::to_string(k_zonal) + "_" + std::to_string(n) + ".vtk";
ofstream Hydrosphere_vtk_zonal_File;
Hydrosphere_vtk_zonal_File.precision ( 4 );
Hydrosphere_vtk_zonal_File.setf ( ios::fixed );
Hydrosphere_vtk_zonal_File.open ( Hydrosphere_zongal_File_Name);
if (!Hydrosphere_vtk_zonal_File.is_open()){
cerr << "ERROR: could not open vtk_zonal file " << __FILE__ << " at line " << __LINE__ << "\n";
abort();
}
Hydrosphere_vtk_zonal_File << "# vtk DataFile Version 3.0" << endl;
Hydrosphere_vtk_zonal_File << "Zonal_Data_Hydrosphere_Circulation\n";
Hydrosphere_vtk_zonal_File << "ASCII" << endl;
Hydrosphere_vtk_zonal_File << "DATASET STRUCTURED_GRID" << endl;
Hydrosphere_vtk_zonal_File << "DIMENSIONS " << j_max << " "<< i_max << " " << 1 << endl;
Hydrosphere_vtk_zonal_File << "POINTS " << i_max * j_max << " float" << endl;
// transformation from spherical to cartesian coordinates
x = 0.;
y = 0.;
z = 0.;
dx = .1;
dy = .05;
for ( int i = 0; i < im; i++ ){
for ( int j = 0; j < jm; j++ ){
if ( j == 0 ) y = 0.;
else y = y + dy;
Hydrosphere_vtk_zonal_File << x << " " << y << " "<< z << endl;
}
y = 0.;
x = x + dx;
}
Hydrosphere_vtk_zonal_File << "POINT_DATA " << i_max * j_max << endl;
dump_zonal("Topography", h, 1., k_zonal, Hydrosphere_vtk_zonal_File);
dump_zonal("u-Component", u, 1000., k_zonal, Hydrosphere_vtk_zonal_File);
dump_zonal("v-Component", v, 1., k_zonal, Hydrosphere_vtk_zonal_File);
dump_zonal("w-Component", w, 1., k_zonal, Hydrosphere_vtk_zonal_File);
dump_zonal("Temperature", t, 1., k_zonal, Hydrosphere_vtk_zonal_File);
dump_zonal("PressureDynamic", p_dyn, u_0 * u_0 * r_0_water * 1e-3, k_zonal, Hydrosphere_vtk_zonal_File);
dump_zonal("PressureStatic", p_stat, 1., k_zonal, Hydrosphere_vtk_zonal_File);
dump_zonal("Salinity", c, 1., k_zonal, Hydrosphere_vtk_zonal_File);
dump_zonal("DensityWater", r_water, 1., k_zonal, Hydrosphere_vtk_zonal_File);
dump_zonal("DensitySaltWater", r_salt_water, 1., k_zonal, Hydrosphere_vtk_zonal_File);
dump_zonal("SaltFinger", Salt_Finger, 1., k_zonal, Hydrosphere_vtk_zonal_File);
dump_zonal("SaltDiffusion", Salt_Diffusion, 1., k_zonal, Hydrosphere_vtk_zonal_File);
dump_zonal("SaltBalance", Salt_Balance, 1., k_zonal, Hydrosphere_vtk_zonal_File);
dump_zonal("BuoyancyForce", Buoyancy_Force, 1., k_zonal, Hydrosphere_vtk_zonal_File);
Hydrosphere_vtk_zonal_File << "VECTORS u-v-Cell float" << endl;
for ( int i = 0; i < im; i++ ){
for ( int j = 0; j < jm; j++ ){
Hydrosphere_vtk_zonal_File << u.x[ i ][ j ][ k_zonal ] << " " << v.x[ i ][ j ][ k_zonal ] << " " << z << endl;
}
}
Hydrosphere_vtk_zonal_File.close();
}
void PostProcess_Hydrosphere::Atmosphere_TransferFile_read ( const string &Name_Bathymetry_File,
Array &v, Array &w, Array &t, Array &p, Array_2D &Evaporation_Dalton,
Array_2D &Precipitation ){
ifstream v_w_Transfer_File;
string Name_v_w_Transfer_File = output_path + "/[" + Name_Bathymetry_File + "]_Transfer_Atm.vw";
v_w_Transfer_File.precision(4);
v_w_Transfer_File.setf(ios::fixed);
v_w_Transfer_File.open(Name_v_w_Transfer_File);
if (!v_w_Transfer_File.is_open()){
cout << "ERROR: transfer file name in hydrosphere: " << Name_v_w_Transfer_File << "\n";
cerr << "ERROR: could not open transfer file " << __FILE__ << " at line " << __LINE__ << "\n";
abort();
}
for ( int j = 0; j < jm; j++ ){
for ( int k = 0; k < km; k++ ){
v_w_Transfer_File >> v.x[ im-1 ][ j ][ k ];
v_w_Transfer_File >> w.x[ im-1 ][ j ][ k ];
v_w_Transfer_File >> t.x[ im-1 ][ j ][ k ];
v_w_Transfer_File >> p.x[ im-1 ][ j ][ k ];
v_w_Transfer_File >> Evaporation_Dalton.y[ j ][ k ];
v_w_Transfer_File >> Precipitation.y[ j ][ k ];
p.x[ im-1 ][ j ][ k ] = 0.;
}
}
v_w_Transfer_File.close();
}
void PostProcess_Hydrosphere::Hydrosphere_PlotData ( const string &Name_Bathymetry_File,
int iter_cnt, double &u_0, Array &h, Array &v, Array &w,
Array &t, Array &c, Array_2D &BottomWater,
Array_2D & Upwelling, Array_2D & Downwelling ){
string path = output_path + "/[" + Name_Bathymetry_File + "]_PlotData_Hyd"+
(iter_cnt > 0 ? "_"+to_string(iter_cnt) : "")+".xyz";
ofstream PlotData_File(path);
PlotData_File.precision ( 4 );
PlotData_File.setf ( ios::fixed );
if (!PlotData_File.is_open()){
cerr << "ERROR: could not open PlotData file " << __FILE__ << " at line " << __LINE__ << "\n";
abort();
}
PlotData_File << "lons(deg)" << ", " << "lats(deg)" << ", " << "topography" << ", " << "v-velocity(m/s)" << ", "
<< "w-velocity(m/s)" << ", " << "velocity-mag(m/s)" << ", " << "temperature(Celsius)" << ", " << "salinity(psu)"
<< ", " << "bottom_water(m/s)" << ", " << "upwelling(m/s)" << ", " << "downwelling(m/s)" << endl;
for ( int k = 0; k < km; k++ ){
for ( int j = 0; j < jm; j++ ){
double vel_mag = sqrt ( pow ( v.x[ im-1 ][ j ][ k ] * u_0 , 2 ) + pow ( w.x[ im-1 ][ j ][ k ] * u_0, 2 ) );
PlotData_File << k << " " << 90-j << " " << h.x[ im-1 ][ j ][ k ] << " " << v.x[ im-1 ][ j ][ k ] * u_0
<< " " << w.x[ im-1 ][ j ][ k ] * u_0 << " " << vel_mag << " " << t.x[ im-1 ][ j ][ k ] * 273.15 - 273.15
<< " " << c.x[ im-1 ][ j ][ k ] * 35. << " " << BottomWater.y[ j ][ k ] << " " << Upwelling.y[ j ][ k ]
<< " " << Downwelling.y[ j ][ k ] << " " << endl;
}
}
}
|
Python
|
UTF-8
| 3,704 | 4.6875 | 5 |
[
"MIT"
] |
permissive
|
# Script: CourseInformation.py
# Description: This program creates a dictionary containing course numbers,
# the meeting times of each course, the names of the instructors
# that teach each course and the room numbers of the rooms
# where the courses meet.Enter any of these course numbers to
# get it's room number, it's instructor and meeting time.
# These are the course numbers: CS101, CS102, CS103, NT110 and CM241.
# Programmer: William Kpabitey Kwabla.
# Date: 15.02.17
# Defining the main function.
def main():
# Calling the intro function to display what the program does.
intro()
# Creating a dictionary to store room numbers.
room_numbers = {"CS101":"3004", "CS102":"4501", "CS103":"6755", "NT110":"1244", "CM241":"1411" }
# Creating a dictionary to store instructors.
instructors = {"CS101":"Haynes", "CS102":"Alvarado", "CS103":"Rich", "NT110":"Burke", "CM241":"Lee"}
# Creating a dictionary to store meeting times.
meeting_times = {"CS101":"8:00 a.m", "CS102":"9:00 a.m", "CS103":"10:00 a.m", "NT110":"11:00 a.m", "CM241":"1.00 p.m"}
# Asking user for course number.
print()
course_number = input("\t\t\t\tPlease Enter the course number: ")
print()
# Displaying course information for user by calling the room number,instructor,meeting time functions
# and passing the course number from the user and their respective dictionaries for each of the function
# which display the room number,instructor and meeting time to the user.
room_number(room_numbers,course_number)
instructor(instructors,course_number)
meeting_time(meeting_times,course_number)
# Defining the intro function to display what the program does.
def intro():
print("\t\t\t\t**********************************************************************")
print("\t\t\t\t* This program creates a dictionary containing course numbers, *")
print("\t\t\t\t* the meeting times of each course, the names of the instructors *")
print("\t\t\t\t* that teach each course and the room numbers of the rooms *")
print("\t\t\t\t* where the courses meet. Enter any of these course numbers to *")
print("\t\t\t\t* get it's room number, it's instructor and meeting time. *")
print("\t\t\t\t* These are the course numbers: CS101, CS102, CS103, NT110 and CM241 *")
print("\t\t\t\t**********************************************************************")
# Defining the room number function and passing the room numbers dictionary and course number
# from user as parameter variables which then return the room number for the course to the fucntion.
def room_number(room_numbers,course):
for key in room_numbers:
if key == course:
print("\t\t\t\tThe room number for", course, "is",room_numbers[key])
# Defining the instructor function and passing the instructors dictionary and course number
# from user as parameter variables which then return the instructor for the course to the fucntion.
def instructor(instructors,course):
for key in instructors:
if key == course:
print("\t\t\t\tThe instructor for", course, "is",instructors[key])
# Defining the meeting time function and passing the meeting times dictionary and course number
# from user as parameter variables which then return the meeting time for the course to the fucntion.
def meeting_time(meeting_times,course):
for key in meeting_times:
if key == course:
print("\t\t\t\tThe meeting time for", course, "is",meeting_times[key])
# Calling the main function to execute the program.
main()
|
C++
|
UTF-8
| 856 | 2.765625 | 3 |
[] |
no_license
|
/*
ID: shanzho2
PROG: milk
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <memory.h>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
int main(void)
{
ifstream fin("milk.in");
ofstream fout("milk.out");
int n, m, p, a;
fin>>n>>m;
vector<pair<int, int> >vec;
while(m--)
{
fin>>p>>a;
vec.push_back(make_pair(p, a));
}
sort(vec.begin(), vec.end());
int res = 0;
for (int i = 0; i != vec.size() && n > 0; i++)
{
cout<<vec[i].first<<endl;
if (n >= vec[i].second)
{
res += (vec [i].first*vec[i].second);
n -= vec[i].second;
}
else
{
res += (vec[i].first*n);
n = 0;
}
}
fout<<res<<endl;
return 0;
}
|
Python
|
UTF-8
| 1,470 | 4.4375 | 4 |
[] |
no_license
|
import random
class MSDie():
# constructor method, the init, function of the class get called
#provide default values if someone forget to put it in; sides=6
def __init__(self, sides):
# self is indictive of the object
self.sides = sides
self.value = 1
def roll(self):
self.value = random.randint(1,self.sides)
#method provided in the class of the current value facing up in the class. Retain what we know, what they know.
#class is a collection of functions
def getValue(self):
#sending back the thing that called it the bit of data. Programative interfaces, they get information
return self.value
def getSides(self):
return self.sides
def setValue(self,value):
self.value = value
def setSides(self,sides):
self.sides = sides
dieBag = []
for i in range(7):
sides = int(input("How many sides? "))
dieBag.append(MSDie(sides))
# die is an MSDie object in the second loop
for die in dieBag:
#ope/close parenthesis b/c it's a method
die.roll()
print(die.getValue())
for die in dieBag:
die.setSides(10)
die.setValue(2)
print(die.getValue(), die.getSides())
#die1 is the object of the class, MSDie
# die1 = MSDie(6)
# for i in range(10):
# die1.roll()
# print(die1.value)
# die1.value = 3
# print(die1.sides)
# print(die1.value)
# die2 = MSDie(100)
|
Swift
|
UTF-8
| 830 | 2.703125 | 3 |
[] |
no_license
|
import UIKit
class FinishViewController: UIViewController {
@IBOutlet weak var phone: UILabel!
@IBOutlet weak var address: UILabel!
@IBOutlet weak var package: UILabel!
@IBOutlet weak var sum: UILabel!
@IBOutlet weak var name: UILabel!
@IBOutlet weak var date: UILabel!
static let identifier = "Finish"
override func viewDidLoad() {
super.viewDidLoad()
name.text = "Имя: \(Order.instance.name)"
phone.text = "Телефон: \(Order.instance.phone)"
address.text = "Адрес: \(Order.instance.address)"
package.text = "Тип упаковки: \(Order.instance.package)"
sum.text = "Сумма к оплате: \(Order.instance.orderSum())₽"
date.text = "Дата доставки: \(Order.instance.date)"
}
}
|
Shell
|
UTF-8
| 836 | 3.3125 | 3 |
[] |
no_license
|
#! /usr/bin/env bash
set -e
token="$1"
ref="${2:-master}"
function run {
echo $ "$@" >&2
$@
}
cd /tmp
set +e
which bananagent
if [[ $? -eq 0 ]]; then
isUpgrade="yes"
fi
set -e
echo "downloading latest agent release..."
curl > agent.zip \
-fLH "Private-Token: ${token}" \
"https://gitlab.enix.io/api/v4/projects/166/jobs/artifacts/${ref}/download?job=build-agent-linux"
if [[ -z ${isUpgrade} ]]; then
run apt update
run apt install -y python-boto duplicity zip jq
fi
run unzip -o agent.zip
run cp bananagent-linux /usr/local/bin/bananagent
run cp config/systemd/* /etc/systemd/system/
run mkdir -p /etc/banana/plugins.d
run cp agent/plugins/* /etc/banana/plugins.d/
if [[ -z ${isUpgrade} ]]; then
run systemctl start banana.timer
run systemctl enable banana.timer
else
run systemctl daemon-reload
fi
echo "success!"
|
Java
|
UTF-8
| 2,341 | 2.28125 | 2 |
[] |
no_license
|
package cn.guanmai.station.bean.system;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/*
* @author liming
* @date Jun 20, 2019 7:50:17 PM
* @des 分拣标签模板
* @version 1.0
*/
public class PrintTagTemplateBean {
private String id;
private String create_time;
private boolean is_default;
private Object address_ids;
private Object spu_ids;
private Content content;
public static class Content {
private JSONArray blocks;
private String name;
private JSONObject page;
/**
* @return the blocks
*/
public JSONArray getBlocks() {
return blocks;
}
/**
* @param blocks the blocks to set
*/
public void setBlocks(JSONArray blocks) {
this.blocks = blocks;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the page
*/
public JSONObject getPage() {
return page;
}
/**
* @param page the page to set
*/
public void setPage(JSONObject page) {
this.page = page;
}
public Content() {
super();
}
}
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the create_time
*/
public String getCreate_time() {
return create_time;
}
/**
* @param create_time the create_time to set
*/
public void setCreate_time(String create_time) {
this.create_time = create_time;
}
/**
* @return the is_default
*/
public boolean isIs_default() {
return is_default;
}
/**
* @param is_default the is_default to set
*/
public void setIs_default(boolean is_default) {
this.is_default = is_default;
}
public Object getAddress_ids() {
return address_ids;
}
public void setAddress_ids(String address_ids) {
this.address_ids = address_ids;
}
public Object getSpu_ids() {
return spu_ids;
}
public void setSpu_ids(String spu_ids) {
this.spu_ids = spu_ids;
}
/**
* @return the content
*/
public Content getContent() {
return content;
}
/**
* @param content the content to set
*/
public void setContent(Content content) {
this.content = content;
}
public PrintTagTemplateBean() {
super();
}
}
|
Java
|
UTF-8
| 344 | 2.421875 | 2 |
[] |
no_license
|
package com.ggar.dev.utils.threadpoolexecutor;
public class OverflowErrorCount {
public static int count = 0;
public static void main(String args[]) {
try {
System.out.println(++count);
main(null);
} catch (StackOverflowError e) {
e.printStackTrace();
System.exit(0);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.