language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 3,686 | 2.3125 | 2 |
[] |
no_license
|
package com.example.myapplication2;
import android.app.DatePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
import DAO.DAO;
import DTO.Pelicula;
import DTO.PuntajeGeneral;
public class pushPeliculaFragment extends Fragment {
public DAO dao;
public Pelicula pelicula;
public Button btnAceptar;
public EditText nombre,autor,puntuacion,sinopsis;
public TextView fecha;
public int mes,dia,año;
public Calendar calendar;
public DatePickerDialog.OnDateSetListener dateSetListener;
public PuntajeGeneral puntajeGeneral;
public pushPeliculaFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dao = new DAO();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_push_pelicula, container, false);
nombre = view.findViewById(R.id.editNombre);
autor = view.findViewById(R.id.editAutor);
sinopsis = view.findViewById(R.id.editSinopsis);
puntuacion = view.findViewById(R.id.editPuntuacion);
btnAceptar = view.findViewById(R.id.btnAceptar);
fecha = view.findViewById(R.id.editFecha);
fecha.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
calendar = Calendar.getInstance();
mes = calendar.get(Calendar.MONTH);
dia = calendar.get(Calendar.DAY_OF_MONTH);
año = calendar.get(Calendar.YEAR);
DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),android.R.style.Theme_Holo_Light_Dialog,
dateSetListener,año,mes,dia);
datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
datePickerDialog.show();
}
});
dateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int año, int mes , int dia) {
mes = mes +1;
fecha.setText(dia+"/"+mes+"/"+año);
}
};
btnAceptar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
puntajeGeneral = new PuntajeGeneral(Integer.parseInt(puntuacion.getText().toString()),Integer.parseInt(puntuacion.getText().toString()),
Integer.parseInt(puntuacion.getText().toString()));
pelicula = new Pelicula(nombre.getText().toString(),autor.getText().toString(),
sinopsis.getText().toString(),
fecha.getText().toString(), puntajeGeneral);
dao.setPelicula(pelicula);
}catch (Exception e){
Toast.makeText(getContext(),"Fecha invalida",Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
}
|
TypeScript
|
UTF-8
| 1,388 | 2.53125 | 3 |
[] |
no_license
|
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { Application } from './application';
@Injectable({
providedIn: 'root'
})
export class ApplicationsService {
private basePath = 'https://hackicims.com/api/v1/companies/24/applications/';
constructor(private http: HttpClient) { }
getApplications(): Observable<Application[]> {
return this.http.get<Application[]>(this.basePath)
.pipe(
catchError(this.handleError('getApplications', []))
);
}
getApplication(id: number): Observable<Application> {
const url = `${this.basePath}/${id}`;
return this.http.get<Application>(url).pipe(
// tap(_ => this.log(`fetched hero id=${id}`)),
catchError(this.handleError<Application>(`getApplication id=${id}`))
);
}
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
// this.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
}
|
Markdown
|
UTF-8
| 2,928 | 2.703125 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Development Workflow
The following graph shows the workflow how to develop KubeSphere backend. For the frontend part please refer to [KubeSphere console](https://github.com/kubesphere/console)

## Step 1. Fork
1. Visit https://github.com/kubesphere/kubesphere
2. Click `Fork` button to create a fork of the project to your GitHub account.
## Step 2. Clone fork to local storage
Per Go's [workspace instructions](https://golang.org/doc/code.html#Workspaces), place KubeSphere code on your `GOPATH` using the following cloning procedure.
Define a local working directory:
```bash
export working_dir=$GOPATH/src/kubesphere.io
export user={your github profile name}
```
Create your clone locally:
```bash
mkdir -p $working_dir
cd $working_dir
git clone https://github.com/$user/kubesphere.git
cd $working_dir/kubesphere
git remote add upstream https://github.com/kubesphere/kubesphere.git
# Never push to upstream master
git remote set-url --push upstream no_push
# Confirm your remotes make sense:
git remote -v
```
## Step 3. Keep your branch in sync
```bash
git fetch upstream
git checkout master
git rebase upstream/master
```
## Step 4. Add new features or fix issues
Create a branch from master:
```bash
git checkout -b myfeature
```
Then edit code on the `myfeature` branch. You can refer to [effective_go](https://golang.org/doc/effective_go.html) while writing code.
### Test and build
Currently, the make rules only contain simple checks such as vet, unit test, will add e2e tests soon.
### Using KubeBuilder
- For Linux OS, you can download and execute this [KubeBuilder script](https://raw.githubusercontent.com/kubesphere/kubesphere/master/hack/install_kubebuilder.sh).
- For MacOS, you can install KubeBuilder by following this [guide](https://book.kubebuilder.io/quick-start.html).
### Run and test
```bash
make all
# Run every unit test
make test
```
Run `make help` for additional information on these make targets.
## Step 5. Development in new branch
### Sync with upstream
After the test is completed, it is a good practice to keep your local in sync with upstream to avoid conflicts.
```bash
# Rebase your master branch of your local repo.
git checkout master
git rebase upstream/master
# Then make your development branch in sync with master branch
git checkout new_feature
git rebase -i master
```
### Commit local changes
```bash
git add <file>
git commit -s -m "add your description"
```
## Step 6. Push to your fork
When ready to review (or just to establish an offsite backup of your work), push your branch to your fork on GitHub:
```bash
git push -f ${your_remote_name} myfeature
```
## Step 7. Create a PR
- Visit your fork at https://github.com/$user/kubesphere
- Click the` Compare & Pull Request` button next to your myfeature branch.
- Check out the [pull request process](pull-request.md) for more details and advice.
|
JavaScript
|
UTF-8
| 1,972 | 3.734375 | 4 |
[] |
no_license
|
/*let facto = function findFactorial(x)
{
let fact = 1;
if(x<0)
fact = null;
else if(x==1||x==0)
fact = 1;
else
{
//for(let i=x;i>=1;i--)
// fact = fact*i;
for(let i=1;i<=x;i++)
fact = fact*i;
}
return fact;
};
console.log(facto(-1));*/
/*let removeVowelsAndSpaces = function(givenString){
// start your code here.
newString="";
replaced = givenString.replace(" ","");
console.log(replaced+"\n");
length = replaced.length;
console.log(length+"\n");
for(var i = 0;i<length;i++)
{
if (replaced[i]==="a"||replaced[i]==="e"||replaced[i]==="i"||replaced[i]==="o"||replaced[i]==="u")
{
console.log("Vowel: "+replaced[i]+"\n");
console.log("Vowel: "+replaced.replace(replaced[i],"-")+"\n");
}
else
newString = newString + replaced[i];
}
console.log(newString);
};
removeVowelsAndSpaces("bad dus");*/
/*let calculateAge = function(day, month, year) {
// start your code here.
dt = new Date(year,month,day);
diff = Date.now()-dt.getTime();
age_diff = new Date(diff);
return Math.abs(age_diff.getUTCFullYear() - 1970);
console.log(age_diff.getUTCFullYear);
};
calculateAge(12,12,1969);
console.log(calculateAge(12,12,1969));*/
/*let removeVowelsAndSpaces = function(givenString){
// start your code here.
let result="";
let finalResult="";
let regex = /^[aeiouAEIOU ]+$/;
let len = givenString.length;
for (i=0;i<len;i++)
{
let c = givenString[i];
if(givenString[i].match(regex)===null)
{
result = result+c;
console.log(result);
}
}
return result;
console.log(result);
};
removeVowelsAndSpaces("samsung sukrit");*/
let findPrime = function prime(n)
{
if(n===1)
return false;
else if(n===2)
return true;
else
{
for(let i=2;i<n;i++)
{
if(n%i===0)
{
return false;
}
}
return true;
}
}
console.log(findPrime(5))
|
Java
|
GB18030
| 305 | 2.390625 | 2 |
[] |
no_license
|
package com.leetcode;
import java.util.List;
public class Exercise54 {
public static void main(String[] args) {
}
public List<Integer> spiralOrder(int[][] matrix) {
//һ˱߽磬˳ʱתһ
//ͬʱҲҪʹñ
return null;
}
}
|
Python
|
UTF-8
| 540 | 3.03125 | 3 |
[] |
no_license
|
# VSCraft
'''
задача: https://projecteuler.net/problem=1
перевод: http://euler.jakumo.org/problems/view/1.html
Если выписать все натуральные числа меньше 10, кратные 3 или 5, то получим 3, 5, 6 и 9. Сумма этих чисел равна 23.
Найдите сумму всех чисел меньше 1000, кратных 3 или 5
'''
# solved 07.05.2019 13:48 (233168)
sum=0
for i in range(1,1000):
if i%3==0 or i%5==0:
sum+=i
print(i, sum)
|
JavaScript
|
UTF-8
| 1,134 | 3.671875 | 4 |
[
"Unlicense"
] |
permissive
|
// DESAFIO 2
console.log('--- \nDesafio 2');
const usuarios = [
{ nome: 'Diego', idade: 23, empresa: 'Rocketseat' },
{ nome: 'Gabriel', idade: 15, empresa: 'Rocketseat' },
{ nome: 'Lucas', idade: 30, empresa: 'Facebook' },
];
const idades = [];
const rockets = [];
let googles;
usuarios.map( usuario => {
const { idade } = usuario;
idades.push(idade);
});
usuarios.filter( usuario => {
const { empresa, idade } = usuario;
if ( empresa == 'Rocketseat' && idade >= 18 )
rockets.push(usuario);
});
usuarios.find( usuario => {
const { empresa } = usuario;
if( empresa == 'Rocketseat' )
googles = true;
});
console.log(idades);
console.log(rockets);
console.log(googles);
const filterByAge = (users, age) => {
const newUsers = []
users.filter( user => {
const { idade } = user;
if ( idade <= age )
newUsers.push(user);
});
return newUsers;
}
const doubleAge = (users) => {
const newUsers = []
users.map( user => {
user.idade = user.idade * 2;
newUsers.push(user);
});
return newUsers;
}
const dobrados = doubleAge(usuarios);
console.log( filterByAge(dobrados, 50) );
|
Java
|
UTF-8
| 1,955 | 2.375 | 2 |
[] |
no_license
|
package com.test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
public class JavaScriptExecutor {
WebDriver driver=null;
@BeforeSuite
public void setUp() {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
driver = new ChromeDriver();
}
@Test
public void javaScriptClickTest() {
driver.get("file:///C:/Users/prajwal/Desktop/selenium/Offline%20Website/Offline%20Website/index.html");
WebElement register=driver.findElement(By.partialLinkText("Register"));
javaScriptClick(driver, register);
WebElement name=driver.findElement(By.id("name"));
javaScriptSendKeys(driver, name, "Dhamma");
javaScriptHighlighElement(driver, name);
}
@Test
public void scrollBar() {
driver.get("http://demo.guru99.com/test/guru99home/");
WebElement Element = driver.findElement(By.linkText("Linux"));
javaScriptScrollBar(driver, Element);
}
private void javaScriptClick(WebDriver driver, WebElement webElem) {
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", webElem);
}
private void javaScriptSendKeys(WebDriver driver, WebElement webElem,String text) {
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].value='"+text+"';", webElem);
}
private void javaScriptHighlighElement(WebDriver driver, WebElement webElem) {
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].style.border='6px solid pink'", webElem);
}
private void javaScriptScrollBar(WebDriver driver,WebElement webele) {
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].scrollIntoView();", webele);
//js.executeScript("window.scrollBy(0,10000)");
}
}
|
Markdown
|
UTF-8
| 1,066 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
## 注册接口
#### 1. URL
/api/v1/auth/register
#### 2. 请求方式
POST
#### 3. 请求头
- nickname,必须有,昵称
- email,必须有,邮箱
- password,必须有,密码
- X-Deviceid,必须有
- timestamp, 时间戳
- nonce, 随机数
- signature, 加密签名, signature=SHA1(timestamp+nonce+token)
> 这里是第一次请求,所以不带token,使用默认的token--32位的1
> 后端需对timestamp进行校验,防止重放攻击(Replay attack)
> 此处直接来个中间件middleware
#### 4. 返回值示例
成功:
```json
{
"code": 0,
"msg": "接口调用成功",
"data": {
"uid": "16489",
"email": "nnn@aaa.com",
"nickname": "Scott Wang",
"avatar": "http://mainsite/api/app/avatar/16489",
"token": "DJSKLDF338JKLWESJKDS83J1JKLSDI83JJKDSFA31939"
}
}
```
失败:
```json
{
"code": 500,
"msg": "服务器内部错误,请稍后再试",
"data": null
}
```
#### 5. 错误码code说明
- code: 0, 操作成功
- code: 1000, 昵称重复
- code: 1001, 邮箱重复
- code: 1002, 请求参数错误(token错误)
- code: 1003, 未知错误,请稍后再试
|
Java
|
UTF-8
| 529 | 2.15625 | 2 |
[] |
no_license
|
package com.justfriend.suratuin.Model.Login;
public class LoginUser {
private String nim;
private String password;
public LoginUser(String nim, String password) {
this.nim = nim;
this.password = password;
}
public String getNim() {
return nim;
}
public void setName(String name) {
this.nim = nim;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
Python
|
UTF-8
| 1,109 | 2.953125 | 3 |
[] |
no_license
|
import argparse
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('file', help='The log file to generate a graph on')
args = parser.parse_args()
graph = []
lst = open(args.file, 'r').readlines()
for i, line in enumerate(lst):
if line.startswith('Failed getting URL'):
if lst[i + 1].startswith('Received status code 999'):
failed_ip = line.split('http://geektalent:NEe2Yue6Jj@')[-1].replace('\n', '')
found = False
for i, item in enumerate(graph):
if item['ip'] == failed_ip:
graph[i]['count'] += 1;
found = True
if not found:
graph.append({
'ip': failed_ip,
'count': 1
});
index = np.arange(len(graph))
x = [a['ip'] for a in graph]
y = np.array([a['count'] for a in graph])
plt.bar(index, y, color="blue")
plt.xticks(index, x)
plt.show()
|
Java
|
UTF-8
| 5,211 | 2.953125 | 3 |
[] |
no_license
|
package dtsoft.main.util;
import java.util.Random;
import dtsoft.main.view.BoardGamePiece;
import dtsoft.main.view.adapter.BoardGameAdapter;
public class GameUtils {
private final int mGameCols = 5;
private static GameUtils mThis = null;
public static GameUtils getInstance() {
if (mThis == null) {
mThis = new GameUtils();
}
return mThis;
}
public GameUtils() {
mRand = new Random();
}
public int getGameCols() {
return mGameCols;
}
public int getGamePieces() {
return (int)Math.pow(getGameCols(), 2);
}
public int[] activateGamePieces(int gamePiece) {
int above,
right,
bottom,
left;
// Determine what is above
above = (gamePiece - mGameCols);
// Determine what is to the right
right = (gamePiece + 1);
if (right % mGameCols == 0) {
// a left most piece
right = -1;
}
// Determine what is so the bottom
bottom = (gamePiece + mGameCols);
// Determine what is to the left
left = (gamePiece - 1);
if (gamePiece % mGameCols == 0) {
left = -1;
}
return new int[] {above, right, bottom, left};
}
public int[] deactivateGamePieces(int[] activeGamePieces, int gamePiece, int totGamePieces) {
int[] results = new int[totGamePieces];
for (int i = 0; i < totGamePieces; i++) {
for (int n : activeGamePieces) {
if (i == gamePiece) {
results[i] = -1;
break;
}
if (i == n) {
results[i] = -1;
break;
} else {
results[i] = i;
}
}
}
return results;
}
public void getLetter(BoardGamePiece bgPiece) {
String curLetter = getRandLetter();
bgPiece.setLetter(curLetter);
}
/**
* Validates the given game board piece
* @param bgPiece
* The board game piece to validate
*/
public void gameBoardValidation(BoardGameAdapter boardGame ) {
BoardGamePiece[] bgPieces = boardGame.getBoardGamePieces();
for (BoardGamePiece bgPiece : bgPieces) {
//validateGamePiece(boardGame, bgPiece);
}
}
private void validateGamePiece(BoardGameAdapter boardGame,
BoardGamePiece bgPiece) {
String curLetter = bgPiece.getLetter();
int gamePiece = bgPiece.getId();
int[] gamePieces = activateGamePieces(gamePiece);
int above = gamePieces[GamePieceCoord.GP_TOP],
right = gamePieces[GamePieceCoord.GP_RIGHT],
bottom = gamePieces[GamePieceCoord.GP_BOTTOM],
left = gamePieces[GamePieceCoord.GP_LEFT];
BoardGamePiece bgAbove = boardGame.getChildAt(above);
BoardGamePiece bgBelow = boardGame.getChildAt(bottom);
BoardGamePiece bgRight = boardGame.getChildAt(right);
BoardGamePiece bgLeft = boardGame.getChildAt(left);
// This prevents us from having too many of the same letter in a row and too many damn consonants
int totalLikeIt = 0;
if (bgAbove != null)
if (bgBelow != null) {
if (bgAbove.getLetter().equalsIgnoreCase(bgBelow.getLetter()))
if (curLetter.equalsIgnoreCase(bgAbove.getLetter())) {
getLetter(bgPiece);
this.validateGamePiece(boardGame, bgPiece);
}
if (Alphas.isConsonant(bgAbove.getLetter()) && Alphas.isConsonant(bgBelow.getLetter()))
if (Alphas.isConsonant(curLetter)) {
getLetter(bgPiece);
this.validateGamePiece(boardGame, bgPiece);
}
if (bgAbove.getLetter().equalsIgnoreCase(curLetter))
totalLikeIt++;
if (bgBelow.getLetter().equalsIgnoreCase(curLetter))
totalLikeIt++;
}
if (bgLeft != null)
if (bgRight != null) {
if (bgLeft.getLetter().equalsIgnoreCase(bgRight.getLetter()))
if (curLetter.equalsIgnoreCase(bgLeft.getLetter())) {
getLetter(bgPiece);
this.validateGamePiece(boardGame, bgPiece);
}
if (Alphas.isConsonant(bgLeft.getLetter()) && Alphas.isConsonant(bgRight.getLetter()))
if (Alphas.isConsonant(curLetter)) {
getLetter(bgPiece);
this.validateGamePiece(boardGame, bgPiece);
}
if (bgLeft.getLetter().equalsIgnoreCase(curLetter))
totalLikeIt++;
if (bgRight.getLetter().equalsIgnoreCase(curLetter))
totalLikeIt++;
}
// If two or more attached are like it then get a new letter
if (totalLikeIt >= 2) {
getLetter(bgPiece);
this.validateGamePiece(boardGame, bgPiece);
}
}
private int[] mPrevRand = new int[] { -1, -1 };
private String getRandLetter() {
int rand = mRand.nextInt(Alphas.WeightedAlphas.WEIGHTED_ALPHAS.length);
String letter = Alphas.WeightedAlphas.WEIGHTED_ALPHAS[rand];
boolean one = false,
two = false;
for (int i = 0; i < mPrevRand.length; i++) {
if (i == 0 && mPrevRand[i] == rand)
one = true;
if (i == 1 && mPrevRand[i] == rand)
two= true;
}
if (one && two) {
letter = getRandLetter();
} else {
mPrevRand[0] = mPrevRand[1];
mPrevRand[1] = rand;
}
return letter;
}
private Random mRand = new Random();
public class GamePieceCoord {
public static final int GP_TOP = 0;
public static final int GP_RIGHT = 1;
public static final int GP_BOTTOM = 2;
public static final int GP_LEFT = 3;
}
}
|
Swift
|
UTF-8
| 2,589 | 2.5625 | 3 |
[
"Apache-2.0"
] |
permissive
|
//routes
import PerfectHTTP
import PerfectHTTPServer
import Foundation
public func routes() -> Routes {
Config()
//AutoLogin Routine to save time
let autoUser = UserDefaults.standard.string(forKey: "user") ?? ""
let autoPass = UserDefaults.standard.string(forKey: "pass") ?? ""
//Auto Login the user
if ( autoUser != "" && autoPass != "" && autoUser.count > 0 && autoPass.count > 0 ) {
let returnData = Login(user: autoUser, pass: autoPass)
if ( returnData.success ) {
let userid = returnData.data;
let _ = Session(channelid: "siriushits1", userid: userid)
let _ = Channels(channeltype: "number", userid: userid)
print("AutoLogin Success")
}
}
var routes = Routes()
// /key/1/{userid}
routes.add(method: .get, uri:"/key/1/{userid}",handler:keyOneRoute)
// /api/v2/login
routes.add(method: .post, uri:"/api/v2/login",handler:loginRoute)
// /key/4/{userid}
routes.add(method: .get, uri:"/key/4",handler:keyFourRoute)
// /api/v2/session
routes.add(method: .post, uri:"/api/v2/session",handler:sessionRoute)
// /api/v2/channels
routes.add(method: .post, uri:"/api/v2/channels",handler:channelsRoute)
// /playlist/{userid}/2.m3u8
routes.add(method: .get, uri:"/playlist/{userid}/**",handler:playlistRoute)
// /audio/{userid}/**.aac
routes.add(method: .get, uri:"/audio/{userid}/**",handler:audioRoute)
// /PDT (artist and song data)
routes.add(method: .get, uri:"/pdt/{userid}",handler:PDTRoute)
// /ping (return is pong) This is way of checking if server is running
routes.add(method: .get, uri:"/ping",handler:pingRoute)
// Check the console to see the logical structure of what was installed.
// print("\(routes.navigator.description)")
// /api/v2/autologin
routes.add(method: .post, uri:"/api/v2/autologin",handler:autoLoginRoute)
// /api/v2/xtrasession
routes.add(method: .post, uri:"/api/v2/xtras",handler:xtraSessionRoute)
routes.add(method: .get, uri:"/xtras/**",handler:xtraPlaylistRoute)
// /clips/**
routes.add(method: .get, uri:"/xtraAudio/**",handler:xtraAudioRoute)
return routes
}
let server = HTTPServer()
server.serverAddress = Global.variable.ipaddress
server.serverPort = UInt16(Global.variable.port)
do {
server.addRoutes( routes() )
try server.start()
} catch {
print("There was an issue starting the server.")
}
|
Java
|
UTF-8
| 3,022 | 2.3125 | 2 |
[] |
no_license
|
package com.aapeli.settingsgui;
import java.awt.Color;
import java.awt.Component;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class Unit implements FocusListener, ItemListener, ActionListener {
private LobbyRoomSettingsPanel anLobbyRoomSettingsPanel__1691;
private String aString1692;
private boolean aBoolean1693;
private double aDouble1694;
private int anInt1695;
public static boolean aBoolean1696;
protected Unit(String var1) {
this.aString1692 = var1;
this.aBoolean1693 = true;
this.aDouble1694 = 1.0D;
}
public void focusGained(FocusEvent var1) {
}
public void focusLost(FocusEvent var1) {
this.anLobbyRoomSettingsPanel__1691.method939(this);
}
public void itemStateChanged(ItemEvent var1) {
this.anLobbyRoomSettingsPanel__1691.method938(this);
}
public void actionPerformed(ActionEvent var1) {
this.anLobbyRoomSettingsPanel__1691.method940(this);
}
public void setRelativeWidth(double var1) {
if (var1 <= 0.0D || var1 > 1.0D) {
var1 = 1.0D;
}
this.aDouble1694 = var1;
}
protected void method1829(LobbyRoomSettingsPanel var1) {
this.anLobbyRoomSettingsPanel__1691 = var1;
}
protected boolean method1830(boolean var1) {
if (var1 == this.aBoolean1693) {
return false;
} else {
this.aBoolean1693 = var1;
Component var2 = this.method1841();
if (var2 != null) {
var2.setVisible(var1);
}
return true;
}
}
protected boolean method1831() {
return this.aBoolean1693;
}
protected void method1832(int var1) {
this.anInt1695 = var1;
}
protected int method1833() {
return this.anInt1695;
}
protected double method1834() {
return this.aDouble1694;
}
protected void method1835(Image var1, int var2, int var3) {
}
protected int method1836() {
return 0;
}
protected boolean method1837() {
return false;
}
protected String method1838() {
return this.aString1692;
}
protected int method1839() {
return 0;
}
protected int method1840() {
return 1;
}
protected Component method1841() {
return null;
}
protected Component[] method1842() {
return null;
}
protected int getItemState() {
return -1;
}
protected boolean setItemState(int var1) {
return false;
}
protected boolean method1843() {
return false;
}
protected String method1844() {
return null;
}
protected void method1845(String var1) {
}
protected void method1846(Color var1, Color var2) {
}
}
|
Python
|
UTF-8
| 137 | 2.765625 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Thu May 30 21:51:43 2019
@author: Lawrence
"""
for steps in range (4):
print (steps)
|
C++
|
UTF-8
| 714 | 2.703125 | 3 |
[] |
no_license
|
//
// Created by Onat Bas on 02/01/17.
//
#include "AdjacentNeighbourCounter.hxx"
#include "AdjacentPopper.hxx"
AdjacentPopperResult AdjacentPopper::pop(const StackSet &set, const BoxPosition &position) const {
NeighboursInVicinityCounter vicinity;
const bool hasEnoughNeighbours = vicinity.hasEnoughNeighbours(set, position, set[position].getColor());
if (!hasEnoughNeighbours) {
return AdjacentPopperResult();
}
AdjacentNeighbourCounter counter;
const auto result = counter.count(set, position);
PoppedPositions positions;
for (int i = 0; i < result.getSameColorAreaCount(); i++)
positions.popPosition(result[i]);
return AdjacentPopperResult(positions);
}
|
Java
|
UTF-8
| 6,247 | 2.0625 | 2 |
[] |
no_license
|
/*
* Copyright 2014 Florian Vogelpohl <floriantobias@gmail.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.hsos.ecs.richwps.wpsmonitor.client;
import de.hsos.ecs.richwps.wpsmonitor.client.exception.WpsMonitorClientException;
import de.hsos.ecs.richwps.wpsmonitor.client.resource.WpsProcessResource;
import de.hsos.ecs.richwps.wpsmonitor.client.resource.WpsResource;
import java.net.URL;
import java.util.List;
/**
* Interface for the WpsMonitorClient.
*
* @author Florian Vogelpohl <floriantobias@gmail.com>
*/
public interface WpsMonitorClient {
/**
* Gets a WpsProcessResource instance from the the choosen WpsMonitor
* System. The wpsEndpoint is the Endpoint of a Web Processing Service
* Server which is registrated in the choosen Monitor.
*
* By default 1000 measured values by the monitor are considered.
*
* @param wpsEndpoint WPS-Server endpoint
* @param wpsProcessIdentifier Process identifier of the WPS Process
* @return WpsProcessResource instance which is comparable with the
* WpsProcessEntity class of the WpsMonitor
* @throws WpsMonitorClientException WpsMonitorClientException capsule any
* Exceptions.
*/
public WpsProcessResource getWpsProcess(final URL wpsEndpoint, final String wpsProcessIdentifier)
throws WpsMonitorClientException;
/**
* Gets a WpsProcessResource instance from the the choosen WpsMonitor
* System. The wpsEndpoint is the Endpoint of a Web Processing Service
* Server which is registrated in the choosen Monitor.
*
* By default 1000 measured values by the monitor are considered.
*
* @param wpsEndpoint WPS-Server endpoint
* @param wpsProcessIdentifier Process identifier of the WPS Process
* @param forceRefresh Refresh the WPS Context (it's not necessary, but if
* you know that the Monitor has new WPS-Server entries, you should set
* forceRefresh to true)
* @return WpsProcessResource instance which is comparable with the
* WpsProcessEntity class of the WpsMonitor
* @throws WpsMonitorClientException WpsMonitorClientException capsule any
* Exceptions.
*/
public WpsProcessResource getWpsProcess(final URL wpsEndpoint, final String wpsProcessIdentifier, final Boolean forceRefresh)
throws WpsMonitorClientException;
/**
* Gets a WpsProcessResource instance from the the choosen WpsMonitor
* System. This is a overloaded method. Internally the MonitorClient works
* with WpsResource instancen. If you are also working with this type of
* instances, you can use this method instead of the method which use
* wpsEndpoint URLs.
*
* By default 1000 measured values by the monitor are considered.
*
* @param wpsResource WpsResource instance
* @param wpsProcessIdentifier Process identifier of the WPS Process
* @return WpsProcessResource instance which is comparable with the
* WpsProcessEntity class of the WpsMonitor
* @throws WpsMonitorClientException WpsMonitorClientException capsule any
* Exceptions.
*/
public WpsProcessResource getWpsProcess(final WpsResource wpsResource, final String wpsProcessIdentifier)
throws WpsMonitorClientException;
/**
* Gets a WpsProcessResource instance from the the choosen WpsMonitor
* System. This is a overloaded method. Internally the MonitorClient works
* with WpsResource instancen. If you are also working with this type of
* instances, you can use this method instead of the method which use
* wpsEndpoint URLs. If you want to specifiy how many measured values should
* be consider for the calculation of metrics by the monitor, you can do
* this with the consider parameter.
*
* @param wpsResource WpsResource instance
* @param wpsProcessIdentifier Process identifier of the WPS Process
* @param consider How many measured values should be considered for the
* calculation of metrics by the monitor
* @return WpsProcessResource instance which is comparable with the
* WpsProcessEntity class of the WpsMonitor
* @throws WpsMonitorClientException WpsMonitorClientException capsule any
* Exceptions.
*/
public WpsProcessResource getWpsProcess(final WpsResource wpsResource, final String wpsProcessIdentifier, final Integer consider)
throws WpsMonitorClientException;
/**
* Gets a WpsResource instance. This instances describes a registrated
* WPS-Server.
*
* @param wpsEndPoint
* @return
* @throws WpsMonitorClientException WpsMonitorClientException capsule any
* Exceptions.
*/
public WpsResource getWps(final URL wpsEndPoint)
throws WpsMonitorClientException;
/**
*
* @param wpsEndPoint
* @param forceRefresh
* @return
* @throws WpsMonitorClientException WpsMonitorClientException capsule any
* Exceptions.
*/
public WpsResource getWps(final URL wpsEndPoint, final Boolean forceRefresh)
throws WpsMonitorClientException;
/**
*
* @return @throws WpsMonitorClientException WpsMonitorClientException
* capsule any Exceptions.
*/
public List<WpsResource> getAllWps()
throws WpsMonitorClientException;
/**
*
* @param forceRefresh
* @return
* @throws WpsMonitorClientException WpsMonitorClientException capsule any
* Exceptions.
*/
public List<WpsResource> getAllWps(final Boolean forceRefresh)
throws WpsMonitorClientException;
/**
* Checks if the WpsMonitor is available.
*
* @return true if available, otherwise false
*/
public Boolean isReachable();
}
|
Java
|
UTF-8
| 1,070 | 3.28125 | 3 |
[] |
no_license
|
package com.my.concurrent.SynchronizedStudy;
import java.util.concurrent.TimeUnit;
public class MySynchronized {
private int id;
public synchronized int getId() {
/*try {
System.out.println("---getId()------- working");
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
// do nothing
}*/
return id;
}
public synchronized void setId(int id) {
this.id = id;
}
public static void main(String[] args) {
MySynchronized mySynchronized = new MySynchronized();
mySynchronized.setId(123);
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(" ----------- " + mySynchronized.getId());
mySynchronized.setId(100);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(" ----------- " + mySynchronized.getId());
}
}).start();
}
}
|
Java
|
UTF-8
| 1,483 | 2.359375 | 2 |
[] |
no_license
|
package tt.helpsys.dao;
import java.util.Date;
import tt.helpsys.entity.Message;
import tt.helpsys.entity.MessageCriteria;
import tt.helpsys.entity.MessageInfo;
import tt.helpsys.util.Page;
/**
* 帖子信息数据访问接口
* @author TRY
*
*/
public interface IMessageDao {
/**
* 添加帖子
* @param msg 帖子信息
* @return
*/
int add(Message msg);
/**
* 删除贴子
* @param msgid 帖子ID
* @return
*/
int delete(int msgid);
/**
* 更新帖子
* @param msg 帖子信息
* @return
*/
int update(Message msg);
/**
* 更新状态
* @param msgid 帖子ID
* @param state 状态
* @return
*/
int updateState(int msgid,int state);
/**
* 查询指定帖子信息
* @param msgid 帖子ID
* @return
*/
MessageInfo get(int msgid);
/**
* 多条件查询帖子信息
* @param messageCriteria 复合条件
* @param page 分页信息
* @return 查询结果
*/
Page query(MessageCriteria messageCriteria,Page page);
/**
* 查询最新的帖子信息
* @param page 分页信息
* @return
*/
Page queryNew(Page page);
/**
* 查询最热的帖子信息
* @param page
* @return
*/
Page queryHot(Page page);
/**
* 查询最热主题信息
* @param page
* @return
*/
Page queryTheme(Page page);
/**
* 根据时间查询帖子数量
* @param startDate 开始时间
* @param endDate 结束时间
* @return
*/
long queryCountByDate(Date startDate,Date endDate);
}
|
Java
|
UTF-8
| 4,679 | 2.046875 | 2 |
[] |
no_license
|
package git.gitrest.api.services;
import git.gitrest.api.dto.NotificationDTO;
import git.gitrest.api.model.Notification;
import git.gitrest.api.repository.ConfirmationTokenRepository;
import git.gitrest.api.repository.NotificationRepository;
import git.gitrest.api.repository.ProfileRepository;
import git.gitrest.api.repository.UserRepository;
import org.slf4j.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
public class NotificationServices {
@Autowired
ProfileRepository profileRepository;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserRepository userRepository;
@Autowired
private NotificationRepository chatRoomRepository;
@Autowired
private ConfirmationTokenRepository confirmationTokenRepository;
@Autowired
private EmailSenderService emailSenderService;
@Autowired
UserService userService;
@Autowired
private PasswordEncoder passwordEncoder;
private List<Notification> notifications = new ArrayList<>();
public List<Notification> getNotification(){
notifications.clear();
chatRoomRepository.findAll().forEach(notify->{
notifications.add(notify);
});
System.out.print(notifications);
return notifications;
}
public List<Notification> getNotifications(String email){
try {
return chatRoomRepository.findByEmail(email);
}catch (NullPointerException e){
List<Notification> profile = new ArrayList<>();
System.out.println(profile);
return profile;
}
}
public Notification addNotification(NotificationDTO profile, String email){
Notification notification = new Notification();
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = new Date(System.currentTimeMillis());
notification.setEmail(email);
notification.setTitle(profile.getTitle());
notification.setImage(profile.getImage());
notification.setText(profile.getText());
notification.setDate(date.toString());
notification.setStatus("Active");
return chatRoomRepository.save(notification);
}
public Notification deleteNotification(Long profile){
Notification notification = chatRoomRepository.findById(profile).get();
notification.setStatus("Deleted");
return chatRoomRepository.save(notification);
}
// public String changePassword(ChangePassword profile){
// Profile profiles = new Profile();
// User user = userRepository.findByEmail(profile.getEmail());
// System.out.println(profile.getEmail());
// System.out.println(profile.getOldpassword());
// System.out.println(user.getPassword());
// String password = passwordEncoder.encode(profile.getOldpassword());
// System.out.println(password);
//
// if (!userService.checkIfValidOldPassword(user, profile.getOldpassword())) {
// return "fail";
// }
// else{
//
//
// user.setPassword(profile.getNewpassword());
//
// userService.save(user);
//
// return "success";
// }
//
//
// }
// public String addPhone(ProfileDTO profile){
//
//
// Profile profiles = profileRepository.findByEmail(profile.getEmail());
// String tokens = "";
// StringBuilder str
// = new StringBuilder();
//
// profiles.setPhone(profile.getPhone());
//
// profileRepository.save(profiles);
// int[] token = sendtokentomailp(profiles.getEmail());
// for(int i = 0; i < token.length; i++){
//
// String string = String.valueOf(token[i]);
// str.append(string);
// System.out.println(string);
// tokens = str.toString();
// System.out.println(tokens);
// }
// System.out.println(tokens);
// return tokens;
//
// }
// public String changePhone(ProfileDTO profile){
//
//
// Profile profiles = profileRepository.findByEmail(profile.getEmail());
//
// profiles.setPhone(profile.getPhone());
//
// profileRepository.save(profiles);
//
// return "success";
//
// }
}
|
Markdown
|
UTF-8
| 1,267 | 2.890625 | 3 |
[] |
no_license
|
# 未决信号、阻塞信号、信号处理函数表
> - 实际执行信号的处理动作称为信号递达(Delivery)。
> - 信号从产生到递达之间的状态,称为信号未决(Pending)。
> - 进程可以选择阻塞 (Block )某个信号。
> - 被阻塞的信号产生时将保持在未决状态,直到进程解除对此信号的阻塞,才执行递达的动作。
> - 注意,阻塞和忽略是不同的,只要信号被阻塞就不会递达,而忽略是在递达之后可选的一种处理动作。

- 这张图表示在一个进程的`PCB`中,存在三个属性是 未决信号集、阻塞信号集和信号处理函数集。
- 未决信号集和阻塞信号集的数据结构是采用 `uint64_t` 的位图来存储的。这就足以表示每个信号。
- 信号处理函数集就是一个函数指针数组,下标就是对应的信号,而内容就是指向接收到该信号后需要执行的动作。
- 阻塞信号就是当接受到信号之后,不立刻处理,而是等待时机合适的时候再处理。
|
Java
|
UTF-8
| 3,463 | 2.3125 | 2 |
[] |
no_license
|
package cn.zalezone.ui.adapter;
import java.util.ArrayList;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import cn.zalezone.domian.LeaseHouseInfo;
import cn.zalezone.domian.LookHouseInfo;
import cn.zalezone.safehome_android.R;
import cn.zalezone.ui.LookHouseStatusActivity;
import cn.zalezone.ui.PropertyVerityActivity;
public class LookHouseRegisterListAdapter extends BaseAdapter{
private ArrayList<LookHouseInfo> list; // 填充数据的list
private Context context; // 上下文
private LayoutInflater inflater = null; // 用来导入布局
private static class ViewHolder {
TextView houseNumberTextView;
TextView communityNameTextView;
TextView locationTextView;
TextView buildingTextView;
TextView floorTextView;
Button verifyButton;
}
public LookHouseRegisterListAdapter(ArrayList<LookHouseInfo> list, Context context)// 构造器
{
this.context = context;
this.list = list;
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.adapter_list_house_property, null);
viewHolder = new ViewHolder();
viewHolder.houseNumberTextView = (TextView) convertView.findViewById(R.id.house_number);
viewHolder.communityNameTextView = (TextView) convertView.findViewById(R.id.community_name);
viewHolder.locationTextView = (TextView) convertView.findViewById(R.id.location);
viewHolder.buildingTextView =(TextView)convertView.findViewById(R.id.building_info);
viewHolder.floorTextView = (TextView)convertView.findViewById(R.id.floor_info);
viewHolder.verifyButton = (Button) convertView.findViewById(R.id.verify);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
final LookHouseInfo info = list.get(position);
viewHolder.houseNumberTextView.setText(info.getHouseCode());
viewHolder.communityNameTextView.setText(info.getVillageName());
viewHolder.locationTextView.setText(info.getHouseAdd());
viewHolder.buildingTextView.setText(info.getBuildingNo()+"幢"+info.getBuildingUnit()+"单元"+info.getBuildingRoom()+"室");
viewHolder.floorTextView.setText(info.getFloorNum()+"/"+info.getFloorCnt()+"层");
viewHolder.verifyButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent lookHouseIntent = new Intent(context, LookHouseStatusActivity.class);
lookHouseIntent.putExtra("lookHouseInfo", info);
context.startActivity(lookHouseIntent);
}
});
return convertView;
}
}
|
Python
|
UTF-8
| 251 | 3.78125 | 4 |
[] |
no_license
|
def pattern1(n):
m = 2 * n - 2
for i in range(0, n):
for j in range(0, m):
print(end=" ")
m = m - 2
for j in range(0, i + 1):
print("* ", end="")
print("\r")
n = 5
pattern1(n)
|
Shell
|
UTF-8
| 2,513 | 3.09375 | 3 |
[] |
no_license
|
# Maintainer: Muflone http://www.muflone.com/contacts/english/
pkgname=vmware-ovftool
pkgver=4.2.0.4586971
pkgrel=1
pkgdesc="VMware Open Virtualization Format tool"
arch=('i686' 'x86_64')
url="https://www.vmware.com/support/developer/ovf/"
license=('custom:vmware')
makedepends=('xorg-server-xvfb')
depends=('curl' 'expat' 'libgpg-error' 'libpng12' 'xerces-c' 'zlib')
source_i686=("http://url.muflone.com/VMware-ovftool-${pkgver%.*}-${pkgver##*.}-lin.i386.bundle")
source_x86_64=("http://url.muflone.com/VMware-ovftool-${pkgver%.*}-${pkgver##*.}-lin.x86_64.bundle")
sha256sums_i686=('53b894dfa977fbbdc7154b8e94e4746f7801e0a22b5881dd725b32638340bff6')
sha256sums_x86_64=('b1f84bfff40680c594da9840be0ffb4c36e377ae26abecddad12b4cadebfa8d8')
prepare() {
# The bundle file doesn't allow extraction using symlinks or relative paths, here's then copied
if [ "${CARCH}" = "x86_64" ]
then
_subarch="x86_64"
else
_subarch="i386"
fi
_bundlepath=$(readlink "${srcdir}/VMware-ovftool-${pkgver%.*}-${pkgver##*.}-lin.${_subarch}.bundle")
cp -f -L "${_bundlepath}" "${srcdir}/VMware-ovftool-${pkgver%.*}-${pkgver##*.}-${CARCH}_file.bundle"
}
build() {
rm -rf "${srcdir}/build"
xvfb-run -a sh "${srcdir}/VMware-ovftool-${pkgver%.*}-${pkgver##*.}-${CARCH}_file.bundle" -x "${srcdir}/build"
# Remove duplicated system libraries
cd "${srcdir}/build/${pkgname}"
rm "libcurl.so.4" "libexpat.so" "libgcc_s.so.1" "libpng12.so.0" "libstdc++.so.6" \
"libxerces-c-3.1.so" "libz.so.1"
}
package() {
cd "${srcdir}/build/${pkgname}"
# Install binaries files
install -m 755 -d "${pkgdir}/usr/lib/${pkgname}"
install -m 644 -t "${pkgdir}/usr/lib/${pkgname}" icudt44l.dat
install -m 755 -t "${pkgdir}/usr/lib/${pkgname}" ovftool ovftool.bin lib*
# Install data files
for _subdir in certs env env/en schemas/DMTF schemas/vmware
do
install -m 755 -d "${pkgdir}/usr/lib/${pkgname}/${_subdir}"
install -m 644 -t "${pkgdir}/usr/lib/${pkgname}/${_subdir}" "${_subdir}"/*.*
done
# Install main script symlink
install -m 755 -d "${pkgdir}/usr/bin"
ln -s "/usr/lib/${pkgname}/ovftool" "${pkgdir}/usr/bin/ovftool"
# Install license files
install -m 755 -d "${pkgdir}/usr/share/licenses/${pkgname}"
install -m 644 -t "${pkgdir}/usr/share/licenses/${pkgname}" \
vmware.eula vmware-eula.rtf open_source_licenses.txt
# Install documentation files
install -m 755 -d "${pkgdir}/usr/share/doc/${pkgname}"
install -m 644 -t "${pkgdir}/usr/share/doc/${pkgname}" README.txt
}
|
Swift
|
UTF-8
| 871 | 3.46875 | 3 |
[] |
no_license
|
//
// PetController.swift
// Pets
//
// Created by Ilgar Ilyasov on 8/28/18.
// Copyright © 2018 Lambda School. All rights reserved.
//
import Foundation
class PetController {
// Create an array to store the Pets. And set it empty
private(set) var pets: [Pet] = []
// Create a function to save new Pet
func createNewPet(name: String, age: Int) {
let newPet = Pet(name: name, age: age)
pets.append(newPet)
}
// Create a function to modify information about any Pet
func updatePet(newPet: Pet, name: String, age: Int) {
guard let index = pets.index(of: newPet) else { return }
var updatedPet = newPet
updatedPet.name = name
updatedPet.age = age
pets.remove(at: index)
pets.insert(newPet, at: index)
}
}
|
TypeScript
|
UTF-8
| 1,054 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
import { coinsConfig } from '../utils/configs';
import { Network_type } from '../utils/constants';
import BitcoinChecker from './bitcoin';
class LitecoinChecker extends BitcoinChecker {
protected prefix: string = '';
protected type: string = '';
protected hash: Uint8Array = new Uint8Array();
constructor(networkType: Network_type = Network_type.Mainnet) {
super(networkType);
this.networkType = networkType;
this.hashAlgorithm = coinsConfig.ltc.algorithm;
this.name = coinsConfig.ltc.fullName;
this.symbol = coinsConfig.ltc.symbol;
}
public isValid(address: string): boolean {
if (this.preCheck(address)) {
const addressType = this.getAddressType(address);
if (addressType) {
return coinsConfig.ltc.addressTypes!.includes(addressType);
}
}
return false;
}
/**
* 通过正则预检查
* @param address 地址
*/
public preCheck(address: string): boolean {
return coinsConfig.ltc.addressReg.some(reg => reg.test(address));
}
}
export default LitecoinChecker;
|
Java
|
UTF-8
| 2,750 | 2.25 | 2 |
[] |
no_license
|
package uta.mav.appoint.db;
import java.sql.SQLException;
import java.util.ArrayList;
import uta.mav.appoint.TimeSlotComponent;
import uta.mav.appoint.beans.*;
import uta.mav.appoint.login.*;
public class DatabaseManager {
private DBImplInterface imp = new RDBImpl();
public Integer createUser(String email, String password, String role) throws SQLException{
return imp.createUser(email, password, role);
}
public LoginUser checkUser(GetSet set) throws SQLException{
return imp.checkUser(set);
}
public Boolean addUser(RegisterBean registerBean) throws SQLException{
return imp.addUser(registerBean);
}
public ArrayList<String> getAdvisors() throws SQLException{
return imp.getAdvisors();
}
public AdvisorUser getAdvisor(String email) throws SQLException{
return imp.getAdvisor(email);
}
public ArrayList<TimeSlotComponent> getAdvisorSchedule(String name) throws SQLException{
return imp.getAdvisorSchedule(name);
}
public Boolean createAppointment(Appointment a,String email) throws SQLException{
return imp.createAppointment(a,email);
}
public ArrayList<Object> getAppointments(LoginUser user) throws SQLException{
if (user instanceof AdvisorUser){
return imp.getAppointments((AdvisorUser)user);
}
else if (user instanceof StudentUser){
return imp.getAppointments((StudentUser)user);
}
else if (user instanceof AdminUser){
return imp.getAppointments((AdminUser)user);
}
else
return null;
}
public Boolean cancelAppointment(int id) throws SQLException{
return imp.cancelAppointment(id);
}
public String addTimeSlot(AllocateTime at) throws SQLException{
return imp.addTimeSlot(at);
}
public ArrayList<AppointmentType> getAppointmentTypes(String pname) throws SQLException{
return imp.getAppointmentTypes(pname);
}
public Boolean updateAppointment(Appointment a) throws SQLException{
return imp.updateAppointment(a);
}
public Boolean deleteTimeSlot(AllocateTime at) throws SQLException{
return imp.deleteTimeSlot(at);
}
public Appointment getAppointment(String date, String email) throws SQLException{
return imp.getAppointment(date,email);
}
public String addAppointmentType(AdvisorUser user, AppointmentType at) throws SQLException{
return imp.addAppointmentType(user, at);
}
public ArrayList<String> getDepartmentStrings() throws SQLException{
return imp.getDepartmentStrings();
}
public ArrayList<String> getMajor() throws SQLException{
return imp.getMajor();
}
public Boolean createAdvisor(Integer userId, String pname, String name_low, String name_high, Integer degree_types, Integer lead_status) throws SQLException{
return imp.createAdvisor(userId, pname, name_low, name_high, degree_types, lead_status);
}
}
|
Java
|
UTF-8
| 1,117 | 2.953125 | 3 |
[] |
no_license
|
package com.training.etiya.java.multithread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class Concurrent2 {
public static void main(final String[] args) {
ExecutorService newFixedThreadPoolLoc = Executors.newFixedThreadPool(5);
// Counter counterLoc = new Counter();
// for (int iLoc = 0; iLoc < 100_000_000; iLoc++) {
// newFixedThreadPoolLoc.execute(new Task(counterLoc));
// }
Future<String> submitLoc = newFixedThreadPoolLoc.submit(new TaskWithReturn());
// Extra process
try {
if (submitLoc.isDone()) {
}
String string2Loc = submitLoc.get(100,
TimeUnit.MILLISECONDS);
String stringLoc = submitLoc.get();
System.out.println("cevap : " + stringLoc);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
C++
|
UTF-8
| 4,783 | 2.84375 | 3 |
[] |
no_license
|
// Rotary Encoder Inputs
#define Rot_1_CLK 31
#define Rot_1_SW 30
#define Rot_1_DT 29
#define Rot_2_CLK 35
#define Rot_2_SW 34
#define Rot_2_DT 33
#define Rot_3_CLK 39
#define Rot_3_SW 38
#define Rot_3_DT 37
#define Brightness 49
#define LCD_Contrast_pin 3
#include <LiquidCrystal.h>
#include "Rotary.h";
Rotary rotary1 = Rotary(Rot_1_CLK, Rot_1_DT);
Rotary rotary2 = Rotary(Rot_2_CLK, Rot_2_DT);
Rotary rotary3 = Rotary(Rot_3_CLK, Rot_3_DT);
String cmdString = "";
int secondsOfInactivityShutOff = 10;
unsigned long timeOfEvent;
unsigned long lastButtonPress = 0;
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
void setup() {
timeOfEvent = millis();
pinMode(Brightness, OUTPUT);
digitalWrite(Brightness,1);
// Set Contrast of LCD to white
pinMode(LCD_Contrast_pin, OUTPUT);
analogWrite(LCD_Contrast_pin, 70);
// Set encoder pins as inputs 1
pinMode(Rot_1_SW, INPUT);
// Encoder 2
pinMode(Rot_2_SW, INPUT);
// Encoder 3
pinMode(Rot_3_SW, INPUT);
// Setup Serial Monitor
Serial.begin(9600);
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("Starting...");
delay(1500);
lcd.clear();
lcd.print("Connecting...");
Serial.begin(9600);
}
void loop() {
if (Serial.available())
{
char ch = Serial.read();
if(ch == ';')
{
processCommand(cmdString);
cmdString = "";
}
else
{
cmdString = cmdString + ch;
}
}
processEncoder1();
processEncoder2();
processEncoder3();
if(timeOfEvent + 1000 * secondsOfInactivityShutOff < millis())
{
// Shut off display aftter doing nothing for 10s
digitalWrite(Brightness,0);
}
}
void processEncoder1()
{
unsigned char result = rotary1.process();
if(result == DIR_CCW)
{
eventWake();
Serial.print("UP-1;");
}
else if(result == DIR_CW)
{
// Encoder is rotating CW so increment
eventWake();
Serial.print("DOWN-1;");
}
// Read the button state
int btnState = digitalRead(Rot_1_SW);
//If we detect LOW signal, button is pressed
if (btnState == LOW) {
//if 50ms have passed since last LOW pulse, it means that the
//button has been pressed, released and pressed again
if (millis() - lastButtonPress > 50)
{
eventWake();
Serial.print("PRESS-1;");
}
// Remember last button press event
lastButtonPress = millis();
}
}
void processEncoder2()
{
unsigned char result = rotary2.process();
if(result == DIR_CCW)
{
eventWake();
Serial.print("UP-2;");
}
else if(result == DIR_CW)
{
// Encoder is rotating CW so increment
eventWake();
Serial.print("DOWN-2;");
}
// Read the button state
int btnState = digitalRead(Rot_2_SW);
//If we detect LOW signal, button is pressed
if (btnState == LOW) {
//if 50ms have passed since last LOW pulse, it means that the
//button has been pressed, released and pressed again
if (millis() - lastButtonPress > 50)
{
eventWake();
Serial.print("PRESS-2;");
}
// Remember last button press event
lastButtonPress = millis();
}
}
void processEncoder3()
{
unsigned char result = rotary3.process();
if(result == DIR_CCW)
{
eventWake();
Serial.print("UP-3;");
}
else if(result == DIR_CW)
{
eventWake();
// Encoder is rotating CW so increment
Serial.print("DOWN-3;");
}
// Read the button state
int btnState = digitalRead(Rot_3_SW);
//If we detect LOW signal, button is pressed
if (btnState == LOW) {
//if 50ms have passed since last LOW pulse, it means that the
//button has been pressed, released and pressed again
if (millis() - lastButtonPress > 50)
{
eventWake();
Serial.print("PRESS-3;");
}
// Remember last button press event
lastButtonPress = millis();
}
}
// Available commands : ROW1: or ROW2:
void processCommand(String command)
{
eventWake();
timeOfEvent = millis();
if(command.startsWith("ROW1:"))
{
displayRow1(command.substring(5));
}
else if(command.startsWith("ROW2:"))
{
displayRow2(command.substring(5));
}
else if(command.startsWith("ECHO:"))
{
Serial.flush();
Serial.print(command + ';');
}
}
void displayRow1(String text)
{
//text = padStringTo16(text);
lcd.setCursor(0, 0);
lcd.print(text);
}
void displayRow2(String text)
{
text = padStringTo16(text);
for(int i = 0; i <= 15; i++)
{
lcd.setCursor(i,1);
if(text.charAt(i) == '*')
{
lcd.print((char)255);
}
else
{
lcd.print(text.charAt(i));
}
}
}
String padStringTo16(String strIn)
{
for(int i = strIn.length(); i <= 16; i++)
{
strIn += " ";
}
return strIn;
}
void eventWake()
{
timeOfEvent = millis();
digitalWrite(Brightness,1);
}
|
Python
|
UTF-8
| 3,408 | 3.84375 | 4 |
[] |
no_license
|
from collections import deque
class Tree(object):
class TreeNode(object):
def __init__(self, key, children=None):
self.key = key
if children is None:
self.children = []
else:
self.children = children
def is_leaf(self):
return len(self.children) == 0
def add_child(self, node):
self.children.append(node)
def __init__(self):
self.root = None
self.values = {}
def insert(self, key, where):
if key in self.values:
return False
if where is None and self.root is None:
self.root = Tree.TreeNode(key)
self.values[key] = True
return True
q = deque()
q.append(self.root)
while len(q):
node = q.popleft()
if node.key == where:
node.add_child(Tree.TreeNode(key))
self.values[key] = True
return True
for child in node.children:
q.append(child)
return False
def height(self, node=None):
if node is None:
node = self.root
# calculate heights of all children
heights = []
for child in node.children:
heights.append(self.height(child))
if len(node.children) == 0:
return 1
return 1 + max(heights)
class Graph(object):
def __init__(self, nodes, adjacency_lists):
self.nodes = nodes
self.adjacency_lists = adjacency_lists
def radius_diameter(self):
# find all eccentricities
eccentricities = []
for node in self.nodes:
t = self.minimum_spanning_tree(node)
h = t.height() - 1
# if the vertex has no adjacent neighbors, its height is 0 but its distance is technically infinite
if h > 0:
eccentricities.append(h)
# return min
return min(eccentricities), max(eccentricities)
@staticmethod
def from_file(filename):
nodes = []
adjacency_lists = {}
with open(filename, "r") as handle:
for line in handle.read().split("\n"):
source, dest = line.split(" ")
if source not in nodes:
nodes.append(source)
adjacency_lists[source] = []
if dest not in nodes:
nodes.append(dest)
adjacency_lists[dest] = []
adjacency_lists[source].append(dest)
return Graph(nodes, adjacency_lists)
def minimum_spanning_tree(self, start):
tree = Tree()
tree.insert(start, None)
# each entry in the queue will be a (parent, target) pair
q = deque()
visited = {}
for adj in self.adjacency_lists[start]:
q.append((start, adj))
while len(q):
parent, target = q.popleft()
visited[target] = True
tree.insert(target, parent)
for adj in self.adjacency_lists[target]:
if adj in visited:
continue
q.append((target, adj))
return tree
if __name__ == '__main__':
g = Graph.from_file("test.txt")
print(g.radius_diameter())
print(Graph.from_file("test2.txt").radius_diameter())
print()
|
JavaScript
|
UTF-8
| 1,243 | 3.1875 | 3 |
[] |
no_license
|
function scroll() {
let h2 = document.querySelector('#slidein');
console.log(window.scrollY);
if (0 <= window.scrollY){
h2.className = "animated slideLeft";
} else {
h2.className = "";
}
}
window.addEventListener("scroll", scroll);
function scroll2() {
let p = document.querySelector('#slidein2');
console.log(window.scrollY);
if (0 <= window.scrollY){
p.className = "animated slideLeft";
} else {
p.className = "";
}
}
window.addEventListener("scroll", scroll2);
function scroll3() {
let img = document.querySelector('#slidein3');
console.log(window.scrollY);
if (0 <= window.scrollY){
img.className = "animated slideRight";
} else {
img.className = "";
}
}
window.addEventListener("scroll", scroll3);
let slideIndex = 0;
showSlides();
// function plusSlides(n) {
// showSlides(slideIndex += n);
// }
function showSlides() {
let i;
let slides = document.getElementsByClassName("mySlides");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex > slides.length) {slideIndex = 1}
slides[slideIndex-1].style.display = "block";
setTimeout(showSlides, 5000); // Change image every 5 seconds
}
|
Java
|
UTF-8
| 1,906 | 2.296875 | 2 |
[] |
no_license
|
package com.smart.musicplayer.listener;
/**
* @date : 2018/11/29 下午5:00
* @author: lichen
* @email : 1960003945@qq.com
* @description :
*/
public interface MusicAllCallBack {
//开始加载,objects[0]是title,object[1]是当前所处播放器(全屏或非全屏)
void onStartPrepared(String url, Object... objects);
//加载成功,objects[0]是title,object[1]是当前所处播放器(全屏或非全屏)
void onPrepared(String url, Object... objects);
//点击了开始按键播放,objects[0]是title,object[1]是当前所处播放器(全屏或非全屏)
void onClickStartIcon(String url, Object... objects);
//点击了错误状态下的开始按键,objects[0]是title,object[1]是当前所处播放器(全屏或非全屏)
void onClickStartError(String url, Object... objects);
//点击了播放状态下的开始按键--->停止,objects[0]是title,object[1]是当前所处播放器(全屏或非全屏)
void onClickStop(String url, Object... objects);
//点击了暂停状态下的开始按键--->播放,objects[0]是title,object[1]是当前所处播放器(全屏或非全屏)
void onClickResume(String url, Object... objects);
//点击了空白弹出seekbar,objects[0]是title,object[1]是当前所处播放器(全屏或非全屏)
void onClickSeekbar(String url, Object... objects);
//播放完了,objects[0]是title,object[1]是当前所处播放器(全屏或非全屏)
void onAutoComplete(String url, Object... objects);
//触摸调整进度,objects[0]是title,object[1]是当前所处播放器(全屏或非全屏)
void onTouchScreenSeekPosition(String url, Object... objects);
//播放错误,objects[0]是title,object[1]是当前所处播放器(全屏或非全屏)
void onPlayError(String url, Object... objects);
}
|
Java
|
UTF-8
| 3,050 | 2.546875 | 3 |
[
"Apache-2.0"
] |
permissive
|
package com.axway.apim.api.export.lib;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.ParseException;
import com.axway.apim.lib.APIMCoreCLIOptions;
public class APIExportCLIOptions extends APIMCoreCLIOptions {
CommandLine cmd;
public APIExportCLIOptions(String[] args) throws ParseException {
super(args);
// Define command line options required for Application export
Option option = new Option("a", "api-path", true, "Define the APIs to be exported, based on the exposure path.\n"
+ "You can use wildcards to export multiple APIs:\n"
+ "-a /api/v1/my/great/api : Export a specific API\n"
+ "-a * : Export all APIs\n"
+ "-a /api/v1/any* : Export all APIs with this prefix\n"
+ "-a */some/other/api : Export APIs end with the same path\n");
option.setRequired(true);
option.setArgName("/api/v1/my/great/api");
options.addOption(option);
option = new Option("s", "stage", true, "The API-Management stage (prod, preprod, qa, etc.)\n"
+ "Is used to lookup the stage configuration file.");
option.setArgName("preprod");
options.addOption(option);
option = new Option("v", "vhost", true, "Limit the export to that specific host.");
option.setRequired(false);
option.setArgName("vhost.customer.com");
options.addOption(option);
option = new Option("l", "localFolder", true, "Defines the location to store API-Definitions locally. Defaults to current folder.\n"
+ "For each API a new folder is created automatically.");
option.setRequired(false);
option.setArgName("my/apis");
options.addOption(option);
option = new Option("df", "deleteFolder", true, "Controls if an existing local folder should be deleted. Defaults to false.");
option.setArgName("true");
options.addOption(option);
}
@Override
public void printUsage(String message, String[] args) {
super.printUsage(message, args);
System.out.println("You may run one of the following examples:");
System.out.println(getBinaryName()+" api export -c samples/basic/minimal-config.json -a ../petstore.json -h localhost -u apiadmin -p changeme");
System.out.println(getBinaryName()+" api export -c samples/basic/minimal-config.json -a ../petstore.json -h localhost -u apiadmin -p changeme -s prod");
System.out.println(getBinaryName()+" api export -c samples/complex/complete-config.json -a ../petstore.json -h localhost -u apiadmin -p changeme");
System.out.println();
System.out.println();
System.out.println("Using parameters provided in properties file stored in conf-folder:");
System.out.println(getBinaryName()+" api export -c samples/basic/minimal-config-api-definition.json -s api-env");
System.out.println();
System.out.println("For more information and advanced examples please visit:");
System.out.println("https://github.com/Axway-API-Management-Plus/apimanager-swagger-promote/wiki");
}
@Override
protected String getAppName() {
return "Application-Export";
}
}
|
Java
|
UTF-8
| 2,418 | 2.078125 | 2 |
[
"MIT"
] |
permissive
|
package info.spicyclient.modules.player;
import org.lwjgl.input.Keyboard;
import info.spicyclient.SpicyClient;
import info.spicyclient.events.Event;
import info.spicyclient.events.listeners.EventReceivePacket;
import info.spicyclient.events.listeners.EventUpdate;
import info.spicyclient.modules.Module;
import info.spicyclient.settings.ModeSetting;
import info.spicyclient.settings.SettingChangeEvent;
import net.minecraft.network.play.server.S02PacketChat;
import net.minecraft.network.play.server.S3BPacketScoreboardObjective;
import net.minecraft.network.play.server.S3CPacketUpdateScore;
import net.minecraft.network.play.server.S3DPacketDisplayScoreboard;
import net.minecraft.util.ChatComponentText;
public class HideName extends Module {
public ModeSetting mode = new ModeSetting("Name", "You", "You", "MooshroomMashUp", "Fox_of_floof", "lavaflowglow", "_Floofy_Fox_");
public HideName() {
super("HideName", Keyboard.KEY_NONE, Category.PLAYER);
resetSettings();
}
@Override
public void resetSettings() {
this.settings.clear();
this.addSettings(mode);
}
@Override
public void onEvent(Event e) {
if (e instanceof EventUpdate && e.isPre()) {
this.additionalInformation = mode.getMode();
}
if (e instanceof EventReceivePacket && e.isPre()) {
EventReceivePacket packetEvent = (EventReceivePacket) e;
if (packetEvent.packet instanceof S02PacketChat) {
S02PacketChat packet = (S02PacketChat) packetEvent.packet;
if (packet.getChatComponent().getUnformattedText().replaceAll("", "").contains(mc.getSession().getUsername())) {
packet.chatComponent = new ChatComponentText(packet.getChatComponent().getFormattedText().replaceAll("", "").replaceAll(mc.getSession().getUsername(), mode.getMode()));
}
}
else if (packetEvent.packet instanceof S3CPacketUpdateScore) {
S3CPacketUpdateScore packet = (S3CPacketUpdateScore) packetEvent.packet;
if (packet.getObjectiveName().replaceAll("", "").contains(mc.getSession().getUsername())){
packet.setObjective(packet.getObjectiveName().replaceAll("", "").replaceAll(mc.getSession().getUsername(), mode.getMode()));
}
if (packet.getName().replaceAll("", "").contains(mc.getSession().getUsername())){
packet.setName(packet.getName().replaceAll("", "").replaceAll(mc.getSession().getUsername(), mode.getMode()));
}
}
}
}
}
|
Java
|
UTF-8
| 543 | 2.125 | 2 |
[] |
no_license
|
package com.sam.delayorderforjava.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class OrderEntity {
private String orderNo;
private String orderNote;
private String status;
@Override
public String toString() {
return "OrderEntity{" +
"orderNo='" + orderNo + '\'' +
", orderNote='" + orderNote + '\'' +
", status='" + status + '\'' +
'}';
}
}
|
Java
|
UTF-8
| 411 | 1.835938 | 2 |
[] |
no_license
|
package com.example.soldrec.web.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TrackingNumberDTO {
/**
* 卖出时间
*/
private Long soldTime;
/**
* 商品名称
*/
private String productName;
/**
* 快递单号
*/
private String trackingNumber;
}
|
Markdown
|
UTF-8
| 2,092 | 3.4375 | 3 |
[] |
no_license
|
## 문제
방향 없는 그래프가 주어졌을 때, 연결 요소 (Connected Component)의 개수를 구하는 프로그램을 작성하시오.
## 입력
첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주어진다.
## 출력
첫째 줄에 연결 요소의 개수를 출력한다.
## 예제 입력 1
```
6 5
1 2
2 5
5 1
3 4
4 6
```
## 예제 출력 1
```
2
```
## 예제 입력 2
```
6 8
1 2
2 5
5 1
3 4
4 6
5 4
2 4
2 3
```
## 예제 출력 2
```
1
```
```java
package N11724;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int[][] map;
static int N;
static int M;
static int result;
static boolean[] visited;
public static void dfs(int ix){
if(visited[ix] == true) return;
else
{
visited[ix] = true;
for (int i = 1; i < N+1; i++) {
if(map[ix][i] == 1) dfs(i);
}
}
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
int u,v;
map = new int[N+1][N+1];
visited = new boolean[N+1];
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
u = Integer.parseInt(st.nextToken());
v = Integer.parseInt(st.nextToken());
map[u][v] = map[v][u] = 1;
}
result = 0;
for (int i = 1; i < N+1; i++) {
if(visited[i] == false){
dfs(i);
result++;
}
}
System.out.println(result);
}
}
```
|
C++
|
UTF-8
| 1,303 | 2.875 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<int> R;
vector<int> parking;
vector<int> W;
queue<int> delay;
int n, m, cash;
int empty_index()
{
for (int i = 0; i < n; i++)
{
if (parking[i] == 0)
{
return i;
}
}
return -1;
}
int find_index(int x)
{
x = x * -1;
for (int i = 0; i < n; i++)
{
if (parking[i] == x)
return i;
}
}
void solve(int x)
{
int index = empty_index();
if (x >= 0)
{
if (index != -1)
{
cash += (R[index] * W[x]);
parking[index] = x;
}
else {
delay.push(x);
}
}
else
{
int fid = find_index(x);
parking[fid] = 0;
if (!delay.empty())
{
int d = delay.front();
delay.pop();
cash += (R[fid] * W[d]);
parking[fid] = d;
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int tc;
cin >> tc;
for (int t = 1; t <= tc; t++)
{
int tmp;
cash = 0;
W.push_back(0);
cin >> n >> m;
for (int i = 0; i < n; i++)
{
cin >> tmp;
R.push_back(tmp);
parking.push_back(0);
}
for (int i = 0; i < m; i++)
{
cin >> tmp;
W.push_back(tmp);
}
for (int i = 0; i < 2 * m; i++)
{
cin >> tmp;
solve(tmp);
}
cout << "#" << t << " " << cash << '\n';
R.clear();
W.clear();
parking.clear();
}
return 0;
}
|
JavaScript
|
UTF-8
| 434 | 3.03125 | 3 |
[] |
no_license
|
'use strict';
var product = {
name: 'laptop',
price: 234.44
};
var product2 = {
name: 'Peanut Butter',
price: 5.99
};
product['description'] = 'A fast laptop';
function calculateTax2() {
return this.price * .08;
}
product.calculateTax = calculateTax2;
product2.calculateTax = calculateTax2;
console.log(product.calculateTax());
console.log(product2.calculateTax());
//console.log(calculateTax2()); this will log an error
|
Java
|
UTF-8
| 1,083 | 2.5 | 2 |
[] |
no_license
|
package com.example.thelabit.modelo;
public class FeedBack {
private Integer Freshness;
private Integer Dureza;
private Integer Recuperacion;
private String Comentario;
public Integer getFreshness() {
return Freshness;
}
public void setFreshness(Integer freshness) {
Freshness = freshness;
}
public Integer getDureza() {
return Dureza;
}
public void setDureza(Integer dureza) {
Dureza = dureza;
}
public Integer getRecuperacion() {
return Recuperacion;
}
public void setRecuperacion(Integer recuperacion) {
Recuperacion = recuperacion;
}
public String getComentario() {
return Comentario;
}
public void setComentario(String comentario) {
Comentario = comentario;
}
public FeedBack() {
}
public FeedBack(Integer freshness, Integer dureza, Integer recuperacion, String comentario) {
Freshness = freshness;
Dureza = dureza;
Recuperacion = recuperacion;
Comentario = comentario;
}
}
|
Markdown
|
UTF-8
| 23 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
# Global-Game-Game-2021
|
Java
|
UTF-8
| 298 | 1.671875 | 2 |
[] |
no_license
|
package com.cnit.yoyo.spider.autohome.service;
import java.util.List;
import com.cnit.yoyo.spider.common.dto.autohome.pojo.CarColor;
/**
* 车颜色
* @Author:yangyi
* @Date:2015年6月8日
* @Version:1.0.0
*/
public interface CarColorService {
void addOrUpd(List<CarColor> eList);
}
|
Java
|
UTF-8
| 3,707 | 2.5625 | 3 |
[] |
no_license
|
package dao;
import java.util.ArrayList;
import java.util.List;
import model.Avaliacao;
import model.Desenvolvedor;
import model.Empresario;
import model.Lance;
import model.Projeto;
import model.Usuario;
import org.hibernate.Query;
import org.hibernate.Session;
public class ProjetoDAO extends GenericDAO {
public ArrayList<Projeto> getAll() {
ArrayList lista = super.getAll("Projeto");
ArrayList<Projeto> temp = new ArrayList<Projeto>();
for (Object obj : lista) {
temp.add((Projeto) obj);
}
return temp;
}
public Projeto getById(Integer id) {
return (Projeto) super.getById("Projeto", id);
}
public List<Projeto> getProjetosByEmpresario(Empresario emp) {
Session session = this.Connection();
String hql = "FROM Projeto p where p.empresario.id = " + emp.getId();
Query query = session.createQuery(hql);
ArrayList<Object> results2 = (ArrayList<Object>) query.list();
session.close();
List<Projeto> projetos = new ArrayList<Projeto>();
for (Object p : results2) {
projetos.add((Projeto) p);
}
return projetos;
}
public List<Projeto> getProjetosByDesenvolvedor(Desenvolvedor dev) {
Session session = super.Connection();
String hql = "FROM Projeto p where p.desenvolvedor.id = '"
+ dev.getId() + "'";
Query query = session.createQuery(hql);
List<Projeto> atuados = (List<Projeto>) query.list();
session.close();
System.out.println(atuados);
return atuados;
}
public List<Lance> getLancesByProjeto(Projeto p) {
Session session = super.Connection();
String hql = "FROM Lance l where l.projeto.id = '" + p.getId() + "'";
Query query = session.createQuery(hql);
List<Lance> lances = (List<Lance>) query.list();
session.close();
return lances;
}
public boolean getAvaliado(Projeto p, String string){
boolean avaliado = false;
Session session = super.Connection();
if(string == "empresario"){
String hql = "FROM Avaliacao a where a.projeto.id = '"+p.getId()+"' AND a.empresarioDestino != NULL";
Query query = session.createQuery(hql);
List<Avaliacao> avaliacoes = (List<Avaliacao>) query.list();
session.close();
if(avaliacoes.size() > 0){
avaliado = true;
}
}
else if(string == "desenvolvedor"){
String hql = "FROM Avaliacao a where a.projeto.id = '"+p.getId()+"' AND a.desenvolvedorDestino != NULL";
Query query = session.createQuery(hql);
List<Avaliacao> avaliacoes = (List<Avaliacao>) query.list();
session.close();
if(avaliacoes.size() > 0){
avaliado = true;
}
}
System.out.println(avaliado);
return avaliado;
}
public ArrayList getProjetosDisponiveis(int limit){
Session session = this.Connection();
String hql = "FROM Projeto p where p.status = 'pendente' OR p.status = 'novo'";
Query query = session.createQuery(hql);
if(limit != 0){
query.setMaxResults(limit);
}
ArrayList<Object> projetosDisponiveis = (ArrayList<Object>) query.list();
session.close();
return projetosDisponiveis;
}
public Usuario getUsuarioByProjeto(Projeto p){
Session session = this.Connection();
String hql = "SELECT desenvolvedor FROM Projeto p where p.id = "+p.getId();
Query query = session.createQuery(hql);
ArrayList<Object> desenvolvedor = (ArrayList<Object>) query.list();
session.close();
return (Usuario)desenvolvedor.get(0);
}
public Lance getLanceAtivoByProjeto(Projeto p) {
Session session = super.Connection();
String hql = "FROM Lance l where l.projeto.id = '" + p.getId() + "' and l.escolhido = 1";
Query query = session.createQuery(hql);
Lance lance = (Lance)query.list().get(0);
session.close();
return lance;
}
public Projeto getLast() {
Projeto p = (Projeto)super.getLast("Projeto");
return p;
}
}
|
PHP
|
UTF-8
| 749 | 2.5625 | 3 |
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: bond
* Date: 23/11/2016
* Time: 22:37
*/
namespace pamel\core\messages;
use pamel\api\core\messages\Exchange as ApiExchange;
class Exchange extends ApiExchange
{
public function getMessage()
{
return $this->message;
}
public function getOriginalMessage()
{
return $this->originalMessage;
}
public function setMessage(Message $message)
{
$this->message = $message;
}
public function setOriginalMessage($originalMessage)
{
$this->originalMessage = $originalMessage;
}
public function setOut($message)
{
$this->out = $message;
}
public function getOut()
{
return $this->out;
}
}
|
Java
|
UTF-8
| 18,672 | 2.390625 | 2 |
[] |
no_license
|
package com.ibm.watson.developer_cloud.personality_insights.v2;
import java.util.List;
import com.ibm.watson.developer_cloud.personality_insights.v2.model.Profile;
import com.ibm.watson.developer_cloud.personality_insights.v2.model.Trait;
public class PersonalityInsightsExample {
public static void main(String[] args) {
PersonalityInsights service = new PersonalityInsights();
//service.setUsernameAndPassword("<username>", "<password>");
service.setUsernameAndPassword("a1b14481-c269-4824-88fc-8a88939eed00", "LXvc0uhcsjCb");
/*
{
"url": "https://gateway.watsonplatform.net/personality-insights/api",
"password": "LXvc0uhcsjCb",
"username": "a1b14481-c269-4824-88fc-8a88939eed00"
}
*/
String text =
"Call me Ishmael. Some years ago-never mind how long "
+ "precisely-having little or no money in my purse, and nothing "
+ "particular to interest me on shore, I thought I would sail about "
+ "a little and see the watery part of the world. It is a way "
+ "I have of driving off the spleen and regulating the circulation. "
+ "Whenever I find myself growing grim about the mouth; whenever it "
+ "is a damp, drizzly November in my soul; whenever I find myself "
+ "involuntarily pausing before coffin warehouses, and bringing up "
+ "the rear of every funeral I meet; and especially whenever my "
+ "hypos get such an upper hand of me, that it requires a strong "
+ "moral principle to prevent me from deliberately stepping into "
+ "the street, and methodically knocking people's hats off-then, "
+ "I account it high time to get to sea as soon as I can.";
Profile profile = service.getProfile(text).execute();
String id=profile.getId();
String processed_lang=profile.getProcessedLanguage();
String source=profile.getSource();
Trait trait = profile.getTree();
int wordCount=profile.getWordCount();
String workCoundMessage=profile.getWordCountMessage();
System.out.println("id=" + id + ";processed_lang=" + processed_lang + ";source=" + source + ";wordCount=" + wordCount + ";workCoundMessage=" + workCoundMessage);
List<Trait> traits1=trait.getChildren();
for( Trait myTrait1 : traits1 ) {
String myCategory1=myTrait1.getCategory();
String myID1=myTrait1.getId();
String myName1=myTrait1.getName();
Double myPercentage1=myTrait1.getPercentage();
Double mySamplingError1=myTrait1.getSamplingError();
System.out.println("Category1=" + myCategory1 + ";id1=" + myID1 + ";name1=" + myName1 + ";percentage1=" + myPercentage1 + ";samplingError1=" + mySamplingError1);
List<Trait> myTraits2=myTrait1.getChildren();
for( Trait myTrait2 : myTraits2 ) {
String myCategory2=myTrait2.getCategory();
String myID2=myTrait2.getId();
String myName2=myTrait2.getName();
Double myPercentage2=myTrait2.getPercentage();
Double mySamplingError2=myTrait2.getSamplingError();
System.out.println("Category2=" + myCategory2 + ";id2=" + myID2 + ";name2=" + myName2 + ";percentage2=" + myPercentage2 + ";samplingError2=" + mySamplingError2);
List<Trait> myTraits3=myTrait2.getChildren();
for( Trait myTrait3 : myTraits3 ) {
String myCategory3=myTrait3.getCategory();
String myID3=myTrait3.getId();
String myName3=myTrait3.getName();
Double myPercentage3=myTrait3.getPercentage();
Double mySamplingError3=myTrait3.getSamplingError();
List<Trait> myTraits4=myTrait3.getChildren();
System.out.println("Category3=" + myCategory3 + ";id3=" + myID3 + ";name3=" + myName3 + ";percentage3=" + myPercentage3 + ";samplingError3=" + mySamplingError3 );
System.out.println(myTraits4);
}
}
}
//System.out.println(profile);
}
}
/*
Aug 14, 2016 9:51:04 PM com.ibm.watson.developer_cloud.util.CredentialUtils getKeyUsingJNDI
INFO: JNDI watson-developer-cloud/personality_insights/credentials not found.
{
"id": "*UNKNOWN*",
"processed_lang": "en",
"source": "*UNKNOWN*",
"tree": {
"children": [
{
"children": [
{
"category": "personality",
"children": [
{
"category": "personality",
"children": [
{
"category": "personality",
"id": "Adventurousness",
"name": "Adventurousness",
"percentage": 0.24273567659303688,
"sampling_error": 0.054508355599999996
},
{
"category": "personality",
"id": "Artistic interests",
"name": "Artistic interests",
"percentage": 0.1043290657163104,
"sampling_error": 0.1105694696
},
{
"category": "personality",
"id": "Emotionality",
"name": "Emotionality",
"percentage": 0.8132992201380651,
"sampling_error": 0.0511414066
},
{
"category": "personality",
"id": "Imagination",
"name": "Imagination",
"percentage": 0.36161485612768607,
"sampling_error": 0.0687314696
},
{
"category": "personality",
"id": "Intellect",
"name": "Intellect",
"percentage": 0.5009869824564314,
"sampling_error": 0.0604259074
},
{
"category": "personality",
"id": "Liberalism",
"name": "Authority-challenging",
"percentage": 0.9440958312234307,
"sampling_error": 0.08844844119999999
}
],
"id": "Openness",
"name": "Openness",
"percentage": 0.7051861397046637,
"sampling_error": 0.0653032944
},
{
"category": "personality",
"children": [
{
"category": "personality",
"id": "Achievement striving",
"name": "Achievement striving",
"percentage": 0.47503219156488846,
"sampling_error": 0.1047757272
},
{
"category": "personality",
"id": "Cautiousness",
"name": "Cautiousness",
"percentage": 0.6962411095195775,
"sampling_error": 0.0969161446
},
{
"category": "personality",
"id": "Dutifulness",
"name": "Dutifulness",
"percentage": 0.45384312564939444,
"sampling_error": 0.066068398
},
{
"category": "personality",
"id": "Orderliness",
"name": "Orderliness",
"percentage": 0.99,
"sampling_error": 0.0745509562
},
{
"category": "personality",
"id": "Self-discipline",
"name": "Self-discipline",
"percentage": 0.6206377869026388,
"sampling_error": 0.0501648544
},
{
"category": "personality",
"id": "Self-efficacy",
"name": "Self-efficacy",
"percentage": 0.7855118958460193,
"sampling_error": 0.09784636840000001
}
],
"id": "Conscientiousness",
"name": "Conscientiousness",
"percentage": 0.7509619654135328,
"sampling_error": 0.0815783018
},
{
"category": "personality",
"children": [
{
"category": "personality",
"id": "Activity level",
"name": "Activity level",
"percentage": 0.13206572673240438,
"sampling_error": 0.0831364296
},
{
"category": "personality",
"id": "Assertiveness",
"name": "Assertiveness",
"percentage": 0.13130439422727444,
"sampling_error": 0.08850146580000001
},
{
"category": "personality",
"id": "Cheerfulness",
"name": "Cheerfulness",
"percentage": 0.08993348833481232,
"sampling_error": 0.11119159220000001
},
{
"category": "personality",
"id": "Excitement-seeking",
"name": "Excitement-seeking",
"percentage": 0.061898016284663605,
"sampling_error": 0.08486297720000001
},
{
"category": "personality",
"id": "Friendliness",
"name": "Outgoing",
"percentage": 0.021582900452582564,
"sampling_error": 0.0799469824
},
{
"category": "personality",
"id": "Gregariousness",
"name": "Gregariousness",
"percentage": 0.009211874520246268,
"sampling_error": 0.0612727814
}
],
"id": "Extraversion",
"name": "Extraversion",
"percentage": 0.0673936678439218,
"sampling_error": 0.0610899574
},
{
"category": "personality",
"children": [
{
"category": "personality",
"id": "Altruism",
"name": "Altruism",
"percentage": 0.09338041151739289,
"sampling_error": 0.0754516306
},
{
"category": "personality",
"id": "Cooperation",
"name": "Cooperation",
"percentage": 0.6156317000117122,
"sampling_error": 0.0840564614
},
{
"category": "personality",
"id": "Modesty",
"name": "Modesty",
"percentage": 0.08280068048565797,
"sampling_error": 0.0603121934
},
{
"category": "personality",
"id": "Morality",
"name": "Uncompromising",
"percentage": 0.5057874217859515,
"sampling_error": 0.067044696
},
{
"category": "personality",
"id": "Sympathy",
"name": "Sympathy",
"percentage": 0.9667826769405433,
"sampling_error": 0.1032267996
},
{
"category": "personality",
"id": "Trust",
"name": "Trust",
"percentage": 0.14365655969774646,
"sampling_error": 0.0615205956
}
],
"id": "Agreeableness",
"name": "Agreeableness",
"percentage": 0.16614363537300278,
"sampling_error": 0.10193945
},
{
"category": "personality",
"children": [
{
"category": "personality",
"id": "Anger",
"name": "Fiery",
"percentage": 0.7763385243499553,
"sampling_error": 0.0993531718
},
{
"category": "personality",
"id": "Anxiety",
"name": "Prone to worry",
"percentage": 0.7761378863706873,
"sampling_error": 0.059064681200000003
},
{
"category": "personality",
"id": "Depression",
"name": "Melancholy",
"percentage": 0.33827105688535825,
"sampling_error": 0.0633628384
},
{
"category": "personality",
"id": "Immoderation",
"name": "Immoderation",
"percentage": 0.6815723142187143,
"sampling_error": 0.057044794
},
{
"category": "personality",
"id": "Self-consciousness",
"name": "Self-consciousness",
"percentage": 0.8580216044727753,
"sampling_error": 0.061179929800000005
},
{
"category": "personality",
"id": "Vulnerability",
"name": "Susceptible to stress",
"percentage": 0.941266993614812,
"sampling_error": 0.090874675
}
],
"id": "Neuroticism",
"name": "Emotional range",
"percentage": 0.8900934212705964,
"sampling_error": 0.09652001299999999
}
],
"id": "Extraversion_parent",
"name": "Extraversion",
"percentage": 0.0673936678439218
}
],
"id": "personality",
"name": "Big 5"
},
{
"children": [
{
"category": "needs",
"children": [
{
"category": "needs",
"id": "Challenge",
"name": "Challenge",
"percentage": 0.2371154709396367,
"sampling_error": 0.087784926
},
{
"category": "needs",
"id": "Closeness",
"name": "Closeness",
"percentage": 0.05317178584318431,
"sampling_error": 0.0866021168
},
{
"category": "needs",
"id": "Curiosity",
"name": "Curiosity",
"percentage": 0.06903749213008605,
"sampling_error": 0.1251023292
},
{
"category": "needs",
"id": "Excitement",
"name": "Excitement",
"percentage": 0.02858786857596093,
"sampling_error": 0.1143929704
},
{
"category": "needs",
"id": "Harmony",
"name": "Harmony",
"percentage": 0.7666679171146792,
"sampling_error": 0.114680861
},
{
"category": "needs",
"id": "Ideal",
"name": "Ideal",
"percentage": 0.03850021769664435,
"sampling_error": 0.1039405576
},
{
"category": "needs",
"id": "Liberty",
"name": "Liberty",
"percentage": 0.1511971508242999,
"sampling_error": 0.1510055532
},
{
"category": "needs",
"id": "Love",
"name": "Love",
"percentage": 0.3595763983667631,
"sampling_error": 0.1054972456
},
{
"category": "needs",
"id": "Practicality",
"name": "Practicality",
"percentage": 0.5357185381465674,
"sampling_error": 0.0918414682
},
{
"category": "needs",
"id": "Self-expression",
"name": "Self-expression",
"percentage": 0.007484747858497035,
"sampling_error": 0.0853109926
},
{
"category": "needs",
"id": "Stability",
"name": "Stability",
"percentage": 0.022806632023977973,
"sampling_error": 0.1115643634
},
{
"category": "needs",
"id": "Structure",
"name": "Structure",
"percentage": 0.00982823875359894,
"sampling_error": 0.0838920682
}
],
"id": "Self-expression_parent",
"name": "Self-expression",
"percentage": 0.007484747858497035
}
],
"id": "needs",
"name": "Needs"
},
{
"children": [
{
"category": "values",
"children": [
{
"category": "values",
"id": "Conservation",
"name": "Conservation",
"percentage": 0.0596056600669576,
"sampling_error": 0.0712865342
},
{
"category": "values",
"id": "Openness to change",
"name": "Openness to change",
"percentage": 0.8359604610465452,
"sampling_error": 0.06873593
},
{
"category": "values",
"id": "Hedonism",
"name": "Hedonism",
"percentage": 0.9744291651859416,
"sampling_error": 0.1428667446
},
{
"category": "values",
"id": "Self-enhancement",
"name": "Self-enhancement",
"percentage": 0.4038628866818849,
"sampling_error": 0.1086705544
},
{
"category": "values",
"id": "Self-transcendence",
"name": "Self-transcendence",
"percentage": 0.636047477500914,
"sampling_error": 0.086691064
}
],
"id": "Hedonism_parent",
"name": "Hedonism",
"percentage": 0.9744291651859416
}
],
"id": "values",
"name": "Values"
}
],
"id": "r",
"name": "root"
},
"word_count": 142,
"word_count_message": "There were 142 words in the input. We need a minimum of 3,500, preferably 6,000 or more, to compute statistically significant estimates"
}
*/
|
Java
|
SHIFT_JIS
| 22,820 | 1.734375 | 2 |
[] |
no_license
|
package com.lab.jti.thai;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.GeoPoint;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.PolylineOptions;
/**
* }bvANeBreB }bv
*/
public class MapActivity extends FragmentActivity implements LocationListener {
private final String TAG = "MapActivity"; // ^O
public static final int MENU_SERVER_START = 0; // ʐMJn
public static final int MENU_SERVER_STOP = 1; // ʐM~
// public static final int MENU_SETTING = 2; // ݒ
public static final int MENU_USER_REGIST = 3; // [U[o^
public static final int MENU_GROUP_REGIST = 4; // O[vlj
public static final int MENU_GROUP_PART= 5; // O[vQ
public static final int MENU_GROUP_SEARCH = 6; // O[v
public static final int MENU_SEARCH = 7; // O[v
public static final int MENU_ROUTE_SEARCH = 8; // oH
static boolean mIsGoogleMap = false; // O[O}bvpۃtO
private static GoogleMap mGoogleMap; // O[O}bv
private int mGooglePlayServicesStatus = 99; // GooglePlayServicesXe[^X
private boolean mIsAvailabilityProvider = false; // voC_pۃtO
public static int mMapType = 0;
public static int mMinTimeVal = 0;
public static int mMinDistanceVal = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
Log.d(TAG, "onCreate: " + "Start");
getLocaltionProvider(); // ʒuvoC_擾
mGooglePlayServicesStatus = setGooglePlayServices(); // GooglePlayServicesݒ菈
setDispLocation(); // ݒn\ݒ菈
updateLocation(); // ݒnXV
setZoomLocation(15); // Y[lݒ菈
// NGXg^C}[ N
startService(new Intent(getBaseContext(), SendRequestTimerService.class));
Log.d(TAG, "onCreate: " + "End");
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume: " + "Start");
Log.d(TAG, "onResume: " + "Start");
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause: " + "Start");
Log.d(TAG, "onPause: " + "End");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.d(TAG, "onCreateOptionsMenu : " + "Start");
getMenuInflater().inflate(R.menu.main, menu);
menu.add(0, MENU_SERVER_START, 0, "ʐMJn");
menu.add(0, MENU_SERVER_STOP, 0, "ʐM~");
// menu.add(0, MENU_SETTING, 0, "ݒ");
// menu.add(0, MENU_USER_REGIST, 0, "[U[o^");
// menu.add(0, MENU_GROUP_REGIST, 0, "O[vo^");
// menu.add(0, MENU_GROUP_PART, 0, "O[vQ");
// menu.add(0, MENU_GROUP_SEARCH, 0, "O[v");
menu.add(0, MENU_ROUTE_SEARCH, 0, "oH");
Log.d(TAG, "onCreateOptionsMenu : " + "End");
return true;
}
public boolean onOptionsItemSelected(MenuItem menuItem) {
Log.d(TAG, "onOptionsItemSelected : " + "Start");
Intent intent = null;
switch (menuItem.getItemId()) {
case MENU_SERVER_START:
Log.d(TAG, "MENU_START : " + "Start");
// NGXg^C}[ Jn
startService(new Intent(getBaseContext(), SendRequestTimerService.class));
Log.d(TAG, "MENU_START : " + "End");
return true;
case MENU_SERVER_STOP:
Log.d(TAG, "MENU_STOP : " + "Start");
// NGXg^C}[ ~
stopService(new Intent(getBaseContext(), SendRequestTimerService.class));
Log.d(TAG, "MENU_STOP : " + "End");
return true;
// case MENU_SETTING:
// Log.d(TAG, "MENU_SETTING : " + "Start");
// stopService(new Intent(getBaseContext(), SendRequestTimerService.class));
// // Mapݒ菈
// intent = new Intent(MapActivity.this, SettingActivity.class);
// startActivity(intent);
// Log.d(TAG, "MENU_SETTING : " + "End");
// return true;
case MENU_USER_REGIST:
Log.d(TAG, "MENU_USER_REGIST : " + "Start");
if (MainActivity.mIsSharedPreferences == true) {
Toast.makeText(this, "[U[o^ς݂ł", Toast.LENGTH_SHORT).show();
} else {
stopService(new Intent(getBaseContext(), SendRequestTimerService.class));
// [U[o^
intent = new Intent(MapActivity.this, RegistUserActivity.class);
startActivity(intent);
}
Log.d(TAG, "MENU_USER_REGIST : " + "End");
return true;
case MENU_GROUP_REGIST:
Log.d(TAG, "MENU_GROUP_REGIST : " + "Start");
if (MainActivity.mIsSharedPreferences == true) {
stopService(new Intent(getBaseContext(), SendRequestTimerService.class));
// O[vlj
intent = new Intent(MapActivity.this, RegistGroupActivity.class);
startActivity(intent);
} else {
Toast.makeText(this, "[U[o^łB", Toast.LENGTH_SHORT).show();
}
Log.d(TAG, "MENU_GROUP_REGIST : " + "End");
return true;
case MENU_GROUP_PART:
Log.d(TAG, "MENU_GROUP_PART : " + "Start");
if (MainActivity.mIsSharedPreferences == true) {
stopService(new Intent(getBaseContext(), SendRequestTimerService.class));
// O[vQ
intent = new Intent(MapActivity.this, PartGroupActivity.class);
startActivity(intent);
} else {
Toast.makeText(this, "[U[o^łB", Toast.LENGTH_SHORT).show();
}
Log.d(TAG, "MENU_GROUP_PART : " + "End");
return true;
case MENU_GROUP_SEARCH:
Log.d(TAG, "MENU_GROUP_SEARCH : " + "Start");
stopService(new Intent(getBaseContext(), SendRequestTimerService.class));
// O[v
intent = new Intent(MapActivity.this, SearchGroupActivity.class);
startActivity(intent);
Log.d(TAG, "MENU_GROUP_SEARCH : " + "End");
return true;
case MENU_ROUTE_SEARCH:
Log.d(TAG, "MENU_ROUTE_SEARCH : " + "Start");
stopService(new Intent(getBaseContext(), SendRequestTimerService.class));
// O[v
intent = new Intent(MapActivity.this, RouteSearchActivity.class);
startActivity(intent);
Log.d(TAG, "MENU_ROUTE_SEARCH : " + "End");
return true;
}
Log.d(TAG, "onOptionsItemSelected : " + "End");
return false;
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.d(TAG, "onLocationChanged : " + "Start");
LocationInfo.setLatitude((float) location.getLatitude()); // ݈ʒüܓx擾
LocationInfo.setLongitude((float) location.getLongitude()); // ݈ʒǔox擾
LocationInfo.setLatLng();
LocationInfo.setActionHistoryList(LocationInfo.getLatLng());
if (mIsGoogleMap) {
Toast.makeText(this, "onLocationChanged = " + location.getLatitude() + " " + location.getLongitude(), Toast.LENGTH_SHORT).show();
updateLocation(); // ݒnXV
setDispLocation(); // ݒn\ݒ菈
drawPolyLine_ActionHistory(); // s|C`揈
}
Log.d(TAG, "onLocationChanged : " + "location.getLatitude() = " + location.getLatitude() + " / " + "location.getLongitude() = " + location.getLongitude());
Log.d(TAG, "onLocationChanged : " + "End");
}
@Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "onProviderDisabled : " + "Start");
Log.d(TAG, "onProviderDisabled : " + "End");
}
@Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "onProviderEnabled : " + "Start");
Log.d(TAG, "onProviderEnabled : " + "End");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "response : " + "onStatusChanged Start");
Log.d(TAG, "response : " + "onStatusChanged End");
}
/**
* ʒuvoC_擾
*/
private void getLocaltionProvider() {
Log.d(TAG, "getLocaltion : " + "Start");
@SuppressWarnings("deprecation")
String providerStatus = android.provider.Settings.Secure.getString(this.getContentResolver(), Secure.LOCATION_PROVIDERS_ALLOWED); // p\voC_J}Ŏ擾
LocationInfo.mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); // LocationManager̎擾
Location location = null; // Location
if (providerStatus.matches(".*" + LocationManager.GPS_PROVIDER + ".*")) { // GPS擾Jn
// LocationInfo.mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 10, this);
LocationInfo.mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, this);
location = LocationInfo.mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) { // lbg[N擾Jn
LocationInfo.mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 10, this);
location = LocationInfo.mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
mIsAvailabilityProvider = true;
}
} else {
mIsAvailabilityProvider = true;
}
} else if (providerStatus.matches(".*" + LocationManager.NETWORK_PROVIDER + ".*")) { // lbg[N擾Jn
LocationInfo.mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 10, this);
location = LocationInfo.mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
mIsAvailabilityProvider = true;
}
if (!mIsAvailabilityProvider) {
Toast.makeText(this, "ʒu擾ł܂", Toast.LENGTH_SHORT).show();
}
onLocationChanged(location);
Log.d(TAG, "getLocaltion : " + "End");
}
/**
* GooglePlayServicesݒ菈
*/
public int setGooglePlayServices() {
Log.d(TAG, "setGooglePlayServices: " + "Start");
int googlePlayServicesStatus = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext()); // GooglePlayServicesԔ
if (googlePlayServicesStatus == ConnectionResult.SUCCESS) {
mGooglePlayServicesStatus = ConnectionResult.SUCCESS;
SupportMapFragment smf = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mGoogleMap = smf.getMap(); // fragmentGoogleMap object擾
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.setIndoorEnabled(true);
if (mMapType == 1) {
} else if (mMapType == 2) {
} else if (mMapType == 3) {
} else if (mMapType == 4) {
} else if (mMapType == 5) {
}
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mGoogleMap.setTrafficEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
// LocationInfo.setBestProvider(locationManager.getBestProvider(criteria,
// true));
// LocationInfo.setBestProvider(LocationInfo.mLocationManager.getBestProvider(criteria,
// true));
mIsGoogleMap = true;
} else {
mGooglePlayServicesStatus = 10;
GooglePlayServicesUtil.getErrorDialog(googlePlayServicesStatus, this, mGooglePlayServicesStatus).show();
}
Log.d(TAG, "setGooglePlayServices : " + "End");
return mGooglePlayServicesStatus;
}
/**
* ݒnXV
*/
public static void updateLocation() {
Log.d("MapActivity", "updateLocation : " + "Start");
while (true) {
if ((int) LocationInfo.getLatitude() > 0 && (int) LocationInfo.getLongitude() > 0) {
LocationInfo.setGeoPoint(new GeoPoint((int) LocationInfo.getLatitude(), (int) LocationInfo.getLongitude()));
break;
}
}
Log.d("MapActivity", "updateLocation : " + "End");
}
/**
* ݒn\ݒ菈
*/
public static void setDispLocation() {
Log.d("MapActivity", "dispLocation : " + "Start");
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(LocationInfo.getLatLng())); // GoogleMapɌݒn\
Log.d("MapActivity", "dispLocation : " + "End");
}
/**
* ݒn\
*/
public static void dispLocation() {
Log.d("MapActivity", "dispLocation : " + "Start");
// ݒnݒ菈
setDispLocation();
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(LocationInfo.getLatitude(), LocationInfo.getLongitude())).zoom(17.0f).bearing(0).build();
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(LocationInfo.getLatLng())); // GoogleMapɌݒn\
Log.d("MapActivity", "dispLocation : " + "End");
}
/**
* Y[lݒ菈
*/
public static void setZoomLocation(int zoomTo) {
Log.d("MapActivity", "setZoomLocation : " + "Start");
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(zoomTo)); // GoogleMapZoomlw
Log.d("MapActivity", "setZoomLocation : " + "End");
}
/**
* tO`揈
*
* @param map
*/
public static void drawShopFlag(HashMap<String, String> map, int iconColor) {
Log.d("MapActivity", "setShopFlag : " + "Start");
MarkerOptions options = new MarkerOptions();
Double shop_latitude = Double.valueOf(map.get("shop_latitude"));
Double shop_longitude = Double.valueOf(map.get("shop_longitude"));
LatLng latLng = new LatLng(shop_latitude, shop_longitude);
options.position(latLng);
options.title(map.get("shop_name"));
options.snippet(map.get("shop_address"));
BitmapDescriptor icon = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET);
if (iconColor == 0) {
icon = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED);
} else if (iconColor == 1) {
icon = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE);
} else if (iconColor == 2) {
icon = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN);
} else {
icon = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET);
}
options.icon(icon);
LocationInfo.setMarker(mGoogleMap.addMarker(options)); // }bvɃ}[J[lj
Log.d("MapActivity", "setShopFlag : " + "End");
}
/**
* s|C`揈
*
*/
private void drawPolyLine_ActionHistory() {
Log.d("MapActivity", "drawPolyLine_ActionHistory : " + "Start");
PolylineOptions polylineOptions = new PolylineOptions();
float latitude = 0;
float longitude = 0;
for (LatLng actionHistory : LocationInfo.getActionHistoryList()) {
float latitudeDiff = (float) (actionHistory.latitude - latitude);
float longitudeDiff = (float) (actionHistory.longitude - longitude);
Log.d("MapActivity", "擾ʒu : " + "latitudeDiff = " + latitudeDiff + " / " + "longitudeDiff = " + longitudeDiff);
if (Math.abs(latitudeDiff) >= 0.001 && Math.abs(longitudeDiff) >= 0.001) { // 100m̍قɂĂ͕`悵Ȃ
latitude = (float) actionHistory.latitude;
longitude = (float) actionHistory.longitude;
polylineOptions.add(actionHistory);
}
}
mGoogleMap.addPolyline(polylineOptions.width(2).color(Color.RED));
Log.d("MapActivity", "drawPolyLine_ActionHistory : " + "End");
}
/**
* s|C`揈
* @return
*
*/
public static void drawPolyLine_SearchGroup() {
PolylineOptions options = new PolylineOptions();
options.add(new LatLng(LocationInfo.getLatitude(), LocationInfo.getLongitude()));
options.add(new LatLng(LocationLog.getUserLatitude(),LocationLog.getUserLongitude()));
options.color(Color.RED);
options.width(4);
mGoogleMap.addPolyline(options);
}
/**
* ʒuNX
*/
public static class LocationInfo {
private static double latitude; // ܓx
private static double longitude; // ox
private static LatLng latLng; // ܓxox
private static GeoPoint geoPoint; // GoogleMapW
private static Marker marker; // }[J[
private static String bestProvider; // voC_
public static LocationManager mLocationManager; // LocationManager
private static List<LatLng> actionHistoryList = new ArrayList<LatLng>();
private static Location location;
public static double getLatitude() {
return latitude;
}
public static void setLatitude(float lati) {
latitude = lati;
}
public static double getLongitude() {
return longitude;
}
public static void setLongitude(float longi) {
longitude = longi;
}
public static LatLng getLatLng() {
return latLng;
}
public static void setLatLng() {
LocationInfo.latLng = new LatLng(latitude, longitude);
}
public GeoPoint getGeoPoint() {
return geoPoint;
}
public static void setGeoPoint(GeoPoint geoPoint) {
LocationInfo.geoPoint = geoPoint;
}
public Marker getMarker() {
return marker;
}
public static void setMarker(Marker marker) {
LocationInfo.marker = marker;
}
public String getBestProvider() {
return bestProvider;
}
public void setBestProvider(String bestProvider) {
LocationInfo.bestProvider = bestProvider;
}
public static List<LatLng> getActionHistoryList() {
return actionHistoryList;
}
public static void setActionHistoryList(LatLng actionHistory) {
LocationInfo.actionHistoryList.add(actionHistory);
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
LocationInfo.location = location;
}
}
/**
* RecNX
*
*/
public static class ContentsInfo {
private String code; // ʃXe[^X
private String message; // ʃbZ[W
private String id; // ID
private String contentsID; // RecID
private String contentsName;// Rec
private String contentsAddress;// RecZ
private String contentsTel;// Recdbԍ
private String contentsMail;// Rec[AhX
private String contentsUrl;// RecURL
private String contentsLatitude;// Recܓx
private String contentsLongitude;// Recox
private String contentsType;// Rec^Cv
private HashMap<String, String> contentsMap = new HashMap<String, String>(); // Rec}bv
private List<HashMap<String, String>> contentsList = new ArrayList<HashMap<String, String>>(); // RecXg
private static List<String> contentsDispList = new ArrayList<String>(); // Rec\σXg
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContentsID() {
return contentsID;
}
public void setContentsID(String contentsID) {
this.contentsID = contentsID;
}
public String getContentsName() {
return contentsName;
}
public void setContentsName(String contentsName) {
this.contentsName = contentsName;
}
public String getContentsAddress() {
return contentsAddress;
}
public void setContentsAddress(String contentsAddress) {
this.contentsAddress = contentsAddress;
}
public String getContentsTel() {
return contentsTel;
}
public void setContentsTel(String contentsTel) {
this.contentsTel = contentsTel;
}
public String getContentsMail() {
return contentsMail;
}
public void setContentsMail(String contentsMail) {
this.contentsMail = contentsMail;
}
public String getContentsUrl() {
return contentsUrl;
}
public void setContentsUrl(String contentsUrl) {
this.contentsUrl = contentsUrl;
}
public String getContentsLatitude() {
return contentsLatitude;
}
public void setContentsLatitude(String contentsLatitude) {
this.contentsLatitude = contentsLatitude;
}
public String getContentsLongitude() {
return contentsLongitude;
}
public void setContentsLongitude(String contentsLongitude) {
this.contentsLongitude = contentsLongitude;
}
public String getContentsType() {
return contentsType;
}
public void setContentsType(String contentsType) {
this.contentsType = contentsType;
}
public HashMap<String, String> getContentsMap() {
return contentsMap;
}
public void setContentsMap() {
contentsMap = new HashMap<String, String>();
contentsMap.put(Constant.MapKey.MAP_KEY_CONTENTS_ID.toString(), getContentsID());
contentsMap.put(Constant.MapKey.MAP_KEY_CONTENTS_NAME.toString(), getContentsName());
contentsMap.put(Constant.MapKey.MAP_KEY_CONTENTS_ADDRESS.toString(), getContentsAddress());
contentsMap.put(Constant.MapKey.MAP_KEY_CONTENTS_TEL.toString(), getContentsTel());
contentsMap.put(Constant.MapKey.MAP_KEY_CONTENTS_MAIL.toString(), getContentsMail());
contentsMap.put(Constant.MapKey.MAP_KEY_CONTENTS_URL.toString(), getContentsUrl());
contentsMap.put(Constant.MapKey.MAP_KEY_CONTENTS_LATITUDE.toString(), getContentsLatitude());
contentsMap.put(Constant.MapKey.MAP_KEY_CONTENTS_LONGITUDE.toString(), getContentsLongitude());
contentsMap.put(Constant.MapKey.MAP_KEY_CONTENTS_TYPE.toString(), getContentsType());
this.contentsMap = contentsMap;
}
public List<HashMap<String, String>> getContentsList() {
return contentsList;
}
public void setContentsList() {
contentsList = new ArrayList<HashMap<String, String>>();
this.contentsList.add(getContentsMap());
}
public static List<String> getContentsDispList() {
return contentsDispList;
}
public static void setContentsDispList(String contentsDisp) {
contentsDispList.add(contentsDisp);
}
}
}
|
C#
|
UTF-8
| 5,917 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Threading;
using System.Threading.Tasks;
using C1.DataCollection;
namespace C1DataCollection101
{
public class YouTubeDataCollection : C1CursorDataCollection<YouTubeVideo>
{
private string _q;
public YouTubeDataCollection()
{
PageSize = 20;
}
public int PageSize { get; set; }
public override bool HasMoreItems
{
get { return _q != null && base.HasMoreItems; }
}
private SemaphoreSlim _searchSemaphore = new SemaphoreSlim(1);
public async Task SearchAsync(string q)
{
//Sets the filter string and wait the Delay time.
_q = q;
await Task.Delay(500);
if (_q != q)//If the text changed means there was another keystroke.
return;
try
{
await _searchSemaphore.WaitAsync();
if (_q != q)//If the text changed means there was another keystroke.
return;
await RefreshAsync();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
finally
{
_searchSemaphore.Release();
}
}
protected override async Task<Tuple<string, IReadOnlyList<YouTubeVideo>>> GetPageAsync(int startingIndex, string pageToken, int? count = null, IReadOnlyList<SortDescription> sortDescriptions = null, FilterExpression filterExpresssion = null, CancellationToken cancellationToken = default(CancellationToken))
{
return await LoadVideosAsync(_q, "date", pageToken, PageSize, cancellationToken);
}
public static async Task<Tuple<string, IReadOnlyList<YouTubeVideo>>> LoadVideosAsync(string q, string orderBy, string pageToken, int maxResults, CancellationToken cancellationToken = default(CancellationToken))
{
q = q ?? "";
var youtubeUrl = string.Format("https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&q={0}&order={1}&maxResults={2}{3}&key={4}", Uri.EscapeUriString(q), orderBy, maxResults, string.IsNullOrWhiteSpace(pageToken) ? "" : "&pageToken=" + pageToken, "AIzaSyCtwKIq-Td5FBNOlvOiWEJaClRBDyq-ZsU");
var client = new HttpClient();
var response = await client.GetAsync(youtubeUrl, cancellationToken);
if (response.IsSuccessStatusCode)
{
var videos = new List<YouTubeVideo>();
var serializer = new DataContractJsonSerializer(typeof(YouTubeSearchResult));
var result = serializer.ReadObject(await response.Content.ReadAsStreamAsync()) as YouTubeSearchResult;
foreach (var item in result.Items)
{
var video = new YouTubeVideo()
{
Title = item.Snippet.Title,
Description = item.Snippet.Description,
Thumbnail = item.Snippet.Thumbnails.Default.Url,
Link = "http://www.youtube.com/watch?v=" + item.Id.VideoId,
ChannelTitle = item.Snippet.ChannelTitle,
PublishedAt = DateTime.Parse(item.Snippet.PublishedAt),
};
videos.Add(video);
}
return new Tuple<string, IReadOnlyList<YouTubeVideo>>(result.NextPageToken, videos);
}
else
{
throw new Exception(await response.Content.ReadAsStringAsync());
}
}
}
[DataContract]
public class YouTubeSearchResult
{
[DataMember(Name = "nextPageToken")]
public string NextPageToken { get; set; }
[DataMember(Name = "items")]
public YouTubeSearchItemResult[] Items { get; set; }
}
[DataContract]
public class YouTubeSearchItemResult
{
[DataMember(Name = "id")]
public YouTubeVideoId Id { get; set; }
[DataMember(Name = "snippet")]
public YouTubeSnippet Snippet { get; set; }
}
[DataContract]
public class YouTubeVideoId
{
[DataMember(Name = "videoId")]
public string VideoId { get; set; }
}
[DataContract]
public class YouTubeSnippet
{
[DataMember(Name = "title")]
public string Title { get; set; }
[DataMember(Name = "description")]
public string Description { get; set; }
[DataMember(Name = "thumbnails")]
public YouTubeThumbnails Thumbnails { get; set; }
[DataMember(Name = "channelTitle")]
public string ChannelTitle { get; set; }
[DataMember(Name = "publishedAt")]
public string PublishedAt { get; set; }
}
[DataContract]
public class YouTubeThumbnails
{
[DataMember(Name = "default")]
public YouTubeThumbnail Default { get; set; }
[DataMember(Name = "medium")]
public YouTubeThumbnail Medium { get; set; }
[DataMember(Name = "high")]
public YouTubeThumbnail High { get; set; }
}
[DataContract]
public class YouTubeThumbnail
{
[DataMember(Name = "url")]
public string Url { get; set; }
}
[DataContract]
public class YouTubeVideo
{
public string Title { get; set; }
public string Description { get; set; }
public string Thumbnail { get; set; }
public string Link { get; set; }
public string ChannelTitle { get; set; }
public DateTime PublishedAt { get; set; }
public string PublishedDay
{
get
{
return $"{PublishedAt.Date:D}";
}
}
}
}
|
PHP
|
ISO-8859-1
| 1,893 | 3.171875 | 3 |
[] |
no_license
|
<?php
/**
* @package FormInput
* @class FormInputConfiguration
* @author Jimmy CHARLEBOIS
* @date 25-01-2007
* @brief Classe d'encapsulation des proprits de configuration d'un lment de formulaire
*/
System::import( 'System.Interfaces.FormInput.IFormInputConfiguration' );
System::import( 'System.BaseClass' );
System::import( 'System.StoreObject' );
class FormInputConfiguration extends BaseClass implements IFormInputConfiguration {
private $_items;
public function __construct() {
parent::__construct();
$this->_items = array();
}
public function store() {
$item_data = array();
foreach( $this->_items AS $key => $value )
$item_data[ $key ] = StoreObject::store( $this->_items[ $key ] );
return array(
'items' => $item_data
);
}
public static function restore( $props ) {
$rv =& new FormInputConfiguration();
foreach( $props[ 'items' ] AS $key => $value )
$rv->add( StoreObject::restore( $value ) );
return $rv;
}
/**
* @brief Retourne la configuration du type demand
* @param $config_type string \ref FormConfigType
* @return IFormInputConfiguration|null
*/
public function getConfig( $config_type ) {
$rv = null;
if ( array_key_exists( $config_type, $this->_items ) )
$rv =& $this->_items[ $config_type ];
return $rv;
}
/**
* @brief Ajoute un lment la configuration
* @return void
*/
public function add( IFormInputConfiguration &$config_item ) {
$this->_items[ $config_item->getType() ] = $config_item;
}
/** @brief Implmentation de l'interface IFormInputConfiguration */
/*@{*/
public function getType() {
return FormInputEnumeration::CONFIG_TYPE_HOLDER;
}
/*@}*/
}
?>
|
PHP
|
UTF-8
| 2,094 | 2.75 | 3 |
[] |
no_license
|
<?php
require 'menu.html';
require 'database.php';
session_start();
$id = $_SESSION['id'];
$usuario = $_SESSION['usuario'];
$nombre = $_SESSION['nombre'];
$correo = $_SESSION['correo'];
$telefono = $_SESSION['telefono'];
$password = $_SESSION['password'];
?>
<html>
<head>
<title>Modificar</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="css/estilo.css">
</head>
<body>
<br>
<form action="modificar.php" method="POST" id="formulario">
<h2>Modifica tus datos</h2>
<h3>Nombre Completo</h3>
<input type="text" name="new_nombre" placeholder="⌨ Nombre Completo" value="<?php echo $nombre; ?>" required>
<h3>Correo Electronico</h3>
<input type="email" name="new_correo" placeholder="✉ Correo" value="<?php echo $correo; ?>" required>
<h3>Telefono</h3>
<input type="number" name="new_telefono" placeholder="✆ Telefono" value="<?php echo $telefono; ?>" required>
<h3>Ingrese la contraseña para realizar los cambios</h3>
<input type="password" name="contraseña" placeholder="🔐 Contraseña" required>
<input type="submit" value="Modificar datos">
</form>
<?php
if(isset($_POST['new_nombre'])){
$nombre = $_POST['new_nombre'];
$correo = $_POST['new_correo'];
$telefono = $_POST['new_telefono'];
$contraseña = $_POST['contraseña'];
$contraseña = sha1($contraseña);
if($password == $contraseña){
$sql = "UPDATE usuarios SET nombre='$nombre', correo='$correo', telefono='$telefono'
WHERE id='$id'";
if($conexion->query($sql) === true){
header("location: user.php");
}else{
die("Error al modificar datos: " . $conexion->error);
}
}else{
echo '<script language="javascript">alert("Contraseña incorrecta");</script>';
}
}
?>
</body>
</html>
|
C#
|
UTF-8
| 347 | 2.59375 | 3 |
[
"Apache-2.0"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ObserverPattern.Contracts
{
public interface IWeatherData
{
double Temperature { get; }
double Humidity { get; }
double Pressure { get; }
void ChangeMeasurements(double temperature, double humidity, double pressure);
}
}
|
TypeScript
|
UTF-8
| 219 | 2.65625 | 3 |
[] |
no_license
|
class LogOutCommand{
private token: string;
public constructor(token: string){
this.token = token;
}
public GetToken(): string{
return this.token;
}
}
export default LogOutCommand;
|
JavaScript
|
UTF-8
| 783 | 3.40625 | 3 |
[
"MIT"
] |
permissive
|
const Graph = require('../breadth-first.js')
describe('our graph works?', () => {
it('can add a node to the graph and can give me all the nodes', () => {
let graph = new Graph();
graph.addNode('A');
graph.addNode('B');
graph.addNode('C');
graph.addNode('D');
let nodes = graph.getNodes();
expect(nodes.length).toBe(4);
expect(nodes).toEqual(['A', 'B', 'C', 'D']);
});
it('return a collection of nodes in the order they were visited.', () => {
let graph = new Graph();
graph.addNode('A');
graph.addNode('B');
graph.addNode('C');
graph.addNode('D');
let breadth = graph.breadthFirst();
expect(breadth).toBe(['A', 'B', 'C', 'D'])
})
});
|
Ruby
|
UTF-8
| 11,768 | 2.90625 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
# ----------------------------------------------------------------------------- #
# File: meds.rb
# Description: prints when a medicine will be finishing and sends alert
# Also, allow input and update of meds.
# Author: j kepler
# Date: 2018-02-28 - 23:13
# Last update: 2019-05-27 10:15
# License: MIT License
# ----------------------------------------------------------------------------- #
# CHANGELOG:
# 2018-10-21 - readline suddenly not working, values don't show during "mod" and go as nil
# 2018-12-08 - write to log file so I know when last I bought something. sometimes I am
# out of medicine but the software shows I have it.
# This does not give an exact idea of how much I bought, just the stock on that day
# which could be a correction.
# 2019-01-12 - Put mod in a loop since i modify several at a shot
# 2019-02-13 - Display only med name in mod menu, and use smenu in place of fzf
# since we get a matrix like menu
# ----------------------------------------------------------------------------- #
# TODO:
#
# ----------------------------------------------------------------------------- #
require 'pp'
require 'readline'
require 'date'
require 'color' # see ~/work/projects/common/color.rb
# print color("Hello there black reverse on yellow\n", "black", "on_yellow", "reverse")
# --- some common stuff --- # {{{
# Taken from imdb/seen.rb
# readline version of gets
def input(prompt="", newline=false)
prompt += "\n" if newline
Readline.readline(prompt, true).squeeze(" ").strip
end
# edit a variable and return value as in zsh vared.
# newstock = vared(newstock, "Enter current stock: ")
## 2019-01-02 - this has stopped working. we should revert to OLD_vared (see seen.rb)
def vared var, prompt=">"
Readline.pre_input_hook = -> do
Readline.insert_text var
Readline.redisplay
# Remove the hook right away.
Readline.pre_input_hook = nil
end
begin
str = Readline.readline(prompt, false)
rescue Exception => e
return nil
end
str
end
# # taken from sed.rb in bugzy
# read the given filename into an array
def _read filename
d = []
File.open(filename).each { |line|
# remove blank lines. NOTE this may not be needed in other programs
next if line.chomp == ""
d << line
}
return d
end
# write the given array to the filename
def _write filename, array
File.open(filename, "w") do |file|
array.each { |row| file.puts row }
end
end
#
# --- end common stuff # }}}
# include? exist? each_pair split gsub join empty?
# this reads the file in a loop.
# It should not print, just put the data into a data structure
# so it can be called for either complete printing, or sending an alert via crontab
# etc.
def read_file_in_loop filename # {{{
sep = '~'
ctr = 0
file_a = []
File.open(filename).each { |line|
line = line.chomp
next if line =~ /^$/
# 2019-02-08 - maybe we can comment off a med that is paused or discontinued
next if line =~ /^#/
ctr += 1
next if ctr <= 1
cols = line.split(sep)
name = cols[0]
daily = cols[1].to_f
stock = cols[2].to_i
as_on = cols[3]
as_on_jd = Date.parse(cols[3]).jd
# 2019-02-08 - if we are not taking a medicine, i have made the stock zero
next if daily == 0
finish_on_jd = as_on_jd + (stock / daily)
finish_on = Date.jd(finish_on_jd)
balance = (stock/daily) - (Date.today.jd - as_on_jd)
balance = balance.to_i
# left is how many tablets are left
left = (balance*daily).to_i
file_a << [ name, daily, stock, as_on, finish_on, balance, left ]
}
return file_a
end # }}}
def print_all file_a # {{{
# sort by left (how many days left)
file_a.sort_by! { |s| s[5] }
format='%-25s %5s %5s %-12s %-12s %10s %6s'
puts color(format % [ "Medicine", "daily", "stock", "as_on" , "finish_on" , "days_left", "left"], "yellow", "on_black", "bold")
file_a.each_with_index {|cols, ix|
name = cols[0]
daily = cols[1]
stock = cols[2]
as_on = cols[3]
finish_on = cols[4]
balance = cols[5]
left = cols[6]
bg = "on_black"
fg = "white"
att = "normal"
code, fgcolor, bgcolor, attrib = case balance
when 0..5
["B", "red", bg, "bold"]
when 6..12
["C", "white", bg, att]
when 13..1000
["C", "green", bg, att]
when -1000..-1
["A", fg, bg, "reverse"]
else
["?", "yellow", "on_red", att]
end
puts color(format % [ name, daily, stock, as_on , finish_on , balance, left], fgcolor, bgcolor, attrib)
}
end # }}}
def change_line filename, argv=[] # {{{
# argv can have name of med or pattern and balance for today
while true
## argv is being repeated. that is an issue
num, line = select_row filename, argv
return unless num
puts line.join("\t")
stock = line[2]
# if user passed a number then ask if stock to be replaced, else prompt
if argv.count == 2
newstock = argv[1]
else
newstock = stock
end
savedval = newstock
puts "stock was #{line[2]} as on #{line[3]}. You passed #{newstock}"
newstock = vared(newstock, "Enter current stock: ")
newstock = savedval if newstock.nil? or newstock == "" ## 2018-10-21 - readline not working
puts "Got :#{newstock}:" if $opt_debug
puts "Got nil :#{newstock}:" if newstock.nil? or newstock == ""
raise ArgumentError, "Newstock nil" unless newstock
# allow user to edit date, default to today
newdate = Date.today.to_s
savedval = newdate
newdate = vared(newdate, "Enter as on date #{savedval}: ")
newdate = savedval if newdate.nil? or newdate == "" ## 2018-10-21 - readline not working
print "How much did you buy: "
bought = $stdin.gets
if bought
bought = bought.chomp.to_i
else
bought = 0
end
puts "Got :#{newdate}:" if $opt_debug
puts "line is #{num}" if $opt_debug
puts "Bought is #{bought}" if $opt_debug
raise ArgumentError, "Newdate nil" unless newdate
newline = line.dup
newline[2] = newstock
newline[3] = newdate
replace_line filename, num, newline
log_line newline, bought
puts
print ">> Modify another item? y/n: "
yesno = $stdin.gets.chomp
if yesno != "y"
break
end
end # while
end # }}}
def replace_line filename, lineno, newline # {{{
sep = "~"
arr = _read filename
num = lineno.to_i - 1
arr[num] = newline.join(sep)
_write(filename, arr)
end # }}}
## log the line to a file with date so we know when we entered what
## @param newline array of medicine name, stock, date
def log_line newline, bought
sep = "~"
newline << bought
str = newline.join(sep)
File.open($logfile, 'a') {|f| f.puts(str) } # or f.puts or f << str
end
# prompt user with rows for selection
# return selected row in an array
def select_row filename, argv=[] # {{{
myarg = argv.first
sep = "~"
## display med names to user, this displays entire line with a number
#str=%x{ nl #{filename} | fzf --query="#{myarg}" -1 -0}
# prompt user with medicine names. Some meds have spaces in it, so -W tells smenu not to separate on that.
# Reject header row with tail, and reject commented out meds
str = %x{ cut -f1 -d~ #{filename} | grep -v "^#" | tail -n +2 | sort | smenu -t -W$'\n' }
return nil,nil if str.nil? or str.chomp.size == 0
# 2019-02-13 - now we only display medicine name,so get the rest of the row
str = %x{ grep -n "#{str}" #{filename} }
#tmp = str.chomp.split("\t")
#puts str
tmp = str.chomp.split(":")
#puts tmp[0]
#puts tmp[1]
# returns lineno, and array containing rest
return tmp[0], tmp[1].split(sep)
end # }}}
# adds a new medicine to the file.
# TODO should check if already present
def add_line filename, argv=[] # {{{
name, dosage, stock, newdate = argv
unless name
print "Enter name of medicine: "
name = gets.chomp
end
unless dosage
dosage = vared("1", "Enter dosage: ")
end
stock = vared("0", "Enter stock: ") unless stock
unless newdate
newdate = Date.today.to_s
newdate = vared(newdate, "Enter as on date: ")
end
str = "#{name}~#{dosage}~#{stock}~#{newdate}"
puts str if $opt_debug
append_to_file filename, str
end # }}}
def append_to_file filename, line # {{{
open(filename, 'a') do |f|
f.puts line
end
end # }}}
def alert_me filename, args=[] # {{{
file_a = read_file_in_loop filename
arr = []
# sort by balance
file_a.sort_by! { |s| s[5] }
file_a.each_with_index do |cols, _ix|
name, daily, stock, as_on, finish_on, balance, left = cols
if balance < 12
#arr << "#{name} will finish on #{finish_on}. #{balance} days left."
arr << "%-28s will finish on #{finish_on}. #{balance} days left." % [name, finish_on, balance]
end
end
return if arr.empty?
# send contents of arr as a message using mail.sh.
str = arr.join("\n")
email_id = ENV['MAIL_ID']
puts email_id if $opt_debug
if $opt_cron
#out = %x{ echo "#{str}" | ~/bin/mail.sh -s "Medicine alert!" #{email_id} 2>&1}
out = %x{ echo "#{str}" | /Users/rahul/bin/mail.sh -s "Medicine alert" #{email_id} }
# checking this 2018-03-25 - since cron is not sending it at all.
#puts str
#puts "#{out}"
else
puts str
puts "#{out}"
end
# install as crontab
end # }}}
def find_line array, patt # {{{
array.each_with_index {|e, ix|
name = e.first
if name =~ /name/
return e
end
}
return nil
end # }}}
if __FILE__ == $0
include Color
filename = nil
$opt_verbose = false
$opt_debug = false
$opt_quiet = false
$opt_cron = false
begin
# http://www.ruby-doc.org/stdlib/libdoc/optparse/rdoc/classes/OptionParser.html
require 'optparse'
## TODO filename should come in from -f option
filename = File.expand_path("~/work/projects/meds/meds.txt");
$logfile = File.expand_path("~/work/projects/meds/meds.log");
options = {}
subtext = <<HELP
Commonly used command are:
mod : update stocks. mod dilzem 45
low : report on medicines running low (less than 10 days stock)
add : add a new medicine. e.g., add aspirin 1 25
HELP
OptionParser.new do |opts|
opts.banner = "Usage: #{$0} [options]"
opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
options[:verbose] = v
$opt_verbose = v
end
opts.on("--crontab", "Send email, don't display on stdout") do |v|
$opt_cron = v
end
opts.on("--debug", "Show debug info") do
options[:debug] = true
$opt_debug = true
end
opts.on("-q", "--quiet", "Run quietly") do |v|
$opt_quiet = true
end
opts.separator ""
opts.separator subtext
end.parse!
p options if $opt_debug
p ARGV if $opt_debug
# --- if processing just one file ---------
unless File.exist? filename
$stderr.puts "File: #{filename} does not exist. Aborting"
exit 1
end
if ARGV.count == 0
file_a = read_file_in_loop filename
print_all file_a
exit 0
end
command = ARGV.shift
case command
when "add","a"
add_line filename, ARGV
when "mod","m"
change_line filename, ARGV
when "low","l"
alert_me filename, ARGV
else
puts "don't know how to handle #{command}!"
exit 1
end
ensure
end
end
|
Java
|
UTF-8
| 2,329 | 3.171875 | 3 |
[] |
no_license
|
/**
* Initially created by Roman Gaev
* 26.02.2018
* Protocol for communication
* <p>
* May the force be with you.
*/
public class Protocol {
NewServerThread thread;
private static final int AUTH = 0;
private static final int PROFILE = 1;
private int state = AUTH;
public Protocol(NewServerThread thread) {
this.thread = thread;
}
public String processInput(String input) {
int command = Integer.parseInt(input);
String generatedOutput;
if (state == AUTH) {
switch (command) {
case 0:
if (thread.signIn()) {
generatedOutput = "Successfully logged in!. 0 for your private user information (I mean no private naked photos). 1 to log out to main menu";
state = PROFILE;
} else
generatedOutput = "Couldn't log in! Something is wrong either with your login or your password or your hands...";
break;
case 1:
generatedOutput = "Sorry! This function is unavailable so far! I need to stop drinking Guinness so much and code more...";
break;
case 2:
generatedOutput = "Did you really think you deserve a surprise? Oh, come on. I would never spend my time on you.";
break;
default:
generatedOutput = "See you in a bit!";
break;
}
} else if (state == PROFILE) {
switch (command) {
case 0:
generatedOutput = thread.getCurrentUser().toString() + ". 0 for your private user information (I mean no private naked photos). 1 to log out to main menu";
break;
default:
thread.setCurrentUser(null);
generatedOutput = "Greetings, motherfucker! Welcome to server! 0 to sign in. 1 to sign up. 2 to get a surprise. 3 to quit the program:";
state = AUTH;
break;
}
} else {
generatedOutput = "Bye.";
state = AUTH;
}
return generatedOutput;
}
}
|
Markdown
|
UTF-8
| 3,071 | 2.8125 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Contributing to python-sparkpost
Transparency is one of our core values, and we encourage developers to contribute and become part of the SparkPost developer community.
The following is a set of guidelines for contributing to python-sparkpost,
which is hosted in the [SparkPost Organization](https://github.com/sparkpost) on GitHub.
These are just guidelines, not rules, use your best judgment and feel free to
propose changes to this document in a pull request.
## Submitting Issues
* You can create an issue [here](https://github.com/sparkpost/python-sparkpost/issues/new), but
before doing that please read the notes below on debugging and submitting issues,
and include as many details as possible with your report.
* Include the version of python-sparkpost you are using.
* Perform a [cursory search](https://github.com/SparkPost/python-sparkpost/issues?q=is%3Aissue+is%3Aopen)
to see if a similar issue has already been submitted.
## Local development
* Fork this repository
* Clone your fork
* Install virtualenv: ``pip install virtualenv``
* Run ``make install``
* Run ``source venv/bin/activate``
* Write code!
## Contribution Steps
### Guidelines
- Provide documentation for any newly added code.
- Provide tests for any newly added code.
- Follow PEP8.
1. Create a new branch named after the issue you’ll be fixing (include the issue number as the branch name, example: Issue in GH is #8 then the branch name should be ISSUE-8))
2. Write corresponding tests and code (only what is needed to satisfy the issue and tests please)
* Include your tests in the 'test' directory in an appropriate test file
* Write code to satisfy the tests
3. Ensure automated tests pass
4. Submit a new Pull Request applying your feature/fix branch to the develop branch
## Testing
Once you are set up for local development:
* Run ``make test`` to test against your current Python environment
* Open htmlcov/index.html to view coverage information
### Testing all version combinations
You can also test all the supported Python and dependencies versions with tox:
1. Install tox: ``pip install tox``
2. Run tox: ``tox``
If you do not have Python 2.7, 3.4, and 3.5, you can install them with pyenv:
1. Install [pyenv](https://github.com/yyuu/pyenv)
2. Install the required versions of Python:
1. ``pyenv install 2.7.11``
2. ``pyenv install 3.4.4``
3. ``pyenv install 3.5.1``
3. Set the global versions: ``pyenv global 2.7.11 3.4.4 3.5.1``
4. Run tox: ``tox``
## Releasing
### Increment the library version number
* Update version number in setup.py
* Update version number in sparkpost/__init__.py
* Update CHANGELOG.md to reflect the changes
### To put python-sparkpost on PyPI
* Ensure you have maintainer privileges in PyPI
* Update your ``~/.pypirc`` if necessary to contain your username and password (hint: you can run ``python setup.py register``)
* Run ``make release``, which will create the dists and upload them to PyPI
* Confirm you are able to successfully install the new version by running ``pip install sparkpost``
|
JavaScript
|
UTF-8
| 940 | 2.734375 | 3 |
[] |
no_license
|
var games = ['Gears of War', 'Bloodbourne', 'Dark Souls', 'Total War: Warhammer', 'Battlefield 4', 'Crysis 2: Maximum Edition', 'Killing Floor',
'Halo', 'Splinter Cell', 'Metal Gear Solid'];
function showGameDetails() {
var game = $(this).attr('data-name');
var queryURL = "http://api.giphy.com/v1/gifs/search?q=" + game + "&api_key=dc6zaTOxFJmzC";
$.ajax({url: queryURL, method: 'GET'})
.done(function(response) {
console.log(response);
var gamesDiv = $('<div class = "gamesDiv">');
});
}
function generateButtons() {
$('#gameButtons').empty();
for (var i = 0; i < games.length; i++) {
var meta = $('<button>');
meta.addClass('games');
meta.attr('data-name', games[i]);
meta.text(games[i]);
$('#gameButtons').append(meta);
}
}
$('#addGames').click(function() {
var videoGames = $('#gamesInput').val().trim();
games.push(videoGames);
generateButtons();
return false;
})
generateButtons();
|
JavaScript
|
UTF-8
| 2,345 | 3.09375 | 3 |
[] |
no_license
|
// make http request
const request = require('request');
const urlAddress = require('./questAPI');
var geocodeAddress = (address, callback) => {
console.log(address);
let encodeA = encodeURIComponent(address)
// encodeURIComponenet('1301 lombard street') turns it into URL readable
console.log(encodeA);
// get the api key from another file
questUrl = urlAddress.urlAddressFunction(encodeA);
// url with geocode location
// json: true = data coming back is json data, convert to object
request({
// using a template string for URL
url: `${questUrl.encoded}`,
json: true
}, (error, response, body) => {
// 1st object, 2nd filter properties, 3rd arg format the json with # of space indentation
//console.log(JSON.stringify(response, undefined, 4));
//console.log(body)
if (error){
// send a callback errorMessage to app.js
callback('Unable to connect to the google servers.');
//console.log('Unable to connect to the google servers.');
}
else if (body.status > 0){
// send a callback errorMessage to app.js
callback('Unable to find address.');
//console.log('Unable to find address.');
}
else if (body.info.statuscode === 0){
// send undefined for errorMessage, send back results to app.js
callback(undefined, {
// setting up my own objects with their properties
address: body.results[0].providedLocation.location,
latitude: body.results[0].locations[0].latLng.lat,
longitude: body.results[0].locations[0].latLng.lng
})
// This was a simple way of sending back console.log with results before adding the code from above
// console.log(`Address: ${body.results[0].providedLocation.location}`);
// console.log(`Lat: ${body.results[0].locations[0].latLng.lat}`);
// console.log(`Lng: ${body.results[0].locations[0].latLng.lng}`)
}
else{
console.log('Something went completely wrong please check address or you have internet coonection');
}
});
};
// lets us pass the geocodeAddress function to app.js
module.exports.geocodeAddress = geocodeAddress
|
C++
|
UTF-8
| 1,197 | 3.65625 | 4 |
[] |
no_license
|
#include <iostream>
#include "token.h"
/* value stack priority:
* = - 1
* | - 2
* & - 3
* operand - -1
*/
Token::Token(std::string s) {
name = s;
char c = s[0];
switch (c) {
case '=': {
stack_priority = 1;
token_type = kTokenAssign;
break;
}
case '|': {
stack_priority = 2;
token_type = kTokenOr;
break;
}
case '&': {
stack_priority = 3;
token_type = kTokenAnd;
break;
}
default: {
stack_priority = -1;
token_type = kTokenConst;
}
}
}
TokenType Token::type() const {
return token_type;
}
int Token::priority() const {
return stack_priority;
}
std::string Token::get_name() const {
return name;
}
bool Token::operator<(const Token &other) const {
return name < other.name;
}
std::ostream &operator<<(std::ostream &out, const Token &source) {
out << source.name;
return out;
}
std::istream &operator>>(std::istream &in, Token *destination) {
std::string buf;
in >> buf;
destination = new Token(buf);
return in;
}
|
PHP
|
UTF-8
| 2,727 | 2.5625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
<?php
/**
* Created by PhpStorm.
* User: denisov
* Date: 27.09.2017
* Time: 10:51
*/
namespace frontend\widgets;
use common\models\Category;
use common\models\Subcategory;
use yii\base\Widget;
use Yii;
class LeftMenu extends Widget
{
public $categories;
public $lang;
public $selected_subcategories;
public function init() {
$this->categories = Category::find()->where(['active' => 1])->all();
$this->lang = \Yii::$app->language;
$subcategories_filter = Yii::$app->request->get('subcategories-filter');
$this->selected_subcategories = $subcategories_filter ? explode(';', $subcategories_filter) : [];
parent::init();
}
public function run()
{
ob_start(); ?>
<div class="head">
<span>☰</span> КАТЕГОРИИ
</div>
<div class="accarBodyblock">
<?php foreach($this->categories as $category) {
/* @var Category $category */
$subcategories = Subcategory::find()->where(['active' => 1 , 'category_id'=>$category->id ])->all();
// Проверим, выбрана ли хоть одна подкатегория
$display_container = false;
foreach($subcategories as $subcategory) {
/* @var Subcategory $subcategory */
if (in_array($subcategory->id, $this->selected_subcategories)) $display_container = true;
}
$container_style = $display_container ? " style='display:block' " : "";
?>
<article class="accar body-inner">
<h3><?= $category->{"name_$this->lang"}?></h3>
<div class="container" <?=$container_style?>>
<div class="control-group">
<?php foreach($subcategories as $subcategory) {
/* @var Subcategory $subcategory */
$id = $subcategory->id;
$selected = in_array($id, $this->selected_subcategories) ? " checked='checked' ": "";
?>
<label class="control control--checkbox">
<input type="checkbox" name="subcategory[]" value="<?=$id?>" <?=$selected?>/>
<span class="control__indicator"></span>
<span class="category-text"><?=$subcategory->{"name_$this->lang"}?></span>
</label>
<?php } ?>
</div>
</div>
</article>
<?php } ?>
</div>
<?php
return ob_get_clean();;
}
}
|
Ruby
|
UTF-8
| 264 | 3.015625 | 3 |
[] |
no_license
|
# builds sentence based on the specific cycle of the recursive function
def build(cycle, level, root, path, str)
if cycle == 1 && level > 1
str = root + ' ' + path + ' '
elsif path == root
str = root + ' '
else
str += path + ' '
end
str
end
|
Java
|
UTF-8
| 2,698 | 2.53125 | 3 |
[] |
no_license
|
package com.example.pc002.labactivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class LabActivity extends AppCompatActivity implements View.OnClickListener {
private View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(LabActivity.this, "Variable Listener", Toast.LENGTH_LONG).show();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lab);
Button ordinaryButton = findViewById(R.id.ordinary_button);
ImageButton imageButton =findViewById(R.id.image_button);
Button buttonWithIconAtLeft = findViewById(R.id.button_with_icon_at_left);
Button buttonWithIconAtRight = findViewById(R.id.button_with_icon_at_right);
// ordinaryButton.setOnClickListener(new View.OnClickListener(){
// @Override
// public void onClick(View view) {
// Toast.makeText(LabActivity.this, "Ordinary button is clicked", Toast.LENGTH_SHORT).show();
//
// }
//
// @Override
// protected Object clone() throws CloneNotSupportedException {
// return super.clone();
// }
// });
//
// imageButton.setOnClickListener(clickListener);
// buttonWithIconAtLeft.setOnClickListener(clickListener);
// buttonWithIconAtRight.setOnClickListener(this);
ordinaryButton.setOnClickListener(this);
imageButton.setOnClickListener(this);
buttonWithIconAtLeft.setOnClickListener(this);
buttonWithIconAtRight.setOnClickListener(this);
}
@Override
public void onClick(View view) {
//Toast.makeText(this, "Activity Listener", Toast.LENGTH_LONG).show();
int id = view.getId();
switch (id){
case R.id.ordinary_button:
Toast.makeText(this,"Ordinary button is clicked", Toast.LENGTH_LONG).show();
break;
case R.id.image_button:
Toast.makeText(this,"Image button is clicked", Toast.LENGTH_LONG).show();
break;
case R.id.button_with_icon_at_left:
Toast.makeText(this,"Icon Left button is clicked", Toast.LENGTH_LONG).show();
break;
case R.id.button_with_icon_at_right:
Toast.makeText(this,"Icon right button is clicked", Toast.LENGTH_LONG).show();
break;
}
}
}
|
Markdown
|
UTF-8
| 4,303 | 2.625 | 3 |
[] |
no_license
|
# Banking System
## Description
This is an Windows Desktop Application which is intended to be used for internal working of banks and all bank related transaction.
This approach replaces the traditional way of paper record keeping to an modern and efficient computerised approach to manage and handle the data of the customers.
### Note
The repository does not contain the Source Code and the Database file. If anybody wants the file mail me at: shivamsom3@gmail.com
```
It's recommended to use the latest and legitimate version of Windows and .NetFramework available. So,that application runs without any issues.
Also, make sure the MYSQL SERVER is running on your pc.(Refer:https://dev.mysql.com/doc/refman/5.7/en/windows-start-command-line.html)
```
The repository does not contain the Source Code and the Database file. If anybody wants the file(s) mail me at: shivamsom3@gmail.com
### Running the Application
* Click on **Bank.exe**. Right Click **Run as Admin**.

* If propmpt select **Yes**.


*Click on OK.

*Select Account Manager/Staff

## Home Page

## Employee Addition

## Assign Employee Login Details

## Search Employee

## Employee Details

## Remove an Existing Employee

## Savings Bank Opening



## Activity Log



## Change Password

## Home Loan Opening

## Cash deposit

## Withdraw Cash

## Deposit Simulator

## Loan Simulator

## Calculator

# Queries ????
**E mail :** *shivamsom3@gmail.com*
**LinkedIN:** *https://www.linkedin.com/in/shivam-som*
|
SQL
|
UTF-8
| 221 | 3.859375 | 4 |
[] |
no_license
|
-- Return the name of the gallery with the most images.
SELECT galleries.name, COUNT(*) as count
FROM galleries JOIN images
ON galleries.id = images.gallery_id
GROUP BY galleries.id
ORDER BY count DESC
LIMIT 1;
|
Java
|
UTF-8
| 2,847 | 2.125 | 2 |
[] |
no_license
|
package com.appabilities.complainmanagementsystem.base;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import com.appabilities.complainmanagementsystem.utils.CommonActions;
import com.appabilities.complainmanagementsystem.utils.NetworkUtils;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.Observable;
import androidx.annotation.CallSuper;
import androidx.fragment.app.Fragment;
public abstract class BaseFragment extends Fragment implements IConectivityObserver {
public BaseActivity mActivity;
public CommonActions ca;
public boolean isNetworkAvailable;
public ProgressDialog progressDialog;
SharedPreferences mSharedPreferences;
@CallSuper
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = (BaseActivity) this.getActivity();
ca = new CommonActions(mActivity);
updateNetworkStatus();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setCancelable(false);
}
public boolean onFragmentBackPressed() {
return false;
}
public void updateNetworkStatus() {
isNetworkAvailable = NetworkUtils.checkConnection(mActivity);
}
@Override
public void onPause() {
super.onPause();
NetworkChangeReceiver.getObservable().deleteObserver(this);
}
@Override
public void onResume() {
super.onResume();
NetworkChangeReceiver.getObservable().addObserver(this);
updateNetworkStatus();
}
@Override
public void update(Observable observable, Object data) {
updateNetworkStatus();
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public String priceFormat(String price) {
double amount = Double.parseDouble(price);
DecimalFormat formatter = new DecimalFormat("#,###.00");
return formatter.format(amount);
}
protected String currentLanguage() {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
return mSharedPreferences.getString("user_preferred_language", "en");
}
}
|
PHP
|
UTF-8
| 2,104 | 2.828125 | 3 |
[] |
no_license
|
<?php
namespace App\Models\DAO;
use App\Models\Entidades\Cliente;
class ClienteDAO extends BaseDAO
{
public function listar($cpf = null)
{
if ($cpf) {
$resultado = $this->select(
"SELECT * FROM cliente WHERE cpf = $cpf"
);
return $resultado->fetchObject(Cliente::class);
} else {
$resultado = $this->select(
'SELECT * FROM cliente ORDER BY nome ASC'
);
return $resultado->fetchAll(\PDO::FETCH_CLASS, Cliente::class);
}
return false;
}
public function listarLogin($login)
{
if ($login) {
$resultado = $this->select("select * from cliente where login = '{$login}'");
return $resultado->rowCount();
}
return false;
}
public function validarLogin(Cliente $cliente)
{
$login = $cliente->getLogin();
$senha = $cliente->getSenha();
$resultado = $this->select("select cpf, nome from cliente where login = '{$login}' and senha = '{$senha}'");
if (!empty($resultado)) {
return $resultado->fetchObject(Cliente::class);
} else {
return false;
}
}
public function salvar(Cliente $cliente)
{
try {
$cpf = $cliente->getCpf();
$nome = $cliente->getNome();
$email = $cliente->getEmail();
$telefone = $cliente->getTelefone();
$login = $cliente->getLogin();
$senha = $cliente->getSenha();
return $this->insert(
'cliente',
":cpf, :nome, :email, :telefone, :login, :senha",
[
':cpf' => $cpf,
':nome' => $nome,
':email' => $email,
':telefone' => $telefone,
':login' => $login,
':senha' => $senha,
]
);
} catch (\Exception $e) {
throw new \Exception("Erro na gravação de dados.", 500);
}
}
}
|
Swift
|
UTF-8
| 1,324 | 2.796875 | 3 |
[] |
no_license
|
//
// NetworkingService.swift
// EyesTest
//
// Created by Reiss Zurbyk on 2019-07-20.
// Copyright © 2019 Reiss Zurbyk. All rights reserved.
//
import Foundation
class NetworkingService {
static let shared = NetworkingService()
private init() {}
let session = URLSession.shared
lazy var dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
return dateFormatter
}()
func getUsers(success successBlock: @escaping (Root) -> Void) {
guard let url = URL(string: "https://eyes-technical-test.herokuapp.com/users") else { return }
let request = URLRequest(url: url)
session.dataTask(with: request) { [weak self] data, _, error in
guard let `self` = self else { return }
if let error = error { print(error); return }
do {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(self.dateFormatter)
let result = try decoder.decode(Root.self, from: data!)
successBlock(result)
} catch {
print(error)
}
}.resume()
}
}
|
JavaScript
|
UTF-8
| 522 | 3.109375 | 3 |
[] |
no_license
|
const addBrush = name =>
document.getElementById(name).onclick = () =>
brush.mode = name
const brush = {
size: 5,
color: '#007700',
x: 1e5,
y: 1e5,
mode: 'fill'
}
for (m of ['oval', 'line', 'pencil', 'fill', 'getColor','soval','rect','srect']) addBrush(m)
const colorPicker = document.getElementById('color')
colorPicker.onchange = function(){ brush.color = '#' + this.jscolor }
document.getElementById('size').onmousemove = function(){ brush.size = +(this.value) }
|
Java
|
UTF-8
| 1,703 | 2.109375 | 2 |
[] |
no_license
|
package se.jensim.chargen.view;
import com.vaadin.cdi.CDIView;
import com.vaadin.cdi.access.JaasAccessControl;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.ui.Button;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import javax.servlet.ServletException;
import se.jensim.chargen.gui.menu.ChargenMenu;
import se.jensim.chargen.prop.ConstRoles;
import se.jensim.chargen.prop.ConstViews;
import se.jensim.chargen.ui.GameUi;
/**
*
* @author jens
*/
@CDIView(uis = GameUi.class, value = ConstViews.LOGOUT)
@RolesAllowed({ConstRoles.USER, ConstRoles.MODERATOR, ConstRoles.ADMIN, ConstRoles.OWNER})
public class ViewLogout extends VerticalLayout
implements View, Button.ClickListener {
@Inject
private ChargenMenu menu;
private final Label lblContent = new Label("Are you sure?", ContentMode.HTML);
private final Button btnLogout = new Button("LOGOUT", this);
private ViewLogout() {
}
@PostConstruct
private void init() {
addComponent(menu);
addComponent(lblContent);
addComponent(btnLogout);
}
@Override
public void enter(ViewChangeListener.ViewChangeEvent event) {
}
@Override
public void buttonClick(Button.ClickEvent event) {
if (event.getButton() == btnLogout) {
try {
JaasAccessControl.logout();
} catch (ServletException ex) {
Logger.getLogger(ViewLogout.class.getName()).log(Level.SEVERE, null, ex);
}
getUI().getPage().setLocation("..");
}
}
}
|
C#
|
UTF-8
| 607 | 2.578125 | 3 |
[] |
no_license
|
using System;
namespace Clock
{
class Program
{
static void Main(string[] args)
{
ReverseWatch reverseWatch = new ReverseWatch();
RWSubscriber subscriber = new RWSubscriber();
subscriber.Subscribe(reverseWatch);
Console.WriteLine("Enter time: ");
int seconds = int.Parse(Console.ReadLine());
Console.WriteLine("Enter message: ");
string message = Console.ReadLine();
reverseWatch.StartCoundown(seconds, message);
Console.ReadLine();
}
}
}
|
Ruby
|
UTF-8
| 1,930 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
require 'rspec'
require 'car_store'
require 'car_options'
describe Vehicle do
before do
Vehicle.clear
end
it 'initializes a Vehicle class with its properties' do
test_vehicle = Vehicle.new("Toyota","Prius","2014","23999")
test_vehicle.should be_an_instance_of Vehicle
end
it 'will provide properties when they are called directly' do
test_vehicle = Vehicle.new("Toyota","Prius","2014","23999")
test_vehicle.make.should eq ("Toyota")
end
it 'initializes a warehouse class variable and make the vehicle object properties accessible' do
test_vehicle = Vehicle.new("Toyota","Prius","2014","23999")
Vehicle.warehouse[0].should be_an_instance_of Vehicle
end
end
describe Options do
before do
Options.clear
end
it 'initializes a Options class with its properties' do
test_options = Options.new("Rims", 1000)
test_options.should be_an_instance_of Options
end
it 'will provide properties when they are called directly' do
test_options = Options.new("Rims", 1000)
test_options.name.should eq ("Rims")
end
it 'initializes a catalog class variable and make the Options object properties accessible' do
test_options = Options.new("Rims", 1000)
Options.catalog[0].should be_an_instance_of Options
end
it 'finds the option in the catalog that is selected and returns that option' do
test_options = Options.new("Rims", 1000)
Options.find_by_name("Rims").should eq test_options
end
it 'finds the option in the catalog that is selected and returns nil when no match is found' do
test_options = Options.new("Rims", 1000)
Options.find_by_name("Mims").should eq (false)
end
it 'removes any option that has alredy been selected from list' do
test_options = Options.new("Rims", 1000)
another_option = Options.new("Spoiler", 500)
Options.delete(test_options)
Options.catalog.should eq [another_option]
end
end
|
Markdown
|
UTF-8
| 5,635 | 3.03125 | 3 |
[] |
no_license
|
---
layout: post
title: "Disposing"
date: 2019-07-14 09:45:19 +0900
categories: RxSwift
tags: Rx RxSwift 번역 Disposing
author: Juhee Kim
mathjax: true
---
* content
{:toc}
## Dispose?
구독 후 Observable Sequence 항목 생성을 취소하고 resource를 반환하려면, `dispose`를 호출하세요.
Sequence가 유한 시간 내에 종료되면, dispose를 호출하지 않거나 disposeBag으로 disposed를 사용하지 않아도 resource leak이 발생하지 않습니다. 하지만 이 resource들은 요소의 생성이 완료되거나 오류를 반환하여 시퀀스가 완료될 때까지 사용됩니다.
만약 Sequence가 스스로 종료되지 않는다면 `disposeBag`, `takeUntil` 연산자를 사용하거나 다른 방식으로 `dispose`가 수동으로 호출되지 않는 한 **리소스가 영구적으로 할당됩니다.**
**dispose bag이나 `takeUntil` 연산자를 사용하면 자원을 정리할 수 있습니다. Sequence가 유한시간 안에 종료되더라도 사용하는 게 좋습니다.**
#### 왜 Swift.Error가 Generic이 아닌가요? (갑자기?) [원본](https://github.com/ReactiveX/RxSwift/blob/master/Documentation/DesignRationale.md#why-error-type-isnt-generic)
```swift
enum Event<Element> {
case next(Element) // next element of a sequence
case error(Error) // sequence failed with error
case completed // sequence terminated successfully
}
```
만약 error가 generic type이라면 어떨까요?
`Observable<String, E1>` and `Observable<String, E2>`가 있다면, 각각의 Observable이 만들어내는 에러 타입이 무엇인지 알아내야 합니다. 이는 composition 속성을 해치며, Rx는 왜 Sequence가 실패했는지에는 관심이 없으며(ㅋㅋ), 실패한 결과를 observable chain 하위로 전달하게 됩니다.
어음 느낌적인 느낌으로 굳이 Generic 타입의 Error를 사용할 필요가 없다-는 건 알겠는데, (이미 Swift에서 정의한 Error protocol을 사용하는 것으로 충분하기 때문에) 글의 의미를 이해를 못하겠음.
## Disposing
observable sequence를 종료시키는 방법입니다. `dispose`를 구독에 호출하면 기존에 할당된 모든 항목과 앞으로의 항목들에 대한 resource가 모두 해제되며 sequence가 종료됩니다.
`interval` 연산자와 관련된 예가 있습니다. 300 milliseconds마다 항목이 발생되며, 2초간 이 쓰레드를 유지해봅시다.
```swift
let scheduler = SerialDispatchQueueScheduler(qos: .default)
let subscription = Observable<Int>.interval(.milliseconds(300), scheduler: scheduler)
.subscribe { event in
print(event)
}
Thread.sleep(forTimeInterval: 2.0)
subscription.dispose()
```
> SerialDispatchQueueScheduler를 사용하여 현제 쓰레드와 별도의 쓰레드를 사용하는 Observable을 만들었습니다.
> 그렇기 때문에 현재 쓰레드가 종료되어 버리면 Observable Sequece의 쓰레드가 아무리 항목을 만들어도 받을 수 없습니다.(구독중인 쓰레드가 종료되었으니까)
> 그래서 `Thread.sleep(forTimeInterval: 2.0)`를 통해 현재 쓰레드를 2초간 유지해줍니다.
> 그럼 300 milliseconds마다 항목이 배출되니까, 다음과 같은 결과가 나오겠죠!
```
0
1
2
3
4
5
```
`dispose`를 호출하고 싶지 않다면, 다른 방법이 있습니다! `DisposeBag`을 사용하거나 `takeUntil` 연산자를 사용하세요!
그래서 위의 코드에서는 `dispose`가 호출된 다음 뭔가가 print 될까요? 정답은 : 때때로 다릅니다. XD
* 만약 `scheduler`가 **serial scheduler**라면 (`MainScheduler`라던가) `dispose`가 **같은 serial scheduler**에서 호출됩니다. 그래서 더 이상 print 되지 않죠.
* 다른 경우에는 네, 그럴 수 있습니다.
#### 예시
```swift
let serial = SerialDispatchQueueScheduler(qos: .default)
let subscription = Observable<Int>.interval(.milliseconds(100), scheduler: serial)
.subscribe { event in
print("serial: \(event)")
}
let concurrent: SchedulerType = ConcurrentDispatchQueueScheduler(qos: .default)
let subscription2 = Observable<Int>.interval(.milliseconds(100), scheduler: concurrent)
.subscribe { event in
print("concurrent: \(event)")
}
Thread.sleep(forTimeInterval: 3.0)
print("ended")
subscription.dispose()
subscription2.dispose()
```
#### 결과
```
serial: next(0)
concurrent: next(0)
serial: next(1)
concurrent: next(1)
...
serial: next(28)
concurrent: next(28)
serial: next(29)
ended
concurrent: next(29)
```
### Dispose Bags
Dispose bag은 Rx에서 ARC와 같은 동작을 합니다. `DisposeBag`이 dealloc되는 시점에, DisposeBag에 포함된 모든 `disposable` 들에 대해 `dispose`가 호출됩니다.
그렇기 때문에 Dispose bag에는 `dispose` 메서드가 없습니다. 만약 Dispose bag의 모든 항목을 정리해야한다면, 새로운 DisposeBag을 만들면 됩니다.
```
self.disposeBag = DisposeBag()
```
그러면 이전 DisposeBag이 dealloc되면서 담겨있던 항목들이 `dispose()`가 호출됩니다.
만약 명시적으로 dispose를 처리하고 싶다면 `CompositeDisposable`을 사용하세요.
### Take until
다른 방법으로는 dealloc될 때 `takeUntil`을 사용해서 자동으로 dispose 되도록 하는 방법이 있습니다.
```swift
sequence
.takeUntil(self.rx.deallocated)
.subscribe {
print($0)
}
```
### 찾아보기
[Disposable의 종류](https://brunch.co.kr/@tilltue/49)
|
C
|
UTF-8
| 2,275 | 2.890625 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<stdlib.h>
struct process{
int burst,wt,tat;
int start_time,end_time;
} proc[20]={0,0};
int p;
void input()
{
int i;
for(i=0;i<p;i++)
{
printf("Enter the burst time of process %d:",i+1);
scanf("%d",&proc[i].burst);
}
for(i=0;i<p;i++)
{
printf("Process %d\t",i+1);
}
printf("\n");
for(i=0;i<p;i++)
{
printf("%d\t\t",proc[i].burst);
}
printf("\n");
}
void calculate(int timeq)
{
int i,j;
int total_time=0;
//initialise
for(i=0;i<p;i++)
{
proc[i].wt=0;
proc[i].tat=0;
proc[i].end_time=0;
proc[i].start_time=0;
}
for(i=0;i<p;i++)
{
proc[i].tat+=proc[i].burst;
}
//
//displaying iteration
for(j=0;j<2*p;j++)
{
printf("\nIteration %d\n",j+1);
for(i=0;i<p;i++)
{
/*if(proc[i].burst==0)
{
}*/
if(proc[i].burst==0)
{
continue;
}
else if(proc[i].burst>=timeq)
{
proc[i].burst=proc[i].burst-timeq;
printf("Process %d:%d",i+1,proc[i].burst);
printf("\t");
proc[i].wt=total_time-proc[i].end_time;
proc[i].start_time=total_time;
proc[i].end_time+=timeq;
total_time+=timeq;
}
else
{
proc[i].wt=total_time-proc[i].end_time;
proc[i].start_time=total_time;
proc[i].end_time+=proc[i].burst;
total_time+=proc[i].burst;
proc[i].burst=0;
printf("Process %d:%d",i+1,proc[i].burst);
printf("\t");
}
}
//terminating condition
int flag=0;
for(i=0;i<p;i++)
{
if(proc[i].burst==0)
flag++;
}
if(flag==p)
{
printf("\nAll processes have Completed their burst time Exiting....\n");
printf("\nTotal Time Is:%d\n",total_time);
//exit(0);
break;
}
//
}
for(i=0;i<p;i++)
{
proc[i].tat+=proc[i].wt;
}
}
void output()
{
int i;
int sumWaiting=0;
int avgWaiting=0;
int sumTurn=0;
int avgTurn=0;
printf("\nWaiting Time\n");
for(i=0;i<p;i++)
printf("Process %d:%d \t",i+1,proc[i].wt);
for(i=0;i<p;i++)
sumWaiting+=proc[i].wt;
printf("\nSum Waiting Time:%d",sumWaiting);
avgWaiting=sumWaiting/p;
printf("\nAverage Waiting Time:%d",avgWaiting);
printf("\nTurnaround Time\n");
for(i=0;i<p;i++)
printf("Process %d:%d \t",i+1,proc[i].tat);
for(i=0;i<p;i++)
sumTurn+=proc[i].tat;
printf("\nSum TA Time:%d",sumTurn);
avgTurn=sumTurn/p;
printf("\nAverage Turnaround Time:%d",avgTurn);
}
void main()
{
printf("Enter the no. of process:");
scanf("%d",&p);
input();
int timeq;
printf("Enter the time quantum\n");
scanf("%d",&timeq);
calculate(timeq);
output();
}
|
PHP
|
UTF-8
| 1,058 | 3.203125 | 3 |
[] |
no_license
|
<?php
require_once('task26.php');
class Registration{
protected $name;
protected $lastname;
protected $email;
protected $pass1;
protected $pass2;
protected $md5email;
public function __construct($name,$lastname,$email, $pass1, $pass2, $md5email)
{
$this->name = $_POST["name"];
$this->lastname = $_POST["lastname"];
$this->email = $_POST["email"];
$this->pass1 = $_POST["pass1"];
$this->pass2 = $_POST["pass2"];
$this->md5email = md5($this->$email);
}
public function checkPassword(){
if($this->pass1 == $this->pass2){
$arr = [$this->name, $this->lastname, $this->email, $this->pass1, $this->pass2];
} else{
return false;
}
}
public function saveData(){
if(file_exists("/home/milosz/Desktop/darcia/projektzkodem/public/data/".$this->md5email.".dat")){
return "Zostałeś zarejestrowany";
} else{
file_put_contents("/home/milosz/Desktop/darcia/projektzkodem/public/data/".$this->md5email.".dat", serialize($arr));
return "Konto zostało utworzone poprawnie!";
}
}
}
|
Java
|
UTF-8
| 8,844 | 1.664063 | 2 |
[] |
no_license
|
/*
* Copyright (c) 2004, 2005 Polarion Software, All rights reserved.
* Email: community@polarion.org
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. Copy of the License is
* located in the file LICENSE.txt in the project distribution. You may also
* obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
*
* POLARION SOFTWARE MAKES NO REPRESENTATIONS OR WARRANTIES
* ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER EXPRESSED OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. POLARION SOFTWARE
* SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT
* OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*
*/
/*
* $Log$
*/
package org.polarion.svnimporter.cvsprovider.internal;
import org.polarion.svnimporter.common.Log;
import org.polarion.svnimporter.cvsprovider.CvsException;
import org.polarion.svnimporter.cvsprovider.CvsProvider;
import org.polarion.svnimporter.cvsprovider.internal.model.CvsBranch;
import org.polarion.svnimporter.cvsprovider.internal.model.CvsCommit;
import org.polarion.svnimporter.cvsprovider.internal.model.CvsModel;
import org.polarion.svnimporter.cvsprovider.internal.model.CvsRevision;
import org.polarion.svnimporter.cvsprovider.internal.model.CvsRevisionState;
import org.polarion.svnimporter.cvsprovider.internal.model.CvsTag;
import org.polarion.svnimporter.svnprovider.SvnModel;
import org.polarion.svnimporter.svnprovider.internal.SvnProperties;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
*
*
* @author <A HREF="mailto:svnimporter@polarion.org">Polarion Software</A>
*/
public class CvsTransform {
private static final Log LOG = Log.getLog(CvsTransform.class);
private static final String CVS_REVISION_NUMBER = "CVSRevisionNumber";
private final CvsProvider provider;
private SvnModel svnModel;
public CvsTransform(CvsProvider cvsProvider) {
this.provider = cvsProvider;
}
/**
* Transform cvsModel to SvnModel
*
* @return
*/
public SvnModel transform(CvsModel srcModel) {
if (srcModel.getCommits().size() < 1) {
return new SvnModel();
}
svnModel = new SvnModel();
if (provider.getConfig() instanceof CvsConfig)
svnModel.setModuleName(((CvsConfig) provider.getConfig()).getModuleName());
svnModel.setSvnimporterUsername(provider.getConfig().getSvnimporterUsername());
CvsCommit firstCommit = (CvsCommit) srcModel.getCommits().get(0);
svnModel.createFirstRevision(firstCommit.getDate());
svnModel.createTrunkPath(provider.getConfig().getTrunkPath());
if (!isOnlyTrunk()) {
svnModel.createBranchesPath(provider.getConfig().getBranchesPath());
svnModel.createTagsPath(provider.getConfig().getTagsPath());
}
for (Iterator i = srcModel.getCommits().iterator(); i.hasNext();)
transformCommit((CvsCommit) i.next());
return svnModel;
}
/**
* @return
*/
private boolean isOnlyTrunk() {
return provider.getConfig().isOnlyTrunk();
}
/**
* Transform CvsCommit to SvnRevision
*
* @param commit
*/
private void transformCommit(CvsCommit commit) {
svnModel.createNewRevision(commit.getAuthor(), commit.getDate(), commit.getMessage());
svnModel.getCurRevision().getProperties().set("CVSRevisionNumbers", commit.joinRevisionNumbers());
Map childBranches = new HashMap(); // CvsBranch -> List of CvsRevisions
Map childTags = new HashMap(); // CvsTag -> List of CvsRevisions
for (Iterator i = commit.getRevisions().iterator(); i.hasNext();) {
CvsRevision revision = (CvsRevision) i.next();
transformRevision(revision);
if (!isOnlyTrunk()) {
//--- record branches ----
for (Iterator b = revision.getChildBranches().iterator(); b.hasNext();) {
CvsBranch childBranch = (CvsBranch) b.next();
if (!childBranches.containsKey((childBranch.getName())))
childBranches.put(childBranch.getName(), new ArrayList());
((Collection) childBranches.get(childBranch.getName())).add(revision);
}
//--- record tags ---
for (Iterator t = revision.getTags().iterator(); t.hasNext();) {
CvsTag childTag = (CvsTag) t.next();
if (!childTags.containsKey(childTag.getName()))
childTags.put(childTag.getName(), new ArrayList());
((Collection) childTags.get(childTag.getName())).add(revision);
}
}
}
if (!isOnlyTrunk()) {
// Remember old SVN revision number.
int oldRevno = svnModel.getCurRevisionNumber();
if (provider.getConfig().useFileCopy()
&& (!childBranches.isEmpty() || !childTags.isEmpty())) {
// If we have child tags, we introduce a new SVN Revision. We must do this
// since Subversion is able to copy files only if the source revision is smaller
// than the actual revision.
svnModel.createNewRevision(commit.getAuthor(),
commit.getDate(), "svnimporter: adding tags and branches to revision " + oldRevno);
}
// create branches
for (Iterator i = childBranches.keySet().iterator(); i.hasNext();) {
String branchName = (String) i.next();
// create branch, if necessary
if (!svnModel.isBranchCreated(branchName))
svnModel.createBranch(branchName, commit.getDate());
for (Iterator j = ((Collection) childBranches.get(branchName)).iterator(); j.hasNext();) {
CvsRevision revision = (CvsRevision) j.next();
if (provider.getConfig().useFileCopy()) {
svnModel.addFileCopyToBranch(revision.getPath(),
branchName,
revision.getBranch().getName(),
revision.getPath(),
oldRevno);
} else {
svnModel.addFile(revision.getPath(),
branchName,
new CvsContentRetriever(provider, revision));
}
}
}
// create tags
for (Iterator i = childTags.keySet().iterator(); i.hasNext();) {
String tagName = (String) i.next();
// create tag, if necessary
if (!svnModel.isTagCreated(tagName))
svnModel.createTag(tagName, commit.getDate());
// copy files into tag folder
for (Iterator j = ((Collection) childTags.get(tagName)).iterator(); j.hasNext();) {
CvsRevision revision = (CvsRevision) j.next();
if (provider.getConfig().useFileCopy()) {
svnModel.addFileCopyToTag(revision.getPath(),
tagName,
revision.getBranch().getName(),
revision.getPath(),
oldRevno);
} else {
svnModel.addFileToTag(revision.getPath(),
tagName,
new CvsContentRetriever(provider, revision));
}
}
}
} // if(!isOnlyTrunk())
}
/**
* Transform CvsRevision to SvnNodeAction
*
* @param revision
*/
private void transformRevision(CvsRevision revision) {
String path = revision.getPath();
String branchName = revision.getBranch().getBranchName();
if (isOnlyTrunk() && !revision.getBranch().isTrunk())
return;
SvnProperties p = new SvnProperties();
p.set(CVS_REVISION_NUMBER, revision.getNumber());
if (revision.getState() == CvsRevisionState.ADD) {
svnModel.addFile(path, branchName, provider.createContentRetriever(revision), p);
} else if (revision.getState() == CvsRevisionState.CHANGE) {
svnModel.changeFile(path, branchName, provider.createContentRetriever(revision), p);
} else if (revision.getState() == CvsRevisionState.DELETE) {
svnModel.deleteFile(path, branchName, p);
} else {
LOG.error(revision.getDebugInfo());
LOG.error(revision.getBranch().getDebugInfo());
throw new CvsException("unknown cvs revision state: " + revision.getState());
}
}
}
|
Go
|
UTF-8
| 3,252 | 2.96875 | 3 |
[] |
no_license
|
package DB
import (
"RMQ_Project/common"
"RMQ_Project/model"
"database/sql"
"fmt"
"log"
"strconv"
)
type MyProduct interface {
Conn() error
Inset(*model.Product) (int64, error)
Delete(int64) bool
Update(*model.Product) error
SelectByKey(int64) (*model.Product, error)
SelectAll() ([]*model.Product, error)
}
type ProductManager struct {
table string
conn *sql.DB
}
func NewProductManager(table string, conn *sql.DB) MyProduct {
return &ProductManager{table: table, conn: conn}
}
// 链接数据库
func (pm ProductManager) Conn() (err error) {
if pm.conn == nil {
mysql, err := common.NewMysqlConn()
if err != nil {
return err
}
pm.conn = mysql
}
if pm.table == "" {
pm.table = "product"
}
return
}
//插入数据
func (pm ProductManager) Inset(product *model.Product) (productID int64, err error) {
if err := pm.Conn(); err != nil {
fmt.Print(err)
return 0, err
}
// 准备sql
const SQL = `INSERT product SET productName=?, productNum=?, productImage=?, productUrl=?`
stmt, err := pm.conn.Prepare(SQL)
if err != nil {
fmt.Print(err)
return 0, err
}
defer stmt.Close()
//插入数据
result, err := stmt.Exec(product.ProductName, product.ProductNum, product.ProductImage, product.ProductUrl)
if err != nil {
fmt.Print(err)
return 0, err
}
//返回数据
fmt.Print(result.LastInsertId())
return result.LastInsertId()
}
func (pm ProductManager) Delete(id int64) bool {
if err := pm.Conn(); err == nil {
return false
}
const SQL = `DELETE FROM product WHERE id=?`
stmt, err := pm.conn.Prepare(SQL)
if err != nil {
log.Print(err)
return false
}
defer stmt.Close()
_, err = stmt.Exec(strconv.FormatInt(id, 10))
if err != nil {
log.Print(err)
return false
}
return true
}
func (pm ProductManager) Update(product *model.Product) error {
if err := pm.Conn(); err == nil {
return err
}
const SQL = `UPDATE product SET productName=?, productNum=?, productImage=?, productUrl=? WHERE id =?`
smtp, err := pm.conn.Prepare(SQL)
if err != nil {
return err
}
defer smtp.Close()
_, err = smtp.Exec(product.ProductName, product.ProductNum, product.ProductImage, product.ProductUrl, product.ID)
if err != nil {
return err
}
return nil
}
func (pm ProductManager) SelectByKey(id int64) (productResult *model.Product, err error) {
if err := pm.Conn(); err == nil {
return &model.Product{}, err
}
SQL := "SELECT * FROM " + pm.table + "WHERE id=?"
row, err := pm.conn.Query(SQL)
if err != nil {
return &model.Product{}, err
}
defer row.Close()
result := common.GetResultRow(row)
if len(result) == 0 {
return &model.Product{}, nil
}
common.DataToStructByTagSql(result, &model.Product{})
return
}
func (pm ProductManager) SelectAll() (productArray []*model.Product, err error) {
if err := pm.Conn(); err != nil {
return nil, err
}
SQL := fmt.Sprintf("SELECT * FROM %s",pm.table)
rows, err := pm.conn.Query(SQL)
if err != nil {
fmt.Print(err)
return nil, err
}
defer rows.Close()
result := common.GetResultRows(rows)
if len(result) == 0 {
return nil, nil
}
for _, v := range result {
product := &model.Product{}
common.DataToStructByTagSql(v, product)
productArray = append(productArray, product)
}
return productArray,err
}
|
Java
|
UTF-8
| 22,491 | 1.890625 | 2 |
[] |
no_license
|
package com.zzz.wc.strawberrycount.activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.zzz.wc.strawberrycount.R;
import com.zzz.wc.strawberrycount.adpter.BoxAdapter;
import com.zzz.wc.strawberrycount.adpter.BtnListenerInterface;
import com.zzz.wc.strawberrycount.adpter.CheckerAdapter;
import com.zzz.wc.strawberrycount.adpter.MyListView;
import com.zzz.wc.strawberrycount.box.Box;
import com.zzz.wc.strawberrycount.box.BoxDAO;
import com.zzz.wc.strawberrycount.checker.Checker;
import com.zzz.wc.strawberrycount.checker.CheckerDAO;
import com.zzz.wc.strawberrycount.util.BoxUtil;
import com.zzz.wc.strawberrycount.util.DateUtil;
import com.zzz.wc.strawberrycount.util.Tag;
import java.util.Calendar;
import java.util.List;
public class BoxActivity extends AppCompatActivity implements CheckerAdapter.CheckerListenerInterface {
private String className = "BoxActivity";
private EditText edit_flat;
private EditText edit_top;
private EditText edit_black;
private EditText edit_pinkcube;
private EditText edit_yellowcube;
private EditText edit_yummycube;
private EditText edit_normalcube;
//plus
private EditText edit_flat_plus;
private EditText edit_top_plus;
private EditText edit_black_plus;
private EditText edit_pinkcube_plus;
private EditText edit_yellowcube_plus;
private EditText edit_yummycube_plus;
private EditText edit_normalcube_plus;
private EditText edit_flat_price;
private EditText edit_black_price;
private EditText edit_top_price;
private EditText edit_cube_price;
private Button dateButton;
private TextView dateText;
//checker
private CheckerDAO checkerDAO;
private List<Checker> checkerList;
private CheckerAdapter checkerAdapter;
private MyListView checkerListView;
private Button btn_checker;
private Box box;
private Box preBox;
private BoxDAO boxDAO;
private int mYear, mMonth, mDay,mHour, mMinute; //DatePicker/TimePicker用
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_box);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
init();
boxDAO = new BoxDAO(this);
checkerDAO = new CheckerDAO(this);
String date = null;
Bundle extras = getIntent().getExtras();
date = (extras == null ? date : extras.getString(Tag.BundleKey.DATE));
if (date != null) {
readData(date);
} else {//建立新Box
box = new Box();
preBox = boxDAO.getLast(); //取最新的一筆
if (preBox != null) { //若有帶出最近的一筆的資料
box.setFlat(preBox.getFlat());
box.setTop(preBox.getTop());
box.setBlack(preBox.getBlack());
box.setCubePink(preBox.getCubePink());
box.setCubeYellow(preBox.getCubeYellow());
box.setCubeYummy(preBox.getCubeYummy());
box.setCubeNormal(preBox.getCubeNormal());
box.setPrint_black(preBox.getPrint_black());
box.setPrint_cube(preBox.getPrint_cube());
box.setPrint_flat(preBox.getPrint_flat());
box.setPrint_top(preBox.getPrint_top());
box.setDate(DateUtil.getToday());
box.setCheckerPrice(preBox.getCheckerPrice());
putToUI(box);
} else { //若沒有給預設值
box.setDate(DateUtil.getToday());
box.setPrint_black(0.25);
box.setPrint_cube(0.16);
box.setPrint_flat(0.14);
box.setPrint_top(0.2);
box.setCheckerPrice(20.41);
putToUI(box);
}
}
}
public void init(){
edit_flat = (EditText) findViewById(R.id.edit_flat);
edit_top = (EditText) findViewById(R.id.edit_top);
edit_black = (EditText) findViewById(R.id.edit_black);
edit_pinkcube = (EditText) findViewById(R.id.edit_pinkcube);
edit_yellowcube = (EditText) findViewById(R.id.edit_yellowcube);
edit_yummycube = (EditText) findViewById(R.id.edit_yummycube);
edit_normalcube = (EditText) findViewById(R.id.edit_normalcube);
edit_flat_plus = (EditText) findViewById(R.id.edit_flat_plus);
edit_top_plus = (EditText) findViewById(R.id.edit_top_plus);
edit_black_plus = (EditText) findViewById(R.id.edit_black_plus);
edit_pinkcube_plus = (EditText) findViewById(R.id.edit_pinkcube_plus);
edit_yellowcube_plus = (EditText) findViewById(R.id.edit_yellowcube_plus);
edit_yummycube_plus = (EditText) findViewById(R.id.edit_yummycube_plus);
edit_normalcube_plus = (EditText) findViewById(R.id.edit_normalcube_plus);
edit_flat_price = (EditText) findViewById(R.id.edit_flat_price);
edit_black_price = (EditText) findViewById(R.id.edit_black_price);
edit_top_price = (EditText) findViewById(R.id.edit_top_price);
edit_cube_price = (EditText) findViewById(R.id.edit_cube_price);
dateButton = (Button)findViewById(R.id.dateButton);
dateText = (TextView)findViewById(R.id.dateText);
checkerListView = (MyListView) findViewById(R.id.lv_checkerlist);
btn_checker = (Button) findViewById(R.id.btn_checker);
dateButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
new DatePickerDialog(BoxActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
String format = setDateFormat(year,month,day);
dateText.setText("日期: "+format);
box.setDate(DateUtil.stringToDate(format));
}
}, mYear,mMonth, mDay).show();
}
});
btn_checker.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onClick(View v) {
openCheckerDialog(null);
}
});
checkerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Log.d(className,"checkerListView click");
Checker checker = checkerList.get(position);
if(checker == null || checker.getCheckerDate()==null)
return;
openCheckerDialog(checker);
}
});
}
public List getCheckerData(){
return checkerDAO.getByDate(BoxUtil.converToString(box.getDate()));
}
/**
* 儲存
*/
public void save(){
int flat = Integer.parseInt(handleEditText(edit_flat));
int top = Integer.parseInt(handleEditText(edit_top));
int black = Integer.parseInt(handleEditText(edit_black));
int pink = Integer.parseInt(handleEditText(edit_pinkcube));
int yellow = Integer.parseInt(handleEditText(edit_yellowcube));
int yummy = Integer.parseInt(handleEditText(edit_yummycube));
int normal = Integer.parseInt(handleEditText(edit_normalcube));
int flat_plus = Integer.parseInt(handleEditText(edit_flat_plus));
int top_plus = Integer.parseInt(handleEditText(edit_top_plus));
int black_plus = Integer.parseInt(handleEditText(edit_black_plus));
int pink_plus = Integer.parseInt(handleEditText(edit_pinkcube_plus));
int yellow_plus = Integer.parseInt(handleEditText(edit_yellowcube_plus));
int yummy_plus = Integer.parseInt(handleEditText(edit_yummycube_plus));
int normal_plus = Integer.parseInt(handleEditText(edit_normalcube_plus));
double price_flat = Double.parseDouble(handleEditText_double(edit_flat_price));
double price_black = Double.parseDouble(handleEditText_double(edit_black_price));
double price_top = Double.parseDouble(handleEditText_double(edit_top_price));
double price_cube = Double.parseDouble(handleEditText_double(edit_cube_price));
// double checkerPrice = Double.parseDouble(handleEditText_double(edit_checker_price));
box.setFlat(flat);
box.setFlat_plus(flat_plus);
box.setTop(top);
box.setTop_plus(top_plus);
box.setBlack(black);
box.setBlack_plus(black_plus);
box.setCubePink(pink);
box.setCubePink_plus(pink_plus);
box.setCubeYellow(yellow);
box.setCubeYellow_plus(yellow_plus);
box.setCubeYummy(yummy);
box.setCubeYummy_plus(yummy_plus);
box.setCubeNormal(normal);
box.setCubeNormal_plus(normal_plus);
box.setPrint_flat(price_flat);
box.setPrint_black(price_black);
box.setPrint_top(price_top);
box.setPrint_cube(price_cube);
// box.setCheckerPrice(checkerPrice);
if (box.getDate()==null) {
Toast.makeText(BoxActivity.this, "請選日期", Toast.LENGTH_LONG).show();
return;
}
long i = boxDAO.saveByDate(box);
if (i > 0) {
Toast.makeText(BoxActivity.this, getString(R.string.txt_save_succuess), Toast.LENGTH_LONG).show();
BoxActivity.this.finish();
}
}
public String handleEditText(EditText edit){
String ss;
ss = edit.getText()==null?"0":edit.getText().toString();
if ("".equals(edit.getText().toString().trim())){
ss = "0";
}
return ss;
}
public String handleEditText_double(EditText edit){
String ss;
ss = edit.getText()==null?"0.0":edit.getText().toString();
if ("".equals(edit.getText().toString().trim())){
ss = "0.0";
}
return ss;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_box, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
long ii = boxDAO.delete(box);
if(ii>0){
Toast.makeText(BoxActivity.this, getString(R.string.txt_save_delete), Toast.LENGTH_SHORT).show();
BoxActivity.this.finish();
}
break;
case R.id.action_save:
save();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
private void readData(String date){
if(date == null)
return;
box = boxDAO.getByDate(date);
checkerList = checkerDAO.getByDate(date);
if(box != null) {
putToUI(box);
}
}
private void reloadChecker(){
checkerList = getCheckerData();
checkerAdapter.reload(checkerList);
}
public void putToUI(Box box){
edit_flat.setText(String.valueOf(box.getFlat()));
edit_top.setText(String.valueOf(box.getTop()));
edit_black.setText(String.valueOf(box.getBlack()));
edit_pinkcube.setText(String.valueOf(box.getCubePink()));
edit_yellowcube.setText(String.valueOf(box.getCubeYellow()));
edit_yummycube.setText(String.valueOf(box.getCubeYummy()));
edit_normalcube.setText(String.valueOf(box.getCubeNormal()));
edit_flat_plus.setText(String.valueOf(box.getFlat_plus()));
edit_top_plus.setText(String.valueOf(box.getTop_plus()));
edit_black_plus.setText(String.valueOf(box.getBlack_plus()));
edit_pinkcube_plus.setText(String.valueOf(box.getCubePink_plus()));
edit_yellowcube_plus.setText(String.valueOf(box.getCubeYellow_plus()));
edit_yummycube_plus.setText(String.valueOf(box.getCubeYummy_plus()));
edit_normalcube_plus.setText(String.valueOf(box.getCubeNormal_plus()));
//讀取日期
String format = "日期: " + String.valueOf( DateUtil.getYear(box.getDate())) + "-"
+ String.valueOf(DateUtil.getMonth(box.getDate())) + "-"
+ String.valueOf(DateUtil.getDayOfMonth(box.getDate()));
dateText.setText(format);
//讀取price
edit_flat_price.setText(String.valueOf(box.getPrint_flat()));
edit_black_price.setText(String.valueOf(box.getPrint_black()));
edit_top_price.setText(String.valueOf(box.getPrint_top()));
edit_cube_price.setText(String.valueOf(box.getPrint_cube()));
//讀取checker
// edit_checker_price.setText(String.valueOf(box.getCheckerPrice()));
// txtTime_start.setText(DateUtil.timeToString(box.getCheckerTime()));
// txtTime_end .setText(DateUtil.timeToString(box.getCheckerTime_end()));
checkerAdapter = new CheckerAdapter(this, checkerList);
checkerAdapter.setCheckerListenerInterface(this);
checkerListView.setAdapter(checkerAdapter);
}
private void openCheckerDialog(Checker cc) {
AlertDialog.Builder builder = new AlertDialog.Builder(BoxActivity.this);
LayoutInflater inflater = LayoutInflater.from(BoxActivity.this);
View contentView = inflater.inflate(R.layout.content_checker, null);
final EditText edit_checker_price = (EditText) contentView.findViewById(R.id.edit_checker_price);
ImageButton btnTime_start = (ImageButton) contentView.findViewById(R.id.btnTime_start);
ImageButton btnTime_end = (ImageButton)contentView.findViewById(R.id.btnTime_end);
final TextView txtTime_start = (TextView)contentView.findViewById(R.id.txtTime_start);
final TextView txtTime_end = (TextView)contentView.findViewById(R.id.txtTime_end);
Button btnStart_reset = (Button) contentView.findViewById(R.id.btnStart_reset);
Button btnEnd_reset = (Button) contentView.findViewById(R.id.btnEnd_reset);
builder.setView(contentView);
final Checker checker = new Checker();
if(cc !=null){ //編輯
edit_checker_price.setText(String.valueOf(cc.getCheckerPrice()));
txtTime_start.setText(DateUtil.timeToString(cc.getCheckerTime()));
txtTime_end .setText(DateUtil.timeToString(cc.getCheckerTime_end()));
checker.setCheckerDate(cc.getCheckerDate());
checker.setCheckerTime(cc.getCheckerTime());
checker.setCheckerTime_end(cc.getCheckerTime_end());
checker.setCheckerPrice(cc.getCheckerPrice());
}
else{
Checker lastChecker = checkerDAO.getLast();
if(lastChecker!=null)
edit_checker_price.setText(String.valueOf(lastChecker.getCheckerPrice()));
}
btnTime_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 設定初始時間
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// 跳出時間選擇器
new TimePickerDialog(BoxActivity.this, new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// 完成選擇,顯示時間
txtTime_start.setText(hourOfDay + ":" + minute);
String format = setTimeFormat(hourOfDay,minute);
checker.setCheckerTime(DateUtil.stringToTime(format));
}
}, mHour, mMinute, false).show();
}
});
btnTime_end.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 設定初始時間
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// 跳出時間選擇器
new TimePickerDialog(BoxActivity.this, new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// 完成選擇,顯示時間
txtTime_end.setText(hourOfDay + ":" + minute);
String format = setTimeFormat(hourOfDay,minute);
checker.setCheckerTime_end(DateUtil.stringToTime(format));
}
}, mHour, mMinute, false).show();
}
});
btnStart_reset.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onClick(View v) {
txtTime_start.setText(null);
checker.setCheckerTime(null);
}
});
btnEnd_reset.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onClick(View v) {
txtTime_end.setText(null);
checker.setCheckerTime_end(null);
}
});
DialogInterface.OnClickListener dialogListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch(which){
case DialogInterface.BUTTON_POSITIVE:
double checkerPrice = Double.parseDouble(handleEditText_double(edit_checker_price));
checker.setCheckerPrice(checkerPrice);
saveChecker(checker);
break;
case DialogInterface.BUTTON_NEGATIVE:
dialog.dismiss();
break;
}
}
};
builder.setPositiveButton(R.string.yes, dialogListener)
.setNegativeButton(R.string.no, dialogListener)
.setTitle(getString(R.string.txt_new_checker))
.setCancelable(false);
AlertDialog cardDialog = builder.create();
cardDialog.show();
}
/**
* 儲存checker
* @param checker
*/
private void saveChecker(Checker checker){
if(checker.getCheckerTime()!=null ){
if(checker.getCheckerTime_end()==null){
Toast.makeText(BoxActivity.this, "請輸入結束時間", Toast.LENGTH_LONG).show();
return;
}
}
if(checker.getCheckerTime_end()!=null ){
if(checker.getCheckerTime()==null){
Toast.makeText(BoxActivity.this, "請輸入開始時間", Toast.LENGTH_LONG).show();
return;
}
}
if(BoxUtil.handleCheckerHour(checker.getCheckerTime().getTime(),checker.getCheckerTime_end().getTime())<=0){
Toast.makeText(BoxActivity.this, "結束時間不能小於開始時間", Toast.LENGTH_LONG).show();
return;
}
checker.setCheckerDate(box.getDate());
final CheckerDAO checkerDAO = new CheckerDAO(this);
long i = checkerDAO.saveByUnid(checker);
if (i > 0) {
Toast.makeText(BoxActivity.this, getString(R.string.txt_save_succuess), Toast.LENGTH_LONG).show();
reloadChecker();
// calCheckerTotal();//偷存checker total
}
}
/**
* 處理日期
* @param year
* @param monthOfYear
* @param dayOfMonth
* @return
*/
private String setDateFormat(int year, int monthOfYear, int dayOfMonth) {
return String.valueOf(year) + "-"
+ String.valueOf(monthOfYear + 1) + "-"
+ String.valueOf(dayOfMonth);
}
private String setTimeFormat(int mHour, int mMinute) {
return String.valueOf(mHour) + ":"
+ String.valueOf(mMinute) + ":"
+ String.valueOf("00");
}
@Override
public void onClick(final Checker checker) {
Log.d(className,"onClick!!!");
final AlertDialog.Builder builder = new AlertDialog.Builder(BoxActivity.this);
builder.setTitle(R.string.title_delete).setIcon(R.mipmap.ic_launcher)
.setMessage(R.string.msg_delete);
builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
long i = checkerDAO.deleteByUnid(checker);
if(i>0){
Toast.makeText(BoxActivity.this,getString(R.string.txt_save_succuess),Toast.LENGTH_SHORT).show();
reloadChecker();
}
}
});
builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
}
|
Python
|
UTF-8
| 1,458 | 4.125 | 4 |
[] |
no_license
|
def enterWord():
counter = 0
word = input("Please enter a word.\n")
display = input("How would you like me to display this?\n")
if display == "Display in a box":
counter = counter + 1
print("You've selected option", counter)
displayInBox(word)
elif display == "Display lower case":
counter += 2
print("You've selected option", counter)
displayLower(word)
elif display == "Display upper case":
counter += 3
print("You've selected option", counter)
displayUpper(word)
elif display == "Display mirror":
counter += 4
print("You've selected option", counter)
displayMirror(word)
elif display == "Repeat":
counter += 5
print("You've selected option", counter)
repeat(word)
else:
print("What you talking bout willis")
print("Thank you for playing with Bot and Beep")
def displayInBox(word):
print("*" * (len(word) + 4))
print("*", word, "*")
print("*" * (len(word) + 4))
def displayLower(word):
print(word.lower())
def displayUpper(word):
print(word.upper())
def displayMirror(word):
phrase = ""
#for loop
for count in range(len(word), 0, -1):
phrase += word[count-1]
print(phrase)
def repeat(word):
times = int(input("How many times should I repeat?\n"))
for count in range (times):
print(word.upper(),word.lower())
enterWord()
|
JavaScript
|
UTF-8
| 2,546 | 4.625 | 5 |
[] |
no_license
|
/*
Given an array of integers
return the index where the smallest integer is located
return -1 if there is no smallest integer (array is empty)
since -1 is not a valid index, this indicates it couldn't be found
If the smallest integer occurs more than once, return the index of the first one.
*/
// const nums1 = [5, 2, 3]
// const expected1 = 1
// const nums2 = [5, 2, 2, 3]
// const expected2 = 1
// const nums3 = [5]
// const expected3 = -1
function indexOfMinVal(nums) {
// given an array (arr) of integers, iterate throught he array. return smallest integer. This will require storing each integer (minVal)found
// replacing only if there is a smaller (<). Also need to store the index (idx) of that integer, because that is what we return.
// if no integers are found, return -1;
if(nums.length < 1){
return -1;
}
var minVal = nums[0];
var idx = 0;
for(var i=1; i<nums.length; i++){
if(nums[i] < minVal){
minVal = nums[i];
idx = i;
}
}
return idx;
}
// console.log(indexOfMinVal(nums1));
// console.log(indexOfMinVal(nums2));
// console.log(indexOfMinVal(nums3));
/* ******************************************************************************** */
/*
Array: Second-Largest
Return the second-largest element of an array, or null if there is none.
Bonus: do it with one loop and no nested loops
*/
const nums1 = [2, 3, 1, 4]
// const expected1 = 3
const nums2 = [3, 3]
// const expected2 = null
const nums3 = [2]
// const expected3 = null
const nums4 = [1,2,5,4]
// const expected4 = null
function secondLargest(nums) {
// given an array (nums) of integers, find the SECOND largest number and return it. Otherwise return null.
// need two variables. One for largest (max), one for second largest (second).
// return null if nums.length < 2
// declare max = nums[0], iterate through nums replacing max when nums[i] > max
// when replacing max with nums[i], FIRST replace second with max.
// return second
if(nums.length < 2){
return null;
}
var max = nums[0];
var second = null;
for(var i=1; i<nums.length; i++){
if(nums[i] > max){
second = max;
max = nums[i];
} else if(nums[i] > second){
second = nums[i];
}
}
return second;
}
console.log(secondLargest(nums1));
console.log(secondLargest(nums2));
console.log(secondLargest(nums3));
console.log(secondLargest(nums4));
|
C#
|
UTF-8
| 1,536 | 2.921875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AcmeCorpDomainObjects;
using AcmeCorpEF;
namespace AcmeCorpServices
{
public class PurchaseOrderService : AcmeCorpServices.IPurchaseOrderService
{
private readonly IUnitOfWorkFactory uwf;
public PurchaseOrderService(IUnitOfWorkFactory uwf)
{
this.uwf = uwf;
}
public List<PurchaseOrder> GetAllOpenPurchaseOrders()
{
using (IUnitOfWork uw = uwf.Create())
{
return (from order in uw.PurchaseOrders.Entities
where order.Status == "Open"
select order).ToList();
}
}
public PurchaseOrder GetPurchaseOrder(int purchaseOrderId )
{
using (IUnitOfWork uw = uwf.Create())
{
return uw.PurchaseOrders.Entities.Single(o => o.Id == purchaseOrderId);
}
}
public void AddToPurchaseOrder(int purchaseOrderId, string item, int quantity, decimal price)
{
using (IUnitOfWork uw = uwf.Create())
{
PurchaseOrder order = uw.PurchaseOrders.Entities.Single(o => o.Id == purchaseOrderId);
order.AddLineItem(new PurchaseOrderLineItem() { Description = item, Quantity = quantity, Price = price, Position = order.Items.Count() });
uw.Commit();
}
}
}
}
|
Ruby
|
UTF-8
| 184 | 3.1875 | 3 |
[] |
no_license
|
class Hamming
def self.compute(dna_a, dna_b)
hamming = 0
[dna_a.size, dna_b.size].min.times do |i|
hamming += 1 if dna_a[i] != dna_b[i]
end
hamming
end
end
|
Markdown
|
UTF-8
| 1,043 | 2.796875 | 3 |
[] |
no_license
|
### cookie
1. 大小限制在4kb左右
2. 一般在服务端生成,可设置失效时间
3. 每次会携带到请求头中
4. 参数
1. httponly:不要在除http/https之外的方式请求cookie如JavaScript,document.cookie
2. secure:仅在加密传输,指示浏览器仅仅在通过安全/加密连接才能使用该cookie。
3. sameSite:Strict-完全禁止第三方Cookie,跨域不携带;Lax-大部分情况下不发送第三方Cookie,但是在导航到目标网址的Get请求除外;None-默认值,自动携带cookie。
### session
1. session是保存在服务端,可以保存集群、数据库、文件中。
### sessionStorage、localStorage
1. 存储大小均为5m左右
2. 都有同源策略限制
3. 仅在客户端中保存,不参与服务端的通信
4. localStorage存储是永久性的,除非用户主动删除;sessionStorage是会话级的,关闭窗口则sessionStorage清空。
5. localStorage可以同源共享;sessionStorage只在同一浏览器,同一窗口下同源共享。
|
Java
|
UTF-8
| 18,193 | 1.960938 | 2 |
[] |
no_license
|
package pe.gob.sunafil.denunciavirtual.siit.persistence.model;
import java.util.ArrayList;
import java.util.List;
public class VstIntendenRegionalesExample {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table SIIT.VST_INTENDEN_REGIONALES
*
* @mbggenerated Tue Mar 07 17:22:30 COT 2017
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table SIIT.VST_INTENDEN_REGIONALES
*
* @mbggenerated Tue Mar 07 17:22:30 COT 2017
*/
protected boolean distinct;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table SIIT.VST_INTENDEN_REGIONALES
*
* @mbggenerated Tue Mar 07 17:22:30 COT 2017
*/
protected List<Criteria> oredCriteria;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SIIT.VST_INTENDEN_REGIONALES
*
* @mbggenerated Tue Mar 07 17:22:30 COT 2017
*/
public VstIntendenRegionalesExample() {
oredCriteria = new ArrayList<Criteria>();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SIIT.VST_INTENDEN_REGIONALES
*
* @mbggenerated Tue Mar 07 17:22:30 COT 2017
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SIIT.VST_INTENDEN_REGIONALES
*
* @mbggenerated Tue Mar 07 17:22:30 COT 2017
*/
public String getOrderByClause() {
return orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SIIT.VST_INTENDEN_REGIONALES
*
* @mbggenerated Tue Mar 07 17:22:30 COT 2017
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SIIT.VST_INTENDEN_REGIONALES
*
* @mbggenerated Tue Mar 07 17:22:30 COT 2017
*/
public boolean isDistinct() {
return distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SIIT.VST_INTENDEN_REGIONALES
*
* @mbggenerated Tue Mar 07 17:22:30 COT 2017
*/
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SIIT.VST_INTENDEN_REGIONALES
*
* @mbggenerated Tue Mar 07 17:22:30 COT 2017
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SIIT.VST_INTENDEN_REGIONALES
*
* @mbggenerated Tue Mar 07 17:22:30 COT 2017
*/
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SIIT.VST_INTENDEN_REGIONALES
*
* @mbggenerated Tue Mar 07 17:22:30 COT 2017
*/
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SIIT.VST_INTENDEN_REGIONALES
*
* @mbggenerated Tue Mar 07 17:22:30 COT 2017
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SIIT.VST_INTENDEN_REGIONALES
*
* @mbggenerated Tue Mar 07 17:22:30 COT 2017
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table SIIT.VST_INTENDEN_REGIONALES
*
* @mbggenerated Tue Mar 07 17:22:30 COT 2017
*/
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andNNumdepIsNull() {
addCriterion("N_NUMDEP is null");
return (Criteria) this;
}
public Criteria andNNumdepIsNotNull() {
addCriterion("N_NUMDEP is not null");
return (Criteria) this;
}
public Criteria andNNumdepEqualTo(String value) {
addCriterion("N_NUMDEP =", value, "nNumdep");
return (Criteria) this;
}
public Criteria andNNumdepNotEqualTo(String value) {
addCriterion("N_NUMDEP <>", value, "nNumdep");
return (Criteria) this;
}
public Criteria andNNumdepGreaterThan(String value) {
addCriterion("N_NUMDEP >", value, "nNumdep");
return (Criteria) this;
}
public Criteria andNNumdepGreaterThanOrEqualTo(String value) {
addCriterion("N_NUMDEP >=", value, "nNumdep");
return (Criteria) this;
}
public Criteria andNNumdepLessThan(String value) {
addCriterion("N_NUMDEP <", value, "nNumdep");
return (Criteria) this;
}
public Criteria andNNumdepLessThanOrEqualTo(String value) {
addCriterion("N_NUMDEP <=", value, "nNumdep");
return (Criteria) this;
}
public Criteria andNNumdepLike(String value) {
addCriterion("N_NUMDEP like", value, "nNumdep");
return (Criteria) this;
}
public Criteria andNNumdepNotLike(String value) {
addCriterion("N_NUMDEP not like", value, "nNumdep");
return (Criteria) this;
}
public Criteria andNNumdepIn(List<String> values) {
addCriterion("N_NUMDEP in", values, "nNumdep");
return (Criteria) this;
}
public Criteria andNNumdepNotIn(List<String> values) {
addCriterion("N_NUMDEP not in", values, "nNumdep");
return (Criteria) this;
}
public Criteria andNNumdepBetween(String value1, String value2) {
addCriterion("N_NUMDEP between", value1, value2, "nNumdep");
return (Criteria) this;
}
public Criteria andNNumdepNotBetween(String value1, String value2) {
addCriterion("N_NUMDEP not between", value1, value2, "nNumdep");
return (Criteria) this;
}
public Criteria andVDesdepIsNull() {
addCriterion("V_DESDEP is null");
return (Criteria) this;
}
public Criteria andVDesdepIsNotNull() {
addCriterion("V_DESDEP is not null");
return (Criteria) this;
}
public Criteria andVDesdepEqualTo(String value) {
addCriterion("V_DESDEP =", value, "vDesdep");
return (Criteria) this;
}
public Criteria andVDesdepNotEqualTo(String value) {
addCriterion("V_DESDEP <>", value, "vDesdep");
return (Criteria) this;
}
public Criteria andVDesdepGreaterThan(String value) {
addCriterion("V_DESDEP >", value, "vDesdep");
return (Criteria) this;
}
public Criteria andVDesdepGreaterThanOrEqualTo(String value) {
addCriterion("V_DESDEP >=", value, "vDesdep");
return (Criteria) this;
}
public Criteria andVDesdepLessThan(String value) {
addCriterion("V_DESDEP <", value, "vDesdep");
return (Criteria) this;
}
public Criteria andVDesdepLessThanOrEqualTo(String value) {
addCriterion("V_DESDEP <=", value, "vDesdep");
return (Criteria) this;
}
public Criteria andVDesdepLike(String value) {
addCriterion("V_DESDEP like", value, "vDesdep");
return (Criteria) this;
}
public Criteria andVDesdepNotLike(String value) {
addCriterion("V_DESDEP not like", value, "vDesdep");
return (Criteria) this;
}
public Criteria andVDesdepIn(List<String> values) {
addCriterion("V_DESDEP in", values, "vDesdep");
return (Criteria) this;
}
public Criteria andVDesdepNotIn(List<String> values) {
addCriterion("V_DESDEP not in", values, "vDesdep");
return (Criteria) this;
}
public Criteria andVDesdepBetween(String value1, String value2) {
addCriterion("V_DESDEP between", value1, value2, "vDesdep");
return (Criteria) this;
}
public Criteria andVDesdepNotBetween(String value1, String value2) {
addCriterion("V_DESDEP not between", value1, value2, "vDesdep");
return (Criteria) this;
}
public Criteria andVCodregIsNull() {
addCriterion("V_CODREG is null");
return (Criteria) this;
}
public Criteria andVCodregIsNotNull() {
addCriterion("V_CODREG is not null");
return (Criteria) this;
}
public Criteria andVCodregEqualTo(String value) {
addCriterion("V_CODREG =", value, "vCodreg");
return (Criteria) this;
}
public Criteria andVCodregNotEqualTo(String value) {
addCriterion("V_CODREG <>", value, "vCodreg");
return (Criteria) this;
}
public Criteria andVCodregGreaterThan(String value) {
addCriterion("V_CODREG >", value, "vCodreg");
return (Criteria) this;
}
public Criteria andVCodregGreaterThanOrEqualTo(String value) {
addCriterion("V_CODREG >=", value, "vCodreg");
return (Criteria) this;
}
public Criteria andVCodregLessThan(String value) {
addCriterion("V_CODREG <", value, "vCodreg");
return (Criteria) this;
}
public Criteria andVCodregLessThanOrEqualTo(String value) {
addCriterion("V_CODREG <=", value, "vCodreg");
return (Criteria) this;
}
public Criteria andVCodregLike(String value) {
addCriterion("V_CODREG like", value, "vCodreg");
return (Criteria) this;
}
public Criteria andVCodregNotLike(String value) {
addCriterion("V_CODREG not like", value, "vCodreg");
return (Criteria) this;
}
public Criteria andVCodregIn(List<String> values) {
addCriterion("V_CODREG in", values, "vCodreg");
return (Criteria) this;
}
public Criteria andVCodregNotIn(List<String> values) {
addCriterion("V_CODREG not in", values, "vCodreg");
return (Criteria) this;
}
public Criteria andVCodregBetween(String value1, String value2) {
addCriterion("V_CODREG between", value1, value2, "vCodreg");
return (Criteria) this;
}
public Criteria andVCodregNotBetween(String value1, String value2) {
addCriterion("V_CODREG not between", value1, value2, "vCodreg");
return (Criteria) this;
}
public Criteria andVNomregIsNull() {
addCriterion("V_NOMREG is null");
return (Criteria) this;
}
public Criteria andVNomregIsNotNull() {
addCriterion("V_NOMREG is not null");
return (Criteria) this;
}
public Criteria andVNomregEqualTo(String value) {
addCriterion("V_NOMREG =", value, "vNomreg");
return (Criteria) this;
}
public Criteria andVNomregNotEqualTo(String value) {
addCriterion("V_NOMREG <>", value, "vNomreg");
return (Criteria) this;
}
public Criteria andVNomregGreaterThan(String value) {
addCriterion("V_NOMREG >", value, "vNomreg");
return (Criteria) this;
}
public Criteria andVNomregGreaterThanOrEqualTo(String value) {
addCriterion("V_NOMREG >=", value, "vNomreg");
return (Criteria) this;
}
public Criteria andVNomregLessThan(String value) {
addCriterion("V_NOMREG <", value, "vNomreg");
return (Criteria) this;
}
public Criteria andVNomregLessThanOrEqualTo(String value) {
addCriterion("V_NOMREG <=", value, "vNomreg");
return (Criteria) this;
}
public Criteria andVNomregLike(String value) {
addCriterion("V_NOMREG like", value, "vNomreg");
return (Criteria) this;
}
public Criteria andVNomregNotLike(String value) {
addCriterion("V_NOMREG not like", value, "vNomreg");
return (Criteria) this;
}
public Criteria andVNomregIn(List<String> values) {
addCriterion("V_NOMREG in", values, "vNomreg");
return (Criteria) this;
}
public Criteria andVNomregNotIn(List<String> values) {
addCriterion("V_NOMREG not in", values, "vNomreg");
return (Criteria) this;
}
public Criteria andVNomregBetween(String value1, String value2) {
addCriterion("V_NOMREG between", value1, value2, "vNomreg");
return (Criteria) this;
}
public Criteria andVNomregNotBetween(String value1, String value2) {
addCriterion("V_NOMREG not between", value1, value2, "vNomreg");
return (Criteria) this;
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table SIIT.VST_INTENDEN_REGIONALES
*
* @mbggenerated do_not_delete_during_merge Tue Mar 07 17:22:30 COT 2017
*/
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table SIIT.VST_INTENDEN_REGIONALES
*
* @mbggenerated Tue Mar 07 17:22:30 COT 2017
*/
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
Shell
|
UTF-8
| 2,120 | 4.09375 | 4 |
[
"MIT"
] |
permissive
|
#!/bin/bash
usage="Graph-based Image Classification Install Script
-----------------------------------------------
Usage: $(basename "$0") [options...] <name>
Installs all requirements in a new conda environment with name <name>. Miniconda needs to be installed.
Options:
-h, --help This help text.
-p, --python The python version to use. (Default: 3.5)
--nauty The nauty version to install. (Default: 26r7)
--pynauty The pynauty version to install. (Default: 0.6.0)"
while [[ $# -gt 0 ]]; do
key="$1"
case $key in
-h|--help)
echo "$usage"
exit
;;
-n|--name)
NAME="$2"
shift
;;
-p|--python)
PYTHON="$2"
shift
;;
--nauty)
NAUTY="$NAUTY"
shift
;;
--pynauty)
PYNAUTY="$PYNAUTY"
shift
;;
*)
NAME="$1"
;;
esac
shift
done
# Set default values.
PYTHON="${PYTHON:-3.5}"
NAUTY="${NAUTY:-26r7}"
PYNAUTY="${PYNAUTY:-0.6.0}"
if [[ -z "$NAME" ]]; then
echo "Abort: No <name> found. See --help for usage information."
exit 1
fi
if ! hash conda 2>/dev/null; then
echo "Abort: Miniconda is not installed on your system."
echo "Run ./bin/conda.sh to install Miniconda."
exit 1
fi
# Create conda environement.
conda create -q -n "$NAME" python="$PYTHON"
# shellcheck disable=SC1091
source activate "$NAME"
# Install conda packages.
conda install numpy scipy matplotlib
# Install nauty and its python wrapper pynauty.
if [[ ! -d "$HOME/.sources/pynauty" ]]; then
curl "https://web.cs.dal.ca/~peter/software/pynauty/pynauty-$PYNAUTY.tar.gz" | tar xz
curl "http://users.cecs.anu.edu.au/~bdm/nauty/nauty$NAUTY.tar.gz" | tar xz
mv "nauty$NAUTY" "pynauty-$PYNAUTY/nauty"
mkdir -p "$HOME/.sources"
mv "pynauty-$PYNAUTY" "$HOME/.sources/pynauty"
cp -f "__pynauty__/graph.py" "$HOME/.sources/pynauty/src/graph.py"
cp -f "__pynauty__/nautywrap.c" "$HOME/.sources/pynauty/src/nautywrap.c"
fi
make pynauty -C "$HOME/.sources/pynauty"
make user-ins -C "$HOME/.sources/pynauty"
# Install all requirements.
pip install -r requirements_test.txt
|
Java
|
UTF-8
| 4,950 | 1.867188 | 2 |
[
"Apache-2.0",
"LicenseRef-scancode-gutenberg-2020",
"CC0-1.0",
"BSD-3-Clause"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.security.sandbox;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteAtomicLong;
import org.apache.ignite.IgniteAtomicReference;
import org.apache.ignite.IgniteAtomicSequence;
import org.apache.ignite.IgniteAtomicStamped;
import org.apache.ignite.IgniteBinary;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteCompute;
import org.apache.ignite.IgniteCountDownLatch;
import org.apache.ignite.IgniteDataStreamer;
import org.apache.ignite.IgniteLock;
import org.apache.ignite.IgniteQueue;
import org.apache.ignite.IgniteScheduler;
import org.apache.ignite.IgniteSemaphore;
import org.apache.ignite.IgniteSet;
import org.apache.ignite.IgniteTransactions;
import org.apache.ignite.binary.BinaryObject;
import org.apache.ignite.cache.affinity.Affinity;
import org.apache.ignite.cache.query.QueryCursor;
import org.apache.ignite.internal.GridKernalContext;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.processors.security.SecurityUtils;
import org.apache.ignite.internal.util.lang.GridIterator;
import org.apache.ignite.transactions.Transaction;
/** Create instace of Ignite component proxy to use inside the Ignite Sandbox. */
public final class SandboxIgniteComponentProxy {
/** The array of classes that should be proxied. */
private static final Class<?>[] PROXIED_CLASSES = new Class[] {
Ignite.class,
IgniteCache.class,
IgniteCompute.class,
ExecutorService.class,
IgniteTransactions.class,
IgniteDataStreamer.class,
IgniteAtomicSequence.class,
IgniteAtomicLong.class,
IgniteAtomicReference.class,
IgniteAtomicStamped.class,
IgniteCountDownLatch.class,
IgniteSemaphore.class,
IgniteLock.class,
IgniteQueue.class,
IgniteSet.class,
IgniteBinary.class,
Affinity.class,
QueryCursor.class,
GridIterator.class,
Transaction.class,
BinaryObject.class,
IgniteScheduler.class
};
/**
* @return The proxy of {@code ignite} to use inside the Ignite Sandbox.
*/
public static Ignite igniteProxy(Ignite ignite) {
return proxy(((IgniteEx)ignite).context(), Ignite.class, ignite);
}
/**
* @return The proxy of {@code instance} to use inside the Ignite Sandbox.
*/
private static <T> T proxy(GridKernalContext ctx, Class<?> cls, T instance) {
Objects.requireNonNull(cls, "Parameter 'cls' cannot be null.");
Objects.requireNonNull(instance, "Parameter 'instance' cannot be null.");
return SecurityUtils.doPrivileged(
() -> (T)Proxy.newProxyInstance(cls.getClassLoader(), new Class[] {cls},
new SandboxIgniteComponentProxyHandler(ctx, instance))
);
}
/** */
private static class SandboxIgniteComponentProxyHandler implements InvocationHandler {
/** */
private final Object original;
/** Context. */
private final GridKernalContext ctx;
/** */
public SandboxIgniteComponentProxyHandler(GridKernalContext ctx, Object original) {
this.ctx = ctx;
this.original = original;
}
/** {@inheritDoc} */
@Override public Object invoke(Object proxy, Method mtd, Object[] args) throws Throwable {
Object res = SecurityUtils.doPrivileged(() -> mtd.invoke(original, args));
if (res != null && SecurityUtils.isSystemType(ctx, res, true)) {
Class<?> cls = proxiedClass(res);
return cls != null ? proxy(ctx, cls, res) : res;
}
return res;
}
/** */
private Class<?> proxiedClass(Object obj) {
for (Class<?> cls : PROXIED_CLASSES) {
if (cls.isInstance(obj))
return cls;
}
return null;
}
}
}
|
PHP
|
UTF-8
| 382 | 3.484375 | 3 |
[] |
no_license
|
<?php
$jam = 10;
if($jam < "10") {
echo "Havve a good morning!";
} elseif ($jam < "20") {
echo "Have a good day!";
}else {
echo "Have a good night!";
}
echo"\n";
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color color is red";
break;
case "blue":
echo "Your favorite color color is blue";
break;
}
?>
|
Python
|
UTF-8
| 2,704 | 3.78125 | 4 |
[] |
no_license
|
# Scheme primitive procedures
cons = lambda x, y: lambda m: m(x, y)
car = lambda z: z(lambda p, q: p)
cdr = lambda z: z(lambda p, q: q)
cadr = lambda x: car(cdr(x))
caddr = lambda x: car(cdr(cdr(x)))
makeList = lambda *items: None if items == () else cons(items[0], makeList(*items[1:]))
appendList = lambda list1, list2: list2 if list1 == None else cons(car(list1), appendList(cdr(list1), list2))
def printList(items):
displayList = lambda items: '[' + displayItems(items) + ']'
displayItems = lambda items: displayItem(car(items)) if cdr(items) == None \
else displayItem(car(items)) + ', ' + displayItem(cdr(items)) if not callable(cdr(items)) \
else displayItem(car(items)) + ', ' + displayItems(cdr(items))
displayItem = lambda item: '[]' if item == None \
else str(item) if not callable(item) \
else displayList(item)
print(displayList(items))
# Representation of binary trees
def entry(tree):
return car(tree)
def leftBranch(tree):
return cadr(tree)
def rightBranch(tree):
return caddr(tree)
def makeTree(entry, left, right):
return makeList(entry, left, right)
# Tree to list
def treeToList1(tree):
if tree == None:
return None
else:
return appendList(treeToList1(leftBranch(tree)), cons(entry(tree), treeToList1(rightBranch(tree))))
def treeToList2(tree):
def copyToList(tree, resultList):
if tree == None:
return resultList
else:
return copyToList(leftBranch(tree), cons(entry(tree), copyToList(rightBranch(tree), resultList)))
return copyToList(tree, None)
printList(treeToList1(makeTree(7, makeTree(3, makeTree(1, None, None), makeTree(5, None, None)), makeTree(9, None, makeTree(11, None, None)))))
# [1, 3, 5, 7, 9, 11]
printList(treeToList1(makeTree(3, makeTree(1, None, None), makeTree(7, makeTree(5, None, None), makeTree(9, None, makeTree(11, None, None))))))
# [1, 3, 5, 7, 9, 11]
printList(treeToList1(makeTree(5, makeTree(3, makeTree(1, None, None), None), makeTree(9, makeTree(7, None, None), makeTree(11, None, None)))))
# [1, 3, 5, 7, 9, 11]
# Order of growth: O(nlogn)
printList(treeToList2(makeTree(7, makeTree(3, makeTree(1, None, None), makeTree(5, None, None)), makeTree(9, None, makeTree(11, None, None)))))
# [1, 3, 5, 7, 9, 11]
printList(treeToList2(makeTree(3, makeTree(1, None, None), makeTree(7, makeTree(5, None, None), makeTree(9, None, makeTree(11, None, None))))))
# [1, 3, 5, 7, 9, 11]
printList(treeToList2(makeTree(5, makeTree(3, makeTree(1, None, None), None), makeTree(9, makeTree(7, None, None), makeTree(11, None, None)))))
# [1, 3, 5, 7, 9, 11]
# Order of growth: O(n)
|
SQL
|
UTF-8
| 454 | 3.28125 | 3 |
[] |
no_license
|
SELECT * FROM KOPO_STUDENT_2018;
SELECT
TEAM_ID
, ROUND(AVG(SCORE_MATH),1)
FROM KOPO_STUDENT_2018
GROUP BY TEAM_ID;
SELECT
A.STUDENT_ID
,A.TEAM_ID
,A.SCORE_MATH
,B.AVG_MATH
FROM
KOPO_STUDENT_2018 A,
(SELECT
TEAM_ID
, ROUND(AVG(SCORE_MATH),1) AS AVG_MATH
FROM KOPO_STUDENT_2018
GROUP BY TEAM_ID) B
WHERE 1=1
AND A.TEAM_ID = B.TEAM_ID(+);
|
C++
|
UTF-8
| 1,025 | 2.546875 | 3 |
[] |
no_license
|
#include "flatfilesystemmodel.h"
#include <QDir>
#include <QHash>
#include <QDebug>
FlatFilesystemModel::FlatFilesystemModel(const QString& path, const QStringList& filters) : m_path(path)
{
QHash<int, QByteArray> names = roleNames();
names.insert(Qt::UserRole, "index");
names.insert(Qt::UserRole+1, "filePathRole");
names.insert(Qt::UserRole+2, "niceFileName");
setRoleNames(names);
QDir d(path);
m_files = d.entryList(filters, QDir::Files|QDir::NoDotAndDotDot);
}
int FlatFilesystemModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return m_files.count();
}
QVariant FlatFilesystemModel::data (const QModelIndex & index, int role) const
{
if (role == Qt::UserRole)
return index.row();
if (role == Qt::UserRole+1)
return m_path+QDir::separator()+m_files[index.row()];
if (role == Qt::UserRole+2) {
QString fileName = m_files[index.row()];
return fileName.remove(QRegExp("\\.(^\\.)*$"));
}
return QVariant();
}
|
C
|
UTF-8
| 4,959 | 3.0625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdint.h>
#include <malloc.h>
#include "../include/cbuffer.h"
#include "../include/cbuffertest.h"
static uint8_t test_count = 0;
static uint8_t init_test_count = 0;
static uint8_t add_test_count = 0;
static uint8_t remove_test_count = 0;
static uint8_t free_test_count = 0;
int main()
{
run_test_cbuffer();
}
void run_test_cbuffer()
{
print_mallinfo();
cbuffer buff1, buff2, buff3, buff4, buff5;
test_cbuffer_init(&buff1,(uint8_t)0);
test_cbuffer_init(&buff2,(uint8_t)1);
test_cbuffer_init(&buff3,(uint8_t)16);
test_cbuffer_init(&buff4,(uint8_t)255);
test_cbuffer_init(&buff5,(uint8_t)256);
test_cbuffer_add(&buff3, 8);
test_cbuffer_remove(&buff3, 12);
test_cbuffer_add(&buff3,0);
test_cbuffer_remove(&buff3,4);
test_cbuffer_add(&buff3,3);
test_cbuffer_remove(&buff3,0);
test_cbuffer_add(&buff3,14);
test_cbuffer_remove(&buff3,15);
print_mallinfo();
test_cbuffer_free(&buff1);
test_cbuffer_free(&buff2);
test_cbuffer_free(&buff3);
test_cbuffer_free(&buff4);
test_cbuffer_free(&buff5);
print_mallinfo();
uint8_t pass_sum = init_test_count + add_test_count + remove_test_count + free_test_count;
printf("CB UNIT TEST SUITE: (%d/%d) PASS\n",pass_sum,test_count);
}
void test_cbuffer_init(cbuffer* buff, uint8_t size)
{
test_count++;
cbuffer_init(buff, size);
if(!buff->start || !buff->end || !buff->head || !buff->tail)
{
printf("Error : buffer pointer null\n");
printf("CB UNIT TEST CBUFFER INITIALIZE (%d) : FAIL (%d/4)\n", test_count, init_test_count);
}
else if(buff->head!=buff->tail || buff->head!=buff->start || buff->start!=buff->tail)
{
printf("Error : buffer pointer initialization\n");
printf("CB UNIT TEST CBUFFER INITIALIZE (%d) : FAIL (%d/4)\n", test_count, init_test_count);
}
else if(buff->start > buff-> end)
{
printf("Error : buffer limits\n");
printf("CB UNIT TEST CBUFFER INITIALIZE (%d) : FAIL (%d/4)\n", test_count, init_test_count);
}
else if(buff->count != 0)
{
printf("Error : buffer fill status\n");
printf("CB UNIT TEST CBUFFER INITIALIZE (%d) : FAIL (%d/4)\n", test_count, init_test_count);
}
else if(buff->size < 1)
{
printf("Error : buffer size\n%d",buff->size);
printf("CB UNIT TEST CBUFFER INITIALIZE (%d) : FAIL (%d/4)\n", test_count, init_test_count);
}
else
{
init_test_count++;
printf("CB UNIT TEST CBUFFER INITIALIZE (%d) : PASS (%d/4)\n", test_count, init_test_count);
}
return;
}
void test_cbuffer_free(cbuffer* buff)
{
cbuffer_free(buff);
free_test_count++;
test_count++;
printf("CB UNIT TEST CBUFFER FREE (%d) : PASS (%d/5)\n", test_count, free_test_count);
}
void test_cbuffer_add(cbuffer* buff, uint8_t amt)
{
test_count++;
printf("add (%d) : ",amt);
for(uint8_t i = 97 ; i <= 97 + amt - 1; i++)
{
cbuffer_add(buff, &i);
printf("%c, ", i);
}
printf("\n");
print_buffer_struct(buff);
print_buffer_content(buff);
if(buff->count > buff->size || buff->count < 0)
{
printf("Error : access error\n");
printf("CB UNIT TEST CBUFFER ADD (%d) : FAIL (%d/4)\n", test_count, init_test_count);
}
add_test_count++;
printf("CB UNIT TEST CBUFFER ADD (%d) : PASS (%d/4)\n", test_count, add_test_count);
return;
}
void test_cbuffer_remove(cbuffer* buff, uint8_t amt)
{
test_count++;
uint8_t e = 0;
printf("remove (%d) : ",amt);
for(uint8_t i = 1; i <= amt; i++)
{
e = 0;
cbuffer_remove(buff, &e);
printf("%c, ", e);
}
printf("\n");
print_buffer_struct(buff);
print_buffer_content(buff);
if(buff->count > buff->size || buff->count < 0)
{
printf("Error : access error\n");
printf("CB UNIT TEST CBUFFER ADD (%d) : FAIL (%d/4)\n", test_count, init_test_count);
}
remove_test_count++;
printf("CB UNIT TEST CBUFFER REMOVE (%d) : PASS (%d/4)\n", test_count, remove_test_count);
return;
}
void print_buffer_struct(cbuffer* buff)
{
printf("start:%p ", buff->start);
printf("end:%p ", buff->end);
printf("head:%p ", buff->head);
printf("tail:%p ", buff->tail);
printf("size:%d ", buff->size);
printf("count:%d ", buff->count);
}
void print_buffer_content(cbuffer* buff)
{
printf("buff:");
for(int i = 0; buff->start + i <= buff->end; i++)
printf("%c",*(buff->start + i));
printf("\n");
}
void print_mallinfo()
{
struct mallinfo mallinf = mallinfo();
printf("arena :%d\n", mallinf.arena);
printf("ordblks :%d\n", mallinf.ordblks);
printf("smblks :%d\n", mallinf.smblks);
printf("hblks :%d\n", mallinf.hblks);
printf("hblkhd :%d\n", mallinf.hblkhd);
printf("usmblks :%d\n", mallinf.usmblks);
printf("fsmblks :%d\n", mallinf.fsmblks);
printf("uordblks:%d\n", mallinf.uordblks);
printf("fordblks:%d\n", mallinf.fordblks);
printf("keepcost:%d\n", mallinf.keepcost);
}
|
Markdown
|
UTF-8
| 3,442 | 3.203125 | 3 |
[] |
no_license
|
성별에 따른 월급 차이
================
정현진
July 30, 2020
## 2\. 성별에 따른 월급 차이
### 분석 절차
성별과 월급 두 변소를 검토 후 전처리, 변수간의 관계 분석(성별 월급 평균표 만들기&그래프 만들기)
### 성별 변수 검토 및 전처리
#### 1\. 변수 검토하기
시작점과 끝점에 \`\`\`입력하고 그 사이에 r코드 작성해주기
``` r
class(welfare$sex)
table(welfare$sex)
```
#### 2\. 전처리
성별 변수1= 남자 2=여자 9=모름/무응답(값이 9여도 성별을 알 수 없으니 결측값) 데이터에 이상치가 있는지 검토하고,
분석에서 이상치를 제외할 수 있도록 NA부여
``` r
#이상치 확인
table(welfare$sex)
table(is.na(welfare$sex))
```
이상치가 없기 때문에 이상치를 결측 처리하는 절차 스킵, 이상치가 발견되면 결측처리 해줘야함 sex변수의 값은 숫자 1 또는 2,
문자 “male”, “female”로 바꾸고, table(), qplot()이용해 바뀐 값이 반영됬는지 결과 확인
``` r
welfare$sex <- ifelse(welfare$sex == 1, "male", "female")
table(welfare$sex)
```
##
## female male
## 9086 7578
``` r
qplot(welfare$sex)
```
<!-- -->
### 월급 변수 검토 및 전처리
#### 1\. 변수 검토하기
월급=일한 달의 월 평균 임금, 1만원 단위 income 검토하고 qplot으로 분포 확인 월급 변수는 연속 변수라 table을
쓰면 항목이 많다 summary를 이용
``` r
#데이터 유형을 알고 싶을 때
class(welfare$income)
```
## [1] "numeric"
``` r
summary(welfare$income)
```
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## 0.0 122.0 192.5 241.6 316.6 2400.0 12030
``` r
qplot(welfare$income) + xlim(0, 1000)
```
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 12051 rows containing non-finite values (stat_bin).
## Warning: Removed 2 rows containing missing values (geom_bar).
<!-- -->
#### 2\. 전처리
월급은 1-9998 사이 값, 모름 또는 무응답은 0이나 9999 결측처리 필요 (직업이 없는 사람)
``` r
#이상치 확인
summary(welfare$income)
```
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## 0.0 122.0 192.5 241.6 316.6 2400.0 12030
``` r
#이상치 결측 처리
welfare$income <- ifelse(welfare$income %in% c(0,9999), NA, welfare$income)
table(is.na(welfare$income))
```
##
## FALSE TRUE
## 4620 12044
### 성별에 따른 월급 차이 분석하기
변수간 관계 분석
#### 1\. 성별 월급 평균표 만들기
``` r
sex_income <- welfare %>%
filter(!is.na(income)) %>%
group_by(sex) %>%
summarise(mean_income = mean(income))
```
## `summarise()` ungrouping output (override with `.groups` argument)
``` r
sex_income
```
## # A tibble: 2 x 2
## sex mean_income
## <chr> <dbl>
## 1 female 163.
## 2 male 312.
#### 2\. 그래프 만들기
``` r
ggplot(data = sex_income, aes(x = sex, y = mean_income)) + geom_col()
```
<!-- -->
|
Markdown
|
UTF-8
| 1,488 | 4.03125 | 4 |
[
"MIT"
] |
permissive
|
# 1449. Form Largest Integer With Digits That Add up to Target
Difficulty: Hard
https://leetcode.com/problems/form-largest-integer-with-digits-that-add-up-to-target/
Given an array of integers cost and an integer target. Return the maximum integer you can paint under the following rules:
* The cost of painting a digit (i+1) is given by cost[i] (0 indexed).
* The total cost used must be equal to target.
* Integer does not have digits 0.
Since the answer may be too large, return it as string.
If there is no way to paint any integer given the condition, return "0".
**Example 1:**
```
Input: cost = [4,3,2,5,6,7,2,5,5], target = 9
Output: "7772"
Explanation: The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost("7772") = 2*3+ 3*1 = 9. You could also paint "977", but "7772" is the largest number.
Digit cost
1 -> 4
2 -> 3
3 -> 2
4 -> 5
5 -> 6
6 -> 7
7 -> 2
8 -> 5
9 -> 5
```
**Example 2:**
```
Input: cost = [7,6,5,5,5,6,8,7,8], target = 12
Output: "85"
Explanation: The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost("85") = 7 + 5 = 12.
```
**Example 3:**
```
Input: cost = [2,4,6,2,4,6,4,4,4], target = 5
Output: "0"
Explanation: It's not possible to paint any integer with total cost equal to target.
```
**Example 4:**
```
Input: cost = [6,10,15,40,40,40,40,40,40], target = 47
Output: "32211"
```
**Constraints:**
* cost.length == 9
* 1 <= cost[i] <= 5000
* 1 <= target <= 5000
|
C++
|
UTF-8
| 1,297 | 2.78125 | 3 |
[
"NCSA"
] |
permissive
|
/* Create 1 buffer per tile and work on it with an accessor
RUN: %{execute}%s
*/
//#define TRISYCL_XILINX_AIE_TILE_CODE_ON_FIBER 1
#include <iostream>
#include <sycl/sycl.hpp>
using namespace sycl::vendor::xilinx;
int main() {
// Define an AIE CGRA with all the tiles of a VC1902
acap::aie::device<acap::aie::layout::vc1902> d;
// 1 buffer per tile
sycl::buffer<int> b[d.x_size][d.y_size];
// Initialize on the host each buffer with 3 sequential values
d.for_each_tile_index([&](int x, int y) {
b[x][y] = { 3 };
sycl::host_accessor a { b[x][y] };
std::iota(a.begin(), a.end(), (d.x_size * y + x) * a.get_count());
});
// Submit some work on each tile, which is SYCL sub-device
d.for_each_tile_index([&](int x, int y) {
d.tile(x, y).submit([&](auto& cgh) {
acap::aie::accessor a { b[x][y], cgh };
cgh.single_task([=] {
for (auto& e : a)
e += 42;
});
});
});
// Wait for the end of each tile execution
d.for_each_tile([](auto& t) { t.wait(); });
// Check the result
d.for_each_tile_index([&](int x, int y) {
for (sycl::host_accessor a { b[x][y] };
auto&& [i, e] : ranges::views::enumerate(a))
if (e != (d.x_size * y + x) * a.get_count() + i + 42)
throw "Bad computation";
});
}
|
C++
|
UTF-8
| 1,132 | 3.078125 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <math.h>
#include "gnuplot_i.hpp"
template<typename T>
T myFun(T x)
{
return sin(x);
}
template<typename T>
T derivativeCentralMeth(T x, T h)
{
return (myFun<T>(x+h) - myFun<T>(x-h))/(2.*h);
}
template<typename T>
T derivative(T x)
{
return cos(x);
}
template<typename T>
T getError(T argument, T h)
{
T der = derivative<T>(argument);
T derCentral = derivativeCentralMeth<T>(argument, h);
T err = der - derCentral;
if(err < 0.)
err*=-1.;
return err;
}
int main()
{
float argument = 2.*M_PI/3.;
//std::cout << der << " " << derCentral << std::endl;
std::vector<float> hValues;
std::vector<float> errValues;
for(float h = 1.e-8; h < 10; h*=10.)
{
hValues.push_back(h);
float error = getError(argument, h);
errValues.push_back(error);
// std::cout << h << " " << error << std::endl;
}
Gnuplot g1 ("lines");
g1.set_xlogscale();
g1.set_ylogscale();
g1.set_style ("points") .plot_xy (hValues, errValues, "Dane") ;
std::cin.ignore();
return 0;
}
|
JavaScript
|
UTF-8
| 307 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
(function(){
'use strict';
var through = require('through2');
var write = function(buffer,encoding,callback){
var info = buffer.toString().toLocaleUpperCase();
this.push(info);
callback();
};
var stream = through(write);
process.stdin.pipe(stream).pipe(process.stdout);
})();
|
C
|
UTF-8
| 935 | 2.703125 | 3 |
[] |
no_license
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
/* Variables and functions */
char* strchr (char const*,char) ;
__attribute__((used)) static int
getbits(const char *src, int *bitsp)
{
static const char digits[] = "0123456789";
int n;
int val;
char ch;
val = 0;
n = 0;
while ((ch = *src++) != '\0')
{
const char *pch;
pch = strchr(digits, ch);
if (pch != NULL)
{
if (n++ != 0 && val == 0) /* no leading zeros */
return 0;
val *= 10;
val += (pch - digits);
if (val > 128) /* range */
return 0;
continue;
}
return 0;
}
if (n == 0)
return 0;
*bitsp = val;
return 1;
}
|
C++
|
UTF-8
| 935 | 3 | 3 |
[
"Apache-2.0"
] |
permissive
|
class Solution {
private:
using citer = vector<int>::const_iterator;
int maxSubArrayDo(citer begin, citer end) {
if (begin + 1 == end) {
return *begin;
}
auto half = (end - begin)>>1;
int maxPre = maxSubArrayDo(begin, begin + half), maxPost = maxSubArrayDo(begin + half, end);
int pre = *(begin + half - 1), mpre = pre, post = *(begin + half), mpost = post;
for (auto i = begin + half - 2; i >= begin; --i) {
pre += *i;
mpre = pre > mpre ? pre : mpre;
}
for (auto i = begin + half + 1; i < end; ++i) {
post += *i;
mpost = post > mpost ? post : mpost;
}
int mid = mpre > 0 && mpost > 0 ? mpre + mpost : max(mpre, mpost);
return max(max(maxPre, maxPost), mid);
}
public:
int maxSubArray(vector<int>& nums) {
return maxSubArrayDo(nums.begin(), nums.end());
}
};
|
C#
|
UTF-8
| 550 | 3 | 3 |
[] |
no_license
|
using System;
namespace Demo_Project1.Variables_Examples
{
public class Var_Ex2
{
static void Mains(string[] args)
{
var Name = "Girish";
var _Intail = 'M';
var age = 30;
var salary = 50400.36;
Console.WriteLine(" Emp_Name : " + Name + " " + _Intail);
Console.WriteLine(" Emp_Name Data Type: " + Name.GetType());
Console.WriteLine(" Emp_Age : " + age);
Console.WriteLine(" Emp_salary : " + salary);
}
}
}
|
Python
|
UTF-8
| 335 | 2.96875 | 3 |
[] |
no_license
|
from linked_list import LinkedListNode, LinkedList, makeN
list = makeN(15)
list.print_all()
# one = LinkedListNode(1)
# cycle = LinkedList(LinkedListNode(0))
# cycle.add(one)
# for n in range(2, 11):
# cycle.add(LinkedListNode(n))
# cycle.print_all()
# cycle.remove(4)
# cycle.print_all()
# cycle.remove(0)
# cycle.print_all()
|
JavaScript
|
UTF-8
| 456 | 2.875 | 3 |
[] |
no_license
|
var fiveMinutes = 5 * 60 * 1000;
module.exports = function(){
memwatch();
setInterval(memwatch, fiveMinutes);
};
function memwatch(){
var memory = process.memoryUsage();
var rss = Math.round(memory.rss / 1024 / 1024);
var used = Math.round(memory.heapUsed / 1024 / 1024);
var total = Math.round(memory.heapTotal / 1024 / 1024);
console.log('Resident set size: ' + rss + ' MB - V8 Heap: ' + used + ' MB / ' + total + ' MB');
}
|
Java
|
UTF-8
| 7,674 | 2.015625 | 2 |
[] |
no_license
|
package com.example.dheoclaveria.projectos;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
import static com.example.dheoclaveria.projectos.Resource.subcolor;
import static com.example.dheoclaveria.projectos.Resource.subimage;
/**
* Created by Dheo Claveria on 10/1/2017.
*/
public class Custom_GridView_Iconselection extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<GridView_Iconselection_Data> lstdata;
Resource res = new Resource();
GridView_Iconselection_Data gsd;
ImageView image;
TextView title;
LinearLayout panel;
public static boolean isselectionmode = false;
public Custom_GridView_Iconselection(Activity a, List<GridView_Iconselection_Data> e) {
this.activity = a;
this.lstdata = e;
}
@Override
public int getCount() {
return lstdata.size();
}
@Override
public Object getItem(int pos) {
return lstdata.get(pos);
}
@Override
public long getItemId(int pos) {
return pos;
}
@Override
public View getView(int pos, View view, ViewGroup vgroup ) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null) {
// if(isselectionmode == true){view = inflater.inflate(R.layout.grid_item_selection, null);}
// else{view = inflater.inflate(R.layout.grid_item, null);}
view = inflater.inflate(R.layout.grid_item_selection, null);
}
//
// if(isselectionmode == true)
// {
// image = view.findViewById(R.id.grid_item_selection_image);
// title = view.findViewById(R.id.grid_item_selection_title);
// panel = view.findViewById(R.id.grid_item_selection_panel);
// }
// else {
image = view.findViewById(R.id.grid_item_selection_image);
title = view.findViewById(R.id.grid_item_selection_title);
panel = view.findViewById(R.id.grid_item_selection_panel);
// }
try {
gsd = lstdata.get(pos);
Uri sube = forimagechoice(gsd.getImage());
Drawable subp = forcolorchoice(gsd.getColor());
image.setImageURI(sube);
panel.setBackgroundDrawable(subp);
title.setText(gsd.getTitle());
}catch(Exception ex){}
return view;
}
public Uri forimagechoice(String imagename) {
try {
switch (imagename) {
case "book":
subimage = Uri.parse("android.resource://com.example.dheoclaveria.projectos/" + R.drawable.book);
break;
case "bookmark":
subimage = Uri.parse("android.resource://com.example.dheoclaveria.projectos/" + R.drawable.bookmark);
break;
case "bookopen":
subimage = Uri.parse("android.resource://com.example.dheoclaveria.projectos/" + R.drawable.bookopen);
break;
case "books":
subimage = Uri.parse("android.resource://com.example.dheoclaveria.projectos/" + R.drawable.books);
break;
case "compass":
subimage = Uri.parse("android.resource://com.example.dheoclaveria.projectos/" + R.drawable.compass);
break;
case "diploma":
subimage = Uri.parse("android.resource://com.example.dheoclaveria.projectos/" + R.drawable.diploma);
break;
case "erase":
subimage = Uri.parse("android.resource://com.example.dheoclaveria.projectos/" + R.drawable.erase);
break;
case "formula":
subimage = Uri.parse("android.resource://com.example.dheoclaveria.projectos/" + R.drawable.formula);
break;
case "notepad":
subimage = Uri.parse("android.resource://com.example.dheoclaveria.projectos/" + R.drawable.notepad);
break;
case "pipette":
subimage = Uri.parse("android.resource://com.example.dheoclaveria.projectos/" + R.drawable.pipette);
break;
case "projection":
subimage = Uri.parse("android.resource://com.example.dheoclaveria.projectos/" + R.drawable.projection);
break;
case "quill":
subimage = Uri.parse("android.resource://com.example.dheoclaveria.projectos/" + R.drawable.quill);
break;
case "studenthat":
subimage = Uri.parse("android.resource://com.example.dheoclaveria.projectos/" + R.drawable.studenthat);
break;
case "transparent":
subimage = Uri.parse("android.resource://com.example.dheoclaveria.projectos/" + R.drawable.transparent);
break;
default:
subimage = Uri.parse("android.resource://com.example.dheoclaveria.projectos/" + R.drawable.book);
}
} catch (Exception ex) {}
return subimage;
}
public ColorDrawable forcolorchoice(String color) {
switch (color) {
case "dark":
subcolor = new ColorDrawable(Color.parseColor("#242424"));
break;
case "red":
subcolor = new ColorDrawable(Color.parseColor("#f6402b"));
break;
case "darkpink":
subcolor = new ColorDrawable(Color.parseColor("#eb1461"));
break;
case "violet":
subcolor = new ColorDrawable(Color.parseColor("#9c1ab2"));
break;
case "blue":
subcolor = new ColorDrawable(Color.parseColor("#1193f5"));
break;
case "lightblue":
subcolor = new ColorDrawable(Color.parseColor("#00bbd6"));
break;
case "bluegreen":
subcolor = new ColorDrawable(Color.parseColor("#009788"));
break;
case "green":
subcolor = new ColorDrawable(Color.parseColor("#01b876"));
break;
case "yellow":
subcolor = new ColorDrawable(Color.parseColor("#ffec16"));
break;
case "orange":
subcolor = new ColorDrawable(Color.parseColor("#ff9801"));
break;
case "darkorange":
subcolor = new ColorDrawable(Color.parseColor("#ff5505"));
break;
case "darkbrown":
subcolor = new ColorDrawable(Color.parseColor("#7a5447"));
break;
case "silver":
subcolor = new ColorDrawable(Color.parseColor("#9d9d9d"));
break;
case "gray":
subcolor = new ColorDrawable(Color.parseColor("#5f7c8c"));
break;
default:
subcolor = new ColorDrawable(Color.parseColor("#5f7c8c"));
}
return subcolor;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.