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
|
---|---|---|---|---|---|---|---|
C#
|
UTF-8
| 847 | 3.140625 | 3 |
[] |
no_license
|
using System;
using System.IO;
namespace MultiFunctionalBot.Commands
{
class BroadcastCommand : ICommandHandler
{
public int Args
{
get
{
return 2;
}
}
public string GetDescription()
{
return "Boradcast message on all run bots;";
}
public void handle(string[] args)
{
string type = args[0];
string msg = "";
if (type == "raw")
msg = args[1];
else if (type == "file" && File.Exists("Files\\" + args[1]))
{
msg = File.ReadAllText("Files\\" + args[1]);
}
foreach (Bot bot in Program.Bots)
{
bot.SendMessage(bot.FormatMessage(msg));
}
}
}
}
|
Python
|
UTF-8
| 817 | 4.125 | 4 |
[] |
no_license
|
''' Program has function which takes two arguments :
1) initial balanace and 2) No. of operations that you want to perform. which are deposit or withdraw
This function adds the deposit amount to balance and deducts the withdrawal amount from balance
'''
def main(bal,itr):
for i in range(itr):
j = list(map(int,list(input("Enter the operation and amount (1 for deposit and 2 for withdrawal) : ").split())))
if j[0]==1:
bal = bal + j[1]
elif j[0] == 2:
if bal >= j[1]:
bal = bal - j[1]
else:
print("Insufficient funds")
print("Balance = ",bal)
if __name__ == '__main__':
bal=int(input("Enter the initial balance : "))
itr=int(input("Enter the no. of operations you want to perform"))
main(bal,itr)
|
C#
|
UTF-8
| 2,337 | 2.828125 | 3 |
[] |
no_license
|
namespace Application.Activities
{
using Application.DTO;
using Application.Errors;
using AutoMapper;
using Domain;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Persistence;
using System;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Defines the <see cref="Details" />
/// </summary>
public class Details
{
/// <summary>
/// Defines the <see cref="Query" />
/// </summary>
public class Query : IRequest<ActivityDto>
{
/// <summary>
/// Gets or sets the Id
/// </summary>
public Guid Id { get; set; }
}
/// <summary>
/// Defines the <see cref="Handler" />
/// </summary>
public class Handler : IRequestHandler<Query, ActivityDto>
{
/// <summary>
/// Defines the _context
/// </summary>
private readonly DataContext _context;
private readonly IMapper _mapper;
/// <summary>
/// Initializes a new instance of the <see cref="Handler"/> class.
/// </summary>
/// <param name="context">The context<see cref="DataContext"/></param>
public Handler(DataContext context,IMapper mapper)
{
_context = context;
_mapper = mapper;
}
/// <summary>
/// The Handle
/// </summary>
/// <param name="request">The request<see cref="Query"/></param>
/// <param name="cancellationToken">The cancellationToken<see cref="CancellationToken"/></param>
/// <returns>The <see cref="Task{Activity}"/></returns>
public async Task<ActivityDto> Handle(Query request, CancellationToken cancellationToken)
{
var activity = await _context.Activities.FindAsync(request.Id);
if (activity == null)
{
throw new RestException(System.Net.HttpStatusCode.NotFound, new { activity = "Not found" });
}
var activityReturns = _mapper.Map<Activity, ActivityDto>(activity);
return activityReturns;
}
}
}
}
|
PHP
|
UTF-8
| 161 | 2.671875 | 3 |
[] |
no_license
|
<?php
class Game extends Product
{
private $games=[];
public function addGames($games)
{
$this->games[] = $games;
}
}
|
C#
|
UTF-8
| 1,196 | 2.75 | 3 |
[] |
no_license
|
using UnityEngine;
public class LightController : MonoBehaviour
{
private Light theLight;
public float maxInstensity;
public float minInstensity;
public Color dayTimeColor;
public Color nightTimeColor;
public float speed;
private void Start()
{
theLight = gameObject.GetComponent<Light>();
}
private float trigonometric(float min, float max,float angle)
{
float rad = angle * Mathf.Deg2Rad;
float A = (max - min) / 2.0f;
float fai = min + A;
return A * Mathf.Cos(rad) + fai;
}
public void setTimeByAngle(float angle)
{
theLight.intensity = trigonometric(minInstensity,maxInstensity,angle);
if(100<angle && angle<200)
theLight.color = nightTimeColor;
else
theLight.color = dayTimeColor;
}
public void setTime(bool isDayTime)
{
if (isDayTime)
{
theLight.intensity = maxInstensity;
theLight.color = dayTimeColor;
}
else
{
theLight.intensity = minInstensity;
theLight.color = nightTimeColor;
}
}
}
|
Markdown
|
UTF-8
| 3,863 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
# data-frisk-reagent
> "Get your facts first, then you can distort them as you please" - Mark Twain
Visualize your data in your Reagent apps as a tree structure.
Suitable for use during development.
<img src="data-frisk.gif">
## Install

