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
| 261 | 1.640625 | 2 |
[] |
no_license
|
package com.blabz.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.blabz.model.LMSModel;
@Repository
public interface LMSRepo extends JpaRepository<LMSModel, Integer> {
}
|
Java
|
UTF-8
| 1,881 | 2.484375 | 2 |
[] |
no_license
|
package br.com.drogaria.teste;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
import br.com.drogaria.dao.FuncionarioDAO;
import br.com.drogaria.dao.VendaDAO;
import br.com.drogaria.domain.Funcionario;
import br.com.drogaria.domain.Venda;
public class VendaDAOTest {
@Test
@Ignore
public void salvar() {
FuncionarioDAO funcionarioDAO = new FuncionarioDAO();
Funcionario funcionario = funcionarioDAO.buscarPorCodigo(2L);
Venda venda = new Venda();
venda.setFuncionario(funcionario);
venda.setHorario(new Date());
venda.setValor(new BigDecimal(19.99D));
VendaDAO vendaDAO = new VendaDAO();
vendaDAO.salvar(venda);
}
@Test
@Ignore
public void buscarPorCodigo() {
VendaDAO vendaDAO = new VendaDAO();
Venda venda = vendaDAO.buscarPorCodigo(1L);
System.out.println(venda);
}
@Test
@Ignore
public void listar() {
VendaDAO vendaDAO = new VendaDAO();
List<Venda> vendas = vendaDAO.listar();
for(Venda venda: vendas) {
System.out.println(venda);
}
}
@Test
@Ignore
public void editar() {
FuncionarioDAO funcionarioDAO = new FuncionarioDAO();
Funcionario funcionario = funcionarioDAO.buscarPorCodigo(1L);
Venda venda = new Venda();
venda.setCodigo(3L);
venda.setFuncionario(funcionario);
venda.setHorario(new Date());
venda.setValor(new BigDecimal(2.99D));
VendaDAO vendaDAO = new VendaDAO();
vendaDAO.editar(venda);
}
@Test
@Ignore
public void excluir() {
FuncionarioDAO funcionarioDAO = new FuncionarioDAO();
Funcionario funcionario = funcionarioDAO.buscarPorCodigo(2L);
Venda venda = new Venda();
venda.setCodigo(5L);
venda.setFuncionario(funcionario);
venda.setHorario(new Date());
venda.setValor(new BigDecimal(19.98D));
VendaDAO vendaDAO = new VendaDAO();
vendaDAO.excluir(venda);
}
}
|
C++
|
UTF-8
| 997 | 3.796875 | 4 |
[] |
no_license
|
/*
Programmer: Oberon Ilano
Assignment: 7
Description: Program to compute the other side of the triangle.
Date: June 11, 2018
Course: CS155 - Computer Science I
*/
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
// Initiate Variables
double side1=0.0, side2=0.0, hypotenuse=0.0;
cout << "This program compute the second side of a triangle" << endl;
// Have user input of the first side and the hypotenuse of a triangle
// assuming the unit measure is in feet
cout << "Enter the hypotenuse of a triangle in feet: ";
cin >> hypotenuse;
cout << "Enter the first side of a triangle in feet: ";
cin >> side1;
if ((side1 <= 0) || (side2 <=0) || (hypotenuse <= side2))
cout << "Invalid data." << endl;
else
{
// Perform a calculation
side2 = sqrt(pow(hypotenuse, 2) + pow(side1, 2));
cout << "The length of the second side of a triangle is: " << setprecision(2)
<< fixed << side2 << " ft." << endl;
}
return 0;
}
|
Markdown
|
UTF-8
| 3,519 | 3.15625 | 3 |
[] |
no_license
|
### Table of Contents
[Home](README.md)
[Reading Day 2](day2.md)
[Read04](read04.md)
[Read05](read05.md)
[Read06a](read06a.md)
[Read06b](read06b.md)
[Read07](read07.md)
[Read08](read08.md)
# Reading Notes Day 1
#### Choosing a Text Editor
- We'll be writing a lot of code, a good text editor will be invaluable
- Text editor is entirely a personal choice, they're all pretty similar
- As long as the text editor you choose can complete a website to your liking
- **What is a text editor?**
- A piece of software that lives online, allowing you to write and edit text and build a website
- Super important for people learning to create websites
- Some important features:
- Code completion
- Like predictive text and autocorrect on your phone, but with code
- Syntax highlighting
- Important elements are color-coded to make writing code simpler
- Makes code easier to read, and helps you find what you're looking for
- Variety of themes
- Some themes (darker ones especially) can reduce eye strain
- Extension choice
- Adds functionality as you learn more coding techniques
- Always code in **plain text**. Your text editor shouldn't allow you to change font sizes, add italics, etc.
- Use proper file extension names
- .html for HTML files
- .css for CSS files
- **Third party text editors**
- Notepad++
- Windows only
- Free
- TextWrangler/BB Edit
- Mac only
- TextWrangler is defunct, BB Edit costs money ($50)
- Visual Studio Code
- Windows, Mac, and Linux compatible
- Free
- Atom
- Windows, Mac, and Linux compatible
- Free
- Created by GitHub
- Brackets
- Windows, Mac, and Linux compatible
- Free
- Created by Adobe
- Sublime Text
- $70 for full version
- Integrated Development Environment (IDE)
- Combines features like these:
- Text editing
- File Management
- Compiling
- Debugging
- Microsoft Outlook is a good example
# Cheat Sheet for Terminal Use
- `pwd` shows you your current directory
- `ls` shows you what files are in your current directory
- `ls [options] [location]` is how it is usually formatted
- `ls -l` shows a long listing
- `ls /etc` shows directory's *contents*
- `ls -l /etc` shows both a command line option and argument
- `~` is a shortcut to your home directory
- `.` references your current directory
- `..` references parent directory
- `cd [location]` changes your directory
- `file [path]` shows what type of file something is
- `ls -a` shows hidden files
# Other Notes
#### The Command Line
- A command is usually the first thing you type
- `echo` displays a system variable
- You can navigate and edit previous commands using the arrow keys
#### Basic Navigation
Paths
- A path is a means to get to a particular file or directory on the system
- Absolute paths
- Show location in relation to root directory
- Start with a forward slash (/)
- Relative
- Specify a location relative to where you are in the system
- Do not begin with a slash
- Tab completion is a form of autocorrect. Can be invoked by pressing **tab**
#### About Files
- A computer sees **everything** as a file
- Case sensitivity **matters**
- If moving a file into a folder that contains a space (e.g., "Honeymoon Pics"), make sure to put that directory in single quotes
- Otherwise the space is seen as a separate command
- An "escape character" (\) works as well
- This would appear as "Honeymoon\ Pics"
- Tab completion does this for you!
|
PHP
|
UTF-8
| 131 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Core\Pattern\Singleton;
class Singleton
{
public function say()
{
var_dump('hello');
}
}
|
Markdown
|
UTF-8
| 931 | 3.765625 | 4 |
[
"BSD-3-Clause",
"CC-BY-SA-4.0",
"CC-BY-4.0"
] |
permissive
|
---
title: Access Multi-Dimensional Arrays With Indexes
localeTitle: Acessar matrizes multi-dimensionais com índices
---
## Acessar matrizes multi-dimensionais com índices
Considere o seguinte array multidimensional:
```javascript
var arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]];
```
Isto é o que parece em forma de tabela.
| Posição | 0 | 1 | 2 | 3 | | --- | --- | --- | --- | --- | | **0** | 1 | 4 | 7 | 10 | | **1** | 2 | 5 | 8 | 11 | | **2** | 3 | 6 | 9 | 12 |
Agora tudo que você precisa fazer é escolher as coordenadas dos dados que você deseja! Por exemplo, se queremos que `myNum` seja igual a 8, então ...
```javascript
var myNum = arr[2][1]; // Equal to 8
```
Ou, se você quer que seja igual a 1. Você faz…
```javascript
var myNum = arr[0][0]; // Equal to 1
```
Primeiro você começa escolhendo em qual coluna o número está, depois escolhe a linha. É como o plano de coordenadas xy!
|
JavaScript
|
UTF-8
| 3,554 | 3.171875 | 3 |
[] |
no_license
|
"use strict";
// ---- canvas ----
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
const dpr = window.devicePixelRatio || 1;
canvas.width = canvas.offsetWidth * dpr;
canvas.height = canvas.offsetHeight * dpr;
// ---- source image ----
let img = {
standardDeviationThreshold: 6,
minSize: 3,
img: new Image(),
data: null,
w: 0,
h: 0,
rx: 0,
ry: 0,
deconstruct() {
this.w = this.img.width;
this.h = this.img.height;
const cmap = document.createElement("canvas");
cmap.width = this.w;
cmap.height = this.h;
const ct = cmap.getContext("2d");
ct.drawImage(this.img, 0, 0);
this.data = ct.getImageData(0, 0, this.w, this.h).data;
// ---- calc brillance ----
for (let i = 0; i < this.w * this.h * 4; i += 4) {
this.data[i + 3] =
0.34 * this.data[i] + 0.5 * this.data[i + 1] + 0.16 * this.data[i + 2];
}
this.rx = canvas.width / this.w;
this.ry = canvas.height / this.h;
},
load(id) {
return new Promise((resolve) => {
this.img.addEventListener("load", (_) => resolve());
this.img.src = document.getElementById(id).src;
});
},
// ---- create new Rectangle ----
Rect(sdt, i, x, y, w, h) {
const x0 = Math.floor(x);
const y0 = Math.floor(y);
const w0 = Math.ceil(w);
const h0 = Math.ceil(h);
const n = w0 * h0;
// ---- average colors ----
let r = 0, g = 0, b = 0, l = 0;
for (let xi = x0; xi < x0 + w0; xi++) {
for (let yi = y0; yi < y0 + h0; yi++) {
const p = (yi * this.w + xi) * 4;
r += this.data[p + 0];
g += this.data[p + 1];
b += this.data[p + 2];
l += this.data[p + 3];
}
}
r = (r / n) | 0;
g = (g / n) | 0;
b = (b / n) | 0;
l = (l / n) | 0;
// ---- standard deviation ----
let sd = 0;
for (let xi = x0; xi < x0 + w0; xi++) {
for (let yi = y0; yi < y0 + h0; yi++) {
const bri = this.data[(yi * this.w + xi) * 4 + 3] - l;
sd += bri * bri;
}
}
if ((w > this.minSize || h > this.minSize) && Math.sqrt(sd / n) > sdt) {
// ---- recursive division ----
this.Rect(sdt, i * 2, x, y, w * 0.5, h * 0.5);
this.Rect(sdt, i * 2, x + w * 0.5, y, w * 0.5, h * 0.5);
this.Rect(sdt, i * 2, x, y + h * 0.5, w * 0.5, h * 0.5);
this.Rect(sdt, i * 2, x + w * 0.5, y + h * 0.5, w * 0.5, h * 0.5);
} else {
// ---- draw final rectangle ----
if (w > 5) {
// rectangle
ctx.fillStyle = `rgb(${r},${g},${b})`;
ctx.fillRect(x * this.rx, y * this.ry, w * this.rx - 0.5, h * this.ry - 0.5);
// circle
ctx.beginPath();
ctx.fillStyle = `rgb(${(r * 1.1) | 0},${(g * 1.1) | 0},${(b * 1.1) | 0})`;
ctx.arc((x + w / 2) * this.rx, (y + h / 2) * this.ry, (w / 2.2) * this.rx, 0, 2 * Math.PI);
ctx.fill();
// text
ctx.fillStyle = "#333";
ctx.fillText(i, x * this.rx + 2, y * this.ry + 10, w);
} else {
// rectangle only
ctx.fillStyle = `rgb(${r},${g},${b})`;
ctx.fillRect(x * this.rx, y * this.ry, w * this.rx - 0.5, h * this.ry - 0.5);
}
}
}
};
// ---- promise raf ----
const requestAnimationFrame = () => {
return new Promise((resolve) => window.requestAnimationFrame(resolve));
};
// ---- animation loop ----
async function run() {
for (let sdt = 80; sdt >= img.standardDeviationThreshold; sdt--) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// ---- create the first rectangle ----
img.Rect(sdt, 1, 0, 0, img.w, img.h);
// ---- wait next frame ----
await requestAnimationFrame();
}
};
// ---- load image and run ----
img.load("source").then(() => {
img.deconstruct();
run();
});
|
Markdown
|
UTF-8
| 14,744 | 3 | 3 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
---
title: Import pre-annotated data into Label Studio
short: Import pre-annotations
type: guide
order: 301
meta_title: Import pre-annotated data into Label Studio
meta_description: Import predicted labels, predictions, pre-annotations, or pre-labels into Label Studio for your data labeling, machine learning, and data science projects.
---
If you have predictions generated for your dataset from a model, either as pre-annotated tasks or pre-labeled tasks, you can import the predictions with your dataset into Label Studio for review and correction. Label Studio automatically displays the pre-annotations that you import on the Labeling page for each task.
To import predicted labels into Label Studio, you must use the [Basic Label Studio JSON format](tasks.html#Basic-Label-Studio-JSON-format) and set up your tasks with the `predictions` JSON key. The Label Studio ML backend also outputs tasks in this format.
For image pre-annotations, Label Studio expects the x, y, width, and height of image annotations to be provided in percentages of overall image dimension. See [Units for image annotations](predictions.html#Units_for_image_annotations) on this page for more about how to convert formats.
Import pre-annotated tasks into Label Studio [using the UI](tasks.html#Import-data-from-the-Label-Studio-UI) or [using the API](/api#operation/projects_import_create).
## Import pre-annotations for images
For example, import predicted labels for tasks to determine whether an item in an image is an airplane or a car.
Use the following labeling configuration:
```xml
<View>
<Choices name="choice" toName="image" showInLine="true">
<Choice value="Boeing" background="blue"/>
<Choice value="Airbus" background="green" />
</Choices>
<RectangleLabels name="label" toName="image">
<Label value="Airplane" background="green"/>
<Label value="Car" background="blue"/>
</RectangleLabels>
<Image name="image" value="$image"/>
</View>
```
After you set up an example project, create example tasks that match the following format.
<br/>
{% details <b>Click to expand the example image JSON</b> %}
Save this example JSON as a file to import it into Label Studio, for example, `example_prediction_task.json`.
{% codeblock lang:json %}
[{
"data": {
"image": "http://localhost:8080/static/samples/sample.jpg"
},
"predictions": [{
"result": [
{
"id": "result1",
"type": "rectanglelabels",
"from_name": "label", "to_name": "image",
"original_width": 600, "original_height": 403,
"image_rotation": 0,
"value": {
"rotation": 0,
"x": 4.98, "y": 12.82,
"width": 32.52, "height": 44.91,
"rectanglelabels": ["Airplane"]
}
},
{
"id": "result2",
"type": "rectanglelabels",
"from_name": "label", "to_name": "image",
"original_width": 600, "original_height": 403,
"image_rotation": 0,
"value": {
"rotation": 0,
"x": 75.47, "y": 82.33,
"width": 5.74, "height": 7.40,
"rectanglelabels": ["Car"]
}
},
{
"id": "result3",
"type": "choices",
"from_name": "choice", "to_name": "image",
"value": {
"choices": ["Airbus"]
}
}],
"score": 0.95
}]
}]
{% endcodeblock %}
In this example there are 3 results inside 1 prediction, or pre-annotation:
- `result1` - the first bounding box
- `result2` - the second bounding box
- `result3` - choice selection
The prediction score applies to the entire prediction.
{% enddetails %}
<br/>
Import pre-annotated tasks into Label Studio [using the UI](tasks.html#Import-data-from-the-Label-Studio-UI) or [using the API](/api#operation/projects_import_create).
In the Label Studio UI, the imported prediction for this task looks like the following:
<center><img src="../images/predictions_loaded.png" alt="screenshot of the Label Studio UI showing an image of airplanes with bounding boxes covering each airplane." style="width: 100%; max-width: 700px"></center>
<!-- md image_units.md -->
## Import pre-annotations for text
In this example, import pre-annotations for text using the [named entity recognition template](/templates/named_entity.html):
```xml
<View>
<Labels name="label" toName="text">
<Label value="Person"></Label>
<Label value="Organization"></Label>
<Label value="Fact"></Label>
<Label value="Money"></Label>
<Label value="Date"></Label>
<Label value="Time"></Label>
<Label value="Ordinal"></Label>
<Label value="Percent"></Label>
<Label value="Product"></Label>
<Label value="Language"></Label>
<Label value="Location"></Label>
</Labels>
<Text name="text" value="$text"></Text>
</View>
```
### Example JSON
This example JSON file contains two tasks, each with two sets of pre-annotations from different models. The first task also contains prediction scores for each NER span.
<br/>
{% details <b>Click to expand the example NER JSON</b> %}
Save this example JSON as a file, for example: `example_preannotated_ner_tasks.json`.
{% codeblock lang:json %}
[
{
"data": {
"text": "All that changed when he was 27 and he came to Jerusalem. It was the weekend of both Easter and Passover, and the city was flooded with tourists."
},
"predictions": [
{
"model_version": "one",
"result": [
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 29,
"end": 31,
"score": 0.70,
"text": "27",
"labels": [
"Date"
]
}
},
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 47,
"end": 56,
"score": 0.65,
"text": "Jerusalem",
"labels": [
"Location"
]
}
},
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 65,
"end": 76,
"score": 0.95,
"text": "the weekend",
"labels": [
"Date"
]
}
},
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 85,
"end": 91,
"score": 0.50,
"text": "Easter",
"labels": [
"Date"
]
}
}
]
},
{
"model_version": "two",
"result": [
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 29,
"end": 31,
"score": 0.55,
"text": "27",
"labels": [
"Date"
]
}
},
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 47,
"end": 56,
"score": 0.40,
"text": "Jerusalem",
"labels": [
"Location"
]
}
},
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 65,
"end": 76,
"score": 0.32,
"text": "the weekend",
"labels": [
"Time"
]
}
},
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 85,
"end": 91,
"score": 0.22,
"text": "Easter",
"labels": [
"Location"
]
}
},
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 96,
"end": 104,
"score": 0.96,
"text": "Passover",
"labels": [
"Date"
]
}
}
]
}
]
},
{
"data": {
"text": " Each journal was several inches thick and bound in leather. On one page are drawn portraits of Sunny in a flowery, Easter dress and sun hat. On another page are hundreds of sketches of leaves that Niyati saw in her yard."
},
"predictions": [
{
"model_version": "one",
"result": [
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 17,
"end": 31,
"text": "several inches",
"labels": [
"Product"
]
}
},
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 63,
"end": 66,
"text": "one",
"labels": [
"Percent"
]
}
},
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 95,
"end": 100,
"text": "Sunny",
"labels": [
"Person"
]
}
},
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 161,
"end": 169,
"text": "hundreds",
"labels": [
"Percent"
]
}
},
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 197,
"end": 203,
"text": "Niyati",
"labels": [
"Person"
]
}
}
]
},
{
"model_version": "two",
"result": [
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 17,
"end": 31,
"text": "several inches",
"labels": [
"Fact"
]
}
},
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 63,
"end": 66,
"text": "one",
"labels": [
"Percent"
]
}
},
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 95,
"end": 100,
"text": "Sunny",
"labels": [
"Time"
]
}
},
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 115,
"end": 121,
"text": "Easter",
"labels": [
"Location"
]
}
},
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 161,
"end": 169,
"text": "hundreds",
"labels": [
"Money"
]
}
},
{
"from_name": "label",
"to_name": "text",
"type": "labels",
"value": {
"start": 197,
"end": 203,
"text": "Niyati",
"labels": [
"Person"
]
}
}
]
}
]
}
]
{% endcodeblock %}
{% enddetails %}
Import pre-annotated tasks into Label Studio [using the UI](tasks.html#Import-data-from-the-Label-Studio-UI) or [using the API](/api#operation/projects_import_create).
In the Label Studio UI, the imported prediction for the first task looks like the following:
<center><img src="../images/predictions_loaded_text.png" alt="screenshot of the Label Studio UI showing the text with highlighted text labels and prediction scores visible." style="width: 100%; max-width: 700px"></center>
You can sort the prediction scores for each labeled region using the **Regions** pane options.
## Troubleshoot pre-annotations
If you encounter unexpected behavior after you import pre-annotations into Label Studio, review this guidance to resolve the issues.
### Check the configuration values of your labeling configuration and tasks
The `from_name` of the pre-annotation task JSON must match the value of the name in the `<Labels name="label" toName="text">` portion of the labeling configuration. The `to_name` must match the `toName` value.
In the text example on this page, the JSON includes `"from_name": "label"` to correspond with the `<Labels name="label"` and `"to_name": text` to correspond with the `toName="text` of the labeling configuration. The default template might contain `<Labels name="ner" toName="text">`. To work with this example JSON, you need to update the values to match.
In the image example on this page, the XML includes
```xml
...
<Choices name="choice" toName="image" showInLine="true">`
...
<RectangleLabels name="label" toName="image">
...
```
To correspond with the following portions of the example JSON:
```json
...
"type": "rectanglelabels",
"from_name": "label", "to_name": "image",
...
type": "choices",
"from_name": "choice", "to_name": "image",
...
```
### Check the labels in your configuration and your tasks
Make sure that you have a labeling configuration set up for the labeling interface, and that the labels in your JSON file exactly match the labels in your configuration. If you're using a [tool to transform your model output](https://github.com/heartexlabs/label-studio-transformers), make sure that the labels aren't altered by the tool.
|
Python
|
UTF-8
| 11,455 | 2.53125 | 3 |
[] |
no_license
|
"""Extra admin commands to manage the DomiNode database server
This script adds some functions to perform DomiNode related tasks in a more
expedite manner than using the bare `psql` client
ricardosilva
lsduser1
ppduser1
INSERT INTO lsd_topomaps.qgis_projects
SELECT * FROM lsd_staging.qgis_projects WHERE name = 'this'
"""
import typing
from contextlib import contextmanager
from pathlib import Path
from time import sleep
import sqlalchemy as sla
import typer
from sqlalchemy.exc import OperationalError
from sqlalchemy.sql import text
from sqlalchemy.engine import Connection
from .constants import UserRole
from . import utils
_help_intro = 'Manage postgis database'
app = typer.Typer(
short_help=_help_intro,
help=_help_intro
)
APP_ROOT = Path(__file__).resolve().parents[1]
config = utils.load_config()
LSD_TOPOMAP_EDITOR_ROLE_NAME = f'lsd_topomap_editor'
@app.command()
def bootstrap(
db_admin_username: typing.Optional[str] = config['db']['admin_username'],
db_admin_password: typing.Optional[str] = config['db']['admin_password'],
db_name: typing.Optional[str] = config['db']['name'],
db_host: str = config['db']['host'],
db_port: int = config['db']['port'],
):
"""Perform initial bootstrap of the database
This function will take care of creating the relevant schemas, group roles
and access controls for using the postgis database for DomiNode.
"""
db_url = get_db_url(
db_admin_username, db_admin_password, db_host, db_port, db_name)
dominode_staging_schema_name = 'dominode_staging'
with get_db_connection(db_url) as db_connection:
typer.echo('Creating general roles...')
create_role(
'admin', db_connection, other_options=('CREATEDB', 'CREATEROLE'))
create_role(
'replicator', db_connection, other_options=('REPLICATION',))
create_role(config['dominode']['generic_user_name'], db_connection)
create_role(
config['dominode']['generic_editor_role_name'],
db_connection,
other_options=('IN ROLE dominode_user', )
)
typer.echo(f'creating {dominode_staging_schema_name!r} schema...')
create_schema(
dominode_staging_schema_name,
config['dominode']['generic_editor_role_name'],
db_connection
)
typer.echo(
f'Granting permissions on {dominode_staging_schema_name!r} '
f'schema...'
)
grant_schema_permissions(
dominode_staging_schema_name,
('USAGE', 'CREATE'),
config['dominode']['generic_user_name'], db_connection
)
typer.echo(f'Creating qgis_projects table...')
create_qgis_projects_table(
db_connection,
dominode_staging_schema_name,
config['dominode']['generic_user_name']
)
for department in utils.get_departments(config):
typer.echo(f'Bootstrapping {department} department...')
bootstrap_department(
db_connection,
department,
config['dominode']['generic_user_name']
)
typer.echo(f'Modifying access permissions on public schema...')
db_connection.execute(
text('REVOKE CREATE ON SCHEMA public FROM public'))
db_connection.execute(
text(
f'GRANT CREATE ON SCHEMA public TO '
f'{config["dominode"]["generic_editor_role_name"]}'
),
)
typer.echo(f'Executing remaining SQL commands...')
raw_connection = db_connection.connection
raw_cursor = raw_connection.cursor()
bootstrap_sql_path = APP_ROOT / 'sql/finalize-bootstrap-db.sql'
raw_cursor.execute(bootstrap_sql_path.read_text())
raw_connection.commit()
@app.command()
def add_department(
department: str,
db_admin_username: typing.Optional[str] = config['db']['admin_username'],
db_admin_password: typing.Optional[str] = config['db']['admin_password'],
db_name: typing.Optional[str] = config['db']['name'],
db_host: str = config['db']['host'],
db_port: int = config['db']['port'],
):
db_url = get_db_url(
db_admin_username, db_admin_password, db_host, db_port, db_name)
with get_db_connection(db_url) as db_connection:
bootstrap_department(
db_connection,
department,
config['dominode']['generic_user_name']
)
@app.command()
def add_department_user(
username: str,
password: str,
departments: typing.List[str],
role: typing.Optional[UserRole] = UserRole.REGULAR_DEPARTMENT_USER,
is_topomap_editor: typing.Optional[bool] = False,
db_admin_username: typing.Optional[str] = config['db']['admin_username'],
db_admin_password: typing.Optional[str] = config['db']['admin_password'],
db_host: typing.Optional[str] = config['db']['host'],
db_port: typing.Optional[int] = config['db']['port'],
db_name: typing.Optional[str] = config['db']['name'],
):
db_url = get_db_url(
db_admin_username, db_admin_password, db_host, db_port, db_name)
role_suffix = 'editor' if role == UserRole.EDITOR else 'user'
parent_roles = [f'{dep}_{role_suffix}' for dep in departments]
if is_topomap_editor:
parent_roles.append(LSD_TOPOMAP_EDITOR_ROLE_NAME)
typer.echo(
f'Adding {username!r} user with parent roles {parent_roles!r}...')
with get_db_connection(db_url) as db_connection:
create_user(
username, password, db_connection, parent_roles=parent_roles)
typer.echo('Done!')
def create_role(
name: str,
connection: Connection,
parent_roles: typing.Optional[typing.Iterable[str]] = None,
other_options: typing.Optional[typing.Tuple] = None,
):
if not check_for_role(name, connection):
options = f'WITH'
if parent_roles is not None:
options = f'{options} IN ROLE {", ".join(parent_roles)}'
if other_options is not None:
options = f'{options} {" ".join(other_options)}'
connection.execute(
text(f'CREATE ROLE {name} {options}')
)
else:
typer.echo(f'Role {name!r} already exists. Skipping...')
def create_user(
name: str,
password: str,
connection: Connection,
parent_roles: typing.Optional[typing.Iterable[str]] = None
):
return create_role(
name,
connection,
parent_roles=parent_roles,
other_options=(
'LOGIN',
f'PASSWORD \'{password}\''
)
)
def check_for_role(role: str, connection: Connection) -> bool:
"""Check if role exists on the database"""
return connection.execute(
text('SELECT EXISTS(SELECT 1 FROM pg_roles WHERE rolname = :role)'),
role=role
).scalar()
def create_schema(name: str, owner_role: str, connection: Connection):
return connection.execute(
text(f'CREATE SCHEMA IF NOT EXISTS {name} AUTHORIZATION {owner_role}')
)
def grant_schema_permissions(
schema: str,
permissions: typing.Iterable[str],
role: str,
connection: Connection
):
return connection.execute(
text(f'GRANT {", ".join(permissions)} ON SCHEMA {schema} TO {role}')
)
@contextmanager
def get_db_connection(db_url: str):
engine = sla.create_engine(db_url)
connected = False
max_tries = 30
current_try = 0
sleep_for = 2 # seconds
while not connected and current_try < max_tries:
try:
with engine.connect() as connection:
connected = True
yield connection
except OperationalError:
print(f'Could not connect to DB ({current_try + 1}/{max_tries})')
current_try += 1
if current_try < max_tries:
sleep(sleep_for)
else:
raise
def bootstrap_department(
db_connection,
department: str,
generic_user_name: str
):
user_role = f'{department}_user'
editor_role = f'{department}_editor'
typer.echo(f'Creating role {user_role!r}...')
create_role(
user_role, db_connection, parent_roles=('dominode_user',))
typer.echo(f'Creating role {editor_role!r}...')
create_role(
editor_role, db_connection, parent_roles=('editor', user_role))
staging_schema_name = f'{department}_staging'
typer.echo(f'Creating {staging_schema_name!r} schema...')
create_schema(staging_schema_name, editor_role, db_connection)
typer.echo(f'Setting schema permissions...')
grant_schema_permissions(
staging_schema_name,
('USAGE', 'CREATE'),
user_role,
db_connection
)
typer.echo(f'Creating qgis_projects table...')
create_qgis_projects_table(db_connection, staging_schema_name, user_role)
typer.echo(f'Adding GeoServer user account...')
geoserver_password = config[
f'{department}-department']['geoserver_password']
create_user(
utils.get_geoserver_db_username(department),
geoserver_password,
db_connection,
)
if department == 'lsd':
bootstrap_lsd_topomaps(db_connection, user_role)
def create_qgis_projects_table(
db_connection,
schema: str,
owner: str,
revoke_owner_updates: typing.Optional[bool] = False,
grant_select_to: typing.Optional[str] = None,
):
table_qualified_name = f'{schema}.qgis_projects'
db_connection.execute(
text(
f'CREATE TABLE IF NOT EXISTS {table_qualified_name} ('
f'name text not null constraint qgis_projects_pkey primary key ,'
f'metadata jsonb,'
f'content bytea'
f')'
)
)
db_connection.execute(
text(f'ALTER TABLE {table_qualified_name} OWNER TO {owner}')
)
if revoke_owner_updates:
db_connection.execute(
text(f'REVOKE UPDATE ON {table_qualified_name} FROM {owner}')
)
if grant_select_to:
db_connection.execute(
text(
f'GRANT SELECT ON {table_qualified_name} TO {grant_select_to}')
)
def bootstrap_lsd_topomaps(db_connection, user_role_name: str):
typer.echo(f'Creating role {LSD_TOPOMAP_EDITOR_ROLE_NAME!r}...')
create_role(
LSD_TOPOMAP_EDITOR_ROLE_NAME,
db_connection,
parent_roles=(user_role_name,)
)
schema_name = f'lsd_topomaps'
typer.echo(f'Creating {schema_name!r} schema...')
create_schema(
schema_name,
LSD_TOPOMAP_EDITOR_ROLE_NAME,
db_connection
)
typer.echo(f'Setting permissions on schema {schema_name!r}...')
grant_schema_permissions(
schema_name,
('USAGE',),
user_role_name,
db_connection
)
create_qgis_projects_table(
db_connection,
schema_name,
LSD_TOPOMAP_EDITOR_ROLE_NAME,
revoke_owner_updates=True,
grant_select_to=user_role_name
)
def get_db_url(
username: str,
password: str,
host: str,
port: typing.Union[str, int],
db_name: typing.Optional[str] = None
) -> str:
return (
f'postgresql://{username}:{password}@'
f'{host}:{port}/{db_name or username}'
)
|
Python
|
UTF-8
| 1,367 | 2.828125 | 3 |
[] |
no_license
|
t = int(input())
t_i = 1
while t_i<=t:
n = input()
digits = list(n)
#print(digits)
prev = '0'
index = 0
dict = {0:'0'}
for digit in digits:
if digit>=prev:
prev = digit
else:
#print('defaulter'+digit)
break
index+=1
dict[index] = prev
if index == len(digits):
print('Case #'+str(t_i)+': '+n)
#print('continue k wala')
t_i+=1
continue
else:
i = 0
#print('index '+str(index))
#print(dict)
#index-=1
new_n = ''
while i<=index:
'''if i==index:
new_n = '9'*(len(digits)-1)
print('inside')
break'''
if int(dict[index-i])-1>=int(dict[index-i-1]) :
tidy_n = digits[:(index-i-1)]
#print('i = '+str(i))
tidy_n.append(str(int(dict[index])-1))
nines = ['9']*(len(digits)-len(tidy_n))
tidy_n.extend(nines)
if tidy_n[0] == '0':
tidy_n = tidy_n[1:]
new_n = ''.join(tidy_n)
break
i+=1
print('Case #'+str(t_i)+': '+new_n)
t_i+=1
|
Go
|
UTF-8
| 547 | 2.59375 | 3 |
[] |
no_license
|
package web_models
import (
"github.com/gorilla/websocket"
)
// TODO: Implement date..
func NewStatusMessage(msg string) *StatusMessage {
return &StatusMessage{Message: msg}
}
// TODO: Implement date..
func NewConnStatusMessage(conn *websocket.Conn, msg string, t string) *ConnStatusMessage {
csm := ConnStatusMessage{Connection: conn}
csm.Message = msg
csm.Type = t
return &csm
}
type StatusMessage struct {
Date string
Message string
Type string
}
type ConnStatusMessage struct {
StatusMessage
Connection *websocket.Conn
}
|
Java
|
UTF-8
| 1,826 | 2.21875 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2019, 2020, 2021, 2022 the original author or authors.
*
* 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 am.validators;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Test {@link TvSeriesValidator} class.
*/
public class AbstractValidatorTest
{
@Before
public void setUp()
{
AbstractValidator.register(MovieValidator.class);
AbstractValidator.register(TvSeriesValidator.class);
}
@Test
public void testHasRegisteredValidators()
{
Assert.assertTrue("After setup there are registered validators.", AbstractValidator.hasRegisteredValidators());
}
@Test
public void testFindByNameNull()
{
Assert.assertNull("Null validator name leads to null validator class.", AbstractValidator.findByName(null));
}
@Test
public void testFindByNameEmpty()
{
Assert.assertNull("Empty validator name leads to null validator class.", AbstractValidator.findByName(""));
}
@Test
public void testFindByNameMovieValidator()
{
final Class<? extends AbstractValidator> val = AbstractValidator.findByName("MovieValidator");
Assert.assertNotNull("Movie validator name leads to non-null class.", val);
Assert.assertEquals("Movie validator name leads to movie validator class.", MovieValidator.class, val);
}
}
|
PHP
|
UTF-8
| 4,565 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace ZanPHP\SPI;
use ZanPHP\SPI\Exception\ClassNotFoundException;
use ZanPHP\SPI\Exception\RedeclareException;
class AliasLoader extends MetaInfoLoader
{
const SUFFIX = "alias.php";
/**
* @var static
*/
private static $instance = null;
private $aliasOriginMap ;
/**
* @return static
*/
public static function getInstance()
{
if (static::$instance === null) {
static::$instance = new static();
}
return static::$instance;
}
public function normalizedClassName($class)
{
return ltrim($class, "\\");
}
protected function accept(\SplFileInfo $fileInfo, $path, \FilesystemIterator $iter)
{
$suffix = static::PREFIX . static::SUFFIX;
$len = strlen($suffix);
if ($fileInfo->isFile()) {
$realPath = $fileInfo->getRealPath();
return substr($realPath, -$len) === $suffix;
}
return false;
}
public function scan($vendor)
{
$this->aliasOriginMap = [];
$metaMap = $this->getMetaInfo($vendor);
$this->parserMetaMap($metaMap);
$this->registerAliasMap();
}
private function parserMetaMap(array $metaMap)
{
foreach ($metaMap as $realPath => $pkgAliasMap) {
if (!is_array($pkgAliasMap)) {
continue;
}
foreach ($pkgAliasMap as $origin => $aliases) {
$aliases = (array)$aliases;
$origin = $this->normalizedClassName($origin);
$aliases = array_map([$this, "normalizedClassName"], $aliases);
// 这里不检查重复定义, 类加载器会检查
foreach ($aliases as $alias) {
$this->aliasOriginMap[$alias] = [$origin, $realPath, false];
}
}
}
}
/**
* 利用 autoload 递归注册依赖别名
* 解决class_alias优先级问题,
*
* @throws ClassNotFoundException
* @throws RedeclareException
*
* 扫描顺序
* 1. class A ---alias--> class B
* 2. class C extends E ---alias--> class A
* 3. class D ---alias--> class E
*
* 检测A是否声明, 触发A自动加载, composer autoload 没有发现,由 [$this, autoload] 处理
* [$this, autoload] 发现 A 是 C 的别名
* 检查是C是否声明, 触发C自动加载, 发现C继承E, 触发E自动加载, composer autoload 没有发现,由 [$this, autoload] 处理
* [$this, autoload] 发现 E 是 D 别名, 检测D是否声明, 未声明, 自动加载D
* 将D 别名成 E, 完成 E自动加载, 从而完成 C 自动加载
* 将 C 别名成 A, 从而完成 A 自动加载,
* 将 A 别名成 B
*/
private function registerAliasMap()
{
spl_autoload_register([$this, "autoload"]);
foreach ($this->aliasOriginMap as $alias => list($origin, $realPath, $hasAliased)) {
if (false === $this->declareIsExists($origin) /* 触发 origin 自动加载 */) {
throw new ClassNotFoundException("class or interface or trait $origin not found in $realPath");
}
if ($hasAliased) {
continue;
}
if ($this->declareIsExists($alias) /* 触发 alias 自动加载 */ ) {
$hasAliased = $this->aliasOriginMap[$alias][2];
if ($hasAliased) {
continue;
}
throw new RedeclareException("Cannot declare alias $alias in $realPath, because the name is already in use");
}
}
spl_autoload_unregister([$this, "autoload"]);
}
public function autoload($class)
{
if (isset($this->aliasOriginMap[$class])) {
// echo "prepare load class $class\n";
list($origin, $realPath) = $this->aliasOriginMap[$class];
if (false === class_alias($origin, $class) /* 触发 origin 自动加载 */) {
throw new \BadMethodCallException("class_alias $origin to $class fail in $realPath");
}
// echo "alias $origin to $class\n";
$this->aliasOriginMap[$class][2] = true;
// echo "finish load class $class\n";
}
}
private function declareIsExists($declare, $autoload = true)
{
return class_exists($declare, $autoload) || interface_exists($declare, $autoload) || trait_exists($declare, $autoload);
}
}
|
C++
|
UTF-8
| 1,226 | 2.59375 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <cmath>
#include <algorithm>
#define MAX 500010
#define MAX2 524288
int n,p;
//int a[MAX];
int b[2*MAX2];
using namespace std;
void Build(){
/*for(int i=0; i<n; ++i)
b[p+i]=a[i+1];*/
for(int i=p+n; i<p<<1; ++i) b[i]=0;
for(int i=p-1; i>0; --i)
b[i]=b[2*i]+b[2*i+1];
}
int GetSum(int v, int ll, int rr, int l, int r){
if(l<ll) l = ll;
if(rr<r) r = rr;
if(ll==l && rr==r) return b[v];
if(l>r) return 0;
int m=(ll+rr)/2;
return GetSum(v*2,ll,m,l,r)+GetSum(v*2+1,m+1,rr,l,r);
}
int Set(int i, int v){
b[p+i-1]=v;
int pr=(p+i-1)/2;
while(pr!=0){
b[pr]=b[2*pr]+b[2*pr+1];
pr/=2;
}
}
int main(){
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
int k,x,y;
char c;
scanf("%d %d",&n,&k);
p=1; for(; p<n; p*=2);
for(int i=1; i<=n; ++i){
scanf("%d",b+p+i-1);
}
Build();
for(int i=0; i<k; ++i){
scanf("%c",&c);
if(c=='='){
scanf("%d %d",&x,&y);
Set(x,y);
}
else
if(c=='?'){
scanf("%d %d",&x,&y);
printf("%d\n",GetSum(1,1,p,x,y));
} else --i;
}
}
|
Java
|
UTF-8
| 3,434 | 2.953125 | 3 |
[] |
no_license
|
package com.mohamadamin.persianmaterialdatetimepicker;
import com.mohamadamin.persianmaterialdatetimepicker.utils.PersianCalendar;
import java.util.Calendar;
import java.util.Locale;
public class XPersianCalendar extends PersianCalendar {
public XPersianCalendar() {
super();
}
public XPersianCalendar(Long date) {
super();
setTimeInMillis(date);
}
public XPersianCalendar(int year, int month, int day) {
super();
setPersianDate(year, month, day);
}
public XPersianCalendar(int day, int month, int year, int hour, int min) {
super();
setPersianDate(year, month, day);
set(HOUR, hour);
set(MINUTE, min);
set(SECOND, 0);
set(MILLISECOND, 0);
}
public static XPersianCalendar getCalendar(String persianStringDate, String timeString) {
if (persianStringDate == null || persianStringDate.isEmpty()) {
return null;
}
String[] splited = persianStringDate.split("/");
String[] timeSplit = timeString.split(":");
if (splited.length != 3) {
return null;
}
XPersianCalendar persianCalendar = new XPersianCalendar();
persianCalendar.setPersianDate(Integer.valueOf(splited[0]), Integer.valueOf(splited[1]), Integer.valueOf(splited[2]));
persianCalendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(timeSplit[0]));
persianCalendar.set(Calendar.MINUTE, Integer.valueOf(timeSplit[1]));
persianCalendar.set(Calendar.SECOND, 0);
persianCalendar.set(Calendar.MILLISECOND, 0);
return persianCalendar;
}
public static XPersianCalendar getCalendar(String persianStringDate) {
return getCalendar(persianStringDate, "00:00");
}
private static String getHourTimeString(XPersianCalendar persianCalendar) {
return String.format(Locale.US, "%02d:%02d", persianCalendar.get(Calendar.HOUR_OF_DAY), persianCalendar.get(Calendar.MINUTE));
}
private static String getPersianShortFormat(XPersianCalendar persianCalendar) {
return String.format(Locale.US, "%04d/%02d/%02d", persianCalendar.getPersianYear(), persianCalendar.getPersianMonth(), persianCalendar.getPersianDay());
}
private static String getGregorianFullFormat(XPersianCalendar sappPersianCalendar) {
String FORMAT = "%04d-%02d-%02d %02d:%02d:%02d";
return String.format(Locale.US,
FORMAT,
sappPersianCalendar.get(Calendar.YEAR),
sappPersianCalendar.get(Calendar.MONTH) + 1,
sappPersianCalendar.get(Calendar.DAY_OF_MONTH),
sappPersianCalendar.get(Calendar.HOUR_OF_DAY),
sappPersianCalendar.get(Calendar.MINUTE),
sappPersianCalendar.get(Calendar.SECOND)
);
}
public String getHourTimeString() {
return getHourTimeString(this);
}
public String getGregorianFullFormat() {
return getGregorianFullFormat(this);
}
public String getPersianShortFormat() {
return getPersianShortFormat(this);
}
public void setDate(PersianCalendar persianCalendar) {
setTimeInMillis(persianCalendar.getTimeInMillis());
}
public void clearTime() {
set(Calendar.HOUR_OF_DAY, 0);
set(Calendar.MINUTE, 0);
set(Calendar.SECOND, 0);
set(Calendar.MILLISECOND, 0);
}
}
|
Java
|
UTF-8
| 663 | 2.9375 | 3 |
[] |
no_license
|
import java.util.*;
import java.lang.*;
public class InvalidBrokenAppliances extends Exception{
//fields
private int no_of_broken_fans;
private int no_of_broken_tables;
private int no_of_broken_lights;
//constructor
public InvalidBrokenAppliances(int broken_lights, int broken_fans, int broken_tables){
this.no_of_broken_lights = broken_lights;
this.no_of_broken_fans = broken_fans;
this.no_of_broken_tables = broken_tables;
}
//methods
public java.lang.String getMessage(){
if (no_of_broken_tables < 0 || no_of_broken_fans < 0 || no_of_broken_lights < 0) {
return "Number of broken appliances invalid.";
}else{
return "";
}
}
}
|
Java
|
UTF-8
| 1,307 | 2.21875 | 2 |
[] |
no_license
|
package com.epam.goalTracker.repositories.entities;
import com.epam.goalTracker.repositories.entities.enums.PersonalGoalStatus;
import lombok.Data;
import lombok.ToString;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
/**
* Personal Goal Entity
*
* @author Yevhenii Kravtsov
* @version 1.0
* @date 18.12.2020 20:53
*/
@Entity
@Table(name = "personal_goals")
@Data
@ToString
public class PersonalGoalEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "start_date")
private Date startDate;
@Column(name = "end_date")
private Date endDate;
@Column(name = "pause_date")
private Date pausedDate;
@Column(name = "status")
@Enumerated(value = EnumType.STRING)
private PersonalGoalStatus status;
@ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
@JoinColumn(name = "global_goals_id", referencedColumnName = "id")
private GlobalGoalEntity globalGoal;
@ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
@JoinColumn(name = "users_id", referencedColumnName = "id")
private UserEntity user;
@OneToMany(mappedBy = "personalGoal", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<DayProgressEntity> dayProgresses;
}
|
Python
|
UTF-8
| 3,412 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
import tensorflow as tf
from tensorflow.keras import Input, Model
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Activation, Lambda, SpatialDropout1D
from tensorflow.keras.layers import Conv1D, LSTM, Multiply, Add, Dense, Dropout
from python.tcn import TCN
def model_LSTM(n_feat):
model = Sequential()
model.add(LSTM(units=16, return_sequences=True, input_shape=(n_steps, n_feat)))
model.add(Dropout(0.2))
model.add(LSTM(units=16, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=16, return_sequences=True))
model.add(Dropout(0.5))
model.add(LSTM(units=16))
model.add(Dropout(0.5))
model.add(Dense(units=1))
return model
def model_TCN(n_his, n_feat, n_out=1, dropout_rate = 0.2):
# convolutional operation parameters
n_filters = 32 # 32
filter_width = 2
dilation_rates = [2**i for i in range(4)] * 2 # 8
dropout_rate = dropout_rate
# define an input history series and pass it through a stack of dilated causal convolution blocks.
history_seq = Input(shape=(n_his, n_feat))
x = history_seq
skips = []
for dilation_rate in dilation_rates:
# preprocessing - equivalent to time-distributed dense
x = Conv1D(32, 1, padding='same', activation='relu')(x)
# filter convolution
x_f = Conv1D(filters=n_filters,
kernel_size=filter_width,
padding='causal',
dilation_rate=dilation_rate)(x)
# gating convolution
x_g = Conv1D(filters=n_filters,
kernel_size=filter_width,
padding='causal',
dilation_rate=dilation_rate)(x)
# multiply filter and gating branches
z = Multiply()([Activation('tanh')(x_f),
Activation('sigmoid')(x_g)])
# postprocessing - equivalent to time-distributed dense
z = Conv1D(32, 1, padding='same', activation='relu')(z)
z = Dropout(dropout_rate)(z)
# residual connection
x = Add()([x, z])
# collect skip connections
skips.append(z)
# add all skip connection outputs
out = Activation('relu')(Add()(skips))
# final time-distributed dense layers
out = Conv1D(128, 1, padding='same')(out)
out = Activation('relu')(out)
out = Dropout(dropout_rate)(out)
out = Conv1D(1, 1, padding='same')(out)
# extract the last 60 time steps as the training target
def slice(x, seq_length):
return x[:,-seq_length:,:]
pred_seq_train = Lambda(slice, arguments={'seq_length':n_out})(out)
model = Model(history_seq, pred_seq_train)
return model
def model_Keras_TCN(n_his, n_feat):
input_layer = Input(shape=(n_his, n_feat))
x = TCN(nb_filters=16,
kernel_size=2,
nb_stacks=2,
dilations=(1, 2, 4, 8),
padding='causal',
use_skip_connections=True,
dropout_rate=0.2,
return_sequences=False,
activation='relu',
kernel_initializer='he_normal',
use_batch_norm=False,
use_layer_norm=False,
name='tcn')(input_layer)
output_layer = Dense(1)(x)
model = Model(input_layer, output_layer)
return model
|
Shell
|
UTF-8
| 415 | 3.171875 | 3 |
[] |
no_license
|
#!/bin/bash
echo Please Enter External IP:
read natIP
echo 1.Wordcount
echo 2.Inverted Index
echo Please enter your choice:
read choice
if [ $choice -eq 1 ]
then
curl -v http://$natIP:7001/ -F datafile=@wordConfig.json -o word_count.txt
elif [ $choice -eq 2 ]
then
curl -v http://$natIP:7001/ -F datafile=@invertedConfig.json -o inverted_index.txt
else
echo Invalid choice. Please try again...
fi
|
Java
|
UTF-8
| 960 | 2.578125 | 3 |
[] |
no_license
|
package easy;
import org.junit.Assert;
import org.junit.Test;
import support.tree.TreeGenerator;
import support.tree.TreeNode;
public class MinimumAbsoluteDifferenceInBstTest {
private MinimumAbsoluteDifferenceInBst solution = new MinimumAbsoluteDifferenceInBst();
@Test
public void test0() {
TreeGenerator generator = new TreeGenerator(10, 0, 100, 1);
TreeNode root = generator.randomTree();
Assert.assertEquals(1, solution.getMinimumDifference(root));
}
@Test
public void test1() {
TreeGenerator generator = new TreeGenerator(10, 0, 100, 2);
TreeNode root = generator.randomTree();
Assert.assertEquals(1, solution.getMinimumDifference(root));
}
@Test
public void test2() {
TreeGenerator generator = new TreeGenerator(100, 0, 10000, 4);
TreeNode root = generator.randomTree();
Assert.assertEquals(1, solution.getMinimumDifference(root));
}
}
|
Markdown
|
UTF-8
| 2,354 | 2.609375 | 3 |
[] |
no_license
|
# PRACTICA 3: WIFI Y BLUETOOTH
##INFORME PART B
####codigo
```
#include <Arduino.h>
//This example code is in the Public Domain (or CC0 licensed, at your option.)
//By Evandro Copercini - 2018
//
//This example creates a bridge between Serial and Classical Bluetooth (SPP)
//and also demonstrate that SerialBT have the same functionalities of a normal Serial
#include "BluetoothSerial.h"
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
BluetoothSerial SerialBT;
void setup() {
Serial.begin(115200);
SerialBT.begin("ESP32test"); //Bluetooth device name
Serial.println("The device started, now you can pair it with bluetooth!");
}
void loop() {
if (Serial.available()) {
SerialBT.write(Serial.read());
}
if (SerialBT.available()) {
Serial.write(SerialBT.read());
}
delay(20);
}
```
#####Realizar el informe de funcionamiento asi como las salidas que se obtienen a través de la impresión serie
El que esta fent el codi d'aquesta pràctica és establir una comunicació entre dos aparells.
En el codi primer de tot s'inicia el bluetooth serial, gràcies a la llibreria BluetoothSerial.h.
S'inicia la comunicació serial en el setup amb un missatge de confirmació que informa si l'aparell està en marxa "The device started, now you can pair it with bluetooth!".
Seguidament tenim l'exemple del terminal en el meu ordinador.
<!--Images-->

Seguidament en el codi trobem un bucle, el que fa es, si esta rebent (llegint) correctament la informació, envia aquesta via bluetooth a l'aparell connectat, aquesta comunicació és establida de manera bidireccional, per tant es segueix el mateix procediment per enviar informació del terminal de visualstudio al de l'aplicació mobil, i per enviar informació de l'apliciació mobil al terminal.
Una vegada està en marxa conectem el nostre telefon a la placa per bluetooth quan s'estableixi la connexió entre els dos aparells si escribim "Hola" a l'aplicació en el nostre mobil podem comprovar que es mostrara el missatge "Hola" en el terminal de visual studio, i el mateix al inreves, si enviem un missatge des del terminal de visual studio, aquest es rebrà al terminal de l'aplicació mobil.
|
Ruby
|
UTF-8
| 333 | 3.53125 | 4 |
[] |
no_license
|
class FileIO
def fileio
@str1 = "Aman Gautam"
puts " The entered string is #{@str1}"
puts "Enter a string"
@str2 = gets
puts "The entered string is #{@str2}"
putc "The first character of the string is #{@str2} "
print "Finally string 1 is : #{@str1}"
print "and string 2 is : #{@str2}"
end
end
ob = FileIO.new
ob.fileio
|
C++
|
UTF-8
| 509 | 2.515625 | 3 |
[
"Apache-2.0"
] |
permissive
|
// 2-parameter registered things
#include "2.sub.class.h"
#include "sugiyama/exception-registry.h"
#include <catch2/catch_test_macros.hpp>
#include <catch2/matchers/catch_matchers_string.hpp>
using Catch::Matchers::Equals;
SCENARIO("2-parameter registry", "[reg]") {
const auto& reg = RegSubject2::obj();
GIVEN("One registered class") {
THEN("It can be manifested correctly") {
auto p1 = reg.make("Subject2a", 50, 80);
REQUIRE(p1->get() == 130);
}
}
} // end 2 parameter scenario
|
Java
|
UTF-8
| 383 | 1.742188 | 2 |
[] |
no_license
|
package com.wt.spring.cloud.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author WuTian
* @date 2018-11-01 17:04
* @description
*/
@Component
@Data
@ConfigurationProperties("address")
public class Address {
private String province;
private String city;
}
|
Python
|
UTF-8
| 1,285 | 3.828125 | 4 |
[] |
no_license
|
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
while head is not None and head.val == val:
head = head.next
# handle null value after moving
if head is None:
return None
# create a pointer reference to the head node, and loop to check its next node's value
# if it is equal to the input val, skip that node
cur = head
while cur.next:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return head
# another soln
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
curr = ListNode(-1)
curr.next = head
prev = curr
# prev = curr
while prev.next:
if prev.next.val == val:
prev.next = prev.next.next
else:
prev = prev.next
return curr.next
|
Python
|
UTF-8
| 241 | 2.59375 | 3 |
[] |
no_license
|
# coding: utf-8
# In[ ]:
import numpy as np
def showInfo(Var,VarName = "UnKnown"):
print("Name ", VarName)
print("type: ", type(Var))
print("Dtype: ", Var.dtype)
print("shape: ", Var.shape)
# print("flags: ", Var.flags)
|
SQL
|
UTF-8
| 4,366 | 2.765625 | 3 |
[] |
no_license
|
CREATE DATABASE IF NOT EXISTS `adminsolzul` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `adminsolzul`;
-- MySQL dump 10.13 Distrib 5.6.17, for Win32 (x86)
--
-- Host: soporte2 Database: adminsolzul
-- ------------------------------------------------------
-- Server version 5.1.42-community
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `corteszeta`
--
DROP TABLE IF EXISTS `corteszeta`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `corteszeta` (
`id_empresa` varchar(6) NOT NULL DEFAULT '',
`agencia` varchar(3) NOT NULL DEFAULT '',
`serial` varchar(50) NOT NULL DEFAULT '',
`codigo` varchar(6) NOT NULL DEFAULT '',
`nombre` varchar(50) NOT NULL DEFAULT '',
`marca` varchar(50) NOT NULL DEFAULT '',
`modelo` varchar(50) NOT NULL DEFAULT '',
`estacion` varchar(3) NOT NULL DEFAULT '',
`ubicacion` varchar(80) NOT NULL,
`numeroz` varchar(8) NOT NULL DEFAULT '',
`fechaz` date NOT NULL DEFAULT '0000-00-00',
`horaz` varchar(5) NOT NULL DEFAULT '',
`razonsocial` varchar(100) NOT NULL DEFAULT '',
`rif` varchar(20) NOT NULL DEFAULT '',
`facexenta` double(15,7) NOT NULL DEFAULT '0.0000000',
`cantidadfac` double(10,0) NOT NULL DEFAULT '0',
`bifacalicgen` double(15,7) NOT NULL DEFAULT '0.0000000',
`ivafacalicgen` double(15,7) NOT NULL DEFAULT '0.0000000',
`bifacalicred` double(15,7) NOT NULL DEFAULT '0.0000000',
`ivafacalicred` double(15,7) NOT NULL DEFAULT '0.0000000',
`bifacalicaum` double(15,7) NOT NULL DEFAULT '0.0000000',
`ivafacalicaum` double(15,7) NOT NULL DEFAULT '0.0000000',
`ncexenta` double(15,7) NOT NULL DEFAULT '0.0000000',
`cantidadnc` double(15,7) NOT NULL DEFAULT '0.0000000',
`bincalicgen` double(15,7) NOT NULL DEFAULT '0.0000000',
`ivancalicgen` double(15,7) NOT NULL DEFAULT '0.0000000',
`bincalicred` double(15,7) NOT NULL DEFAULT '0.0000000',
`ivancalicred` double(15,7) NOT NULL DEFAULT '0.0000000',
`bincalicaum` double(15,7) NOT NULL DEFAULT '0.0000000',
`ivancalicaum` double(15,7) NOT NULL DEFAULT '0.0000000',
`descexento` double(15,7) NOT NULL DEFAULT '0.0000000',
`cantidaddesc` double(10,0) NOT NULL DEFAULT '0',
`bidescalicgen` double(15,7) NOT NULL DEFAULT '0.0000000',
`ivadescalicgen` double(15,7) NOT NULL DEFAULT '0.0000000',
`bidescalicred` double(15,7) NOT NULL DEFAULT '0.0000000',
`ivadescalicred` double(15,7) NOT NULL DEFAULT '0.0000000',
`bidescalicaum` double(15,7) NOT NULL DEFAULT '0.0000000',
`ivadescalicaum` double(15,7) NOT NULL DEFAULT '0.0000000',
`primfact` varchar(15) NOT NULL DEFAULT '',
`primnc` varchar(15) NOT NULL DEFAULT '',
`ultifact` varchar(15) NOT NULL DEFAULT '',
`fechultfac` date NOT NULL DEFAULT '0000-00-00',
`horaultfac` varchar(5) NOT NULL DEFAULT '',
`ultinc` varchar(15) NOT NULL DEFAULT '',
`fechultnc` date NOT NULL DEFAULT '0000-00-00',
`horaultnc` varchar(5) NOT NULL DEFAULT '',
PRIMARY KEY (`id_empresa`,`agencia`,`serial`,`codigo`,`fechaz`,`numeroz`,`horaz`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `corteszeta`
--
LOCK TABLES `corteszeta` WRITE;
/*!40000 ALTER TABLE `corteszeta` DISABLE KEYS */;
/*!40000 ALTER TABLE `corteszeta` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2014-07-25 10:46:25
|
Ruby
|
UTF-8
| 1,175 | 2.59375 | 3 |
[
"Apache-2.0"
] |
permissive
|
###
# The Bookplate class deserializes a solr field representing a Bookplate
# The expected format of that field is "FUND-NAME -|- DRUID -|- FILE-ID -|- BOOKPLATE-TEXT"
# Example: "SHARPS -|- druid:rq470hm8269 -|- rq470hm8269_00_0001.jp2 -|- Susan and Ruth Sharp Fund"
###
class Bookplate
attr_reader :bookplate_data
include StacksImages
def initialize(bookplate_data)
@bookplate_data = bookplate_data
end
def thumbnail_url
craft_image_url(druid:, image_id: file_id, size: :large)
end
def text
split_fields[3]
end
def params_for_search
{ f: { facet_field_key.to_sym => [druid] } }
end
def to_partial_path
'bookplates/bookplate'
end
def matches?(params)
values = Array.wrap(params.dig(:f, facet_field_key.to_sym))
values.include?(druid) || values.include?(fund_name)
end
private
def fund_name
split_fields[0]
end
def druid
split_fields[1].gsub('druid:', '')
end
def file_id
split_fields[2].gsub(/\..*$/, '')
end
def split_fields
bookplate_data.split(data_delimiter).map(&:strip)
end
def facet_field_key
:fund_facet
end
def data_delimiter
'-|-'
end
end
|
C
|
UTF-8
| 6,953 | 2.703125 | 3 |
[
"ISC",
"MIT",
"LicenseRef-scancode-public-domain"
] |
permissive
|
#ifndef COSMOPOLITAN_THIRD_PARTY_SQLITE3_SQLITE3EXPERT_H_
#define COSMOPOLITAN_THIRD_PARTY_SQLITE3_SQLITE3EXPERT_H_
#include "third_party/sqlite3/sqlite3.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
typedef struct sqlite3expert sqlite3expert;
/*
** Create a new sqlite3expert object.
**
** If successful, a pointer to the new object is returned and (*pzErr) set
** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
** an English-language error message. In this case it is the responsibility
** of the caller to eventually free the error message buffer using
** sqlite3_free().
*/
sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
/*
** Configure an sqlite3expert object.
**
** EXPERT_CONFIG_SAMPLE:
** By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
** each candidate index. This involves scanning and sorting the entire
** contents of each user database table once for each candidate index
** associated with the table. For large databases, this can be
** prohibitively slow. This option allows the sqlite3expert object to
** be configured so that sqlite_stat1 data is instead generated based on a
** subset of each table, or so that no sqlite_stat1 data is used at all.
**
** A single integer argument is passed to this option. If the value is less
** than or equal to zero, then no sqlite_stat1 data is generated or used by
** the analysis - indexes are recommended based on the database schema only.
** Or, if the value is 100 or greater, complete sqlite_stat1 data is
** generated for each candidate index (this is the default). Finally, if the
** value falls between 0 and 100, then it represents the percentage of user
** table rows that should be considered when generating sqlite_stat1 data.
**
** Examples:
**
** // Do not generate any sqlite_stat1 data
** sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
**
** // Generate sqlite_stat1 data based on 10% of the rows in each table.
** sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
*/
int sqlite3_expert_config(sqlite3expert *p, int op, ...);
#define EXPERT_CONFIG_SAMPLE 1 /* int */
/*
** Specify zero or more SQL statements to be included in the analysis.
**
** Buffer zSql must contain zero or more complete SQL statements. This
** function parses all statements contained in the buffer and adds them
** to the internal list of statements to analyze. If successful, SQLITE_OK
** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
** may be set to point to an English language error message. In this case
** the caller is responsible for eventually freeing the error message buffer
** using sqlite3_free().
**
** If an error does occur while processing one of the statements in the
** buffer passed as the second argument, none of the statements in the
** buffer are added to the analysis.
**
** This function must be called before sqlite3_expert_analyze(). If a call
** to this function is made on an sqlite3expert object that has already
** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
** immediately and no statements are added to the analysis.
*/
int sqlite3_expert_sql(
sqlite3expert *p, /* From a successful sqlite3_expert_new() */
const char *zSql, /* SQL statement(s) to add */
char **pzErr /* OUT: Error message (if any) */
);
/*
** This function is called after the sqlite3expert object has been configured
** with all SQL statements using sqlite3_expert_sql() to actually perform
** the analysis. Once this function has been called, it is not possible to
** add further SQL statements to the analysis.
**
** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
** an error occurs, an SQLite error code is returned and (*pzErr) set to
** point to a buffer containing an English language error message. In this
** case it is the responsibility of the caller to eventually free the buffer
** using sqlite3_free().
**
** If an error does occur within this function, the sqlite3expert object
** is no longer useful for any purpose. At that point it is no longer
** possible to add further SQL statements to the object or to re-attempt
** the analysis. The sqlite3expert object must still be freed using a call
** sqlite3_expert_destroy().
*/
int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
/*
** Return the total number of statements loaded using sqlite3_expert_sql().
** The total number of SQL statements may be different from the total number
** to calls to sqlite3_expert_sql().
*/
int sqlite3_expert_count(sqlite3expert *);
/*
** Return a component of the report.
**
** This function is called after sqlite3_expert_analyze() to extract the
** results of the analysis. Each call to this function returns either a
** NULL pointer or a pointer to a buffer containing a nul-terminated string.
** The value passed as the third argument must be one of the EXPERT_REPORT_*
** #define constants defined below.
**
** For some EXPERT_REPORT_* parameters, the buffer returned contains
** information relating to a specific SQL statement. In these cases that
** SQL statement is identified by the value passed as the second argument.
** SQL statements are numbered from 0 in the order in which they are parsed.
** If an out-of-range value (less than zero or equal to or greater than the
** value returned by sqlite3_expert_count()) is passed as the second argument
** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
**
** EXPERT_REPORT_SQL:
** Return the text of SQL statement iStmt.
**
** EXPERT_REPORT_INDEXES:
** Return a buffer containing the CREATE INDEX statements for all recommended
** indexes for statement iStmt. If there are no new recommeded indexes, NULL
** is returned.
**
** EXPERT_REPORT_PLAN:
** Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
** iStmt after the proposed indexes have been added to the database schema.
**
** EXPERT_REPORT_CANDIDATES:
** Return a pointer to a buffer containing the CREATE INDEX statements
** for all indexes that were tested (for all SQL statements). The iStmt
** parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
*/
const char *sqlite3_expert_report(sqlite3expert *, int iStmt, int eReport);
/*
** Values for the third argument passed to sqlite3_expert_report().
*/
#define EXPERT_REPORT_SQL 1
#define EXPERT_REPORT_INDEXES 2
#define EXPERT_REPORT_PLAN 3
#define EXPERT_REPORT_CANDIDATES 4
/*
** Free an (sqlite3expert*) handle and all associated resources. There
** should be one call to this function for each successful call to
** sqlite3-expert_new().
*/
void sqlite3_expert_destroy(sqlite3expert *);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_THIRD_PARTY_SQLITE3_SQLITE3EXPERT_H_ */
|
C#
|
UTF-8
| 6,366 | 2.765625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Yatzhee
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Scorecard scorecard = new Scorecard();
List<CheckBox> checkBoxes = new List<CheckBox>();
List<RadioButton> radioButtons = new List<RadioButton>();
int counter, decision, rollNumber = 0, gameTurns = 0;
public MainWindow()
{
InitializeComponent();
scorecard.SetupGame();
// Added CheckBoxes and RadioButtons to lists to use them more effectively later
checkBoxes.Add(chBoxDie1);
checkBoxes.Add(chBoxDie2);
checkBoxes.Add(chBoxDie3);
checkBoxes.Add(chBoxDie4);
checkBoxes.Add(chBoxDie5);
radioButtons.Add(radioAces);
radioButtons.Add(radioTwos);
radioButtons.Add(radioThrees);
radioButtons.Add(radioFours);
radioButtons.Add(radioFives);
radioButtons.Add(radioSixes);
radioButtons.Add(radioThreeOfAKind);
radioButtons.Add(radioFourOfAKind);
radioButtons.Add(radioFullHouse);
radioButtons.Add(radioSmallStraight);
radioButtons.Add(radioLargeStraight);
radioButtons.Add(radioYatzhee);
radioButtons.Add(radioChance);
}
#region Buttons
// Button that roll dice
private void BtnRoll_Click(object sender, RoutedEventArgs e)
{
btnSubmit.IsEnabled = true;
counter = 0;
// Makes Checkboxes usable after at least first roll
foreach (CheckBox box in checkBoxes)
{
box.IsEnabled = true;
}
// Rolls dice and displays them
foreach (Die die in scorecard.Dice)
{
die.RollDie();
checkBoxes[counter].Content = die.CurrentValue;
counter++;
}
// Only lets you roll three times
rollNumber++;
if (rollNumber == 3)
{
btnRoll.IsEnabled = false;
}
}
// Button that submits and calculates answer
private void BtnSubmit_Click(object sender, RoutedEventArgs e)
{
decision = 0;
// Checks each radiobutton to see which one is chosen, then disables and clears it
foreach (RadioButton button in radioButtons)
{
if ((bool)button.IsChecked)
{
decision = Convert.ToInt32(button.Tag);
button.IsEnabled = false;
button.IsChecked = false;
}
}
// Calculates and displays the value of the chosen option
switch (decision)
{
case 1:
lbAces.Content = scorecard.OneScore;
break;
case 2:
lbTwos.Content = scorecard.TwoScore;
break;
case 3:
lbThrees.Content = scorecard.ThreeScore;
break;
case 4:
lbFours.Content = scorecard.FourScore;
break;
case 5:
lbFives.Content = scorecard.FiveScore;
break;
case 6:
lbSixes.Content = scorecard.SixScore;
break;
case 7:
lbThreeOfAKind.Content = scorecard.ThreeOfAKind;
break;
case 8:
lbFourOfAKind.Content = scorecard.FourOfAKind;
break;
case 9:
lbFullHouse.Content = scorecard.FullHouse;
break;
case 10:
lbsmallStraight.Content = scorecard.SmallStraight;
break;
case 11:
lbLargeStraight.Content = scorecard.LargeStraight;
break;
case 12:
lbYatzhee.Content = scorecard.Yahtzee;
break;
case 13:
lbChance.Content = scorecard.Chance;
break;
default:
break;
}
// If choice is in upper section, calculates upper score
if (decision != 0 && decision <= 6)
{
lbUpperTotalNum.Content = scorecard.UpperScore;
}
// If choice is in lower section, calculates lower score
if (decision > 6)
{
lbLowerTotalNum.Content = scorecard.LowerScore;
}
// If a choice has been made: Calculates grand total, Disables submit button
// Enables roll button as long as game is not over, Disables and clears checkboxes
if (decision != 0)
{
lbGrandTotalNum.Content = scorecard.TotalScore;
btnSubmit.IsEnabled = false;
rollNumber = 0;
btnRoll.IsEnabled = true;
gameTurns++;
if (gameTurns >= 13)
{
btnRoll.IsEnabled = false;
}
foreach (CheckBox box in checkBoxes)
{
box.IsChecked = false;
box.IsEnabled = false;
}
}
}
#endregion
#region CheckBoxes
// When checked, holds the die so that it won't be rolled
private void ChBoxDice_Checked(object sender, RoutedEventArgs e)
{
scorecard.Dice[Convert.ToInt32(((CheckBox)sender).Tag)].Hold = true;
}
// When unchecked, unholds the die so that it can be rolled
private void ChBoxDice_Unchecked(object sender, RoutedEventArgs e)
{
scorecard.Dice[Convert.ToInt32(((CheckBox)sender).Tag)].Hold = false;
}
#endregion
}
}
|
Markdown
|
UTF-8
| 7,419 | 3.0625 | 3 |
[] |
no_license
|
# Java 使用 Graphql , 搭建查询服务 - z69183787的专栏 - CSDN博客
2018年04月20日 15:23:55[OkidoGreen](https://me.csdn.net/z69183787)阅读数:373
[https://blog.csdn.net/qq362228416/article/details/50854980](https://blog.csdn.net/qq362228416/article/details/50854980)
#### 背景
随着react的开源,facebook相继开源了很多相关的项目,这些项目在他们内部已经使用了多年,其中引起我注意的就是本次讨论的是graphql,目前官方只有nodejs版,由于很多公司的后台技术栈都是java,所以便有了graphql的java版实现,在[github](https://github.com/andimarek/graphql-java)上可以找到,废话不多说,直接看代码吧,具体介绍还是去看官网吧,不然就跑题了。
#### GraphQLSchema
Schema相当于一个数据库,它有很多GraphQLFieldDefinition组成,Field相当于数据库表/视图,每个表/视图又由名称、查询参数、数据结构、数据组成.
1) 先定义一个数据结构(GraphQLOutputType)字段,然后定义一个初始化方法
```
private GraphQLOutputType userType;
private void initOutputType() {
/**
* 会员对象结构
*/
userType = newObject()
.name("User")
.field(newFieldDefinition().name("id").type(GraphQLInt).build())
.field(newFieldDefinition().name("age").type(GraphQLInt).build())
.field(newFieldDefinition().name("sex").type(GraphQLInt).build())
.field(newFieldDefinition().name("name").type(GraphQLString).build())
.field(newFieldDefinition().name("pic").type(GraphQLString).build())
.build();
}
```
2)再定义两个表/视图,它包括名称,查询参数,数据结构,以及数据检索器
```java
/**
* 查询单个用户信息
* @return
*/
private GraphQLFieldDefinition createUserField() {
return GraphQLFieldDefinition.newFieldDefinition()
.name("user")
.argument(newArgument().name("id").type(GraphQLInt).build())
.type(userType)
.dataFetcher(environment -> {
// 获取查询参数
int id = environment.getArgument("id");
// 执行查询, 这里随便用一些测试数据来说明问题
User user = new User();
user.setId(id);
user.setAge(id + 15);
user.setSex(id % 2);
user.setName("Name_" + id);
user.setPic("pic_" + id + ".jpg");
return user;
})
.build();
}
/**
* 查询多个会员信息
* @return
*/
private GraphQLFieldDefinition createUsersField() {
return GraphQLFieldDefinition.newFieldDefinition()
.name("users")
.argument(newArgument().name("page").type(GraphQLInt).build())
.argument(newArgument().name("size").type(GraphQLInt).build())
.argument(newArgument().name("name").type(GraphQLString).build())
.type(new GraphQLList(userType))
.dataFetcher(environment -> {
// 获取查询参数
int page = environment.getArgument("page");
int size = environment.getArgument("size");
String name = environment.getArgument("name");
// 执行查询, 这里随便用一些测试数据来说明问题
List<User> list = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
User user = new User();
user.setId(i);
user.setAge(i + 15);
user.setSex(i % 2);
user.setName(name + "_" + page + "_" + i);
user.setPic("pic_" + i + ".jpg");
list.add(user);
}
return list;
})
.build();
}
```
3)接着定义一个Schema,并将其初始化,它包含一个名称,以及一个或多个表/视图(Field)
```
private GraphQLSchema schema;
public GraphSchema() {
initOutputType();
schema = GraphQLSchema.newSchema().query(newObject()
.name("GraphQuery")
.field(createUsersField())
.field(createUserField())
.build()).build();
}
```
4)完成以上步骤之后,还需要定义一个model,类名不限,但是结构需要满足前面定义的数据结构,而且必须是public的
```
public class User {
private int id;
private int age;
private int sex;
private String name;
private String pic;
// getter, setter...
}
```
5)之后写一个main方法,来测试一下
```java
public static void main(String[] args) {
GraphQLSchema schema = new GraphSchema().getSchema();
String query1 = "{users(page:2,size:5,name:\"john\") {id,sex,name,pic}}";
String query2 = "{user(id:6) {id,sex,name,pic}}";
String query3 = "{user(id:6) {id,sex,name,pic},users(page:2,size:5,name:\"john\") {id,sex,name,pic}}";
Map<String, Object> result1 = (Map<String, Object>) new GraphQL(schema).execute(query1).getData();
Map<String, Object> result2 = (Map<String, Object>) new GraphQL(schema).execute(query2).getData();
Map<String, Object> result3 = (Map<String, Object>) new GraphQL(schema).execute(query3).getData();
// 查询用户列表
System.out.println(result1);
// 查询单个用户
System.out.println(result2);
// 单个用户、跟用户列表一起查
System.out.println(result3);
}
```
输出:
```
{users=[{id=0, sex=0, name=john_2_0, pic=pic_0.jpg}, {id=1, sex=1, name=john_2_1, pic=pic_1.jpg}, {id=2, sex=0, name=john_2_2, pic=pic_2.jpg}, {id=3, sex=1, name=john_2_3, pic=pic_3.jpg}, {id=4, sex=0, name=john_2_4, pic=pic_4.jpg}]}
{user={id=6, sex=0, name=Name_6, pic=pic_6.jpg}}
{user={id=6, sex=0, name=Name_6, pic=pic_6.jpg}, users=[{id=0, sex=0, name=john_2_0, pic=pic_0.jpg}, {id=1, sex=1, name=john_2_1, pic=pic_1.jpg}, {id=2, sex=0, name=john_2_2, pic=pic_2.jpg}, {id=3, sex=1, name=john_2_3, pic=pic_3.jpg}, {id=4, sex=0, name=john_2_4, pic=pic_4.jpg}]}
```
6)最后把main方法里面的代码放到web层,只需要定义一个query参数,很容易就把查询服务搭建好了,dataFetcher 里面还是调用原来的查询接口
7)引入maven依赖
```xml
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java</artifactId>
<version>2.0.0</version>
</dependency>
```
关于graphql查询什么定义,看看这个或许对你有帮助
json
```
{
id=6,
sex=0,
name="Name_6",
pic="pic_6.jpg"
}
```
query
```
{
id,
sex,
name,
pic
}
```
后面那部分,其实就是json字符串,去掉=和value的结果,还是可读的
### 结语
graphql 带了一种全新的思维方式,可以简化web api的开发,由客户端指定需要什么数据,服务端返回什么数据,减少不必要的流量传输,对移动端友好,还提供多种数据聚合查询,多个查询只是用一个请求,既满足api最小粒度,又满足前端需要,减少请求,提高性能。
|
Java
|
UTF-8
| 301 | 2.25 | 2 |
[] |
no_license
|
package br.newtonpaiva.poo.junit_demo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class CalculadoraTest {
@Test
public void test_Somar() {
var calc = new Calculadora();
assertEquals(5, calc.somar(2, 3));
}
}
|
Ruby
|
UTF-8
| 2,503 | 2.671875 | 3 |
[
"Apache-2.0",
"MIT",
"CC-BY-4.0",
"CC-BY-SA-4.0"
] |
permissive
|
# == Schema Information
#
# Table name: licenses
#
# id :integer not null, primary key
# display_description :text not null
# license_type :text not null
# url :text
# created_at :datetime not null
# updated_at :datetime not null
#
require 'test_helper'
class LicenseTest < ActiveSupport::TestCase
test 'valid license' do
license = licenses(:nocc)
assert(license.valid?)
end
test 'invalid without display_description' do
license = licenses(:nocc)
license.display_description = nil
assert(license.invalid?)
end
test 'invalid without license_type' do
license = licenses(:nocc)
license.license_type = nil
assert(license.invalid?)
end
test 'valid without url' do
license = licenses(:nocc)
license.url = nil
assert(license.valid?)
end
test 'need not have any theses' do
license = licenses(:ccbysa)
license.theses = []
assert(license.valid?)
end
test 'deleting a license will not delete its associated theses' do
license = licenses(:sacrificial)
thesis = theses(:two)
thesis_count = Thesis.count
license_count = License.count
assert_equal thesis.license, license
license.delete
assert_equal license_count - 1, License.count
assert_equal thesis_count, Thesis.count
end
test 'license types are mapped correctly' do
# Maps license text for no Creative Commons licenses
nocc = licenses(:nocc)
assert_equal 'In Copyright - Educational Use Permitted', nocc.map_license_type
# Does not map license text otherwise
ccby = licenses(:ccby)
assert_equal 'Attribution 4.0 International (CC BY 4.0)', ccby.map_license_type
ccbysa = licenses(:ccbysa)
assert_equal 'Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)', ccbysa.map_license_type
end
test 'license urls are mapped correctly' do
# Maps license url for no Creative Commons licenses
nocc = licenses(:nocc)
assert_equal 'https://rightsstatements.org/page/InC-EDU/1.0/', nocc.evaluate_license_url
# Returns regular license url otherwise
ccby = licenses(:ccby)
assert_equal 'https://creativecommons.org/licenses/by/4.0/', ccby.evaluate_license_url
ccbysa = licenses(:ccbysa)
assert_equal 'https://creativecommons.org/licenses/by-sa/4.0/', ccbysa.evaluate_license_url
nourl = licenses(:sacrificial)
assert_nil nourl.evaluate_license_url
end
end
|
JavaScript
|
UTF-8
| 1,555 | 2.609375 | 3 |
[] |
no_license
|
import React, { Component } from 'react';
import CanvasJSReact from './assets/canvasjs.react';
var CanvasJSChart = CanvasJSReact.CanvasJSChart;
/*
class CandlestickChart extends Component {
render() {
/!*const options = {
theme: "dark1", // "light1", "light2", "dark1", "dark2"
animationEnabled: true,
exportEnabled: true,
title:{
text: "Variaciones del precio del Dolar"
},
axisX: {
valueFormatString: "MMM"
},
axisY: {
includeZero:false,
prefix: "$",
title: "Price (in USD)"
},
data: [{
type: "candlestick",
showInLegend: true,
name: "Graficas de valores del dolar",
yValueFormatString: "$###0.00",
xValueFormatString: "MMMM YY",
dataPoints: [
// { x: new Date("2017-01-01"), y: [36.61, 38.45, 36.19, 36.82] }
]
}
]
}*!/
return (
<div>
<h1>React Candlestick Chart</h1>
<CanvasJSChart options = {this.props.options}
/!* onRef={ref => this.chart = ref} *!/
/>
{/!*You can get reference to the chart instance as shown above using onRef. This allows you to access all chart properties and methods*!/}
</div>
);
}
}
export default CandlestickChart;*/
|
Markdown
|
UTF-8
| 416 | 2.890625 | 3 |
[] |
no_license
|
# finance-ipsum
Generate filler text for your fin-tech web app mockup.
---
Visit the live website [Finance Ipsum](https://finance-ipsum.herokuapp.com/finance-ipsum)
There is also an API endpoint you can use to get up to 10 paragraphs of finance ipsum.
https://finance-ipsum.herokuapp.com/ipsum/#
Where # is between 1 and 10 inclusive. Any numbers above or below this will produce 1 or 10 paragraphs respectively.
|
C
|
UTF-8
| 8,822 | 3.359375 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
size_t HEAP_SIZE = 1028; // in bytes (e.g. 1kb of memory)
int WORD_SIZE = sizeof(int);
void* heap_ptr = NULL;
void* current_free_list = NULL;
void setup_heap() {
// The mmap system call asks the operating system to please put
// HEAP_SIZE
// memory into this process's address space. The resulting addresses
// start at the very beginning of heap space (more or less). This is
// the
// lowest-level interface to access memory without writing an
// operating
// system yourself. It returns memory in fairly large chunks (usually
// at least 1kb gets mapped at a time).
heap_ptr = mmap(NULL, HEAP_SIZE, PROT_READ | PROT_WRITE,
MAP_ANON | MAP_SHARED, -1, 0);
// Set the first word on the heap to hold the total size available.
// See above for
// a description of *(int*)ptr
*(int*)heap_ptr = HEAP_SIZE - WORD_SIZE;
*(void**)(heap_ptr+WORD_SIZE) = NULL;
current_free_list = heap_ptr;
}
/*
* Name: teardown_heap
* Parameter: None
* Function: This function is to tear the heap created in each tester
* function down.
* Return: None
*/
void teardown_heap(){
munmap(heap_ptr, HEAP_SIZE);
heap_ptr = NULL;
current_free_list = NULL;
}
/*
* Name: my_malloc
* Parameter: size - the size that needs to be allocated in heap
* Purpose: This function is to see whether there exists a free byte large
* enough to contain the the parameter size. If it has been found, change
* the value inside that address into odd number.
* Return: a void* representing the address of the newly created point
*/
void *my_malloc(size_t size){
//edge case to check the range
if (size <= 0) {
return NULL;
}
if (size > HEAP_SIZE) {
return NULL;
}
//make the size become the multiple of 4
if (size % WORD_SIZE != 0) {
size = size + (WORD_SIZE - (size % WORD_SIZE));
}
//enter the linked list of free bytes
void* cur = current_free_list;
void* old = NULL;
//check the address of cur
while(cur != NULL) {
//get teh size of current free byte
int cur_size = *(int*)cur;
//if that byte is too small to store the input size
//promote to next free-byte address
if (cur_size < size) {
old = cur;
cur = *(void**)(cur + WORD_SIZE);
continue;
}
//else, check the splitting and reusing cases
else {
//splitting case
if (size + WORD_SIZE + WORD_SIZE <= cur_size) {
//get the address of new free byte after
//splitting
void* addressOfNewFree = cur + size +
WORD_SIZE;
//if the first free byte in the list is used
if (cur == current_free_list) {
//change current_free_list's address
current_free_list = addressOfNewFree;
}
//otherwise, let the next pointer of last free
//byte point to new free byte
else {
*(void**)(old + WORD_SIZE) =
addressOfNewFree;
}
//change the content of new free byte
*(int*)addressOfNewFree = cur_size -
size - WORD_SIZE;
//change the content of new next pointer
*(void**)(addressOfNewFree + WORD_SIZE)=
*(void**)(cur + WORD_SIZE);
//set the content of original cur to odd
//number
*(int*)cur = size;
*(int*)cur |= 0x1;
return cur + WORD_SIZE;
}
//reusing the whole free byte
else {
//add the content by 1
*(int*)cur |= 0x1;
//store the new address
void* newAddress = *(void**)(cur + WORD_SIZE);
//check if the 1st free byte is used
if (cur == current_free_list) {
//current_free_list points to the new
//address
current_free_list = newAddress;
}
//otherwise, change the content of last
//"next pointer"
else {
*(void**)(old + WORD_SIZE) =
newAddress;
}
return cur + WORD_SIZE;
}
}
}
return NULL;
}
/*
* Name: my_free
* Parameter: ptr - a random address needed to be checked
* Purpose: This function is to check whether the input address can be
* freed from the existing heap.
* Return: 1 - successful; 0 - failure
*/
int my_free(void *ptr){
if(ptr == NULL) {
return 0;
}
//chech the range of ptr
if (ptr <= heap_ptr) {
return 0;
}
if (ptr > heap_ptr + HEAP_SIZE) {
return 0;
}
//see if the ptr is the multiple of 4
if ((int)ptr % WORD_SIZE != 0) {
return 0;
}
//check from the beginning
void* check = heap_ptr;
//keep checking
while (1) {
//get the size of each byte
int size = *(int*)check;
//see if the byte is occupied or not
if (size % WORD_SIZE == 0) {
//if unoccupied, promote to next byte
check = check + size + WORD_SIZE;
}
//if it is occupied
else {
//if it is at the correct position
if (ptr == check + WORD_SIZE) {
break;
}
//if we have passed the desired address
else if (ptr < check + WORD_SIZE) {
return 0;
}
//if we passed, keep checking next byte
else {
check = check + (size - 1) + WORD_SIZE;
}
}
//check the range of check pointer
if (check >= heap_ptr + HEAP_SIZE) {
return 0;
}
}
//if it passes all the checkings, set the value of occupied byte
//into a value of free byte
*(int*)(ptr - WORD_SIZE) &= ~0x1;
//make the next pointer point to last free byte
*(void**)ptr = current_free_list;
//renew the current_free_list
current_free_list = ptr - WORD_SIZE;
return 1;
}
/*
* Name: consolidate
* Parameter: None
* Purpose: consolidate all the adjacant free bytes inside the heap, and
* renew the address of "current_free_list" and "next*" if necessary.
* Return: None
*/
void consolidate(){
//enter from the beginning of heap
void* check = heap_ptr;
void* oldValAddress = NULL;
void* oldPtrAddress = NULL;
void* newValAddress = NULL;
void* newPtrAddress = NULL;
//set the range of check variable
while (check < heap_ptr + HEAP_SIZE) {
//get the size of each byte
int size = *(int*)check;
//if it is free byte
if (size % WORD_SIZE == 0) {
//get the address of next byte
newValAddress = check + size + WORD_SIZE;
//store the address of current byte
oldValAddress = check;
oldPtrAddress = check + WORD_SIZE;
//if the next bytes (one or more) are also free bytes
//and that address does not exceed the range of heap
while (*(int*)newValAddress % WORD_SIZE == 0 &&
newValAddress < heap_ptr + HEAP_SIZE) {
//renew the size of current free byte
*(int*)oldValAddress += *(int*)newValAddress
+ WORD_SIZE;
//the next pointer's address of next free byte
newPtrAddress = newValAddress + WORD_SIZE;
//renew the content of current next pointer
*(void**)oldPtrAddress =
*(void**)newPtrAddress;
//promote to check the next byte of next byte
newValAddress += *(int*)newValAddress +
WORD_SIZE;
}
//renew check to promote loop checking
check = newValAddress;
}
//if it is occupied byte, skip it
else {
check = check + (size - 1) + WORD_SIZE;
}
}
//entering the beginning of heap after consolidation
void* freeAdd = heap_ptr;
//reset current_free_list if it doesn't enter the loop below
current_free_list = NULL;
//the loop to reset current_free_list pointing to the 1st free byte
while (freeAdd < heap_ptr + HEAP_SIZE) {
int tempVal = *(int*)freeAdd;
if (tempVal % WORD_SIZE == 0) {
current_free_list = freeAdd;
break;
}
else {
freeAdd += (tempVal - 1) + WORD_SIZE;
}
}
}
/*
* Name: print_heap
* Parameter: None
* Purpose: print the whole heap
* Return: None
*/
void print_heap(){
int i;
for (i = 0; i < HEAP_SIZE; i = i + 4) {
printf("%10p:\t%d\t%#010x\n", heap_ptr + i,
*(int*)(heap_ptr + i), *(int*)(heap_ptr + i));
}
}
/*
* Name: free_space
* Parameter: None
* Purpose: This function is to get the total number of free space
* Return: num - the total number of free space
*/
int free_space(){
//enter the free list
void* count = current_free_list;
int num = 0;
//adding the value store in each free-byte address
while (count != NULL) {
num += *(int*)count;
count = *(void**)(count + WORD_SIZE);
}
return num;
}
/*
* Name: live_data
* Parameter: None
* Purpose: This function is to calculate the total number of occupied bytes
* in the heap.
* Return: count - the total number of occupied bytes
*/
int live_data() {
//get the beginning of the heap_ptr
void* data = heap_ptr;
int count = 0;
//see if the address of data is outside the range
while (data < heap_ptr + HEAP_SIZE) {
//store the number of bytes
int size = *(int*)data;
//if it is free byte, skip to next byte
if (size % WORD_SIZE == 0) {
data = data + size + WORD_SIZE;
}
//if it is occupied byte, plus count by (size - 1)
//and then promote to check next byte
else {
count += (size - 1);
data = data + (size - 1) + WORD_SIZE;
}
}
return count;
}
|
Java
|
UTF-8
| 10,664 | 3.65625 | 4 |
[] |
no_license
|
package correcter;
public class StringProcessor {
/*
* Converts a normal string to a hex Array
*/
public String[] stringToHex(String stringToHex) {
char[] hexArray = stringToHex.toCharArray();
String[] hexStringArray = new String[stringToHex.length()];
for (int i = 0; i < hexArray.length; i++) {
hexStringArray[i] = Integer.toHexString(hexArray[i]);
}
return hexStringArray;
}
public String hexStringToText(String stringHex) {
String[] hexArray = stringHex.split(" ");
StringBuilder text = new StringBuilder();
for (String hex : hexArray) {
text.append((char) Integer.parseInt(hex, 16));
}
return text.toString();
}
/*
* Returns a string with a more readable format of the hex String array
*/
public String formatHexArray(String[] hexStringArray) {
StringBuilder auxString = new StringBuilder();
for (String s : hexStringArray) {
auxString.append(s).append(" ");
}
return auxString.toString();
}
/*
* Creates an array of bytes from a given String
*/
public byte[] stringToByteArray(String string) {
char[] arrayString = string.toCharArray();
byte[] byteArray = new byte[arrayString.length];
for (int i = 0; i < arrayString.length; i++) {
byteArray[i] = (byte)arrayString[i];
}
return byteArray;
}
/*
* Returns a byte representation as string, with 8 bits;
*/
public String byteToString(byte b) {
StringBuilder bString = new StringBuilder();
bString.append(Integer.toBinaryString(b));
if (bString.length() > 8) {
bString.delete(0, 24);
}
while (bString.length() < 8) {
bString.insert(0, "0");
}
return bString.toString();
}
/*
* Returns a string with a more readable format of the byte array
*/
public String byteArrayToString(byte[] byteArray) {
StringBuilder auxString = new StringBuilder();
for (byte b : byteArray) {
auxString.append(byteToString(b)).append(" ");
}
return auxString.toString();
}
/*
* Returns a string with a more readable format of a String array
*/
public String stringFromStringArray(String[] StringArray) {
StringBuilder auxString = new StringBuilder();
for (String value : StringArray) {
auxString.append(value).append(" ");
}
auxString.replace(auxString.length() - 1, auxString.length() - 1, "");
return auxString.toString();
}
/*
* Returns an array of bytes with parity
*/
public String[] parityBytes(String expandedBytes) {
String[] expandedByteArray = expandedBytes.split(" ");
String[] parityByteArray = new String[expandedByteArray.length];
for (int byteIndex = 0; byteIndex < expandedByteArray.length; byteIndex++) {
parityByteArray[byteIndex] = byteParityHamming(expandedByteArray[byteIndex]);
}
return parityByteArray;
}
/*
* Returns an hex String array from a byte String array
*/
public String[] byteArrayToHexArray(String[] byteArray) {
String[] hexArray = new String[byteArray.length];
byte[] byteArrayAux = new byte[byteArray.length];
for (int index = 0; index < byteArray.length; index++) {
byteArrayAux[index] = (byte) Integer.parseInt(byteArray[index], 2);
}
for (int index = 0; index < byteArray.length; index++) {
hexArray[index] = String.format("%02X", byteArrayAux[index]);
}
return hexArray;
}
/*
* Corrects a String array of bytes
*/
public String[] correctByteStrings(String[] byteStringArrays) {
String[] correctByteStrings = new String[byteStringArrays.length];
for (int index = 0; index < correctByteStrings.length; index++) {
correctByteStrings[index] = correctByte(byteStringArrays[index]);
}
return correctByteStrings;
}
/*
* Corrects the bytes using Hamming correction.
*/
public String correctByte(String byteString) {
StringBuilder correctByte = new StringBuilder();
int bit1Parity = Character.getNumericValue(byteString.charAt(0));
int bit2Parity = Character.getNumericValue(byteString.charAt(1));
int bit1Significant = Character.getNumericValue(byteString.charAt(2));
int bit3Parity = Character.getNumericValue(byteString.charAt(3));
int bit2Significant = Character.getNumericValue(byteString.charAt(4));
int bit3Significant = Character.getNumericValue(byteString.charAt(5));
int bit4Significant = Character.getNumericValue(byteString.charAt(6));
int lastBit = Character.getNumericValue(byteString.charAt(7));
int parity1 = bit1Significant ^ bit2Significant ^ bit4Significant;
int parity2 = bit1Significant ^ bit3Significant ^ bit4Significant;
int parity3 = bit2Significant ^ bit3Significant ^ bit4Significant;
if (lastBit != 0) {
correctByte.append(byteString, 0, 7);
correctByte.append("0");
return correctByte.toString();
} else if (bit1Parity != parity1 && bit2Parity != parity2 && bit3Parity != parity3) {
correctByte.append(byteString, 0, 6);
correctByte.append(switchBit(bit4Significant));
correctByte.append("0");
return correctByte.toString();
}else if (bit1Parity != parity1 && bit2Parity != parity2) {
correctByte.append(byteString, 0, 2);
correctByte.append(switchBit(bit1Significant));
correctByte.append(byteString, 3, 8);
return correctByte.toString();
} else if (bit1Parity != parity1 && bit3Parity != parity3) {
correctByte.append(byteString, 0, 4);
correctByte.append(switchBit(bit2Significant));
correctByte.append(byteString, 5, 8);
return correctByte.toString();
} else if (bit2Parity != parity2 && bit3Parity != parity3) {
correctByte.append(byteString, 0, 5);
correctByte.append(switchBit(bit3Significant));
correctByte.append(byteString, 6, 8);
return correctByte.toString();
} else if (bit1Parity != parity1) {
correctByte.append(parity1);
correctByte.append(byteString, 1, 8);
return correctByte.toString();
} else if (bit2Parity != parity2) {
correctByte.append(bit1Parity).append(parity2);
correctByte.append(byteString, 2, 8);
return correctByte.toString();
} else if (bit3Parity != parity3) {
correctByte.append(byteString, 0, 3);
correctByte.append(parity3);
correctByte.append(byteString, 4, 8);
return correctByte.toString();
} else {
return "error not found";
}
}
private String switchBit(int bit) {
if (bit == 0) {
return "1";
} else {
return "0";
}
}
/*
* Decodes the full corrected string by removing parity bits.
*/
public String decodedByteString(String byteString) {
byteString = byteString.replace(" ", "");
StringBuilder decodedBytes = new StringBuilder();
int bitEnd = 0;
try {
for (int bitIndex = 0; bitIndex < byteString.length(); bitIndex++) {
bitIndex = bitIndex + 2;
decodedBytes.append(byteString.charAt(bitIndex));
bitIndex = bitIndex + 2;
decodedBytes.append(byteString, bitIndex, bitIndex + 3);
bitIndex = bitIndex + 3;
bitEnd++;
if (bitEnd == 2) {
decodedBytes.append(" ");
bitEnd = 0;
}
}
} catch (IndexOutOfBoundsException ignored) {}
return decodedBytes.toString();
}
/*
* Removes useless last 0 bits
*/
public String removeLastByte(String byteString) {
String[] bytes = byteString.split(" ");
StringBuilder cleanString = new StringBuilder();
if (!bytes[bytes.length - 1].contains("1")) {
for (int byteIndex = 0; byteIndex < bytes.length - 1 ; byteIndex++) {
cleanString.append(bytes[byteIndex]).append(" ");
}
return cleanString.deleteCharAt(cleanString.length() - 1).toString();
} else {
return byteString;
}
}
/**
* @param inputByteArray Transforms a byteArray in an expansion of bits compatible with hamming correction
* @return String
*/
public String expandedBytesHamming(byte[] inputByteArray) {
String bitString = byteArrayToString(inputByteArray).replace(" ", "");
StringBuilder expandedByteHamming = new StringBuilder();
int bitNumber = 0;
for (char bit : bitString.toCharArray()) {
if (bitNumber == 0) {
expandedByteHamming.append("..").append(bit).append(".");
bitNumber++;
} else if (bitNumber == 3) {
expandedByteHamming.append(bit).append(". ");
bitNumber = 0;
} else {
expandedByteHamming.append(bit);
bitNumber++;
}
}
return expandedByteHamming.toString();
}
/*
* Replaces the dots into bits of parity according to the Hamming correction
*/
public String byteParityHamming(String byteExpanded) {
StringBuilder parityHamming = new StringBuilder();
int significantBit1 = Character.getNumericValue(byteExpanded.charAt(2));
int significantBit2 = Character.getNumericValue(byteExpanded.charAt(4));
int significantBit3 = Character.getNumericValue(byteExpanded.charAt(5));
int significantBit4 = Character.getNumericValue(byteExpanded.charAt(6));
int parity1 = significantBit1 ^ significantBit2 ^ significantBit4;
parityHamming.append(parity1);
int parity2 = significantBit1 ^ significantBit3 ^ significantBit4;
parityHamming.append(parity2).append(significantBit1);
int parity3 = significantBit2 ^ significantBit3 ^ significantBit4;
parityHamming.append(parity3).append(significantBit2).append( significantBit3).append(significantBit4).append("0");
return parityHamming.toString();
}
}
|
Ruby
|
UTF-8
| 7,161 | 2.546875 | 3 |
[] |
no_license
|
require "test_helper"
class TeamMemberTest < MiniTest::Unit::TestCase
def setup
DatabaseCleaner.start
end
def teardown
DatabaseCleaner.clean
end
def test
skip 'Not implemented'
end
def test_good_construction_and_save
a_person = Person.sample_person_alfred_with_email
a_person.save!
a_team = Team.sample_single_chair_team
a_team.save!
a_team_member = TeamMember.new(a_person, a_team)
a_team_member.save!
a_team_member.reload
assert(a_team_member.persisted?)
assert(a_team_member.is_role_member?)
assert(a_team_member.has_valid_email?)
refute(a_team_member.has_nominate_privilege?)
refute(a_team_member.has_delete_privilege?)
assert_equal(a_team_member.class_name, "TeamMember")
refute_empty(TeamMember.all)
end
def test_duplicate_construction_with_same_person_and_team
a_person = Person.sample_person_alfred_with_email
a_person.save!
a_team = Team.sample_single_chair_team
a_team.save!
a_team_member = TeamMember.new(a_person, a_team)
a_team_member.save!
assert_raises(BusinessRuleError) { TeamMember.new(a_person, a_team) }
end
def test_bad_construction_with_nil_person
a_team = Team.sample_single_chair_team
a_team.save!
assert_raises(BusinessRuleError) { TeamMember.new(nil, a_team) }
end
def test_bad_construction_with_wrong_type_person
a_team = Team.sample_single_chair_team
a_team.save!
assert_raises(BusinessRuleError) { TeamMember.new(a_team, a_team) }
end
def test_bad_construction_with_nil_team
a_person = Person.sample_person_alfred_with_email
a_person.save!
assert_raises(BusinessRuleError) { TeamMember.new(a_person, nil) }
end
def test_bad_construction_with_wrong_type_team
a_person = Person.sample_person_alfred_with_email
a_person.save!
assert_raises(BusinessRuleError) { TeamMember.new(a_person, a_person) }
end
def test_bad_construction_with_person_without_email
a_person = Person.sample_person_tony_without_email
a_person.save!
a_team = Team.sample_single_chair_team
a_team.save!
assert_raises(BusinessRuleError) { TeamMember.new(a_person, a_team) }
end
def test_adding_person_to_existing_team_member
a_team_member = TeamMember.sample_chair
a_team_member.save!
a_person = Person.sample_person_tony_without_email
a_person.email = "tony@tiger.com"
a_person.save!
assert_raises(BusinessRuleError) { a_team_member.add_person(a_person) }
end
def test_adding_team_to_existing_team_member
a_team_member = TeamMember.sample_chair
a_team_member.save!
a_team = Team.sample_no_chair_team
a_team.save!
assert_raises(BusinessRuleError) { a_team_member.add_team(a_team) }
end
def test_object_inheritance_from_person
a_team_member = TeamMember.sample_chair
a_person = a_team_member.person
assert_equal(a_team_member.name, a_person.name)
assert_equal(a_team_member.title, a_person.title)
assert_equal(a_team_member.email, a_person.email)
assert_equal(a_team_member.has_valid_email?, a_person.has_valid_email?)
end
def test_getting_nominations
a_nomination = Nomination.sample_document_nomination
a_nomination.save!
a_team_member = a_nomination.team_member
a_team_member.reload
refute_empty(a_team_member.nominations)
end
def test_good_eradication
a_team_member = TeamMember.sample_chair
a_team_member.save!
a_team_member.eradicate
assert_raises(BusinessRuleError) { a_team_member.save! }
a_person = a_team_member.person
a_team = a_team_member.team
refute(a_team.team_member_for(a_person))
a_person.reload
a_team.reload
refute(a_team.team_member_for(a_person))
end
def test_eradication_with_nominations
a_nomination = Nomination.sample_document_nomination
a_nomination.save!
a_team_member = a_nomination.team_member
assert_raises(BusinessRuleError) { a_team_member.eradicate }
end
def test_making_team_member_chair_on_team_without_chairs
a_team = Team.sample_no_chair_team
a_team.save!
a_person = Person.sample_person_alfred_with_email
a_person.save!
a_team_member = TeamMember.new(a_person, a_team)
a_team_member.save!
assert_raises(BusinessRuleError) { a_team_member.make_chair }
end
def test_roles_and_privileges
a_team_member = TeamMember.sample_chair
a_team_member.make_chair
assert(a_team_member.is_role_chair?)
assert(a_team_member.has_nominate_privilege?)
assert(a_team_member.has_delete_privilege?)
a_team_member.make_member
assert(a_team_member.is_role_member?)
refute(a_team_member.has_nominate_privilege?)
refute(a_team_member.has_delete_privilege?)
a_team_member.make_admin
assert(a_team_member.is_role_admin?)
assert(a_team_member.has_nominate_privilege?)
refute(a_team_member.has_delete_privilege?)
end
def test_revoking_privileges
a_team_member = TeamMember.sample_chair
assert(a_team_member.has_nominate_privilege?)
assert(a_team_member.has_delete_privilege?)
a_team_member.revoke_nominate_privilege
a_team_member.revoke_delete_privilege
refute(a_team_member.has_nominate_privilege?)
refute(a_team_member.has_delete_privilege?)
end
def test_max_nominations
a_team_member = TeamMember.sample_no_nominate
a_team_member.grant_nominate_privilege
a_team_member.save!
5.times do |i|
a_document = Document.new("Document #{i}")
a_document.save!
a_nomination = a_document.nominate(a_team_member)
a_nomination.save!
end
assert(a_team_member.nominations.size == 5)
a_document = Document.new("Document 6")
a_document.save!
assert_raises(BusinessRuleError) { a_document.nominate(a_team_member) }
end
def test_max_chair_nominations
a_team_member = TeamMember.sample_chair
a_team_member.grant_nominate_privilege
a_team_member.save!
10.times do |i|
a_document = Document.new("Document #{i}")
a_document.save!
a_nomination = a_document.nominate(a_team_member)
a_nomination.save!
end
assert(a_team_member.nominations.size == 10)
a_document = Document.new("Document 11")
a_document.save!
assert_raises(BusinessRuleError) { a_document.nominate(a_team_member) }
end
def test_no_nomination_privilege
a_team_member = TeamMember.sample_no_nominate
a_team_member.save!
a_document = Document.sample_normal
a_document.save!
assert_raises(BusinessRuleError) { a_document.nominate(a_team_member) }
end
def test_equals
a_team_member = TeamMember.sample_chair
a_team_member.save!
a_person = a_team_member.person
a_team = Team.sample_single_chair_team
a_team.save!
z_team_member = TeamMember.new(a_person, a_team)
z_team_member.save!
assert(a_team_member == a_team_member)
refute(a_team_member.eql?(z_team_member))
end
def test_to_s
a_team_member = TeamMember.sample_chair
assert_match(/TeamMember/, a_team_member.to_s)
end
def test_as_json
a_team_member = TeamMember.sample_chair
a_team_member.save!
refute_empty(a_team_member.as_json)
end
end
|
C++
|
UTF-8
| 1,545 | 2.546875 | 3 |
[] |
no_license
|
#ifndef __SELECT_AND_TEST_HPP__
#define __SELECT_AND_TEST_HPP__
#include "gtest/gtest.h"
#include "select_and.hpp"
#include "spreadsheet.hpp"
#include "select_mock.hpp"
#include <string>
//Spreadsheet sheet;
//// sheet.set_column_names({"First","Last","Age","Major"});
//// sheet.add_row({"","","",""}); //empty row, row = 0
//// sheet.add_row({"Brian","Becker","21","computer science"});//normal row, row = 1
//// sheet.add_row({"Bri","Beck","2","comp sci"});//normal row abbrev, row = 2
//// sheet.add_row({"CaBrio","CaBecko","Ca2o","Macomp scio"});//normal row appended, row = 3
//// sheet.add_row({" ","\n ","\t","\t\n "});//spacing row, row = 4
//
TEST(select_AndTest, Select_AndTF) {
Spreadsheet sheet;
Select* selectMock1 = new Select_MockFalse();
Select* selectMock2 = new Select_MockTrue();
Select_And* test = new Select_And(selectMock1, selectMock2);
EXPECT_FALSE(test->select(&sheet, 2));
delete test;
}
TEST(select_AndTest, Select_AndTT) {
Spreadsheet sheet;
Select* selectMock1 = new Select_MockTrue();
Select* selectMock2 = new Select_MockTrue();
Select_And* test = new Select_And(selectMock1, selectMock2);
EXPECT_TRUE(test->select(&sheet, 2));
delete test;
}
TEST(select_AndTest, Select_AndFF) {
Spreadsheet sheet;
Select* selectMock1 = new Select_MockFalse();
Select* selectMock2 = new Select_MockFalse();
Select_And* test = new Select_And(selectMock1, selectMock2);
EXPECT_FALSE(test->select(&sheet, 2));
delete test;
}
#endif
|
JavaScript
|
UTF-8
| 1,087 | 2.59375 | 3 |
[] |
no_license
|
#pragma strict
var cam1 : Camera;
var cam2 : Camera;
var cockpit : GameObject;
function Start () {
Screen.showCursor = false;
cam1.enabled = true;
cam2.enabled = false;
cockpit.active = false;
}
function Update () {
//get the SCREEN position of the mouse
var mousePos = Input.mousePosition;
//create a virtual 'plane' 10 further in from the camera
mousePos.z = 100;
//translate from pixels to world coordinates
if (Input.GetKeyDown(KeyCode.C)){
cam1.enabled = !cam1.enabled;
cam2.enabled = !cam2.enabled;
if(cam1.enabled == true){
//var point = Camera.mainCamera.ScreenToWorldPoint(mousePos)
cockpit.active = false;
//GameObject.FindGameObjectWithTag("Ship").gameObject.renderer.enabled = true;
}
else
{
//var point = Camera.mainCamera.ScreenToWorldPoint(mousePos)
cockpit.active = true;
// GameObject.FindGameObjectWithTag("Ship").gameObject.renderer.enabled = false;
}
}
var point = Camera.mainCamera.ScreenToWorldPoint(mousePos);
//set the position of the cursor
transform.position = point;
}
|
Java
|
UTF-8
| 699 | 1.773438 | 2 |
[] |
no_license
|
package com.jwell.classifiedProtection.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.jwell.classifiedProtection.entry.Organization;
import com.jwell.classifiedProtection.entry.vo.OrganizationPagingVo;
/**
* <p>
* 单位组织 服务类
* </p>
*
* @author RonnieXu
* @since 2019-10-22
*/
public interface IOrganizationService extends IService<Organization> {
/**
* 单位组织分页列表
*
* @param iPage
* @param organization
* @return
*/
IPage<OrganizationPagingVo> selectOrganizationVoPaging(IPage<OrganizationPagingVo> iPage, Organization organization);
}
|
PHP
|
UTF-8
| 976 | 2.8125 | 3 |
[] |
no_license
|
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
$qty_course="[5, 3, 1, 4, 5]";
$len_course=5;
echo "qty_course: ".$qty_course[0];
echo "<br />";
// for ($length = 0;isset($qty_course[$length]);$length++) ;
// echo "length: ".$qty_course[(int)$length-1];
echo "<br />";
$res=array_map('trim', explode(',',$qty_course));
print_r($res);
if ($res[0][0]==="[" && strpos($res[count($res)-1], ']') && count($res)==$len_course) {
$res[0]=str_replace('[', '', $res[0]);
$res[count($res)-1]=str_replace(']', '', $res[count($res)-1]);
} else {
for ($i = 0; $i < count($res); $i++) {
$res[$i]=1;
}
}
echo "<br />";
print_r($res);
$stop=0;
|
Java
|
UTF-8
| 2,158 | 2.703125 | 3 |
[] |
no_license
|
package eav.dao;
import eav.manager.ObjectManager;
import eav.model.Object;
import eav.names.AttributeName;
import eav.names.ObjectTypeName;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class UserDao {
private ObjectManager objectManager;
public UserDao(Connection connection) throws SQLException {
this.objectManager = new ObjectManager(connection);
}
public Object getUser(String login, String password) throws SQLException {
List<Object> users = objectManager.getObjectsByObjectTypeId(ObjectTypeName.TYPE_ID_USERS);
Object user = null;
for (Object object : users) {
for (int j = 0; j < object.getAttributes().size(); j++) {
if ((object.getAttributes().get(j).getAttributeTypeId().equals(AttributeName.ATTR_TYPE_ID_USERS_LOGIN)
&& object.getAttributes().get(j).getValue().equals(login))
|| (object.getAttributes().get(j).getAttributeTypeId().equals(AttributeName.ATTR_TYPE_ID_USERS_PASSWORD)
&& object.getAttributes().get(j).getValue().equals(password))
) {
user = objectManager.getObjectById(object.getObjectId());
}
}
}
return user;
}
public Object getUserByLogin(String login) throws SQLException {
List<Object> users = objectManager.getObjectsByObjectTypeId(ObjectTypeName.TYPE_ID_USERS);
Object user = null;
for (Object object : users) {
for (int j = 0; j < object.getAttributes().size(); j++) {
if ((object.getAttributes().get(j).getAttributeTypeId().equals(AttributeName.ATTR_TYPE_ID_USERS_LOGIN)
&& object.getAttributes().get(j).getValue().equals(login))
) {
user = objectManager.getObjectById(object.getObjectId());
}
}
}
return user;
}
public List<Object> getAllStudents() throws SQLException {
return objectManager.getObjectsByObjectTypeId(ObjectTypeName.TYPE_ID_USERS);
}
}
|
PHP
|
UTF-8
| 585 | 2.875 | 3 |
[] |
no_license
|
/*Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size. Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the previous one exactly by 1. He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of additional statues needed.*/
function makeArrayConsecutive2($statues) {
$max = max($statues);
$min = min($statues);
return ((($max - $min) + 1) - sizeof($statues));
}
|
Swift
|
UTF-8
| 1,133 | 3.3125 | 3 |
[] |
no_license
|
//
// PrimitiveButton.swift
// The Gram
//
// Created by Tommy Goossens on 14/03/2020.
// Copyright © 2020 Tommy Goossens. All rights reserved.
//
import SwiftUI
struct PrimitiveButton: ButtonStyle {
let isCancelButton: Bool
let colorCancel: Color = Color.red
let colorConfirm: Color = Color.green
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.foregroundColor(.white)
.padding()
.background(RoundedRectangle(cornerRadius: 5).fill(self.isCancelButton ? self.colorCancel : self.colorConfirm))
.compositingGroup()
.shadow(color: .black, radius: 3)
.opacity(configuration.isPressed ? 0.5 : 1.0)
}
}
struct PrimitiveButton_Previews: PreviewProvider {
static var previews: some View {
VStack{
Button(action: {print("button")}, label: {Text("press me")}).buttonStyle(PrimitiveButton(isCancelButton: false)).padding()
Button(action: {print("button")}, label: {Text("press me")}).buttonStyle(PrimitiveButton(isCancelButton: true)).padding()
}
}
}
|
Java
|
UTF-8
| 615 | 1.703125 | 2 |
[] |
no_license
|
package com.tencent.mm.plugin.backup.b;
import com.tencent.mm.lan_cs.Client.a;
import java.io.IOException;
class a$2 implements a {
final /* synthetic */ a gRT;
a$2(a aVar) {
this.gRT = aVar;
}
public final void onRecv(String str, int i, byte[] bArr) {
a.a(this.gRT, str);
a.a(this.gRT, i);
try {
a.a(this.gRT, bArr);
} catch (IOException e) {
a.a(this.gRT, 10006, ("client readErr:" + e.toString()).getBytes());
}
}
public final void Fh() {
a.a(this.gRT, 10011, "client onDisconnect".getBytes());
}
}
|
C#
|
UTF-8
| 1,067 | 3.40625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GuiaEjercicios
{
class Ejercicio38
{
public void Main()
{
Ejercicio38 obj1;
obj1 = new Ejercicio38();
obj1.Ejer38();
}
public void Ejer38()
{
int i, impar;
Console.WriteLine("Algoritmo que me imprime los numeros Impares");
Console.WriteLine("Comprendidos entre 201 y 499");
for (i = 0; i <= 500; i++)
{
impar = i % 2;
if (impar == 1)
{
if (i >= 201 && i <= 499)
{
Console.WriteLine("Numero " + i);
}
}
}
Console.WriteLine("Algoritmo que me imprime los numeros Impares");
Console.WriteLine("Comprendidos entre 201 y 499");
Console.ReadKey();
}
}
}
|
Markdown
|
UTF-8
| 5,002 | 2.953125 | 3 |
[
"Apache-2.0"
] |
permissive
|
+++
title = "Configuring Timeouts"
description = "Configure Linkerd to automatically fail requests that take too long."
+++
To limit how long Linkerd will wait before failing an outgoing request to
another service, you can configure timeouts. Timeouts specify the maximum amount
of time to wait for a response from a remote service to complete after the
request is sent. If the timeout elapses without receiving a response, Linkerd
will cancel the request and return a [504 Gateway Timeout] response.
Timeouts can be specified either [using HTTPRoutes](#using-httproutes) or [using
legacy ServiceProfiles](#using-serviceprofiles). Since [HTTPRoute] is a newer
configuration mechanism intended to replace [ServiceProfile]s, prefer the use of
HTTPRoute timeouts unless a ServiceProfile already exists for the Service.
## Using HTTPRoutes
Linkerd supports timeouts as specified in [GEP-1742], for [outbound
HTTPRoutes](../../features/httproute/#inbound-and-outbound-httproutes)
with Service parents.
{{< warning >}}
Support for [GEP-1742](https://gateway-api.sigs.k8s.io/geps/gep-1742/) has not
yet been implemented by the upstream Gateway API HTTPRoute resource. The GEP has
been accepted, but it has not yet been added to the definition of the HTTPRoute
resource. This means that HTTPRoute timeout fields can currently be used only in
HTTPRoute resources with the `policy.linkerd.io` API group, *not* the
`gateway.networking.k8s.io` API group.
When the [GEP-1742](https://gateway-api.sigs.k8s.io/geps/gep-1742/) timeout
fields are added to the upstream resource definition, Linkerd will support
timeout configuration for HTTPRoutes with both API groups.
See [the HTTPRoute reference
documentation](../../reference/httproute/#linkerd-and-gateway-api-httproutes)
for details on the two versions of the HTTPRoute resource.
{{< /warning >}}
Each [rule](../../reference/httproute/#httprouterule) in an [HTTPRoute] may
define an optional [`timeouts`](../../reference/httproute/#httproutetimeouts)
object, which can define `request` and/or `backendRequest` fields:
- `timeouts.request` specifies the *total time* to wait for a request matching
this rule to complete (including retries). This timeout starts when the proxy
receives a request, and ends when successful response is sent to the client.
- `timeouts.backendRequest` specifies the time to wait for a single request to a
backend to complete. This timeout starts when a request is dispatched to a
[backend](../../reference/httproute/#httpbackendref), and ends when a response
is received from that backend. This is a subset of the `timeouts.request`
timeout. If the request fails and is retried (if applicable), the
`backendRequest` timeout will be restarted for each retry request.
Timeout durations are specified specified as strings using the [Gateway API
duration format] specified by
[GEP-2257](https://gateway-api.sigs.k8s.io/geps/gep-2257/)
(e.g. 1h/1m/1s/1ms), and must be at least 1ms. If either field is unspecified or
set to 0, the timeout configured by that field will not be enforced.
For example:
```yaml
spec:
rules:
- matches:
- path:
type: RegularExpression
value: /authors/[^/]*\.json"
method: GET
timeouts:
request: 600ms
backendRequest: 300ms
```
## Using ServiceProfiles
Each [route](../../reference/service-profiles/#route) in a [ServiceProfile] may
define a request timeout for requests matching that route. This timeout secifies
the maximum amount of time to wait for a response (including retries) to
complete after the request is sent. If unspecified, the default timeout is 10
seconds.
```yaml
spec:
routes:
- condition:
method: HEAD
pathRegex: /authors/[^/]*\.json
name: HEAD /authors/{id}.json
timeout: 300ms
```
Check out the [timeouts section](../books/#timeouts) of the books demo for
a tutorial of how to configure timeouts using ServiceProfiles.
## Monitoring Timeouts
Requests which reach the timeout will be canceled, return a [504 Gateway
Timeout] response, and count as a failure for the purposes of [effective success
rate](../configuring-retries/#monitoring-retries). Since the request was
canceled before any actual response was received, a timeout will not count
towards the actual request volume at all. This means that effective request
rate can be higher than actual request rate when timeouts are configured.
Furthermore, if a response is received just as the timeout is exceeded, it is
possible for the request to be counted as an actual success but an effective
failure. This can result in effective success rate being lower than actual
success rate.
[HTTPRoute]: ../../features/httproute/
[ServiceProfile]: ../../features/service-profiles/
[504 Gateway Timeout]:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504
[GEP-1742]: https://gateway-api.sigs.k8s.io/geps/gep-1742/
[Gateway API duration format]:
https://gateway-api.sigs.k8s.io/geps/gep-2257/#gateway-api-duration-format
|
C++
|
UTF-8
| 5,994 | 2.59375 | 3 |
[
"Zlib"
] |
permissive
|
#include "../include/core.hpp"
#include "../include/parser.hpp"
#include "../include/ast/astidentifier.hpp"
using namespace numbat::lexer;
using namespace numbat::parser;
void addOperator (ParsingContext * context, int precidence, bool ltr, const string & pattern, OperatorDecleration::OperatorParser parser, OperatorDecleration::DefaultImplementation defImp = nullptr) {
OperatorDecleration oppdec (precidence, ltr, pattern, nullptr, parser, defImp);
if (context->operators.find (pattern) != context->operators.end ()) {
return;
}
shared_ptr <OperatorDecleration> opp (new OperatorDecleration (oppdec));
context->operators [pattern] = opp;
for (const string & s : opp->getSymbols ()) {
if (s != " ") {
context->operatorsByFirstToken.insert (std::make_pair (s.substr(0,1), opp));
break;
}
}
for (const string & s : opp->getSymbols ()) {
if (s != " ") {
context->keywords.insert(s);
}
}
}
void addBlock (ParsingContext * context, const string & open, const string & close) {
context->blocks [open] = close;
}
AbstractSyntaxTree * ast = new AbstractSyntaxTree ();
ParsingContext * context = getContext (ast);
void parseTest (const string & code) {
auto program = lex (code);
Position pos (program.begin (), findToken (program.begin (), program.end (), TOKEN::semicolon));
std::cout << parseExpression (pos, ast)->toString () << std::endl;
}
void parseBodyTest (const string & code) {
auto program = lex (code);
Position pos (program.begin (), findToken (program.begin (), program.end (), TOKEN::eof));
std::cout << parseBody (pos, ast)->toString () << std::endl;
}
int main () {
addBlock (context, "(", ")");
addBlock (context, "[", "]");
addBlock (context, "{", "}");
// addBlock (context, "?", ":");
addOperator (context, 100, true, "{}", parseBlockOperator);
addOperator (context, 100, true, "{ }", parseBlockOperator);
addOperator (context, 100, true, "( )", parseSubExpression);
addOperator (context, 100, true, " ( )", parseCall);
addOperator (context, 100, true, " ()", parseCall);
//addOperator (context, 100, true, "[ ] ");
addOperator (context, 100, true, " [ ] ", parseArrayDecleration);
addOperator (context, 100, true, " []", parseIndex);
addOperator (context, 100, true, " [ ]", parseIndex);
addOperator (context, 300, false, "- ", parseUnary, defNegation);
addOperator (context, 300, false, "! ", parseUnary, defNegation);
addOperator (context, 500, true, " + ", parseBinary, defArithmetic);
addOperator (context, 500, true, " - ", parseBinary, defArithmetic);
// addOperator (context, 500, true, " ~ ", parseBinary, defConcat);
//addOperator (context, 1100, true, " or ", parseBinary, defLogic);
addOperator (context, 1400, true, " , ", parseComma);
//addOperator (context, 1500, true, " ? : ", parseTernaryOperator);
addOperator (context, 1600, false, " = ", parseAssignmentOperator);
//addOperator (context, 1700, false, "if( ) ");
//addOperator (context, 1700, false, "if( ) else ");
//addOperator (context, 1700, false, "lock( ) ");
addOperator (context, 1700, false, "while( ) ", parseWhileLoop);
if (!createRawType (ast, "int32", 32, NumbatRawType::SIGNED)) return 1;
if (!createRawType (ast, "uint64", 64, NumbatRawType::UNSIGNED)) return 1;
if (!createRawType (ast, "double", 64, NumbatRawType::FLOAT)) return 1;
ASTnode intType (new ASTtype (0, false, false, getType (ast, "int32")));
for (char c = 'a'; c <= 'z'; ++c) {
createVariable (ast, intType, nullptr, (string () + c), false, false);
}
parseTest ("3 + 5");
parseTest ("3.0 + 5");
parseTest ("3 + 5.0");
parseTest ("3.0 + 5.0");
parseTest ("a = 3");
parseTest ("a = 3 + 5");
parseTest ("a = b - 3 + 5");
parseTest ("a = b = c + 2 - 5 + 49");
parseTest ("n = 4 + 6 + g");
parseTest ("n = 4 + -6 + g");
parseTest ("n = 4 + (6 + g)");
// parseTest ("n = a ? b : c");
// parseTest ("n = a ? b = f : c");
// parseTest ("n = 7 + (a - 8 ? b - 5 + 8 : 8 + c) ? 0 : 9");
// parseTest ("n = 7 + a - 8 ? b - 5 + 8 : 8 + c ? 0 : 9");
parseTest ("n = b (r)");
parseTest ("n = b ()");
parseTest ("n = k ( )");
parseTest ("n = k + y (8 -9) + 50");
parseTest ("n = !k");
parseTest ("n = !k + !5 ()");
parseTest ("n, m = a, b");
parseTest ("n, m = a, b = d, e");
parseTest ("n, m = a, b + 5, 6");
parseTest ("n, m = a, b = !e, g + 6, 7");
parseTest ("n, m = a, b + y");
// parseTest ("n, m = a, b ? c, d : e, f");
// parseTest ("n, m = a, b ? c, d + 7, 6 - 3 : e, f");
parseTest ("n = f (x, y - 1, z)");
//parseTest ("[n] r [10] t");
parseBodyTest ("a = b; r = f; t = d + 4\n t = y - 9\n r = c ? a : b\n g = y");
parseTest ("{a + b}");
//parseTest ("a or b");
//parseTest ("a or b");
parseTest ("while (a) c");
parseTest ("while(b) (a - h)");
parseTest ("while(b) {}");
parseTest ("while(b) {a - h}");
// parseTest ("if(a)b");
// parseTest ("if(a){b}");
// parseTest ("if(a){b}else{c}");
// parseTest ("e = if (a) b else c");
// parseTest ("if(a){\nb\n}else{\nc\n}");
// parseTest ("if(a){\nb\n}else if (e) {\nc\n} else if (g) {\nf\n}");
// parseTest ("x = if (a) b else c");
// parseTest ("x = if (a) b = y else c = z");
// parseTest ("x = if (a) b = y else z + u");
// parseTest ("lock (a) b");
// parseTest ("lock (a) {b + c}");
// parseTest ("lock (a) while (b) {}");
parseTest ("int32 A");
parseTest ("int32 B = a");
parseTest ("int32 C = a + b - c");
parseTest ("a = a + int32 F - c");
parseTest ("j = F");
parseBodyTest (
"r = func (n)\n"
"struct testType {int32 first}\n"
"def func (int32 arg, int32 arg2, ) -> (int32 ret) {\n"
"F = arg\n"
"}\n"
"r = func (n)"
);
parseBodyTest (
"r = func (n)\n"
"struct testType {int32 first}\n"
"def func (int32 arg, int32 arg2, ) -> (int32 ret) {\n"
"while (r) {\n"
"a = b\n"
"while (r) {\n"
"r = 6 + d\n"
"}\n"
"}\n"
"F = arg\n"
"}\n"
"r = func (n)"
);
parseTest ("{\n\tint32 r = f;\n}");
std::cout << "\n\n\n\n" << ast->NumbatScope::toString ();
delete ast;
return 0;
}
|
Java
|
UTF-8
| 308 | 2.828125 | 3 |
[] |
no_license
|
package com.gbn.thread;
public class Printer {
synchronized public static void print() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(i);
}
}
}
|
C++
|
UTF-8
| 401 | 3.203125 | 3 |
[] |
no_license
|
class Solution
{
public:
int maxProfit(vector<int> &prices)
{
int n = prices.size();
if(n == 0)return 0;
int ans = 0;
for(int i = 1, temp; i < n; i++)
{
temp = prices[i] - prices[i - 1];
if(temp > 0)ans += temp;
}
return ans;
}
};
|
C#
|
UTF-8
| 2,734 | 2.65625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sample32.Reports
{
public class SalesReport : ReportBase
{
string fileName = "";
public SalesReport(int batchNumber, string filePath) : base(batchNumber, filePath)
{
fileName = new FilePathResolver(batchNumber).GetSalesFileName();
tableName = "tblSalesTemp";
}
public override void ExportToDB()
{
var dataTable = new CsvParser().ReadCsvFile(filePath);
var columnsInTable = GetDatabaseColumns(tableName);
List<string> columnsToExcludeFromInsert = new List<string> {
"DataFrom",
"SalesFileName",
"ImportedDate",
"tblId"
};
List<string> columnsToExcludeFromCsv = new List<string>
{
};
columnsToExcludeFromInsert.ForEach(s => { s = s.ToLower(); });
columnsInTable.ForEach(s => { s.ColumnName = s.ColumnName.ToLower(); });
columnsToExcludeFromCsv.ForEach(s => { s = s.ToLower(); });
SqlConnection connection = new SqlConnection(ConfigReader.ConnectionString);
string insertQuery = BuildInsertQuery(GetDatabaseColumns(tableName), columnsToExcludeFromInsert, tableName);
int index = 1;
connection.Open();
foreach (DataRow row in dataTable.Rows)
{
index++;
try
{
SqlCommand cmd = new SqlCommand(insertQuery, connection);
foreach (var item in dataTable.Columns)
{
var columnName = item.ToString().ToLower();
var columnNameWithoutSpace = item.ToString().Replace(" ", "").ToLower();
if (!columnsToExcludeFromCsv.Contains(columnName))
{
SqlParameter parameter = new SqlParameter($"@{columnNameWithoutSpace}", row[columnName]);
cmd.Parameters.Add(parameter);
}
}
SqlParameter batchNumberParameter = new SqlParameter($"@batchnumber", batchNumber);
cmd.Parameters.Add(batchNumberParameter);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
connection.Close();
base.ExportToDB();
}
}
}
|
Java
|
UTF-8
| 5,905 | 3.859375 | 4 |
[] |
no_license
|
import java.util.*;
import java.util.stream.Stream;
/**
* @ClassName: ProcessOperation
* @Author Paulson
* @Date 2020/7/18
* @Description: 流式编程的中间操作
*/
public class ProcessOperation {
/**
* 学生类
* 存储于集合中数据类型
*/
private static class Student implements Comparable<Student> {
private String name;
private Integer age;
private Integer score;
public Student(String name, Integer age, Integer score) {
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Student student = (Student) o;
return Objects.equals(name, student.name) &&
Objects.equals(age, student.age) &&
Objects.equals(score, student.score);
}
@Override
public int hashCode() {
return Objects.hash(name, age, score);
}
@Override
public int compareTo(Student o) {
return score - o.score;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
}
public static void main(String[] args) {
// filterUsage();
// distinctUsage();
// sortedUsage();
// limitAndSkipUsage();
// mapUsage();
flatmapUsage();
}
/**
* 中间操作:flatmap
* 扁平化映射:一般用在map映射完成后,流中的数据是一个容器,而我们需要对容器中的数据进行处理
* 此时使用扁平化映射
*/
public static void flatmapUsage() {
String[] array = {"hello", "world"};
Stream<String> stream = Arrays.stream(array);
// stream.map(String::toCharArray).forEach(e -> System.out.println(Arrays.toString(e)));
stream.map(s -> s.split(""))
.flatMap(Arrays::stream)
.forEach(System.out::println);
}
/**
* 读取数据源
*
* @return 从数据源中读取到的数据
*/
public static Stream<Student> getDataSource() {
List<Student> arrayList = new ArrayList<>();
Collections.addAll(arrayList, new Student("小明", 18, 90),
new Student("xiaohong", 19, 90),
new Student("xiaohong", 20, 60),
new Student("xiaohong", 18, 98),
new Student("xiaohong", 17, 56),
new Student("xiaohong", 21, 56),
new Student("xiaohong", 20, 34),
new Student("xiaohong", 22, 75),
new Student("xiaohong", 21, 98),
new Student("xiaohong", 28, 100),
new Student("xiaobao", 28, 100),
new Student("xiaobao", 28, 100),
new Student("xiaohong", 15, 23)
);
return arrayList.stream();
}
/**
* 中间操作:map
* 元素映射:提供一个映射规则,将流中的每一个元素替换成指定的元素
*/
public static void mapUsage() {
Stream<Student> dataSource = getDataSource();
// 获取所有学生的名字
// dataSource.map(Student::getName).forEach(System.out::println);
// 获取所有的成绩
dataSource.map(Student::getScore).forEach(System.out::println);
}
/**
* 中间操作:sorted
* 排序
* sorted() 将流中的数据按照其对应的类实现的Comparable接口提供的比较奥尼规则进行排序
* sorted(Comparator<T> comparator) 将流中的数据按照昂参数接口提供的比较规则进行排序
*/
public static void sortedUsage() {
Stream<Student> dataSource = getDataSource();
// dataSource.sorted().forEach(System.out::println);
dataSource.sorted(Comparator.comparingInt(Student::getAge)).forEach(System.out::println);
}
/**
* 中间操作:limit skip
* limit:限制,表示截取流中的指定数量的数据
* skip:跳过指定数量的数据,截取剩余部分
*/
public static void limitAndSkipUsage() {
Stream<Student> dataSource = getDataSource();
// 获取成绩前3-5名
dataSource.sorted((s1, s2) -> s2.getScore() - s1.getScore())
.distinct()
.skip(2)
.limit(3)
.forEach(System.out::println);
}
/**
* 中间操作:distinct
* 去重:无参,去重规则与hashSet相同
* 1. hashcode
* 2. equals
*/
public static void distinctUsage() {
Stream<Student> dataSource = getDataSource();
dataSource.distinct().forEach(System.out::println);
}
/**
* 中间操作:filter
* 条件过滤: 将流中满足指定条件的数据保留,删除不满足指定条件的数据
*/
public static void filterUsage() {
Stream<Student> dataSource = getDataSource();
// 过滤掉不及格的信息
dataSource.filter(s -> s.getScore() >= 60).forEach(System.out::println);
}
}
|
Java
|
UTF-8
| 1,326 | 2.078125 | 2 |
[] |
no_license
|
package com.cuebiq.cuebiqsdk.model.wrapper;
import com.cuebiq.cuebiqsdk.CuebiqSDKImpl;
import com.cuebiq.cuebiqsdk.utils.InformationList;
import java.util.List;
public class TrackRequest {
private Auth auth;
private Device device;
private InformationList information;
private List<BluetoothDevice> pairedDevices;
private Integer settingsVersion;
public Auth getAuth() {
return this.auth;
}
public Device getDevice() {
return this.device;
}
public InformationList getInformation() {
return this.information;
}
public List<BluetoothDevice> getPairedDevices() {
return this.pairedDevices;
}
public Integer getSettingsVersion() {
return this.settingsVersion;
}
public void setAuth(Auth auth) {
this.auth = auth;
}
public void setDevice(Device device) {
this.device = device;
}
public void setInformation(InformationList informationList) {
this.information = informationList;
}
public void setPairedDevices(List<BluetoothDevice> list) {
this.pairedDevices = list;
}
public void setSettingsVersion(Integer num) {
this.settingsVersion = num;
}
public String toString() {
return CuebiqSDKImpl.GSON.toJson((Object) this);
}
}
|
Java
|
UTF-8
| 2,972 | 2.65625 | 3 |
[
"Apache-2.0"
] |
permissive
|
package eu.dnetlib.iis.core.examples.spark.rdd;
import eu.dnetlib.iis.common.utils.AvroGsonFactory;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.mapred.AvroKey;
import org.apache.hadoop.io.NullWritable;
import org.apache.spark.SparkFiles;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import scala.Tuple2;
import java.io.Serializable;
/**
* Executor of mapreduce scripts using spark pipes.
* It imitates hadoop streaming behavior.
*
* @author madryk
*/
public class SparkPipeExecutor implements Serializable {
private static final long serialVersionUID = 1L;
//------------------------ LOGIC --------------------------
/**
* Imitates map part of hadoop streaming job.
* It executes provided script for every key in inputRecords rdd.
* <br/><br/>
* It is assumed that provided script will read records from standard input (one line for one record)
* and write mapped record into standard output (also one line for one record).
* Mapped record can be a key/value pair. In that case script should return key and value
* splitted by tab (\t) character in single line.
*/
public JavaPairRDD<String, String> doMap(JavaPairRDD<AvroKey<GenericRecord>, NullWritable> inputRecords, String scriptName, String args) {
JavaRDD<String> mappedRecords = inputRecords
.keys()
.pipe("python " + SparkFiles.get(scriptName) + " " + args);
return mappedRecords
.mapToPair(line -> {
String[] splittedPair = line.split("\t");
return new Tuple2<>(splittedPair[0], (splittedPair.length == 1) ? null : splittedPair[1]);
});
}
/**
* Imitates reduce part of hadoop streaming job.
* <br/><br/>
* It is assumed that provided script will read records from standard input (one line for one record)
* and group records with the same key into single record (reduce).
* Method assures that all input records with the same key will be transfered in adjacent lines.
* Reduced records should be written by script into standard output (one line for one record).
* Reduced records must be json strings of class provided as argument.
*/
public JavaPairRDD<AvroKey<GenericRecord>, NullWritable> doReduce(JavaPairRDD<String, String> inputRecords, String scriptName, String args, Class<? extends GenericRecord> outputClass) {
JavaRDD<String> reducedRecords = inputRecords
.sortByKey()
.map(record -> record._1 + ((record._2 == null) ? "" : ("\t" + record._2)))
.pipe("python " + SparkFiles.get(scriptName) + " " + args);
return reducedRecords
.map(recordString -> AvroGsonFactory.create().fromJson(recordString, outputClass))
.mapToPair(record -> new Tuple2<>(new AvroKey<>(record), NullWritable.get()));
}
}
|
JavaScript
|
UTF-8
| 2,555 | 3.25 | 3 |
[] |
no_license
|
var board = [[0,0,0],[0,0,0],[0,0,0]];
var gameOver = false;
var players = [
{name:' ', nick:' '},
{name:'Player 1', nick:'1'},
{name:'Player 2', nick:'2'}
];
var setPlayers = function setPlayers(p1, p2){
players[1] = p1;
players[2] = p2;
document.getElementById('matchup').innerHTML = p1.name + " vs. " + p2.name;
}
var mark = function mark(t){
if(gameOver) return;
var row = t.id.charCodeAt(0) - 65;
var col = t.id.charCodeAt(1) - 65;
board[row][col] = player;
t.setAttribute('class', 'p' + player);
t.setAttribute('onclick', null);
t.innerHTML = players[player].nick;
nextPlayer();
var winner = findWinner();
if(winner){
gameOver = true;
setWinner(winner == 1, winner == 2);
var status = winner < 0 ? "Stalemate - your wits seem matched" : players[winner].name + " is the Champion";
document.getElementById('status').innerHTML = status;
document.getElementById('again').setAttribute('style', '');
}
}
var nextPlayer = function nextPlayer(){
var lastPlayer = player;
if(player == 1)
player = 2;
else
player = 1;
setActiveState(document.getElementById('p' + player), 'active');
setActiveState(document.getElementById('p' + lastPlayer), 'inactive');
}
var setWinner = function setWinner(p1, p2){
setActiveState(document.getElementById('p1'), p1 ? 'active' : 'inactive');
setActiveState(document.getElementById('p2'), p2 ? 'active' : 'inactive');
};
var setActiveState = function setActiveState(cell, newState){
var newClass = cell.getAttribute('class').replace(/\s*(in)?active/g, '') + ' ' + newState;
cell.setAttribute('class', newClass);
};
var findWinner = function findWinner(){
if(isWinner(1)) return 1;
if(isWinner(2)) return 2;
if(isFilled()) return -1;
return 0;
}
var isWinner = function isWinner(player){
var on = function(row,col){return player == board[row][col]};
return false
|| (on(0,0) && on(0,1) && on(0,2))
|| (on(1,0) && on(1,1) && on(1,2))
|| (on(2,0) && on(2,1) && on(2,2))
|| (on(0,0) && on(1,0) && on(2,0))
|| (on(0,1) && on(1,1) && on(2,1))
|| (on(0,2) && on(1,2) && on(2,2))
|| (on(0,0) && on(1,1) && on(2,2))
|| (on(2,0) && on(1,1) && on(0,2))
;
}
var isFilled = function isWinner(player){
var on = function(row,col){return board[row][col]};
return true
&& on(0,0) && on(0,1) && on(0,2)
&& on(1,0) && on(1,1) && on(1,2)
&& on(2,0) && on(2,1) && on(2,2)
;
}
var player = 2;
nextPlayer();
|
C#
|
UTF-8
| 1,451 | 3.15625 | 3 |
[] |
no_license
|
// <copyright file="MinimumAgeAttribute.cs" company="Luxury Travel Deals">
// Copyright (c) Luxury Travel Deals All rights reserved.
// </copyright>
namespace HiTours.TBO.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
/// <summary>
/// MinimumAgeAttribute
/// </summary>
public class MinimumAgeAttribute : ValidationAttribute
{
/// <summary>
/// The minimum age
/// </summary>
private int minimumAge;
/// <summary>
/// Initializes a new instance of the <see cref="MinimumAgeAttribute"/> class.
/// </summary>
/// <param name="minimumAge">The minimum age.</param>
public MinimumAgeAttribute(int minimumAge)
{
this.minimumAge = minimumAge;
}
/// <summary>
/// Returns true if ... is valid.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>
/// <c>true</c> if the specified value is valid; otherwise, <c>false</c>.
/// </returns>
public override bool IsValid(object value)
{
DateTime date;
if (DateTime.TryParse(value.ToString(), out date))
{
return date.AddYears(this.minimumAge) < DateTime.Now;
}
return false;
}
}
}
|
Java
|
UTF-8
| 1,223 | 1.75 | 2 |
[] |
no_license
|
package com.softlab.okr.service;
import com.github.pagehelper.PageInfo;
import com.softlab.okr.exception.ServiceException;
import com.softlab.okr.model.bo.RoleResourceBo;
import com.softlab.okr.model.dto.ResourceDTO;
import com.softlab.okr.model.entity.Resource;
import com.softlab.okr.model.vo.ResourceVO;
import java.util.Collection;
import java.util.List;
import java.util.Set;
public interface ResourceService {
int saveResources(List<Resource> resourceList) throws ServiceException;
int saveRoleResource(RoleResourceBo bo) throws ServiceException;
int removeList() throws ServiceException;
Resource getResourceByPath(String path) throws ServiceException;
Resource getResourceById(int resourceId) throws ServiceException;
List<Integer> getResourceIds(String role) throws ServiceException;
PageInfo<ResourceVO> getResourceList(ResourceDTO dto) throws ServiceException;
int reloadRoleResource(RoleResourceBo bo) throws ServiceException;
int modifyResourceStatus(int resourceId) throws ServiceException;
void appStartLoad(List<Resource> list) throws ServiceException;
Set<Resource> filterResource(Collection<Resource> list) throws ServiceException;
}
|
Java
|
UTF-8
| 1,542 | 2.234375 | 2 |
[] |
no_license
|
package com.bawei.wangyi20200402.model;
import com.bawei.wangyi20200402.bean.Loginbean;
import com.bawei.wangyi20200402.contract.LoginContract;
import com.bawei.wangyi20200402.utils.NetUtils;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
/**
* m 层
*/
public class LoginModel implements LoginContract.IModel{
@Override
public void doLogin(String phone, String pwd, final IModelCallBack callBack) {
NetUtils.getInstance().getApis().dologin(phone,pwd)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Loginbean>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Loginbean loginbean) {
if(callBack!=null){
callBack.LoginSuccess(loginbean);
}
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
if(callBack!=null){
callBack.LoginFailure(e.getMessage());
}
}
@Override
public void onComplete() {
}
});
}
}
|
Java
|
UTF-8
| 2,482 | 3.390625 | 3 |
[] |
no_license
|
package itSovy.carConsumption.detail;
public class Car {
public double fuelCapacity;
public double fuelConsumption;
public String brand;
public int year;
public String type;
public String horsePower;
private Engine engine;
public Color color;
public Car(double fuelCapacity, double fuelConsumption, String brand,int year,String type,int horsePower, char fuel, int engineCylinder, int power, int volume,Color color){
this.fuelCapacity = fuelCapacity;
this.fuelConsumption = fuelConsumption;
this.brand = brand;
this.year = year;
this.type = type;
this.horsePower = horsePower + "kW";
this.color = color;
engine = new Engine(engineCylinder, power, volume, fuel);
}
public void enduranceDistance(double pricePaid){
double distance=0;
double fuelPrice = 1.361;
double litreBought = (Math.round( (pricePaid/fuelPrice)*100.0)) /100.0;
if((fuelCapacity-litreBought)>0){
distance= Math.round((litreBought/(fuelConsumption/100))*100.0) /100.0;
System.out.println("\nYou bought "+ litreBought+"l of fuel");
System.out.println("Your possible enduranceDistance is "+ distance+" KM");
}else{
double returnCash = (fuelCapacity-litreBought)*-1;
distance= Math.round((fuelCapacity/(fuelConsumption/100))*100.0) /100.0;
returnCash = (Math.round((returnCash*fuelPrice)*100.0))/100.0;
System.out.println("\nYou fully fill your fuelCapacity");
System.out.println("Money for return "+returnCash+"EUR");
System.out.println("Your possible enduranceDistance is "+ distance+" KM");
}
}
public double getFuelCapacity() {
return fuelCapacity;
}
public int getYear() {
return year;
}
public double getFuelConsumption() {
return fuelConsumption;
}
public String getBrand() {
return brand;
}
public Engine getEngine() {
return engine;
}
public void print() {
System.out.println("\nfuelCapacity "+fuelCapacity+"\nfuelConsumption "+fuelConsumption+"\nbrand "+brand+"\nyear "+year+"\ntype "+type);
}
public void printDetail(){
print();
System.out.println("Engine details \nPower: "+engine.getPower()+"\nVolume: "+engine.getVolume()+"\nengineCylinder "+engine.getEngineCylinder()+"\nfuel "+engine.getFuel()+"\nColor "+color );
}
}
|
Python
|
UTF-8
| 2,576 | 3.84375 | 4 |
[] |
no_license
|
class Vehicle():
class_name=''
vehicles={}
#constructor
def __init__(self, kind, speed, material, substance): #THE MATERIAL PARAMETER WILL NOT BE ASSIGNED WHEN AN OBJECT OF THE CLASS IS CREATED (APPARENTLY PYTHON 3.0 AND ABOVE)
self.kind = kind
self.speed = speed
self.material = material #BECAUSE A GETTER AND A SETTER ALREADY HAVE THIS NAME, THIS ASSIGNMENT WILL BE IGNORED
self.substance = substance
self.status=0
self._integrity = 'intact' #INITIAL VALUE OF THE PROPERTY
Vehicle.vehicles[self.class_name] = self
#getter
@property
def material(self): #THE GETTER AND SETTER NEED NOT HAVE THE SAME NAME AS THE PROPERTY
if self.status==0:
self._integrity='intact'
elif self.status==1:
self._integrity='integrity 75%'
elif self.status==2:
self._integrity='integrity 50%'
elif self.status==3:
self._integrity='integrity 25%'
elif self.status==4:
self._integrity='compromised'
return self._integrity
#setter
@material.setter
def material(self, value): #THE GETTER AND SETTER NEED NOT HAVE THE SAME NAME AS THE PROPERTY
self.status = value #THE SETTER IS CALLED AT ANY POINT IN THIS CODE WHERE YOU TRY TO ASSIGN A NEW VALUE TO SELF.STATUS
return 'test' #setter won't return this
print('test') #setter won't print this
#CREATE A SUB CLASS
class Car(Vehicle):
class_name='car'
#CREATE AN OBJECT OF THE CAR CLASS
car1 = Car('sports', 600, 'steel', 'tin') #STEEL IS NOT ASSIGNED TO MATERIAL (APPARENTLY PYTHON 3.0 AND ABOVE), NEVERTHELESS 4 ARGUMENTS ARE MANDATORY HERE
print(car1.kind)
print(car1.speed)
print(car1.material) #RATHER THAN CALL THE MATERIAL ATTRIBUTE, THIS WILL CALL THE MATERIAL PROPERTY (APPARENTLY PYTHON 3.0 AND ABOVE)
print(car1.substance)
print('\n'*5)
def crash(item):
print('whoops! you\'ve crashed into something!!!')
item.status += 1 #THIS STATEMENT ATTEMPTS TO ASSIGN A NEW VALUE TO A VARIABLE WHOSE VALUE IS CONTROLLED IN THE SETTER,
#AND THEREFORE THIS STATEMENT CALLS THE SETTER
print(car1.material)
def getinput():
command = (input('enter command:')).split(' ')
verbword = command[0]
if verbword in verbdict:
verb = verbdict[verbword]
else:
print('you can\'t do that')
return
if len(command)>1:
noun = command[1]
myarg = Vehicle.vehicles[noun]
#command[0](myarg) #WRONG. COMMAND[0] IS A STRING. A STRING ISN'T CALLABLE
verb(myarg)
verbdict={'crash':crash}
while True:
getinput()
|
C
|
UTF-8
| 187 | 2.671875 | 3 |
[] |
no_license
|
#include <time.h>
#include <stdio.h>
#include <sys/time.h>
int main(void){
time_t t,t1;
t = time(NULL);
sleep(10);
t1 = time(NULL);
printf("end = %ld\n",t1-t);
}
|
Java
|
UTF-8
| 157 | 1.960938 | 2 |
[] |
no_license
|
package com.irisida.lang.part03.chapter10.interfaces.interfaceinheritance;
public interface DefaultRunnable extends Runnable {
void displayDetails();
}
|
Rust
|
UTF-8
| 5,045 | 2.53125 | 3 |
[] |
no_license
|
use super::terrain::TerrainGeometry;
use super::utils::*;
use cell_traits::*;
use color::Color;
use commons::barycentric::triangle_interpolate_any;
use commons::grid::Grid;
use commons::*;
use graphics::Drawing;
use Command;
pub const HOUSE_FLOATS: usize = 252;
pub struct House<'a> {
pub position: &'a V2<usize>,
pub width: &'a f32,
pub height: &'a f32,
pub roof_height: &'a f32,
pub rotated: bool,
pub base_color: &'a Color,
pub light_direction: &'a V3<f32>,
}
fn get_floats<T>(terrain: &dyn Grid<T>, house: House) -> Vec<f32>
where
T: WithPosition + WithElevation + WithVisibility + WithJunction,
{
let House {
position,
width,
height,
roof_height,
rotated,
base_color,
light_direction,
} = house;
let triangle_coloring = AngleTriangleColoring::new(*base_color, *light_direction);
let square_coloring = AngleSquareColoring::new(*base_color, *light_direction);
let x = position.x as f32 + 0.5;
let y = position.y as f32 + 0.5;
let w = width;
let [base_a, base_b, base_c, base_d] = get_house_base_corners(terrain, position, w);
let zs = [base_a.z, base_b.z, base_c.z, base_d.z];
let floor_z = zs.iter().max_by(unsafe_ordering).unwrap();
let top_a = v3(x - w, y - w, floor_z + height);
let top_b = v3(x + w, y - w, floor_z + height);
let top_c = v3(x + w, y + w, floor_z + height);
let top_d = v3(x - w, y + w, floor_z + height);
let (roof_a, roof_b, roof_c, roof_d, ridge_a, ridge_b) = if rotated {
(
top_a,
top_b,
top_c,
top_d,
v3(x - w, y, floor_z + height + roof_height),
v3(x + w, y, floor_z + height + roof_height),
)
} else {
(
top_b,
top_c,
top_d,
top_a,
v3(x, y - w, floor_z + height + roof_height),
v3(x, y + w, floor_z + height + roof_height),
)
};
let mut floats = Vec::with_capacity(HOUSE_FLOATS);
floats.append(&mut get_colored_vertices_from_square(
&[top_a, top_d, base_d, base_a],
&square_coloring,
));
floats.append(&mut get_colored_vertices_from_square(
&[top_d, top_c, base_c, base_d],
&square_coloring,
));
floats.append(&mut get_colored_vertices_from_square(
&[top_c, top_b, base_b, base_c],
&square_coloring,
));
floats.append(&mut get_colored_vertices_from_square(
&[top_b, top_a, base_a, base_b],
&square_coloring,
));
floats.append(&mut get_colored_vertices_from_triangle(
&[roof_d, roof_a, ridge_a],
&triangle_coloring,
));
floats.append(&mut get_colored_vertices_from_square(
&[roof_c, roof_d, ridge_a, ridge_b],
&square_coloring,
));
floats.append(&mut get_colored_vertices_from_triangle(
&[roof_b, roof_c, ridge_b],
&triangle_coloring,
));
floats.append(&mut get_colored_vertices_from_square(
&[roof_a, roof_b, ridge_b, ridge_a],
&square_coloring,
));
floats
}
pub fn get_house_base_corners<T>(
terrain: &dyn Grid<T>,
position: &V2<usize>,
width: &f32,
) -> [V3<f32>; 4]
where
T: WithPosition + WithElevation + WithVisibility + WithJunction,
{
let x = position.x as f32 + 0.5;
let y = position.y as f32 + 0.5;
let geometry = TerrainGeometry::of(terrain);
let triangles = geometry.get_triangles_for_tile(position);
let get_base_corner = move |offset: V2<usize>| {
let corner2d = v2(
x + (offset.x as f32 * 2.0 - 1.0) * width,
y + (offset.y as f32 * 2.0 - 1.0) * width,
);
v3(
corner2d.x,
corner2d.y,
triangle_interpolate_any(&corner2d, &triangles)
.unwrap_or_else(|| terrain.get_cell_unsafe(&(position + offset)).elevation()),
)
};
[
get_base_corner(v2(0, 0)),
get_base_corner(v2(1, 0)),
get_base_corner(v2(1, 1)),
get_base_corner(v2(0, 1)),
]
}
pub fn create_house_drawing(name: String, count: usize) -> Command {
Command::CreateDrawing(Drawing::plain(name, HOUSE_FLOATS * count))
}
pub fn update_house_drawing_vertices<T>(
name: String,
terrain: &dyn Grid<T>,
houses: Vec<House>,
) -> Command
where
T: WithPosition + WithElevation + WithVisibility + WithJunction,
{
let mut floats = Vec::with_capacity(HOUSE_FLOATS * houses.len());
for house in houses {
floats.append(&mut get_floats(terrain, house));
}
Command::UpdateVertices {
name,
index: 0,
floats,
}
}
pub fn create_and_update_house_drawing<T>(
name: String,
terrain: &dyn Grid<T>,
houses: Vec<House>,
) -> Vec<Command>
where
T: WithPosition + WithElevation + WithVisibility + WithJunction,
{
vec![
create_house_drawing(name.clone(), houses.len()),
update_house_drawing_vertices(name, terrain, houses),
]
}
|
Markdown
|
UTF-8
| 45,467 | 3.484375 | 3 |
[] |
no_license
|
# Go语言学习笔记
### 1. Go语言简介
**Go语言特色**
- 简洁、快速、安全
- 并行、有趣、开源
- 内存管理、数组安全、编译迅速
**Go语言用途**
- Go语言被设计成一门应用于搭载Web服务器,存储集群或类似用途的巨型中央服务器的系统编程语言
- 对于高性能分布式系统领域而言,Go语言比大多数其他语言有更高开发效率
- 提供了海量并行的支持,对于游戏服务端的开发很好
**Go语言开发工具**
GoLand、LiteIDE、Eclipse
### 2. Go语言结构
**Hello World实例**
```go
package main
import "fmt"
func main() {
/* 这是我的第一个简单的程序 */
fmt.Println("Hello, World!")
}
```
Go语言基础组成:
①包声明:package main表示一个可独立执行的程序,每个Go应用程序都包含一个名为main的包
②引入包:fmt包实现了格式化IO的函数
③函数:main函数是每一个可执行程序所必须包含的,一般是在启动后第一个执行的函数(如有 `init()`函数则先执行该函数)
④注释:单行注释用 `//`开头,多行注释以 `/*`开头,以 `*/`结尾
⑤语句&表达式
⑥变量:当标识符以一个大写字母开头,那么使用这种形式的标识符的对象就可以被外部包的代码所使用,称为导出(类似面向对象中的public);当标识符以小写字母开头,则对包外不可见,但在整个包内部是可见并且可用的(类似面向对象中的protected)
**执行Go程序**
- 在命令行中输入 `go run filename.go`
- 在命令行使用 `go build filename.go`命令生成二进制文件
⭐注意 `{` 不可以单独放在一行
### 3. Go基础语法
**Go标记**
Go程序可由多个标记组成,可以是关键字,标识符,常量,字符串,符号
**行分隔符**
一行代表一个语句结束,无需添加分号结尾,因为这些工作将由Go编译器自动完成
**标识符**
一个标识符是由一个或多个字母、数字、下划线组成的序列,但第一个字符必须是字母或下划线而不能是数字
**字符串连接**
类似Java,以 `+`实现
**关键字**
25个关键字或保留字:
| break | default | func | interface | select |
| ------------ | --------------- | ---------- | ----------- | ---------- |
| **case** | **defer** | **go** | **map** | **struct** |
| **chan** | **else** | **goto** | **package** | **switch** |
| **const** | **fallthrough** | **if** | **range** | **type** |
| **continue** | **for** | **import** | **return** | **var** |
**空格**
变量的声明必须使用空格隔开
### 4. Go语言数据类型
按类别分为:
①布尔型:true、false。 `var b bool = true`
②数字类型:int、float32、float64、复数。位的运算使用补码
③字符串类型:Go的字符串是由单个字节连接起来,使用UTF-8编码标识Unicode文本
④派生类型:指针类型(Pointer)、数组类型、结构化类型(Struct)、Channel类型、函数类型、切片类型、接口类型(interface)、Map类型
**数字类型**
| **unit8** | **无符号8位整型(0-255)** | **int8** | **有符号8位整型(-128到127)** |
| ---------- | ------------------------ | --------- | ----------------------------- |
| **uint16** | **无符号16位整型** | **int16** | **有符号16位整型** |
| **unit32** | **无符号32位整型** | **int32** | **有符号32位整型** |
| **unit64** | **无符号64位整型** | **int64** | **有符号64位整型** |
浮点型
| **float32** | **IEEE-754 32位浮点型数** | **complex64** | **32位实数和虚数** |
| ----------- | ------------------------- | -------------- | ------------------ |
| **float64** | **IEEE-754 64位浮点型数** | **complex128** | **64位实数和虚数** |
其他数字类型
| **byte** | **类似uint8** |
| ----------- | -------------------------------- |
| **rune** | **类似int32** |
| **uint** | **32位或64位** |
| **int** | **与uint一样大小** |
| **uintptr** | **无符号整型,用于存放一个指针** |
### 5. Go语言变量
声明变量的一般形式: `var identifier type`
一次声明多个变量形式:`var identifier1,identifier2 type`
```go
package main
import "fmt"
func main() {
var a int = 2
var b string = "Test"
fmt.Println(a,b)
}
```
**变量声明的三种方式**
①指定变量类型,如没有初始化,则默认为零值
```go
package main
import "fmt"
func main() {
var a int
a = 2
var b int
var c bool
var d string
var e *int
fmt.Println(a,b,c,d,e)
}
```
"零值"
- 数值类型(包括complex64/128)为0
- 布尔类型为false
- 字符串为“”(空字符串)
- 以下几种类型为nil:
```go
var a *int
var a []int
var a map[string] int
var a chan int
var a func(string) int
var a error // error 是接口
```
②根据值自行判断变量类型
```go
package main
import "fmt"
func main() {
var a = "str"
fmt.Println(a)
}
```
③省略var,注意 `:=`左侧如果没有声明新的变量就会产生编译错误
```go
package main
import "fmt"
func main() {
a := "str"
var b int
// b := 2(编译错误)
b,c := 2,3 //有声明新的变量,ok
fmt.Println(a,b,c)
}
```
**多变量声明**
```go
//类型相同多个变量,非全局变量
var vname1,vname2,vname3 type
vname1,vname2,vname3 = v1,v2,v3
//和python很像,不需要显式声明类型
var vname1,vname2,vname3 = v1,v2,v3
//:=左侧变量不应该是已经被声明过的
vname1,vname2,vname3 := v1,v2,v3
//这种因式分解关键字写法一般用于声明全局变量
var(
vname1 v_type1
vname2 v_type2
)
```
实例
```go
package main
import "fmt"
var x,y int
var(
a int
b bool
)
var c,d int = 1, 5
var e,f = 123,"str"
// g,h := 123,"str"(这种不带声明格式的只能在函数体内出现)
func main() {
g,h := 123,"str"
fmt.Println(x,y,a,b,c,d,e,f,g,h)
}
```
**值类型和引用类型**
①值类型
- 所有像int、float、bool和string这些基本类型都属于值类型,使用这些类型的变量直接指向内存中的值。
- 当使用等号进行赋值时,如 b = a ,实际上是在内存中将a的值进行了拷贝
②引用类型
- 更复杂的数据通常需要使用多个字,这些数据使用引用类型保存
- 一个引用类型的变量r1存储r1的值所在的内存地址,或内存地址中第一个字所在的位置。这个内存地址称为指针,这个指针实际上也被存在了另外的某一个字中
- 当使用等号进行赋值时,只有引用(地址)被复制,如 r2 = r1,如果r1值被改变,那么这个值的所有引用都会指向被修改后的内容,r2也受到影响
**使用 := 赋值操作符**
- :=为变量赋值只能被用于函数体内,不可以用于全局变量的声明与赋值。使用操作符 := 高效创建一个新的变量,称之为初始化声明。
- 声明了一个局部变量却没有在相同的代码块中使用它,也会有编译错误
- 全局变量允许声明但不使用。同一类型的多个变量可声明在同一行
- 多变量可在同一行赋值
- 如果想要交换两个变量的值,可以用 `a,b=b,a`,两变量类型必须相同
**空白标识符 _**
用于抛弃值。如 `_,b = 5,7`中,值5被抛弃
_ 实际上是一个只写变量,不能得到它的值。因为Go语言中必须使用所有被声明的变量。但有时并不需要使用从一个函数得到的所有返回值。
### 6. Go语言常量
常量中的数据类型只可以是布尔型、数字型(整型、浮点型和复数)和字符串型
常量定义格式:`const identifier [type] = value`
- 显式类型定义:`const b string = "str"`
- 隐式类型定义:`const b = "str"`
- 多个相同类型声明:`const c_name1,c_name2 = value1,value2`
常量还可以用于枚举:
```go
const(
Unknown = 0
Female = 1
Male = 2
)
```
常量可用len()、cap()、unsafe.Sizeof()函数计算表达式的值。常量表达式中,函数必须是内置函数:
```go
package main
import "unsafe"
const(
a = "str"
b = len(a)
c = unsafe.Sizeof(a)
)
func main() {
println(a,b,c)
}
/*
输出 str 3 16
*/
```
🔺字符串类型在go里是个结构,包含指向底层数组的指针和长度,这两部分每部分都是8个字节,所以字符串类型大小为16个字节
**iota**
特殊常量,可认为是一个可被编译器修改的常量
iota在const关键字出现时将被重置为0(const内部的第一行之前),const中每新增一行常量声明将使iota计数一次(iota可理解为const语句块中行索引)
iota可被用作枚举值:
```go
const(
a = iota
b = iota
c = iota
)
```
iota用法:
```go
package main
import "fmt"
func main() {
const(
a = iota
b
c
d = 50
e
f = iota
g
)
fmt.Println(a,b,c,d,e,f,g)
}
/*
输出 0 1 2 50 50 5 6
*/
```
🔺在定义常量组时,如不提供初始值,则表示使用上行的表达式
另一个iota实例:
```go
package main
import "fmt"
func main() {
const(
a = 1<<iota
b = 3<<iota
c
d
)
fmt.Println(a,b,c,d)
}
/*
输出 1 6 12 24
*/
```
a = 1<<0,b=3<<1,c=3<<2,d=3<<3
### 7. Go语言运算符
| 分类 | 运算符 |
| ---------- | -------------------------------------------- |
| 算术运算符 | +、-、*、/(整数除法)、%、++、-- |
| 关系运算符 | ==、!=、>、<、>=、<= |
| 逻辑运算符 | &&、\|\|、! |
| 位运算符 | &、\|、^(异或)、<<、>> |
| 赋值运算符 | =、+=、-=、*=、/=、%=、<<=、>>=、&=、\|=、^= |
| 其他运算符 | &(返回变量存储地址)、*(指针变量) |
**运算符优先级**
由高到低:
| 优先级 | 运算符 |
| ------ | ---------------------- |
| 5 | *、/、%、<<、>>、&、&^ |
| 4 | +、-、\|、^ |
| 3 | ==、!=、<、<=、>、>= |
| 2 | && |
| 1 | \|\| |
二元运算符运算方向从左至右
***和&的使用区别**
```go
package main
import "fmt"
func main() {
var a int = 3
var ptr *int
ptr = &a
fmt.Println(a,*ptr,ptr)
}
/*
输出 3 3 0xc0000a0090
*/
```
🔺指针变量保存的是一个地址值,会分配独立的内存来分配一个整型数字。当变量前面有*号标识时,才等同于&用法,否则会直接输出一个整型数字。
### 8. Go条件语句
①if语句
②if...else语句
③if嵌套语句
④switch语句
- switch语句执行过程从上到下,直到找到匹配项,匹配项后面不需要加break
- 默认case最后自带break语句,匹配成功后不会执行其他case,要使用后面的case可使用fallthrough
```go
switch var1{
case val1:
case val2:
...
default:
}
```
var1可以是任何类型。val1和val2可以是同类型任意值。类型不局限于常量或整数,但必须是相同类型;或者最终结果为相同类型表达式
可以同时测试多个可能值,使用逗号分隔,如case val1,val2,val3
```go
package main
import "fmt"
func main() {
var grade string = "B"
var marks int = 90
switch marks{
case 90:grade = "A"
case 80:grade = "B"
case 60,70:grade = "C"
default:grade = "D"
}
switch{
case grade == "A":
fmt.Println("优秀")
case grade == "B":
fmt.Println("良好")
case grade == "C":
fmt.Println("及格")
case grade == "D":
fmt.Println("不及格")
}
fmt.Printf("等级为 %s\n",grade)
}
```
**Type Switch**
判断某个interface变量中实际存储的变量类型
```go
switch x.(type){
case type:
stmts;
case type:
stmts;
default:
stmts;
}
```
实例:
```go
package main
import "fmt"
func main() {
var x interface{}
switch i:=x.(type){
case nil:
fmt.Println("x的类型为",i)
case int:
fmt.Println("x是int型")
default:
fmt.Println("未知")
}
}
```
**fallthrough用法**
```go
package main
import "fmt"
func main() {
switch{
case false:
fmt.Println("false")
fallthrough
case true:
fmt.Println("true")
fallthrough
case false:
fmt.Println("false")
fallthrough
case true:
fmt.Println("true")
case false:
fmt.Println("false")
fallthrough
default:
fmt.Println("default")
}
}
/*
true
false
true
*/
```
switch从第一个判断表达式为true的case开始执行,如果case带有fallthrough,程序继续执行下一条case,不会判断下一个case表达式是否为true
⑤select语句
- 类似于用于通信的switch语句,每个case必须是一个通信操作,要么是发送要么是接收。
- select随机执行一个可运行的case,如果没有case可运行,它将阻塞,直到有case可运行,一个默认子句应该总是可运行的。
```go
select{
case communication clause:
stmts;
case communication clause:
stmts;
default:
stmts;
}
```
所有channel表达式都会被求值,所有被发送的表达式都会被求值
实例:
```go
package main
import "fmt"
func main() {
var c1, c2, c3 chan int
var i1, i2 int
select {
case i1 = <-c1:
fmt.Printf("received ", i1, " from c1\n")
case c2 <- i2:
fmt.Printf("sent ", i2, " to c2\n")
case i3, ok := (<-c3): // same as: i3, ok := <-c3
if ok {
fmt.Printf("received ", i3, " from c3\n")
} else {
fmt.Printf("c3 is closed\n")
}
default:
fmt.Printf("no communication\n")
}
}
/*
no communication
*/
```
select会循环检测条件,如果有满足则执行并退出,否则一直循环检测
### 9. Go循环语句
①for语句
三种使用方式:
- 和C语言的for一样: `for init;condition;post{}`
- 和C语言的while一样:`for condition{}`
- 和C语言的for(;;)一样:`for {}`
for循环的range格式可对slice、map、数组、字符串等进行迭代循环:
```go
for key,value := range oldMap{
newMap[key] = value
}
```
实例:
```go
package main
import "fmt"
func main() {
sum := 0
for i:=0;i<=10;i++{
sum+=i
}
fmt.Println(sum)
}
```
**For-each range循环**
对字符串、数组、切片等进行迭代输出元素
```go
package main
import "fmt"
func main() {
strings := []string{"google", "runoob"}
for i, s := range strings {
fmt.Println(i, s)
}
numbers := [6]int{1, 2, 3, 5}
for i,x:= range numbers {
fmt.Printf("第 %d 位 x 的值 = %d\n", i,x)
}
}
/*
0 google
1 runoob
第 0 位 x 的值 = 1
第 1 位 x 的值 = 2
第 2 位 x 的值 = 3
第 3 位 x 的值 = 5
第 4 位 x 的值 = 0
第 5 位 x 的值 = 0
*/
```
②循环嵌套
```go
for [condition|(init;condition;increment)|Range]
{
for [condition|(init;condition;increment)|Range]
{
stmts;
}
stmts;
}
```
输出2到100之间素数实例:
```go
package main
import "fmt"
func main() {
var i, j int
for i=2; i < 100; i++ {
for j=2; j <= (i/j); j++ {
if i%j==0 {
break // 如果发现因子,则不是素数
}
}
if j > (i/j) {
fmt.Printf("%d 是素数\n", i);
}
}
}
```
③break语句
- 用于跳出循环,并开始执行循环之后语句
- 在多重循环中,可使用标记label标记出想break的循环
多重循环break实例:
```go
package main
import "fmt"
func main() {
fmt.Println("---- break ----")
for i := 1; i <= 3; i++ {
fmt.Printf("i: %d\n", i)
for i2 := 11; i2 <= 13; i2++ {
fmt.Printf("i2: %d\n", i2)
break
}
}
fmt.Println("---- break label ----")
re:
for i := 1; i <= 3; i++ {
fmt.Printf("i: %d\n", i)
for i2 := 11; i2 <= 13; i2++ {
fmt.Printf("i2: %d\n", i2)
break re
}
}
}
/*
---- break ----
i: 1
i2: 11
i: 2
i2: 11
i: 3
i2: 11
---- break label ----
i: 1
i2: 11
*/
```
④continue语句
- 用于跳过当前循环执行下一次循环语句
- 多重循环中,可用标记label标记出想continue的循环
```go
package main
import "fmt"
func main() {
fmt.Println("---- continue ---- ")
for i := 1; i <= 3; i++ {
fmt.Printf("i: %d\n", i)
for i2 := 11; i2 <= 13; i2++ {
fmt.Printf("i2: %d\n", i2)
continue
}
}
fmt.Println("---- continue label ----")
re:
for i := 1; i <= 3; i++ {
fmt.Printf("i: %d\n", i)
for i2 := 11; i2 <= 13; i2++ {
fmt.Printf("i2: %d\n", i2)
continue re
}
}
}
/*
---- continue ----
i: 1
i2: 11
i2: 12
i2: 13
i: 2
i2: 11
i2: 12
i2: 13
i: 3
i2: 11
i2: 12
i2: 13
---- continue label ----
i: 1
i2: 11
i: 2
i2: 11
i: 3
i2: 11
*/
```
⑤goto语句
无条件转移到过程中指定的行
goto语句通常与条件语句配合使用,用来实现循环,跳出循环体等功能
```go
goto label;
..
.
label:stmt;
```
### 10. Go函数
Go语言最少有个main()函数
```go
func function_name ([parameter list]) [return_types]{
函数体
}
```
函数由func开始声明,函数名和参数列表一起构成了函数签名
**函数调用**
求两个数最大值实例:
```go
package main
import "fmt"
func main() {
var a int = 50
var b int = 100
res := max(a,b)
fmt.Println(res)
}
func max(num1,num2 int)int{
var result int
if num1>num2 {
result = num1
} else{
result = num2
}
return result
}
```
**函数返回多个值**
交换两个元素实例:
```go
package main
import "fmt"
func main() {
a,b := swap("str1","str2")
fmt.Println(a,b)
}
func swap(x,y string)(string,string){
return y,x
}
```
**函数参数**
🔺Go语言默认使用值传递,即调用过程中不会影响到实际参数
| 传递类型 | 描述 |
| -------- | ------------------------------------------------------------ |
| 值传递 | 在调用函数时将实际参数复制一份传递到函数中;在函数中如果对参数进行修改将不会影响到实际参数 |
| 引用传递 | 在调用函数时将实际参数的地址传递到函数中;在函数中对参数的修改将影响到实际参数 |
值传递实例:
```go
package main
import "fmt"
func main() {
var a int = 100
var b int = 200
fmt.Printf("交换前 a 的值为 : %d\n", a )
fmt.Printf("交换前 b 的值为 : %d\n", b )
swap(a, b)
fmt.Printf("交换后 a 的值 : %d\n", a )
fmt.Printf("交换后 b 的值 : %d\n", b )
}
func swap(x, y int) int {
var temp int
temp = x /* 保存 x 的值 */
x = y /* 将 y 值赋给 x */
y = temp /* 将 temp 值赋给 y*/
return temp
}
/*
交换前 a 的值为 : 100
交换前 b 的值为 : 200
交换后 a 的值 : 100
交换后 b 的值 : 200
*/
```
引用传递实例:
```go
package main
import "fmt"
func main() {
var a int = 100
var b int= 200
fmt.Printf("交换前,a 的值 : %d\n", a )
fmt.Printf("交换前,b 的值 : %d\n", b )
/* 调用 swap() 函数
* &a 指向 a 指针,a 变量的地址
* &b 指向 b 指针,b 变量的地址
*/
swap(&a, &b)
fmt.Printf("交换后,a 的值 : %d\n", a )
fmt.Printf("交换后,b 的值 : %d\n", b )
}
func swap(x *int, y *int) {
var temp int
temp = *x /* 保存 x 地址上的值 */
*x = *y /* 将 y 值赋给 x */
*y = temp /* 将 temp 值赋给 y */
}
/*
交换前,a 的值 : 100
交换前,b 的值 : 200
交换后,a 的值 : 200
交换后,b 的值 : 100
*/
```
**Go语言函数作为实参**
```go
package main
import(
"fmt"
"math"
)
func main(){
getSquareRoot := func(x float64) float64{
return math.Sqrt(x)
}
fmt.Println(getSquareRoot(9))
}
```
**函数作为参数传递,实现回调**
```go
package main
import "fmt"
// 声明一个函数类型
type cb func(int) int
func main() {
testCallBack(1, callBack)
testCallBack(2, func(x int) int {
fmt.Printf("我是回调,x:%d\n", x)
return x
})
}
func testCallBack(x int, f cb) {
f(x)
}
func callBack(x int) int {
fmt.Printf("我是回调,x:%d\n", x)
return x
}
/*
我是回调,x:1
我是回调,x:2
*/
```
**Go函数闭包**
Go语言支持匿名函数,可作为闭包。匿名函数是一个“内联”语句或表达式。匿名函数优越性在于可直接使用函数内的变量,不必声明。
实例:创建函数getSequence(),返回另外一个函数
```go
package main
import "fmt"
func getSequence() func() int {
i:=0
return func() int {
i+=1
return i
}
}
func main(){
/* nextNumber 为一个函数,函数 i 为 0 */
nextNumber := getSequence()
/* 调用 nextNumber 函数,i 变量自增 1 并返回 */
fmt.Println(nextNumber())
fmt.Println(nextNumber())
fmt.Println(nextNumber())
/* 创建新的函数 nextNumber1,并查看结果 */
nextNumber1 := getSequence()
fmt.Println(nextNumber1())
fmt.Println(nextNumber1())
}
/*
1
2
3
1
2
*/
```
闭包带参数:
```go
package main
import "fmt"
func main() {
add_func := add(1,2)
fmt.Println(add_func())
fmt.Println(add_func())
fmt.Println(add_func())
}
// 闭包使用方法
func add(x1, x2 int) func()(int,int) {
i := 0
return func() (int,int){
i++
return i,x1+x2
}
}
/*
1 3
2 3
3 3
*/
```
```go
package main
import "fmt"
func main() {
add_func := add(1,2)
fmt.Println(add_func(1,1))
fmt.Println(add_func(0,0))
fmt.Println(add_func(2,2))
}
// 闭包使用方法
func add(x1, x2 int) func(x3 int,x4 int)(int,int,int) {
i := 0
return func(x3 int,x4 int) (int,int,int){
i++
return i,x1+x2,x3+x4
}
}
/*
1 3 2
2 3 0
3 3 4
*/
```
**Go语言函数方法**
Go语言同时有函数和方法。一个方法就是一个包含了接受者的参数,接受者可以是命名类型或者是结构体类型的一个值或者是一个指针。所有给定类型的方法属于该类型的方法集。
```go
func(variable_name variable_data_type) function_name()[return_type]{
/* 函数体 */
}
```
实例:
```go
package main
import (
"fmt"
)
/* 定义结构体 */
type Circle struct {
radius float64
}
func main() {
var c1 Circle
c1.radius = 10.00
fmt.Println("圆的面积 = ", c1.getArea())
}
//该 method 属于 Circle 类型对象中的方法
func (c Circle) getArea() float64 {
//c.radius 即为 Circle 类型对象中的属性
return 3.14 * c.radius * c.radius
}
```
### 11. Go语言变量作用域
作用域为已声明标识符所表示的常量、类型、变量、函数或包在源代码中的作用范围
- 函数内定义的变量称为局部变量
- 函数外定义的变量称为全局变量
- 函数定义中的变量称为形式参数
**局部变量**
作用域只在函数体内,参数和返回值变量也是局部变量
**全局变量**
全局变量可在整个包甚至外部包(被导出后)使用
全局变量可在任何函数使用
🔺全局变量与局部变量名称可以相同,但函数内的局部变量会被优先考虑
**形式参数**
作为函数局部变量使用
**初始化局部和全局变量**
| 数据类型 | 初始化默认值 |
| -------- | ------------ |
| int | 0 |
| float32 | 0 |
| pointer | nil |
### 12. Go数组
数组是具有相同唯一类型的一组已编号且长度固定的数据项序列,这种类型可以是任意的原始类型如整型、字符串或自定义类型。
**声明数组**
```go
var balance [10] float32
```
如上定义了数组名为balance,长度为10,类型为float32
**初始化数组**
```go
var balance = [5]float32{100.0,2.0,3.6,7.0,24.0}
```
如果忽略[]中数字不设置数组大小,Go语言会根据元素的个数来设置数组大小:
```go
var balance = [...]float32{100.0,2.0,3.6,7.0,24.0}
```
**访问数组元素**
```go
package main
import "fmt"
func main(){
var n = [4]int{1,3,4}
n[3] = 7
for i:=0;i<len(n);i++{
fmt.Printf("n[%d] = %d\n", i,n[i])
}
}
```
**多维数组**
```go
var arrayName [x][y] variable_type
```
初始化二维数组
```go
a = [2][3] int{
{0,1,2},
{3,4,5},
}
```
访问二维数组元素
```go
package main
import "fmt"
func main(){
var a = [2][3]int{
{1,2,3},
{4,5,6},
}
for i:=0;i<len(a);i++{
for j:=0;j<len(a[0]);j++{
fmt.Printf("a[%d][%d] = %d\n",i,j,a[i][j])
}
}
}
```
**向函数传递数组**
- 形参设定数组大小:
```go
void myFunction(param [10]int)
{
...
}
```
- 形参未设定数组大小:
```go
void myFunction(param []int)
{
...
}
```
实例:
```go
package main
import "fmt"
func main(){
var n = [4]int{1,2,3,4}
fmt.Println(getSum(n))
}
func getSum(arr[4]int) int {
var sum int
for i:=0;i<len(arr);i++{
sum+=arr[i]
}
return sum
}
```
### 13. Go切片(Slice)
Go切片是对数组的抽象。Go数组长度不可变,而切片长度不固定,可以追加元素,在追加时可使切片容量增大
**定义切片**
```go
var identifier []type
var slice1 []type = make([]type,len)
var slice1 []type = make([]T,length,capacity)
```
len是数组长度也是切片初始长度,容量capacity为可选参数
**切片初始化**
```go
s :=[] int{1,2,3} //cap=len=3
s := arr[:] //s是对arr的引用
s := arr[start:end]
s := arr[start:]
s := arr[:end]
s1 := s[start:end] //用切片s初始化切片s1
s := make([]int,len,cap)
```
**len()和cap()**
```go
package main
import "fmt"
func main(){
var slice1 = make([]int,2,6)
printSlice(slice1)
}
func printSlice(x []int){
fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)
}
/*
len=2 cap=6 slice=[0 0]
*/
```
切片是可索引的,由 `len()`获取长度,由 `cap()`测量切片最长可达到多少
**空(nil)切片**
一个切片在未初始化之前默认为nil,长度为0
**切片截取**
```go
package main
import "fmt"
func main(){
var slice1 =make([]int,2,6)
slice1 = []int{1,3,4,5,6}
fmt.Println(slice1[2:5])
fmt.Println(slice1[:])
fmt.Println(slice1[:2])
fmt.Println(slice1[3:])
nums1 := make([]int,1,5)
printSlice(nums1)
nums2 := slice1[:2]
printSlice(nums2)
nums3 := slice1[3:4]
printSlice(nums3)
}
func printSlice(x []int){
fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)
}
/*
[4 5 6]
[1 3 4 5 6]
[1 3]
[5 6]
len=1 cap=5 slice=[0]
len=2 cap=5 slice=[1 3]
len=1 cap=2 slice=[5]
*/
```
**append()和copy()**
如想增加切片容量,必须创建一个新的更大的切片并把原分片的内容都拷贝过来
```go
package main
import "fmt"
func main(){
var slice1 []int
printSlice(slice1)
slice1 = append(slice1,0)
printSlice(slice1)
slice1 = append(slice1,1)
printSlice(slice1)
slice1 = append(slice1,2,3,4)
printSlice(slice1)
slice2 := make([]int,len(slice1),(cap(slice1))*2)
copy(slice2,slice1)
printSlice(slice2)
}
func printSlice(x []int){
fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)
}
/*
len=0 cap=0 slice=[]
len=1 cap=1 slice=[0]
len=2 cap=2 slice=[0 1]
len=5 cap=6 slice=[0 1 2 3 4]
len=5 cap=12 slice=[0 1 2 3 4]
*/
```
⭐对于底层数组容量为k的切片slice[i:j],长度为 j-i,容量为 k-i
⭐Q:**为什么上面代码中有一步骤cap是变成6?**
`append(list,[params])`
- 当一个一个添加元素时
len(list)+1<=cap: cap = cap
len(list)+1>cap: cap = 2*cap
- 当同时添加多个元素时
len(list)+len([params])为偶数: cap = len(list)+len([params])
len(list)+len([params])为奇数: cap = len(list)+len([params])+1
⭐函数调用时,slice按引用传递,array按值传递
```go
package main
import "fmt"
func main(){
changeTest()
}
func changeTest(){
arr1 := []int{1,2}
arr2 := [2]int{1,2}
arr3 := [2]int{1,2}
fmt.Println("before:arr1",arr1)
changeSlice(arr1)
fmt.Println("after:arr1",arr1)
fmt.Println("before:arr1",arr2)
changeArray(arr2)
fmt.Println("after:arr1",arr2)
fmt.Println("before:arr1",arr3)
changeArrayByPointer(&arr3)
fmt.Println("after:arr1",arr3)
}
func changeSlice(arr[]int){
arr[0] = 50
}
func changeArray(arr [2]int){
arr[0] = 50
}
func changeArrayByPointer(arr *[2]int){
arr[0] = 50
}
/*
before:arr1 [1 2]
after:arr1 [50 2]
before:arr1 [1 2]
after:arr1 [1 2]
before:arr1 [1 2]
after:arr1 [50 2]
*/
```
### 14. Go指针
Go语言取地址符是&,放到一个变量前会返回相应变量内存地址
```go
package main
import "fmt"
func main(){
var a int = 5
fmt.Printf("变量地址:%x\n",&a)
}
/*
变量地址:c0000a0090
*/
```
**什么是指针**
一个指针变量指向了一个值的内存地址
声明指针:
```go
var var_name *var-type //指向var-type类型
```
**使用指针**
```go
package main
import "fmt"
func main(){
var a int = 5
var ip *int
ip = &a
fmt.Printf("a 变量地址:%x\n",&a)
fmt.Printf("ip 变量存储的指针地址:%x\n",ip)
fmt.Printf("ip变量的值:%d\n",*ip)
}
/*
a 变量地址:c00000c0e8
ip 变量存储的指针地址:c00000c0e8
ip变量的值:5
*/
```
**空指针**
当一个指针被定义后没有分配到任何变量时,它的值为nil
nil指针也称为空指针。
```go
package main
import "fmt"
func main(){
var ptr *int
fmt.Printf("ptr值:%x\n",ptr)
fmt.Println(ptr)
fmt.Println(&ptr)
}
/*
ptr值:0
<nil>
0xc000006028
*/
```
**指针数组**
在使用数组时,有时可能需要保存数组,就需要用到指针
```go
package main
import "fmt"
func main(){
arr := [3]int{2,4,6}
var ptr [3]*int
for i:=0;i<len(arr);i++{
ptr[i] = &arr[i]
}
for j:=0;j<len(arr);j++{
fmt.Printf("arr[%d] = %d\n",j,*ptr[j])
}
}
/*
arr[0] = 2
arr[1] = 4
arr[2] = 6
*/
```
⭐创建指针数组时,不适合用range循环
**指向指针的指针**
如果一个指针变量存放的又是另一个指针变量的地址,则称这个指针变量为指向指针的指针变量
```go
package main
import "fmt"
func main(){
var a int = 10
var ptr *int
var pptr **int
ptr = &a
pptr = &ptr
fmt.Printf("a = %d\n",a)
fmt.Printf("*ptr = %d\n",*ptr)
fmt.Printf("**ptr = %d\n",**pptr)
fmt.Printf("pptr = %x\n",pptr)
fmt.Printf("ptr = %x\n",ptr)
}
/*
a = 10
*ptr = 10
**ptr = 10
pptr = c000006028
ptr = c00000c0e8
*/
```
**指针作为函数参数**
### 15. Go结构体
数组可存储同一类型数据,结构体中可为不同项定义不同的数据类型。
结构体是由一系列具有相同类型或不同类型的数据构成的数据集合。
**定义结构体**
```go
type struct_variable_type struct{
member definition
member definition
member definition
}
```
接下来可用于变量声明
```go
variable_name := struct_variable_type {value1,value2,...,valuen}
variable_name := struct_variable_type {key1:value1,key2:value2,...,keyn:valuen}
```
**访问结构体成员**
```go
结构体。成员名
```
使用点号操作符
**结构体作为函数参数**
**结构体指针**
```go
var struct_pointer *Books
struct_pointer = &Book1
struct_pointer.title //访问成员
```
实例:
```go
package main
import "fmt"
type Books struct{
title string
id int
author string
}
func main(){
fmt.Println(Books{"abc",12,"Anna"})
fmt.Println(Books{title:"abcd",id:10,author:"Bobby"})
var book1 Books
book1.title = "Go语言"
book1.id = 12345
book1.author = "Louis"
printBook(book1)
printBook2(&book1)
changeBook(book1)
fmt.Println(book1.id)
changeBook2(&book1)
fmt.Println(book1.id)
}
func printBook(book Books){
fmt.Printf("Book author : %s\n",book.author)
}
func printBook2(book *Books){
fmt.Printf("Book id : %d\n",book.id)
}
func changeBook(book Books){
book.id = 123
}
func changeBook2(book *Books){
book.id = 123456
}
/*
{abc 12 Anna}
{abcd 10 Bobby}
Book author : Louis
Book id : 12345
12345
123456
*/
```
⭐结构体是作为参数的值传递,想要在函数里面改变结构体数据内容需要传入指针
### 16. Go范围(Range)
range关键字用于for循环中迭代数组、切片、通道或集合的元素。在数组和切片中它返回元素的索引和索引对应的值,在集合中返回key-value对
```go
package main
import "fmt"
func main(){
nums := [3]int{1,2,3}
sum := 0
length := 0
for range nums{
length++
}
fmt.Println(length)
for _,num:=range nums{
sum+=num
}
fmt.Println(sum)
kvs := map[string]string{"a":"apple","b":"banana"}
for k,v := range kvs{
fmt.Printf("%s -> %s\n",k,v)
}
// 枚举Unicode字符串
for i,c := range "go"{
fmt.Println(i,c)
}
}
/*
3
6
a -> apple
b -> banana
0 103
1 111
*/
```
### 17. Go的Map(集合)
Map是一种无序的键值对集合,通过key快速检索数据,key类似索引,指向数据值。
可以像迭代数组和切片那样迭代它,但无法决定它的返回顺序,因为Map是以hash表实现的。
**定义Map**
```go
var map_variable map[key_data_type]value_data_type
map_variable := make(map[key_data_type]value_data_type)
```
如果不初始化map,就会创建一个nil map。nil map不能用来存放键值对。
**delete()**
delete()函数用于删除集合元素,参数为map和其对应的key
```go
package main
import "fmt"
func main(){
var myMap map[string]int
myMap = make(map[string]int)
myMap["a"] = 1
myMap["b"] = 2
myMap["e"] = 5
for k,v:=range myMap{
fmt.Printf("%s -> %d\n",k,v)
}
character,ok := myMap["d"]
if(ok){
fmt.Println(character)
}else{
fmt.Println("not exist")
}
delete(myMap,"a")
fmt.Println(myMap)
}
/*
e -> 5
a -> 1
b -> 2
not exist
map[b:2 e:5]
*/
```
### 18. Go递归函数
使用递归时,开发者需要设置退出条件,否则递归将陷入无限循环。
**斐波那契数列**
```go
package main
import "fmt"
func main(){
a:=6
fmt.Println(fib(a))
}
func fib(n int)int{
if(n<2){
return n
}
return fib(n-1)+fib(n-2)
}
```
🔺一种更好的斐波那契数列的实现
```go
package main
import "fmt"
func main(){
a:=6
fmt.Println(fib(a))
}
func fib(n int)int{
_,b:=fib2(n)
return b
}
func fib2(n int)(int,int){
if n<2{
return 0,n
}
a,b:=fib2(n-1)
return b,a+b
}
```
### 19. Go类型转换
基本格式:
```go
type_name(expression)
```
实例:
```go
package main
import "fmt"
func main(){
var a int = 17
var b int = 5
var mean float32
mean = float32(a)/float32(b)
meanint := a/b
fmt.Println(mean)
fmt.Println(meanint)
}
/*
3.4
3
*/
```
### 20. Go接口
把所有具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口
```go
type interface_name interface{
method_name1 [return_type]
...
method_namen [return_type]
}
type struct_name struct{
}
func (struct_name_variable struct_name) method_name1() [return_type]{
}
func (struct_name_variable struct_name) method_namen() [return_type]{
}
```
**普通实例**
```go
package main
import "fmt"
type Animal interface {
run()
}
type Dog struct{
}
type Cat struct{
}
func (dog Dog) run(){
fmt.Println("Dog run")
}
func (cat Cat) run(){
fmt.Println("Cat run")
}
func main(){
var animal Animal
animal = new(Dog)
animal.run()
animal = new(Cat)
animal.run()
}
/*
Dog run
Cat run
*/
```
**接口增加参数**
```go
package main
import "fmt"
type Animal interface {
name() string
}
type Dog struct{
}
func (dog Dog) name() string{
return "Bobby"
}
func main(){
var animal Animal
animal = new(Dog)
fmt.Println(animal.name())
}
/*
Bobby
*/
```
**接口方法传参和返回结果**
```go
package main
import "fmt"
type Animal interface {
run(s int)
}
type Dog struct{
}
func (dog Dog) run(s int){
fmt.Printf("A dog runs %d s",s)
}
func main(){
var animal Animal
animal = new(Dog)
animal.run(15)
}
/*
A dog runs 15 s
*/
```
**将接口作为参数**
```go
package main
import "fmt"
type Phone interface {
call() string
}
type Android struct{
brand string
}
type IPhone struct{
ver string
}
func (android Android) call() string{
return "Android "+ android.brand
}
func (iPhone IPhone) call() string{
return "IPhone "+iPhone.ver
}
func print(p Phone){
fmt.Println(p.call()+", I can call you.")
}
func main(){
huawei := Android{"HuaWei"}
i7 := IPhone{"7"}
print(huawei)
print(i7)
}
/*
Android HuaWei, I can call you.
IPhone 7, I can call you.
*/
```
**通过接口方法修改属性,在传入指针的结构体**
```go
package main
import "fmt"
type Animal interface {
getName() string
setName(name string)
}
type Dog struct{
name string
}
func (dog *Dog) getName() string{
return dog.name
}
func (dog *Dog) setName(name string){
dog.name = name
}
func main(){
var animal Animal
animal = new(Dog)
animal.setName("Bob")
fmt.Println(animal.getName())
animal.setName("Kot")
fmt.Println(animal.getName())
}
/*
Bob
Kot
*/
```
### 21. Go错误处理
error类型是一个接口类型:
```go
type Error interface{
Error() string
}
```
🔺通过实现error接口类型生成错误信息
函数通常在最后的返回值中返回错误信息。使用errors.New可返回一个错误信息:
```go
func Sqrt(f float64) (float64,error){
if f<0{
return 0,errors.New("math:square root of negative number")
}
}
```
调用Sqrt传递一个负数,得到non-nil的error对象,将此对象与nil比较,fmt包在处理error时会调用Error方法:
```go
result,err := Sqrt(-1)
if err != nil{
fmt.Println(err)
}
```
**除零错误实例**
```go
package main
import "fmt"
type DIV_ERR struct{
etype int
v1 int
v2 int
}
func (div_err DIV_ERR) Error() string{
if 0==div_err.etype {
return "除零错误"
}else{
return "其他未知错误"
}
}
func div(a int,b int)(int,*DIV_ERR){
if b==0{
return 0,&DIV_ERR{0,a,b}
}else{
return a/b,nil
}
}
func main(){
_,r := div(50,5)
if nil != r{
fmt.Println("fail")
}else{
fmt.Println("succeed")
}
_,r = div(50,0)
if nil!=r{
fmt.Println("fail")
}else{
fmt.Println("succeed")
}
}
```
**panic、recover、defer**
panic和recover是内置函数,用于处理Go运行时的错误。
panic主动抛出错误,recover捕获panic抛出的错误
🔺引发panic两种情况:①程序主动调用、②程序产生运行时错误,由运行时检测并退出
🔺发生panic后,程序从调用panic的函数位置或发生panic的地方立即返回,逐层向上执行函数defer语句,然后逐层打印函数调用堆栈,直到被recover捕获或运行到最外层函数
🔺panic不但可在函数正常流程中抛出,在defer逻辑里也可以再次调用panic或抛出panic。defer里面的panic能够被后续执行的defer捕获。
🔺recover用来捕获panic,阻止panic继续向上传递。recover()和defer一起使用,但是defer只有后面的函数体内直接被调用才能捕获panic来终止异常,否则返回nil,异常继续向外传递
实例1:
```go
package main
import "fmt"
func main(){
defer func(){
if err := recover() ; err != nil {
fmt.Println(err)
}
}()
defer func(){
panic("three")
}()
defer func(){
panic("two")
}()
panic("one")
}
/*
three
*/
```
多个panic只会捕捉最后一个
🔺panic在没有用recover前以及在recover捕获那一级函数栈,panic之后的代码均不会执行;一旦被recover捕获后,外层的函数栈代码恢复正常,所有代码均会得到执行
🔺panic后,不再执行后面的代码,立即按照逆序执行defer,并逐级往外层函数栈扩散;defer类似finally
🔺利用recover捕获panic时,defer需要在panic之前声明,否则由于panic之后的代码得不到执行,因此也无法recover
实例2:
```go
package main
import "fmt"
func main() {
fmt.Println("外层开始")
defer func() {
fmt.Println("外层准备recover")
if err := recover(); err != nil {
fmt.Printf("%#v-%#v\n", "外层", err) // err已经在上一级的函数中捕获了,这里没有异常,只是例行先执行defer,然后执行后面的代码
} else {
fmt.Println("外层没做啥事")
}
fmt.Println("外层完成recover")
}()
fmt.Println("外层即将异常")
f()
fmt.Println("外层异常后")
defer func() {
fmt.Println("外层异常后defer")
}()
}
func f() {
fmt.Println("内层开始")
defer func() {
fmt.Println("内层recover前的defer")
}()
defer func() {
fmt.Println("内层准备recover")
if err := recover(); err != nil {
fmt.Printf("%#v-%#v\n", "内层", err) // 这里err就是panic传入的内容
}
fmt.Println("内层完成recover")
}()
defer func() {
fmt.Println("内层异常前recover后的defer")
}()
panic("异常信息")
defer func() {
fmt.Println("内层异常后的defer")
}()
fmt.Println("内层异常后语句") //recover捕获的一级或者完全不捕获这里开始下面代码不会再执行
}
/*
外层开始
外层即将异常
内层开始
内层异常前recover后的defer
内层准备recover
"内层"-"异常信息"
内层完成recover
内层recover前的defer
外层异常后
外层异常后defer
外层准备recover
外层没做啥事
外层完成recover
*/
```
### 22. Go并发
通过go关键字开启goroutine。
goroutine是轻量级线程,goroutine的调度是由Golang运行时进行管理的。
goroutine语法格式:
```go
go 函数名(参数列表)
```
Go允许使用go语句开启一个新的运行期线程,即goroutine,以一个不同的、新创建的goroutine来执行一个函数。
同一个程序中所有goroutine共享同一个地址空间。
```go
package main
import (
"fmt"
"time"
)
func print(s string){
for i:=0;i<5;i++{
time.Sleep(100*time.Millisecond)
fmt.Println(s)
}
}
func main(){
go print("a")
print("b")
}
/*
a
b
b
a
a
b
a
b
b
a
*/
```
输出没有固定顺序
**通道(Channel)**
通道是用来传递数据的一个数据结构。
通道可用于两个goroutine之间通过传递一个指定类型的值来同步运行和通讯。
操作符 `<-`用于指定通道方向,发送或接收。如果未指定方向,则为双向通道。
```go
ch <- v //把v发送到通道ch
v := <- ch //从ch接收数据并把值赋给v
```
声明一个通道:
```go
ch := make(chan int)
```
⭐默认通道不带缓冲区。发送端发送数据,同时必须有接收端相应的接收数据
实例:
```go
package main
import "fmt"
func sum(arr[]int,c chan int){
sum := 0
for _,v := range(arr){
sum+=v
}
c <- sum
}
func main(){
arr:=[]int{1,4,2,3,2,7}
c:=make(chan int)
go sum(arr[:len(arr)/2],c)
go sum(arr[len(arr)/2:],c)
a,b:=<-c,<-c
fmt.Println(a,b)
}
/*
12 7
*/
```
**通道缓冲区**
通过make的第二个参数指定缓冲区大小:
```go
ch := make(chan int,100)
```
带缓冲区的通道允许发送端的数据发送和接收端的数据获取处于异步状态,即发送端发送的数据可以放在缓冲区里,等待接收端获取数据,而不是立刻需要接收端获取数据。
但缓冲区大小有限,还是必须有接收端接收数据,否则缓冲区一满数据发送端就无法再发送数据了。
⭐如果通道不带缓冲,发送方会阻塞直到接收方从通道中接收了值。如果通道带缓冲,发送方则会阻塞直到发送的值被拷贝到缓冲区内;如果缓冲区已满,意味着需要等待直到某个接收方获取到一个值。接收方在有值可以接收之前会一直阻塞。
```go
package main
import "fmt"
func main(){
ch := make(chan int,10)
ch <- 1
ch <- 3
ch <- 4
fmt.Println(<-ch)
fmt.Println(<-ch)
fmt.Println(<-ch)
}
/*
1
3
4
*/
```
**遍历通道与关闭通道**
```go
package main
import (
"fmt"
"time"
)
func main(){
ch := make(chan int,10)
go fib(cap(ch),ch)
/*
如果ch通道不关闭,那么range函数就不会结束,从而在接收第11个数据时会阻塞
*/
for i:=range ch{
fmt.Println(i)
}
}
func fib(n int,c chan int){
x,y:=0,1
for i:=0;i<n;i++{
c <- x
x, y = y,x+y
time.Sleep(1000*time.Millisecond)
}
close(c)
}
```
🔺关闭通道并不会丢失里面的数据,只是让读取通道数据的时候不会读完之后一直阻塞等待新数据写入
🔺Channel可以控制读写权限
```go
go func(c chan int) // 读写均可的channel
go func(c <- chan int) //只读的channel
go func(c chan <- int) //只写的channel
```
⭐通道遵循先进先出原则:
```go
package main
import "fmt"
func main(){
ch := make(chan int,2)
ch <- 1
a:= <- ch
ch <- 2
ch <- 3
fmt.Println(<-ch)
fmt.Println(<-ch)
fmt.Println(a)
}
/*
2
3
1
*/
```
🔺一个实例:
```go
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s, (i+1)*100)
}
}
func say2(s string) {
for i := 0; i < 5; i++ {
time.Sleep(150 * time.Millisecond)
fmt.Println(s, (i+1)*150)
}
}
func main() {
go say2("world")
say("hello")
}
/*
hello 100
world 150
hello 200
world 300
hello 300
hello 400
world 450
hello 500
*/
```
say2只执行了3次,而不是5次,是因为goroutine还没来得及跑完5次主函数已经退出了。
下面想办法阻止主函数结束,要等待goroutine执行完成后,再退出主函数。
```go
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s, (i+1)*100)
}
}
func say2(s string, ch chan int) {
for i := 0; i < 5; i++ {
time.Sleep(150 * time.Millisecond)
fmt.Println(s, (i+1)*150)
}
ch <- 0
close(ch)
}
func main() {
ch := make(chan int)
go say2("world", ch)
say("hello")
fmt.Println(<-ch)
}
```
引入一个默认信道,信道的存消息和取消息都是阻塞的,goroutine执行完后给信道一个值0,则主函数会一直等待信道中的值,一旦信道有值主函数才会结束。
|
PHP
|
UTF-8
| 2,386 | 2.515625 | 3 |
[] |
no_license
|
<?php
namespace RessourceBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* groupe
*
* @ORM\Table(name="groupe")
* @ORM\Entity(repositoryClass="RessourceBundle\Repository\groupeRepository")
*/
class Groupe
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
* @ORM\Column(name="designation", type="string", length=255)
*/
private $designation;
/**
* @ORM\OneToMany(targetEntity="Enfant", mappedBy="groupe",cascade={"persist"})
*/
private $enfants;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set designation
*
* @param string $designation
*
* @return groupe
*/
public function setLabelG($designation)
{
$this->designation = $designation;
return $this;
}
/**
* Get designation
*
* @return string
*/
public function getLabelG()
{
return $this->designation;
}
/**
* Set designation
*
* @param string $designation
*
* @return Groupe
*/
public function setDesignation($designation)
{
$this->designation = $designation;
return $this;
}
/**
* Get designation
*
* @return string
*/
public function getDesignation()
{
return $this->designation;
}
/**
* Constructor
*/
public function __construct()
{
$this->enfants = new ArrayCollection();
}
/**
* Add enfant
*
* @param Enfant $enfant
*
* @return Groupe
*/
public function addEnfant(Enfant $enfant)
{
$this->enfants[] = $enfant;
return $this;
}
/**
* Remove enfant
*
* @param Enfant $enfant
*/
public function removeEnfant(Enfant $enfant)
{
$this->enfants->removeElement($enfant);
}
/**
* Get enfants
*
* @return Collection
*/
public function getEnfants()
{
return $this->enfants;
}
public function __toString()
{
return $this->designation;
}
}
|
Java
|
UTF-8
| 1,499 | 2.109375 | 2 |
[] |
no_license
|
package uk.co.thomasc.codmw.killstreaks;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import uk.co.thomasc.codmw.Main;
import uk.co.thomasc.codmw.objects.MineCodListener;
import uk.co.thomasc.codmw.objects.Reason;
import uk.co.thomasc.codmw.objects.CPlayer;
import uk.co.thomasc.codmw.objects.SpawnItems;
public class Killstreak extends MineCodListener {
int starttick = 0;
public Killstreak(Main instance, Player owner, Object[] args) {
super(instance, owner);
starttick = plugin.game.time;
getOwnerplayer().addPoints(3);
}
public int getLifetime() {
return plugin.game.time - starttick;
}
public void teamSwitch() {
}
@Override
public int onDamage(int damage, Player attacker, Player defender, Reason reason, Object ks) {
return damage;
}
@Override
public void onKill(CPlayer attacker, CPlayer defender, Reason reason, Object ks) {
}
@Override
public void onInteract(PlayerInteractEvent event) {
}
@Override
public void onMove(PlayerMoveEvent event, boolean blockmove) {
}
@Override
public void tickfast() {
}
@Override
public void tick() {
}
@Override
public void afterDeath(CPlayer p) {
}
@Override
public void onRespawn(CPlayer p, SpawnItems inventory) {
}
@Override
public double getVar(CPlayer p, String name, double def) {
return def;
}
}
|
Java
|
UTF-8
| 9,800 | 2.09375 | 2 |
[] |
no_license
|
package com.eclipsesource.v8;
import com.tencent.matrix.trace.core.AppMethodBeat;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
public class PlatformDetector$Vendor
{
private static final String LINUX_ID_PREFIX = "ID=";
private static final String[] LINUX_OS_RELEASE_FILES = { "/etc/os-release", "/usr/lib/os-release" };
private static final String REDHAT_RELEASE_FILE = "/etc/redhat-release";
private static void closeQuietly(Closeable paramCloseable)
{
AppMethodBeat.i(75017);
if (paramCloseable != null);
try
{
paramCloseable.close();
AppMethodBeat.o(75017);
return;
}
catch (IOException paramCloseable)
{
while (true)
AppMethodBeat.o(75017);
}
}
private static String getLinuxOsReleaseId()
{
AppMethodBeat.i(75014);
Object localObject = LINUX_OS_RELEASE_FILES;
int i = localObject.length;
int j = 0;
if (j < i)
{
File localFile = new File(localObject[j]);
if (localFile.exists())
{
localObject = parseLinuxOsReleaseFile(localFile);
AppMethodBeat.o(75014);
}
}
while (true)
{
return localObject;
j++;
break;
localObject = new File("/etc/redhat-release");
if (!((File)localObject).exists())
break label85;
localObject = parseLinuxRedhatReleaseFile((File)localObject);
AppMethodBeat.o(75014);
}
label85: localObject = new UnsatisfiedLinkError("Unsupported linux vendor: " + getName());
AppMethodBeat.o(75014);
throw ((Throwable)localObject);
}
public static String getName()
{
AppMethodBeat.i(75013);
if (PlatformDetector.OS.isWindows())
{
localObject = "microsoft";
AppMethodBeat.o(75013);
}
while (true)
{
return localObject;
if (PlatformDetector.OS.isMac())
{
localObject = "apple";
AppMethodBeat.o(75013);
}
else if (PlatformDetector.OS.isLinux())
{
localObject = getLinuxOsReleaseId();
AppMethodBeat.o(75013);
}
else
{
if (!PlatformDetector.OS.isAndroid())
break;
localObject = "google";
AppMethodBeat.o(75013);
}
}
Object localObject = new UnsatisfiedLinkError("Unsupported vendor: " + getName());
AppMethodBeat.o(75013);
throw ((Throwable)localObject);
}
// ERROR //
private static String parseLinuxOsReleaseFile(File paramFile)
{
// Byte code:
// 0: aconst_null
// 1: astore_1
// 2: aconst_null
// 3: astore_2
// 4: ldc 112
// 6: invokestatic 41 com/tencent/matrix/trace/core/AppMethodBeat:i (I)V
// 9: new 114 java/io/BufferedReader
// 12: astore_3
// 13: new 116 java/io/InputStreamReader
// 16: astore 4
// 18: new 118 java/io/FileInputStream
// 21: astore 5
// 23: aload 5
// 25: aload_0
// 26: invokespecial 121 java/io/FileInputStream:<init> (Ljava/io/File;)V
// 29: aload 4
// 31: aload 5
// 33: ldc 123
// 35: invokespecial 126 java/io/InputStreamReader:<init> (Ljava/io/InputStream;Ljava/lang/String;)V
// 38: aload_3
// 39: aload 4
// 41: invokespecial 129 java/io/BufferedReader:<init> (Ljava/io/Reader;)V
// 44: aload_3
// 45: invokevirtual 132 java/io/BufferedReader:readLine ()Ljava/lang/String;
// 48: astore 4
// 50: aload_2
// 51: astore_0
// 52: aload 4
// 54: ifnull +23 -> 77
// 57: aload 4
// 59: ldc 11
// 61: invokevirtual 136 java/lang/String:startsWith (Ljava/lang/String;)Z
// 64: ifeq -20 -> 44
// 67: aload 4
// 69: iconst_3
// 70: invokevirtual 140 java/lang/String:substring (I)Ljava/lang/String;
// 73: invokestatic 144 com/eclipsesource/v8/PlatformDetector:access$300 (Ljava/lang/String;)Ljava/lang/String;
// 76: astore_0
// 77: aload_3
// 78: invokestatic 146 com/eclipsesource/v8/PlatformDetector$Vendor:closeQuietly (Ljava/io/Closeable;)V
// 81: ldc 112
// 83: invokestatic 49 com/tencent/matrix/trace/core/AppMethodBeat:o (I)V
// 86: aload_0
// 87: areturn
// 88: astore_0
// 89: aconst_null
// 90: astore_3
// 91: aload_3
// 92: invokestatic 146 com/eclipsesource/v8/PlatformDetector$Vendor:closeQuietly (Ljava/io/Closeable;)V
// 95: ldc 112
// 97: invokestatic 49 com/tencent/matrix/trace/core/AppMethodBeat:o (I)V
// 100: aload_1
// 101: astore_0
// 102: goto -16 -> 86
// 105: astore_3
// 106: aconst_null
// 107: astore_0
// 108: aload_0
// 109: invokestatic 146 com/eclipsesource/v8/PlatformDetector$Vendor:closeQuietly (Ljava/io/Closeable;)V
// 112: ldc 112
// 114: invokestatic 49 com/tencent/matrix/trace/core/AppMethodBeat:o (I)V
// 117: aload_3
// 118: athrow
// 119: astore_1
// 120: aload_3
// 121: astore_0
// 122: aload_1
// 123: astore_3
// 124: goto -16 -> 108
// 127: astore_0
// 128: goto -37 -> 91
//
// Exception table:
// from to target type
// 9 44 88 java/io/IOException
// 9 44 105 finally
// 44 50 119 finally
// 57 77 119 finally
// 44 50 127 java/io/IOException
// 57 77 127 java/io/IOException
}
// ERROR //
private static String parseLinuxRedhatReleaseFile(File paramFile)
{
// Byte code:
// 0: aconst_null
// 1: astore_1
// 2: ldc 147
// 4: invokestatic 41 com/tencent/matrix/trace/core/AppMethodBeat:i (I)V
// 7: new 114 java/io/BufferedReader
// 10: astore_2
// 11: new 116 java/io/InputStreamReader
// 14: astore_3
// 15: new 118 java/io/FileInputStream
// 18: astore 4
// 20: aload 4
// 22: aload_0
// 23: invokespecial 121 java/io/FileInputStream:<init> (Ljava/io/File;)V
// 26: aload_3
// 27: aload 4
// 29: ldc 123
// 31: invokespecial 126 java/io/InputStreamReader:<init> (Ljava/io/InputStream;Ljava/lang/String;)V
// 34: aload_2
// 35: aload_3
// 36: invokespecial 129 java/io/BufferedReader:<init> (Ljava/io/Reader;)V
// 39: aload_2
// 40: invokevirtual 132 java/io/BufferedReader:readLine ()Ljava/lang/String;
// 43: astore_0
// 44: aload_0
// 45: ifnull +78 -> 123
// 48: aload_0
// 49: getstatic 153 java/util/Locale:US Ljava/util/Locale;
// 52: invokevirtual 157 java/lang/String:toLowerCase (Ljava/util/Locale;)Ljava/lang/String;
// 55: astore_0
// 56: aload_0
// 57: ldc 159
// 59: invokevirtual 163 java/lang/String:contains (Ljava/lang/CharSequence;)Z
// 62: ifeq +17 -> 79
// 65: ldc 159
// 67: astore_0
// 68: aload_2
// 69: invokestatic 146 com/eclipsesource/v8/PlatformDetector$Vendor:closeQuietly (Ljava/io/Closeable;)V
// 72: ldc 147
// 74: invokestatic 49 com/tencent/matrix/trace/core/AppMethodBeat:o (I)V
// 77: aload_0
// 78: areturn
// 79: aload_0
// 80: ldc 165
// 82: invokevirtual 163 java/lang/String:contains (Ljava/lang/CharSequence;)Z
// 85: ifeq +9 -> 94
// 88: ldc 165
// 90: astore_0
// 91: goto -23 -> 68
// 94: aload_0
// 95: ldc 167
// 97: invokevirtual 163 java/lang/String:contains (Ljava/lang/CharSequence;)Z
// 100: ifeq +9 -> 109
// 103: ldc 169
// 105: astore_0
// 106: goto -38 -> 68
// 109: aload_2
// 110: invokestatic 146 com/eclipsesource/v8/PlatformDetector$Vendor:closeQuietly (Ljava/io/Closeable;)V
// 113: ldc 147
// 115: invokestatic 49 com/tencent/matrix/trace/core/AppMethodBeat:o (I)V
// 118: aload_1
// 119: astore_0
// 120: goto -43 -> 77
// 123: aload_2
// 124: invokestatic 146 com/eclipsesource/v8/PlatformDetector$Vendor:closeQuietly (Ljava/io/Closeable;)V
// 127: ldc 147
// 129: invokestatic 49 com/tencent/matrix/trace/core/AppMethodBeat:o (I)V
// 132: aload_1
// 133: astore_0
// 134: goto -57 -> 77
// 137: astore_0
// 138: aconst_null
// 139: astore_2
// 140: aload_2
// 141: invokestatic 146 com/eclipsesource/v8/PlatformDetector$Vendor:closeQuietly (Ljava/io/Closeable;)V
// 144: goto -17 -> 127
// 147: astore_0
// 148: aconst_null
// 149: astore_2
// 150: aload_2
// 151: invokestatic 146 com/eclipsesource/v8/PlatformDetector$Vendor:closeQuietly (Ljava/io/Closeable;)V
// 154: ldc 147
// 156: invokestatic 49 com/tencent/matrix/trace/core/AppMethodBeat:o (I)V
// 159: aload_0
// 160: athrow
// 161: astore_0
// 162: goto -12 -> 150
// 165: astore_0
// 166: goto -26 -> 140
//
// Exception table:
// from to target type
// 7 39 137 java/io/IOException
// 7 39 147 finally
// 39 44 161 finally
// 48 65 161 finally
// 79 88 161 finally
// 94 103 161 finally
// 39 44 165 java/io/IOException
// 48 65 165 java/io/IOException
// 79 88 165 java/io/IOException
// 94 103 165 java/io/IOException
}
}
/* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes2-dex2jar.jar
* Qualified Name: com.eclipsesource.v8.PlatformDetector.Vendor
* JD-Core Version: 0.6.2
*/
|
Python
|
UTF-8
| 315 | 3.515625 | 4 |
[] |
no_license
|
N = int(input())
ans = set()
for i in range(1, N+1):
for j in range(i+1, N+1):
ans.add((i, j))
if N % 2 == 1: # 奇数
for i in range(1, N+1):
j = N - i
ans.discard((i, j))
else: # 偶数
for i in range(1, N+1):
j = N + 1 - i
ans.discard((i, j))
print(len(ans))
for a in ans:
print(*a)
|
Shell
|
UTF-8
| 3,239 | 4.1875 | 4 |
[] |
no_license
|
#!/bin/bash
source_dir=$1
destination_dir=$2
# max_copies_count=10
check_paths() {
src_path=$1
dest_path=$2
if [ $src_path = $dest_path ]; then
echo 'bad'
elif [ $(dirname $src_path) = $dest_path ] ||
[ $(dirname $dest_path) = $src_path ]; then
echo 'bad'
else
echo 'ok'
fi
}
check_disk() {
src_path=$1
dest_path=$2
# kbytes
needed_space=$( du -k $src_path | tail -1 | tr -dc 0-9 )
available_space=$( df -k $dest_path | awk 'NR == 2 {print $4}' )
if [ $needed_space -lt $available_space ]; then
echo 'ok'
else
echo 'bad'
fi
}
get_date_postfix() {
printf "%s_%s" `date '+%Y%m%d'` `date '+%H%M%S'`
}
get_count_postfix() {
echo "0"
}
update_count_postfixes() {
dir=$1
name=$2
limit=$3
i=`find $dir -regextype posix-awk -regex ".*${name}_[0-9]{1,100}.tar.gz" | sort -r | wc -l`
for file in `find $dir -regextype posix-awk -regex ".*${name}_[0-9]{1,100}.tar.gz" | sort -r`; do
move_to=$(printf "%s/%s_%s.tar.gz" $(dirname $file) $name $i )
echo $file >> chk.txt
echo $move_to >> chk.txt
mv $file $move_to
(( i=i-1 ))
done
}
remove_redundant_copies() {
dir=$1
name=$2
limit=$3
i=1
for file in `find $dir -regextype posix-awk -regex ".*${name}_[0-9]{1,100}.tar.gz" | sort`; do
if [ $i -ge $limit ]; then
rm $file
fi
(( i=i+1 ))
done
}
compress_dir() {
dir_to_compress=$1
pfix=$2
# echo "${dir_to_compress}_${pfix}.tar.gz"
# echo $dir_to_compress
tar -zcvf "${dir_to_compress}_${pfix}.tar.gz" $dir_to_compress
}
complete_move() {
src_path=$1
dest_path=$2
echo $src_path
echo $dest_path
mv $src_path $dest_path
}
complete_action() {
read -p "Choose postfix type(1 for YYMMDD_HHSS | 2 for counter): " postfix_type
case $postfix_type in
1) postfix=$(get_date_postfix)
compress_dir $source_dir $postfix
complete_move "${source_dir}_${postfix}.tar.gz" $destination_dir
;;
2) read -p "Enter max copies count: " max_copies_count
postfix=$(get_count_postfix)
compress_dir $source_dir $postfix
update_count_postfixes $destination_dir `basename $source_dir` $max_copies_count
remove_redundant_copies $destination_dir `basename $source_dir` $max_copies_count
complete_move "${source_dir}_${postfix}.tar.gz" $destination_dir
;;
*) echo 'Incorrect input.'; exit 0
;;
esac
}
paths_status=$(check_paths $source_dir $destination_dir)
disk_status=$(check_paths $source_dir $destination_dir)
if [ $paths_status == 'ok' ]; then
if [ $disk_status == 'ok' ]; then
complete_action
else
read -p "Not enougth space on destination disk(С or Y to continue anyway | N or A to break):" choice
case $choice in
C|Y) complete_action
;;
N|A) exit 0
;;
*) echo 'Incorrect input.'; exit 0
;;
esac
fi
else
echo "Incorrect paths of directories."; exit 0
fi
|
Java
|
UTF-8
| 3,027 | 1.765625 | 2 |
[
"BSD-3-Clause"
] |
permissive
|
package bio.terra.service.snapshot.flight.create;
import bio.terra.common.iam.AuthenticatedUserRequest;
import bio.terra.model.BillingProfileModel;
import bio.terra.service.common.CommonMapKeys;
import bio.terra.service.dataset.flight.ingest.IngestUtils;
import bio.terra.service.filedata.azure.AzureSynapsePdao;
import bio.terra.service.filedata.azure.blobstore.AzureBlobStorePdao;
import bio.terra.service.profile.flight.ProfileMapKeys;
import bio.terra.service.resourcemanagement.azure.AzureStorageAccountResource;
import bio.terra.stairway.FlightContext;
import bio.terra.stairway.FlightMap;
import bio.terra.stairway.Step;
import bio.terra.stairway.StepResult;
import bio.terra.stairway.StepStatus;
import com.azure.storage.blob.BlobUrlParts;
import java.sql.SQLException;
import java.util.Arrays;
// TODO - this is the exact same step as used for ingest - find way to share code
public class CreateSnapshotTargetDataSourceAzureStep implements Step {
private final AzureSynapsePdao azureSynapsePdao;
private final AzureBlobStorePdao azureBlobStorePdao;
private final AuthenticatedUserRequest userRequest;
public CreateSnapshotTargetDataSourceAzureStep(
AzureSynapsePdao azureSynapsePdao,
AzureBlobStorePdao azureBlobStorePdao,
AuthenticatedUserRequest userRequest) {
this.azureSynapsePdao = azureSynapsePdao;
this.azureBlobStorePdao = azureBlobStorePdao;
this.userRequest = userRequest;
}
@Override
public StepResult doStep(FlightContext context) throws InterruptedException {
FlightMap workingMap = context.getWorkingMap();
BillingProfileModel billingProfile =
workingMap.get(ProfileMapKeys.PROFILE_MODEL, BillingProfileModel.class);
AzureStorageAccountResource snapshotAzureStorageAccountResource =
workingMap.get(
CommonMapKeys.SNAPSHOT_STORAGE_ACCOUNT_RESOURCE, AzureStorageAccountResource.class);
String snapshotParquetTargetLocation =
snapshotAzureStorageAccountResource.getStorageAccountUrl();
BlobUrlParts snapshotSignUrlBlob =
azureBlobStorePdao.getOrSignUrlForTargetFactory(
snapshotParquetTargetLocation,
billingProfile,
snapshotAzureStorageAccountResource,
userRequest);
try {
azureSynapsePdao.getOrCreateExternalDataSource(
snapshotSignUrlBlob,
IngestUtils.getTargetScopedCredentialName(context.getFlightId()),
IngestUtils.getTargetDataSourceName(context.getFlightId()));
} catch (SQLException ex) {
return new StepResult(StepStatus.STEP_RESULT_FAILURE_FATAL, ex);
}
return StepResult.getStepResultSuccess();
}
@Override
public StepResult undoStep(FlightContext context) {
azureSynapsePdao.dropDataSources(
Arrays.asList(IngestUtils.getTargetDataSourceName(context.getFlightId())));
azureSynapsePdao.dropScopedCredentials(
Arrays.asList(IngestUtils.getTargetScopedCredentialName(context.getFlightId())));
return StepResult.getStepResultSuccess();
}
}
|
Shell
|
UTF-8
| 560 | 2.90625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env bash
source config.sh
DATE=`date +%Y_%m_%d`
SUITES="engine heat_equation numpy_vs_bohrium"
#SUITES="heat_equation leibnitz_pi rosenbrock numpy_vs_bohrium"
#SUITES="engine heat_equation leibnitz_pi rosenbrock"
#SUITES="leibnitz_pi heat_equation rosenbrock"
for SUITE in $SUITES
do
echo "** Adding ${SUITE} to watch" >> $PT_REPOS/janitor.log
touch $PT_REPOS/workdir/watch/$SUITE
echo "${DATE}" >> $PT_REPOS/workdir/watch/$SUITE
#echo "01" >> $PT_REPOS/workdir/watch/$SUITE
#echo "02" >> $PT_REPOS/workdir/watch/$SUITE
done
|
JavaScript
|
UTF-8
| 5,378 | 3.03125 | 3 |
[] |
no_license
|
//适合pc端关闭网页或者跳转网页,移动端不知是否兼容
/*
*2016 12 26
*autor guangweiguo
*version 1.0.0
*
*----必须
*@wrapper 外层的包裹wrapper需要是唯一的变量名(不可重复)最好是id名 ----必须
* -----一下为非必须
*@expire为储存时间,单位日
*@selectClass 为所有要储存信息元素的class名, 默认wrapper里所有input
*@deletBtn 为删除存储所有,提交后若果先删除村粗,可以用这个btn
*@savaData 缓存的数据
*@isonbeforeunload 是否离开页面储存数据 默认是
*@isStorage 是否进行存储 默认存储
*@isTypeIn 是否把存储数据写进input框框, 默认写入 慎重写 不录入数据单可以存储数据
*@saveBtn 为立刻触发本地储存的元素 非必须
*@btnTrigger 为立即触发本地储存元素的事件, 无需on,如mouseover,click,等,如果用户自己定义的事件
*
*----方法
*此方法用于用户直接饮用,饮用方法为 --相触发事件的地方写localSave_trigger(a,b)
*localSave_trigger(a,b) a为选择器 #id、.class、nodeName b为事件类型(字符串)
*推荐使用方法 而不是saveBtn 和 btnTrigger
*/
(function(win){
function localSave(param){
this.param = param || {};
this.data = {};
this.wrapper =this.param.wrapper;//根据id或者class进行
this.param.wrapper = this.param.wrapper.substring(1);
this.expire = this.param.expire ? this.param.expire :null;
this.selectClass= this.param.selectClass ? this.param.selectClass :null;
this.deletBtn = this.param.deletBtn ? this.param.deletBtn : null;
this.saveBtn = this.param.saveBtn ? this.param.saveBtn :null;
this.saveData = localStorage.getItem(this.param.wrapper) ? JSON.parse(localStorage.getItem(this.param.wrapper)):null;
this.isStorage = this.param.hasOwnProperty('isStorage') ? (this.param.isStorage ? true:false) :true;
this.btnTrigger = this.param.btnTrigger ? this.param.btnTrigger :null;
this.isTypeIn = String(this.param.isTypeIn) =='false' ? false:true;
this.init();
}
localSave.prototype = {
constructor:localSave,
init :function(){
var that = this;
this.data = JSON.parse(localStorage.getItem(this.param.wrapper));
if(this.data.local_save_time > Date().now){
this.isTypeIn ? (this.saveData ? this.writeSave() : '') : "";
}
this.deletBtn ? document.querySelector(this.deletBtn).addEventListener('click',function(){
that.delete();
}) :'';
this.isonbeforeunload = String(this.param.isonbeforeunload) == 'fasle' ? false:true;
this.isonbeforeunload ?
window.onbeforeunload = function(){//默认离开页面进行存储
if(that.isStorage){
that.toSave();
}
} : '';
//var event = document.createEvent("CustomEvent");//onchange事件要用HTMLEvents
//event.initEvent(that.btnTrigger,true,true);//三个参数分别对应event的 type 属性、bubbles 属性和 cancelable 属性
try{
document.querySelector(this.saveBtn).addEventListener(that.btnTrigger,function(){
alert('cufale')
that.toSave();
},false) ;
}catch(e){
console.log(e)
}
//document.querySelector(this.saveBtn).dispatchEvent(event);//给元素分派事件
//为用户自定义事件触发的方法
localSave_trigger = function(ele, event) {
document.querySelector(ele).addEventListener(event, function() {
that.toSave();
}, false);
if (document.all) {
document.querySelector(ele).event()
} else {
var evtType = event == 'onchange' ? 'HTMLEvenets' : 'Event';
var evt = document.createEvent(evtType); //onchange需要HTMLEvenets
evt.initEvent(event, true, true);
document.querySelector(ele).dispatchEvent(evt);
}
}
},
writeSave : function(){
for (var i in this.saveData) {
var el = document.querySelector(this.wrapper).querySelector('input[name = '+i+']') || document.querySelector(this.wrapper).querySelector('select[name = '+i+']')
if(el.type && (el.type ==='radio')){
var thisRadio = document.querySelector(this.wrapper).querySelectorAll('input[name = '+i+']');
for(var j =0;j<thisRadio.length;j++){
if(thisRadio[j].value == this.saveData[i]){
thisRadio[j].checked = 'checked';
break;
}
}
}else{
el.value = this.saveData[i];
}
}
},
toSave:function (){
var data = {};
var saveList =this.selectClass ? document.querySelectorAll(this.selectClass)
: document.querySelector(this.wrapper).querySelectorAll('input');
for(var i= 0;i<saveList.length;i++){
var res = saveList[i].value.replace(/(^\s*)|(\s*$)/g, "");
if(res.length>0)
if((typeof saveList[i].type !='underfined') && saveList[i].type == 'radio' ){//若果单选的话
saveList[i].checked ? (data[saveList[i].name] = res) :'';
}else{
data[saveList[i].name] = res;
}
}
data['local_save_time'] = new Date().setDate(new Date().getDate()+this.expire);
data = JSON.stringify(data);
localStorage.setItem(this.param.wrapper,data);
// if(this.expire){
// setTimeout(function(){
// localStorage.removeItem(this.param.wrapper);
// window.location.href="http://www.video.com"
// },this.expire)
// }
return ;
},
delete: function(){
localStorage.removeItem(this.param.wrapper);
this.isStorage = false;
}
}
win.localSave = localSave;
})(window)
|
C++
|
UTF-8
| 304 | 2.6875 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
int func(int n)
{
int count = 0;
if(n && n&(n-1))
{
while(n>0)
{
n = n>>1;
count++;
}
n = 1<<count;
return n;
}
else if(n==0) return 1;
else if(!(n&(n-1))) return n;
}
int main()
{
int i,n;
cin>>n;
cout<<func(n)<<'\n';
return 0;
}
|
Java
|
UTF-8
| 605 | 3.1875 | 3 |
[] |
no_license
|
package Learn.Day216.demo03;
import java.util.Random;
import java.util.Scanner;
public class Random02 {
public static void main(String[] args) {
Random r = new Random();
System.out.println("请输入数字");
Scanner sc = new Scanner(System.in);
int x=sc.nextInt();
Boolean is=true;
int i=0;
while(is){
int num = r.nextInt(100)+1;//[1,100
System.out.println(num);
i++;
if(num==x){
is=false;
}
}
System.out.println("第"+i+"次猜出来的2");
}
}
|
Python
|
UTF-8
| 336 | 2.859375 | 3 |
[] |
no_license
|
def data_loader(data_path):
print("loading data ...")
import pandas as pd
import os
"""Just take a data path as input and render original datasets"""
load = lambda x: pd.read_csv(x,compression="zip")
data_files = os.listdir(data_path)
test, train = [load(os.path.join(data_path,i)) for i in data_files]
return test, train
|
Java
|
UTF-8
| 536 | 2.15625 | 2 |
[] |
no_license
|
package com.mac.bry.kurs1024kb.api;
import java.io.IOException;
import java.util.List;
import com.mac.bry.kurs1024kb.entity.Product;
public interface ProductService {
List<Product> getAllProducts() throws IOException;
int getNumberOfProductsOnList();
Product getProductByProductName(String productName) throws IOException;
boolean isProductCountIsGreaterThenZero();
boolean isProducWithProductNameExist(String productName) throws IOException;
boolean isProductWithProductIdExist(int productId) throws IOException;
}
|
Java
|
UTF-8
| 4,290 | 2.328125 | 2 |
[] |
no_license
|
package com.devotion.dao.route.support;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import com.devotion.dao.route.support.bean.VirtualNodeLocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import com.devotion.dao.utils.DaoUtils;
import com.devotion.dao.constants.DaoConstants;
import com.devotion.dao.route.RouteConfig;
import com.googlecode.aviator.AviatorEvaluator;
import com.devotion.dao.support.sql.FreeMakerParser;
/**
* 根据用户设定的路由规则进行数据库的路由选择,路由根据一致性hash进行选择
*/
public class ConsistentHashSharding implements RouteConfig, InitializingBean {
/**
* 日志
*/
private static Logger logger = LoggerFactory.getLogger(ConsistentHashSharding.class);
/**
* 路由规则key
*/
private String routeParam;
/**
* 虚拟节点配置Map
*/
private Map<String, DataSource> nodeMapping;
/**
* 虚拟节点定位
*/
private VirtualNodeLocator virtualNodeLocator;
/**
* 路由链
*/
private RouteConfig chainRouteConfig;
/**
* 数据源路由解析
*
* @param parameter 路由参数
* @return 解析得到的数据源
*/
@Override
public DataSource route(Object parameter) {
if (routeParam != null && parameter != null) {
/** 将得到的参数值进行转换 */
Object[] params = DaoUtils.convertToObjectArray(parameter);
for (Object param : params) {
try {
logger.debug("route parameter :" + param);
Map<String, Object> env = new HashMap<>();
env.put(DaoConstants.ROUTE, param);
/** 通过Freemarker解析器进行解析参数值 */
String expression = FreeMakerParser.process(routeParam, env);
/** 通过表达式解析出相应的值 */
expression = String.valueOf(AviatorEvaluator.execute(expression, env));
logger.debug("nodeName is {}", virtualNodeLocator.getPrimary(expression).getNodeName());
/** 根据虚拟节点的名称获得对应的数据源 */
return virtualNodeLocator.getPrimary(expression).getDataSource();
} catch (Exception e) {
logger.warn("Datasource route exception occurred :{}", e);
}
}
}
return routeChain(chainRouteConfig, parameter);
}
/**
* 功能描述: <br>
* 路由链传递
*
* @param chainRouteConfig 传递的路由
* @param parameter 路由参
* @return 路由数据源
*/
private DataSource routeChain(RouteConfig chainRouteConfig, Object parameter) {
if (chainRouteConfig != null) {
return chainRouteConfig.route(parameter);
}
return null;
}
/**
* 功能描述: <br>
* 〈功能详细描述〉 设置路由参数
*
* @param routeParam 路由参数
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
public void setRouteParam(String routeParam) {
this.routeParam = routeParam;
}
/**
* 功能描述: <br>
* 〈功能详细描述〉 设置节点匹配
*
* @param nodeMapping 节点匹配
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
public void setNodeMapping(Map<String, DataSource> nodeMapping) {
this.nodeMapping = nodeMapping;
}
/**
* 功能描述: <br>
* 〈功能详细描述〉 设置路由链配置
*
* @param chainRouteConfig 路由链配置
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
public void setChainRouteConfig(RouteConfig chainRouteConfig) {
this.chainRouteConfig = chainRouteConfig;
}
/**
* 配置bean加载时候实例化虚拟节点定位
*
* @throws Exception 异常
*/
@Override
public void afterPropertiesSet() throws Exception {
virtualNodeLocator = new VirtualNodeLocator(nodeMapping);
}
}
|
TypeScript
|
UTF-8
| 4,352 | 3.171875 | 3 |
[] |
no_license
|
import {FileWriter} from './FileWriter';
import {GqlToTSConfig, Mapper} from "./types";
import {getTypeOptions} from "./gqlNodeTools";
const path = require('path');
export class TypescriptFileWriter {
private fw: FileWriter;
private readonly fullFilePath: string;
constructor(private options: GqlToTSConfig, private typedValues: Mapper, startMessage: string) {
this.fullFilePath = path.join(options.outputFile);
this.fw = new FileWriter(this.fullFilePath);
this.fw.appendLine(startMessage);
if (options.namespace) {
this.fw.appendLine(`export namespace ${options.namespace} {`);
}
}
append(str: string) {
this.fw.appendLine(str);
return this;
}
writeDescription(indentation: string, description: string) {
if (description) {
this.append(`${indentation}/* ${description} */`);
}
}
writeEnum(name: string, enumarations: Array<string>, descriptionMap: Mapper) {
this.writeDescription(`\t`, descriptionMap[name]);
this.append(`\texport enum ${name} {`);
enumarations.forEach(e => this.append(`\t\t${e},`));
this.append('\t}');
}
private fixTyping(unknownType: string) {
return this.typedValues[unknownType] || 'any';
}
private createAdvancedInterfaceField(label: string, rawType: any) {
let advancedType = 'any';
if (rawType.kind === 'function') {
const {returnType, args} = rawType;
const printableArguments = args.map(({name, required, type}) => {
return `${name}${required ? '' : '?'}: ${this.fixTyping(type)}`;
}).join(', ');
advancedType = `(${printableArguments}) => ${this.fixTyping(returnType)}`;
} else {
// unknown field...
console.warn(`unknown field ${label}`);
}
return `\t\t${label}?: ${advancedType};`;
}
private createArrayInterfaceField(label: string, rawType: string) {
// this is in order to support 1d/2d/3d... arrays
const arraySymbols = getArraySymbols(rawType);
const childType = removeArraySymbols(rawType);
const {type, required} = getTypeOptions(childType);
return `\t\t${label}${required ? '' : '?'}: ${this.fixTyping(type)}${arraySymbols};`;
}
private createRegularInterfaceField(label: string, rawType: string) {
const {type, required} = getTypeOptions(rawType);
return `\t\t${label}${required ? '' : '?'}: ${this.fixTyping(type)};`;
}
writeInterface(name: string, data: Mapper, descriptionMap: Mapper) {
this.writeDescription(`\t`, descriptionMap[name]);
this.append(`\texport interface ${name} {`);
Object.entries(data).forEach(([label, rawType]) => {
this.writeDescription(`\t`, descriptionMap[`${name}->${label}`]);
if (typeof rawType === "string") {
if (rawType.endsWith('[]') || rawType.endsWith('[]!')) {
this.append(this.createArrayInterfaceField(label, rawType))
} else {
this.append(this.createRegularInterfaceField(label, rawType))
}
} else {
this.append(this.createAdvancedInterfaceField(label, rawType))
}
});
this.append('\t}')
}
finish(silent: boolean = false) {
const {options: {namespace}, fullFilePath} = this;
return this.fw
.appendLine('}')
.appendLine('')
.finish()
.then(() => {
if (!silent) {
console.log(`
The types file was saved!.
You can import it like so:
import { ${namespace} } from '${fullFilePath}';
`);
}
})
}
}
/**
* accept a string with an array symbols such as number[][], and returns the array symbols ('[][]')
* @param rawString
*/
function getArraySymbols(rawString: string) {
const numberOfMatches = rawString.match(/\[\]/g).length;
return '[]'.repeat(numberOfMatches);
}
/**
* Accept a string with array symbols and return the type without the array part
* @param rawString
*/
function removeArraySymbols(rawString: string) {
return rawString.replace(/\[\]/g, '')
}
|
PHP
|
UTF-8
| 411 | 2.78125 | 3 |
[] |
no_license
|
<?php
namespace App\Exceptions;
class ViewNotFoundException extends FileNotFoundException
{
/**
* Constructor call FileNotFoundException by code
*
* @param string $message
* @param integer $code
* @param Exception $previous
*/
public function __construct($class, $code = 0, $previous = null)
{
parent::__construct($class, 'view', $code, $previous);
}
}
|
Python
|
UTF-8
| 3,192 | 3.21875 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 6 09:56:56 2020
@author: Ali Barkın Kara
"""
#Ödev1
#from datetime import datetime, date
#print("tarih giriniz")
#gun=int(input("tarih gün degeri: "))
#ay=int(input("tarih ay degeri: "))
#yıl=int(input("tarih yıl degeri: "))
#tarih2 = date(day = gun, month = ay, year = yıl)
#print("1.tarih : ",tarih2)
#Ödev2
#def durum1(x):
#fact=1;
#for i in range (1,(3*x)+1):
#fact = fact * i
#return fact
#def durum2(x):
#out=0
#for i in range (1,x+1):
#out = out + (2*i)
#return out
#x = int(input("x değerini giriniz "))
#if (x>=0 and x<9):
#print(durum1(x))
#elif (x>=9 and x<16):
#print(durum2(x))
#else:
#print("Geçersiz girdi")
#Ödev3
#import string
#import numpy as np
#import math
#from sympy import Matrix #inverse key
#def letterToNumber(letter):
#return string.ascii_lowercase.index(letter)
#def numberToLetter(number):
#return chr(int(number) + 97)
#module = 26
#raw_message = "alk"
#raw_message = "ali karaba"
#print("raw message: ",raw_message)
#message = []
#key = np.array([
#[1, 2, -1],
#[2, 5, 2],
#[-1, -2, 2]
#])
#key_rows = key.shape[0]
#key_columns = key.shape[1]
#if key_rows != key_columns:
#raise Exception('anahtar kare matris olmalıdır')
#for i in range(0, len(raw_message)):
#current_letter = raw_message[i:i+1].lower()
#if current_letter != ' ':
#letter_index = letterToNumber(current_letter)
#message.append(letter_index)
#if len(message) % key_rows != 0:
#for i in range(0, len(message)):
#message.append(message[i])
#if len(message) % key_rows == 0:
#break
#message = np.array(message)
#message_length = message.shape[0]
#print("message: ",message)
#message.resize(int(message_length/key_rows), key_rows)
#encryption = np.matmul(message, key)
#encryption = np.remainder(encryption, module)
#print("şifreli metin: \n",encryption)
#print("ters anahtarı bulma")
#inverse_key = Matrix(key).inv_mod(module)
#inverse_key = np.array(inverse_key)
#inverse_key = inverse_key.astype(float)
#print("ters anahtarı bulma: ",inverse_key)
#print("ters anahtarı doğrulama. ")
#check = np.matmul(key, inverse_key)
#check = np.remainder(check, module)
#print("key times inverse key: ",check)
#print("bu matris ",np.allclose(check, np.eye(3)))
#print("şifre çözme:")
#decryption = np.matmul(encryption, inverse_key)
#decryption = np.remainder(decryption, module).flatten()
#print("şifre çözme ",decryption)
#decrypted_message = ""
#for i in range(0, len(decryption)):
#letter_num = int(decryption[i])
#letter = numberToLetter(decryption[i])
#decrypted_message = decrypted_message + letter
#print("şifresi çözülmüş mesaj: ",decrypted_message)
#ödev4
#print(1,"ile",51,"arasındaki asal sayılar:")
#for sayi in range(1,51 + 1):
#if sayi > 1:
#for i in range(2,sayi):
#if (sayi % i) == 0:
#break
#else:
#print(sayi)
|
C
|
UTF-8
| 1,056 | 3.65625 | 4 |
[] |
no_license
|
/**
* CS 2261 - Linked List Lab
*
* list.h
**/
#ifndef LIST_H
#define LIST_H
/* The node struct. Has a prev pointer, next pointer, and data. */
typedef struct lnode
{
struct lnode* prev; /* Pointer to previous node */
struct lnode* next; /* Pointer to next node */
int data; /* User data */
} node;
/* The linked list struct. Has a head pointer. */
typedef struct llist
{
struct lnode* head; /* Head pointer either points to a node with data or NULL */
struct lnode* tail;
} list;
/* A function pointer type that points to a function that takes in a void* and an int */
typedef int (*list_operation)(int x);
/* Prototypes */
/* Creating */
static node* create_node(int data);
list* create_list(void);
/* Adding */
void push_front(list* llist, int data);
void push_back(list* llist, int data);
/* Removing */
int pop_front(list* llist);
int pop_back(list* llist);
/* Querying List */
int size(list* llist);
/* Freeing */
void empty_list(list* llist);
/* Traversal */
void traverse(list* llist, list_operation do_func);
#endif
|
Go
|
UTF-8
| 590 | 3.125 | 3 |
[] |
no_license
|
package main
import (
"fmt"
"log"
"time"
"github.com/zabawaba99/firego"
)
type chat struct {
Message string
Name string
}
func main() {
// create a reference to data in Firebase and authorize it with a JWT token
f := firego.New("https://radiant-heat-5110.firebaseio.com/chat", nil)
f.Unauth()
tick := time.Tick(5 * time.Second)
for now := range tick {
// update Firebase with new data
newData := &chat{
Name: "Guus",
Message: fmt.Sprintf("Hello from Golang! It's now: %+v", now),
}
if _, err := f.Push(newData); err != nil {
log.Fatal(err)
}
}
}
|
PHP
|
UTF-8
| 248 | 2.625 | 3 |
[] |
no_license
|
<?php
namespace App\Infrastructure\Interfaces;
interface IResource
{
public function setOpenedResource($resource);
public function getOpenedResource();
public function getFirstLine();
public function loopByLine(): \Generator;
}
|
C++
|
UTF-8
| 340 | 3.40625 | 3 |
[] |
no_license
|
// two pointer approach one fast pointer and one slow pointer
class Solution {
public:
bool hasCycle(ListNode *head) {
if (!head)
return false;
ListNode* slow = head;
ListNode* fast = head->next;
while (fast && fast->next) {
if (slow == fast)
return true;
slow = slow->next;
fast = fast->next->next;
}
return false;
}
};
|
Python
|
UTF-8
| 1,081 | 3.6875 | 4 |
[] |
no_license
|
#!usr/bin/python
import cmath
from math import *
#Objetivo: devuelve en un arhivo una lista de puntos para graficar con gnuplot.
#ecuacion: Z = az + bz/ |z|
#donde a= exp(pi*i/4) = (1/sqr(2)(1 + i) y b = Conjugado(a)
def Z( z_before, def_of_a, def_of_b):
a = def_of_a
b = def_of_b
z = z_before
abs_of_z = abs(z_before)
z = a*z + b*z/abs_of_z
return z
def marigold_spiral():
exp_of_pi = cmath.exp(cmath.pi * 1j)
#another form: (1/sqr(2) ) ( 1 + 1*j)
first_term = (1.0/ sqrt(2) ) * (1 + 1j)
# first_term = exp_of_pi / 4.0
conjugate_of_first = first_term.conjugate()
second_term = conjugate_of_first
point_of_z= 1 + 0j
list_of_points = []
for iterator in range(1,1000,1):
list_of_points.append(point_of_z)
point_of_z = Z(point_of_z, first_term, second_term)
return list_of_points
list_of_points = marigold_spiral()
print list_of_points
#save to file
output_file = open('pointsOfMarigoldSpiral.txt','w')
for point in list_of_points:
output_file.write("%s %s\n" % (point.real, point.imag))
|
Java
|
UTF-8
| 2,684 | 2.28125 | 2 |
[] |
no_license
|
package com.concrete.poletime.db;
import com.concrete.poletime.seasonticket.SeasonTicket;
import com.concrete.poletime.user.PoleUser;
import com.concrete.poletime.user.PoleUserRepository;
import com.concrete.poletime.utils.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.Set;
@Service
public class DbInit implements CommandLineRunner {
private PoleUserRepository poleUserRepo;
private PasswordEncoder passwordEncoder;
@Autowired
public DbInit(PoleUserRepository poleUserRepo, PasswordEncoder passwordEncoder) {
this.poleUserRepo = poleUserRepo;
this.passwordEncoder = passwordEncoder;
}
@Override
public void run(String... args) throws Exception {
PoleUser admin = new PoleUser(
"admin@concrete.hu",
"admin",
"admin",
passwordEncoder.encode("aA@123456"));
admin.setEnabled(true);
admin.setRole(Role.ADMIN);
poleUserRepo.save(admin);
PoleUser trainer = new PoleUser(
"trainer@concrete.hu",
"trainer",
"trainer",
passwordEncoder.encode("aA@123456"));
trainer.setEnabled(true);
trainer.setRole(Role.TRAINER);
poleUserRepo.save(trainer);
for (int i = 0; i < 20; i++) {
PoleUser guest = new PoleUser(
"pole_user" + (i + 1) + "@concrete.hu",
"firstName" + (i + 1),
"lastName" + (i + 1),
passwordEncoder.encode("aA@123456"));
guest.setEnabled(true);
SeasonTicket seasonTicket = new SeasonTicket();
seasonTicket.setAmount(20);
seasonTicket.setUsed(0);
seasonTicket.setSellerId(admin.getId());
seasonTicket.setValidFrom(LocalDate.now());
seasonTicket.setValidTo(seasonTicket.getValidFrom().plusDays(30));
Set<SeasonTicket> seasonTickets = guest.getSeasonTickets();
seasonTickets.add(seasonTicket);
guest.setSeasonTickets(seasonTickets);
seasonTicket.setPoleUser(guest);
poleUserRepo.save(guest);
}
PoleUser guest = new PoleUser(
"pole_user" + 21 + "@concrete.hu",
"firstName" + 21,
"lastName" + 21,
passwordEncoder.encode("aA@123456"));
guest.setEnabled(true);
poleUserRepo.save(guest);
}
}
|
Java
|
UTF-8
| 797 | 2.09375 | 2 |
[] |
no_license
|
/*
* Created on June 29, 2006
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and
Comments
*/
package com.bituos.lca.Beans;
/**
* @author cirm
*/
public class BeanDoctorRepresentative{
private int id;
private BeanDoctor id_doctor;
private BeanRepresentative id_representative;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public BeanDoctor getId_doctor() {
return id_doctor;
}
public void setId_doctor(BeanDoctor id_doctor) {
this.id_doctor = id_doctor;
}
public BeanRepresentative getId_representative() {
return id_representative;
}
public void setId_representative(BeanRepresentative id_representative) {
this.id_representative = id_representative;
}
}
|
JavaScript
|
UTF-8
| 427 | 2.828125 | 3 |
[] |
no_license
|
// 1. Create .on("click", function() {} ) handlers for each of the thumbnails: #first, #second, #third, #fourth
// 2. Use .attr() to change the `src` attribute of #bigimage to correspond to image that was clicked
$('.thumbnails .zoom').click(function(e){
e.preventDefault();
var photo_fullsize = $(this).find('img').attr('src');
$('.woocommerce-main-image img').attr('src', photo_fullsize);
});
|
C
|
UTF-8
| 270 | 3.078125 | 3 |
[] |
no_license
|
#include<stdio.h>
int main() {
int vetorX[10];
int k=0;
for (k=0;k<10;k++){
scanf("%d",&vetorX[k]);
if(vetorX[k] <= 0){
vetorX[k] = 1;
}
printf("X[%d] = %d\n",k,vetorX[k]);
}
return 0;
}
|
Java
|
UTF-8
| 3,795 | 3.28125 | 3 |
[] |
no_license
|
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.*;
import java.io.*;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
public class Palindromic
{
public boolean isPalindromic(String str)
{
boolean tem=false;
for(int i=0,j=str.length()-1;i<str.length()/2;i++,j--)
{
if(str.charAt(i)!=str.charAt(j))
{
tem=false;
break;
}
else if(str.charAt(i)==str.charAt(j))
{
tem=true;
}
}
return tem;
}
private void writeUsingBufferedWriter(TreeSet data,int len) {
String fileName = "out.txt";
try {
// Open given file in append mode.
BufferedWriter out = new BufferedWriter(
new FileWriter(fileName, true));
out.newLine();
out.write("Length "+len+": [");
Iterator<String> itr = data.iterator();
while(itr.hasNext()){
String str=itr.next();
out.write(str);
out.append(",");
out.flush();
}
out.write("]");
out.close();
}
catch (IOException e) {
System.out.println("exception occoured" + e);
}
}
synchronized public void genPl(String str,int len)
{
TreeSet<String> obj=new TreeSet<String>();
int sze=len,k=len;
for(int i=0;i<str.length()-sze;i++)
{
boolean check=isPalindromic(str.substring(i,k));
if(check==true)
{
obj.add(str.substring(i,k));
}
k++;
}
Palindromic p=new Palindromic();
p.writeUsingBufferedWriter(obj,len);
obj.clear();
}
public static void main(String []args)
{
try {
BufferedReader in = new BufferedReader( new FileReader("test.txt"));
String str=in.readLine();
Palindromic pn=new Palindromic();
//Create Fixed 5 thread Which When finshed his tak Get New Auto task by usinng Thread pooling
ExecutorService executor=Executors.newFixedThreadPool(5);
for(int i=2;i<10;i++)
{
Runnable worker=new MyThread(pn, i,str);
executor.execute(worker);
}
executor.shutdown();
/* while(executor.isTerminated())
System.out.println("FNished All Thread" ); */
}catch (IOException e) {
System.out.println("Exception Occurred" + e);
}
}
}
class MyThread extends Thread {
Palindromic pn;
int len;
String str;
MyThread(Palindromic pn,int len,String str)
{
this.pn=pn;
this.len=len;
this.str=str;
}
public void run() {
System.out.println(Thread.currentThread().getName()+" Start");
pn.genPl(str, len);
try{
Thread.sleep(500);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" End");
}
}
|
SQL
|
UTF-8
| 170 | 3.828125 | 4 |
[] |
no_license
|
SELECT
a.score AS Score, COUNT(DISTINCT b.score) AS Rank
FROM
scores a
JOIN
scores b
WHERE
b.score >= a.score
GROUP BY a.id
ORDER BY a.score DESC
|
C#
|
UTF-8
| 1,997 | 2.71875 | 3 |
[] |
no_license
|
using Microsoft.Extensions.Configuration;
using System.Collections.Concurrent;
using System.Reflection;
namespace BeckmanCoulter.BookStore.Extensions
{
/// <summary>
/// Cache Configurations for <see cref="IConfigurationRoot"/>.
/// </summary>
public static class AppConfiguration
{
private static readonly ConcurrentDictionary<string, IConfigurationRoot> s_configurationCache;
static AppConfiguration()
{
s_configurationCache = new ConcurrentDictionary<string, IConfigurationRoot>();
}
/// <summary>
/// Get configuration.
/// </summary>
/// <param name="path">Configuration file path</param>
/// <param name="environmentName">Hosting environment name.</param>
/// <param name="addUserSecrets">Adds the user secrets configuration source.</param>
/// <returns></returns>
public static IConfigurationRoot Get(string path, string environmentName = null, bool addUserSecrets = false)
{
var cacheKey = $"{path}#{environmentName}#{addUserSecrets}";
return s_configurationCache.GetOrAdd(
cacheKey,
_ => BuildConfiguration(path, environmentName, addUserSecrets)
);
}
private static IConfigurationRoot BuildConfiguration(string path, string environmentName = null, bool addUserSecrets = false)
{
var builder = new ConfigurationBuilder()
.SetBasePath(path)
.AddJsonFile("appsettings.json", true, true);
if (!string.IsNullOrWhiteSpace(environmentName))
{
builder = builder.AddJsonFile($"appsettings.{environmentName}.json", true);
}
builder = builder.AddEnvironmentVariables();
if (addUserSecrets)
{
builder.AddUserSecrets(Assembly.GetEntryAssembly());
}
return builder.Build();
}
}
}
|
C++
|
UTF-8
| 2,549 | 3.984375 | 4 |
[] |
no_license
|
#include <climits>
#include <iostream>
// Brute force approach- Recursive
int minStepTo1_bf(int n) {
// base case
if (n == 1)
return 0;
int x = minStepTo1_bf(n - 1);
int y = INT_MAX;
if (n % 2 == 0)
y = minStepTo1_bf(n / 2);
int z = INT_MAX;
if (n % 3 == 0)
z = minStepTo1_bf(n / 3);
return std::min(x, std::min(y, z)) + 1;
}
// Memoization
int minStepTo1_mem_helper(int *arr, int n) {
// base case
if (n == 1)
return 0;
// small calculation and recursive call
if (arr[n] != -1)
return arr[n];
int x = minStepTo1_mem_helper(arr, n - 1);
int y = INT_MAX;
if (n % 2 == 0)
y = minStepTo1_mem_helper(arr, n / 2);
int z = INT_MAX;
if (n % 3 == 0)
z = minStepTo1_mem_helper(arr, n / 3);
// storing value
arr[n] = std::min(x, std::min(y, z)) + 1;
return arr[n];
}
int minStepTo1_mem(int n) {
int arr[n + 1];
for (int i = 0; i < n + 1; i++) {
arr[i] = -1;
}
return minStepTo1_mem_helper(arr, n);
}
// DP
int minStepTo1_dp(int n) {
// storage
int arr[n + 1];
arr[0] = 0;
arr[1] = 0;
// filling up and acessing filled
for (int i = 2; i < n + 1; i++) {
int x = arr[i - 1];
int y = INT_MAX;
if (i % 2 == 0)
y = arr[i / 2];
int z = INT_MAX;
if (i % 3 == 0)
z = arr[i / 3];
arr[i] = std::min(x, std::min(y, z)) + 1;
}
// once done time to return
return arr[n];
}
int main(void) {
int n;
std::cin >> n;
std::cout << minStepTo1_bf(n) << std::endl;
std::cout << minStepTo1_mem(n) << std::endl;
std::cout << minStepTo1_dp(n) << std::endl;
return 0;
}
/*
Coding Problem
Problem Statement: Min Steps to one using DP
Problem Level: EASY
Problem Description:
Given a positive integer 'n', find and return the minimum number of steps that
'n' has to take to get reduced to 1. You can perform any one of the following 3
steps: 1.) Subtract 1 from it. (n = n - 1) , 2.) If n is divisible by 2, divide
by 2.( if n % 2 == 0, then n = n / 2 ) , 3.) If n is divisible by 3, divide
by 3. (if n % 3 == 0, then n = n / 3 ).
Input format :
The first and the only line of input contains an integer value, 'n'.
Output format :
Print the minimum number of steps.
Constraints :
1 <= n <= 10 ^ 6
Time Limit: 1 sec
Sample Input 1 :
4
Sample Output 1 :
2
Explanation of Sample Output 1 :
For n = 4
Step 1 : n = 4 / 2 = 2
Step 2 : n = 2 / 2 = 1
Sample Input 2 :
7
Sample Output 2 :
3
Explanation of Sample Output 2 :
For n = 7
Step 1 : n = 7 - 1 = 6
Step 2 : n = 6 / 3 = 2
Step 3 : n = 2 / 2 = 1
*/
|
Java
|
UTF-8
| 187 | 1.53125 | 2 |
[] |
no_license
|
package timaxa007.rotating_block.r4upside;
import net.minecraft.tileentity.TileEntity;
public class TileEntityRotatingObj extends TileEntity {
public TileEntityRotatingObj() {
}
}
|
Java
|
UTF-8
| 10,869 | 2.125 | 2 |
[] |
no_license
|
package com.ssm.dao;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.session.SqlSession;
import com.ssm.dao.provider.DeptDynaSqlProvider;
import com.ssm.mapper.DeptMapper;
import com.ssm.mapper.MoneyMapper;
import com.ssm.mapper.UserMapper;
import com.ssm.pojo.AccountDetail;
import com.ssm.pojo.Dept;
import com.ssm.pojo.User;
import com.ssm.utils.ArithUtil;
import com.ssm.utils.Constants;
import com.ssm.utils.PageModel;
import com.ssm.utils.Pager;
import com.ssm.utils.SqlSessionFactoryUtils;
public class MoneyDao {
SqlSession sqlSession = SqlSessionFactoryUtils.openSqlSession();
//创建能执行映射文件中sql的sqlSession
MoneyMapper moneyMapper = sqlSession.getMapper(MoneyMapper.class);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
public Pager findByPage(AccountDetail ad,String type,Pager pager){
Map<String,Object> params = new HashMap<>();
try {
params.put("account",ad);
if(type.equals("1")){
params.put("tableName", "rmoney_detail");
}else if(type.equals("2")){
params.put("tableName", "cash_num_detail");
}else if(type.equals("3")){
params.put("tableName", "cash_detail");
}else if(type.equals("4")){
params.put("tableName", "integral_detail");
}
if(!type.equals("")) {
int recordCount = moneyMapper.count(params);
double[] sum ={0,0};
Double s1 = moneyMapper.sum1(params);
Double s2 = moneyMapper.sum2(params);
if(s1!=null) sum[0]= s1;
if(s2!=null) sum[1]= s2;
pager.setSum(sum);
pager.setRowCount(recordCount);
if(recordCount>0){
params.put("pageModel", pager);
}
List<AccountDetail> ads = moneyMapper.selectByPage(params);
pager.setResultList(ads);
}
sqlSession.commit();
}catch(Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
return pager;
}
public List<AccountDetail> findAllByList(AccountDetail ad,String type){
Map<String,Object> params = new HashMap<>();
List<AccountDetail> result = new ArrayList<AccountDetail>();
try {
params.put("account",ad);
if(type.equals("1")){
params.put("tableName", "rmoney_detail");
}else if(type.equals("2")){
params.put("tableName", "cash_detail");
}else if(type.equals("3")){
params.put("tableName", "cash_num_detail");
}else if(type.equals("4")){
params.put("tableName", "integral_detail");
}
result = moneyMapper.selectAll(params);
sqlSession.commit();
}catch(Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
return result;
}
public List<AccountDetail> findByUserId(String tableName,String userId){
List<AccountDetail> alist = new ArrayList<AccountDetail>();
try {
String sql = "select * from "+tableName+" where user_id='"+userId+"' order by entry_time asc";
alist = moneyMapper.selectByList(sql);
sqlSession.commit();
}catch(Exception e){
e.printStackTrace();
sqlSession.rollback();
}finally {
sqlSession.close();
}
return alist;
}
public String saveMoney(AccountDetail ad,String type){
String str = "";
try {
Map<String,Object> params = new HashMap<>();
if(type.equals("1")){
params.put("tableName", "rmoney_detail");
}else if(type.equals("2")){
params.put("tableName", "cash_detail");
}else if(type.equals("3")){
params.put("tableName", "cash_num_detail");
}else if(type.equals("4")){
params.put("tableName", "integral_detail");
}
if(!type.equals("")){
params.put("account",ad);
moneyMapper.save(params);
sqlSession.commit();
str =ad.getUserId()+"账户明细保存成功。";
}else{
str ="该账户已经存在。";
}
}finally {
sqlSession.close();
}
return str;
}
public User findAllMoney(){
User ad = null;
try {
ad = moneyMapper.selectAllMoney();
}finally {
sqlSession.close();
}
return ad;
}
public int updateForSql(String sql){
int value =0;
try {
Integer update = moneyMapper.updateForSql(sql);
if(update!=null&&update>0){
value= update;
sqlSession.commit();
}
}finally {
sqlSession.close();
}
return value;
}
public String updateMoney(AccountDetail ad,String type){
String str = "";
try {
if(!type.equals("")){
Map<String,Object> params = new HashMap<>();
if(type.equals("1")){
params.put("tableName", "rmoney_detail");
}else if(type.equals("2")){
params.put("tableName", "cash_detail");
}else if(type.equals("3")){
params.put("tableName", "cash_num_detail");
}else if(type.equals("4")){
params.put("tableName", "integral_detail");
}
params.put("account",ad);
moneyMapper.update(params);
sqlSession.commit();
str =ad.getUserId()+"账户明细修改成功。";
}else{
str ="该账户已经存在。";
}
}finally {
str="系统繁忙。";
sqlSession.close();
}
return str;
}
public String saveEMoneyTransfer(String userId1,String userId2,double amount,Timestamp date){
String str = "";
try {
User user1 = userMapper.selectByUserIdForUpdate(userId1);
User user2 = userMapper.selectByUserIdForUpdate(userId2);
if(user1!=null){
if(user2!=null){
if(ArithUtil.sub(user1.getEmoney(), amount)>=0){
AccountDetail ad = new AccountDetail();
AccountDetail ad1 = new AccountDetail();
ad.setId(user1.getId());
ad.setUserId(user1.getUserId());
ad.setUserName(user1.getUserName());
ad.setAmount(amount);
ad.setBalance(ArithUtil.sub(user1.getEmoney(), amount));
ad.setTradeType("电子币互转");
ad.setSummary("转给"+userId2);
ad.setPayType(2);
ad.setEntryTime(date);
ad1.setId(user2.getId());
ad1.setUserId(user2.getUserId());
ad1.setUserName(user2.getUserName());
ad1.setAmount(amount);
ad1.setBalance(ArithUtil.add(user2.getEmoney(), amount));
ad1.setTradeType("电子币互转");
ad1.setSummary(userId1+"转入");
ad1.setPayType(1);
ad1.setEntryTime(date);
User up_user_1 = new User();
User up_user_2 = new User();
up_user_1.setId(user1.getId());
up_user_1.setEmoney(ArithUtil.sub(user1.getEmoney(), amount));
up_user_2.setId(user2.getId());
up_user_2.setEmoney(ArithUtil.add(user2.getEmoney(), amount));
Map<String,Object> params = new HashMap<>();
params.put("account",ad);
params.put("tableName", "emoneyDetail");
if(moneyMapper.save(params)>0){
params.put("account",ad1);
params.put("tableName", "emoneyDetail");
if(moneyMapper.save(params)>0){
if(userMapper.updateUser(up_user_1)>0){
if(userMapper.updateUser(up_user_2)>0){
str = "yes";
sqlSession.commit();
}else{
str = "收款人账户余额更新失败。";
sqlSession.rollback();
}
}else{
str = "转账人账户余额更新失败。";
sqlSession.rollback();
}
}else{
str = "收款人账户明细更新失败。";
sqlSession.rollback();
}
}else{
str = "转账人账户明细更新失败。";
sqlSession.rollback();
}
}else{
str = "报单券账户余额不足。";
sqlSession.rollback();
}
}else{
str="收款人信息获取失败。";
sqlSession.rollback();
}
}else{
str="转账人信息获取失败。";
sqlSession.rollback();
}
}catch(Exception e){
str="数据操作有误。";
e.printStackTrace();
sqlSession.rollback();
}finally {
sqlSession.close();
}
return str;
}
public String saveToEmoney(String userId1,double amount,Timestamp date){
String str = "";
try {
User user1 = userMapper.selectByUserIdForUpdate(userId1);
if(user1!=null){
if(ArithUtil.sub(user1.getRmoney(), amount)>=0){
AccountDetail ad = new AccountDetail();
AccountDetail ad1 = new AccountDetail();
ad.setId(user1.getId());
ad.setUserId(user1.getUserId());
ad.setUserName(user1.getUserName());
ad.setAmount(amount);
ad.setBalance(ArithUtil.sub(user1.getRmoney(), amount));
ad.setTradeType("奖金转报单");
ad.setSummary("转为报单券");
ad.setPayType(2);
ad.setEntryTime(date);
ad1.setId(user1.getId());
ad1.setUserId(user1.getUserId());
ad1.setUserName(user1.getUserName());
ad1.setAmount(amount);
ad1.setBalance(ArithUtil.add(user1.getEmoney(), amount));
ad1.setTradeType("奖金转报单");
ad1.setSummary("奖金券转入");
ad1.setPayType(1);
ad1.setEntryTime(date);
User up_user_1 = new User();
up_user_1.setId(user1.getId());
up_user_1.setRmoney(ArithUtil.sub(user1.getRmoney(), amount));
up_user_1.setEmoney(ArithUtil.add(user1.getEmoney(), amount));
Map<String,Object> params = new HashMap<>();
params.put("account",ad);
params.put("tableName", "rmoneyDetail");
if(moneyMapper.save(params)>0){
params.put("account",ad1);
params.put("tableName", "emoneyDetail");
if(moneyMapper.save(params)>0){
if(userMapper.updateUser(up_user_1)>0){
str = "yes";
sqlSession.commit();
}else{
str = "会员账户余额更新失败。";
sqlSession.rollback();
}
}else{
str = "报单券账户明细更新失败。";
sqlSession.rollback();
}
}else{
str = "奖金券账户明细更新失败。";
sqlSession.rollback();
}
}else{
str = "奖金券券账户余额不足。";
sqlSession.rollback();
}
}else{
str="会员信息获取失败。";
sqlSession.rollback();
}
}catch(Exception e){
str="数据操作有误。";
e.printStackTrace();
sqlSession.rollback();
}finally {
sqlSession.close();
}
return str;
}
}
|
Swift
|
UTF-8
| 1,445 | 3.53125 | 4 |
[] |
no_license
|
//: [Previous](@previous)
import UIKit
@testable import Constraints
// Example code
let painting = UILabel(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
var n = 0
(() |-* 5).produceConstraints(view_index: &n).formatString
(() |-* 1.23).produceConstraints(view_index: &n).formatString
(() |-* painting).produceConstraints(view_index: &n).formatString
(() |-* ==5).produceConstraints(view_index: &n).formatString
(() |-* >=5.with(priority: 999)).produceConstraints(view_index: &n).formatString
(5 *-| ()).produceConstraints(view_index: &n).formatString
(1.23 *-| ()).produceConstraints(view_index: &n).formatString
(painting *-| ()).produceConstraints(view_index: &n).formatString
(==5 *-| ()).produceConstraints(view_index: &n).formatString
(>=5.with(priority: 999) *-| ()).produceConstraints(view_index: &n).formatString
(() |-* painting *-| ()).produceConstraints(view_index: &n).formatString
(() |-* painting *-* 9 *-| ()).produceConstraints(view_index: &n).formatString
(() |-* 9 *-* painting *-| ()).produceConstraints(view_index: &n).formatString
(() |-* painting *-* >=9 *-| ()).produceConstraints(view_index: &n).formatString
(() |-* >=9 *-* painting *-| ()).produceConstraints(view_index: &n).formatString
(() |-* painting *-* >=9.with(priority: 999) *-| ()).produceConstraints(view_index: &n).formatString
(() |-* >=9.with(priority: 5) *-* painting *-| ()).produceConstraints(view_index: &n).formatString
//: [Next](@next)
|
C#
|
UTF-8
| 672 | 2.515625 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class platformMover : MonoBehaviour {
Vector3 startPos;
public Transform endPosition;
public float speed;
Vector3 targetPos;
void Start () {
startPos = transform.position;
targetPos = endPosition.position;
}
// Update is called once per frame
void Update () {
transform.position = Vector3.MoveTowards (transform.position, targetPos, Time.deltaTime * speed);
if(Vector3.Distance(transform.position, targetPos) < 0.2f){
if (targetPos == endPosition.position) {
targetPos = startPos;
} else {
targetPos = endPosition.position;
}
}
}
}
|
JavaScript
|
UTF-8
| 1,593 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
import generateUID from "@akwaba/object-extensions/src/generate-uuid";
const model = {};
/**
* Retrieves the storage entry for the given element. The element's "_storageId" property is used as the
* key for its entries
*
* @param {Node} element the element for which to retrieve the storage
* @return {Object} the storage entry for the given element
*/
const getStorage = (element) => {
const id = element._storageId || (element._storageId = generateUID());
return model[id] || (model[id] = { }); /* eslint-disable-line no-return-assign */
};
/**
* Stores a key/value pair of content for the given element. If the value parameter is an object, stores
* each property of the object with its specific value
*
* @param {Node} element the element for which to store the properties
* @param {Array} rest the argument list that contains the key and value to store
*/
const store = (element, ...rest) => {
if (rest.length === 1) {
Object.assign(getStorage(element), rest[0]);
} else {
getStorage(element)[rest[0]] = rest[1]; /* eslint-disable-line prefer-destructuring */
}
};
/**
* Retrieves the value of the key specified in this element's storage unit
*
* @param {Node} element the element for which to retrieve the storage value
* @param {String} key the key for which to return the value
* @return {String|Object} the value for the specified key in this element's storage unit
*/
const retrieve = (element, key) => getStorage(element)[key];
export default {
getStorage,
store,
retrieve
};
|
JavaScript
|
UTF-8
| 548 | 3.671875 | 4 |
[] |
no_license
|
// 기본 매개변수 (객체)
const defaultHuman = {
name : {
last : "조",
first : "구함"
},
sports: "유도",
ranking : 2
}
function olympicSports(human = defaultHuman){
console.log(`${human.name.last}${human.name.first}은 ${human.sports} 선수입니다`)
console.log(`${human.sports}에서 ${human.ranking}등 했습니다`)
}
olympicSports({
name : {
last : "김",
first : "연경"
},
sports: "배구",
ranking : 4
})
olympicSports()
// olympicSports(77) // error
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.