Add `data-frisk-reagent` to the dev `:dependencies` in your `project.clj`
## Usage
This library's public API consists of two public functions/reagent-components: `datafrisk.core/DataFriskShell` and `datafrisk.core/FriskInline`.
### DataFriskShell
This is what you see in the gif animation above. This component renders as a single data navigation "shell" fixed to the bottom of the window. It can be expanded/hidden via a toggle at the bottom right hand corner of the screen. It's best when all the data you want to frisk is within scope within a single parent component.
Example:
```clojure
(ns datafrisk.demo
(:require [reagent.core :as r]
[datafrisk.core :as d]))
(defn mount-root []
(r/render
[d/DataFriskShell
;; List of arguments you want to visualize
{:data {:some-string "a"
:vector-with-map [1 2 3 3 {:a "a" :b "b"}]
:a-set #{1 2 3}
:a-map {:x "x" :y "y" :z [1 2 3 4]}
:a-list '(1 2 3)
:a-seq (seq [1 2])
:an-object (clj->js {:a "a"})
:this-is-a-very-long-keyword :g}}
{:a :b :c :d}]
(js/document.getElementById "app")))
```
However, if you did something like:
```clojure
(ns datafrisk.demo
(:require [reagent.core :as r]
[datafrisk.core :as d]))
(defn some-component
[name]
[:div "Hi " name [d/DataFriskShell {:name name :testing 123}]])
(defn mount-root []
(r/render
[:div
(for [x ["Bob" "Jo" "Ellen"]]
[some-component x])]
(js/document.getElementById "app")))
```
Then you'll find that one of the `:testing` maps will end up being accessible via the shell.
For this situation, we have the following:
### FriskInline
This component renders as a small box label "data frisk" which expands into a navigator much like that found in the shell. It's perfect for situations where you want to frisk data from multiple components (or multiple instances of the same component, as with our `some-component` example above). Here's a quick demo.
```clojure
(ns datafrisk.demo
(:require [reagent.core :as r]
[datafrisk.core :as d]))
(defn some-component
[name]
[:div "Hi " name [d/FriskInline {:name name :testing 123}]])
(defn mount-root []
(r/render
[:div
(for [x ["Bob" "Jo" "Ellen"]]
[some-component x])]
(js/document.getElementById "app")))
```
Et viola!
### Use with re-frame
This example uses [re-frame](https://github.com/Day8/re-frame) to display a data-frisk component displaying the current app database:
```clojure
(ns datafrisk.re-frame-example
(:require [reagent.core :as r]
[datafrisk.core :as d]
[re-frame.core :refer [subscribe reg-sub]]))
;; Set up a subscription
(defn- app-db-subscription
"Subscribe to any change in the app db under the path"
[db [_ path]]
(get-in db path))
(reg-sub :debug/everything app-db-subscription)
;; Define a form-2 component
(defn frisk
[& path]
(let [everything (subscribe [:debug/everything path])]
(fn [& path]
[d/DataFriskShell @everything])))
;; Now you can use the component thusly:
(defn mount-root []
(r/render
[:div
[:h1 "Welcome to ZomboCom"]
;; This displays the entire app database:
[frisk]
;; This displays everything under a specific subtree:
[frisk :subtree :that :interests-me]]
(js/document.getElementById "app")))
```
### For more
See the dev/demo.cljs namespace for more usage of the shell.
## License
Copyright © 2016 Odin Standal
Distributed under the MIT License (MIT)
|
C#
|
UTF-8
| 7,493 | 3 | 3 |
[
"MIT",
"BSD-3-Clause"
] |
permissive
|
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace Mercurial
{
/// <summary>
/// This class is responsible for decoding the output from the Mercurial
/// instance running in Command Server mode.
/// </summary>
internal static class CommandServerOutputDecoder
{
/// <summary>
/// The encoding used by the standard output from the Mercurial persistent client.
/// </summary>
private static readonly Encoding _Encoding = ClientExecutable.TextEncoding;
/// <summary>
/// Retrieve the complete output from executing a command, as
/// separate standard output, standard error and the exit code.
/// </summary>
/// <param name="reader">
/// The <see cref="StreamReader"/> that output is read from.
/// </param>
/// <param name="standardOutput">
/// Upon exit, if the method returns <c>true</c>, then this parameter has been
/// changed to contain the standard output from executing the command.
/// </param>
/// <param name="standardError">
/// Upon exit, if the method returns <c>true</c>, then this parameter has been
/// changed to contain the standard error from executing the command.
/// </param>
/// <param name="exitCode">
/// Upon exit, if the method returns <c>true</c>, then this parameter has been
/// changed to contain the exit code from executing the command.
/// </param>
/// <returns>
/// <c>true</c> if the output was successfully decoded;
/// otherwise, <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="reader"/> is <c>null</c>.</para>
/// </exception>
public static bool GetOutput(StreamReader reader, out string standardOutput, out string standardError, out int exitCode)
{
if (reader == null)
throw new ArgumentNullException("reader");
standardOutput = string.Empty;
standardError = string.Empty;
exitCode = 0;
var standardOutputBuilder = new StringBuilder();
var standardErrorBuilder = new StringBuilder();
while (true)
{
char type;
string content;
if (!DecodeOneBlock(reader, out type, out content, out exitCode))
return false;
switch (type)
{
case 'o':
standardOutputBuilder.Append(content);
break;
case 'e':
standardErrorBuilder.Append(content);
break;
case 'r':
standardOutput = standardOutputBuilder.ToString();
standardError = standardErrorBuilder.ToString();
return true;
}
}
}
/// <summary>
/// Decodes one block of output from the reader.
/// </summary>
/// <param name="reader">
/// The <see cref="StreamReader"/> to decode a block from.
/// </param>
/// <param name="type">
/// Upon return from the method, if the method returns <c>true</c>, then
/// this parameter contains the one-character type of the output, which is
/// either 'o', 'e' or 'r'.
/// </param>
/// <param name="content">
/// Upon return from the method, if the method returns <c>true</c>, then
/// this parameter contains the decoded string content of the 'o' or 'e' type.
/// </param>
/// <param name="exitCode">
/// Upon return from the method, if the method returns <c>true</c>, then
/// this parameter contains the exit code of the command, for the 'r' type.
/// </param>
/// <returns>
/// <c>true</c> if the output was successfully decoded;
/// otherwise, <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="reader"/> is <c>null</c>.</para>
/// </exception>
public static bool DecodeOneBlock(StreamReader reader, out char type, out string content, out int exitCode)
{
if (reader == null)
throw new ArgumentNullException("reader");
type = '\0';
content = string.Empty;
exitCode = 0;
int typeValue = reader.Read();
if (typeValue == -1)
return false;
type = (char)typeValue;
switch (type)
{
case 'o':
case 'e':
content = DecodeString(reader);
return true;
case 'r':
var length = DecodeInt32(reader);
if (length != 4)
return false;
exitCode = DecodeInt32(reader);
return true;
}
return false;
}
/// <summary>
/// Decodes and returns a single string from the <see cref="StreamReader"/>.
/// </summary>
/// <param name="reader">
/// The <see cref="StreamReader"/> to decode the string from.
/// </param>
/// <returns>
/// The decoded string or <c>null</c> if the data could not be decoded.
/// </returns>
/// <remarks>
/// Note that this method will not check that <paramref name="reader"/> is non-null.
/// </remarks>
private static string DecodeString(StreamReader reader)
{
var length = DecodeInt32(reader);
if (length < 0)
return null;
// max: 1MB, to avoid memory problems with corrupt data
if (length > 1 * 1024 * 1024)
return null;
var buffer = new byte[length];
for (int index = 0; index < length; index++)
{
int unencodedByte = reader.Read();
if (unencodedByte == -1)
return null;
buffer[index] = (byte)unencodedByte;
}
return _Encoding.GetString(buffer);
}
/// <summary>
/// Decodes and returns a single 32-bit integer from the <see cref="StreamReader"/>.
/// </summary>
/// <param name="reader">
/// The <see cref="StreamReader"/> to decode the 32-bit integer from.
/// </param>
/// <returns>
/// The decoded integer, or -1 if the data could not be decoded.
/// </returns>
/// <remarks>
/// Note that this method will not check that <paramref name="reader"/> is non-null.
/// </remarks>
private static int DecodeInt32(StreamReader reader)
{
int b1 = reader.Read();
int b2 = reader.Read();
int b3 = reader.Read();
int b4 = reader.Read();
if (b1 == -1 || b2 == -1 || b3 == -1 || b4 == -1)
return -1;
return b4 | (b3 << 8) | (b2 << 16) | (b1 << 24);
}
}
}
|
Markdown
|
UTF-8
| 3,210 | 2.703125 | 3 |
[] |
no_license
|
# Objectifs pédagogiques session 4
## Session 4 - Développement Front End professionnel
### Semaine 2
#### **Lun 6 et Mar 7 Jan :** Découverte d'Angular
* **Notions :** [Découverte d'Angular](../cours/angular.md)
* **Objectif•s :**
* Comprendre les bases d'Angular (Components & Templates)
* Interpolation `{{ }}`
* Property binding `[ ]`
* Event binding `( )`
* Structural directives (`*ngFor` & `*ngIf`)
* Input
* Output
* Savoir utiliser le Routing pour naviguer dans son application
* Savoir créer des services pour la gestion de données
* Savoir créer des formulaires
* **Compétence•s visées•s :** 2 et 3
* **Modalité•s pédagogique•s :** Notions et exercices d'application [Tutoriel Angular](../exercice/angular.md)
* **Temporalité :** 14h
#### **Mer 8 et Jeu 9 Jan :** Mini projet calculateur glycémique
* **Objectif•s :**
* Appliquer les notions de base d'Angular
* **Compétence•s visées•s :** 2 et 3
* **Modalité•s pédagogique•s :** Mini projet [calculateur de charge glycémique](https://simplonline.co/briefs/detail/yrwtLNwFiqbBDAqNE)
* **Temporalité :** 14h
#### **Ven 10 Jan :** Fonctions utilitaires tableaux JS et récap Angular
* **Notions :** [Fonction utilitaires tableaux](https://stackblitz.com/edit/tableaux-js-jlsgrand), [Récap semaine 1 Angular](../ressource/angular-cheat-sheet.md)
* **Objectif•s :**
* Savoir déclarer des fonctions fléchées
* Savoir utiliser les fonctions utilitaires des tableaux (`filter()`, `map()`, `reduce()`).
* **Compétence•s visées•s :** 2 et 3
* **Modalité•s pédagogique•s :** Exercice en live coding, Construction lexique en groupe
* **Temporalité :** 7h
### Semaine 3
#### **Lun 13 Jan (matin):** Challenge Angular design
* **Objectif•s :** Réaliser en groupe la page d'une application de suivi d'activité des apprenants Simplon
* Découvrir le développement en équipe
* Se challenger sur la réalisation d'interface graphique
* **Compétence•s visées•s :** 2 et 3
* **Modalité•s pédagogique•s :** [Angular Challange](../exercice/challenge.md)
* **Temporalité :** 3h
#### Mar 14 (matin) Jan :** Correction mini projet Alimentation / Notions RxJs
* **Objectif•s :**
* Comprendre la philosophie RxJs
* `Observable`
* `operators`
* `Subscription`
* Connecter son application Angular sur une API REST
* **Compétence•s visées•s :** 2 et 3
* **Modalité•s pédagogique•s :** Optionnel : [Exercice RxJs](../exercice/rxjs.md)
* **Temporalité :** 3h
#### **Lun 13 (après-midi), Mar 14 (après-midi), Mer 15 et Jeu 16 Jan :** Mini projet Timeline
* **Objectif•s :**
* Appliquer les notions de base d'Angular
* Connecter son application Angular sur une API REST
* **Compétence•s visées•s :** 2 et 3
* **Modalité•s pédagogique•s :** [Mini projet Timeline](https://simplonline.co/briefs/detail/4ZMRzQx3NjbF9xpqs)
* **Temporalité :** 21h
#### **Ven 17 Jan :** Présentation et Feedback
* **Objectif•s :**
* Savoir présenter son travail à un groupe
* **Compétence•s visées•s :** 2 et 3
* **Modalité•s pédagogique•s :** Présentation du mini projet
* **Temporalité :** 7h
|
Shell
|
UTF-8
| 431 | 3.875 | 4 |
[] |
no_license
|
#!/bin/bash
#Finds active virtual machines and creates a folder where all block devices for each machine are kept
#Ex.: timemcn03 block devices are kept in "/cloud/storage/timemcn03-mounts"
list_vms=$(virsh list --all --name)
path1=/cloud/storage
for i in $list_vms; do
path2="$path1/$i-mounts"
if [[ -d "$path2" ]]
then
printf "$i-mounts already exists\n"
else
mkdir $path2 &&
printf "$i has been created\n"
fi
done
|
Markdown
|
UTF-8
| 2,504 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
Password Generator - https://github.com/SkinnySk8ter/homework3
assignment#3
Table Of Contents
[General Info]
[Assignment Deatails]
[how to setup]
[Look Out!]
[General Info] - UPDATED
This is the ReadMe File for Homework assignment #3. For this assignment we were tasked with promoting user interaction to store responses in order to generate a random password based off of what the user selected.
[Assignment Details]
When the user arrives at your page they should receive an alert asking them to choose a number between 8-128. After choosing a number between that range the user is then asked a series of questions to help us get a better understanding of what kind of password should be generated. In my example I tried to use the method of having the answers stored and having the ability to click on a "generate password" button and have a random series of characters pop up depending on the choices of the user. For example, if the user chose 50 characters, uppercase letters, and numbers, then the resulting generated password will equal the same set of choices.
I currently have the user inputting an amount for the length. Still working on getting specific options to work such as all capital letters or all integers.
[How To Setup]
The files within this document are going to be updated on a regular basis! However....there are some things to be aware of.
1.The css style sheet is located in the same folder under style.css.
2.All of the pages are linked together so feel free to click away to explore!
4.As stated before, this is a work in progress! Notes on things that have not been worked out yet are marked in green notation (or possibly another color depending on what you prefer).
[Look-Out!]
As stated before the page is still a work in progress! The page is nice and basic with a little bit of CSS to give the page a little bit of order. There are a lot of things that have been commented out as I did not want to lose my train of thought while trying different things to get the code to work with the password generator button. The popups work just fine however. There were a few times where I would try to work on the button and the popups would disappear; resulting in a lot of things being commented out so that way I would not lose any of the thoughts in progress but still have the ability to keep the page up and functioning somewhat.
update- removed promps. Went with giving one alert to instruct the user about the input boxes instead for easier interaction.
|
PHP
|
UTF-8
| 1,091 | 2.734375 | 3 |
[] |
no_license
|
<?php
namespace APP\Controllers;
use APP\Core\Controller;
use APP\Models\RegisterModel;
class RegisterController extends Controller{
public function register()
{
$method = strtolower($_SERVER['REQUEST_METHOD']);
if ( $method == 'get') {
$this->render('register');
} elseif ($method == 'post') {
if (empty($_POST)) {
echo 'Please provide some data.';
} else {
$data = [
'name' => $_POST['name'],
'email' => $_POST['email'],
'phone' => $_POST['phone'],
'password' => $_POST['password'],
];
$model = new RegisterModel();
$inserted = $model->insertData('users', $data);
if ($inserted) {
echo 'Data inserted successfully';
} else {
echo 'Data insertion failed!';
}
}
}
}
}
|
Java
|
UTF-8
| 17,088 | 2.40625 | 2 |
[] |
no_license
|
package com.daveclay.midi;
import com.daveclay.midi.random.RandyTheRandom;
import java.util.HashMap;
import java.util.Map;
import static com.daveclay.midi.NoteValueType.*;
public enum NoteValue {
C0("C", "C0", 0, NOTE),
C_SHARP0("C#", "C#0", 1, NOTE),
D_FLAT0("Db", "Db0", 1, NOTE),
D0("D", "D0", 2, NOTE),
D_SHARP0("D#", "D#0", 3, NOTE),
E_FLAT0("Eb", "Eb0", 3, NOTE),
E0("E", "E0", 4, NOTE),
F0("F", "F0", 5, NOTE),
F_SHARP0("F#", "F#0", 6, NOTE),
G_FLAT0("Gb", "Gb0", 6, NOTE),
G0("G", "G0", 7, NOTE),
G_SHARP0("G#", "G#0", 8, NOTE),
A_FLAT0("Ab", "Ab0", 8, NOTE),
A0("A", "A0", 9, NOTE),
A_SHARP0("A#", "A#0", 10, NOTE),
B_FLAT0("Bb", "Bb0", 10, NOTE),
B0("B", "B0", 11, NOTE),
C1("C", "C1", 12, NOTE),
C_SHARP1("C#", "C#1", 13, NOTE),
D_FLAT1("Db", "Db1", 13, NOTE),
D1("D", "D1", 14, NOTE),
D_SHARP1("D#", "D#1", 15, NOTE),
E_FLAT1("Eb", "Eb1", 15, NOTE),
E1("E", "E1", 16, NOTE),
F1("F", "F1", 17, NOTE),
F_SHARP1("F#", "F#1", 18, NOTE),
G_FLAT1("Gb", "Gb1", 18, NOTE),
G1("G", "G1", 19, NOTE),
G_SHARP1("G#", "G#1", 20, NOTE),
A_FLAT1("Ab", "Ab1", 20, NOTE),
A1("A", "A1", 21, NOTE),
A_SHARP1("A#", "A#1", 22, NOTE),
B_FLAT1("Bb", "Bb1", 22, NOTE),
B1("B", "B1", 23, NOTE),
C2("C", "C2", 24, NOTE),
C_SHARP2("C#", "C#2", 25, NOTE),
D_FLAT2("Db", "Db2", 25, NOTE),
D2("D", "D2", 26, NOTE),
D_SHARP2("D#", "D#2", 27, NOTE),
E_FLAT2("Eb", "Eb2", 27, NOTE),
E2("E", "E2", 28, NOTE),
F2("F", "F2", 29, NOTE),
F_SHARP2("F#", "F#2", 30, NOTE),
G_FLAT2("Gb", "Gb2", 30, NOTE),
G2("G", "G2", 31, NOTE),
G_SHARP2("G#", "G#2", 32, NOTE),
A_FLAT2("Ab", "Ab2", 32, NOTE),
A2("A", "A2", 33, NOTE),
A_SHARP2("A#", "A#2", 34, NOTE),
B_FLAT2("Bb", "Bb2", 34, NOTE),
B2("B", "B2", 35, NOTE),
C3("C", "C3", 36, NOTE),
C_SHARP3("C#", "C#3", 37, NOTE),
D_FLAT3("Db", "Db3", 37, NOTE),
D3("D", "D3", 38, NOTE),
D_SHARP3("D#", "D#3", 39, NOTE),
E_FLAT3("Eb", "Eb3", 39, NOTE),
E3("E", "E3", 40, NOTE),
F3("F", "F3", 41, NOTE),
F_SHARP3("F#", "F#3", 42, NOTE),
G_FLAT3("Gb", "Gb3", 42, NOTE),
G3("G", "G3", 43, NOTE),
G_SHARP3("G#", "G#3", 44, NOTE),
A_FLAT3("Ab", "Ab3", 44, NOTE),
A3("A", "A3", 45, NOTE),
A_SHARP3("A#", "A#3", 46, NOTE),
B_FLAT3("Bb", "Bb3", 46, NOTE),
B3("B", "B3", 47, NOTE),
C4("C", "C4", 48, NOTE),
C_SHARP4("C#", "C#4", 49, NOTE),
D_FLAT4("Db", "Db4", 49, NOTE),
D4("D", "D4", 50, NOTE),
D_SHARP4("D#", "D#4", 51, NOTE),
E_FLAT4("Eb", "Eb4", 51, NOTE),
E4("E", "E4", 52, NOTE),
F4("F", "F4", 53, NOTE),
F_SHARP4("F#", "F#4", 54, NOTE),
G_FLAT4("Gb", "Gb4", 54, NOTE),
G4("G", "G4", 55, NOTE),
G_SHARP4("G#", "G#4", 56, NOTE),
A_FLAT4("Ab", "Ab4", 56, NOTE),
A4("A", "A4", 57, NOTE),
A_SHARP4("A#", "A#4", 58, NOTE),
B_FLAT4("Bb", "Bb4", 58, NOTE),
B4("B", "B4", 59, NOTE),
C5("C", "C5", 60, NOTE),
C_SHARP5("C#", "C#5", 61, NOTE),
D_FLAT5("Db", "Db5", 61, NOTE),
D5("D", "D5", 62, NOTE),
D_SHARP5("D#", "D#5", 63, NOTE),
E_FLAT5("Eb", "Eb5", 63, NOTE),
E5("E", "E5", 64, NOTE),
F5("F", "F5", 65, NOTE),
F_SHARP5("F#", "F#5", 66, NOTE),
G_FLAT5("Gb", "Gb5", 66, NOTE),
G5("G", "G5", 67, NOTE),
G_SHARP5("G#", "G#5", 68, NOTE),
A_FLAT5("Ab", "Ab5", 68, NOTE),
A5("A", "A5", 69, NOTE),
A_SHARP5("A#", "A#5", 70, NOTE),
B_FLAT5("Bb", "Bb5", 70, NOTE),
B5("B", "B5", 71, NOTE),
C6("C", "C6", 72, NOTE),
C_SHARP6("C#", "C#6", 73, NOTE),
D_FLAT6("Db", "Db6", 73, NOTE),
D6("D", "D6", 74, NOTE),
D_SHARP6("D#", "D#6", 75, NOTE),
E_FLAT6("Eb", "Eb6", 75, NOTE),
E6("E", "E6", 76, NOTE),
F6("F", "F6", 77, NOTE),
F_SHARP6("F#", "F#6", 78, NOTE),
G_FLAT6("Gb", "Gb6", 78, NOTE),
G6("G", "G6", 79, NOTE),
G_SHARP6("G#", "G#6", 80, NOTE),
A_FLAT6("Ab", "Ab6", 80, NOTE),
A6("A", "A6", 81, NOTE),
A_SHARP6("A#", "A#6", 82, NOTE),
B_FLAT6("Bb", "Bb6", 82, NOTE),
B6("B", "B6", 83, NOTE),
C7("C", "C7", 84, NOTE),
C_SHARP7("C#", "C#7", 85, NOTE),
D_FLAT7("Db", "Db7", 85, NOTE),
D7("D", "D7", 86, NOTE),
D_SHARP7("D#", "D#7", 87, NOTE),
E_FLAT7("Eb", "Eb7", 87, NOTE),
E7("E", "E7", 88, NOTE),
F7("F", "F7", 89, NOTE),
F_SHARP7("F#", "F#7", 90, NOTE),
G_FLAT7("Gb", "Gb7", 90, NOTE),
G7("G", "G7", 91, NOTE),
G_SHARP7("G#", "G#7", 92, NOTE),
A_FLAT7("Ab", "Ab7", 92, NOTE),
A7("A", "A7", 93, NOTE),
A_SHARP7("A#", "A#7", 94, NOTE),
B_FLAT7("Bb", "Bb7", 94, NOTE),
B7("B", "B7", 95, NOTE),
C8("C", "C8", 96, NOTE),
C_SHARP8("C#", "C#8", 97, NOTE),
D_FLAT8("Db", "Db8", 97, NOTE),
D8("D", "D8", 98, NOTE),
D_SHARP8("D#", "D#8", 99, NOTE),
E_FLAT8("Eb", "Eb8", 99, NOTE),
E8("E", "E8", 100, NOTE),
F8("F", "F8", 101, NOTE),
F_SHARP8("F#", "F#8", 102, NOTE),
G_FLAT8("Gb", "Gb8", 102, NOTE),
G8("G", "G8", 103, NOTE),
G_SHARP8("G#", "G#8", 104, NOTE),
A_FLAT8("Ab", "Ab8", 104, NOTE),
A8("A", "A8", 105, NOTE),
A_SHARP8("A#", "A#8", 106, NOTE),
B_FLAT8("Bb", "Bb8", 106, NOTE),
B8("B", "B8", 107, NOTE),
C9("C", "C9", 108, NOTE),
C_SHARP9("C#", "C#9", 109, NOTE),
D_FLAT9("Db", "Db9", 109, NOTE),
D9("D", "D9", 110, NOTE),
D_SHARP9("D#", "D#9", 111, NOTE),
E_FLAT9("Eb", "Eb9", 111, NOTE),
E9("E", "E9", 112, NOTE),
F9("F", "F9", 113, NOTE),
F_SHARP9("F#", "F#9", 114, NOTE),
G_FLAT9("Gb", "Gb9", 114, NOTE),
G9("G", "G9", 115, NOTE),
G_SHARP9("G#", "G#9", 116, NOTE),
A_FLAT9("Ab", "Ab9", 116, NOTE),
A9("A", "A9", 117, NOTE),
A_SHARP9("A#", "A#9", 118, NOTE),
B_FLAT9("Bb", "Bb9", 118, NOTE),
B9("B", "B9", 119, NOTE),
C10("C", "C10", 120, NOTE),
C_SHARP10("C#", "C#10", 121, NOTE),
D_FLAT10("Db", "Db10", 121, NOTE),
D10("D", "D10", 122, NOTE),
D_SHARP10("D#", "D#10", 123, NOTE),
E_FLAT10("Eb", "Eb10", 123, NOTE),
E10("E", "E10", 124, NOTE),
F10("F", "F10", 125, NOTE),
F_SHARP10("F#", "F#10", 126, NOTE),
G_FLAT10("Gb", "Gb10", 126, NOTE),
G10("G", "G10", 127, NOTE),
GM_ACOUSTIC_BASS_DRUM("GM_ACOUSTIC_BASS_DRUM", 36, GM_SOUND),
GM_BASS_DRUM_1("GM_BASS_DRUM_1", 36, GM_SOUND),
GM_SIDE_STICK("GM_SIDE_STICK", 37, GM_SOUND),
GM_ACOUSTIC_SNARE("GM_ACOUSTIC_SNARE", 38, GM_SOUND),
GM_HAND_CLAP("GM_HAND_CLAP", 39, GM_SOUND),
GM_ELECTRIC_SNARE("GM_ELECTRIC_SNARE", 40, GM_SOUND),
GM_LOW_FLOOR_TOM("GM_LOW_FLOOR_TOM", 41, GM_SOUND),
GM_CLOSED_HI_HAT("GM_CLOSED_HI_HAT", 42, GM_SOUND),
GM_HIGH_FLOOR_TOM("GM_HIGH_FLOOR_TOM", 43, GM_SOUND),
GM_PEDAL_HI_HAT("GM_PEDAL_HI_HAT", 44, GM_SOUND),
GM_LOW_TOM("GM_LOW_TOM", 45, GM_SOUND),
GM_OPEN_HI_HAT("GM_OPEN_HI_HAT", 46, GM_SOUND),
GM_LOW_MID_TOM("GM_LOW_MID_TOM", 47, GM_SOUND),
GM_HI_MID_TOM("GM_HI_MID_TOM", 48, GM_SOUND),
GM_CRASH_CYMBAL_1("GM_CRASH_CYMBAL_1", 49, GM_SOUND),
GM_HIGH_TOM("GM_HIGH_TOM", 50, GM_SOUND),
GM_RIDE_CYMBAL_1("GM_RIDE_CYMBAL_1", 51, GM_SOUND),
GM_CHINESE_CYMBAL("GM_CHINESE_CYMBAL", 52, GM_SOUND),
GM_RIDE_BELL("GM_RIDE_BELL", 53, GM_SOUND),
GM_TAMBOURINE("GM_TAMBOURINE", 54, GM_SOUND),
GM_SPLASH_CYMBAL("GM_SPLASH_CYMBAL", 55, GM_SOUND),
GM_COWBELL("GM_COWBELL", 56, GM_SOUND),
GM_CRASH_CYMBAL_2("GM_CRASH_CYMBAL_2", 57, GM_SOUND),
GM_VIBRASLAP("GM_VIBRASLAP", 58, GM_SOUND),
GM_RIDE_CYMBAL_2("GM_RIDE_CYMBAL_2", 59, GM_SOUND),
GM_HI_BONGO("GM_HI_BONGO", 60, GM_SOUND),
GM_LOW_BONGO("GM_LOW_BONGO", 61, GM_SOUND),
GM_MUTE_HI_CONGA("GM_MUTE_HI_CONGA", 62, GM_SOUND),
GM_OPEN_HI_CONGA("GM_OPEN_HI_CONGA", 63, GM_SOUND),
GM_LOW_CONGA("GM_LOW_CONGA", 64, GM_SOUND),
GM_HIGH_TIMBALE("GM_HIGH_TIMBALE", 65, GM_SOUND),
GM_LOW_TIMBALE("GM_LOW_TIMBALE", 66, GM_SOUND),
GM_HIGH_AGOGO("GM_HIGH_AGOGO", 67, GM_SOUND),
GM_LOW_AGOGO("GM_LOW_AGOGO", 68, GM_SOUND),
GM_CABASA("GM_CABASA", 69, GM_SOUND),
GM_MARACAS("GM_MARACAS", 70, GM_SOUND),
GM_SHORT_WHISTLE("GM_SHORT_WHISTLE", 71, GM_SOUND),
GM_LONG_WHISTLE("GM_LONG_WHISTLE", 72, GM_SOUND),
GM_SHORT_GUIRO("GM_SHORT_GUIRO", 73, GM_SOUND),
GM_LONG_GUIRO("GM_LONG_GUIRO", 74, GM_SOUND),
GM_CLAVES("GM_CLAVES", 75, GM_SOUND),
GM_HI_WOOD_BLOCK("GM_HI_WOOD_BLOCK", 76, GM_SOUND),
GM_LOW_WOOD_BLOCK("GM_LOW_WOOD_BLOCK", 77, GM_SOUND),
GM_MUTE_CUICA("GM_MUTE_CUICA", 78, GM_SOUND),
GM_OPEN_CUICA("GM_OPEN_CUICA", 79, GM_SOUND),
GM_MUTE_TRIANGLE("GM_MUTE_TRIANGLE", 80, GM_SOUND),
GM_OPEN_TRIANGLE("GM_OPEN_TRIANGLE", 81, GM_SOUND),
GM_ACOUSTIC_GRAND_PIANO("GM_ACOUSTIC_GRAND_PIANO", 1 - 1, GM_SOUND),
GM_BRIGHT_ACOUSTIC_PIANO("GM_BRIGHT_ACOUSTIC_PIANO", 2 - 1, GM_SOUND),
GM_ELECTRIC_GRAND_PIANO("GM_ELECTRIC_GRAND_PIANO", 3 - 1, GM_SOUND),
GM_HONKY_TONK_PIANO("GM_HONKY_TONK_PIANO", 4 - 1, GM_SOUND),
GM_ELECTRIC_PIANO_1("GM_ELECTRIC_PIANO_1", 5 - 1, GM_SOUND),
GM_ELECTRIC_PIANO_2("GM_ELECTRIC_PIANO_2", 6 - 1, GM_SOUND),
GM_HARPSICHORD("GM_HARPSICHORD", 7 - 1, GM_SOUND),
GM_CLAVINET("GM_CLAVINET", 8 - 1, GM_SOUND),
GM_CELESTA("GM_CELESTA", 9 - 1, GM_SOUND),
GM_GLOCKENSPIEL("GM_GLOCKENSPIEL", 10 - 1, GM_SOUND),
GM_MUSIC_BOX("GM_MUSIC_BOX", 11 - 1, GM_SOUND),
GM_VIBRAPHONE("GM_VIBRAPHONE", 12 - 1, GM_SOUND),
GM_MARIMBA("GM_MARIMBA", 13 - 1, GM_SOUND),
GM_XYLOPHONE("GM_XYLOPHONE", 14 - 1, GM_SOUND),
GM_TUBULAR_BELLS("GM_TUBULAR_BELLS", 15 - 1, GM_SOUND),
GM_DULCIMER("GM_DULCIMER", 16 - 1, GM_SOUND),
GM_DRAWBAR_ORGAN("GM_DRAWBAR_ORGAN", 17 - 1, GM_SOUND),
GM_PERCUSSIVE_ORGAN("GM_PERCUSSIVE_ORGAN", 18 - 1, GM_SOUND),
GM_ROCK_ORGAN("GM_ROCK_ORGAN", 19 - 1, GM_SOUND),
GM_CHURCH_ORGAN("GM_CHURCH_ORGAN", 20 - 1, GM_SOUND),
GM_REED_ORGAN("GM_REED_ORGAN", 21 - 1, GM_SOUND),
GM_ACCORDION("GM_ACCORDION", 22 - 1, GM_SOUND),
GM_HARMONICA("GM_HARMONICA", 23 - 1, GM_SOUND),
GM_TANGO_ACCORDION("GM_TANGO_ACCORDION", 24 - 1, GM_SOUND),
GM_ACOUSTIC_GUITAR_NYLON("GM_ACOUSTIC_GUITAR_NYLON", 25 - 1, GM_SOUND),
GM_ACOUSTIC_GUITAR_STEEL("GM_ACOUSTIC_GUITAR_STEEL", 26 - 1, GM_SOUND),
GM_ELECTRIC_GUITAR_JAZZ("GM_ELECTRIC_GUITAR_JAZZ", 27 - 1, GM_SOUND),
GM_ELECTRIC_GUITAR_CLEAN("GM_ELECTRIC_GUITAR_CLEAN", 28 - 1, GM_SOUND),
GM_ELECTRIC_GUITAR_MUTED("GM_ELECTRIC_GUITAR_MUTED", 29 - 1, GM_SOUND),
GM_OVERDRIVEN_GUITAR("GM_OVERDRIVEN_GUITAR", 30 - 1, GM_SOUND),
GM_DISTORTION_GUITAR("GM_DISTORTION_GUITAR", 31 - 1, GM_SOUND),
GM_GUITAR_HARMONICS("GM_GUITAR_HARMONICS", 32 - 1, GM_SOUND),
GM_ACOUSTIC_BASS("GM_ACOUSTIC_BASS", 33 - 1, GM_SOUND),
GM_ELECTRIC_BASS_FINGER("GM_ELECTRIC_BASS_FINGER", 34 - 1, GM_SOUND),
GM_ELECTRIC_BASS_PICK("GM_ELECTRIC_BASS_PICK", 35 - 1, GM_SOUND),
GM_FRETLESS_BASS("GM_FRETLESS_BASS", 36 - 1, GM_SOUND),
GM_SLAP_BASS_1("GM_SLAP_BASS_1", 37 - 1, GM_SOUND),
GM_SLAP_BASS_2("GM_SLAP_BASS_2", 38 - 1, GM_SOUND),
GM_SYNTH_BASS_1("GM_SYNTH_BASS_1", 39 - 1, GM_SOUND),
GM_SYNTH_BASS_2("GM_SYNTH_BASS_2", 40 - 1, GM_SOUND),
GM_VIOLIN("GM_VIOLIN", 41 - 1, GM_SOUND),
GM_VIOLA("GM_VIOLA", 42 - 1, GM_SOUND),
GM_CELLO("GM_CELLO", 43 - 1, GM_SOUND),
GM_CONTRABASS("GM_CONTRABASS", 44 - 1, GM_SOUND),
GM_TREMOLO_STRINGS("GM_TREMOLO_STRINGS", 45 - 1, GM_SOUND),
GM_PIZZICATO_STRINGS("GM_PIZZICATO_STRINGS", 46 - 1, GM_SOUND),
GM_ORCHESTRAL_HARP("GM_ORCHESTRAL_HARP", 47 - 1, GM_SOUND),
GM_TIMPANI("GM_TIMPANI", 48 - 1, GM_SOUND),
GM_STRING_ENSEMBLE_1("GM_STRING_ENSEMBLE_1", 49 - 1, GM_SOUND),
GM_STRING_ENSEMBLE_2("GM_STRING_ENSEMBLE_2", 50 - 1, GM_SOUND),
GM_SYNTH_STRINGS_1("GM_SYNTH_STRINGS_1", 51 - 1, GM_SOUND),
GM_SYNTH_STRINGS_2("GM_SYNTH_STRINGS_2", 52 - 1, GM_SOUND),
GM_CHOIR_AAHS("GM_CHOIR_AAHS", 53 - 1, GM_SOUND),
GM_VOICE_OOHS("GM_VOICE_OOHS", 54 - 1, GM_SOUND),
GM_SYNTH_CHOIR("GM_SYNTH_CHOIR", 55 - 1, GM_SOUND),
GM_ORCHESTRA_HIT("GM_ORCHESTRA_HIT", 56 - 1, GM_SOUND),
GM_TRUMPET("GM_TRUMPET", 57 - 1, GM_SOUND),
GM_TROMBONE("GM_TROMBONE", 58 - 1, GM_SOUND),
GM_TUBA("GM_TUBA", 59 - 1, GM_SOUND),
GM_MUTED_TRUMPET("GM_MUTED_TRUMPET", 60 - 1, GM_SOUND),
GM_FRENCH_HORN("GM_FRENCH_HORN", 61 - 1, GM_SOUND),
GM_BRASS_SECTION("GM_BRASS_SECTION", 62 - 1, GM_SOUND),
GM_SYNTH_BRASS_1("GM_SYNTH_BRASS_1", 63 - 1, GM_SOUND),
GM_SYNTH_BRASS_2("GM_SYNTH_BRASS_2", 64 - 1, GM_SOUND),
GM_SOPRANO_SAX("GM_SOPRANO_SAX", 65 - 1, GM_SOUND),
GM_ALTO_SAX("GM_ALTO_SAX", 66 - 1, GM_SOUND),
GM_TENOR_SAX("GM_TENOR_SAX", 67 - 1, GM_SOUND),
GM_BARITONE_SAX("GM_BARITONE_SAX", 68 - 1, GM_SOUND),
GM_OBOE("GM_OBOE", 69 - 1, GM_SOUND),
GM_ENGLISH_HORN("GM_ENGLISH_HORN", 70 - 1, GM_SOUND),
GM_BASSOON("GM_BASSOON", 71 - 1, GM_SOUND),
GM_CLARINET("GM_CLARINET", 72 - 1, GM_SOUND),
GM_PICCOLO("GM_PICCOLO", 73 - 1, GM_SOUND),
GM_FLUTE("GM_FLUTE", 74 - 1, GM_SOUND),
GM_RECORDER("GM_RECORDER", 75 - 1, GM_SOUND),
GM_PAN_FLUTE("GM_PAN_FLUTE", 76 - 1, GM_SOUND),
GM_BLOWN_BOTTLE("GM_BLOWN_BOTTLE", 77 - 1, GM_SOUND),
GM_SHAKUHACHI("GM_SHAKUHACHI", 78 - 1, GM_SOUND),
GM_WHISTLE("GM_WHISTLE", 79 - 1, GM_SOUND),
GM_OCARINA("GM_OCARINA", 80 - 1, GM_SOUND),
GM_SYNTH_LEAD_1_SQUARE("GM_SYNTH_LEAD_1_SQUARE", 81 - 1, GM_SOUND),
GM_SYNTH_LEAD_2_SAWTOOTH("GM_SYNTH_LEAD_2_SAWTOOTH", 82 - 1, GM_SOUND),
GM_SYNTH_LEAD_3_CALLIOPE("GM_SYNTH_LEAD_3_CALLIOPE", 83 - 1, GM_SOUND),
GM_SYNTH_LEAD_4_CHIFF("GM_SYNTH_LEAD_4_CHIFF", 84 - 1, GM_SOUND),
GM_SYNTH_LEAD_5_CHARANG("GM_SYNTH_LEAD_5_CHARANG", 85 - 1, GM_SOUND),
GM_SYNTH_LEAD_6_VOICE("GM_SYNTH_LEAD_6_VOICE", 86 - 1, GM_SOUND),
GM_SYNTH_LEAD_7_FIFTHS("GM_SYNTH_LEAD_7_FIFTHS", 87 - 1, GM_SOUND),
GM_SYNTH_LEAD_8_BASS_AND_LEAD("GM_SYNTH_LEAD_8_BASS_AND_LEAD", 88 - 1, GM_SOUND),
GM_SYNTH_PAD_1_NEW_AGE("GM_SYNTH_PAD_1_NEW_AGE", 89 - 1, GM_SOUND),
GM_SYNTH_PAD_2_WARM("GM_SYNTH_PAD_2_WARM", 90 - 1, GM_SOUND),
GM_SYNTH_PAD_3_POLYSYNTH("GM_SYNTH_PAD_3_POLYSYNTH", 91 - 1, GM_SOUND),
GM_SYNTH_PAD_4_CHOIR("GM_SYNTH_PAD_4_CHOIR", 92 - 1, GM_SOUND),
GM_SYNTH_PAD_5_BOWED("GM_SYNTH_PAD_5_BOWED", 93 - 1, GM_SOUND),
GM_SYNTH_PAD_6_METALLIC("GM_SYNTH_PAD_6_METALLIC", 94 - 1, GM_SOUND),
GM_SYNTH_PAD_7_HALO("GM_SYNTH_PAD_7_HALO", 95 - 1, GM_SOUND),
GM_SYNTH_PAD_8_SWEEP("GM_SYNTH_PAD_8_SWEEP", 96 - 1, GM_SOUND),
GM_SYNTH_FX_1_RAIN("GM_SYNTH_FX_1_RAIN", 97 - 1, GM_SOUND),
GM_SYNTH_FX_2_SOUNDTRACK("GM_SYNTH_FX_2_SOUNDTRACK", 98 - 1, GM_SOUND),
GM_SYNTH_FX_3_CRYSTAL("GM_SYNTH_FX_3_CRYSTAL", 99 - 1, GM_SOUND),
GM_SYNTH_FX_4_ATMOSPHERE("GM_SYNTH_FX_4_ATMOSPHERE", 100 - 1, GM_SOUND),
GM_SYNTH_FX_5_BRIGHTNESS("GM_SYNTH_FX_5_BRIGHTNESS", 101 - 1, GM_SOUND),
GM_SYNTH_FX_6_GOBLINS("GM_SYNTH_FX_6_GOBLINS", 102 - 1, GM_SOUND),
GM_SYNTH_FX_7_ECHOES("GM_SYNTH_FX_7_ECHOES", 103 - 1, GM_SOUND),
GM_SYNTH_FX_8_SCI_FI("GM_SYNTH_FX_8_SCI_FI", 104 - 1, GM_SOUND),
GM_SITAR("GM_SITAR", 105 - 1, GM_SOUND),
GM_BANJO("GM_BANJO", 106 - 1, GM_SOUND),
GM_SHAMISEN("GM_SHAMISEN", 107 - 1, GM_SOUND),
GM_KOTO("GM_KOTO", 108 - 1, GM_SOUND),
GM_KALIMBA("GM_KALIMBA", 109 - 1, GM_SOUND),
GM_BAG_PIPE("GM_BAG_PIPE", 110 - 1, GM_SOUND),
GM_FIDDLE("GM_FIDDLE", 111 - 1, GM_SOUND),
GM_SHANAI("GM_SHANAI", 112 - 1, GM_SOUND),
GM_TINKLE_BELL("GM_TINKLE_BELL", 113 - 1, GM_SOUND),
GM_AGOGO("GM_AGOGO", 114 - 1, GM_SOUND),
GM_STEEL_DRUMS("GM_STEEL_DRUMS", 115 - 1, GM_SOUND),
GM_WOODBLOCK("GM_WOODBLOCK", 116 - 1, GM_SOUND),
GM_TAIKO_DRUM("GM_TAIKO_DRUM", 117 - 1, GM_SOUND),
GM_MELODIC_TOM("GM_MELODIC_TOM", 118 - 1, GM_SOUND),
GM_SYNTH_DRUM("GM_SYNTH_DRUM", 119 - 1, GM_SOUND),
GM_REVERSE_CYMBAL("GM_REVERSE_CYMBAL", 120 - 1, GM_SOUND),
GM_GUITAR_FRET_NOISE("GM_GUITAR_FRET_NOISE", 121 - 1, GM_SOUND),
GM_BREATH_NOISE("GM_BREATH_NOISE", 122 - 1, GM_SOUND),
GM_SEASHORE("GM_SEASHORE", 123 - 1, GM_SOUND),
GM_BIRD_TWEET("GM_BIRD_TWEET", 124 - 1, GM_SOUND),
GM_TELEPHONE_RING("GM_TELEPHONE_RING", 125 - 1, GM_SOUND),
GM_HELICOPTER("GM_HELICOPTER", 126 - 1, GM_SOUND),
GM_APPLAUSE("GM_APPLAUSE", 127 - 1, GM_SOUND),
GM_GUNSHOT("GM_GUNSHOT", 128 - 1, GM_SOUND);
static {
createLinkedList();
}
private static void createLinkedList() {
System.out.println("hi!");
for (NoteValue noteValue : NoteValue.values()) {
noteValue.above = NoteValueMap.get(noteValue.value + 1);
noteValue.below = NoteValueMap.get(noteValue.value - 1);
}
}
private String simpleNote;
private String noteAndOctave;
private int value;
private NoteValueType type;
private NoteValue above;
private NoteValue below;
private NoteValue(String name, int value, NoteValueType type) {
this(name, name, value, type);
}
private NoteValue(String simpleNote, String noteAndOctave, int value, NoteValueType type) {
this.simpleNote = simpleNote;
this.noteAndOctave = noteAndOctave;
this.value = value;
this.type = type;
NoteValueMap.add(this);
}
public NoteValueType getNoteValueType() {
return type;
}
public String getSimpleNote() {
return simpleNote;
}
public String getNoteAndOctave() {
return noteAndOctave;
}
public int getIntValue() {
return value;
}
public boolean isHigher(NoteValue note) {
return this.value > note.value;
}
public boolean isLower(NoteValue note) {
return this.value < note.value;
}
public static NoteValue forInt(int intValue) {
return NoteValueMap.get(intValue);
}
public static NoteValue randomNoteBetween(NoteValue a, NoteValue b) {
int val = RandyTheRandom.randomIntBetweenExclusive(a.getIntValue(), b.getIntValue());
return NoteValue.forInt(val);
}
public NoteValue halfStepUp() {
return above;
}
public NoteValue halfStepDown() {
return below;
}
public boolean isOctave(NoteValue note) {
int dif = Math.abs(this.value - note.value);
if (dif % Interval.OCTAVE.asInt() == 0) {
return true;
}
return false;
}
}
|
C#
|
UTF-8
| 9,258 | 2.734375 | 3 |
[] |
no_license
|
//Start1.aspx.cs code behind for page start1.aspx.
//Erik Drysén 2015-10-22.
//Revised 2015-11-02 by Erik Drysén.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI.HtmlControls;
using Npgsql;
namespace Uppg_4_Dry_Jos_Star
{
public partial class start1 : System.Web.UI.Page
{
int userId = 2; //To get the user you would like, choose users id here.
protected void Page_Load(object sender, EventArgs e) //Session[username] gets set here
{
if(!IsPostBack)
{
CheckPrivilegeHideNavButton();
UpdateWebsiteGUI();
Session["userName"] = lblUserName.Text;
}
}
/// <summary>
/// Method assumes that that a user has been redirected from a login page
/// calls method GetLoggedinuserinfo to retrieve what privielge user have
/// to see if admin or not. Hides navbar button to get to adminpanel.
/// Should maybe put this in a class togheter with GeLoggedInUserInfo
/// to be able to use it on every page? Good enough for the demo,
/// but will have to be reworked, preferably with a proper nuget or built in
/// system to restrict access to webpages.
/// </summary>
private void CheckPrivilegeHideNavButton()
{
DatabaseConnection dc = new DatabaseConnection();
DataTable dt = dc.GetPersonInfo(userId);
string userType = dt.Rows[0]["privilege"].ToString();
if (userType != "Admin")
{
//Goes through HTML to find buttons to hide.
HtmlAnchor menuButton = (HtmlAnchor)Page.Master.FindControl("adminButton");
HtmlAnchor menuButton1 = (HtmlAnchor)Page.Master.FindControl("a1");
//Hides buttons.
menuButton.Visible = false;
menuButton1.Visible = false;
}
}
/// <summary>
/// Method updates labels on start1.aspx with relevant values.
/// Uses method GetLoggedInUserInfo to retrieve said information,
/// </summary>
private void UpdateWebsiteGUI()
{
DatabaseConnection dc = new DatabaseConnection();
DataTable dt = new DataTable();
DataTable dtAllInfo = new DataTable();
dt = dc.GetPersonInfo(userId);
string userName = dt.Rows[0]["username"].ToString();
lblUserName.Text = userName;
dtAllInfo = dc.GetPersonAndTestInfo(userName);
if (dtAllInfo.Rows.Count <= 0)
{
lblresult.Text = "Inget test hittat";
lbldate.Text = "Inget datum";
lbltestToDo.Text = "1";
lblTestType.Text = "LST";
DateTime today = DateTime.Now;
lblNextTestDate.Text = today.ToString("yyyy-MM-dd");
btnGoToOldTest.Enabled = false;
}
else
{
string passTest = dtAllInfo.Rows[0]["passed"].ToString();
DateTime date = DateTime.Parse(dtAllInfo.Rows[0]["date"].ToString());
lblresult.Text = SetPassOrFail(passTest);
lbltestToDo.Text = CheckDateOfLastTest(date, passTest);
lbldate.Text = date.ToString("yyyy-MM-dd");
lblTestType.Text = SetTypeOfTest();
lblTestTypeDone.Text = dtAllInfo.Rows[0]["testtype"].ToString();
}
}
/// <summary>
/// Method recevis a string, which was a bool in the database
/// and sets a new string value to make it readable for the user
/// so he or she can understand. New value depends on if the value
/// from db is true or false.
/// </summary>
/// <param name="passTest">A value from the database which is True or False</param>
/// <returns>Returns string value to make sense for the user.</returns>
private string SetPassOrFail(string passTest)
{
if (passTest == "False")
{
passTest = "Inte godkänd";
}
else
{
passTest = "Godkänd";
}
return passTest;
}
/// <summary>
/// This method should probably be broken up into smaller methods.
/// Method takes param date and param passTest.
/// Evaluates if passtest is false, if false evaluates timespan is more or less
/// than 7 days to see if user is allowed to retake the test.
/// If passTest is true, evaluates timespan between date of test and date of
/// today. If more than 1year ago user can retake test.
/// </summary>
/// <param name="date">DateTime value from database</param>
/// <param name="passTest">bool/string value from database</param>
/// <returns>Returns new string value</returns>
private string CheckDateOfLastTest(DateTime date, string passTest)
{
string toDoTest = string.Empty;
DateTime today = DateTime.Now;
TimeSpan test = today - date;
int totalDays = test.Days;
int year = 365;
int week = 7;
DateTime nextTestDate;
if(passTest == "False")
{
if(totalDays > week)
{
nextTestDate = date.AddDays(7);
lblNextTestDate.Text = nextTestDate.ToString("yyyy-MM-dd");
toDoTest = "1";
btnStartTest.Enabled = true;
btnGoToOldTest.Enabled = false;
btnGoToOldTest.Style.Add("background", "#66c7f1");
btnGoToOldTest.Style.Add("cursor", "not-allowed");
return toDoTest;
}
else
{
nextTestDate = date.AddDays(7);
lblNextTestDate.Text = nextTestDate.ToString("yyyy-MM-dd");
toDoTest = "1";
btnStartTest.Enabled = false;
btnStartTest.Style.Add("background", "#66c7f1");
btnStartTest.Style.Add("cursor", "not-allowed");
btnGoToOldTest.Enabled = false;
btnGoToOldTest.Style.Add("background", "#66c7f1");
btnGoToOldTest.Style.Add("cursor", "not-allowed");
return toDoTest;
}
}
else
{
if (totalDays > year)
{
nextTestDate = date.AddYears(1);
lblNextTestDate.Text = nextTestDate.ToString("yyyy-MM-dd");
toDoTest = "1";
return toDoTest;
}
else
{
nextTestDate = date.AddYears(1);
lblNextTestDate.Text = nextTestDate.ToString("yyyy-MM-dd");
toDoTest = "0";
btnStartTest.Enabled = false;
btnStartTest.Style.Add("background", "#66c7f1");
btnStartTest.Style.Add("cursor", "not-allowed");
return toDoTest;
}
}
}
/// <summary>
/// Method evaluates what type of test user should do, either ÅKU or LST.
/// </summary>
/// <returns>Returns new string value.</returns>
private string SetTypeOfTest()
{
DatabaseConnection dc = new DatabaseConnection();
string userName = lblUserName.Text;
DataTable dt = dc.GetPersonAndTestInfo(userName);
string typeOfTest = string.Empty;
string passTest = string.Empty;
if (dt.Rows.Count <= 0)
{
typeOfTest = "LST";
return typeOfTest;
}
else
{
typeOfTest = dt.Rows[0]["testtype"].ToString();
passTest = dt.Rows[0]["passed"].ToString();
if (typeOfTest == "LST" && passTest == "False")
{
typeOfTest = "LST";
return typeOfTest;
}
else
{
typeOfTest = "ÅKU";
return typeOfTest;
}
}
}
/// <summary>
/// btnStartTest event click, redirects user to testpage so he or she can
/// start the test. Sends value to testPage with a querystring.
/// </summary>
protected void Button1_Click(object sender, EventArgs e) //Session[typeOfTest] gets set here
{
string typeOfTest = SetTypeOfTest();
Session["typeOfTest"] = typeOfTest;
Response.Redirect("~/testPage.aspx");
}
/// <summary>
/// btnGoToOldTest event click.
/// </summary>
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("~/UserOldTest.aspx");
}
}
}
|
Shell
|
UTF-8
| 406 | 3.078125 | 3 |
[] |
no_license
|
#!/bin/sh
cd /home/pi/openFrameworks/addons/ofxPiMapper/example_bareconductiveFinal/bin/data
INPUT_FILE="presets.xml"
OUTPUT_FILE="presetFinal.xml"
TOKEN1="__PICTURE__.jpg"
TOKEN2="__NAME__.jpg"
length=12
rm -f $OUTPUT_FILE
for i in $( seq 1 $length )
do
echo "Copy calibration value in "$OUTPUT_FILE
sed -- "s/$TOKEN1/image$i.jpg/g" $INPUT_FILE | sed -- "s/$TOKEN2/nom$i.jpg/g" >> $OUTPUT_FILE
done
|
C#
|
UTF-8
| 518 | 2.5625 | 3 |
[] |
no_license
|
using UnityEngine;
using System.Collections;
public class KeyboardPlayer : MonoBehaviour {
float posY = 0;
float speed = 0.7f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (posY + (Input.GetAxis ("Vertical") * speed) <= 3.5 && posY + (Input.GetAxis ("Vertical") * speed) > -3.5) {
posY += (Input.GetAxis ("Vertical") * speed);
}
var pos = new Vector3(8,posY);
if (pos.y < 3.5 && pos.y > -3.5){
transform.position = pos;
}
}
}
|
Markdown
|
UTF-8
| 1,474 | 2.96875 | 3 |
[] |
no_license
|
## Socket编程地址信息结构体
```
struct sockaddr
{
uint16_t sa_family;
char sa_data[14];
}
```
socket编程中比如bind, connect等函数均使用的是该结构体, 不过由于赋值问题, 通常使用的是`sockaddr_in`结构体(进行强制类型转换即可)
```
struct sockaddr_in
{
short sin_family;
uint16_t sin_port;
struct in_addr sin_addr;
char sin_zero[8];
}
```
在windows中和linux中`in_addr`结构体具有一定的差别
### Windows
```
struct in_addr
{
union
{
struct
{
uint8_t s_b1, s_b2, s_b3, s_b4;
}S_un_b;
struct
{
uint16_t s_w1, s_w2;
}
uint32_t S_addr;
}S_un;
}
```
### Linux
```
struct in_addr
{
unsigned long s_addr;
}
```
### `in_addr`赋值函数
在很久以前存在一些如`inet_addr`, `inet_ntoa()`函数, 但是由于不支持IPV6的原因, 不应该使用
```
int inet_pton(int af, const char *src, void *dst); //将点分十进制转换为二进制整数
const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt);
```
第一个参数`af`指明类型,能够处理ipv4和ipv6; 第二个参数`src`为ip字符串, 第三个参数`dst`为in_addr或者in6_addr结构体
第二个函数, 参数与第一个相同, 多了一个socklen_t指明缓冲区dst大小, 避免溢出
相关头文件:
windows
`#include <WS2tcpip.h>`
linux
```
#include <sys/socket.h>
#include <netinet/in.h>
#include<arpa/inet.h>
```
|
Java
|
UTF-8
| 1,077 | 2.34375 | 2 |
[] |
no_license
|
package com.netcracker.odstc.logviewer.service;
import com.netcracker.odstc.logviewer.models.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
@Service
public class MailService {
@Value("${spring.mail.username}")
private String mailFrom;
public SimpleMailMessage constructResetTokenEmail(
String contextPath, String token, User user) {
String url = contextPath + "#/changePassword/" +
user.getObjectId() + "/" + token;
String message = "message.resetPassword";
return constructEmail("Reset Password", message + " \r\n" + url, user);
}
private SimpleMailMessage constructEmail(String subject, String body,
User user) {
SimpleMailMessage email = new SimpleMailMessage();
email.setSubject(subject);
email.setText(body);
email.setTo(user.getEmail());
email.setFrom(mailFrom);
return email;
}
}
|
PHP
|
UTF-8
| 954 | 2.734375 | 3 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
<?php
namespace Softonic\LaravelIntelligentScraper\Scraper\Models;
use Illuminate\Database\Eloquent\Model;
class Configuration extends Model
{
/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = false;
/**
* The attributes that should be cast to native types.
*
* @var array
*/
public $casts = ['xpaths' => 'json'];
/**
* The primary key for the model.
*
* @var string
*/
protected $primaryKey = 'name';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'type',
'xpaths',
];
public function getXpathsAttribute($xpaths): array
{
return (array) $this->castAttribute('xpaths', $xpaths);
}
public function scopeWithType($query, string $type)
{
return $query->where('type', $type);
}
}
|
Java
|
UTF-8
| 2,198 | 2.109375 | 2 |
[] |
no_license
|
package com.benz.user.model;
import java.util.Date;
public class UserResponse {
private int userId;
private String fname;
private String lname;
private String uniqueId;
private String district;
private String email;
private String pnum;
private String uPassword;
private Date created_date;
private Date modifiedDate;
private String userType;
private boolean isLogged;
private String errorMsg;
private String successMsg;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getUniqueId() {
return uniqueId;
}
public void setUniqueId(String uniqueId) {
this.uniqueId = uniqueId;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPnum() {
return pnum;
}
public void setPnum(String pnum) {
this.pnum = pnum;
}
public String getuPassword() {
return uPassword;
}
public void setuPassword(String uPassword) {
this.uPassword = uPassword;
}
public Date getCreated_date() {
return created_date;
}
public void setCreated_date(Date created_date) {
this.created_date = created_date;
}
public Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public boolean isLogged() {
return isLogged;
}
public void setLogged(boolean isLogged) {
this.isLogged = isLogged;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public String getSuccessMsg() {
return successMsg;
}
public void setSuccessMsg(String successMsg) {
this.successMsg = successMsg;
}
}
|
Java
|
UTF-8
| 814 | 1.914063 | 2 |
[
"MIT"
] |
permissive
|
package io.github.donggi.mvc.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@ComponentScan(basePackages = "io.github.donggi.mvc.aop, io.github.donggi.mvc.controller, io.github.donggi.mvc.service")
@EnableWebMvc
@Configuration
public class AppConfig implements WebMvcConfigurer {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.mediaType("xxx", MediaType.APPLICATION_JSON);
}
}
|
TypeScript
|
UTF-8
| 1,412 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
import { InputType } from "@nestjs/graphql";
import { StringComparisonInput } from "../../../gql/string-comparison.input";
import { NumberComparisonInput } from "../../../gql/number-comparison.input";
import { DateComparisonInput } from "../../../gql/date-comparison.input";
/**
* Input type for filtering Productions in ReadMany queries.
*/
@InputType()
export class FilterProductionInput {
/**
* Filter by ID
*/
id?: NumberComparisonInput;
/**
* Filter by name
*/
name?: StringComparisonInput;
/**
* Filter by description
*/
description?: StringComparisonInput;
/**
* Filter by start time
*/
startTime?: DateComparisonInput;
/**
* Filter by end time
*/
endTime?: DateComparisonInput;
/**
* Filter by category ID
*/
categoryId?: NumberComparisonInput;
/**
* Filter by closet location
*/
closetLocation?: StringComparisonInput;
/**
* Filter by closet time
*/
closetTime?: DateComparisonInput;
/**
* Filter by event location
*/
eventLocation?: StringComparisonInput;
/**
* Filter by team notes
*/
teamNotes?: StringComparisonInput;
/**
* Filter by thumbnail Image ID
*/
thumbnailId?: NumberComparisonInput;
AND?: FilterProductionInput[];
OR?: FilterProductionInput[];
NOT?: FilterProductionInput;
}
|
Java
|
UTF-8
| 344 | 1.59375 | 2 |
[] |
no_license
|
package com.Satish.Satish_firstspring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SatishFirstspringApplication {
public static void main(String[] args) {
SpringApplication.run(SatishFirstspringApplication.class, args);
}
}
|
Python
|
UTF-8
| 5,127 | 2.734375 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
# test_mailroom4.py - Lesson06 - Assignment 5 - Unittesting with Pytest
from mailroom4 import *
import sys
from mock import patch
from io import StringIO
import pathlib
import os
import pytest
# Data to check against
expected_report = 'Donor Name | Total Given| Num Gifts| Average Gift\
\n------------------------------------------------------------------------\
\nRichie Rich $ 1500000.00 2 $ 750000.00\
\nScrooge McDuck $ 78000.00 2 $ 39000.00\
\nChet Worthington $ 54787.63 3 $ 18262.54\
\nMontgomery Burns $ 49.53 1 $ 49.53\
\nSilas Skinflint $ 1.68 3 $ 0.56'
expected_write_letter = '\nDear Montgomery Burns,\n\n Thank you\
for your very kind donations totaling $49.53.\n\n It will be put\
to very good use.\n\n Sincerely,\n - The team'
monty_name = "Montgomery Burns"
monty_value = [49.53]
thanks_newberry = 'Dear John Newberry\nThank you for your generous donation of 5.00'
thanks_silas = 'Dear Silas Skinflint\nThank you for your generous donation of 500.00'
newberry_db = {"Scrooge McDuck": [8000.00, 70000.00],
"Montgomery Burns": [49.53],
"Richie Rich": [1000000.00, 500000.00],
"Chet Worthington": [200.00, 44387.63, 10200.00],
"Silas Skinflint": [0.25, 1.00, 0.43],
"John Newberry": [5.00]}
filelist = ['Montgomery_Burns.txt', 'Richie_Rich.txt', 'Chet_Worthington.txt',
'Silas_Skinflint.txt', 'Scrooge_McDuck.txt']
newberry_addition = {"John Newberry": [5.00]}
invalid_selection = '----> Invalid Selection: Please input a number 1-4'
invalid_amount = '--->Not a valid amount, please try your submission again'
# TEST exit_program():
def test_exit():
with patch('sys.exit') as exit_mock:
exit_program()
assert exit_mock.called is True
# TEST list_invoked():
def test_list_invoked_notlist():
assert list_invoked('cat') == 'cat'
def test_list_invoked_list():
with patch('mailroom4.report') as report_mock:
list_invoked('list')
assert report_mock.called is True
# TEST amt_logic():
def test_valid_amt():
with patch('mailroom4.ty_logic') as tylogic_mock:
amt_logic('name', 43)
assert tylogic_mock.called is True
def test_invalid_amt():
with patch('sys.stdout', new=StringIO()) as fake_output:
amt_logic('name', 'blah')
assert fake_output.getvalue().strip() == invalid_amount
# TEST main_switch()
def test_switch_bad1():
with patch('sys.stdout', new=StringIO()) as fake_output2:
main_switch('dog')
assert fake_output2.getvalue().strip() == invalid_selection
def test_switch_bad2():
with patch('sys.stdout', new=StringIO()) as fake_output3:
main_switch(5)
assert fake_output3.getvalue().strip() == invalid_selection
# TEST report()
def test_report():
with patch('sys.stdout', new=StringIO()) as fake_output4:
report()
assert fake_output4.getvalue().strip() == expected_report
# TEST write_letter():
def test_write_letter():
form_letter = write_letter(monty_name, monty_value)
assert form_letter == expected_write_letter
# TEST ty_logic():
def test_thankyou_main():
with patch('mailroom4.input', return_value='4') as tyinput_mock, \
patch('mailroom4.list_invoked') as listmock, \
patch('mailroom4.amt_logic') as amtlogicmock:
thank_you()
assert tyinput_mock.called is True
assert listmock.called is True
assert amtlogicmock.called is True
assert tyinput_mock.call_count == 2
def test_ty_logic_new():
with patch('sys.stdout', new=StringIO()) as ty_output:
ty_logic('John Newberry', 5.00)
assert ty_output.getvalue().strip() == thanks_newberry
assert donor_db['John Newberry'] == [5.0]
del donor_db['John Newberry']
# TEST report()
def test_report2():
'''In order to check that test_ty_logic_new() was reset'''
with patch('sys.stdout', new=StringIO()) as fake_output4:
report()
assert fake_output4.getvalue().strip() == expected_report
def test_ty_logic_update():
with patch('sys.stdout', new=StringIO()) as ty_output2:
ty_logic('Silas Skinflint', 500.00)
assert ty_output2.getvalue().strip() == thanks_silas
assert donor_db['Silas Skinflint'] == [0.25, 1.00, 0.43, 500.00]
donor_db['Silas Skinflint'].pop(3)
def test_report3():
'''In order to check that test_ty_logic_update() was reset'''
with patch('sys.stdout', new=StringIO()) as fake_output4:
report()
assert fake_output4.getvalue().strip() == expected_report
# TEST create_text_file():
def test_file_creation():
create_text_file('File Flisby', [400.00, 800.00, 1200.00])
testpth = pathlib.Path('./')
testdest = testpth.absolute() / 'File_Flisby.txt'
assert os.path.isfile(testdest) is True
def test_send_letter():
send_letter()
testpth = pathlib.Path('./')
for filesel in filelist:
testdest = testpth.absolute() / filesel
assert os.path.isfile(testdest) is True
|
Java
|
UTF-8
| 272 | 1.632813 | 2 |
[] |
no_license
|
package com.graduation.mode;
import lombok.Data;
@Data
public class Loginer {
/**
* 用户账号
*/
private String id;
/**
* 用户密码
*/
private String password;
/**
* 用户密角色
*/
private String type;
}
|
Markdown
|
UTF-8
| 1,233 | 2.78125 | 3 |
[] |
no_license
|
# Modern Rhetoric - an NLP approach
Project for Math/English 190S - Democracy, Game Theory, and Persuasion - at Duke University
## What did we do?
We used Aristotle's modes of persuasion and sentiment analysis within Tweets related to current politics in the United States to understand the use of rhetoric in a modern context.
Two sets of Tweets were analyzed for subjectivity and polarized language:
* Tweets published by Trump on his personal account and
* Tweets published by the general population about the Florida Midterm Elections.
## What did we find?
* We demonstrated the use of computer algorithms in natural language processing as effective in measuring elements of rhetoric.
* We quantified the high levels of rhetoric in modern politics by pairing it with Aristotle’s modes of persuasion.
* We witnessed high levels of usage of pathos and ethos via emotional polarization and subjectivity to manipulate and convince voters.
Our complete analysis, along with all figures, can be found here: [bit.ly/TwitterRhetoric](https://bit.ly/TwitterRhetoric)
## Built Using
* Python 3
* TextBlob - NLP Toolkit used for Sentiment Analysis
### Prerequisites
Import TextBlob library:
```
pip install -U textblob
```
|
PHP
|
UTF-8
| 4,540 | 3.4375 | 3 |
[] |
no_license
|
<?php
namespace App\Classes;
use App\Exceptions\InstructionParseException;
/**
* Class InstructionHandler
* @package App\Classes
*/
class InstructionHandler
{
private $output;
private $dataMatrix;
/**
* InstructionHandler constructor.
*/
public function __construct()
{
$this->output = array();
$this->dataMatrix = new DataMatrix();
}
/**
* @return array
*/
public function getOutputAsArray()
{
return $this->output;
}
/**
* @return string
*/
public function getOutputAsString()
{
return implode(PHP_EOL, $this->output);
}
/**
* Process an input string
*
* @param $instructions
*/
public Function processInput($instructions)
{
$lines = $this->getLines($instructions);
$lineNumber = 1;
$numberOfTestCases = $this->getNumberOfTestCases(array_shift($lines), $lineNumber++);
while ($numberOfTestCases > 0) {
$numberOfInstructions =
$this->getSizeAndNumberOfInstructions(array_shift($lines),
$lineNumber++);
while ($numberOfInstructions > 0) {
$this->processInstruction(array_shift($lines),
$lineNumber++);
$numberOfInstructions--;
}
$numberOfTestCases--;
}
}
/**
* Split the input string into a list of lines
*
* @param $input
* @return array
*/
protected function getLines($input)
{
return preg_split("/\r\n|\n|\r/", trim($input));
}
/**
* Get the number of test cases to be executed
*
* @param $line
* @param $lineNumber
* @return int
*/
protected function getNumberOfTestCases($line, $lineNumber)
{
if ($line == null || $line === "") {
throw new InstructionParseException($lineNumber);
}
$numberOfTestCases = 0;
if (sscanf($line, "%d", $numberOfTestCases) !== 1) {
throw new InstructionParseException($lineNumber);
}
return $numberOfTestCases;
}
/**
* Get the size of the matrix and number of instructions to read
*
* @param $line
* @param $lineNumber
* @return int
* @internal param DataMatrix $dataMatrix
*/
protected function getSizeAndNumberOfInstructions($line, $lineNumber)
{
if ($line == null || $line === "") {
throw new InstructionParseException($lineNumber);
}
$size = 0;
$numberOfInstructions = 0;
if (sscanf($line, "%d %d", $size, $numberOfInstructions) !== 2) {
throw new InstructionParseException($lineNumber);
}
$this->dataMatrix->create($size);
return $numberOfInstructions;
}
/**
* Process instruction lines
*
* @param $line
* @param $lineNumber
* @return int|null
* @internal param $output
* @internal param DataMatrix $dataMatrix
*/
protected function processInstruction($line, $lineNumber)
{
if (str_contains($line, 'UPDATE')) {
$this->processUpdate($line, $lineNumber);
} else if (str_contains($line, 'QUERY')) {
$this->output[] = $this->processQuery($line, $lineNumber);
} else {
throw new InstructionParseException($lineNumber);
}
}
/**
* Process update instructions
*
* @param $line
* @param $lineNumber
* @internal param DataMatrix $dataMatrix
*/
protected function processUpdate($line, $lineNumber)
{
$x = 0;
$y = 0;
$z = 0;
$value = 0;
if (sscanf($line, "UPDATE %d %d %d %d", $x, $y, $z, $value) !== 4) {
throw new InstructionParseException($lineNumber);
}
$this->dataMatrix->update($x, $y, $z, $value, $lineNumber);
}
/**
* Process query instructions
*
* @param $line
* @param $lineNumber
* @return int
* @internal param DataMatrix $dataMatrix
*/
protected function processQuery($line, $lineNumber)
{
$x1 = 0;
$y1 = 0;
$z1 = 0;
$x2 = 0;
$y2 = 0;
$z2 = 0;
if (sscanf($line, "QUERY %d %d %d %d %d %d", $x1, $y1, $z1, $x2, $y2, $z2) !== 6) {
throw new InstructionParseException($lineNumber);
}
return $this->dataMatrix->query($x1, $y1, $z1, $x2, $y2, $z2, $lineNumber);
}
}
|
Markdown
|
UTF-8
| 7,452 | 3.34375 | 3 |
[] |
no_license
|
# MySQL日志
在任何一种数据库中,都会有各种各样的日志,记录着数据库工作的方方面面,以帮助数据库管理员追踪数据库曾经发生过的各种事件
MySQL 也不例外,在 MySQL 中,有 4 种不同的日志,分别是错误日志、二进制日志(BINLOG 日志)、查询日志和慢查询日志,这些日志记录着数据库在不同方面的踪迹。
## 错误日志
错误日志是 MySQL 中最重要的日志之一,它记录了当 mysqld 启动和停止时,以及服务器在运行过程中发生任何严重错误时的相关信息。当数据库出现任何故障导致无法正常使用时,可以首先查看此日志
该日志是默认开启的 , 默认存放目录为 mysql 的数据目录(`var/lib/mysql`), 默认的日志文件名为 `hostname.err`(hostname是主机名)
查看日志位置指令 :
```mysql
show variables like 'log_error%';
+---------------------+------------------------------------------------------+
| Variable_name | Value |
+---------------------+------------------------------------------------------+
| log_error | /var/lib/mysql/xaxh-server.err |
| log_error_verbosity | 3 |
+---------------------+------------------------------------------------------+
```
查看日志内容 :
```shell
tail -f /var/lib/mysql/xaxh-server.err
```
## 二进制日志(BINLOG)重要
### 概述
二进制日志(BINLOG)记录了所有的 DDL(数据定义语言)语句和 DML(数据操纵语言)语句,但是 <font color=red>不包括数据查询语句</font>。<font color=blue>此日志对于灾难时的数据恢复起着极其重要的作用,**MySQL的主从复制, 就是通过 binlog实现的**</font>
二进制日志,**默认情况下是没有开启的**,需要到MySQL的配置文件中开启,并配置MySQL日志的格式
- 配置文件位置 : `/usr/my.cnf`
- 日志存放位置 :
- 配置时,给定了文件名但是没有指定路径,日志默认写入 MySQL 的数据目录
- 日志的文件前缀为 mysqlbin;生成的文件名如 : `mysqlbin.000001,mysqlbin.000002`
```nginx
# 配置开启binlog日志
log_bin=mysqlbin
# 配置二进制日志的格式
binlog_format=STATEMENT
#binlog_format=ROW
#binlog_format=MIXED
```
### 日志格式
#### **STATEMENT**
该日志格式在日志文件中<font color=red>**记录的都是SQL语句**</font>(statement),每一条对数据进行修改的SQL都会记录在日志文件中,通过 MySQL 提供的 mysqlbinlog 工具,可以清晰的查看到每条语句的文本
主从复制的时候,从库(slave)会将日志解析为原文本,并在从库重新执行一次
#### **ROW**
该日志格式在日志文件中记录的是每一行的数据变更,而不是记录SQL语句
比如,执行SQL语句 : `update t_book set status='1'`
- 如果是 STATEMENT 日志格式,在日志中只会记录这一条SQL语句
- 如果是ROW,由于是对全表进行更新,也就是每一行记录都会发生变更,ROW 格式的日志中会**记录每一行的数据变更**
#### **MIXED**(默认格式)
这是目前 MySQL **默认的日志格式**,即混合了STATEMENT 和 ROW两种格式。
默认情况下采用STATEMENT,但是在一些特殊情况下采用ROW来进行记录。MIXED 格式能尽量利用两种模式的优点,而避开他们的缺点
### 日志读取
由于日志以二进制方式存储,不能直接读取,需要用 mysqlbinlog 工具来查看,语法如下 :
```shell
mysqlbinlog log-file;
```
**查看STATEMENT格式日志**
1. 执行插入语句
```mysql
insert into tb_book values(null,'Lucene','2088-05-01','0');
```
2. 查看日志文件
- mysqlbin.index:该文件是日志索引文件,记录日志的文件名
- mysqlbing.000001 :日志文件
3. 查看日志内容
```shell
mysqlbinlog mysqlbing.000001;
```
**查看ROW格式日志**
1. 插入数据
```mysql
insert into tb_book values(null,'SpringCloud实战','2088-05-05','0');
```
2. 如果日志格式是 ROW , 直接查看数据 , 是看不懂的;可以在 mysqlbinlog 后面加上参数 -vv
```shell
mysqlbinlog -vv mysqlbin.000002;
```
### 日志删除
对于比较繁忙的系统,由于每天生成日志量大 ,这些日志如果长时间不清楚,将会占用大量的磁盘空间。下面我们将会讲解几种删除日志的常见方法
**方式一**
通过 `Reset Master` 指令删除全部 binlog 日志,删除之后,日志编号,将从 xxxx.000001重新开始
```shell
Reset Master
```
**方式二**
```shell
purge master logs to 'mysqlbin.******'
```
该命令将删除 ``` ******``` 编号之前的所有日志
**方式三**
```mysql
purge master logs before 'yyyy-mm-dd hh24:mi:ss'
```
该命令将删除日志为 "yyyy-mm-dd hh24:mi:ss" 之前产生的所有日志
**方式四**
设置参数 `--expire_logs_days=#` ,此参数的含义是设置日志的过期天数, 过了指定的天数后日志将会被自动删除,这样将有利于减少DBA 管理日志的工作量
配置如下 :
```nginx
# 配置开启binlog日志
log_bin=mysqlbin
# 配置二进制日志的格式
binlog_format=STATEMENT
#配置二进制日志过期时间
--expire_logs_days=8
```
## 查询日志
查询日志中记录了客户端的所有操作语句,而二进制日志不包含查询数据的SQL语句
默认情况下, 查询日志是未开启的
如果需要开启查询日志,需要在 `/usr/my.cnf` 加上以下配置 :
```nginx
#该选项用来开启查询日志: 0 代表关闭, 1 代表开启
general_log=1
#设置日志的文件名,如果没有指定, 默认的文件名为 host_name.log
general_log_file=file_name
```
## 慢查询日志
慢查询日志记录了所有<font color=red>**执行时间超过参数 `long_query_time` 设置值**</font>并且<font color=blue>**扫描记录数不小于 `min_examined_row_limit`** </font>的所有的SQL语句的日志
`long_query_time` 默认为 10 秒,最小为 0, 精度可以到微秒
### 文件位置和格式
慢查询日志默认是关闭的
可以通过两个参数来控制慢查询日志 `/usr/my.cnf` :
```nginx
# 该参数用来控制慢查询日志是否开启, 1 代表开启,0 代表关闭
slow_query_log=1
# 该参数用来指定慢查询日志的文件名
slow_query_log_file=slow_query.log
# 该选项用来配置查询的时间限制
# 超过这个时间将认为是慢查询,将需要进行日志记录,默认10s
long_query_time=10
```
### 日志的读取
和错误日志、查询日志一样,慢查询日志记录的格式也是纯文本,可以被直接读取
1) 查询 `long_query_time` 的值
```mysql
mysql> show variables like 'long_query_time';
```
2) 查看慢查询日志文件
直接通过cat 指令查询该日志文件 :
```shell
cat slow_query.log;
```
如果慢查询日志内容很多, 直接查看文件,比较麻烦, 这个时候可以借助于mysql自带的 mysqldumpslow 工具, 来对慢查询日志进行分类汇总
```shell
mysqldumpslow slow_query.log;
```
|
Markdown
|
UTF-8
| 4,011 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
# Google Cloud Storage
## Using the Storage API
### Setting up StorageConfiguration
To make GoogleCloudKit as flexible as possible to work with different API's and projects,
you can configure each API with their own configuration if the default `GoogleCloudCredentialsConfiguration` doesn't satisfy your needs.
For example the `GoogleCloudCredentialsConfiguration` can be configured with a `ProjectID`, but you might
want to use this specific API with a different project than other APIs. Additionally every API has their own scope and you might want to configure.
To use the CloudStorage API you can create a `GoogleCloudStorageConfiguration` in one of 2 ways.
```swift
let credentialsConfiguration = GoogleCloudCredentialsConfiguration(project: "my-project-1",
credentialsFile: "/path/to/service-account.json")
let cloudStorageConfiguration = GoogleCloudStorageConfiguration(scope: [.fullControl, .cloudPlatformReadOnly],
serviceAccount: "default",
project: "my-project-2")
// OR
let cloudStorageConfiguration = GoogleCloudStorageConfig.default()
// has full control access and uses default service account with no project specified.
```
### Now create a `GoogleCloudStorageClient` with the configuration and an `HTTPClient`
```swift
let let client = HTTPClient(...)
let gcs = try GoogleCloudStorageClient(credentials: credentialsConfiguration,
storageConfiguration: cloudStorageConfiguration,
httpClient: client,
eventLoop: myEventLoop)
```
The order of priority for which configured projectID the StorageClient will use is as follows:
1. `$GOOGLE_PROJECT_ID` environment variable.
1. `$PROJECT_ID` environment variable.
2. The Service Accounts projectID (Service account configured via the credentials path in the credentials configuration).
3. `GoogleCloudStorageConfiguration`'s `project` property.
4. `GoogleCloudCredentialsConfiguration`'s `project` property.
Initializing the client will throw an error if no projectID is set anywhere.
### Creating a storage bucket
```swift
func createBucket() {
let gcs = try GoogleCloudStorageClient(credentials: credentialsConfiguration,
storageConfiguration: cloudStorageConfiguration,
httpClient: client,
eventLoop: myEventLoop)
gcs.buckets.insert(name: "nio-cloud-storage-demo").flatMap { newBucket in
print(newBucket.selfLink) // prints "https://www.googleapis.com/storage/v1/b/nio-cloud-storage-demo"
}
}
```
### Uploading an object to cloud storage
```swift
func uploadImage(data: Data) {
let gcs = try GoogleCloudStorageClient(credentials: credentialsConfiguration,
storageConfiguration: cloudStorageConfiguration,
httpClient: client,
eventLoop: myEventLoop)
gcs.object.createSimpleUpload(bucket: "nio-cloud-storage-demo",
data: data,
name: "SwiftBird",
contentType: "image/jpeg").flatMap { uploadedObject in
print(uploadedObject.mediaLink) // prints the download link for the image.
}
}
```
There are other API's available which are well [documented](https://cloud.google.com/storage/docs/json_api/v1/).
This is just a basic example of creating a bucket and uploading an object.
### What's implemented
* [x] BucketAccessControls
* [x] Buckets
* [x] Channels
* [x] DefaultObjectAccessControls
* [x] Notifications
* [x] ObjectAccessControls
* [x] Simple Object upload
* [ ] Multipart Object upload
* [ ] Resumable Object upload
|
Markdown
|
UTF-8
| 2,541 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
---
title: The Business Plan
description: A business plan outline
slug: business-plan
date: 2015-09-02
---
I am currently enrolled in the California Program for Entrepreneurs, and we recently discussed business plans and models. I figured I would share the business plan outline we received, and also digitize it for myself, since we received a hard copy. As I write my own, I will go through and share my thoughts on how each section should be structured and what key points should be made in each section
---
1. **Industry, the Company, and its Products**
+ Overview
+ The Company
+ The Company’s Products
+ The Industry
+ Critical Success Factor
+ Structural Analysis of the Industry
+ Description of Industry Evolution
2. **Market Research & Analysis**
+ Customer Segments, Buyer Decision Making Issues
+ Target Market(s) Size and Trends
+ Competition
+ Estimate Market Share & Sales
+ Ongoing Market Evaluation
3. **Marketing Plan**
+ Overall Marketing Strategy
+ Target Market Definition
+ Market Positioning (Price vs. Quality)
+ Competitive Advantage
+ Pricing (Economic Value to Customer)
+ Channel Plan
+ Marketing Communications Plan
+ Sales Plan to generate first six months of sales
+ Service & Warranty Policies
+ Advertising & Promotion Plans
+ Marketing Budget
4. **Design & Development Status**
+ Development Status & Tasks
+ Difficulties & Risks
+ Product Improvement & New Products
+ Cost Management Plan
5. **Operations Plan**
+ Geographical Location
+ Facilities & Improvement
+ Strategy & Plans
6. **Management Team**
+ Organization
+ Key Management Personnel
+ Management Compensation & Ownership
+ Board of Directors
+ Supporting Professional Services
7. **Critical Risks & Problems**
8. **The Financial Plan**
+ Profit & Loss Forecasts
+ Pro Forma Cash Flow Analysis
+ Pro Forma Balance Sheets
+ Break Even Analysis
9. **Proposed Company Offering**
+ Desired Financing
+ Securities Offering
+ Capitalization
+ Use of Funds
**Exhibit 1:** Pro Forma Income Statements (monthly for first year; annual for first 5 years)
**Exhibit 2:** Pro Forma Cash Flows (monthly for first year; quarterly for 2 years)
**Exhibit 3:** Pro Forma Balance Sheets (for startup & for end of year for first 3 years)
**Exhibit 4:** Break Even Analysis
**Exhibit 5:** Critical Success Factors
**Exhibit 6:** Structural Analysis of Industry
|
Python
|
UTF-8
| 1,994 | 3.96875 | 4 |
[] |
no_license
|
#define the question class
class Question:
#set class attributes
def __init__(self,question,answer1,answer2,answer3,answer4,correctAnswer):
self.__question = question
self.__answer1 = answer1
self.__answer2 = answer2
self.__answer3 = answer3
self.__answer4 = answer4
self.__correctAnswer = correctAnswer
#set mutators and accessors
def setQuestion(self, question):
self.__question = question
def setAnswer1(self, answer1):
self.__answer1 = answer1
def setAnswer2(self, answer2):
self.__answer2 = answer2
def setAnswer3(self, answer3):
self.__answer3 = answer3
def setAnswer4(self, answer4):
self.__answer4 = answer4
def setCorrectAnswer(self, correctAnswer):
self.__correctAnswer = correctAnswer
def getQuestion(self):
return self.__question
def getAnswer1(self):
return self.__answer1
def getAnswer2(self):
return self.__answer2
def getAnswer3(self):
return self.__answer3
def getAnswer4(self):
return self.__answer4
def getCorrectAnswer(self):
return self.__correctAnswer
triviaQuestions = open("trivia-questions.txt", "r")
qList = []
answers = [1,3,3,4,3,3,3,2,1,2]
for line in triviaQuestions:
qList.append(line.rstrip("\n"))
triviaQuestions.close()
question1 = Question(qList[0],qList[1],qList[2],qList[3],qList[4],answers[0])
question2 = Question(qList[5],qList[6],qList[7],qList[8],qList[9],answers[1])
question2 = Question(qList[10],qList[11],qList[12],qList[13],qList[14],answers[2])
question3 = Question(qList[15],qList[16],qList[17],qList[17],qList[18],answers[3])
numQuestions = 4
while numQuestions != 0:
if numQuestions % 2 == 0:
print("Player 1's turn: ")
else:
print("Player 2's turn: ")
numQuestions -= 1
#https://www.slader.com/textbook/9780134444321-starting-out-with-python-4th-edition/549/programming-exercises/9/
|
PHP
|
UTF-8
| 2,810 | 2.78125 | 3 |
[] |
no_license
|
<?php
namespace Pipa\Data;
/**
* Provides a way to add functionality on top of a DataSource-specific
* Criteria implementation without losing low-level functionality
*/
class CriteriaDecorator extends Criteria {
protected $criteria;
protected static $passthough = array(
'collection', 'dataSource', 'distinct', 'expressions',
'fields', 'index', 'limit', 'order'
);
function __construct(Criteria $criteria) {
$this->criteria = $criteria;
foreach(self::$passthough as $property) {
unset($this->$property);
}
}
function __clone() {
$this->criteria = clone $this->criteria;
}
function __get($property) {
if (in_array($property, self::$passthough)) {
return $this->criteria->$property;
}
}
function __set($property, $value) {
if (in_array($property, self::$passthough)) {
$this->criteria->$property = $value;
} else {
$this->$property = $value;
}
}
function getCriteria() {
return $this->criteria;
}
function add(Criterion $criterion) {
$this->criteria->add($criterion);
return $this;
}
function addAll($_ = null) {
foreach(\Pipa\array_flatten(func_get_args()) as $arg)
$this->add($arg);
return $this;
}
function aggregate(Aggregate $aggregate) {
return $this->criteria->aggregate($aggregate);
}
function count() {
return $this->criteria->count();
}
function delete() {
return $this->criteria->delete();
}
function distinct($fields) {
$this->criteria->distinct($fields);
return $this;
}
function eq($a, $b) {
$this->criteria->eq($a, $b);
return $this;
}
function fields($fields) {
$this->criteria->fields($fields);
return $this;
}
function from($collection) {
$this->criteria->from($collection);
return $this;
}
function indexBy($field) {
$this->criteria->indexBy($field);
return $this;
}
function limit(Limit $limit) {
$this->criteria->limit($limit);
return $this;
}
function order(Order $order) {
$this->criteria->order($order);
return $this;
}
function orderBy($field, $type = Order::TYPE_ASC) {
$this->criteria->orderBy($field, $type);
return $this;
}
function page($page, $size) {
$this->criteria->page($page, $size);
return $this;
}
function pageCount($size) {
return $this->criteria->pageCount($size);
}
function n($n) {
$this->criteria->n($n);
return $this;
}
function queryAll() {
return $this->criteria->queryAll();
}
function queryField($field = null) {
return $this->criteria->queryField($field);
}
function querySingle() {
return $this->criteria->querySingle();
}
function queryValue() {
return $this->criteria->queryValue();
}
function update(array $values) {
return $this->criteria->update($values);
}
function where(Expression $expression) {
$this->criteria->where($expression);
return $this;
}
}
|
Java
|
UTF-8
| 4,311 | 2.390625 | 2 |
[
"MIT"
] |
permissive
|
package org.dnstv.botcontroller;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
/**
* Created by paulv on 8/21/2017.
*/
public class Pair extends AppCompatActivity implements View.OnClickListener {
//private final String DEVICE_ADDRESS = "20:16:06:13:21:89"; //TEST MAC Address of Bluetooth Module
private final String DEVICE_ADDRESS = "20:16:12:05:66:82"; //MAC Address of Bluetooth Module
private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
private BluetoothDevice device;
private BluetoothSocket socket;
private OutputStream outputStream;
private InputStream inputStream;
boolean connected = false;
Button connect;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pair);
connect = (Button) findViewById(R.id.btnConnect);
connect.setOnClickListener(this);
//Initializes bluetooth module
}
@Override
public void onClick(View v) {
if(v.getId()==R.id.btnConnect)
{
if(BTinit()){
if(BTconnect()) {
DataHolder.getInstance().setData(outputStream);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
}else{
Toast.makeText(this, "Connect to the device first.", Toast.LENGTH_SHORT).show();
}
}
}
public boolean BTinit() {
boolean found = false;
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) //Checks if the device supports bluetooth
{
Toast.makeText(this, "Device doesn't support bluetooth", Toast.LENGTH_SHORT).show();
}
if (!bluetoothAdapter.isEnabled()) //Checks if bluetooth is enabled. If not, the program will ask permission from the user to enable it
{
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
if (bondedDevices.isEmpty()) //Checks for paired bluetooth devices
{
Toast.makeText(this, "Please pair the device first", Toast.LENGTH_SHORT).show();
} else {
for (BluetoothDevice iterator : bondedDevices) {
if (iterator.getAddress().equals(DEVICE_ADDRESS)) {
device = iterator;
found = true;
break;
}
}
}
return found;
}
public boolean BTconnect() {
try {
socket = device.createRfcommSocketToServiceRecord(PORT_UUID); //Creates a socket to handle the outgoing connection
socket.connect();
Toast.makeText(this, "Connection to bluetooth device successful", Toast.LENGTH_LONG).show();
connected = true;
} catch (IOException e) {
e.printStackTrace();
connected = false;
}
if (connected) {
try {
outputStream = socket.getOutputStream(); //gets the output stream of the socket
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream = socket.getInputStream(); //gets the input stream of the socket
} catch (IOException e) {
e.printStackTrace();
}
}
return connected;
}
}
|
Swift
|
UTF-8
| 923 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
import ArgumentParser
import Foundation
import TSCBasic
import TuistSupport
struct CloudOrganizationInviteCommand: AsyncParsableCommand {
static var configuration: CommandConfiguration {
CommandConfiguration(
commandName: "invite",
_superCommandName: "organization",
abstract: "Invite a new member to your organization."
)
}
@Argument(
help: "The name of the organization to invite the user to."
)
var organizationName: String
@Argument(
help: "The email of the user to invite."
)
var email: String
@Option(
name: .long,
help: "URL to the cloud server."
)
var serverURL: String?
func run() async throws {
try await CloudOrganizationInviteService().run(
organizationName: organizationName,
email: email,
serverURL: serverURL
)
}
}
|
Java
|
UTF-8
| 414 | 2.046875 | 2 |
[] |
no_license
|
package tk.fishfish.admin.entity.enums;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import tk.fishfish.enums.EnumType;
/**
* 审计类型
*
* @author 奔波儿灞
* @version 1.5.0
*/
@Getter
@RequiredArgsConstructor
public enum AuditType implements EnumType {
LOGIN("登录", "0"),
LOGOUT("登出", "1"),
;
private final String name;
private final String value;
}
|
Python
|
UTF-8
| 1,234 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/python3
from sorters.sort_base import sort_base
from sort_util.data_tools import data_store
class bucket_sort(sort_base):
def __init__(self) -> None:
super().__init__()
def name(self) -> str:
return 'Bucket'
def __insertion_sort__(self, data: data_store, start: int, end: int):
for i in range(start, end):
src_index = i
for j in range(0, i):
if data.is_less_than(src_index, j):
data.move(src_index, j)
break
def _do_sort(self, data: data_store) -> None:
bucket_size = 50
num_buckets = int(data.size() / bucket_size)
if num_buckets == 0:
self.__insertion_sort__(data, 0, data.size())
return
bucket_sizes = [0] * num_buckets
for i in range(data.size()):
bucket_idx = int(data[i] / bucket_size)
dest_idx = sum(bucket_sizes[0: bucket_idx + 1])
data.move(i, dest_idx)
bucket_sizes[bucket_idx] += 1
for i in range(num_buckets - 1, -1, -1):
start = sum(bucket_sizes[0: i])
end = start + bucket_sizes[i]
self.__insertion_sort__(data, start, end)
|
Markdown
|
UTF-8
| 25,002 | 2.53125 | 3 |
[] |
no_license
|
# <a name="index"></a>ZEN MINING PROJECT WHITE PAPER
##### [Предпосылки](#background)
##### [Решение](#solution)
##### [Рынок](#market)
##### [Описание проекта](#description)
##### [Бизнес-модель](#model)
##### [Роадмэп проекта](#roadmap)
##### [Токены PRANA](#token-ico)
##### [Команда](#team)
##### [Условия](#agreement)
---
Мы создаем программную инфраструктуру для майнинга криптовалют. Система сбора и анализа данных, собственный майнер и операционная система для майнинга - все это создается для эффективного и прозрачного управления майнингом.
> В самом названии дзен-майнинг заложена концепция созерцания и спокойствия
## <a name="background"></a>Предпосылки
Один из основателей сервиса профессионально занимается майнингом. Мы обнаружили, что для отслеживания важных показателей оборудования и пула приходится изворачиваться и устанавливать множество ПО, порой сомнительного происхождения. Также стоит актуальный вопрос о системе уведомлений об авариях и критических значениях показателей. Некоторые пулы позволяют получать уведомления, однако задержка достигает нескольких часов. Еще одна проблема - это сбор статистики. Большинство программного обеспечения не собирает и не хранит данные, а статистика порой крайне важна, тем более при проведении различных А/Б тестов.
Еще одной предпосылкой является то, что рынок программного обеспечения для майнинга пока не сформировался. Уже есть большая потребность в различном качественном софте, но его еще нет.
[↑ оглавление](#index)
## <a name="solution"></a>Решение
Как и в любом бизнесе, отслеживание ключевых показателей системы крайне важно для принятия управленческих решений. Мы создаем программное обеспечение, которое отображает и анализирует все ключевые показатели. Это критически важно для выбора как программного обеспечения, так и пула майнинга. Не секрет, что в зависимости от оборудования, операционной системы и аппаратных настроек оборудования, установленного у майнера, различный софт будет вести себя по-разному. Мы создаем программное обеспечение, которое помогает в принятии правильных решений и выборе наиболее эффективного софта и аппаратных настроек оборудования. Что напрямую влияет на доходность.
Наш сервис позволит отслеживать ключевые показатели оборудования и пула, собирать всю возможную статистику и отправлять нотификации о критических показателях. Zenmining позволяет анализировать данные, полученные из логов самого майнера и API пулов, для оптимизации доходов. Также рядовой майнер сможет понять, какую именно комиссию берет пул и насколько расчетные показатели доходности отличаются от реальных. Эти данные необходимы для выбора нужного пула и ПО для майнинга.
Создание инструментов мониторинга - это первый шаг, конечная же цель - создание комплексного программного решения для GPU и ASIC майнинга. Для GPU ригов мы разрабатываем собственный майнер, конкурент Claymor. А также операционную систему, сборку на Linux, специально заточенную под майнинг.
[↑ оглавление](#index)
## <a name="market"></a>Рынок
Проанализировав данные на август 2017, можно сказать, что на крупнейших ETH пулах насчитывается около 200К майнеров, у каждого из которых - в среднем 3 рига (без учета ETC, Zchas и прочих алькоинов). По расчетам, наша суммарная аудитория порядка 500К майнеров, и каждый из них в среднем зарабатывает порядка $600 в месяц.
*TODO:добавить аналитические данные*
[↑ оглавление](#index)
## <a name="description"></a>Описание проекта
Цель нашего продукта - создание программной инфраструктуры для эффективного майнинга криптовалют. В самом названии дзен-майнинг заложена концепция созерцания и спокойствия.
### Модуль аналитики
Сервис аналитики собирает данные из популярных майнеров (Claymore, Genoils, QtMiner), а также данные майнинг пулов (ethermine, dwarfpool, f2pool). Собранные данные агрегируются в единую систему и предоставляют пользователю расширенную аналитику по таким показателям, как:
* Хэшрейт - суммарный, по каждому ригу и по каждой видеокарте, на основе данных из майнера;
* Температура и скорость вращения вентилятора по каждой видеокарте;
* Отслеживание температуры в комнате (решение на основе watchdog);
* Количество shares принятые и отклоненные;
* Данные по хэшрейту и шарам (shares) из пула;
* Динамика заработка по каждому из ригов.
Используя эти данные, возможно получить:
* Текущее состояние оборудования - температуру и скорость вращения вентиляторов;
* Текущую производительность оборудования (hashrate), и её сравнение на майнере и пуле;
* Историю изменений ключевых показателей (hashrate, shares, температура и скорость вращения) за любой выбранный период времени;
* Аналитику данных из GPU ригов и ASICов в одном месте;
* Систему нотификаций (почта, telegram, sms) о критических изменениях показателей;
* Телеграмм бота для удаленного предоставления любой информации и управления фермой;
* Сравнение расчетного и фактического заработков;
* Контроль комиссий пула и майнера, а также сравнение этих показателей;
* Прогнозирование возможных проблем и рекомендаций для майнера на основе собранной статистики;
* Удаленное управление оборудованием.
### Майнер
Наша цель - создание завершенного продукта для майнеров, и это возможно с созданием собственного майнера. Ключевой особенностью нашего майнера будут прозрачность комиссии, скорость, удобство работы (конечно, с уже встроенной подробной аналитикой).
### ZenminingOS
После создания майнера следующим этапом будет сборка операционной системы. Операционная система представляет собой Linux сборку с набором предустановленных и предварительно настроенных компонентов, а также экосистему для майнера. Под экосистемой подразумевается наличие документации, FAQ, инструкции, удобного пользовательского интерфейса и службы поддержки.
[↑ оглавление](#index)
## <a name="model"></a> Бизнес модель
Сам майнер будет распространяться бесплатно и иметь только консольный интерфейс в бесплатной версии. А вот за использование интерфейса мониторинга и системы нотификаций мы будем взымать 0,5% - 1,5% от дохода майнера. Программное обеспечение будет распространяться по модели SaaS.
### Open source майнер и ОС
Одна из наших идей - это развивать сам майнер (и операционную систему как подпроект) силами комьюнити. Имеется в виду создание open source майнера, на содержание которого мы будет отдавать часть прибыли. Очень часто в интернете попадается информация о том, что Claymore снимает большую комиссию, чем декларирует. Проверить это сложно, во-первых, из-за закрытого кода самого майнера, во-вторых, из-за отсутствия подробной статистики. Создание open source майнера с характеристиками не хуже, чем у Claymore, откроет нам путь к сердцам майнеров.
[↑ оглавление](#index)
## <a name="roadmap"></a>Роадмэп проекта
### 01 сентября 2017
Запуск закрытого альфа-тестирования системы мониторинга
##### 21 сентября 2017
Старт pre-ICO
##### 25 сентября 2017
Запуск публичной бета-версии системы мониторинга
##### октябрь 2017
Расширение функционала сервиса согласно backlog разработки, запуск телеграмм бота
##### ноябрь 2017
Поддержка мониторинга и управления ASIC майнеров
##### декабрь 2017 - январь 2018
Альфа-версия zen-майнера, формирование принципов DAO разработки. Альфа-версия мобильного приложения
##### февраль-март 2018
Выпуск стабильной версии zen-майнера с упакованным инструментом аналитики и мобильного приложения
##### апрель-май 2018
Старт ICO, выпуск альфа-версии zen-miningOS. Подключение 50000-го воркера
##### июнь-август 2018
Выпуск публичной беты zen-miningOS
[↑ оглавление](#index)
## <a name="prana-token"></a> Токены PRANA
Услуги сервиса можно будет оплатить только токенами PRANA, которые мы выпускаем в конце августа 2017 года. Токены PRANA можно будет приобрести в личном кабинете (через внутреннюю биржу), обменяв на BTC, ETH, Waves и другие криптовалюты. Подразумевается, что майнер будет раскулачивать именно той монетой, которую он майнил.
Также токенами PRANA мы будем рассчитываться с комьюнити, помогающим нам развивать продукт.
В личном кабинете каждого пользователя будет доступна возможность купить/продать токены PRANA таким же участникам сообщества. Стоимость токена - та цена, по которой мы его продаем - устанавливается нами и начинается от $0,0008. Владелец токена PRANA вправе продавать его по любой цене на внутренней бирже.
Будет эмитирован 1 миллиард токенов PRANA на платформе Etherium.
### Распределим токенов
30% - команде
52% - ICO и preICO
10% - резервный фонд
8% - баунти программа
Токены будут распространяться по следующей модели:
### Seed (подготовка preICO)
Для подготовки к preICO мы планируем привлечь $10K - $16K, по следующей схеме:
* Цена токена PRANA - $0,0008
* Будет продано до 20 000 000 PRANA
Полученные деньги будут потрачены прежде всего на маркетинг (60%), перевод промо-материалов (10%), создание смарт-контракта и личного кабинета (20%) и работу с комьюнити (10%). Цель поднятия раунда - подготовка к проведению preICO.
### preICO
Проведение запланировано на 25 сентября 2018.
Будет продано до 150 000 000 PRANA.
Стоимость PRANA - $0,0015
Цель: $180000 - $225000
По завершении preICO цена токена будет установлена 1 PRANA = $0,003
Полученные деньги будут потрачены на создание стабильной версии системы аналитики, майнера, маркетинг (не менее 20%) и поддержку сообщества (не менее 7%). До выхода на ICO мы подключим 50К воркеров.
### ICO
Запланировано на апрель 2018.
Будет продано 350 000 000 PRANA.
Soft Cap - $1,000,000
Cap - $3,750,000
Hard Cap - $10,000,000
Стоимость 1 PRANA = $0,01-$0.03
После ICO - $0.05
Собранные средства пойдут на глобальный маркетинг, улучшение продукта и создание решений для крупных игроков рынка.
[↑ оглавление](#index)
## <a name="team"></a>Команда
Участники команды Zenmining более 10-ти лет совместно работают в сфере разработки программного обеспечения для бизнеса. Мы имеем успешный 4-х летний опыт разработки ПО и консультирования в сфере автоматизации для рынка США. Проекты нашей команды в рамках различных мероприятий были отмечены компаниями IBM (Startup Village 2015) и Microsoft (Стартап Школа СКФО 2015). Наша команда является победителем хакатона, проводимого фондом ПЕРИ Инновации (группа Сумма). А еще мы просто любим то, что мы делаем.
[↑ оглавление](#index)
## <a name="agreement"></a>Условия и положения
* Этот документ предназначен исключительно для информационных целей и не является предложением или призывом продавать акции или ценные бумаги Zenmining или любой другой связанной или ассоциированной компании.
* Токены PRANA не предоставляют право контроля.
* Владение токенами PRANA не наделяет его держателя правом собственности или правом на имущество в Zenmining. В то время как мнение и отзывы сообщества могут быть учтены, токены PRANA не дают никакого права участвовать в принятии решений или какого-либо направления развития бизнеса, связанного с системой Zenmining. Токены PRANA могут быть использованы для оплаты сервиса Zenmining.
* Отсутствие гарантий получения доходов или прибыли
* Все примеры расчета дохода и прибыли, используемые в настоящем документе, были приведены только для демонстративных целей или демонстрации средних показателей отрасли и не представляют собой гарантии, что данные результаты будут достигнуты, согласно маркетинговому плану.
* Технологии, имеющие отношение к блокчейну является предметом надзора и контроля со стороны различных регулирующих органов по всему миру. Токены PRANA могут попасть под один или несколько запросов или действий с их стороны, в том числе, но не ограничиваясь, наложением ограничения на использование или владение цифровыми токенами, такими как PRANA, которые могут замедлить или ограничить функциональность, или выкуп PRANA токенов в будущем.
* PRANA токены не являются инвестицией
* PRANA токены не являются какого-либо рода официальной или имеющей обязательную юридическую силу инвестицией. По причине непредвиденных обстоятельств, цели, изложенные в этом документе, могут быть изменены. Несмотря на то, что мы намерены достичь всех пунктов, описанных в этом документе, все лица и стороны, участвующие в покупке токенов PRANA делают это на свой собственный риск.
* Несмотря на то, что токены PRANA не должны рассматриваться как инвестиция, они могут получить ценность со временем. Их ценность также может упасть, если сервис Zenmining будет испытывать нехватку в их использовании и применении.
* Риск потери денежных средств. Средства собранные в процессе ICO не застрахованы. В случае утраты или потери стоимости, отсутствует частный или общественный страховой представитель, к которому покупатель сможет обратиться.
* Риск Неудачи. Вполне возможно, что по разным причинам, в том числе без ограничения, несостоятельности деловых договоренностей или маркетинговых стратегий, что система Zenmining и все последующие действия маркетинга, относительно собранных средств в этом ICO, могут не достичь успеха.
* Риск использования новых технологий. Крипто-токены, такие как PRANA, являются достаточно новой и относительно не проверенной технологией. В дополнение к рискам, упомянутым в настоящем документе, существуют дополнительные риски, которые команда сервиса Zenminng не может предвидеть. Эти риски могут материализоваться в других формах рисков, нежели указанные здесь.
* Настоящее Соглашение представляет собой полное соглашение между сторонами в отношении предмета настоящего Договора. Все предыдущие соглашения, обсуждения, презентации, гарантии, и условия объединены в настоящем документе. Нет никаких гарантий, представлений, условий или соглашений, явных или подразумеваемых, между сторонами, за исключением тех, которые четко указаны в настоящем Соглашении. Настоящее Соглашение может быть изменено только посредством письменного документа, оформленного надлежащим образом сторонами.
* Отказ от предоставления гарантий. Вы соглашаетесь, что ваше использование или невозможность использования, токенов PRANA, осуществляется исключительно на собственный риск, и вы снимаете всю ответственность с компании Zenmining. С момента выпуска, токены PRANA будут высланы вам без каких-либо гарантий, явных или подразумеваемых, включая отказ каких-либо гарантий на все подразумеваемые гарантии коммерческой ценности для конкретной цели, название, без нарушения чьих-либо прав интеллектуальной собственности, поскольку некоторые юрисдикции не позволяют исключение подразумеваемых гарантий, вышеуказанные исключения подразумеваемых гарантий могут к вам не относиться.
[↑ оглавление](#index)
|
Python
|
UTF-8
| 634 | 3.109375 | 3 |
[] |
no_license
|
#Dojo Survey
"""
Build a new Flask project. The goal is to help you get familiar with sending POST requests
through a form and displaying that information:
You should have two routes: '/' and '/result' both of which render a template
"""
from flask import Flask,render_template,request,redirect
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/result', methods=['POST'])
def result():
print request.form
if len(request.form['name']) > 0:
return render_template('result.html', user = request.form)
else:
return redirect('/')
app.run(debug=True)
|
Java
|
UTF-8
| 6,577 | 1.976563 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.yl.campus.app.activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import com.yl.campus.R;
import com.yl.campus.app.adapter.GridViewAdapter;
import com.yl.campus.app.presenter.MainPresenter;
import com.yl.campus.app.view.MainView;
import com.yl.campus.common.base.BaseMvpActivity;
import com.yl.campus.common.utils.ActivityCollector;
import com.yl.campus.common.utils.DialogUtils;
import com.yl.campus.common.utils.PrefsUtils;
import com.yl.campus.common.utils.ToastUtils;
import butterknife.BindView;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends BaseMvpActivity<MainView, MainPresenter> implements
MainView, AdapterView.OnItemClickListener,
NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
@BindView(R.id.drawerLayout)
DrawerLayout drawerLayout;
@BindView(R.id.navView)
NavigationView navView;
@BindView(R.id.gridView)
GridView gridView;
TextView nameText, idText;
private boolean isLogon;
@Override
protected void initView() {
initNavigationView();
initGridView();
}
@Override
protected void initData() {
isLogon = LoginActivity.isLogon(this);
nameText.setText(isLogon ? PrefsUtils.getString(this, "nickname") : "点击登录");
idText.setText(isLogon ? PrefsUtils.getString(this, "login_id") : "您还没有登陆");
navView.setCheckedItem(R.id.item_home);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
navView.setCheckedItem(R.id.item_home);
drawerLayout.openDrawer(GravityCompat.START);
}
return true;
}
@Override
protected int getLayoutId() {
return R.layout.activity_main;
}
@Override
protected String getDefaultTitle() {
return getString(R.string.app_name);
}
@Override
protected String getToolbarTitle() {
return super.getToolbarTitle();
}
@Override
protected int getHomeAsUpIndicator() {
return R.drawable.ic_menu;
}
private void initGridView() {
final GridViewAdapter adapter = new GridViewAdapter();
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(this);
}
private void initNavigationView() {
View navHeader = navView.getHeaderView(0);
CircleImageView headImage = (CircleImageView)
navHeader.findViewById(R.id.headImage);
nameText = (TextView) navHeader.findViewById(R.id.nameText);
idText = (TextView) navHeader.findViewById(R.id.idText);
headImage.setOnClickListener(this);
nameText.setOnClickListener(this);
idText.setOnClickListener(this);
navView.setNavigationItemSelectedListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
startActivity(new Intent(MainActivity.this, NewsActivity.class));
break;
case 1:
if (isLogon) {
startActivity(new Intent(MainActivity.this, CurriculumActivity.class));
} else {
ToastUtils.showToast(this, "请先登录", 0);
}
break;
case 2:
startActivity(new Intent(MainActivity.this, BookSearchActivity.class));
break;
case 3:
if (isLogon) {
startActivity(new Intent(MainActivity.this, BalanceActivity.class));
} else {
ToastUtils.showToast(this, "请先登录", 0);
}
break;
case 4:
startActivity(new Intent(MainActivity.this, SettingActivity.class));
break;
default:
break;
}
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
if (item.getItemId() != R.id.item_home && !isLogon) {
ToastUtils.showToast(this, "请先登录", 0);
return true;
}
switch (item.getItemId()) {
case R.id.item_home:
drawerLayout.closeDrawers();
break;
case R.id.item_info:
startActivity(new Intent(MainActivity.this, PersonalInfoActivity.class));
break;
case R.id.item_exit:
showExitDialog();
break;
}
return true;
}
public void showExitDialog() {
DialogUtils.showTipDialog(this, "退出", "确认退出当前用户?", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
showLoadView("正在退出");
onExitLogin();
}
});
}
@Override
protected MainPresenter initPresenter() {
return new MainPresenter();
}
private void onExitLogin() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
hideLoadView();
PrefsUtils.putString(MainActivity.this, "login_psw", null);
PrefsUtils.putBoolean(MainActivity.this, "is_logon", false);
ToastUtils.showToast(MainActivity.this, "已退出当前账号", 0);
ActivityCollector.finishAll();
startActivity(new Intent(MainActivity.this, MainActivity.class));
}
}, 1500);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.headImage:
case R.id.idText:
case R.id.nameText:
if (isLogon) {
startActivity(new Intent(MainActivity.this, PersonalInfoActivity.class));
} else {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
break;
default:
break;
}
}
}
|
C#
|
UTF-8
| 1,376 | 3.84375 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DelegateDemo
{
public class GenericDelegates
{
static void Main(string[] args)
{
//Encapsulates a method that has one or more parameter and returns a value of the type specified by the TResult parameter.
//Return type parameter should be declared
Func<int, float, double, double> obj1 = (x, y, z) =>
{
return x + y + z;
};
double Result = obj1.Invoke(100, 125.45f, 456.789);
Console.WriteLine(Result);
//Encapsulates a method that has one or more parameter and does not return a value.
Action<int, float, double> obj2 = (x, y, z) =>
{
Console.WriteLine(x + y + z);
};
obj2.Invoke(50, 255.45f, 123.456);
//A function that returns true or false is a predicate
Predicate<string> obj3 = new Predicate<string>(CheckLength);
bool Status = obj3.Invoke("Pranaya");
Console.WriteLine(Status);
Console.ReadKey();
}
public static bool CheckLength(string name)
{
if (name.Length > 5)
return true;
return false;
}
}
}
|
C#
|
UTF-8
| 4,475 | 2.828125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
namespace SymulatorSamochoduProjekt
{
public class Samochod
{
private Timer paliwoLicznik = new Timer(100);
public Action paliwoZmienione;
public Action samochodOdpalony;
public Action stanSamochoduZmieniony;
public string nazwa { get; set; }
public TypSamochodu rodzajSamochodu { get; set; }
public int maxPaliwo { get; set; }
public int paliwo { get; set; }
public bool czyOdpalony { get; set; }
public stanSamochodu stan { get; set; }
public Samochod(string nazwa, TypSamochodu rodzajSamochodu, int maxPaliwo, stanSamochodu stan)
{
this.nazwa = nazwa;
this.rodzajSamochodu = rodzajSamochodu;
this.paliwo = paliwo;
this.maxPaliwo = maxPaliwo;
this.czyOdpalony = false;
this.paliwoLicznik = new Timer(2000);
this.paliwoLicznik.Elapsed += this.SkonczonePaliwo;
this.stan = stan;
}
public void WlaczWylaczSamochod()
{
this.czyOdpalony = this.czyOdpalony ? false : true;
if(this.czyOdpalony)
{
this.paliwoLicznik.Start();
}
else
{
this.paliwoLicznik.Stop();
}
if (this.samochodOdpalony != null)
{
this.samochodOdpalony();
}
}
public void UzupelnijSamochod()
{
this.paliwo = this.maxPaliwo;
if (this.paliwoZmienione != null)
{
this.paliwoZmienione();
}
}
public void NaprawSamochod()
{
this.stan.Napraw(this);
if(this.stanSamochoduZmieniony != null)
{
this.stanSamochoduZmieniony();
}
}
public void UszkodzSamochod()
{
this.stan.Uszkodzenia(this);
if(this.stanSamochoduZmieniony!= null)
{
this.stanSamochoduZmieniony();
}
}
public int JedzSamochodem()
{
int km = new Random(DateTime.Now.Second).Next(20, 101);
if (km * 2 > this.paliwo)
{
int dystans = this.paliwo;
this.paliwo = 0;
return dystans;
}
else
{
this.paliwo -= km * 2;
return km;
}
}
public bool UszkodzeniaLosowe()
{
if(new Random(DateTime.Now.Second).Next(1,6)== 5)
{
this.UszkodzSamochod();
return true;
}
else
{
return false;
}
}
private void SkonczonePaliwo(object obj, ElapsedEventArgs e)
{
if(this.paliwo <= 0)
{
this.WlaczWylaczSamochod();
}
else
{
this.paliwo -= 1;
}
if(this.paliwoZmienione != null)
{
this.paliwoZmienione();
}
}
}
public static class FabrykaSamochodow
{
public static Samochod UtworzSamochod(TypSamochodu rodzajSamochodu, string nazwa)
{
int maxPaliwo = rodzajSamochodu == TypSamochodu.Sportowy ? 800
: rodzajSamochodu == TypSamochodu.Terenowy ? 1000
: rodzajSamochodu == TypSamochodu.Sedan ? 700
: rodzajSamochodu == TypSamochodu.Minivan ? 200 : 0;
stanSamochodu stan = null;
switch(rodzajSamochodu)
{
case TypSamochodu.Sportowy:
stan = new NowyStan();
break;
case TypSamochodu.Terenowy:
stan = new DobryStan();
break;
case TypSamochodu.Sedan:
stan = new BardzoDobryStan();
break;
case TypSamochodu.Minivan:
stan = new SredniStan();
break;
}
return new Samochod(nazwa, rodzajSamochodu, maxPaliwo, stan);
}
}
}
|
Python
|
UTF-8
| 640 | 2.515625 | 3 |
[] |
no_license
|
#!/usr/bin/env python
from todolist import TodoList
from todoitem import TodoItem
from user import User
from service import Service
from datetime import datetime
from config import STATE_UNDO, STATE_DONE
service = Service()
service.add_user('David')
service.add_user('Tiiiiiiiiim')
service.add_user('Jack')
service.add_todoitem('David', TodoItem(1, 'David', datetime.now(), STATE_UNDO, "Hello I am David!"))
service.add_todoitem('David', TodoItem(2, 'David', datetime.now(), STATE_UNDO, "Hello I am David!"))
service.add_todoitem('Jack', TodoItem(3, 'Jack', datetime.now(), STATE_UNDO, "I am Jack, I hate you, David!"))
service.save()
|
C++
|
UTF-8
| 2,820 | 3.046875 | 3 |
[] |
no_license
|
#ifndef _HuffmanCode_h_
#define _HuffmanCode_h_
#include "HuffmanNode.h"
class HuffmanCode
{
///////////////////////////////////////////////////////////////////////////////
public:
///////////////////////////////////////////////////////////////////////////////
HuffmanCode ( ) ;
// new_code builds a HuffmanCode from a
// leaf in a Huffman tree.
HuffmanCode (const HuffmanNode* leaf) ;
~HuffmanCode ( ) ;
///
/// \brief nbBits returns number of bits associated to this code. The
/// bits (1/0) can be retrieved from the 'bit' method.
/// \return
///
size_t nbBits ( ) const ;
///
/// \brief bit returns the i-th bit, for this code. [0,...,nbBits]
/// \param i
/// \return
Byte bit (size_t i) const ;
/// \brief bitArrayString creates string, with an array of 1 and 0
/// \return
std::string bitArrayString ( ) const ;
const Byte* byteArray ( ) const ;
// the size of this code
///
/// \brief size Number of bytes internally used to store the code. The
/// size of the 'bitArray' array.
/// \return
///
size_t nbByte ( ) const ;
const HuffmanNode* leaf ( ) const ;
/// \brief symbol returns the symbol associated to this code
/// \return
const Symbol& symbol ( ) const ;
// Writes the code for this current node, that represents a symbol
//
// writes: [symbol] [nb bits] [count: # of symbol on stream] [ byte array ]
// not that the byte array is padded. For example,
// if the symbol contains 11 bits, 2 bytes will be written.
bool writeCode (Stream& out) const ;
///////////////////////////////////////////////////////////////////////////////
private:
///////////////////////////////////////////////////////////////////////////////
// The length of this code in bits.
unsigned char m_nbBits ;
// The bits associated to this code.
// 1st bit at position 0 in bits[0]
// 2nd bit at position 1 in bits[0]
// 8th bit at position 7 in bits[0]
Byte* m_bits ;
const HuffmanNode* m_leaf ;
};
#endif
|
Python
|
UTF-8
| 2,882 | 4.25 | 4 |
[] |
no_license
|
# -*- coding:utf-8 -*-
from sys import exit
def gold_room():
print("This room is full of gold.How much do you take? 这里有一屋子的金子,你想拿走多少?")
choice = input(">")
if "0" in choice or "1" in choice:
how_much = int(choice)
else:
dead("Man, learn to type a number. 你的数学是体育老师教的吗?写数字!!")
if how_much < 50:
print("Nice, you're not greedy, you win! 你还不算太贪心,恭喜你可以带着黄金走了")
else:
dead("You greedy bastard! 你真是个贪心鬼!!!")
def bear_room():
print("""
There is a bear here.
The bear has a bunch of honey.
The fat bear is in front of anther door.
How are you going to move the bear?
这里有一头大熊
它有一堆蜂蜜
这头肥熊正在另一扇门前挡着
你怎么赶走这头熊呢?
""")
bear_moved = False
while True:
choice = input(">")
if choice == "take honey" or choice == "拿走蜂蜜":
dead("The bear looks at you then slaps your face off.哈哈,熊看了看你,然后拍扁了你的脑袋")
elif choice =="taunt bear" or choice =="大吼一声" and not bear_moved:
print("The bear has moves from the door.You can go though it now.熊从门口走开了,你可以通过了")
bear_moved = True
elif choice == "taunt bear" or choice =="大吼一声" and bear_moved:
dead("The bear gets passed and chews your leg off.")
elif choice == "open door" or choice == "开门" and bear_moved:
gold_room()
else:
print("I got no idea what that means.我不懂你想让我干嘛")
def cthulhu_room():
print("""
Here you see the great evil Cthulhu.
He,it,whatever stares at you and you go insane.
Do you flee for your life or eat your head?
在这里有一个大恶魔
这个家伙正注视着你,你感到心慌了
你是要逃走,还是献上你的脑袋?
""")
choice = input(">")
if "flee" in choice or "逃" in choice:
start()
elif "head" in choice or "脑袋" in choice:
dead("Well that was tasty! 嗯,很美味")
else:
cthulhu_room()
def dead(why):
print(why,"Good job!")
exit(100) #此处的参数使用0或者1或者其它数字有什么不同?
def start():
print("""
You are in a dark room.
There a door to your right and left.
Which one do you take?
现在你在一个小黑屋里面
你的左右两边各有一扇门
你选择哪边的?
""")
choice = input(">")
if choice == "左边":
bear_room()
elif choice == "右边":
cthulhu_room()
else:
dead("You stumble around the room until you starve.你也可以不选择,四处转转等着饿死吧!")
start()
|
Shell
|
UTF-8
| 180 | 3.03125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
_GET_TRACES=$(find -type f -iregex '.*trace_core.*\.log')
for trace in $_GET_TRACES; do
column -t -s $'\t' -o ' ' -R 1,2,3,4,5 $trace > $(dirname $trace)/trace_pretty.log
done
|
JavaScript
|
UTF-8
| 1,308 | 2.5625 | 3 |
[] |
no_license
|
import React, { useState } from 'react'
import axios from 'axios'
export const ProposalContext = React.createContext()
const proposalAxios = axios.create()
export default function ProposalProvider(props){
const initState = {
proposals: []
}
const [ propState, setPropState ] = useState(initState)
function getUserProposals(){
proposalAxios.get("api/proposal/user")
.then(res => {
setPropState(prevPropState => ({
...prevPropState,
proposals: res.data
}))
})
.catch(err => console.log(err.response.data.errMsg))
}
function addProposal(newProposal){
proposalAxios.post("api/proposal", newProposal)
.then(res => {
setPropState(prevPropState => ({
...prevPropState,
proposals: [...[prevPropState.proposals, res.data]]
}))
})
.catch(err => console.log(err.response.data.errMsg))
}
return(
<ProposalContext.Provider
value={{
...propState,
addProposal,
getUserProposals
}}>
{ props.children }
</ProposalContext.Provider>
)
}
|
SQL
|
UTF-8
| 2,169 | 3.34375 | 3 |
[] |
no_license
|
-- MySQL Script generated by MySQL Workbench
-- za 11 nov 2017 19:57:11 CET
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema DaaS
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema DaaS
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `DaaS` DEFAULT CHARACTER SET utf8 ;
USE `DaaS` ;
-- -----------------------------------------------------
-- Table `DaaS`.`devices`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DaaS`.`devices` (
`iddevices` INT NOT NULL AUTO_INCREMENT,
`dev_arbeitsplatz` VARCHAR(255) NOT NULL,
`dev_device` VARCHAR(255) NOT NULL,
`dev_beschreibung` VARCHAR(255) NULL,
`dev_preis` DECIMAL(7,2) NOT NULL,
`dev_anwendung` VARCHAR(255) NOT NULL,
`dev_geeignet` VARCHAR(255) NOT NULL,
`dev_imagepath` VARCHAR(255) NULL,
PRIMARY KEY (`iddevices`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `DaaS`.`config`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DaaS`.`config` (
`idconfig` INT NOT NULL AUTO_INCREMENT,
`conf_iddevice_fk` INT NOT NULL,
`conf_order` INT NULL,
`conf_type` VARCHAR(45) NOT NULL,
`conf_name` VARCHAR(255) NOT NULL,
`conf_beschreibung` VARCHAR(255) NULL,
`conf_prechecked` INT NULL,
`conf_preis` DECIMAL(7,2) NOT NULL,
`conf_image_path` VARCHAR(255) NULL,
`conf_select_option` VARCHAR(45) NULL,
PRIMARY KEY (`idconfig`),
INDEX `iddevices_FK_idx` (`conf_iddevice_fk` ASC),
CONSTRAINT `iddevices_FK`
FOREIGN KEY (`conf_iddevice_fk`)
REFERENCES `DaaS`.`devices` (`iddevices`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
|
C++
|
UTF-8
| 640 | 2.546875 | 3 |
[] |
no_license
|
#include "AreaLighting.h"
#include "../World/World.h"
#include "../Utilities/ShadeRec.h"
#include "../Materials/Material.h"
#include <iostream>
AreaLighting :: AreaLighting()
: Tracer()
{}
AreaLighting :: AreaLighting( World* world_ptr )
: Tracer( world_ptr )
{}
AreaLighting :: ~AreaLighting() {}
RGBColor AreaLighting :: trace_ray( const Ray& ray , const int depth ) const
{
ShadeRec sr( world_ptr -> hit_objects( ray ) ) ;
if ( sr.hit_an_object ) {
sr.ray = ray ;
RGBColor res = sr.material_ptr -> area_light_shade ( sr ) ;
return ( res ) ;
}
else
return ( world_ptr -> background_color ) ;
}
|
Java
|
UTF-8
| 4,291 | 2.265625 | 2 |
[] |
no_license
|
package tr.com.khg.caching.domain;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Cascade;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;
/**
* A Person.
*/
@Entity
@Table(name = "person")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Person extends AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "surname")
private String surname;
@Column(name = "birthday")
private LocalDate birthday;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(unique = true)
private Identity identity;
@OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
private Set<Phone> phones = new HashSet<>();
@OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
private Set<PastCities> cities = new HashSet<>();
// jhipster-needle-entity-add-field - JHipster will add fields here
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public Person name(String name) {
this.name = name;
return this;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public Person surname(String surname) {
this.surname = surname;
return this;
}
public void setSurname(String surname) {
this.surname = surname;
}
public LocalDate getBirthday() {
return birthday;
}
public Person birthday(LocalDate birthday) {
this.birthday = birthday;
return this;
}
public void setBirthday(LocalDate birthday) {
this.birthday = birthday;
}
public Identity getIdentity() {
return identity;
}
public Person identity(Identity identity) {
this.identity = identity;
return this;
}
public void setIdentity(Identity identity) {
this.identity = identity;
}
public Set<Phone> getPhones() {
return phones;
}
public Person phones(Set<Phone> phones) {
this.phones = phones;
return this;
}
public Person addPhones(Phone phone) {
this.phones.add(phone);
phone.setPerson(this);
return this;
}
public Person removePhones(Phone phone) {
this.phones.remove(phone);
phone.setPerson(null);
return this;
}
public void setPhones(Set<Phone> phones) {
this.phones = phones;
}
public Set<PastCities> getCities() {
return cities;
}
public Person cities(Set<PastCities> pastCities) {
this.cities = pastCities;
return this;
}
public Person addCities(PastCities pastCities) {
this.cities.add(pastCities);
pastCities.setPerson(this);
return this;
}
public Person removeCities(PastCities pastCities) {
this.cities.remove(pastCities);
pastCities.setPerson(null);
return this;
}
public void setCities(Set<PastCities> pastCities) {
this.cities = pastCities;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Person)) {
return false;
}
return id != null && id.equals(((Person) o).id);
}
@Override
public int hashCode() {
return 31;
}
// prettier-ignore
@Override
public String toString() {
return "Person{" +
"id=" + getId() +
", name='" + getName() + "'" +
", surname='" + getSurname() + "'" +
", birthday='" + getBirthday() + "'" +
"}";
}
}
|
TypeScript
|
UTF-8
| 4,672 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
import { Router, Request, Response } from "express";
import Playlist from "../../database/models/playlist";
import Song from "../../database/models/song";
import User from "../../database/models/user";
import authenticated from "../middleware/authenticated";
import validatePlaylist from "../middleware/validation/playlist";
import validatePlaylistSong from "../middleware/validation/playlist-song";
import playlistResource from "../resources/playlist-resource";
import playlistSongResource from "../resources/playlist-song-resource";
import * as PlaylistService from "../../services/playlist";
import { co } from "../helpers";
import NotFound from "../../errors/notfound";
import ValidationError from "../../errors/validation";
import logger from "../../logger";
const router = Router();
/**
* Import a youtube playlist
*/
router.post("/youtube/import", authenticated, co(async (req: Request, res: Response) => {
const user = await User.findById(req.userId) as Database.User;
if (user.limits.lastPlaylistImport.getTime() > Date.now() - 1000 * 60 * 60 * 24) {
throw new ValidationError(["You can only import 1 playlist per day"]);
}
PlaylistService.importYoutubePlaylist(req.body.playlistId, req.userId)
.catch((err) => logger.error(`Playlist import error id: ${req.body.playlistId}`, err));
user.limits.lastPlaylistImport = new Date();
user.save();
res.json({ message : "Your playlist has been added to the import queue and will be imported soon" });
}));
/**
* Get all playlists ids that have a specific song
*/
router.get("/song/:videoId/playlists", authenticated, co(async (req: Request, res: Response) => {
const playlists = await Playlist.find({ user : req.userId, songs : req.params.videoId }, { _id : 1 });
return res.json({ data : playlists.map(item => item._id) });
}));
/**
* Add a song to a specific playlist
*/
router.post("/:playlistId/song", [authenticated, validatePlaylistSong], co(async (req: Request, res: Response) => {
const { playlistId } = req.params;
const { videoId } = req.body;
await PlaylistService.addSong(playlistId, videoId);
return res.json({ message : "Added successfully" });
}));
/**
* Add an entire playlist to the queue
*/
router.post("/:playlistId/queue", authenticated, co(async (req: Request, res: Response) => {
const { playlistId } = req.params;
const count = await PlaylistService.addToQueue(playlistId, req.userId);
return res.json({ message : `${count} ${count > 1 ? "songs" : "song"} ${count > 1 ? "were" : "was"} successfully added to the queue` });
}));
/**
* Remove a song from a playlist
*/
router.delete("/:playlistId/song/:videoId", [authenticated], co(async (req: Request, res: Response) => {
const { playlistId, videoId } = req.params;
PlaylistService.removeSong(playlistId, videoId);
return res.json({ message : "Deleted successfully" });
}));
/**
* Get all the playlists for the logged in user
*/
router.get("/", authenticated, co(async (req: Request, res: Response) => {
const playlists: Database.Playlist[] = await Playlist.find({ user : req.userId }).sort({ name : 1 });
return res.json({ data : playlists.map(item => playlistResource(req)(item)) });
}));
/**
* Get all the songs in a specific playlist
*/
router.get("/:playlistId/songs", authenticated, co(async (req: Request, res: Response) => {
const { playlistId } = req.params;
const playlist = await Playlist.findOne({ _id : playlistId });
if (!playlist) {
throw new NotFound("The specified playlist doesn't exist");
}
const songs: Database.Song[] = await Song.find({ videoId : { $in : playlist.songs } }).sort({ title : 1 });
return res.json({ data : songs.map(item => playlistSongResource(req)(item)) });
}))
/**
* Create a new playlist for the logged in user
*/
router.post("/", [authenticated, validatePlaylist], co(async (req: Request<{}, {}, { name: string }>, res: Response) => {
const { name } = req.body;
const playlist = await Playlist.create({ name, user : req.userId, songs: [] });
return res.json({ data : playlistResource(req)(playlist) });
}));
/**
* Delete a specific playlist
*/
router.delete("/:playlistId", [authenticated], co(async (req: Request, res: Response) => {
const { playlistId } = req.params;
const playlist = await Playlist.findOne({ user : req.userId, _id : playlistId });
if (!playlist) {
throw new NotFound("The specified playlist was not found");
}
await playlist.remove();
return res.json({ message : `${playlist.name} has been deleted successfully` });
}));
export default router;
|
Markdown
|
UTF-8
| 18,246 | 2.765625 | 3 |
[] |
no_license
|

### TABLE OF CONTENTS
#### [Emotiv Xavier Tools](#0)
#### [1. Introduction to XavierEmoKey](#1)
#### [1.1 Connecting XavierEmoKey to Emotiv EmoEngine](#1.1)
#### [1.2 Configuring XavierEmoKey Rules](#1.2)
#### [1.3 XavierEmoKey Keyboard Emulation](#1.3)
#### [1.4 Configuring XavierEmoKey Rule Trigger Conditions](#1.4)
#### [1.5 Saving Rules to an XavierEmoKey Mapping file](#1.5)
#### [2. Xavier Composer usage](#2)
#### [2.1 INTERACTIVE mode](#2.1)
#### [2.2 EmoScript Mode](#2.2)
### <a name="0"></a> Emotiv Xavier Tools
This section explains the software utilities provided with the Emotiv Xavier: XavierEmoKey and XavierComposer.
XavierEmoKey allows you to connect detection results received from the EmoEngine to predefined keystrokes according to easy-to-define, logical rules. This functionality may be used to experiment with the headset as an input controller during application development. It also provides a mechanism for integrating the Emotiv neuroheadset with a preexisting application via the application’s legacy keyboard interface.
XavierComposer emulates the behavior of the EmoEngine with an attached Emotiv neuroheadset. It is intended to be used as a development and testing tool; it makes it easy to send simulated EmoEngine events and request responses to applications using the Emotiv API in a transparent and deterministic way.
#### <a name="1"></a> 1. Introduction to XavierEmoKey
XavierEmoKey translates Emotiv detection results to predefined sequences of keystrokes according to logical rules defined by the user through the XavierEmoKey user interface. A set of rules, known as an “EmoKey Mapping”, can be saved for later reuse. XavierEmoKey communicates with Emotiv EmoEngine in the same manner as would a third-party application: by using the Emotiv API exposed by InsightEDK.dll.
##### <a name="1.1"></a> 1.1 Connecting XavierEmoKey to Emotiv EmoEngine
By default, XavierEmoKey will attempt to connect to Emotiv Xavier when the application launches. If Emotiv Xavier isn’t running, then XavierEmoKey will display a warning message above the system tray. The reason XavierEmoKey connects to the Insight SDK, instead of connecting directly to the EmoEngine and the neuroheadset, is to allow the user to select his profile, configure the detection suite settings, and get contact quality feedback through the Insight SDK user interface. Please see Section **Error! Reference source not found**. for more details about when Emotiv SDK developers might wish to follow a similar strategy.
XavierEmoKey can also be connected to XavierComposer . This is useful when creating and testing a new EmoKey Mapping since the user can easily generate EmoState update events that satisfy the conditions for rules defined in XavierEmoKey. Refer to Section 1.2 for more information about XavierComposer.

**Figure 1 XavierEmoKey Connect Menu**
XavierEmoKey’s connection settings can be changed by using the application’s ***Connect*** menu. If XavierEmoKey is not able to connect to the target application (usually because the connection target is not running), then the XavierEmoKey icon in the system tray will be drawn as gray, instead of orange). If this occurs, then run the desired application (either Xavier Driver or Xavier Composer ) and then select ***Reconnect*** from the ***Connect*** menu.
##### <a name="1.2"></a> 1.2 Configuring XavierEmoKey Rules

**Figure 2 Example XavierEmoKey Mapping**
Figure above shows an example of an EmoKey Mapping as it might be configured to communicate with an Instant Messenger (IM) application. In this example, XavierEmoKey will translate Blink events generated by Emotiv’s Expressiv to the text “LOL” (as long as the AffectivTM’s Instantaneous Excitement detection is also reporting a score > 0.3), which causes the IM program to send “LOL” automatically when the user is blink.
The topmost table in XavierEmoKey contains user interface controls that allow you to define rules that specify which keystrokes are emulated. Rules can be added by clicking on the ***Add Rule*** button. Existing rules can be deleted by selecting the appropriate row and pressing the ***Delete Rule*** button. In Figure 2, two rules, named “LOL” and “Wink”, were added. Rules can be edited as outlined below, in Table 1.
Field | Description | Notes
------------- | ------------- | -------------
***Enabled*** | Checkbox to selectively enable or disable individual rules | The indicator “light” will turn green when the rule conditions are satisfied.
***Player*** | Identifies the neuroheadset that is associated with this rule | Player 1 corresponds to user ID 0 in Xavier Composer and Xavier SDK.
***Name*** | User-friendly rule name | Edit by double clicking on the cell.
***Key*** | Keystroke sequence to be sent to the Windows input queue | Edit by double clicking on the cell.
***Behavior*** | Checkbox to control whether the key sequence is sent only once, or repeatedly, each time an EmoState update satisfies the rule conditions | If checked, then XavierEmoKey must receive an EmoState update that does NOT satisfy the rule’s conditions before this rule can be triggered again.
***Table 1 XavierEmoKey Rule Definition Fields***
##### <a name="1.3"></a> 1.3 XavierEmoKey Keyboard Emulation
XavierEmoKey emulates a Windows-compatible keyboard and sends keyboard input to the Windows operating system’s input queue. The application with the input focus will receive the emulated keystrokes. In practice, this often means that XavierEmoKey is run in the background. Please note that closing the XavierEmoKey window will only hide the application window and that it will continue to run. When running, the XavierEmoKey/Emotiv icon will be visible in the Windows system tray. Double-click on this icon to bring XavierEmoKey back to the foreground. Choose **Quit** from the **Application** or **system-tray menu** to really quit the application.

***Figure 3 XavierEmoKey System Tray Icon***
Double-clicking in the Key field of a rule will bring up the Keys dialog as shown in

***Figure 4 Defining Keys and Keystroke Behavior***
The Keys dialog allows the user to specify the desired keystrokes and customize the keystroke behavior. The customizable options include:
- Holding a key press: hold the key down for the duration of the rule activation period.
The Hold the key checkbox is only enabled when a single key has been specified in
the keystroke edit box.
- Hot keys or special keyboard keys: any combination of control, alt, shift, the Windows
key, and another keystroke. You may also use this option if you need to specify
special keys such as Caps Lock, Shift, or Enter.
- Key press duration and delay times: some applications, especially games, are
sensitive to the timing of key presses. If necessary, use these controls to adjust the simulated keyboard behavior.
##### <a name="1.4"></a> 1.4 Configuring XavierEmoKey Rule Trigger Conditions
The ***Trigger Conditions*** table in XavierEmoKey contains user interface controls that allow you to define logical conditions that determine when the corresponding rule is activated. Clicking on a new rule in the Rules table will refresh the contents of the ***Trigger Conditions*** table, causing it to display only the conditions associated with the selected rule.
Conditions can be added by clicking on the ***Add Condition*** button. Existing rules can be deleted by selecting the appropriate condition and pressing the ***Delete Condition*** button. In Figure 2, two conditions, which examine the state of the Expressiv Laugh detection and the AffectivTMInstantaneous Excitement detection, respectively, are associated with the LOL rule. All enabled conditions must be satisfied by the most recent EmoState update received from Emotiv Xavier or Xavier Composer for a rule to be triggered.
The fields of the ***Trigger Conditions*** table are described below, in Table 2.
Field | Description
------- | -----------
**Enabled** | Checkbox to selectively enable or disable individual trigger conditions
**Action** | The name of the Expressiv expression, AffectivTMdetection, or Cognitiv action being examined by this condition.
**Trigger** | Description of the trigger condition being evaluated
**Value** |For non-binary trigger conditions, the value being compared to the action score returned by the designated detection
**Table 2 XavierEmoKey Trigger Condition Fields**
Double-clicking on any of the fields of a condition in the ***Trigger Conditions*** table will reveal the ***Configure Condition*** dialog box, as shown in Figure 5. Use the controls on this dialog to specify an action (or detection) name, a comparison function, and a value, that must evaluate to true for this condition to be satisfied.

***Figure 5 Defining an XavierEmoKey Condition***
##### <a name="1.5"></a> 1.5 Saving Rules to an XavierEmoKey Mapping file
XavierEmoKey allows you to save the current set of rule definitions to an XavierEmoKey Mapping file that can be reloaded for subsequent use. Use the appropriate command in XavierEmoKey’s Application menu to rename, save, and load EmoKey mapping files.
#### <a name="2"></a> 2. Xavier Composer usage
Xavier Composer allows you to send user-defined EmoStatesTM to Emotiv Xavier, XavierEmoKey, or any other application that makes use of the Emotiv API. Xavier Composer supports two modes of EmoState generation: Interactive mode and EmoScript mode. In addition to generating EmoStates, Xavier Composer can also simulate Emotiv EmoEngine’s handling of profile management and training requests.
SDK users will rely on Xavier Composer to simulate the behavior of Emotiv EmoEngine and Emotiv neuroheadsets. However, it is a very useful tool for all Emotiv SDK developers, allowing for easy experimentation with the Emotiv API early in the development process, and facilitating manual and automated testing later in the development cycle.
##### <a name="2.1"></a> 2.1 INTERACTIVE mode

**Figure 6 Xavier Composer interactive mode**
Xavier Composer Interactive mode allows you to define and send specific EmoState values to any application using the Emotiv SDK. The user interface settings are described below.
- Player: choose the player number who’s EmoState you wish to define and send. The player number defaults to 0. When the player number is changed for the first time, an application connected to XavierComposer will receive an EE_UserAdded event with the new player number reported as the user ID.
- Wireless: sets the simulated wireless signal strength. Note: if the signal strength is set to “Bad” or “No Signal” then XavierComposer TM simulates the behavior of the EmoEngine by setting subsequent EmoState detection values and signal quality values to 0.
- Contact Quality tab: this tab allows you to adjust the reported contact quality for each sensor on the Emotiv neuroheadset. When the Contact Quality tab is active, all other EmoState detection values are set to 0. You can choose between typical sensor signal quality readings by selecting a preset from the General Settings drop- down list box. If you choose the Custom preset, each sensor value can be controlled individually by clicking on a sensor and then selecting a new CQ Status value in the Sensor Details box. Note that the two sensors above and behind the ears, correspond to the reference sensors on the Emotiv SDK Neuroheadset, must always report a CQ value of Good and cannot be adjusted.
- Detection tab: this tab allows you to interactively control EmoStateTM detection values and training result values. When the Detection tab is active, the contact quality values for generated EmoStates will always be set to EEG_CQ_GOOD.
- EMOSTATE: define the detection settings in an EmoStateTM by selecting the particular event type for each detection group in the appropriate drop-down list box. Set the event’s value in the spin box adjacent to the event name. You can define your own time value in the Time edit box, or allow XavierComposer TM to set the value automatically by incrementing it by the value of the EmoState Interval spin box after each EmoStateTM is sent. The AffectivTMExcitement state is unique in that the EmoEngine returns both short-term (for Instantaneous Excitement) and long-term values. XavierComposer TM simulates the long-term value calculation adequately enough for testing purposes but does not reproduce the exact algorithm used by the AffectivTMdetection suite in EmoEngineTM. Note that the value for the eye detections is binary (Active or Inactive) and that it is automatically reset to be Inactive after an EmoStateTM is sent. If Auto Repeat mode is active, then you can press and hold the Activate button to maintain a particular eye state across multiple time intervals. Also note that the value for a neutral Cognitiv detection is automatically set to 0.
- TRAINING RESULTS: specify the desired return value for EmoEngineTM requests generated for the current player by the EE_CognitivSetTrainingControl and IEE_FacialExpressivSetTrainingControl functions.
- EMOENGINE LOG: contents are intended to give developers a clearer picture about how the EmoEngine processes requests generated by various Emotiv API functions. The log displays three different output types: Request, Reply, CogResult, and ExpResult. An API function call that results in a new request to the EmoEngine will cause a Request output line to be displayed in the log. The multitude of API functions are translated to roughly a dozen different strings intended to allow the Emotiv SDK developer to see that an API function call has been serviced . These strings include: PROFILE_ADD_USER, PROFILE_CHANGE_USER, PROFILE_REMOVE_USER, PROFILE_LIST_USER, PROFILE_GET_CURRENT_USER, PROFILE_LOAD, PROFILE_SAVE, FACIALEXPRESSIV_GET, FACIALEXPRESSIV_SET, PERFORMANCEMETRIC_GET, PERFORMANCEMETRIC_SET, COGNITIV_SET and COGNITIV_GET. Because of the comparatively complex API protocol used to facilitate training the Cognitiv algorithms, we display additional detail when we receive training control messages generated by the EE_CognitivSetTrainingControl API function. These strings are: COGNITIV_START, COGNITIV_ACCEPT, and COGNITIV_REJECT, which correspond to the EE_TrainingControl_t constants exposed to developers in edk.h. Similar strings are used for the equivalent Expressiv messages. All other request types are displayed as API_REQUEST. The Reply output line displays the error code and is either green or red, depending on whether an error has occurred (i.e. the error code != 0). The CogResult and ExpResult outputs are used to inform the developer of an asynchronous response sent from the EmoEngine via an EmoState update as the result of an active Cognitiv or Expressiv training request.
- START: sends the EmoStateTM to a connected application or the Emotiv Xavier. Note that Insight SDK will display “Cannot Acquire Data” until the first EmoStateTM is received from XavierComposer .
- Auto Reset: check this box to tell XavierComposer TM to automatically send EmoStatesTM at the time interval specified in the EmoStateTM Interval spin box. Use the Start/Stop button to turn the automated send on and off. You may interact with the EmoStateTM controls to dynamically change the EmoStateTM values while the automated send is active. Note: switching between the Contact Quality and Detection tabs in Interactive mode will automatically stop an automated send.
#### <a name="2.2"></a> 2.2 EmoScript Mode

**Figure 7 XavierComposer EmoScript Mode**
XavierComposer TM EmoScript mode allows you to playback a predefined sequence of EmoStateTM values to any application using the EmoEngine. The user interface settings are described below. EmoScript files are written in EML (XavierComposer TM Markup Language). EML syntax details can be found in the EML Language Specification section in **Error! Reference source not found**. this document.
- Player: choose the player number to associate with the generated EmoStatesTM.
- File: click the “...” button to select and load an EmoScript file from disk. If the file loads successfully then the timeline slider bar and Start button will be activated. If an error occurs, a message box will appear with a description and approximate location
in the file.
- Timeline Slider: move the slider control to see the EmoStateTM and signal quality values for any point on the timeline defined by the EmoScript file.
- Start/Stop button: starts and stops the playback of the EmoStateTM values generated by the EmoScript file.
- Wireless: the wireless signal strength setting is disabled while in EmoScript mode and the wireless signal strength is always set to “Good.”
- Contact Quality tab: the indicators on the head model correspond to the values defined by the contact_quality tag at specific time code in the EmoScript file. If no contact_quality tag has been specified then the contact quality values in the generated EmoStates default to CQ_GOOD.
- Detection tab: this tab allows you to view EmoState detection values and provides interactive control over training result values. Unlike Real Time Interactive mode, the signal quality and detection values are determined entirely by the contents of the EmoScript file and you can switch between the Signal Quality tab and the Detection tab to view the appropriate data during playback or timeline navigation.
- EmoState: the values displayed correspond to the EmoStateTM values for a particular point in time as defined by the EmoScript file. Note that these EmoScript values are not interactive and cannot be modified by the user (use the Interactive mode for this instead).
- Training Results and EmoEngine Log: these controls operate exactly the same as they do in Interactive Mode. See the Interactive Mode documentation (above) for more details.
|
Java
|
UTF-8
| 1,235 | 2.125 | 2 |
[] |
no_license
|
package hh.Harjotustyo.harjotustyo;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import hh.Harjotustyo.harjotustyo.domain.Movie;
import hh.Harjotustyo.harjotustyo.domain.MovieRepository;
@RunWith(SpringRunner.class)
@DataJpaTest
public class MovieRepoTest {
@Autowired
private MovieRepository mrepo;
@Test
public void findbyName(){
List<Movie> movies = mrepo.findByTitle("The Matrix");
assertThat(movies).hasSize(1);
assertThat(movies.get(0).getYear()).isEqualTo(1998);
}
@Test
public void createNew(){
Movie movie = new Movie("Test", 2018, "Test");
mrepo.save(movie);
List<Movie> movies = mrepo.findByTitle("Test");
assertThat(movies).hasSize(1);
}
@Test
public void delete(){
List<Movie> movies = mrepo.findByTitle("The Matrix");
Movie movie = movies.get(0);
mrepo.delete(movie);
List<Movie> movies2 = mrepo.findByTitle("The Matrix");
assertThat(movies2).hasSize(0);
}
}
|
Java
|
UTF-8
| 1,315 | 2.34375 | 2 |
[] |
no_license
|
package me.li2.android.photogallery.ui;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import me.li2.android.photogallery.util.PictureUtils;
public class PhotoFullScreenFragment extends DialogFragment {
private static final String EXTRA_IMAGE_PATH ="me.li2.android.photogallery.image_path";
public static PhotoFullScreenFragment newInstance(String imagePath) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_IMAGE_PATH, imagePath);
PhotoFullScreenFragment fragment = new PhotoFullScreenFragment();
fragment.setArguments(args);
fragment.setStyle(DialogFragment.STYLE_NO_TITLE, 0);
return fragment;
}
private ImageView mImageView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
mImageView = new ImageView(getActivity());
String path = (String) getArguments().getSerializable(EXTRA_IMAGE_PATH);
Bitmap bitmap = PictureUtils.getScaledBitmap(path, getActivity());
mImageView.setImageBitmap(bitmap);
return mImageView;
}
}
|
JavaScript
|
UTF-8
| 479 | 2.828125 | 3 |
[] |
no_license
|
// Thanks AlexT
var setting = function(r, g, b) {
background(r, g, b);
};
var word = function(string, x, y, xConstrain, yConstrain) {
text(string, x, y, xConstrain, yConstrain);
};
var wordSize=function(size) {
textSize(size);
};
var wordAlign = function(align, yAlign) {
if(YAlign >= 0) {
textAlign(align, yAlign);
} else {
textAlign(align, align);
}
};
var circle = function(x, y, width, height) {
ellipse(x, y, width, height);
};
|
Markdown
|
UTF-8
| 528 | 2.515625 | 3 |
[] |
no_license
|
# Dual Screen Video
This template demonstrates one way to create a dual-screen video app for
Apple TV.
## Core concepts
* Using `bc.device.externalscreen` methods and events to handle communication
between an iPad and Apple TV
* Using the [Brightcove Video Cloud Media API][1]
* Working with the HTML5 `<video>` element
* Handling cases when an Apple TV device is not present or connected, or when
the target device does not support streaming to Apple TV
[1]: http://support.brightcove.com/en/docs/getting-started-media-api
|
C++
|
UTF-8
| 4,165 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
#ifdef WIN32
#include <sdl2.2.0.5\build\native\include\SDL.h>
#include <sdl2_image.v140.2.0.1\build\native\include\SDL_image.h>
#else
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#endif
#include <iostream>
#include <string>
#include <cburggie.h>
#include <EventHandler.h>
/*
static SDL_Window * window = NULL;
static SDL_Renderer * renderer = NULL;
static SDL_Texture * texture = NULL;
static SDL_Rect rect;
static const SDL_Color black = { 0, 0, 0, 255 };
*/
static cburggie::Window * window = NULL;
static cburggie::Element * image = NULL;
static cburggie::Element * text = NULL;
static const char * message_text = "Hello, world!";
static const int font_size = 20;
static const Uint32 frame_delay_ms = 20;
static int dx = 2, dy = 2;
#ifdef WIN32
static const char * image_path = "E:\\Programming Projects\\playing_with_SDL2\\Debug\\image.jpg";
#else
static const char * image_path = "image.png";
#endif
static void loop()
{
if (text->getDrawY() + dy < 0 ||
text->getDrawY() + text->getDrawHeight() + dy > window->getHeight())
{
dy *= -1;
EventHandler::PushEvent(EventHandler::event::WALL_COLLIDE);
}
if (text->getDrawX() + dx < 0 ||
text->getDrawX() + text->getDrawWidth() + dx > window->getWidth())
{
dx *= -1;
EventHandler::PushEvent(EventHandler::event::WALL_COLLIDE);
}
text->moveDrawPosition(dy,dx);
}
static void render()
{
window->clear();
window->drawAll();
window->present();
}
int main(int argc, char * argv[])
{
//init SDL2
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER) < 0)
{
cburggie::logger("SDL_Init() failed");
return -1;
}
EventHandler::RegisterEvent(EventHandler::event::SDL_QUIT, [] {
cburggie::logger("calling SDL_Quit()...");
SDL_Quit();
});
//create Window object
window = new cburggie::Window();
EventHandler::RegisterEvent(EventHandler::event::SDL_QUIT, [] {
cburggie::logger("calling cburggie::Window::close()...");
window->close(); //deletes all associated elements
cburggie::logger("deleting cburggie::Window object...");
delete window;
});
//init SDL2_image
#ifdef WIN32
int imgflags = IMG_INIT_JPG | IMG_INIT_TIF;
#else
int imgflags = IMG_INIT_PNG | IMG_INIT_JPG | IMG_INIT_TIF;
#endif
if (IMG_Init(imgflags) != imgflags)
{
cburggie::logger("IMG_Init() failed");
SDL_Quit();
return -1;
}
EventHandler::RegisterEvent(EventHandler::event::SDL_QUIT, [] {
cburggie::logger("calling IMG_Quit()...");
IMG_Quit();
});
//init SDL2_ttf
cburggie::Font::Init();
cburggie::Font font;
font.open(*window, cburggie::constants::font_path, font_size);
EventHandler::RegisterEvent(EventHandler::event::SDL_QUIT, [] {
cburggie::logger("calling cburggie::Font::Quit()...");
cburggie::Font::Quit();
});
//create Element object from image
image = window->createElement();
image->createFromImageFile(image_path);
//set Window size to image size
window->setSize(image->getWidth(), image->getHeight());
//create Element object from Font and string
text = window->createElement();
text->createFromText(font, message_text);
font.close();
EventHandler::Init();
//setup a timer to create a SDL_USEREVENT regularly
SDL_TimerID FrameUpdateAndRenderTimer = SDL_AddTimer(
frame_delay_ms,
[] (Uint32 interval, void*param) {
EventHandler::PushEvent(EventHandler::event::FRAME_UPDATE);
return interval;
},
nullptr
);
EventHandler::RegisterEvent(EventHandler::event::SDL_QUIT, [FrameUpdateAndRenderTimer] {
cburggie::logger("calling SDL_RemoveTimer...");
SDL_RemoveTimer(FrameUpdateAndRenderTimer);
});
EventHandler::RegisterEvent(EventHandler::event::FRAME_UPDATE, [] {
loop();
render();
});
EventHandler::RegisterEvent(EventHandler::event::WALL_COLLIDE, [] {
std::cout << "boop\n";
});
EventHandler::RegisterEvent(EventHandler::event::SDL_QUIT, [](SDL_Event* e) {
std::cout << e->quit.timestamp << "\n";
std::cout << "quit1\n";
});
EventHandler::RegisterEvent(EventHandler::event::SDL_QUIT, [] {
std::cout << "quit2\n";
});
render();
EventHandler::HandleEvents();
window = NULL;
text = NULL;
image = NULL;
cburggie::logger("ending program");
return 0;
}
|
PHP
|
UTF-8
| 2,868 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Innerent\Contacts\Repositories;
use Illuminate\Database\Eloquent\Model;
use Innerent\Contacts\Contracts\Contact as ContactInterface;
use Innerent\Contacts\Models\Address;
use Innerent\Contacts\Models\Contact;
use Innerent\Contacts\Models\Email;
use Innerent\Contacts\Models\Phone;
class ContactRepository implements ContactInterface
{
protected $contact;
public function make($contactable, $data): ContactInterface
{
$this->contact = $contactable->contacts()->create([
'name' => $data['name'],
'type' => $data['type'],
]);
return $this;
}
public function update($data): ContactInterface
{
$this->contact->update(['name' => $data['name']]);
return $this;
}
public function find($contactable, $id)
{
$this->contact = $contactable->contacts()->find($id);
if (! $this->contact instanceof Contact) {
abort(404);
}
return $this;
}
public function get($contactable, $id): ContactInterface
{
$this->contact = $contactable->contacts()->find($id);
if (!$this->contact) {
abort(404);
}
$this->contact = $this->contact->load('emails', 'addresses', 'phones');
return $this;
}
public function delete($contactable, $id, $force = false)
{
$this->get($contactable, $id)->toModel()->delete();
return true;
}
public function sync($data)
{
$emails = collect($data['emails'])->where('id', '!=', null);
$this->contact->emails()->whereNotIn('id', $emails->pluck('id')->toArray())->delete();
$phones = collect($data['phones'])->where('id', '!=', null);
$this->contact->phones()->whereNotIn('id', $phones->pluck('id')->toArray())->delete();
$addresses = collect($data['addresses'])->where('id', '!=', null);
$this->contact->addresses()->whereNotIn('id', $addresses->pluck('id')->toArray())->delete();
return $this;
}
public function toModel(): Model
{
return $this->contact->load('emails', 'phones', 'addresses');
}
public function toArray(): array
{
return $this->toModel()->toArray();
}
public function email(Email $email)
{
$this->contact->emails()->updateOrCreate(
['id' => $email->id],
$email->toArray()
);
return $this;
}
public function address(Address $address)
{
$this->contact->addresses()->updateOrCreate(
['id' => $address->id],
$address->toArray()
);
return $this;
}
public function phone(Phone $phone)
{
$this->contact->phones()->updateOrCreate(
['id' => $phone->id],
$phone->toArray()
);
return $this;
}
}
|
TypeScript
|
UTF-8
| 4,399 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
import { environment } from '../../environments/environment';
import DomMethods from '../shared/DomMethods';
/**
* Creates HTML markups <script> and add Google Analytics source to it.
*/
class GoogleAnalytics {
/**
* Make GA send function available from class.
*/
public static sendGaData(hitType: string, eventCategory: string, eventAction: string, eventLabel: string) {
// @ts-ignore
if (window.ga) {
// @ts-ignore
window.ga('send', { hitType, eventCategory, eventAction, eventLabel });
} else {
return false;
}
}
private static GA_MEASUREMENT_ID: string = environment.GA_MEASUREMENT_ID;
private static GA_INIT_SCRIPT_CONTENT: string = `window.ga=window.ga||function(){(ga.q=ga.q||[]).
push(arguments)};ga.l=+new Date;
`;
private static GA_SCRIPT_SRC: string = environment.GA_SCRIPT_SRC;
private static GA_DISABLE_COOKIES: string = `ga('create', 'UA-${GoogleAnalytics.GA_MEASUREMENT_ID}'
, {'storage': 'none'});`;
private static GA_IP_ANONYMIZATION: string = `ga('set', 'anonymizeIp', true);`;
private static GA_DISABLE_ADVERTISING_FEATURES: string = `ga('set', 'allowAdFeatures', false);`;
private static GA_PAGE_VIEW: string = `ga('send', 'pageview', location.pathname);`;
private static TRANSLATION_SCRIPT_SUCCEEDED: string = 'Google Analytics: script has been created';
private static TRANSLATION_SCRIPT_FAILED: string = 'Google Analytics: an error occurred loading script';
private static TRANSLATION_SCRIPT_APPENDED: string = 'Google Analytics: script has been appended';
private static TRANSLATION_SCRIPT_APPENDED_FAILURE: string = 'Google Analytics: an error occurred appending script';
/**
* Disables User ID tracking (User Opt-out).
* @private
*/
private static _disableUserIDTracking() {
// @ts-ignore
return (window[`ga-disable-UA-${GoogleAnalytics.GA_MEASUREMENT_ID}-Y`] = true);
}
/**
* Adds all required features by interpolating static strings.
* @private
*/
private static _returnScriptWithFeatures() {
return `${GoogleAnalytics.GA_INIT_SCRIPT_CONTENT}
${GoogleAnalytics.GA_DISABLE_COOKIES}
${GoogleAnalytics.GA_IP_ANONYMIZATION}
${GoogleAnalytics.GA_DISABLE_ADVERTISING_FEATURES}
${GoogleAnalytics.GA_PAGE_VIEW}`;
}
private _communicate: string;
private _gaLibrary: HTMLScriptElement;
private _gaScript: HTMLScriptElement;
private _gaScriptContent: Text;
constructor() {
this._onInit();
}
/**
* Initializes Google Analytics scripts on merchants page.
* Gathers all methods needed to establish GGoogle Analytics functionality.
* @private
*/
private _onInit() {
this._insertGALibrary();
this._createGAScript()
.then(() => {
this._insertGAScript()
.then(() => {
GoogleAnalytics._disableUserIDTracking();
})
.catch(error => {
throw new Error(error);
});
})
.catch(error => {
throw new Error(error);
});
}
/**
* Creates GA script, which is executed inside <script> markup.
* Appends it in <script> tag.
* @private
*/
private _createGAScript() {
return new Promise((resolve, reject) => {
this._gaScript = document.createElement('script');
this._gaScript.type = 'text/javascript';
this._gaScriptContent = document.createTextNode(GoogleAnalytics._returnScriptWithFeatures());
this._gaScript.appendChild(this._gaScriptContent);
resolve((this._communicate = GoogleAnalytics.TRANSLATION_SCRIPT_SUCCEEDED));
reject((this._communicate = GoogleAnalytics.TRANSLATION_SCRIPT_FAILED));
});
}
/**
* Inserts GA library after the GA script created by _createGAScript().
* @private
*/
private _insertGALibrary() {
this._gaLibrary = DomMethods.insertScript('head', GoogleAnalytics.GA_SCRIPT_SRC);
this._gaLibrary.async = true;
document.head.appendChild(this._gaLibrary);
}
/**
* Appends GA script if it has been successfully created by __createGAScript().
* @private
*/
private _insertGAScript() {
return new Promise((resolve, reject) => {
document.head.appendChild(this._gaScript);
resolve((this._communicate = GoogleAnalytics.TRANSLATION_SCRIPT_APPENDED));
reject((this._communicate = GoogleAnalytics.TRANSLATION_SCRIPT_APPENDED_FAILURE));
});
}
}
export default GoogleAnalytics;
|
Java
|
UTF-8
| 241 | 1.664063 | 2 |
[] |
no_license
|
package samples.demo;
public class GitTest {
@SuppressWarnings("unused")
private String gigi;
public void Gigi() {
gigi = "git is fun";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
|
JavaScript
|
UTF-8
| 2,442 | 2.59375 | 3 |
[] |
no_license
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
function Task(props) {
const divStyles = {
// 'width': '20px',
'height': '20px',
'line-height': '20px',
'background-color': 'gray',
'border': '1px solid black',
'padding': '3px',
'margin': '5px',
'text-align': 'center',
};
return (
<div style={divStyles}>
{props.task.name}
</div>
)
}
class Queue extends React.Component {
render() {
const divStyles = {
'width': '200px',
'border': '1px solid black',
'border-top': 'none',
'padding': '3px',
'margin': '5px',
'text-align': 'center',
};
return (
<div className="queue" style={divStyles}>
<div>
{
this.props.tasks.map(
function(object, i){
return <Task task={object} />;
}
)
}
</div>
</div>
)
}
}
class WorkerInstance extends React.Component {
render() {
return (
<div>
<Task task={this.props.currentTask} />
</div>
)
}
}
function randomTask() {
var task = {};
task.id = String(Math.floor(Math.random() * 1000000000));
task.name = "Task " + task.id;
return task
}
class App extends React.Component {
constructor(props) {
super(props);
const tasks = [
randomTask(),
randomTask(),
randomTask(),
randomTask(),
randomTask(),
randomTask(),
randomTask(),
randomTask(),
randomTask(),
randomTask(),
randomTask(),
randomTask(),
];
this.state = {
tasks: tasks,
currentTask: randomTask(),
};
}
render() {
return (
<div className="app">
<Queue
tasks={this.state.tasks}
/>
<WorkerInstance
currentTask={this.state.currentTask}
/>
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
JavaScript
|
UTF-8
| 2,150 | 2.828125 | 3 |
[] |
no_license
|
//// Paul Irish requestAnimationFrame Polyfill
//// http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
//window.requestAnimFrame = (function(){
// return window.requestAnimationFrame ||
// window.webkitRequestAnimationFrame ||
// window.mozRequestAnimationFrame ||
// function( callback ){
// window.setTimeout(callback, 1000 / 60);
// };
//})();
//
//$(function() {
//
////freqAnalyser('http://10.153.0.30/files/import/video_91bee58b2fb9b23e13c43dee7d3836e5.mp3');
//
//
//// draw the analyser to the canvas
//function freqAnalyser(src) {
// var audioVisual = document.getElementById('audio-visual');
// console.log(audioVisual);
// // canvas stuff
// var canvas = document.getElementById('c');
// canvas_context = canvas.getContext('2d');
//
// // audio stuff
// var audio = new Audio();
// var audioSrc = src;
// audio.src = audioSrc;
// audio.controls = true;
// audio.autoplay = true;
// audio.id = 'a';
// audioVisual.appendChild(audio);
//
// // analyser stuff
// var context = new webkitAudioContext();
// var analyser = context.createAnalyser();
// analyser.fftSize = 2048;
//
// // connect the stuff up to eachother
// var source = context.createMediaElementSource(audio);
// source.connect(analyser);
// analyser.connect(context.destination);
// window.requestAnimFrame(freqAnalyser);
// var sum;
// var average;
// var bar_width;
// var scaled_average;
// var num_bars = 60;
// var data = new Uint8Array(2048);
// analyser.getByteFrequencyData(data);
//
// // clear canvas
// canvas_context.clearRect(0, 0, canvas.width, canvas.height);
// var bin_size = Math.floor(data.length / num_bars);
// for (var i = 0; i < num_bars; i += 1) {
// sum = 0;
// for (var j = 0; j < bin_size; j += 1) {
// sum += data[(i * bin_size) + j];
// }
// average = sum / bin_size;
// bar_width = canvas.width / num_bars;
// scaled_average = (average / 256) * canvas.height;
// canvas_context.fillRect(i * bar_width, canvas.height, bar_width - 2, - scaled_average);
// }
//}
//});
|
Ruby
|
UTF-8
| 1,999 | 2.5625 | 3 |
[] |
no_license
|
require File.dirname(__FILE__) + "/ebay_items_details_parser_data"
class EbayItemsDetailsParser
include EbayItemsDetailsParserData
def self.parse(xml)
parsed_items = CobraVsMongoose.xml_to_hash(xml)
items = parsed_items[GETMULTIPLEITEMSRESPONSE][ITEM] || []
items = ArrayUtil.arrayifiy(items)
ebay_items = []
items.each do |item|
if (item['BidCount']['$'].to_i > 0)
parsed_specifics = extract_value(ITEMSPECIFICS, item)
begin
ebay_items << EbayItemData.new(
:description => extract_value(DESCRIPTION, item),
:itemid => extract_value(ITEMID, item),
:endtime => extract_value(ENDTIME, item),
:starttime => extract_value(STARTTIME, item),
:url => extract_value(URL, item),
:galleryimg => extract_value(IMAGE, item),
:bidcount => extract_value(BIDCOUNT, item),
:price => extract_value(PRICE, item),
:sellerid => extract_value(USERID, item[SELLER]),
:title => extract_value(TITLE, item),
:country => extract_value(COUNTRY, item),
:pictureimgs => extract_value(PICTURE, item),
:currencytype => extract_value(CURRENCY_ID, item[PRICE]),
:size => parsed_specifics[RECORDSIZE],
:subgenre => parsed_specifics[SUBGENRE],
:genre => parsed_specifics[GENRE],
:condition => parsed_specifics[CONDITION],
:speed => parsed_specifics[SPEED])
rescue Exception => e
puts "problem with itemid: #{extract_value(ITEMID, item)}"
puts e
end
end
end
ebay_items
end
private
def self.extract_value(field, node)
#TODO: please tear out exception handling!! or test something like it
begin
VALUE_EXTRACTOR[field].call(node[field])
rescue Exception => e
puts "problem with nil field: #{field} node: #{node}"
raise e
end
end
end
|
C
|
UTF-8
| 424 | 3.296875 | 3 |
[
"MIT"
] |
permissive
|
#include<stdio.h>
int main()
{
double n;
scanf("%lf",&n);
if(n<0 || n>100){
printf("Fora de intervalo\n");
}
else if(n<=25.00){
printf("Intervalo [0,25]\n");
}
else if(n<=50.0){
printf("Intervalo (25,50]\n");
}
else if(n<=75.0){
printf("Intervalo (50,75]\n");
}
else if(n<=100.0){
printf("Intervalo (75,100]\n");
}
return 0;
}
|
JavaScript
|
UTF-8
| 895 | 2.5625 | 3 |
[] |
no_license
|
import { FORM_TYPE} from './FormType';
const initialState ={
userData : {}
// fname : '',
// lname: '',
// email : '',
// password : '',
// contact : ''
}
const formAppReducer= (state=initialState, action) => {
switch(action.type){
/* case DETAILS:
{
fname= this.state.fname,
lname= this.state.lname,
email=this.state.email,
password=this.state.password,
contact=this.state.contact
} */
case FORM_TYPE.DETAILS:
return {
...state,
userData : action.payload
// fname : action.payload,
// lname : state.lname,
// email : state.email,
// password : state.password,
// contact : state.contact
}
default:
return state;
}
}
export default formAppReducer;
|
C#
|
UTF-8
| 246 | 3.078125 | 3 |
[] |
no_license
|
public class Solution
{
public int Divide (int dividend, int divisor)
{
try
{
return dividend / divisor;
}
catch (OverflowException)
{
return int.MaxValue;
}
}
}
|
C++
|
UTF-8
| 750 | 3.546875 | 4 |
[] |
no_license
|
#include "misc.h"
/*
* Validate if a given string can be interpreted as a decimal number.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
" -90e3 " => true
" 1e" => false
"e3" => false
" 6e-1" => true
" 99e2.5 " => false
"53.5e93" => true
" --6 " => false
"-+3" => false
"95a54e53" => false
Note: It is intended for the problem statement to be ambiguous.
You should gather all requirements up front before implementing one.
However, here is a list of characters that can be in a valid decimal number:
Numbers 0-9
Exponent - "e"
Positive/negative sign - "+"/"-"
Decimal point - "."
Of course, the context of these characters also matters in the input.
*/
bool isNumber(string s) {
return false;
}
|
JavaScript
|
UTF-8
| 2,088 | 2.671875 | 3 |
[] |
no_license
|
function closeDown () {
document.querySelector('.bigCards')
.style.display = "none";
document.querySelector('#basePrice')
.style.display = "none";
document.querySelector('#proPrice')
.style.display = "none";
document.querySelector('#betaProg')
.style.display = "none";
document.querySelector('#faq')
.style.display = "none";
document.querySelector('#support')
.style.display = "none";
document.querySelector('#contactUs')
.style.display = "none";
}
window.onclick = function(event) {
if (event.target.className === "closeBtn") {
closeDown();
}
};
document.querySelector('.basePrice')
.addEventListener('click', function () {
document.querySelector('.bigCards')
.style.display = "flex";
document.querySelector('#basePrice')
.style.display = "block";
});
document.querySelector('.proPrice')
.addEventListener('click', function () {
document.querySelector('.bigCards')
.style.display = "flex";
document.querySelector('#proPrice')
.style.display = "block";
});
document.querySelector('.betaProg')
.addEventListener('click', function () {
document.querySelector('.bigCards')
.style.display = "flex";
document.querySelector('#betaProg')
.style.display = "block";
});
document.querySelector('.faq')
.addEventListener('click', function () {
document.querySelector('.bigCards')
.style.display = "flex";
document.querySelector('#faq')
.style.display = "block";
});
document.querySelector('.support')
.addEventListener('click', function () {
document.querySelector('.bigCards')
.style.display = "flex";
document.querySelector('#support')
.style.display = "block";
});
document.querySelector('.contactUs')
.addEventListener('click', function () {
document.querySelector('.bigCards')
.style.display = "flex";
document.querySelector('#contactUs')
.style.display = "block";
});
|
C
|
UTF-8
| 2,901 | 2.75 | 3 |
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* write_precisions.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nireznik <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/05/20 10:18:43 by nireznik #+# #+# */
/* Updated: 2020/05/20 10:18:43 by nireznik ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static void write_spaces(t_mystruct *box, long long x, char c)
{
while (x > 0)
{
writechar(c, box);
x--;
}
}
void writechar_preciz(char c, t_mystruct *box, t_preciz *preciz)
{
if (!preciz->dash)
write_spaces(box, preciz->left_nb - 1, ' ');
writechar(c, box);
if (preciz->dash)
write_spaces(box, preciz->left_nb - 1, ' ');
}
void writestring_preciz(char *str, t_mystruct *box, t_preciz *preciz)
{
unsigned long x;
x = preciz->left_nb - min(ft_strlen(str), preciz->right_nb);
if (!preciz->dash)
write_spaces(box, x, ' ');
writestring(str, box, preciz->right_nb);
if (preciz->dash)
write_spaces(box, x, ' ');
}
void writeint_preciz(long long x, t_mystruct *box, t_preciz *preciz)
{
int zero;
int spaces;
zero = (preciz->zero && preciz->right_nb == -1);
spaces = preciz->left_nb - (preciz->right_nb != -1 ?
max(preciz->right_nb, ft_intlen(x)) : ft_intlen(x));
if (x < 0 && zero)
writechar('-', box);
if (!preciz->dash)
write_spaces(box, spaces, zero ? '0' : ' ');
if (x < 0 && !zero)
writechar('-', box);
if (x < 0)
write_spaces(box, preciz->right_nb - ft_intlen(x) + 1, '0');
else
write_spaces(box, preciz->right_nb - ft_intlen(x), '0');
if (!preciz->point || preciz->zero || preciz->dash || preciz->star || (preciz->point && x != 0))
writeint(x, box);
if (preciz->dash)
write_spaces(box, spaces, ' ');
}
void writehexa_preciz(unsigned long long x, t_mystruct *box,
t_preciz *preciz, const char *content)
{
int pointeur;
int p_value;
pointeur = content[box->x] == 'p';
p_value = pointeur ? 2 : 0;
if (x == 0 && pointeur)
{
writestring("(nil)", box, 5);
return ;
}
if (!preciz->dash)
write_spaces(box, preciz->left_nb - ft_hexalen(x) - p_value,
preciz->zero ? '0' : ' ');
if (pointeur)
writestring("0x", box, 2);
write_spaces(box, preciz->right_nb - ft_hexalen(x) - p_value, '0');
writehexa(x, box, content);
if (preciz->dash)
write_spaces(box, preciz->left_nb - ft_hexalen(x) - p_value, ' ');
}
|
Markdown
|
UTF-8
| 4,388 | 3.109375 | 3 |
[] |
no_license
|
---
title: Nuxt Introduction
description: Learn how Nuxt and Vue are related and how they work together.
---
## What is NuxtJS
NuxtJS is a standardization tool that is built off of VueJS. The official [NuxtJS Website](https://nuxtjs.org/) will explain this in better detail, but here is a summary of what Nuxt standardizes for us.
1. Routing and navigation
2. Directory structure
3. Build process
These three items may not seem like much, but in reality they can greatly simplify the process of building a web application.
<question-answer q="What is a build process and why do we use it?">
A build process looks at your code and performs some operations on it to prepare it for consumption and production use. Most often a build process is used for transpilation, converting your code from one state to the next.
For example, TypeScript must be converted to JavaScript before it will run.
</question-answer>
## Getting Started
For the latest, see https://nuxtjs.org/docs/2.x/get-started/installation.
1. Open a terminal and navigate to the parent directory for your project.
2. Run `npm init nuxt-app <project-name>`
3. Answer the prompts (information on those below).
4. Wait for installation to complete.
### NuxtJS Prompts
There are several questions that the Nuxt initialization will ask you. Here are a few of those and what they do.
**Yarn or Npm**
- NPM is the Node Package Manager that comes bundled with node.
- Both do essentially the same thing but in slightly different ways.
- Yarn was developed to address deficiencies in NPM, but it's development lead to great improvements in NPM so that they are both highly competive.
**UI Frameworks**
These are Vue libraries that add some nice UI components. Selecting one here will reduce installing and setup work. You can look each of these up using Google.
Vuetify is probably the most popular and uses a material design and has great accessiblity support.
In my opinion Element UI is nice looking.
**Nuxt.js Modules**
- Axios will let you use the axios library to make AJAX calls. If you don't use this, Nuxt has a built in ajax library that is accessible with the `$http` property.
- Progressive Web App refers to applications that act more like native applications. This provides system notifications, gps, etc.
- Content is used for creating a static content website from Markdown docs.
**Linting Tools**
These are used to help you have consistent formatting with your code. For professional projects I highly recommend them. For learning I recommend avoiding them because it will further complicate what you need to do for your builds.
**Testing Tools**
These are tools for testing your font-end browser code.
**Rendering Mode**
- Universal (SSR / SSG) is a mode that serves your static files and API endpoints from a single server. It also allows for first page renders to happen server side and additions to happen client side. Overall this simplifies development but it requires more expensive server hardware to run.
- Single Page App is a mode where all rending happens on the browser. This makes for less expensive servers but it does add complexity when making calls to your API.
## A REST API with NuxtJs
Most of what Nuxt brings is for front-end browser development, but it also has an option for running a server so that you can create a REST API. For details, see https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-servermiddleware/#custom-api-endpoint.
1. Create an `/api` directory at the root of your Nuxt app.
2. Create the file `/api/index.ts` with this content:
```ts
import express from 'express'
import path from 'path'
// Create express instance
const app = express()
// Create a simple logging middleware
app.use((req, res, next) => {
console.log(req.method.toUpperCase() + ' ' + req.path)
next()
})
// Require API routes
const users = require('./routes/users')
// Import API Routes
app.use(users)
// Export express app
module.exports = app
// Start standalone server if directly running
if (require.main === module) {
const port = process.env.PORT || 3001
app.listen(port, () => {
console.log(`API server listening on port ${port}`)
})
}
```
3. Open the `nuxt.config.js` file and add this section:
```js
{
serverMiddleware: [
{ path: '/api', handler: '~/api' }
]
}
```
|
JavaScript
|
UTF-8
| 1,580 | 3.125 | 3 |
[
"MIT"
] |
permissive
|
window.onload = function() {
var points = [],
offset = 0,
scaleFactor = .35;
init();
function init() {
chaos.init();
offset = chaos.height / 2;
points.push({
x: 0,
y: chaos.height / 2
});
points.push({
x: chaos.width,
y: chaos.height / 2
});
drawCoast();
document.body.addEventListener("keyup", function(event) {
// console.log(event.keyCode);
switch(event.keyCode) {
case 32: // space
iterate();
drawCoast();
break;
case 80: // p
chaos.popImage();
break;
default:
break;
}
});
}
function drawCoast() {
var length = 0;
chaos.clear();
chaos.context.lineWidth = 2;
chaos.context.beginPath();
chaos.context.moveTo(points[0].x, points[0].y);
for(var i = 1; i < points.length; i += 1) {
chaos.context.lineTo(points[i].x, points[i].y);
length += measureLine(points[i], points[i - 1]);
}
chaos.context.stroke();
length = Math.round(length * 10) / 10;
console.log(length);
}
function iterate() {
var newPoints = [];
for(var i = 0; i < points.length - 1; i += 1) {
var p0 = points[i],
p1 = points[i + 1],
newPoint = {
x: (p0.x + p1.x) / 2,
y: (p0.y + p1.y) / 2
};
newPoint.x += Math.random() * offset * 2 - offset;
newPoint.y += Math.random() * offset * 2 - offset;
newPoints.push(p0, newPoint);
}
newPoints.push(points[points.length - 1]);
points = newPoints;
offset *= scaleFactor;
}
function measureLine(p0, p1) {
var dx = p1.x - p0.x,
dy = p1.y - p0.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
|
JavaScript
|
UTF-8
| 191 | 3.625 | 4 |
[] |
no_license
|
function getLengthOfTwoWords(word1, word2) {
// your code here
return sum = word1.length + word2.length;
}
var output = getLengthOfTwoWords('some', 'words');
console.log(output); // --> 9
|
Python
|
UTF-8
| 1,366 | 2.625 | 3 |
[] |
no_license
|
from tkinter import*
import sys
import random
def rand_pass():
x=''.join(random.choices('asdfghjklçzxcvbnmqwertyuiop0123456789!@#$%*()',k=int(sb.get())))
y=e.get("1.0",END)
with open("/home/loukis/D:/Desenvolvimento_de_sistemas/0/senhas.txt") as f:
a=f.readlines()
b=e.get("1.0",END)[:-1]
c=True
for i in a:
if b == i.rsplit(maxsplit=1)[0][:-1]:
c=False
d=i.rsplit(maxsplit=1)
d[1]=x
a[a.index(i)]=' '.join(d) +'\n'
if c:
ab=open("/home/loukis/D:/Desenvolvimento_de_sistemas/0/senhas.txt", 'a')
ab.write(b+': '+x+'\n')
ab.close()
else:
ab=open("/home/loukis/D:/Desenvolvimento_de_sistemas/0/senhas.txt", 'w')
ab.writelines(a)
ab.close()
janela.clipboard_clear()
janela.clipboard_append(x)
janela.update()
l['text']=x
janela = Tk()
janela.title("Gerador de senhas")
janela.geometry("350x120")
v0=Label(janela);v0.pack()
frame = Frame(janela);frame.pack()
e = Text(frame, height=1, width=35, borderwidth=2)
e.grid(row=0,column=0)
l=Label(frame, text="''")
l.grid(row=1,column=0)
bt= Button(frame, text="gerar", command=rand_pass)
bt.grid(row=2,column=0)
sb = Spinbox(frame, from_=0, to=40, width=3)
sb.delete(0,"end")
sb.insert(0,16)
sb.grid(row=2,column=0,sticky='e')
janela.mainloop()
|
Markdown
|
UTF-8
| 688 | 2.59375 | 3 |
[] |
no_license
|
这个脚本是最近写的比较长的脚本了,用python去查询、修改系统中json串,本质上就是:
1. 可执行文件的调用
2. json和字符串的处理
但是,写完这个总结几个之前没接触过的点:
1. 程序启动的参数解析,竟然有自带的库,而且还十分好用!!!
2. 调用可执行文件的传送,要注意使用多转译一次,我用了一个小技巧,借助json库进行
3. 调用可执行文件时,要根据的输出情况和是否同步等待,决定自己用os还是subprocess
4. 对python一切皆对象有了较多的认识,python一切皆对象的更彻底,看上去像基础类型的int其实也是对象
|
Python
|
UTF-8
| 1,800 | 3.640625 | 4 |
[] |
no_license
|
class Solution:
# my sol1, using dict
# def __init__(self):
# self.dic = set()
# def isHappy(self, n):
# """
# :type n: int
# :rtype: bool
# """
# if n == 1:
# return True
# if n in self.dic:
# return False
# else:
# self.dic.add(n)
# res = 0
# while n > 0:
# res += (n % 10)**2
# n = n // 10
# return self.isHappy(res)
# sol 1.1 using dict, but more elegant(no recursion)
#from https://leetcode.com/problems/happy-number/discuss/56915/My-Python-Solution
# def isHappy(self, n):
# dic = set()
# while n!= 1:
# n = sum( (int(i) ** 2) for i in str(n))
# if n in dic:
# return False
# else:
# dic.add(n)
# return True
# sol2, not using dict, Floyd Cycle detection algorithm
# from https://leetcode.com/problems/happy-number/discuss/56917/My-solution-in-C(-O(1)-space-and-no-magic-math-property-involved-)
def isHappy(self, n):
def square_sum( n):
res = 0
while n > 0:
res += (n % 10) ** 2
n = n // 10
return res
slow = n
fast = square_sum(n)
while( slow != fast ):
slow = square_sum(slow)
fast = square_sum(square_sum(fast))
if slow == 1:
return True
else:
return False
# math proof of repeat in this problem
#https://leetcode.com/problems/happy-number/discuss/56919/Explanation-of-why-those-posted-algorithms-are-mathematically-valid
|
PHP
|
UTF-8
| 586 | 2.796875 | 3 |
[] |
no_license
|
<?php
namespace amzeker\parser;
class Parser implements ParserInterface
{
public function process(string $tag, string $url): array
{
$htmlpage = file_get_contents($url);
if ($htmlpage === false ) {
return ['Invalid URL'];
}
// Regular expression
preg_match('/<' .$tag . '.*?>(.*?)<\/' . $tag . '>/a', $htmlpage, $strings);
if (empty($strings[1])) {
return ['There are no such tags on the page'];
}
}
public function test()
{
// feature
}
}
?>
|
Markdown
|
UTF-8
| 423 | 3.5625 | 4 |
[] |
no_license
|
判断元素是否在列表
```python
nums = [1, 2, 3]
if 0 in nums:
print("True")
else:
print("False")
```
判断子字符串是否在文本中
```python
sentence = "我爱天安门"
if "天安门" in sentence:
print("true")
else:
print("false")
```
判断字典中是否含有某元素
```python
data = {"name": "li", "age": 3}
if 'age' in data:
print("True")
else:
print("False")
```
|
Python
|
UTF-8
| 2,704 | 3.4375 | 3 |
[] |
no_license
|
'''
Use case example:
INPUT bmhnYnpuZ3ZiYXZmbmpyZmJ6cg==
KEY 13
DECODED nhgbzngvbavfnjrfbzr
DECRYPTED automationisawesome
'''
import string
import base64
import argparse
from argparse import RawTextHelpFormatter
# === GLOBAL VARS ===
useless_bar = 50 * "="
# === FUNCTIONS DEFINITION ===
def rot_cipher(input_text, shift):
alphabet = string.ascii_lowercase
shifted_alphabet = alphabet[shift:] + alphabet[:shift]
table = string.maketrans(alphabet, shifted_alphabet)
return input_text.translate(table)
def encode_b64(text, encode):
if encode is None:
return text
if encode:
return base64.urlsafe_b64encode(text.encode("utf-8"))
else:
return base64.b64decode(text)
def arguments_definition():
parser = argparse.ArgumentParser(
formatter_class=RawTextHelpFormatter,
description=' Cipher/Decipher for binary 64 encoded or plain text.\n\
Examples:\n\
to encrypt and encode a text\n\
python rot_cipher.py automationisawesome --encrypt --encode --key 13\n\
to decrypt and decode a text:\n\
python rot_cipher.py bmhnYnpuZ3ZiYXZmbmpyZmJ6cg== --decrypt --decode --key 13\n')
parser.add_argument('input_text', type=str,
help="input string")
parser.add_argument('--encrypt', dest='to_encrypt', action='store_true',
help='encrypt input text with Caesar rotation algorithm')
parser.add_argument('--decrypt', dest='to_encrypt', action='store_false',
help='decrypt input text with Caesar rotation algorithm')
parser.set_defaults(to_encrypt=False)
parser.add_argument('--encode', dest='to_encode', action='store_true',
help='encode the text in base64 before encryption')
parser.add_argument('--decode', dest='to_encode', action='store_false',
help='decode the text from base64 before encryption')
parser.set_defaults(to_encode=None)
parser.add_argument('--key', dest='key', type=int,
help='number of rotations of the alphabet letters')
return parser
# === MAIN ===
if __name__ == "__main__":
parser = arguments_definition()
args = parser.parse_args()
print(useless_bar + "\n" + " THE ULTIMATE CLARANET CRYPTO CHALLENGE \n" + useless_bar + "\n")
if args.to_encrypt:
encrypted = rot_cipher(args.input_text, args.key)
out_text = encode_b64(encrypted, args.to_encode)
else:
decoded = encode_b64(args.input_text, args.to_encode)
out_text = rot_cipher(decoded, args.key)
print (" The final text is: {}".format(out_text))
|
Python
|
UTF-8
| 223 | 3.359375 | 3 |
[] |
no_license
|
class Abc(object):
def __init__(self):
self.s=""
def getString():
self.s=input("Enter:")
def printString():
print(self.s.upper())
obj = InputOutString()
obj.getString()
obj.printString()
|
Python
|
UTF-8
| 489 | 2.65625 | 3 |
[] |
no_license
|
n=int(input())
li=list(int(i)for i in input().split())
p=int(input())
dp=[-1]*(n)
s=set()
for i in range(p):
a,b=map(int,input().split())
a,b=a-1,b-1
if dp[a]==-1 and dp[b]==-1:
s.add(a+1)
s.add(b+1)
dp[a] , dp[b] = li[a]+li[b] , li[a]+li[b]
elif dp[a]==-1 and dp[b]>=0:
s.add(a+1)
dp[a] = max(dp[a],li[a]+li[b])
elif dp[a]>=0 and dp[b]==-1:
s.add(b+1)
dp[b] = max(dp[b],li[a]+li[b])
print(dp,s)
|
PHP
|
UTF-8
| 7,808 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
<?php
/**
* OpenWebPresence Support Library - openwebpresence.com
*
* @copyright 2001 - 2017, Brian Tafoya.
* @package OwpSettings
* @author Brian Tafoya <[email protected]>
* @version 1.0
* @license MIT
* @license https://opensource.org/licenses/MIT The MIT License
* @category OpenWebPresence_Support_Library
* @link http://openwebpresence.com OpenWebPresence
*
* Copyright (c) 2017, Brian Tafoya
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* This class provides settings data management functionality.
*/
class OwpSettings
{
/**
* @var array $settings_data Data storage array
*/
static protected $settings_data = array();
/**
* @var array $ezSqlDB Data storage array
*/
static public $ezSqlDB = array();
/**
* Constructor.
*
* @method mixed __construct()
* @access public
*/
function __construct()
{
$dotenv = new Dotenv\Dotenv(ROOT_PATH, '.env');
$dotenv->load();
$dotenv->required(['DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASS']);
/*
* Init the database class
*/
self::$ezSqlDB = new OwpDBMySQLi($_ENV["DB_USER"], $_ENV["DB_PASS"], $_ENV["DB_NAME"], $_ENV["DB_HOST"]);
self::$ezSqlDB->use_disk_cache = false;
self::$ezSqlDB->cache_queries = false;
self::$ezSqlDB->hide_errors();
self::loadSettings();
}//end __construct()
/**
* __debugInfo
*
* @method mixed __debugInfo()
* @access public
*
* @return mixed settings_data
*
* @author Brian Tafoya <[email protected]>
* @version 1.0
*/
public function __debugInfo()
{
return [
'settings_data' => self::$settings_data,
];
}//end __debugInfo()
/**
* __get
*
* @method mixed __get($itemName) Add mod data by key
* @access public
*
* @param string $itemName Mod data array key
*
* @return mixed Array value
*
* @throws InvalidArgumentException Mod data key does not exist, code 20
*
* @author Brian Tafoya <[email protected]>
* @version 1.0
*/
public function __get($itemName)
{
return self::getModDataItem($itemName);
}//end __get()
/**
* __isset
*
* @method mixed __isset($itemName) Add mod data by key
* @access public
*
* @param string $itemName Mod data array key
*
* @return boolean
*
* @author Brian Tafoya <[email protected]>
* @version 1.0
*/
public function __isset($itemName)
{
return isset(self::$settings_data[$itemName]);
}//end __isset()
/**
* __set
*
* @method mixed __set($itemName, $itemValue) Add mod data by key
* @access public
*
* @param string $itemName Mod data array key
* @param mixed $itemValue Mod data value
*
* @author Brian Tafoya <[email protected]>
* @version 1.0
*/
public function __set($itemName, $itemValue)
{
self::setModDataItem($itemName, $itemValue);
}//end __set()
/**
* __unset
*
* @method mixed __unset($itemName) Add mod data by key
* @access public
*
* @param string $itemName Mod data array key
*
* @author Brian Tafoya <[email protected]>
* @version 1.0
*/
public function __unset($itemName)
{
if(isset(self::$settings_data[$itemName])) {
self::deleteModDataItem($itemName);
}
}//end __unset()
/**
* deleteModDataItem
*
* @method mixed deleteModDataItem($itemName) Add mod data by key
* @access public
*
* @param string $itemName Mod data array key
* @return boolean Array value
* @throws Exception SQL exception
*
* @author Brian Tafoya <[email protected]>
* @version 1.0
*/
static public function deleteModDataItem($itemName)
{
self::$ezSqlDB->query('BEGIN');
self::$ezSqlDB->query("DELETE FROM tbl_settings WHERE tbl_settings.setting_name = '".self::$ezSqlDB->escape($itemName)."' LIMIT 1");
if (self::$ezSqlDB->query('COMMIT') !== false) {
self::loadSettings();
} else {
self::$ezSqlDB->query('ROLLBACK');
throw new Exception("SQL error while attempting to update ".$itemName.": ".self::$ezSqlDB->last_error);
}
return true;
}//end deleteModDataItem()
/**
* getModDataItem
*
* @method mixed getModDataItem($itemName) Add mod data by key
* @access public
*
* @param string $itemName Mod data array key
*
* @return mixed Array value
*
* @throws InvalidArgumentException Mod data key does not exist, code 20
*
* @author Brian Tafoya <[email protected]>
* @version 1.0
*/
static public function getModDataItem($itemName)
{
if(isset(self::$settings_data[$itemName])) {
return self::$settings_data[$itemName];
} else {
throw new InvalidArgumentException("Data item ".$itemName." does not exist.", 20);
}
}//end getModDataItem()
/**
* setModDataItem
*
* @method mixed setModDataItem($itemName, $itemValue) Add mod data by key
* @access public
*
* @param string $itemName Mod data array key
* @param mixed $itemValue Mod data value
* @throws Exception SQL exception
*
* @author Brian Tafoya <[email protected]>
* @version 1.0
*/
static public function setModDataItem($itemName, $itemValue)
{
self::$ezSqlDB->query('BEGIN');
self::$ezSqlDB->query(
"
REPLACE INTO tbl_settings
SET
tbl_settings.setting_name = '".self::$ezSqlDB->escape($itemName)."',
tbl_settings.setting_value = '".self::$ezSqlDB->escape(json_encode($itemValue))."',
tbl_settings.setting_last_updated = SYSDATE(),
tbl_settings.setting_last_updated_by_userID = 0
"
);
if (self::$ezSqlDB->query('COMMIT') !== false) {
self::loadSettings();
} else {
self::$ezSqlDB->query('ROLLBACK');
throw new Exception("SQL error while attempting to update ".$itemName.": ".self::$ezSqlDB->last_error);
}
}//end setModDataItem()
/**
* loadSettings
*
* @method mixed loadSettings() Add mod data by key
* @access private
*
* @author Brian Tafoya <[email protected]>
* @version 1.0
*/
static private function loadSettings()
{
$tmp = self::$ezSqlDB->get_results("SELECT * FROM tbl_settings ORDER BY tbl_settings.setting_name");
self::$settings_data = array();
if($tmp) {
foreach ($tmp as $t) {
self::$settings_data[$t->setting_name] = json_decode($t->setting_value, true);
}
}
}//end loadSettings()
}//end class
|
Markdown
|
UTF-8
| 1,580 | 2.515625 | 3 |
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
TOCTitle: Zmienianie konta usługi programu RMS
Title: Zmienianie konta usługi programu RMS
ms:assetid: 'f257d66d-b823-41e4-bcb7-7c90eb295238'
ms:contentKeyID: 18123501
ms:mtpsurl: 'https://technet.microsoft.com/pl-pl/library/Cc747736(v=WS.10)'
---
Zmienianie konta usługi programu RMS
====================================
Podczas instalacji program RMS tworzy na lokalnym komputerze grupę usługi programu RMS i udziela jej odpowiednich uprawnień do wszystkich zasobów, których wymaga działanie programu RMS. Podczas zastrzegania programu RMS na serwerze definiuje się konto usługi programu RMS przy użyciu konta domeny. Jako konta usługi programu RMS nie można użyć konta domeny, za pomocą którego instalowano program RMS. To konto staje się członkiem grupy usługi programu RMS i uzyskuje uprawnienia skojarzone z tą grupą. W normalnych warunkach program RMS działa na koncie usługi programu RMS.
Konto usługi programu RMS można zmienić w dowolnym momencie. W takim przypadku poprzednio określone konto jest automatycznie usuwane z grupy usługi programu RMS, a nowe konto staje się jej członkiem.
> [!Important]
> Ze względów bezpieczeństwa zaleca się utworzenie specjalnego konta użytkownika, które będzie używane wyłącznie jako konto usługi programu RMS i nie będzie służyło do innych celów. Ponadto kontu temu nie należy udzielać żadnych dodatkowych uprawnień.
> [!note]
> Jako konta usługi programu RMS nie można użyć konta domeny, za pomocą którego instalowano program RMS z dodatkiem Service Pack 1.
|
PHP
|
UTF-8
| 4,824 | 2.515625 | 3 |
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: javaci
* Date: 2020-08-30
* Time: 12:22
*/
define("IPORDOMAIN","");
define("USERNAME", "");
define("PASSHASH", "");
define("PRTG_ENABLED",true);
class Prtg
{
public $userName;
public $objId;
public function __construct($userName = "")
{
$this->userName = $userName;
}
public function getUserObjId()
{
if (!PRTG_ENABLED){
return false;
}
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://".IPORDOMAIN."/api/table.xml?content=sensors&columns=objid,group,device,sensor,status,message,lastvalue,priority,favorite&username=" . USERNAME . "&passhash=" . PASSHASH,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
));
$response = curl_exec($curl);
curl_close($curl);
$xml = new SimpleXMLElement($response);
$arr = (array)$xml;
$baseArray = array();
foreach ($arr["item"] as $item) {
$item = (array)$item;
if (strpos($item["sensor"], $this->userName) !== false) {
array_push($baseArray, $item);
}
}
if (isset($baseArray[0])) {
foreach ($baseArray as $item) {
if ($item["status_raw"] == "3" or $item["status_raw"] == 3){
$this->objId = $item["objid"];
return true;
}
}
$this->objId = $baseArray[count($baseArray) - 1 ]["objid"];
return true;
}
return false;
}
public function getUserGraphOnSvg($graphId = 0)
{
if (!PRTG_ENABLED){
return false;
}
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://".IPORDOMAIN."/chart.svg?type=graph&graphid=".$graphId."&width=1500&height=500&tooltexts=1&refreshable=true&columns=datetime%2Cvalue_%2Ccoverage&id=" . $this->objId . "&graphstyling=baseFontSize%3D%2710%27%20showLegend%3D%271%27&tooltexts=1" . $this->objId . "&username=" . USERNAME . "&passhash=" . PASSHASH,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
public function getAnaInternet($interface, $graphID,$type)
{
if (!PRTG_ENABLED){
return false;
}
$id = "";
if ($interface == "sfp"){
$id = 2027;
}
if ($interface == "nida"){
$id= 2030;
}
$curl = curl_init();
$urlStr = "http://".IPORDOMAIN."//chart.svg?type=graph&graphid=".$graphID."&width=1500&height=500&tooltexts=1&refreshable=true&columns=datetime%2Cvalue_%2Ccoverage&_=1591881406779&id=" .$id."&hide=&tooltexts=1&username=" . USERNAME . "&passhash=" . PASSHASH;
if ($type == "url"){
return "<br><a href=\"".$urlStr."\" target='_blank'> <button class='btn btn-success'> Büyüt </button></a>";
}
// echo $urlStr."\n";
curl_setopt_array($curl, array(
CURLOPT_URL => $urlStr,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
public function getUserInternet($graphID, $userName )
{
if (!PRTG_ENABLED){
return false;
}
$this->userName = $userName;
$this->getUserObjId();
return $this->getUserGraphOnSvg($graphID);
}
/**
* @return string
*/
public function getUserName(): string
{
return $this->userName;
}
/**
* @param string $userName
*/
public function setUserName(string $userName): void
{
$this->userName = $userName;
}
/**
* @return mixed
*/
public function getObjId()
{
return $this->objId;
}
/**
* @param mixed $objId
*/
public function setObjId($objId): void
{
$this->objId = $objId;
}
}
|
C++
|
UTF-8
| 4,480 | 2.796875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sdk_util/thread_pool.h"
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include "sdk_util/auto_lock.h"
namespace sdk_util {
#ifdef __APPLE__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#endif
// Initializes mutex, semaphores and a pool of threads. If 0 is passed for
// num_threads, all work will be performed on the dispatch thread.
ThreadPool::ThreadPool(int num_threads)
: threads_(NULL), counter_(0), num_threads_(num_threads), exiting_(false),
user_data_(NULL), user_work_function_(NULL) {
if (num_threads_ > 0) {
int status;
status = sem_init(&work_sem_, 0, 0);
if (-1 == status) {
fprintf(stderr, "Failed to initialize semaphore!\n");
exit(-1);
}
status = sem_init(&done_sem_, 0, 0);
if (-1 == status) {
fprintf(stderr, "Failed to initialize semaphore!\n");
exit(-1);
}
threads_ = new pthread_t[num_threads_];
for (int i = 0; i < num_threads_; i++) {
status = pthread_create(&threads_[i], NULL, WorkerThreadEntry, this);
if (0 != status) {
fprintf(stderr, "Failed to create thread!\n");
exit(-1);
}
}
}
}
// Post exit request, wait for all threads to join, and cleanup.
ThreadPool::~ThreadPool() {
if (num_threads_ > 0) {
PostExitAndJoinAll();
delete[] threads_;
sem_destroy(&done_sem_);
sem_destroy(&work_sem_);
}
}
// Setup work parameters. This function is called from the dispatch thread,
// when all worker threads are sleeping.
void ThreadPool::Setup(int counter, WorkFunction work, void *data) {
counter_ = counter;
user_work_function_ = work;
user_data_ = data;
}
// Return decremented task counter. This function
// can be called from multiple threads at any given time.
int ThreadPool::DecCounter() {
return AtomicAddFetch(&counter_, -1);
}
// Set exit flag, post and join all the threads in the pool. This function is
// called only from the dispatch thread, and only when all worker threads are
// sleeping.
void ThreadPool::PostExitAndJoinAll() {
exiting_ = true;
// Wake up all the sleeping worker threads.
for (int i = 0; i < num_threads_; ++i)
sem_post(&work_sem_);
void* retval;
for (int i = 0; i < num_threads_; ++i)
pthread_join(threads_[i], &retval);
}
// Main work loop - one for each worker thread.
void ThreadPool::WorkLoop() {
while (true) {
// Wait for work. If no work is available, this thread will sleep here.
sem_wait(&work_sem_);
if (exiting_) break;
while (true) {
// Grab a task index to work on from the counter.
int task_index = DecCounter();
if (task_index < 0)
break;
user_work_function_(task_index, user_data_);
}
// Post to dispatch thread work is done.
sem_post(&done_sem_);
}
}
// pthread entry point for a worker thread.
void* ThreadPool::WorkerThreadEntry(void* thiz) {
static_cast<ThreadPool*>(thiz)->WorkLoop();
return NULL;
}
// DispatchMany() will dispatch a set of tasks across worker threads.
// Note: This function will block until all work has completed.
void ThreadPool::DispatchMany(int num_tasks, WorkFunction work, void* data) {
// On entry, all worker threads are sleeping.
Setup(num_tasks, work, data);
// Wake up the worker threads & have them process tasks.
for (int i = 0; i < num_threads_; i++)
sem_post(&work_sem_);
// Worker threads are now awake and busy.
// This dispatch thread will now sleep-wait for the worker threads to finish.
for (int i = 0; i < num_threads_; i++)
sem_wait(&done_sem_);
// On exit, all tasks are done and all worker threads are sleeping again.
}
#ifdef __APPLE__
#pragma clang diagnostic pop
#endif
// DispatchHere will dispatch all tasks on this thread.
void ThreadPool::DispatchHere(int num_tasks, WorkFunction work, void* data) {
for (int i = 0; i < num_tasks; i++)
work(i, data);
}
// Dispatch() will invoke the user supplied work function across
// one or more threads for each task.
// Note: This function will block until all work has completed.
void ThreadPool::Dispatch(int num_tasks, WorkFunction work, void* data) {
if (num_threads_ > 0)
DispatchMany(num_tasks, work, data);
else
DispatchHere(num_tasks, work, data);
}
} // namespace sdk_util
|
C++
|
UTF-8
| 337 | 3.53125 | 4 |
[] |
no_license
|
//(7.12)Implicit conversions of reference parameters
#include <iostream>
void double_it(double &it) { it *= 2; }
void print_it(const double &it) { std::cout << it << std::endl; }
int main() {
double d{123};
double_it(d);
print_it(d);
int i{456};
// double_it(i); /* error, does not compile! */
print_it(i);
}
|
C++
|
UTF-8
| 1,218 | 3.734375 | 4 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
node* next;
};
node* head = NULL;
void insert_end(int d)
{
node* new_node = new node;
new_node -> data = d;
new_node -> next = NULL;
if(head == NULL)
{
head = new_node;
}
else
{
node* t = head;
while(t -> next != NULL)
{
t = t -> next;
}
t -> next = new_node;
}
}
void insert_begin(int d)
{
node* new_node = new node;
new_node -> data = d;
new_node -> next = head;
head = new_node;
}
void deletee_end()
{
if(head==NULL)
cout<<"List is empty."<<endl;
else
{
node* t = head;
while(t->next->next != NULL)
{
t = t->next;
}
node* tmp = t -> next;
cout<<"Element deleted:"<<tmp -> data<<endl;
t -> next = NULL;
free(tmp);
}
}
void deletee_begin()
{
if(head == NULL)
cout<<"List is empty."<<endl;
else
{
node* tmp = head;
head = tmp->next;
free(tmp);
}
}
void print()
{
node* t = head;
while(t != NULL)
{
cout<<t->data<<" ";
t = t->next;
}
cout<<endl;
}
int main()
{
insert_end(1);
insert_end(2);
insert_end(3);
print();
deletee_end();
print();
insert_begin(4);
print();
insert_begin(5);
print();
insert_end(6);
print();
deletee_begin();
print();
return 0;
}
|
Java
|
UTF-8
| 551 | 3.125 | 3 |
[] |
no_license
|
public class Game{
private Prog06 word = new Prog06();
private Prog07 ball = new Prog07();
private Prog08 tic = new Prog08();
public void run(String i){
if (i.equals("Word Guess"))
word.run();
else if (i.equals("Baseball"))
ball.run();
else if (i.equals("Tic-Tac-Toe"))
tic.run();
}
public Prog06 getWord() {
return word;
}
public Prog07 getBall() {
return ball;
}
public Prog08 getTic() {
return tic;
}
}
|
PHP
|
UTF-8
| 10,903 | 2.640625 | 3 |
[] |
no_license
|
<?php
//セッション開始
if(!isset($_SESSION)){
session_start();
}
//XSS対策
function h($str) {
return htmlspecialchars($str, ENT_QUOTES, "UTF-8");
}
//性別
if($_SESSION["gender"]==0){
$genderWord = "男性";
}else{
$genderWord = "女性";
}
//生活レベル
switch($_SESSION["level"]){
case 0:
$levelWord = "低い";
break;
case 1:
$levelWord = "やや低い";
break;
case 2:
$levelWord = "適度";
break;
case 3:
$levelWord = "高い";
break;
}
//目的
if($_SESSION["purpose"]==0){
$purposeWord = "減量";
}elseif($_SESSION["purpose"]==1){
$purposeWord = "維持";
}else{
$purposeWord = "増量";
}
?>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<!-- css -->
<link rel="stylesheet" href="../css/common.css" type="text/css">
<!-- font awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<title>PFCバランス計算app -登録内容確認-</title>
</head>
<body>
<div class="container">
<!--navbar-->
<header>
<div class="navbar navbar-default pt-3 mt-4">
<div class="container d-flex justify-content-between">
<div class="d-flex align-items-center text-black-50">
<a href="../index.php" class="toppage-link text-black-50 font-weight-light">
<i class="fas fa-carrot fa-lg"></i> PFC バランス計算 app
</a>
</div>
</div>
</div>
</header>
<main>
<!--タイトル-->
<div class="titles text-center text-black-50">
<h2>内容確認</h2>
<p>以下の内容でよろしければ<br class="br2">登録するボタンを押してください。</p>
</div>
<!--確認-->
<div class="contents text-muted bg-light">
<div class="container">
<div class="row">
<p class="col text-right">名前:</p>
<p class="col text-left"><?php echo h($_SESSION["name"]); ?> 様</p>
</div>
<div class="row">
<p class="col text-right">メールアドレス:</p>
<p class="col text-left"><?php echo h($_SESSION["email"]); ?></p>
</div>
<div class="row">
<p class="col text-right">パスワード:</p>
<p class="col text-left"><?php echo h($_SESSION["pass"]); ?></p>
</div>
<div class="row">
<p class="col text-right">年齢:</p>
<p class="col text-left"><?php echo $_SESSION["age"]; ?> 歳</p>
</div>
<div class="row">
<p class="col text-right">身長:</p>
<p class="col text-left"><?php echo $_SESSION["height"]; ?> cm</p>
</div>
<div class="row">
<p class="col text-right">体重:</p>
<p class="col text-left"><?php echo $_SESSION["weight"]; ?> kg</p>
</div>
<div class="row">
<p class="col text-right">性別:</p>
<p class="col text-left"><?php echo $genderWord; ?></p>
</div>
<div class="row">
<p class="col text-right">1日の活動レベル:</p>
<p class="col text-left"><?php echo $levelWord; ?></p>
</div>
<div class="row">
<p class="col text-right">目的:</p>
<p class="col text-left"><?php echo $purposeWord; ?></p>
</div>
<hr>
<!--計算結果-->
<p class="text-center mb-4">入力された内容から<br class="br2">あなたについて計算しました。</p>
<div class="row">
<p class="col text-right">BMI値:</p>
<p class="col text-left"><?php echo $_SESSION["bmi"]; ?></p>
</div>
<div class="row">
<p class="col text-right">基礎代謝量:</p>
<p class="col text-left"><?php echo $_SESSION["basal"]; ?> kcal/日</p>
</div>
<div class="row">
<p class="col text-right">消費エネルギー量:</p>
<p class="col text-left"><?php echo $_SESSION["burn"]; ?> kcal/日</p>
</div>
<hr>
<!--目標値-->
<p class="text-center mb-4">そして、以下があなたの摂取目標となる<br class="br2">エネルギー量、PFCバランスです。</p>
<div class="row">
<p class="col text-right">摂取エネルギー量:</p>
<p class="col text-left"><?php echo $_SESSION["targetCal"]; ?> kcal/日</p>
</div>
<div class="row">
<p class="col text-right">タンパク質:</p>
<p class="col text-left"><?php echo $_SESSION["targetP"]; ?> g/日</p>
</div>
<div class="row">
<p class="col text-right">脂質:</p>
<p class="col text-left"><?php echo $_SESSION["targetF"]; ?> g/日</p>
</div>
<div class="row">
<p class="col text-right">炭水化物(糖質):</p>
<p class="col text-left"><?php echo $_SESSION["targetC"]; ?> g/日</p>
</div>
<p class="text-center mt-5 mb-5">数値だけでは分かりにくいので<br class="br2">グラフをご用意しました。</p>
<!--グラフ-->
<div class="chart-container" style="position: relative; width:60%; height:60%; margin: 0 auto;">
<canvas id="targetChart"></canvas>
</div>
<!--登録ボタン-->
<form action = "check.php" method="post">
<p class="text-center bottom-btn my-5">
<button class="btn btn-secondary btn-lg mx-5 my-2" type="submit" name="back" value="戻る"> 戻る </button>
<button class="btn btn-success btn-lg mx-5 my-2" type="submit" name="next" value="登録する">登録する</button>
</p>
</form>
<hr>
<!--注意-->
<div class="notice text-left">
<p>
※計算結果はあくまで目安です。<br class="br2">無理なく続けられる範囲でバランスのとれた食事を<br class="br2">心がけましょう。
<br>※BMI値 =【体重(kg) ÷ 身長(m)の二乗】
<br>※基礎代謝量 =<br class="br2">『ハリス・ベネディクトの式(日本人用)』
<br>※消費エネルギー量 =<br class="br2">【基礎代謝量(kcal) × 1日の活動レベル<br class="br2">(低:1.3 やや低:1.5 適度:1.7 高:1.9)】
<br>※目標摂取エネルギー量 =<br class="br2">【消費エネルギー(kcal) × 目的<br class="br2">(減量:0.8 維持:1 増量:1.2)】
<br>※目標摂取pfcバランス =<br class="br1">【消費エネルギー(kcal) × 各栄養素バランス(%)<br class="br2">(P:20% F:30% C:50%)】
<br>(厚生労働省 日本人の食事摂取基準(2015年版)より)
</p>
</div>
</div>
</div>
</main>
</div>
<footer class="text-black-50">
<!--作成者-->
<div class="container">
<p class="float-left">
<small>作成者:テラシマ【<i class="fab fa-twitter"></i><a href="https://twitter.com/ssssssspgg" class="text-success">@ssssssspgg</a>】</small>
</p>
</div>
<!--トップへ-->
<div class="container">
<p class="float-right">
<a href="#" class="text-success">Back to top</a>
</p>
</div>
<br>
<br>
<br>
</footer>
<!--chart.js CDN(グラフ)-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.min.js"></script>
<script>
//目標摂取(kcal) と PFC量(g)
var targetCal = <?php echo $_SESSION["targetCal"]?>;
var targetP = <?php echo $_SESSION["targetP"]?>;
var targetF = <?php echo $_SESSION["targetF"]?>;
var targetC = <?php echo $_SESSION["targetC"]?>;
//PFC を (g)から(kcal)へ
var targetPcal = targetP * 4;
var targetFcal = targetF * 9;
var targetCcal = targetC * 4;
//PFC のカロリーにおける割合の算出
var targetPper = Math.round(targetPcal / targetCal * 100);
var targetFper = Math.round(targetFcal / targetCal * 100);
var targetCper = Math.round(targetCcal / targetCal * 100);
//パイチャート
var ctx = document.getElementById("targetChart");
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["P(タンパク質)", "F(脂質)", "C(炭水化物)"],
datasets: [{
data: [targetPper, targetFper, targetCper],//割合
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)'
],
borderWidth: 1
}]
},
options: {
maintainAspectRatio: false,
tooltips:{
callbacks:{
label: function (tooltipItem, data) {
//栄養素により1gあたりのkcalが違うので振り分け(小数点以下四捨五入されてる)
if(data.datasets[0].data[tooltipItem.index] == targetPper){
var targetGram = targetP;
}else if(data.datasets[0].data[tooltipItem.index] == targetFper){
var targetGram = targetF;
}else if(data.datasets[0].data[tooltipItem.index] == targetCper){
var targetGram = targetC;
}
//データ値の %〜g までを付け足す
return data.labels[tooltipItem.index]
+ ": "
+ data.datasets[0].data[tooltipItem.index]
+ " %"
+ " "
+ targetGram
+ " g";
}
}
}
}
});
</script>
<!--
BMI,(g) は小数点第一位以下四捨五入
(kcal),% は小数点以下四捨五入
-->
</body>
</html>
|
C#
|
UTF-8
| 4,088 | 2.578125 | 3 |
[] |
no_license
|
namespace ElTahmKench.Components.Spells
{
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using ElTahmKench.Enumerations;
using ElTahmKench.Utils;
using Aimtec;
using Aimtec.SDK;
using Aimtec.SDK.Prediction;
using Aimtec.SDK.Prediction.Skillshots;
/// <summary>
/// Base class for the spells.
/// </summary>
internal class ISpell
{
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="ISpell" /> class.
/// The initialize.
/// </summary>
[SuppressMessage("ReSharper", "DoNotCallOverridableMethodsInConstructor", Justification = "Input is known.")]
internal ISpell()
{
try
{
this.SpellObject = new Aimtec.SDK.Spell(this.SpellSlot, this.Range);
if (this.Targeted)
{
//this.SpellObject.SetTargetted(this.Delay, this.Speed);
}
else
{
this.SpellObject.SetSkillshot(
this.Delay,
this.Width,
this.Speed,
this.Collision,
this.SkillshotType);
}
}
catch (Exception e)
{
Logging.AddEntry(LoggingEntryType.Error, "@ISpell.cs: Can not initialize the base class - {0}", e);
throw;
}
}
#endregion
#region Properties
/// <summary>
/// Gets or sets a value indicating whether the spell is an AoE spell.
/// </summary>
[DefaultValue(false)]
internal virtual bool Aoe { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the spell has collision.
/// </summary>
[DefaultValue(false)]
internal virtual bool Collision { get; set; }
/// <summary>
/// Gets or sets the damage type.
/// </summary>
//internal virtual TargetSelector.DamageType DamageType { get; set; }
/// <summary>
/// Gets or sets the delay.
/// </summary>
internal virtual float Delay { get; set; }
/// <summary>
/// Gets or sets the range.
/// </summary>
internal virtual float Range { get; set; }
/// <summary>
/// Gets or sets the skillshot type.
/// </summary>
internal virtual SkillshotType SkillshotType { get; set; }
/// <summary>
/// Gets or sets the speed.
/// </summary>
internal virtual float Speed { get; set; }
/// <summary>
/// Gets or sets the spell object.
/// </summary>
internal Aimtec.SDK.Spell SpellObject { get; set; }
/// <summary>
/// Gets or sets the spell slot.
/// </summary>
internal virtual SpellSlot SpellSlot { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the spell is targeted.
/// </summary>
[DefaultValue(false)]
internal virtual bool Targeted { get; set; }
/// <summary>
/// Gets or sets the width.
/// </summary>
internal virtual float Width { get; set; }
#endregion
#region Methods
/// <summary>
/// The on on combo callback.
/// </summary>
internal virtual void OnCombo()
{
}
/// <summary>
/// The on last hit callback.
/// </summary>
internal virtual void OnLastHit()
{
}
/// <summary>
/// The on mixed callback.
/// </summary>
internal virtual void OnMixed()
{
}
/// <summary>
/// The on update callback.
/// </summary>
internal virtual void OnUpdate()
{
}
#endregion
}
}
|
Java
|
UTF-8
| 3,997 | 1.835938 | 2 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
* Copyright (c) 2016-2019 VMware, Inc. All Rights Reserved.
*
* This product is licensed to you under the Apache License, Version 2.0 (the "License").
* You may not use this product except in compliance with the License.
*
* This product may include a number of subcomponents with separate copyright notices
* and license terms. Your use of these subcomponents is subject to the terms and
* conditions of the subcomponent's license, as noted in the LICENSE file.
*/
package com.vmware.mangle.faults.plugin.tasks.helpers;
import java.util.List;
import org.pf4j.Extension;
import org.springframework.beans.factory.annotation.Autowired;
import com.vmware.mangle.cassandra.model.tasks.FaultTask;
import com.vmware.mangle.cassandra.model.tasks.SupportScriptInfo;
import com.vmware.mangle.cassandra.model.tasks.Task;
import com.vmware.mangle.cassandra.model.tasks.TaskType;
import com.vmware.mangle.faults.plugin.helpers.aws.AwsEC2FaultHelper;
import com.vmware.mangle.model.aws.faults.spec.AwsEC2FaultSpec;
import com.vmware.mangle.task.framework.helpers.AbstractCommandExecutionTaskHelper;
import com.vmware.mangle.task.framework.utils.TaskDescriptionUtils;
import com.vmware.mangle.utils.ICommandExecutor;
import com.vmware.mangle.utils.exceptions.MangleException;
/**
* @author bkaranam
*
* AWS EC2 specific fault Task implementation that delegates the creation of the injection
* commands, remediation commands and execution of each one of them
*/
@Extension(ordinal = 1)
public class AwsEC2SpecificFaultTaskHelper<T extends AwsEC2FaultSpec> extends AbstractCommandExecutionTaskHelper<T> {
private AwsEC2FaultHelper awsEC2FaultHelper;
@Autowired
public void setAwsEC2FaultHelper(AwsEC2FaultHelper awsEC2FaultHelper) {
this.awsEC2FaultHelper = awsEC2FaultHelper;
}
@Override
public Task<T> init(T faultSpec) {
return init(faultSpec, null);
}
public Task<T> init(T faultSpec, String injectionId) {
return init(new FaultTask<>(), faultSpec, injectionId);
}
@Override
protected void prepareEndpoint(Task<T> task, List<SupportScriptInfo> listFaultInjectionScripts)
throws MangleException {
//When needed we will implement this
}
@Override
public ICommandExecutor getExecutor(Task<T> task) throws MangleException {
return awsEC2FaultHelper.getExecutor(task.getTaskData());
}
@Override
public String getDescription(Task<T> task) {
return TaskDescriptionUtils.getDescription(task);
}
@Override
public void checkInjectionPreRequisites(Task<T> task) throws MangleException {
//No Injection prerequisites are determined as of now for this endpoint
}
@Override
public void checkRemediationPreRequisites(Task<T> task) throws MangleException {
//No Injection prerequisites are determined as of now for this endpoint
}
@Override
public void executeTask(Task<T> task) throws MangleException {
AwsEC2FaultSpec faultSpec = task.getTaskData();
if (task.getTaskType().equals(TaskType.INJECTION)) {
faultSpec.setInstanceIds(
awsEC2FaultHelper.getInstanceIds(faultSpec.getAwsTags(), faultSpec.isRandomInjection(), faultSpec));
task.getTaskData().setInjectionCommandInfoList(
awsEC2FaultHelper.getInjectionCommandInfoList(getExecutor(task), faultSpec));
task.getTaskData().setRemediationCommandInfoList(
awsEC2FaultHelper.getRemediationCommandInfoList(getExecutor(task), faultSpec));
}
super.executeTask(task);
task.updateTaskOutPut("Executed on EC2 instances: " + faultSpec.getInstanceIds());
}
@Override
protected void checkTaskSpecificPrerequisites(Task<T> task) throws MangleException {
//When needed we will implement this
}
}
|
C#
|
UTF-8
| 3,441 | 2.8125 | 3 |
[] |
no_license
|
using HT.Framework.Contracts;
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace HT.Framework.MVC
{
/// <summary>
/// ApiAiHttpClient
/// </summary>
public class ApiAiHttpClient : IHttpClient
{
/// <summary>
/// HttpClient
/// </summary>
private readonly HttpClient _httpClient;
/// <summary>
/// Constructor
/// </summary>
/// <param name="apiAiSettings"></param>
public ApiAiHttpClient(ApiAiSettings apiAiSettings)
{
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiAiSettings.AccessToken}");
_httpClient.Timeout = apiAiSettings.Timeout;
_httpClient.BaseAddress = new Uri($"{apiAiSettings.DefaultBaseUrl + apiAiSettings.DefaultApiVersion}");
}
/// <summary>
/// Get async
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
public async Task<T> GetAsync<T>(string query)
{
T result = default(T);
try
{
_httpClient.BaseAddress = new Uri(_httpClient.BaseAddress.ToString() + query);
HttpResponseMessage httpResponseMessage = await _httpClient.GetAsync(_httpClient.BaseAddress);
string content = await httpResponseMessage.Content.ReadAsStringAsync();
result = ApiAiJson<T>.Deserialize(content);
}
catch (Exception ex)
{
string meesage = ex.Message;
}
return result;
}
/// <summary>
/// Post async
/// </summary>
/// <param name="requestUri"></param>
/// <param name="content"></param>
/// <returns></returns>
public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content)
{
Task<HttpResponseMessage> httpResponseMessage = _httpClient.PostAsync(requestUri, content);
if (httpResponseMessage == null)
{
throw new Exception("Post async error - Http response message is null.");
}
return httpResponseMessage;
}
/// <summary>
/// Put async
/// </summary>
/// <param name="requestUri"></param>
/// <param name="content"></param>
/// <returns></returns>
public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content)
{
Task<HttpResponseMessage> httpResponseMessage = _httpClient.PutAsync(requestUri.AbsoluteUri, content);
if (httpResponseMessage == null)
{
throw new Exception("Put async error - Http response message is null.");
}
return httpResponseMessage;
}
/// <summary>
/// Delete async
/// </summary>
/// <param name="requestUri"></param>
/// <returns></returns>
public Task<HttpResponseMessage> DeleteAsync(Uri requestUri)
{
Task<HttpResponseMessage> httpResponseMessage = _httpClient.DeleteAsync(requestUri);
if (httpResponseMessage == null)
{
throw new Exception("Delete async error - Http response message is null.");
}
return httpResponseMessage;
}
}
}
|
Shell
|
UTF-8
| 1,035 | 3.421875 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env sh
set -e
cd /etc/shlink
initTables() {
rm -f data/cache/app_config.php
php vendor/doctrine/orm/bin/doctrine.php orm:schema-tool:create
php vendor/doctrine/migrations/bin/doctrine-migrations.php migrations:migrate
php vendor/doctrine/orm/bin/doctrine.php orm:generate-proxies
shlink visit:update-db
}
if [[ -n "$(head -1 /proc/1/cgroup | grep -oE "\/{1}(lxc|docker|ecs)")" ]]; then
# NOTE: We are in an ECS environment so we don't need to re-init as long as the tables already exist
doTablesExist=$(php -f ./CheckTablesExist.php)
if [[ "$doTablesExist" = false ]]; then
initTables
fi
# If proxies have not been generated yet, run first-time operations
elif [ -z "$(ls -A data/proxies)" ]; then
initTables
fi
# When restarting the container, swoole might think it is already in execution
# This forces the app to be started every second until the exit code is 0
until php vendor/zendframework/zend-expressive-swoole/bin/zend-expressive-swoole start; do sleep 1 ; done
|
Java
|
UTF-8
| 3,532 | 1.523438 | 2 |
[
"EPL-1.0",
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2013-2016 consulo.io
*
* 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 consulo.dotnet.mono.debugger.run;
import consulo.annotation.component.ExtensionImpl;
import consulo.application.AllIcons;
import consulo.dotnet.debugger.impl.DotNetDebugProcessBase;
import consulo.dotnet.debugger.impl.runner.remote.DotNetRemoteConfiguration;
import consulo.dotnet.module.extension.DotNetModuleExtension;
import consulo.dotnet.mono.debugger.MonoDebugProcess;
import consulo.dotnet.mono.debugger.MonoVirtualMachineListener;
import consulo.dotnet.mono.debugger.localize.MonoDebuggerLocalize;
import consulo.dotnet.util.DebugConnectionInfo;
import consulo.execution.configuration.ConfigurationFactory;
import consulo.execution.configuration.ConfigurationTypeBase;
import consulo.execution.configuration.RunConfiguration;
import consulo.execution.debug.XDebugSession;
import consulo.module.extension.ModuleExtensionHelper;
import consulo.process.ExecutionException;
import consulo.process.ProcessHandler;
import consulo.process.ProcessHandlerStopper;
import consulo.process.ProcessOutputTypes;
import consulo.project.Project;
import mono.debugger.VirtualMachine;
import javax.annotation.Nonnull;
/**
* @author VISTALL
* @since 27-Dec-16
*/
@ExtensionImpl
public class MonoRemoteConfiguration extends ConfigurationTypeBase
{
public MonoRemoteConfiguration()
{
super("MonoRemoteConfiguration", MonoDebuggerLocalize.monoRemoteConfigurationName(), AllIcons.RunConfigurations.Remote);
addFactory(new ConfigurationFactory(this)
{
@Override
public RunConfiguration createTemplateConfiguration(Project project)
{
return new DotNetRemoteConfiguration(project, this)
{
@Nonnull
@Override
public DotNetDebugProcessBase createDebuggerProcess(@Nonnull XDebugSession session, @Nonnull DebugConnectionInfo info) throws ExecutionException
{
MonoDebugProcess process = new MonoDebugProcess(session, this, info);
process.getDebugThread().addListener(new MonoVirtualMachineListener()
{
@Override
public void connectionSuccess(@Nonnull VirtualMachine machine)
{
ProcessHandler processHandler = process.getProcessHandler();
processHandler.notifyTextAvailable(String.format("Success attach to %s:%d", info.getHost(), info.getPort()), ProcessOutputTypes.STDOUT);
}
@Override
public void connectionStopped()
{
}
@Override
public void connectionFailed()
{
ProcessHandler processHandler = process.getProcessHandler();
processHandler.notifyTextAvailable(String.format("Failed attach to %s:%d", info.getHost(), info.getPort()), ProcessOutputTypes.STDERR);
ProcessHandlerStopper.stop(processHandler);
}
});
return process;
}
};
}
@Override
public boolean isApplicable(@Nonnull Project project)
{
return ModuleExtensionHelper.getInstance(project).hasModuleExtension(DotNetModuleExtension.class);
}
});
}
}
|
Python
|
UTF-8
| 4,232 | 2.734375 | 3 |
[
"Apache-2.0",
"MIT",
"BSD-2-Clause"
] |
permissive
|
# -*- coding: utf-8 -*-
'''
Configuration of the kernel using sysctl
========================================
Control the kernel sysctl system.
.. code-block:: yaml
vm.swappiness:
sysctl.present:
- value: 20
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import re
# Import salt libs
from salt.exceptions import CommandExecutionError
# Import 3rd part libs
from salt.ext import six
def __virtual__():
'''
This state is only available on Minions which support sysctl
'''
return 'sysctl.show' in __salt__
def present(name, value, config=None):
'''
Ensure that the named sysctl value is set in memory and persisted to the
named configuration file. The default sysctl configuration file is
/etc/sysctl.conf
name
The name of the sysctl value to edit
value
The sysctl value to apply
config
The location of the sysctl configuration file. If not specified, the
proper location will be detected based on platform.
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if config is None:
# Certain linux systems will ignore /etc/sysctl.conf, get the right
# default configuration file.
if 'sysctl.default_config' in __salt__:
config = __salt__['sysctl.default_config']()
else:
config = '/etc/sysctl.conf'
if __opts__['test']:
current = __salt__['sysctl.show']()
configured = __salt__['sysctl.show'](config_file=config)
if configured is None:
ret['result'] = None
ret['comment'] = (
'Sysctl option {0} might be changed, we failed to check '
'config file at {1}. The file is either unreadable, or '
'missing.'.format(name, config)
)
return ret
if name in current and name not in configured:
if re.sub(' +|\t+', ' ', current[name]) != \
re.sub(' +|\t+', ' ', six.text_type(value)):
ret['result'] = None
ret['comment'] = (
'Sysctl option {0} set to be changed to {1}'
.format(name, value)
)
return ret
else:
ret['result'] = None
ret['comment'] = (
'Sysctl value is currently set on the running system but '
'not in a config file. Sysctl option {0} set to be '
'changed to {1} in config file.'.format(name, value)
)
return ret
elif name in configured and name not in current:
ret['result'] = None
ret['comment'] = (
'Sysctl value {0} is present in configuration file but is not '
'present in the running config. The value {0} is set to be '
'changed to {1}'.format(name, value)
)
return ret
elif name in configured and name in current:
if six.text_type(value).split() == __salt__['sysctl.get'](name).split():
ret['result'] = True
ret['comment'] = (
'Sysctl value {0} = {1} is already set'
.format(name, value)
)
return ret
# otherwise, we don't have it set anywhere and need to set it
ret['result'] = None
ret['comment'] = (
'Sysctl option {0} would be changed to {1}'.format(name, value)
)
return ret
try:
update = __salt__['sysctl.persist'](name, value, config)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = (
'Failed to set {0} to {1}: {2}'.format(name, value, exc)
)
return ret
if update == 'Updated':
ret['changes'] = {name: value}
ret['comment'] = 'Updated sysctl value {0} = {1}'.format(name, value)
elif update == 'Already set':
ret['comment'] = (
'Sysctl value {0} = {1} is already set'
.format(name, value)
)
return ret
|
Java
|
UTF-8
| 325 | 2.71875 | 3 |
[] |
no_license
|
package week3.day2.classroom;
public class College extends University{
public static void main(String[] args) {
College myColl = new College();
myColl.pg();
myColl.getug();
}
@Override
public void getug() {
System.out.println("print unimplemented method of ug from the college");
}
}
|
Markdown
|
UTF-8
| 1,221 | 2.875 | 3 |
[
"CC-BY-4.0"
] |
permissive
|
---
id: onRowMoved
title: On Row Moved
---
| Code | Peut être appelé par | Définition |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------ |
| 34 | [List Box de type tableau](FormObjects/listbox_overview.md#array-list-boxes) - [Colonne de List Box](FormObjects/listbox_overview.md#list-box-columns) | Une ligne de list box est déplacée par l'utilisateur par glisser-déposer |
## Description
Cet événement est généré lorsqu'une ligne de list box (de [type tableau uniquement](FormObjects/listbox_overview.md#array-list-boxes)) est déplacée par l'utilisateur à l'aide du glisser-déposer ([si autorisé](FormObjects/properties_Action.md#movable-rows)). Il n'est pas généré si la ligne est glissée puis déposée à son emplacement initial.
La commande `LISTBOX MOVED ROW NUMBER` retourne la nouvelle position de la ligne.
|
Markdown
|
UTF-8
| 934 | 2.90625 | 3 |
[] |
no_license
|
#Codebook for data.csv
**File-Type:** CSV, 15 rows (+ 1 header), 13 column, N=1046
`data.csv` *is a processed form of the raw dataset: I aggregated passengers to age categories and only kept variables for victims and all passengers (seperated by men and women).*
## Variables
- **age_cat**: age categorie (ordinal) ["0 to 5", "6 to 10", ..., "70+]
- **m_died_pclass1**: number of 1st class male passengers who died (metric)
- **m_total_pclass1**: number of all 1st class male passengers (survived and died)
- **f_died_pclass1**: number of 1st class female passengers who died (metric)
- **f_total_pclass1**: number of all 1st class female passengers (survived and died)
- *... (same for 2nd and 3rd class)*
## Resources
[1] [Link to the raw dataset](http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic3.csv)
[2] [Codebook of the raw dataset](http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic3info.txt)
|
JavaScript
|
UTF-8
| 1,399 | 3.046875 | 3 |
[
"MIT"
] |
permissive
|
/*jshint esversion: 6 */
class Ball {
constructor(x, y, vel) {
this.pos = createVector(x, y);
if (vel)
this.vel = vel;
else
this.vel = createVector(random(-2, 2), random(-2, 2));
this.size = 8;
this.alive = true;
}
update() {
this.pos.add(this.vel);
if (this.intersect(pad)) {
this.hitPad();
}
if (this.pos.x - this.size / 2 <= 0 || this.pos.x + this.size / 2 >= width) {
this.hitSide();
}
if (this.pos.y - this.size / 2 <= 0) {
this.hitTop();
}
if (this.pos.y + this.size / 2 >= height) {
this.alive = false;
}
}
hitSide() {
this.vel.x *= -1;
}
hitTop() {
this.vel.y *= -1;
}
hitPad() {
this.hitTop();
this.vel.x = map(pad.pos.x - this.pos.x, -pad.width / 2, pad.width / 2, 3, -3);
}
show() {
fill(255);
noStroke();
ellipse(this.pos.x, this.pos.y, this.size, this.size);
}
intersect(obj2) {
return (this.pos.x - this.size / 2 <= obj2.pos.x + obj2.width / 2 &&
this.pos.x + this.size / 2 >= obj2.pos.x - obj2.width / 2 &&
this.pos.y + this.size / 2 >= obj2.pos.y - obj2.height / 2 &&
this.pos.y - this.size / 2 <= obj2.pos.y + obj2.height / 2);
}
}
|
JavaScript
|
UTF-8
| 1,323 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
import createReducer from '../../utils/createReducer'
import ActionTypes from '../../constants/actionTypes'
const initialState = {
placesData: {},
placesResults: {},
searchTexts: {}
}
const handlers = {
// Pattern:
// [ActionTypes.ACTION_NAME]: actionFunction
[ActionTypes.PLACES_UPDATE_DATA]: updateData,
[ActionTypes.PLACES_UPDATE_TEXT]: updateText,
[ActionTypes.PLACES_UPDATE_RESULT]: updateResult,
[ActionTypes.PLACES_CLEAR_ALL]: clearAll
}
export default createReducer(initialState, handlers)
function clearAll(state) {
return {
...state,
placesData: {},
placesResults: {},
searchTexts: {}
}
}
function updateResult(state, { payload }) {
const { placesResult, index } = payload
const { placesResults } = state
const obj = { ...placesResults }
obj[index] = placesResult
return {
...state,
placesResults: obj
}
}
function updateText(state, { payload }) {
const { searchText, index } = payload
const { searchTexts } = state
const obj = { ...searchTexts }
obj[index] = searchText
return {
...state,
searchTexts: obj
}
}
function updateData(state, { payload }) {
const { places, index } = payload
const { placesData } = state
const obj = { ...placesData }
obj[index] = places
return {
...state,
placesData: obj
}
}
|
C
|
UTF-8
| 2,164 | 3.71875 | 4 |
[
"MIT"
] |
permissive
|
// Author: Trevor Martin
// Date of Completion: 18 March 2019
// Language: C
// Class: CSCI241 | Systems Programming | Oberlin College
// Homework#: 4, tobinary.c
//===================================================================================================
// DESCRIPTION
//===================================================================================================
// Outputs a signed integer value in binary format with a leading 0b
//===================================================================================================
// this is a file in our directory so it gets " " and not < >, getnum.c calls tobinary.c so we must
// include it here to be visible
#include "getnum.c"
int main()
{
// where did we get user_specified_input! I thought that was exclusive to getnum.c! Well no,
// user_specified_input is visible to tobinary.c because we did #include "getnum.c". Also,
// we will be able to use our functions in getnum.c such as getnum(), which converts the
// integer to a long (I have yet to write this) but for now all that you need to know is
// its functionality. There will be errors in formats inputted, so the variable
// number_of_returned_errors will hold that in
while (user_specified_input != EOF)
{
// store the user specified inputted converted to a long in the variable number
long number = getnum();
// if there are no errors
if (!(number_of_returned_errors > 0))
{
// we have a variable that determines the negative_status. If there is a negative status,
// the value of negative will be 1, which is greater than 0 and this beckons us to print
// a "-" before we print our binary number
if (negative_sign > 0)
{
// convert the number to binary format preceeded by a negative sign
printf("%c",'-');
convert_to_binary(number);
}
// if there was no negative flag
else
{
// convert the number to binary format without a negative sign
convert_to_binary(number);
}
}
else
{
// tell the user that they've enter a poorly formatted input value
printf("\n%s\n","ERROR");
}
}
return 0;
}
|
Python
|
UTF-8
| 577 | 3.265625 | 3 |
[] |
no_license
|
class ABBYYException(Exception):
def __init__(self, code, message, *args, **kwargs):
"""
Initialize exception
:param code: return code
:type code: int
:param message: message
:type message: str
"""
self.code = code
self.message = message
super(ABBYYException, self).__init__(*args, **kwargs)
def __str__(self):
return "ABBYY SmartClassifier exception : {0}.\nReturn code {1}".format(
self.message, self.code
)
def __repr__(self):
return str(self)
|
Java
|
UTF-8
| 3,280 | 2.265625 | 2 |
[] |
no_license
|
package org.tarena.note.service;
import javax.annotation.Resource;
import org.springframework.dao.support.DaoSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.tarena.note.dao.UserDao;
import org.tarena.note.entity.User;
import org.tarena.note.util.NoteResult;
import org.tarena.note.util.NoteUtil;
@Service("userServiceImpl")
@Transactional
public class UserServiceImpl implements UserService {
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
@Resource(name="userDao")
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public NoteResult checkLogin(String username, String password) {
NoteResult result = new NoteResult();
//检测用户名
User user = userDao.findByName(username);
if(user == null){
result.setStatus(1);
result.setMsg("用户不存在");
result.setData(null);
return result;
}
//检测密码
//将用户收入的密码加密
String md5_password = NoteUtil.md5(password);
//将加密结果和数据表中的密文进行对比
if(!user.getCn_user_password().equals(md5_password)){
result.setStatus(2);
result.setMsg("密码错误");
result.setData(null);
return result;
}
result.setStatus(0);
result.setMsg("用户名和密码正确");
result.setData(user.getCn_user_id());
return result;
}
public NoteResult registUser(String username, String password,
String nickname) {
NoteResult result = new NoteResult();
//检测用户名是否注册
User dbUser = userDao.findByName(username);
if(dbUser != null){
result.setStatus(1);
result.setMsg("用户名已存在");
result.setData(null);
return result;
}
//注册操作
User user = new User();
String id = NoteUtil.createId();
user.setCn_user_id(id);//设置ID
user.setCn_user_name(username);//设置用户名
String md5_pwd = NoteUtil.md5(password);
user.setCn_user_password(md5_pwd);//设置密码
user.setCn_user_token(null);//设置令牌
user.setCn_user_desc(nickname);//设置昵称
userDao.save(user);//保存到cn_user表
result.setStatus(0);
result.setMsg("注册成功");
result.setData(null);
// //模拟一个异常
// String str = null;
// str.length();
return result;
}
public NoteResult changePwd(String lastPassword, String newPassword, String userId) {
String password = userDao.findPwd(userId);
NoteResult result = new NoteResult();
//将用户收入的密码加密
String md5_lastPassword = NoteUtil.md5(lastPassword);
String md5_newPassword = NoteUtil.md5(newPassword);
if(!md5_lastPassword.equals(password)){
result.setStatus(2);
result.setMsg("原密码错误");
result.setData(null);
return result;
}
userDao.updatePwd(md5_newPassword);
result.setStatus(0);
result.setMsg("修改密码成功");
result.setData(null);
return result;
}
@Override
public NoteResult findName(String userId) {
User user = userDao.findAll(userId);
String userName = user.getCn_user_name();
NoteResult result = new NoteResult();
result.setStatus(0);
result.setMsg("获取姓名成功");
result.setData(userName);
return result;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.